@smart-coders-hq/opencode-model-fallback 1.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +190 -0
- package/README.md +237 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +4198 -0
- package/dist/src/config/agent-loader.d.ts +5 -0
- package/dist/src/config/agent-loader.d.ts.map +1 -0
- package/dist/src/config/defaults.d.ts +5 -0
- package/dist/src/config/defaults.d.ts.map +1 -0
- package/dist/src/config/loader.d.ts +9 -0
- package/dist/src/config/loader.d.ts.map +1 -0
- package/dist/src/config/migrate.d.ts +16 -0
- package/dist/src/config/migrate.d.ts.map +1 -0
- package/dist/src/config/schema.d.ts +30 -0
- package/dist/src/config/schema.d.ts.map +1 -0
- package/dist/src/detection/classifier.d.ts +3 -0
- package/dist/src/detection/classifier.d.ts.map +1 -0
- package/dist/src/detection/patterns.d.ts +5 -0
- package/dist/src/detection/patterns.d.ts.map +1 -0
- package/dist/src/display/notifier.d.ts +8 -0
- package/dist/src/display/notifier.d.ts.map +1 -0
- package/dist/src/display/usage.d.ts +24 -0
- package/dist/src/display/usage.d.ts.map +1 -0
- package/dist/src/logging/logger.d.ts +24 -0
- package/dist/src/logging/logger.d.ts.map +1 -0
- package/dist/src/plugin.d.ts +9 -0
- package/dist/src/plugin.d.ts.map +1 -0
- package/dist/src/preemptive.d.ts +16 -0
- package/dist/src/preemptive.d.ts.map +1 -0
- package/dist/src/replay/message-converter.d.ts +22 -0
- package/dist/src/replay/message-converter.d.ts.map +1 -0
- package/dist/src/replay/orchestrator.d.ts +13 -0
- package/dist/src/replay/orchestrator.d.ts.map +1 -0
- package/dist/src/resolution/agent-resolver.d.ts +11 -0
- package/dist/src/resolution/agent-resolver.d.ts.map +1 -0
- package/dist/src/resolution/fallback-resolver.d.ts +13 -0
- package/dist/src/resolution/fallback-resolver.d.ts.map +1 -0
- package/dist/src/state/model-health.d.ts +18 -0
- package/dist/src/state/model-health.d.ts.map +1 -0
- package/dist/src/state/session-state.d.ts +18 -0
- package/dist/src/state/session-state.d.ts.map +1 -0
- package/dist/src/state/store.d.ts +14 -0
- package/dist/src/state/store.d.ts.map +1 -0
- package/dist/src/tools/fallback-status.d.ts +8 -0
- package/dist/src/tools/fallback-status.d.ts.map +1 -0
- package/dist/src/types.d.ts +51 -0
- package/dist/src/types.d.ts.map +1 -0
- package/examples/model-fallback.json +34 -0
- package/package.json +73 -0
- package/plugin.json +14 -0
package/dist/index.js
ADDED
|
@@ -0,0 +1,4198 @@
|
|
|
1
|
+
// src/plugin.ts
|
|
2
|
+
import { existsSync as existsSync3, mkdirSync as mkdirSync2, writeFileSync } from "fs";
|
|
3
|
+
import { dirname as dirname2, join as join4 } from "path";
|
|
4
|
+
import { homedir as homedir5 } from "os";
|
|
5
|
+
|
|
6
|
+
// src/config/loader.ts
|
|
7
|
+
import { readFileSync as readFileSync2, existsSync as existsSync2 } from "fs";
|
|
8
|
+
import { basename as basename2, join as join3 } from "path";
|
|
9
|
+
import { homedir as homedir4 } from "os";
|
|
10
|
+
|
|
11
|
+
// src/config/schema.ts
|
|
12
|
+
import { z } from "zod";
|
|
13
|
+
import { homedir as homedir2 } from "os";
|
|
14
|
+
import { isAbsolute, relative, resolve } from "path";
|
|
15
|
+
|
|
16
|
+
// src/config/defaults.ts
|
|
17
|
+
import { homedir } from "os";
|
|
18
|
+
import { join } from "path";
|
|
19
|
+
var DEFAULT_PATTERNS = [
|
|
20
|
+
"rate limit",
|
|
21
|
+
"usage limit",
|
|
22
|
+
"too many requests",
|
|
23
|
+
"quota exceeded",
|
|
24
|
+
"overloaded",
|
|
25
|
+
"capacity exceeded",
|
|
26
|
+
"credits exhausted",
|
|
27
|
+
"billing limit",
|
|
28
|
+
"429"
|
|
29
|
+
];
|
|
30
|
+
var DEFAULT_LOG_PATH = join(homedir(), ".local/share/opencode/logs/model-fallback.log");
|
|
31
|
+
var DEFAULT_CONFIG = {
|
|
32
|
+
enabled: true,
|
|
33
|
+
defaults: {
|
|
34
|
+
fallbackOn: ["rate_limit", "quota_exceeded", "5xx", "timeout", "overloaded"],
|
|
35
|
+
cooldownMs: 300000,
|
|
36
|
+
retryOriginalAfterMs: 900000,
|
|
37
|
+
maxFallbackDepth: 3
|
|
38
|
+
},
|
|
39
|
+
agents: {
|
|
40
|
+
"*": {
|
|
41
|
+
fallbackModels: []
|
|
42
|
+
}
|
|
43
|
+
},
|
|
44
|
+
patterns: DEFAULT_PATTERNS,
|
|
45
|
+
logging: true,
|
|
46
|
+
logPath: DEFAULT_LOG_PATH,
|
|
47
|
+
agentDirs: []
|
|
48
|
+
};
|
|
49
|
+
|
|
50
|
+
// src/config/schema.ts
|
|
51
|
+
var MODEL_KEY_RE = /^[a-zA-Z0-9_-]{1,100}\/[a-zA-Z0-9._-]{1,100}$/;
|
|
52
|
+
var home = resolve(homedir2());
|
|
53
|
+
function formatPath(path) {
|
|
54
|
+
return path.map((segment) => String(segment)).join(".");
|
|
55
|
+
}
|
|
56
|
+
function normalizeLogPath(path) {
|
|
57
|
+
if (path.startsWith("~/")) {
|
|
58
|
+
return resolve(home, path.slice(2));
|
|
59
|
+
}
|
|
60
|
+
return resolve(path);
|
|
61
|
+
}
|
|
62
|
+
function isPathWithinHome(path) {
|
|
63
|
+
const rel = relative(home, path);
|
|
64
|
+
return rel === "" || !rel.startsWith("..") && !isAbsolute(rel);
|
|
65
|
+
}
|
|
66
|
+
var modelKey = z.string().regex(MODEL_KEY_RE, "Model key must be 'providerID/modelID'");
|
|
67
|
+
var agentConfig = z.object({
|
|
68
|
+
fallbackModels: z.array(modelKey).min(1)
|
|
69
|
+
});
|
|
70
|
+
var fallbackDefaults = z.object({
|
|
71
|
+
fallbackOn: z.array(z.enum(["rate_limit", "quota_exceeded", "5xx", "timeout", "overloaded"])).optional(),
|
|
72
|
+
cooldownMs: z.number().min(1e4).optional(),
|
|
73
|
+
retryOriginalAfterMs: z.number().min(1e4).optional(),
|
|
74
|
+
maxFallbackDepth: z.number().int().min(1).max(10).optional()
|
|
75
|
+
});
|
|
76
|
+
var logPathSchema = z.string().refine((p) => isPathWithinHome(normalizeLogPath(p)), "logPath must resolve within $HOME");
|
|
77
|
+
var pluginConfigSchema = z.object({
|
|
78
|
+
enabled: z.boolean().optional(),
|
|
79
|
+
defaults: fallbackDefaults.optional(),
|
|
80
|
+
agents: z.record(z.string(), agentConfig).optional(),
|
|
81
|
+
patterns: z.array(z.string()).optional(),
|
|
82
|
+
logging: z.boolean().optional(),
|
|
83
|
+
logPath: logPathSchema.optional(),
|
|
84
|
+
agentDirs: z.array(z.string()).optional()
|
|
85
|
+
}).strict();
|
|
86
|
+
function parseConfig(raw) {
|
|
87
|
+
const warnings = [];
|
|
88
|
+
if (!raw || typeof raw !== "object" || Array.isArray(raw)) {
|
|
89
|
+
warnings.push("Config warning at root: expected object — using default");
|
|
90
|
+
return { config: {}, warnings };
|
|
91
|
+
}
|
|
92
|
+
const obj = raw;
|
|
93
|
+
const allowed = new Set([
|
|
94
|
+
"enabled",
|
|
95
|
+
"defaults",
|
|
96
|
+
"agents",
|
|
97
|
+
"patterns",
|
|
98
|
+
"logging",
|
|
99
|
+
"logPath",
|
|
100
|
+
"agentDirs"
|
|
101
|
+
]);
|
|
102
|
+
for (const key of Object.keys(obj)) {
|
|
103
|
+
if (!allowed.has(key)) {
|
|
104
|
+
warnings.push(`Config warning at ${key}: unknown field — using default`);
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
const config = {};
|
|
108
|
+
const enabledResult = z.boolean().safeParse(obj.enabled);
|
|
109
|
+
if (obj.enabled !== undefined) {
|
|
110
|
+
if (enabledResult.success) {
|
|
111
|
+
config.enabled = enabledResult.data;
|
|
112
|
+
} else {
|
|
113
|
+
warnings.push(`Config warning at enabled: ${enabledResult.error.issues[0].message} — using default`);
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
if (obj.defaults !== undefined) {
|
|
117
|
+
if (!obj.defaults || typeof obj.defaults !== "object" || Array.isArray(obj.defaults)) {
|
|
118
|
+
warnings.push("Config warning at defaults: expected object — using default");
|
|
119
|
+
} else {
|
|
120
|
+
const defaultsObj = obj.defaults;
|
|
121
|
+
const parsedDefaults = {};
|
|
122
|
+
const fallbackOnResult = fallbackDefaults.shape.fallbackOn.safeParse(defaultsObj.fallbackOn);
|
|
123
|
+
if (defaultsObj.fallbackOn !== undefined) {
|
|
124
|
+
if (fallbackOnResult.success && fallbackOnResult.data !== undefined) {
|
|
125
|
+
parsedDefaults.fallbackOn = fallbackOnResult.data;
|
|
126
|
+
} else if (!fallbackOnResult.success) {
|
|
127
|
+
for (const issue of fallbackOnResult.error.issues) {
|
|
128
|
+
const suffix = issue.path.length > 0 ? `.${formatPath(issue.path)}` : "";
|
|
129
|
+
warnings.push(`Config warning at defaults.fallbackOn${suffix}: ${issue.message} — using default`);
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
const cooldownResult = fallbackDefaults.shape.cooldownMs.safeParse(defaultsObj.cooldownMs);
|
|
134
|
+
if (defaultsObj.cooldownMs !== undefined) {
|
|
135
|
+
if (cooldownResult.success && cooldownResult.data !== undefined) {
|
|
136
|
+
parsedDefaults.cooldownMs = cooldownResult.data;
|
|
137
|
+
} else if (!cooldownResult.success) {
|
|
138
|
+
for (const issue of cooldownResult.error.issues) {
|
|
139
|
+
const suffix = issue.path.length > 0 ? `.${formatPath(issue.path)}` : "";
|
|
140
|
+
warnings.push(`Config warning at defaults.cooldownMs${suffix}: ${issue.message} — using default`);
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
const retryResult = fallbackDefaults.shape.retryOriginalAfterMs.safeParse(defaultsObj.retryOriginalAfterMs);
|
|
145
|
+
if (defaultsObj.retryOriginalAfterMs !== undefined) {
|
|
146
|
+
if (retryResult.success && retryResult.data !== undefined) {
|
|
147
|
+
parsedDefaults.retryOriginalAfterMs = retryResult.data;
|
|
148
|
+
} else if (!retryResult.success) {
|
|
149
|
+
for (const issue of retryResult.error.issues) {
|
|
150
|
+
const suffix = issue.path.length > 0 ? `.${formatPath(issue.path)}` : "";
|
|
151
|
+
warnings.push(`Config warning at defaults.retryOriginalAfterMs${suffix}: ${issue.message} — using default`);
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
const depthResult = fallbackDefaults.shape.maxFallbackDepth.safeParse(defaultsObj.maxFallbackDepth);
|
|
156
|
+
if (defaultsObj.maxFallbackDepth !== undefined) {
|
|
157
|
+
if (depthResult.success && depthResult.data !== undefined) {
|
|
158
|
+
parsedDefaults.maxFallbackDepth = depthResult.data;
|
|
159
|
+
} else if (!depthResult.success) {
|
|
160
|
+
for (const issue of depthResult.error.issues) {
|
|
161
|
+
const suffix = issue.path.length > 0 ? `.${formatPath(issue.path)}` : "";
|
|
162
|
+
warnings.push(`Config warning at defaults.maxFallbackDepth${suffix}: ${issue.message} — using default`);
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
for (const key of Object.keys(defaultsObj)) {
|
|
167
|
+
if (!Object.hasOwn(fallbackDefaults.shape, key)) {
|
|
168
|
+
warnings.push(`Config warning at defaults.${key}: unknown field — using default`);
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
if (Object.keys(parsedDefaults).length > 0) {
|
|
172
|
+
config.defaults = parsedDefaults;
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
if (obj.agents !== undefined) {
|
|
177
|
+
if (!obj.agents || typeof obj.agents !== "object" || Array.isArray(obj.agents)) {
|
|
178
|
+
warnings.push("Config warning at agents: expected object — using default");
|
|
179
|
+
} else {
|
|
180
|
+
const parsedAgents = {};
|
|
181
|
+
for (const [agentName, agentValue] of Object.entries(obj.agents)) {
|
|
182
|
+
const agentResult = agentConfig.safeParse(agentValue);
|
|
183
|
+
if (agentResult.success) {
|
|
184
|
+
parsedAgents[agentName] = agentResult.data;
|
|
185
|
+
continue;
|
|
186
|
+
}
|
|
187
|
+
for (const issue of agentResult.error.issues) {
|
|
188
|
+
const suffix = issue.path.length > 0 ? `.${formatPath(issue.path)}` : "";
|
|
189
|
+
warnings.push(`Config warning at agents.${agentName}${suffix}: ${issue.message} — using default`);
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
config.agents = parsedAgents;
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
if (obj.patterns !== undefined) {
|
|
196
|
+
const patternsResult = z.array(z.string()).safeParse(obj.patterns);
|
|
197
|
+
if (patternsResult.success) {
|
|
198
|
+
config.patterns = patternsResult.data;
|
|
199
|
+
} else {
|
|
200
|
+
for (const issue of patternsResult.error.issues) {
|
|
201
|
+
const suffix = issue.path.length > 0 ? `.${formatPath(issue.path)}` : "";
|
|
202
|
+
warnings.push(`Config warning at patterns${suffix}: ${issue.message} — using default`);
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
if (obj.logging !== undefined) {
|
|
207
|
+
const loggingResult = z.boolean().safeParse(obj.logging);
|
|
208
|
+
if (loggingResult.success) {
|
|
209
|
+
config.logging = loggingResult.data;
|
|
210
|
+
} else {
|
|
211
|
+
warnings.push(`Config warning at logging: ${loggingResult.error.issues[0].message} — using default`);
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
if (obj.logPath !== undefined) {
|
|
215
|
+
const logPathResult = logPathSchema.safeParse(obj.logPath);
|
|
216
|
+
if (logPathResult.success) {
|
|
217
|
+
config.logPath = obj.logPath;
|
|
218
|
+
} else {
|
|
219
|
+
for (const issue of logPathResult.error.issues) {
|
|
220
|
+
const suffix = issue.path.length > 0 ? `.${formatPath(issue.path)}` : "";
|
|
221
|
+
warnings.push(`Config warning at logPath${suffix}: ${issue.message} — using default`);
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
if (obj.agentDirs !== undefined) {
|
|
226
|
+
const agentDirsResult = z.array(z.string()).safeParse(obj.agentDirs);
|
|
227
|
+
if (agentDirsResult.success) {
|
|
228
|
+
config.agentDirs = agentDirsResult.data;
|
|
229
|
+
} else {
|
|
230
|
+
for (const issue of agentDirsResult.error.issues) {
|
|
231
|
+
const suffix = issue.path.length > 0 ? `.${formatPath(issue.path)}` : "";
|
|
232
|
+
warnings.push(`Config warning at agentDirs${suffix}: ${issue.message} — using default`);
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
return { config, warnings };
|
|
237
|
+
}
|
|
238
|
+
function mergeWithDefaults(raw) {
|
|
239
|
+
const def = DEFAULT_CONFIG;
|
|
240
|
+
const logPath = raw.logPath ? normalizeLogPath(raw.logPath) : def.logPath;
|
|
241
|
+
return {
|
|
242
|
+
enabled: raw.enabled ?? def.enabled,
|
|
243
|
+
defaults: {
|
|
244
|
+
fallbackOn: raw.defaults?.fallbackOn ?? def.defaults.fallbackOn,
|
|
245
|
+
cooldownMs: raw.defaults?.cooldownMs ?? def.defaults.cooldownMs,
|
|
246
|
+
retryOriginalAfterMs: raw.defaults?.retryOriginalAfterMs ?? def.defaults.retryOriginalAfterMs,
|
|
247
|
+
maxFallbackDepth: raw.defaults?.maxFallbackDepth ?? def.defaults.maxFallbackDepth
|
|
248
|
+
},
|
|
249
|
+
agents: raw.agents ?? def.agents,
|
|
250
|
+
patterns: raw.patterns ?? def.patterns,
|
|
251
|
+
logging: raw.logging ?? def.logging,
|
|
252
|
+
logPath,
|
|
253
|
+
agentDirs: raw.agentDirs ?? def.agentDirs
|
|
254
|
+
};
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
// src/config/migrate.ts
|
|
258
|
+
function isOldFormat(raw) {
|
|
259
|
+
if (typeof raw !== "object" || raw === null)
|
|
260
|
+
return false;
|
|
261
|
+
return "fallbackModel" in raw && typeof raw.fallbackModel === "string";
|
|
262
|
+
}
|
|
263
|
+
function migrateOldConfig(old) {
|
|
264
|
+
const migrated = {};
|
|
265
|
+
if (typeof old.enabled === "boolean")
|
|
266
|
+
migrated.enabled = old.enabled;
|
|
267
|
+
if (typeof old.logging === "boolean")
|
|
268
|
+
migrated.logging = old.logging;
|
|
269
|
+
if (Array.isArray(old.patterns))
|
|
270
|
+
migrated.patterns = old.patterns;
|
|
271
|
+
if (old.fallbackModel) {
|
|
272
|
+
migrated.agents = {
|
|
273
|
+
"*": { fallbackModels: [old.fallbackModel] }
|
|
274
|
+
};
|
|
275
|
+
}
|
|
276
|
+
if (typeof old.cooldownMs === "number") {
|
|
277
|
+
migrated.defaults = { cooldownMs: old.cooldownMs };
|
|
278
|
+
}
|
|
279
|
+
return migrated;
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
// src/config/agent-loader.ts
|
|
283
|
+
import { existsSync, readFileSync, readdirSync, realpathSync, statSync } from "fs";
|
|
284
|
+
import { homedir as homedir3 } from "os";
|
|
285
|
+
import { basename, extname, isAbsolute as isAbsolute2, join as join2, relative as relative2, resolve as resolve2 } from "path";
|
|
286
|
+
|
|
287
|
+
// node_modules/js-yaml/dist/js-yaml.mjs
|
|
288
|
+
/*! js-yaml 4.1.1 https://github.com/nodeca/js-yaml @license MIT */
|
|
289
|
+
function isNothing(subject) {
|
|
290
|
+
return typeof subject === "undefined" || subject === null;
|
|
291
|
+
}
|
|
292
|
+
function isObject(subject) {
|
|
293
|
+
return typeof subject === "object" && subject !== null;
|
|
294
|
+
}
|
|
295
|
+
function toArray(sequence) {
|
|
296
|
+
if (Array.isArray(sequence))
|
|
297
|
+
return sequence;
|
|
298
|
+
else if (isNothing(sequence))
|
|
299
|
+
return [];
|
|
300
|
+
return [sequence];
|
|
301
|
+
}
|
|
302
|
+
function extend(target, source) {
|
|
303
|
+
var index, length, key, sourceKeys;
|
|
304
|
+
if (source) {
|
|
305
|
+
sourceKeys = Object.keys(source);
|
|
306
|
+
for (index = 0, length = sourceKeys.length;index < length; index += 1) {
|
|
307
|
+
key = sourceKeys[index];
|
|
308
|
+
target[key] = source[key];
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
return target;
|
|
312
|
+
}
|
|
313
|
+
function repeat(string, count) {
|
|
314
|
+
var result = "", cycle;
|
|
315
|
+
for (cycle = 0;cycle < count; cycle += 1) {
|
|
316
|
+
result += string;
|
|
317
|
+
}
|
|
318
|
+
return result;
|
|
319
|
+
}
|
|
320
|
+
function isNegativeZero(number) {
|
|
321
|
+
return number === 0 && Number.NEGATIVE_INFINITY === 1 / number;
|
|
322
|
+
}
|
|
323
|
+
var isNothing_1 = isNothing;
|
|
324
|
+
var isObject_1 = isObject;
|
|
325
|
+
var toArray_1 = toArray;
|
|
326
|
+
var repeat_1 = repeat;
|
|
327
|
+
var isNegativeZero_1 = isNegativeZero;
|
|
328
|
+
var extend_1 = extend;
|
|
329
|
+
var common = {
|
|
330
|
+
isNothing: isNothing_1,
|
|
331
|
+
isObject: isObject_1,
|
|
332
|
+
toArray: toArray_1,
|
|
333
|
+
repeat: repeat_1,
|
|
334
|
+
isNegativeZero: isNegativeZero_1,
|
|
335
|
+
extend: extend_1
|
|
336
|
+
};
|
|
337
|
+
function formatError(exception, compact) {
|
|
338
|
+
var where = "", message = exception.reason || "(unknown reason)";
|
|
339
|
+
if (!exception.mark)
|
|
340
|
+
return message;
|
|
341
|
+
if (exception.mark.name) {
|
|
342
|
+
where += 'in "' + exception.mark.name + '" ';
|
|
343
|
+
}
|
|
344
|
+
where += "(" + (exception.mark.line + 1) + ":" + (exception.mark.column + 1) + ")";
|
|
345
|
+
if (!compact && exception.mark.snippet) {
|
|
346
|
+
where += `
|
|
347
|
+
|
|
348
|
+
` + exception.mark.snippet;
|
|
349
|
+
}
|
|
350
|
+
return message + " " + where;
|
|
351
|
+
}
|
|
352
|
+
function YAMLException$1(reason, mark) {
|
|
353
|
+
Error.call(this);
|
|
354
|
+
this.name = "YAMLException";
|
|
355
|
+
this.reason = reason;
|
|
356
|
+
this.mark = mark;
|
|
357
|
+
this.message = formatError(this, false);
|
|
358
|
+
if (Error.captureStackTrace) {
|
|
359
|
+
Error.captureStackTrace(this, this.constructor);
|
|
360
|
+
} else {
|
|
361
|
+
this.stack = new Error().stack || "";
|
|
362
|
+
}
|
|
363
|
+
}
|
|
364
|
+
YAMLException$1.prototype = Object.create(Error.prototype);
|
|
365
|
+
YAMLException$1.prototype.constructor = YAMLException$1;
|
|
366
|
+
YAMLException$1.prototype.toString = function toString(compact) {
|
|
367
|
+
return this.name + ": " + formatError(this, compact);
|
|
368
|
+
};
|
|
369
|
+
var exception = YAMLException$1;
|
|
370
|
+
function getLine(buffer, lineStart, lineEnd, position, maxLineLength) {
|
|
371
|
+
var head = "";
|
|
372
|
+
var tail = "";
|
|
373
|
+
var maxHalfLength = Math.floor(maxLineLength / 2) - 1;
|
|
374
|
+
if (position - lineStart > maxHalfLength) {
|
|
375
|
+
head = " ... ";
|
|
376
|
+
lineStart = position - maxHalfLength + head.length;
|
|
377
|
+
}
|
|
378
|
+
if (lineEnd - position > maxHalfLength) {
|
|
379
|
+
tail = " ...";
|
|
380
|
+
lineEnd = position + maxHalfLength - tail.length;
|
|
381
|
+
}
|
|
382
|
+
return {
|
|
383
|
+
str: head + buffer.slice(lineStart, lineEnd).replace(/\t/g, "→") + tail,
|
|
384
|
+
pos: position - lineStart + head.length
|
|
385
|
+
};
|
|
386
|
+
}
|
|
387
|
+
function padStart(string, max) {
|
|
388
|
+
return common.repeat(" ", max - string.length) + string;
|
|
389
|
+
}
|
|
390
|
+
function makeSnippet(mark, options) {
|
|
391
|
+
options = Object.create(options || null);
|
|
392
|
+
if (!mark.buffer)
|
|
393
|
+
return null;
|
|
394
|
+
if (!options.maxLength)
|
|
395
|
+
options.maxLength = 79;
|
|
396
|
+
if (typeof options.indent !== "number")
|
|
397
|
+
options.indent = 1;
|
|
398
|
+
if (typeof options.linesBefore !== "number")
|
|
399
|
+
options.linesBefore = 3;
|
|
400
|
+
if (typeof options.linesAfter !== "number")
|
|
401
|
+
options.linesAfter = 2;
|
|
402
|
+
var re = /\r?\n|\r|\0/g;
|
|
403
|
+
var lineStarts = [0];
|
|
404
|
+
var lineEnds = [];
|
|
405
|
+
var match;
|
|
406
|
+
var foundLineNo = -1;
|
|
407
|
+
while (match = re.exec(mark.buffer)) {
|
|
408
|
+
lineEnds.push(match.index);
|
|
409
|
+
lineStarts.push(match.index + match[0].length);
|
|
410
|
+
if (mark.position <= match.index && foundLineNo < 0) {
|
|
411
|
+
foundLineNo = lineStarts.length - 2;
|
|
412
|
+
}
|
|
413
|
+
}
|
|
414
|
+
if (foundLineNo < 0)
|
|
415
|
+
foundLineNo = lineStarts.length - 1;
|
|
416
|
+
var result = "", i, line;
|
|
417
|
+
var lineNoLength = Math.min(mark.line + options.linesAfter, lineEnds.length).toString().length;
|
|
418
|
+
var maxLineLength = options.maxLength - (options.indent + lineNoLength + 3);
|
|
419
|
+
for (i = 1;i <= options.linesBefore; i++) {
|
|
420
|
+
if (foundLineNo - i < 0)
|
|
421
|
+
break;
|
|
422
|
+
line = getLine(mark.buffer, lineStarts[foundLineNo - i], lineEnds[foundLineNo - i], mark.position - (lineStarts[foundLineNo] - lineStarts[foundLineNo - i]), maxLineLength);
|
|
423
|
+
result = common.repeat(" ", options.indent) + padStart((mark.line - i + 1).toString(), lineNoLength) + " | " + line.str + `
|
|
424
|
+
` + result;
|
|
425
|
+
}
|
|
426
|
+
line = getLine(mark.buffer, lineStarts[foundLineNo], lineEnds[foundLineNo], mark.position, maxLineLength);
|
|
427
|
+
result += common.repeat(" ", options.indent) + padStart((mark.line + 1).toString(), lineNoLength) + " | " + line.str + `
|
|
428
|
+
`;
|
|
429
|
+
result += common.repeat("-", options.indent + lineNoLength + 3 + line.pos) + "^" + `
|
|
430
|
+
`;
|
|
431
|
+
for (i = 1;i <= options.linesAfter; i++) {
|
|
432
|
+
if (foundLineNo + i >= lineEnds.length)
|
|
433
|
+
break;
|
|
434
|
+
line = getLine(mark.buffer, lineStarts[foundLineNo + i], lineEnds[foundLineNo + i], mark.position - (lineStarts[foundLineNo] - lineStarts[foundLineNo + i]), maxLineLength);
|
|
435
|
+
result += common.repeat(" ", options.indent) + padStart((mark.line + i + 1).toString(), lineNoLength) + " | " + line.str + `
|
|
436
|
+
`;
|
|
437
|
+
}
|
|
438
|
+
return result.replace(/\n$/, "");
|
|
439
|
+
}
|
|
440
|
+
var snippet = makeSnippet;
|
|
441
|
+
var TYPE_CONSTRUCTOR_OPTIONS = [
|
|
442
|
+
"kind",
|
|
443
|
+
"multi",
|
|
444
|
+
"resolve",
|
|
445
|
+
"construct",
|
|
446
|
+
"instanceOf",
|
|
447
|
+
"predicate",
|
|
448
|
+
"represent",
|
|
449
|
+
"representName",
|
|
450
|
+
"defaultStyle",
|
|
451
|
+
"styleAliases"
|
|
452
|
+
];
|
|
453
|
+
var YAML_NODE_KINDS = [
|
|
454
|
+
"scalar",
|
|
455
|
+
"sequence",
|
|
456
|
+
"mapping"
|
|
457
|
+
];
|
|
458
|
+
function compileStyleAliases(map) {
|
|
459
|
+
var result = {};
|
|
460
|
+
if (map !== null) {
|
|
461
|
+
Object.keys(map).forEach(function(style) {
|
|
462
|
+
map[style].forEach(function(alias) {
|
|
463
|
+
result[String(alias)] = style;
|
|
464
|
+
});
|
|
465
|
+
});
|
|
466
|
+
}
|
|
467
|
+
return result;
|
|
468
|
+
}
|
|
469
|
+
function Type$1(tag, options) {
|
|
470
|
+
options = options || {};
|
|
471
|
+
Object.keys(options).forEach(function(name) {
|
|
472
|
+
if (TYPE_CONSTRUCTOR_OPTIONS.indexOf(name) === -1) {
|
|
473
|
+
throw new exception('Unknown option "' + name + '" is met in definition of "' + tag + '" YAML type.');
|
|
474
|
+
}
|
|
475
|
+
});
|
|
476
|
+
this.options = options;
|
|
477
|
+
this.tag = tag;
|
|
478
|
+
this.kind = options["kind"] || null;
|
|
479
|
+
this.resolve = options["resolve"] || function() {
|
|
480
|
+
return true;
|
|
481
|
+
};
|
|
482
|
+
this.construct = options["construct"] || function(data) {
|
|
483
|
+
return data;
|
|
484
|
+
};
|
|
485
|
+
this.instanceOf = options["instanceOf"] || null;
|
|
486
|
+
this.predicate = options["predicate"] || null;
|
|
487
|
+
this.represent = options["represent"] || null;
|
|
488
|
+
this.representName = options["representName"] || null;
|
|
489
|
+
this.defaultStyle = options["defaultStyle"] || null;
|
|
490
|
+
this.multi = options["multi"] || false;
|
|
491
|
+
this.styleAliases = compileStyleAliases(options["styleAliases"] || null);
|
|
492
|
+
if (YAML_NODE_KINDS.indexOf(this.kind) === -1) {
|
|
493
|
+
throw new exception('Unknown kind "' + this.kind + '" is specified for "' + tag + '" YAML type.');
|
|
494
|
+
}
|
|
495
|
+
}
|
|
496
|
+
var type = Type$1;
|
|
497
|
+
function compileList(schema, name) {
|
|
498
|
+
var result = [];
|
|
499
|
+
schema[name].forEach(function(currentType) {
|
|
500
|
+
var newIndex = result.length;
|
|
501
|
+
result.forEach(function(previousType, previousIndex) {
|
|
502
|
+
if (previousType.tag === currentType.tag && previousType.kind === currentType.kind && previousType.multi === currentType.multi) {
|
|
503
|
+
newIndex = previousIndex;
|
|
504
|
+
}
|
|
505
|
+
});
|
|
506
|
+
result[newIndex] = currentType;
|
|
507
|
+
});
|
|
508
|
+
return result;
|
|
509
|
+
}
|
|
510
|
+
function compileMap() {
|
|
511
|
+
var result = {
|
|
512
|
+
scalar: {},
|
|
513
|
+
sequence: {},
|
|
514
|
+
mapping: {},
|
|
515
|
+
fallback: {},
|
|
516
|
+
multi: {
|
|
517
|
+
scalar: [],
|
|
518
|
+
sequence: [],
|
|
519
|
+
mapping: [],
|
|
520
|
+
fallback: []
|
|
521
|
+
}
|
|
522
|
+
}, index, length;
|
|
523
|
+
function collectType(type2) {
|
|
524
|
+
if (type2.multi) {
|
|
525
|
+
result.multi[type2.kind].push(type2);
|
|
526
|
+
result.multi["fallback"].push(type2);
|
|
527
|
+
} else {
|
|
528
|
+
result[type2.kind][type2.tag] = result["fallback"][type2.tag] = type2;
|
|
529
|
+
}
|
|
530
|
+
}
|
|
531
|
+
for (index = 0, length = arguments.length;index < length; index += 1) {
|
|
532
|
+
arguments[index].forEach(collectType);
|
|
533
|
+
}
|
|
534
|
+
return result;
|
|
535
|
+
}
|
|
536
|
+
function Schema$1(definition) {
|
|
537
|
+
return this.extend(definition);
|
|
538
|
+
}
|
|
539
|
+
Schema$1.prototype.extend = function extend2(definition) {
|
|
540
|
+
var implicit = [];
|
|
541
|
+
var explicit = [];
|
|
542
|
+
if (definition instanceof type) {
|
|
543
|
+
explicit.push(definition);
|
|
544
|
+
} else if (Array.isArray(definition)) {
|
|
545
|
+
explicit = explicit.concat(definition);
|
|
546
|
+
} else if (definition && (Array.isArray(definition.implicit) || Array.isArray(definition.explicit))) {
|
|
547
|
+
if (definition.implicit)
|
|
548
|
+
implicit = implicit.concat(definition.implicit);
|
|
549
|
+
if (definition.explicit)
|
|
550
|
+
explicit = explicit.concat(definition.explicit);
|
|
551
|
+
} else {
|
|
552
|
+
throw new exception("Schema.extend argument should be a Type, [ Type ], " + "or a schema definition ({ implicit: [...], explicit: [...] })");
|
|
553
|
+
}
|
|
554
|
+
implicit.forEach(function(type$1) {
|
|
555
|
+
if (!(type$1 instanceof type)) {
|
|
556
|
+
throw new exception("Specified list of YAML types (or a single Type object) contains a non-Type object.");
|
|
557
|
+
}
|
|
558
|
+
if (type$1.loadKind && type$1.loadKind !== "scalar") {
|
|
559
|
+
throw new exception("There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported.");
|
|
560
|
+
}
|
|
561
|
+
if (type$1.multi) {
|
|
562
|
+
throw new exception("There is a multi type in the implicit list of a schema. Multi tags can only be listed as explicit.");
|
|
563
|
+
}
|
|
564
|
+
});
|
|
565
|
+
explicit.forEach(function(type$1) {
|
|
566
|
+
if (!(type$1 instanceof type)) {
|
|
567
|
+
throw new exception("Specified list of YAML types (or a single Type object) contains a non-Type object.");
|
|
568
|
+
}
|
|
569
|
+
});
|
|
570
|
+
var result = Object.create(Schema$1.prototype);
|
|
571
|
+
result.implicit = (this.implicit || []).concat(implicit);
|
|
572
|
+
result.explicit = (this.explicit || []).concat(explicit);
|
|
573
|
+
result.compiledImplicit = compileList(result, "implicit");
|
|
574
|
+
result.compiledExplicit = compileList(result, "explicit");
|
|
575
|
+
result.compiledTypeMap = compileMap(result.compiledImplicit, result.compiledExplicit);
|
|
576
|
+
return result;
|
|
577
|
+
};
|
|
578
|
+
var schema = Schema$1;
|
|
579
|
+
var str = new type("tag:yaml.org,2002:str", {
|
|
580
|
+
kind: "scalar",
|
|
581
|
+
construct: function(data) {
|
|
582
|
+
return data !== null ? data : "";
|
|
583
|
+
}
|
|
584
|
+
});
|
|
585
|
+
var seq = new type("tag:yaml.org,2002:seq", {
|
|
586
|
+
kind: "sequence",
|
|
587
|
+
construct: function(data) {
|
|
588
|
+
return data !== null ? data : [];
|
|
589
|
+
}
|
|
590
|
+
});
|
|
591
|
+
var map = new type("tag:yaml.org,2002:map", {
|
|
592
|
+
kind: "mapping",
|
|
593
|
+
construct: function(data) {
|
|
594
|
+
return data !== null ? data : {};
|
|
595
|
+
}
|
|
596
|
+
});
|
|
597
|
+
var failsafe = new schema({
|
|
598
|
+
explicit: [
|
|
599
|
+
str,
|
|
600
|
+
seq,
|
|
601
|
+
map
|
|
602
|
+
]
|
|
603
|
+
});
|
|
604
|
+
function resolveYamlNull(data) {
|
|
605
|
+
if (data === null)
|
|
606
|
+
return true;
|
|
607
|
+
var max = data.length;
|
|
608
|
+
return max === 1 && data === "~" || max === 4 && (data === "null" || data === "Null" || data === "NULL");
|
|
609
|
+
}
|
|
610
|
+
function constructYamlNull() {
|
|
611
|
+
return null;
|
|
612
|
+
}
|
|
613
|
+
function isNull(object) {
|
|
614
|
+
return object === null;
|
|
615
|
+
}
|
|
616
|
+
var _null = new type("tag:yaml.org,2002:null", {
|
|
617
|
+
kind: "scalar",
|
|
618
|
+
resolve: resolveYamlNull,
|
|
619
|
+
construct: constructYamlNull,
|
|
620
|
+
predicate: isNull,
|
|
621
|
+
represent: {
|
|
622
|
+
canonical: function() {
|
|
623
|
+
return "~";
|
|
624
|
+
},
|
|
625
|
+
lowercase: function() {
|
|
626
|
+
return "null";
|
|
627
|
+
},
|
|
628
|
+
uppercase: function() {
|
|
629
|
+
return "NULL";
|
|
630
|
+
},
|
|
631
|
+
camelcase: function() {
|
|
632
|
+
return "Null";
|
|
633
|
+
},
|
|
634
|
+
empty: function() {
|
|
635
|
+
return "";
|
|
636
|
+
}
|
|
637
|
+
},
|
|
638
|
+
defaultStyle: "lowercase"
|
|
639
|
+
});
|
|
640
|
+
function resolveYamlBoolean(data) {
|
|
641
|
+
if (data === null)
|
|
642
|
+
return false;
|
|
643
|
+
var max = data.length;
|
|
644
|
+
return max === 4 && (data === "true" || data === "True" || data === "TRUE") || max === 5 && (data === "false" || data === "False" || data === "FALSE");
|
|
645
|
+
}
|
|
646
|
+
function constructYamlBoolean(data) {
|
|
647
|
+
return data === "true" || data === "True" || data === "TRUE";
|
|
648
|
+
}
|
|
649
|
+
function isBoolean(object) {
|
|
650
|
+
return Object.prototype.toString.call(object) === "[object Boolean]";
|
|
651
|
+
}
|
|
652
|
+
var bool = new type("tag:yaml.org,2002:bool", {
|
|
653
|
+
kind: "scalar",
|
|
654
|
+
resolve: resolveYamlBoolean,
|
|
655
|
+
construct: constructYamlBoolean,
|
|
656
|
+
predicate: isBoolean,
|
|
657
|
+
represent: {
|
|
658
|
+
lowercase: function(object) {
|
|
659
|
+
return object ? "true" : "false";
|
|
660
|
+
},
|
|
661
|
+
uppercase: function(object) {
|
|
662
|
+
return object ? "TRUE" : "FALSE";
|
|
663
|
+
},
|
|
664
|
+
camelcase: function(object) {
|
|
665
|
+
return object ? "True" : "False";
|
|
666
|
+
}
|
|
667
|
+
},
|
|
668
|
+
defaultStyle: "lowercase"
|
|
669
|
+
});
|
|
670
|
+
function isHexCode(c) {
|
|
671
|
+
return 48 <= c && c <= 57 || 65 <= c && c <= 70 || 97 <= c && c <= 102;
|
|
672
|
+
}
|
|
673
|
+
function isOctCode(c) {
|
|
674
|
+
return 48 <= c && c <= 55;
|
|
675
|
+
}
|
|
676
|
+
function isDecCode(c) {
|
|
677
|
+
return 48 <= c && c <= 57;
|
|
678
|
+
}
|
|
679
|
+
function resolveYamlInteger(data) {
|
|
680
|
+
if (data === null)
|
|
681
|
+
return false;
|
|
682
|
+
var max = data.length, index = 0, hasDigits = false, ch;
|
|
683
|
+
if (!max)
|
|
684
|
+
return false;
|
|
685
|
+
ch = data[index];
|
|
686
|
+
if (ch === "-" || ch === "+") {
|
|
687
|
+
ch = data[++index];
|
|
688
|
+
}
|
|
689
|
+
if (ch === "0") {
|
|
690
|
+
if (index + 1 === max)
|
|
691
|
+
return true;
|
|
692
|
+
ch = data[++index];
|
|
693
|
+
if (ch === "b") {
|
|
694
|
+
index++;
|
|
695
|
+
for (;index < max; index++) {
|
|
696
|
+
ch = data[index];
|
|
697
|
+
if (ch === "_")
|
|
698
|
+
continue;
|
|
699
|
+
if (ch !== "0" && ch !== "1")
|
|
700
|
+
return false;
|
|
701
|
+
hasDigits = true;
|
|
702
|
+
}
|
|
703
|
+
return hasDigits && ch !== "_";
|
|
704
|
+
}
|
|
705
|
+
if (ch === "x") {
|
|
706
|
+
index++;
|
|
707
|
+
for (;index < max; index++) {
|
|
708
|
+
ch = data[index];
|
|
709
|
+
if (ch === "_")
|
|
710
|
+
continue;
|
|
711
|
+
if (!isHexCode(data.charCodeAt(index)))
|
|
712
|
+
return false;
|
|
713
|
+
hasDigits = true;
|
|
714
|
+
}
|
|
715
|
+
return hasDigits && ch !== "_";
|
|
716
|
+
}
|
|
717
|
+
if (ch === "o") {
|
|
718
|
+
index++;
|
|
719
|
+
for (;index < max; index++) {
|
|
720
|
+
ch = data[index];
|
|
721
|
+
if (ch === "_")
|
|
722
|
+
continue;
|
|
723
|
+
if (!isOctCode(data.charCodeAt(index)))
|
|
724
|
+
return false;
|
|
725
|
+
hasDigits = true;
|
|
726
|
+
}
|
|
727
|
+
return hasDigits && ch !== "_";
|
|
728
|
+
}
|
|
729
|
+
}
|
|
730
|
+
if (ch === "_")
|
|
731
|
+
return false;
|
|
732
|
+
for (;index < max; index++) {
|
|
733
|
+
ch = data[index];
|
|
734
|
+
if (ch === "_")
|
|
735
|
+
continue;
|
|
736
|
+
if (!isDecCode(data.charCodeAt(index))) {
|
|
737
|
+
return false;
|
|
738
|
+
}
|
|
739
|
+
hasDigits = true;
|
|
740
|
+
}
|
|
741
|
+
if (!hasDigits || ch === "_")
|
|
742
|
+
return false;
|
|
743
|
+
return true;
|
|
744
|
+
}
|
|
745
|
+
function constructYamlInteger(data) {
|
|
746
|
+
var value = data, sign = 1, ch;
|
|
747
|
+
if (value.indexOf("_") !== -1) {
|
|
748
|
+
value = value.replace(/_/g, "");
|
|
749
|
+
}
|
|
750
|
+
ch = value[0];
|
|
751
|
+
if (ch === "-" || ch === "+") {
|
|
752
|
+
if (ch === "-")
|
|
753
|
+
sign = -1;
|
|
754
|
+
value = value.slice(1);
|
|
755
|
+
ch = value[0];
|
|
756
|
+
}
|
|
757
|
+
if (value === "0")
|
|
758
|
+
return 0;
|
|
759
|
+
if (ch === "0") {
|
|
760
|
+
if (value[1] === "b")
|
|
761
|
+
return sign * parseInt(value.slice(2), 2);
|
|
762
|
+
if (value[1] === "x")
|
|
763
|
+
return sign * parseInt(value.slice(2), 16);
|
|
764
|
+
if (value[1] === "o")
|
|
765
|
+
return sign * parseInt(value.slice(2), 8);
|
|
766
|
+
}
|
|
767
|
+
return sign * parseInt(value, 10);
|
|
768
|
+
}
|
|
769
|
+
function isInteger(object) {
|
|
770
|
+
return Object.prototype.toString.call(object) === "[object Number]" && (object % 1 === 0 && !common.isNegativeZero(object));
|
|
771
|
+
}
|
|
772
|
+
var int = new type("tag:yaml.org,2002:int", {
|
|
773
|
+
kind: "scalar",
|
|
774
|
+
resolve: resolveYamlInteger,
|
|
775
|
+
construct: constructYamlInteger,
|
|
776
|
+
predicate: isInteger,
|
|
777
|
+
represent: {
|
|
778
|
+
binary: function(obj) {
|
|
779
|
+
return obj >= 0 ? "0b" + obj.toString(2) : "-0b" + obj.toString(2).slice(1);
|
|
780
|
+
},
|
|
781
|
+
octal: function(obj) {
|
|
782
|
+
return obj >= 0 ? "0o" + obj.toString(8) : "-0o" + obj.toString(8).slice(1);
|
|
783
|
+
},
|
|
784
|
+
decimal: function(obj) {
|
|
785
|
+
return obj.toString(10);
|
|
786
|
+
},
|
|
787
|
+
hexadecimal: function(obj) {
|
|
788
|
+
return obj >= 0 ? "0x" + obj.toString(16).toUpperCase() : "-0x" + obj.toString(16).toUpperCase().slice(1);
|
|
789
|
+
}
|
|
790
|
+
},
|
|
791
|
+
defaultStyle: "decimal",
|
|
792
|
+
styleAliases: {
|
|
793
|
+
binary: [2, "bin"],
|
|
794
|
+
octal: [8, "oct"],
|
|
795
|
+
decimal: [10, "dec"],
|
|
796
|
+
hexadecimal: [16, "hex"]
|
|
797
|
+
}
|
|
798
|
+
});
|
|
799
|
+
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))$");
|
|
800
|
+
function resolveYamlFloat(data) {
|
|
801
|
+
if (data === null)
|
|
802
|
+
return false;
|
|
803
|
+
if (!YAML_FLOAT_PATTERN.test(data) || data[data.length - 1] === "_") {
|
|
804
|
+
return false;
|
|
805
|
+
}
|
|
806
|
+
return true;
|
|
807
|
+
}
|
|
808
|
+
function constructYamlFloat(data) {
|
|
809
|
+
var value, sign;
|
|
810
|
+
value = data.replace(/_/g, "").toLowerCase();
|
|
811
|
+
sign = value[0] === "-" ? -1 : 1;
|
|
812
|
+
if ("+-".indexOf(value[0]) >= 0) {
|
|
813
|
+
value = value.slice(1);
|
|
814
|
+
}
|
|
815
|
+
if (value === ".inf") {
|
|
816
|
+
return sign === 1 ? Number.POSITIVE_INFINITY : Number.NEGATIVE_INFINITY;
|
|
817
|
+
} else if (value === ".nan") {
|
|
818
|
+
return NaN;
|
|
819
|
+
}
|
|
820
|
+
return sign * parseFloat(value, 10);
|
|
821
|
+
}
|
|
822
|
+
var SCIENTIFIC_WITHOUT_DOT = /^[-+]?[0-9]+e/;
|
|
823
|
+
function representYamlFloat(object, style) {
|
|
824
|
+
var res;
|
|
825
|
+
if (isNaN(object)) {
|
|
826
|
+
switch (style) {
|
|
827
|
+
case "lowercase":
|
|
828
|
+
return ".nan";
|
|
829
|
+
case "uppercase":
|
|
830
|
+
return ".NAN";
|
|
831
|
+
case "camelcase":
|
|
832
|
+
return ".NaN";
|
|
833
|
+
}
|
|
834
|
+
} else if (Number.POSITIVE_INFINITY === object) {
|
|
835
|
+
switch (style) {
|
|
836
|
+
case "lowercase":
|
|
837
|
+
return ".inf";
|
|
838
|
+
case "uppercase":
|
|
839
|
+
return ".INF";
|
|
840
|
+
case "camelcase":
|
|
841
|
+
return ".Inf";
|
|
842
|
+
}
|
|
843
|
+
} else if (Number.NEGATIVE_INFINITY === object) {
|
|
844
|
+
switch (style) {
|
|
845
|
+
case "lowercase":
|
|
846
|
+
return "-.inf";
|
|
847
|
+
case "uppercase":
|
|
848
|
+
return "-.INF";
|
|
849
|
+
case "camelcase":
|
|
850
|
+
return "-.Inf";
|
|
851
|
+
}
|
|
852
|
+
} else if (common.isNegativeZero(object)) {
|
|
853
|
+
return "-0.0";
|
|
854
|
+
}
|
|
855
|
+
res = object.toString(10);
|
|
856
|
+
return SCIENTIFIC_WITHOUT_DOT.test(res) ? res.replace("e", ".e") : res;
|
|
857
|
+
}
|
|
858
|
+
function isFloat(object) {
|
|
859
|
+
return Object.prototype.toString.call(object) === "[object Number]" && (object % 1 !== 0 || common.isNegativeZero(object));
|
|
860
|
+
}
|
|
861
|
+
var float = new type("tag:yaml.org,2002:float", {
|
|
862
|
+
kind: "scalar",
|
|
863
|
+
resolve: resolveYamlFloat,
|
|
864
|
+
construct: constructYamlFloat,
|
|
865
|
+
predicate: isFloat,
|
|
866
|
+
represent: representYamlFloat,
|
|
867
|
+
defaultStyle: "lowercase"
|
|
868
|
+
});
|
|
869
|
+
var json = failsafe.extend({
|
|
870
|
+
implicit: [
|
|
871
|
+
_null,
|
|
872
|
+
bool,
|
|
873
|
+
int,
|
|
874
|
+
float
|
|
875
|
+
]
|
|
876
|
+
});
|
|
877
|
+
var core = json;
|
|
878
|
+
var YAML_DATE_REGEXP = new RegExp("^([0-9][0-9][0-9][0-9])" + "-([0-9][0-9])" + "-([0-9][0-9])$");
|
|
879
|
+
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]))?))?$");
|
|
880
|
+
function resolveYamlTimestamp(data) {
|
|
881
|
+
if (data === null)
|
|
882
|
+
return false;
|
|
883
|
+
if (YAML_DATE_REGEXP.exec(data) !== null)
|
|
884
|
+
return true;
|
|
885
|
+
if (YAML_TIMESTAMP_REGEXP.exec(data) !== null)
|
|
886
|
+
return true;
|
|
887
|
+
return false;
|
|
888
|
+
}
|
|
889
|
+
function constructYamlTimestamp(data) {
|
|
890
|
+
var match, year, month, day, hour, minute, second, fraction = 0, delta = null, tz_hour, tz_minute, date;
|
|
891
|
+
match = YAML_DATE_REGEXP.exec(data);
|
|
892
|
+
if (match === null)
|
|
893
|
+
match = YAML_TIMESTAMP_REGEXP.exec(data);
|
|
894
|
+
if (match === null)
|
|
895
|
+
throw new Error("Date resolve error");
|
|
896
|
+
year = +match[1];
|
|
897
|
+
month = +match[2] - 1;
|
|
898
|
+
day = +match[3];
|
|
899
|
+
if (!match[4]) {
|
|
900
|
+
return new Date(Date.UTC(year, month, day));
|
|
901
|
+
}
|
|
902
|
+
hour = +match[4];
|
|
903
|
+
minute = +match[5];
|
|
904
|
+
second = +match[6];
|
|
905
|
+
if (match[7]) {
|
|
906
|
+
fraction = match[7].slice(0, 3);
|
|
907
|
+
while (fraction.length < 3) {
|
|
908
|
+
fraction += "0";
|
|
909
|
+
}
|
|
910
|
+
fraction = +fraction;
|
|
911
|
+
}
|
|
912
|
+
if (match[9]) {
|
|
913
|
+
tz_hour = +match[10];
|
|
914
|
+
tz_minute = +(match[11] || 0);
|
|
915
|
+
delta = (tz_hour * 60 + tz_minute) * 60000;
|
|
916
|
+
if (match[9] === "-")
|
|
917
|
+
delta = -delta;
|
|
918
|
+
}
|
|
919
|
+
date = new Date(Date.UTC(year, month, day, hour, minute, second, fraction));
|
|
920
|
+
if (delta)
|
|
921
|
+
date.setTime(date.getTime() - delta);
|
|
922
|
+
return date;
|
|
923
|
+
}
|
|
924
|
+
function representYamlTimestamp(object) {
|
|
925
|
+
return object.toISOString();
|
|
926
|
+
}
|
|
927
|
+
var timestamp = new type("tag:yaml.org,2002:timestamp", {
|
|
928
|
+
kind: "scalar",
|
|
929
|
+
resolve: resolveYamlTimestamp,
|
|
930
|
+
construct: constructYamlTimestamp,
|
|
931
|
+
instanceOf: Date,
|
|
932
|
+
represent: representYamlTimestamp
|
|
933
|
+
});
|
|
934
|
+
function resolveYamlMerge(data) {
|
|
935
|
+
return data === "<<" || data === null;
|
|
936
|
+
}
|
|
937
|
+
var merge = new type("tag:yaml.org,2002:merge", {
|
|
938
|
+
kind: "scalar",
|
|
939
|
+
resolve: resolveYamlMerge
|
|
940
|
+
});
|
|
941
|
+
var BASE64_MAP = `ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=
|
|
942
|
+
\r`;
|
|
943
|
+
function resolveYamlBinary(data) {
|
|
944
|
+
if (data === null)
|
|
945
|
+
return false;
|
|
946
|
+
var code, idx, bitlen = 0, max = data.length, map2 = BASE64_MAP;
|
|
947
|
+
for (idx = 0;idx < max; idx++) {
|
|
948
|
+
code = map2.indexOf(data.charAt(idx));
|
|
949
|
+
if (code > 64)
|
|
950
|
+
continue;
|
|
951
|
+
if (code < 0)
|
|
952
|
+
return false;
|
|
953
|
+
bitlen += 6;
|
|
954
|
+
}
|
|
955
|
+
return bitlen % 8 === 0;
|
|
956
|
+
}
|
|
957
|
+
function constructYamlBinary(data) {
|
|
958
|
+
var idx, tailbits, input = data.replace(/[\r\n=]/g, ""), max = input.length, map2 = BASE64_MAP, bits = 0, result = [];
|
|
959
|
+
for (idx = 0;idx < max; idx++) {
|
|
960
|
+
if (idx % 4 === 0 && idx) {
|
|
961
|
+
result.push(bits >> 16 & 255);
|
|
962
|
+
result.push(bits >> 8 & 255);
|
|
963
|
+
result.push(bits & 255);
|
|
964
|
+
}
|
|
965
|
+
bits = bits << 6 | map2.indexOf(input.charAt(idx));
|
|
966
|
+
}
|
|
967
|
+
tailbits = max % 4 * 6;
|
|
968
|
+
if (tailbits === 0) {
|
|
969
|
+
result.push(bits >> 16 & 255);
|
|
970
|
+
result.push(bits >> 8 & 255);
|
|
971
|
+
result.push(bits & 255);
|
|
972
|
+
} else if (tailbits === 18) {
|
|
973
|
+
result.push(bits >> 10 & 255);
|
|
974
|
+
result.push(bits >> 2 & 255);
|
|
975
|
+
} else if (tailbits === 12) {
|
|
976
|
+
result.push(bits >> 4 & 255);
|
|
977
|
+
}
|
|
978
|
+
return new Uint8Array(result);
|
|
979
|
+
}
|
|
980
|
+
function representYamlBinary(object) {
|
|
981
|
+
var result = "", bits = 0, idx, tail, max = object.length, map2 = BASE64_MAP;
|
|
982
|
+
for (idx = 0;idx < max; idx++) {
|
|
983
|
+
if (idx % 3 === 0 && idx) {
|
|
984
|
+
result += map2[bits >> 18 & 63];
|
|
985
|
+
result += map2[bits >> 12 & 63];
|
|
986
|
+
result += map2[bits >> 6 & 63];
|
|
987
|
+
result += map2[bits & 63];
|
|
988
|
+
}
|
|
989
|
+
bits = (bits << 8) + object[idx];
|
|
990
|
+
}
|
|
991
|
+
tail = max % 3;
|
|
992
|
+
if (tail === 0) {
|
|
993
|
+
result += map2[bits >> 18 & 63];
|
|
994
|
+
result += map2[bits >> 12 & 63];
|
|
995
|
+
result += map2[bits >> 6 & 63];
|
|
996
|
+
result += map2[bits & 63];
|
|
997
|
+
} else if (tail === 2) {
|
|
998
|
+
result += map2[bits >> 10 & 63];
|
|
999
|
+
result += map2[bits >> 4 & 63];
|
|
1000
|
+
result += map2[bits << 2 & 63];
|
|
1001
|
+
result += map2[64];
|
|
1002
|
+
} else if (tail === 1) {
|
|
1003
|
+
result += map2[bits >> 2 & 63];
|
|
1004
|
+
result += map2[bits << 4 & 63];
|
|
1005
|
+
result += map2[64];
|
|
1006
|
+
result += map2[64];
|
|
1007
|
+
}
|
|
1008
|
+
return result;
|
|
1009
|
+
}
|
|
1010
|
+
function isBinary(obj) {
|
|
1011
|
+
return Object.prototype.toString.call(obj) === "[object Uint8Array]";
|
|
1012
|
+
}
|
|
1013
|
+
var binary = new type("tag:yaml.org,2002:binary", {
|
|
1014
|
+
kind: "scalar",
|
|
1015
|
+
resolve: resolveYamlBinary,
|
|
1016
|
+
construct: constructYamlBinary,
|
|
1017
|
+
predicate: isBinary,
|
|
1018
|
+
represent: representYamlBinary
|
|
1019
|
+
});
|
|
1020
|
+
var _hasOwnProperty$3 = Object.prototype.hasOwnProperty;
|
|
1021
|
+
var _toString$2 = Object.prototype.toString;
|
|
1022
|
+
function resolveYamlOmap(data) {
|
|
1023
|
+
if (data === null)
|
|
1024
|
+
return true;
|
|
1025
|
+
var objectKeys = [], index, length, pair, pairKey, pairHasKey, object = data;
|
|
1026
|
+
for (index = 0, length = object.length;index < length; index += 1) {
|
|
1027
|
+
pair = object[index];
|
|
1028
|
+
pairHasKey = false;
|
|
1029
|
+
if (_toString$2.call(pair) !== "[object Object]")
|
|
1030
|
+
return false;
|
|
1031
|
+
for (pairKey in pair) {
|
|
1032
|
+
if (_hasOwnProperty$3.call(pair, pairKey)) {
|
|
1033
|
+
if (!pairHasKey)
|
|
1034
|
+
pairHasKey = true;
|
|
1035
|
+
else
|
|
1036
|
+
return false;
|
|
1037
|
+
}
|
|
1038
|
+
}
|
|
1039
|
+
if (!pairHasKey)
|
|
1040
|
+
return false;
|
|
1041
|
+
if (objectKeys.indexOf(pairKey) === -1)
|
|
1042
|
+
objectKeys.push(pairKey);
|
|
1043
|
+
else
|
|
1044
|
+
return false;
|
|
1045
|
+
}
|
|
1046
|
+
return true;
|
|
1047
|
+
}
|
|
1048
|
+
function constructYamlOmap(data) {
|
|
1049
|
+
return data !== null ? data : [];
|
|
1050
|
+
}
|
|
1051
|
+
var omap = new type("tag:yaml.org,2002:omap", {
|
|
1052
|
+
kind: "sequence",
|
|
1053
|
+
resolve: resolveYamlOmap,
|
|
1054
|
+
construct: constructYamlOmap
|
|
1055
|
+
});
|
|
1056
|
+
var _toString$1 = Object.prototype.toString;
|
|
1057
|
+
function resolveYamlPairs(data) {
|
|
1058
|
+
if (data === null)
|
|
1059
|
+
return true;
|
|
1060
|
+
var index, length, pair, keys, result, object = data;
|
|
1061
|
+
result = new Array(object.length);
|
|
1062
|
+
for (index = 0, length = object.length;index < length; index += 1) {
|
|
1063
|
+
pair = object[index];
|
|
1064
|
+
if (_toString$1.call(pair) !== "[object Object]")
|
|
1065
|
+
return false;
|
|
1066
|
+
keys = Object.keys(pair);
|
|
1067
|
+
if (keys.length !== 1)
|
|
1068
|
+
return false;
|
|
1069
|
+
result[index] = [keys[0], pair[keys[0]]];
|
|
1070
|
+
}
|
|
1071
|
+
return true;
|
|
1072
|
+
}
|
|
1073
|
+
function constructYamlPairs(data) {
|
|
1074
|
+
if (data === null)
|
|
1075
|
+
return [];
|
|
1076
|
+
var index, length, pair, keys, result, object = data;
|
|
1077
|
+
result = new Array(object.length);
|
|
1078
|
+
for (index = 0, length = object.length;index < length; index += 1) {
|
|
1079
|
+
pair = object[index];
|
|
1080
|
+
keys = Object.keys(pair);
|
|
1081
|
+
result[index] = [keys[0], pair[keys[0]]];
|
|
1082
|
+
}
|
|
1083
|
+
return result;
|
|
1084
|
+
}
|
|
1085
|
+
var pairs = new type("tag:yaml.org,2002:pairs", {
|
|
1086
|
+
kind: "sequence",
|
|
1087
|
+
resolve: resolveYamlPairs,
|
|
1088
|
+
construct: constructYamlPairs
|
|
1089
|
+
});
|
|
1090
|
+
var _hasOwnProperty$2 = Object.prototype.hasOwnProperty;
|
|
1091
|
+
function resolveYamlSet(data) {
|
|
1092
|
+
if (data === null)
|
|
1093
|
+
return true;
|
|
1094
|
+
var key, object = data;
|
|
1095
|
+
for (key in object) {
|
|
1096
|
+
if (_hasOwnProperty$2.call(object, key)) {
|
|
1097
|
+
if (object[key] !== null)
|
|
1098
|
+
return false;
|
|
1099
|
+
}
|
|
1100
|
+
}
|
|
1101
|
+
return true;
|
|
1102
|
+
}
|
|
1103
|
+
function constructYamlSet(data) {
|
|
1104
|
+
return data !== null ? data : {};
|
|
1105
|
+
}
|
|
1106
|
+
var set = new type("tag:yaml.org,2002:set", {
|
|
1107
|
+
kind: "mapping",
|
|
1108
|
+
resolve: resolveYamlSet,
|
|
1109
|
+
construct: constructYamlSet
|
|
1110
|
+
});
|
|
1111
|
+
var _default = core.extend({
|
|
1112
|
+
implicit: [
|
|
1113
|
+
timestamp,
|
|
1114
|
+
merge
|
|
1115
|
+
],
|
|
1116
|
+
explicit: [
|
|
1117
|
+
binary,
|
|
1118
|
+
omap,
|
|
1119
|
+
pairs,
|
|
1120
|
+
set
|
|
1121
|
+
]
|
|
1122
|
+
});
|
|
1123
|
+
var _hasOwnProperty$1 = Object.prototype.hasOwnProperty;
|
|
1124
|
+
var CONTEXT_FLOW_IN = 1;
|
|
1125
|
+
var CONTEXT_FLOW_OUT = 2;
|
|
1126
|
+
var CONTEXT_BLOCK_IN = 3;
|
|
1127
|
+
var CONTEXT_BLOCK_OUT = 4;
|
|
1128
|
+
var CHOMPING_CLIP = 1;
|
|
1129
|
+
var CHOMPING_STRIP = 2;
|
|
1130
|
+
var CHOMPING_KEEP = 3;
|
|
1131
|
+
var PATTERN_NON_PRINTABLE = /[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x84\x86-\x9F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/;
|
|
1132
|
+
var PATTERN_NON_ASCII_LINE_BREAKS = /[\x85\u2028\u2029]/;
|
|
1133
|
+
var PATTERN_FLOW_INDICATORS = /[,\[\]\{\}]/;
|
|
1134
|
+
var PATTERN_TAG_HANDLE = /^(?:!|!!|![a-z\-]+!)$/i;
|
|
1135
|
+
var PATTERN_TAG_URI = /^(?:!|[^,\[\]\{\}])(?:%[0-9a-f]{2}|[0-9a-z\-#;\/\?:@&=\+\$,_\.!~\*'\(\)\[\]])*$/i;
|
|
1136
|
+
function _class(obj) {
|
|
1137
|
+
return Object.prototype.toString.call(obj);
|
|
1138
|
+
}
|
|
1139
|
+
function is_EOL(c) {
|
|
1140
|
+
return c === 10 || c === 13;
|
|
1141
|
+
}
|
|
1142
|
+
function is_WHITE_SPACE(c) {
|
|
1143
|
+
return c === 9 || c === 32;
|
|
1144
|
+
}
|
|
1145
|
+
function is_WS_OR_EOL(c) {
|
|
1146
|
+
return c === 9 || c === 32 || c === 10 || c === 13;
|
|
1147
|
+
}
|
|
1148
|
+
function is_FLOW_INDICATOR(c) {
|
|
1149
|
+
return c === 44 || c === 91 || c === 93 || c === 123 || c === 125;
|
|
1150
|
+
}
|
|
1151
|
+
function fromHexCode(c) {
|
|
1152
|
+
var lc;
|
|
1153
|
+
if (48 <= c && c <= 57) {
|
|
1154
|
+
return c - 48;
|
|
1155
|
+
}
|
|
1156
|
+
lc = c | 32;
|
|
1157
|
+
if (97 <= lc && lc <= 102) {
|
|
1158
|
+
return lc - 97 + 10;
|
|
1159
|
+
}
|
|
1160
|
+
return -1;
|
|
1161
|
+
}
|
|
1162
|
+
function escapedHexLen(c) {
|
|
1163
|
+
if (c === 120) {
|
|
1164
|
+
return 2;
|
|
1165
|
+
}
|
|
1166
|
+
if (c === 117) {
|
|
1167
|
+
return 4;
|
|
1168
|
+
}
|
|
1169
|
+
if (c === 85) {
|
|
1170
|
+
return 8;
|
|
1171
|
+
}
|
|
1172
|
+
return 0;
|
|
1173
|
+
}
|
|
1174
|
+
function fromDecimalCode(c) {
|
|
1175
|
+
if (48 <= c && c <= 57) {
|
|
1176
|
+
return c - 48;
|
|
1177
|
+
}
|
|
1178
|
+
return -1;
|
|
1179
|
+
}
|
|
1180
|
+
function simpleEscapeSequence(c) {
|
|
1181
|
+
return c === 48 ? "\x00" : c === 97 ? "\x07" : c === 98 ? "\b" : c === 116 ? "\t" : c === 9 ? "\t" : c === 110 ? `
|
|
1182
|
+
` : 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" : "";
|
|
1183
|
+
}
|
|
1184
|
+
function charFromCodepoint(c) {
|
|
1185
|
+
if (c <= 65535) {
|
|
1186
|
+
return String.fromCharCode(c);
|
|
1187
|
+
}
|
|
1188
|
+
return String.fromCharCode((c - 65536 >> 10) + 55296, (c - 65536 & 1023) + 56320);
|
|
1189
|
+
}
|
|
1190
|
+
function setProperty(object, key, value) {
|
|
1191
|
+
if (key === "__proto__") {
|
|
1192
|
+
Object.defineProperty(object, key, {
|
|
1193
|
+
configurable: true,
|
|
1194
|
+
enumerable: true,
|
|
1195
|
+
writable: true,
|
|
1196
|
+
value
|
|
1197
|
+
});
|
|
1198
|
+
} else {
|
|
1199
|
+
object[key] = value;
|
|
1200
|
+
}
|
|
1201
|
+
}
|
|
1202
|
+
var simpleEscapeCheck = new Array(256);
|
|
1203
|
+
var simpleEscapeMap = new Array(256);
|
|
1204
|
+
for (i = 0;i < 256; i++) {
|
|
1205
|
+
simpleEscapeCheck[i] = simpleEscapeSequence(i) ? 1 : 0;
|
|
1206
|
+
simpleEscapeMap[i] = simpleEscapeSequence(i);
|
|
1207
|
+
}
|
|
1208
|
+
var i;
|
|
1209
|
+
function State$1(input, options) {
|
|
1210
|
+
this.input = input;
|
|
1211
|
+
this.filename = options["filename"] || null;
|
|
1212
|
+
this.schema = options["schema"] || _default;
|
|
1213
|
+
this.onWarning = options["onWarning"] || null;
|
|
1214
|
+
this.legacy = options["legacy"] || false;
|
|
1215
|
+
this.json = options["json"] || false;
|
|
1216
|
+
this.listener = options["listener"] || null;
|
|
1217
|
+
this.implicitTypes = this.schema.compiledImplicit;
|
|
1218
|
+
this.typeMap = this.schema.compiledTypeMap;
|
|
1219
|
+
this.length = input.length;
|
|
1220
|
+
this.position = 0;
|
|
1221
|
+
this.line = 0;
|
|
1222
|
+
this.lineStart = 0;
|
|
1223
|
+
this.lineIndent = 0;
|
|
1224
|
+
this.firstTabInLine = -1;
|
|
1225
|
+
this.documents = [];
|
|
1226
|
+
}
|
|
1227
|
+
function generateError(state, message) {
|
|
1228
|
+
var mark = {
|
|
1229
|
+
name: state.filename,
|
|
1230
|
+
buffer: state.input.slice(0, -1),
|
|
1231
|
+
position: state.position,
|
|
1232
|
+
line: state.line,
|
|
1233
|
+
column: state.position - state.lineStart
|
|
1234
|
+
};
|
|
1235
|
+
mark.snippet = snippet(mark);
|
|
1236
|
+
return new exception(message, mark);
|
|
1237
|
+
}
|
|
1238
|
+
function throwError(state, message) {
|
|
1239
|
+
throw generateError(state, message);
|
|
1240
|
+
}
|
|
1241
|
+
function throwWarning(state, message) {
|
|
1242
|
+
if (state.onWarning) {
|
|
1243
|
+
state.onWarning.call(null, generateError(state, message));
|
|
1244
|
+
}
|
|
1245
|
+
}
|
|
1246
|
+
var directiveHandlers = {
|
|
1247
|
+
YAML: function handleYamlDirective(state, name, args) {
|
|
1248
|
+
var match, major, minor;
|
|
1249
|
+
if (state.version !== null) {
|
|
1250
|
+
throwError(state, "duplication of %YAML directive");
|
|
1251
|
+
}
|
|
1252
|
+
if (args.length !== 1) {
|
|
1253
|
+
throwError(state, "YAML directive accepts exactly one argument");
|
|
1254
|
+
}
|
|
1255
|
+
match = /^([0-9]+)\.([0-9]+)$/.exec(args[0]);
|
|
1256
|
+
if (match === null) {
|
|
1257
|
+
throwError(state, "ill-formed argument of the YAML directive");
|
|
1258
|
+
}
|
|
1259
|
+
major = parseInt(match[1], 10);
|
|
1260
|
+
minor = parseInt(match[2], 10);
|
|
1261
|
+
if (major !== 1) {
|
|
1262
|
+
throwError(state, "unacceptable YAML version of the document");
|
|
1263
|
+
}
|
|
1264
|
+
state.version = args[0];
|
|
1265
|
+
state.checkLineBreaks = minor < 2;
|
|
1266
|
+
if (minor !== 1 && minor !== 2) {
|
|
1267
|
+
throwWarning(state, "unsupported YAML version of the document");
|
|
1268
|
+
}
|
|
1269
|
+
},
|
|
1270
|
+
TAG: function handleTagDirective(state, name, args) {
|
|
1271
|
+
var handle, prefix;
|
|
1272
|
+
if (args.length !== 2) {
|
|
1273
|
+
throwError(state, "TAG directive accepts exactly two arguments");
|
|
1274
|
+
}
|
|
1275
|
+
handle = args[0];
|
|
1276
|
+
prefix = args[1];
|
|
1277
|
+
if (!PATTERN_TAG_HANDLE.test(handle)) {
|
|
1278
|
+
throwError(state, "ill-formed tag handle (first argument) of the TAG directive");
|
|
1279
|
+
}
|
|
1280
|
+
if (_hasOwnProperty$1.call(state.tagMap, handle)) {
|
|
1281
|
+
throwError(state, 'there is a previously declared suffix for "' + handle + '" tag handle');
|
|
1282
|
+
}
|
|
1283
|
+
if (!PATTERN_TAG_URI.test(prefix)) {
|
|
1284
|
+
throwError(state, "ill-formed tag prefix (second argument) of the TAG directive");
|
|
1285
|
+
}
|
|
1286
|
+
try {
|
|
1287
|
+
prefix = decodeURIComponent(prefix);
|
|
1288
|
+
} catch (err) {
|
|
1289
|
+
throwError(state, "tag prefix is malformed: " + prefix);
|
|
1290
|
+
}
|
|
1291
|
+
state.tagMap[handle] = prefix;
|
|
1292
|
+
}
|
|
1293
|
+
};
|
|
1294
|
+
function captureSegment(state, start, end, checkJson) {
|
|
1295
|
+
var _position, _length, _character, _result;
|
|
1296
|
+
if (start < end) {
|
|
1297
|
+
_result = state.input.slice(start, end);
|
|
1298
|
+
if (checkJson) {
|
|
1299
|
+
for (_position = 0, _length = _result.length;_position < _length; _position += 1) {
|
|
1300
|
+
_character = _result.charCodeAt(_position);
|
|
1301
|
+
if (!(_character === 9 || 32 <= _character && _character <= 1114111)) {
|
|
1302
|
+
throwError(state, "expected valid JSON character");
|
|
1303
|
+
}
|
|
1304
|
+
}
|
|
1305
|
+
} else if (PATTERN_NON_PRINTABLE.test(_result)) {
|
|
1306
|
+
throwError(state, "the stream contains non-printable characters");
|
|
1307
|
+
}
|
|
1308
|
+
state.result += _result;
|
|
1309
|
+
}
|
|
1310
|
+
}
|
|
1311
|
+
function mergeMappings(state, destination, source, overridableKeys) {
|
|
1312
|
+
var sourceKeys, key, index, quantity;
|
|
1313
|
+
if (!common.isObject(source)) {
|
|
1314
|
+
throwError(state, "cannot merge mappings; the provided source object is unacceptable");
|
|
1315
|
+
}
|
|
1316
|
+
sourceKeys = Object.keys(source);
|
|
1317
|
+
for (index = 0, quantity = sourceKeys.length;index < quantity; index += 1) {
|
|
1318
|
+
key = sourceKeys[index];
|
|
1319
|
+
if (!_hasOwnProperty$1.call(destination, key)) {
|
|
1320
|
+
setProperty(destination, key, source[key]);
|
|
1321
|
+
overridableKeys[key] = true;
|
|
1322
|
+
}
|
|
1323
|
+
}
|
|
1324
|
+
}
|
|
1325
|
+
function storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, startLine, startLineStart, startPos) {
|
|
1326
|
+
var index, quantity;
|
|
1327
|
+
if (Array.isArray(keyNode)) {
|
|
1328
|
+
keyNode = Array.prototype.slice.call(keyNode);
|
|
1329
|
+
for (index = 0, quantity = keyNode.length;index < quantity; index += 1) {
|
|
1330
|
+
if (Array.isArray(keyNode[index])) {
|
|
1331
|
+
throwError(state, "nested arrays are not supported inside keys");
|
|
1332
|
+
}
|
|
1333
|
+
if (typeof keyNode === "object" && _class(keyNode[index]) === "[object Object]") {
|
|
1334
|
+
keyNode[index] = "[object Object]";
|
|
1335
|
+
}
|
|
1336
|
+
}
|
|
1337
|
+
}
|
|
1338
|
+
if (typeof keyNode === "object" && _class(keyNode) === "[object Object]") {
|
|
1339
|
+
keyNode = "[object Object]";
|
|
1340
|
+
}
|
|
1341
|
+
keyNode = String(keyNode);
|
|
1342
|
+
if (_result === null) {
|
|
1343
|
+
_result = {};
|
|
1344
|
+
}
|
|
1345
|
+
if (keyTag === "tag:yaml.org,2002:merge") {
|
|
1346
|
+
if (Array.isArray(valueNode)) {
|
|
1347
|
+
for (index = 0, quantity = valueNode.length;index < quantity; index += 1) {
|
|
1348
|
+
mergeMappings(state, _result, valueNode[index], overridableKeys);
|
|
1349
|
+
}
|
|
1350
|
+
} else {
|
|
1351
|
+
mergeMappings(state, _result, valueNode, overridableKeys);
|
|
1352
|
+
}
|
|
1353
|
+
} else {
|
|
1354
|
+
if (!state.json && !_hasOwnProperty$1.call(overridableKeys, keyNode) && _hasOwnProperty$1.call(_result, keyNode)) {
|
|
1355
|
+
state.line = startLine || state.line;
|
|
1356
|
+
state.lineStart = startLineStart || state.lineStart;
|
|
1357
|
+
state.position = startPos || state.position;
|
|
1358
|
+
throwError(state, "duplicated mapping key");
|
|
1359
|
+
}
|
|
1360
|
+
setProperty(_result, keyNode, valueNode);
|
|
1361
|
+
delete overridableKeys[keyNode];
|
|
1362
|
+
}
|
|
1363
|
+
return _result;
|
|
1364
|
+
}
|
|
1365
|
+
function readLineBreak(state) {
|
|
1366
|
+
var ch;
|
|
1367
|
+
ch = state.input.charCodeAt(state.position);
|
|
1368
|
+
if (ch === 10) {
|
|
1369
|
+
state.position++;
|
|
1370
|
+
} else if (ch === 13) {
|
|
1371
|
+
state.position++;
|
|
1372
|
+
if (state.input.charCodeAt(state.position) === 10) {
|
|
1373
|
+
state.position++;
|
|
1374
|
+
}
|
|
1375
|
+
} else {
|
|
1376
|
+
throwError(state, "a line break is expected");
|
|
1377
|
+
}
|
|
1378
|
+
state.line += 1;
|
|
1379
|
+
state.lineStart = state.position;
|
|
1380
|
+
state.firstTabInLine = -1;
|
|
1381
|
+
}
|
|
1382
|
+
function skipSeparationSpace(state, allowComments, checkIndent) {
|
|
1383
|
+
var lineBreaks = 0, ch = state.input.charCodeAt(state.position);
|
|
1384
|
+
while (ch !== 0) {
|
|
1385
|
+
while (is_WHITE_SPACE(ch)) {
|
|
1386
|
+
if (ch === 9 && state.firstTabInLine === -1) {
|
|
1387
|
+
state.firstTabInLine = state.position;
|
|
1388
|
+
}
|
|
1389
|
+
ch = state.input.charCodeAt(++state.position);
|
|
1390
|
+
}
|
|
1391
|
+
if (allowComments && ch === 35) {
|
|
1392
|
+
do {
|
|
1393
|
+
ch = state.input.charCodeAt(++state.position);
|
|
1394
|
+
} while (ch !== 10 && ch !== 13 && ch !== 0);
|
|
1395
|
+
}
|
|
1396
|
+
if (is_EOL(ch)) {
|
|
1397
|
+
readLineBreak(state);
|
|
1398
|
+
ch = state.input.charCodeAt(state.position);
|
|
1399
|
+
lineBreaks++;
|
|
1400
|
+
state.lineIndent = 0;
|
|
1401
|
+
while (ch === 32) {
|
|
1402
|
+
state.lineIndent++;
|
|
1403
|
+
ch = state.input.charCodeAt(++state.position);
|
|
1404
|
+
}
|
|
1405
|
+
} else {
|
|
1406
|
+
break;
|
|
1407
|
+
}
|
|
1408
|
+
}
|
|
1409
|
+
if (checkIndent !== -1 && lineBreaks !== 0 && state.lineIndent < checkIndent) {
|
|
1410
|
+
throwWarning(state, "deficient indentation");
|
|
1411
|
+
}
|
|
1412
|
+
return lineBreaks;
|
|
1413
|
+
}
|
|
1414
|
+
function testDocumentSeparator(state) {
|
|
1415
|
+
var _position = state.position, ch;
|
|
1416
|
+
ch = state.input.charCodeAt(_position);
|
|
1417
|
+
if ((ch === 45 || ch === 46) && ch === state.input.charCodeAt(_position + 1) && ch === state.input.charCodeAt(_position + 2)) {
|
|
1418
|
+
_position += 3;
|
|
1419
|
+
ch = state.input.charCodeAt(_position);
|
|
1420
|
+
if (ch === 0 || is_WS_OR_EOL(ch)) {
|
|
1421
|
+
return true;
|
|
1422
|
+
}
|
|
1423
|
+
}
|
|
1424
|
+
return false;
|
|
1425
|
+
}
|
|
1426
|
+
function writeFoldedLines(state, count) {
|
|
1427
|
+
if (count === 1) {
|
|
1428
|
+
state.result += " ";
|
|
1429
|
+
} else if (count > 1) {
|
|
1430
|
+
state.result += common.repeat(`
|
|
1431
|
+
`, count - 1);
|
|
1432
|
+
}
|
|
1433
|
+
}
|
|
1434
|
+
function readPlainScalar(state, nodeIndent, withinFlowCollection) {
|
|
1435
|
+
var preceding, following, captureStart, captureEnd, hasPendingContent, _line, _lineStart, _lineIndent, _kind = state.kind, _result = state.result, ch;
|
|
1436
|
+
ch = state.input.charCodeAt(state.position);
|
|
1437
|
+
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) {
|
|
1438
|
+
return false;
|
|
1439
|
+
}
|
|
1440
|
+
if (ch === 63 || ch === 45) {
|
|
1441
|
+
following = state.input.charCodeAt(state.position + 1);
|
|
1442
|
+
if (is_WS_OR_EOL(following) || withinFlowCollection && is_FLOW_INDICATOR(following)) {
|
|
1443
|
+
return false;
|
|
1444
|
+
}
|
|
1445
|
+
}
|
|
1446
|
+
state.kind = "scalar";
|
|
1447
|
+
state.result = "";
|
|
1448
|
+
captureStart = captureEnd = state.position;
|
|
1449
|
+
hasPendingContent = false;
|
|
1450
|
+
while (ch !== 0) {
|
|
1451
|
+
if (ch === 58) {
|
|
1452
|
+
following = state.input.charCodeAt(state.position + 1);
|
|
1453
|
+
if (is_WS_OR_EOL(following) || withinFlowCollection && is_FLOW_INDICATOR(following)) {
|
|
1454
|
+
break;
|
|
1455
|
+
}
|
|
1456
|
+
} else if (ch === 35) {
|
|
1457
|
+
preceding = state.input.charCodeAt(state.position - 1);
|
|
1458
|
+
if (is_WS_OR_EOL(preceding)) {
|
|
1459
|
+
break;
|
|
1460
|
+
}
|
|
1461
|
+
} else if (state.position === state.lineStart && testDocumentSeparator(state) || withinFlowCollection && is_FLOW_INDICATOR(ch)) {
|
|
1462
|
+
break;
|
|
1463
|
+
} else if (is_EOL(ch)) {
|
|
1464
|
+
_line = state.line;
|
|
1465
|
+
_lineStart = state.lineStart;
|
|
1466
|
+
_lineIndent = state.lineIndent;
|
|
1467
|
+
skipSeparationSpace(state, false, -1);
|
|
1468
|
+
if (state.lineIndent >= nodeIndent) {
|
|
1469
|
+
hasPendingContent = true;
|
|
1470
|
+
ch = state.input.charCodeAt(state.position);
|
|
1471
|
+
continue;
|
|
1472
|
+
} else {
|
|
1473
|
+
state.position = captureEnd;
|
|
1474
|
+
state.line = _line;
|
|
1475
|
+
state.lineStart = _lineStart;
|
|
1476
|
+
state.lineIndent = _lineIndent;
|
|
1477
|
+
break;
|
|
1478
|
+
}
|
|
1479
|
+
}
|
|
1480
|
+
if (hasPendingContent) {
|
|
1481
|
+
captureSegment(state, captureStart, captureEnd, false);
|
|
1482
|
+
writeFoldedLines(state, state.line - _line);
|
|
1483
|
+
captureStart = captureEnd = state.position;
|
|
1484
|
+
hasPendingContent = false;
|
|
1485
|
+
}
|
|
1486
|
+
if (!is_WHITE_SPACE(ch)) {
|
|
1487
|
+
captureEnd = state.position + 1;
|
|
1488
|
+
}
|
|
1489
|
+
ch = state.input.charCodeAt(++state.position);
|
|
1490
|
+
}
|
|
1491
|
+
captureSegment(state, captureStart, captureEnd, false);
|
|
1492
|
+
if (state.result) {
|
|
1493
|
+
return true;
|
|
1494
|
+
}
|
|
1495
|
+
state.kind = _kind;
|
|
1496
|
+
state.result = _result;
|
|
1497
|
+
return false;
|
|
1498
|
+
}
|
|
1499
|
+
function readSingleQuotedScalar(state, nodeIndent) {
|
|
1500
|
+
var ch, captureStart, captureEnd;
|
|
1501
|
+
ch = state.input.charCodeAt(state.position);
|
|
1502
|
+
if (ch !== 39) {
|
|
1503
|
+
return false;
|
|
1504
|
+
}
|
|
1505
|
+
state.kind = "scalar";
|
|
1506
|
+
state.result = "";
|
|
1507
|
+
state.position++;
|
|
1508
|
+
captureStart = captureEnd = state.position;
|
|
1509
|
+
while ((ch = state.input.charCodeAt(state.position)) !== 0) {
|
|
1510
|
+
if (ch === 39) {
|
|
1511
|
+
captureSegment(state, captureStart, state.position, true);
|
|
1512
|
+
ch = state.input.charCodeAt(++state.position);
|
|
1513
|
+
if (ch === 39) {
|
|
1514
|
+
captureStart = state.position;
|
|
1515
|
+
state.position++;
|
|
1516
|
+
captureEnd = state.position;
|
|
1517
|
+
} else {
|
|
1518
|
+
return true;
|
|
1519
|
+
}
|
|
1520
|
+
} else if (is_EOL(ch)) {
|
|
1521
|
+
captureSegment(state, captureStart, captureEnd, true);
|
|
1522
|
+
writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent));
|
|
1523
|
+
captureStart = captureEnd = state.position;
|
|
1524
|
+
} else if (state.position === state.lineStart && testDocumentSeparator(state)) {
|
|
1525
|
+
throwError(state, "unexpected end of the document within a single quoted scalar");
|
|
1526
|
+
} else {
|
|
1527
|
+
state.position++;
|
|
1528
|
+
captureEnd = state.position;
|
|
1529
|
+
}
|
|
1530
|
+
}
|
|
1531
|
+
throwError(state, "unexpected end of the stream within a single quoted scalar");
|
|
1532
|
+
}
|
|
1533
|
+
function readDoubleQuotedScalar(state, nodeIndent) {
|
|
1534
|
+
var captureStart, captureEnd, hexLength, hexResult, tmp, ch;
|
|
1535
|
+
ch = state.input.charCodeAt(state.position);
|
|
1536
|
+
if (ch !== 34) {
|
|
1537
|
+
return false;
|
|
1538
|
+
}
|
|
1539
|
+
state.kind = "scalar";
|
|
1540
|
+
state.result = "";
|
|
1541
|
+
state.position++;
|
|
1542
|
+
captureStart = captureEnd = state.position;
|
|
1543
|
+
while ((ch = state.input.charCodeAt(state.position)) !== 0) {
|
|
1544
|
+
if (ch === 34) {
|
|
1545
|
+
captureSegment(state, captureStart, state.position, true);
|
|
1546
|
+
state.position++;
|
|
1547
|
+
return true;
|
|
1548
|
+
} else if (ch === 92) {
|
|
1549
|
+
captureSegment(state, captureStart, state.position, true);
|
|
1550
|
+
ch = state.input.charCodeAt(++state.position);
|
|
1551
|
+
if (is_EOL(ch)) {
|
|
1552
|
+
skipSeparationSpace(state, false, nodeIndent);
|
|
1553
|
+
} else if (ch < 256 && simpleEscapeCheck[ch]) {
|
|
1554
|
+
state.result += simpleEscapeMap[ch];
|
|
1555
|
+
state.position++;
|
|
1556
|
+
} else if ((tmp = escapedHexLen(ch)) > 0) {
|
|
1557
|
+
hexLength = tmp;
|
|
1558
|
+
hexResult = 0;
|
|
1559
|
+
for (;hexLength > 0; hexLength--) {
|
|
1560
|
+
ch = state.input.charCodeAt(++state.position);
|
|
1561
|
+
if ((tmp = fromHexCode(ch)) >= 0) {
|
|
1562
|
+
hexResult = (hexResult << 4) + tmp;
|
|
1563
|
+
} else {
|
|
1564
|
+
throwError(state, "expected hexadecimal character");
|
|
1565
|
+
}
|
|
1566
|
+
}
|
|
1567
|
+
state.result += charFromCodepoint(hexResult);
|
|
1568
|
+
state.position++;
|
|
1569
|
+
} else {
|
|
1570
|
+
throwError(state, "unknown escape sequence");
|
|
1571
|
+
}
|
|
1572
|
+
captureStart = captureEnd = state.position;
|
|
1573
|
+
} else if (is_EOL(ch)) {
|
|
1574
|
+
captureSegment(state, captureStart, captureEnd, true);
|
|
1575
|
+
writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent));
|
|
1576
|
+
captureStart = captureEnd = state.position;
|
|
1577
|
+
} else if (state.position === state.lineStart && testDocumentSeparator(state)) {
|
|
1578
|
+
throwError(state, "unexpected end of the document within a double quoted scalar");
|
|
1579
|
+
} else {
|
|
1580
|
+
state.position++;
|
|
1581
|
+
captureEnd = state.position;
|
|
1582
|
+
}
|
|
1583
|
+
}
|
|
1584
|
+
throwError(state, "unexpected end of the stream within a double quoted scalar");
|
|
1585
|
+
}
|
|
1586
|
+
function readFlowCollection(state, nodeIndent) {
|
|
1587
|
+
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;
|
|
1588
|
+
ch = state.input.charCodeAt(state.position);
|
|
1589
|
+
if (ch === 91) {
|
|
1590
|
+
terminator = 93;
|
|
1591
|
+
isMapping = false;
|
|
1592
|
+
_result = [];
|
|
1593
|
+
} else if (ch === 123) {
|
|
1594
|
+
terminator = 125;
|
|
1595
|
+
isMapping = true;
|
|
1596
|
+
_result = {};
|
|
1597
|
+
} else {
|
|
1598
|
+
return false;
|
|
1599
|
+
}
|
|
1600
|
+
if (state.anchor !== null) {
|
|
1601
|
+
state.anchorMap[state.anchor] = _result;
|
|
1602
|
+
}
|
|
1603
|
+
ch = state.input.charCodeAt(++state.position);
|
|
1604
|
+
while (ch !== 0) {
|
|
1605
|
+
skipSeparationSpace(state, true, nodeIndent);
|
|
1606
|
+
ch = state.input.charCodeAt(state.position);
|
|
1607
|
+
if (ch === terminator) {
|
|
1608
|
+
state.position++;
|
|
1609
|
+
state.tag = _tag;
|
|
1610
|
+
state.anchor = _anchor;
|
|
1611
|
+
state.kind = isMapping ? "mapping" : "sequence";
|
|
1612
|
+
state.result = _result;
|
|
1613
|
+
return true;
|
|
1614
|
+
} else if (!readNext) {
|
|
1615
|
+
throwError(state, "missed comma between flow collection entries");
|
|
1616
|
+
} else if (ch === 44) {
|
|
1617
|
+
throwError(state, "expected the node content, but found ','");
|
|
1618
|
+
}
|
|
1619
|
+
keyTag = keyNode = valueNode = null;
|
|
1620
|
+
isPair = isExplicitPair = false;
|
|
1621
|
+
if (ch === 63) {
|
|
1622
|
+
following = state.input.charCodeAt(state.position + 1);
|
|
1623
|
+
if (is_WS_OR_EOL(following)) {
|
|
1624
|
+
isPair = isExplicitPair = true;
|
|
1625
|
+
state.position++;
|
|
1626
|
+
skipSeparationSpace(state, true, nodeIndent);
|
|
1627
|
+
}
|
|
1628
|
+
}
|
|
1629
|
+
_line = state.line;
|
|
1630
|
+
_lineStart = state.lineStart;
|
|
1631
|
+
_pos = state.position;
|
|
1632
|
+
composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true);
|
|
1633
|
+
keyTag = state.tag;
|
|
1634
|
+
keyNode = state.result;
|
|
1635
|
+
skipSeparationSpace(state, true, nodeIndent);
|
|
1636
|
+
ch = state.input.charCodeAt(state.position);
|
|
1637
|
+
if ((isExplicitPair || state.line === _line) && ch === 58) {
|
|
1638
|
+
isPair = true;
|
|
1639
|
+
ch = state.input.charCodeAt(++state.position);
|
|
1640
|
+
skipSeparationSpace(state, true, nodeIndent);
|
|
1641
|
+
composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true);
|
|
1642
|
+
valueNode = state.result;
|
|
1643
|
+
}
|
|
1644
|
+
if (isMapping) {
|
|
1645
|
+
storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, _line, _lineStart, _pos);
|
|
1646
|
+
} else if (isPair) {
|
|
1647
|
+
_result.push(storeMappingPair(state, null, overridableKeys, keyTag, keyNode, valueNode, _line, _lineStart, _pos));
|
|
1648
|
+
} else {
|
|
1649
|
+
_result.push(keyNode);
|
|
1650
|
+
}
|
|
1651
|
+
skipSeparationSpace(state, true, nodeIndent);
|
|
1652
|
+
ch = state.input.charCodeAt(state.position);
|
|
1653
|
+
if (ch === 44) {
|
|
1654
|
+
readNext = true;
|
|
1655
|
+
ch = state.input.charCodeAt(++state.position);
|
|
1656
|
+
} else {
|
|
1657
|
+
readNext = false;
|
|
1658
|
+
}
|
|
1659
|
+
}
|
|
1660
|
+
throwError(state, "unexpected end of the stream within a flow collection");
|
|
1661
|
+
}
|
|
1662
|
+
function readBlockScalar(state, nodeIndent) {
|
|
1663
|
+
var captureStart, folding, chomping = CHOMPING_CLIP, didReadContent = false, detectedIndent = false, textIndent = nodeIndent, emptyLines = 0, atMoreIndented = false, tmp, ch;
|
|
1664
|
+
ch = state.input.charCodeAt(state.position);
|
|
1665
|
+
if (ch === 124) {
|
|
1666
|
+
folding = false;
|
|
1667
|
+
} else if (ch === 62) {
|
|
1668
|
+
folding = true;
|
|
1669
|
+
} else {
|
|
1670
|
+
return false;
|
|
1671
|
+
}
|
|
1672
|
+
state.kind = "scalar";
|
|
1673
|
+
state.result = "";
|
|
1674
|
+
while (ch !== 0) {
|
|
1675
|
+
ch = state.input.charCodeAt(++state.position);
|
|
1676
|
+
if (ch === 43 || ch === 45) {
|
|
1677
|
+
if (CHOMPING_CLIP === chomping) {
|
|
1678
|
+
chomping = ch === 43 ? CHOMPING_KEEP : CHOMPING_STRIP;
|
|
1679
|
+
} else {
|
|
1680
|
+
throwError(state, "repeat of a chomping mode identifier");
|
|
1681
|
+
}
|
|
1682
|
+
} else if ((tmp = fromDecimalCode(ch)) >= 0) {
|
|
1683
|
+
if (tmp === 0) {
|
|
1684
|
+
throwError(state, "bad explicit indentation width of a block scalar; it cannot be less than one");
|
|
1685
|
+
} else if (!detectedIndent) {
|
|
1686
|
+
textIndent = nodeIndent + tmp - 1;
|
|
1687
|
+
detectedIndent = true;
|
|
1688
|
+
} else {
|
|
1689
|
+
throwError(state, "repeat of an indentation width identifier");
|
|
1690
|
+
}
|
|
1691
|
+
} else {
|
|
1692
|
+
break;
|
|
1693
|
+
}
|
|
1694
|
+
}
|
|
1695
|
+
if (is_WHITE_SPACE(ch)) {
|
|
1696
|
+
do {
|
|
1697
|
+
ch = state.input.charCodeAt(++state.position);
|
|
1698
|
+
} while (is_WHITE_SPACE(ch));
|
|
1699
|
+
if (ch === 35) {
|
|
1700
|
+
do {
|
|
1701
|
+
ch = state.input.charCodeAt(++state.position);
|
|
1702
|
+
} while (!is_EOL(ch) && ch !== 0);
|
|
1703
|
+
}
|
|
1704
|
+
}
|
|
1705
|
+
while (ch !== 0) {
|
|
1706
|
+
readLineBreak(state);
|
|
1707
|
+
state.lineIndent = 0;
|
|
1708
|
+
ch = state.input.charCodeAt(state.position);
|
|
1709
|
+
while ((!detectedIndent || state.lineIndent < textIndent) && ch === 32) {
|
|
1710
|
+
state.lineIndent++;
|
|
1711
|
+
ch = state.input.charCodeAt(++state.position);
|
|
1712
|
+
}
|
|
1713
|
+
if (!detectedIndent && state.lineIndent > textIndent) {
|
|
1714
|
+
textIndent = state.lineIndent;
|
|
1715
|
+
}
|
|
1716
|
+
if (is_EOL(ch)) {
|
|
1717
|
+
emptyLines++;
|
|
1718
|
+
continue;
|
|
1719
|
+
}
|
|
1720
|
+
if (state.lineIndent < textIndent) {
|
|
1721
|
+
if (chomping === CHOMPING_KEEP) {
|
|
1722
|
+
state.result += common.repeat(`
|
|
1723
|
+
`, didReadContent ? 1 + emptyLines : emptyLines);
|
|
1724
|
+
} else if (chomping === CHOMPING_CLIP) {
|
|
1725
|
+
if (didReadContent) {
|
|
1726
|
+
state.result += `
|
|
1727
|
+
`;
|
|
1728
|
+
}
|
|
1729
|
+
}
|
|
1730
|
+
break;
|
|
1731
|
+
}
|
|
1732
|
+
if (folding) {
|
|
1733
|
+
if (is_WHITE_SPACE(ch)) {
|
|
1734
|
+
atMoreIndented = true;
|
|
1735
|
+
state.result += common.repeat(`
|
|
1736
|
+
`, didReadContent ? 1 + emptyLines : emptyLines);
|
|
1737
|
+
} else if (atMoreIndented) {
|
|
1738
|
+
atMoreIndented = false;
|
|
1739
|
+
state.result += common.repeat(`
|
|
1740
|
+
`, emptyLines + 1);
|
|
1741
|
+
} else if (emptyLines === 0) {
|
|
1742
|
+
if (didReadContent) {
|
|
1743
|
+
state.result += " ";
|
|
1744
|
+
}
|
|
1745
|
+
} else {
|
|
1746
|
+
state.result += common.repeat(`
|
|
1747
|
+
`, emptyLines);
|
|
1748
|
+
}
|
|
1749
|
+
} else {
|
|
1750
|
+
state.result += common.repeat(`
|
|
1751
|
+
`, didReadContent ? 1 + emptyLines : emptyLines);
|
|
1752
|
+
}
|
|
1753
|
+
didReadContent = true;
|
|
1754
|
+
detectedIndent = true;
|
|
1755
|
+
emptyLines = 0;
|
|
1756
|
+
captureStart = state.position;
|
|
1757
|
+
while (!is_EOL(ch) && ch !== 0) {
|
|
1758
|
+
ch = state.input.charCodeAt(++state.position);
|
|
1759
|
+
}
|
|
1760
|
+
captureSegment(state, captureStart, state.position, false);
|
|
1761
|
+
}
|
|
1762
|
+
return true;
|
|
1763
|
+
}
|
|
1764
|
+
function readBlockSequence(state, nodeIndent) {
|
|
1765
|
+
var _line, _tag = state.tag, _anchor = state.anchor, _result = [], following, detected = false, ch;
|
|
1766
|
+
if (state.firstTabInLine !== -1)
|
|
1767
|
+
return false;
|
|
1768
|
+
if (state.anchor !== null) {
|
|
1769
|
+
state.anchorMap[state.anchor] = _result;
|
|
1770
|
+
}
|
|
1771
|
+
ch = state.input.charCodeAt(state.position);
|
|
1772
|
+
while (ch !== 0) {
|
|
1773
|
+
if (state.firstTabInLine !== -1) {
|
|
1774
|
+
state.position = state.firstTabInLine;
|
|
1775
|
+
throwError(state, "tab characters must not be used in indentation");
|
|
1776
|
+
}
|
|
1777
|
+
if (ch !== 45) {
|
|
1778
|
+
break;
|
|
1779
|
+
}
|
|
1780
|
+
following = state.input.charCodeAt(state.position + 1);
|
|
1781
|
+
if (!is_WS_OR_EOL(following)) {
|
|
1782
|
+
break;
|
|
1783
|
+
}
|
|
1784
|
+
detected = true;
|
|
1785
|
+
state.position++;
|
|
1786
|
+
if (skipSeparationSpace(state, true, -1)) {
|
|
1787
|
+
if (state.lineIndent <= nodeIndent) {
|
|
1788
|
+
_result.push(null);
|
|
1789
|
+
ch = state.input.charCodeAt(state.position);
|
|
1790
|
+
continue;
|
|
1791
|
+
}
|
|
1792
|
+
}
|
|
1793
|
+
_line = state.line;
|
|
1794
|
+
composeNode(state, nodeIndent, CONTEXT_BLOCK_IN, false, true);
|
|
1795
|
+
_result.push(state.result);
|
|
1796
|
+
skipSeparationSpace(state, true, -1);
|
|
1797
|
+
ch = state.input.charCodeAt(state.position);
|
|
1798
|
+
if ((state.line === _line || state.lineIndent > nodeIndent) && ch !== 0) {
|
|
1799
|
+
throwError(state, "bad indentation of a sequence entry");
|
|
1800
|
+
} else if (state.lineIndent < nodeIndent) {
|
|
1801
|
+
break;
|
|
1802
|
+
}
|
|
1803
|
+
}
|
|
1804
|
+
if (detected) {
|
|
1805
|
+
state.tag = _tag;
|
|
1806
|
+
state.anchor = _anchor;
|
|
1807
|
+
state.kind = "sequence";
|
|
1808
|
+
state.result = _result;
|
|
1809
|
+
return true;
|
|
1810
|
+
}
|
|
1811
|
+
return false;
|
|
1812
|
+
}
|
|
1813
|
+
function readBlockMapping(state, nodeIndent, flowIndent) {
|
|
1814
|
+
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;
|
|
1815
|
+
if (state.firstTabInLine !== -1)
|
|
1816
|
+
return false;
|
|
1817
|
+
if (state.anchor !== null) {
|
|
1818
|
+
state.anchorMap[state.anchor] = _result;
|
|
1819
|
+
}
|
|
1820
|
+
ch = state.input.charCodeAt(state.position);
|
|
1821
|
+
while (ch !== 0) {
|
|
1822
|
+
if (!atExplicitKey && state.firstTabInLine !== -1) {
|
|
1823
|
+
state.position = state.firstTabInLine;
|
|
1824
|
+
throwError(state, "tab characters must not be used in indentation");
|
|
1825
|
+
}
|
|
1826
|
+
following = state.input.charCodeAt(state.position + 1);
|
|
1827
|
+
_line = state.line;
|
|
1828
|
+
if ((ch === 63 || ch === 58) && is_WS_OR_EOL(following)) {
|
|
1829
|
+
if (ch === 63) {
|
|
1830
|
+
if (atExplicitKey) {
|
|
1831
|
+
storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos);
|
|
1832
|
+
keyTag = keyNode = valueNode = null;
|
|
1833
|
+
}
|
|
1834
|
+
detected = true;
|
|
1835
|
+
atExplicitKey = true;
|
|
1836
|
+
allowCompact = true;
|
|
1837
|
+
} else if (atExplicitKey) {
|
|
1838
|
+
atExplicitKey = false;
|
|
1839
|
+
allowCompact = true;
|
|
1840
|
+
} else {
|
|
1841
|
+
throwError(state, "incomplete explicit mapping pair; a key node is missed; or followed by a non-tabulated empty line");
|
|
1842
|
+
}
|
|
1843
|
+
state.position += 1;
|
|
1844
|
+
ch = following;
|
|
1845
|
+
} else {
|
|
1846
|
+
_keyLine = state.line;
|
|
1847
|
+
_keyLineStart = state.lineStart;
|
|
1848
|
+
_keyPos = state.position;
|
|
1849
|
+
if (!composeNode(state, flowIndent, CONTEXT_FLOW_OUT, false, true)) {
|
|
1850
|
+
break;
|
|
1851
|
+
}
|
|
1852
|
+
if (state.line === _line) {
|
|
1853
|
+
ch = state.input.charCodeAt(state.position);
|
|
1854
|
+
while (is_WHITE_SPACE(ch)) {
|
|
1855
|
+
ch = state.input.charCodeAt(++state.position);
|
|
1856
|
+
}
|
|
1857
|
+
if (ch === 58) {
|
|
1858
|
+
ch = state.input.charCodeAt(++state.position);
|
|
1859
|
+
if (!is_WS_OR_EOL(ch)) {
|
|
1860
|
+
throwError(state, "a whitespace character is expected after the key-value separator within a block mapping");
|
|
1861
|
+
}
|
|
1862
|
+
if (atExplicitKey) {
|
|
1863
|
+
storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos);
|
|
1864
|
+
keyTag = keyNode = valueNode = null;
|
|
1865
|
+
}
|
|
1866
|
+
detected = true;
|
|
1867
|
+
atExplicitKey = false;
|
|
1868
|
+
allowCompact = false;
|
|
1869
|
+
keyTag = state.tag;
|
|
1870
|
+
keyNode = state.result;
|
|
1871
|
+
} else if (detected) {
|
|
1872
|
+
throwError(state, "can not read an implicit mapping pair; a colon is missed");
|
|
1873
|
+
} else {
|
|
1874
|
+
state.tag = _tag;
|
|
1875
|
+
state.anchor = _anchor;
|
|
1876
|
+
return true;
|
|
1877
|
+
}
|
|
1878
|
+
} else if (detected) {
|
|
1879
|
+
throwError(state, "can not read a block mapping entry; a multiline key may not be an implicit key");
|
|
1880
|
+
} else {
|
|
1881
|
+
state.tag = _tag;
|
|
1882
|
+
state.anchor = _anchor;
|
|
1883
|
+
return true;
|
|
1884
|
+
}
|
|
1885
|
+
}
|
|
1886
|
+
if (state.line === _line || state.lineIndent > nodeIndent) {
|
|
1887
|
+
if (atExplicitKey) {
|
|
1888
|
+
_keyLine = state.line;
|
|
1889
|
+
_keyLineStart = state.lineStart;
|
|
1890
|
+
_keyPos = state.position;
|
|
1891
|
+
}
|
|
1892
|
+
if (composeNode(state, nodeIndent, CONTEXT_BLOCK_OUT, true, allowCompact)) {
|
|
1893
|
+
if (atExplicitKey) {
|
|
1894
|
+
keyNode = state.result;
|
|
1895
|
+
} else {
|
|
1896
|
+
valueNode = state.result;
|
|
1897
|
+
}
|
|
1898
|
+
}
|
|
1899
|
+
if (!atExplicitKey) {
|
|
1900
|
+
storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, _keyLine, _keyLineStart, _keyPos);
|
|
1901
|
+
keyTag = keyNode = valueNode = null;
|
|
1902
|
+
}
|
|
1903
|
+
skipSeparationSpace(state, true, -1);
|
|
1904
|
+
ch = state.input.charCodeAt(state.position);
|
|
1905
|
+
}
|
|
1906
|
+
if ((state.line === _line || state.lineIndent > nodeIndent) && ch !== 0) {
|
|
1907
|
+
throwError(state, "bad indentation of a mapping entry");
|
|
1908
|
+
} else if (state.lineIndent < nodeIndent) {
|
|
1909
|
+
break;
|
|
1910
|
+
}
|
|
1911
|
+
}
|
|
1912
|
+
if (atExplicitKey) {
|
|
1913
|
+
storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos);
|
|
1914
|
+
}
|
|
1915
|
+
if (detected) {
|
|
1916
|
+
state.tag = _tag;
|
|
1917
|
+
state.anchor = _anchor;
|
|
1918
|
+
state.kind = "mapping";
|
|
1919
|
+
state.result = _result;
|
|
1920
|
+
}
|
|
1921
|
+
return detected;
|
|
1922
|
+
}
|
|
1923
|
+
function readTagProperty(state) {
|
|
1924
|
+
var _position, isVerbatim = false, isNamed = false, tagHandle, tagName, ch;
|
|
1925
|
+
ch = state.input.charCodeAt(state.position);
|
|
1926
|
+
if (ch !== 33)
|
|
1927
|
+
return false;
|
|
1928
|
+
if (state.tag !== null) {
|
|
1929
|
+
throwError(state, "duplication of a tag property");
|
|
1930
|
+
}
|
|
1931
|
+
ch = state.input.charCodeAt(++state.position);
|
|
1932
|
+
if (ch === 60) {
|
|
1933
|
+
isVerbatim = true;
|
|
1934
|
+
ch = state.input.charCodeAt(++state.position);
|
|
1935
|
+
} else if (ch === 33) {
|
|
1936
|
+
isNamed = true;
|
|
1937
|
+
tagHandle = "!!";
|
|
1938
|
+
ch = state.input.charCodeAt(++state.position);
|
|
1939
|
+
} else {
|
|
1940
|
+
tagHandle = "!";
|
|
1941
|
+
}
|
|
1942
|
+
_position = state.position;
|
|
1943
|
+
if (isVerbatim) {
|
|
1944
|
+
do {
|
|
1945
|
+
ch = state.input.charCodeAt(++state.position);
|
|
1946
|
+
} while (ch !== 0 && ch !== 62);
|
|
1947
|
+
if (state.position < state.length) {
|
|
1948
|
+
tagName = state.input.slice(_position, state.position);
|
|
1949
|
+
ch = state.input.charCodeAt(++state.position);
|
|
1950
|
+
} else {
|
|
1951
|
+
throwError(state, "unexpected end of the stream within a verbatim tag");
|
|
1952
|
+
}
|
|
1953
|
+
} else {
|
|
1954
|
+
while (ch !== 0 && !is_WS_OR_EOL(ch)) {
|
|
1955
|
+
if (ch === 33) {
|
|
1956
|
+
if (!isNamed) {
|
|
1957
|
+
tagHandle = state.input.slice(_position - 1, state.position + 1);
|
|
1958
|
+
if (!PATTERN_TAG_HANDLE.test(tagHandle)) {
|
|
1959
|
+
throwError(state, "named tag handle cannot contain such characters");
|
|
1960
|
+
}
|
|
1961
|
+
isNamed = true;
|
|
1962
|
+
_position = state.position + 1;
|
|
1963
|
+
} else {
|
|
1964
|
+
throwError(state, "tag suffix cannot contain exclamation marks");
|
|
1965
|
+
}
|
|
1966
|
+
}
|
|
1967
|
+
ch = state.input.charCodeAt(++state.position);
|
|
1968
|
+
}
|
|
1969
|
+
tagName = state.input.slice(_position, state.position);
|
|
1970
|
+
if (PATTERN_FLOW_INDICATORS.test(tagName)) {
|
|
1971
|
+
throwError(state, "tag suffix cannot contain flow indicator characters");
|
|
1972
|
+
}
|
|
1973
|
+
}
|
|
1974
|
+
if (tagName && !PATTERN_TAG_URI.test(tagName)) {
|
|
1975
|
+
throwError(state, "tag name cannot contain such characters: " + tagName);
|
|
1976
|
+
}
|
|
1977
|
+
try {
|
|
1978
|
+
tagName = decodeURIComponent(tagName);
|
|
1979
|
+
} catch (err) {
|
|
1980
|
+
throwError(state, "tag name is malformed: " + tagName);
|
|
1981
|
+
}
|
|
1982
|
+
if (isVerbatim) {
|
|
1983
|
+
state.tag = tagName;
|
|
1984
|
+
} else if (_hasOwnProperty$1.call(state.tagMap, tagHandle)) {
|
|
1985
|
+
state.tag = state.tagMap[tagHandle] + tagName;
|
|
1986
|
+
} else if (tagHandle === "!") {
|
|
1987
|
+
state.tag = "!" + tagName;
|
|
1988
|
+
} else if (tagHandle === "!!") {
|
|
1989
|
+
state.tag = "tag:yaml.org,2002:" + tagName;
|
|
1990
|
+
} else {
|
|
1991
|
+
throwError(state, 'undeclared tag handle "' + tagHandle + '"');
|
|
1992
|
+
}
|
|
1993
|
+
return true;
|
|
1994
|
+
}
|
|
1995
|
+
function readAnchorProperty(state) {
|
|
1996
|
+
var _position, ch;
|
|
1997
|
+
ch = state.input.charCodeAt(state.position);
|
|
1998
|
+
if (ch !== 38)
|
|
1999
|
+
return false;
|
|
2000
|
+
if (state.anchor !== null) {
|
|
2001
|
+
throwError(state, "duplication of an anchor property");
|
|
2002
|
+
}
|
|
2003
|
+
ch = state.input.charCodeAt(++state.position);
|
|
2004
|
+
_position = state.position;
|
|
2005
|
+
while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) {
|
|
2006
|
+
ch = state.input.charCodeAt(++state.position);
|
|
2007
|
+
}
|
|
2008
|
+
if (state.position === _position) {
|
|
2009
|
+
throwError(state, "name of an anchor node must contain at least one character");
|
|
2010
|
+
}
|
|
2011
|
+
state.anchor = state.input.slice(_position, state.position);
|
|
2012
|
+
return true;
|
|
2013
|
+
}
|
|
2014
|
+
function readAlias(state) {
|
|
2015
|
+
var _position, alias, ch;
|
|
2016
|
+
ch = state.input.charCodeAt(state.position);
|
|
2017
|
+
if (ch !== 42)
|
|
2018
|
+
return false;
|
|
2019
|
+
ch = state.input.charCodeAt(++state.position);
|
|
2020
|
+
_position = state.position;
|
|
2021
|
+
while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) {
|
|
2022
|
+
ch = state.input.charCodeAt(++state.position);
|
|
2023
|
+
}
|
|
2024
|
+
if (state.position === _position) {
|
|
2025
|
+
throwError(state, "name of an alias node must contain at least one character");
|
|
2026
|
+
}
|
|
2027
|
+
alias = state.input.slice(_position, state.position);
|
|
2028
|
+
if (!_hasOwnProperty$1.call(state.anchorMap, alias)) {
|
|
2029
|
+
throwError(state, 'unidentified alias "' + alias + '"');
|
|
2030
|
+
}
|
|
2031
|
+
state.result = state.anchorMap[alias];
|
|
2032
|
+
skipSeparationSpace(state, true, -1);
|
|
2033
|
+
return true;
|
|
2034
|
+
}
|
|
2035
|
+
function composeNode(state, parentIndent, nodeContext, allowToSeek, allowCompact) {
|
|
2036
|
+
var allowBlockStyles, allowBlockScalars, allowBlockCollections, indentStatus = 1, atNewLine = false, hasContent = false, typeIndex, typeQuantity, typeList, type2, flowIndent, blockIndent;
|
|
2037
|
+
if (state.listener !== null) {
|
|
2038
|
+
state.listener("open", state);
|
|
2039
|
+
}
|
|
2040
|
+
state.tag = null;
|
|
2041
|
+
state.anchor = null;
|
|
2042
|
+
state.kind = null;
|
|
2043
|
+
state.result = null;
|
|
2044
|
+
allowBlockStyles = allowBlockScalars = allowBlockCollections = CONTEXT_BLOCK_OUT === nodeContext || CONTEXT_BLOCK_IN === nodeContext;
|
|
2045
|
+
if (allowToSeek) {
|
|
2046
|
+
if (skipSeparationSpace(state, true, -1)) {
|
|
2047
|
+
atNewLine = true;
|
|
2048
|
+
if (state.lineIndent > parentIndent) {
|
|
2049
|
+
indentStatus = 1;
|
|
2050
|
+
} else if (state.lineIndent === parentIndent) {
|
|
2051
|
+
indentStatus = 0;
|
|
2052
|
+
} else if (state.lineIndent < parentIndent) {
|
|
2053
|
+
indentStatus = -1;
|
|
2054
|
+
}
|
|
2055
|
+
}
|
|
2056
|
+
}
|
|
2057
|
+
if (indentStatus === 1) {
|
|
2058
|
+
while (readTagProperty(state) || readAnchorProperty(state)) {
|
|
2059
|
+
if (skipSeparationSpace(state, true, -1)) {
|
|
2060
|
+
atNewLine = true;
|
|
2061
|
+
allowBlockCollections = allowBlockStyles;
|
|
2062
|
+
if (state.lineIndent > parentIndent) {
|
|
2063
|
+
indentStatus = 1;
|
|
2064
|
+
} else if (state.lineIndent === parentIndent) {
|
|
2065
|
+
indentStatus = 0;
|
|
2066
|
+
} else if (state.lineIndent < parentIndent) {
|
|
2067
|
+
indentStatus = -1;
|
|
2068
|
+
}
|
|
2069
|
+
} else {
|
|
2070
|
+
allowBlockCollections = false;
|
|
2071
|
+
}
|
|
2072
|
+
}
|
|
2073
|
+
}
|
|
2074
|
+
if (allowBlockCollections) {
|
|
2075
|
+
allowBlockCollections = atNewLine || allowCompact;
|
|
2076
|
+
}
|
|
2077
|
+
if (indentStatus === 1 || CONTEXT_BLOCK_OUT === nodeContext) {
|
|
2078
|
+
if (CONTEXT_FLOW_IN === nodeContext || CONTEXT_FLOW_OUT === nodeContext) {
|
|
2079
|
+
flowIndent = parentIndent;
|
|
2080
|
+
} else {
|
|
2081
|
+
flowIndent = parentIndent + 1;
|
|
2082
|
+
}
|
|
2083
|
+
blockIndent = state.position - state.lineStart;
|
|
2084
|
+
if (indentStatus === 1) {
|
|
2085
|
+
if (allowBlockCollections && (readBlockSequence(state, blockIndent) || readBlockMapping(state, blockIndent, flowIndent)) || readFlowCollection(state, flowIndent)) {
|
|
2086
|
+
hasContent = true;
|
|
2087
|
+
} else {
|
|
2088
|
+
if (allowBlockScalars && readBlockScalar(state, flowIndent) || readSingleQuotedScalar(state, flowIndent) || readDoubleQuotedScalar(state, flowIndent)) {
|
|
2089
|
+
hasContent = true;
|
|
2090
|
+
} else if (readAlias(state)) {
|
|
2091
|
+
hasContent = true;
|
|
2092
|
+
if (state.tag !== null || state.anchor !== null) {
|
|
2093
|
+
throwError(state, "alias node should not have any properties");
|
|
2094
|
+
}
|
|
2095
|
+
} else if (readPlainScalar(state, flowIndent, CONTEXT_FLOW_IN === nodeContext)) {
|
|
2096
|
+
hasContent = true;
|
|
2097
|
+
if (state.tag === null) {
|
|
2098
|
+
state.tag = "?";
|
|
2099
|
+
}
|
|
2100
|
+
}
|
|
2101
|
+
if (state.anchor !== null) {
|
|
2102
|
+
state.anchorMap[state.anchor] = state.result;
|
|
2103
|
+
}
|
|
2104
|
+
}
|
|
2105
|
+
} else if (indentStatus === 0) {
|
|
2106
|
+
hasContent = allowBlockCollections && readBlockSequence(state, blockIndent);
|
|
2107
|
+
}
|
|
2108
|
+
}
|
|
2109
|
+
if (state.tag === null) {
|
|
2110
|
+
if (state.anchor !== null) {
|
|
2111
|
+
state.anchorMap[state.anchor] = state.result;
|
|
2112
|
+
}
|
|
2113
|
+
} else if (state.tag === "?") {
|
|
2114
|
+
if (state.result !== null && state.kind !== "scalar") {
|
|
2115
|
+
throwError(state, 'unacceptable node kind for !<?> tag; it should be "scalar", not "' + state.kind + '"');
|
|
2116
|
+
}
|
|
2117
|
+
for (typeIndex = 0, typeQuantity = state.implicitTypes.length;typeIndex < typeQuantity; typeIndex += 1) {
|
|
2118
|
+
type2 = state.implicitTypes[typeIndex];
|
|
2119
|
+
if (type2.resolve(state.result)) {
|
|
2120
|
+
state.result = type2.construct(state.result);
|
|
2121
|
+
state.tag = type2.tag;
|
|
2122
|
+
if (state.anchor !== null) {
|
|
2123
|
+
state.anchorMap[state.anchor] = state.result;
|
|
2124
|
+
}
|
|
2125
|
+
break;
|
|
2126
|
+
}
|
|
2127
|
+
}
|
|
2128
|
+
} else if (state.tag !== "!") {
|
|
2129
|
+
if (_hasOwnProperty$1.call(state.typeMap[state.kind || "fallback"], state.tag)) {
|
|
2130
|
+
type2 = state.typeMap[state.kind || "fallback"][state.tag];
|
|
2131
|
+
} else {
|
|
2132
|
+
type2 = null;
|
|
2133
|
+
typeList = state.typeMap.multi[state.kind || "fallback"];
|
|
2134
|
+
for (typeIndex = 0, typeQuantity = typeList.length;typeIndex < typeQuantity; typeIndex += 1) {
|
|
2135
|
+
if (state.tag.slice(0, typeList[typeIndex].tag.length) === typeList[typeIndex].tag) {
|
|
2136
|
+
type2 = typeList[typeIndex];
|
|
2137
|
+
break;
|
|
2138
|
+
}
|
|
2139
|
+
}
|
|
2140
|
+
}
|
|
2141
|
+
if (!type2) {
|
|
2142
|
+
throwError(state, "unknown tag !<" + state.tag + ">");
|
|
2143
|
+
}
|
|
2144
|
+
if (state.result !== null && type2.kind !== state.kind) {
|
|
2145
|
+
throwError(state, "unacceptable node kind for !<" + state.tag + '> tag; it should be "' + type2.kind + '", not "' + state.kind + '"');
|
|
2146
|
+
}
|
|
2147
|
+
if (!type2.resolve(state.result, state.tag)) {
|
|
2148
|
+
throwError(state, "cannot resolve a node with !<" + state.tag + "> explicit tag");
|
|
2149
|
+
} else {
|
|
2150
|
+
state.result = type2.construct(state.result, state.tag);
|
|
2151
|
+
if (state.anchor !== null) {
|
|
2152
|
+
state.anchorMap[state.anchor] = state.result;
|
|
2153
|
+
}
|
|
2154
|
+
}
|
|
2155
|
+
}
|
|
2156
|
+
if (state.listener !== null) {
|
|
2157
|
+
state.listener("close", state);
|
|
2158
|
+
}
|
|
2159
|
+
return state.tag !== null || state.anchor !== null || hasContent;
|
|
2160
|
+
}
|
|
2161
|
+
function readDocument(state) {
|
|
2162
|
+
var documentStart = state.position, _position, directiveName, directiveArgs, hasDirectives = false, ch;
|
|
2163
|
+
state.version = null;
|
|
2164
|
+
state.checkLineBreaks = state.legacy;
|
|
2165
|
+
state.tagMap = Object.create(null);
|
|
2166
|
+
state.anchorMap = Object.create(null);
|
|
2167
|
+
while ((ch = state.input.charCodeAt(state.position)) !== 0) {
|
|
2168
|
+
skipSeparationSpace(state, true, -1);
|
|
2169
|
+
ch = state.input.charCodeAt(state.position);
|
|
2170
|
+
if (state.lineIndent > 0 || ch !== 37) {
|
|
2171
|
+
break;
|
|
2172
|
+
}
|
|
2173
|
+
hasDirectives = true;
|
|
2174
|
+
ch = state.input.charCodeAt(++state.position);
|
|
2175
|
+
_position = state.position;
|
|
2176
|
+
while (ch !== 0 && !is_WS_OR_EOL(ch)) {
|
|
2177
|
+
ch = state.input.charCodeAt(++state.position);
|
|
2178
|
+
}
|
|
2179
|
+
directiveName = state.input.slice(_position, state.position);
|
|
2180
|
+
directiveArgs = [];
|
|
2181
|
+
if (directiveName.length < 1) {
|
|
2182
|
+
throwError(state, "directive name must not be less than one character in length");
|
|
2183
|
+
}
|
|
2184
|
+
while (ch !== 0) {
|
|
2185
|
+
while (is_WHITE_SPACE(ch)) {
|
|
2186
|
+
ch = state.input.charCodeAt(++state.position);
|
|
2187
|
+
}
|
|
2188
|
+
if (ch === 35) {
|
|
2189
|
+
do {
|
|
2190
|
+
ch = state.input.charCodeAt(++state.position);
|
|
2191
|
+
} while (ch !== 0 && !is_EOL(ch));
|
|
2192
|
+
break;
|
|
2193
|
+
}
|
|
2194
|
+
if (is_EOL(ch))
|
|
2195
|
+
break;
|
|
2196
|
+
_position = state.position;
|
|
2197
|
+
while (ch !== 0 && !is_WS_OR_EOL(ch)) {
|
|
2198
|
+
ch = state.input.charCodeAt(++state.position);
|
|
2199
|
+
}
|
|
2200
|
+
directiveArgs.push(state.input.slice(_position, state.position));
|
|
2201
|
+
}
|
|
2202
|
+
if (ch !== 0)
|
|
2203
|
+
readLineBreak(state);
|
|
2204
|
+
if (_hasOwnProperty$1.call(directiveHandlers, directiveName)) {
|
|
2205
|
+
directiveHandlers[directiveName](state, directiveName, directiveArgs);
|
|
2206
|
+
} else {
|
|
2207
|
+
throwWarning(state, 'unknown document directive "' + directiveName + '"');
|
|
2208
|
+
}
|
|
2209
|
+
}
|
|
2210
|
+
skipSeparationSpace(state, true, -1);
|
|
2211
|
+
if (state.lineIndent === 0 && state.input.charCodeAt(state.position) === 45 && state.input.charCodeAt(state.position + 1) === 45 && state.input.charCodeAt(state.position + 2) === 45) {
|
|
2212
|
+
state.position += 3;
|
|
2213
|
+
skipSeparationSpace(state, true, -1);
|
|
2214
|
+
} else if (hasDirectives) {
|
|
2215
|
+
throwError(state, "directives end mark is expected");
|
|
2216
|
+
}
|
|
2217
|
+
composeNode(state, state.lineIndent - 1, CONTEXT_BLOCK_OUT, false, true);
|
|
2218
|
+
skipSeparationSpace(state, true, -1);
|
|
2219
|
+
if (state.checkLineBreaks && PATTERN_NON_ASCII_LINE_BREAKS.test(state.input.slice(documentStart, state.position))) {
|
|
2220
|
+
throwWarning(state, "non-ASCII line breaks are interpreted as content");
|
|
2221
|
+
}
|
|
2222
|
+
state.documents.push(state.result);
|
|
2223
|
+
if (state.position === state.lineStart && testDocumentSeparator(state)) {
|
|
2224
|
+
if (state.input.charCodeAt(state.position) === 46) {
|
|
2225
|
+
state.position += 3;
|
|
2226
|
+
skipSeparationSpace(state, true, -1);
|
|
2227
|
+
}
|
|
2228
|
+
return;
|
|
2229
|
+
}
|
|
2230
|
+
if (state.position < state.length - 1) {
|
|
2231
|
+
throwError(state, "end of the stream or a document separator is expected");
|
|
2232
|
+
} else {
|
|
2233
|
+
return;
|
|
2234
|
+
}
|
|
2235
|
+
}
|
|
2236
|
+
function loadDocuments(input, options) {
|
|
2237
|
+
input = String(input);
|
|
2238
|
+
options = options || {};
|
|
2239
|
+
if (input.length !== 0) {
|
|
2240
|
+
if (input.charCodeAt(input.length - 1) !== 10 && input.charCodeAt(input.length - 1) !== 13) {
|
|
2241
|
+
input += `
|
|
2242
|
+
`;
|
|
2243
|
+
}
|
|
2244
|
+
if (input.charCodeAt(0) === 65279) {
|
|
2245
|
+
input = input.slice(1);
|
|
2246
|
+
}
|
|
2247
|
+
}
|
|
2248
|
+
var state = new State$1(input, options);
|
|
2249
|
+
var nullpos = input.indexOf("\x00");
|
|
2250
|
+
if (nullpos !== -1) {
|
|
2251
|
+
state.position = nullpos;
|
|
2252
|
+
throwError(state, "null byte is not allowed in input");
|
|
2253
|
+
}
|
|
2254
|
+
state.input += "\x00";
|
|
2255
|
+
while (state.input.charCodeAt(state.position) === 32) {
|
|
2256
|
+
state.lineIndent += 1;
|
|
2257
|
+
state.position += 1;
|
|
2258
|
+
}
|
|
2259
|
+
while (state.position < state.length - 1) {
|
|
2260
|
+
readDocument(state);
|
|
2261
|
+
}
|
|
2262
|
+
return state.documents;
|
|
2263
|
+
}
|
|
2264
|
+
function loadAll$1(input, iterator, options) {
|
|
2265
|
+
if (iterator !== null && typeof iterator === "object" && typeof options === "undefined") {
|
|
2266
|
+
options = iterator;
|
|
2267
|
+
iterator = null;
|
|
2268
|
+
}
|
|
2269
|
+
var documents = loadDocuments(input, options);
|
|
2270
|
+
if (typeof iterator !== "function") {
|
|
2271
|
+
return documents;
|
|
2272
|
+
}
|
|
2273
|
+
for (var index = 0, length = documents.length;index < length; index += 1) {
|
|
2274
|
+
iterator(documents[index]);
|
|
2275
|
+
}
|
|
2276
|
+
}
|
|
2277
|
+
function load$1(input, options) {
|
|
2278
|
+
var documents = loadDocuments(input, options);
|
|
2279
|
+
if (documents.length === 0) {
|
|
2280
|
+
return;
|
|
2281
|
+
} else if (documents.length === 1) {
|
|
2282
|
+
return documents[0];
|
|
2283
|
+
}
|
|
2284
|
+
throw new exception("expected a single document in the stream, but found more");
|
|
2285
|
+
}
|
|
2286
|
+
var loadAll_1 = loadAll$1;
|
|
2287
|
+
var load_1 = load$1;
|
|
2288
|
+
var loader = {
|
|
2289
|
+
loadAll: loadAll_1,
|
|
2290
|
+
load: load_1
|
|
2291
|
+
};
|
|
2292
|
+
var _toString = Object.prototype.toString;
|
|
2293
|
+
var _hasOwnProperty = Object.prototype.hasOwnProperty;
|
|
2294
|
+
var CHAR_BOM = 65279;
|
|
2295
|
+
var CHAR_TAB = 9;
|
|
2296
|
+
var CHAR_LINE_FEED = 10;
|
|
2297
|
+
var CHAR_CARRIAGE_RETURN = 13;
|
|
2298
|
+
var CHAR_SPACE = 32;
|
|
2299
|
+
var CHAR_EXCLAMATION = 33;
|
|
2300
|
+
var CHAR_DOUBLE_QUOTE = 34;
|
|
2301
|
+
var CHAR_SHARP = 35;
|
|
2302
|
+
var CHAR_PERCENT = 37;
|
|
2303
|
+
var CHAR_AMPERSAND = 38;
|
|
2304
|
+
var CHAR_SINGLE_QUOTE = 39;
|
|
2305
|
+
var CHAR_ASTERISK = 42;
|
|
2306
|
+
var CHAR_COMMA = 44;
|
|
2307
|
+
var CHAR_MINUS = 45;
|
|
2308
|
+
var CHAR_COLON = 58;
|
|
2309
|
+
var CHAR_EQUALS = 61;
|
|
2310
|
+
var CHAR_GREATER_THAN = 62;
|
|
2311
|
+
var CHAR_QUESTION = 63;
|
|
2312
|
+
var CHAR_COMMERCIAL_AT = 64;
|
|
2313
|
+
var CHAR_LEFT_SQUARE_BRACKET = 91;
|
|
2314
|
+
var CHAR_RIGHT_SQUARE_BRACKET = 93;
|
|
2315
|
+
var CHAR_GRAVE_ACCENT = 96;
|
|
2316
|
+
var CHAR_LEFT_CURLY_BRACKET = 123;
|
|
2317
|
+
var CHAR_VERTICAL_LINE = 124;
|
|
2318
|
+
var CHAR_RIGHT_CURLY_BRACKET = 125;
|
|
2319
|
+
var ESCAPE_SEQUENCES = {};
|
|
2320
|
+
ESCAPE_SEQUENCES[0] = "\\0";
|
|
2321
|
+
ESCAPE_SEQUENCES[7] = "\\a";
|
|
2322
|
+
ESCAPE_SEQUENCES[8] = "\\b";
|
|
2323
|
+
ESCAPE_SEQUENCES[9] = "\\t";
|
|
2324
|
+
ESCAPE_SEQUENCES[10] = "\\n";
|
|
2325
|
+
ESCAPE_SEQUENCES[11] = "\\v";
|
|
2326
|
+
ESCAPE_SEQUENCES[12] = "\\f";
|
|
2327
|
+
ESCAPE_SEQUENCES[13] = "\\r";
|
|
2328
|
+
ESCAPE_SEQUENCES[27] = "\\e";
|
|
2329
|
+
ESCAPE_SEQUENCES[34] = "\\\"";
|
|
2330
|
+
ESCAPE_SEQUENCES[92] = "\\\\";
|
|
2331
|
+
ESCAPE_SEQUENCES[133] = "\\N";
|
|
2332
|
+
ESCAPE_SEQUENCES[160] = "\\_";
|
|
2333
|
+
ESCAPE_SEQUENCES[8232] = "\\L";
|
|
2334
|
+
ESCAPE_SEQUENCES[8233] = "\\P";
|
|
2335
|
+
var DEPRECATED_BOOLEANS_SYNTAX = [
|
|
2336
|
+
"y",
|
|
2337
|
+
"Y",
|
|
2338
|
+
"yes",
|
|
2339
|
+
"Yes",
|
|
2340
|
+
"YES",
|
|
2341
|
+
"on",
|
|
2342
|
+
"On",
|
|
2343
|
+
"ON",
|
|
2344
|
+
"n",
|
|
2345
|
+
"N",
|
|
2346
|
+
"no",
|
|
2347
|
+
"No",
|
|
2348
|
+
"NO",
|
|
2349
|
+
"off",
|
|
2350
|
+
"Off",
|
|
2351
|
+
"OFF"
|
|
2352
|
+
];
|
|
2353
|
+
var DEPRECATED_BASE60_SYNTAX = /^[-+]?[0-9_]+(?::[0-9_]+)+(?:\.[0-9_]*)?$/;
|
|
2354
|
+
function compileStyleMap(schema2, map2) {
|
|
2355
|
+
var result, keys, index, length, tag, style, type2;
|
|
2356
|
+
if (map2 === null)
|
|
2357
|
+
return {};
|
|
2358
|
+
result = {};
|
|
2359
|
+
keys = Object.keys(map2);
|
|
2360
|
+
for (index = 0, length = keys.length;index < length; index += 1) {
|
|
2361
|
+
tag = keys[index];
|
|
2362
|
+
style = String(map2[tag]);
|
|
2363
|
+
if (tag.slice(0, 2) === "!!") {
|
|
2364
|
+
tag = "tag:yaml.org,2002:" + tag.slice(2);
|
|
2365
|
+
}
|
|
2366
|
+
type2 = schema2.compiledTypeMap["fallback"][tag];
|
|
2367
|
+
if (type2 && _hasOwnProperty.call(type2.styleAliases, style)) {
|
|
2368
|
+
style = type2.styleAliases[style];
|
|
2369
|
+
}
|
|
2370
|
+
result[tag] = style;
|
|
2371
|
+
}
|
|
2372
|
+
return result;
|
|
2373
|
+
}
|
|
2374
|
+
function encodeHex(character) {
|
|
2375
|
+
var string, handle, length;
|
|
2376
|
+
string = character.toString(16).toUpperCase();
|
|
2377
|
+
if (character <= 255) {
|
|
2378
|
+
handle = "x";
|
|
2379
|
+
length = 2;
|
|
2380
|
+
} else if (character <= 65535) {
|
|
2381
|
+
handle = "u";
|
|
2382
|
+
length = 4;
|
|
2383
|
+
} else if (character <= 4294967295) {
|
|
2384
|
+
handle = "U";
|
|
2385
|
+
length = 8;
|
|
2386
|
+
} else {
|
|
2387
|
+
throw new exception("code point within a string may not be greater than 0xFFFFFFFF");
|
|
2388
|
+
}
|
|
2389
|
+
return "\\" + handle + common.repeat("0", length - string.length) + string;
|
|
2390
|
+
}
|
|
2391
|
+
var QUOTING_TYPE_SINGLE = 1;
|
|
2392
|
+
var QUOTING_TYPE_DOUBLE = 2;
|
|
2393
|
+
function State(options) {
|
|
2394
|
+
this.schema = options["schema"] || _default;
|
|
2395
|
+
this.indent = Math.max(1, options["indent"] || 2);
|
|
2396
|
+
this.noArrayIndent = options["noArrayIndent"] || false;
|
|
2397
|
+
this.skipInvalid = options["skipInvalid"] || false;
|
|
2398
|
+
this.flowLevel = common.isNothing(options["flowLevel"]) ? -1 : options["flowLevel"];
|
|
2399
|
+
this.styleMap = compileStyleMap(this.schema, options["styles"] || null);
|
|
2400
|
+
this.sortKeys = options["sortKeys"] || false;
|
|
2401
|
+
this.lineWidth = options["lineWidth"] || 80;
|
|
2402
|
+
this.noRefs = options["noRefs"] || false;
|
|
2403
|
+
this.noCompatMode = options["noCompatMode"] || false;
|
|
2404
|
+
this.condenseFlow = options["condenseFlow"] || false;
|
|
2405
|
+
this.quotingType = options["quotingType"] === '"' ? QUOTING_TYPE_DOUBLE : QUOTING_TYPE_SINGLE;
|
|
2406
|
+
this.forceQuotes = options["forceQuotes"] || false;
|
|
2407
|
+
this.replacer = typeof options["replacer"] === "function" ? options["replacer"] : null;
|
|
2408
|
+
this.implicitTypes = this.schema.compiledImplicit;
|
|
2409
|
+
this.explicitTypes = this.schema.compiledExplicit;
|
|
2410
|
+
this.tag = null;
|
|
2411
|
+
this.result = "";
|
|
2412
|
+
this.duplicates = [];
|
|
2413
|
+
this.usedDuplicates = null;
|
|
2414
|
+
}
|
|
2415
|
+
function indentString(string, spaces) {
|
|
2416
|
+
var ind = common.repeat(" ", spaces), position = 0, next = -1, result = "", line, length = string.length;
|
|
2417
|
+
while (position < length) {
|
|
2418
|
+
next = string.indexOf(`
|
|
2419
|
+
`, position);
|
|
2420
|
+
if (next === -1) {
|
|
2421
|
+
line = string.slice(position);
|
|
2422
|
+
position = length;
|
|
2423
|
+
} else {
|
|
2424
|
+
line = string.slice(position, next + 1);
|
|
2425
|
+
position = next + 1;
|
|
2426
|
+
}
|
|
2427
|
+
if (line.length && line !== `
|
|
2428
|
+
`)
|
|
2429
|
+
result += ind;
|
|
2430
|
+
result += line;
|
|
2431
|
+
}
|
|
2432
|
+
return result;
|
|
2433
|
+
}
|
|
2434
|
+
function generateNextLine(state, level) {
|
|
2435
|
+
return `
|
|
2436
|
+
` + common.repeat(" ", state.indent * level);
|
|
2437
|
+
}
|
|
2438
|
+
function testImplicitResolving(state, str2) {
|
|
2439
|
+
var index, length, type2;
|
|
2440
|
+
for (index = 0, length = state.implicitTypes.length;index < length; index += 1) {
|
|
2441
|
+
type2 = state.implicitTypes[index];
|
|
2442
|
+
if (type2.resolve(str2)) {
|
|
2443
|
+
return true;
|
|
2444
|
+
}
|
|
2445
|
+
}
|
|
2446
|
+
return false;
|
|
2447
|
+
}
|
|
2448
|
+
function isWhitespace(c) {
|
|
2449
|
+
return c === CHAR_SPACE || c === CHAR_TAB;
|
|
2450
|
+
}
|
|
2451
|
+
function isPrintable(c) {
|
|
2452
|
+
return 32 <= c && c <= 126 || 161 <= c && c <= 55295 && c !== 8232 && c !== 8233 || 57344 <= c && c <= 65533 && c !== CHAR_BOM || 65536 <= c && c <= 1114111;
|
|
2453
|
+
}
|
|
2454
|
+
function isNsCharOrWhitespace(c) {
|
|
2455
|
+
return isPrintable(c) && c !== CHAR_BOM && c !== CHAR_CARRIAGE_RETURN && c !== CHAR_LINE_FEED;
|
|
2456
|
+
}
|
|
2457
|
+
function isPlainSafe(c, prev, inblock) {
|
|
2458
|
+
var cIsNsCharOrWhitespace = isNsCharOrWhitespace(c);
|
|
2459
|
+
var cIsNsChar = cIsNsCharOrWhitespace && !isWhitespace(c);
|
|
2460
|
+
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;
|
|
2461
|
+
}
|
|
2462
|
+
function isPlainSafeFirst(c) {
|
|
2463
|
+
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;
|
|
2464
|
+
}
|
|
2465
|
+
function isPlainSafeLast(c) {
|
|
2466
|
+
return !isWhitespace(c) && c !== CHAR_COLON;
|
|
2467
|
+
}
|
|
2468
|
+
function codePointAt(string, pos) {
|
|
2469
|
+
var first = string.charCodeAt(pos), second;
|
|
2470
|
+
if (first >= 55296 && first <= 56319 && pos + 1 < string.length) {
|
|
2471
|
+
second = string.charCodeAt(pos + 1);
|
|
2472
|
+
if (second >= 56320 && second <= 57343) {
|
|
2473
|
+
return (first - 55296) * 1024 + second - 56320 + 65536;
|
|
2474
|
+
}
|
|
2475
|
+
}
|
|
2476
|
+
return first;
|
|
2477
|
+
}
|
|
2478
|
+
function needIndentIndicator(string) {
|
|
2479
|
+
var leadingSpaceRe = /^\n* /;
|
|
2480
|
+
return leadingSpaceRe.test(string);
|
|
2481
|
+
}
|
|
2482
|
+
var STYLE_PLAIN = 1;
|
|
2483
|
+
var STYLE_SINGLE = 2;
|
|
2484
|
+
var STYLE_LITERAL = 3;
|
|
2485
|
+
var STYLE_FOLDED = 4;
|
|
2486
|
+
var STYLE_DOUBLE = 5;
|
|
2487
|
+
function chooseScalarStyle(string, singleLineOnly, indentPerLevel, lineWidth, testAmbiguousType, quotingType, forceQuotes, inblock) {
|
|
2488
|
+
var i2;
|
|
2489
|
+
var char = 0;
|
|
2490
|
+
var prevChar = null;
|
|
2491
|
+
var hasLineBreak = false;
|
|
2492
|
+
var hasFoldableLine = false;
|
|
2493
|
+
var shouldTrackWidth = lineWidth !== -1;
|
|
2494
|
+
var previousLineBreak = -1;
|
|
2495
|
+
var plain = isPlainSafeFirst(codePointAt(string, 0)) && isPlainSafeLast(codePointAt(string, string.length - 1));
|
|
2496
|
+
if (singleLineOnly || forceQuotes) {
|
|
2497
|
+
for (i2 = 0;i2 < string.length; char >= 65536 ? i2 += 2 : i2++) {
|
|
2498
|
+
char = codePointAt(string, i2);
|
|
2499
|
+
if (!isPrintable(char)) {
|
|
2500
|
+
return STYLE_DOUBLE;
|
|
2501
|
+
}
|
|
2502
|
+
plain = plain && isPlainSafe(char, prevChar, inblock);
|
|
2503
|
+
prevChar = char;
|
|
2504
|
+
}
|
|
2505
|
+
} else {
|
|
2506
|
+
for (i2 = 0;i2 < string.length; char >= 65536 ? i2 += 2 : i2++) {
|
|
2507
|
+
char = codePointAt(string, i2);
|
|
2508
|
+
if (char === CHAR_LINE_FEED) {
|
|
2509
|
+
hasLineBreak = true;
|
|
2510
|
+
if (shouldTrackWidth) {
|
|
2511
|
+
hasFoldableLine = hasFoldableLine || i2 - previousLineBreak - 1 > lineWidth && string[previousLineBreak + 1] !== " ";
|
|
2512
|
+
previousLineBreak = i2;
|
|
2513
|
+
}
|
|
2514
|
+
} else if (!isPrintable(char)) {
|
|
2515
|
+
return STYLE_DOUBLE;
|
|
2516
|
+
}
|
|
2517
|
+
plain = plain && isPlainSafe(char, prevChar, inblock);
|
|
2518
|
+
prevChar = char;
|
|
2519
|
+
}
|
|
2520
|
+
hasFoldableLine = hasFoldableLine || shouldTrackWidth && (i2 - previousLineBreak - 1 > lineWidth && string[previousLineBreak + 1] !== " ");
|
|
2521
|
+
}
|
|
2522
|
+
if (!hasLineBreak && !hasFoldableLine) {
|
|
2523
|
+
if (plain && !forceQuotes && !testAmbiguousType(string)) {
|
|
2524
|
+
return STYLE_PLAIN;
|
|
2525
|
+
}
|
|
2526
|
+
return quotingType === QUOTING_TYPE_DOUBLE ? STYLE_DOUBLE : STYLE_SINGLE;
|
|
2527
|
+
}
|
|
2528
|
+
if (indentPerLevel > 9 && needIndentIndicator(string)) {
|
|
2529
|
+
return STYLE_DOUBLE;
|
|
2530
|
+
}
|
|
2531
|
+
if (!forceQuotes) {
|
|
2532
|
+
return hasFoldableLine ? STYLE_FOLDED : STYLE_LITERAL;
|
|
2533
|
+
}
|
|
2534
|
+
return quotingType === QUOTING_TYPE_DOUBLE ? STYLE_DOUBLE : STYLE_SINGLE;
|
|
2535
|
+
}
|
|
2536
|
+
function writeScalar(state, string, level, iskey, inblock) {
|
|
2537
|
+
state.dump = function() {
|
|
2538
|
+
if (string.length === 0) {
|
|
2539
|
+
return state.quotingType === QUOTING_TYPE_DOUBLE ? '""' : "''";
|
|
2540
|
+
}
|
|
2541
|
+
if (!state.noCompatMode) {
|
|
2542
|
+
if (DEPRECATED_BOOLEANS_SYNTAX.indexOf(string) !== -1 || DEPRECATED_BASE60_SYNTAX.test(string)) {
|
|
2543
|
+
return state.quotingType === QUOTING_TYPE_DOUBLE ? '"' + string + '"' : "'" + string + "'";
|
|
2544
|
+
}
|
|
2545
|
+
}
|
|
2546
|
+
var indent = state.indent * Math.max(1, level);
|
|
2547
|
+
var lineWidth = state.lineWidth === -1 ? -1 : Math.max(Math.min(state.lineWidth, 40), state.lineWidth - indent);
|
|
2548
|
+
var singleLineOnly = iskey || state.flowLevel > -1 && level >= state.flowLevel;
|
|
2549
|
+
function testAmbiguity(string2) {
|
|
2550
|
+
return testImplicitResolving(state, string2);
|
|
2551
|
+
}
|
|
2552
|
+
switch (chooseScalarStyle(string, singleLineOnly, state.indent, lineWidth, testAmbiguity, state.quotingType, state.forceQuotes && !iskey, inblock)) {
|
|
2553
|
+
case STYLE_PLAIN:
|
|
2554
|
+
return string;
|
|
2555
|
+
case STYLE_SINGLE:
|
|
2556
|
+
return "'" + string.replace(/'/g, "''") + "'";
|
|
2557
|
+
case STYLE_LITERAL:
|
|
2558
|
+
return "|" + blockHeader(string, state.indent) + dropEndingNewline(indentString(string, indent));
|
|
2559
|
+
case STYLE_FOLDED:
|
|
2560
|
+
return ">" + blockHeader(string, state.indent) + dropEndingNewline(indentString(foldString(string, lineWidth), indent));
|
|
2561
|
+
case STYLE_DOUBLE:
|
|
2562
|
+
return '"' + escapeString(string) + '"';
|
|
2563
|
+
default:
|
|
2564
|
+
throw new exception("impossible error: invalid scalar style");
|
|
2565
|
+
}
|
|
2566
|
+
}();
|
|
2567
|
+
}
|
|
2568
|
+
function blockHeader(string, indentPerLevel) {
|
|
2569
|
+
var indentIndicator = needIndentIndicator(string) ? String(indentPerLevel) : "";
|
|
2570
|
+
var clip = string[string.length - 1] === `
|
|
2571
|
+
`;
|
|
2572
|
+
var keep = clip && (string[string.length - 2] === `
|
|
2573
|
+
` || string === `
|
|
2574
|
+
`);
|
|
2575
|
+
var chomp = keep ? "+" : clip ? "" : "-";
|
|
2576
|
+
return indentIndicator + chomp + `
|
|
2577
|
+
`;
|
|
2578
|
+
}
|
|
2579
|
+
function dropEndingNewline(string) {
|
|
2580
|
+
return string[string.length - 1] === `
|
|
2581
|
+
` ? string.slice(0, -1) : string;
|
|
2582
|
+
}
|
|
2583
|
+
function foldString(string, width) {
|
|
2584
|
+
var lineRe = /(\n+)([^\n]*)/g;
|
|
2585
|
+
var result = function() {
|
|
2586
|
+
var nextLF = string.indexOf(`
|
|
2587
|
+
`);
|
|
2588
|
+
nextLF = nextLF !== -1 ? nextLF : string.length;
|
|
2589
|
+
lineRe.lastIndex = nextLF;
|
|
2590
|
+
return foldLine(string.slice(0, nextLF), width);
|
|
2591
|
+
}();
|
|
2592
|
+
var prevMoreIndented = string[0] === `
|
|
2593
|
+
` || string[0] === " ";
|
|
2594
|
+
var moreIndented;
|
|
2595
|
+
var match;
|
|
2596
|
+
while (match = lineRe.exec(string)) {
|
|
2597
|
+
var prefix = match[1], line = match[2];
|
|
2598
|
+
moreIndented = line[0] === " ";
|
|
2599
|
+
result += prefix + (!prevMoreIndented && !moreIndented && line !== "" ? `
|
|
2600
|
+
` : "") + foldLine(line, width);
|
|
2601
|
+
prevMoreIndented = moreIndented;
|
|
2602
|
+
}
|
|
2603
|
+
return result;
|
|
2604
|
+
}
|
|
2605
|
+
function foldLine(line, width) {
|
|
2606
|
+
if (line === "" || line[0] === " ")
|
|
2607
|
+
return line;
|
|
2608
|
+
var breakRe = / [^ ]/g;
|
|
2609
|
+
var match;
|
|
2610
|
+
var start = 0, end, curr = 0, next = 0;
|
|
2611
|
+
var result = "";
|
|
2612
|
+
while (match = breakRe.exec(line)) {
|
|
2613
|
+
next = match.index;
|
|
2614
|
+
if (next - start > width) {
|
|
2615
|
+
end = curr > start ? curr : next;
|
|
2616
|
+
result += `
|
|
2617
|
+
` + line.slice(start, end);
|
|
2618
|
+
start = end + 1;
|
|
2619
|
+
}
|
|
2620
|
+
curr = next;
|
|
2621
|
+
}
|
|
2622
|
+
result += `
|
|
2623
|
+
`;
|
|
2624
|
+
if (line.length - start > width && curr > start) {
|
|
2625
|
+
result += line.slice(start, curr) + `
|
|
2626
|
+
` + line.slice(curr + 1);
|
|
2627
|
+
} else {
|
|
2628
|
+
result += line.slice(start);
|
|
2629
|
+
}
|
|
2630
|
+
return result.slice(1);
|
|
2631
|
+
}
|
|
2632
|
+
function escapeString(string) {
|
|
2633
|
+
var result = "";
|
|
2634
|
+
var char = 0;
|
|
2635
|
+
var escapeSeq;
|
|
2636
|
+
for (var i2 = 0;i2 < string.length; char >= 65536 ? i2 += 2 : i2++) {
|
|
2637
|
+
char = codePointAt(string, i2);
|
|
2638
|
+
escapeSeq = ESCAPE_SEQUENCES[char];
|
|
2639
|
+
if (!escapeSeq && isPrintable(char)) {
|
|
2640
|
+
result += string[i2];
|
|
2641
|
+
if (char >= 65536)
|
|
2642
|
+
result += string[i2 + 1];
|
|
2643
|
+
} else {
|
|
2644
|
+
result += escapeSeq || encodeHex(char);
|
|
2645
|
+
}
|
|
2646
|
+
}
|
|
2647
|
+
return result;
|
|
2648
|
+
}
|
|
2649
|
+
function writeFlowSequence(state, level, object) {
|
|
2650
|
+
var _result = "", _tag = state.tag, index, length, value;
|
|
2651
|
+
for (index = 0, length = object.length;index < length; index += 1) {
|
|
2652
|
+
value = object[index];
|
|
2653
|
+
if (state.replacer) {
|
|
2654
|
+
value = state.replacer.call(object, String(index), value);
|
|
2655
|
+
}
|
|
2656
|
+
if (writeNode(state, level, value, false, false) || typeof value === "undefined" && writeNode(state, level, null, false, false)) {
|
|
2657
|
+
if (_result !== "")
|
|
2658
|
+
_result += "," + (!state.condenseFlow ? " " : "");
|
|
2659
|
+
_result += state.dump;
|
|
2660
|
+
}
|
|
2661
|
+
}
|
|
2662
|
+
state.tag = _tag;
|
|
2663
|
+
state.dump = "[" + _result + "]";
|
|
2664
|
+
}
|
|
2665
|
+
function writeBlockSequence(state, level, object, compact) {
|
|
2666
|
+
var _result = "", _tag = state.tag, index, length, value;
|
|
2667
|
+
for (index = 0, length = object.length;index < length; index += 1) {
|
|
2668
|
+
value = object[index];
|
|
2669
|
+
if (state.replacer) {
|
|
2670
|
+
value = state.replacer.call(object, String(index), value);
|
|
2671
|
+
}
|
|
2672
|
+
if (writeNode(state, level + 1, value, true, true, false, true) || typeof value === "undefined" && writeNode(state, level + 1, null, true, true, false, true)) {
|
|
2673
|
+
if (!compact || _result !== "") {
|
|
2674
|
+
_result += generateNextLine(state, level);
|
|
2675
|
+
}
|
|
2676
|
+
if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) {
|
|
2677
|
+
_result += "-";
|
|
2678
|
+
} else {
|
|
2679
|
+
_result += "- ";
|
|
2680
|
+
}
|
|
2681
|
+
_result += state.dump;
|
|
2682
|
+
}
|
|
2683
|
+
}
|
|
2684
|
+
state.tag = _tag;
|
|
2685
|
+
state.dump = _result || "[]";
|
|
2686
|
+
}
|
|
2687
|
+
function writeFlowMapping(state, level, object) {
|
|
2688
|
+
var _result = "", _tag = state.tag, objectKeyList = Object.keys(object), index, length, objectKey, objectValue, pairBuffer;
|
|
2689
|
+
for (index = 0, length = objectKeyList.length;index < length; index += 1) {
|
|
2690
|
+
pairBuffer = "";
|
|
2691
|
+
if (_result !== "")
|
|
2692
|
+
pairBuffer += ", ";
|
|
2693
|
+
if (state.condenseFlow)
|
|
2694
|
+
pairBuffer += '"';
|
|
2695
|
+
objectKey = objectKeyList[index];
|
|
2696
|
+
objectValue = object[objectKey];
|
|
2697
|
+
if (state.replacer) {
|
|
2698
|
+
objectValue = state.replacer.call(object, objectKey, objectValue);
|
|
2699
|
+
}
|
|
2700
|
+
if (!writeNode(state, level, objectKey, false, false)) {
|
|
2701
|
+
continue;
|
|
2702
|
+
}
|
|
2703
|
+
if (state.dump.length > 1024)
|
|
2704
|
+
pairBuffer += "? ";
|
|
2705
|
+
pairBuffer += state.dump + (state.condenseFlow ? '"' : "") + ":" + (state.condenseFlow ? "" : " ");
|
|
2706
|
+
if (!writeNode(state, level, objectValue, false, false)) {
|
|
2707
|
+
continue;
|
|
2708
|
+
}
|
|
2709
|
+
pairBuffer += state.dump;
|
|
2710
|
+
_result += pairBuffer;
|
|
2711
|
+
}
|
|
2712
|
+
state.tag = _tag;
|
|
2713
|
+
state.dump = "{" + _result + "}";
|
|
2714
|
+
}
|
|
2715
|
+
function writeBlockMapping(state, level, object, compact) {
|
|
2716
|
+
var _result = "", _tag = state.tag, objectKeyList = Object.keys(object), index, length, objectKey, objectValue, explicitPair, pairBuffer;
|
|
2717
|
+
if (state.sortKeys === true) {
|
|
2718
|
+
objectKeyList.sort();
|
|
2719
|
+
} else if (typeof state.sortKeys === "function") {
|
|
2720
|
+
objectKeyList.sort(state.sortKeys);
|
|
2721
|
+
} else if (state.sortKeys) {
|
|
2722
|
+
throw new exception("sortKeys must be a boolean or a function");
|
|
2723
|
+
}
|
|
2724
|
+
for (index = 0, length = objectKeyList.length;index < length; index += 1) {
|
|
2725
|
+
pairBuffer = "";
|
|
2726
|
+
if (!compact || _result !== "") {
|
|
2727
|
+
pairBuffer += generateNextLine(state, level);
|
|
2728
|
+
}
|
|
2729
|
+
objectKey = objectKeyList[index];
|
|
2730
|
+
objectValue = object[objectKey];
|
|
2731
|
+
if (state.replacer) {
|
|
2732
|
+
objectValue = state.replacer.call(object, objectKey, objectValue);
|
|
2733
|
+
}
|
|
2734
|
+
if (!writeNode(state, level + 1, objectKey, true, true, true)) {
|
|
2735
|
+
continue;
|
|
2736
|
+
}
|
|
2737
|
+
explicitPair = state.tag !== null && state.tag !== "?" || state.dump && state.dump.length > 1024;
|
|
2738
|
+
if (explicitPair) {
|
|
2739
|
+
if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) {
|
|
2740
|
+
pairBuffer += "?";
|
|
2741
|
+
} else {
|
|
2742
|
+
pairBuffer += "? ";
|
|
2743
|
+
}
|
|
2744
|
+
}
|
|
2745
|
+
pairBuffer += state.dump;
|
|
2746
|
+
if (explicitPair) {
|
|
2747
|
+
pairBuffer += generateNextLine(state, level);
|
|
2748
|
+
}
|
|
2749
|
+
if (!writeNode(state, level + 1, objectValue, true, explicitPair)) {
|
|
2750
|
+
continue;
|
|
2751
|
+
}
|
|
2752
|
+
if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) {
|
|
2753
|
+
pairBuffer += ":";
|
|
2754
|
+
} else {
|
|
2755
|
+
pairBuffer += ": ";
|
|
2756
|
+
}
|
|
2757
|
+
pairBuffer += state.dump;
|
|
2758
|
+
_result += pairBuffer;
|
|
2759
|
+
}
|
|
2760
|
+
state.tag = _tag;
|
|
2761
|
+
state.dump = _result || "{}";
|
|
2762
|
+
}
|
|
2763
|
+
function detectType(state, object, explicit) {
|
|
2764
|
+
var _result, typeList, index, length, type2, style;
|
|
2765
|
+
typeList = explicit ? state.explicitTypes : state.implicitTypes;
|
|
2766
|
+
for (index = 0, length = typeList.length;index < length; index += 1) {
|
|
2767
|
+
type2 = typeList[index];
|
|
2768
|
+
if ((type2.instanceOf || type2.predicate) && (!type2.instanceOf || typeof object === "object" && object instanceof type2.instanceOf) && (!type2.predicate || type2.predicate(object))) {
|
|
2769
|
+
if (explicit) {
|
|
2770
|
+
if (type2.multi && type2.representName) {
|
|
2771
|
+
state.tag = type2.representName(object);
|
|
2772
|
+
} else {
|
|
2773
|
+
state.tag = type2.tag;
|
|
2774
|
+
}
|
|
2775
|
+
} else {
|
|
2776
|
+
state.tag = "?";
|
|
2777
|
+
}
|
|
2778
|
+
if (type2.represent) {
|
|
2779
|
+
style = state.styleMap[type2.tag] || type2.defaultStyle;
|
|
2780
|
+
if (_toString.call(type2.represent) === "[object Function]") {
|
|
2781
|
+
_result = type2.represent(object, style);
|
|
2782
|
+
} else if (_hasOwnProperty.call(type2.represent, style)) {
|
|
2783
|
+
_result = type2.represent[style](object, style);
|
|
2784
|
+
} else {
|
|
2785
|
+
throw new exception("!<" + type2.tag + '> tag resolver accepts not "' + style + '" style');
|
|
2786
|
+
}
|
|
2787
|
+
state.dump = _result;
|
|
2788
|
+
}
|
|
2789
|
+
return true;
|
|
2790
|
+
}
|
|
2791
|
+
}
|
|
2792
|
+
return false;
|
|
2793
|
+
}
|
|
2794
|
+
function writeNode(state, level, object, block, compact, iskey, isblockseq) {
|
|
2795
|
+
state.tag = null;
|
|
2796
|
+
state.dump = object;
|
|
2797
|
+
if (!detectType(state, object, false)) {
|
|
2798
|
+
detectType(state, object, true);
|
|
2799
|
+
}
|
|
2800
|
+
var type2 = _toString.call(state.dump);
|
|
2801
|
+
var inblock = block;
|
|
2802
|
+
var tagStr;
|
|
2803
|
+
if (block) {
|
|
2804
|
+
block = state.flowLevel < 0 || state.flowLevel > level;
|
|
2805
|
+
}
|
|
2806
|
+
var objectOrArray = type2 === "[object Object]" || type2 === "[object Array]", duplicateIndex, duplicate;
|
|
2807
|
+
if (objectOrArray) {
|
|
2808
|
+
duplicateIndex = state.duplicates.indexOf(object);
|
|
2809
|
+
duplicate = duplicateIndex !== -1;
|
|
2810
|
+
}
|
|
2811
|
+
if (state.tag !== null && state.tag !== "?" || duplicate || state.indent !== 2 && level > 0) {
|
|
2812
|
+
compact = false;
|
|
2813
|
+
}
|
|
2814
|
+
if (duplicate && state.usedDuplicates[duplicateIndex]) {
|
|
2815
|
+
state.dump = "*ref_" + duplicateIndex;
|
|
2816
|
+
} else {
|
|
2817
|
+
if (objectOrArray && duplicate && !state.usedDuplicates[duplicateIndex]) {
|
|
2818
|
+
state.usedDuplicates[duplicateIndex] = true;
|
|
2819
|
+
}
|
|
2820
|
+
if (type2 === "[object Object]") {
|
|
2821
|
+
if (block && Object.keys(state.dump).length !== 0) {
|
|
2822
|
+
writeBlockMapping(state, level, state.dump, compact);
|
|
2823
|
+
if (duplicate) {
|
|
2824
|
+
state.dump = "&ref_" + duplicateIndex + state.dump;
|
|
2825
|
+
}
|
|
2826
|
+
} else {
|
|
2827
|
+
writeFlowMapping(state, level, state.dump);
|
|
2828
|
+
if (duplicate) {
|
|
2829
|
+
state.dump = "&ref_" + duplicateIndex + " " + state.dump;
|
|
2830
|
+
}
|
|
2831
|
+
}
|
|
2832
|
+
} else if (type2 === "[object Array]") {
|
|
2833
|
+
if (block && state.dump.length !== 0) {
|
|
2834
|
+
if (state.noArrayIndent && !isblockseq && level > 0) {
|
|
2835
|
+
writeBlockSequence(state, level - 1, state.dump, compact);
|
|
2836
|
+
} else {
|
|
2837
|
+
writeBlockSequence(state, level, state.dump, compact);
|
|
2838
|
+
}
|
|
2839
|
+
if (duplicate) {
|
|
2840
|
+
state.dump = "&ref_" + duplicateIndex + state.dump;
|
|
2841
|
+
}
|
|
2842
|
+
} else {
|
|
2843
|
+
writeFlowSequence(state, level, state.dump);
|
|
2844
|
+
if (duplicate) {
|
|
2845
|
+
state.dump = "&ref_" + duplicateIndex + " " + state.dump;
|
|
2846
|
+
}
|
|
2847
|
+
}
|
|
2848
|
+
} else if (type2 === "[object String]") {
|
|
2849
|
+
if (state.tag !== "?") {
|
|
2850
|
+
writeScalar(state, state.dump, level, iskey, inblock);
|
|
2851
|
+
}
|
|
2852
|
+
} else if (type2 === "[object Undefined]") {
|
|
2853
|
+
return false;
|
|
2854
|
+
} else {
|
|
2855
|
+
if (state.skipInvalid)
|
|
2856
|
+
return false;
|
|
2857
|
+
throw new exception("unacceptable kind of an object to dump " + type2);
|
|
2858
|
+
}
|
|
2859
|
+
if (state.tag !== null && state.tag !== "?") {
|
|
2860
|
+
tagStr = encodeURI(state.tag[0] === "!" ? state.tag.slice(1) : state.tag).replace(/!/g, "%21");
|
|
2861
|
+
if (state.tag[0] === "!") {
|
|
2862
|
+
tagStr = "!" + tagStr;
|
|
2863
|
+
} else if (tagStr.slice(0, 18) === "tag:yaml.org,2002:") {
|
|
2864
|
+
tagStr = "!!" + tagStr.slice(18);
|
|
2865
|
+
} else {
|
|
2866
|
+
tagStr = "!<" + tagStr + ">";
|
|
2867
|
+
}
|
|
2868
|
+
state.dump = tagStr + " " + state.dump;
|
|
2869
|
+
}
|
|
2870
|
+
}
|
|
2871
|
+
return true;
|
|
2872
|
+
}
|
|
2873
|
+
function getDuplicateReferences(object, state) {
|
|
2874
|
+
var objects = [], duplicatesIndexes = [], index, length;
|
|
2875
|
+
inspectNode(object, objects, duplicatesIndexes);
|
|
2876
|
+
for (index = 0, length = duplicatesIndexes.length;index < length; index += 1) {
|
|
2877
|
+
state.duplicates.push(objects[duplicatesIndexes[index]]);
|
|
2878
|
+
}
|
|
2879
|
+
state.usedDuplicates = new Array(length);
|
|
2880
|
+
}
|
|
2881
|
+
function inspectNode(object, objects, duplicatesIndexes) {
|
|
2882
|
+
var objectKeyList, index, length;
|
|
2883
|
+
if (object !== null && typeof object === "object") {
|
|
2884
|
+
index = objects.indexOf(object);
|
|
2885
|
+
if (index !== -1) {
|
|
2886
|
+
if (duplicatesIndexes.indexOf(index) === -1) {
|
|
2887
|
+
duplicatesIndexes.push(index);
|
|
2888
|
+
}
|
|
2889
|
+
} else {
|
|
2890
|
+
objects.push(object);
|
|
2891
|
+
if (Array.isArray(object)) {
|
|
2892
|
+
for (index = 0, length = object.length;index < length; index += 1) {
|
|
2893
|
+
inspectNode(object[index], objects, duplicatesIndexes);
|
|
2894
|
+
}
|
|
2895
|
+
} else {
|
|
2896
|
+
objectKeyList = Object.keys(object);
|
|
2897
|
+
for (index = 0, length = objectKeyList.length;index < length; index += 1) {
|
|
2898
|
+
inspectNode(object[objectKeyList[index]], objects, duplicatesIndexes);
|
|
2899
|
+
}
|
|
2900
|
+
}
|
|
2901
|
+
}
|
|
2902
|
+
}
|
|
2903
|
+
}
|
|
2904
|
+
function dump$1(input, options) {
|
|
2905
|
+
options = options || {};
|
|
2906
|
+
var state = new State(options);
|
|
2907
|
+
if (!state.noRefs)
|
|
2908
|
+
getDuplicateReferences(input, state);
|
|
2909
|
+
var value = input;
|
|
2910
|
+
if (state.replacer) {
|
|
2911
|
+
value = state.replacer.call({ "": value }, "", value);
|
|
2912
|
+
}
|
|
2913
|
+
if (writeNode(state, 0, value, true, true))
|
|
2914
|
+
return state.dump + `
|
|
2915
|
+
`;
|
|
2916
|
+
return "";
|
|
2917
|
+
}
|
|
2918
|
+
var dump_1 = dump$1;
|
|
2919
|
+
var dumper = {
|
|
2920
|
+
dump: dump_1
|
|
2921
|
+
};
|
|
2922
|
+
function renamed(from, to) {
|
|
2923
|
+
return function() {
|
|
2924
|
+
throw new Error("Function yaml." + from + " is removed in js-yaml 4. " + "Use yaml." + to + " instead, which is now safe by default.");
|
|
2925
|
+
};
|
|
2926
|
+
}
|
|
2927
|
+
var Type = type;
|
|
2928
|
+
var Schema = schema;
|
|
2929
|
+
var FAILSAFE_SCHEMA = failsafe;
|
|
2930
|
+
var JSON_SCHEMA = json;
|
|
2931
|
+
var CORE_SCHEMA = core;
|
|
2932
|
+
var DEFAULT_SCHEMA = _default;
|
|
2933
|
+
var load = loader.load;
|
|
2934
|
+
var loadAll = loader.loadAll;
|
|
2935
|
+
var dump = dumper.dump;
|
|
2936
|
+
var YAMLException = exception;
|
|
2937
|
+
var types = {
|
|
2938
|
+
binary,
|
|
2939
|
+
float,
|
|
2940
|
+
map,
|
|
2941
|
+
null: _null,
|
|
2942
|
+
pairs,
|
|
2943
|
+
set,
|
|
2944
|
+
timestamp,
|
|
2945
|
+
bool,
|
|
2946
|
+
int,
|
|
2947
|
+
merge,
|
|
2948
|
+
omap,
|
|
2949
|
+
seq,
|
|
2950
|
+
str
|
|
2951
|
+
};
|
|
2952
|
+
var safeLoad = renamed("safeLoad", "load");
|
|
2953
|
+
var safeLoadAll = renamed("safeLoadAll", "loadAll");
|
|
2954
|
+
var safeDump = renamed("safeDump", "dump");
|
|
2955
|
+
var jsYaml = {
|
|
2956
|
+
Type,
|
|
2957
|
+
Schema,
|
|
2958
|
+
FAILSAFE_SCHEMA,
|
|
2959
|
+
JSON_SCHEMA,
|
|
2960
|
+
CORE_SCHEMA,
|
|
2961
|
+
DEFAULT_SCHEMA,
|
|
2962
|
+
load,
|
|
2963
|
+
loadAll,
|
|
2964
|
+
dump,
|
|
2965
|
+
YAMLException,
|
|
2966
|
+
types,
|
|
2967
|
+
safeLoad,
|
|
2968
|
+
safeLoadAll,
|
|
2969
|
+
safeDump
|
|
2970
|
+
};
|
|
2971
|
+
|
|
2972
|
+
// src/config/agent-loader.ts
|
|
2973
|
+
var MODEL_KEY_RE2 = /^[a-zA-Z0-9_-]{1,100}\/[a-zA-Z0-9._-]{1,100}$/;
|
|
2974
|
+
function isPathInside(baseDir, targetPath) {
|
|
2975
|
+
const rel = relative2(baseDir, targetPath);
|
|
2976
|
+
return rel === "" || !rel.startsWith("..") && !isAbsolute2(rel);
|
|
2977
|
+
}
|
|
2978
|
+
function toRelativeAgentPath(absPath, projectDirectory, homeDir = homedir3()) {
|
|
2979
|
+
const resolvedAbs = resolve2(absPath);
|
|
2980
|
+
const configBase = resolve2(join2(homeDir, ".config", "opencode"));
|
|
2981
|
+
const projectBase = resolve2(projectDirectory);
|
|
2982
|
+
if (isPathInside(configBase, resolvedAbs)) {
|
|
2983
|
+
const rel = relative2(configBase, resolvedAbs);
|
|
2984
|
+
if (rel)
|
|
2985
|
+
return rel;
|
|
2986
|
+
}
|
|
2987
|
+
if (isPathInside(projectBase, resolvedAbs)) {
|
|
2988
|
+
const rel = relative2(projectBase, resolvedAbs);
|
|
2989
|
+
if (rel)
|
|
2990
|
+
return rel;
|
|
2991
|
+
}
|
|
2992
|
+
return basename(absPath);
|
|
2993
|
+
}
|
|
2994
|
+
function stemName(filePath) {
|
|
2995
|
+
const base = basename(filePath);
|
|
2996
|
+
const ext = extname(base);
|
|
2997
|
+
return ext ? base.slice(0, -ext.length) : base;
|
|
2998
|
+
}
|
|
2999
|
+
function collectFiles(dir, recursive) {
|
|
3000
|
+
if (!existsSync(dir))
|
|
3001
|
+
return [];
|
|
3002
|
+
const baseDir = resolve2(dir);
|
|
3003
|
+
let baseRealPath = baseDir;
|
|
3004
|
+
try {
|
|
3005
|
+
baseRealPath = realpathSync(baseDir);
|
|
3006
|
+
} catch {
|
|
3007
|
+
return [];
|
|
3008
|
+
}
|
|
3009
|
+
try {
|
|
3010
|
+
let entries;
|
|
3011
|
+
if (recursive) {
|
|
3012
|
+
entries = readdirSync(baseDir, { recursive: true });
|
|
3013
|
+
} else {
|
|
3014
|
+
entries = readdirSync(baseDir);
|
|
3015
|
+
}
|
|
3016
|
+
return entries.filter((e) => e.endsWith(".md") || e.endsWith(".json")).map((e) => {
|
|
3017
|
+
const candidatePath = resolve2(join2(baseDir, e));
|
|
3018
|
+
if (!isPathInside(baseDir, candidatePath))
|
|
3019
|
+
return null;
|
|
3020
|
+
try {
|
|
3021
|
+
const realPath = realpathSync(candidatePath);
|
|
3022
|
+
if (!isPathInside(baseRealPath, realPath))
|
|
3023
|
+
return null;
|
|
3024
|
+
if (!statSync(realPath).isFile())
|
|
3025
|
+
return null;
|
|
3026
|
+
return realPath;
|
|
3027
|
+
} catch {
|
|
3028
|
+
return null;
|
|
3029
|
+
}
|
|
3030
|
+
}).filter((path) => path !== null);
|
|
3031
|
+
} catch {
|
|
3032
|
+
return [];
|
|
3033
|
+
}
|
|
3034
|
+
}
|
|
3035
|
+
function parseFrontmatter(content) {
|
|
3036
|
+
if (!content.startsWith("---"))
|
|
3037
|
+
return null;
|
|
3038
|
+
const end = content.indexOf(`
|
|
3039
|
+
---`, 3);
|
|
3040
|
+
if (end === -1)
|
|
3041
|
+
return null;
|
|
3042
|
+
const frontmatter = content.slice(3, end).trim();
|
|
3043
|
+
try {
|
|
3044
|
+
return jsYaml.load(frontmatter, { schema: jsYaml.CORE_SCHEMA });
|
|
3045
|
+
} catch {
|
|
3046
|
+
return null;
|
|
3047
|
+
}
|
|
3048
|
+
}
|
|
3049
|
+
function parseAgentFile(filePath) {
|
|
3050
|
+
try {
|
|
3051
|
+
const content = readFileSync(filePath, "utf-8");
|
|
3052
|
+
let data;
|
|
3053
|
+
if (filePath.endsWith(".json")) {
|
|
3054
|
+
data = JSON.parse(content);
|
|
3055
|
+
} else {
|
|
3056
|
+
data = parseFrontmatter(content);
|
|
3057
|
+
}
|
|
3058
|
+
if (!data || typeof data !== "object" || Array.isArray(data))
|
|
3059
|
+
return null;
|
|
3060
|
+
const obj = data;
|
|
3061
|
+
const fallback = obj.fallback;
|
|
3062
|
+
if (!fallback || typeof fallback !== "object" || Array.isArray(fallback))
|
|
3063
|
+
return null;
|
|
3064
|
+
const models = fallback.models;
|
|
3065
|
+
if (!Array.isArray(models) || models.length === 0)
|
|
3066
|
+
return null;
|
|
3067
|
+
const validModels = [];
|
|
3068
|
+
for (const m of models) {
|
|
3069
|
+
if (typeof m !== "string" || !MODEL_KEY_RE2.test(m)) {
|
|
3070
|
+
console.warn(`[model-fallback] agent-loader: skipping invalid model key ${JSON.stringify(m)} in ${filePath}`);
|
|
3071
|
+
continue;
|
|
3072
|
+
}
|
|
3073
|
+
validModels.push(m);
|
|
3074
|
+
}
|
|
3075
|
+
if (validModels.length === 0)
|
|
3076
|
+
return null;
|
|
3077
|
+
const name = typeof obj.name === "string" && obj.name.length > 0 ? obj.name : stemName(filePath);
|
|
3078
|
+
return { name, config: { fallbackModels: validModels } };
|
|
3079
|
+
} catch (err) {
|
|
3080
|
+
console.warn(`[model-fallback] agent-loader: failed to parse ${filePath}:`, err);
|
|
3081
|
+
return null;
|
|
3082
|
+
}
|
|
3083
|
+
}
|
|
3084
|
+
function resolveAgentFile(agentName, projectDirectory, customDirs, homeDir = homedir3()) {
|
|
3085
|
+
const scanDirs = customDirs && customDirs.length > 0 ? customDirs.map((d) => [d, false]) : [
|
|
3086
|
+
[join2(homeDir, ".config", "opencode", "agents"), false],
|
|
3087
|
+
[join2(homeDir, ".config", "opencode", "agent"), true],
|
|
3088
|
+
[join2(projectDirectory, ".opencode", "agents"), false],
|
|
3089
|
+
[join2(projectDirectory, ".opencode", "agent"), true]
|
|
3090
|
+
];
|
|
3091
|
+
const allFiles = [];
|
|
3092
|
+
for (const [dir, recursive] of scanDirs) {
|
|
3093
|
+
allFiles.push(...collectFiles(dir, recursive));
|
|
3094
|
+
}
|
|
3095
|
+
for (const file of allFiles) {
|
|
3096
|
+
if (stemName(file) === agentName)
|
|
3097
|
+
return file;
|
|
3098
|
+
}
|
|
3099
|
+
for (const file of allFiles) {
|
|
3100
|
+
try {
|
|
3101
|
+
const content = readFileSync(file, "utf-8");
|
|
3102
|
+
const data = file.endsWith(".json") ? JSON.parse(content) : parseFrontmatter(content);
|
|
3103
|
+
if (data && typeof data === "object" && !Array.isArray(data) && data.name === agentName) {
|
|
3104
|
+
return file;
|
|
3105
|
+
}
|
|
3106
|
+
} catch {}
|
|
3107
|
+
}
|
|
3108
|
+
return null;
|
|
3109
|
+
}
|
|
3110
|
+
function loadAgentFallbackConfigs(projectDirectory, homeDir = homedir3()) {
|
|
3111
|
+
const scanDirs = [
|
|
3112
|
+
[join2(homeDir, ".config", "opencode", "agents"), false],
|
|
3113
|
+
[join2(homeDir, ".config", "opencode", "agent"), true],
|
|
3114
|
+
[join2(projectDirectory, ".opencode", "agents"), false],
|
|
3115
|
+
[join2(projectDirectory, ".opencode", "agent"), true]
|
|
3116
|
+
];
|
|
3117
|
+
const result = {};
|
|
3118
|
+
for (const [dir, recursive] of scanDirs) {
|
|
3119
|
+
const files = collectFiles(dir, recursive);
|
|
3120
|
+
for (const file of files) {
|
|
3121
|
+
const parsed = parseAgentFile(file);
|
|
3122
|
+
if (parsed) {
|
|
3123
|
+
result[parsed.name] = parsed.config;
|
|
3124
|
+
}
|
|
3125
|
+
}
|
|
3126
|
+
}
|
|
3127
|
+
return result;
|
|
3128
|
+
}
|
|
3129
|
+
|
|
3130
|
+
// src/config/loader.ts
|
|
3131
|
+
var CONFIG_FILENAME = "model-fallback.json";
|
|
3132
|
+
var OLD_CONFIG_FILENAME = "rate-limit-fallback.json";
|
|
3133
|
+
function candidatePaths(directory) {
|
|
3134
|
+
const home2 = homedir4();
|
|
3135
|
+
return [
|
|
3136
|
+
join3(directory, ".opencode", CONFIG_FILENAME),
|
|
3137
|
+
join3(home2, ".config", "opencode", CONFIG_FILENAME),
|
|
3138
|
+
join3(directory, ".opencode", OLD_CONFIG_FILENAME),
|
|
3139
|
+
join3(home2, ".config", "opencode", OLD_CONFIG_FILENAME)
|
|
3140
|
+
];
|
|
3141
|
+
}
|
|
3142
|
+
function loadConfig(directory) {
|
|
3143
|
+
const agentFileConfigs = loadAgentFallbackConfigs(directory);
|
|
3144
|
+
const candidates = candidatePaths(directory);
|
|
3145
|
+
for (const candidate of candidates) {
|
|
3146
|
+
if (!existsSync2(candidate))
|
|
3147
|
+
continue;
|
|
3148
|
+
let raw;
|
|
3149
|
+
try {
|
|
3150
|
+
raw = JSON.parse(readFileSync2(candidate, "utf-8"));
|
|
3151
|
+
} catch {
|
|
3152
|
+
return {
|
|
3153
|
+
config: {
|
|
3154
|
+
...DEFAULT_CONFIG,
|
|
3155
|
+
agents: { ...agentFileConfigs, ...DEFAULT_CONFIG.agents }
|
|
3156
|
+
},
|
|
3157
|
+
path: candidate,
|
|
3158
|
+
warnings: [`Failed to parse ${basename2(candidate)}: invalid JSON — using defaults`],
|
|
3159
|
+
migrated: false
|
|
3160
|
+
};
|
|
3161
|
+
}
|
|
3162
|
+
const isOld = isOldFormat(raw);
|
|
3163
|
+
if (isOld) {
|
|
3164
|
+
raw = migrateOldConfig(raw);
|
|
3165
|
+
}
|
|
3166
|
+
const { config: parsed, warnings } = parseConfig(raw);
|
|
3167
|
+
const merged = mergeWithDefaults(parsed);
|
|
3168
|
+
merged.agents = { ...agentFileConfigs, ...merged.agents };
|
|
3169
|
+
return {
|
|
3170
|
+
config: merged,
|
|
3171
|
+
path: candidate,
|
|
3172
|
+
warnings,
|
|
3173
|
+
migrated: isOld
|
|
3174
|
+
};
|
|
3175
|
+
}
|
|
3176
|
+
return {
|
|
3177
|
+
config: {
|
|
3178
|
+
...DEFAULT_CONFIG,
|
|
3179
|
+
agents: { ...agentFileConfigs, ...DEFAULT_CONFIG.agents }
|
|
3180
|
+
},
|
|
3181
|
+
path: null,
|
|
3182
|
+
warnings: [],
|
|
3183
|
+
migrated: false
|
|
3184
|
+
};
|
|
3185
|
+
}
|
|
3186
|
+
|
|
3187
|
+
// src/logging/logger.ts
|
|
3188
|
+
import { appendFileSync, mkdirSync } from "fs";
|
|
3189
|
+
import { dirname } from "path";
|
|
3190
|
+
|
|
3191
|
+
class Logger {
|
|
3192
|
+
client;
|
|
3193
|
+
logPath;
|
|
3194
|
+
enabled;
|
|
3195
|
+
dirCreated = false;
|
|
3196
|
+
constructor(client, logPath, enabled) {
|
|
3197
|
+
this.client = client;
|
|
3198
|
+
this.logPath = logPath;
|
|
3199
|
+
this.enabled = enabled;
|
|
3200
|
+
}
|
|
3201
|
+
log(level, event, fields = {}) {
|
|
3202
|
+
const entry = {
|
|
3203
|
+
ts: new Date().toISOString(),
|
|
3204
|
+
level,
|
|
3205
|
+
event,
|
|
3206
|
+
...fields
|
|
3207
|
+
};
|
|
3208
|
+
if (this.enabled) {
|
|
3209
|
+
this.writeToFile(entry);
|
|
3210
|
+
}
|
|
3211
|
+
if (level !== "debug") {
|
|
3212
|
+
const message = `[model-fallback] ${event}${Object.keys(fields).length ? " " + JSON.stringify(fields) : ""}`;
|
|
3213
|
+
this.client.app.log({
|
|
3214
|
+
body: { service: "model-fallback", level, message }
|
|
3215
|
+
}).catch(() => {});
|
|
3216
|
+
}
|
|
3217
|
+
}
|
|
3218
|
+
info(event, fields) {
|
|
3219
|
+
this.log("info", event, fields);
|
|
3220
|
+
}
|
|
3221
|
+
warn(event, fields) {
|
|
3222
|
+
this.log("warn", event, fields);
|
|
3223
|
+
}
|
|
3224
|
+
error(event, fields) {
|
|
3225
|
+
this.log("error", event, fields);
|
|
3226
|
+
}
|
|
3227
|
+
debug(event, fields) {
|
|
3228
|
+
this.log("debug", event, fields);
|
|
3229
|
+
}
|
|
3230
|
+
writeToFile(entry) {
|
|
3231
|
+
try {
|
|
3232
|
+
if (!this.dirCreated) {
|
|
3233
|
+
mkdirSync(dirname(this.logPath), { recursive: true });
|
|
3234
|
+
this.dirCreated = true;
|
|
3235
|
+
}
|
|
3236
|
+
appendFileSync(this.logPath, JSON.stringify(entry) + `
|
|
3237
|
+
`, "utf-8");
|
|
3238
|
+
} catch {}
|
|
3239
|
+
}
|
|
3240
|
+
}
|
|
3241
|
+
|
|
3242
|
+
// src/state/model-health.ts
|
|
3243
|
+
class ModelHealthStore {
|
|
3244
|
+
store = new Map;
|
|
3245
|
+
timer = null;
|
|
3246
|
+
onTransition;
|
|
3247
|
+
constructor(opts) {
|
|
3248
|
+
this.onTransition = opts?.onTransition;
|
|
3249
|
+
this.timer = setInterval(() => this.tick(), 30000);
|
|
3250
|
+
}
|
|
3251
|
+
get(modelKey2) {
|
|
3252
|
+
return this.store.get(modelKey2) ?? this.newHealth(modelKey2);
|
|
3253
|
+
}
|
|
3254
|
+
markRateLimited(modelKey2, cooldownMs, retryOriginalAfterMs) {
|
|
3255
|
+
const now = Date.now();
|
|
3256
|
+
const existing = this.get(modelKey2);
|
|
3257
|
+
const health = {
|
|
3258
|
+
...existing,
|
|
3259
|
+
state: "rate_limited",
|
|
3260
|
+
lastFailure: now,
|
|
3261
|
+
failureCount: existing.failureCount + 1,
|
|
3262
|
+
cooldownExpiresAt: now + cooldownMs,
|
|
3263
|
+
retryOriginalAt: now + retryOriginalAfterMs
|
|
3264
|
+
};
|
|
3265
|
+
this.store.set(modelKey2, health);
|
|
3266
|
+
}
|
|
3267
|
+
isUsable(modelKey2) {
|
|
3268
|
+
const h = this.get(modelKey2);
|
|
3269
|
+
return h.state === "healthy" || h.state === "cooldown";
|
|
3270
|
+
}
|
|
3271
|
+
preferScore(modelKey2) {
|
|
3272
|
+
const state = this.get(modelKey2).state;
|
|
3273
|
+
if (state === "healthy")
|
|
3274
|
+
return 2;
|
|
3275
|
+
if (state === "cooldown")
|
|
3276
|
+
return 1;
|
|
3277
|
+
return 0;
|
|
3278
|
+
}
|
|
3279
|
+
getAll() {
|
|
3280
|
+
return Array.from(this.store.values());
|
|
3281
|
+
}
|
|
3282
|
+
destroy() {
|
|
3283
|
+
if (this.timer) {
|
|
3284
|
+
clearInterval(this.timer);
|
|
3285
|
+
this.timer = null;
|
|
3286
|
+
}
|
|
3287
|
+
}
|
|
3288
|
+
tick() {
|
|
3289
|
+
const now = Date.now();
|
|
3290
|
+
for (const [key, health] of this.store) {
|
|
3291
|
+
if (health.state === "rate_limited" && health.cooldownExpiresAt && now >= health.cooldownExpiresAt) {
|
|
3292
|
+
const next = { ...health, state: "cooldown" };
|
|
3293
|
+
this.store.set(key, next);
|
|
3294
|
+
this.onTransition?.(key, "rate_limited", "cooldown");
|
|
3295
|
+
} else if (health.state === "cooldown" && health.retryOriginalAt && now >= health.retryOriginalAt) {
|
|
3296
|
+
const next = {
|
|
3297
|
+
...health,
|
|
3298
|
+
state: "healthy",
|
|
3299
|
+
cooldownExpiresAt: null,
|
|
3300
|
+
retryOriginalAt: null
|
|
3301
|
+
};
|
|
3302
|
+
this.store.set(key, next);
|
|
3303
|
+
this.onTransition?.(key, "cooldown", "healthy");
|
|
3304
|
+
}
|
|
3305
|
+
}
|
|
3306
|
+
}
|
|
3307
|
+
newHealth(modelKey2) {
|
|
3308
|
+
return {
|
|
3309
|
+
modelKey: modelKey2,
|
|
3310
|
+
state: "healthy",
|
|
3311
|
+
lastFailure: null,
|
|
3312
|
+
failureCount: 0,
|
|
3313
|
+
cooldownExpiresAt: null,
|
|
3314
|
+
retryOriginalAt: null
|
|
3315
|
+
};
|
|
3316
|
+
}
|
|
3317
|
+
}
|
|
3318
|
+
|
|
3319
|
+
// src/state/session-state.ts
|
|
3320
|
+
class SessionStateStore {
|
|
3321
|
+
store = new Map;
|
|
3322
|
+
get(sessionId) {
|
|
3323
|
+
if (!this.store.has(sessionId)) {
|
|
3324
|
+
this.store.set(sessionId, this.newState(sessionId));
|
|
3325
|
+
}
|
|
3326
|
+
return this.store.get(sessionId);
|
|
3327
|
+
}
|
|
3328
|
+
acquireLock(sessionId) {
|
|
3329
|
+
const state = this.get(sessionId);
|
|
3330
|
+
if (state.isProcessing)
|
|
3331
|
+
return false;
|
|
3332
|
+
state.isProcessing = true;
|
|
3333
|
+
return true;
|
|
3334
|
+
}
|
|
3335
|
+
releaseLock(sessionId) {
|
|
3336
|
+
const state = this.store.get(sessionId);
|
|
3337
|
+
if (state)
|
|
3338
|
+
state.isProcessing = false;
|
|
3339
|
+
}
|
|
3340
|
+
isInDedupWindow(sessionId, windowMs = 3000) {
|
|
3341
|
+
const state = this.get(sessionId);
|
|
3342
|
+
if (!state.lastFallbackAt)
|
|
3343
|
+
return false;
|
|
3344
|
+
return Date.now() - state.lastFallbackAt < windowMs;
|
|
3345
|
+
}
|
|
3346
|
+
recordFallback(sessionId, fromModel, toModel, reason, agentName) {
|
|
3347
|
+
const state = this.get(sessionId);
|
|
3348
|
+
const event = {
|
|
3349
|
+
at: Date.now(),
|
|
3350
|
+
fromModel,
|
|
3351
|
+
toModel,
|
|
3352
|
+
reason,
|
|
3353
|
+
sessionId,
|
|
3354
|
+
trigger: "reactive",
|
|
3355
|
+
agentName
|
|
3356
|
+
};
|
|
3357
|
+
state.currentModel = toModel;
|
|
3358
|
+
state.fallbackDepth++;
|
|
3359
|
+
state.lastFallbackAt = event.at;
|
|
3360
|
+
state.recoveryNotifiedForModel = null;
|
|
3361
|
+
state.fallbackHistory.push(event);
|
|
3362
|
+
if (agentName)
|
|
3363
|
+
state.agentName = agentName;
|
|
3364
|
+
}
|
|
3365
|
+
recordPreemptiveRedirect(sessionId, fromModel, toModel, agentName) {
|
|
3366
|
+
const state = this.get(sessionId);
|
|
3367
|
+
const event = {
|
|
3368
|
+
at: Date.now(),
|
|
3369
|
+
fromModel,
|
|
3370
|
+
toModel,
|
|
3371
|
+
reason: "rate_limit",
|
|
3372
|
+
sessionId,
|
|
3373
|
+
trigger: "preemptive",
|
|
3374
|
+
agentName
|
|
3375
|
+
};
|
|
3376
|
+
state.currentModel = toModel;
|
|
3377
|
+
state.recoveryNotifiedForModel = null;
|
|
3378
|
+
state.fallbackHistory.push(event);
|
|
3379
|
+
if (agentName)
|
|
3380
|
+
state.agentName = agentName;
|
|
3381
|
+
}
|
|
3382
|
+
setOriginalModel(sessionId, model) {
|
|
3383
|
+
const state = this.get(sessionId);
|
|
3384
|
+
if (!state.originalModel) {
|
|
3385
|
+
state.originalModel = model;
|
|
3386
|
+
state.currentModel = model;
|
|
3387
|
+
}
|
|
3388
|
+
}
|
|
3389
|
+
setAgentName(sessionId, agentName) {
|
|
3390
|
+
const state = this.get(sessionId);
|
|
3391
|
+
state.agentName = agentName;
|
|
3392
|
+
}
|
|
3393
|
+
setAgentFile(sessionId, agentFile) {
|
|
3394
|
+
const state = this.get(sessionId);
|
|
3395
|
+
state.agentFile = agentFile;
|
|
3396
|
+
}
|
|
3397
|
+
partialReset(sessionId) {
|
|
3398
|
+
const state = this.store.get(sessionId);
|
|
3399
|
+
if (!state)
|
|
3400
|
+
return;
|
|
3401
|
+
state.fallbackHistory = [];
|
|
3402
|
+
state.lastFallbackAt = null;
|
|
3403
|
+
state.isProcessing = false;
|
|
3404
|
+
}
|
|
3405
|
+
delete(sessionId) {
|
|
3406
|
+
this.store.delete(sessionId);
|
|
3407
|
+
}
|
|
3408
|
+
getAll() {
|
|
3409
|
+
return Array.from(this.store.values());
|
|
3410
|
+
}
|
|
3411
|
+
newState(sessionId) {
|
|
3412
|
+
return {
|
|
3413
|
+
sessionId,
|
|
3414
|
+
agentName: null,
|
|
3415
|
+
agentFile: null,
|
|
3416
|
+
originalModel: null,
|
|
3417
|
+
currentModel: null,
|
|
3418
|
+
fallbackDepth: 0,
|
|
3419
|
+
isProcessing: false,
|
|
3420
|
+
lastFallbackAt: null,
|
|
3421
|
+
fallbackHistory: [],
|
|
3422
|
+
recoveryNotifiedForModel: null
|
|
3423
|
+
};
|
|
3424
|
+
}
|
|
3425
|
+
}
|
|
3426
|
+
|
|
3427
|
+
// src/state/store.ts
|
|
3428
|
+
class FallbackStore {
|
|
3429
|
+
health;
|
|
3430
|
+
sessions;
|
|
3431
|
+
constructor(_config, logger) {
|
|
3432
|
+
this.sessions = new SessionStateStore;
|
|
3433
|
+
this.health = new ModelHealthStore({
|
|
3434
|
+
onTransition: (modelKey2, from, to) => {
|
|
3435
|
+
logger.info("health.transition", { modelKey: modelKey2, from, to });
|
|
3436
|
+
}
|
|
3437
|
+
});
|
|
3438
|
+
}
|
|
3439
|
+
destroy() {
|
|
3440
|
+
this.health.destroy();
|
|
3441
|
+
}
|
|
3442
|
+
}
|
|
3443
|
+
|
|
3444
|
+
// src/detection/patterns.ts
|
|
3445
|
+
function matchesAnyPattern(text, patterns) {
|
|
3446
|
+
const lower = text.toLowerCase();
|
|
3447
|
+
return patterns.some((p) => lower.includes(p.toLowerCase()));
|
|
3448
|
+
}
|
|
3449
|
+
|
|
3450
|
+
// src/detection/classifier.ts
|
|
3451
|
+
var RATE_LIMIT_PATTERNS = ["rate limit", "ratelimit", "too many requests", "usage limit", "429"];
|
|
3452
|
+
var QUOTA_PATTERNS = [
|
|
3453
|
+
"quota exceeded",
|
|
3454
|
+
"credits exhausted",
|
|
3455
|
+
"billing limit",
|
|
3456
|
+
"credit limit",
|
|
3457
|
+
"insufficient quota",
|
|
3458
|
+
"out of credits"
|
|
3459
|
+
];
|
|
3460
|
+
var OVERLOADED_PATTERNS = [
|
|
3461
|
+
"overloaded",
|
|
3462
|
+
"capacity exceeded",
|
|
3463
|
+
"server is busy",
|
|
3464
|
+
"engine is currently overloaded"
|
|
3465
|
+
];
|
|
3466
|
+
var TIMEOUT_PATTERNS = ["timeout", "timed out", "request timeout", "connection timeout"];
|
|
3467
|
+
var SERVER_ERROR_PATTERNS = [
|
|
3468
|
+
"internal server error",
|
|
3469
|
+
"bad gateway",
|
|
3470
|
+
"service unavailable",
|
|
3471
|
+
"gateway timeout",
|
|
3472
|
+
"500",
|
|
3473
|
+
"502",
|
|
3474
|
+
"503",
|
|
3475
|
+
"504"
|
|
3476
|
+
];
|
|
3477
|
+
function classifyError(message, statusCode) {
|
|
3478
|
+
const text = message.toLowerCase();
|
|
3479
|
+
if (statusCode === 429 || matchesAnyPattern(text, RATE_LIMIT_PATTERNS)) {
|
|
3480
|
+
return "rate_limit";
|
|
3481
|
+
}
|
|
3482
|
+
if (matchesAnyPattern(text, QUOTA_PATTERNS)) {
|
|
3483
|
+
return "quota_exceeded";
|
|
3484
|
+
}
|
|
3485
|
+
if (matchesAnyPattern(text, OVERLOADED_PATTERNS)) {
|
|
3486
|
+
return "overloaded";
|
|
3487
|
+
}
|
|
3488
|
+
if (matchesAnyPattern(text, TIMEOUT_PATTERNS)) {
|
|
3489
|
+
return "timeout";
|
|
3490
|
+
}
|
|
3491
|
+
if (statusCode !== undefined && statusCode >= 500 || matchesAnyPattern(text, SERVER_ERROR_PATTERNS)) {
|
|
3492
|
+
return "5xx";
|
|
3493
|
+
}
|
|
3494
|
+
return "unknown";
|
|
3495
|
+
}
|
|
3496
|
+
|
|
3497
|
+
// src/resolution/agent-resolver.ts
|
|
3498
|
+
async function resolveAgentName(client, sessionId, cachedName) {
|
|
3499
|
+
if (cachedName)
|
|
3500
|
+
return cachedName;
|
|
3501
|
+
try {
|
|
3502
|
+
const result = await client.session.messages({ path: { id: sessionId } });
|
|
3503
|
+
const entries = result.data;
|
|
3504
|
+
if (!Array.isArray(entries))
|
|
3505
|
+
return null;
|
|
3506
|
+
for (let i2 = entries.length - 1;i2 >= 0; i2--) {
|
|
3507
|
+
const { info } = entries[i2];
|
|
3508
|
+
if (info.role === "user" && typeof info.agent === "string") {
|
|
3509
|
+
return info.agent;
|
|
3510
|
+
}
|
|
3511
|
+
}
|
|
3512
|
+
return null;
|
|
3513
|
+
} catch {
|
|
3514
|
+
return null;
|
|
3515
|
+
}
|
|
3516
|
+
}
|
|
3517
|
+
function resolveFallbackModels(config, agentName) {
|
|
3518
|
+
if (agentName && config.agents[agentName]) {
|
|
3519
|
+
return config.agents[agentName].fallbackModels;
|
|
3520
|
+
}
|
|
3521
|
+
return config.agents["*"]?.fallbackModels ?? [];
|
|
3522
|
+
}
|
|
3523
|
+
|
|
3524
|
+
// src/resolution/fallback-resolver.ts
|
|
3525
|
+
function resolveFallbackModel(chain, currentModel, health) {
|
|
3526
|
+
const candidates = chain.filter((m) => m !== currentModel);
|
|
3527
|
+
const healthy = candidates.find((m) => health.get(m).state === "healthy");
|
|
3528
|
+
if (healthy)
|
|
3529
|
+
return healthy;
|
|
3530
|
+
const cooldown = candidates.find((m) => health.get(m).state === "cooldown");
|
|
3531
|
+
if (cooldown)
|
|
3532
|
+
return cooldown;
|
|
3533
|
+
return null;
|
|
3534
|
+
}
|
|
3535
|
+
|
|
3536
|
+
// src/replay/message-converter.ts
|
|
3537
|
+
function convertPartsForPrompt(parts) {
|
|
3538
|
+
const result = [];
|
|
3539
|
+
for (const part of parts) {
|
|
3540
|
+
if (part.type === "text") {
|
|
3541
|
+
if (part.synthetic || part.ignored)
|
|
3542
|
+
continue;
|
|
3543
|
+
result.push({ type: "text", text: part.text });
|
|
3544
|
+
continue;
|
|
3545
|
+
}
|
|
3546
|
+
if (part.type === "file") {
|
|
3547
|
+
result.push({
|
|
3548
|
+
type: "file",
|
|
3549
|
+
mime: part.mime,
|
|
3550
|
+
url: part.url,
|
|
3551
|
+
filename: part.filename
|
|
3552
|
+
});
|
|
3553
|
+
continue;
|
|
3554
|
+
}
|
|
3555
|
+
if (part.type === "agent") {
|
|
3556
|
+
result.push({ type: "agent", name: part.name });
|
|
3557
|
+
continue;
|
|
3558
|
+
}
|
|
3559
|
+
}
|
|
3560
|
+
return result;
|
|
3561
|
+
}
|
|
3562
|
+
|
|
3563
|
+
// src/replay/orchestrator.ts
|
|
3564
|
+
async function attemptFallback(sessionId, reason, client, store, config, logger, directory) {
|
|
3565
|
+
const sessionState = store.sessions.get(sessionId);
|
|
3566
|
+
if (!store.sessions.acquireLock(sessionId)) {
|
|
3567
|
+
logger.debug("fallback.skipped.locked", { sessionId });
|
|
3568
|
+
return { success: false, error: "already processing" };
|
|
3569
|
+
}
|
|
3570
|
+
try {
|
|
3571
|
+
if (store.sessions.isInDedupWindow(sessionId)) {
|
|
3572
|
+
logger.debug("fallback.skipped.dedup", { sessionId });
|
|
3573
|
+
return { success: false, error: "dedup window" };
|
|
3574
|
+
}
|
|
3575
|
+
const agentName = await resolveAgentName(client, sessionId, sessionState.agentName);
|
|
3576
|
+
if (agentName) {
|
|
3577
|
+
store.sessions.setAgentName(sessionId, agentName);
|
|
3578
|
+
if (!sessionState.agentFile) {
|
|
3579
|
+
const absPath = resolveAgentFile(agentName, directory, config.agentDirs?.length ? config.agentDirs : undefined);
|
|
3580
|
+
if (absPath)
|
|
3581
|
+
store.sessions.setAgentFile(sessionId, toRelativeAgentPath(absPath, directory));
|
|
3582
|
+
}
|
|
3583
|
+
}
|
|
3584
|
+
const chain = resolveFallbackModels(config, agentName);
|
|
3585
|
+
if (chain.length === 0) {
|
|
3586
|
+
logger.warn("fallback.no-chain", { sessionId, agentName });
|
|
3587
|
+
return { success: false, error: "no fallback chain configured" };
|
|
3588
|
+
}
|
|
3589
|
+
let messageEntries;
|
|
3590
|
+
try {
|
|
3591
|
+
const result = await client.session.messages({ path: { id: sessionId } });
|
|
3592
|
+
messageEntries = Array.isArray(result.data) ? result.data : [];
|
|
3593
|
+
} catch (err) {
|
|
3594
|
+
logger.error("replay.messages.failed", { sessionId, err: String(err) });
|
|
3595
|
+
return { success: false, error: "messages fetch failed" };
|
|
3596
|
+
}
|
|
3597
|
+
let lastUserEntry = null;
|
|
3598
|
+
for (let i2 = messageEntries.length - 1;i2 >= 0; i2--) {
|
|
3599
|
+
const entry = messageEntries[i2];
|
|
3600
|
+
if (!entry || typeof entry !== "object")
|
|
3601
|
+
continue;
|
|
3602
|
+
const info = entry.info;
|
|
3603
|
+
if (!info || typeof info !== "object")
|
|
3604
|
+
continue;
|
|
3605
|
+
const role = info.role;
|
|
3606
|
+
if (role !== "user")
|
|
3607
|
+
continue;
|
|
3608
|
+
const id = info.id;
|
|
3609
|
+
if (typeof id !== "string")
|
|
3610
|
+
continue;
|
|
3611
|
+
const rawParts = entry.parts;
|
|
3612
|
+
const safeParts = sanitizeParts(rawParts);
|
|
3613
|
+
if (safeParts.length === 0 && Array.isArray(rawParts) && rawParts.length > 0) {
|
|
3614
|
+
continue;
|
|
3615
|
+
}
|
|
3616
|
+
const rawModel = info.model;
|
|
3617
|
+
let model;
|
|
3618
|
+
if (rawModel && typeof rawModel === "object") {
|
|
3619
|
+
const providerID2 = rawModel.providerID;
|
|
3620
|
+
const modelID2 = rawModel.modelID;
|
|
3621
|
+
if (typeof providerID2 === "string" && typeof modelID2 === "string") {
|
|
3622
|
+
model = { providerID: providerID2, modelID: modelID2 };
|
|
3623
|
+
}
|
|
3624
|
+
}
|
|
3625
|
+
lastUserEntry = {
|
|
3626
|
+
id,
|
|
3627
|
+
model,
|
|
3628
|
+
parts: safeParts
|
|
3629
|
+
};
|
|
3630
|
+
break;
|
|
3631
|
+
}
|
|
3632
|
+
if (!lastUserEntry) {
|
|
3633
|
+
logger.warn("replay.no-user-message", { sessionId });
|
|
3634
|
+
return { success: false, error: "no user message found" };
|
|
3635
|
+
}
|
|
3636
|
+
const msgModel = lastUserEntry.model;
|
|
3637
|
+
if (msgModel) {
|
|
3638
|
+
const modelKey2 = `${msgModel.providerID}/${msgModel.modelID}`;
|
|
3639
|
+
store.sessions.setOriginalModel(sessionId, modelKey2);
|
|
3640
|
+
if (sessionState.currentModel !== modelKey2) {
|
|
3641
|
+
const wasOnFallback = sessionState.currentModel !== null && sessionState.currentModel !== sessionState.originalModel;
|
|
3642
|
+
sessionState.currentModel = modelKey2;
|
|
3643
|
+
if (wasOnFallback && modelKey2 === sessionState.originalModel) {
|
|
3644
|
+
sessionState.fallbackDepth = 0;
|
|
3645
|
+
logger.debug("session.depth.reset", { sessionId, modelKey: modelKey2 });
|
|
3646
|
+
}
|
|
3647
|
+
logger.debug("session.model.synced", { sessionId, modelKey: modelKey2 });
|
|
3648
|
+
}
|
|
3649
|
+
}
|
|
3650
|
+
if (sessionState.fallbackDepth >= config.defaults.maxFallbackDepth) {
|
|
3651
|
+
logger.warn("fallback.exhausted", {
|
|
3652
|
+
sessionId,
|
|
3653
|
+
depth: sessionState.fallbackDepth,
|
|
3654
|
+
max: config.defaults.maxFallbackDepth
|
|
3655
|
+
});
|
|
3656
|
+
return { success: false, error: "max fallback depth reached" };
|
|
3657
|
+
}
|
|
3658
|
+
const fallbackModel = resolveFallbackModel(chain, sessionState.currentModel, store.health);
|
|
3659
|
+
if (!fallbackModel) {
|
|
3660
|
+
logger.warn("fallback.all-exhausted", { sessionId, chain });
|
|
3661
|
+
return { success: false, error: "all fallback models exhausted" };
|
|
3662
|
+
}
|
|
3663
|
+
const currentModel = sessionState.currentModel;
|
|
3664
|
+
if (currentModel) {
|
|
3665
|
+
store.health.markRateLimited(currentModel, config.defaults.cooldownMs, config.defaults.retryOriginalAfterMs);
|
|
3666
|
+
}
|
|
3667
|
+
sessionState.lastFallbackAt = Date.now();
|
|
3668
|
+
try {
|
|
3669
|
+
await client.session.abort({ path: { id: sessionId } });
|
|
3670
|
+
logger.debug("replay.abort.ok", { sessionId });
|
|
3671
|
+
} catch (err) {
|
|
3672
|
+
logger.error("replay.abort.failed", { sessionId, err: String(err) });
|
|
3673
|
+
return { success: false, error: "abort failed" };
|
|
3674
|
+
}
|
|
3675
|
+
try {
|
|
3676
|
+
await client.session.revert({
|
|
3677
|
+
path: { id: sessionId },
|
|
3678
|
+
body: { messageID: lastUserEntry.id }
|
|
3679
|
+
});
|
|
3680
|
+
logger.debug("replay.revert.ok", {
|
|
3681
|
+
sessionId,
|
|
3682
|
+
messageID: lastUserEntry.id
|
|
3683
|
+
});
|
|
3684
|
+
} catch (err) {
|
|
3685
|
+
logger.error("replay.revert.failed", { sessionId, err: String(err) });
|
|
3686
|
+
return { success: false, error: "revert failed" };
|
|
3687
|
+
}
|
|
3688
|
+
const promptParts = convertPartsForPrompt(lastUserEntry.parts);
|
|
3689
|
+
if (promptParts.length === 0) {
|
|
3690
|
+
promptParts.push({ type: "text", text: "" });
|
|
3691
|
+
}
|
|
3692
|
+
const [providerID, ...rest] = fallbackModel.split("/");
|
|
3693
|
+
const modelID = rest.join("/");
|
|
3694
|
+
try {
|
|
3695
|
+
await client.session.prompt({
|
|
3696
|
+
path: { id: sessionId },
|
|
3697
|
+
body: {
|
|
3698
|
+
model: { providerID, modelID },
|
|
3699
|
+
parts: promptParts
|
|
3700
|
+
}
|
|
3701
|
+
});
|
|
3702
|
+
logger.debug("replay.prompt.ok", { sessionId, fallbackModel });
|
|
3703
|
+
} catch (err) {
|
|
3704
|
+
logger.error("replay.prompt.failed", {
|
|
3705
|
+
sessionId,
|
|
3706
|
+
fallbackModel,
|
|
3707
|
+
err: String(err)
|
|
3708
|
+
});
|
|
3709
|
+
return { success: false, error: "prompt failed" };
|
|
3710
|
+
}
|
|
3711
|
+
const newDepth = sessionState.fallbackDepth + 1;
|
|
3712
|
+
store.sessions.recordFallback(sessionId, currentModel ?? fallbackModel, fallbackModel, reason, agentName);
|
|
3713
|
+
logger.info("fallback.success", {
|
|
3714
|
+
sessionId,
|
|
3715
|
+
agentName,
|
|
3716
|
+
agentFile: store.sessions.get(sessionId).agentFile,
|
|
3717
|
+
from: currentModel,
|
|
3718
|
+
to: fallbackModel,
|
|
3719
|
+
reason,
|
|
3720
|
+
depth: newDepth
|
|
3721
|
+
});
|
|
3722
|
+
return { success: true, fallbackModel };
|
|
3723
|
+
} finally {
|
|
3724
|
+
store.sessions.releaseLock(sessionId);
|
|
3725
|
+
}
|
|
3726
|
+
}
|
|
3727
|
+
function sanitizeParts(parts) {
|
|
3728
|
+
if (!Array.isArray(parts))
|
|
3729
|
+
return [];
|
|
3730
|
+
return parts.filter((part) => typeof part === "object" && part !== null && ("type" in part));
|
|
3731
|
+
}
|
|
3732
|
+
|
|
3733
|
+
// src/display/notifier.ts
|
|
3734
|
+
async function notifyFallback(client, from, to, reason) {
|
|
3735
|
+
const fromLabel = from ? shortModelName(from) : "current model";
|
|
3736
|
+
const message = `Model fallback: switched from ${fromLabel} to ${shortModelName(to)} (${reason})`;
|
|
3737
|
+
await client.tui.showToast({
|
|
3738
|
+
body: {
|
|
3739
|
+
title: "Model Fallback",
|
|
3740
|
+
message,
|
|
3741
|
+
variant: "warning",
|
|
3742
|
+
duration: 6000
|
|
3743
|
+
}
|
|
3744
|
+
}).catch(() => {});
|
|
3745
|
+
}
|
|
3746
|
+
async function notifyFallbackActive(client, originalModel, currentModel) {
|
|
3747
|
+
const message = `Using ${shortModelName(currentModel)} (fallback from ${shortModelName(originalModel)})`;
|
|
3748
|
+
await client.tui.showToast({
|
|
3749
|
+
body: {
|
|
3750
|
+
title: "Fallback Active",
|
|
3751
|
+
message,
|
|
3752
|
+
variant: "warning",
|
|
3753
|
+
duration: 4000
|
|
3754
|
+
}
|
|
3755
|
+
}).catch(() => {});
|
|
3756
|
+
}
|
|
3757
|
+
async function notifyRecovery(client, originalModel) {
|
|
3758
|
+
const message = `Original model ${shortModelName(originalModel)} is available again`;
|
|
3759
|
+
await client.tui.showToast({
|
|
3760
|
+
body: {
|
|
3761
|
+
title: "Model Recovered",
|
|
3762
|
+
message,
|
|
3763
|
+
variant: "info",
|
|
3764
|
+
duration: 5000
|
|
3765
|
+
}
|
|
3766
|
+
}).catch(() => {});
|
|
3767
|
+
}
|
|
3768
|
+
function shortModelName(key) {
|
|
3769
|
+
const parts = key.split("/");
|
|
3770
|
+
return parts.length > 1 ? parts.slice(1).join("/") : key;
|
|
3771
|
+
}
|
|
3772
|
+
|
|
3773
|
+
// src/tools/fallback-status.ts
|
|
3774
|
+
import { tool } from "@opencode-ai/plugin";
|
|
3775
|
+
|
|
3776
|
+
// src/display/usage.ts
|
|
3777
|
+
async function getFallbackUsage(client, state) {
|
|
3778
|
+
const summary = {
|
|
3779
|
+
sessionId: state.sessionId,
|
|
3780
|
+
totalInputTokens: 0,
|
|
3781
|
+
totalOutputTokens: 0,
|
|
3782
|
+
totalCost: 0,
|
|
3783
|
+
fallbackPeriods: []
|
|
3784
|
+
};
|
|
3785
|
+
try {
|
|
3786
|
+
const result = await client.session.messages({ path: { id: state.sessionId } });
|
|
3787
|
+
const entries = result.data ?? [];
|
|
3788
|
+
for (const entry of entries) {
|
|
3789
|
+
const msg = entry.info;
|
|
3790
|
+
if (msg.role !== "assistant")
|
|
3791
|
+
continue;
|
|
3792
|
+
summary.totalInputTokens += msg.tokens?.input ?? 0;
|
|
3793
|
+
summary.totalOutputTokens += msg.tokens?.output ?? 0;
|
|
3794
|
+
summary.totalCost += msg.cost ?? 0;
|
|
3795
|
+
}
|
|
3796
|
+
for (let i2 = 0;i2 < state.fallbackHistory.length; i2++) {
|
|
3797
|
+
const event = state.fallbackHistory[i2];
|
|
3798
|
+
const nextEvent = state.fallbackHistory[i2 + 1];
|
|
3799
|
+
const periodTokens = getPeriodTokens(entries, event.at, nextEvent?.at ?? null);
|
|
3800
|
+
summary.fallbackPeriods.push({
|
|
3801
|
+
model: event.toModel,
|
|
3802
|
+
from: event.at,
|
|
3803
|
+
to: nextEvent?.at ?? null,
|
|
3804
|
+
...periodTokens
|
|
3805
|
+
});
|
|
3806
|
+
}
|
|
3807
|
+
} catch {}
|
|
3808
|
+
return summary;
|
|
3809
|
+
}
|
|
3810
|
+
function getPeriodTokens(entries, fromMs, toMs) {
|
|
3811
|
+
let inputTokens = 0;
|
|
3812
|
+
let outputTokens = 0;
|
|
3813
|
+
let cost = 0;
|
|
3814
|
+
for (const entry of entries) {
|
|
3815
|
+
const msg = entry.info;
|
|
3816
|
+
if (msg.role !== "assistant")
|
|
3817
|
+
continue;
|
|
3818
|
+
const created = msg.time.created;
|
|
3819
|
+
if (created < fromMs)
|
|
3820
|
+
continue;
|
|
3821
|
+
if (toMs !== null && created >= toMs)
|
|
3822
|
+
continue;
|
|
3823
|
+
inputTokens += msg.tokens?.input ?? 0;
|
|
3824
|
+
outputTokens += msg.tokens?.output ?? 0;
|
|
3825
|
+
cost += msg.cost ?? 0;
|
|
3826
|
+
}
|
|
3827
|
+
return { inputTokens, outputTokens, cost };
|
|
3828
|
+
}
|
|
3829
|
+
|
|
3830
|
+
// src/tools/fallback-status.ts
|
|
3831
|
+
function createFallbackStatusTool(store, config, client, directory) {
|
|
3832
|
+
return tool({
|
|
3833
|
+
description: "Show the current model fallback status: which models are healthy/rate-limited, fallback history for this session, and usage breakdown by model.",
|
|
3834
|
+
args: {
|
|
3835
|
+
verbose: tool.schema.boolean().optional().describe("Include detailed token/cost usage per model period")
|
|
3836
|
+
},
|
|
3837
|
+
async execute(args, context) {
|
|
3838
|
+
const sessionId = context.sessionID;
|
|
3839
|
+
const sessionState = store.sessions.get(sessionId);
|
|
3840
|
+
const allHealth = store.health.getAll();
|
|
3841
|
+
let activeModel = null;
|
|
3842
|
+
let agentName = sessionState.agentName;
|
|
3843
|
+
if (!sessionState.originalModel) {
|
|
3844
|
+
try {
|
|
3845
|
+
const msgs = await client.session.messages({
|
|
3846
|
+
path: { id: sessionId }
|
|
3847
|
+
});
|
|
3848
|
+
const latestUserMessage = getLastUserModelAndAgent(msgs.data);
|
|
3849
|
+
if (latestUserMessage) {
|
|
3850
|
+
activeModel = latestUserMessage.modelKey;
|
|
3851
|
+
if (!agentName && latestUserMessage.agentName) {
|
|
3852
|
+
agentName = latestUserMessage.agentName;
|
|
3853
|
+
}
|
|
3854
|
+
}
|
|
3855
|
+
} catch {}
|
|
3856
|
+
}
|
|
3857
|
+
const agentFile = agentName ? resolveAgentFile(agentName, directory, config.agentDirs.length ? config.agentDirs : undefined) : null;
|
|
3858
|
+
const agentLabel = agentName ? agentFile ? `${agentName} (${agentFile})` : agentName : "(unknown)";
|
|
3859
|
+
const lines = [`## Model Fallback Status
|
|
3860
|
+
`];
|
|
3861
|
+
lines.push(`**Plugin:** ${config.enabled ? "enabled" : "disabled"}`);
|
|
3862
|
+
lines.push("");
|
|
3863
|
+
lines.push("### Current Session");
|
|
3864
|
+
lines.push(`- **Session ID:** ${sessionId}`);
|
|
3865
|
+
lines.push(`- **Agent:** ${agentLabel}`);
|
|
3866
|
+
lines.push(`- **Original model:** ${sessionState.originalModel ?? activeModel ?? "(not set)"}`);
|
|
3867
|
+
lines.push(`- **Current model:** ${sessionState.currentModel ?? activeModel ?? "(not set)"}`);
|
|
3868
|
+
lines.push(`- **Fallback depth:** ${sessionState.fallbackDepth}`);
|
|
3869
|
+
lines.push("");
|
|
3870
|
+
if (sessionState.fallbackHistory.length > 0) {
|
|
3871
|
+
lines.push("### Fallback History");
|
|
3872
|
+
for (const event of sessionState.fallbackHistory) {
|
|
3873
|
+
const time = new Date(event.at).toLocaleTimeString();
|
|
3874
|
+
const eventKind = event.trigger === "preemptive" ? "preemptive" : "reactive";
|
|
3875
|
+
const eventAgent = event.agentName ?? agentName;
|
|
3876
|
+
lines.push(`- **${time}** — \`${event.fromModel}\` → \`${event.toModel}\` (${event.reason}, ${eventKind})` + (eventAgent ? ` · agent: ${eventAgent}` : ""));
|
|
3877
|
+
}
|
|
3878
|
+
lines.push("");
|
|
3879
|
+
}
|
|
3880
|
+
lines.push("### Model Health");
|
|
3881
|
+
if (allHealth.length === 0) {
|
|
3882
|
+
lines.push("- All models healthy (no issues detected)");
|
|
3883
|
+
} else {
|
|
3884
|
+
for (const h of allHealth) {
|
|
3885
|
+
const stateEmoji = h.state === "healthy" ? "✓" : h.state === "cooldown" ? "~" : "✗";
|
|
3886
|
+
let detail = `- \`${h.modelKey}\` — **${h.state}** ${stateEmoji}`;
|
|
3887
|
+
if (h.state === "rate_limited" && h.cooldownExpiresAt) {
|
|
3888
|
+
const secsLeft = Math.max(0, Math.round((h.cooldownExpiresAt - Date.now()) / 1000));
|
|
3889
|
+
detail += ` (cooldown in ${secsLeft}s)`;
|
|
3890
|
+
} else if (h.state === "cooldown" && h.retryOriginalAt) {
|
|
3891
|
+
const secsLeft = Math.max(0, Math.round((h.retryOriginalAt - Date.now()) / 1000));
|
|
3892
|
+
detail += ` (recovery in ${secsLeft}s)`;
|
|
3893
|
+
}
|
|
3894
|
+
if (h.failureCount > 0)
|
|
3895
|
+
detail += ` [${h.failureCount} failures]`;
|
|
3896
|
+
lines.push(detail);
|
|
3897
|
+
}
|
|
3898
|
+
}
|
|
3899
|
+
lines.push("");
|
|
3900
|
+
if (args.verbose && sessionState.fallbackHistory.length > 0) {
|
|
3901
|
+
const usage = await getFallbackUsage(client, sessionState);
|
|
3902
|
+
lines.push("### Usage Summary");
|
|
3903
|
+
lines.push(`- **Total input tokens:** ${usage.totalInputTokens.toLocaleString()}`);
|
|
3904
|
+
lines.push(`- **Total output tokens:** ${usage.totalOutputTokens.toLocaleString()}`);
|
|
3905
|
+
lines.push(`- **Total cost:** $${usage.totalCost.toFixed(6)}`);
|
|
3906
|
+
if (usage.fallbackPeriods.length > 0) {
|
|
3907
|
+
lines.push("");
|
|
3908
|
+
lines.push("**By model period:**");
|
|
3909
|
+
for (const period of usage.fallbackPeriods) {
|
|
3910
|
+
const from = new Date(period.from).toLocaleTimeString();
|
|
3911
|
+
const to = period.to ? new Date(period.to).toLocaleTimeString() : "now";
|
|
3912
|
+
lines.push(`- \`${period.model}\` (${from}–${to}): ${period.inputTokens.toLocaleString()} in / ${period.outputTokens.toLocaleString()} out / $${period.cost.toFixed(6)}`);
|
|
3913
|
+
}
|
|
3914
|
+
}
|
|
3915
|
+
}
|
|
3916
|
+
return lines.join(`
|
|
3917
|
+
`);
|
|
3918
|
+
}
|
|
3919
|
+
});
|
|
3920
|
+
}
|
|
3921
|
+
function getLastUserModelAndAgent(data) {
|
|
3922
|
+
if (!Array.isArray(data))
|
|
3923
|
+
return null;
|
|
3924
|
+
for (let i2 = data.length - 1;i2 >= 0; i2--) {
|
|
3925
|
+
const entry = data[i2];
|
|
3926
|
+
if (!entry || typeof entry !== "object")
|
|
3927
|
+
continue;
|
|
3928
|
+
const info = entry.info;
|
|
3929
|
+
if (!info || typeof info !== "object")
|
|
3930
|
+
continue;
|
|
3931
|
+
if (info.role !== "user")
|
|
3932
|
+
continue;
|
|
3933
|
+
const model = info.model;
|
|
3934
|
+
if (!model || typeof model !== "object")
|
|
3935
|
+
continue;
|
|
3936
|
+
const providerID = model.providerID;
|
|
3937
|
+
const modelID = model.modelID;
|
|
3938
|
+
if (typeof providerID !== "string" || typeof modelID !== "string")
|
|
3939
|
+
continue;
|
|
3940
|
+
const agentName = info.agent;
|
|
3941
|
+
return {
|
|
3942
|
+
modelKey: `${providerID}/${modelID}`,
|
|
3943
|
+
agentName: typeof agentName === "string" ? agentName : null
|
|
3944
|
+
};
|
|
3945
|
+
}
|
|
3946
|
+
return null;
|
|
3947
|
+
}
|
|
3948
|
+
|
|
3949
|
+
// src/preemptive.ts
|
|
3950
|
+
function tryPreemptiveRedirect(sessionId, modelKey2, agentName, store, config, logger) {
|
|
3951
|
+
const sessionState = store.sessions.get(sessionId);
|
|
3952
|
+
store.sessions.setOriginalModel(sessionId, modelKey2);
|
|
3953
|
+
if (sessionState.currentModel !== modelKey2) {
|
|
3954
|
+
const wasOnFallback = sessionState.currentModel !== null && sessionState.currentModel !== sessionState.originalModel;
|
|
3955
|
+
sessionState.currentModel = modelKey2;
|
|
3956
|
+
if (wasOnFallback && modelKey2 === sessionState.originalModel) {
|
|
3957
|
+
sessionState.fallbackDepth = 0;
|
|
3958
|
+
logger.debug("preemptive.depth.reset", { sessionId, modelKey: modelKey2 });
|
|
3959
|
+
}
|
|
3960
|
+
}
|
|
3961
|
+
const health = store.health.get(modelKey2);
|
|
3962
|
+
if (health.state !== "rate_limited") {
|
|
3963
|
+
return { redirected: false };
|
|
3964
|
+
}
|
|
3965
|
+
const chain = resolveFallbackModels(config, agentName);
|
|
3966
|
+
if (chain.length === 0) {
|
|
3967
|
+
logger.debug("preemptive.no-chain", { sessionId, agentName });
|
|
3968
|
+
return { redirected: false };
|
|
3969
|
+
}
|
|
3970
|
+
const fallbackModel = resolveFallbackModel(chain, modelKey2, store.health);
|
|
3971
|
+
if (!fallbackModel) {
|
|
3972
|
+
logger.debug("preemptive.all-exhausted", { sessionId });
|
|
3973
|
+
return { redirected: false };
|
|
3974
|
+
}
|
|
3975
|
+
logger.info("preemptive.redirect", {
|
|
3976
|
+
sessionId,
|
|
3977
|
+
from: modelKey2,
|
|
3978
|
+
to: fallbackModel
|
|
3979
|
+
});
|
|
3980
|
+
store.sessions.recordPreemptiveRedirect(sessionId, modelKey2, fallbackModel, agentName);
|
|
3981
|
+
return { redirected: true, fallbackModel };
|
|
3982
|
+
}
|
|
3983
|
+
|
|
3984
|
+
// src/plugin.ts
|
|
3985
|
+
var createPlugin = async ({ client, directory }) => {
|
|
3986
|
+
const { config, path: configPath, warnings, migrated } = loadConfig(directory);
|
|
3987
|
+
const logger = new Logger(client, config.logPath, config.logging);
|
|
3988
|
+
const cmdPath = join4(homedir5(), ".config/opencode/commands/fallback-status.md");
|
|
3989
|
+
try {
|
|
3990
|
+
if (!existsSync3(cmdPath)) {
|
|
3991
|
+
mkdirSync2(dirname2(cmdPath), { recursive: true });
|
|
3992
|
+
writeFileSync(cmdPath, `Call the fallback-status tool and display the full output.
|
|
3993
|
+
`);
|
|
3994
|
+
}
|
|
3995
|
+
} catch (err) {
|
|
3996
|
+
logger.warn("fallback-status.command.write.failed", {
|
|
3997
|
+
cmdPath,
|
|
3998
|
+
err: String(err)
|
|
3999
|
+
});
|
|
4000
|
+
}
|
|
4001
|
+
logger.info("plugin.init", {
|
|
4002
|
+
configPath,
|
|
4003
|
+
enabled: config.enabled,
|
|
4004
|
+
migrated,
|
|
4005
|
+
agentCount: Object.keys(config.agents).length
|
|
4006
|
+
});
|
|
4007
|
+
for (const w of warnings) {
|
|
4008
|
+
logger.warn("config.warning", { message: w });
|
|
4009
|
+
}
|
|
4010
|
+
if (migrated) {
|
|
4011
|
+
logger.info("config.migrated", {
|
|
4012
|
+
message: "Auto-migrated from old rate-limit-fallback.json format"
|
|
4013
|
+
});
|
|
4014
|
+
}
|
|
4015
|
+
if (!config.enabled) {
|
|
4016
|
+
logger.info("plugin.disabled");
|
|
4017
|
+
return {};
|
|
4018
|
+
}
|
|
4019
|
+
const store = new FallbackStore(config, logger);
|
|
4020
|
+
const hooks = {
|
|
4021
|
+
async event({ event }) {
|
|
4022
|
+
await handleEvent(event, client, store, config, logger, directory);
|
|
4023
|
+
},
|
|
4024
|
+
"chat.message": async (input, output) => {
|
|
4025
|
+
if (!input.model)
|
|
4026
|
+
return;
|
|
4027
|
+
const modelKey2 = `${input.model.providerID}/${input.model.modelID}`;
|
|
4028
|
+
const sessionState = store.sessions.get(input.sessionID);
|
|
4029
|
+
if (input.agent) {
|
|
4030
|
+
store.sessions.setAgentName(input.sessionID, input.agent);
|
|
4031
|
+
if (!sessionState.agentFile) {
|
|
4032
|
+
const absPath = resolveAgentFile(input.agent, directory, config.agentDirs?.length ? config.agentDirs : undefined);
|
|
4033
|
+
if (absPath) {
|
|
4034
|
+
store.sessions.setAgentFile(input.sessionID, toRelativeAgentPath(absPath, directory));
|
|
4035
|
+
}
|
|
4036
|
+
}
|
|
4037
|
+
}
|
|
4038
|
+
const result = tryPreemptiveRedirect(input.sessionID, modelKey2, sessionState.agentName, store, config, logger);
|
|
4039
|
+
if (result.redirected && result.fallbackModel) {
|
|
4040
|
+
const [providerID, ...rest] = result.fallbackModel.split("/");
|
|
4041
|
+
const modelID = rest.join("/");
|
|
4042
|
+
output.message.model = { providerID, modelID };
|
|
4043
|
+
logger.debug("chat.message.redirected", {
|
|
4044
|
+
sessionID: input.sessionID,
|
|
4045
|
+
from: modelKey2,
|
|
4046
|
+
to: result.fallbackModel
|
|
4047
|
+
});
|
|
4048
|
+
}
|
|
4049
|
+
const current = sessionState.currentModel;
|
|
4050
|
+
const original = sessionState.originalModel;
|
|
4051
|
+
if (current && original && current !== original) {
|
|
4052
|
+
notifyFallbackActive(client, original, current).catch(() => {});
|
|
4053
|
+
}
|
|
4054
|
+
},
|
|
4055
|
+
tool: {
|
|
4056
|
+
"fallback-status": createFallbackStatusTool(store, config, client, directory)
|
|
4057
|
+
}
|
|
4058
|
+
};
|
|
4059
|
+
return hooks;
|
|
4060
|
+
};
|
|
4061
|
+
async function handleEvent(event, client, store, config, logger, directory) {
|
|
4062
|
+
if (event.type === "session.status") {
|
|
4063
|
+
const { sessionID, status } = event.properties;
|
|
4064
|
+
if (status.type === "retry") {
|
|
4065
|
+
await handleRetry(sessionID, status.message, client, store, config, logger, directory);
|
|
4066
|
+
} else if (status.type === "idle") {
|
|
4067
|
+
await handleIdle(sessionID, client, store, config, logger);
|
|
4068
|
+
}
|
|
4069
|
+
return;
|
|
4070
|
+
}
|
|
4071
|
+
if (event.type === "session.error") {
|
|
4072
|
+
const { sessionID, error } = event.properties;
|
|
4073
|
+
if (!sessionID || !error)
|
|
4074
|
+
return;
|
|
4075
|
+
if (error.name === "APIError") {
|
|
4076
|
+
const apiMessage = typeof error.data?.message === "string" ? error.data.message : "";
|
|
4077
|
+
const apiStatusCode = typeof error.data?.statusCode === "number" ? error.data.statusCode : undefined;
|
|
4078
|
+
const category = classifyError(apiMessage, apiStatusCode);
|
|
4079
|
+
if (config.defaults.fallbackOn.includes(category)) {
|
|
4080
|
+
const result = await attemptFallback(sessionID, category, client, store, config, logger, directory);
|
|
4081
|
+
if (result.success && result.fallbackModel) {
|
|
4082
|
+
const state = store.sessions.get(sessionID);
|
|
4083
|
+
await notifyFallback(client, state.originalModel, result.fallbackModel, category);
|
|
4084
|
+
}
|
|
4085
|
+
}
|
|
4086
|
+
}
|
|
4087
|
+
return;
|
|
4088
|
+
}
|
|
4089
|
+
if (event.type === "session.deleted") {
|
|
4090
|
+
const sessionID = event.properties.info.id;
|
|
4091
|
+
store.sessions.delete(sessionID);
|
|
4092
|
+
return;
|
|
4093
|
+
}
|
|
4094
|
+
if (event.type === "session.compacted") {
|
|
4095
|
+
const sessionID = event.properties.sessionID;
|
|
4096
|
+
store.sessions.partialReset(sessionID);
|
|
4097
|
+
logger.info("session.compacted.reset", { sessionID });
|
|
4098
|
+
return;
|
|
4099
|
+
}
|
|
4100
|
+
}
|
|
4101
|
+
async function handleRetry(sessionId, message, client, store, config, logger, directory) {
|
|
4102
|
+
if (!matchesAnyPattern(message, config.patterns)) {
|
|
4103
|
+
return;
|
|
4104
|
+
}
|
|
4105
|
+
const category = classifyError(message);
|
|
4106
|
+
if (!config.defaults.fallbackOn.includes(category)) {
|
|
4107
|
+
logger.debug("retry.ignored", { sessionId, message, category });
|
|
4108
|
+
return;
|
|
4109
|
+
}
|
|
4110
|
+
const sessionState = store.sessions.get(sessionId);
|
|
4111
|
+
if (!sessionState.currentModel) {
|
|
4112
|
+
try {
|
|
4113
|
+
const msgs = await client.session.messages({ path: { id: sessionId } });
|
|
4114
|
+
const latestUserMessage = getLastUserModelAndAgent2(msgs.data);
|
|
4115
|
+
if (latestUserMessage?.modelKey) {
|
|
4116
|
+
store.sessions.setOriginalModel(sessionId, latestUserMessage.modelKey);
|
|
4117
|
+
if (latestUserMessage.agentName) {
|
|
4118
|
+
store.sessions.setAgentName(sessionId, latestUserMessage.agentName);
|
|
4119
|
+
const absPath = resolveAgentFile(latestUserMessage.agentName, directory, config.agentDirs?.length ? config.agentDirs : undefined);
|
|
4120
|
+
if (absPath) {
|
|
4121
|
+
store.sessions.setAgentFile(sessionId, toRelativeAgentPath(absPath, directory));
|
|
4122
|
+
}
|
|
4123
|
+
}
|
|
4124
|
+
}
|
|
4125
|
+
} catch {}
|
|
4126
|
+
}
|
|
4127
|
+
if (sessionState.agentName && !sessionState.agentFile) {
|
|
4128
|
+
const absPath = resolveAgentFile(sessionState.agentName, directory, config.agentDirs?.length ? config.agentDirs : undefined);
|
|
4129
|
+
if (absPath) {
|
|
4130
|
+
store.sessions.setAgentFile(sessionId, toRelativeAgentPath(absPath, directory));
|
|
4131
|
+
}
|
|
4132
|
+
}
|
|
4133
|
+
logger.info("retry.detected", {
|
|
4134
|
+
sessionId,
|
|
4135
|
+
message,
|
|
4136
|
+
category,
|
|
4137
|
+
agentName: sessionState.agentName,
|
|
4138
|
+
agentFile: sessionState.agentFile
|
|
4139
|
+
});
|
|
4140
|
+
const result = await attemptFallback(sessionId, category, client, store, config, logger, directory);
|
|
4141
|
+
if (result.success && result.fallbackModel) {
|
|
4142
|
+
const state = store.sessions.get(sessionId);
|
|
4143
|
+
await notifyFallback(client, state.originalModel, result.fallbackModel, category);
|
|
4144
|
+
}
|
|
4145
|
+
}
|
|
4146
|
+
async function handleIdle(sessionId, client, store, _config, logger) {
|
|
4147
|
+
const state = store.sessions.get(sessionId);
|
|
4148
|
+
if (!state.originalModel)
|
|
4149
|
+
return;
|
|
4150
|
+
if (state.currentModel === state.originalModel) {
|
|
4151
|
+
state.recoveryNotifiedForModel = null;
|
|
4152
|
+
return;
|
|
4153
|
+
}
|
|
4154
|
+
const health = store.health.get(state.originalModel);
|
|
4155
|
+
if (health.state !== "healthy") {
|
|
4156
|
+
state.recoveryNotifiedForModel = null;
|
|
4157
|
+
return;
|
|
4158
|
+
}
|
|
4159
|
+
if (state.recoveryNotifiedForModel === state.originalModel)
|
|
4160
|
+
return;
|
|
4161
|
+
logger.info("recovery.available", {
|
|
4162
|
+
sessionId,
|
|
4163
|
+
originalModel: state.originalModel
|
|
4164
|
+
});
|
|
4165
|
+
await notifyRecovery(client, state.originalModel);
|
|
4166
|
+
state.recoveryNotifiedForModel = state.originalModel;
|
|
4167
|
+
}
|
|
4168
|
+
function getLastUserModelAndAgent2(data) {
|
|
4169
|
+
if (!Array.isArray(data))
|
|
4170
|
+
return null;
|
|
4171
|
+
for (let i2 = data.length - 1;i2 >= 0; i2--) {
|
|
4172
|
+
const entry = data[i2];
|
|
4173
|
+
if (!entry || typeof entry !== "object")
|
|
4174
|
+
continue;
|
|
4175
|
+
const info = entry.info;
|
|
4176
|
+
if (!info || typeof info !== "object")
|
|
4177
|
+
continue;
|
|
4178
|
+
const role = info.role;
|
|
4179
|
+
if (role !== "user")
|
|
4180
|
+
continue;
|
|
4181
|
+
const model = info.model;
|
|
4182
|
+
if (!model || typeof model !== "object")
|
|
4183
|
+
continue;
|
|
4184
|
+
const providerID = model.providerID;
|
|
4185
|
+
const modelID = model.modelID;
|
|
4186
|
+
if (typeof providerID !== "string" || typeof modelID !== "string")
|
|
4187
|
+
continue;
|
|
4188
|
+
const agent = info.agent;
|
|
4189
|
+
return {
|
|
4190
|
+
modelKey: `${providerID}/${modelID}`,
|
|
4191
|
+
agentName: typeof agent === "string" ? agent : null
|
|
4192
|
+
};
|
|
4193
|
+
}
|
|
4194
|
+
return null;
|
|
4195
|
+
}
|
|
4196
|
+
export {
|
|
4197
|
+
createPlugin
|
|
4198
|
+
};
|