@nextblock-cms/cortex 0.13.1 → 0.13.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const w=require("ai"),Ft=require("./ai-global-agent-db-tools.cjs.js"),Nt=require("./ai-global-agent-custom-block-tools.cjs.js");require("./zod-config.cjs.js");const o=require("zod"),N=["text","heading","image","button","posts_grid","video_embed","section","form","testimonial","product_grid","featured_product","cart","checkout","product_details"],jt=1e4,qt={arabic:"ar",chinese:"zh",dutch:"nl",english:"en",french:"fr",francaise:"fr",francais:"fr",german:"de",italian:"it",japanese:"ja",korean:"ko",portuguese:"pt",russian:"ru",spanish:"es"},it=o.z.string().trim().min(1).max(2048).refine(e=>e.startsWith("/")||e.startsWith("#")||e.startsWith("http://")||e.startsWith("https://")||e.startsWith("mailto:")||e.startsWith("tel:"),"URL must be a relative path, hash link, http(s) URL, mailto URL, or tel URL."),He=o.z.strictObject({label:o.z.string().trim().min(1).max(120),target:o.z.enum(["_self","_blank"]).optional(),url:it}),ye=He.extend({children:o.z.array(He).max(20).optional()}),Ot=o.z.strictObject({label:o.z.string().trim().min(1).max(120).optional(),url:it.optional()}).refine(e=>!!(e.label||e.url),{message:"Navigation item match requires label or url."}),G=o.z.strictObject({items:o.z.array(ye).min(1).max(30),languageCode:o.z.string().trim().min(2).max(80).default("en").describe('Locale code or language name, for example "en", "fr", "English", or "French".'),match:Ot.optional().describe('For mode "update", identifies the existing navigation item to update.'),mode:o.z.enum(["append","replace","update"]).default("append")}),R=o.z.strictObject({copyright:o.z.record(o.z.string().trim().min(2).max(12),o.z.string().trim().min(1).max(500)).optional(),languageCode:o.z.string().trim().min(2).max(80).default("en").describe('Locale code or language name, for example "en", "fr", "English", or "French".'),links:o.z.array(ye).min(1).max(30).optional()}),de=o.z.strictObject({limit:o.z.number().int().min(1).max(8).default(4),query:o.z.string().trim().min(2).max(300)}),ke=o.z.object({currency:o.z.string().trim().min(3).max(3).optional().describe("Optional currency code for currency-specific monetary reports (e.g., USD, CAD). Do not set this for plain order-status counts unless the user asks for a currency."),query:o.z.string().describe("The analytical question about orders, products, or revenue."),reportType:o.z.enum(["revenue","orders","products","general"]).optional().default("general").describe("The focus area of the statistical report."),timeRange:o.z.enum(["today","this_month","last_7_days","last_30_days","last_month","last_90_days","all_time"]).optional().default("all_time").describe("The time period for the report. Use all_time for current order-status counts unless the user names a specific period.")}),we=o.z.strictObject({contentType:o.z.enum(["page","post","product"]),currentEditor:o.z.strictObject({blockId:o.z.union([o.z.number().int().positive(),o.z.string().trim().min(1).max(120)]).nullable().optional(),blockType:o.z.string().trim().min(1).max(80).nullable().optional(),field:o.z.string().trim().min(1).max(120).nullable().optional()}).optional(),entityId:o.z.union([o.z.number().int().positive(),o.z.string().trim().min(1).max(120)]),languageId:o.z.number().int().positive().nullable().optional(),slug:o.z.string().trim().min(1).max(300).nullable().optional(),title:o.z.string().trim().min(1).max(300).nullable().optional(),translationGroupId:o.z.string().trim().min(1).max(120).nullable().optional()}),ze=o.z.strictObject({includeBlockContent:o.z.boolean().default(!1),includeBlocks:o.z.boolean().default(!0)}),K=o.z.strictObject({fields:o.z.strictObject({description_json:o.z.unknown().optional(),excerpt:o.z.string().max(2e3).nullable().optional(),feature_image_id:o.z.string().trim().min(1).max(120).nullable().optional(),label:o.z.string().max(120).nullable().optional(),meta_description:o.z.string().max(500).nullable().optional(),meta_title:o.z.string().max(160).nullable().optional(),published_at:o.z.string().max(80).nullable().optional(),short_description:o.z.string().max(2e3).nullable().optional(),slug:o.z.string().trim().min(1).max(300).optional(),status:o.z.enum(["draft","published","active","archived"]).optional(),subtitle:o.z.string().max(300).nullable().optional(),title:o.z.string().trim().min(1).max(300).optional()}).partial()}),V=o.z.strictObject({blockId:o.z.number().int().positive(),blockType:o.z.enum(N).optional(),content:o.z.record(o.z.string(),o.z.unknown())}),J=o.z.strictObject({blockIndex:o.z.number().int().min(0),blockType:o.z.enum(N).optional(),columnIndex:o.z.number().int().min(0),content:o.z.record(o.z.string(),o.z.unknown()),parentBlockId:o.z.number().int().positive()}),Ut=o.z.enum(["page","post","product"]),pe=o.z.strictObject({contentType:Ut.optional(),entityId:o.z.union([o.z.number().int().positive(),o.z.string().trim().min(1).max(120)]).optional(),slug:o.z.string().trim().min(1).max(300).optional(),title:o.z.string().trim().min(1).max(300).optional()}),Ie=o.z.strictObject({blockType:o.z.enum(N),content:o.z.record(o.z.string(),o.z.unknown()),order:o.z.number().int().min(0).optional()}),W=pe.extend({anchorBlockId:o.z.number().int().positive().optional(),anchorBlockType:o.z.enum(N).optional(),block:Ie,position:o.z.enum(["before","after","start","end"]).default("end")}),H=o.z.strictObject({blocks:o.z.array(Ie).max(20).optional(),contactEmail:o.z.string().email().optional(),feature_image_id:o.z.string().trim().min(1).max(120).nullable().optional(),languageCode:o.z.string().trim().min(2).max(80).optional(),meta_description:o.z.string().max(500).nullable().optional(),meta_title:o.z.string().max(160).nullable().optional(),slug:o.z.string().trim().min(1).max(300).optional(),status:o.z.enum(["draft","published","archived"]).default("draft"),title:o.z.string().trim().min(1).max(300),translationGroupId:o.z.string().trim().min(1).max(120).optional()}),Y=o.z.strictObject({blocks:o.z.array(Ie).max(20).optional(),excerpt:o.z.string().max(2e3).nullable().optional(),feature_image_id:o.z.string().trim().min(1).max(120).nullable().optional(),label:o.z.string().max(120).nullable().optional(),languageCode:o.z.string().trim().min(2).max(80).optional(),meta_description:o.z.string().max(500).nullable().optional(),meta_title:o.z.string().max(160).nullable().optional(),published_at:o.z.string().max(80).nullable().optional(),slug:o.z.string().trim().min(1).max(300).optional(),status:o.z.enum(["draft","published","archived"]).default("draft"),subtitle:o.z.string().max(300).nullable().optional(),title:o.z.string().trim().min(1).max(300),translationGroupId:o.z.string().trim().min(1).max(120).optional()}),Q=o.z.strictObject({description_json:o.z.unknown().optional(),freemius_plan_id:o.z.string().optional(),freemius_product_id:o.z.string().optional(),is_taxable:o.z.boolean().default(!0),languageCode:o.z.string().trim().min(2).max(80).optional(),meta_description:o.z.string().max(500).nullable().optional(),meta_title:o.z.string().max(160).nullable().optional(),payment_provider:o.z.enum(["stripe","freemius"]).default("stripe"),price:o.z.number().min(0).default(0),prices:o.z.record(o.z.string(),o.z.number().min(0)).optional(),product_type:o.z.enum(["physical","digital"]).default("physical"),sale_price:o.z.number().min(0).nullable().optional(),sale_prices:o.z.record(o.z.string(),o.z.number().min(0).nullable()).optional(),short_description:o.z.string().max(2e3).nullable().optional(),sku:o.z.string().trim().min(1).max(120).optional(),slug:o.z.string().trim().min(1).max(300).optional(),status:o.z.enum(["draft","active","archived"]).default("draft"),stock:o.z.number().int().min(0).default(0),title:o.z.string().trim().min(1).max(300),trial_period_days:o.z.number().int().min(0).default(0),trial_requires_payment_method:o.z.boolean().default(!1),translationGroupId:o.z.string().trim().min(1).max(120).optional(),upc:o.z.string().max(120).nullable().optional()}),X=pe.extend({currencyCode:o.z.string().trim().min(3).max(3).optional(),endsAt:o.z.string().max(80).nullable().optional(),field:o.z.string().trim().min(1).max(120),startsAt:o.z.string().max(80).nullable().optional(),value:o.z.unknown()}),Ce=pe,Z=pe,at=o.z.discriminatedUnion("tool",[o.z.strictObject({input:H,tool:o.z.literal("create_cms_page")}),o.z.strictObject({input:Y,tool:o.z.literal("create_cms_post")}),o.z.strictObject({input:Q,tool:o.z.literal("create_cms_product")}),o.z.strictObject({input:Z,tool:o.z.literal("delete_cms_item")}),o.z.strictObject({input:X,tool:o.z.literal("update_cms_item_field")}),o.z.strictObject({input:V,tool:o.z.literal("update_content_block")}),o.z.strictObject({input:W,tool:o.z.literal("insert_content_block")}),o.z.strictObject({input:K,tool:o.z.literal("update_current_cms_fields")}),o.z.strictObject({input:R,tool:o.z.literal("update_footer")}),o.z.strictObject({input:G,tool:o.z.literal("update_navigation_bar")}),o.z.strictObject({input:J,tool:o.z.literal("update_section_column_block")})]),Dt=o.z.union([H.extend({tool:o.z.literal("create_cms_page")}).transform(({tool:e,...n})=>({input:n,tool:e})),Y.extend({tool:o.z.literal("create_cms_post")}).transform(({tool:e,...n})=>({input:n,tool:e})),Q.extend({tool:o.z.literal("create_cms_product")}).transform(({tool:e,...n})=>({input:n,tool:e})),Z.extend({tool:o.z.literal("delete_cms_item")}).transform(({tool:e,...n})=>({input:n,tool:e})),X.extend({tool:o.z.literal("update_cms_item_field")}).transform(({tool:e,...n})=>({input:n,tool:e})),V.extend({tool:o.z.literal("update_content_block")}).transform(({tool:e,...n})=>({input:n,tool:e})),W.extend({tool:o.z.literal("insert_content_block")}).transform(({tool:e,...n})=>({input:n,tool:e})),K.extend({tool:o.z.literal("update_current_cms_fields")}).transform(({tool:e,...n})=>({input:n,tool:e})),R.extend({tool:o.z.literal("update_footer")}).transform(({tool:e,...n})=>({input:n,tool:e})),G.extend({tool:o.z.literal("update_navigation_bar")}).transform(({tool:e,...n})=>({input:n,tool:e})),J.extend({tool:o.z.literal("update_section_column_block")}).transform(({tool:e,...n})=>({input:n,tool:e}))]),Mt=o.z.string().transform((e,n)=>{const t=Vt(e);return t.success?t.action:(n.addIssue({code:"custom",message:t.message}),o.z.NEVER)}),Lt=o.z.union([at,Dt,Mt]),xe=o.z.strictObject({actions:o.z.array(Lt).min(1).max(8),summary:o.z.string().trim().min(1).max(500).optional()});function Gt(e){const n=[];let t="",r=0,i=null,a=!1;for(const s of e){if(i){t+=s,a?a=!1:s==="\\"?a=!0:s===i&&(i=null);continue}if(s==='"'||s==="'"){i=s,t+=s;continue}if(s==="["||s==="{"||s==="("){r++,t+=s;continue}if(s==="]"||s==="}"||s===")"){r=Math.max(0,r-1),t+=s;continue}if(s===","&&r===0){t.trim()&&n.push(t.trim()),t="";continue}t+=s}return t.trim()&&n.push(t.trim()),n}function Ye(e){let n="";for(let t=0;t<e.length;t++){const r=e[t];if(r!=="'"){n+=r;continue}let i="",a=!1;for(t++;t<e.length;t++){const s=e[t];if(a){i+=s,a=!1;continue}if(s==="\\"){a=!0;continue}if(s==="'")break;i+=s}n+=JSON.stringify(i)}return n.replace(/\bTrue\b/g,"true").replace(/\bFalse\b/g,"false").replace(/\bNone\b/g,"null")}function Rt(e){const n=e.trim();return n.startsWith("'")&&n.endsWith("'")||n.startsWith('"')&&n.endsWith('"')||n.startsWith("[")||n.startsWith("{")?JSON.parse(Ye(n)):/^-?\d+(?:\.\d+)?$/.test(n)?Number(n):n==="true"||n==="True"?!0:n==="false"||n==="False"?!1:n==="null"||n==="None"?null:n}function Kt(e){const n={};for(const t of Gt(e)){const r=t.indexOf("=");if(r<=0)throw new Error(`Expected key=value argument, received "${t}".`);const i=t.slice(0,r).trim();if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(i))throw new Error(`Invalid argument name "${i}".`);n[i]=Rt(t.slice(r+1))}return n}function Vt(e){const t=e.trim().match(/^([a-z_]+)\(([\s\S]*)\)$/);if(!t)return{message:'Action plan actions must be JSON objects like { "tool": "create_cms_page", "input": { ... } }, not freeform text.',success:!1};const r=t[1];let i;try{i=Kt(t[2])}catch(l){return{message:l instanceof Error?l.message:"Could not parse action-plan command arguments.",success:!1}}const a={input:i,tool:r},s=at.safeParse(a);return s.success?{action:s.data,success:!0}:{message:`Invalid action-plan command "${r}": ${s.error.issues.map(l=>l.message).join("; ")}`,success:!1}}function Jt(e){return e.normalize("NFD").replace(/[\u0300-\u036f]/g,"").toLowerCase().replace(/\s+/g," ").trim()}function oe(e,n){return n.some(t=>e.includes(t))}function Wt(e){const n=Jt(e),t=oe(n,["add ","insert ","put ","create "]),r=oe(n,["title","heading","description","intro","copy","paragraph"]),i=n.includes("form")&&oe(n,["above","before"]),a=n.includes("contact page")||n.includes("contact pages")||n.includes("contact us")||n.includes("contactez-nous"),s=n.includes("english")&&oe(n,["french","francais","francaise"]);return!t||!r||!i||!a||!s?null:{actions:[{input:{anchorBlockType:"form",block:{blockType:"text",content:{html_content:"<h2>Let us help you move faster</h2><p>Have a question, project idea, or need help choosing the right next step? Send us a message and the NextBlock team will get back to you soon.</p>"}},contentType:"page",position:"before",slug:"contact-us"},tool:"insert_content_block"},{input:{anchorBlockType:"form",block:{blockType:"text",content:{html_content:"<h2>Parlons de votre projet</h2><p>Vous avez une question, une idee de projet ou besoin d'aide pour avancer? Envoyez-nous un message et l'equipe NextBlock vous repondra rapidement.</p>"}},contentType:"page",position:"before",slug:"contactez-nous"},tool:"insert_content_block"}],summary:"Add visible title and description copy above the forms on the English and French Contact pages."}}const Ht=o.z.enum(N),Qe=o.z.object({direction:o.z.string().optional(),stops:o.z.array(o.z.object({color:o.z.string(),position:o.z.number()})),type:o.z.enum(["linear","radial"])}),Yt=o.z.object({gradient:Qe.optional(),image:o.z.object({alt_text:o.z.string().optional(),blur_data_url:o.z.string().optional(),height:o.z.number().optional(),media_id:o.z.string(),object_key:o.z.string(),overlay:o.z.object({gradient:Qe,type:o.z.literal("gradient")}).optional(),position:o.z.enum(["center","top","bottom","left","right"]),quality:o.z.number().nullable().optional(),size:o.z.enum(["cover","contain"]),width:o.z.number().optional()}).optional(),min_height:o.z.string().optional(),solid_color:o.z.string().optional(),theme:o.z.enum(["primary","secondary","muted","accent","destructive"]).optional(),type:o.z.enum(["none","theme","solid","gradient","image"])}),Qt=o.z.object({block_type:Ht,content:o.z.record(o.z.string(),o.z.any()),temp_id:o.z.string().optional()}),Xt=o.z.object({background:Yt,column_blocks:o.z.array(o.z.array(Qt)),column_gap:o.z.enum(["none","sm","md","lg","xl"]),container_type:o.z.enum(["full-width","container","container-sm","container-lg","container-xl"]),padding:o.z.object({bottom:o.z.enum(["none","sm","md","lg","xl"]),top:o.z.enum(["none","sm","md","lg","xl"])}),responsive_columns:o.z.object({desktop:o.z.union([o.z.literal(1),o.z.literal(2),o.z.literal(3),o.z.literal(4)]),mobile:o.z.union([o.z.literal(1),o.z.literal(2)]),tablet:o.z.union([o.z.literal(1),o.z.literal(2),o.z.literal(3)])}),vertical_alignment:o.z.enum(["start","center","end","stretch"]).optional()}),Zt={button:o.z.object({position:o.z.enum(["left","center","right"]).optional(),size:o.z.enum(["default","sm","lg","full"]).optional(),text:o.z.string(),url:o.z.string(),variant:o.z.enum(["default","outline","secondary","ghost","link"]).optional()}),cart:o.z.object({}),checkout:o.z.object({}),featured_product:o.z.object({imagePosition:o.z.enum(["left","right"]).default("left"),productId:o.z.string().min(1),showBackground:o.z.boolean().default(!1)}),form:o.z.object({fields:o.z.array(o.z.object({field_type:o.z.enum(["text","email","textarea","select","radio","checkbox"]),is_required:o.z.boolean(),label:o.z.string(),options:o.z.array(o.z.object({label:o.z.string(),value:o.z.string()})).optional(),placeholder:o.z.string().optional(),temp_id:o.z.string()})),recipient_email:o.z.string().email(),submit_button_text:o.z.string(),success_message:o.z.string()}),heading:o.z.object({level:o.z.union([o.z.literal(1),o.z.literal(2),o.z.literal(3),o.z.literal(4),o.z.literal(5),o.z.literal(6)]),textAlign:o.z.enum(["left","center","right","justify"]).optional(),textColor:o.z.enum(["primary","secondary","accent","muted","destructive","background"]).optional(),text_content:o.z.string()}),image:o.z.object({alt_text:o.z.string().optional(),caption:o.z.string().optional(),height:o.z.number().nullable().optional(),media_id:o.z.string().nullable(),object_key:o.z.string().nullable().optional(),width:o.z.number().nullable().optional()}),posts_grid:o.z.object({columns:o.z.number().min(1).max(6),postsPerPage:o.z.number().min(1).max(50),showPagination:o.z.boolean(),title:o.z.string().optional()}),product_details:o.z.object({}),product_grid:o.z.object({categoryId:o.z.string().optional(),limit:o.z.number().min(1).max(20).default(6),title:o.z.string().optional(),type:o.z.enum(["latest","category"]).default("latest")}),section:Xt,testimonial:o.z.object({author_name:o.z.string().min(1),author_title:o.z.string().optional(),image_url:o.z.string().url().optional().or(o.z.literal("")),quote:o.z.string().min(1)}),text:o.z.object({html_content:o.z.string()}),video_embed:o.z.object({autoplay:o.z.boolean().optional(),controls:o.z.boolean().optional(),title:o.z.string().optional(),url:o.z.string()})};function en(e){return N.includes(e)}function tn(e){return typeof e?.validateBlockContent=="function"?e.validateBlockContent:null}function nn(e,n,t){const r=tn(t);if(r)return r(e,n);const i=Zt[e].safeParse(n);return i.success?{errors:[],isValid:!0,warnings:[]}:{errors:i.error.issues.map(a=>{const s=a.path.join(".");return s?`${s}: ${a.message}`:a.message}),isValid:!1,warnings:[]}}function on(){return o.z.object({content:o.z.array(o.z.any()).optional(),type:o.z.literal("doc")})}function Te(){try{const{revalidatePath:e}=require("next/cache");return e}catch{return null}}function y(e){if(!e?.supabase)throw new Error("A Supabase service client is required to execute Cortex AI global tools.");return e.supabase}function rn(e,n,t){let r;const i=new Promise(a=>{r=setTimeout(()=>a(t()),n)});return Promise.race([e.finally(()=>{r&&clearTimeout(r)}),i])}function me(e){const n=we.safeParse(e?.pageContext);if(!n.success)throw new Error("No current CMS page context is available. Open a page, post, or product edit screen before using this editing tool.");return n.data}function st(e){const n=typeof e.entityId=="number"?e.entityId:Number.parseInt(e.entityId,10);if(!Number.isInteger(n)||n<=0)throw new Error(`Current ${e.contentType} id must be a positive integer.`);return n}function an(e){const n=String(e.entityId||"").trim();if(!n)throw new Error(`Current ${e.contentType} id is missing.`);return n}function $e(e){return e.contentType==="product"?an(e):st(e)}function sn(e){return typeof e=="string"?e.trim().replace(/^\/+|\/+$/g,""):""}function ln(e,n){const t=sn(n??e.slug);return t?e.contentType==="page"?t==="home"?"/":`/${t}`:e.contentType==="post"?`/article/${t}`:`/product/${t}`:null}function cn(e){const n=String(e.entityId);return e.contentType==="page"?`/cms/pages/${n}/edit`:e.contentType==="post"?`/cms/posts/${n}/edit`:`/cms/products/${n}/edit`}function B(e,n,t){const r=e?.revalidatePath??Te();if(!r)return;r(cn(n));const i=ln(n,t);i&&r(i),n.contentType==="product"&&r("/cms/products")}function lt(e){const n=e?.revalidatePath??Te();n&&(n("/","layout"),n("/cms/navigation"))}function f(e){return e?typeof e=="object"&&"message"in e?String(e.message||"Unknown database error."):String(e):"Unknown database error."}async function ve(){return Promise.resolve().then(()=>require("./ai-global-agent-ecommerce.cjs.js"))}function fe(e){return e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?`[${e.map(n=>fe(n)).join(",")}]`:`{${Object.keys(e).filter(n=>n!=="temp_id").sort().map(n=>`${JSON.stringify(n)}:${fe(e[n])}`).join(",")}}`}function un(e){let n=2166136261;const t=fe(e);for(let r=0;r<t.length;r++)n^=t.charCodeAt(r),n=Math.imul(n,16777619);return(n>>>0).toString(16).padStart(8,"0")}function _e(e){return e.replace(/\s+/g," ").trim().toUpperCase()}function dn(e,n,t){return`${_e(`CONFIRM ${e} ${n}`)} #${un(t)}`}function ct(e){return{confirmationPhrase:dn(e.action,e.subject,e.payload),mutationExecuted:!1,preview:e.preview,requiresConfirmation:!0,success:!0}}function $(e,n){const t=e[n];return typeof t=="string"&&t.trim()?t.trim():null}function re(e,n){const t=Number(e[n]);return Number.isFinite(t)?t:null}function F(e,n,t=`${n}s`){return`${e} ${e===1?n:t}`}function pn(e,n){const t=$(n,"summary");if(t)return t;const r=$(n,"title"),i=$(n,"slug"),a=$(n,"status"),s=$(n,"contentType"),l=$(n,"field"),m=$(n,"mode"),u=$(n,"languageCode"),c=re(n,"blockCount"),d=re(n,"itemCount"),g=re(n,"affectedCount");if(e==="create_cms_page"||e==="create_cms_post")return`Create ${a||"draft"} ${e==="create_cms_page"?"page":"post"} "${r||i||"Untitled"}"${i?` at slug "${i}"`:""}${c!==null?` with ${F(c,"content block")}`:""}.`;if(e==="create_cms_product")return`Create ${a||"draft"} product "${r||i||"Untitled"}"${i?` at slug "${i}"`:""}.`;if(e==="update_cms_item_field")return`Update ${l||"one field"} on the ${s||"CMS item"} "${r||i||"selected item"}".`;if(e==="update_navigation_bar")return`${m==="append"?"Add":m==="update"?"Update":"Replace"} ${d!==null?F(d,"navigation item"):"navigation items"} in the ${u||"selected"} header navigation.`;if(e==="update_footer"){const p=re(n,"linkCount");return`Update the ${u||"selected"} footer${p!==null?` with ${F(p,"link")}`:""}.`}return e==="update_content_block"?`Update the selected ${$(n,"blockType")||"content"} block.`:e==="insert_content_block"?`Insert ${$(n,"blockType")||"content"} block on the ${s||"CMS item"} "${r||i||"selected item"}".`:e==="update_section_column_block"?`Update the selected nested ${$(n,"nestedBlockType")||"section"} block.`:e==="delete_cms_item"||e==="prepare_delete_cms_item"?`Delete ${g!==null?F(g,s||"CMS item"):`the selected ${s||"CMS item"}`}${r||i?` for "${r||i}"`:""}.`:"Complete the requested CMS change."}function x(e){if(e.context?.skipConfirmation)return null;const n=ct(e),t=_e(e.context?.latestUserMessage||""),r=_e(n.confirmationPhrase);return t.includes(r)?null:n}function ut(e){const n=e?.actorUserId;if(!n)throw new Error("A confirmed CMS mutation requires an authenticated admin actor.");return n}function Se(){return globalThis.crypto?.randomUUID?.()||`id-${Date.now()}-${Math.random().toString(36).slice(2)}`}function ge(e){return e.toLowerCase().trim().replace(/\s+/g,"-").replace(/[^a-z0-9-]/g,"").replace(/-+/g,"-").replace(/^-|-$/g,"").slice(0,300)}function Ee(e){return(e||"USD").trim().toUpperCase()}function Ae(e,n){const r=new Set(["BIF","CLP","DJF","GNF","JPY","KMF","KRW","MGA","PYG","RWF","UGX","VND","VUV","XAF","XOF","XPF"]).has(Ee(n))?0:2;return e/10**r}function mn(e,n){return typeof e=="number"&&Number.isFinite(e)?Ae(e,n):0}function Xe(e,n){return!e||typeof e!="object"||Array.isArray(e)?{}:Object.entries(e).reduce((t,[r,i])=>(typeof i=="number"&&Number.isFinite(i)&&(t[Ee(r||n)]=Ae(i,r||n)),t),{})}function ee(e,n){if(!L(e))throw new Error(`${n} content must be a JSON object.`);return JSON.parse(JSON.stringify(e))}function ae(e){return JSON.parse(JSON.stringify(e))}function L(e){return!!(e&&typeof e=="object"&&!Array.isArray(e))}function be(e,n){const t=ae(e);for(const[r,i]of Object.entries(n))if(i!==void 0){if(L(i)&&L(t[r])){t[r]=be(t[r],i);continue}t[r]=ae(i)}return t}function dt(e,n){if(n.contentType==="product")throw new Error("Products do not have page/post content blocks in this editor context.");const t=st(n);if((n.contentType==="page"?Number(e.page_id):Number(e.post_id))!==t)throw new Error(`Block ${e.id} does not belong to the current ${n.contentType} being edited.`)}function se(e,n){const t=typeof e=="string"?e:"";if(!en(t))throw new Error(`${n} has unsupported block type "${t||"unknown"}".`);return t}function pt(e,n,t){if(e&&e!==n)throw new Error(`${t} is a "${n}" block. Refusing to update it as "${e}".`)}function j(e,n,t,r){const i=nn(e,n,r);if(!i.isValid)throw new Error(`${t} content is invalid for block type "${e}": ${i.errors.join("; ")}`)}function mt(e){return e==="section"}function gn(e){return typeof e.html_content=="string"?"text":typeof e.text=="string"&&typeof e.url=="string"?"button":typeof e.text_content=="string"?"heading":"media_id"in e||"object_key"in e?"image":typeof e.quote=="string"&&typeof e.author_name=="string"?"testimonial":typeof e.url=="string"&&("controls"in e||"autoplay"in e||"title"in e)?"video_embed":Array.isArray(e.fields)||typeof e.recipient_email=="string"?"form":"postsPerPage"in e||"showPagination"in e?"posts_grid":typeof e.productId=="string"?"featured_product":"limit"in e&&"type"in e?"product_grid":null}function le(e){return`ai-${e}-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}function Ze(e,n,t){if(!L(e))throw new Error(`${n} must be a JSON object.`);const r=e.block_type??e.blockType,i=se(r,n);if(mt(i))throw new Error(`${n} cannot be a nested ${i} block.`);const a=bt(i,ee(e.content,n),n,t),s=e.temp_id??e.tempId,l=typeof s=="string"&&s.trim()?s:le(i);return{block_type:i,content:a,temp_id:l}}function fn(e,n){const t=[];if("append_block"in e&&t.push(Ze(e.append_block,"Nested block to append",n)),"append_blocks"in e){const r=e.append_blocks;if(!Array.isArray(r))throw new Error("append_blocks must be an array of nested block objects.");r.forEach((i,a)=>{t.push(Ze(i,`Nested block to append ${a}`,n))})}return t}function _n(e,n){if("append_block"in e||"append_blocks"in e||"background"in e||"column_blocks"in e||"column_gap"in e||"container_type"in e||"padding"in e||"responsive_columns"in e||"vertical_alignment"in e)return null;const t=gn(e);if(!t)return null;const r=ee(e,`Nested ${t} block`);return j(t,r,`Nested ${t} block`,n),{block_type:t,content:r,temp_id:le(t)}}function bn(e,n){const t=e.append_column_index??e.column_index;if(t===void 0)return 0;if(typeof t!="number"||!Number.isInteger(t)||t<0)throw new Error("append_column_index must be a non-negative integer.");if(n>0&&t>=n)throw new Error(`append_column_index ${t} is outside the existing ${n} column(s).`);return t}function hn(e,n,t,r){if(!mt(e))return be(n,t);const i={...t},a=fn(i,r),s=_n(i,r);s&&a.push(s),delete i.append_block,delete i.append_blocks,delete i.append_column_index,delete i.column_index;const l=be(n,i);if(a.length>0){const m=Array.isArray(n.column_blocks)?ae(n.column_blocks):[],u=bn(t,m.length),c=m.length>0?m:[[]];for(;c.length<=u;)c.push([]);c[u]=[...c[u]||[],...a],l.column_blocks=c}return l}function yn(e,n){return{blockType:e.block_type,content:n?e.content:void 0,id:e.id,languageId:e.language_id,order:e.order,pageId:e.page_id,postId:e.post_id}}function q(e){return typeof e=="string"?e.trim().toLowerCase():""}function et(e){return typeof e=="string"?e.trim().toLowerCase():""}function gt(e){return e.reduce((n,t)=>n+1+(t.children?.length||0),0)}function ie(e){return typeof e=="string"?e.trim().toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g,""):""}async function O(e,n){const t=n.trim(),r=ie(t),i=qt[r],{data:a,error:s}=await e.from("languages").select("id, code, name, is_active");if(s)throw new Error(`Failed to load language "${n}": ${f(s)}`);const m=(Array.isArray(a)?a:[]).filter(c=>c.is_active!==!1),u=m.find(c=>{const d=ie(c.code),g=ie(c.name);return d===r||d===i||g===r});if(!u?.id||!u?.code){const c=m.map(d=>d.code).filter(Boolean).join(", ");throw new Error(`Language "${n}" was not found.${c?` Available languages: ${c}.`:""}`)}return{code:String(u.code),id:Number(u.id)}}async function Pe(e,n){if(n)return O(e,n);const{data:t,error:r}=await e.from("languages").select("id, code, name, is_active, is_default");if(r)throw new Error(`Failed to load active languages: ${f(r)}`);const i=(Array.isArray(t)?t:[]).filter(s=>s.is_active!==!1),a=i.find(s=>s.is_default)||i.find(s=>ie(s.code)==="en")||i[0];if(!a?.id||!a?.code)throw new Error("No active CMS language is available for Cortex AI content creation.");return{code:String(a.code),id:Number(a.id)}}async function kn(e){try{const{data:n,error:t}=await e.from("currencies").select("code, is_default, is_active").eq("is_active",!0);if(t)return"USD";const r=Array.isArray(n)?n:[],i=r.find(a=>a.is_default)||r[0];return Ee(i?.code||"USD")}catch{return"USD"}}async function wn(e){const n=e.contentType==="page"?"pages":e.contentType==="post"?"posts":"products";let t="id",r=e.entityId;if(r===void 0&&e.slug&&(t="slug",r=e.slug),r===void 0&&e.title&&(t="title",r=e.title),r===void 0)throw new Error(`A ${e.contentType} target requires an id, slug, title, or current edit context.`);const{data:i,error:a}=await e.supabase.from(n).select("*").eq(t,r);if(a)throw new Error(`Failed to resolve ${e.contentType}: ${f(a)}`);const s=Array.isArray(i)?i:i?[i]:[];if(s.length!==1)throw new Error(s.length===0?`No ${e.contentType} matched ${t} "${String(r)}".`:`Multiple ${e.contentType}s matched ${t} "${String(r)}"; use an exact id.`);return s[0]}async function Be(e,n){const t=we.safeParse(n?.pageContext).success?n?.pageContext:null,r=e.contentType||t?.contentType;if(!r)throw new Error("Target contentType is required when no current CMS edit context exists.");const i=e.entityId!==void 0||!!e.slug||!!e.title,a=e.entityId??(i?void 0:t?.entityId),s=e.slug??(i?void 0:t?.slug??void 0),l=e.title??(i?void 0:t?.title??void 0),m=await wn({contentType:r,entityId:a,slug:a===void 0&&s||void 0,supabase:y(n),title:a===void 0&&!s&&l||void 0});return{contentType:r,item:m}}async function ce(e){const n=await In({item:e.item,languageId:e.languageId,menuKey:e.menuKey,supabase:e.supabase}),t={label:e.item.label,language_id:e.languageId,menu_key:e.menuKey,order:e.order,page_id:n?.pageId??null,parent_id:e.parentId??null,...n?.navigationTranslationGroupId?{translation_group_id:n.navigationTranslationGroupId}:{},url:e.item.url},{data:r,error:i}=await e.supabase.from("navigation_items").insert(t).select("id").single();if(i)throw new Error(`Failed to insert ${e.menuKey} navigation item: ${f(i)}`);return Number(r.id)}function zn(e){const n=e.trim();if(!n.startsWith("/")||n.startsWith("//"))return null;const t=n.split("?")[0]?.split("#")[0]||"",r=t==="/"?"home":t.replace(/^\/+|\/+$/g,"");return r&&!r.includes("/")?r:null}async function In(e){const n=zn(e.item.url);if(!n)return null;const{data:t,error:r}=await e.supabase.from("pages").select("id, slug, translation_group_id, language_id").eq("slug",n).eq("language_id",e.languageId);if(r)throw new Error(`Failed to resolve linked page for navigation item: ${f(r)}`);const i=Array.isArray(t)?t[0]:t;if(!i?.id)return null;let a=Se();if(i.translation_group_id){const{data:s,error:l}=await e.supabase.from("pages").select("id").eq("translation_group_id",i.translation_group_id);if(l)throw new Error(`Failed to inspect linked page translations for navigation item: ${f(l)}`);const m=new Set((Array.isArray(s)?s:[]).map(g=>String(g.id)).filter(Boolean)),{data:u,error:c}=await e.supabase.from("navigation_items").select("id, page_id, translation_group_id, menu_key").eq("menu_key",e.menuKey);if(c)throw new Error(`Failed to inspect related navigation translations: ${f(c)}`);const d=(Array.isArray(u)?u:[]).find(g=>g.translation_group_id&&m.has(String(g.page_id)));d?.translation_group_id&&(a=d.translation_group_id)}return{navigationTranslationGroupId:a,pageId:Number(i.id)}}async function ft(e){const n=await O(e.supabase,e.languageCode),{data:t,error:r}=await e.supabase.from("navigation_items").select("id, parent_id").eq("menu_key",e.menuKey).eq("language_id",n.id);if(r)throw new Error(`Failed to inspect existing ${e.menuKey} navigation items: ${f(r)}`);const i=Array.isArray(t)?t:[],a=i.filter(u=>u.parent_id==null).length,s=gt(e.items);_t({existingItemCount:i.length,existingTopLevelCount:a,languageCode:n.code,menuKey:e.menuKey,replacementItemCount:s});const{error:l}=await e.supabase.from("navigation_items").delete().eq("menu_key",e.menuKey).eq("language_id",n.id);if(l)throw new Error(`Failed to clear ${e.menuKey} navigation items: ${f(l)}`);let m=0;for(const[u,c]of e.items.entries()){const d=await ce({item:c,languageId:n.id,menuKey:e.menuKey,order:u,supabase:e.supabase});m++;for(const[g,p]of(c.children??[]).entries())await ce({item:p,languageId:n.id,menuKey:e.menuKey,order:g,parentId:d,supabase:e.supabase}),m++}return{insertedCount:m,languageCode:n.code,menuKey:e.menuKey,skippedCount:0,updatedCount:0}}function _t(e){if(!(e.existingItemCount===0||e.replacementItemCount>=e.existingItemCount))throw new Error(`Refusing destructive ${e.menuKey} navigation replacement for ${e.languageCode}: existing menu has ${e.existingItemCount} items (${e.existingTopLevelCount} top-level), but the replacement only contains ${e.replacementItemCount}. Use mode "update" for renaming or changing a single link, or provide the full menu.`)}async function Cn(e){const n=await O(e.supabase,e.languageCode),{data:t,error:r}=await e.supabase.from("navigation_items").select("id, parent_id").eq("menu_key",e.menuKey).eq("language_id",n.id);if(r)throw new Error(`Failed to inspect existing ${e.menuKey} navigation items: ${f(r)}`);const i=Array.isArray(t)?t:[];_t({existingItemCount:i.length,existingTopLevelCount:i.filter(a=>a.parent_id==null).length,languageCode:n.code,menuKey:e.menuKey,replacementItemCount:gt(e.items)})}async function xn(e){if(e.items.length!==1)throw new Error('mode "update" requires exactly one navigation item.');const n=await O(e.supabase,e.languageCode),t=e.items[0],r=q(e.match?.url)||q(t.url),i=et(e.match?.label),{data:a,error:s}=await e.supabase.from("navigation_items").select("id, label, url, parent_id, order").eq("menu_key",e.menuKey).eq("language_id",n.id);if(s)throw new Error(`Failed to load existing ${e.menuKey} navigation items: ${f(s)}`);const m=(Array.isArray(a)?a:[]).find(c=>{const d=q(c.url),g=et(c.label);return!!(r&&d===r||i&&g===i)});if(!m?.id)throw new Error(`Could not find a ${e.menuKey} navigation item to update in ${n.code}. Use a matching label or url.`);const{error:u}=await e.supabase.from("navigation_items").update({label:t.label,url:t.url}).eq("id",m.id);if(u)throw new Error(`Failed to update ${e.menuKey} navigation item: ${f(u)}`);return{insertedCount:0,languageCode:n.code,menuKey:e.menuKey,skippedCount:0,updatedCount:1}}async function Tn(e){const n=await O(e.supabase,e.languageCode),{data:t,error:r}=await e.supabase.from("navigation_items").select("id, url, parent_id, order").eq("menu_key",e.menuKey).eq("language_id",n.id);if(r)throw new Error(`Failed to load existing ${e.menuKey} navigation items: ${f(r)}`);let i=0,a=0;const s=Array.isArray(t)?t:[],l=new Set(s.map(c=>q(c.url)).filter(Boolean)),m=s.filter(c=>c.parent_id==null).map(c=>Number(c.order)).filter(Number.isFinite);let u=m.length>0?Math.max(...m)+1:s.length;for(const c of e.items){const d=q(c.url);if(d&&l.has(d)){a++;continue}const g=await ce({item:c,languageId:n.id,menuKey:e.menuKey,order:u,supabase:e.supabase});i++,u++,d&&l.add(d);let p=0;for(const _ of c.children??[]){const k=q(_.url);if(k&&l.has(k)){a++;continue}await ce({item:_,languageId:n.id,menuKey:e.menuKey,order:p,parentId:g,supabase:e.supabase}),i++,p++,k&&l.add(k)}}return{insertedCount:i,languageCode:n.code,menuKey:e.menuKey,skippedCount:a,updatedCount:0}}function b(e){return typeof e=="string"&&e.trim()?e.trim():""}function $n(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function vn(e){const n=b(e.field_type??e.fieldType??e.type??e.input_type).toLowerCase().replace(/\s+/g,"_"),t=b(e.label??e.name??e.placeholder).toLowerCase();return["email","textarea","select","radio","checkbox","text"].includes(n)?n:t.includes("email")?"email":t.includes("message")||t.includes("comment")||t.includes("details")?"textarea":"text"}function Sn(e){return(Array.isArray(e)&&e.length>0?e:[{field_type:"text",is_required:!0,label:"Name",placeholder:"Your name"},{field_type:"email",is_required:!0,label:"Email",placeholder:"you@example.com"},{field_type:"textarea",is_required:!0,label:"Message",placeholder:"How can we help?"}]).map((t,r)=>{const i=L(t)?t:{},a=b(i.label??i.name)||(r===0?"Name":r===1?"Email":"Message"),s=vn({...i,label:a}),l=i.is_required??i.isRequired??i.required;return{field_type:s,is_required:typeof l=="boolean"?l:!0,label:a,options:Array.isArray(i.options)?i.options:void 0,placeholder:b(i.placeholder)||void 0,temp_id:b(i.temp_id??i.tempId??i.id)||`field-${r+1}`}})}function bt(e,n,t,r){const i=ae(n);if(e==="heading"&&(i.text_content=b(i.text_content)||b(i.text)||b(i.title)||b(i.heading)||"Untitled",i.level=typeof i.level=="number"?i.level:1),e==="text"){const a=b(i.html_content)||b(i.html)||b(i.content)||b(i.text);a&&(i.html_content=/<\/?[a-z][\s\S]*>/i.test(a)?a:`<p>${$n(a)}</p>`)}return e==="button"&&(i.text=b(i.text)||b(i.label)||b(i.title)||"Learn More",i.url=b(i.url)||b(i.href)||b(i.link)||"#"),e==="form"&&(i.fields=Sn(i.fields),i.submit_button_text=b(i.submit_button_text??i.submitButtonText??i.button_text)||"Send Message",i.success_message=b(i.success_message??i.successMessage)||"Thanks for reaching out. We will reply as soon as possible."),j(e,i,t,r),i}function ue(e,n,t){const r=bt(e.blockType,ee(e.content,`Block ${n}`),`Block ${n}`,t);return{block_type:e.blockType,content:r,order:e.order??n}}function En(e,n="Contact Us",t){return[ue({blockType:"section",content:{is_hero:!0,background:{type:"none"},column_blocks:[[{block_type:"heading",content:{level:1,textAlign:"center",text_content:n},temp_id:le("heading")},{block_type:"text",content:{html_content:"<p>Have a question, project, or support request? Send us a note and we will get back to you soon.</p>"},temp_id:le("text")}]],column_gap:"lg",container_type:"container",padding:{bottom:"xl",top:"xl"},responsive_columns:{desktop:1,mobile:1,tablet:1},vertical_alignment:"center"}},0,t),ue({blockType:"form",content:{fields:[{field_type:"text",is_required:!0,label:"Name",placeholder:"Your name",temp_id:"field-name"},{field_type:"email",is_required:!0,label:"Email",placeholder:"you@example.com",temp_id:"field-email"},{field_type:"textarea",is_required:!0,label:"Message",placeholder:"How can we help?",temp_id:"field-message"}],recipient_email:e,submit_button_text:"Send Message",success_message:"Thanks for reaching out. We will reply as soon as possible."}},1,t)]}function ht(e,n,t,r){return(!e||e.length===0)&&n?En(n,t,r):(e||[]).map((i,a)=>ue(i,a,r))}async function Fe(e){const n=e.contentType==="page"?"pages":e.contentType==="post"?"posts":"products",{data:t,error:r}=await e.supabase.from(n).select("id, title, slug, language_id").eq("slug",e.slug).eq("language_id",e.languageId);if(r)throw new Error(`Failed to check ${e.contentType} slug uniqueness: ${f(r)}`);const i=Array.isArray(t)?t:[];return i.length>0?{duplicate:!0,existingItem:i[0],mutationExecuted:!1,success:!1,message:`A ${e.contentType} with slug "${e.slug}" already exists for this language.`}:null}async function Ne(e){if(!e.suppliedTranslationGroupId)return{translationGroupId:void 0};const n=e.contentType==="page"?"pages":e.contentType==="post"?"posts":"products",{data:t,error:r}=await e.supabase.from(n).select("id, title, slug, language_id, translation_group_id").eq("translation_group_id",e.suppliedTranslationGroupId);if(r)throw new Error(`Failed to inspect ${e.contentType} translation group: ${f(r)}`);const i=Array.isArray(t)?t:[];if(i.length===0)return{result:{message:`The ${e.contentType} translation group "${e.suppliedTranslationGroupId}" was not found.`,mutationExecuted:!1,success:!1},translationGroupId:e.suppliedTranslationGroupId};const a=i.find(s=>Number(s.language_id)===e.languageId);return a?{result:{duplicateTranslation:!0,existingItem:a,message:`A ${e.contentType} translation already exists for ${e.languageCode} in this translation group.`,mutationExecuted:!1,success:!1},translationGroupId:e.suppliedTranslationGroupId}:{translationGroupId:e.suppliedTranslationGroupId}}async function yt(e){if(e.blocks.length===0)return[];const n=e.blocks.map((i,a)=>({block_type:i.block_type,content:i.content,language_id:e.languageId,order:i.order??a,page_id:e.contentType==="page"?e.itemId:null,post_id:e.contentType==="post"?e.itemId:null})),{data:t,error:r}=await e.supabase.from("blocks").insert(n).select("*");if(r)throw new Error(`Failed to insert ${e.contentType} blocks: ${f(r)}`);return Array.isArray(t)?t:[]}async function kt(e){const n=e.contentType==="page"?"pages":"posts";await e.supabase.from(n).delete().eq("id",e.itemId)}function je(e,n){return e==="page"?`/cms/pages/${n}/edit`:e==="post"?`/cms/posts/${n}/edit`:`/cms/products/${n}/edit`}function tt(e){return e==="page"?"/cms/pages":e==="post"?"/cms/posts":"/cms/products"}async function qe(e,n){const t=G.parse(e),r=y(n);t.mode==="replace"&&await Cn({items:t.items,languageCode:t.languageCode,menuKey:"HEADER",supabase:r});const i=x({action:"UPDATE NAVIGATION",context:n,payload:{input:t,tool:"update_navigation_bar"},preview:{itemCount:t.items.length,languageCode:t.languageCode,mode:t.mode,target:"header navigation"},subject:`${t.mode} header`});if(i)return i;const a=t.mode==="update"?await xn({items:t.items,languageCode:t.languageCode,match:t.match,menuKey:"HEADER",supabase:r}):t.mode==="append"?await Tn({items:t.items,languageCode:t.languageCode,menuKey:"HEADER",supabase:r}):await ft({items:t.items,languageCode:t.languageCode,menuKey:"HEADER",supabase:r});return lt(n),{...a,mutationExecuted:!0,mode:t.mode,success:!0}}async function Oe(e,n){const t=R.parse(e);if(!t.links?.length&&!t.copyright)throw new Error("update_footer requires links or copyright.");const r=y(n),i=x({action:"UPDATE FOOTER",context:n,payload:{input:t,tool:"update_footer"},preview:{copyrightUpdated:!!t.copyright,linkCount:t.links?.length||0,languageCode:t.languageCode,target:"footer"},subject:t.languageCode});if(i)return i;let a=null;if(t.links?.length&&(a=await ft({items:t.links,languageCode:t.languageCode,menuKey:"FOOTER",supabase:r})),t.copyright){const{error:s}=await r.from("site_settings").upsert({key:"footer_copyright",value:t.copyright});if(s)throw new Error(`Failed to update footer copyright: ${f(s)}`)}return lt(n),{copyrightUpdated:!!t.copyright,footerNavigation:a,mutationExecuted:!0,success:!0}}function wt(e){return typeof e=="string"?e.toLowerCase():""}function An(e,n){const t=n.map(wt).join(" ");return e.reduce((r,i)=>r+(t.includes(i)?1:0),0)}function nt(e,n){return(e.find(t=>n.some(r=>wt(t).includes(r)))||e.find(t=>t.trim().length>0)||"No excerpt available.").slice(0,500)}async function zt(e,n){const t=de.parse(e),r=y(n),i=t.query.toLowerCase().split(/\s+/).map(c=>c.trim()).filter(Boolean),[a,s]=await Promise.all([r.from("posts").select("id, title, slug, excerpt, subtitle, meta_description, status, updated_at").eq("status","published").limit(100),r.from("pages").select("id, title, slug, meta_description, status, updated_at").eq("status","published").limit(100)]);if(a.error)throw new Error(`Failed to search documentation posts: ${f(a.error)}`);if(s.error)throw new Error(`Failed to search documentation pages: ${f(s.error)}`);const l=(a.data??[]).map(c=>({excerpt:nt([c.excerpt,c.subtitle,c.meta_description,c.slug].filter(Boolean),i),source:"post",title:c.title,url:`/article/${c.slug}`})),m=(s.data??[]).map(c=>({excerpt:nt([c.meta_description,c.slug].filter(Boolean),i),source:"page",title:c.title,url:c.slug==="home"?"/":`/${c.slug}`})),u=[...l,...m].map(c=>({...c,score:An(i,[c.title,c.excerpt,c.url])})).filter(c=>c.score>0).sort((c,d)=>d.score-c.score).slice(0,t.limit).map(c=>({excerpt:c.excerpt,source:c.source,title:c.title,url:c.url}));return{query:t.query,results:u,success:!0}}async function It(e,n,t=jt){const r=de.safeParse(e),i=r.success?r.data.query:"";return rn(zt(e,n),t,()=>({message:"Documentation search took too long to respond. Please try again or ask a more specific question.",query:i,results:[],success:!1,timedOut:!0}))}const Pn=["pending","trial","paid","shipped","cancelled","refunded","failed"],Bn={awaiting:"pending",canceled:"cancelled",cancelled:"cancelled",complete:"paid",completed:"paid",failed:"failed",paid:"paid",payment_pending:"pending",pending:"pending",refund:"refunded",refunded:"refunded",refunds:"refunded",shipped:"shipped",trial:"trial",trials:"trial"};function Fn(e){return String(e??"unknown").trim().toLowerCase()||"unknown"}function ot(e){const n=Object.fromEntries(Pn.map(t=>[t,0]));for(const t of e){const r=Fn(t.status);n[r]=(n[r]??0)+1}return n}function Nn(e){const t=e.toLowerCase().replace(/[^a-z0-9_]+/g," ").split(/\s+/).filter(Boolean);for(const r of t){const i=Bn[r];if(i)return i}return null}function M(e){const n=Number(e);return Number.isFinite(n)?n:0}async function Ct(e,n){const t=ke.parse(e),r=y(n),i=new Date;let a=null,s=null;switch(t.timeRange){case"today":a=new Date(i.getFullYear(),i.getMonth(),i.getDate());break;case"this_month":a=new Date(i.getFullYear(),i.getMonth(),1);break;case"last_7_days":a=new Date(i.getTime()-10080*60*1e3);break;case"last_30_days":a=new Date(i.getTime()-720*60*60*1e3);break;case"last_month":a=new Date(i.getFullYear(),i.getMonth()-1,1),s=new Date(i.getFullYear(),i.getMonth(),0,23,59,59,999);break;case"last_90_days":a=new Date(i.getTime()-2160*60*60*1e3);break;case"all_time":a=null;break}const l=t.currency?.toUpperCase(),m=Nn(t.query),u=r.from("orders").select("id, status, total, currency, created_at, paid_at");l&&u.eq("currency",l),a&&u.gte("created_at",a.toISOString()),s&&u.lte("created_at",s.toISOString());const d=t.reportType==="products"||t.reportType==="revenue"||t.reportType==="general"?r.from("order_items").select(`
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const T=require("ai"),on=require("./ai-global-agent-db-tools.cjs.js"),rn=require("./ai-global-agent-custom-block-tools.cjs.js");require("./zod-config.cjs.js");const i=require("zod"),L=["text","heading","image","button","posts_grid","video_embed","section","form","testimonial","product_grid","featured_product","cart","checkout","product_details"],an=1e4,sn={arabic:"ar",chinese:"zh",dutch:"nl",english:"en",french:"fr",francaise:"fr",francais:"fr",german:"de",italian:"it",japanese:"ja",korean:"ko",portuguese:"pt",russian:"ru",spanish:"es"},Tt=i.z.string().trim().min(1).max(2048).refine(e=>e.startsWith("/")||e.startsWith("#")||e.startsWith("http://")||e.startsWith("https://")||e.startsWith("mailto:")||e.startsWith("tel:"),"URL must be a relative path, hash link, http(s) URL, mailto URL, or tel URL."),ut=i.z.strictObject({label:i.z.string().trim().min(1).max(120),target:i.z.enum(["_self","_blank"]).optional(),url:Tt}),Fe=ut.extend({children:i.z.array(ut).max(20).optional()}),ln=i.z.strictObject({label:i.z.string().trim().min(1).max(120).optional(),url:Tt.optional()}).refine(e=>!!(e.label||e.url),{message:"Navigation item match requires label or url."}),H=i.z.strictObject({items:i.z.array(Fe).min(1).max(30),languageCode:i.z.string().trim().min(2).max(80).default("en").describe('Locale code or language name, for example "en", "fr", "English", or "French".'),match:ln.optional().describe('For mode "update", identifies the existing navigation item to update.'),mode:i.z.enum(["append","replace","update"]).default("append")}),J=i.z.strictObject({copyright:i.z.record(i.z.string().trim().min(2).max(12),i.z.string().trim().min(1).max(500)).optional(),languageCode:i.z.string().trim().min(2).max(80).default("en").describe('Locale code or language name, for example "en", "fr", "English", or "French".'),links:i.z.array(Fe).min(1).max(30).optional()}),be=i.z.strictObject({limit:i.z.number().int().min(1).max(8).default(4),query:i.z.string().trim().min(2).max(300)}),Oe=i.z.object({currency:i.z.string().trim().min(3).max(3).optional().describe("Optional currency code for currency-specific monetary reports (e.g., USD, CAD). Do not set this for plain order-status counts unless the user asks for a currency."),query:i.z.string().describe("The analytical question about orders, products, or revenue."),reportType:i.z.enum(["revenue","orders","products","general"]).optional().default("general").describe("The focus area of the statistical report."),timeRange:i.z.enum(["today","this_month","last_7_days","last_30_days","last_month","last_90_days","all_time"]).optional().default("all_time").describe("The time period for the report. Use all_time for current order-status counts unless the user names a specific period.")}),qe=i.z.strictObject({contentType:i.z.enum(["page","post","product"]),currentEditor:i.z.strictObject({blockId:i.z.union([i.z.number().int().positive(),i.z.string().trim().min(1).max(120)]).nullable().optional(),blockType:i.z.string().trim().min(1).max(80).nullable().optional(),field:i.z.string().trim().min(1).max(120).nullable().optional()}).optional(),entityId:i.z.union([i.z.number().int().positive(),i.z.string().trim().min(1).max(120)]),languageId:i.z.number().int().positive().nullable().optional(),slug:i.z.string().trim().min(1).max(300).nullable().optional(),title:i.z.string().trim().min(1).max(300).nullable().optional(),translationGroupId:i.z.string().trim().min(1).max(120).nullable().optional()}),Be=i.z.strictObject({includeBlockContent:i.z.boolean().default(!1),includeBlocks:i.z.boolean().default(!0)}),Y=i.z.strictObject({fields:i.z.strictObject({description_json:i.z.unknown().optional(),excerpt:i.z.string().max(2e3).nullable().optional(),feature_image_id:i.z.string().trim().min(1).max(2048).nullable().optional(),label:i.z.string().max(120).nullable().optional(),meta_description:i.z.string().max(500).nullable().optional(),meta_title:i.z.string().max(160).nullable().optional(),published_at:i.z.string().max(80).nullable().optional(),short_description:i.z.string().max(2e3).nullable().optional(),slug:i.z.string().trim().min(1).max(300).optional(),status:i.z.enum(["draft","published","active","archived"]).optional(),subtitle:i.z.string().max(300).nullable().optional(),title:i.z.string().trim().min(1).max(300).optional()}).partial()}),X=i.z.strictObject({blockId:i.z.number().int().positive(),blockType:i.z.enum(L).optional(),content:i.z.record(i.z.string(),i.z.unknown())}),Q=i.z.strictObject({blockIndex:i.z.number().int().min(0),blockType:i.z.enum(L).optional(),columnIndex:i.z.number().int().min(0),content:i.z.record(i.z.string(),i.z.unknown()),parentBlockId:i.z.number().int().positive()}),cn=i.z.enum(["page","post","product"]),Z=i.z.strictObject({contentType:cn.optional(),entityId:i.z.union([i.z.number().int().positive(),i.z.string().trim().min(1).max(120)]).optional(),slug:i.z.string().trim().min(1).max(300).optional(),title:i.z.string().trim().min(1).max(300).optional()}),ke=i.z.strictObject({blockType:i.z.enum(L),content:i.z.record(i.z.string(),i.z.unknown()),order:i.z.number().int().min(0).optional()}),ee=Z.extend({anchorBlockId:i.z.number().int().positive().optional(),anchorBlockType:i.z.enum(L).optional(),block:ke,position:i.z.enum(["before","after","start","end"]).default("end")}),te=i.z.strictObject({blocks:i.z.array(ke).max(20).optional(),contactEmail:i.z.string().email().optional(),feature_image_id:i.z.string().trim().min(1).max(2048).nullable().optional(),languageCode:i.z.string().trim().min(2).max(80).optional(),meta_description:i.z.string().max(500).nullable().optional(),meta_title:i.z.string().max(160).nullable().optional(),slug:i.z.string().trim().min(1).max(300).optional(),status:i.z.enum(["draft","published","archived"]).default("draft"),title:i.z.string().trim().min(1).max(300),translationGroupId:i.z.string().trim().min(1).max(120).optional()}),ne=i.z.strictObject({blocks:i.z.array(ke).max(20).optional(),excerpt:i.z.string().max(2e3).nullable().optional(),feature_image_id:i.z.string().trim().min(1).max(2048).nullable().optional(),label:i.z.string().max(120).nullable().optional(),languageCode:i.z.string().trim().min(2).max(80).optional(),meta_description:i.z.string().max(500).nullable().optional(),meta_title:i.z.string().max(160).nullable().optional(),published_at:i.z.string().max(80).nullable().optional(),slug:i.z.string().trim().min(1).max(300).optional(),status:i.z.enum(["draft","published","archived"]).default("draft"),subtitle:i.z.string().max(300).nullable().optional(),title:i.z.string().trim().min(1).max(300),translationGroupId:i.z.string().trim().min(1).max(120).optional()}),oe=i.z.strictObject({description_json:i.z.unknown().optional(),freemius_plan_id:i.z.string().optional(),freemius_product_id:i.z.string().optional(),is_taxable:i.z.boolean().default(!0),languageCode:i.z.string().trim().min(2).max(80).optional(),meta_description:i.z.string().max(500).nullable().optional(),meta_title:i.z.string().max(160).nullable().optional(),payment_provider:i.z.enum(["stripe","freemius"]).default("stripe"),price:i.z.number().min(0).default(0),prices:i.z.record(i.z.string(),i.z.number().min(0)).optional(),product_type:i.z.enum(["physical","digital"]).default("physical"),sale_price:i.z.number().min(0).nullable().optional(),sale_prices:i.z.record(i.z.string(),i.z.number().min(0).nullable()).optional(),short_description:i.z.string().max(2e3).nullable().optional(),sku:i.z.string().trim().min(1).max(120).optional(),slug:i.z.string().trim().min(1).max(300).optional(),status:i.z.enum(["draft","active","archived"]).default("draft"),stock:i.z.number().int().min(0).default(0),title:i.z.string().trim().min(1).max(300),trial_period_days:i.z.number().int().min(0).default(0),trial_requires_payment_method:i.z.boolean().default(!1),translationGroupId:i.z.string().trim().min(1).max(120).optional(),upc:i.z.string().max(120).nullable().optional()}),re=Z.extend({currencyCode:i.z.string().trim().min(3).max(3).optional(),endsAt:i.z.string().max(80).nullable().optional(),field:i.z.string().trim().min(1).max(120),startsAt:i.z.string().max(80).nullable().optional(),value:i.z.unknown()}),je=Z,ie=Z,xt=i.z.discriminatedUnion("tool",[i.z.strictObject({input:te,tool:i.z.literal("create_cms_page")}),i.z.strictObject({input:ne,tool:i.z.literal("create_cms_post")}),i.z.strictObject({input:oe,tool:i.z.literal("create_cms_product")}),i.z.strictObject({input:ie,tool:i.z.literal("delete_cms_item")}),i.z.strictObject({input:re,tool:i.z.literal("update_cms_item_field")}),i.z.strictObject({input:X,tool:i.z.literal("update_content_block")}),i.z.strictObject({input:ee,tool:i.z.literal("insert_content_block")}),i.z.strictObject({input:Y,tool:i.z.literal("update_current_cms_fields")}),i.z.strictObject({input:J,tool:i.z.literal("update_footer")}),i.z.strictObject({input:H,tool:i.z.literal("update_navigation_bar")}),i.z.strictObject({input:Q,tool:i.z.literal("update_section_column_block")})]),un=i.z.union([te.extend({tool:i.z.literal("create_cms_page")}).transform(({tool:e,...t})=>({input:t,tool:e})),ne.extend({tool:i.z.literal("create_cms_post")}).transform(({tool:e,...t})=>({input:t,tool:e})),oe.extend({tool:i.z.literal("create_cms_product")}).transform(({tool:e,...t})=>({input:t,tool:e})),ie.extend({tool:i.z.literal("delete_cms_item")}).transform(({tool:e,...t})=>({input:t,tool:e})),re.extend({tool:i.z.literal("update_cms_item_field")}).transform(({tool:e,...t})=>({input:t,tool:e})),X.extend({tool:i.z.literal("update_content_block")}).transform(({tool:e,...t})=>({input:t,tool:e})),ee.extend({tool:i.z.literal("insert_content_block")}).transform(({tool:e,...t})=>({input:t,tool:e})),Y.extend({tool:i.z.literal("update_current_cms_fields")}).transform(({tool:e,...t})=>({input:t,tool:e})),J.extend({tool:i.z.literal("update_footer")}).transform(({tool:e,...t})=>({input:t,tool:e})),H.extend({tool:i.z.literal("update_navigation_bar")}).transform(({tool:e,...t})=>({input:t,tool:e})),Q.extend({tool:i.z.literal("update_section_column_block")}).transform(({tool:e,...t})=>({input:t,tool:e}))]),dn=i.z.string().transform((e,t)=>{const n=hn(e);return n.success?n.action:(t.addIssue({code:"custom",message:n.message}),i.z.NEVER)}),pn=i.z.union([xt,un,dn]),Le=i.z.strictObject({actions:i.z.array(pn).min(1).max(8),summary:i.z.string().trim().min(1).max(500).optional()});function mn(e){const t=[];let n="",o=0,r=null,a=!1;for(const s of e){if(r){n+=s,a?a=!1:s==="\\"?a=!0:s===r&&(r=null);continue}if(s==='"'||s==="'"){r=s,n+=s;continue}if(s==="["||s==="{"||s==="("){o++,n+=s;continue}if(s==="]"||s==="}"||s===")"){o=Math.max(0,o-1),n+=s;continue}if(s===","&&o===0){n.trim()&&t.push(n.trim()),n="";continue}n+=s}return n.trim()&&t.push(n.trim()),t}function dt(e){let t="";for(let n=0;n<e.length;n++){const o=e[n];if(o!=="'"){t+=o;continue}let r="",a=!1;for(n++;n<e.length;n++){const s=e[n];if(a){r+=s,a=!1;continue}if(s==="\\"){a=!0;continue}if(s==="'")break;r+=s}t+=JSON.stringify(r)}return t.replace(/\bTrue\b/g,"true").replace(/\bFalse\b/g,"false").replace(/\bNone\b/g,"null")}function gn(e){const t=e.trim();return t.startsWith("'")&&t.endsWith("'")||t.startsWith('"')&&t.endsWith('"')||t.startsWith("[")||t.startsWith("{")?JSON.parse(dt(t)):/^-?\d+(?:\.\d+)?$/.test(t)?Number(t):t==="true"||t==="True"?!0:t==="false"||t==="False"?!1:t==="null"||t==="None"?null:t}function fn(e){const t={};for(const n of mn(e)){const o=n.indexOf("=");if(o<=0)throw new Error(`Expected key=value argument, received "${n}".`);const r=n.slice(0,o).trim();if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(r))throw new Error(`Invalid argument name "${r}".`);t[r]=gn(n.slice(o+1))}return t}function hn(e){const n=e.trim().match(/^([a-z_]+)\(([\s\S]*)\)$/);if(!n)return{message:'Action plan actions must be JSON objects like { "tool": "create_cms_page", "input": { ... } }, not freeform text.',success:!1};const o=n[1];let r;try{r=fn(n[2])}catch(l){return{message:l instanceof Error?l.message:"Could not parse action-plan command arguments.",success:!1}}const a={input:r,tool:o},s=xt.safeParse(a);return s.success?{action:s.data,success:!0}:{message:`Invalid action-plan command "${o}": ${s.error.issues.map(l=>l.message).join("; ")}`,success:!1}}function _n(e){return e.normalize("NFD").replace(/[\u0300-\u036f]/g,"").toLowerCase().replace(/\s+/g," ").trim()}function ue(e,t){return t.some(n=>e.includes(n))}function yn(e){const t=_n(e),n=ue(t,["add ","insert ","put ","create "]),o=ue(t,["title","heading","description","intro","copy","paragraph"]),r=t.includes("form")&&ue(t,["above","before"]),a=t.includes("contact page")||t.includes("contact pages")||t.includes("contact us")||t.includes("contactez-nous"),s=t.includes("english")&&ue(t,["french","francais","francaise"]);return!n||!o||!r||!a||!s?null:{actions:[{input:{anchorBlockType:"form",block:{blockType:"text",content:{html_content:"<h2>Let us help you move faster</h2><p>Have a question, project idea, or need help choosing the right next step? Send us a message and the NextBlock team will get back to you soon.</p>"}},contentType:"page",position:"before",slug:"contact-us"},tool:"insert_content_block"},{input:{anchorBlockType:"form",block:{blockType:"text",content:{html_content:"<h2>Parlons de votre projet</h2><p>Vous avez une question, une idee de projet ou besoin d'aide pour avancer? Envoyez-nous un message et l'equipe NextBlock vous repondra rapidement.</p>"}},contentType:"page",position:"before",slug:"contactez-nous"},tool:"insert_content_block"}],summary:"Add visible title and description copy above the forms on the English and French Contact pages."}}const bn=i.z.enum(L),pt=i.z.object({direction:i.z.string().optional(),stops:i.z.array(i.z.object({color:i.z.string(),position:i.z.number()})),type:i.z.enum(["linear","radial"])}),kn=i.z.object({gradient:pt.optional(),image:i.z.object({alt_text:i.z.string().optional(),blur_data_url:i.z.string().optional(),external_url:i.z.string().optional(),height:i.z.number().optional(),media_id:i.z.string().optional(),object_key:i.z.string().optional(),overlay:i.z.object({gradient:pt,type:i.z.literal("gradient")}).optional(),position:i.z.enum(["center","top","bottom","left","right"]),quality:i.z.number().nullable().optional(),size:i.z.enum(["cover","contain"]),width:i.z.number().optional()}).optional(),min_height:i.z.string().optional(),solid_color:i.z.string().optional(),theme:i.z.enum(["primary","secondary","muted","accent","destructive"]).optional(),type:i.z.enum(["none","theme","solid","gradient","image"])}),wn=i.z.object({block_type:bn,content:i.z.record(i.z.string(),i.z.any()),temp_id:i.z.string().optional()}),In=i.z.object({background:kn,column_blocks:i.z.array(i.z.array(wn)),column_gap:i.z.enum(["none","sm","md","lg","xl"]),container_type:i.z.enum(["full-width","container","container-sm","container-lg","container-xl"]),padding:i.z.object({bottom:i.z.enum(["none","sm","md","lg","xl"]),top:i.z.enum(["none","sm","md","lg","xl"])}),responsive_columns:i.z.object({desktop:i.z.union([i.z.literal(1),i.z.literal(2),i.z.literal(3),i.z.literal(4)]),mobile:i.z.union([i.z.literal(1),i.z.literal(2)]),tablet:i.z.union([i.z.literal(1),i.z.literal(2),i.z.literal(3)])}),vertical_alignment:i.z.enum(["start","center","end","stretch"]).optional()}),Tn={button:i.z.object({position:i.z.enum(["left","center","right"]).optional(),size:i.z.enum(["default","sm","lg","full"]).optional(),text:i.z.string(),url:i.z.string(),variant:i.z.enum(["default","outline","secondary","ghost","link"]).optional()}),cart:i.z.object({}),checkout:i.z.object({}),featured_product:i.z.object({imagePosition:i.z.enum(["left","right"]).default("left"),productId:i.z.string().min(1),showBackground:i.z.boolean().default(!1)}),form:i.z.object({fields:i.z.array(i.z.object({field_type:i.z.enum(["text","email","textarea","select","radio","checkbox"]),is_required:i.z.boolean(),label:i.z.string(),options:i.z.array(i.z.object({label:i.z.string(),value:i.z.string()})).optional(),placeholder:i.z.string().optional(),temp_id:i.z.string()})),recipient_email:i.z.string().email(),submit_button_text:i.z.string(),success_message:i.z.string()}),heading:i.z.object({level:i.z.union([i.z.literal(1),i.z.literal(2),i.z.literal(3),i.z.literal(4),i.z.literal(5),i.z.literal(6)]),textAlign:i.z.enum(["left","center","right","justify"]).optional(),textColor:i.z.enum(["primary","secondary","accent","muted","destructive","background"]).optional(),text_content:i.z.string()}),image:i.z.object({alt_text:i.z.string().optional(),caption:i.z.string().optional(),external_url:i.z.string().nullable().optional(),height:i.z.number().nullable().optional(),media_id:i.z.string().nullable().optional(),object_key:i.z.string().nullable().optional(),width:i.z.number().nullable().optional()}),posts_grid:i.z.object({columns:i.z.number().min(1).max(6),postsPerPage:i.z.number().min(1).max(50),showPagination:i.z.boolean(),title:i.z.string().optional()}),product_details:i.z.object({}),product_grid:i.z.object({categoryId:i.z.string().optional(),limit:i.z.number().min(1).max(20).default(6),title:i.z.string().optional(),type:i.z.enum(["latest","category"]).default("latest")}),section:In,testimonial:i.z.object({author_name:i.z.string().min(1),author_title:i.z.string().optional(),image_url:i.z.string().url().optional().or(i.z.literal("")),quote:i.z.string().min(1)}),text:i.z.object({html_content:i.z.string()}),video_embed:i.z.object({autoplay:i.z.boolean().optional(),controls:i.z.boolean().optional(),title:i.z.string().optional(),url:i.z.string()})};function xn(e){return L.includes(e)}function zn(e){return typeof e?.validateBlockContent=="function"?e.validateBlockContent:null}function Cn(e,t,n){const o=zn(n);if(o)return o(e,t);const r=Tn[e].safeParse(t);return r.success?{errors:[],isValid:!0,warnings:[]}:{errors:r.error.issues.map(a=>{const s=a.path.join(".");return s?`${s}: ${a.message}`:a.message}),isValid:!1,warnings:[]}}function Sn(){return i.z.object({content:i.z.array(i.z.any()).optional(),type:i.z.literal("doc")})}function Re(){try{const{revalidatePath:e}=require("next/cache");return e}catch{return null}}function I(e){if(!e?.supabase)throw new Error("A Supabase service client is required to execute Cortex AI global tools.");return e.supabase}function vn(e,t,n){let o;const r=new Promise(a=>{o=setTimeout(()=>a(n()),t)});return Promise.race([e.finally(()=>{o&&clearTimeout(o)}),r])}function D(e){const t=qe.safeParse(e?.pageContext);if(!t.success)throw new Error("No current CMS page context is available. Open a page, post, or product edit screen before using this editing tool.");return t.data}function De(e){const t=typeof e.entityId=="number"?e.entityId:Number.parseInt(e.entityId,10);if(!Number.isInteger(t)||t<=0)throw new Error(`Current ${e.contentType} id must be a positive integer.`);return t}function En(e){const t=String(e.entityId||"").trim();if(!t)throw new Error(`Current ${e.contentType} id is missing.`);return t}function we(e){return e.contentType==="product"?En(e):De(e)}const $n=/^https?:\/\//i,An=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;async function ae(e,t,n){if(typeof e!="string")return null;const o=e.trim();if(!o)return null;if(!$n.test(o)){if(An.test(o))return o;throw new Error(`"${o}" is not a usable image reference — provide an https:// image URL or a media library id.`)}const r=t?.importExternalImage;if(!r)throw new Error("I can only attach an image from a URL when media import is available here. Please pick an image from the media library instead.");const a=await r({altText:n,url:o});if("error"in a)throw new Error(`I could not import the image from that URL: ${a.error}`);return a.id}function zt(e){return typeof e=="string"?e.trim().replace(/^\/+|\/+$/g,""):""}function Pn(e,t){const n=zt(t??e.slug);return n?e.contentType==="page"?n==="home"?"/":`/${n}`:e.contentType==="post"?`/article/${n}`:`/product/${n}`:null}function Nn(e){const t=String(e.entityId);return e.contentType==="page"?`/cms/pages/${t}/edit`:e.contentType==="post"?`/cms/posts/${t}/edit`:`/cms/products/${t}/edit`}function P(e,t,n){const o=e?.revalidatePath??Re();if(!o)return;o(Nn(t));const r=Pn(t,n);r&&o(r),t.contentType==="page"&&r!=="/"&&o("/"),t.contentType==="product"&&o("/cms/products")}function Ct(e){const t=e?.revalidatePath??Re();t&&(t("/","layout"),t("/cms/navigation"))}function h(e){return e?typeof e=="object"&&"message"in e?String(e.message||"Unknown database error."):String(e):"Unknown database error."}async function Un(){return Promise.resolve().then(()=>require("./ai-global-agent-ecommerce.cjs.js"))}function Se(e){return e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?`[${e.map(t=>Se(t)).join(",")}]`:`{${Object.keys(e).filter(t=>t!=="temp_id").sort().map(t=>`${JSON.stringify(t)}:${Se(e[t])}`).join(",")}}`}function Fn(e){let t=2166136261;const n=Se(e);for(let o=0;o<n.length;o++)t^=n.charCodeAt(o),t=Math.imul(t,16777619);return(t>>>0).toString(16).padStart(8,"0")}function ve(e){return e.replace(/\s+/g," ").trim().toUpperCase()}function On(e,t,n){return`${ve(`CONFIRM ${e} ${t}`)} #${Fn(n)}`}function St(e){return{confirmationPhrase:On(e.action,e.subject,e.payload),mutationExecuted:!1,preview:e.preview,requiresConfirmation:!0,success:!0}}function N(e,t){const n=e[t];return typeof n=="string"&&n.trim()?n.trim():null}function de(e,t){const n=Number(e[t]);return Number.isFinite(n)?n:null}function U(e,t,n=`${t}s`){return`${e} ${e===1?t:n}`}function qn(e,t){const n=N(t,"summary");if(n)return n;const o=N(t,"title"),r=N(t,"slug"),a=N(t,"status"),s=N(t,"contentType"),l=N(t,"field"),u=N(t,"mode"),d=N(t,"languageCode"),c=de(t,"blockCount"),p=de(t,"itemCount"),g=de(t,"affectedCount");if(e==="create_cms_page"||e==="create_cms_post")return`Create ${a||"draft"} ${e==="create_cms_page"?"page":"post"} "${o||r||"Untitled"}"${r?` at slug "${r}"`:""}${c!==null?` with ${U(c,"content block")}`:""}.`;if(e==="create_cms_product")return`Create ${a||"draft"} product "${o||r||"Untitled"}"${r?` at slug "${r}"`:""}.`;if(e==="update_cms_item_field")return`Update ${l||"one field"} on the ${s||"CMS item"} "${o||r||"selected item"}".`;if(e==="update_navigation_bar")return`${u==="append"?"Add":u==="update"?"Update":"Replace"} ${p!==null?U(p,"navigation item"):"navigation items"} in the ${d||"selected"} header navigation.`;if(e==="update_footer"){const m=de(t,"linkCount");return`Update the ${d||"selected"} footer${m!==null?` with ${U(m,"link")}`:""}.`}return e==="update_content_block"?`Update the selected ${N(t,"blockType")||"content"} block.`:e==="insert_content_block"?`Insert ${N(t,"blockType")||"content"} block on the ${s||"CMS item"} "${o||r||"selected item"}".`:e==="update_section_column_block"?`Update the selected nested ${N(t,"nestedBlockType")||"section"} block.`:e==="delete_cms_item"||e==="prepare_delete_cms_item"?`Delete ${g!==null?U(g,s||"CMS item"):`the selected ${s||"CMS item"}`}${o||r?` for "${o||r}"`:""}.`:"Complete the requested CMS change."}function A(e){if(e.context?.skipConfirmation)return null;const t=St(e),n=ve(e.context?.latestUserMessage||""),o=ve(t.confirmationPhrase);return n.includes(o)?null:t}function Me(e){const t=e?.actorUserId;if(!t)throw new Error("A confirmed CMS mutation requires an authenticated admin actor.");return t}function Ge(){return globalThis.crypto?.randomUUID?.()||`id-${Date.now()}-${Math.random().toString(36).slice(2)}`}function se(e){return e.toLowerCase().trim().replace(/\s+/g,"-").replace(/[^a-z0-9-]/g,"").replace(/-+/g,"-").replace(/^-|-$/g,"").slice(0,300)}function Ke(e){return(e||"USD").trim().toUpperCase()}const Bn=new Set(["BIF","CLP","DJF","GNF","JPY","KMF","KRW","MGA","PYG","RWF","UGX","VND","VUV","XAF","XOF","XPF"]);function jn(e){return Bn.has(Ke(e))?0:2}function vt(e,t){return Math.round(e*10**jn(t))}function Ln(e,t){return!e||typeof e!="object"||Array.isArray(e)?{}:Object.entries(e).reduce((n,[o,r])=>{if(typeof r=="number"&&Number.isFinite(r)&&r>=0){const a=Ke(o||t);n[a]=vt(r,a)}return n},{})}function le(e,t){if(!$(e))throw new Error(`${t} content must be a JSON object.`);return JSON.parse(JSON.stringify(e))}function W(e){return JSON.parse(JSON.stringify(e))}function $(e){return!!(e&&typeof e=="object"&&!Array.isArray(e))}function Ee(e,t){const n=W(e);for(const[o,r]of Object.entries(t))if(r!==void 0){if($(r)&&$(n[o])){n[o]=Ee(n[o],r);continue}n[o]=W(r)}return n}function Et(e,t){if(t.contentType==="product")throw new Error("Products do not have page/post content blocks in this editor context.");const n=De(t);if((t.contentType==="page"?Number(e.page_id):Number(e.post_id))!==n)throw new Error(`Block ${e.id} does not belong to the current ${t.contentType} being edited.`)}function fe(e,t){const n=typeof e=="string"?e:"";if(!xn(n))throw new Error(`${t} has unsupported block type "${n||"unknown"}".`);return n}function $t(e,t,n){if(e&&e!==t)throw new Error(`${n} is a "${t}" block. Refusing to update it as "${e}".`)}function j(e,t,n,o){const r=Cn(e,t,o);if(!r.isValid)throw new Error(`${n} content is invalid for block type "${e}": ${r.errors.join("; ")}`)}function At(e){return e==="section"}function Rn(e){return typeof e.html_content=="string"?"text":typeof e.text=="string"&&typeof e.url=="string"?"button":typeof e.text_content=="string"?"heading":"media_id"in e||"object_key"in e||"external_url"in e?"image":typeof e.quote=="string"&&typeof e.author_name=="string"?"testimonial":typeof e.url=="string"&&("controls"in e||"autoplay"in e||"title"in e)?"video_embed":Array.isArray(e.fields)||typeof e.recipient_email=="string"?"form":"postsPerPage"in e||"showPagination"in e?"posts_grid":typeof e.productId=="string"?"featured_product":"limit"in e&&"type"in e?"product_grid":null}function he(e){return`ai-${e}-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}function $e(e,t,n){if(!$(e))throw new Error(`${t} must be a JSON object.`);const o=e.block_type??e.blockType,r=fe(o,t);if(At(r))throw new Error(`${t} cannot be a nested ${r} block.`);const a=Ft(r,le(e.content,t),t,n),s=e.temp_id??e.tempId,l=typeof s=="string"&&s.trim()?s:he(r);return{block_type:r,content:a,temp_id:l}}function Dn(e,t){const n=[];if("append_block"in e&&n.push($e(e.append_block,"Nested block to append",t)),"append_blocks"in e){const o=e.append_blocks;if(!Array.isArray(o))throw new Error("append_blocks must be an array of nested block objects.");o.forEach((r,a)=>{n.push($e(r,`Nested block to append ${a}`,t))})}return n}function Mn(e,t){if("append_block"in e||"append_blocks"in e||"background"in e||"column_blocks"in e||"column_gap"in e||"container_type"in e||"padding"in e||"responsive_columns"in e||"vertical_alignment"in e)return null;const n=Rn(e);if(!n)return null;const o=le(e,`Nested ${n} block`);return j(n,o,`Nested ${n} block`,t),{block_type:n,content:o,temp_id:he(n)}}function Gn(e,t){const n=e.append_column_index??e.column_index;if(n===void 0)return 0;if(typeof n!="number"||!Number.isInteger(n)||n<0)throw new Error("append_column_index must be a non-negative integer.");if(t>0&&n>=t)throw new Error(`append_column_index ${n} is outside the existing ${t} column(s).`);return n}function Kn(e,t,n,o){if(!At(e))return Ee(t,n);const r={...n},a=Dn(r,o),s=Mn(r,o);s&&a.push(s),delete r.append_block,delete r.append_blocks,delete r.append_column_index,delete r.column_index;const l=Ee(t,r);if(a.length>0){const u=Array.isArray(t.column_blocks)?W(t.column_blocks):[],d=Gn(n,u.length),c=u.length>0?u:[[]];for(;c.length<=d;)c.push([]);c[d]=[...c[d]||[],...a],l.column_blocks=c}return l}function Vn(e,t){return{blockType:e.block_type,content:t?e.content:void 0,id:e.id,languageId:e.language_id,order:e.order,pageId:e.page_id,postId:e.post_id}}function R(e){return typeof e=="string"?e.trim().toLowerCase():""}function mt(e){return typeof e=="string"?e.trim().toLowerCase():""}function Pt(e){return e.reduce((t,n)=>t+1+(n.children?.length||0),0)}function ge(e){return typeof e=="string"?e.trim().toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g,""):""}async function M(e,t){const n=t.trim(),o=ge(n),r=sn[o],{data:a,error:s}=await e.from("languages").select("id, code, name, is_active");if(s)throw new Error(`Failed to load language "${t}": ${h(s)}`);const u=(Array.isArray(a)?a:[]).filter(c=>c.is_active!==!1),d=u.find(c=>{const p=ge(c.code),g=ge(c.name);return p===o||p===r||g===o});if(!d?.id||!d?.code){const c=u.map(p=>p.code).filter(Boolean).join(", ");throw new Error(`Language "${t}" was not found.${c?` Available languages: ${c}.`:""}`)}return{code:String(d.code),id:Number(d.id)}}async function Ie(e,t){if(t)return M(e,t);const{data:n,error:o}=await e.from("languages").select("id, code, name, is_active, is_default");if(o)throw new Error(`Failed to load active languages: ${h(o)}`);const r=(Array.isArray(n)?n:[]).filter(s=>s.is_active!==!1),a=r.find(s=>s.is_default)||r.find(s=>ge(s.code)==="en")||r[0];if(!a?.id||!a?.code)throw new Error("No active CMS language is available for Cortex AI content creation.");return{code:String(a.code),id:Number(a.id)}}async function gt(e){try{const{data:t,error:n}=await e.from("currencies").select("code, is_default, is_active").eq("is_active",!0);if(n)return"USD";const o=Array.isArray(t)?t:[],r=o.find(a=>a.is_default)||o[0];return Ke(r?.code||"USD")}catch{return"USD"}}async function Wn(e){const t=e.contentType==="page"?"pages":e.contentType==="post"?"posts":"products";let n="id",o=e.entityId;if(o===void 0&&e.slug&&(n="slug",o=e.slug),o===void 0&&e.title&&(n="title",o=e.title),o===void 0)throw new Error(`A ${e.contentType} target requires an id, slug, title, or current edit context.`);const{data:r,error:a}=await e.supabase.from(t).select("*").eq(n,o);if(a)throw new Error(`Failed to resolve ${e.contentType}: ${h(a)}`);const s=Array.isArray(r)?r:r?[r]:[];if(s.length!==1)throw new Error(s.length===0?`No ${e.contentType} matched ${n} "${String(o)}".`:`Multiple ${e.contentType}s matched ${n} "${String(o)}"; use an exact id.`);return s[0]}async function Te(e,t){const n=qe.safeParse(t?.pageContext).success?t?.pageContext:null,o=e.contentType||n?.contentType;if(!o)throw new Error("Target contentType is required when no current CMS edit context exists.");const r=e.entityId!==void 0||!!e.slug||!!e.title,a=e.entityId??(r?void 0:n?.entityId),s=e.slug??(r?void 0:n?.slug??void 0),l=e.title??(r?void 0:n?.title??void 0),u=await Wn({contentType:o,entityId:a,slug:a===void 0&&s||void 0,supabase:I(t),title:a===void 0&&!s&&l||void 0});return{contentType:o,item:u}}async function _e(e){const t=await Jn({item:e.item,languageId:e.languageId,menuKey:e.menuKey,supabase:e.supabase}),n={label:e.item.label,language_id:e.languageId,menu_key:e.menuKey,order:e.order,page_id:t?.pageId??null,parent_id:e.parentId??null,...t?.navigationTranslationGroupId?{translation_group_id:t.navigationTranslationGroupId}:{},url:e.item.url},{data:o,error:r}=await e.supabase.from("navigation_items").insert(n).select("id").single();if(r)throw new Error(`Failed to insert ${e.menuKey} navigation item: ${h(r)}`);return Number(o.id)}function Hn(e){const t=e.trim();if(!t.startsWith("/")||t.startsWith("//"))return null;const n=t.split("?")[0]?.split("#")[0]||"",o=n==="/"?"home":n.replace(/^\/+|\/+$/g,"");return o&&!o.includes("/")?o:null}async function Jn(e){const t=Hn(e.item.url);if(!t)return null;const{data:n,error:o}=await e.supabase.from("pages").select("id, slug, translation_group_id, language_id").eq("slug",t).eq("language_id",e.languageId);if(o)throw new Error(`Failed to resolve linked page for navigation item: ${h(o)}`);const r=Array.isArray(n)?n[0]:n;if(!r?.id)return null;let a=Ge();if(r.translation_group_id){const{data:s,error:l}=await e.supabase.from("pages").select("id").eq("translation_group_id",r.translation_group_id);if(l)throw new Error(`Failed to inspect linked page translations for navigation item: ${h(l)}`);const u=new Set((Array.isArray(s)?s:[]).map(g=>String(g.id)).filter(Boolean)),{data:d,error:c}=await e.supabase.from("navigation_items").select("id, page_id, translation_group_id, menu_key").eq("menu_key",e.menuKey);if(c)throw new Error(`Failed to inspect related navigation translations: ${h(c)}`);const p=(Array.isArray(d)?d:[]).find(g=>g.translation_group_id&&u.has(String(g.page_id)));p?.translation_group_id&&(a=p.translation_group_id)}return{navigationTranslationGroupId:a,pageId:Number(r.id)}}async function Nt(e){const t=await M(e.supabase,e.languageCode),{data:n,error:o}=await e.supabase.from("navigation_items").select("id, parent_id").eq("menu_key",e.menuKey).eq("language_id",t.id);if(o)throw new Error(`Failed to inspect existing ${e.menuKey} navigation items: ${h(o)}`);const r=Array.isArray(n)?n:[],a=r.filter(d=>d.parent_id==null).length,s=Pt(e.items);Ut({existingItemCount:r.length,existingTopLevelCount:a,languageCode:t.code,menuKey:e.menuKey,replacementItemCount:s});const{error:l}=await e.supabase.from("navigation_items").delete().eq("menu_key",e.menuKey).eq("language_id",t.id);if(l)throw new Error(`Failed to clear ${e.menuKey} navigation items: ${h(l)}`);let u=0;for(const[d,c]of e.items.entries()){const p=await _e({item:c,languageId:t.id,menuKey:e.menuKey,order:d,supabase:e.supabase});u++;for(const[g,m]of(c.children??[]).entries())await _e({item:m,languageId:t.id,menuKey:e.menuKey,order:g,parentId:p,supabase:e.supabase}),u++}return{insertedCount:u,languageCode:t.code,menuKey:e.menuKey,skippedCount:0,updatedCount:0}}function Ut(e){if(!(e.existingItemCount===0||e.replacementItemCount>=e.existingItemCount))throw new Error(`Refusing destructive ${e.menuKey} navigation replacement for ${e.languageCode}: existing menu has ${e.existingItemCount} items (${e.existingTopLevelCount} top-level), but the replacement only contains ${e.replacementItemCount}. Use mode "update" for renaming or changing a single link, or provide the full menu.`)}async function Yn(e){const t=await M(e.supabase,e.languageCode),{data:n,error:o}=await e.supabase.from("navigation_items").select("id, parent_id").eq("menu_key",e.menuKey).eq("language_id",t.id);if(o)throw new Error(`Failed to inspect existing ${e.menuKey} navigation items: ${h(o)}`);const r=Array.isArray(n)?n:[];Ut({existingItemCount:r.length,existingTopLevelCount:r.filter(a=>a.parent_id==null).length,languageCode:t.code,menuKey:e.menuKey,replacementItemCount:Pt(e.items)})}async function Xn(e){if(e.items.length!==1)throw new Error('mode "update" requires exactly one navigation item.');const t=await M(e.supabase,e.languageCode),n=e.items[0],o=R(e.match?.url)||R(n.url),r=mt(e.match?.label),{data:a,error:s}=await e.supabase.from("navigation_items").select("id, label, url, parent_id, order").eq("menu_key",e.menuKey).eq("language_id",t.id);if(s)throw new Error(`Failed to load existing ${e.menuKey} navigation items: ${h(s)}`);const u=(Array.isArray(a)?a:[]).find(c=>{const p=R(c.url),g=mt(c.label);return!!(o&&p===o||r&&g===r)});if(!u?.id)throw new Error(`Could not find a ${e.menuKey} navigation item to update in ${t.code}. Use a matching label or url.`);const{error:d}=await e.supabase.from("navigation_items").update({label:n.label,url:n.url}).eq("id",u.id);if(d)throw new Error(`Failed to update ${e.menuKey} navigation item: ${h(d)}`);return{insertedCount:0,languageCode:t.code,menuKey:e.menuKey,skippedCount:0,updatedCount:1}}async function Qn(e){const t=await M(e.supabase,e.languageCode),{data:n,error:o}=await e.supabase.from("navigation_items").select("id, url, parent_id, order").eq("menu_key",e.menuKey).eq("language_id",t.id);if(o)throw new Error(`Failed to load existing ${e.menuKey} navigation items: ${h(o)}`);let r=0,a=0;const s=Array.isArray(n)?n:[],l=new Set(s.map(c=>R(c.url)).filter(Boolean)),u=s.filter(c=>c.parent_id==null).map(c=>Number(c.order)).filter(Number.isFinite);let d=u.length>0?Math.max(...u)+1:s.length;for(const c of e.items){const p=R(c.url);if(p&&l.has(p)){a++;continue}const g=await _e({item:c,languageId:t.id,menuKey:e.menuKey,order:d,supabase:e.supabase});r++,d++,p&&l.add(p);let m=0;for(const f of c.children??[]){const _=R(f.url);if(_&&l.has(_)){a++;continue}await _e({item:f,languageId:t.id,menuKey:e.menuKey,order:m,parentId:g,supabase:e.supabase}),r++,m++,_&&l.add(_)}}return{insertedCount:r,languageCode:t.code,menuKey:e.menuKey,skippedCount:a,updatedCount:0}}function x(e){return typeof e=="string"&&e.trim()?e.trim():""}function Zn(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function eo(e){const t=x(e.field_type??e.fieldType??e.type??e.input_type).toLowerCase().replace(/\s+/g,"_"),n=x(e.label??e.name??e.placeholder).toLowerCase();return["email","textarea","select","radio","checkbox","text"].includes(t)?t:n.includes("email")?"email":n.includes("message")||n.includes("comment")||n.includes("details")?"textarea":"text"}function to(e){return(Array.isArray(e)&&e.length>0?e:[{field_type:"text",is_required:!0,label:"Name",placeholder:"Your name"},{field_type:"email",is_required:!0,label:"Email",placeholder:"you@example.com"},{field_type:"textarea",is_required:!0,label:"Message",placeholder:"How can we help?"}]).map((n,o)=>{const r=$(n)?n:{},a=x(r.label??r.name)||(o===0?"Name":o===1?"Email":"Message"),s=eo({...r,label:a}),l=r.is_required??r.isRequired??r.required;return{field_type:s,is_required:typeof l=="boolean"?l:!0,label:a,options:Array.isArray(r.options)?r.options:void 0,placeholder:x(r.placeholder)||void 0,temp_id:x(r.temp_id??r.tempId??r.id)||`field-${o+1}`}})}const no=new Set(["none","sm","md","lg","xl"]),ft=new Set(["none","sm","md","lg","xl"]),oo=new Set(["full-width","container","container-sm","container-lg","container-xl"]),ro=new Set(["start","center","end","stretch"]),io=new Set(["none","theme","solid","gradient","image"]),ao=new Set(["primary","secondary","muted","accent","destructive"]),so=new Set(["center","top","bottom","left","right"]);function lo(e){return typeof e=="string"&&/^https?:\/\//i.test(e.trim())}function q(e,t,n){return typeof e=="string"&&t.has(e)?e:n}function co(e){return Number.isFinite(e)?Math.min(4,Math.max(1,Math.round(e))):1}function uo(e){const t=[{color:"#1e3a8a",position:0},{color:"#3b82f6",position:100}];if(!$(e))return{direction:"to bottom right",stops:t,type:"linear"};const n=e.type==="radial"?"radial":"linear",o=Array.isArray(e.stops)&&e.stops.length>=2?e.stops:t;return{direction:typeof e.direction=="string"&&e.direction.trim()?e.direction:n==="radial"?"circle at center":"to bottom right",stops:o,type:n}}function po(e){if(!$(e))return{type:"none"};const t=q(e.type,io,"none"),n=typeof e.min_height=="string"&&e.min_height.trim()?{min_height:e.min_height}:{};if(t==="theme")return{theme:q(e.theme,ao,"muted"),type:t,...n};if(t==="solid")return typeof e.solid_color=="string"&&e.solid_color.trim()?{solid_color:e.solid_color,type:t,...n}:{type:"none"};if(t==="gradient")return{gradient:uo(e.gradient),type:t,...n};if(t==="image"){const o=$(e.image)?e.image:null,r=o&&lo(o.external_url)?o.external_url.trim():null,a=!!(o&&typeof o.media_id=="string"&&o.media_id.trim()&&typeof o.object_key=="string"&&o.object_key.trim());return o&&(r||a)?{image:{...o,...r?{external_url:r}:{},position:q(o.position,so,"center"),size:o.size==="contain"?"contain":"cover"},type:t,...n}:{type:"none"}}return{type:"none",...n}}function mo(e,t,n){const o=e.is_hero===!0;let r=Array.isArray(e.column_blocks)?e.column_blocks:[];r.length>0&&r.every(_=>$(_)&&!Array.isArray(_))&&(r=[r]);const a=r.map((_,k)=>(Array.isArray(_)?_:[]).map((v,y)=>$e(v,`${t} column ${k} block ${y}`,n))),s=a.length>0?a:[[]],l=co(s.length),u=$(e.responsive_columns)?e.responsive_columns:{},d=Number(u.tablet),c=Number(u.mobile),p=Number.isFinite(d)?Math.min(3,Math.max(1,Math.min(l,d))):Math.min(3,l),g=Number.isFinite(c)?Math.min(2,Math.max(1,c)):1,m=$(e.padding)?e.padding:{},f={...e,background:po(e.background),column_blocks:s,column_gap:q(e.column_gap,no,"lg"),container_type:q(e.container_type,oo,"container"),padding:{bottom:q(m.bottom,ft,"xl"),top:q(m.top,ft,"xl")},responsive_columns:{desktop:l,mobile:g,tablet:p},vertical_alignment:q(e.vertical_alignment,ro,o?"center":"start")};return f.slider===!0&&!(Array.isArray(f.slides)&&f.slides.length>0)&&(f.slider=!1),f}function Ft(e,t,n,o){if(e==="section"){const a=mo(t,n,o);return j(e,a,n,o),a}const r=W(t);if(e==="heading"&&(r.text_content=x(r.text_content)||x(r.text)||x(r.title)||x(r.heading)||"Untitled",r.level=typeof r.level=="number"?r.level:1),e==="text"){const a=x(r.html_content)||x(r.html)||x(r.content)||x(r.text);a&&(r.html_content=/<\/?[a-z][\s\S]*>/i.test(a)?a:`<p>${Zn(a)}</p>`)}return e==="button"&&(r.text=x(r.text)||x(r.label)||x(r.title)||"Learn More",r.url=x(r.url)||x(r.href)||x(r.link)||"#"),e==="form"&&(r.fields=to(r.fields),r.submit_button_text=x(r.submit_button_text??r.submitButtonText??r.button_text)||"Send Message",r.success_message=x(r.success_message??r.successMessage)||"Thanks for reaching out. We will reply as soon as possible."),j(e,r,n,o),r}function ye(e,t,n){const o=Ft(e.blockType,le(e.content,`Block ${t}`),`Block ${t}`,n);return{block_type:e.blockType,content:o,order:e.order??t}}function go(e,t="Contact Us",n){return[ye({blockType:"section",content:{is_hero:!0,background:{type:"none"},column_blocks:[[{block_type:"heading",content:{level:1,textAlign:"center",text_content:t},temp_id:he("heading")},{block_type:"text",content:{html_content:"<p>Have a question, project, or support request? Send us a note and we will get back to you soon.</p>"},temp_id:he("text")}]],column_gap:"lg",container_type:"container",padding:{bottom:"xl",top:"xl"},responsive_columns:{desktop:1,mobile:1,tablet:1},vertical_alignment:"center"}},0,n),ye({blockType:"form",content:{fields:[{field_type:"text",is_required:!0,label:"Name",placeholder:"Your name",temp_id:"field-name"},{field_type:"email",is_required:!0,label:"Email",placeholder:"you@example.com",temp_id:"field-email"},{field_type:"textarea",is_required:!0,label:"Message",placeholder:"How can we help?",temp_id:"field-message"}],recipient_email:e,submit_button_text:"Send Message",success_message:"Thanks for reaching out. We will reply as soon as possible."}},1,n)]}function Ve(e,t,n,o){return(!e||e.length===0)&&t?go(t,n,o):(e||[]).map((r,a)=>ye(r,a,o))}async function We(e){const t=e.contentType==="page"?"pages":e.contentType==="post"?"posts":"products",{data:n,error:o}=await e.supabase.from(t).select("id, title, slug, language_id").eq("slug",e.slug).eq("language_id",e.languageId);if(o)throw new Error(`Failed to check ${e.contentType} slug uniqueness: ${h(o)}`);const r=Array.isArray(n)?n:[];return r.length>0?{duplicate:!0,existingItem:r[0],mutationExecuted:!1,success:!1,message:`A ${e.contentType} with slug "${e.slug}" already exists for this language.`}:null}async function He(e){if(!e.suppliedTranslationGroupId)return{translationGroupId:void 0};const t=e.contentType==="page"?"pages":e.contentType==="post"?"posts":"products",{data:n,error:o}=await e.supabase.from(t).select("id, title, slug, language_id, translation_group_id").eq("translation_group_id",e.suppliedTranslationGroupId);if(o)throw new Error(`Failed to inspect ${e.contentType} translation group: ${h(o)}`);const r=Array.isArray(n)?n:[];if(r.length===0)return{result:{message:`The ${e.contentType} translation group "${e.suppliedTranslationGroupId}" was not found.`,mutationExecuted:!1,success:!1},translationGroupId:e.suppliedTranslationGroupId};const a=r.find(s=>Number(s.language_id)===e.languageId);return a?{result:{duplicateTranslation:!0,existingItem:a,message:`A ${e.contentType} translation already exists for ${e.languageCode} in this translation group.`,mutationExecuted:!1,success:!1},translationGroupId:e.suppliedTranslationGroupId}:{translationGroupId:e.suppliedTranslationGroupId}}async function Ot(e){if(e.blocks.length===0)return[];const t=e.blocks.map((r,a)=>({block_type:r.block_type,content:r.content,language_id:e.languageId,order:r.order??a,page_id:e.contentType==="page"?e.itemId:null,post_id:e.contentType==="post"?e.itemId:null})),{data:n,error:o}=await e.supabase.from("blocks").insert(t).select("*");if(o)throw new Error(`Failed to insert ${e.contentType} blocks: ${h(o)}`);return ce(e.blocks,e.supabase),Array.isArray(n)?n:[]}async function qt(e){const t=e.contentType==="page"?"pages":"posts";await e.supabase.from(t).delete().eq("id",e.itemId)}function Je(e,t){return e==="page"?`/cms/pages/${t}/edit`:e==="post"?`/cms/posts/${t}/edit`:`/cms/products/${t}/edit`}function ht(e){return e==="page"?"/cms/pages":e==="post"?"/cms/posts":"/cms/products"}async function Ye(e,t){const n=H.parse(e),o=I(t);n.mode==="replace"&&await Yn({items:n.items,languageCode:n.languageCode,menuKey:"HEADER",supabase:o});const r=A({action:"UPDATE NAVIGATION",context:t,payload:{input:n,tool:"update_navigation_bar"},preview:{itemCount:n.items.length,languageCode:n.languageCode,mode:n.mode,target:"header navigation"},subject:`${n.mode} header`});if(r)return r;const a=n.mode==="update"?await Xn({items:n.items,languageCode:n.languageCode,match:n.match,menuKey:"HEADER",supabase:o}):n.mode==="append"?await Qn({items:n.items,languageCode:n.languageCode,menuKey:"HEADER",supabase:o}):await Nt({items:n.items,languageCode:n.languageCode,menuKey:"HEADER",supabase:o});return Ct(t),{...a,mutationExecuted:!0,mode:n.mode,success:!0}}async function Xe(e,t){const n=J.parse(e);if(!n.links?.length&&!n.copyright)throw new Error("update_footer requires links or copyright.");const o=I(t),r=A({action:"UPDATE FOOTER",context:t,payload:{input:n,tool:"update_footer"},preview:{copyrightUpdated:!!n.copyright,linkCount:n.links?.length||0,languageCode:n.languageCode,target:"footer"},subject:n.languageCode});if(r)return r;let a=null;if(n.links?.length&&(a=await Nt({items:n.links,languageCode:n.languageCode,menuKey:"FOOTER",supabase:o})),n.copyright){const{error:s}=await o.from("site_settings").upsert({key:"footer_copyright",value:n.copyright});if(s)throw new Error(`Failed to update footer copyright: ${h(s)}`)}return Ct(t),{copyrightUpdated:!!n.copyright,footerNavigation:a,mutationExecuted:!0,success:!0}}function Bt(e){return typeof e=="string"?e.toLowerCase():""}function fo(e,t){const n=t.map(Bt).join(" ");return e.reduce((o,r)=>o+(n.includes(r)?1:0),0)}function _t(e,t){return(e.find(n=>t.some(o=>Bt(n).includes(o)))||e.find(n=>n.trim().length>0)||"No excerpt available.").slice(0,500)}async function jt(e,t){const n=be.parse(e),o=I(t),r=n.query.toLowerCase().split(/\s+/).map(c=>c.trim()).filter(Boolean),[a,s]=await Promise.all([o.from("posts").select("id, title, slug, excerpt, subtitle, meta_description, status, updated_at").eq("status","published").limit(100),o.from("pages").select("id, title, slug, meta_description, status, updated_at").eq("status","published").limit(100)]);if(a.error)throw new Error(`Failed to search documentation posts: ${h(a.error)}`);if(s.error)throw new Error(`Failed to search documentation pages: ${h(s.error)}`);const l=(a.data??[]).map(c=>({excerpt:_t([c.excerpt,c.subtitle,c.meta_description,c.slug].filter(Boolean),r),source:"post",title:c.title,url:`/article/${c.slug}`})),u=(s.data??[]).map(c=>({excerpt:_t([c.meta_description,c.slug].filter(Boolean),r),source:"page",title:c.title,url:c.slug==="home"?"/":`/${c.slug}`})),d=[...l,...u].map(c=>({...c,score:fo(r,[c.title,c.excerpt,c.url])})).filter(c=>c.score>0).sort((c,p)=>p.score-c.score).slice(0,n.limit).map(c=>({excerpt:c.excerpt,source:c.source,title:c.title,url:c.url}));return{query:n.query,results:d,success:!0}}async function Lt(e,t,n=an){const o=be.safeParse(e),r=o.success?o.data.query:"";return vn(jt(e,t),n,()=>({message:"Documentation search took too long to respond. Please try again or ask a more specific question.",query:r,results:[],success:!1,timedOut:!0}))}const ho=["pending","trial","paid","shipped","cancelled","refunded","failed"],_o={awaiting:"pending",canceled:"cancelled",cancelled:"cancelled",complete:"paid",completed:"paid",failed:"failed",paid:"paid",payment_pending:"pending",pending:"pending",refund:"refunded",refunded:"refunded",refunds:"refunded",shipped:"shipped",trial:"trial",trials:"trial"};function yo(e){return String(e??"unknown").trim().toLowerCase()||"unknown"}function yt(e){const t=Object.fromEntries(ho.map(n=>[n,0]));for(const n of e){const o=yo(n.status);t[o]=(t[o]??0)+1}return t}function bo(e){const n=e.toLowerCase().replace(/[^a-z0-9_]+/g," ").split(/\s+/).filter(Boolean);for(const o of n){const r=_o[o];if(r)return r}return null}function V(e){const t=Number(e);return Number.isFinite(t)?t:0}async function Rt(e,t){const n=Oe.parse(e),o=I(t),r=new Date;let a=null,s=null;switch(n.timeRange){case"today":a=new Date(r.getFullYear(),r.getMonth(),r.getDate());break;case"this_month":a=new Date(r.getFullYear(),r.getMonth(),1);break;case"last_7_days":a=new Date(r.getTime()-10080*60*1e3);break;case"last_30_days":a=new Date(r.getTime()-720*60*60*1e3);break;case"last_month":a=new Date(r.getFullYear(),r.getMonth()-1,1),s=new Date(r.getFullYear(),r.getMonth(),0,23,59,59,999);break;case"last_90_days":a=new Date(r.getTime()-2160*60*60*1e3);break;case"all_time":a=null;break}const l=n.currency?.toUpperCase(),u=bo(n.query),d=o.from("orders").select("id, status, total, currency, created_at, paid_at");l&&d.eq("currency",l),a&&d.gte("created_at",a.toISOString()),s&&d.lte("created_at",s.toISOString());const p=n.reportType==="products"||n.reportType==="revenue"||n.reportType==="general"?o.from("order_items").select(`
2
2
  quantity,
