2594 lines
80 KiB
HTML
2594 lines
80 KiB
HTML
<!DOCTYPE html>
|
||
<html lang="fa" dir="rtl">
|
||
<head>
|
||
<meta charset="UTF-8">
|
||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||
<title>XFramework Backend SDK Manager</title>
|
||
<style>
|
||
@import url('https://fonts.googleapis.com/css2?family=Vazirmatn:wght@300;400;500;600;700;800&display=swap');
|
||
@import url('https://fonts.googleapis.com/css2?family=Fira+Code:wght@400;500;600&display=swap');
|
||
|
||
:root {
|
||
--primary: #1a365d;
|
||
--primary-light: #2c5282;
|
||
--primary-dark: #0f2341;
|
||
--accent: #c9a961;
|
||
--accent-dark: #a8893f;
|
||
--accent-light: #e0c789;
|
||
--bg: #f5f7fa;
|
||
--board-bg: #e2e8f0;
|
||
--card-bg: #ffffff;
|
||
--column-bg: #edf2f7;
|
||
--panel-bg: #ffffff;
|
||
--text: #1a202c;
|
||
--text-muted: #4a5568;
|
||
--text-light: #718096;
|
||
--border: #cbd5e0;
|
||
--border-light: #e2e8f0;
|
||
--success: #38a169;
|
||
--danger: #e53e3e;
|
||
--warning: #dd6b20;
|
||
--info: #3182ce;
|
||
--shadow: 0 4px 6px rgba(0,0,0,0.08), 0 10px 20px rgba(26,54,93,0.1);
|
||
--shadow-sm: 0 2px 4px rgba(0,0,0,0.06);
|
||
--shadow-lg: 0 10px 30px rgba(0,0,0,0.15);
|
||
--radius: 10px;
|
||
--radius-sm: 6px;
|
||
--sidebar-width: 300px;
|
||
--header-height: 64px;
|
||
--footer-height: 36px;
|
||
}
|
||
|
||
[data-theme="dark"] {
|
||
--primary: #2c5282;
|
||
--primary-light: #3b6fb5;
|
||
--primary-dark: #1a365d;
|
||
--accent: #e0c789;
|
||
--accent-dark: #c9a961;
|
||
--accent-light: #f0d9a0;
|
||
--bg: #1a202c;
|
||
--board-bg: #2d3748;
|
||
--card-bg: #2d3748;
|
||
--column-bg: #374151;
|
||
--panel-bg: #1f2937;
|
||
--text: #e2e8f0;
|
||
--text-muted: #cbd5e0;
|
||
--text-light: #a0aec0;
|
||
--border: #4a5568;
|
||
--border-light: #374151;
|
||
}
|
||
|
||
* { box-sizing: border-box; margin: 0; padding: 0; }
|
||
|
||
body {
|
||
font-family: 'Vazirmatn', Tahoma, sans-serif;
|
||
background: var(--bg);
|
||
color: var(--text);
|
||
height: 100vh;
|
||
overflow: hidden;
|
||
font-size: 14px;
|
||
display: flex;
|
||
flex-direction: column;
|
||
transition: background 0.3s, color 0.3s;
|
||
}
|
||
|
||
/* ============ Header ============ */
|
||
.app-header {
|
||
background: linear-gradient(135deg, var(--primary) 0%, var(--primary-light) 100%);
|
||
color: white;
|
||
padding: 0 20px;
|
||
height: var(--header-height);
|
||
display: flex;
|
||
align-items: center;
|
||
justify-content: space-between;
|
||
border-bottom: 3px solid var(--accent);
|
||
box-shadow: var(--shadow);
|
||
z-index: 100;
|
||
flex-shrink: 0;
|
||
position: relative;
|
||
overflow: hidden;
|
||
}
|
||
|
||
.app-header::before {
|
||
content: '';
|
||
position: absolute;
|
||
top: -50%;
|
||
left: -10%;
|
||
width: 300px;
|
||
height: 300px;
|
||
background: radial-gradient(circle, rgba(201,169,97,0.15) 0%, transparent 70%);
|
||
border-radius: 50%;
|
||
pointer-events: none;
|
||
}
|
||
|
||
.app-brand {
|
||
display: flex;
|
||
align-items: center;
|
||
gap: 14px;
|
||
position: relative;
|
||
z-index: 1;
|
||
}
|
||
|
||
.app-logo {
|
||
width: 44px; height: 44px;
|
||
background: var(--accent);
|
||
border-radius: 10px;
|
||
display: flex;
|
||
align-items: center;
|
||
justify-content: center;
|
||
font-size: 22px;
|
||
font-weight: 800;
|
||
color: var(--primary-dark);
|
||
box-shadow: 0 4px 12px rgba(0,0,0,0.25);
|
||
flex-shrink: 0;
|
||
}
|
||
|
||
.app-brand-text { display: flex; flex-direction: column; gap: 2px; }
|
||
.app-title { font-size: 16px; font-weight: 800; letter-spacing: -0.3px; color: white; }
|
||
.app-subtitle { font-size: 11px; opacity: 0.85; color: rgba(255,255,255,0.9); }
|
||
|
||
.header-actions { display: flex; gap: 10px; align-items: center; position: relative; z-index: 1; }
|
||
|
||
/* ============ Buttons ============ */
|
||
.btn {
|
||
background: linear-gradient(135deg, var(--primary-light), var(--primary));
|
||
color: white;
|
||
border: none;
|
||
padding: 8px 14px;
|
||
border-radius: var(--radius-sm);
|
||
cursor: pointer;
|
||
font-family: inherit;
|
||
font-size: 13px;
|
||
font-weight: 600;
|
||
display: inline-flex;
|
||
align-items: center;
|
||
gap: 6px;
|
||
transition: all 0.2s;
|
||
box-shadow: 0 2px 4px rgba(0,0,0,0.15);
|
||
white-space: nowrap;
|
||
}
|
||
|
||
.btn:hover { transform: translateY(-1px); box-shadow: 0 4px 8px rgba(0,0,0,0.2); filter: brightness(1.1); }
|
||
.btn:active { transform: translateY(0); }
|
||
.btn:disabled { opacity: 0.5; cursor: not-allowed; }
|
||
|
||
.btn-accent {
|
||
background: linear-gradient(135deg, var(--accent), var(--accent-dark));
|
||
color: var(--primary-dark);
|
||
font-weight: 700;
|
||
}
|
||
|
||
.btn-ghost {
|
||
background: rgba(255,255,255,0.1);
|
||
border: 1px solid rgba(255,255,255,0.25);
|
||
color: white;
|
||
font-weight: 600;
|
||
}
|
||
|
||
.btn-ghost:hover { background: rgba(255,255,255,0.2); }
|
||
|
||
.btn-success { background: linear-gradient(135deg, #48bb78, var(--success)); }
|
||
.btn-danger { background: linear-gradient(135deg, #f56565, var(--danger)); }
|
||
.btn-sm { padding: 6px 10px; font-size: 12px; }
|
||
|
||
/* ============ Main Layout ============ */
|
||
.app-main {
|
||
flex: 1;
|
||
display: flex;
|
||
overflow: hidden;
|
||
position: relative;
|
||
flex-direction: row;
|
||
}
|
||
|
||
/* ============ Sidebar ============ */
|
||
.sidebar {
|
||
order: -1;
|
||
width: var(--sidebar-width);
|
||
background: var(--panel-bg);
|
||
border-right: 1px solid var(--border);
|
||
display: flex;
|
||
flex-direction: column;
|
||
transition: width 0.3s ease;
|
||
box-shadow: var(--shadow);
|
||
overflow: hidden;
|
||
flex-shrink: 0;
|
||
z-index: 50;
|
||
}
|
||
|
||
.sidebar.collapsed { width: 0; overflow: hidden; }
|
||
|
||
.sidebar-header {
|
||
background: linear-gradient(135deg, var(--primary), var(--primary-light));
|
||
color: white;
|
||
padding: 12px;
|
||
display: flex;
|
||
align-items: center;
|
||
justify-content: space-between;
|
||
border-bottom: 2px solid var(--accent);
|
||
min-height: 48px;
|
||
}
|
||
|
||
.sidebar-title {
|
||
font-size: 13px;
|
||
font-weight: 700;
|
||
display: flex;
|
||
align-items: center;
|
||
gap: 8px;
|
||
white-space: nowrap;
|
||
}
|
||
|
||
.sidebar-body { flex: 1; overflow-y: auto; padding: 8px; }
|
||
|
||
/* ============ Search Input ============ */
|
||
.search-input-wrapper {
|
||
position: relative;
|
||
margin-bottom: 8px;
|
||
}
|
||
|
||
.search-input {
|
||
width: 100%;
|
||
padding: 8px 12px 8px 32px;
|
||
border: 1px solid var(--border);
|
||
border-radius: var(--radius-sm);
|
||
font-family: inherit;
|
||
font-size: 12px;
|
||
background: var(--card-bg);
|
||
color: var(--text);
|
||
transition: all 0.2s;
|
||
}
|
||
|
||
.search-input:focus {
|
||
outline: none;
|
||
border-color: var(--accent);
|
||
box-shadow: 0 0 0 3px rgba(201,169,97,0.15);
|
||
}
|
||
|
||
.search-icon {
|
||
position: absolute;
|
||
left: 10px;
|
||
top: 50%;
|
||
transform: translateY(-50%);
|
||
font-size: 14px;
|
||
opacity: 0.5;
|
||
pointer-events: none;
|
||
}
|
||
|
||
.search-clear {
|
||
position: absolute;
|
||
right: 8px;
|
||
top: 50%;
|
||
transform: translateY(-50%);
|
||
background: transparent;
|
||
border: none;
|
||
color: var(--text-muted);
|
||
cursor: pointer;
|
||
font-size: 14px;
|
||
padding: 2px 6px;
|
||
border-radius: 4px;
|
||
display: none;
|
||
}
|
||
|
||
.search-clear:hover {
|
||
background: var(--border-light);
|
||
color: var(--text);
|
||
}
|
||
|
||
.search-clear.visible { display: block; }
|
||
|
||
.controller-item {
|
||
background: var(--card-bg);
|
||
border: 1px solid var(--border-light);
|
||
color: var(--text);
|
||
padding: 10px 12px;
|
||
border-radius: var(--radius-sm);
|
||
cursor: pointer;
|
||
font-family: inherit;
|
||
font-size: 13px;
|
||
font-weight: 500;
|
||
display: flex;
|
||
align-items: center;
|
||
gap: 10px;
|
||
transition: all 0.2s;
|
||
text-align: right;
|
||
width: 100%;
|
||
margin-bottom: 4px;
|
||
position: relative;
|
||
}
|
||
|
||
.controller-item:hover {
|
||
background: linear-gradient(135deg, var(--primary), var(--primary-light));
|
||
color: white;
|
||
border-color: var(--primary);
|
||
transform: translateX(-2px);
|
||
}
|
||
|
||
.controller-item.active {
|
||
background: linear-gradient(135deg, var(--primary), var(--primary-light));
|
||
color: white;
|
||
border-color: var(--accent);
|
||
box-shadow: 0 2px 8px rgba(201,169,97,0.3);
|
||
}
|
||
|
||
.controller-item .ctrl-icon { font-size: 18px; flex-shrink: 0; }
|
||
.controller-item .ctrl-name { flex: 1; font-weight: 600; }
|
||
.controller-item .ctrl-badge {
|
||
font-size: 10px;
|
||
background: rgba(201,169,97,0.2);
|
||
color: var(--accent-dark);
|
||
padding: 2px 7px;
|
||
border-radius: 10px;
|
||
font-weight: 700;
|
||
}
|
||
.controller-item.active .ctrl-badge { background: rgba(255,255,255,0.25); color: white; }
|
||
|
||
/* ============ Board Area ============ */
|
||
.board-area {
|
||
flex: 1;
|
||
overflow: auto;
|
||
padding: 20px;
|
||
background: var(--board-bg);
|
||
transition: background 0.3s;
|
||
}
|
||
|
||
/* ============ Upload Zone ============ */
|
||
.upload-zone {
|
||
background: var(--card-bg);
|
||
border: 3px dashed var(--border);
|
||
border-radius: var(--radius);
|
||
padding: 60px 40px;
|
||
text-align: center;
|
||
transition: all 0.3s;
|
||
cursor: pointer;
|
||
max-width: 700px;
|
||
margin: 40px auto;
|
||
}
|
||
|
||
.upload-zone:hover, .upload-zone.dragover {
|
||
border-color: var(--accent);
|
||
background: linear-gradient(to left, #fffaf0, #fef5e7);
|
||
transform: translateY(-2px);
|
||
box-shadow: var(--shadow);
|
||
}
|
||
|
||
[data-theme="dark"] .upload-zone:hover,
|
||
[data-theme="dark"] .upload-zone.dragover {
|
||
background: rgba(201,169,97,0.08);
|
||
}
|
||
|
||
.upload-zone-icon { font-size: 70px; margin-bottom: 20px; opacity: 0.7; }
|
||
.upload-zone h2 { color: var(--primary); font-size: 22px; margin-bottom: 10px; }
|
||
[data-theme="dark"] .upload-zone h2 { color: var(--accent); }
|
||
.upload-zone p { color: var(--text-muted); margin-bottom: 20px; }
|
||
|
||
/* ============ Tabs ============ */
|
||
.controller-tabs {
|
||
display: flex;
|
||
gap: 4px;
|
||
background: var(--card-bg);
|
||
padding: 6px;
|
||
border-radius: var(--radius);
|
||
margin-bottom: 20px;
|
||
box-shadow: var(--shadow-sm);
|
||
flex-wrap: wrap;
|
||
}
|
||
|
||
.controller-tab {
|
||
background: transparent;
|
||
border: none;
|
||
color: var(--text-muted);
|
||
padding: 10px 16px;
|
||
border-radius: var(--radius-sm);
|
||
cursor: pointer;
|
||
font-family: inherit;
|
||
font-size: 13px;
|
||
font-weight: 600;
|
||
transition: all 0.2s;
|
||
display: flex;
|
||
align-items: center;
|
||
gap: 6px;
|
||
}
|
||
|
||
.controller-tab:hover { background: var(--column-bg); color: var(--text); }
|
||
|
||
.controller-tab.active {
|
||
background: linear-gradient(135deg, var(--primary), var(--primary-light));
|
||
color: white;
|
||
box-shadow: var(--shadow-sm);
|
||
}
|
||
|
||
/* ============ Content Sections ============ */
|
||
.content-section {
|
||
background: var(--card-bg);
|
||
border-radius: var(--radius);
|
||
padding: 24px;
|
||
margin-bottom: 20px;
|
||
box-shadow: var(--shadow-sm);
|
||
}
|
||
|
||
.section-header {
|
||
display: flex;
|
||
align-items: center;
|
||
gap: 12px;
|
||
padding-bottom: 14px;
|
||
border-bottom: 2px solid var(--border-light);
|
||
margin-bottom: 18px;
|
||
}
|
||
|
||
.section-icon {
|
||
width: 44px; height: 44px;
|
||
background: linear-gradient(135deg, var(--primary), var(--primary-light));
|
||
color: white;
|
||
border-radius: 10px;
|
||
display: flex;
|
||
align-items: center;
|
||
justify-content: center;
|
||
font-size: 20px;
|
||
flex-shrink: 0;
|
||
box-shadow: 0 4px 10px rgba(26,54,93,0.2);
|
||
}
|
||
|
||
.section-title { flex: 1; }
|
||
.section-title h3 { font-size: 17px; font-weight: 700; color: var(--primary); margin-bottom: 2px; }
|
||
[data-theme="dark"] .section-title h3 { color: var(--accent); }
|
||
.section-title .subtitle { font-size: 12px; color: var(--text-muted); }
|
||
|
||
/* ============ Models List ============ */
|
||
.models-grid {
|
||
display: grid;
|
||
grid-template-columns: repeat(auto-fill, minmax(260px, 1fr));
|
||
gap: 12px;
|
||
}
|
||
|
||
.model-card {
|
||
background: var(--column-bg);
|
||
border: 2px solid var(--border-light);
|
||
border-radius: var(--radius-sm);
|
||
padding: 14px;
|
||
cursor: pointer;
|
||
transition: all 0.2s;
|
||
position: relative;
|
||
}
|
||
|
||
.model-card:hover {
|
||
border-color: var(--accent);
|
||
transform: translateY(-2px);
|
||
box-shadow: var(--shadow);
|
||
}
|
||
|
||
.model-card-header {
|
||
display: flex;
|
||
align-items: center;
|
||
gap: 8px;
|
||
margin-bottom: 8px;
|
||
}
|
||
|
||
.model-card-icon {
|
||
width: 32px; height: 32px;
|
||
background: linear-gradient(135deg, var(--accent), var(--accent-dark));
|
||
color: var(--primary-dark);
|
||
border-radius: 8px;
|
||
display: flex;
|
||
align-items: center;
|
||
justify-content: center;
|
||
font-size: 14px;
|
||
font-weight: 800;
|
||
flex-shrink: 0;
|
||
}
|
||
|
||
.model-card-name {
|
||
font-size: 14px;
|
||
font-weight: 700;
|
||
color: var(--primary);
|
||
flex: 1;
|
||
overflow: hidden;
|
||
text-overflow: ellipsis;
|
||
white-space: nowrap;
|
||
}
|
||
|
||
[data-theme="dark"] .model-card-name { color: var(--accent); }
|
||
|
||
.model-card-meta {
|
||
font-size: 11px;
|
||
color: var(--text-muted);
|
||
display: flex;
|
||
gap: 10px;
|
||
margin-top: 6px;
|
||
}
|
||
|
||
.model-card-meta span { display: flex; align-items: center; gap: 4px; }
|
||
|
||
/* ============ Endpoints Table ============ */
|
||
.endpoints-table {
|
||
width: 100%;
|
||
border-collapse: collapse;
|
||
background: var(--card-bg);
|
||
border-radius: 8px;
|
||
overflow: hidden;
|
||
box-shadow: var(--shadow-sm);
|
||
}
|
||
|
||
.endpoints-table thead {
|
||
background: linear-gradient(135deg, var(--primary), var(--primary-light));
|
||
color: white;
|
||
}
|
||
|
||
.endpoints-table th {
|
||
padding: 12px 14px;
|
||
text-align: right;
|
||
font-weight: 600;
|
||
font-size: 12px;
|
||
}
|
||
|
||
.endpoints-table td {
|
||
padding: 11px 14px;
|
||
border-bottom: 1px solid var(--border-light);
|
||
font-size: 12px;
|
||
}
|
||
|
||
.endpoints-table tbody tr:last-child td { border-bottom: none; }
|
||
.endpoints-table tbody tr:nth-child(even) { background: var(--column-bg); }
|
||
|
||
.method-badge {
|
||
display: inline-block;
|
||
padding: 3px 10px;
|
||
border-radius: 4px;
|
||
font-size: 10px;
|
||
font-weight: 800;
|
||
color: white;
|
||
letter-spacing: 0.5px;
|
||
font-family: 'Fira Code', monospace;
|
||
}
|
||
|
||
.method-get { background: var(--info); }
|
||
.method-post { background: var(--success); }
|
||
.method-put { background: var(--warning); }
|
||
.method-delete { background: var(--danger); }
|
||
|
||
.endpoint-path {
|
||
font-family: 'Fira Code', monospace;
|
||
font-size: 11px;
|
||
color: var(--text);
|
||
direction: ltr;
|
||
text-align: left;
|
||
}
|
||
|
||
/* ============ Modal ============ */
|
||
.modal-overlay {
|
||
position: fixed;
|
||
inset: 0;
|
||
background: rgba(26,54,93,0.6);
|
||
backdrop-filter: blur(3px);
|
||
display: none;
|
||
align-items: center;
|
||
justify-content: center;
|
||
z-index: 1000;
|
||
padding: 20px;
|
||
animation: fadeIn 0.2s;
|
||
}
|
||
|
||
.modal-overlay.active { display: flex; }
|
||
@keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } }
|
||
|
||
.modal {
|
||
background: var(--panel-bg);
|
||
color: var(--text);
|
||
border-radius: 12px;
|
||
width: 100%;
|
||
max-width: 1100px;
|
||
max-height: 90vh;
|
||
overflow: hidden;
|
||
display: flex;
|
||
flex-direction: column;
|
||
box-shadow: var(--shadow-lg);
|
||
animation: slideUp 0.25s;
|
||
}
|
||
|
||
@keyframes slideUp {
|
||
from { opacity: 0; transform: translateY(20px); }
|
||
to { opacity: 1; transform: translateY(0); }
|
||
}
|
||
|
||
.modal-header {
|
||
background: linear-gradient(135deg, var(--primary), var(--primary-light));
|
||
color: white;
|
||
padding: 16px 20px;
|
||
display: flex;
|
||
align-items: center;
|
||
justify-content: space-between;
|
||
border-bottom: 3px solid var(--accent);
|
||
}
|
||
|
||
.modal-title {
|
||
font-size: 16px;
|
||
font-weight: 700;
|
||
display: flex;
|
||
align-items: center;
|
||
gap: 10px;
|
||
}
|
||
|
||
.modal-close {
|
||
background: rgba(255,255,255,0.15);
|
||
border: none;
|
||
color: white;
|
||
width: 30px; height: 30px;
|
||
border-radius: 50%;
|
||
cursor: pointer;
|
||
font-size: 16px;
|
||
transition: all 0.2s;
|
||
}
|
||
|
||
.modal-close:hover { background: var(--danger); }
|
||
|
||
.modal-body { padding: 20px; overflow-y: auto; flex: 1; }
|
||
|
||
.modal-footer {
|
||
padding: 14px 20px;
|
||
border-top: 1px solid var(--border);
|
||
display: flex;
|
||
justify-content: flex-start;
|
||
gap: 8px;
|
||
background: var(--border-light);
|
||
}
|
||
|
||
/* ============ Code Block ============ */
|
||
.code-block {
|
||
background: #1e1e1e;
|
||
color: #d4d4d4;
|
||
border-radius: 8px;
|
||
padding: 16px;
|
||
font-family: 'Fira Code', 'Courier New', monospace;
|
||
font-size: 12px;
|
||
line-height: 1.7;
|
||
overflow-x: auto;
|
||
direction: ltr;
|
||
text-align: left;
|
||
position: relative;
|
||
margin-top: 12px;
|
||
max-height: 600px;
|
||
overflow-y: auto;
|
||
}
|
||
|
||
.code-block-header {
|
||
display: flex;
|
||
justify-content: space-between;
|
||
align-items: center;
|
||
background: #2d2d2d;
|
||
padding: 8px 14px;
|
||
border-radius: 8px 8px 0 0;
|
||
color: #d4d4d4;
|
||
font-family: 'Fira Code', monospace;
|
||
font-size: 11px;
|
||
}
|
||
|
||
.code-block-header + .code-block { border-radius: 0 0 8px 8px; margin-top: 0; }
|
||
|
||
.code-block pre { margin: 0; white-space: pre; }
|
||
|
||
.code-keyword { color: #569cd6; }
|
||
.code-type { color: #4ec9b0; }
|
||
.code-string { color: #ce9178; }
|
||
.code-comment { color: #6a9955; font-style: italic; }
|
||
.code-number { color: #b5cea8; }
|
||
.code-decorator { color: #dcdcaa; }
|
||
|
||
/* ============ Toast ============ */
|
||
.toast-container {
|
||
position: fixed;
|
||
bottom: 20px;
|
||
left: 20px;
|
||
z-index: 2000;
|
||
display: flex;
|
||
flex-direction: column;
|
||
gap: 8px;
|
||
}
|
||
|
||
.toast {
|
||
background: var(--primary);
|
||
color: white;
|
||
padding: 12px 18px;
|
||
border-radius: 8px;
|
||
box-shadow: var(--shadow-lg);
|
||
font-size: 13px;
|
||
display: flex;
|
||
align-items: center;
|
||
gap: 10px;
|
||
animation: slideInLeft 0.3s;
|
||
min-width: 250px;
|
||
}
|
||
|
||
.toast.success { background: var(--success); }
|
||
.toast.error { background: var(--danger); }
|
||
.toast.warning { background: var(--warning); }
|
||
|
||
@keyframes slideInLeft {
|
||
from { opacity: 0; transform: translateX(-30px); }
|
||
to { opacity: 1; transform: translateX(0); }
|
||
}
|
||
|
||
/* ============ Stats Grid ============ */
|
||
.stats-grid {
|
||
display: grid;
|
||
grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
|
||
gap: 14px;
|
||
margin-bottom: 20px;
|
||
}
|
||
|
||
.stat-card {
|
||
background: linear-gradient(135deg, var(--primary), var(--primary-light));
|
||
color: white;
|
||
padding: 18px;
|
||
border-radius: var(--radius);
|
||
text-align: center;
|
||
box-shadow: 0 4px 12px rgba(26,54,93,0.2);
|
||
}
|
||
|
||
.stat-card .stat-value {
|
||
font-size: 28px;
|
||
font-weight: 800;
|
||
margin-bottom: 4px;
|
||
color: var(--accent);
|
||
line-height: 1.3;
|
||
}
|
||
|
||
.stat-card .stat-label { font-size: 12px; opacity: 0.9; }
|
||
|
||
/* ============ Footer ============ */
|
||
.app-footer {
|
||
background: linear-gradient(135deg, var(--primary), var(--primary-light));
|
||
color: white;
|
||
padding: 8px 20px;
|
||
font-size: 11px;
|
||
display: flex;
|
||
justify-content: space-between;
|
||
align-items: center;
|
||
border-top: 2px solid var(--accent);
|
||
flex-shrink: 0;
|
||
}
|
||
|
||
.footer-brand { color: var(--accent); font-weight: 700; }
|
||
|
||
/* ============ Scrollbar ============ */
|
||
::-webkit-scrollbar { width: 8px; height: 8px; }
|
||
::-webkit-scrollbar-track { background: transparent; }
|
||
::-webkit-scrollbar-thumb { background: var(--border); border-radius: 4px; }
|
||
::-webkit-scrollbar-thumb:hover { background: var(--text-muted); }
|
||
|
||
/* ============ File Input Hidden ============ */
|
||
.hidden-input { display: none; }
|
||
|
||
/* ============ Empty State ============ */
|
||
.empty-state {
|
||
text-align: center;
|
||
padding: 40px 20px;
|
||
color: var(--text-muted);
|
||
}
|
||
|
||
.empty-state-icon { font-size: 60px; opacity: 0.3; margin-bottom: 14px; }
|
||
.empty-state h3 { color: var(--primary); margin-bottom: 8px; }
|
||
[data-theme="dark"] .empty-state h3 { color: var(--accent); }
|
||
|
||
/* ============ Provider Service Tab ============ */
|
||
.provider-service-info {
|
||
background: linear-gradient(to left, #ebf8ff, #e6f6ff);
|
||
border: 1px solid #90cdf4;
|
||
border-right: 4px solid var(--info);
|
||
padding: 14px 18px;
|
||
border-radius: 8px;
|
||
margin-bottom: 18px;
|
||
font-size: 13px;
|
||
color: var(--text-muted);
|
||
}
|
||
|
||
[data-theme="dark"] .provider-service-info {
|
||
background: rgba(49, 130, 206, 0.12);
|
||
border-color: rgba(49, 130, 206, 0.3);
|
||
}
|
||
|
||
.provider-service-info strong {
|
||
color: var(--info);
|
||
}
|
||
|
||
.file-actions {
|
||
display: flex;
|
||
gap: 8px;
|
||
margin-top: 14px;
|
||
flex-wrap: wrap;
|
||
}
|
||
|
||
@media (max-width: 768px) {
|
||
.sidebar { position: absolute; height: 100%; z-index: 200; }
|
||
.sidebar.collapsed { width: 0; }
|
||
.models-grid { grid-template-columns: 1fr; }
|
||
.stats-grid { grid-template-columns: 1fr 1fr; }
|
||
}
|
||
</style>
|
||
</head>
|
||
<body>
|
||
|
||
<!-- ============ Header ============ -->
|
||
<header class="app-header">
|
||
<div class="app-brand">
|
||
<div class="app-logo">⚡</div>
|
||
<div class="app-brand-text">
|
||
<div class="app-title">XFramework Backend SDK Manager</div>
|
||
<div class="app-subtitle">تولید سرویس های فراخوانی سرویس دهنده</div>
|
||
</div>
|
||
</div>
|
||
<div class="header-actions">
|
||
<button class="btn btn-ghost btn-sm" id="themeToggle" title="تغییر تم">
|
||
<span id="themeIcon">☀️</span>
|
||
</button>
|
||
<button class="btn btn-accent btn-sm" id="loadFileBtn">
|
||
<span>📂</span>
|
||
<span>بارگذاری Swagger JSON</span>
|
||
</button>
|
||
</div>
|
||
</header>
|
||
|
||
<!-- ============ Main Layout ============ -->
|
||
<div class="app-main">
|
||
<!-- Sidebar -->
|
||
<aside class="sidebar" id="sidebar">
|
||
<div class="sidebar-header">
|
||
<div class="sidebar-title">🎛️ کنترلرها</div>
|
||
</div>
|
||
<div class="sidebar-body" id="controllersList">
|
||
<div class="empty-state">
|
||
<div class="empty-state-icon">📭</div>
|
||
<p>ابتدا فایل Swagger را بارگذاری کنید</p>
|
||
</div>
|
||
</div>
|
||
</aside>
|
||
|
||
<!-- Board Area -->
|
||
<main class="board-area" id="boardArea">
|
||
<!-- Upload Zone (Initial) -->
|
||
<div id="uploadZone" class="upload-zone">
|
||
<div class="upload-zone-icon">📄</div>
|
||
<h2>فایل Swagger JSON را بارگذاری کنید</h2>
|
||
<p>فایل را اینجا بکشید و رها کنید یا روی این ناحیه کلیک کنید</p>
|
||
<button class="btn btn-accent">
|
||
<span>📁</span>
|
||
<span>انتخاب فایل</span>
|
||
</button>
|
||
</div>
|
||
|
||
<!-- Loaded Content (Hidden Initially) -->
|
||
<div id="loadedContent" style="display: none;">
|
||
<!-- Stats -->
|
||
<div class="stats-grid" id="statsGrid"></div>
|
||
|
||
<!-- Controller Tabs -->
|
||
<div class="controller-tabs" id="controllerTabs"></div>
|
||
|
||
<!-- Controller Content -->
|
||
<div id="controllerContent"></div>
|
||
</div>
|
||
</main>
|
||
</div>
|
||
|
||
<!-- ============ Footer ============ -->
|
||
<footer class="app-footer">
|
||
<div>
|
||
<span class="footer-brand">طراح و توسعهدهنده:</span> هادی خزاعی اصل
|
||
<span style="margin: 0 10px;">|</span>
|
||
<span class="footer-brand">شرکت:</span> فن آوران ساحر علم
|
||
</div>
|
||
<div>
|
||
<span class="footer-brand">نسخه:</span> 1.2.0
|
||
</div>
|
||
</footer>
|
||
|
||
<!-- ============ Model Detail Modal ============ -->
|
||
<div class="modal-overlay" id="modelModal">
|
||
<div class="modal">
|
||
<div class="modal-header">
|
||
<div class="modal-title">
|
||
<span>📦</span>
|
||
<span id="modelModalTitle">جزئیات مدل</span>
|
||
</div>
|
||
<button class="modal-close" data-close-modal>✕</button>
|
||
</div>
|
||
<div class="modal-body" id="modelModalBody"></div>
|
||
<div class="modal-footer">
|
||
<button class="btn btn-success" id="downloadDtoBtn">
|
||
<span>💾</span>
|
||
<span>دانلود فایل DTO</span>
|
||
</button>
|
||
<button class="btn btn-ghost" style="background: var(--column-bg); color: var(--text); border: 1px solid var(--border);" id="copyCodeBtn">
|
||
<span>📋</span>
|
||
<span>کپی کد</span>
|
||
</button>
|
||
<button class="btn btn-ghost" style="background: var(--column-bg); color: var(--text); border: 1px solid var(--border);" data-close-modal>بستن</button>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
|
||
<!-- ============ Provider Service Modal ============ -->
|
||
<div class="modal-overlay" id="providerModal">
|
||
<div class="modal" style="max-width: 1200px;">
|
||
<div class="modal-header">
|
||
<div class="modal-title">
|
||
<span>🔌</span>
|
||
<span id="providerModalTitle">Provider Service</span>
|
||
</div>
|
||
<button class="modal-close" data-close-modal-provider>✕</button>
|
||
</div>
|
||
<div class="modal-body" id="providerModalBody"></div>
|
||
<div class="modal-footer">
|
||
<button class="btn btn-success" id="downloadProviderBtn">
|
||
<span>💾</span>
|
||
<span>دانلود فایل Service</span>
|
||
</button>
|
||
<button class="btn btn-ghost" style="background: var(--column-bg); color: var(--text); border: 1px solid var(--border);" id="copyProviderCodeBtn">
|
||
<span>📋</span>
|
||
<span>کپی کد</span>
|
||
</button>
|
||
<button class="btn btn-ghost" style="background: var(--column-bg); color: var(--text); border: 1px solid var(--border);" data-close-modal-provider>بستن</button>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
|
||
<!-- Hidden File Input -->
|
||
<input type="file" id="fileInput" class="hidden-input" accept=".json,application/json">
|
||
|
||
<!-- Toast Container -->
|
||
<div class="toast-container" id="toastContainer"></div>
|
||
|
||
<script>
|
||
/* =========================================================================
|
||
XFramework Backend SDK Generator - Core Logic
|
||
========================================================================= */
|
||
|
||
// ============ Global State ============
|
||
const AppState = {
|
||
swagger: null,
|
||
controllers: {},
|
||
allSchemas: {},
|
||
activeController: null,
|
||
selectedModel: null,
|
||
generatedCode: '',
|
||
generatedProviderCode: '',
|
||
generatedProviderFilename: '',
|
||
searchTerms: {
|
||
controllers: '',
|
||
models: '',
|
||
endpoints: ''
|
||
}
|
||
};
|
||
|
||
// ============ Toast System ============
|
||
function showToast(message, type = 'info', duration = 3000) {
|
||
const container = document.getElementById('toastContainer');
|
||
const toast = document.createElement('div');
|
||
toast.className = `toast ${type}`;
|
||
const icons = { success: '✅', error: '❌', warning: '⚠️', info: 'ℹ️' };
|
||
toast.innerHTML = `<span>${icons[type] || 'ℹ️'}</span><span>${message}</span>`;
|
||
container.appendChild(toast);
|
||
setTimeout(() => {
|
||
toast.style.transition = 'opacity 0.3s, transform 0.3s';
|
||
toast.style.opacity = '0';
|
||
toast.style.transform = 'translateX(-30px)';
|
||
setTimeout(() => toast.remove(), 300);
|
||
}, duration);
|
||
}
|
||
|
||
// ============ Theme Toggle ============
|
||
const themeToggle = document.getElementById('themeToggle');
|
||
const themeIcon = document.getElementById('themeIcon');
|
||
const html = document.documentElement;
|
||
const savedTheme = localStorage.getItem('swagger-sdk-theme') || 'dark';
|
||
html.setAttribute('data-theme', savedTheme);
|
||
updateThemeUI(savedTheme);
|
||
|
||
themeToggle.addEventListener('click', () => {
|
||
const currentTheme = html.getAttribute('data-theme');
|
||
const newTheme = currentTheme === 'dark' ? 'light' : 'dark';
|
||
html.setAttribute('data-theme', newTheme);
|
||
localStorage.setItem('swagger-sdk-theme', newTheme);
|
||
updateThemeUI(newTheme);
|
||
});
|
||
|
||
function updateThemeUI(theme) {
|
||
themeIcon.textContent = theme === 'dark' ? '☀️' : '🌙';
|
||
}
|
||
|
||
// ============ File Upload ============
|
||
const fileInput = document.getElementById('fileInput');
|
||
const uploadZone = document.getElementById('uploadZone');
|
||
const loadFileBtn = document.getElementById('loadFileBtn');
|
||
|
||
loadFileBtn.addEventListener('click', () => fileInput.click());
|
||
uploadZone.addEventListener('click', () => fileInput.click());
|
||
|
||
uploadZone.addEventListener('dragover', (e) => {
|
||
e.preventDefault();
|
||
uploadZone.classList.add('dragover');
|
||
});
|
||
|
||
uploadZone.addEventListener('dragleave', () => {
|
||
uploadZone.classList.remove('dragover');
|
||
});
|
||
|
||
uploadZone.addEventListener('drop', (e) => {
|
||
e.preventDefault();
|
||
uploadZone.classList.remove('dragover');
|
||
const file = e.dataTransfer.files[0];
|
||
if (file) handleFile(file);
|
||
});
|
||
|
||
fileInput.addEventListener('change', (e) => {
|
||
const file = e.target.files[0];
|
||
if (file) handleFile(file);
|
||
});
|
||
|
||
function handleFile(file) {
|
||
if (!file.name.endsWith('.json') && file.type !== 'application/json') {
|
||
showToast('لطفاً یک فایل JSON معتبر انتخاب کنید', 'error');
|
||
return;
|
||
}
|
||
|
||
const reader = new FileReader();
|
||
reader.onload = (e) => {
|
||
try {
|
||
const json = JSON.parse(e.target.result);
|
||
const normalizedJson = normalizeSwaggerKeys(json);
|
||
processSwagger(normalizedJson);
|
||
showToast('فایل Swagger با موفقیت بارگذاری شد', 'success');
|
||
} catch (err) {
|
||
showToast('خطا در پردازش فایل JSON: ' + err.message, 'error');
|
||
}
|
||
};
|
||
reader.readAsText(file);
|
||
}
|
||
|
||
// ============ Normalize Swagger Keys ============
|
||
function normalizeSwaggerKeys(obj) {
|
||
if (obj === null || typeof obj !== 'object') return obj;
|
||
if (Array.isArray(obj)) return obj.map(normalizeSwaggerKeys);
|
||
const normalized = {};
|
||
for (const key in obj) {
|
||
const trimmedKey = key.trim();
|
||
normalized[trimmedKey] = normalizeSwaggerKeys(obj[key]);
|
||
}
|
||
return normalized;
|
||
}
|
||
|
||
// ============ Swagger Parser ============
|
||
function processSwagger(swagger) {
|
||
AppState.swagger = swagger;
|
||
AppState.allSchemas = swagger.components?.schemas || {};
|
||
AppState.controllers = extractControllers(swagger);
|
||
|
||
renderStats();
|
||
renderControllersList();
|
||
renderControllerTabs();
|
||
|
||
uploadZone.style.display = 'none';
|
||
document.getElementById('loadedContent').style.display = 'block';
|
||
|
||
const firstCtrl = Object.keys(AppState.controllers)[0];
|
||
if (firstCtrl) selectController(firstCtrl);
|
||
}
|
||
|
||
function extractControllers(swagger) {
|
||
const controllers = {};
|
||
const paths = swagger.paths || {};
|
||
|
||
Object.keys(paths).forEach(path => {
|
||
const pathItem = paths[path];
|
||
Object.keys(pathItem).forEach(method => {
|
||
if (['get','post','put','delete','patch','options','head'].indexOf(method) === -1) return;
|
||
const operation = pathItem[method];
|
||
const tags = operation.tags || ['Default'];
|
||
tags.forEach(tag => {
|
||
if (!controllers[tag]) {
|
||
controllers[tag] = { name: tag, endpoints: [], models: new Set() };
|
||
}
|
||
controllers[tag].endpoints.push({
|
||
path, method, operation,
|
||
summary: operation.summary || '',
|
||
description: operation.description || ''
|
||
});
|
||
|
||
const reqBody = operation.requestBody;
|
||
if (reqBody?.content) {
|
||
Object.values(reqBody.content).forEach(ct => {
|
||
if (ct.schema) extractModelsFromSchema(ct.schema, controllers[tag].models);
|
||
});
|
||
}
|
||
|
||
const responses = operation.responses || {};
|
||
Object.values(responses).forEach(resp => {
|
||
if (resp.content) {
|
||
Object.values(resp.content).forEach(ct => {
|
||
if (ct.schema) extractModelsFromSchema(ct.schema, controllers[tag].models);
|
||
});
|
||
}
|
||
});
|
||
});
|
||
});
|
||
});
|
||
|
||
return controllers;
|
||
}
|
||
|
||
function extractModelsFromSchema(schema, modelSet) {
|
||
if (!schema) return;
|
||
if (schema.$ref) {
|
||
const refName = schema.$ref.replace('#/components/schemas/', '');
|
||
if (!modelSet.has(refName) && AppState.allSchemas[refName]) {
|
||
modelSet.add(refName);
|
||
const refSchema = AppState.allSchemas[refName];
|
||
if (refSchema.properties) {
|
||
Object.values(refSchema.properties).forEach(prop => {
|
||
extractModelsFromSchema(prop, modelSet);
|
||
});
|
||
}
|
||
if (refSchema.items) {
|
||
extractModelsFromSchema(refSchema.items, modelSet);
|
||
}
|
||
}
|
||
} else if (schema.items) {
|
||
extractModelsFromSchema(schema.items, modelSet);
|
||
} else if (schema.properties) {
|
||
Object.values(schema.properties).forEach(prop => {
|
||
extractModelsFromSchema(prop, modelSet);
|
||
});
|
||
}
|
||
}
|
||
|
||
// ============ Render Stats ============
|
||
function renderStats() {
|
||
const grid = document.getElementById('statsGrid');
|
||
const totalControllers = Object.keys(AppState.controllers).length;
|
||
const totalEndpoints = Object.values(AppState.controllers).reduce((sum, c) => sum + c.endpoints.length, 0);
|
||
const totalModels = Object.keys(AppState.allSchemas).length;
|
||
const usedModels = new Set();
|
||
Object.values(AppState.controllers).forEach(c => c.models.forEach(m => usedModels.add(m)));
|
||
|
||
grid.innerHTML = `
|
||
<div class="stat-card">
|
||
<div class="stat-value">${totalControllers}</div>
|
||
<div class="stat-label">تعداد کنترلرها</div>
|
||
</div>
|
||
<div class="stat-card">
|
||
<div class="stat-value">${totalEndpoints}</div>
|
||
<div class="stat-label">تعداد اندپوینتها</div>
|
||
</div>
|
||
<div class="stat-card">
|
||
<div class="stat-value">${totalModels}</div>
|
||
<div class="stat-label">کل مدلها</div>
|
||
</div>
|
||
<div class="stat-card">
|
||
<div class="stat-value">${usedModels.size}</div>
|
||
<div class="stat-label">مدلهای استفاده شده</div>
|
||
</div>
|
||
`;
|
||
}
|
||
|
||
// ============ Render Controllers List ============
|
||
function renderControllersList() {
|
||
const list = document.getElementById('controllersList');
|
||
list.innerHTML = '';
|
||
|
||
// Search Input
|
||
const searchWrapper = document.createElement('div');
|
||
searchWrapper.className = 'search-input-wrapper';
|
||
searchWrapper.innerHTML = `
|
||
<input type="text" class="search-input" id="controllerSearch" placeholder="جستجوی کنترلر...">
|
||
<span class="search-icon">🔍</span>
|
||
<button class="search-clear" id="controllerSearchClear">✕</button>
|
||
`;
|
||
list.appendChild(searchWrapper);
|
||
|
||
const ctrlIcons = {
|
||
Account: '👤', FileProvider: '📁', StringProvider: '🔤',
|
||
TagProvider: '🏷️', ContentProvider: '📝', CategoryProvider: '📂',
|
||
SubCategoryProvider: '📑', TermsAndConditionsProvider: '📜',
|
||
TestProvider: '🧪', TestIdentity: '🔐', TestFeatures: '⚙️',
|
||
Startup: '🚀', Default: '📦'
|
||
};
|
||
|
||
const controllersContainer = document.createElement('div');
|
||
controllersContainer.id = 'controllersContainer';
|
||
list.appendChild(controllersContainer);
|
||
|
||
renderFilteredControllers(controllersContainer, ctrlIcons);
|
||
|
||
// Search Handler
|
||
const searchInput = document.getElementById('controllerSearch');
|
||
const clearBtn = document.getElementById('controllerSearchClear');
|
||
|
||
searchInput.addEventListener('input', (e) => {
|
||
AppState.searchTerms.controllers = e.target.value;
|
||
clearBtn.classList.toggle('visible', e.target.value.length > 0);
|
||
renderFilteredControllers(controllersContainer, ctrlIcons);
|
||
});
|
||
|
||
clearBtn.addEventListener('click', () => {
|
||
searchInput.value = '';
|
||
AppState.searchTerms.controllers = '';
|
||
clearBtn.classList.remove('visible');
|
||
renderFilteredControllers(controllersContainer, ctrlIcons);
|
||
});
|
||
}
|
||
|
||
function renderFilteredControllers(container, ctrlIcons) {
|
||
container.innerHTML = '';
|
||
const searchTerm = AppState.searchTerms.controllers.toLowerCase();
|
||
|
||
Object.keys(AppState.controllers).sort().forEach(name => {
|
||
if (searchTerm && !name.toLowerCase().includes(searchTerm)) return;
|
||
|
||
const ctrl = AppState.controllers[name];
|
||
const btn = document.createElement('button');
|
||
btn.className = 'controller-item' + (AppState.activeController === name ? ' active' : '');
|
||
btn.dataset.controller = name;
|
||
btn.innerHTML = `
|
||
<span class="ctrl-icon">${ctrlIcons[name] || '📦'}</span>
|
||
<span class="ctrl-name">${name}</span>
|
||
<span class="ctrl-badge">${ctrl.endpoints.length}</span>
|
||
`;
|
||
btn.addEventListener('click', () => selectController(name));
|
||
container.appendChild(btn);
|
||
});
|
||
|
||
if (container.children.length === 0 && searchTerm) {
|
||
container.innerHTML = '<div class="empty-state" style="padding: 20px;"><p>نتیجهای یافت نشد</p></div>';
|
||
}
|
||
}
|
||
|
||
// ============ Render Controller Tabs ============
|
||
function renderControllerTabs() {
|
||
const tabs = document.getElementById('controllerTabs');
|
||
tabs.innerHTML = '';
|
||
const tabIcons = { overview: '📊', models: '📦', endpoints: '🔌', provider: '⚙️' };
|
||
|
||
['overview', 'models', 'endpoints', 'provider'].forEach(tab => {
|
||
const btn = document.createElement('button');
|
||
btn.className = 'controller-tab' + (tab === 'overview' ? ' active' : '');
|
||
btn.dataset.tab = tab;
|
||
const tabNames = { overview: 'نمای کلی', models: 'مدلها', endpoints: 'اندپوینتها', provider: 'Service' };
|
||
btn.innerHTML = `<span>${tabIcons[tab]}</span><span>${tabNames[tab]}</span>`;
|
||
btn.addEventListener('click', () => switchTab(tab));
|
||
tabs.appendChild(btn);
|
||
});
|
||
}
|
||
|
||
function switchTab(tabName) {
|
||
document.querySelectorAll('.controller-tab').forEach(t => {
|
||
t.classList.toggle('active', t.dataset.tab === tabName);
|
||
});
|
||
renderControllerContent(tabName);
|
||
}
|
||
|
||
// ============ Select Controller ============
|
||
function selectController(name) {
|
||
AppState.activeController = name;
|
||
document.querySelectorAll('.controller-item').forEach(item => {
|
||
item.classList.toggle('active', item.dataset.controller === name);
|
||
});
|
||
const activeTab = document.querySelector('.controller-tab.active')?.dataset.tab || 'overview';
|
||
renderControllerContent(activeTab);
|
||
}
|
||
|
||
// ============ Render Controller Content ============
|
||
function renderControllerContent(tabName) {
|
||
const content = document.getElementById('controllerContent');
|
||
const ctrl = AppState.controllers[AppState.activeController];
|
||
if (!ctrl) {
|
||
content.innerHTML = '<div class="empty-state"><div class="empty-state-icon">📭</div><h3>کنترلری انتخاب نشده</h3></div>';
|
||
return;
|
||
}
|
||
|
||
if (tabName === 'overview') renderOverview(ctrl, content);
|
||
else if (tabName === 'models') renderModels(ctrl, content);
|
||
else if (tabName === 'endpoints') renderEndpoints(ctrl, content);
|
||
else if (tabName === 'provider') renderProviderService(ctrl, content);
|
||
}
|
||
|
||
// ============ Overview Tab ============
|
||
function renderOverview(ctrl, container) {
|
||
const methodCounts = { get: 0, post: 0, put: 0, delete: 0 };
|
||
ctrl.endpoints.forEach(e => { if (methodCounts[e.method] !== undefined) methodCounts[e.method]++; });
|
||
|
||
container.innerHTML = `
|
||
<div class="content-section">
|
||
<div class="section-header">
|
||
<div class="section-icon">📊</div>
|
||
<div class="section-title">
|
||
<h3>کنترلر ${ctrl.name}</h3>
|
||
<div class="subtitle">نمای کلی از کنترلر و آمار آن</div>
|
||
</div>
|
||
</div>
|
||
<div class="stats-grid">
|
||
<div class="stat-card">
|
||
<div class="stat-value">${ctrl.endpoints.length}</div>
|
||
<div class="stat-label">تعداد اندپوینتها</div>
|
||
</div>
|
||
<div class="stat-card">
|
||
<div class="stat-value">${ctrl.models.size}</div>
|
||
<div class="stat-label">مدلهای مرتبط</div>
|
||
</div>
|
||
<div class="stat-card">
|
||
<div class="stat-value" style="color: #63b3ed;">${methodCounts.get}</div>
|
||
<div class="stat-label">GET</div>
|
||
</div>
|
||
<div class="stat-card">
|
||
<div class="stat-value" style="color: #68d391;">${methodCounts.post}</div>
|
||
<div class="stat-label">POST</div>
|
||
</div>
|
||
<div class="stat-card">
|
||
<div class="stat-value" style="color: #f6ad55;">${methodCounts.put}</div>
|
||
<div class="stat-label">PUT</div>
|
||
</div>
|
||
<div class="stat-card">
|
||
<div class="stat-value" style="color: #fc8181;">${methodCounts.delete}</div>
|
||
<div class="stat-label">DELETE</div>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="content-section">
|
||
<div class="section-header">
|
||
<div class="section-icon">🔌</div>
|
||
<div class="section-title">
|
||
<h3>اندپوینتهای اخیر</h3>
|
||
<div class="subtitle">۵ اندپوینت اول کنترلر</div>
|
||
</div>
|
||
</div>
|
||
${renderEndpointsTable(ctrl.endpoints.slice(0, 5))}
|
||
</div>
|
||
`;
|
||
}
|
||
|
||
// ============ Models Tab ============
|
||
function renderModels(ctrl, container) {
|
||
const models = Array.from(ctrl.models).sort();
|
||
|
||
container.innerHTML = `
|
||
<div class="content-section">
|
||
<div class="section-header">
|
||
<div class="section-icon">📦</div>
|
||
<div class="section-title">
|
||
<h3>مدلهای کنترلر ${ctrl.name}</h3>
|
||
<div class="subtitle">برای مشاهده جزئیات و تولید کد TypeScript روی هر مدل کلیک کنید</div>
|
||
</div>
|
||
</div>
|
||
<div class="search-input-wrapper" style="max-width: 400px; margin-bottom: 16px;">
|
||
<input type="text" class="search-input" id="modelSearch" placeholder="جستجوی مدل...">
|
||
<span class="search-icon">🔍</span>
|
||
<button class="search-clear" id="modelSearchClear">✕</button>
|
||
</div>
|
||
<div class="models-grid" id="modelsGrid"></div>
|
||
</div>
|
||
`;
|
||
|
||
renderFilteredModels(models);
|
||
|
||
const searchInput = document.getElementById('modelSearch');
|
||
const clearBtn = document.getElementById('modelSearchClear');
|
||
|
||
searchInput.addEventListener('input', (e) => {
|
||
AppState.searchTerms.models = e.target.value;
|
||
clearBtn.classList.toggle('visible', e.target.value.length > 0);
|
||
renderFilteredModels(models);
|
||
});
|
||
|
||
clearBtn.addEventListener('click', () => {
|
||
searchInput.value = '';
|
||
AppState.searchTerms.models = '';
|
||
clearBtn.classList.remove('visible');
|
||
renderFilteredModels(models);
|
||
});
|
||
}
|
||
|
||
function renderFilteredModels(allModels) {
|
||
const grid = document.getElementById('modelsGrid');
|
||
if (!grid) return;
|
||
|
||
const searchTerm = AppState.searchTerms.models.toLowerCase();
|
||
const filteredModels = allModels.filter(name =>
|
||
!searchTerm || name.toLowerCase().includes(searchTerm)
|
||
);
|
||
|
||
if (filteredModels.length === 0) {
|
||
grid.innerHTML = searchTerm
|
||
? '<div class="empty-state" style="grid-column: 1/-1;"><p>مدلی با این نام یافت نشد</p></div>'
|
||
: '<div class="empty-state" style="grid-column: 1/-1;"><div class="empty-state-icon">📭</div><h3>مدلی یافت نشد</h3></div>';
|
||
return;
|
||
}
|
||
|
||
const modelCards = filteredModels.map(name => {
|
||
const schema = AppState.allSchemas[name];
|
||
const propsCount = schema?.properties ? Object.keys(schema.properties).length : 0;
|
||
const type = schema?.enum ? 'Enum' : 'DTO';
|
||
const icon = type === 'Enum' ? '🔢' : '📦';
|
||
return `
|
||
<div class="model-card" data-model="${name}">
|
||
<div class="model-card-header">
|
||
<div class="model-card-icon">${icon}</div>
|
||
<div class="model-card-name" title="${name}">${name}</div>
|
||
</div>
|
||
<div class="model-card-meta">
|
||
<span>🔹 ${type}</span>
|
||
<span>📐 ${propsCount} فیلد</span>
|
||
</div>
|
||
</div>
|
||
`;
|
||
}).join('');
|
||
|
||
grid.innerHTML = modelCards;
|
||
|
||
grid.querySelectorAll('.model-card').forEach(card => {
|
||
card.addEventListener('click', () => {
|
||
openModelModal(card.dataset.model);
|
||
});
|
||
});
|
||
}
|
||
|
||
// ============ Endpoints Tab ============
|
||
function renderEndpoints(ctrl, container) {
|
||
container.innerHTML = `
|
||
<div class="content-section">
|
||
<div class="section-header">
|
||
<div class="section-icon">🔌</div>
|
||
<div class="section-title">
|
||
<h3>اندپوینتهای کنترلر ${ctrl.name}</h3>
|
||
<div class="subtitle">لیست کامل اندپوینتهای این کنترلر</div>
|
||
</div>
|
||
</div>
|
||
<div class="search-input-wrapper" style="max-width: 400px; margin-bottom: 16px;">
|
||
<input type="text" class="search-input" id="endpointSearch" placeholder="جستجوی اندپوینت (مسیر یا توضیحات)...">
|
||
<span class="search-icon">🔍</span>
|
||
<button class="search-clear" id="endpointSearchClear">✕</button>
|
||
</div>
|
||
<div id="endpointsTable"></div>
|
||
</div>
|
||
`;
|
||
|
||
renderFilteredEndpoints(ctrl.endpoints);
|
||
|
||
const searchInput = document.getElementById('endpointSearch');
|
||
const clearBtn = document.getElementById('endpointSearchClear');
|
||
|
||
searchInput.addEventListener('input', (e) => {
|
||
AppState.searchTerms.endpoints = e.target.value;
|
||
clearBtn.classList.toggle('visible', e.target.value.length > 0);
|
||
renderFilteredEndpoints(ctrl.endpoints);
|
||
});
|
||
|
||
clearBtn.addEventListener('click', () => {
|
||
searchInput.value = '';
|
||
AppState.searchTerms.endpoints = '';
|
||
clearBtn.classList.remove('visible');
|
||
renderFilteredEndpoints(ctrl.endpoints);
|
||
});
|
||
}
|
||
|
||
function renderFilteredEndpoints(allEndpoints) {
|
||
const tableContainer = document.getElementById('endpointsTable');
|
||
if (!tableContainer) return;
|
||
|
||
const searchTerm = AppState.searchTerms.endpoints.toLowerCase();
|
||
const filteredEndpoints = allEndpoints.filter(e => {
|
||
if (!searchTerm) return true;
|
||
return e.path.toLowerCase().includes(searchTerm) ||
|
||
(e.summary || '').toLowerCase().includes(searchTerm);
|
||
});
|
||
|
||
if (filteredEndpoints.length === 0) {
|
||
tableContainer.innerHTML = searchTerm
|
||
? '<div class="empty-state"><p>اندپوینتی با این مشخصات یافت نشد</p></div>'
|
||
: '<div class="empty-state"><div class="empty-state-icon">📭</div><h3>اندپوینتی یافت نشد</h3></div>';
|
||
return;
|
||
}
|
||
|
||
tableContainer.innerHTML = renderEndpointsTable(filteredEndpoints);
|
||
}
|
||
|
||
function renderEndpointsTable(endpoints) {
|
||
const rows = endpoints.map(e => `
|
||
<tr>
|
||
<td><span class="method-badge method-${e.method}">${e.method.toUpperCase()}</span></td>
|
||
<td class="endpoint-path">${e.path}</td>
|
||
<td>${e.summary || '-'}</td>
|
||
</tr>
|
||
`).join('');
|
||
|
||
return `
|
||
<table class="endpoints-table">
|
||
<thead>
|
||
<tr>
|
||
<th>متد</th>
|
||
<th>مسیر</th>
|
||
<th>توضیحات</th>
|
||
</tr>
|
||
</thead>
|
||
<tbody>${rows}</tbody>
|
||
</table>
|
||
`;
|
||
}
|
||
|
||
/* =========================================================================
|
||
Provider Service Generator
|
||
========================================================================= */
|
||
|
||
function renderProviderService(ctrl, content) {
|
||
const providerCode = generateProviderService(ctrl.name, ctrl.endpoints);
|
||
AppState.generatedProviderCode = providerCode.code;
|
||
AppState.generatedProviderFilename = providerCode.filename;
|
||
|
||
content.innerHTML = `
|
||
<div class="content-section">
|
||
<div class="section-header">
|
||
<div class="section-icon">⚙️</div>
|
||
<div class="section-title">
|
||
<h3>Service برای کنترلر ${ctrl.name}</h3>
|
||
<div class="subtitle">تولید خودکار کلاس فراخوانی سرویسها مطابق با الگوی xApiSDKHolder</div>
|
||
</div>
|
||
</div>
|
||
<div class="provider-service-info">
|
||
<strong>ℹ️ توضیحات:</strong>
|
||
این سرویس بر اساس الگوی <code>XStringProviderService</code> از پروژه <code>xApiSDKHolder</code> تولید شده است.
|
||
شامل تمام متدها با ۴ overload، کامنتهای JSDoc، و استفاده از
|
||
<code>XValidators</code>، <code>fillRouteParams</code>، <code>addCustomParam</code> و
|
||
<code>applyConnectionIdToHeader</code> میباشد.
|
||
</div>
|
||
<div class="file-actions">
|
||
<button class="btn btn-success" onclick="downloadProviderFile()">
|
||
<span>💾</span>
|
||
<span>دانلود ${providerCode.filename}</span>
|
||
</button>
|
||
<button class="btn btn-ghost" style="background: var(--column-bg); color: var(--text); border: 1px solid var(--border);" onclick="openProviderModal()">
|
||
<span>👁️</span>
|
||
<span>مشاهده کامل کد</span>
|
||
</button>
|
||
<button class="btn btn-ghost" style="background: var(--column-bg); color: var(--text); border: 1px solid var(--border);" onclick="copyProviderCode()">
|
||
<span>📋</span>
|
||
<span>کپی کد</span>
|
||
</button>
|
||
</div>
|
||
<div class="code-block-header" style="margin-top: 18px;">
|
||
<span>📄 ${providerCode.filename}</span>
|
||
<span style="color: var(--accent);">TypeScript | ${providerCode.methodCount} متد</span>
|
||
</div>
|
||
<div class="code-block"><pre>${highlightTS(providerCode.code)}</pre></div>
|
||
</div>
|
||
`;
|
||
}
|
||
|
||
function generateProviderService(controllerName, endpoints) {
|
||
const filteredEndpoints = endpoints.filter(e => {
|
||
const path = e.path.toLowerCase();
|
||
return !path.includes('/test/') && !path.endsWith('/test');
|
||
});
|
||
|
||
if (filteredEndpoints.length === 0) {
|
||
return {
|
||
code: `// هیچ اندپوینت قابل استفادهای در این کنترلر وجود ندارد\n`,
|
||
filename: `${controllerName}.service.ts`,
|
||
methodCount: 0
|
||
};
|
||
}
|
||
|
||
const className = `X${controllerName}Service`;
|
||
const routeEnumName = `X${controllerName}ServiceRoute`;
|
||
const paramEnumName = `X${controllerName}Param`;
|
||
const endPointEnumValue = `XApiEndPoint.${controllerName}sService`;
|
||
|
||
const basePath = extractBasePath(filteredEndpoints);
|
||
|
||
const routeEntries = [];
|
||
const paramEntries = new Map();
|
||
const methods = [];
|
||
|
||
filteredEndpoints.forEach(ep => {
|
||
const routeInfo = extractRouteInfo(ep.path, basePath);
|
||
const routeName = routeInfo.routeName;
|
||
const routeValue = routeInfo.routeValue;
|
||
|
||
if (!routeEntries.find(r => r.name === routeName)) {
|
||
routeEntries.push({ name: routeName, value: routeValue });
|
||
}
|
||
|
||
const pathParams = extractPathParams(ep.path, basePath);
|
||
pathParams.forEach(p => paramEntries.set(p.name, p.name));
|
||
|
||
const queryParams = (ep.operation.parameters || []).filter(p => p.in === 'query');
|
||
queryParams.forEach(p => paramEntries.set(p.name, p.name));
|
||
|
||
const methodInfo = generateMethod(ep, routeName, routeValue, basePath);
|
||
methods.push(methodInfo);
|
||
});
|
||
|
||
const routeEnumCode = generateRouteEnum(routeEnumName, routeEntries);
|
||
const paramEnumCode = generateParamEnum(paramEnumName, Array.from(paramEntries.values()));
|
||
const classCode = generateProviderClass(
|
||
className,
|
||
routeEnumName,
|
||
paramEnumName,
|
||
endPointEnumValue,
|
||
controllerName,
|
||
methods
|
||
);
|
||
|
||
const importsCode = generateImports(controllerName, methods);
|
||
|
||
const fullCode = `${importsCode}
|
||
|
||
${routeEnumCode}
|
||
|
||
${paramEnumCode}
|
||
|
||
${classCode}
|
||
`;
|
||
|
||
return {
|
||
code: fullCode,
|
||
filename: `${controllerName}.service.ts`,
|
||
methodCount: methods.length
|
||
};
|
||
}
|
||
|
||
function extractBasePath(endpoints) {
|
||
const paths = endpoints.map(e => e.path);
|
||
if (paths.length === 0) return '';
|
||
|
||
const firstPath = paths[0];
|
||
const parts = firstPath.split('/').filter(p => p);
|
||
let basePath = '';
|
||
|
||
for (let i = 0; i < parts.length; i++) {
|
||
const part = parts[i];
|
||
if (part.endsWith('Provider') || part === 'Account' || part === 'Startup' || part === 'TestIdentity' || part === 'TestFeatures') {
|
||
basePath = '/' + parts.slice(0, i + 1).join('/');
|
||
break;
|
||
}
|
||
}
|
||
|
||
return basePath;
|
||
}
|
||
|
||
function extractRouteInfo(path, basePath) {
|
||
let relativePath = path;
|
||
if (basePath && path.startsWith(basePath)) {
|
||
relativePath = path.substring(basePath.length);
|
||
}
|
||
if (relativePath.startsWith('/')) relativePath = relativePath.substring(1);
|
||
|
||
let routeName;
|
||
let routeValue = relativePath;
|
||
|
||
if (relativePath === '' || relativePath === '/') {
|
||
routeName = 'Root';
|
||
} else {
|
||
const segments = relativePath.split('/').filter(s => s);
|
||
routeName = segments.map(s => {
|
||
if (s.startsWith('{') && s.endsWith('}')) return 'ById';
|
||
return s.charAt(0).toUpperCase() + s.slice(1);
|
||
}).join('');
|
||
}
|
||
|
||
if (routeName === 'Root') routeName = 'All';
|
||
if (routeName === 'ById') routeName = 'Get';
|
||
if (routeName === 'Query') routeName = 'Query';
|
||
if (routeName === 'FindOne') routeName = 'FindOne';
|
||
if (routeName === 'FindMany') routeName = 'FindMany';
|
||
if (routeName === 'Add') routeName = 'Add';
|
||
if (routeName === 'UpdateById' || routeName === 'Update') routeName = 'Update';
|
||
if (routeName === 'RemoveById' || routeName === 'Remove') routeName = 'Remove';
|
||
if (routeName === 'QueryOwned') routeName = 'QueryOwned';
|
||
|
||
return { routeName, routeValue };
|
||
}
|
||
|
||
function extractPathParams(path, basePath) {
|
||
let relativePath = path;
|
||
if (basePath && path.startsWith(basePath)) {
|
||
relativePath = path.substring(basePath.length);
|
||
}
|
||
const params = [];
|
||
const matches = relativePath.matchAll(/\{([^}]+)\}/g);
|
||
for (const match of matches) {
|
||
const paramName = match[1];
|
||
if (paramName !== 'version') {
|
||
params.push({ name: paramName });
|
||
}
|
||
}
|
||
return params;
|
||
}
|
||
|
||
function generateRouteEnum(enumName, entries) {
|
||
const lines = entries.map(e => `${e.name} = '${e.value}',`).join('\n ');
|
||
return `/**
|
||
* All Available EndPoint Routes ...
|
||
*/
|
||
export enum ${enumName} {
|
||
${lines}
|
||
}`;
|
||
}
|
||
|
||
function generateParamEnum(enumName, paramNames) {
|
||
if (paramNames.length === 0) {
|
||
return `/**
|
||
* All Params Which Used in Related Services ...
|
||
*/
|
||
export enum ${enumName} {
|
||
// No params
|
||
}
|
||
`;
|
||
}
|
||
const lines = paramNames.map(p => {
|
||
const pascalName = p.charAt(0).toUpperCase() + p.slice(1);
|
||
return `${pascalName} = '${p}',`;
|
||
}).join('\n ');
|
||
return `/**
|
||
* All Params Which Used in Related Services ...
|
||
*/
|
||
export enum ${enumName} {
|
||
${lines}
|
||
}`;
|
||
}
|
||
|
||
function generateImports(controllerName, methods) {
|
||
const needsFormData = methods.some(m => m.isFormData);
|
||
const needsConnectionId = methods.some(m => m.hasConnectionId);
|
||
const needsFillRouteParams = methods.some(m => m.hasPathParams);
|
||
const needsXQuery = methods.some(m => m.isXQuery);
|
||
|
||
const coreImports = ['XValidators'];
|
||
if (needsFormData) coreImports.push('toArray', 'hasChild');
|
||
|
||
const httpImports = ['HttpEvent', 'HttpClient', 'HttpParams', 'HttpHeaders', 'HttpResponse'];
|
||
const identityImports = ['X_API_CONFIG', 'XBaseApiService', 'XApiConfiguration'];
|
||
if (needsXQuery) identityImports.push('XQueryDto', 'XQueryResultDto');
|
||
|
||
const routeEnumName = `X${controllerName}ServiceRoute`;
|
||
const paramEnumName = `X${controllerName}Param`;
|
||
|
||
const usedModels = new Set();
|
||
methods.forEach(m => {
|
||
if (m.bodyType && !m.bodyType.startsWith('Array<') && !['string', 'number', 'boolean', 'void', 'any', 'FormData'].includes(m.bodyType)) {
|
||
usedModels.add(m.bodyType.replace('Array<', '').replace('>', ''));
|
||
}
|
||
if (m.returnType && !m.returnType.startsWith('Array<') && !['string', 'number', 'boolean', 'void', 'any', 'ArrayBuffer', 'Blob'].includes(m.returnType)) {
|
||
usedModels.add(m.returnType.replace('Array<', '').replace('>', ''));
|
||
}
|
||
});
|
||
|
||
let imports = `import {
|
||
${coreImports.join(',\n ')},
|
||
} from 'x-framework-core';
|
||
import {
|
||
${httpImports.join(',\n ')},
|
||
} from '@angular/common/http';
|
||
import {
|
||
${identityImports.join(',\n ')},
|
||
} from 'x-framework-identity-sdk';
|
||
import { Observable } from 'rxjs';
|
||
import { Router } from '@angular/router';
|
||
import { Inject, Injectable } from '@angular/core';`;
|
||
|
||
if (needsFillRouteParams) {
|
||
imports += `\nimport { fillRouteParams } from '../../tools/x-route.tools';`;
|
||
}
|
||
|
||
imports += `\nimport { XApiEndPoint } from '../../typings/x-endpoint.typings';`;
|
||
imports += `\nimport { ${routeEnumName}, ${paramEnumName} } from '../x-${toKebabCase(controllerName)}.typings';`;
|
||
|
||
if (needsConnectionId) {
|
||
imports += `\nimport { applyConnectionIdToHeader } from '../../typings/x-push-provider.typings';`;
|
||
}
|
||
|
||
imports += `\nimport { X_SAHERELM_API_SDK_CONFIG } from '../../tokens/x-injectable-tokens';`;
|
||
imports += `\nimport { XSaherElmApiSDKConfig } from '../../config/x-saherelm-api-sdk.config';`;
|
||
|
||
if (usedModels.size > 0) {
|
||
const modelImports = Array.from(usedModels).map(m => m);
|
||
imports += `\n//\n// Models ...`;
|
||
modelImports.forEach(m => {
|
||
const fileName = toKebabCase(m);
|
||
imports += `\nimport { ${m} } from '../../models/${fileName}.dto';`;
|
||
});
|
||
}
|
||
|
||
return imports;
|
||
}
|
||
|
||
function generateMethod(endpoint, routeName, routeValue, basePath) {
|
||
const method = endpoint.method;
|
||
const operation = endpoint.operation;
|
||
const summary = (operation.summary || '').replace(/\r?\n/g, ' ').trim();
|
||
const description = (operation.description || '').replace(/\r?\n/g, ' ').trim();
|
||
|
||
const parameters = operation.parameters || [];
|
||
const pathParams = parameters.filter(p => p.in === 'path' && p.name !== 'version');
|
||
const queryParams = parameters.filter(p => p.in === 'query');
|
||
|
||
let bodyType = null;
|
||
let bodyParamName = null;
|
||
let isFormData = false;
|
||
const requestBody = operation.requestBody;
|
||
if (requestBody?.content) {
|
||
if (requestBody.content['multipart/form-data']) {
|
||
isFormData = true;
|
||
bodyType = 'FormData';
|
||
bodyParamName = 'formData';
|
||
} else if (requestBody.content['application/json']) {
|
||
const schema = requestBody.content['application/json'].schema;
|
||
bodyType = resolveType(schema);
|
||
bodyParamName = 'model';
|
||
}
|
||
}
|
||
|
||
let returnType = 'void';
|
||
const successResponse = operation.responses?.['200'];
|
||
if (successResponse?.content?.['application/json']?.schema) {
|
||
returnType = resolveType(successResponse.content['application/json'].schema);
|
||
}
|
||
|
||
const isXQuery = queryParams.some(p => ['Filter', 'ContainsDetail', 'SortBy', 'IsAscending', 'Page', 'PageSize'].includes(p.name));
|
||
const hasConnectionId = method === 'post' || method === 'put' || method === 'delete';
|
||
const methodName = toCamelCase(routeName);
|
||
|
||
const methodParams = [];
|
||
|
||
pathParams.forEach(p => {
|
||
const tsType = resolveParamType(p.schema);
|
||
methodParams.push({ name: p.name, type: tsType, required: true, source: 'path' });
|
||
});
|
||
|
||
if (bodyType && !isFormData) {
|
||
methodParams.push({ name: bodyParamName, type: bodyType, required: true, source: 'body' });
|
||
}
|
||
|
||
if (!isXQuery) {
|
||
queryParams.forEach(p => {
|
||
const tsType = resolveParamType(p.schema);
|
||
methodParams.push({ name: p.name, type: tsType, required: p.required || false, source: 'query' });
|
||
});
|
||
} else {
|
||
methodParams.push({ name: 'query', type: 'XQueryDto', required: true, source: 'query' });
|
||
}
|
||
|
||
if (hasConnectionId) {
|
||
methodParams.push({ name: 'connectionId', type: 'string', required: false, source: 'connection' });
|
||
}
|
||
|
||
methodParams.push({ name: 'observe', type: "'body' | 'response' | 'events'", required: false, source: 'observe' });
|
||
methodParams.push({ name: 'reportProgress', type: 'boolean', required: false, source: 'progress' });
|
||
|
||
return {
|
||
methodName,
|
||
httpMethod: method,
|
||
routeName,
|
||
routeValue,
|
||
summary,
|
||
description,
|
||
pathParams,
|
||
queryParams,
|
||
bodyType,
|
||
bodyParamName,
|
||
returnType,
|
||
isFormData,
|
||
isXQuery,
|
||
hasConnectionId,
|
||
hasPathParams: pathParams.length > 0,
|
||
methodParams
|
||
};
|
||
}
|
||
|
||
function resolveParamType(schema) {
|
||
if (!schema) return 'string';
|
||
if (schema.$ref) return schema.$ref.replace('#/components/schemas/', '');
|
||
if (schema.type === 'string') {
|
||
if (schema.format === 'uuid') return 'string';
|
||
if (schema.format === 'date-time') return 'string';
|
||
return 'string';
|
||
}
|
||
if (schema.type === 'integer' || schema.type === 'number') return 'number';
|
||
if (schema.type === 'boolean') return 'boolean';
|
||
if (schema.type === 'array') return 'Array<string>';
|
||
return 'string';
|
||
}
|
||
|
||
function resolveType(schema) {
|
||
if (!schema) return 'any';
|
||
if (schema.$ref) return schema.$ref.replace('#/components/schemas/', '');
|
||
if (schema.type === 'array') {
|
||
const itemType = resolveType(schema.items);
|
||
return `Array<${itemType}>`;
|
||
}
|
||
if (schema.type === 'string') {
|
||
if (schema.format === 'date-time') return 'Date';
|
||
if (schema.format === 'binary') return 'File';
|
||
if (schema.format === 'uuid') return 'string';
|
||
return 'string';
|
||
}
|
||
if (schema.type === 'integer' || schema.type === 'number') return 'number';
|
||
if (schema.type === 'boolean') return 'boolean';
|
||
return 'any';
|
||
}
|
||
|
||
function generateProviderClass(className, routeEnumName, paramEnumName, endPointEnumValue, controllerName, methods) {
|
||
const methodsCode = methods.map(m => generateMethodCode(m, routeEnumName, paramEnumName)).join('\n\n');
|
||
|
||
return `/**
|
||
* Provides all Provider Actions as a Service ...
|
||
*/
|
||
@Injectable({
|
||
providedIn: 'root',
|
||
})
|
||
export class ${className} extends XBaseApiService {
|
||
//
|
||
//#region Constructor ...
|
||
constructor(
|
||
protected router: Router,
|
||
protected httpClient: HttpClient,
|
||
@Inject(X_SAHERELM_API_SDK_CONFIG) config: XSaherElmApiSDKConfig,
|
||
@Inject(X_API_CONFIG) apiConfig: XApiConfiguration
|
||
) {
|
||
super(${endPointEnumValue}, true, true, httpClient, config, apiConfig);
|
||
}
|
||
//#endregion
|
||
//
|
||
//#region Actions ...
|
||
//
|
||
${methodsCode}
|
||
//#endregion
|
||
}`;
|
||
}
|
||
|
||
function generateMethodCode(methodInfo, routeEnumName, paramEnumName) {
|
||
const { methodName, httpMethod, routeName, summary, description, pathParams, queryParams, bodyType, bodyParamName, returnType, isFormData, isXQuery, hasConnectionId, hasPathParams, methodParams } = methodInfo;
|
||
|
||
const signatureParams = methodParams.filter(p => p.source !== 'observe' && p.source !== 'progress');
|
||
const signatureStr = signatureParams.map(p => {
|
||
const optional = p.required ? '' : '?';
|
||
return `${p.name}${optional}: ${p.type}`;
|
||
}).join(',\n ');
|
||
|
||
let jsDoc = `/**\n`;
|
||
if (summary) {
|
||
jsDoc += `* ${summary}\n`;
|
||
}
|
||
if (description && description !== summary) {
|
||
jsDoc += `*\n* ${description.substring(0, 200)}\n`;
|
||
}
|
||
signatureParams.forEach(p => {
|
||
jsDoc += `*\n* @param ${p.name}\n`;
|
||
});
|
||
jsDoc += `*\n* @param observe\n* @param reportProgress\n*/`;
|
||
|
||
const overloads = [];
|
||
const observeTypes = ['body', 'response', 'events'];
|
||
observeTypes.forEach(obs => {
|
||
let obsReturnType;
|
||
if (obs === 'body') obsReturnType = returnType;
|
||
else if (obs === 'response') obsReturnType = `HttpResponse<${returnType}>`;
|
||
else obsReturnType = `HttpEvent<${returnType}>`;
|
||
|
||
const obsParams = signatureParams.map(p => {
|
||
const optional = p.required ? '' : '?';
|
||
return `${p.name}${optional}: ${p.type}`;
|
||
});
|
||
obsParams.push(`observe?: '${obs}'`);
|
||
obsParams.push(`reportProgress?: boolean`);
|
||
|
||
overloads.push(` public ${methodName}(\n ${obsParams.join(',\n ')}\n ): Observable<${obsReturnType}>;`);
|
||
});
|
||
|
||
const finalParams = signatureParams.map(p => {
|
||
const optional = p.required ? '' : '?';
|
||
return `${p.name}${optional}: ${p.type}`;
|
||
});
|
||
finalParams.push(`observe: any = 'body'`);
|
||
finalParams.push(`reportProgress: boolean = false`);
|
||
|
||
const methodBody = generateMethodBody(methodInfo, routeEnumName, paramEnumName);
|
||
|
||
return `${jsDoc}
|
||
${overloads.join('\n')}
|
||
public ${methodName}(
|
||
${finalParams.join(',\n ')}
|
||
): Observable<any> {
|
||
${methodBody}
|
||
}`;
|
||
}
|
||
|
||
function generateMethodBody(methodInfo, routeEnumName, paramEnumName) {
|
||
const { httpMethod, routeName, pathParams, queryParams, bodyType, bodyParamName, returnType, isFormData, isXQuery, hasConnectionId, hasPathParams } = methodInfo;
|
||
|
||
let body = '';
|
||
|
||
const validations = [];
|
||
pathParams.forEach(p => {
|
||
if (p.schema?.type === 'string' || !p.schema) {
|
||
validations.push(`XValidators.validateNotEmpty(${p.name});`);
|
||
} else {
|
||
validations.push(`XValidators.validateNotNull(${p.name});`);
|
||
}
|
||
});
|
||
|
||
if (bodyType && !isFormData) {
|
||
validations.push(`XValidators.validateNotNull(${bodyParamName});`);
|
||
}
|
||
|
||
queryParams.forEach(p => {
|
||
if (p.required) {
|
||
if (p.schema?.type === 'string') {
|
||
validations.push(`XValidators.validateNotEmpty(${p.name});`);
|
||
} else {
|
||
validations.push(`XValidators.validateNotNull(${p.name});`);
|
||
}
|
||
}
|
||
});
|
||
|
||
if (validations.length > 0) {
|
||
body += ` //\n // Validate Args ...\n`;
|
||
validations.forEach(v => body += ` ${v}\n`);
|
||
}
|
||
|
||
if (isFormData) {
|
||
body += ` //\n // Preparing Form Data ...\n`;
|
||
body += ` let formData = new FormData();\n`;
|
||
const filesParam = queryParams.find(p => p.name.toLowerCase() === 'files');
|
||
if (filesParam) {
|
||
body += ` const filesArr = toArray(${filesParam.name});\n`;
|
||
body += ` if (hasChild(filesArr)) {\n`;
|
||
body += ` filesArr.forEach((f) => {\n`;
|
||
body += ` formData.append('${filesParam.name}', f, f.name);\n`;
|
||
body += ` });\n`;
|
||
body += ` }\n`;
|
||
}
|
||
}
|
||
|
||
body += ` //\n // Base Requirements ...\n`;
|
||
body += ` let params: HttpParams = null;\n`;
|
||
body += ` let headers: HttpHeaders = this.defaultHeaders;\n`;
|
||
body += ` //\n`;
|
||
body += ` // Authentication ...\n`;
|
||
body += ` headers = this.addAuthentication(headers);\n`;
|
||
|
||
if (httpMethod !== 'get' && !isFormData) {
|
||
body += ` headers = this.addAcceptJson(headers);\n`;
|
||
body += ` headers = this.addContentType(headers);\n`;
|
||
} else if (isFormData) {
|
||
body += ` headers = this.addAuthentication(headers);\n`;
|
||
}
|
||
|
||
if (hasConnectionId) {
|
||
body += ` headers = applyConnectionIdToHeader(connectionId, headers);\n`;
|
||
}
|
||
|
||
body += ` //\n // Prepare Endpoint\n`;
|
||
if (hasPathParams) {
|
||
const paramMappings = pathParams.map(p => {
|
||
const pascalName = p.name.charAt(0).toUpperCase() + p.name.slice(1);
|
||
return ` {\n key: ${paramEnumName}.${pascalName},\n value: ${p.name}.toString(),\n }`;
|
||
}).join(',\n');
|
||
body += ` const endPointPath = fillRouteParams(\n //\n // Base Route on Endpoint ...\n this.getActionRoute(${routeEnumName}.${methodInfo.routeName}),\n //\n // Params ...\n [\n${paramMappings}\n ]\n );\n`;
|
||
} else {
|
||
body += ` const endPointPath = this.getActionRoute(${routeEnumName}.${methodInfo.routeName});\n`;
|
||
}
|
||
|
||
if (isXQuery) {
|
||
body += ` //\n // Preparing HttpParams ...\n`;
|
||
body += ` params = this.generateXQueryHttpParams(query);\n`;
|
||
} else {
|
||
const nonSpecialQueryParams = queryParams.filter(p => !['Filter', 'ContainsDetail', 'SortBy', 'IsAscending', 'Page', 'PageSize', 'version', 'useDefaultOrders', 'useDefaultIncludes'].includes(p.name));
|
||
if (nonSpecialQueryParams.length > 0) {
|
||
body += ` //\n // Preparing HttpParams ...\n`;
|
||
nonSpecialQueryParams.forEach(p => {
|
||
const pascalName = p.name.charAt(0).toUpperCase() + p.name.slice(1);
|
||
if (p.schema?.type === 'string') {
|
||
body += ` if (!isNullOrEmptyString(${p.name})) {\n`;
|
||
body += ` params = this.addCustomParam(params, {\n`;
|
||
body += ` key: ${paramEnumName}.${pascalName},\n`;
|
||
body += ` value: ${p.name},\n`;
|
||
body += ` });\n`;
|
||
body += ` }\n`;
|
||
} else {
|
||
body += ` if (!isNullOrUndefined(${p.name})) {\n`;
|
||
body += ` params = this.addCustomParam(params, {\n`;
|
||
body += ` key: ${paramEnumName}.${pascalName},\n`;
|
||
body += ` value: ${p.name}.toString(),\n`;
|
||
body += ` });\n`;
|
||
body += ` }\n`;
|
||
}
|
||
});
|
||
}
|
||
}
|
||
|
||
body += ` //\n // Prepare Result ...\n`;
|
||
|
||
const httpClientMethod = httpMethod === 'delete' ? 'delete' : httpMethod;
|
||
let bodyArg = '';
|
||
if (isFormData) bodyArg = 'formData';
|
||
else if (bodyType && httpMethod !== 'get' && httpMethod !== 'delete') bodyArg = bodyParamName;
|
||
else if (httpMethod === 'get' || httpMethod === 'delete') bodyArg = '';
|
||
|
||
const responseType = returnType === 'ArrayBuffer' ? ",\n responseType: 'arraybuffer'" :
|
||
returnType === 'Blob' ? ",\n responseType: 'blob'" : '';
|
||
|
||
if (bodyArg) {
|
||
body += ` return this.httpClient.${httpClientMethod}<${returnType}>(endPointPath, ${bodyArg}, {\n`;
|
||
} else {
|
||
body += ` return this.httpClient.${httpClientMethod}<${returnType}>(endPointPath, {\n`;
|
||
}
|
||
body += ` withCredentials: this.apiConfig.withCredentials,\n`;
|
||
body += ` headers,\n`;
|
||
body += ` observe,\n`;
|
||
body += ` params,\n`;
|
||
if (responseType) body += ` ${responseType.trim().replace(',\n ', '')}\n`;
|
||
body += ` reportProgress,\n`;
|
||
body += ` });\n`;
|
||
|
||
return body;
|
||
}
|
||
|
||
// ============ Utility Functions ============
|
||
function toKebabCase(str) {
|
||
return str
|
||
.replace(/([a-z])([A-Z])/g, '$1-$2')
|
||
.replace(/([A-Z]+)([A-Z][a-z])/g, '$1-$2')
|
||
.toLowerCase();
|
||
}
|
||
|
||
function toCamelCase(str) {
|
||
if (!str) return str;
|
||
return str.charAt(0).toLowerCase() + str.slice(1);
|
||
}
|
||
|
||
// ============ Open Provider Modal ============
|
||
function openProviderModal() {
|
||
document.getElementById('providerModalTitle').textContent = `Service - ${AppState.activeController}`;
|
||
const body = document.getElementById('providerModalBody');
|
||
body.innerHTML = `
|
||
<div class="code-block-header">
|
||
<span>📄 ${AppState.generatedProviderFilename}</span>
|
||
<span style="color: var(--accent);">TypeScript</span>
|
||
</div>
|
||
<div class="code-block"><pre>${highlightTS(AppState.generatedProviderCode)}</pre></div>
|
||
`;
|
||
document.getElementById('providerModal').classList.add('active');
|
||
}
|
||
|
||
function downloadProviderFile() {
|
||
if (!AppState.generatedProviderCode) return;
|
||
downloadFile(AppState.generatedProviderCode, AppState.generatedProviderFilename);
|
||
showToast(`فایل ${AppState.generatedProviderFilename} دانلود شد`, 'success');
|
||
}
|
||
|
||
function copyProviderCode() {
|
||
if (!AppState.generatedProviderCode) return;
|
||
navigator.clipboard.writeText(AppState.generatedProviderCode).then(() => {
|
||
showToast('کد Service در کلیپبورد کپی شد', 'success');
|
||
}).catch(() => {
|
||
showToast('خطا در کپی کد', 'error');
|
||
});
|
||
}
|
||
|
||
document.querySelectorAll('[data-close-modal-provider]').forEach(btn => {
|
||
btn.addEventListener('click', () => {
|
||
document.getElementById('providerModal').classList.remove('active');
|
||
});
|
||
});
|
||
|
||
document.getElementById('providerModal').addEventListener('click', (e) => {
|
||
if (e.target.id === 'providerModal') {
|
||
document.getElementById('providerModal').classList.remove('active');
|
||
}
|
||
});
|
||
|
||
/* =========================================================================
|
||
TypeScript DTO Generator
|
||
========================================================================= */
|
||
|
||
function openModelModal(modelName) {
|
||
AppState.selectedModel = modelName;
|
||
const schema = AppState.allSchemas[modelName];
|
||
if (!schema) {
|
||
showToast('مدل مورد نظر یافت نشد', 'error');
|
||
return;
|
||
}
|
||
|
||
document.getElementById('modelModalTitle').textContent = `مدل ${modelName}`;
|
||
const body = document.getElementById('modelModalBody');
|
||
|
||
const tsCode = generateTypeScriptDto(modelName, schema);
|
||
AppState.generatedCode = tsCode;
|
||
|
||
const props = schema.properties || {};
|
||
const propsList = Object.keys(props).map(name => {
|
||
const prop = props[name];
|
||
const tsType = resolveType(prop);
|
||
const required = (schema.required || []).includes(name);
|
||
return `
|
||
<tr>
|
||
<td style="font-family: 'Fira Code', monospace; font-size: 12px; direction: ltr; text-align: left;">${name}</td>
|
||
<td style="font-family: 'Fira Code', monospace; font-size: 12px; color: var(--info); direction: ltr; text-align: left;">${tsType}</td>
|
||
<td>${required ? '<span style="color: var(--danger); font-weight: 700;">ضروری ✓</span>' : '<span style="color: var(--text-muted);">اختیاری</span>'}</td>
|
||
<td style="font-size: 11px; color: var(--text-muted);">${prop.description || '-'}</td>
|
||
</tr>
|
||
`;
|
||
}).join('');
|
||
|
||
body.innerHTML = `
|
||
<div class="section-header">
|
||
<div class="section-icon">📋</div>
|
||
<div class="section-title">
|
||
<h3>مشخصات مدل</h3>
|
||
<div class="subtitle">${schema.description || 'بدون توضیحات'}</div>
|
||
</div>
|
||
</div>
|
||
<table class="endpoints-table" style="margin-bottom: 20px;">
|
||
<thead>
|
||
<tr>
|
||
<th>نام فیلد</th>
|
||
<th>نوع</th>
|
||
<th>وضعیت</th>
|
||
<th>توضیحات</th>
|
||
</tr>
|
||
</thead>
|
||
<tbody>${propsList}</tbody>
|
||
</table>
|
||
|
||
<div class="section-header">
|
||
<div class="section-icon">💻</div>
|
||
<div class="section-title">
|
||
<h3>کد TypeScript تولید شده</h3>
|
||
<div class="subtitle">فایل ${toFileName(modelName)}.ts</div>
|
||
</div>
|
||
</div>
|
||
<div class="code-block-header">
|
||
<span>📄 ${toFileName(modelName)}.ts</span>
|
||
<span style="color: var(--accent);">TypeScript</span>
|
||
</div>
|
||
<div class="code-block"><pre>${highlightTS(tsCode)}</pre></div>
|
||
`;
|
||
|
||
document.getElementById('modelModal').classList.add('active');
|
||
}
|
||
|
||
document.querySelectorAll('[data-close-modal]').forEach(btn => {
|
||
btn.addEventListener('click', () => {
|
||
document.getElementById('modelModal').classList.remove('active');
|
||
});
|
||
});
|
||
|
||
document.getElementById('modelModal').addEventListener('click', (e) => {
|
||
if (e.target.id === 'modelModal') {
|
||
document.getElementById('modelModal').classList.remove('active');
|
||
}
|
||
});
|
||
|
||
document.getElementById('downloadDtoBtn').addEventListener('click', () => {
|
||
if (!AppState.selectedModel || !AppState.generatedCode) return;
|
||
const filename = toFileName(AppState.selectedModel) + '.ts';
|
||
downloadFile(AppState.generatedCode, filename);
|
||
showToast(`فایل ${filename} دانلود شد`, 'success');
|
||
});
|
||
|
||
document.getElementById('copyCodeBtn').addEventListener('click', () => {
|
||
if (!AppState.generatedCode) return;
|
||
navigator.clipboard.writeText(AppState.generatedCode).then(() => {
|
||
showToast('کد در کلیپبورد کپی شد', 'success');
|
||
}).catch(() => {
|
||
showToast('خطا در کپی کد', 'error');
|
||
});
|
||
});
|
||
|
||
function generateTypeScriptDto(modelName, schema) {
|
||
const props = schema.properties || {};
|
||
const requiredFields = schema.required || [];
|
||
const isEnum = !!schema.enum;
|
||
|
||
if (isEnum) return generateEnum(modelName, schema);
|
||
|
||
const parentType = detectParentType(props);
|
||
const interfaceCode = generateInterface(modelName, schema, parentType);
|
||
const defaultObjName = 'default' + modelName.replace(/^X/, '');
|
||
const defaultObjCode = generateDefaultObject(modelName, props, defaultObjName, parentType);
|
||
const prepareFuncCode = generatePrepareFunction(modelName, props, defaultObjName);
|
||
const isDefaultCode = generateIsDefaultFunction(modelName, defaultObjName);
|
||
const typeGuardCode = generateTypeGuard(modelName, props, requiredFields);
|
||
|
||
return `${interfaceCode}
|
||
|
||
${defaultObjCode}
|
||
|
||
${prepareFuncCode}
|
||
|
||
${isDefaultCode}
|
||
|
||
${typeGuardCode}
|
||
`;
|
||
}
|
||
|
||
function detectParentType(props) {
|
||
if (props.id && (props.id.type === 'integer' || props.id.format === 'int32' || props.id.format === 'int64')) {
|
||
return 'XBaseNumberIDDto';
|
||
}
|
||
return 'XBaseDto';
|
||
}
|
||
|
||
function generateInterface(modelName, schema, parentType) {
|
||
const props = schema.properties || {};
|
||
const requiredFields = schema.required || [];
|
||
const description = schema.description || `a Model for Describing a ${modelName.replace(/^X/, '').replace(/Dto$/, '')} ...`;
|
||
|
||
const fields = Object.keys(props).map(name => {
|
||
if (['id', 'deleted'].includes(name) && parentType !== 'none') return '';
|
||
const prop = props[name];
|
||
const tsType = resolveType(prop);
|
||
const isRequired = requiredFields.includes(name);
|
||
const optional = isRequired ? '' : '?';
|
||
const propDesc = prop.description ? ` // ${prop.description.replace(/\r?\n/g, ' ')}` : '';
|
||
return ` ${name}${optional}: ${tsType};${propDesc}`;
|
||
}).filter(f => f).join('\n');
|
||
|
||
return `/**
|
||
* ${description}
|
||
*/
|
||
export interface ${modelName} extends ${parentType} {
|
||
${fields}
|
||
}`;
|
||
}
|
||
|
||
function generateDefaultObject(modelName, props, defaultObjName, parentType) {
|
||
const fields = Object.keys(props).map(name => {
|
||
if (['id', 'deleted'].includes(name) && parentType !== 'none') return '';
|
||
const prop = props[name];
|
||
const defaultValue = getDefaultValue(prop);
|
||
return ` ${name}: ${defaultValue},`;
|
||
}).filter(f => f).join('\n');
|
||
|
||
return `/**
|
||
* Default model ...
|
||
*/
|
||
export const ${defaultObjName}: ${modelName} = {
|
||
${fields}
|
||
};`;
|
||
}
|
||
|
||
function getDefaultValue(prop) {
|
||
if (!prop) return 'undefined';
|
||
if (prop.$ref) return 'undefined';
|
||
if (prop.type === 'array') return '[]';
|
||
if (prop.type === 'string') {
|
||
if (prop.format === 'date-time') return 'undefined';
|
||
return "''";
|
||
}
|
||
if (prop.type === 'integer' || prop.type === 'number') {
|
||
if (prop.format === 'int64') return 'undefined';
|
||
return '0';
|
||
}
|
||
if (prop.type === 'boolean') return 'false';
|
||
if (prop.type === 'object') return 'undefined';
|
||
return 'undefined';
|
||
}
|
||
|
||
function generatePrepareFunction(modelName, props, defaultObjName) {
|
||
const fields = Object.keys(props).map(name => {
|
||
if (['id', 'deleted'].includes(name)) return '';
|
||
const prop = props[name];
|
||
return generateFieldPrepare(name, prop, defaultObjName);
|
||
}).filter(f => f).join('\n');
|
||
|
||
return `/**
|
||
* Preparing Dto Field ...
|
||
*
|
||
* @param model
|
||
*/
|
||
export function prepare${modelName.replace(/^X/, '')}Fields(model?: ${modelName}) {
|
||
//
|
||
if (isNullOrUndefined(model)) {
|
||
//
|
||
model = {
|
||
...${defaultObjName},
|
||
};
|
||
}
|
||
//
|
||
model = {
|
||
${fields}
|
||
};
|
||
//
|
||
return model;
|
||
}`;
|
||
}
|
||
|
||
function generateFieldPrepare(name, prop, defaultObjName) {
|
||
if (!prop) return ` ${name}: !isNullOrUndefined(model.${name}) ? model.${name} : ${defaultObjName}.${name},`;
|
||
|
||
if (prop.$ref) {
|
||
return ` ${name}: !isNullOrUndefined(model.${name})
|
||
? { ...model.${name} }
|
||
: ${defaultObjName}.${name},`;
|
||
}
|
||
|
||
if (prop.type === 'array') {
|
||
return ` ${name}: !isNullOrUndefined(model.${name}) && !hasChild(model.${name})
|
||
? [...model.${name}]
|
||
: ${defaultObjName}.${name},`;
|
||
}
|
||
|
||
if (prop.type === 'string' && prop.format !== 'date-time' && prop.format !== 'uuid') {
|
||
return ` ${name}: !isNullOrEmptyString(model.${name})
|
||
? model.${name}
|
||
: ${defaultObjName}.${name},`;
|
||
}
|
||
|
||
if (prop.type === 'string' && prop.format === 'date-time') {
|
||
return ` ${name}: !isNullOrUndefined(model.${name})
|
||
? model.${name}
|
||
: ${defaultObjName}.${name},`;
|
||
}
|
||
|
||
if ((prop.type === 'integer' || prop.type === 'number') && prop.format !== 'int64') {
|
||
return ` ${name}: !isNullOrUndefined(model.${name})
|
||
? model.${name}
|
||
: ${defaultObjName}.${name},`;
|
||
}
|
||
|
||
if (prop.type === 'boolean') {
|
||
return ` ${name}: !isNullOrUndefined(model.${name})
|
||
? model.${name}
|
||
: ${defaultObjName}.${name},`;
|
||
}
|
||
|
||
if (prop.format === 'uuid') {
|
||
return ` ${name}: !isNullOrEmptyString(model.${name})
|
||
? model.${name}
|
||
: ${defaultObjName}.${name},`;
|
||
}
|
||
|
||
return ` ${name}: !isNullOrUndefined(model.${name})
|
||
? model.${name}
|
||
: ${defaultObjName}.${name},`;
|
||
}
|
||
|
||
function generateIsDefaultFunction(modelName, defaultObjName) {
|
||
const funcName = 'prepare' + modelName.replace(/^X/, '') + 'Fields';
|
||
return `/**
|
||
* Check Model is Default or not ...
|
||
*
|
||
* @param model
|
||
*/
|
||
export function isDefault${modelName.replace(/^X/, '')}(model?: ${modelName}) {
|
||
return isSameObject(${funcName}(model), ${defaultObjName});
|
||
}`;
|
||
}
|
||
|
||
function generateTypeGuard(modelName, props, requiredFields) {
|
||
let guardFields = requiredFields.filter(f => f !== 'deleted');
|
||
|
||
if (guardFields.length === 0) {
|
||
guardFields = Object.keys(props).filter(name => {
|
||
if (['deleted'].includes(name)) return false;
|
||
const prop = props[name];
|
||
if (!prop) return false;
|
||
if (prop.$ref) return false;
|
||
if (prop.type === 'array') return false;
|
||
return ['string', 'integer', 'number', 'boolean'].includes(prop.type);
|
||
}).slice(0, 5);
|
||
}
|
||
|
||
const fieldsList = guardFields.map(f => ` '${f}',`).join('\n');
|
||
|
||
return `/**
|
||
* Model Type Guard ...
|
||
*/
|
||
export const is${modelName} = typeGuard<${modelName}>([
|
||
${fieldsList}
|
||
]);`;
|
||
}
|
||
|
||
function generateEnum(modelName, schema) {
|
||
const values = schema.enum || [];
|
||
const isInt = values.length > 0 && typeof values[0] === 'number';
|
||
const entries = values.map((v, i) => {
|
||
if (isInt) return ` ${v} = ${v},`;
|
||
const key = String(v).replace(/[^a-zA-Z0-9_]/g, '_');
|
||
return ` ${key} = '${v}',`;
|
||
}).join('\n');
|
||
|
||
return `/**
|
||
* ${schema.description || `Enum ${modelName}`}
|
||
*/
|
||
export enum ${modelName} {
|
||
${entries}
|
||
}`;
|
||
}
|
||
|
||
function toFileName(modelName) {
|
||
return modelName
|
||
.replace(/^X/, 'x-')
|
||
.replace(/([a-z])([A-Z])/g, '$1-$2')
|
||
.replace(/([A-Z]+)([A-Z][a-z])/g, '$1-$2')
|
||
.toLowerCase();
|
||
}
|
||
|
||
function downloadFile(content, filename) {
|
||
const blob = new Blob([content], { type: 'text/typescript;charset=utf-8' });
|
||
const url = URL.createObjectURL(blob);
|
||
const a = document.createElement('a');
|
||
a.href = url;
|
||
a.download = filename;
|
||
document.body.appendChild(a);
|
||
a.click();
|
||
document.body.removeChild(a);
|
||
URL.revokeObjectURL(url);
|
||
}
|
||
|
||
// ============ Improved Syntax Highlighting (Placeholder-based) ============
|
||
function highlightTS(code) {
|
||
// Step 1: Escape HTML
|
||
let escaped = code
|
||
.replace(/&/g, '&')
|
||
.replace(/</g, '<')
|
||
.replace(/>/g, '>');
|
||
|
||
// Step 2: Extract strings and comments, replace with placeholders
|
||
const placeholders = [];
|
||
let placeholderIndex = 0;
|
||
|
||
// Extract multi-line comments
|
||
escaped = escaped.replace(/\/\*[\s\S]*?\*\//g, (match) => {
|
||
const placeholder = `__COMMENT_${placeholderIndex}__`;
|
||
placeholders.push({ placeholder, content: `<span class="code-comment">${match}</span>` });
|
||
placeholderIndex++;
|
||
return placeholder;
|
||
});
|
||
|
||
// Extract single-line comments
|
||
escaped = escaped.replace(/\/\/.*$/gm, (match) => {
|
||
const placeholder = `__COMMENT_${placeholderIndex}__`;
|
||
placeholders.push({ placeholder, content: `<span class="code-comment">${match}</span>` });
|
||
placeholderIndex++;
|
||
return placeholder;
|
||
});
|
||
|
||
// Extract strings (single and double quotes)
|
||
escaped = escaped.replace(/'([^'\\]|\\.)*'/g, (match) => {
|
||
const placeholder = `__STRING_${placeholderIndex}__`;
|
||
placeholders.push({ placeholder, content: `<span class="code-string">${match}</span>` });
|
||
placeholderIndex++;
|
||
return placeholder;
|
||
});
|
||
|
||
escaped = escaped.replace(/"([^"\\]|\\.)*"/g, (match) => {
|
||
const placeholder = `__STRING_${placeholderIndex}__`;
|
||
placeholders.push({ placeholder, content: `<span class="code-string">${match}</span>` });
|
||
placeholderIndex++;
|
||
return placeholder;
|
||
});
|
||
|
||
// Step 3: Highlight keywords
|
||
const keywords = ['export', 'interface', 'const', 'function', 'enum', 'extends', 'import', 'from', 'return', 'if', 'typeof', 'public', 'private', 'protected', 'class', 'constructor', 'Injectable', 'Inject'];
|
||
keywords.forEach(kw => {
|
||
const regex = new RegExp(`\\b(${kw})\\b`, 'g');
|
||
escaped = escaped.replace(regex, '<span class="code-keyword">$1</span>');
|
||
});
|
||
|
||
// Step 4: Highlight types
|
||
const types = ['string', 'number', 'boolean', 'any', 'void', 'Date', 'File', 'Array', 'Observable', 'HttpResponse', 'HttpEvent', 'HttpParams', 'HttpHeaders', 'FormData', 'ArrayBuffer', 'Blob'];
|
||
types.forEach(t => {
|
||
const regex = new RegExp(`\\b(${t})\\b`, 'g');
|
||
escaped = escaped.replace(regex, '<span class="code-type">$1</span>');
|
||
});
|
||
|
||
// Step 5: Restore placeholders
|
||
placeholders.forEach(({ placeholder, content }) => {
|
||
escaped = escaped.replace(placeholder, content);
|
||
});
|
||
|
||
return escaped;
|
||
}
|
||
|
||
// ============ Initial State ============
|
||
showToast('XFramework Backend SDK Manager آماده استفاده است', 'success', 4000);
|
||
</script>
|
||
</body>
|
||
</html> |