(function() { var MAX_FILE_BYTES = 256 * 1024; var OPERATIONS_PER_PAGE = 100; var APPLY_REPLAY_STORAGE_KEY = 'crank_openapi_plan_apply_replay_v2'; var restoredApplyRequest = loadApplyReplay(); var state = { workspaceId: null, onImported: null, file: null, jobId: null, preview: null, existingOperations: [], operationsReady: false, decisions: Object.create(null), plan: null, securityChoices: [], securityStatus: 'unresolved', securityByOperation: Object.create(null), filterQuery: '', filterMethod: '', selectedOperationKeys: new Set(), operationGroups: [], pageIndex: 0, partialMode: false, planPageIndex: 0, resultPageIndex: 0, planVersion: 0, planRevalidationGeneration: 0, planRevalidationState: 'current', revision: 0, previewController: null, planController: null, applyController: null, applyInFlight: false, applyRequest: restoredApplyRequest, applyMetadata: restoredApplyRequest && restoredApplyRequest.operationMetadata || [], applyResult: null, applyOutcomeUnknown: !!restoredApplyRequest, applyRefreshFailed: false, restoreFocus: null, }; function validApplyReplay(request) { return request && typeof request.workspaceId === 'string' && request.workspaceId.length > 0 && request.workspaceId.length <= 128 && typeof request.planReference === 'string' && request.planReference.length > 0 && request.planReference.length <= 128 && typeof request.planDigest === 'string' && /^[a-f0-9]{64}$/.test(request.planDigest) && typeof request.idempotencyKey === 'string' && request.idempotencyKey.length > 0 && request.idempotencyKey.length <= 128; } function loadApplyReplay() { try { var request = JSON.parse(sessionStorage.getItem(APPLY_REPLAY_STORAGE_KEY) || 'null'); return validApplyReplay(request) ? request : null; } catch (_error) { return null; } } function persistApplyReplay(request) { if (!validApplyReplay(request)) return; try { sessionStorage.setItem(APPLY_REPLAY_STORAGE_KEY, JSON.stringify(request)); } catch (_error) {} } function clearApplyReplay() { try { sessionStorage.removeItem(APPLY_REPLAY_STORAGE_KEY); } catch (_error) {} } function qs(id) { return document.getElementById(id); } function tKey(key) { return window.t ? window.t(key) : key; } function tfKey(key, vars) { return window.tf ? window.tf(key, vars) : tKey(key); } function locale() { return localStorage.getItem('crank_lang') === 'ru' ? 'ru' : 'en'; } function isSameContext(revision, workspaceId, language) { return revision === state.revision && workspaceId === state.workspaceId && language === locale(); } function isCurrent(revision, workspaceId, language) { return isSameContext(revision, workspaceId, language) && !qs('openapi-import-modal').hidden; } function setStatus(message, isError, focus) { var node = qs('openapi-import-status'); if (!node) return; node.textContent = message || ''; node.classList.toggle('error', !!isError); if (focus && message) { node.focus(); } } function boundedFileName(file) { var name = String(file && file.name || ''); return name.length > 128 ? name.slice(0, 127) + '…' : name; } function formatSize(bytes) { var language = locale() === 'ru' ? 'ru-RU' : 'en-US'; return new Intl.NumberFormat(language).format(bytes) + ' B'; } function renderFileName() { var node = qs('openapi-import-file-name'); if (!node) return; node.textContent = state.file ? boundedFileName(state.file) + ' · ' + formatSize(state.file.size) : tKey('openapi.file.none'); } function selectedKeys() { return importOperations() .map(function(operation) { return operation.key; }) .filter(function(key) { return state.selectedOperationKeys.has(key); }); } function importOperations() { return (state.preview && state.preview.groups || []).flatMap(function(group) { return group.operations || []; }); } function operationConflicts(operationKey) { return (state.preview && state.preview.conflicts || []).filter(function(conflict) { return conflict && conflict.operation_key === operationKey; }); } function sourcePointer(location) { return location && typeof location.pointer === 'string' ? location.pointer : ''; } function hasTypedError(findings) { return (findings || []).some(function(finding) { return String(finding && finding.severity || '').toLowerCase() === 'error'; }); } function operationIsBlocked(operation) { return String(operation && operation.status || '').toLowerCase() === 'blocked' || hasTypedError(operation && operation.findings) || hasTypedError((state.preview && state.preview.findings || []).filter(function(finding) { return operation && finding && finding.operation_key === operation.key; })); } function operationReadiness(operation) { var status = String(operation && operation.status || '').toLowerCase(); var labelKey = { actionable: 'openapi.operation.readiness_actionable', blocked: 'openapi.operation.readiness_blocked', unresolved: 'openapi.operation.readiness_unresolved', }[status]; if (!labelKey) return ''; return '' + escapeHtml(tKey(labelKey)) + ''; } function documentIsBlocked() { var preview = state.preview || {}; return String(preview.status || '').toLowerCase() === 'blocked' || hasTypedError((preview.findings || []).filter(function(finding) { return !finding || !finding.operation_key; })); } function decisionFor(operationKey) { if (!state.decisions[operationKey]) { var conflicts = operationConflicts(operationKey); state.decisions[operationKey] = { action: conflicts.length ? 'rename' : 'create', targetOperationId: '', confirmedName: conflicts.length ? String(conflicts[0].proposed_name || '') : '', securityAlternativeIndex: null, authProfileId: null, }; } return state.decisions[operationKey]; } function matchingOperations(operation) { return state.existingOperations.filter(function(existing) { return existing.name === operation.suggested_name; }); } function renderDecisionControls(operation, row) { var previous = row.querySelector('.openapi-import-decision-controls'); if (previous) previous.remove(); var controls = document.createElement('div'); var actionLabel = document.createElement('label'); var actionSelect = document.createElement('select'); var candidateDecision = decisionFor(operation.key); var matches = matchingOperations(operation); var versionable = matches.filter(function(existing) { return existing.protocol === 'rest' && existing.status !== 'archived'; }); var actions = [ ['create', 'openapi.decision.create'], ['skip', 'openapi.decision.skip'], ['rename', 'openapi.decision.rename'], ['new_version', 'openapi.decision.new_version'], ]; controls.className = 'openapi-import-decision-controls'; actionLabel.textContent = tKey('openapi.decision.action_label'); actionLabel.htmlFor = 'openapi-import-decision-' + operation.key; actionSelect.id = actionLabel.htmlFor; actionSelect.dataset.openapiDecisionAction = operation.key; actions.forEach(function(spec) { var option = document.createElement('option'); option.value = spec[0]; option.textContent = tKey(spec[1]); if ((spec[0] === 'skip' && !matches.length) || (spec[0] === 'new_version' && !versionable.length)) { option.disabled = true; } actionSelect.appendChild(option); }); actionSelect.value = candidateDecision.action; actionSelect.addEventListener('change', function() { candidateDecision.action = actionSelect.value; if (candidateDecision.action === 'skip' || candidateDecision.action === 'new_version') { var allowed = candidateDecision.action === 'new_version' ? versionable : matches; if (!allowed.some(function(existing) { return existing.id === candidateDecision.targetOperationId; })) { candidateDecision.targetOperationId = allowed.length === 1 ? allowed[0].id : ''; } } renderDecisionControls(operation, row); renderSecurityControls(operation, row); updateSecuritySummary(); }); actionLabel.appendChild(actionSelect); controls.appendChild(actionLabel); if (candidateDecision.action === 'skip' || candidateDecision.action === 'new_version') { var targetLabel = document.createElement('label'); var targetSelect = document.createElement('select'); var allowedTargets = candidateDecision.action === 'new_version' ? versionable : matches; var placeholder = document.createElement('option'); targetLabel.textContent = tKey('openapi.decision.target_label'); targetSelect.dataset.openapiDecisionTarget = operation.key; placeholder.value = ''; placeholder.textContent = tKey('openapi.decision.target_placeholder'); targetSelect.appendChild(placeholder); allowedTargets.forEach(function(existing) { var option = document.createElement('option'); option.value = existing.id; option.textContent = existing.name + ' · ' + existing.id; targetSelect.appendChild(option); }); targetSelect.value = candidateDecision.targetOperationId; targetSelect.addEventListener('change', function() { candidateDecision.targetOperationId = targetSelect.value; }); targetLabel.appendChild(targetSelect); controls.appendChild(targetLabel); } if (candidateDecision.action === 'rename') { var renameLabel = document.createElement('label'); var renameInput = document.createElement('input'); renameLabel.textContent = tKey('openapi.decision.confirmed_name_label'); renameInput.type = 'text'; renameInput.maxLength = 128; renameInput.value = candidateDecision.confirmedName; renameInput.placeholder = tKey('openapi.decision.confirmed_name_placeholder'); renameInput.dataset.openapiDecisionName = operation.key; if (operationConflicts(operation.key).length) renameInput.dataset.testid = 'openapi-import-rename-proposal'; renameInput.addEventListener('input', function() { candidateDecision.confirmedName = renameInput.value; }); renameLabel.appendChild(renameInput); controls.appendChild(renameLabel); } row.appendChild(controls); } function operationRows() { return Array.from(document.querySelectorAll('.openapi-import-operation')); } function visibleOperationRows() { return operationRows().filter(function(row) { return !row.hidden; }); } function updateSelection() { var node = qs('openapi-import-selection'); var selectedCount = selectedKeys().length; var totalCount = importOperations().length; var visibleCount = visibleOperationRows().length; if (node) { node.textContent = tfKey('openapi.selection', { selected: selectedCount, total: totalCount, visible: visibleCount, }); } document.querySelectorAll('.openapi-import-group').forEach(function(groupNode) { var rows = Array.from(groupNode.querySelectorAll('.openapi-import-operation')); var visibleInputs = rows .filter(function(row) { return !row.hidden; }) .map(function(row) { return row.querySelector('[data-openapi-operation]'); }) .filter(Boolean); var selectedVisible = visibleInputs.filter(function(input) { return input.checked; }).length; var selectedTotal = rows.reduce(function(count, row) { var input = row.querySelector('[data-openapi-operation]'); return count + (input && state.selectedOperationKeys.has(input.value) ? 1 : 0); }, 0); var checkbox = groupNode.querySelector('[data-openapi-group]'); var counter = groupNode.querySelector('[data-openapi-group-count]'); if (checkbox) { checkbox.indeterminate = selectedVisible > 0 && selectedVisible < visibleInputs.length; checkbox.checked = visibleInputs.length > 0 && selectedVisible === visibleInputs.length; } if (counter) { counter.textContent = tfKey('openapi.group.selection', { selected: selectedTotal, total: rows.length, visible: visibleInputs.length, }); } }); updateSecuritySummary(); } function applyFilters() { state.pageIndex = 0; renderOperationPage(); updateSelection(); } function setVisibleSelection(checked) { visibleOperationRows().forEach(function(row) { var input = row.querySelector('[data-openapi-operation]'); if (!input) return; if (checked && input.disabled) return; input.checked = checked; if (checked) state.selectedOperationKeys.add(input.value); else state.selectedOperationKeys.delete(input.value); }); renderOperationPage(); updateSelection(); } function filteredOperationGroups() { var query = state.filterQuery.toLowerCase(); var method = state.filterMethod.toLowerCase(); return state.operationGroups.map(function(group) { return { group: group, operations: group.operations.filter(function(operation) { var matchesMethod = !method || String(operation.method).toLowerCase() === method; var searchable = [group.title, operation.key, operation.suggested_name, operation.suggested_display_name, operation.path, operation.method].join(' ').toLowerCase(); return matchesMethod && (!query || searchable.indexOf(query) >= 0); }), }; }).filter(function(group) { return group.operations.length > 0; }); } function createOperationRow(operation, groupTitle) { var row = document.createElement('div'); var selectionLabel = document.createElement('label'); row.className = 'openapi-import-operation'; selectionLabel.className = 'openapi-import-operation-selection'; row.dataset.openapiMethod = operation.method; row.dataset.openapiSearch = [groupTitle, operation.key, operation.suggested_name, operation.suggested_display_name, operation.path, operation.method].join(' '); selectionLabel.innerHTML = '' + '
' + escapeHtml(code) + ' ' : '')
+ escapeHtml(findingMessage(finding))
+ (pointer ? ' '
+ escapeHtml(pointer) + '' : '')
+ '';
}
function renderSkippedPanel(items) {
var page = 0;
var details = document.createElement('details');
var summary = document.createElement('summary');
var content = document.createElement('div');
var pageSize = OPERATIONS_PER_PAGE;
details.className = 'openapi-import-result-skipped';
summary.textContent = tfKey('openapi.result.skipped_count', { count: items.length });
content.className = 'openapi-import-result-skipped-page';
function renderPage() {
var list = document.createElement('ul');
items.slice(page * pageSize, (page + 1) * pageSize).forEach(function(item) {
var entry = document.createElement('li');
entry.textContent = (item.name || item.operation_key || tKey('openapi.result.unnamed')) + ' — '
+ findingMessage({ code: item.code || item.reason_code || item.reason });
list.appendChild(entry);
});
content.replaceChildren(list);
if (items.length > pageSize) {
content.appendChild(createPageNavigation(page, items.length, 'openapi.pagination.result_label', function(nextPage) {
page = nextPage;
renderPage();
}));
}
}
details.addEventListener('toggle', function() {
if (details.open && !content.childElementCount) renderPage();
});
details.append(summary, content);
return details;
}
function renderFindingsPanel(findings) {
if (!findings || !findings.length) return null;
var pageSize = 5;
var page = 0;
var details = document.createElement('details');
var summary = document.createElement('summary');
var content = document.createElement('div');
var pagination = document.createElement('div');
var previous = document.createElement('button');
var status = document.createElement('span');
var next = document.createElement('button');
details.className = 'openapi-import-findings';
summary.textContent = tfKey('openapi.findings.summary', { count: findings.length });
content.className = 'openapi-import-findings-page';
pagination.className = 'openapi-import-findings-pagination';
pagination.hidden = findings.length <= pageSize;
previous.type = 'button';
previous.className = 'btn-secondary';
previous.textContent = tKey('openapi.pagination.previous');
status.setAttribute('role', 'status');
status.setAttribute('aria-live', 'polite');
status.setAttribute('aria-atomic', 'true');
next.type = 'button';
next.className = 'btn-secondary';
next.textContent = tKey('openapi.pagination.next');
function renderPage() {
var pages = Math.max(1, Math.ceil(findings.length / pageSize));
content.innerHTML = findings.slice(page * pageSize, (page + 1) * pageSize).map(renderFinding).join('');
status.textContent = tfKey('openapi.pagination.status', { page: page + 1, pages: pages, total: findings.length });
previous.disabled = page === 0;
next.disabled = page + 1 >= pages;
}
previous.addEventListener('click', function() { page = Math.max(0, page - 1); renderPage(); });
next.addEventListener('click', function() {
page = Math.min(Math.ceil(findings.length / pageSize) - 1, page + 1);
renderPage();
});
details.addEventListener('toggle', function() {
if (details.open && !content.childElementCount) renderPage();
});
pagination.append(previous, status, next);
details.append(summary, content, pagination);
return details;
}
function createPageNavigation(page, total, labelKey, onPage) {
var pageCount = Math.max(1, Math.ceil(total / OPERATIONS_PER_PAGE));
var navigation = document.createElement('nav');
var previous = document.createElement('button');
var status = document.createElement('span');
var next = document.createElement('button');
navigation.className = 'openapi-import-pagination';
navigation.setAttribute('aria-label', tKey(labelKey));
navigation.setAttribute('role', 'navigation');
previous.type = 'button';
previous.className = 'btn-secondary';
previous.textContent = tKey('openapi.pagination.previous');
status.setAttribute('role', 'status');
status.setAttribute('aria-live', 'polite');
status.setAttribute('aria-atomic', 'true');
status.textContent = tfKey('openapi.pagination.status', {
page: page + 1, pages: pageCount, total: total,
});
next.type = 'button';
next.className = 'btn-secondary';
next.textContent = tKey('openapi.pagination.next');
previous.disabled = page === 0;
next.disabled = page + 1 >= pageCount;
previous.addEventListener('click', function() { onPage(Math.max(0, page - 1)); });
next.addEventListener('click', function() { onPage(Math.min(pageCount - 1, page + 1)); });
navigation.append(previous, status, next);
return navigation;
}
function findingMessage(finding) {
var code = String(finding && finding.code || '').replace(/^.*\./, '');
var known = {
missing_servers: 'openapi.finding.missing_servers',
multiple_servers: 'openapi.finding.multiple_servers',
unsupported_request_body: 'openapi.finding.unsupported_request_body',
unsupported_security_scheme: 'openapi.finding.unsupported_security_scheme',
unsupported_security_and_requirement: 'openapi.finding.unsupported_security_and_requirement',
auth_profile_required: 'openapi.error.auth_profile_required',
operation_name_renamed: 'openapi.finding.operation_name_renamed',
operation_name_conflict: 'openapi.finding.operation_name_conflict',
weak_tool_description: 'openapi.finding.weak_tool_description',
};
return tKey(known[code] || 'openapi.finding.generic');
}
function appendMappingGroup(root, label, values) {
if (!values || !values.length) return;
var group = document.createElement('div');
group.className = 'openapi-import-mapping-group';
var title = document.createElement('span');
title.className = 'openapi-import-mapping-label';
title.textContent = label;
group.appendChild(title);
values.slice(0, 8).forEach(function(value) {
var chip = document.createElement('code');
chip.className = 'openapi-import-mapping-chip';
chip.textContent = value;
group.appendChild(chip);
});
if (values.length > 8) {
var more = document.createElement('span');
more.className = 'openapi-import-mapping-more';
more.textContent = '+' + (values.length - 8);
group.appendChild(more);
}
root.appendChild(group);
}
function renderOperationMappingPreview(operation) {
var details = document.createElement('div');
var request = { path: [], query: [], headers: [], body: [] };
var inputRules = operation
&& operation.draft
&& operation.draft.input_mapping
&& Array.isArray(operation.draft.input_mapping.rules)
? operation.draft.input_mapping.rules
: [];
var outputRules = operation
&& operation.draft
&& operation.draft.output_mapping
&& Array.isArray(operation.draft.output_mapping.rules)
? operation.draft.output_mapping.rules
: [];
details.className = 'openapi-import-mapping-preview';
inputRules.forEach(function(rule) {
var target = String(rule.target || '');
if (target.indexOf('$.request.path.') === 0) {
request.path.push(target.slice(15));
} else if (target.indexOf('$.request.query.') === 0) {
request.query.push(target.slice(16));
} else if (target.indexOf('$.request.headers.') === 0) {
request.headers.push(target.slice(18));
} else if (target.indexOf('$.request.body.') === 0) {
request.body.push(target.slice(15));
} else if (target === '$.request.body') {
request.body.push('body');
}
});
appendMappingGroup(details, tKey('openapi.mapping.path'), request.path);
appendMappingGroup(details, tKey('openapi.mapping.query'), request.query);
appendMappingGroup(details, tKey('openapi.mapping.header'), request.headers);
appendMappingGroup(details, tKey('openapi.mapping.body'), request.body);
appendMappingGroup(details, tKey('openapi.mapping.response'), outputRules.map(function(rule) {
var target = String(rule.target || '').replace('$.output.', '').replace('$.output', 'result');
var source = String(rule.source || '').replace('$.response.body.', '').replace('$.response.body', 'body');
return target + ' ← ' + source;
}));
return details;
}
function populateServers(preview) {
var serverSelect = qs('openapi-import-server');
var servers = preview.source && preview.source.servers && preview.source.servers.length
? preview.source.servers
: [''];
serverSelect.replaceChildren();
servers.forEach(function(server) {
var option = document.createElement('option');
option.value = server;
option.textContent = server || tKey('openapi.server.required');
serverSelect.appendChild(option);
});
}
function populateMethodFilter(preview) {
var methodFilter = qs('openapi-import-method-filter');
var all = document.createElement('option');
var methods = Array.from(new Set((preview.groups || []).flatMap(function(group) {
return (group.operations || []).map(function(operation) {
return operation.method;
});
}))).sort();
methodFilter.replaceChildren();
all.value = '';
all.textContent = tKey('openapi.method.all');
methodFilter.appendChild(all);
methods.forEach(function(method) {
var option = document.createElement('option');
option.value = method;
option.textContent = method;
methodFilter.appendChild(option);
});
}
var SECURITY_STATUS_KEYS = {
no_auth: 'openapi.security.status_no_auth',
required: 'openapi.security.status_required',
unresolved: 'openapi.security.status_unresolved',
unverified: 'openapi.security.status_unverified',
resolved: 'openapi.security.status_resolved',
blocked: 'openapi.security.status_blocked',
};
var SECURITY_PLAN_ERROR_CODES = [
'import_plan_auth_unavailable',
'import_plan_auth_incompatible',
'import_plan_security_alternative_required',
];
function securityStatusLabel(status) {
return tKey(SECURITY_STATUS_KEYS[status] || SECURITY_STATUS_KEYS.unresolved);
}
function renderSecurityStatus() {
var node = qs('openapi-import-security-status');
if (!node) return;
node.textContent = securityStatusLabel(state.securityStatus);
}
function setSecurityStatus(status) {
state.securityStatus = status;
renderSecurityStatus();
}
function securityOperationNode(operationKey) {
// Compare dataset values against a constant selector: imported operation
// keys are untrusted and must never be interpolated into a CSS selector.
var nodes = document.querySelectorAll('[data-openapi-security-op-status]');
for (var i = 0; i < nodes.length; i += 1) {
if (nodes[i].dataset.openapiSecurityOpStatus === operationKey) return nodes[i];
}
return null;
}
function renderOperationSecurityStatus(operationKey) {
var node = securityOperationNode(operationKey);
if (!node) return;
var status = state.securityByOperation[operationKey] || 'unresolved';
node.dataset.status = status;
node.textContent = securityStatusLabel(status);
}
function setOperationSecurityStatus(operationKey, status) {
state.securityByOperation[operationKey] = status;
renderOperationSecurityStatus(operationKey);
}
// Summary only: the per-operation nodes carry the authority, this aggregate
// id reports whether any selected operation still needs attention.
function updateSecuritySummary() {
var selected = new Set(selectedKeys());
var statuses = [];
importOperations().forEach(function(operation) {
if (!selected.has(operation.key)) return;
statuses.push(state.securityByOperation[operation.key] || baselineSecurityStatus(operation));
});
var summary = 'unresolved';
if (statuses.indexOf('blocked') >= 0) summary = 'blocked';
else if (statuses.indexOf('required') >= 0) summary = 'required';
else if (statuses.indexOf('unverified') >= 0) summary = 'unverified';
else if (statuses.indexOf('resolved') >= 0) summary = 'resolved';
else if (statuses.length && statuses.every(function(status) { return status === 'no_auth'; })) summary = 'no_auth';
setSecurityStatus(summary);
}
function securityAlternativesFor(operation) {
var requirements = operation && operation.security_requirements;
return requirements && Array.isArray(requirements.alternatives) ? requirements.alternatives : [];
}
function alternativeFor(operation, index) {
if (index === null || index === undefined) return null;
return securityAlternativesFor(operation)[Number(index)] || null;
}
function isAnonymousAlternative(alternative) {
if (!alternative || alternative.supported === false) return false;
var schemes = Array.isArray(alternative.schemes) ? alternative.schemes : [];
return schemes.length === 0;
}
function operationRequiresAuth(operation) {
return securityAlternativesFor(operation).some(function(alternative) {
return alternative && alternative.supported !== false
&& Array.isArray(alternative.schemes) && alternative.schemes.length > 0;
});
}
function securityProfilesFor(operation, alternativeIndex) {
var profiles = [];
(state.securityChoices || []).forEach(function(choice) {
if (!choice || choice.operation_key !== operation.key) return;
// Filter to the exact selected alternative. While no alternative is
// chosen the safe union supports profile-first selection and lets the
// API own compatibility validation.
if (alternativeIndex !== null && alternativeIndex !== undefined
&& Number(choice.alternative_index) !== Number(alternativeIndex)) return;
if (Array.isArray(choice.profiles)) profiles = profiles.concat(choice.profiles);
});
// Keep a stable order across alternatives: first occurrence wins.
var seen = {};
return profiles.filter(function(profile) {
if (!profile || typeof profile.id !== 'string' || !profile.id || seen[profile.id]) return false;
seen[profile.id] = true;
return true;
});
}
// Local expectation only; resolved/blocked never originate here.
function baselineSecurityStatus(operation) {
var alternatives = securityAlternativesFor(operation);
if (!alternatives.length) return 'no_auth';
var decision = decisionFor(operation.key);
if (decision.action === 'skip') return 'unresolved';
if (!alternatives.some(function(alternative) { return alternative && alternative.supported !== false; })) {
return 'blocked';
}
if (!operationRequiresAuth(operation)) return 'no_auth';
var alternative = alternativeFor(operation, decision.securityAlternativeIndex);
if (isAnonymousAlternative(alternative)) return 'unresolved';
if (decision.authProfileId) return 'unresolved';
return 'required';
}
function resetSecurityStatuses() {
importOperations().forEach(function(operation) {
state.securityByOperation[operation.key] = baselineSecurityStatus(operation);
});
document.querySelectorAll('[data-openapi-security-op-status]').forEach(function(node) {
var key = node.dataset.openapiSecurityOpStatus;
var status = state.securityByOperation[key] || 'unresolved';
node.dataset.status = status;
node.textContent = securityStatusLabel(status);
});
updateSecuritySummary();
}
function operationRowFor(operation) {
return Array.from(document.querySelectorAll('.openapi-import-operation')).find(function(row) {
var input = row.querySelector('[data-openapi-operation]');
return input && input.value === operation.key;
}) || null;
}
function invalidatePendingPlan() {
// Even without a stored plan a prior blocked state must be cleared: the
// edited selection is unverified until the next plan response arrives.
if (state.plan) {
state.planRevalidationGeneration += 1;
state.plan = null;
state.planRevalidationState = 'current';
qs('openapi-import-plan-confirmation').hidden = true;
qs('openapi-import-plan-counts').replaceChildren();
qs('openapi-import-plan-candidates').replaceChildren();
qs('openapi-import-versioning-consequences').hidden = true;
qs('openapi-import-plan-blocked-help').hidden = true;
qs('openapi-import-plan-stale').hidden = true;
qs('openapi-import-plan-revalidation-status').textContent = '';
}
resetSecurityStatuses();
}
function renderSecurityControls(operation, row) {
var previous = row.querySelector('.openapi-import-security');
if (previous) previous.remove();
var decision = decisionFor(operation.key);
var alternatives = securityAlternativesFor(operation);
if (decision.action === 'skip') {
// A skipped operation keeps the existing operation untouched: no
// security binding may be attached, so clear it instead of trapping the
// user in a local validation error.
decision.authProfileId = null;
decision.securityAlternativeIndex = null;
setOperationSecurityStatus(operation.key, 'unresolved');
return;
}
var wrapper = document.createElement('div');
wrapper.className = 'openapi-import-security';
var statusNode = document.createElement('span');
statusNode.className = 'openapi-import-security-op-status';
statusNode.setAttribute('data-openapi-security-op-status', operation.key);
statusNode.setAttribute('data-testid', 'openapi-security-op-status');
// Announce per-operation changes even when the aggregate text is unchanged.
statusNode.setAttribute('role', 'status');
statusNode.setAttribute('aria-live', 'polite');
wrapper.appendChild(statusNode);
if (alternatives.length) {
var controls = document.createElement('div');
controls.className = 'openapi-import-security-controls';
// Only the alternative index and the typed profile id are stored locally.
// The API remains the authority for OR/AND semantics and compatibility.
var alternativeLabel = document.createElement('label');
var alternativeSelect = document.createElement('select');
alternativeLabel.textContent = tKey('openapi.security.alternative_label');
alternativeSelect.dataset.openapiSecurityAlternative = operation.key;
var alternativePlaceholder = document.createElement('option');
alternativePlaceholder.value = '';
alternativePlaceholder.textContent = tKey('openapi.security.alternative_placeholder');
alternativeSelect.appendChild(alternativePlaceholder);
var findingsNode = null;
alternatives.forEach(function(alternative, index) {
var option = document.createElement('option');
var schemes = alternative && Array.isArray(alternative.schemes) ? alternative.schemes : [];
option.value = String(index);
option.textContent = schemes.length ? schemes.join(' + ') : tKey('openapi.security.no_auth');
if (alternative && alternative.supported === false) {
option.disabled = true;
option.textContent += ' · ' + tKey('openapi.security.unsupported');
var finding = Array.isArray(alternative.findings) && alternative.findings[0];
// Surface the blocker as a safe, localized message next to the control.
if (finding) {
if (!findingsNode) {
findingsNode = document.createElement('span');
findingsNode.className = 'openapi-import-security-findings';
}
var findingSpan = document.createElement('span');
findingSpan.className = 'openapi-import-finding openapi-import-finding-warning';
findingSpan.textContent = findingMessage({ code: finding });
findingsNode.appendChild(findingSpan);
}
}
alternativeSelect.appendChild(option);
});
alternativeSelect.value = decision.securityAlternativeIndex === null
? ''
: String(decision.securityAlternativeIndex);
alternativeSelect.addEventListener('change', function() {
// Switching the alternative invalidates the previous profile binding and
// any server-confirmed plan: the API revalidates the current selection.
decision.securityAlternativeIndex = alternativeSelect.value === ''
? null
: Number(alternativeSelect.value);
decision.authProfileId = null;
invalidatePendingPlan();
renderSecurityControls(operation, row);
});
alternativeLabel.appendChild(alternativeSelect);
controls.appendChild(alternativeLabel);
if (findingsNode) controls.appendChild(findingsNode);
var selectedAlternative = alternativeFor(operation, decision.securityAlternativeIndex);
var anonymous = isAnonymousAlternative(selectedAlternative);
var profiles = securityProfilesFor(operation, decision.securityAlternativeIndex);
// An anonymous alternative must offer no profile at all.
if (!anonymous) {
var profileLabel = document.createElement('label');
var profileSelect = document.createElement('select');
profileLabel.textContent = tKey('openapi.security.profile_label');
profileSelect.dataset.openapiSecurityProfile = operation.key;
var profilePlaceholder = document.createElement('option');
profilePlaceholder.value = '';
profilePlaceholder.textContent = tKey('openapi.security.profile_placeholder');
profileSelect.appendChild(profilePlaceholder);
profiles.forEach(function(profile) {
// Safe metadata only: id, name, kind. Never credential material.
var option = document.createElement('option');
option.value = profile.id;
option.textContent = String(profile.name || profile.id);
if (profile.kind) option.textContent += ' · ' + profile.kind;
profileSelect.appendChild(option);
});
var emptyProfiles = decision.securityAlternativeIndex !== null
&& selectedAlternative && selectedAlternative.supported !== false
&& !anonymous && profiles.length === 0;
if (emptyProfiles) {
profileSelect.disabled = true;
var guidance = document.createElement('span');
guidance.className = 'openapi-import-security-guidance';
guidance.textContent = tKey('openapi.security.empty_profiles');
profileLabel.appendChild(guidance);
}
profileSelect.value = decision.authProfileId || '';
profileSelect.addEventListener('change', function() {
decision.authProfileId = profileSelect.value || null;
invalidatePendingPlan();
});
profileLabel.appendChild(profileSelect);
controls.appendChild(profileLabel);
}
wrapper.appendChild(controls);
}
row.appendChild(wrapper);
setOperationSecurityStatus(operation.key, baselineSecurityStatus(operation));
}
function renderPreview(response) {
var preview = response.preview;
var count = (preview.groups || []).reduce(function(sum, group) {
return sum + (group.operations || []).length;
}, 0);
var source = qs('openapi-import-source');
state.jobId = response.job_id;
state.preview = preview;
state.existingOperations = [];
state.operationsReady = false;
state.decisions = Object.create(null);
state.securityChoices = Array.isArray(response.security_profile_choices)
? response.security_profile_choices
: [];
state.securityByOperation = Object.create(null);
state.operationGroups = preview.groups || [];
state.selectedOperationKeys = new Set(importOperations().map(function(operation) { return operation.key; }));
state.pageIndex = 0;
state.partialMode = false;
qs('openapi-import-partial-mode').checked = false;
importOperations().forEach(function(operation) { decisionFor(operation.key); });
state.filterQuery = '';
state.filterMethod = '';
qs('openapi-import-preview-panel').hidden = false;
qs('openapi-import-result').hidden = true;
qs('openapi-import-result').replaceChildren();
source.textContent = tfKey('openapi.source.summary', {
name: boundedFileName(state.file),
size: formatSize(state.file.size),
count: count,
});
qs('openapi-import-search').value = '';
populateServers(preview);
populateMethodFilter(preview);
renderOperationPage();
updateSelection();
}
function validateFile(file) {
if (!file) return 'openapi.error.file_required';
var name = String(file.name || '').toLowerCase();
var yaml = /\.(yaml|yml)$/.test(name);
var json = /\.json$/.test(name);
if (!yaml && !json) return 'openapi.error.file_type';
if (!file.size) return 'openapi.error.file_empty';
if (file.size > MAX_FILE_BYTES) return 'openapi.error.file_large';
var type = String(file.type || '').toLowerCase();
if (!type || type === 'application/octet-stream') return null;
var allowed = yaml
? ['application/yaml', 'application/x-yaml', 'text/yaml', 'text/x-yaml']
: ['application/json', 'application/openapi+json'];
return allowed.indexOf(type) >= 0 ? null : 'openapi.error.file_type';
}
function abort(controller) {
if (controller) controller.abort();
}
function clearPreview() {
state.planRevalidationGeneration += 1;
state.planVersion = 0;
state.planRevalidationState = 'current';
state.jobId = null;
state.preview = null;
state.existingOperations = [];
state.operationsReady = false;
state.decisions = Object.create(null);
state.securityChoices = [];
state.securityStatus = 'unresolved';
state.securityByOperation = Object.create(null);
state.operationGroups = [];
state.selectedOperationKeys = new Set();
state.pageIndex = 0;
state.partialMode = false;
qs('openapi-import-partial-mode').checked = false;
state.plan = null;
state.applyRequest = null;
state.applyMetadata = [];
state.applyResult = null;
state.applyOutcomeUnknown = false;
state.applyRefreshFailed = false;
state.filterQuery = '';
state.filterMethod = '';
qs('openapi-import-preview-panel').hidden = true;
qs('openapi-import-plan-confirmation').hidden = true;
qs('openapi-import-plan-counts').replaceChildren();
qs('openapi-import-plan-candidates').replaceChildren();
qs('openapi-import-plan-pagination').hidden = true;
qs('openapi-import-versioning-consequences').hidden = true;
qs('openapi-import-plan-blocked-help').hidden = true;
qs('openapi-import-plan-stale').hidden = true;
qs('openapi-import-plan-revalidation-status').textContent = '';
qs('openapi-import-groups').replaceChildren();
qs('openapi-import-pagination').hidden = true;
qs('openapi-import-page-previous').disabled = true;
qs('openapi-import-page-next').disabled = true;
qs('openapi-import-select-visible').disabled = true;
qs('openapi-import-clear-visible').disabled = true;
renderSecurityStatus();
qs('openapi-import-result').hidden = true;
qs('openapi-import-result').replaceChildren();
updateSelection();
}
function clearServerSelection() {
qs('openapi-import-server-custom').value = '';
qs('openapi-import-server').replaceChildren();
}
function invalidate(options) {
state.revision += 1;
abort(state.previewController);
abort(state.planController);
abort(state.applyController);
state.previewController = null;
state.planController = null;
state.applyController = null;
state.applyInFlight = false;
qs('openapi-import-preview').disabled = false;
qs('openapi-import-create').disabled = false;
qs('openapi-import-plan-apply').disabled = false;
qs('openapi-import-plan-back').disabled = false;
qs('openapi-import-file-select').disabled = false;
qs('openapi-import-reset').disabled = false;
qs('openapi-import-cancel').hidden = true;
clearPreview();
if (options && options.clearFile) {
state.file = null;
qs('openapi-import-file').value = '';
renderFileName();
}
}
function showRetry(show) {
qs('openapi-import-retry').hidden = !show;
}
function lockApplyInputs(locked) {
qs('openapi-import-create').disabled = locked;
qs('openapi-import-preview').disabled = locked;
qs('openapi-import-file-select').disabled = locked;
qs('openapi-import-reset').disabled = locked;
qs('openapi-import-plan-apply').disabled = locked;
qs('openapi-import-plan-back').disabled = locked;
qs('openapi-import-server').disabled = locked;
qs('openapi-import-server-custom').disabled = locked;
qs('openapi-import-search').disabled = locked;
qs('openapi-import-method-filter').disabled = locked;
qs('openapi-import-select-visible').disabled = locked || !state.partialMode;
qs('openapi-import-clear-visible').disabled = locked || !state.partialMode;
qs('openapi-import-partial-mode').disabled = locked || documentIsBlocked();
qs('openapi-import-page-previous').disabled = locked || state.pageIndex === 0;
qs('openapi-import-page-next').disabled = locked || state.pageIndex + 1 >= Math.ceil(filteredOperationGroups().reduce(function(sum, group) { return sum + group.operations.length; }, 0) / OPERATIONS_PER_PAGE);
document.querySelectorAll('[data-openapi-operation], [data-openapi-group]').forEach(function(input) {
var row = input.closest('.openapi-import-operation');
var operation = row && importOperations().find(function(candidate) {
return candidate.key === input.value;
});
input.disabled = locked || !state.partialMode || documentIsBlocked()
|| (input.matches('[data-openapi-operation]') && operationIsBlocked(operation));
});
document.querySelectorAll('.openapi-import-decision-controls select, .openapi-import-decision-controls input').forEach(function(input) {
input.disabled = locked;
});
document.querySelectorAll('.openapi-import-security-controls select, .openapi-import-security-controls input').forEach(function(input) {
input.disabled = locked;
});
}
function lockPlanEditing(locked) {
qs('openapi-import-create').disabled = locked;
qs('openapi-import-preview').disabled = locked;
qs('openapi-import-file-select').disabled = locked;
qs('openapi-import-reset').disabled = locked;
qs('openapi-import-server').disabled = locked;
qs('openapi-import-server-custom').disabled = locked;
qs('openapi-import-search').disabled = locked;
qs('openapi-import-method-filter').disabled = locked;
qs('openapi-import-select-visible').disabled = locked || !state.partialMode;
qs('openapi-import-clear-visible').disabled = locked || !state.partialMode;
qs('openapi-import-partial-mode').disabled = locked || documentIsBlocked();
qs('openapi-import-page-previous').disabled = locked || state.pageIndex === 0;
qs('openapi-import-page-next').disabled = locked || state.pageIndex + 1 >= Math.ceil(filteredOperationGroups().reduce(function(sum, group) { return sum + group.operations.length; }, 0) / OPERATIONS_PER_PAGE);
document.querySelectorAll('[data-openapi-operation], [data-openapi-group]').forEach(function(input) {
var row = input.closest('.openapi-import-operation');
var operation = row && importOperations().find(function(candidate) {
return candidate.key === input.value;
});
input.disabled = locked || !state.partialMode || documentIsBlocked()
|| (input.matches('[data-openapi-operation]') && operationIsBlocked(operation));
});
document.querySelectorAll('.openapi-import-decision-controls select, .openapi-import-decision-controls input').forEach(function(input) {
input.disabled = locked;
});
document.querySelectorAll('.openapi-import-security-controls select, .openapi-import-security-controls input').forEach(function(input) {
input.disabled = locked;
});
}
function markApplyOutcomeUnknown(options) {
if (!state.applyRequest) return false;
abort(state.applyController);
state.applyController = null;
state.applyInFlight = false;
state.applyOutcomeUnknown = true;
persistApplyReplay(state.applyRequest);
// Until the same plan is replayed, starting another import could hide an
// already committed server outcome and lead to duplicate drafts.
lockApplyInputs(true);
qs('openapi-import-cancel').hidden = true;
if (!options || options.render !== false) {
showRetry(true);
setStatus(tKey('openapi.plan.retry_unknown'), true, true);
}
return true;
}
function cancelCurrent() {
if (state.applyInFlight || state.applyController) {
markApplyOutcomeUnknown();
return;
}
if (state.planController) {
abort(state.planController);
state.planController = null;
state.revision += 1;
lockPlanEditing(false);
qs('openapi-import-cancel').hidden = true;
showRetry(false);
setStatus(tKey('openapi.status.cancelled'));
return;
}
if (!state.previewController) return;
invalidate();
showRetry(!!state.file);
setStatus(tKey('openapi.status.cancelled'));
}
function errorStatus(error, fallback) {
var known = {
'openapi_upload.missing_file': 'openapi.error.file_required',
'openapi_upload.invalid_media_type': 'openapi.error.file_type',
'openapi_upload.empty_file': 'openapi.error.file_empty',
'openapi_upload.file_too_large': 'openapi.error.file_large',
'openapi_upload.no_methods': 'openapi.error.no_methods',
'openapi_upload.malformed_multipart': 'openapi.error.malformed_multipart',
'openapi_upload.invalid_utf8': 'openapi.error.invalid_utf8',
'openapi_upload.invalid_document': 'openapi.error.invalid_document',
'openapi_upload.parser_unavailable': 'openapi.error.parser_unavailable',
'openapi_upload.storage_unavailable': 'openapi.error.storage_unavailable',
'openapi_upload.source_integrity': 'openapi.error.source_integrity',
'openapi_upload.source_unavailable': 'openapi.error.source_unavailable',
'import_plan_auth_unavailable': 'openapi.error.auth_unavailable',
'import_plan_auth_incompatible': 'openapi.error.auth_incompatible',
'import_plan_security_alternative_required': 'openapi.error.security_alternative_required',
};
var message = tKey(known[error && error.code] || fallback);
var identifiers = [];
if (error && error.requestId) {
identifiers.push(tfKey('openapi.correlation.request_id', { id: error.requestId }));
}
if (error && error.traceId) {
identifiers.push(tfKey('openapi.correlation.trace_id', { id: error.traceId }));
}
return identifiers.length ? message + ' ' + identifiers.join(' · ') : message;
}
async function preview() {
var localError = validateFile(state.file);
if (localError) {
setStatus(tKey(localError), true, true);
showRetry(false);
return;
}
if (!state.workspaceId) {
setStatus(tKey('openapi.error.workspace'), true, true);
return;
}
invalidate();
var revision = state.revision;
var workspaceId = state.workspaceId;
var language = locale();
var controller = new AbortController();
state.previewController = controller;
qs('openapi-import-preview').disabled = true;
qs('openapi-import-cancel').hidden = false;
showRetry(false);
setStatus(tKey('openapi.status.uploading'));
try {
var response = await window.CrankApi.previewOpenApiImport(workspaceId, state.file, { signal: controller.signal });
if (!isCurrent(revision, workspaceId, language)) return;
setStatus(tKey('openapi.status.parsing'));
await new Promise(function(resolve) { window.requestAnimationFrame(resolve); });
if (!isCurrent(revision, workspaceId, language)) return;
renderPreview(response);
qs('openapi-import-create').disabled = true;
setStatus(tKey('openapi.status.loading_operations'));
var operationResponse = await window.CrankApi.listOperations(workspaceId);
if (!isCurrent(revision, workspaceId, language)) return;
if (!operationResponse || !Array.isArray(operationResponse.items)) {
throw new Error('Backend returned an invalid operations list response');
}
state.existingOperations = operationResponse.items;
state.operationsReady = true;
importOperations().forEach(function(operation) {
var row = operationRowFor(operation);
if (row) {
renderDecisionControls(operation, row);
renderSecurityControls(operation, row);
}
});
qs('openapi-import-create').disabled = false;
setStatus(tKey('openapi.status.preview_ready'));
} catch (error) {
if (!isCurrent(revision, workspaceId, language)) return;
if (error && error.name === 'AbortError') {
setStatus(tKey('openapi.status.cancelled'));
return;
}
clearPreview();
showRetry(true);
setStatus(errorStatus(error, 'openapi.error.preview'), true, true);
} finally {
if (isCurrent(revision, workspaceId, language)) {
state.previewController = null;
qs('openapi-import-preview').disabled = false;
qs('openapi-import-cancel').hidden = true;
}
}
}
function previewOperationForCreated(created) {
var groups = state.preview && state.preview.groups || [];
for (var groupIndex = 0; groupIndex < groups.length; groupIndex += 1) {
var operations = groups[groupIndex].operations || [];
for (var operationIndex = 0; operationIndex < operations.length; operationIndex += 1) {
if (created.operation_key && operations[operationIndex].key === created.operation_key) {
return operations[operationIndex];
}
}
}
// Older servers did not return operation_key. Keep result rendering useful
// during a rolling upgrade, but use the unambiguous key whenever it exists.
for (var fallbackGroupIndex = 0; fallbackGroupIndex < groups.length; fallbackGroupIndex += 1) {
var fallbackOperations = groups[fallbackGroupIndex].operations || [];
for (var fallbackOperationIndex = 0; fallbackOperationIndex < fallbackOperations.length; fallbackOperationIndex += 1) {
if (fallbackOperations[fallbackOperationIndex].suggested_name === created.name) {
return fallbackOperations[fallbackOperationIndex];
}
}
}
for (var metadataIndex = 0; metadataIndex < state.applyMetadata.length; metadataIndex += 1) {
if (created.operation_key && state.applyMetadata[metadataIndex].key === created.operation_key) {
return state.applyMetadata[metadataIndex];
}
}
return null;
}
function wizardHref(operationId) {
return ((window.CrankRoutes && window.CrankRoutes.wizard) || '/wizard/')
+ '?mode=edit&operationId=' + encodeURIComponent(operationId);
}
function appendFindingNodes(root, findings) {
if (!findings || !findings.length) {
var empty = document.createElement('span');
empty.className = 'openapi-import-result-ok';
empty.textContent = tKey('openapi.result.no_findings');
root.appendChild(empty);
return;
}
root.appendChild(renderFindingsPanel(findings));
}
function renderResult(response) {
var node = qs('openapi-import-result');
var title = document.createElement('strong');
node.replaceChildren();
title.textContent = tKey('openapi.result.title');
node.appendChild(title);
if (response.created && response.created.length) {
var primary = document.createElement('div');
var table = document.createElement('div');
primary.className = 'openapi-import-primary-result';
primary.innerHTML = ''
+ escapeHtml(tKey('openapi.result.open_first'))
+ '';
node.appendChild(primary);
table.className = 'openapi-import-result-table';
table.setAttribute('role', 'table');
table.innerHTML = '