3
3
  price_at_purchase,
4
4
  products!inner (
@@ -12,4 +12,4 @@
12
12
  paid_at,
13
13
  currency
14
14
  )
15
- `).eq("orders.status","paid"):null;d&&(l&&d.eq("orders.currency",l),a&&d.gte("orders.paid_at",a.toISOString()),s&&d.lte("orders.paid_at",s.toISOString()));const p=t.timeRange!=="all_time"&&(t.reportType==="orders"||m)?r.from("orders").select("id, status, currency"):null;p&&l&&p.eq("currency",l);const[{data:_,error:k},{data:S,error:v},E]=await Promise.all([u,d??Promise.resolve({data:[],error:null}),p??Promise.resolve({data:null,error:null})]);if(k)throw new Error(`Failed to fetch ecommerce stats: ${f(k)}`);if(v)throw new Error(`Failed to fetch ecommerce stats: ${f(v)}`);if(E.error)throw new Error(`Failed to fetch ecommerce stats: ${f(E.error)}`);const h=Array.isArray(_)?_:[],z=Array.isArray(S)?S:[],A=ot(h),T=Array.isArray(E.data)?E.data:null,U=T?ot(T):null,te={};for(const I of z){const C=Array.isArray(I.orders)?I.orders[0]:I.orders,P=String(C?.currency||l||"unknown").toUpperCase();te[P]=(te[P]??0)+M(I.quantity)*M(I.price_at_purchase)/100}const ne={currency:l??null,currencyFiltered:!!l,orderStatusCounts:A,paidOrderCount:A.paid??0,query:t.query,reportType:t.reportType,revenueByCurrency:te,timeRange:t.timeRange,totalOrders:h.length,totalRevenue:Object.values(te).reduce((I,C)=>I+C,0)};if(U&&(ne.allTimeOrderStatusCounts=U),m&&(ne.matchingOrderStatus={allTimeCount:U?.[m]??A[m]??0,count:A[m]??0,status:m,timeRange:t.timeRange}),t.reportType==="products"||t.reportType==="revenue"||t.reportType==="general"){const I={};for(const C of z){const P=Array.isArray(C.products)?C.products[0]:C.products;if(!P?.id)continue;const D=P.id;I[D]||(I[D]={id:D,quantity:0,revenue:0,title:P.title,type:P.product_type}),I[D].quantity+=M(C.quantity),I[D].revenue+=M(C.quantity)*M(C.price_at_purchase)/100}ne.topProducts=Object.values(I).sort((C,P)=>P.revenue-C.revenue).slice(0,10)}return{report:ne,success:!0}}async function xt(e,n){const t=ze.parse(e),r=y(n),i=me(n),a=$e(i),s=i.contentType==="page"?"pages":i.contentType==="post"?"posts":"products",{data:l,error:m}=await r.from(s).select("*").eq("id",a).single();if(m||!l)throw new Error(`Failed to read current ${i.contentType}: ${f(m)}`);let u=[];if(t.includeBlocks&&i.contentType!=="product"){const c=i.contentType==="page"?"page_id":"post_id",{data:d,error:g}=await r.from("blocks").select("id, page_id, post_id, language_id, block_type, content, order").eq(c,a);if(g)throw new Error(`Failed to read current ${i.contentType} blocks: ${f(g)}`);u=(Array.isArray(d)?d:[]).slice().sort((p,_)=>Number(p.order)-Number(_.order)).map(p=>yn(p,t.includeBlockContent))}return{blocks:u,context:i,item:l,success:!0}}const Tt=new Set(["feature_image_id","language_id","meta_description","meta_title","slug","status","title"]),$t=new Set(["excerpt","feature_image_id","label","language_id","meta_description","meta_title","published_at","slug","status","subtitle","title"]),jn=new Set(["description_json","language_id","meta_description","meta_title","short_description","slug","status","title"]),qn=new Set(["excerpt","feature_image_id","label","meta_description","meta_title","published_at","short_description","subtitle"]);function On(e){return e==="page"?Tt:e==="post"?$t:jn}function vt(e,n){return qn.has(e)&&n===""?null:n}function he(e,n){if(typeof n!="string")return;const t=e==="product"?["active","archived","draft"]:["archived","draft","published"];if(!t.includes(n))throw new Error(`Status "${n}" is not valid for ${e}. Allowed statuses: ${t.join(", ")}.`)}function Un(e,n){const t=On(n.contentType),r={};for(const[i,a]of Object.entries(e))if(a!==void 0){if(!t.has(i))throw new Error(`Field "${i}" cannot be updated for ${n.contentType} content.`);i==="status"&&he(n.contentType,a),r[i]=vt(i,a)}return r}async function Ue(e,n){const t=K.parse(e),r=y(n),i=me(n),a=$e(i),s=Un(t.fields,i),l=Object.keys(s);if(l.length===0)throw new Error("update_current_cms_fields requires at least one supported field.");const m=x({action:"UPDATE CMS FIELDS",context:n,payload:{contentType:i.contentType,entityId:a,fields:s,tool:"update_current_cms_fields"},preview:{contentType:i.contentType,entityId:a,fields:l,slug:i.slug,title:i.title},subject:`${i.contentType} ${String(a)}`});if(m)return m;const u=i.contentType==="page"?"pages":i.contentType==="post"?"posts":"products",{data:c,error:d}=await r.from(u).update({...s,updated_at:new Date().toISOString()}).eq("id",a).select("id, language_id, slug, status, title").single();if(d||!c)throw new Error(`Failed to update current ${i.contentType}: ${f(d)}`);return B(n,i,c.slug),{contentType:i.contentType,entityId:a,mutationExecuted:!0,slug:c.slug,success:!0,updatedFields:l}}async function De(e,n){const t=V.parse(e),r=y(n),i=me(n),{data:a,error:s}=await r.from("blocks").select("id, page_id, post_id, language_id, block_type, content, order").eq("id",t.blockId).single();if(s||!a)throw new Error(`Failed to read block ${t.blockId}: ${f(s)}`);dt(a,i);const l=se(a.block_type,`Block ${t.blockId}`);pt(t.blockType,l,`Block ${t.blockId}`);const m=ee(a.content,`Block ${t.blockId}`),u=hn(l,m,t.content,n);j(l,u,`Block ${t.blockId}`,n);const c=x({action:"UPDATE CONTENT BLOCK",context:n,payload:{blockId:t.blockId,blockType:l,content:u,tool:"update_content_block"},preview:{blockId:t.blockId,blockType:l,contentType:i.contentType,entityId:$e(i)},subject:`${l} block ${t.blockId}`});if(c)return c;const{data:d,error:g}=await r.from("blocks").update({content:u,updated_at:new Date().toISOString()}).eq("id",t.blockId).select("id, block_type, order").single();if(g||!d)throw new Error(`Failed to update block ${t.blockId}: ${f(g)}`);return B(n,i),{blockId:d.id,blockType:d.block_type,contentUpdated:!0,mutationExecuted:!0,success:!0}}async function Me(e,n){const t=W.parse(e),r=y(n),i=await Be(t,n);if(i.contentType==="product")throw new Error("Products do not have page/post content blocks in this editor context.");const a=Number(i.item.id),s=i.contentType==="page"?"page_id":"post_id",l=async()=>{const{data:h,error:z}=await r.from("blocks").select("id, page_id, post_id, language_id, block_type, content, order").eq(s,a);if(z)throw new Error(`Failed to read ${i.contentType} blocks: ${f(z)}`);return(Array.isArray(h)?h:[]).sort((A,T)=>Number(A.order)-Number(T.order))},m=h=>{if(t.position==="start")return 0;if(t.position==="end"){const T=h.map(U=>Number(U.order)).filter(Number.isFinite);return T.length>0?Math.max(...T)+1:0}const z=t.anchorBlockId?h.find(T=>Number(T.id)===t.anchorBlockId):t.anchorBlockType?h.find(T=>T.block_type===t.anchorBlockType):null;if(!z)throw new Error(t.anchorBlockType?`Could not find a ${t.anchorBlockType} block to insert ${t.position}.`:`Could not find block ${t.anchorBlockId} to insert ${t.position}.`);const A=Number(z.order);return t.position==="before"?A:A+1},u=ue(t.block,0,n),c=await l(),d=m(c),g={contentType:i.contentType,entityId:i.item.id,languageId:i.item.language_id,slug:i.item.slug,title:i.item.title,translationGroupId:i.item.translation_group_id},p=x({action:"INSERT CONTENT BLOCK",context:n,payload:{block:u,order:d,target:{contentType:i.contentType,id:i.item.id,slug:i.item.slug},tool:"insert_content_block"},preview:{anchorBlockId:t.anchorBlockId,anchorBlockType:t.anchorBlockType,blockType:u.block_type,contentType:i.contentType,entityId:i.item.id,position:t.position,slug:i.item.slug,summary:`Insert ${u.block_type} block ${t.position} ${t.anchorBlockType?`the first ${t.anchorBlockType} block`:t.anchorBlockId?`block ${t.anchorBlockId}`:"the content"} on ${i.contentType} "${i.item.title||i.item.slug}".`,title:i.item.title},subject:`${u.block_type} block on ${i.contentType} ${i.item.id}`});if(p)return p;const _=await l(),k=m(_),S=_.filter(h=>Number(h.order)>=k).sort((h,z)=>Number(z.order)-Number(h.order));for(const h of S){const{error:z}=await r.from("blocks").update({order:Number(h.order)+1,updated_at:new Date().toISOString()}).eq("id",h.id);if(z)throw new Error(`Failed to shift block ${h.id}: ${f(z)}`)}const{data:v,error:E}=await r.from("blocks").insert({block_type:u.block_type,content:u.content,language_id:i.item.language_id,order:k,page_id:i.contentType==="page"?a:null,post_id:i.contentType==="post"?a:null}).select("id, block_type, order").single();if(E||!v)throw new Error(`Failed to insert content block: ${f(E)}`);return B(n,g),{blockId:v.id,blockType:v.block_type,contentType:i.contentType,entityId:i.item.id,mutationExecuted:!0,order:v.order,success:!0}}async function Le(e,n){const t=J.parse(e),r=y(n),i=me(n),{data:a,error:s}=await r.from("blocks").select("id, page_id, post_id, language_id, block_type, content, order").eq("id",t.parentBlockId).single();if(s||!a)throw new Error(`Failed to read parent block ${t.parentBlockId}: ${f(s)}`);dt(a,i);const l=se(a.block_type,`Parent block ${t.parentBlockId}`);if(l!=="section")throw new Error(`Parent block ${t.parentBlockId} must be a section block, not "${l}".`);const m=ee(a.content,`Parent block ${t.parentBlockId}`);j(l,m,`Parent block ${t.parentBlockId}`,n);const c=m.column_blocks?.[t.columnIndex]?.[t.blockIndex];if(!c)throw new Error(`Nested block was not found at column ${t.columnIndex}, index ${t.blockIndex}.`);const d=se(c.block_type,`Nested block ${t.columnIndex}:${t.blockIndex}`);pt(t.blockType,d,`Nested block ${t.columnIndex}:${t.blockIndex}`),j(d,t.content,`Nested block ${t.columnIndex}:${t.blockIndex}`,n);const g=m.column_blocks.map((v,E)=>E===t.columnIndex?v.map((h,z)=>z===t.blockIndex?{...h,content:t.content}:h):v),p={...m,column_blocks:g};j(l,p,`Updated parent block ${t.parentBlockId}`,n);const _=x({action:"UPDATE NESTED BLOCK",context:n,payload:{blockIndex:t.blockIndex,columnIndex:t.columnIndex,content:t.content,nestedBlockType:d,parentBlockId:t.parentBlockId,tool:"update_section_column_block"},preview:{blockIndex:t.blockIndex,columnIndex:t.columnIndex,nestedBlockType:d,parentBlockId:t.parentBlockId,parentBlockType:l},subject:`${d} nested block ${t.columnIndex}:${t.blockIndex}`});if(_)return _;const{data:k,error:S}=await r.from("blocks").update({content:p,updated_at:new Date().toISOString()}).eq("id",t.parentBlockId).select("id, block_type").single();if(S||!k)throw new Error(`Failed to update parent block ${t.parentBlockId}: ${f(S)}`);return B(n,i),{blockIndex:t.blockIndex,columnIndex:t.columnIndex,mutationExecuted:!0,nestedBlockType:d,parentBlockId:k.id,parentBlockType:k.block_type,success:!0}}async function Ge(e,n){const t=H.parse(e),r=y(n),i=ut(n),a=await Pe(r,t.languageCode),s=ge(t.slug||t.title),l=ht(t.blocks,t.contactEmail,t.title,n),m=await Fe({contentType:"page",languageId:a.id,slug:s,supabase:r});if(m)return m;const u=await Ne({contentType:"page",languageCode:a.code,languageId:a.id,suppliedTranslationGroupId:t.translationGroupId,supabase:r});if(u.result)return u.result;const c={blocks:l,item:{feature_image_id:t.feature_image_id??null,language_id:a.id,meta_description:t.meta_description??null,meta_title:t.meta_title??null,slug:s,status:t.status,title:t.title,translation_group_id:u.translationGroupId},tool:"create_cms_page"},d=x({action:"CREATE PAGE",context:n,payload:c,preview:{blockCount:l.length,languageCode:a.code,slug:s,status:t.status,title:t.title,translationGroupId:u.translationGroupId},subject:s});if(d)return d;const g=u.translationGroupId||Se(),{data:p,error:_}=await r.from("pages").insert({...c.item,author_id:i,translation_group_id:g}).select("id, language_id, slug, status, title, translation_group_id").single();if(_||!p?.id)throw new Error(`Failed to create page: ${f(_)}`);try{await yt({blocks:l,contentType:"page",itemId:Number(p.id),languageId:a.id,supabase:r})}catch(k){throw await kt({contentType:"page",itemId:Number(p.id),supabase:r}),k}return B(n,{contentType:"page",entityId:Number(p.id),languageId:a.id,slug:s,title:t.title},s),n?.revalidatePath?.("/cms/pages"),{blockCount:l.length,contentType:"page",editPath:je("page",p.id),entityId:p.id,mutationExecuted:!0,slug:s,success:!0,title:t.title,translationGroupId:p.translation_group_id}}async function Re(e,n){const t=Y.parse(e),r=y(n),i=ut(n),a=await Pe(r,t.languageCode),s=ge(t.slug||t.title),l=ht(t.blocks,void 0,void 0,n),m=await Fe({contentType:"post",languageId:a.id,slug:s,supabase:r});if(m)return m;const u=await Ne({contentType:"post",languageCode:a.code,languageId:a.id,suppliedTranslationGroupId:t.translationGroupId,supabase:r});if(u.result)return u.result;const c=t.published_at&&!Number.isNaN(new Date(t.published_at).getTime())?new Date(t.published_at).toISOString():t.published_at??null,d={blocks:l,item:{excerpt:t.excerpt??null,feature_image_id:t.feature_image_id??null,label:t.label??null,language_id:a.id,meta_description:t.meta_description??null,meta_title:t.meta_title??null,published_at:c,slug:s,status:t.status,subtitle:t.subtitle??null,title:t.title,translation_group_id:u.translationGroupId},tool:"create_cms_post"},g=x({action:"CREATE POST",context:n,payload:d,preview:{blockCount:l.length,languageCode:a.code,slug:s,status:t.status,title:t.title,translationGroupId:u.translationGroupId},subject:s});if(g)return g;const p=u.translationGroupId||Se(),{data:_,error:k}=await r.from("posts").insert({...d.item,author_id:i,translation_group_id:p}).select("id, language_id, slug, status, title, translation_group_id").single();if(k||!_?.id)throw new Error(`Failed to create post: ${f(k)}`);try{await yt({blocks:l,contentType:"post",itemId:Number(_.id),languageId:a.id,supabase:r})}catch(S){throw await kt({contentType:"post",itemId:Number(_.id),supabase:r}),S}return B(n,{contentType:"post",entityId:Number(_.id),languageId:a.id,slug:s,title:t.title},s),n?.revalidatePath?.("/cms/posts"),n?.revalidatePath?.("/articles"),{blockCount:l.length,contentType:"post",editPath:je("post",_.id),entityId:_.id,mutationExecuted:!0,slug:s,success:!0,title:t.title,translationGroupId:_.translation_group_id}}function Dn(e,n){return(n||ge(e)||"product").replace(/-/g,"").slice(0,24).toUpperCase()}function St(e){if(e===void 0)return;const n=on().safeParse(e);if(!n.success)throw new Error(`Product description_json failed editor document validation: ${n.error.issues.map(t=>t.message).join("; ")}`);return n.data}async function Ke(e,n){const t=Q.parse(e),r=y(n),i=await Pe(r,t.languageCode),a=ge(t.slug||t.title),s=await Fe({contentType:"product",languageId:i.id,slug:a,supabase:r});if(s)return s;const l=await Ne({contentType:"product",languageCode:i.code,languageId:i.id,suppliedTranslationGroupId:t.translationGroupId,supabase:r});if(l.result)return l.result;const{createProduct:m,productSchema:u}=await ve(),d=t.product_type==="digital"&&t.payment_provider==="freemius"?t.trial_period_days:0,g=u.parse({description_json:St(t.description_json),freemius_plan_id:t.freemius_plan_id||"",freemius_product_id:t.freemius_product_id||"",is_taxable:t.is_taxable,language_id:i.id,meta_description:t.meta_description??"",meta_title:t.meta_title??"",payment_provider:t.payment_provider,price:t.price,prices:t.prices||{},product_media:[],product_type:t.product_type,sale_price:t.sale_price??null,sale_prices:t.sale_prices||{},short_description:t.short_description??"",sku:t.sku||Dn(t.title,a),slug:a,status:t.status,stock:t.stock,title:t.title,trial_period_days:d,trial_requires_payment_method:d>0?t.trial_requires_payment_method:!1,translation_group_id:l.translationGroupId,upc:t.upc??"",variation_attributes:[],variants:[]}),p=x({action:"CREATE PRODUCT",context:n,payload:{item:g,tool:"create_cms_product"},preview:{languageCode:i.code,price:g.price,sku:g.sku,slug:a,status:g.status,stock:g.stock,title:g.title,translationGroupId:l.translationGroupId},subject:a});if(p)return p;const _=await m(r,g);if(!_?.id)throw new Error("Failed to create product.");return B(n,{contentType:"product",entityId:_.id,languageId:i.id,slug:a,title:t.title},a),n?.revalidatePath?.("/cms/products"),{contentType:"product",editPath:je("product",_.id),entityId:_.id,mutationExecuted:!0,slug:a,success:!0,title:t.title,translationGroupId:_.translation_group_id}}function Ve(e){return e.trim().replace(/[\s-]+/g,"_").toLowerCase()}function Mn(e,n){const t=typeof n=="string"?Ve(n):n;return e==="product"?t==="public"||t==="publish"||t==="published"?"active":t:t==="public"||t==="active"||t==="publish"?"published":t}function Ln(e){const n=Ve(e.field);return!!(e.startsAt||e.endsAt||n.includes("start")||n.includes("end")||n.includes("schedule")||n.includes("special_date"))}async function Gn(e,n,t){const r=await kn(n),{productSchema:i}=await ve();return i.parse({description_json:t.description_json!==void 0?St(t.description_json):e.description_json||void 0,freemius_plan_id:e.freemius_plan_id||"",freemius_product_id:e.freemius_product_id||"",is_taxable:t.is_taxable??e.is_taxable??!0,language_id:t.language_id??e.language_id,meta_description:t.meta_description??e.meta_description??"",meta_title:t.meta_title??e.meta_title??"",payment_provider:t.payment_provider??e.payment_provider??"stripe",price:t.price!==void 0?t.price:mn(e.price,r),prices:t.prices??Xe(e.prices,r),product_media:void 0,product_type:t.product_type??e.product_type??"physical",sale_price:t.sale_price!==void 0?t.sale_price:e.sale_price===null||e.sale_price===void 0?null:Ae(Number(e.sale_price),r),sale_prices:t.sale_prices??Xe(e.sale_prices,r),short_description:t.short_description??e.short_description??"",sku:t.sku??e.sku,slug:t.slug??e.slug,status:t.status??e.status??"draft",stock:t.stock??e.stock??0,title:t.title??e.title,trial_period_days:t.trial_period_days??e.trial_period_days??0,trial_requires_payment_method:t.trial_requires_payment_method??e.trial_requires_payment_method??!1,upc:t.upc??e.upc??"",variation_attributes:[],variants:[]})}function Rn(e,n){const t=Ve(e.field),r=t==="status"?Mn(n.contentType,e.value):e.value,a={description:"description_json",feature_image:"feature_image_id",feature_image_id:"feature_image_id",language:"language_id",meta_description:"meta_description",meta_title:"meta_title",payment:"payment_provider",provider:"payment_provider",regular_price:"price",sale:"sale_price",sale_price:"sale_price",short_description:"short_description",taxable:"is_taxable",trial:"trial_period_days",trial_days:"trial_period_days",trial_payment_method_required:"trial_requires_payment_method",type:"product_type"}[t]||t;if(n.contentType!=="product"){if(!(n.contentType==="page"?Tt:$t).has(a))throw new Error(`Field "${e.field}" cannot be updated for ${n.contentType}.`);return a==="status"&&he(n.contentType,r),{field:a,payload:{[a]:vt(a,r)}}}if(!new Set(["description_json","freemius_plan_id","freemius_product_id","is_taxable","language_id","meta_description","meta_title","payment_provider","price","prices","product_type","sale_price","sale_prices","short_description","sku","slug","status","stock","title","trial_period_days","trial_requires_payment_method","upc"]).has(a))throw new Error(`Field "${e.field}" cannot be updated for product.`);if(a==="status"&&he("product",r),(a==="price"||a==="sale_price")&&r!==null&&(typeof r!="number"||r<0))throw new Error(`${a} must be a non-negative number or null.`);if(a==="stock"&&(!Number.isInteger(r)||Number(r)<0))throw new Error("stock must be a non-negative integer.");if(a==="trial_period_days"&&(!Number.isInteger(r)||Number(r)<0))throw new Error("trial_period_days must be a non-negative integer.");if(a==="trial_requires_payment_method"&&typeof r!="boolean")throw new Error("trial_requires_payment_method must be a boolean.");return{field:a,payload:{[a]:r}}}async function Je(e,n){const t=X.parse(e);if(Ln(t))return{message:"Scheduled product specials are not supported by the current product schema yet. I can set or clear sale_price now, but not start/end dates.",mutationExecuted:!1,success:!1,unsupported:!0};const r=await Be(t,n),i=Rn(t,r),a=i.field;let s=i.payload;if(a==="language_id"&&typeof s.language_id=="string"){const d=await O(y(n),s.language_id);s={...s,language_id:d.id}}const l=x({action:"UPDATE FIELD",context:n,payload:{contentType:r.contentType,entityId:r.item.id,field:a,payload:s,tool:"update_cms_item_field"},preview:{contentType:r.contentType,field:a,from:r.item[a],slug:r.item.slug,title:r.item.title,to:s[a]},subject:`${r.contentType} ${r.item.slug||r.item.id} ${a}`});if(l)return l;if(r.contentType==="product"){const{updateProduct:d}=await ve(),g=await Gn(r.item,y(n),s),p=await d(y(n),String(r.item.id),g);return B(n,{contentType:"product",entityId:String(r.item.id),languageId:p?.language_id??r.item.language_id,slug:p?.slug??r.item.slug,title:p?.title??r.item.title},p?.slug??r.item.slug),{contentType:"product",entityId:r.item.id,field:a,mutationExecuted:!0,slug:p?.slug??r.item.slug,success:!0,updatedFields:[a]}}const m=r.contentType==="page"?"pages":"posts",{data:u,error:c}=await y(n).from(m).update({...s,updated_at:new Date().toISOString()}).eq("id",r.item.id).select("id, language_id, slug, status, title").single();if(c||!u)throw new Error(`Failed to update ${r.contentType}: ${f(c)}`);return B(n,{contentType:r.contentType,entityId:Number(u.id),languageId:u.language_id,slug:u.slug,title:u.title},u.slug),{contentType:r.contentType,entityId:u.id,field:a,mutationExecuted:!0,slug:u.slug,success:!0,updatedFields:[a]}}async function Et(e,n){const t=Ce.parse(e),r=await Be(t,n);if(r.contentType==="product")return{affectedCount:1,collectionPath:tt("product"),contentType:"product",item:r.item,navigationLinkCount:0,publicPaths:r.item.slug?[`/product/${r.item.slug}`]:[],targetIds:[r.item.id]};const i=r.contentType==="page"?"pages":"posts",{data:a,error:s}=await y(n).from(i).select("id, slug, title, translation_group_id").eq("translation_group_id",r.item.translation_group_id);if(s)throw new Error(`Failed to inspect related ${r.contentType}s: ${f(s)}`);const l=Array.isArray(a)?a:[],m=l.map(p=>r.contentType==="page"?p.slug==="home"?"/":`/${p.slug}`:`/article/${p.slug}`).filter(Boolean),u=new Set(m),{data:c,error:d}=await y(n).from("navigation_items").select("id, url");if(d)throw new Error(`Failed to inspect related navigation links: ${f(d)}`);const g=(Array.isArray(c)?c:[]).filter(p=>u.has(p.url)).length;return{affectedCount:l.length,collectionPath:tt(r.contentType),contentType:r.contentType,item:r.item,navigationLinkCount:g,publicPaths:m,targetIds:l.map(p=>p.id)}}function At(e){const n=e.item.title||e.item.slug||"selected item",t=e.item.slug?` (${e.item.slug})`:"";if(e.contentType==="product")return`Delete product "${n}"${t}.`;const r=[`${F(e.affectedCount,"language version")}`,e.navigationLinkCount>0?`${F(e.navigationLinkCount,"navigation link")}`:null].filter(Boolean);return`Delete ${e.contentType} "${n}"${t}, including ${r.join(" and ")}.`}async function Pt(e,n){const t=await Et(e,n);return{...ct({action:`DELETE ${t.contentType}`,payload:{affectedCount:t.affectedCount,contentType:t.contentType,targetIds:t.targetIds,tool:"delete_cms_item"},preview:{affectedCount:t.affectedCount,collectionPath:t.collectionPath,contentType:t.contentType,navigationLinkCount:t.navigationLinkCount,publicPaths:t.publicPaths,slug:t.item.slug,summary:At(t),title:t.item.title},subject:`${t.item.id} ${t.item.slug||""}`}),preparedDelete:!0}}async function We(e,n){const t=Z.parse(e),r=await Et(t,n),i=x({action:`DELETE ${r.contentType}`,context:n,payload:{affectedCount:r.affectedCount,contentType:r.contentType,targetIds:r.targetIds,tool:"delete_cms_item"},preview:{affectedCount:r.affectedCount,collectionPath:r.collectionPath,contentType:r.contentType,navigationLinkCount:r.navigationLinkCount,publicPaths:r.publicPaths,slug:r.item.slug,summary:At(r),title:r.item.title},subject:`${r.item.id} ${r.item.slug||""}`});if(i)return i;const a=y(n);if(r.contentType==="product"){const{error:l}=await a.from("products").delete().eq("id",r.item.id);if(l)throw new Error(`Failed to delete product: ${f(l)}`)}else{for(const u of r.publicPaths)await a.from("navigation_items").delete().eq("url",u);const l=r.contentType==="page"?"pages":"posts",{error:m}=await a.from(l).delete().eq("translation_group_id",r.item.translation_group_id);if(m)throw new Error(`Failed to delete ${r.contentType}: ${f(m)}`)}const s=n?.revalidatePath??Te();return s&&(s(r.collectionPath),s("/cms/navigation"),r.publicPaths.forEach(l=>s(l))),{affectedCount:r.affectedCount,collectionPath:r.collectionPath,contentType:r.contentType,mutationExecuted:!0,redirectPath:r.collectionPath,success:!0}}async function rt(e,n){switch(e.tool){case"create_cms_page":return Ge(e.input,n);case"create_cms_post":return Re(e.input,n);case"create_cms_product":return Ke(e.input,n);case"delete_cms_item":return We(e.input,n);case"update_cms_item_field":return Je(e.input,n);case"update_content_block":return De(e.input,n);case"insert_content_block":return Me(e.input,n);case"update_current_cms_fields":return Ue(e.input,n);case"update_footer":return Oe(e.input,n);case"update_navigation_bar":return qe(e.input,n);case"update_section_column_block":return Le(e.input,n)}}function Kn(e,n){if(e.tool!=="create_cms_page"&&e.tool!=="create_cms_post"&&e.tool!=="create_cms_product"||e.input.translationGroupId||!e.input.languageCode)return e;const t=n[e.tool];return t?{...e,input:{...e.input,translationGroupId:t}}:e}async function Bt(e,n){const t=xe.parse(e);if(!n?.skipConfirmation){const u=[];for(const g of t.actions){const p=await rt(g,{...n,latestUserMessage:null});if(!p||typeof p!="object")return{message:`Could not prepare action ${u.length+1}.`,mutationExecuted:!1,success:!1};if(p.success===!1||p.unsupported===!0)return p;p.requiresConfirmation===!0&&p.preview?u.push(pn(g.tool,p.preview)):u.push(`Run ${g.tool.replace(/_/g," ")}.`)}const c=t.summary||`Complete ${F(t.actions.length,"CMS action")}.`,d=x({action:"EXECUTE CMS ACTION PLAN",context:n,payload:{actions:t.actions,tool:"execute_cms_action_plan"},preview:{actionCount:t.actions.length,actionSummaries:u,summary:c},subject:`${t.actions.length} actions`});if(d)return d}const r={...n,skipConfirmation:!0},i=[];let a=!1,s=null,l=null;const m={};for(const[u,c]of t.actions.entries()){const d=Kn(c,m),g=await rt(d,r);if(i.push({output:g,tool:d.tool}),g&&typeof g=="object"){const p=g;if(p.mutationExecuted===!0&&(a=!0),!s&&typeof p.editPath=="string"&&(s=p.editPath),typeof p.redirectPath=="string"&&(l=p.redirectPath),(d.tool==="create_cms_page"||d.tool==="create_cms_post"||d.tool==="create_cms_product")&&typeof p.translationGroupId=="string"&&(m[d.tool]=p.translationGroupId),p.success===!1||p.unsupported===!0)return{actionCount:t.actions.length,failedActionIndex:u,failedTool:d.tool,message:typeof p.message=="string"?p.message:`Action ${u+1} failed.`,mutationExecuted:a,results:i,success:!1,...s?{editPath:s}:{},...l?{redirectPath:l}:{}}}}return{actionCount:t.actions.length,editPath:l?void 0:s??void 0,mutationExecuted:a,redirectPath:l??void 0,results:i,success:!0,summary:t.summary??null}}function Vn(e){return{...Ft.createCortexDatabaseAgentTools(e),...Nt.createCortexCustomBlockTools(e),fetch_ecommerce_stats:w.tool({description:"Fetch quantitative ecommerce statistics and reports from the database. Use this to answer questions about revenue, order counts, order status counts such as pending or trial, and top-selling products over a time range. This tool is read-only and does not require confirmation.",execute:n=>Ct(n,e),inputSchema:ke,strict:!0}),read_current_cms_item:w.tool({description:"Read the CMS item currently being edited. Requires pageContext and returns page/post/product metadata plus page/post block summaries or content.",execute:n=>xt(n,e),inputSchema:ze,strict:!0}),search_documentation:w.tool({description:"Search the NextBlock documentation database and return concise source snippets for factual CMS guidance.",execute:n=>It(n,e),inputSchema:de,strict:!0}),create_cms_page:w.tool({description:"Create a new CMS page with metadata and optional validated page blocks. Mutating: first returns a confirmation phrase; only executes after the user replies with the exact phrase. For translations, pass translationGroupId from the source page/post/product context so the new language is linked to the same backend translation group. For contact pages, provide contactEmail or a form block with recipient_email and fields.",execute:n=>Ge(n,e),inputSchema:H,strict:!0}),create_cms_post:w.tool({description:"Create a new CMS post with metadata and optional validated post blocks. Mutating: first returns a confirmation phrase; only executes after the user replies with the exact phrase. For translations, pass translationGroupId from the source post context so the new language is linked to the same backend translation group.",execute:n=>Re(n,e),inputSchema:Y,strict:!0}),create_cms_product:w.tool({description:"Create a new draft-capable product. Defaults missing product fields safely: physical Stripe product, generated SKU, price 0, stock 0, taxable, draft. For translations, pass translationGroupId from the source product context. Mutating: first returns a confirmation phrase; only executes after exact confirmation.",execute:n=>Ke(n,e),inputSchema:Q,strict:!0}),delete_cms_item:w.tool({description:"Delete a resolved page, post, or product after exact confirmation. Pages/posts delete all translations in the translation group and related navigation links. Mutating: refuses unless the latest user message includes the exact confirmation phrase.",execute:n=>We(n,e),inputSchema:Z,strict:!0}),prepare_delete_cms_item:w.tool({description:"Inspect the page, post, or product that would be deleted and return the exact confirmation phrase. This tool does not mutate data.",execute:n=>Pt(n,e),inputSchema:Ce,strict:!0}),update_footer:w.tool({description:"Replace the public footer links and/or footer copyright settings for a locale. Use links for footer navigation and copyright for locale text templates. Mutating: first returns a confirmation phrase; only executes after exact confirmation.",execute:n=>Oe(n,e),inputSchema:R,strict:!0}),update_content_block:w.tool({description:'Update the JSON content of an existing top-level page/post block that belongs to the current CMS edit context. Content is merged with the existing block before validation. For section blocks, add nested blocks with content.append_block or content.append_blocks using objects like { block_type: "button", content: { text: "Contact Us", url: "/contact" } }; existing column_blocks and layout fields are preserved. Mutating: first returns a confirmation phrase; only executes after exact confirmation.',execute:n=>De(n,e),inputSchema:V,strict:!0}),insert_content_block:w.tool({description:'Insert a new validated top-level page/post block before or after an existing block, or at the start/end. Use this for visible content additions like adding a rich text title and paragraph above a form. For "above the form", use position "before" with anchorBlockType "form" and blockType "text" containing html_content. Mutating: first returns a confirmation phrase; only executes after exact confirmation.',execute:n=>Me(n,e),inputSchema:W,strict:!0}),update_current_cms_fields:w.tool({description:"Update validated metadata fields on the current page, post, or product. For products, description_json must be a valid NextBlock editor document JSON object. Mutating: first returns a confirmation phrase; only executes after exact confirmation.",execute:n=>Ue(n,e),inputSchema:K,strict:!0}),update_cms_item_field:w.tool({description:"Update one field on a page, post, or product, resolving by current edit context, id, slug, or exact title. Use this for requests like changing price, stock, title, slug, status, sale_price, or meta fields. Interpret public as published for pages/posts and active for products. Scheduled sale date ranges are not supported and will be refused without mutation. Mutating: first returns a confirmation phrase; only executes after exact confirmation.",execute:n=>Je(n,e),inputSchema:X,strict:!0}),update_navigation_bar:w.tool({description:'Update the public header navigation bar for a locale. Use mode "append" when adding links while preserving existing navigation. Use mode "update" when renaming or changing an existing single link. Use mode "replace" only when the user asks to rebuild the complete header and you provide the full menu; destructive partial replacements are refused. Mutating: first returns a confirmation phrase; only executes after exact confirmation.',execute:n=>qe(n,e),inputSchema:G,strict:!0}),update_section_column_block:w.tool({description:"Update the content of one existing nested block inside a section block that belongs to the current CMS edit context. This tool must not change the nested block type. To add a new nested block, update the parent section with update_content_block and preserve existing column_blocks. Mutating: first returns a confirmation phrase; only executes after exact confirmation.",execute:n=>Le(n,e),inputSchema:J,strict:!0}),execute_cms_action_plan:w.tool({description:"Execute multiple CMS mutations as one confirmed plan. Use this whenever the user asks for more than one change in the same prompt, such as creating a page and adding a navigation link. First returns one combined confirmation preview and Confirm button; after confirmation, runs each action in order and stops on the first failure.",execute:n=>Bt(n,e),inputSchema:xe,strict:!0})}}exports.availableCortexAiBlockTypes=N;exports.buildVisibleContactIntroActionPlan=Wt;exports.cortexAiPageContextSchema=we;exports.createCmsPageInputSchema=H;exports.createCmsPostInputSchema=Y;exports.createCmsProductInputSchema=Q;exports.createCortexGlobalAgentTools=Vn;exports.deleteCmsItemInputSchema=Z;exports.executeCmsActionPlan=Bt;exports.executeCmsActionPlanInputSchema=xe;exports.executeCreateCmsPage=Ge;exports.executeCreateCmsPost=Re;exports.executeCreateCmsProduct=Ke;exports.executeDeleteCmsItem=We;exports.executeFetchEcommerceStats=Ct;exports.executeInsertContentBlock=Me;exports.executePrepareDeleteCmsItem=Pt;exports.executeReadCurrentCmsItem=xt;exports.executeSearchDocumentation=zt;exports.executeSearchDocumentationWithTimeout=It;exports.executeUpdateCmsItemField=Je;exports.executeUpdateContentBlock=De;exports.executeUpdateCurrentCmsFields=Ue;exports.executeUpdateFooter=Oe;exports.executeUpdateNavigationBar=qe;exports.executeUpdateSectionColumnBlock=Le;exports.fetchEcommerceStatsInputSchema=ke;exports.insertContentBlockInputSchema=W;exports.navigationItemInputSchema=ye;exports.prepareDeleteCmsItemInputSchema=Ce;exports.readCurrentCmsItemInputSchema=ze;exports.searchDocumentationInputSchema=de;exports.updateCmsItemFieldInputSchema=X;exports.updateContentBlockInputSchema=V;exports.updateCurrentCmsFieldsInputSchema=K;exports.updateFooterInputSchema=R;exports.updateNavigationBarInputSchema=G;exports.updateSectionColumnBlockInputSchema=J;
15
+ `).eq("orders.status","paid"):null;p&&(l&&p.eq("orders.currency",l),a&&p.gte("orders.paid_at",a.toISOString()),s&&p.lte("orders.paid_at",s.toISOString()));const m=n.timeRange!=="all_time"&&(n.reportType==="orders"||u)?o.from("orders").select("id, status, currency"):null;m&&l&&m.eq("currency",l);const[{data:f,error:_},{data:k,error:w},v]=await Promise.all([d,p??Promise.resolve({data:[],error:null}),m??Promise.resolve({data:null,error:null})]);if(_)throw new Error(`Failed to fetch ecommerce stats: ${h(_)}`);if(w)throw new Error(`Failed to fetch ecommerce stats: ${h(w)}`);if(v.error)throw new Error(`Failed to fetch ecommerce stats: ${h(v.error)}`);const y=Array.isArray(f)?f:[],z=Array.isArray(k)?k:[],C=yt(y),S=Array.isArray(v.data)?v.data:null,O=S?yt(S):null,B={};for(const b of z){const E=Array.isArray(b.orders)?b.orders[0]:b.orders,F=String(E?.currency||l||"unknown").toUpperCase();B[F]=(B[F]??0)+V(b.quantity)*V(b.price_at_purchase)/100}const G={currency:l??null,currencyFiltered:!!l,orderStatusCounts:C,paidOrderCount:C.paid??0,query:n.query,reportType:n.reportType,revenueByCurrency:B,timeRange:n.timeRange,totalOrders:y.length,totalRevenue:Object.values(B).reduce((b,E)=>b+E,0)};if(O&&(G.allTimeOrderStatusCounts=O),u&&(G.matchingOrderStatus={allTimeCount:O?.[u]??C[u]??0,count:C[u]??0,status:u,timeRange:n.timeRange}),n.reportType==="products"||n.reportType==="revenue"||n.reportType==="general"){const b={};for(const E of z){const F=Array.isArray(E.products)?E.products[0]:E.products;if(!F?.id)continue;const K=F.id;b[K]||(b[K]={id:K,quantity:0,revenue:0,title:F.title,type:F.product_type}),b[K].quantity+=V(E.quantity),b[K].revenue+=V(E.quantity)*V(E.price_at_purchase)/100}G.topProducts=Object.values(b).sort((E,F)=>F.revenue-E.revenue).slice(0,10)}return{report:G,success:!0}}async function Dt(e,t){const n=Be.parse(e),o=I(t),r=D(t),a=we(r),s=r.contentType==="page"?"pages":r.contentType==="post"?"posts":"products",{data:l,error:u}=await o.from(s).select("*").eq("id",a).single();if(u||!l)throw new Error(`Failed to read current ${r.contentType}: ${h(u)}`);let d=[];if(n.includeBlocks&&r.contentType!=="product"){const c=r.contentType==="page"?"page_id":"post_id",{data:p,error:g}=await o.from("blocks").select("id, page_id, post_id, language_id, block_type, content, order").eq(c,a);if(g)throw new Error(`Failed to read current ${r.contentType} blocks: ${h(g)}`);d=(Array.isArray(p)?p:[]).slice().sort((m,f)=>Number(m.order)-Number(f.order)).map(m=>Vn(m,n.includeBlockContent))}return{blocks:d,context:r,item:l,success:!0}}const Mt=new Set(["feature_image_id","language_id","meta_description","meta_title","slug","status","title"]),Gt=new Set(["excerpt","feature_image_id","label","language_id","meta_description","meta_title","published_at","slug","status","subtitle","title"]),ko=new Set(["description_json","language_id","meta_description","meta_title","short_description","slug","status","title"]),wo=new Set(["excerpt","feature_image_id","label","meta_description","meta_title","published_at","short_description","subtitle"]);function Io(e){return e==="page"?Mt:e==="post"?Gt:ko}function Kt(e,t){return wo.has(e)&&t===""?null:t}function Ae(e,t){if(typeof t!="string")return;const n=e==="product"?["active","archived","draft"]:["archived","draft","published"];if(!n.includes(t))throw new Error(`Status "${t}" is not valid for ${e}. Allowed statuses: ${n.join(", ")}.`)}function To(e,t){const n=Io(t.contentType),o={};for(const[r,a]of Object.entries(e))if(a!==void 0){if(!n.has(r))throw new Error(`Field "${r}" cannot be updated for ${t.contentType} content.`);r==="status"&&Ae(t.contentType,a),o[r]=Kt(r,a)}return o}async function Qe(e,t){const n=Y.parse(e),o=I(t),r=D(t),a=we(r),s=To(n.fields,r),l=Object.keys(s);if(l.length===0)throw new Error("update_current_cms_fields requires at least one supported field.");const u=A({action:"UPDATE CMS FIELDS",context:t,payload:{contentType:r.contentType,entityId:a,fields:s,tool:"update_current_cms_fields"},preview:{contentType:r.contentType,entityId:a,fields:l,slug:r.slug,title:r.title},subject:`${r.contentType} ${String(a)}`});if(u)return u;typeof s.feature_image_id=="string"&&(s.feature_image_id=await ae(s.feature_image_id,t,typeof r.title=="string"?r.title:void 0));const d=r.contentType==="page"?"pages":r.contentType==="post"?"posts":"products",{data:c,error:p}=await o.from(d).update({...s,updated_at:new Date().toISOString()}).eq("id",a).select("id, language_id, slug, status, title").single();if(p||!c)throw new Error(`Failed to update current ${r.contentType}: ${h(p)}`);return P(t,r,c.slug),{contentType:r.contentType,entityId:a,mutationExecuted:!0,slug:c.slug,success:!0,updatedFields:l}}async function Ze(e,t){const n=X.parse(e),o=I(t),r=D(t),{data:a,error:s}=await o.from("blocks").select("id, page_id, post_id, language_id, block_type, content, order").eq("id",n.blockId).single();if(s||!a)throw new Error(`Failed to read block ${n.blockId}: ${h(s)}`);Et(a,r);const l=fe(a.block_type,`Block ${n.blockId}`);$t(n.blockType,l,`Block ${n.blockId}`);const u=le(a.content,`Block ${n.blockId}`),d=Kn(l,u,n.content,t);j(l,d,`Block ${n.blockId}`,t);const c=A({action:"UPDATE CONTENT BLOCK",context:t,payload:{blockId:n.blockId,blockType:l,content:d,tool:"update_content_block"},preview:{blockId:n.blockId,blockType:l,contentType:r.contentType,entityId:we(r)},subject:`${l} block ${n.blockId}`});if(c)return c;const{data:p,error:g}=await o.from("blocks").update({content:d,updated_at:new Date().toISOString()}).eq("id",n.blockId).select("id, block_type, order").single();if(g||!p)throw new Error(`Failed to update block ${n.blockId}: ${h(g)}`);return ce([{content:d}],o),P(t,r),{blockId:p.id,blockType:p.block_type,contentUpdated:!0,mutationExecuted:!0,success:!0}}async function et(e,t){const n=ee.parse(e),o=I(t),r=await Te(n,t);if(r.contentType==="product")throw new Error("Products do not have page/post content blocks in this editor context.");const a=Number(r.item.id),s=r.contentType==="page"?"page_id":"post_id",l=async()=>{const{data:y,error:z}=await o.from("blocks").select("id, page_id, post_id, language_id, block_type, content, order").eq(s,a);if(z)throw new Error(`Failed to read ${r.contentType} blocks: ${h(z)}`);return(Array.isArray(y)?y:[]).sort((C,S)=>Number(C.order)-Number(S.order))},u=y=>{if(n.position==="start")return 0;if(n.position==="end"){const S=y.map(O=>Number(O.order)).filter(Number.isFinite);return S.length>0?Math.max(...S)+1:0}const z=n.anchorBlockId?y.find(S=>Number(S.id)===n.anchorBlockId):n.anchorBlockType?y.find(S=>S.block_type===n.anchorBlockType):null;if(!z)throw new Error(n.anchorBlockType?`Could not find a ${n.anchorBlockType} block to insert ${n.position}.`:`Could not find block ${n.anchorBlockId} to insert ${n.position}.`);const C=Number(z.order);return n.position==="before"?C:C+1},d=ye(n.block,0,t),c=await l(),p=u(c),g={contentType:r.contentType,entityId:r.item.id,languageId:r.item.language_id,slug:r.item.slug,title:r.item.title,translationGroupId:r.item.translation_group_id},m=A({action:"INSERT CONTENT BLOCK",context:t,payload:{block:d,order:p,target:{contentType:r.contentType,id:r.item.id,slug:r.item.slug},tool:"insert_content_block"},preview:{anchorBlockId:n.anchorBlockId,anchorBlockType:n.anchorBlockType,blockType:d.block_type,contentType:r.contentType,entityId:r.item.id,position:n.position,slug:r.item.slug,summary:`Insert ${d.block_type} block ${n.position} ${n.anchorBlockType?`the first ${n.anchorBlockType} block`:n.anchorBlockId?`block ${n.anchorBlockId}`:"the content"} on ${r.contentType} "${r.item.title||r.item.slug}".`,title:r.item.title},subject:`${d.block_type} block on ${r.contentType} ${r.item.id}`});if(m)return m;const f=await l(),_=u(f),k=f.filter(y=>Number(y.order)>=_).sort((y,z)=>Number(z.order)-Number(y.order));for(const y of k){const{error:z}=await o.from("blocks").update({order:Number(y.order)+1,updated_at:new Date().toISOString()}).eq("id",y.id);if(z)throw new Error(`Failed to shift block ${y.id}: ${h(z)}`)}const{data:w,error:v}=await o.from("blocks").insert({block_type:d.block_type,content:d.content,language_id:r.item.language_id,order:_,page_id:r.contentType==="page"?a:null,post_id:r.contentType==="post"?a:null}).select("id, block_type, order").single();if(v||!w)throw new Error(`Failed to insert content block: ${h(v)}`);return ce([d],o),P(t,g),{blockId:w.id,blockType:w.block_type,contentType:r.contentType,entityId:r.item.id,mutationExecuted:!0,order:w.order,success:!0}}async function tt(e,t){const n=Q.parse(e),o=I(t),r=D(t),{data:a,error:s}=await o.from("blocks").select("id, page_id, post_id, language_id, block_type, content, order").eq("id",n.parentBlockId).single();if(s||!a)throw new Error(`Failed to read parent block ${n.parentBlockId}: ${h(s)}`);Et(a,r);const l=fe(a.block_type,`Parent block ${n.parentBlockId}`);if(l!=="section")throw new Error(`Parent block ${n.parentBlockId} must be a section block, not "${l}".`);const u=le(a.content,`Parent block ${n.parentBlockId}`);j(l,u,`Parent block ${n.parentBlockId}`,t);const c=u.column_blocks?.[n.columnIndex]?.[n.blockIndex];if(!c)throw new Error(`Nested block was not found at column ${n.columnIndex}, index ${n.blockIndex}.`);const p=fe(c.block_type,`Nested block ${n.columnIndex}:${n.blockIndex}`);$t(n.blockType,p,`Nested block ${n.columnIndex}:${n.blockIndex}`),j(p,n.content,`Nested block ${n.columnIndex}:${n.blockIndex}`,t);const g=u.column_blocks.map((w,v)=>v===n.columnIndex?w.map((y,z)=>z===n.blockIndex?{...y,content:n.content}:y):w),m={...u,column_blocks:g};j(l,m,`Updated parent block ${n.parentBlockId}`,t);const f=A({action:"UPDATE NESTED BLOCK",context:t,payload:{blockIndex:n.blockIndex,columnIndex:n.columnIndex,content:n.content,nestedBlockType:p,parentBlockId:n.parentBlockId,tool:"update_section_column_block"},preview:{blockIndex:n.blockIndex,columnIndex:n.columnIndex,nestedBlockType:p,parentBlockId:n.parentBlockId,parentBlockType:l},subject:`${p} nested block ${n.columnIndex}:${n.blockIndex}`});if(f)return f;const{data:_,error:k}=await o.from("blocks").update({content:m,updated_at:new Date().toISOString()}).eq("id",n.parentBlockId).select("id, block_type").single();if(k||!_)throw new Error(`Failed to update parent block ${n.parentBlockId}: ${h(k)}`);return P(t,r),{blockIndex:n.blockIndex,columnIndex:n.columnIndex,mutationExecuted:!0,nestedBlockType:p,parentBlockId:_.id,parentBlockType:_.block_type,success:!0}}async function xe(e,t){const n=te.parse(e),o=I(t),r=Me(t),a=await Ie(o,n.languageCode),s=se(n.slug||n.title),l=Ve(n.blocks,n.contactEmail,n.title,t),u=await We({contentType:"page",languageId:a.id,slug:s,supabase:o});if(u)return u;const d=await He({contentType:"page",languageCode:a.code,languageId:a.id,suppliedTranslationGroupId:n.translationGroupId,supabase:o});if(d.result)return d.result;const c={blocks:l,item:{feature_image_id:n.feature_image_id??null,language_id:a.id,meta_description:n.meta_description??null,meta_title:n.meta_title??null,slug:s,status:n.status,title:n.title,translation_group_id:d.translationGroupId},tool:"create_cms_page"},p=A({action:"CREATE PAGE",context:t,payload:c,preview:{blockCount:l.length,languageCode:a.code,slug:s,status:n.status,title:n.title,translationGroupId:d.translationGroupId},subject:s});if(p)return p;const g=d.translationGroupId||Ge(),m=await ae(c.item.feature_image_id,t,n.title),{data:f,error:_}=await o.from("pages").insert({...c.item,author_id:r,feature_image_id:m,translation_group_id:g}).select("id, language_id, slug, status, title, translation_group_id").single();if(_||!f?.id)throw new Error(`Failed to create page: ${h(_)}`);try{await Ot({blocks:l,contentType:"page",itemId:Number(f.id),languageId:a.id,supabase:o})}catch(k){throw await qt({contentType:"page",itemId:Number(f.id),supabase:o}),k}return P(t,{contentType:"page",entityId:Number(f.id),languageId:a.id,slug:s,title:n.title},s),t?.revalidatePath?.("/cms/pages"),{blockCount:l.length,contentType:"page",editPath:Je("page",f.id),entityId:f.id,mutationExecuted:!0,slug:s,success:!0,title:n.title,translationGroupId:f.translation_group_id}}async function ze(e,t){const n=ne.parse(e),o=I(t),r=Me(t),a=await Ie(o,n.languageCode),s=se(n.slug||n.title),l=Ve(n.blocks,void 0,void 0,t),u=await We({contentType:"post",languageId:a.id,slug:s,supabase:o});if(u)return u;const d=await He({contentType:"post",languageCode:a.code,languageId:a.id,suppliedTranslationGroupId:n.translationGroupId,supabase:o});if(d.result)return d.result;const c=n.published_at&&!Number.isNaN(new Date(n.published_at).getTime())?new Date(n.published_at).toISOString():n.published_at??null,p={blocks:l,item:{excerpt:n.excerpt??null,feature_image_id:n.feature_image_id??null,label:n.label??null,language_id:a.id,meta_description:n.meta_description??null,meta_title:n.meta_title??null,published_at:c,slug:s,status:n.status,subtitle:n.subtitle??null,title:n.title,translation_group_id:d.translationGroupId},tool:"create_cms_post"},g=A({action:"CREATE POST",context:t,payload:p,preview:{blockCount:l.length,languageCode:a.code,slug:s,status:n.status,title:n.title,translationGroupId:d.translationGroupId},subject:s});if(g)return g;const m=d.translationGroupId||Ge(),f=await ae(p.item.feature_image_id,t,n.title),{data:_,error:k}=await o.from("posts").insert({...p.item,author_id:r,feature_image_id:f,translation_group_id:m}).select("id, language_id, slug, status, title, translation_group_id").single();if(k||!_?.id)throw new Error(`Failed to create post: ${h(k)}`);try{await Ot({blocks:l,contentType:"post",itemId:Number(_.id),languageId:a.id,supabase:o})}catch(w){throw await qt({contentType:"post",itemId:Number(_.id),supabase:o}),w}return P(t,{contentType:"post",entityId:Number(_.id),languageId:a.id,slug:s,title:n.title},s),t?.revalidatePath?.("/cms/posts"),t?.revalidatePath?.("/articles"),{blockCount:l.length,contentType:"post",editPath:Je("post",_.id),entityId:_.id,mutationExecuted:!0,slug:s,success:!0,title:n.title,translationGroupId:_.translation_group_id}}function xo(e,t){return(t||se(e)||"product").replace(/-/g,"").slice(0,24).toUpperCase()}function Vt(e){if(e===void 0)return;const t=Sn().safeParse(e);if(!t.success)throw new Error(`Product description_json failed editor document validation: ${t.error.issues.map(n=>n.message).join("; ")}`);return t.data}async function nt(e,t){const n=oe.parse(e),o=I(t),r=await Ie(o,n.languageCode),a=se(n.slug||n.title),s=await We({contentType:"product",languageId:r.id,slug:a,supabase:o});if(s)return s;const l=await He({contentType:"product",languageCode:r.code,languageId:r.id,suppliedTranslationGroupId:n.translationGroupId,supabase:o});if(l.result)return l.result;const{createProduct:u,productSchema:d}=await Un(),p=n.product_type==="digital"&&n.payment_provider==="freemius"?n.trial_period_days:0,g=d.parse({description_json:Vt(n.description_json),freemius_plan_id:n.freemius_plan_id||"",freemius_product_id:n.freemius_product_id||"",is_taxable:n.is_taxable,language_id:r.id,meta_description:n.meta_description??"",meta_title:n.meta_title??"",payment_provider:n.payment_provider,price:n.price,prices:n.prices||{},product_media:[],product_type:n.product_type,sale_price:n.sale_price??null,sale_prices:n.sale_prices||{},short_description:n.short_description??"",sku:n.sku||xo(n.title,a),slug:a,status:n.status,stock:n.stock,title:n.title,trial_period_days:p,trial_requires_payment_method:p>0?n.trial_requires_payment_method:!1,translation_group_id:l.translationGroupId,upc:n.upc??"",variation_attributes:[],variants:[]}),m=A({action:"CREATE PRODUCT",context:t,payload:{item:g,tool:"create_cms_product"},preview:{languageCode:r.code,price:g.price,sku:g.sku,slug:a,status:g.status,stock:g.stock,title:g.title,translationGroupId:l.translationGroupId},subject:a});if(m)return m;const f=await u(o,g);if(!f?.id)throw new Error("Failed to create product.");return P(t,{contentType:"product",entityId:f.id,languageId:r.id,slug:a,title:n.title},a),t?.revalidatePath?.("/cms/products"),{contentType:"product",editPath:Je("product",f.id),entityId:f.id,mutationExecuted:!0,slug:a,success:!0,title:n.title,translationGroupId:f.translation_group_id}}function ot(e){return e.trim().replace(/[\s-]+/g,"_").toLowerCase()}function zo(e,t){const n=typeof t=="string"?ot(t):t;return e==="product"?n==="public"||n==="publish"||n==="published"?"active":n:n==="public"||n==="active"||n==="publish"?"published":n}function Co(e){const t=ot(e.field);return!!(e.startsAt||e.endsAt||t.includes("start")||t.includes("end")||t.includes("schedule")||t.includes("special_date"))}async function So(e,t,n){if(e==="price"||e==="sale_price"){if(t==null)return{[e]:null};const o=await gt(n);return{[e]:vt(Number(t),o)}}if(e==="prices"||e==="sale_prices"){const o=await gt(n);return{[e]:Ln(t,o)}}return e==="description_json"?{description_json:Vt(t)}:{[e]:t}}function vo(e,t){const n=ot(e.field),o=n==="status"?zo(t.contentType,e.value):e.value,a={description:"description_json",feature_image:"feature_image_id",feature_image_id:"feature_image_id",language:"language_id",meta_description:"meta_description",meta_title:"meta_title",payment:"payment_provider",provider:"payment_provider",regular_price:"price",sale:"sale_price",sale_price:"sale_price",short_description:"short_description",taxable:"is_taxable",trial:"trial_period_days",trial_days:"trial_period_days",trial_payment_method_required:"trial_requires_payment_method",type:"product_type"}[n]||n;if(t.contentType!=="product"){if(!(t.contentType==="page"?Mt:Gt).has(a))throw new Error(`Field "${e.field}" cannot be updated for ${t.contentType}.`);return a==="status"&&Ae(t.contentType,o),{field:a,payload:{[a]:Kt(a,o)}}}if(!new Set(["description_json","freemius_plan_id","freemius_product_id","is_taxable","language_id","meta_description","meta_title","payment_provider","price","prices","product_type","sale_price","sale_prices","short_description","sku","slug","status","stock","title","trial_period_days","trial_requires_payment_method","upc"]).has(a))throw new Error(`Field "${e.field}" cannot be updated for product.`);if(a==="status"&&Ae("product",o),(a==="price"||a==="sale_price")&&o!==null&&(typeof o!="number"||o<0))throw new Error(`${a} must be a non-negative number or null.`);if(a==="stock"&&(!Number.isInteger(o)||Number(o)<0))throw new Error("stock must be a non-negative integer.");if(a==="trial_period_days"&&(!Number.isInteger(o)||Number(o)<0))throw new Error("trial_period_days must be a non-negative integer.");if(a==="trial_requires_payment_method"&&typeof o!="boolean")throw new Error("trial_requires_payment_method must be a boolean.");return{field:a,payload:{[a]:o}}}async function rt(e,t){const n=re.parse(e);if(Co(n))return{message:"Scheduled product specials are not supported by the current product schema yet. I can set or clear sale_price now, but not start/end dates.",mutationExecuted:!1,success:!1,unsupported:!0};const o=await Te(n,t),r=vo(n,o),a=r.field;let s=r.payload;if(a==="language_id"&&typeof s.language_id=="string"){const p=await M(I(t),s.language_id);s={...s,language_id:p.id}}const l=A({action:"UPDATE FIELD",context:t,payload:{contentType:o.contentType,entityId:o.item.id,field:a,payload:s,tool:"update_cms_item_field"},preview:{contentType:o.contentType,field:a,from:o.item[a],slug:o.item.slug,title:o.item.title,to:s[a]},subject:`${o.contentType} ${o.item.slug||o.item.id} ${a}`});if(l)return l;if(o.contentType==="product"){const p=I(t),g=await So(a,s[a],p),{data:m,error:f}=await p.from("products").update({...g,updated_at:new Date().toISOString()}).eq("id",o.item.id).select("id, language_id, slug, status, title").single();if(f||!m)throw new Error(`Failed to update product: ${h(f)}`);return P(t,{contentType:"product",entityId:String(m.id),languageId:m.language_id,slug:m.slug,title:m.title},m.slug),{contentType:"product",entityId:m.id,field:a,mutationExecuted:!0,slug:m.slug,success:!0,updatedFields:[a]}}a==="feature_image_id"&&typeof s.feature_image_id=="string"&&(s={...s,feature_image_id:await ae(s.feature_image_id,t,typeof o.item.title=="string"?o.item.title:void 0)});const u=o.contentType==="page"?"pages":"posts",{data:d,error:c}=await I(t).from(u).update({...s,updated_at:new Date().toISOString()}).eq("id",o.item.id).select("id, language_id, slug, status, title").single();if(c||!d)throw new Error(`Failed to update ${o.contentType}: ${h(c)}`);return P(t,{contentType:o.contentType,entityId:Number(d.id),languageId:d.language_id,slug:d.slug,title:d.title},d.slug),{contentType:o.contentType,entityId:d.id,field:a,mutationExecuted:!0,slug:d.slug,success:!0,updatedFields:[a]}}async function Wt(e,t){const n=je.parse(e),o=await Te(n,t);if(o.contentType==="product")return{affectedCount:1,collectionPath:ht("product"),contentType:"product",item:o.item,navigationLinkCount:0,publicPaths:o.item.slug?[`/product/${o.item.slug}`]:[],targetIds:[o.item.id]};const r=o.contentType==="page"?"pages":"posts",{data:a,error:s}=await I(t).from(r).select("id, slug, title, translation_group_id").eq("translation_group_id",o.item.translation_group_id);if(s)throw new Error(`Failed to inspect related ${o.contentType}s: ${h(s)}`);const l=Array.isArray(a)?a:[],u=l.map(m=>o.contentType==="page"?m.slug==="home"?"/":`/${m.slug}`:`/article/${m.slug}`).filter(Boolean),d=new Set(u),{data:c,error:p}=await I(t).from("navigation_items").select("id, url");if(p)throw new Error(`Failed to inspect related navigation links: ${h(p)}`);const g=(Array.isArray(c)?c:[]).filter(m=>d.has(m.url)).length;return{affectedCount:l.length,collectionPath:ht(o.contentType),contentType:o.contentType,item:o.item,navigationLinkCount:g,publicPaths:u,targetIds:l.map(m=>m.id)}}function Ht(e){const t=e.item.title||e.item.slug||"selected item",n=e.item.slug?` (${e.item.slug})`:"";if(e.contentType==="product")return`Delete product "${t}"${n}.`;const o=[`${U(e.affectedCount,"language version")}`,e.navigationLinkCount>0?`${U(e.navigationLinkCount,"navigation link")}`:null].filter(Boolean);return`Delete ${e.contentType} "${t}"${n}, including ${o.join(" and ")}.`}async function Jt(e,t){const n=await Wt(e,t);return{...St({action:`DELETE ${n.contentType}`,payload:{affectedCount:n.affectedCount,contentType:n.contentType,targetIds:n.targetIds,tool:"delete_cms_item"},preview:{affectedCount:n.affectedCount,collectionPath:n.collectionPath,contentType:n.contentType,navigationLinkCount:n.navigationLinkCount,publicPaths:n.publicPaths,slug:n.item.slug,summary:Ht(n),title:n.item.title},subject:`${n.item.id} ${n.item.slug||""}`}),preparedDelete:!0}}async function it(e,t){const n=ie.parse(e),o=await Wt(n,t),r=A({action:`DELETE ${o.contentType}`,context:t,payload:{affectedCount:o.affectedCount,contentType:o.contentType,targetIds:o.targetIds,tool:"delete_cms_item"},preview:{affectedCount:o.affectedCount,collectionPath:o.collectionPath,contentType:o.contentType,navigationLinkCount:o.navigationLinkCount,publicPaths:o.publicPaths,slug:o.item.slug,summary:Ht(o),title:o.item.title},subject:`${o.item.id} ${o.item.slug||""}`});if(r)return r;const a=I(t);if(o.contentType==="product"){const{error:l}=await a.from("products").delete().eq("id",o.item.id);if(l)throw new Error(`Failed to delete product: ${h(l)}`)}else{for(const d of o.publicPaths)await a.from("navigation_items").delete().eq("url",d);const l=o.contentType==="page"?"pages":"posts",{error:u}=await a.from(l).delete().eq("translation_group_id",o.item.translation_group_id);if(u)throw new Error(`Failed to delete ${o.contentType}: ${h(u)}`)}const s=t?.revalidatePath??Re();return s&&(s(o.collectionPath),s("/cms/navigation"),o.publicPaths.forEach(l=>s(l))),{affectedCount:o.affectedCount,collectionPath:o.collectionPath,contentType:o.contentType,mutationExecuted:!0,redirectPath:o.collectionPath,success:!0}}async function bt(e,t){switch(e.tool){case"create_cms_page":return xe(e.input,t);case"create_cms_post":return ze(e.input,t);case"create_cms_product":return nt(e.input,t);case"delete_cms_item":return it(e.input,t);case"update_cms_item_field":return rt(e.input,t);case"update_content_block":return Ze(e.input,t);case"insert_content_block":return et(e.input,t);case"update_current_cms_fields":return Qe(e.input,t);case"update_footer":return Xe(e.input,t);case"update_navigation_bar":return Ye(e.input,t);case"update_section_column_block":return tt(e.input,t)}}function Eo(e,t){if(e.tool!=="create_cms_page"&&e.tool!=="create_cms_post"&&e.tool!=="create_cms_product"||e.input.translationGroupId||!e.input.languageCode)return e;const n=t[e.tool];return n?{...e,input:{...e.input,translationGroupId:n}}:e}async function Yt(e,t){const n=Le.parse(e);if(!t?.skipConfirmation){const d=[];for(const g of n.actions){const m=await bt(g,{...t,latestUserMessage:null});if(!m||typeof m!="object")return{message:`Could not prepare action ${d.length+1}.`,mutationExecuted:!1,success:!1};if(m.success===!1||m.unsupported===!0)return m;m.requiresConfirmation===!0&&m.preview?d.push(qn(g.tool,m.preview)):d.push(`Run ${g.tool.replace(/_/g," ")}.`)}const c=n.summary||`Complete ${U(n.actions.length,"CMS action")}.`,p=A({action:"EXECUTE CMS ACTION PLAN",context:t,payload:{actions:n.actions,tool:"execute_cms_action_plan"},preview:{actionCount:n.actions.length,actionSummaries:d,summary:c},subject:`${n.actions.length} actions`});if(p)return p}const o={...t,skipConfirmation:!0},r=[];let a=!1,s=null,l=null;const u={};for(const[d,c]of n.actions.entries()){const p=Eo(c,u),g=await bt(p,o);if(r.push({output:g,tool:p.tool}),g&&typeof g=="object"){const m=g;if(m.mutationExecuted===!0&&(a=!0),!s&&typeof m.editPath=="string"&&(s=m.editPath),typeof m.redirectPath=="string"&&(l=m.redirectPath),(p.tool==="create_cms_page"||p.tool==="create_cms_post"||p.tool==="create_cms_product")&&typeof m.translationGroupId=="string"&&(u[p.tool]=m.translationGroupId),m.success===!1||m.unsupported===!0)return{actionCount:n.actions.length,failedActionIndex:d,failedTool:p.tool,message:typeof m.message=="string"?m.message:`Action ${d+1} failed.`,mutationExecuted:a,results:r,success:!1,...s?{editPath:s}:{},...l?{redirectPath:l}:{}}}}return{actionCount:n.actions.length,editPath:l?void 0:s??void 0,mutationExecuted:a,redirectPath:l??void 0,results:r,success:!0,summary:n.summary??null}}const at=i.z.strictObject({maxChars:i.z.number().int().min(500).max(2e4).default(8e3).describe("Maximum characters of readable body text to return."),url:i.z.string().trim().min(1).max(2048).refine(e=>/^https?:\/\//i.test(e),"URL must start with http:// or https://.")}),$o=12e3,kt=2e6;function wt(e){const t=e.trim().toLowerCase().replace(/\.$/,"").replace(/^\[|\]$/g,"");if(!t||t==="localhost"||t.endsWith(".localhost")||t.endsWith(".local")||t.endsWith(".internal")||t==="metadata.google.internal"||t==="0.0.0.0"||t==="::1"||t.startsWith("fe80:")||t.startsWith("fc")||t.startsWith("fd"))return!0;const n=t.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/);if(n){const o=Number(n[1]),r=Number(n[2]);if(o===10||o===127||o===0||o===192&&r===168||o===169&&r===254||o===172&&r>=16&&r<=31)return!0}return!1}function pe(e){return e.replace(/<[^>]+>/g," ").replace(/&nbsp;/gi," ").replace(/&amp;/gi,"&").replace(/&lt;/gi,"<").replace(/&gt;/gi,">").replace(/&quot;/gi,'"').replace(/&#39;/gi,"'").replace(/\s+/g," ").trim()}function Ao(e,t){const n=e.replace(/<script\b[\s\S]*?<\/script>/gi," ").replace(/<style\b[\s\S]*?<\/style>/gi," ").replace(/<noscript\b[\s\S]*?<\/noscript>/gi," ").replace(/<svg\b[\s\S]*?<\/svg>/gi," "),o=e.match(/<title\b[^>]*>([\s\S]*?)<\/title>/i),r=e.match(/<meta[^>]+name=["']description["'][^>]*content=["']([^"']*)["'][^>]*>/i)||e.match(/<meta[^>]+content=["']([^"']*)["'][^>]*name=["']description["'][^>]*>/i),a=[...n.matchAll(/<h([1-3])\b[^>]*>([\s\S]*?)<\/h\1>/gi)].map(u=>pe(u[2])).filter(Boolean).slice(0,40),s=n.match(/<body\b[^>]*>([\s\S]*?)<\/body>/i),l=pe(s?.[1]??n);return{description:r?pe(r[1]):"",headings:a,text:l.slice(0,t),title:o?pe(o[1]):"",truncated:l.length>t}}async function Xt(e){const t=at.parse(e);let n;try{n=new URL(t.url)}catch{return{message:`"${t.url}" is not a valid URL.`,success:!1,url:t.url}}if(n.protocol!=="http:"&&n.protocol!=="https:")return{message:"Only http and https URLs can be fetched.",success:!1,url:t.url};if(wt(n.hostname))return{message:"Refusing to fetch a local, private, or internal address.",success:!1,url:t.url};const o=new AbortController,r=setTimeout(()=>o.abort(),$o);try{const a=await fetch(n.toString(),{headers:{accept:"text/html,application/xhtml+xml,text/plain","user-agent":"NextBlockCortexAI/1.0 (+https://nextblock.dev)"},redirect:"follow",signal:o.signal});if(!a.ok)return{message:`The URL responded with HTTP ${a.status}.`,status:a.status,success:!1,url:t.url};const s=a.url||n.toString();try{if(wt(new URL(s).hostname))return{message:"The URL redirected to a blocked internal address.",success:!1,url:t.url}}catch{}const l=a.headers.get("content-type")||"";if(!/text\/html|text\/plain|application\/xhtml/i.test(l))return{contentType:l,message:`The URL is not an HTML or text page (content-type: ${l||"unknown"}).`,success:!1,url:t.url};const u=await a.text(),d=u.length>kt?u.slice(0,kt):u,c=Ao(d,t.maxChars);return!c.text&&!c.title?{message:"The URL returned no readable text content.",success:!1,url:t.url}:{description:c.description,finalUrl:s,headings:c.headings,success:!0,text:c.text,title:c.title,truncated:c.truncated,url:t.url}}catch(a){return{message:a instanceof Error&&(a.name==="AbortError"||/abort/i.test(a.message))?"Fetching the URL timed out.":`Failed to fetch the URL: ${h(a)}`,success:!1,url:t.url}}finally{clearTimeout(r)}}const st=i.z.strictObject({count:i.z.number().int().min(1).max(15).default(6),orientation:i.z.enum(["landscape","portrait","square"]).optional().describe("Preferred image orientation. Use landscape for hero/section backgrounds."),query:i.z.string().trim().min(2).max(200).describe('What the photos should depict, e.g. "herbal supplements".')}),Po=12e3;async function Ce(e){let t=null,n=null;if(e)try{const{CORTEX_AI_PEXELS_SETTING_KEY:r,CORTEX_AI_UNSPLASH_SETTING_KEY:a,decryptStoredOpenRouterApiKey:s}=await Promise.resolve().then(()=>require("./ai-config.cjs.js")),l=c=>{if(!c)return null;try{const p=s(c);return typeof p=="string"&&p.trim()?p.trim():null}catch{return null}},{data:u}=await e.from("site_settings").select("key, value").in("key",[r,a]),d=Array.isArray(u)?u:[];t=l(d.find(c=>c.key===r)?.value),n=l(d.find(c=>c.key===a)?.value)}catch{}t||(t=process.env.PEXELS_API_KEY?.trim()||null),n||(n=process.env.UNSPLASH_ACCESS_KEY?.trim()||null);const o=[];return t&&o.push({apiKey:t,provider:"pexels"}),n&&o.push({apiKey:n,provider:"unsplash"}),o}async function No(e){return(await Ce(e))[0]??null}async function Uo(e){if(e)try{const{CORTEX_AI_UNSPLASH_APP_NAME_SETTING_KEY:t}=await Promise.resolve().then(()=>require("./ai-config.cjs.js")),{data:n}=await e.from("site_settings").select("value").eq("key",t).maybeSingle(),o=n?.value;if(typeof o=="string"&&o.trim())return o.trim()}catch{}return process.env.UNSPLASH_APP_NAME?.trim()||null}async function It(e,t){const n=new AbortController,o=setTimeout(()=>n.abort(),Po);try{const r=await fetch(e,{headers:t,signal:n.signal});if(!r.ok)throw new Error(`Stock photo provider responded with HTTP ${r.status}.`);return await r.json()}finally{clearTimeout(o)}}function me(e){const t=Number(e);return Number.isFinite(t)&&t>0?t:null}function Pe(e,t){if(!$(e))return;const n=o=>{$(o)&&o.provider==="unsplash"&&typeof o.downloadLocation=="string"&&o.downloadLocation.trim()&&t.add(o.downloadLocation.trim())};if(n(e.attribution),$(e.background)&&$(e.background.image)&&n(e.background.image.attribution),Array.isArray(e.column_blocks)){for(const o of e.column_blocks)if(Array.isArray(o))for(const r of o)$(r)&&Pe(r.content,t)}if(Array.isArray(e.slides))for(const o of e.slides)Pe(o,t)}async function ce(e,t){try{const n=new Set;for(const a of e)Pe(a?.content,n);if(n.size===0)return;const r=(await Ce(t)).find(a=>a.provider==="unsplash");if(!r)return;await Promise.all([...n].map(a=>fetch(a,{headers:{Authorization:`Client-ID ${r.apiKey}`}}).catch(()=>{})))}catch{}}async function Fo(e,t,n){const o=new URLSearchParams({per_page:String(t.count),query:t.query});if(t.orientation&&o.set("orientation",t.orientation),e.provider==="pexels"){const a=await It(`https://api.pexels.com/v1/search?${o.toString()}`,{Authorization:e.apiKey});return(Array.isArray(a?.photos)?a.photos:[]).map(s=>{const l=typeof s?.photographer=="string"?s.photographer:null;return{alt:typeof s?.alt=="string"&&s.alt.trim()?s.alt.trim():t.query,credit:l?`Photo by ${l} on Pexels`:"Photo on Pexels",downloadLocation:null,height:me(s?.height),photographer:l,photographerUrl:typeof s?.photographer_url=="string"?s.photographer_url:null,provider:"pexels",sourceUrl:typeof s?.url=="string"?s.url:null,thumbnailUrl:s?.src?.medium||s?.src?.large||null,url:s?.src?.large2x||s?.src?.large||s?.src?.original||null,width:me(s?.width)}}).filter(s=>typeof s.url=="string")}const r=await It(`https://api.unsplash.com/search/photos?${o.toString()}`,{Authorization:`Client-ID ${e.apiKey}`});return(Array.isArray(r?.results)?r.results:[]).map(a=>{const s=typeof a?.user?.name=="string"?a.user.name:null;return{alt:typeof a?.alt_description=="string"&&a.alt_description.trim()||typeof a?.description=="string"&&a.description.trim()||t.query,credit:s?`Photo by ${s} on Unsplash`:"Photo on Unsplash",downloadLocation:typeof a?.links?.download_location=="string"?a.links.download_location:null,height:me(a?.height),photographer:s,photographerUrl:typeof a?.user?.links?.html=="string"?a.user.links.html:null,provider:"unsplash",sourceUrl:typeof a?.links?.html=="string"?a.links.html:null,thumbnailUrl:a?.urls?.small||a?.urls?.thumb||null,url:a?.urls?.regular||a?.urls?.full||a?.urls?.raw||null,utmSource:n||null,width:me(a?.width)}}).filter(a=>typeof a.url=="string")}async function Qt(e,t){const n=st.parse(e),o=await Ce(t?.supabase);if(o.length===0)return{message:"No stock photo provider is configured. Add a free Pexels or Unsplash API key in /cms/settings/cortex-ai (or set PEXELS_API_KEY / UNSPLASH_ACCESS_KEY).",photos:[],success:!1};const r=o.some(l=>l.provider==="unsplash")?await Uo(t?.supabase):null,a=[];let s=null;for(const l of o){a.push(l.provider);try{const u=await Fo(l,n,r);if(u.length>0)return{attemptedProviders:a,photos:u,provider:l.provider,query:n.query,success:!0,usageGuidance:l.provider==="unsplash"?'Unsplash photos: keep them hotlinked (use `url` as external_url; never save an Unsplash photo to the media library) and attribute each one — copy the photo\'s attribution fields into the image content\'s `attribution` (photographer, photographerUrl, sourceUrl, downloadLocation, utmSource, provider "unsplash"). The site renders the "Photo by … on Unsplash" credit from `attribution` automatically, so do NOT also copy the credit into `caption` (leave caption empty unless you have a genuine descriptive caption).':'Set the image content\'s `attribution` (photographer, photographerUrl, sourceUrl, provider "pexels"). The site renders the "Photo by … on Pexels" credit from `attribution` automatically, so do NOT also copy the credit into `caption` (leave caption empty unless you have a genuine descriptive caption). Pexels attribution is appreciated but optional.'}}catch(u){s=u}}return{attemptedProviders:a,message:s?`Stock photo search failed across ${a.join(", ")}: ${h(s)}`:`No matching stock photos found for "${n.query}".`,photos:[],success:!1}}const lt=Z.extend({blocks:i.z.array(ke).min(1).max(20),meta:i.z.strictObject({meta_description:i.z.string().max(500).nullable().optional(),meta_title:i.z.string().max(160).nullable().optional(),slug:i.z.string().trim().min(1).max(300).optional(),status:i.z.enum(["draft","published","archived"]).optional(),title:i.z.string().trim().min(1).max(300).optional()}).partial().optional()}),Oo=["custom_canonical","excerpt","feature_image_id","label","language_id","meta_description","meta_title","published_at","slug","status","subtitle","title","translation_group_id"];function qo(e){const t={};for(const n of Oo)n in e&&e[n]!==void 0&&(t[n]=e[n]);return t}function Bo(e,t){if(!t)return null;const n=e==="page"?t==="home"?"/":`/${t}`:`/article/${t}`;return`/api/draft/start?path=${encodeURIComponent(n)}`}async function Zt(e,t){const n=lt.parse(e),o=I(t),r=Me(t),a=await Te(n,t);if(a.contentType==="product")throw new Error("rewrite_page_draft supports pages and posts only. Products use description_json, not page blocks.");const s=a.contentType,l=Number(a.item.id);if(!Number.isInteger(l)||l<=0)throw new Error("Could not resolve a valid page/post id for the draft rewrite.");const u=Number(a.item.language_id);if(!Number.isInteger(u)||u<=0)throw new Error("The target page/post is missing a language id.");const c=Ve(n.blocks,void 0,void 0,t).map((C,S)=>({block_type:C.block_type,content:C.content,language_id:u,order:S,page_id:s==="page"?l:null,post_id:s==="post"?l:null,product_id:null})),p=qo(a.item);if(n.meta)for(const[C,S]of Object.entries(n.meta))S!==void 0&&(p[C]=S);const g=zt(typeof p.slug=="string"?p.slug:a.item.slug),m=typeof p.title=="string"&&p.title.trim()?p.title:String(a.item.title||g||"Untitled"),f=s==="page"?`/cms/pages/${l}/edit`:`/cms/posts/${l}/edit`,_=Bo(s,g),w=A({action:"REWRITE DRAFT",context:t,payload:{blocks:c,meta:p,parent_id:l,parent_type:s,tool:"rewrite_page_draft"},preview:{blockCount:c.length,contentType:s,slug:g,summary:`Stage a Live Draft that replaces the ${s} "${m}" with ${U(c.length,"new block")}. Nothing goes live until you review the draft and click Publish (which also saves a revision snapshot).`,title:m},subject:`${s}-${l}`});if(w)return w;const v=Number(a.item.version)||1,{error:y}=await o.from("content_drafts").delete().eq("parent_type",s).eq("parent_id",l);if(y)throw new Error(`Failed to clear the existing draft: ${h(y)}`);const{error:z}=await o.from("content_drafts").insert({author_id:r,base_version:v,blocks:c,meta:p,parent_id:l,parent_type:s});if(z)throw new Error(`Failed to save the draft: ${h(z)}`);return ce(c,o),P(t,{contentType:s,entityId:l,slug:g},g),{blockCount:c.length,contentType:s,draftPreviewPath:_,editPath:f,entityId:l,isDraft:!0,mutationExecuted:!0,slug:g,success:!0,title:m}}const jo=new Set(["alt_text","author_name","author_title","caption","html_content","label","placeholder","quote","submit_button_text","success_message","text","text_content","title"]);function Ne(e,t,n){if(!e)return e;if(Object.prototype.hasOwnProperty.call(t,e))return t[e];const o=e.trim();if(o!==e&&Object.prototype.hasOwnProperty.call(t,o))return e.replace(o,t[o]);let r=e;for(const[a,s]of n)a&&r.includes(a)&&(r=r.split(a).join(s));return r}function Ue(e,t,n){if(Array.isArray(e))return e.map(o=>Ue(o,t,n));if(e&&typeof e=="object"){const o={};for(const[r,a]of Object.entries(e))typeof a=="string"&&jo.has(r)?o[r]=Ne(a,t,n):a&&typeof a=="object"?o[r]=Ue(a,t,n):o[r]=a;return o}return e}const ct=i.z.strictObject({targetLanguageCode:i.z.string().trim().min(2).max(80).describe('Target language code or name, e.g. "fr" or "French".'),title:i.z.string().trim().min(1).max(300).optional().describe("Translated page title (defaults to translating the source title)."),translations:i.z.record(i.z.string(),i.z.string()).describe('Map of every visible source string to its translation, e.g. { "Explore Our Products": "Explorez nos produits" }. Include headings, paragraph text, button labels, image alt text, captions, and form labels.')});async function en(e,t){const n=ct.parse(e),o=D(t);if(o.contentType==="product")throw new Error("translate_page supports pages and posts only.");const r=I(t),a=De(o),s=o.contentType==="page"?"pages":"posts",l=o.contentType==="page"?"page_id":"post_id",{data:u,error:d}=await r.from(s).select("*").eq("id",a).single();if(d||!u)throw new Error(`Could not read the source ${o.contentType} to translate: ${h(d)}`);const{data:c,error:p}=await r.from("blocks").select("id, block_type, content, order").eq(l,a);if(p)throw new Error(`Could not read the source blocks: ${h(p)}`);const g=(Array.isArray(c)?c:[]).slice().sort((b,E)=>Number(b.order)-Number(E.order));if(g.length===0)throw new Error(`The source ${o.contentType} has no content blocks to translate.`);const m=n.translations||{},f=Object.entries(m).filter(([b])=>!!b).sort((b,E)=>E[0].length-b[0].length),_=g.map((b,E)=>({blockType:b.block_type,content:Ue(W(b.content),m,f),order:E})),k=await Ie(r,n.targetLanguageCode),w=String(u.title||""),v=n.title||Ne(w,m,f)||w||"Untitled",y=b=>typeof b=="string"&&b.trim()?Ne(b,m,f):void 0,z=se(v)||u.slug||"translated-page",C={blocks:_,feature_image_id:u.feature_image_id??void 0,languageCode:k.code,meta_description:y(u.meta_description),meta_title:y(u.meta_title),slug:z,status:"published",title:v,translationGroupId:u.translation_group_id||void 0},S=o.contentType==="post"?{...C,excerpt:y(u.excerpt),label:y(u.label),published_at:u.published_at??new Date().toISOString(),subtitle:y(u.subtitle)}:C,O=A({action:"TRANSLATE",context:t,payload:{createInput:S,sourceId:u.id,tool:"translate_page"},preview:{blockCount:_.length,contentType:o.contentType,languageCode:k.code,slug:C.slug,status:C.status,summary:`Publish a ${k.code.toUpperCase()} translation of "${w}" — it goes live immediately, linked to the original ${o.contentType}, at /${C.slug} with ${U(_.length,"translated block")}.`,title:v},subject:`translate ${o.contentType} ${u.id} to ${k.code}`});if(O)return O;const B={...t,skipConfirmation:!0};return{...o.contentType==="post"?await ze(S,B):await xe(S,B),isTranslation:!0,languageCode:k.code}}const tn=i.z.strictObject({images:i.z.array(i.z.string().trim().min(1).max(2048)).min(1).max(12)});async function nn(e,t){const n=tn.parse(e),o=D(t),r=I(t),a=we(o),s=o.title||o.slug||"current item",l=o.contentType==="product",u=A({action:"SET IMAGES",context:t,payload:{images:n.images,tool:"set_content_images"},preview:{contentType:o.contentType,imageCount:n.images.length,slug:o.slug,summary:l?`Set ${U(n.images.length,"image")} on product "${s}" (the first becomes the main product image, the rest the gallery).`:`Set the feature image on the ${o.contentType} "${s}".`,title:o.title},subject:`set images on ${o.contentType} ${String(a)}`});if(u)return u;const d=[];for(let m=0;m<n.images.length;m+=1){const f=await ae(n.images[m],t,`${s} image ${m+1}`);f&&d.push(f)}if(d.length===0)throw new Error("None of the provided images could be resolved to a media item.");if(l){const{data:m,error:f}=await r.from("products").select("id, slug, language_id, title").eq("id",a).maybeSingle();if(f||!m)throw new Error(`Could not load the product to set images: ${h(f)}`);const _=[...new Set(d)],{error:k}=await r.from("product_media").delete().eq("product_id",a);if(k)throw new Error(`Could not clear the product's existing images: ${h(k)}`);const{error:w}=await r.from("product_media").insert(_.map((v,y)=>({media_id:v,product_id:a,sort_order:y})));if(w)throw new Error(`Could not save the product images: ${h(w)}`);return P(t,{contentType:"product",entityId:String(a),languageId:m.language_id,slug:m.slug,title:m.title},m.slug),t?.revalidatePath?.("/cms/products"),{contentType:"product",entityId:a,imageCount:_.length,mutationExecuted:!0,slug:m.slug,success:!0}}const c=o.contentType==="page"?"pages":"posts",{data:p,error:g}=await r.from(c).update({feature_image_id:d[0],updated_at:new Date().toISOString()}).eq("id",a).select("id, language_id, slug, status, title").single();if(g||!p)throw new Error(`Failed to set the feature image: ${h(g)}`);return P(t,o,p.slug),{contentType:o.contentType,entityId:a,extraImagesIgnored:d.length-1,imageCount:1,mutationExecuted:!0,slug:p.slug,success:!0}}function Lo(e){return{...on.createCortexDatabaseAgentTools(e),...rn.createCortexCustomBlockTools(e),fetch_ecommerce_stats:T.tool({description:"Fetch quantitative ecommerce statistics and reports from the database. Use this to answer questions about revenue, order counts, order status counts such as pending or trial, and top-selling products over a time range. This tool is read-only and does not require confirmation.",execute:t=>Rt(t,e),inputSchema:Oe,strict:!0}),read_current_cms_item:T.tool({description:"Read the CMS item currently being edited. Requires pageContext and returns page/post/product metadata plus page/post block summaries or content.",execute:t=>Dt(t,e),inputSchema:Be,strict:!0}),search_documentation:T.tool({description:"Search the NextBlock documentation database and return concise source snippets for factual CMS guidance.",execute:t=>Lt(t,e),inputSchema:be,strict:!0}),fetch_url_content:T.tool({description:'Fetch the readable content (title, meta description, headings, and body text) of an external web page so you can base new CMS content on it. Read-only, no confirmation. Use this first whenever the user references an external URL to copy, adapt, or draw inspiration from, e.g. "rewrite my home page based on https://example.com".',execute:t=>Xt(t),inputSchema:at,strict:!0}),search_stock_photos:T.tool({description:"Find relevant, free, high-quality stock photos (Unsplash/Pexels) for page imagery. Returns a list of photos each with a direct image `url`, `width`, `height`, `alt`, and `photographer`. Read-only, zero cost. Use the returned `url` directly as an image block's external_url or a section image background's image.external_url when building or revamping pages, so layouts show real photos instantly. Set orientation \"landscape\" for hero/section backgrounds.",execute:t=>Qt(t,e),inputSchema:st,strict:!0}),rewrite_page_draft:T.tool({description:'Replace ALL blocks of an existing page or post with a brand-new set of blocks, staged as a Live Draft (content_drafts) that the user previews before publishing. Use this for whole-page redesigns/rewrites such as "rewrite my home page with 5 sections". Provide the complete new list of top-level blocks in `blocks` (usually section blocks for a landing/home page, each with nested heading/text/button blocks). Nothing goes live until the user publishes the draft, and publishing auto-creates a revision snapshot so the change is reversible. Mutating: first returns a confirmation phrase; only stages the draft after the user replies with the exact phrase.',execute:t=>Zt(t,e),inputSchema:lt,strict:!0}),translate_page:T.tool({description:'Translate the CURRENT page or post into another language. This copies the source page\'s entire structure, layout, and images automatically and links the new page to the original as a translation — you ONLY supply the text translations. Provide targetLanguageCode (e.g. "fr") and a `translations` map of every visible source string to its translation (headings, paragraph text, button labels, image alt text, captions, form labels). Do NOT rebuild the layout or call search_stock_photos for a translation. Requires an open page/post. Mutating: first returns a confirmation phrase; only creates the translation after exact confirmation.',execute:t=>en(t,e),inputSchema:ct,strict:!0}),set_content_images:T.tool({description:"Set the feature image for the CURRENT page or post, or the image gallery for the CURRENT product. Pass `images`: a list of image URLs (e.g. `url` values returned by search_stock_photos) and/or existing media library IDs. External URLs are imported into the media library automatically — NEVER put an image URL directly into feature_image_id. The FIRST image becomes the feature image (pages/posts) or the main product image (products); for a product the remaining images become its gallery in order (this REPLACES the product's current images). Requires an open page/post/product. Mutating: first returns a confirmation phrase; only applies after exact confirmation.",execute:t=>nn(t,e),inputSchema:tn,strict:!0}),create_cms_page:T.tool({description:"Create a new CMS page with metadata and optional validated page blocks. Mutating: first returns a confirmation phrase; only executes after the user replies with the exact phrase. For translations, pass translationGroupId from the source page/post/product context so the new language is linked to the same backend translation group. For contact pages, provide contactEmail or a form block with recipient_email and fields.",execute:t=>xe(t,e),inputSchema:te,strict:!0}),create_cms_post:T.tool({description:"Create a new CMS post with metadata and optional validated post blocks. Mutating: first returns a confirmation phrase; only executes after the user replies with the exact phrase. For translations, pass translationGroupId from the source post context so the new language is linked to the same backend translation group.",execute:t=>ze(t,e),inputSchema:ne,strict:!0}),create_cms_product:T.tool({description:"Create a new draft-capable product. Defaults missing product fields safely: physical Stripe product, generated SKU, price 0, stock 0, taxable, draft. For translations, pass translationGroupId from the source product context. Mutating: first returns a confirmation phrase; only executes after exact confirmation.",execute:t=>nt(t,e),inputSchema:oe,strict:!0}),delete_cms_item:T.tool({description:"Delete a resolved page, post, or product after exact confirmation. Pages/posts delete all translations in the translation group and related navigation links. Mutating: refuses unless the latest user message includes the exact confirmation phrase.",execute:t=>it(t,e),inputSchema:ie,strict:!0}),prepare_delete_cms_item:T.tool({description:"Inspect the page, post, or product that would be deleted and return the exact confirmation phrase. This tool does not mutate data.",execute:t=>Jt(t,e),inputSchema:je,strict:!0}),update_footer:T.tool({description:"Replace the public footer links and/or footer copyright settings for a locale. Use links for footer navigation and copyright for locale text templates. Mutating: first returns a confirmation phrase; only executes after exact confirmation.",execute:t=>Xe(t,e),inputSchema:J,strict:!0}),update_content_block:T.tool({description:'Update the JSON content of an existing top-level page/post block that belongs to the current CMS edit context. Content is merged with the existing block before validation. For section blocks, add nested blocks with content.append_block or content.append_blocks using objects like { block_type: "button", content: { text: "Contact Us", url: "/contact" } }; existing column_blocks and layout fields are preserved. Mutating: first returns a confirmation phrase; only executes after exact confirmation.',execute:t=>Ze(t,e),inputSchema:X,strict:!0}),insert_content_block:T.tool({description:'Insert a new validated top-level page/post block before or after an existing block, or at the start/end. Use this for visible content additions like adding a rich text title and paragraph above a form. For "above the form", use position "before" with anchorBlockType "form" and blockType "text" containing html_content. Mutating: first returns a confirmation phrase; only executes after exact confirmation.',execute:t=>et(t,e),inputSchema:ee,strict:!0}),update_current_cms_fields:T.tool({description:"Update validated metadata fields on the current page, post, or product. For products, description_json must be a valid NextBlock editor document JSON object. Mutating: first returns a confirmation phrase; only executes after exact confirmation.",execute:t=>Qe(t,e),inputSchema:Y,strict:!0}),update_cms_item_field:T.tool({description:"Update one field on a page, post, or product, resolving by current edit context, id, slug, or exact title. Use this for requests like changing price, stock, title, slug, status, sale_price, or meta fields. Interpret public as published for pages/posts and active for products. Scheduled sale date ranges are not supported and will be refused without mutation. Mutating: first returns a confirmation phrase; only executes after exact confirmation.",execute:t=>rt(t,e),inputSchema:re,strict:!0}),update_navigation_bar:T.tool({description:'Update the public header navigation bar for a locale. Use mode "append" when adding links while preserving existing navigation. Use mode "update" when renaming or changing an existing single link. Use mode "replace" only when the user asks to rebuild the complete header and you provide the full menu; destructive partial replacements are refused. Mutating: first returns a confirmation phrase; only executes after exact confirmation.',execute:t=>Ye(t,e),inputSchema:H,strict:!0}),update_section_column_block:T.tool({description:"Update the content of one existing nested block inside a section block that belongs to the current CMS edit context. This tool must not change the nested block type. To add a new nested block, update the parent section with update_content_block and preserve existing column_blocks. Mutating: first returns a confirmation phrase; only executes after exact confirmation.",execute:t=>tt(t,e),inputSchema:Q,strict:!0}),execute_cms_action_plan:T.tool({description:"Execute multiple CMS mutations as one confirmed plan. Use this whenever the user asks for more than one change in the same prompt, such as creating a page and adding a navigation link. First returns one combined confirmation preview and Confirm button; after confirmation, runs each action in order and stops on the first failure.",execute:t=>Yt(t,e),inputSchema:Le,strict:!0})}}exports.availableCortexAiBlockTypes=L;exports.buildVisibleContactIntroActionPlan=yn;exports.cortexAiPageContextSchema=qe;exports.createCmsPageInputSchema=te;exports.createCmsPostInputSchema=ne;exports.createCmsProductInputSchema=oe;exports.createCortexGlobalAgentTools=Lo;exports.deleteCmsItemInputSchema=ie;exports.executeCmsActionPlan=Yt;exports.executeCmsActionPlanInputSchema=Le;exports.executeCreateCmsPage=xe;exports.executeCreateCmsPost=ze;exports.executeCreateCmsProduct=nt;exports.executeDeleteCmsItem=it;exports.executeFetchEcommerceStats=Rt;exports.executeFetchUrlContent=Xt;exports.executeInsertContentBlock=et;exports.executePrepareDeleteCmsItem=Jt;exports.executeReadCurrentCmsItem=Dt;exports.executeRewritePageDraft=Zt;exports.executeSearchDocumentation=jt;exports.executeSearchDocumentationWithTimeout=Lt;exports.executeSearchStockPhotos=Qt;exports.executeSetContentImages=nn;exports.executeTranslatePage=en;exports.executeUpdateCmsItemField=rt;exports.executeUpdateContentBlock=Ze;exports.executeUpdateCurrentCmsFields=Qe;exports.executeUpdateFooter=Xe;exports.executeUpdateNavigationBar=Ye;exports.executeUpdateSectionColumnBlock=tt;exports.fetchEcommerceStatsInputSchema=Oe;exports.fetchUrlContentInputSchema=at;exports.insertContentBlockInputSchema=ee;exports.maybeTriggerStockPhotoDownloads=ce;exports.navigationItemInputSchema=Fe;exports.prepareDeleteCmsItemInputSchema=je;exports.readCurrentCmsItemInputSchema=Be;exports.resolveCortexAiStockPhotoProvider=No;exports.resolveCortexAiStockPhotoProviders=Ce;exports.rewritePageDraftInputSchema=lt;exports.searchDocumentationInputSchema=be;exports.searchStockPhotosInputSchema=st;exports.translatePageInputSchema=ct;exports.updateCmsItemFieldInputSchema=re;exports.updateContentBlockInputSchema=X;exports.updateCurrentCmsFieldsInputSchema=Y;exports.updateFooterInputSchema=J;exports.updateNavigationBarInputSchema=H;exports.updateSectionColumnBlockInputSchema=Q;