@nextblock-cms/cortex 0.18.5 → 0.18.7

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 S=require("ai"),En=require("./ai-global-agent-db-tools.cjs.js"),$n=require("./ai-global-agent-custom-block-tools.cjs.js"),zn=require("./ai-global-agent-content-ops-tools.cjs.js"),An=require("./ai-global-agent-theming-tools.cjs.js"),Pn=require("./ai-global-agent-site-tools.cjs.js"),jt=require("./editor-document-from-html.cjs.js");require("./zod-config.cjs.js");const R=require("./block-content-schemas.cjs.js"),s=require("zod");async function W(e,t,n){if(e?.recordRevision)try{return await e.recordRevision({contentType:t,entityId:n,phase:"capture"})}catch(r){console.error("Cortex AI: failed to capture revision baseline",r);return}}async function G(e,t,n,r){if(!(!e?.recordRevision||r===void 0))try{await e.recordRevision({baseline:r,contentType:t,entityId:n,phase:"commit"})}catch(o){console.error("Cortex AI: failed to record revision",o)}}const Nn=1e4,Un={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"},Gt=s.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."),At=s.z.strictObject({label:s.z.string().trim().min(1).max(120),target:s.z.enum(["_self","_blank"]).optional(),url:Gt}),Xe=At.extend({children:s.z.array(At).max(20).optional()}),On=s.z.strictObject({label:s.z.string().trim().min(1).max(120).optional(),url:Gt.optional()}).refine(e=>!!(e.label||e.url),{message:"Navigation item match requires label or url."}),ie=s.z.strictObject({items:s.z.array(Xe).min(1).max(30),languageCode:s.z.string().trim().min(2).max(80).default("en").describe('Locale code or language name, for example "en", "fr", "English", or "French".'),match:On.optional().describe('For mode "update", identifies the existing navigation item to update.'),mode:s.z.enum(["append","replace","update"]).default("append")}),ae=s.z.strictObject({copyright:s.z.record(s.z.string().trim().min(2).max(12),s.z.string().trim().min(1).max(500)).optional(),languageCode:s.z.string().trim().min(2).max(80).default("en").describe('Locale code or language name, for example "en", "fr", "English", or "French".'),links:s.z.array(Xe).min(1).max(30).optional()}),Ae=s.z.strictObject({limit:s.z.number().int().min(1).max(8).default(4),query:s.z.string().trim().min(2).max(300)}),Qe=s.z.object({currency:s.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:s.z.string().describe("The analytical question about orders, products, or revenue."),reportType:s.z.enum(["revenue","orders","products","general"]).optional().default("general").describe("The focus area of the statistical report."),timeRange:s.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.")}),Pe=s.z.strictObject({contentType:s.z.enum(["page","post","product"]),currentEditor:s.z.strictObject({blockId:s.z.union([s.z.number().int().positive(),s.z.string().trim().min(1).max(120)]).nullable().optional(),blockType:s.z.string().trim().min(1).max(80).nullable().optional(),field:s.z.string().trim().min(1).max(120).nullable().optional()}).optional(),entityId:s.z.union([s.z.number().int().positive(),s.z.string().trim().min(1).max(120)]),languageId:s.z.number().int().positive().nullable().optional(),slug:s.z.string().trim().min(1).max(300).nullable().optional(),title:s.z.string().trim().min(1).max(300).nullable().optional(),translationGroupId:s.z.string().trim().min(1).max(120).nullable().optional()}),Fn=s.z.enum(["page","post","product"]),J=s.z.strictObject({contentType:Fn.optional(),entityId:s.z.union([s.z.number().int().positive(),s.z.string().trim().min(1).max(120)]).optional(),slug:s.z.string().trim().min(1).max(300).optional(),title:s.z.string().trim().min(1).max(300).optional()}),se=J.optional().describe("Names the page, post, or product to act on when no CMS editor is open (MCP clients). Pass contentType plus one of slug, entityId, or title. Ignored when an editor is already open."),Ze=s.z.strictObject({cmsTarget:se,includeBlockContent:s.z.boolean().default(!1),includeBlocks:s.z.boolean().default(!0)}),ce=s.z.strictObject({cmsTarget:se,fields:s.z.strictObject({description_json:s.z.unknown().optional(),excerpt:s.z.string().max(2e3).nullable().optional(),feature_image_id:s.z.string().trim().min(1).max(2048).nullable().optional().describe("The feature image. Accepts EITHER an existing media library id OR an external https:// image URL, which is downloaded into the media library automatically — so pass `mainImage` from fetch_url_content or a `url` from search_stock_photos straight in. Despite the name, you do not need to import the image yourself. Every page and post should get one: it is the social/OG preview image and the card thumbnail in post listings."),label:s.z.string().max(120).nullable().optional(),meta_description:s.z.string().max(500).nullable().optional(),meta_title:s.z.string().max(160).nullable().optional(),published_at:s.z.string().max(80).nullable().optional(),short_description:s.z.string().max(2e3).nullable().optional(),slug:s.z.string().trim().min(1).max(300).optional(),status:s.z.enum(["draft","published","active","archived"]).optional(),subtitle:s.z.string().max(300).nullable().optional(),title:s.z.string().trim().min(1).max(300).optional()}).partial()}),Ne=s.z.string().trim().min(1).max(120).describe(`A built-in block type (${R.availableCortexAiBlockTypes.join(", ")}) or the slug of a custom block definition from list_custom_blocks, whose content is the flat { field_key: value } map its fields describe.`),le=s.z.strictObject({blockId:s.z.number().int().positive(),blockType:Ne.optional(),cmsTarget:se,content:s.z.record(s.z.string(),s.z.unknown())}),ue=s.z.strictObject({blockIndex:s.z.number().int().min(0),blockType:Ne.optional(),cmsTarget:se,columnIndex:s.z.number().int().min(0),content:s.z.record(s.z.string(),s.z.unknown()),parentBlockId:s.z.number().int().positive()}),de=s.z.strictObject({blockType:Ne,content:s.z.record(s.z.string(),s.z.unknown()).describe("The block content, matching that block type's schema. For a `text` block, `html_content` is rendered as real HTML and may include an inline <style> and an inline <script> — so you can add scroll reveals, counters, hover effects, and other motion directly in a block. Inline scripts are stamped with the site CSP nonce automatically. Three rules. (1) THE PAGE IS REACT-HYDRATED. Do not change the text, classes, or attributes of surrounding server-rendered markup: React reconciles afterwards and reverts your change (a counter animates then snaps back) or logs a hydration mismatch. Waiting for `load` is NOT sufficient — hydration can still be in flight. Safe patterns instead: animate with the Web Animations API (el.animate() touches no attribute); append your own new elements and style those; use CSS for anything CSS can do; and if you must set text, render the FINAL value server-side and only animate toward it once the element scrolls into view. (2) `on*` attributes (onclick, onload, …) are stripped, so bind with addEventListener. (3) The script runs once per full page load, not on client-side navigation — for site-wide behaviour use manage_site_script."),order:s.z.number().int().min(0).optional()}),pe=J.extend({images:s.z.array(s.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).")}),me=J.extend({anchorBlockId:s.z.number().int().positive().optional(),anchorBlockType:Ne.optional(),block:de,position:s.z.enum(["before","after","start","end"]).default("end")}),ge=s.z.strictObject({blocks:s.z.array(de).max(20).optional(),contactEmail:s.z.string().email().optional(),feature_image_id:s.z.string().trim().min(1).max(2048).nullable().optional().describe("The feature image. Accepts EITHER an existing media library id OR an external https:// image URL, which is downloaded into the media library automatically — so pass `mainImage` from fetch_url_content or a `url` from search_stock_photos straight in. Despite the name, you do not need to import the image yourself. Every page and post should get one: it is the social/OG preview image and the card thumbnail in post listings."),languageCode:s.z.string().trim().min(2).max(80).optional(),meta_description:s.z.string().max(500).nullable().optional(),meta_title:s.z.string().max(160).nullable().optional(),slug:s.z.string().trim().min(1).max(300).optional(),status:s.z.enum(["draft","published","archived"]).default("draft"),title:s.z.string().trim().min(1).max(300),translationGroupId:s.z.string().trim().min(1).max(120).optional()}),fe=s.z.strictObject({blocks:s.z.array(de).max(20).optional(),excerpt:s.z.string().max(2e3).nullable().optional(),feature_image_id:s.z.string().trim().min(1).max(2048).nullable().optional().describe("The feature image. Accepts EITHER an existing media library id OR an external https:// image URL, which is downloaded into the media library automatically — so pass `mainImage` from fetch_url_content or a `url` from search_stock_photos straight in. Despite the name, you do not need to import the image yourself. Every page and post should get one: it is the social/OG preview image and the card thumbnail in post listings."),label:s.z.string().max(120).nullable().optional(),languageCode:s.z.string().trim().min(2).max(80).optional(),meta_description:s.z.string().max(500).nullable().optional(),meta_title:s.z.string().max(160).nullable().optional(),published_at:s.z.string().max(80).nullable().optional(),slug:s.z.string().trim().min(1).max(300).optional(),status:s.z.enum(["draft","published","archived"]).default("draft"),subtitle:s.z.string().max(300).nullable().optional(),title:s.z.string().trim().min(1).max(300),translationGroupId:s.z.string().trim().min(1).max(120).optional()}),he=s.z.strictObject({blocks:s.z.array(de).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:s.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:s.z.unknown().optional(),freemius_plan_id:s.z.string().optional(),freemius_product_id:s.z.string().optional(),images:s.z.array(s.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:s.z.boolean().default(!0),languageCode:s.z.string().trim().min(2).max(80).optional(),meta_description:s.z.string().max(500).nullable().optional(),meta_title:s.z.string().max(160).nullable().optional(),payment_provider:s.z.enum(["stripe","freemius"]).default("stripe"),price:s.z.number().min(0).default(0),prices:s.z.record(s.z.string(),s.z.number().min(0)).optional(),product_type:s.z.enum(["physical","digital"]).default("physical"),sale_price:s.z.number().min(0).nullable().optional(),sale_prices:s.z.record(s.z.string(),s.z.number().min(0).nullable()).optional(),short_description:s.z.string().max(2e3).nullable().optional(),sku:s.z.string().trim().min(1).max(120).optional(),slug:s.z.string().trim().min(1).max(300).optional(),status:s.z.enum(["draft","active","archived"]).default("draft"),stock:s.z.number().int().min(0).default(0),title:s.z.string().trim().min(1).max(300),trial_period_days:s.z.number().int().min(0).default(0),trial_requires_payment_method:s.z.boolean().default(!1),translationGroupId:s.z.string().trim().min(1).max(120).optional(),upc:s.z.string().max(120).nullable().optional()}),ye=J.extend({currencyCode:s.z.string().trim().min(3).max(3).optional(),endsAt:s.z.string().max(80).nullable().optional(),field:s.z.string().trim().min(1).max(120),startsAt:s.z.string().max(80).nullable().optional(),value:s.z.unknown()}),et=J,be=J,Kt=s.z.discriminatedUnion("tool",[s.z.strictObject({input:ge,tool:s.z.literal("create_cms_page")}),s.z.strictObject({input:fe,tool:s.z.literal("create_cms_post")}),s.z.strictObject({input:he,tool:s.z.literal("create_cms_product")}),s.z.strictObject({input:be,tool:s.z.literal("delete_cms_item")}),s.z.strictObject({input:ye,tool:s.z.literal("update_cms_item_field")}),s.z.strictObject({input:le,tool:s.z.literal("update_content_block")}),s.z.strictObject({input:me,tool:s.z.literal("insert_content_block")}),s.z.strictObject({input:ce,tool:s.z.literal("update_current_cms_fields")}),s.z.strictObject({input:ae,tool:s.z.literal("update_footer")}),s.z.strictObject({input:ie,tool:s.z.literal("update_navigation_bar")}),s.z.strictObject({input:ue,tool:s.z.literal("update_section_column_block")}),s.z.strictObject({input:pe,tool:s.z.literal("set_content_images")})]),Bn=s.z.union([ge.extend({tool:s.z.literal("create_cms_page")}).transform(({tool:e,...t})=>({input:t,tool:e})),fe.extend({tool:s.z.literal("create_cms_post")}).transform(({tool:e,...t})=>({input:t,tool:e})),he.extend({tool:s.z.literal("create_cms_product")}).transform(({tool:e,...t})=>({input:t,tool:e})),be.extend({tool:s.z.literal("delete_cms_item")}).transform(({tool:e,...t})=>({input:t,tool:e})),ye.extend({tool:s.z.literal("update_cms_item_field")}).transform(({tool:e,...t})=>({input:t,tool:e})),le.extend({tool:s.z.literal("update_content_block")}).transform(({tool:e,...t})=>({input:t,tool:e})),me.extend({tool:s.z.literal("insert_content_block")}).transform(({tool:e,...t})=>({input:t,tool:e})),ce.extend({tool:s.z.literal("update_current_cms_fields")}).transform(({tool:e,...t})=>({input:t,tool:e})),ae.extend({tool:s.z.literal("update_footer")}).transform(({tool:e,...t})=>({input:t,tool:e})),ie.extend({tool:s.z.literal("update_navigation_bar")}).transform(({tool:e,...t})=>({input:t,tool:e})),ue.extend({tool:s.z.literal("update_section_column_block")}).transform(({tool:e,...t})=>({input:t,tool:e})),pe.extend({tool:s.z.literal("set_content_images")}).transform(({tool:e,...t})=>({input:t,tool:e}))]),Ln=s.z.string().transform((e,t)=>{const n=jn(e);return n.success?n.action:(t.addIssue({code:"custom",message:n.message}),s.z.NEVER)}),Rn=s.z.union([Kt,Bn,Ln]),tt=s.z.strictObject({actions:s.z.array(Rn).min(1).max(8),summary:s.z.string().trim().min(1).max(500).optional()});function qn(e){const t=[];let n="",r=0,o=null,i=!1;for(const a of e){if(o){n+=a,i?i=!1:a==="\\"?i=!0:a===o&&(o=null);continue}if(a==='"'||a==="'"){o=a,n+=a;continue}if(a==="["||a==="{"||a==="("){r++,n+=a;continue}if(a==="]"||a==="}"||a===")"){r=Math.max(0,r-1),n+=a;continue}if(a===","&&r===0){n.trim()&&t.push(n.trim()),n="";continue}n+=a}return n.trim()&&t.push(n.trim()),t}function Pt(e){let t="";for(let n=0;n<e.length;n++){const r=e[n];if(r!=="'"){t+=r;continue}let o="",i=!1;for(n++;n<e.length;n++){const a=e[n];if(i){o+=a,i=!1;continue}if(a==="\\"){i=!0;continue}if(a==="'")break;o+=a}t+=JSON.stringify(o)}return t.replace(/\bTrue\b/g,"true").replace(/\bFalse\b/g,"false").replace(/\bNone\b/g,"null")}function Dn(e){const t=e.trim();return t.startsWith("'")&&t.endsWith("'")||t.startsWith('"')&&t.endsWith('"')||t.startsWith("[")||t.startsWith("{")?JSON.parse(Pt(t)):/^-?\d+(?:\.\d+)?$/.test(t)?Number(t):t==="true"||t==="True"?!0:t==="false"||t==="False"?!1:t==="null"||t==="None"?null:t}function Mn(e){const t={};for(const n of qn(e)){const r=n.indexOf("=");if(r<=0)throw new Error(`Expected key=value argument, received "${n}".`);const o=n.slice(0,r).trim();if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(o))throw new Error(`Invalid argument name "${o}".`);t[o]=Dn(n.slice(r+1))}return t}function jn(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 r=n[1];let o;try{o=Mn(n[2])}catch(c){return{message:c instanceof Error?c.message:"Could not parse action-plan command arguments.",success:!1}}const i={input:o,tool:r},a=Kt.safeParse(i);return a.success?{action:a.data,success:!0}:{message:`Invalid action-plan command "${r}": ${a.error.issues.map(c=>c.message).join("; ")}`,success:!1}}function Gn(e){return e.normalize("NFD").replace(/[\u0300-\u036f]/g,"").toLowerCase().replace(/\s+/g," ").trim()}function ke(e,t){return t.some(n=>e.includes(n))}function Kn(e){const t=Gn(e),n=ke(t,["add ","insert ","put ","create "]),r=ke(t,["title","heading","description","intro","copy","paragraph"]),o=t.includes("form")&&ke(t,["above","before"]),i=t.includes("contact page")||t.includes("contact pages")||t.includes("contact us")||t.includes("contactez-nous"),a=t.includes("english")&&ke(t,["french","francais","francaise"]);return!n||!r||!o||!i||!a?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."}}function Nt(){return s.z.object({content:s.z.array(s.z.any()).optional(),type:s.z.literal("doc")})}function nt(){try{const{revalidatePath:e}=require("next/cache");return e}catch{return null}}function x(e){if(!e?.supabase)throw new Error("A Supabase service client is required to execute Cortex AI global tools.");return e.supabase}function Hn(e,t,n){let r;const o=new Promise(i=>{r=setTimeout(()=>i(n()),t)});return Promise.race([e.finally(()=>{r&&clearTimeout(r)}),o])}function Vn(e){const t=Pe.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 Ue(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 Ht(e){const t=String(e.entityId||"").trim();if(!t)throw new Error(`Current ${e.contentType} id is missing.`);return t}function M(e){return e.contentType==="product"?Ht(e):Ue(e)}const Wn=/^https?:\/\//i,Jn=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;async function Q(e,t,n){if(typeof e!="string")return null;const r=e.trim();if(!r)return null;if(!Wn.test(r)){if(Jn.test(r))return r;throw new Error(`"${r}" is not a usable image reference — provide an https:// image URL or a media library id.`)}const o=t?.importExternalImage;if(!o)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 i=await o({altText:n,url:r});if("error"in i)throw new Error(`I could not import the image from that URL: ${i.error}`);return i.id}async function Vt(e,t,n){const r=[];for(let o=0;o<e.length;o+=1){const i=await Q(e[o],t,`${n} image ${o+1}`);i&&r.push(i)}return r}async function Yn(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: ${b(n)}`);if(t.length>0){const{error:r}=await e.supabase.from("product_media").insert(t.map((o,i)=>({media_id:o,product_id:e.productId,sort_order:i})));if(r)throw new Error(`Could not save the product images: ${b(r)}`)}return t}async function Oe(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 r=e.patch({blocks:Array.isArray(t.blocks)?K(t.blocks):[],meta:z(t.meta)?K(t.meta):{}}),o={updated_at:new Date().toISOString()};if(r.blocks&&(o.blocks=r.blocks),r.meta&&(o.meta=r.meta),Object.keys(o).length===1)return!1;const{error:i}=await e.supabase.from("product_drafts").update(o).eq("id",t.id);if(i)throw new Error(`The product was updated, but its open draft could not be kept in sync: ${b(i)}. Publishing that draft would undo this change — publish or discard it in the product editor first.`);return!0}function Wt(e){return typeof e=="string"?e.trim().replace(/^\/+|\/+$/g,""):""}function Xn(e,t){const n=Wt(t??e.slug);return n?e.contentType==="page"?n==="home"?"/":`/${n}`:e.contentType==="post"?`/article/${n}`:`/product/${n}`:null}function Qn(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 U(e,t,n){const r=e?.revalidatePath??nt();if(!r)return;r(Qn(t));const o=Xn(t,n);o&&r(o),t.contentType==="page"&&o!=="/"&&r("/"),t.contentType==="product"&&r("/cms/products")}function Jt(e){const t=e?.revalidatePath??nt();t&&(t("/","layout"),t("/cms/navigation"))}function b(e){return e?typeof e=="object"&&"message"in e?String(e.message||"Unknown database error."):String(e):"Unknown database error."}async function Zn(){return Promise.resolve().then(()=>require("./ai-global-agent-ecommerce.cjs.js"))}function De(e){return e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?`[${e.map(t=>De(t)).join(",")}]`:`{${Object.keys(e).filter(t=>t!=="temp_id").sort().map(t=>`${JSON.stringify(t)}:${De(e[t])}`).join(",")}}`}function er(e){let t=2166136261;const n=De(e);for(let r=0;r<n.length;r++)t^=n.charCodeAt(r),t=Math.imul(t,16777619);return(t>>>0).toString(16).padStart(8,"0")}function Me(e){return e.replace(/\s+/g," ").trim().toUpperCase()}function tr(e,t,n){return`${Me(`CONFIRM ${e} ${t}`)} #${er(n)}`}function Yt(e){return{confirmationPhrase:tr(e.action,e.subject,e.payload),mutationExecuted:!1,preview:e.preview,requiresConfirmation:!0,success:!0}}function B(e,t){const n=e[t];return typeof n=="string"&&n.trim()?n.trim():null}function V(e,t){const n=Number(e[t]);return Number.isFinite(n)?n:null}function N(e,t,n=`${t}s`){return`${e} ${e===1?t:n}`}function nr(e,t){const n=B(t,"summary");if(n)return n;const r=B(t,"title"),o=B(t,"slug"),i=B(t,"status"),a=B(t,"contentType"),c=B(t,"field"),u=B(t,"mode"),d=B(t,"languageCode"),l=V(t,"blockCount"),p=V(t,"itemCount"),h=V(t,"affectedCount");if(e==="create_cms_page"||e==="create_cms_post")return`Create ${i||"draft"} ${e==="create_cms_page"?"page":"post"} "${r||o||"Untitled"}"${o?` at slug "${o}"`:""}${l!==null?` with ${N(l,"content block")}`:""}.`;if(e==="create_cms_product"){const m=V(t,"imageCount"),f=V(t,"blockCount"),g=[m?N(m,"image"):null,f?N(f,"description block"):V(t,"descriptionLength")?"a full description":null].filter(Boolean);return`Create ${i||"draft"} product "${r||o||"Untitled"}"${o?` at slug "${o}"`:""}${g.length?` with ${g.join(" and ")}`:""}.`}if(e==="update_cms_item_field")return`Update ${c||"one field"} on the ${a||"CMS item"} "${r||o||"selected item"}".`;if(e==="update_navigation_bar")return`${u==="append"?"Add":u==="update"?"Update":"Replace"} ${p!==null?N(p,"navigation item"):"navigation items"} in the ${d||"selected"} header navigation.`;if(e==="update_footer"){const m=V(t,"linkCount");return`Update the ${d||"selected"} footer${m!==null?` with ${N(m,"link")}`:""}.`}return e==="update_content_block"?`Update the selected ${B(t,"blockType")||"content"} block.`:e==="insert_content_block"?`Insert ${B(t,"blockType")||"content"} block on the ${a||"CMS item"} "${r||o||"selected item"}".`:e==="update_section_column_block"?`Update the selected nested ${B(t,"nestedBlockType")||"section"} block.`:e==="delete_cms_item"||e==="prepare_delete_cms_item"?`Delete ${h!==null?N(h,a||"CMS item"):`the selected ${a||"CMS item"}`}${r||o?` for "${r||o}"`:""}.`:"Complete the requested CMS change."}function P(e){if(e.context?.skipConfirmation)return null;const t=Yt(e),n=Me(e.context?.latestUserMessage||""),r=Me(t.confirmationPhrase);return n.includes(r)?null:t}function rt(e){const t=e?.actorUserId;if(!t)throw new Error("A confirmed CMS mutation requires an authenticated admin actor.");return t}function ot(){return globalThis.crypto?.randomUUID?.()||`id-${Date.now()}-${Math.random().toString(36).slice(2)}`}function O(e){return e.normalize("NFD").replace(new RegExp("\\p{Diacritic}","gu"),"").toLowerCase().trim().replace(/\s+/g,"-").replace(/[^a-z0-9-]/g,"").replace(/-+/g,"-").replace(/^-|-$/g,"").slice(0,300)}function it(e){return(e||"USD").trim().toUpperCase()}const rr=new Set(["BIF","CLP","DJF","GNF","JPY","KMF","KRW","MGA","PYG","RWF","UGX","VND","VUV","XAF","XOF","XPF"]);function or(e){return rr.has(it(e))?0:2}function ve(e,t){return Math.round(e*10**or(t))}function ir(e,t){return!e||typeof e!="object"||Array.isArray(e)?{}:Object.entries(e).reduce((n,[r,o])=>{if(typeof o=="number"&&Number.isFinite(o)&&o>=0){const i=it(r||t);n[i]=ve(o,i)}return n},{})}function _e(e,t){if(!z(e))throw new Error(`${t} content must be a JSON object.`);return JSON.parse(JSON.stringify(e))}function K(e){return JSON.parse(JSON.stringify(e))}function z(e){return!!(e&&typeof e=="object"&&!Array.isArray(e))}function je(e,t){const n=K(e);for(const[r,o]of Object.entries(t))if(o!==void 0){if(z(o)&&z(n[r])){n[r]=je(n[r],o);continue}n[r]=K(o)}return n}function Xt(e,t){if(t.contentType==="product"){if(String(e.product_id??"")!==String(Ht(t)))throw new Error(`Block ${e.id} does not belong to the current product being edited.`);return}const n=Ue(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 at(e,t){return t?.customBlockDefinitions?.find(n=>n.slug===e)??null}function Ge(e,t=new Set,n=0){if(n>12||!e)return t;if(typeof e=="string")return t.add(e),t;if(Array.isArray(e)){for(const r of e)Ge(r,t,n+1);return t}if(typeof e=="object")for(const[r,o]of Object.entries(e))(r==="block_type"||r==="blockType"||r==="anchorBlockType")&&typeof o=="string"?t.add(o):o&&typeof o=="object"&&Ge(o,t,n+1);return t}async function H(e,t){return e?.customBlockDefinitions||!e?.supabase||![...Ge(t)].some(o=>!R.isValidBlockType(o))?e:{...e,customBlockDefinitions:await R.loadCustomBlockDefinitions(e.supabase)}}function oe(e,t,n){const r=typeof e=="string"?e.trim():"";if(R.isValidBlockType(r)||r&&at(r,n))return r;throw new Error(`${t} has unsupported block type "${r||"unknown"}". Built-in types: ${R.availableCortexAiBlockTypes.join(", ")}; a custom block must use a slug returned by list_custom_blocks.`)}function Qt(e,t,n){if(e&&e!==t)throw new Error(`${n} is a "${t}" block. Refusing to update it as "${e}".`)}function j(e,t,n,r){if(!R.isValidBlockType(e)){const i=at(e,r);if(!i)throw new Error(`${n} references custom block "${e}", which does not exist.`);const a=R.validateCustomBlockInstanceContent(i,t);if(!a.isValid)throw new Error(`${n} content is invalid for custom block "${e}": ${a.errors.join("; ")}`);return}const o=R.validateCortexBlockContent(e,t,r);if(!o.isValid)throw new Error(`${n} content is invalid for block type "${e}": ${o.errors.join("; ")}`)}function Zt(e){return e==="section"}function ar(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.form_key=="string"||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 Se(e){return`ai-${e}-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}function Ke(e,t,n){if(!z(e))throw new Error(`${t} must be a JSON object.`);const r=e.block_type??e.blockType,o=oe(r,t,n);if(Zt(o))throw new Error(`${t} cannot be a nested ${o} block.`);const i=rn(o,_e(e.content,t),t,n),a=e.temp_id??e.tempId,c=typeof a=="string"&&a.trim()?a:Se(o);return{block_type:o,content:i,temp_id:c}}function sr(e,t){const n=[];if("append_block"in e&&n.push(Ke(e.append_block,"Nested block to append",t)),"append_blocks"in e){const r=e.append_blocks;if(!Array.isArray(r))throw new Error("append_blocks must be an array of nested block objects.");r.forEach((o,i)=>{n.push(Ke(o,`Nested block to append ${i}`,t))})}return n}function cr(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=ar(e);if(!n)return null;const r=_e(e,`Nested ${n} block`);return j(n,r,`Nested ${n} block`,t),{block_type:n,content:r,temp_id:Se(n)}}function lr(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 ur(e,t,n,r){if(!Zt(e))return je(t,n);const o={...n},i=sr(o,r),a=cr(o,r);a&&i.push(a),delete o.append_block,delete o.append_blocks,delete o.append_column_index,delete o.column_index;const c=je(t,o);if(i.length>0){const u=Array.isArray(t.column_blocks)?K(t.column_blocks):[],d=lr(n,u.length),l=u.length>0?u:[[]];for(;l.length<=d;)l.push([]);l[d]=[...l[d]||[],...i],c.column_blocks=l}return c}function dr(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 X(e){return typeof e=="string"?e.trim().toLowerCase():""}function Ut(e){return typeof e=="string"?e.trim().toLowerCase():""}function en(e){return e.reduce((t,n)=>t+1+(n.children?.length||0),0)}function Ce(e){return typeof e=="string"?e.trim().toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g,""):""}async function Z(e,t){const n=t.trim(),r=Ce(n),o=Un[r],{data:i,error:a}=await e.from("languages").select("id, code, name, is_active");if(a)throw new Error(`Failed to load language "${t}": ${b(a)}`);const u=(Array.isArray(i)?i:[]).filter(l=>l.is_active!==!1),d=u.find(l=>{const p=Ce(l.code),h=Ce(l.name);return p===r||p===o||h===r});if(!d?.id||!d?.code){const l=u.map(p=>p.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 Fe(e,t){if(t)return Z(e,t);const{data:n,error:r}=await e.from("languages").select("id, code, name, is_active, is_default");if(r)throw new Error(`Failed to load active languages: ${b(r)}`);const o=(Array.isArray(n)?n:[]).filter(a=>a.is_active!==!1),i=o.find(a=>a.is_default)||o.find(a=>Ce(a.code)==="en")||o[0];if(!i?.id||!i?.code)throw new Error("No active CMS language is available for Cortex AI content creation.");return{code:String(i.code),id:Number(i.id)}}async function He(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 r=Array.isArray(t)?t:[],o=r.find(i=>i.is_default)||r[0];return it(o?.code||"USD")}catch{return"USD"}}async function pr(e){const t=e.contentType==="page"?"pages":e.contentType==="post"?"posts":"products";let n="id",r=e.entityId;if(r===void 0&&e.slug&&(n="slug",r=e.slug),r===void 0&&e.title&&(n="title",r=e.title),r===void 0)throw new Error(`A ${e.contentType} target requires an id, slug, title, or current edit context.`);const{data:o,error:i}=await e.supabase.from(t).select("*").eq(n,r);if(i)throw new Error(`Failed to resolve ${e.contentType}: ${b(i)}`);const a=Array.isArray(o)?o:o?[o]:[];if(a.length!==1)throw new Error(a.length===0?`No ${e.contentType} matched ${n} "${String(r)}".`:`Multiple ${e.contentType}s matched ${n} "${String(r)}"; use an exact id.`);return a[0]}async function Y(e,t){const n=Pe.safeParse(t?.pageContext).success?t?.pageContext:null,r=e.contentType||n?.contentType;if(!r)throw new Error("Target contentType is required when no current CMS edit context exists.");const o=e.entityId!==void 0||!!e.slug||!!e.title,i=e.entityId??(o?void 0:n?.entityId),a=e.slug??(o?void 0:n?.slug??void 0),c=e.title??(o?void 0:n?.title??void 0),u=await pr({contentType:r,entityId:i,slug:i===void 0&&a||void 0,supabase:x(t),title:i===void 0&&!a&&c||void 0});return{contentType:r,item:u}}async function ee(e,t){const n=Pe.safeParse(t?.pageContext);if(n.success)return n.data;if(!(e!==void 0&&(e.entityId!==void 0||!!e.slug||!!e.title)))throw new Error("No current CMS page context is available. Open a page, post, or product edit screen, or pass `cmsTarget` naming the item — contentType plus one of slug, entityId, or title.");const o=await Y(e,t),i=o.item;return{contentType:o.contentType,entityId:i.id,slug:typeof i.slug=="string"?i.slug:"",title:typeof i.title=="string"?i.title:""}}async function xe(e){const t=await gr({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:r,error:o}=await e.supabase.from("navigation_items").insert(n).select("id").single();if(o)throw new Error(`Failed to insert ${e.menuKey} navigation item: ${b(o)}`);return Number(r.id)}function mr(e){const t=e.trim();if(!t.startsWith("/")||t.startsWith("//"))return null;const n=t.split("?")[0]?.split("#")[0]||"",r=n==="/"?"home":n.replace(/^\/+|\/+$/g,"");return r&&!r.includes("/")?r:null}async function gr(e){const t=mr(e.item.url);if(!t)return null;const{data:n,error:r}=await e.supabase.from("pages").select("id, slug, translation_group_id, language_id").eq("slug",t).eq("language_id",e.languageId);if(r)throw new Error(`Failed to resolve linked page for navigation item: ${b(r)}`);const o=Array.isArray(n)?n[0]:n;if(!o?.id)return null;let i=ot();if(o.translation_group_id){const{data:a,error:c}=await e.supabase.from("pages").select("id").eq("translation_group_id",o.translation_group_id);if(c)throw new Error(`Failed to inspect linked page translations for navigation item: ${b(c)}`);const u=new Set((Array.isArray(a)?a:[]).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: ${b(l)}`);const p=(Array.isArray(d)?d:[]).find(h=>h.translation_group_id&&u.has(String(h.page_id)));p?.translation_group_id&&(i=p.translation_group_id)}return{navigationTranslationGroupId:i,pageId:Number(o.id)}}async function tn(e){const t=await Z(e.supabase,e.languageCode),{data:n,error:r}=await e.supabase.from("navigation_items").select("id, parent_id").eq("menu_key",e.menuKey).eq("language_id",t.id);if(r)throw new Error(`Failed to inspect existing ${e.menuKey} navigation items: ${b(r)}`);const o=Array.isArray(n)?n:[],i=o.filter(d=>d.parent_id==null).length,a=en(e.items);nn({existingItemCount:o.length,existingTopLevelCount:i,languageCode:t.code,menuKey:e.menuKey,replacementItemCount:a});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: ${b(c)}`);let u=0;for(const[d,l]of e.items.entries()){const p=await xe({item:l,languageId:t.id,menuKey:e.menuKey,order:d,supabase:e.supabase});u++;for(const[h,m]of(l.children??[]).entries())await xe({item:m,languageId:t.id,menuKey:e.menuKey,order:h,parentId:p,supabase:e.supabase}),u++}return{insertedCount:u,languageCode:t.code,menuKey:e.menuKey,skippedCount:0,updatedCount:0}}function nn(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 fr(e){const t=await Z(e.supabase,e.languageCode),{data:n,error:r}=await e.supabase.from("navigation_items").select("id, parent_id").eq("menu_key",e.menuKey).eq("language_id",t.id);if(r)throw new Error(`Failed to inspect existing ${e.menuKey} navigation items: ${b(r)}`);const o=Array.isArray(n)?n:[];nn({existingItemCount:o.length,existingTopLevelCount:o.filter(i=>i.parent_id==null).length,languageCode:t.code,menuKey:e.menuKey,replacementItemCount:en(e.items)})}async function hr(e){if(e.items.length!==1)throw new Error('mode "update" requires exactly one navigation item.');const t=await Z(e.supabase,e.languageCode),n=e.items[0],r=X(e.match?.url)||X(n.url),o=Ut(e.match?.label),{data:i,error:a}=await e.supabase.from("navigation_items").select("id, label, url, parent_id, order").eq("menu_key",e.menuKey).eq("language_id",t.id);if(a)throw new Error(`Failed to load existing ${e.menuKey} navigation items: ${b(a)}`);const u=(Array.isArray(i)?i:[]).find(l=>{const p=X(l.url),h=Ut(l.label);return!!(r&&p===r||o&&h===o)});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: ${b(d)}`);return{insertedCount:0,languageCode:t.code,menuKey:e.menuKey,skippedCount:0,updatedCount:1}}async function yr(e){const t=await Z(e.supabase,e.languageCode),{data:n,error:r}=await e.supabase.from("navigation_items").select("id, url, parent_id, order").eq("menu_key",e.menuKey).eq("language_id",t.id);if(r)throw new Error(`Failed to load existing ${e.menuKey} navigation items: ${b(r)}`);let o=0,i=0;const a=Array.isArray(n)?n:[],c=new Set(a.map(l=>X(l.url)).filter(Boolean)),u=a.filter(l=>l.parent_id==null).map(l=>Number(l.order)).filter(Number.isFinite);let d=u.length>0?Math.max(...u)+1:a.length;for(const l of e.items){const p=X(l.url);if(p&&c.has(p)){i++;continue}const h=await xe({item:l,languageId:t.id,menuKey:e.menuKey,order:d,supabase:e.supabase});o++,d++,p&&c.add(p);let m=0;for(const f of l.children??[]){const g=X(f.url);if(g&&c.has(g)){i++;continue}await xe({item:f,languageId:t.id,menuKey:e.menuKey,order:m,parentId:h,supabase:e.supabase}),o++,m++,g&&c.add(g)}}return{insertedCount:o,languageCode:t.code,menuKey:e.menuKey,skippedCount:i,updatedCount:0}}function $(e){return typeof e=="string"&&e.trim()?e.trim():""}function br(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function _r(e){const t=$(e.field_type??e.fieldType??e.type??e.input_type).toLowerCase().replace(/\s+/g,"_"),n=$(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 wr(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,r)=>{const o=z(n)?n:{},i=$(o.label??o.name)||(r===0?"Name":r===1?"Email":"Message"),a=_r({...o,label:i}),c=o.is_required??o.isRequired??o.required;return{field_type:a,is_required:typeof c=="boolean"?c:!0,label:i,options:Array.isArray(o.options)?o.options:void 0,placeholder:$(o.placeholder)||void 0,temp_id:$(o.temp_id??o.tempId??o.id)||`field-${r+1}`}})}const kr=new Set(["none","sm","md","lg","xl"]),Ot=new Set(["none","sm","md","lg","xl"]),Ir=new Set(["full-width","container","container-sm","container-lg","container-xl"]),Tr=new Set(["start","center","end","stretch"]),Cr=new Set(["none","theme","solid","gradient","image"]),vr=new Set(["primary","secondary","muted","accent","destructive"]),Sr=new Set(["center","top","bottom","left","right"]);function xr(e){return typeof e=="string"&&/^https?:\/\//i.test(e.trim())}function D(e,t,n){return typeof e=="string"&&t.has(e)?e:n}function Er(e){return Number.isFinite(e)?Math.min(4,Math.max(1,Math.round(e))):1}function $r(e){const t=[{color:"#1e3a8a",position:0},{color:"#3b82f6",position:100}];if(!z(e))return{direction:"to bottom right",stops:t,type:"linear"};const n=e.type==="radial"?"radial":"linear",r=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:r,type:n}}function zr(e){if(!z(e))return{type:"none"};const t=D(e.type,Cr,"none"),n=typeof e.min_height=="string"&&e.min_height.trim()?{min_height:e.min_height}:{};if(t==="theme")return{theme:D(e.theme,vr,"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:$r(e.gradient),type:t,...n};if(t==="image"){const r=z(e.image)?e.image:null,o=r&&xr(r.external_url)?r.external_url.trim():null,i=!!(r&&typeof r.media_id=="string"&&r.media_id.trim()&&typeof r.object_key=="string"&&r.object_key.trim());return r&&(o||i)?{image:{...r,...o?{external_url:o}:{},position:D(r.position,Sr,"center"),size:r.size==="contain"?"contain":"cover"},type:t,...n}:{type:"none"}}return{type:"none",...n}}function Ar(e,t,n){const r=e.is_hero===!0;let o=Array.isArray(e.column_blocks)?e.column_blocks:[];o.length>0&&o.every(g=>z(g)&&!Array.isArray(g))&&(o=[o]);const i=o.map((g,y)=>(Array.isArray(g)?g:[]).map((k,I)=>Ke(k,`${t} column ${y} block ${I}`,n))),a=i.length>0?i:[[]],c=Er(a.length),u=z(e.responsive_columns)?e.responsive_columns:{},d=Number(u.tablet),l=Number(u.mobile),p=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,m=z(e.padding)?e.padding:{},f={...e,background:zr(e.background),column_blocks:a,column_gap:D(e.column_gap,kr,"lg"),container_type:D(e.container_type,Ir,"container"),padding:{bottom:D(m.bottom,Ot,"xl"),top:D(m.top,Ot,"xl")},responsive_columns:{desktop:c,mobile:h,tablet:p},vertical_alignment:D(e.vertical_alignment,Tr,r?"center":"start")};return f.slider===!0&&!(Array.isArray(f.slides)&&f.slides.length>0)&&(f.slider=!1),f}function rn(e,t,n,r){if(!R.isValidBlockType(e)){const i=K(t);return j(e,i,n,r),i}if(e==="section"){const i=Ar(t,n,r);return j(e,i,n,r),i}const o=K(t);if(e==="heading"&&(o.text_content=$(o.text_content)||$(o.text)||$(o.title)||$(o.heading)||"Untitled",o.level=typeof o.level=="number"?o.level:1),e==="text"){const i=$(o.html_content)||$(o.html)||$(o.content)||$(o.text);i&&(o.html_content=/<\/?[a-z][\s\S]*>/i.test(i)?i:`<p>${br(i)}</p>`)}return e==="button"&&(o.text=$(o.text)||$(o.label)||$(o.title)||"Learn More",o.url=$(o.url)||$(o.href)||$(o.link)||"#"),e==="form"&&(o.fields=wr(o.fields),o.submit_button_text=$(o.submit_button_text??o.submitButtonText??o.button_text)||"Send Message",o.success_message=$(o.success_message??o.successMessage)||"Thanks for reaching out. We will reply as soon as possible."),j(e,o,n,r),o}function Ee(e,t,n){const r=oe(e.blockType,`Block ${t}`,n),o=rn(r,_e(e.content,`Block ${t}`),`Block ${t}`,n);return{block_type:r,content:o,order:e.order??t}}function Pr(e,t="Contact Us",n){return[Ee({blockType:"section",content:{is_hero:!0,background:{type:"none"},column_blocks:[[{block_type:"heading",content:{level:1,textAlign:"center",text_content:t},temp_id:Se("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:Se("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),Ee({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"}],submit_button_text:"Send Message",success_message:"Thanks for reaching out. We will reply as soon as possible."}},1,n)]}function Be(e,t,n,r){return(!e||e.length===0)&&t?Pr(t,n,r):(e||[]).map((o,i)=>Ee(o,i,r))}async function st(e){const t=e.contentType==="page"?"pages":e.contentType==="post"?"posts":"products",{data:n,error:r}=await e.supabase.from(t).select("id, title, slug, language_id").eq("slug",e.slug).eq("language_id",e.languageId);if(r)throw new Error(`Failed to check ${e.contentType} slug uniqueness: ${b(r)}`);const o=Array.isArray(n)?n:[];return o.length>0?{duplicate:!0,existingItem:o[0],mutationExecuted:!1,success:!1,message:`A ${e.contentType} with slug "${e.slug}" already exists for this language.`}:null}async function ct(e){if(!e.suppliedTranslationGroupId)return{translationGroupId:void 0};const t=e.contentType==="page"?"pages":e.contentType==="post"?"posts":"products",{data:n,error:r}=await e.supabase.from(t).select("id, title, slug, language_id, translation_group_id").eq("translation_group_id",e.suppliedTranslationGroupId);if(r)throw new Error(`Failed to inspect ${e.contentType} translation group: ${b(r)}`);const o=Array.isArray(n)?n:[];if(o.length===0)return{result:{message:`The ${e.contentType} translation group "${e.suppliedTranslationGroupId}" was not found.`,mutationExecuted:!1,success:!1},translationGroupId:e.suppliedTranslationGroupId};const i=o.find(a=>Number(a.language_id)===e.languageId);return i?{result:{duplicateTranslation:!0,existingItem:i,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 lt(e){if(e.blocks.length===0)return[];const t=e.blocks.map((o,i)=>({block_type:o.block_type,content:o.content,language_id:e.languageId,order:o.order??i,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:r}=await e.supabase.from("blocks").insert(t).select("*");if(r)throw new Error(`Failed to insert ${e.contentType} blocks: ${b(r)}`);return we(e.blocks,e.supabase),Array.isArray(n)?n:[]}async function ut(e){const t=e.contentType==="page"?"pages":e.contentType==="post"?"posts":"products";await e.supabase.from(t).delete().eq("id",e.itemId)}function dt(e,t){return e==="page"?`/cms/pages/${t}/edit`:e==="post"?`/cms/posts/${t}/edit`:`/cms/products/${t}/edit`}function Ft(e){return e==="page"?"/cms/pages":e==="post"?"/cms/posts":"/cms/products"}async function pt(e,t){const n=ie.parse(e),r=x(t);n.mode==="replace"&&await fr({items:n.items,languageCode:n.languageCode,menuKey:"HEADER",supabase:r});const o=P({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(o)return o;const i=n.mode==="update"?await hr({items:n.items,languageCode:n.languageCode,match:n.match,menuKey:"HEADER",supabase:r}):n.mode==="append"?await yr({items:n.items,languageCode:n.languageCode,menuKey:"HEADER",supabase:r}):await tn({items:n.items,languageCode:n.languageCode,menuKey:"HEADER",supabase:r});return Jt(t),{...i,mutationExecuted:!0,mode:n.mode,success:!0}}async function mt(e,t){const n=ae.parse(e);if(!n.links?.length&&!n.copyright)throw new Error("update_footer requires links or copyright.");const r=x(t),o=P({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(o)return o;let i=null;if(n.links?.length&&(i=await tn({items:n.links,languageCode:n.languageCode,menuKey:"FOOTER",supabase:r})),n.copyright){const{error:a}=await r.from("site_settings").upsert({key:"footer_copyright",value:n.copyright});if(a)throw new Error(`Failed to update footer copyright: ${b(a)}`)}return Jt(t),{copyrightUpdated:!!n.copyright,footerNavigation:i,mutationExecuted:!0,success:!0}}function on(e){return typeof e=="string"?e.toLowerCase():""}function Nr(e,t){const n=t.map(on).join(" ");return e.reduce((r,o)=>r+(n.includes(o)?1:0),0)}function Bt(e,t){return(e.find(n=>t.some(r=>on(n).includes(r)))||e.find(n=>n.trim().length>0)||"No excerpt available.").slice(0,500)}async function an(e,t){const n=Ae.parse(e),r=x(t),o=n.query.toLowerCase().split(/\s+/).map(l=>l.trim()).filter(Boolean),[i,a]=await Promise.all([r.from("posts").select("id, title, slug, excerpt, subtitle, meta_description, status, updated_at").eq("status","published").limit(100),r.from("pages").select("id, title, slug, meta_description, status, updated_at").eq("status","published").limit(100)]);if(i.error)throw new Error(`Failed to search documentation posts: ${b(i.error)}`);if(a.error)throw new Error(`Failed to search documentation pages: ${b(a.error)}`);const c=(i.data??[]).map(l=>({excerpt:Bt([l.excerpt,l.subtitle,l.meta_description,l.slug].filter(Boolean),o),source:"post",title:l.title,url:`/article/${l.slug}`})),u=(a.data??[]).map(l=>({excerpt:Bt([l.meta_description,l.slug].filter(Boolean),o),source:"page",title:l.title,url:l.slug==="home"?"/":`/${l.slug}`})),d=[...c,...u].map(l=>({...l,score:Nr(o,[l.title,l.excerpt,l.url])})).filter(l=>l.score>0).sort((l,p)=>p.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 sn(e,t,n=Nn){const r=Ae.safeParse(e),o=r.success?r.data.query:"";return Hn(an(e,t),n,()=>({message:"Documentation search took too long to respond. Please try again or ask a more specific question.",query:o,results:[],success:!1,timedOut:!0}))}const Ur=["pending","trial","paid","shipped","cancelled","refunded","failed"],Or={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 Fr(e){return String(e??"unknown").trim().toLowerCase()||"unknown"}function Lt(e){const t=Object.fromEntries(Ur.map(n=>[n,0]));for(const n of e){const r=Fr(n.status);t[r]=(t[r]??0)+1}return t}function Br(e){const n=e.toLowerCase().replace(/[^a-z0-9_]+/g," ").split(/\s+/).filter(Boolean);for(const r of n){const o=Or[r];if(o)return o}return null}function re(e){const t=Number(e);return Number.isFinite(t)?t:0}async function cn(e,t){const n=Qe.parse(e),r=x(t),o=new Date;let i=null,a=null;switch(n.timeRange){case"today":i=new Date(o.getFullYear(),o.getMonth(),o.getDate());break;case"this_month":i=new Date(o.getFullYear(),o.getMonth(),1);break;case"last_7_days":i=new Date(o.getTime()-10080*60*1e3);break;case"last_30_days":i=new Date(o.getTime()-720*60*60*1e3);break;case"last_month":i=new Date(o.getFullYear(),o.getMonth()-1,1),a=new Date(o.getFullYear(),o.getMonth(),0,23,59,59,999);break;case"last_90_days":i=new Date(o.getTime()-2160*60*60*1e3);break;case"all_time":i=null;break}const c=n.currency?.toUpperCase(),u=Br(n.query),d=r.from("orders").select("id, status, total, currency, created_at, paid_at");c&&d.eq("currency",c),i&&d.gte("created_at",i.toISOString()),a&&d.lte("created_at",a.toISOString());const p=n.reportType==="products"||n.reportType==="revenue"||n.reportType==="general"?r.from("order_items").select(`
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const S=require("ai"),zn=require("./ai-global-agent-db-tools.cjs.js"),An=require("./ai-global-agent-custom-block-tools.cjs.js"),Pn=require("./ai-global-agent-content-ops-tools.cjs.js"),Nn=require("./ai-global-agent-theming-tools.cjs.js"),Un=require("./ai-global-agent-site-tools.cjs.js"),Kt=require("./editor-document-from-html.cjs.js");require("./zod-config.cjs.js");const R=require("./block-content-schemas.cjs.js"),s=require("zod");async function W(e,t,n){if(e?.recordRevision)try{return await e.recordRevision({contentType:t,entityId:n,phase:"capture"})}catch(r){console.error("Cortex AI: failed to capture revision baseline",r);return}}async function G(e,t,n,r){if(!(!e?.recordRevision||r===void 0))try{await e.recordRevision({baseline:r,contentType:t,entityId:n,phase:"commit"})}catch(o){console.error("Cortex AI: failed to record revision",o)}}const Fn=1e4,On={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"},Vt=s.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."),Pt=s.z.strictObject({label:s.z.string().trim().min(1).max(120),target:s.z.enum(["_self","_blank"]).optional(),url:Vt}),Xe=Pt.extend({children:s.z.array(Pt).max(20).optional()}),Bn=s.z.strictObject({label:s.z.string().trim().min(1).max(120).optional(),url:Vt.optional()}).refine(e=>!!(e.label||e.url),{message:"Navigation item match requires label or url."}),ie=s.z.strictObject({items:s.z.array(Xe).min(1).max(30),languageCode:s.z.string().trim().min(2).max(80).default("en").describe('Locale code or language name, for example "en", "fr", "English", or "French".'),match:Bn.optional().describe('For mode "update", identifies the existing navigation item to update.'),mode:s.z.enum(["append","replace","update"]).default("append")}),ae=s.z.strictObject({copyright:s.z.record(s.z.string().trim().min(2).max(12),s.z.string().trim().min(1).max(500)).optional(),languageCode:s.z.string().trim().min(2).max(80).default("en").describe('Locale code or language name, for example "en", "fr", "English", or "French".'),links:s.z.array(Xe).min(1).max(30).optional()}),Pe=s.z.strictObject({limit:s.z.number().int().min(1).max(8).default(4),query:s.z.string().trim().min(2).max(300)}),Qe=s.z.object({currency:s.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:s.z.string().describe("The analytical question about orders, products, or revenue."),reportType:s.z.enum(["revenue","orders","products","general"]).optional().default("general").describe("The focus area of the statistical report."),timeRange:s.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.")}),Ne=s.z.strictObject({contentType:s.z.enum(["page","post","product"]),currentEditor:s.z.strictObject({blockId:s.z.union([s.z.number().int().positive(),s.z.string().trim().min(1).max(120)]).nullable().optional(),blockType:s.z.string().trim().min(1).max(80).nullable().optional(),field:s.z.string().trim().min(1).max(120).nullable().optional()}).optional(),entityId:s.z.union([s.z.number().int().positive(),s.z.string().trim().min(1).max(120)]),languageId:s.z.number().int().positive().nullable().optional(),slug:s.z.string().trim().min(1).max(300).nullable().optional(),title:s.z.string().trim().min(1).max(300).nullable().optional(),translationGroupId:s.z.string().trim().min(1).max(120).nullable().optional()}),Ln=s.z.enum(["page","post","product"]),J=s.z.strictObject({contentType:Ln.optional(),entityId:s.z.union([s.z.number().int().positive(),s.z.string().trim().min(1).max(120)]).optional(),slug:s.z.string().trim().min(1).max(300).optional(),title:s.z.string().trim().min(1).max(300).optional()}),se=J.optional().describe("Names the page, post, or product to act on when no CMS editor is open (MCP clients). Pass contentType plus one of slug, entityId, or title. Ignored when an editor is already open."),Ze=s.z.strictObject({cmsTarget:se,includeBlockContent:s.z.boolean().default(!1),includeBlocks:s.z.boolean().default(!0)}),et="The feature image: an existing media library id OR an external https:// image URL, which is downloaded into the media library automatically (pass `mainImage` from fetch_url_content or a `url` from search_stock_photos straight in). WHAT IT DOES: on a page it renders as a full-width title banner ABOVE the page's blocks (the image as a dimmed cover background, about 200-300px tall, with the page title centred over it in white); on a post it is the article's hero image above the header. It is also the social/OG preview image and the card thumbnail in post listings. RULES: give every post one. Give a page one only when a title banner above its content is wanted; NEVER set one on the home page or on any page that opens with its own hero section (the banner would stack above the hero and repeat the title) — set the site-wide social preview with update_site_identity `social_image` instead. Pick a very wide landscape image (about 3:1, at least 1600px wide): the banner crops it to a short full-width band.",ce=s.z.strictObject({cmsTarget:se,fields:s.z.strictObject({description_json:s.z.unknown().optional(),excerpt:s.z.string().max(2e3).nullable().optional(),feature_image_id:s.z.string().trim().min(1).max(2048).nullable().optional().describe(et),label:s.z.string().max(120).nullable().optional(),meta_description:s.z.string().max(500).nullable().optional(),meta_title:s.z.string().max(160).nullable().optional(),published_at:s.z.string().max(80).nullable().optional(),short_description:s.z.string().max(2e3).nullable().optional(),slug:s.z.string().trim().min(1).max(300).optional(),status:s.z.enum(["draft","published","active","archived"]).optional(),subtitle:s.z.string().max(300).nullable().optional(),title:s.z.string().trim().min(1).max(300).optional()}).partial()}),Ue=s.z.string().trim().min(1).max(120).describe(`A built-in block type (${R.availableCortexAiBlockTypes.join(", ")}) or the slug of a custom block definition from list_custom_blocks, whose content is the flat { field_key: value } map its fields describe.`),le=s.z.strictObject({blockId:s.z.number().int().positive(),blockType:Ue.optional(),cmsTarget:se,content:s.z.record(s.z.string(),s.z.unknown())}),ue=s.z.strictObject({blockIndex:s.z.number().int().min(0),blockType:Ue.optional(),cmsTarget:se,columnIndex:s.z.number().int().min(0),content:s.z.record(s.z.string(),s.z.unknown()),parentBlockId:s.z.number().int().positive()}),de=s.z.strictObject({blockType:Ue,content:s.z.record(s.z.string(),s.z.unknown()).describe('The block content, matching that block type\'s schema. For a `text` block, `html_content` is rendered as real HTML and may include an inline <style> and an inline <script> — so you can add scroll reveals, counters, hover effects, and other motion directly in a block. Inline scripts are stamped with the site CSP nonce automatically. Three rules. (1) THE PAGE IS REACT-HYDRATED. Do not change the text, classes, or attributes of surrounding server-rendered markup: React reconciles afterwards and reverts your change (a counter animates then snaps back) or logs a hydration mismatch. Waiting for `load` is NOT sufficient — hydration can still be in flight. Safe patterns instead: animate with the Web Animations API (el.animate() touches no attribute); append your own new elements and style those; use CSS for anything CSS can do; and if you must set text, render the FINAL value server-side and only animate toward it once the element scrolls into view. (2) `on*` attributes (onclick, onload, …) are stripped, so bind with addEventListener. (3) The script runs once per full page load, not on client-side navigation — for site-wide behaviour use manage_site_script. For a `section` block: `is_hero: true` marks the page hero (the editor checkbox "Hero Section (Prioritized image loading)": its background image loads with priority and its content is vertically centred); `slider: true` with a `slides` array ([{ background, column_blocks }, …], the editor checkbox "Enable Slider (Carousel layout)") renders a carousel of full sections: only the slides are drawn, but the grid track count still comes from the top-level `column_blocks`, so send one top-level column per column you want inside each slide (empty columns are fine) and give every slide that same number of columns. Add `autoplay: true` and `timeframe` in seconds (default 5) to rotate it.'),order:s.z.number().int().min(0).optional()}),pe=J.extend({images:s.z.array(s.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).")}),me=J.extend({anchorBlockId:s.z.number().int().positive().optional(),anchorBlockType:Ue.optional(),block:de,position:s.z.enum(["before","after","start","end"]).default("end")}),ge=s.z.strictObject({blocks:s.z.array(de).max(20).optional(),contactEmail:s.z.string().email().optional(),feature_image_id:s.z.string().trim().min(1).max(2048).nullable().optional().describe(et),languageCode:s.z.string().trim().min(2).max(80).optional(),meta_description:s.z.string().max(500).nullable().optional(),meta_title:s.z.string().max(160).nullable().optional(),slug:s.z.string().trim().min(1).max(300).optional(),status:s.z.enum(["draft","published","archived"]).default("draft"),title:s.z.string().trim().min(1).max(300),translationGroupId:s.z.string().trim().min(1).max(120).optional()}),fe=s.z.strictObject({blocks:s.z.array(de).max(20).optional(),excerpt:s.z.string().max(2e3).nullable().optional(),feature_image_id:s.z.string().trim().min(1).max(2048).nullable().optional().describe(et),label:s.z.string().max(120).nullable().optional(),languageCode:s.z.string().trim().min(2).max(80).optional(),meta_description:s.z.string().max(500).nullable().optional(),meta_title:s.z.string().max(160).nullable().optional(),published_at:s.z.string().max(80).nullable().optional(),slug:s.z.string().trim().min(1).max(300).optional(),status:s.z.enum(["draft","published","archived"]).default("draft"),subtitle:s.z.string().max(300).nullable().optional(),title:s.z.string().trim().min(1).max(300),translationGroupId:s.z.string().trim().min(1).max(120).optional()}),he=s.z.strictObject({blocks:s.z.array(de).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:s.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:s.z.unknown().optional(),freemius_plan_id:s.z.string().optional(),freemius_product_id:s.z.string().optional(),images:s.z.array(s.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:s.z.boolean().default(!0),languageCode:s.z.string().trim().min(2).max(80).optional(),meta_description:s.z.string().max(500).nullable().optional(),meta_title:s.z.string().max(160).nullable().optional(),payment_provider:s.z.enum(["stripe","freemius"]).default("stripe"),price:s.z.number().min(0).default(0),prices:s.z.record(s.z.string(),s.z.number().min(0)).optional(),product_type:s.z.enum(["physical","digital"]).default("physical"),sale_price:s.z.number().min(0).nullable().optional(),sale_prices:s.z.record(s.z.string(),s.z.number().min(0).nullable()).optional(),short_description:s.z.string().max(2e3).nullable().optional(),sku:s.z.string().trim().min(1).max(120).optional(),slug:s.z.string().trim().min(1).max(300).optional(),status:s.z.enum(["draft","active","archived"]).default("draft"),stock:s.z.number().int().min(0).default(0),title:s.z.string().trim().min(1).max(300),trial_period_days:s.z.number().int().min(0).default(0),trial_requires_payment_method:s.z.boolean().default(!1),translationGroupId:s.z.string().trim().min(1).max(120).optional(),upc:s.z.string().max(120).nullable().optional()}),ye=J.extend({currencyCode:s.z.string().trim().min(3).max(3).optional(),endsAt:s.z.string().max(80).nullable().optional(),field:s.z.string().trim().min(1).max(120),startsAt:s.z.string().max(80).nullable().optional(),value:s.z.unknown()}),tt=J,be=J,Ht=s.z.discriminatedUnion("tool",[s.z.strictObject({input:ge,tool:s.z.literal("create_cms_page")}),s.z.strictObject({input:fe,tool:s.z.literal("create_cms_post")}),s.z.strictObject({input:he,tool:s.z.literal("create_cms_product")}),s.z.strictObject({input:be,tool:s.z.literal("delete_cms_item")}),s.z.strictObject({input:ye,tool:s.z.literal("update_cms_item_field")}),s.z.strictObject({input:le,tool:s.z.literal("update_content_block")}),s.z.strictObject({input:me,tool:s.z.literal("insert_content_block")}),s.z.strictObject({input:ce,tool:s.z.literal("update_current_cms_fields")}),s.z.strictObject({input:ae,tool:s.z.literal("update_footer")}),s.z.strictObject({input:ie,tool:s.z.literal("update_navigation_bar")}),s.z.strictObject({input:ue,tool:s.z.literal("update_section_column_block")}),s.z.strictObject({input:pe,tool:s.z.literal("set_content_images")})]),Rn=s.z.union([ge.extend({tool:s.z.literal("create_cms_page")}).transform(({tool:e,...t})=>({input:t,tool:e})),fe.extend({tool:s.z.literal("create_cms_post")}).transform(({tool:e,...t})=>({input:t,tool:e})),he.extend({tool:s.z.literal("create_cms_product")}).transform(({tool:e,...t})=>({input:t,tool:e})),be.extend({tool:s.z.literal("delete_cms_item")}).transform(({tool:e,...t})=>({input:t,tool:e})),ye.extend({tool:s.z.literal("update_cms_item_field")}).transform(({tool:e,...t})=>({input:t,tool:e})),le.extend({tool:s.z.literal("update_content_block")}).transform(({tool:e,...t})=>({input:t,tool:e})),me.extend({tool:s.z.literal("insert_content_block")}).transform(({tool:e,...t})=>({input:t,tool:e})),ce.extend({tool:s.z.literal("update_current_cms_fields")}).transform(({tool:e,...t})=>({input:t,tool:e})),ae.extend({tool:s.z.literal("update_footer")}).transform(({tool:e,...t})=>({input:t,tool:e})),ie.extend({tool:s.z.literal("update_navigation_bar")}).transform(({tool:e,...t})=>({input:t,tool:e})),ue.extend({tool:s.z.literal("update_section_column_block")}).transform(({tool:e,...t})=>({input:t,tool:e})),pe.extend({tool:s.z.literal("set_content_images")}).transform(({tool:e,...t})=>({input:t,tool:e}))]),qn=s.z.string().transform((e,t)=>{const n=Kn(e);return n.success?n.action:(t.addIssue({code:"custom",message:n.message}),s.z.NEVER)}),Dn=s.z.union([Ht,Rn,qn]),nt=s.z.strictObject({actions:s.z.array(Dn).min(1).max(8),summary:s.z.string().trim().min(1).max(500).optional()});function Mn(e){const t=[];let n="",r=0,o=null,i=!1;for(const a of e){if(o){n+=a,i?i=!1:a==="\\"?i=!0:a===o&&(o=null);continue}if(a==='"'||a==="'"){o=a,n+=a;continue}if(a==="["||a==="{"||a==="("){r++,n+=a;continue}if(a==="]"||a==="}"||a===")"){r=Math.max(0,r-1),n+=a;continue}if(a===","&&r===0){n.trim()&&t.push(n.trim()),n="";continue}n+=a}return n.trim()&&t.push(n.trim()),t}function Nt(e){let t="";for(let n=0;n<e.length;n++){const r=e[n];if(r!=="'"){t+=r;continue}let o="",i=!1;for(n++;n<e.length;n++){const a=e[n];if(i){o+=a,i=!1;continue}if(a==="\\"){i=!0;continue}if(a==="'")break;o+=a}t+=JSON.stringify(o)}return t.replace(/\bTrue\b/g,"true").replace(/\bFalse\b/g,"false").replace(/\bNone\b/g,"null")}function jn(e){const t=e.trim();return t.startsWith("'")&&t.endsWith("'")||t.startsWith('"')&&t.endsWith('"')||t.startsWith("[")||t.startsWith("{")?JSON.parse(Nt(t)):/^-?\d+(?:\.\d+)?$/.test(t)?Number(t):t==="true"||t==="True"?!0:t==="false"||t==="False"?!1:t==="null"||t==="None"?null:t}function Gn(e){const t={};for(const n of Mn(e)){const r=n.indexOf("=");if(r<=0)throw new Error(`Expected key=value argument, received "${n}".`);const o=n.slice(0,r).trim();if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(o))throw new Error(`Invalid argument name "${o}".`);t[o]=jn(n.slice(r+1))}return t}function Kn(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 r=n[1];let o;try{o=Gn(n[2])}catch(c){return{message:c instanceof Error?c.message:"Could not parse action-plan command arguments.",success:!1}}const i={input:o,tool:r},a=Ht.safeParse(i);return a.success?{action:a.data,success:!0}:{message:`Invalid action-plan command "${r}": ${a.error.issues.map(c=>c.message).join("; ")}`,success:!1}}function Vn(e){return e.normalize("NFD").replace(/[\u0300-\u036f]/g,"").toLowerCase().replace(/\s+/g," ").trim()}function ke(e,t){return t.some(n=>e.includes(n))}function Hn(e){const t=Vn(e),n=ke(t,["add ","insert ","put ","create "]),r=ke(t,["title","heading","description","intro","copy","paragraph"]),o=t.includes("form")&&ke(t,["above","before"]),i=t.includes("contact page")||t.includes("contact pages")||t.includes("contact us")||t.includes("contactez-nous"),a=t.includes("english")&&ke(t,["french","francais","francaise"]);return!n||!r||!o||!i||!a?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."}}function Ut(){return s.z.object({content:s.z.array(s.z.any()).optional(),type:s.z.literal("doc")})}function rt(){try{const{revalidatePath:e}=require("next/cache");return e}catch{return null}}function x(e){if(!e?.supabase)throw new Error("A Supabase service client is required to execute Cortex AI global tools.");return e.supabase}function Wn(e,t,n){let r;const o=new Promise(i=>{r=setTimeout(()=>i(n()),t)});return Promise.race([e.finally(()=>{r&&clearTimeout(r)}),o])}function Jn(e){const t=Ne.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 Fe(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 Wt(e){const t=String(e.entityId||"").trim();if(!t)throw new Error(`Current ${e.contentType} id is missing.`);return t}function M(e){return e.contentType==="product"?Wt(e):Fe(e)}const Yn=/^https?:\/\//i,Xn=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;async function Q(e,t,n){if(typeof e!="string")return null;const r=e.trim();if(!r)return null;if(!Yn.test(r)){if(Xn.test(r))return r;throw new Error(`"${r}" is not a usable image reference — provide an https:// image URL or a media library id.`)}const o=t?.importExternalImage;if(!o)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 i=await o({altText:n,url:r});if("error"in i)throw new Error(`I could not import the image from that URL: ${i.error}`);return i.id}async function Jt(e,t,n){const r=[];for(let o=0;o<e.length;o+=1){const i=await Q(e[o],t,`${n} image ${o+1}`);i&&r.push(i)}return r}async function Qn(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:r}=await e.supabase.from("product_media").insert(t.map((o,i)=>({media_id:o,product_id:e.productId,sort_order:i})));if(r)throw new Error(`Could not save the product images: ${_(r)}`)}return t}async function Oe(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 r=e.patch({blocks:Array.isArray(t.blocks)?K(t.blocks):[],meta:z(t.meta)?K(t.meta):{}}),o={updated_at:new Date().toISOString()};if(r.blocks&&(o.blocks=r.blocks),r.meta&&(o.meta=r.meta),Object.keys(o).length===1)return!1;const{error:i}=await e.supabase.from("product_drafts").update(o).eq("id",t.id);if(i)throw new Error(`The product was updated, but its open draft could not be kept in sync: ${_(i)}. Publishing that draft would undo this change — publish or discard it in the product editor first.`);return!0}function Yt(e){return typeof e=="string"?e.trim().replace(/^\/+|\/+$/g,""):""}function Zn(e,t){const n=Yt(t??e.slug);return n?e.contentType==="page"?n==="home"?"/":`/${n}`:e.contentType==="post"?`/article/${n}`:`/product/${n}`:null}function er(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 U(e,t,n){const r=e?.revalidatePath??rt();if(!r)return;r(er(t));const o=Zn(t,n);o&&r(o),t.contentType==="page"&&o!=="/"&&r("/"),t.contentType==="product"&&r("/cms/products")}function Xt(e){const t=e?.revalidatePath??rt();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 tr(){return Promise.resolve().then(()=>require("./ai-global-agent-ecommerce.cjs.js"))}function Me(e){return e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?`[${e.map(t=>Me(t)).join(",")}]`:`{${Object.keys(e).filter(t=>t!=="temp_id").sort().map(t=>`${JSON.stringify(t)}:${Me(e[t])}`).join(",")}}`}function nr(e){let t=2166136261;const n=Me(e);for(let r=0;r<n.length;r++)t^=n.charCodeAt(r),t=Math.imul(t,16777619);return(t>>>0).toString(16).padStart(8,"0")}function je(e){return e.replace(/\s+/g," ").trim().toUpperCase()}function rr(e,t,n){return`${je(`CONFIRM ${e} ${t}`)} #${nr(n)}`}function Qt(e){return{confirmationPhrase:rr(e.action,e.subject,e.payload),mutationExecuted:!1,preview:e.preview,requiresConfirmation:!0,success:!0}}function B(e,t){const n=e[t];return typeof n=="string"&&n.trim()?n.trim():null}function H(e,t){const n=Number(e[t]);return Number.isFinite(n)?n:null}function N(e,t,n=`${t}s`){return`${e} ${e===1?t:n}`}function or(e,t){const n=B(t,"summary");if(n)return n;const r=B(t,"title"),o=B(t,"slug"),i=B(t,"status"),a=B(t,"contentType"),c=B(t,"field"),u=B(t,"mode"),d=B(t,"languageCode"),l=H(t,"blockCount"),m=H(t,"itemCount"),h=H(t,"affectedCount");if(e==="create_cms_page"||e==="create_cms_post")return`Create ${i||"draft"} ${e==="create_cms_page"?"page":"post"} "${r||o||"Untitled"}"${o?` at slug "${o}"`:""}${l!==null?` with ${N(l,"content block")}`:""}.`;if(e==="create_cms_product"){const g=H(t,"imageCount"),f=H(t,"blockCount"),p=[g?N(g,"image"):null,f?N(f,"description block"):H(t,"descriptionLength")?"a full description":null].filter(Boolean);return`Create ${i||"draft"} product "${r||o||"Untitled"}"${o?` at slug "${o}"`:""}${p.length?` with ${p.join(" and ")}`:""}.`}if(e==="update_cms_item_field")return`Update ${c||"one field"} on the ${a||"CMS item"} "${r||o||"selected item"}".`;if(e==="update_navigation_bar")return`${u==="append"?"Add":u==="update"?"Update":"Replace"} ${m!==null?N(m,"navigation item"):"navigation items"} in the ${d||"selected"} header navigation.`;if(e==="update_footer"){const g=H(t,"linkCount");return`Update the ${d||"selected"} footer${g!==null?` with ${N(g,"link")}`:""}.`}return e==="update_content_block"?`Update the selected ${B(t,"blockType")||"content"} block.`:e==="insert_content_block"?`Insert ${B(t,"blockType")||"content"} block on the ${a||"CMS item"} "${r||o||"selected item"}".`:e==="update_section_column_block"?`Update the selected nested ${B(t,"nestedBlockType")||"section"} block.`:e==="delete_cms_item"||e==="prepare_delete_cms_item"?`Delete ${h!==null?N(h,a||"CMS item"):`the selected ${a||"CMS item"}`}${r||o?` for "${r||o}"`:""}.`:"Complete the requested CMS change."}function P(e){if(e.context?.skipConfirmation)return null;const t=Qt(e),n=je(e.context?.latestUserMessage||""),r=je(t.confirmationPhrase);return n.includes(r)?null:t}function ot(e){const t=e?.actorUserId;if(!t)throw new Error("A confirmed CMS mutation requires an authenticated admin actor.");return t}function it(){return globalThis.crypto?.randomUUID?.()||`id-${Date.now()}-${Math.random().toString(36).slice(2)}`}function F(e){return e.normalize("NFD").replace(new RegExp("\\p{Diacritic}","gu"),"").toLowerCase().trim().replace(/\s+/g,"-").replace(/[^a-z0-9-]/g,"").replace(/-+/g,"-").replace(/^-|-$/g,"").slice(0,300)}function at(e){return(e||"USD").trim().toUpperCase()}const ir=new Set(["BIF","CLP","DJF","GNF","JPY","KMF","KRW","MGA","PYG","RWF","UGX","VND","VUV","XAF","XOF","XPF"]);function ar(e){return ir.has(at(e))?0:2}function ve(e,t){return Math.round(e*10**ar(t))}function sr(e,t){return!e||typeof e!="object"||Array.isArray(e)?{}:Object.entries(e).reduce((n,[r,o])=>{if(typeof o=="number"&&Number.isFinite(o)&&o>=0){const i=at(r||t);n[i]=ve(o,i)}return n},{})}function _e(e,t){if(!z(e))throw new Error(`${t} content must be a JSON object.`);return JSON.parse(JSON.stringify(e))}function K(e){return JSON.parse(JSON.stringify(e))}function z(e){return!!(e&&typeof e=="object"&&!Array.isArray(e))}function Ge(e,t){const n=K(e);for(const[r,o]of Object.entries(t))if(o!==void 0){if(z(o)&&z(n[r])){n[r]=Ge(n[r],o);continue}n[r]=K(o)}return n}function Zt(e,t){if(t.contentType==="product"){if(String(e.product_id??"")!==String(Wt(t)))throw new Error(`Block ${e.id} does not belong to the current product being edited.`);return}const n=Fe(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 st(e,t){return t?.customBlockDefinitions?.find(n=>n.slug===e)??null}function Ke(e,t=new Set,n=0){if(n>12||!e)return t;if(typeof e=="string")return t.add(e),t;if(Array.isArray(e)){for(const r of e)Ke(r,t,n+1);return t}if(typeof e=="object")for(const[r,o]of Object.entries(e))(r==="block_type"||r==="blockType"||r==="anchorBlockType")&&typeof o=="string"?t.add(o):o&&typeof o=="object"&&Ke(o,t,n+1);return t}async function V(e,t){return e?.customBlockDefinitions||!e?.supabase||![...Ke(t)].some(o=>!R.isValidBlockType(o))?e:{...e,customBlockDefinitions:await R.loadCustomBlockDefinitions(e.supabase)}}function oe(e,t,n){const r=typeof e=="string"?e.trim():"";if(R.isValidBlockType(r)||r&&st(r,n))return r;throw new Error(`${t} has unsupported block type "${r||"unknown"}". Built-in types: ${R.availableCortexAiBlockTypes.join(", ")}; a custom block must use a slug returned by list_custom_blocks.`)}function en(e,t,n){if(e&&e!==t)throw new Error(`${n} is a "${t}" block. Refusing to update it as "${e}".`)}function j(e,t,n,r){if(!R.isValidBlockType(e)){const i=st(e,r);if(!i)throw new Error(`${n} references custom block "${e}", which does not exist.`);const a=R.validateCustomBlockInstanceContent(i,t);if(!a.isValid)throw new Error(`${n} content is invalid for custom block "${e}": ${a.errors.join("; ")}`);return}const o=R.validateCortexBlockContent(e,t,r);if(!o.isValid)throw new Error(`${n} content is invalid for block type "${e}": ${o.errors.join("; ")}`)}function tn(e){return e==="section"}function cr(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.form_key=="string"||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 Se(e){return`ai-${e}-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}function xe(e,t,n){if(!z(e))throw new Error(`${t} must be a JSON object.`);const r=e.block_type??e.blockType,o=oe(r,t,n);if(tn(o))throw new Error(`${t} cannot be a nested ${o} block.`);const i=an(o,_e(e.content,t),t,n),a=e.temp_id??e.tempId,c=typeof a=="string"&&a.trim()?a:Se(o);return{block_type:o,content:i,temp_id:c}}function lr(e,t){const n=[];if("append_block"in e&&n.push(xe(e.append_block,"Nested block to append",t)),"append_blocks"in e){const r=e.append_blocks;if(!Array.isArray(r))throw new Error("append_blocks must be an array of nested block objects.");r.forEach((o,i)=>{n.push(xe(o,`Nested block to append ${i}`,t))})}return n}function ur(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=cr(e);if(!n)return null;const r=_e(e,`Nested ${n} block`);return j(n,r,`Nested ${n} block`,t),{block_type:n,content:r,temp_id:Se(n)}}function dr(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 pr(e,t,n,r){if(!tn(e))return Ge(t,n);const o={...n},i=lr(o,r),a=ur(o,r);a&&i.push(a),delete o.append_block,delete o.append_blocks,delete o.append_column_index,delete o.column_index;const c=Ge(t,o);if(i.length>0){const u=Array.isArray(t.column_blocks)?K(t.column_blocks):[],d=dr(n,u.length),l=u.length>0?u:[[]];for(;l.length<=d;)l.push([]);l[d]=[...l[d]||[],...i],c.column_blocks=l}return c}function mr(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 X(e){return typeof e=="string"?e.trim().toLowerCase():""}function Ft(e){return typeof e=="string"?e.trim().toLowerCase():""}function nn(e){return e.reduce((t,n)=>t+1+(n.children?.length||0),0)}function Ce(e){return typeof e=="string"?e.trim().toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g,""):""}async function Z(e,t){const n=t.trim(),r=Ce(n),o=On[r],{data:i,error:a}=await e.from("languages").select("id, code, name, is_active");if(a)throw new Error(`Failed to load language "${t}": ${_(a)}`);const u=(Array.isArray(i)?i:[]).filter(l=>l.is_active!==!1),d=u.find(l=>{const m=Ce(l.code),h=Ce(l.name);return m===r||m===o||h===r});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 Be(e,t){if(t)return Z(e,t);const{data:n,error:r}=await e.from("languages").select("id, code, name, is_active, is_default");if(r)throw new Error(`Failed to load active languages: ${_(r)}`);const o=(Array.isArray(n)?n:[]).filter(a=>a.is_active!==!1),i=o.find(a=>a.is_default)||o.find(a=>Ce(a.code)==="en")||o[0];if(!i?.id||!i?.code)throw new Error("No active CMS language is available for Cortex AI content creation.");return{code:String(i.code),id:Number(i.id)}}async function Ve(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 r=Array.isArray(t)?t:[],o=r.find(i=>i.is_default)||r[0];return at(o?.code||"USD")}catch{return"USD"}}async function gr(e){const t=e.contentType==="page"?"pages":e.contentType==="post"?"posts":"products";let n="id",r=e.entityId;if(r===void 0&&e.slug&&(n="slug",r=e.slug),r===void 0&&e.title&&(n="title",r=e.title),r===void 0)throw new Error(`A ${e.contentType} target requires an id, slug, title, or current edit context.`);const{data:o,error:i}=await e.supabase.from(t).select("*").eq(n,r);if(i)throw new Error(`Failed to resolve ${e.contentType}: ${_(i)}`);const a=Array.isArray(o)?o:o?[o]:[];if(a.length!==1)throw new Error(a.length===0?`No ${e.contentType} matched ${n} "${String(r)}".`:`Multiple ${e.contentType}s matched ${n} "${String(r)}"; use an exact id.`);return a[0]}async function Y(e,t){const n=Ne.safeParse(t?.pageContext).success?t?.pageContext:null,r=e.contentType||n?.contentType;if(!r)throw new Error("Target contentType is required when no current CMS edit context exists.");const o=e.entityId!==void 0||!!e.slug||!!e.title,i=e.entityId??(o?void 0:n?.entityId),a=e.slug??(o?void 0:n?.slug??void 0),c=e.title??(o?void 0:n?.title??void 0),u=await gr({contentType:r,entityId:i,slug:i===void 0&&a||void 0,supabase:x(t),title:i===void 0&&!a&&c||void 0});return{contentType:r,item:u}}async function ee(e,t){const n=Ne.safeParse(t?.pageContext);if(n.success)return n.data;if(!(e!==void 0&&(e.entityId!==void 0||!!e.slug||!!e.title)))throw new Error("No current CMS page context is available. Open a page, post, or product edit screen, or pass `cmsTarget` naming the item — contentType plus one of slug, entityId, or title.");const o=await Y(e,t),i=o.item;return{contentType:o.contentType,entityId:i.id,slug:typeof i.slug=="string"?i.slug:"",title:typeof i.title=="string"?i.title:""}}async function Ee(e){const t=await hr({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:r,error:o}=await e.supabase.from("navigation_items").insert(n).select("id").single();if(o)throw new Error(`Failed to insert ${e.menuKey} navigation item: ${_(o)}`);return Number(r.id)}function fr(e){const t=e.trim();if(!t.startsWith("/")||t.startsWith("//"))return null;const n=t.split("?")[0]?.split("#")[0]||"",r=n==="/"?"home":n.replace(/^\/+|\/+$/g,"");return r&&!r.includes("/")?r:null}async function hr(e){const t=fr(e.item.url);if(!t)return null;const{data:n,error:r}=await e.supabase.from("pages").select("id, slug, translation_group_id, language_id").eq("slug",t).eq("language_id",e.languageId);if(r)throw new Error(`Failed to resolve linked page for navigation item: ${_(r)}`);const o=Array.isArray(n)?n[0]:n;if(!o?.id)return null;let i=it();if(o.translation_group_id){const{data:a,error:c}=await e.supabase.from("pages").select("id").eq("translation_group_id",o.translation_group_id);if(c)throw new Error(`Failed to inspect linked page translations for navigation item: ${_(c)}`);const u=new Set((Array.isArray(a)?a:[]).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&&(i=m.translation_group_id)}return{navigationTranslationGroupId:i,pageId:Number(o.id)}}async function rn(e){const t=await Z(e.supabase,e.languageCode),{data:n,error:r}=await e.supabase.from("navigation_items").select("id, parent_id").eq("menu_key",e.menuKey).eq("language_id",t.id);if(r)throw new Error(`Failed to inspect existing ${e.menuKey} navigation items: ${_(r)}`);const o=Array.isArray(n)?n:[],i=o.filter(d=>d.parent_id==null).length,a=nn(e.items);on({existingItemCount:o.length,existingTopLevelCount:i,languageCode:t.code,menuKey:e.menuKey,replacementItemCount:a});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 Ee({item:l,languageId:t.id,menuKey:e.menuKey,order:d,supabase:e.supabase});u++;for(const[h,g]of(l.children??[]).entries())await Ee({item:g,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 on(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 yr(e){const t=await Z(e.supabase,e.languageCode),{data:n,error:r}=await e.supabase.from("navigation_items").select("id, parent_id").eq("menu_key",e.menuKey).eq("language_id",t.id);if(r)throw new Error(`Failed to inspect existing ${e.menuKey} navigation items: ${_(r)}`);const o=Array.isArray(n)?n:[];on({existingItemCount:o.length,existingTopLevelCount:o.filter(i=>i.parent_id==null).length,languageCode:t.code,menuKey:e.menuKey,replacementItemCount:nn(e.items)})}async function br(e){if(e.items.length!==1)throw new Error('mode "update" requires exactly one navigation item.');const t=await Z(e.supabase,e.languageCode),n=e.items[0],r=X(e.match?.url)||X(n.url),o=Ft(e.match?.label),{data:i,error:a}=await e.supabase.from("navigation_items").select("id, label, url, parent_id, order").eq("menu_key",e.menuKey).eq("language_id",t.id);if(a)throw new Error(`Failed to load existing ${e.menuKey} navigation items: ${_(a)}`);const u=(Array.isArray(i)?i:[]).find(l=>{const m=X(l.url),h=Ft(l.label);return!!(r&&m===r||o&&h===o)});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 _r(e){const t=await Z(e.supabase,e.languageCode),{data:n,error:r}=await e.supabase.from("navigation_items").select("id, url, parent_id, order").eq("menu_key",e.menuKey).eq("language_id",t.id);if(r)throw new Error(`Failed to load existing ${e.menuKey} navigation items: ${_(r)}`);let o=0,i=0;const a=Array.isArray(n)?n:[],c=new Set(a.map(l=>X(l.url)).filter(Boolean)),u=a.filter(l=>l.parent_id==null).map(l=>Number(l.order)).filter(Number.isFinite);let d=u.length>0?Math.max(...u)+1:a.length;for(const l of e.items){const m=X(l.url);if(m&&c.has(m)){i++;continue}const h=await Ee({item:l,languageId:t.id,menuKey:e.menuKey,order:d,supabase:e.supabase});o++,d++,m&&c.add(m);let g=0;for(const f of l.children??[]){const p=X(f.url);if(p&&c.has(p)){i++;continue}await Ee({item:f,languageId:t.id,menuKey:e.menuKey,order:g,parentId:h,supabase:e.supabase}),o++,g++,p&&c.add(p)}}return{insertedCount:o,languageCode:t.code,menuKey:e.menuKey,skippedCount:i,updatedCount:0}}function $(e){return typeof e=="string"&&e.trim()?e.trim():""}function wr(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function kr(e){const t=$(e.field_type??e.fieldType??e.type??e.input_type).toLowerCase().replace(/\s+/g,"_"),n=$(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 Ir(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,r)=>{const o=z(n)?n:{},i=$(o.label??o.name)||(r===0?"Name":r===1?"Email":"Message"),a=kr({...o,label:i}),c=o.is_required??o.isRequired??o.required;return{field_type:a,is_required:typeof c=="boolean"?c:!0,label:i,options:Array.isArray(o.options)?o.options:void 0,placeholder:$(o.placeholder)||void 0,temp_id:$(o.temp_id??o.tempId??o.id)||`field-${r+1}`}})}const Tr=new Set(["none","sm","md","lg","xl"]),Ot=new Set(["none","sm","md","lg","xl"]),Cr=new Set(["full-width","container","container-sm","container-lg","container-xl"]),vr=new Set(["start","center","end","stretch"]),Sr=new Set(["none","theme","solid","gradient","image"]),xr=new Set(["primary","secondary","muted","accent","destructive"]),Er=new Set(["center","top","bottom","left","right"]);function $r(e){return typeof e=="string"&&/^https?:\/\//i.test(e.trim())}function D(e,t,n){return typeof e=="string"&&t.has(e)?e:n}function zr(e){return Number.isFinite(e)?Math.min(4,Math.max(1,Math.round(e))):1}function Ar(e){const t=[{color:"#1e3a8a",position:0},{color:"#3b82f6",position:100}];if(!z(e))return{direction:"to bottom right",stops:t,type:"linear"};const n=e.type==="radial"?"radial":"linear",r=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:r,type:n}}function Bt(e){if(!z(e))return{type:"none"};const t=D(e.type,Sr,"none"),n=typeof e.min_height=="string"&&e.min_height.trim()?{min_height:e.min_height}:{};if(t==="theme")return{theme:D(e.theme,xr,"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:Ar(e.gradient),type:t,...n};if(t==="image"){const r=z(e.image)?e.image:null,o=r&&$r(r.external_url)?r.external_url.trim():null,i=!!(r&&typeof r.media_id=="string"&&r.media_id.trim()&&typeof r.object_key=="string"&&r.object_key.trim());return r&&(o||i)?{image:{...r,...o?{external_url:o}:{},position:D(r.position,Er,"center"),size:r.size==="contain"?"contain":"cover"},type:t,...n}:{type:"none"}}return{type:"none",...n}}function Pr(e,t,n){const r=e.is_hero===!0;let o=Array.isArray(e.column_blocks)?e.column_blocks:[];o.length>0&&o.every(p=>z(p)&&!Array.isArray(p))&&(o=[o]);const i=o.map((p,b)=>(Array.isArray(p)?p:[]).map((w,I)=>xe(w,`${t} column ${b} block ${I}`,n))),a=i.length>0?i:[[]],c=zr(a.length),u=z(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,g=z(e.padding)?e.padding:{},f={...e,background:Bt(e.background),column_blocks:a,column_gap:D(e.column_gap,Tr,"lg"),container_type:D(e.container_type,Cr,"container"),padding:{bottom:D(g.bottom,Ot,"xl"),top:D(g.top,Ot,"xl")},responsive_columns:{desktop:c,mobile:h,tablet:m},vertical_alignment:D(e.vertical_alignment,vr,r?"center":"start")};return Array.isArray(e.slides)&&(f.slides=e.slides.filter(p=>z(p)).map((p,b)=>{let y=Array.isArray(p.column_blocks)?p.column_blocks:[];return y.length>0&&y.every(w=>z(w)&&!Array.isArray(w))&&(y=[y]),{background:Bt(p.background),column_blocks:y.map((w,I)=>(Array.isArray(w)?w:[]).map((k,C)=>xe(k,`${t} slide ${b} column ${I} block ${C}`,n)))}})),f.slider===!0&&!(Array.isArray(f.slides)&&f.slides.length>0)&&(f.slider=!1),f}function an(e,t,n,r){if(!R.isValidBlockType(e)){const i=K(t);return j(e,i,n,r),i}if(e==="section"){const i=Pr(t,n,r);return j(e,i,n,r),i}const o=K(t);if(e==="heading"&&(o.text_content=$(o.text_content)||$(o.text)||$(o.title)||$(o.heading)||"Untitled",o.level=typeof o.level=="number"?o.level:1),e==="text"){const i=$(o.html_content)||$(o.html)||$(o.content)||$(o.text);i&&(o.html_content=/<\/?[a-z][\s\S]*>/i.test(i)?i:`<p>${wr(i)}</p>`)}return e==="button"&&(o.text=$(o.text)||$(o.label)||$(o.title)||"Learn More",o.url=$(o.url)||$(o.href)||$(o.link)||"#"),e==="form"&&(o.fields=Ir(o.fields),o.submit_button_text=$(o.submit_button_text??o.submitButtonText??o.button_text)||"Send Message",o.success_message=$(o.success_message??o.successMessage)||"Thanks for reaching out. We will reply as soon as possible."),j(e,o,n,r),o}function $e(e,t,n){const r=oe(e.blockType,`Block ${t}`,n),o=an(r,_e(e.content,`Block ${t}`),`Block ${t}`,n);return{block_type:r,content:o,order:e.order??t}}function Nr(e,t="Contact Us",n){return[$e({blockType:"section",content:{is_hero:!0,background:{type:"none"},column_blocks:[[{block_type:"heading",content:{level:1,textAlign:"center",text_content:t},temp_id:Se("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:Se("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),$e({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"}],submit_button_text:"Send Message",success_message:"Thanks for reaching out. We will reply as soon as possible."}},1,n)]}function Le(e,t,n,r){return(!e||e.length===0)&&t?Nr(t,n,r):(e||[]).map((o,i)=>$e(o,i,r))}async function ct(e){const t=e.contentType==="page"?"pages":e.contentType==="post"?"posts":"products",{data:n,error:r}=await e.supabase.from(t).select("id, title, slug, language_id").eq("slug",e.slug).eq("language_id",e.languageId);if(r)throw new Error(`Failed to check ${e.contentType} slug uniqueness: ${_(r)}`);const o=Array.isArray(n)?n:[];return o.length>0?{duplicate:!0,existingItem:o[0],mutationExecuted:!1,success:!1,message:`A ${e.contentType} with slug "${e.slug}" already exists for this language.`}:null}async function lt(e){if(!e.suppliedTranslationGroupId)return{translationGroupId:void 0};const t=e.contentType==="page"?"pages":e.contentType==="post"?"posts":"products",{data:n,error:r}=await e.supabase.from(t).select("id, title, slug, language_id, translation_group_id").eq("translation_group_id",e.suppliedTranslationGroupId);if(r)throw new Error(`Failed to inspect ${e.contentType} translation group: ${_(r)}`);const o=Array.isArray(n)?n:[];if(o.length===0)return{result:{message:`The ${e.contentType} translation group "${e.suppliedTranslationGroupId}" was not found.`,mutationExecuted:!1,success:!1},translationGroupId:e.suppliedTranslationGroupId};const i=o.find(a=>Number(a.language_id)===e.languageId);return i?{result:{duplicateTranslation:!0,existingItem:i,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 ut(e){if(e.blocks.length===0)return[];const t=e.blocks.map((o,i)=>({block_type:o.block_type,content:o.content,language_id:e.languageId,order:o.order??i,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:r}=await e.supabase.from("blocks").insert(t).select("*");if(r)throw new Error(`Failed to insert ${e.contentType} blocks: ${_(r)}`);return we(e.blocks,e.supabase),Array.isArray(n)?n:[]}async function dt(e){const t=e.contentType==="page"?"pages":e.contentType==="post"?"posts":"products";await e.supabase.from(t).delete().eq("id",e.itemId)}function pt(e,t){return e==="page"?`/cms/pages/${t}/edit`:e==="post"?`/cms/posts/${t}/edit`:`/cms/products/${t}/edit`}function Lt(e){return e==="page"?"/cms/pages":e==="post"?"/cms/posts":"/cms/products"}async function mt(e,t){const n=ie.parse(e),r=x(t);n.mode==="replace"&&await yr({items:n.items,languageCode:n.languageCode,menuKey:"HEADER",supabase:r});const o=P({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(o)return o;const i=n.mode==="update"?await br({items:n.items,languageCode:n.languageCode,match:n.match,menuKey:"HEADER",supabase:r}):n.mode==="append"?await _r({items:n.items,languageCode:n.languageCode,menuKey:"HEADER",supabase:r}):await rn({items:n.items,languageCode:n.languageCode,menuKey:"HEADER",supabase:r});return Xt(t),{...i,mutationExecuted:!0,mode:n.mode,success:!0}}async function gt(e,t){const n=ae.parse(e);if(!n.links?.length&&!n.copyright)throw new Error("update_footer requires links or copyright.");const r=x(t),o=P({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(o)return o;let i=null;if(n.links?.length&&(i=await rn({items:n.links,languageCode:n.languageCode,menuKey:"FOOTER",supabase:r})),n.copyright){const{error:a}=await r.from("site_settings").upsert({key:"footer_copyright",value:n.copyright});if(a)throw new Error(`Failed to update footer copyright: ${_(a)}`)}return Xt(t),{copyrightUpdated:!!n.copyright,footerNavigation:i,mutationExecuted:!0,success:!0}}function sn(e){return typeof e=="string"?e.toLowerCase():""}function Ur(e,t){const n=t.map(sn).join(" ");return e.reduce((r,o)=>r+(n.includes(o)?1:0),0)}function Rt(e,t){return(e.find(n=>t.some(r=>sn(n).includes(r)))||e.find(n=>n.trim().length>0)||"No excerpt available.").slice(0,500)}async function cn(e,t){const n=Pe.parse(e),r=x(t),o=n.query.toLowerCase().split(/\s+/).map(l=>l.trim()).filter(Boolean),[i,a]=await Promise.all([r.from("posts").select("id, title, slug, excerpt, subtitle, meta_description, status, updated_at").eq("status","published").limit(100),r.from("pages").select("id, title, slug, meta_description, status, updated_at").eq("status","published").limit(100)]);if(i.error)throw new Error(`Failed to search documentation posts: ${_(i.error)}`);if(a.error)throw new Error(`Failed to search documentation pages: ${_(a.error)}`);const c=(i.data??[]).map(l=>({excerpt:Rt([l.excerpt,l.subtitle,l.meta_description,l.slug].filter(Boolean),o),source:"post",title:l.title,url:`/article/${l.slug}`})),u=(a.data??[]).map(l=>({excerpt:Rt([l.meta_description,l.slug].filter(Boolean),o),source:"page",title:l.title,url:l.slug==="home"?"/":`/${l.slug}`})),d=[...c,...u].map(l=>({...l,score:Ur(o,[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 ln(e,t,n=Fn){const r=Pe.safeParse(e),o=r.success?r.data.query:"";return Wn(cn(e,t),n,()=>({message:"Documentation search took too long to respond. Please try again or ask a more specific question.",query:o,results:[],success:!1,timedOut:!0}))}const Fr=["pending","trial","paid","shipped","cancelled","refunded","failed"],Or={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 Br(e){return String(e??"unknown").trim().toLowerCase()||"unknown"}function qt(e){const t=Object.fromEntries(Fr.map(n=>[n,0]));for(const n of e){const r=Br(n.status);t[r]=(t[r]??0)+1}return t}function Lr(e){const n=e.toLowerCase().replace(/[^a-z0-9_]+/g," ").split(/\s+/).filter(Boolean);for(const r of n){const o=Or[r];if(o)return o}return null}function re(e){const t=Number(e);return Number.isFinite(t)?t:0}async function un(e,t){const n=Qe.parse(e),r=x(t),o=new Date;let i=null,a=null;switch(n.timeRange){case"today":i=new Date(o.getFullYear(),o.getMonth(),o.getDate());break;case"this_month":i=new Date(o.getFullYear(),o.getMonth(),1);break;case"last_7_days":i=new Date(o.getTime()-10080*60*1e3);break;case"last_30_days":i=new Date(o.getTime()-720*60*60*1e3);break;case"last_month":i=new Date(o.getFullYear(),o.getMonth()-1,1),a=new Date(o.getFullYear(),o.getMonth(),0,23,59,59,999);break;case"last_90_days":i=new Date(o.getTime()-2160*60*60*1e3);break;case"all_time":i=null;break}const c=n.currency?.toUpperCase(),u=Lr(n.query),d=r.from("orders").select("id, status, total, currency, created_at, paid_at");c&&d.eq("currency",c),i&&d.gte("created_at",i.toISOString()),a&&d.lte("created_at",a.toISOString());const m=n.reportType==="products"||n.reportType==="revenue"||n.reportType==="general"?r.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;p&&(c&&p.eq("orders.currency",c),i&&p.gte("orders.paid_at",i.toISOString()),a&&p.lte("orders.paid_at",a.toISOString()));const m=n.timeRange!=="all_time"&&(n.reportType==="orders"||u)?r.from("orders").select("id, status, currency"):null;m&&c&&m.eq("currency",c);const[{data:f,error:g},{data:y,error:_},k]=await Promise.all([d,p??Promise.resolve({data:[],error:null}),m??Promise.resolve({data:null,error:null})]);if(g)throw new Error(`Failed to fetch ecommerce stats: ${b(g)}`);if(_)throw new Error(`Failed to fetch ecommerce stats: ${b(_)}`);if(k.error)throw new Error(`Failed to fetch ecommerce stats: ${b(k.error)}`);const I=Array.isArray(f)?f:[],T=Array.isArray(y)?y:[],w=Lt(I),C=Array.isArray(k.data)?k.data:null,E=C?Lt(C):null,F={};for(const v of T){const A=Array.isArray(v.orders)?v.orders[0]:v.orders,q=String(A?.currency||c||"unknown").toUpperCase();F[q]=(F[q]??0)+re(v.quantity)*re(v.price_at_purchase)/100}const te={currency:c??null,currencyFiltered:!!c,orderStatusCounts:w,paidOrderCount:w.paid??0,query:n.query,reportType:n.reportType,revenueByCurrency:F,timeRange:n.timeRange,totalOrders:I.length,totalRevenue:Object.values(F).reduce((v,A)=>v+A,0)};if(E&&(te.allTimeOrderStatusCounts=E),u&&(te.matchingOrderStatus={allTimeCount:E?.[u]??w[u]??0,count:w[u]??0,status:u,timeRange:n.timeRange}),n.reportType==="products"||n.reportType==="revenue"||n.reportType==="general"){const v={};for(const A of T){const q=Array.isArray(A.products)?A.products[0]:A.products;if(!q?.id)continue;const ne=q.id;v[ne]||(v[ne]={id:ne,quantity:0,revenue:0,title:q.title,type:q.product_type}),v[ne].quantity+=re(A.quantity),v[ne].revenue+=re(A.quantity)*re(A.price_at_purchase)/100}te.topProducts=Object.values(v).sort((A,q)=>q.revenue-A.revenue).slice(0,10)}return{report:te,success:!0}}async function ln(e,t){const n=Ze.parse(e),r=x(t),o=await ee(n.cmsTarget,t),i=M(o),a=o.contentType==="page"?"pages":o.contentType==="post"?"posts":"products",{data:c,error:u}=await r.from(a).select("*").eq("id",i).single();if(u||!c)throw new Error(`Failed to read current ${o.contentType}: ${b(u)}`);let d=[];if(n.includeBlocks){const l=o.contentType==="page"?"page_id":o.contentType==="post"?"post_id":"product_id",{data:p,error:h}=await r.from("blocks").select("id, page_id, post_id, product_id, language_id, block_type, content, order").eq(l,i);if(h)throw new Error(`Failed to read current ${o.contentType} blocks: ${b(h)}`);d=(Array.isArray(p)?p:[]).slice().sort((m,f)=>Number(m.order)-Number(f.order)).map(m=>dr(m,n.includeBlockContent))}return{blocks:d,context:o,item:c,success:!0}}const un=new Set(["feature_image_id","language_id","meta_description","meta_title","slug","status","title"]),dn=new Set(["excerpt","feature_image_id","label","language_id","meta_description","meta_title","published_at","slug","status","subtitle","title"]),Lr=new Set(["description_json","language_id","meta_description","meta_title","short_description","slug","status","title"]),Rr=new Set(["excerpt","feature_image_id","label","meta_description","meta_title","published_at","short_description","subtitle"]);function qr(e){return e==="page"?un:e==="post"?dn:Lr}function pn(e,t){return Rr.has(e)&&t===""?null:t}function Ve(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 Dr(e,t){const n=qr(t.contentType),r={};for(const[o,i]of Object.entries(e))if(i!==void 0){if(!n.has(o))throw new Error(`Field "${o}" cannot be updated for ${t.contentType} content.`);o==="status"&&Ve(t.contentType,i),r[o]=pn(o,i)}return r}async function gt(e,t){const n=ce.parse(e),r=x(t),o=await ee(n.cmsTarget,t),i=M(o),a=Dr(n.fields,o),c=Object.keys(a);if(c.length===0)throw new Error("update_current_cms_fields requires at least one supported field.");const u=P({action:"UPDATE CMS FIELDS",context:t,payload:{contentType:o.contentType,entityId:i,fields:a,tool:"update_current_cms_fields"},preview:{contentType:o.contentType,entityId:i,fields:c,slug:o.slug,title:o.title},subject:`${o.contentType} ${String(i)}`});if(u)return u;const d=await W(t,o.contentType,i);typeof a.feature_image_id=="string"&&(a.feature_image_id=await Q(a.feature_image_id,t,typeof o.title=="string"?o.title:void 0));const l=o.contentType==="page"?"pages":o.contentType==="post"?"posts":"products",{data:p,error:h}=await r.from(l).update({...a,updated_at:new Date().toISOString()}).eq("id",i).select("id, language_id, slug, status, title").single();if(h||!p)throw new Error(`Failed to update current ${o.contentType}: ${b(h)}`);return await G(t,o.contentType,i,d),U(t,o,p.slug),{contentType:o.contentType,entityId:i,mutationExecuted:!0,slug:p.slug,success:!0,updatedFields:c}}async function ft(e,t){const n=le.parse(e),r=x(t),o=await ee(n.cmsTarget,t),{data:i,error:a}=await r.from("blocks").select("id, page_id, post_id, product_id, language_id, block_type, content, order").eq("id",n.blockId).single();if(a||!i)throw new Error(`Failed to read block ${n.blockId}: ${b(a)}`);Xt(i,o),t=await H(t,[i.block_type,i.content,n.content]);const c=oe(i.block_type,`Block ${n.blockId}`,t);Qt(n.blockType,c,`Block ${n.blockId}`);const u=_e(i.content,`Block ${n.blockId}`),d=ur(c,u,n.content,t);j(c,d,`Block ${n.blockId}`,t);const l=P({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:o.contentType,entityId:M(o)},subject:`${c} block ${n.blockId}`});if(l)return l;const p=await W(t,o.contentType,M(o)),{data:h,error:m}=await r.from("blocks").update({content:d,updated_at:new Date().toISOString()}).eq("id",n.blockId).select("id, block_type, order").single();if(m||!h)throw new Error(`Failed to update block ${n.blockId}: ${b(m)}`);return await G(t,o.contentType,M(o),p),await Oe({patch:({blocks:f})=>({blocks:f.map(g=>String(g?.id)===String(n.blockId)?{...g,content:d}:g)}),productId:i.product_id,supabase:r}),we([{content:d}],r),U(t,o),{blockId:h.id,blockType:h.block_type,contentUpdated:!0,mutationExecuted:!0,success:!0}}async function ht(e,t){const n=me.parse(e);t=await H(t,n.block);const r=x(t),o=await Y(n,t),i=o.contentType==="product"?o.item.id:Number(o.item.id),a=o.contentType==="page"?"page_id":o.contentType==="post"?"post_id":"product_id",c=async()=>{const{data:T,error:w}=await r.from("blocks").select("id, page_id, post_id, product_id, language_id, block_type, content, order").eq(a,i);if(w)throw new Error(`Failed to read ${o.contentType} blocks: ${b(w)}`);return(Array.isArray(T)?T:[]).sort((C,E)=>Number(C.order)-Number(E.order))},u=T=>{if(n.position==="start")return 0;if(n.position==="end"){const E=T.map(F=>Number(F.order)).filter(Number.isFinite);return E.length>0?Math.max(...E)+1:0}const w=n.anchorBlockId?T.find(E=>Number(E.id)===n.anchorBlockId):n.anchorBlockType?T.find(E=>E.block_type===n.anchorBlockType):null;if(!w)throw new Error(n.anchorBlockType?`Could not find a ${n.anchorBlockType} block to insert ${n.position}.`:`Could not find block ${n.anchorBlockId} to insert ${n.position}.`);const C=Number(w.order);return n.position==="before"?C:C+1},d=Ee(n.block,0,t),l=await c(),p=u(l),h={contentType:o.contentType,entityId:o.item.id,languageId:o.item.language_id,slug:o.item.slug,title:o.item.title,translationGroupId:o.item.translation_group_id},m=P({action:"INSERT CONTENT BLOCK",context:t,payload:{block:d,order:p,target:{contentType:o.contentType,id:o.item.id,slug:o.item.slug},tool:"insert_content_block"},preview:{anchorBlockId:n.anchorBlockId,anchorBlockType:n.anchorBlockType,blockType:d.block_type,contentType:o.contentType,entityId:o.item.id,position:n.position,slug:o.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 ${o.contentType} "${o.item.title||o.item.slug}".`,title:o.item.title},subject:`${d.block_type} block on ${o.contentType} ${o.item.id}`});if(m)return m;const f=await c(),g=u(f),y=f.filter(T=>Number(T.order)>=g).sort((T,w)=>Number(w.order)-Number(T.order)),_=await W(t,o.contentType,i);for(const T of y){const{error:w}=await r.from("blocks").update({order:Number(T.order)+1,updated_at:new Date().toISOString()}).eq("id",T.id);if(w)throw new Error(`Failed to shift block ${T.id}: ${b(w)}`)}const{data:k,error:I}=await r.from("blocks").insert({block_type:d.block_type,content:d.content,language_id:o.item.language_id,order:g,page_id:o.contentType==="page"?i:null,post_id:o.contentType==="post"?i:null,product_id:o.contentType==="product"?i:null}).select("id, block_type, order").single();if(I||!k)throw new Error(`Failed to insert content block: ${b(I)}`);return o.contentType==="product"&&await Oe({patch:({blocks:T})=>({blocks:[...T.map(w=>Number(w?.order)>=g?{...w,order:Number(w.order)+1}:w),{block_type:d.block_type,content:d.content,id:k.id,language_id:o.item.language_id,order:g,page_id:null,post_id:null,product_id:i}].sort((w,C)=>Number(w.order)-Number(C.order))}),productId:i,supabase:r}),await G(t,o.contentType,i,_),we([d],r),U(t,h),{blockId:k.id,blockType:k.block_type,contentType:o.contentType,entityId:o.item.id,mutationExecuted:!0,order:k.order,success:!0}}async function yt(e,t){const n=ue.parse(e),r=x(t),o=await ee(n.cmsTarget,t),{data:i,error:a}=await r.from("blocks").select("id, page_id, post_id, product_id, language_id, block_type, content, order").eq("id",n.parentBlockId).single();if(a||!i)throw new Error(`Failed to read parent block ${n.parentBlockId}: ${b(a)}`);Xt(i,o),t=await H(t,[i.block_type,i.content,n.content]);const c=oe(i.block_type,`Parent block ${n.parentBlockId}`,t);if(c!=="section")throw new Error(`Parent block ${n.parentBlockId} must be a section block, not "${c}".`);const u=_e(i.content,`Parent block ${n.parentBlockId}`);j(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 p=oe(l.block_type,`Nested block ${n.columnIndex}:${n.blockIndex}`,t);Qt(n.blockType,p,`Nested block ${n.columnIndex}:${n.blockIndex}`),j(p,n.content,`Nested block ${n.columnIndex}:${n.blockIndex}`,t);const h=u.column_blocks.map((k,I)=>I===n.columnIndex?k.map((T,w)=>w===n.blockIndex?{...T,content:n.content}:T):k),m={...u,column_blocks:h};j(c,m,`Updated parent block ${n.parentBlockId}`,t);const f=P({action:"UPDATE NESTED BLOCK",context:t,payload:{blockIndex:n.blockIndex,columnIndex:n.columnIndex,content:n.content,nestedBlockType:p,parentBlockId:n.parentBlockId,tool:"update_section_column_block"},preview:{blockIndex:n.blockIndex,columnIndex:n.columnIndex,nestedBlockType:p,parentBlockId:n.parentBlockId,parentBlockType:c},subject:`${p} nested block ${n.columnIndex}:${n.blockIndex}`});if(f)return f;const g=await W(t,o.contentType,M(o)),{data:y,error:_}=await r.from("blocks").update({content:m,updated_at:new Date().toISOString()}).eq("id",n.parentBlockId).select("id, block_type").single();if(_||!y)throw new Error(`Failed to update parent block ${n.parentBlockId}: ${b(_)}`);return await Oe({patch:({blocks:k})=>({blocks:k.map(I=>String(I?.id)===String(n.parentBlockId)?{...I,content:m}:I)}),productId:i.product_id,supabase:r}),await G(t,o.contentType,M(o),g),U(t,o),{blockIndex:n.blockIndex,columnIndex:n.columnIndex,mutationExecuted:!0,nestedBlockType:p,parentBlockId:y.id,parentBlockType:y.block_type,success:!0}}async function Le(e,t){const n=ge.parse(e);t=await H(t,n.blocks);const r=x(t),o=rt(t),i=await Fe(r,n.languageCode),a=O(n.slug||n.title),c=Be(n.blocks,n.contactEmail,n.title,t),u=await st({contentType:"page",languageId:i.id,slug:a,supabase:r});if(u)return u;const d=await ct({contentType:"page",languageCode:i.code,languageId:i.id,suppliedTranslationGroupId:n.translationGroupId,supabase:r});if(d.result)return d.result;const l={blocks:c,item:{feature_image_id:n.feature_image_id??null,language_id:i.id,meta_description:n.meta_description??null,meta_title:n.meta_title??null,slug:a,status:n.status,title:n.title,translation_group_id:d.translationGroupId},tool:"create_cms_page"},p=P({action:"CREATE PAGE",context:t,payload:l,preview:{blockCount:c.length,languageCode:i.code,slug:a,status:n.status,title:n.title,translationGroupId:d.translationGroupId},subject:a});if(p)return p;const h=d.translationGroupId||ot(),m=await Q(l.item.feature_image_id,t,n.title),{data:f,error:g}=await r.from("pages").insert({...l.item,author_id:o,feature_image_id:m,translation_group_id:h}).select("id, language_id, slug, status, title, translation_group_id").single();if(g||!f?.id)throw new Error(`Failed to create page: ${b(g)}`);try{await lt({blocks:c,contentType:"page",itemId:Number(f.id),languageId:i.id,supabase:r})}catch(y){throw await ut({contentType:"page",itemId:Number(f.id),supabase:r}),y}return U(t,{contentType:"page",entityId:Number(f.id),languageId:i.id,slug:a,title:n.title},a),t?.revalidatePath?.("/cms/pages"),{blockCount:c.length,contentType:"page",editPath:dt("page",f.id),entityId:f.id,mutationExecuted:!0,slug:a,success:!0,title:n.title,translationGroupId:f.translation_group_id}}async function Re(e,t){const n=fe.parse(e);t=await H(t,n.blocks);const r=x(t),o=rt(t),i=await Fe(r,n.languageCode),a=O(n.slug||n.title),c=Be(n.blocks,void 0,void 0,t),u=await st({contentType:"post",languageId:i.id,slug:a,supabase:r});if(u)return u;const d=await ct({contentType:"post",languageCode:i.code,languageId:i.id,suppliedTranslationGroupId:n.translationGroupId,supabase:r});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,p={blocks:c,item:{excerpt:n.excerpt??null,feature_image_id:n.feature_image_id??null,label:n.label??null,language_id:i.id,meta_description:n.meta_description??null,meta_title:n.meta_title??null,published_at:l,slug:a,status:n.status,subtitle:n.subtitle??null,title:n.title,translation_group_id:d.translationGroupId},tool:"create_cms_post"},h=P({action:"CREATE POST",context:t,payload:p,preview:{blockCount:c.length,languageCode:i.code,slug:a,status:n.status,title:n.title,translationGroupId:d.translationGroupId},subject:a});if(h)return h;const m=d.translationGroupId||ot(),f=await Q(p.item.feature_image_id,t,n.title),{data:g,error:y}=await r.from("posts").insert({...p.item,author_id:o,feature_image_id:f,translation_group_id:m}).select("id, language_id, slug, status, title, translation_group_id").single();if(y||!g?.id)throw new Error(`Failed to create post: ${b(y)}`);try{await lt({blocks:c,contentType:"post",itemId:Number(g.id),languageId:i.id,supabase:r})}catch(_){throw await ut({contentType:"post",itemId:Number(g.id),supabase:r}),_}return U(t,{contentType:"post",entityId:Number(g.id),languageId:i.id,slug:a,title:n.title},a),t?.revalidatePath?.("/cms/posts"),t?.revalidatePath?.("/articles"),{blockCount:c.length,contentType:"post",editPath:dt("post",g.id),entityId:g.id,mutationExecuted:!0,slug:a,success:!0,title:n.title,translationGroupId:g.translation_group_id}}function Mr(e,t){return(t||O(e)||"product").replace(/-/g,"").slice(0,24).toUpperCase()}function mn(e){if(e==null)return;if(typeof e=="string")return jt.editorDocumentFromHtml(e)??void 0;const t=Array.isArray(e)?{content:e,type:"doc"}:z(e)&&e.type!=="doc"&&Array.isArray(e.content)?{...e,type:"doc"}:e,n=Nt().safeParse(t);if(!n.success){if(z(e)&&typeof e.type=="string"){const r=Nt().safeParse({content:[e],type:"doc"});if(r.success)return r.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(r=>r.message).join("; ")}`)}return n.data}function jr(e){const t=o=>!!(o&&Array.isArray(o.content)&&o.content.length>0),n=mn(e.description_json);if(t(n))return n;const r=e.description_html?jt.editorDocumentFromHtml(e.description_html):null;return t(r)?r:void 0}async function bt(e,t){const n=he.parse(e);t=await H(t,n.blocks);const r=x(t),o=await Fe(r,n.languageCode),i=O(n.slug||n.title),a=Be(n.blocks,void 0,void 0,t),c=await st({contentType:"product",languageId:o.id,slug:i,supabase:r});if(c)return c;const u=await ct({contentType:"product",languageCode:o.code,languageId:o.id,suppliedTranslationGroupId:n.translationGroupId,supabase:r});if(u.result)return u.result;const{createProduct:d,productSchema:l}=await Zn(),h=n.product_type==="digital"&&n.payment_provider==="freemius"?n.trial_period_days:0,m=l.parse({description_json:jr(n),freemius_plan_id:n.freemius_plan_id||"",freemius_product_id:n.freemius_product_id||"",is_taxable:n.is_taxable,language_id:o.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||Mr(n.title,i),slug:i,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:[]}),f=n.images??[],g=P({action:"CREATE PRODUCT",context:t,payload:{blocks:a,images:f,item:m,tool:"create_cms_product"},preview:{blockCount:a.length,descriptionLength:m.description_json?JSON.stringify(m.description_json).length:0,imageCount:f.length,languageCode:o.code,price:m.price,sku:m.sku,slug:i,status:m.status,stock:m.stock,title:m.title,translationGroupId:u.translationGroupId},subject:i});if(g)return g;let y=[],_=null;if(f.length>0)try{if(y=[...new Set(await Vt(f,t,n.title))],y.length===0)throw new Error("None of the provided images could be resolved to a media item.")}catch(I){_=I instanceof Error?I.message:String(I)}const k=await d(r,{...m,product_media:y.map(I=>({media_id:I}))});if(!k?.id)throw new Error("Failed to create product.");try{await lt({blocks:a,contentType:"product",itemId:k.id,languageId:o.id,supabase:r})}catch(I){throw await ut({contentType:"product",itemId:k.id,supabase:r}),I}return U(t,{contentType:"product",entityId:k.id,languageId:o.id,slug:i,title:n.title},i),t?.revalidatePath?.("/cms/products"),{blockCount:a.length,contentType:"product",editPath:dt("product",k.id),entityId:k.id,imageCount:y.length,..._?{imageError:_}:{},mutationExecuted:!0,slug:i,success:!0,title:n.title,translationGroupId:k.translation_group_id}}function _t(e){return e.trim().replace(/[\s-]+/g,"_").toLowerCase()}function Gr(e,t){const n=typeof t=="string"?_t(t):t;return e==="product"?n==="public"||n==="publish"||n==="published"?"active":n:n==="public"||n==="active"||n==="publish"?"published":n}function Kr(e){const t=_t(e.field);return!!(e.startsAt||e.endsAt||t.includes("start")||t.includes("end")||t.includes("schedule")||t.includes("special_date"))}async function Hr(e,t,n){if(e==="price"||e==="sale_price"){if(t==null)return{[e]:null};const r=await He(n);return{[e]:ve(Number(t),r)}}if(e==="prices"||e==="sale_prices"){const r=await He(n);return{[e]:ir(t,r)}}return e==="description_json"?{description_json:mn(t)}:{[e]:t}}const Vr=new Set(["language_id","price","sale_price","stock","trial_period_days"]),Wr=new Set(["is_taxable","trial_requires_payment_method"]);function Jr(e,t){if(typeof t!="string")return t;const n=t.trim();if(Vr.has(e)){if(n.toLowerCase()==="null")return null;if(n==="")return t;const r=Number(n);return Number.isFinite(r)?r:t}if(Wr.has(e)){const r=n.toLowerCase();if(r==="true")return!0;if(r==="false")return!1}return t}function Yr(e,t){const n=_t(e.field),o={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,i=o==="status"?Gr(t.contentType,e.value):Jr(o,e.value);if(t.contentType!=="product"){if(!(t.contentType==="page"?un:dn).has(o))throw new Error(`Field "${e.field}" cannot be updated for ${t.contentType}.`);return o==="status"&&Ve(t.contentType,i),{field:o,payload:{[o]:pn(o,i)}}}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(o))throw new Error(`Field "${e.field}" cannot be updated for product.`);if(o==="status"&&Ve("product",i),(o==="price"||o==="sale_price")&&i!==null&&(typeof i!="number"||i<0))throw new Error(`${o} must be a non-negative number or null.`);if(o==="stock"&&(!Number.isInteger(i)||Number(i)<0))throw new Error("stock must be a non-negative integer.");if(o==="trial_period_days"&&(!Number.isInteger(i)||Number(i)<0))throw new Error("trial_period_days must be a non-negative integer.");if(o==="trial_requires_payment_method"&&typeof i!="boolean")throw new Error("trial_requires_payment_method must be a boolean.");return{field:o,payload:{[o]:i}}}async function wt(e,t){const n=ye.parse(e);if(Kr(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 r=await Y(n,t),o=Yr(n,r),i=o.field;let a=o.payload;if(i==="language_id"&&typeof a.language_id=="string"){const h=await Z(x(t),a.language_id);a={...a,language_id:h.id}}const c=P({action:"UPDATE FIELD",context:t,payload:{contentType:r.contentType,entityId:r.item.id,field:i,payload:a,tool:"update_cms_item_field"},preview:{contentType:r.contentType,field:i,from:r.item[i],slug:r.item.slug,title:r.item.title,to:a[i]},subject:`${r.contentType} ${r.item.slug||r.item.id} ${i}`});if(c)return c;const u=await W(t,r.contentType,r.item.id);if(r.contentType==="product"){const h=x(t),m=await Hr(i,a[i],h),{data:f,error:g}=await h.from("products").update({...m,updated_at:new Date().toISOString()}).eq("id",r.item.id).select("id, language_id, slug, status, title").single();if(g||!f)throw new Error(`Failed to update product: ${b(g)}`);return U(t,{contentType:"product",entityId:String(f.id),languageId:f.language_id,slug:f.slug,title:f.title},f.slug),await G(t,"product",f.id,u),{contentType:"product",entityId:f.id,field:i,mutationExecuted:!0,slug:f.slug,success:!0,updatedFields:[i]}}i==="feature_image_id"&&typeof a.feature_image_id=="string"&&(a={...a,feature_image_id:await Q(a.feature_image_id,t,typeof r.item.title=="string"?r.item.title:void 0)});const d=r.contentType==="page"?"pages":"posts",{data:l,error:p}=await x(t).from(d).update({...a,updated_at:new Date().toISOString()}).eq("id",r.item.id).select("id, language_id, slug, status, title").single();if(p||!l)throw new Error(`Failed to update ${r.contentType}: ${b(p)}`);return U(t,{contentType:r.contentType,entityId:Number(l.id),languageId:l.language_id,slug:l.slug,title:l.title},l.slug),await G(t,r.contentType,l.id,u),{contentType:r.contentType,entityId:l.id,field:i,mutationExecuted:!0,slug:l.slug,success:!0,updatedFields:[i]}}async function gn(e,t){const n=et.parse(e),r=await Y(n,t);if(r.contentType==="product")return{affectedCount:1,collectionPath:Ft("product"),contentType:"product",item:r.item,navigationLinkCount:0,publicPaths:r.item.slug?[`/product/${r.item.slug}`]:[],targetIds:[r.item.id]};const o=r.contentType==="page"?"pages":"posts",{data:i,error:a}=await x(t).from(o).select("id, slug, title, translation_group_id").eq("translation_group_id",r.item.translation_group_id);if(a)throw new Error(`Failed to inspect related ${r.contentType}s: ${b(a)}`);const c=Array.isArray(i)?i:[],u=c.map(m=>r.contentType==="page"?m.slug==="home"?"/":`/${m.slug}`:`/article/${m.slug}`).filter(Boolean),d=new Set(u),{data:l,error:p}=await x(t).from("navigation_items").select("id, url");if(p)throw new Error(`Failed to inspect related navigation links: ${b(p)}`);const h=(Array.isArray(l)?l:[]).filter(m=>d.has(m.url)).length;return{affectedCount:c.length,collectionPath:Ft(r.contentType),contentType:r.contentType,item:r.item,navigationLinkCount:h,publicPaths:u,targetIds:c.map(m=>m.id)}}function fn(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 r=[`${N(e.affectedCount,"language version")}`,e.navigationLinkCount>0?`${N(e.navigationLinkCount,"navigation link")}`:null].filter(Boolean);return`Delete ${e.contentType} "${t}"${n}, including ${r.join(" and ")}.`}async function hn(e,t){const n=await gn(e,t);return{...Yt({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:fn(n),title:n.item.title},subject:`${n.item.id} ${n.item.slug||""}`}),preparedDelete:!0}}async function kt(e,t){const n=be.parse(e),r=await gn(n,t),o=P({action:`DELETE ${r.contentType}`,context:t,payload:{affectedCount:r.affectedCount,contentType:r.contentType,targetIds:r.targetIds,tool:"delete_cms_item"},preview:{affectedCount:r.affectedCount,collectionPath:r.collectionPath,contentType:r.contentType,navigationLinkCount:r.navigationLinkCount,publicPaths:r.publicPaths,slug:r.item.slug,summary:fn(r),title:r.item.title},subject:`${r.item.id} ${r.item.slug||""}`});if(o)return o;const i=x(t);if(r.contentType==="product"){const{error:c}=await i.from("products").delete().eq("id",r.item.id);if(c)throw new Error(`Failed to delete product: ${b(c)}`)}else{for(const d of r.publicPaths)await i.from("navigation_items").delete().eq("url",d);const c=r.contentType==="page"?"pages":"posts",{error:u}=await i.from(c).delete().eq("translation_group_id",r.item.translation_group_id);if(u)throw new Error(`Failed to delete ${r.contentType}: ${b(u)}`)}const a=t?.revalidatePath??nt();return a&&(a(r.collectionPath),a("/cms/navigation"),r.publicPaths.forEach(c=>a(c))),{affectedCount:r.affectedCount,collectionPath:r.collectionPath,contentType:r.contentType,mutationExecuted:!0,redirectPath:r.collectionPath,success:!0}}async function Rt(e,t){switch(e.tool){case"create_cms_page":return Le(e.input,t);case"create_cms_post":return Re(e.input,t);case"create_cms_product":return bt(e.input,t);case"delete_cms_item":return kt(e.input,t);case"update_cms_item_field":return wt(e.input,t);case"update_content_block":return ft(e.input,t);case"insert_content_block":return ht(e.input,t);case"update_current_cms_fields":return gt(e.input,t);case"update_footer":return mt(e.input,t);case"update_navigation_bar":return pt(e.input,t);case"update_section_column_block":return yt(e.input,t);case"set_content_images":return zt(e.input,t)}}function Xr(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 qt(e){return e==="create_cms_page"?"page":e==="create_cms_post"?"post":"product"}function Qr(e,t,n){if(e.tool!=="set_content_images")return e;const r=e.input;if(r.entityId!==void 0)return e;const o=r.slug?t.get(`${r.contentType||"product"}:${O(r.slug)}`):n;return o?{...e,input:{...r,contentType:o.contentType,entityId:o.entityId}}:e}async function yn(e,t){const n=tt.parse(e),r=new Set(n.actions.filter(m=>m.tool==="create_cms_page"||m.tool==="create_cms_post"||m.tool==="create_cms_product").map(m=>{const f=m.input;return`${qt(m.tool)}:${O(f.slug||f.title||"")}`})),o=m=>{if(m.tool!=="set_content_images")return!1;const f=m.input;return f.slug?r.has(`${f.contentType||"product"}:${O(f.slug)}`):r.size>0};if(!t?.skipConfirmation){const m=[];for(const y of n.actions){if(o(y)){const k=y.input;m.push(`Set ${N(k.images.length,"image")} on the ${k.slug?`"${k.slug}"`:"new"} item created in this plan.`);continue}const _=await Rt(y,{...t,latestUserMessage:null});if(!_||typeof _!="object")return{message:`Could not prepare action ${m.length+1}.`,mutationExecuted:!1,success:!1};if(_.success===!1||_.unsupported===!0)return _;_.requiresConfirmation===!0&&_.preview?m.push(nr(y.tool,_.preview)):m.push(`Run ${y.tool.replace(/_/g," ")}.`)}const f=n.summary||`Complete ${N(n.actions.length,"CMS action")}.`,g=P({action:"EXECUTE CMS ACTION PLAN",context:t,payload:{actions:n.actions,tool:"execute_cms_action_plan"},preview:{actionCount:n.actions.length,actionSummaries:m,summary:f},subject:`${n.actions.length} actions`});if(g)return g}const i={...t,skipConfirmation:!0},a=[];let c=!1,u=null,d=null;const l={},p=new Map;let h=null;for(const[m,f]of n.actions.entries()){const g=Qr(Xr(f,l),p,h),y=await Rt(g,i);if(a.push({output:y,tool:g.tool}),y&&typeof y=="object"){const _=y;if(_.mutationExecuted===!0&&(c=!0),!u&&typeof _.editPath=="string"&&(u=_.editPath),typeof _.redirectPath=="string"&&(d=_.redirectPath),(g.tool==="create_cms_page"||g.tool==="create_cms_post"||g.tool==="create_cms_product")&&(typeof _.translationGroupId=="string"&&(l[g.tool]=_.translationGroupId),_.entityId!==void 0&&_.entityId!==null)){const k=qt(g.tool),I={contentType:k,entityId:_.entityId};h=I,typeof _.slug=="string"&&p.set(`${k}:${_.slug}`,I)}if(_.success===!1||_.unsupported===!0)return{actionCount:n.actions.length,failedActionIndex:m,failedTool:g.tool,message:typeof _.message=="string"?_.message:`Action ${m+1} failed.`,mutationExecuted:c,results:a,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:a,success:!0,summary:n.summary??null}}const It=s.z.strictObject({maxChars:s.z.number().int().min(500).max(2e4).default(8e3).describe("Maximum characters of readable body text to return."),url:s.z.string().trim().min(1).max(2048).refine(e=>/^https?:\/\//i.test(e),"URL must start with http:// or https://.")}),Zr=12e3,Dt=2e6;function eo(e){const t=e.match(/^::ffff:(.+)$/i);if(!t)return null;const n=t[1];if(/^\d{1,3}(\.\d{1,3}){3}$/.test(n))return n;const r=n.match(/^([0-9a-f]{1,4}):([0-9a-f]{1,4})$/i);if(!r)return null;const o=Number.parseInt(r[1],16),i=Number.parseInt(r[2],16);return[o>>8&255,o&255,i>>8&255,i&255].join(".")}function $e(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==="::"||t==="::1"||t.startsWith("fe80:")||t.startsWith("fc")||t.startsWith("fd"))return!0;const n=eo(t);if(n)return $e(n);const r=t.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/);if(r){const o=Number(r[1]),i=Number(r[2]);if(o===10||o===127||o===0||o===192&&i===168||o===169&&i===254||o===172&&i>=16&&i<=31)return!0}return!1}function Ie(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 to(e){return e.trim().replace(/&amp;/gi,"&").replace(/&#38;/g,"&").replace(/&quot;/gi,'"').replace(/&#39;/g,"'")}const bn=/\.(avif|gif|jpe?g|png|webp)(?:[?#]|$)/i,_n=/(?:^|[/_-])(?: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 ze(e,t){if(typeof e!="string")return null;const n=to(e);if(!n||n.startsWith("data:"))return null;try{const r=new URL(n,t);return r.protocol!=="http:"&&r.protocol!=="https:"?null:r.toString()}catch{return null}}function no(e){let t=null;for(const n of e.split(",")){const r=n.trim().split(/\s+/),o=r[0];if(!o)continue;const i=r[1]||"",a=i.match(/^(\d+(?:\.\d+)?)w$/i),c=i.match(/^(\d+(?:\.\d+)?)x$/i),u=a?Number(a[1]):c?Number(c[1])*1e3:1;(!t||u>t.weight)&&(t={url:o,weight:u})}return t?.url??null}function L(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 ro(e,t){const n=[],r=[],o=(c,u)=>{if(typeof c=="string"){const d=ze(c,t);d&&u.push(d);return}if(Array.isArray(c)){for(const d of c)o(d,u);return}c&&typeof c=="object"&&(o(c.url,u),o(c.contentUrl,u))},i=(c,u)=>{if(u>8||!c||typeof c!="object")return;if(Array.isArray(c)){for(const m of c)i(m,u+1);return}const d=c,l=d["@type"],h=(Array.isArray(l)?l:[l]).filter(m=>typeof m=="string").map(m=>m.toLowerCase()).some(m=>m==="product"||m==="productgroup"||m==="itempage");"image"in d&&o(d.image,h?n:r);for(const m of Object.values(d))i(m,u+1)},a=e.matchAll(/<script\b[^>]*type\s*=\s*["']application\/ld\+json["'][^>]*>([\s\S]*?)<\/script>/gi);for(const c of a){const u=(c[1]||"").trim();if(u)try{i(JSON.parse(u),0)}catch{}}return[...n,...r]}const wn=/(?:^|[/_-])(?:thumbnails?|thumbs?|small|mini)(?:[/_.-]|$)/i;function kn(e){try{const{pathname:t}=new URL(e);return decodeURIComponent(t.slice(t.lastIndexOf("/")+1)).toLowerCase()||null}catch{return null}}function oo(e,t){const n=new Map;for(const r of e.matchAll(/<a\b[^>]*>/gi)){const o=ze(L(r[0],"href"),t);if(!o||!bn.test(o)||wn.test(o)||_n.test(o))continue;const i=kn(o);i&&!n.has(i)&&n.set(i,o)}return n}function io(e,t){const n=[...ro(e,t)],r=[/<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 r)for(const p of e.matchAll(l)){const h=p[0],m=ze(L(h,"content")||L(h,"href"),t);m&&n.push(m)}const o=[];for(const l of e.matchAll(/<img\b[^>]*>/gi)){const p=l[0],h=L(p,"srcset")||L(p,"data-srcset"),m=[h?no(h):null,L(p,"src"),L(p,"data-src"),L(p,"data-original"),L(p,"data-lazy-src"),L(p,"data-image")];let f=null;for(const y of m)if(f=ze(y,t),f)break;if(!f||_n.test(f))continue;const g=Number(L(p,"width"));Number.isFinite(g)&&g>0&&g<200||o.push(f)}const i=l=>bn.test(l);n.push(...o.filter(i),...o.filter(l=>!i(l)));const a=oo(e,t),c=l=>{if(!wn.test(l))return l;const p=kn(l);return p&&a.get(p)||l},u=new Set,d=[];for(const l of n){const p=c(l);if(!u.has(p)&&(u.add(p),d.push(p),d.length>=12))break}return{images:d,mainImage:d[0]??null}}function ao(e,t,n){const r=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:o,mainImage:i}=io(e,n),a=e.match(/<title\b[^>]*>([\s\S]*?)<\/title>/i),c=e.match(/<meta[^>]+name=["']description["'][^>]*content=["']([^"']*)["'][^>]*>/i)||e.match(/<meta[^>]+content=["']([^"']*)["'][^>]*name=["']description["'][^>]*>/i),u=[...r.matchAll(/<h([1-3])\b[^>]*>([\s\S]*?)<\/h\1>/gi)].map(p=>Ie(p[2])).filter(Boolean).slice(0,40),d=r.match(/<body\b[^>]*>([\s\S]*?)<\/body>/i),l=Ie(d?.[1]??r);return{description:c?Ie(c[1]):"",headings:u,images:o,mainImage:i,text:l.slice(0,t),title:a?Ie(a[1]):"",truncated:l.length>t}}async function In(e){const t=It.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($e(n.hostname))return{message:"Refusing to fetch a local, private, or internal address.",success:!1,url:t.url};const r=new AbortController,o=setTimeout(()=>r.abort(),Zr);try{const i=await fetch(n.toString(),{headers:{accept:"text/html,application/xhtml+xml,text/plain","user-agent":"NextBlockCortexAI/1.0 (+https://nextblock.dev)"},redirect:"follow",signal:r.signal});if(!i.ok)return{message:`The URL responded with HTTP ${i.status}.`,status:i.status,success:!1,url:t.url};const a=i.url||n.toString();try{if($e(new URL(a).hostname))return{message:"The URL redirected to a blocked internal address.",success:!1,url:t.url}}catch{}const c=i.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 i.text(),d=u.length>Dt?u.slice(0,Dt):u,l=ao(d,t.maxChars,a);return!l.text&&!l.title?{message:"The URL returned no readable text content.",success:!1,url:t.url}:{description:l.description,finalUrl:a,headings:l.headings,images:l.images,mainImage:l.mainImage,success:!0,text:l.text,title:l.title,truncated:l.truncated,url:t.url}}catch(i){return{message:i instanceof Error&&(i.name==="AbortError"||/abort/i.test(i.message))?"Fetching the URL timed out.":`Failed to fetch the URL: ${b(i)}`,success:!1,url:t.url}}finally{clearTimeout(o)}}const Tt=s.z.strictObject({count:s.z.number().int().min(1).max(15).default(6),orientation:s.z.enum(["landscape","portrait","square"]).optional().describe("Preferred image orientation. Use landscape for hero/section backgrounds."),query:s.z.string().trim().min(2).max(200).describe('What the photos should depict, e.g. "herbal supplements".')}),so=12e3;async function qe(e){let t=null,n=null;if(e)try{const{CORTEX_AI_PEXELS_SETTING_KEY:o,CORTEX_AI_UNSPLASH_SETTING_KEY:i,decryptStoredOpenRouterApiKey:a}=await Promise.resolve().then(()=>require("./ai-config.cjs.js")),c=l=>{if(!l)return null;try{const p=a(l);return typeof p=="string"&&p.trim()?p.trim():null}catch{return null}},{data:u}=await e.from("site_settings").select("key, value").in("key",[o,i]),d=Array.isArray(u)?u:[];t=c(d.find(l=>l.key===o)?.value),n=c(d.find(l=>l.key===i)?.value)}catch{}t||(t=process.env.PEXELS_API_KEY?.trim()||null),n||(n=process.env.UNSPLASH_ACCESS_KEY?.trim()||null);const r=[];return t&&r.push({apiKey:t,provider:"pexels"}),n&&r.push({apiKey:n,provider:"unsplash"}),r}async function co(e){return(await qe(e))[0]??null}async function lo(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(),r=n?.value;if(typeof r=="string"&&r.trim())return r.trim()}catch{}return process.env.UNSPLASH_APP_NAME?.trim()||null}async function Mt(e,t){const n=new AbortController,r=setTimeout(()=>n.abort(),so);try{const o=await fetch(e,{headers:t,signal:n.signal});if(!o.ok)throw new Error(`Stock photo provider responded with HTTP ${o.status}.`);return await o.json()}finally{clearTimeout(r)}}function Te(e){const t=Number(e);return Number.isFinite(t)&&t>0?t:null}function We(e,t){if(!z(e))return;const n=r=>{z(r)&&r.provider==="unsplash"&&typeof r.downloadLocation=="string"&&r.downloadLocation.trim()&&t.add(r.downloadLocation.trim())};if(n(e.attribution),z(e.background)&&z(e.background.image)&&n(e.background.image.attribution),Array.isArray(e.column_blocks)){for(const r of e.column_blocks)if(Array.isArray(r))for(const o of r)z(o)&&We(o.content,t)}if(Array.isArray(e.slides))for(const r of e.slides)We(r,t)}async function we(e,t){try{const n=new Set;for(const i of e)We(i?.content,n);if(n.size===0)return;const o=(await qe(t)).find(i=>i.provider==="unsplash");if(!o)return;await Promise.all([...n].map(i=>fetch(i,{headers:{Authorization:`Client-ID ${o.apiKey}`}}).catch(()=>{})))}catch{}}async function uo(e,t,n){const r=new URLSearchParams({per_page:String(t.count),query:t.query});if(t.orientation&&r.set("orientation",t.orientation),e.provider==="pexels"){const i=await Mt(`https://api.pexels.com/v1/search?${r.toString()}`,{Authorization:e.apiKey});return(Array.isArray(i?.photos)?i.photos:[]).map(a=>{const c=typeof a?.photographer=="string"?a.photographer:null;return{alt:typeof a?.alt=="string"&&a.alt.trim()?a.alt.trim():t.query,credit:c?`Photo by ${c} on Pexels`:"Photo on Pexels",downloadLocation:null,height:Te(a?.height),photographer:c,photographerUrl:typeof a?.photographer_url=="string"?a.photographer_url:null,provider:"pexels",sourceUrl:typeof a?.url=="string"?a.url:null,thumbnailUrl:a?.src?.medium||a?.src?.large||null,url:a?.src?.large2x||a?.src?.large||a?.src?.original||null,width:Te(a?.width)}}).filter(a=>typeof a.url=="string")}const o=await Mt(`https://api.unsplash.com/search/photos?${r.toString()}`,{Authorization:`Client-ID ${e.apiKey}`});return(Array.isArray(o?.results)?o.results:[]).map(i=>{const a=typeof i?.user?.name=="string"?i.user.name:null;return{alt:typeof i?.alt_description=="string"&&i.alt_description.trim()||typeof i?.description=="string"&&i.description.trim()||t.query,credit:a?`Photo by ${a} on Unsplash`:"Photo on Unsplash",downloadLocation:typeof i?.links?.download_location=="string"?i.links.download_location:null,height:Te(i?.height),photographer:a,photographerUrl:typeof i?.user?.links?.html=="string"?i.user.links.html:null,provider:"unsplash",sourceUrl:typeof i?.links?.html=="string"?i.links.html:null,thumbnailUrl:i?.urls?.small||i?.urls?.thumb||null,url:i?.urls?.regular||i?.urls?.full||i?.urls?.raw||null,utmSource:n||null,width:Te(i?.width)}}).filter(i=>typeof i.url=="string")}async function Tn(e,t){const n=Tt.parse(e),r=await qe(t?.supabase);if(r.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 o=r.some(c=>c.provider==="unsplash")?await lo(t?.supabase):null,i=[];let a=null;for(const c of r){i.push(c.provider);try{const u=await uo(c,n,o);if(u.length>0)return{attemptedProviders:i,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){a=u}}return{attemptedProviders:i,message:a?`Stock photo search failed across ${i.join(", ")}: ${b(a)}`:`No matching stock photos found for "${n.query}".`,photos:[],success:!1}}const Ct=J.extend({blocks:s.z.array(de).min(1).max(20),meta:s.z.strictObject({meta_description:s.z.string().max(500).nullable().optional(),meta_title:s.z.string().max(160).nullable().optional(),slug:s.z.string().trim().min(1).max(300).optional(),status:s.z.enum(["draft","published","archived"]).optional(),title:s.z.string().trim().min(1).max(300).optional()}).partial().optional()}),po=["custom_canonical","excerpt","feature_image_id","label","language_id","meta_description","meta_title","published_at","slug","status","subtitle","title","translation_group_id"];function mo(e){const t={};for(const n of po)n in e&&e[n]!==void 0&&(t[n]=e[n]);return t}function go(e,t){if(!t)return null;const n=e==="page"?t==="home"?"/":`/${t}`:`/article/${t}`;return`/api/draft/start?path=${encodeURIComponent(n)}`}async function Cn(e,t){const n=Ct.parse(e);t=await H(t,n.blocks);const r=x(t),o=rt(t),i=await Y(n,t);if(i.contentType==="product")throw new Error("rewrite_page_draft supports pages and posts only. Products use description_json, not page blocks.");const a=i.contentType,c=Number(i.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(i.item.language_id);if(!Number.isInteger(u)||u<=0)throw new Error("The target page/post is missing a language id.");const l=Be(n.blocks,void 0,void 0,t).map((w,C)=>({block_type:w.block_type,content:w.content,language_id:u,order:C,page_id:a==="page"?c:null,post_id:a==="post"?c:null,product_id:null})),p=mo(i.item);if(n.meta)for(const[w,C]of Object.entries(n.meta))C!==void 0&&(p[w]=C);const h=Wt(typeof p.slug=="string"?p.slug:i.item.slug),m=typeof p.title=="string"&&p.title.trim()?p.title:String(i.item.title||h||"Untitled"),f=a==="page"?`/cms/pages/${c}/edit`:`/cms/posts/${c}/edit`,g=go(a,h),_=P({action:"REWRITE DRAFT",context:t,payload:{blocks:l,meta:p,parent_id:c,parent_type:a,tool:"rewrite_page_draft"},preview:{blockCount:l.length,contentType:a,slug:h,summary:`Stage a Live Draft that replaces the ${a} "${m}" with ${N(l.length,"new block")}. Nothing goes live until you review the draft and click Publish (which also saves a revision snapshot).`,title:m},subject:`${a}-${c}`});if(_)return _;const k=Number(i.item.version)||1,{error:I}=await r.from("content_drafts").delete().eq("parent_type",a).eq("parent_id",c);if(I)throw new Error(`Failed to clear the existing draft: ${b(I)}`);const{error:T}=await r.from("content_drafts").insert({author_id:o,base_version:k,blocks:l,meta:p,parent_id:c,parent_type:a});if(T)throw new Error(`Failed to save the draft: ${b(T)}`);return we(l,r),U(t,{contentType:a,entityId:c,slug:h},h),{blockCount:l.length,contentType:a,draftPreviewPath:g,editPath:f,entityId:c,isDraft:!0,mutationExecuted:!0,slug:h,success:!0,title:m}}const vt=s.z.strictObject({attributes:s.z.array(s.z.strictObject({name:s.z.string().trim().min(1).max(120).describe('Attribute name, e.g. "Size" or "Flavour".'),terms:s.z.array(s.z.string().trim().min(1).max(120)).min(1).max(50).describe('Every possible value for this attribute, e.g. ["100 ml", "500 ml"].')})).max(5).optional().describe("The option axes this product varies on. Attributes and terms are global and reused across products: an existing one with the same name is matched, never duplicated. Omit if the attributes already exist."),entityId:s.z.union([s.z.number().int().positive(),s.z.string().trim().min(1).max(120)]).optional(),mode:s.z.enum(["replace","append"]).default("replace").describe(`"replace" removes the product's existing variants first; "append" keeps them and adds these.`),slug:s.z.string().trim().min(1).max(300).optional(),title:s.z.string().trim().min(1).max(300).optional(),variants:s.z.array(s.z.strictObject({image:s.z.string().trim().min(1).max(2048).optional().describe("Variant-specific image: an https:// URL (imported automatically) or a media library id."),options:s.z.record(s.z.string(),s.z.string()).describe('Which term this variant is, per attribute, e.g. { "Size": "500 ml" }. Every attribute must be given a value.'),price:s.z.number().min(0).optional().describe("Price in major units (25 = $25.00). Defaults to the product price."),sale_price:s.z.number().min(0).nullable().optional().describe("Sale price in major units, or null for none."),sku:s.z.string().trim().min(1).max(120).describe("Unique SKU for this variant."),stock:s.z.number().int().min(0).default(0),upc:s.z.string().trim().max(120).nullable().optional()})).min(1).max(50)});async function fo(e,t){const n=O(t.name),{data:r}=await e.from("product_attributes").select("id").eq("slug",n).maybeSingle();let o=r?.id;if(!o){const{data:a,error:c}=await e.from("product_attributes").insert({name:t.name,slug:n}).select("id").single();if(c||!a?.id)throw new Error(`Could not create the "${t.name}" attribute: ${b(c)}`);o=a.id}const i=new Map;for(let a=0;a<t.terms.length;a+=1){const c=t.terms[a],u=O(c),{data:d}=await e.from("product_attribute_terms").select("id").eq("attribute_id",o).eq("slug",u).maybeSingle();if(d?.id){i.set(c,d.id);continue}const{data:l,error:p}=await e.from("product_attribute_terms").insert({attribute_id:o,slug:u,sort_order:a,value:c}).select("id").single();if(p||!l?.id)throw new Error(`Could not create the "${c}" option: ${b(p)}`);i.set(c,l.id)}return{attributeId:o,termIdByValue:i}}async function vn(e,t){const n=vt.parse(e),r=x(t),i=(await Y({contentType:"product",...n.entityId!==void 0?{entityId:n.entityId}:{},...n.slug?{slug:n.slug}:{},...n.title?{title:n.title}:{}},t)).item,a=String(i.id),c=P({action:"SET VARIANTS",context:t,payload:{entityId:a,mode:n.mode,variantCount:n.variants.length},preview:{contentType:"product",slug:i.slug,summary:`${n.mode==="replace"?"Replace":"Add"} ${N(n.variants.length,"variant")} on "${i.title}". Product stock becomes the sum of variant stock.`,title:i.title},subject:`product-${a}-variants`});if(c)return c;const u=new Map;for(const g of n.attributes??[]){const{termIdByValue:y}=await fo(r,g);u.set(g.name,y)}for(const g of n.variants)for(const[y,_]of Object.entries(g.options)){if(u.get(y)?.has(_))continue;const{data:k}=await r.from("product_attributes").select("id").eq("slug",O(y)).maybeSingle();if(!k?.id)throw new Error(`Unknown attribute "${y}". Pass it in \`attributes\` with its full list of terms.`);const{data:I}=await r.from("product_attribute_terms").select("id").eq("attribute_id",k.id).eq("slug",O(_)).maybeSingle();if(!I?.id)throw new Error(`Unknown option "${_}" for attribute "${y}". Add it to that attribute's \`terms\`.`);const T=u.get(y)??new Map;T.set(_,I.id),u.set(y,T)}if(n.mode==="replace"){const{error:g}=await r.from("product_variants").delete().eq("product_id",a);if(g)throw new Error(`Could not clear the existing variants: ${b(g)}`)}const d=await He(r),l=Number(i.price)||0,p=[];for(const g of n.variants){const y=g.image?await Q(g.image,t,`${i.title} ${g.sku}`):null,{data:_,error:k}=await r.from("product_variants").insert({main_media_id:y,price:g.price===void 0?l:ve(g.price,d),product_id:a,sale_price:g.sale_price===void 0||g.sale_price===null?null:ve(g.sale_price,d),sku:g.sku,stock_quantity:g.stock,upc:g.upc??null}).select("id").single();if(k||!_?.id)throw new Error(`Could not create variant "${g.sku}": ${b(k)}`);const I=Object.entries(g.options).map(([T,w])=>({attribute_term_id:u.get(T)?.get(w),variant_id:_.id}));if(I.length>0){const{error:T}=await r.from("variant_attribute_mapping").insert(I);if(T)throw new Error(`Could not link variant "${g.sku}" to its options: ${b(T)}`)}p.push(g.sku)}const{data:h}=await r.from("product_variants").select("stock_quantity").eq("product_id",a),m=(h??[]).reduce((g,y)=>g+(Number(y?.stock_quantity)||0),0),{error:f}=await r.from("products").update({stock:m}).eq("id",a);if(f)throw new Error(`Variants saved, but the product stock total failed: ${b(f)}`);return U(t,{contentType:"product",entityId:a,slug:i.slug,title:i.title},i.slug),{contentType:"product",entityId:a,mode:n.mode,mutationExecuted:!0,skus:p,slug:i.slug,success:!0,totalStock:m,variantCount:p.length}}const St=s.z.strictObject({items:s.z.array(s.z.strictObject({contentType:s.z.enum(["page","post"]).default("page"),slug:s.z.string().trim().min(1).max(300).describe("Slug of the source page or post."),title:s.z.string().trim().min(1).max(300).optional().describe("Translated title. Defaults to translating the source title."),translations:s.z.record(s.z.string(),s.z.string()).describe("Source string -> translated string for every visible string in THIS item.")})).min(1).max(25),targetLanguageCode:s.z.string().trim().min(2).max(80).describe('Target language code or name, e.g. "fr". The language must already exist — create it with manage_language first.')});async function Sn(e,t){const n=St.parse(e),r=P({action:"TRANSLATE BULK",context:t,payload:{count:n.items.length,language:n.targetLanguageCode},preview:{contentType:"page",summary:`Create ${n.targetLanguageCode} translations of ${N(n.items.length,"item")}: ${n.items.map(a=>a.slug).join(", ")}.`,title:`Bulk translate to ${n.targetLanguageCode}`},subject:`bulk-translate-${n.targetLanguageCode}`});if(r)return r;const o=[],i=[];for(const a of n.items)try{const c=await $t({cmsTarget:{contentType:a.contentType,slug:a.slug},targetLanguageCode:n.targetLanguageCode,...a.title?{title:a.title}:{},translations:a.translations},t);o.push({slug:a.slug,...c})}catch(c){i.push({error:c instanceof Error?c.message:String(c),slug:a.slug})}return{failed:i,failedCount:i.length,mutationExecuted:o.length>0,success:i.length===0,targetLanguageCode:n.targetLanguageCode,translated:o,translatedCount:o.length}}const xt=s.z.strictObject({action:s.z.enum(["publish","discard"]).default("publish").describe('"publish" applies the draft to the live page/post; "discard" deletes it and leaves the live content untouched.'),contentType:s.z.enum(["page","post"]).optional(),entityId:s.z.union([s.z.number().int().positive(),s.z.string().trim().min(1).max(120)]).optional(),slug:s.z.string().trim().min(1).max(300).optional(),title:s.z.string().trim().min(1).max(300).optional()}),ho=["title","slug"],yo=["custom_canonical","feature_image_id","meta_description","meta_title"];async function xn(e,t){const n=xt.parse(e),r=x(t),o=await ee({...n.contentType?{contentType:n.contentType}:{},...n.entityId!==void 0?{entityId:n.entityId}:{},...n.slug?{slug:n.slug}:{},...n.title?{title:n.title}:{}},t);if(o.contentType==="product")throw new Error("publish_content_draft supports pages and posts. Product drafts live in product_drafts and are published from the product editor.");const i=o.contentType,a=Ue(o),c=i==="page"?"pages":"posts",{data:u,error:d}=await r.from("content_drafts").select("*").eq("parent_type",i).eq("parent_id",a).maybeSingle();if(d)throw new Error(`Failed to read the draft: ${b(d)}`);if(!u)return{contentType:i,entityId:a,message:`No Live Draft exists for ${i} "${o.title||o.slug}". Nothing to ${n.action}.`,mutationExecuted:!1,success:!1};const l=o.title||o.slug||`${i} ${a}`,p=P({action:n.action==="publish"?"PUBLISH DRAFT":"DISCARD DRAFT",context:t,payload:{action:n.action,contentType:i,entityId:String(a)},preview:{contentType:i,slug:o.slug,summary:n.action==="publish"?`Publish the Live Draft for ${i} "${l}", replacing its live blocks. A revision snapshot is saved first, so this is reversible from Revision History.`:`Discard the Live Draft for ${i} "${l}". The live content is left untouched.`,title:o.title},subject:`${i}-${a}-draft`});if(p)return p;const h=u.meta??{},m=Array.isArray(u.blocks)?u.blocks:[];if(n.action==="discard"){const{error:w}=await r.from("content_drafts").delete().eq("id",u.id);if(w)throw new Error(`Failed to discard the draft: ${b(w)}`);return U(t,o,o.slug),{action:"discard",contentType:i,entityId:a,mutationExecuted:!0,success:!0}}const f=await W(t,i,a),g={};for(const w of ho){const C=h[w];typeof C=="string"&&C.trim()&&(g[w]=C.trim())}for(const w of yo)if(Object.prototype.hasOwnProperty.call(h,w)){const C=h[w];g[w]=typeof C=="string"&&C.trim()?C.trim():null}if(Object.keys(g).length>0){const{error:w}=await r.from(c).update(g).eq("id",a);if(w)throw new Error(`Failed to apply the draft metadata: ${b(w)}`)}const y=i==="page"?"page_id":"post_id",{error:_}=await r.from("blocks").delete().eq(y,a);if(_)throw new Error(`Failed to clear the live blocks: ${b(_)}`);const k=Number(h.language_id)||Number(o.languageId)||Number(m[0]?.language_id)||0;if(m.length>0){const w=m.map((E,F)=>({block_type:E?.block_type,content:E?.content??{},language_id:Number(E?.language_id)||k,order:Number.isFinite(E?.order)?E.order:F,page_id:i==="page"?a:null,post_id:i==="post"?a:null,product_id:null})),{error:C}=await r.from("blocks").insert(w);if(C)throw new Error(`Failed to publish the draft blocks: ${b(C)}`)}await G(t,i,a,f);const{error:I}=await r.from("content_drafts").delete().eq("id",u.id),T=typeof g.slug=="string"?g.slug:o.slug;return U(t,{...o,slug:T},T??void 0),{action:"publish",blockCount:m.length,contentType:i,entityId:a,mutationExecuted:!0,slug:T,success:!0,...I?{warning:`Published, but the draft row was not removed: ${b(I)}`}:{}}}const bo=new Set(["alt_text","author_name","author_title","caption","html_content","label","placeholder","quote","submit_button_text","success_message","text","text_content","title"]);function Je(e,t,n){if(!e)return e;if(Object.prototype.hasOwnProperty.call(t,e))return t[e];const r=e.trim();if(r!==e&&Object.prototype.hasOwnProperty.call(t,r))return e.replace(r,t[r]);let o=e;for(const[i,a]of n)i&&o.includes(i)&&(o=o.split(i).join(a));return o}function Ye(e,t,n,r){if(Array.isArray(e))return e.map(o=>Ye(o,t,n,r));if(e&&typeof e=="object"){const o={};for(const[i,a]of Object.entries(e))typeof a=="string"&&(bo.has(i)||r?.has(i))?o[i]=Je(a,t,n):a&&typeof a=="object"?o[i]=Ye(a,t,n,r):o[i]=a;return o}return e}function _o(e,t){if(typeof e!="string"||R.isValidBlockType(e))return;const n=at(e,t);if(n)return new Set(R.readCustomBlockFields(n).filter(r=>r.type==="text"||r.type==="rich-text").map(r=>r.key))}const Et=s.z.strictObject({cmsTarget:se,targetLanguageCode:s.z.string().trim().min(2).max(80).describe('Target language code or name, e.g. "fr" or "French".'),title:s.z.string().trim().min(1).max(300).optional().describe("Translated page title (defaults to translating the source title)."),translations:s.z.record(s.z.string(),s.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 $t(e,t){const n=Et.parse(e),r=await ee(n.cmsTarget,t);if(r.contentType==="product")throw new Error("translate_page supports pages and posts only.");const o=x(t),i=Ue(r),a=r.contentType==="page"?"pages":"posts",c=r.contentType==="page"?"page_id":"post_id",{data:u,error:d}=await o.from(a).select("*").eq("id",i).single();if(d||!u)throw new Error(`Could not read the source ${r.contentType} to translate: ${b(d)}`);const{data:l,error:p}=await o.from("blocks").select("id, block_type, content, order").eq(c,i);if(p)throw new Error(`Could not read the source blocks: ${b(p)}`);const h=(Array.isArray(l)?l:[]).slice().sort((v,A)=>Number(v.order)-Number(A.order));if(h.length===0)throw new Error(`The source ${r.contentType} has no content blocks to translate.`);t=await H(t,h);const m=n.translations||{},f=Object.entries(m).filter(([v])=>!!v).sort((v,A)=>A[0].length-v[0].length),g=h.map((v,A)=>({blockType:v.block_type,content:Ye(K(v.content),m,f,_o(v.block_type,t)),order:A})),y=await Fe(o,n.targetLanguageCode),_=String(u.title||""),k=n.title||Je(_,m,f)||_||"Untitled",I=v=>typeof v=="string"&&v.trim()?Je(v,m,f):void 0,T=O(k)||u.slug||"translated-page",w={blocks:g,feature_image_id:u.feature_image_id??void 0,languageCode:y.code,meta_description:I(u.meta_description),meta_title:I(u.meta_title),slug:T,status:"published",title:k,translationGroupId:u.translation_group_id||void 0},C=r.contentType==="post"?{...w,excerpt:I(u.excerpt),label:I(u.label),published_at:u.published_at??new Date().toISOString(),subtitle:I(u.subtitle)}:w,E=P({action:"TRANSLATE",context:t,payload:{createInput:C,sourceId:u.id,tool:"translate_page"},preview:{blockCount:g.length,contentType:r.contentType,languageCode:y.code,slug:w.slug,status:w.status,summary:`Publish a ${y.code.toUpperCase()} translation of "${_}" — it goes live immediately, linked to the original ${r.contentType}, at /${w.slug} with ${N(g.length,"translated block")}.`,title:k},subject:`translate ${r.contentType} ${u.id} to ${y.code}`});if(E)return E;const F={...t,skipConfirmation:!0};return{...r.contentType==="post"?await Re(C,F):await Le(C,F),isTranslation:!0,languageCode:y.code}}async function zt(e,t){const n=pe.parse(e),r=n.entityId!==void 0||!!n.slug||!!n.title,o=x(t);let i,a;if(r){const g=await Y({contentType:n.contentType,entityId:n.entityId,slug:n.slug,title:n.title},t),y=g.item;a=y.id,i={contentType:g.contentType,entityId:a,slug:typeof y.slug=="string"?y.slug:"",title:typeof y.title=="string"?y.title:""}}else i=Vn(t),a=M(i);const c=i.title||i.slug||"current item",u=i.contentType==="product",d=P({action:"SET IMAGES",context:t,payload:{contentType:i.contentType,entityId:String(a),images:n.images,tool:"set_content_images"},preview:{contentType:i.contentType,imageCount:n.images.length,slug:i.slug,summary:u?`Set ${N(n.images.length,"image")} on product "${c}" (the first becomes the main product image, the rest the gallery).`:`Set the feature image on the ${i.contentType} "${c}".`,title:i.title},subject:`set images on ${i.contentType} ${String(a)}`});if(d)return d;const l=await Vt(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:y}=await o.from("products").select("id, slug, language_id, title").eq("id",a).maybeSingle();if(y||!g)throw new Error(`Could not load the product to set images: ${b(y)}`);const _=await Yn({mediaIds:l,productId:a,supabase:o});return await Oe({patch:({meta:k})=>Array.isArray(k.product_media)?{meta:{...k,product_media:_.map((I,T)=>({media_id:I,sort_order:T}))}}:{},productId:a,supabase:o}),U(t,{contentType:"product",entityId:String(a),languageId:g.language_id,slug:g.slug,title:g.title},g.slug),t?.revalidatePath?.("/cms/products"),{contentType:"product",entityId:a,imageCount:_.length,mutationExecuted:!0,slug:g.slug,success:!0}}const p=await W(t,i.contentType,a),h=i.contentType==="page"?"pages":"posts",{data:m,error:f}=await o.from(h).update({feature_image_id:l[0],updated_at:new Date().toISOString()}).eq("id",a).select("id, language_id, slug, status, title").single();if(f||!m)throw new Error(`Failed to set the feature image: ${b(f)}`);return await G(t,i.contentType,a,p),U(t,i,m.slug),{contentType:i.contentType,entityId:a,extraImagesIgnored:l.length-1,imageCount:1,mutationExecuted:!0,slug:m.slug,success:!0}}function wo(e){return{...En.createCortexDatabaseAgentTools(e),...$n.createCortexCustomBlockTools(e),...zn.createCortexContentOpsTools(e),...An.createCortexThemingTools(e),...Pn.createCortexSiteTools(e),fetch_ecommerce_stats:S.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=>cn(t,e),inputSchema:Qe,strict:!0}),read_current_cms_item:S.tool({description:"Read a CMS item: page/post/product metadata plus page/post block summaries or content. Defaults to the item currently open in the CMS editor; with no editor open (MCP clients) pass `cmsTarget` with contentType plus slug, entityId, or title. Read-only.",execute:t=>ln(t,e),inputSchema:Ze,strict:!0}),search_documentation:S.tool({description:"Search the NextBlock documentation database and return concise source snippets for factual CMS guidance.",execute:t=>sn(t,e),inputSchema:Ae,strict:!0}),fetch_url_content:S.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=>In(t),inputSchema:It,strict:!0}),search_stock_photos:S.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=>Tn(t,e),inputSchema:Tt,strict:!0}),manage_product_variants:S.tool({description:'Give a product sellable variations — size, flavour, colour, format — each with its own SKU, price, stock, and optional image. Define the option axes in `attributes` (name plus every term) and one entry in `variants` per purchasable combination, naming its term per attribute in `options`. Attributes and terms are global and reused across products, so an existing "Size" is matched rather than duplicated. Prices are in major units (25 = $25.00). The product\'s stock becomes the sum of its variants. Use mode "replace" to rebuild the variant set, "append" to add to it. Mutating: first returns a confirmation phrase; only executes after exact confirmation.',execute:t=>vn(t,e),inputSchema:vt,strict:!0}),translate_content_bulk:S.tool({description:"Translate SEVERAL pages or posts into one language in a single call. Use this instead of repeating translate_page when making a site multilingual: pass the target language once and one entry per item, each with its own source-string -> translation map. Layout, blocks, and imagery are copied automatically and each copy is linked to its original as a translation. The language must exist first (manage_language). Items are processed independently, so one bad entry does not abandon the rest — check `failed` in the result. Mutating: first returns a confirmation phrase; only executes after exact confirmation.",execute:t=>Sn(t,e),inputSchema:St,strict:!0}),publish_content_draft:S.tool({description:"Publish (or discard) the Live Draft staged on a page or post by generate_jsonb_layout / rewrite_page_draft. Publishing applies the draft blocks and metadata to the live record and snapshots a revision first, so it is reversible from Revision History; visibility (status/published_at) is never changed. Use this to finish a build that staged a draft — without it the new layout stays invisible on the public site. Target the record with contentType plus slug, entityId, or title. Mutating: first returns a confirmation phrase; only executes after exact confirmation.",execute:t=>xn(t,e),inputSchema:xt,strict:!0}),rewrite_page_draft:S.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=>Cn(t,e),inputSchema:Ct,strict:!0}),translate_page:S.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. Targets the open page/post by default; with no editor open (MCP clients) pass `cmsTarget` with contentType plus slug, entityId, or title. Mutating: first returns a confirmation phrase; only creates the translation after exact confirmation.',execute:t=>$t(t,e),inputSchema:Et,strict:!0}),set_content_images:S.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=>zt(t,e),inputSchema:pe,strict:!0}),create_cms_page:S.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 a form block with fields; the destination address is configured once in CMS -> Messages and is never stored on the block.",execute:t=>Le(t,e),inputSchema:ge,strict:!0}),create_cms_post:S.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=>Re(t,e),inputSchema:fe,strict:!0}),create_cms_product:S.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=>bt(t,e),inputSchema:he,strict:!0}),delete_cms_item:S.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=>kt(t,e),inputSchema:be,strict:!0}),prepare_delete_cms_item:S.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=>hn(t,e),inputSchema:et,strict:!0}),update_footer:S.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=>mt(t,e),inputSchema:ae,strict:!0}),update_content_block:S.tool({description:'Update the JSON content of an existing top-level page/post block. The block must belong to the item being edited — the open CMS editor, or the item named by `cmsTarget` (contentType plus slug, entityId, or title) when no editor is open, as with MCP clients. 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=>ft(t,e),inputSchema:le,strict:!0}),insert_content_block:S.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=>ht(t,e),inputSchema:me,strict:!0}),update_current_cms_fields:S.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=>gt(t,e),inputSchema:ce,strict:!0}),update_cms_item_field:S.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=>wt(t,e),inputSchema:ye,strict:!0}),update_navigation_bar:S.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=>pt(t,e),inputSchema:ie,strict:!0}),update_section_column_block:S.tool({description:"Update the content of one existing nested block inside a section block. The parent section must belong to the item being edited — the open CMS editor, or the item named by `cmsTarget` (contentType plus slug, entityId, or title) when no editor is open, as with MCP clients. 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=>yt(t,e),inputSchema:ue,strict:!0}),execute_cms_action_plan:S.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=>yn(t,e),inputSchema:tt,strict:!0})}}exports.buildVisibleContactIntroActionPlan=Kn;exports.cortexAiPageContextSchema=Pe;exports.createCmsPageInputSchema=ge;exports.createCmsPostInputSchema=fe;exports.createCmsProductInputSchema=he;exports.createCortexGlobalAgentTools=wo;exports.deleteCmsItemInputSchema=be;exports.executeCmsActionPlan=yn;exports.executeCmsActionPlanInputSchema=tt;exports.executeCreateCmsPage=Le;exports.executeCreateCmsPost=Re;exports.executeCreateCmsProduct=bt;exports.executeDeleteCmsItem=kt;exports.executeFetchEcommerceStats=cn;exports.executeFetchUrlContent=In;exports.executeInsertContentBlock=ht;exports.executeManageProductVariants=vn;exports.executePrepareDeleteCmsItem=hn;exports.executePublishContentDraft=xn;exports.executeReadCurrentCmsItem=ln;exports.executeRewritePageDraft=Cn;exports.executeSearchDocumentation=an;exports.executeSearchDocumentationWithTimeout=sn;exports.executeSearchStockPhotos=Tn;exports.executeSetContentImages=zt;exports.executeTranslateContentBulk=Sn;exports.executeTranslatePage=$t;exports.executeUpdateCmsItemField=wt;exports.executeUpdateContentBlock=ft;exports.executeUpdateCurrentCmsFields=gt;exports.executeUpdateFooter=mt;exports.executeUpdateNavigationBar=pt;exports.executeUpdateSectionColumnBlock=yt;exports.fetchEcommerceStatsInputSchema=Qe;exports.fetchUrlContentInputSchema=It;exports.insertContentBlockInputSchema=me;exports.isBlockedFetchHost=$e;exports.manageProductVariantsInputSchema=vt;exports.maybeTriggerStockPhotoDownloads=we;exports.navigationItemInputSchema=Xe;exports.prepareDeleteCmsItemInputSchema=et;exports.publishContentDraftInputSchema=xt;exports.readCurrentCmsItemInputSchema=Ze;exports.resolveCortexAiStockPhotoProvider=co;exports.resolveCortexAiStockPhotoProviders=qe;exports.rewritePageDraftInputSchema=Ct;exports.searchDocumentationInputSchema=Ae;exports.searchStockPhotosInputSchema=Tt;exports.setContentImagesInputSchema=pe;exports.translateContentBulkInputSchema=St;exports.translatePageInputSchema=Et;exports.updateCmsItemFieldInputSchema=ye;exports.updateContentBlockInputSchema=le;exports.updateCurrentCmsFieldsInputSchema=ce;exports.updateFooterInputSchema=ae;exports.updateNavigationBarInputSchema=ie;exports.updateSectionColumnBlockInputSchema=ue;
15
+ `).eq("orders.status","paid"):null;m&&(c&&m.eq("orders.currency",c),i&&m.gte("orders.paid_at",i.toISOString()),a&&m.lte("orders.paid_at",a.toISOString()));const g=n.timeRange!=="all_time"&&(n.reportType==="orders"||u)?r.from("orders").select("id, status, currency"):null;g&&c&&g.eq("currency",c);const[{data:f,error:p},{data:b,error:y},w]=await Promise.all([d,m??Promise.resolve({data:[],error:null}),g??Promise.resolve({data:null,error:null})]);if(p)throw new Error(`Failed to fetch ecommerce stats: ${_(p)}`);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 I=Array.isArray(f)?f:[],T=Array.isArray(b)?b:[],k=qt(I),C=Array.isArray(w.data)?w.data:null,E=C?qt(C):null,O={};for(const v of T){const A=Array.isArray(v.orders)?v.orders[0]:v.orders,q=String(A?.currency||c||"unknown").toUpperCase();O[q]=(O[q]??0)+re(v.quantity)*re(v.price_at_purchase)/100}const te={currency:c??null,currencyFiltered:!!c,orderStatusCounts:k,paidOrderCount:k.paid??0,query:n.query,reportType:n.reportType,revenueByCurrency:O,timeRange:n.timeRange,totalOrders:I.length,totalRevenue:Object.values(O).reduce((v,A)=>v+A,0)};if(E&&(te.allTimeOrderStatusCounts=E),u&&(te.matchingOrderStatus={allTimeCount:E?.[u]??k[u]??0,count:k[u]??0,status:u,timeRange:n.timeRange}),n.reportType==="products"||n.reportType==="revenue"||n.reportType==="general"){const v={};for(const A of T){const q=Array.isArray(A.products)?A.products[0]:A.products;if(!q?.id)continue;const ne=q.id;v[ne]||(v[ne]={id:ne,quantity:0,revenue:0,title:q.title,type:q.product_type}),v[ne].quantity+=re(A.quantity),v[ne].revenue+=re(A.quantity)*re(A.price_at_purchase)/100}te.topProducts=Object.values(v).sort((A,q)=>q.revenue-A.revenue).slice(0,10)}return{report:te,success:!0}}async function dn(e,t){const n=Ze.parse(e),r=x(t),o=await ee(n.cmsTarget,t),i=M(o),a=o.contentType==="page"?"pages":o.contentType==="post"?"posts":"products",{data:c,error:u}=await r.from(a).select("*").eq("id",i).single();if(u||!c)throw new Error(`Failed to read current ${o.contentType}: ${_(u)}`);let d=[];if(n.includeBlocks){const l=o.contentType==="page"?"page_id":o.contentType==="post"?"post_id":"product_id",{data:m,error:h}=await r.from("blocks").select("id, page_id, post_id, product_id, language_id, block_type, content, order").eq(l,i);if(h)throw new Error(`Failed to read current ${o.contentType} blocks: ${_(h)}`);d=(Array.isArray(m)?m:[]).slice().sort((g,f)=>Number(g.order)-Number(f.order)).map(g=>mr(g,n.includeBlockContent))}return{blocks:d,context:o,item:c,success:!0}}const pn=new Set(["feature_image_id","language_id","meta_description","meta_title","slug","status","title"]),mn=new Set(["excerpt","feature_image_id","label","language_id","meta_description","meta_title","published_at","slug","status","subtitle","title"]),Rr=new Set(["description_json","language_id","meta_description","meta_title","short_description","slug","status","title"]),qr=new Set(["excerpt","feature_image_id","label","meta_description","meta_title","published_at","short_description","subtitle"]);function Dr(e){return e==="page"?pn:e==="post"?mn:Rr}function gn(e,t){return qr.has(e)&&t===""?null:t}function He(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 Mr(e,t){const n=Dr(t.contentType),r={};for(const[o,i]of Object.entries(e))if(i!==void 0){if(!n.has(o))throw new Error(`Field "${o}" cannot be updated for ${t.contentType} content.`);o==="status"&&He(t.contentType,i),r[o]=gn(o,i)}return r}async function ft(e,t){const n=ce.parse(e),r=x(t),o=await ee(n.cmsTarget,t),i=M(o),a=Mr(n.fields,o),c=Object.keys(a);if(c.length===0)throw new Error("update_current_cms_fields requires at least one supported field.");const u=P({action:"UPDATE CMS FIELDS",context:t,payload:{contentType:o.contentType,entityId:i,fields:a,tool:"update_current_cms_fields"},preview:{contentType:o.contentType,entityId:i,fields:c,slug:o.slug,title:o.title},subject:`${o.contentType} ${String(i)}`});if(u)return u;const d=await W(t,o.contentType,i);typeof a.feature_image_id=="string"&&(a.feature_image_id=await Q(a.feature_image_id,t,typeof o.title=="string"?o.title:void 0));const l=o.contentType==="page"?"pages":o.contentType==="post"?"posts":"products",{data:m,error:h}=await r.from(l).update({...a,updated_at:new Date().toISOString()}).eq("id",i).select("id, language_id, slug, status, title").single();if(h||!m)throw new Error(`Failed to update current ${o.contentType}: ${_(h)}`);return await G(t,o.contentType,i,d),U(t,o,m.slug),{contentType:o.contentType,entityId:i,mutationExecuted:!0,slug:m.slug,success:!0,updatedFields:c}}async function ht(e,t){const n=le.parse(e),r=x(t),o=await ee(n.cmsTarget,t),{data:i,error:a}=await r.from("blocks").select("id, page_id, post_id, product_id, language_id, block_type, content, order").eq("id",n.blockId).single();if(a||!i)throw new Error(`Failed to read block ${n.blockId}: ${_(a)}`);Zt(i,o),t=await V(t,[i.block_type,i.content,n.content]);const c=oe(i.block_type,`Block ${n.blockId}`,t);en(n.blockType,c,`Block ${n.blockId}`);const u=_e(i.content,`Block ${n.blockId}`),d=pr(c,u,n.content,t);j(c,d,`Block ${n.blockId}`,t);const l=P({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:o.contentType,entityId:M(o)},subject:`${c} block ${n.blockId}`});if(l)return l;const m=await W(t,o.contentType,M(o)),{data:h,error:g}=await r.from("blocks").update({content:d,updated_at:new Date().toISOString()}).eq("id",n.blockId).select("id, block_type, order").single();if(g||!h)throw new Error(`Failed to update block ${n.blockId}: ${_(g)}`);return await G(t,o.contentType,M(o),m),await Oe({patch:({blocks:f})=>({blocks:f.map(p=>String(p?.id)===String(n.blockId)?{...p,content:d}:p)}),productId:i.product_id,supabase:r}),we([{content:d}],r),U(t,o),{blockId:h.id,blockType:h.block_type,contentUpdated:!0,mutationExecuted:!0,success:!0}}async function yt(e,t){const n=me.parse(e);t=await V(t,n.block);const r=x(t),o=await Y(n,t),i=o.contentType==="product"?o.item.id:Number(o.item.id),a=o.contentType==="page"?"page_id":o.contentType==="post"?"post_id":"product_id",c=async()=>{const{data:T,error:k}=await r.from("blocks").select("id, page_id, post_id, product_id, language_id, block_type, content, order").eq(a,i);if(k)throw new Error(`Failed to read ${o.contentType} blocks: ${_(k)}`);return(Array.isArray(T)?T:[]).sort((C,E)=>Number(C.order)-Number(E.order))},u=T=>{if(n.position==="start")return 0;if(n.position==="end"){const E=T.map(O=>Number(O.order)).filter(Number.isFinite);return E.length>0?Math.max(...E)+1:0}const k=n.anchorBlockId?T.find(E=>Number(E.id)===n.anchorBlockId):n.anchorBlockType?T.find(E=>E.block_type===n.anchorBlockType):null;if(!k)throw new Error(n.anchorBlockType?`Could not find a ${n.anchorBlockType} block to insert ${n.position}.`:`Could not find block ${n.anchorBlockId} to insert ${n.position}.`);const C=Number(k.order);return n.position==="before"?C:C+1},d=$e(n.block,0,t),l=await c(),m=u(l),h={contentType:o.contentType,entityId:o.item.id,languageId:o.item.language_id,slug:o.item.slug,title:o.item.title,translationGroupId:o.item.translation_group_id},g=P({action:"INSERT CONTENT BLOCK",context:t,payload:{block:d,order:m,target:{contentType:o.contentType,id:o.item.id,slug:o.item.slug},tool:"insert_content_block"},preview:{anchorBlockId:n.anchorBlockId,anchorBlockType:n.anchorBlockType,blockType:d.block_type,contentType:o.contentType,entityId:o.item.id,position:n.position,slug:o.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 ${o.contentType} "${o.item.title||o.item.slug}".`,title:o.item.title},subject:`${d.block_type} block on ${o.contentType} ${o.item.id}`});if(g)return g;const f=await c(),p=u(f),b=f.filter(T=>Number(T.order)>=p).sort((T,k)=>Number(k.order)-Number(T.order)),y=await W(t,o.contentType,i);for(const T of b){const{error:k}=await r.from("blocks").update({order:Number(T.order)+1,updated_at:new Date().toISOString()}).eq("id",T.id);if(k)throw new Error(`Failed to shift block ${T.id}: ${_(k)}`)}const{data:w,error:I}=await r.from("blocks").insert({block_type:d.block_type,content:d.content,language_id:o.item.language_id,order:p,page_id:o.contentType==="page"?i:null,post_id:o.contentType==="post"?i:null,product_id:o.contentType==="product"?i:null}).select("id, block_type, order").single();if(I||!w)throw new Error(`Failed to insert content block: ${_(I)}`);return o.contentType==="product"&&await Oe({patch:({blocks:T})=>({blocks:[...T.map(k=>Number(k?.order)>=p?{...k,order:Number(k.order)+1}:k),{block_type:d.block_type,content:d.content,id:w.id,language_id:o.item.language_id,order:p,page_id:null,post_id:null,product_id:i}].sort((k,C)=>Number(k.order)-Number(C.order))}),productId:i,supabase:r}),await G(t,o.contentType,i,y),we([d],r),U(t,h),{blockId:w.id,blockType:w.block_type,contentType:o.contentType,entityId:o.item.id,mutationExecuted:!0,order:w.order,success:!0}}async function bt(e,t){const n=ue.parse(e),r=x(t),o=await ee(n.cmsTarget,t),{data:i,error:a}=await r.from("blocks").select("id, page_id, post_id, product_id, language_id, block_type, content, order").eq("id",n.parentBlockId).single();if(a||!i)throw new Error(`Failed to read parent block ${n.parentBlockId}: ${_(a)}`);Zt(i,o),t=await V(t,[i.block_type,i.content,n.content]);const c=oe(i.block_type,`Parent block ${n.parentBlockId}`,t);if(c!=="section")throw new Error(`Parent block ${n.parentBlockId} must be a section block, not "${c}".`);const u=_e(i.content,`Parent block ${n.parentBlockId}`);j(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=oe(l.block_type,`Nested block ${n.columnIndex}:${n.blockIndex}`,t);en(n.blockType,m,`Nested block ${n.columnIndex}:${n.blockIndex}`),j(m,n.content,`Nested block ${n.columnIndex}:${n.blockIndex}`,t);const h=u.column_blocks.map((w,I)=>I===n.columnIndex?w.map((T,k)=>k===n.blockIndex?{...T,content:n.content}:T):w),g={...u,column_blocks:h};j(c,g,`Updated parent block ${n.parentBlockId}`,t);const f=P({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(f)return f;const p=await W(t,o.contentType,M(o)),{data:b,error:y}=await r.from("blocks").update({content:g,updated_at:new Date().toISOString()}).eq("id",n.parentBlockId).select("id, block_type").single();if(y||!b)throw new Error(`Failed to update parent block ${n.parentBlockId}: ${_(y)}`);return await Oe({patch:({blocks:w})=>({blocks:w.map(I=>String(I?.id)===String(n.parentBlockId)?{...I,content:g}:I)}),productId:i.product_id,supabase:r}),await G(t,o.contentType,M(o),p),U(t,o),{blockIndex:n.blockIndex,columnIndex:n.columnIndex,mutationExecuted:!0,nestedBlockType:m,parentBlockId:b.id,parentBlockType:b.block_type,success:!0}}async function Re(e,t){const n=ge.parse(e);t=await V(t,n.blocks);const r=x(t),o=ot(t),i=await Be(r,n.languageCode),a=F(n.slug||n.title),c=Le(n.blocks,n.contactEmail,n.title,t),u=await ct({contentType:"page",languageId:i.id,slug:a,supabase:r});if(u)return u;const d=await lt({contentType:"page",languageCode:i.code,languageId:i.id,suppliedTranslationGroupId:n.translationGroupId,supabase:r});if(d.result)return d.result;const l={blocks:c,item:{feature_image_id:n.feature_image_id??null,language_id:i.id,meta_description:n.meta_description??null,meta_title:n.meta_title??null,slug:a,status:n.status,title:n.title,translation_group_id:d.translationGroupId},tool:"create_cms_page"},m=P({action:"CREATE PAGE",context:t,payload:l,preview:{blockCount:c.length,languageCode:i.code,slug:a,status:n.status,title:n.title,translationGroupId:d.translationGroupId},subject:a});if(m)return m;const h=d.translationGroupId||it(),g=await Q(l.item.feature_image_id,t,n.title),{data:f,error:p}=await r.from("pages").insert({...l.item,author_id:o,feature_image_id:g,translation_group_id:h}).select("id, language_id, slug, status, title, translation_group_id").single();if(p||!f?.id)throw new Error(`Failed to create page: ${_(p)}`);try{await ut({blocks:c,contentType:"page",itemId:Number(f.id),languageId:i.id,supabase:r})}catch(b){throw await dt({contentType:"page",itemId:Number(f.id),supabase:r}),b}return U(t,{contentType:"page",entityId:Number(f.id),languageId:i.id,slug:a,title:n.title},a),t?.revalidatePath?.("/cms/pages"),{blockCount:c.length,contentType:"page",editPath:pt("page",f.id),entityId:f.id,mutationExecuted:!0,slug:a,success:!0,title:n.title,translationGroupId:f.translation_group_id}}async function qe(e,t){const n=fe.parse(e);t=await V(t,n.blocks);const r=x(t),o=ot(t),i=await Be(r,n.languageCode),a=F(n.slug||n.title),c=Le(n.blocks,void 0,void 0,t),u=await ct({contentType:"post",languageId:i.id,slug:a,supabase:r});if(u)return u;const d=await lt({contentType:"post",languageCode:i.code,languageId:i.id,suppliedTranslationGroupId:n.translationGroupId,supabase:r});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:i.id,meta_description:n.meta_description??null,meta_title:n.meta_title??null,published_at:l,slug:a,status:n.status,subtitle:n.subtitle??null,title:n.title,translation_group_id:d.translationGroupId},tool:"create_cms_post"},h=P({action:"CREATE POST",context:t,payload:m,preview:{blockCount:c.length,languageCode:i.code,slug:a,status:n.status,title:n.title,translationGroupId:d.translationGroupId},subject:a});if(h)return h;const g=d.translationGroupId||it(),f=await Q(m.item.feature_image_id,t,n.title),{data:p,error:b}=await r.from("posts").insert({...m.item,author_id:o,feature_image_id:f,translation_group_id:g}).select("id, language_id, slug, status, title, translation_group_id").single();if(b||!p?.id)throw new Error(`Failed to create post: ${_(b)}`);try{await ut({blocks:c,contentType:"post",itemId:Number(p.id),languageId:i.id,supabase:r})}catch(y){throw await dt({contentType:"post",itemId:Number(p.id),supabase:r}),y}return U(t,{contentType:"post",entityId:Number(p.id),languageId:i.id,slug:a,title:n.title},a),t?.revalidatePath?.("/cms/posts"),t?.revalidatePath?.("/articles"),{blockCount:c.length,contentType:"post",editPath:pt("post",p.id),entityId:p.id,mutationExecuted:!0,slug:a,success:!0,title:n.title,translationGroupId:p.translation_group_id}}function jr(e,t){return(t||F(e)||"product").replace(/-/g,"").slice(0,24).toUpperCase()}function fn(e){if(e==null)return;if(typeof e=="string")return Kt.editorDocumentFromHtml(e)??void 0;const t=Array.isArray(e)?{content:e,type:"doc"}:z(e)&&e.type!=="doc"&&Array.isArray(e.content)?{...e,type:"doc"}:e,n=Ut().safeParse(t);if(!n.success){if(z(e)&&typeof e.type=="string"){const r=Ut().safeParse({content:[e],type:"doc"});if(r.success)return r.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(r=>r.message).join("; ")}`)}return n.data}function Gr(e){const t=o=>!!(o&&Array.isArray(o.content)&&o.content.length>0),n=fn(e.description_json);if(t(n))return n;const r=e.description_html?Kt.editorDocumentFromHtml(e.description_html):null;return t(r)?r:void 0}async function _t(e,t){const n=he.parse(e);t=await V(t,n.blocks);const r=x(t),o=await Be(r,n.languageCode),i=F(n.slug||n.title),a=Le(n.blocks,void 0,void 0,t),c=await ct({contentType:"product",languageId:o.id,slug:i,supabase:r});if(c)return c;const u=await lt({contentType:"product",languageCode:o.code,languageId:o.id,suppliedTranslationGroupId:n.translationGroupId,supabase:r});if(u.result)return u.result;const{createProduct:d,productSchema:l}=await tr(),h=n.product_type==="digital"&&n.payment_provider==="freemius"?n.trial_period_days:0,g=l.parse({description_json:Gr(n),freemius_plan_id:n.freemius_plan_id||"",freemius_product_id:n.freemius_product_id||"",is_taxable:n.is_taxable,language_id:o.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||jr(n.title,i),slug:i,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:[]}),f=n.images??[],p=P({action:"CREATE PRODUCT",context:t,payload:{blocks:a,images:f,item:g,tool:"create_cms_product"},preview:{blockCount:a.length,descriptionLength:g.description_json?JSON.stringify(g.description_json).length:0,imageCount:f.length,languageCode:o.code,price:g.price,sku:g.sku,slug:i,status:g.status,stock:g.stock,title:g.title,translationGroupId:u.translationGroupId},subject:i});if(p)return p;let b=[],y=null;if(f.length>0)try{if(b=[...new Set(await Jt(f,t,n.title))],b.length===0)throw new Error("None of the provided images could be resolved to a media item.")}catch(I){y=I instanceof Error?I.message:String(I)}const w=await d(r,{...g,product_media:b.map(I=>({media_id:I}))});if(!w?.id)throw new Error("Failed to create product.");try{await ut({blocks:a,contentType:"product",itemId:w.id,languageId:o.id,supabase:r})}catch(I){throw await dt({contentType:"product",itemId:w.id,supabase:r}),I}return U(t,{contentType:"product",entityId:w.id,languageId:o.id,slug:i,title:n.title},i),t?.revalidatePath?.("/cms/products"),{blockCount:a.length,contentType:"product",editPath:pt("product",w.id),entityId:w.id,imageCount:b.length,...y?{imageError:y}:{},mutationExecuted:!0,slug:i,success:!0,title:n.title,translationGroupId:w.translation_group_id}}function wt(e){return e.trim().replace(/[\s-]+/g,"_").toLowerCase()}function Kr(e,t){const n=typeof t=="string"?wt(t):t;return e==="product"?n==="public"||n==="publish"||n==="published"?"active":n:n==="public"||n==="active"||n==="publish"?"published":n}function Vr(e){const t=wt(e.field);return!!(e.startsAt||e.endsAt||t.includes("start")||t.includes("end")||t.includes("schedule")||t.includes("special_date"))}async function Hr(e,t,n){if(e==="price"||e==="sale_price"){if(t==null)return{[e]:null};const r=await Ve(n);return{[e]:ve(Number(t),r)}}if(e==="prices"||e==="sale_prices"){const r=await Ve(n);return{[e]:sr(t,r)}}return e==="description_json"?{description_json:fn(t)}:{[e]:t}}const Wr=new Set(["language_id","price","sale_price","stock","trial_period_days"]),Jr=new Set(["is_taxable","trial_requires_payment_method"]);function Yr(e,t){if(typeof t!="string")return t;const n=t.trim();if(Wr.has(e)){if(n.toLowerCase()==="null")return null;if(n==="")return t;const r=Number(n);return Number.isFinite(r)?r:t}if(Jr.has(e)){const r=n.toLowerCase();if(r==="true")return!0;if(r==="false")return!1}return t}function Xr(e,t){const n=wt(e.field),o={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,i=o==="status"?Kr(t.contentType,e.value):Yr(o,e.value);if(t.contentType!=="product"){if(!(t.contentType==="page"?pn:mn).has(o))throw new Error(`Field "${e.field}" cannot be updated for ${t.contentType}.`);return o==="status"&&He(t.contentType,i),{field:o,payload:{[o]:gn(o,i)}}}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(o))throw new Error(`Field "${e.field}" cannot be updated for product.`);if(o==="status"&&He("product",i),(o==="price"||o==="sale_price")&&i!==null&&(typeof i!="number"||i<0))throw new Error(`${o} must be a non-negative number or null.`);if(o==="stock"&&(!Number.isInteger(i)||Number(i)<0))throw new Error("stock must be a non-negative integer.");if(o==="trial_period_days"&&(!Number.isInteger(i)||Number(i)<0))throw new Error("trial_period_days must be a non-negative integer.");if(o==="trial_requires_payment_method"&&typeof i!="boolean")throw new Error("trial_requires_payment_method must be a boolean.");return{field:o,payload:{[o]:i}}}async function kt(e,t){const n=ye.parse(e);if(Vr(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 r=await Y(n,t),o=Xr(n,r),i=o.field;let a=o.payload;if(i==="language_id"&&typeof a.language_id=="string"){const h=await Z(x(t),a.language_id);a={...a,language_id:h.id}}const c=P({action:"UPDATE FIELD",context:t,payload:{contentType:r.contentType,entityId:r.item.id,field:i,payload:a,tool:"update_cms_item_field"},preview:{contentType:r.contentType,field:i,from:r.item[i],slug:r.item.slug,title:r.item.title,to:a[i]},subject:`${r.contentType} ${r.item.slug||r.item.id} ${i}`});if(c)return c;const u=await W(t,r.contentType,r.item.id);if(r.contentType==="product"){const h=x(t),g=await Hr(i,a[i],h),{data:f,error:p}=await h.from("products").update({...g,updated_at:new Date().toISOString()}).eq("id",r.item.id).select("id, language_id, slug, status, title").single();if(p||!f)throw new Error(`Failed to update product: ${_(p)}`);return U(t,{contentType:"product",entityId:String(f.id),languageId:f.language_id,slug:f.slug,title:f.title},f.slug),await G(t,"product",f.id,u),{contentType:"product",entityId:f.id,field:i,mutationExecuted:!0,slug:f.slug,success:!0,updatedFields:[i]}}i==="feature_image_id"&&typeof a.feature_image_id=="string"&&(a={...a,feature_image_id:await Q(a.feature_image_id,t,typeof r.item.title=="string"?r.item.title:void 0)});const d=r.contentType==="page"?"pages":"posts",{data:l,error:m}=await x(t).from(d).update({...a,updated_at:new Date().toISOString()}).eq("id",r.item.id).select("id, language_id, slug, status, title").single();if(m||!l)throw new Error(`Failed to update ${r.contentType}: ${_(m)}`);return U(t,{contentType:r.contentType,entityId:Number(l.id),languageId:l.language_id,slug:l.slug,title:l.title},l.slug),await G(t,r.contentType,l.id,u),{contentType:r.contentType,entityId:l.id,field:i,mutationExecuted:!0,slug:l.slug,success:!0,updatedFields:[i]}}async function hn(e,t){const n=tt.parse(e),r=await Y(n,t);if(r.contentType==="product")return{affectedCount:1,collectionPath:Lt("product"),contentType:"product",item:r.item,navigationLinkCount:0,publicPaths:r.item.slug?[`/product/${r.item.slug}`]:[],targetIds:[r.item.id]};const o=r.contentType==="page"?"pages":"posts",{data:i,error:a}=await x(t).from(o).select("id, slug, title, translation_group_id").eq("translation_group_id",r.item.translation_group_id);if(a)throw new Error(`Failed to inspect related ${r.contentType}s: ${_(a)}`);const c=Array.isArray(i)?i:[],u=c.map(g=>r.contentType==="page"?g.slug==="home"?"/":`/${g.slug}`:`/article/${g.slug}`).filter(Boolean),d=new Set(u),{data:l,error:m}=await x(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(g=>d.has(g.url)).length;return{affectedCount:c.length,collectionPath:Lt(r.contentType),contentType:r.contentType,item:r.item,navigationLinkCount:h,publicPaths:u,targetIds:c.map(g=>g.id)}}function yn(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 r=[`${N(e.affectedCount,"language version")}`,e.navigationLinkCount>0?`${N(e.navigationLinkCount,"navigation link")}`:null].filter(Boolean);return`Delete ${e.contentType} "${t}"${n}, including ${r.join(" and ")}.`}async function bn(e,t){const n=await hn(e,t);return{...Qt({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:yn(n),title:n.item.title},subject:`${n.item.id} ${n.item.slug||""}`}),preparedDelete:!0}}async function It(e,t){const n=be.parse(e),r=await hn(n,t),o=P({action:`DELETE ${r.contentType}`,context:t,payload:{affectedCount:r.affectedCount,contentType:r.contentType,targetIds:r.targetIds,tool:"delete_cms_item"},preview:{affectedCount:r.affectedCount,collectionPath:r.collectionPath,contentType:r.contentType,navigationLinkCount:r.navigationLinkCount,publicPaths:r.publicPaths,slug:r.item.slug,summary:yn(r),title:r.item.title},subject:`${r.item.id} ${r.item.slug||""}`});if(o)return o;const i=x(t);if(r.contentType==="product"){const{error:c}=await i.from("products").delete().eq("id",r.item.id);if(c)throw new Error(`Failed to delete product: ${_(c)}`)}else{for(const d of r.publicPaths)await i.from("navigation_items").delete().eq("url",d);const c=r.contentType==="page"?"pages":"posts",{error:u}=await i.from(c).delete().eq("translation_group_id",r.item.translation_group_id);if(u)throw new Error(`Failed to delete ${r.contentType}: ${_(u)}`)}const a=t?.revalidatePath??rt();return a&&(a(r.collectionPath),a("/cms/navigation"),r.publicPaths.forEach(c=>a(c))),{affectedCount:r.affectedCount,collectionPath:r.collectionPath,contentType:r.contentType,mutationExecuted:!0,redirectPath:r.collectionPath,success:!0}}async function Dt(e,t){switch(e.tool){case"create_cms_page":return Re(e.input,t);case"create_cms_post":return qe(e.input,t);case"create_cms_product":return _t(e.input,t);case"delete_cms_item":return It(e.input,t);case"update_cms_item_field":return kt(e.input,t);case"update_content_block":return ht(e.input,t);case"insert_content_block":return yt(e.input,t);case"update_current_cms_fields":return ft(e.input,t);case"update_footer":return gt(e.input,t);case"update_navigation_bar":return mt(e.input,t);case"update_section_column_block":return bt(e.input,t);case"set_content_images":return At(e.input,t)}}function Qr(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 Mt(e){return e==="create_cms_page"?"page":e==="create_cms_post"?"post":"product"}function Zr(e,t,n){if(e.tool!=="set_content_images")return e;const r=e.input;if(r.entityId!==void 0)return e;const o=r.slug?t.get(`${r.contentType||"product"}:${F(r.slug)}`):n;return o?{...e,input:{...r,contentType:o.contentType,entityId:o.entityId}}:e}async function _n(e,t){const n=nt.parse(e),r=new Set(n.actions.filter(g=>g.tool==="create_cms_page"||g.tool==="create_cms_post"||g.tool==="create_cms_product").map(g=>{const f=g.input;return`${Mt(g.tool)}:${F(f.slug||f.title||"")}`})),o=g=>{if(g.tool!=="set_content_images")return!1;const f=g.input;return f.slug?r.has(`${f.contentType||"product"}:${F(f.slug)}`):r.size>0};if(!t?.skipConfirmation){const g=[];for(const b of n.actions){if(o(b)){const w=b.input;g.push(`Set ${N(w.images.length,"image")} on the ${w.slug?`"${w.slug}"`:"new"} item created in this plan.`);continue}const y=await Dt(b,{...t,latestUserMessage:null});if(!y||typeof y!="object")return{message:`Could not prepare action ${g.length+1}.`,mutationExecuted:!1,success:!1};if(y.success===!1||y.unsupported===!0)return y;y.requiresConfirmation===!0&&y.preview?g.push(or(b.tool,y.preview)):g.push(`Run ${b.tool.replace(/_/g," ")}.`)}const f=n.summary||`Complete ${N(n.actions.length,"CMS action")}.`,p=P({action:"EXECUTE CMS ACTION PLAN",context:t,payload:{actions:n.actions,tool:"execute_cms_action_plan"},preview:{actionCount:n.actions.length,actionSummaries:g,summary:f},subject:`${n.actions.length} actions`});if(p)return p}const i={...t,skipConfirmation:!0},a=[];let c=!1,u=null,d=null;const l={},m=new Map;let h=null;for(const[g,f]of n.actions.entries()){const p=Zr(Qr(f,l),m,h),b=await Dt(p,i);if(a.push({output:b,tool:p.tool}),b&&typeof b=="object"){const y=b;if(y.mutationExecuted===!0&&(c=!0),!u&&typeof y.editPath=="string"&&(u=y.editPath),typeof y.redirectPath=="string"&&(d=y.redirectPath),(p.tool==="create_cms_page"||p.tool==="create_cms_post"||p.tool==="create_cms_product")&&(typeof y.translationGroupId=="string"&&(l[p.tool]=y.translationGroupId),y.entityId!==void 0&&y.entityId!==null)){const w=Mt(p.tool),I={contentType:w,entityId:y.entityId};h=I,typeof y.slug=="string"&&m.set(`${w}:${y.slug}`,I)}if(y.success===!1||y.unsupported===!0)return{actionCount:n.actions.length,failedActionIndex:g,failedTool:p.tool,message:typeof y.message=="string"?y.message:`Action ${g+1} failed.`,mutationExecuted:c,results:a,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:a,success:!0,summary:n.summary??null}}const Tt=s.z.strictObject({maxChars:s.z.number().int().min(500).max(2e4).default(8e3).describe("Maximum characters of readable body text to return."),url:s.z.string().trim().min(1).max(2048).refine(e=>/^https?:\/\//i.test(e),"URL must start with http:// or https://.")}),eo=12e3,jt=2e6;function to(e){const t=e.match(/^::ffff:(.+)$/i);if(!t)return null;const n=t[1];if(/^\d{1,3}(\.\d{1,3}){3}$/.test(n))return n;const r=n.match(/^([0-9a-f]{1,4}):([0-9a-f]{1,4})$/i);if(!r)return null;const o=Number.parseInt(r[1],16),i=Number.parseInt(r[2],16);return[o>>8&255,o&255,i>>8&255,i&255].join(".")}function ze(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==="::"||t==="::1"||t.startsWith("fe80:")||t.startsWith("fc")||t.startsWith("fd"))return!0;const n=to(t);if(n)return ze(n);const r=t.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/);if(r){const o=Number(r[1]),i=Number(r[2]);if(o===10||o===127||o===0||o===192&&i===168||o===169&&i===254||o===172&&i>=16&&i<=31)return!0}return!1}function Ie(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 no(e){return e.trim().replace(/&amp;/gi,"&").replace(/&#38;/g,"&").replace(/&quot;/gi,'"').replace(/&#39;/g,"'")}const wn=/\.(avif|gif|jpe?g|png|webp)(?:[?#]|$)/i,kn=/(?:^|[/_-])(?: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 Ae(e,t){if(typeof e!="string")return null;const n=no(e);if(!n||n.startsWith("data:"))return null;try{const r=new URL(n,t);return r.protocol!=="http:"&&r.protocol!=="https:"?null:r.toString()}catch{return null}}function ro(e){let t=null;for(const n of e.split(",")){const r=n.trim().split(/\s+/),o=r[0];if(!o)continue;const i=r[1]||"",a=i.match(/^(\d+(?:\.\d+)?)w$/i),c=i.match(/^(\d+(?:\.\d+)?)x$/i),u=a?Number(a[1]):c?Number(c[1])*1e3:1;(!t||u>t.weight)&&(t={url:o,weight:u})}return t?.url??null}function L(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 oo(e,t){const n=[],r=[],o=(c,u)=>{if(typeof c=="string"){const d=Ae(c,t);d&&u.push(d);return}if(Array.isArray(c)){for(const d of c)o(d,u);return}c&&typeof c=="object"&&(o(c.url,u),o(c.contentUrl,u))},i=(c,u)=>{if(u>8||!c||typeof c!="object")return;if(Array.isArray(c)){for(const g of c)i(g,u+1);return}const d=c,l=d["@type"],h=(Array.isArray(l)?l:[l]).filter(g=>typeof g=="string").map(g=>g.toLowerCase()).some(g=>g==="product"||g==="productgroup"||g==="itempage");"image"in d&&o(d.image,h?n:r);for(const g of Object.values(d))i(g,u+1)},a=e.matchAll(/<script\b[^>]*type\s*=\s*["']application\/ld\+json["'][^>]*>([\s\S]*?)<\/script>/gi);for(const c of a){const u=(c[1]||"").trim();if(u)try{i(JSON.parse(u),0)}catch{}}return[...n,...r]}const In=/(?:^|[/_-])(?:thumbnails?|thumbs?|small|mini)(?:[/_.-]|$)/i;function Tn(e){try{const{pathname:t}=new URL(e);return decodeURIComponent(t.slice(t.lastIndexOf("/")+1)).toLowerCase()||null}catch{return null}}function io(e,t){const n=new Map;for(const r of e.matchAll(/<a\b[^>]*>/gi)){const o=Ae(L(r[0],"href"),t);if(!o||!wn.test(o)||In.test(o)||kn.test(o))continue;const i=Tn(o);i&&!n.has(i)&&n.set(i,o)}return n}function ao(e,t){const n=[...oo(e,t)],r=[/<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 r)for(const m of e.matchAll(l)){const h=m[0],g=Ae(L(h,"content")||L(h,"href"),t);g&&n.push(g)}const o=[];for(const l of e.matchAll(/<img\b[^>]*>/gi)){const m=l[0],h=L(m,"srcset")||L(m,"data-srcset"),g=[h?ro(h):null,L(m,"src"),L(m,"data-src"),L(m,"data-original"),L(m,"data-lazy-src"),L(m,"data-image")];let f=null;for(const b of g)if(f=Ae(b,t),f)break;if(!f||kn.test(f))continue;const p=Number(L(m,"width"));Number.isFinite(p)&&p>0&&p<200||o.push(f)}const i=l=>wn.test(l);n.push(...o.filter(i),...o.filter(l=>!i(l)));const a=io(e,t),c=l=>{if(!In.test(l))return l;const m=Tn(l);return m&&a.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 so(e,t,n){const r=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:o,mainImage:i}=ao(e,n),a=e.match(/<title\b[^>]*>([\s\S]*?)<\/title>/i),c=e.match(/<meta[^>]+name=["']description["'][^>]*content=["']([^"']*)["'][^>]*>/i)||e.match(/<meta[^>]+content=["']([^"']*)["'][^>]*name=["']description["'][^>]*>/i),u=[...r.matchAll(/<h([1-3])\b[^>]*>([\s\S]*?)<\/h\1>/gi)].map(m=>Ie(m[2])).filter(Boolean).slice(0,40),d=r.match(/<body\b[^>]*>([\s\S]*?)<\/body>/i),l=Ie(d?.[1]??r);return{description:c?Ie(c[1]):"",headings:u,images:o,mainImage:i,text:l.slice(0,t),title:a?Ie(a[1]):"",truncated:l.length>t}}async function Cn(e){const t=Tt.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(ze(n.hostname))return{message:"Refusing to fetch a local, private, or internal address.",success:!1,url:t.url};const r=new AbortController,o=setTimeout(()=>r.abort(),eo);try{const i=await fetch(n.toString(),{headers:{accept:"text/html,application/xhtml+xml,text/plain","user-agent":"NextBlockCortexAI/1.0 (+https://nextblock.dev)"},redirect:"follow",signal:r.signal});if(!i.ok)return{message:`The URL responded with HTTP ${i.status}.`,status:i.status,success:!1,url:t.url};const a=i.url||n.toString();try{if(ze(new URL(a).hostname))return{message:"The URL redirected to a blocked internal address.",success:!1,url:t.url}}catch{}const c=i.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 i.text(),d=u.length>jt?u.slice(0,jt):u,l=so(d,t.maxChars,a);return!l.text&&!l.title?{message:"The URL returned no readable text content.",success:!1,url:t.url}:{description:l.description,finalUrl:a,headings:l.headings,images:l.images,mainImage:l.mainImage,success:!0,text:l.text,title:l.title,truncated:l.truncated,url:t.url}}catch(i){return{message:i instanceof Error&&(i.name==="AbortError"||/abort/i.test(i.message))?"Fetching the URL timed out.":`Failed to fetch the URL: ${_(i)}`,success:!1,url:t.url}}finally{clearTimeout(o)}}const Ct=s.z.strictObject({count:s.z.number().int().min(1).max(15).default(6),orientation:s.z.enum(["landscape","portrait","square"]).optional().describe("Preferred image orientation. Use landscape for hero/section backgrounds."),query:s.z.string().trim().min(2).max(200).describe('What the photos should depict, e.g. "herbal supplements".')}),co=12e3;async function De(e){let t=null,n=null;if(e)try{const{CORTEX_AI_PEXELS_SETTING_KEY:o,CORTEX_AI_UNSPLASH_SETTING_KEY:i,decryptStoredOpenRouterApiKey:a}=await Promise.resolve().then(()=>require("./ai-config.cjs.js")),c=l=>{if(!l)return null;try{const m=a(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",[o,i]),d=Array.isArray(u)?u:[];t=c(d.find(l=>l.key===o)?.value),n=c(d.find(l=>l.key===i)?.value)}catch{}t||(t=process.env.PEXELS_API_KEY?.trim()||null),n||(n=process.env.UNSPLASH_ACCESS_KEY?.trim()||null);const r=[];return t&&r.push({apiKey:t,provider:"pexels"}),n&&r.push({apiKey:n,provider:"unsplash"}),r}async function lo(e){return(await De(e))[0]??null}async function uo(e){if(e)try{const{CORTEX_AI_UNSPLASH_APP_NAME_SETTING_KEY:t}=await Promise.resolve().then(()=>require("./ai-config.cjs.js")),{data:n}=await e.from("site_settings").select("value").eq("key",t).maybeSingle(),r=n?.value;if(typeof r=="string"&&r.trim())return r.trim()}catch{}return process.env.UNSPLASH_APP_NAME?.trim()||null}async function Gt(e,t){const n=new AbortController,r=setTimeout(()=>n.abort(),co);try{const o=await fetch(e,{headers:t,signal:n.signal});if(!o.ok)throw new Error(`Stock photo provider responded with HTTP ${o.status}.`);return await o.json()}finally{clearTimeout(r)}}function Te(e){const t=Number(e);return Number.isFinite(t)&&t>0?t:null}function We(e,t){if(!z(e))return;const n=r=>{z(r)&&r.provider==="unsplash"&&typeof r.downloadLocation=="string"&&r.downloadLocation.trim()&&t.add(r.downloadLocation.trim())};if(n(e.attribution),z(e.background)&&z(e.background.image)&&n(e.background.image.attribution),Array.isArray(e.column_blocks)){for(const r of e.column_blocks)if(Array.isArray(r))for(const o of r)z(o)&&We(o.content,t)}if(Array.isArray(e.slides))for(const r of e.slides)We(r,t)}async function we(e,t){try{const n=new Set;for(const i of e)We(i?.content,n);if(n.size===0)return;const o=(await De(t)).find(i=>i.provider==="unsplash");if(!o)return;await Promise.all([...n].map(i=>fetch(i,{headers:{Authorization:`Client-ID ${o.apiKey}`}}).catch(()=>{})))}catch{}}async function po(e,t,n){const r=new URLSearchParams({per_page:String(t.count),query:t.query});if(t.orientation&&r.set("orientation",t.orientation),e.provider==="pexels"){const i=await Gt(`https://api.pexels.com/v1/search?${r.toString()}`,{Authorization:e.apiKey});return(Array.isArray(i?.photos)?i.photos:[]).map(a=>{const c=typeof a?.photographer=="string"?a.photographer:null;return{alt:typeof a?.alt=="string"&&a.alt.trim()?a.alt.trim():t.query,credit:c?`Photo by ${c} on Pexels`:"Photo on Pexels",downloadLocation:null,height:Te(a?.height),photographer:c,photographerUrl:typeof a?.photographer_url=="string"?a.photographer_url:null,provider:"pexels",sourceUrl:typeof a?.url=="string"?a.url:null,thumbnailUrl:a?.src?.medium||a?.src?.large||null,url:a?.src?.large2x||a?.src?.large||a?.src?.original||null,width:Te(a?.width)}}).filter(a=>typeof a.url=="string")}const o=await Gt(`https://api.unsplash.com/search/photos?${r.toString()}`,{Authorization:`Client-ID ${e.apiKey}`});return(Array.isArray(o?.results)?o.results:[]).map(i=>{const a=typeof i?.user?.name=="string"?i.user.name:null;return{alt:typeof i?.alt_description=="string"&&i.alt_description.trim()||typeof i?.description=="string"&&i.description.trim()||t.query,credit:a?`Photo by ${a} on Unsplash`:"Photo on Unsplash",downloadLocation:typeof i?.links?.download_location=="string"?i.links.download_location:null,height:Te(i?.height),photographer:a,photographerUrl:typeof i?.user?.links?.html=="string"?i.user.links.html:null,provider:"unsplash",sourceUrl:typeof i?.links?.html=="string"?i.links.html:null,thumbnailUrl:i?.urls?.small||i?.urls?.thumb||null,url:i?.urls?.regular||i?.urls?.full||i?.urls?.raw||null,utmSource:n||null,width:Te(i?.width)}}).filter(i=>typeof i.url=="string")}async function vn(e,t){const n=Ct.parse(e),r=await De(t?.supabase);if(r.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 o=r.some(c=>c.provider==="unsplash")?await uo(t?.supabase):null,i=[];let a=null;for(const c of r){i.push(c.provider);try{const u=await po(c,n,o);if(u.length>0)return{attemptedProviders:i,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){a=u}}return{attemptedProviders:i,message:a?`Stock photo search failed across ${i.join(", ")}: ${_(a)}`:`No matching stock photos found for "${n.query}".`,photos:[],success:!1}}const vt=J.extend({blocks:s.z.array(de).min(1).max(20),meta:s.z.strictObject({meta_description:s.z.string().max(500).nullable().optional(),meta_title:s.z.string().max(160).nullable().optional(),slug:s.z.string().trim().min(1).max(300).optional(),status:s.z.enum(["draft","published","archived"]).optional(),title:s.z.string().trim().min(1).max(300).optional()}).partial().optional()}),mo=["custom_canonical","excerpt","feature_image_id","label","language_id","meta_description","meta_title","published_at","slug","status","subtitle","title","translation_group_id"];function go(e){const t={};for(const n of mo)n in e&&e[n]!==void 0&&(t[n]=e[n]);return t}function fo(e,t){if(!t)return null;const n=e==="page"?t==="home"?"/":`/${t}`:`/article/${t}`;return`/api/draft/start?path=${encodeURIComponent(n)}`}async function Sn(e,t){const n=vt.parse(e);t=await V(t,n.blocks);const r=x(t),o=ot(t),i=await Y(n,t);if(i.contentType==="product")throw new Error("rewrite_page_draft supports pages and posts only. Products use description_json, not page blocks.");const a=i.contentType,c=Number(i.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(i.item.language_id);if(!Number.isInteger(u)||u<=0)throw new Error("The target page/post is missing a language id.");const l=Le(n.blocks,void 0,void 0,t).map((k,C)=>({block_type:k.block_type,content:k.content,language_id:u,order:C,page_id:a==="page"?c:null,post_id:a==="post"?c:null,product_id:null})),m=go(i.item);if(n.meta)for(const[k,C]of Object.entries(n.meta))C!==void 0&&(m[k]=C);const h=Yt(typeof m.slug=="string"?m.slug:i.item.slug),g=typeof m.title=="string"&&m.title.trim()?m.title:String(i.item.title||h||"Untitled"),f=a==="page"?`/cms/pages/${c}/edit`:`/cms/posts/${c}/edit`,p=fo(a,h),y=P({action:"REWRITE DRAFT",context:t,payload:{blocks:l,meta:m,parent_id:c,parent_type:a,tool:"rewrite_page_draft"},preview:{blockCount:l.length,contentType:a,slug:h,summary:`Stage a Live Draft that replaces the ${a} "${g}" with ${N(l.length,"new block")}. Nothing goes live until you review the draft and click Publish (which also saves a revision snapshot).`,title:g},subject:`${a}-${c}`});if(y)return y;const w=Number(i.item.version)||1,{error:I}=await r.from("content_drafts").delete().eq("parent_type",a).eq("parent_id",c);if(I)throw new Error(`Failed to clear the existing draft: ${_(I)}`);const{error:T}=await r.from("content_drafts").insert({author_id:o,base_version:w,blocks:l,meta:m,parent_id:c,parent_type:a});if(T)throw new Error(`Failed to save the draft: ${_(T)}`);return we(l,r),U(t,{contentType:a,entityId:c,slug:h},h),{blockCount:l.length,contentType:a,draftPreviewPath:p,editPath:f,entityId:c,isDraft:!0,mutationExecuted:!0,slug:h,success:!0,title:g}}const St=s.z.strictObject({attributes:s.z.array(s.z.strictObject({name:s.z.string().trim().min(1).max(120).describe('Attribute name, e.g. "Size" or "Flavour".'),terms:s.z.array(s.z.string().trim().min(1).max(120)).min(1).max(50).describe('Every possible value for this attribute, e.g. ["100 ml", "500 ml"].')})).max(5).optional().describe("The option axes this product varies on. Attributes and terms are global and reused across products: an existing one with the same name is matched, never duplicated. Omit if the attributes already exist."),entityId:s.z.union([s.z.number().int().positive(),s.z.string().trim().min(1).max(120)]).optional(),mode:s.z.enum(["replace","append"]).default("replace").describe(`"replace" removes the product's existing variants first; "append" keeps them and adds these.`),slug:s.z.string().trim().min(1).max(300).optional(),title:s.z.string().trim().min(1).max(300).optional(),variants:s.z.array(s.z.strictObject({image:s.z.string().trim().min(1).max(2048).optional().describe("Variant-specific image: an https:// URL (imported automatically) or a media library id."),options:s.z.record(s.z.string(),s.z.string()).describe('Which term this variant is, per attribute, e.g. { "Size": "500 ml" }. Every attribute must be given a value.'),price:s.z.number().min(0).optional().describe("Price in major units (25 = $25.00). Defaults to the product price."),sale_price:s.z.number().min(0).nullable().optional().describe("Sale price in major units, or null for none."),sku:s.z.string().trim().min(1).max(120).describe("Unique SKU for this variant."),stock:s.z.number().int().min(0).default(0),upc:s.z.string().trim().max(120).nullable().optional()})).min(1).max(50)});async function ho(e,t){const n=F(t.name),{data:r}=await e.from("product_attributes").select("id").eq("slug",n).maybeSingle();let o=r?.id;if(!o){const{data:a,error:c}=await e.from("product_attributes").insert({name:t.name,slug:n}).select("id").single();if(c||!a?.id)throw new Error(`Could not create the "${t.name}" attribute: ${_(c)}`);o=a.id}const i=new Map;for(let a=0;a<t.terms.length;a+=1){const c=t.terms[a],u=F(c),{data:d}=await e.from("product_attribute_terms").select("id").eq("attribute_id",o).eq("slug",u).maybeSingle();if(d?.id){i.set(c,d.id);continue}const{data:l,error:m}=await e.from("product_attribute_terms").insert({attribute_id:o,slug:u,sort_order:a,value:c}).select("id").single();if(m||!l?.id)throw new Error(`Could not create the "${c}" option: ${_(m)}`);i.set(c,l.id)}return{attributeId:o,termIdByValue:i}}async function xn(e,t){const n=St.parse(e),r=x(t),i=(await Y({contentType:"product",...n.entityId!==void 0?{entityId:n.entityId}:{},...n.slug?{slug:n.slug}:{},...n.title?{title:n.title}:{}},t)).item,a=String(i.id),c=P({action:"SET VARIANTS",context:t,payload:{entityId:a,mode:n.mode,variantCount:n.variants.length},preview:{contentType:"product",slug:i.slug,summary:`${n.mode==="replace"?"Replace":"Add"} ${N(n.variants.length,"variant")} on "${i.title}". Product stock becomes the sum of variant stock.`,title:i.title},subject:`product-${a}-variants`});if(c)return c;const u=new Map;for(const p of n.attributes??[]){const{termIdByValue:b}=await ho(r,p);u.set(p.name,b)}for(const p of n.variants)for(const[b,y]of Object.entries(p.options)){if(u.get(b)?.has(y))continue;const{data:w}=await r.from("product_attributes").select("id").eq("slug",F(b)).maybeSingle();if(!w?.id)throw new Error(`Unknown attribute "${b}". Pass it in \`attributes\` with its full list of terms.`);const{data:I}=await r.from("product_attribute_terms").select("id").eq("attribute_id",w.id).eq("slug",F(y)).maybeSingle();if(!I?.id)throw new Error(`Unknown option "${y}" for attribute "${b}". Add it to that attribute's \`terms\`.`);const T=u.get(b)??new Map;T.set(y,I.id),u.set(b,T)}if(n.mode==="replace"){const{error:p}=await r.from("product_variants").delete().eq("product_id",a);if(p)throw new Error(`Could not clear the existing variants: ${_(p)}`)}const d=await Ve(r),l=Number(i.price)||0,m=[];for(const p of n.variants){const b=p.image?await Q(p.image,t,`${i.title} ${p.sku}`):null,{data:y,error:w}=await r.from("product_variants").insert({main_media_id:b,price:p.price===void 0?l:ve(p.price,d),product_id:a,sale_price:p.sale_price===void 0||p.sale_price===null?null:ve(p.sale_price,d),sku:p.sku,stock_quantity:p.stock,upc:p.upc??null}).select("id").single();if(w||!y?.id)throw new Error(`Could not create variant "${p.sku}": ${_(w)}`);const I=Object.entries(p.options).map(([T,k])=>({attribute_term_id:u.get(T)?.get(k),variant_id:y.id}));if(I.length>0){const{error:T}=await r.from("variant_attribute_mapping").insert(I);if(T)throw new Error(`Could not link variant "${p.sku}" to its options: ${_(T)}`)}m.push(p.sku)}const{data:h}=await r.from("product_variants").select("stock_quantity").eq("product_id",a),g=(h??[]).reduce((p,b)=>p+(Number(b?.stock_quantity)||0),0),{error:f}=await r.from("products").update({stock:g}).eq("id",a);if(f)throw new Error(`Variants saved, but the product stock total failed: ${_(f)}`);return U(t,{contentType:"product",entityId:a,slug:i.slug,title:i.title},i.slug),{contentType:"product",entityId:a,mode:n.mode,mutationExecuted:!0,skus:m,slug:i.slug,success:!0,totalStock:g,variantCount:m.length}}const xt=s.z.strictObject({items:s.z.array(s.z.strictObject({contentType:s.z.enum(["page","post"]).default("page"),slug:s.z.string().trim().min(1).max(300).describe("Slug of the source page or post."),title:s.z.string().trim().min(1).max(300).optional().describe("Translated title. Defaults to translating the source title."),translations:s.z.record(s.z.string(),s.z.string()).describe("Source string -> translated string for every visible string in THIS item.")})).min(1).max(25),targetLanguageCode:s.z.string().trim().min(2).max(80).describe('Target language code or name, e.g. "fr". The language must already exist — create it with manage_language first.')});async function En(e,t){const n=xt.parse(e),r=P({action:"TRANSLATE BULK",context:t,payload:{count:n.items.length,language:n.targetLanguageCode},preview:{contentType:"page",summary:`Create ${n.targetLanguageCode} translations of ${N(n.items.length,"item")}: ${n.items.map(a=>a.slug).join(", ")}.`,title:`Bulk translate to ${n.targetLanguageCode}`},subject:`bulk-translate-${n.targetLanguageCode}`});if(r)return r;const o=[],i=[];for(const a of n.items)try{const c=await zt({cmsTarget:{contentType:a.contentType,slug:a.slug},targetLanguageCode:n.targetLanguageCode,...a.title?{title:a.title}:{},translations:a.translations},t);o.push({slug:a.slug,...c})}catch(c){i.push({error:c instanceof Error?c.message:String(c),slug:a.slug})}return{failed:i,failedCount:i.length,mutationExecuted:o.length>0,success:i.length===0,targetLanguageCode:n.targetLanguageCode,translated:o,translatedCount:o.length}}const Et=s.z.strictObject({action:s.z.enum(["publish","discard"]).default("publish").describe('"publish" applies the draft to the live page/post; "discard" deletes it and leaves the live content untouched.'),contentType:s.z.enum(["page","post"]).optional(),entityId:s.z.union([s.z.number().int().positive(),s.z.string().trim().min(1).max(120)]).optional(),slug:s.z.string().trim().min(1).max(300).optional(),title:s.z.string().trim().min(1).max(300).optional()}),yo=["title","slug"],bo=["custom_canonical","feature_image_id","meta_description","meta_title"];async function $n(e,t){const n=Et.parse(e),r=x(t),o=await ee({...n.contentType?{contentType:n.contentType}:{},...n.entityId!==void 0?{entityId:n.entityId}:{},...n.slug?{slug:n.slug}:{},...n.title?{title:n.title}:{}},t);if(o.contentType==="product")throw new Error("publish_content_draft supports pages and posts. Product drafts live in product_drafts and are published from the product editor.");const i=o.contentType,a=Fe(o),c=i==="page"?"pages":"posts",{data:u,error:d}=await r.from("content_drafts").select("*").eq("parent_type",i).eq("parent_id",a).maybeSingle();if(d)throw new Error(`Failed to read the draft: ${_(d)}`);if(!u)return{contentType:i,entityId:a,message:`No Live Draft exists for ${i} "${o.title||o.slug}". Nothing to ${n.action}.`,mutationExecuted:!1,success:!1};const l=o.title||o.slug||`${i} ${a}`,m=P({action:n.action==="publish"?"PUBLISH DRAFT":"DISCARD DRAFT",context:t,payload:{action:n.action,contentType:i,entityId:String(a)},preview:{contentType:i,slug:o.slug,summary:n.action==="publish"?`Publish the Live Draft for ${i} "${l}", replacing its live blocks. A revision snapshot is saved first, so this is reversible from Revision History.`:`Discard the Live Draft for ${i} "${l}". The live content is left untouched.`,title:o.title},subject:`${i}-${a}-draft`});if(m)return m;const h=u.meta??{},g=Array.isArray(u.blocks)?u.blocks:[];if(n.action==="discard"){const{error:k}=await r.from("content_drafts").delete().eq("id",u.id);if(k)throw new Error(`Failed to discard the draft: ${_(k)}`);return U(t,o,o.slug),{action:"discard",contentType:i,entityId:a,mutationExecuted:!0,success:!0}}const f=await W(t,i,a),p={};for(const k of yo){const C=h[k];typeof C=="string"&&C.trim()&&(p[k]=C.trim())}for(const k of bo)if(Object.prototype.hasOwnProperty.call(h,k)){const C=h[k];p[k]=typeof C=="string"&&C.trim()?C.trim():null}if(Object.keys(p).length>0){const{error:k}=await r.from(c).update(p).eq("id",a);if(k)throw new Error(`Failed to apply the draft metadata: ${_(k)}`)}const b=i==="page"?"page_id":"post_id",{error:y}=await r.from("blocks").delete().eq(b,a);if(y)throw new Error(`Failed to clear the live blocks: ${_(y)}`);const w=Number(h.language_id)||Number(o.languageId)||Number(g[0]?.language_id)||0;if(g.length>0){const k=g.map((E,O)=>({block_type:E?.block_type,content:E?.content??{},language_id:Number(E?.language_id)||w,order:Number.isFinite(E?.order)?E.order:O,page_id:i==="page"?a:null,post_id:i==="post"?a:null,product_id:null})),{error:C}=await r.from("blocks").insert(k);if(C)throw new Error(`Failed to publish the draft blocks: ${_(C)}`)}await G(t,i,a,f);const{error:I}=await r.from("content_drafts").delete().eq("id",u.id),T=typeof p.slug=="string"?p.slug:o.slug;return U(t,{...o,slug:T},T??void 0),{action:"publish",blockCount:g.length,contentType:i,entityId:a,mutationExecuted:!0,slug:T,success:!0,...I?{warning:`Published, but the draft row was not removed: ${_(I)}`}:{}}}const _o=new Set(["alt_text","author_name","author_title","caption","html_content","label","placeholder","quote","submit_button_text","success_message","text","text_content","title"]);function Je(e,t,n){if(!e)return e;if(Object.prototype.hasOwnProperty.call(t,e))return t[e];const r=e.trim();if(r!==e&&Object.prototype.hasOwnProperty.call(t,r))return e.replace(r,t[r]);let o=e;for(const[i,a]of n)i&&o.includes(i)&&(o=o.split(i).join(a));return o}function Ye(e,t,n,r){if(Array.isArray(e))return e.map(o=>Ye(o,t,n,r));if(e&&typeof e=="object"){const o={};for(const[i,a]of Object.entries(e))typeof a=="string"&&(_o.has(i)||r?.has(i))?o[i]=Je(a,t,n):a&&typeof a=="object"?o[i]=Ye(a,t,n,r):o[i]=a;return o}return e}function wo(e,t){if(typeof e!="string"||R.isValidBlockType(e))return;const n=st(e,t);if(n)return new Set(R.readCustomBlockFields(n).filter(r=>r.type==="text"||r.type==="rich-text").map(r=>r.key))}const $t=s.z.strictObject({cmsTarget:se,targetLanguageCode:s.z.string().trim().min(2).max(80).describe('Target language code or name, e.g. "fr" or "French".'),title:s.z.string().trim().min(1).max(300).optional().describe("Translated page title (defaults to translating the source title)."),translations:s.z.record(s.z.string(),s.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 zt(e,t){const n=$t.parse(e),r=await ee(n.cmsTarget,t);if(r.contentType==="product")throw new Error("translate_page supports pages and posts only.");const o=x(t),i=Fe(r),a=r.contentType==="page"?"pages":"posts",c=r.contentType==="page"?"page_id":"post_id",{data:u,error:d}=await o.from(a).select("*").eq("id",i).single();if(d||!u)throw new Error(`Could not read the source ${r.contentType} to translate: ${_(d)}`);const{data:l,error:m}=await o.from("blocks").select("id, block_type, content, order").eq(c,i);if(m)throw new Error(`Could not read the source blocks: ${_(m)}`);const h=(Array.isArray(l)?l:[]).slice().sort((v,A)=>Number(v.order)-Number(A.order));if(h.length===0)throw new Error(`The source ${r.contentType} has no content blocks to translate.`);t=await V(t,h);const g=n.translations||{},f=Object.entries(g).filter(([v])=>!!v).sort((v,A)=>A[0].length-v[0].length),p=h.map((v,A)=>({blockType:v.block_type,content:Ye(K(v.content),g,f,wo(v.block_type,t)),order:A})),b=await Be(o,n.targetLanguageCode),y=String(u.title||""),w=n.title||Je(y,g,f)||y||"Untitled",I=v=>typeof v=="string"&&v.trim()?Je(v,g,f):void 0,T=F(w)||u.slug||"translated-page",k={blocks:p,feature_image_id:u.feature_image_id??void 0,languageCode:b.code,meta_description:I(u.meta_description),meta_title:I(u.meta_title),slug:T,status:"published",title:w,translationGroupId:u.translation_group_id||void 0},C=r.contentType==="post"?{...k,excerpt:I(u.excerpt),label:I(u.label),published_at:u.published_at??new Date().toISOString(),subtitle:I(u.subtitle)}:k,E=P({action:"TRANSLATE",context:t,payload:{createInput:C,sourceId:u.id,tool:"translate_page"},preview:{blockCount:p.length,contentType:r.contentType,languageCode:b.code,slug:k.slug,status:k.status,summary:`Publish a ${b.code.toUpperCase()} translation of "${y}" — it goes live immediately, linked to the original ${r.contentType}, at /${k.slug} with ${N(p.length,"translated block")}.`,title:w},subject:`translate ${r.contentType} ${u.id} to ${b.code}`});if(E)return E;const O={...t,skipConfirmation:!0};return{...r.contentType==="post"?await qe(C,O):await Re(C,O),isTranslation:!0,languageCode:b.code}}async function At(e,t){const n=pe.parse(e),r=n.entityId!==void 0||!!n.slug||!!n.title,o=x(t);let i,a;if(r){const p=await Y({contentType:n.contentType,entityId:n.entityId,slug:n.slug,title:n.title},t),b=p.item;a=b.id,i={contentType:p.contentType,entityId:a,slug:typeof b.slug=="string"?b.slug:"",title:typeof b.title=="string"?b.title:""}}else i=Jn(t),a=M(i);const c=i.title||i.slug||"current item",u=i.contentType==="product",d=P({action:"SET IMAGES",context:t,payload:{contentType:i.contentType,entityId:String(a),images:n.images,tool:"set_content_images"},preview:{contentType:i.contentType,imageCount:n.images.length,slug:i.slug,summary:u?`Set ${N(n.images.length,"image")} on product "${c}" (the first becomes the main product image, the rest the gallery).`:`Set the feature image on the ${i.contentType} "${c}".`,title:i.title},subject:`set images on ${i.contentType} ${String(a)}`});if(d)return d;const l=await Jt(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:p,error:b}=await o.from("products").select("id, slug, language_id, title").eq("id",a).maybeSingle();if(b||!p)throw new Error(`Could not load the product to set images: ${_(b)}`);const y=await Qn({mediaIds:l,productId:a,supabase:o});return await Oe({patch:({meta:w})=>Array.isArray(w.product_media)?{meta:{...w,product_media:y.map((I,T)=>({media_id:I,sort_order:T}))}}:{},productId:a,supabase:o}),U(t,{contentType:"product",entityId:String(a),languageId:p.language_id,slug:p.slug,title:p.title},p.slug),t?.revalidatePath?.("/cms/products"),{contentType:"product",entityId:a,imageCount:y.length,mutationExecuted:!0,slug:p.slug,success:!0}}const m=await W(t,i.contentType,a),h=i.contentType==="page"?"pages":"posts",{data:g,error:f}=await o.from(h).update({feature_image_id:l[0],updated_at:new Date().toISOString()}).eq("id",a).select("id, language_id, slug, status, title").single();if(f||!g)throw new Error(`Failed to set the feature image: ${_(f)}`);return await G(t,i.contentType,a,m),U(t,i,g.slug),{contentType:i.contentType,entityId:a,extraImagesIgnored:l.length-1,imageCount:1,mutationExecuted:!0,slug:g.slug,success:!0}}function ko(e){return{...zn.createCortexDatabaseAgentTools(e),...An.createCortexCustomBlockTools(e),...Pn.createCortexContentOpsTools(e),...Nn.createCortexThemingTools(e),...Un.createCortexSiteTools(e),fetch_ecommerce_stats:S.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=>un(t,e),inputSchema:Qe,strict:!0}),read_current_cms_item:S.tool({description:"Read a CMS item: page/post/product metadata plus page/post block summaries or content. Defaults to the item currently open in the CMS editor; with no editor open (MCP clients) pass `cmsTarget` with contentType plus slug, entityId, or title. Read-only.",execute:t=>dn(t,e),inputSchema:Ze,strict:!0}),search_documentation:S.tool({description:"Search the NextBlock documentation database and return concise source snippets for factual CMS guidance.",execute:t=>ln(t,e),inputSchema:Pe,strict:!0}),fetch_url_content:S.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=>Cn(t),inputSchema:Tt,strict:!0}),search_stock_photos:S.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=>vn(t,e),inputSchema:Ct,strict:!0}),manage_product_variants:S.tool({description:'Give a product sellable variations — size, flavour, colour, format — each with its own SKU, price, stock, and optional image. Define the option axes in `attributes` (name plus every term) and one entry in `variants` per purchasable combination, naming its term per attribute in `options`. Attributes and terms are global and reused across products, so an existing "Size" is matched rather than duplicated. Prices are in major units (25 = $25.00). The product\'s stock becomes the sum of its variants. Use mode "replace" to rebuild the variant set, "append" to add to it. Mutating: first returns a confirmation phrase; only executes after exact confirmation.',execute:t=>xn(t,e),inputSchema:St,strict:!0}),translate_content_bulk:S.tool({description:"Translate SEVERAL pages or posts into one language in a single call. Use this instead of repeating translate_page when making a site multilingual: pass the target language once and one entry per item, each with its own source-string -> translation map. Layout, blocks, and imagery are copied automatically and each copy is linked to its original as a translation. The language must exist first (manage_language). Items are processed independently, so one bad entry does not abandon the rest — check `failed` in the result. Mutating: first returns a confirmation phrase; only executes after exact confirmation.",execute:t=>En(t,e),inputSchema:xt,strict:!0}),publish_content_draft:S.tool({description:"Publish (or discard) the Live Draft staged on a page or post by generate_jsonb_layout / rewrite_page_draft. Publishing applies the draft blocks and metadata to the live record and snapshots a revision first, so it is reversible from Revision History; visibility (status/published_at) is never changed. Use this to finish a build that staged a draft — without it the new layout stays invisible on the public site. Target the record with contentType plus slug, entityId, or title. Mutating: first returns a confirmation phrase; only executes after exact confirmation.",execute:t=>$n(t,e),inputSchema:Et,strict:!0}),rewrite_page_draft:S.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=>Sn(t,e),inputSchema:vt,strict:!0}),translate_page:S.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. Targets the open page/post by default; with no editor open (MCP clients) pass `cmsTarget` with contentType plus slug, entityId, or title. Mutating: first returns a confirmation phrase; only creates the translation after exact confirmation.',execute:t=>zt(t,e),inputSchema:$t,strict:!0}),set_content_images:S.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). On a PAGE the feature image renders as a full-width title banner above the blocks, so never set one on the home page or on a page that opens with its own hero section — use update_site_identity `social_image` for that page's share preview instead; posts should always have one. 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=>At(t,e),inputSchema:pe,strict:!0}),create_cms_page:S.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 a form block with fields; the destination address is configured once in CMS -> Messages and is never stored on the block.",execute:t=>Re(t,e),inputSchema:ge,strict:!0}),create_cms_post:S.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=>qe(t,e),inputSchema:fe,strict:!0}),create_cms_product:S.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=>_t(t,e),inputSchema:he,strict:!0}),delete_cms_item:S.tool({description:"Delete a resolved page, post, or product after exact confirmation. Pages/posts delete all translations in the translation group and related navigation links. Mutating: refuses unless the latest user message includes the exact confirmation phrase.",execute:t=>It(t,e),inputSchema:be,strict:!0}),prepare_delete_cms_item:S.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=>bn(t,e),inputSchema:tt,strict:!0}),update_footer:S.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=>gt(t,e),inputSchema:ae,strict:!0}),update_content_block:S.tool({description:'Update the JSON content of an existing top-level page/post block. The block must belong to the item being edited — the open CMS editor, or the item named by `cmsTarget` (contentType plus slug, entityId, or title) when no editor is open, as with MCP clients. 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=>ht(t,e),inputSchema:le,strict:!0}),insert_content_block:S.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=>yt(t,e),inputSchema:me,strict:!0}),update_current_cms_fields:S.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=>ft(t,e),inputSchema:ce,strict:!0}),update_cms_item_field:S.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=>kt(t,e),inputSchema:ye,strict:!0}),update_navigation_bar:S.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=>mt(t,e),inputSchema:ie,strict:!0}),update_section_column_block:S.tool({description:"Update the content of one existing nested block inside a section block. The parent section must belong to the item being edited — the open CMS editor, or the item named by `cmsTarget` (contentType plus slug, entityId, or title) when no editor is open, as with MCP clients. 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=>bt(t,e),inputSchema:ue,strict:!0}),execute_cms_action_plan:S.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=>_n(t,e),inputSchema:nt,strict:!0})}}exports.buildVisibleContactIntroActionPlan=Hn;exports.cortexAiPageContextSchema=Ne;exports.createCmsPageInputSchema=ge;exports.createCmsPostInputSchema=fe;exports.createCmsProductInputSchema=he;exports.createCortexGlobalAgentTools=ko;exports.deleteCmsItemInputSchema=be;exports.executeCmsActionPlan=_n;exports.executeCmsActionPlanInputSchema=nt;exports.executeCreateCmsPage=Re;exports.executeCreateCmsPost=qe;exports.executeCreateCmsProduct=_t;exports.executeDeleteCmsItem=It;exports.executeFetchEcommerceStats=un;exports.executeFetchUrlContent=Cn;exports.executeInsertContentBlock=yt;exports.executeManageProductVariants=xn;exports.executePrepareDeleteCmsItem=bn;exports.executePublishContentDraft=$n;exports.executeReadCurrentCmsItem=dn;exports.executeRewritePageDraft=Sn;exports.executeSearchDocumentation=cn;exports.executeSearchDocumentationWithTimeout=ln;exports.executeSearchStockPhotos=vn;exports.executeSetContentImages=At;exports.executeTranslateContentBulk=En;exports.executeTranslatePage=zt;exports.executeUpdateCmsItemField=kt;exports.executeUpdateContentBlock=ht;exports.executeUpdateCurrentCmsFields=ft;exports.executeUpdateFooter=gt;exports.executeUpdateNavigationBar=mt;exports.executeUpdateSectionColumnBlock=bt;exports.fetchEcommerceStatsInputSchema=Qe;exports.fetchUrlContentInputSchema=Tt;exports.insertContentBlockInputSchema=me;exports.isBlockedFetchHost=ze;exports.manageProductVariantsInputSchema=St;exports.maybeTriggerStockPhotoDownloads=we;exports.navigationItemInputSchema=Xe;exports.prepareDeleteCmsItemInputSchema=tt;exports.publishContentDraftInputSchema=Et;exports.readCurrentCmsItemInputSchema=Ze;exports.resolveCortexAiStockPhotoProvider=lo;exports.resolveCortexAiStockPhotoProviders=De;exports.rewritePageDraftInputSchema=vt;exports.searchDocumentationInputSchema=Pe;exports.searchStockPhotosInputSchema=Ct;exports.setContentImagesInputSchema=pe;exports.translateContentBulkInputSchema=xt;exports.translatePageInputSchema=$t;exports.updateCmsItemFieldInputSchema=ye;exports.updateContentBlockInputSchema=le;exports.updateCurrentCmsFieldsInputSchema=ce;exports.updateFooterInputSchema=ae;exports.updateNavigationBarInputSchema=ie;exports.updateSectionColumnBlockInputSchema=ue;