@nextblock-cms/cortex 0.14.2 → 0.14.3

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 z=require("ai"),hn=require("./ai-global-agent-db-tools.cjs.js"),yn=require("./ai-global-agent-custom-block-tools.cjs.js"),Pt=require("./editor-document-from-html.cjs.js");require("./zod-config.cjs.js");const i=require("zod"),G=["text","heading","image","button","posts_grid","video_embed","section","form","testimonial","product_grid","featured_product","cart","checkout","product_details"],_n=1e4,bn={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"},Nt=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."),yt=i.z.strictObject({label:i.z.string().trim().min(1).max(120),target:i.z.enum(["_self","_blank"]).optional(),url:Nt}),qe=yt.extend({children:i.z.array(yt).max(20).optional()}),kn=i.z.strictObject({label:i.z.string().trim().min(1).max(120).optional(),url:Nt.optional()}).refine(e=>!!(e.label||e.url),{message:"Navigation item match requires label or url."}),Q=i.z.strictObject({items:i.z.array(qe).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:kn.optional().describe('For mode "update", identifies the existing navigation item to update.'),mode:i.z.enum(["append","replace","update"]).default("append")}),Z=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(qe).min(1).max(30).optional()}),xe=i.z.strictObject({limit:i.z.number().int().min(1).max(8).default(4),query:i.z.string().trim().min(2).max(300)}),Re=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.")}),Me=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()}),De=i.z.strictObject({includeBlockContent:i.z.boolean().default(!1),includeBlocks:i.z.boolean().default(!0)}),ee=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()}),te=i.z.strictObject({blockId:i.z.number().int().positive(),blockType:i.z.enum(G).optional(),content:i.z.record(i.z.string(),i.z.unknown())}),ne=i.z.strictObject({blockIndex:i.z.number().int().min(0),blockType:i.z.enum(G).optional(),columnIndex:i.z.number().int().min(0),content:i.z.record(i.z.string(),i.z.unknown()),parentBlockId:i.z.number().int().positive()}),wn=i.z.enum(["page","post","product"]),H=i.z.strictObject({contentType:wn.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()}),oe=i.z.strictObject({blockType:i.z.enum(G),content:i.z.record(i.z.string(),i.z.unknown()),order:i.z.number().int().min(0).optional()}),re=H.extend({images:i.z.array(i.z.string().trim().min(1).max(2048)).min(1).max(12).describe("External https image URLs (imported into the media library automatically) and/or existing media library ids. The first entry is the feature image (pages/posts) or the main product image (products).")}),ie=H.extend({anchorBlockId:i.z.number().int().positive().optional(),anchorBlockType:i.z.enum(G).optional(),block:oe,position:i.z.enum(["before","after","start","end"]).default("end")}),ae=i.z.strictObject({blocks:i.z.array(oe).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()}),se=i.z.strictObject({blocks:i.z.array(oe).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()}),ce=i.z.strictObject({blocks:i.z.array(oe).max(20).optional().describe("Content blocks for the product description area, same block vocabulary as create_cms_page. Rendered on the public product page in place of the plain description."),description_html:i.z.string().max(6e4).optional().describe("The product body as an HTML fragment (headings, paragraphs, lists, bold/italic/links). Converted to the editor document automatically. Prefer this over description_json."),description_json:i.z.unknown().optional(),freemius_plan_id:i.z.string().optional(),freemius_product_id:i.z.string().optional(),images:i.z.array(i.z.string().trim().min(1).max(2048)).max(12).optional().describe("Product images, in order: the first becomes the main product image and the rest the gallery. Each entry is either an external https image URL (imported into the media library automatically) or an existing media library id."),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()}),le=H.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()}),Ge=H,ue=H,Ut=i.z.discriminatedUnion("tool",[i.z.strictObject({input:ae,tool:i.z.literal("create_cms_page")}),i.z.strictObject({input:se,tool:i.z.literal("create_cms_post")}),i.z.strictObject({input:ce,tool:i.z.literal("create_cms_product")}),i.z.strictObject({input:ue,tool:i.z.literal("delete_cms_item")}),i.z.strictObject({input:le,tool:i.z.literal("update_cms_item_field")}),i.z.strictObject({input:te,tool:i.z.literal("update_content_block")}),i.z.strictObject({input:ie,tool:i.z.literal("insert_content_block")}),i.z.strictObject({input:ee,tool:i.z.literal("update_current_cms_fields")}),i.z.strictObject({input:Z,tool:i.z.literal("update_footer")}),i.z.strictObject({input:Q,tool:i.z.literal("update_navigation_bar")}),i.z.strictObject({input:ne,tool:i.z.literal("update_section_column_block")}),i.z.strictObject({input:re,tool:i.z.literal("set_content_images")})]),In=i.z.union([ae.extend({tool:i.z.literal("create_cms_page")}).transform(({tool:e,...t})=>({input:t,tool:e})),se.extend({tool:i.z.literal("create_cms_post")}).transform(({tool:e,...t})=>({input:t,tool:e})),ce.extend({tool:i.z.literal("create_cms_product")}).transform(({tool:e,...t})=>({input:t,tool:e})),ue.extend({tool:i.z.literal("delete_cms_item")}).transform(({tool:e,...t})=>({input:t,tool:e})),le.extend({tool:i.z.literal("update_cms_item_field")}).transform(({tool:e,...t})=>({input:t,tool:e})),te.extend({tool:i.z.literal("update_content_block")}).transform(({tool:e,...t})=>({input:t,tool:e})),ie.extend({tool:i.z.literal("insert_content_block")}).transform(({tool:e,...t})=>({input:t,tool:e})),ee.extend({tool:i.z.literal("update_current_cms_fields")}).transform(({tool:e,...t})=>({input:t,tool:e})),Z.extend({tool:i.z.literal("update_footer")}).transform(({tool:e,...t})=>({input:t,tool:e})),Q.extend({tool:i.z.literal("update_navigation_bar")}).transform(({tool:e,...t})=>({input:t,tool:e})),ne.extend({tool:i.z.literal("update_section_column_block")}).transform(({tool:e,...t})=>({input:t,tool:e})),re.extend({tool:i.z.literal("set_content_images")}).transform(({tool:e,...t})=>({input:t,tool:e}))]),Tn=i.z.string().transform((e,t)=>{const n=vn(e);return n.success?n.action:(t.addIssue({code:"custom",message:n.message}),i.z.NEVER)}),xn=i.z.union([Ut,In,Tn]),Ke=i.z.strictObject({actions:i.z.array(xn).min(1).max(8),summary:i.z.string().trim().min(1).max(500).optional()});function Cn(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 _t(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 zn(e){const t=e.trim();return t.startsWith("'")&&t.endsWith("'")||t.startsWith('"')&&t.endsWith('"')||t.startsWith("[")||t.startsWith("{")?JSON.parse(_t(t)):/^-?\d+(?:\.\d+)?$/.test(t)?Number(t):t==="true"||t==="True"?!0:t==="false"||t==="False"?!1:t==="null"||t==="None"?null:t}function Sn(e){const t={};for(const n of Cn(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]=zn(n.slice(o+1))}return t}function vn(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=Sn(n[2])}catch(c){return{message:c instanceof Error?c.message:"Could not parse action-plan command arguments.",success:!1}}const a={input:r,tool:o},s=Ut.safeParse(a);return s.success?{action:s.data,success:!0}:{message:`Invalid action-plan command "${o}": ${s.error.issues.map(c=>c.message).join("; ")}`,success:!1}}function En(e){return e.normalize("NFD").replace(/[\u0300-\u036f]/g,"").toLowerCase().replace(/\s+/g," ").trim()}function fe(e,t){return t.some(n=>e.includes(n))}function $n(e){const t=En(e),n=fe(t,["add ","insert ","put ","create "]),o=fe(t,["title","heading","description","intro","copy","paragraph"]),r=t.includes("form")&&fe(t,["above","before"]),a=t.includes("contact page")||t.includes("contact pages")||t.includes("contact us")||t.includes("contactez-nous"),s=t.includes("english")&&fe(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 An=i.z.enum(G),bt=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"])}),Pn=i.z.object({gradient:bt.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:bt,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"])}),Nn=i.z.object({block_type:An,content:i.z.record(i.z.string(),i.z.any()),temp_id:i.z.string().optional()}),Un=i.z.object({background:Pn,column_blocks:i.z.array(i.z.array(Nn)),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()}),Fn={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(),categoryIds:i.z.array(i.z.string()).max(20).optional(),limit:i.z.number().min(0).max(48).default(6),productIds:i.z.array(i.z.string()).max(24).optional(),showPagination:i.z.boolean().default(!1),title:i.z.string().optional(),type:i.z.enum(["latest","category","manual"]).default("latest")}),section:Un,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 On(e){return G.includes(e)}function jn(e){return typeof e?.validateBlockContent=="function"?e.validateBlockContent:null}function Bn(e,t,n){const o=jn(n);if(o)return o(e,t);const r=Fn[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 kt(){return i.z.object({content:i.z.array(i.z.any()).optional(),type:i.z.literal("doc")})}function He(){try{const{revalidatePath:e}=require("next/cache");return e}catch{return null}}function C(e){if(!e?.supabase)throw new Error("A Supabase service client is required to execute Cortex AI global tools.");return e.supabase}function Ln(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 V(e){const t=Me.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 Ve(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 Ft(e){const t=String(e.entityId||"").trim();if(!t)throw new Error(`Current ${e.contentType} id is missing.`);return t}function Ce(e){return e.contentType==="product"?Ft(e):Ve(e)}const qn=/^https?:\/\//i,Rn=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;async function de(e,t,n){if(typeof e!="string")return null;const o=e.trim();if(!o)return null;if(!qn.test(o)){if(Rn.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}async function Ot(e,t,n){const o=[];for(let r=0;r<e.length;r+=1){const a=await de(e[r],t,`${n} image ${r+1}`);a&&o.push(a)}return o}async function Mn(e){const t=[...new Set(e.mediaIds)],{error:n}=await e.supabase.from("product_media").delete().eq("product_id",e.productId);if(n)throw new Error(`Could not clear the product's existing images: ${_(n)}`);if(t.length>0){const{error:o}=await e.supabase.from("product_media").insert(t.map((r,a)=>({media_id:r,product_id:e.productId,sort_order:a})));if(o)throw new Error(`Could not save the product images: ${_(o)}`)}return t}async function ze(e){if(!e.productId)return!1;const{data:t,error:n}=await e.supabase.from("product_drafts").select("id, blocks, meta").eq("product_id",e.productId).maybeSingle();if(n||!t)return!1;const o=e.patch({blocks:Array.isArray(t.blocks)?D(t.blocks):[],meta:E(t.meta)?D(t.meta):{}}),r={updated_at:new Date().toISOString()};if(o.blocks&&(r.blocks=o.blocks),o.meta&&(r.meta=o.meta),Object.keys(r).length===1)return!1;const{error:a}=await e.supabase.from("product_drafts").update(r).eq("id",t.id);if(a)throw new Error(`The product was updated, but its open draft could not be kept in sync: ${_(a)}. Publishing that draft would undo this change — publish or discard it in the product editor first.`);return!0}function jt(e){return typeof e=="string"?e.trim().replace(/^\/+|\/+$/g,""):""}function Dn(e,t){const n=jt(t??e.slug);return n?e.contentType==="page"?n==="home"?"/":`/${n}`:e.contentType==="post"?`/article/${n}`:`/product/${n}`:null}function Gn(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 N(e,t,n){const o=e?.revalidatePath??He();if(!o)return;o(Gn(t));const r=Dn(t,n);r&&o(r),t.contentType==="page"&&r!=="/"&&o("/"),t.contentType==="product"&&o("/cms/products")}function Bt(e){const t=e?.revalidatePath??He();t&&(t("/","layout"),t("/cms/navigation"))}function _(e){return e?typeof e=="object"&&"message"in e?String(e.message||"Unknown database error."):String(e):"Unknown database error."}async function Kn(){return Promise.resolve().then(()=>require("./ai-global-agent-ecommerce.cjs.js"))}function Pe(e){return e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?`[${e.map(t=>Pe(t)).join(",")}]`:`{${Object.keys(e).filter(t=>t!=="temp_id").sort().map(t=>`${JSON.stringify(t)}:${Pe(e[t])}`).join(",")}}`}function Hn(e){let t=2166136261;const n=Pe(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 Ne(e){return e.replace(/\s+/g," ").trim().toUpperCase()}function Vn(e,t,n){return`${Ne(`CONFIRM ${e} ${t}`)} #${Hn(n)}`}function Lt(e){return{confirmationPhrase:Vn(e.action,e.subject,e.payload),mutationExecuted:!1,preview:e.preview,requiresConfirmation:!0,success:!0}}function U(e,t){const n=e[t];return typeof n=="string"&&n.trim()?n.trim():null}function R(e,t){const n=Number(e[t]);return Number.isFinite(n)?n:null}function P(e,t,n=`${t}s`){return`${e} ${e===1?t:n}`}function Wn(e,t){const n=U(t,"summary");if(n)return n;const o=U(t,"title"),r=U(t,"slug"),a=U(t,"status"),s=U(t,"contentType"),c=U(t,"field"),u=U(t,"mode"),d=U(t,"languageCode"),l=R(t,"blockCount"),m=R(t,"itemCount"),h=R(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}"`:""}${l!==null?` with ${P(l,"content block")}`:""}.`;if(e==="create_cms_product"){const p=R(t,"imageCount"),g=R(t,"blockCount"),f=[p?P(p,"image"):null,g?P(g,"description block"):R(t,"descriptionLength")?"a full description":null].filter(Boolean);return`Create ${a||"draft"} product "${o||r||"Untitled"}"${r?` at slug "${r}"`:""}${f.length?` with ${f.join(" and ")}`:""}.`}if(e==="update_cms_item_field")return`Update ${c||"one field"} on the ${s||"CMS item"} "${o||r||"selected item"}".`;if(e==="update_navigation_bar")return`${u==="append"?"Add":u==="update"?"Update":"Replace"} ${m!==null?P(m,"navigation item"):"navigation items"} in the ${d||"selected"} header navigation.`;if(e==="update_footer"){const p=R(t,"linkCount");return`Update the ${d||"selected"} footer${p!==null?` with ${P(p,"link")}`:""}.`}return e==="update_content_block"?`Update the selected ${U(t,"blockType")||"content"} block.`:e==="insert_content_block"?`Insert ${U(t,"blockType")||"content"} block on the ${s||"CMS item"} "${o||r||"selected item"}".`:e==="update_section_column_block"?`Update the selected nested ${U(t,"nestedBlockType")||"section"} block.`:e==="delete_cms_item"||e==="prepare_delete_cms_item"?`Delete ${h!==null?P(h,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=Lt(e),n=Ne(e.context?.latestUserMessage||""),o=Ne(t.confirmationPhrase);return n.includes(o)?null:t}function We(e){const t=e?.actorUserId;if(!t)throw new Error("A confirmed CMS mutation requires an authenticated admin actor.");return t}function Je(){return globalThis.crypto?.randomUUID?.()||`id-${Date.now()}-${Math.random().toString(36).slice(2)}`}function L(e){return e.toLowerCase().trim().replace(/\s+/g,"-").replace(/[^a-z0-9-]/g,"").replace(/-+/g,"-").replace(/^-|-$/g,"").slice(0,300)}function Ye(e){return(e||"USD").trim().toUpperCase()}const Jn=new Set(["BIF","CLP","DJF","GNF","JPY","KMF","KRW","MGA","PYG","RWF","UGX","VND","VUV","XAF","XOF","XPF"]);function Yn(e){return Jn.has(Ye(e))?0:2}function qt(e,t){return Math.round(e*10**Yn(t))}function Xn(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=Ye(o||t);n[a]=qt(r,a)}return n},{})}function pe(e,t){if(!E(e))throw new Error(`${t} content must be a JSON object.`);return JSON.parse(JSON.stringify(e))}function D(e){return JSON.parse(JSON.stringify(e))}function E(e){return!!(e&&typeof e=="object"&&!Array.isArray(e))}function Ue(e,t){const n=D(e);for(const[o,r]of Object.entries(t))if(r!==void 0){if(E(r)&&E(n[o])){n[o]=Ue(n[o],r);continue}n[o]=D(r)}return n}function Rt(e,t){if(t.contentType==="product"){if(String(e.product_id??"")!==String(Ft(t)))throw new Error(`Block ${e.id} does not belong to the current product being edited.`);return}const n=Ve(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 be(e,t){const n=typeof e=="string"?e:"";if(!On(n))throw new Error(`${t} has unsupported block type "${n||"unknown"}".`);return n}function Mt(e,t,n){if(e&&e!==t)throw new Error(`${n} is a "${t}" block. Refusing to update it as "${e}".`)}function M(e,t,n,o){const r=Bn(e,t,o);if(!r.isValid)throw new Error(`${n} content is invalid for block type "${e}": ${r.errors.join("; ")}`)}function Dt(e){return e==="section"}function Qn(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 ke(e){return`ai-${e}-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}function Fe(e,t,n){if(!E(e))throw new Error(`${t} must be a JSON object.`);const o=e.block_type??e.blockType,r=be(o,t);if(Dt(r))throw new Error(`${t} cannot be a nested ${r} block.`);const a=Vt(r,pe(e.content,t),t,n),s=e.temp_id??e.tempId,c=typeof s=="string"&&s.trim()?s:ke(r);return{block_type:r,content:a,temp_id:c}}function Zn(e,t){const n=[];if("append_block"in e&&n.push(Fe(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(Fe(r,`Nested block to append ${a}`,t))})}return n}function eo(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=Qn(e);if(!n)return null;const o=pe(e,`Nested ${n} block`);return M(n,o,`Nested ${n} block`,t),{block_type:n,content:o,temp_id:ke(n)}}function to(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 no(e,t,n,o){if(!Dt(e))return Ue(t,n);const r={...n},a=Zn(r,o),s=eo(r,o);s&&a.push(s),delete r.append_block,delete r.append_blocks,delete r.append_column_index,delete r.column_index;const c=Ue(t,r);if(a.length>0){const u=Array.isArray(t.column_blocks)?D(t.column_blocks):[],d=to(n,u.length),l=u.length>0?u:[[]];for(;l.length<=d;)l.push([]);l[d]=[...l[d]||[],...a],c.column_blocks=l}return c}function oo(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 K(e){return typeof e=="string"?e.trim().toLowerCase():""}function wt(e){return typeof e=="string"?e.trim().toLowerCase():""}function Gt(e){return e.reduce((t,n)=>t+1+(n.children?.length||0),0)}function _e(e){return typeof e=="string"?e.trim().toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g,""):""}async function W(e,t){const n=t.trim(),o=_e(n),r=bn[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}": ${_(s)}`);const u=(Array.isArray(a)?a:[]).filter(l=>l.is_active!==!1),d=u.find(l=>{const m=_e(l.code),h=_e(l.name);return m===o||m===r||h===o});if(!d?.id||!d?.code){const l=u.map(m=>m.code).filter(Boolean).join(", ");throw new Error(`Language "${t}" was not found.${l?` Available languages: ${l}.`:""}`)}return{code:String(d.code),id:Number(d.id)}}async function Se(e,t){if(t)return W(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: ${_(o)}`);const r=(Array.isArray(n)?n:[]).filter(s=>s.is_active!==!1),a=r.find(s=>s.is_default)||r.find(s=>_e(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 It(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 Ye(r?.code||"USD")}catch{return"USD"}}async function ro(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}: ${_(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 me(e,t){const n=Me.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),c=e.title??(r?void 0:n?.title??void 0),u=await ro({contentType:o,entityId:a,slug:a===void 0&&s||void 0,supabase:C(t),title:a===void 0&&!s&&c||void 0});return{contentType:o,item:u}}async function we(e){const t=await ao({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: ${_(r)}`);return Number(o.id)}function io(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 ao(e){const t=io(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: ${_(o)}`);const r=Array.isArray(n)?n[0]:n;if(!r?.id)return null;let a=Je();if(r.translation_group_id){const{data:s,error:c}=await e.supabase.from("pages").select("id").eq("translation_group_id",r.translation_group_id);if(c)throw new Error(`Failed to inspect linked page translations for navigation item: ${_(c)}`);const u=new Set((Array.isArray(s)?s:[]).map(h=>String(h.id)).filter(Boolean)),{data:d,error:l}=await e.supabase.from("navigation_items").select("id, page_id, translation_group_id, menu_key").eq("menu_key",e.menuKey);if(l)throw new Error(`Failed to inspect related navigation translations: ${_(l)}`);const m=(Array.isArray(d)?d:[]).find(h=>h.translation_group_id&&u.has(String(h.page_id)));m?.translation_group_id&&(a=m.translation_group_id)}return{navigationTranslationGroupId:a,pageId:Number(r.id)}}async function Kt(e){const t=await W(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: ${_(o)}`);const r=Array.isArray(n)?n:[],a=r.filter(d=>d.parent_id==null).length,s=Gt(e.items);Ht({existingItemCount:r.length,existingTopLevelCount:a,languageCode:t.code,menuKey:e.menuKey,replacementItemCount:s});const{error:c}=await e.supabase.from("navigation_items").delete().eq("menu_key",e.menuKey).eq("language_id",t.id);if(c)throw new Error(`Failed to clear ${e.menuKey} navigation items: ${_(c)}`);let u=0;for(const[d,l]of e.items.entries()){const m=await we({item:l,languageId:t.id,menuKey:e.menuKey,order:d,supabase:e.supabase});u++;for(const[h,p]of(l.children??[]).entries())await we({item:p,languageId:t.id,menuKey:e.menuKey,order:h,parentId:m,supabase:e.supabase}),u++}return{insertedCount:u,languageCode:t.code,menuKey:e.menuKey,skippedCount:0,updatedCount:0}}function Ht(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 so(e){const t=await W(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: ${_(o)}`);const r=Array.isArray(n)?n:[];Ht({existingItemCount:r.length,existingTopLevelCount:r.filter(a=>a.parent_id==null).length,languageCode:t.code,menuKey:e.menuKey,replacementItemCount:Gt(e.items)})}async function co(e){if(e.items.length!==1)throw new Error('mode "update" requires exactly one navigation item.');const t=await W(e.supabase,e.languageCode),n=e.items[0],o=K(e.match?.url)||K(n.url),r=wt(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: ${_(s)}`);const u=(Array.isArray(a)?a:[]).find(l=>{const m=K(l.url),h=wt(l.label);return!!(o&&m===o||r&&h===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: ${_(d)}`);return{insertedCount:0,languageCode:t.code,menuKey:e.menuKey,skippedCount:0,updatedCount:1}}async function lo(e){const t=await W(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: ${_(o)}`);let r=0,a=0;const s=Array.isArray(n)?n:[],c=new Set(s.map(l=>K(l.url)).filter(Boolean)),u=s.filter(l=>l.parent_id==null).map(l=>Number(l.order)).filter(Number.isFinite);let d=u.length>0?Math.max(...u)+1:s.length;for(const l of e.items){const m=K(l.url);if(m&&c.has(m)){a++;continue}const h=await we({item:l,languageId:t.id,menuKey:e.menuKey,order:d,supabase:e.supabase});r++,d++,m&&c.add(m);let p=0;for(const g of l.children??[]){const f=K(g.url);if(f&&c.has(f)){a++;continue}await we({item:g,languageId:t.id,menuKey:e.menuKey,order:p,parentId:h,supabase:e.supabase}),r++,p++,f&&c.add(f)}}return{insertedCount:r,languageCode:t.code,menuKey:e.menuKey,skippedCount:a,updatedCount:0}}function S(e){return typeof e=="string"&&e.trim()?e.trim():""}function uo(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function po(e){const t=S(e.field_type??e.fieldType??e.type??e.input_type).toLowerCase().replace(/\s+/g,"_"),n=S(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 mo(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=E(n)?n:{},a=S(r.label??r.name)||(o===0?"Name":o===1?"Email":"Message"),s=po({...r,label:a}),c=r.is_required??r.isRequired??r.required;return{field_type:s,is_required:typeof c=="boolean"?c:!0,label:a,options:Array.isArray(r.options)?r.options:void 0,placeholder:S(r.placeholder)||void 0,temp_id:S(r.temp_id??r.tempId??r.id)||`field-${o+1}`}})}const go=new Set(["none","sm","md","lg","xl"]),Tt=new Set(["none","sm","md","lg","xl"]),fo=new Set(["full-width","container","container-sm","container-lg","container-xl"]),ho=new Set(["start","center","end","stretch"]),yo=new Set(["none","theme","solid","gradient","image"]),_o=new Set(["primary","secondary","muted","accent","destructive"]),bo=new Set(["center","top","bottom","left","right"]);function ko(e){return typeof e=="string"&&/^https?:\/\//i.test(e.trim())}function B(e,t,n){return typeof e=="string"&&t.has(e)?e:n}function wo(e){return Number.isFinite(e)?Math.min(4,Math.max(1,Math.round(e))):1}function Io(e){const t=[{color:"#1e3a8a",position:0},{color:"#3b82f6",position:100}];if(!E(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 To(e){if(!E(e))return{type:"none"};const t=B(e.type,yo,"none"),n=typeof e.min_height=="string"&&e.min_height.trim()?{min_height:e.min_height}:{};if(t==="theme")return{theme:B(e.theme,_o,"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:Io(e.gradient),type:t,...n};if(t==="image"){const o=E(e.image)?e.image:null,r=o&&ko(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:B(o.position,bo,"center"),size:o.size==="contain"?"contain":"cover"},type:t,...n}:{type:"none"}}return{type:"none",...n}}function xo(e,t,n){const o=e.is_hero===!0;let r=Array.isArray(e.column_blocks)?e.column_blocks:[];r.length>0&&r.every(f=>E(f)&&!Array.isArray(f))&&(r=[r]);const a=r.map((f,k)=>(Array.isArray(f)?f:[]).map((w,b)=>Fe(w,`${t} column ${k} block ${b}`,n))),s=a.length>0?a:[[]],c=wo(s.length),u=E(e.responsive_columns)?e.responsive_columns:{},d=Number(u.tablet),l=Number(u.mobile),m=Number.isFinite(d)?Math.min(3,Math.max(1,Math.min(c,d))):Math.min(3,c),h=Number.isFinite(l)?Math.min(2,Math.max(1,l)):1,p=E(e.padding)?e.padding:{},g={...e,background:To(e.background),column_blocks:s,column_gap:B(e.column_gap,go,"lg"),container_type:B(e.container_type,fo,"container"),padding:{bottom:B(p.bottom,Tt,"xl"),top:B(p.top,Tt,"xl")},responsive_columns:{desktop:c,mobile:h,tablet:m},vertical_alignment:B(e.vertical_alignment,ho,o?"center":"start")};return g.slider===!0&&!(Array.isArray(g.slides)&&g.slides.length>0)&&(g.slider=!1),g}function Vt(e,t,n,o){if(e==="section"){const a=xo(t,n,o);return M(e,a,n,o),a}const r=D(t);if(e==="heading"&&(r.text_content=S(r.text_content)||S(r.text)||S(r.title)||S(r.heading)||"Untitled",r.level=typeof r.level=="number"?r.level:1),e==="text"){const a=S(r.html_content)||S(r.html)||S(r.content)||S(r.text);a&&(r.html_content=/<\/?[a-z][\s\S]*>/i.test(a)?a:`<p>${uo(a)}</p>`)}return e==="button"&&(r.text=S(r.text)||S(r.label)||S(r.title)||"Learn More",r.url=S(r.url)||S(r.href)||S(r.link)||"#"),e==="form"&&(r.fields=mo(r.fields),r.submit_button_text=S(r.submit_button_text??r.submitButtonText??r.button_text)||"Send Message",r.success_message=S(r.success_message??r.successMessage)||"Thanks for reaching out. We will reply as soon as possible."),M(e,r,n,o),r}function Ie(e,t,n){const o=Vt(e.blockType,pe(e.content,`Block ${t}`),`Block ${t}`,n);return{block_type:e.blockType,content:o,order:e.order??t}}function Co(e,t="Contact Us",n){return[Ie({blockType:"section",content:{is_hero:!0,background:{type:"none"},column_blocks:[[{block_type:"heading",content:{level:1,textAlign:"center",text_content:t},temp_id:ke("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:ke("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),Ie({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?Co(t,n,o):(e||[]).map((r,a)=>Ie(r,a,o))}async function Xe(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: ${_(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 Qe(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: ${_(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 Ze(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,product_id:e.contentType==="product"?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: ${_(o)}`);return ge(e.blocks,e.supabase),Array.isArray(n)?n:[]}async function et(e){const t=e.contentType==="page"?"pages":e.contentType==="post"?"posts":"products";await e.supabase.from(t).delete().eq("id",e.itemId)}function tt(e,t){return e==="page"?`/cms/pages/${t}/edit`:e==="post"?`/cms/posts/${t}/edit`:`/cms/products/${t}/edit`}function xt(e){return e==="page"?"/cms/pages":e==="post"?"/cms/posts":"/cms/products"}async function nt(e,t){const n=Q.parse(e),o=C(t);n.mode==="replace"&&await so({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 co({items:n.items,languageCode:n.languageCode,match:n.match,menuKey:"HEADER",supabase:o}):n.mode==="append"?await lo({items:n.items,languageCode:n.languageCode,menuKey:"HEADER",supabase:o}):await Kt({items:n.items,languageCode:n.languageCode,menuKey:"HEADER",supabase:o});return Bt(t),{...a,mutationExecuted:!0,mode:n.mode,success:!0}}async function ot(e,t){const n=Z.parse(e);if(!n.links?.length&&!n.copyright)throw new Error("update_footer requires links or copyright.");const o=C(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 Kt({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: ${_(s)}`)}return Bt(t),{copyrightUpdated:!!n.copyright,footerNavigation:a,mutationExecuted:!0,success:!0}}function Wt(e){return typeof e=="string"?e.toLowerCase():""}function zo(e,t){const n=t.map(Wt).join(" ");return e.reduce((o,r)=>o+(n.includes(r)?1:0),0)}function Ct(e,t){return(e.find(n=>t.some(o=>Wt(n).includes(o)))||e.find(n=>n.trim().length>0)||"No excerpt available.").slice(0,500)}async function Jt(e,t){const n=xe.parse(e),o=C(t),r=n.query.toLowerCase().split(/\s+/).map(l=>l.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: ${_(a.error)}`);if(s.error)throw new Error(`Failed to search documentation pages: ${_(s.error)}`);const c=(a.data??[]).map(l=>({excerpt:Ct([l.excerpt,l.subtitle,l.meta_description,l.slug].filter(Boolean),r),source:"post",title:l.title,url:`/article/${l.slug}`})),u=(s.data??[]).map(l=>({excerpt:Ct([l.meta_description,l.slug].filter(Boolean),r),source:"page",title:l.title,url:l.slug==="home"?"/":`/${l.slug}`})),d=[...c,...u].map(l=>({...l,score:zo(r,[l.title,l.excerpt,l.url])})).filter(l=>l.score>0).sort((l,m)=>m.score-l.score).slice(0,n.limit).map(l=>({excerpt:l.excerpt,source:l.source,title:l.title,url:l.url}));return{query:n.query,results:d,success:!0}}async function Yt(e,t,n=_n){const o=xe.safeParse(e),r=o.success?o.data.query:"";return Ln(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 So=["pending","trial","paid","shipped","cancelled","refunded","failed"],vo={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 Eo(e){return String(e??"unknown").trim().toLowerCase()||"unknown"}function zt(e){const t=Object.fromEntries(So.map(n=>[n,0]));for(const n of e){const o=Eo(n.status);t[o]=(t[o]??0)+1}return t}function $o(e){const n=e.toLowerCase().replace(/[^a-z0-9_]+/g," ").split(/\s+/).filter(Boolean);for(const o of n){const r=vo[o];if(r)return r}return null}function X(e){const t=Number(e);return Number.isFinite(t)?t:0}async function Xt(e,t){const n=Re.parse(e),o=C(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 c=n.currency?.toUpperCase(),u=$o(n.query),d=o.from("orders").select("id, status, total, currency, created_at, paid_at");c&&d.eq("currency",c),a&&d.gte("created_at",a.toISOString()),s&&d.lte("created_at",s.toISOString());const m=n.reportType==="products"||n.reportType==="revenue"||n.reportType==="general"?o.from("order_items").select(`
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const C=require("ai"),hn=require("./ai-global-agent-db-tools.cjs.js"),yn=require("./ai-global-agent-custom-block-tools.cjs.js"),Pt=require("./editor-document-from-html.cjs.js");require("./zod-config.cjs.js");const i=require("zod"),G=["text","heading","image","button","posts_grid","video_embed","section","form","testimonial","product_grid","featured_product","cart","checkout","product_details"],_n=1e4,bn={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"},Nt=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."),yt=i.z.strictObject({label:i.z.string().trim().min(1).max(120),target:i.z.enum(["_self","_blank"]).optional(),url:Nt}),qe=yt.extend({children:i.z.array(yt).max(20).optional()}),kn=i.z.strictObject({label:i.z.string().trim().min(1).max(120).optional(),url:Nt.optional()}).refine(e=>!!(e.label||e.url),{message:"Navigation item match requires label or url."}),Q=i.z.strictObject({items:i.z.array(qe).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:kn.optional().describe('For mode "update", identifies the existing navigation item to update.'),mode:i.z.enum(["append","replace","update"]).default("append")}),Z=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(qe).min(1).max(30).optional()}),xe=i.z.strictObject({limit:i.z.number().int().min(1).max(8).default(4),query:i.z.string().trim().min(2).max(300)}),Re=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.")}),Me=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()}),De=i.z.strictObject({includeBlockContent:i.z.boolean().default(!1),includeBlocks:i.z.boolean().default(!0)}),ee=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()}),te=i.z.strictObject({blockId:i.z.number().int().positive(),blockType:i.z.enum(G).optional(),content:i.z.record(i.z.string(),i.z.unknown())}),ne=i.z.strictObject({blockIndex:i.z.number().int().min(0),blockType:i.z.enum(G).optional(),columnIndex:i.z.number().int().min(0),content:i.z.record(i.z.string(),i.z.unknown()),parentBlockId:i.z.number().int().positive()}),wn=i.z.enum(["page","post","product"]),H=i.z.strictObject({contentType:wn.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()}),oe=i.z.strictObject({blockType:i.z.enum(G),content:i.z.record(i.z.string(),i.z.unknown()),order:i.z.number().int().min(0).optional()}),re=H.extend({images:i.z.array(i.z.string().trim().min(1).max(2048)).min(1).max(12).describe("External https image URLs (imported into the media library automatically) and/or existing media library ids. The first entry is the feature image (pages/posts) or the main product image (products).")}),ie=H.extend({anchorBlockId:i.z.number().int().positive().optional(),anchorBlockType:i.z.enum(G).optional(),block:oe,position:i.z.enum(["before","after","start","end"]).default("end")}),ae=i.z.strictObject({blocks:i.z.array(oe).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()}),se=i.z.strictObject({blocks:i.z.array(oe).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()}),ce=i.z.strictObject({blocks:i.z.array(oe).max(20).optional().describe("Content blocks for the product description area, same block vocabulary as create_cms_page. Rendered on the public product page in place of the plain description."),description_html:i.z.string().max(6e4).optional().describe("The product body as an HTML fragment (headings, paragraphs, lists, bold/italic/links). Converted to the editor document automatically. Prefer this over description_json."),description_json:i.z.unknown().optional(),freemius_plan_id:i.z.string().optional(),freemius_product_id:i.z.string().optional(),images:i.z.array(i.z.string().trim().min(1).max(2048)).max(12).optional().describe("Product images, in order: the first becomes the main product image and the rest the gallery. Each entry is either an external https image URL (imported into the media library automatically) or an existing media library id."),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()}),le=H.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()}),Ge=H,ue=H,Ut=i.z.discriminatedUnion("tool",[i.z.strictObject({input:ae,tool:i.z.literal("create_cms_page")}),i.z.strictObject({input:se,tool:i.z.literal("create_cms_post")}),i.z.strictObject({input:ce,tool:i.z.literal("create_cms_product")}),i.z.strictObject({input:ue,tool:i.z.literal("delete_cms_item")}),i.z.strictObject({input:le,tool:i.z.literal("update_cms_item_field")}),i.z.strictObject({input:te,tool:i.z.literal("update_content_block")}),i.z.strictObject({input:ie,tool:i.z.literal("insert_content_block")}),i.z.strictObject({input:ee,tool:i.z.literal("update_current_cms_fields")}),i.z.strictObject({input:Z,tool:i.z.literal("update_footer")}),i.z.strictObject({input:Q,tool:i.z.literal("update_navigation_bar")}),i.z.strictObject({input:ne,tool:i.z.literal("update_section_column_block")}),i.z.strictObject({input:re,tool:i.z.literal("set_content_images")})]),In=i.z.union([ae.extend({tool:i.z.literal("create_cms_page")}).transform(({tool:e,...t})=>({input:t,tool:e})),se.extend({tool:i.z.literal("create_cms_post")}).transform(({tool:e,...t})=>({input:t,tool:e})),ce.extend({tool:i.z.literal("create_cms_product")}).transform(({tool:e,...t})=>({input:t,tool:e})),ue.extend({tool:i.z.literal("delete_cms_item")}).transform(({tool:e,...t})=>({input:t,tool:e})),le.extend({tool:i.z.literal("update_cms_item_field")}).transform(({tool:e,...t})=>({input:t,tool:e})),te.extend({tool:i.z.literal("update_content_block")}).transform(({tool:e,...t})=>({input:t,tool:e})),ie.extend({tool:i.z.literal("insert_content_block")}).transform(({tool:e,...t})=>({input:t,tool:e})),ee.extend({tool:i.z.literal("update_current_cms_fields")}).transform(({tool:e,...t})=>({input:t,tool:e})),Z.extend({tool:i.z.literal("update_footer")}).transform(({tool:e,...t})=>({input:t,tool:e})),Q.extend({tool:i.z.literal("update_navigation_bar")}).transform(({tool:e,...t})=>({input:t,tool:e})),ne.extend({tool:i.z.literal("update_section_column_block")}).transform(({tool:e,...t})=>({input:t,tool:e})),re.extend({tool:i.z.literal("set_content_images")}).transform(({tool:e,...t})=>({input:t,tool:e}))]),Tn=i.z.string().transform((e,t)=>{const n=vn(e);return n.success?n.action:(t.addIssue({code:"custom",message:n.message}),i.z.NEVER)}),xn=i.z.union([Ut,In,Tn]),Ke=i.z.strictObject({actions:i.z.array(xn).min(1).max(8),summary:i.z.string().trim().min(1).max(500).optional()});function zn(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 _t(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 Cn(e){const t=e.trim();return t.startsWith("'")&&t.endsWith("'")||t.startsWith('"')&&t.endsWith('"')||t.startsWith("[")||t.startsWith("{")?JSON.parse(_t(t)):/^-?\d+(?:\.\d+)?$/.test(t)?Number(t):t==="true"||t==="True"?!0:t==="false"||t==="False"?!1:t==="null"||t==="None"?null:t}function Sn(e){const t={};for(const n of zn(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]=Cn(n.slice(o+1))}return t}function vn(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=Sn(n[2])}catch(c){return{message:c instanceof Error?c.message:"Could not parse action-plan command arguments.",success:!1}}const a={input:r,tool:o},s=Ut.safeParse(a);return s.success?{action:s.data,success:!0}:{message:`Invalid action-plan command "${o}": ${s.error.issues.map(c=>c.message).join("; ")}`,success:!1}}function En(e){return e.normalize("NFD").replace(/[\u0300-\u036f]/g,"").toLowerCase().replace(/\s+/g," ").trim()}function fe(e,t){return t.some(n=>e.includes(n))}function $n(e){const t=En(e),n=fe(t,["add ","insert ","put ","create "]),o=fe(t,["title","heading","description","intro","copy","paragraph"]),r=t.includes("form")&&fe(t,["above","before"]),a=t.includes("contact page")||t.includes("contact pages")||t.includes("contact us")||t.includes("contactez-nous"),s=t.includes("english")&&fe(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 An=i.z.enum(G),bt=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"])}),Pn=i.z.object({gradient:bt.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:bt,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"])}),Nn=i.z.object({block_type:An,content:i.z.record(i.z.string(),i.z.any()),temp_id:i.z.string().optional()}),Un=i.z.object({background:Pn,column_blocks:i.z.array(i.z.array(Nn)),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()}),Fn={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.union([i.z.enum(["foreground","primary","secondary","accent","muted","destructive","background"]),i.z.string().regex(/^(#(?:[0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})|rgba?\([^)]+\)|hsla?\([^)]+\))$/i,"Must be a hex, rgb(a) or hsl(a) colour")]).optional().describe("Prefer a theme token so the heading adapts to dark mode; use a CSS colour only when the brand requires an exact value"),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(),categoryIds:i.z.array(i.z.string()).max(20).optional(),limit:i.z.number().min(0).max(48).default(6),productIds:i.z.array(i.z.string()).max(24).optional(),showPagination:i.z.boolean().default(!1),title:i.z.string().optional(),type:i.z.enum(["latest","category","manual"]).default("latest")}),section:Un,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 On(e){return G.includes(e)}function jn(e){return typeof e?.validateBlockContent=="function"?e.validateBlockContent:null}function Bn(e,t,n){const o=jn(n);if(o)return o(e,t);const r=Fn[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 kt(){return i.z.object({content:i.z.array(i.z.any()).optional(),type:i.z.literal("doc")})}function He(){try{const{revalidatePath:e}=require("next/cache");return e}catch{return null}}function z(e){if(!e?.supabase)throw new Error("A Supabase service client is required to execute Cortex AI global tools.");return e.supabase}function Ln(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 V(e){const t=Me.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 Ve(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 Ft(e){const t=String(e.entityId||"").trim();if(!t)throw new Error(`Current ${e.contentType} id is missing.`);return t}function ze(e){return e.contentType==="product"?Ft(e):Ve(e)}const qn=/^https?:\/\//i,Rn=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;async function de(e,t,n){if(typeof e!="string")return null;const o=e.trim();if(!o)return null;if(!qn.test(o)){if(Rn.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}async function Ot(e,t,n){const o=[];for(let r=0;r<e.length;r+=1){const a=await de(e[r],t,`${n} image ${r+1}`);a&&o.push(a)}return o}async function Mn(e){const t=[...new Set(e.mediaIds)],{error:n}=await e.supabase.from("product_media").delete().eq("product_id",e.productId);if(n)throw new Error(`Could not clear the product's existing images: ${_(n)}`);if(t.length>0){const{error:o}=await e.supabase.from("product_media").insert(t.map((r,a)=>({media_id:r,product_id:e.productId,sort_order:a})));if(o)throw new Error(`Could not save the product images: ${_(o)}`)}return t}async function Ce(e){if(!e.productId)return!1;const{data:t,error:n}=await e.supabase.from("product_drafts").select("id, blocks, meta").eq("product_id",e.productId).maybeSingle();if(n||!t)return!1;const o=e.patch({blocks:Array.isArray(t.blocks)?D(t.blocks):[],meta:E(t.meta)?D(t.meta):{}}),r={updated_at:new Date().toISOString()};if(o.blocks&&(r.blocks=o.blocks),o.meta&&(r.meta=o.meta),Object.keys(r).length===1)return!1;const{error:a}=await e.supabase.from("product_drafts").update(r).eq("id",t.id);if(a)throw new Error(`The product was updated, but its open draft could not be kept in sync: ${_(a)}. Publishing that draft would undo this change — publish or discard it in the product editor first.`);return!0}function jt(e){return typeof e=="string"?e.trim().replace(/^\/+|\/+$/g,""):""}function Dn(e,t){const n=jt(t??e.slug);return n?e.contentType==="page"?n==="home"?"/":`/${n}`:e.contentType==="post"?`/article/${n}`:`/product/${n}`:null}function Gn(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 N(e,t,n){const o=e?.revalidatePath??He();if(!o)return;o(Gn(t));const r=Dn(t,n);r&&o(r),t.contentType==="page"&&r!=="/"&&o("/"),t.contentType==="product"&&o("/cms/products")}function Bt(e){const t=e?.revalidatePath??He();t&&(t("/","layout"),t("/cms/navigation"))}function _(e){return e?typeof e=="object"&&"message"in e?String(e.message||"Unknown database error."):String(e):"Unknown database error."}async function Kn(){return Promise.resolve().then(()=>require("./ai-global-agent-ecommerce.cjs.js"))}function Pe(e){return e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?`[${e.map(t=>Pe(t)).join(",")}]`:`{${Object.keys(e).filter(t=>t!=="temp_id").sort().map(t=>`${JSON.stringify(t)}:${Pe(e[t])}`).join(",")}}`}function Hn(e){let t=2166136261;const n=Pe(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 Ne(e){return e.replace(/\s+/g," ").trim().toUpperCase()}function Vn(e,t,n){return`${Ne(`CONFIRM ${e} ${t}`)} #${Hn(n)}`}function Lt(e){return{confirmationPhrase:Vn(e.action,e.subject,e.payload),mutationExecuted:!1,preview:e.preview,requiresConfirmation:!0,success:!0}}function U(e,t){const n=e[t];return typeof n=="string"&&n.trim()?n.trim():null}function R(e,t){const n=Number(e[t]);return Number.isFinite(n)?n:null}function P(e,t,n=`${t}s`){return`${e} ${e===1?t:n}`}function Wn(e,t){const n=U(t,"summary");if(n)return n;const o=U(t,"title"),r=U(t,"slug"),a=U(t,"status"),s=U(t,"contentType"),c=U(t,"field"),u=U(t,"mode"),d=U(t,"languageCode"),l=R(t,"blockCount"),m=R(t,"itemCount"),h=R(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}"`:""}${l!==null?` with ${P(l,"content block")}`:""}.`;if(e==="create_cms_product"){const p=R(t,"imageCount"),g=R(t,"blockCount"),f=[p?P(p,"image"):null,g?P(g,"description block"):R(t,"descriptionLength")?"a full description":null].filter(Boolean);return`Create ${a||"draft"} product "${o||r||"Untitled"}"${r?` at slug "${r}"`:""}${f.length?` with ${f.join(" and ")}`:""}.`}if(e==="update_cms_item_field")return`Update ${c||"one field"} on the ${s||"CMS item"} "${o||r||"selected item"}".`;if(e==="update_navigation_bar")return`${u==="append"?"Add":u==="update"?"Update":"Replace"} ${m!==null?P(m,"navigation item"):"navigation items"} in the ${d||"selected"} header navigation.`;if(e==="update_footer"){const p=R(t,"linkCount");return`Update the ${d||"selected"} footer${p!==null?` with ${P(p,"link")}`:""}.`}return e==="update_content_block"?`Update the selected ${U(t,"blockType")||"content"} block.`:e==="insert_content_block"?`Insert ${U(t,"blockType")||"content"} block on the ${s||"CMS item"} "${o||r||"selected item"}".`:e==="update_section_column_block"?`Update the selected nested ${U(t,"nestedBlockType")||"section"} block.`:e==="delete_cms_item"||e==="prepare_delete_cms_item"?`Delete ${h!==null?P(h,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=Lt(e),n=Ne(e.context?.latestUserMessage||""),o=Ne(t.confirmationPhrase);return n.includes(o)?null:t}function We(e){const t=e?.actorUserId;if(!t)throw new Error("A confirmed CMS mutation requires an authenticated admin actor.");return t}function Je(){return globalThis.crypto?.randomUUID?.()||`id-${Date.now()}-${Math.random().toString(36).slice(2)}`}function L(e){return e.toLowerCase().trim().replace(/\s+/g,"-").replace(/[^a-z0-9-]/g,"").replace(/-+/g,"-").replace(/^-|-$/g,"").slice(0,300)}function Ye(e){return(e||"USD").trim().toUpperCase()}const Jn=new Set(["BIF","CLP","DJF","GNF","JPY","KMF","KRW","MGA","PYG","RWF","UGX","VND","VUV","XAF","XOF","XPF"]);function Yn(e){return Jn.has(Ye(e))?0:2}function qt(e,t){return Math.round(e*10**Yn(t))}function Xn(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=Ye(o||t);n[a]=qt(r,a)}return n},{})}function pe(e,t){if(!E(e))throw new Error(`${t} content must be a JSON object.`);return JSON.parse(JSON.stringify(e))}function D(e){return JSON.parse(JSON.stringify(e))}function E(e){return!!(e&&typeof e=="object"&&!Array.isArray(e))}function Ue(e,t){const n=D(e);for(const[o,r]of Object.entries(t))if(r!==void 0){if(E(r)&&E(n[o])){n[o]=Ue(n[o],r);continue}n[o]=D(r)}return n}function Rt(e,t){if(t.contentType==="product"){if(String(e.product_id??"")!==String(Ft(t)))throw new Error(`Block ${e.id} does not belong to the current product being edited.`);return}const n=Ve(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 be(e,t){const n=typeof e=="string"?e:"";if(!On(n))throw new Error(`${t} has unsupported block type "${n||"unknown"}".`);return n}function Mt(e,t,n){if(e&&e!==t)throw new Error(`${n} is a "${t}" block. Refusing to update it as "${e}".`)}function M(e,t,n,o){const r=Bn(e,t,o);if(!r.isValid)throw new Error(`${n} content is invalid for block type "${e}": ${r.errors.join("; ")}`)}function Dt(e){return e==="section"}function Qn(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 ke(e){return`ai-${e}-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}function Fe(e,t,n){if(!E(e))throw new Error(`${t} must be a JSON object.`);const o=e.block_type??e.blockType,r=be(o,t);if(Dt(r))throw new Error(`${t} cannot be a nested ${r} block.`);const a=Vt(r,pe(e.content,t),t,n),s=e.temp_id??e.tempId,c=typeof s=="string"&&s.trim()?s:ke(r);return{block_type:r,content:a,temp_id:c}}function Zn(e,t){const n=[];if("append_block"in e&&n.push(Fe(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(Fe(r,`Nested block to append ${a}`,t))})}return n}function eo(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=Qn(e);if(!n)return null;const o=pe(e,`Nested ${n} block`);return M(n,o,`Nested ${n} block`,t),{block_type:n,content:o,temp_id:ke(n)}}function to(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 no(e,t,n,o){if(!Dt(e))return Ue(t,n);const r={...n},a=Zn(r,o),s=eo(r,o);s&&a.push(s),delete r.append_block,delete r.append_blocks,delete r.append_column_index,delete r.column_index;const c=Ue(t,r);if(a.length>0){const u=Array.isArray(t.column_blocks)?D(t.column_blocks):[],d=to(n,u.length),l=u.length>0?u:[[]];for(;l.length<=d;)l.push([]);l[d]=[...l[d]||[],...a],c.column_blocks=l}return c}function oo(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 K(e){return typeof e=="string"?e.trim().toLowerCase():""}function wt(e){return typeof e=="string"?e.trim().toLowerCase():""}function Gt(e){return e.reduce((t,n)=>t+1+(n.children?.length||0),0)}function _e(e){return typeof e=="string"?e.trim().toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g,""):""}async function W(e,t){const n=t.trim(),o=_e(n),r=bn[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}": ${_(s)}`);const u=(Array.isArray(a)?a:[]).filter(l=>l.is_active!==!1),d=u.find(l=>{const m=_e(l.code),h=_e(l.name);return m===o||m===r||h===o});if(!d?.id||!d?.code){const l=u.map(m=>m.code).filter(Boolean).join(", ");throw new Error(`Language "${t}" was not found.${l?` Available languages: ${l}.`:""}`)}return{code:String(d.code),id:Number(d.id)}}async function Se(e,t){if(t)return W(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: ${_(o)}`);const r=(Array.isArray(n)?n:[]).filter(s=>s.is_active!==!1),a=r.find(s=>s.is_default)||r.find(s=>_e(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 It(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 Ye(r?.code||"USD")}catch{return"USD"}}async function ro(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}: ${_(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 me(e,t){const n=Me.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),c=e.title??(r?void 0:n?.title??void 0),u=await ro({contentType:o,entityId:a,slug:a===void 0&&s||void 0,supabase:z(t),title:a===void 0&&!s&&c||void 0});return{contentType:o,item:u}}async function we(e){const t=await ao({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: ${_(r)}`);return Number(o.id)}function io(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 ao(e){const t=io(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: ${_(o)}`);const r=Array.isArray(n)?n[0]:n;if(!r?.id)return null;let a=Je();if(r.translation_group_id){const{data:s,error:c}=await e.supabase.from("pages").select("id").eq("translation_group_id",r.translation_group_id);if(c)throw new Error(`Failed to inspect linked page translations for navigation item: ${_(c)}`);const u=new Set((Array.isArray(s)?s:[]).map(h=>String(h.id)).filter(Boolean)),{data:d,error:l}=await e.supabase.from("navigation_items").select("id, page_id, translation_group_id, menu_key").eq("menu_key",e.menuKey);if(l)throw new Error(`Failed to inspect related navigation translations: ${_(l)}`);const m=(Array.isArray(d)?d:[]).find(h=>h.translation_group_id&&u.has(String(h.page_id)));m?.translation_group_id&&(a=m.translation_group_id)}return{navigationTranslationGroupId:a,pageId:Number(r.id)}}async function Kt(e){const t=await W(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: ${_(o)}`);const r=Array.isArray(n)?n:[],a=r.filter(d=>d.parent_id==null).length,s=Gt(e.items);Ht({existingItemCount:r.length,existingTopLevelCount:a,languageCode:t.code,menuKey:e.menuKey,replacementItemCount:s});const{error:c}=await e.supabase.from("navigation_items").delete().eq("menu_key",e.menuKey).eq("language_id",t.id);if(c)throw new Error(`Failed to clear ${e.menuKey} navigation items: ${_(c)}`);let u=0;for(const[d,l]of e.items.entries()){const m=await we({item:l,languageId:t.id,menuKey:e.menuKey,order:d,supabase:e.supabase});u++;for(const[h,p]of(l.children??[]).entries())await we({item:p,languageId:t.id,menuKey:e.menuKey,order:h,parentId:m,supabase:e.supabase}),u++}return{insertedCount:u,languageCode:t.code,menuKey:e.menuKey,skippedCount:0,updatedCount:0}}function Ht(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 so(e){const t=await W(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: ${_(o)}`);const r=Array.isArray(n)?n:[];Ht({existingItemCount:r.length,existingTopLevelCount:r.filter(a=>a.parent_id==null).length,languageCode:t.code,menuKey:e.menuKey,replacementItemCount:Gt(e.items)})}async function co(e){if(e.items.length!==1)throw new Error('mode "update" requires exactly one navigation item.');const t=await W(e.supabase,e.languageCode),n=e.items[0],o=K(e.match?.url)||K(n.url),r=wt(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: ${_(s)}`);const u=(Array.isArray(a)?a:[]).find(l=>{const m=K(l.url),h=wt(l.label);return!!(o&&m===o||r&&h===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: ${_(d)}`);return{insertedCount:0,languageCode:t.code,menuKey:e.menuKey,skippedCount:0,updatedCount:1}}async function lo(e){const t=await W(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: ${_(o)}`);let r=0,a=0;const s=Array.isArray(n)?n:[],c=new Set(s.map(l=>K(l.url)).filter(Boolean)),u=s.filter(l=>l.parent_id==null).map(l=>Number(l.order)).filter(Number.isFinite);let d=u.length>0?Math.max(...u)+1:s.length;for(const l of e.items){const m=K(l.url);if(m&&c.has(m)){a++;continue}const h=await we({item:l,languageId:t.id,menuKey:e.menuKey,order:d,supabase:e.supabase});r++,d++,m&&c.add(m);let p=0;for(const g of l.children??[]){const f=K(g.url);if(f&&c.has(f)){a++;continue}await we({item:g,languageId:t.id,menuKey:e.menuKey,order:p,parentId:h,supabase:e.supabase}),r++,p++,f&&c.add(f)}}return{insertedCount:r,languageCode:t.code,menuKey:e.menuKey,skippedCount:a,updatedCount:0}}function S(e){return typeof e=="string"&&e.trim()?e.trim():""}function uo(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function po(e){const t=S(e.field_type??e.fieldType??e.type??e.input_type).toLowerCase().replace(/\s+/g,"_"),n=S(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 mo(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=E(n)?n:{},a=S(r.label??r.name)||(o===0?"Name":o===1?"Email":"Message"),s=po({...r,label:a}),c=r.is_required??r.isRequired??r.required;return{field_type:s,is_required:typeof c=="boolean"?c:!0,label:a,options:Array.isArray(r.options)?r.options:void 0,placeholder:S(r.placeholder)||void 0,temp_id:S(r.temp_id??r.tempId??r.id)||`field-${o+1}`}})}const go=new Set(["none","sm","md","lg","xl"]),Tt=new Set(["none","sm","md","lg","xl"]),fo=new Set(["full-width","container","container-sm","container-lg","container-xl"]),ho=new Set(["start","center","end","stretch"]),yo=new Set(["none","theme","solid","gradient","image"]),_o=new Set(["primary","secondary","muted","accent","destructive"]),bo=new Set(["center","top","bottom","left","right"]);function ko(e){return typeof e=="string"&&/^https?:\/\//i.test(e.trim())}function B(e,t,n){return typeof e=="string"&&t.has(e)?e:n}function wo(e){return Number.isFinite(e)?Math.min(4,Math.max(1,Math.round(e))):1}function Io(e){const t=[{color:"#1e3a8a",position:0},{color:"#3b82f6",position:100}];if(!E(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 To(e){if(!E(e))return{type:"none"};const t=B(e.type,yo,"none"),n=typeof e.min_height=="string"&&e.min_height.trim()?{min_height:e.min_height}:{};if(t==="theme")return{theme:B(e.theme,_o,"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:Io(e.gradient),type:t,...n};if(t==="image"){const o=E(e.image)?e.image:null,r=o&&ko(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:B(o.position,bo,"center"),size:o.size==="contain"?"contain":"cover"},type:t,...n}:{type:"none"}}return{type:"none",...n}}function xo(e,t,n){const o=e.is_hero===!0;let r=Array.isArray(e.column_blocks)?e.column_blocks:[];r.length>0&&r.every(f=>E(f)&&!Array.isArray(f))&&(r=[r]);const a=r.map((f,k)=>(Array.isArray(f)?f:[]).map((w,b)=>Fe(w,`${t} column ${k} block ${b}`,n))),s=a.length>0?a:[[]],c=wo(s.length),u=E(e.responsive_columns)?e.responsive_columns:{},d=Number(u.tablet),l=Number(u.mobile),m=Number.isFinite(d)?Math.min(3,Math.max(1,Math.min(c,d))):Math.min(3,c),h=Number.isFinite(l)?Math.min(2,Math.max(1,l)):1,p=E(e.padding)?e.padding:{},g={...e,background:To(e.background),column_blocks:s,column_gap:B(e.column_gap,go,"lg"),container_type:B(e.container_type,fo,"container"),padding:{bottom:B(p.bottom,Tt,"xl"),top:B(p.top,Tt,"xl")},responsive_columns:{desktop:c,mobile:h,tablet:m},vertical_alignment:B(e.vertical_alignment,ho,o?"center":"start")};return g.slider===!0&&!(Array.isArray(g.slides)&&g.slides.length>0)&&(g.slider=!1),g}function Vt(e,t,n,o){if(e==="section"){const a=xo(t,n,o);return M(e,a,n,o),a}const r=D(t);if(e==="heading"&&(r.text_content=S(r.text_content)||S(r.text)||S(r.title)||S(r.heading)||"Untitled",r.level=typeof r.level=="number"?r.level:1),e==="text"){const a=S(r.html_content)||S(r.html)||S(r.content)||S(r.text);a&&(r.html_content=/<\/?[a-z][\s\S]*>/i.test(a)?a:`<p>${uo(a)}</p>`)}return e==="button"&&(r.text=S(r.text)||S(r.label)||S(r.title)||"Learn More",r.url=S(r.url)||S(r.href)||S(r.link)||"#"),e==="form"&&(r.fields=mo(r.fields),r.submit_button_text=S(r.submit_button_text??r.submitButtonText??r.button_text)||"Send Message",r.success_message=S(r.success_message??r.successMessage)||"Thanks for reaching out. We will reply as soon as possible."),M(e,r,n,o),r}function Ie(e,t,n){const o=Vt(e.blockType,pe(e.content,`Block ${t}`),`Block ${t}`,n);return{block_type:e.blockType,content:o,order:e.order??t}}function zo(e,t="Contact Us",n){return[Ie({blockType:"section",content:{is_hero:!0,background:{type:"none"},column_blocks:[[{block_type:"heading",content:{level:1,textAlign:"center",text_content:t},temp_id:ke("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:ke("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),Ie({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?zo(t,n,o):(e||[]).map((r,a)=>Ie(r,a,o))}async function Xe(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: ${_(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 Qe(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: ${_(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 Ze(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,product_id:e.contentType==="product"?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: ${_(o)}`);return ge(e.blocks,e.supabase),Array.isArray(n)?n:[]}async function et(e){const t=e.contentType==="page"?"pages":e.contentType==="post"?"posts":"products";await e.supabase.from(t).delete().eq("id",e.itemId)}function tt(e,t){return e==="page"?`/cms/pages/${t}/edit`:e==="post"?`/cms/posts/${t}/edit`:`/cms/products/${t}/edit`}function xt(e){return e==="page"?"/cms/pages":e==="post"?"/cms/posts":"/cms/products"}async function nt(e,t){const n=Q.parse(e),o=z(t);n.mode==="replace"&&await so({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 co({items:n.items,languageCode:n.languageCode,match:n.match,menuKey:"HEADER",supabase:o}):n.mode==="append"?await lo({items:n.items,languageCode:n.languageCode,menuKey:"HEADER",supabase:o}):await Kt({items:n.items,languageCode:n.languageCode,menuKey:"HEADER",supabase:o});return Bt(t),{...a,mutationExecuted:!0,mode:n.mode,success:!0}}async function ot(e,t){const n=Z.parse(e);if(!n.links?.length&&!n.copyright)throw new Error("update_footer requires links or copyright.");const o=z(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 Kt({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: ${_(s)}`)}return Bt(t),{copyrightUpdated:!!n.copyright,footerNavigation:a,mutationExecuted:!0,success:!0}}function Wt(e){return typeof e=="string"?e.toLowerCase():""}function Co(e,t){const n=t.map(Wt).join(" ");return e.reduce((o,r)=>o+(n.includes(r)?1:0),0)}function zt(e,t){return(e.find(n=>t.some(o=>Wt(n).includes(o)))||e.find(n=>n.trim().length>0)||"No excerpt available.").slice(0,500)}async function Jt(e,t){const n=xe.parse(e),o=z(t),r=n.query.toLowerCase().split(/\s+/).map(l=>l.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: ${_(a.error)}`);if(s.error)throw new Error(`Failed to search documentation pages: ${_(s.error)}`);const c=(a.data??[]).map(l=>({excerpt:zt([l.excerpt,l.subtitle,l.meta_description,l.slug].filter(Boolean),r),source:"post",title:l.title,url:`/article/${l.slug}`})),u=(s.data??[]).map(l=>({excerpt:zt([l.meta_description,l.slug].filter(Boolean),r),source:"page",title:l.title,url:l.slug==="home"?"/":`/${l.slug}`})),d=[...c,...u].map(l=>({...l,score:Co(r,[l.title,l.excerpt,l.url])})).filter(l=>l.score>0).sort((l,m)=>m.score-l.score).slice(0,n.limit).map(l=>({excerpt:l.excerpt,source:l.source,title:l.title,url:l.url}));return{query:n.query,results:d,success:!0}}async function Yt(e,t,n=_n){const o=xe.safeParse(e),r=o.success?o.data.query:"";return Ln(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 So=["pending","trial","paid","shipped","cancelled","refunded","failed"],vo={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 Eo(e){return String(e??"unknown").trim().toLowerCase()||"unknown"}function Ct(e){const t=Object.fromEntries(So.map(n=>[n,0]));for(const n of e){const o=Eo(n.status);t[o]=(t[o]??0)+1}return t}function $o(e){const n=e.toLowerCase().replace(/[^a-z0-9_]+/g," ").split(/\s+/).filter(Boolean);for(const o of n){const r=vo[o];if(r)return r}return null}function X(e){const t=Number(e);return Number.isFinite(t)?t:0}async function Xt(e,t){const n=Re.parse(e),o=z(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 c=n.currency?.toUpperCase(),u=$o(n.query),d=o.from("orders").select("id, status, total, currency, created_at, paid_at");c&&d.eq("currency",c),a&&d.gte("created_at",a.toISOString()),s&&d.lte("created_at",s.toISOString());const m=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;m&&(c&&m.eq("orders.currency",c),a&&m.gte("orders.paid_at",a.toISOString()),s&&m.lte("orders.paid_at",s.toISOString()));const p=n.timeRange!=="all_time"&&(n.reportType==="orders"||u)?o.from("orders").select("id, status, currency"):null;p&&c&&p.eq("currency",c);const[{data:g,error:f},{data:k,error:y},w]=await Promise.all([d,m??Promise.resolve({data:[],error:null}),p??Promise.resolve({data:null,error:null})]);if(f)throw new Error(`Failed to fetch ecommerce stats: ${_(f)}`);if(y)throw new Error(`Failed to fetch ecommerce stats: ${_(y)}`);if(w.error)throw new Error(`Failed to fetch ecommerce stats: ${_(w.error)}`);const b=Array.isArray(g)?g:[],I=Array.isArray(k)?k:[],x=zt(b),v=Array.isArray(w.data)?w.data:null,j=v?zt(v):null,q={};for(const T of I){const $=Array.isArray(T.orders)?T.orders[0]:T.orders,O=String($?.currency||c||"unknown").toUpperCase();q[O]=(q[O]??0)+X(T.quantity)*X(T.price_at_purchase)/100}const J={currency:c??null,currencyFiltered:!!c,orderStatusCounts:x,paidOrderCount:x.paid??0,query:n.query,reportType:n.reportType,revenueByCurrency:q,timeRange:n.timeRange,totalOrders:b.length,totalRevenue:Object.values(q).reduce((T,$)=>T+$,0)};if(j&&(J.allTimeOrderStatusCounts=j),u&&(J.matchingOrderStatus={allTimeCount:j?.[u]??x[u]??0,count:x[u]??0,status:u,timeRange:n.timeRange}),n.reportType==="products"||n.reportType==="revenue"||n.reportType==="general"){const T={};for(const $ of I){const O=Array.isArray($.products)?$.products[0]:$.products;if(!O?.id)continue;const Y=O.id;T[Y]||(T[Y]={id:Y,quantity:0,revenue:0,title:O.title,type:O.product_type}),T[Y].quantity+=X($.quantity),T[Y].revenue+=X($.quantity)*X($.price_at_purchase)/100}J.topProducts=Object.values(T).sort(($,O)=>O.revenue-$.revenue).slice(0,10)}return{report:J,success:!0}}async function Qt(e,t){const n=De.parse(e),o=C(t),r=V(t),a=Ce(r),s=r.contentType==="page"?"pages":r.contentType==="post"?"posts":"products",{data:c,error:u}=await o.from(s).select("*").eq("id",a).single();if(u||!c)throw new Error(`Failed to read current ${r.contentType}: ${_(u)}`);let d=[];if(n.includeBlocks){const l=r.contentType==="page"?"page_id":r.contentType==="post"?"post_id":"product_id",{data:m,error:h}=await o.from("blocks").select("id, page_id, post_id, product_id, language_id, block_type, content, order").eq(l,a);if(h)throw new Error(`Failed to read current ${r.contentType} blocks: ${_(h)}`);d=(Array.isArray(m)?m:[]).slice().sort((p,g)=>Number(p.order)-Number(g.order)).map(p=>oo(p,n.includeBlockContent))}return{blocks:d,context:r,item:c,success:!0}}const Zt=new Set(["feature_image_id","language_id","meta_description","meta_title","slug","status","title"]),en=new Set(["excerpt","feature_image_id","label","language_id","meta_description","meta_title","published_at","slug","status","subtitle","title"]),Ao=new Set(["description_json","language_id","meta_description","meta_title","short_description","slug","status","title"]),Po=new Set(["excerpt","feature_image_id","label","meta_description","meta_title","published_at","short_description","subtitle"]);function No(e){return e==="page"?Zt:e==="post"?en:Ao}function tn(e,t){return Po.has(e)&&t===""?null:t}function Oe(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 Uo(e,t){const n=No(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"&&Oe(t.contentType,a),o[r]=tn(r,a)}return o}async function rt(e,t){const n=ee.parse(e),o=C(t),r=V(t),a=Ce(r),s=Uo(n.fields,r),c=Object.keys(s);if(c.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:c,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 de(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:l,error:m}=await o.from(d).update({...s,updated_at:new Date().toISOString()}).eq("id",a).select("id, language_id, slug, status, title").single();if(m||!l)throw new Error(`Failed to update current ${r.contentType}: ${_(m)}`);return N(t,r,l.slug),{contentType:r.contentType,entityId:a,mutationExecuted:!0,slug:l.slug,success:!0,updatedFields:c}}async function it(e,t){const n=te.parse(e),o=C(t),r=V(t),{data:a,error:s}=await o.from("blocks").select("id, page_id, post_id, product_id, language_id, block_type, content, order").eq("id",n.blockId).single();if(s||!a)throw new Error(`Failed to read block ${n.blockId}: ${_(s)}`);Rt(a,r);const c=be(a.block_type,`Block ${n.blockId}`);Mt(n.blockType,c,`Block ${n.blockId}`);const u=pe(a.content,`Block ${n.blockId}`),d=no(c,u,n.content,t);M(c,d,`Block ${n.blockId}`,t);const l=A({action:"UPDATE CONTENT BLOCK",context:t,payload:{blockId:n.blockId,blockType:c,content:d,tool:"update_content_block"},preview:{blockId:n.blockId,blockType:c,contentType:r.contentType,entityId:Ce(r)},subject:`${c} block ${n.blockId}`});if(l)return l;const{data:m,error:h}=await o.from("blocks").update({content:d,updated_at:new Date().toISOString()}).eq("id",n.blockId).select("id, block_type, order").single();if(h||!m)throw new Error(`Failed to update block ${n.blockId}: ${_(h)}`);return await ze({patch:({blocks:p})=>({blocks:p.map(g=>String(g?.id)===String(n.blockId)?{...g,content:d}:g)}),productId:a.product_id,supabase:o}),ge([{content:d}],o),N(t,r),{blockId:m.id,blockType:m.block_type,contentUpdated:!0,mutationExecuted:!0,success:!0}}async function at(e,t){const n=ie.parse(e),o=C(t),r=await me(n,t),a=r.contentType==="product"?r.item.id:Number(r.item.id),s=r.contentType==="page"?"page_id":r.contentType==="post"?"post_id":"product_id",c=async()=>{const{data:b,error:I}=await o.from("blocks").select("id, page_id, post_id, product_id, language_id, block_type, content, order").eq(s,a);if(I)throw new Error(`Failed to read ${r.contentType} blocks: ${_(I)}`);return(Array.isArray(b)?b:[]).sort((x,v)=>Number(x.order)-Number(v.order))},u=b=>{if(n.position==="start")return 0;if(n.position==="end"){const v=b.map(j=>Number(j.order)).filter(Number.isFinite);return v.length>0?Math.max(...v)+1:0}const I=n.anchorBlockId?b.find(v=>Number(v.id)===n.anchorBlockId):n.anchorBlockType?b.find(v=>v.block_type===n.anchorBlockType):null;if(!I)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 x=Number(I.order);return n.position==="before"?x:x+1},d=Ie(n.block,0,t),l=await c(),m=u(l),h={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},p=A({action:"INSERT CONTENT BLOCK",context:t,payload:{block:d,order:m,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(p)return p;const g=await c(),f=u(g),k=g.filter(b=>Number(b.order)>=f).sort((b,I)=>Number(I.order)-Number(b.order));for(const b of k){const{error:I}=await o.from("blocks").update({order:Number(b.order)+1,updated_at:new Date().toISOString()}).eq("id",b.id);if(I)throw new Error(`Failed to shift block ${b.id}: ${_(I)}`)}const{data:y,error:w}=await o.from("blocks").insert({block_type:d.block_type,content:d.content,language_id:r.item.language_id,order:f,page_id:r.contentType==="page"?a:null,post_id:r.contentType==="post"?a:null,product_id:r.contentType==="product"?a:null}).select("id, block_type, order").single();if(w||!y)throw new Error(`Failed to insert content block: ${_(w)}`);return r.contentType==="product"&&await ze({patch:({blocks:b})=>({blocks:[...b.map(I=>Number(I?.order)>=f?{...I,order:Number(I.order)+1}:I),{block_type:d.block_type,content:d.content,id:y.id,language_id:r.item.language_id,order:f,page_id:null,post_id:null,product_id:a}].sort((I,x)=>Number(I.order)-Number(x.order))}),productId:a,supabase:o}),ge([d],o),N(t,h),{blockId:y.id,blockType:y.block_type,contentType:r.contentType,entityId:r.item.id,mutationExecuted:!0,order:y.order,success:!0}}async function st(e,t){const n=ne.parse(e),o=C(t),r=V(t),{data:a,error:s}=await o.from("blocks").select("id, page_id, post_id, product_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}: ${_(s)}`);Rt(a,r);const c=be(a.block_type,`Parent block ${n.parentBlockId}`);if(c!=="section")throw new Error(`Parent block ${n.parentBlockId} must be a section block, not "${c}".`);const u=pe(a.content,`Parent block ${n.parentBlockId}`);M(c,u,`Parent block ${n.parentBlockId}`,t);const l=u.column_blocks?.[n.columnIndex]?.[n.blockIndex];if(!l)throw new Error(`Nested block was not found at column ${n.columnIndex}, index ${n.blockIndex}.`);const m=be(l.block_type,`Nested block ${n.columnIndex}:${n.blockIndex}`);Mt(n.blockType,m,`Nested block ${n.columnIndex}:${n.blockIndex}`),M(m,n.content,`Nested block ${n.columnIndex}:${n.blockIndex}`,t);const h=u.column_blocks.map((y,w)=>w===n.columnIndex?y.map((b,I)=>I===n.blockIndex?{...b,content:n.content}:b):y),p={...u,column_blocks:h};M(c,p,`Updated parent block ${n.parentBlockId}`,t);const g=A({action:"UPDATE NESTED BLOCK",context:t,payload:{blockIndex:n.blockIndex,columnIndex:n.columnIndex,content:n.content,nestedBlockType:m,parentBlockId:n.parentBlockId,tool:"update_section_column_block"},preview:{blockIndex:n.blockIndex,columnIndex:n.columnIndex,nestedBlockType:m,parentBlockId:n.parentBlockId,parentBlockType:c},subject:`${m} nested block ${n.columnIndex}:${n.blockIndex}`});if(g)return g;const{data:f,error:k}=await o.from("blocks").update({content:p,updated_at:new Date().toISOString()}).eq("id",n.parentBlockId).select("id, block_type").single();if(k||!f)throw new Error(`Failed to update parent block ${n.parentBlockId}: ${_(k)}`);return await ze({patch:({blocks:y})=>({blocks:y.map(w=>String(w?.id)===String(n.parentBlockId)?{...w,content:p}:w)}),productId:a.product_id,supabase:o}),N(t,r),{blockIndex:n.blockIndex,columnIndex:n.columnIndex,mutationExecuted:!0,nestedBlockType:m,parentBlockId:f.id,parentBlockType:f.block_type,success:!0}}async function Ee(e,t){const n=ae.parse(e),o=C(t),r=We(t),a=await Se(o,n.languageCode),s=L(n.slug||n.title),c=ve(n.blocks,n.contactEmail,n.title,t),u=await Xe({contentType:"page",languageId:a.id,slug:s,supabase:o});if(u)return u;const d=await Qe({contentType:"page",languageCode:a.code,languageId:a.id,suppliedTranslationGroupId:n.translationGroupId,supabase:o});if(d.result)return d.result;const l={blocks:c,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"},m=A({action:"CREATE PAGE",context:t,payload:l,preview:{blockCount:c.length,languageCode:a.code,slug:s,status:n.status,title:n.title,translationGroupId:d.translationGroupId},subject:s});if(m)return m;const h=d.translationGroupId||Je(),p=await de(l.item.feature_image_id,t,n.title),{data:g,error:f}=await o.from("pages").insert({...l.item,author_id:r,feature_image_id:p,translation_group_id:h}).select("id, language_id, slug, status, title, translation_group_id").single();if(f||!g?.id)throw new Error(`Failed to create page: ${_(f)}`);try{await Ze({blocks:c,contentType:"page",itemId:Number(g.id),languageId:a.id,supabase:o})}catch(k){throw await et({contentType:"page",itemId:Number(g.id),supabase:o}),k}return N(t,{contentType:"page",entityId:Number(g.id),languageId:a.id,slug:s,title:n.title},s),t?.revalidatePath?.("/cms/pages"),{blockCount:c.length,contentType:"page",editPath:tt("page",g.id),entityId:g.id,mutationExecuted:!0,slug:s,success:!0,title:n.title,translationGroupId:g.translation_group_id}}async function $e(e,t){const n=se.parse(e),o=C(t),r=We(t),a=await Se(o,n.languageCode),s=L(n.slug||n.title),c=ve(n.blocks,void 0,void 0,t),u=await Xe({contentType:"post",languageId:a.id,slug:s,supabase:o});if(u)return u;const d=await Qe({contentType:"post",languageCode:a.code,languageId:a.id,suppliedTranslationGroupId:n.translationGroupId,supabase:o});if(d.result)return d.result;const l=n.published_at&&!Number.isNaN(new Date(n.published_at).getTime())?new Date(n.published_at).toISOString():n.published_at??null,m={blocks:c,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:l,slug:s,status:n.status,subtitle:n.subtitle??null,title:n.title,translation_group_id:d.translationGroupId},tool:"create_cms_post"},h=A({action:"CREATE POST",context:t,payload:m,preview:{blockCount:c.length,languageCode:a.code,slug:s,status:n.status,title:n.title,translationGroupId:d.translationGroupId},subject:s});if(h)return h;const p=d.translationGroupId||Je(),g=await de(m.item.feature_image_id,t,n.title),{data:f,error:k}=await o.from("posts").insert({...m.item,author_id:r,feature_image_id:g,translation_group_id:p}).select("id, language_id, slug, status, title, translation_group_id").single();if(k||!f?.id)throw new Error(`Failed to create post: ${_(k)}`);try{await Ze({blocks:c,contentType:"post",itemId:Number(f.id),languageId:a.id,supabase:o})}catch(y){throw await et({contentType:"post",itemId:Number(f.id),supabase:o}),y}return N(t,{contentType:"post",entityId:Number(f.id),languageId:a.id,slug:s,title:n.title},s),t?.revalidatePath?.("/cms/posts"),t?.revalidatePath?.("/articles"),{blockCount:c.length,contentType:"post",editPath:tt("post",f.id),entityId:f.id,mutationExecuted:!0,slug:s,success:!0,title:n.title,translationGroupId:f.translation_group_id}}function Fo(e,t){return(t||L(e)||"product").replace(/-/g,"").slice(0,24).toUpperCase()}function nn(e){if(e==null)return;if(typeof e=="string")return Pt.editorDocumentFromHtml(e)??void 0;const t=Array.isArray(e)?{content:e,type:"doc"}:E(e)&&e.type!=="doc"&&Array.isArray(e.content)?{...e,type:"doc"}:e,n=kt().safeParse(t);if(!n.success){if(E(e)&&typeof e.type=="string"){const o=kt().safeParse({content:[e],type:"doc"});if(o.success)return o.data}throw new Error(`Product description_json must be an editor document like { "type": "doc", "content": [ { "type": "paragraph", "content": [ { "type": "text", "text": "..." } ] } ] }, or simply an HTML string. Received: ${n.error.issues.map(o=>o.message).join("; ")}`)}return n.data}function Oo(e){const t=r=>!!(r&&Array.isArray(r.content)&&r.content.length>0),n=nn(e.description_json);if(t(n))return n;const o=e.description_html?Pt.editorDocumentFromHtml(e.description_html):null;return t(o)?o:void 0}async function ct(e,t){const n=ce.parse(e),o=C(t),r=await Se(o,n.languageCode),a=L(n.slug||n.title),s=ve(n.blocks,void 0,void 0,t),c=await Xe({contentType:"product",languageId:r.id,slug:a,supabase:o});if(c)return c;const u=await Qe({contentType:"product",languageCode:r.code,languageId:r.id,suppliedTranslationGroupId:n.translationGroupId,supabase:o});if(u.result)return u.result;const{createProduct:d,productSchema:l}=await Kn(),h=n.product_type==="digital"&&n.payment_provider==="freemius"?n.trial_period_days:0,p=l.parse({description_json:Oo(n),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||Fo(n.title,a),slug:a,status:n.status,stock:n.stock,title:n.title,trial_period_days:h,trial_requires_payment_method:h>0?n.trial_requires_payment_method:!1,translation_group_id:u.translationGroupId,upc:n.upc??"",variation_attributes:[],variants:[]}),g=n.images??[],f=A({action:"CREATE PRODUCT",context:t,payload:{blocks:s,images:g,item:p,tool:"create_cms_product"},preview:{blockCount:s.length,descriptionLength:p.description_json?JSON.stringify(p.description_json).length:0,imageCount:g.length,languageCode:r.code,price:p.price,sku:p.sku,slug:a,status:p.status,stock:p.stock,title:p.title,translationGroupId:u.translationGroupId},subject:a});if(f)return f;let k=[],y=null;if(g.length>0)try{if(k=[...new Set(await Ot(g,t,n.title))],k.length===0)throw new Error("None of the provided images could be resolved to a media item.")}catch(b){y=b instanceof Error?b.message:String(b)}const w=await d(o,{...p,product_media:k.map(b=>({media_id:b}))});if(!w?.id)throw new Error("Failed to create product.");try{await Ze({blocks:s,contentType:"product",itemId:w.id,languageId:r.id,supabase:o})}catch(b){throw await et({contentType:"product",itemId:w.id,supabase:o}),b}return N(t,{contentType:"product",entityId:w.id,languageId:r.id,slug:a,title:n.title},a),t?.revalidatePath?.("/cms/products"),{blockCount:s.length,contentType:"product",editPath:tt("product",w.id),entityId:w.id,imageCount:k.length,...y?{imageError:y}:{},mutationExecuted:!0,slug:a,success:!0,title:n.title,translationGroupId:w.translation_group_id}}function lt(e){return e.trim().replace(/[\s-]+/g,"_").toLowerCase()}function jo(e,t){const n=typeof t=="string"?lt(t):t;return e==="product"?n==="public"||n==="publish"||n==="published"?"active":n:n==="public"||n==="active"||n==="publish"?"published":n}function Bo(e){const t=lt(e.field);return!!(e.startsAt||e.endsAt||t.includes("start")||t.includes("end")||t.includes("schedule")||t.includes("special_date"))}async function Lo(e,t,n){if(e==="price"||e==="sale_price"){if(t==null)return{[e]:null};const o=await It(n);return{[e]:qt(Number(t),o)}}if(e==="prices"||e==="sale_prices"){const o=await It(n);return{[e]:Xn(t,o)}}return e==="description_json"?{description_json:nn(t)}:{[e]:t}}function qo(e,t){const n=lt(e.field),o=n==="status"?jo(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"?Zt:en).has(a))throw new Error(`Field "${e.field}" cannot be updated for ${t.contentType}.`);return a==="status"&&Oe(t.contentType,o),{field:a,payload:{[a]:tn(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"&&Oe("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 ut(e,t){const n=le.parse(e);if(Bo(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 me(n,t),r=qo(n,o),a=r.field;let s=r.payload;if(a==="language_id"&&typeof s.language_id=="string"){const m=await W(C(t),s.language_id);s={...s,language_id:m.id}}const c=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(c)return c;if(o.contentType==="product"){const m=C(t),h=await Lo(a,s[a],m),{data:p,error:g}=await m.from("products").update({...h,updated_at:new Date().toISOString()}).eq("id",o.item.id).select("id, language_id, slug, status, title").single();if(g||!p)throw new Error(`Failed to update product: ${_(g)}`);return N(t,{contentType:"product",entityId:String(p.id),languageId:p.language_id,slug:p.slug,title:p.title},p.slug),{contentType:"product",entityId:p.id,field:a,mutationExecuted:!0,slug:p.slug,success:!0,updatedFields:[a]}}a==="feature_image_id"&&typeof s.feature_image_id=="string"&&(s={...s,feature_image_id:await de(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:l}=await C(t).from(u).update({...s,updated_at:new Date().toISOString()}).eq("id",o.item.id).select("id, language_id, slug, status, title").single();if(l||!d)throw new Error(`Failed to update ${o.contentType}: ${_(l)}`);return N(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 on(e,t){const n=Ge.parse(e),o=await me(n,t);if(o.contentType==="product")return{affectedCount:1,collectionPath:xt("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 C(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: ${_(s)}`);const c=Array.isArray(a)?a:[],u=c.map(p=>o.contentType==="page"?p.slug==="home"?"/":`/${p.slug}`:`/article/${p.slug}`).filter(Boolean),d=new Set(u),{data:l,error:m}=await C(t).from("navigation_items").select("id, url");if(m)throw new Error(`Failed to inspect related navigation links: ${_(m)}`);const h=(Array.isArray(l)?l:[]).filter(p=>d.has(p.url)).length;return{affectedCount:c.length,collectionPath:xt(o.contentType),contentType:o.contentType,item:o.item,navigationLinkCount:h,publicPaths:u,targetIds:c.map(p=>p.id)}}function rn(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=[`${P(e.affectedCount,"language version")}`,e.navigationLinkCount>0?`${P(e.navigationLinkCount,"navigation link")}`:null].filter(Boolean);return`Delete ${e.contentType} "${t}"${n}, including ${o.join(" and ")}.`}async function an(e,t){const n=await on(e,t);return{...Lt({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:rn(n),title:n.item.title},subject:`${n.item.id} ${n.item.slug||""}`}),preparedDelete:!0}}async function dt(e,t){const n=ue.parse(e),o=await on(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:rn(o),title:o.item.title},subject:`${o.item.id} ${o.item.slug||""}`});if(r)return r;const a=C(t);if(o.contentType==="product"){const{error:c}=await a.from("products").delete().eq("id",o.item.id);if(c)throw new Error(`Failed to delete product: ${_(c)}`)}else{for(const d of o.publicPaths)await a.from("navigation_items").delete().eq("url",d);const c=o.contentType==="page"?"pages":"posts",{error:u}=await a.from(c).delete().eq("translation_group_id",o.item.translation_group_id);if(u)throw new Error(`Failed to delete ${o.contentType}: ${_(u)}`)}const s=t?.revalidatePath??He();return s&&(s(o.collectionPath),s("/cms/navigation"),o.publicPaths.forEach(c=>s(c))),{affectedCount:o.affectedCount,collectionPath:o.collectionPath,contentType:o.contentType,mutationExecuted:!0,redirectPath:o.collectionPath,success:!0}}async function St(e,t){switch(e.tool){case"create_cms_page":return Ee(e.input,t);case"create_cms_post":return $e(e.input,t);case"create_cms_product":return ct(e.input,t);case"delete_cms_item":return dt(e.input,t);case"update_cms_item_field":return ut(e.input,t);case"update_content_block":return it(e.input,t);case"insert_content_block":return at(e.input,t);case"update_current_cms_fields":return rt(e.input,t);case"update_footer":return ot(e.input,t);case"update_navigation_bar":return nt(e.input,t);case"update_section_column_block":return st(e.input,t);case"set_content_images":return ht(e.input,t)}}function Ro(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}function vt(e){return e==="create_cms_page"?"page":e==="create_cms_post"?"post":"product"}function Mo(e,t,n){if(e.tool!=="set_content_images")return e;const o=e.input;if(o.entityId!==void 0)return e;const r=o.slug?t.get(`${o.contentType||"product"}:${L(o.slug)}`):n;return r?{...e,input:{...o,contentType:r.contentType,entityId:r.entityId}}:e}async function sn(e,t){const n=Ke.parse(e),o=new Set(n.actions.filter(p=>p.tool==="create_cms_page"||p.tool==="create_cms_post"||p.tool==="create_cms_product").map(p=>{const g=p.input;return`${vt(p.tool)}:${L(g.slug||g.title||"")}`})),r=p=>{if(p.tool!=="set_content_images")return!1;const g=p.input;return g.slug?o.has(`${g.contentType||"product"}:${L(g.slug)}`):o.size>0};if(!t?.skipConfirmation){const p=[];for(const k of n.actions){if(r(k)){const w=k.input;p.push(`Set ${P(w.images.length,"image")} on the ${w.slug?`"${w.slug}"`:"new"} item created in this plan.`);continue}const y=await St(k,{...t,latestUserMessage:null});if(!y||typeof y!="object")return{message:`Could not prepare action ${p.length+1}.`,mutationExecuted:!1,success:!1};if(y.success===!1||y.unsupported===!0)return y;y.requiresConfirmation===!0&&y.preview?p.push(Wn(k.tool,y.preview)):p.push(`Run ${k.tool.replace(/_/g," ")}.`)}const g=n.summary||`Complete ${P(n.actions.length,"CMS action")}.`,f=A({action:"EXECUTE CMS ACTION PLAN",context:t,payload:{actions:n.actions,tool:"execute_cms_action_plan"},preview:{actionCount:n.actions.length,actionSummaries:p,summary:g},subject:`${n.actions.length} actions`});if(f)return f}const a={...t,skipConfirmation:!0},s=[];let c=!1,u=null,d=null;const l={},m=new Map;let h=null;for(const[p,g]of n.actions.entries()){const f=Mo(Ro(g,l),m,h),k=await St(f,a);if(s.push({output:k,tool:f.tool}),k&&typeof k=="object"){const y=k;if(y.mutationExecuted===!0&&(c=!0),!u&&typeof y.editPath=="string"&&(u=y.editPath),typeof y.redirectPath=="string"&&(d=y.redirectPath),(f.tool==="create_cms_page"||f.tool==="create_cms_post"||f.tool==="create_cms_product")&&(typeof y.translationGroupId=="string"&&(l[f.tool]=y.translationGroupId),y.entityId!==void 0&&y.entityId!==null)){const w=vt(f.tool),b={contentType:w,entityId:y.entityId};h=b,typeof y.slug=="string"&&m.set(`${w}:${y.slug}`,b)}if(y.success===!1||y.unsupported===!0)return{actionCount:n.actions.length,failedActionIndex:p,failedTool:f.tool,message:typeof y.message=="string"?y.message:`Action ${p+1} failed.`,mutationExecuted:c,results:s,success:!1,...u?{editPath:u}:{},...d?{redirectPath:d}:{}}}}return{actionCount:n.actions.length,editPath:d?void 0:u??void 0,mutationExecuted:c,redirectPath:d??void 0,results:s,success:!0,summary:n.summary??null}}const pt=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://.")}),Do=12e3,Et=2e6;function $t(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 he(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 Go(e){return e.trim().replace(/&amp;/gi,"&").replace(/&#38;/g,"&").replace(/&quot;/gi,'"').replace(/&#39;/g,"'")}const cn=/\.(avif|gif|jpe?g|png|webp)(?:[?#]|$)/i,ln=/(?:^|[/_-])(?:sprite|icon|favicon|logo|placeholder|pixel|spacer|blank|avatar|badge|flag|loader|spinner|1x1|transparent|watermark|payment|visa|mastercard|paypal|amex|social|share|facebook|twitter|instagram|youtube|pinterest|linkedin)(?:[/_.-]|$)/i;function Te(e,t){if(typeof e!="string")return null;const n=Go(e);if(!n||n.startsWith("data:"))return null;try{const o=new URL(n,t);return o.protocol!=="http:"&&o.protocol!=="https:"?null:o.toString()}catch{return null}}function Ko(e){let t=null;for(const n of e.split(",")){const o=n.trim().split(/\s+/),r=o[0];if(!r)continue;const a=o[1]||"",s=a.match(/^(\d+(?:\.\d+)?)w$/i),c=a.match(/^(\d+(?:\.\d+)?)x$/i),u=s?Number(s[1]):c?Number(c[1])*1e3:1;(!t||u>t.weight)&&(t={url:r,weight:u})}return t?.url??null}function F(e,t){const n=e.match(new RegExp(`\\b${t}\\s*=\\s*(?:"([^"]*)"|'([^']*)'|([^\\s>]+))`,"i"));return n?n[1]??n[2]??n[3]??null:null}function Ho(e,t){const n=[],o=[],r=(c,u)=>{if(typeof c=="string"){const d=Te(c,t);d&&u.push(d);return}if(Array.isArray(c)){for(const d of c)r(d,u);return}c&&typeof c=="object"&&(r(c.url,u),r(c.contentUrl,u))},a=(c,u)=>{if(u>8||!c||typeof c!="object")return;if(Array.isArray(c)){for(const p of c)a(p,u+1);return}const d=c,l=d["@type"],h=(Array.isArray(l)?l:[l]).filter(p=>typeof p=="string").map(p=>p.toLowerCase()).some(p=>p==="product"||p==="productgroup"||p==="itempage");"image"in d&&r(d.image,h?n:o);for(const p of Object.values(d))a(p,u+1)},s=e.matchAll(/<script\b[^>]*type\s*=\s*["']application\/ld\+json["'][^>]*>([\s\S]*?)<\/script>/gi);for(const c of s){const u=(c[1]||"").trim();if(u)try{a(JSON.parse(u),0)}catch{}}return[...n,...o]}const un=/(?:^|[/_-])(?:thumbnails?|thumbs?|small|mini)(?:[/_.-]|$)/i;function dn(e){try{const{pathname:t}=new URL(e);return decodeURIComponent(t.slice(t.lastIndexOf("/")+1)).toLowerCase()||null}catch{return null}}function Vo(e,t){const n=new Map;for(const o of e.matchAll(/<a\b[^>]*>/gi)){const r=Te(F(o[0],"href"),t);if(!r||!cn.test(r)||un.test(r)||ln.test(r))continue;const a=dn(r);a&&!n.has(a)&&n.set(a,r)}return n}function Wo(e,t){const n=[...Ho(e,t)],o=[/<meta\b[^>]*\b(?:property|name)\s*=\s*["'](?:og:image:secure_url|og:image:url|og:image)["'][^>]*>/gi,/<meta\b[^>]*\b(?:property|name)\s*=\s*["'](?:twitter:image:src|twitter:image)["'][^>]*>/gi,/<meta\b[^>]*\bitemprop\s*=\s*["']image["'][^>]*>/gi,/<link\b[^>]*\brel\s*=\s*["']image_src["'][^>]*>/gi];for(const l of o)for(const m of e.matchAll(l)){const h=m[0],p=Te(F(h,"content")||F(h,"href"),t);p&&n.push(p)}const r=[];for(const l of e.matchAll(/<img\b[^>]*>/gi)){const m=l[0],h=F(m,"srcset")||F(m,"data-srcset"),p=[h?Ko(h):null,F(m,"src"),F(m,"data-src"),F(m,"data-original"),F(m,"data-lazy-src"),F(m,"data-image")];let g=null;for(const k of p)if(g=Te(k,t),g)break;if(!g||ln.test(g))continue;const f=Number(F(m,"width"));Number.isFinite(f)&&f>0&&f<200||r.push(g)}const a=l=>cn.test(l);n.push(...r.filter(a),...r.filter(l=>!a(l)));const s=Vo(e,t),c=l=>{if(!un.test(l))return l;const m=dn(l);return m&&s.get(m)||l},u=new Set,d=[];for(const l of n){const m=c(l);if(!u.has(m)&&(u.add(m),d.push(m),d.length>=12))break}return{images:d,mainImage:d[0]??null}}function Jo(e,t,n){const o=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," "),{images:r,mainImage:a}=Wo(e,n),s=e.match(/<title\b[^>]*>([\s\S]*?)<\/title>/i),c=e.match(/<meta[^>]+name=["']description["'][^>]*content=["']([^"']*)["'][^>]*>/i)||e.match(/<meta[^>]+content=["']([^"']*)["'][^>]*name=["']description["'][^>]*>/i),u=[...o.matchAll(/<h([1-3])\b[^>]*>([\s\S]*?)<\/h\1>/gi)].map(m=>he(m[2])).filter(Boolean).slice(0,40),d=o.match(/<body\b[^>]*>([\s\S]*?)<\/body>/i),l=he(d?.[1]??o);return{description:c?he(c[1]):"",headings:u,images:r,mainImage:a,text:l.slice(0,t),title:s?he(s[1]):"",truncated:l.length>t}}async function pn(e){const t=pt.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($t(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(),Do);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($t(new URL(s).hostname))return{message:"The URL redirected to a blocked internal address.",success:!1,url:t.url}}catch{}const c=a.headers.get("content-type")||"";if(!/text\/html|text\/plain|application\/xhtml/i.test(c))return{contentType:c,message:`The URL is not an HTML or text page (content-type: ${c||"unknown"}).`,success:!1,url:t.url};const u=await a.text(),d=u.length>Et?u.slice(0,Et):u,l=Jo(d,t.maxChars,s);return!l.text&&!l.title?{message:"The URL returned no readable text content.",success:!1,url:t.url}:{description:l.description,finalUrl:s,headings:l.headings,images:l.images,mainImage:l.mainImage,success:!0,text:l.text,title:l.title,truncated:l.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: ${_(a)}`,success:!1,url:t.url}}finally{clearTimeout(r)}}const mt=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".')}),Yo=12e3;async function Ae(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")),c=l=>{if(!l)return null;try{const m=s(l);return typeof m=="string"&&m.trim()?m.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=c(d.find(l=>l.key===r)?.value),n=c(d.find(l=>l.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 Xo(e){return(await Ae(e))[0]??null}async function Qo(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 At(e,t){const n=new AbortController,o=setTimeout(()=>n.abort(),Yo);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 ye(e){const t=Number(e);return Number.isFinite(t)&&t>0?t:null}function je(e,t){if(!E(e))return;const n=o=>{E(o)&&o.provider==="unsplash"&&typeof o.downloadLocation=="string"&&o.downloadLocation.trim()&&t.add(o.downloadLocation.trim())};if(n(e.attribution),E(e.background)&&E(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)E(r)&&je(r.content,t)}if(Array.isArray(e.slides))for(const o of e.slides)je(o,t)}async function ge(e,t){try{const n=new Set;for(const a of e)je(a?.content,n);if(n.size===0)return;const r=(await Ae(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 Zo(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 At(`https://api.pexels.com/v1/search?${o.toString()}`,{Authorization:e.apiKey});return(Array.isArray(a?.photos)?a.photos:[]).map(s=>{const c=typeof s?.photographer=="string"?s.photographer:null;return{alt:typeof s?.alt=="string"&&s.alt.trim()?s.alt.trim():t.query,credit:c?`Photo by ${c} on Pexels`:"Photo on Pexels",downloadLocation:null,height:ye(s?.height),photographer:c,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:ye(s?.width)}}).filter(s=>typeof s.url=="string")}const r=await At(`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:ye(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:ye(a?.width)}}).filter(a=>typeof a.url=="string")}async function mn(e,t){const n=mt.parse(e),o=await Ae(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(c=>c.provider==="unsplash")?await Qo(t?.supabase):null,a=[];let s=null;for(const c of o){a.push(c.provider);try{const u=await Zo(c,n,r);if(u.length>0)return{attemptedProviders:a,photos:u,provider:c.provider,query:n.query,success:!0,usageGuidance:c.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(", ")}: ${_(s)}`:`No matching stock photos found for "${n.query}".`,photos:[],success:!1}}const gt=H.extend({blocks:i.z.array(oe).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()}),er=["custom_canonical","excerpt","feature_image_id","label","language_id","meta_description","meta_title","published_at","slug","status","subtitle","title","translation_group_id"];function tr(e){const t={};for(const n of er)n in e&&e[n]!==void 0&&(t[n]=e[n]);return t}function nr(e,t){if(!t)return null;const n=e==="page"?t==="home"?"/":`/${t}`:`/article/${t}`;return`/api/draft/start?path=${encodeURIComponent(n)}`}async function gn(e,t){const n=gt.parse(e),o=C(t),r=We(t),a=await me(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,c=Number(a.item.id);if(!Number.isInteger(c)||c<=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 l=ve(n.blocks,void 0,void 0,t).map((x,v)=>({block_type:x.block_type,content:x.content,language_id:u,order:v,page_id:s==="page"?c:null,post_id:s==="post"?c:null,product_id:null})),m=tr(a.item);if(n.meta)for(const[x,v]of Object.entries(n.meta))v!==void 0&&(m[x]=v);const h=jt(typeof m.slug=="string"?m.slug:a.item.slug),p=typeof m.title=="string"&&m.title.trim()?m.title:String(a.item.title||h||"Untitled"),g=s==="page"?`/cms/pages/${c}/edit`:`/cms/posts/${c}/edit`,f=nr(s,h),y=A({action:"REWRITE DRAFT",context:t,payload:{blocks:l,meta:m,parent_id:c,parent_type:s,tool:"rewrite_page_draft"},preview:{blockCount:l.length,contentType:s,slug:h,summary:`Stage a Live Draft that replaces the ${s} "${p}" with ${P(l.length,"new block")}. Nothing goes live until you review the draft and click Publish (which also saves a revision snapshot).`,title:p},subject:`${s}-${c}`});if(y)return y;const w=Number(a.item.version)||1,{error:b}=await o.from("content_drafts").delete().eq("parent_type",s).eq("parent_id",c);if(b)throw new Error(`Failed to clear the existing draft: ${_(b)}`);const{error:I}=await o.from("content_drafts").insert({author_id:r,base_version:w,blocks:l,meta:m,parent_id:c,parent_type:s});if(I)throw new Error(`Failed to save the draft: ${_(I)}`);return ge(l,o),N(t,{contentType:s,entityId:c,slug:h},h),{blockCount:l.length,contentType:s,draftPreviewPath:f,editPath:g,entityId:c,isDraft:!0,mutationExecuted:!0,slug:h,success:!0,title:p}}const or=new Set(["alt_text","author_name","author_title","caption","html_content","label","placeholder","quote","submit_button_text","success_message","text","text_content","title"]);function Be(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 Le(e,t,n){if(Array.isArray(e))return e.map(o=>Le(o,t,n));if(e&&typeof e=="object"){const o={};for(const[r,a]of Object.entries(e))typeof a=="string"&&or.has(r)?o[r]=Be(a,t,n):a&&typeof a=="object"?o[r]=Le(a,t,n):o[r]=a;return o}return e}const ft=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 fn(e,t){const n=ft.parse(e),o=V(t);if(o.contentType==="product")throw new Error("translate_page supports pages and posts only.");const r=C(t),a=Ve(o),s=o.contentType==="page"?"pages":"posts",c=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: ${_(d)}`);const{data:l,error:m}=await r.from("blocks").select("id, block_type, content, order").eq(c,a);if(m)throw new Error(`Could not read the source blocks: ${_(m)}`);const h=(Array.isArray(l)?l:[]).slice().sort((T,$)=>Number(T.order)-Number($.order));if(h.length===0)throw new Error(`The source ${o.contentType} has no content blocks to translate.`);const p=n.translations||{},g=Object.entries(p).filter(([T])=>!!T).sort((T,$)=>$[0].length-T[0].length),f=h.map((T,$)=>({blockType:T.block_type,content:Le(D(T.content),p,g),order:$})),k=await Se(r,n.targetLanguageCode),y=String(u.title||""),w=n.title||Be(y,p,g)||y||"Untitled",b=T=>typeof T=="string"&&T.trim()?Be(T,p,g):void 0,I=L(w)||u.slug||"translated-page",x={blocks:f,feature_image_id:u.feature_image_id??void 0,languageCode:k.code,meta_description:b(u.meta_description),meta_title:b(u.meta_title),slug:I,status:"published",title:w,translationGroupId:u.translation_group_id||void 0},v=o.contentType==="post"?{...x,excerpt:b(u.excerpt),label:b(u.label),published_at:u.published_at??new Date().toISOString(),subtitle:b(u.subtitle)}:x,j=A({action:"TRANSLATE",context:t,payload:{createInput:v,sourceId:u.id,tool:"translate_page"},preview:{blockCount:f.length,contentType:o.contentType,languageCode:k.code,slug:x.slug,status:x.status,summary:`Publish a ${k.code.toUpperCase()} translation of "${y}" — it goes live immediately, linked to the original ${o.contentType}, at /${x.slug} with ${P(f.length,"translated block")}.`,title:w},subject:`translate ${o.contentType} ${u.id} to ${k.code}`});if(j)return j;const q={...t,skipConfirmation:!0};return{...o.contentType==="post"?await $e(v,q):await Ee(v,q),isTranslation:!0,languageCode:k.code}}async function ht(e,t){const n=re.parse(e),o=n.entityId!==void 0||!!n.slug||!!n.title,r=C(t);let a,s;if(o){const g=await me({contentType:n.contentType,entityId:n.entityId,slug:n.slug,title:n.title},t),f=g.item;s=f.id,a={contentType:g.contentType,entityId:s,slug:typeof f.slug=="string"?f.slug:"",title:typeof f.title=="string"?f.title:""}}else a=V(t),s=Ce(a);const c=a.title||a.slug||"current item",u=a.contentType==="product",d=A({action:"SET IMAGES",context:t,payload:{contentType:a.contentType,entityId:String(s),images:n.images,tool:"set_content_images"},preview:{contentType:a.contentType,imageCount:n.images.length,slug:a.slug,summary:u?`Set ${P(n.images.length,"image")} on product "${c}" (the first becomes the main product image, the rest the gallery).`:`Set the feature image on the ${a.contentType} "${c}".`,title:a.title},subject:`set images on ${a.contentType} ${String(s)}`});if(d)return d;const l=await Ot(n.images,t,c);if(l.length===0)throw new Error("None of the provided images could be resolved to a media item.");if(u){const{data:g,error:f}=await r.from("products").select("id, slug, language_id, title").eq("id",s).maybeSingle();if(f||!g)throw new Error(`Could not load the product to set images: ${_(f)}`);const k=await Mn({mediaIds:l,productId:s,supabase:r});return await ze({patch:({meta:y})=>Array.isArray(y.product_media)?{meta:{...y,product_media:k.map((w,b)=>({media_id:w,sort_order:b}))}}:{},productId:s,supabase:r}),N(t,{contentType:"product",entityId:String(s),languageId:g.language_id,slug:g.slug,title:g.title},g.slug),t?.revalidatePath?.("/cms/products"),{contentType:"product",entityId:s,imageCount:k.length,mutationExecuted:!0,slug:g.slug,success:!0}}const m=a.contentType==="page"?"pages":"posts",{data:h,error:p}=await r.from(m).update({feature_image_id:l[0],updated_at:new Date().toISOString()}).eq("id",s).select("id, language_id, slug, status, title").single();if(p||!h)throw new Error(`Failed to set the feature image: ${_(p)}`);return N(t,a,h.slug),{contentType:a.contentType,entityId:s,extraImagesIgnored:l.length-1,imageCount:1,mutationExecuted:!0,slug:h.slug,success:!0}}function rr(e){return{...hn.createCortexDatabaseAgentTools(e),...yn.createCortexCustomBlockTools(e),fetch_ecommerce_stats:z.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=>Xt(t,e),inputSchema:Re,strict:!0}),read_current_cms_item:z.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=>Qt(t,e),inputSchema:De,strict:!0}),search_documentation:z.tool({description:"Search the NextBlock documentation database and return concise source snippets for factual CMS guidance.",execute:t=>Yt(t,e),inputSchema:xe,strict:!0}),fetch_url_content:z.tool({description:"Fetch an external web page and return its title, meta description, headings, body text, AND its images: `mainImage` (the page's subject image — schema.org Product image, else og:image, else the best in-body <img>) plus a ranked `images` list, all as absolute URLs. Read-only, no confirmation. Use this first whenever the user references an external URL to copy, adapt, clone, or draw inspiration from. To reuse the source page's image, pass `mainImage` straight into create_cms_product `images` or a page/post `feature_image_id` — it is imported into the media library automatically. Never invent an image URL: if `mainImage` is null, the page had none.",execute:t=>pn(t),inputSchema:pt,strict:!0}),search_stock_photos:z.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=>mn(t,e),inputSchema:mt,strict:!0}),rewrite_page_draft:z.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=>gn(t,e),inputSchema:gt,strict:!0}),translate_page:z.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=>fn(t,e),inputSchema:ft,strict:!0}),set_content_images:z.tool({description:"Set the feature image for a page or post, or the image gallery for a product. Pass `images`: a list of image URLs (e.g. `mainImage` from fetch_url_content or `url` values from 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). Targets the currently open page/post/product by default; to target any other item (for example a product you just created from the dashboard) pass contentType plus slug, entityId, or title — no open editor needed. Mutating: first returns a confirmation phrase; only applies after exact confirmation.",execute:t=>ht(t,e),inputSchema:re,strict:!0}),create_cms_page:z.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=>Ee(t,e),inputSchema:ae,strict:!0}),create_cms_post:z.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=>$e(t,e),inputSchema:se,strict:!0}),create_cms_product:z.tool({description:"Create a new draft-capable product, complete with its images and its body copy in ONE call. Pass `images` to set the main product image and gallery (external https URLs are imported into the media library automatically — use `mainImage` from fetch_url_content to reuse a source page's photo). Pass `blocks` to build the product's \"Product Description Blocks\" — the SAME block vocabulary and section-based design rules as create_cms_page, rendered on the public product page. This is the richest product body and is what you should produce whenever the user asks to copy or write real product content. Also pass `short_description` for the one-line summary shown on product cards. `description_html` is a plain-HTML fallback body used only when no blocks are supplied. Defaults missing fields safely: physical Stripe product, generated SKU, price 0, stock 0, taxable, draft. `price` is in major units (25 = $25.00). For translations, pass translationGroupId from the source product context. Mutating: first returns a confirmation phrase; only executes after exact confirmation.",execute:t=>ct(t,e),inputSchema:ce,strict:!0}),delete_cms_item:z.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=>dt(t,e),inputSchema:ue,strict:!0}),prepare_delete_cms_item:z.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=>an(t,e),inputSchema:Ge,strict:!0}),update_footer:z.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=>ot(t,e),inputSchema:Z,strict:!0}),update_content_block:z.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=>it(t,e),inputSchema:te,strict:!0}),insert_content_block:z.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=>at(t,e),inputSchema:ie,strict:!0}),update_current_cms_fields:z.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=>rt(t,e),inputSchema:ee,strict:!0}),update_cms_item_field:z.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=>ut(t,e),inputSchema:le,strict:!0}),update_navigation_bar:z.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=>nt(t,e),inputSchema:Q,strict:!0}),update_section_column_block:z.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=>st(t,e),inputSchema:ne,strict:!0}),execute_cms_action_plan:z.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=>sn(t,e),inputSchema:Ke,strict:!0})}}exports.availableCortexAiBlockTypes=G;exports.buildVisibleContactIntroActionPlan=$n;exports.cortexAiPageContextSchema=Me;exports.createCmsPageInputSchema=ae;exports.createCmsPostInputSchema=se;exports.createCmsProductInputSchema=ce;exports.createCortexGlobalAgentTools=rr;exports.deleteCmsItemInputSchema=ue;exports.executeCmsActionPlan=sn;exports.executeCmsActionPlanInputSchema=Ke;exports.executeCreateCmsPage=Ee;exports.executeCreateCmsPost=$e;exports.executeCreateCmsProduct=ct;exports.executeDeleteCmsItem=dt;exports.executeFetchEcommerceStats=Xt;exports.executeFetchUrlContent=pn;exports.executeInsertContentBlock=at;exports.executePrepareDeleteCmsItem=an;exports.executeReadCurrentCmsItem=Qt;exports.executeRewritePageDraft=gn;exports.executeSearchDocumentation=Jt;exports.executeSearchDocumentationWithTimeout=Yt;exports.executeSearchStockPhotos=mn;exports.executeSetContentImages=ht;exports.executeTranslatePage=fn;exports.executeUpdateCmsItemField=ut;exports.executeUpdateContentBlock=it;exports.executeUpdateCurrentCmsFields=rt;exports.executeUpdateFooter=ot;exports.executeUpdateNavigationBar=nt;exports.executeUpdateSectionColumnBlock=st;exports.fetchEcommerceStatsInputSchema=Re;exports.fetchUrlContentInputSchema=pt;exports.insertContentBlockInputSchema=ie;exports.maybeTriggerStockPhotoDownloads=ge;exports.navigationItemInputSchema=qe;exports.prepareDeleteCmsItemInputSchema=Ge;exports.readCurrentCmsItemInputSchema=De;exports.resolveCortexAiStockPhotoProvider=Xo;exports.resolveCortexAiStockPhotoProviders=Ae;exports.rewritePageDraftInputSchema=gt;exports.searchDocumentationInputSchema=xe;exports.searchStockPhotosInputSchema=mt;exports.setContentImagesInputSchema=re;exports.translatePageInputSchema=ft;exports.updateCmsItemFieldInputSchema=le;exports.updateContentBlockInputSchema=te;exports.updateCurrentCmsFieldsInputSchema=ee;exports.updateFooterInputSchema=Z;exports.updateNavigationBarInputSchema=Q;exports.updateSectionColumnBlockInputSchema=ne;
15
+ `).eq("orders.status","paid"):null;m&&(c&&m.eq("orders.currency",c),a&&m.gte("orders.paid_at",a.toISOString()),s&&m.lte("orders.paid_at",s.toISOString()));const p=n.timeRange!=="all_time"&&(n.reportType==="orders"||u)?o.from("orders").select("id, status, currency"):null;p&&c&&p.eq("currency",c);const[{data:g,error:f},{data:k,error:y},w]=await Promise.all([d,m??Promise.resolve({data:[],error:null}),p??Promise.resolve({data:null,error:null})]);if(f)throw new Error(`Failed to fetch ecommerce stats: ${_(f)}`);if(y)throw new Error(`Failed to fetch ecommerce stats: ${_(y)}`);if(w.error)throw new Error(`Failed to fetch ecommerce stats: ${_(w.error)}`);const b=Array.isArray(g)?g:[],I=Array.isArray(k)?k:[],x=Ct(b),v=Array.isArray(w.data)?w.data:null,j=v?Ct(v):null,q={};for(const T of I){const $=Array.isArray(T.orders)?T.orders[0]:T.orders,O=String($?.currency||c||"unknown").toUpperCase();q[O]=(q[O]??0)+X(T.quantity)*X(T.price_at_purchase)/100}const J={currency:c??null,currencyFiltered:!!c,orderStatusCounts:x,paidOrderCount:x.paid??0,query:n.query,reportType:n.reportType,revenueByCurrency:q,timeRange:n.timeRange,totalOrders:b.length,totalRevenue:Object.values(q).reduce((T,$)=>T+$,0)};if(j&&(J.allTimeOrderStatusCounts=j),u&&(J.matchingOrderStatus={allTimeCount:j?.[u]??x[u]??0,count:x[u]??0,status:u,timeRange:n.timeRange}),n.reportType==="products"||n.reportType==="revenue"||n.reportType==="general"){const T={};for(const $ of I){const O=Array.isArray($.products)?$.products[0]:$.products;if(!O?.id)continue;const Y=O.id;T[Y]||(T[Y]={id:Y,quantity:0,revenue:0,title:O.title,type:O.product_type}),T[Y].quantity+=X($.quantity),T[Y].revenue+=X($.quantity)*X($.price_at_purchase)/100}J.topProducts=Object.values(T).sort(($,O)=>O.revenue-$.revenue).slice(0,10)}return{report:J,success:!0}}async function Qt(e,t){const n=De.parse(e),o=z(t),r=V(t),a=ze(r),s=r.contentType==="page"?"pages":r.contentType==="post"?"posts":"products",{data:c,error:u}=await o.from(s).select("*").eq("id",a).single();if(u||!c)throw new Error(`Failed to read current ${r.contentType}: ${_(u)}`);let d=[];if(n.includeBlocks){const l=r.contentType==="page"?"page_id":r.contentType==="post"?"post_id":"product_id",{data:m,error:h}=await o.from("blocks").select("id, page_id, post_id, product_id, language_id, block_type, content, order").eq(l,a);if(h)throw new Error(`Failed to read current ${r.contentType} blocks: ${_(h)}`);d=(Array.isArray(m)?m:[]).slice().sort((p,g)=>Number(p.order)-Number(g.order)).map(p=>oo(p,n.includeBlockContent))}return{blocks:d,context:r,item:c,success:!0}}const Zt=new Set(["feature_image_id","language_id","meta_description","meta_title","slug","status","title"]),en=new Set(["excerpt","feature_image_id","label","language_id","meta_description","meta_title","published_at","slug","status","subtitle","title"]),Ao=new Set(["description_json","language_id","meta_description","meta_title","short_description","slug","status","title"]),Po=new Set(["excerpt","feature_image_id","label","meta_description","meta_title","published_at","short_description","subtitle"]);function No(e){return e==="page"?Zt:e==="post"?en:Ao}function tn(e,t){return Po.has(e)&&t===""?null:t}function Oe(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 Uo(e,t){const n=No(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"&&Oe(t.contentType,a),o[r]=tn(r,a)}return o}async function rt(e,t){const n=ee.parse(e),o=z(t),r=V(t),a=ze(r),s=Uo(n.fields,r),c=Object.keys(s);if(c.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:c,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 de(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:l,error:m}=await o.from(d).update({...s,updated_at:new Date().toISOString()}).eq("id",a).select("id, language_id, slug, status, title").single();if(m||!l)throw new Error(`Failed to update current ${r.contentType}: ${_(m)}`);return N(t,r,l.slug),{contentType:r.contentType,entityId:a,mutationExecuted:!0,slug:l.slug,success:!0,updatedFields:c}}async function it(e,t){const n=te.parse(e),o=z(t),r=V(t),{data:a,error:s}=await o.from("blocks").select("id, page_id, post_id, product_id, language_id, block_type, content, order").eq("id",n.blockId).single();if(s||!a)throw new Error(`Failed to read block ${n.blockId}: ${_(s)}`);Rt(a,r);const c=be(a.block_type,`Block ${n.blockId}`);Mt(n.blockType,c,`Block ${n.blockId}`);const u=pe(a.content,`Block ${n.blockId}`),d=no(c,u,n.content,t);M(c,d,`Block ${n.blockId}`,t);const l=A({action:"UPDATE CONTENT BLOCK",context:t,payload:{blockId:n.blockId,blockType:c,content:d,tool:"update_content_block"},preview:{blockId:n.blockId,blockType:c,contentType:r.contentType,entityId:ze(r)},subject:`${c} block ${n.blockId}`});if(l)return l;const{data:m,error:h}=await o.from("blocks").update({content:d,updated_at:new Date().toISOString()}).eq("id",n.blockId).select("id, block_type, order").single();if(h||!m)throw new Error(`Failed to update block ${n.blockId}: ${_(h)}`);return await Ce({patch:({blocks:p})=>({blocks:p.map(g=>String(g?.id)===String(n.blockId)?{...g,content:d}:g)}),productId:a.product_id,supabase:o}),ge([{content:d}],o),N(t,r),{blockId:m.id,blockType:m.block_type,contentUpdated:!0,mutationExecuted:!0,success:!0}}async function at(e,t){const n=ie.parse(e),o=z(t),r=await me(n,t),a=r.contentType==="product"?r.item.id:Number(r.item.id),s=r.contentType==="page"?"page_id":r.contentType==="post"?"post_id":"product_id",c=async()=>{const{data:b,error:I}=await o.from("blocks").select("id, page_id, post_id, product_id, language_id, block_type, content, order").eq(s,a);if(I)throw new Error(`Failed to read ${r.contentType} blocks: ${_(I)}`);return(Array.isArray(b)?b:[]).sort((x,v)=>Number(x.order)-Number(v.order))},u=b=>{if(n.position==="start")return 0;if(n.position==="end"){const v=b.map(j=>Number(j.order)).filter(Number.isFinite);return v.length>0?Math.max(...v)+1:0}const I=n.anchorBlockId?b.find(v=>Number(v.id)===n.anchorBlockId):n.anchorBlockType?b.find(v=>v.block_type===n.anchorBlockType):null;if(!I)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 x=Number(I.order);return n.position==="before"?x:x+1},d=Ie(n.block,0,t),l=await c(),m=u(l),h={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},p=A({action:"INSERT CONTENT BLOCK",context:t,payload:{block:d,order:m,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(p)return p;const g=await c(),f=u(g),k=g.filter(b=>Number(b.order)>=f).sort((b,I)=>Number(I.order)-Number(b.order));for(const b of k){const{error:I}=await o.from("blocks").update({order:Number(b.order)+1,updated_at:new Date().toISOString()}).eq("id",b.id);if(I)throw new Error(`Failed to shift block ${b.id}: ${_(I)}`)}const{data:y,error:w}=await o.from("blocks").insert({block_type:d.block_type,content:d.content,language_id:r.item.language_id,order:f,page_id:r.contentType==="page"?a:null,post_id:r.contentType==="post"?a:null,product_id:r.contentType==="product"?a:null}).select("id, block_type, order").single();if(w||!y)throw new Error(`Failed to insert content block: ${_(w)}`);return r.contentType==="product"&&await Ce({patch:({blocks:b})=>({blocks:[...b.map(I=>Number(I?.order)>=f?{...I,order:Number(I.order)+1}:I),{block_type:d.block_type,content:d.content,id:y.id,language_id:r.item.language_id,order:f,page_id:null,post_id:null,product_id:a}].sort((I,x)=>Number(I.order)-Number(x.order))}),productId:a,supabase:o}),ge([d],o),N(t,h),{blockId:y.id,blockType:y.block_type,contentType:r.contentType,entityId:r.item.id,mutationExecuted:!0,order:y.order,success:!0}}async function st(e,t){const n=ne.parse(e),o=z(t),r=V(t),{data:a,error:s}=await o.from("blocks").select("id, page_id, post_id, product_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}: ${_(s)}`);Rt(a,r);const c=be(a.block_type,`Parent block ${n.parentBlockId}`);if(c!=="section")throw new Error(`Parent block ${n.parentBlockId} must be a section block, not "${c}".`);const u=pe(a.content,`Parent block ${n.parentBlockId}`);M(c,u,`Parent block ${n.parentBlockId}`,t);const l=u.column_blocks?.[n.columnIndex]?.[n.blockIndex];if(!l)throw new Error(`Nested block was not found at column ${n.columnIndex}, index ${n.blockIndex}.`);const m=be(l.block_type,`Nested block ${n.columnIndex}:${n.blockIndex}`);Mt(n.blockType,m,`Nested block ${n.columnIndex}:${n.blockIndex}`),M(m,n.content,`Nested block ${n.columnIndex}:${n.blockIndex}`,t);const h=u.column_blocks.map((y,w)=>w===n.columnIndex?y.map((b,I)=>I===n.blockIndex?{...b,content:n.content}:b):y),p={...u,column_blocks:h};M(c,p,`Updated parent block ${n.parentBlockId}`,t);const g=A({action:"UPDATE NESTED BLOCK",context:t,payload:{blockIndex:n.blockIndex,columnIndex:n.columnIndex,content:n.content,nestedBlockType:m,parentBlockId:n.parentBlockId,tool:"update_section_column_block"},preview:{blockIndex:n.blockIndex,columnIndex:n.columnIndex,nestedBlockType:m,parentBlockId:n.parentBlockId,parentBlockType:c},subject:`${m} nested block ${n.columnIndex}:${n.blockIndex}`});if(g)return g;const{data:f,error:k}=await o.from("blocks").update({content:p,updated_at:new Date().toISOString()}).eq("id",n.parentBlockId).select("id, block_type").single();if(k||!f)throw new Error(`Failed to update parent block ${n.parentBlockId}: ${_(k)}`);return await Ce({patch:({blocks:y})=>({blocks:y.map(w=>String(w?.id)===String(n.parentBlockId)?{...w,content:p}:w)}),productId:a.product_id,supabase:o}),N(t,r),{blockIndex:n.blockIndex,columnIndex:n.columnIndex,mutationExecuted:!0,nestedBlockType:m,parentBlockId:f.id,parentBlockType:f.block_type,success:!0}}async function Ee(e,t){const n=ae.parse(e),o=z(t),r=We(t),a=await Se(o,n.languageCode),s=L(n.slug||n.title),c=ve(n.blocks,n.contactEmail,n.title,t),u=await Xe({contentType:"page",languageId:a.id,slug:s,supabase:o});if(u)return u;const d=await Qe({contentType:"page",languageCode:a.code,languageId:a.id,suppliedTranslationGroupId:n.translationGroupId,supabase:o});if(d.result)return d.result;const l={blocks:c,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"},m=A({action:"CREATE PAGE",context:t,payload:l,preview:{blockCount:c.length,languageCode:a.code,slug:s,status:n.status,title:n.title,translationGroupId:d.translationGroupId},subject:s});if(m)return m;const h=d.translationGroupId||Je(),p=await de(l.item.feature_image_id,t,n.title),{data:g,error:f}=await o.from("pages").insert({...l.item,author_id:r,feature_image_id:p,translation_group_id:h}).select("id, language_id, slug, status, title, translation_group_id").single();if(f||!g?.id)throw new Error(`Failed to create page: ${_(f)}`);try{await Ze({blocks:c,contentType:"page",itemId:Number(g.id),languageId:a.id,supabase:o})}catch(k){throw await et({contentType:"page",itemId:Number(g.id),supabase:o}),k}return N(t,{contentType:"page",entityId:Number(g.id),languageId:a.id,slug:s,title:n.title},s),t?.revalidatePath?.("/cms/pages"),{blockCount:c.length,contentType:"page",editPath:tt("page",g.id),entityId:g.id,mutationExecuted:!0,slug:s,success:!0,title:n.title,translationGroupId:g.translation_group_id}}async function $e(e,t){const n=se.parse(e),o=z(t),r=We(t),a=await Se(o,n.languageCode),s=L(n.slug||n.title),c=ve(n.blocks,void 0,void 0,t),u=await Xe({contentType:"post",languageId:a.id,slug:s,supabase:o});if(u)return u;const d=await Qe({contentType:"post",languageCode:a.code,languageId:a.id,suppliedTranslationGroupId:n.translationGroupId,supabase:o});if(d.result)return d.result;const l=n.published_at&&!Number.isNaN(new Date(n.published_at).getTime())?new Date(n.published_at).toISOString():n.published_at??null,m={blocks:c,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:l,slug:s,status:n.status,subtitle:n.subtitle??null,title:n.title,translation_group_id:d.translationGroupId},tool:"create_cms_post"},h=A({action:"CREATE POST",context:t,payload:m,preview:{blockCount:c.length,languageCode:a.code,slug:s,status:n.status,title:n.title,translationGroupId:d.translationGroupId},subject:s});if(h)return h;const p=d.translationGroupId||Je(),g=await de(m.item.feature_image_id,t,n.title),{data:f,error:k}=await o.from("posts").insert({...m.item,author_id:r,feature_image_id:g,translation_group_id:p}).select("id, language_id, slug, status, title, translation_group_id").single();if(k||!f?.id)throw new Error(`Failed to create post: ${_(k)}`);try{await Ze({blocks:c,contentType:"post",itemId:Number(f.id),languageId:a.id,supabase:o})}catch(y){throw await et({contentType:"post",itemId:Number(f.id),supabase:o}),y}return N(t,{contentType:"post",entityId:Number(f.id),languageId:a.id,slug:s,title:n.title},s),t?.revalidatePath?.("/cms/posts"),t?.revalidatePath?.("/articles"),{blockCount:c.length,contentType:"post",editPath:tt("post",f.id),entityId:f.id,mutationExecuted:!0,slug:s,success:!0,title:n.title,translationGroupId:f.translation_group_id}}function Fo(e,t){return(t||L(e)||"product").replace(/-/g,"").slice(0,24).toUpperCase()}function nn(e){if(e==null)return;if(typeof e=="string")return Pt.editorDocumentFromHtml(e)??void 0;const t=Array.isArray(e)?{content:e,type:"doc"}:E(e)&&e.type!=="doc"&&Array.isArray(e.content)?{...e,type:"doc"}:e,n=kt().safeParse(t);if(!n.success){if(E(e)&&typeof e.type=="string"){const o=kt().safeParse({content:[e],type:"doc"});if(o.success)return o.data}throw new Error(`Product description_json must be an editor document like { "type": "doc", "content": [ { "type": "paragraph", "content": [ { "type": "text", "text": "..." } ] } ] }, or simply an HTML string. Received: ${n.error.issues.map(o=>o.message).join("; ")}`)}return n.data}function Oo(e){const t=r=>!!(r&&Array.isArray(r.content)&&r.content.length>0),n=nn(e.description_json);if(t(n))return n;const o=e.description_html?Pt.editorDocumentFromHtml(e.description_html):null;return t(o)?o:void 0}async function ct(e,t){const n=ce.parse(e),o=z(t),r=await Se(o,n.languageCode),a=L(n.slug||n.title),s=ve(n.blocks,void 0,void 0,t),c=await Xe({contentType:"product",languageId:r.id,slug:a,supabase:o});if(c)return c;const u=await Qe({contentType:"product",languageCode:r.code,languageId:r.id,suppliedTranslationGroupId:n.translationGroupId,supabase:o});if(u.result)return u.result;const{createProduct:d,productSchema:l}=await Kn(),h=n.product_type==="digital"&&n.payment_provider==="freemius"?n.trial_period_days:0,p=l.parse({description_json:Oo(n),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||Fo(n.title,a),slug:a,status:n.status,stock:n.stock,title:n.title,trial_period_days:h,trial_requires_payment_method:h>0?n.trial_requires_payment_method:!1,translation_group_id:u.translationGroupId,upc:n.upc??"",variation_attributes:[],variants:[]}),g=n.images??[],f=A({action:"CREATE PRODUCT",context:t,payload:{blocks:s,images:g,item:p,tool:"create_cms_product"},preview:{blockCount:s.length,descriptionLength:p.description_json?JSON.stringify(p.description_json).length:0,imageCount:g.length,languageCode:r.code,price:p.price,sku:p.sku,slug:a,status:p.status,stock:p.stock,title:p.title,translationGroupId:u.translationGroupId},subject:a});if(f)return f;let k=[],y=null;if(g.length>0)try{if(k=[...new Set(await Ot(g,t,n.title))],k.length===0)throw new Error("None of the provided images could be resolved to a media item.")}catch(b){y=b instanceof Error?b.message:String(b)}const w=await d(o,{...p,product_media:k.map(b=>({media_id:b}))});if(!w?.id)throw new Error("Failed to create product.");try{await Ze({blocks:s,contentType:"product",itemId:w.id,languageId:r.id,supabase:o})}catch(b){throw await et({contentType:"product",itemId:w.id,supabase:o}),b}return N(t,{contentType:"product",entityId:w.id,languageId:r.id,slug:a,title:n.title},a),t?.revalidatePath?.("/cms/products"),{blockCount:s.length,contentType:"product",editPath:tt("product",w.id),entityId:w.id,imageCount:k.length,...y?{imageError:y}:{},mutationExecuted:!0,slug:a,success:!0,title:n.title,translationGroupId:w.translation_group_id}}function lt(e){return e.trim().replace(/[\s-]+/g,"_").toLowerCase()}function jo(e,t){const n=typeof t=="string"?lt(t):t;return e==="product"?n==="public"||n==="publish"||n==="published"?"active":n:n==="public"||n==="active"||n==="publish"?"published":n}function Bo(e){const t=lt(e.field);return!!(e.startsAt||e.endsAt||t.includes("start")||t.includes("end")||t.includes("schedule")||t.includes("special_date"))}async function Lo(e,t,n){if(e==="price"||e==="sale_price"){if(t==null)return{[e]:null};const o=await It(n);return{[e]:qt(Number(t),o)}}if(e==="prices"||e==="sale_prices"){const o=await It(n);return{[e]:Xn(t,o)}}return e==="description_json"?{description_json:nn(t)}:{[e]:t}}function qo(e,t){const n=lt(e.field),o=n==="status"?jo(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"?Zt:en).has(a))throw new Error(`Field "${e.field}" cannot be updated for ${t.contentType}.`);return a==="status"&&Oe(t.contentType,o),{field:a,payload:{[a]:tn(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"&&Oe("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 ut(e,t){const n=le.parse(e);if(Bo(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 me(n,t),r=qo(n,o),a=r.field;let s=r.payload;if(a==="language_id"&&typeof s.language_id=="string"){const m=await W(z(t),s.language_id);s={...s,language_id:m.id}}const c=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(c)return c;if(o.contentType==="product"){const m=z(t),h=await Lo(a,s[a],m),{data:p,error:g}=await m.from("products").update({...h,updated_at:new Date().toISOString()}).eq("id",o.item.id).select("id, language_id, slug, status, title").single();if(g||!p)throw new Error(`Failed to update product: ${_(g)}`);return N(t,{contentType:"product",entityId:String(p.id),languageId:p.language_id,slug:p.slug,title:p.title},p.slug),{contentType:"product",entityId:p.id,field:a,mutationExecuted:!0,slug:p.slug,success:!0,updatedFields:[a]}}a==="feature_image_id"&&typeof s.feature_image_id=="string"&&(s={...s,feature_image_id:await de(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:l}=await z(t).from(u).update({...s,updated_at:new Date().toISOString()}).eq("id",o.item.id).select("id, language_id, slug, status, title").single();if(l||!d)throw new Error(`Failed to update ${o.contentType}: ${_(l)}`);return N(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 on(e,t){const n=Ge.parse(e),o=await me(n,t);if(o.contentType==="product")return{affectedCount:1,collectionPath:xt("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 z(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: ${_(s)}`);const c=Array.isArray(a)?a:[],u=c.map(p=>o.contentType==="page"?p.slug==="home"?"/":`/${p.slug}`:`/article/${p.slug}`).filter(Boolean),d=new Set(u),{data:l,error:m}=await z(t).from("navigation_items").select("id, url");if(m)throw new Error(`Failed to inspect related navigation links: ${_(m)}`);const h=(Array.isArray(l)?l:[]).filter(p=>d.has(p.url)).length;return{affectedCount:c.length,collectionPath:xt(o.contentType),contentType:o.contentType,item:o.item,navigationLinkCount:h,publicPaths:u,targetIds:c.map(p=>p.id)}}function rn(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=[`${P(e.affectedCount,"language version")}`,e.navigationLinkCount>0?`${P(e.navigationLinkCount,"navigation link")}`:null].filter(Boolean);return`Delete ${e.contentType} "${t}"${n}, including ${o.join(" and ")}.`}async function an(e,t){const n=await on(e,t);return{...Lt({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:rn(n),title:n.item.title},subject:`${n.item.id} ${n.item.slug||""}`}),preparedDelete:!0}}async function dt(e,t){const n=ue.parse(e),o=await on(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:rn(o),title:o.item.title},subject:`${o.item.id} ${o.item.slug||""}`});if(r)return r;const a=z(t);if(o.contentType==="product"){const{error:c}=await a.from("products").delete().eq("id",o.item.id);if(c)throw new Error(`Failed to delete product: ${_(c)}`)}else{for(const d of o.publicPaths)await a.from("navigation_items").delete().eq("url",d);const c=o.contentType==="page"?"pages":"posts",{error:u}=await a.from(c).delete().eq("translation_group_id",o.item.translation_group_id);if(u)throw new Error(`Failed to delete ${o.contentType}: ${_(u)}`)}const s=t?.revalidatePath??He();return s&&(s(o.collectionPath),s("/cms/navigation"),o.publicPaths.forEach(c=>s(c))),{affectedCount:o.affectedCount,collectionPath:o.collectionPath,contentType:o.contentType,mutationExecuted:!0,redirectPath:o.collectionPath,success:!0}}async function St(e,t){switch(e.tool){case"create_cms_page":return Ee(e.input,t);case"create_cms_post":return $e(e.input,t);case"create_cms_product":return ct(e.input,t);case"delete_cms_item":return dt(e.input,t);case"update_cms_item_field":return ut(e.input,t);case"update_content_block":return it(e.input,t);case"insert_content_block":return at(e.input,t);case"update_current_cms_fields":return rt(e.input,t);case"update_footer":return ot(e.input,t);case"update_navigation_bar":return nt(e.input,t);case"update_section_column_block":return st(e.input,t);case"set_content_images":return ht(e.input,t)}}function Ro(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}function vt(e){return e==="create_cms_page"?"page":e==="create_cms_post"?"post":"product"}function Mo(e,t,n){if(e.tool!=="set_content_images")return e;const o=e.input;if(o.entityId!==void 0)return e;const r=o.slug?t.get(`${o.contentType||"product"}:${L(o.slug)}`):n;return r?{...e,input:{...o,contentType:r.contentType,entityId:r.entityId}}:e}async function sn(e,t){const n=Ke.parse(e),o=new Set(n.actions.filter(p=>p.tool==="create_cms_page"||p.tool==="create_cms_post"||p.tool==="create_cms_product").map(p=>{const g=p.input;return`${vt(p.tool)}:${L(g.slug||g.title||"")}`})),r=p=>{if(p.tool!=="set_content_images")return!1;const g=p.input;return g.slug?o.has(`${g.contentType||"product"}:${L(g.slug)}`):o.size>0};if(!t?.skipConfirmation){const p=[];for(const k of n.actions){if(r(k)){const w=k.input;p.push(`Set ${P(w.images.length,"image")} on the ${w.slug?`"${w.slug}"`:"new"} item created in this plan.`);continue}const y=await St(k,{...t,latestUserMessage:null});if(!y||typeof y!="object")return{message:`Could not prepare action ${p.length+1}.`,mutationExecuted:!1,success:!1};if(y.success===!1||y.unsupported===!0)return y;y.requiresConfirmation===!0&&y.preview?p.push(Wn(k.tool,y.preview)):p.push(`Run ${k.tool.replace(/_/g," ")}.`)}const g=n.summary||`Complete ${P(n.actions.length,"CMS action")}.`,f=A({action:"EXECUTE CMS ACTION PLAN",context:t,payload:{actions:n.actions,tool:"execute_cms_action_plan"},preview:{actionCount:n.actions.length,actionSummaries:p,summary:g},subject:`${n.actions.length} actions`});if(f)return f}const a={...t,skipConfirmation:!0},s=[];let c=!1,u=null,d=null;const l={},m=new Map;let h=null;for(const[p,g]of n.actions.entries()){const f=Mo(Ro(g,l),m,h),k=await St(f,a);if(s.push({output:k,tool:f.tool}),k&&typeof k=="object"){const y=k;if(y.mutationExecuted===!0&&(c=!0),!u&&typeof y.editPath=="string"&&(u=y.editPath),typeof y.redirectPath=="string"&&(d=y.redirectPath),(f.tool==="create_cms_page"||f.tool==="create_cms_post"||f.tool==="create_cms_product")&&(typeof y.translationGroupId=="string"&&(l[f.tool]=y.translationGroupId),y.entityId!==void 0&&y.entityId!==null)){const w=vt(f.tool),b={contentType:w,entityId:y.entityId};h=b,typeof y.slug=="string"&&m.set(`${w}:${y.slug}`,b)}if(y.success===!1||y.unsupported===!0)return{actionCount:n.actions.length,failedActionIndex:p,failedTool:f.tool,message:typeof y.message=="string"?y.message:`Action ${p+1} failed.`,mutationExecuted:c,results:s,success:!1,...u?{editPath:u}:{},...d?{redirectPath:d}:{}}}}return{actionCount:n.actions.length,editPath:d?void 0:u??void 0,mutationExecuted:c,redirectPath:d??void 0,results:s,success:!0,summary:n.summary??null}}const pt=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://.")}),Do=12e3,Et=2e6;function $t(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 he(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 Go(e){return e.trim().replace(/&amp;/gi,"&").replace(/&#38;/g,"&").replace(/&quot;/gi,'"').replace(/&#39;/g,"'")}const cn=/\.(avif|gif|jpe?g|png|webp)(?:[?#]|$)/i,ln=/(?:^|[/_-])(?:sprite|icon|favicon|logo|placeholder|pixel|spacer|blank|avatar|badge|flag|loader|spinner|1x1|transparent|watermark|payment|visa|mastercard|paypal|amex|social|share|facebook|twitter|instagram|youtube|pinterest|linkedin)(?:[/_.-]|$)/i;function Te(e,t){if(typeof e!="string")return null;const n=Go(e);if(!n||n.startsWith("data:"))return null;try{const o=new URL(n,t);return o.protocol!=="http:"&&o.protocol!=="https:"?null:o.toString()}catch{return null}}function Ko(e){let t=null;for(const n of e.split(",")){const o=n.trim().split(/\s+/),r=o[0];if(!r)continue;const a=o[1]||"",s=a.match(/^(\d+(?:\.\d+)?)w$/i),c=a.match(/^(\d+(?:\.\d+)?)x$/i),u=s?Number(s[1]):c?Number(c[1])*1e3:1;(!t||u>t.weight)&&(t={url:r,weight:u})}return t?.url??null}function F(e,t){const n=e.match(new RegExp(`\\b${t}\\s*=\\s*(?:"([^"]*)"|'([^']*)'|([^\\s>]+))`,"i"));return n?n[1]??n[2]??n[3]??null:null}function Ho(e,t){const n=[],o=[],r=(c,u)=>{if(typeof c=="string"){const d=Te(c,t);d&&u.push(d);return}if(Array.isArray(c)){for(const d of c)r(d,u);return}c&&typeof c=="object"&&(r(c.url,u),r(c.contentUrl,u))},a=(c,u)=>{if(u>8||!c||typeof c!="object")return;if(Array.isArray(c)){for(const p of c)a(p,u+1);return}const d=c,l=d["@type"],h=(Array.isArray(l)?l:[l]).filter(p=>typeof p=="string").map(p=>p.toLowerCase()).some(p=>p==="product"||p==="productgroup"||p==="itempage");"image"in d&&r(d.image,h?n:o);for(const p of Object.values(d))a(p,u+1)},s=e.matchAll(/<script\b[^>]*type\s*=\s*["']application\/ld\+json["'][^>]*>([\s\S]*?)<\/script>/gi);for(const c of s){const u=(c[1]||"").trim();if(u)try{a(JSON.parse(u),0)}catch{}}return[...n,...o]}const un=/(?:^|[/_-])(?:thumbnails?|thumbs?|small|mini)(?:[/_.-]|$)/i;function dn(e){try{const{pathname:t}=new URL(e);return decodeURIComponent(t.slice(t.lastIndexOf("/")+1)).toLowerCase()||null}catch{return null}}function Vo(e,t){const n=new Map;for(const o of e.matchAll(/<a\b[^>]*>/gi)){const r=Te(F(o[0],"href"),t);if(!r||!cn.test(r)||un.test(r)||ln.test(r))continue;const a=dn(r);a&&!n.has(a)&&n.set(a,r)}return n}function Wo(e,t){const n=[...Ho(e,t)],o=[/<meta\b[^>]*\b(?:property|name)\s*=\s*["'](?:og:image:secure_url|og:image:url|og:image)["'][^>]*>/gi,/<meta\b[^>]*\b(?:property|name)\s*=\s*["'](?:twitter:image:src|twitter:image)["'][^>]*>/gi,/<meta\b[^>]*\bitemprop\s*=\s*["']image["'][^>]*>/gi,/<link\b[^>]*\brel\s*=\s*["']image_src["'][^>]*>/gi];for(const l of o)for(const m of e.matchAll(l)){const h=m[0],p=Te(F(h,"content")||F(h,"href"),t);p&&n.push(p)}const r=[];for(const l of e.matchAll(/<img\b[^>]*>/gi)){const m=l[0],h=F(m,"srcset")||F(m,"data-srcset"),p=[h?Ko(h):null,F(m,"src"),F(m,"data-src"),F(m,"data-original"),F(m,"data-lazy-src"),F(m,"data-image")];let g=null;for(const k of p)if(g=Te(k,t),g)break;if(!g||ln.test(g))continue;const f=Number(F(m,"width"));Number.isFinite(f)&&f>0&&f<200||r.push(g)}const a=l=>cn.test(l);n.push(...r.filter(a),...r.filter(l=>!a(l)));const s=Vo(e,t),c=l=>{if(!un.test(l))return l;const m=dn(l);return m&&s.get(m)||l},u=new Set,d=[];for(const l of n){const m=c(l);if(!u.has(m)&&(u.add(m),d.push(m),d.length>=12))break}return{images:d,mainImage:d[0]??null}}function Jo(e,t,n){const o=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," "),{images:r,mainImage:a}=Wo(e,n),s=e.match(/<title\b[^>]*>([\s\S]*?)<\/title>/i),c=e.match(/<meta[^>]+name=["']description["'][^>]*content=["']([^"']*)["'][^>]*>/i)||e.match(/<meta[^>]+content=["']([^"']*)["'][^>]*name=["']description["'][^>]*>/i),u=[...o.matchAll(/<h([1-3])\b[^>]*>([\s\S]*?)<\/h\1>/gi)].map(m=>he(m[2])).filter(Boolean).slice(0,40),d=o.match(/<body\b[^>]*>([\s\S]*?)<\/body>/i),l=he(d?.[1]??o);return{description:c?he(c[1]):"",headings:u,images:r,mainImage:a,text:l.slice(0,t),title:s?he(s[1]):"",truncated:l.length>t}}async function pn(e){const t=pt.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($t(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(),Do);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($t(new URL(s).hostname))return{message:"The URL redirected to a blocked internal address.",success:!1,url:t.url}}catch{}const c=a.headers.get("content-type")||"";if(!/text\/html|text\/plain|application\/xhtml/i.test(c))return{contentType:c,message:`The URL is not an HTML or text page (content-type: ${c||"unknown"}).`,success:!1,url:t.url};const u=await a.text(),d=u.length>Et?u.slice(0,Et):u,l=Jo(d,t.maxChars,s);return!l.text&&!l.title?{message:"The URL returned no readable text content.",success:!1,url:t.url}:{description:l.description,finalUrl:s,headings:l.headings,images:l.images,mainImage:l.mainImage,success:!0,text:l.text,title:l.title,truncated:l.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: ${_(a)}`,success:!1,url:t.url}}finally{clearTimeout(r)}}const mt=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".')}),Yo=12e3;async function Ae(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")),c=l=>{if(!l)return null;try{const m=s(l);return typeof m=="string"&&m.trim()?m.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=c(d.find(l=>l.key===r)?.value),n=c(d.find(l=>l.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 Xo(e){return(await Ae(e))[0]??null}async function Qo(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 At(e,t){const n=new AbortController,o=setTimeout(()=>n.abort(),Yo);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 ye(e){const t=Number(e);return Number.isFinite(t)&&t>0?t:null}function je(e,t){if(!E(e))return;const n=o=>{E(o)&&o.provider==="unsplash"&&typeof o.downloadLocation=="string"&&o.downloadLocation.trim()&&t.add(o.downloadLocation.trim())};if(n(e.attribution),E(e.background)&&E(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)E(r)&&je(r.content,t)}if(Array.isArray(e.slides))for(const o of e.slides)je(o,t)}async function ge(e,t){try{const n=new Set;for(const a of e)je(a?.content,n);if(n.size===0)return;const r=(await Ae(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 Zo(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 At(`https://api.pexels.com/v1/search?${o.toString()}`,{Authorization:e.apiKey});return(Array.isArray(a?.photos)?a.photos:[]).map(s=>{const c=typeof s?.photographer=="string"?s.photographer:null;return{alt:typeof s?.alt=="string"&&s.alt.trim()?s.alt.trim():t.query,credit:c?`Photo by ${c} on Pexels`:"Photo on Pexels",downloadLocation:null,height:ye(s?.height),photographer:c,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:ye(s?.width)}}).filter(s=>typeof s.url=="string")}const r=await At(`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:ye(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:ye(a?.width)}}).filter(a=>typeof a.url=="string")}async function mn(e,t){const n=mt.parse(e),o=await Ae(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(c=>c.provider==="unsplash")?await Qo(t?.supabase):null,a=[];let s=null;for(const c of o){a.push(c.provider);try{const u=await Zo(c,n,r);if(u.length>0)return{attemptedProviders:a,photos:u,provider:c.provider,query:n.query,success:!0,usageGuidance:c.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(", ")}: ${_(s)}`:`No matching stock photos found for "${n.query}".`,photos:[],success:!1}}const gt=H.extend({blocks:i.z.array(oe).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()}),er=["custom_canonical","excerpt","feature_image_id","label","language_id","meta_description","meta_title","published_at","slug","status","subtitle","title","translation_group_id"];function tr(e){const t={};for(const n of er)n in e&&e[n]!==void 0&&(t[n]=e[n]);return t}function nr(e,t){if(!t)return null;const n=e==="page"?t==="home"?"/":`/${t}`:`/article/${t}`;return`/api/draft/start?path=${encodeURIComponent(n)}`}async function gn(e,t){const n=gt.parse(e),o=z(t),r=We(t),a=await me(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,c=Number(a.item.id);if(!Number.isInteger(c)||c<=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 l=ve(n.blocks,void 0,void 0,t).map((x,v)=>({block_type:x.block_type,content:x.content,language_id:u,order:v,page_id:s==="page"?c:null,post_id:s==="post"?c:null,product_id:null})),m=tr(a.item);if(n.meta)for(const[x,v]of Object.entries(n.meta))v!==void 0&&(m[x]=v);const h=jt(typeof m.slug=="string"?m.slug:a.item.slug),p=typeof m.title=="string"&&m.title.trim()?m.title:String(a.item.title||h||"Untitled"),g=s==="page"?`/cms/pages/${c}/edit`:`/cms/posts/${c}/edit`,f=nr(s,h),y=A({action:"REWRITE DRAFT",context:t,payload:{blocks:l,meta:m,parent_id:c,parent_type:s,tool:"rewrite_page_draft"},preview:{blockCount:l.length,contentType:s,slug:h,summary:`Stage a Live Draft that replaces the ${s} "${p}" with ${P(l.length,"new block")}. Nothing goes live until you review the draft and click Publish (which also saves a revision snapshot).`,title:p},subject:`${s}-${c}`});if(y)return y;const w=Number(a.item.version)||1,{error:b}=await o.from("content_drafts").delete().eq("parent_type",s).eq("parent_id",c);if(b)throw new Error(`Failed to clear the existing draft: ${_(b)}`);const{error:I}=await o.from("content_drafts").insert({author_id:r,base_version:w,blocks:l,meta:m,parent_id:c,parent_type:s});if(I)throw new Error(`Failed to save the draft: ${_(I)}`);return ge(l,o),N(t,{contentType:s,entityId:c,slug:h},h),{blockCount:l.length,contentType:s,draftPreviewPath:f,editPath:g,entityId:c,isDraft:!0,mutationExecuted:!0,slug:h,success:!0,title:p}}const or=new Set(["alt_text","author_name","author_title","caption","html_content","label","placeholder","quote","submit_button_text","success_message","text","text_content","title"]);function Be(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 Le(e,t,n){if(Array.isArray(e))return e.map(o=>Le(o,t,n));if(e&&typeof e=="object"){const o={};for(const[r,a]of Object.entries(e))typeof a=="string"&&or.has(r)?o[r]=Be(a,t,n):a&&typeof a=="object"?o[r]=Le(a,t,n):o[r]=a;return o}return e}const ft=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 fn(e,t){const n=ft.parse(e),o=V(t);if(o.contentType==="product")throw new Error("translate_page supports pages and posts only.");const r=z(t),a=Ve(o),s=o.contentType==="page"?"pages":"posts",c=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: ${_(d)}`);const{data:l,error:m}=await r.from("blocks").select("id, block_type, content, order").eq(c,a);if(m)throw new Error(`Could not read the source blocks: ${_(m)}`);const h=(Array.isArray(l)?l:[]).slice().sort((T,$)=>Number(T.order)-Number($.order));if(h.length===0)throw new Error(`The source ${o.contentType} has no content blocks to translate.`);const p=n.translations||{},g=Object.entries(p).filter(([T])=>!!T).sort((T,$)=>$[0].length-T[0].length),f=h.map((T,$)=>({blockType:T.block_type,content:Le(D(T.content),p,g),order:$})),k=await Se(r,n.targetLanguageCode),y=String(u.title||""),w=n.title||Be(y,p,g)||y||"Untitled",b=T=>typeof T=="string"&&T.trim()?Be(T,p,g):void 0,I=L(w)||u.slug||"translated-page",x={blocks:f,feature_image_id:u.feature_image_id??void 0,languageCode:k.code,meta_description:b(u.meta_description),meta_title:b(u.meta_title),slug:I,status:"published",title:w,translationGroupId:u.translation_group_id||void 0},v=o.contentType==="post"?{...x,excerpt:b(u.excerpt),label:b(u.label),published_at:u.published_at??new Date().toISOString(),subtitle:b(u.subtitle)}:x,j=A({action:"TRANSLATE",context:t,payload:{createInput:v,sourceId:u.id,tool:"translate_page"},preview:{blockCount:f.length,contentType:o.contentType,languageCode:k.code,slug:x.slug,status:x.status,summary:`Publish a ${k.code.toUpperCase()} translation of "${y}" — it goes live immediately, linked to the original ${o.contentType}, at /${x.slug} with ${P(f.length,"translated block")}.`,title:w},subject:`translate ${o.contentType} ${u.id} to ${k.code}`});if(j)return j;const q={...t,skipConfirmation:!0};return{...o.contentType==="post"?await $e(v,q):await Ee(v,q),isTranslation:!0,languageCode:k.code}}async function ht(e,t){const n=re.parse(e),o=n.entityId!==void 0||!!n.slug||!!n.title,r=z(t);let a,s;if(o){const g=await me({contentType:n.contentType,entityId:n.entityId,slug:n.slug,title:n.title},t),f=g.item;s=f.id,a={contentType:g.contentType,entityId:s,slug:typeof f.slug=="string"?f.slug:"",title:typeof f.title=="string"?f.title:""}}else a=V(t),s=ze(a);const c=a.title||a.slug||"current item",u=a.contentType==="product",d=A({action:"SET IMAGES",context:t,payload:{contentType:a.contentType,entityId:String(s),images:n.images,tool:"set_content_images"},preview:{contentType:a.contentType,imageCount:n.images.length,slug:a.slug,summary:u?`Set ${P(n.images.length,"image")} on product "${c}" (the first becomes the main product image, the rest the gallery).`:`Set the feature image on the ${a.contentType} "${c}".`,title:a.title},subject:`set images on ${a.contentType} ${String(s)}`});if(d)return d;const l=await Ot(n.images,t,c);if(l.length===0)throw new Error("None of the provided images could be resolved to a media item.");if(u){const{data:g,error:f}=await r.from("products").select("id, slug, language_id, title").eq("id",s).maybeSingle();if(f||!g)throw new Error(`Could not load the product to set images: ${_(f)}`);const k=await Mn({mediaIds:l,productId:s,supabase:r});return await Ce({patch:({meta:y})=>Array.isArray(y.product_media)?{meta:{...y,product_media:k.map((w,b)=>({media_id:w,sort_order:b}))}}:{},productId:s,supabase:r}),N(t,{contentType:"product",entityId:String(s),languageId:g.language_id,slug:g.slug,title:g.title},g.slug),t?.revalidatePath?.("/cms/products"),{contentType:"product",entityId:s,imageCount:k.length,mutationExecuted:!0,slug:g.slug,success:!0}}const m=a.contentType==="page"?"pages":"posts",{data:h,error:p}=await r.from(m).update({feature_image_id:l[0],updated_at:new Date().toISOString()}).eq("id",s).select("id, language_id, slug, status, title").single();if(p||!h)throw new Error(`Failed to set the feature image: ${_(p)}`);return N(t,a,h.slug),{contentType:a.contentType,entityId:s,extraImagesIgnored:l.length-1,imageCount:1,mutationExecuted:!0,slug:h.slug,success:!0}}function rr(e){return{...hn.createCortexDatabaseAgentTools(e),...yn.createCortexCustomBlockTools(e),fetch_ecommerce_stats:C.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=>Xt(t,e),inputSchema:Re,strict:!0}),read_current_cms_item:C.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=>Qt(t,e),inputSchema:De,strict:!0}),search_documentation:C.tool({description:"Search the NextBlock documentation database and return concise source snippets for factual CMS guidance.",execute:t=>Yt(t,e),inputSchema:xe,strict:!0}),fetch_url_content:C.tool({description:"Fetch an external web page and return its title, meta description, headings, body text, AND its images: `mainImage` (the page's subject image — schema.org Product image, else og:image, else the best in-body <img>) plus a ranked `images` list, all as absolute URLs. Read-only, no confirmation. Use this first whenever the user references an external URL to copy, adapt, clone, or draw inspiration from. To reuse the source page's image, pass `mainImage` straight into create_cms_product `images` or a page/post `feature_image_id` — it is imported into the media library automatically. Never invent an image URL: if `mainImage` is null, the page had none.",execute:t=>pn(t),inputSchema:pt,strict:!0}),search_stock_photos:C.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=>mn(t,e),inputSchema:mt,strict:!0}),rewrite_page_draft:C.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=>gn(t,e),inputSchema:gt,strict:!0}),translate_page:C.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=>fn(t,e),inputSchema:ft,strict:!0}),set_content_images:C.tool({description:"Set the feature image for a page or post, or the image gallery for a product. Pass `images`: a list of image URLs (e.g. `mainImage` from fetch_url_content or `url` values from 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). Targets the currently open page/post/product by default; to target any other item (for example a product you just created from the dashboard) pass contentType plus slug, entityId, or title — no open editor needed. Mutating: first returns a confirmation phrase; only applies after exact confirmation.",execute:t=>ht(t,e),inputSchema:re,strict:!0}),create_cms_page:C.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=>Ee(t,e),inputSchema:ae,strict:!0}),create_cms_post:C.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=>$e(t,e),inputSchema:se,strict:!0}),create_cms_product:C.tool({description:"Create a new draft-capable product, complete with its images and its body copy in ONE call. Pass `images` to set the main product image and gallery (external https URLs are imported into the media library automatically — use `mainImage` from fetch_url_content to reuse a source page's photo). Pass `blocks` to build the product's \"Product Description Blocks\" — the SAME block vocabulary and section-based design rules as create_cms_page, rendered on the public product page. This is the richest product body and is what you should produce whenever the user asks to copy or write real product content. Also pass `short_description` for the one-line summary shown on product cards. `description_html` is a plain-HTML fallback body used only when no blocks are supplied. Defaults missing fields safely: physical Stripe product, generated SKU, price 0, stock 0, taxable, draft. `price` is in major units (25 = $25.00). For translations, pass translationGroupId from the source product context. Mutating: first returns a confirmation phrase; only executes after exact confirmation.",execute:t=>ct(t,e),inputSchema:ce,strict:!0}),delete_cms_item:C.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=>dt(t,e),inputSchema:ue,strict:!0}),prepare_delete_cms_item:C.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=>an(t,e),inputSchema:Ge,strict:!0}),update_footer:C.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=>ot(t,e),inputSchema:Z,strict:!0}),update_content_block:C.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=>it(t,e),inputSchema:te,strict:!0}),insert_content_block:C.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=>at(t,e),inputSchema:ie,strict:!0}),update_current_cms_fields:C.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=>rt(t,e),inputSchema:ee,strict:!0}),update_cms_item_field:C.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=>ut(t,e),inputSchema:le,strict:!0}),update_navigation_bar:C.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=>nt(t,e),inputSchema:Q,strict:!0}),update_section_column_block:C.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=>st(t,e),inputSchema:ne,strict:!0}),execute_cms_action_plan:C.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=>sn(t,e),inputSchema:Ke,strict:!0})}}exports.availableCortexAiBlockTypes=G;exports.buildVisibleContactIntroActionPlan=$n;exports.cortexAiPageContextSchema=Me;exports.createCmsPageInputSchema=ae;exports.createCmsPostInputSchema=se;exports.createCmsProductInputSchema=ce;exports.createCortexGlobalAgentTools=rr;exports.deleteCmsItemInputSchema=ue;exports.executeCmsActionPlan=sn;exports.executeCmsActionPlanInputSchema=Ke;exports.executeCreateCmsPage=Ee;exports.executeCreateCmsPost=$e;exports.executeCreateCmsProduct=ct;exports.executeDeleteCmsItem=dt;exports.executeFetchEcommerceStats=Xt;exports.executeFetchUrlContent=pn;exports.executeInsertContentBlock=at;exports.executePrepareDeleteCmsItem=an;exports.executeReadCurrentCmsItem=Qt;exports.executeRewritePageDraft=gn;exports.executeSearchDocumentation=Jt;exports.executeSearchDocumentationWithTimeout=Yt;exports.executeSearchStockPhotos=mn;exports.executeSetContentImages=ht;exports.executeTranslatePage=fn;exports.executeUpdateCmsItemField=ut;exports.executeUpdateContentBlock=it;exports.executeUpdateCurrentCmsFields=rt;exports.executeUpdateFooter=ot;exports.executeUpdateNavigationBar=nt;exports.executeUpdateSectionColumnBlock=st;exports.fetchEcommerceStatsInputSchema=Re;exports.fetchUrlContentInputSchema=pt;exports.insertContentBlockInputSchema=ie;exports.maybeTriggerStockPhotoDownloads=ge;exports.navigationItemInputSchema=qe;exports.prepareDeleteCmsItemInputSchema=Ge;exports.readCurrentCmsItemInputSchema=De;exports.resolveCortexAiStockPhotoProvider=Xo;exports.resolveCortexAiStockPhotoProviders=Ae;exports.rewritePageDraftInputSchema=gt;exports.searchDocumentationInputSchema=xe;exports.searchStockPhotosInputSchema=mt;exports.setContentImagesInputSchema=re;exports.translatePageInputSchema=ft;exports.updateCmsItemFieldInputSchema=le;exports.updateContentBlockInputSchema=te;exports.updateCurrentCmsFieldsInputSchema=ee;exports.updateFooterInputSchema=Z;exports.updateNavigationBarInputSchema=Q;exports.updateSectionColumnBlockInputSchema=ne;
@@ -463,7 +463,16 @@ const kn = i.enum(K), Ze = i.object({
463
463
  heading: i.object({
464
464
  level: i.union([i.literal(1), i.literal(2), i.literal(3), i.literal(4), i.literal(5), i.literal(6)]),
465
465
  textAlign: i.enum(["left", "center", "right", "justify"]).optional(),
466
- textColor: i.enum(["primary", "secondary", "accent", "muted", "destructive", "background"]).optional(),
466
+ // Mirrors TextColorSchema in apps/nextblock/lib/blocks/blockRegistry.ts
467
+ // a theme token, or a literal CSS colour from the block editor's picker.
468
+ // libs/* cannot import from the app, so the union is restated here.
469
+ textColor: i.union([
470
+ i.enum(["foreground", "primary", "secondary", "accent", "muted", "destructive", "background"]),
471
+ i.string().regex(
472
+ /^(#(?:[0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})|rgba?\([^)]+\)|hsla?\([^)]+\))$/i,
473
+ "Must be a hex, rgb(a) or hsl(a) colour"
474
+ )
475
+ ]).optional().describe("Prefer a theme token so the heading adapts to dark mode; use a CSS colour only when the brand requires an exact value"),
467
476
  text_content: i.string()
468
477
  }),
469
478
  image: i.object({
@@ -758,16 +767,16 @@ function P(e) {
758
767
  const t = Ct(e), n = $e(e.context?.latestUserMessage || ""), r = $e(t.confirmationPhrase);
759
768
  return n.includes(r) ? null : t;
760
769
  }
761
- function Re(e) {
770
+ function qe(e) {
762
771
  const t = e?.actorUserId;
763
772
  if (!t)
764
773
  throw new Error("A confirmed CMS mutation requires an authenticated admin actor.");
765
774
  return t;
766
775
  }
767
- function qe() {
776
+ function Re() {
768
777
  return globalThis.crypto?.randomUUID?.() || `id-${Date.now()}-${Math.random().toString(36).slice(2)}`;
769
778
  }
770
- function R(e) {
779
+ function q(e) {
771
780
  return e.toLowerCase().trim().replace(/\s+/g, "-").replace(/[^a-z0-9-]/g, "").replace(/-+/g, "-").replace(/^-|-$/g, "").slice(0, 300);
772
781
  }
773
782
  function Me(e) {
@@ -791,13 +800,13 @@ const Bn = /* @__PURE__ */ new Set([
791
800
  "XOF",
792
801
  "XPF"
793
802
  ]);
794
- function Rn(e) {
803
+ function qn(e) {
795
804
  return Bn.has(Me(e)) ? 0 : 2;
796
805
  }
797
806
  function St(e, t) {
798
- return Math.round(e * 10 ** Rn(t));
807
+ return Math.round(e * 10 ** qn(t));
799
808
  }
800
- function qn(e, t) {
809
+ function Rn(e, t) {
801
810
  return !e || typeof e != "object" || Array.isArray(e) ? {} : Object.entries(e).reduce(
802
811
  (n, [r, o]) => {
803
812
  if (typeof o == "number" && Number.isFinite(o) && o >= 0) {
@@ -1081,7 +1090,7 @@ async function Wn(e) {
1081
1090
  const o = Array.isArray(n) ? n[0] : n;
1082
1091
  if (!o?.id)
1083
1092
  return null;
1084
- let a = qe();
1093
+ let a = Re();
1085
1094
  if (o.translation_group_id) {
1086
1095
  const { data: s, error: l } = await e.supabase.from("pages").select("id").eq("translation_group_id", o.translation_group_id);
1087
1096
  if (l)
@@ -1790,10 +1799,10 @@ async function wr(e, t) {
1790
1799
  throw new Error(`Failed to fetch ecommerce stats: ${_(y)}`);
1791
1800
  if (w.error)
1792
1801
  throw new Error(`Failed to fetch ecommerce stats: ${_(w.error)}`);
1793
- const b = Array.isArray(g) ? g : [], I = Array.isArray(k) ? k : [], x = at(b), E = Array.isArray(w.data) ? w.data : null, L = E ? at(E) : null, q = {};
1802
+ const b = Array.isArray(g) ? g : [], I = Array.isArray(k) ? k : [], x = at(b), E = Array.isArray(w.data) ? w.data : null, L = E ? at(E) : null, R = {};
1794
1803
  for (const T of I) {
1795
1804
  const A = Array.isArray(T.orders) ? T.orders[0] : T.orders, j = String(A?.currency || l || "unknown").toUpperCase();
1796
- q[j] = (q[j] ?? 0) + X(T.quantity) * X(T.price_at_purchase) / 100;
1805
+ R[j] = (R[j] ?? 0) + X(T.quantity) * X(T.price_at_purchase) / 100;
1797
1806
  }
1798
1807
  const W = {
1799
1808
  currency: l ?? null,
@@ -1802,10 +1811,10 @@ async function wr(e, t) {
1802
1811
  paidOrderCount: x.paid ?? 0,
1803
1812
  query: n.query,
1804
1813
  reportType: n.reportType,
1805
- revenueByCurrency: q,
1814
+ revenueByCurrency: R,
1806
1815
  timeRange: n.timeRange,
1807
1816
  totalOrders: b.length,
1808
- totalRevenue: Object.values(q).reduce(
1817
+ totalRevenue: Object.values(R).reduce(
1809
1818
  (T, A) => T + A,
1810
1819
  0
1811
1820
  )
@@ -1899,7 +1908,7 @@ const Lt = /* @__PURE__ */ new Set([
1899
1908
  function Cr(e) {
1900
1909
  return e === "page" ? Lt : e === "post" ? Bt : Tr;
1901
1910
  }
1902
- function Rt(e, t) {
1911
+ function qt(e, t) {
1903
1912
  return xr.has(e) && t === "" ? null : t;
1904
1913
  }
1905
1914
  function Ne(e, t) {
@@ -1919,11 +1928,11 @@ function Sr(e, t) {
1919
1928
  throw new Error(
1920
1929
  `Field "${o}" cannot be updated for ${t.contentType} content.`
1921
1930
  );
1922
- o === "status" && Ne(t.contentType, a), r[o] = Rt(o, a);
1931
+ o === "status" && Ne(t.contentType, a), r[o] = qt(o, a);
1923
1932
  }
1924
1933
  return r;
1925
1934
  }
1926
- async function qt(e, t) {
1935
+ async function Rt(e, t) {
1927
1936
  const n = me.parse(e), r = C(t), o = V(t), a = Te(o), s = Sr(n.fields, o), l = Object.keys(s);
1928
1937
  if (l.length === 0)
1929
1938
  throw new Error("update_current_cms_fields requires at least one supported field.");
@@ -2241,7 +2250,7 @@ async function zt(e, t) {
2241
2250
  };
2242
2251
  }
2243
2252
  async function Ve(e, t) {
2244
- const n = _e.parse(e), r = C(t), o = Re(t), a = await Ce(r, n.languageCode), s = R(n.slug || n.title), l = Se(n.blocks, n.contactEmail, n.title, t), u = await De({
2253
+ const n = _e.parse(e), r = C(t), o = qe(t), a = await Ce(r, n.languageCode), s = q(n.slug || n.title), l = Se(n.blocks, n.contactEmail, n.title, t), u = await De({
2245
2254
  contentType: "page",
2246
2255
  languageId: a.id,
2247
2256
  slug: s,
@@ -2287,7 +2296,7 @@ async function Ve(e, t) {
2287
2296
  });
2288
2297
  if (m)
2289
2298
  return m;
2290
- const h = d.translationGroupId || qe(), p = await Z(
2299
+ const h = d.translationGroupId || Re(), p = await Z(
2291
2300
  c.item.feature_image_id,
2292
2301
  t,
2293
2302
  n.title
@@ -2327,7 +2336,7 @@ async function Ve(e, t) {
2327
2336
  };
2328
2337
  }
2329
2338
  async function Je(e, t) {
2330
- const n = be.parse(e), r = C(t), o = Re(t), a = await Ce(r, n.languageCode), s = R(n.slug || n.title), l = Se(n.blocks, void 0, void 0, t), u = await De({
2339
+ const n = be.parse(e), r = C(t), o = qe(t), a = await Ce(r, n.languageCode), s = q(n.slug || n.title), l = Se(n.blocks, void 0, void 0, t), u = await De({
2331
2340
  contentType: "post",
2332
2341
  languageId: a.id,
2333
2342
  slug: s,
@@ -2377,7 +2386,7 @@ async function Je(e, t) {
2377
2386
  });
2378
2387
  if (h)
2379
2388
  return h;
2380
- const p = d.translationGroupId || qe(), g = await Z(
2389
+ const p = d.translationGroupId || Re(), g = await Z(
2381
2390
  m.item.feature_image_id,
2382
2391
  t,
2383
2392
  n.title
@@ -2417,7 +2426,7 @@ async function Je(e, t) {
2417
2426
  };
2418
2427
  }
2419
2428
  function vr(e, t) {
2420
- return (t || R(e) || "product").replace(/-/g, "").slice(0, 24).toUpperCase();
2429
+ return (t || q(e) || "product").replace(/-/g, "").slice(0, 24).toUpperCase();
2421
2430
  }
2422
2431
  function Gt(e) {
2423
2432
  if (e == null)
@@ -2448,7 +2457,7 @@ function Er(e) {
2448
2457
  return t(r) ? r : void 0;
2449
2458
  }
2450
2459
  async function Kt(e, t) {
2451
- const n = ke.parse(e), r = C(t), o = await Ce(r, n.languageCode), a = R(n.slug || n.title), s = Se(n.blocks, void 0, void 0, t), l = await De({
2460
+ const n = ke.parse(e), r = C(t), o = await Ce(r, n.languageCode), a = q(n.slug || n.title), s = Se(n.blocks, void 0, void 0, t), l = await De({
2452
2461
  contentType: "product",
2453
2462
  languageId: o.id,
2454
2463
  slug: a,
@@ -2577,7 +2586,7 @@ async function Pr(e, t, n) {
2577
2586
  }
2578
2587
  if (e === "prices" || e === "sale_prices") {
2579
2588
  const r = await nt(n);
2580
- return { [e]: qn(t, r) };
2589
+ return { [e]: Rn(t, r) };
2581
2590
  }
2582
2591
  return e === "description_json" ? { description_json: Gt(t) } : { [e]: t };
2583
2592
  }
@@ -2607,7 +2616,7 @@ function Nr(e, t) {
2607
2616
  return a === "status" && Ne(t.contentType, r), {
2608
2617
  field: a,
2609
2618
  payload: {
2610
- [a]: Rt(a, r)
2619
+ [a]: qt(a, r)
2611
2620
  }
2612
2621
  };
2613
2622
  }
@@ -2884,7 +2893,7 @@ async function st(e, t) {
2884
2893
  case "insert_content_block":
2885
2894
  return Dt(e.input, t);
2886
2895
  case "update_current_cms_fields":
2887
- return qt(e.input, t);
2896
+ return Rt(e.input, t);
2888
2897
  case "update_footer":
2889
2898
  return Ft(e.input, t);
2890
2899
  case "update_navigation_bar":
@@ -2917,7 +2926,7 @@ function Fr(e, t, n) {
2917
2926
  if (r.entityId !== void 0)
2918
2927
  return e;
2919
2928
  const o = r.slug ? t.get(
2920
- `${r.contentType || "product"}:${R(r.slug)}`
2929
+ `${r.contentType || "product"}:${q(r.slug)}`
2921
2930
  ) : n;
2922
2931
  return o ? {
2923
2932
  ...e,
@@ -2934,14 +2943,14 @@ async function jr(e, t) {
2934
2943
  (p) => p.tool === "create_cms_page" || p.tool === "create_cms_post" || p.tool === "create_cms_product"
2935
2944
  ).map((p) => {
2936
2945
  const g = p.input;
2937
- return `${lt(p.tool)}:${R(g.slug || g.title || "")}`;
2946
+ return `${lt(p.tool)}:${q(g.slug || g.title || "")}`;
2938
2947
  })
2939
2948
  ), o = (p) => {
2940
2949
  if (p.tool !== "set_content_images")
2941
2950
  return !1;
2942
2951
  const g = p.input;
2943
2952
  return g.slug ? r.has(
2944
- `${g.contentType || "product"}:${R(g.slug)}`
2953
+ `${g.contentType || "product"}:${q(g.slug)}`
2945
2954
  ) : r.size > 0;
2946
2955
  };
2947
2956
  if (!t?.skipConfirmation) {
@@ -3066,7 +3075,7 @@ function ue(e, t) {
3066
3075
  return null;
3067
3076
  }
3068
3077
  }
3069
- function Rr(e) {
3078
+ function qr(e) {
3070
3079
  let t = null;
3071
3080
  for (const n of e.split(",")) {
3072
3081
  const r = n.trim().split(/\s+/), o = r[0];
@@ -3083,7 +3092,7 @@ function F(e, t) {
3083
3092
  );
3084
3093
  return n ? n[1] ?? n[2] ?? n[3] ?? null : null;
3085
3094
  }
3086
- function qr(e, t) {
3095
+ function Rr(e, t) {
3087
3096
  const n = [], r = [], o = (l, u) => {
3088
3097
  if (typeof l == "string") {
3089
3098
  const d = ue(l, t);
@@ -3144,7 +3153,7 @@ function Mr(e, t) {
3144
3153
  return n;
3145
3154
  }
3146
3155
  function Dr(e, t) {
3147
- const n = [...qr(e, t)], r = [
3156
+ const n = [...Rr(e, t)], r = [
3148
3157
  /<meta\b[^>]*\b(?:property|name)\s*=\s*["'](?:og:image:secure_url|og:image:url|og:image)["'][^>]*>/gi,
3149
3158
  /<meta\b[^>]*\b(?:property|name)\s*=\s*["'](?:twitter:image:src|twitter:image)["'][^>]*>/gi,
3150
3159
  /<meta\b[^>]*\bitemprop\s*=\s*["']image["'][^>]*>/gi,
@@ -3161,7 +3170,7 @@ function Dr(e, t) {
3161
3170
  const o = [];
3162
3171
  for (const c of e.matchAll(/<img\b[^>]*>/gi)) {
3163
3172
  const m = c[0], h = F(m, "srcset") || F(m, "data-srcset"), p = [
3164
- h ? Rr(h) : null,
3173
+ h ? qr(h) : null,
3165
3174
  F(m, "src"),
3166
3175
  F(m, "data-src"),
3167
3176
  F(m, "data-original"),
@@ -3496,7 +3505,7 @@ function Xr(e, t) {
3496
3505
  return `/api/draft/start?path=${encodeURIComponent(n)}`;
3497
3506
  }
3498
3507
  async function Qr(e, t) {
3499
- const n = nn.parse(e), r = C(t), o = Re(t), a = await te(n, t);
3508
+ const n = nn.parse(e), r = C(t), o = qe(t), a = await te(n, t);
3500
3509
  if (a.contentType === "product")
3501
3510
  throw new Error(
3502
3511
  "rewrite_page_draft supports pages and posts only. Products use description_json, not page blocks."
@@ -3640,7 +3649,7 @@ async function eo(e, t) {
3640
3649
  blockType: T.block_type,
3641
3650
  content: Fe(z(T.content), p, g),
3642
3651
  order: A
3643
- })), k = await Ce(o, n.targetLanguageCode), y = String(u.title || ""), w = n.title || Oe(y, p, g) || y || "Untitled", b = (T) => typeof T == "string" && T.trim() ? Oe(T, p, g) : void 0, I = R(w) || u.slug || "translated-page", x = {
3652
+ })), k = await Ce(o, n.targetLanguageCode), y = String(u.title || ""), w = n.title || Oe(y, p, g) || y || "Untitled", b = (T) => typeof T == "string" && T.trim() ? Oe(T, p, g) : void 0, I = q(w) || u.slug || "translated-page", x = {
3644
3653
  blocks: f,
3645
3654
  feature_image_id: u.feature_image_id ?? void 0,
3646
3655
  languageCode: k.code,
@@ -3682,8 +3691,8 @@ async function eo(e, t) {
3682
3691
  });
3683
3692
  if (L)
3684
3693
  return L;
3685
- const q = { ...t, skipConfirmation: !0 };
3686
- return { ...r.contentType === "post" ? await Je(E, q) : await Ve(E, q), isTranslation: !0, languageCode: k.code };
3694
+ const R = { ...t, skipConfirmation: !0 };
3695
+ return { ...r.contentType === "post" ? await Je(E, R) : await Ve(E, R), isTranslation: !0, languageCode: k.code };
3687
3696
  }
3688
3697
  async function on(e, t) {
3689
3698
  const n = he.parse(e), r = n.entityId !== void 0 || !!n.slug || !!n.title, o = C(t);
@@ -3892,7 +3901,7 @@ function co(e) {
3892
3901
  }),
3893
3902
  update_current_cms_fields: S({
3894
3903
  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.",
3895
- execute: (t) => qt(t, e),
3904
+ execute: (t) => Rt(t, e),
3896
3905
  inputSchema: me,
3897
3906
  strict: !0
3898
3907
  }),
@@ -3950,7 +3959,7 @@ export {
3950
3959
  eo as executeTranslatePage,
3951
3960
  Ht as executeUpdateCmsItemField,
3952
3961
  Mt as executeUpdateContentBlock,
3953
- qt as executeUpdateCurrentCmsFields,
3962
+ Rt as executeUpdateCurrentCmsFields,
3954
3963
  Ft as executeUpdateFooter,
3955
3964
  Ot as executeUpdateNavigationBar,
3956
3965
  zt as executeUpdateSectionColumnBlock,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nextblock-cms/cortex",
3
- "version": "0.14.2",
3
+ "version": "0.14.3",
4
4
  "publishConfig": {
5
5
  "access": "public"
6
6
  },
@@ -27,9 +27,9 @@
27
27
  },
28
28
  "dependencies": {
29
29
  "@ai-sdk/openai-compatible": "^2.0.42",
30
- "@nextblock-cms/db": "^0.14.2",
31
- "@nextblock-cms/ecommerce": "npm:@nextblock-cms/ecom@^0.14.2",
32
- "@nextblock-cms/utils": "^0.14.2",
30
+ "@nextblock-cms/db": "^0.14.3",
31
+ "@nextblock-cms/ecommerce": "npm:@nextblock-cms/ecom@^0.14.3",
32
+ "@nextblock-cms/utils": "^0.14.3",
33
33
  "ai": "^6.0.170",
34
34
  "zod": "^4.3.6"
35
35
  },