@astrasyncai/verification-gateway 3.6.0 → 3.7.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.
Files changed (42) hide show
  1. package/dist/adapters/express.js +1 -1
  2. package/dist/adapters/express.js.map +1 -1
  3. package/dist/adapters/express.mjs +1 -1
  4. package/dist/adapters/express.mjs.map +1 -1
  5. package/dist/adapters/mcp.js +1 -1
  6. package/dist/adapters/mcp.js.map +1 -1
  7. package/dist/adapters/mcp.mjs +1 -1
  8. package/dist/adapters/mcp.mjs.map +1 -1
  9. package/dist/adapters/nextjs.js +1 -1
  10. package/dist/adapters/nextjs.js.map +1 -1
  11. package/dist/adapters/nextjs.mjs +1 -1
  12. package/dist/adapters/nextjs.mjs.map +1 -1
  13. package/dist/adapters/sdk.js +1 -1
  14. package/dist/adapters/sdk.js.map +1 -1
  15. package/dist/adapters/sdk.mjs +1 -1
  16. package/dist/adapters/sdk.mjs.map +1 -1
  17. package/dist/bin/astrasync-claude-hook.js +4791 -0
  18. package/dist/bin/astrasync-guard.js +5990 -0
  19. package/dist/bin/astrasync.js +6840 -330
  20. package/dist/browser/background.js +1 -1
  21. package/dist/browser/background.js.map +1 -1
  22. package/dist/browser/background.mjs +1 -1
  23. package/dist/browser/background.mjs.map +1 -1
  24. package/dist/claude-code/claude-code-adapter.d.mts +96 -0
  25. package/dist/claude-code/claude-code-adapter.d.ts +96 -0
  26. package/dist/claude-code/claude-code-adapter.js +277 -0
  27. package/dist/claude-code/claude-code-adapter.js.map +1 -0
  28. package/dist/claude-code/claude-code-adapter.mjs +249 -0
  29. package/dist/claude-code/claude-code-adapter.mjs.map +1 -0
  30. package/dist/cursor/extension.js +1 -1
  31. package/dist/cursor/extension.js.map +1 -1
  32. package/dist/cursor/extension.mjs +1 -1
  33. package/dist/cursor/extension.mjs.map +1 -1
  34. package/dist/gateway/gateway.js +1 -1
  35. package/dist/gateway/gateway.js.map +1 -1
  36. package/dist/gateway/gateway.mjs +1 -1
  37. package/dist/gateway/gateway.mjs.map +1 -1
  38. package/dist/index.js +1 -1
  39. package/dist/index.js.map +1 -1
  40. package/dist/index.mjs +1 -1
  41. package/dist/index.mjs.map +1 -1
  42. package/package.json +9 -2
