@fro.bot/systematic 2.33.2 → 3.0.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 (112) hide show
  1. package/ATTRIBUTIONS.md +1 -1
  2. package/agents/design/design-iterator.md +1 -0
  3. package/agents/research/best-practices-researcher.md +6 -8
  4. package/agents/review/pattern-recognition-specialist.md +1 -1
  5. package/agents/workflow/systematic-implementer.md +1 -0
  6. package/dist/cli.js +348 -53
  7. package/dist/{index-vyzhzvap.js → index-yskzf7vh.js} +587 -386
  8. package/dist/index.js +100 -155
  9. package/dist/lib/agent-overlays.d.ts +0 -1
  10. package/dist/lib/agent-resolver.d.ts +28 -0
  11. package/dist/lib/bootstrap.d.ts +8 -1
  12. package/dist/lib/bundled-names.d.ts +3 -3
  13. package/dist/lib/pi-delegate-session.d.ts +31 -0
  14. package/dist/lib/pi-delegate-tool.d.ts +42 -0
  15. package/dist/lib/removed-names.d.ts +3 -3
  16. package/dist/lib/setup.d.ts +36 -0
  17. package/dist/lib/skill-loader.d.ts +1 -2
  18. package/dist/lib/skill-resolver.d.ts +39 -0
  19. package/dist/lib/skill-tool.d.ts +2 -11
  20. package/dist/lib/skills.d.ts +1 -9
  21. package/dist/lib/source-model-defaults.d.ts +1 -1
  22. package/dist/pi.d.ts +7 -0
  23. package/dist/pi.js +3641 -0
  24. package/dist/schemas/systematic-config.schema.json +47 -242
  25. package/package.json +31 -8
  26. package/skills/ce-brainstorm/references/handoff.md +5 -26
  27. package/skills/ce-brainstorm/references/universal-brainstorming.md +0 -1
  28. package/skills/ce-compound/SKILL.md +8 -12
  29. package/skills/ce-ideate/references/post-ideation-workflow.md +21 -85
  30. package/skills/ce-plan/SKILL.md +6 -6
  31. package/skills/ce-plan/references/deepening-workflow.md +6 -7
  32. package/skills/ce-plan/references/plan-handoff.md +1 -17
  33. package/skills/ce-plan/references/universal-planning.md +0 -4
  34. package/skills/ce-review/SKILL.md +10 -19
  35. package/skills/ce-review/references/persona-catalog.md +2 -7
  36. package/skills/ce-review/references/review-output-template.md +0 -1
  37. package/skills/ce-work/SKILL.md +1 -1
  38. package/skills/deepen-plan/SKILL.md +6 -7
  39. package/skills/document-review/SKILL.md +2 -2
  40. package/skills/git-commit-push-pr/SKILL.md +1 -2
  41. package/skills/lfg/SKILL.md +1 -1
  42. package/skills/onboarding/SKILL.md +1 -12
  43. package/skills/orchestrating-subagents/SKILL.md +2 -2
  44. package/skills/slfg/SKILL.md +2 -3
  45. package/skills/test-browser/SKILL.md +2 -2
  46. package/skills/todos/SKILL.md +239 -0
  47. package/skills/writing-skills/SKILL.md +102 -1
  48. package/skills/{writing-systematic-skills → writing-skills}/references/foundation-conventions.md +5 -5
  49. package/agents/design/design-implementation-reviewer.md +0 -95
  50. package/agents/design/figma-design-sync.md +0 -173
  51. package/agents/docs/ankane-readme-writer.md +0 -51
  52. package/agents/review/cli-agent-readiness-reviewer.md +0 -418
  53. package/agents/review/data-integrity-guardian.md +0 -72
  54. package/agents/review/data-migration-expert.md +0 -99
  55. package/agents/review/dhh-rails-reviewer.md +0 -46
  56. package/agents/review/julik-frontend-races-reviewer.md +0 -49
  57. package/agents/review/kieran-python-reviewer.md +0 -47
  58. package/agents/review/kieran-rails-reviewer.md +0 -47
  59. package/agents/review/performance-oracle.md +0 -112
  60. package/agents/review/schema-drift-detector.md +0 -143
  61. package/agents/review/security-sentinel.md +0 -95
  62. package/agents/workflow/lint.md +0 -17
  63. package/dist/lib/converter.d.ts +0 -14
  64. package/skills/andrew-kane-gem-writer/SKILL.md +0 -184
  65. package/skills/andrew-kane-gem-writer/references/database-adapters.md +0 -231
  66. package/skills/andrew-kane-gem-writer/references/module-organization.md +0 -121
  67. package/skills/andrew-kane-gem-writer/references/rails-integration.md +0 -183
  68. package/skills/andrew-kane-gem-writer/references/resources.md +0 -119
  69. package/skills/andrew-kane-gem-writer/references/testing-patterns.md +0 -261
  70. package/skills/changelog/SKILL.md +0 -139
  71. package/skills/claude-permissions-optimizer/SKILL.md +0 -166
  72. package/skills/claude-permissions-optimizer/scripts/extract-commands.mjs +0 -655
  73. package/skills/claude-permissions-optimizer/scripts/normalize.mjs +0 -151
  74. package/skills/dhh-rails-style/SKILL.md +0 -186
  75. package/skills/dhh-rails-style/references/architecture.md +0 -653
  76. package/skills/dhh-rails-style/references/controllers.md +0 -303
  77. package/skills/dhh-rails-style/references/frontend.md +0 -510
  78. package/skills/dhh-rails-style/references/gems.md +0 -266
  79. package/skills/dhh-rails-style/references/models.md +0 -359
  80. package/skills/dhh-rails-style/references/testing.md +0 -338
  81. package/skills/dspy-ruby/SKILL.md +0 -737
  82. package/skills/dspy-ruby/assets/config-template.rb +0 -187
  83. package/skills/dspy-ruby/assets/module-template.rb +0 -300
  84. package/skills/dspy-ruby/assets/signature-template.rb +0 -221
  85. package/skills/dspy-ruby/references/core-concepts.md +0 -674
  86. package/skills/dspy-ruby/references/observability.md +0 -366
  87. package/skills/dspy-ruby/references/optimization.md +0 -603
  88. package/skills/dspy-ruby/references/providers.md +0 -418
  89. package/skills/dspy-ruby/references/toolsets.md +0 -502
  90. package/skills/every-style-editor/SKILL.md +0 -135
  91. package/skills/every-style-editor/references/EVERY_WRITE_STYLE.md +0 -529
  92. package/skills/feature-video/SKILL.md +0 -383
  93. package/skills/gemini-imagegen/SKILL.md +0 -237
  94. package/skills/gemini-imagegen/requirements.txt +0 -2
  95. package/skills/gemini-imagegen/scripts/compose_images.py +0 -157
  96. package/skills/gemini-imagegen/scripts/edit_image.py +0 -144
  97. package/skills/gemini-imagegen/scripts/gemini_images.py +0 -263
  98. package/skills/gemini-imagegen/scripts/generate_image.py +0 -133
  99. package/skills/gemini-imagegen/scripts/multi_turn_chat.py +0 -216
  100. package/skills/generate_command/SKILL.md +0 -164
  101. package/skills/orchestrating-swarms/SKILL.md +0 -1723
  102. package/skills/proof/SKILL.md +0 -291
  103. package/skills/proof/references/hitl-review.md +0 -368
  104. package/skills/rclone/SKILL.md +0 -150
  105. package/skills/rclone/scripts/check_setup.sh +0 -60
  106. package/skills/setup/SKILL.md +0 -22
  107. package/skills/test-xcode/SKILL.md +0 -214
  108. package/skills/todo-create/SKILL.md +0 -109
  109. package/skills/todo-resolve/SKILL.md +0 -68
  110. package/skills/todo-triage/SKILL.md +0 -70
  111. package/skills/writing-systematic-skills/SKILL.md +0 -119
  112. /package/skills/{todo-create → todos}/assets/todo-template.md +0 -0
