-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathapp.js
More file actions
1300 lines (1138 loc) · 46.4 KB
/
Copy pathapp.js
File metadata and controls
1300 lines (1138 loc) · 46.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* Schema Doctor: Reducer Edition — app.js
* Static, client-side only. No backend required.
*/
// Global state
let originalEditor, reducedEditor, ajvInstance = null;
const HTTP_METHODS = new Set(['get','post','put','patch','delete','head','options','trace']);
// (near the top of app.js, after HTTP_METHODS)
const GENERIC_RESPONSES = {
"200": "OK",
"201": "Created",
"202": "Accepted",
"204": "No Content",
"400": "Bad Request",
"401": "Unauthorized",
"403": "Forbidden",
"404": "Not Found",
"409": "Conflict",
"429": "Too Many Requests",
"500": "Internal Server Error",
"503": "Service Unavailable"
};
// ---- operationId helpers ----
function camelize(parts) {
const safe = parts
.filter(Boolean)
.map(s => s.replace(/[{}]/g, '')) // drop {param} braces
.map(s => s.replace(/[^0-9A-Za-z]+/g, ' ')) // non-alnum -> space
.flatMap(s => s.trim().split(/\s+/));
if (!safe.length) return 'op';
const head = safe[0].toLowerCase();
const tail = safe.slice(1).map(w => w.charAt(0).toUpperCase() + w.slice(1).toLowerCase());
return head + tail.join('');
}
function makeOpId(pathKey, method) {
// e.g. /v1/users/{userId}/roles -> usersUserIdRoles
const tokens = String(pathKey).split('/').filter(Boolean);
const base = camelize(tokens);
// Prefix method for disambiguation (common pattern)
const m = method.toLowerCase();
const verb = ({get:'get', post:'create', put:'update', patch:'patch', delete:'delete'})[m] || m;
return verb + base.charAt(0).toUpperCase() + base.slice(1);
}
function ensureUniqueId(candidate, used) {
let id = candidate && candidate.trim() ? candidate.trim() : 'op';
// Avoid starting with a digit (some tools are picky)
if (/^\d/.test(id)) id = 'op_' + id;
// Collapse weird characters
id = id.replace(/[^A-Za-z0-9_.-]/g, '_');
if (!used.has(id)) { used.add(id); return id; }
let n = 2;
while (used.has(`${id}_${n}`)) n++;
const unique = `${id}_${n}`;
used.add(unique);
return unique;
}
(function initSplitter() {
const root = document.documentElement;
const layout = document.getElementById('app-layout');
const splitter = document.getElementById('splitter');
if (!layout || !splitter) return;
// Load previous width
const saved = localStorage.getItem('schemaDoctor.sidebarW');
if (saved) root.style.setProperty('--sidebar-w', saved);
let dragging = false;
const min = 260; // px
const maxClamp = () => Math.min(900, layout.clientWidth - 320);
function setWidth(px) {
const w = Math.max(min, Math.min(maxClamp(), px));
const val = `${w}px`;
root.style.setProperty('--sidebar-w', val);
localStorage.setItem('schemaDoctor.sidebarW', val);
}
splitter.addEventListener('pointerdown', (e) => {
dragging = true;
splitter.setPointerCapture(e.pointerId);
document.body.style.userSelect = 'none';
});
window.addEventListener('pointermove', (e) => {
if (!dragging) return;
const rect = layout.getBoundingClientRect();
setWidth(e.clientX - rect.left);
});
window.addEventListener('pointerup', () => {
if (!dragging) return;
dragging = false;
document.body.style.userSelect = '';
});
// Keyboard resize
splitter.addEventListener('keydown', (e) => {
const step = e.shiftKey ? 40 : 12;
const current = parseFloat(getComputedStyle(root).getPropertyValue('--sidebar-w')) || 360;
if (e.key === 'ArrowLeft') { setWidth(current - step); e.preventDefault(); }
if (e.key === 'ArrowRight') { setWidth(current + step); e.preventDefault(); }
});
})();
function responseComponentNameFor(code) {
const safe = String(code).replace(/[^0-9A-Za-z]+/g, '_');
return `Response_${safe}`;
}
let __filterDirty = false;
function updateFilterPendingUI() {
const enabled = !!document.getElementById('filter-enabled')?.checked;
const el = document.getElementById('filter-pending');
if (!el) return;
const show = enabled && __filterDirty;
el.classList.toggle('hidden', !show);
}
// ---- Keep payload schemas safely ----
function safeKeyFrom(path, method, operationId) {
const base = operationId && String(operationId).trim()
? operationId.trim()
: `${method}_${String(path).replace(/[^0-9A-Za-z]+/g, '_')}`;
return base.slice(0, 120);
}
function resolveComponentRef(spec, ref) {
if (typeof ref !== 'string' || !ref.startsWith('#/components/')) return null;
const parts = ref.replace(/^#\//, '').split('/');
let cur = spec;
for (const p of parts) {
if (!cur || typeof cur !== 'object') return null;
cur = cur[p];
}
return cur || null;
}
// Collect #/components/schemas/* refs from a JSON Schema
function collectSchemaRefs(schema, outSet = new Set(), seen = new Set()) {
if (!schema || typeof schema !== 'object') return outSet;
if (seen.has(schema)) return outSet;
seen.add(schema);
if (typeof schema.$ref === 'string') {
const m = schema.$ref.match(/^#\/components\/schemas\/([^\/]+)$/);
if (m) outSet.add(m[1]);
}
const recurseKeys = [
'allOf','oneOf','anyOf','not','if','then','else','items','additionalItems',
'properties','patternProperties','additionalProperties','unevaluatedProperties',
'prefixItems','contains','propertyNames','dependentSchemas'
];
for (const k of recurseKeys) {
const v = schema[k];
if (!v) continue;
if (Array.isArray(v)) v.forEach(x => collectSchemaRefs(x, outSet, seen));
else if (typeof v === 'object') {
if (k === 'properties' || k === 'patternProperties') {
for (const sub of Object.values(v)) collectSchemaRefs(sub, outSet, seen);
} else {
collectSchemaRefs(v, outSet, seen);
}
}
}
return outSet;
}
// Expand transitive schema deps and copy them over
function copyNeededSchemas(spec, out, neededSchemas) {
if (!spec?.components?.schemas || !neededSchemas?.size) return;
const src = spec.components.schemas;
const have = new Set();
let changed = true;
while (changed) {
changed = false;
for (const name of Array.from(neededSchemas)) {
if (have.has(name)) continue;
const s = src[name];
if (!s) continue;
if (!out.components.schemas) out.components.schemas = {};
out.components.schemas[name] = s; // shallow copy is ok
have.add(name);
// pull nested schema refs
const nested = collectSchemaRefs(s);
for (const n of nested) {
if (!neededSchemas.has(n)) {
neededSchemas.add(n);
changed = true;
}
}
}
}
}
function normalizeStatusCode(code) {
// Turn "2xx", "4XX", " 3 Xx " into "200", "400", "300"
const s = String(code).trim();
const m = s.match(/^([1-5])\s*[Xx]{2}$/);
return m ? `${m[1]}00` : s;
}
// Keep only JSON content; collect schema refs
function pickJsonContent(content, neededSchemas) {
if (!content || typeof content !== 'object') return undefined;
const json = content['application/json'];
if (!json || typeof json !== 'object') return undefined;
const out = {};
const dest = {};
if (json.schema && typeof json.schema === 'object') {
dest.schema = json.schema; // keep as-is; refs copied later
collectSchemaRefs(dest.schema, neededSchemas);
}
// (optional) pass through example(s) if present
if ('example' in json) dest.example = json.example;
if ('examples' in json) dest.examples = json.examples;
out['application/json'] = dest;
return out;
}
// --- Fix: object has "required" but no "properties" ---
function ensureRequiredPropsOnObject(schema) {
if (!schema || typeof schema !== 'object' || Array.isArray(schema)) return;
const hasRequired = Array.isArray(schema.required) && schema.required.length > 0;
// If "required" exists but type is missing, assume object (that's the only type with "required" for properties)
if (hasRequired && !schema.type) schema.type = 'object';
if (schema.type === 'object') {
const props = (schema.properties && typeof schema.properties === 'object') ? schema.properties : (hasRequired ? (schema.properties = {}) : null);
if (props && hasRequired) {
for (const name of schema.required) {
if (!props[name]) {
props[name] = {
type: 'string',
description: `Auto-generated placeholder for ${name}.`
};
}
}
}
}
}
// Generic schema walker (mirrors the keys you already recurse for elsewhere)
function walkSchema(schema, seen = new Set()) {
if (!schema || typeof schema !== 'object') return;
if (seen.has(schema)) return;
seen.add(schema);
// Apply the fix at this node
ensureRequiredPropsOnObject(schema);
// Recurse common JSON Schema keywords
const keys = [
'allOf','oneOf','anyOf','not','if','then','else',
'items','additionalItems','contains','propertyNames','dependentSchemas',
'unevaluatedProperties','additionalProperties','prefixItems'
];
for (const k of keys) {
const v = schema[k];
if (!v) continue;
if (Array.isArray(v)) v.forEach(x => walkSchema(x, seen));
else if (typeof v === 'object') walkSchema(v, seen);
}
// Properties and patternProperties hold nested schemas in their values
if (schema.properties && typeof schema.properties === 'object') {
for (const sub of Object.values(schema.properties)) walkSchema(sub, seen);
}
if (schema.patternProperties && typeof schema.patternProperties === 'object') {
for (const sub of Object.values(schema.patternProperties)) walkSchema(sub, seen);
}
}
// Run the fix across the whole reduced document
function fixRequiredPropsAcrossDoc(out) {
// Components.schemas
if (out?.components?.schemas && typeof out.components.schemas === 'object') {
for (const s of Object.values(out.components.schemas)) walkSchema(s);
}
// Components.requestBodies -> application/json schema
if (out?.components?.requestBodies) {
for (const rb of Object.values(out.components.requestBodies)) {
const sch = rb?.content?.['application/json']?.schema;
if (sch) walkSchema(sch);
}
}
// Components.responses -> application/json schema + header schemas
if (out?.components?.responses) {
for (const resp of Object.values(out.components.responses)) {
const sch = resp?.content?.['application/json']?.schema;
if (sch) walkSchema(sch);
if (resp?.headers && typeof resp.headers === 'object') {
for (const h of Object.values(resp.headers)) {
if (h?.schema) walkSchema(h.schema);
}
}
}
}
// Inline requestBody at operation level (if you keep those)
if (out?.paths && typeof out.paths === 'object') {
for (const item of Object.values(out.paths)) {
for (const op of Object.values(item || {})) {
const inl = op?.requestBody?.content?.['application/json']?.schema;
if (inl) walkSchema(inl);
}
}
}
}
// Merge original op params (path/query/header) + required path stubs
function mergeParamsWithPathStubs(operation, pathLevelParams, pathKey) {
const out = [];
const byKey = new Map(); // `${in}:${name}` -> index
const allow = new Set(['path','query','header']);
const srcParams = Array.isArray(operation.parameters) ? operation.parameters : [];
for (const p of srcParams) {
if (!p || typeof p !== 'object') continue;
if (p.$ref) {
// Keep component refs as-is
out.push({ $ref: p.$ref });
byKey.set(`$ref:${p.$ref}`, out.length - 1);
continue;
}
if (!allow.has(p.in)) continue;
const copy = JSON.parse(JSON.stringify(p));
if (copy.in === 'path') {
copy.required = true;
if (!copy.description || !String(copy.description).trim()) {
copy.description = `Path parameter ${copy.name}.`;
}
if (!copy.schema || typeof copy.schema !== 'object') {
copy.schema = { type: 'string' };
} else if (!copy.schema.type) {
copy.schema.type = 'string';
}
}
out.push(copy);
byKey.set(`${copy.in}:${copy.name}`, out.length - 1);
}
// ensure all {params} in the path exist
const needed = extractPathParams(pathKey);
const pathParams = Array.isArray(pathLevelParams) ? pathLevelParams : [];
for (const name of needed) {
const k1 = `path:${name}`;
if (byKey.has(k1)) {
// ensure required + description on existing
const idx = byKey.get(k1);
const existing = out[idx];
if (existing && !existing.required) existing.required = true;
if (existing && (!existing.description || !String(existing.description).trim())) {
existing.description = `Path parameter ${name}.`;
}
if (existing && (!existing.schema || !existing.schema.type)) {
existing.schema = existing.schema || {};
existing.schema.type = 'string';
}
continue;
}
const src =
srcParams.find(p => p && p.in === 'path' && p.name === name) ||
pathParams.find(p => p && p.in === 'path' && p.name === name);
out.push(makePathParamStub(name, src));
}
return out.length ? out : undefined;
}
function ensureResponseRef(out, code, optionalDescription, sourceResponse, keySuffix, neededSchemas) {
if (!out.components) out.components = {};
if (!out.components.responses) out.components.responses = {};
const hasPayload = !!(sourceResponse &&
(sourceResponse.content || sourceResponse.headers));
// Use generic key when no payload; otherwise make it per-operation to avoid collisions
const baseKey = responseComponentNameFor(code);
const key = hasPayload && keySuffix ? `${baseKey}__${String(keySuffix).replace(/[^0-9A-Za-z_]+/g, '_')}` : baseKey;
const desc = (typeof optionalDescription === 'string' && optionalDescription.trim())
? optionalDescription.trim()
: (GENERIC_RESPONSES[code] || 'Response');
if (!out.components.responses[key]) out.components.responses[key] = {};
const comp = out.components.responses[key];
if (!comp.description || !String(comp.description).trim()) {
comp.description = desc;
}
// Carry JSON content schema (and response headers) if present
if (sourceResponse) {
if (sourceResponse.content) {
const json = pickJsonContent(sourceResponse.content, neededSchemas);
if (json) comp.content = json;
}
if (sourceResponse.headers && typeof sourceResponse.headers === 'object') {
comp.headers = sourceResponse.headers;
// Collect potential schema refs from header schemas
for (const h of Object.values(comp.headers)) {
if (h && h.schema) collectSchemaRefs(h.schema, neededSchemas);
}
}
}
return key;
}
function extractPathParams(path) {
return Array.from(String(path).matchAll(/\{([^}]+)\}/g)).map(m => m[1]);
}
function makePathParamStub(name, from) {
const description = (from && typeof from.description === 'string' && from.description.trim())
? from.description.trim()
: `Path parameter ${name}.`;
const type = (from && from.schema && typeof from.schema.type === 'string' && from.schema.type.trim())
? from.schema.type.trim()
: 'string';
return {
name,
in: 'path',
required: true,
schema: { type },
description
};
}
// Utility: set status text
function setStatus(msg, type = 'info') {
const el = document.getElementById('status');
el.textContent = msg || '';
el.className = `status ${type}`;
}
// ---- Metrics helpers ----
function countLines(text) {
if (!text) return 0;
const m = text.match(/\r\n|\r|\n/g);
return (m ? m.length : 0) + 1;
}
function countActionsFromSpec(spec) {
let count = 0;
if (spec && spec.paths && typeof spec.paths === 'object') {
for (const item of Object.values(spec.paths || {})) {
if (!item || typeof item !== 'object') continue;
for (const k of Object.keys(item)) {
if (HTTP_METHODS.has(k.toLowerCase())) count++;
}
}
}
return count;
}
/** Append line + action counts to the status line */
function updateMetricsDisplay(reducedObj, { alsoStatus = true } = {}) {
const origText = originalEditor ? originalEditor.getValue() : '';
const redText = reducedEditor ? reducedEditor.getValue() : '';
const origObj = parseMaybeYamlOrJson(origText) || {};
const origLines = countLines(origText);
const redLines = countLines(redText);
const origActs = countActionsFromSpec(origObj);
const redActs = countActionsFromSpec(reducedObj);
// Persist in the page
renderMetrics({ origLines, reducedLines: redLines, origActions: origActs, reducedActions: redActs });
// Optional: also append to the status line
if (alsoStatus) {
const el = document.getElementById('status');
if (el) {
const linesMsg = `Lines ${origLines}→${redLines}`;
const actionsMsg = `Actions ${origActs}/${redActs}`;
el.textContent = (el.textContent || '').replace(/\s*$/, '') + ` • ${linesMsg} • ${actionsMsg}`;
}
}
}
// Utility: detect & parse JSON or YAML
function parseMaybeYamlOrJson(text) {
// Try JSON first (fast path)
try { return JSON.parse(text); } catch {}
// Fallback to YAML
try { return jsyaml.load(text); } catch {}
return null;
}
// Initialize Monaco editors
function initEditors() {
require(['vs/editor/editor.main'], function() {
originalEditor = monaco.editor.create(document.getElementById('originalEditor'), {
value: `{
"openapi": "3.0.0",
"info": { "title": "Ticketing API", "version": "1.0.0" },
"paths": { "/tickets": { "get": { "summary": "List tickets", "operationId": "listTickets", "responses": { "200": {} } } } }
}`,
language: 'json',
readOnly: true,
automaticLayout: true,
minimap: { enabled: false },
theme: document.body.classList.contains('theme-dark') ? 'vs-dark' : 'vs'
});
reducedEditor = monaco.editor.create(document.getElementById('reducedEditor'), {
value: '{\n "openapi": "3.0.0",\n "info": { "title": "", "version": "" },\n "paths": {}\n}',
language: 'json',
readOnly: false,
automaticLayout: true,
minimap: { enabled: false },
theme: document.body.classList.contains('theme-dark') ? 'vs-dark' : 'vs'
});
});
}
// Theme toggle
function setTheme(dark) {
document.body.classList.toggle('theme-dark', dark);
if (window.monaco && monaco.editor) {
monaco.editor.setTheme(dark ? 'vs-dark' : 'vs');
}
}
// Load from URL
async function fetchSchemaFromUrl() {
const url = document.getElementById('schemaUrl').value.trim();
if (!url) return setStatus('Please enter a schema URL.', 'warn');
setStatus('Fetching…');
try {
const res = await fetch(url, { credentials: 'omit' });
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const text = await res.text();
const obj = parseMaybeYamlOrJson(text);
if (!obj) throw new Error('Could not parse as JSON or YAML.');
originalEditor.setValue(JSON.stringify(obj, null, 2));
setStatus('Loaded schema from URL.');
} catch (e) {
console.error(e);
setStatus(`Fetch failed: ${e.message}. If this is a CORS issue, download the file and use Upload/Paste.`, 'error');
}
}
// Load from paste area
function loadFromPaste() {
const text = document.getElementById('pasteArea').value.trim();
if (!text) return setStatus('Nothing to load from paste area.', 'warn');
const obj = parseMaybeYamlOrJson(text);
if (!obj) return setStatus('Paste is not valid JSON or YAML.', 'error');
originalEditor.setValue(JSON.stringify(obj, null, 2));
setStatus('Loaded schema from paste.');
}
// Drag & drop / file input
function initDropZone() {
const dz = document.getElementById('dropZone');
const fileInput = document.getElementById('fileInput');
if (!dz || !fileInput) {
console.warn('Dropzone elements missing (skipping DnD wiring)');
return;
}
const openPicker = () => fileInput.click();
dz.addEventListener('click', openPicker);
dz.addEventListener('keydown', (e) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); openPicker(); } });
['dragenter','dragover'].forEach(evt => dz.addEventListener(evt, e => {
e.preventDefault(); e.stopPropagation(); dz.classList.add('dragging');
}));
['dragleave','drop'].forEach(evt => dz.addEventListener(evt, e => {
e.preventDefault(); e.stopPropagation(); dz.classList.remove('dragging');
}));
dz.addEventListener('drop', (e) => {
const file = e.dataTransfer.files && e.dataTransfer.files[0];
if (file) readFile(file);
});
fileInput.addEventListener('change', (e) => {
const file = e.target.files && e.target.files[0];
if (file) readFile(file);
});
}
function readFile(file) {
setStatus(`Reading ${file.name}…`);
const reader = new FileReader();
reader.onload = () => {
const text = reader.result;
const obj = parseMaybeYamlOrJson(text);
if (!obj) return setStatus('File is not valid JSON or YAML.', 'error');
originalEditor.setValue(JSON.stringify(obj, null, 2));
setStatus('Loaded schema from file.');
};
reader.onerror = () => setStatus('Could not read file.', 'error');
reader.readAsText(file);
}
// Ensure info.title and info.description exist and are not identical.
// Prompts only if missing/equal; remembers last answers in localStorage.
function ensureInfoTitleAndDescription(existingTitle, existingDescription) {
const fallbackTitle = 'Reduced API';
const fallbackDesc = 'Reduced OpenAPI for automation pipelines.';
const sanitize = (s) => (typeof s === 'string' ? s.trim() : '');
const norm = (s) => sanitize(s).replace(/\s+/g, ' ').toLowerCase();
let title = sanitize(existingTitle);
let desc = sanitize(existingDescription);
try {
if (!title) {
const last = localStorage.getItem('schemaDoctor.lastTitle') || fallbackTitle;
title = window.prompt('API Title (cannot equal Description):', last) || last;
title = sanitize(title) || fallbackTitle;
localStorage.setItem('schemaDoctor.lastTitle', title);
}
if (!desc) {
const lastD = localStorage.getItem('schemaDoctor.lastDescription') || fallbackDesc;
desc = window.prompt('API Description (cannot equal Title):', lastD) || lastD;
desc = sanitize(desc) || fallbackDesc;
localStorage.setItem('schemaDoctor.lastDescription', desc);
}
} catch (_) {
// In case prompts are blocked (e.g., popup settings), fall back silently.
if (!title) title = fallbackTitle;
if (!desc) desc = fallbackDesc;
}
// Enforce distinct values (case/whitespace-insensitive)
if (norm(title) === norm(desc)) {
try {
const attempt = window.prompt('Title and Description must be different. Enter a new Description:', desc);
const cleaned = sanitize(attempt);
if (cleaned && norm(title) !== norm(cleaned)) {
desc = cleaned;
localStorage.setItem('schemaDoctor.lastDescription', desc);
} else {
// Final fallback to make them distinct without re-prompting again
desc = desc + ' (description)';
}
} catch (_) {
desc = desc + ' (description)';
}
}
return { title, description: desc };
}
function pickStringTags(arr) {
if (!Array.isArray(arr)) return [];
const cleaned = arr
.map(t => (typeof t === 'string' ? t.trim() : ''))
.filter(Boolean);
return Array.from(new Set(cleaned)); // de-dupe, stable-ish
}
function reduceOpenAPI(spec, filter) {
const ensured = ensureInfoTitleAndDescription(spec?.info?.title, spec?.info?.description);
const out = {
openapi: typeof spec.openapi === 'string' ? spec.openapi : '3.0.0',
info: {
title: ensured.title,
version: spec?.info?.version || '1.0.0',
description: ensured.description
},
paths: {},
components: {}
};
// ---- servers (OAS) or construct from Swagger 2.0 ----
if (Array.isArray(spec.servers) && spec.servers.length) {
out.servers = spec.servers;
} else if (spec.swagger === '2.0' && (spec.host || spec.basePath)) {
const scheme = Array.isArray(spec.schemes) && spec.schemes.length ? spec.schemes[0] : 'https';
const host = spec.host || '';
const basePath = spec.basePath || '';
out.servers = [{ url: `${scheme}://${host}${basePath}` }];
}
// Root security (optional)
if (Array.isArray(spec.security)) out.security = spec.security;
// securitySchemes passthrough
if (spec.components && typeof spec.components === 'object' && spec.components.securitySchemes) {
out.components.securitySchemes = spec.components.securitySchemes;
}
// ---- Tag metadata index (preserve tag descriptions when used) ----
const sourceTagIndex = new Map();
if (Array.isArray(spec.tags)) {
for (const t of spec.tags) {
if (t && typeof t.name === 'string' && t.name.trim()) {
sourceTagIndex.set(t.name.trim(), {
name: t.name.trim(),
description: (typeof t.description === 'string' && t.description.trim()) ? t.description.trim() : undefined,
externalDocs: (t.externalDocs && typeof t.externalDocs === 'object') ? t.externalDocs : undefined
});
}
}
}
const usedTagNames = new Set();
const usedOperationIds = new Set();
// ---- Track components we must carry over ----
const neededSchemas = new Set();
const neededParameters = new Set();
const neededRequestBodies = new Set();
// ---- Paths & methods ----
if (spec.paths && typeof spec.paths === 'object') {
for (const [pathKey, pathItem] of Object.entries(spec.paths)) {
if (!pathItem || typeof pathItem !== 'object') continue;
const reducedPathItem = {};
const pathLevelParams = Array.isArray(pathItem.parameters) ? pathItem.parameters : [];
for (const [maybeMethod, operation] of Object.entries(pathItem)) {
const method = maybeMethod.toLowerCase();
if (!HTTP_METHODS.has(method)) continue;
if (!operation || typeof operation !== 'object') continue;
if (!opMatchesFilter(pathKey, method, operation, filter)) continue;
const reducedOp = {};
if (operation.summary) reducedOp.summary = operation.summary;
if (operation.description) reducedOp.description = operation.description;
// ---- operationId: copy or synthesize, then ensure global uniqueness ----
const rawOpId = operation.operationId || makeOpId(pathKey, method);
const opId = ensureUniqueId(rawOpId, usedOperationIds);
reducedOp.operationId = opId;
// if (operation.operationId) reducedOp.operationId = operation.operationId;
// tags
const opTags = pickStringTags(operation.tags);
if (opTags.length) {
reducedOp.tags = opTags;
opTags.forEach(n => usedTagNames.add(n));
}
// parameters: retain path/query/header; ensure path requirements; add missing path stubs
const mergedParams = mergeParamsWithPathStubs(operation, pathLevelParams, pathKey);
if (mergedParams) {
reducedOp.parameters = mergedParams;
// collect component param refs
for (const p of mergedParams) {
if (p && p.$ref) {
const m = p.$ref.match(/^#\/components\/parameters\/([^\/]+)$/);
if (m) neededParameters.add(m[1]);
} else if (p && p.schema) {
collectSchemaRefs(p.schema, neededSchemas);
}
}
}
// requestBody: keep only application/json (inline or $ref)
if (operation.requestBody) {
if (operation.requestBody.$ref) {
reducedOp.requestBody = { $ref: operation.requestBody.$ref };
const m = operation.requestBody.$ref.match(/^#\/components\/requestBodies\/([^\/]+)$/);
if (m) neededRequestBodies.add(m[1]);
} else if (operation.requestBody.content) {
const rb = { };
if (typeof operation.requestBody.description === 'string' && operation.requestBody.description.trim()) {
rb.description = operation.requestBody.description.trim();
}
if (typeof operation.requestBody.required === 'boolean') {
rb.required = operation.requestBody.required;
}
const json = pickJsonContent(operation.requestBody.content, neededSchemas);
if (json) {
rb.content = json;
reducedOp.requestBody = rb;
}
}
}
// Responses: $ref to components; carry JSON schema + headers when present
const srcResponses = (operation.responses && typeof operation.responses === 'object') ? operation.responses : null;
const codes = srcResponses ? Object.keys(srcResponses) : [];
const finalCodes = codes.length ? codes : ['200'];
reducedOp.responses = {};
const seenNormalized = new Set();
for (const rawCode of finalCodes) {
const normCode = normalizeStatusCode(rawCode);
if (seenNormalized.has(normCode)) continue; // avoid dupes like 400 + 4xx
seenNormalized.add(normCode);
let src = srcResponses ? srcResponses[rawCode] : null;
if (src && src.$ref) {
const resolved = resolveComponentRef(spec, src.$ref);
if (resolved) src = resolved;
}
const desc = (src && typeof src.description === 'string' && src.description.trim())
? src.description.trim()
: undefined;
const opKey = safeKeyFrom(pathKey, method, opId);
const compKey = ensureResponseRef(out, normCode, desc, src, opKey, neededSchemas);
// Use the normalized code as the operation key
reducedOp.responses[normCode] = { $ref: `#/components/responses/${compKey}` };
}
reducedPathItem[method] = reducedOp;
}
if (Object.keys(reducedPathItem).length) {
out.paths[pathKey] = reducedPathItem;
}
}
}
// ---- top-level tags actually used ----
if (usedTagNames.size) {
out.tags = [...usedTagNames].map(name => {
const meta = sourceTagIndex.get(name);
if (meta) {
const t = { name: meta.name };
if (meta.description) t.description = meta.description;
if (meta.externalDocs) t.externalDocs = meta.externalDocs;
return t;
}
return { name };
});
}
// ---- bring over needed components: parameters, requestBodies, schemas (closure) ----
if (neededParameters.size && spec?.components?.parameters) {
for (const name of neededParameters) {
const p = spec.components.parameters[name];
if (p) {
if (!out.components.parameters) out.components.parameters = {};
out.components.parameters[name] = p;
// collect schema refs from component parameter
if (p.schema) collectSchemaRefs(p.schema, neededSchemas);
}
}
}
if (neededRequestBodies.size && spec?.components?.requestBodies) {
for (const name of neededRequestBodies) {
const rb = spec.components.requestBodies[name];
if (rb) {
if (!out.components.requestBodies) out.components.requestBodies = {};
const kept = {};
if (typeof rb.description === 'string' && rb.description.trim()) kept.description = rb.description.trim();
if (typeof rb.required === 'boolean') kept.required = rb.required;
const json = pickJsonContent(rb.content, neededSchemas);
if (json) kept.content = json;
out.components.requestBodies[name] = kept;
}
}
}
copyNeededSchemas(spec, out, neededSchemas);
fixRequiredPropsAcrossDoc(out);
return out;
}
// Ajv validation (optional, best‑effort). Loads OAS schema 3.0/3.1 dynamically if possible.
async function validateWithAjv(oas) {
// Try to detect Ajv constructor from available globals
const AjvCtor = (window.ajv7 && (window.ajv7.default || window.ajv7)) || window.Ajv;
if (!AjvCtor) return { ok: true, errors: [] };
try {
if (!ajvInstance) ajvInstance = new AjvCtor({ strict: false, allErrors: true });
const version = (oas.openapi || '').toString();
const is31 = version.startsWith('3.1');
// Official OAS JSON Schemas (served with CORS by spec.openapis.org)
const schemaUrl = is31
? 'https://spec.openapis.org/oas/3.1/schema/2022-10-07'
: 'https://spec.openapis.org/oas/3.0/schema/2021-09-28';
const res = await fetch(schemaUrl, { cache: 'force-cache' });
if (!res.ok) throw new Error('Could not load OpenAPI JSON Schema');
const schema = await res.json();
const validate = ajvInstance.compile(schema);
const ok = validate(oas);
return { ok, errors: ok ? [] : validate.errors };
} catch (e) {
console.warn('Validation skipped:', e.message);
return { ok: true, errors: [] }; // non‑blocking
}
}
function renderMetrics({ origLines, reducedLines, origActions, reducedActions }) {
const wrap = document.getElementById('metrics');
if (!wrap) return;
const linesEl = document.getElementById('metric-lines');
const actsEl = document.getElementById('metric-actions');
const linesText = `Lines: ${origLines} → ${reducedLines}`;
const actsText = `Actions: ${origActions}/${reducedActions}${origActions === reducedActions ? '' : ' ⚠'}`;
if (linesEl) linesEl.textContent = linesText;
if (actsEl) actsEl.textContent = actsText;
wrap.style.visibility = 'visible';
}
function wireFilterPanel(spec) {
const panel = document.getElementById('filter-panel');
if (!panel || panel.__wired) return;
panel.__wired = true;
// Hard block opening when locked (covers keyboard toggles)
panel.addEventListener('toggle', (e) => {
if (panel.classList.contains('locked')) {
panel.open = false; // immediately re-close
// optional: surface a friendly hint
setStatus('Generate a schema first to enable filtering.', 'warn');
return;
}
// Lazy-build tag UI the first time it *legitimately* opens
if (panel.open && !__filterUIBuilt) {
buildTagFilterUI(spec);
wireFilterButtons();
__filterUIBuilt = true;
recomputeFilterStatsDebounced(spec);
}
});
const onAnyChange = debounce(() => {
__filterDirty = true; // mark pending
getFilterFromUI(spec); // refresh summary + stats
updateFilterPendingUI(); // show banner if needed
}, 120);
panel.addEventListener('change', onAnyChange);
panel.addEventListener('input', onAnyChange);
// Inline Apply button
const applyBtn = document.getElementById('filter-apply-inline');
if (applyBtn && !applyBtn.__wired) {
applyBtn.__wired = true;
applyBtn.addEventListener('click', (e) => {
e.preventDefault();
generateReduced(); // reuse your existing flow
});
}
}
// Generate reduced schema from the original editor
async function generateReduced() {
try {
setStatus('Reducing…');
const origText = originalEditor.getValue();
const spec = parseMaybeYamlOrJson(origText);
if (!spec) throw new Error('Unable to parse schema. Is it valid JSON or YAML?');
// Lazy-build/wire the accordion (only on first open)
wireFilterPanel(spec);
// If user already opened it and picked things, read them now
const filter = getFilterFromUI(spec);
const reduced = reduceOpenAPI(spec, filter);
const { ok, errors } = await validateWithAjv(reduced);
reducedEditor.setValue(JSON.stringify(reduced, null, 2));
updateMetricsDisplay(reduced);
// Unlock the filter panel now that a schema exists
const panel = document.getElementById('filter-panel');
if (panel && panel.classList.contains('locked')) {
panel.classList.remove('locked');
panel.removeAttribute('aria-disabled');
}
// Clear pending state now that results reflect current filter
__filterDirty = false;
updateFilterSummary();
updateFilterPendingUI();
setStatus(
ok
? `Reduced schema ready${filter?.enabled ? ' (filtered)' : ''}.`
: `Reduced schema generated with validation notes (${errors.length})${filter?.enabled ? ' (filtered)' : ''}.`,
ok ? 'info' : 'warn'
);
} catch (e) {
console.error(e);
setStatus(e.message || 'Failed to reduce schema', 'error');
}
}
// Clipboard copy
async function copyReduced() {
try {
const text = reducedEditor.getValue();
await navigator.clipboard.writeText(text);