@@ -0,0 +1,4791 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __export = (target, all) => {
8
+ for (var name in all)
9
+ __defProp(target, name, { get: all[name], enumerable: true });
10
+ };
11
+ var __copyProps = (to, from, except, desc) => {
12
+ if (from && typeof from === "object" || typeof from === "function") {
13
+ for (let key of __getOwnPropNames(from))
14
+ if (!__hasOwnProp.call(to, key) && key !== except)
15
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
16
+ }
17
+ return to;
18
+ };
19
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
20
+
21
+ // src/claude-code/hook.ts
22
+ var hook_exports = {};
23
+ __export(hook_exports, {
24
+ processHookPayload: () => processHookPayload,
25
+ resolveGuardConfig: () => resolveGuardConfig
26
+ });
27
+ module.exports = __toCommonJS(hook_exports);
28
+ var import_fs4 = require("fs");
29
+ var import_os = require("os");
30
+ var import_path3 = require("path");
31
+
32
+ // src/gateway/types.ts
33
+ var HIGH_RISK_COMMANDS = [
34
+ "rm",
35
+ "rmdir",
36
+ "dd",
37
+ "mkfs",
38
+ "chmod",
39
+ "chown",
40
+ "sudo",
41
+ "su",
42
+ "curl",
43
+ "wget",
44
+ "nc",
45
+ "netcat",
46
+ "ssh",
47
+ "scp",
48
+ "rsync",
49
+ "git push",
50
+ "npm publish",
51
+ "docker",
52
+ "kubectl"
53
+ ];
54
+ var SENSITIVE_PATHS = [
55
+ ".ssh",
56
+ ".aws",
57
+ ".gnupg",
58
+ ".env",
59
+ "credentials",
60
+ "secrets",
61
+ "password",
62
+ ".git/config",
63
+ "/etc",
64
+ "/var",
65
+ "/root",
66
+ "id_rsa",
67
+ ".npmrc",
68
+ ".pypirc"
69
+ ];
70
+
71
+ // src/local-evaluator/evaluator.ts
72
+ var LocalEvaluator = class {
73
+ constructor(policy) {
74
+ this.requestCounts = /* @__PURE__ */ new Map();
75
+ this.policy = policy;
76
+ }
77
+ /**
78
+ * Update the policy (e.g. after hot-reload or sync).
79
+ */
80
+ updatePolicy(policy) {
81
+ this.policy = policy;
82
+ }
83
+ /**
84
+ * Evaluate an action context against the loaded policy.
85
+ */
86
+ evaluate(context) {
87
+ const purposeRule = this.policy.purposes.find((p) => p.id === context.purpose);
88
+ if (!purposeRule) {
89
+ return { recommendation: "DENY", reason: "Purpose not in policy" };
90
+ }
91
+ if (!purposeRule.allowed) {
92
+ return { recommendation: "DENY", reason: "Purpose explicitly blocked" };
93
+ }
94
+ if (purposeRule.targets && !this.matchesAnyPattern(context.target, purposeRule.targets)) {
95
+ return { recommendation: "DENY", reason: "Target not in allowed list" };
96
+ }
97
+ if (purposeRule.blockedPatterns && this.matchesAnyPattern(context.target, purposeRule.blockedPatterns)) {
98
+ return { recommendation: "DENY", reason: "Target matches blocked pattern" };
99
+ }
100
+ const scopeBlock = this.checkScopeBlock(context);
101
+ if (scopeBlock) {
102
+ return { recommendation: "DENY", reason: scopeBlock };
103
+ }
104
+ const limitViolation = this.checkLimits(context);
105
+ if (limitViolation) {
106
+ return { recommendation: "DENY", reason: limitViolation };
107
+ }
108
+ if (context.purpose === "sub_agent.spawn" && this.policy.selfInstantiation) {
109
+ if (!this.policy.selfInstantiation.allowed) {
110
+ return { recommendation: "DENY", reason: "Sub-agent spawning is not allowed" };
111
+ }
112
+ const depth = context.metadata?.subAgentDepth || 0;
113
+ if (this.policy.selfInstantiation.maxDepth !== void 0 && depth >= this.policy.selfInstantiation.maxDepth) {
114
+ return {
115
+ recommendation: "DENY",
116
+ reason: `Sub-agent depth ${depth} exceeds max depth ${this.policy.selfInstantiation.maxDepth}`
117
+ };
118
+ }
119
+ }
120
+ if (purposeRule.requiresApproval) {
121
+ return { recommendation: "MANUAL_REVIEW", reason: "Purpose requires approval" };
122
+ }
123
+ const riskDecision = this.checkRiskThresholds(context);
124
+ if (riskDecision) {
125
+ return riskDecision;
126
+ }
127
+ return {
128
+ recommendation: "ALLOW",
129
+ reason: "All PDLSS checks passed",
130
+ evaluatedDimensions: {
131
+ purpose: true,
132
+ scope: !!this.policy.scope,
133
+ limits: !!this.policy.limits,
134
+ riskThresholds: !!this.policy.riskThresholds
135
+ }
136
+ };
137
+ }
138
+ checkScopeBlock(context) {
139
+ const scope = this.policy.scope;
140
+ if (!scope) return null;
141
+ if (scope.blockedDomains) {
142
+ const targetDomain = this.extractDomain(context.target);
143
+ if (this.matchesAnyPattern(targetDomain, scope.blockedDomains)) {
144
+ return `Target blocked by scope: ${context.target}`;
145
+ }
146
+ if (context.networkAccess) {
147
+ for (const domain of context.networkAccess) {
148
+ if (this.matchesAnyPattern(this.extractDomain(domain), scope.blockedDomains)) {
149
+ return `Domain blocked by scope: ${domain}`;
150
+ }
151
+ }
152
+ }
153
+ }
154
+ if (scope.blockedResources && this.matchesAnyPattern(context.target, scope.blockedResources)) {
155
+ return `Resource blocked by scope: ${context.target}`;
156
+ }
157
+ if (scope.allowedDomains && context.networkAccess) {
158
+ for (const domain of context.networkAccess) {
159
+ if (!this.matchesAnyPattern(this.extractDomain(domain), scope.allowedDomains)) {
160
+ return `Domain not in allowed list: ${domain}`;
161
+ }
162
+ }
163
+ }
164
+ return null;
165
+ }
166
+ checkLimits(context) {
167
+ const limits = this.policy.limits;
168
+ if (!limits) return null;
169
+ if (limits.maxTransactionAmount !== void 0 && context.transactionValue !== void 0) {
170
+ if (context.transactionValue > limits.maxTransactionAmount) {
171
+ return `Transaction value ${context.transactionValue} exceeds limit ${limits.maxTransactionAmount}`;
172
+ }
173
+ }
174
+ if (limits.maxRequestsPerHour !== void 0) {
175
+ const key = context.purpose;
176
+ const now = Date.now();
177
+ const entry = this.requestCounts.get(key);
178
+ const hourMs = 36e5;
179
+ if (!entry || now - entry.windowStart > hourMs) {
180
+ this.requestCounts.set(key, { count: 1, windowStart: now });
181
+ } else {
182
+ entry.count++;
183
+ if (entry.count > limits.maxRequestsPerHour) {
184
+ return `Rate limit exceeded: ${entry.count}/${limits.maxRequestsPerHour} requests per hour`;
185
+ }
186
+ }
187
+ }
188
+ return null;
189
+ }
190
+ checkRiskThresholds(context) {
191
+ if (!this.policy.riskThresholds) return null;
192
+ const riskScore = this.calculateRiskScore(context);
193
+ const thresholds = this.policy.riskThresholds;
194
+ if (riskScore >= thresholds.autoBlock.min) {
195
+ return { recommendation: "DENY", reason: `Risk score ${riskScore} exceeds block threshold` };
196
+ }
197
+ if (riskScore >= thresholds.requireApproval.min) {
198
+ return {
199
+ recommendation: "MANUAL_REVIEW",
200
+ reason: `Risk score ${riskScore} requires approval`
201
+ };
202
+ }
203
+ return null;
204
+ }
205
+ calculateRiskScore(context) {
206
+ let score = 0;
207
+ if (context.riskFactors?.length) {
208
+ const severityScores = {
209
+ low: 10,
210
+ medium: 40,
211
+ high: 70,
212
+ critical: 90
213
+ };
214
+ for (const factor of context.riskFactors) {
215
+ const factorScore = severityScores[factor.severity] || 0;
216
+ if (factorScore > score) score = factorScore;
217
+ }
218
+ return score;
219
+ }
220
+ if (context.purpose === "shell.exec" && context.target) {
221
+ const targetLower = context.target.toLowerCase();
222
+ for (const cmd of HIGH_RISK_COMMANDS) {
223
+ if (targetLower.startsWith(cmd) || targetLower.includes(` ${cmd} `) || targetLower.includes(` ${cmd}`)) {
224
+ score = Math.max(score, 80);
225
+ break;
226
+ }
227
+ }
228
+ }
229
+ if ((context.purpose === "file.read" || context.purpose === "file.write" || context.purpose === "file.delete") && context.target) {
230
+ const targetLower = context.target.toLowerCase();
231
+ for (const sensitivePath of SENSITIVE_PATHS) {
232
+ if (targetLower.includes(sensitivePath.toLowerCase())) {
233
+ score = Math.max(score, 50);
234
+ break;
235
+ }
236
+ }
237
+ }
238
+ return score;
239
+ }
240
+ /**
241
+ * Extract domain from a URL-like string (strips protocol and path).
242
+ */
243
+ extractDomain(value) {
244
+ let domain = value;
245
+ const protoIndex = domain.indexOf("://");
246
+ if (protoIndex !== -1) domain = domain.slice(protoIndex + 3);
247
+ const slashIndex = domain.indexOf("/");
248
+ if (slashIndex !== -1) domain = domain.slice(0, slashIndex);
249
+ const colonIndex = domain.indexOf(":");
250
+ if (colonIndex !== -1) domain = domain.slice(0, colonIndex);
251
+ return domain;
252
+ }
253
+ /**
254
+ * Check if a value matches any of the given glob patterns.
255
+ */
256
+ matchesAnyPattern(value, patterns) {
257
+ return patterns.some((pattern) => this.matchGlob(value, pattern));
258
+ }
259
+ /**
260
+ * Simple glob pattern matching.
261
+ * Supports * (matches any characters including / and spaces) and ? (single char).
262
+ * Uses the same approach as the backend's matchGlobPattern.
263
+ */
264
+ matchGlob(value, pattern) {
265
+ if (pattern === value) return true;
266
+ const starCount = (pattern.match(/\*/g) ?? []).length;
267
+ if (starCount > 8) {
268
+ return false;
269
+ }
270
+ const regexStr = pattern.replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*").replace(/\?/g, ".");
271
+ try {
272
+ return new RegExp(`^${regexStr}$`, "i").test(value);
273
+ } catch {
274
+ return false;
275
+ }
276
+ }
277
+ };
278
+
279
+ // ../../node_modules/js-yaml/dist/js-yaml.mjs
280
+ function getDefaultExportFromCjs(x) {
281
+ return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, "default") ? x["default"] : x;
282
+ }
283
+ var jsYaml = {};
284
+ var loader = {};
285
+ var common = {};
286
+ var hasRequiredCommon;
287
+ function requireCommon() {
288
+ if (hasRequiredCommon) return common;
289
+ hasRequiredCommon = 1;
290
+ function isNothing(subject) {
291
+ return typeof subject === "undefined" || subject === null;
292
+ }
293
+ function isObject(subject) {
294
+ return typeof subject === "object" && subject !== null;
295
+ }
296
+ function toArray(sequence) {
297
+ if (Array.isArray(sequence)) return sequence;
298
+ else if (isNothing(sequence)) return [];
299
+ return [sequence];
300
+ }
301
+ function extend(target, source) {
302
+ if (source) {
303
+ const sourceKeys = Object.keys(source);
304
+ for (let index = 0, length = sourceKeys.length; index < length; index += 1) {
305
+ const key = sourceKeys[index];
306
+ target[key] = source[key];
307
+ }
308
+ }
309
+ return target;
310
+ }
311
+ function repeat(string, count) {
312
+ let result = "";
313
+ for (let cycle = 0; cycle < count; cycle += 1) {
314
+ result += string;
315
+ }
316
+ return result;
317
+ }
318
+ function isNegativeZero(number) {
319
+ return number === 0 && Number.NEGATIVE_INFINITY === 1 / number;
320
+ }
321
+ common.isNothing = isNothing;
322
+ common.isObject = isObject;
323
+ common.toArray = toArray;
324
+ common.repeat = repeat;
325
+ common.isNegativeZero = isNegativeZero;
326
+ common.extend = extend;
327
+ return common;
328
+ }
329
+ var exception;
330
+ var hasRequiredException;
331
+ function requireException() {
332
+ if (hasRequiredException) return exception;
333
+ hasRequiredException = 1;
334
+ function formatError(exception2, compact) {
335
+ let where = "";
336
+ const message = exception2.reason || "(unknown reason)";
337
+ if (!exception2.mark) return message;
338
+ if (exception2.mark.name) {
339
+ where += 'in "' + exception2.mark.name + '" ';
340
+ }
341
+ where += "(" + (exception2.mark.line + 1) + ":" + (exception2.mark.column + 1) + ")";
342
+ if (!compact && exception2.mark.snippet) {
343
+ where += "\n\n" + exception2.mark.snippet;
344
+ }
345
+ return message + " " + where;
346
+ }
347
+ function YAMLException2(reason, mark) {
348
+ Error.call(this);
349
+ this.name = "YAMLException";
350
+ this.reason = reason;
351
+ this.mark = mark;
352
+ this.message = formatError(this, false);
353
+ if (Error.captureStackTrace) {
354
+ Error.captureStackTrace(this, this.constructor);
355
+ } else {
356
+ this.stack = new Error().stack || "";
357
+ }
358
+ }
359
+ YAMLException2.prototype = Object.create(Error.prototype);
360
+ YAMLException2.prototype.constructor = YAMLException2;
361
+ YAMLException2.prototype.toString = function toString(compact) {
362
+ return this.name + ": " + formatError(this, compact);
363
+ };
364
+ exception = YAMLException2;
365
+ return exception;
366
+ }
367
+ var snippet;
368
+ var hasRequiredSnippet;
369
+ function requireSnippet() {
370
+ if (hasRequiredSnippet) return snippet;
371
+ hasRequiredSnippet = 1;
372
+ const common2 = requireCommon();
373
+ function getLine(buffer, lineStart, lineEnd, position, maxLineLength) {
374
+ let head = "";
375
+ let tail = "";
376
+ const maxHalfLength = Math.floor(maxLineLength / 2) - 1;
377
+ if (position - lineStart > maxHalfLength) {
378
+ head = " ... ";
379
+ lineStart = position - maxHalfLength + head.length;
380
+ }
381
+ if (lineEnd - position > maxHalfLength) {
382
+ tail = " ...";
383
+ lineEnd = position + maxHalfLength - tail.length;
384
+ }
385
+ return {
386
+ str: head + buffer.slice(lineStart, lineEnd).replace(/\t/g, "\u2192") + tail,
387
+ pos: position - lineStart + head.length
388
+ // relative position
389
+ };
390
+ }
391
+ function padStart(string, max) {
392
+ return common2.repeat(" ", max - string.length) + string;
393
+ }
394
+ function makeSnippet(mark, options) {
395
+ options = Object.create(options || null);
396
+ if (!mark.buffer) return null;
397
+ if (!options.maxLength) options.maxLength = 79;
398
+ if (typeof options.indent !== "number") options.indent = 1;
399
+ if (typeof options.linesBefore !== "number") options.linesBefore = 3;
400
+ if (typeof options.linesAfter !== "number") options.linesAfter = 2;
401
+ const re = /\r?\n|\r|\0/g;
402
+ const lineStarts = [0];
403
+ const lineEnds = [];
404
+ let match;
405
+ let foundLineNo = -1;
406
+ while (match = re.exec(mark.buffer)) {
407
+ lineEnds.push(match.index);
408
+ lineStarts.push(match.index + match[0].length);
409
+ if (mark.position <= match.index && foundLineNo < 0) {
410
+ foundLineNo = lineStarts.length - 2;
411
+ }
412
+ }
413
+ if (foundLineNo < 0) foundLineNo = lineStarts.length - 1;
414
+ let result = "";
415
+ const lineNoLength = Math.min(mark.line + options.linesAfter, lineEnds.length).toString().length;
416
+ const maxLineLength = options.maxLength - (options.indent + lineNoLength + 3);
417
+ for (let i = 1; i <= options.linesBefore; i++) {
418
+ if (foundLineNo - i < 0) break;
419
+ const line2 = getLine(
420
+ mark.buffer,
421
+ lineStarts[foundLineNo - i],
422
+ lineEnds[foundLineNo - i],
423
+ mark.position - (lineStarts[foundLineNo] - lineStarts[foundLineNo - i]),
424
+ maxLineLength
425
+ );
426
+ result = common2.repeat(" ", options.indent) + padStart((mark.line - i + 1).toString(), lineNoLength) + " | " + line2.str + "\n" + result;
427
+ }
428
+ const line = getLine(mark.buffer, lineStarts[foundLineNo], lineEnds[foundLineNo], mark.position, maxLineLength);
429
+ result += common2.repeat(" ", options.indent) + padStart((mark.line + 1).toString(), lineNoLength) + " | " + line.str + "\n";
430
+ result += common2.repeat("-", options.indent + lineNoLength + 3 + line.pos) + "^\n";
431
+ for (let i = 1; i <= options.linesAfter; i++) {
432
+ if (foundLineNo + i >= lineEnds.length) break;
433
+ const line2 = getLine(
434
+ mark.buffer,
435
+ lineStarts[foundLineNo + i],
436
+ lineEnds[foundLineNo + i],
437
+ mark.position - (lineStarts[foundLineNo] - lineStarts[foundLineNo + i]),
438
+ maxLineLength
439
+ );
440
+ result += common2.repeat(" ", options.indent) + padStart((mark.line + i + 1).toString(), lineNoLength) + " | " + line2.str + "\n";
441
+ }
442
+ return result.replace(/\n$/, "");
443
+ }
444
+ snippet = makeSnippet;
445
+ return snippet;
446
+ }
447
+ var type;
448
+ var hasRequiredType;
449
+ function requireType() {
450
+ if (hasRequiredType) return type;
451
+ hasRequiredType = 1;
452
+ const YAMLException2 = requireException();
453
+ const TYPE_CONSTRUCTOR_OPTIONS = [
454
+ "kind",
455
+ "multi",
456
+ "resolve",
457
+ "construct",
458
+ "instanceOf",
459
+ "predicate",
460
+ "represent",
461
+ "representName",
462
+ "defaultStyle",
463
+ "styleAliases"
464
+ ];
465
+ const YAML_NODE_KINDS = [
466
+ "scalar",
467
+ "sequence",
468
+ "mapping"
469
+ ];
470
+ function compileStyleAliases(map2) {
471
+ const result = {};
472
+ if (map2 !== null) {
473
+ Object.keys(map2).forEach(function(style) {
474
+ map2[style].forEach(function(alias) {
475
+ result[String(alias)] = style;
476
+ });
477
+ });
478
+ }
479
+ return result;
480
+ }
481
+ function Type2(tag, options) {
482
+ options = options || {};
483
+ Object.keys(options).forEach(function(name) {
484
+ if (TYPE_CONSTRUCTOR_OPTIONS.indexOf(name) === -1) {
485
+ throw new YAMLException2('Unknown option "' + name + '" is met in definition of "' + tag + '" YAML type.');
486
+ }
487
+ });
488
+ this.options = options;
489
+ this.tag = tag;
490
+ this.kind = options["kind"] || null;
491
+ this.resolve = options["resolve"] || function() {
492
+ return true;
493
+ };
494
+ this.construct = options["construct"] || function(data) {
495
+ return data;
496
+ };
497
+ this.instanceOf = options["instanceOf"] || null;
498
+ this.predicate = options["predicate"] || null;
499
+ this.represent = options["represent"] || null;
500
+ this.representName = options["representName"] || null;
501
+ this.defaultStyle = options["defaultStyle"] || null;
502
+ this.multi = options["multi"] || false;
503
+ this.styleAliases = compileStyleAliases(options["styleAliases"] || null);
504
+ if (YAML_NODE_KINDS.indexOf(this.kind) === -1) {
505
+ throw new YAMLException2('Unknown kind "' + this.kind + '" is specified for "' + tag + '" YAML type.');
506
+ }
507
+ }
508
+ type = Type2;
509
+ return type;
510
+ }
511
+ var schema;
512
+ var hasRequiredSchema;
513
+ function requireSchema() {
514
+ if (hasRequiredSchema) return schema;
515
+ hasRequiredSchema = 1;
516
+ const YAMLException2 = requireException();
517
+ const Type2 = requireType();
518
+ function compileList(schema2, name) {
519
+ const result = [];
520
+ schema2[name].forEach(function(currentType) {
521
+ let newIndex = result.length;
522
+ result.forEach(function(previousType, previousIndex) {
523
+ if (previousType.tag === currentType.tag && previousType.kind === currentType.kind && previousType.multi === currentType.multi) {
524
+ newIndex = previousIndex;
525
+ }
526
+ });
527
+ result[newIndex] = currentType;
528
+ });
529
+ return result;
530
+ }
531
+ function compileMap() {
532
+ const result = {
533
+ scalar: {},
534
+ sequence: {},
535
+ mapping: {},
536
+ fallback: {},
537
+ multi: {
538
+ scalar: [],
539
+ sequence: [],
540
+ mapping: [],
541
+ fallback: []
542
+ }
543
+ };
544
+ function collectType(type2) {
545
+ if (type2.multi) {
546
+ result.multi[type2.kind].push(type2);
547
+ result.multi["fallback"].push(type2);
548
+ } else {
549
+ result[type2.kind][type2.tag] = result["fallback"][type2.tag] = type2;
550
+ }
551
+ }
552
+ for (let index = 0, length = arguments.length; index < length; index += 1) {
553
+ arguments[index].forEach(collectType);
554
+ }
555
+ return result;
556
+ }
557
+ function Schema2(definition) {
558
+ return this.extend(definition);
559
+ }
560
+ Schema2.prototype.extend = function extend(definition) {
561
+ let implicit = [];
562
+ let explicit = [];
563
+ if (definition instanceof Type2) {
564
+ explicit.push(definition);
565
+ } else if (Array.isArray(definition)) {
566
+ explicit = explicit.concat(definition);
567
+ } else if (definition && (Array.isArray(definition.implicit) || Array.isArray(definition.explicit))) {
568
+ if (definition.implicit) implicit = implicit.concat(definition.implicit);
569
+ if (definition.explicit) explicit = explicit.concat(definition.explicit);
570
+ } else {
571
+ throw new YAMLException2("Schema.extend argument should be a Type, [ Type ], or a schema definition ({ implicit: [...], explicit: [...] })");
572
+ }
573
+ implicit.forEach(function(type2) {
574
+ if (!(type2 instanceof Type2)) {
575
+ throw new YAMLException2("Specified list of YAML types (or a single Type object) contains a non-Type object.");
576
+ }
577
+ if (type2.loadKind && type2.loadKind !== "scalar") {
578
+ throw new YAMLException2("There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported.");
579
+ }
580
+ if (type2.multi) {
581
+ throw new YAMLException2("There is a multi type in the implicit list of a schema. Multi tags can only be listed as explicit.");
582
+ }
583
+ });
584
+ explicit.forEach(function(type2) {
585
+ if (!(type2 instanceof Type2)) {
586
+ throw new YAMLException2("Specified list of YAML types (or a single Type object) contains a non-Type object.");
587
+ }
588
+ });
589
+ const result = Object.create(Schema2.prototype);
590
+ result.implicit = (this.implicit || []).concat(implicit);
591
+ result.explicit = (this.explicit || []).concat(explicit);
592
+ result.compiledImplicit = compileList(result, "implicit");
593
+ result.compiledExplicit = compileList(result, "explicit");
594
+ result.compiledTypeMap = compileMap(result.compiledImplicit, result.compiledExplicit);
595
+ return result;
596
+ };
597
+ schema = Schema2;
598
+ return schema;
599
+ }
600
+ var str;
601
+ var hasRequiredStr;
602
+ function requireStr() {
603
+ if (hasRequiredStr) return str;
604
+ hasRequiredStr = 1;
605
+ const Type2 = requireType();
606
+ str = new Type2("tag:yaml.org,2002:str", {
607
+ kind: "scalar",
608
+ construct: function(data) {
609
+ return data !== null ? data : "";
610
+ }
611
+ });
612
+ return str;
613
+ }
614
+ var seq;
615
+ var hasRequiredSeq;
616
+ function requireSeq() {
617
+ if (hasRequiredSeq) return seq;
618
+ hasRequiredSeq = 1;
619
+ const Type2 = requireType();
620
+ seq = new Type2("tag:yaml.org,2002:seq", {
621
+ kind: "sequence",
622
+ construct: function(data) {
623
+ return data !== null ? data : [];
624
+ }
625
+ });
626
+ return seq;
627
+ }
628
+ var map;
629
+ var hasRequiredMap;
630
+ function requireMap() {
631
+ if (hasRequiredMap) return map;
632
+ hasRequiredMap = 1;
633
+ const Type2 = requireType();
634
+ map = new Type2("tag:yaml.org,2002:map", {
635
+ kind: "mapping",
636
+ construct: function(data) {
637
+ return data !== null ? data : {};
638
+ }
639
+ });
640
+ return map;
641
+ }
642
+ var failsafe;
643
+ var hasRequiredFailsafe;
644
+ function requireFailsafe() {
645
+ if (hasRequiredFailsafe) return failsafe;
646
+ hasRequiredFailsafe = 1;
647
+ const Schema2 = requireSchema();
648
+ failsafe = new Schema2({
649
+ explicit: [
650
+ requireStr(),
651
+ requireSeq(),
652
+ requireMap()
653
+ ]
654
+ });
655
+ return failsafe;
656
+ }
657
+ var _null;
658
+ var hasRequired_null;
659
+ function require_null() {
660
+ if (hasRequired_null) return _null;
661
+ hasRequired_null = 1;
662
+ const Type2 = requireType();
663
+ function resolveYamlNull(data) {
664
+ if (data === null) return true;
665
+ const max = data.length;
666
+ return max === 1 && data === "~" || max === 4 && (data === "null" || data === "Null" || data === "NULL");
667
+ }
668
+ function constructYamlNull() {
669
+ return null;
670
+ }
671
+ function isNull(object) {
672
+ return object === null;
673
+ }
674
+ _null = new Type2("tag:yaml.org,2002:null", {
675
+ kind: "scalar",
676
+ resolve: resolveYamlNull,
677
+ construct: constructYamlNull,
678
+ predicate: isNull,
679
+ represent: {
680
+ canonical: function() {
681
+ return "~";
682
+ },
683
+ lowercase: function() {
684
+ return "null";
685
+ },
686
+ uppercase: function() {
687
+ return "NULL";
688
+ },
689
+ camelcase: function() {
690
+ return "Null";
691
+ },
692
+ empty: function() {
693
+ return "";
694
+ }
695
+ },
696
+ defaultStyle: "lowercase"
697
+ });
698
+ return _null;
699
+ }
700
+ var bool;
701
+ var hasRequiredBool;
702
+ function requireBool() {
703
+ if (hasRequiredBool) return bool;
704
+ hasRequiredBool = 1;
705
+ const Type2 = requireType();
706
+ function resolveYamlBoolean(data) {
707
+ if (data === null) return false;
708
+ const max = data.length;
709
+ return max === 4 && (data === "true" || data === "True" || data === "TRUE") || max === 5 && (data === "false" || data === "False" || data === "FALSE");
710
+ }
711
+ function constructYamlBoolean(data) {
712
+ return data === "true" || data === "True" || data === "TRUE";
713
+ }
714
+ function isBoolean(object) {
715
+ return Object.prototype.toString.call(object) === "[object Boolean]";
716
+ }
717
+ bool = new Type2("tag:yaml.org,2002:bool", {
718
+ kind: "scalar",
719
+ resolve: resolveYamlBoolean,
720
+ construct: constructYamlBoolean,
721
+ predicate: isBoolean,
722
+ represent: {
723
+ lowercase: function(object) {
724
+ return object ? "true" : "false";
725
+ },
726
+ uppercase: function(object) {
727
+ return object ? "TRUE" : "FALSE";
728
+ },
729
+ camelcase: function(object) {
730
+ return object ? "True" : "False";
731
+ }
732
+ },
733
+ defaultStyle: "lowercase"
734
+ });
735
+ return bool;
736
+ }
737
+ var int;
738
+ var hasRequiredInt;
739
+ function requireInt() {
740
+ if (hasRequiredInt) return int;
741
+ hasRequiredInt = 1;
742
+ const common2 = requireCommon();
743
+ const Type2 = requireType();
744
+ function isHexCode(c) {
745
+ return c >= 48 && c <= 57 || c >= 65 && c <= 70 || c >= 97 && c <= 102;
746
+ }
747
+ function isOctCode(c) {
748
+ return c >= 48 && c <= 55;
749
+ }
750
+ function isDecCode(c) {
751
+ return c >= 48 && c <= 57;
752
+ }
753
+ function resolveYamlInteger(data) {
754
+ if (data === null) return false;
755
+ const max = data.length;
756
+ let index = 0;
757
+ let hasDigits = false;
758
+ if (!max) return false;
759
+ let ch = data[index];
760
+ if (ch === "-" || ch === "+") {
761
+ ch = data[++index];
762
+ }
763
+ if (ch === "0") {
764
+ if (index + 1 === max) return true;
765
+ ch = data[++index];
766
+ if (ch === "b") {
767
+ index++;
768
+ for (; index < max; index++) {
769
+ ch = data[index];
770
+ if (ch !== "0" && ch !== "1") return false;
771
+ hasDigits = true;
772
+ }
773
+ return hasDigits && isFinite(parseYamlInteger(data));
774
+ }
775
+ if (ch === "x") {
776
+ index++;
777
+ for (; index < max; index++) {
778
+ if (!isHexCode(data.charCodeAt(index))) return false;
779
+ hasDigits = true;
780
+ }
781
+ return hasDigits && isFinite(parseYamlInteger(data));
782
+ }
783
+ if (ch === "o") {
784
+ index++;
785
+ for (; index < max; index++) {
786
+ if (!isOctCode(data.charCodeAt(index))) return false;
787
+ hasDigits = true;
788
+ }
789
+ return hasDigits && isFinite(parseYamlInteger(data));
790
+ }
791
+ }
792
+ for (; index < max; index++) {
793
+ if (!isDecCode(data.charCodeAt(index))) {
794
+ return false;
795
+ }
796
+ hasDigits = true;
797
+ }
798
+ if (!hasDigits) return false;
799
+ return isFinite(parseYamlInteger(data));
800
+ }
801
+ function parseYamlInteger(data) {
802
+ let value = data;
803
+ let sign = 1;
804
+ let ch = value[0];
805
+ if (ch === "-" || ch === "+") {
806
+ if (ch === "-") sign = -1;
807
+ value = value.slice(1);
808
+ ch = value[0];
809
+ }
810
+ if (value === "0") return 0;
811
+ if (ch === "0") {
812
+ if (value[1] === "b") return sign * parseInt(value.slice(2), 2);
813
+ if (value[1] === "x") return sign * parseInt(value.slice(2), 16);
814
+ if (value[1] === "o") return sign * parseInt(value.slice(2), 8);
815
+ }
816
+ return sign * parseInt(value, 10);
817
+ }
818
+ function constructYamlInteger(data) {
819
+ return parseYamlInteger(data);
820
+ }
821
+ function isInteger(object) {
822
+ return Object.prototype.toString.call(object) === "[object Number]" && (object % 1 === 0 && !common2.isNegativeZero(object));
823
+ }
824
+ int = new Type2("tag:yaml.org,2002:int", {
825
+ kind: "scalar",
826
+ resolve: resolveYamlInteger,
827
+ construct: constructYamlInteger,
828
+ predicate: isInteger,
829
+ represent: {
830
+ binary: function(obj) {
831
+ return obj >= 0 ? "0b" + obj.toString(2) : "-0b" + obj.toString(2).slice(1);
832
+ },
833
+ octal: function(obj) {
834
+ return obj >= 0 ? "0o" + obj.toString(8) : "-0o" + obj.toString(8).slice(1);
835
+ },
836
+ decimal: function(obj) {
837
+ return obj.toString(10);
838
+ },
839
+ hexadecimal: function(obj) {
840
+ return obj >= 0 ? "0x" + obj.toString(16).toUpperCase() : "-0x" + obj.toString(16).toUpperCase().slice(1);
841
+ }
842
+ },
843
+ defaultStyle: "decimal",
844
+ styleAliases: {
845
+ binary: [2, "bin"],
846
+ octal: [8, "oct"],
847
+ decimal: [10, "dec"],
848
+ hexadecimal: [16, "hex"]
849
+ }
850
+ });
851
+ return int;
852
+ }
853
+ var float;
854
+ var hasRequiredFloat;
855
+ function requireFloat() {
856
+ if (hasRequiredFloat) return float;
857
+ hasRequiredFloat = 1;
858
+ const common2 = requireCommon();
859
+ const Type2 = requireType();
860
+ const YAML_FLOAT_PATTERN = new RegExp(
861
+ // 2.5e4, 2.5 and integers
862
+ "^(?:[-+]?(?:[0-9]+)(?:\\.[0-9]*)?(?:[eE][-+]?[0-9]+)?|\\.[0-9]+(?:[eE][-+]?[0-9]+)?|[-+]?\\.(?:inf|Inf|INF)|\\.(?:nan|NaN|NAN))$"
863
+ );
864
+ const YAML_FLOAT_SPECIAL_PATTERN = new RegExp(
865
+ "^(?:[-+]?\\.(?:inf|Inf|INF)|\\.(?:nan|NaN|NAN))$"
866
+ );
867
+ function resolveYamlFloat(data) {
868
+ if (data === null) return false;
869
+ if (!YAML_FLOAT_PATTERN.test(data)) {
870
+ return false;
871
+ }
872
+ if (isFinite(parseFloat(data, 10))) {
873
+ return true;
874
+ }
875
+ return YAML_FLOAT_SPECIAL_PATTERN.test(data);
876
+ }
877
+ function constructYamlFloat(data) {
878
+ let value = data.toLowerCase();
879
+ const sign = value[0] === "-" ? -1 : 1;
880
+ if ("+-".indexOf(value[0]) >= 0) {
881
+ value = value.slice(1);
882
+ }
883
+ if (value === ".inf") {
884
+ return sign === 1 ? Number.POSITIVE_INFINITY : Number.NEGATIVE_INFINITY;
885
+ } else if (value === ".nan") {
886
+ return NaN;
887
+ }
888
+ return sign * parseFloat(value, 10);
889
+ }
890
+ const SCIENTIFIC_WITHOUT_DOT = /^[-+]?[0-9]+e/;
891
+ function representYamlFloat(object, style) {
892
+ if (isNaN(object)) {
893
+ switch (style) {
894
+ case "lowercase":
895
+ return ".nan";
896
+ case "uppercase":
897
+ return ".NAN";
898
+ case "camelcase":
899
+ return ".NaN";
900
+ }
901
+ } else if (Number.POSITIVE_INFINITY === object) {
902
+ switch (style) {
903
+ case "lowercase":
904
+ return ".inf";
905
+ case "uppercase":
906
+ return ".INF";
907
+ case "camelcase":
908
+ return ".Inf";
909
+ }
910
+ } else if (Number.NEGATIVE_INFINITY === object) {
911
+ switch (style) {
912
+ case "lowercase":
913
+ return "-.inf";
914
+ case "uppercase":
915
+ return "-.INF";
916
+ case "camelcase":
917
+ return "-.Inf";
918
+ }
919
+ } else if (common2.isNegativeZero(object)) {
920
+ return "-0.0";
921
+ }
922
+ const res = object.toString(10);
923
+ return SCIENTIFIC_WITHOUT_DOT.test(res) ? res.replace("e", ".e") : res;
924
+ }
925
+ function isFloat(object) {
926
+ return Object.prototype.toString.call(object) === "[object Number]" && (object % 1 !== 0 || common2.isNegativeZero(object));
927
+ }
928
+ float = new Type2("tag:yaml.org,2002:float", {
929
+ kind: "scalar",
930
+ resolve: resolveYamlFloat,
931
+ construct: constructYamlFloat,
932
+ predicate: isFloat,
933
+ represent: representYamlFloat,
934
+ defaultStyle: "lowercase"
935
+ });
936
+ return float;
937
+ }
938
+ var json;
939
+ var hasRequiredJson;
940
+ function requireJson() {
941
+ if (hasRequiredJson) return json;
942
+ hasRequiredJson = 1;
943
+ json = requireFailsafe().extend({
944
+ implicit: [
945
+ require_null(),
946
+ requireBool(),
947
+ requireInt(),
948
+ requireFloat()
949
+ ]
950
+ });
951
+ return json;
952
+ }
953
+ var core;
954
+ var hasRequiredCore;
955
+ function requireCore() {
956
+ if (hasRequiredCore) return core;
957
+ hasRequiredCore = 1;
958
+ core = requireJson();
959
+ return core;
960
+ }
961
+ var timestamp;
962
+ var hasRequiredTimestamp;
963
+ function requireTimestamp() {
964
+ if (hasRequiredTimestamp) return timestamp;
965
+ hasRequiredTimestamp = 1;
966
+ const Type2 = requireType();
967
+ const YAML_DATE_REGEXP = new RegExp(
968
+ "^([0-9][0-9][0-9][0-9])-([0-9][0-9])-([0-9][0-9])$"
969
+ );
970
+ const YAML_TIMESTAMP_REGEXP = new RegExp(
971
+ "^([0-9][0-9][0-9][0-9])-([0-9][0-9]?)-([0-9][0-9]?)(?:[Tt]|[ \\t]+)([0-9][0-9]?):([0-9][0-9]):([0-9][0-9])(?:\\.([0-9]*))?(?:[ \\t]*(Z|([-+])([0-9][0-9]?)(?::([0-9][0-9]))?))?$"
972
+ );
973
+ function resolveYamlTimestamp(data) {
974
+ if (data === null) return false;
975
+ if (YAML_DATE_REGEXP.exec(data) !== null) return true;
976
+ if (YAML_TIMESTAMP_REGEXP.exec(data) !== null) return true;
977
+ return false;
978
+ }
979
+ function constructYamlTimestamp(data) {
980
+ let fraction = 0;
981
+ let delta = null;
982
+ let match = YAML_DATE_REGEXP.exec(data);
983
+ if (match === null) match = YAML_TIMESTAMP_REGEXP.exec(data);
984
+ if (match === null) throw new Error("Date resolve error");
985
+ const year = +match[1];
986
+ const month = +match[2] - 1;
987
+ const day = +match[3];
988
+ if (!match[4]) {
989
+ return new Date(Date.UTC(year, month, day));
990
+ }
991
+ const hour = +match[4];
992
+ const minute = +match[5];
993
+ const second = +match[6];
994
+ if (match[7]) {
995
+ fraction = match[7].slice(0, 3);
996
+ while (fraction.length < 3) {
997
+ fraction += "0";
998
+ }
999
+ fraction = +fraction;
1000
+ }
1001
+ if (match[9]) {
1002
+ const tzHour = +match[10];
1003
+ const tzMinute = +(match[11] || 0);
1004
+ delta = (tzHour * 60 + tzMinute) * 6e4;
1005
+ if (match[9] === "-") delta = -delta;
1006
+ }
1007
+ const date = new Date(Date.UTC(year, month, day, hour, minute, second, fraction));
1008
+ if (delta) date.setTime(date.getTime() - delta);
1009
+ return date;
1010
+ }
1011
+ function representYamlTimestamp(object) {
1012
+ return object.toISOString();
1013
+ }
1014
+ timestamp = new Type2("tag:yaml.org,2002:timestamp", {
1015
+ kind: "scalar",
1016
+ resolve: resolveYamlTimestamp,
1017
+ construct: constructYamlTimestamp,
1018
+ instanceOf: Date,
1019
+ represent: representYamlTimestamp
1020
+ });
1021
+ return timestamp;
1022
+ }
1023
+ var merge;
1024
+ var hasRequiredMerge;
1025
+ function requireMerge() {
1026
+ if (hasRequiredMerge) return merge;
1027
+ hasRequiredMerge = 1;
1028
+ const Type2 = requireType();
1029
+ function resolveYamlMerge(data) {
1030
+ return data === "<<" || data === null;
1031
+ }
1032
+ merge = new Type2("tag:yaml.org,2002:merge", {
1033
+ kind: "scalar",
1034
+ resolve: resolveYamlMerge
1035
+ });
1036
+ return merge;
1037
+ }
1038
+ var binary;
1039
+ var hasRequiredBinary;
1040
+ function requireBinary() {
1041
+ if (hasRequiredBinary) return binary;
1042
+ hasRequiredBinary = 1;
1043
+ const Type2 = requireType();
1044
+ const BASE64_MAP = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\n\r";
1045
+ function resolveYamlBinary(data) {
1046
+ if (data === null) return false;
1047
+ let bitlen = 0;
1048
+ const max = data.length;
1049
+ const map2 = BASE64_MAP;
1050
+ for (let idx = 0; idx < max; idx++) {
1051
+ const code = map2.indexOf(data.charAt(idx));
1052
+ if (code > 64) continue;
1053
+ if (code < 0) return false;
1054
+ bitlen += 6;
1055
+ }
1056
+ return bitlen % 8 === 0;
1057
+ }
1058
+ function constructYamlBinary(data) {
1059
+ const input = data.replace(/[\r\n=]/g, "");
1060
+ const max = input.length;
1061
+ const map2 = BASE64_MAP;
1062
+ let bits = 0;
1063
+ const result = [];
1064
+ for (let idx = 0; idx < max; idx++) {
1065
+ if (idx % 4 === 0 && idx) {
1066
+ result.push(bits >> 16 & 255);
1067
+ result.push(bits >> 8 & 255);
1068
+ result.push(bits & 255);
1069
+ }
1070
+ bits = bits << 6 | map2.indexOf(input.charAt(idx));
1071
+ }
1072
+ const tailbits = max % 4 * 6;
1073
+ if (tailbits === 0) {
1074
+ result.push(bits >> 16 & 255);
1075
+ result.push(bits >> 8 & 255);
1076
+ result.push(bits & 255);
1077
+ } else if (tailbits === 18) {
1078
+ result.push(bits >> 10 & 255);
1079
+ result.push(bits >> 2 & 255);
1080
+ } else if (tailbits === 12) {
1081
+ result.push(bits >> 4 & 255);
1082
+ }
1083
+ return new Uint8Array(result);
1084
+ }
1085
+ function representYamlBinary(object) {
1086
+ let result = "";
1087
+ let bits = 0;
1088
+ const max = object.length;
1089
+ const map2 = BASE64_MAP;
1090
+ for (let idx = 0; idx < max; idx++) {
1091
+ if (idx % 3 === 0 && idx) {
1092
+ result += map2[bits >> 18 & 63];
1093
+ result += map2[bits >> 12 & 63];
1094
+ result += map2[bits >> 6 & 63];
1095
+ result += map2[bits & 63];
1096
+ }
1097
+ bits = (bits << 8) + object[idx];
1098
+ }
1099
+ const tail = max % 3;
1100
+ if (tail === 0) {
1101
+ result += map2[bits >> 18 & 63];
1102
+ result += map2[bits >> 12 & 63];
1103
+ result += map2[bits >> 6 & 63];
1104
+ result += map2[bits & 63];
1105
+ } else if (tail === 2) {
1106
+ result += map2[bits >> 10 & 63];
1107
+ result += map2[bits >> 4 & 63];
1108
+ result += map2[bits << 2 & 63];
1109
+ result += map2[64];
1110
+ } else if (tail === 1) {
1111
+ result += map2[bits >> 2 & 63];
1112
+ result += map2[bits << 4 & 63];
1113
+ result += map2[64];
1114
+ result += map2[64];
1115
+ }
1116
+ return result;
1117
+ }
1118
+ function isBinary(obj) {
1119
+ return Object.prototype.toString.call(obj) === "[object Uint8Array]";
1120
+ }
1121
+ binary = new Type2("tag:yaml.org,2002:binary", {
1122
+ kind: "scalar",
1123
+ resolve: resolveYamlBinary,
1124
+ construct: constructYamlBinary,
1125
+ predicate: isBinary,
1126
+ represent: representYamlBinary
1127
+ });
1128
+ return binary;
1129
+ }
1130
+ var omap;
1131
+ var hasRequiredOmap;
1132
+ function requireOmap() {
1133
+ if (hasRequiredOmap) return omap;
1134
+ hasRequiredOmap = 1;
1135
+ const Type2 = requireType();
1136
+ const _hasOwnProperty = Object.prototype.hasOwnProperty;
1137
+ const _toString = Object.prototype.toString;
1138
+ function resolveYamlOmap(data) {
1139
+ if (data === null) return true;
1140
+ const objectKeys = [];
1141
+ const object = data;
1142
+ for (let index = 0, length = object.length; index < length; index += 1) {
1143
+ const pair = object[index];
1144
+ let pairHasKey = false;
1145
+ if (_toString.call(pair) !== "[object Object]") return false;
1146
+ let pairKey;
1147
+ for (pairKey in pair) {
1148
+ if (_hasOwnProperty.call(pair, pairKey)) {
1149
+ if (!pairHasKey) pairHasKey = true;
1150
+ else return false;
1151
+ }
1152
+ }
1153
+ if (!pairHasKey) return false;
1154
+ if (objectKeys.indexOf(pairKey) === -1) objectKeys.push(pairKey);
1155
+ else return false;
1156
+ }
1157
+ return true;
1158
+ }
1159
+ function constructYamlOmap(data) {
1160
+ return data !== null ? data : [];
1161
+ }
1162
+ omap = new Type2("tag:yaml.org,2002:omap", {
1163
+ kind: "sequence",
1164
+ resolve: resolveYamlOmap,
1165
+ construct: constructYamlOmap
1166
+ });
1167
+ return omap;
1168
+ }
1169
+ var pairs;
1170
+ var hasRequiredPairs;
1171
+ function requirePairs() {
1172
+ if (hasRequiredPairs) return pairs;
1173
+ hasRequiredPairs = 1;
1174
+ const Type2 = requireType();
1175
+ const _toString = Object.prototype.toString;
1176
+ function resolveYamlPairs(data) {
1177
+ if (data === null) return true;
1178
+ const object = data;
1179
+ const result = new Array(object.length);
1180
+ for (let index = 0, length = object.length; index < length; index += 1) {
1181
+ const pair = object[index];
1182
+ if (_toString.call(pair) !== "[object Object]") return false;
1183
+ const keys = Object.keys(pair);
1184
+ if (keys.length !== 1) return false;
1185
+ result[index] = [keys[0], pair[keys[0]]];
1186
+ }
1187
+ return true;
1188
+ }
1189
+ function constructYamlPairs(data) {
1190
+ if (data === null) return [];
1191
+ const object = data;
1192
+ const result = new Array(object.length);
1193
+ for (let index = 0, length = object.length; index < length; index += 1) {
1194
+ const pair = object[index];
1195
+ const keys = Object.keys(pair);
1196
+ result[index] = [keys[0], pair[keys[0]]];
1197
+ }
1198
+ return result;
1199
+ }
1200
+ pairs = new Type2("tag:yaml.org,2002:pairs", {
1201
+ kind: "sequence",
1202
+ resolve: resolveYamlPairs,
1203
+ construct: constructYamlPairs
1204
+ });
1205
+ return pairs;
1206
+ }
1207
+ var set;
1208
+ var hasRequiredSet;
1209
+ function requireSet() {
1210
+ if (hasRequiredSet) return set;
1211
+ hasRequiredSet = 1;
1212
+ const Type2 = requireType();
1213
+ const _hasOwnProperty = Object.prototype.hasOwnProperty;
1214
+ function resolveYamlSet(data) {
1215
+ if (data === null) return true;
1216
+ const object = data;
1217
+ for (const key in object) {
1218
+ if (_hasOwnProperty.call(object, key)) {
1219
+ if (object[key] !== null) return false;
1220
+ }
1221
+ }
1222
+ return true;
1223
+ }
1224
+ function constructYamlSet(data) {
1225
+ return data !== null ? data : {};
1226
+ }
1227
+ set = new Type2("tag:yaml.org,2002:set", {
1228
+ kind: "mapping",
1229
+ resolve: resolveYamlSet,
1230
+ construct: constructYamlSet
1231
+ });
1232
+ return set;
1233
+ }
1234
+ var _default;
1235
+ var hasRequired_default;
1236
+ function require_default() {
1237
+ if (hasRequired_default) return _default;
1238
+ hasRequired_default = 1;
1239
+ _default = requireCore().extend({
1240
+ implicit: [
1241
+ requireTimestamp(),
1242
+ requireMerge()
1243
+ ],
1244
+ explicit: [
1245
+ requireBinary(),
1246
+ requireOmap(),
1247
+ requirePairs(),
1248
+ requireSet()
1249
+ ]
1250
+ });
1251
+ return _default;
1252
+ }
1253
+ var hasRequiredLoader;
1254
+ function requireLoader() {
1255
+ if (hasRequiredLoader) return loader;
1256
+ hasRequiredLoader = 1;
1257
+ const common2 = requireCommon();
1258
+ const YAMLException2 = requireException();
1259
+ const makeSnippet = requireSnippet();
1260
+ const DEFAULT_SCHEMA2 = require_default();
1261
+ const _hasOwnProperty = Object.prototype.hasOwnProperty;
1262
+ const CONTEXT_FLOW_IN = 1;
1263
+ const CONTEXT_FLOW_OUT = 2;
1264
+ const CONTEXT_BLOCK_IN = 3;
1265
+ const CONTEXT_BLOCK_OUT = 4;
1266
+ const CHOMPING_CLIP = 1;
1267
+ const CHOMPING_STRIP = 2;
1268
+ const CHOMPING_KEEP = 3;
1269
+ const PATTERN_NON_PRINTABLE = /[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x84\x86-\x9F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/;
1270
+ const PATTERN_NON_ASCII_LINE_BREAKS = /[\x85\u2028\u2029]/;
1271
+ const PATTERN_FLOW_INDICATORS = /[,\[\]{}]/;
1272
+ const PATTERN_TAG_HANDLE = /^(?:!|!!|![0-9A-Za-z-]+!)$/;
1273
+ const PATTERN_TAG_URI = /^(?:!|[^,\[\]{}])(?:%[0-9a-f]{2}|[0-9a-z\-#;/?:@&=+$,_.!~*'()\[\]])*$/i;
1274
+ function _class(obj) {
1275
+ return Object.prototype.toString.call(obj);
1276
+ }
1277
+ function isEol(c) {
1278
+ return c === 10 || c === 13;
1279
+ }
1280
+ function isWhiteSpace(c) {
1281
+ return c === 9 || c === 32;
1282
+ }
1283
+ function isWsOrEol(c) {
1284
+ return c === 9 || c === 32 || c === 10 || c === 13;
1285
+ }
1286
+ function isFlowIndicator(c) {
1287
+ return c === 44 || c === 91 || c === 93 || c === 123 || c === 125;
1288
+ }
1289
+ function fromHexCode(c) {
1290
+ if (c >= 48 && c <= 57) {
1291
+ return c - 48;
1292
+ }
1293
+ const lc = c | 32;
1294
+ if (lc >= 97 && lc <= 102) {
1295
+ return lc - 97 + 10;
1296
+ }
1297
+ return -1;
1298
+ }
1299
+ function escapedHexLen(c) {
1300
+ if (c === 120) {
1301
+ return 2;
1302
+ }
1303
+ if (c === 117) {
1304
+ return 4;
1305
+ }
1306
+ if (c === 85) {
1307
+ return 8;
1308
+ }
1309
+ return 0;
1310
+ }
1311
+ function fromDecimalCode(c) {
1312
+ if (c >= 48 && c <= 57) {
1313
+ return c - 48;
1314
+ }
1315
+ return -1;
1316
+ }
1317
+ function simpleEscapeSequence(c) {
1318
+ switch (c) {
1319
+ case 48:
1320
+ return "\0";
1321
+ case 97:
1322
+ return "\x07";
1323
+ case 98:
1324
+ return "\b";
1325
+ case 116:
1326
+ return " ";
1327
+ case 9:
1328
+ return " ";
1329
+ case 110:
1330
+ return "\n";
1331
+ case 118:
1332
+ return "\v";
1333
+ case 102:
1334
+ return "\f";
1335
+ case 114:
1336
+ return "\r";
1337
+ case 101:
1338
+ return "\x1B";
1339
+ case 32:
1340
+ return " ";
1341
+ case 34:
1342
+ return '"';
1343
+ case 47:
1344
+ return "/";
1345
+ case 92:
1346
+ return "\\";
1347
+ case 78:
1348
+ return "\x85";
1349
+ case 95:
1350
+ return "\xA0";
1351
+ case 76:
1352
+ return "\u2028";
1353
+ case 80:
1354
+ return "\u2029";
1355
+ default:
1356
+ return "";
1357
+ }
1358
+ }
1359
+ function charFromCodepoint(c) {
1360
+ if (c <= 65535) {
1361
+ return String.fromCharCode(c);
1362
+ }
1363
+ return String.fromCharCode(
1364
+ (c - 65536 >> 10) + 55296,
1365
+ (c - 65536 & 1023) + 56320
1366
+ );
1367
+ }
1368
+ function setProperty(object, key, value) {
1369
+ if (key === "__proto__") {
1370
+ Object.defineProperty(object, key, {
1371
+ configurable: true,
1372
+ enumerable: true,
1373
+ writable: true,
1374
+ value
1375
+ });
1376
+ } else {
1377
+ object[key] = value;
1378
+ }
1379
+ }
1380
+ const simpleEscapeCheck = new Array(256);
1381
+ const simpleEscapeMap = new Array(256);
1382
+ for (let i = 0; i < 256; i++) {
1383
+ simpleEscapeCheck[i] = simpleEscapeSequence(i) ? 1 : 0;
1384
+ simpleEscapeMap[i] = simpleEscapeSequence(i);
1385
+ }
1386
+ function State(input, options) {
1387
+ this.input = input;
1388
+ this.filename = options["filename"] || null;
1389
+ this.schema = options["schema"] || DEFAULT_SCHEMA2;
1390
+ this.onWarning = options["onWarning"] || null;
1391
+ this.legacy = options["legacy"] || false;
1392
+ this.json = options["json"] || false;
1393
+ this.listener = options["listener"] || null;
1394
+ this.maxDepth = typeof options["maxDepth"] === "number" ? options["maxDepth"] : 100;
1395
+ this.maxTotalMergeKeys = typeof options["maxTotalMergeKeys"] === "number" ? options["maxTotalMergeKeys"] : 1e4;
1396
+ this.implicitTypes = this.schema.compiledImplicit;
1397
+ this.typeMap = this.schema.compiledTypeMap;
1398
+ this.length = input.length;
1399
+ this.position = 0;
1400
+ this.line = 0;
1401
+ this.lineStart = 0;
1402
+ this.lineIndent = 0;
1403
+ this.depth = 0;
1404
+ this.totalMergeKeys = 0;
1405
+ this.firstTabInLine = -1;
1406
+ this.documents = [];
1407
+ this.anchorMapTransactions = [];
1408
+ }
1409
+ function generateError(state, message) {
1410
+ const mark = {
1411
+ name: state.filename,
1412
+ buffer: state.input.slice(0, -1),
1413
+ // omit trailing \0
1414
+ position: state.position,
1415
+ line: state.line,
1416
+ column: state.position - state.lineStart
1417
+ };
1418
+ mark.snippet = makeSnippet(mark);
1419
+ return new YAMLException2(message, mark);
1420
+ }
1421
+ function throwError(state, message) {
1422
+ throw generateError(state, message);
1423
+ }
1424
+ function throwWarning(state, message) {
1425
+ if (state.onWarning) {
1426
+ state.onWarning.call(null, generateError(state, message));
1427
+ }
1428
+ }
1429
+ function storeAnchor(state, name, value) {
1430
+ const transactions = state.anchorMapTransactions;
1431
+ if (transactions.length !== 0) {
1432
+ const transaction = transactions[transactions.length - 1];
1433
+ if (!_hasOwnProperty.call(transaction, name)) {
1434
+ transaction[name] = {
1435
+ existed: _hasOwnProperty.call(state.anchorMap, name),
1436
+ value: state.anchorMap[name]
1437
+ };
1438
+ }
1439
+ }
1440
+ state.anchorMap[name] = value;
1441
+ }
1442
+ function beginAnchorTransaction(state) {
1443
+ state.anchorMapTransactions.push(/* @__PURE__ */ Object.create(null));
1444
+ }
1445
+ function commitAnchorTransaction(state) {
1446
+ const transaction = state.anchorMapTransactions.pop();
1447
+ const transactions = state.anchorMapTransactions;
1448
+ if (transactions.length === 0) return;
1449
+ const parent = transactions[transactions.length - 1];
1450
+ const names = Object.keys(transaction);
1451
+ for (let index = 0, length = names.length; index < length; index += 1) {
1452
+ const name = names[index];
1453
+ if (!_hasOwnProperty.call(parent, name)) {
1454
+ parent[name] = transaction[name];
1455
+ }
1456
+ }
1457
+ }
1458
+ function rollbackAnchorTransaction(state) {
1459
+ const transaction = state.anchorMapTransactions.pop();
1460
+ const names = Object.keys(transaction);
1461
+ for (let index = names.length - 1; index >= 0; index -= 1) {
1462
+ const entry = transaction[names[index]];
1463
+ if (entry.existed) {
1464
+ state.anchorMap[names[index]] = entry.value;
1465
+ } else {
1466
+ delete state.anchorMap[names[index]];
1467
+ }
1468
+ }
1469
+ }
1470
+ function snapshotState(state) {
1471
+ return {
1472
+ position: state.position,
1473
+ line: state.line,
1474
+ lineStart: state.lineStart,
1475
+ lineIndent: state.lineIndent,
1476
+ firstTabInLine: state.firstTabInLine,
1477
+ tag: state.tag,
1478
+ anchor: state.anchor,
1479
+ kind: state.kind,
1480
+ result: state.result
1481
+ };
1482
+ }
1483
+ function restoreState(state, snapshot) {
1484
+ state.position = snapshot.position;
1485
+ state.line = snapshot.line;
1486
+ state.lineStart = snapshot.lineStart;
1487
+ state.lineIndent = snapshot.lineIndent;
1488
+ state.firstTabInLine = snapshot.firstTabInLine;
1489
+ state.tag = snapshot.tag;
1490
+ state.anchor = snapshot.anchor;
1491
+ state.kind = snapshot.kind;
1492
+ state.result = snapshot.result;
1493
+ }
1494
+ const directiveHandlers = {
1495
+ YAML: function handleYamlDirective(state, name, args) {
1496
+ if (state.version !== null) {
1497
+ throwError(state, "duplication of %YAML directive");
1498
+ }
1499
+ if (args.length !== 1) {
1500
+ throwError(state, "YAML directive accepts exactly one argument");
1501
+ }
1502
+ const match = /^([0-9]+)\.([0-9]+)$/.exec(args[0]);
1503
+ if (match === null) {
1504
+ throwError(state, "ill-formed argument of the YAML directive");
1505
+ }
1506
+ const major = parseInt(match[1], 10);
1507
+ const minor = parseInt(match[2], 10);
1508
+ if (major !== 1) {
1509
+ throwError(state, "unacceptable YAML version of the document");
1510
+ }
1511
+ state.version = args[0];
1512
+ state.checkLineBreaks = minor < 2;
1513
+ if (minor !== 1 && minor !== 2) {
1514
+ throwWarning(state, "unsupported YAML version of the document");
1515
+ }
1516
+ },
1517
+ TAG: function handleTagDirective(state, name, args) {
1518
+ let prefix;
1519
+ if (args.length !== 2) {
1520
+ throwError(state, "TAG directive accepts exactly two arguments");
1521
+ }
1522
+ const handle = args[0];
1523
+ prefix = args[1];
1524
+ if (!PATTERN_TAG_HANDLE.test(handle)) {
1525
+ throwError(state, "ill-formed tag handle (first argument) of the TAG directive");
1526
+ }
1527
+ if (_hasOwnProperty.call(state.tagMap, handle)) {
1528
+ throwError(state, 'there is a previously declared suffix for "' + handle + '" tag handle');
1529
+ }
1530
+ if (!PATTERN_TAG_URI.test(prefix)) {
1531
+ throwError(state, "ill-formed tag prefix (second argument) of the TAG directive");
1532
+ }
1533
+ try {
1534
+ prefix = decodeURIComponent(prefix);
1535
+ } catch (err) {
1536
+ throwError(state, "tag prefix is malformed: " + prefix);
1537
+ }
1538
+ state.tagMap[handle] = prefix;
1539
+ }
1540
+ };
1541
+ function captureSegment(state, start, end, checkJson) {
1542
+ if (start < end) {
1543
+ const _result = state.input.slice(start, end);
1544
+ if (checkJson) {
1545
+ for (let _position = 0, _length = _result.length; _position < _length; _position += 1) {
1546
+ const _character = _result.charCodeAt(_position);
1547
+ if (!(_character === 9 || _character >= 32 && _character <= 1114111)) {
1548
+ throwError(state, "expected valid JSON character");
1549
+ }
1550
+ }
1551
+ } else if (PATTERN_NON_PRINTABLE.test(_result)) {
1552
+ throwError(state, "the stream contains non-printable characters");
1553
+ }
1554
+ state.result += _result;
1555
+ }
1556
+ }
1557
+ function mergeMappings(state, destination, source, overridableKeys) {
1558
+ if (!common2.isObject(source)) {
1559
+ throwError(state, "cannot merge mappings; the provided source object is unacceptable");
1560
+ }
1561
+ const sourceKeys = Object.keys(source);
1562
+ for (let index = 0, quantity = sourceKeys.length; index < quantity; index += 1) {
1563
+ const key = sourceKeys[index];
1564
+ if (state.maxTotalMergeKeys !== -1 && ++state.totalMergeKeys > state.maxTotalMergeKeys) {
1565
+ throwError(state, "merge keys exceeded maxTotalMergeKeys (" + state.maxTotalMergeKeys + ")");
1566
+ }
1567
+ if (!_hasOwnProperty.call(destination, key)) {
1568
+ setProperty(destination, key, source[key]);
1569
+ overridableKeys[key] = true;
1570
+ }
1571
+ }
1572
+ }
1573
+ function storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, startLine, startLineStart, startPos) {
1574
+ if (Array.isArray(keyNode)) {
1575
+ keyNode = Array.prototype.slice.call(keyNode);
1576
+ for (let index = 0, quantity = keyNode.length; index < quantity; index += 1) {
1577
+ if (Array.isArray(keyNode[index])) {
1578
+ throwError(state, "nested arrays are not supported inside keys");
1579
+ }
1580
+ if (typeof keyNode === "object" && _class(keyNode[index]) === "[object Object]") {
1581
+ keyNode[index] = "[object Object]";
1582
+ }
1583
+ }
1584
+ }
1585
+ if (typeof keyNode === "object" && _class(keyNode) === "[object Object]") {
1586
+ keyNode = "[object Object]";
1587
+ }
1588
+ keyNode = String(keyNode);
1589
+ if (_result === null) {
1590
+ _result = {};
1591
+ }
1592
+ if (keyTag === "tag:yaml.org,2002:merge") {
1593
+ if (Array.isArray(valueNode)) {
1594
+ for (let index = 0, quantity = valueNode.length; index < quantity; index += 1) {
1595
+ mergeMappings(state, _result, valueNode[index], overridableKeys);
1596
+ }
1597
+ } else {
1598
+ mergeMappings(state, _result, valueNode, overridableKeys);
1599
+ }
1600
+ } else {
1601
+ if (!state.json && !_hasOwnProperty.call(overridableKeys, keyNode) && _hasOwnProperty.call(_result, keyNode)) {
1602
+ state.line = startLine || state.line;
1603
+ state.lineStart = startLineStart || state.lineStart;
1604
+ state.position = startPos || state.position;
1605
+ throwError(state, "duplicated mapping key");
1606
+ }
1607
+ setProperty(_result, keyNode, valueNode);
1608
+ delete overridableKeys[keyNode];
1609
+ }
1610
+ return _result;
1611
+ }
1612
+ function readLineBreak(state) {
1613
+ const ch = state.input.charCodeAt(state.position);
1614
+ if (ch === 10) {
1615
+ state.position++;
1616
+ } else if (ch === 13) {
1617
+ state.position++;
1618
+ if (state.input.charCodeAt(state.position) === 10) {
1619
+ state.position++;
1620
+ }
1621
+ } else {
1622
+ throwError(state, "a line break is expected");
1623
+ }
1624
+ state.line += 1;
1625
+ state.lineStart = state.position;
1626
+ state.firstTabInLine = -1;
1627
+ }
1628
+ function skipSeparationSpace(state, allowComments, checkIndent) {
1629
+ let lineBreaks = 0;
1630
+ let ch = state.input.charCodeAt(state.position);
1631
+ while (ch !== 0) {
1632
+ while (isWhiteSpace(ch)) {
1633
+ if (ch === 9 && state.firstTabInLine === -1) {
1634
+ state.firstTabInLine = state.position;
1635
+ }
1636
+ ch = state.input.charCodeAt(++state.position);
1637
+ }
1638
+ if (allowComments && ch === 35) {
1639
+ do {
1640
+ ch = state.input.charCodeAt(++state.position);
1641
+ } while (ch !== 10 && ch !== 13 && ch !== 0);
1642
+ }
1643
+ if (isEol(ch)) {
1644
+ readLineBreak(state);
1645
+ ch = state.input.charCodeAt(state.position);
1646
+ lineBreaks++;
1647
+ state.lineIndent = 0;
1648
+ while (ch === 32) {
1649
+ state.lineIndent++;
1650
+ ch = state.input.charCodeAt(++state.position);
1651
+ }
1652
+ } else {
1653
+ break;
1654
+ }
1655
+ }
1656
+ if (checkIndent !== -1 && lineBreaks !== 0 && state.lineIndent < checkIndent) {
1657
+ throwWarning(state, "deficient indentation");
1658
+ }
1659
+ return lineBreaks;
1660
+ }
1661
+ function testDocumentSeparator(state) {
1662
+ let _position = state.position;
1663
+ let ch = state.input.charCodeAt(_position);
1664
+ if ((ch === 45 || ch === 46) && ch === state.input.charCodeAt(_position + 1) && ch === state.input.charCodeAt(_position + 2)) {
1665
+ _position += 3;
1666
+ ch = state.input.charCodeAt(_position);
1667
+ if (ch === 0 || isWsOrEol(ch)) {
1668
+ return true;
1669
+ }
1670
+ }
1671
+ return false;
1672
+ }
1673
+ function writeFoldedLines(state, count) {
1674
+ if (count === 1) {
1675
+ state.result += " ";
1676
+ } else if (count > 1) {
1677
+ state.result += common2.repeat("\n", count - 1);
1678
+ }
1679
+ }
1680
+ function readPlainScalar(state, nodeIndent, withinFlowCollection) {
1681
+ let captureStart;
1682
+ let captureEnd;
1683
+ let hasPendingContent;
1684
+ let _line;
1685
+ let _lineStart;
1686
+ let _lineIndent;
1687
+ const _kind = state.kind;
1688
+ const _result = state.result;
1689
+ let ch = state.input.charCodeAt(state.position);
1690
+ if (isWsOrEol(ch) || isFlowIndicator(ch) || ch === 35 || ch === 38 || ch === 42 || ch === 33 || ch === 124 || ch === 62 || ch === 39 || ch === 34 || ch === 37 || ch === 64 || ch === 96) {
1691
+ return false;
1692
+ }
1693
+ if (ch === 63 || ch === 45) {
1694
+ const following = state.input.charCodeAt(state.position + 1);
1695
+ if (isWsOrEol(following) || withinFlowCollection && isFlowIndicator(following)) {
1696
+ return false;
1697
+ }
1698
+ }
1699
+ state.kind = "scalar";
1700
+ state.result = "";
1701
+ captureStart = captureEnd = state.position;
1702
+ hasPendingContent = false;
1703
+ while (ch !== 0) {
1704
+ if (ch === 58) {
1705
+ const following = state.input.charCodeAt(state.position + 1);
1706
+ if (isWsOrEol(following) || withinFlowCollection && isFlowIndicator(following)) {
1707
+ break;
1708
+ }
1709
+ } else if (ch === 35) {
1710
+ const preceding = state.input.charCodeAt(state.position - 1);
1711
+ if (isWsOrEol(preceding)) {
1712
+ break;
1713
+ }
1714
+ } else if (state.position === state.lineStart && testDocumentSeparator(state) || withinFlowCollection && isFlowIndicator(ch)) {
1715
+ break;
1716
+ } else if (isEol(ch)) {
1717
+ _line = state.line;
1718
+ _lineStart = state.lineStart;
1719
+ _lineIndent = state.lineIndent;
1720
+ skipSeparationSpace(state, false, -1);
1721
+ if (state.lineIndent >= nodeIndent) {
1722
+ hasPendingContent = true;
1723
+ ch = state.input.charCodeAt(state.position);
1724
+ continue;
1725
+ } else {
1726
+ state.position = captureEnd;
1727
+ state.line = _line;
1728
+ state.lineStart = _lineStart;
1729
+ state.lineIndent = _lineIndent;
1730
+ break;
1731
+ }
1732
+ }
1733
+ if (hasPendingContent) {
1734
+ captureSegment(state, captureStart, captureEnd, false);
1735
+ writeFoldedLines(state, state.line - _line);
1736
+ captureStart = captureEnd = state.position;
1737
+ hasPendingContent = false;
1738
+ }
1739
+ if (!isWhiteSpace(ch)) {
1740
+ captureEnd = state.position + 1;
1741
+ }
1742
+ ch = state.input.charCodeAt(++state.position);
1743
+ }
1744
+ captureSegment(state, captureStart, captureEnd, false);
1745
+ if (state.result) {
1746
+ return true;
1747
+ }
1748
+ state.kind = _kind;
1749
+ state.result = _result;
1750
+ return false;
1751
+ }
1752
+ function readSingleQuotedScalar(state, nodeIndent) {
1753
+ let captureStart;
1754
+ let captureEnd;
1755
+ let ch = state.input.charCodeAt(state.position);
1756
+ if (ch !== 39) {
1757
+ return false;
1758
+ }
1759
+ state.kind = "scalar";
1760
+ state.result = "";
1761
+ state.position++;
1762
+ captureStart = captureEnd = state.position;
1763
+ while ((ch = state.input.charCodeAt(state.position)) !== 0) {
1764
+ if (ch === 39) {
1765
+ captureSegment(state, captureStart, state.position, true);
1766
+ ch = state.input.charCodeAt(++state.position);
1767
+ if (ch === 39) {
1768
+ captureStart = state.position;
1769
+ state.position++;
1770
+ captureEnd = state.position;
1771
+ } else {
1772
+ return true;
1773
+ }
1774
+ } else if (isEol(ch)) {
1775
+ captureSegment(state, captureStart, captureEnd, true);
1776
+ writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent));
1777
+ captureStart = captureEnd = state.position;
1778
+ } else if (state.position === state.lineStart && testDocumentSeparator(state)) {
1779
+ throwError(state, "unexpected end of the document within a single quoted scalar");
1780
+ } else {
1781
+ state.position++;
1782
+ if (!isWhiteSpace(ch)) {
1783
+ captureEnd = state.position;
1784
+ }
1785
+ }
1786
+ }
1787
+ throwError(state, "unexpected end of the stream within a single quoted scalar");
1788
+ }
1789
+ function readDoubleQuotedScalar(state, nodeIndent) {
1790
+ let captureStart;
1791
+ let captureEnd;
1792
+ let tmp;
1793
+ let ch = state.input.charCodeAt(state.position);
1794
+ if (ch !== 34) {
1795
+ return false;
1796
+ }
1797
+ state.kind = "scalar";
1798
+ state.result = "";
1799
+ state.position++;
1800
+ captureStart = captureEnd = state.position;
1801
+ while ((ch = state.input.charCodeAt(state.position)) !== 0) {
1802
+ if (ch === 34) {
1803
+ captureSegment(state, captureStart, state.position, true);
1804
+ state.position++;
1805
+ return true;
1806
+ } else if (ch === 92) {
1807
+ captureSegment(state, captureStart, state.position, true);
1808
+ ch = state.input.charCodeAt(++state.position);
1809
+ if (isEol(ch)) {
1810
+ skipSeparationSpace(state, false, nodeIndent);
1811
+ } else if (ch < 256 && simpleEscapeCheck[ch]) {
1812
+ state.result += simpleEscapeMap[ch];
1813
+ state.position++;
1814
+ } else if ((tmp = escapedHexLen(ch)) > 0) {
1815
+ let hexLength = tmp;
1816
+ let hexResult = 0;
1817
+ for (; hexLength > 0; hexLength--) {
1818
+ ch = state.input.charCodeAt(++state.position);
1819
+ if ((tmp = fromHexCode(ch)) >= 0) {
1820
+ hexResult = (hexResult << 4) + tmp;
1821
+ } else {
1822
+ throwError(state, "expected hexadecimal character");
1823
+ }
1824
+ }
1825
+ state.result += charFromCodepoint(hexResult);
1826
+ state.position++;
1827
+ } else {
1828
+ throwError(state, "unknown escape sequence");
1829
+ }
1830
+ captureStart = captureEnd = state.position;
1831
+ } else if (isEol(ch)) {
1832
+ captureSegment(state, captureStart, captureEnd, true);
1833
+ writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent));
1834
+ captureStart = captureEnd = state.position;
1835
+ } else if (state.position === state.lineStart && testDocumentSeparator(state)) {
1836
+ throwError(state, "unexpected end of the document within a double quoted scalar");
1837
+ } else {
1838
+ state.position++;
1839
+ if (!isWhiteSpace(ch)) {
1840
+ captureEnd = state.position;
1841
+ }
1842
+ }
1843
+ }
1844
+ throwError(state, "unexpected end of the stream within a double quoted scalar");
1845
+ }
1846
+ function readFlowCollection(state, nodeIndent) {
1847
+ let readNext = true;
1848
+ let _line;
1849
+ let _lineStart;
1850
+ let _pos;
1851
+ const _tag = state.tag;
1852
+ let _result;
1853
+ const _anchor = state.anchor;
1854
+ let terminator;
1855
+ let isPair;
1856
+ let isExplicitPair;
1857
+ let isMapping;
1858
+ const overridableKeys = /* @__PURE__ */ Object.create(null);
1859
+ let keyNode;
1860
+ let keyTag;
1861
+ let valueNode;
1862
+ let ch = state.input.charCodeAt(state.position);
1863
+ if (ch === 91) {
1864
+ terminator = 93;
1865
+ isMapping = false;
1866
+ _result = [];
1867
+ } else if (ch === 123) {
1868
+ terminator = 125;
1869
+ isMapping = true;
1870
+ _result = {};
1871
+ } else {
1872
+ return false;
1873
+ }
1874
+ if (state.anchor !== null) {
1875
+ storeAnchor(state, state.anchor, _result);
1876
+ }
1877
+ ch = state.input.charCodeAt(++state.position);
1878
+ while (ch !== 0) {
1879
+ skipSeparationSpace(state, true, nodeIndent);
1880
+ ch = state.input.charCodeAt(state.position);
1881
+ if (ch === terminator) {
1882
+ state.position++;
1883
+ state.tag = _tag;
1884
+ state.anchor = _anchor;
1885
+ state.kind = isMapping ? "mapping" : "sequence";
1886
+ state.result = _result;
1887
+ return true;
1888
+ } else if (!readNext) {
1889
+ throwError(state, "missed comma between flow collection entries");
1890
+ } else if (ch === 44) {
1891
+ throwError(state, "expected the node content, but found ','");
1892
+ }
1893
+ keyTag = keyNode = valueNode = null;
1894
+ isPair = isExplicitPair = false;
1895
+ if (ch === 63) {
1896
+ const following = state.input.charCodeAt(state.position + 1);
1897
+ if (isWsOrEol(following)) {
1898
+ isPair = isExplicitPair = true;
1899
+ state.position++;
1900
+ skipSeparationSpace(state, true, nodeIndent);
1901
+ }
1902
+ }
1903
+ _line = state.line;
1904
+ _lineStart = state.lineStart;
1905
+ _pos = state.position;
1906
+ composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true);
1907
+ keyTag = state.tag;
1908
+ keyNode = state.result;
1909
+ skipSeparationSpace(state, true, nodeIndent);
1910
+ ch = state.input.charCodeAt(state.position);
1911
+ if ((isExplicitPair || state.line === _line) && ch === 58) {
1912
+ isPair = true;
1913
+ ch = state.input.charCodeAt(++state.position);
1914
+ skipSeparationSpace(state, true, nodeIndent);
1915
+ composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true);
1916
+ valueNode = state.result;
1917
+ }
1918
+ if (isMapping) {
1919
+ storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, _line, _lineStart, _pos);
1920
+ } else if (isPair) {
1921
+ _result.push(storeMappingPair(state, null, overridableKeys, keyTag, keyNode, valueNode, _line, _lineStart, _pos));
1922
+ } else {
1923
+ _result.push(keyNode);
1924
+ }
1925
+ skipSeparationSpace(state, true, nodeIndent);
1926
+ ch = state.input.charCodeAt(state.position);
1927
+ if (ch === 44) {
1928
+ readNext = true;
1929
+ ch = state.input.charCodeAt(++state.position);
1930
+ } else {
1931
+ readNext = false;
1932
+ }
1933
+ }
1934
+ throwError(state, "unexpected end of the stream within a flow collection");
1935
+ }
1936
+ function readBlockScalar(state, nodeIndent) {
1937
+ let folding;
1938
+ let chomping = CHOMPING_CLIP;
1939
+ let didReadContent = false;
1940
+ let detectedIndent = false;
1941
+ let textIndent = nodeIndent;
1942
+ let emptyLines = 0;
1943
+ let atMoreIndented = false;
1944
+ let tmp;
1945
+ let ch = state.input.charCodeAt(state.position);
1946
+ if (ch === 124) {
1947
+ folding = false;
1948
+ } else if (ch === 62) {
1949
+ folding = true;
1950
+ } else {
1951
+ return false;
1952
+ }
1953
+ state.kind = "scalar";
1954
+ state.result = "";
1955
+ while (ch !== 0) {
1956
+ ch = state.input.charCodeAt(++state.position);
1957
+ if (ch === 43 || ch === 45) {
1958
+ if (CHOMPING_CLIP === chomping) {
1959
+ chomping = ch === 43 ? CHOMPING_KEEP : CHOMPING_STRIP;
1960
+ } else {
1961
+ throwError(state, "repeat of a chomping mode identifier");
1962
+ }
1963
+ } else if ((tmp = fromDecimalCode(ch)) >= 0) {
1964
+ if (tmp === 0) {
1965
+ throwError(state, "bad explicit indentation width of a block scalar; it cannot be less than one");
1966
+ } else if (!detectedIndent) {
1967
+ textIndent = nodeIndent + tmp - 1;
1968
+ detectedIndent = true;
1969
+ } else {
1970
+ throwError(state, "repeat of an indentation width identifier");
1971
+ }
1972
+ } else {
1973
+ break;
1974
+ }
1975
+ }
1976
+ if (isWhiteSpace(ch)) {
1977
+ do {
1978
+ ch = state.input.charCodeAt(++state.position);
1979
+ } while (isWhiteSpace(ch));
1980
+ if (ch === 35) {
1981
+ do {
1982
+ ch = state.input.charCodeAt(++state.position);
1983
+ } while (!isEol(ch) && ch !== 0);
1984
+ }
1985
+ }
1986
+ while (ch !== 0) {
1987
+ readLineBreak(state);
1988
+ state.lineIndent = 0;
1989
+ ch = state.input.charCodeAt(state.position);
1990
+ while ((!detectedIndent || state.lineIndent < textIndent) && ch === 32) {
1991
+ state.lineIndent++;
1992
+ ch = state.input.charCodeAt(++state.position);
1993
+ }
1994
+ if (!detectedIndent && state.lineIndent > textIndent) {
1995
+ textIndent = state.lineIndent;
1996
+ }
1997
+ if (isEol(ch)) {
1998
+ emptyLines++;
1999
+ continue;
2000
+ }
2001
+ if (!detectedIndent && textIndent === 0) {
2002
+ throwError(state, "missing indentation for block scalar");
2003
+ }
2004
+ if (state.lineIndent < textIndent) {
2005
+ if (chomping === CHOMPING_KEEP) {
2006
+ state.result += common2.repeat("\n", didReadContent ? 1 + emptyLines : emptyLines);
2007
+ } else if (chomping === CHOMPING_CLIP) {
2008
+ if (didReadContent) {
2009
+ state.result += "\n";
2010
+ }
2011
+ }
2012
+ break;
2013
+ }
2014
+ if (folding) {
2015
+ if (isWhiteSpace(ch)) {
2016
+ atMoreIndented = true;
2017
+ state.result += common2.repeat("\n", didReadContent ? 1 + emptyLines : emptyLines);
2018
+ } else if (atMoreIndented) {
2019
+ atMoreIndented = false;
2020
+ state.result += common2.repeat("\n", emptyLines + 1);
2021
+ } else if (emptyLines === 0) {
2022
+ if (didReadContent) {
2023
+ state.result += " ";
2024
+ }
2025
+ } else {
2026
+ state.result += common2.repeat("\n", emptyLines);
2027
+ }
2028
+ } else {
2029
+ state.result += common2.repeat("\n", didReadContent ? 1 + emptyLines : emptyLines);
2030
+ }
2031
+ didReadContent = true;
2032
+ detectedIndent = true;
2033
+ emptyLines = 0;
2034
+ const captureStart = state.position;
2035
+ while (!isEol(ch) && ch !== 0) {
2036
+ ch = state.input.charCodeAt(++state.position);
2037
+ }
2038
+ captureSegment(state, captureStart, state.position, false);
2039
+ }
2040
+ return true;
2041
+ }
2042
+ function readBlockSequence(state, nodeIndent) {
2043
+ const _tag = state.tag;
2044
+ const _anchor = state.anchor;
2045
+ const _result = [];
2046
+ let detected = false;
2047
+ if (state.firstTabInLine !== -1) return false;
2048
+ if (state.anchor !== null) {
2049
+ storeAnchor(state, state.anchor, _result);
2050
+ }
2051
+ let ch = state.input.charCodeAt(state.position);
2052
+ while (ch !== 0) {
2053
+ if (state.firstTabInLine !== -1) {
2054
+ state.position = state.firstTabInLine;
2055
+ throwError(state, "tab characters must not be used in indentation");
2056
+ }
2057
+ if (ch !== 45) {
2058
+ break;
2059
+ }
2060
+ const following = state.input.charCodeAt(state.position + 1);
2061
+ if (!isWsOrEol(following)) {
2062
+ break;
2063
+ }
2064
+ detected = true;
2065
+ state.position++;
2066
+ if (skipSeparationSpace(state, true, -1)) {
2067
+ if (state.lineIndent <= nodeIndent) {
2068
+ _result.push(null);
2069
+ ch = state.input.charCodeAt(state.position);
2070
+ continue;
2071
+ }
2072
+ }
2073
+ const _line = state.line;
2074
+ composeNode(state, nodeIndent, CONTEXT_BLOCK_IN, false, true);
2075
+ _result.push(state.result);
2076
+ skipSeparationSpace(state, true, -1);
2077
+ ch = state.input.charCodeAt(state.position);
2078
+ if ((state.line === _line || state.lineIndent > nodeIndent) && ch !== 0) {
2079
+ throwError(state, "bad indentation of a sequence entry");
2080
+ } else if (state.lineIndent < nodeIndent) {
2081
+ break;
2082
+ }
2083
+ }
2084
+ if (detected) {
2085
+ state.tag = _tag;
2086
+ state.anchor = _anchor;
2087
+ state.kind = "sequence";
2088
+ state.result = _result;
2089
+ return true;
2090
+ }
2091
+ return false;
2092
+ }
2093
+ function readBlockMapping(state, nodeIndent, flowIndent) {
2094
+ let allowCompact;
2095
+ let _keyLine;
2096
+ let _keyLineStart;
2097
+ let _keyPos;
2098
+ const _tag = state.tag;
2099
+ const _anchor = state.anchor;
2100
+ const _result = {};
2101
+ const overridableKeys = /* @__PURE__ */ Object.create(null);
2102
+ let keyTag = null;
2103
+ let keyNode = null;
2104
+ let valueNode = null;
2105
+ let atExplicitKey = false;
2106
+ let detected = false;
2107
+ if (state.firstTabInLine !== -1) return false;
2108
+ if (state.anchor !== null) {
2109
+ storeAnchor(state, state.anchor, _result);
2110
+ }
2111
+ let ch = state.input.charCodeAt(state.position);
2112
+ while (ch !== 0) {
2113
+ if (!atExplicitKey && state.firstTabInLine !== -1) {
2114
+ state.position = state.firstTabInLine;
2115
+ throwError(state, "tab characters must not be used in indentation");
2116
+ }
2117
+ const following = state.input.charCodeAt(state.position + 1);
2118
+ const _line = state.line;
2119
+ if ((ch === 63 || ch === 58) && isWsOrEol(following)) {
2120
+ if (ch === 63) {
2121
+ if (atExplicitKey) {
2122
+ storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos);
2123
+ keyTag = keyNode = valueNode = null;
2124
+ }
2125
+ detected = true;
2126
+ atExplicitKey = true;
2127
+ allowCompact = true;
2128
+ } else if (atExplicitKey) {
2129
+ atExplicitKey = false;
2130
+ allowCompact = true;
2131
+ } else {
2132
+ throwError(state, "incomplete explicit mapping pair; a key node is missed; or followed by a non-tabulated empty line");
2133
+ }
2134
+ state.position += 1;
2135
+ ch = following;
2136
+ } else {
2137
+ _keyLine = state.line;
2138
+ _keyLineStart = state.lineStart;
2139
+ _keyPos = state.position;
2140
+ if (!composeNode(state, flowIndent, CONTEXT_FLOW_OUT, false, true)) {
2141
+ break;
2142
+ }
2143
+ if (state.line === _line) {
2144
+ ch = state.input.charCodeAt(state.position);
2145
+ while (isWhiteSpace(ch)) {
2146
+ ch = state.input.charCodeAt(++state.position);
2147
+ }
2148
+ if (ch === 58) {
2149
+ ch = state.input.charCodeAt(++state.position);
2150
+ if (!isWsOrEol(ch)) {
2151
+ throwError(state, "a whitespace character is expected after the key-value separator within a block mapping");
2152
+ }
2153
+ if (atExplicitKey) {
2154
+ storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos);
2155
+ keyTag = keyNode = valueNode = null;
2156
+ }
2157
+ detected = true;
2158
+ atExplicitKey = false;
2159
+ allowCompact = false;
2160
+ keyTag = state.tag;
2161
+ keyNode = state.result;
2162
+ } else if (detected) {
2163
+ throwError(state, "can not read an implicit mapping pair; a colon is missed");
2164
+ } else {
2165
+ state.tag = _tag;
2166
+ state.anchor = _anchor;
2167
+ return true;
2168
+ }
2169
+ } else if (detected) {
2170
+ throwError(state, "can not read a block mapping entry; a multiline key may not be an implicit key");
2171
+ } else {
2172
+ state.tag = _tag;
2173
+ state.anchor = _anchor;
2174
+ return true;
2175
+ }
2176
+ }
2177
+ if (state.line === _line || state.lineIndent > nodeIndent) {
2178
+ if (atExplicitKey) {
2179
+ _keyLine = state.line;
2180
+ _keyLineStart = state.lineStart;
2181
+ _keyPos = state.position;
2182
+ }
2183
+ if (composeNode(state, nodeIndent, CONTEXT_BLOCK_OUT, true, allowCompact)) {
2184
+ if (atExplicitKey) {
2185
+ keyNode = state.result;
2186
+ } else {
2187
+ valueNode = state.result;
2188
+ }
2189
+ }
2190
+ if (!atExplicitKey) {
2191
+ storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, _keyLine, _keyLineStart, _keyPos);
2192
+ keyTag = keyNode = valueNode = null;
2193
+ }
2194
+ skipSeparationSpace(state, true, -1);
2195
+ ch = state.input.charCodeAt(state.position);
2196
+ }
2197
+ if ((state.line === _line || state.lineIndent > nodeIndent) && ch !== 0) {
2198
+ throwError(state, "bad indentation of a mapping entry");
2199
+ } else if (state.lineIndent < nodeIndent) {
2200
+ break;
2201
+ }
2202
+ }
2203
+ if (atExplicitKey) {
2204
+ storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos);
2205
+ }
2206
+ if (detected) {
2207
+ state.tag = _tag;
2208
+ state.anchor = _anchor;
2209
+ state.kind = "mapping";
2210
+ state.result = _result;
2211
+ }
2212
+ return detected;
2213
+ }
2214
+ function readTagProperty(state) {
2215
+ let isVerbatim = false;
2216
+ let isNamed = false;
2217
+ let tagHandle;
2218
+ let tagName;
2219
+ let ch = state.input.charCodeAt(state.position);
2220
+ if (ch !== 33) return false;
2221
+ if (state.tag !== null) {
2222
+ throwError(state, "duplication of a tag property");
2223
+ }
2224
+ ch = state.input.charCodeAt(++state.position);
2225
+ if (ch === 60) {
2226
+ isVerbatim = true;
2227
+ ch = state.input.charCodeAt(++state.position);
2228
+ } else if (ch === 33) {
2229
+ isNamed = true;
2230
+ tagHandle = "!!";
2231
+ ch = state.input.charCodeAt(++state.position);
2232
+ } else {
2233
+ tagHandle = "!";
2234
+ }
2235
+ let _position = state.position;
2236
+ if (isVerbatim) {
2237
+ do {
2238
+ ch = state.input.charCodeAt(++state.position);
2239
+ } while (ch !== 0 && ch !== 62);
2240
+ if (state.position < state.length) {
2241
+ tagName = state.input.slice(_position, state.position);
2242
+ ch = state.input.charCodeAt(++state.position);
2243
+ } else {
2244
+ throwError(state, "unexpected end of the stream within a verbatim tag");
2245
+ }
2246
+ } else {
2247
+ while (ch !== 0 && !isWsOrEol(ch)) {
2248
+ if (ch === 33) {
2249
+ if (!isNamed) {
2250
+ tagHandle = state.input.slice(_position - 1, state.position + 1);
2251
+ if (!PATTERN_TAG_HANDLE.test(tagHandle)) {
2252
+ throwError(state, "named tag handle cannot contain such characters");
2253
+ }
2254
+ isNamed = true;
2255
+ _position = state.position + 1;
2256
+ } else {
2257
+ throwError(state, "tag suffix cannot contain exclamation marks");
2258
+ }
2259
+ }
2260
+ ch = state.input.charCodeAt(++state.position);
2261
+ }
2262
+ tagName = state.input.slice(_position, state.position);
2263
+ if (PATTERN_FLOW_INDICATORS.test(tagName)) {
2264
+ throwError(state, "tag suffix cannot contain flow indicator characters");
2265
+ }
2266
+ }
2267
+ if (tagName && !PATTERN_TAG_URI.test(tagName)) {
2268
+ throwError(state, "tag name cannot contain such characters: " + tagName);
2269
+ }
2270
+ try {
2271
+ tagName = decodeURIComponent(tagName);
2272
+ } catch (err) {
2273
+ throwError(state, "tag name is malformed: " + tagName);
2274
+ }
2275
+ if (isVerbatim) {
2276
+ state.tag = tagName;
2277
+ } else if (_hasOwnProperty.call(state.tagMap, tagHandle)) {
2278
+ state.tag = state.tagMap[tagHandle] + tagName;
2279
+ } else if (tagHandle === "!") {
2280
+ state.tag = "!" + tagName;
2281
+ } else if (tagHandle === "!!") {
2282
+ state.tag = "tag:yaml.org,2002:" + tagName;
2283
+ } else {
2284
+ throwError(state, 'undeclared tag handle "' + tagHandle + '"');
2285
+ }
2286
+ return true;
2287
+ }
2288
+ function readAnchorProperty(state) {
2289
+ let ch = state.input.charCodeAt(state.position);
2290
+ if (ch !== 38) return false;
2291
+ if (state.anchor !== null) {
2292
+ throwError(state, "duplication of an anchor property");
2293
+ }
2294
+ ch = state.input.charCodeAt(++state.position);
2295
+ const _position = state.position;
2296
+ while (ch !== 0 && !isWsOrEol(ch) && !isFlowIndicator(ch)) {
2297
+ ch = state.input.charCodeAt(++state.position);
2298
+ }
2299
+ if (state.position === _position) {
2300
+ throwError(state, "name of an anchor node must contain at least one character");
2301
+ }
2302
+ state.anchor = state.input.slice(_position, state.position);
2303
+ return true;
2304
+ }
2305
+ function readAlias(state) {
2306
+ let ch = state.input.charCodeAt(state.position);
2307
+ if (ch !== 42) return false;
2308
+ ch = state.input.charCodeAt(++state.position);
2309
+ const _position = state.position;
2310
+ while (ch !== 0 && !isWsOrEol(ch) && !isFlowIndicator(ch)) {
2311
+ ch = state.input.charCodeAt(++state.position);
2312
+ }
2313
+ if (state.position === _position) {
2314
+ throwError(state, "name of an alias node must contain at least one character");
2315
+ }
2316
+ const alias = state.input.slice(_position, state.position);
2317
+ if (!_hasOwnProperty.call(state.anchorMap, alias)) {
2318
+ throwError(state, 'unidentified alias "' + alias + '"');
2319
+ }
2320
+ state.result = state.anchorMap[alias];
2321
+ skipSeparationSpace(state, true, -1);
2322
+ return true;
2323
+ }
2324
+ function tryReadBlockMappingFromProperty(state, propertyStart, nodeIndent, flowIndent) {
2325
+ const fallbackState = snapshotState(state);
2326
+ beginAnchorTransaction(state);
2327
+ restoreState(state, propertyStart);
2328
+ state.tag = null;
2329
+ state.anchor = null;
2330
+ state.kind = null;
2331
+ state.result = null;
2332
+ if (readBlockMapping(state, nodeIndent, flowIndent) && state.kind === "mapping") {
2333
+ commitAnchorTransaction(state);
2334
+ return true;
2335
+ }
2336
+ rollbackAnchorTransaction(state);
2337
+ restoreState(state, fallbackState);
2338
+ return false;
2339
+ }
2340
+ function composeNode(state, parentIndent, nodeContext, allowToSeek, allowCompact) {
2341
+ let allowBlockScalars;
2342
+ let allowBlockCollections;
2343
+ let indentStatus = 1;
2344
+ let atNewLine = false;
2345
+ let hasContent = false;
2346
+ let propertyStart = null;
2347
+ let type2;
2348
+ let flowIndent;
2349
+ let blockIndent;
2350
+ if (state.depth >= state.maxDepth) {
2351
+ throwError(state, "nesting exceeded maxDepth (" + state.maxDepth + ")");
2352
+ }
2353
+ state.depth += 1;
2354
+ if (state.listener !== null) {
2355
+ state.listener("open", state);
2356
+ }
2357
+ state.tag = null;
2358
+ state.anchor = null;
2359
+ state.kind = null;
2360
+ state.result = null;
2361
+ const allowBlockStyles = allowBlockScalars = allowBlockCollections = CONTEXT_BLOCK_OUT === nodeContext || CONTEXT_BLOCK_IN === nodeContext;
2362
+ if (allowToSeek) {
2363
+ if (skipSeparationSpace(state, true, -1)) {
2364
+ atNewLine = true;
2365
+ if (state.lineIndent > parentIndent) {
2366
+ indentStatus = 1;
2367
+ } else if (state.lineIndent === parentIndent) {
2368
+ indentStatus = 0;
2369
+ } else if (state.lineIndent < parentIndent) {
2370
+ indentStatus = -1;
2371
+ }
2372
+ }
2373
+ }
2374
+ if (indentStatus === 1) {
2375
+ while (true) {
2376
+ const ch = state.input.charCodeAt(state.position);
2377
+ const propertyState = snapshotState(state);
2378
+ if (atNewLine && (ch === 33 && state.tag !== null || ch === 38 && state.anchor !== null)) {
2379
+ break;
2380
+ }
2381
+ if (!readTagProperty(state) && !readAnchorProperty(state)) {
2382
+ break;
2383
+ }
2384
+ if (propertyStart === null) {
2385
+ propertyStart = propertyState;
2386
+ }
2387
+ if (skipSeparationSpace(state, true, -1)) {
2388
+ atNewLine = true;
2389
+ allowBlockCollections = allowBlockStyles;
2390
+ if (state.lineIndent > parentIndent) {
2391
+ indentStatus = 1;
2392
+ } else if (state.lineIndent === parentIndent) {
2393
+ indentStatus = 0;
2394
+ } else if (state.lineIndent < parentIndent) {
2395
+ indentStatus = -1;
2396
+ }
2397
+ } else {
2398
+ allowBlockCollections = false;
2399
+ }
2400
+ }
2401
+ }
2402
+ if (allowBlockCollections) {
2403
+ allowBlockCollections = atNewLine || allowCompact;
2404
+ }
2405
+ if (indentStatus === 1 || CONTEXT_BLOCK_OUT === nodeContext) {
2406
+ if (CONTEXT_FLOW_IN === nodeContext || CONTEXT_FLOW_OUT === nodeContext) {
2407
+ flowIndent = parentIndent;
2408
+ } else {
2409
+ flowIndent = parentIndent + 1;
2410
+ }
2411
+ blockIndent = state.position - state.lineStart;
2412
+ if (indentStatus === 1) {
2413
+ if (allowBlockCollections && (readBlockSequence(state, blockIndent) || readBlockMapping(state, blockIndent, flowIndent)) || readFlowCollection(state, flowIndent)) {
2414
+ hasContent = true;
2415
+ } else {
2416
+ const ch = state.input.charCodeAt(state.position);
2417
+ if (propertyStart !== null && allowBlockStyles && !allowBlockCollections && ch !== 124 && ch !== 62 && tryReadBlockMappingFromProperty(
2418
+ state,
2419
+ propertyStart,
2420
+ propertyStart.position - propertyStart.lineStart,
2421
+ flowIndent
2422
+ )) {
2423
+ hasContent = true;
2424
+ } else if (allowBlockScalars && readBlockScalar(state, flowIndent) || readSingleQuotedScalar(state, flowIndent) || readDoubleQuotedScalar(state, flowIndent)) {
2425
+ hasContent = true;
2426
+ } else if (readAlias(state)) {
2427
+ hasContent = true;
2428
+ if (state.tag !== null || state.anchor !== null) {
2429
+ throwError(state, "alias node should not have any properties");
2430
+ }
2431
+ } else if (readPlainScalar(state, flowIndent, CONTEXT_FLOW_IN === nodeContext)) {
2432
+ hasContent = true;
2433
+ if (state.tag === null) {
2434
+ state.tag = "?";
2435
+ }
2436
+ }
2437
+ if (state.anchor !== null) {
2438
+ storeAnchor(state, state.anchor, state.result);
2439
+ }
2440
+ }
2441
+ } else if (indentStatus === 0) {
2442
+ hasContent = allowBlockCollections && readBlockSequence(state, blockIndent);
2443
+ }
2444
+ }
2445
+ if (state.tag === null) {
2446
+ if (state.anchor !== null) {
2447
+ storeAnchor(state, state.anchor, state.result);
2448
+ }
2449
+ } else if (state.tag === "?") {
2450
+ if (state.result !== null && state.kind !== "scalar") {
2451
+ throwError(state, 'unacceptable node kind for !<?> tag; it should be "scalar", not "' + state.kind + '"');
2452
+ }
2453
+ for (let typeIndex = 0, typeQuantity = state.implicitTypes.length; typeIndex < typeQuantity; typeIndex += 1) {
2454
+ type2 = state.implicitTypes[typeIndex];
2455
+ if (type2.resolve(state.result)) {
2456
+ state.result = type2.construct(state.result);
2457
+ state.tag = type2.tag;
2458
+ if (state.anchor !== null) {
2459
+ storeAnchor(state, state.anchor, state.result);
2460
+ }
2461
+ break;
2462
+ }
2463
+ }
2464
+ } else if (state.tag !== "!") {
2465
+ if (_hasOwnProperty.call(state.typeMap[state.kind || "fallback"], state.tag)) {
2466
+ type2 = state.typeMap[state.kind || "fallback"][state.tag];
2467
+ } else {
2468
+ type2 = null;
2469
+ const typeList = state.typeMap.multi[state.kind || "fallback"];
2470
+ for (let typeIndex = 0, typeQuantity = typeList.length; typeIndex < typeQuantity; typeIndex += 1) {
2471
+ if (state.tag.slice(0, typeList[typeIndex].tag.length) === typeList[typeIndex].tag) {
2472
+ type2 = typeList[typeIndex];
2473
+ break;
2474
+ }
2475
+ }
2476
+ }
2477
+ if (!type2) {
2478
+ throwError(state, "unknown tag !<" + state.tag + ">");
2479
+ }
2480
+ if (state.result !== null && type2.kind !== state.kind) {
2481
+ throwError(state, "unacceptable node kind for !<" + state.tag + '> tag; it should be "' + type2.kind + '", not "' + state.kind + '"');
2482
+ }
2483
+ if (!type2.resolve(state.result, state.tag)) {
2484
+ throwError(state, "cannot resolve a node with !<" + state.tag + "> explicit tag");
2485
+ } else {
2486
+ state.result = type2.construct(state.result, state.tag);
2487
+ if (state.anchor !== null) {
2488
+ storeAnchor(state, state.anchor, state.result);
2489
+ }
2490
+ }
2491
+ }
2492
+ if (state.listener !== null) {
2493
+ state.listener("close", state);
2494
+ }
2495
+ state.depth -= 1;
2496
+ return state.tag !== null || state.anchor !== null || hasContent;
2497
+ }
2498
+ function readDocument(state) {
2499
+ const documentStart = state.position;
2500
+ let hasDirectives = false;
2501
+ let ch;
2502
+ state.version = null;
2503
+ state.checkLineBreaks = state.legacy;
2504
+ state.tagMap = /* @__PURE__ */ Object.create(null);
2505
+ state.anchorMap = /* @__PURE__ */ Object.create(null);
2506
+ while ((ch = state.input.charCodeAt(state.position)) !== 0) {
2507
+ skipSeparationSpace(state, true, -1);
2508
+ ch = state.input.charCodeAt(state.position);
2509
+ if (state.lineIndent > 0 || ch !== 37) {
2510
+ break;
2511
+ }
2512
+ hasDirectives = true;
2513
+ ch = state.input.charCodeAt(++state.position);
2514
+ let _position = state.position;
2515
+ while (ch !== 0 && !isWsOrEol(ch)) {
2516
+ ch = state.input.charCodeAt(++state.position);
2517
+ }
2518
+ const directiveName = state.input.slice(_position, state.position);
2519
+ const directiveArgs = [];
2520
+ if (directiveName.length < 1) {
2521
+ throwError(state, "directive name must not be less than one character in length");
2522
+ }
2523
+ while (ch !== 0) {
2524
+ while (isWhiteSpace(ch)) {
2525
+ ch = state.input.charCodeAt(++state.position);
2526
+ }
2527
+ if (ch === 35) {
2528
+ do {
2529
+ ch = state.input.charCodeAt(++state.position);
2530
+ } while (ch !== 0 && !isEol(ch));
2531
+ break;
2532
+ }
2533
+ if (isEol(ch)) break;
2534
+ _position = state.position;
2535
+ while (ch !== 0 && !isWsOrEol(ch)) {
2536
+ ch = state.input.charCodeAt(++state.position);
2537
+ }
2538
+ directiveArgs.push(state.input.slice(_position, state.position));
2539
+ }
2540
+ if (ch !== 0) readLineBreak(state);
2541
+ if (_hasOwnProperty.call(directiveHandlers, directiveName)) {
2542
+ directiveHandlers[directiveName](state, directiveName, directiveArgs);
2543
+ } else {
2544
+ throwWarning(state, 'unknown document directive "' + directiveName + '"');
2545
+ }
2546
+ }
2547
+ skipSeparationSpace(state, true, -1);
2548
+ if (state.lineIndent === 0 && state.input.charCodeAt(state.position) === 45 && state.input.charCodeAt(state.position + 1) === 45 && state.input.charCodeAt(state.position + 2) === 45) {
2549
+ state.position += 3;
2550
+ skipSeparationSpace(state, true, -1);
2551
+ } else if (hasDirectives) {
2552
+ throwError(state, "directives end mark is expected");
2553
+ }
2554
+ composeNode(state, state.lineIndent - 1, CONTEXT_BLOCK_OUT, false, true);
2555
+ skipSeparationSpace(state, true, -1);
2556
+ if (state.checkLineBreaks && PATTERN_NON_ASCII_LINE_BREAKS.test(state.input.slice(documentStart, state.position))) {
2557
+ throwWarning(state, "non-ASCII line breaks are interpreted as content");
2558
+ }
2559
+ state.documents.push(state.result);
2560
+ if (state.position === state.lineStart && testDocumentSeparator(state)) {
2561
+ if (state.input.charCodeAt(state.position) === 46) {
2562
+ state.position += 3;
2563
+ skipSeparationSpace(state, true, -1);
2564
+ }
2565
+ return;
2566
+ }
2567
+ if (state.position < state.length - 1) {
2568
+ throwError(state, "end of the stream or a document separator is expected");
2569
+ }
2570
+ }
2571
+ function loadDocuments(input, options) {
2572
+ input = String(input);
2573
+ options = options || {};
2574
+ if (input.length !== 0) {
2575
+ if (input.charCodeAt(input.length - 1) !== 10 && input.charCodeAt(input.length - 1) !== 13) {
2576
+ input += "\n";
2577
+ }
2578
+ if (input.charCodeAt(0) === 65279) {
2579
+ input = input.slice(1);
2580
+ }
2581
+ }
2582
+ const state = new State(input, options);
2583
+ const nullpos = input.indexOf("\0");
2584
+ if (nullpos !== -1) {
2585
+ state.position = nullpos;
2586
+ throwError(state, "null byte is not allowed in input");
2587
+ }
2588
+ state.input += "\0";
2589
+ while (state.input.charCodeAt(state.position) === 32) {
2590
+ state.lineIndent += 1;
2591
+ state.position += 1;
2592
+ }
2593
+ while (state.position < state.length - 1) {
2594
+ readDocument(state);
2595
+ }
2596
+ return state.documents;
2597
+ }
2598
+ function loadAll2(input, iterator, options) {
2599
+ if (iterator !== null && typeof iterator === "object" && typeof options === "undefined") {
2600
+ options = iterator;
2601
+ iterator = null;
2602
+ }
2603
+ const documents = loadDocuments(input, options);
2604
+ if (typeof iterator !== "function") {
2605
+ return documents;
2606
+ }
2607
+ for (let index = 0, length = documents.length; index < length; index += 1) {
2608
+ iterator(documents[index]);
2609
+ }
2610
+ }
2611
+ function load2(input, options) {
2612
+ const documents = loadDocuments(input, options);
2613
+ if (documents.length === 0) {
2614
+ return void 0;
2615
+ } else if (documents.length === 1) {
2616
+ return documents[0];
2617
+ }
2618
+ throw new YAMLException2("expected a single document in the stream, but found more");
2619
+ }
2620
+ loader.loadAll = loadAll2;
2621
+ loader.load = load2;
2622
+ return loader;
2623
+ }
2624
+ var dumper = {};
2625
+ var hasRequiredDumper;
2626
+ function requireDumper() {
2627
+ if (hasRequiredDumper) return dumper;
2628
+ hasRequiredDumper = 1;
2629
+ const common2 = requireCommon();
2630
+ const YAMLException2 = requireException();
2631
+ const DEFAULT_SCHEMA2 = require_default();
2632
+ const _toString = Object.prototype.toString;
2633
+ const _hasOwnProperty = Object.prototype.hasOwnProperty;
2634
+ const CHAR_BOM = 65279;
2635
+ const CHAR_TAB = 9;
2636
+ const CHAR_LINE_FEED = 10;
2637
+ const CHAR_CARRIAGE_RETURN = 13;
2638
+ const CHAR_SPACE = 32;
2639
+ const CHAR_EXCLAMATION = 33;
2640
+ const CHAR_DOUBLE_QUOTE = 34;
2641
+ const CHAR_SHARP = 35;
2642
+ const CHAR_PERCENT = 37;
2643
+ const CHAR_AMPERSAND = 38;
2644
+ const CHAR_SINGLE_QUOTE = 39;
2645
+ const CHAR_ASTERISK = 42;
2646
+ const CHAR_COMMA = 44;
2647
+ const CHAR_MINUS = 45;
2648
+ const CHAR_COLON = 58;
2649
+ const CHAR_EQUALS = 61;
2650
+ const CHAR_GREATER_THAN = 62;
2651
+ const CHAR_QUESTION = 63;
2652
+ const CHAR_COMMERCIAL_AT = 64;
2653
+ const CHAR_LEFT_SQUARE_BRACKET = 91;
2654
+ const CHAR_RIGHT_SQUARE_BRACKET = 93;
2655
+ const CHAR_GRAVE_ACCENT = 96;
2656
+ const CHAR_LEFT_CURLY_BRACKET = 123;
2657
+ const CHAR_VERTICAL_LINE = 124;
2658
+ const CHAR_RIGHT_CURLY_BRACKET = 125;
2659
+ const ESCAPE_SEQUENCES = {};
2660
+ ESCAPE_SEQUENCES[0] = "\\0";
2661
+ ESCAPE_SEQUENCES[7] = "\\a";
2662
+ ESCAPE_SEQUENCES[8] = "\\b";
2663
+ ESCAPE_SEQUENCES[9] = "\\t";
2664
+ ESCAPE_SEQUENCES[10] = "\\n";
2665
+ ESCAPE_SEQUENCES[11] = "\\v";
2666
+ ESCAPE_SEQUENCES[12] = "\\f";
2667
+ ESCAPE_SEQUENCES[13] = "\\r";
2668
+ ESCAPE_SEQUENCES[27] = "\\e";
2669
+ ESCAPE_SEQUENCES[34] = '\\"';
2670
+ ESCAPE_SEQUENCES[92] = "\\\\";
2671
+ ESCAPE_SEQUENCES[133] = "\\N";
2672
+ ESCAPE_SEQUENCES[160] = "\\_";
2673
+ ESCAPE_SEQUENCES[8232] = "\\L";
2674
+ ESCAPE_SEQUENCES[8233] = "\\P";
2675
+ const DEPRECATED_BOOLEANS_SYNTAX = [
2676
+ "y",
2677
+ "Y",
2678
+ "yes",
2679
+ "Yes",
2680
+ "YES",
2681
+ "on",
2682
+ "On",
2683
+ "ON",
2684
+ "n",
2685
+ "N",
2686
+ "no",
2687
+ "No",
2688
+ "NO",
2689
+ "off",
2690
+ "Off",
2691
+ "OFF"
2692
+ ];
2693
+ const DEPRECATED_BASE60_SYNTAX = /^[-+]?[0-9_]+(?::[0-9_]+)+(?:\.[0-9_]*)?$/;
2694
+ function compileStyleMap(schema2, map2) {
2695
+ if (map2 === null) return {};
2696
+ const result = {};
2697
+ const keys = Object.keys(map2);
2698
+ for (let index = 0, length = keys.length; index < length; index += 1) {
2699
+ let tag = keys[index];
2700
+ let style = String(map2[tag]);
2701
+ if (tag.slice(0, 2) === "!!") {
2702
+ tag = "tag:yaml.org,2002:" + tag.slice(2);
2703
+ }
2704
+ const type2 = schema2.compiledTypeMap["fallback"][tag];
2705
+ if (type2 && _hasOwnProperty.call(type2.styleAliases, style)) {
2706
+ style = type2.styleAliases[style];
2707
+ }
2708
+ result[tag] = style;
2709
+ }
2710
+ return result;
2711
+ }
2712
+ function encodeHex(character) {
2713
+ let handle;
2714
+ let length;
2715
+ const string = character.toString(16).toUpperCase();
2716
+ if (character <= 255) {
2717
+ handle = "x";
2718
+ length = 2;
2719
+ } else if (character <= 65535) {
2720
+ handle = "u";
2721
+ length = 4;
2722
+ } else if (character <= 4294967295) {
2723
+ handle = "U";
2724
+ length = 8;
2725
+ } else {
2726
+ throw new YAMLException2("code point within a string may not be greater than 0xFFFFFFFF");
2727
+ }
2728
+ return "\\" + handle + common2.repeat("0", length - string.length) + string;
2729
+ }
2730
+ const QUOTING_TYPE_SINGLE = 1;
2731
+ const QUOTING_TYPE_DOUBLE = 2;
2732
+ function State(options) {
2733
+ this.schema = options["schema"] || DEFAULT_SCHEMA2;
2734
+ this.indent = Math.max(1, options["indent"] || 2);
2735
+ this.noArrayIndent = options["noArrayIndent"] || false;
2736
+ this.skipInvalid = options["skipInvalid"] || false;
2737
+ this.flowLevel = common2.isNothing(options["flowLevel"]) ? -1 : options["flowLevel"];
2738
+ this.styleMap = compileStyleMap(this.schema, options["styles"] || null);
2739
+ this.sortKeys = options["sortKeys"] || false;
2740
+ this.lineWidth = options["lineWidth"] || 80;
2741
+ this.noRefs = options["noRefs"] || false;
2742
+ this.noCompatMode = options["noCompatMode"] || false;
2743
+ this.condenseFlow = options["condenseFlow"] || false;
2744
+ this.quotingType = options["quotingType"] === '"' ? QUOTING_TYPE_DOUBLE : QUOTING_TYPE_SINGLE;
2745
+ this.forceQuotes = options["forceQuotes"] || false;
2746
+ this.replacer = typeof options["replacer"] === "function" ? options["replacer"] : null;
2747
+ this.implicitTypes = this.schema.compiledImplicit;
2748
+ this.explicitTypes = this.schema.compiledExplicit;
2749
+ this.tag = null;
2750
+ this.result = "";
2751
+ this.duplicates = [];
2752
+ this.usedDuplicates = null;
2753
+ }
2754
+ function indentString(string, spaces) {
2755
+ const ind = common2.repeat(" ", spaces);
2756
+ let position = 0;
2757
+ let result = "";
2758
+ const length = string.length;
2759
+ while (position < length) {
2760
+ let line;
2761
+ const next = string.indexOf("\n", position);
2762
+ if (next === -1) {
2763
+ line = string.slice(position);
2764
+ position = length;
2765
+ } else {
2766
+ line = string.slice(position, next + 1);
2767
+ position = next + 1;
2768
+ }
2769
+ if (line.length && line !== "\n") result += ind;
2770
+ result += line;
2771
+ }
2772
+ return result;
2773
+ }
2774
+ function generateNextLine(state, level) {
2775
+ return "\n" + common2.repeat(" ", state.indent * level);
2776
+ }
2777
+ function testImplicitResolving(state, str2) {
2778
+ for (let index = 0, length = state.implicitTypes.length; index < length; index += 1) {
2779
+ const type2 = state.implicitTypes[index];
2780
+ if (type2.resolve(str2)) {
2781
+ return true;
2782
+ }
2783
+ }
2784
+ return false;
2785
+ }
2786
+ function isWhitespace(c) {
2787
+ return c === CHAR_SPACE || c === CHAR_TAB;
2788
+ }
2789
+ function isPrintable(c) {
2790
+ return c >= 32 && c <= 126 || c >= 161 && c <= 55295 && c !== 8232 && c !== 8233 || c >= 57344 && c <= 65533 && c !== CHAR_BOM || c >= 65536 && c <= 1114111;
2791
+ }
2792
+ function isNsCharOrWhitespace(c) {
2793
+ return isPrintable(c) && c !== CHAR_BOM && // - b-char
2794
+ c !== CHAR_CARRIAGE_RETURN && c !== CHAR_LINE_FEED;
2795
+ }
2796
+ function isPlainSafe(c, prev, inblock) {
2797
+ const cIsNsCharOrWhitespace = isNsCharOrWhitespace(c);
2798
+ const cIsNsChar = cIsNsCharOrWhitespace && !isWhitespace(c);
2799
+ return (
2800
+ // ns-plain-safe
2801
+ (inblock ? cIsNsCharOrWhitespace : cIsNsCharOrWhitespace && // - c-flow-indicator
2802
+ c !== CHAR_COMMA && c !== CHAR_LEFT_SQUARE_BRACKET && c !== CHAR_RIGHT_SQUARE_BRACKET && c !== CHAR_LEFT_CURLY_BRACKET && c !== CHAR_RIGHT_CURLY_BRACKET) && // ns-plain-char
2803
+ c !== CHAR_SHARP && // false on '#'
2804
+ !(prev === CHAR_COLON && !cIsNsChar) || // false on ': '
2805
+ isNsCharOrWhitespace(prev) && !isWhitespace(prev) && c === CHAR_SHARP || // change to true on '[^ ]#'
2806
+ prev === CHAR_COLON && cIsNsChar
2807
+ );
2808
+ }
2809
+ function isPlainSafeFirst(c) {
2810
+ return isPrintable(c) && c !== CHAR_BOM && !isWhitespace(c) && // - s-white
2811
+ // - (c-indicator ::=
2812
+ // “-” | “?” | “:” | “,” | “[” | “]” | “{” | “}”
2813
+ c !== CHAR_MINUS && c !== CHAR_QUESTION && c !== CHAR_COLON && c !== CHAR_COMMA && c !== CHAR_LEFT_SQUARE_BRACKET && c !== CHAR_RIGHT_SQUARE_BRACKET && c !== CHAR_LEFT_CURLY_BRACKET && c !== CHAR_RIGHT_CURLY_BRACKET && // | “#” | “&” | “*” | “!” | “|” | “=” | “>” | “'” | “"”
2814
+ c !== CHAR_SHARP && c !== CHAR_AMPERSAND && c !== CHAR_ASTERISK && c !== CHAR_EXCLAMATION && c !== CHAR_VERTICAL_LINE && c !== CHAR_EQUALS && c !== CHAR_GREATER_THAN && c !== CHAR_SINGLE_QUOTE && c !== CHAR_DOUBLE_QUOTE && // | “%” | “@” | “`”)
2815
+ c !== CHAR_PERCENT && c !== CHAR_COMMERCIAL_AT && c !== CHAR_GRAVE_ACCENT;
2816
+ }
2817
+ function isPlainSafeLast(c) {
2818
+ return !isWhitespace(c) && c !== CHAR_COLON;
2819
+ }
2820
+ function codePointAt(string, pos) {
2821
+ const first = string.charCodeAt(pos);
2822
+ let second;
2823
+ if (first >= 55296 && first <= 56319 && pos + 1 < string.length) {
2824
+ second = string.charCodeAt(pos + 1);
2825
+ if (second >= 56320 && second <= 57343) {
2826
+ return (first - 55296) * 1024 + second - 56320 + 65536;
2827
+ }
2828
+ }
2829
+ return first;
2830
+ }
2831
+ function needIndentIndicator(string) {
2832
+ const leadingSpaceRe = /^\n* /;
2833
+ return leadingSpaceRe.test(string);
2834
+ }
2835
+ const STYLE_PLAIN = 1;
2836
+ const STYLE_SINGLE = 2;
2837
+ const STYLE_LITERAL = 3;
2838
+ const STYLE_FOLDED = 4;
2839
+ const STYLE_DOUBLE = 5;
2840
+ function chooseScalarStyle(string, singleLineOnly, indentPerLevel, lineWidth, testAmbiguousType, quotingType, forceQuotes, inblock) {
2841
+ let i;
2842
+ let char = 0;
2843
+ let prevChar = null;
2844
+ let hasLineBreak = false;
2845
+ let hasFoldableLine = false;
2846
+ const shouldTrackWidth = lineWidth !== -1;
2847
+ let previousLineBreak = -1;
2848
+ let plain = isPlainSafeFirst(codePointAt(string, 0)) && isPlainSafeLast(codePointAt(string, string.length - 1));
2849
+ if (singleLineOnly || forceQuotes) {
2850
+ for (i = 0; i < string.length; char >= 65536 ? i += 2 : i++) {
2851
+ char = codePointAt(string, i);
2852
+ if (!isPrintable(char)) {
2853
+ return STYLE_DOUBLE;
2854
+ }
2855
+ plain = plain && isPlainSafe(char, prevChar, inblock);
2856
+ prevChar = char;
2857
+ }
2858
+ } else {
2859
+ for (i = 0; i < string.length; char >= 65536 ? i += 2 : i++) {
2860
+ char = codePointAt(string, i);
2861
+ if (char === CHAR_LINE_FEED) {
2862
+ hasLineBreak = true;
2863
+ if (shouldTrackWidth) {
2864
+ hasFoldableLine = hasFoldableLine || // Foldable line = too long, and not more-indented.
2865
+ i - previousLineBreak - 1 > lineWidth && string[previousLineBreak + 1] !== " ";
2866
+ previousLineBreak = i;
2867
+ }
2868
+ } else if (!isPrintable(char)) {
2869
+ return STYLE_DOUBLE;
2870
+ }
2871
+ plain = plain && isPlainSafe(char, prevChar, inblock);
2872
+ prevChar = char;
2873
+ }
2874
+ hasFoldableLine = hasFoldableLine || shouldTrackWidth && (i - previousLineBreak - 1 > lineWidth && string[previousLineBreak + 1] !== " ");
2875
+ }
2876
+ if (!hasLineBreak && !hasFoldableLine) {
2877
+ if (plain && !forceQuotes && !testAmbiguousType(string)) {
2878
+ return STYLE_PLAIN;
2879
+ }
2880
+ return quotingType === QUOTING_TYPE_DOUBLE ? STYLE_DOUBLE : STYLE_SINGLE;
2881
+ }
2882
+ if (indentPerLevel > 9 && needIndentIndicator(string)) {
2883
+ return STYLE_DOUBLE;
2884
+ }
2885
+ if (!forceQuotes) {
2886
+ return hasFoldableLine ? STYLE_FOLDED : STYLE_LITERAL;
2887
+ }
2888
+ return quotingType === QUOTING_TYPE_DOUBLE ? STYLE_DOUBLE : STYLE_SINGLE;
2889
+ }
2890
+ function writeScalar(state, string, level, iskey, inblock) {
2891
+ state.dump = (function() {
2892
+ if (string.length === 0) {
2893
+ return state.quotingType === QUOTING_TYPE_DOUBLE ? '""' : "''";
2894
+ }
2895
+ if (!state.noCompatMode) {
2896
+ if (DEPRECATED_BOOLEANS_SYNTAX.indexOf(string) !== -1 || DEPRECATED_BASE60_SYNTAX.test(string)) {
2897
+ return state.quotingType === QUOTING_TYPE_DOUBLE ? '"' + string + '"' : "'" + string + "'";
2898
+ }
2899
+ }
2900
+ const indent = state.indent * Math.max(1, level);
2901
+ const lineWidth = state.lineWidth === -1 ? -1 : Math.max(Math.min(state.lineWidth, 40), state.lineWidth - indent);
2902
+ const singleLineOnly = iskey || // No block styles in flow mode.
2903
+ state.flowLevel > -1 && level >= state.flowLevel;
2904
+ function testAmbiguity(string2) {
2905
+ return testImplicitResolving(state, string2);
2906
+ }
2907
+ switch (chooseScalarStyle(
2908
+ string,
2909
+ singleLineOnly,
2910
+ state.indent,
2911
+ lineWidth,
2912
+ testAmbiguity,
2913
+ state.quotingType,
2914
+ state.forceQuotes && !iskey,
2915
+ inblock
2916
+ )) {
2917
+ case STYLE_PLAIN:
2918
+ return string;
2919
+ case STYLE_SINGLE:
2920
+ return "'" + string.replace(/'/g, "''") + "'";
2921
+ case STYLE_LITERAL:
2922
+ return "|" + blockHeader(string, state.indent) + dropEndingNewline(indentString(string, indent));
2923
+ case STYLE_FOLDED:
2924
+ return ">" + blockHeader(string, state.indent) + dropEndingNewline(indentString(foldString(string, lineWidth), indent));
2925
+ case STYLE_DOUBLE:
2926
+ return '"' + escapeString(string) + '"';
2927
+ default:
2928
+ throw new YAMLException2("impossible error: invalid scalar style");
2929
+ }
2930
+ })();
2931
+ }
2932
+ function blockHeader(string, indentPerLevel) {
2933
+ const indentIndicator = needIndentIndicator(string) ? String(indentPerLevel) : "";
2934
+ const clip = string[string.length - 1] === "\n";
2935
+ const keep = clip && (string[string.length - 2] === "\n" || string === "\n");
2936
+ const chomp = keep ? "+" : clip ? "" : "-";
2937
+ return indentIndicator + chomp + "\n";
2938
+ }
2939
+ function dropEndingNewline(string) {
2940
+ return string[string.length - 1] === "\n" ? string.slice(0, -1) : string;
2941
+ }
2942
+ function foldString(string, width) {
2943
+ const lineRe = /(\n+)([^\n]*)/g;
2944
+ let result = (function() {
2945
+ let nextLF = string.indexOf("\n");
2946
+ nextLF = nextLF !== -1 ? nextLF : string.length;
2947
+ lineRe.lastIndex = nextLF;
2948
+ return foldLine(string.slice(0, nextLF), width);
2949
+ })();
2950
+ let prevMoreIndented = string[0] === "\n" || string[0] === " ";
2951
+ let moreIndented;
2952
+ let match;
2953
+ while (match = lineRe.exec(string)) {
2954
+ const prefix = match[1];
2955
+ const line = match[2];
2956
+ moreIndented = line[0] === " ";
2957
+ result += prefix + (!prevMoreIndented && !moreIndented && line !== "" ? "\n" : "") + foldLine(line, width);
2958
+ prevMoreIndented = moreIndented;
2959
+ }
2960
+ return result;
2961
+ }
2962
+ function foldLine(line, width) {
2963
+ if (line === "" || line[0] === " ") return line;
2964
+ const breakRe = / [^ ]/g;
2965
+ let match;
2966
+ let start = 0;
2967
+ let end;
2968
+ let curr = 0;
2969
+ let next = 0;
2970
+ let result = "";
2971
+ while (match = breakRe.exec(line)) {
2972
+ next = match.index;
2973
+ if (next - start > width) {
2974
+ end = curr > start ? curr : next;
2975
+ result += "\n" + line.slice(start, end);
2976
+ start = end + 1;
2977
+ }
2978
+ curr = next;
2979
+ }
2980
+ result += "\n";
2981
+ if (line.length - start > width && curr > start) {
2982
+ result += line.slice(start, curr) + "\n" + line.slice(curr + 1);
2983
+ } else {
2984
+ result += line.slice(start);
2985
+ }
2986
+ return result.slice(1);
2987
+ }
2988
+ function escapeString(string) {
2989
+ let result = "";
2990
+ let char = 0;
2991
+ for (let i = 0; i < string.length; char >= 65536 ? i += 2 : i++) {
2992
+ char = codePointAt(string, i);
2993
+ const escapeSeq = ESCAPE_SEQUENCES[char];
2994
+ if (!escapeSeq && isPrintable(char)) {
2995
+ result += string[i];
2996
+ if (char >= 65536) result += string[i + 1];
2997
+ } else {
2998
+ result += escapeSeq || encodeHex(char);
2999
+ }
3000
+ }
3001
+ return result;
3002
+ }
3003
+ function writeFlowSequence(state, level, object) {
3004
+ let _result = "";
3005
+ const _tag = state.tag;
3006
+ for (let index = 0, length = object.length; index < length; index += 1) {
3007
+ let value = object[index];
3008
+ if (state.replacer) {
3009
+ value = state.replacer.call(object, String(index), value);
3010
+ }
3011
+ if (writeNode(state, level, value, false, false) || typeof value === "undefined" && writeNode(state, level, null, false, false)) {
3012
+ if (_result !== "") _result += "," + (!state.condenseFlow ? " " : "");
3013
+ _result += state.dump;
3014
+ }
3015
+ }
3016
+ state.tag = _tag;
3017
+ state.dump = "[" + _result + "]";
3018
+ }
3019
+ function writeBlockSequence(state, level, object, compact) {
3020
+ let _result = "";
3021
+ const _tag = state.tag;
3022
+ for (let index = 0, length = object.length; index < length; index += 1) {
3023
+ let value = object[index];
3024
+ if (state.replacer) {
3025
+ value = state.replacer.call(object, String(index), value);
3026
+ }
3027
+ if (writeNode(state, level + 1, value, true, true, false, true) || typeof value === "undefined" && writeNode(state, level + 1, null, true, true, false, true)) {
3028
+ if (!compact || _result !== "") {
3029
+ _result += generateNextLine(state, level);
3030
+ }
3031
+ if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) {
3032
+ _result += "-";
3033
+ } else {
3034
+ _result += "- ";
3035
+ }
3036
+ _result += state.dump;
3037
+ }
3038
+ }
3039
+ state.tag = _tag;
3040
+ state.dump = _result || "[]";
3041
+ }
3042
+ function writeFlowMapping(state, level, object) {
3043
+ let _result = "";
3044
+ const _tag = state.tag;
3045
+ const objectKeyList = Object.keys(object);
3046
+ for (let index = 0, length = objectKeyList.length; index < length; index += 1) {
3047
+ let pairBuffer = "";
3048
+ if (_result !== "") pairBuffer += ", ";
3049
+ if (state.condenseFlow) pairBuffer += '"';
3050
+ const objectKey = objectKeyList[index];
3051
+ let objectValue = object[objectKey];
3052
+ if (state.replacer) {
3053
+ objectValue = state.replacer.call(object, objectKey, objectValue);
3054
+ }
3055
+ if (!writeNode(state, level, objectKey, false, false)) {
3056
+ continue;
3057
+ }
3058
+ if (state.dump.length > 1024) pairBuffer += "? ";
3059
+ pairBuffer += state.dump + (state.condenseFlow ? '"' : "") + ":" + (state.condenseFlow ? "" : " ");
3060
+ if (!writeNode(state, level, objectValue, false, false)) {
3061
+ continue;
3062
+ }
3063
+ pairBuffer += state.dump;
3064
+ _result += pairBuffer;
3065
+ }
3066
+ state.tag = _tag;
3067
+ state.dump = "{" + _result + "}";
3068
+ }
3069
+ function writeBlockMapping(state, level, object, compact) {
3070
+ let _result = "";
3071
+ const _tag = state.tag;
3072
+ const objectKeyList = Object.keys(object);
3073
+ if (state.sortKeys === true) {
3074
+ objectKeyList.sort();
3075
+ } else if (typeof state.sortKeys === "function") {
3076
+ objectKeyList.sort(state.sortKeys);
3077
+ } else if (state.sortKeys) {
3078
+ throw new YAMLException2("sortKeys must be a boolean or a function");
3079
+ }
3080
+ for (let index = 0, length = objectKeyList.length; index < length; index += 1) {
3081
+ let pairBuffer = "";
3082
+ if (!compact || _result !== "") {
3083
+ pairBuffer += generateNextLine(state, level);
3084
+ }
3085
+ const objectKey = objectKeyList[index];
3086
+ let objectValue = object[objectKey];
3087
+ if (state.replacer) {
3088
+ objectValue = state.replacer.call(object, objectKey, objectValue);
3089
+ }
3090
+ if (!writeNode(state, level + 1, objectKey, true, true, true)) {
3091
+ continue;
3092
+ }
3093
+ const explicitPair = state.tag !== null && state.tag !== "?" || state.dump && state.dump.length > 1024;
3094
+ if (explicitPair) {
3095
+ if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) {
3096
+ pairBuffer += "?";
3097
+ } else {
3098
+ pairBuffer += "? ";
3099
+ }
3100
+ }
3101
+ pairBuffer += state.dump;
3102
+ if (explicitPair) {
3103
+ pairBuffer += generateNextLine(state, level);
3104
+ }
3105
+ if (!writeNode(state, level + 1, objectValue, true, explicitPair)) {
3106
+ continue;
3107
+ }
3108
+ if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) {
3109
+ pairBuffer += ":";
3110
+ } else {
3111
+ pairBuffer += ": ";
3112
+ }
3113
+ pairBuffer += state.dump;
3114
+ _result += pairBuffer;
3115
+ }
3116
+ state.tag = _tag;
3117
+ state.dump = _result || "{}";
3118
+ }
3119
+ function detectType(state, object, explicit) {
3120
+ const typeList = explicit ? state.explicitTypes : state.implicitTypes;
3121
+ for (let index = 0, length = typeList.length; index < length; index += 1) {
3122
+ const type2 = typeList[index];
3123
+ if ((type2.instanceOf || type2.predicate) && (!type2.instanceOf || typeof object === "object" && object instanceof type2.instanceOf) && (!type2.predicate || type2.predicate(object))) {
3124
+ if (explicit) {
3125
+ if (type2.multi && type2.representName) {
3126
+ state.tag = type2.representName(object);
3127
+ } else {
3128
+ state.tag = type2.tag;
3129
+ }
3130
+ } else {
3131
+ state.tag = "?";
3132
+ }
3133
+ if (type2.represent) {
3134
+ const style = state.styleMap[type2.tag] || type2.defaultStyle;
3135
+ let _result;
3136
+ if (_toString.call(type2.represent) === "[object Function]") {
3137
+ _result = type2.represent(object, style);
3138
+ } else if (_hasOwnProperty.call(type2.represent, style)) {
3139
+ _result = type2.represent[style](object, style);
3140
+ } else {
3141
+ throw new YAMLException2("!<" + type2.tag + '> tag resolver accepts not "' + style + '" style');
3142
+ }
3143
+ state.dump = _result;
3144
+ }
3145
+ return true;
3146
+ }
3147
+ }
3148
+ return false;
3149
+ }
3150
+ function writeNode(state, level, object, block, compact, iskey, isblockseq) {
3151
+ state.tag = null;
3152
+ state.dump = object;
3153
+ if (!detectType(state, object, false)) {
3154
+ detectType(state, object, true);
3155
+ }
3156
+ const type2 = _toString.call(state.dump);
3157
+ const inblock = block;
3158
+ if (block) {
3159
+ block = state.flowLevel < 0 || state.flowLevel > level;
3160
+ }
3161
+ const objectOrArray = type2 === "[object Object]" || type2 === "[object Array]";
3162
+ let duplicateIndex;
3163
+ let duplicate;
3164
+ if (objectOrArray) {
3165
+ duplicateIndex = state.duplicates.indexOf(object);
3166
+ duplicate = duplicateIndex !== -1;
3167
+ }
3168
+ if (state.tag !== null && state.tag !== "?" || duplicate || state.indent !== 2 && level > 0) {
3169
+ compact = false;
3170
+ }
3171
+ if (duplicate && state.usedDuplicates[duplicateIndex]) {
3172
+ state.dump = "*ref_" + duplicateIndex;
3173
+ } else {
3174
+ if (objectOrArray && duplicate && !state.usedDuplicates[duplicateIndex]) {
3175
+ state.usedDuplicates[duplicateIndex] = true;
3176
+ }
3177
+ if (type2 === "[object Object]") {
3178
+ if (block && Object.keys(state.dump).length !== 0) {
3179
+ writeBlockMapping(state, level, state.dump, compact);
3180
+ if (duplicate) {
3181
+ state.dump = "&ref_" + duplicateIndex + state.dump;
3182
+ }
3183
+ } else {
3184
+ writeFlowMapping(state, level, state.dump);
3185
+ if (duplicate) {
3186
+ state.dump = "&ref_" + duplicateIndex + " " + state.dump;
3187
+ }
3188
+ }
3189
+ } else if (type2 === "[object Array]") {
3190
+ if (block && state.dump.length !== 0) {
3191
+ if (state.noArrayIndent && !isblockseq && level > 0) {
3192
+ writeBlockSequence(state, level - 1, state.dump, compact);
3193
+ } else {
3194
+ writeBlockSequence(state, level, state.dump, compact);
3195
+ }
3196
+ if (duplicate) {
3197
+ state.dump = "&ref_" + duplicateIndex + state.dump;
3198
+ }
3199
+ } else {
3200
+ writeFlowSequence(state, level, state.dump);
3201
+ if (duplicate) {
3202
+ state.dump = "&ref_" + duplicateIndex + " " + state.dump;
3203
+ }
3204
+ }
3205
+ } else if (type2 === "[object String]") {
3206
+ if (state.tag !== "?") {
3207
+ writeScalar(state, state.dump, level, iskey, inblock);
3208
+ }
3209
+ } else if (type2 === "[object Undefined]") {
3210
+ return false;
3211
+ } else {
3212
+ if (state.skipInvalid) return false;
3213
+ throw new YAMLException2("unacceptable kind of an object to dump " + type2);
3214
+ }
3215
+ if (state.tag !== null && state.tag !== "?") {
3216
+ let tagStr = encodeURI(
3217
+ state.tag[0] === "!" ? state.tag.slice(1) : state.tag
3218
+ ).replace(/!/g, "%21");
3219
+ if (state.tag[0] === "!") {
3220
+ tagStr = "!" + tagStr;
3221
+ } else if (tagStr.slice(0, 18) === "tag:yaml.org,2002:") {
3222
+ tagStr = "!!" + tagStr.slice(18);
3223
+ } else {
3224
+ tagStr = "!<" + tagStr + ">";
3225
+ }
3226
+ state.dump = tagStr + " " + state.dump;
3227
+ }
3228
+ }
3229
+ return true;
3230
+ }
3231
+ function getDuplicateReferences(object, state) {
3232
+ const objects = [];
3233
+ const duplicatesIndexes = [];
3234
+ inspectNode(object, objects, duplicatesIndexes);
3235
+ const length = duplicatesIndexes.length;
3236
+ for (let index = 0; index < length; index += 1) {
3237
+ state.duplicates.push(objects[duplicatesIndexes[index]]);
3238
+ }
3239
+ state.usedDuplicates = new Array(length);
3240
+ }
3241
+ function inspectNode(object, objects, duplicatesIndexes) {
3242
+ if (object !== null && typeof object === "object") {
3243
+ const index = objects.indexOf(object);
3244
+ if (index !== -1) {
3245
+ if (duplicatesIndexes.indexOf(index) === -1) {
3246
+ duplicatesIndexes.push(index);
3247
+ }
3248
+ } else {
3249
+ objects.push(object);
3250
+ if (Array.isArray(object)) {
3251
+ for (let i = 0, length = object.length; i < length; i += 1) {
3252
+ inspectNode(object[i], objects, duplicatesIndexes);
3253
+ }
3254
+ } else {
3255
+ const objectKeyList = Object.keys(object);
3256
+ for (let i = 0, length = objectKeyList.length; i < length; i += 1) {
3257
+ inspectNode(object[objectKeyList[i]], objects, duplicatesIndexes);
3258
+ }
3259
+ }
3260
+ }
3261
+ }
3262
+ }
3263
+ function dump2(input, options) {
3264
+ options = options || {};
3265
+ const state = new State(options);
3266
+ if (!state.noRefs) getDuplicateReferences(input, state);
3267
+ let value = input;
3268
+ if (state.replacer) {
3269
+ value = state.replacer.call({ "": value }, "", value);
3270
+ }
3271
+ if (writeNode(state, 0, value, true, true)) return state.dump + "\n";
3272
+ return "";
3273
+ }
3274
+ dumper.dump = dump2;
3275
+ return dumper;
3276
+ }
3277
+ var hasRequiredJsYaml;
3278
+ function requireJsYaml() {
3279
+ if (hasRequiredJsYaml) return jsYaml;
3280
+ hasRequiredJsYaml = 1;
3281
+ const loader2 = requireLoader();
3282
+ const dumper2 = requireDumper();
3283
+ function renamed(from, to) {
3284
+ return function() {
3285
+ throw new Error("Function yaml." + from + " is removed in js-yaml 4. Use yaml." + to + " instead, which is now safe by default.");
3286
+ };
3287
+ }
3288
+ jsYaml.Type = requireType();
3289
+ jsYaml.Schema = requireSchema();
3290
+ jsYaml.FAILSAFE_SCHEMA = requireFailsafe();
3291
+ jsYaml.JSON_SCHEMA = requireJson();
3292
+ jsYaml.CORE_SCHEMA = requireCore();
3293
+ jsYaml.DEFAULT_SCHEMA = require_default();
3294
+ jsYaml.load = loader2.load;
3295
+ jsYaml.loadAll = loader2.loadAll;
3296
+ jsYaml.dump = dumper2.dump;
3297
+ jsYaml.YAMLException = requireException();
3298
+ jsYaml.types = {
3299
+ binary: requireBinary(),
3300
+ float: requireFloat(),
3301
+ map: requireMap(),
3302
+ null: require_null(),
3303
+ pairs: requirePairs(),
3304
+ set: requireSet(),
3305
+ timestamp: requireTimestamp(),
3306
+ bool: requireBool(),
3307
+ int: requireInt(),
3308
+ merge: requireMerge(),
3309
+ omap: requireOmap(),
3310
+ seq: requireSeq(),
3311
+ str: requireStr()
3312
+ };
3313
+ jsYaml.safeLoad = renamed("safeLoad", "load");
3314
+ jsYaml.safeLoadAll = renamed("safeLoadAll", "loadAll");
3315
+ jsYaml.safeDump = renamed("safeDump", "dump");
3316
+ return jsYaml;
3317
+ }
3318
+ var jsYamlExports = requireJsYaml();
3319
+ var yaml = /* @__PURE__ */ getDefaultExportFromCjs(jsYamlExports);
3320
+ var {
3321
+ Type,
3322
+ Schema,
3323
+ FAILSAFE_SCHEMA,
3324
+ JSON_SCHEMA,
3325
+ CORE_SCHEMA,
3326
+ DEFAULT_SCHEMA,
3327
+ load,
3328
+ loadAll,
3329
+ dump,
3330
+ YAMLException,
3331
+ types,
3332
+ safeLoad,
3333
+ safeLoadAll,
3334
+ safeDump
3335
+ } = yaml;
3336
+
3337
+ // src/local-evaluator/pdlss-parser.ts
3338
+ var import_fs = require("fs");
3339
+
3340
+ // src/local-evaluator/schema.ts
3341
+ function validatePolicy(policy) {
3342
+ const errors = [];
3343
+ if (!policy || typeof policy !== "object") {
3344
+ return { valid: false, errors: [{ path: "", message: "Policy must be an object" }] };
3345
+ }
3346
+ const p = policy;
3347
+ if (typeof p.version !== "string") {
3348
+ errors.push({ path: "version", message: "version is required and must be a string" });
3349
+ }
3350
+ if (typeof p.name !== "string") {
3351
+ errors.push({ path: "name", message: "name is required and must be a string" });
3352
+ }
3353
+ if (!Array.isArray(p.purposes)) {
3354
+ errors.push({ path: "purposes", message: "purposes is required and must be an array" });
3355
+ } else {
3356
+ p.purposes.forEach((purpose, i) => {
3357
+ errors.push(...validatePurpose(purpose, `purposes[${i}]`));
3358
+ });
3359
+ }
3360
+ if (p.scope !== void 0) {
3361
+ errors.push(...validateScope(p.scope, "scope"));
3362
+ }
3363
+ if (p.limits !== void 0) {
3364
+ errors.push(...validateLimits(p.limits, "limits"));
3365
+ }
3366
+ if (p.riskThresholds !== void 0) {
3367
+ errors.push(...validateRiskThresholds(p.riskThresholds, "riskThresholds"));
3368
+ }
3369
+ return { valid: errors.length === 0, errors };
3370
+ }
3371
+ function validatePurpose(purpose, path) {
3372
+ const errors = [];
3373
+ if (!purpose || typeof purpose !== "object") {
3374
+ return [{ path, message: "purpose must be an object" }];
3375
+ }
3376
+ const p = purpose;
3377
+ if (typeof p.id !== "string" || !p.id) {
3378
+ errors.push({ path: `${path}.id`, message: "id is required and must be a non-empty string" });
3379
+ }
3380
+ if (typeof p.allowed !== "boolean") {
3381
+ errors.push({ path: `${path}.allowed`, message: "allowed is required and must be a boolean" });
3382
+ }
3383
+ if (p.targets !== void 0 && !isStringArray(p.targets)) {
3384
+ errors.push({ path: `${path}.targets`, message: "targets must be an array of strings" });
3385
+ }
3386
+ if (p.blockedPatterns !== void 0 && !isStringArray(p.blockedPatterns)) {
3387
+ errors.push({ path: `${path}.blockedPatterns`, message: "blockedPatterns must be an array of strings" });
3388
+ }
3389
+ if (p.requiresApproval !== void 0 && typeof p.requiresApproval !== "boolean") {
3390
+ errors.push({ path: `${path}.requiresApproval`, message: "requiresApproval must be a boolean" });
3391
+ }
3392
+ return errors;
3393
+ }
3394
+ function validateScope(scope, path) {
3395
+ const errors = [];
3396
+ if (typeof scope !== "object" || scope === null) {
3397
+ return [{ path, message: "scope must be an object" }];
3398
+ }
3399
+ const s = scope;
3400
+ for (const field of ["allowedDomains", "blockedDomains", "blockedResources"]) {
3401
+ if (s[field] !== void 0 && !isStringArray(s[field])) {
3402
+ errors.push({ path: `${path}.${field}`, message: `${field} must be an array of strings` });
3403
+ }
3404
+ }
3405
+ return errors;
3406
+ }
3407
+ function validateLimits(limits, path) {
3408
+ const errors = [];
3409
+ if (typeof limits !== "object" || limits === null) {
3410
+ return [{ path, message: "limits must be an object" }];
3411
+ }
3412
+ const l = limits;
3413
+ if (l.maxTransactionAmount !== void 0 && typeof l.maxTransactionAmount !== "number") {
3414
+ errors.push({ path: `${path}.maxTransactionAmount`, message: "maxTransactionAmount must be a number" });
3415
+ }
3416
+ if (l.maxRequestsPerHour !== void 0 && typeof l.maxRequestsPerHour !== "number") {
3417
+ errors.push({ path: `${path}.maxRequestsPerHour`, message: "maxRequestsPerHour must be a number" });
3418
+ }
3419
+ if (l.currency !== void 0 && typeof l.currency !== "string") {
3420
+ errors.push({ path: `${path}.currency`, message: "currency must be a string" });
3421
+ }
3422
+ return errors;
3423
+ }
3424
+ function validateRiskThresholds(thresholds, path) {
3425
+ const errors = [];
3426
+ if (typeof thresholds !== "object" || thresholds === null) {
3427
+ return [{ path, message: "riskThresholds must be an object" }];
3428
+ }
3429
+ const t = thresholds;
3430
+ for (const range of ["autoAllow", "requireApproval", "autoBlock"]) {
3431
+ if (!t[range] || typeof t[range] !== "object") {
3432
+ errors.push({ path: `${path}.${range}`, message: `${range} is required and must be an object with min and max` });
3433
+ continue;
3434
+ }
3435
+ const r = t[range];
3436
+ if (typeof r.min !== "number" || typeof r.max !== "number") {
3437
+ errors.push({ path: `${path}.${range}`, message: `${range} must have numeric min and max` });
3438
+ } else if (r.min > r.max) {
3439
+ errors.push({ path: `${path}.${range}`, message: `${range}.min must be <= ${range}.max` });
3440
+ }
3441
+ }
3442
+ if (isValidThresholdShape(t)) {
3443
+ const thresholdObj = t;
3444
+ if (thresholdObj.autoAllow.max + 1 !== thresholdObj.requireApproval.min) {
3445
+ errors.push({
3446
+ path: `${path}`,
3447
+ message: `Gap between autoAllow.max (${thresholdObj.autoAllow.max}) and requireApproval.min (${thresholdObj.requireApproval.min}). Ranges must be contiguous.`
3448
+ });
3449
+ }
3450
+ if (thresholdObj.requireApproval.max + 1 !== thresholdObj.autoBlock.min) {
3451
+ errors.push({
3452
+ path: `${path}`,
3453
+ message: `Gap between requireApproval.max (${thresholdObj.requireApproval.max}) and autoBlock.min (${thresholdObj.autoBlock.min}). Ranges must be contiguous.`
3454
+ });
3455
+ }
3456
+ }
3457
+ return errors;
3458
+ }
3459
+ function isStringArray(val) {
3460
+ return Array.isArray(val) && val.every((v) => typeof v === "string");
3461
+ }
3462
+ function isValidThresholdShape(t) {
3463
+ for (const key of ["autoAllow", "requireApproval", "autoBlock"]) {
3464
+ const r = t[key];
3465
+ if (!r || typeof r !== "object") return false;
3466
+ const range = r;
3467
+ if (typeof range.min !== "number" || typeof range.max !== "number") return false;
3468
+ }
3469
+ return true;
3470
+ }
3471
+
3472
+ // src/local-evaluator/pdlss-parser.ts
3473
+ function parseYaml(yamlContent) {
3474
+ let parsed;
3475
+ try {
3476
+ parsed = load(yamlContent);
3477
+ } catch (err) {
3478
+ const message = err instanceof Error ? err.message : "Invalid YAML";
3479
+ return {
3480
+ policy: null,
3481
+ validation: { valid: false, errors: [{ path: "", message: `YAML parse error: ${message}` }] },
3482
+ rawYaml: yamlContent
3483
+ };
3484
+ }
3485
+ const validation = validatePolicy(parsed);
3486
+ if (!validation.valid) {
3487
+ return { policy: null, validation, rawYaml: yamlContent };
3488
+ }
3489
+ return {
3490
+ policy: parsed,
3491
+ validation,
3492
+ rawYaml: yamlContent
3493
+ };
3494
+ }
3495
+ function parseFile(filePath) {
3496
+ let content;
3497
+ try {
3498
+ content = (0, import_fs.readFileSync)(filePath, "utf-8");
3499
+ } catch (err) {
3500
+ const message = err instanceof Error ? err.message : "File read error";
3501
+ return {
3502
+ policy: null,
3503
+ validation: { valid: false, errors: [{ path: "", message: `Failed to read policy file: ${message}` }] }
3504
+ };
3505
+ }
3506
+ return parseYaml(content);
3507
+ }
3508
+
3509
+ // src/gateway/modes/local.ts
3510
+ function loadEvaluator(config) {
3511
+ if (config.policy) {
3512
+ return new LocalEvaluator(config.policy);
3513
+ }
3514
+ if (config.policyFile) {
3515
+ const result = parseFile(config.policyFile);
3516
+ if (!result.policy) {
3517
+ const errors = result.validation.errors.map((e) => `${e.path}: ${e.message}`).join("; ");
3518
+ throw new Error(`Invalid policy file ${config.policyFile}: ${errors}`);
3519
+ }
3520
+ return new LocalEvaluator(result.policy);
3521
+ }
3522
+ throw new Error("Local mode requires either policyFile or policy in config");
3523
+ }
3524
+ function verifyLocal(evaluator, context) {
3525
+ return evaluator.evaluate(context);
3526
+ }
3527
+
3528
+ // src/access-levels.ts
3529
+ function getTrustLevel(score) {
3530
+ if (score >= 80) return "PLATINUM";
3531
+ if (score >= 60) return "GOLD";
3532
+ if (score >= 40) return "SILVER";
3533
+ return "BRONZE";
3534
+ }
3535
+
3536
+ // src/version.ts
3537
+ var SDK_VERSION = "3.7.0";
3538
+
3539
+ // src/well-known.ts
3540
+ var CACHE_TTL_MS = 60 * 60 * 1e3;
3541
+ var cache = /* @__PURE__ */ new Map();
3542
+ function getCachedWellKnownUrls(apiBaseUrl) {
3543
+ return cache.get(apiBaseUrl)?.data;
3544
+ }
3545
+
3546
+ // src/verify.ts
3547
+ var DEFAULT_CONFIG = {
3548
+ apiBaseUrl: "https://astrasync.ai/api",
3549
+ // v2.3.9 (defect #30): default for unconfigured callers is `'none'` (no
3550
+ // access). Pre-rename this defaulted to `'guidance'`, which combined with
3551
+ // a route gated at `'guidance'` to silently let unverified traffic
3552
+ // through (`hasMinimumAccess('guidance', 'guidance') === true`).
3553
+ defaultAccessLevel: "none",
3554
+ // minTrustScore + minTrustScoreForFull deprecated in v2.3.0 — server decides.
3555
+ // cacheTtl deliberately unset. When undefined, cacheResult applies the 60s
3556
+ // default; the caller's explicit value is honoured for cacheable results.
3557
+ // Denials and step-up escalations are NEVER cached (3.6.0) regardless of
3558
+ // cacheTtl. Set cacheTtl: 0 to disable caching entirely.
3559
+ debug: false
3560
+ };
3561
+ var initCheckPerformed = false;
3562
+ var deprecationWarningShown = false;
3563
+ async function performInitCheck(apiBaseUrl, debug, strictInit) {
3564
+ initCheckPerformed = true;
3565
+ try {
3566
+ const probeUrl = `${apiBaseUrl}/agents/verify-access`;
3567
+ const response = await fetch(probeUrl, { method: "HEAD" });
3568
+ const contentType = response.headers.get("content-type") ?? "";
3569
+ if (contentType.startsWith("text/html")) {
3570
+ const message = `[VerificationGateway] apiBaseUrl '${apiBaseUrl}' returned HTML (content-type: ${contentType}). This usually means apiBaseUrl is pointing at a marketing site instead of the API. Expected: 'https://astrasync.ai/api' (prod) or 'https://staging.astrasync.ai/api' (staging).`;
3571
+ if (strictInit) {
3572
+ throw new Error(`${message} (strictInit=true)`);
3573
+ }
3574
+ console.warn(`${message} Set disableInitChecks: true on GatewayConfig to silence.`);
3575
+ } else if (debug) {
3576
+ console.log(
3577
+ `[VerificationGateway] init check passed for ${apiBaseUrl} (content-type: ${contentType})`
3578
+ );
3579
+ }
3580
+ } catch (err) {
3581
+ if (strictInit) {
3582
+ throw err;
3583
+ }
3584
+ if (debug) {
3585
+ console.log(`[VerificationGateway] init check failed (non-blocking): ${String(err)}`);
3586
+ }
3587
+ }
3588
+ }
3589
+ var verificationCache = /* @__PURE__ */ new Map();
3590
+ function getCacheKey(request, counterpartyId) {
3591
+ const c = request.credentials;
3592
+ return [
3593
+ c.astraId || "",
3594
+ c.apiKey || "",
3595
+ c.jwt || "",
3596
+ request.purpose || "",
3597
+ request.action || "",
3598
+ request.resourceType || "",
3599
+ request.resource || "",
3600
+ request.jurisdiction || "",
3601
+ request.transactionValue ?? "",
3602
+ request.currency || "",
3603
+ // SECURITY (cross-merchant cache leak): the merchant identity is sent via
3604
+ // `config.counterpartyId`, NOT on the request, so it was previously absent
3605
+ // from the key — two verifies for the SAME agent/purpose/action/value but
3606
+ // DIFFERENT merchants collided, and a grant at a permissive merchant (low
3607
+ // trust floor) was served for a stricter one. Same bug class as the
3608
+ // duration omission (F-A1-07). counterpartyId affects the backend verdict
3609
+ // (trust floor / per-route policy), so it MUST key the cache.
3610
+ counterpartyId || "",
3611
+ request.counterpartyUrl || "",
3612
+ request.counterpartyType || "",
3613
+ request.isSubAgentRequest ? "1" : "0",
3614
+ request.parentAgentId || "",
3615
+ request.subAgentDepth ?? "",
3616
+ // Audit F-A1-07: previously-missing dimensions that DO affect the
3617
+ // backend verdict. Without these, two requests with different
3618
+ // durations (e.g. 60s vs 86400s) collided on the same cache key and
3619
+ // the shorter-duration allow served the longer-duration request.
3620
+ request.durationRequired ?? "",
3621
+ request.invocationProtocol || "",
3622
+ request.enableRuntimeChallenge ? "1" : "0",
3623
+ // callerMetadata fields contribute to risk model; include the ones
3624
+ // backend reads. sourceIp/userAgent/forwardedFor change per-request
3625
+ // so their inclusion effectively forces a re-check for any varying
3626
+ // client (the right behavior — IP-driven anomaly scoring shouldn't
3627
+ // be cached across IPs).
3628
+ request.callerMetadata?.sourceIp || "",
3629
+ request.callerMetadata?.userAgent || "",
3630
+ request.callerMetadata?.forwardedFor || "",
3631
+ request.callerMetadata?.agentCardUrl || ""
3632
+ ].join("|");
3633
+ }
3634
+ function getCachedResult(request, counterpartyId) {
3635
+ const key = getCacheKey(request, counterpartyId);
3636
+ const cached = verificationCache.get(key);
3637
+ if (cached && cached.expiresAt > Date.now()) {
3638
+ return cached.result;
3639
+ }
3640
+ if (cached) {
3641
+ verificationCache.delete(key);
3642
+ }
3643
+ return null;
3644
+ }
3645
+ var DEFAULT_CACHE_TTL_SECONDS = 60;
3646
+ function cacheResult(request, result, configuredTtl, counterpartyId) {
3647
+ const ttlSeconds = configuredTtl && configuredTtl > 0 ? configuredTtl : DEFAULT_CACHE_TTL_SECONDS;
3648
+ const key = getCacheKey(request, counterpartyId);
3649
+ verificationCache.set(key, {
3650
+ result,
3651
+ expiresAt: Date.now() + ttlSeconds * 1e3
3652
+ });
3653
+ }
3654
+ function createGuidanceResponse(_config, reason, options = {}) {
3655
+ const source = options.source ?? "no_credentials";
3656
+ const isApiError = source === "api_error";
3657
+ const urls = options.urls;
3658
+ const guidance = isApiError ? {
3659
+ message: "Verification is temporarily unavailable. Retry with exponential backoff; if the issue persists, contact support with the correlationId.",
3660
+ registrationUrl: urls?.registrationUrl ?? "",
3661
+ documentationUrl: urls?.documentationUrl ?? "",
3662
+ steps: [
3663
+ "Retry the request with exponential backoff",
3664
+ "If failures persist, share the correlationId with support"
3665
+ ]
3666
+ } : {
3667
+ message: "This service verifies AI agents before granting access. Please register your agent with AstraSync.",
3668
+ registrationUrl: urls?.registrationUrl ?? "",
3669
+ documentationUrl: urls?.documentationUrl ?? "",
3670
+ steps: [
3671
+ "Register for an AstraSync account",
3672
+ "Create and register your agent",
3673
+ "Add your ASTRA-ID to request headers",
3674
+ "Retry your request"
3675
+ ]
3676
+ };
3677
+ return {
3678
+ // Round-18 G4: createGuidanceResponse fires for unverified-agent path or
3679
+ // API-error fallback. Identity is not verified (no agent resolved);
3680
+ // policy is not evaluated (we never reached the gate).
3681
+ identityVerified: false,
3682
+ policyAllowed: false,
3683
+ // v2.3.9 (defect #30): denials grant `'none'`, NEVER a positive band.
3684
+ // Adapters additionally short-circuit on `!identityVerified ||
3685
+ // !policyAllowed` before the gate check, but the access level still has
3686
+ // to be honest at the data layer so downstream consumers (SDK adapters
3687
+ // in other languages, custom integrations) inherit the correct
3688
+ // semantics.
3689
+ accessLevel: "none",
3690
+ guidance,
3691
+ denialReasons: reason ? [reason] : ["No valid agent credentials provided"],
3692
+ // Round-10 (#47, O5): on API-error fallback, surface a typed failure so
3693
+ // partners (and their custom onDenied handlers) can branch on
3694
+ // dimension. Without this, the synthesised stub was indistinguishable
3695
+ // from a real policy deny.
3696
+ failures: isApiError ? [
3697
+ {
3698
+ dimension: "verify_access.api_error",
3699
+ message: reason ?? "Verification temporarily unavailable",
3700
+ guidance: guidance.message
3701
+ }
3702
+ ] : void 0,
3703
+ correlationId: options.correlationId,
3704
+ verifiedAt: /* @__PURE__ */ new Date()
3705
+ };
3706
+ }
3707
+ async function callVerifyAccessAPI(config, request) {
3708
+ const { credentials, ...requestData } = request;
3709
+ const body = {
3710
+ ...credentials.astraId && { agentId: credentials.astraId },
3711
+ ...requestData.purpose && { purpose: requestData.purpose }
3712
+ };
3713
+ if (requestData.action) body.action = requestData.action;
3714
+ if (requestData.resourceType) body.resourceType = requestData.resourceType;
3715
+ if (requestData.resource) body.resource = requestData.resource;
3716
+ if (requestData.jurisdiction) body.jurisdiction = requestData.jurisdiction;
3717
+ if (requestData.transactionValue) body.transactionValue = requestData.transactionValue;
3718
+ if (requestData.currency) body.currency = requestData.currency;
3719
+ if (requestData.isSubAgentRequest) body.isSubAgentRequest = requestData.isSubAgentRequest;
3720
+ if (requestData.parentAgentId) body.parentAgentId = requestData.parentAgentId;
3721
+ if (requestData.subAgentDepth !== void 0) body.subAgentDepth = requestData.subAgentDepth;
3722
+ if (requestData.enableRuntimeChallenge)
3723
+ body.enableRuntimeChallenge = requestData.enableRuntimeChallenge;
3724
+ if (requestData.createSession) body.createSession = requestData.createSession;
3725
+ if (requestData.durationRequired) body.durationRequired = requestData.durationRequired;
3726
+ if (requestData.counterpartyType) body.counterpartyType = requestData.counterpartyType;
3727
+ if (requestData.counterpartyUrl) body.counterpartyUrl = requestData.counterpartyUrl;
3728
+ if (config.counterpartyId) body.counterpartyId = config.counterpartyId;
3729
+ if (requestData.runtimeChallengeOptions)
3730
+ body.runtimeChallengeOptions = requestData.runtimeChallengeOptions;
3731
+ if (requestData.invocationProtocol) body.invocationProtocol = requestData.invocationProtocol;
3732
+ body.sdkVersion = SDK_VERSION;
3733
+ if (requestData.callerMetadata || requestData.clientIp || requestData.userAgent) {
3734
+ const meta = {
3735
+ ...requestData.clientIp && { sourceIp: requestData.clientIp },
3736
+ ...requestData.userAgent && { userAgent: requestData.userAgent },
3737
+ ...requestData.callerMetadata
3738
+ };
3739
+ if (Object.keys(meta).length > 0) body.callerMetadata = meta;
3740
+ }
3741
+ const headers = {
3742
+ "Content-Type": "application/json",
3743
+ ...config.customHeaders
3744
+ };
3745
+ if (config.apiKey) {
3746
+ headers["Authorization"] = `Bearer ${config.apiKey}`;
3747
+ headers["X-API-Key"] = config.apiKey;
3748
+ }
3749
+ try {
3750
+ const response = await fetch(`${config.apiBaseUrl}/agents/verify-access`, {
3751
+ method: "POST",
3752
+ headers,
3753
+ body: JSON.stringify(body)
3754
+ });
3755
+ const data = await response.json();
3756
+ if (response.status === 410) {
3757
+ return {
3758
+ success: true,
3759
+ access: {
3760
+ allowed: false,
3761
+ accessLevel: "none",
3762
+ reason: "endpoint_deactivated",
3763
+ failures: [
3764
+ {
3765
+ dimension: "endpoint.deactivated",
3766
+ message: typeof data?.message === "string" ? data.message : "Endpoint has been deactivated",
3767
+ guidance: typeof data?.guidance === "string" ? data.guidance : "Reactivate via POST /api/endpoints/{id}/reactivate, or update the URL on the calling agent."
3768
+ }
3769
+ ]
3770
+ }
3771
+ };
3772
+ }
3773
+ if (!response.ok) {
3774
+ return {
3775
+ success: false,
3776
+ error: data.message || data.error || `API returned ${response.status}`,
3777
+ correlationId: typeof data?.correlationId === "string" ? data.correlationId : void 0
3778
+ };
3779
+ }
3780
+ return data;
3781
+ } catch (error) {
3782
+ const message = error instanceof Error ? error.message : "Unknown error";
3783
+ return {
3784
+ success: false,
3785
+ error: `Failed to call verify-access API: ${message}`
3786
+ };
3787
+ }
3788
+ }
3789
+ async function verify(config, request, options) {
3790
+ const mergedConfig = { ...DEFAULT_CONFIG, ...config };
3791
+ const urls = mergedConfig.apiBaseUrl ? getCachedWellKnownUrls(mergedConfig.apiBaseUrl) : void 0;
3792
+ if (!initCheckPerformed && !mergedConfig.disableInitChecks && mergedConfig.apiBaseUrl) {
3793
+ if (mergedConfig.strictInit) {
3794
+ await performInitCheck(mergedConfig.apiBaseUrl, mergedConfig.debug, true);
3795
+ } else {
3796
+ void performInitCheck(mergedConfig.apiBaseUrl, mergedConfig.debug, false);
3797
+ }
3798
+ }
3799
+ if (!deprecationWarningShown && (config.minTrustScore !== void 0 || config.minTrustScoreForFull !== void 0)) {
3800
+ deprecationWarningShown = true;
3801
+ console.warn(
3802
+ "[VerificationGateway] minTrustScore / minTrustScoreForFull are deprecated in v2.3.0 and have no effect. Server is now the single source of truth for access-level decisions (the SDK reads access.accessLevel from the verify-access response). To gate access to an endpoint, configure the endpoint's trust_score_requirement server-side."
3803
+ );
3804
+ }
3805
+ if (mergedConfig.cacheTtl !== 0 && !options?.bypassCache) {
3806
+ const cached = getCachedResult(request, mergedConfig.counterpartyId);
3807
+ if (cached) {
3808
+ if (mergedConfig.debug) {
3809
+ console.log("[VerificationGateway] Returning cached result");
3810
+ }
3811
+ return cached;
3812
+ }
3813
+ }
3814
+ const enrichedRequest = { ...request };
3815
+ if (!enrichedRequest.counterpartyUrl && mergedConfig.counterpartyUrl) {
3816
+ enrichedRequest.counterpartyUrl = mergedConfig.counterpartyUrl;
3817
+ }
3818
+ if (!enrichedRequest.counterpartyType && mergedConfig.counterpartyType) {
3819
+ enrichedRequest.counterpartyType = mergedConfig.counterpartyType;
3820
+ }
3821
+ if (mergedConfig.debug) {
3822
+ console.log("[VerificationGateway] Calling verify-access API");
3823
+ }
3824
+ const apiResponse = await callVerifyAccessAPI(mergedConfig, enrichedRequest);
3825
+ const rawServerDenialReasons = apiResponse.denialReasons;
3826
+ const serverDenialReasons = Array.isArray(rawServerDenialReasons) && rawServerDenialReasons.length > 0 ? rawServerDenialReasons : void 0;
3827
+ if (!apiResponse.success) {
3828
+ return createGuidanceResponse(mergedConfig, apiResponse.error, {
3829
+ source: "api_error",
3830
+ correlationId: apiResponse.correlationId,
3831
+ urls
3832
+ });
3833
+ }
3834
+ if (!apiResponse.access?.allowed) {
3835
+ const aggregatedFailures = apiResponse.access?.failures;
3836
+ const idVerifiedFromBackend = apiResponse.verificationContext?.idVerified === true;
3837
+ const result2 = {
3838
+ identityVerified: idVerifiedFromBackend,
3839
+ policyAllowed: false,
3840
+ // v2.3.9 (defect #30): denials grant `'none'`, NEVER a positive band.
3841
+ // Pre-rename this hardcoded `'guidance'`, which conflated with the
3842
+ // colocated `guidance: {...}` help-payload object below and let
3843
+ // denied requests pass any route gated at `'guidance'` because
3844
+ // `hasMinimumAccess('guidance', 'guidance') === true`. Adapters now
3845
+ // ALSO short-circuit on `!identityVerified || !policyAllowed` before
3846
+ // the gate check — belt-and-braces.
3847
+ accessLevel: "none",
3848
+ // 3.6.0: the server now emits top-level denialReasons on every deny
3849
+ // path — prefer it verbatim; the failure-message reconstruction remains
3850
+ // as the fallback for older backends.
3851
+ denialReasons: serverDenialReasons ?? (aggregatedFailures && aggregatedFailures.length > 0 ? aggregatedFailures.map((f) => f.message) : apiResponse.access?.reason ? [apiResponse.access.reason] : ["Access denied"]),
3852
+ failures: aggregatedFailures,
3853
+ requiresStepUp: apiResponse.access?.requiresStepUp,
3854
+ requiresApproval: apiResponse.access?.requiresApproval,
3855
+ guidance: {
3856
+ message: apiResponse.access?.reason || "Access denied by PDLSS policy",
3857
+ registrationUrl: urls?.registrationUrl ?? "",
3858
+ documentationUrl: urls?.documentationUrl ?? ""
3859
+ },
3860
+ verifiedAt: /* @__PURE__ */ new Date(),
3861
+ // Extract sessionId so decisions can be recorded for denials too
3862
+ sessionId: apiResponse.sessionId,
3863
+ // Anonymous traffic has no session → correlationId is the per-attempt
3864
+ // linking key (the sessionId-equivalent for anonymous callers).
3865
+ correlationId: apiResponse.correlationId,
3866
+ recommendation: apiResponse.recommendation,
3867
+ recommendationReasons: apiResponse.recommendationReasons,
3868
+ stepUpApproval: apiResponse.stepUpApproval,
3869
+ settlement: apiResponse.settlement
3870
+ };
3871
+ return result2;
3872
+ }
3873
+ const agent = apiResponse.agent ? {
3874
+ astraId: apiResponse.agent.astraId,
3875
+ name: apiResponse.agent.name,
3876
+ trustScore: apiResponse.agent.trustScore,
3877
+ trustLevel: getTrustLevel(apiResponse.agent.trustScore),
3878
+ blockchainVerified: apiResponse.agent.blockchainStatus === "verified",
3879
+ status: apiResponse.agent.agentStatus
3880
+ } : void 0;
3881
+ const developer = apiResponse.developer ? {
3882
+ astradId: apiResponse.developer.kyaOwnerId,
3883
+ name: apiResponse.developer.fullName,
3884
+ trustScore: apiResponse.developer.trustScore || 0,
3885
+ verified: apiResponse.developer.identityVerified
3886
+ } : void 0;
3887
+ const organization = apiResponse.organization ? {
3888
+ name: apiResponse.organization.name,
3889
+ verified: apiResponse.organization.verified,
3890
+ trustScore: apiResponse.organization.trustScore
3891
+ } : void 0;
3892
+ const verificationContext = apiResponse.verificationContext;
3893
+ const accessLevel = apiResponse.access?.accessLevel ?? "standard";
3894
+ const result = {
3895
+ // Round-18 G4: backend allowed access. Identity is verified (we resolved
3896
+ // the caller to an agent) and policy passed all gates. Read idVerified
3897
+ // from verificationContext for symmetry with the deny branch; default true
3898
+ // on success path since `access.allowed === true` implies identity was
3899
+ // resolvable (anonymous-allow paths flow through createGuidanceResponse).
3900
+ identityVerified: apiResponse.verificationContext?.idVerified !== false,
3901
+ policyAllowed: true,
3902
+ accessLevel,
3903
+ agent,
3904
+ developer,
3905
+ organization,
3906
+ appliedPolicy: apiResponse.access?.appliedPolicy,
3907
+ verificationContext,
3908
+ requiresStepUp: apiResponse.access?.requiresStepUp,
3909
+ requiresApproval: apiResponse.access?.requiresApproval,
3910
+ verifiedAt: /* @__PURE__ */ new Date(),
3911
+ cacheTtl: mergedConfig.cacheTtl,
3912
+ // Handshake Protocol v10 enhanced fields (present when backend returns them)
3913
+ sessionId: apiResponse.sessionId,
3914
+ // v2.3.10 (defect #34, round-4): anonymous responses surface correlationId
3915
+ // (no session row exists for unverified callers).
3916
+ correlationId: apiResponse.correlationId,
3917
+ runtimeChallenge: apiResponse.runtimeChallenge,
3918
+ tokenGuidance: apiResponse.tokenGuidance,
3919
+ recommendation: apiResponse.recommendation,
3920
+ recommendationReasons: apiResponse.recommendationReasons,
3921
+ warningHeader: apiResponse.warningHeader,
3922
+ stepUpApproval: apiResponse.stepUpApproval,
3923
+ settlement: apiResponse.settlement
3924
+ };
3925
+ if (result.recommendation === "deny") {
3926
+ result.policyAllowed = false;
3927
+ result.accessLevel = "none";
3928
+ result.denialReasons = serverDenialReasons ?? result.recommendationReasons ?? ["Access denied by AstraSync recommendation"];
3929
+ result.guidance = result.runtimeChallenge ? {
3930
+ message: `Verification failed: ${result.runtimeChallenge.reason || "runtime challenge failed"}`,
3931
+ registrationUrl: urls?.registrationUrl ?? "",
3932
+ documentationUrl: urls?.documentationUrl ?? ""
3933
+ } : {
3934
+ message: result.recommendationReasons?.[0] || "Access denied by AstraSync recommendation",
3935
+ registrationUrl: urls?.registrationUrl ?? "",
3936
+ documentationUrl: urls?.documentationUrl ?? ""
3937
+ };
3938
+ } else if (result.recommendation === "step_up_required") {
3939
+ result.requiresStepUp = true;
3940
+ result.denialReasons = serverDenialReasons ?? result.recommendationReasons ?? ["Step-up verification required"];
3941
+ }
3942
+ const escalates = result.requiresStepUp === true || result.requiresApproval === true || result.recommendation === "step_up_required";
3943
+ if (mergedConfig.cacheTtl !== 0 && result.recommendation !== "deny" && !escalates) {
3944
+ cacheResult(request, result, mergedConfig.cacheTtl, mergedConfig.counterpartyId);
3945
+ }
3946
+ return result;
3947
+ }
3948
+
3949
+ // src/adapters/stepup-poll.ts
3950
+ var FALLBACK_MAX_WAIT_MS = 5 * 60 * 1e3;
3951
+
3952
+ // src/adapters/express.ts
3953
+ var DEFAULT_ROUTES_REFRESH_MS = 5 * 60 * 1e3;
3954
+
3955
+ // src/adapters/nextjs.ts
3956
+ var DEFAULT_ROUTES_REFRESH_MS2 = 5 * 60 * 1e3;
3957
+
3958
+ // src/transport/rfc9421.ts
3959
+ var import_structured_headers = require("structured-headers");
3960
+
3961
+ // src/transport/rfc9421-verify.ts
3962
+ var import_http_message_signatures = require("http-message-signatures");
3963
+
3964
+ // src/transport/nonce-store.ts
3965
+ var InMemoryNonceStore = class {
3966
+ constructor(capacity = 1e4) {
3967
+ this.entries = /* @__PURE__ */ new Map();
3968
+ this.lastSweepMs = 0;
3969
+ this.capacity = capacity;
3970
+ }
3971
+ seen(key, expiresAtMs) {
3972
+ const nowMs = Date.now();
3973
+ if (nowMs - this.lastSweepMs > 1e3) {
3974
+ for (const [k, exp] of this.entries) {
3975
+ if (exp <= nowMs) this.entries.delete(k);
3976
+ }
3977
+ this.lastSweepMs = nowMs;
3978
+ }
3979
+ const existing = this.entries.get(key);
3980
+ if (existing !== void 0 && existing > nowMs) {
3981
+ return true;
3982
+ }
3983
+ if (this.entries.size >= this.capacity) {
3984
+ const oldest = this.entries.keys().next().value;
3985
+ if (oldest !== void 0) this.entries.delete(oldest);
3986
+ }
3987
+ this.entries.set(key, expiresAtMs);
3988
+ return false;
3989
+ }
3990
+ };
3991
+ var defaultNonceStore = new InMemoryNonceStore();
3992
+
3993
+ // src/transport/vi.ts
3994
+ var import_decode = require("@sd-jwt/decode");
3995
+ var import_node_crypto = require("crypto");
3996
+
3997
+ // src/transport/stripe-webhook.ts
3998
+ var import_node_crypto2 = require("crypto");
3999
+
4000
+ // src/transport/ap2.ts
4001
+ var import_decode2 = require("@sd-jwt/decode");
4002
+ var import_node_crypto3 = require("crypto");
4003
+
4004
+ // src/transport/mpp.ts
4005
+ var import_mppx = require("mppx");
4006
+
4007
+ // src/transport/mpp-verify.ts
4008
+ var import_mppx2 = require("mppx");
4009
+
4010
+ // src/transport/x402.ts
4011
+ var import_schemas = require("@x402/core/schemas");
4012
+ var import_utils = require("@x402/core/utils");
4013
+
4014
+ // src/transport/vi-verify.ts
4015
+ var import_node_crypto4 = require("crypto");
4016
+
4017
+ // src/transport/registry/visa.ts
4018
+ var import_jose = require("jose");
4019
+
4020
+ // src/gateway/modes/online.ts
4021
+ function toGatewayConfig(config) {
4022
+ return {
4023
+ apiBaseUrl: config.apiBaseUrl || "https://api.astrasync.ai",
4024
+ apiKey: config.apiKey,
4025
+ defaultAccessLevel: config.defaultAccessLevel,
4026
+ minTrustScore: config.minTrustScore,
4027
+ minTrustScoreForFull: config.minTrustScoreForFull,
4028
+ cacheTtl: config.cacheTtl,
4029
+ debug: config.debug,
4030
+ customHeaders: config.customHeaders,
4031
+ counterpartyUrl: config.counterpartyUrl,
4032
+ counterpartyType: config.counterpartyType
4033
+ };
4034
+ }
4035
+ function toVerificationRequest(context, astraId) {
4036
+ return {
4037
+ credentials: { astraId },
4038
+ purpose: context.purpose,
4039
+ action: context.action,
4040
+ resourceType: context.resourceType,
4041
+ resource: context.target,
4042
+ transactionValue: context.transactionValue,
4043
+ currency: context.currency,
4044
+ createSession: true
4045
+ };
4046
+ }
4047
+ function toDecision(result) {
4048
+ if (result.identityVerified && result.policyAllowed) {
4049
+ return {
4050
+ recommendation: "ALLOW",
4051
+ reason: `Verified with access level: ${result.accessLevel}`,
4052
+ trustScore: result.agent?.trustScore,
4053
+ sessionId: "sessionId" in result ? result.sessionId : void 0
4054
+ };
4055
+ }
4056
+ if (result.requiresStepUp || result.requiresApproval) {
4057
+ return {
4058
+ recommendation: "MANUAL_REVIEW",
4059
+ reason: result.denialReasons?.[0] || "Step-up or approval required",
4060
+ trustScore: result.agent?.trustScore
4061
+ };
4062
+ }
4063
+ return {
4064
+ recommendation: "DENY",
4065
+ reason: result.denialReasons?.[0] || "Access denied",
4066
+ trustScore: result.agent?.trustScore
4067
+ };
4068
+ }
4069
+ async function verifyOnline(config, context, astraId) {
4070
+ const gatewayConfig = toGatewayConfig(config);
4071
+ const request = toVerificationRequest(context, astraId);
4072
+ const result = await verify(gatewayConfig, request);
4073
+ return toDecision(result);
4074
+ }
4075
+
4076
+ // src/gateway/modes/hybrid.ts
4077
+ var import_fs2 = require("fs");
4078
+ var import_path = require("path");
4079
+ var MAX_QUEUE_SIZE = 1e3;
4080
+ var MAX_RETRIES = 3;
4081
+ var HybridSyncQueue = class {
4082
+ constructor(config, persistPath) {
4083
+ this.queue = [];
4084
+ this.timer = null;
4085
+ this.processing = false;
4086
+ this.persistPath = null;
4087
+ this.config = config;
4088
+ this.persistPath = persistPath ?? null;
4089
+ this.loadFromDisk();
4090
+ }
4091
+ /**
4092
+ * Start periodic sync.
4093
+ */
4094
+ start(intervalMs) {
4095
+ if (this.timer) return;
4096
+ this.timer = setInterval(() => this.flush(), intervalMs);
4097
+ }
4098
+ /**
4099
+ * Stop periodic sync and flush remaining entries.
4100
+ */
4101
+ async stop() {
4102
+ if (this.timer) {
4103
+ clearInterval(this.timer);
4104
+ this.timer = null;
4105
+ }
4106
+ await this.flush();
4107
+ this.saveToDisk();
4108
+ }
4109
+ /**
4110
+ * Add a decision to the sync queue.
4111
+ */
4112
+ enqueue(context, decision) {
4113
+ if (this.queue.length >= MAX_QUEUE_SIZE) {
4114
+ this.queue.shift();
4115
+ }
4116
+ this.queue.push({
4117
+ id: `${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,
4118
+ context,
4119
+ decision,
4120
+ timestamp: /* @__PURE__ */ new Date(),
4121
+ retryCount: 0,
4122
+ status: "pending"
4123
+ });
4124
+ this.saveToDisk();
4125
+ }
4126
+ /**
4127
+ * Flush pending entries to the API.
4128
+ */
4129
+ async flush() {
4130
+ if (this.processing) return;
4131
+ this.processing = true;
4132
+ try {
4133
+ const pending = this.queue.filter((e) => e.status === "pending");
4134
+ for (const entry of pending) {
4135
+ try {
4136
+ await verifyOnline(this.config, entry.context);
4137
+ entry.status = "synced";
4138
+ } catch {
4139
+ entry.retryCount++;
4140
+ if (entry.retryCount >= MAX_RETRIES) {
4141
+ entry.status = "failed";
4142
+ }
4143
+ }
4144
+ }
4145
+ this.queue = this.queue.filter((e) => e.status === "pending");
4146
+ this.saveToDisk();
4147
+ } finally {
4148
+ this.processing = false;
4149
+ }
4150
+ }
4151
+ /**
4152
+ * Get queue status.
4153
+ */
4154
+ getStatus() {
4155
+ return {
4156
+ pending: this.queue.filter((e) => e.status === "pending").length,
4157
+ total: this.queue.length
4158
+ };
4159
+ }
4160
+ /**
4161
+ * Load persisted queue entries from disk.
4162
+ */
4163
+ loadFromDisk() {
4164
+ if (!this.persistPath) return;
4165
+ try {
4166
+ if (!(0, import_fs2.existsSync)(this.persistPath)) return;
4167
+ const data = (0, import_fs2.readFileSync)(this.persistPath, "utf-8");
4168
+ const entries = JSON.parse(data);
4169
+ this.queue = entries.filter((e) => e.status === "pending").map((e) => ({ ...e, timestamp: new Date(e.timestamp) }));
4170
+ } catch {
4171
+ this.queue = [];
4172
+ }
4173
+ }
4174
+ /**
4175
+ * Persist queue entries to disk.
4176
+ */
4177
+ saveToDisk() {
4178
+ if (!this.persistPath) return;
4179
+ try {
4180
+ const dir = (0, import_path.dirname)(this.persistPath);
4181
+ if (!(0, import_fs2.existsSync)(dir)) (0, import_fs2.mkdirSync)(dir, { recursive: true });
4182
+ (0, import_fs2.writeFileSync)(this.persistPath, JSON.stringify(this.queue, null, 2), "utf-8");
4183
+ } catch {
4184
+ }
4185
+ }
4186
+ };
4187
+ function verifyHybrid(evaluator, syncQueue, context) {
4188
+ const decision = evaluator.evaluate(context);
4189
+ syncQueue.enqueue(context, decision);
4190
+ return decision;
4191
+ }
4192
+
4193
+ // src/gateway/trace-logger.ts
4194
+ var import_fs3 = require("fs");
4195
+ var import_path2 = require("path");
4196
+ var MAX_FILE_SIZE = 10 * 1024 * 1024;
4197
+ var MAX_FILES = 10;
4198
+ var TraceLogger = class {
4199
+ constructor(tracePath, enabled) {
4200
+ this.tracePath = tracePath;
4201
+ this.enabled = enabled;
4202
+ if (enabled) {
4203
+ (0, import_fs3.mkdirSync)(tracePath, { recursive: true });
4204
+ }
4205
+ }
4206
+ /**
4207
+ * Log an evaluation event.
4208
+ */
4209
+ logEvaluation(context, decision) {
4210
+ if (!this.enabled) return;
4211
+ this.write({
4212
+ id: this.generateId(),
4213
+ timestamp: /* @__PURE__ */ new Date(),
4214
+ type: "evaluation",
4215
+ context,
4216
+ decision
4217
+ });
4218
+ }
4219
+ /**
4220
+ * Log a mode switch event.
4221
+ */
4222
+ logModeSwitch(from, to) {
4223
+ if (!this.enabled) return;
4224
+ this.write({
4225
+ id: this.generateId(),
4226
+ timestamp: /* @__PURE__ */ new Date(),
4227
+ type: "mode_switch",
4228
+ metadata: { from, to }
4229
+ });
4230
+ }
4231
+ /**
4232
+ * Log an error event.
4233
+ */
4234
+ logError(error, context) {
4235
+ if (!this.enabled) return;
4236
+ this.write({
4237
+ id: this.generateId(),
4238
+ timestamp: /* @__PURE__ */ new Date(),
4239
+ type: "error",
4240
+ context,
4241
+ metadata: { error }
4242
+ });
4243
+ }
4244
+ write(event) {
4245
+ try {
4246
+ const filePath = this.getCurrentFilePath();
4247
+ const line = JSON.stringify(event) + "\n";
4248
+ if ((0, import_fs3.existsSync)(filePath)) {
4249
+ const stats = (0, import_fs3.statSync)(filePath);
4250
+ if (stats.size > MAX_FILE_SIZE) {
4251
+ this.rotate();
4252
+ }
4253
+ }
4254
+ (0, import_fs3.appendFileSync)(filePath, line);
4255
+ } catch {
4256
+ }
4257
+ }
4258
+ getCurrentFilePath() {
4259
+ const date = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
4260
+ return (0, import_path2.join)(this.tracePath, `trace-${date}.jsonl`);
4261
+ }
4262
+ rotate() {
4263
+ try {
4264
+ const files = (0, import_fs3.readdirSync)(this.tracePath).filter((f) => f.startsWith("trace-") && f.endsWith(".jsonl")).sort();
4265
+ while (files.length >= MAX_FILES) {
4266
+ const oldest = files.shift();
4267
+ (0, import_fs3.unlinkSync)((0, import_path2.join)(this.tracePath, oldest));
4268
+ }
4269
+ } catch {
4270
+ }
4271
+ }
4272
+ generateId() {
4273
+ return `${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
4274
+ }
4275
+ };
4276
+
4277
+ // src/gateway/gateway.ts
4278
+ var AstraSyncGateway = class {
4279
+ constructor(config) {
4280
+ this.evaluator = null;
4281
+ this.syncQueue = null;
4282
+ this.traceLogger = null;
4283
+ this.initialized = false;
4284
+ this.config = config;
4285
+ this.validateConfig();
4286
+ }
4287
+ validateConfig() {
4288
+ const { mode } = this.config;
4289
+ if (mode === "online") {
4290
+ if (!this.config.apiBaseUrl && !this.config.apiKey) {
4291
+ throw new Error("Online mode requires apiBaseUrl or apiKey");
4292
+ }
4293
+ }
4294
+ if (mode === "local") {
4295
+ if (!this.config.policyFile && !this.config.policy) {
4296
+ throw new Error("Local mode requires policyFile or policy");
4297
+ }
4298
+ }
4299
+ if (mode === "hybrid") {
4300
+ if (!this.config.policyFile && !this.config.policy) {
4301
+ throw new Error("Hybrid mode requires policyFile or policy");
4302
+ }
4303
+ }
4304
+ }
4305
+ /**
4306
+ * Initialize the gateway (loads policy files, starts sync queues).
4307
+ * Called automatically on first evaluate() if not called manually.
4308
+ */
4309
+ async initialize() {
4310
+ if (this.initialized) return;
4311
+ const { mode } = this.config;
4312
+ if (mode === "local" || mode === "hybrid") {
4313
+ this.evaluator = loadEvaluator(this.config);
4314
+ }
4315
+ if (mode === "hybrid") {
4316
+ const persistPath = this.config.tracePath ? `${this.config.tracePath}/../sync-queue.json` : ".astrasync/sync-queue.json";
4317
+ this.syncQueue = new HybridSyncQueue(this.config, persistPath);
4318
+ const intervalMs = (this.config.syncInterval || 3600) * 1e3;
4319
+ this.syncQueue.start(intervalMs);
4320
+ }
4321
+ if (this.config.traceEnabled) {
4322
+ const tracePath = this.config.tracePath || ".astrasync/traces";
4323
+ this.traceLogger = new TraceLogger(tracePath, true);
4324
+ }
4325
+ this.initialized = true;
4326
+ if (this.config.debug) {
4327
+ const posture = this.config.posture || "active";
4328
+ console.log(`[AstraSyncGateway] Initialized in ${mode} mode (${posture})`);
4329
+ }
4330
+ }
4331
+ /**
4332
+ * Graceful shutdown. Flushes sync queue and cleans up resources.
4333
+ */
4334
+ async shutdown() {
4335
+ if (this.syncQueue) {
4336
+ await this.syncQueue.stop();
4337
+ this.syncQueue = null;
4338
+ }
4339
+ this.evaluator = null;
4340
+ this.initialized = false;
4341
+ if (this.config.debug) {
4342
+ console.log("[AstraSyncGateway] Shut down");
4343
+ }
4344
+ }
4345
+ /**
4346
+ * Evaluate an action against the verification policy.
4347
+ * Routes to the appropriate mode handler.
4348
+ *
4349
+ * In passive posture, evaluation runs but always returns ALLOW
4350
+ * (the real decision is logged for telemetry).
4351
+ */
4352
+ async evaluate(context, astraId) {
4353
+ if (!this.initialized) {
4354
+ await this.initialize();
4355
+ }
4356
+ let decision;
4357
+ switch (this.config.mode) {
4358
+ case "online":
4359
+ decision = await verifyOnline(this.config, context, astraId);
4360
+ break;
4361
+ case "local":
4362
+ if (!this.evaluator) throw new Error("Local evaluator not initialized");
4363
+ decision = verifyLocal(this.evaluator, context);
4364
+ break;
4365
+ case "hybrid":
4366
+ if (!this.evaluator || !this.syncQueue) throw new Error("Hybrid mode not initialized");
4367
+ decision = verifyHybrid(this.evaluator, this.syncQueue, context);
4368
+ break;
4369
+ default:
4370
+ throw new Error(`Unknown mode: ${this.config.mode}`);
4371
+ }
4372
+ if (this.config.posture === "passive" && decision.recommendation !== "ALLOW") {
4373
+ decision = {
4374
+ ...decision,
4375
+ recommendation: "ALLOW",
4376
+ reason: `[PASSIVE] Would have been ${decision.recommendation}: ${decision.reason}`
4377
+ };
4378
+ }
4379
+ this.traceLogger?.logEvaluation(context, decision);
4380
+ return decision;
4381
+ }
4382
+ /**
4383
+ * Get the current mode.
4384
+ */
4385
+ get mode() {
4386
+ return this.config.mode;
4387
+ }
4388
+ /**
4389
+ * Get the current posture (active or passive).
4390
+ */
4391
+ get posture() {
4392
+ return this.config.posture || "active";
4393
+ }
4394
+ /**
4395
+ * Switch modes at runtime (e.g. after upgrade from free to paid).
4396
+ */
4397
+ async switchMode(newMode, additionalConfig) {
4398
+ const oldMode = this.config.mode;
4399
+ await this.shutdown();
4400
+ this.config = { ...this.config, ...additionalConfig, mode: newMode };
4401
+ this.validateConfig();
4402
+ await this.initialize();
4403
+ this.traceLogger?.logModeSwitch(oldMode, newMode);
4404
+ if (this.config.debug) {
4405
+ console.log(`[AstraSyncGateway] Switched to ${newMode} mode`);
4406
+ }
4407
+ }
4408
+ /**
4409
+ * Get sync queue status (hybrid mode only).
4410
+ */
4411
+ getSyncStatus() {
4412
+ return this.syncQueue?.getStatus() || null;
4413
+ }
4414
+ };
4415
+
4416
+ // src/adapter-interface/interface.ts
4417
+ var ADAPTER_INTERFACE_VERSION = 1;
4418
+
4419
+ // src/adapter-interface/purpose-mapping.ts
4420
+ var TOOL_PURPOSE_MAP = {
4421
+ // Shell
4422
+ shell_exec: "shell.exec",
4423
+ run_command: "shell.exec",
4424
+ execute: "shell.exec",
4425
+ terminal_exec: "shell.exec",
4426
+ run_terminal_command: "shell.exec",
4427
+ // File read
4428
+ file_read: "file.read",
4429
+ read_file: "file.read",
4430
+ // File write
4431
+ file_write: "file.write",
4432
+ write_file: "file.write",
4433
+ create_file: "file.write",
4434
+ edit_file: "file.write",
4435
+ // File delete
4436
+ file_delete: "file.delete",
4437
+ delete_file: "file.delete",
4438
+ // Network
4439
+ http_request: "network.request",
4440
+ fetch: "network.request",
4441
+ web_request: "network.request",
4442
+ // Email
4443
+ send_email: "email.send",
4444
+ read_email: "email.read",
4445
+ // Calendar
4446
+ create_event: "calendar.create",
4447
+ // Database
4448
+ query_database: "database.query",
4449
+ write_database: "database.write",
4450
+ // Payment
4451
+ payment_execute: "payment.execute"
4452
+ };
4453
+ function mapToolToPurpose(toolName) {
4454
+ return TOOL_PURPOSE_MAP[toolName] || `tool.${toolName}`;
4455
+ }
4456
+ function registerToolMappings(mappings) {
4457
+ for (const [tool, purpose] of Object.entries(mappings)) {
4458
+ if (!(tool in TOOL_PURPOSE_MAP)) {
4459
+ TOOL_PURPOSE_MAP[tool] = purpose;
4460
+ }
4461
+ }
4462
+ }
4463
+ function extractTarget(toolName, args) {
4464
+ const purpose = mapToolToPurpose(toolName);
4465
+ if (purpose.startsWith("shell.")) {
4466
+ return String(args.command || args.cmd || args.script || "");
4467
+ }
4468
+ if (purpose.startsWith("file.")) {
4469
+ return String(args.path || args.file || args.filename || args.file_path || "");
4470
+ }
4471
+ if (purpose.startsWith("network.")) {
4472
+ return String(args.url || args.endpoint || args.uri || "");
4473
+ }
4474
+ if (purpose.startsWith("email.")) {
4475
+ return String(args.to || args.recipient || args.address || "");
4476
+ }
4477
+ if (purpose.startsWith("database.")) {
4478
+ return String(args.query || args.table || "");
4479
+ }
4480
+ if (purpose.startsWith("payment.")) {
4481
+ return String(args.description || args.merchant || args.amount || "");
4482
+ }
4483
+ if (args.command) return String(args.command);
4484
+ if (args.path) return String(args.path);
4485
+ if (args.url) return String(args.url);
4486
+ for (const val of Object.values(args)) {
4487
+ if (typeof val === "string" && val.length > 0) return val;
4488
+ }
4489
+ return toolName;
4490
+ }
4491
+ function extractNetworkDomains(target) {
4492
+ try {
4493
+ if (target.startsWith("http://") || target.startsWith("https://")) {
4494
+ const url = new URL(target);
4495
+ return [url.hostname];
4496
+ }
4497
+ } catch {
4498
+ }
4499
+ return void 0;
4500
+ }
4501
+
4502
+ // src/claude-code/tool-mapping.ts
4503
+ var CLAUDE_CODE_TOOL_MAP = {
4504
+ Bash: "shell.exec",
4505
+ Write: "file.write",
4506
+ Edit: "file.write",
4507
+ MultiEdit: "file.write",
4508
+ NotebookEdit: "file.write",
4509
+ Read: "file.read",
4510
+ Glob: "file.read",
4511
+ Grep: "file.read",
4512
+ WebFetch: "network.request",
4513
+ WebSearch: "network.request",
4514
+ Task: "sub_agent.spawn",
4515
+ Agent: "sub_agent.spawn"
4516
+ };
4517
+ var registered = false;
4518
+ function registerClaudeCodeMappings() {
4519
+ if (registered) return;
4520
+ registerToolMappings(CLAUDE_CODE_TOOL_MAP);
4521
+ registered = true;
4522
+ }
4523
+ function mapMcpTool(toolName) {
4524
+ const match = /^mcp__(.+?)__(.+)$/.exec(toolName);
4525
+ if (!match) return null;
4526
+ return `${match[1]}.${match[2]}`;
4527
+ }
4528
+
4529
+ // src/claude-code/claude-code-adapter.ts
4530
+ var DEFAULT_SKIP_TOOLS = [
4531
+ "TodoWrite",
4532
+ "TaskCreate",
4533
+ "TaskUpdate",
4534
+ "TaskList",
4535
+ "TaskGet",
4536
+ "ExitPlanMode",
4537
+ "EnterPlanMode",
4538
+ "AskUserQuestion",
4539
+ "BashOutput",
4540
+ "KillShell",
4541
+ "TaskStop",
4542
+ "TaskOutput",
4543
+ "ListMcpResourcesTool"
4544
+ ];
4545
+ var ClaudeCodeAdapter = class {
4546
+ constructor(options) {
4547
+ this.interfaceVersion = ADAPTER_INTERFACE_VERSION;
4548
+ this._isRunning = false;
4549
+ this.skipTools = new Set(options?.skipTools ?? DEFAULT_SKIP_TOOLS);
4550
+ this.strictUnmapped = options?.strictUnmapped ?? false;
4551
+ this.governMcp = options?.governMcp ?? true;
4552
+ registerClaudeCodeMappings();
4553
+ }
4554
+ get isRunning() {
4555
+ return this._isRunning;
4556
+ }
4557
+ async initialize(config) {
4558
+ this.gateway = config.gateway;
4559
+ if (Array.isArray(config.adapterOptions.skipTools)) {
4560
+ this.skipTools = new Set(config.adapterOptions.skipTools);
4561
+ }
4562
+ if (typeof config.adapterOptions.strictUnmapped === "boolean") {
4563
+ this.strictUnmapped = config.adapterOptions.strictUnmapped;
4564
+ }
4565
+ this._isRunning = true;
4566
+ }
4567
+ async shutdown() {
4568
+ this._isRunning = false;
4569
+ }
4570
+ async interceptAction(action) {
4571
+ const raw = action.raw;
4572
+ if (!raw || typeof raw.tool_name !== "string" || raw.tool_name.length === 0) {
4573
+ return { intercepted: false, skipReason: "No tool_name in payload" };
4574
+ }
4575
+ if (this.skipTools.has(raw.tool_name)) {
4576
+ return { intercepted: false, skipReason: `Tool ${raw.tool_name} is not governed` };
4577
+ }
4578
+ const isMcp = mapMcpTool(raw.tool_name) !== null;
4579
+ if (isMcp && !this.governMcp) {
4580
+ return { intercepted: false, skipReason: `MCP tools not governed (governMcp off)` };
4581
+ }
4582
+ const isMapped = raw.tool_name in CLAUDE_CODE_TOOL_MAP || isMcp;
4583
+ if (!isMapped && !this.strictUnmapped) {
4584
+ return {
4585
+ intercepted: false,
4586
+ skipReason: `Unmapped tool ${raw.tool_name} (strictUnmapped off)`
4587
+ };
4588
+ }
4589
+ const context = this.extractContext(action);
4590
+ return { intercepted: true, context };
4591
+ }
4592
+ extractContext(action) {
4593
+ const raw = action.raw;
4594
+ const toolName = raw.tool_name;
4595
+ const args = raw.tool_input ?? {};
4596
+ const mcpPurpose = mapMcpTool(toolName);
4597
+ const purpose = mcpPurpose ?? mapToolToPurpose(toolName);
4598
+ const target = extractTarget(toolName, args);
4599
+ const networkAccess = extractNetworkDomains(target);
4600
+ return {
4601
+ purpose,
4602
+ action: toolName,
4603
+ target,
4604
+ ...networkAccess && { networkAccess },
4605
+ metadata: {
4606
+ ...raw.session_id && { sessionId: raw.session_id },
4607
+ ...raw.cwd && { cwd: raw.cwd },
4608
+ platform: "claude-code"
4609
+ }
4610
+ };
4611
+ }
4612
+ /**
4613
+ * Translate a gateway decision into hook stdout JSON.
4614
+ * Returns null on ALLOW — the hook stays silent and Claude Code's own
4615
+ * permission system remains in charge (strictly-tightening invariant).
4616
+ */
4617
+ decisionToHookOutput(decision) {
4618
+ switch (decision.recommendation) {
4619
+ case "DENY":
4620
+ return {
4621
+ hookSpecificOutput: {
4622
+ hookEventName: "PreToolUse",
4623
+ permissionDecision: "deny",
4624
+ permissionDecisionReason: `AstraSync Local Guard: ${decision.reason}`
4625
+ }
4626
+ };
4627
+ case "MANUAL_REVIEW":
4628
+ return {
4629
+ hookSpecificOutput: {
4630
+ hookEventName: "PreToolUse",
4631
+ permissionDecision: "ask",
4632
+ permissionDecisionReason: `AstraSync Local Guard requires approval: ${decision.reason}`
4633
+ }
4634
+ };
4635
+ case "ALLOW":
4636
+ return null;
4637
+ }
4638
+ }
4639
+ /**
4640
+ * Convenience for the hook entry: full payload → hook output (or null).
4641
+ */
4642
+ async evaluatePayload(payload) {
4643
+ const action = {
4644
+ raw: payload,
4645
+ platform: "claude-code",
4646
+ timestamp: /* @__PURE__ */ new Date()
4647
+ };
4648
+ const interception = await this.interceptAction(action);
4649
+ if (!interception.intercepted || !interception.context) return null;
4650
+ const decision = await this.gateway.evaluate(interception.context);
4651
+ return this.decisionToHookOutput(decision);
4652
+ }
4653
+ /**
4654
+ * Enforcement happens via the stdout JSON the hook prints (see
4655
+ * decisionToHookOutput); there is no in-process side to enforce on.
4656
+ */
4657
+ async enforceDecision(_decision) {
4658
+ }
4659
+ };
4660
+
4661
+ // src/claude-code/hook.ts
4662
+ var MAX_STDIN_BYTES = 1024 * 1024;
4663
+ var STDIN_TIMEOUT_MS = 5e3;
4664
+ function resolveGuardConfig(env, payloadCwd, home = (0, import_os.homedir)()) {
4665
+ const candidateRoots = [env.CLAUDE_PROJECT_DIR, payloadCwd, home].filter(
4666
+ (root) => typeof root === "string" && root.length > 0
4667
+ );
4668
+ for (const root of candidateRoots) {
4669
+ const guardDir = (0, import_path3.join)(root, ".astrasync");
4670
+ const policyFile = (0, import_path3.join)(guardDir, "policy.yaml");
4671
+ if (!(0, import_fs4.existsSync)(policyFile)) continue;
4672
+ let settings = {};
4673
+ const settingsFile = (0, import_path3.join)(guardDir, "guard.json");
4674
+ if ((0, import_fs4.existsSync)(settingsFile)) {
4675
+ try {
4676
+ settings = JSON.parse((0, import_fs4.readFileSync)(settingsFile, "utf-8"));
4677
+ } catch {
4678
+ settings = {};
4679
+ }
4680
+ }
4681
+ return { policyFile, guardDir, settings };
4682
+ }
4683
+ return null;
4684
+ }
4685
+ function denyOutput(reason) {
4686
+ return {
4687
+ hookSpecificOutput: {
4688
+ hookEventName: "PreToolUse",
4689
+ permissionDecision: "deny",
4690
+ permissionDecisionReason: reason
4691
+ }
4692
+ };
4693
+ }
4694
+ async function processHookPayload(payloadJson, options = {}) {
4695
+ const env = options.env ?? process.env;
4696
+ if (env.ASTRASYNC_GUARD_DISABLE === "1") {
4697
+ return { output: null, exitCode: 0 };
4698
+ }
4699
+ const envFailOpen = env.ASTRASYNC_GUARD_FAIL_OPEN === "1";
4700
+ let payload;
4701
+ try {
4702
+ payload = JSON.parse(payloadJson);
4703
+ } catch {
4704
+ if (envFailOpen) return { output: null, exitCode: 0 };
4705
+ return {
4706
+ output: denyOutput("AstraSync Local Guard: could not parse hook payload"),
4707
+ exitCode: 0
4708
+ };
4709
+ }
4710
+ const resolved = resolveGuardConfig(env, payload.cwd, options.home);
4711
+ if (!resolved) {
4712
+ return { output: null, exitCode: 0 };
4713
+ }
4714
+ const failOpen = envFailOpen || resolved.settings.failOpen === true;
4715
+ try {
4716
+ const gatewayConfig = {
4717
+ mode: "local",
4718
+ policyFile: resolved.policyFile,
4719
+ posture: resolved.settings.posture ?? "active",
4720
+ traceEnabled: true,
4721
+ tracePath: (0, import_path3.join)(resolved.guardDir, "traces"),
4722
+ debug: false
4723
+ };
4724
+ const gateway = options.gatewayFactory ? options.gatewayFactory(gatewayConfig) : new AstraSyncGateway(gatewayConfig);
4725
+ await gateway.initialize();
4726
+ const adapter = new ClaudeCodeAdapter({
4727
+ ...resolved.settings.skipTools && { skipTools: resolved.settings.skipTools },
4728
+ ...typeof resolved.settings.governMcp === "boolean" && {
4729
+ governMcp: resolved.settings.governMcp
4730
+ }
4731
+ });
4732
+ await adapter.initialize({ gateway, adapterOptions: {} });
4733
+ const output = await adapter.evaluatePayload(payload);
4734
+ await adapter.shutdown();
4735
+ await gateway.shutdown();
4736
+ return { output, exitCode: 0 };
4737
+ } catch (err) {
4738
+ if (failOpen) return { output: null, exitCode: 0 };
4739
+ const detail = err instanceof Error ? err.message : String(err);
4740
+ return {
4741
+ output: denyOutput(`AstraSync Local Guard: policy evaluation failed (${detail})`),
4742
+ exitCode: 0
4743
+ };
4744
+ }
4745
+ }
4746
+ function readStdin() {
4747
+ return new Promise((resolve) => {
4748
+ const chunks = [];
4749
+ let total = 0;
4750
+ let done = false;
4751
+ const finish = () => {
4752
+ if (done) return;
4753
+ done = true;
4754
+ clearTimeout(timer);
4755
+ resolve(Buffer.concat(chunks).toString("utf-8"));
4756
+ };
4757
+ const timer = setTimeout(finish, STDIN_TIMEOUT_MS);
4758
+ process.stdin.on("data", (chunk) => {
4759
+ total += chunk.length;
4760
+ if (total > MAX_STDIN_BYTES) {
4761
+ chunks.length = 0;
4762
+ chunks.push(Buffer.from("OVERSIZED_PAYLOAD"));
4763
+ finish();
4764
+ return;
4765
+ }
4766
+ chunks.push(chunk);
4767
+ });
4768
+ process.stdin.on("end", finish);
4769
+ process.stdin.on("error", finish);
4770
+ });
4771
+ }
4772
+ async function main() {
4773
+ console.log = (...args) => console.error(...args);
4774
+ const payloadJson = await readStdin();
4775
+ const result = await processHookPayload(payloadJson);
4776
+ if (result.output) {
4777
+ process.stdout.write(JSON.stringify(result.output));
4778
+ }
4779
+ process.exit(result.exitCode);
4780
+ }
4781
+ if (typeof require !== "undefined" && require.main === module) {
4782
+ main().catch((err) => {
4783
+ console.error(`AstraSync Local Guard hook crashed: ${err}`);
4784
+ process.exit(process.env.ASTRASYNC_GUARD_FAIL_OPEN === "1" ? 0 : 2);
4785
+ });
4786
+ }
4787
+ // Annotate the CommonJS export names for ESM import in node:
4788
+ 0 && (module.exports = {
4789
+ processHookPayload,
4790
+ resolveGuardConfig
4791
+ });