@first-ch/tools-mcp 0.36.0 → 0.38.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.
@@ -0,0 +1,2954 @@
1
+ /* OpenAPI → 日本語ドキュメント&TypeScript型定義(openapi_doc_generate)
2
+ * tools.first-ch.com/openapi-doc-gen/ と同一ロジック。
3
+ * 変換コアの開始コメントから oaFileBase の終わりまでは FirstCHTools の site/openapi-doc-gen/core.js と同一
4
+ * (2箇所ルール: site側が正本・片方を直したらもう片方も同じ内容で反映する)。次の diff が空なら同期している
5
+ * (site側は末尾の export { … } を落として字下げ2文字を落とす・こちらは写しの終わりの目印の手前まで):
6
+ * S=…/FirstCHTools/site/openapi-doc-gen/core.js
7
+ * diff <(sed -n '/^ \/\* =* ここから変換コア/,/^export {/p' $S | sed '$d' | sed 's/^ //') \
8
+ * <(sed -n '/^\/\* =* ここから変換コア/,/^\/\* =* ここまで site/p' openapi-doc.mjs | sed '$d' | sed '$d')
9
+ *
10
+ * YAML・JSON のパーサ(変換コア)は json-yaml.mjs と中身がほぼ同じだが、import せずに写しを持つ。
11
+ * 違いが jyParseYaml の内側の1行(プレーンスカラーの折り返し行が「- 」で始まっても続きの文として読む)で、
12
+ * 変換コアは関数の外から挙動を切り替える口を持たないため、json-yaml.mjs の挙動(json_to_yaml / yaml_to_json は
13
+ * 書き損じとしてエラーにする)を変えずに共有する方法が無い。site 側も同じ理由で core.js に写しを持っている。
14
+ * site 側の CI(tests/openapi-doc-gen.test.mjs)が /json-yaml/ との「1行を除いた一致」を確かめているので、
15
+ * site/openapi-doc-gen/core.js と一致していれば json-yaml.mjs とも1行差で揃う。
16
+ *
17
+ * 外部ライブラリなし。完全ローカル処理・ネットワーク送信なし(別ファイル・URLを指す $ref も読みに行かない)。 */
18
+
19
+ import { readFile } from 'node:fs/promises';
20
+ import { join, isAbsolute } from 'node:path';
21
+ import { writeOutput } from './fs-safe.mjs';
22
+
23
+ // 「ここから変換コア」〜「ここまで変換コア」は /json-yaml/app.js の同じ範囲(YAML・JSON の自前パーサ)を
24
+ // 写したもの。向こうを直したらこちらにも写し直す(tests/openapi-doc-gen.test.mjs が一致を確かめる)。
25
+ // 違いは1行だけ: プレーンスカラーの折り返し行が「- 」で始まっても続きの文として読む(YAML の仕様どおり)。
26
+ // /json-yaml/ は書き損じを黙って通さないためにここをエラーにしているが、実在の仕様書の description
27
+ // (GitHub の REST API 仕様など)はこの書き方を普通に使うので、こちらでは読めないと困る。
28
+ /* eslint-disable no-unused-vars */
29
+
30
+ /* ==================== ここから変換コア(site / MCP で同一) ==================== */
31
+
32
+ // 入れ子の深さの上限(壊れた入力でスタックを食い潰さないための保険)
33
+ const JY_MAX_DEPTH = 200;
34
+
35
+ // 指摘事項の重さ。warn = 出力が意図と変わる可能性あり / info = 知っておくと良い
36
+ const JY_NOTE_LEVEL = {
37
+ DUPLICATE_KEY: 'warn',
38
+ NUMBER_PRECISION: 'warn',
39
+ NONFINITE_OUTPUT: 'warn',
40
+ LONE_SURROGATE: 'warn',
41
+ MULTI_DOC: 'info',
42
+ JSON_COMMENT: 'warn',
43
+ JSON_TRAILING_COMMA: 'warn',
44
+ JSON_SINGLE_QUOTE: 'warn',
45
+ JSON_UNQUOTED_KEY: 'warn',
46
+ JSON_RELAXED_NUMBER: 'warn',
47
+ JSON_RAW_CONTROL: 'warn',
48
+ JSON_NONFINITE: 'warn',
49
+ YAML_LEADING_ZERO: 'warn',
50
+ YAML11_BOOL: 'info',
51
+ YAML_TIMESTAMP: 'info',
52
+ YAML_SEXAGESIMAL: 'warn',
53
+ YAML_MERGE_KEY: 'info',
54
+ YAML_BAD_MERGE: 'warn',
55
+ YAML_NONSTRING_KEY: 'warn',
56
+ YAML_DIRECTIVE: 'info',
57
+ YAML_UNKNOWN_TAG: 'warn',
58
+ YAML_BINARY: 'info',
59
+ YAML_ALIAS_EXPANDED: 'info',
60
+ };
61
+
62
+ // YAML 1.1 が真偽値として扱っていた綴り。1.2 では文字列だが、
63
+ // 読み込む側のパーサが 1.1 のままだと意味が変わるので指摘する(いわゆる Norway problem)。
64
+ const JY_YAML11_BOOL = /^(y|Y|yes|Yes|YES|n|N|no|No|NO|on|On|ON|off|Off|OFF)$/;
65
+
66
+ // YAML 1.1 の60進数表記。1.2 では文字列だが、PyYAML 等では 12:30 が 750 になる。
67
+ const JY_SEXAGESIMAL = /^[-+]?[0-9][0-9_]*(:[0-5]?[0-9])+$/;
68
+
69
+ /** 指摘事項を種類ごとにまとめて数える入れ物 */
70
+ function jyNotes() {
71
+ const list = [];
72
+ const byCode = Object.create(null);
73
+ return {
74
+ list,
75
+ add(code, item, line) {
76
+ let n = byCode[code];
77
+ if (!n) {
78
+ n = { code, level: JY_NOTE_LEVEL[code] || 'warn', count: 0, items: [], lines: [] };
79
+ byCode[code] = n;
80
+ list.push(n);
81
+ }
82
+ n.count += 1;
83
+ if (item !== undefined && item !== null && n.items.length < 6 && n.items.indexOf(item) === -1) n.items.push(item);
84
+ if (line && n.lines.length < 6 && n.lines.indexOf(line) === -1) n.lines.push(line);
85
+ return n;
86
+ },
87
+ };
88
+ }
89
+
90
+ /** 文字列中のインデックスを 1 始まりの行・桁へ */
91
+ function jyLineCol(src, index) {
92
+ let line = 1;
93
+ let lastBreak = -1;
94
+ const end = Math.min(index, src.length);
95
+ for (let k = 0; k < end; k++) {
96
+ if (src.charCodeAt(k) === 10) {
97
+ line += 1;
98
+ lastBreak = k;
99
+ }
100
+ }
101
+ return { line, col: end - lastBreak };
102
+ }
103
+
104
+ const jyIsPlainObject = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
105
+
106
+ /**
107
+ * YAML のプレーンスカラーを値へ解決する(YAML 1.2 core schema)。
108
+ * 出力側(formatYaml)でも「引用符なしで書けるか」の判定に使うので、副作用なしの純関数にしてある。
109
+ */
110
+ function jyResolveScalar(s) {
111
+ if (s === '' || s === '~' || s === 'null' || s === 'Null' || s === 'NULL') return null;
112
+ if (s === 'true' || s === 'True' || s === 'TRUE') return true;
113
+ if (s === 'false' || s === 'False' || s === 'FALSE') return false;
114
+ if (/^[-+]?[0-9]+$/.test(s)) return Number(s);
115
+ if (/^0o[0-7]+$/.test(s)) return parseInt(s.slice(2), 8);
116
+ if (/^[-+]?0x[0-9a-fA-F]+$/.test(s)) {
117
+ const n = parseInt(s.replace(/^[-+]/, '').slice(2), 16);
118
+ return s.charAt(0) === '-' ? -n : n;
119
+ }
120
+ if (/^[-+]?(\.[0-9]+|[0-9]+(\.[0-9]*)?)([eE][-+]?[0-9]+)?$/.test(s)) return Number(s);
121
+ if (/^[-+]?\.(inf|Inf|INF)$/.test(s)) return s.charAt(0) === '-' ? -Infinity : Infinity;
122
+ if (/^\.(nan|NaN|NAN)$/.test(s)) return NaN;
123
+ return s;
124
+ }
125
+
126
+ /** プレーンスカラーについて出す指摘のコード(値そのものは変えない) */
127
+ function jyScalarNotes(s) {
128
+ const out = [];
129
+ if (/^[-+]?0[0-9]+$/.test(s)) out.push('YAML_LEADING_ZERO');
130
+ if (/^[-+]?[0-9]+$/.test(s) && !Number.isSafeInteger(Number(s))) out.push('NUMBER_PRECISION');
131
+ if (JY_YAML11_BOOL.test(s)) out.push('YAML11_BOOL');
132
+ if (/^[0-9]{4}-[0-9]{2}-[0-9]{2}([Tt ].*)?$/.test(s)) out.push('YAML_TIMESTAMP');
133
+ if (JY_SEXAGESIMAL.test(s)) out.push('YAML_SEXAGESIMAL');
134
+ return out;
135
+ }
136
+
137
+ /* ---------------------------------------------------------------------------
138
+ * JSON パーサ
139
+ *
140
+ * JSON.parse を使わず自前で読むのは、エラーの行・桁をブラウザ差なく取るため。
141
+ * relaxed(既定 true)では tsconfig 系のコメント・末尾カンマ・シングルクォート・
142
+ * 裸のキーも受け取り、「JSONとしては不正」と指摘したうえで変換する。
143
+ * ------------------------------------------------------------------------- */
144
+ function jyParseJson(text, opts) {
145
+ const o = opts || {};
146
+ const relaxed = o.relaxed !== false;
147
+ const src = String(text).replace(/^\uFEFF/, '');
148
+ const N = jyNotes();
149
+ let i = 0;
150
+ let depth = 0;
151
+
152
+ const fail = (code, at, found) => {
153
+ const e = new Error(code);
154
+ e.jy = { code, index: at === undefined ? i : at, found };
155
+ throw e;
156
+ };
157
+ const lineOf = (at) => jyLineCol(src, at).line;
158
+ const here = () => (i < src.length ? src.charAt(i) : 'EOF');
159
+
160
+ function ws() {
161
+ for (;;) {
162
+ const c = src.charCodeAt(i);
163
+ if (c === 32 || c === 9 || c === 10 || c === 13) {
164
+ i += 1;
165
+ continue;
166
+ }
167
+ if (src.charAt(i) === '/' && (src.charAt(i + 1) === '/' || src.charAt(i + 1) === '*')) {
168
+ if (!relaxed) fail('JSON_COMMENT', i);
169
+ N.add('JSON_COMMENT', null, lineOf(i));
170
+ if (src.charAt(i + 1) === '/') {
171
+ while (i < src.length && src.charAt(i) !== '\n') i += 1;
172
+ } else {
173
+ const end = src.indexOf('*/', i + 2);
174
+ if (end === -1) fail('JSON_UNTERMINATED_COMMENT', i);
175
+ i = end + 2;
176
+ }
177
+ continue;
178
+ }
179
+ return;
180
+ }
181
+ }
182
+
183
+ function readString(quote) {
184
+ const start = i;
185
+ i += 1;
186
+ let out = '';
187
+ for (;;) {
188
+ if (i >= src.length) fail('JSON_UNTERMINATED_STRING', start, quote);
189
+ const c = src.charAt(i);
190
+ if (c === quote) {
191
+ i += 1;
192
+ return out;
193
+ }
194
+ if (c === '\\') {
195
+ const e = src.charAt(i + 1);
196
+ if (e === 'u') {
197
+ const hex = src.substr(i + 2, 4);
198
+ if (!/^[0-9a-fA-F]{4}$/.test(hex)) fail('JSON_BAD_ESCAPE', i, src.substr(i, 6));
199
+ out += String.fromCharCode(parseInt(hex, 16));
200
+ i += 6;
201
+ continue;
202
+ }
203
+ const simple = { '"': '"', "'": "'", '\\': '\\', '/': '/', b: '\b', f: '\f', n: '\n', r: '\r', t: '\t' };
204
+ if (simple[e] === undefined) fail('JSON_BAD_ESCAPE', i, '\\' + (e || ''));
205
+ if (e === "'") {
206
+ if (!relaxed) fail('JSON_BAD_ESCAPE', i, "\\'");
207
+ N.add('JSON_RELAXED_NUMBER', "\\'", lineOf(i));
208
+ }
209
+ out += simple[e];
210
+ i += 2;
211
+ continue;
212
+ }
213
+ const code = src.charCodeAt(i);
214
+ if (code < 0x20) {
215
+ if (!relaxed) fail('JSON_RAW_CONTROL', i, 'U+' + code.toString(16).toUpperCase().padStart(4, '0'));
216
+ N.add('JSON_RAW_CONTROL', 'U+' + code.toString(16).toUpperCase().padStart(4, '0'), lineOf(i));
217
+ }
218
+ out += c;
219
+ i += 1;
220
+ }
221
+ }
222
+
223
+ function readLiteral() {
224
+ const start = i;
225
+ while (i < src.length && ',}]: \t\r\n'.indexOf(src.charAt(i)) === -1) {
226
+ if (src.charAt(i) === '/' && (src.charAt(i + 1) === '/' || src.charAt(i + 1) === '*')) break;
227
+ i += 1;
228
+ }
229
+ const tok = src.slice(start, i);
230
+ if (tok === '') fail('JSON_VALUE_EXPECTED', start, here());
231
+ if (tok === 'true') return true;
232
+ if (tok === 'false') return false;
233
+ if (tok === 'null') return null;
234
+ if (/^-?(0|[1-9][0-9]*)(\.[0-9]+)?([eE][-+]?[0-9]+)?$/.test(tok)) {
235
+ const n = Number(tok);
236
+ if (/^-?[0-9]+$/.test(tok) && !Number.isSafeInteger(n)) N.add('NUMBER_PRECISION', tok, lineOf(start));
237
+ return n;
238
+ }
239
+ // JSON としては不正だが読めるもの(+1 / .5 / 1. / 0755 / 0x1F / NaN / Infinity)
240
+ if (/^[-+]?(NaN|Infinity)$/.test(tok)) {
241
+ if (!relaxed) fail('JSON_BAD_TOKEN', start, tok);
242
+ N.add('JSON_NONFINITE', tok, lineOf(start));
243
+ return tok.charAt(0) === '-' ? (tok.indexOf('NaN') !== -1 ? NaN : -Infinity) : tok.indexOf('NaN') !== -1 ? NaN : Infinity;
244
+ }
245
+ if (/^[-+]?(0[xX][0-9a-fA-F]+|[0-9]*\.?[0-9]*([eE][-+]?[0-9]+)?)$/.test(tok) && /[0-9]/.test(tok)) {
246
+ if (!relaxed) fail('JSON_BAD_TOKEN', start, tok);
247
+ N.add('JSON_RELAXED_NUMBER', tok, lineOf(start));
248
+ const n = /^[-+]?0[xX]/.test(tok)
249
+ ? (tok.charAt(0) === '-' ? -1 : 1) * parseInt(tok.replace(/^[-+]/, '').slice(2), 16)
250
+ : Number(tok);
251
+ if (!Number.isFinite(n)) fail('JSON_BAD_TOKEN', start, tok);
252
+ if (Number.isInteger(n) && !Number.isSafeInteger(n)) N.add('NUMBER_PRECISION', tok, lineOf(start));
253
+ return n;
254
+ }
255
+ fail('JSON_BAD_TOKEN', start, tok.length > 24 ? tok.slice(0, 24) + '…' : tok);
256
+ return null;
257
+ }
258
+
259
+ function readKey() {
260
+ const c = src.charAt(i);
261
+ if (c === '"') return readString('"');
262
+ if (c === "'") {
263
+ if (!relaxed) fail('JSON_SINGLE_QUOTE', i);
264
+ N.add('JSON_SINGLE_QUOTE', null, lineOf(i));
265
+ return readString("'");
266
+ }
267
+ const m = /^[A-Za-z_$][A-Za-z0-9_$-]*/.exec(src.slice(i));
268
+ if (!m) fail('JSON_KEY_EXPECTED', i, here());
269
+ if (!relaxed) fail('JSON_UNQUOTED_KEY', i, m[0]);
270
+ N.add('JSON_UNQUOTED_KEY', m[0], lineOf(i));
271
+ i += m[0].length;
272
+ return m[0];
273
+ }
274
+
275
+ function readObject() {
276
+ depth += 1;
277
+ if (depth > JY_MAX_DEPTH) fail('TOO_DEEP', i);
278
+ i += 1;
279
+ // __proto__ を書き込まれてもプロトタイプ汚染にならないよう、素のオブジェクトは使わない
280
+ const out = Object.create(null);
281
+ ws();
282
+ if (src.charAt(i) === '}') {
283
+ i += 1;
284
+ depth -= 1;
285
+ return out;
286
+ }
287
+ for (;;) {
288
+ ws();
289
+ const at = i;
290
+ const key = readKey();
291
+ ws();
292
+ if (src.charAt(i) !== ':') fail('JSON_COLON_EXPECTED', i, here());
293
+ i += 1;
294
+ const value = readValue();
295
+ if (Object.prototype.hasOwnProperty.call(out, key)) N.add('DUPLICATE_KEY', key, lineOf(at));
296
+ out[key] = value;
297
+ ws();
298
+ if (src.charAt(i) === ',') {
299
+ i += 1;
300
+ ws();
301
+ if (src.charAt(i) === '}') {
302
+ if (!relaxed) fail('JSON_TRAILING_COMMA', i);
303
+ N.add('JSON_TRAILING_COMMA', null, lineOf(i));
304
+ i += 1;
305
+ depth -= 1;
306
+ return out;
307
+ }
308
+ continue;
309
+ }
310
+ if (src.charAt(i) === '}') {
311
+ i += 1;
312
+ depth -= 1;
313
+ return out;
314
+ }
315
+ fail('JSON_COMMA_EXPECTED', i, here());
316
+ }
317
+ }
318
+
319
+ function readArray() {
320
+ depth += 1;
321
+ if (depth > JY_MAX_DEPTH) fail('TOO_DEEP', i);
322
+ i += 1;
323
+ const out = [];
324
+ ws();
325
+ if (src.charAt(i) === ']') {
326
+ i += 1;
327
+ depth -= 1;
328
+ return out;
329
+ }
330
+ for (;;) {
331
+ out.push(readValue());
332
+ ws();
333
+ if (src.charAt(i) === ',') {
334
+ i += 1;
335
+ ws();
336
+ if (src.charAt(i) === ']') {
337
+ if (!relaxed) fail('JSON_TRAILING_COMMA', i);
338
+ N.add('JSON_TRAILING_COMMA', null, lineOf(i));
339
+ i += 1;
340
+ depth -= 1;
341
+ return out;
342
+ }
343
+ continue;
344
+ }
345
+ if (src.charAt(i) === ']') {
346
+ i += 1;
347
+ depth -= 1;
348
+ return out;
349
+ }
350
+ fail('JSON_COMMA_EXPECTED', i, here());
351
+ }
352
+ }
353
+
354
+ function readValue() {
355
+ ws();
356
+ if (i >= src.length) fail('JSON_UNEXPECTED_END', i);
357
+ const c = src.charAt(i);
358
+ if (c === '{') return readObject();
359
+ if (c === '[') return readArray();
360
+ if (c === '"') return readString('"');
361
+ if (c === "'") {
362
+ if (!relaxed) fail('JSON_SINGLE_QUOTE', i);
363
+ N.add('JSON_SINGLE_QUOTE', null, lineOf(i));
364
+ return readString("'");
365
+ }
366
+ return readLiteral();
367
+ }
368
+
369
+ try {
370
+ ws();
371
+ if (i >= src.length) return { ok: false, error: { code: 'EMPTY_INPUT', line: 1, col: 1 }, notes: N.list };
372
+ const value = readValue();
373
+ ws();
374
+ if (i < src.length) fail('JSON_TRAILING_DATA', i, here());
375
+ return { ok: true, value, notes: N.list };
376
+ } catch (e) {
377
+ if (!e.jy) throw e;
378
+ const pos = jyLineCol(src, e.jy.index);
379
+ return {
380
+ ok: false,
381
+ error: { code: e.jy.code, line: pos.line, col: pos.col, found: e.jy.found },
382
+ notes: N.list,
383
+ };
384
+ }
385
+ }
386
+
387
+ /* ---------------------------------------------------------------------------
388
+ * YAML パーサ(インデント方式のブロック構造 + フロー表記)
389
+ *
390
+ * 対応: 複数ドキュメント(--- / ...)・ブロックマップ / シーケンス・フロー表記 [] {}・
391
+ * 引用スカラー(複数行・エスケープ)・ブロックスカラー | > と chomping - + と明示インデント・
392
+ * アンカー &a / エイリアス *a / マージキー <<・タグ !!str !!int 等・コメント。
393
+ * 非対応: 明示キー "? " と、"!" による独自タグの型付け(エラー / 指摘にして黙って壊さない)。
394
+ * ------------------------------------------------------------------------- */
395
+ function jyParseYaml(text) {
396
+ const N = jyNotes();
397
+ const src = String(text).replace(/^\uFEFF/, '').replace(/\r\n?/g, '\n');
398
+ const lines = src.split('\n').map((raw, k) => {
399
+ const ws = /^[ \t]*/.exec(raw)[0];
400
+ const body = raw.slice(ws.length);
401
+ return { n: k + 1, text: raw, ws, indent: ws.length, body, blank: body === '', comment: body.charAt(0) === '#' };
402
+ });
403
+ const anchors = Object.create(null);
404
+ let p = 0;
405
+ let depth = 0;
406
+ let usedAlias = false;
407
+
408
+ const fail = (code, line, col, found) => {
409
+ const e = new Error(code);
410
+ e.jy = { code, line: line || 1, col: col || 1, found };
411
+ throw e;
412
+ };
413
+
414
+ // インデントにタブを使うと解釈がパーサ任せになる(YAMLはタブでのインデントを禁じている)。
415
+ // ブロックスカラーの中身は対象外なので、構造として読む行だけで確かめる。
416
+ function checkTab(L) {
417
+ if (L.ws.indexOf('\t') !== -1) fail('TAB_INDENT', L.n, L.ws.indexOf('\t') + 1);
418
+ }
419
+
420
+ /** 構造として意味のある次の行まで進める(空行・コメント行は飛ばす) */
421
+ function skip() {
422
+ while (p < lines.length && (lines[p].blank || lines[p].comment)) p += 1;
423
+ if (p >= lines.length) return null;
424
+ checkTab(lines[p]);
425
+ return lines[p];
426
+ }
427
+
428
+ const isSeqEntry = (body) => body === '-' || body.slice(0, 2) === '- ' || body.slice(0, 2) === '-\t';
429
+ const isDocStart = (body) => body === '---' || body.slice(0, 4) === '--- ';
430
+ const isDocEnd = (body) => body === '...' || body.slice(0, 4) === '... ';
431
+ // --- と ... はドキュメントの区切り。ただし桁0に書かれたときだけで、字下げされていれば普通の値
432
+ const isBoundary = (L) => L.indent === 0 && (isDocStart(L.body) || isDocEnd(L.body));
433
+
434
+ /** 行の内容からコメントを落とす(引用符の中の # と、空白が前に無い # は残す) */
435
+ function stripComment(s) {
436
+ let inS = false;
437
+ let inD = false;
438
+ for (let k = 0; k < s.length; k++) {
439
+ const c = s.charAt(k);
440
+ if (inS) {
441
+ if (c === "'") {
442
+ if (s.charAt(k + 1) === "'") k += 1;
443
+ else inS = false;
444
+ }
445
+ continue;
446
+ }
447
+ if (inD) {
448
+ if (c === '\\') k += 1;
449
+ else if (c === '"') inD = false;
450
+ continue;
451
+ }
452
+ if (c === "'") inS = true;
453
+ else if (c === '"') inD = true;
454
+ else if (c === '#' && (k === 0 || s.charAt(k - 1) === ' ' || s.charAt(k - 1) === '\t')) {
455
+ return s.slice(0, k).replace(/[ \t]+$/, '');
456
+ }
457
+ }
458
+ return s;
459
+ }
460
+
461
+ /** 「キー: 」の区切りを探す。引用符とフロー表記の中は無視する */
462
+ function splitKey(s) {
463
+ let inS = false;
464
+ let inD = false;
465
+ let flow = 0;
466
+ for (let k = 0; k < s.length; k++) {
467
+ const c = s.charAt(k);
468
+ if (inS) {
469
+ if (c === "'") {
470
+ if (s.charAt(k + 1) === "'") k += 1;
471
+ else inS = false;
472
+ }
473
+ continue;
474
+ }
475
+ if (inD) {
476
+ if (c === '\\') k += 1;
477
+ else if (c === '"') inD = false;
478
+ continue;
479
+ }
480
+ if (c === "'") inS = true;
481
+ else if (c === '"') inD = true;
482
+ else if (c === '[' || c === '{') flow += 1;
483
+ else if (c === ']' || c === '}') flow -= 1;
484
+ else if (c === '#' && flow === 0 && (k === 0 || s.charAt(k - 1) === ' ')) return null;
485
+ else if (c === ':' && flow === 0) {
486
+ const nx = s.charAt(k + 1);
487
+ if (k + 1 >= s.length || nx === ' ' || nx === '\t') return { key: s.slice(0, k), rest: s.slice(k + 1) };
488
+ }
489
+ }
490
+ return null;
491
+ }
492
+
493
+ /** 値の前に付く &アンカー / *エイリアス / !タグ を剥がす */
494
+ function takeProps(s) {
495
+ const props = { anchor: null, alias: null, tag: null };
496
+ let rest = s;
497
+ for (let guard = 0; guard < 4; guard++) {
498
+ const m = /^(?:&([^\s,[\]{}]+)|\*([^\s,[\]{}]+)|(![^\s,[\]{}]*))(?:[ \t]+|$)/.exec(rest);
499
+ if (!m) break;
500
+ if (m[1]) props.anchor = m[1];
501
+ else if (m[2]) props.alias = m[2];
502
+ else props.tag = m[3];
503
+ rest = rest.slice(m[0].length);
504
+ if (props.alias) break;
505
+ }
506
+ return { props, rest };
507
+ }
508
+
509
+ /** スカラー文字列をタグ・引用の有無に従って値へ */
510
+ function toScalar(token, props, line, quoted) {
511
+ const tag = props && props.tag;
512
+ if (!tag) {
513
+ if (quoted) return token;
514
+ for (const code of jyScalarNotes(token)) N.add(code, token, line);
515
+ return jyResolveScalar(token);
516
+ }
517
+ switch (tag.replace(/^!!?/, '')) {
518
+ case 'str':
519
+ return token;
520
+ case 'int': {
521
+ const n = /^[-+]?0[xob]/i.test(token) ? jyResolveScalar(token) : parseInt(token, 10);
522
+ if (typeof n !== 'number' || !Number.isFinite(n)) fail('YAML_BAD_TAG_VALUE', line, 1, tag + ' ' + token);
523
+ return n;
524
+ }
525
+ case 'float': {
526
+ const n = Number(token);
527
+ if (!Number.isFinite(n)) fail('YAML_BAD_TAG_VALUE', line, 1, tag + ' ' + token);
528
+ return n;
529
+ }
530
+ case 'bool':
531
+ return /^(true|yes|on|y|1)$/i.test(token);
532
+ case 'null':
533
+ return null;
534
+ case 'binary':
535
+ N.add('YAML_BINARY', null, line);
536
+ return token.replace(/\s+/g, '');
537
+ case 'map':
538
+ case 'seq':
539
+ return quoted ? token : jyResolveScalar(token);
540
+ default:
541
+ N.add('YAML_UNKNOWN_TAG', tag, line);
542
+ return quoted ? token : jyResolveScalar(token);
543
+ }
544
+ }
545
+
546
+ const ESCAPES = {
547
+ '0': '\0', a: '\x07', b: '\b', t: '\t', '\t': '\t', n: '\n', v: '\v', f: '\f', r: '\r',
548
+ e: '\x1b', ' ': ' ', '"': '"', '/': '/', '\\': '\\', N: '\u0085', _: '\u00a0', L: '\u2028', P: '\u2029',
549
+ };
550
+
551
+ /** 二重引用符の中のエスケープを1つ読む。読めなければ null */
552
+ function readEscape(s, k) {
553
+ const c = s.charAt(k + 1);
554
+ if (k + 1 >= s.length) return { text: '', next: s.length }; // 行末の \ は行継続
555
+ if (c === 'x' || c === 'u' || c === 'U') {
556
+ const len = c === 'x' ? 2 : c === 'u' ? 4 : 8;
557
+ const hex = s.substr(k + 2, len);
558
+ if (hex.length < len || !/^[0-9a-fA-F]+$/.test(hex)) return null;
559
+ const cp = parseInt(hex, 16);
560
+ if (cp > 0x10ffff) return null;
561
+ return { text: String.fromCodePoint(cp), next: k + 2 + len };
562
+ }
563
+ if (ESCAPES[c] === undefined) return null;
564
+ return { text: ESCAPES[c], next: k + 2 };
565
+ }
566
+
567
+ /**
568
+ * 引用符つきスカラーを読む(複数行にまたがってよい)。
569
+ * 戻り値の rest は閉じ引用符より後ろ。p は最後に読んだ行を指す。
570
+ */
571
+ function readQuoted(s) {
572
+ const quote = s.charAt(0);
573
+ const startLine = lines[p].n;
574
+ let cur = s;
575
+ let k = 1;
576
+ let out = '';
577
+ for (;;) {
578
+ while (k < cur.length) {
579
+ const c = cur.charAt(k);
580
+ if (quote === "'") {
581
+ if (c === "'") {
582
+ if (cur.charAt(k + 1) === "'") {
583
+ out += "'";
584
+ k += 2;
585
+ continue;
586
+ }
587
+ return { value: out, rest: cur.slice(k + 1) };
588
+ }
589
+ out += c;
590
+ k += 1;
591
+ continue;
592
+ }
593
+ if (c === '\\') {
594
+ const e = readEscape(cur, k);
595
+ if (e === null) fail('YAML_BAD_ESCAPE', lines[p].n, k + 1, cur.substr(k, 2));
596
+ out += e.text;
597
+ k = e.next;
598
+ continue;
599
+ }
600
+ if (c === '"') return { value: out, rest: cur.slice(k + 1) };
601
+ out += c;
602
+ k += 1;
603
+ }
604
+ // 行末に達した = 折り返し。空行の数だけ改行になり、無ければ空白1つになる
605
+ out = out.replace(/[ \t]+$/, '');
606
+ let breaks = 0;
607
+ for (;;) {
608
+ p += 1;
609
+ if (p >= lines.length) fail('YAML_UNTERMINATED_QUOTE', startLine, 1, quote);
610
+ if (lines[p].blank) {
611
+ breaks += 1;
612
+ continue;
613
+ }
614
+ break;
615
+ }
616
+ out += breaks === 0 ? ' ' : '\n'.repeat(breaks);
617
+ cur = lines[p].body;
618
+ k = 0;
619
+ }
620
+ }
621
+
622
+ /** フロー表記 [ … ] / { … } を読む(複数行にまたがってよい) */
623
+ function readFlow(s) {
624
+ const startLine = lines[p].n;
625
+ let text = s;
626
+ let idx = 0;
627
+ let level = 0;
628
+ let inS = false;
629
+ let inD = false;
630
+ for (;;) {
631
+ while (idx < text.length) {
632
+ const c = text.charAt(idx);
633
+ if (inS) {
634
+ if (c === "'") {
635
+ if (text.charAt(idx + 1) === "'") idx += 1;
636
+ else inS = false;
637
+ }
638
+ idx += 1;
639
+ continue;
640
+ }
641
+ if (inD) {
642
+ if (c === '\\') idx += 1;
643
+ else if (c === '"') inD = false;
644
+ idx += 1;
645
+ continue;
646
+ }
647
+ if (c === "'") inS = true;
648
+ else if (c === '"') inD = true;
649
+ else if (c === '[' || c === '{') level += 1;
650
+ else if (c === ']' || c === '}') {
651
+ level -= 1;
652
+ if (level === 0) {
653
+ idx += 1;
654
+ return { value: parseFlow(text.slice(0, idx), startLine), rest: text.slice(idx) };
655
+ }
656
+ }
657
+ idx += 1;
658
+ }
659
+ p += 1;
660
+ if (p >= lines.length) fail('YAML_UNTERMINATED_FLOW', startLine, 1);
661
+ // 引用符の途中でなければ、続きの行のコメントは落としてから連結する
662
+ text += ' ' + (inS || inD ? lines[p].body : stripComment(lines[p].body));
663
+ }
664
+ }
665
+
666
+ /** 括弧の対応が取れているフロー表記の文字列を値へ */
667
+ function parseFlow(text, line) {
668
+ let k = 0;
669
+ const ws = () => {
670
+ while (k < text.length && /\s/.test(text.charAt(k))) k += 1;
671
+ };
672
+
673
+ function value() {
674
+ ws();
675
+ const c = text.charAt(k);
676
+ if (c === '[') return seq();
677
+ if (c === '{') return map();
678
+ if (c === '"' || c === "'") {
679
+ const saved = p;
680
+ const r = (function () {
681
+ // 1行に収まっているので readQuoted の折り返し処理には入らない
682
+ const sub = text.slice(k);
683
+ const q = readQuotedInline(sub, line);
684
+ k += sub.length - q.rest.length;
685
+ return q.value;
686
+ })();
687
+ p = saved;
688
+ return r;
689
+ }
690
+ const start = k;
691
+ while (k < text.length) {
692
+ const ch = text.charAt(k);
693
+ if (ch === ',' || ch === ']' || ch === '}') break;
694
+ if (ch === ':' && (k + 1 >= text.length || /[\s,\]}]/.test(text.charAt(k + 1)))) break;
695
+ k += 1;
696
+ }
697
+ const tok = text.slice(start, k).trim();
698
+ const t = takeProps(tok);
699
+ if (t.props.alias) {
700
+ if (!(t.props.alias in anchors)) fail('YAML_ALIAS_NOT_FOUND', line, 1, '*' + t.props.alias);
701
+ usedAlias = true;
702
+ return anchors[t.props.alias];
703
+ }
704
+ const v = toScalar(t.rest, t.props, line, false);
705
+ if (t.props.anchor) anchors[t.props.anchor] = v;
706
+ return v;
707
+ }
708
+
709
+ function seq() {
710
+ depth += 1;
711
+ if (depth > JY_MAX_DEPTH) fail('TOO_DEEP', line);
712
+ k += 1;
713
+ const arr = [];
714
+ for (;;) {
715
+ ws();
716
+ if (text.charAt(k) === ']') {
717
+ k += 1;
718
+ depth -= 1;
719
+ return arr;
720
+ }
721
+ if (k >= text.length) fail('YAML_UNTERMINATED_FLOW', line, 1);
722
+ const quotedKey = text.charAt(k) === '"' || text.charAt(k) === "'";
723
+ const v = value();
724
+ ws();
725
+ if (text.charAt(k) === ':') {
726
+ // [a: 1] のように括弧なしのペアが書かれた場合
727
+ k += 1;
728
+ const pair = Object.create(null);
729
+ const own = new Set();
730
+ setKey(pair, own, v, value(), line, !quotedKey);
731
+ arr.push(pair);
732
+ ws();
733
+ } else {
734
+ arr.push(v);
735
+ }
736
+ if (text.charAt(k) === ',') {
737
+ k += 1;
738
+ continue;
739
+ }
740
+ if (text.charAt(k) === ']') {
741
+ k += 1;
742
+ depth -= 1;
743
+ return arr;
744
+ }
745
+ fail('YAML_FLOW_SEP', line, 1, text.charAt(k) || 'EOF');
746
+ }
747
+ }
748
+
749
+ function map() {
750
+ depth += 1;
751
+ if (depth > JY_MAX_DEPTH) fail('TOO_DEEP', line);
752
+ k += 1;
753
+ const obj = Object.create(null);
754
+ const own = new Set();
755
+ for (;;) {
756
+ ws();
757
+ if (text.charAt(k) === '}') {
758
+ k += 1;
759
+ depth -= 1;
760
+ return obj;
761
+ }
762
+ if (k >= text.length) fail('YAML_UNTERMINATED_FLOW', line, 1);
763
+ const quotedKey = text.charAt(k) === '"' || text.charAt(k) === "'";
764
+ const key = value();
765
+ ws();
766
+ let v = null;
767
+ if (text.charAt(k) === ':') {
768
+ k += 1;
769
+ v = value();
770
+ ws();
771
+ } else if (text.charAt(k) !== ',' && text.charAt(k) !== '}') {
772
+ fail('YAML_FLOW_COLON', line, 1, text.charAt(k) || 'EOF');
773
+ }
774
+ setKey(obj, own, key, v, line, !quotedKey);
775
+ if (text.charAt(k) === ',') {
776
+ k += 1;
777
+ continue;
778
+ }
779
+ if (text.charAt(k) === '}') {
780
+ k += 1;
781
+ depth -= 1;
782
+ return obj;
783
+ }
784
+ fail('YAML_FLOW_SEP', line, 1, text.charAt(k) || 'EOF');
785
+ }
786
+ }
787
+
788
+ const out = value();
789
+ ws();
790
+ if (k < text.length) fail('YAML_FLOW_SEP', line, 1, text.charAt(k));
791
+ return out;
792
+ }
793
+
794
+ /** 1行に収まっている引用スカラーを読む(フロー表記の中で使う) */
795
+ function readQuotedInline(s, line) {
796
+ const quote = s.charAt(0);
797
+ let out = '';
798
+ for (let k = 1; k < s.length; k++) {
799
+ const c = s.charAt(k);
800
+ if (quote === "'") {
801
+ if (c === "'") {
802
+ if (s.charAt(k + 1) === "'") {
803
+ out += "'";
804
+ k += 1;
805
+ continue;
806
+ }
807
+ return { value: out, rest: s.slice(k + 1) };
808
+ }
809
+ out += c;
810
+ continue;
811
+ }
812
+ if (c === '\\') {
813
+ const e = readEscape(s, k);
814
+ if (e === null) fail('YAML_BAD_ESCAPE', line, k + 1, s.substr(k, 2));
815
+ out += e.text;
816
+ k = e.next - 1;
817
+ continue;
818
+ }
819
+ if (c === '"') return { value: out, rest: s.slice(k + 1) };
820
+ out += c;
821
+ }
822
+ fail('YAML_UNTERMINATED_QUOTE', line, 1, quote);
823
+ return null;
824
+ }
825
+
826
+ /** ブロックスカラー(| と >)を読む。s はヘッダ(| や >- など)から始まる */
827
+ function readBlockScalar(s, baseIndent) {
828
+ const style = s.charAt(0);
829
+ let k = 1;
830
+ let chomp = '';
831
+ let explicit = 0;
832
+ while (k < s.length) {
833
+ const c = s.charAt(k);
834
+ if ((c === '+' || c === '-') && !chomp) {
835
+ chomp = c;
836
+ k += 1;
837
+ continue;
838
+ }
839
+ if (c >= '1' && c <= '9' && !explicit) {
840
+ explicit = Number(c);
841
+ k += 1;
842
+ continue;
843
+ }
844
+ break;
845
+ }
846
+ const tail = stripComment(s.slice(k)).trim();
847
+ if (tail !== '') fail('YAML_BLOCK_HEADER', lines[p].n, k + 1, tail);
848
+
849
+ p += 1;
850
+ const body = [];
851
+ let contentIndent = explicit ? baseIndent + explicit : 0;
852
+ while (p < lines.length) {
853
+ const L = lines[p];
854
+ if (L.blank) {
855
+ body.push('');
856
+ p += 1;
857
+ continue;
858
+ }
859
+ if (!contentIndent) {
860
+ if (L.indent <= baseIndent) break;
861
+ contentIndent = L.indent;
862
+ } else if (L.indent < contentIndent) {
863
+ // ブロックの中身より浅く、しかし親より深い = インデントの取り違え
864
+ if (L.indent > baseIndent) fail('YAML_BLOCK_INDENT', L.n, L.indent + 1);
865
+ break;
866
+ }
867
+ body.push(L.text.slice(contentIndent));
868
+ p += 1;
869
+ }
870
+
871
+ let end = body.length;
872
+ while (end > 0 && body[end - 1] === '') end -= 1;
873
+ const trailingBlanks = body.length - end;
874
+ const content = body.slice(0, end);
875
+
876
+ let out;
877
+ if (style === '|') {
878
+ out = content.join('\n');
879
+ } else {
880
+ out = '';
881
+ for (let q = 0; q < content.length; q++) {
882
+ const ln = content[q];
883
+ if (q === 0) {
884
+ out = ln;
885
+ continue;
886
+ }
887
+ const prev = content[q - 1];
888
+ if (ln === '') out += '\n';
889
+ else if (prev === '') out += ln;
890
+ else if (/^[ \t]/.test(ln) || /^[ \t]/.test(prev)) out += '\n' + ln;
891
+ else out += ' ' + ln;
892
+ }
893
+ }
894
+ if (content.length) out += '\n';
895
+ if (chomp === '-') out = out.replace(/\n+$/, '');
896
+ else if (chomp === '+') out += '\n'.repeat(trailingBlanks);
897
+ return out;
898
+ }
899
+
900
+ /**
901
+ * マップへキーを入れる(マージキー <<・文字列以外のキー・キーの重複を処理する)。
902
+ * << は引用符なしで書かれたときだけマージ指示になる('<<' と書けば普通のキー。js-yaml も同じ扱い)。
903
+ */
904
+ function setKey(obj, own, key, value, line, plainKey) {
905
+ if (key === '<<' && plainKey !== false) {
906
+ const sources = Array.isArray(value) ? value : [value];
907
+ for (const s of sources) {
908
+ if (!jyIsPlainObject(s)) {
909
+ N.add('YAML_BAD_MERGE', null, line);
910
+ continue;
911
+ }
912
+ for (const k of Object.keys(s)) if (!own.has(k)) obj[k] = s[k];
913
+ }
914
+ N.add('YAML_MERGE_KEY', null, line);
915
+ return;
916
+ }
917
+ let name;
918
+ if (typeof key === 'string') {
919
+ name = key;
920
+ } else {
921
+ name = key === null ? 'null' : typeof key === 'object' ? jyFormatJson(key, { indent: 0 }) : String(key);
922
+ N.add('YAML_NONSTRING_KEY', name, line);
923
+ }
924
+ if (own.has(name)) N.add('DUPLICATE_KEY', name, line);
925
+ own.add(name);
926
+ obj[name] = value;
927
+ }
928
+
929
+ /**
930
+ * 「: の後ろ」または「- の後ろ」に続く値を解釈する。
931
+ * baseIndent より深い行だけを続きとして取り込む。戻るとき p は次の未処理行を指す。
932
+ */
933
+ function parseTrailing(rawRest, baseIndent) {
934
+ const L = lines[p];
935
+ const line = L.n;
936
+ const t = takeProps(rawRest.replace(/^[ \t]+/, ''));
937
+ const props = t.props;
938
+ let s = t.rest;
939
+
940
+ if (props.alias) {
941
+ if (stripComment(s).trim() !== '') fail('YAML_ALIAS_TRAILING', line, 1, stripComment(s).trim());
942
+ if (!(props.alias in anchors)) fail('YAML_ALIAS_NOT_FOUND', line, 1, '*' + props.alias);
943
+ usedAlias = true;
944
+ p += 1;
945
+ return anchors[props.alias];
946
+ }
947
+
948
+ if (/^[|>]/.test(s)) {
949
+ const v = readBlockScalar(s, baseIndent);
950
+ const out = props.tag ? toScalar(v, props, line, true) : v;
951
+ if (props.anchor) anchors[props.anchor] = out;
952
+ return out;
953
+ }
954
+
955
+ if (stripComment(s).trim() === '') {
956
+ // 値は次の行以降にある
957
+ p += 1;
958
+ const child = parseChild(baseIndent);
959
+ if (props.tag && !/^!!?(map|seq)$/.test(props.tag)) N.add('YAML_UNKNOWN_TAG', props.tag, line);
960
+ if (props.anchor) anchors[props.anchor] = child;
961
+ return child;
962
+ }
963
+
964
+ if (s.charAt(0) === '"' || s.charAt(0) === "'") {
965
+ const q = readQuoted(s);
966
+ const rest = stripComment(q.rest).trim();
967
+ if (rest !== '') fail('YAML_TRAILING_TEXT', lines[p].n, 1, rest.slice(0, 24));
968
+ p += 1;
969
+ const out = toScalar(q.value, props, line, true);
970
+ if (props.anchor) anchors[props.anchor] = out;
971
+ return out;
972
+ }
973
+
974
+ if (s.charAt(0) === '[' || s.charAt(0) === '{') {
975
+ const f = readFlow(s);
976
+ const rest = stripComment(f.rest).trim();
977
+ if (rest !== '') fail('YAML_TRAILING_TEXT', lines[p].n, 1, rest.slice(0, 24));
978
+ p += 1;
979
+ if (props.anchor) anchors[props.anchor] = f.value;
980
+ return f.value;
981
+ }
982
+
983
+ // プレーンスカラー。次の行以降へ折り返している場合は空白1つで連結する
984
+ const first = stripComment(s).replace(/[ \t]+$/, '');
985
+ if (/^-([ \t]|$)/.test(first)) fail('YAML_SEQ_INLINE', line, L.text.length - rawRest.length + 1, first.slice(0, 24));
986
+ if (splitKey(first)) fail('YAML_NESTED_COLON', line, L.text.length - rawRest.length + 1, first.slice(0, 24));
987
+ const parts = [first];
988
+ p += 1;
989
+ while (p < lines.length) {
990
+ const L2 = lines[p];
991
+ if (L2.blank || L2.comment) break;
992
+ checkTab(L2);
993
+ if (L2.indent <= baseIndent || isBoundary(L2)) break;
994
+ const body = stripComment(L2.body).replace(/[ \t]+$/, '');
995
+ if (splitKey(body)) fail('YAML_VALUE_THEN_BLOCK', L2.n, L2.indent + 1, body.slice(0, 24));
996
+ parts.push(body);
997
+ p += 1;
998
+ }
999
+ const token = parts.join(' ').replace(/[ \t]+$/, '');
1000
+ const out = toScalar(token, props, line, false);
1001
+ if (props.anchor) anchors[props.anchor] = out;
1002
+ return out;
1003
+ }
1004
+
1005
+ /** 親より深い行(またはキーと同じ深さのシーケンス)を子ノードとして読む */
1006
+ function parseChild(baseIndent) {
1007
+ const L = skip();
1008
+ if (!L || isBoundary(L)) return null;
1009
+ if (L.indent > baseIndent) return parseNode(L.indent);
1010
+ // key: の下に同じ深さで - を並べるのは YAML として正しい
1011
+ if (L.indent === baseIndent && isSeqEntry(L.body)) return parseSeq(baseIndent);
1012
+ return null;
1013
+ }
1014
+
1015
+ function parseNode(indent) {
1016
+ depth += 1;
1017
+ if (depth > JY_MAX_DEPTH) fail('TOO_DEEP', lines[p] ? lines[p].n : 1);
1018
+ try {
1019
+ const L = skip();
1020
+ if (!L || L.indent < indent || isBoundary(L)) return null;
1021
+ // 「? key」「: value」の明示キー記法は、JSONに落とせないので受け取らない
1022
+ if (/^[?:]([ \t]|$)/.test(L.body)) fail('YAML_EXPLICIT_KEY', L.n, L.indent + 1);
1023
+ if (isSeqEntry(L.body)) return parseSeq(indent);
1024
+ if (splitKey(L.body)) return parseMap(indent);
1025
+ return parseTrailing(L.body, indent - 1);
1026
+ } finally {
1027
+ depth -= 1;
1028
+ }
1029
+ }
1030
+
1031
+ function parseMap(indent) {
1032
+ const obj = Object.create(null);
1033
+ const own = new Set();
1034
+ for (;;) {
1035
+ const L = skip();
1036
+ if (!L || L.indent < indent || isBoundary(L)) break;
1037
+ if (L.indent > indent) fail('YAML_BAD_INDENT', L.n, L.indent + 1, stripComment(L.body).slice(0, 24));
1038
+ if (isSeqEntry(L.body)) fail('YAML_SEQ_IN_MAP', L.n, L.indent + 1);
1039
+ const kv = splitKey(L.body);
1040
+ if (!kv) {
1041
+ if (/^\?([ \t]|$)/.test(L.body)) fail('YAML_EXPLICIT_KEY', L.n, L.indent + 1);
1042
+ fail('YAML_KEY_EXPECTED', L.n, L.indent + 1, stripComment(L.body).trim().slice(0, 24));
1043
+ }
1044
+ const line = L.n;
1045
+ const kt = takeProps(kv.key.trim());
1046
+ const rawKey = kt.rest;
1047
+ const quotedKey = rawKey.charAt(0) === '"' || rawKey.charAt(0) === "'";
1048
+ const key = quotedKey ? readQuotedInline(rawKey, line).value : toScalar(rawKey, kt.props, line, false);
1049
+ const value = parseTrailing(kv.rest, indent);
1050
+ setKey(obj, own, key, value, line, !quotedKey);
1051
+ }
1052
+ return obj;
1053
+ }
1054
+
1055
+ function parseSeq(indent) {
1056
+ const arr = [];
1057
+ for (;;) {
1058
+ const L = skip();
1059
+ if (!L || L.indent < indent || isBoundary(L)) break;
1060
+ if (!isSeqEntry(L.body)) {
1061
+ // 同じ深さにマップのキーが来たら、呼び出し側(マップ)へ制御を戻す
1062
+ if (L.indent === indent) break;
1063
+ fail('YAML_BAD_INDENT', L.n, L.indent + 1, stripComment(L.body).slice(0, 24));
1064
+ }
1065
+ if (L.indent > indent) fail('YAML_BAD_INDENT', L.n, L.indent + 1, stripComment(L.body).slice(0, 24));
1066
+ const rest = L.body.slice(1);
1067
+ const lead = /^[ \t]*/.exec(rest)[0].length;
1068
+ const inner = rest.slice(lead);
1069
+ if (stripComment(inner).trim() === '') {
1070
+ p += 1;
1071
+ // 「-」だけの行の中身は、より深い行だけ。同じ深さの「-」は(親の値ではなく)次の要素なので、
1072
+ // key: の下に同じ深さで - を並べられる parseChild は使えない
1073
+ const next = skip();
1074
+ arr.push(!next || isBoundary(next) || next.indent <= indent ? null : parseNode(next.indent));
1075
+ continue;
1076
+ }
1077
+ // 「- 」に続く中身を、その桁から始まる行として読み直す(- name: a の下に同じ桁で続くキーを拾うため)
1078
+ const itemIndent = indent + 1 + lead;
1079
+ lines[p] = { ...L, ws: L.text.slice(0, itemIndent), indent: itemIndent, body: inner };
1080
+ arr.push(parseNode(itemIndent));
1081
+ }
1082
+ return arr;
1083
+ }
1084
+
1085
+ const docs = [];
1086
+ try {
1087
+ let guard = 0;
1088
+ while (p < lines.length) {
1089
+ if ((guard += 1) > lines.length + 16) fail('YAML_INTERNAL', lines[p] ? lines[p].n : 1);
1090
+ const L = skip();
1091
+ if (!L) break;
1092
+ if (L.body.charAt(0) === '%') {
1093
+ N.add('YAML_DIRECTIVE', stripComment(L.body).trim(), L.n);
1094
+ p += 1;
1095
+ continue;
1096
+ }
1097
+ if (L.indent === 0 && isDocEnd(L.body)) {
1098
+ p += 1;
1099
+ continue;
1100
+ }
1101
+ if (L.indent === 0 && isDocStart(L.body)) {
1102
+ const rest = L.body.slice(3);
1103
+ if (stripComment(rest).trim() === '') {
1104
+ p += 1;
1105
+ const next = skip();
1106
+ docs.push(!next || isBoundary(next) ? null : parseNode(next.indent));
1107
+ } else {
1108
+ const lead = /^[ \t]*/.exec(rest)[0].length;
1109
+ const itemIndent = 3 + lead;
1110
+ lines[p] = { ...L, ws: L.text.slice(0, itemIndent), indent: itemIndent, body: rest.slice(lead) };
1111
+ docs.push(parseNode(itemIndent));
1112
+ }
1113
+ continue;
1114
+ }
1115
+ docs.push(parseNode(L.indent));
1116
+ }
1117
+ } catch (e) {
1118
+ if (!e.jy) throw e;
1119
+ return { ok: false, error: e.jy, notes: N.list, docs };
1120
+ }
1121
+
1122
+ if (usedAlias) N.add('YAML_ALIAS_EXPANDED');
1123
+ if (docs.length > 1) N.add('MULTI_DOC', null, null).count = docs.length;
1124
+ return {
1125
+ ok: true,
1126
+ docs,
1127
+ value: docs.length === 0 ? null : docs.length === 1 ? docs[0] : docs,
1128
+ notes: N.list,
1129
+ };
1130
+ }
1131
+
1132
+ /* ---------------------------------------------------------------------------
1133
+ * JSON 出力
1134
+ * ------------------------------------------------------------------------- */
1135
+
1136
+ /**
1137
+ * 値をJSON文字列へ。JSON.stringify と違い、キーの並べ替え・非ASCIIのエスケープ・
1138
+ * インデント文字(タブ / 1行)を選べる。NaN と Infinity は JSON に無いので null にする。
1139
+ *
1140
+ * @param {*} value
1141
+ * @param {object} [opts]
1142
+ * @param {number|'tab'} [opts.indent=2] 0 なら改行なしの1行
1143
+ * @param {boolean} [opts.sortKeys=false]
1144
+ * @param {boolean} [opts.ascii=false] 非ASCII文字を \uXXXX にする
1145
+ */
1146
+ function jyFormatJson(value, opts) {
1147
+ const o = opts || {};
1148
+ const tab = o.indent === 'tab';
1149
+ const width = tab ? 1 : o.indent === undefined ? 2 : Number(o.indent) || 0;
1150
+ const pad = tab ? '\t' : ' '.repeat(width);
1151
+ const oneLine = !tab && width === 0;
1152
+ const nl = oneLine ? '' : '\n';
1153
+ const sortKeys = Boolean(o.sortKeys);
1154
+ const ascii = Boolean(o.ascii);
1155
+
1156
+ const hex4 = (n) => '\\u' + n.toString(16).toLowerCase().padStart(4, '0');
1157
+
1158
+ function str(s) {
1159
+ let out = '"';
1160
+ for (let k = 0; k < s.length; k++) {
1161
+ const c = s.charAt(k);
1162
+ const cp = s.charCodeAt(k);
1163
+ if (c === '"') out += '\\"';
1164
+ else if (c === '\\') out += '\\\\';
1165
+ else if (c === '\n') out += '\\n';
1166
+ else if (c === '\r') out += '\\r';
1167
+ else if (c === '\t') out += '\\t';
1168
+ else if (cp === 8) out += '\\b';
1169
+ else if (cp === 12) out += '\\f';
1170
+ else if (cp < 0x20 || cp === 0x7f) out += hex4(cp);
1171
+ else if (ascii && cp > 0x7e) out += hex4(cp);
1172
+ else out += c;
1173
+ }
1174
+ return out + '"';
1175
+ }
1176
+
1177
+ function scalar(v) {
1178
+ if (v === null || v === undefined) return 'null';
1179
+ if (typeof v === 'boolean') return v ? 'true' : 'false';
1180
+ if (typeof v === 'number') return Number.isFinite(v) ? String(v) : 'null';
1181
+ return str(String(v));
1182
+ }
1183
+
1184
+ function write(v, level) {
1185
+ if (Array.isArray(v)) {
1186
+ if (!v.length) return '[]';
1187
+ const ind = oneLine ? '' : pad.repeat(level + 1);
1188
+ const close = oneLine ? '' : pad.repeat(level);
1189
+ const items = v.map((item) => ind + write(item, level + 1));
1190
+ return '[' + nl + items.join(',' + nl) + nl + close + ']';
1191
+ }
1192
+ if (jyIsPlainObject(v)) {
1193
+ const keys = sortKeys ? Object.keys(v).sort() : Object.keys(v);
1194
+ if (!keys.length) return '{}';
1195
+ const ind = oneLine ? '' : pad.repeat(level + 1);
1196
+ const close = oneLine ? '' : pad.repeat(level);
1197
+ const items = keys.map((k) => ind + str(k) + (oneLine ? ':' : ': ') + write(v[k], level + 1));
1198
+ return '{' + nl + items.join(',' + nl) + nl + close + '}';
1199
+ }
1200
+ return scalar(v);
1201
+ }
1202
+
1203
+ return write(value, 0);
1204
+ }
1205
+
1206
+ /* ---------------------------------------------------------------------------
1207
+ * YAML 出力
1208
+ * ------------------------------------------------------------------------- */
1209
+
1210
+ const JY_CONTROL_RE = /[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f-\u009f\uFEFF]/;
1211
+
1212
+ /** 引用符なし(プレーン)で書ける文字列かどうか */
1213
+ function jyPlainSafe(s) {
1214
+ if (s === '') return false;
1215
+ if (/^[ \t]|[ \t]$/.test(s)) return false; // 前後の空白は失われる
1216
+ if (/[\n\r]/.test(s) || JY_CONTROL_RE.test(s)) return false; // 改行・制御文字
1217
+ if (/: /.test(s) || /:$/.test(s)) return false; // マップの区切りに見える
1218
+ if (JY_SEXAGESIMAL.test(s)) return false; // 12:30 が 750 に化けるパーサがある
1219
+ if (/ #/.test(s)) return false; // コメントの始まりに見える
1220
+ if (/^[-?:]([ \t]|$)/.test(s)) return false; // 指示子+空白
1221
+ if (/^[,[\]{}#&*!|>'"%@`]/.test(s)) return false; // 先頭に置けない記号
1222
+ if (s === '---' || s === '...') return false; // ドキュメントの区切りに見える
1223
+ if (typeof jyResolveScalar(s) !== 'string') return false; // 数値・真偽値・null に化ける
1224
+ if (JY_YAML11_BOOL.test(s)) return false; // YAML 1.1 のパーサで真偽値に化ける
1225
+ if (/^[0-9]{4}-[0-9]{2}-[0-9]{2}([Tt ].*)?$/.test(s)) return false; // 日付に化ける
1226
+ return true;
1227
+ }
1228
+
1229
+ /**
1230
+ * 値をYAML文字列へ。
1231
+ *
1232
+ * @param {*} value
1233
+ * @param {object} [opts]
1234
+ * @param {number} [opts.indent=2] ネスト1段あたりの空白数(1-8)
1235
+ * @param {boolean}[opts.block=true] 改行を含む文字列をブロックスカラー(|)で書く
1236
+ * @param {boolean}[opts.sortKeys=false] キーを名前順に並べる
1237
+ * @param {boolean}[opts.docStart=false] 先頭に --- を付ける
1238
+ * @param {'auto'|'single'|'double'} [opts.quote='auto'] 引用符の付け方
1239
+ * @param {'null'|'tilde'|'empty'} [opts.nullStyle='null'] null の書き方
1240
+ */
1241
+ function jyFormatYaml(value, opts) {
1242
+ const o = opts || {};
1243
+ const step = Math.max(1, Math.min(8, Number(o.indent) || 2));
1244
+ const pad = ' '.repeat(step);
1245
+ const quote = o.quote === 'single' || o.quote === 'double' ? o.quote : 'auto';
1246
+ const block = o.block !== false;
1247
+ const sortKeys = Boolean(o.sortKeys);
1248
+ const nullText = o.nullStyle === 'tilde' ? '~' : o.nullStyle === 'empty' ? '' : 'null';
1249
+
1250
+ function dq(s) {
1251
+ let out = '"';
1252
+ for (let k = 0; k < s.length; k++) {
1253
+ const c = s.charAt(k);
1254
+ const cp = s.charCodeAt(k);
1255
+ if (c === '"') out += '\\"';
1256
+ else if (c === '\\') out += '\\\\';
1257
+ else if (c === '\n') out += '\\n';
1258
+ else if (c === '\r') out += '\\r';
1259
+ else if (c === '\t') out += '\\t';
1260
+ else if (cp < 0x20 || cp === 0x7f) out += '\\x' + cp.toString(16).toUpperCase().padStart(2, '0');
1261
+ else if (cp >= 0x80 && cp <= 0x9f) out += '\\u' + cp.toString(16).toUpperCase().padStart(4, '0');
1262
+ else out += c;
1263
+ }
1264
+ return out + '"';
1265
+ }
1266
+
1267
+ function quoted(s) {
1268
+ if (quote === 'double') return dq(s);
1269
+ if (/[\n\r]/.test(s) || JY_CONTROL_RE.test(s)) return dq(s);
1270
+ return "'" + s.replace(/'/g, "''") + "'";
1271
+ }
1272
+
1273
+ /** ブロックスカラー(|)で安全に書ける文字列かどうか */
1274
+ function blockSafe(s) {
1275
+ if (!block || s.indexOf('\n') === -1) return false;
1276
+ if (JY_CONTROL_RE.test(s) || s.indexOf('\r') !== -1) return false;
1277
+ if (/^[ \t]/.test(s)) return false; // 1行目の字下げは復元できない
1278
+ if (/[ \t]$/m.test(s)) return false; // 行末の空白は復元できない
1279
+ if (/\n{2,}$/.test(s)) return false; // 末尾の空行は次の行と紛れる
1280
+ if (/^\s*$/.test(s)) return false;
1281
+ return true;
1282
+ }
1283
+
1284
+ function scalarText(v) {
1285
+ if (v === null || v === undefined) return nullText;
1286
+ if (typeof v === 'boolean') return v ? 'true' : 'false';
1287
+ if (typeof v === 'number') {
1288
+ if (Number.isNaN(v)) return '.nan';
1289
+ if (v === Infinity) return '.inf';
1290
+ if (v === -Infinity) return '-.inf';
1291
+ return String(v);
1292
+ }
1293
+ const s = String(v);
1294
+ if (quote === 'auto' && jyPlainSafe(s)) return s;
1295
+ return quoted(s);
1296
+ }
1297
+
1298
+ function keyText(k) {
1299
+ // << を素で書くとマージ指示になるので、データとしてのキーなら必ず引用符で囲む
1300
+ if (k === '<<') return quoted(k);
1301
+ if (quote === 'auto' && jyPlainSafe(k) && k.indexOf('#') === -1) return k;
1302
+ return quoted(k);
1303
+ }
1304
+
1305
+ const out = [];
1306
+
1307
+ /** head は "key:" か "-"。値の形に応じて1行で書くか、下へ続けるかを決める */
1308
+ function writeEntry(head, v, level, isSeq) {
1309
+ const ind = pad.repeat(level);
1310
+ if (Array.isArray(v)) {
1311
+ if (!v.length) {
1312
+ out.push(ind + head + ' []');
1313
+ return;
1314
+ }
1315
+ if (isSeq) {
1316
+ pushCompact(ind, v, true);
1317
+ return;
1318
+ }
1319
+ out.push(ind + head);
1320
+ writeSeq(v, level + 1);
1321
+ return;
1322
+ }
1323
+ if (jyIsPlainObject(v)) {
1324
+ const keys = Object.keys(v);
1325
+ if (!keys.length) {
1326
+ out.push(ind + head + ' {}');
1327
+ return;
1328
+ }
1329
+ if (isSeq) {
1330
+ pushCompact(ind, v, false);
1331
+ return;
1332
+ }
1333
+ out.push(ind + head);
1334
+ writeMap(v, level + 1);
1335
+ return;
1336
+ }
1337
+ if (typeof v === 'string' && blockSafe(v)) {
1338
+ // 末尾に改行が無ければ |- 、1つだけなら |(余分な改行を足さない・削らない)
1339
+ out.push(ind + head + ' ' + (/\n$/.test(v) ? '|' : '|-'));
1340
+ const body = v.replace(/\n$/, '').split('\n');
1341
+ const inner = ind + pad;
1342
+ for (const ln of body) out.push(ln === '' ? '' : inner + ln);
1343
+ return;
1344
+ }
1345
+ const text = scalarText(v);
1346
+ if (text !== '') {
1347
+ out.push(ind + head + ' ' + text);
1348
+ return;
1349
+ }
1350
+ // null を空欄で書く設定でも、シーケンスの「- 」だけの行は次の行との切れ目が
1351
+ // 読み手にもパーサにも曖昧になるので、要素のときは必ず null と書く
1352
+ out.push(isSeq ? ind + head + ' null' : ind + head);
1353
+ }
1354
+
1355
+ /** 「- 」に続けて入れ子を書く(- name: a のコンパクト記法) */
1356
+ function pushCompact(ind, v, isArray) {
1357
+ const sub = [];
1358
+ const saved = out.length;
1359
+ if (isArray) writeSeq(v, 0);
1360
+ else writeMap(v, 0);
1361
+ for (let k = saved; k < out.length; k++) sub.push(out[k]);
1362
+ out.length = saved;
1363
+ out.push(ind + '- ' + sub[0]);
1364
+ for (let k = 1; k < sub.length; k++) out.push(sub[k] === '' ? '' : ind + ' ' + sub[k]);
1365
+ }
1366
+
1367
+ function writeMap(obj, level) {
1368
+ const keys = sortKeys ? Object.keys(obj).sort() : Object.keys(obj);
1369
+ for (const k of keys) writeEntry(keyText(k) + ':', obj[k], level, false);
1370
+ }
1371
+
1372
+ function writeSeq(arr, level) {
1373
+ for (const v of arr) writeEntry('-', v, level, true);
1374
+ }
1375
+
1376
+ if (o.docStart) out.push('---');
1377
+ if (Array.isArray(value)) {
1378
+ if (!value.length) out.push('[]');
1379
+ else writeSeq(value, 0);
1380
+ } else if (jyIsPlainObject(value)) {
1381
+ if (!Object.keys(value).length) out.push('{}');
1382
+ else writeMap(value, 0);
1383
+ } else if (typeof value === 'string' && blockSafe(value)) {
1384
+ out.push(/\n$/.test(value) ? '|' : '|-');
1385
+ for (const ln of value.replace(/\n$/, '').split('\n')) out.push(ln === '' ? '' : pad + ln);
1386
+ } else {
1387
+ out.push(scalarText(value));
1388
+ }
1389
+ return out.join('\n') + '\n';
1390
+ }
1391
+
1392
+ /* ---------------------------------------------------------------------------
1393
+ * 統計・エラー位置の抜き出し・変換の入口
1394
+ * ------------------------------------------------------------------------- */
1395
+
1396
+ const jyByteLength = (s) => (typeof TextEncoder === 'function' ? new TextEncoder().encode(s).length : Buffer.byteLength(s, 'utf8'));
1397
+
1398
+ /** 変換結果の規模を数える(キー数・最大の入れ子の深さなど) */
1399
+ function jyStats(value) {
1400
+ const s = { nodes: 0, keys: 0, objects: 0, arrays: 0, scalars: 0, max_depth: 0, non_finite: 0 };
1401
+ (function walk(v, d) {
1402
+ s.nodes += 1;
1403
+ if (d > s.max_depth) s.max_depth = d;
1404
+ if (Array.isArray(v)) {
1405
+ s.arrays += 1;
1406
+ for (const item of v) walk(item, d + 1);
1407
+ return;
1408
+ }
1409
+ if (jyIsPlainObject(v)) {
1410
+ s.objects += 1;
1411
+ const keys = Object.keys(v);
1412
+ s.keys += keys.length;
1413
+ for (const k of keys) walk(v[k], d + 1);
1414
+ return;
1415
+ }
1416
+ s.scalars += 1;
1417
+ if (typeof v === 'number' && !Number.isFinite(v)) s.non_finite += 1;
1418
+ })(value, 1);
1419
+ return s;
1420
+ }
1421
+
1422
+ /** エラー行の前後を切り出す(画面ではこれをそのままハイライト表示に使う) */
1423
+ function jyExcerpt(text, line, col, span) {
1424
+ const all = String(text).replace(/\r\n?/g, '\n').split('\n');
1425
+ if (all.length > 1 && all[all.length - 1] === '') all.pop(); // 末尾の改行が作る空行は数えない
1426
+ const from = Math.max(1, line - 2);
1427
+ const to = Math.min(all.length, line + 2);
1428
+ const rows = [];
1429
+ for (let n = from; n <= to; n++) {
1430
+ rows.push({ line: n, text: all[n - 1] === undefined ? '' : all[n - 1], error: n === line });
1431
+ }
1432
+ return { rows, line, col, span: span || 1 };
1433
+ }
1434
+
1435
+ /**
1436
+ * JSON ⇄ YAML の変換1回分。整形(json→json / yaml→yaml)も同じ入口で扱う。
1437
+ *
1438
+ * @param {object} opts
1439
+ * @param {'json2yaml'|'yaml2json'|'json2json'|'yaml2yaml'} [opts.direction='json2yaml']
1440
+ * @param {string} opts.text
1441
+ * @param {boolean}[opts.relaxed=true] JSON入力でコメント・末尾カンマ等を受け取る
1442
+ * 出力オプションは jyFormatYaml / jyFormatJson と共通。
1443
+ */
1444
+ function jyConvert(opts) {
1445
+ const o = opts || {};
1446
+ const allowed = ['json2yaml', 'yaml2json', 'json2json', 'yaml2yaml'];
1447
+ const direction = allowed.indexOf(o.direction) === -1 ? 'json2yaml' : o.direction;
1448
+ const from = direction.slice(0, 4);
1449
+ const to = direction.slice(5);
1450
+ const text = typeof o.text === 'string' ? o.text : '';
1451
+
1452
+ if (text.trim() === '') {
1453
+ return { ok: true, direction, from, to, empty: true, output: '', notes: [], stats: null, documents: 0 };
1454
+ }
1455
+
1456
+ const parsed = from === 'json' ? jyParseJson(text, o) : jyParseYaml(text);
1457
+ if (!parsed.ok) {
1458
+ return {
1459
+ ok: false,
1460
+ direction,
1461
+ from,
1462
+ to,
1463
+ error: parsed.error,
1464
+ excerpt: jyExcerpt(text, parsed.error.line, parsed.error.col, parsed.error.found ? String(parsed.error.found).length : 1),
1465
+ notes: parsed.notes,
1466
+ };
1467
+ }
1468
+
1469
+ const value = parsed.value;
1470
+ const stats = jyStats(value);
1471
+ const notes = parsed.notes.slice();
1472
+ if (to === 'json' && stats.non_finite > 0) {
1473
+ notes.push({ code: 'NONFINITE_OUTPUT', level: 'warn', count: stats.non_finite, items: [], lines: [] });
1474
+ }
1475
+ const output = to === 'yaml' ? jyFormatYaml(value, o) : jyFormatJson(value, o) + '\n';
1476
+
1477
+ return {
1478
+ ok: true,
1479
+ direction,
1480
+ from,
1481
+ to,
1482
+ output,
1483
+ value,
1484
+ documents: from === 'yaml' ? parsed.docs.length : 1,
1485
+ input_bytes: jyByteLength(text),
1486
+ output_bytes: jyByteLength(output),
1487
+ input_lines: text.replace(/\n$/, '').split('\n').length,
1488
+ output_lines: output.replace(/\n$/, '').split('\n').length,
1489
+ stats,
1490
+ notes,
1491
+ };
1492
+ }
1493
+
1494
+ /* ==================== ここまで変換コア ==================== */
1495
+
1496
+ /* ==================== OpenAPI → 日本語ドキュメント / TypeScript 型定義 ==================== */
1497
+
1498
+ const OA_METHODS = ['get', 'put', 'post', 'delete', 'options', 'head', 'patch', 'trace'];
1499
+ const oaOwn = (o, k) => o !== null && typeof o === 'object' && Object.prototype.hasOwnProperty.call(o, k);
1500
+ const oaStr = (v) => (typeof v === 'string' ? v : typeof v === 'number' || typeof v === 'boolean' ? String(v) : '');
1501
+
1502
+ // 1回の生成で schema を辿る回数の上限。YAML のエイリアスは同じ物を共有したまま展開されるため、
1503
+ // 入れ子にしたエイリアスで出力が指数的に膨らむ入力を途中で止める。
1504
+ const OA_MAX_VISITS = 20000000;
1505
+ // 型の式1つの長さの上限(文字数)。共有されたエイリアスは回数より先に文字列の長さで膨らむので、こちらでも止める
1506
+ const OA_MAX_TYPE_CHARS = 4000000;
1507
+ function oaTooLarge() {
1508
+ const e = new Error('OA_TOO_LARGE');
1509
+ e.oa = { code: 'OA_TOO_LARGE' };
1510
+ throw e;
1511
+ }
1512
+ // インラインの入れ子($ref を挟まない object の中の object)を型として書き出す深さの上限
1513
+ const OA_MAX_INLINE_DEPTH = 24;
1514
+
1515
+ // 指摘の重さ(warn = 出力が仕様どおりにならない所がある / info = 知っておくと良い)
1516
+ const OA_NOTE_LEVEL = {
1517
+ OA_MULTI_DOC: 'info',
1518
+ OA_EXTERNAL_REF: 'warn',
1519
+ OA_BROKEN_REF: 'warn',
1520
+ OA_DUP_OPERATION_ID: 'warn',
1521
+ OA_NO_PATHS: 'info',
1522
+ OA_RENAMED_TYPE: 'info',
1523
+ OA_VERSION_UNKNOWN: 'warn',
1524
+ OA_JSON_RELAXED: 'info',
1525
+ };
1526
+
1527
+ function oaNotes() {
1528
+ const list = [];
1529
+ const byCode = Object.create(null);
1530
+ return {
1531
+ list,
1532
+ add(code, item) {
1533
+ let n = byCode[code];
1534
+ if (!n) {
1535
+ n = { code, level: OA_NOTE_LEVEL[code] || 'warn', count: 0, items: [] };
1536
+ byCode[code] = n;
1537
+ list.push(n);
1538
+ }
1539
+ n.count += 1;
1540
+ if (item !== undefined && item !== null && n.items.length < 6 && n.items.indexOf(item) === -1) n.items.push(item);
1541
+ return n;
1542
+ },
1543
+ };
1544
+ }
1545
+
1546
+ /**
1547
+ * 文字列を OpenAPI / Swagger の仕様として読む。先頭が { か [ なら JSON、それ以外は YAML。
1548
+ * 返り値: { ok, spec, version, kind: 'openapi3'|'swagger2', format, notes } か { ok:false, error, excerpt }
1549
+ */
1550
+ function oaParse(text) {
1551
+ const src = typeof text === 'string' ? text : '';
1552
+ const N = oaNotes();
1553
+ if (src.trim() === '') return { ok: false, error: { code: 'EMPTY_INPUT', line: 1, col: 1 }, notes: [] };
1554
+ const head = src.replace(/^/, '').replace(/^\s+/, '').charAt(0);
1555
+ const format = head === '{' || head === '[' ? 'json' : 'yaml';
1556
+ const parsed = format === 'json' ? jyParseJson(src, { relaxed: true }) : jyParseYaml(src);
1557
+ if (!parsed.ok) {
1558
+ const e = parsed.error;
1559
+ return { ok: false, format, error: e, excerpt: jyExcerpt(src, e.line, e.col, e.found ? String(e.found).length : 1), notes: [] };
1560
+ }
1561
+ if (format === 'json' && parsed.notes.some((n) => /^JSON_/.test(n.code))) N.add('OA_JSON_RELAXED');
1562
+ let spec = parsed.value;
1563
+ if (format === 'yaml' && parsed.docs && parsed.docs.length > 1) {
1564
+ spec = parsed.docs[0];
1565
+ N.add('OA_MULTI_DOC');
1566
+ }
1567
+ if (!jyIsPlainObject(spec)) return { ok: false, format, error: { code: 'OA_NOT_OBJECT', line: 1, col: 1 }, notes: N.list };
1568
+ let kind = null;
1569
+ let version = '';
1570
+ if (oaOwn(spec, 'openapi')) {
1571
+ version = oaStr(spec.openapi);
1572
+ kind = 'openapi3';
1573
+ if (!/^3\./.test(version)) N.add('OA_VERSION_UNKNOWN', version || '?');
1574
+ } else if (oaOwn(spec, 'swagger')) {
1575
+ version = oaStr(spec.swagger);
1576
+ kind = 'swagger2';
1577
+ if (!/^2(\.0)?$/.test(version)) N.add('OA_VERSION_UNKNOWN', version || '?');
1578
+ } else {
1579
+ return { ok: false, format, error: { code: 'OA_NOT_SPEC', line: 1, col: 1 }, notes: N.list };
1580
+ }
1581
+ return { ok: true, spec, kind, version, format, notes: N.list };
1582
+ }
1583
+
1584
+ /* ---------------------------------------------------------------------------
1585
+ * 仕様の読み取り(Swagger 2.0 も OpenAPI 3 と同じ形の内部モデルへ揃える)
1586
+ * ------------------------------------------------------------------------- */
1587
+
1588
+ /** JSON Pointer(#/components/schemas/Pet)を辿る。見つからなければ undefined */
1589
+ function oaPointer(root, ref) {
1590
+ if (ref === '#') return root;
1591
+ if (ref.slice(0, 2) !== '#/') return undefined;
1592
+ let cur = root;
1593
+ for (const raw of ref.slice(2).split('/')) {
1594
+ let key = raw.replace(/~1/g, '/').replace(/~0/g, '~');
1595
+ try { key = decodeURIComponent(key); } catch (e) { /* % を含むキーはそのまま */ }
1596
+ if (Array.isArray(cur)) {
1597
+ if (!/^(0|[1-9][0-9]*)$/.test(key) || Number(key) >= cur.length) return undefined;
1598
+ cur = cur[Number(key)];
1599
+ } else if (oaOwn(cur, key)) {
1600
+ cur = cur[key];
1601
+ } else {
1602
+ return undefined;
1603
+ }
1604
+ }
1605
+ return cur;
1606
+ }
1607
+
1608
+ const OA_TS_RESERVED = new Set(('any unknown never object string number boolean symbol bigint void null undefined ' +
1609
+ 'break case catch class const continue debugger default delete do else enum export extends false finally for ' +
1610
+ 'function if import in instanceof new return super switch this throw true try typeof var while with ' +
1611
+ 'implements interface let package private protected public static yield type as await ' +
1612
+ 'Record Partial Required Readonly Pick Omit Array Object String Number Boolean Date Promise Map Set Blob File Error').split(' '));
1613
+
1614
+ /** 名前を TypeScript の型名(PascalCase)へ。英数字以外は区切りとみなす */
1615
+ function oaPascal(name) {
1616
+ const parts = String(name).split(/[^\p{L}\p{N}_$]+/u).filter(Boolean);
1617
+ let s = parts.map((p) => p.charAt(0).toUpperCase() + p.slice(1)).join('');
1618
+ if (s === '') s = 'Schema';
1619
+ if (/^\p{N}/u.test(s)) s = '_' + s;
1620
+ return s;
1621
+ }
1622
+
1623
+ /** プロパティ名。識別子として書けないものは引用符で囲む */
1624
+ function oaPropKey(k) {
1625
+ return /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(k) ? k : JSON.stringify(k);
1626
+ }
1627
+
1628
+ /**
1629
+ * 仕様全体を、ドキュメントと型定義の両方が使う形へ読み替える。
1630
+ * @param {object} spec oaParse が返した spec
1631
+ * @param {'openapi3'|'swagger2'} kind
1632
+ */
1633
+ function oaModel(spec, kind) {
1634
+ const N = oaNotes();
1635
+ const v2 = kind === 'swagger2';
1636
+ let visits = 0;
1637
+ const tick = () => {
1638
+ visits += 1;
1639
+ if (visits > OA_MAX_VISITS) oaTooLarge();
1640
+ };
1641
+
1642
+ /** $ref を辿りきった実体を返す(循環・外部参照・壊れた参照は null) */
1643
+ function deref(node) {
1644
+ let cur = node;
1645
+ for (let hop = 0; hop < 32; hop++) {
1646
+ if (!jyIsPlainObject(cur) || typeof cur.$ref !== 'string') return cur;
1647
+ const ref = cur.$ref;
1648
+ if (ref.charAt(0) !== '#') {
1649
+ N.add('OA_EXTERNAL_REF', ref);
1650
+ return null;
1651
+ }
1652
+ const next = oaPointer(spec, ref);
1653
+ if (next === undefined) {
1654
+ N.add('OA_BROKEN_REF', ref);
1655
+ return null;
1656
+ }
1657
+ cur = next;
1658
+ }
1659
+ return null;
1660
+ }
1661
+
1662
+ // 名前の付いたスキーマ(components.schemas / definitions)
1663
+ const schemaPrefix = v2 ? '#/definitions/' : '#/components/schemas/';
1664
+ const schemaRoot = v2 ? spec.definitions : jyIsPlainObject(spec.components) ? spec.components.schemas : undefined;
1665
+ const schemas = [];
1666
+ const byRef = new Map();
1667
+ const usedTs = new Set();
1668
+ if (jyIsPlainObject(schemaRoot)) {
1669
+ for (const name of Object.keys(schemaRoot)) {
1670
+ // pet → Pet のような書き換えは黙って行い、予約語・重複を避けて名前を変えたときだけ知らせる
1671
+ let ts = oaPascal(name);
1672
+ const plain = ts;
1673
+ if (OA_TS_RESERVED.has(ts)) ts += 'Schema';
1674
+ let k = 2;
1675
+ const base = ts;
1676
+ while (usedTs.has(ts)) ts = base + k++;
1677
+ usedTs.add(ts);
1678
+ if (ts !== plain) N.add('OA_RENAMED_TYPE', `${name} → ${ts}`);
1679
+ const ref = schemaPrefix + name.replace(/~/g, '~0').replace(/\//g, '~1');
1680
+ const entry = { name, ts, ref, schema: schemaRoot[name] };
1681
+ schemas.push(entry);
1682
+ byRef.set(ref, entry);
1683
+ }
1684
+ }
1685
+ /** $ref が名前付きスキーマを指していればその項目(%エンコードされた参照も拾う) */
1686
+ function named(ref) {
1687
+ if (byRef.has(ref)) return byRef.get(ref);
1688
+ if (ref.indexOf('%') !== -1) {
1689
+ try { return byRef.get(decodeURIComponent(ref)) || null; } catch (e) { return null; }
1690
+ }
1691
+ return null;
1692
+ }
1693
+
1694
+ const info = jyIsPlainObject(spec.info) ? spec.info : {};
1695
+
1696
+ // サーバー(ベースURL)
1697
+ const servers = [];
1698
+ if (v2) {
1699
+ if (typeof spec.host === 'string' && spec.host) {
1700
+ const schemes = Array.isArray(spec.schemes) && spec.schemes.length ? spec.schemes : ['https'];
1701
+ for (const s of schemes) servers.push({ url: `${oaStr(s)}://${spec.host}${oaStr(spec.basePath)}`, description: '' });
1702
+ } else if (typeof spec.basePath === 'string' && spec.basePath) {
1703
+ servers.push({ url: spec.basePath, description: '' });
1704
+ }
1705
+ } else if (Array.isArray(spec.servers)) {
1706
+ for (const s of spec.servers) {
1707
+ if (jyIsPlainObject(s) && typeof s.url === 'string') servers.push({ url: s.url, description: oaStr(s.description) });
1708
+ }
1709
+ }
1710
+
1711
+ // 認証方式
1712
+ const security = [];
1713
+ const secRoot = v2 ? spec.securityDefinitions : jyIsPlainObject(spec.components) ? spec.components.securitySchemes : undefined;
1714
+ if (jyIsPlainObject(secRoot)) {
1715
+ for (const name of Object.keys(secRoot)) {
1716
+ const s = deref(secRoot[name]);
1717
+ if (!jyIsPlainObject(s)) continue;
1718
+ security.push({
1719
+ name,
1720
+ type: oaStr(s.type),
1721
+ scheme: oaStr(s.scheme),
1722
+ bearerFormat: oaStr(s.bearerFormat),
1723
+ in: oaStr(s.in),
1724
+ paramName: oaStr(s.name),
1725
+ flow: oaStr(s.flow) || (jyIsPlainObject(s.flows) ? Object.keys(s.flows).join(', ') : ''),
1726
+ openIdConnectUrl: oaStr(s.openIdConnectUrl),
1727
+ description: oaStr(s.description),
1728
+ });
1729
+ }
1730
+ }
1731
+ const globalSecurity = Array.isArray(spec.security) ? spec.security : null;
1732
+ const secNames = (list) => {
1733
+ if (!Array.isArray(list)) return null;
1734
+ const out = [];
1735
+ for (const req of list) if (jyIsPlainObject(req)) for (const k of Object.keys(req)) if (out.indexOf(k) === -1) out.push(k);
1736
+ return out;
1737
+ };
1738
+
1739
+ const globalConsumes = Array.isArray(spec.consumes) ? spec.consumes.filter((x) => typeof x === 'string') : [];
1740
+ const globalProduces = Array.isArray(spec.produces) ? spec.produces.filter((x) => typeof x === 'string') : [];
1741
+
1742
+ /** Swagger 2.0 の非 body パラメータ(type 等を直に持つ)を schema の形へ */
1743
+ function v2ParamSchema(p) {
1744
+ if (jyIsPlainObject(p.schema)) return p.schema;
1745
+ const s = {};
1746
+ for (const k of ['type', 'format', 'items', 'enum', 'default', 'minimum', 'maximum', 'pattern', 'minLength', 'maxLength']) {
1747
+ if (oaOwn(p, k)) s[k] = p[k];
1748
+ }
1749
+ if (s.type === 'file') {
1750
+ s.type = 'string';
1751
+ s.format = 'binary';
1752
+ }
1753
+ return s;
1754
+ }
1755
+
1756
+ /** パラメータの並び(パス共通 + 操作ごと。同じ name+in は操作側が勝つ) */
1757
+ function mergeParams(shared, own) {
1758
+ const map = new Map();
1759
+ for (const list of [shared, own]) {
1760
+ if (!Array.isArray(list)) continue;
1761
+ for (const raw of list) {
1762
+ const p = deref(raw);
1763
+ if (!jyIsPlainObject(p) || typeof p.name !== 'string') continue;
1764
+ map.set(`${oaStr(p.in)}\u0000${p.name}`, p);
1765
+ }
1766
+ }
1767
+ return Array.from(map.values());
1768
+ }
1769
+
1770
+ /** media type の例(example → examples の最初 → schema.example の順) */
1771
+ function mediaExample(media, schema) {
1772
+ if (oaOwn(media, 'example')) return { has: true, value: media.example };
1773
+ if (jyIsPlainObject(media.examples)) {
1774
+ for (const k of Object.keys(media.examples)) {
1775
+ const ex = deref(media.examples[k]);
1776
+ if (jyIsPlainObject(ex) && oaOwn(ex, 'value')) return { has: true, value: ex.value };
1777
+ }
1778
+ }
1779
+ const s = deref(schema);
1780
+ if (jyIsPlainObject(s) && oaOwn(s, 'example')) return { has: true, value: s.example };
1781
+ return { has: false };
1782
+ }
1783
+
1784
+ function contentsOf(content) {
1785
+ const out = [];
1786
+ if (!jyIsPlainObject(content)) return out;
1787
+ for (const type of Object.keys(content)) {
1788
+ const media = jyIsPlainObject(content[type]) ? content[type] : {};
1789
+ const schema = oaOwn(media, 'schema') ? media.schema : null;
1790
+ out.push({ type, schema, example: mediaExample(media, schema) });
1791
+ }
1792
+ return out;
1793
+ }
1794
+
1795
+ const operations = [];
1796
+ const tagOrder = [];
1797
+ const tagInfo = new Map();
1798
+ if (Array.isArray(spec.tags)) {
1799
+ for (const t of spec.tags) {
1800
+ if (jyIsPlainObject(t) && typeof t.name === 'string' && !tagInfo.has(t.name)) {
1801
+ tagOrder.push(t.name);
1802
+ tagInfo.set(t.name, oaStr(t.description));
1803
+ }
1804
+ }
1805
+ }
1806
+ const seenOpIds = new Set();
1807
+ const paths = jyIsPlainObject(spec.paths) ? spec.paths : null;
1808
+ if (!paths || Object.keys(paths).filter((k) => k.slice(0, 2) !== 'x-').length === 0) N.add('OA_NO_PATHS');
1809
+ if (paths) {
1810
+ for (const path of Object.keys(paths)) {
1811
+ if (path.slice(0, 2) === 'x-') continue;
1812
+ const item = deref(paths[path]);
1813
+ if (!jyIsPlainObject(item)) continue;
1814
+ for (const method of OA_METHODS) {
1815
+ if (!jyIsPlainObject(item[method])) continue;
1816
+ tick();
1817
+ const op = item[method];
1818
+ const params = [];
1819
+ let body = null;
1820
+ const formProps = {};
1821
+ const formRequired = [];
1822
+ for (const p of mergeParams(item.parameters, op.parameters)) {
1823
+ const where = oaStr(p.in);
1824
+ if (v2 && where === 'body') {
1825
+ const types = Array.isArray(op.consumes) && op.consumes.length ? op.consumes : globalConsumes.length ? globalConsumes : ['application/json'];
1826
+ body = {
1827
+ required: p.required === true,
1828
+ description: oaStr(p.description),
1829
+ contents: types.filter((t) => typeof t === 'string').slice(0, 1).map((type) => ({ type, schema: p.schema || null, example: mediaExample({}, p.schema) })),
1830
+ };
1831
+ continue;
1832
+ }
1833
+ if (v2 && where === 'formData') {
1834
+ formProps[p.name] = Object.assign({}, v2ParamSchema(p), p.description ? { description: oaStr(p.description) } : {});
1835
+ if (p.required === true) formRequired.push(p.name);
1836
+ continue;
1837
+ }
1838
+ params.push({
1839
+ name: p.name,
1840
+ in: where,
1841
+ required: p.required === true || where === 'path',
1842
+ description: oaStr(p.description),
1843
+ deprecated: p.deprecated === true,
1844
+ schema: v2 ? v2ParamSchema(p) : jyIsPlainObject(p.schema) ? p.schema : p.content && jyIsPlainObject(p.content) ? (contentsOf(p.content)[0] || {}).schema || null : null,
1845
+ example: oaOwn(p, 'example') ? { has: true, value: p.example } : { has: false },
1846
+ });
1847
+ }
1848
+ if (v2 && Object.keys(formProps).length) {
1849
+ const consumes = Array.isArray(op.consumes) && op.consumes.length ? op.consumes : globalConsumes;
1850
+ const hasFile = Object.keys(formProps).some((k) => formProps[k].format === 'binary');
1851
+ const type = consumes.find((t) => /multipart|urlencoded/.test(t)) || (hasFile ? 'multipart/form-data' : 'application/x-www-form-urlencoded');
1852
+ const schema = { type: 'object', properties: formProps };
1853
+ if (formRequired.length) schema.required = formRequired;
1854
+ body = { required: formRequired.length > 0, description: '', contents: [{ type, schema, example: { has: false } }] };
1855
+ }
1856
+ if (!v2 && oaOwn(op, 'requestBody')) {
1857
+ const rb = deref(op.requestBody);
1858
+ if (jyIsPlainObject(rb)) body = { required: rb.required === true, description: oaStr(rb.description), contents: contentsOf(rb.content) };
1859
+ }
1860
+
1861
+ const responses = [];
1862
+ if (jyIsPlainObject(op.responses)) {
1863
+ for (const status of Object.keys(op.responses)) {
1864
+ if (status.slice(0, 2) === 'x-') continue;
1865
+ const r = deref(op.responses[status]);
1866
+ if (!jyIsPlainObject(r)) {
1867
+ responses.push({ status, description: '', contents: [], headers: [] });
1868
+ continue;
1869
+ }
1870
+ let contents;
1871
+ if (v2) {
1872
+ contents = [];
1873
+ if (oaOwn(r, 'schema')) {
1874
+ const produces = Array.isArray(op.produces) && op.produces.length ? op.produces : globalProduces.length ? globalProduces : ['application/json'];
1875
+ const type = produces.find((t) => /json/.test(t)) || produces[0];
1876
+ let example = { has: false };
1877
+ if (jyIsPlainObject(r.examples)) {
1878
+ const k = Object.keys(r.examples).find((t) => /json/.test(t)) || Object.keys(r.examples)[0];
1879
+ if (k !== undefined) example = { has: true, value: r.examples[k] };
1880
+ }
1881
+ if (!example.has) example = mediaExample({}, r.schema);
1882
+ contents.push({ type, schema: r.schema, example });
1883
+ }
1884
+ } else {
1885
+ contents = contentsOf(r.content);
1886
+ }
1887
+ const headers = [];
1888
+ if (jyIsPlainObject(r.headers)) {
1889
+ for (const h of Object.keys(r.headers)) {
1890
+ const hd = deref(r.headers[h]);
1891
+ if (!jyIsPlainObject(hd)) continue;
1892
+ headers.push({ name: h, description: oaStr(hd.description), schema: v2 ? v2ParamSchema(hd) : hd.schema || null });
1893
+ }
1894
+ }
1895
+ responses.push({ status, description: oaStr(r.description), contents, headers });
1896
+ }
1897
+ }
1898
+
1899
+ const operationId = typeof op.operationId === 'string' && op.operationId ? op.operationId : '';
1900
+ if (operationId) {
1901
+ if (seenOpIds.has(operationId)) N.add('OA_DUP_OPERATION_ID', operationId);
1902
+ seenOpIds.add(operationId);
1903
+ }
1904
+ const tags = Array.isArray(op.tags) ? op.tags.filter((t) => typeof t === 'string') : [];
1905
+ for (const t of tags) {
1906
+ if (!tagInfo.has(t)) {
1907
+ tagOrder.push(t);
1908
+ tagInfo.set(t, '');
1909
+ }
1910
+ }
1911
+ const sec = secNames(oaOwn(op, 'security') ? op.security : globalSecurity);
1912
+ operations.push({
1913
+ method,
1914
+ path,
1915
+ operationId,
1916
+ summary: oaStr(op.summary),
1917
+ description: oaStr(op.description),
1918
+ tags,
1919
+ deprecated: op.deprecated === true,
1920
+ params,
1921
+ body,
1922
+ responses,
1923
+ security: sec,
1924
+ });
1925
+ }
1926
+ }
1927
+ }
1928
+
1929
+ return {
1930
+ kind,
1931
+ v2,
1932
+ spec,
1933
+ title: oaStr(info.title),
1934
+ version: oaStr(info.version),
1935
+ description: oaStr(info.description),
1936
+ servers,
1937
+ security,
1938
+ globalSecurity: secNames(globalSecurity),
1939
+ operations,
1940
+ schemas,
1941
+ tags: tagOrder.map((name) => ({ name, description: tagInfo.get(name) })),
1942
+ notes: N,
1943
+ deref,
1944
+ named,
1945
+ tick,
1946
+ };
1947
+ }
1948
+
1949
+ /* ---------------------------------------------------------------------------
1950
+ * schema の読み方(型の表示・例の生成・TypeScript の型)
1951
+ * ------------------------------------------------------------------------- */
1952
+
1953
+ /** schema.type を配列にそろえる(3.1 の type: [string, "null"] と 3.0 の nullable を同じに扱う) */
1954
+ function oaTypes(s) {
1955
+ let types = Array.isArray(s.type) ? s.type.filter((t) => typeof t === 'string') : typeof s.type === 'string' ? [s.type] : [];
1956
+ if (types.length === 0) {
1957
+ if (jyIsPlainObject(s.properties) || oaOwn(s, 'additionalProperties')) types = ['object'];
1958
+ else if (oaOwn(s, 'items') || Array.isArray(s.prefixItems)) types = ['array'];
1959
+ }
1960
+ const nullable = s.nullable === true || types.indexOf('null') !== -1;
1961
+ return { types: types.filter((t) => t !== 'null'), nullable };
1962
+ }
1963
+
1964
+ /** ドキュメントの表に出す型の表記(例: Pet[] / string(date-time) / integer | null) */
1965
+ function oaTypeLabel(m, schema, depth) {
1966
+ m.tick();
1967
+ const d = depth || 0;
1968
+ if (schema === true || schema === undefined || schema === null) return 'any';
1969
+ if (!jyIsPlainObject(schema)) return 'any';
1970
+ if (typeof schema.$ref === 'string') {
1971
+ const n = m.named(schema.$ref);
1972
+ if (n) return n.name;
1973
+ if (d > 8) return 'object';
1974
+ const r = m.deref(schema);
1975
+ return r ? oaTypeLabel(m, r, d + 1) : 'any';
1976
+ }
1977
+ if (d > 8) return 'object';
1978
+ if (oaOwn(schema, 'const')) return JSON.stringify(schema.const);
1979
+ const joinOf = (key, sep) => schema[key].map((x) => oaTypeLabel(m, x, d + 1)).join(sep);
1980
+ if (Array.isArray(schema.oneOf) && schema.oneOf.length) return joinOf('oneOf', ' | ');
1981
+ if (Array.isArray(schema.anyOf) && schema.anyOf.length) return joinOf('anyOf', ' | ');
1982
+ if (Array.isArray(schema.allOf) && schema.allOf.length) return schema.allOf.length === 1 ? oaTypeLabel(m, schema.allOf[0], d + 1) : joinOf('allOf', ' & ');
1983
+ const { types, nullable } = oaTypes(schema);
1984
+ const labels = types.map((t) => {
1985
+ if (t === 'array') {
1986
+ return `${oaWrap(oaTypeLabel(m, schema.items, d + 1))}[]`;
1987
+ }
1988
+ if (typeof schema.format === 'string' && schema.format) return `${t}(${schema.format})`;
1989
+ return t;
1990
+ });
1991
+ let out = labels.length ? labels.join(' | ') : Array.isArray(schema.enum) ? 'enum' : 'any';
1992
+ if (nullable) out += ' | null';
1993
+ return out;
1994
+ }
1995
+
1996
+ /** 例の値を schema から作る(example → default → enum の先頭 → 型ごとの見本) */
1997
+ function oaSample(m, schema, depth, stack) {
1998
+ m.tick();
1999
+ const d = depth || 0;
2000
+ const st = stack || [];
2001
+ if (!jyIsPlainObject(schema)) return null;
2002
+ if (typeof schema.$ref === 'string') {
2003
+ if (st.indexOf(schema.$ref) !== -1 || d > 10) return null;
2004
+ const r = m.deref(schema);
2005
+ return r ? oaSample(m, r, d + 1, st.concat(schema.$ref)) : null;
2006
+ }
2007
+ if (oaOwn(schema, 'example')) return schema.example;
2008
+ if (Array.isArray(schema.examples) && schema.examples.length) return schema.examples[0];
2009
+ if (oaOwn(schema, 'const')) return schema.const;
2010
+ if (oaOwn(schema, 'default')) return schema.default;
2011
+ if (Array.isArray(schema.enum) && schema.enum.length) return schema.enum[0];
2012
+ if (d > 10) return null;
2013
+ if (Array.isArray(schema.allOf) && schema.allOf.length) {
2014
+ let merged = null;
2015
+ for (const part of schema.allOf) {
2016
+ const v = oaSample(m, part, d + 1, st);
2017
+ if (jyIsPlainObject(v)) merged = Object.assign(merged || {}, v);
2018
+ else if (merged === null && v !== null) return v;
2019
+ }
2020
+ if (jyIsPlainObject(schema.properties)) merged = Object.assign(merged || {}, oaSample(m, Object.assign({}, schema, { allOf: undefined }), d + 1, st));
2021
+ return merged;
2022
+ }
2023
+ const alt = Array.isArray(schema.oneOf) && schema.oneOf.length ? schema.oneOf : Array.isArray(schema.anyOf) && schema.anyOf.length ? schema.anyOf : null;
2024
+ if (alt) return oaSample(m, alt[0], d + 1, st);
2025
+ const { types } = oaTypes(schema);
2026
+ const t = types[0];
2027
+ if (t === 'object') {
2028
+ const out = {};
2029
+ if (jyIsPlainObject(schema.properties)) {
2030
+ for (const k of Object.keys(schema.properties)) {
2031
+ const ps = m.deref(schema.properties[k]);
2032
+ if (jyIsPlainObject(ps) && ps.writeOnly === true) continue;
2033
+ out[k] = oaSample(m, schema.properties[k], d + 1, st);
2034
+ }
2035
+ } else if (jyIsPlainObject(schema.additionalProperties)) {
2036
+ out.key = oaSample(m, schema.additionalProperties, d + 1, st);
2037
+ }
2038
+ return out;
2039
+ }
2040
+ if (t === 'array') {
2041
+ if (Array.isArray(schema.prefixItems)) return schema.prefixItems.map((x) => oaSample(m, x, d + 1, st));
2042
+ // 要素の例が作れない(循環する $ref など)ときは [null] でなく空の配列にする
2043
+ const v = oaSample(m, schema.items, d + 1, st);
2044
+ return v === null ? [] : [v];
2045
+ }
2046
+ if (t === 'integer') return typeof schema.minimum === 'number' ? Math.ceil(schema.minimum) : 0;
2047
+ if (t === 'number') return typeof schema.minimum === 'number' ? schema.minimum : 0;
2048
+ if (t === 'boolean') return true;
2049
+ if (t === 'string') {
2050
+ const f = oaStr(schema.format);
2051
+ if (f === 'date-time') return '2026-01-01T00:00:00Z';
2052
+ if (f === 'date') return '2026-01-01';
2053
+ if (f === 'time') return '12:00:00';
2054
+ if (f === 'email') return 'user@example.com';
2055
+ if (f === 'uuid') return '3fa85f64-5717-4562-b3fc-2c963f66afa6';
2056
+ if (f === 'uri' || f === 'url') return 'https://example.com';
2057
+ if (f === 'hostname') return 'example.com';
2058
+ if (f === 'ipv4') return '192.0.2.1';
2059
+ if (f === 'ipv6') return '2001:db8::1';
2060
+ if (f === 'byte') return 'U3dhZ2dlcg==';
2061
+ if (f === 'binary') return '(binary)';
2062
+ if (f === 'password') return '********';
2063
+ return 'string';
2064
+ }
2065
+ return null;
2066
+ }
2067
+
2068
+ /** 上限つきの JSON 整形(共有されたエイリアスで巨大になる例を途中で切る) */
2069
+ function oaJson(value, limit) {
2070
+ const max = limit || 20000;
2071
+ let out = '';
2072
+ let cut = false;
2073
+ (function w(v, ind) {
2074
+ if (cut) return;
2075
+ if (out.length > max) {
2076
+ cut = true;
2077
+ return;
2078
+ }
2079
+ if (Array.isArray(v)) {
2080
+ if (v.length === 0) {
2081
+ out += '[]';
2082
+ return;
2083
+ }
2084
+ out += '[\n';
2085
+ v.forEach((x, k) => {
2086
+ out += ind + ' ';
2087
+ w(x, ind + ' ');
2088
+ if (k < v.length - 1) out += ',';
2089
+ out += '\n';
2090
+ });
2091
+ out += ind + ']';
2092
+ return;
2093
+ }
2094
+ if (jyIsPlainObject(v)) {
2095
+ const keys = Object.keys(v).filter((k) => v[k] !== undefined);
2096
+ if (keys.length === 0) {
2097
+ out += '{}';
2098
+ return;
2099
+ }
2100
+ out += '{\n';
2101
+ keys.forEach((k, n) => {
2102
+ out += ind + ' ' + JSON.stringify(k) + ': ';
2103
+ w(v[k], ind + ' ');
2104
+ if (n < keys.length - 1) out += ',';
2105
+ out += '\n';
2106
+ });
2107
+ out += ind + '}';
2108
+ return;
2109
+ }
2110
+ if (typeof v === 'number') {
2111
+ out += Number.isFinite(v) ? String(v) : 'null';
2112
+ return;
2113
+ }
2114
+ if (v === undefined) {
2115
+ out += 'null';
2116
+ return;
2117
+ }
2118
+ out += JSON.stringify(v);
2119
+ })(value, '');
2120
+ return cut ? out.slice(0, max) + '\n…' : out;
2121
+ }
2122
+
2123
+ /** TypeScript のリテラル型 */
2124
+ function oaLiteral(v) {
2125
+ if (v === null) return 'null';
2126
+ if (typeof v === 'string') return JSON.stringify(v);
2127
+ if (typeof v === 'number') return Number.isFinite(v) ? String(v) : 'number';
2128
+ if (typeof v === 'boolean') return String(v);
2129
+ return 'unknown';
2130
+ }
2131
+
2132
+ /** JSDoc の1ブロック(説明・形式・既定値・非推奨) */
2133
+ function oaDoc(s, ind) {
2134
+ if (!jyIsPlainObject(s)) return '';
2135
+ const lines = [];
2136
+ const desc = oaStr(s.description).trim() || oaStr(s.title).trim();
2137
+ if (desc) for (const l of desc.split(/\r?\n/)) lines.push(l.replace(/\s+$/, ''));
2138
+ if (typeof s.format === 'string' && s.format) lines.push(`@format ${s.format}`);
2139
+ if (oaOwn(s, 'default') && (s.default === null || typeof s.default !== 'object')) lines.push(`@default ${JSON.stringify(s.default)}`);
2140
+ if (s.deprecated === true) lines.push('@deprecated');
2141
+ while (lines.length && lines[lines.length - 1] === '') lines.pop();
2142
+ if (lines.length === 0) return '';
2143
+ const safe = lines.map((l) => l.replace(/\*\//g, '*\\/'));
2144
+ if (safe.length === 1) return `${ind}/** ${safe[0]} */\n`;
2145
+ return `${ind}/**\n${safe.map((l) => (l ? `${ind} * ${l}` : `${ind} *`)).join('\n')}\n${ind} */\n`;
2146
+ }
2147
+
2148
+ /** 型の式の一番外側に | か & があるか({ } [ ] ( ) < > と引用符の中は見ない) */
2149
+ function oaTopLevelOp(t) {
2150
+ let depth = 0;
2151
+ let q = '';
2152
+ for (let k = 0; k < t.length; k++) {
2153
+ const c = t.charAt(k);
2154
+ if (q) {
2155
+ if (c === '\\') k += 1;
2156
+ else if (c === q) q = '';
2157
+ continue;
2158
+ }
2159
+ if (c === '"' || c === "'") q = c;
2160
+ else if (c === '{' || c === '[' || c === '(' || c === '<') depth += 1;
2161
+ else if (c === '}' || c === ']' || c === ')' || c === '>') depth -= 1;
2162
+ else if (depth === 0 && (c === '|' || c === '&')) return true;
2163
+ }
2164
+ return false;
2165
+ }
2166
+ const oaWrap = (t) => (oaTopLevelOp(t) ? `(${t})` : t);
2167
+
2168
+ /** schema → TypeScript の型の式 */
2169
+ function oaTs(m, schema, ind, depth) {
2170
+ const t = oaTsExpr(m, schema, ind, depth);
2171
+ if (t.length > OA_MAX_TYPE_CHARS) oaTooLarge();
2172
+ return t;
2173
+ }
2174
+
2175
+ function oaTsExpr(m, schema, ind, depth) {
2176
+ m.tick();
2177
+ const d = depth || 0;
2178
+ if (schema === false) return 'never';
2179
+ if (!jyIsPlainObject(schema)) return 'unknown';
2180
+ if (typeof schema.$ref === 'string') {
2181
+ const n = m.named(schema.$ref);
2182
+ if (n) return n.ts;
2183
+ if (schema.$ref.charAt(0) !== '#') return 'unknown';
2184
+ if (d > OA_MAX_INLINE_DEPTH) return 'unknown';
2185
+ const r = m.deref(schema);
2186
+ return r === null ? 'unknown' : oaTs(m, r, ind, d + 1);
2187
+ }
2188
+ if (d > OA_MAX_INLINE_DEPTH) return 'unknown';
2189
+ const { types, nullable } = oaTypes(schema);
2190
+ const withNull = (t) => (nullable && t !== 'unknown' && !/(^|\| )null$/.test(t) ? `${t} | null` : t);
2191
+ if (oaOwn(schema, 'const')) return withNull(oaLiteral(schema.const));
2192
+ if (Array.isArray(schema.enum) && schema.enum.length) {
2193
+ const lits = [];
2194
+ for (const v of schema.enum) {
2195
+ const l = oaLiteral(v);
2196
+ if (lits.indexOf(l) === -1) lits.push(l);
2197
+ }
2198
+ return withNull(lits.join(' | '));
2199
+ }
2200
+ const comp = (list, sep) => {
2201
+ const parts = [];
2202
+ for (const x of list) {
2203
+ const t = oaTs(m, x, ind, d + 1);
2204
+ if (parts.indexOf(t) === -1) parts.push(t);
2205
+ }
2206
+ return parts.length === 1 ? parts[0] : parts.map(oaWrap).join(sep);
2207
+ };
2208
+ const hasProps = jyIsPlainObject(schema.properties) || oaOwn(schema, 'additionalProperties');
2209
+ if (Array.isArray(schema.allOf) && schema.allOf.length) {
2210
+ const parts = schema.allOf.map((x) => oaWrap(oaTs(m, x, ind, d + 1)));
2211
+ if (hasProps) parts.push(oaObject(m, schema, ind, d + 1));
2212
+ return withNull(parts.length === 1 ? parts[0] : parts.join(' & '));
2213
+ }
2214
+ const alt = Array.isArray(schema.oneOf) && schema.oneOf.length ? schema.oneOf : Array.isArray(schema.anyOf) && schema.anyOf.length ? schema.anyOf : null;
2215
+ if (alt) {
2216
+ const u = comp(alt, ' | ');
2217
+ return withNull(hasProps ? `${oaWrap(u)} & ${oaObject(m, schema, ind, d + 1)}` : u);
2218
+ }
2219
+ if (types.length === 0) return nullable && (schema.type === 'null' || Array.isArray(schema.type)) ? 'null' : 'unknown';
2220
+ const out = types.map((t) => {
2221
+ if (t === 'string') return schema.format === 'binary' ? 'Blob' : 'string';
2222
+ if (t === 'integer' || t === 'number') return 'number';
2223
+ if (t === 'boolean') return 'boolean';
2224
+ if (t === 'array') {
2225
+ if (Array.isArray(schema.prefixItems)) return `[${schema.prefixItems.map((x) => oaTs(m, x, ind, d + 1)).join(', ')}]`;
2226
+ return `${oaWrap(oaTs(m, schema.items, ind, d + 1))}[]`;
2227
+ }
2228
+ if (t === 'object') return oaObject(m, schema, ind, d + 1);
2229
+ return 'unknown';
2230
+ });
2231
+ const uniq = out.filter((t, k) => out.indexOf(t) === k);
2232
+ return withNull(uniq.join(' | '));
2233
+ }
2234
+
2235
+ /** object の型リテラル({ … })。中身が無ければ Record */
2236
+ function oaObject(m, schema, ind, depth) {
2237
+ const props = jyIsPlainObject(schema.properties) ? schema.properties : null;
2238
+ const addl = schema.additionalProperties;
2239
+ const keys = props ? Object.keys(props) : [];
2240
+ if (keys.length === 0) {
2241
+ if (addl === false) return 'Record<string, never>';
2242
+ if (jyIsPlainObject(addl) && Object.keys(addl).length) return `Record<string, ${oaTs(m, addl, ind, depth + 1)}>`;
2243
+ return 'Record<string, unknown>';
2244
+ }
2245
+ return `{\n${oaObjectBody(m, schema, ind + ' ', depth)}${ind}}`;
2246
+ }
2247
+
2248
+ /** object の中身の行(interface の本体にも使う) */
2249
+ function oaObjectBody(m, schema, ind, depth) {
2250
+ const props = jyIsPlainObject(schema.properties) ? schema.properties : {};
2251
+ const required = Array.isArray(schema.required) ? schema.required : [];
2252
+ let out = '';
2253
+ for (const k of Object.keys(props)) {
2254
+ m.tick();
2255
+ const ps = props[k];
2256
+ // $ref だけのプロパティは参照先の型に説明があるので、ここでは自分の横に書かれた説明だけを付ける
2257
+ const doc = oaDoc(jyIsPlainObject(ps) ? ps : {}, ind);
2258
+ const shown = jyIsPlainObject(ps) && typeof ps.$ref === 'string' ? Object.assign({}, m.deref(ps) || {}, ps) : ps;
2259
+ const ro = jyIsPlainObject(shown) && shown.readOnly === true ? 'readonly ' : '';
2260
+ const opt = required.indexOf(k) === -1 ? '?' : '';
2261
+ out += `${doc}${ind}${ro}${oaPropKey(k)}${opt}: ${oaTs(m, ps, ind, depth + 1)};\n`;
2262
+ if (out.length > OA_MAX_TYPE_CHARS) oaTooLarge();
2263
+ }
2264
+ const addl = schema.additionalProperties;
2265
+ if (addl === true || jyIsPlainObject(addl)) out += `${ind}[key: string]: unknown;\n`;
2266
+ return out;
2267
+ }
2268
+
2269
+ /** 名前付きスキーマ1件の宣言(interface か type) */
2270
+ function oaDeclare(m, entry) {
2271
+ const s = entry.schema;
2272
+ const doc = oaDoc(jyIsPlainObject(s) ? s : {}, '');
2273
+ if (jyIsPlainObject(s) && typeof s.$ref !== 'string') {
2274
+ const { types, nullable } = oaTypes(s);
2275
+ const plainObject = types.length === 1 && types[0] === 'object' && !nullable && jyIsPlainObject(s.properties) && Object.keys(s.properties).length &&
2276
+ !s.allOf && !s.oneOf && !s.anyOf && !s.enum && !oaOwn(s, 'const');
2277
+ if (plainObject) return `${doc}export interface ${entry.ts} {\n${oaObjectBody(m, s, ' ', 0)}}\n`;
2278
+ }
2279
+ return `${doc}export type ${entry.ts} = ${oaTs(m, s, '', 0)};\n`;
2280
+ }
2281
+
2282
+ /** 操作の型名の土台(operationId があればそれ、無ければ メソッド+パス) */
2283
+ function oaOpBase(op) {
2284
+ if (op.operationId) return oaPascal(op.operationId);
2285
+ const segs = op.path.split('/').filter(Boolean).map((seg) => {
2286
+ const m = /^\{(.+)\}$/.exec(seg);
2287
+ return m ? 'By' + oaPascal(m[1]) : oaPascal(seg);
2288
+ });
2289
+ return oaPascal(op.method) + (segs.join('') || 'Root');
2290
+ }
2291
+
2292
+ /** content の中から型に使う1件(JSON系を優先) */
2293
+ function oaPickContent(contents) {
2294
+ if (!contents || contents.length === 0) return null;
2295
+ return contents.find((c) => /json/i.test(c.type)) || contents[0];
2296
+ }
2297
+
2298
+ /**
2299
+ * TypeScript の型定義ファイル(.ts)を作る。
2300
+ * @param {object} m oaModel の返り値
2301
+ * @param {object} [opts]
2302
+ * @param {boolean} [opts.operations=true] エンドポイントごとの引数・レスポンスの型も出す
2303
+ */
2304
+ function oaTypeScript(m, opts) {
2305
+ const o = opts || {};
2306
+ const withOps = o.operations !== false;
2307
+ const head = [
2308
+ '/**',
2309
+ ` * ${(m.title || 'API').replace(/\*\//g, '*\\/')}${m.version ? ` v${m.version.replace(/\*\//g, '*\\/')}` : ''}`,
2310
+ ` * Generated from ${m.v2 ? 'Swagger' : 'OpenAPI'} ${m.v2 ? oaStr(m.spec.swagger) : oaStr(m.spec.openapi)} by First CH Tools (https://tools.first-ch.com/openapi-doc-gen/).`,
2311
+ ' */',
2312
+ '',
2313
+ ];
2314
+ const blocks = [];
2315
+ for (const e of m.schemas) blocks.push(oaDeclare(m, e));
2316
+ if (withOps && m.operations.length) {
2317
+ const used = new Set(m.schemas.map((e) => e.ts));
2318
+ for (const op of m.operations) {
2319
+ let base = oaOpBase(op);
2320
+ const want = (b) => ['Params', 'RequestBody', 'Response'].some((suf) => used.has(b + suf));
2321
+ let k = 2;
2322
+ const b0 = base;
2323
+ while (want(base)) base = b0 + k++;
2324
+ const title = `${op.method.toUpperCase()} ${op.path}${op.summary ? ` — ${op.summary}` : ''}`.replace(/\*\//g, '*\\/').replace(/\s*\n\s*/g, ' ');
2325
+ const parts = [];
2326
+ const groups = ['path', 'query', 'header', 'cookie'];
2327
+ const lines = [];
2328
+ for (const g of groups) {
2329
+ const ps = op.params.filter((p) => p.in === g);
2330
+ if (!ps.length) continue;
2331
+ const req = ps.some((p) => p.required);
2332
+ let inner = '';
2333
+ for (const p of ps) {
2334
+ const sch = m.deref(p.schema);
2335
+ inner += oaDoc(Object.assign({}, jyIsPlainObject(sch) ? sch : {}, { description: p.description, deprecated: p.deprecated }), ' ');
2336
+ inner += ` ${oaPropKey(p.name)}${p.required ? '' : '?'}: ${oaTs(m, p.schema, ' ', 0)};\n`;
2337
+ }
2338
+ lines.push(` ${g}${req ? '' : '?'}: {\n${inner} };\n`);
2339
+ }
2340
+ if (lines.length) {
2341
+ parts.push(`export interface ${base}Params {\n${lines.join('')}}\n`);
2342
+ used.add(base + 'Params');
2343
+ }
2344
+ const body = op.body ? oaPickContent(op.body.contents) : null;
2345
+ if (body) {
2346
+ parts.push(`/** ${body.type}${op.body.required ? '' : ' (optional)'} */\nexport type ${base}RequestBody = ${oaTs(m, body.schema, '', 0)};\n`);
2347
+ used.add(base + 'RequestBody');
2348
+ }
2349
+ const ok = op.responses.filter((r) => /^2/.test(r.status));
2350
+ if (ok.length) {
2351
+ const ts = [];
2352
+ for (const r of ok) {
2353
+ const c = oaPickContent(r.contents);
2354
+ const t = c ? oaTs(m, c.schema, '', 0) : 'void';
2355
+ if (ts.indexOf(t) === -1) ts.push(t);
2356
+ }
2357
+ parts.push(`/** ${ok.map((r) => r.status).join(', ')} */\nexport type ${base}Response = ${ts.length === 1 ? ts[0] : ts.map(oaWrap).join(' | ')};\n`);
2358
+ used.add(base + 'Response');
2359
+ }
2360
+ if (parts.length) blocks.push(`/* ${title} */\n` + parts.join('\n'));
2361
+ }
2362
+ }
2363
+ if (blocks.length === 0) blocks.push('export {};\n');
2364
+ return head.join('\n') + blocks.join('\n');
2365
+ }
2366
+
2367
+ /* ---------------------------------------------------------------------------
2368
+ * Markdown ドキュメント
2369
+ * ------------------------------------------------------------------------- */
2370
+
2371
+ const OA_MD_TEXT = {
2372
+ ja: {
2373
+ docTitle: (t) => `${t} API リファレンス`,
2374
+ generated: (k, v) => `${k} ${v} の仕様書から生成`,
2375
+ apiVersion: 'APIのバージョン',
2376
+ servers: 'ベースURL',
2377
+ toc: 'エンドポイント一覧',
2378
+ method: 'メソッド',
2379
+ path: 'パス',
2380
+ summary: '概要',
2381
+ auth: '認証',
2382
+ authName: '名前',
2383
+ authType: '方式',
2384
+ authDetail: '詳細',
2385
+ endpoints: 'エンドポイント',
2386
+ other: 'その他',
2387
+ opId: 'operationId',
2388
+ deprecated: '非推奨',
2389
+ deprecatedNote: '> **非推奨**: このエンドポイントは廃止予定です。',
2390
+ authNeeded: '必要な認証',
2391
+ noAuth: 'なし',
2392
+ params: 'パラメータ',
2393
+ name: '名前',
2394
+ where: '場所',
2395
+ type: '型',
2396
+ required: '必須',
2397
+ desc: '説明',
2398
+ yes: '○',
2399
+ no: '',
2400
+ inLabel: { path: 'パス', query: 'クエリ', header: 'ヘッダー', cookie: 'Cookie' },
2401
+ body: 'リクエストボディ',
2402
+ bodyRequired: '(必須)',
2403
+ responses: 'レスポンス',
2404
+ status: 'ステータス',
2405
+ contentType: 'Content-Type',
2406
+ example: '例',
2407
+ autoExample: '(スキーマから自動生成)',
2408
+ requestExample: 'リクエストの例',
2409
+ responseExample: (s) => `${s} の例`,
2410
+ headers: 'レスポンスヘッダー',
2411
+ schemas: 'スキーマ',
2412
+ property: 'プロパティ',
2413
+ values: (v) => `値: ${v}`,
2414
+ defaultVal: (v) => `既定値: ${v}`,
2415
+ schemaIs: (c) => `型: ${c}`,
2416
+ none: '(なし)',
2417
+ noEndpoints: '(エンドポイントはありません)',
2418
+ readOnly: '読み取り専用',
2419
+ writeOnly: '書き込み専用',
2420
+ },
2421
+ en: {
2422
+ docTitle: (t) => `${t} API Reference`,
2423
+ generated: (k, v) => `Generated from ${/^[AEIOU]/.test(k) ? 'an' : 'a'} ${k} ${v} specification`,
2424
+ apiVersion: 'API version',
2425
+ servers: 'Base URL',
2426
+ toc: 'Endpoints',
2427
+ method: 'Method',
2428
+ path: 'Path',
2429
+ summary: 'Summary',
2430
+ auth: 'Authentication',
2431
+ authName: 'Name',
2432
+ authType: 'Type',
2433
+ authDetail: 'Details',
2434
+ endpoints: 'Endpoints',
2435
+ other: 'Other',
2436
+ opId: 'operationId',
2437
+ deprecated: 'Deprecated',
2438
+ deprecatedNote: '> **Deprecated**: this endpoint is scheduled for removal.',
2439
+ authNeeded: 'Authentication',
2440
+ noAuth: 'None',
2441
+ params: 'Parameters',
2442
+ name: 'Name',
2443
+ where: 'In',
2444
+ type: 'Type',
2445
+ required: 'Required',
2446
+ desc: 'Description',
2447
+ yes: 'Yes',
2448
+ no: '',
2449
+ inLabel: { path: 'path', query: 'query', header: 'header', cookie: 'cookie' },
2450
+ body: 'Request body',
2451
+ bodyRequired: ' (required)',
2452
+ responses: 'Responses',
2453
+ status: 'Status',
2454
+ contentType: 'Content-Type',
2455
+ example: 'Example',
2456
+ autoExample: ' (generated from the schema)',
2457
+ requestExample: 'Example request',
2458
+ responseExample: (s) => `Example ${s}`,
2459
+ headers: 'Response headers',
2460
+ schemas: 'Schemas',
2461
+ property: 'Property',
2462
+ values: (v) => `Values: ${v}`,
2463
+ defaultVal: (v) => `Default: ${v}`,
2464
+ schemaIs: (c) => `Type: ${c}`,
2465
+ none: '(none)',
2466
+ noEndpoints: '(no endpoints)',
2467
+ readOnly: 'read-only',
2468
+ writeOnly: 'write-only',
2469
+ },
2470
+ };
2471
+
2472
+ /** Markdown の表のセル(| と改行を逃がす) */
2473
+ function oaCell(s) {
2474
+ return String(s).replace(/\r\n?/g, '\n').trim().replace(/\|/g, '\\|').replace(/\n+/g, '<br>');
2475
+ }
2476
+ /** インラインコード(中にバッククォートがあれば囲みを長くする) */
2477
+ function oaCode(s) {
2478
+ const str = String(s);
2479
+ const runs = str.match(/`+/g) || [];
2480
+ const n = runs.reduce((a, r) => Math.max(a, r.length), 0) + 1;
2481
+ const fence = '`'.repeat(n);
2482
+ const pad = /^`|`$/.test(str) ? ' ' : '';
2483
+ return `${fence}${pad}${str}${pad}${fence}`;
2484
+ }
2485
+ /** 表のセルに置くインラインコード。GFM はコードの中の | でもセルを割るので \| にする */
2486
+ function oaTc(s) {
2487
+ return oaCode(String(s).replace(/\s*[\r\n]+\s*/g, ' ')).replace(/\|/g, '\\|');
2488
+ }
2489
+ /** コードブロック(中の ``` より長い囲みにする) */
2490
+ function oaFence(body, lang) {
2491
+ const runs = String(body).match(/`{3,}/g) || [];
2492
+ const n = Math.max(3, runs.reduce((a, r) => Math.max(a, r.length + 1), 0));
2493
+ const f = '`'.repeat(n);
2494
+ return `${f}${lang || ''}\n${body}\n${f}`;
2495
+ }
2496
+
2497
+ /** schema の説明列(説明・列挙値・既定値・読み取り専用) */
2498
+ function oaSchemaDesc(m, schema, t, extra) {
2499
+ const s = jyIsPlainObject(schema) && typeof schema.$ref === 'string' ? Object.assign({}, m.deref(schema) || {}, schema) : schema;
2500
+ const bits = [];
2501
+ if (extra) bits.push(extra);
2502
+ if (jyIsPlainObject(s)) {
2503
+ if (oaStr(s.description).trim()) bits.push(oaStr(s.description).trim());
2504
+ if (Array.isArray(s.enum) && s.enum.length) bits.push(t.values(s.enum.slice(0, 30).map((v) => oaCode(JSON.stringify(v))).join(', ') + (s.enum.length > 30 ? ' …' : '')));
2505
+ if (oaOwn(s, 'default') && (s.default === null || typeof s.default !== 'object')) bits.push(t.defaultVal(oaCode(JSON.stringify(s.default))));
2506
+ if (s.readOnly === true) bits.push(t.readOnly);
2507
+ if (s.writeOnly === true) bits.push(t.writeOnly);
2508
+ if (s.deprecated === true) bits.push(t.deprecated);
2509
+ }
2510
+ return bits.join(' / ');
2511
+ }
2512
+
2513
+ /** object schema のプロパティを表の行に($ref の先も1段だけ開く) */
2514
+ function oaPropRows(m, schema, t) {
2515
+ const s = m.deref(schema);
2516
+ if (!jyIsPlainObject(s)) return [];
2517
+ // allOf は並び順どおりに重ね、最後に自分の properties を載せる
2518
+ const props = {};
2519
+ let required = [];
2520
+ for (const part of (Array.isArray(s.allOf) ? s.allOf.map((x) => m.deref(x)) : []).concat([s])) {
2521
+ if (!jyIsPlainObject(part)) continue;
2522
+ if (jyIsPlainObject(part.properties)) Object.assign(props, part.properties);
2523
+ if (Array.isArray(part.required)) required = required.concat(part.required);
2524
+ }
2525
+ return Object.keys(props).map((k) => {
2526
+ m.tick();
2527
+ return `| ${oaTc(k)} | ${oaTc(oaTypeLabel(m, props[k]))} | ${required.indexOf(k) !== -1 ? t.yes : t.no} | ${oaCell(oaSchemaDesc(m, props[k], t))} |`;
2528
+ });
2529
+ }
2530
+
2531
+ /**
2532
+ * 日本語(または英語)の Markdown ドキュメントを作る。
2533
+ * @param {object} m oaModel の返り値
2534
+ * @param {object} [opts]
2535
+ * @param {'ja'|'en'} [opts.lang='ja']
2536
+ * @param {boolean} [opts.examples=true] 例が書かれていないレスポンスにスキーマから例を作る
2537
+ * @param {boolean} [opts.schemas=true] スキーマの節を付ける
2538
+ */
2539
+ function oaMarkdown(m, opts) {
2540
+ const o = opts || {};
2541
+ const lang = o.lang === 'en' ? 'en' : 'ja';
2542
+ const t = OA_MD_TEXT[lang];
2543
+ const genExamples = o.examples !== false;
2544
+ const out = [];
2545
+ const title = (m.title || 'API').replace(/\s+/g, ' ').trim();
2546
+ out.push(`# ${t.docTitle(title)}`, '');
2547
+ const meta = [];
2548
+ if (m.version) meta.push(`${t.apiVersion}: ${oaCode(m.version)}`);
2549
+ meta.push(t.generated(m.v2 ? 'Swagger' : 'OpenAPI', m.v2 ? oaStr(m.spec.swagger) : oaStr(m.spec.openapi)));
2550
+ out.push(meta.join(' / '), '');
2551
+ if (m.description.trim()) out.push(m.description.trim(), '');
2552
+ if (m.servers.length) {
2553
+ out.push(`## ${t.servers}`, '');
2554
+ for (const s of m.servers) out.push(`- ${oaCode(s.url)}${s.description ? ` — ${s.description.replace(/\s*\n\s*/g, ' ')}` : ''}`);
2555
+ out.push('');
2556
+ }
2557
+
2558
+ out.push(`## ${t.toc}`, '');
2559
+ if (m.operations.length) {
2560
+ out.push(`| ${t.method} | ${t.path} | ${t.summary} |`, '| --- | --- | --- |');
2561
+ for (const op of m.operations) {
2562
+ out.push(`| ${op.method.toUpperCase()} | ${oaTc(op.path)} | ${oaCell((op.summary || op.operationId || '') + (op.deprecated ? `(${t.deprecated})` : ''))} |`);
2563
+ }
2564
+ } else {
2565
+ out.push(t.noEndpoints);
2566
+ }
2567
+ out.push('');
2568
+
2569
+ if (m.security.length) {
2570
+ out.push(`## ${t.auth}`, '');
2571
+ out.push(`| ${t.authName} | ${t.authType} | ${t.authDetail} |`, '| --- | --- | --- |');
2572
+ for (const s of m.security) {
2573
+ const detail = [];
2574
+ if (s.type === 'apiKey') detail.push(`${s.in}: ${oaCode(s.paramName)}`);
2575
+ if (s.scheme) detail.push(`scheme: ${s.scheme}`);
2576
+ if (s.bearerFormat) detail.push(`bearerFormat: ${s.bearerFormat}`);
2577
+ if (s.flow) detail.push(`flow: ${s.flow}`);
2578
+ if (s.openIdConnectUrl) detail.push(s.openIdConnectUrl);
2579
+ if (s.description) detail.push(s.description);
2580
+ out.push(`| ${oaTc(s.name)} | ${oaCell(s.type)} | ${oaCell(detail.join(' / '))} |`);
2581
+ }
2582
+ out.push('');
2583
+ }
2584
+
2585
+ // タグごとにまとめる(タグが1つも無ければまとめない)
2586
+ const anyTag = m.operations.some((op) => op.tags.length);
2587
+ const groups = [];
2588
+ if (anyTag) {
2589
+ for (const tag of m.tags) {
2590
+ const ops = m.operations.filter((op) => op.tags[0] === tag.name);
2591
+ if (ops.length) groups.push({ name: tag.name, description: tag.description, ops });
2592
+ }
2593
+ const rest = m.operations.filter((op) => op.tags.length === 0);
2594
+ if (rest.length) groups.push({ name: t.other, description: '', ops: rest });
2595
+ } else if (m.operations.length) {
2596
+ groups.push({ name: null, ops: m.operations });
2597
+ }
2598
+ if (groups.length) out.push(`## ${t.endpoints}`, '');
2599
+ const h = anyTag ? '####' : '###';
2600
+ for (const g of groups) {
2601
+ if (g.name !== null) {
2602
+ out.push(`### ${g.name}`, '');
2603
+ if (g.description && g.description.trim()) out.push(g.description.trim(), '');
2604
+ }
2605
+ for (const op of g.ops) {
2606
+ m.tick();
2607
+ out.push(`${h} ${op.method.toUpperCase()} ${op.path}${op.summary ? ` — ${op.summary.replace(/\s*\n\s*/g, ' ')}` : ''}`, '');
2608
+ if (op.deprecated) out.push(t.deprecatedNote, '');
2609
+ if (op.description.trim()) out.push(op.description.trim(), '');
2610
+ const facts = [];
2611
+ if (op.operationId) facts.push(`- ${t.opId}: ${oaCode(op.operationId)}`);
2612
+ if (op.security !== null && m.security.length) facts.push(`- ${t.authNeeded}: ${op.security.length ? op.security.map(oaCode).join(', ') : t.noAuth}`);
2613
+ if (facts.length) out.push(...facts, '');
2614
+
2615
+ if (op.params.length) {
2616
+ out.push(`**${t.params}**`, '');
2617
+ out.push(`| ${t.name} | ${t.where} | ${t.type} | ${t.required} | ${t.desc} |`, '| --- | --- | --- | --- | --- |');
2618
+ for (const p of op.params) {
2619
+ const extra = p.example.has ? `${t.example}: ${oaCode(JSON.stringify(p.example.value))}` : '';
2620
+ const desc = [oaSchemaDesc(m, Object.assign({}, jyIsPlainObject(p.schema) ? p.schema : {}, p.description ? { description: p.description } : {}, p.deprecated ? { deprecated: true } : {}), t), extra].filter(Boolean).join(' / ');
2621
+ out.push(`| ${oaTc(p.name)} | ${t.inLabel[p.in] || oaCell(p.in)} | ${oaTc(oaTypeLabel(m, p.schema))} | ${p.required ? t.yes : t.no} | ${oaCell(desc)} |`);
2622
+ }
2623
+ out.push('');
2624
+ }
2625
+
2626
+ if (op.body) {
2627
+ out.push(`**${t.body}**${op.body.required ? t.bodyRequired : ''}`, '');
2628
+ if (op.body.description.trim()) out.push(op.body.description.trim(), '');
2629
+ for (const c of op.body.contents) {
2630
+ out.push(`- ${t.contentType}: ${oaCode(c.type)} / ${t.schemaIs(oaCode(oaTypeLabel(m, c.schema)))}`);
2631
+ }
2632
+ out.push('');
2633
+ const main = oaPickContent(op.body.contents);
2634
+ if (main) {
2635
+ const rows = oaPropRows(m, main.schema, t);
2636
+ if (rows.length) out.push(`| ${t.property} | ${t.type} | ${t.required} | ${t.desc} |`, '| --- | --- | --- | --- |', ...rows, '');
2637
+ const ex = main.example.has ? main.example.value : genExamples && main.schema ? oaSample(m, main.schema) : undefined;
2638
+ if (ex !== undefined && ex !== null) {
2639
+ out.push(`${t.requestExample}${main.example.has ? '' : t.autoExample}:`, '');
2640
+ out.push(oaFence(typeof ex === 'string' && !/json/i.test(main.type) ? ex : oaJson(ex), typeof ex === 'string' && !/json/i.test(main.type) ? '' : 'json'), '');
2641
+ }
2642
+ }
2643
+ }
2644
+
2645
+ if (op.responses.length) {
2646
+ out.push(`**${t.responses}**`, '');
2647
+ out.push(`| ${t.status} | ${t.desc} | ${t.contentType} | ${t.type} |`, '| --- | --- | --- | --- |');
2648
+ for (const r of op.responses) {
2649
+ const cs = r.contents.length ? r.contents : [null];
2650
+ cs.forEach((c, k) => {
2651
+ out.push(`| ${k === 0 ? oaTc(r.status) : ''} | ${k === 0 ? oaCell(r.description) : ''} | ${c ? oaTc(c.type) : ''} | ${c && c.schema ? oaTc(oaTypeLabel(m, c.schema)) : ''} |`);
2652
+ });
2653
+ }
2654
+ out.push('');
2655
+ for (const r of op.responses) {
2656
+ if (r.headers.length) {
2657
+ out.push(`${t.headers}(${r.status}):`, '');
2658
+ for (const hd of r.headers) out.push(`- ${oaCode(hd.name)}${hd.schema ? ` (${oaTypeLabel(m, hd.schema)})` : ''}${hd.description ? ` — ${hd.description.replace(/\s*\n\s*/g, ' ')}` : ''}`);
2659
+ out.push('');
2660
+ }
2661
+ const c = oaPickContent(r.contents);
2662
+ if (!c) continue;
2663
+ const ex = c.example.has ? c.example.value : genExamples && c.schema ? oaSample(m, c.schema) : undefined;
2664
+ if (ex === undefined || ex === null) continue;
2665
+ const raw = typeof ex === 'string' && !/json/i.test(c.type);
2666
+ out.push(`${t.responseExample(r.status)}${c.example.has ? '' : t.autoExample}:`, '');
2667
+ out.push(oaFence(raw ? ex : oaJson(ex), raw ? '' : 'json'), '');
2668
+ }
2669
+ }
2670
+ }
2671
+ }
2672
+
2673
+ if (o.schemas !== false && m.schemas.length) {
2674
+ out.push(`## ${t.schemas}`, '');
2675
+ for (const e of m.schemas) {
2676
+ m.tick();
2677
+ out.push(`### ${e.name}`, '');
2678
+ const s = m.deref(e.schema);
2679
+ if (jyIsPlainObject(s) && oaStr(s.description).trim()) out.push(oaStr(s.description).trim(), '');
2680
+ const rows = oaPropRows(m, e.schema, t);
2681
+ if (rows.length) {
2682
+ out.push(`| ${t.property} | ${t.type} | ${t.required} | ${t.desc} |`, '| --- | --- | --- | --- |', ...rows, '');
2683
+ } else {
2684
+ const extra = oaSchemaDesc(m, Object.assign({}, jyIsPlainObject(s) ? s : {}, { description: '' }), t);
2685
+ out.push(t.schemaIs(oaCode(oaTypeLabel(m, e.schema, 1))) + (extra ? ` / ${extra}` : ''), '');
2686
+ }
2687
+ }
2688
+ }
2689
+ return out.join('\n').replace(/\n{3,}/g, '\n\n').replace(/\s+$/, '') + '\n';
2690
+ }
2691
+
2692
+ /**
2693
+ * 入口: 仕様の文字列から Markdown と TypeScript をまとめて作る。
2694
+ * @param {object} opts
2695
+ * @param {string} opts.text OpenAPI / Swagger の JSON か YAML
2696
+ * @param {'ja'|'en'} [opts.lang='ja'] ドキュメントの言語
2697
+ * @param {boolean} [opts.examples=true]
2698
+ * @param {boolean} [opts.operations=true]
2699
+ */
2700
+ function oaGenerate(opts) {
2701
+ const o = opts || {};
2702
+ const parsed = oaParse(o.text);
2703
+ if (!parsed.ok) return parsed;
2704
+ try {
2705
+ const m = oaModel(parsed.spec, parsed.kind);
2706
+ const markdown = oaMarkdown(m, o);
2707
+ const typescript = oaTypeScript(m, o);
2708
+ const notes = parsed.notes.concat(m.notes.list);
2709
+ return {
2710
+ ok: true,
2711
+ kind: parsed.kind,
2712
+ format: parsed.format,
2713
+ specVersion: parsed.version,
2714
+ title: m.title,
2715
+ version: m.version,
2716
+ endpoints: m.operations.length,
2717
+ schemas: m.schemas.length,
2718
+ markdown,
2719
+ typescript,
2720
+ notes,
2721
+ };
2722
+ } catch (e) {
2723
+ if (e && e.oa) return { ok: false, error: { code: e.oa.code, line: 1, col: 1 }, notes: [] };
2724
+ if (e instanceof RangeError) return { ok: false, error: { code: 'OA_TOO_LARGE', line: 1, col: 1 }, notes: [] };
2725
+ throw e;
2726
+ }
2727
+ }
2728
+
2729
+ /** ダウンロードのファイル名の土台(タイトルの文字と数字。無ければ openapi) */
2730
+ function oaFileBase(title) {
2731
+ const s = String(title || '').normalize('NFKC').toLowerCase().replace(/[^\p{L}\p{N}]+/gu, '-').replace(/^-+|-+$/g, '').slice(0, 60);
2732
+ return s || 'openapi';
2733
+ }
2734
+
2735
+
2736
+ /* ==================== ここまで site/openapi-doc-gen/core.js の写し ==================== */
2737
+
2738
+ /* ---------------------------------------------------------------------------
2739
+ * MCPの入口
2740
+ * 文言は site/openapi-doc-gen/app.js の ERR_JA / ERR_EN / NOTE_JA / NOTE_EN と同じ
2741
+ * ------------------------------------------------------------------------- */
2742
+
2743
+ const ERR_JA = {
2744
+ EMPTY_INPUT: () => '入力が空です。',
2745
+ TOO_DEEP: () => '入れ子が深すぎます(200段まで)。',
2746
+ JSON_UNEXPECTED_END: () => '入力が途中で終わっています。閉じ括弧が足りていないか確認してください。',
2747
+ JSON_TRAILING_DATA: (e) => `JSONの値の後ろに余分な文字があります(${e.found})。JSONに書けるのは1つの値だけです。`,
2748
+ JSON_VALUE_EXPECTED: (e) => `値が必要な位置に ${e.found} があります。`,
2749
+ JSON_KEY_EXPECTED: (e) => `キーが必要な位置に ${e.found} があります。キーは "…" で囲みます。`,
2750
+ JSON_COLON_EXPECTED: (e) => `キーの後ろに : が必要です(見つかったのは ${e.found})。`,
2751
+ JSON_COMMA_EXPECTED: (e) => `区切りの , か閉じ括弧が必要です(見つかったのは ${e.found})。`,
2752
+ JSON_UNTERMINATED_STRING: (e) => `文字列が ${e.found} で閉じられていません。`,
2753
+ JSON_UNTERMINATED_COMMENT: () => 'コメント /* が */ で閉じられていません。',
2754
+ JSON_BAD_ESCAPE: (e) => `文字列の中で使えないエスケープです(${e.found})。`,
2755
+ JSON_BAD_TOKEN: (e) => `JSONの値として読めません(${e.found})。文字列なら "…" で囲んでください。`,
2756
+ JSON_RAW_CONTROL: (e) => `文字列の中に生の制御文字(${e.found})があります。\\n や \\t のように書いてください。`,
2757
+ TAB_INDENT: () => 'インデントにタブが使われています。YAMLはタブでの字下げを認めていないので、半角スペースに置き換えてください。',
2758
+ YAML_BAD_INDENT: (e) => `インデントが揃っていません(${e.found})。同じ階層の行は桁を合わせてください。`,
2759
+ YAML_SEQ_IN_MAP: () => 'キーが並ぶ位置に「- 」があります。マップとシーケンスは同じ階層に混ぜられません。',
2760
+ YAML_KEY_EXPECTED: (e) => `「キー: 値」の形になっていません(${e.found})。値の後ろには : が必要です。`,
2761
+ YAML_EXPLICIT_KEY: () => '「? キー」という明示キーの書き方には対応していません。通常の「キー: 値」に書き換えてください。',
2762
+ YAML_VALUE_THEN_BLOCK: (e) => `値を書いた行の下に、より深い行が続いています(${e.found})。上の行の値を消すか、この行のインデントを浅くしてください。`,
2763
+ YAML_NESTED_COLON: (e) => `1行に「キー: 値」が2つあります(${e.found})。値に「: 」を含めるなら "…" で囲んでください。`,
2764
+ YAML_SEQ_INLINE: (e) => `「- 」で始まる要素は次の行から書きます(${e.found})。1行に収めるなら [a, b] の形にしてください。`,
2765
+ YAML_UNTERMINATED_QUOTE: (e) => `引用符 ${e.found} が閉じられていません。`,
2766
+ YAML_BAD_ESCAPE: (e) => `"…" の中で使えないエスケープです(${e.found})。`,
2767
+ YAML_UNTERMINATED_FLOW: () => '[ または { が閉じられていません。',
2768
+ YAML_FLOW_SEP: (e) => `[ ] { } の中の区切りが不正です(${e.found})。要素は , で区切ります。`,
2769
+ YAML_FLOW_COLON: (e) => `{ } の中でキーの後ろに : がありません(${e.found})。`,
2770
+ YAML_ALIAS_NOT_FOUND: (e) => `参照先のアンカーがありません(${e.found})。*.js のように * で始まる値は "…" で囲んでください。`,
2771
+ YAML_ALIAS_TRAILING: (e) => `エイリアスの後ろに余分な文字があります(${e.found})。`,
2772
+ YAML_TRAILING_TEXT: (e) => `引用符や [ ] { } の後ろに余分な文字があります(${e.found})。`,
2773
+ YAML_BLOCK_HEADER: (e) => `ブロックスカラー(| や >)の指定が読めません(${e.found})。書けるのは chomping(- +)とインデント(1-9)だけです。`,
2774
+ YAML_BLOCK_INDENT: () => '| や > の中身のインデントが揃っていません。最初の行より浅い行は書けません。',
2775
+ YAML_BAD_TAG_VALUE: (e) => `タグの型に合わない値です(${e.found})。`,
2776
+ YAML_INTERNAL: () => '解析が進まなくなりました。書き方を単純にしてお試しください。',
2777
+ OA_NOT_OBJECT: () => '仕様書の一番上が「キー: 値」の並び(オブジェクト)になっていません。',
2778
+ OA_NOT_SPEC: () => '「openapi:」または「swagger:」のキーが見つかりません。OpenAPI 3.x / Swagger 2.0 の仕様書を入れてください。',
2779
+ OA_TOO_LARGE: () => '出力が大きくなりすぎるため生成を止めました(YAMLのエイリアスを何重にも入れ子にした仕様書など)。',
2780
+ };
2781
+
2782
+ const ERR_EN = {
2783
+ EMPTY_INPUT: () => 'The input is empty.',
2784
+ TOO_DEEP: () => 'Nesting is too deep (200 levels maximum).',
2785
+ JSON_UNEXPECTED_END: () => 'The input ends unexpectedly — check for a missing closing bracket.',
2786
+ JSON_TRAILING_DATA: (e) => `Extra characters after the JSON value (${e.found}). A JSON document holds exactly one value.`,
2787
+ JSON_VALUE_EXPECTED: (e) => `Expected a value here, found ${e.found}.`,
2788
+ JSON_KEY_EXPECTED: (e) => `Expected a key here, found ${e.found}. Keys must be wrapped in "…".`,
2789
+ JSON_COLON_EXPECTED: (e) => `Expected ":" after the key, found ${e.found}.`,
2790
+ JSON_COMMA_EXPECTED: (e) => `Expected "," or a closing bracket, found ${e.found}.`,
2791
+ JSON_UNTERMINATED_STRING: (e) => `This string is never closed with ${e.found}.`,
2792
+ JSON_UNTERMINATED_COMMENT: () => 'A /* comment is never closed with */.',
2793
+ JSON_BAD_ESCAPE: (e) => `Invalid escape sequence inside the string (${e.found}).`,
2794
+ JSON_BAD_TOKEN: (e) => `Not a valid JSON value (${e.found}). Wrap strings in "…".`,
2795
+ JSON_RAW_CONTROL: (e) => `A raw control character (${e.found}) is inside a string. Write it as \\n or \\t instead.`,
2796
+ TAB_INDENT: () => 'A tab is used for indentation. YAML forbids tabs for indenting — replace them with spaces.',
2797
+ YAML_BAD_INDENT: (e) => `Indentation does not line up (${e.found}). Keys at the same level need the same column.`,
2798
+ YAML_SEQ_IN_MAP: () => 'A "- " item appears where mapping keys are listed. A block cannot be both a mapping and a sequence.',
2799
+ YAML_KEY_EXPECTED: (e) => `This is not a "key: value" line (${e.found}). A colon is required after the key.`,
2800
+ YAML_EXPLICIT_KEY: () => 'Explicit "? key" notation is not supported. Rewrite it as a normal "key: value" line.',
2801
+ YAML_VALUE_THEN_BLOCK: (e) => `A more deeply indented line follows a line that already has a value (${e.found}). Remove the value above, or outdent this line.`,
2802
+ YAML_NESTED_COLON: (e) => `Two "key: value" pairs on one line (${e.found}). Wrap the value in "…" if it must contain ": ".`,
2803
+ YAML_SEQ_INLINE: (e) => `Sequence items start on the following line (${e.found}). To keep it on one line use the [a, b] form.`,
2804
+ YAML_UNTERMINATED_QUOTE: (e) => `This ${e.found} quote is never closed.`,
2805
+ YAML_BAD_ESCAPE: (e) => `Invalid escape sequence inside "…" (${e.found}).`,
2806
+ YAML_UNTERMINATED_FLOW: () => 'A "[" or "{" is never closed.',
2807
+ YAML_FLOW_SEP: (e) => `Invalid separator inside [ ] or { } (${e.found}). Items are separated by commas.`,
2808
+ YAML_FLOW_COLON: (e) => `Missing ":" after a key inside { } (${e.found}).`,
2809
+ YAML_ALIAS_NOT_FOUND: (e) => `No such anchor to reference (${e.found}). Values starting with "*", such as *.js, must be quoted.`,
2810
+ YAML_ALIAS_TRAILING: (e) => `Extra characters after the alias (${e.found}).`,
2811
+ YAML_TRAILING_TEXT: (e) => `Extra characters after the quoted value or [ ] { } (${e.found}).`,
2812
+ YAML_BLOCK_HEADER: (e) => `Cannot read the block scalar header (${e.found}). Only chomping (- +) and an indent digit (1-9) are allowed.`,
2813
+ YAML_BLOCK_INDENT: () => 'The body of a | or > block is not indented consistently — no line may be shallower than the first one.',
2814
+ YAML_BAD_TAG_VALUE: (e) => `The value does not match the tag type (${e.found}).`,
2815
+ YAML_INTERNAL: () => 'Parsing stopped making progress. Try simplifying the input.',
2816
+ OA_NOT_OBJECT: () => 'The top level of the specification is not a mapping of "key: value" pairs.',
2817
+ OA_NOT_SPEC: () => 'No "openapi:" or "swagger:" key was found. Please provide an OpenAPI 3.x or Swagger 2.0 specification.',
2818
+ OA_TOO_LARGE: () => 'Generation was stopped because the output grew too large (for example, YAML aliases nested many times over).',
2819
+ };
2820
+
2821
+ const listJa = (n) => n.items.join('、');
2822
+ const listEn = (n) => n.items.join(', ');
2823
+ const NOTE_JA = {
2824
+ OA_MULTI_DOC: () => 'YAMLに複数のドキュメント(---)があるため、最初の1つだけを読みました。',
2825
+ OA_EXTERNAL_REF: (n) => `別ファイル・URLを指す $ref は読みに行きません(${listJa(n)})。その部分の型は unknown になっています。1ファイルにまとめた仕様書を入れてください。`,
2826
+ OA_BROKEN_REF: (n) => `参照先が見つからない $ref があります(${listJa(n)})。その部分の型は unknown になっています。`,
2827
+ OA_DUP_OPERATION_ID: (n) => `operationId が重複しています(${listJa(n)})。型の名前は末尾に番号を付けて分けました。`,
2828
+ OA_NO_PATHS: () => 'paths にエンドポイントがありません。スキーマだけを出力しました。',
2829
+ OA_RENAMED_TYPE: (n) => `TypeScriptの予約語・組み込みの型と重なる、または重複する名前を付け替えました(${listJa(n)})。`,
2830
+ OA_VERSION_UNKNOWN: (n) => `想定していないバージョン(${listJa(n)})です。読める範囲で生成しました。`,
2831
+ OA_JSON_RELAXED: () => 'JSONとしては不正な書き方(コメント・末尾のカンマなど)がありましたが、読み取って続けました。',
2832
+ };
2833
+
2834
+ const NOTE_EN = {
2835
+ OA_MULTI_DOC: () => 'The YAML holds several documents (---); only the first one was read.',
2836
+ OA_EXTERNAL_REF: (n) => `$ref values pointing to other files or URLs are not fetched (${listEn(n)}). Those parts are typed as unknown — use a bundled, single-file specification.`,
2837
+ OA_BROKEN_REF: (n) => `Some $ref targets could not be found (${listEn(n)}). Those parts are typed as unknown.`,
2838
+ OA_DUP_OPERATION_ID: (n) => `Duplicate operationId (${listEn(n)}). The type names were told apart with a number suffix.`,
2839
+ OA_NO_PATHS: () => 'There are no endpoints under paths; only the schemas were written.',
2840
+ OA_RENAMED_TYPE: (n) => `Names that clash with TypeScript keywords or built-in types, or with each other, were renamed (${listEn(n)}).`,
2841
+ OA_VERSION_UNKNOWN: (n) => `Unexpected version (${listEn(n)}). Output was generated from what could be read.`,
2842
+ OA_JSON_RELAXED: () => 'The JSON contained things JSON does not allow (comments, trailing commas, …); they were accepted and reading continued.',
2843
+ };
2844
+
2845
+ const TEXT = { ja: { err: ERR_JA, note: NOTE_JA }, en: { err: ERR_EN, note: NOTE_EN } };
2846
+
2847
+ // site 側がファイルとして読み込む上限(20MB)と同じ
2848
+ const MAX_BYTES = 20 * 1024 * 1024;
2849
+
2850
+ export class OpenApiDocToolError extends Error {}
2851
+
2852
+ /**
2853
+ * OpenAPI 3.x / Swagger 2.0 の仕様書(YAML か JSON)から、日本語(または英語)の Markdown ドキュメントと
2854
+ * TypeScript の型定義を作る。
2855
+ *
2856
+ * @param {object} opts
2857
+ * @param {string} [opts.spec] 仕様書の本文(path と排他)
2858
+ * @param {string} [opts.path] 仕様書ファイルの絶対パス(UTF-8 として読む)
2859
+ * @param {'ja'|'en'} [opts.lang] ドキュメント・指摘・エラーの言語(既定 ja)
2860
+ * @param {boolean} [opts.examples] 例が書かれていないレスポンスにスキーマから例を作る(既定 true)
2861
+ * @param {boolean} [opts.operations] エンドポイントごとの引数・レスポンスの型も出す(既定 true)
2862
+ * @param {'both'|'markdown'|'typescript'} [opts.output] 返す(書き出す)もの(既定 both)
2863
+ * @param {string} [opts.outputDir] 書き出し先ディレクトリ(絶対パス)。<タイトル>.md / <タイトル>.ts を置き、本文は返さない
2864
+ * @param {boolean} [opts.overwrite]
2865
+ */
2866
+ export async function openApiDocGenerateTool(opts = {}) {
2867
+ const o = opts || {};
2868
+ const lang = o.lang === undefined ? 'ja' : o.lang;
2869
+ if (lang !== 'ja' && lang !== 'en') throw new OpenApiDocToolError(`lang は ja か en: ${o.lang}`);
2870
+ const output = o.output === undefined ? 'both' : o.output;
2871
+ if (['both', 'markdown', 'typescript'].indexOf(output) === -1) {
2872
+ throw new OpenApiDocToolError(`output は both / markdown / typescript のどれかです: ${o.output}`);
2873
+ }
2874
+ const hasSpec = typeof o.spec === 'string';
2875
+ const hasPath = typeof o.path === 'string' && o.path.trim() !== '';
2876
+ if (hasSpec === hasPath) throw new OpenApiDocToolError('spec か path のどちらか一方を指定してください');
2877
+ if (hasPath && !isAbsolute(o.path)) throw new OpenApiDocToolError('path は絶対パスで指定してください');
2878
+ if (o.outputDir !== undefined && (typeof o.outputDir !== 'string' || !isAbsolute(o.outputDir))) {
2879
+ throw new OpenApiDocToolError('outputDir は絶対パスで指定してください');
2880
+ }
2881
+
2882
+ let text;
2883
+ if (hasSpec) {
2884
+ text = o.spec;
2885
+ } else {
2886
+ const buf = await readFile(o.path);
2887
+ if (buf.length > MAX_BYTES) throw new OpenApiDocToolError(`${MAX_BYTES / 1024 / 1024}MBを超えるファイルは読み込みません: ${o.path}`);
2888
+ text = buf.toString('utf8');
2889
+ }
2890
+ if (Buffer.byteLength(text, 'utf8') > MAX_BYTES) throw new OpenApiDocToolError(`仕様書は ${MAX_BYTES / 1024 / 1024}MB まで`);
2891
+
2892
+ const T = TEXT[lang];
2893
+ let r;
2894
+ try {
2895
+ r = oaGenerate({ text, lang, examples: o.examples !== false, operations: o.operations !== false });
2896
+ } catch (e) {
2897
+ // site 側と同じく、想定外の例外(スタックの食い潰しなど)もエラーとして返す
2898
+ r = { ok: false, error: { code: e instanceof RangeError ? 'OA_TOO_LARGE' : 'YAML_INTERNAL', line: 1, col: 1 } };
2899
+ }
2900
+ if (!r.ok) {
2901
+ const e = r.error;
2902
+ const fn = T.err[e.code];
2903
+ const err = { code: e.code, message: fn ? fn(e) : e.code };
2904
+ if (r.excerpt) {
2905
+ err.line = e.line;
2906
+ err.col = e.col;
2907
+ err.excerpt = r.excerpt;
2908
+ }
2909
+ return { ok: false, error: err };
2910
+ }
2911
+
2912
+ const base = oaFileBase(r.title);
2913
+ const result = {
2914
+ ok: true,
2915
+ kind: r.kind,
2916
+ format: r.format,
2917
+ spec_version: r.specVersion,
2918
+ title: r.title,
2919
+ version: r.version,
2920
+ endpoints: r.endpoints,
2921
+ schemas: r.schemas,
2922
+ file_names: { markdown: `${base}.md`, typescript: `${base}.ts` },
2923
+ };
2924
+ if (output !== 'typescript') result.markdown = r.markdown;
2925
+ if (output !== 'markdown') result.typescript = r.typescript;
2926
+ result.notes = r.notes.map((n) => {
2927
+ const fn = T.note[n.code];
2928
+ const out = { code: n.code, level: n.level, count: n.count, message: fn ? fn(n) : n.code };
2929
+ if (n.items.length) out.items = n.items;
2930
+ return out;
2931
+ });
2932
+
2933
+ if (o.outputDir) {
2934
+ const written = {};
2935
+ if (output !== 'typescript') {
2936
+ written.markdown = join(o.outputDir, `${base}.md`);
2937
+ await writeOutput(written.markdown, r.markdown, { overwrite: o.overwrite });
2938
+ }
2939
+ if (output !== 'markdown') {
2940
+ written.typescript = join(o.outputDir, `${base}.ts`);
2941
+ await writeOutput(written.typescript, r.typescript, { overwrite: o.overwrite });
2942
+ }
2943
+ result.output = written;
2944
+ // ファイルに書けたなら本文は重複した重い情報でしかない
2945
+ delete result.markdown;
2946
+ delete result.typescript;
2947
+ }
2948
+ return result;
2949
+ }
2950
+
2951
+ export {
2952
+ jyParseJson, jyParseYaml, jyExcerpt,
2953
+ oaParse, oaModel, oaMarkdown, oaTypeScript, oaGenerate, oaFileBase, oaPascal, oaSample, oaTs, oaTypeLabel,
2954
+ };