Keep Studio business branding in verified client storage

This commit is contained in:
khondokartowsif171
2026-10-19 11:54:13 +06:00
parent 165320cc9f
commit 54091f4578
11 changed files with 151 additions and 38 deletions
+11 -2
View File
@@ -1,4 +1,5 @@
const { fail, requireProductWrite } = require('./workspace.cjs');
const { normalizeBrand } = require('./brand.cjs');
function sendJson(response, status, value) {
if (response.destroyed || response.writableEnded) return;
@@ -78,7 +79,7 @@ function createApiHandler({ resolveWorkspace, store, scrape, imageHandler, getCo
try {
const pathname = new URL(request.url, origin).pathname;
const routes = {
'/api/workspace': 'GET', '/api/catalog-image': 'GET',
'/api/workspace': 'GET', '/api/brand': 'POST', '/api/catalog-image': 'GET',
'/api/get-synced-stores': 'GET', '/api/sync-store': 'POST', '/api/delete-synced-store': 'POST'
};
if (!routes[pathname]) return sendJson(response, 404, { success: false, code: 'NOT_FOUND', error: 'API পাওয়া যায়নি।' });
@@ -86,7 +87,10 @@ function createApiHandler({ resolveWorkspace, store, scrape, imageHandler, getCo
if (request.method === 'POST') writeOrigin(request);
const workspace = await resolveWorkspace(request);
const publicWorkspace = { clientId: workspace.clientId, name: workspace.displayName, tenant: workspace.tenant, canWriteProducts: workspace.canWriteProducts };
if (pathname === '/api/workspace') return sendJson(response, 200, { success: true, workspace: publicWorkspace });
if (pathname === '/api/workspace') {
publicWorkspace.brand = normalizeBrand(await store.readBrand(workspace) || {}, workspace.displayName);
return sendJson(response, 200, { success: true, workspace: publicWorkspace });
}
if (pathname === '/api/catalog-image') {
if (!imageHandler) throw fail(503, 'IMAGE_UNAVAILABLE', 'Product image এখন পাওয়া যাচ্ছে না।');
return await imageHandler(request, response, workspace);
@@ -98,6 +102,11 @@ function createApiHandler({ resolveWorkspace, store, scrape, imageHandler, getCo
}
requireProductWrite(workspace);
const body = await readJson(request, maxBodyBytes);
if (pathname === '/api/brand') {
const brand = normalizeBrand(body, workspace.displayName);
await store.saveBrand(workspace, brand);
return sendJson(response, 200, { success: true, brand });
}
if (pathname === '/api/delete-synced-store') {
if (typeof body.storeId === 'string' && body.storeId.startsWith('connected:')) throw fail(403, 'CONNECTED_CATALOG_READ_ONLY', 'Connected catalog মূল Client dashboard থেকে পরিচালনা করুন।');
if (typeof body.storeId !== 'string' || !body.storeId || body.storeId.length > 160) throw fail(400, 'INVALID_STORE_ID', 'সঠিক store নির্বাচন করুন।');
+24
View File
@@ -0,0 +1,24 @@
const { fail } = require('./workspace.cjs');
function normalizeBrand(input, defaultName = '') {
if (!input || typeof input !== 'object' || Array.isArray(input)) throw fail(400, 'INVALID_BRAND', 'Business তথ্য সঠিক নয়।');
const text = (key, max) => {
if (input[key] !== undefined && typeof input[key] !== 'string') throw fail(400, 'INVALID_BRAND', 'Business তথ্য text হতে হবে।');
const value = (input[key] || '').trim();
if (value.length > max || /[\u0000-\u001f\u007f]/.test(value)) throw fail(400, 'INVALID_BRAND', 'Business তথ্য সঠিক নয়।');
return value;
};
const name = text('name', 256) || defaultName;
let website = text('website', 2048);
if (website) {
let url;
try { url = new URL(website); } catch { throw fail(400, 'INVALID_WEBSITE', 'সম্পূর্ণ http/https website URL দিন।'); }
if (!['https:', 'http:'].includes(url.protocol) || url.username || url.password || url.search || url.hash) throw fail(400, 'INVALID_WEBSITE', 'Website URL-এ password, query বা fragment ব্যবহার করবেন না।');
website = url.href.replace(/\/$/, '');
}
const phone = text('phone', 32).replace(/[\s().-]/g, '');
if (phone && !/^\+[1-9]\d{6,14}$/.test(phone)) throw fail(400, 'INVALID_PHONE', 'Country code সহ international WhatsApp নম্বর দিন, যেমন +880…।');
return { name, website, phone };
}
module.exports = { normalizeBrand };
+2 -3
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', 'workspace.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']);
function createStaticHandler(publicDirectory, { maxCacheBytes = 16 * 1024 * 1024 } = {}) {
const root = path.resolve(publicDirectory), cache = new Map();
@@ -20,8 +20,7 @@ function createStaticHandler(publicDirectory, { maxCacheBytes = 16 * 1024 * 1024
if (pathname.includes('\\') || pathname.includes('\0') || pathname.split('/').some(p => p.startsWith('.'))) return missing(response);
let relative = pathname === '/' ? 'index.html' : pathname.replace(/^\/+/, '');
const asset = relative.startsWith('assets/') && MIME[path.extname(relative).toLowerCase()];
const legacyData = relative === 'data/synced_stores.json';
if (!ROOT_FILES.has(relative) && !asset && !legacyData) {
if (!ROOT_FILES.has(relative) && !asset) {
if (!path.extname(relative) && !/^(?:server|docs|test|data|node_modules)(?:\/|$)/.test(relative) && String(request.headers.accept || '').includes('text/html')) relative = 'index.html';
else return missing(response);
}
+11 -8
View File
@@ -17,25 +17,26 @@ function createStore(rootDirectory) {
return dir;
}
async function read(workspace) {
async function read(workspace, kind = 'stores') {
if (!['stores', 'brand'].includes(kind)) throw new Error('Invalid storage kind');
const dir = await directory(workspace);
let text;
try { text = await fs.readFile(path.join(dir, 'stores.json'), 'utf8'); }
catch (error) { if (error.code === 'ENOENT') return []; throw error; }
try { text = await fs.readFile(path.join(dir, kind + '.json'), 'utf8'); }
catch (error) { if (error.code === 'ENOENT') return kind === 'stores' ? [] : null; throw error; }
const records = JSON.parse(text);
if (!Array.isArray(records)) throw new Error('Invalid saved store data');
if (kind === 'stores' ? !Array.isArray(records) : (!records || typeof records !== 'object' || Array.isArray(records))) throw new Error('Invalid saved workspace data');
return records;
}
async function update(workspace, change) {
async function update(workspace, change, kind = 'stores') {
const key = workspace.namespace;
const previous = queues.get(key) || Promise.resolve();
const task = previous.catch(() => {}).then(async () => {
const records = await read(workspace);
const records = await read(workspace, kind);
const next = change(records);
const dir = await directory(workspace);
const target = path.join(dir, 'stores.json');
const temporary = path.join(dir, '.stores-' + randomUUID() + '.tmp');
const target = path.join(dir, kind + '.json');
const temporary = path.join(dir, '.' + kind + '-' + randomUUID() + '.tmp');
let handle;
try {
handle = await fs.open(temporary, 'wx', 0o600);
@@ -61,6 +62,8 @@ function createStore(rootDirectory) {
return {
read,
readBrand(workspace) { return read(workspace, 'brand'); },
saveBrand(workspace, brand) { return update(workspace, () => brand, 'brand'); },
upsert(workspace, store) {
if (!store || typeof store.id !== 'string' || !store.id || store.id.length > 160 || !Array.isArray(store.products)) {
return Promise.reject(new Error('Invalid imported store'));