(function() { var MAX_FILE_BYTES = 256 * 1024; 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: '', 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 Array.from(document.querySelectorAll('[data-openapi-operation]:checked')) .map(function(input) { return input.value; }); } function importOperations() { return (state.preview && state.preview.groups || []).flatMap(function(group) { return group.operations || []; }); } function decisionFor(operationKey) { if (!state.decisions[operationKey]) { state.decisions[operationKey] = { action: 'create', targetOperationId: '', confirmedName: '', 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; 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 = document.querySelectorAll('[data-openapi-operation]').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.filter(function(row) { var input = row.querySelector('[data-openapi-operation]'); return input && input.checked; }).length; 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() { var query = state.filterQuery.toLowerCase(); var method = state.filterMethod.toLowerCase(); document.querySelectorAll('.openapi-import-group').forEach(function(groupNode) { var visibleInGroup = 0; groupNode.querySelectorAll('.openapi-import-operation').forEach(function(row) { var matchesMethod = !method || String(row.dataset.openapiMethod).toLowerCase() === method; var matchesQuery = !query || String(row.dataset.openapiSearch).toLowerCase().indexOf(query) >= 0; var visible = matchesMethod && matchesQuery; row.hidden = !visible; if (visible) visibleInGroup += 1; }); groupNode.hidden = visibleInGroup === 0; }); updateSelection(); } function setVisibleSelection(checked) { visibleOperationRows().forEach(function(row) { var input = row.querySelector('[data-openapi-operation]'); if (input) input.checked = checked; }); updateSelection(); } function escapeHtml(value) { return String(value || '') .replace(/&/g, '&') .replace(//g, '>') .replace(/"/g, '"'); } function renderFinding(finding) { var severity = String(finding && finding.severity || 'warning').toLowerCase(); var label = severity === 'info' ? 'i' : severity === 'error' ? '×' : '!'; return '' + '' + label + ' ' + escapeHtml(findingMessage(finding)) + ''; } 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); renderOperationSecurityStatus(operation.key); }); 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.plan = null; 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; } 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'); var groupsNode = qs('openapi-import-groups'); 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); 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); groupsNode.replaceChildren(); if (preview.findings && preview.findings.length) { var documentFindings = document.createElement('div'); documentFindings.className = 'openapi-import-document-findings'; documentFindings.innerHTML = preview.findings.map(renderFinding).join(''); groupsNode.appendChild(documentFindings); } (preview.groups || []).forEach(function(group) { var groupNode = document.createElement('section'); var header = document.createElement('div'); groupNode.className = 'openapi-import-group'; header.className = 'openapi-import-group-header'; header.innerHTML = '' + escapeHtml(group.title) + ' · ' + group.operations.length + '' + '' + ''; groupNode.appendChild(header); group.operations.forEach(function(operation) { 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 = [ group.title, operation.key, operation.suggested_name, operation.suggested_display_name, operation.path, operation.method, ].join(' '); selectionLabel.innerHTML = '' + '
' + escapeHtml(operation.suggested_display_name) + '
' + '
' + escapeHtml(operation.suggested_name) + ' · ' + escapeHtml(operation.path) + ' · ' + escapeHtml(tfKey('openapi.operation.fields', { input: operation.input_fields, output: operation.output_fields })) + '
' + escapeHtml(operation.method) + ''; row.appendChild(selectionLabel); row.appendChild(renderOperationMappingPreview(operation)); if (operation.findings && operation.findings.length) { var findings = document.createElement('div'); findings.className = 'openapi-import-findings'; findings.innerHTML = operation.findings.map(renderFinding).join(''); row.appendChild(findings); } renderDecisionControls(operation, row); renderSecurityControls(operation, row); groupNode.appendChild(row); }); groupNode.querySelector('[data-openapi-group]').addEventListener('change', function(event) { groupNode.querySelectorAll('.openapi-import-operation').forEach(function(row) { var input = row.querySelector('[data-openapi-operation]'); if (!row.hidden && input) input.checked = event.target.checked; }); updateSelection(); }); groupsNode.appendChild(groupNode); }); groupsNode.querySelectorAll('[data-openapi-operation]').forEach(function(input) { input.addEventListener('change', updateSelection); }); applyFilters(); resetSecurityStatuses(); } 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.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.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-versioning-consequences').hidden = true; qs('openapi-import-plan-blocked-help').hidden = true; qs('openapi-import-groups').replaceChildren(); 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; qs('openapi-import-clear-visible').disabled = locked; document.querySelectorAll('[data-openapi-operation], [data-openapi-group]').forEach(function(input) { input.disabled = locked; }); 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; qs('openapi-import-clear-visible').disabled = locked; document.querySelectorAll('[data-openapi-operation], [data-openapi-group]').forEach(function(input) { input.disabled = locked; }); 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.previewing')); try { var response = await window.CrankApi.previewOpenApiImport(workspaceId, state.file, { signal: controller.signal }); 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; } findings.slice(0, 4).forEach(function(finding) { var wrapper = document.createElement('div'); wrapper.innerHTML = renderFinding(finding); root.appendChild(wrapper.firstElementChild); }); if (findings.length > 4) { var more = document.createElement('span'); more.className = 'openapi-import-result-more'; more.textContent = tfKey('openapi.result.more', { count: findings.length - 4 }); root.appendChild(more); } } 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 = '
' + '
' + escapeHtml(tKey('openapi.result.draft')) + '
' + '
' + escapeHtml(tKey('openapi.result.findings')) + '
' + '
' + escapeHtml(tKey('openapi.result.action')) + '
' + '
'; response.created.forEach(function(operation) { var previewOperation = previewOperationForCreated(operation); var row = document.createElement('div'); var nameCell = document.createElement('div'); var name = document.createElement('div'); var meta = document.createElement('div'); var findingsCell = document.createElement('div'); var actionCell = document.createElement('div'); var action = document.createElement('a'); row.className = 'openapi-import-result-row'; row.setAttribute('role', 'row'); nameCell.setAttribute('role', 'cell'); name.className = 'openapi-import-result-name'; name.textContent = operation.name; meta.className = 'openapi-import-result-meta'; meta.textContent = previewOperation ? previewOperation.method + ' ' + previewOperation.path + ' · v' + operation.version : 'v' + operation.version; nameCell.append(name, meta); findingsCell.className = 'openapi-import-result-findings'; findingsCell.setAttribute('role', 'cell'); appendFindingNodes(findingsCell, previewOperation && previewOperation.findings); actionCell.setAttribute('role', 'cell'); action.className = 'btn-secondary openapi-import-result-action'; action.href = wizardHref(operation.operation_id); action.textContent = previewOperation && previewOperation.findings && previewOperation.findings.length ? tKey('openapi.result.fix') : tKey('openapi.result.open'); actionCell.appendChild(action); row.append(nameCell, findingsCell, actionCell); table.appendChild(row); }); node.appendChild(table); } if (response.skipped && response.skipped.length) { var skippedNode = document.createElement('div'); skippedNode.className = 'openapi-import-result-skipped'; skippedNode.textContent = tKey('openapi.result.skipped') + ': ' + response.skipped.map(function(item) { return (item.name || item.operation_key || tKey('openapi.result.unnamed')) + ' — ' + findingMessage({ code: item.code || item.reason_code || item.reason }); }).join('; '); node.appendChild(skippedNode); } if (response.findings && response.findings.length) { var findings = document.createElement('div'); findings.className = 'openapi-import-result-findings'; findings.innerHTML = response.findings.map(renderFinding).join(''); node.appendChild(findings); } node.hidden = false; } function createdStatus(response) { if (response && response.counts) { return tfKey('openapi.plan.summary', { applied: (Number(response.counts.created) || 0) + (Number(response.counts.versioned) || 0) + (Number(response.counts.renamed) || 0), skipped: Number(response.counts.skipped) || 0, excluded: Number(response.counts.excluded) || 0, rejected: Number(response.counts.rejected) || 0, }); } return tfKey('openapi.status.created', { created: (response.created || []).length, skipped: (response.skipped || []).length, }); } function planActionLabel(candidate) { if (candidate.state === 'excluded') return tKey('openapi.plan.action.excluded'); if (candidate.state === 'blocked') return tKey('openapi.plan.action.blocked'); var action = String(candidate.action || 'create'); var key = 'openapi.plan.action.' + action; return tKey(key) === key ? tKey('openapi.plan.action.create') : tKey(key); } function renderImportPlan(plan) { var countsNode = qs('openapi-import-plan-counts'); var candidatesNode = qs('openapi-import-plan-candidates'); var versioningNode = qs('openapi-import-versioning-consequences'); var counts = plan.counts || {}; var hasBlocked = (Number(counts.blocked) || 0) > 0; var operationsByKey = Object.create(null); importOperations().forEach(function(operation) { operationsByKey[operation.key] = operation; }); // The plan API is the sole authority for each operation's binding outcome. (Array.isArray(plan.candidates) ? plan.candidates : []).forEach(function(candidate) { if (!candidate || !candidate.key) return; var operation = operationsByKey[candidate.key]; var alternativeIndex = candidate.security_alternative_index; var anonymous = alternativeIndex !== null && alternativeIndex !== undefined && isAnonymousAlternative(alternativeFor(operation, alternativeIndex)); var status; if (candidate.state === 'blocked') { status = 'blocked'; } else if (candidate.state === 'actionable') { // Only a genuine auth binding confirmed by the API is resolved; a // no-auth/anonymous or unbound candidate must never read as resolved. if (candidate.auth_profile_id) status = 'resolved'; else if (operation && !operationRequiresAuth(operation)) status = 'no_auth'; else if (anonymous) status = 'no_auth'; else status = 'unresolved'; } else { // Excluded/skipped candidates keep the operation untouched. status = 'unresolved'; } setOperationSecurityStatus(candidate.key, status); }); updateSecuritySummary(); var countSpecs = [ ['selected', 'openapi.plan.selected'], ['excluded', 'openapi.plan.excluded'], ['actionable', 'openapi.plan.actionable'], ['blocked', 'openapi.plan.blocked'], ]; countsNode.replaceChildren(); candidatesNode.replaceChildren(); countSpecs.forEach(function(spec) { var item = document.createElement('span'); item.className = 'openapi-import-plan-count'; item.textContent = tfKey(spec[1], { count: Number(counts[spec[0]]) || 0 }); countsNode.appendChild(item); }); var hasNewVersion = false; (Array.isArray(plan.candidates) ? plan.candidates : []).forEach(function(candidate) { var item = document.createElement('article'); var title = document.createElement('strong'); var key = document.createElement('code'); var action = document.createElement('p'); item.className = 'openapi-import-plan-candidate'; item.dataset.state = String(candidate.state || 'blocked'); title.textContent = String(candidate.name || candidate.key || tKey('openapi.result.unnamed')); key.textContent = String(candidate.key || ''); action.textContent = planActionLabel(candidate); item.append(title, key, action); if (candidate.target_operation_id) { var target = document.createElement('p'); target.textContent = tKey('openapi.plan.exact_target') + ': ' + candidate.target_operation_id; item.appendChild(target); } if (candidate.confirmed_name) { var confirmedName = document.createElement('p'); confirmedName.textContent = tKey('openapi.plan.confirmed_name') + ': ' + candidate.confirmed_name; item.appendChild(confirmedName); } if (candidate.action === 'new_version' && candidate.state !== 'blocked' && candidate.state !== 'excluded') { hasNewVersion = true; } if (candidate.reason) { var reason = document.createElement('p'); reason.className = 'openapi-import-plan-reason'; reason.textContent = findingMessage({ code: candidate.reason }); item.appendChild(reason); } candidatesNode.appendChild(item); }); versioningNode.textContent = tKey('openapi.plan.versioning_new'); versioningNode.hidden = !hasNewVersion; qs('openapi-import-plan-confirmation').hidden = false; qs('openapi-import-plan-blocked-help').hidden = !hasBlocked; qs('openapi-import-result').hidden = true; qs('openapi-import-plan-apply').disabled = hasBlocked; qs('openapi-import-plan-back').textContent = tKey(hasBlocked ? 'openapi.plan.back_fix' : 'openapi.plan.back'); lockPlanEditing(true); } function reportOutcomeLabel(outcome) { var value = String(outcome || 'rejected'); var key = 'openapi.plan.outcome.' + value; return tKey(key) === key ? tKey('openapi.plan.outcome.rejected') : tKey(key); } function renderImportPlanReport(report) { var node = qs('openapi-import-result'); var title = document.createElement('strong'); node.replaceChildren(); title.textContent = tKey('openapi.plan.result_title'); node.appendChild(title); var counts = report.counts || {}; var applied = (Number(counts.created) || 0) + (Number(counts.versioned) || 0) + (Number(counts.renamed) || 0); var summary = document.createElement('p'); summary.className = 'openapi-import-plan-summary'; summary.textContent = tfKey('openapi.plan.summary', { applied: applied, skipped: Number(counts.skipped) || 0, excluded: Number(counts.excluded) || 0, rejected: Number(counts.rejected) || 0, }); node.appendChild(summary); var outcomes = Array.isArray(report.outcomes) ? report.outcomes : []; if (outcomes.length) { var list = document.createElement('div'); list.className = 'openapi-import-plan-outcomes'; outcomes.forEach(function(outcome) { var item = document.createElement('article'); var heading = document.createElement('strong'); var key = document.createElement('code'); var detail = document.createElement('p'); var outcomeStatus = outcome.status || outcome.outcome || 'rejected'; item.className = 'openapi-import-plan-outcome'; item.dataset.outcome = String(outcomeStatus); heading.textContent = String(outcome.name || outcome.key || tKey('openapi.result.unnamed')); key.textContent = String(outcome.key || ''); detail.textContent = reportOutcomeLabel(outcomeStatus); if (Number.isInteger(outcome.version)) { detail.textContent += ' · v' + outcome.version; } item.append(heading, key, detail); if (outcome.reason) { var reason = document.createElement('p'); reason.className = 'openapi-import-plan-reason'; reason.textContent = findingMessage({ code: outcome.reason }); item.appendChild(reason); } list.appendChild(item); }); node.appendChild(list); } node.hidden = false; qs('openapi-import-plan-confirmation').hidden = true; } function recoveryCode(payload) { var value = payload && payload.error && typeof payload.error === 'object' ? payload.error : payload; var context = value && value.context && typeof value.context === 'object' ? value.context : value; return String((context && context.recovery) || (payload && payload.recovery) || ''); } function reportFromPayload(payload) { if (!payload || typeof payload !== 'object') return null; var errorContext = payload.error && payload.error.context; var report = payload.report || payload.apply_report || (errorContext && (errorContext.report || errorContext.apply_report || errorContext)) || payload; return report && Array.isArray(report.outcomes) ? report : null; } async function notifyImported(revision, workspaceId, language) { if (typeof state.onImported !== 'function') return; try { await state.onImported(); } catch (_error) { state.applyRefreshFailed = true; if (isCurrent(revision, workspaceId, language) && state.applyResult) { setStatus(createdStatus(state.applyResult) + ' ' + tKey('openapi.status.refresh_failed'), false, true); } } } async function submitApply(request) { if (state.applyInFlight) return; var revision = state.revision; var workspaceId = request.workspaceId; var language = locale(); var controller = new AbortController(); state.applyController = controller; state.applyInFlight = true; state.applyOutcomeUnknown = false; state.applyRefreshFailed = false; lockApplyInputs(true); qs('openapi-import-cancel').hidden = false; showRetry(false); setStatus(tKey('openapi.status.applying')); try { var response = await window.CrankApi.applyOpenApiImportPlan( workspaceId, request.planReference, { plan_digest: request.planDigest, idempotency_key: request.idempotencyKey, }, { signal: controller.signal } ); // Abort is advisory: a superseded request can still deliver a response. // Only the controller installed by this attempt may mutate UI authority. if (state.applyController !== controller) return; state.applyOutcomeUnknown = false; clearApplyReplay(); state.applyController = null; state.applyInFlight = false; lockApplyInputs(false); qs('openapi-import-cancel').hidden = true; showRetry(false); if (!isSameContext(revision, workspaceId, language)) { // The original workspace job is now resolved. Do not render its result // into another workspace/language context. state.applyResult = null; state.applyRequest = null; return; } state.applyResult = response; state.applyRequest = null; state.plan = null; if (isCurrent(revision, workspaceId, language)) { renderImportPlanReport(response); if (response.recovery === 'repreview_required') { setStatus(tKey('openapi.plan.repreview'), true, true); showRetry(true); } else if (response.status === 'rejected' || response.recovery === 'confirm_skip_rename_or_new_version') { setStatus(tKey('openapi.plan.resolve_conflict'), true, true); showRetry(true); } else { setStatus(tKey('openapi.status.applied')); } } await notifyImported(revision, workspaceId, language); } catch (error) { // A cancelled attempt may settle after an idempotent retry has already // installed a new controller. It must not overwrite the newer state. if (state.applyController !== controller) return; if (error && error.name === 'AbortError') { state.applyOutcomeUnknown = true; persistApplyReplay(state.applyRequest); lockApplyInputs(true); showRetry(true); if (!qs('openapi-import-modal').hidden) { setStatus(tKey('openapi.plan.retry_unknown'), true, true); } return; } if (Number.isInteger(error && error.status) && error.status >= 400 && error.status < 500 && error.status !== 408) { state.applyOutcomeUnknown = false; state.applyRequest = null; clearApplyReplay(); showRetry(true); var report = reportFromPayload(error.payload); if (report && isCurrent(revision, workspaceId, language)) { state.applyResult = report; renderImportPlanReport(report); } var recovery = recoveryCode(error.payload); state.plan = null; qs('openapi-import-plan-confirmation').hidden = true; lockPlanEditing(false); // A rejected/repreview Apply voids the prior resolved security review. resetSecurityStatuses(); if (!qs('openapi-import-modal').hidden) { if (recovery === 'repreview_required') { setStatus(tKey('openapi.plan.repreview'), true, true); } else if (recovery === 'confirm_skip_rename_or_new_version') { setStatus(tKey('openapi.plan.resolve_conflict'), true, true); } else { setStatus(errorStatus(error, 'openapi.error.apply'), true, true); } } return; } // A browser/network failure is not proof that the server rolled the // transaction back. Replaying this exact plan is idempotent server-side. state.applyOutcomeUnknown = true; persistApplyReplay(state.applyRequest); lockApplyInputs(true); showRetry(true); if (!qs('openapi-import-modal').hidden) { setStatus(errorStatus(error, 'openapi.error.apply') + ' ' + tKey('openapi.plan.retry_unknown'), true, true); } } finally { if (state.applyController === controller) { state.applyController = null; state.applyInFlight = false; lockApplyInputs(state.applyOutcomeUnknown); qs('openapi-import-cancel').hidden = true; } } } async function createImportPlan() { if (state.applyInFlight || state.planController) return; var keys = selectedKeys(); if (!keys.length) { setStatus(tKey('openapi.error.selection'), true, true); return; } if (keys.length > 512 || importOperations().length - keys.length > 512) { setStatus(tKey('openapi.error.plan_too_large'), true, true); return; } if (!state.jobId || !state.preview) { setStatus(tKey('openapi.error.preview_required'), true, true); return; } var serverUrl = (qs('openapi-import-server-custom').value || qs('openapi-import-server').value || '').trim(); if (!serverUrl) { setStatus(tKey('openapi.error.server'), true, true); return; } if (!state.workspaceId) { setStatus(tKey('openapi.error.workspace'), true, true); return; } if (!state.operationsReady) { setStatus(tKey('openapi.error.operations_unavailable'), true, true); return; } var selectedSet = new Set(keys); var decisions = []; var invalidDecision = null; importOperations().forEach(function(operation) { if (!selectedSet.has(operation.key)) return; var decision = decisionFor(operation.key); // Skip decisions keep the existing operation untouched: no security // binding may be attached to them. if (decision.action === 'skip' && (decision.authProfileId || decision.securityAlternativeIndex !== null)) { invalidDecision = 'openapi.error.security_with_skip'; } }); importOperations().forEach(function(operation) { if (!selectedSet.has(operation.key) || invalidDecision) return; var decision = decisionFor(operation.key); var output = { operation_key: operation.key, action: decision.action }; if (decision.action === 'skip' || decision.action === 'new_version') { var allowedTargets = matchingOperations(operation).filter(function(existing) { return decision.action !== 'new_version' || (existing.protocol === 'rest' && existing.status !== 'archived'); }); if (!allowedTargets.some(function(existing) { return existing.id === decision.targetOperationId; })) { invalidDecision = 'openapi.error.decision_target'; return; } output.target_operation_id = decision.targetOperationId; } else if (decision.action === 'rename') { if (!decision.confirmedName || !decision.confirmedName.trim()) { invalidDecision = 'openapi.error.confirmed_name'; return; } output.confirmed_name = decision.confirmedName; } else if (decision.action !== 'create') { invalidDecision = 'openapi.error.decision_action'; return; } // Security binding is a typed reference only: alternative index and, // when chosen, the profile id. Resolution stays server-side. if (decision.action !== 'skip') { if (decision.authProfileId) output.auth_profile_id = decision.authProfileId; if (decision.securityAlternativeIndex !== null) { output.security_alternative_index = decision.securityAlternativeIndex; } } if (decision.action !== 'create' || decision.authProfileId || decision.securityAlternativeIndex !== null) { decisions.push(output); } }); if (invalidDecision) { setStatus(tKey(invalidDecision), true, true); return; } var total = (state.preview.groups || []).reduce(function(count, group) { return count + (group.operations || []).length; }, 0); var selectionMode = keys.length === total ? 'full' : 'partial'; var payload = { selection_mode: selectionMode, selected_operation_keys: selectionMode === 'full' ? [] : keys, server_url: serverUrl, decisions: decisions, }; var revision = state.revision; var workspaceId = state.workspaceId; var language = locale(); var controller = new AbortController(); state.planController = controller; state.plan = null; lockPlanEditing(true); qs('openapi-import-cancel').hidden = false; qs('openapi-import-plan-confirmation').hidden = true; showRetry(false); setStatus(tKey('openapi.status.planning')); try { var plan = await window.CrankApi.createOpenApiImportPlan( workspaceId, state.jobId, payload, { signal: controller.signal } ); if (state.planController !== controller) return; if (!isCurrent(revision, workspaceId, language)) return; if (!plan || typeof plan.plan_reference !== 'string' || !/^[a-f0-9]{64}$/.test(String(plan.plan_digest || '')) || !plan.counts || !Array.isArray(plan.candidates)) { throw new Error('Backend returned an invalid ImportPlan response'); } state.plan = plan; renderImportPlan(plan); setStatus(tKey('openapi.status.plan_ready')); } catch (error) { if (state.planController !== controller) return; if (error && error.name === 'AbortError') { setStatus(tKey('openapi.status.cancelled')); return; } setStatus(errorStatus(error, 'openapi.error.plan'), true, true); showRetry(true); // A typed API rejection of a security binding is authoritative blocked; // a transport/network failure only means the selection is unverified. var securityRejection = Number.isInteger(error && error.status) && error.status >= 400 && error.status < 500 && SECURITY_PLAN_ERROR_CODES.indexOf(String(error.code)) >= 0; importOperations().forEach(function(operation) { if (!selectedSet.has(operation.key) || !securityAlternativesFor(operation).length) return; setOperationSecurityStatus(operation.key, securityRejection ? 'blocked' : 'unverified'); }); updateSecuritySummary(); } finally { if (state.planController === controller) { state.planController = null; lockPlanEditing(!!state.plan); qs('openapi-import-cancel').hidden = true; } } } function newIdempotencyKey() { if (window.crypto && typeof window.crypto.randomUUID === 'function') { return 'openapi:' + window.crypto.randomUUID(); } return 'openapi:' + Date.now().toString(36) + ':' + Math.random().toString(36).slice(2); } async function applyImportPlan() { if (state.applyInFlight || !state.plan || state.applyOutcomeUnknown) return; var request = { workspaceId: state.workspaceId, planReference: state.plan.plan_reference, planDigest: state.plan.plan_digest, idempotencyKey: newIdempotencyKey(), }; if (!validApplyReplay(request)) { setStatus(tKey('openapi.error.apply'), true, true); return; } state.applyRequest = request; persistApplyReplay(request); await submitApply(request); } function backToImportSelection() { if (state.applyInFlight || state.applyOutcomeUnknown) return; state.plan = null; // Returning to editing voids the previous review: revalidation is done by // the next plan request. resetSecurityStatuses(); 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-back').textContent = tKey('openapi.plan.back'); lockPlanEditing(false); setStatus(tKey('openapi.status.preview_ready')); } function retryCurrent() { if (state.applyOutcomeUnknown && state.applyRequest) { return submitApply(state.applyRequest); } return preview(); } function reset() { invalidate({ clearFile: true }); showRetry(false); setStatus(''); qs('openapi-import-server-custom').value = ''; } function open(options) { if (state.workspaceId && state.workspaceId !== options.workspaceId && !(state.applyOutcomeUnknown && state.applyRequest)) { invalidate({ clearFile: true }); } state.workspaceId = options.workspaceId; state.onImported = options.onImported; state.restoreFocus = document.activeElement; qs('openapi-import-modal').hidden = false; renderFileName(); if (state.applyResult) { if (Array.isArray(state.applyResult.outcomes)) { renderImportPlanReport(state.applyResult); } else { renderResult(state.applyResult); } if (state.applyResult.recovery === 'repreview_required') { showRetry(true); setStatus(tKey('openapi.plan.repreview'), true, true); } else if (state.applyResult.status === 'rejected' || state.applyResult.recovery === 'confirm_skip_rename_or_new_version') { showRetry(true); setStatus(tKey('openapi.plan.resolve_conflict'), true, true); } else { setStatus(createdStatus(state.applyResult) + (state.applyRefreshFailed ? ' ' + tKey('openapi.status.refresh_failed') : '')); } } else if (state.applyOutcomeUnknown && state.applyRequest) { lockApplyInputs(true); showRetry(true); setStatus(tKey('openapi.plan.retry_unknown'), true, true); qs('openapi-import-retry').focus(); return; } qs('openapi-import-file-select').focus(); } function close() { if (state.applyInFlight || state.applyController) { markApplyOutcomeUnknown({ render: false }); qs('openapi-import-modal').hidden = true; if (state.restoreFocus && typeof state.restoreFocus.focus === 'function') { state.restoreFocus.focus(); } return; } if (state.applyOutcomeUnknown && state.applyRequest) { persistApplyReplay(state.applyRequest); qs('openapi-import-modal').hidden = true; if (state.restoreFocus && typeof state.restoreFocus.focus === 'function') { state.restoreFocus.focus(); } return; } invalidate({ clearFile: true }); showRetry(false); qs('openapi-import-modal').hidden = true; if (state.restoreFocus && typeof state.restoreFocus.focus === 'function') { state.restoreFocus.focus(); } } function selectFile(file) { clearServerSelection(); invalidate(); state.file = file || null; showRetry(false); var localError = validateFile(state.file); renderFileName(); if (localError) { setStatus(tKey(localError), true, true); } else if (state.file) { setStatus(tKey('openapi.status.file_ready')); } } document.addEventListener('DOMContentLoaded', function() { if (!qs('openapi-import-modal')) return; renderFileName(); // Dedicated screen-reader output for the API-authoritative binding state. var groupsNode = qs('openapi-import-groups'); if (!qs('openapi-import-security-status') && groupsNode && groupsNode.parentNode) { var securityStatusNode = document.createElement('div'); securityStatusNode.id = 'openapi-import-security-status'; securityStatusNode.className = 'openapi-import-security-status'; securityStatusNode.setAttribute('data-testid', 'openapi-security-status'); securityStatusNode.setAttribute('role', 'status'); securityStatusNode.setAttribute('aria-live', 'polite'); groupsNode.parentNode.insertBefore(securityStatusNode, groupsNode); } qs('openapi-import-file-select').addEventListener('click', function(event) { event.preventDefault(); qs('openapi-import-file').click(); }); qs('openapi-import-file').addEventListener('change', function(event) { selectFile(event.target.files && event.target.files[0]); }); qs('openapi-import-preview').addEventListener('click', preview); qs('openapi-import-retry').addEventListener('click', retryCurrent); qs('openapi-import-create').addEventListener('click', createImportPlan); qs('openapi-import-plan-apply').addEventListener('click', applyImportPlan); qs('openapi-import-plan-back').addEventListener('click', backToImportSelection); qs('openapi-import-cancel').addEventListener('click', cancelCurrent); qs('openapi-import-reset').addEventListener('click', reset); qs('openapi-import-search').addEventListener('input', function(event) { state.filterQuery = event.target.value.trim(); applyFilters(); }); qs('openapi-import-method-filter').addEventListener('change', function(event) { state.filterMethod = event.target.value; applyFilters(); }); qs('openapi-import-select-visible').addEventListener('click', function() { setVisibleSelection(true); }); qs('openapi-import-clear-visible').addEventListener('click', function() { setVisibleSelection(false); }); document.querySelectorAll('[data-openapi-close]').forEach(function(node) { node.addEventListener('click', close); }); document.addEventListener('keydown', function(event) { var modal = qs('openapi-import-modal'); if (event.key === 'Escape' && !qs('openapi-import-modal').hidden) { event.preventDefault(); close(); } if (event.key !== 'Tab' || modal.hidden) return; var focusable = Array.from(modal.querySelectorAll('button:not([disabled]):not([hidden]), input:not([disabled]), select:not([disabled]), a[href]')) .filter(function(node) { return node.tabIndex >= 0 && !node.closest('[hidden]'); }); if (!focusable.length) return; var first = focusable[0]; var last = focusable[focusable.length - 1]; if (event.shiftKey && (document.activeElement === first || !modal.contains(document.activeElement))) { event.preventDefault(); last.focus(); } else if (!event.shiftKey && document.activeElement === last) { event.preventDefault(); first.focus(); } }); function invalidateForContext(options) { if (!qs('openapi-import-modal').hidden) { if (state.applyInFlight || state.applyController) { markApplyOutcomeUnknown(); return; } if (state.applyOutcomeUnknown && state.applyRequest) { showRetry(true); setStatus(tKey('openapi.plan.retry_unknown'), true, true); return; } invalidate(options); renderFileName(); showRetry(!options || !options.clearFile ? !!state.file : false); setStatus(tKey('openapi.status.context_changed')); } } function handleLanguageChange() { // While an Apply owns the locked controls, re-rendering would re-enable // them. Route straight to the context-change path, which marks the apply // outcome unknown and keeps the controls locked. if (state.applyInFlight || state.applyController || (state.applyOutcomeUnknown && state.applyRequest)) { renderSecurityStatus(); invalidateForContext(); return; } importOperations().forEach(function(operation) { var row = operationRowFor(operation); if (row) { renderDecisionControls(operation, row); renderSecurityControls(operation, row); } }); if (!qs('openapi-import-modal').hidden && state.plan) { renderImportPlan(state.plan); setStatus(tKey('openapi.status.plan_ready')); return; } updateSecuritySummary(); invalidateForContext(); } window.addEventListener('crank:langchange', handleLanguageChange); window.addEventListener('crank:workspacechange', function(event) { if (!qs('openapi-import-modal').hidden) { state.workspaceId = event.detail && event.detail.id || null; invalidateForContext({ clearFile: true }); } }); window.addEventListener('storage', function(event) { if (event.key === 'crank_lang') handleLanguageChange(); }); window.addEventListener('pagehide', function() { if (state.applyInFlight || state.applyController) { markApplyOutcomeUnknown({ render: false }); state.file = null; qs('openapi-import-file').value = ''; renderFileName(); } else if (state.applyOutcomeUnknown && state.applyRequest) { persistApplyReplay(state.applyRequest); } else { invalidate({ clearFile: true }); } clearServerSelection(); showRetry(false); setStatus(''); }); window.addEventListener('pageshow', function(event) { if (!event.persisted || qs('openapi-import-modal').hidden) return; if (state.applyOutcomeUnknown && state.applyRequest) { lockApplyInputs(true); showRetry(true); setStatus(tKey('openapi.plan.retry_unknown'), true, true); } else { invalidateForContext({ clearFile: true }); } }); }); window.CrankOpenApiImport = { open: open, close: close, reset: reset, }; }());