@nextblock-cms/cortex 0.17.7 → 0.17.8
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.
- package/index.cjs.js +1 -1
- package/index.d.ts +3 -0
- package/index.es.js +237 -199
- package/lib/ai-global-agent-db-tools.cjs.js +1 -1
- package/lib/ai-global-agent-db-tools.d.ts +7 -0
- package/lib/ai-global-agent-db-tools.es.js +309 -192
- package/lib/ai-global-agent-site-tools.cjs.js +2 -0
- package/lib/ai-global-agent-site-tools.d.ts +1153 -0
- package/lib/ai-global-agent-site-tools.es.js +712 -0
- package/lib/ai-global-agent-theming-tools.cjs.js +2 -2
- package/lib/ai-global-agent-theming-tools.d.ts +18 -0
- package/lib/ai-global-agent-theming-tools.es.js +1 -0
- package/lib/ai-global-agent-tools.cjs.js +2 -2
- package/lib/ai-global-agent-tools.es.js +1826 -1925
- package/lib/block-content-schemas.cjs.js +1 -0
- package/lib/block-content-schemas.d.ts +216 -0
- package/lib/block-content-schemas.es.js +246 -0
- package/lib/mcp-tool-registry.cjs.js +4 -2
- package/lib/mcp-tool-registry.d.ts +15 -0
- package/lib/mcp-tool-registry.es.js +103 -70
- package/lib/site-brief.cjs.js +2 -0
- package/lib/site-brief.d.ts +159 -0
- package/lib/site-brief.es.js +109 -0
- package/package.json +4 -4
- package/lib/ai-global-agent-tools.d.ts +0 -4374
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const z=require("ai"),Cn=require("./ai-global-agent-db-tools.cjs.js"),zn=require("./ai-global-agent-custom-block-tools.cjs.js"),xn=require("./ai-global-agent-content-ops-tools.cjs.js"),Sn=require("./ai-global-agent-theming-tools.cjs.js"),jt=require("./editor-document-from-html.cjs.js");require("./zod-config.cjs.js");const i=require("zod"),H=["text","heading","image","button","posts_grid","video_embed","section","form","testimonial","product_grid","featured_product","cart","checkout","product_details"];async function V(e,t,n){if(e?.recordRevision)try{return await e.recordRevision({contentType:t,entityId:n,phase:"capture"})}catch(o){console.error("Cortex AI: failed to capture revision baseline",o);return}}async function M(e,t,n,o){if(!(!e?.recordRevision||o===void 0))try{await e.recordRevision({baseline:o,contentType:t,entityId:n,phase:"commit"})}catch(r){console.error("Cortex AI: failed to record revision",r)}}const En=1e4,$n={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"},qt=i.z.string().trim().min(1).max(2048).refine(e=>e.startsWith("/")||e.startsWith("#")||e.startsWith("http://")||e.startsWith("https://")||e.startsWith("mailto:")||e.startsWith("tel:"),"URL must be a relative path, hash link, http(s) URL, mailto URL, or tel URL."),xt=i.z.strictObject({label:i.z.string().trim().min(1).max(120),target:i.z.enum(["_self","_blank"]).optional(),url:qt}),We=xt.extend({children:i.z.array(xt).max(20).optional()}),An=i.z.strictObject({label:i.z.string().trim().min(1).max(120).optional(),url:qt.optional()}).refine(e=>!!(e.label||e.url),{message:"Navigation item match requires label or url."}),re=i.z.strictObject({items:i.z.array(We).min(1).max(30),languageCode:i.z.string().trim().min(2).max(80).default("en").describe('Locale code or language name, for example "en", "fr", "English", or "French".'),match:An.optional().describe('For mode "update", identifies the existing navigation item to update.'),mode:i.z.enum(["append","replace","update"]).default("append")}),oe=i.z.strictObject({copyright:i.z.record(i.z.string().trim().min(2).max(12),i.z.string().trim().min(1).max(500)).optional(),languageCode:i.z.string().trim().min(2).max(80).default("en").describe('Locale code or language name, for example "en", "fr", "English", or "French".'),links:i.z.array(We).min(1).max(30).optional()}),$e=i.z.strictObject({limit:i.z.number().int().min(1).max(8).default(4),query:i.z.string().trim().min(2).max(300)}),Je=i.z.object({currency:i.z.string().trim().min(3).max(3).optional().describe("Optional currency code for currency-specific monetary reports (e.g., USD, CAD). Do not set this for plain order-status counts unless the user asks for a currency."),query:i.z.string().describe("The analytical question about orders, products, or revenue."),reportType:i.z.enum(["revenue","orders","products","general"]).optional().default("general").describe("The focus area of the statistical report."),timeRange:i.z.enum(["today","this_month","last_7_days","last_30_days","last_month","last_90_days","all_time"]).optional().default("all_time").describe("The time period for the report. Use all_time for current order-status counts unless the user names a specific period.")}),Ae=i.z.strictObject({contentType:i.z.enum(["page","post","product"]),currentEditor:i.z.strictObject({blockId:i.z.union([i.z.number().int().positive(),i.z.string().trim().min(1).max(120)]).nullable().optional(),blockType:i.z.string().trim().min(1).max(80).nullable().optional(),field:i.z.string().trim().min(1).max(120).nullable().optional()}).optional(),entityId:i.z.union([i.z.number().int().positive(),i.z.string().trim().min(1).max(120)]),languageId:i.z.number().int().positive().nullable().optional(),slug:i.z.string().trim().min(1).max(300).nullable().optional(),title:i.z.string().trim().min(1).max(300).nullable().optional(),translationGroupId:i.z.string().trim().min(1).max(120).nullable().optional()}),Pn=i.z.enum(["page","post","product"]),W=i.z.strictObject({contentType:Pn.optional(),entityId:i.z.union([i.z.number().int().positive(),i.z.string().trim().min(1).max(120)]).optional(),slug:i.z.string().trim().min(1).max(300).optional(),title:i.z.string().trim().min(1).max(300).optional()}),ie=W.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."),Ye=i.z.strictObject({cmsTarget:ie,includeBlockContent:i.z.boolean().default(!1),includeBlocks:i.z.boolean().default(!0)}),ae=i.z.strictObject({cmsTarget:ie,fields:i.z.strictObject({description_json:i.z.unknown().optional(),excerpt:i.z.string().max(2e3).nullable().optional(),feature_image_id:i.z.string().trim().min(1).max(2048).nullable().optional().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:i.z.string().max(120).nullable().optional(),meta_description:i.z.string().max(500).nullable().optional(),meta_title:i.z.string().max(160).nullable().optional(),published_at:i.z.string().max(80).nullable().optional(),short_description:i.z.string().max(2e3).nullable().optional(),slug:i.z.string().trim().min(1).max(300).optional(),status:i.z.enum(["draft","published","active","archived"]).optional(),subtitle:i.z.string().max(300).nullable().optional(),title:i.z.string().trim().min(1).max(300).optional()}).partial()}),se=i.z.strictObject({blockId:i.z.number().int().positive(),blockType:i.z.enum(H).optional(),cmsTarget:ie,content:i.z.record(i.z.string(),i.z.unknown())}),ce=i.z.strictObject({blockIndex:i.z.number().int().min(0),blockType:i.z.enum(H).optional(),cmsTarget:ie,columnIndex:i.z.number().int().min(0),content:i.z.record(i.z.string(),i.z.unknown()),parentBlockId:i.z.number().int().positive()}),le=i.z.strictObject({blockType:i.z.enum(H),content:i.z.record(i.z.string(),i.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:i.z.number().int().min(0).optional()}),ue=W.extend({images:i.z.array(i.z.string().trim().min(1).max(2048)).min(1).max(12).describe("External https image URLs (imported into the media library automatically) and/or existing media library ids. The first entry is the feature image (pages/posts) or the main product image (products).")}),de=W.extend({anchorBlockId:i.z.number().int().positive().optional(),anchorBlockType:i.z.enum(H).optional(),block:le,position:i.z.enum(["before","after","start","end"]).default("end")}),pe=i.z.strictObject({blocks:i.z.array(le).max(20).optional(),contactEmail:i.z.string().email().optional(),feature_image_id:i.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:i.z.string().trim().min(2).max(80).optional(),meta_description:i.z.string().max(500).nullable().optional(),meta_title:i.z.string().max(160).nullable().optional(),slug:i.z.string().trim().min(1).max(300).optional(),status:i.z.enum(["draft","published","archived"]).default("draft"),title:i.z.string().trim().min(1).max(300),translationGroupId:i.z.string().trim().min(1).max(120).optional()}),me=i.z.strictObject({blocks:i.z.array(le).max(20).optional(),excerpt:i.z.string().max(2e3).nullable().optional(),feature_image_id:i.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:i.z.string().max(120).nullable().optional(),languageCode:i.z.string().trim().min(2).max(80).optional(),meta_description:i.z.string().max(500).nullable().optional(),meta_title:i.z.string().max(160).nullable().optional(),published_at:i.z.string().max(80).nullable().optional(),slug:i.z.string().trim().min(1).max(300).optional(),status:i.z.enum(["draft","published","archived"]).default("draft"),subtitle:i.z.string().max(300).nullable().optional(),title:i.z.string().trim().min(1).max(300),translationGroupId:i.z.string().trim().min(1).max(120).optional()}),ge=i.z.strictObject({blocks:i.z.array(le).max(20).optional().describe("Content blocks for the product description area, same block vocabulary as create_cms_page. Rendered on the public product page in place of the plain description."),description_html:i.z.string().max(6e4).optional().describe("The product body as an HTML fragment (headings, paragraphs, lists, bold/italic/links). Converted to the editor document automatically. Prefer this over description_json."),description_json:i.z.unknown().optional(),freemius_plan_id:i.z.string().optional(),freemius_product_id:i.z.string().optional(),images:i.z.array(i.z.string().trim().min(1).max(2048)).max(12).optional().describe("Product images, in order: the first becomes the main product image and the rest the gallery. Each entry is either an external https image URL (imported into the media library automatically) or an existing media library id."),is_taxable:i.z.boolean().default(!0),languageCode:i.z.string().trim().min(2).max(80).optional(),meta_description:i.z.string().max(500).nullable().optional(),meta_title:i.z.string().max(160).nullable().optional(),payment_provider:i.z.enum(["stripe","freemius"]).default("stripe"),price:i.z.number().min(0).default(0),prices:i.z.record(i.z.string(),i.z.number().min(0)).optional(),product_type:i.z.enum(["physical","digital"]).default("physical"),sale_price:i.z.number().min(0).nullable().optional(),sale_prices:i.z.record(i.z.string(),i.z.number().min(0).nullable()).optional(),short_description:i.z.string().max(2e3).nullable().optional(),sku:i.z.string().trim().min(1).max(120).optional(),slug:i.z.string().trim().min(1).max(300).optional(),status:i.z.enum(["draft","active","archived"]).default("draft"),stock:i.z.number().int().min(0).default(0),title:i.z.string().trim().min(1).max(300),trial_period_days:i.z.number().int().min(0).default(0),trial_requires_payment_method:i.z.boolean().default(!1),translationGroupId:i.z.string().trim().min(1).max(120).optional(),upc:i.z.string().max(120).nullable().optional()}),fe=W.extend({currencyCode:i.z.string().trim().min(3).max(3).optional(),endsAt:i.z.string().max(80).nullable().optional(),field:i.z.string().trim().min(1).max(120),startsAt:i.z.string().max(80).nullable().optional(),value:i.z.unknown()}),Xe=W,he=W,Mt=i.z.discriminatedUnion("tool",[i.z.strictObject({input:pe,tool:i.z.literal("create_cms_page")}),i.z.strictObject({input:me,tool:i.z.literal("create_cms_post")}),i.z.strictObject({input:ge,tool:i.z.literal("create_cms_product")}),i.z.strictObject({input:he,tool:i.z.literal("delete_cms_item")}),i.z.strictObject({input:fe,tool:i.z.literal("update_cms_item_field")}),i.z.strictObject({input:se,tool:i.z.literal("update_content_block")}),i.z.strictObject({input:de,tool:i.z.literal("insert_content_block")}),i.z.strictObject({input:ae,tool:i.z.literal("update_current_cms_fields")}),i.z.strictObject({input:oe,tool:i.z.literal("update_footer")}),i.z.strictObject({input:re,tool:i.z.literal("update_navigation_bar")}),i.z.strictObject({input:ce,tool:i.z.literal("update_section_column_block")}),i.z.strictObject({input:ue,tool:i.z.literal("set_content_images")})]),Nn=i.z.union([pe.extend({tool:i.z.literal("create_cms_page")}).transform(({tool:e,...t})=>({input:t,tool:e})),me.extend({tool:i.z.literal("create_cms_post")}).transform(({tool:e,...t})=>({input:t,tool:e})),ge.extend({tool:i.z.literal("create_cms_product")}).transform(({tool:e,...t})=>({input:t,tool:e})),he.extend({tool:i.z.literal("delete_cms_item")}).transform(({tool:e,...t})=>({input:t,tool:e})),fe.extend({tool:i.z.literal("update_cms_item_field")}).transform(({tool:e,...t})=>({input:t,tool:e})),se.extend({tool:i.z.literal("update_content_block")}).transform(({tool:e,...t})=>({input:t,tool:e})),de.extend({tool:i.z.literal("insert_content_block")}).transform(({tool:e,...t})=>({input:t,tool:e})),ae.extend({tool:i.z.literal("update_current_cms_fields")}).transform(({tool:e,...t})=>({input:t,tool:e})),oe.extend({tool:i.z.literal("update_footer")}).transform(({tool:e,...t})=>({input:t,tool:e})),re.extend({tool:i.z.literal("update_navigation_bar")}).transform(({tool:e,...t})=>({input:t,tool:e})),ce.extend({tool:i.z.literal("update_section_column_block")}).transform(({tool:e,...t})=>({input:t,tool:e})),ue.extend({tool:i.z.literal("set_content_images")}).transform(({tool:e,...t})=>({input:t,tool:e}))]),Un=i.z.string().transform((e,t)=>{const n=Bn(e);return n.success?n.action:(t.addIssue({code:"custom",message:n.message}),i.z.NEVER)}),On=i.z.union([Mt,Nn,Un]),Qe=i.z.strictObject({actions:i.z.array(On).min(1).max(8),summary:i.z.string().trim().min(1).max(500).optional()});function Fn(e){const t=[];let n="",o=0,r=null,a=!1;for(const s of e){if(r){n+=s,a?a=!1:s==="\\"?a=!0:s===r&&(r=null);continue}if(s==='"'||s==="'"){r=s,n+=s;continue}if(s==="["||s==="{"||s==="("){o++,n+=s;continue}if(s==="]"||s==="}"||s===")"){o=Math.max(0,o-1),n+=s;continue}if(s===","&&o===0){n.trim()&&t.push(n.trim()),n="";continue}n+=s}return n.trim()&&t.push(n.trim()),t}function St(e){let t="";for(let n=0;n<e.length;n++){const o=e[n];if(o!=="'"){t+=o;continue}let r="",a=!1;for(n++;n<e.length;n++){const s=e[n];if(a){r+=s,a=!1;continue}if(s==="\\"){a=!0;continue}if(s==="'")break;r+=s}t+=JSON.stringify(r)}return t.replace(/\bTrue\b/g,"true").replace(/\bFalse\b/g,"false").replace(/\bNone\b/g,"null")}function Ln(e){const t=e.trim();return t.startsWith("'")&&t.endsWith("'")||t.startsWith('"')&&t.endsWith('"')||t.startsWith("[")||t.startsWith("{")?JSON.parse(St(t)):/^-?\d+(?:\.\d+)?$/.test(t)?Number(t):t==="true"||t==="True"?!0:t==="false"||t==="False"?!1:t==="null"||t==="None"?null:t}function Rn(e){const t={};for(const n of Fn(e)){const o=n.indexOf("=");if(o<=0)throw new Error(`Expected key=value argument, received "${n}".`);const r=n.slice(0,o).trim();if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(r))throw new Error(`Invalid argument name "${r}".`);t[r]=Ln(n.slice(o+1))}return t}function Bn(e){const n=e.trim().match(/^([a-z_]+)\(([\s\S]*)\)$/);if(!n)return{message:'Action plan actions must be JSON objects like { "tool": "create_cms_page", "input": { ... } }, not freeform text.',success:!1};const o=n[1];let r;try{r=Rn(n[2])}catch(c){return{message:c instanceof Error?c.message:"Could not parse action-plan command arguments.",success:!1}}const a={input:r,tool:o},s=Mt.safeParse(a);return s.success?{action:s.data,success:!0}:{message:`Invalid action-plan command "${o}": ${s.error.issues.map(c=>c.message).join("; ")}`,success:!1}}function jn(e){return e.normalize("NFD").replace(/[\u0300-\u036f]/g,"").toLowerCase().replace(/\s+/g," ").trim()}function _e(e,t){return t.some(n=>e.includes(n))}function qn(e){const t=jn(e),n=_e(t,["add ","insert ","put ","create "]),o=_e(t,["title","heading","description","intro","copy","paragraph"]),r=t.includes("form")&&_e(t,["above","before"]),a=t.includes("contact page")||t.includes("contact pages")||t.includes("contact us")||t.includes("contactez-nous"),s=t.includes("english")&&_e(t,["french","francais","francaise"]);return!n||!o||!r||!a||!s?null:{actions:[{input:{anchorBlockType:"form",block:{blockType:"text",content:{html_content:"<h2>Let us help you move faster</h2><p>Have a question, project idea, or need help choosing the right next step? Send us a message and the NextBlock team will get back to you soon.</p>"}},contentType:"page",position:"before",slug:"contact-us"},tool:"insert_content_block"},{input:{anchorBlockType:"form",block:{blockType:"text",content:{html_content:"<h2>Parlons de votre projet</h2><p>Vous avez une question, une idee de projet ou besoin d'aide pour avancer? Envoyez-nous un message et l'equipe NextBlock vous repondra rapidement.</p>"}},contentType:"page",position:"before",slug:"contactez-nous"},tool:"insert_content_block"}],summary:"Add visible title and description copy above the forms on the English and French Contact pages."}}const Mn=i.z.enum(H),Et=i.z.object({direction:i.z.string().optional(),stops:i.z.array(i.z.object({color:i.z.string(),position:i.z.number()})),type:i.z.enum(["linear","radial"])}),Dn=i.z.object({gradient:Et.optional(),image:i.z.object({alt_text:i.z.string().optional(),blur_data_url:i.z.string().optional(),external_url:i.z.string().optional(),height:i.z.number().optional(),media_id:i.z.string().optional(),object_key:i.z.string().optional(),overlay:i.z.object({gradient:Et,type:i.z.literal("gradient")}).optional(),position:i.z.enum(["center","top","bottom","left","right"]),quality:i.z.number().nullable().optional(),size:i.z.enum(["cover","contain"]),width:i.z.number().optional()}).optional(),min_height:i.z.string().optional(),solid_color:i.z.string().optional(),theme:i.z.enum(["primary","secondary","muted","accent","destructive"]).optional(),type:i.z.enum(["none","theme","solid","gradient","image"])}),Gn=i.z.object({block_type:Mn,content:i.z.record(i.z.string(),i.z.any()),temp_id:i.z.string().optional()}),Kn=i.z.object({background:Dn,column_blocks:i.z.array(i.z.array(Gn)),column_gap:i.z.enum(["none","sm","md","lg","xl"]),container_type:i.z.enum(["full-width","container","container-sm","container-lg","container-xl"]),padding:i.z.object({bottom:i.z.enum(["none","sm","md","lg","xl"]),top:i.z.enum(["none","sm","md","lg","xl"])}),responsive_columns:i.z.object({desktop:i.z.union([i.z.literal(1),i.z.literal(2),i.z.literal(3),i.z.literal(4)]),mobile:i.z.union([i.z.literal(1),i.z.literal(2)]),tablet:i.z.union([i.z.literal(1),i.z.literal(2),i.z.literal(3)])}),vertical_alignment:i.z.enum(["start","center","end","stretch"]).optional()}),Hn={button:i.z.object({position:i.z.enum(["left","center","right"]).optional(),size:i.z.enum(["default","sm","lg","full"]).optional(),text:i.z.string(),url:i.z.string(),variant:i.z.enum(["default","outline","secondary","ghost","link"]).optional()}),cart:i.z.object({}),checkout:i.z.object({}),featured_product:i.z.object({imagePosition:i.z.enum(["left","right"]).default("left"),productId:i.z.string().min(1),showBackground:i.z.boolean().default(!1)}),form:i.z.object({fields:i.z.array(i.z.object({field_type:i.z.enum(["text","email","textarea","select","radio","checkbox"]),is_required:i.z.boolean(),label:i.z.string(),options:i.z.array(i.z.object({label:i.z.string(),value:i.z.string()})).optional(),placeholder:i.z.string().optional(),temp_id:i.z.string()})),form_key:i.z.string().optional(),recipient_email:i.z.string().email().optional(),submit_button_text:i.z.string(),success_message:i.z.string()}),heading:i.z.object({level:i.z.union([i.z.literal(1),i.z.literal(2),i.z.literal(3),i.z.literal(4),i.z.literal(5),i.z.literal(6)]),textAlign:i.z.enum(["left","center","right","justify"]).optional(),textColor:i.z.union([i.z.enum(["foreground","primary","secondary","accent","muted","destructive","background"]),i.z.string().regex(/^(#(?:[0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})|rgba?\([^)]+\)|hsla?\([^)]+\))$/i,"Must be a hex, rgb(a) or hsl(a) colour")]).optional().describe("Prefer a theme token so the heading adapts to dark mode; use a CSS colour only when the brand requires an exact value"),text_content:i.z.string()}),image:i.z.object({alt_text:i.z.string().optional(),caption:i.z.string().optional(),external_url:i.z.string().nullable().optional(),height:i.z.number().nullable().optional(),media_id:i.z.string().nullable().optional(),object_key:i.z.string().nullable().optional(),width:i.z.number().nullable().optional()}),posts_grid:i.z.object({columns:i.z.number().min(1).max(6),postsPerPage:i.z.number().min(1).max(50),showPagination:i.z.boolean(),title:i.z.string().optional()}),product_details:i.z.object({}),product_grid:i.z.object({categoryId:i.z.string().optional(),categoryIds:i.z.array(i.z.string()).max(20).optional(),limit:i.z.number().min(0).max(48).default(6),productIds:i.z.array(i.z.string()).max(24).optional(),showPagination:i.z.boolean().default(!1),title:i.z.string().optional(),type:i.z.enum(["latest","category","manual"]).default("latest")}),section:Kn,testimonial:i.z.object({author_name:i.z.string().min(1),author_title:i.z.string().optional(),image_url:i.z.string().url().optional().or(i.z.literal("")),quote:i.z.string().min(1)}),text:i.z.object({html_content:i.z.string()}),video_embed:i.z.object({autoplay:i.z.boolean().optional(),controls:i.z.boolean().optional(),title:i.z.string().optional(),url:i.z.string()})};function Vn(e){return H.includes(e)}function Wn(e){return typeof e?.validateBlockContent=="function"?e.validateBlockContent:null}function Jn(e,t,n){const o=Wn(n);if(o)return o(e,t);const r=Hn[e].safeParse(t);return r.success?{errors:[],isValid:!0,warnings:[]}:{errors:r.error.issues.map(a=>{const s=a.path.join(".");return s?`${s}: ${a.message}`:a.message}),isValid:!1,warnings:[]}}function $t(){return i.z.object({content:i.z.array(i.z.any()).optional(),type:i.z.literal("doc")})}function Ze(){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 Yn(e,t,n){let o;const r=new Promise(a=>{o=setTimeout(()=>a(n()),t)});return Promise.race([e.finally(()=>{o&&clearTimeout(o)}),r])}function Xn(e){const t=Ae.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 Pe(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 Dt(e){const t=String(e.entityId||"").trim();if(!t)throw new Error(`Current ${e.contentType} id is missing.`);return t}function q(e){return e.contentType==="product"?Dt(e):Pe(e)}const Qn=/^https?:\/\//i,Zn=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;async function X(e,t,n){if(typeof e!="string")return null;const o=e.trim();if(!o)return null;if(!Qn.test(o)){if(Zn.test(o))return o;throw new Error(`"${o}" is not a usable image reference — provide an https:// image URL or a media library id.`)}const r=t?.importExternalImage;if(!r)throw new Error("I can only attach an image from a URL when media import is available here. Please pick an image from the media library instead.");const a=await r({altText:n,url:o});if("error"in a)throw new Error(`I could not import the image from that URL: ${a.error}`);return a.id}async function Gt(e,t,n){const o=[];for(let r=0;r<e.length;r+=1){const a=await X(e[r],t,`${n} image ${r+1}`);a&&o.push(a)}return o}async function er(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:o}=await e.supabase.from("product_media").insert(t.map((r,a)=>({media_id:r,product_id:e.productId,sort_order:a})));if(o)throw new Error(`Could not save the product images: ${b(o)}`)}return t}async function Ne(e){if(!e.productId)return!1;const{data:t,error:n}=await e.supabase.from("product_drafts").select("id, blocks, meta").eq("product_id",e.productId).maybeSingle();if(n||!t)return!1;const o=e.patch({blocks:Array.isArray(t.blocks)?K(t.blocks):[],meta:$(t.meta)?K(t.meta):{}}),r={updated_at:new Date().toISOString()};if(o.blocks&&(r.blocks=o.blocks),o.meta&&(r.meta=o.meta),Object.keys(r).length===1)return!1;const{error:a}=await e.supabase.from("product_drafts").update(r).eq("id",t.id);if(a)throw new Error(`The product was updated, but its open draft could not be kept in sync: ${b(a)}. Publishing that draft would undo this change — publish or discard it in the product editor first.`);return!0}function Kt(e){return typeof e=="string"?e.trim().replace(/^\/+|\/+$/g,""):""}function tr(e,t){const n=Kt(t??e.slug);return n?e.contentType==="page"?n==="home"?"/":`/${n}`:e.contentType==="post"?`/article/${n}`:`/product/${n}`:null}function nr(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 o=e?.revalidatePath??Ze();if(!o)return;o(nr(t));const r=tr(t,n);r&&o(r),t.contentType==="page"&&r!=="/"&&o("/"),t.contentType==="product"&&o("/cms/products")}function Ht(e){const t=e?.revalidatePath??Ze();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 rr(){return Promise.resolve().then(()=>require("./ai-global-agent-ecommerce.cjs.js"))}function Be(e){return e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?`[${e.map(t=>Be(t)).join(",")}]`:`{${Object.keys(e).filter(t=>t!=="temp_id").sort().map(t=>`${JSON.stringify(t)}:${Be(e[t])}`).join(",")}}`}function or(e){let t=2166136261;const n=Be(e);for(let o=0;o<n.length;o++)t^=n.charCodeAt(o),t=Math.imul(t,16777619);return(t>>>0).toString(16).padStart(8,"0")}function je(e){return e.replace(/\s+/g," ").trim().toUpperCase()}function ir(e,t,n){return`${je(`CONFIRM ${e} ${t}`)} #${or(n)}`}function Vt(e){return{confirmationPhrase:ir(e.action,e.subject,e.payload),mutationExecuted:!1,preview:e.preview,requiresConfirmation:!0,success:!0}}function L(e,t){const n=e[t];return typeof n=="string"&&n.trim()?n.trim():null}function D(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 ar(e,t){const n=L(t,"summary");if(n)return n;const o=L(t,"title"),r=L(t,"slug"),a=L(t,"status"),s=L(t,"contentType"),c=L(t,"field"),u=L(t,"mode"),d=L(t,"languageCode"),l=D(t,"blockCount"),p=D(t,"itemCount"),h=D(t,"affectedCount");if(e==="create_cms_page"||e==="create_cms_post")return`Create ${a||"draft"} ${e==="create_cms_page"?"page":"post"} "${o||r||"Untitled"}"${r?` at slug "${r}"`:""}${l!==null?` with ${N(l,"content block")}`:""}.`;if(e==="create_cms_product"){const m=D(t,"imageCount"),f=D(t,"blockCount"),g=[m?N(m,"image"):null,f?N(f,"description block"):D(t,"descriptionLength")?"a full description":null].filter(Boolean);return`Create ${a||"draft"} product "${o||r||"Untitled"}"${r?` at slug "${r}"`:""}${g.length?` with ${g.join(" and ")}`:""}.`}if(e==="update_cms_item_field")return`Update ${c||"one field"} on the ${s||"CMS item"} "${o||r||"selected item"}".`;if(e==="update_navigation_bar")return`${u==="append"?"Add":u==="update"?"Update":"Replace"} ${p!==null?N(p,"navigation item"):"navigation items"} in the ${d||"selected"} header navigation.`;if(e==="update_footer"){const m=D(t,"linkCount");return`Update the ${d||"selected"} footer${m!==null?` with ${N(m,"link")}`:""}.`}return e==="update_content_block"?`Update the selected ${L(t,"blockType")||"content"} block.`:e==="insert_content_block"?`Insert ${L(t,"blockType")||"content"} block on the ${s||"CMS item"} "${o||r||"selected item"}".`:e==="update_section_column_block"?`Update the selected nested ${L(t,"nestedBlockType")||"section"} block.`:e==="delete_cms_item"||e==="prepare_delete_cms_item"?`Delete ${h!==null?N(h,s||"CMS item"):`the selected ${s||"CMS item"}`}${o||r?` for "${o||r}"`:""}.`:"Complete the requested CMS change."}function P(e){if(e.context?.skipConfirmation)return null;const t=Vt(e),n=je(e.context?.latestUserMessage||""),o=je(t.confirmationPhrase);return n.includes(o)?null:t}function et(e){const t=e?.actorUserId;if(!t)throw new Error("A confirmed CMS mutation requires an authenticated admin actor.");return t}function tt(){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 nt(e){return(e||"USD").trim().toUpperCase()}const sr=new Set(["BIF","CLP","DJF","GNF","JPY","KMF","KRW","MGA","PYG","RWF","UGX","VND","VUV","XAF","XOF","XPF"]);function cr(e){return sr.has(nt(e))?0:2}function Te(e,t){return Math.round(e*10**cr(t))}function lr(e,t){return!e||typeof e!="object"||Array.isArray(e)?{}:Object.entries(e).reduce((n,[o,r])=>{if(typeof r=="number"&&Number.isFinite(r)&&r>=0){const a=nt(o||t);n[a]=Te(r,a)}return n},{})}function ye(e,t){if(!$(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 $(e){return!!(e&&typeof e=="object"&&!Array.isArray(e))}function qe(e,t){const n=K(e);for(const[o,r]of Object.entries(t))if(r!==void 0){if($(r)&&$(n[o])){n[o]=qe(n[o],r);continue}n[o]=K(r)}return n}function Wt(e,t){if(t.contentType==="product"){if(String(e.product_id??"")!==String(Dt(t)))throw new Error(`Block ${e.id} does not belong to the current product being edited.`);return}const n=Pe(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 ve(e,t){const n=typeof e=="string"?e:"";if(!Vn(n))throw new Error(`${t} has unsupported block type "${n||"unknown"}".`);return n}function Jt(e,t,n){if(e&&e!==t)throw new Error(`${n} is a "${t}" block. Refusing to update it as "${e}".`)}function G(e,t,n,o){const r=Jn(e,t,o);if(!r.isValid)throw new Error(`${n} content is invalid for block type "${e}": ${r.errors.join("; ")}`)}function Yt(e){return e==="section"}function ur(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 Ce(e){return`ai-${e}-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}function Me(e,t,n){if(!$(e))throw new Error(`${t} must be a JSON object.`);const o=e.block_type??e.blockType,r=ve(o,t);if(Yt(r))throw new Error(`${t} cannot be a nested ${r} block.`);const a=en(r,ye(e.content,t),t,n),s=e.temp_id??e.tempId,c=typeof s=="string"&&s.trim()?s:Ce(r);return{block_type:r,content:a,temp_id:c}}function dr(e,t){const n=[];if("append_block"in e&&n.push(Me(e.append_block,"Nested block to append",t)),"append_blocks"in e){const o=e.append_blocks;if(!Array.isArray(o))throw new Error("append_blocks must be an array of nested block objects.");o.forEach((r,a)=>{n.push(Me(r,`Nested block to append ${a}`,t))})}return n}function pr(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=ur(e);if(!n)return null;const o=ye(e,`Nested ${n} block`);return G(n,o,`Nested ${n} block`,t),{block_type:n,content:o,temp_id:Ce(n)}}function mr(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 gr(e,t,n,o){if(!Yt(e))return qe(t,n);const r={...n},a=dr(r,o),s=pr(r,o);s&&a.push(s),delete r.append_block,delete r.append_blocks,delete r.append_column_index,delete r.column_index;const c=qe(t,r);if(a.length>0){const u=Array.isArray(t.column_blocks)?K(t.column_blocks):[],d=mr(n,u.length),l=u.length>0?u:[[]];for(;l.length<=d;)l.push([]);l[d]=[...l[d]||[],...a],c.column_blocks=l}return c}function fr(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 Y(e){return typeof e=="string"?e.trim().toLowerCase():""}function At(e){return typeof e=="string"?e.trim().toLowerCase():""}function Xt(e){return e.reduce((t,n)=>t+1+(n.children?.length||0),0)}function Ie(e){return typeof e=="string"?e.trim().toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g,""):""}async function Q(e,t){const n=t.trim(),o=Ie(n),r=$n[o],{data:a,error:s}=await e.from("languages").select("id, code, name, is_active");if(s)throw new Error(`Failed to load language "${t}": ${b(s)}`);const u=(Array.isArray(a)?a:[]).filter(l=>l.is_active!==!1),d=u.find(l=>{const p=Ie(l.code),h=Ie(l.name);return p===o||p===r||h===o});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 Ue(e,t){if(t)return Q(e,t);const{data:n,error:o}=await e.from("languages").select("id, code, name, is_active, is_default");if(o)throw new Error(`Failed to load active languages: ${b(o)}`);const r=(Array.isArray(n)?n:[]).filter(s=>s.is_active!==!1),a=r.find(s=>s.is_default)||r.find(s=>Ie(s.code)==="en")||r[0];if(!a?.id||!a?.code)throw new Error("No active CMS language is available for Cortex AI content creation.");return{code:String(a.code),id:Number(a.id)}}async function De(e){try{const{data:t,error:n}=await e.from("currencies").select("code, is_default, is_active").eq("is_active",!0);if(n)return"USD";const o=Array.isArray(t)?t:[],r=o.find(a=>a.is_default)||o[0];return nt(r?.code||"USD")}catch{return"USD"}}async function hr(e){const t=e.contentType==="page"?"pages":e.contentType==="post"?"posts":"products";let n="id",o=e.entityId;if(o===void 0&&e.slug&&(n="slug",o=e.slug),o===void 0&&e.title&&(n="title",o=e.title),o===void 0)throw new Error(`A ${e.contentType} target requires an id, slug, title, or current edit context.`);const{data:r,error:a}=await e.supabase.from(t).select("*").eq(n,o);if(a)throw new Error(`Failed to resolve ${e.contentType}: ${b(a)}`);const s=Array.isArray(r)?r:r?[r]:[];if(s.length!==1)throw new Error(s.length===0?`No ${e.contentType} matched ${n} "${String(o)}".`:`Multiple ${e.contentType}s matched ${n} "${String(o)}"; use an exact id.`);return s[0]}async function J(e,t){const n=Ae.safeParse(t?.pageContext).success?t?.pageContext:null,o=e.contentType||n?.contentType;if(!o)throw new Error("Target contentType is required when no current CMS edit context exists.");const r=e.entityId!==void 0||!!e.slug||!!e.title,a=e.entityId??(r?void 0:n?.entityId),s=e.slug??(r?void 0:n?.slug??void 0),c=e.title??(r?void 0:n?.title??void 0),u=await hr({contentType:o,entityId:a,slug:a===void 0&&s||void 0,supabase:x(t),title:a===void 0&&!s&&c||void 0});return{contentType:o,item:u}}async function Z(e,t){const n=Ae.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 r=await J(e,t),a=r.item;return{contentType:r.contentType,entityId:a.id,slug:typeof a.slug=="string"?a.slug:"",title:typeof a.title=="string"?a.title:""}}async function ze(e){const t=await br({item:e.item,languageId:e.languageId,menuKey:e.menuKey,supabase:e.supabase}),n={label:e.item.label,language_id:e.languageId,menu_key:e.menuKey,order:e.order,page_id:t?.pageId??null,parent_id:e.parentId??null,...t?.navigationTranslationGroupId?{translation_group_id:t.navigationTranslationGroupId}:{},url:e.item.url},{data:o,error:r}=await e.supabase.from("navigation_items").insert(n).select("id").single();if(r)throw new Error(`Failed to insert ${e.menuKey} navigation item: ${b(r)}`);return Number(o.id)}function yr(e){const t=e.trim();if(!t.startsWith("/")||t.startsWith("//"))return null;const n=t.split("?")[0]?.split("#")[0]||"",o=n==="/"?"home":n.replace(/^\/+|\/+$/g,"");return o&&!o.includes("/")?o:null}async function br(e){const t=yr(e.item.url);if(!t)return null;const{data:n,error:o}=await e.supabase.from("pages").select("id, slug, translation_group_id, language_id").eq("slug",t).eq("language_id",e.languageId);if(o)throw new Error(`Failed to resolve linked page for navigation item: ${b(o)}`);const r=Array.isArray(n)?n[0]:n;if(!r?.id)return null;let a=tt();if(r.translation_group_id){const{data:s,error:c}=await e.supabase.from("pages").select("id").eq("translation_group_id",r.translation_group_id);if(c)throw new Error(`Failed to inspect linked page translations for navigation item: ${b(c)}`);const u=new Set((Array.isArray(s)?s:[]).map(h=>String(h.id)).filter(Boolean)),{data:d,error:l}=await e.supabase.from("navigation_items").select("id, page_id, translation_group_id, menu_key").eq("menu_key",e.menuKey);if(l)throw new Error(`Failed to inspect related navigation translations: ${b(l)}`);const p=(Array.isArray(d)?d:[]).find(h=>h.translation_group_id&&u.has(String(h.page_id)));p?.translation_group_id&&(a=p.translation_group_id)}return{navigationTranslationGroupId:a,pageId:Number(r.id)}}async function Qt(e){const t=await Q(e.supabase,e.languageCode),{data:n,error:o}=await e.supabase.from("navigation_items").select("id, parent_id").eq("menu_key",e.menuKey).eq("language_id",t.id);if(o)throw new Error(`Failed to inspect existing ${e.menuKey} navigation items: ${b(o)}`);const r=Array.isArray(n)?n:[],a=r.filter(d=>d.parent_id==null).length,s=Xt(e.items);Zt({existingItemCount:r.length,existingTopLevelCount:a,languageCode:t.code,menuKey:e.menuKey,replacementItemCount:s});const{error:c}=await e.supabase.from("navigation_items").delete().eq("menu_key",e.menuKey).eq("language_id",t.id);if(c)throw new Error(`Failed to clear ${e.menuKey} navigation items: ${b(c)}`);let u=0;for(const[d,l]of e.items.entries()){const p=await ze({item:l,languageId:t.id,menuKey:e.menuKey,order:d,supabase:e.supabase});u++;for(const[h,m]of(l.children??[]).entries())await ze({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 Zt(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 _r(e){const t=await Q(e.supabase,e.languageCode),{data:n,error:o}=await e.supabase.from("navigation_items").select("id, parent_id").eq("menu_key",e.menuKey).eq("language_id",t.id);if(o)throw new Error(`Failed to inspect existing ${e.menuKey} navigation items: ${b(o)}`);const r=Array.isArray(n)?n:[];Zt({existingItemCount:r.length,existingTopLevelCount:r.filter(a=>a.parent_id==null).length,languageCode:t.code,menuKey:e.menuKey,replacementItemCount:Xt(e.items)})}async function wr(e){if(e.items.length!==1)throw new Error('mode "update" requires exactly one navigation item.');const t=await Q(e.supabase,e.languageCode),n=e.items[0],o=Y(e.match?.url)||Y(n.url),r=At(e.match?.label),{data:a,error:s}=await e.supabase.from("navigation_items").select("id, label, url, parent_id, order").eq("menu_key",e.menuKey).eq("language_id",t.id);if(s)throw new Error(`Failed to load existing ${e.menuKey} navigation items: ${b(s)}`);const u=(Array.isArray(a)?a:[]).find(l=>{const p=Y(l.url),h=At(l.label);return!!(o&&p===o||r&&h===r)});if(!u?.id)throw new Error(`Could not find a ${e.menuKey} navigation item to update in ${t.code}. Use a matching label or url.`);const{error:d}=await e.supabase.from("navigation_items").update({label:n.label,url:n.url}).eq("id",u.id);if(d)throw new Error(`Failed to update ${e.menuKey} navigation item: ${b(d)}`);return{insertedCount:0,languageCode:t.code,menuKey:e.menuKey,skippedCount:0,updatedCount:1}}async function kr(e){const t=await Q(e.supabase,e.languageCode),{data:n,error:o}=await e.supabase.from("navigation_items").select("id, url, parent_id, order").eq("menu_key",e.menuKey).eq("language_id",t.id);if(o)throw new Error(`Failed to load existing ${e.menuKey} navigation items: ${b(o)}`);let r=0,a=0;const s=Array.isArray(n)?n:[],c=new Set(s.map(l=>Y(l.url)).filter(Boolean)),u=s.filter(l=>l.parent_id==null).map(l=>Number(l.order)).filter(Number.isFinite);let d=u.length>0?Math.max(...u)+1:s.length;for(const l of e.items){const p=Y(l.url);if(p&&c.has(p)){a++;continue}const h=await ze({item:l,languageId:t.id,menuKey:e.menuKey,order:d,supabase:e.supabase});r++,d++,p&&c.add(p);let m=0;for(const f of l.children??[]){const g=Y(f.url);if(g&&c.has(g)){a++;continue}await ze({item:f,languageId:t.id,menuKey:e.menuKey,order:m,parentId:h,supabase:e.supabase}),r++,m++,g&&c.add(g)}}return{insertedCount:r,languageCode:t.code,menuKey:e.menuKey,skippedCount:a,updatedCount:0}}function E(e){return typeof e=="string"&&e.trim()?e.trim():""}function Ir(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function Tr(e){const t=E(e.field_type??e.fieldType??e.type??e.input_type).toLowerCase().replace(/\s+/g,"_"),n=E(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 vr(e){return(Array.isArray(e)&&e.length>0?e:[{field_type:"text",is_required:!0,label:"Name",placeholder:"Your name"},{field_type:"email",is_required:!0,label:"Email",placeholder:"you@example.com"},{field_type:"textarea",is_required:!0,label:"Message",placeholder:"How can we help?"}]).map((n,o)=>{const r=$(n)?n:{},a=E(r.label??r.name)||(o===0?"Name":o===1?"Email":"Message"),s=Tr({...r,label:a}),c=r.is_required??r.isRequired??r.required;return{field_type:s,is_required:typeof c=="boolean"?c:!0,label:a,options:Array.isArray(r.options)?r.options:void 0,placeholder:E(r.placeholder)||void 0,temp_id:E(r.temp_id??r.tempId??r.id)||`field-${o+1}`}})}const Cr=new Set(["none","sm","md","lg","xl"]),Pt=new Set(["none","sm","md","lg","xl"]),zr=new Set(["full-width","container","container-sm","container-lg","container-xl"]),xr=new Set(["start","center","end","stretch"]),Sr=new Set(["none","theme","solid","gradient","image"]),Er=new Set(["primary","secondary","muted","accent","destructive"]),$r=new Set(["center","top","bottom","left","right"]);function Ar(e){return typeof e=="string"&&/^https?:\/\//i.test(e.trim())}function j(e,t,n){return typeof e=="string"&&t.has(e)?e:n}function Pr(e){return Number.isFinite(e)?Math.min(4,Math.max(1,Math.round(e))):1}function Nr(e){const t=[{color:"#1e3a8a",position:0},{color:"#3b82f6",position:100}];if(!$(e))return{direction:"to bottom right",stops:t,type:"linear"};const n=e.type==="radial"?"radial":"linear",o=Array.isArray(e.stops)&&e.stops.length>=2?e.stops:t;return{direction:typeof e.direction=="string"&&e.direction.trim()?e.direction:n==="radial"?"circle at center":"to bottom right",stops:o,type:n}}function Ur(e){if(!$(e))return{type:"none"};const t=j(e.type,Sr,"none"),n=typeof e.min_height=="string"&&e.min_height.trim()?{min_height:e.min_height}:{};if(t==="theme")return{theme:j(e.theme,Er,"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:Nr(e.gradient),type:t,...n};if(t==="image"){const o=$(e.image)?e.image:null,r=o&&Ar(o.external_url)?o.external_url.trim():null,a=!!(o&&typeof o.media_id=="string"&&o.media_id.trim()&&typeof o.object_key=="string"&&o.object_key.trim());return o&&(r||a)?{image:{...o,...r?{external_url:r}:{},position:j(o.position,$r,"center"),size:o.size==="contain"?"contain":"cover"},type:t,...n}:{type:"none"}}return{type:"none",...n}}function Or(e,t,n){const o=e.is_hero===!0;let r=Array.isArray(e.column_blocks)?e.column_blocks:[];r.length>0&&r.every(g=>$(g)&&!Array.isArray(g))&&(r=[r]);const a=r.map((g,y)=>(Array.isArray(g)?g:[]).map((k,I)=>Me(k,`${t} column ${y} block ${I}`,n))),s=a.length>0?a:[[]],c=Pr(s.length),u=$(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=$(e.padding)?e.padding:{},f={...e,background:Ur(e.background),column_blocks:s,column_gap:j(e.column_gap,Cr,"lg"),container_type:j(e.container_type,zr,"container"),padding:{bottom:j(m.bottom,Pt,"xl"),top:j(m.top,Pt,"xl")},responsive_columns:{desktop:c,mobile:h,tablet:p},vertical_alignment:j(e.vertical_alignment,xr,o?"center":"start")};return f.slider===!0&&!(Array.isArray(f.slides)&&f.slides.length>0)&&(f.slider=!1),f}function en(e,t,n,o){if(e==="section"){const a=Or(t,n,o);return G(e,a,n,o),a}const r=K(t);if(e==="heading"&&(r.text_content=E(r.text_content)||E(r.text)||E(r.title)||E(r.heading)||"Untitled",r.level=typeof r.level=="number"?r.level:1),e==="text"){const a=E(r.html_content)||E(r.html)||E(r.content)||E(r.text);a&&(r.html_content=/<\/?[a-z][\s\S]*>/i.test(a)?a:`<p>${Ir(a)}</p>`)}return e==="button"&&(r.text=E(r.text)||E(r.label)||E(r.title)||"Learn More",r.url=E(r.url)||E(r.href)||E(r.link)||"#"),e==="form"&&(r.fields=vr(r.fields),r.submit_button_text=E(r.submit_button_text??r.submitButtonText??r.button_text)||"Send Message",r.success_message=E(r.success_message??r.successMessage)||"Thanks for reaching out. We will reply as soon as possible."),G(e,r,n,o),r}function xe(e,t,n){const o=en(e.blockType,ye(e.content,`Block ${t}`),`Block ${t}`,n);return{block_type:e.blockType,content:o,order:e.order??t}}function Fr(e,t="Contact Us",n){return[xe({blockType:"section",content:{is_hero:!0,background:{type:"none"},column_blocks:[[{block_type:"heading",content:{level:1,textAlign:"center",text_content:t},temp_id:Ce("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:Ce("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),xe({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 Oe(e,t,n,o){return(!e||e.length===0)&&t?Fr(t,n,o):(e||[]).map((r,a)=>xe(r,a,o))}async function rt(e){const t=e.contentType==="page"?"pages":e.contentType==="post"?"posts":"products",{data:n,error:o}=await e.supabase.from(t).select("id, title, slug, language_id").eq("slug",e.slug).eq("language_id",e.languageId);if(o)throw new Error(`Failed to check ${e.contentType} slug uniqueness: ${b(o)}`);const r=Array.isArray(n)?n:[];return r.length>0?{duplicate:!0,existingItem:r[0],mutationExecuted:!1,success:!1,message:`A ${e.contentType} with slug "${e.slug}" already exists for this language.`}:null}async function ot(e){if(!e.suppliedTranslationGroupId)return{translationGroupId:void 0};const t=e.contentType==="page"?"pages":e.contentType==="post"?"posts":"products",{data:n,error:o}=await e.supabase.from(t).select("id, title, slug, language_id, translation_group_id").eq("translation_group_id",e.suppliedTranslationGroupId);if(o)throw new Error(`Failed to inspect ${e.contentType} translation group: ${b(o)}`);const r=Array.isArray(n)?n:[];if(r.length===0)return{result:{message:`The ${e.contentType} translation group "${e.suppliedTranslationGroupId}" was not found.`,mutationExecuted:!1,success:!1},translationGroupId:e.suppliedTranslationGroupId};const a=r.find(s=>Number(s.language_id)===e.languageId);return a?{result:{duplicateTranslation:!0,existingItem:a,message:`A ${e.contentType} translation already exists for ${e.languageCode} in this translation group.`,mutationExecuted:!1,success:!1},translationGroupId:e.suppliedTranslationGroupId}:{translationGroupId:e.suppliedTranslationGroupId}}async function it(e){if(e.blocks.length===0)return[];const t=e.blocks.map((r,a)=>({block_type:r.block_type,content:r.content,language_id:e.languageId,order:r.order??a,page_id:e.contentType==="page"?e.itemId:null,post_id:e.contentType==="post"?e.itemId:null,product_id:e.contentType==="product"?e.itemId:null})),{data:n,error:o}=await e.supabase.from("blocks").insert(t).select("*");if(o)throw new Error(`Failed to insert ${e.contentType} blocks: ${b(o)}`);return be(e.blocks,e.supabase),Array.isArray(n)?n:[]}async function at(e){const t=e.contentType==="page"?"pages":e.contentType==="post"?"posts":"products";await e.supabase.from(t).delete().eq("id",e.itemId)}function st(e,t){return e==="page"?`/cms/pages/${t}/edit`:e==="post"?`/cms/posts/${t}/edit`:`/cms/products/${t}/edit`}function Nt(e){return e==="page"?"/cms/pages":e==="post"?"/cms/posts":"/cms/products"}async function ct(e,t){const n=re.parse(e),o=x(t);n.mode==="replace"&&await _r({items:n.items,languageCode:n.languageCode,menuKey:"HEADER",supabase:o});const r=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(r)return r;const a=n.mode==="update"?await wr({items:n.items,languageCode:n.languageCode,match:n.match,menuKey:"HEADER",supabase:o}):n.mode==="append"?await kr({items:n.items,languageCode:n.languageCode,menuKey:"HEADER",supabase:o}):await Qt({items:n.items,languageCode:n.languageCode,menuKey:"HEADER",supabase:o});return Ht(t),{...a,mutationExecuted:!0,mode:n.mode,success:!0}}async function lt(e,t){const n=oe.parse(e);if(!n.links?.length&&!n.copyright)throw new Error("update_footer requires links or copyright.");const o=x(t),r=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(r)return r;let a=null;if(n.links?.length&&(a=await Qt({items:n.links,languageCode:n.languageCode,menuKey:"FOOTER",supabase:o})),n.copyright){const{error:s}=await o.from("site_settings").upsert({key:"footer_copyright",value:n.copyright});if(s)throw new Error(`Failed to update footer copyright: ${b(s)}`)}return Ht(t),{copyrightUpdated:!!n.copyright,footerNavigation:a,mutationExecuted:!0,success:!0}}function tn(e){return typeof e=="string"?e.toLowerCase():""}function Lr(e,t){const n=t.map(tn).join(" ");return e.reduce((o,r)=>o+(n.includes(r)?1:0),0)}function Ut(e,t){return(e.find(n=>t.some(o=>tn(n).includes(o)))||e.find(n=>n.trim().length>0)||"No excerpt available.").slice(0,500)}async function nn(e,t){const n=$e.parse(e),o=x(t),r=n.query.toLowerCase().split(/\s+/).map(l=>l.trim()).filter(Boolean),[a,s]=await Promise.all([o.from("posts").select("id, title, slug, excerpt, subtitle, meta_description, status, updated_at").eq("status","published").limit(100),o.from("pages").select("id, title, slug, meta_description, status, updated_at").eq("status","published").limit(100)]);if(a.error)throw new Error(`Failed to search documentation posts: ${b(a.error)}`);if(s.error)throw new Error(`Failed to search documentation pages: ${b(s.error)}`);const c=(a.data??[]).map(l=>({excerpt:Ut([l.excerpt,l.subtitle,l.meta_description,l.slug].filter(Boolean),r),source:"post",title:l.title,url:`/article/${l.slug}`})),u=(s.data??[]).map(l=>({excerpt:Ut([l.meta_description,l.slug].filter(Boolean),r),source:"page",title:l.title,url:l.slug==="home"?"/":`/${l.slug}`})),d=[...c,...u].map(l=>({...l,score:Lr(r,[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 rn(e,t,n=En){const o=$e.safeParse(e),r=o.success?o.data.query:"";return Yn(nn(e,t),n,()=>({message:"Documentation search took too long to respond. Please try again or ask a more specific question.",query:r,results:[],success:!1,timedOut:!0}))}const Rr=["pending","trial","paid","shipped","cancelled","refunded","failed"],Br={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 jr(e){return String(e??"unknown").trim().toLowerCase()||"unknown"}function Ot(e){const t=Object.fromEntries(Rr.map(n=>[n,0]));for(const n of e){const o=jr(n.status);t[o]=(t[o]??0)+1}return t}function qr(e){const n=e.toLowerCase().replace(/[^a-z0-9_]+/g," ").split(/\s+/).filter(Boolean);for(const o of n){const r=Br[o];if(r)return r}return null}function ne(e){const t=Number(e);return Number.isFinite(t)?t:0}async function on(e,t){const n=Je.parse(e),o=x(t),r=new Date;let a=null,s=null;switch(n.timeRange){case"today":a=new Date(r.getFullYear(),r.getMonth(),r.getDate());break;case"this_month":a=new Date(r.getFullYear(),r.getMonth(),1);break;case"last_7_days":a=new Date(r.getTime()-10080*60*1e3);break;case"last_30_days":a=new Date(r.getTime()-720*60*60*1e3);break;case"last_month":a=new Date(r.getFullYear(),r.getMonth()-1,1),s=new Date(r.getFullYear(),r.getMonth(),0,23,59,59,999);break;case"last_90_days":a=new Date(r.getTime()-2160*60*60*1e3);break;case"all_time":a=null;break}const c=n.currency?.toUpperCase(),u=qr(n.query),d=o.from("orders").select("id, status, total, currency, created_at, paid_at");c&&d.eq("currency",c),a&&d.gte("created_at",a.toISOString()),s&&d.lte("created_at",s.toISOString());const p=n.reportType==="products"||n.reportType==="revenue"||n.reportType==="general"?o.from("order_items").select(`
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const 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,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}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(`
|
|
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),a&&p.gte("orders.paid_at",a.toISOString()),s&&p.lte("orders.paid_at",s.toISOString()));const m=n.timeRange!=="all_time"&&(n.reportType==="orders"||u)?o.from("orders").select("id, status, currency"):null;m&&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=Ot(I),v=Array.isArray(k.data)?k.data:null,S=v?Ot(v):null,F={};for(const C of T){const A=Array.isArray(C.orders)?C.orders[0]:C.orders,B=String(A?.currency||c||"unknown").toUpperCase();F[B]=(F[B]??0)+ne(C.quantity)*ne(C.price_at_purchase)/100}const ee={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((C,A)=>C+A,0)};if(S&&(ee.allTimeOrderStatusCounts=S),u&&(ee.matchingOrderStatus={allTimeCount:S?.[u]??w[u]??0,count:w[u]??0,status:u,timeRange:n.timeRange}),n.reportType==="products"||n.reportType==="revenue"||n.reportType==="general"){const C={};for(const A of T){const B=Array.isArray(A.products)?A.products[0]:A.products;if(!B?.id)continue;const te=B.id;C[te]||(C[te]={id:te,quantity:0,revenue:0,title:B.title,type:B.product_type}),C[te].quantity+=ne(A.quantity),C[te].revenue+=ne(A.quantity)*ne(A.price_at_purchase)/100}ee.topProducts=Object.values(C).sort((A,B)=>B.revenue-A.revenue).slice(0,10)}return{report:ee,success:!0}}async function an(e,t){const n=Ye.parse(e),o=x(t),r=await Z(n.cmsTarget,t),a=q(r),s=r.contentType==="page"?"pages":r.contentType==="post"?"posts":"products",{data:c,error:u}=await o.from(s).select("*").eq("id",a).single();if(u||!c)throw new Error(`Failed to read current ${r.contentType}: ${b(u)}`);let d=[];if(n.includeBlocks){const l=r.contentType==="page"?"page_id":r.contentType==="post"?"post_id":"product_id",{data:p,error:h}=await o.from("blocks").select("id, page_id, post_id, product_id, language_id, block_type, content, order").eq(l,a);if(h)throw new Error(`Failed to read current ${r.contentType} blocks: ${b(h)}`);d=(Array.isArray(p)?p:[]).slice().sort((m,f)=>Number(m.order)-Number(f.order)).map(m=>fr(m,n.includeBlockContent))}return{blocks:d,context:r,item:c,success:!0}}const sn=new Set(["feature_image_id","language_id","meta_description","meta_title","slug","status","title"]),cn=new Set(["excerpt","feature_image_id","label","language_id","meta_description","meta_title","published_at","slug","status","subtitle","title"]),Mr=new Set(["description_json","language_id","meta_description","meta_title","short_description","slug","status","title"]),Dr=new Set(["excerpt","feature_image_id","label","meta_description","meta_title","published_at","short_description","subtitle"]);function Gr(e){return e==="page"?sn:e==="post"?cn:Mr}function ln(e,t){return Dr.has(e)&&t===""?null:t}function Ge(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 Kr(e,t){const n=Gr(t.contentType),o={};for(const[r,a]of Object.entries(e))if(a!==void 0){if(!n.has(r))throw new Error(`Field "${r}" cannot be updated for ${t.contentType} content.`);r==="status"&&Ge(t.contentType,a),o[r]=ln(r,a)}return o}async function ut(e,t){const n=ae.parse(e),o=x(t),r=await Z(n.cmsTarget,t),a=q(r),s=Kr(n.fields,r),c=Object.keys(s);if(c.length===0)throw new Error("update_current_cms_fields requires at least one supported field.");const u=P({action:"UPDATE CMS FIELDS",context:t,payload:{contentType:r.contentType,entityId:a,fields:s,tool:"update_current_cms_fields"},preview:{contentType:r.contentType,entityId:a,fields:c,slug:r.slug,title:r.title},subject:`${r.contentType} ${String(a)}`});if(u)return u;const d=await V(t,r.contentType,a);typeof s.feature_image_id=="string"&&(s.feature_image_id=await X(s.feature_image_id,t,typeof r.title=="string"?r.title:void 0));const l=r.contentType==="page"?"pages":r.contentType==="post"?"posts":"products",{data:p,error:h}=await o.from(l).update({...s,updated_at:new Date().toISOString()}).eq("id",a).select("id, language_id, slug, status, title").single();if(h||!p)throw new Error(`Failed to update current ${r.contentType}: ${b(h)}`);return await M(t,r.contentType,a,d),U(t,r,p.slug),{contentType:r.contentType,entityId:a,mutationExecuted:!0,slug:p.slug,success:!0,updatedFields:c}}async function dt(e,t){const n=se.parse(e),o=x(t),r=await Z(n.cmsTarget,t),{data:a,error:s}=await o.from("blocks").select("id, page_id, post_id, product_id, language_id, block_type, content, order").eq("id",n.blockId).single();if(s||!a)throw new Error(`Failed to read block ${n.blockId}: ${b(s)}`);Wt(a,r);const c=ve(a.block_type,`Block ${n.blockId}`);Jt(n.blockType,c,`Block ${n.blockId}`);const u=ye(a.content,`Block ${n.blockId}`),d=gr(c,u,n.content,t);G(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:r.contentType,entityId:q(r)},subject:`${c} block ${n.blockId}`});if(l)return l;const p=await V(t,r.contentType,q(r)),{data:h,error:m}=await o.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 M(t,r.contentType,q(r),p),await Ne({patch:({blocks:f})=>({blocks:f.map(g=>String(g?.id)===String(n.blockId)?{...g,content:d}:g)}),productId:a.product_id,supabase:o}),be([{content:d}],o),U(t,r),{blockId:h.id,blockType:h.block_type,contentUpdated:!0,mutationExecuted:!0,success:!0}}async function pt(e,t){const n=de.parse(e),o=x(t),r=await J(n,t),a=r.contentType==="product"?r.item.id:Number(r.item.id),s=r.contentType==="page"?"page_id":r.contentType==="post"?"post_id":"product_id",c=async()=>{const{data:T,error:w}=await o.from("blocks").select("id, page_id, post_id, product_id, language_id, block_type, content, order").eq(s,a);if(w)throw new Error(`Failed to read ${r.contentType} blocks: ${b(w)}`);return(Array.isArray(T)?T:[]).sort((v,S)=>Number(v.order)-Number(S.order))},u=T=>{if(n.position==="start")return 0;if(n.position==="end"){const S=T.map(F=>Number(F.order)).filter(Number.isFinite);return S.length>0?Math.max(...S)+1:0}const w=n.anchorBlockId?T.find(S=>Number(S.id)===n.anchorBlockId):n.anchorBlockType?T.find(S=>S.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 v=Number(w.order);return n.position==="before"?v:v+1},d=xe(n.block,0,t),l=await c(),p=u(l),h={contentType:r.contentType,entityId:r.item.id,languageId:r.item.language_id,slug:r.item.slug,title:r.item.title,translationGroupId:r.item.translation_group_id},m=P({action:"INSERT CONTENT BLOCK",context:t,payload:{block:d,order:p,target:{contentType:r.contentType,id:r.item.id,slug:r.item.slug},tool:"insert_content_block"},preview:{anchorBlockId:n.anchorBlockId,anchorBlockType:n.anchorBlockType,blockType:d.block_type,contentType:r.contentType,entityId:r.item.id,position:n.position,slug:r.item.slug,summary:`Insert ${d.block_type} block ${n.position} ${n.anchorBlockType?`the first ${n.anchorBlockType} block`:n.anchorBlockId?`block ${n.anchorBlockId}`:"the content"} on ${r.contentType} "${r.item.title||r.item.slug}".`,title:r.item.title},subject:`${d.block_type} block on ${r.contentType} ${r.item.id}`});if(m)return m;const f=await c(),g=u(f),y=f.filter(T=>Number(T.order)>=g).sort((T,w)=>Number(w.order)-Number(T.order)),_=await V(t,r.contentType,a);for(const T of y){const{error:w}=await o.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 o.from("blocks").insert({block_type:d.block_type,content:d.content,language_id:r.item.language_id,order:g,page_id:r.contentType==="page"?a:null,post_id:r.contentType==="post"?a:null,product_id:r.contentType==="product"?a:null}).select("id, block_type, order").single();if(I||!k)throw new Error(`Failed to insert content block: ${b(I)}`);return r.contentType==="product"&&await Ne({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:r.item.language_id,order:g,page_id:null,post_id:null,product_id:a}].sort((w,v)=>Number(w.order)-Number(v.order))}),productId:a,supabase:o}),await M(t,r.contentType,a,_),be([d],o),U(t,h),{blockId:k.id,blockType:k.block_type,contentType:r.contentType,entityId:r.item.id,mutationExecuted:!0,order:k.order,success:!0}}async function mt(e,t){const n=ce.parse(e),o=x(t),r=await Z(n.cmsTarget,t),{data:a,error:s}=await o.from("blocks").select("id, page_id, post_id, product_id, language_id, block_type, content, order").eq("id",n.parentBlockId).single();if(s||!a)throw new Error(`Failed to read parent block ${n.parentBlockId}: ${b(s)}`);Wt(a,r);const c=ve(a.block_type,`Parent block ${n.parentBlockId}`);if(c!=="section")throw new Error(`Parent block ${n.parentBlockId} must be a section block, not "${c}".`);const u=ye(a.content,`Parent block ${n.parentBlockId}`);G(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=ve(l.block_type,`Nested block ${n.columnIndex}:${n.blockIndex}`);Jt(n.blockType,p,`Nested block ${n.columnIndex}:${n.blockIndex}`),G(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};G(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 V(t,r.contentType,q(r)),{data:y,error:_}=await o.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 Ne({patch:({blocks:k})=>({blocks:k.map(I=>String(I?.id)===String(n.parentBlockId)?{...I,content:m}:I)}),productId:a.product_id,supabase:o}),await M(t,r.contentType,q(r),g),U(t,r),{blockIndex:n.blockIndex,columnIndex:n.columnIndex,mutationExecuted:!0,nestedBlockType:p,parentBlockId:y.id,parentBlockType:y.block_type,success:!0}}async function Fe(e,t){const n=pe.parse(e),o=x(t),r=et(t),a=await Ue(o,n.languageCode),s=O(n.slug||n.title),c=Oe(n.blocks,n.contactEmail,n.title,t),u=await rt({contentType:"page",languageId:a.id,slug:s,supabase:o});if(u)return u;const d=await ot({contentType:"page",languageCode:a.code,languageId:a.id,suppliedTranslationGroupId:n.translationGroupId,supabase:o});if(d.result)return d.result;const l={blocks:c,item:{feature_image_id:n.feature_image_id??null,language_id:a.id,meta_description:n.meta_description??null,meta_title:n.meta_title??null,slug:s,status:n.status,title:n.title,translation_group_id:d.translationGroupId},tool:"create_cms_page"},p=P({action:"CREATE PAGE",context:t,payload:l,preview:{blockCount:c.length,languageCode:a.code,slug:s,status:n.status,title:n.title,translationGroupId:d.translationGroupId},subject:s});if(p)return p;const h=d.translationGroupId||tt(),m=await X(l.item.feature_image_id,t,n.title),{data:f,error:g}=await o.from("pages").insert({...l.item,author_id:r,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 it({blocks:c,contentType:"page",itemId:Number(f.id),languageId:a.id,supabase:o})}catch(y){throw await at({contentType:"page",itemId:Number(f.id),supabase:o}),y}return U(t,{contentType:"page",entityId:Number(f.id),languageId:a.id,slug:s,title:n.title},s),t?.revalidatePath?.("/cms/pages"),{blockCount:c.length,contentType:"page",editPath:st("page",f.id),entityId:f.id,mutationExecuted:!0,slug:s,success:!0,title:n.title,translationGroupId:f.translation_group_id}}async function Le(e,t){const n=me.parse(e),o=x(t),r=et(t),a=await Ue(o,n.languageCode),s=O(n.slug||n.title),c=Oe(n.blocks,void 0,void 0,t),u=await rt({contentType:"post",languageId:a.id,slug:s,supabase:o});if(u)return u;const d=await ot({contentType:"post",languageCode:a.code,languageId:a.id,suppliedTranslationGroupId:n.translationGroupId,supabase:o});if(d.result)return d.result;const l=n.published_at&&!Number.isNaN(new Date(n.published_at).getTime())?new Date(n.published_at).toISOString():n.published_at??null,p={blocks:c,item:{excerpt:n.excerpt??null,feature_image_id:n.feature_image_id??null,label:n.label??null,language_id:a.id,meta_description:n.meta_description??null,meta_title:n.meta_title??null,published_at:l,slug:s,status:n.status,subtitle:n.subtitle??null,title:n.title,translation_group_id:d.translationGroupId},tool:"create_cms_post"},h=P({action:"CREATE POST",context:t,payload:p,preview:{blockCount:c.length,languageCode:a.code,slug:s,status:n.status,title:n.title,translationGroupId:d.translationGroupId},subject:s});if(h)return h;const m=d.translationGroupId||tt(),f=await X(p.item.feature_image_id,t,n.title),{data:g,error:y}=await o.from("posts").insert({...p.item,author_id:r,feature_image_id:f,translation_group_id:m}).select("id, language_id, slug, status, title, translation_group_id").single();if(y||!g?.id)throw new Error(`Failed to create post: ${b(y)}`);try{await it({blocks:c,contentType:"post",itemId:Number(g.id),languageId:a.id,supabase:o})}catch(_){throw await at({contentType:"post",itemId:Number(g.id),supabase:o}),_}return U(t,{contentType:"post",entityId:Number(g.id),languageId:a.id,slug:s,title:n.title},s),t?.revalidatePath?.("/cms/posts"),t?.revalidatePath?.("/articles"),{blockCount:c.length,contentType:"post",editPath:st("post",g.id),entityId:g.id,mutationExecuted:!0,slug:s,success:!0,title:n.title,translationGroupId:g.translation_group_id}}function Hr(e,t){return(t||O(e)||"product").replace(/-/g,"").slice(0,24).toUpperCase()}function un(e){if(e==null)return;if(typeof e=="string")return jt.editorDocumentFromHtml(e)??void 0;const t=Array.isArray(e)?{content:e,type:"doc"}:$(e)&&e.type!=="doc"&&Array.isArray(e.content)?{...e,type:"doc"}:e,n=$t().safeParse(t);if(!n.success){if($(e)&&typeof e.type=="string"){const o=$t().safeParse({content:[e],type:"doc"});if(o.success)return o.data}throw new Error(`Product description_json must be an editor document like { "type": "doc", "content": [ { "type": "paragraph", "content": [ { "type": "text", "text": "..." } ] } ] }, or simply an HTML string. Received: ${n.error.issues.map(o=>o.message).join("; ")}`)}return n.data}function Vr(e){const t=r=>!!(r&&Array.isArray(r.content)&&r.content.length>0),n=un(e.description_json);if(t(n))return n;const o=e.description_html?jt.editorDocumentFromHtml(e.description_html):null;return t(o)?o:void 0}async function gt(e,t){const n=ge.parse(e),o=x(t),r=await Ue(o,n.languageCode),a=O(n.slug||n.title),s=Oe(n.blocks,void 0,void 0,t),c=await rt({contentType:"product",languageId:r.id,slug:a,supabase:o});if(c)return c;const u=await ot({contentType:"product",languageCode:r.code,languageId:r.id,suppliedTranslationGroupId:n.translationGroupId,supabase:o});if(u.result)return u.result;const{createProduct:d,productSchema:l}=await rr(),h=n.product_type==="digital"&&n.payment_provider==="freemius"?n.trial_period_days:0,m=l.parse({description_json:Vr(n),freemius_plan_id:n.freemius_plan_id||"",freemius_product_id:n.freemius_product_id||"",is_taxable:n.is_taxable,language_id:r.id,meta_description:n.meta_description??"",meta_title:n.meta_title??"",payment_provider:n.payment_provider,price:n.price,prices:n.prices||{},product_media:[],product_type:n.product_type,sale_price:n.sale_price??null,sale_prices:n.sale_prices||{},short_description:n.short_description??"",sku:n.sku||Hr(n.title,a),slug:a,status:n.status,stock:n.stock,title:n.title,trial_period_days:h,trial_requires_payment_method:h>0?n.trial_requires_payment_method:!1,translation_group_id:u.translationGroupId,upc:n.upc??"",variation_attributes:[],variants:[]}),f=n.images??[],g=P({action:"CREATE PRODUCT",context:t,payload:{blocks:s,images:f,item:m,tool:"create_cms_product"},preview:{blockCount:s.length,descriptionLength:m.description_json?JSON.stringify(m.description_json).length:0,imageCount:f.length,languageCode:r.code,price:m.price,sku:m.sku,slug:a,status:m.status,stock:m.stock,title:m.title,translationGroupId:u.translationGroupId},subject:a});if(g)return g;let y=[],_=null;if(f.length>0)try{if(y=[...new Set(await Gt(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(o,{...m,product_media:y.map(I=>({media_id:I}))});if(!k?.id)throw new Error("Failed to create product.");try{await it({blocks:s,contentType:"product",itemId:k.id,languageId:r.id,supabase:o})}catch(I){throw await at({contentType:"product",itemId:k.id,supabase:o}),I}return U(t,{contentType:"product",entityId:k.id,languageId:r.id,slug:a,title:n.title},a),t?.revalidatePath?.("/cms/products"),{blockCount:s.length,contentType:"product",editPath:st("product",k.id),entityId:k.id,imageCount:y.length,..._?{imageError:_}:{},mutationExecuted:!0,slug:a,success:!0,title:n.title,translationGroupId:k.translation_group_id}}function ft(e){return e.trim().replace(/[\s-]+/g,"_").toLowerCase()}function Wr(e,t){const n=typeof t=="string"?ft(t):t;return e==="product"?n==="public"||n==="publish"||n==="published"?"active":n:n==="public"||n==="active"||n==="publish"?"published":n}function Jr(e){const t=ft(e.field);return!!(e.startsAt||e.endsAt||t.includes("start")||t.includes("end")||t.includes("schedule")||t.includes("special_date"))}async function Yr(e,t,n){if(e==="price"||e==="sale_price"){if(t==null)return{[e]:null};const o=await De(n);return{[e]:Te(Number(t),o)}}if(e==="prices"||e==="sale_prices"){const o=await De(n);return{[e]:lr(t,o)}}return e==="description_json"?{description_json:un(t)}:{[e]:t}}const Xr=new Set(["language_id","price","sale_price","stock","trial_period_days"]),Qr=new Set(["is_taxable","trial_requires_payment_method"]);function Zr(e,t){if(typeof t!="string")return t;const n=t.trim();if(Xr.has(e)){if(n.toLowerCase()==="null")return null;if(n==="")return t;const o=Number(n);return Number.isFinite(o)?o:t}if(Qr.has(e)){const o=n.toLowerCase();if(o==="true")return!0;if(o==="false")return!1}return t}function eo(e,t){const n=ft(e.field),r={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,a=r==="status"?Wr(t.contentType,e.value):Zr(r,e.value);if(t.contentType!=="product"){if(!(t.contentType==="page"?sn:cn).has(r))throw new Error(`Field "${e.field}" cannot be updated for ${t.contentType}.`);return r==="status"&&Ge(t.contentType,a),{field:r,payload:{[r]:ln(r,a)}}}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(r))throw new Error(`Field "${e.field}" cannot be updated for product.`);if(r==="status"&&Ge("product",a),(r==="price"||r==="sale_price")&&a!==null&&(typeof a!="number"||a<0))throw new Error(`${r} must be a non-negative number or null.`);if(r==="stock"&&(!Number.isInteger(a)||Number(a)<0))throw new Error("stock must be a non-negative integer.");if(r==="trial_period_days"&&(!Number.isInteger(a)||Number(a)<0))throw new Error("trial_period_days must be a non-negative integer.");if(r==="trial_requires_payment_method"&&typeof a!="boolean")throw new Error("trial_requires_payment_method must be a boolean.");return{field:r,payload:{[r]:a}}}async function ht(e,t){const n=fe.parse(e);if(Jr(n))return{message:"Scheduled product specials are not supported by the current product schema yet. I can set or clear sale_price now, but not start/end dates.",mutationExecuted:!1,success:!1,unsupported:!0};const o=await J(n,t),r=eo(n,o),a=r.field;let s=r.payload;if(a==="language_id"&&typeof s.language_id=="string"){const h=await Q(x(t),s.language_id);s={...s,language_id:h.id}}const c=P({action:"UPDATE FIELD",context:t,payload:{contentType:o.contentType,entityId:o.item.id,field:a,payload:s,tool:"update_cms_item_field"},preview:{contentType:o.contentType,field:a,from:o.item[a],slug:o.item.slug,title:o.item.title,to:s[a]},subject:`${o.contentType} ${o.item.slug||o.item.id} ${a}`});if(c)return c;const u=await V(t,o.contentType,o.item.id);if(o.contentType==="product"){const h=x(t),m=await Yr(a,s[a],h),{data:f,error:g}=await h.from("products").update({...m,updated_at:new Date().toISOString()}).eq("id",o.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 M(t,"product",f.id,u),{contentType:"product",entityId:f.id,field:a,mutationExecuted:!0,slug:f.slug,success:!0,updatedFields:[a]}}a==="feature_image_id"&&typeof s.feature_image_id=="string"&&(s={...s,feature_image_id:await X(s.feature_image_id,t,typeof o.item.title=="string"?o.item.title:void 0)});const d=o.contentType==="page"?"pages":"posts",{data:l,error:p}=await x(t).from(d).update({...s,updated_at:new Date().toISOString()}).eq("id",o.item.id).select("id, language_id, slug, status, title").single();if(p||!l)throw new Error(`Failed to update ${o.contentType}: ${b(p)}`);return U(t,{contentType:o.contentType,entityId:Number(l.id),languageId:l.language_id,slug:l.slug,title:l.title},l.slug),await M(t,o.contentType,l.id,u),{contentType:o.contentType,entityId:l.id,field:a,mutationExecuted:!0,slug:l.slug,success:!0,updatedFields:[a]}}async function dn(e,t){const n=Xe.parse(e),o=await J(n,t);if(o.contentType==="product")return{affectedCount:1,collectionPath:Nt("product"),contentType:"product",item:o.item,navigationLinkCount:0,publicPaths:o.item.slug?[`/product/${o.item.slug}`]:[],targetIds:[o.item.id]};const r=o.contentType==="page"?"pages":"posts",{data:a,error:s}=await x(t).from(r).select("id, slug, title, translation_group_id").eq("translation_group_id",o.item.translation_group_id);if(s)throw new Error(`Failed to inspect related ${o.contentType}s: ${b(s)}`);const c=Array.isArray(a)?a:[],u=c.map(m=>o.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:Nt(o.contentType),contentType:o.contentType,item:o.item,navigationLinkCount:h,publicPaths:u,targetIds:c.map(m=>m.id)}}function pn(e){const t=e.item.title||e.item.slug||"selected item",n=e.item.slug?` (${e.item.slug})`:"";if(e.contentType==="product")return`Delete product "${t}"${n}.`;const o=[`${N(e.affectedCount,"language version")}`,e.navigationLinkCount>0?`${N(e.navigationLinkCount,"navigation link")}`:null].filter(Boolean);return`Delete ${e.contentType} "${t}"${n}, including ${o.join(" and ")}.`}async function mn(e,t){const n=await dn(e,t);return{...Vt({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:pn(n),title:n.item.title},subject:`${n.item.id} ${n.item.slug||""}`}),preparedDelete:!0}}async function yt(e,t){const n=he.parse(e),o=await dn(n,t),r=P({action:`DELETE ${o.contentType}`,context:t,payload:{affectedCount:o.affectedCount,contentType:o.contentType,targetIds:o.targetIds,tool:"delete_cms_item"},preview:{affectedCount:o.affectedCount,collectionPath:o.collectionPath,contentType:o.contentType,navigationLinkCount:o.navigationLinkCount,publicPaths:o.publicPaths,slug:o.item.slug,summary:pn(o),title:o.item.title},subject:`${o.item.id} ${o.item.slug||""}`});if(r)return r;const a=x(t);if(o.contentType==="product"){const{error:c}=await a.from("products").delete().eq("id",o.item.id);if(c)throw new Error(`Failed to delete product: ${b(c)}`)}else{for(const d of o.publicPaths)await a.from("navigation_items").delete().eq("url",d);const c=o.contentType==="page"?"pages":"posts",{error:u}=await a.from(c).delete().eq("translation_group_id",o.item.translation_group_id);if(u)throw new Error(`Failed to delete ${o.contentType}: ${b(u)}`)}const s=t?.revalidatePath??Ze();return s&&(s(o.collectionPath),s("/cms/navigation"),o.publicPaths.forEach(c=>s(c))),{affectedCount:o.affectedCount,collectionPath:o.collectionPath,contentType:o.contentType,mutationExecuted:!0,redirectPath:o.collectionPath,success:!0}}async function Ft(e,t){switch(e.tool){case"create_cms_page":return Fe(e.input,t);case"create_cms_post":return Le(e.input,t);case"create_cms_product":return gt(e.input,t);case"delete_cms_item":return yt(e.input,t);case"update_cms_item_field":return ht(e.input,t);case"update_content_block":return dt(e.input,t);case"insert_content_block":return pt(e.input,t);case"update_current_cms_fields":return ut(e.input,t);case"update_footer":return lt(e.input,t);case"update_navigation_bar":return ct(e.input,t);case"update_section_column_block":return mt(e.input,t);case"set_content_images":return zt(e.input,t)}}function to(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 Lt(e){return e==="create_cms_page"?"page":e==="create_cms_post"?"post":"product"}function no(e,t,n){if(e.tool!=="set_content_images")return e;const o=e.input;if(o.entityId!==void 0)return e;const r=o.slug?t.get(`${o.contentType||"product"}:${O(o.slug)}`):n;return r?{...e,input:{...o,contentType:r.contentType,entityId:r.entityId}}:e}async function gn(e,t){const n=Qe.parse(e),o=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`${Lt(m.tool)}:${O(f.slug||f.title||"")}`})),r=m=>{if(m.tool!=="set_content_images")return!1;const f=m.input;return f.slug?o.has(`${f.contentType||"product"}:${O(f.slug)}`):o.size>0};if(!t?.skipConfirmation){const m=[];for(const y of n.actions){if(r(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 Ft(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(ar(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 a={...t,skipConfirmation:!0},s=[];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=no(to(f,l),p,h),y=await Ft(g,a);if(s.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=Lt(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:s,success:!1,...u?{editPath:u}:{},...d?{redirectPath:d}:{}}}}return{actionCount:n.actions.length,editPath:d?void 0:u??void 0,mutationExecuted:c,redirectPath:d??void 0,results:s,success:!0,summary:n.summary??null}}const bt=i.z.strictObject({maxChars:i.z.number().int().min(500).max(2e4).default(8e3).describe("Maximum characters of readable body text to return."),url:i.z.string().trim().min(1).max(2048).refine(e=>/^https?:\/\//i.test(e),"URL must start with http:// or https://.")}),ro=12e3,Rt=2e6;function oo(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 o=n.match(/^([0-9a-f]{1,4}):([0-9a-f]{1,4})$/i);if(!o)return null;const r=Number.parseInt(o[1],16),a=Number.parseInt(o[2],16);return[r>>8&255,r&255,a>>8&255,a&255].join(".")}function Se(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=oo(t);if(n)return Se(n);const o=t.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/);if(o){const r=Number(o[1]),a=Number(o[2]);if(r===10||r===127||r===0||r===192&&a===168||r===169&&a===254||r===172&&a>=16&&a<=31)return!0}return!1}function we(e){return e.replace(/<[^>]+>/g," ").replace(/ /gi," ").replace(/&/gi,"&").replace(/</gi,"<").replace(/>/gi,">").replace(/"/gi,'"').replace(/'/gi,"'").replace(/\s+/g," ").trim()}function io(e){return e.trim().replace(/&/gi,"&").replace(/&/g,"&").replace(/"/gi,'"').replace(/'/g,"'")}const fn=/\.(avif|gif|jpe?g|png|webp)(?:[?#]|$)/i,hn=/(?:^|[/_-])(?: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 Ee(e,t){if(typeof e!="string")return null;const n=io(e);if(!n||n.startsWith("data:"))return null;try{const o=new URL(n,t);return o.protocol!=="http:"&&o.protocol!=="https:"?null:o.toString()}catch{return null}}function ao(e){let t=null;for(const n of e.split(",")){const o=n.trim().split(/\s+/),r=o[0];if(!r)continue;const a=o[1]||"",s=a.match(/^(\d+(?:\.\d+)?)w$/i),c=a.match(/^(\d+(?:\.\d+)?)x$/i),u=s?Number(s[1]):c?Number(c[1])*1e3:1;(!t||u>t.weight)&&(t={url:r,weight:u})}return t?.url??null}function R(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 so(e,t){const n=[],o=[],r=(c,u)=>{if(typeof c=="string"){const d=Ee(c,t);d&&u.push(d);return}if(Array.isArray(c)){for(const d of c)r(d,u);return}c&&typeof c=="object"&&(r(c.url,u),r(c.contentUrl,u))},a=(c,u)=>{if(u>8||!c||typeof c!="object")return;if(Array.isArray(c)){for(const m of c)a(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&&r(d.image,h?n:o);for(const m of Object.values(d))a(m,u+1)},s=e.matchAll(/<script\b[^>]*type\s*=\s*["']application\/ld\+json["'][^>]*>([\s\S]*?)<\/script>/gi);for(const c of s){const u=(c[1]||"").trim();if(u)try{a(JSON.parse(u),0)}catch{}}return[...n,...o]}const yn=/(?:^|[/_-])(?:thumbnails?|thumbs?|small|mini)(?:[/_.-]|$)/i;function bn(e){try{const{pathname:t}=new URL(e);return decodeURIComponent(t.slice(t.lastIndexOf("/")+1)).toLowerCase()||null}catch{return null}}function co(e,t){const n=new Map;for(const o of e.matchAll(/<a\b[^>]*>/gi)){const r=Ee(R(o[0],"href"),t);if(!r||!fn.test(r)||yn.test(r)||hn.test(r))continue;const a=bn(r);a&&!n.has(a)&&n.set(a,r)}return n}function lo(e,t){const n=[...so(e,t)],o=[/<meta\b[^>]*\b(?:property|name)\s*=\s*["'](?:og:image:secure_url|og:image:url|og:image)["'][^>]*>/gi,/<meta\b[^>]*\b(?:property|name)\s*=\s*["'](?:twitter:image:src|twitter:image)["'][^>]*>/gi,/<meta\b[^>]*\bitemprop\s*=\s*["']image["'][^>]*>/gi,/<link\b[^>]*\brel\s*=\s*["']image_src["'][^>]*>/gi];for(const l of o)for(const p of e.matchAll(l)){const h=p[0],m=Ee(R(h,"content")||R(h,"href"),t);m&&n.push(m)}const r=[];for(const l of e.matchAll(/<img\b[^>]*>/gi)){const p=l[0],h=R(p,"srcset")||R(p,"data-srcset"),m=[h?ao(h):null,R(p,"src"),R(p,"data-src"),R(p,"data-original"),R(p,"data-lazy-src"),R(p,"data-image")];let f=null;for(const y of m)if(f=Ee(y,t),f)break;if(!f||hn.test(f))continue;const g=Number(R(p,"width"));Number.isFinite(g)&&g>0&&g<200||r.push(f)}const a=l=>fn.test(l);n.push(...r.filter(a),...r.filter(l=>!a(l)));const s=co(e,t),c=l=>{if(!yn.test(l))return l;const p=bn(l);return p&&s.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 uo(e,t,n){const o=e.replace(/<script\b[\s\S]*?<\/script>/gi," ").replace(/<style\b[\s\S]*?<\/style>/gi," ").replace(/<noscript\b[\s\S]*?<\/noscript>/gi," ").replace(/<svg\b[\s\S]*?<\/svg>/gi," "),{images:r,mainImage:a}=lo(e,n),s=e.match(/<title\b[^>]*>([\s\S]*?)<\/title>/i),c=e.match(/<meta[^>]+name=["']description["'][^>]*content=["']([^"']*)["'][^>]*>/i)||e.match(/<meta[^>]+content=["']([^"']*)["'][^>]*name=["']description["'][^>]*>/i),u=[...o.matchAll(/<h([1-3])\b[^>]*>([\s\S]*?)<\/h\1>/gi)].map(p=>we(p[2])).filter(Boolean).slice(0,40),d=o.match(/<body\b[^>]*>([\s\S]*?)<\/body>/i),l=we(d?.[1]??o);return{description:c?we(c[1]):"",headings:u,images:r,mainImage:a,text:l.slice(0,t),title:s?we(s[1]):"",truncated:l.length>t}}async function _n(e){const t=bt.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(Se(n.hostname))return{message:"Refusing to fetch a local, private, or internal address.",success:!1,url:t.url};const o=new AbortController,r=setTimeout(()=>o.abort(),ro);try{const a=await fetch(n.toString(),{headers:{accept:"text/html,application/xhtml+xml,text/plain","user-agent":"NextBlockCortexAI/1.0 (+https://nextblock.dev)"},redirect:"follow",signal:o.signal});if(!a.ok)return{message:`The URL responded with HTTP ${a.status}.`,status:a.status,success:!1,url:t.url};const s=a.url||n.toString();try{if(Se(new URL(s).hostname))return{message:"The URL redirected to a blocked internal address.",success:!1,url:t.url}}catch{}const c=a.headers.get("content-type")||"";if(!/text\/html|text\/plain|application\/xhtml/i.test(c))return{contentType:c,message:`The URL is not an HTML or text page (content-type: ${c||"unknown"}).`,success:!1,url:t.url};const u=await a.text(),d=u.length>Rt?u.slice(0,Rt):u,l=uo(d,t.maxChars,s);return!l.text&&!l.title?{message:"The URL returned no readable text content.",success:!1,url:t.url}:{description:l.description,finalUrl:s,headings:l.headings,images:l.images,mainImage:l.mainImage,success:!0,text:l.text,title:l.title,truncated:l.truncated,url:t.url}}catch(a){return{message:a instanceof Error&&(a.name==="AbortError"||/abort/i.test(a.message))?"Fetching the URL timed out.":`Failed to fetch the URL: ${b(a)}`,success:!1,url:t.url}}finally{clearTimeout(r)}}const _t=i.z.strictObject({count:i.z.number().int().min(1).max(15).default(6),orientation:i.z.enum(["landscape","portrait","square"]).optional().describe("Preferred image orientation. Use landscape for hero/section backgrounds."),query:i.z.string().trim().min(2).max(200).describe('What the photos should depict, e.g. "herbal supplements".')}),po=12e3;async function Re(e){let t=null,n=null;if(e)try{const{CORTEX_AI_PEXELS_SETTING_KEY:r,CORTEX_AI_UNSPLASH_SETTING_KEY:a,decryptStoredOpenRouterApiKey:s}=await Promise.resolve().then(()=>require("./ai-config.cjs.js")),c=l=>{if(!l)return null;try{const p=s(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",[r,a]),d=Array.isArray(u)?u:[];t=c(d.find(l=>l.key===r)?.value),n=c(d.find(l=>l.key===a)?.value)}catch{}t||(t=process.env.PEXELS_API_KEY?.trim()||null),n||(n=process.env.UNSPLASH_ACCESS_KEY?.trim()||null);const o=[];return t&&o.push({apiKey:t,provider:"pexels"}),n&&o.push({apiKey:n,provider:"unsplash"}),o}async function mo(e){return(await Re(e))[0]??null}async function go(e){if(e)try{const{CORTEX_AI_UNSPLASH_APP_NAME_SETTING_KEY:t}=await Promise.resolve().then(()=>require("./ai-config.cjs.js")),{data:n}=await e.from("site_settings").select("value").eq("key",t).maybeSingle(),o=n?.value;if(typeof o=="string"&&o.trim())return o.trim()}catch{}return process.env.UNSPLASH_APP_NAME?.trim()||null}async function Bt(e,t){const n=new AbortController,o=setTimeout(()=>n.abort(),po);try{const r=await fetch(e,{headers:t,signal:n.signal});if(!r.ok)throw new Error(`Stock photo provider responded with HTTP ${r.status}.`);return await r.json()}finally{clearTimeout(o)}}function ke(e){const t=Number(e);return Number.isFinite(t)&&t>0?t:null}function Ke(e,t){if(!$(e))return;const n=o=>{$(o)&&o.provider==="unsplash"&&typeof o.downloadLocation=="string"&&o.downloadLocation.trim()&&t.add(o.downloadLocation.trim())};if(n(e.attribution),$(e.background)&&$(e.background.image)&&n(e.background.image.attribution),Array.isArray(e.column_blocks)){for(const o of e.column_blocks)if(Array.isArray(o))for(const r of o)$(r)&&Ke(r.content,t)}if(Array.isArray(e.slides))for(const o of e.slides)Ke(o,t)}async function be(e,t){try{const n=new Set;for(const a of e)Ke(a?.content,n);if(n.size===0)return;const r=(await Re(t)).find(a=>a.provider==="unsplash");if(!r)return;await Promise.all([...n].map(a=>fetch(a,{headers:{Authorization:`Client-ID ${r.apiKey}`}}).catch(()=>{})))}catch{}}async function fo(e,t,n){const o=new URLSearchParams({per_page:String(t.count),query:t.query});if(t.orientation&&o.set("orientation",t.orientation),e.provider==="pexels"){const a=await Bt(`https://api.pexels.com/v1/search?${o.toString()}`,{Authorization:e.apiKey});return(Array.isArray(a?.photos)?a.photos:[]).map(s=>{const c=typeof s?.photographer=="string"?s.photographer:null;return{alt:typeof s?.alt=="string"&&s.alt.trim()?s.alt.trim():t.query,credit:c?`Photo by ${c} on Pexels`:"Photo on Pexels",downloadLocation:null,height:ke(s?.height),photographer:c,photographerUrl:typeof s?.photographer_url=="string"?s.photographer_url:null,provider:"pexels",sourceUrl:typeof s?.url=="string"?s.url:null,thumbnailUrl:s?.src?.medium||s?.src?.large||null,url:s?.src?.large2x||s?.src?.large||s?.src?.original||null,width:ke(s?.width)}}).filter(s=>typeof s.url=="string")}const r=await Bt(`https://api.unsplash.com/search/photos?${o.toString()}`,{Authorization:`Client-ID ${e.apiKey}`});return(Array.isArray(r?.results)?r.results:[]).map(a=>{const s=typeof a?.user?.name=="string"?a.user.name:null;return{alt:typeof a?.alt_description=="string"&&a.alt_description.trim()||typeof a?.description=="string"&&a.description.trim()||t.query,credit:s?`Photo by ${s} on Unsplash`:"Photo on Unsplash",downloadLocation:typeof a?.links?.download_location=="string"?a.links.download_location:null,height:ke(a?.height),photographer:s,photographerUrl:typeof a?.user?.links?.html=="string"?a.user.links.html:null,provider:"unsplash",sourceUrl:typeof a?.links?.html=="string"?a.links.html:null,thumbnailUrl:a?.urls?.small||a?.urls?.thumb||null,url:a?.urls?.regular||a?.urls?.full||a?.urls?.raw||null,utmSource:n||null,width:ke(a?.width)}}).filter(a=>typeof a.url=="string")}async function wn(e,t){const n=_t.parse(e),o=await Re(t?.supabase);if(o.length===0)return{message:"No stock photo provider is configured. Add a free Pexels or Unsplash API key in /cms/settings/cortex-ai (or set PEXELS_API_KEY / UNSPLASH_ACCESS_KEY).",photos:[],success:!1};const r=o.some(c=>c.provider==="unsplash")?await go(t?.supabase):null,a=[];let s=null;for(const c of o){a.push(c.provider);try{const u=await fo(c,n,r);if(u.length>0)return{attemptedProviders:a,photos:u,provider:c.provider,query:n.query,success:!0,usageGuidance:c.provider==="unsplash"?'Unsplash photos: keep them hotlinked (use `url` as external_url; never save an Unsplash photo to the media library) and attribute each one — copy the photo\'s attribution fields into the image content\'s `attribution` (photographer, photographerUrl, sourceUrl, downloadLocation, utmSource, provider "unsplash"). The site renders the "Photo by … on Unsplash" credit from `attribution` automatically, so do NOT also copy the credit into `caption` (leave caption empty unless you have a genuine descriptive caption).':'Set the image content\'s `attribution` (photographer, photographerUrl, sourceUrl, provider "pexels"). The site renders the "Photo by … on Pexels" credit from `attribution` automatically, so do NOT also copy the credit into `caption` (leave caption empty unless you have a genuine descriptive caption). Pexels attribution is appreciated but optional.'}}catch(u){s=u}}return{attemptedProviders:a,message:s?`Stock photo search failed across ${a.join(", ")}: ${b(s)}`:`No matching stock photos found for "${n.query}".`,photos:[],success:!1}}const wt=W.extend({blocks:i.z.array(le).min(1).max(20),meta:i.z.strictObject({meta_description:i.z.string().max(500).nullable().optional(),meta_title:i.z.string().max(160).nullable().optional(),slug:i.z.string().trim().min(1).max(300).optional(),status:i.z.enum(["draft","published","archived"]).optional(),title:i.z.string().trim().min(1).max(300).optional()}).partial().optional()}),ho=["custom_canonical","excerpt","feature_image_id","label","language_id","meta_description","meta_title","published_at","slug","status","subtitle","title","translation_group_id"];function yo(e){const t={};for(const n of ho)n in e&&e[n]!==void 0&&(t[n]=e[n]);return t}function bo(e,t){if(!t)return null;const n=e==="page"?t==="home"?"/":`/${t}`:`/article/${t}`;return`/api/draft/start?path=${encodeURIComponent(n)}`}async function kn(e,t){const n=wt.parse(e),o=x(t),r=et(t),a=await J(n,t);if(a.contentType==="product")throw new Error("rewrite_page_draft supports pages and posts only. Products use description_json, not page blocks.");const s=a.contentType,c=Number(a.item.id);if(!Number.isInteger(c)||c<=0)throw new Error("Could not resolve a valid page/post id for the draft rewrite.");const u=Number(a.item.language_id);if(!Number.isInteger(u)||u<=0)throw new Error("The target page/post is missing a language id.");const l=Oe(n.blocks,void 0,void 0,t).map((w,v)=>({block_type:w.block_type,content:w.content,language_id:u,order:v,page_id:s==="page"?c:null,post_id:s==="post"?c:null,product_id:null})),p=yo(a.item);if(n.meta)for(const[w,v]of Object.entries(n.meta))v!==void 0&&(p[w]=v);const h=Kt(typeof p.slug=="string"?p.slug:a.item.slug),m=typeof p.title=="string"&&p.title.trim()?p.title:String(a.item.title||h||"Untitled"),f=s==="page"?`/cms/pages/${c}/edit`:`/cms/posts/${c}/edit`,g=bo(s,h),_=P({action:"REWRITE DRAFT",context:t,payload:{blocks:l,meta:p,parent_id:c,parent_type:s,tool:"rewrite_page_draft"},preview:{blockCount:l.length,contentType:s,slug:h,summary:`Stage a Live Draft that replaces the ${s} "${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:`${s}-${c}`});if(_)return _;const k=Number(a.item.version)||1,{error:I}=await o.from("content_drafts").delete().eq("parent_type",s).eq("parent_id",c);if(I)throw new Error(`Failed to clear the existing draft: ${b(I)}`);const{error:T}=await o.from("content_drafts").insert({author_id:r,base_version:k,blocks:l,meta:p,parent_id:c,parent_type:s});if(T)throw new Error(`Failed to save the draft: ${b(T)}`);return be(l,o),U(t,{contentType:s,entityId:c,slug:h},h),{blockCount:l.length,contentType:s,draftPreviewPath:g,editPath:f,entityId:c,isDraft:!0,mutationExecuted:!0,slug:h,success:!0,title:m}}const kt=i.z.strictObject({attributes:i.z.array(i.z.strictObject({name:i.z.string().trim().min(1).max(120).describe('Attribute name, e.g. "Size" or "Flavour".'),terms:i.z.array(i.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:i.z.union([i.z.number().int().positive(),i.z.string().trim().min(1).max(120)]).optional(),mode:i.z.enum(["replace","append"]).default("replace").describe(`"replace" removes the product's existing variants first; "append" keeps them and adds these.`),slug:i.z.string().trim().min(1).max(300).optional(),title:i.z.string().trim().min(1).max(300).optional(),variants:i.z.array(i.z.strictObject({image:i.z.string().trim().min(1).max(2048).optional().describe("Variant-specific image: an https:// URL (imported automatically) or a media library id."),options:i.z.record(i.z.string(),i.z.string()).describe('Which term this variant is, per attribute, e.g. { "Size": "500 ml" }. Every attribute must be given a value.'),price:i.z.number().min(0).optional().describe("Price in major units (25 = $25.00). Defaults to the product price."),sale_price:i.z.number().min(0).nullable().optional().describe("Sale price in major units, or null for none."),sku:i.z.string().trim().min(1).max(120).describe("Unique SKU for this variant."),stock:i.z.number().int().min(0).default(0),upc:i.z.string().trim().max(120).nullable().optional()})).min(1).max(50)});async function _o(e,t){const n=O(t.name),{data:o}=await e.from("product_attributes").select("id").eq("slug",n).maybeSingle();let r=o?.id;if(!r){const{data:s,error:c}=await e.from("product_attributes").insert({name:t.name,slug:n}).select("id").single();if(c||!s?.id)throw new Error(`Could not create the "${t.name}" attribute: ${b(c)}`);r=s.id}const a=new Map;for(let s=0;s<t.terms.length;s+=1){const c=t.terms[s],u=O(c),{data:d}=await e.from("product_attribute_terms").select("id").eq("attribute_id",r).eq("slug",u).maybeSingle();if(d?.id){a.set(c,d.id);continue}const{data:l,error:p}=await e.from("product_attribute_terms").insert({attribute_id:r,slug:u,sort_order:s,value:c}).select("id").single();if(p||!l?.id)throw new Error(`Could not create the "${c}" option: ${b(p)}`);a.set(c,l.id)}return{attributeId:r,termIdByValue:a}}async function In(e,t){const n=kt.parse(e),o=x(t),a=(await J({contentType:"product",...n.entityId!==void 0?{entityId:n.entityId}:{},...n.slug?{slug:n.slug}:{},...n.title?{title:n.title}:{}},t)).item,s=String(a.id),c=P({action:"SET VARIANTS",context:t,payload:{entityId:s,mode:n.mode,variantCount:n.variants.length},preview:{contentType:"product",slug:a.slug,summary:`${n.mode==="replace"?"Replace":"Add"} ${N(n.variants.length,"variant")} on "${a.title}". Product stock becomes the sum of variant stock.`,title:a.title},subject:`product-${s}-variants`});if(c)return c;const u=new Map;for(const g of n.attributes??[]){const{termIdByValue:y}=await _o(o,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 o.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 o.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 o.from("product_variants").delete().eq("product_id",s);if(g)throw new Error(`Could not clear the existing variants: ${b(g)}`)}const d=await De(o),l=Number(a.price)||0,p=[];for(const g of n.variants){const y=g.image?await X(g.image,t,`${a.title} ${g.sku}`):null,{data:_,error:k}=await o.from("product_variants").insert({main_media_id:y,price:g.price===void 0?l:Te(g.price,d),product_id:s,sale_price:g.sale_price===void 0||g.sale_price===null?null:Te(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 o.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 o.from("product_variants").select("stock_quantity").eq("product_id",s),m=(h??[]).reduce((g,y)=>g+(Number(y?.stock_quantity)||0),0),{error:f}=await o.from("products").update({stock:m}).eq("id",s);if(f)throw new Error(`Variants saved, but the product stock total failed: ${b(f)}`);return U(t,{contentType:"product",entityId:s,slug:a.slug,title:a.title},a.slug),{contentType:"product",entityId:s,mode:n.mode,mutationExecuted:!0,skus:p,slug:a.slug,success:!0,totalStock:m,variantCount:p.length}}const It=i.z.strictObject({items:i.z.array(i.z.strictObject({contentType:i.z.enum(["page","post"]).default("page"),slug:i.z.string().trim().min(1).max(300).describe("Slug of the source page or post."),title:i.z.string().trim().min(1).max(300).optional().describe("Translated title. Defaults to translating the source title."),translations:i.z.record(i.z.string(),i.z.string()).describe("Source string -> translated string for every visible string in THIS item.")})).min(1).max(25),targetLanguageCode:i.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 Tn(e,t){const n=It.parse(e),o=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(s=>s.slug).join(", ")}.`,title:`Bulk translate to ${n.targetLanguageCode}`},subject:`bulk-translate-${n.targetLanguageCode}`});if(o)return o;const r=[],a=[];for(const s of n.items)try{const c=await Ct({cmsTarget:{contentType:s.contentType,slug:s.slug},targetLanguageCode:n.targetLanguageCode,...s.title?{title:s.title}:{},translations:s.translations},t);r.push({slug:s.slug,...c})}catch(c){a.push({error:c instanceof Error?c.message:String(c),slug:s.slug})}return{failed:a,failedCount:a.length,mutationExecuted:r.length>0,success:a.length===0,targetLanguageCode:n.targetLanguageCode,translated:r,translatedCount:r.length}}const Tt=i.z.strictObject({action:i.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:i.z.enum(["page","post"]).optional(),entityId:i.z.union([i.z.number().int().positive(),i.z.string().trim().min(1).max(120)]).optional(),slug:i.z.string().trim().min(1).max(300).optional(),title:i.z.string().trim().min(1).max(300).optional()}),wo=["title","slug"],ko=["custom_canonical","feature_image_id","meta_description","meta_title"];async function vn(e,t){const n=Tt.parse(e),o=x(t),r=await Z({...n.contentType?{contentType:n.contentType}:{},...n.entityId!==void 0?{entityId:n.entityId}:{},...n.slug?{slug:n.slug}:{},...n.title?{title:n.title}:{}},t);if(r.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 a=r.contentType,s=Pe(r),c=a==="page"?"pages":"posts",{data:u,error:d}=await o.from("content_drafts").select("*").eq("parent_type",a).eq("parent_id",s).maybeSingle();if(d)throw new Error(`Failed to read the draft: ${b(d)}`);if(!u)return{contentType:a,entityId:s,message:`No Live Draft exists for ${a} "${r.title||r.slug}". Nothing to ${n.action}.`,mutationExecuted:!1,success:!1};const l=r.title||r.slug||`${a} ${s}`,p=P({action:n.action==="publish"?"PUBLISH DRAFT":"DISCARD DRAFT",context:t,payload:{action:n.action,contentType:a,entityId:String(s)},preview:{contentType:a,slug:r.slug,summary:n.action==="publish"?`Publish the Live Draft for ${a} "${l}", replacing its live blocks. A revision snapshot is saved first, so this is reversible from Revision History.`:`Discard the Live Draft for ${a} "${l}". The live content is left untouched.`,title:r.title},subject:`${a}-${s}-draft`});if(p)return p;const h=u.meta??{},m=Array.isArray(u.blocks)?u.blocks:[];if(n.action==="discard"){const{error:w}=await o.from("content_drafts").delete().eq("id",u.id);if(w)throw new Error(`Failed to discard the draft: ${b(w)}`);return U(t,r,r.slug),{action:"discard",contentType:a,entityId:s,mutationExecuted:!0,success:!0}}const f=await V(t,a,s),g={};for(const w of wo){const v=h[w];typeof v=="string"&&v.trim()&&(g[w]=v.trim())}for(const w of ko)if(Object.prototype.hasOwnProperty.call(h,w)){const v=h[w];g[w]=typeof v=="string"&&v.trim()?v.trim():null}if(Object.keys(g).length>0){const{error:w}=await o.from(c).update(g).eq("id",s);if(w)throw new Error(`Failed to apply the draft metadata: ${b(w)}`)}const y=a==="page"?"page_id":"post_id",{error:_}=await o.from("blocks").delete().eq(y,s);if(_)throw new Error(`Failed to clear the live blocks: ${b(_)}`);const k=Number(h.language_id)||Number(r.languageId)||Number(m[0]?.language_id)||0;if(m.length>0){const w=m.map((S,F)=>({block_type:S?.block_type,content:S?.content??{},language_id:Number(S?.language_id)||k,order:Number.isFinite(S?.order)?S.order:F,page_id:a==="page"?s:null,post_id:a==="post"?s:null,product_id:null})),{error:v}=await o.from("blocks").insert(w);if(v)throw new Error(`Failed to publish the draft blocks: ${b(v)}`)}await M(t,a,s,f);const{error:I}=await o.from("content_drafts").delete().eq("id",u.id),T=typeof g.slug=="string"?g.slug:r.slug;return U(t,{...r,slug:T},T??void 0),{action:"publish",blockCount:m.length,contentType:a,entityId:s,mutationExecuted:!0,slug:T,success:!0,...I?{warning:`Published, but the draft row was not removed: ${b(I)}`}:{}}}const Io=new Set(["alt_text","author_name","author_title","caption","html_content","label","placeholder","quote","submit_button_text","success_message","text","text_content","title"]);function He(e,t,n){if(!e)return e;if(Object.prototype.hasOwnProperty.call(t,e))return t[e];const o=e.trim();if(o!==e&&Object.prototype.hasOwnProperty.call(t,o))return e.replace(o,t[o]);let r=e;for(const[a,s]of n)a&&r.includes(a)&&(r=r.split(a).join(s));return r}function Ve(e,t,n){if(Array.isArray(e))return e.map(o=>Ve(o,t,n));if(e&&typeof e=="object"){const o={};for(const[r,a]of Object.entries(e))typeof a=="string"&&Io.has(r)?o[r]=He(a,t,n):a&&typeof a=="object"?o[r]=Ve(a,t,n):o[r]=a;return o}return e}const vt=i.z.strictObject({cmsTarget:ie,targetLanguageCode:i.z.string().trim().min(2).max(80).describe('Target language code or name, e.g. "fr" or "French".'),title:i.z.string().trim().min(1).max(300).optional().describe("Translated page title (defaults to translating the source title)."),translations:i.z.record(i.z.string(),i.z.string()).describe('Map of every visible source string to its translation, e.g. { "Explore Our Products": "Explorez nos produits" }. Include headings, paragraph text, button labels, image alt text, captions, and form labels.')});async function Ct(e,t){const n=vt.parse(e),o=await Z(n.cmsTarget,t);if(o.contentType==="product")throw new Error("translate_page supports pages and posts only.");const r=x(t),a=Pe(o),s=o.contentType==="page"?"pages":"posts",c=o.contentType==="page"?"page_id":"post_id",{data:u,error:d}=await r.from(s).select("*").eq("id",a).single();if(d||!u)throw new Error(`Could not read the source ${o.contentType} to translate: ${b(d)}`);const{data:l,error:p}=await r.from("blocks").select("id, block_type, content, order").eq(c,a);if(p)throw new Error(`Could not read the source blocks: ${b(p)}`);const h=(Array.isArray(l)?l:[]).slice().sort((C,A)=>Number(C.order)-Number(A.order));if(h.length===0)throw new Error(`The source ${o.contentType} has no content blocks to translate.`);const m=n.translations||{},f=Object.entries(m).filter(([C])=>!!C).sort((C,A)=>A[0].length-C[0].length),g=h.map((C,A)=>({blockType:C.block_type,content:Ve(K(C.content),m,f),order:A})),y=await Ue(r,n.targetLanguageCode),_=String(u.title||""),k=n.title||He(_,m,f)||_||"Untitled",I=C=>typeof C=="string"&&C.trim()?He(C,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},v=o.contentType==="post"?{...w,excerpt:I(u.excerpt),label:I(u.label),published_at:u.published_at??new Date().toISOString(),subtitle:I(u.subtitle)}:w,S=P({action:"TRANSLATE",context:t,payload:{createInput:v,sourceId:u.id,tool:"translate_page"},preview:{blockCount:g.length,contentType:o.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 ${o.contentType}, at /${w.slug} with ${N(g.length,"translated block")}.`,title:k},subject:`translate ${o.contentType} ${u.id} to ${y.code}`});if(S)return S;const F={...t,skipConfirmation:!0};return{...o.contentType==="post"?await Le(v,F):await Fe(v,F),isTranslation:!0,languageCode:y.code}}async function zt(e,t){const n=ue.parse(e),o=n.entityId!==void 0||!!n.slug||!!n.title,r=x(t);let a,s;if(o){const g=await J({contentType:n.contentType,entityId:n.entityId,slug:n.slug,title:n.title},t),y=g.item;s=y.id,a={contentType:g.contentType,entityId:s,slug:typeof y.slug=="string"?y.slug:"",title:typeof y.title=="string"?y.title:""}}else a=Xn(t),s=q(a);const c=a.title||a.slug||"current item",u=a.contentType==="product",d=P({action:"SET IMAGES",context:t,payload:{contentType:a.contentType,entityId:String(s),images:n.images,tool:"set_content_images"},preview:{contentType:a.contentType,imageCount:n.images.length,slug:a.slug,summary:u?`Set ${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 ${a.contentType} "${c}".`,title:a.title},subject:`set images on ${a.contentType} ${String(s)}`});if(d)return d;const l=await Gt(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 r.from("products").select("id, slug, language_id, title").eq("id",s).maybeSingle();if(y||!g)throw new Error(`Could not load the product to set images: ${b(y)}`);const _=await er({mediaIds:l,productId:s,supabase:r});return await Ne({patch:({meta:k})=>Array.isArray(k.product_media)?{meta:{...k,product_media:_.map((I,T)=>({media_id:I,sort_order:T}))}}:{},productId:s,supabase:r}),U(t,{contentType:"product",entityId:String(s),languageId:g.language_id,slug:g.slug,title:g.title},g.slug),t?.revalidatePath?.("/cms/products"),{contentType:"product",entityId:s,imageCount:_.length,mutationExecuted:!0,slug:g.slug,success:!0}}const p=await V(t,a.contentType,s),h=a.contentType==="page"?"pages":"posts",{data:m,error:f}=await r.from(h).update({feature_image_id:l[0],updated_at:new Date().toISOString()}).eq("id",s).select("id, language_id, slug, status, title").single();if(f||!m)throw new Error(`Failed to set the feature image: ${b(f)}`);return await M(t,a.contentType,s,p),U(t,a,m.slug),{contentType:a.contentType,entityId:s,extraImagesIgnored:l.length-1,imageCount:1,mutationExecuted:!0,slug:m.slug,success:!0}}function To(e){return{...Cn.createCortexDatabaseAgentTools(e),...zn.createCortexCustomBlockTools(e),...xn.createCortexContentOpsTools(e),...Sn.createCortexThemingTools(e),fetch_ecommerce_stats:z.tool({description:"Fetch quantitative ecommerce statistics and reports from the database. Use this to answer questions about revenue, order counts, order status counts such as pending or trial, and top-selling products over a time range. This tool is read-only and does not require confirmation.",execute:t=>on(t,e),inputSchema:Je,strict:!0}),read_current_cms_item:z.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=>an(t,e),inputSchema:Ye,strict:!0}),search_documentation:z.tool({description:"Search the NextBlock documentation database and return concise source snippets for factual CMS guidance.",execute:t=>rn(t,e),inputSchema:$e,strict:!0}),fetch_url_content:z.tool({description:"Fetch an external web page and return its title, meta description, headings, body text, AND its images: `mainImage` (the page's subject image — schema.org Product image, else og:image, else the best in-body <img>) plus a ranked `images` list, all as absolute URLs. Read-only, no confirmation. Use this first whenever the user references an external URL to copy, adapt, clone, or draw inspiration from. To reuse the source page's image, pass `mainImage` straight into create_cms_product `images` or a page/post `feature_image_id` — it is imported into the media library automatically. Never invent an image URL: if `mainImage` is null, the page had none.",execute:t=>_n(t),inputSchema:bt,strict:!0}),search_stock_photos:z.tool({description:"Find relevant, free, high-quality stock photos (Unsplash/Pexels) for page imagery. Returns a list of photos each with a direct image `url`, `width`, `height`, `alt`, and `photographer`. Read-only, zero cost. Use the returned `url` directly as an image block's external_url or a section image background's image.external_url when building or revamping pages, so layouts show real photos instantly. Set orientation \"landscape\" for hero/section backgrounds.",execute:t=>wn(t,e),inputSchema:_t,strict:!0}),manage_product_variants:z.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=>In(t,e),inputSchema:kt,strict:!0}),translate_content_bulk:z.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=>Tn(t,e),inputSchema:It,strict:!0}),publish_content_draft:z.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=>vn(t,e),inputSchema:Tt,strict:!0}),rewrite_page_draft:z.tool({description:'Replace ALL blocks of an existing page or post with a brand-new set of blocks, staged as a Live Draft (content_drafts) that the user previews before publishing. Use this for whole-page redesigns/rewrites such as "rewrite my home page with 5 sections". Provide the complete new list of top-level blocks in `blocks` (usually section blocks for a landing/home page, each with nested heading/text/button blocks). Nothing goes live until the user publishes the draft, and publishing auto-creates a revision snapshot so the change is reversible. Mutating: first returns a confirmation phrase; only stages the draft after the user replies with the exact phrase.',execute:t=>kn(t,e),inputSchema:wt,strict:!0}),translate_page:z.tool({description:'Translate the CURRENT page or post into another language. This copies the source page\'s entire structure, layout, and images automatically and links the new page to the original as a translation — you ONLY supply the text translations. Provide targetLanguageCode (e.g. "fr") and a `translations` map of every visible source string to its translation (headings, paragraph text, button labels, image alt text, captions, form labels). Do NOT rebuild the layout or call search_stock_photos for a translation. 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=>Ct(t,e),inputSchema:vt,strict:!0}),set_content_images:z.tool({description:"Set the feature image for a page or post, or the image gallery for a product. Pass `images`: a list of image URLs (e.g. `mainImage` from fetch_url_content or `url` values from search_stock_photos) and/or existing media library IDs. External URLs are imported into the media library automatically — NEVER put an image URL directly into feature_image_id. The FIRST image becomes the feature image (pages/posts) or the main product image (products); for a product the remaining images become its gallery in order (this REPLACES the product's current images). Targets the currently open page/post/product by default; to target any other item (for example a product you just created from the dashboard) pass contentType plus slug, entityId, or title — no open editor needed. Mutating: first returns a confirmation phrase; only applies after exact confirmation.",execute:t=>zt(t,e),inputSchema:ue,strict:!0}),create_cms_page:z.tool({description:"Create a new CMS page with metadata and optional validated page blocks. Mutating: first returns a confirmation phrase; only executes after the user replies with the exact phrase. For translations, pass translationGroupId from the source page/post/product context so the new language is linked to the same backend translation group. For contact pages, provide a form block with fields; the destination address is configured once in CMS -> Messages and is never stored on the block.",execute:t=>Fe(t,e),inputSchema:pe,strict:!0}),create_cms_post:z.tool({description:"Create a new CMS post with metadata and optional validated post blocks. Mutating: first returns a confirmation phrase; only executes after the user replies with the exact phrase. For translations, pass translationGroupId from the source post context so the new language is linked to the same backend translation group.",execute:t=>Le(t,e),inputSchema:me,strict:!0}),create_cms_product:z.tool({description:"Create a new draft-capable product, complete with its images and its body copy in ONE call. Pass `images` to set the main product image and gallery (external https URLs are imported into the media library automatically — use `mainImage` from fetch_url_content to reuse a source page's photo). Pass `blocks` to build the product's \"Product Description Blocks\" — the SAME block vocabulary and section-based design rules as create_cms_page, rendered on the public product page. This is the richest product body and is what you should produce whenever the user asks to copy or write real product content. Also pass `short_description` for the one-line summary shown on product cards. `description_html` is a plain-HTML fallback body used only when no blocks are supplied. Defaults missing fields safely: physical Stripe product, generated SKU, price 0, stock 0, taxable, draft. `price` is in major units (25 = $25.00). For translations, pass translationGroupId from the source product context. Mutating: first returns a confirmation phrase; only executes after exact confirmation.",execute:t=>gt(t,e),inputSchema:ge,strict:!0}),delete_cms_item:z.tool({description:"Delete a resolved page, post, or product after exact confirmation. Pages/posts delete all translations in the translation group and related navigation links. Mutating: refuses unless the latest user message includes the exact confirmation phrase.",execute:t=>yt(t,e),inputSchema:he,strict:!0}),prepare_delete_cms_item:z.tool({description:"Inspect the page, post, or product that would be deleted and return the exact confirmation phrase. This tool does not mutate data.",execute:t=>mn(t,e),inputSchema:Xe,strict:!0}),update_footer:z.tool({description:"Replace the public footer links and/or footer copyright settings for a locale. Use links for footer navigation and copyright for locale text templates. Mutating: first returns a confirmation phrase; only executes after exact confirmation.",execute:t=>lt(t,e),inputSchema:oe,strict:!0}),update_content_block:z.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=>dt(t,e),inputSchema:se,strict:!0}),insert_content_block:z.tool({description:'Insert a new validated top-level page/post block before or after an existing block, or at the start/end. Use this for visible content additions like adding a rich text title and paragraph above a form. For "above the form", use position "before" with anchorBlockType "form" and blockType "text" containing html_content. Mutating: first returns a confirmation phrase; only executes after exact confirmation.',execute:t=>pt(t,e),inputSchema:de,strict:!0}),update_current_cms_fields:z.tool({description:"Update validated metadata fields on the current page, post, or product. For products, description_json must be a valid NextBlock editor document JSON object. Mutating: first returns a confirmation phrase; only executes after exact confirmation.",execute:t=>ut(t,e),inputSchema:ae,strict:!0}),update_cms_item_field:z.tool({description:"Update one field on a page, post, or product, resolving by current edit context, id, slug, or exact title. Use this for requests like changing price, stock, title, slug, status, sale_price, or meta fields. Interpret public as published for pages/posts and active for products. Scheduled sale date ranges are not supported and will be refused without mutation. Mutating: first returns a confirmation phrase; only executes after exact confirmation.",execute:t=>ht(t,e),inputSchema:fe,strict:!0}),update_navigation_bar:z.tool({description:'Update the public header navigation bar for a locale. Use mode "append" when adding links while preserving existing navigation. Use mode "update" when renaming or changing an existing single link. Use mode "replace" only when the user asks to rebuild the complete header and you provide the full menu; destructive partial replacements are refused. Mutating: first returns a confirmation phrase; only executes after exact confirmation.',execute:t=>ct(t,e),inputSchema:re,strict:!0}),update_section_column_block:z.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=>mt(t,e),inputSchema:ce,strict:!0}),execute_cms_action_plan:z.tool({description:"Execute multiple CMS mutations as one confirmed plan. Use this whenever the user asks for more than one change in the same prompt, such as creating a page and adding a navigation link. First returns one combined confirmation preview and Confirm button; after confirmation, runs each action in order and stops on the first failure.",execute:t=>gn(t,e),inputSchema:Qe,strict:!0})}}exports.availableCortexAiBlockTypes=H;exports.buildVisibleContactIntroActionPlan=qn;exports.cortexAiPageContextSchema=Ae;exports.createCmsPageInputSchema=pe;exports.createCmsPostInputSchema=me;exports.createCmsProductInputSchema=ge;exports.createCortexGlobalAgentTools=To;exports.deleteCmsItemInputSchema=he;exports.executeCmsActionPlan=gn;exports.executeCmsActionPlanInputSchema=Qe;exports.executeCreateCmsPage=Fe;exports.executeCreateCmsPost=Le;exports.executeCreateCmsProduct=gt;exports.executeDeleteCmsItem=yt;exports.executeFetchEcommerceStats=on;exports.executeFetchUrlContent=_n;exports.executeInsertContentBlock=pt;exports.executeManageProductVariants=In;exports.executePrepareDeleteCmsItem=mn;exports.executePublishContentDraft=vn;exports.executeReadCurrentCmsItem=an;exports.executeRewritePageDraft=kn;exports.executeSearchDocumentation=nn;exports.executeSearchDocumentationWithTimeout=rn;exports.executeSearchStockPhotos=wn;exports.executeSetContentImages=zt;exports.executeTranslateContentBulk=Tn;exports.executeTranslatePage=Ct;exports.executeUpdateCmsItemField=ht;exports.executeUpdateContentBlock=dt;exports.executeUpdateCurrentCmsFields=ut;exports.executeUpdateFooter=lt;exports.executeUpdateNavigationBar=ct;exports.executeUpdateSectionColumnBlock=mt;exports.fetchEcommerceStatsInputSchema=Je;exports.fetchUrlContentInputSchema=bt;exports.insertContentBlockInputSchema=de;exports.isBlockedFetchHost=Se;exports.manageProductVariantsInputSchema=kt;exports.maybeTriggerStockPhotoDownloads=be;exports.navigationItemInputSchema=We;exports.prepareDeleteCmsItemInputSchema=Xe;exports.publishContentDraftInputSchema=Tt;exports.readCurrentCmsItemInputSchema=Ye;exports.resolveCortexAiStockPhotoProvider=mo;exports.resolveCortexAiStockPhotoProviders=Re;exports.rewritePageDraftInputSchema=wt;exports.searchDocumentationInputSchema=$e;exports.searchStockPhotosInputSchema=_t;exports.setContentImagesInputSchema=ue;exports.translateContentBulkInputSchema=It;exports.translatePageInputSchema=vt;exports.updateCmsItemFieldInputSchema=fe;exports.updateContentBlockInputSchema=se;exports.updateCurrentCmsFieldsInputSchema=ae;exports.updateFooterInputSchema=oe;exports.updateNavigationBarInputSchema=re;exports.updateSectionColumnBlockInputSchema=ce;
|
|
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(/ /gi," ").replace(/&/gi,"&").replace(/</gi,"<").replace(/>/gi,">").replace(/"/gi,'"').replace(/'/gi,"'").replace(/\s+/g," ").trim()}function to(e){return e.trim().replace(/&/gi,"&").replace(/&/g,"&").replace(/"/gi,'"').replace(/'/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;
|