@first-ch/tools-mcp 0.4.1 → 0.24.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +52 -4
- package/aspect-ratio.mjs +706 -0
- package/base64.mjs +356 -0
- package/color.mjs +629 -0
- package/cron.mjs +633 -0
- package/diff.mjs +322 -0
- package/hash.mjs +234 -0
- package/html-escape.mjs +308 -0
- package/json-yaml.mjs +1693 -0
- package/jwt.mjs +639 -0
- package/lib.mjs +103 -0
- package/markdown-table.mjs +641 -0
- package/marp-theme.css +51 -0
- package/marp.mjs +219 -0
- package/package.json +130 -3
- package/px-rem.mjs +488 -0
- package/qr.mjs +744 -0
- package/server.mjs +942 -2
- package/sql-format.mjs +694 -0
- package/testdata.mjs +608 -0
- package/unixtime.mjs +505 -0
- package/url.mjs +415 -0
- package/user-agent.mjs +633 -0
- package/uuid.mjs +238 -0
package/json-yaml.mjs
ADDED
|
@@ -0,0 +1,1693 @@
|
|
|
1
|
+
// JSON ⇄ YAML 相互変換&構文フォーマッター(tools.first-ch.com/json-yaml/ と同一ロジック)
|
|
2
|
+
//
|
|
3
|
+
// 「変換コア」ブロックは site 側の site/json-yaml/app.js と同一の実装。
|
|
4
|
+
// 2箇所ルール: 片方を直したらもう片方も同じ内容で直す(site側が正本)。
|
|
5
|
+
// 使っているのは String / RegExp / Object だけなので、ブラウザ版のコードをそのまま持ってこられる
|
|
6
|
+
// (YAMLの解析・生成も自前実装で、js-yaml 等の外部ライブラリには依存しない)。
|
|
7
|
+
import { readFile, writeFile } from 'node:fs/promises';
|
|
8
|
+
import { basename } from 'node:path';
|
|
9
|
+
|
|
10
|
+
/* ==================== ここから変換コア(site / MCP で同一) ==================== */
|
|
11
|
+
|
|
12
|
+
// 入れ子の深さの上限(壊れた入力でスタックを食い潰さないための保険)
|
|
13
|
+
const JY_MAX_DEPTH = 200;
|
|
14
|
+
|
|
15
|
+
// 指摘事項の重さ。warn = 出力が意図と変わる可能性あり / info = 知っておくと良い
|
|
16
|
+
const JY_NOTE_LEVEL = {
|
|
17
|
+
DUPLICATE_KEY: 'warn',
|
|
18
|
+
NUMBER_PRECISION: 'warn',
|
|
19
|
+
NONFINITE_OUTPUT: 'warn',
|
|
20
|
+
LONE_SURROGATE: 'warn',
|
|
21
|
+
MULTI_DOC: 'info',
|
|
22
|
+
JSON_COMMENT: 'warn',
|
|
23
|
+
JSON_TRAILING_COMMA: 'warn',
|
|
24
|
+
JSON_SINGLE_QUOTE: 'warn',
|
|
25
|
+
JSON_UNQUOTED_KEY: 'warn',
|
|
26
|
+
JSON_RELAXED_NUMBER: 'warn',
|
|
27
|
+
JSON_RAW_CONTROL: 'warn',
|
|
28
|
+
JSON_NONFINITE: 'warn',
|
|
29
|
+
YAML_LEADING_ZERO: 'warn',
|
|
30
|
+
YAML11_BOOL: 'info',
|
|
31
|
+
YAML_TIMESTAMP: 'info',
|
|
32
|
+
YAML_SEXAGESIMAL: 'warn',
|
|
33
|
+
YAML_MERGE_KEY: 'info',
|
|
34
|
+
YAML_BAD_MERGE: 'warn',
|
|
35
|
+
YAML_NONSTRING_KEY: 'warn',
|
|
36
|
+
YAML_DIRECTIVE: 'info',
|
|
37
|
+
YAML_UNKNOWN_TAG: 'warn',
|
|
38
|
+
YAML_BINARY: 'info',
|
|
39
|
+
YAML_ALIAS_EXPANDED: 'info',
|
|
40
|
+
};
|
|
41
|
+
|
|
42
|
+
// YAML 1.1 が真偽値として扱っていた綴り。1.2 では文字列だが、
|
|
43
|
+
// 読み込む側のパーサが 1.1 のままだと意味が変わるので指摘する(いわゆる Norway problem)。
|
|
44
|
+
const JY_YAML11_BOOL = /^(y|Y|yes|Yes|YES|n|N|no|No|NO|on|On|ON|off|Off|OFF)$/;
|
|
45
|
+
|
|
46
|
+
// YAML 1.1 の60進数表記。1.2 では文字列だが、PyYAML 等では 12:30 が 750 になる。
|
|
47
|
+
const JY_SEXAGESIMAL = /^[-+]?[0-9][0-9_]*(:[0-5]?[0-9])+$/;
|
|
48
|
+
|
|
49
|
+
/** 指摘事項を種類ごとにまとめて数える入れ物 */
|
|
50
|
+
function jyNotes() {
|
|
51
|
+
const list = [];
|
|
52
|
+
const byCode = Object.create(null);
|
|
53
|
+
return {
|
|
54
|
+
list,
|
|
55
|
+
add(code, item, line) {
|
|
56
|
+
let n = byCode[code];
|
|
57
|
+
if (!n) {
|
|
58
|
+
n = { code, level: JY_NOTE_LEVEL[code] || 'warn', count: 0, items: [], lines: [] };
|
|
59
|
+
byCode[code] = n;
|
|
60
|
+
list.push(n);
|
|
61
|
+
}
|
|
62
|
+
n.count += 1;
|
|
63
|
+
if (item !== undefined && item !== null && n.items.length < 6 && n.items.indexOf(item) === -1) n.items.push(item);
|
|
64
|
+
if (line && n.lines.length < 6 && n.lines.indexOf(line) === -1) n.lines.push(line);
|
|
65
|
+
return n;
|
|
66
|
+
},
|
|
67
|
+
};
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** 文字列中のインデックスを 1 始まりの行・桁へ */
|
|
71
|
+
function jyLineCol(src, index) {
|
|
72
|
+
let line = 1;
|
|
73
|
+
let lastBreak = -1;
|
|
74
|
+
const end = Math.min(index, src.length);
|
|
75
|
+
for (let k = 0; k < end; k++) {
|
|
76
|
+
if (src.charCodeAt(k) === 10) {
|
|
77
|
+
line += 1;
|
|
78
|
+
lastBreak = k;
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
return { line, col: end - lastBreak };
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
const jyIsPlainObject = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* YAML のプレーンスカラーを値へ解決する(YAML 1.2 core schema)。
|
|
88
|
+
* 出力側(formatYaml)でも「引用符なしで書けるか」の判定に使うので、副作用なしの純関数にしてある。
|
|
89
|
+
*/
|
|
90
|
+
function jyResolveScalar(s) {
|
|
91
|
+
if (s === '' || s === '~' || s === 'null' || s === 'Null' || s === 'NULL') return null;
|
|
92
|
+
if (s === 'true' || s === 'True' || s === 'TRUE') return true;
|
|
93
|
+
if (s === 'false' || s === 'False' || s === 'FALSE') return false;
|
|
94
|
+
if (/^[-+]?[0-9]+$/.test(s)) return Number(s);
|
|
95
|
+
if (/^0o[0-7]+$/.test(s)) return parseInt(s.slice(2), 8);
|
|
96
|
+
if (/^[-+]?0x[0-9a-fA-F]+$/.test(s)) {
|
|
97
|
+
const n = parseInt(s.replace(/^[-+]/, '').slice(2), 16);
|
|
98
|
+
return s.charAt(0) === '-' ? -n : n;
|
|
99
|
+
}
|
|
100
|
+
if (/^[-+]?(\.[0-9]+|[0-9]+(\.[0-9]*)?)([eE][-+]?[0-9]+)?$/.test(s)) return Number(s);
|
|
101
|
+
if (/^[-+]?\.(inf|Inf|INF)$/.test(s)) return s.charAt(0) === '-' ? -Infinity : Infinity;
|
|
102
|
+
if (/^\.(nan|NaN|NAN)$/.test(s)) return NaN;
|
|
103
|
+
return s;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** プレーンスカラーについて出す指摘のコード(値そのものは変えない) */
|
|
107
|
+
function jyScalarNotes(s) {
|
|
108
|
+
const out = [];
|
|
109
|
+
if (/^[-+]?0[0-9]+$/.test(s)) out.push('YAML_LEADING_ZERO');
|
|
110
|
+
if (/^[-+]?[0-9]+$/.test(s) && !Number.isSafeInteger(Number(s))) out.push('NUMBER_PRECISION');
|
|
111
|
+
if (JY_YAML11_BOOL.test(s)) out.push('YAML11_BOOL');
|
|
112
|
+
if (/^[0-9]{4}-[0-9]{2}-[0-9]{2}([Tt ].*)?$/.test(s)) out.push('YAML_TIMESTAMP');
|
|
113
|
+
if (JY_SEXAGESIMAL.test(s)) out.push('YAML_SEXAGESIMAL');
|
|
114
|
+
return out;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/* ---------------------------------------------------------------------------
|
|
118
|
+
* JSON パーサ
|
|
119
|
+
*
|
|
120
|
+
* JSON.parse を使わず自前で読むのは、エラーの行・桁をブラウザ差なく取るため。
|
|
121
|
+
* relaxed(既定 true)では tsconfig 系のコメント・末尾カンマ・シングルクォート・
|
|
122
|
+
* 裸のキーも受け取り、「JSONとしては不正」と指摘したうえで変換する。
|
|
123
|
+
* ------------------------------------------------------------------------- */
|
|
124
|
+
function jyParseJson(text, opts) {
|
|
125
|
+
const o = opts || {};
|
|
126
|
+
const relaxed = o.relaxed !== false;
|
|
127
|
+
const src = String(text).replace(/^\uFEFF/, '');
|
|
128
|
+
const N = jyNotes();
|
|
129
|
+
let i = 0;
|
|
130
|
+
let depth = 0;
|
|
131
|
+
|
|
132
|
+
const fail = (code, at, found) => {
|
|
133
|
+
const e = new Error(code);
|
|
134
|
+
e.jy = { code, index: at === undefined ? i : at, found };
|
|
135
|
+
throw e;
|
|
136
|
+
};
|
|
137
|
+
const lineOf = (at) => jyLineCol(src, at).line;
|
|
138
|
+
const here = () => (i < src.length ? src.charAt(i) : 'EOF');
|
|
139
|
+
|
|
140
|
+
function ws() {
|
|
141
|
+
for (;;) {
|
|
142
|
+
const c = src.charCodeAt(i);
|
|
143
|
+
if (c === 32 || c === 9 || c === 10 || c === 13) {
|
|
144
|
+
i += 1;
|
|
145
|
+
continue;
|
|
146
|
+
}
|
|
147
|
+
if (src.charAt(i) === '/' && (src.charAt(i + 1) === '/' || src.charAt(i + 1) === '*')) {
|
|
148
|
+
if (!relaxed) fail('JSON_COMMENT', i);
|
|
149
|
+
N.add('JSON_COMMENT', null, lineOf(i));
|
|
150
|
+
if (src.charAt(i + 1) === '/') {
|
|
151
|
+
while (i < src.length && src.charAt(i) !== '\n') i += 1;
|
|
152
|
+
} else {
|
|
153
|
+
const end = src.indexOf('*/', i + 2);
|
|
154
|
+
if (end === -1) fail('JSON_UNTERMINATED_COMMENT', i);
|
|
155
|
+
i = end + 2;
|
|
156
|
+
}
|
|
157
|
+
continue;
|
|
158
|
+
}
|
|
159
|
+
return;
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
function readString(quote) {
|
|
164
|
+
const start = i;
|
|
165
|
+
i += 1;
|
|
166
|
+
let out = '';
|
|
167
|
+
for (;;) {
|
|
168
|
+
if (i >= src.length) fail('JSON_UNTERMINATED_STRING', start, quote);
|
|
169
|
+
const c = src.charAt(i);
|
|
170
|
+
if (c === quote) {
|
|
171
|
+
i += 1;
|
|
172
|
+
return out;
|
|
173
|
+
}
|
|
174
|
+
if (c === '\\') {
|
|
175
|
+
const e = src.charAt(i + 1);
|
|
176
|
+
if (e === 'u') {
|
|
177
|
+
const hex = src.substr(i + 2, 4);
|
|
178
|
+
if (!/^[0-9a-fA-F]{4}$/.test(hex)) fail('JSON_BAD_ESCAPE', i, src.substr(i, 6));
|
|
179
|
+
out += String.fromCharCode(parseInt(hex, 16));
|
|
180
|
+
i += 6;
|
|
181
|
+
continue;
|
|
182
|
+
}
|
|
183
|
+
const simple = { '"': '"', "'": "'", '\\': '\\', '/': '/', b: '\b', f: '\f', n: '\n', r: '\r', t: '\t' };
|
|
184
|
+
if (simple[e] === undefined) fail('JSON_BAD_ESCAPE', i, '\\' + (e || ''));
|
|
185
|
+
if (e === "'") {
|
|
186
|
+
if (!relaxed) fail('JSON_BAD_ESCAPE', i, "\\'");
|
|
187
|
+
N.add('JSON_RELAXED_NUMBER', "\\'", lineOf(i));
|
|
188
|
+
}
|
|
189
|
+
out += simple[e];
|
|
190
|
+
i += 2;
|
|
191
|
+
continue;
|
|
192
|
+
}
|
|
193
|
+
const code = src.charCodeAt(i);
|
|
194
|
+
if (code < 0x20) {
|
|
195
|
+
if (!relaxed) fail('JSON_RAW_CONTROL', i, 'U+' + code.toString(16).toUpperCase().padStart(4, '0'));
|
|
196
|
+
N.add('JSON_RAW_CONTROL', 'U+' + code.toString(16).toUpperCase().padStart(4, '0'), lineOf(i));
|
|
197
|
+
}
|
|
198
|
+
out += c;
|
|
199
|
+
i += 1;
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
function readLiteral() {
|
|
204
|
+
const start = i;
|
|
205
|
+
while (i < src.length && ',}]: \t\r\n'.indexOf(src.charAt(i)) === -1) {
|
|
206
|
+
if (src.charAt(i) === '/' && (src.charAt(i + 1) === '/' || src.charAt(i + 1) === '*')) break;
|
|
207
|
+
i += 1;
|
|
208
|
+
}
|
|
209
|
+
const tok = src.slice(start, i);
|
|
210
|
+
if (tok === '') fail('JSON_VALUE_EXPECTED', start, here());
|
|
211
|
+
if (tok === 'true') return true;
|
|
212
|
+
if (tok === 'false') return false;
|
|
213
|
+
if (tok === 'null') return null;
|
|
214
|
+
if (/^-?(0|[1-9][0-9]*)(\.[0-9]+)?([eE][-+]?[0-9]+)?$/.test(tok)) {
|
|
215
|
+
const n = Number(tok);
|
|
216
|
+
if (/^-?[0-9]+$/.test(tok) && !Number.isSafeInteger(n)) N.add('NUMBER_PRECISION', tok, lineOf(start));
|
|
217
|
+
return n;
|
|
218
|
+
}
|
|
219
|
+
// JSON としては不正だが読めるもの(+1 / .5 / 1. / 0755 / 0x1F / NaN / Infinity)
|
|
220
|
+
if (/^[-+]?(NaN|Infinity)$/.test(tok)) {
|
|
221
|
+
if (!relaxed) fail('JSON_BAD_TOKEN', start, tok);
|
|
222
|
+
N.add('JSON_NONFINITE', tok, lineOf(start));
|
|
223
|
+
return tok.charAt(0) === '-' ? (tok.indexOf('NaN') !== -1 ? NaN : -Infinity) : tok.indexOf('NaN') !== -1 ? NaN : Infinity;
|
|
224
|
+
}
|
|
225
|
+
if (/^[-+]?(0[xX][0-9a-fA-F]+|[0-9]*\.?[0-9]*([eE][-+]?[0-9]+)?)$/.test(tok) && /[0-9]/.test(tok)) {
|
|
226
|
+
if (!relaxed) fail('JSON_BAD_TOKEN', start, tok);
|
|
227
|
+
N.add('JSON_RELAXED_NUMBER', tok, lineOf(start));
|
|
228
|
+
const n = /^[-+]?0[xX]/.test(tok)
|
|
229
|
+
? (tok.charAt(0) === '-' ? -1 : 1) * parseInt(tok.replace(/^[-+]/, '').slice(2), 16)
|
|
230
|
+
: Number(tok);
|
|
231
|
+
if (!Number.isFinite(n)) fail('JSON_BAD_TOKEN', start, tok);
|
|
232
|
+
if (Number.isInteger(n) && !Number.isSafeInteger(n)) N.add('NUMBER_PRECISION', tok, lineOf(start));
|
|
233
|
+
return n;
|
|
234
|
+
}
|
|
235
|
+
fail('JSON_BAD_TOKEN', start, tok.length > 24 ? tok.slice(0, 24) + '…' : tok);
|
|
236
|
+
return null;
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
function readKey() {
|
|
240
|
+
const c = src.charAt(i);
|
|
241
|
+
if (c === '"') return readString('"');
|
|
242
|
+
if (c === "'") {
|
|
243
|
+
if (!relaxed) fail('JSON_SINGLE_QUOTE', i);
|
|
244
|
+
N.add('JSON_SINGLE_QUOTE', null, lineOf(i));
|
|
245
|
+
return readString("'");
|
|
246
|
+
}
|
|
247
|
+
const m = /^[A-Za-z_$][A-Za-z0-9_$-]*/.exec(src.slice(i));
|
|
248
|
+
if (!m) fail('JSON_KEY_EXPECTED', i, here());
|
|
249
|
+
if (!relaxed) fail('JSON_UNQUOTED_KEY', i, m[0]);
|
|
250
|
+
N.add('JSON_UNQUOTED_KEY', m[0], lineOf(i));
|
|
251
|
+
i += m[0].length;
|
|
252
|
+
return m[0];
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
function readObject() {
|
|
256
|
+
depth += 1;
|
|
257
|
+
if (depth > JY_MAX_DEPTH) fail('TOO_DEEP', i);
|
|
258
|
+
i += 1;
|
|
259
|
+
// __proto__ を書き込まれてもプロトタイプ汚染にならないよう、素のオブジェクトは使わない
|
|
260
|
+
const out = Object.create(null);
|
|
261
|
+
ws();
|
|
262
|
+
if (src.charAt(i) === '}') {
|
|
263
|
+
i += 1;
|
|
264
|
+
depth -= 1;
|
|
265
|
+
return out;
|
|
266
|
+
}
|
|
267
|
+
for (;;) {
|
|
268
|
+
ws();
|
|
269
|
+
const at = i;
|
|
270
|
+
const key = readKey();
|
|
271
|
+
ws();
|
|
272
|
+
if (src.charAt(i) !== ':') fail('JSON_COLON_EXPECTED', i, here());
|
|
273
|
+
i += 1;
|
|
274
|
+
const value = readValue();
|
|
275
|
+
if (Object.prototype.hasOwnProperty.call(out, key)) N.add('DUPLICATE_KEY', key, lineOf(at));
|
|
276
|
+
out[key] = value;
|
|
277
|
+
ws();
|
|
278
|
+
if (src.charAt(i) === ',') {
|
|
279
|
+
i += 1;
|
|
280
|
+
ws();
|
|
281
|
+
if (src.charAt(i) === '}') {
|
|
282
|
+
if (!relaxed) fail('JSON_TRAILING_COMMA', i);
|
|
283
|
+
N.add('JSON_TRAILING_COMMA', null, lineOf(i));
|
|
284
|
+
i += 1;
|
|
285
|
+
depth -= 1;
|
|
286
|
+
return out;
|
|
287
|
+
}
|
|
288
|
+
continue;
|
|
289
|
+
}
|
|
290
|
+
if (src.charAt(i) === '}') {
|
|
291
|
+
i += 1;
|
|
292
|
+
depth -= 1;
|
|
293
|
+
return out;
|
|
294
|
+
}
|
|
295
|
+
fail('JSON_COMMA_EXPECTED', i, here());
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
function readArray() {
|
|
300
|
+
depth += 1;
|
|
301
|
+
if (depth > JY_MAX_DEPTH) fail('TOO_DEEP', i);
|
|
302
|
+
i += 1;
|
|
303
|
+
const out = [];
|
|
304
|
+
ws();
|
|
305
|
+
if (src.charAt(i) === ']') {
|
|
306
|
+
i += 1;
|
|
307
|
+
depth -= 1;
|
|
308
|
+
return out;
|
|
309
|
+
}
|
|
310
|
+
for (;;) {
|
|
311
|
+
out.push(readValue());
|
|
312
|
+
ws();
|
|
313
|
+
if (src.charAt(i) === ',') {
|
|
314
|
+
i += 1;
|
|
315
|
+
ws();
|
|
316
|
+
if (src.charAt(i) === ']') {
|
|
317
|
+
if (!relaxed) fail('JSON_TRAILING_COMMA', i);
|
|
318
|
+
N.add('JSON_TRAILING_COMMA', null, lineOf(i));
|
|
319
|
+
i += 1;
|
|
320
|
+
depth -= 1;
|
|
321
|
+
return out;
|
|
322
|
+
}
|
|
323
|
+
continue;
|
|
324
|
+
}
|
|
325
|
+
if (src.charAt(i) === ']') {
|
|
326
|
+
i += 1;
|
|
327
|
+
depth -= 1;
|
|
328
|
+
return out;
|
|
329
|
+
}
|
|
330
|
+
fail('JSON_COMMA_EXPECTED', i, here());
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
function readValue() {
|
|
335
|
+
ws();
|
|
336
|
+
if (i >= src.length) fail('JSON_UNEXPECTED_END', i);
|
|
337
|
+
const c = src.charAt(i);
|
|
338
|
+
if (c === '{') return readObject();
|
|
339
|
+
if (c === '[') return readArray();
|
|
340
|
+
if (c === '"') return readString('"');
|
|
341
|
+
if (c === "'") {
|
|
342
|
+
if (!relaxed) fail('JSON_SINGLE_QUOTE', i);
|
|
343
|
+
N.add('JSON_SINGLE_QUOTE', null, lineOf(i));
|
|
344
|
+
return readString("'");
|
|
345
|
+
}
|
|
346
|
+
return readLiteral();
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
try {
|
|
350
|
+
ws();
|
|
351
|
+
if (i >= src.length) return { ok: false, error: { code: 'EMPTY_INPUT', line: 1, col: 1 }, notes: N.list };
|
|
352
|
+
const value = readValue();
|
|
353
|
+
ws();
|
|
354
|
+
if (i < src.length) fail('JSON_TRAILING_DATA', i, here());
|
|
355
|
+
return { ok: true, value, notes: N.list };
|
|
356
|
+
} catch (e) {
|
|
357
|
+
if (!e.jy) throw e;
|
|
358
|
+
const pos = jyLineCol(src, e.jy.index);
|
|
359
|
+
return {
|
|
360
|
+
ok: false,
|
|
361
|
+
error: { code: e.jy.code, line: pos.line, col: pos.col, found: e.jy.found },
|
|
362
|
+
notes: N.list,
|
|
363
|
+
};
|
|
364
|
+
}
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
/* ---------------------------------------------------------------------------
|
|
368
|
+
* YAML パーサ(インデント方式のブロック構造 + フロー表記)
|
|
369
|
+
*
|
|
370
|
+
* 対応: 複数ドキュメント(--- / ...)・ブロックマップ / シーケンス・フロー表記 [] {}・
|
|
371
|
+
* 引用スカラー(複数行・エスケープ)・ブロックスカラー | > と chomping - + と明示インデント・
|
|
372
|
+
* アンカー &a / エイリアス *a / マージキー <<・タグ !!str !!int 等・コメント。
|
|
373
|
+
* 非対応: 明示キー "? " と、"!" による独自タグの型付け(エラー / 指摘にして黙って壊さない)。
|
|
374
|
+
* ------------------------------------------------------------------------- */
|
|
375
|
+
function jyParseYaml(text) {
|
|
376
|
+
const N = jyNotes();
|
|
377
|
+
const src = String(text).replace(/^\uFEFF/, '').replace(/\r\n?/g, '\n');
|
|
378
|
+
const lines = src.split('\n').map((raw, k) => {
|
|
379
|
+
const ws = /^[ \t]*/.exec(raw)[0];
|
|
380
|
+
const body = raw.slice(ws.length);
|
|
381
|
+
return { n: k + 1, text: raw, ws, indent: ws.length, body, blank: body === '', comment: body.charAt(0) === '#' };
|
|
382
|
+
});
|
|
383
|
+
const anchors = Object.create(null);
|
|
384
|
+
let p = 0;
|
|
385
|
+
let depth = 0;
|
|
386
|
+
let usedAlias = false;
|
|
387
|
+
|
|
388
|
+
const fail = (code, line, col, found) => {
|
|
389
|
+
const e = new Error(code);
|
|
390
|
+
e.jy = { code, line: line || 1, col: col || 1, found };
|
|
391
|
+
throw e;
|
|
392
|
+
};
|
|
393
|
+
|
|
394
|
+
// インデントにタブを使うと解釈がパーサ任せになる(YAMLはタブでのインデントを禁じている)。
|
|
395
|
+
// ブロックスカラーの中身は対象外なので、構造として読む行だけで確かめる。
|
|
396
|
+
function checkTab(L) {
|
|
397
|
+
if (L.ws.indexOf('\t') !== -1) fail('TAB_INDENT', L.n, L.ws.indexOf('\t') + 1);
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
/** 構造として意味のある次の行まで進める(空行・コメント行は飛ばす) */
|
|
401
|
+
function skip() {
|
|
402
|
+
while (p < lines.length && (lines[p].blank || lines[p].comment)) p += 1;
|
|
403
|
+
if (p >= lines.length) return null;
|
|
404
|
+
checkTab(lines[p]);
|
|
405
|
+
return lines[p];
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
const isSeqEntry = (body) => body === '-' || body.slice(0, 2) === '- ' || body.slice(0, 2) === '-\t';
|
|
409
|
+
const isDocStart = (body) => body === '---' || body.slice(0, 4) === '--- ';
|
|
410
|
+
const isDocEnd = (body) => body === '...' || body.slice(0, 4) === '... ';
|
|
411
|
+
// --- と ... はドキュメントの区切り。ただし桁0に書かれたときだけで、字下げされていれば普通の値
|
|
412
|
+
const isBoundary = (L) => L.indent === 0 && (isDocStart(L.body) || isDocEnd(L.body));
|
|
413
|
+
|
|
414
|
+
/** 行の内容からコメントを落とす(引用符の中の # と、空白が前に無い # は残す) */
|
|
415
|
+
function stripComment(s) {
|
|
416
|
+
let inS = false;
|
|
417
|
+
let inD = false;
|
|
418
|
+
for (let k = 0; k < s.length; k++) {
|
|
419
|
+
const c = s.charAt(k);
|
|
420
|
+
if (inS) {
|
|
421
|
+
if (c === "'") {
|
|
422
|
+
if (s.charAt(k + 1) === "'") k += 1;
|
|
423
|
+
else inS = false;
|
|
424
|
+
}
|
|
425
|
+
continue;
|
|
426
|
+
}
|
|
427
|
+
if (inD) {
|
|
428
|
+
if (c === '\\') k += 1;
|
|
429
|
+
else if (c === '"') inD = false;
|
|
430
|
+
continue;
|
|
431
|
+
}
|
|
432
|
+
if (c === "'") inS = true;
|
|
433
|
+
else if (c === '"') inD = true;
|
|
434
|
+
else if (c === '#' && (k === 0 || s.charAt(k - 1) === ' ' || s.charAt(k - 1) === '\t')) {
|
|
435
|
+
return s.slice(0, k).replace(/[ \t]+$/, '');
|
|
436
|
+
}
|
|
437
|
+
}
|
|
438
|
+
return s;
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
/** 「キー: 」の区切りを探す。引用符とフロー表記の中は無視する */
|
|
442
|
+
function splitKey(s) {
|
|
443
|
+
let inS = false;
|
|
444
|
+
let inD = false;
|
|
445
|
+
let flow = 0;
|
|
446
|
+
for (let k = 0; k < s.length; k++) {
|
|
447
|
+
const c = s.charAt(k);
|
|
448
|
+
if (inS) {
|
|
449
|
+
if (c === "'") {
|
|
450
|
+
if (s.charAt(k + 1) === "'") k += 1;
|
|
451
|
+
else inS = false;
|
|
452
|
+
}
|
|
453
|
+
continue;
|
|
454
|
+
}
|
|
455
|
+
if (inD) {
|
|
456
|
+
if (c === '\\') k += 1;
|
|
457
|
+
else if (c === '"') inD = false;
|
|
458
|
+
continue;
|
|
459
|
+
}
|
|
460
|
+
if (c === "'") inS = true;
|
|
461
|
+
else if (c === '"') inD = true;
|
|
462
|
+
else if (c === '[' || c === '{') flow += 1;
|
|
463
|
+
else if (c === ']' || c === '}') flow -= 1;
|
|
464
|
+
else if (c === '#' && flow === 0 && (k === 0 || s.charAt(k - 1) === ' ')) return null;
|
|
465
|
+
else if (c === ':' && flow === 0) {
|
|
466
|
+
const nx = s.charAt(k + 1);
|
|
467
|
+
if (k + 1 >= s.length || nx === ' ' || nx === '\t') return { key: s.slice(0, k), rest: s.slice(k + 1) };
|
|
468
|
+
}
|
|
469
|
+
}
|
|
470
|
+
return null;
|
|
471
|
+
}
|
|
472
|
+
|
|
473
|
+
/** 値の前に付く &アンカー / *エイリアス / !タグ を剥がす */
|
|
474
|
+
function takeProps(s) {
|
|
475
|
+
const props = { anchor: null, alias: null, tag: null };
|
|
476
|
+
let rest = s;
|
|
477
|
+
for (let guard = 0; guard < 4; guard++) {
|
|
478
|
+
const m = /^(?:&([^\s,[\]{}]+)|\*([^\s,[\]{}]+)|(![^\s,[\]{}]*))(?:[ \t]+|$)/.exec(rest);
|
|
479
|
+
if (!m) break;
|
|
480
|
+
if (m[1]) props.anchor = m[1];
|
|
481
|
+
else if (m[2]) props.alias = m[2];
|
|
482
|
+
else props.tag = m[3];
|
|
483
|
+
rest = rest.slice(m[0].length);
|
|
484
|
+
if (props.alias) break;
|
|
485
|
+
}
|
|
486
|
+
return { props, rest };
|
|
487
|
+
}
|
|
488
|
+
|
|
489
|
+
/** スカラー文字列をタグ・引用の有無に従って値へ */
|
|
490
|
+
function toScalar(token, props, line, quoted) {
|
|
491
|
+
const tag = props && props.tag;
|
|
492
|
+
if (!tag) {
|
|
493
|
+
if (quoted) return token;
|
|
494
|
+
for (const code of jyScalarNotes(token)) N.add(code, token, line);
|
|
495
|
+
return jyResolveScalar(token);
|
|
496
|
+
}
|
|
497
|
+
switch (tag.replace(/^!!?/, '')) {
|
|
498
|
+
case 'str':
|
|
499
|
+
return token;
|
|
500
|
+
case 'int': {
|
|
501
|
+
const n = /^[-+]?0[xob]/i.test(token) ? jyResolveScalar(token) : parseInt(token, 10);
|
|
502
|
+
if (typeof n !== 'number' || !Number.isFinite(n)) fail('YAML_BAD_TAG_VALUE', line, 1, tag + ' ' + token);
|
|
503
|
+
return n;
|
|
504
|
+
}
|
|
505
|
+
case 'float': {
|
|
506
|
+
const n = Number(token);
|
|
507
|
+
if (!Number.isFinite(n)) fail('YAML_BAD_TAG_VALUE', line, 1, tag + ' ' + token);
|
|
508
|
+
return n;
|
|
509
|
+
}
|
|
510
|
+
case 'bool':
|
|
511
|
+
return /^(true|yes|on|y|1)$/i.test(token);
|
|
512
|
+
case 'null':
|
|
513
|
+
return null;
|
|
514
|
+
case 'binary':
|
|
515
|
+
N.add('YAML_BINARY', null, line);
|
|
516
|
+
return token.replace(/\s+/g, '');
|
|
517
|
+
case 'map':
|
|
518
|
+
case 'seq':
|
|
519
|
+
return quoted ? token : jyResolveScalar(token);
|
|
520
|
+
default:
|
|
521
|
+
N.add('YAML_UNKNOWN_TAG', tag, line);
|
|
522
|
+
return quoted ? token : jyResolveScalar(token);
|
|
523
|
+
}
|
|
524
|
+
}
|
|
525
|
+
|
|
526
|
+
const ESCAPES = {
|
|
527
|
+
'0': '\0', a: '\x07', b: '\b', t: '\t', '\t': '\t', n: '\n', v: '\v', f: '\f', r: '\r',
|
|
528
|
+
e: '\x1b', ' ': ' ', '"': '"', '/': '/', '\\': '\\', N: '\u0085', _: '\u00a0', L: '\u2028', P: '\u2029',
|
|
529
|
+
};
|
|
530
|
+
|
|
531
|
+
/** 二重引用符の中のエスケープを1つ読む。読めなければ null */
|
|
532
|
+
function readEscape(s, k) {
|
|
533
|
+
const c = s.charAt(k + 1);
|
|
534
|
+
if (k + 1 >= s.length) return { text: '', next: s.length }; // 行末の \ は行継続
|
|
535
|
+
if (c === 'x' || c === 'u' || c === 'U') {
|
|
536
|
+
const len = c === 'x' ? 2 : c === 'u' ? 4 : 8;
|
|
537
|
+
const hex = s.substr(k + 2, len);
|
|
538
|
+
if (hex.length < len || !/^[0-9a-fA-F]+$/.test(hex)) return null;
|
|
539
|
+
const cp = parseInt(hex, 16);
|
|
540
|
+
if (cp > 0x10ffff) return null;
|
|
541
|
+
return { text: String.fromCodePoint(cp), next: k + 2 + len };
|
|
542
|
+
}
|
|
543
|
+
if (ESCAPES[c] === undefined) return null;
|
|
544
|
+
return { text: ESCAPES[c], next: k + 2 };
|
|
545
|
+
}
|
|
546
|
+
|
|
547
|
+
/**
|
|
548
|
+
* 引用符つきスカラーを読む(複数行にまたがってよい)。
|
|
549
|
+
* 戻り値の rest は閉じ引用符より後ろ。p は最後に読んだ行を指す。
|
|
550
|
+
*/
|
|
551
|
+
function readQuoted(s) {
|
|
552
|
+
const quote = s.charAt(0);
|
|
553
|
+
const startLine = lines[p].n;
|
|
554
|
+
let cur = s;
|
|
555
|
+
let k = 1;
|
|
556
|
+
let out = '';
|
|
557
|
+
for (;;) {
|
|
558
|
+
while (k < cur.length) {
|
|
559
|
+
const c = cur.charAt(k);
|
|
560
|
+
if (quote === "'") {
|
|
561
|
+
if (c === "'") {
|
|
562
|
+
if (cur.charAt(k + 1) === "'") {
|
|
563
|
+
out += "'";
|
|
564
|
+
k += 2;
|
|
565
|
+
continue;
|
|
566
|
+
}
|
|
567
|
+
return { value: out, rest: cur.slice(k + 1) };
|
|
568
|
+
}
|
|
569
|
+
out += c;
|
|
570
|
+
k += 1;
|
|
571
|
+
continue;
|
|
572
|
+
}
|
|
573
|
+
if (c === '\\') {
|
|
574
|
+
const e = readEscape(cur, k);
|
|
575
|
+
if (e === null) fail('YAML_BAD_ESCAPE', lines[p].n, k + 1, cur.substr(k, 2));
|
|
576
|
+
out += e.text;
|
|
577
|
+
k = e.next;
|
|
578
|
+
continue;
|
|
579
|
+
}
|
|
580
|
+
if (c === '"') return { value: out, rest: cur.slice(k + 1) };
|
|
581
|
+
out += c;
|
|
582
|
+
k += 1;
|
|
583
|
+
}
|
|
584
|
+
// 行末に達した = 折り返し。空行の数だけ改行になり、無ければ空白1つになる
|
|
585
|
+
out = out.replace(/[ \t]+$/, '');
|
|
586
|
+
let breaks = 0;
|
|
587
|
+
for (;;) {
|
|
588
|
+
p += 1;
|
|
589
|
+
if (p >= lines.length) fail('YAML_UNTERMINATED_QUOTE', startLine, 1, quote);
|
|
590
|
+
if (lines[p].blank) {
|
|
591
|
+
breaks += 1;
|
|
592
|
+
continue;
|
|
593
|
+
}
|
|
594
|
+
break;
|
|
595
|
+
}
|
|
596
|
+
out += breaks === 0 ? ' ' : '\n'.repeat(breaks);
|
|
597
|
+
cur = lines[p].body;
|
|
598
|
+
k = 0;
|
|
599
|
+
}
|
|
600
|
+
}
|
|
601
|
+
|
|
602
|
+
/** フロー表記 [ … ] / { … } を読む(複数行にまたがってよい) */
|
|
603
|
+
function readFlow(s) {
|
|
604
|
+
const startLine = lines[p].n;
|
|
605
|
+
let text = s;
|
|
606
|
+
let idx = 0;
|
|
607
|
+
let level = 0;
|
|
608
|
+
let inS = false;
|
|
609
|
+
let inD = false;
|
|
610
|
+
for (;;) {
|
|
611
|
+
while (idx < text.length) {
|
|
612
|
+
const c = text.charAt(idx);
|
|
613
|
+
if (inS) {
|
|
614
|
+
if (c === "'") {
|
|
615
|
+
if (text.charAt(idx + 1) === "'") idx += 1;
|
|
616
|
+
else inS = false;
|
|
617
|
+
}
|
|
618
|
+
idx += 1;
|
|
619
|
+
continue;
|
|
620
|
+
}
|
|
621
|
+
if (inD) {
|
|
622
|
+
if (c === '\\') idx += 1;
|
|
623
|
+
else if (c === '"') inD = false;
|
|
624
|
+
idx += 1;
|
|
625
|
+
continue;
|
|
626
|
+
}
|
|
627
|
+
if (c === "'") inS = true;
|
|
628
|
+
else if (c === '"') inD = true;
|
|
629
|
+
else if (c === '[' || c === '{') level += 1;
|
|
630
|
+
else if (c === ']' || c === '}') {
|
|
631
|
+
level -= 1;
|
|
632
|
+
if (level === 0) {
|
|
633
|
+
idx += 1;
|
|
634
|
+
return { value: parseFlow(text.slice(0, idx), startLine), rest: text.slice(idx) };
|
|
635
|
+
}
|
|
636
|
+
}
|
|
637
|
+
idx += 1;
|
|
638
|
+
}
|
|
639
|
+
p += 1;
|
|
640
|
+
if (p >= lines.length) fail('YAML_UNTERMINATED_FLOW', startLine, 1);
|
|
641
|
+
// 引用符の途中でなければ、続きの行のコメントは落としてから連結する
|
|
642
|
+
text += ' ' + (inS || inD ? lines[p].body : stripComment(lines[p].body));
|
|
643
|
+
}
|
|
644
|
+
}
|
|
645
|
+
|
|
646
|
+
/** 括弧の対応が取れているフロー表記の文字列を値へ */
|
|
647
|
+
function parseFlow(text, line) {
|
|
648
|
+
let k = 0;
|
|
649
|
+
const ws = () => {
|
|
650
|
+
while (k < text.length && /\s/.test(text.charAt(k))) k += 1;
|
|
651
|
+
};
|
|
652
|
+
|
|
653
|
+
function value() {
|
|
654
|
+
ws();
|
|
655
|
+
const c = text.charAt(k);
|
|
656
|
+
if (c === '[') return seq();
|
|
657
|
+
if (c === '{') return map();
|
|
658
|
+
if (c === '"' || c === "'") {
|
|
659
|
+
const saved = p;
|
|
660
|
+
const r = (function () {
|
|
661
|
+
// 1行に収まっているので readQuoted の折り返し処理には入らない
|
|
662
|
+
const sub = text.slice(k);
|
|
663
|
+
const q = readQuotedInline(sub, line);
|
|
664
|
+
k += sub.length - q.rest.length;
|
|
665
|
+
return q.value;
|
|
666
|
+
})();
|
|
667
|
+
p = saved;
|
|
668
|
+
return r;
|
|
669
|
+
}
|
|
670
|
+
const start = k;
|
|
671
|
+
while (k < text.length) {
|
|
672
|
+
const ch = text.charAt(k);
|
|
673
|
+
if (ch === ',' || ch === ']' || ch === '}') break;
|
|
674
|
+
if (ch === ':' && (k + 1 >= text.length || /[\s,\]}]/.test(text.charAt(k + 1)))) break;
|
|
675
|
+
k += 1;
|
|
676
|
+
}
|
|
677
|
+
const tok = text.slice(start, k).trim();
|
|
678
|
+
const t = takeProps(tok);
|
|
679
|
+
if (t.props.alias) {
|
|
680
|
+
if (!(t.props.alias in anchors)) fail('YAML_ALIAS_NOT_FOUND', line, 1, '*' + t.props.alias);
|
|
681
|
+
usedAlias = true;
|
|
682
|
+
return anchors[t.props.alias];
|
|
683
|
+
}
|
|
684
|
+
const v = toScalar(t.rest, t.props, line, false);
|
|
685
|
+
if (t.props.anchor) anchors[t.props.anchor] = v;
|
|
686
|
+
return v;
|
|
687
|
+
}
|
|
688
|
+
|
|
689
|
+
function seq() {
|
|
690
|
+
depth += 1;
|
|
691
|
+
if (depth > JY_MAX_DEPTH) fail('TOO_DEEP', line);
|
|
692
|
+
k += 1;
|
|
693
|
+
const arr = [];
|
|
694
|
+
for (;;) {
|
|
695
|
+
ws();
|
|
696
|
+
if (text.charAt(k) === ']') {
|
|
697
|
+
k += 1;
|
|
698
|
+
depth -= 1;
|
|
699
|
+
return arr;
|
|
700
|
+
}
|
|
701
|
+
if (k >= text.length) fail('YAML_UNTERMINATED_FLOW', line, 1);
|
|
702
|
+
const quotedKey = text.charAt(k) === '"' || text.charAt(k) === "'";
|
|
703
|
+
const v = value();
|
|
704
|
+
ws();
|
|
705
|
+
if (text.charAt(k) === ':') {
|
|
706
|
+
// [a: 1] のように括弧なしのペアが書かれた場合
|
|
707
|
+
k += 1;
|
|
708
|
+
const pair = Object.create(null);
|
|
709
|
+
const own = new Set();
|
|
710
|
+
setKey(pair, own, v, value(), line, !quotedKey);
|
|
711
|
+
arr.push(pair);
|
|
712
|
+
ws();
|
|
713
|
+
} else {
|
|
714
|
+
arr.push(v);
|
|
715
|
+
}
|
|
716
|
+
if (text.charAt(k) === ',') {
|
|
717
|
+
k += 1;
|
|
718
|
+
continue;
|
|
719
|
+
}
|
|
720
|
+
if (text.charAt(k) === ']') {
|
|
721
|
+
k += 1;
|
|
722
|
+
depth -= 1;
|
|
723
|
+
return arr;
|
|
724
|
+
}
|
|
725
|
+
fail('YAML_FLOW_SEP', line, 1, text.charAt(k) || 'EOF');
|
|
726
|
+
}
|
|
727
|
+
}
|
|
728
|
+
|
|
729
|
+
function map() {
|
|
730
|
+
depth += 1;
|
|
731
|
+
if (depth > JY_MAX_DEPTH) fail('TOO_DEEP', line);
|
|
732
|
+
k += 1;
|
|
733
|
+
const obj = Object.create(null);
|
|
734
|
+
const own = new Set();
|
|
735
|
+
for (;;) {
|
|
736
|
+
ws();
|
|
737
|
+
if (text.charAt(k) === '}') {
|
|
738
|
+
k += 1;
|
|
739
|
+
depth -= 1;
|
|
740
|
+
return obj;
|
|
741
|
+
}
|
|
742
|
+
if (k >= text.length) fail('YAML_UNTERMINATED_FLOW', line, 1);
|
|
743
|
+
const quotedKey = text.charAt(k) === '"' || text.charAt(k) === "'";
|
|
744
|
+
const key = value();
|
|
745
|
+
ws();
|
|
746
|
+
let v = null;
|
|
747
|
+
if (text.charAt(k) === ':') {
|
|
748
|
+
k += 1;
|
|
749
|
+
v = value();
|
|
750
|
+
ws();
|
|
751
|
+
} else if (text.charAt(k) !== ',' && text.charAt(k) !== '}') {
|
|
752
|
+
fail('YAML_FLOW_COLON', line, 1, text.charAt(k) || 'EOF');
|
|
753
|
+
}
|
|
754
|
+
setKey(obj, own, key, v, line, !quotedKey);
|
|
755
|
+
if (text.charAt(k) === ',') {
|
|
756
|
+
k += 1;
|
|
757
|
+
continue;
|
|
758
|
+
}
|
|
759
|
+
if (text.charAt(k) === '}') {
|
|
760
|
+
k += 1;
|
|
761
|
+
depth -= 1;
|
|
762
|
+
return obj;
|
|
763
|
+
}
|
|
764
|
+
fail('YAML_FLOW_SEP', line, 1, text.charAt(k) || 'EOF');
|
|
765
|
+
}
|
|
766
|
+
}
|
|
767
|
+
|
|
768
|
+
const out = value();
|
|
769
|
+
ws();
|
|
770
|
+
if (k < text.length) fail('YAML_FLOW_SEP', line, 1, text.charAt(k));
|
|
771
|
+
return out;
|
|
772
|
+
}
|
|
773
|
+
|
|
774
|
+
/** 1行に収まっている引用スカラーを読む(フロー表記の中で使う) */
|
|
775
|
+
function readQuotedInline(s, line) {
|
|
776
|
+
const quote = s.charAt(0);
|
|
777
|
+
let out = '';
|
|
778
|
+
for (let k = 1; k < s.length; k++) {
|
|
779
|
+
const c = s.charAt(k);
|
|
780
|
+
if (quote === "'") {
|
|
781
|
+
if (c === "'") {
|
|
782
|
+
if (s.charAt(k + 1) === "'") {
|
|
783
|
+
out += "'";
|
|
784
|
+
k += 1;
|
|
785
|
+
continue;
|
|
786
|
+
}
|
|
787
|
+
return { value: out, rest: s.slice(k + 1) };
|
|
788
|
+
}
|
|
789
|
+
out += c;
|
|
790
|
+
continue;
|
|
791
|
+
}
|
|
792
|
+
if (c === '\\') {
|
|
793
|
+
const e = readEscape(s, k);
|
|
794
|
+
if (e === null) fail('YAML_BAD_ESCAPE', line, k + 1, s.substr(k, 2));
|
|
795
|
+
out += e.text;
|
|
796
|
+
k = e.next - 1;
|
|
797
|
+
continue;
|
|
798
|
+
}
|
|
799
|
+
if (c === '"') return { value: out, rest: s.slice(k + 1) };
|
|
800
|
+
out += c;
|
|
801
|
+
}
|
|
802
|
+
fail('YAML_UNTERMINATED_QUOTE', line, 1, quote);
|
|
803
|
+
return null;
|
|
804
|
+
}
|
|
805
|
+
|
|
806
|
+
/** ブロックスカラー(| と >)を読む。s はヘッダ(| や >- など)から始まる */
|
|
807
|
+
function readBlockScalar(s, baseIndent) {
|
|
808
|
+
const style = s.charAt(0);
|
|
809
|
+
let k = 1;
|
|
810
|
+
let chomp = '';
|
|
811
|
+
let explicit = 0;
|
|
812
|
+
while (k < s.length) {
|
|
813
|
+
const c = s.charAt(k);
|
|
814
|
+
if ((c === '+' || c === '-') && !chomp) {
|
|
815
|
+
chomp = c;
|
|
816
|
+
k += 1;
|
|
817
|
+
continue;
|
|
818
|
+
}
|
|
819
|
+
if (c >= '1' && c <= '9' && !explicit) {
|
|
820
|
+
explicit = Number(c);
|
|
821
|
+
k += 1;
|
|
822
|
+
continue;
|
|
823
|
+
}
|
|
824
|
+
break;
|
|
825
|
+
}
|
|
826
|
+
const tail = stripComment(s.slice(k)).trim();
|
|
827
|
+
if (tail !== '') fail('YAML_BLOCK_HEADER', lines[p].n, k + 1, tail);
|
|
828
|
+
|
|
829
|
+
p += 1;
|
|
830
|
+
const body = [];
|
|
831
|
+
let contentIndent = explicit ? baseIndent + explicit : 0;
|
|
832
|
+
while (p < lines.length) {
|
|
833
|
+
const L = lines[p];
|
|
834
|
+
if (L.blank) {
|
|
835
|
+
body.push('');
|
|
836
|
+
p += 1;
|
|
837
|
+
continue;
|
|
838
|
+
}
|
|
839
|
+
if (!contentIndent) {
|
|
840
|
+
if (L.indent <= baseIndent) break;
|
|
841
|
+
contentIndent = L.indent;
|
|
842
|
+
} else if (L.indent < contentIndent) {
|
|
843
|
+
// ブロックの中身より浅く、しかし親より深い = インデントの取り違え
|
|
844
|
+
if (L.indent > baseIndent) fail('YAML_BLOCK_INDENT', L.n, L.indent + 1);
|
|
845
|
+
break;
|
|
846
|
+
}
|
|
847
|
+
body.push(L.text.slice(contentIndent));
|
|
848
|
+
p += 1;
|
|
849
|
+
}
|
|
850
|
+
|
|
851
|
+
let end = body.length;
|
|
852
|
+
while (end > 0 && body[end - 1] === '') end -= 1;
|
|
853
|
+
const trailingBlanks = body.length - end;
|
|
854
|
+
const content = body.slice(0, end);
|
|
855
|
+
|
|
856
|
+
let out;
|
|
857
|
+
if (style === '|') {
|
|
858
|
+
out = content.join('\n');
|
|
859
|
+
} else {
|
|
860
|
+
out = '';
|
|
861
|
+
for (let q = 0; q < content.length; q++) {
|
|
862
|
+
const ln = content[q];
|
|
863
|
+
if (q === 0) {
|
|
864
|
+
out = ln;
|
|
865
|
+
continue;
|
|
866
|
+
}
|
|
867
|
+
const prev = content[q - 1];
|
|
868
|
+
if (ln === '') out += '\n';
|
|
869
|
+
else if (prev === '') out += ln;
|
|
870
|
+
else if (/^[ \t]/.test(ln) || /^[ \t]/.test(prev)) out += '\n' + ln;
|
|
871
|
+
else out += ' ' + ln;
|
|
872
|
+
}
|
|
873
|
+
}
|
|
874
|
+
if (content.length) out += '\n';
|
|
875
|
+
if (chomp === '-') out = out.replace(/\n+$/, '');
|
|
876
|
+
else if (chomp === '+') out += '\n'.repeat(trailingBlanks);
|
|
877
|
+
return out;
|
|
878
|
+
}
|
|
879
|
+
|
|
880
|
+
/**
|
|
881
|
+
* マップへキーを入れる(マージキー <<・文字列以外のキー・キーの重複を処理する)。
|
|
882
|
+
* << は引用符なしで書かれたときだけマージ指示になる('<<' と書けば普通のキー。js-yaml も同じ扱い)。
|
|
883
|
+
*/
|
|
884
|
+
function setKey(obj, own, key, value, line, plainKey) {
|
|
885
|
+
if (key === '<<' && plainKey !== false) {
|
|
886
|
+
const sources = Array.isArray(value) ? value : [value];
|
|
887
|
+
for (const s of sources) {
|
|
888
|
+
if (!jyIsPlainObject(s)) {
|
|
889
|
+
N.add('YAML_BAD_MERGE', null, line);
|
|
890
|
+
continue;
|
|
891
|
+
}
|
|
892
|
+
for (const k of Object.keys(s)) if (!own.has(k)) obj[k] = s[k];
|
|
893
|
+
}
|
|
894
|
+
N.add('YAML_MERGE_KEY', null, line);
|
|
895
|
+
return;
|
|
896
|
+
}
|
|
897
|
+
let name;
|
|
898
|
+
if (typeof key === 'string') {
|
|
899
|
+
name = key;
|
|
900
|
+
} else {
|
|
901
|
+
name = key === null ? 'null' : typeof key === 'object' ? jyFormatJson(key, { indent: 0 }) : String(key);
|
|
902
|
+
N.add('YAML_NONSTRING_KEY', name, line);
|
|
903
|
+
}
|
|
904
|
+
if (own.has(name)) N.add('DUPLICATE_KEY', name, line);
|
|
905
|
+
own.add(name);
|
|
906
|
+
obj[name] = value;
|
|
907
|
+
}
|
|
908
|
+
|
|
909
|
+
/**
|
|
910
|
+
* 「: の後ろ」または「- の後ろ」に続く値を解釈する。
|
|
911
|
+
* baseIndent より深い行だけを続きとして取り込む。戻るとき p は次の未処理行を指す。
|
|
912
|
+
*/
|
|
913
|
+
function parseTrailing(rawRest, baseIndent) {
|
|
914
|
+
const L = lines[p];
|
|
915
|
+
const line = L.n;
|
|
916
|
+
const t = takeProps(rawRest.replace(/^[ \t]+/, ''));
|
|
917
|
+
const props = t.props;
|
|
918
|
+
let s = t.rest;
|
|
919
|
+
|
|
920
|
+
if (props.alias) {
|
|
921
|
+
if (stripComment(s).trim() !== '') fail('YAML_ALIAS_TRAILING', line, 1, stripComment(s).trim());
|
|
922
|
+
if (!(props.alias in anchors)) fail('YAML_ALIAS_NOT_FOUND', line, 1, '*' + props.alias);
|
|
923
|
+
usedAlias = true;
|
|
924
|
+
p += 1;
|
|
925
|
+
return anchors[props.alias];
|
|
926
|
+
}
|
|
927
|
+
|
|
928
|
+
if (/^[|>]/.test(s)) {
|
|
929
|
+
const v = readBlockScalar(s, baseIndent);
|
|
930
|
+
const out = props.tag ? toScalar(v, props, line, true) : v;
|
|
931
|
+
if (props.anchor) anchors[props.anchor] = out;
|
|
932
|
+
return out;
|
|
933
|
+
}
|
|
934
|
+
|
|
935
|
+
if (stripComment(s).trim() === '') {
|
|
936
|
+
// 値は次の行以降にある
|
|
937
|
+
p += 1;
|
|
938
|
+
const child = parseChild(baseIndent);
|
|
939
|
+
if (props.tag && !/^!!?(map|seq)$/.test(props.tag)) N.add('YAML_UNKNOWN_TAG', props.tag, line);
|
|
940
|
+
if (props.anchor) anchors[props.anchor] = child;
|
|
941
|
+
return child;
|
|
942
|
+
}
|
|
943
|
+
|
|
944
|
+
if (s.charAt(0) === '"' || s.charAt(0) === "'") {
|
|
945
|
+
const q = readQuoted(s);
|
|
946
|
+
const rest = stripComment(q.rest).trim();
|
|
947
|
+
if (rest !== '') fail('YAML_TRAILING_TEXT', lines[p].n, 1, rest.slice(0, 24));
|
|
948
|
+
p += 1;
|
|
949
|
+
const out = toScalar(q.value, props, line, true);
|
|
950
|
+
if (props.anchor) anchors[props.anchor] = out;
|
|
951
|
+
return out;
|
|
952
|
+
}
|
|
953
|
+
|
|
954
|
+
if (s.charAt(0) === '[' || s.charAt(0) === '{') {
|
|
955
|
+
const f = readFlow(s);
|
|
956
|
+
const rest = stripComment(f.rest).trim();
|
|
957
|
+
if (rest !== '') fail('YAML_TRAILING_TEXT', lines[p].n, 1, rest.slice(0, 24));
|
|
958
|
+
p += 1;
|
|
959
|
+
if (props.anchor) anchors[props.anchor] = f.value;
|
|
960
|
+
return f.value;
|
|
961
|
+
}
|
|
962
|
+
|
|
963
|
+
// プレーンスカラー。次の行以降へ折り返している場合は空白1つで連結する
|
|
964
|
+
const first = stripComment(s).replace(/[ \t]+$/, '');
|
|
965
|
+
if (/^-([ \t]|$)/.test(first)) fail('YAML_SEQ_INLINE', line, L.text.length - rawRest.length + 1, first.slice(0, 24));
|
|
966
|
+
if (splitKey(first)) fail('YAML_NESTED_COLON', line, L.text.length - rawRest.length + 1, first.slice(0, 24));
|
|
967
|
+
const parts = [first];
|
|
968
|
+
p += 1;
|
|
969
|
+
while (p < lines.length) {
|
|
970
|
+
const L2 = lines[p];
|
|
971
|
+
if (L2.blank || L2.comment) break;
|
|
972
|
+
checkTab(L2);
|
|
973
|
+
if (L2.indent <= baseIndent || isBoundary(L2)) break;
|
|
974
|
+
const body = stripComment(L2.body).replace(/[ \t]+$/, '');
|
|
975
|
+
if (isSeqEntry(L2.body) || splitKey(body)) fail('YAML_VALUE_THEN_BLOCK', L2.n, L2.indent + 1, body.slice(0, 24));
|
|
976
|
+
parts.push(body);
|
|
977
|
+
p += 1;
|
|
978
|
+
}
|
|
979
|
+
const token = parts.join(' ').replace(/[ \t]+$/, '');
|
|
980
|
+
const out = toScalar(token, props, line, false);
|
|
981
|
+
if (props.anchor) anchors[props.anchor] = out;
|
|
982
|
+
return out;
|
|
983
|
+
}
|
|
984
|
+
|
|
985
|
+
/** 親より深い行(またはキーと同じ深さのシーケンス)を子ノードとして読む */
|
|
986
|
+
function parseChild(baseIndent) {
|
|
987
|
+
const L = skip();
|
|
988
|
+
if (!L || isBoundary(L)) return null;
|
|
989
|
+
if (L.indent > baseIndent) return parseNode(L.indent);
|
|
990
|
+
// key: の下に同じ深さで - を並べるのは YAML として正しい
|
|
991
|
+
if (L.indent === baseIndent && isSeqEntry(L.body)) return parseSeq(baseIndent);
|
|
992
|
+
return null;
|
|
993
|
+
}
|
|
994
|
+
|
|
995
|
+
function parseNode(indent) {
|
|
996
|
+
depth += 1;
|
|
997
|
+
if (depth > JY_MAX_DEPTH) fail('TOO_DEEP', lines[p] ? lines[p].n : 1);
|
|
998
|
+
try {
|
|
999
|
+
const L = skip();
|
|
1000
|
+
if (!L || L.indent < indent || isBoundary(L)) return null;
|
|
1001
|
+
// 「? key」「: value」の明示キー記法は、JSONに落とせないので受け取らない
|
|
1002
|
+
if (/^[?:]([ \t]|$)/.test(L.body)) fail('YAML_EXPLICIT_KEY', L.n, L.indent + 1);
|
|
1003
|
+
if (isSeqEntry(L.body)) return parseSeq(indent);
|
|
1004
|
+
if (splitKey(L.body)) return parseMap(indent);
|
|
1005
|
+
return parseTrailing(L.body, indent - 1);
|
|
1006
|
+
} finally {
|
|
1007
|
+
depth -= 1;
|
|
1008
|
+
}
|
|
1009
|
+
}
|
|
1010
|
+
|
|
1011
|
+
function parseMap(indent) {
|
|
1012
|
+
const obj = Object.create(null);
|
|
1013
|
+
const own = new Set();
|
|
1014
|
+
for (;;) {
|
|
1015
|
+
const L = skip();
|
|
1016
|
+
if (!L || L.indent < indent || isBoundary(L)) break;
|
|
1017
|
+
if (L.indent > indent) fail('YAML_BAD_INDENT', L.n, L.indent + 1, stripComment(L.body).slice(0, 24));
|
|
1018
|
+
if (isSeqEntry(L.body)) fail('YAML_SEQ_IN_MAP', L.n, L.indent + 1);
|
|
1019
|
+
const kv = splitKey(L.body);
|
|
1020
|
+
if (!kv) {
|
|
1021
|
+
if (/^\?([ \t]|$)/.test(L.body)) fail('YAML_EXPLICIT_KEY', L.n, L.indent + 1);
|
|
1022
|
+
fail('YAML_KEY_EXPECTED', L.n, L.indent + 1, stripComment(L.body).trim().slice(0, 24));
|
|
1023
|
+
}
|
|
1024
|
+
const line = L.n;
|
|
1025
|
+
const kt = takeProps(kv.key.trim());
|
|
1026
|
+
const rawKey = kt.rest;
|
|
1027
|
+
const quotedKey = rawKey.charAt(0) === '"' || rawKey.charAt(0) === "'";
|
|
1028
|
+
const key = quotedKey ? readQuotedInline(rawKey, line).value : toScalar(rawKey, kt.props, line, false);
|
|
1029
|
+
const value = parseTrailing(kv.rest, indent);
|
|
1030
|
+
setKey(obj, own, key, value, line, !quotedKey);
|
|
1031
|
+
}
|
|
1032
|
+
return obj;
|
|
1033
|
+
}
|
|
1034
|
+
|
|
1035
|
+
function parseSeq(indent) {
|
|
1036
|
+
const arr = [];
|
|
1037
|
+
for (;;) {
|
|
1038
|
+
const L = skip();
|
|
1039
|
+
if (!L || L.indent < indent || isBoundary(L)) break;
|
|
1040
|
+
if (!isSeqEntry(L.body)) {
|
|
1041
|
+
// 同じ深さにマップのキーが来たら、呼び出し側(マップ)へ制御を戻す
|
|
1042
|
+
if (L.indent === indent) break;
|
|
1043
|
+
fail('YAML_BAD_INDENT', L.n, L.indent + 1, stripComment(L.body).slice(0, 24));
|
|
1044
|
+
}
|
|
1045
|
+
if (L.indent > indent) fail('YAML_BAD_INDENT', L.n, L.indent + 1, stripComment(L.body).slice(0, 24));
|
|
1046
|
+
const rest = L.body.slice(1);
|
|
1047
|
+
const lead = /^[ \t]*/.exec(rest)[0].length;
|
|
1048
|
+
const inner = rest.slice(lead);
|
|
1049
|
+
if (stripComment(inner).trim() === '') {
|
|
1050
|
+
p += 1;
|
|
1051
|
+
// 「-」だけの行の中身は、より深い行だけ。同じ深さの「-」は(親の値ではなく)次の要素なので、
|
|
1052
|
+
// key: の下に同じ深さで - を並べられる parseChild は使えない
|
|
1053
|
+
const next = skip();
|
|
1054
|
+
arr.push(!next || isBoundary(next) || next.indent <= indent ? null : parseNode(next.indent));
|
|
1055
|
+
continue;
|
|
1056
|
+
}
|
|
1057
|
+
// 「- 」に続く中身を、その桁から始まる行として読み直す(- name: a の下に同じ桁で続くキーを拾うため)
|
|
1058
|
+
const itemIndent = indent + 1 + lead;
|
|
1059
|
+
lines[p] = { ...L, ws: L.text.slice(0, itemIndent), indent: itemIndent, body: inner };
|
|
1060
|
+
arr.push(parseNode(itemIndent));
|
|
1061
|
+
}
|
|
1062
|
+
return arr;
|
|
1063
|
+
}
|
|
1064
|
+
|
|
1065
|
+
const docs = [];
|
|
1066
|
+
try {
|
|
1067
|
+
let guard = 0;
|
|
1068
|
+
while (p < lines.length) {
|
|
1069
|
+
if ((guard += 1) > lines.length + 16) fail('YAML_INTERNAL', lines[p] ? lines[p].n : 1);
|
|
1070
|
+
const L = skip();
|
|
1071
|
+
if (!L) break;
|
|
1072
|
+
if (L.body.charAt(0) === '%') {
|
|
1073
|
+
N.add('YAML_DIRECTIVE', stripComment(L.body).trim(), L.n);
|
|
1074
|
+
p += 1;
|
|
1075
|
+
continue;
|
|
1076
|
+
}
|
|
1077
|
+
if (L.indent === 0 && isDocEnd(L.body)) {
|
|
1078
|
+
p += 1;
|
|
1079
|
+
continue;
|
|
1080
|
+
}
|
|
1081
|
+
if (L.indent === 0 && isDocStart(L.body)) {
|
|
1082
|
+
const rest = L.body.slice(3);
|
|
1083
|
+
if (stripComment(rest).trim() === '') {
|
|
1084
|
+
p += 1;
|
|
1085
|
+
const next = skip();
|
|
1086
|
+
docs.push(!next || isBoundary(next) ? null : parseNode(next.indent));
|
|
1087
|
+
} else {
|
|
1088
|
+
const lead = /^[ \t]*/.exec(rest)[0].length;
|
|
1089
|
+
const itemIndent = 3 + lead;
|
|
1090
|
+
lines[p] = { ...L, ws: L.text.slice(0, itemIndent), indent: itemIndent, body: rest.slice(lead) };
|
|
1091
|
+
docs.push(parseNode(itemIndent));
|
|
1092
|
+
}
|
|
1093
|
+
continue;
|
|
1094
|
+
}
|
|
1095
|
+
docs.push(parseNode(L.indent));
|
|
1096
|
+
}
|
|
1097
|
+
} catch (e) {
|
|
1098
|
+
if (!e.jy) throw e;
|
|
1099
|
+
return { ok: false, error: e.jy, notes: N.list, docs };
|
|
1100
|
+
}
|
|
1101
|
+
|
|
1102
|
+
if (usedAlias) N.add('YAML_ALIAS_EXPANDED');
|
|
1103
|
+
if (docs.length > 1) N.add('MULTI_DOC', null, null).count = docs.length;
|
|
1104
|
+
return {
|
|
1105
|
+
ok: true,
|
|
1106
|
+
docs,
|
|
1107
|
+
value: docs.length === 0 ? null : docs.length === 1 ? docs[0] : docs,
|
|
1108
|
+
notes: N.list,
|
|
1109
|
+
};
|
|
1110
|
+
}
|
|
1111
|
+
|
|
1112
|
+
/* ---------------------------------------------------------------------------
|
|
1113
|
+
* JSON 出力
|
|
1114
|
+
* ------------------------------------------------------------------------- */
|
|
1115
|
+
|
|
1116
|
+
/**
|
|
1117
|
+
* 値をJSON文字列へ。JSON.stringify と違い、キーの並べ替え・非ASCIIのエスケープ・
|
|
1118
|
+
* インデント文字(タブ / 1行)を選べる。NaN と Infinity は JSON に無いので null にする。
|
|
1119
|
+
*
|
|
1120
|
+
* @param {*} value
|
|
1121
|
+
* @param {object} [opts]
|
|
1122
|
+
* @param {number|'tab'} [opts.indent=2] 0 なら改行なしの1行
|
|
1123
|
+
* @param {boolean} [opts.sortKeys=false]
|
|
1124
|
+
* @param {boolean} [opts.ascii=false] 非ASCII文字を \uXXXX にする
|
|
1125
|
+
*/
|
|
1126
|
+
function jyFormatJson(value, opts) {
|
|
1127
|
+
const o = opts || {};
|
|
1128
|
+
const tab = o.indent === 'tab';
|
|
1129
|
+
const width = tab ? 1 : o.indent === undefined ? 2 : Number(o.indent) || 0;
|
|
1130
|
+
const pad = tab ? '\t' : ' '.repeat(width);
|
|
1131
|
+
const oneLine = !tab && width === 0;
|
|
1132
|
+
const nl = oneLine ? '' : '\n';
|
|
1133
|
+
const sortKeys = Boolean(o.sortKeys);
|
|
1134
|
+
const ascii = Boolean(o.ascii);
|
|
1135
|
+
|
|
1136
|
+
const hex4 = (n) => '\\u' + n.toString(16).toLowerCase().padStart(4, '0');
|
|
1137
|
+
|
|
1138
|
+
function str(s) {
|
|
1139
|
+
let out = '"';
|
|
1140
|
+
for (let k = 0; k < s.length; k++) {
|
|
1141
|
+
const c = s.charAt(k);
|
|
1142
|
+
const cp = s.charCodeAt(k);
|
|
1143
|
+
if (c === '"') out += '\\"';
|
|
1144
|
+
else if (c === '\\') out += '\\\\';
|
|
1145
|
+
else if (c === '\n') out += '\\n';
|
|
1146
|
+
else if (c === '\r') out += '\\r';
|
|
1147
|
+
else if (c === '\t') out += '\\t';
|
|
1148
|
+
else if (cp === 8) out += '\\b';
|
|
1149
|
+
else if (cp === 12) out += '\\f';
|
|
1150
|
+
else if (cp < 0x20 || cp === 0x7f) out += hex4(cp);
|
|
1151
|
+
else if (ascii && cp > 0x7e) out += hex4(cp);
|
|
1152
|
+
else out += c;
|
|
1153
|
+
}
|
|
1154
|
+
return out + '"';
|
|
1155
|
+
}
|
|
1156
|
+
|
|
1157
|
+
function scalar(v) {
|
|
1158
|
+
if (v === null || v === undefined) return 'null';
|
|
1159
|
+
if (typeof v === 'boolean') return v ? 'true' : 'false';
|
|
1160
|
+
if (typeof v === 'number') return Number.isFinite(v) ? String(v) : 'null';
|
|
1161
|
+
return str(String(v));
|
|
1162
|
+
}
|
|
1163
|
+
|
|
1164
|
+
function write(v, level) {
|
|
1165
|
+
if (Array.isArray(v)) {
|
|
1166
|
+
if (!v.length) return '[]';
|
|
1167
|
+
const ind = oneLine ? '' : pad.repeat(level + 1);
|
|
1168
|
+
const close = oneLine ? '' : pad.repeat(level);
|
|
1169
|
+
const items = v.map((item) => ind + write(item, level + 1));
|
|
1170
|
+
return '[' + nl + items.join(',' + nl) + nl + close + ']';
|
|
1171
|
+
}
|
|
1172
|
+
if (jyIsPlainObject(v)) {
|
|
1173
|
+
const keys = sortKeys ? Object.keys(v).sort() : Object.keys(v);
|
|
1174
|
+
if (!keys.length) return '{}';
|
|
1175
|
+
const ind = oneLine ? '' : pad.repeat(level + 1);
|
|
1176
|
+
const close = oneLine ? '' : pad.repeat(level);
|
|
1177
|
+
const items = keys.map((k) => ind + str(k) + (oneLine ? ':' : ': ') + write(v[k], level + 1));
|
|
1178
|
+
return '{' + nl + items.join(',' + nl) + nl + close + '}';
|
|
1179
|
+
}
|
|
1180
|
+
return scalar(v);
|
|
1181
|
+
}
|
|
1182
|
+
|
|
1183
|
+
return write(value, 0);
|
|
1184
|
+
}
|
|
1185
|
+
|
|
1186
|
+
/* ---------------------------------------------------------------------------
|
|
1187
|
+
* YAML 出力
|
|
1188
|
+
* ------------------------------------------------------------------------- */
|
|
1189
|
+
|
|
1190
|
+
const JY_CONTROL_RE = /[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f-\u009f\uFEFF]/;
|
|
1191
|
+
|
|
1192
|
+
/** 引用符なし(プレーン)で書ける文字列かどうか */
|
|
1193
|
+
function jyPlainSafe(s) {
|
|
1194
|
+
if (s === '') return false;
|
|
1195
|
+
if (/^[ \t]|[ \t]$/.test(s)) return false; // 前後の空白は失われる
|
|
1196
|
+
if (/[\n\r]/.test(s) || JY_CONTROL_RE.test(s)) return false; // 改行・制御文字
|
|
1197
|
+
if (/: /.test(s) || /:$/.test(s)) return false; // マップの区切りに見える
|
|
1198
|
+
if (JY_SEXAGESIMAL.test(s)) return false; // 12:30 が 750 に化けるパーサがある
|
|
1199
|
+
if (/ #/.test(s)) return false; // コメントの始まりに見える
|
|
1200
|
+
if (/^[-?:]([ \t]|$)/.test(s)) return false; // 指示子+空白
|
|
1201
|
+
if (/^[,[\]{}#&*!|>'"%@`]/.test(s)) return false; // 先頭に置けない記号
|
|
1202
|
+
if (s === '---' || s === '...') return false; // ドキュメントの区切りに見える
|
|
1203
|
+
if (typeof jyResolveScalar(s) !== 'string') return false; // 数値・真偽値・null に化ける
|
|
1204
|
+
if (JY_YAML11_BOOL.test(s)) return false; // YAML 1.1 のパーサで真偽値に化ける
|
|
1205
|
+
if (/^[0-9]{4}-[0-9]{2}-[0-9]{2}([Tt ].*)?$/.test(s)) return false; // 日付に化ける
|
|
1206
|
+
return true;
|
|
1207
|
+
}
|
|
1208
|
+
|
|
1209
|
+
/**
|
|
1210
|
+
* 値をYAML文字列へ。
|
|
1211
|
+
*
|
|
1212
|
+
* @param {*} value
|
|
1213
|
+
* @param {object} [opts]
|
|
1214
|
+
* @param {number} [opts.indent=2] ネスト1段あたりの空白数(1-8)
|
|
1215
|
+
* @param {boolean}[opts.block=true] 改行を含む文字列をブロックスカラー(|)で書く
|
|
1216
|
+
* @param {boolean}[opts.sortKeys=false] キーを名前順に並べる
|
|
1217
|
+
* @param {boolean}[opts.docStart=false] 先頭に --- を付ける
|
|
1218
|
+
* @param {'auto'|'single'|'double'} [opts.quote='auto'] 引用符の付け方
|
|
1219
|
+
* @param {'null'|'tilde'|'empty'} [opts.nullStyle='null'] null の書き方
|
|
1220
|
+
*/
|
|
1221
|
+
function jyFormatYaml(value, opts) {
|
|
1222
|
+
const o = opts || {};
|
|
1223
|
+
const step = Math.max(1, Math.min(8, Number(o.indent) || 2));
|
|
1224
|
+
const pad = ' '.repeat(step);
|
|
1225
|
+
const quote = o.quote === 'single' || o.quote === 'double' ? o.quote : 'auto';
|
|
1226
|
+
const block = o.block !== false;
|
|
1227
|
+
const sortKeys = Boolean(o.sortKeys);
|
|
1228
|
+
const nullText = o.nullStyle === 'tilde' ? '~' : o.nullStyle === 'empty' ? '' : 'null';
|
|
1229
|
+
|
|
1230
|
+
function dq(s) {
|
|
1231
|
+
let out = '"';
|
|
1232
|
+
for (let k = 0; k < s.length; k++) {
|
|
1233
|
+
const c = s.charAt(k);
|
|
1234
|
+
const cp = s.charCodeAt(k);
|
|
1235
|
+
if (c === '"') out += '\\"';
|
|
1236
|
+
else if (c === '\\') out += '\\\\';
|
|
1237
|
+
else if (c === '\n') out += '\\n';
|
|
1238
|
+
else if (c === '\r') out += '\\r';
|
|
1239
|
+
else if (c === '\t') out += '\\t';
|
|
1240
|
+
else if (cp < 0x20 || cp === 0x7f) out += '\\x' + cp.toString(16).toUpperCase().padStart(2, '0');
|
|
1241
|
+
else if (cp >= 0x80 && cp <= 0x9f) out += '\\u' + cp.toString(16).toUpperCase().padStart(4, '0');
|
|
1242
|
+
else out += c;
|
|
1243
|
+
}
|
|
1244
|
+
return out + '"';
|
|
1245
|
+
}
|
|
1246
|
+
|
|
1247
|
+
function quoted(s) {
|
|
1248
|
+
if (quote === 'double') return dq(s);
|
|
1249
|
+
if (/[\n\r]/.test(s) || JY_CONTROL_RE.test(s)) return dq(s);
|
|
1250
|
+
return "'" + s.replace(/'/g, "''") + "'";
|
|
1251
|
+
}
|
|
1252
|
+
|
|
1253
|
+
/** ブロックスカラー(|)で安全に書ける文字列かどうか */
|
|
1254
|
+
function blockSafe(s) {
|
|
1255
|
+
if (!block || s.indexOf('\n') === -1) return false;
|
|
1256
|
+
if (JY_CONTROL_RE.test(s) || s.indexOf('\r') !== -1) return false;
|
|
1257
|
+
if (/^[ \t]/.test(s)) return false; // 1行目の字下げは復元できない
|
|
1258
|
+
if (/[ \t]$/m.test(s)) return false; // 行末の空白は復元できない
|
|
1259
|
+
if (/\n{2,}$/.test(s)) return false; // 末尾の空行は次の行と紛れる
|
|
1260
|
+
if (/^\s*$/.test(s)) return false;
|
|
1261
|
+
return true;
|
|
1262
|
+
}
|
|
1263
|
+
|
|
1264
|
+
function scalarText(v) {
|
|
1265
|
+
if (v === null || v === undefined) return nullText;
|
|
1266
|
+
if (typeof v === 'boolean') return v ? 'true' : 'false';
|
|
1267
|
+
if (typeof v === 'number') {
|
|
1268
|
+
if (Number.isNaN(v)) return '.nan';
|
|
1269
|
+
if (v === Infinity) return '.inf';
|
|
1270
|
+
if (v === -Infinity) return '-.inf';
|
|
1271
|
+
return String(v);
|
|
1272
|
+
}
|
|
1273
|
+
const s = String(v);
|
|
1274
|
+
if (quote === 'auto' && jyPlainSafe(s)) return s;
|
|
1275
|
+
return quoted(s);
|
|
1276
|
+
}
|
|
1277
|
+
|
|
1278
|
+
function keyText(k) {
|
|
1279
|
+
// << を素で書くとマージ指示になるので、データとしてのキーなら必ず引用符で囲む
|
|
1280
|
+
if (k === '<<') return quoted(k);
|
|
1281
|
+
if (quote === 'auto' && jyPlainSafe(k) && k.indexOf('#') === -1) return k;
|
|
1282
|
+
return quoted(k);
|
|
1283
|
+
}
|
|
1284
|
+
|
|
1285
|
+
const out = [];
|
|
1286
|
+
|
|
1287
|
+
/** head は "key:" か "-"。値の形に応じて1行で書くか、下へ続けるかを決める */
|
|
1288
|
+
function writeEntry(head, v, level, isSeq) {
|
|
1289
|
+
const ind = pad.repeat(level);
|
|
1290
|
+
if (Array.isArray(v)) {
|
|
1291
|
+
if (!v.length) {
|
|
1292
|
+
out.push(ind + head + ' []');
|
|
1293
|
+
return;
|
|
1294
|
+
}
|
|
1295
|
+
if (isSeq) {
|
|
1296
|
+
pushCompact(ind, v, true);
|
|
1297
|
+
return;
|
|
1298
|
+
}
|
|
1299
|
+
out.push(ind + head);
|
|
1300
|
+
writeSeq(v, level + 1);
|
|
1301
|
+
return;
|
|
1302
|
+
}
|
|
1303
|
+
if (jyIsPlainObject(v)) {
|
|
1304
|
+
const keys = Object.keys(v);
|
|
1305
|
+
if (!keys.length) {
|
|
1306
|
+
out.push(ind + head + ' {}');
|
|
1307
|
+
return;
|
|
1308
|
+
}
|
|
1309
|
+
if (isSeq) {
|
|
1310
|
+
pushCompact(ind, v, false);
|
|
1311
|
+
return;
|
|
1312
|
+
}
|
|
1313
|
+
out.push(ind + head);
|
|
1314
|
+
writeMap(v, level + 1);
|
|
1315
|
+
return;
|
|
1316
|
+
}
|
|
1317
|
+
if (typeof v === 'string' && blockSafe(v)) {
|
|
1318
|
+
// 末尾に改行が無ければ |- 、1つだけなら |(余分な改行を足さない・削らない)
|
|
1319
|
+
out.push(ind + head + ' ' + (/\n$/.test(v) ? '|' : '|-'));
|
|
1320
|
+
const body = v.replace(/\n$/, '').split('\n');
|
|
1321
|
+
const inner = ind + pad;
|
|
1322
|
+
for (const ln of body) out.push(ln === '' ? '' : inner + ln);
|
|
1323
|
+
return;
|
|
1324
|
+
}
|
|
1325
|
+
const text = scalarText(v);
|
|
1326
|
+
if (text !== '') {
|
|
1327
|
+
out.push(ind + head + ' ' + text);
|
|
1328
|
+
return;
|
|
1329
|
+
}
|
|
1330
|
+
// null を空欄で書く設定でも、シーケンスの「- 」だけの行は次の行との切れ目が
|
|
1331
|
+
// 読み手にもパーサにも曖昧になるので、要素のときは必ず null と書く
|
|
1332
|
+
out.push(isSeq ? ind + head + ' null' : ind + head);
|
|
1333
|
+
}
|
|
1334
|
+
|
|
1335
|
+
/** 「- 」に続けて入れ子を書く(- name: a のコンパクト記法) */
|
|
1336
|
+
function pushCompact(ind, v, isArray) {
|
|
1337
|
+
const sub = [];
|
|
1338
|
+
const saved = out.length;
|
|
1339
|
+
if (isArray) writeSeq(v, 0);
|
|
1340
|
+
else writeMap(v, 0);
|
|
1341
|
+
for (let k = saved; k < out.length; k++) sub.push(out[k]);
|
|
1342
|
+
out.length = saved;
|
|
1343
|
+
out.push(ind + '- ' + sub[0]);
|
|
1344
|
+
for (let k = 1; k < sub.length; k++) out.push(sub[k] === '' ? '' : ind + ' ' + sub[k]);
|
|
1345
|
+
}
|
|
1346
|
+
|
|
1347
|
+
function writeMap(obj, level) {
|
|
1348
|
+
const keys = sortKeys ? Object.keys(obj).sort() : Object.keys(obj);
|
|
1349
|
+
for (const k of keys) writeEntry(keyText(k) + ':', obj[k], level, false);
|
|
1350
|
+
}
|
|
1351
|
+
|
|
1352
|
+
function writeSeq(arr, level) {
|
|
1353
|
+
for (const v of arr) writeEntry('-', v, level, true);
|
|
1354
|
+
}
|
|
1355
|
+
|
|
1356
|
+
if (o.docStart) out.push('---');
|
|
1357
|
+
if (Array.isArray(value)) {
|
|
1358
|
+
if (!value.length) out.push('[]');
|
|
1359
|
+
else writeSeq(value, 0);
|
|
1360
|
+
} else if (jyIsPlainObject(value)) {
|
|
1361
|
+
if (!Object.keys(value).length) out.push('{}');
|
|
1362
|
+
else writeMap(value, 0);
|
|
1363
|
+
} else if (typeof value === 'string' && blockSafe(value)) {
|
|
1364
|
+
out.push(/\n$/.test(value) ? '|' : '|-');
|
|
1365
|
+
for (const ln of value.replace(/\n$/, '').split('\n')) out.push(ln === '' ? '' : pad + ln);
|
|
1366
|
+
} else {
|
|
1367
|
+
out.push(scalarText(value));
|
|
1368
|
+
}
|
|
1369
|
+
return out.join('\n') + '\n';
|
|
1370
|
+
}
|
|
1371
|
+
|
|
1372
|
+
/* ---------------------------------------------------------------------------
|
|
1373
|
+
* 統計・エラー位置の抜き出し・変換の入口
|
|
1374
|
+
* ------------------------------------------------------------------------- */
|
|
1375
|
+
|
|
1376
|
+
const jyByteLength = (s) => (typeof TextEncoder === 'function' ? new TextEncoder().encode(s).length : Buffer.byteLength(s, 'utf8'));
|
|
1377
|
+
|
|
1378
|
+
/** 変換結果の規模を数える(キー数・最大の入れ子の深さなど) */
|
|
1379
|
+
function jyStats(value) {
|
|
1380
|
+
const s = { nodes: 0, keys: 0, objects: 0, arrays: 0, scalars: 0, max_depth: 0, non_finite: 0 };
|
|
1381
|
+
(function walk(v, d) {
|
|
1382
|
+
s.nodes += 1;
|
|
1383
|
+
if (d > s.max_depth) s.max_depth = d;
|
|
1384
|
+
if (Array.isArray(v)) {
|
|
1385
|
+
s.arrays += 1;
|
|
1386
|
+
for (const item of v) walk(item, d + 1);
|
|
1387
|
+
return;
|
|
1388
|
+
}
|
|
1389
|
+
if (jyIsPlainObject(v)) {
|
|
1390
|
+
s.objects += 1;
|
|
1391
|
+
const keys = Object.keys(v);
|
|
1392
|
+
s.keys += keys.length;
|
|
1393
|
+
for (const k of keys) walk(v[k], d + 1);
|
|
1394
|
+
return;
|
|
1395
|
+
}
|
|
1396
|
+
s.scalars += 1;
|
|
1397
|
+
if (typeof v === 'number' && !Number.isFinite(v)) s.non_finite += 1;
|
|
1398
|
+
})(value, 1);
|
|
1399
|
+
return s;
|
|
1400
|
+
}
|
|
1401
|
+
|
|
1402
|
+
/** エラー行の前後を切り出す(画面ではこれをそのままハイライト表示に使う) */
|
|
1403
|
+
function jyExcerpt(text, line, col, span) {
|
|
1404
|
+
const all = String(text).replace(/\r\n?/g, '\n').split('\n');
|
|
1405
|
+
if (all.length > 1 && all[all.length - 1] === '') all.pop(); // 末尾の改行が作る空行は数えない
|
|
1406
|
+
const from = Math.max(1, line - 2);
|
|
1407
|
+
const to = Math.min(all.length, line + 2);
|
|
1408
|
+
const rows = [];
|
|
1409
|
+
for (let n = from; n <= to; n++) {
|
|
1410
|
+
rows.push({ line: n, text: all[n - 1] === undefined ? '' : all[n - 1], error: n === line });
|
|
1411
|
+
}
|
|
1412
|
+
return { rows, line, col, span: span || 1 };
|
|
1413
|
+
}
|
|
1414
|
+
|
|
1415
|
+
/**
|
|
1416
|
+
* JSON ⇄ YAML の変換1回分。整形(json→json / yaml→yaml)も同じ入口で扱う。
|
|
1417
|
+
*
|
|
1418
|
+
* @param {object} opts
|
|
1419
|
+
* @param {'json2yaml'|'yaml2json'|'json2json'|'yaml2yaml'} [opts.direction='json2yaml']
|
|
1420
|
+
* @param {string} opts.text
|
|
1421
|
+
* @param {boolean}[opts.relaxed=true] JSON入力でコメント・末尾カンマ等を受け取る
|
|
1422
|
+
* 出力オプションは jyFormatYaml / jyFormatJson と共通。
|
|
1423
|
+
*/
|
|
1424
|
+
function jyConvert(opts) {
|
|
1425
|
+
const o = opts || {};
|
|
1426
|
+
const allowed = ['json2yaml', 'yaml2json', 'json2json', 'yaml2yaml'];
|
|
1427
|
+
const direction = allowed.indexOf(o.direction) === -1 ? 'json2yaml' : o.direction;
|
|
1428
|
+
const from = direction.slice(0, 4);
|
|
1429
|
+
const to = direction.slice(5);
|
|
1430
|
+
const text = typeof o.text === 'string' ? o.text : '';
|
|
1431
|
+
|
|
1432
|
+
if (text.trim() === '') {
|
|
1433
|
+
return { ok: true, direction, from, to, empty: true, output: '', notes: [], stats: null, documents: 0 };
|
|
1434
|
+
}
|
|
1435
|
+
|
|
1436
|
+
const parsed = from === 'json' ? jyParseJson(text, o) : jyParseYaml(text);
|
|
1437
|
+
if (!parsed.ok) {
|
|
1438
|
+
return {
|
|
1439
|
+
ok: false,
|
|
1440
|
+
direction,
|
|
1441
|
+
from,
|
|
1442
|
+
to,
|
|
1443
|
+
error: parsed.error,
|
|
1444
|
+
excerpt: jyExcerpt(text, parsed.error.line, parsed.error.col, parsed.error.found ? String(parsed.error.found).length : 1),
|
|
1445
|
+
notes: parsed.notes,
|
|
1446
|
+
};
|
|
1447
|
+
}
|
|
1448
|
+
|
|
1449
|
+
const value = parsed.value;
|
|
1450
|
+
const stats = jyStats(value);
|
|
1451
|
+
const notes = parsed.notes.slice();
|
|
1452
|
+
if (to === 'json' && stats.non_finite > 0) {
|
|
1453
|
+
notes.push({ code: 'NONFINITE_OUTPUT', level: 'warn', count: stats.non_finite, items: [], lines: [] });
|
|
1454
|
+
}
|
|
1455
|
+
const output = to === 'yaml' ? jyFormatYaml(value, o) : jyFormatJson(value, o) + '\n';
|
|
1456
|
+
|
|
1457
|
+
return {
|
|
1458
|
+
ok: true,
|
|
1459
|
+
direction,
|
|
1460
|
+
from,
|
|
1461
|
+
to,
|
|
1462
|
+
output,
|
|
1463
|
+
value,
|
|
1464
|
+
documents: from === 'yaml' ? parsed.docs.length : 1,
|
|
1465
|
+
input_bytes: jyByteLength(text),
|
|
1466
|
+
output_bytes: jyByteLength(output),
|
|
1467
|
+
input_lines: text.replace(/\n$/, '').split('\n').length,
|
|
1468
|
+
output_lines: output.replace(/\n$/, '').split('\n').length,
|
|
1469
|
+
stats,
|
|
1470
|
+
notes,
|
|
1471
|
+
};
|
|
1472
|
+
}
|
|
1473
|
+
|
|
1474
|
+
/* ==================== ここまで変換コア ==================== */
|
|
1475
|
+
|
|
1476
|
+
/* ---------------------------------------------------------------------------
|
|
1477
|
+
* MCPの入口
|
|
1478
|
+
* ------------------------------------------------------------------------- */
|
|
1479
|
+
|
|
1480
|
+
// 構文エラーの説明(サイト側は同じコードを日英で出し分けている。ここは日本語のみ)
|
|
1481
|
+
const ERROR_TEXT = {
|
|
1482
|
+
EMPTY_INPUT: () => '入力が空です。',
|
|
1483
|
+
TOO_DEEP: () => '入れ子が深すぎます(200段まで)。',
|
|
1484
|
+
JSON_UNEXPECTED_END: () => '入力が途中で終わっています。閉じ括弧が足りていないか確認してください。',
|
|
1485
|
+
JSON_TRAILING_DATA: (e) => `JSONの値の後ろに余分な文字があります(${e.found})。JSONに書けるのは1つの値だけです。`,
|
|
1486
|
+
JSON_VALUE_EXPECTED: (e) => `値が必要な位置に ${e.found} があります。`,
|
|
1487
|
+
JSON_KEY_EXPECTED: (e) => `キーが必要な位置に ${e.found} があります。キーは "…" で囲みます。`,
|
|
1488
|
+
JSON_COLON_EXPECTED: (e) => `キーの後ろに : が必要です(見つかったのは ${e.found})。`,
|
|
1489
|
+
JSON_COMMA_EXPECTED: (e) => `区切りの , か閉じ括弧が必要です(見つかったのは ${e.found})。`,
|
|
1490
|
+
JSON_UNTERMINATED_STRING: (e) => `文字列が ${e.found} で閉じられていません。`,
|
|
1491
|
+
JSON_UNTERMINATED_COMMENT: () => 'コメント /* が */ で閉じられていません。',
|
|
1492
|
+
JSON_BAD_ESCAPE: (e) => `文字列の中で使えないエスケープです(${e.found})。`,
|
|
1493
|
+
JSON_BAD_TOKEN: (e) => `JSONの値として読めません(${e.found})。文字列なら "…" で囲んでください。`,
|
|
1494
|
+
JSON_RAW_CONTROL: (e) => `文字列の中に生の制御文字(${e.found})があります。\\n や \\t のように書いてください。`,
|
|
1495
|
+
JSON_TRAILING_COMMA: () => '最後の要素の後ろにカンマがあります。JSONでは書けません。',
|
|
1496
|
+
JSON_SINGLE_QUOTE: () => "JSONの文字列は ' ではなく \" で囲みます。",
|
|
1497
|
+
JSON_UNQUOTED_KEY: (e) => `キーを "…" で囲んでください(${e.found})。`,
|
|
1498
|
+
JSON_COMMENT: () => 'JSONにコメントは書けません。',
|
|
1499
|
+
TAB_INDENT: () => 'インデントにタブが使われています。YAMLはタブでの字下げを認めていないので、半角スペースに置き換えてください。',
|
|
1500
|
+
YAML_BAD_INDENT: (e) => `インデントが揃っていません(${e.found})。同じ階層の行は桁を合わせてください。`,
|
|
1501
|
+
YAML_SEQ_IN_MAP: () => 'キーが並ぶ位置に「- 」があります。マップとシーケンスは同じ階層に混ぜられません。',
|
|
1502
|
+
YAML_KEY_EXPECTED: (e) => `「キー: 値」の形になっていません(${e.found})。値の後ろには : が必要です。`,
|
|
1503
|
+
YAML_EXPLICIT_KEY: () => '「? キー」という明示キーの書き方には対応していません(JSONのキーは文字列だけなので、通常の「キー: 値」に書き換えてください)。',
|
|
1504
|
+
YAML_VALUE_THEN_BLOCK: (e) => `値を書いた行の下に、より深い行が続いています(${e.found})。上の行の値を消すか、この行のインデントを浅くしてください。`,
|
|
1505
|
+
YAML_NESTED_COLON: (e) => `1行に「キー: 値」が2つあります(${e.found})。値に「: 」を含めるなら "…" で囲んでください。`,
|
|
1506
|
+
YAML_SEQ_INLINE: (e) => `「- 」で始まる要素は次の行から書きます(${e.found})。1行に収めるなら [a, b] の形にしてください。`,
|
|
1507
|
+
YAML_UNTERMINATED_QUOTE: (e) => `引用符 ${e.found} が閉じられていません。`,
|
|
1508
|
+
YAML_BAD_ESCAPE: (e) => `"…" の中で使えないエスケープです(${e.found})。`,
|
|
1509
|
+
YAML_UNTERMINATED_FLOW: () => '[ または { が閉じられていません。',
|
|
1510
|
+
YAML_FLOW_SEP: (e) => `[ ] { } の中の区切りが不正です(${e.found})。要素は , で区切ります。`,
|
|
1511
|
+
YAML_FLOW_COLON: (e) => `{ } の中でキーの後ろに : がありません(${e.found})。`,
|
|
1512
|
+
YAML_ALIAS_NOT_FOUND: (e) => `参照先のアンカーがありません(${e.found})。*.js のように * で始まる値は "…" で囲んでください。`,
|
|
1513
|
+
YAML_ALIAS_TRAILING: (e) => `エイリアスの後ろに余分な文字があります(${e.found})。`,
|
|
1514
|
+
YAML_TRAILING_TEXT: (e) => `引用符や [ ] { } の後ろに余分な文字があります(${e.found})。`,
|
|
1515
|
+
YAML_BLOCK_HEADER: (e) => `ブロックスカラー(| や >)の指定が読めません(${e.found})。書けるのは chomping(- +)とインデント(1-9)だけです。`,
|
|
1516
|
+
YAML_BLOCK_INDENT: () => '| や > の中身のインデントが揃っていません。最初の行より浅い行は書けません。',
|
|
1517
|
+
YAML_BAD_TAG_VALUE: (e) => `タグの型に合わない値です(${e.found})。`,
|
|
1518
|
+
YAML_INTERNAL: () => '解析が進まなくなりました。書き方を単純にしてお試しください。',
|
|
1519
|
+
};
|
|
1520
|
+
|
|
1521
|
+
// 指摘事項(構文としては通るが、読み替えで意味が変わりうるもの)の説明
|
|
1522
|
+
const NOTE_TEXT = {
|
|
1523
|
+
DUPLICATE_KEY: (n) => `同じキーが重なっています(${n.items.join(' / ')})。最後に書いた値だけが残ります。`,
|
|
1524
|
+
NUMBER_PRECISION: (n) => `${n.items.join(' / ')} は倍精度小数で正確に表せない大きさです。桁が落ちるので、IDなら "…" で囲んで文字列にしてください。`,
|
|
1525
|
+
NONFINITE_OUTPUT: (n) => `.inf / .nan はJSONに無い値なので null にしました(${n.count}件)。`,
|
|
1526
|
+
MULTI_DOC: (n) => `--- で区切られた${n.count}個のドキュメントを、JSONの配列1つにまとめました。`,
|
|
1527
|
+
JSON_COMMENT: (n) => `コメントが${n.count}箇所あります。JSONの仕様には無いので、読み飛ばして変換しました(YAMLにはコメントを書けます)。`,
|
|
1528
|
+
JSON_TRAILING_COMMA: (n) => `最後の要素の後ろのカンマが${n.count}箇所あります。JSONとしては不正なので、無いものとして解釈しました。`,
|
|
1529
|
+
JSON_SINGLE_QUOTE: (n) => `シングルクォートの文字列が${n.count}箇所あります。JSONでは " を使います。`,
|
|
1530
|
+
JSON_UNQUOTED_KEY: (n) => `引用符の無いキーがあります(${n.items.join(' / ')})。JSONでは "…" で囲みます。`,
|
|
1531
|
+
JSON_RELAXED_NUMBER: (n) => `JSONの数値としては不正な書き方です(${n.items.join(' / ')})。読める形に解釈しました。`,
|
|
1532
|
+
JSON_RAW_CONTROL: (n) => `文字列の中に生の制御文字があります(${n.items.join(' / ')})。`,
|
|
1533
|
+
JSON_NONFINITE: (n) => `NaN / Infinity はJSONに無い値です(${n.items.join(' / ')})。`,
|
|
1534
|
+
YAML_LEADING_ZERO: (n) => `${n.items.join(' / ')} は先頭の0を無視した10進の数値になります。パーミッションや電話番号なら "…" で囲んで文字列にしてください。`,
|
|
1535
|
+
YAML11_BOOL: (n) => `${n.items.join(' / ')} はYAML 1.2では文字列ですが、YAML 1.1のパーサ(PyYAMLなど)では真偽値になります。文字列として渡すなら "…" で囲むと安全です。`,
|
|
1536
|
+
YAML_TIMESTAMP: (n) => `${n.items.join(' / ')} は日付に見えます。ここでは文字列にしていますが、日時型として読むパーサもあります。`,
|
|
1537
|
+
YAML_SEXAGESIMAL: (n) => `${n.items.join(' / ')} はYAML 1.1のパーサでは60進数の整数として読まれます(12:30 → 750)。時刻なら "…" で囲んでください。`,
|
|
1538
|
+
YAML_MERGE_KEY: (n) => `マージキー << を${n.count}箇所で展開しました。JSONにマージの仕組みは無いので、展開後の内容を書き出します。`,
|
|
1539
|
+
YAML_BAD_MERGE: (n) => `<< の参照先がマップではないため、マージできませんでした(${n.count}箇所)。`,
|
|
1540
|
+
YAML_NONSTRING_KEY: (n) => `文字列でないキー(${n.items.join(' / ')})を文字列にしました。JSONのキーは文字列だけです。`,
|
|
1541
|
+
YAML_DIRECTIVE: (n) => `ディレクティブ(${n.items.join(' / ')})は読み飛ばしました。`,
|
|
1542
|
+
YAML_UNKNOWN_TAG: (n) => `知らないタグ(${n.items.join(' / ')})は無視して、値をそのまま使いました。`,
|
|
1543
|
+
YAML_BINARY: (n) => `!!binary はBase64の文字列のまま渡しました(${n.count}箇所)。`,
|
|
1544
|
+
YAML_ALIAS_EXPANDED: () => 'エイリアス(*名前)を展開しました。JSONに参照の仕組みは無いので、同じ内容が複製されます。',
|
|
1545
|
+
};
|
|
1546
|
+
|
|
1547
|
+
export class JsonYamlError extends Error {}
|
|
1548
|
+
|
|
1549
|
+
/** エラーの位置を、行番号つきの抜き出しと ^ で示す文字列にする */
|
|
1550
|
+
function excerptText(excerpt) {
|
|
1551
|
+
if (!excerpt) return '';
|
|
1552
|
+
const width = String(excerpt.rows[excerpt.rows.length - 1].line).length;
|
|
1553
|
+
const out = [];
|
|
1554
|
+
for (const row of excerpt.rows) {
|
|
1555
|
+
const shown = row.text.replace(/\t/g, '→ ');
|
|
1556
|
+
out.push(` ${String(row.line).padStart(width, ' ')} | ${shown}`);
|
|
1557
|
+
if (row.error) {
|
|
1558
|
+
const before = row.text.slice(0, Math.max(0, excerpt.col - 1)).replace(/\t/g, '→ ');
|
|
1559
|
+
out.push(` ${' '.repeat(width)} | ${' '.repeat(before.length)}^`);
|
|
1560
|
+
}
|
|
1561
|
+
}
|
|
1562
|
+
return out.join('\n');
|
|
1563
|
+
}
|
|
1564
|
+
|
|
1565
|
+
/**
|
|
1566
|
+
* JSON ⇄ YAML の変換1回分(MCPの入口の中身)。
|
|
1567
|
+
* 構文エラーは JsonYamlError として投げる(行・桁・原因・抜き出しをメッセージに含める)。
|
|
1568
|
+
*/
|
|
1569
|
+
async function convert(direction, opts) {
|
|
1570
|
+
const o = opts || {};
|
|
1571
|
+
const hasText = typeof o.text === 'string';
|
|
1572
|
+
if (hasText === Boolean(o.path)) throw new JsonYamlError('text か path のどちらか一方を渡してください');
|
|
1573
|
+
if (o.indent !== undefined && o.indent !== 'tab' && !(Number.isInteger(Number(o.indent)) && Number(o.indent) >= 0 && Number(o.indent) <= 8)) {
|
|
1574
|
+
throw new JsonYamlError(`indent は 0-8 の整数か "tab": ${o.indent}`);
|
|
1575
|
+
}
|
|
1576
|
+
if (o.quote && ['auto', 'single', 'double'].indexOf(o.quote) === -1) {
|
|
1577
|
+
throw new JsonYamlError(`quote は auto / single / double: ${o.quote}`);
|
|
1578
|
+
}
|
|
1579
|
+
if (o.nullStyle && ['null', 'tilde', 'empty'].indexOf(o.nullStyle) === -1) {
|
|
1580
|
+
throw new JsonYamlError(`nullStyle は null / tilde / empty: ${o.nullStyle}`);
|
|
1581
|
+
}
|
|
1582
|
+
|
|
1583
|
+
const input = hasText ? o.text : await readFile(o.path, 'utf8');
|
|
1584
|
+
const r = jyConvert({ ...o, direction, text: input });
|
|
1585
|
+
|
|
1586
|
+
if (!r.ok) {
|
|
1587
|
+
const fn = ERROR_TEXT[r.error.code];
|
|
1588
|
+
const where = `${r.error.line}行 ${r.error.col}桁`;
|
|
1589
|
+
const what = fn ? fn(r.error) : r.error.code;
|
|
1590
|
+
const body = excerptText(r.excerpt);
|
|
1591
|
+
throw new JsonYamlError(
|
|
1592
|
+
`${r.from === 'json' ? 'JSON' : 'YAML'}の構文エラー(${r.error.code}): ${where}: ${what}${body ? '\n' + body : ''}`,
|
|
1593
|
+
);
|
|
1594
|
+
}
|
|
1595
|
+
|
|
1596
|
+
const result = {
|
|
1597
|
+
direction: r.direction,
|
|
1598
|
+
from: r.from,
|
|
1599
|
+
to: r.to,
|
|
1600
|
+
source: hasText ? { type: 'text' } : { path: o.path, name: basename(o.path) },
|
|
1601
|
+
empty: Boolean(r.empty),
|
|
1602
|
+
text: r.output,
|
|
1603
|
+
input_bytes: r.empty ? 0 : r.input_bytes,
|
|
1604
|
+
output_bytes: r.empty ? 0 : r.output_bytes,
|
|
1605
|
+
input_lines: r.empty ? 0 : r.input_lines,
|
|
1606
|
+
output_lines: r.empty ? 0 : r.output_lines,
|
|
1607
|
+
documents: r.documents,
|
|
1608
|
+
stats: r.stats,
|
|
1609
|
+
options: r.to === 'yaml'
|
|
1610
|
+
? {
|
|
1611
|
+
indent: Number(o.indent) || 2,
|
|
1612
|
+
quote: o.quote || 'auto',
|
|
1613
|
+
null_style: o.nullStyle || 'null',
|
|
1614
|
+
block: o.block !== false,
|
|
1615
|
+
sort_keys: Boolean(o.sortKeys),
|
|
1616
|
+
doc_start: Boolean(o.docStart),
|
|
1617
|
+
}
|
|
1618
|
+
: {
|
|
1619
|
+
indent: o.indent === undefined ? 2 : o.indent === 'tab' ? 'tab' : Number(o.indent),
|
|
1620
|
+
sort_keys: Boolean(o.sortKeys),
|
|
1621
|
+
ascii: Boolean(o.ascii),
|
|
1622
|
+
},
|
|
1623
|
+
notes: (r.notes || []).map((n) => ({
|
|
1624
|
+
code: n.code,
|
|
1625
|
+
level: n.level,
|
|
1626
|
+
count: n.count,
|
|
1627
|
+
lines: n.lines,
|
|
1628
|
+
message: NOTE_TEXT[n.code] ? NOTE_TEXT[n.code](n) : n.code,
|
|
1629
|
+
})),
|
|
1630
|
+
};
|
|
1631
|
+
|
|
1632
|
+
if (o.outputPath) {
|
|
1633
|
+
await writeFile(o.outputPath, r.output, 'utf8');
|
|
1634
|
+
result.output = o.outputPath;
|
|
1635
|
+
// ファイルに書けたなら本文は重複した重い情報でしかない
|
|
1636
|
+
delete result.text;
|
|
1637
|
+
}
|
|
1638
|
+
return result;
|
|
1639
|
+
}
|
|
1640
|
+
|
|
1641
|
+
/**
|
|
1642
|
+
* JSON(またはUTF-8のJSONファイル)をYAMLへ変換して整形する。
|
|
1643
|
+
*
|
|
1644
|
+
* @param {object} opts
|
|
1645
|
+
* @param {string} [opts.text] 変換するJSON(path と排他)
|
|
1646
|
+
* @param {string} [opts.path] 変換するJSONファイルの絶対パス(text と排他)
|
|
1647
|
+
* @param {string} [opts.outputPath] 結果を書き出す絶対パス(指定すると text は返さない)
|
|
1648
|
+
* @param {number} [opts.indent=2] YAMLのインデント幅(1-8)
|
|
1649
|
+
* @param {'auto'|'single'|'double'} [opts.quote='auto'] 引用符の付け方
|
|
1650
|
+
* @param {'null'|'tilde'|'empty'} [opts.nullStyle='null'] null の書き方
|
|
1651
|
+
* @param {boolean}[opts.block=true] 改行を含む文字列をブロックスカラー(|)で書く
|
|
1652
|
+
* @param {boolean}[opts.sortKeys=false] キーを名前順に並べる
|
|
1653
|
+
* @param {boolean}[opts.docStart=false] 先頭に --- を付ける
|
|
1654
|
+
* @param {boolean}[opts.relaxed=true] コメント・末尾カンマ等を含むJSONも読む
|
|
1655
|
+
*/
|
|
1656
|
+
export function jsonToYaml(opts = {}) {
|
|
1657
|
+
return convert('json2yaml', opts);
|
|
1658
|
+
}
|
|
1659
|
+
|
|
1660
|
+
/**
|
|
1661
|
+
* YAML(またはUTF-8のYAMLファイル)をJSONへ変換する。構文チェックにも使える。
|
|
1662
|
+
*
|
|
1663
|
+
* @param {object} opts
|
|
1664
|
+
* @param {string} [opts.text] 変換するYAML(path と排他)
|
|
1665
|
+
* @param {string} [opts.path] 変換するYAMLファイルの絶対パス(text と排他)
|
|
1666
|
+
* @param {string} [opts.outputPath] 結果を書き出す絶対パス(指定すると text は返さない)
|
|
1667
|
+
* @param {number|'tab'} [opts.indent=2] JSONのインデント(0 で1行にまとめる)
|
|
1668
|
+
* @param {boolean}[opts.sortKeys=false] キーを名前順に並べる
|
|
1669
|
+
* @param {boolean}[opts.ascii=false] 非ASCII文字を \\uXXXX にする
|
|
1670
|
+
*/
|
|
1671
|
+
export function yamlToJson(opts = {}) {
|
|
1672
|
+
return convert('yaml2json', opts);
|
|
1673
|
+
}
|
|
1674
|
+
|
|
1675
|
+
/** JSONをJSONのまま整形する(インデントの付け替え・キーの並べ替え) */
|
|
1676
|
+
export function formatJsonFile(opts = {}) {
|
|
1677
|
+
return convert('json2json', opts);
|
|
1678
|
+
}
|
|
1679
|
+
|
|
1680
|
+
/** YAMLをYAMLのまま整形する(インデント・引用符の正規化) */
|
|
1681
|
+
export function formatYamlFile(opts = {}) {
|
|
1682
|
+
return convert('yaml2yaml', opts);
|
|
1683
|
+
}
|
|
1684
|
+
|
|
1685
|
+
export {
|
|
1686
|
+
jyParseJson as parseJson,
|
|
1687
|
+
jyParseYaml as parseYaml,
|
|
1688
|
+
jyFormatJson as formatJson,
|
|
1689
|
+
jyFormatYaml as formatYaml,
|
|
1690
|
+
jyConvert as jsonYamlConvert,
|
|
1691
|
+
jyResolveScalar as resolveYamlScalar,
|
|
1692
|
+
jyPlainSafe as yamlPlainSafe,
|
|
1693
|
+
};
|