Gate Studio frontend by workspace and isolate browser catalog state

This commit is contained in:
khondokartowsif171
2026-10-19 01:20:55 +06:00
parent 07f711ff2d
commit 6db99f96df
10 changed files with 350 additions and 259 deletions
+1 -1
View File
@@ -9,7 +9,7 @@ RUN rm -rf /usr/share/nginx/html/*
COPY nginx.conf /etc/nginx/conf.d/default.conf
# Publish web assets only. Backend source, tests and local configuration are not static downloads.
COPY index.html app.js style.css sw.js manifest.json gt_full_catalog.json /usr/share/nginx/html/
COPY index.html app.js workspace.js style.css sw.js manifest.json gt_full_catalog.json /usr/share/nginx/html/
COPY assets/ /usr/share/nginx/html/assets/
COPY data/ /usr/share/nginx/html/data/
+1 -1
View File
@@ -5,7 +5,7 @@ ENV NODE_ENV=production PORT=3000 STUDIO_DATA_DIR=/data/studio
COPY package.json package-lock.json ./
RUN npm ci --omit=dev --ignore-scripts --no-fund --no-audit
COPY server/ ./server/
COPY index.html app.js style.css sw.js manifest.json gt_full_catalog.json ./public/
COPY index.html app.js workspace.js style.css sw.js manifest.json gt_full_catalog.json ./public/
COPY assets/ ./public/assets/
COPY data/ ./public/data/
RUN mkdir -p /data/studio && chown -R node:node /app /data/studio
+122 -192
View File
@@ -19,10 +19,10 @@ const I18N_DICTIONARY = {
poster_mode_label: "ডিসপ্লে মোড (Display Mode):",
mode_single_btn: "🎯 ১টি প্রোডাক্ট হিরো ৩ডি স্টেজ",
mode_multi_btn: "🔲 মাল্টি-প্রোডাক্ট গ্রিড ভিউ (৩-৪টি প্রোডাক্ট)",
trends_label: "🔥 গুগল ট্রেন্ডিং সার্চ (Google Trends 1-Click Load):",
trends_badge: "Realtime BD Trends",
trends_label: "🛍️ আপনার catalog থেকে বাছুন:",
trends_badge: "Workspace catalog",
product_input_label: "প্রডাক্ট লিংক বা নাম (Product Link or Name):",
open_catalog_btn: "🛍️ GT ক্যাটালগ লিস্ট (560+)",
open_catalog_btn: "🛍️ আপনার catalog",
product_input_ph: "e.g. Silk Saree, Smartwatch, Pure Honey, Sneaker or Skincare",
product_price_label: "মূল্য ও অফার (Price & Discount):",
product_price_ph: "e.g. ৳ ১,০৬০ (৳ ১,৪৭০) 28% OFF",
@@ -220,10 +220,10 @@ const I18N_DICTIONARY = {
poster_mode_label: "Display Mode:",
mode_single_btn: "🎯 1 Product Hero 3D Stage",
mode_multi_btn: "🔲 Multi-Product Grid View (3-4 Products)",
trends_label: "🔥 Google Trending Searches (Google Trends 1-Click Load):",
trends_badge: "Realtime BD Trends",
trends_label: "🛍️ Choose from your catalog:",
trends_badge: "Workspace catalog",
product_input_label: "Product Link or Name:",
open_catalog_btn: "🛍️ GT Catalog List (560+)",
open_catalog_btn: "🛍️ Your catalog",
product_input_ph: "e.g. Silk Saree, Smartwatch, Pure Honey, Sneaker or Skincare",
product_price_label: "Price & Discount Offer:",
product_price_ph: "e.g. ৳ 1,060 (৳ 1,470) 28% OFF",
@@ -465,7 +465,17 @@ window.applyLanguage = function(lang) {
if (typeof renderHistory === 'function') renderHistory();
};
document.addEventListener('DOMContentLoaded', () => {
document.addEventListener('aura-studio-ready', () => {
const brandSelect = document.getElementById('brandWatermarkSelect');
if (brandSelect) brandSelect.replaceChildren(new Option(window.AuraStudio.workspace.name || window.AuraStudio.workspace.tenant, 'workspace'));
const storeContext = document.getElementById('inboxStoreContext');
if (storeContext) storeContext.value = window.AuraStudio.workspace.name || window.AuraStudio.workspace.tenant;
['productInput', 'productPrice', 'customBadgeInput', 'ugcProductName', 'ugcTargetAudience', 'gridMainHeadlineInput'].forEach(id => {
const field = document.getElementById(id); if (field) field.value = '';
});
for (let slot = 1; slot <= 4; slot++) {
['slotTitle', 'slotPrice', 'slotBadge'].forEach(prefix => { const field = document.getElementById(prefix + slot); if (field) field.value = ''; });
}
initNavigation();
initSettings();
initCatalogBrowser();
@@ -552,9 +562,9 @@ function initSettings() {
const statusMsg = document.getElementById('settingsStatusMsg');
// Load saved settings
const savedKey = localStorage.getItem('opal_gemini_api_key') || '';
const savedModel = localStorage.getItem('opal_selected_model') || 'gemini-2.0-flash';
const savedN8n = localStorage.getItem('opal_n8n_webhook') || 'https://n8n.auraajenticai.cloud/webhook/gt-auto-post';
const savedKey = window.AuraStudio.local.getItem('opal_gemini_api_key') || '';
const savedModel = window.AuraStudio.local.getItem('opal_selected_model') || 'gemini-2.0-flash';
const savedN8n = window.AuraStudio.local.getItem('opal_n8n_webhook') || '';
if (apiKeyInput) apiKeyInput.value = savedKey;
if (modelSelect) modelSelect.value = savedModel;
@@ -567,11 +577,11 @@ function initSettings() {
const n8nUrl = n8nWebhookInput ? n8nWebhookInput.value.trim() : '';
if (n8nUrl) {
localStorage.setItem('opal_n8n_webhook', n8nUrl);
window.AuraStudio.local.setItem('opal_n8n_webhook', n8nUrl);
}
if (!key) {
localStorage.setItem('opal_selected_model', model);
window.AuraStudio.local.setItem('opal_selected_model', model);
statusMsg.classList.remove('hidden');
statusMsg.style.color = '#10B981';
statusMsg.textContent = '✅ Settings saved (Offline templates active).';
@@ -585,8 +595,8 @@ function initSettings() {
try {
const res = await callGeminiApi(key, model, "Respond with: 'Aura Studio Connected successfully!'");
if (res) {
localStorage.setItem('opal_gemini_api_key', key);
localStorage.setItem('opal_selected_model', model);
window.AuraStudio.local.setItem('opal_gemini_api_key', key);
window.AuraStudio.local.setItem('opal_selected_model', model);
statusMsg.style.color = '#10B981';
statusMsg.textContent = `✅ Verified & Active: ${res.trim()}`;
}
@@ -606,7 +616,7 @@ function getCachedPromptResult(cacheKey) {
return GEMINI_CACHE.get(cacheKey);
}
try {
const stored = sessionStorage.getItem(`opal_cache_${cacheKey}`);
const stored = window.AuraStudio.session.getItem(`opal_cache_${cacheKey}`);
if (stored) {
const parsed = JSON.parse(stored);
if (Date.now() - parsed.ts < 1000 * 60 * 60 * 2) { // 2 hour cache
@@ -621,7 +631,7 @@ function getCachedPromptResult(cacheKey) {
function setCachedPromptResult(cacheKey, data) {
GEMINI_CACHE.set(cacheKey, data);
try {
sessionStorage.setItem(`opal_cache_${cacheKey}`, JSON.stringify({ ts: Date.now(), data }));
window.AuraStudio.session.setItem(`opal_cache_${cacheKey}`, JSON.stringify({ ts: Date.now(), data }));
} catch (e) {}
}
@@ -638,7 +648,7 @@ async function callGeminiApi(apiKey, model, prompt, retries = 2) {
}
const modelHierarchy = [
model || localStorage.getItem('opal_selected_model') || 'gemini-2.0-flash',
model || window.AuraStudio.local.getItem('opal_selected_model') || 'gemini-2.0-flash',
'gemini-1.5-flash',
'gemma-2-27b-it'
];
@@ -1012,7 +1022,7 @@ function initMiniAppsHub() {
}
function getCustomMiniApps() {
return JSON.parse(localStorage.getItem('opal_custom_apps') || '[]');
return JSON.parse(window.AuraStudio.local.getItem('opal_custom_apps') || '[]');
}
function renderMiniApps() {
@@ -1105,7 +1115,7 @@ function initMiniAppBuilder() {
const existing = getCustomMiniApps();
existing.unshift(newApp);
localStorage.setItem('opal_custom_apps', JSON.stringify(existing));
window.AuraStudio.local.setItem('opal_custom_apps', JSON.stringify(existing));
statusMsg.classList.remove('hidden');
statusMsg.style.color = '#10B981';
@@ -1193,7 +1203,7 @@ window.closeAppRunner = function() {
};
// Handle Mini-App Execution
document.addEventListener('DOMContentLoaded', () => {
document.addEventListener('aura-studio-ready', () => {
const execBtn = document.getElementById('runnerExecuteBtn');
if (execBtn) {
execBtn.addEventListener('click', async () => {
@@ -1212,7 +1222,7 @@ document.addEventListener('DOMContentLoaded', () => {
const inputs = document.querySelectorAll('.runner-input');
const selectedBrandKey = document.getElementById('brandWatermarkSelect')?.value || 'glamourstouch';
const activeBrand = getBrandProfile(selectedBrandKey);
const cleanPhone = (activeBrand.footerHotline || '01712-426871').replace(/\D/g, '');
const cleanPhone = (activeBrand.footerHotline || '').replace(/\D/g, '');
const dynamicWaLink = `https://wa.me/88${cleanPhone}`;
let prompt = currentRunningApp.promptTemplate || 'Generate helpful response for the user.';
@@ -1231,8 +1241,8 @@ document.addEventListener('DOMContentLoaded', () => {
prompt = prompt.replace(/{{wa_link}}/g, dynamicWaLink);
prompt = prompt.replace(/https:\/\/wa\.me\/8801712426871/g, dynamicWaLink);
const apiKey = localStorage.getItem('opal_gemini_api_key') || '';
const model = currentRunningApp.model || localStorage.getItem('opal_selected_model') || 'gemini-2.0-flash';
const apiKey = window.AuraStudio.local.getItem('opal_gemini_api_key') || '';
const model = currentRunningApp.model || window.AuraStudio.local.getItem('opal_selected_model') || 'gemini-2.0-flash';
try {
let output = '';
@@ -1705,9 +1715,9 @@ function initPosterLab() {
shareWhatsAppBtn.addEventListener('click', () => {
const selectedBrand = document.getElementById('brandWatermarkSelect')?.value || 'glamourstouch';
const activeBrand = getBrandProfile(selectedBrand);
const cleanPhone = (activeBrand.footerHotline || '01712-426871').replace(/\D/g, '');
const cleanPhone = (activeBrand.footerHotline || '').replace(/\D/g, '');
const pTitle = productInput.value.trim() || 'Authentic Product';
const text = encodeURIComponent(`✨ Hello! I want to order: ${pTitle}\nWebsite: https://${activeBrand.footerSite || 'glamourstouch.com'}\nHotline: ${activeBrand.footerHotline}`);
const text = encodeURIComponent(`✨ Hello! I want to order: ${pTitle}\nWebsite: https://${activeBrand.footerSite || ''}\nHotline: ${activeBrand.footerHotline}`);
window.open(`https://wa.me/88${cleanPhone}?text=${text}`, '_blank');
});
@@ -1717,7 +1727,7 @@ function initPosterLab() {
if (autoPostN8nBtn) {
autoPostN8nBtn.addEventListener('click', async () => {
const webhookUrl = localStorage.getItem('opal_n8n_webhook');
const webhookUrl = window.AuraStudio.local.getItem('opal_n8n_webhook');
if (!webhookUrl) {
alert('⚠️ Please configure n8n Webhook URL in Settings first!');
switchToTab('tabSettings');
@@ -1732,7 +1742,7 @@ function initPosterLab() {
try {
const selectedBrand = document.getElementById('brandWatermarkSelect')?.value || 'glamourstouch';
const activeBrand = getBrandProfile(selectedBrand);
const cleanPhone = (activeBrand.footerHotline || '01712-426871').replace(/\D/g, '');
const cleanPhone = (activeBrand.footerHotline || '').replace(/\D/g, '');
const pTitle = productInput.value.trim() || 'Authentic Product';
const pPrice = productPrice.value.trim() || '৳ ১,০৬০';
const posterDataUrl = posterCanvas.toDataURL('image/jpeg', 0.92);
@@ -1774,100 +1784,17 @@ function initPosterLab() {
// --- Dynamic Brand Profiles & Tenant Sync Engine ---
const DEFAULT_BRAND_PROFILES = {
glamourstouch: {
id: 'glamourstouch',
headerTitle: "✨ GLAMOUR'S TOUCH ✨",
headerSub: '100% AUTHENTIC KOREAN COSMETICS • DERMATOLOGIST TESTED',
badgeL1: '🌿 Pure & Safe Care',
badgeL2: '🛡️ Authentic Seal',
footerSite: 'glamourstouch.com',
footerHotline: '01712-426871',
theme: 'obsidian_gold',
category: 'cosmetics'
},
panjabi: {
id: 'panjabi',
headerTitle: '👑 AURA HERITAGE PANJABI 👑',
headerSub: 'ROYAL DESIGNER PANJABI & KABLI SUITS • 100% PURE COTTON & SILK',
badgeL1: '🧵 100% Pre-Shrunk Weave',
badgeL2: '✨ Size Trial Available',
footerSite: 'panjabi.auraajenticai.cloud',
footerHotline: '01712-426871',
theme: 'obsidian_gold',
category: 'panjabi'
},
snehalata: {
id: 'snehalata',
headerTitle: '🌸 SNEHALATA AURA 🌸',
headerSub: 'PREMIUM LUXURY FASHION, SAREE & LIFESTYLE • 100% AUTHENTIC',
badgeL1: '👗 Pure Fabric Weave',
badgeL2: '✨ Size Trial Guarantee',
footerSite: 'snehalata.com',
footerHotline: '01712-426871',
theme: 'rose_quartz',
category: 'fashion'
},
techvolt: {
id: 'techvolt',
headerTitle: '⚡ TECHVOLT GADGETS ⚡',
headerSub: 'OFFICIAL WARRANTY • SMART ELECTRONICS & AUDIO ACCESSORIES',
badgeL1: '🔋 High Battery Life',
badgeL2: '🛡️ 1 Year Warranty',
footerSite: 'techvolt.auraajenticai.cloud',
footerHotline: '01712-426871',
theme: 'cyber_neon',
category: 'electronics'
},
organic: {
id: 'organic',
headerTitle: '🍯 PRANON ORGANIC 🍯',
headerSub: '100% PURE NATURAL HONEY & UNADULTERATED ORGANIC FOODS',
badgeL1: '🌿 100% Lab Tested',
badgeL2: '🛡️ Double Money Back',
footerSite: 'organic.auraajenticai.cloud',
footerHotline: '01712-426871',
theme: 'botanical_eco',
category: 'organic'
},
sneakerlab: {
id: 'sneakerlab',
headerTitle: '👟 SNEAKERLAB BD 👟',
headerSub: 'PREMIUM STREETWEAR & GENUINE LEATHER FOOTWEAR',
badgeL1: '👟 Memory Foam Cushion',
badgeL2: '✨ Doorstep Fitting',
footerSite: 'sneakers.auraajenticai.cloud',
footerHotline: '01712-426871',
theme: 'obsidian_gold',
category: 'sneakerlab'
},
royale: {
id: 'royale',
headerTitle: '💎 AURA ROYALE 💎',
headerSub: 'LUXURY JEWELRY, WATCHES & 24-HOUR SIGNATURE PERFUMES',
badgeL1: '💎 24h Projection',
badgeL2: '👑 Pure Luxury Finish',
footerSite: 'royale.auraajenticai.cloud',
footerHotline: '01712-426871',
theme: 'obsidian_gold',
category: 'royale'
},
custom: {
id: 'custom',
headerTitle: '🛍️ UNIVERSAL MERCHANT 🛍️',
headerSub: '100% ORIGINAL AUTHENTIC • CASH ON DELIVERY BANGLADESH',
badgeL1: '⭐ Premium Quality',
badgeL2: '🛡️ 100% Original',
footerSite: 'auraajenticai.cloud',
footerHotline: '01712-426871',
theme: 'obsidian_gold',
category: 'general'
workspace: {
id: 'workspace', headerTitle: window.AuraStudio.workspace.name || window.AuraStudio.workspace.tenant,
headerSub: '', badgeL1: '', badgeL2: '', footerSite: '', footerHotline: '',
theme: 'obsidian_gold', category: 'general'
}
};
function getDynamicBrandProfiles() {
let customMap = {};
try {
const saved = localStorage.getItem('opal_custom_brands');
const saved = window.AuraStudio.local.getItem('opal_custom_brands');
if (saved) customMap = JSON.parse(saved);
} catch (e) {}
return Object.assign({}, DEFAULT_BRAND_PROFILES, customMap);
@@ -1875,7 +1802,7 @@ function getDynamicBrandProfiles() {
function getBrandProfile(brandKey) {
const all = getDynamicBrandProfiles();
return all[brandKey] || all.glamourstouch;
return all[brandKey] || all.workspace;
}
// Universal Dynamic Product Resolver
@@ -6206,7 +6133,8 @@ window.loadCgiIntoPosterLab = function(promptId) {
}
};
async function drawWhatsAppQrOnCanvas(ctx, x, y, size, hotline = '01712-426871') {
async function drawWhatsAppQrOnCanvas(ctx, x, y, size, hotline = '') {
if (!String(hotline).replace(/\D/g, '')) return;
ctx.fillStyle = '#FFFFFF';
roundRect(ctx, x - 4, y - 4, size + 8, size + 8, 10);
ctx.fill();
@@ -6266,12 +6194,12 @@ function initInboxAI() {
generateBtn.addEventListener('click', async () => {
const query = customerMsgInput.value.trim();
const storeInfo = storeContextInput.value.trim();
const apiKey = localStorage.getItem('opal_gemini_api_key') || '';
const model = localStorage.getItem('opal_selected_model') || 'gemini-2.0-flash';
const apiKey = window.AuraStudio.local.getItem('opal_gemini_api_key') || '';
const model = window.AuraStudio.local.getItem('opal_selected_model') || 'gemini-2.0-flash';
const selectedBrand = document.getElementById('brandWatermarkSelect')?.value || 'glamourstouch';
const activeBrand = getBrandProfile(selectedBrand);
const cleanPhone = (activeBrand.footerHotline || '01712-426871').replace(/\D/g, '');
const cleanPhone = (activeBrand.footerHotline || '').replace(/\D/g, '');
const dynamicWaLink = `https://wa.me/88${cleanPhone}`;
if (!query) {
@@ -6331,7 +6259,7 @@ function initHistory() {
function renderHistory() {
if (!historyContainer) return;
const dict = I18N_DICTIONARY[window.currentLang] || I18N_DICTIONARY.bn;
const list = JSON.parse(localStorage.getItem('opal_history') || '[]');
const list = JSON.parse(window.AuraStudio.local.getItem('opal_history') || '[]');
if (list.length === 0) {
historyContainer.innerHTML = `
<div class="empty-state">
@@ -6358,7 +6286,7 @@ function initHistory() {
if (clearBtn) {
clearBtn.addEventListener('click', () => {
localStorage.removeItem('opal_history');
window.AuraStudio.local.removeItem('opal_history');
renderHistory();
});
}
@@ -6367,9 +6295,9 @@ function initHistory() {
}
function saveGenerationToHistory(item) {
const list = JSON.parse(localStorage.getItem('opal_history') || '[]');
const list = JSON.parse(window.AuraStudio.local.getItem('opal_history') || '[]');
list.unshift(item);
localStorage.setItem('opal_history', JSON.stringify(list.slice(0, 30)));
window.AuraStudio.local.setItem('opal_history', JSON.stringify(list.slice(0, 30)));
}
// --- 7. Google Flow & Omni UGC Video Ads Studio (Google Veo 3.1) ---
@@ -6541,8 +6469,8 @@ function initUgcStudio() {
const preset = UGC_PRESET_LIBRARY[selectedUgcPreset] || UGC_PRESET_LIBRARY.unhinged_review;
try {
const apiKey = localStorage.getItem('opal_gemini_api_key') || '';
const model = localStorage.getItem('opal_selected_model') || 'gemini-2.0-flash';
const apiKey = window.AuraStudio.local.getItem('opal_gemini_api_key') || '';
const model = window.AuraStudio.local.getItem('opal_selected_model') || 'gemini-2.0-flash';
let masterPrompt = '';
let timelineShots = [];
@@ -6661,7 +6589,7 @@ Generate:
// --- Universal Multi-Store Catalog & Client URL Sync Engine ---
window.ALL_STORES = {};
window.activeStoreId = 'glamourstouch';
window.activeStoreId = null;
window.GT_CATALOG = [];
let selectedCatalogBrand = 'all';
@@ -6689,36 +6617,29 @@ async function initCatalogBrowser() {
const productInput = document.getElementById('productInput');
const autocompleteList = document.getElementById('productAutocompleteList');
// 1. Initialize Master Store: Glamour's Touch (563 Products)
try {
const res = await fetch('gt_full_catalog.json');
if (res.ok) {
window.GT_CATALOG = await res.json();
window.ALL_STORES['glamourstouch'] = {
id: 'glamourstouch',
name: "Glamour's Touch",
icon: '✨',
domain: 'glamourstouch.com',
url: 'https://glamourstouch.com',
category: 'cosmetics',
badge: 'KOREAN COSMETICS',
count: window.GT_CATALOG.length,
products: window.GT_CATALOG,
isMaster: true
};
}
} catch (e) {
console.warn('Could not load gt_full_catalog.json:', e);
}
const htmlText = window.AuraStudio.escapeText;
const apiUrl = window.AuraStudio.apiUrl;
// Load only the authenticated workspace catalog; no global merchant fallback.
// 2. Load Synced Stores from backend API
await loadSyncedStoresFromBackend();
window.activeStoreId = Object.keys(window.ALL_STORES)[0] || null;
const shortcuts = document.getElementById('trendingPosterChips');
if (shortcuts) {
shortcuts.replaceChildren();
Object.values(window.ALL_STORES).flatMap(item => item.products || []).slice(0, 7).forEach(product => {
const button = document.createElement('button');
button.type = 'button'; button.className = 'pill-btn'; button.textContent = product.title;
button.addEventListener('click', () => window.applyCatalogProductToPoster(product.id));
shortcuts.appendChild(button);
});
}
async function loadSyncedStoresFromBackend() {
try {
const res = await fetch('/api/get-synced-stores');
if (res.ok) {
const res = await fetch(apiUrl('/api/get-synced-stores'), { cache: 'no-store' });
{
const data = await res.json();
if (!res.ok || data.success !== true) throw new Error(data.error || 'Catalog load হয়নি।');
if (data && Array.isArray(data.stores)) {
data.stores.forEach(s => {
let catEmoji = '🛍️';
@@ -6746,7 +6667,7 @@ async function initCatalogBrowser() {
}
}
} catch (e) {
console.warn('Could not load synced stores:', e);
if (storeSyncStatusMsg) { storeSyncStatusMsg.classList.remove('hidden'); storeSyncStatusMsg.textContent = e.message || 'Catalog load হয়নি।'; }
}
}
@@ -6760,8 +6681,8 @@ async function initCatalogBrowser() {
const st = window.ALL_STORES[k];
const isActive = k === window.activeStoreId;
html += `
<button type="button" class="store-chip-btn ${isActive ? 'active' : ''}" data-store-id="${st.id}">
<span>${st.icon || '🛍️'}</span> ${st.name} (${st.count || st.products.length})
<button type="button" class="store-chip-btn ${isActive ? 'active' : ''}" data-store-id="${htmlText(st.id)}">
<span>${htmlText(st.icon || '🛍️')}</span> ${htmlText(st.name)} (${st.count || st.products.length})
</button>
`;
});
@@ -6812,7 +6733,13 @@ async function initCatalogBrowser() {
// Update Store Banner
function updateStoreBanner() {
const cur = window.ALL_STORES[window.activeStoreId];
if (!cur) return;
if (!cur) {
if (activeStoreTitle) activeStoreTitle.textContent = window.AuraStudio.workspace.name || window.AuraStudio.workspace.tenant;
if (activeStoreBadge) activeStoreBadge.textContent = 'CATALOG';
if (activeStoreUrlLink) { activeStoreUrlLink.removeAttribute('href'); activeStoreUrlLink.textContent = ''; }
if (deleteCurrentStoreBtn) deleteCurrentStoreBtn.classList.add('hidden');
return;
}
if (activeStoreIcon) activeStoreIcon.textContent = cur.icon || '🛍️';
if (activeStoreTitle) activeStoreTitle.textContent = `${cur.name} (${cur.domain})`;
@@ -6839,13 +6766,16 @@ async function initCatalogBrowser() {
if (confirm(`আপনি কি "${cur.name}" স্টোর বক্স এবং এর সব প্রডাক্ট মুছে ফেলতে চান?`)) {
try {
await fetch('/api/delete-synced-store', {
const response = await fetch(apiUrl('/api/delete-synced-store'), {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ storeId: cur.id })
});
const result = await response.json();
if (!response.ok || result.success !== true) throw new Error(result.error || 'Store মুছে ফেলা হয়নি।');
delete window.ALL_STORES[cur.id];
switchActiveStore('glamourstouch');
window.activeStoreId = Object.keys(window.ALL_STORES)[0] || null;
renderStoreSwitcher(); updateStoreBanner(); renderBrandFilterChips(); renderCatalogGrid();
} catch (e) {
alert('Error deleting store: ' + e.message);
}
@@ -6879,7 +6809,7 @@ async function initCatalogBrowser() {
startStoreSyncBtn.disabled = true;
try {
const res = await fetch('/api/sync-store', {
const res = await fetch(apiUrl('/api/sync-store'), {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
@@ -6986,7 +6916,7 @@ async function initCatalogBrowser() {
return;
}
const brandCounts = {};
const brandCounts = Object.create(null);
cur.products.forEach(p => {
const b = p.brand || cur.name || 'Brand';
brandCounts[b] = (brandCounts[b] || 0) + 1;
@@ -6999,7 +6929,7 @@ async function initCatalogBrowser() {
let html = `<button class="filter-chip ${selectedCatalogBrand === 'all' ? 'active' : ''}" data-brand="all">🔥 All Brands (${cur.products.length})</button>`;
topBrands.forEach(b => {
html += `<button class="filter-chip ${selectedCatalogBrand.toLowerCase() === b.toLowerCase() ? 'active' : ''}" data-brand="${b}">${b} (${brandCounts[b]})</button>`;
html += `<button class="filter-chip ${selectedCatalogBrand.toLowerCase() === b.toLowerCase() ? 'active' : ''}" data-brand="${htmlText(b)}">${htmlText(b)} (${brandCounts[b]})</button>`;
});
brandChipsContainer.innerHTML = html;
@@ -7018,7 +6948,14 @@ async function initCatalogBrowser() {
function renderCatalogGrid() {
if (!catalogGridContainer) return;
const cur = window.ALL_STORES[window.activeStoreId];
if (!cur) return;
if (!cur) {
catalogGridContainer.replaceChildren();
const empty = document.createElement('p');
empty.textContent = 'এই workspace-এ catalog এখনও যোগ করা হয়নি। নিজের store connect বা URL দিয়ে sync করুন।';
catalogGridContainer.appendChild(empty);
if (catalogCountText) catalogCountText.textContent = '0 products';
return;
}
const dict = I18N_DICTIONARY[window.currentLang] || I18N_DICTIONARY.bn;
const query = (catalogSearchInput ? catalogSearchInput.value : '').toLowerCase().trim();
@@ -7036,9 +6973,9 @@ async function initCatalogBrowser() {
if (catalogCountText) {
if (window.currentLang === 'en') {
catalogCountText.textContent = `${cur.name} — ${filtered.length} authentic products found (Total ${cur.products.length})`;
catalogCountText.textContent = `${cur.name} — ${filtered.length} products found (Total ${cur.products.length})`;
} else {
catalogCountText.textContent = `${cur.name} — ${filtered.length}টি আসল প্রোডাক্ট পাওয়া গেছে (মোট ${cur.products.length}টি)`;
catalogCountText.textContent = `${cur.name} — ${filtered.length}টি প্রোডাক্ট পাওয়া গেছে (মোট ${cur.products.length}টি)`;
}
}
@@ -7055,20 +6992,20 @@ async function initCatalogBrowser() {
const displayList = filtered.slice(0, 150);
catalogGridContainer.innerHTML = displayList.map(p => `
<div class="catalog-item-card">
<img class="catalog-item-img" src="${p.image || '/assets/products/cosmetics_3d_cgi.jpg'}" alt="${p.title}" loading="lazy" onerror="this.src='/assets/products/cosmetics_3d_cgi.jpg'">
<img class="catalog-item-img" src="${htmlText(p.image || '/assets/products/cosmetics_3d_cgi.jpg')}" alt="${htmlText(p.title)}" loading="lazy" onerror="this.src='/assets/products/cosmetics_3d_cgi.jpg'">
<div style="flex:1;">
<span style="font-size:10px; font-weight:800; color:#C084FC; text-transform:uppercase; letter-spacing:0.5px;">${p.brand || cur.name}</span>
<h4 class="catalog-item-title" title="${p.title}">${p.title}</h4>
<span style="font-size:10px; font-weight:800; color:#C084FC; text-transform:uppercase; letter-spacing:0.5px;">${htmlText(p.brand || cur.name)}</span>
<h4 class="catalog-item-title" title="${htmlText(p.title)}">${htmlText(p.title)}</h4>
<div class="catalog-item-price-row">
<span class="catalog-item-price">${p.price}</span>
<span class="catalog-item-reg-price">${p.regularPrice}</span>
<span class="catalog-item-price">${htmlText(p.price)}</span>
<span class="catalog-item-reg-price">${htmlText(p.regularPrice)}</span>
</div>
</div>
<div class="catalog-item-actions">
<button type="button" class="btn-catalog-copy" onclick="window.copyCatalogProductInfo('${p.id}')">
<button type="button" class="btn-catalog-copy" onclick="window.copyCatalogProductInfo(decodeURIComponent('${encodeURIComponent(String(p.id)).replace(/'/g, '%27')}'))">
${dict.btn_catalog_copy || '📋 কপি'}
</button>
<button type="button" class="btn-catalog-use" onclick="window.applyCatalogProductToPoster('${p.id}')">
<button type="button" class="btn-catalog-use" onclick="window.applyCatalogProductToPoster(decodeURIComponent('${encodeURIComponent(String(p.id)).replace(/'/g, '%27')}'))">
${dict.btn_catalog_use || '⚡ ৩ডি পোস্টার'}
</button>
</div>
@@ -7092,7 +7029,7 @@ async function initCatalogBrowser() {
}
if (!p) return;
const text = `✨ ${p.title}\n🏷️ ব্র্যান্ড / স্টোর: ${p.brand || storeObj.name}\n💰 অফার মূল্য: ${p.price} (রেগুলার ${p.regularPrice})\n🛡️ ১০০% আসল ও প্রিমিয়াম কোয়ালিটি নিশ্চিত\n🔗 লিংক: ${p.link || storeObj.url}\n📸 ইমেজ: ${p.image}`;
const text = `✨ ${p.title}\n🏷️ ব্র্যান্ড / স্টোর: ${p.brand || storeObj.name}\n💰 মূল্য: ${p.price}${p.regularPrice ? ' (রেগুলার ' + p.regularPrice + ')' : ''}\n🔗 লিংক: ${p.link || storeObj.url}\n📸 ইমেজ: ${p.image}`;
navigator.clipboard.writeText(text).then(() => {
alert(`✅ "${p.title}"-এর সম্পূর্ণ তথ্য কপি হয়েছে!`);
}).catch(() => {
@@ -7131,33 +7068,26 @@ async function initCatalogBrowser() {
const clearBtn = document.getElementById('clearPhotoBtn');
if (pInput) pInput.value = p.title;
if (pPrice) pPrice.value = `${p.price} (${p.regularPrice}) 20% OFF`;
if (pBadge) pBadge.value = `🛡️ 100% Authentic ${p.brand || storeObj.name}`;
if (pPrice) pPrice.value = [p.price, p.regularPrice ? '(' + p.regularPrice + ')' : ''].filter(Boolean).join(' ');
if (pBadge) pBadge.value = '';
if (pBrand) {
if (storeObj.id === 'glamourstouch') {
pBrand.value = 'glamourstouch';
} else if (storeObj.category && pBrand.querySelector(`option[value="${storeObj.category}"]`)) {
pBrand.value = storeObj.category;
} else {
pBrand.value = 'custom';
}
}
if (pBrand) pBrand.value = 'workspace';
if (photoImg && photoBox && p.image) {
photoImg.src = p.image;
photoBox.classList.remove('hidden');
if (clearBtn) clearBtn.classList.remove('hidden');
} else if (photoImg && photoBox) {
photoImg.removeAttribute('src');
photoBox.classList.add('hidden');
if (clearBtn) clearBtn.classList.add('hidden');
}
window.closeCatalogModal();
if (autocompleteList) autocompleteList.classList.add('hidden');
switchToTab('tabPosterLab');
setTimeout(() => {
const genBtn = document.getElementById('generatePosterBtn');
if (genBtn) genBtn.click();
}, 250);
// Product selection fills the form; rendering remains an explicit user action.
};
// 8. Live Autocomplete on #productInput across all active stores
@@ -7185,16 +7115,16 @@ async function initCatalogBrowser() {
const dict = I18N_DICTIONARY[window.currentLang] || I18N_DICTIONARY.bn;
autocompleteList.innerHTML = matches.map(p => `
<div class="autocomplete-item" onclick="window.applyCatalogProductToPoster('${p.id}')">
<img class="autocomplete-thumb" src="${p.image || '/assets/products/cosmetics_3d_cgi.jpg'}" alt="${p.title}" onerror="this.src='/assets/products/cosmetics_3d_cgi.jpg'">
<div class="autocomplete-item" onclick="window.applyCatalogProductToPoster(decodeURIComponent('${encodeURIComponent(String(p.id)).replace(/'/g, '%27')}'))">
<img class="autocomplete-thumb" src="${htmlText(p.image || '/assets/products/cosmetics_3d_cgi.jpg')}" alt="${htmlText(p.title)}" onerror="this.src='/assets/products/cosmetics_3d_cgi.jpg'">
<div class="autocomplete-info">
<div class="autocomplete-title">${p.title}</div>
<div class="autocomplete-title">${htmlText(p.title)}</div>
<div class="autocomplete-meta">
<span class="autocomplete-brand">${p.brand || p.storeName || "Authentic"}</span>
<span class="autocomplete-price">${p.price}</span>
<span class="autocomplete-brand">${htmlText(p.brand || p.storeName || "Authentic")}</span>
<span class="autocomplete-price">${htmlText(p.price)}</span>
</div>
</div>
<button type="button" class="autocomplete-copy-btn" onclick="event.stopPropagation(); window.copyCatalogProductInfo('${p.id}');">
<button type="button" class="autocomplete-copy-btn" onclick="event.stopPropagation(); window.copyCatalogProductInfo(decodeURIComponent('${encodeURIComponent(String(p.id)).replace(/'/g, '%27')}'));">
${dict.btn_catalog_copy || '📋 কপি'}
</button>
</div>
+6 -1
View File
@@ -1,3 +1,9 @@
# Frontend workspace integration — 19 October 2026
The candidate now gates app startup on verified workspace identity, scopes browser private state by client UUID, removes prototype merchant catalog/default policy for new clients, and escapes imported catalog markup. Local and Linux image tests pass 58/58. Separate loopback browser QA confirms inert HTML-like product names, source price transfer without a fabricated discount, and an empty second workspace. The large poster renderer section is unchanged. CLI configuration now requires STUDIO_LOGIN_URL.
Connected Client catalog brokerage, full Client startup/recovery, persistent Studio service configuration and actual release remain open. No Meta 1-Click Connector inspection or change was made.
# Studio runtime source reconciliation
Captured on 2026-10-18 from the running Aura Studio static application. app.js is restored byte-for-byte from the privately preserved live file, SHA-256 025a1d94971361944cc3a3197bb894255d96cc824f603da3425466fab4cbdf74. The remaining checked static entry/config files match repository main after line-ending normalization.
@@ -38,4 +44,3 @@ Catalog list/import/delete responses replace merchant image URLs with a same-ori
The backend candidate is not deployed. Frontend authentication/workspace selection, private browser-state namespacing, imported-text rendering, connected Client catalog access and persistent production configuration remain required release work. The prototype global GT catalog is not a valid default for another client. No Meta connector inspection or modification is part of this work.
The local branch reference was found zero-filled. Its bytes were retained outside the Git refs directory, the remote branch was read, and the existing local commit object was checked before restoring the reference to `cbe6e0ae94e22e6c34ecc55bad036ff8c165b488`. No working files were reset. The cause of that local reference damage is not established.
+42 -62
View File
@@ -22,6 +22,17 @@
<link rel="stylesheet" href="style.css?v=6">
</head>
<body>
<section id="studioWorkspaceGate" role="dialog" aria-modal="true" aria-labelledby="workspaceTitle" style="position:fixed;inset:0;z-index:99999;background:#0b1020;color:#eef2ff;padding:10vh 8vw;overflow:auto">
<h1 id="workspaceTitle">Aura Studio</h1>
<p id="workspaceStatus" role="status">আপনার workspace যাচাই হচ্ছে…</p>
<a id="workspaceLogin" class="pill-btn primary" hidden>Login করুন</a>
<form id="workspaceForm" hidden>
<label for="workspaceTenant">Client workspace ID</label>
<input id="workspaceTenant" name="tenant" maxlength="256" required autocomplete="off" placeholder="আপনার client workspace ID">
<button type="submit" class="pill-btn primary">Workspace খুলুন</button>
</form>
<button id="workspaceRetry" type="button" class="pill-btn">আবার চেষ্টা করুন</button>
</section>
<!-- Top App Header -->
<header class="app-header">
@@ -246,16 +257,7 @@
<option value="1:1" selected>Square (1:1 • 1080x1080) — Facebook/Instagram Feed</option>
<option value="9:16">Portrait (9:16 • 1080x1920) — Stories & Reels</option>
</select>
<select id="brandWatermarkSelect">
<option value="glamourstouch" selected>✨ Glamour's Touch (Cosmetics & K-Beauty)</option>
<option value="snehalata">👗 Snehalata (Fashion, Saree & Lifestyle)</option>
<option value="panjabi">👑 Aura Heritage (Royal Designer Panjabi & Kabli)</option>
<option value="techvolt">📱 TechVolt (Gadgets & Smart Electronics)</option>
<option value="organic">🍯 Pranon Organic (Pure Honey & Natural Food)</option>
<option value="sneakerlab">👟 SneakerLab (Footwear & Streetwear)</option>
<option value="royale">💎 Aura Royale (Luxury Jewelry & Fragrance)</option>
<option value="custom">🛍️ Universal E-Commerce Merchant</option>
</select>
<select id="brandWatermarkSelect"><option value="workspace">আপনার workspace</option></select>
</div>
</div>
@@ -277,37 +279,29 @@
<!-- Trending Google Search Suggestions -->
<div class="form-group">
<label style="display:flex; justify-content:space-between; align-items:center;">
<span data-i18n="trends_label">🔥 গুগল ট্রেন্ডিং সার্চ (Google Trends 1-Click Load):</span>
<span style="font-size:10.5px; color:var(--primary); font-weight:600;" data-i18n="trends_badge">Realtime BD Trends</span>
<span data-i18n="trends_label">🛍️ আপনার catalog থেকে বাছুন:</span>
<span style="font-size:10.5px; color:var(--primary); font-weight:600;" data-i18n="trends_badge">Workspace catalog</span>
</label>
<div class="trending-chips-bar" id="trendingPosterChips">
<button type="button" class="trend-chip active" data-brand="glamourstouch" data-title="Medicube Collagen Jelly Cream" data-price="৳ ১,০৬০ (৳ ১,৪৭০) 28% OFF" data-badge="🛡️ 100% Authentic Korean Seal">✨ K-Beauty Cream</button>
<button type="button" class="trend-chip" data-brand="panjabi" data-title="Royal Platinum Silk Designer Panjabi" data-price="৳ ২,৯৫০ (৳ ৩,৮০০) 22% OFF" data-badge="👑 100% Pre-Shrunk Weave">👑 Royal Panjabi</button>
<button type="button" class="trend-chip" data-brand="snehalata" data-title="Katan Silk Handloom Party Saree" data-price="৳ ৩,৪৫০ (৳ ৪,৫০০) 23% OFF" data-badge="👗 Authentic Handloom Weave">👗 Silk Saree</button>
<button type="button" class="trend-chip" data-brand="techvolt" data-title="T900 Ultra Smartwatch Series 9" data-price="৳ ১,৬৫০ (৳ ২,২০০) 25% OFF" data-badge="⚡ 1 Year Official Warranty">⚡ Smartwatch</button>
<button type="button" class="trend-chip" data-brand="organic" data-title="Sundarban Pure Raw Khalsi Honey 1kg" data-price="৳ ১,২৫০ (৳ ১,৫০০) 16% OFF" data-badge="🍯 100% Pure Lab Tested">🍯 Pure Honey</button>
<button type="button" class="trend-chip" data-brand="sneakerlab" data-title="Air Cushion Streetwear Sneaker 2026" data-price="৳ ২,৪৫০ (৳ ৩,২০০) 23% OFF" data-badge="👟 Memory Foam Cushion">👟 Street Sneaker</button>
<button type="button" class="trend-chip" data-brand="royale" data-title="Oud Al Layl 24h Signature Perfume 100ml" data-price="৳ ৩,২০০ (৳ ৪,০০০) 20% OFF" data-badge="💎 24h Long Lasting Sillage">💎 Luxury Perfume</button>
</div>
<div class="trending-chips-bar" id="trendingPosterChips"></div>
</div>
<div class="form-group" style="position: relative;">
<label for="productInput" style="display:flex; justify-content:space-between; align-items:center; flex-wrap:wrap; gap:6px;">
<span data-i18n="product_input_label">প্রডাক্ট লিংক বা নাম (Product Link or Name):</span>
<button type="button" id="openCatalogModalBtn" class="pill-btn primary" style="padding:4px 10px; font-size:11px; cursor:pointer;" data-i18n="open_catalog_btn">🛍️ GT ক্যাটালগ লিস্ট (560+)</button>
<button type="button" id="openCatalogModalBtn" class="pill-btn primary" style="padding:4px 10px; font-size:11px; cursor:pointer;" data-i18n="open_catalog_btn">🛍️ আপনার catalog</button>
</label>
<input type="text" id="productInput" data-i18n-ph="product_input_ph" placeholder="e.g. Silk Saree, Smartwatch, Pure Honey, Sneaker or Skincare" value="Medicube Collagen Jelly Cream" autocomplete="off">
<input type="text" id="productInput" data-i18n-ph="product_input_ph" placeholder="e.g. Silk Saree, Smartwatch, Pure Honey, Sneaker or Skincare" value="" autocomplete="off">
<div id="productAutocompleteList" class="autocomplete-dropdown hidden"></div>
</div>
<div class="form-row">
<div class="form-group">
<label for="productPrice" data-i18n="product_price_label">মূল্য ও অফার (Price & Discount):</label>
<input type="text" id="productPrice" data-i18n-ph="product_price_ph" placeholder="e.g. ৳ ১,০৬০ (৳ ১,৪৭০) 28% OFF" value="৳ ১,০৬০ (৳ ১,৪৭০) 28% OFF">
<input type="text" id="productPrice" data-i18n-ph="product_price_ph" placeholder="e.g. ৳ ১,০৬০ (৳ ১,৪৭০) 28% OFF" value="">
</div>
<div class="form-group">
<label for="customBadgeInput" data-i18n="product_badge_label">কাস্টম ব্যাজ টেক্সট (Trust Badge):</label>
<input type="text" id="customBadgeInput" data-i18n-ph="product_badge_ph" placeholder="e.g. 🛡️ 100% Original Guarantee" value="🛡️ 100% Original Guarantee">
<input type="text" id="customBadgeInput" data-i18n-ph="product_badge_ph" placeholder="e.g. 🛡️ 100% Original Guarantee" value="">
</div>
</div>
@@ -348,13 +342,7 @@
<span data-i18n="multi_combos_label">🎁 ট্রেন্ডিং মাল্টি-প্যাক কম্বো (1-Click Multi Combos):</span>
<span style="font-size:10.5px; color:var(--primary); font-weight:600;" data-i18n="multi_combos_badge">Full Catalog Combos</span>
</label>
<div class="trending-chips-bar" id="multiComboChips">
<button type="button" class="trend-chip active" data-combo="kbeauty_4">🌸 K-Beauty 4-Pack</button>
<button type="button" class="trend-chip" data-combo="panjabi_3">👑 Royal Panjabi Trio</button>
<button type="button" class="trend-chip" data-combo="tech_3">📱 TechVolt Trio</button>
<button type="button" class="trend-chip" data-combo="organic_3">🍯 Pure Nature Trio</button>
<button type="button" class="trend-chip" data-combo="sneaker_4">👟 SneakerLab 4-Pack</button>
</div>
<div class="trending-chips-bar" id="multiComboChips"></div>
</div>
<!-- 4 Interactive Product Slots -->
@@ -370,10 +358,10 @@
<span id="slotPlaceholder1" style="font-size:11px; color:#64748B;" data-i18n="slot_placeholder_text">ছবি সিলেক্ট করুন</span>
</div>
<div class="slot-inputs-row">
<input type="text" id="slotTitle1" class="slot-input" data-i18n-ph="slot_title_ph" placeholder="প্রোডাক্ট নাম" value="Medicube Collagen Jelly Cream">
<input type="text" id="slotPrice1" class="slot-input" data-i18n-ph="slot_price_ph" placeholder="মূল্য" value="৳ ১,০৬০">
<input type="text" id="slotTitle1" class="slot-input" data-i18n-ph="slot_title_ph" placeholder="প্রোডাক্ট নাম" value="">
<input type="text" id="slotPrice1" class="slot-input" data-i18n-ph="slot_price_ph" placeholder="মূল্য" value="">
</div>
<input type="text" id="slotBadge1" class="slot-input" data-i18n-ph="slot_badge_ph" placeholder="ব্যাজ" value="🛡️ 100% Original">
<input type="text" id="slotBadge1" class="slot-input" data-i18n-ph="slot_badge_ph" placeholder="ব্যাজ" value="">
</div>
<!-- SLOT 2 -->
@@ -387,10 +375,10 @@
<span id="slotPlaceholder2" style="font-size:11px; color:#64748B;" data-i18n="slot_placeholder_text">ছবি সিলেক্ট করুন</span>
</div>
<div class="slot-inputs-row">
<input type="text" id="slotTitle2" class="slot-input" data-i18n-ph="slot_title_ph" placeholder="প্রোডাক্ট নাম" value="Anua Heartleaf 77% Toner">
<input type="text" id="slotPrice2" class="slot-input" data-i18n-ph="slot_price_ph" placeholder="মূল্য" value="৳ ১,৪৮০">
<input type="text" id="slotTitle2" class="slot-input" data-i18n-ph="slot_title_ph" placeholder="প্রোডাক্ট নাম" value="">
<input type="text" id="slotPrice2" class="slot-input" data-i18n-ph="slot_price_ph" placeholder="মূল্য" value="">
</div>
<input type="text" id="slotBadge2" class="slot-input" data-i18n-ph="slot_badge_ph" placeholder="ব্যাজ" value="🌿 Soothing Care">
<input type="text" id="slotBadge2" class="slot-input" data-i18n-ph="slot_badge_ph" placeholder="ব্যাজ" value="">
</div>
<!-- SLOT 3 -->
@@ -404,10 +392,10 @@
<span id="slotPlaceholder3" style="font-size:11px; color:#64748B;" data-i18n="slot_placeholder_text">ছবি সিলেক্ট করুন</span>
</div>
<div class="slot-inputs-row">
<input type="text" id="slotTitle3" class="slot-input" data-i18n-ph="slot_title_ph" placeholder="প্রোডাক্ট নাম" value="COSRX Snail 96 Mucin Essence">
<input type="text" id="slotPrice3" class="slot-input" data-i18n-ph="slot_price_ph" placeholder="মূল্য" value="৳ ১,৩৫০">
<input type="text" id="slotTitle3" class="slot-input" data-i18n-ph="slot_title_ph" placeholder="প্রোডাক্ট নাম" value="">
<input type="text" id="slotPrice3" class="slot-input" data-i18n-ph="slot_price_ph" placeholder="মূল্য" value="">
</div>
<input type="text" id="slotBadge3" class="slot-input" data-i18n-ph="slot_badge_ph" placeholder="ব্যাজ" value="✨ Glass Skin Glow">
<input type="text" id="slotBadge3" class="slot-input" data-i18n-ph="slot_badge_ph" placeholder="ব্যাজ" value="">
</div>
<!-- SLOT 4 -->
@@ -421,10 +409,10 @@
<span id="slotPlaceholder4" style="font-size:11px; color:#64748B;" data-i18n="slot_placeholder_text">ছবি সিলেক্ট করুন</span>
</div>
<div class="slot-inputs-row">
<input type="text" id="slotTitle4" class="slot-input" data-i18n-ph="slot_title_ph" placeholder="প্রোডাক্ট নাম" value="Beauty of Joseon Sun Relief">
<input type="text" id="slotPrice4" class="slot-input" data-i18n-ph="slot_price_ph" placeholder="মূল্য" value="৳ ১,১৫০">
<input type="text" id="slotTitle4" class="slot-input" data-i18n-ph="slot_title_ph" placeholder="প্রোডাক্ট নাম" value="">
<input type="text" id="slotPrice4" class="slot-input" data-i18n-ph="slot_price_ph" placeholder="মূল্য" value="">
</div>
<input type="text" id="slotBadge4" class="slot-input" data-i18n-ph="slot_badge_ph" placeholder="ব্যাজ" value="☀️ SPF50+ PA++++">
<input type="text" id="slotBadge4" class="slot-input" data-i18n-ph="slot_badge_ph" placeholder="ব্যাজ" value="">
</div>
</div>
</div>
@@ -649,11 +637,11 @@ Format with clear bullet points, emojis, and a call-to-action.</textarea>
<div class="form-row">
<div class="form-group">
<label for="ugcProductName" data-i18n="ugc_prod_label">প্রডাক্টের নাম ও ব্র্যান্ড (Product):</label>
<input type="text" id="ugcProductName" data-i18n-ph="ugc_prod_ph" placeholder="e.g. Medicube Collagen Jelly Cream" value="Medicube Collagen Jelly Cream">
<input type="text" id="ugcProductName" data-i18n-ph="ugc_prod_ph" placeholder="e.g. Medicube Collagen Jelly Cream" value="">
</div>
<div class="form-group">
<label for="ugcTargetAudience" data-i18n="ugc_aud_label">টার্গেট অডিয়েন্স ও সমস্যা (Audience/Problem):</label>
<input type="text" id="ugcTargetAudience" data-i18n-ph="ugc_aud_ph" placeholder="e.g. যাদের ত্বক খসখসে ও রোদে পোড়া দাগ রয়েছে" value="যাদের ত্বক খসখসে ও রোদে পোড়া দাগ রয়েছে">
<input type="text" id="ugcTargetAudience" data-i18n-ph="ugc_aud_ph" placeholder="e.g. যাদের ত্বক খসখসে ও রোদে পোড়া দাগ রয়েছে" value="">
</div>
</div>
@@ -777,7 +765,7 @@ Format with clear bullet points, emojis, and a call-to-action.</textarea>
<div class="form-group">
<label for="inboxStoreContext" data-i18n="inbox_store_label">দোকানের পলিসি ও হটলাইন (Store Info):</label>
<input type="text" id="inboxStoreContext" data-i18n-ph="inbox_store_ph" value="Store: Glamour's Touch (glamourstouch.com), Hotline: 01712-426871, 100% Authentic Korean Skincare, Delivery: Dhaka ৳70, Outside Dhaka ৳130, Free delivery on ৳2000+">
<input type="text" id="inboxStoreContext" data-i18n-ph="inbox_store_ph" value="">
</div>
<button id="generateInboxReplyBtn" class="btn-primary">
@@ -856,8 +844,8 @@ Format with clear bullet points, emojis, and a call-to-action.</textarea>
<div class="form-group">
<label for="n8nWebhookInput" data-i18n="settings_webhook_label">n8n Auto-Post Webhook URL (Aura Ajentic AI):</label>
<input type="text" id="n8nWebhookInput" placeholder="https://n8n.auraajenticai.cloud/webhook/gt-auto-post" value="https://n8n.auraajenticai.cloud/webhook/gt-auto-post">
<small class="hint-text" data-i18n="settings_webhook_hint">Pre-configured with your n8n cloud instance at n8n.auraajenticai.cloud</small>
<input type="text" id="n8nWebhookInput" placeholder="আপনার অনুমোদিত n8n webhook URL" value="">
<small class="hint-text" data-i18n="settings_webhook_hint">নিজের workspace-এর অনুমোদিত webhook URL দিন।</small>
</div>
<button id="saveApiKeyBtn" class="btn-primary" data-i18n="btn_save_settings">
@@ -983,15 +971,7 @@ Format with clear bullet points, emojis, and a call-to-action.</textarea>
</div>
<!-- Store Switcher Box Tabs -->
<div class="store-switcher-bar" id="storeSwitcherBar">
<button type="button" class="store-chip-btn active" data-store-id="glamourstouch">
<span>✨</span> Glamour's Touch (563)
</button>
<!-- Synced Store chips will be injected here -->
<button type="button" class="store-chip-btn add-store-btn" id="toggleSyncPanelBtn">
<span>➕</span> <span data-i18n="btn_sync_new_store">নতুন ক্লায়েন্ট স্টোর সিঙ্ক</span>
</button>
</div>
<div class="store-switcher-bar" id="storeSwitcherBar"></div>
<!-- Client URL Sync Input Panel (Collapsible) -->
<div id="storeSyncPanel" class="store-sync-panel hidden">
@@ -1024,11 +1004,11 @@ Format with clear bullet points, emojis, and a call-to-action.</textarea>
<div id="storeInfoBanner" class="store-info-banner">
<div class="store-info-left">
<span id="activeStoreIcon">✨</span>
<strong id="activeStoreTitle">Glamour's Touch (GT)</strong>
<span id="activeStoreBadge" class="store-badge-tag">KOREAN COSMETICS</span>
<strong id="activeStoreTitle">আপনার workspace</strong>
<span id="activeStoreBadge" class="store-badge-tag">CATALOG</span>
</div>
<div style="display:flex; align-items:center; gap:8px;">
<a id="activeStoreUrlLink" href="https://glamourstouch.com" target="_blank" style="font-size:11px; color:#38BDF8; text-decoration:none;">🔗 Visit Store</a>
<a id="activeStoreUrlLink" target="_blank" rel="noopener noreferrer" style="font-size:11px; color:#38BDF8; text-decoration:none;">🔗 Visit Store</a>
<button type="button" id="deleteCurrentStoreBtn" class="btn-delete-store hidden" data-i18n="btn_delete_store">🗑️ মুছুন</button>
</div>
</div>
@@ -1052,7 +1032,7 @@ Format with clear bullet points, emojis, and a call-to-action.</textarea>
<!-- Hidden container for generating QR code SVG/Canvas -->
<div id="qrcodeHidden" style="display:none;"></div>
<script src="app.js?v=8"></script>
<script src="workspace.js?v=1"></script>
<script>
if ('serviceWorker' in navigator) {
window.addEventListener('load', () => {
+12 -1
View File
@@ -9,6 +9,12 @@ const { createImageHandler } = require('./images.cjs');
const { createStaticHandler } = require('./static.cjs');
function createStudioServer(config) {
let loginUrl = null;
if (config.loginUrl) {
const parsed = new URL(config.loginUrl);
if (!['https:', 'http:'].includes(parsed.protocol) || parsed.username || parsed.password || parsed.hash) throw new Error('Invalid public login URL');
loginUrl = parsed.href;
}
const resolveWorkspace = createWorkspaceResolver({ authMeUrl: config.authMeUrl, clientMeUrl: config.clientMeUrl });
const store = createStore(config.dataDirectory);
const scrape = createScraper({ fetchPublic: createPublicFetcher(config.fetchLimits), ...config.importLimits });
@@ -18,6 +24,10 @@ function createStudioServer(config) {
const server = http.createServer({ maxHeaderSize: 16384 }, async (req, res) => {
try {
const pathname = new URL(req.url, config.publicOrigin).pathname;
if (pathname === '/api/studio-config' && req.method === 'GET') {
res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8', 'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff' });
return res.end(JSON.stringify({ loginUrl }));
}
if (pathname === '/health' && ['GET', 'HEAD'].includes(req.method)) {
res.writeHead(200, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' });
return res.end(req.method === 'HEAD' ? undefined : JSON.stringify({ ok: true, service: 'aura-studio' }));
@@ -37,7 +47,7 @@ function createStudioServer(config) {
if (require.main === module) {
try {
const required = ['STUDIO_PUBLIC_ORIGIN', 'STUDIO_AUTH_ME_URL', 'STUDIO_CLIENT_ME_URL', 'STUDIO_DATA_DIR'];
const required = ['STUDIO_PUBLIC_ORIGIN', 'STUDIO_LOGIN_URL', 'STUDIO_AUTH_ME_URL', 'STUDIO_CLIENT_ME_URL', 'STUDIO_DATA_DIR'];
if (required.some(name => !process.env[name])) throw new Error('Required Studio service configuration is missing');
const port = Number(process.env.PORT || 3000);
if (!Number.isInteger(port) || port < 1 || port > 65535) throw new Error('Invalid Studio port');
@@ -49,6 +59,7 @@ if (require.main === module) {
}
const server = createStudioServer({
publicOrigin: process.env.STUDIO_PUBLIC_ORIGIN,
loginUrl: process.env.STUDIO_LOGIN_URL,
authMeUrl: process.env.STUDIO_AUTH_ME_URL, clientMeUrl: process.env.STUDIO_CLIENT_ME_URL,
dataDirectory: process.env.STUDIO_DATA_DIR,
publicDirectory: process.env.STUDIO_PUBLIC_DIR || path.join(__dirname, '../public'),
+1 -1
View File
@@ -4,7 +4,7 @@ const { createHash } = require('node:crypto');
const { gzipSync } = require('node:zlib');
const MIME = { '.html': 'text/html; charset=utf-8', '.js': 'application/javascript; charset=utf-8', '.css': 'text/css; charset=utf-8', '.json': 'application/json; charset=utf-8', '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.webp': 'image/webp', '.svg': 'image/svg+xml', '.ico': 'image/x-icon', '.woff': 'font/woff', '.woff2': 'font/woff2' };
const ROOT_FILES = new Set(['index.html', 'app.js', 'style.css', 'sw.js', 'manifest.json', 'gt_full_catalog.json']);
const ROOT_FILES = new Set(['index.html', 'app.js', 'workspace.js', 'style.css', 'sw.js', 'manifest.json', 'gt_full_catalog.json']);
function createStaticHandler(publicDirectory, { maxCacheBytes = 16 * 1024 * 1024 } = {}) {
const root = path.resolve(publicDirectory), cache = new Map();
+73
View File
@@ -0,0 +1,73 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const vm = require('node:vm');
const path = require('node:path');
const workspaceModule = fs.existsSync(path.join(__dirname, '../workspace.js')) ? '../workspace.js' : '../public/workspace.js';
const { scopedStorage, escapeText } = require(workspaceModule);
const a = '11111111-1111-4111-8111-111111111111';
const b = '22222222-2222-4222-8222-222222222222';
function memory() {
const values = new Map();
return { getItem: key => values.has(key) ? values.get(key) : null, setItem: (key, value) => values.set(key, String(value)), removeItem: key => values.delete(key), values };
}
test('private browser keys are scoped by verified client, with no automatic legacy migration', () => {
const storage = memory(); storage.setItem('opal_gemini_api_key', 'legacy-test-key');
const first = scopedStorage(storage, a), other = scopedStorage(storage, b), staff = scopedStorage(storage, a.toUpperCase());
assert.equal(first.getItem('opal_gemini_api_key'), null);
first.setItem('opal_gemini_api_key', 'client-a-test-key');
assert.equal(staff.getItem('opal_gemini_api_key'), 'client-a-test-key');
assert.equal(other.getItem('opal_gemini_api_key'), null);
other.removeItem('opal_gemini_api_key');
assert.equal(first.getItem('opal_gemini_api_key'), 'client-a-test-key');
assert.equal(storage.getItem('opal_gemini_api_key'), 'legacy-test-key');
assert.throws(() => scopedStorage(storage, '../tenant'), /Verified/);
});
test('imported markup is text in both quoted attributes and HTML content', () => {
assert.equal(escapeText('<img src=x onerror="alert(1)"> & \'SKU\''), '&lt;img src=x onerror=&quot;alert(1)&quot;&gt; &amp; &#39;SKU&#39;');
});
async function bootstrap(response, config = { loginUrl: 'https://auth.fixture/login' }) {
const nodes = new Map(), requests = [], scripts = [], events = [];
function node() { return { hidden: true, value: '', textContent: '', inert: false, prepend() {} }; }
const get = id => { if (!nodes.has(id)) nodes.set(id, node()); return nodes.get(id); };
let start;
const context = {
URL, URLSearchParams, Event, Object, encodeURIComponent,
location: { href: 'https://studio.fixture/?tenant=chosen', origin: 'https://studio.fixture', search: '?tenant=chosen', reload() {}, assign() {} },
localStorage: memory(), sessionStorage: memory(),
fetch: async url => { requests.push(url); return { ok: url === '/api/studio-config' ? true : response.status === 200, status: response.status, json: async () => url === '/api/studio-config' ? config : response.body }; },
document: {
getElementById: get, querySelectorAll: () => [], querySelector: () => null,
createElement: tag => ({ tag }),
addEventListener: (event, callback) => { if (event === 'DOMContentLoaded') start = callback; },
dispatchEvent: event => events.push(event.type),
body: { appendChild: script => scripts.push(script) }
}
};
context.window = context;
vm.runInNewContext(fs.readFileSync(require.resolve(workspaceModule), 'utf8'), context);
await start();
return { context, nodes, requests, scripts, events };
}
test('login and workspace selection failures do not load app code or expose saved client state', async () => {
const login = await bootstrap({ status: 401, body: { code: 'LOGIN_REQUIRED', error: 'Login first' } });
assert.equal(login.scripts.length, 0); assert.equal(login.context.AuraStudio, undefined);
assert.equal(login.nodes.get('workspaceLogin').hidden, false);
assert.equal(new URL(login.nodes.get('workspaceLogin').href).searchParams.get('next'), login.context.location.href);
const owner = await bootstrap({ status: 409, body: { code: 'WORKSPACE_REQUIRED', error: 'Choose workspace' } });
assert.equal(owner.nodes.get('workspaceForm').hidden, false);
assert.equal(owner.scripts.length, 0);
const invalid = await bootstrap({ status: 200, body: { success: true, workspace: { clientId: 'bad', tenant: 'chosen' } } });
assert.equal(invalid.scripts.length, 0);
});
test('validated workspace loads app once and preserves canonical tenant in API requests', async () => {
const ready = await bootstrap({ status: 200, body: { success: true, workspace: { clientId: a, name: 'Fixture shop', tenant: 'canonical' } } });
assert.equal(ready.scripts.length, 1);
assert.equal(ready.scripts[0].src, '/app.js?v=workspace-1');
assert.equal(ready.context.AuraStudio.apiUrl('/api/sync-store?tenant=attacker'), '/api/sync-store?tenant=canonical');
assert.throws(() => ready.context.AuraStudio.apiUrl('https://attacker.fixture/api/x'));
ready.scripts[0].onload();
assert.deepEqual(ready.events, ['aura-studio-ready']);
assert.equal(ready.nodes.get('studioWorkspaceGate').hidden, true);
});
+3
View File
@@ -51,4 +51,7 @@ test('API failures stay JSON and service health is distinct from authenticated w
const unknown = await fetch(base + '/api/missing');
assert.equal(unknown.status, 404);
assert.match(unknown.headers.get('content-type'), /application\/json/);
const config = await fetch(base + '/api/studio-config');
assert.deepEqual(await config.json(), { loginUrl: null });
assert.match(config.headers.get('cache-control'), /no-store/);
});
+89
View File
@@ -0,0 +1,89 @@
(function (root) {
'use strict';
function scopedStorage(storage, clientId) {
if (!/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i.test(clientId || '')) throw new Error('Verified client identity required');
const prefix = 'aura-studio:' + clientId.toLowerCase() + ':';
return Object.freeze({
getItem(key) { return storage.getItem(prefix + key); },
setItem(key, value) { storage.setItem(prefix + key, value); },
removeItem(key) { storage.removeItem(prefix + key); }
});
}
function escapeText(value) {
return String(value ?? '').replace(/[&<>"']/g, char => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[char]));
}
if (typeof module === 'object' && module.exports) { module.exports = { scopedStorage, escapeText }; return; }
async function start() {
const gate = document.getElementById('studioWorkspaceGate');
const status = document.getElementById('workspaceStatus');
const form = document.getElementById('workspaceForm');
const tenantInput = document.getElementById('workspaceTenant');
const login = document.getElementById('workspaceLogin');
const retry = document.getElementById('workspaceRetry');
const params = new URLSearchParams(location.search);
const tenant = params.get('tenant') || '';
tenantInput.value = tenant;
document.querySelectorAll('body > :not(#studioWorkspaceGate):not(script)').forEach(el => el.inert = true);
retry.onclick = () => location.reload();
form.onsubmit = event => {
event.preventDefault();
const next = new URL(location.href);
next.searchParams.set('tenant', tenantInput.value.trim());
location.assign(next.href);
};
try {
const response = await fetch('/api/workspace' + (tenant ? '?tenant=' + encodeURIComponent(tenant) : ''), { credentials: 'same-origin', cache: 'no-store' });
const data = await response.json();
if (!response.ok || data.success !== true) {
status.textContent = data.error || 'Workspace যাচাই করা যায়নি।';
if (data.code === 'WORKSPACE_REQUIRED') form.hidden = false;
if (response.status === 401) {
const configResponse = await fetch('/api/studio-config', { cache: 'no-store' });
const config = await configResponse.json();
if (configResponse.ok && config.loginUrl) {
const target = new URL(config.loginUrl);
if (!['https:', 'http:'].includes(target.protocol) || target.username || target.password) throw new Error('Invalid login destination');
target.searchParams.set('next', location.href);
login.href = target.href; login.hidden = false;
}
}
return;
}
const workspace = data.workspace;
const runtime = {
workspace: Object.freeze({ ...workspace }),
local: scopedStorage(localStorage, workspace.clientId),
session: scopedStorage(sessionStorage, workspace.clientId),
escapeText,
apiUrl(path) {
const url = new URL(path, location.origin);
if (url.origin !== location.origin || !url.pathname.startsWith('/api/')) throw new Error('Invalid Studio API URL');
url.searchParams.set('tenant', workspace.tenant);
return url.pathname + url.search;
}
};
Object.defineProperty(window, 'AuraStudio', { value: Object.freeze(runtime), writable: false });
const script = document.createElement('script');
script.src = '/app.js?v=workspace-1';
script.onerror = () => { status.textContent = 'Studio load হয়নি। Refresh করে আবার চেষ্টা করুন।'; };
script.onload = () => {
try {
document.dispatchEvent(new Event('aura-studio-ready'));
document.querySelectorAll('body > :not(#studioWorkspaceGate):not(script)').forEach(el => el.inert = false);
gate.hidden = true;
const button = document.createElement('button');
button.type = 'button'; button.className = 'pill-btn';
button.textContent = workspace.name || workspace.tenant;
button.title = 'Workspace নির্বাচন';
button.onclick = () => { gate.hidden = false; form.hidden = false; status.textContent = 'অন্য workspace নির্বাচন করুন।'; };
document.querySelector('.header-actions')?.prepend(button);
} catch { status.textContent = 'Studio চালু হয়নি। Refresh করে আবার চেষ্টা করুন।'; }
};
document.body.appendChild(script);
} catch {
status.textContent = 'Workspace service-এর উত্তর পাওয়া যায়নি। Refresh করে আবার চেষ্টা করুন।';
}
}
document.addEventListener('DOMContentLoaded', start, { once: true });
})(typeof globalThis === 'object' ? globalThis : this);