Repository navigation
Expand file tree
/
Copy pathscript.js
More file actions
512 lines (420 loc) · 13.4 KB
/
Copy pathscript.js
File metadata and controls
512 lines (420 loc) · 13.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
const OPENAI_API_URL = 'https://api.openai.com/v1/responses';
const OPENAI_MODEL = 'gpt-4.1-mini';
const STORAGE_KEY = 'schematch.openai.apiKey';
const THEME_KEY = 'schematch.theme';
const THEME_COLORS = {
light: '#f4f6fb',
dark: '#0a0a0f'
};
const SAMPLE_PAYLOAD = {
schema: {
user_id: 'number',
email: 'string',
status: 'string',
marketing_opt_in: 'boolean'
},
response: {
user_id: '123abc',
status: 'active',
marketing_opt_in: 'yes'
}
};
const FIELD_LABELS = {
schema: 'Expected Schema',
response: 'Actual API Response'
};
function showError(msg) {
const banner = document.getElementById('errorBanner');
banner.textContent = msg;
banner.classList.add('visible');
}
function setActionStatus(message, isError = false) {
const status = document.getElementById('actionStatus');
if (!status) {
return;
}
status.textContent = message;
status.dataset.state = message ? (isError ? 'error' : 'success') : '';
}
function hideError() {
document.getElementById('errorBanner').classList.remove('visible');
}
function formatJSON(value) {
return JSON.stringify(JSON.parse(value), null, 2);
}
function escapeHTML(value) {
return String(value)
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
}
function getStoredApiKey() {
return localStorage.getItem(STORAGE_KEY) || '';
}
function saveApiKey(value) {
localStorage.setItem(STORAGE_KEY, value.trim());
}
function clearApiKey() {
localStorage.removeItem(STORAGE_KEY);
}
function getActualType(value) {
if (value === null) {
return 'null';
}
if (Array.isArray(value)) {
return 'array';
}
return typeof value;
}
function normalizeExpectedType(value) {
return typeof value === 'string' ? value.trim().toLowerCase() : '';
}
function validateContract(schema, response) {
const errors = [];
if (!schema || Array.isArray(schema) || typeof schema !== 'object') {
return {
valid: false,
errors: ['Schema must be a JSON object with top-level fields mapped to expected type names.']
};
}
if (!response || Array.isArray(response) || typeof response !== 'object') {
return {
valid: false,
errors: ['Response must be a JSON object.']
};
}
for (const field of Object.keys(schema)) {
if (!(field in response)) {
errors.push(`Missing field: "${field}"`);
continue;
}
const expectedType = normalizeExpectedType(schema[field]);
const actualType = getActualType(response[field]);
if (!expectedType) {
errors.push(`Field "${field}": expected type must be a string like string, number, or boolean.`);
continue;
}
if (actualType !== expectedType) {
errors.push(`Field "${field}": expected ${expectedType}, got ${actualType}`);
}
}
return {
valid: errors.length === 0,
errors
};
}
function extractResponseText(data) {
if (typeof data.output_text === 'string' && data.output_text.trim()) {
return data.output_text.trim();
}
if (!Array.isArray(data.output)) {
return '';
}
const parts = [];
for (const item of data.output) {
if (!Array.isArray(item.content)) {
continue;
}
for (const contentItem of item.content) {
if (typeof contentItem.text === 'string' && contentItem.text.trim()) {
parts.push(contentItem.text.trim());
continue;
}
if (typeof contentItem.output_text === 'string' && contentItem.output_text.trim()) {
parts.push(contentItem.output_text.trim());
}
}
}
return parts.join('\n\n').trim();
}
async function requestAIDiagnosis(apiKey, errors, schema, response) {
const prompt = [
'You are an API debugging assistant.',
'',
'The following errors were found when validating an API response against its expected schema:',
'',
`Errors: ${JSON.stringify(errors)}`,
'',
`Schema: ${JSON.stringify(schema, null, 2)}`,
'',
`Actual Response: ${JSON.stringify(response, null, 2)}`,
'',
'Explain clearly:',
'1. What broke',
'2. Why it likely happened',
'3. How to fix it'
].join('\n');
const res = await fetch(OPENAI_API_URL, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${apiKey}`
},
body: JSON.stringify({
model: OPENAI_MODEL,
input: prompt
})
});
if (!res.ok) {
let message = `OpenAI returned ${res.status}`;
try {
const errorData = await res.json();
message = errorData.error?.message || message;
} catch {
}
throw new Error(message);
}
const data = await res.json();
const text = extractResponseText(data);
if (!text) {
throw new Error('OpenAI returned a response, but no readable text was found in the payload.');
}
return text;
}
function renderResult(result, aiText = '', aiError = '') {
const resultElement = document.getElementById('result');
resultElement.classList.add('visible', result.valid ? 'valid' : 'invalid');
document.getElementById('resultTitle').textContent = result.valid
? 'Contract Valid - Response matches schema'
: `Contract Invalid - ${result.errors.length} error${result.errors.length > 1 ? 's' : ''} detected`;
let bodyHTML = '';
if (!result.valid && result.errors.length > 0) {
bodyHTML += `<div class="errors-list">
<div class="errors-title">Validation Errors</div>
${result.errors.map((error) => `<div class="error-item">${escapeHTML(error)}</div>`).join('')}
</div>`;
}
if (aiText) {
bodyHTML += `<div class="ai-section">
<div class="ai-label">AI Diagnosis</div>
<div class="ai-text">${formatAI(escapeHTML(aiText))}</div>
</div>`;
} else if (!result.valid) {
bodyHTML += `<div class="info-callout">${escapeHTML(aiError || 'Add an OpenAI API key to receive AI diagnosis for invalid responses.')}</div>`;
}
if (!bodyHTML) {
bodyHTML = '<div class="ai-text success-copy">All fields match the expected schema. No issues found.</div>';
}
document.getElementById('resultBody').innerHTML = bodyHTML;
}
function buildResultText() {
const result = document.getElementById('result');
const title = document.getElementById('resultTitle').textContent.trim();
const body = document.getElementById('resultBody').innerText.trim();
if (!result.classList.contains('visible') || !title) {
return '';
}
return [title, body].filter(Boolean).join('\n\n');
}
function syncApiKeyUI() {
const apiKeyField = document.getElementById('apiKey');
const status = document.getElementById('apiKeyStatus');
const hasKey = Boolean(getStoredApiKey());
if (apiKeyField && !apiKeyField.value) {
apiKeyField.value = getStoredApiKey();
}
if (status) {
status.textContent = hasKey
? 'Key saved in this browser.'
: 'No key saved. Use a test key for AI diagnosis.';
}
}
function updateSubmitState() {
const schemaField = document.getElementById('schema');
const responseField = document.getElementById('response');
const button = document.getElementById('submitBtn');
const hasInvalidField = [schemaField, responseField].some(
(textarea) => textarea.dataset.jsonValid === 'false'
);
if (!button.classList.contains('loading')) {
button.disabled = hasInvalidField;
}
}
function setFieldValidity(textarea, isValid) {
textarea.dataset.jsonValid = String(isValid);
textarea.setAttribute('aria-invalid', String(!isValid));
updateSubmitState();
}
function validateJSONField(textarea, options = {}) {
const { formatIfValid = false, showErrorMessage = false } = options;
const raw = textarea.value.trim();
if (!raw) {
setFieldValidity(textarea, true);
return true;
}
try {
const formatted = formatJSON(raw);
if (formatIfValid) {
textarea.value = formatted;
}
setFieldValidity(textarea, true);
hideError();
return true;
} catch (error) {
setFieldValidity(textarea, false);
if (showErrorMessage) {
showError(`Invalid JSON in ${FIELD_LABELS[textarea.id]}: ${error.message}`);
}
return false;
}
}
function attachJSONHandlers(textarea) {
textarea.addEventListener('paste', () => {
queueMicrotask(() => {
validateJSONField(textarea, { formatIfValid: true, showErrorMessage: true });
});
});
textarea.addEventListener('blur', () => {
validateJSONField(textarea, { formatIfValid: true, showErrorMessage: true });
});
textarea.addEventListener('input', () => {
setFieldValidity(textarea, true);
hideError();
});
}
function getStoredTheme() {
const stored = localStorage.getItem(THEME_KEY);
return stored === 'light' || stored === 'dark' ? stored : null;
}
function getPreferredTheme() {
const stored = getStoredTheme();
if (stored) return stored;
return window.matchMedia('(prefers-color-scheme: light)').matches ? 'light' : 'dark';
}
function applyTheme(theme) {
document.documentElement.dataset.theme = theme;
const meta = document.querySelector('meta[name="theme-color"]');
if (meta) meta.setAttribute('content', THEME_COLORS[theme]);
const logo = document.querySelector('.logo');
if (logo) logo.src = theme === 'light' ? './schematch-light.svg' : './schematch.svg';
const toggle = document.getElementById('themeToggle');
if (toggle) {
const nextTheme = theme === 'light' ? 'dark' : 'light';
toggle.setAttribute('aria-label', `Switch to ${nextTheme} theme`);
toggle.querySelector('.theme-toggle__label').textContent = nextTheme === 'light' ? 'Light' : 'Dark';
toggle.querySelector('.theme-toggle__icon').textContent = theme === 'light' ? '☾' : '☀';
}
}
function toggleTheme() {
const current = document.documentElement.dataset.theme || getPreferredTheme();
const next = current === 'light' ? 'dark' : 'light';
localStorage.setItem(THEME_KEY, next);
applyTheme(next);
}
function initTheme() {
applyTheme(getPreferredTheme());
const toggle = document.getElementById('themeToggle');
if (toggle) toggle.addEventListener('click', toggleTheme);
if (!getStoredTheme()) {
window.matchMedia('(prefers-color-scheme: light)').addEventListener('change', (event) => {
if (getStoredTheme()) return;
applyTheme(event.matches ? 'light' : 'dark');
});
}
}
document.addEventListener('DOMContentLoaded', () => {
initTheme();
attachJSONHandlers(document.getElementById('schema'));
attachJSONHandlers(document.getElementById('response'));
const apiKeyField = document.getElementById('apiKey');
if (apiKeyField) {
apiKeyField.value = getStoredApiKey();
apiKeyField.addEventListener('blur', () => {
const value = apiKeyField.value.trim();
if (value) {
saveApiKey(value);
} else {
clearApiKey();
}
syncApiKeyUI();
});
}
syncApiKeyUI();
setActionStatus('');
updateSubmitState();
});
function formatAI(text) {
return text
.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
.replace(/### (.*?)(\n|$)/g, '<strong>$1</strong>\n')
.replace(/^- /gm, '→ ');
}
async function validate() {
hideError();
setActionStatus('');
const schemaField = document.getElementById('schema');
const responseField = document.getElementById('response');
const schemaRaw = schemaField.value.trim();
const responseRaw = responseField.value.trim();
const btn = document.getElementById('submitBtn');
const result = document.getElementById('result');
if (!schemaRaw || !responseRaw) {
showError('Both fields are required.');
return;
}
if (!validateJSONField(schemaField, { formatIfValid: true, showErrorMessage: true })) {
return;
}
if (!validateJSONField(responseField, { formatIfValid: true, showErrorMessage: true })) {
return;
}
btn.disabled = true;
btn.classList.add('loading');
result.classList.remove('visible', 'valid', 'invalid');
try {
const schema = JSON.parse(schemaField.value);
const response = JSON.parse(responseField.value);
const validationResult = validateContract(schema, response);
let aiText = '';
let aiError = '';
if (!validationResult.valid) {
const apiKey = getStoredApiKey();
if (apiKey) {
try {
aiText = await requestAIDiagnosis(apiKey, validationResult.errors, schema, response);
} catch (error) {
aiError = `AI diagnosis unavailable: ${error.message}`;
}
}
}
renderResult(validationResult, aiText, aiError);
} catch(e) {
showError('Validation failed: ' + e.message);
} finally {
btn.disabled = false;
btn.classList.remove('loading');
}
}
function clearSavedKey() {
const apiKeyField = document.getElementById('apiKey');
clearApiKey();
if (apiKeyField) {
apiKeyField.value = '';
}
syncApiKeyUI();
}
function loadSamplePayload() {
const schemaField = document.getElementById('schema');
const responseField = document.getElementById('response');
schemaField.value = JSON.stringify(SAMPLE_PAYLOAD.schema, null, 2);
responseField.value = JSON.stringify(SAMPLE_PAYLOAD.response, null, 2);
setFieldValidity(schemaField, true);
setFieldValidity(responseField, true);
hideError();
setActionStatus('Sample payload loaded.');
}
async function copyResult() {
const text = buildResultText();
if (!text) {
setActionStatus('Run a validation before copying the result.', true);
return;
}
try {
await navigator.clipboard.writeText(text);
setActionStatus('Result copied to clipboard.');
} catch (error) {
setActionStatus(`Copy failed: ${error.message}`, true);
}
}