package/dist/pi.js ADDED
@@ -0,0 +1,3641 @@
1
+ // src/pi.ts
2
+ import path6 from "node:path";
3
+ import { fileURLToPath } from "node:url";
4
+ import { Type as Type3 } from "typebox";
5
+
6
+ // src/lib/agent-resolver.ts
7
+ import fs2 from "node:fs";
8
+
9
+ // node_modules/.bun/js-yaml@4.1.1/node_modules/js-yaml/dist/js-yaml.mjs
10
+ /*! js-yaml 4.1.1 https://github.com/nodeca/js-yaml @license MIT */
11
+ function isNothing(subject) {
12
+ return typeof subject === "undefined" || subject === null;
13
+ }
14
+ function isObject(subject) {
15
+ return typeof subject === "object" && subject !== null;
16
+ }
17
+ function toArray(sequence) {
18
+ if (Array.isArray(sequence))
19
+ return sequence;
20
+ else if (isNothing(sequence))
21
+ return [];
22
+ return [sequence];
23
+ }
24
+ function extend(target, source) {
25
+ var index, length, key, sourceKeys;
26
+ if (source) {
27
+ sourceKeys = Object.keys(source);
28
+ for (index = 0, length = sourceKeys.length;index < length; index += 1) {
29
+ key = sourceKeys[index];
30
+ target[key] = source[key];
31
+ }
32
+ }
33
+ return target;
34
+ }
35
+ function repeat(string, count) {
36
+ var result = "", cycle;
37
+ for (cycle = 0;cycle < count; cycle += 1) {
38
+ result += string;
39
+ }
40
+ return result;
41
+ }
42
+ function isNegativeZero(number) {
43
+ return number === 0 && Number.NEGATIVE_INFINITY === 1 / number;
44
+ }
45
+ var isNothing_1 = isNothing;
46
+ var isObject_1 = isObject;
47
+ var toArray_1 = toArray;
48
+ var repeat_1 = repeat;
49
+ var isNegativeZero_1 = isNegativeZero;
50
+ var extend_1 = extend;
51
+ var common = {
52
+ isNothing: isNothing_1,
53
+ isObject: isObject_1,
54
+ toArray: toArray_1,
55
+ repeat: repeat_1,
56
+ isNegativeZero: isNegativeZero_1,
57
+ extend: extend_1
58
+ };
59
+ function formatError(exception, compact) {
60
+ var where = "", message = exception.reason || "(unknown reason)";
61
+ if (!exception.mark)
62
+ return message;
63
+ if (exception.mark.name) {
64
+ where += 'in "' + exception.mark.name + '" ';
65
+ }
66
+ where += "(" + (exception.mark.line + 1) + ":" + (exception.mark.column + 1) + ")";
67
+ if (!compact && exception.mark.snippet) {
68
+ where += `
69
+
70
+ ` + exception.mark.snippet;
71
+ }
72
+ return message + " " + where;
73
+ }
74
+ function YAMLException$1(reason, mark) {
75
+ Error.call(this);
76
+ this.name = "YAMLException";
77
+ this.reason = reason;
78
+ this.mark = mark;
79
+ this.message = formatError(this, false);
80
+ if (Error.captureStackTrace) {
81
+ Error.captureStackTrace(this, this.constructor);
82
+ } else {
83
+ this.stack = new Error().stack || "";
84
+ }
85
+ }
86
+ YAMLException$1.prototype = Object.create(Error.prototype);
87
+ YAMLException$1.prototype.constructor = YAMLException$1;
88
+ YAMLException$1.prototype.toString = function toString(compact) {
89
+ return this.name + ": " + formatError(this, compact);
90
+ };
91
+ var exception = YAMLException$1;
92
+ function getLine(buffer, lineStart, lineEnd, position, maxLineLength) {
93
+ var head = "";
94
+ var tail = "";
95
+ var maxHalfLength = Math.floor(maxLineLength / 2) - 1;
96
+ if (position - lineStart > maxHalfLength) {
97
+ head = " ... ";
98
+ lineStart = position - maxHalfLength + head.length;
99
+ }
100
+ if (lineEnd - position > maxHalfLength) {
101
+ tail = " ...";
102
+ lineEnd = position + maxHalfLength - tail.length;
103
+ }
104
+ return {
105
+ str: head + buffer.slice(lineStart, lineEnd).replace(/\t/g, "→") + tail,
106
+ pos: position - lineStart + head.length
107
+ };
108
+ }
109
+ function padStart(string, max) {
110
+ return common.repeat(" ", max - string.length) + string;
111
+ }
112
+ function makeSnippet(mark, options) {
113
+ options = Object.create(options || null);
114
+ if (!mark.buffer)
115
+ return null;
116
+ if (!options.maxLength)
117
+ options.maxLength = 79;
118
+ if (typeof options.indent !== "number")
119
+ options.indent = 1;
120
+ if (typeof options.linesBefore !== "number")
121
+ options.linesBefore = 3;
122
+ if (typeof options.linesAfter !== "number")
123
+ options.linesAfter = 2;
124
+ var re = /\r?\n|\r|\0/g;
125
+ var lineStarts = [0];
126
+ var lineEnds = [];
127
+ var match;
128
+ var foundLineNo = -1;
129
+ while (match = re.exec(mark.buffer)) {
130
+ lineEnds.push(match.index);
131
+ lineStarts.push(match.index + match[0].length);
132
+ if (mark.position <= match.index && foundLineNo < 0) {
133
+ foundLineNo = lineStarts.length - 2;
134
+ }
135
+ }
136
+ if (foundLineNo < 0)
137
+ foundLineNo = lineStarts.length - 1;
138
+ var result = "", i, line;
139
+ var lineNoLength = Math.min(mark.line + options.linesAfter, lineEnds.length).toString().length;
140
+ var maxLineLength = options.maxLength - (options.indent + lineNoLength + 3);
141
+ for (i = 1;i <= options.linesBefore; i++) {
142
+ if (foundLineNo - i < 0)
143
+ break;
144
+ line = getLine(mark.buffer, lineStarts[foundLineNo - i], lineEnds[foundLineNo - i], mark.position - (lineStarts[foundLineNo] - lineStarts[foundLineNo - i]), maxLineLength);
145
+ result = common.repeat(" ", options.indent) + padStart((mark.line - i + 1).toString(), lineNoLength) + " | " + line.str + `
146
+ ` + result;
147
+ }
148
+ line = getLine(mark.buffer, lineStarts[foundLineNo], lineEnds[foundLineNo], mark.position, maxLineLength);
149
+ result += common.repeat(" ", options.indent) + padStart((mark.line + 1).toString(), lineNoLength) + " | " + line.str + `
150
+ `;
151
+ result += common.repeat("-", options.indent + lineNoLength + 3 + line.pos) + "^" + `
152
+ `;
153
+ for (i = 1;i <= options.linesAfter; i++) {
154
+ if (foundLineNo + i >= lineEnds.length)
155
+ break;
156
+ line = getLine(mark.buffer, lineStarts[foundLineNo + i], lineEnds[foundLineNo + i], mark.position - (lineStarts[foundLineNo] - lineStarts[foundLineNo + i]), maxLineLength);
157
+ result += common.repeat(" ", options.indent) + padStart((mark.line + i + 1).toString(), lineNoLength) + " | " + line.str + `
158
+ `;
159
+ }
160
+ return result.replace(/\n$/, "");
161
+ }
162
+ var snippet = makeSnippet;
163
+ var TYPE_CONSTRUCTOR_OPTIONS = [
164
+ "kind",
165
+ "multi",
166
+ "resolve",
167
+ "construct",
168
+ "instanceOf",
169
+ "predicate",
170
+ "represent",
171
+ "representName",
172
+ "defaultStyle",
173
+ "styleAliases"
174
+ ];
175
+ var YAML_NODE_KINDS = [
176
+ "scalar",
177
+ "sequence",
178
+ "mapping"
179
+ ];
180
+ function compileStyleAliases(map) {
181
+ var result = {};
182
+ if (map !== null) {
183
+ Object.keys(map).forEach(function(style) {
184
+ map[style].forEach(function(alias) {
185
+ result[String(alias)] = style;
186
+ });
187
+ });
188
+ }
189
+ return result;
190
+ }
191
+ function Type$1(tag, options) {
192
+ options = options || {};
193
+ Object.keys(options).forEach(function(name) {
194
+ if (TYPE_CONSTRUCTOR_OPTIONS.indexOf(name) === -1) {
195
+ throw new exception('Unknown option "' + name + '" is met in definition of "' + tag + '" YAML type.');
196
+ }
197
+ });
198
+ this.options = options;
199
+ this.tag = tag;
200
+ this.kind = options["kind"] || null;
201
+ this.resolve = options["resolve"] || function() {
202
+ return true;
203
+ };
204
+ this.construct = options["construct"] || function(data) {
205
+ return data;
206
+ };
207
+ this.instanceOf = options["instanceOf"] || null;
208
+ this.predicate = options["predicate"] || null;
209
+ this.represent = options["represent"] || null;
210
+ this.representName = options["representName"] || null;
211
+ this.defaultStyle = options["defaultStyle"] || null;
212
+ this.multi = options["multi"] || false;
213
+ this.styleAliases = compileStyleAliases(options["styleAliases"] || null);
214
+ if (YAML_NODE_KINDS.indexOf(this.kind) === -1) {
215
+ throw new exception('Unknown kind "' + this.kind + '" is specified for "' + tag + '" YAML type.');
216
+ }
217
+ }
218
+ var type = Type$1;
219
+ function compileList(schema, name) {
220
+ var result = [];
221
+ schema[name].forEach(function(currentType) {
222
+ var newIndex = result.length;
223
+ result.forEach(function(previousType, previousIndex) {
224
+ if (previousType.tag === currentType.tag && previousType.kind === currentType.kind && previousType.multi === currentType.multi) {
225
+ newIndex = previousIndex;
226
+ }
227
+ });
228
+ result[newIndex] = currentType;
229
+ });
230
+ return result;
231
+ }
232
+ function compileMap() {
233
+ var result = {
234
+ scalar: {},
235
+ sequence: {},
236
+ mapping: {},
237
+ fallback: {},
238
+ multi: {
239
+ scalar: [],
240
+ sequence: [],
241
+ mapping: [],
242
+ fallback: []
243
+ }
244
+ }, index, length;
245
+ function collectType(type2) {
246
+ if (type2.multi) {
247
+ result.multi[type2.kind].push(type2);
248
+ result.multi["fallback"].push(type2);
249
+ } else {
250
+ result[type2.kind][type2.tag] = result["fallback"][type2.tag] = type2;
251
+ }
252
+ }
253
+ for (index = 0, length = arguments.length;index < length; index += 1) {
254
+ arguments[index].forEach(collectType);
255
+ }
256
+ return result;
257
+ }
258
+ function Schema$1(definition) {
259
+ return this.extend(definition);
260
+ }
261
+ Schema$1.prototype.extend = function extend2(definition) {
262
+ var implicit = [];
263
+ var explicit = [];
264
+ if (definition instanceof type) {
265
+ explicit.push(definition);
266
+ } else if (Array.isArray(definition)) {
267
+ explicit = explicit.concat(definition);
268
+ } else if (definition && (Array.isArray(definition.implicit) || Array.isArray(definition.explicit))) {
269
+ if (definition.implicit)
270
+ implicit = implicit.concat(definition.implicit);
271
+ if (definition.explicit)
272
+ explicit = explicit.concat(definition.explicit);
273
+ } else {
274
+ throw new exception("Schema.extend argument should be a Type, [ Type ], " + "or a schema definition ({ implicit: [...], explicit: [...] })");
275
+ }
276
+ implicit.forEach(function(type$1) {
277
+ if (!(type$1 instanceof type)) {
278
+ throw new exception("Specified list of YAML types (or a single Type object) contains a non-Type object.");
279
+ }
280
+ if (type$1.loadKind && type$1.loadKind !== "scalar") {
281
+ throw new exception("There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported.");
282
+ }
283
+ if (type$1.multi) {
284
+ throw new exception("There is a multi type in the implicit list of a schema. Multi tags can only be listed as explicit.");
285
+ }
286
+ });
287
+ explicit.forEach(function(type$1) {
288
+ if (!(type$1 instanceof type)) {
289
+ throw new exception("Specified list of YAML types (or a single Type object) contains a non-Type object.");
290
+ }
291
+ });
292
+ var result = Object.create(Schema$1.prototype);
293
+ result.implicit = (this.implicit || []).concat(implicit);
294
+ result.explicit = (this.explicit || []).concat(explicit);
295
+ result.compiledImplicit = compileList(result, "implicit");
296
+ result.compiledExplicit = compileList(result, "explicit");
297
+ result.compiledTypeMap = compileMap(result.compiledImplicit, result.compiledExplicit);
298
+ return result;
299
+ };
300
+ var schema = Schema$1;
301
+ var str = new type("tag:yaml.org,2002:str", {
302
+ kind: "scalar",
303
+ construct: function(data) {
304
+ return data !== null ? data : "";
305
+ }
306
+ });
307
+ var seq = new type("tag:yaml.org,2002:seq", {
308
+ kind: "sequence",
309
+ construct: function(data) {
310
+ return data !== null ? data : [];
311
+ }
312
+ });
313
+ var map = new type("tag:yaml.org,2002:map", {
314
+ kind: "mapping",
315
+ construct: function(data) {
316
+ return data !== null ? data : {};
317
+ }
318
+ });
319
+ var failsafe = new schema({
320
+ explicit: [
321
+ str,
322
+ seq,
323
+ map
324
+ ]
325
+ });
326
+ function resolveYamlNull(data) {
327
+ if (data === null)
328
+ return true;
329
+ var max = data.length;
330
+ return max === 1 && data === "~" || max === 4 && (data === "null" || data === "Null" || data === "NULL");
331
+ }
332
+ function constructYamlNull() {
333
+ return null;
334
+ }
335
+ function isNull(object) {
336
+ return object === null;
337
+ }
338
+ var _null = new type("tag:yaml.org,2002:null", {
339
+ kind: "scalar",
340
+ resolve: resolveYamlNull,
341
+ construct: constructYamlNull,
342
+ predicate: isNull,
343
+ represent: {
344
+ canonical: function() {
345
+ return "~";
346
+ },
347
+ lowercase: function() {
348
+ return "null";
349
+ },
350
+ uppercase: function() {
351
+ return "NULL";
352
+ },
353
+ camelcase: function() {
354
+ return "Null";
355
+ },
356
+ empty: function() {
357
+ return "";
358
+ }
359
+ },
360
+ defaultStyle: "lowercase"
361
+ });
362
+ function resolveYamlBoolean(data) {
363
+ if (data === null)
364
+ return false;
365
+ var max = data.length;
366
+ return max === 4 && (data === "true" || data === "True" || data === "TRUE") || max === 5 && (data === "false" || data === "False" || data === "FALSE");
367
+ }
368
+ function constructYamlBoolean(data) {
369
+ return data === "true" || data === "True" || data === "TRUE";
370
+ }
371
+ function isBoolean(object) {
372
+ return Object.prototype.toString.call(object) === "[object Boolean]";
373
+ }
374
+ var bool = new type("tag:yaml.org,2002:bool", {
375
+ kind: "scalar",
376
+ resolve: resolveYamlBoolean,
377
+ construct: constructYamlBoolean,
378
+ predicate: isBoolean,
379
+ represent: {
380
+ lowercase: function(object) {
381
+ return object ? "true" : "false";
382
+ },
383
+ uppercase: function(object) {
384
+ return object ? "TRUE" : "FALSE";
385
+ },
386
+ camelcase: function(object) {
387
+ return object ? "True" : "False";
388
+ }
389
+ },
390
+ defaultStyle: "lowercase"
391
+ });
392
+ function isHexCode(c) {
393
+ return 48 <= c && c <= 57 || 65 <= c && c <= 70 || 97 <= c && c <= 102;
394
+ }
395
+ function isOctCode(c) {
396
+ return 48 <= c && c <= 55;
397
+ }
398
+ function isDecCode(c) {
399
+ return 48 <= c && c <= 57;
400
+ }
401
+ function resolveYamlInteger(data) {
402
+ if (data === null)
403
+ return false;
404
+ var max = data.length, index = 0, hasDigits = false, ch;
405
+ if (!max)
406
+ return false;
407
+ ch = data[index];
408
+ if (ch === "-" || ch === "+") {
409
+ ch = data[++index];
410
+ }
411
+ if (ch === "0") {
412
+ if (index + 1 === max)
413
+ return true;
414
+ ch = data[++index];
415
+ if (ch === "b") {
416
+ index++;
417
+ for (;index < max; index++) {
418
+ ch = data[index];
419
+ if (ch === "_")
420
+ continue;
421
+ if (ch !== "0" && ch !== "1")
422
+ return false;
423
+ hasDigits = true;
424
+ }
425
+ return hasDigits && ch !== "_";
426
+ }
427
+ if (ch === "x") {
428
+ index++;
429
+ for (;index < max; index++) {
430
+ ch = data[index];
431
+ if (ch === "_")
432
+ continue;
433
+ if (!isHexCode(data.charCodeAt(index)))
434
+ return false;
435
+ hasDigits = true;
436
+ }
437
+ return hasDigits && ch !== "_";
438
+ }
439
+ if (ch === "o") {
440
+ index++;
441
+ for (;index < max; index++) {
442
+ ch = data[index];
443
+ if (ch === "_")
444
+ continue;
445
+ if (!isOctCode(data.charCodeAt(index)))
446
+ return false;
447
+ hasDigits = true;
448
+ }
449
+ return hasDigits && ch !== "_";
450
+ }
451
+ }
452
+ if (ch === "_")
453
+ return false;
454
+ for (;index < max; index++) {
455
+ ch = data[index];
456
+ if (ch === "_")
457
+ continue;
458
+ if (!isDecCode(data.charCodeAt(index))) {
459
+ return false;
460
+ }
461
+ hasDigits = true;
462
+ }
463
+ if (!hasDigits || ch === "_")
464
+ return false;
465
+ return true;
466
+ }
467
+ function constructYamlInteger(data) {
468
+ var value = data, sign = 1, ch;
469
+ if (value.indexOf("_") !== -1) {
470
+ value = value.replace(/_/g, "");
471
+ }
472
+ ch = value[0];
473
+ if (ch === "-" || ch === "+") {
474
+ if (ch === "-")
475
+ sign = -1;
476
+ value = value.slice(1);
477
+ ch = value[0];
478
+ }
479
+ if (value === "0")
480
+ return 0;
481
+ if (ch === "0") {
482
+ if (value[1] === "b")
483
+ return sign * parseInt(value.slice(2), 2);
484
+ if (value[1] === "x")
485
+ return sign * parseInt(value.slice(2), 16);
486
+ if (value[1] === "o")
487
+ return sign * parseInt(value.slice(2), 8);
488
+ }
489
+ return sign * parseInt(value, 10);
490
+ }
491
+ function isInteger(object) {
492
+ return Object.prototype.toString.call(object) === "[object Number]" && (object % 1 === 0 && !common.isNegativeZero(object));
493
+ }
494
+ var int = new type("tag:yaml.org,2002:int", {
495
+ kind: "scalar",
496
+ resolve: resolveYamlInteger,
497
+ construct: constructYamlInteger,
498
+ predicate: isInteger,
499
+ represent: {
500
+ binary: function(obj) {
501
+ return obj >= 0 ? "0b" + obj.toString(2) : "-0b" + obj.toString(2).slice(1);
502
+ },
503
+ octal: function(obj) {
504
+ return obj >= 0 ? "0o" + obj.toString(8) : "-0o" + obj.toString(8).slice(1);
505
+ },
506
+ decimal: function(obj) {
507
+ return obj.toString(10);
508
+ },
509
+ hexadecimal: function(obj) {
510
+ return obj >= 0 ? "0x" + obj.toString(16).toUpperCase() : "-0x" + obj.toString(16).toUpperCase().slice(1);
511
+ }
512
+ },
513
+ defaultStyle: "decimal",
514
+ styleAliases: {
515
+ binary: [2, "bin"],
516
+ octal: [8, "oct"],
517
+ decimal: [10, "dec"],
518
+ hexadecimal: [16, "hex"]
519
+ }
520
+ });
521
+ var YAML_FLOAT_PATTERN = new RegExp("^(?:[-+]?(?:[0-9][0-9_]*)(?:\\.[0-9_]*)?(?:[eE][-+]?[0-9]+)?" + "|\\.[0-9_]+(?:[eE][-+]?[0-9]+)?" + "|[-+]?\\.(?:inf|Inf|INF)" + "|\\.(?:nan|NaN|NAN))$");
522
+ function resolveYamlFloat(data) {
523
+ if (data === null)
524
+ return false;
525
+ if (!YAML_FLOAT_PATTERN.test(data) || data[data.length - 1] === "_") {
526
+ return false;
527
+ }
528
+ return true;
529
+ }
530
+ function constructYamlFloat(data) {
531
+ var value, sign;
532
+ value = data.replace(/_/g, "").toLowerCase();
533
+ sign = value[0] === "-" ? -1 : 1;
534
+ if ("+-".indexOf(value[0]) >= 0) {
535
+ value = value.slice(1);
536
+ }
537
+ if (value === ".inf") {
538
+ return sign === 1 ? Number.POSITIVE_INFINITY : Number.NEGATIVE_INFINITY;
539
+ } else if (value === ".nan") {
540
+ return NaN;
541
+ }
542
+ return sign * parseFloat(value, 10);
543
+ }
544
+ var SCIENTIFIC_WITHOUT_DOT = /^[-+]?[0-9]+e/;
545
+ function representYamlFloat(object, style) {
546
+ var res;
547
+ if (isNaN(object)) {
548
+ switch (style) {
549
+ case "lowercase":
550
+ return ".nan";
551
+ case "uppercase":
552
+ return ".NAN";
553
+ case "camelcase":
554
+ return ".NaN";
555
+ }
556
+ } else if (Number.POSITIVE_INFINITY === object) {
557
+ switch (style) {
558
+ case "lowercase":
559
+ return ".inf";
560
+ case "uppercase":
561
+ return ".INF";
562
+ case "camelcase":
563
+ return ".Inf";
564
+ }
565
+ } else if (Number.NEGATIVE_INFINITY === object) {
566
+ switch (style) {
567
+ case "lowercase":
568
+ return "-.inf";
569
+ case "uppercase":
570
+ return "-.INF";
571
+ case "camelcase":
572
+ return "-.Inf";
573
+ }
574
+ } else if (common.isNegativeZero(object)) {
575
+ return "-0.0";
576
+ }
577
+ res = object.toString(10);
578
+ return SCIENTIFIC_WITHOUT_DOT.test(res) ? res.replace("e", ".e") : res;
579
+ }
580
+ function isFloat(object) {
581
+ return Object.prototype.toString.call(object) === "[object Number]" && (object % 1 !== 0 || common.isNegativeZero(object));
582
+ }
583
+ var float = new type("tag:yaml.org,2002:float", {
584
+ kind: "scalar",
585
+ resolve: resolveYamlFloat,
586
+ construct: constructYamlFloat,
587
+ predicate: isFloat,
588
+ represent: representYamlFloat,
589
+ defaultStyle: "lowercase"
590
+ });
591
+ var json = failsafe.extend({
592
+ implicit: [
593
+ _null,
594
+ bool,
595
+ int,
596
+ float
597
+ ]
598
+ });
599
+ var core = json;
600
+ var YAML_DATE_REGEXP = new RegExp("^([0-9][0-9][0-9][0-9])" + "-([0-9][0-9])" + "-([0-9][0-9])$");
601
+ var YAML_TIMESTAMP_REGEXP = new RegExp("^([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]))?))?$");
602
+ function resolveYamlTimestamp(data) {
603
+ if (data === null)
604
+ return false;
605
+ if (YAML_DATE_REGEXP.exec(data) !== null)
606
+ return true;
607
+ if (YAML_TIMESTAMP_REGEXP.exec(data) !== null)
608
+ return true;
609
+ return false;
610
+ }
611
+ function constructYamlTimestamp(data) {
612
+ var match, year, month, day, hour, minute, second, fraction = 0, delta = null, tz_hour, tz_minute, date;
613
+ match = YAML_DATE_REGEXP.exec(data);
614
+ if (match === null)
615
+ match = YAML_TIMESTAMP_REGEXP.exec(data);
616
+ if (match === null)
617
+ throw new Error("Date resolve error");
618
+ year = +match[1];
619
+ month = +match[2] - 1;
620
+ day = +match[3];
621
+ if (!match[4]) {
622
+ return new Date(Date.UTC(year, month, day));
623
+ }
624
+ hour = +match[4];
625
+ minute = +match[5];
626
+ second = +match[6];
627
+ if (match[7]) {
628
+ fraction = match[7].slice(0, 3);
629
+ while (fraction.length < 3) {
630
+ fraction += "0";
631
+ }
632
+ fraction = +fraction;
633
+ }
634
+ if (match[9]) {
635
+ tz_hour = +match[10];
636
+ tz_minute = +(match[11] || 0);
637
+ delta = (tz_hour * 60 + tz_minute) * 60000;
638
+ if (match[9] === "-")
639
+ delta = -delta;
640
+ }
641
+ date = new Date(Date.UTC(year, month, day, hour, minute, second, fraction));
642
+ if (delta)
643
+ date.setTime(date.getTime() - delta);
644
+ return date;
645
+ }
646
+ function representYamlTimestamp(object) {
647
+ return object.toISOString();
648
+ }
649
+ var timestamp = new type("tag:yaml.org,2002:timestamp", {
650
+ kind: "scalar",
651
+ resolve: resolveYamlTimestamp,
652
+ construct: constructYamlTimestamp,
653
+ instanceOf: Date,
654
+ represent: representYamlTimestamp
655
+ });
656
+ function resolveYamlMerge(data) {
657
+ return data === "<<" || data === null;
658
+ }
659
+ var merge = new type("tag:yaml.org,2002:merge", {
660
+ kind: "scalar",
661
+ resolve: resolveYamlMerge
662
+ });
663
+ var BASE64_MAP = `ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=
664
+ \r`;
665
+ function resolveYamlBinary(data) {
666
+ if (data === null)
667
+ return false;
668
+ var code, idx, bitlen = 0, max = data.length, map2 = BASE64_MAP;
669
+ for (idx = 0;idx < max; idx++) {
670
+ code = map2.indexOf(data.charAt(idx));
671
+ if (code > 64)
672
+ continue;
673
+ if (code < 0)
674
+ return false;
675
+ bitlen += 6;
676
+ }
677
+ return bitlen % 8 === 0;
678
+ }
679
+ function constructYamlBinary(data) {
680
+ var idx, tailbits, input = data.replace(/[\r\n=]/g, ""), max = input.length, map2 = BASE64_MAP, bits = 0, result = [];
681
+ for (idx = 0;idx < max; idx++) {
682
+ if (idx % 4 === 0 && idx) {
683
+ result.push(bits >> 16 & 255);
684
+ result.push(bits >> 8 & 255);
685
+ result.push(bits & 255);
686
+ }
687
+ bits = bits << 6 | map2.indexOf(input.charAt(idx));
688
+ }
689
+ tailbits = max % 4 * 6;
690
+ if (tailbits === 0) {
691
+ result.push(bits >> 16 & 255);
692
+ result.push(bits >> 8 & 255);
693
+ result.push(bits & 255);
694
+ } else if (tailbits === 18) {
695
+ result.push(bits >> 10 & 255);
696
+ result.push(bits >> 2 & 255);
697
+ } else if (tailbits === 12) {
698
+ result.push(bits >> 4 & 255);
699
+ }
700
+ return new Uint8Array(result);
701
+ }
702
+ function representYamlBinary(object) {
703
+ var result = "", bits = 0, idx, tail, max = object.length, map2 = BASE64_MAP;
704
+ for (idx = 0;idx < max; idx++) {
705
+ if (idx % 3 === 0 && idx) {
706
+ result += map2[bits >> 18 & 63];
707
+ result += map2[bits >> 12 & 63];
708
+ result += map2[bits >> 6 & 63];
709
+ result += map2[bits & 63];
710
+ }
711
+ bits = (bits << 8) + object[idx];
712
+ }
713
+ tail = max % 3;
714
+ if (tail === 0) {
715
+ result += map2[bits >> 18 & 63];
716
+ result += map2[bits >> 12 & 63];
717
+ result += map2[bits >> 6 & 63];
718
+ result += map2[bits & 63];
719
+ } else if (tail === 2) {
720
+ result += map2[bits >> 10 & 63];
721
+ result += map2[bits >> 4 & 63];
722
+ result += map2[bits << 2 & 63];
723
+ result += map2[64];
724
+ } else if (tail === 1) {
725
+ result += map2[bits >> 2 & 63];
726
+ result += map2[bits << 4 & 63];
727
+ result += map2[64];
728
+ result += map2[64];
729
+ }
730
+ return result;
731
+ }
732
+ function isBinary(obj) {
733
+ return Object.prototype.toString.call(obj) === "[object Uint8Array]";
734
+ }
735
+ var binary = new type("tag:yaml.org,2002:binary", {
736
+ kind: "scalar",
737
+ resolve: resolveYamlBinary,
738
+ construct: constructYamlBinary,
739
+ predicate: isBinary,
740
+ represent: representYamlBinary
741
+ });
742
+ var _hasOwnProperty$3 = Object.prototype.hasOwnProperty;
743
+ var _toString$2 = Object.prototype.toString;
744
+ function resolveYamlOmap(data) {
745
+ if (data === null)
746
+ return true;
747
+ var objectKeys = [], index, length, pair, pairKey, pairHasKey, object = data;
748
+ for (index = 0, length = object.length;index < length; index += 1) {
749
+ pair = object[index];
750
+ pairHasKey = false;
751
+ if (_toString$2.call(pair) !== "[object Object]")
752
+ return false;
753
+ for (pairKey in pair) {
754
+ if (_hasOwnProperty$3.call(pair, pairKey)) {
755
+ if (!pairHasKey)
756
+ pairHasKey = true;
757
+ else
758
+ return false;
759
+ }
760
+ }
761
+ if (!pairHasKey)
762
+ return false;
763
+ if (objectKeys.indexOf(pairKey) === -1)
764
+ objectKeys.push(pairKey);
765
+ else
766
+ return false;
767
+ }
768
+ return true;
769
+ }
770
+ function constructYamlOmap(data) {
771
+ return data !== null ? data : [];
772
+ }
773
+ var omap = new type("tag:yaml.org,2002:omap", {
774
+ kind: "sequence",
775
+ resolve: resolveYamlOmap,
776
+ construct: constructYamlOmap
777
+ });
778
+ var _toString$1 = Object.prototype.toString;
779
+ function resolveYamlPairs(data) {
780
+ if (data === null)
781
+ return true;
782
+ var index, length, pair, keys, result, object = data;
783
+ result = new Array(object.length);
784
+ for (index = 0, length = object.length;index < length; index += 1) {
785
+ pair = object[index];
786
+ if (_toString$1.call(pair) !== "[object Object]")
787
+ return false;
788
+ keys = Object.keys(pair);
789
+ if (keys.length !== 1)
790
+ return false;
791
+ result[index] = [keys[0], pair[keys[0]]];
792
+ }
793
+ return true;
794
+ }
795
+ function constructYamlPairs(data) {
796
+ if (data === null)
797
+ return [];
798
+ var index, length, pair, keys, result, object = data;
799
+ result = new Array(object.length);
800
+ for (index = 0, length = object.length;index < length; index += 1) {
801
+ pair = object[index];
802
+ keys = Object.keys(pair);
803
+ result[index] = [keys[0], pair[keys[0]]];
804
+ }
805
+ return result;
806
+ }
807
+ var pairs = new type("tag:yaml.org,2002:pairs", {
808
+ kind: "sequence",
809
+ resolve: resolveYamlPairs,
810
+ construct: constructYamlPairs
811
+ });
812
+ var _hasOwnProperty$2 = Object.prototype.hasOwnProperty;
813
+ function resolveYamlSet(data) {
814
+ if (data === null)
815
+ return true;
816
+ var key, object = data;
817
+ for (key in object) {
818
+ if (_hasOwnProperty$2.call(object, key)) {
819
+ if (object[key] !== null)
820
+ return false;
821
+ }
822
+ }
823
+ return true;
824
+ }
825
+ function constructYamlSet(data) {
826
+ return data !== null ? data : {};
827
+ }
828
+ var set = new type("tag:yaml.org,2002:set", {
829
+ kind: "mapping",
830
+ resolve: resolveYamlSet,
831
+ construct: constructYamlSet
832
+ });
833
+ var _default = core.extend({
834
+ implicit: [
835
+ timestamp,
836
+ merge
837
+ ],
838
+ explicit: [
839
+ binary,
840
+ omap,
841
+ pairs,
842
+ set
843
+ ]
844
+ });
845
+ var _hasOwnProperty$1 = Object.prototype.hasOwnProperty;
846
+ var CONTEXT_FLOW_IN = 1;
847
+ var CONTEXT_FLOW_OUT = 2;
848
+ var CONTEXT_BLOCK_IN = 3;
849
+ var CONTEXT_BLOCK_OUT = 4;
850
+ var CHOMPING_CLIP = 1;
851
+ var CHOMPING_STRIP = 2;
852
+ var CHOMPING_KEEP = 3;
853
+ var PATTERN_NON_PRINTABLE = /[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x84\x86-\x9F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/;
854
+ var PATTERN_NON_ASCII_LINE_BREAKS = /[\x85\u2028\u2029]/;
855
+ var PATTERN_FLOW_INDICATORS = /[,\[\]\{\}]/;
856
+ var PATTERN_TAG_HANDLE = /^(?:!|!!|![a-z\-]+!)$/i;
857
+ var PATTERN_TAG_URI = /^(?:!|[^,\[\]\{\}])(?:%[0-9a-f]{2}|[0-9a-z\-#;\/\?:@&=\+\$,_\.!~\*'\(\)\[\]])*$/i;
858
+ function _class(obj) {
859
+ return Object.prototype.toString.call(obj);
860
+ }
861
+ function is_EOL(c) {
862
+ return c === 10 || c === 13;
863
+ }
864
+ function is_WHITE_SPACE(c) {
865
+ return c === 9 || c === 32;
866
+ }
867
+ function is_WS_OR_EOL(c) {
868
+ return c === 9 || c === 32 || c === 10 || c === 13;
869
+ }
870
+ function is_FLOW_INDICATOR(c) {
871
+ return c === 44 || c === 91 || c === 93 || c === 123 || c === 125;
872
+ }
873
+ function fromHexCode(c) {
874
+ var lc;
875
+ if (48 <= c && c <= 57) {
876
+ return c - 48;
877
+ }
878
+ lc = c | 32;
879
+ if (97 <= lc && lc <= 102) {
880
+ return lc - 97 + 10;
881
+ }
882
+ return -1;
883
+ }
884
+ function escapedHexLen(c) {
885
+ if (c === 120) {
886
+ return 2;
887
+ }
888
+ if (c === 117) {
889
+ return 4;
890
+ }
891
+ if (c === 85) {
892
+ return 8;
893
+ }
894
+ return 0;
895
+ }
896
+ function fromDecimalCode(c) {
897
+ if (48 <= c && c <= 57) {
898
+ return c - 48;
899
+ }
900
+ return -1;
901
+ }
902
+ function simpleEscapeSequence(c) {
903
+ return c === 48 ? "\x00" : c === 97 ? "\x07" : c === 98 ? "\b" : c === 116 ? "\t" : c === 9 ? "\t" : c === 110 ? `
904
+ ` : c === 118 ? "\v" : c === 102 ? "\f" : c === 114 ? "\r" : c === 101 ? "\x1B" : c === 32 ? " " : c === 34 ? '"' : c === 47 ? "/" : c === 92 ? "\\" : c === 78 ? "…" : c === 95 ? " " : c === 76 ? "\u2028" : c === 80 ? "\u2029" : "";
905
+ }
906
+ function charFromCodepoint(c) {
907
+ if (c <= 65535) {
908
+ return String.fromCharCode(c);
909
+ }
910
+ return String.fromCharCode((c - 65536 >> 10) + 55296, (c - 65536 & 1023) + 56320);
911
+ }
912
+ function setProperty(object, key, value) {
913
+ if (key === "__proto__") {
914
+ Object.defineProperty(object, key, {
915
+ configurable: true,
916
+ enumerable: true,
917
+ writable: true,
918
+ value
919
+ });
920
+ } else {
921
+ object[key] = value;
922
+ }
923
+ }
924
+ var simpleEscapeCheck = new Array(256);
925
+ var simpleEscapeMap = new Array(256);
926
+ for (i = 0;i < 256; i++) {
927
+ simpleEscapeCheck[i] = simpleEscapeSequence(i) ? 1 : 0;
928
+ simpleEscapeMap[i] = simpleEscapeSequence(i);
929
+ }
930
+ var i;
931
+ function State$1(input, options) {
932
+ this.input = input;
933
+ this.filename = options["filename"] || null;
934
+ this.schema = options["schema"] || _default;
935
+ this.onWarning = options["onWarning"] || null;
936
+ this.legacy = options["legacy"] || false;
937
+ this.json = options["json"] || false;
938
+ this.listener = options["listener"] || null;
939
+ this.implicitTypes = this.schema.compiledImplicit;
940
+ this.typeMap = this.schema.compiledTypeMap;
941
+ this.length = input.length;
942
+ this.position = 0;
943
+ this.line = 0;
944
+ this.lineStart = 0;
945
+ this.lineIndent = 0;
946
+ this.firstTabInLine = -1;
947
+ this.documents = [];
948
+ }
949
+ function generateError(state, message) {
950
+ var mark = {
951
+ name: state.filename,
952
+ buffer: state.input.slice(0, -1),
953
+ position: state.position,
954
+ line: state.line,
955
+ column: state.position - state.lineStart
956
+ };
957
+ mark.snippet = snippet(mark);
958
+ return new exception(message, mark);
959
+ }
960
+ function throwError(state, message) {
961
+ throw generateError(state, message);
962
+ }
963
+ function throwWarning(state, message) {
964
+ if (state.onWarning) {
965
+ state.onWarning.call(null, generateError(state, message));
966
+ }
967
+ }
968
+ var directiveHandlers = {
969
+ YAML: function handleYamlDirective(state, name, args) {
970
+ var match, major, minor;
971
+ if (state.version !== null) {
972
+ throwError(state, "duplication of %YAML directive");
973
+ }
974
+ if (args.length !== 1) {
975
+ throwError(state, "YAML directive accepts exactly one argument");
976
+ }
977
+ match = /^([0-9]+)\.([0-9]+)$/.exec(args[0]);
978
+ if (match === null) {
979
+ throwError(state, "ill-formed argument of the YAML directive");
980
+ }
981
+ major = parseInt(match[1], 10);
982
+ minor = parseInt(match[2], 10);
983
+ if (major !== 1) {
984
+ throwError(state, "unacceptable YAML version of the document");
985
+ }
986
+ state.version = args[0];
987
+ state.checkLineBreaks = minor < 2;
988
+ if (minor !== 1 && minor !== 2) {
989
+ throwWarning(state, "unsupported YAML version of the document");
990
+ }
991
+ },
992
+ TAG: function handleTagDirective(state, name, args) {
993
+ var handle, prefix;
994
+ if (args.length !== 2) {
995
+ throwError(state, "TAG directive accepts exactly two arguments");
996
+ }
997
+ handle = args[0];
998
+ prefix = args[1];
999
+ if (!PATTERN_TAG_HANDLE.test(handle)) {
1000
+ throwError(state, "ill-formed tag handle (first argument) of the TAG directive");
1001
+ }
1002
+ if (_hasOwnProperty$1.call(state.tagMap, handle)) {
1003
+ throwError(state, 'there is a previously declared suffix for "' + handle + '" tag handle');
1004
+ }
1005
+ if (!PATTERN_TAG_URI.test(prefix)) {
1006
+ throwError(state, "ill-formed tag prefix (second argument) of the TAG directive");
1007
+ }
1008
+ try {
1009
+ prefix = decodeURIComponent(prefix);
1010
+ } catch (err) {
1011
+ throwError(state, "tag prefix is malformed: " + prefix);
1012
+ }
1013
+ state.tagMap[handle] = prefix;
1014
+ }
1015
+ };
1016
+ function captureSegment(state, start, end, checkJson) {
1017
+ var _position, _length, _character, _result;
1018
+ if (start < end) {
1019
+ _result = state.input.slice(start, end);
1020
+ if (checkJson) {
1021
+ for (_position = 0, _length = _result.length;_position < _length; _position += 1) {
1022
+ _character = _result.charCodeAt(_position);
1023
+ if (!(_character === 9 || 32 <= _character && _character <= 1114111)) {
1024
+ throwError(state, "expected valid JSON character");
1025
+ }
1026
+ }
1027
+ } else if (PATTERN_NON_PRINTABLE.test(_result)) {
1028
+ throwError(state, "the stream contains non-printable characters");
1029
+ }
1030
+ state.result += _result;
1031
+ }
1032
+ }
1033
+ function mergeMappings(state, destination, source, overridableKeys) {
1034
+ var sourceKeys, key, index, quantity;
1035
+ if (!common.isObject(source)) {
1036
+ throwError(state, "cannot merge mappings; the provided source object is unacceptable");
1037
+ }
1038
+ sourceKeys = Object.keys(source);
1039
+ for (index = 0, quantity = sourceKeys.length;index < quantity; index += 1) {
1040
+ key = sourceKeys[index];
1041
+ if (!_hasOwnProperty$1.call(destination, key)) {
1042
+ setProperty(destination, key, source[key]);
1043
+ overridableKeys[key] = true;
1044
+ }
1045
+ }
1046
+ }
1047
+ function storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, startLine, startLineStart, startPos) {
1048
+ var index, quantity;
1049
+ if (Array.isArray(keyNode)) {
1050
+ keyNode = Array.prototype.slice.call(keyNode);
1051
+ for (index = 0, quantity = keyNode.length;index < quantity; index += 1) {
1052
+ if (Array.isArray(keyNode[index])) {
1053
+ throwError(state, "nested arrays are not supported inside keys");
1054
+ }
1055
+ if (typeof keyNode === "object" && _class(keyNode[index]) === "[object Object]") {
1056
+ keyNode[index] = "[object Object]";
1057
+ }
1058
+ }
1059
+ }
1060
+ if (typeof keyNode === "object" && _class(keyNode) === "[object Object]") {
1061
+ keyNode = "[object Object]";
1062
+ }
1063
+ keyNode = String(keyNode);
1064
+ if (_result === null) {
1065
+ _result = {};
1066
+ }
1067
+ if (keyTag === "tag:yaml.org,2002:merge") {
1068
+ if (Array.isArray(valueNode)) {
1069
+ for (index = 0, quantity = valueNode.length;index < quantity; index += 1) {
1070
+ mergeMappings(state, _result, valueNode[index], overridableKeys);
1071
+ }
1072
+ } else {
1073
+ mergeMappings(state, _result, valueNode, overridableKeys);
1074
+ }
1075
+ } else {
1076
+ if (!state.json && !_hasOwnProperty$1.call(overridableKeys, keyNode) && _hasOwnProperty$1.call(_result, keyNode)) {
1077
+ state.line = startLine || state.line;
1078
+ state.lineStart = startLineStart || state.lineStart;
1079
+ state.position = startPos || state.position;
1080
+ throwError(state, "duplicated mapping key");
1081
+ }
1082
+ setProperty(_result, keyNode, valueNode);
1083
+ delete overridableKeys[keyNode];
1084
+ }
1085
+ return _result;
1086
+ }
1087
+ function readLineBreak(state) {
1088
+ var ch;
1089
+ ch = state.input.charCodeAt(state.position);
1090
+ if (ch === 10) {
1091
+ state.position++;
1092
+ } else if (ch === 13) {
1093
+ state.position++;
1094
+ if (state.input.charCodeAt(state.position) === 10) {
1095
+ state.position++;
1096
+ }
1097
+ } else {
1098
+ throwError(state, "a line break is expected");
1099
+ }
1100
+ state.line += 1;
1101
+ state.lineStart = state.position;
1102
+ state.firstTabInLine = -1;
1103
+ }
1104
+ function skipSeparationSpace(state, allowComments, checkIndent) {
1105
+ var lineBreaks = 0, ch = state.input.charCodeAt(state.position);
1106
+ while (ch !== 0) {
1107
+ while (is_WHITE_SPACE(ch)) {
1108
+ if (ch === 9 && state.firstTabInLine === -1) {
1109
+ state.firstTabInLine = state.position;
1110
+ }
1111
+ ch = state.input.charCodeAt(++state.position);
1112
+ }
1113
+ if (allowComments && ch === 35) {
1114
+ do {
1115
+ ch = state.input.charCodeAt(++state.position);
1116
+ } while (ch !== 10 && ch !== 13 && ch !== 0);
1117
+ }
1118
+ if (is_EOL(ch)) {
1119
+ readLineBreak(state);
1120
+ ch = state.input.charCodeAt(state.position);
1121
+ lineBreaks++;
1122
+ state.lineIndent = 0;
1123
+ while (ch === 32) {
1124
+ state.lineIndent++;
1125
+ ch = state.input.charCodeAt(++state.position);
1126
+ }
1127
+ } else {
1128
+ break;
1129
+ }
1130
+ }
1131
+ if (checkIndent !== -1 && lineBreaks !== 0 && state.lineIndent < checkIndent) {
1132
+ throwWarning(state, "deficient indentation");
1133
+ }
1134
+ return lineBreaks;
1135
+ }
1136
+ function testDocumentSeparator(state) {
1137
+ var _position = state.position, ch;
1138
+ ch = state.input.charCodeAt(_position);
1139
+ if ((ch === 45 || ch === 46) && ch === state.input.charCodeAt(_position + 1) && ch === state.input.charCodeAt(_position + 2)) {
1140
+ _position += 3;
1141
+ ch = state.input.charCodeAt(_position);
1142
+ if (ch === 0 || is_WS_OR_EOL(ch)) {
1143
+ return true;
1144
+ }
1145
+ }
1146
+ return false;
1147
+ }
1148
+ function writeFoldedLines(state, count) {
1149
+ if (count === 1) {
1150
+ state.result += " ";
1151
+ } else if (count > 1) {
1152
+ state.result += common.repeat(`
1153
+ `, count - 1);
1154
+ }
1155
+ }
1156
+ function readPlainScalar(state, nodeIndent, withinFlowCollection) {
1157
+ var preceding, following, captureStart, captureEnd, hasPendingContent, _line, _lineStart, _lineIndent, _kind = state.kind, _result = state.result, ch;
1158
+ ch = state.input.charCodeAt(state.position);
1159
+ if (is_WS_OR_EOL(ch) || is_FLOW_INDICATOR(ch) || ch === 35 || ch === 38 || ch === 42 || ch === 33 || ch === 124 || ch === 62 || ch === 39 || ch === 34 || ch === 37 || ch === 64 || ch === 96) {
1160
+ return false;
1161
+ }
1162
+ if (ch === 63 || ch === 45) {
1163
+ following = state.input.charCodeAt(state.position + 1);
1164
+ if (is_WS_OR_EOL(following) || withinFlowCollection && is_FLOW_INDICATOR(following)) {
1165
+ return false;
1166
+ }
1167
+ }
1168
+ state.kind = "scalar";
1169
+ state.result = "";
1170
+ captureStart = captureEnd = state.position;
1171
+ hasPendingContent = false;
1172
+ while (ch !== 0) {
1173
+ if (ch === 58) {
1174
+ following = state.input.charCodeAt(state.position + 1);
1175
+ if (is_WS_OR_EOL(following) || withinFlowCollection && is_FLOW_INDICATOR(following)) {
1176
+ break;
1177
+ }
1178
+ } else if (ch === 35) {
1179
+ preceding = state.input.charCodeAt(state.position - 1);
1180
+ if (is_WS_OR_EOL(preceding)) {
1181
+ break;
1182
+ }
1183
+ } else if (state.position === state.lineStart && testDocumentSeparator(state) || withinFlowCollection && is_FLOW_INDICATOR(ch)) {
1184
+ break;
1185
+ } else if (is_EOL(ch)) {
1186
+ _line = state.line;
1187
+ _lineStart = state.lineStart;
1188
+ _lineIndent = state.lineIndent;
1189
+ skipSeparationSpace(state, false, -1);
1190
+ if (state.lineIndent >= nodeIndent) {
1191
+ hasPendingContent = true;
1192
+ ch = state.input.charCodeAt(state.position);
1193
+ continue;
1194
+ } else {
1195
+ state.position = captureEnd;
1196
+ state.line = _line;
1197
+ state.lineStart = _lineStart;
1198
+ state.lineIndent = _lineIndent;
1199
+ break;
1200
+ }
1201
+ }
1202
+ if (hasPendingContent) {
1203
+ captureSegment(state, captureStart, captureEnd, false);
1204
+ writeFoldedLines(state, state.line - _line);
1205
+ captureStart = captureEnd = state.position;
1206
+ hasPendingContent = false;
1207
+ }
1208
+ if (!is_WHITE_SPACE(ch)) {
1209
+ captureEnd = state.position + 1;
1210
+ }
1211
+ ch = state.input.charCodeAt(++state.position);
1212
+ }
1213
+ captureSegment(state, captureStart, captureEnd, false);
1214
+ if (state.result) {
1215
+ return true;
1216
+ }
1217
+ state.kind = _kind;
1218
+ state.result = _result;
1219
+ return false;
1220
+ }
1221
+ function readSingleQuotedScalar(state, nodeIndent) {
1222
+ var ch, captureStart, captureEnd;
1223
+ ch = state.input.charCodeAt(state.position);
1224
+ if (ch !== 39) {
1225
+ return false;
1226
+ }
1227
+ state.kind = "scalar";
1228
+ state.result = "";
1229
+ state.position++;
1230
+ captureStart = captureEnd = state.position;
1231
+ while ((ch = state.input.charCodeAt(state.position)) !== 0) {
1232
+ if (ch === 39) {
1233
+ captureSegment(state, captureStart, state.position, true);
1234
+ ch = state.input.charCodeAt(++state.position);
1235
+ if (ch === 39) {
1236
+ captureStart = state.position;
1237
+ state.position++;
1238
+ captureEnd = state.position;
1239
+ } else {
1240
+ return true;
1241
+ }
1242
+ } else if (is_EOL(ch)) {
1243
+ captureSegment(state, captureStart, captureEnd, true);
1244
+ writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent));
1245
+ captureStart = captureEnd = state.position;
1246
+ } else if (state.position === state.lineStart && testDocumentSeparator(state)) {
1247
+ throwError(state, "unexpected end of the document within a single quoted scalar");
1248
+ } else {
1249
+ state.position++;
1250
+ captureEnd = state.position;
1251
+ }
1252
+ }
1253
+ throwError(state, "unexpected end of the stream within a single quoted scalar");
1254
+ }
1255
+ function readDoubleQuotedScalar(state, nodeIndent) {
1256
+ var captureStart, captureEnd, hexLength, hexResult, tmp, ch;
1257
+ ch = state.input.charCodeAt(state.position);
1258
+ if (ch !== 34) {
1259
+ return false;
1260
+ }
1261
+ state.kind = "scalar";
1262
+ state.result = "";
1263
+ state.position++;
1264
+ captureStart = captureEnd = state.position;
1265
+ while ((ch = state.input.charCodeAt(state.position)) !== 0) {
1266
+ if (ch === 34) {
1267
+ captureSegment(state, captureStart, state.position, true);
1268
+ state.position++;
1269
+ return true;
1270
+ } else if (ch === 92) {
1271
+ captureSegment(state, captureStart, state.position, true);
1272
+ ch = state.input.charCodeAt(++state.position);
1273
+ if (is_EOL(ch)) {
1274
+ skipSeparationSpace(state, false, nodeIndent);
1275
+ } else if (ch < 256 && simpleEscapeCheck[ch]) {
1276
+ state.result += simpleEscapeMap[ch];
1277
+ state.position++;
1278
+ } else if ((tmp = escapedHexLen(ch)) > 0) {
1279
+ hexLength = tmp;
1280
+ hexResult = 0;
1281
+ for (;hexLength > 0; hexLength--) {
1282
+ ch = state.input.charCodeAt(++state.position);
1283
+ if ((tmp = fromHexCode(ch)) >= 0) {
1284
+ hexResult = (hexResult << 4) + tmp;
1285
+ } else {
1286
+ throwError(state, "expected hexadecimal character");
1287
+ }
1288
+ }
1289
+ state.result += charFromCodepoint(hexResult);
1290
+ state.position++;
1291
+ } else {
1292
+ throwError(state, "unknown escape sequence");
1293
+ }
1294
+ captureStart = captureEnd = state.position;
1295
+ } else if (is_EOL(ch)) {
1296
+ captureSegment(state, captureStart, captureEnd, true);
1297
+ writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent));
1298
+ captureStart = captureEnd = state.position;
1299
+ } else if (state.position === state.lineStart && testDocumentSeparator(state)) {
1300
+ throwError(state, "unexpected end of the document within a double quoted scalar");
1301
+ } else {
1302
+ state.position++;
1303
+ captureEnd = state.position;
1304
+ }
1305
+ }
1306
+ throwError(state, "unexpected end of the stream within a double quoted scalar");
1307
+ }
1308
+ function readFlowCollection(state, nodeIndent) {
1309
+ var readNext = true, _line, _lineStart, _pos, _tag = state.tag, _result, _anchor = state.anchor, following, terminator, isPair, isExplicitPair, isMapping, overridableKeys = Object.create(null), keyNode, keyTag, valueNode, ch;
1310
+ ch = state.input.charCodeAt(state.position);
1311
+ if (ch === 91) {
1312
+ terminator = 93;
1313
+ isMapping = false;
1314
+ _result = [];
1315
+ } else if (ch === 123) {
1316
+ terminator = 125;
1317
+ isMapping = true;
1318
+ _result = {};
1319
+ } else {
1320
+ return false;
1321
+ }
1322
+ if (state.anchor !== null) {
1323
+ state.anchorMap[state.anchor] = _result;
1324
+ }
1325
+ ch = state.input.charCodeAt(++state.position);
1326
+ while (ch !== 0) {
1327
+ skipSeparationSpace(state, true, nodeIndent);
1328
+ ch = state.input.charCodeAt(state.position);
1329
+ if (ch === terminator) {
1330
+ state.position++;
1331
+ state.tag = _tag;
1332
+ state.anchor = _anchor;
1333
+ state.kind = isMapping ? "mapping" : "sequence";
1334
+ state.result = _result;
1335
+ return true;
1336
+ } else if (!readNext) {
1337
+ throwError(state, "missed comma between flow collection entries");
1338
+ } else if (ch === 44) {
1339
+ throwError(state, "expected the node content, but found ','");
1340
+ }
1341
+ keyTag = keyNode = valueNode = null;
1342
+ isPair = isExplicitPair = false;
1343
+ if (ch === 63) {
1344
+ following = state.input.charCodeAt(state.position + 1);
1345
+ if (is_WS_OR_EOL(following)) {
1346
+ isPair = isExplicitPair = true;
1347
+ state.position++;
1348
+ skipSeparationSpace(state, true, nodeIndent);
1349
+ }
1350
+ }
1351
+ _line = state.line;
1352
+ _lineStart = state.lineStart;
1353
+ _pos = state.position;
1354
+ composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true);
1355
+ keyTag = state.tag;
1356
+ keyNode = state.result;
1357
+ skipSeparationSpace(state, true, nodeIndent);
1358
+ ch = state.input.charCodeAt(state.position);
1359
+ if ((isExplicitPair || state.line === _line) && ch === 58) {
1360
+ isPair = true;
1361
+ ch = state.input.charCodeAt(++state.position);
1362
+ skipSeparationSpace(state, true, nodeIndent);
1363
+ composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true);
1364
+ valueNode = state.result;
1365
+ }
1366
+ if (isMapping) {
1367
+ storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, _line, _lineStart, _pos);
1368
+ } else if (isPair) {
1369
+ _result.push(storeMappingPair(state, null, overridableKeys, keyTag, keyNode, valueNode, _line, _lineStart, _pos));
1370
+ } else {
1371
+ _result.push(keyNode);
1372
+ }
1373
+ skipSeparationSpace(state, true, nodeIndent);
1374
+ ch = state.input.charCodeAt(state.position);
1375
+ if (ch === 44) {
1376
+ readNext = true;
1377
+ ch = state.input.charCodeAt(++state.position);
1378
+ } else {
1379
+ readNext = false;
1380
+ }
1381
+ }
1382
+ throwError(state, "unexpected end of the stream within a flow collection");
1383
+ }
1384
+ function readBlockScalar(state, nodeIndent) {
1385
+ var captureStart, folding, chomping = CHOMPING_CLIP, didReadContent = false, detectedIndent = false, textIndent = nodeIndent, emptyLines = 0, atMoreIndented = false, tmp, ch;
1386
+ ch = state.input.charCodeAt(state.position);
1387
+ if (ch === 124) {
1388
+ folding = false;
1389
+ } else if (ch === 62) {
1390
+ folding = true;
1391
+ } else {
1392
+ return false;
1393
+ }
1394
+ state.kind = "scalar";
1395
+ state.result = "";
1396
+ while (ch !== 0) {
1397
+ ch = state.input.charCodeAt(++state.position);
1398
+ if (ch === 43 || ch === 45) {
1399
+ if (CHOMPING_CLIP === chomping) {
1400
+ chomping = ch === 43 ? CHOMPING_KEEP : CHOMPING_STRIP;
1401
+ } else {
1402
+ throwError(state, "repeat of a chomping mode identifier");
1403
+ }
1404
+ } else if ((tmp = fromDecimalCode(ch)) >= 0) {
1405
+ if (tmp === 0) {
1406
+ throwError(state, "bad explicit indentation width of a block scalar; it cannot be less than one");
1407
+ } else if (!detectedIndent) {
1408
+ textIndent = nodeIndent + tmp - 1;
1409
+ detectedIndent = true;
1410
+ } else {
1411
+ throwError(state, "repeat of an indentation width identifier");
1412
+ }
1413
+ } else {
1414
+ break;
1415
+ }
1416
+ }
1417
+ if (is_WHITE_SPACE(ch)) {
1418
+ do {
1419
+ ch = state.input.charCodeAt(++state.position);
1420
+ } while (is_WHITE_SPACE(ch));
1421
+ if (ch === 35) {
1422
+ do {
1423
+ ch = state.input.charCodeAt(++state.position);
1424
+ } while (!is_EOL(ch) && ch !== 0);
1425
+ }
1426
+ }
1427
+ while (ch !== 0) {
1428
+ readLineBreak(state);
1429
+ state.lineIndent = 0;
1430
+ ch = state.input.charCodeAt(state.position);
1431
+ while ((!detectedIndent || state.lineIndent < textIndent) && ch === 32) {
1432
+ state.lineIndent++;
1433
+ ch = state.input.charCodeAt(++state.position);
1434
+ }
1435
+ if (!detectedIndent && state.lineIndent > textIndent) {
1436
+ textIndent = state.lineIndent;
1437
+ }
1438
+ if (is_EOL(ch)) {
1439
+ emptyLines++;
1440
+ continue;
1441
+ }
1442
+ if (state.lineIndent < textIndent) {
1443
+ if (chomping === CHOMPING_KEEP) {
1444
+ state.result += common.repeat(`
1445
+ `, didReadContent ? 1 + emptyLines : emptyLines);
1446
+ } else if (chomping === CHOMPING_CLIP) {
1447
+ if (didReadContent) {
1448
+ state.result += `
1449
+ `;
1450
+ }
1451
+ }
1452
+ break;
1453
+ }
1454
+ if (folding) {
1455
+ if (is_WHITE_SPACE(ch)) {
1456
+ atMoreIndented = true;
1457
+ state.result += common.repeat(`
1458
+ `, didReadContent ? 1 + emptyLines : emptyLines);
1459
+ } else if (atMoreIndented) {
1460
+ atMoreIndented = false;
1461
+ state.result += common.repeat(`
1462
+ `, emptyLines + 1);
1463
+ } else if (emptyLines === 0) {
1464
+ if (didReadContent) {
1465
+ state.result += " ";
1466
+ }
1467
+ } else {
1468
+ state.result += common.repeat(`
1469
+ `, emptyLines);
1470
+ }
1471
+ } else {
1472
+ state.result += common.repeat(`
1473
+ `, didReadContent ? 1 + emptyLines : emptyLines);
1474
+ }
1475
+ didReadContent = true;
1476
+ detectedIndent = true;
1477
+ emptyLines = 0;
1478
+ captureStart = state.position;
1479
+ while (!is_EOL(ch) && ch !== 0) {
1480
+ ch = state.input.charCodeAt(++state.position);
1481
+ }
1482
+ captureSegment(state, captureStart, state.position, false);
1483
+ }
1484
+ return true;
1485
+ }
1486
+ function readBlockSequence(state, nodeIndent) {
1487
+ var _line, _tag = state.tag, _anchor = state.anchor, _result = [], following, detected = false, ch;
1488
+ if (state.firstTabInLine !== -1)
1489
+ return false;
1490
+ if (state.anchor !== null) {
1491
+ state.anchorMap[state.anchor] = _result;
1492
+ }
1493
+ ch = state.input.charCodeAt(state.position);
1494
+ while (ch !== 0) {
1495
+ if (state.firstTabInLine !== -1) {
1496
+ state.position = state.firstTabInLine;
1497
+ throwError(state, "tab characters must not be used in indentation");
1498
+ }
1499
+ if (ch !== 45) {
1500
+ break;
1501
+ }
1502
+ following = state.input.charCodeAt(state.position + 1);
1503
+ if (!is_WS_OR_EOL(following)) {
1504
+ break;
1505
+ }
1506
+ detected = true;
1507
+ state.position++;
1508
+ if (skipSeparationSpace(state, true, -1)) {
1509
+ if (state.lineIndent <= nodeIndent) {
1510
+ _result.push(null);
1511
+ ch = state.input.charCodeAt(state.position);
1512
+ continue;
1513
+ }
1514
+ }
1515
+ _line = state.line;
1516
+ composeNode(state, nodeIndent, CONTEXT_BLOCK_IN, false, true);
1517
+ _result.push(state.result);
1518
+ skipSeparationSpace(state, true, -1);
1519
+ ch = state.input.charCodeAt(state.position);
1520
+ if ((state.line === _line || state.lineIndent > nodeIndent) && ch !== 0) {
1521
+ throwError(state, "bad indentation of a sequence entry");
1522
+ } else if (state.lineIndent < nodeIndent) {
1523
+ break;
1524
+ }
1525
+ }
1526
+ if (detected) {
1527
+ state.tag = _tag;
1528
+ state.anchor = _anchor;
1529
+ state.kind = "sequence";
1530
+ state.result = _result;
1531
+ return true;
1532
+ }
1533
+ return false;
1534
+ }
1535
+ function readBlockMapping(state, nodeIndent, flowIndent) {
1536
+ var following, allowCompact, _line, _keyLine, _keyLineStart, _keyPos, _tag = state.tag, _anchor = state.anchor, _result = {}, overridableKeys = Object.create(null), keyTag = null, keyNode = null, valueNode = null, atExplicitKey = false, detected = false, ch;
1537
+ if (state.firstTabInLine !== -1)
1538
+ return false;
1539
+ if (state.anchor !== null) {
1540
+ state.anchorMap[state.anchor] = _result;
1541
+ }
1542
+ ch = state.input.charCodeAt(state.position);
1543
+ while (ch !== 0) {
1544
+ if (!atExplicitKey && state.firstTabInLine !== -1) {
1545
+ state.position = state.firstTabInLine;
1546
+ throwError(state, "tab characters must not be used in indentation");
1547
+ }
1548
+ following = state.input.charCodeAt(state.position + 1);
1549
+ _line = state.line;
1550
+ if ((ch === 63 || ch === 58) && is_WS_OR_EOL(following)) {
1551
+ if (ch === 63) {
1552
+ if (atExplicitKey) {
1553
+ storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos);
1554
+ keyTag = keyNode = valueNode = null;
1555
+ }
1556
+ detected = true;
1557
+ atExplicitKey = true;
1558
+ allowCompact = true;
1559
+ } else if (atExplicitKey) {
1560
+ atExplicitKey = false;
1561
+ allowCompact = true;
1562
+ } else {
1563
+ throwError(state, "incomplete explicit mapping pair; a key node is missed; or followed by a non-tabulated empty line");
1564
+ }
1565
+ state.position += 1;
1566
+ ch = following;
1567
+ } else {
1568
+ _keyLine = state.line;
1569
+ _keyLineStart = state.lineStart;
1570
+ _keyPos = state.position;
1571
+ if (!composeNode(state, flowIndent, CONTEXT_FLOW_OUT, false, true)) {
1572
+ break;
1573
+ }
1574
+ if (state.line === _line) {
1575
+ ch = state.input.charCodeAt(state.position);
1576
+ while (is_WHITE_SPACE(ch)) {
1577
+ ch = state.input.charCodeAt(++state.position);
1578
+ }
1579
+ if (ch === 58) {
1580
+ ch = state.input.charCodeAt(++state.position);
1581
+ if (!is_WS_OR_EOL(ch)) {
1582
+ throwError(state, "a whitespace character is expected after the key-value separator within a block mapping");
1583
+ }
1584
+ if (atExplicitKey) {
1585
+ storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos);
1586
+ keyTag = keyNode = valueNode = null;
1587
+ }
1588
+ detected = true;
1589
+ atExplicitKey = false;
1590
+ allowCompact = false;
1591
+ keyTag = state.tag;
1592
+ keyNode = state.result;
1593
+ } else if (detected) {
1594
+ throwError(state, "can not read an implicit mapping pair; a colon is missed");
1595
+ } else {
1596
+ state.tag = _tag;
1597
+ state.anchor = _anchor;
1598
+ return true;
1599
+ }
1600
+ } else if (detected) {
1601
+ throwError(state, "can not read a block mapping entry; a multiline key may not be an implicit key");
1602
+ } else {
1603
+ state.tag = _tag;
1604
+ state.anchor = _anchor;
1605
+ return true;
1606
+ }
1607
+ }
1608
+ if (state.line === _line || state.lineIndent > nodeIndent) {
1609
+ if (atExplicitKey) {
1610
+ _keyLine = state.line;
1611
+ _keyLineStart = state.lineStart;
1612
+ _keyPos = state.position;
1613
+ }
1614
+ if (composeNode(state, nodeIndent, CONTEXT_BLOCK_OUT, true, allowCompact)) {
1615
+ if (atExplicitKey) {
1616
+ keyNode = state.result;
1617
+ } else {
1618
+ valueNode = state.result;
1619
+ }
1620
+ }
1621
+ if (!atExplicitKey) {
1622
+ storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, _keyLine, _keyLineStart, _keyPos);
1623
+ keyTag = keyNode = valueNode = null;
1624
+ }
1625
+ skipSeparationSpace(state, true, -1);
1626
+ ch = state.input.charCodeAt(state.position);
1627
+ }
1628
+ if ((state.line === _line || state.lineIndent > nodeIndent) && ch !== 0) {
1629
+ throwError(state, "bad indentation of a mapping entry");
1630
+ } else if (state.lineIndent < nodeIndent) {
1631
+ break;
1632
+ }
1633
+ }
1634
+ if (atExplicitKey) {
1635
+ storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos);
1636
+ }
1637
+ if (detected) {
1638
+ state.tag = _tag;
1639
+ state.anchor = _anchor;
1640
+ state.kind = "mapping";
1641
+ state.result = _result;
1642
+ }
1643
+ return detected;
1644
+ }
1645
+ function readTagProperty(state) {
1646
+ var _position, isVerbatim = false, isNamed = false, tagHandle, tagName, ch;
1647
+ ch = state.input.charCodeAt(state.position);
1648
+ if (ch !== 33)
1649
+ return false;
1650
+ if (state.tag !== null) {
1651
+ throwError(state, "duplication of a tag property");
1652
+ }
1653
+ ch = state.input.charCodeAt(++state.position);
1654
+ if (ch === 60) {
1655
+ isVerbatim = true;
1656
+ ch = state.input.charCodeAt(++state.position);
1657
+ } else if (ch === 33) {
1658
+ isNamed = true;
1659
+ tagHandle = "!!";
1660
+ ch = state.input.charCodeAt(++state.position);
1661
+ } else {
1662
+ tagHandle = "!";
1663
+ }
1664
+ _position = state.position;
1665
+ if (isVerbatim) {
1666
+ do {
1667
+ ch = state.input.charCodeAt(++state.position);
1668
+ } while (ch !== 0 && ch !== 62);
1669
+ if (state.position < state.length) {
1670
+ tagName = state.input.slice(_position, state.position);
1671
+ ch = state.input.charCodeAt(++state.position);
1672
+ } else {
1673
+ throwError(state, "unexpected end of the stream within a verbatim tag");
1674
+ }
1675
+ } else {
1676
+ while (ch !== 0 && !is_WS_OR_EOL(ch)) {
1677
+ if (ch === 33) {
1678
+ if (!isNamed) {
1679
+ tagHandle = state.input.slice(_position - 1, state.position + 1);
1680
+ if (!PATTERN_TAG_HANDLE.test(tagHandle)) {
1681
+ throwError(state, "named tag handle cannot contain such characters");
1682
+ }
1683
+ isNamed = true;
1684
+ _position = state.position + 1;
1685
+ } else {
1686
+ throwError(state, "tag suffix cannot contain exclamation marks");
1687
+ }
1688
+ }
1689
+ ch = state.input.charCodeAt(++state.position);
1690
+ }
1691
+ tagName = state.input.slice(_position, state.position);
1692
+ if (PATTERN_FLOW_INDICATORS.test(tagName)) {
1693
+ throwError(state, "tag suffix cannot contain flow indicator characters");
1694
+ }
1695
+ }
1696
+ if (tagName && !PATTERN_TAG_URI.test(tagName)) {
1697
+ throwError(state, "tag name cannot contain such characters: " + tagName);
1698
+ }
1699
+ try {
1700
+ tagName = decodeURIComponent(tagName);
1701
+ } catch (err) {
1702
+ throwError(state, "tag name is malformed: " + tagName);
1703
+ }
1704
+ if (isVerbatim) {
1705
+ state.tag = tagName;
1706
+ } else if (_hasOwnProperty$1.call(state.tagMap, tagHandle)) {
1707
+ state.tag = state.tagMap[tagHandle] + tagName;
1708
+ } else if (tagHandle === "!") {
1709
+ state.tag = "!" + tagName;
1710
+ } else if (tagHandle === "!!") {
1711
+ state.tag = "tag:yaml.org,2002:" + tagName;
1712
+ } else {
1713
+ throwError(state, 'undeclared tag handle "' + tagHandle + '"');
1714
+ }
1715
+ return true;
1716
+ }
1717
+ function readAnchorProperty(state) {
1718
+ var _position, ch;
1719
+ ch = state.input.charCodeAt(state.position);
1720
+ if (ch !== 38)
1721
+ return false;
1722
+ if (state.anchor !== null) {
1723
+ throwError(state, "duplication of an anchor property");
1724
+ }
1725
+ ch = state.input.charCodeAt(++state.position);
1726
+ _position = state.position;
1727
+ while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) {
1728
+ ch = state.input.charCodeAt(++state.position);
1729
+ }
1730
+ if (state.position === _position) {
1731
+ throwError(state, "name of an anchor node must contain at least one character");
1732
+ }
1733
+ state.anchor = state.input.slice(_position, state.position);
1734
+ return true;
1735
+ }
1736
+ function readAlias(state) {
1737
+ var _position, alias, ch;
1738
+ ch = state.input.charCodeAt(state.position);
1739
+ if (ch !== 42)
1740
+ return false;
1741
+ ch = state.input.charCodeAt(++state.position);
1742
+ _position = state.position;
1743
+ while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) {
1744
+ ch = state.input.charCodeAt(++state.position);
1745
+ }
1746
+ if (state.position === _position) {
1747
+ throwError(state, "name of an alias node must contain at least one character");
1748
+ }
1749
+ alias = state.input.slice(_position, state.position);
1750
+ if (!_hasOwnProperty$1.call(state.anchorMap, alias)) {
1751
+ throwError(state, 'unidentified alias "' + alias + '"');
1752
+ }
1753
+ state.result = state.anchorMap[alias];
1754
+ skipSeparationSpace(state, true, -1);
1755
+ return true;
1756
+ }
1757
+ function composeNode(state, parentIndent, nodeContext, allowToSeek, allowCompact) {
1758
+ var allowBlockStyles, allowBlockScalars, allowBlockCollections, indentStatus = 1, atNewLine = false, hasContent = false, typeIndex, typeQuantity, typeList, type2, flowIndent, blockIndent;
1759
+ if (state.listener !== null) {
1760
+ state.listener("open", state);
1761
+ }
1762
+ state.tag = null;
1763
+ state.anchor = null;
1764
+ state.kind = null;
1765
+ state.result = null;
1766
+ allowBlockStyles = allowBlockScalars = allowBlockCollections = CONTEXT_BLOCK_OUT === nodeContext || CONTEXT_BLOCK_IN === nodeContext;
1767
+ if (allowToSeek) {
1768
+ if (skipSeparationSpace(state, true, -1)) {
1769
+ atNewLine = true;
1770
+ if (state.lineIndent > parentIndent) {
1771
+ indentStatus = 1;
1772
+ } else if (state.lineIndent === parentIndent) {
1773
+ indentStatus = 0;
1774
+ } else if (state.lineIndent < parentIndent) {
1775
+ indentStatus = -1;
1776
+ }
1777
+ }
1778
+ }
1779
+ if (indentStatus === 1) {
1780
+ while (readTagProperty(state) || readAnchorProperty(state)) {
1781
+ if (skipSeparationSpace(state, true, -1)) {
1782
+ atNewLine = true;
1783
+ allowBlockCollections = allowBlockStyles;
1784
+ if (state.lineIndent > parentIndent) {
1785
+ indentStatus = 1;
1786
+ } else if (state.lineIndent === parentIndent) {
1787
+ indentStatus = 0;
1788
+ } else if (state.lineIndent < parentIndent) {
1789
+ indentStatus = -1;
1790
+ }
1791
+ } else {
1792
+ allowBlockCollections = false;
1793
+ }
1794
+ }
1795
+ }
1796
+ if (allowBlockCollections) {
1797
+ allowBlockCollections = atNewLine || allowCompact;
1798
+ }
1799
+ if (indentStatus === 1 || CONTEXT_BLOCK_OUT === nodeContext) {
1800
+ if (CONTEXT_FLOW_IN === nodeContext || CONTEXT_FLOW_OUT === nodeContext) {
1801
+ flowIndent = parentIndent;
1802
+ } else {
1803
+ flowIndent = parentIndent + 1;
1804
+ }
1805
+ blockIndent = state.position - state.lineStart;
1806
+ if (indentStatus === 1) {
1807
+ if (allowBlockCollections && (readBlockSequence(state, blockIndent) || readBlockMapping(state, blockIndent, flowIndent)) || readFlowCollection(state, flowIndent)) {
1808
+ hasContent = true;
1809
+ } else {
1810
+ if (allowBlockScalars && readBlockScalar(state, flowIndent) || readSingleQuotedScalar(state, flowIndent) || readDoubleQuotedScalar(state, flowIndent)) {
1811
+ hasContent = true;
1812
+ } else if (readAlias(state)) {
1813
+ hasContent = true;
1814
+ if (state.tag !== null || state.anchor !== null) {
1815
+ throwError(state, "alias node should not have any properties");
1816
+ }
1817
+ } else if (readPlainScalar(state, flowIndent, CONTEXT_FLOW_IN === nodeContext)) {
1818
+ hasContent = true;
1819
+ if (state.tag === null) {
1820
+ state.tag = "?";
1821
+ }
1822
+ }
1823
+ if (state.anchor !== null) {
1824
+ state.anchorMap[state.anchor] = state.result;
1825
+ }
1826
+ }
1827
+ } else if (indentStatus === 0) {
1828
+ hasContent = allowBlockCollections && readBlockSequence(state, blockIndent);
1829
+ }
1830
+ }
1831
+ if (state.tag === null) {
1832
+ if (state.anchor !== null) {
1833
+ state.anchorMap[state.anchor] = state.result;
1834
+ }
1835
+ } else if (state.tag === "?") {
1836
+ if (state.result !== null && state.kind !== "scalar") {
1837
+ throwError(state, 'unacceptable node kind for !<?> tag; it should be "scalar", not "' + state.kind + '"');
1838
+ }
1839
+ for (typeIndex = 0, typeQuantity = state.implicitTypes.length;typeIndex < typeQuantity; typeIndex += 1) {
1840
+ type2 = state.implicitTypes[typeIndex];
1841
+ if (type2.resolve(state.result)) {
1842
+ state.result = type2.construct(state.result);
1843
+ state.tag = type2.tag;
1844
+ if (state.anchor !== null) {
1845
+ state.anchorMap[state.anchor] = state.result;
1846
+ }
1847
+ break;
1848
+ }
1849
+ }
1850
+ } else if (state.tag !== "!") {
1851
+ if (_hasOwnProperty$1.call(state.typeMap[state.kind || "fallback"], state.tag)) {
1852
+ type2 = state.typeMap[state.kind || "fallback"][state.tag];
1853
+ } else {
1854
+ type2 = null;
1855
+ typeList = state.typeMap.multi[state.kind || "fallback"];
1856
+ for (typeIndex = 0, typeQuantity = typeList.length;typeIndex < typeQuantity; typeIndex += 1) {
1857
+ if (state.tag.slice(0, typeList[typeIndex].tag.length) === typeList[typeIndex].tag) {
1858
+ type2 = typeList[typeIndex];
1859
+ break;
1860
+ }
1861
+ }
1862
+ }
1863
+ if (!type2) {
1864
+ throwError(state, "unknown tag !<" + state.tag + ">");
1865
+ }
1866
+ if (state.result !== null && type2.kind !== state.kind) {
1867
+ throwError(state, "unacceptable node kind for !<" + state.tag + '> tag; it should be "' + type2.kind + '", not "' + state.kind + '"');
1868
+ }
1869
+ if (!type2.resolve(state.result, state.tag)) {
1870
+ throwError(state, "cannot resolve a node with !<" + state.tag + "> explicit tag");
1871
+ } else {
1872
+ state.result = type2.construct(state.result, state.tag);
1873
+ if (state.anchor !== null) {
1874
+ state.anchorMap[state.anchor] = state.result;
1875
+ }
1876
+ }
1877
+ }
1878
+ if (state.listener !== null) {
1879
+ state.listener("close", state);
1880
+ }
1881
+ return state.tag !== null || state.anchor !== null || hasContent;
1882
+ }
1883
+ function readDocument(state) {
1884
+ var documentStart = state.position, _position, directiveName, directiveArgs, hasDirectives = false, ch;
1885
+ state.version = null;
1886
+ state.checkLineBreaks = state.legacy;
1887
+ state.tagMap = Object.create(null);
1888
+ state.anchorMap = Object.create(null);
1889
+ while ((ch = state.input.charCodeAt(state.position)) !== 0) {
1890
+ skipSeparationSpace(state, true, -1);
1891
+ ch = state.input.charCodeAt(state.position);
1892
+ if (state.lineIndent > 0 || ch !== 37) {
1893
+ break;
1894
+ }
1895
+ hasDirectives = true;
1896
+ ch = state.input.charCodeAt(++state.position);
1897
+ _position = state.position;
1898
+ while (ch !== 0 && !is_WS_OR_EOL(ch)) {
1899
+ ch = state.input.charCodeAt(++state.position);
1900
+ }
1901
+ directiveName = state.input.slice(_position, state.position);
1902
+ directiveArgs = [];
1903
+ if (directiveName.length < 1) {
1904
+ throwError(state, "directive name must not be less than one character in length");
1905
+ }
1906
+ while (ch !== 0) {
1907
+ while (is_WHITE_SPACE(ch)) {
1908
+ ch = state.input.charCodeAt(++state.position);
1909
+ }
1910
+ if (ch === 35) {
1911
+ do {
1912
+ ch = state.input.charCodeAt(++state.position);
1913
+ } while (ch !== 0 && !is_EOL(ch));
1914
+ break;
1915
+ }
1916
+ if (is_EOL(ch))
1917
+ break;
1918
+ _position = state.position;
1919
+ while (ch !== 0 && !is_WS_OR_EOL(ch)) {
1920
+ ch = state.input.charCodeAt(++state.position);
1921
+ }
1922
+ directiveArgs.push(state.input.slice(_position, state.position));
1923
+ }
1924
+ if (ch !== 0)
1925
+ readLineBreak(state);
1926
+ if (_hasOwnProperty$1.call(directiveHandlers, directiveName)) {
1927
+ directiveHandlers[directiveName](state, directiveName, directiveArgs);
1928
+ } else {
1929
+ throwWarning(state, 'unknown document directive "' + directiveName + '"');
1930
+ }
1931
+ }
1932
+ skipSeparationSpace(state, true, -1);
1933
+ if (state.lineIndent === 0 && state.input.charCodeAt(state.position) === 45 && state.input.charCodeAt(state.position + 1) === 45 && state.input.charCodeAt(state.position + 2) === 45) {
1934
+ state.position += 3;
1935
+ skipSeparationSpace(state, true, -1);
1936
+ } else if (hasDirectives) {
1937
+ throwError(state, "directives end mark is expected");
1938
+ }
1939
+ composeNode(state, state.lineIndent - 1, CONTEXT_BLOCK_OUT, false, true);
1940
+ skipSeparationSpace(state, true, -1);
1941
+ if (state.checkLineBreaks && PATTERN_NON_ASCII_LINE_BREAKS.test(state.input.slice(documentStart, state.position))) {
1942
+ throwWarning(state, "non-ASCII line breaks are interpreted as content");
1943
+ }
1944
+ state.documents.push(state.result);
1945
+ if (state.position === state.lineStart && testDocumentSeparator(state)) {
1946
+ if (state.input.charCodeAt(state.position) === 46) {
1947
+ state.position += 3;
1948
+ skipSeparationSpace(state, true, -1);
1949
+ }
1950
+ return;
1951
+ }
1952
+ if (state.position < state.length - 1) {
1953
+ throwError(state, "end of the stream or a document separator is expected");
1954
+ } else {
1955
+ return;
1956
+ }
1957
+ }
1958
+ function loadDocuments(input, options) {
1959
+ input = String(input);
1960
+ options = options || {};
1961
+ if (input.length !== 0) {
1962
+ if (input.charCodeAt(input.length - 1) !== 10 && input.charCodeAt(input.length - 1) !== 13) {
1963
+ input += `
1964
+ `;
1965
+ }
1966
+ if (input.charCodeAt(0) === 65279) {
1967
+ input = input.slice(1);
1968
+ }
1969
+ }
1970
+ var state = new State$1(input, options);
1971
+ var nullpos = input.indexOf("\x00");
1972
+ if (nullpos !== -1) {
1973
+ state.position = nullpos;
1974
+ throwError(state, "null byte is not allowed in input");
1975
+ }
1976
+ state.input += "\x00";
1977
+ while (state.input.charCodeAt(state.position) === 32) {
1978
+ state.lineIndent += 1;
1979
+ state.position += 1;
1980
+ }
1981
+ while (state.position < state.length - 1) {
1982
+ readDocument(state);
1983
+ }
1984
+ return state.documents;
1985
+ }
1986
+ function loadAll$1(input, iterator, options) {
1987
+ if (iterator !== null && typeof iterator === "object" && typeof options === "undefined") {
1988
+ options = iterator;
1989
+ iterator = null;
1990
+ }
1991
+ var documents = loadDocuments(input, options);
1992
+ if (typeof iterator !== "function") {
1993
+ return documents;
1994
+ }
1995
+ for (var index = 0, length = documents.length;index < length; index += 1) {
1996
+ iterator(documents[index]);
1997
+ }
1998
+ }
1999
+ function load$1(input, options) {
2000
+ var documents = loadDocuments(input, options);
2001
+ if (documents.length === 0) {
2002
+ return;
2003
+ } else if (documents.length === 1) {
2004
+ return documents[0];
2005
+ }
2006
+ throw new exception("expected a single document in the stream, but found more");
2007
+ }
2008
+ var loadAll_1 = loadAll$1;
2009
+ var load_1 = load$1;
2010
+ var loader = {
2011
+ loadAll: loadAll_1,
2012
+ load: load_1
2013
+ };
2014
+ var _toString = Object.prototype.toString;
2015
+ var _hasOwnProperty = Object.prototype.hasOwnProperty;
2016
+ var CHAR_BOM = 65279;
2017
+ var CHAR_TAB = 9;
2018
+ var CHAR_LINE_FEED = 10;
2019
+ var CHAR_CARRIAGE_RETURN = 13;
2020
+ var CHAR_SPACE = 32;
2021
+ var CHAR_EXCLAMATION = 33;
2022
+ var CHAR_DOUBLE_QUOTE = 34;
2023
+ var CHAR_SHARP = 35;
2024
+ var CHAR_PERCENT = 37;
2025
+ var CHAR_AMPERSAND = 38;
2026
+ var CHAR_SINGLE_QUOTE = 39;
2027
+ var CHAR_ASTERISK = 42;
2028
+ var CHAR_COMMA = 44;
2029
+ var CHAR_MINUS = 45;
2030
+ var CHAR_COLON = 58;
2031
+ var CHAR_EQUALS = 61;
2032
+ var CHAR_GREATER_THAN = 62;
2033
+ var CHAR_QUESTION = 63;
2034
+ var CHAR_COMMERCIAL_AT = 64;
2035
+ var CHAR_LEFT_SQUARE_BRACKET = 91;
2036
+ var CHAR_RIGHT_SQUARE_BRACKET = 93;
2037
+ var CHAR_GRAVE_ACCENT = 96;
2038
+ var CHAR_LEFT_CURLY_BRACKET = 123;
2039
+ var CHAR_VERTICAL_LINE = 124;
2040
+ var CHAR_RIGHT_CURLY_BRACKET = 125;
2041
+ var ESCAPE_SEQUENCES = {};
2042
+ ESCAPE_SEQUENCES[0] = "\\0";
2043
+ ESCAPE_SEQUENCES[7] = "\\a";
2044
+ ESCAPE_SEQUENCES[8] = "\\b";
2045
+ ESCAPE_SEQUENCES[9] = "\\t";
2046
+ ESCAPE_SEQUENCES[10] = "\\n";
2047
+ ESCAPE_SEQUENCES[11] = "\\v";
2048
+ ESCAPE_SEQUENCES[12] = "\\f";
2049
+ ESCAPE_SEQUENCES[13] = "\\r";
2050
+ ESCAPE_SEQUENCES[27] = "\\e";
2051
+ ESCAPE_SEQUENCES[34] = "\\\"";
2052
+ ESCAPE_SEQUENCES[92] = "\\\\";
2053
+ ESCAPE_SEQUENCES[133] = "\\N";
2054
+ ESCAPE_SEQUENCES[160] = "\\_";
2055
+ ESCAPE_SEQUENCES[8232] = "\\L";
2056
+ ESCAPE_SEQUENCES[8233] = "\\P";
2057
+ var DEPRECATED_BOOLEANS_SYNTAX = [
2058
+ "y",
2059
+ "Y",
2060
+ "yes",
2061
+ "Yes",
2062
+ "YES",
2063
+ "on",
2064
+ "On",
2065
+ "ON",
2066
+ "n",
2067
+ "N",
2068
+ "no",
2069
+ "No",
2070
+ "NO",
2071
+ "off",
2072
+ "Off",
2073
+ "OFF"
2074
+ ];
2075
+ var DEPRECATED_BASE60_SYNTAX = /^[-+]?[0-9_]+(?::[0-9_]+)+(?:\.[0-9_]*)?$/;
2076
+ function compileStyleMap(schema2, map2) {
2077
+ var result, keys, index, length, tag, style, type2;
2078
+ if (map2 === null)
2079
+ return {};
2080
+ result = {};
2081
+ keys = Object.keys(map2);
2082
+ for (index = 0, length = keys.length;index < length; index += 1) {
2083
+ tag = keys[index];
2084
+ style = String(map2[tag]);
2085
+ if (tag.slice(0, 2) === "!!") {
2086
+ tag = "tag:yaml.org,2002:" + tag.slice(2);
2087
+ }
2088
+ type2 = schema2.compiledTypeMap["fallback"][tag];
2089
+ if (type2 && _hasOwnProperty.call(type2.styleAliases, style)) {
2090
+ style = type2.styleAliases[style];
2091
+ }
2092
+ result[tag] = style;
2093
+ }
2094
+ return result;
2095
+ }
2096
+ function encodeHex(character) {
2097
+ var string, handle, length;
2098
+ string = character.toString(16).toUpperCase();
2099
+ if (character <= 255) {
2100
+ handle = "x";
2101
+ length = 2;
2102
+ } else if (character <= 65535) {
2103
+ handle = "u";
2104
+ length = 4;
2105
+ } else if (character <= 4294967295) {
2106
+ handle = "U";
2107
+ length = 8;
2108
+ } else {
2109
+ throw new exception("code point within a string may not be greater than 0xFFFFFFFF");
2110
+ }
2111
+ return "\\" + handle + common.repeat("0", length - string.length) + string;
2112
+ }
2113
+ var QUOTING_TYPE_SINGLE = 1;
2114
+ var QUOTING_TYPE_DOUBLE = 2;
2115
+ function State(options) {
2116
+ this.schema = options["schema"] || _default;
2117
+ this.indent = Math.max(1, options["indent"] || 2);
2118
+ this.noArrayIndent = options["noArrayIndent"] || false;
2119
+ this.skipInvalid = options["skipInvalid"] || false;
2120
+ this.flowLevel = common.isNothing(options["flowLevel"]) ? -1 : options["flowLevel"];
2121
+ this.styleMap = compileStyleMap(this.schema, options["styles"] || null);
2122
+ this.sortKeys = options["sortKeys"] || false;
2123
+ this.lineWidth = options["lineWidth"] || 80;
2124
+ this.noRefs = options["noRefs"] || false;
2125
+ this.noCompatMode = options["noCompatMode"] || false;
2126
+ this.condenseFlow = options["condenseFlow"] || false;
2127
+ this.quotingType = options["quotingType"] === '"' ? QUOTING_TYPE_DOUBLE : QUOTING_TYPE_SINGLE;
2128
+ this.forceQuotes = options["forceQuotes"] || false;
2129
+ this.replacer = typeof options["replacer"] === "function" ? options["replacer"] : null;
2130
+ this.implicitTypes = this.schema.compiledImplicit;
2131
+ this.explicitTypes = this.schema.compiledExplicit;
2132
+ this.tag = null;
2133
+ this.result = "";
2134
+ this.duplicates = [];
2135
+ this.usedDuplicates = null;
2136
+ }
2137
+ function indentString(string, spaces) {
2138
+ var ind = common.repeat(" ", spaces), position = 0, next = -1, result = "", line, length = string.length;
2139
+ while (position < length) {
2140
+ next = string.indexOf(`
2141
+ `, position);
2142
+ if (next === -1) {
2143
+ line = string.slice(position);
2144
+ position = length;
2145
+ } else {
2146
+ line = string.slice(position, next + 1);
2147
+ position = next + 1;
2148
+ }
2149
+ if (line.length && line !== `
2150
+ `)
2151
+ result += ind;
2152
+ result += line;
2153
+ }
2154
+ return result;
2155
+ }
2156
+ function generateNextLine(state, level) {
2157
+ return `
2158
+ ` + common.repeat(" ", state.indent * level);
2159
+ }
2160
+ function testImplicitResolving(state, str2) {
2161
+ var index, length, type2;
2162
+ for (index = 0, length = state.implicitTypes.length;index < length; index += 1) {
2163
+ type2 = state.implicitTypes[index];
2164
+ if (type2.resolve(str2)) {
2165
+ return true;
2166
+ }
2167
+ }
2168
+ return false;
2169
+ }
2170
+ function isWhitespace(c) {
2171
+ return c === CHAR_SPACE || c === CHAR_TAB;
2172
+ }
2173
+ function isPrintable(c) {
2174
+ return 32 <= c && c <= 126 || 161 <= c && c <= 55295 && c !== 8232 && c !== 8233 || 57344 <= c && c <= 65533 && c !== CHAR_BOM || 65536 <= c && c <= 1114111;
2175
+ }
2176
+ function isNsCharOrWhitespace(c) {
2177
+ return isPrintable(c) && c !== CHAR_BOM && c !== CHAR_CARRIAGE_RETURN && c !== CHAR_LINE_FEED;
2178
+ }
2179
+ function isPlainSafe(c, prev, inblock) {
2180
+ var cIsNsCharOrWhitespace = isNsCharOrWhitespace(c);
2181
+ var cIsNsChar = cIsNsCharOrWhitespace && !isWhitespace(c);
2182
+ return (inblock ? cIsNsCharOrWhitespace : cIsNsCharOrWhitespace && c !== CHAR_COMMA && c !== CHAR_LEFT_SQUARE_BRACKET && c !== CHAR_RIGHT_SQUARE_BRACKET && c !== CHAR_LEFT_CURLY_BRACKET && c !== CHAR_RIGHT_CURLY_BRACKET) && c !== CHAR_SHARP && !(prev === CHAR_COLON && !cIsNsChar) || isNsCharOrWhitespace(prev) && !isWhitespace(prev) && c === CHAR_SHARP || prev === CHAR_COLON && cIsNsChar;
2183
+ }
2184
+ function isPlainSafeFirst(c) {
2185
+ return isPrintable(c) && c !== CHAR_BOM && !isWhitespace(c) && 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 && 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 && c !== CHAR_PERCENT && c !== CHAR_COMMERCIAL_AT && c !== CHAR_GRAVE_ACCENT;
2186
+ }
2187
+ function isPlainSafeLast(c) {
2188
+ return !isWhitespace(c) && c !== CHAR_COLON;
2189
+ }
2190
+ function codePointAt(string, pos) {
2191
+ var first = string.charCodeAt(pos), second;
2192
+ if (first >= 55296 && first <= 56319 && pos + 1 < string.length) {
2193
+ second = string.charCodeAt(pos + 1);
2194
+ if (second >= 56320 && second <= 57343) {
2195
+ return (first - 55296) * 1024 + second - 56320 + 65536;
2196
+ }
2197
+ }
2198
+ return first;
2199
+ }
2200
+ function needIndentIndicator(string) {
2201
+ var leadingSpaceRe = /^\n* /;
2202
+ return leadingSpaceRe.test(string);
2203
+ }
2204
+ var STYLE_PLAIN = 1;
2205
+ var STYLE_SINGLE = 2;
2206
+ var STYLE_LITERAL = 3;
2207
+ var STYLE_FOLDED = 4;
2208
+ var STYLE_DOUBLE = 5;
2209
+ function chooseScalarStyle(string, singleLineOnly, indentPerLevel, lineWidth, testAmbiguousType, quotingType, forceQuotes, inblock) {
2210
+ var i2;
2211
+ var char = 0;
2212
+ var prevChar = null;
2213
+ var hasLineBreak = false;
2214
+ var hasFoldableLine = false;
2215
+ var shouldTrackWidth = lineWidth !== -1;
2216
+ var previousLineBreak = -1;
2217
+ var plain = isPlainSafeFirst(codePointAt(string, 0)) && isPlainSafeLast(codePointAt(string, string.length - 1));
2218
+ if (singleLineOnly || forceQuotes) {
2219
+ for (i2 = 0;i2 < string.length; char >= 65536 ? i2 += 2 : i2++) {
2220
+ char = codePointAt(string, i2);
2221
+ if (!isPrintable(char)) {
2222
+ return STYLE_DOUBLE;
2223
+ }
2224
+ plain = plain && isPlainSafe(char, prevChar, inblock);
2225
+ prevChar = char;
2226
+ }
2227
+ } else {
2228
+ for (i2 = 0;i2 < string.length; char >= 65536 ? i2 += 2 : i2++) {
2229
+ char = codePointAt(string, i2);
2230
+ if (char === CHAR_LINE_FEED) {
2231
+ hasLineBreak = true;
2232
+ if (shouldTrackWidth) {
2233
+ hasFoldableLine = hasFoldableLine || i2 - previousLineBreak - 1 > lineWidth && string[previousLineBreak + 1] !== " ";
2234
+ previousLineBreak = i2;
2235
+ }
2236
+ } else if (!isPrintable(char)) {
2237
+ return STYLE_DOUBLE;
2238
+ }
2239
+ plain = plain && isPlainSafe(char, prevChar, inblock);
2240
+ prevChar = char;
2241
+ }
2242
+ hasFoldableLine = hasFoldableLine || shouldTrackWidth && (i2 - previousLineBreak - 1 > lineWidth && string[previousLineBreak + 1] !== " ");
2243
+ }
2244
+ if (!hasLineBreak && !hasFoldableLine) {
2245
+ if (plain && !forceQuotes && !testAmbiguousType(string)) {
2246
+ return STYLE_PLAIN;
2247
+ }
2248
+ return quotingType === QUOTING_TYPE_DOUBLE ? STYLE_DOUBLE : STYLE_SINGLE;
2249
+ }
2250
+ if (indentPerLevel > 9 && needIndentIndicator(string)) {
2251
+ return STYLE_DOUBLE;
2252
+ }
2253
+ if (!forceQuotes) {
2254
+ return hasFoldableLine ? STYLE_FOLDED : STYLE_LITERAL;
2255
+ }
2256
+ return quotingType === QUOTING_TYPE_DOUBLE ? STYLE_DOUBLE : STYLE_SINGLE;
2257
+ }
2258
+ function writeScalar(state, string, level, iskey, inblock) {
2259
+ state.dump = function() {
2260
+ if (string.length === 0) {
2261
+ return state.quotingType === QUOTING_TYPE_DOUBLE ? '""' : "''";
2262
+ }
2263
+ if (!state.noCompatMode) {
2264
+ if (DEPRECATED_BOOLEANS_SYNTAX.indexOf(string) !== -1 || DEPRECATED_BASE60_SYNTAX.test(string)) {
2265
+ return state.quotingType === QUOTING_TYPE_DOUBLE ? '"' + string + '"' : "'" + string + "'";
2266
+ }
2267
+ }
2268
+ var indent = state.indent * Math.max(1, level);
2269
+ var lineWidth = state.lineWidth === -1 ? -1 : Math.max(Math.min(state.lineWidth, 40), state.lineWidth - indent);
2270
+ var singleLineOnly = iskey || state.flowLevel > -1 && level >= state.flowLevel;
2271
+ function testAmbiguity(string2) {
2272
+ return testImplicitResolving(state, string2);
2273
+ }
2274
+ switch (chooseScalarStyle(string, singleLineOnly, state.indent, lineWidth, testAmbiguity, state.quotingType, state.forceQuotes && !iskey, inblock)) {
2275
+ case STYLE_PLAIN:
2276
+ return string;
2277
+ case STYLE_SINGLE:
2278
+ return "'" + string.replace(/'/g, "''") + "'";
2279
+ case STYLE_LITERAL:
2280
+ return "|" + blockHeader(string, state.indent) + dropEndingNewline(indentString(string, indent));
2281
+ case STYLE_FOLDED:
2282
+ return ">" + blockHeader(string, state.indent) + dropEndingNewline(indentString(foldString(string, lineWidth), indent));
2283
+ case STYLE_DOUBLE:
2284
+ return '"' + escapeString(string) + '"';
2285
+ default:
2286
+ throw new exception("impossible error: invalid scalar style");
2287
+ }
2288
+ }();
2289
+ }
2290
+ function blockHeader(string, indentPerLevel) {
2291
+ var indentIndicator = needIndentIndicator(string) ? String(indentPerLevel) : "";
2292
+ var clip = string[string.length - 1] === `
2293
+ `;
2294
+ var keep = clip && (string[string.length - 2] === `
2295
+ ` || string === `
2296
+ `);
2297
+ var chomp = keep ? "+" : clip ? "" : "-";
2298
+ return indentIndicator + chomp + `
2299
+ `;
2300
+ }
2301
+ function dropEndingNewline(string) {
2302
+ return string[string.length - 1] === `
2303
+ ` ? string.slice(0, -1) : string;
2304
+ }
2305
+ function foldString(string, width) {
2306
+ var lineRe = /(\n+)([^\n]*)/g;
2307
+ var result = function() {
2308
+ var nextLF = string.indexOf(`
2309
+ `);
2310
+ nextLF = nextLF !== -1 ? nextLF : string.length;
2311
+ lineRe.lastIndex = nextLF;
2312
+ return foldLine(string.slice(0, nextLF), width);
2313
+ }();
2314
+ var prevMoreIndented = string[0] === `
2315
+ ` || string[0] === " ";
2316
+ var moreIndented;
2317
+ var match;
2318
+ while (match = lineRe.exec(string)) {
2319
+ var prefix = match[1], line = match[2];
2320
+ moreIndented = line[0] === " ";
2321
+ result += prefix + (!prevMoreIndented && !moreIndented && line !== "" ? `
2322
+ ` : "") + foldLine(line, width);
2323
+ prevMoreIndented = moreIndented;
2324
+ }
2325
+ return result;
2326
+ }
2327
+ function foldLine(line, width) {
2328
+ if (line === "" || line[0] === " ")
2329
+ return line;
2330
+ var breakRe = / [^ ]/g;
2331
+ var match;
2332
+ var start = 0, end, curr = 0, next = 0;
2333
+ var result = "";
2334
+ while (match = breakRe.exec(line)) {
2335
+ next = match.index;
2336
+ if (next - start > width) {
2337
+ end = curr > start ? curr : next;
2338
+ result += `
2339
+ ` + line.slice(start, end);
2340
+ start = end + 1;
2341
+ }
2342
+ curr = next;
2343
+ }
2344
+ result += `
2345
+ `;
2346
+ if (line.length - start > width && curr > start) {
2347
+ result += line.slice(start, curr) + `
2348
+ ` + line.slice(curr + 1);
2349
+ } else {
2350
+ result += line.slice(start);
2351
+ }
2352
+ return result.slice(1);
2353
+ }
2354
+ function escapeString(string) {
2355
+ var result = "";
2356
+ var char = 0;
2357
+ var escapeSeq;
2358
+ for (var i2 = 0;i2 < string.length; char >= 65536 ? i2 += 2 : i2++) {
2359
+ char = codePointAt(string, i2);
2360
+ escapeSeq = ESCAPE_SEQUENCES[char];
2361
+ if (!escapeSeq && isPrintable(char)) {
2362
+ result += string[i2];
2363
+ if (char >= 65536)
2364
+ result += string[i2 + 1];
2365
+ } else {
2366
+ result += escapeSeq || encodeHex(char);
2367
+ }
2368
+ }
2369
+ return result;
2370
+ }
2371
+ function writeFlowSequence(state, level, object) {
2372
+ var _result = "", _tag = state.tag, index, length, value;
2373
+ for (index = 0, length = object.length;index < length; index += 1) {
2374
+ value = object[index];
2375
+ if (state.replacer) {
2376
+ value = state.replacer.call(object, String(index), value);
2377
+ }
2378
+ if (writeNode(state, level, value, false, false) || typeof value === "undefined" && writeNode(state, level, null, false, false)) {
2379
+ if (_result !== "")
2380
+ _result += "," + (!state.condenseFlow ? " " : "");
2381
+ _result += state.dump;
2382
+ }
2383
+ }
2384
+ state.tag = _tag;
2385
+ state.dump = "[" + _result + "]";
2386
+ }
2387
+ function writeBlockSequence(state, level, object, compact) {
2388
+ var _result = "", _tag = state.tag, index, length, value;
2389
+ for (index = 0, length = object.length;index < length; index += 1) {
2390
+ value = object[index];
2391
+ if (state.replacer) {
2392
+ value = state.replacer.call(object, String(index), value);
2393
+ }
2394
+ if (writeNode(state, level + 1, value, true, true, false, true) || typeof value === "undefined" && writeNode(state, level + 1, null, true, true, false, true)) {
2395
+ if (!compact || _result !== "") {
2396
+ _result += generateNextLine(state, level);
2397
+ }
2398
+ if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) {
2399
+ _result += "-";
2400
+ } else {
2401
+ _result += "- ";
2402
+ }
2403
+ _result += state.dump;
2404
+ }
2405
+ }
2406
+ state.tag = _tag;
2407
+ state.dump = _result || "[]";
2408
+ }
2409
+ function writeFlowMapping(state, level, object) {
2410
+ var _result = "", _tag = state.tag, objectKeyList = Object.keys(object), index, length, objectKey, objectValue, pairBuffer;
2411
+ for (index = 0, length = objectKeyList.length;index < length; index += 1) {
2412
+ pairBuffer = "";
2413
+ if (_result !== "")
2414
+ pairBuffer += ", ";
2415
+ if (state.condenseFlow)
2416
+ pairBuffer += '"';
2417
+ objectKey = objectKeyList[index];
2418
+ objectValue = object[objectKey];
2419
+ if (state.replacer) {
2420
+ objectValue = state.replacer.call(object, objectKey, objectValue);
2421
+ }
2422
+ if (!writeNode(state, level, objectKey, false, false)) {
2423
+ continue;
2424
+ }
2425
+ if (state.dump.length > 1024)
2426
+ pairBuffer += "? ";
2427
+ pairBuffer += state.dump + (state.condenseFlow ? '"' : "") + ":" + (state.condenseFlow ? "" : " ");
2428
+ if (!writeNode(state, level, objectValue, false, false)) {
2429
+ continue;
2430
+ }
2431
+ pairBuffer += state.dump;
2432
+ _result += pairBuffer;
2433
+ }
2434
+ state.tag = _tag;
2435
+ state.dump = "{" + _result + "}";
2436
+ }
2437
+ function writeBlockMapping(state, level, object, compact) {
2438
+ var _result = "", _tag = state.tag, objectKeyList = Object.keys(object), index, length, objectKey, objectValue, explicitPair, pairBuffer;
2439
+ if (state.sortKeys === true) {
2440
+ objectKeyList.sort();
2441
+ } else if (typeof state.sortKeys === "function") {
2442
+ objectKeyList.sort(state.sortKeys);
2443
+ } else if (state.sortKeys) {
2444
+ throw new exception("sortKeys must be a boolean or a function");
2445
+ }
2446
+ for (index = 0, length = objectKeyList.length;index < length; index += 1) {
2447
+ pairBuffer = "";
2448
+ if (!compact || _result !== "") {
2449
+ pairBuffer += generateNextLine(state, level);
2450
+ }
2451
+ objectKey = objectKeyList[index];
2452
+ objectValue = object[objectKey];
2453
+ if (state.replacer) {
2454
+ objectValue = state.replacer.call(object, objectKey, objectValue);
2455
+ }
2456
+ if (!writeNode(state, level + 1, objectKey, true, true, true)) {
2457
+ continue;
2458
+ }
2459
+ explicitPair = state.tag !== null && state.tag !== "?" || state.dump && state.dump.length > 1024;
2460
+ if (explicitPair) {
2461
+ if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) {
2462
+ pairBuffer += "?";
2463
+ } else {
2464
+ pairBuffer += "? ";
2465
+ }
2466
+ }
2467
+ pairBuffer += state.dump;
2468
+ if (explicitPair) {
2469
+ pairBuffer += generateNextLine(state, level);
2470
+ }
2471
+ if (!writeNode(state, level + 1, objectValue, true, explicitPair)) {
2472
+ continue;
2473
+ }
2474
+ if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) {
2475
+ pairBuffer += ":";
2476
+ } else {
2477
+ pairBuffer += ": ";
2478
+ }
2479
+ pairBuffer += state.dump;
2480
+ _result += pairBuffer;
2481
+ }
2482
+ state.tag = _tag;
2483
+ state.dump = _result || "{}";
2484
+ }
2485
+ function detectType(state, object, explicit) {
2486
+ var _result, typeList, index, length, type2, style;
2487
+ typeList = explicit ? state.explicitTypes : state.implicitTypes;
2488
+ for (index = 0, length = typeList.length;index < length; index += 1) {
2489
+ type2 = typeList[index];
2490
+ if ((type2.instanceOf || type2.predicate) && (!type2.instanceOf || typeof object === "object" && object instanceof type2.instanceOf) && (!type2.predicate || type2.predicate(object))) {
2491
+ if (explicit) {
2492
+ if (type2.multi && type2.representName) {
2493
+ state.tag = type2.representName(object);
2494
+ } else {
2495
+ state.tag = type2.tag;
2496
+ }
2497
+ } else {
2498
+ state.tag = "?";
2499
+ }
2500
+ if (type2.represent) {
2501
+ style = state.styleMap[type2.tag] || type2.defaultStyle;
2502
+ if (_toString.call(type2.represent) === "[object Function]") {
2503
+ _result = type2.represent(object, style);
2504
+ } else if (_hasOwnProperty.call(type2.represent, style)) {
2505
+ _result = type2.represent[style](object, style);
2506
+ } else {
2507
+ throw new exception("!<" + type2.tag + '> tag resolver accepts not "' + style + '" style');
2508
+ }
2509
+ state.dump = _result;
2510
+ }
2511
+ return true;
2512
+ }
2513
+ }
2514
+ return false;
2515
+ }
2516
+ function writeNode(state, level, object, block, compact, iskey, isblockseq) {
2517
+ state.tag = null;
2518
+ state.dump = object;
2519
+ if (!detectType(state, object, false)) {
2520
+ detectType(state, object, true);
2521
+ }
2522
+ var type2 = _toString.call(state.dump);
2523
+ var inblock = block;
2524
+ var tagStr;
2525
+ if (block) {
2526
+ block = state.flowLevel < 0 || state.flowLevel > level;
2527
+ }
2528
+ var objectOrArray = type2 === "[object Object]" || type2 === "[object Array]", duplicateIndex, duplicate;
2529
+ if (objectOrArray) {
2530
+ duplicateIndex = state.duplicates.indexOf(object);
2531
+ duplicate = duplicateIndex !== -1;
2532
+ }
2533
+ if (state.tag !== null && state.tag !== "?" || duplicate || state.indent !== 2 && level > 0) {
2534
+ compact = false;
2535
+ }
2536
+ if (duplicate && state.usedDuplicates[duplicateIndex]) {
2537
+ state.dump = "*ref_" + duplicateIndex;
2538
+ } else {
2539
+ if (objectOrArray && duplicate && !state.usedDuplicates[duplicateIndex]) {
2540
+ state.usedDuplicates[duplicateIndex] = true;
2541
+ }
2542
+ if (type2 === "[object Object]") {
2543
+ if (block && Object.keys(state.dump).length !== 0) {
2544
+ writeBlockMapping(state, level, state.dump, compact);
2545
+ if (duplicate) {
2546
+ state.dump = "&ref_" + duplicateIndex + state.dump;
2547
+ }
2548
+ } else {
2549
+ writeFlowMapping(state, level, state.dump);
2550
+ if (duplicate) {
2551
+ state.dump = "&ref_" + duplicateIndex + " " + state.dump;
2552
+ }
2553
+ }
2554
+ } else if (type2 === "[object Array]") {
2555
+ if (block && state.dump.length !== 0) {
2556
+ if (state.noArrayIndent && !isblockseq && level > 0) {
2557
+ writeBlockSequence(state, level - 1, state.dump, compact);
2558
+ } else {
2559
+ writeBlockSequence(state, level, state.dump, compact);
2560
+ }
2561
+ if (duplicate) {
2562
+ state.dump = "&ref_" + duplicateIndex + state.dump;
2563
+ }
2564
+ } else {
2565
+ writeFlowSequence(state, level, state.dump);
2566
+ if (duplicate) {
2567
+ state.dump = "&ref_" + duplicateIndex + " " + state.dump;
2568
+ }
2569
+ }
2570
+ } else if (type2 === "[object String]") {
2571
+ if (state.tag !== "?") {
2572
+ writeScalar(state, state.dump, level, iskey, inblock);
2573
+ }
2574
+ } else if (type2 === "[object Undefined]") {
2575
+ return false;
2576
+ } else {
2577
+ if (state.skipInvalid)
2578
+ return false;
2579
+ throw new exception("unacceptable kind of an object to dump " + type2);
2580
+ }
2581
+ if (state.tag !== null && state.tag !== "?") {
2582
+ tagStr = encodeURI(state.tag[0] === "!" ? state.tag.slice(1) : state.tag).replace(/!/g, "%21");
2583
+ if (state.tag[0] === "!") {
2584
+ tagStr = "!" + tagStr;
2585
+ } else if (tagStr.slice(0, 18) === "tag:yaml.org,2002:") {
2586
+ tagStr = "!!" + tagStr.slice(18);
2587
+ } else {
2588
+ tagStr = "!<" + tagStr + ">";
2589
+ }
2590
+ state.dump = tagStr + " " + state.dump;
2591
+ }
2592
+ }
2593
+ return true;
2594
+ }
2595
+ function getDuplicateReferences(object, state) {
2596
+ var objects = [], duplicatesIndexes = [], index, length;
2597
+ inspectNode(object, objects, duplicatesIndexes);
2598
+ for (index = 0, length = duplicatesIndexes.length;index < length; index += 1) {
2599
+ state.duplicates.push(objects[duplicatesIndexes[index]]);
2600
+ }
2601
+ state.usedDuplicates = new Array(length);
2602
+ }
2603
+ function inspectNode(object, objects, duplicatesIndexes) {
2604
+ var objectKeyList, index, length;
2605
+ if (object !== null && typeof object === "object") {
2606
+ index = objects.indexOf(object);
2607
+ if (index !== -1) {
2608
+ if (duplicatesIndexes.indexOf(index) === -1) {
2609
+ duplicatesIndexes.push(index);
2610
+ }
2611
+ } else {
2612
+ objects.push(object);
2613
+ if (Array.isArray(object)) {
2614
+ for (index = 0, length = object.length;index < length; index += 1) {
2615
+ inspectNode(object[index], objects, duplicatesIndexes);
2616
+ }
2617
+ } else {
2618
+ objectKeyList = Object.keys(object);
2619
+ for (index = 0, length = objectKeyList.length;index < length; index += 1) {
2620
+ inspectNode(object[objectKeyList[index]], objects, duplicatesIndexes);
2621
+ }
2622
+ }
2623
+ }
2624
+ }
2625
+ }
2626
+ function dump$1(input, options) {
2627
+ options = options || {};
2628
+ var state = new State(options);
2629
+ if (!state.noRefs)
2630
+ getDuplicateReferences(input, state);
2631
+ var value = input;
2632
+ if (state.replacer) {
2633
+ value = state.replacer.call({ "": value }, "", value);
2634
+ }
2635
+ if (writeNode(state, 0, value, true, true))
2636
+ return state.dump + `
2637
+ `;
2638
+ return "";
2639
+ }
2640
+ var dump_1 = dump$1;
2641
+ var dumper = {
2642
+ dump: dump_1
2643
+ };
2644
+ function renamed(from, to) {
2645
+ return function() {
2646
+ throw new Error("Function yaml." + from + " is removed in js-yaml 4. " + "Use yaml." + to + " instead, which is now safe by default.");
2647
+ };
2648
+ }
2649
+ var Type = type;
2650
+ var Schema = schema;
2651
+ var FAILSAFE_SCHEMA = failsafe;
2652
+ var JSON_SCHEMA = json;
2653
+ var CORE_SCHEMA = core;
2654
+ var DEFAULT_SCHEMA = _default;
2655
+ var load = loader.load;
2656
+ var loadAll = loader.loadAll;
2657
+ var dump = dumper.dump;
2658
+ var YAMLException = exception;
2659
+ var types = {
2660
+ binary,
2661
+ float,
2662
+ map,
2663
+ null: _null,
2664
+ pairs,
2665
+ set,
2666
+ timestamp,
2667
+ bool,
2668
+ int,
2669
+ merge,
2670
+ omap,
2671
+ seq,
2672
+ str
2673
+ };
2674
+ var safeLoad = renamed("safeLoad", "load");
2675
+ var safeLoadAll = renamed("safeLoadAll", "loadAll");
2676
+ var safeDump = renamed("safeDump", "dump");
2677
+ var jsYaml = {
2678
+ Type,
2679
+ Schema,
2680
+ FAILSAFE_SCHEMA,
2681
+ JSON_SCHEMA,
2682
+ CORE_SCHEMA,
2683
+ DEFAULT_SCHEMA,
2684
+ load,
2685
+ loadAll,
2686
+ dump,
2687
+ YAMLException,
2688
+ types,
2689
+ safeLoad,
2690
+ safeLoadAll,
2691
+ safeDump
2692
+ };
2693
+
2694
+ // src/lib/frontmatter.ts
2695
+ function parseFrontmatter(content) {
2696
+ const frontmatterRegex = /^---\r?\n([\s\S]*?)\r?\n?---\r?\n([\s\S]*)$/;
2697
+ const match = content.match(frontmatterRegex);
2698
+ if (!match) {
2699
+ return {
2700
+ data: {},
2701
+ body: content,
2702
+ hadFrontmatter: false,
2703
+ parseError: false
2704
+ };
2705
+ }
2706
+ const yamlContent = match[1];
2707
+ const body = match[2];
2708
+ try {
2709
+ const parsed = jsYaml.load(yamlContent, { schema: jsYaml.JSON_SCHEMA });
2710
+ const data = parsed ?? {};
2711
+ return { data, body, hadFrontmatter: true, parseError: false };
2712
+ } catch {
2713
+ return { data: {}, body, hadFrontmatter: true, parseError: true };
2714
+ }
2715
+ }
2716
+
2717
+ // src/lib/validation.ts
2718
+ function isRecord(value) {
2719
+ return typeof value === "object" && value !== null && !Array.isArray(value);
2720
+ }
2721
+ function extractString(data, key, fallback = "") {
2722
+ const value = data[key];
2723
+ return typeof value === "string" ? value : fallback;
2724
+ }
2725
+ function extractNonEmptyString(data, key) {
2726
+ const value = data[key];
2727
+ if (typeof value !== "string")
2728
+ return;
2729
+ const trimmed = value.trim();
2730
+ return trimmed !== "" ? trimmed : undefined;
2731
+ }
2732
+ function extractBoolean(data, key) {
2733
+ const value = data[key];
2734
+ if (typeof value === "boolean")
2735
+ return value;
2736
+ if (typeof value === "string") {
2737
+ const normalized = value.trim().toLowerCase();
2738
+ if (normalized === "true")
2739
+ return true;
2740
+ if (normalized === "false")
2741
+ return false;
2742
+ }
2743
+ return;
2744
+ }
2745
+
2746
+ // src/lib/walk-dir.ts
2747
+ import fs from "node:fs";
2748
+ import path from "node:path";
2749
+ function walkDir(rootDir, options = {}) {
2750
+ const { maxDepth = 3, filter } = options;
2751
+ const results = [];
2752
+ if (!fs.existsSync(rootDir))
2753
+ return results;
2754
+ function recurse(currentDir, depth, category) {
2755
+ if (depth > maxDepth)
2756
+ return;
2757
+ const entries = fs.readdirSync(currentDir, { withFileTypes: true });
2758
+ for (const entry of entries) {
2759
+ const fullPath = path.join(currentDir, entry.name);
2760
+ const walkEntry = {
2761
+ path: fullPath,
2762
+ name: entry.name,
2763
+ isDirectory: entry.isDirectory(),
2764
+ depth,
2765
+ category
2766
+ };
2767
+ if (!filter || filter(walkEntry)) {
2768
+ results.push(walkEntry);
2769
+ }
2770
+ if (entry.isDirectory()) {
2771
+ recurse(fullPath, depth + 1, entry.name);
2772
+ }
2773
+ }
2774
+ }
2775
+ recurse(rootDir, 0);
2776
+ return results;
2777
+ }
2778
+
2779
+ // src/lib/agents.ts
2780
+ function findAgentsInDir(dir, maxDepth = 2) {
2781
+ const entries = walkDir(dir, {
2782
+ maxDepth,
2783
+ filter: (e) => !e.isDirectory && e.name.endsWith(".md")
2784
+ });
2785
+ return entries.map((entry) => ({
2786
+ name: entry.name.replace(/\.md$/, ""),
2787
+ file: entry.path,
2788
+ category: entry.category
2789
+ }));
2790
+ }
2791
+
2792
+ // src/lib/agent-resolver.ts
2793
+ function buildAgentCatalog(agentsDir) {
2794
+ const infos = findAgentsInDir(agentsDir);
2795
+ const byName = new Map;
2796
+ const entries = [];
2797
+ for (const info of infos) {
2798
+ const content = fs2.readFileSync(info.file, "utf8");
2799
+ const entry = parseValidatedAgentEntry(content, info.file);
2800
+ try {
2801
+ resolveToolAllowlist(entry.toolsSource);
2802
+ } catch (error) {
2803
+ const message = error instanceof Error ? error.message : String(error);
2804
+ throw new Error(`Agent file "${info.file}": ${message}`);
2805
+ }
2806
+ const existing = byName.get(entry.name);
2807
+ if (existing) {
2808
+ existing.push(info.category ?? "(root)");
2809
+ } else {
2810
+ byName.set(entry.name, [info.category ?? "(root)"]);
2811
+ }
2812
+ entries.push(entry);
2813
+ }
2814
+ const duplicates = [...byName.entries()].filter(([, cats]) => cats.length > 1);
2815
+ if (duplicates.length > 0) {
2816
+ const detail = duplicates.map(([name, cats]) => `"${name}" (categories: ${cats.join(", ")})`).join("; ");
2817
+ throw new Error(`Duplicate persona name(s) detected while flattening the agent catalog: ${detail}. ` + "Persona names must be unique across categories once category is dropped.");
2818
+ }
2819
+ return entries.sort((a, b) => a.name.localeCompare(b.name));
2820
+ }
2821
+ function parseValidatedAgentEntry(content, sourceFile) {
2822
+ const { data, body, parseError } = parseFrontmatter(content);
2823
+ if (parseError) {
2824
+ throw new Error(`Failed to parse YAML frontmatter in agent file "${sourceFile}".`);
2825
+ }
2826
+ const name = extractString(data, "name");
2827
+ if (name.trim() === "") {
2828
+ throw new Error(`Agent file "${sourceFile}" is missing a non-empty "name" in its frontmatter.`);
2829
+ }
2830
+ const description = extractString(data, "description");
2831
+ if (description.trim() === "") {
2832
+ throw new Error(`Agent file "${sourceFile}" is missing a non-empty "description" in its frontmatter.`);
2833
+ }
2834
+ const prompt = body.trim();
2835
+ if (prompt === "") {
2836
+ throw new Error(`Agent file "${sourceFile}" has an empty persona body (system prompt).`);
2837
+ }
2838
+ return {
2839
+ name,
2840
+ description,
2841
+ body: prompt,
2842
+ toolsSource: extractRawToolsSource(data, sourceFile)
2843
+ };
2844
+ }
2845
+ function extractRawToolsSource(data, sourceFile) {
2846
+ if (!("tools" in data))
2847
+ return;
2848
+ const value = data.tools;
2849
+ if (typeof value !== "string") {
2850
+ throw new Error(`Agent file "${sourceFile}" has a "tools" frontmatter value that is not a string; expected a comma-separated list (e.g. "Read, Grep, Glob, Bash").`);
2851
+ }
2852
+ const trimmed = value.trim();
2853
+ if (trimmed === "") {
2854
+ throw new Error(`Agent file "${sourceFile}" declares an empty "tools" frontmatter value.`);
2855
+ }
2856
+ return trimmed;
2857
+ }
2858
+ function resolveAgent(catalog, name) {
2859
+ return catalog.find((entry) => entry.name === name);
2860
+ }
2861
+ var DEFAULT_READONLY_TOOLS = ["read", "grep", "find", "ls"];
2862
+ var OPENCODE_TO_PI_TOOL = {
2863
+ Read: "read",
2864
+ Grep: "grep",
2865
+ Glob: "find",
2866
+ Bash: "bash",
2867
+ Edit: "edit",
2868
+ Write: "write"
2869
+ };
2870
+ function unknownDeclaredToolError(toolName) {
2871
+ const error = new Error(`Unknown declared tool "${toolName}" in persona frontmatter; refusing to map ` + "to a Pi built-in (fail-closed). Known tools: " + `${Object.keys(OPENCODE_TO_PI_TOOL).join(", ")}.`);
2872
+ error.name = "UnknownDeclaredToolError";
2873
+ return error;
2874
+ }
2875
+ function resolveToolAllowlist(toolsSource) {
2876
+ if (toolsSource === undefined) {
2877
+ return { tools: [...DEFAULT_READONLY_TOOLS] };
2878
+ }
2879
+ const declared = toolsSource.split(",").map((t) => t.trim()).filter((t) => t !== "");
2880
+ const mapped = [];
2881
+ for (const name of declared) {
2882
+ if (name === "Task") {
2883
+ throw unknownDeclaredToolError(name);
2884
+ }
2885
+ const piName = OPENCODE_TO_PI_TOOL[name];
2886
+ if (!piName) {
2887
+ throw unknownDeclaredToolError(name);
2888
+ }
2889
+ mapped.push(piName);
2890
+ }
2891
+ return { tools: mapped };
2892
+ }
2893
+
2894
+ // src/lib/bootstrap.ts
2895
+ import fs5 from "node:fs";
2896
+ import os from "node:os";
2897
+ import path4 from "node:path";
2898
+
2899
+ // src/lib/skill-catalog.ts
2900
+ import { pathToFileURL } from "node:url";
2901
+
2902
+ // src/lib/skill-loader.ts
2903
+ import fs3 from "node:fs";
2904
+ import path2 from "node:path";
2905
+ var SKILL_PREFIX = "systematic:";
2906
+ var SKILL_DESCRIPTION_PREFIX = "(Systematic) ";
2907
+ function formatSkillCommandName(name) {
2908
+ if (name.includes(":")) {
2909
+ return name;
2910
+ }
2911
+ return `${SKILL_PREFIX}${name}`;
2912
+ }
2913
+ function formatSkillDescription(description, fallbackName) {
2914
+ const desc = description || `${fallbackName} skill`;
2915
+ if (desc.startsWith(SKILL_DESCRIPTION_PREFIX)) {
2916
+ return desc;
2917
+ }
2918
+ return `${SKILL_DESCRIPTION_PREFIX}${desc}`;
2919
+ }
2920
+ function wrapSkillTemplate(skillPath, body) {
2921
+ const skillDir = path2.dirname(skillPath);
2922
+ return `<skill-instruction>
2923
+ Base directory for this skill: ${skillDir}/
2924
+ File references (@path) in this skill are relative to this directory.
2925
+
2926
+ ${body.trim()}
2927
+ </skill-instruction>
2928
+
2929
+ <user-request>
2930
+ $ARGUMENTS
2931
+ </user-request>`;
2932
+ }
2933
+ function extractSkillBody(wrappedTemplate) {
2934
+ const match = wrappedTemplate.match(/<skill-instruction>([\s\S]*?)<\/skill-instruction>/);
2935
+ return match ? match[1].trim() : wrappedTemplate;
2936
+ }
2937
+ function loadSkill(skillInfo) {
2938
+ try {
2939
+ const content = fs3.readFileSync(skillInfo.skillFile, "utf8");
2940
+ const { body } = parseFrontmatter(content);
2941
+ const wrappedTemplate = wrapSkillTemplate(skillInfo.skillFile, body);
2942
+ return {
2943
+ name: skillInfo.name,
2944
+ prefixedName: formatSkillCommandName(skillInfo.name),
2945
+ description: formatSkillDescription(skillInfo.description, skillInfo.name),
2946
+ path: skillInfo.path,
2947
+ skillFile: skillInfo.skillFile,
2948
+ wrappedTemplate,
2949
+ disableModelInvocation: skillInfo.disableModelInvocation,
2950
+ userInvocable: skillInfo.userInvocable,
2951
+ subtask: skillInfo.subtask,
2952
+ agent: skillInfo.agent,
2953
+ model: skillInfo.model,
2954
+ argumentHint: skillInfo.argumentHint
2955
+ };
2956
+ } catch {
2957
+ return null;
2958
+ }
2959
+ }
2960
+
2961
+ // src/lib/skills.ts
2962
+ import fs4 from "node:fs";
2963
+ import path3 from "node:path";
2964
+ function parseMetadata(data) {
2965
+ const metadataRaw = data.metadata;
2966
+ if (!isRecord(metadataRaw)) {
2967
+ return;
2968
+ }
2969
+ const entries = Object.entries(metadataRaw);
2970
+ if (!entries.every(([, v]) => typeof v === "string")) {
2971
+ return;
2972
+ }
2973
+ return Object.fromEntries(entries);
2974
+ }
2975
+ function extractFrontmatterFromContent(content) {
2976
+ const { data, parseError } = parseFrontmatter(content);
2977
+ if (parseError) {
2978
+ return { name: "", description: "" };
2979
+ }
2980
+ const metadata = parseMetadata(data);
2981
+ const argumentHintRaw = extractNonEmptyString(data, "argument-hint");
2982
+ const argumentHint = argumentHintRaw?.replace(/^["']|["']$/g, "") || undefined;
2983
+ return {
2984
+ name: extractString(data, "name"),
2985
+ description: extractString(data, "description"),
2986
+ license: extractNonEmptyString(data, "license"),
2987
+ compatibility: extractNonEmptyString(data, "compatibility"),
2988
+ metadata,
2989
+ disableModelInvocation: extractBoolean(data, "disable-model-invocation"),
2990
+ userInvocable: extractBoolean(data, "user-invocable"),
2991
+ subtask: data.context === "fork" ? true : extractBoolean(data, "subtask") ?? undefined,
2992
+ agent: extractNonEmptyString(data, "agent"),
2993
+ model: extractNonEmptyString(data, "model"),
2994
+ argumentHint: argumentHint !== "" ? argumentHint : undefined,
2995
+ allowedTools: extractNonEmptyString(data, "allowed-tools")
2996
+ };
2997
+ }
2998
+ function extractFrontmatter(filePath) {
2999
+ try {
3000
+ const content = fs4.readFileSync(filePath, "utf8");
3001
+ return extractFrontmatterFromContent(content);
3002
+ } catch {
3003
+ return { name: "", description: "" };
3004
+ }
3005
+ }
3006
+ function findSkillsInDir(dir, maxDepth = 3) {
3007
+ const skills = [];
3008
+ const entries = walkDir(dir, {
3009
+ maxDepth,
3010
+ filter: (e) => e.isDirectory
3011
+ });
3012
+ for (const entry of entries) {
3013
+ const skillFile = path3.join(entry.path, "SKILL.md");
3014
+ if (fs4.existsSync(skillFile)) {
3015
+ const frontmatter = extractFrontmatter(skillFile);
3016
+ skills.push({
3017
+ path: entry.path,
3018
+ skillFile,
3019
+ name: frontmatter.name || entry.name,
3020
+ description: frontmatter.description || "",
3021
+ license: frontmatter.license,
3022
+ compatibility: frontmatter.compatibility,
3023
+ metadata: frontmatter.metadata,
3024
+ disableModelInvocation: frontmatter.disableModelInvocation,
3025
+ userInvocable: frontmatter.userInvocable,
3026
+ subtask: frontmatter.subtask,
3027
+ agent: frontmatter.agent,
3028
+ model: frontmatter.model,
3029
+ argumentHint: frontmatter.argumentHint,
3030
+ allowedTools: frontmatter.allowedTools
3031
+ });
3032
+ }
3033
+ }
3034
+ return skills;
3035
+ }
3036
+
3037
+ // src/lib/skill-catalog.ts
3038
+ function escapeXml(text) {
3039
+ return text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
3040
+ }
3041
+ function buildCatalogEntries(options) {
3042
+ const { bundledSkillsDir, disabledSkills } = options;
3043
+ return findSkillsInDir(bundledSkillsDir).filter((s) => !disabledSkills.includes(s.name)).filter((s) => s.disableModelInvocation !== true).sort((a, b) => a.name.localeCompare(b.name)).map((s) => ({
3044
+ name: s.name,
3045
+ prefixedName: formatSkillCommandName(s.name),
3046
+ description: s.description,
3047
+ path: s.path,
3048
+ skillFile: s.skillFile
3049
+ }));
3050
+ }
3051
+ function renderCatalogVerbose(options) {
3052
+ const entries = buildCatalogEntries(options);
3053
+ if (entries.length === 0)
3054
+ return "";
3055
+ const skillLines = entries.flatMap((entry) => [
3056
+ " <skill>",
3057
+ ` <name>${escapeXml(entry.prefixedName)}</name>`,
3058
+ ` <description>${escapeXml(entry.description)}</description>`,
3059
+ ` <location>${pathToFileURL(entry.path).href}</location>`,
3060
+ " </skill>"
3061
+ ]);
3062
+ return ["<available_skills>", ...skillLines, "</available_skills>"].join(`
3063
+ `);
3064
+ }
3065
+ function renderCatalogCompact(options) {
3066
+ const entries = buildCatalogEntries(options);
3067
+ const heading = "## Available Systematic Skills";
3068
+ if (entries.length === 0) {
3069
+ return `${heading}
3070
+
3071
+ No Systematic skills are currently available.`;
3072
+ }
3073
+ const bullets = entries.map((entry) => `- ${entry.prefixedName}: ${entry.description}`).join(`
3074
+ `);
3075
+ return `${heading}
3076
+
3077
+ ${bullets}`;
3078
+ }
3079
+
3080
+ // src/lib/bootstrap.ts
3081
+ var DEFAULT_BOOTSTRAP_CONFIG = {
3082
+ bootstrap: { enabled: true },
3083
+ disabled_skills: []
3084
+ };
3085
+ function computeBootstrapContentSafe(deps, reportError) {
3086
+ try {
3087
+ return getBootstrapContent(DEFAULT_BOOTSTRAP_CONFIG, deps);
3088
+ } catch (error) {
3089
+ if (reportError !== undefined) {
3090
+ try {
3091
+ reportError(error);
3092
+ } catch {}
3093
+ }
3094
+ return null;
3095
+ }
3096
+ }
3097
+ function composeSystemPromptWithBootstrap(existingSystemPrompt, bootstrapContent) {
3098
+ if (bootstrapContent === null)
3099
+ return null;
3100
+ if (existingSystemPrompt === bootstrapContent || existingSystemPrompt.endsWith(`
3101
+
3102
+ ${bootstrapContent}`)) {
3103
+ return existingSystemPrompt;
3104
+ }
3105
+ return existingSystemPrompt.length > 0 ? `${existingSystemPrompt}
3106
+
3107
+ ${bootstrapContent}` : bootstrapContent;
3108
+ }
3109
+ function getSkillUsageTemplate() {
3110
+ return `**Skills naming:**
3111
+ - Systematic bundled skills use the \`systematic:\` prefix (e.g., \`systematic:onboarding\`)
3112
+ - Workflow skills with their own namespace keep it (e.g., \`ce:brainstorm\`)
3113
+ - Skills can also be invoked without prefix if unambiguous
3114
+
3115
+ **Skills usage:**
3116
+ - Use \`systematic_skill\` to load Systematic bundled skills
3117
+ - Use the \`skill\` tool for non-Systematic skills
3118
+
3119
+ **Skills location:**
3120
+ Bundled skills ship with the Systematic plugin and are discoverable via \`systematic_skill\`.`;
3121
+ }
3122
+ function getBootstrapContent(config, deps) {
3123
+ const { bundledSkillsDir, usageTemplate } = deps;
3124
+ if (!config.bootstrap.enabled)
3125
+ return null;
3126
+ if (config.bootstrap.file) {
3127
+ const customPath = config.bootstrap.file.startsWith("~/") ? path4.join(os.homedir(), config.bootstrap.file.slice(2)) : config.bootstrap.file;
3128
+ if (fs5.existsSync(customPath)) {
3129
+ return fs5.readFileSync(customPath, "utf8");
3130
+ }
3131
+ }
3132
+ const usingSystematicPath = path4.join(bundledSkillsDir, "using-systematic/SKILL.md");
3133
+ if (!fs5.existsSync(usingSystematicPath))
3134
+ return null;
3135
+ const fullContent = fs5.readFileSync(usingSystematicPath, "utf8");
3136
+ const { body } = parseFrontmatter(fullContent);
3137
+ const content = body.trim();
3138
+ const skillUsage = usageTemplate ?? getSkillUsageTemplate();
3139
+ const catalog = renderCatalogVerbose({
3140
+ bundledSkillsDir,
3141
+ disabledSkills: config.disabled_skills
3142
+ });
3143
+ const catalogSection = catalog.length > 0 ? `
3144
+
3145
+ ${catalog}` : "";
3146
+ return `<SYSTEMATIC_WORKFLOWS>
3147
+ You have access to structured engineering workflows via the Systematic plugin.
3148
+
3149
+ **IMPORTANT: The using-systematic skill content is included below. It is ALREADY LOADED - you are currently following it. Do NOT use the systematic_skill tool to load "using-systematic" again - that would be redundant.**
3150
+
3151
+ ${content}
3152
+
3153
+ ${skillUsage}${catalogSection}
3154
+ </SYSTEMATIC_WORKFLOWS>`;
3155
+ }
3156
+
3157
+ // src/lib/pi-delegate-session.ts
3158
+ import {
3159
+ createAgentSession,
3160
+ DefaultResourceLoader,
3161
+ getAgentDir,
3162
+ SessionManager
3163
+ } from "@earendil-works/pi-coding-agent";
3164
+
3165
+ // src/lib/pi-delegate-tool.ts
3166
+ import { Type as Type2 } from "typebox";
3167
+ var MAX_DELEGATE_TURNS = 20;
3168
+ var DELEGATE_TOOL_NAME = "systematic_delegate";
3169
+ var DELEGATE_EXECUTION_MODE = "sequential";
3170
+ var MAX_DELEGATE_DESCRIPTION_CHARS = 6000;
3171
+ function buildDescription(catalog) {
3172
+ const intro = [
3173
+ `Delegate a task to one of Systematic's specialist personas.`,
3174
+ "",
3175
+ "Routing guidelines:",
3176
+ "- Use the narrowest persona that fits the task.",
3177
+ "- Send one concrete task plus constraints; don't ask the child to delegate again.",
3178
+ "- The child is in-process, sequential, capped at 20 turns, and inherits your model and working directory.",
3179
+ "",
3180
+ "## Available Personas",
3181
+ ""
3182
+ ].join(`
3183
+ `);
3184
+ const catalogText = renderDelegateCatalogCompact(catalog, MAX_DELEGATE_DESCRIPTION_CHARS - intro.length);
3185
+ return `${intro}${catalogText}`;
3186
+ }
3187
+ function buildAgentParameterHint(catalog) {
3188
+ const examples = catalog.slice(0, 3).map((e) => `'${e.name}'`).join(", ");
3189
+ const hint = examples.length > 0 ? ` (e.g., ${examples}, ...)` : "";
3190
+ return `Name of the Systematic persona to delegate to${hint}`;
3191
+ }
3192
+ function compactText(text, maxChars) {
3193
+ if (maxChars <= 0)
3194
+ return "";
3195
+ const normalized = text.replace(/\s+/g, " ").trim();
3196
+ if (normalized.length <= maxChars)
3197
+ return normalized;
3198
+ if (maxChars === 1)
3199
+ return normalized.slice(0, 1);
3200
+ return `${normalized.slice(0, maxChars - 1).trimEnd()}…`;
3201
+ }
3202
+ function buildPromptSnippet(body) {
3203
+ const firstParagraph = body.split(/\n\s*\n/u, 1)[0] ?? body;
3204
+ return compactText(firstParagraph, 96);
3205
+ }
3206
+ function renderDelegateCatalogCompact(catalog, budget) {
3207
+ if (catalog.length === 0) {
3208
+ return "No Systematic personas are currently available.";
3209
+ }
3210
+ const fixedOverhead = catalog.reduce((total, entry) => total + `- ${entry.name}: — promptSnippet: `.length, 0) + (catalog.length - 1);
3211
+ if (budget <= fixedOverhead) {
3212
+ return catalog.map((entry) => `- ${entry.name}:`).join(`
3213
+ `);
3214
+ }
3215
+ const perEntryBudget = Math.floor((budget - fixedOverhead) / catalog.length);
3216
+ const descriptionBudget = Math.max(1, Math.floor(perEntryBudget * 0.6));
3217
+ const promptSnippetBudget = Math.max(1, perEntryBudget - descriptionBudget);
3218
+ return catalog.map((entry) => {
3219
+ const description = compactText(entry.description, descriptionBudget);
3220
+ const promptSnippet = compactText(buildPromptSnippet(entry.body), promptSnippetBudget);
3221
+ return `- ${entry.name}: ${description} — promptSnippet: ${promptSnippet}`;
3222
+ }).join(`
3223
+ `);
3224
+ }
3225
+ function createPiDelegateTool(deps) {
3226
+ const { catalog } = deps;
3227
+ return {
3228
+ name: DELEGATE_TOOL_NAME,
3229
+ label: "Systematic Delegate",
3230
+ description: buildDescription(catalog),
3231
+ promptSnippet: "Use the narrowest persona that fits the task, and delegate one concrete job.",
3232
+ parameters: buildDelegateParametersSchema(catalog),
3233
+ executionMode: DELEGATE_EXECUTION_MODE,
3234
+ async execute(_toolCallId, params, signal, _onUpdate, ctx) {
3235
+ return runDelegateTool(deps, params, signal, ctx);
3236
+ }
3237
+ };
3238
+ }
3239
+ function buildDelegateParametersSchema(catalog) {
3240
+ return Type2.Object({
3241
+ agent: Type2.String({ description: buildAgentParameterHint(catalog) }),
3242
+ task: Type2.String({
3243
+ description: "The task to delegate to the persona."
3244
+ })
3245
+ });
3246
+ }
3247
+ function buildSuccessResult(agentName, turnCount, text) {
3248
+ return {
3249
+ content: [{ type: "text", text }],
3250
+ details: { persona: agentName, turnCount, outcome: "completed" }
3251
+ };
3252
+ }
3253
+ function buildAbortError(agentName, turnCount) {
3254
+ const suffix = turnCount > 0 ? ` after ${turnCount} turns` : " before the child session finished starting";
3255
+ return new Error(`Delegation to "${agentName}" was aborted${suffix}.`);
3256
+ }
3257
+ function buildTurnLimitError(agentName, turnCount) {
3258
+ return new Error(`Delegation to "${agentName}" stopped after the ${MAX_DELEGATE_TURNS}-turn limit (${turnCount} turns).`);
3259
+ }
3260
+ function buildFailureError(agentName, turnCount, message) {
3261
+ const suffix = turnCount > 0 ? ` after ${turnCount} turns` : "";
3262
+ return new Error(`Delegation to "${agentName}" failed${suffix}: ${message}`);
3263
+ }
3264
+ function normalizeError(error) {
3265
+ return error instanceof Error ? error : new Error(String(error));
3266
+ }
3267
+ function validateDelegateRequest(catalog, params, ctx) {
3268
+ const { agent: agentName, task } = params;
3269
+ const persona = resolveAgent(catalog, agentName);
3270
+ if (!persona) {
3271
+ throw new Error(`Unknown persona "${agentName}". Available personas: ${catalog.map((e) => e.name).join(", ")}`);
3272
+ }
3273
+ if (ctx.model === undefined) {
3274
+ throw new Error(`Delegation to "${agentName}" cannot start because no model is available to inherit from the parent session; refusing to select a default model (fail-closed).`);
3275
+ }
3276
+ let allowedToolNames;
3277
+ try {
3278
+ allowedToolNames = resolveToolAllowlist(persona.toolsSource).tools;
3279
+ } catch (error) {
3280
+ throw new Error(`Delegation to "${agentName}" cannot start because its tool allowlist is invalid: ${normalizeError(error).message}`);
3281
+ }
3282
+ if (allowedToolNames.includes(DELEGATE_TOOL_NAME)) {
3283
+ throw new Error(`Internal error: resolved tool allowlist for persona "${agentName}" included ${DELEGATE_TOOL_NAME}; refusing to spawn (fail-closed re-entry guard).`);
3284
+ }
3285
+ return {
3286
+ agentName,
3287
+ task,
3288
+ personaBody: persona.body,
3289
+ allowedToolNames,
3290
+ model: ctx.model
3291
+ };
3292
+ }
3293
+ function requestAbort(state, reason) {
3294
+ if (state.abortPromise)
3295
+ return;
3296
+ state.abortReason = reason;
3297
+ state.abortPromise = state.session?.abort().catch((error) => {
3298
+ state.abortError = error;
3299
+ });
3300
+ }
3301
+ function subscribeTurnCap(session, state) {
3302
+ return session.subscribe((event) => {
3303
+ if (event.type !== "turn_start")
3304
+ return;
3305
+ if (state.turnCount >= MAX_DELEGATE_TURNS) {
3306
+ requestAbort(state, "turn_limit");
3307
+ return;
3308
+ }
3309
+ state.turnCount += 1;
3310
+ });
3311
+ }
3312
+ async function runPromptRespectingAbort(session, task, signal, state) {
3313
+ const onExternalAbort = () => requestAbort(state, "external");
3314
+ signal?.addEventListener("abort", onExternalAbort);
3315
+ if (signal?.aborted) {
3316
+ requestAbort(state, "external");
3317
+ }
3318
+ try {
3319
+ if (!state.abortReason) {
3320
+ await session.prompt(task);
3321
+ }
3322
+ } catch (promptError) {
3323
+ if (!state.abortReason)
3324
+ throw promptError;
3325
+ } finally {
3326
+ signal?.removeEventListener("abort", onExternalAbort);
3327
+ }
3328
+ }
3329
+ function cleanUpLateSession(session) {
3330
+ session.abort().catch(() => {}).finally(() => {
3331
+ try {
3332
+ session.dispose();
3333
+ } catch {}
3334
+ });
3335
+ }
3336
+ async function runValidatedDelegateSession(createDelegateSession, request, signal, cwd) {
3337
+ const { agentName, task, personaBody, allowedToolNames, model } = request;
3338
+ if (signal?.aborted) {
3339
+ throw buildAbortError(agentName, 0);
3340
+ }
3341
+ const state = {
3342
+ session: undefined,
3343
+ turnCount: 0,
3344
+ abortReason: undefined,
3345
+ abortPromise: undefined,
3346
+ abortError: undefined
3347
+ };
3348
+ let unsubscribe;
3349
+ let removeExternalAbortListener;
3350
+ try {
3351
+ const sessionPromise = createDelegateSession({
3352
+ agentName,
3353
+ model,
3354
+ cwd,
3355
+ systemPromptOverride: personaBody,
3356
+ allowedToolNames
3357
+ });
3358
+ sessionPromise.then((session) => {
3359
+ if (signal?.aborted || state.abortReason !== undefined) {
3360
+ cleanUpLateSession(session);
3361
+ }
3362
+ }, () => {});
3363
+ const sessionOrAbort = signal ? await Promise.race([
3364
+ sessionPromise.then((session) => ({
3365
+ kind: "session",
3366
+ session
3367
+ })),
3368
+ new Promise((resolve) => {
3369
+ const onAbort = () => {
3370
+ signal.removeEventListener("abort", onAbort);
3371
+ requestAbort(state, "external");
3372
+ resolve("aborted");
3373
+ };
3374
+ signal.addEventListener("abort", onAbort);
3375
+ removeExternalAbortListener = () => {
3376
+ signal.removeEventListener("abort", onAbort);
3377
+ };
3378
+ })
3379
+ ]) : { kind: "session", session: await sessionPromise };
3380
+ if (sessionOrAbort === "aborted") {
3381
+ throw buildAbortError(agentName, state.turnCount);
3382
+ }
3383
+ const activeSession = sessionOrAbort.session;
3384
+ state.session = activeSession;
3385
+ unsubscribe = subscribeTurnCap(activeSession, state);
3386
+ await runPromptRespectingAbort(activeSession, task, signal, state);
3387
+ if (state.abortPromise)
3388
+ await state.abortPromise;
3389
+ if (state.abortError !== undefined) {
3390
+ throw buildFailureError(agentName, state.turnCount, normalizeError(state.abortError).message);
3391
+ }
3392
+ if (state.abortReason === "turn_limit") {
3393
+ throw buildTurnLimitError(agentName, state.turnCount);
3394
+ }
3395
+ if (state.abortReason === "external") {
3396
+ throw buildAbortError(agentName, state.turnCount);
3397
+ }
3398
+ const text = activeSession.getLastAssistantText() ?? "";
3399
+ return buildSuccessResult(agentName, state.turnCount, text);
3400
+ } catch (error) {
3401
+ const normalized = normalizeError(error);
3402
+ if (normalized.message.startsWith(`Delegation to "${agentName}" was aborted`) || normalized.message.startsWith(`Delegation to "${agentName}" stopped after`) || normalized.message.startsWith(`Delegation to "${agentName}" failed`)) {
3403
+ throw normalized;
3404
+ }
3405
+ throw buildFailureError(agentName, state.turnCount, normalized.message);
3406
+ } finally {
3407
+ removeExternalAbortListener?.();
3408
+ unsubscribe?.();
3409
+ state.session?.dispose();
3410
+ }
3411
+ }
3412
+ async function runDelegateTool(deps, params, signal, ctx) {
3413
+ const request = validateDelegateRequest(deps.catalog, params, ctx);
3414
+ return runValidatedDelegateSession(deps.createDelegateSession, request, signal, ctx.cwd);
3415
+ }
3416
+
3417
+ // src/lib/pi-delegate-session.ts
3418
+ var REAL_PI_DELEGATE_SESSION_RUNTIME = {
3419
+ getAgentDir,
3420
+ createResourceLoader: (options) => new DefaultResourceLoader(options),
3421
+ createInMemorySessionManager: (cwd) => SessionManager.inMemory(cwd),
3422
+ createAgentSession
3423
+ };
3424
+ function buildDelegateResourceLoaderOptions(options) {
3425
+ const { cwd, agentDir, systemPromptOverride } = options;
3426
+ return {
3427
+ cwd,
3428
+ agentDir,
3429
+ noExtensions: true,
3430
+ noSkills: true,
3431
+ noPromptTemplates: true,
3432
+ noThemes: true,
3433
+ noContextFiles: true,
3434
+ systemPromptOverride: () => systemPromptOverride,
3435
+ appendSystemPromptOverride: () => []
3436
+ };
3437
+ }
3438
+ function buildDelegateAgentSessionOptions(options) {
3439
+ const {
3440
+ cwd,
3441
+ agentDir,
3442
+ model,
3443
+ allowedToolNames,
3444
+ resourceLoader,
3445
+ sessionManager
3446
+ } = options;
3447
+ return {
3448
+ cwd,
3449
+ agentDir,
3450
+ model,
3451
+ tools: allowedToolNames,
3452
+ customTools: [],
3453
+ resourceLoader,
3454
+ sessionManager
3455
+ };
3456
+ }
3457
+ function createDelegateSessionWith(runtime) {
3458
+ return async (options) => {
3459
+ const { model, cwd, systemPromptOverride, allowedToolNames } = options;
3460
+ if (allowedToolNames.includes(DELEGATE_TOOL_NAME)) {
3461
+ throw new Error(`Refusing to construct delegate child session: allowedToolNames included ${DELEGATE_TOOL_NAME} (fail-closed re-entry guard).`);
3462
+ }
3463
+ const agentDir = runtime.getAgentDir();
3464
+ const resourceLoader = runtime.createResourceLoader(buildDelegateResourceLoaderOptions({
3465
+ cwd,
3466
+ agentDir,
3467
+ systemPromptOverride
3468
+ }));
3469
+ await resourceLoader.reload();
3470
+ const sessionManager = runtime.createInMemorySessionManager(cwd);
3471
+ const { session } = await runtime.createAgentSession(buildDelegateAgentSessionOptions({
3472
+ cwd,
3473
+ agentDir,
3474
+ model,
3475
+ allowedToolNames,
3476
+ resourceLoader,
3477
+ sessionManager
3478
+ }));
3479
+ return session;
3480
+ };
3481
+ }
3482
+ var createRealPiDelegateSession = createDelegateSessionWith(REAL_PI_DELEGATE_SESSION_RUNTIME);
3483
+
3484
+ // src/lib/skill-resolver.ts
3485
+ import fs6 from "node:fs";
3486
+ import path5 from "node:path";
3487
+ import { pathToFileURL as pathToFileURL2 } from "node:url";
3488
+ function getAllSkills(options) {
3489
+ const { bundledSkillsDir, disabledSkills } = options;
3490
+ return findSkillsInDir(bundledSkillsDir).filter((s) => !disabledSkills.includes(s.name)).map((skillInfo) => loadSkill(skillInfo)).filter((s) => s !== null).sort((a, b) => a.name.localeCompare(b.name));
3491
+ }
3492
+ function resolveSkill(options, requestedName) {
3493
+ const normalizedName = requestedName.startsWith("systematic:") ? requestedName.slice("systematic:".length) : requestedName;
3494
+ const skills = getAllSkills(options);
3495
+ const matchedSkill = skills.find((s) => s.name === normalizedName);
3496
+ if (!matchedSkill) {
3497
+ const availableSystematic = buildCatalogEntries(options).map((s) => s.prefixedName);
3498
+ throw new Error(`Skill "${requestedName}" not found. Available systematic skills: ${availableSystematic.join(", ")}`);
3499
+ }
3500
+ return matchedSkill;
3501
+ }
3502
+ function buildSkillToolDescription(options) {
3503
+ const catalog = renderCatalogCompact(options);
3504
+ return `Load a specialized skill that provides domain-specific instructions and workflows.
3505
+
3506
+ When you recognize that a task matches one of the available skills listed below, use this tool to load the full skill instructions.
3507
+
3508
+ The skill will inject detailed instructions, workflows, and access to bundled resources (scripts, references, templates) into the conversation context.
3509
+
3510
+ Tool output includes a \`<skill_content name="...">\` block with the loaded content.
3511
+
3512
+ ${catalog}`;
3513
+ }
3514
+ function buildSkillToolParameterHint(options) {
3515
+ const entries = buildCatalogEntries(options);
3516
+ const examples = entries.slice(0, 3).map((s) => `'${s.prefixedName}'`).join(", ");
3517
+ const hint = examples.length > 0 ? ` (e.g., ${examples}, ...)` : "";
3518
+ return `The name of the skill from available_skills${hint}`;
3519
+ }
3520
+ function buildSkillContentOutput(matchedSkill) {
3521
+ const body = extractSkillBody(matchedSkill.wrappedTemplate);
3522
+ const dir = path5.dirname(matchedSkill.skillFile);
3523
+ const base = pathToFileURL2(dir).href;
3524
+ const files = discoverSkillFiles(dir);
3525
+ const lines = [
3526
+ `<skill_content name="${matchedSkill.prefixedName}">`,
3527
+ `# Skill: ${matchedSkill.prefixedName}`,
3528
+ "",
3529
+ body.trim(),
3530
+ "",
3531
+ `Base directory for this skill: ${base}`,
3532
+ "Relative paths in this skill (e.g., scripts/, reference/) are relative to this base directory.",
3533
+ "Note: file list is sampled."
3534
+ ];
3535
+ if (files) {
3536
+ lines.push("", "<skill_files>", files, "</skill_files>");
3537
+ }
3538
+ lines.push("</skill_content>");
3539
+ return { output: lines.join(`
3540
+ `), dir };
3541
+ }
3542
+ function discoverSkillFiles(dir, limit = 10) {
3543
+ const files = [];
3544
+ function shouldSkipDirectory(name) {
3545
+ return name === ".git";
3546
+ }
3547
+ function shouldIncludeFile(name) {
3548
+ return name !== "SKILL.md";
3549
+ }
3550
+ function handleEntry(entry, currentDir) {
3551
+ if (entry.isDirectory()) {
3552
+ if (!shouldSkipDirectory(entry.name)) {
3553
+ recurse(path5.resolve(currentDir, entry.name));
3554
+ }
3555
+ } else if (shouldIncludeFile(entry.name)) {
3556
+ files.push(path5.resolve(currentDir, entry.name));
3557
+ }
3558
+ }
3559
+ function recurse(currentDir) {
3560
+ if (files.length >= limit)
3561
+ return;
3562
+ try {
3563
+ const entries = fs6.readdirSync(currentDir, { withFileTypes: true });
3564
+ for (const entry of entries) {
3565
+ if (files.length >= limit)
3566
+ break;
3567
+ handleEntry(entry, currentDir);
3568
+ }
3569
+ } catch {}
3570
+ }
3571
+ recurse(dir);
3572
+ return files.map((file) => ` <file>${file}</file>`).join(`
3573
+ `);
3574
+ }
3575
+
3576
+ // src/pi.ts
3577
+ var __dirname2 = path6.dirname(fileURLToPath(import.meta.url));
3578
+ var packageRoot = path6.resolve(__dirname2, "..");
3579
+ var bundledSkillsDir = path6.join(packageRoot, "skills");
3580
+ var bundledAgentsDir = path6.join(packageRoot, "agents");
3581
+ var PI_BOOTSTRAP_USAGE_TEMPLATE = `**Skills usage:**
3582
+ - Use \`systematic_skill\` for Systematic skills.
3583
+ - For non-Systematic skills, follow Pi's native skill instructions and read the listed SKILL.md path.`;
3584
+ var reportPiBootstrapFailure = () => {
3585
+ process.stderr.write(`[systematic] Failed to compute Pi bootstrap; continuing without injection.
3586
+ `);
3587
+ };
3588
+ var reportPiDelegateCatalogFailure = (error) => {
3589
+ const message = error instanceof Error ? error.message : String(error);
3590
+ process.stderr.write(`[systematic] Failed to build Pi agent catalog; systematic_delegate will not be registered: ${message}
3591
+ `);
3592
+ };
3593
+ var defaultPiExtensionDependencies = {
3594
+ buildAgentCatalog
3595
+ };
3596
+ async function systematicPiExtension(pi, deps = defaultPiExtensionDependencies) {
3597
+ const { buildAgentCatalog: buildAgentCatalogFn = buildAgentCatalog } = deps;
3598
+ const disabledSkills = [];
3599
+ const resolverOptions = { bundledSkillsDir, disabledSkills };
3600
+ const bootstrapContent = computeBootstrapContentSafe({
3601
+ bundledSkillsDir,
3602
+ usageTemplate: PI_BOOTSTRAP_USAGE_TEMPLATE
3603
+ }, reportPiBootstrapFailure);
3604
+ pi.on("before_agent_start", (event) => {
3605
+ const systemPrompt = composeSystemPromptWithBootstrap(event.systemPrompt, bootstrapContent);
3606
+ if (systemPrompt === null)
3607
+ return;
3608
+ return { systemPrompt };
3609
+ });
3610
+ pi.registerTool({
3611
+ name: "systematic_skill",
3612
+ label: "Systematic Skill",
3613
+ description: buildSkillToolDescription(resolverOptions),
3614
+ promptSnippet: "Use `systematic_skill` to load Systematic skills.",
3615
+ parameters: Type3.Object({
3616
+ name: Type3.String({
3617
+ description: buildSkillToolParameterHint(resolverOptions)
3618
+ })
3619
+ }),
3620
+ async execute(_toolCallId, params) {
3621
+ const matchedSkill = resolveSkill(resolverOptions, params.name);
3622
+ const { output, dir } = buildSkillContentOutput(matchedSkill);
3623
+ return {
3624
+ content: [{ type: "text", text: output }],
3625
+ details: { skillDir: dir }
3626
+ };
3627
+ }
3628
+ });
3629
+ try {
3630
+ const catalog = buildAgentCatalogFn(bundledAgentsDir);
3631
+ pi.registerTool(createPiDelegateTool({
3632
+ catalog,
3633
+ createDelegateSession: createRealPiDelegateSession
3634
+ }));
3635
+ } catch (error) {
3636
+ reportPiDelegateCatalogFailure(error);
3637
+ }
3638
+ }
3639
+ export {
3640
+ systematicPiExtension as default
3641
+ };