@nextblock-cms/cortex 0.12.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/client.cjs.js +1 -0
  2. package/client.d.ts +1 -0
  3. package/client.es.js +4 -0
  4. package/index.cjs.js +1 -0
  5. package/index.d.ts +13 -0
  6. package/index.es.js +135 -0
  7. package/lib/ai-block-generation.cjs.js +5 -0
  8. package/lib/ai-block-generation.d.ts +21 -0
  9. package/lib/ai-block-generation.es.js +195 -0
  10. package/lib/ai-client.cjs.js +1 -0
  11. package/lib/ai-client.d.ts +48 -0
  12. package/lib/ai-client.es.js +141 -0
  13. package/lib/ai-config.cjs.js +1 -0
  14. package/lib/ai-config.d.ts +31 -0
  15. package/lib/ai-config.es.js +72 -0
  16. package/lib/ai-cortex-widget-builder.cjs.js +1 -0
  17. package/lib/ai-cortex-widget-builder.d.ts +14 -0
  18. package/lib/ai-cortex-widget-builder.es.js +72 -0
  19. package/lib/ai-global-agent-custom-block-tools.cjs.js +1 -0
  20. package/lib/ai-global-agent-custom-block-tools.d.ts +208 -0
  21. package/lib/ai-global-agent-custom-block-tools.es.js +220 -0
  22. package/lib/ai-global-agent-db-tools.cjs.js +1 -0
  23. package/lib/ai-global-agent-db-tools.d.ts +280 -0
  24. package/lib/ai-global-agent-db-tools.es.js +879 -0
  25. package/lib/ai-global-agent-ecommerce.cjs.js +1 -0
  26. package/lib/ai-global-agent-ecommerce.d.ts +2 -0
  27. package/lib/ai-global-agent-ecommerce.es.js +7 -0
  28. package/lib/ai-global-agent-tools.cjs.js +15 -0
  29. package/lib/ai-global-agent-tools.d.ts +3109 -0
  30. package/lib/ai-global-agent-tools.es.js +2812 -0
  31. package/lib/ai-key-crypto.cjs.js +1 -0
  32. package/lib/ai-key-crypto.d.ts +32 -0
  33. package/lib/ai-key-crypto.es.js +88 -0
  34. package/lib/ai-model-catalog.cjs.js +1 -0
  35. package/lib/ai-model-catalog.d.ts +7 -0
  36. package/lib/ai-model-catalog.es.js +25 -0
  37. package/lib/ai-model-registry.cjs.js +3 -0
  38. package/lib/ai-model-registry.d.ts +79 -0
  39. package/lib/ai-model-registry.es.js +279 -0
  40. package/lib/cortex-widget-registry.cjs.js +1 -0
  41. package/lib/cortex-widget-registry.d.ts +19 -0
  42. package/lib/cortex-widget-registry.es.js +47 -0
  43. package/lib/cortex-widget-schema.cjs.js +5 -0
  44. package/lib/cortex-widget-schema.d.ts +224 -0
  45. package/lib/cortex-widget-schema.es.js +316 -0
  46. package/lib/zod-config.cjs.js +1 -0
  47. package/lib/zod-config.d.ts +2 -0
  48. package/lib/zod-config.es.js +6 -0
  49. package/package.json +39 -0
@@ -0,0 +1 @@
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("@nextblock-cms/ecommerce/product-actions"),t=require("@nextblock-cms/ecommerce/product-schema");Object.defineProperty(exports,"createProduct",{enumerable:!0,get:()=>e.createProduct});Object.defineProperty(exports,"updateProduct",{enumerable:!0,get:()=>e.updateProduct});Object.defineProperty(exports,"productSchema",{enumerable:!0,get:()=>t.productSchema});
@@ -0,0 +1,2 @@
1
+ export { createProduct, updateProduct } from '../../../ecommerce/src/lib/product-actions';
2
+ export { productSchema } from '../../../ecommerce/src/lib/product-schema';
@@ -0,0 +1,7 @@
1
+ import { createProduct as t, updateProduct as e } from "@nextblock-cms/ecommerce/product-actions";
2
+ import { productSchema as d } from "@nextblock-cms/ecommerce/product-schema";
3
+ export {
4
+ t as createProduct,
5
+ d as productSchema,
6
+ e as updateProduct
7
+ };
@@ -0,0 +1,15 @@
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const w=require("ai"),Ft=require("./ai-global-agent-db-tools.cjs.js"),Nt=require("./ai-global-agent-custom-block-tools.cjs.js");require("./zod-config.cjs.js");const o=require("zod"),N=["text","heading","image","button","posts_grid","video_embed","section","form","testimonial","product_grid","featured_product","cart","checkout","product_details"],jt=1e4,qt={arabic:"ar",chinese:"zh",dutch:"nl",english:"en",french:"fr",francaise:"fr",francais:"fr",german:"de",italian:"it",japanese:"ja",korean:"ko",portuguese:"pt",russian:"ru",spanish:"es"},it=o.z.string().trim().min(1).max(2048).refine(e=>e.startsWith("/")||e.startsWith("#")||e.startsWith("http://")||e.startsWith("https://")||e.startsWith("mailto:")||e.startsWith("tel:"),"URL must be a relative path, hash link, http(s) URL, mailto URL, or tel URL."),He=o.z.strictObject({label:o.z.string().trim().min(1).max(120),target:o.z.enum(["_self","_blank"]).optional(),url:it}),ye=He.extend({children:o.z.array(He).max(20).optional()}),Ot=o.z.strictObject({label:o.z.string().trim().min(1).max(120).optional(),url:it.optional()}).refine(e=>!!(e.label||e.url),{message:"Navigation item match requires label or url."}),G=o.z.strictObject({items:o.z.array(ye).min(1).max(30),languageCode:o.z.string().trim().min(2).max(80).default("en").describe('Locale code or language name, for example "en", "fr", "English", or "French".'),match:Ot.optional().describe('For mode "update", identifies the existing navigation item to update.'),mode:o.z.enum(["append","replace","update"]).default("append")}),R=o.z.strictObject({copyright:o.z.record(o.z.string().trim().min(2).max(12),o.z.string().trim().min(1).max(500)).optional(),languageCode:o.z.string().trim().min(2).max(80).default("en").describe('Locale code or language name, for example "en", "fr", "English", or "French".'),links:o.z.array(ye).min(1).max(30).optional()}),de=o.z.strictObject({limit:o.z.number().int().min(1).max(8).default(4),query:o.z.string().trim().min(2).max(300)}),ke=o.z.object({currency:o.z.string().trim().min(3).max(3).optional().describe("Optional currency code for currency-specific monetary reports (e.g., USD, CAD). Do not set this for plain order-status counts unless the user asks for a currency."),query:o.z.string().describe("The analytical question about orders, products, or revenue."),reportType:o.z.enum(["revenue","orders","products","general"]).optional().default("general").describe("The focus area of the statistical report."),timeRange:o.z.enum(["today","this_month","last_7_days","last_30_days","last_month","last_90_days","all_time"]).optional().default("all_time").describe("The time period for the report. Use all_time for current order-status counts unless the user names a specific period.")}),we=o.z.strictObject({contentType:o.z.enum(["page","post","product"]),currentEditor:o.z.strictObject({blockId:o.z.union([o.z.number().int().positive(),o.z.string().trim().min(1).max(120)]).nullable().optional(),blockType:o.z.string().trim().min(1).max(80).nullable().optional(),field:o.z.string().trim().min(1).max(120).nullable().optional()}).optional(),entityId:o.z.union([o.z.number().int().positive(),o.z.string().trim().min(1).max(120)]),languageId:o.z.number().int().positive().nullable().optional(),slug:o.z.string().trim().min(1).max(300).nullable().optional(),title:o.z.string().trim().min(1).max(300).nullable().optional(),translationGroupId:o.z.string().trim().min(1).max(120).nullable().optional()}),ze=o.z.strictObject({includeBlockContent:o.z.boolean().default(!1),includeBlocks:o.z.boolean().default(!0)}),K=o.z.strictObject({fields:o.z.strictObject({description_json:o.z.unknown().optional(),excerpt:o.z.string().max(2e3).nullable().optional(),feature_image_id:o.z.string().trim().min(1).max(120).nullable().optional(),label:o.z.string().max(120).nullable().optional(),meta_description:o.z.string().max(500).nullable().optional(),meta_title:o.z.string().max(160).nullable().optional(),published_at:o.z.string().max(80).nullable().optional(),short_description:o.z.string().max(2e3).nullable().optional(),slug:o.z.string().trim().min(1).max(300).optional(),status:o.z.enum(["draft","published","active","archived"]).optional(),subtitle:o.z.string().max(300).nullable().optional(),title:o.z.string().trim().min(1).max(300).optional()}).partial()}),V=o.z.strictObject({blockId:o.z.number().int().positive(),blockType:o.z.enum(N).optional(),content:o.z.record(o.z.string(),o.z.unknown())}),J=o.z.strictObject({blockIndex:o.z.number().int().min(0),blockType:o.z.enum(N).optional(),columnIndex:o.z.number().int().min(0),content:o.z.record(o.z.string(),o.z.unknown()),parentBlockId:o.z.number().int().positive()}),Ut=o.z.enum(["page","post","product"]),pe=o.z.strictObject({contentType:Ut.optional(),entityId:o.z.union([o.z.number().int().positive(),o.z.string().trim().min(1).max(120)]).optional(),slug:o.z.string().trim().min(1).max(300).optional(),title:o.z.string().trim().min(1).max(300).optional()}),Ie=o.z.strictObject({blockType:o.z.enum(N),content:o.z.record(o.z.string(),o.z.unknown()),order:o.z.number().int().min(0).optional()}),W=pe.extend({anchorBlockId:o.z.number().int().positive().optional(),anchorBlockType:o.z.enum(N).optional(),block:Ie,position:o.z.enum(["before","after","start","end"]).default("end")}),H=o.z.strictObject({blocks:o.z.array(Ie).max(20).optional(),contactEmail:o.z.string().email().optional(),feature_image_id:o.z.string().trim().min(1).max(120).nullable().optional(),languageCode:o.z.string().trim().min(2).max(80).optional(),meta_description:o.z.string().max(500).nullable().optional(),meta_title:o.z.string().max(160).nullable().optional(),slug:o.z.string().trim().min(1).max(300).optional(),status:o.z.enum(["draft","published","archived"]).default("draft"),title:o.z.string().trim().min(1).max(300),translationGroupId:o.z.string().trim().min(1).max(120).optional()}),Y=o.z.strictObject({blocks:o.z.array(Ie).max(20).optional(),excerpt:o.z.string().max(2e3).nullable().optional(),feature_image_id:o.z.string().trim().min(1).max(120).nullable().optional(),label:o.z.string().max(120).nullable().optional(),languageCode:o.z.string().trim().min(2).max(80).optional(),meta_description:o.z.string().max(500).nullable().optional(),meta_title:o.z.string().max(160).nullable().optional(),published_at:o.z.string().max(80).nullable().optional(),slug:o.z.string().trim().min(1).max(300).optional(),status:o.z.enum(["draft","published","archived"]).default("draft"),subtitle:o.z.string().max(300).nullable().optional(),title:o.z.string().trim().min(1).max(300),translationGroupId:o.z.string().trim().min(1).max(120).optional()}),Q=o.z.strictObject({description_json:o.z.unknown().optional(),freemius_plan_id:o.z.string().optional(),freemius_product_id:o.z.string().optional(),is_taxable:o.z.boolean().default(!0),languageCode:o.z.string().trim().min(2).max(80).optional(),meta_description:o.z.string().max(500).nullable().optional(),meta_title:o.z.string().max(160).nullable().optional(),payment_provider:o.z.enum(["stripe","freemius"]).default("stripe"),price:o.z.number().min(0).default(0),prices:o.z.record(o.z.string(),o.z.number().min(0)).optional(),product_type:o.z.enum(["physical","digital"]).default("physical"),sale_price:o.z.number().min(0).nullable().optional(),sale_prices:o.z.record(o.z.string(),o.z.number().min(0).nullable()).optional(),short_description:o.z.string().max(2e3).nullable().optional(),sku:o.z.string().trim().min(1).max(120).optional(),slug:o.z.string().trim().min(1).max(300).optional(),status:o.z.enum(["draft","active","archived"]).default("draft"),stock:o.z.number().int().min(0).default(0),title:o.z.string().trim().min(1).max(300),trial_period_days:o.z.number().int().min(0).default(0),trial_requires_payment_method:o.z.boolean().default(!1),translationGroupId:o.z.string().trim().min(1).max(120).optional(),upc:o.z.string().max(120).nullable().optional()}),X=pe.extend({currencyCode:o.z.string().trim().min(3).max(3).optional(),endsAt:o.z.string().max(80).nullable().optional(),field:o.z.string().trim().min(1).max(120),startsAt:o.z.string().max(80).nullable().optional(),value:o.z.unknown()}),Ce=pe,Z=pe,at=o.z.discriminatedUnion("tool",[o.z.strictObject({input:H,tool:o.z.literal("create_cms_page")}),o.z.strictObject({input:Y,tool:o.z.literal("create_cms_post")}),o.z.strictObject({input:Q,tool:o.z.literal("create_cms_product")}),o.z.strictObject({input:Z,tool:o.z.literal("delete_cms_item")}),o.z.strictObject({input:X,tool:o.z.literal("update_cms_item_field")}),o.z.strictObject({input:V,tool:o.z.literal("update_content_block")}),o.z.strictObject({input:W,tool:o.z.literal("insert_content_block")}),o.z.strictObject({input:K,tool:o.z.literal("update_current_cms_fields")}),o.z.strictObject({input:R,tool:o.z.literal("update_footer")}),o.z.strictObject({input:G,tool:o.z.literal("update_navigation_bar")}),o.z.strictObject({input:J,tool:o.z.literal("update_section_column_block")})]),Dt=o.z.union([H.extend({tool:o.z.literal("create_cms_page")}).transform(({tool:e,...n})=>({input:n,tool:e})),Y.extend({tool:o.z.literal("create_cms_post")}).transform(({tool:e,...n})=>({input:n,tool:e})),Q.extend({tool:o.z.literal("create_cms_product")}).transform(({tool:e,...n})=>({input:n,tool:e})),Z.extend({tool:o.z.literal("delete_cms_item")}).transform(({tool:e,...n})=>({input:n,tool:e})),X.extend({tool:o.z.literal("update_cms_item_field")}).transform(({tool:e,...n})=>({input:n,tool:e})),V.extend({tool:o.z.literal("update_content_block")}).transform(({tool:e,...n})=>({input:n,tool:e})),W.extend({tool:o.z.literal("insert_content_block")}).transform(({tool:e,...n})=>({input:n,tool:e})),K.extend({tool:o.z.literal("update_current_cms_fields")}).transform(({tool:e,...n})=>({input:n,tool:e})),R.extend({tool:o.z.literal("update_footer")}).transform(({tool:e,...n})=>({input:n,tool:e})),G.extend({tool:o.z.literal("update_navigation_bar")}).transform(({tool:e,...n})=>({input:n,tool:e})),J.extend({tool:o.z.literal("update_section_column_block")}).transform(({tool:e,...n})=>({input:n,tool:e}))]),Mt=o.z.string().transform((e,n)=>{const t=Vt(e);return t.success?t.action:(n.addIssue({code:"custom",message:t.message}),o.z.NEVER)}),Lt=o.z.union([at,Dt,Mt]),xe=o.z.strictObject({actions:o.z.array(Lt).min(1).max(8),summary:o.z.string().trim().min(1).max(500).optional()});function Gt(e){const n=[];let t="",r=0,i=null,a=!1;for(const s of e){if(i){t+=s,a?a=!1:s==="\\"?a=!0:s===i&&(i=null);continue}if(s==='"'||s==="'"){i=s,t+=s;continue}if(s==="["||s==="{"||s==="("){r++,t+=s;continue}if(s==="]"||s==="}"||s===")"){r=Math.max(0,r-1),t+=s;continue}if(s===","&&r===0){t.trim()&&n.push(t.trim()),t="";continue}t+=s}return t.trim()&&n.push(t.trim()),n}function Ye(e){let n="";for(let t=0;t<e.length;t++){const r=e[t];if(r!=="'"){n+=r;continue}let i="",a=!1;for(t++;t<e.length;t++){const s=e[t];if(a){i+=s,a=!1;continue}if(s==="\\"){a=!0;continue}if(s==="'")break;i+=s}n+=JSON.stringify(i)}return n.replace(/\bTrue\b/g,"true").replace(/\bFalse\b/g,"false").replace(/\bNone\b/g,"null")}function Rt(e){const n=e.trim();return n.startsWith("'")&&n.endsWith("'")||n.startsWith('"')&&n.endsWith('"')||n.startsWith("[")||n.startsWith("{")?JSON.parse(Ye(n)):/^-?\d+(?:\.\d+)?$/.test(n)?Number(n):n==="true"||n==="True"?!0:n==="false"||n==="False"?!1:n==="null"||n==="None"?null:n}function Kt(e){const n={};for(const t of Gt(e)){const r=t.indexOf("=");if(r<=0)throw new Error(`Expected key=value argument, received "${t}".`);const i=t.slice(0,r).trim();if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(i))throw new Error(`Invalid argument name "${i}".`);n[i]=Rt(t.slice(r+1))}return n}function Vt(e){const t=e.trim().match(/^([a-z_]+)\(([\s\S]*)\)$/);if(!t)return{message:'Action plan actions must be JSON objects like { "tool": "create_cms_page", "input": { ... } }, not freeform text.',success:!1};const r=t[1];let i;try{i=Kt(t[2])}catch(l){return{message:l instanceof Error?l.message:"Could not parse action-plan command arguments.",success:!1}}const a={input:i,tool:r},s=at.safeParse(a);return s.success?{action:s.data,success:!0}:{message:`Invalid action-plan command "${r}": ${s.error.issues.map(l=>l.message).join("; ")}`,success:!1}}function Jt(e){return e.normalize("NFD").replace(/[\u0300-\u036f]/g,"").toLowerCase().replace(/\s+/g," ").trim()}function oe(e,n){return n.some(t=>e.includes(t))}function Wt(e){const n=Jt(e),t=oe(n,["add ","insert ","put ","create "]),r=oe(n,["title","heading","description","intro","copy","paragraph"]),i=n.includes("form")&&oe(n,["above","before"]),a=n.includes("contact page")||n.includes("contact pages")||n.includes("contact us")||n.includes("contactez-nous"),s=n.includes("english")&&oe(n,["french","francais","francaise"]);return!t||!r||!i||!a||!s?null:{actions:[{input:{anchorBlockType:"form",block:{blockType:"text",content:{html_content:"<h2>Let us help you move faster</h2><p>Have a question, project idea, or need help choosing the right next step? Send us a message and the NextBlock team will get back to you soon.</p>"}},contentType:"page",position:"before",slug:"contact-us"},tool:"insert_content_block"},{input:{anchorBlockType:"form",block:{blockType:"text",content:{html_content:"<h2>Parlons de votre projet</h2><p>Vous avez une question, une idee de projet ou besoin d'aide pour avancer? Envoyez-nous un message et l'equipe NextBlock vous repondra rapidement.</p>"}},contentType:"page",position:"before",slug:"contactez-nous"},tool:"insert_content_block"}],summary:"Add visible title and description copy above the forms on the English and French Contact pages."}}const Ht=o.z.enum(N),Qe=o.z.object({direction:o.z.string().optional(),stops:o.z.array(o.z.object({color:o.z.string(),position:o.z.number()})),type:o.z.enum(["linear","radial"])}),Yt=o.z.object({gradient:Qe.optional(),image:o.z.object({alt_text:o.z.string().optional(),blur_data_url:o.z.string().optional(),height:o.z.number().optional(),media_id:o.z.string(),object_key:o.z.string(),overlay:o.z.object({gradient:Qe,type:o.z.literal("gradient")}).optional(),position:o.z.enum(["center","top","bottom","left","right"]),quality:o.z.number().nullable().optional(),size:o.z.enum(["cover","contain"]),width:o.z.number().optional()}).optional(),min_height:o.z.string().optional(),solid_color:o.z.string().optional(),theme:o.z.enum(["primary","secondary","muted","accent","destructive"]).optional(),type:o.z.enum(["none","theme","solid","gradient","image"])}),Qt=o.z.object({block_type:Ht,content:o.z.record(o.z.string(),o.z.any()),temp_id:o.z.string().optional()}),Xt=o.z.object({background:Yt,column_blocks:o.z.array(o.z.array(Qt)),column_gap:o.z.enum(["none","sm","md","lg","xl"]),container_type:o.z.enum(["full-width","container","container-sm","container-lg","container-xl"]),padding:o.z.object({bottom:o.z.enum(["none","sm","md","lg","xl"]),top:o.z.enum(["none","sm","md","lg","xl"])}),responsive_columns:o.z.object({desktop:o.z.union([o.z.literal(1),o.z.literal(2),o.z.literal(3),o.z.literal(4)]),mobile:o.z.union([o.z.literal(1),o.z.literal(2)]),tablet:o.z.union([o.z.literal(1),o.z.literal(2),o.z.literal(3)])}),vertical_alignment:o.z.enum(["start","center","end","stretch"]).optional()}),Zt={button:o.z.object({position:o.z.enum(["left","center","right"]).optional(),size:o.z.enum(["default","sm","lg","full"]).optional(),text:o.z.string(),url:o.z.string(),variant:o.z.enum(["default","outline","secondary","ghost","link"]).optional()}),cart:o.z.object({}),checkout:o.z.object({}),featured_product:o.z.object({imagePosition:o.z.enum(["left","right"]).default("left"),productId:o.z.string().min(1),showBackground:o.z.boolean().default(!1)}),form:o.z.object({fields:o.z.array(o.z.object({field_type:o.z.enum(["text","email","textarea","select","radio","checkbox"]),is_required:o.z.boolean(),label:o.z.string(),options:o.z.array(o.z.object({label:o.z.string(),value:o.z.string()})).optional(),placeholder:o.z.string().optional(),temp_id:o.z.string()})),recipient_email:o.z.string().email(),submit_button_text:o.z.string(),success_message:o.z.string()}),heading:o.z.object({level:o.z.union([o.z.literal(1),o.z.literal(2),o.z.literal(3),o.z.literal(4),o.z.literal(5),o.z.literal(6)]),textAlign:o.z.enum(["left","center","right","justify"]).optional(),textColor:o.z.enum(["primary","secondary","accent","muted","destructive","background"]).optional(),text_content:o.z.string()}),image:o.z.object({alt_text:o.z.string().optional(),caption:o.z.string().optional(),height:o.z.number().nullable().optional(),media_id:o.z.string().nullable(),object_key:o.z.string().nullable().optional(),width:o.z.number().nullable().optional()}),posts_grid:o.z.object({columns:o.z.number().min(1).max(6),postsPerPage:o.z.number().min(1).max(50),showPagination:o.z.boolean(),title:o.z.string().optional()}),product_details:o.z.object({}),product_grid:o.z.object({categoryId:o.z.string().optional(),limit:o.z.number().min(1).max(20).default(6),title:o.z.string().optional(),type:o.z.enum(["latest","category"]).default("latest")}),section:Xt,testimonial:o.z.object({author_name:o.z.string().min(1),author_title:o.z.string().optional(),image_url:o.z.string().url().optional().or(o.z.literal("")),quote:o.z.string().min(1)}),text:o.z.object({html_content:o.z.string()}),video_embed:o.z.object({autoplay:o.z.boolean().optional(),controls:o.z.boolean().optional(),title:o.z.string().optional(),url:o.z.string()})};function en(e){return N.includes(e)}function tn(e){return typeof e?.validateBlockContent=="function"?e.validateBlockContent:null}function nn(e,n,t){const r=tn(t);if(r)return r(e,n);const i=Zt[e].safeParse(n);return i.success?{errors:[],isValid:!0,warnings:[]}:{errors:i.error.issues.map(a=>{const s=a.path.join(".");return s?`${s}: ${a.message}`:a.message}),isValid:!1,warnings:[]}}function on(){return o.z.object({content:o.z.array(o.z.any()).optional(),type:o.z.literal("doc")})}function Te(){try{const{revalidatePath:e}=require("next/cache");return e}catch{return null}}function y(e){if(!e?.supabase)throw new Error("A Supabase service client is required to execute Cortex AI global tools.");return e.supabase}function rn(e,n,t){let r;const i=new Promise(a=>{r=setTimeout(()=>a(t()),n)});return Promise.race([e.finally(()=>{r&&clearTimeout(r)}),i])}function me(e){const n=we.safeParse(e?.pageContext);if(!n.success)throw new Error("No current CMS page context is available. Open a page, post, or product edit screen before using this editing tool.");return n.data}function st(e){const n=typeof e.entityId=="number"?e.entityId:Number.parseInt(e.entityId,10);if(!Number.isInteger(n)||n<=0)throw new Error(`Current ${e.contentType} id must be a positive integer.`);return n}function an(e){const n=String(e.entityId||"").trim();if(!n)throw new Error(`Current ${e.contentType} id is missing.`);return n}function $e(e){return e.contentType==="product"?an(e):st(e)}function sn(e){return typeof e=="string"?e.trim().replace(/^\/+|\/+$/g,""):""}function ln(e,n){const t=sn(n??e.slug);return t?e.contentType==="page"?t==="home"?"/":`/${t}`:e.contentType==="post"?`/article/${t}`:`/product/${t}`:null}function cn(e){const n=String(e.entityId);return e.contentType==="page"?`/cms/pages/${n}/edit`:e.contentType==="post"?`/cms/posts/${n}/edit`:`/cms/products/${n}/edit`}function B(e,n,t){const r=e?.revalidatePath??Te();if(!r)return;r(cn(n));const i=ln(n,t);i&&r(i),n.contentType==="product"&&r("/cms/products")}function lt(e){const n=e?.revalidatePath??Te();n&&(n("/","layout"),n("/cms/navigation"))}function f(e){return e?typeof e=="object"&&"message"in e?String(e.message||"Unknown database error."):String(e):"Unknown database error."}async function ve(){return Promise.resolve().then(()=>require("./ai-global-agent-ecommerce.cjs.js"))}function fe(e){return e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?`[${e.map(n=>fe(n)).join(",")}]`:`{${Object.keys(e).filter(n=>n!=="temp_id").sort().map(n=>`${JSON.stringify(n)}:${fe(e[n])}`).join(",")}}`}function un(e){let n=2166136261;const t=fe(e);for(let r=0;r<t.length;r++)n^=t.charCodeAt(r),n=Math.imul(n,16777619);return(n>>>0).toString(16).padStart(8,"0")}function _e(e){return e.replace(/\s+/g," ").trim().toUpperCase()}function dn(e,n,t){return`${_e(`CONFIRM ${e} ${n}`)} #${un(t)}`}function ct(e){return{confirmationPhrase:dn(e.action,e.subject,e.payload),mutationExecuted:!1,preview:e.preview,requiresConfirmation:!0,success:!0}}function $(e,n){const t=e[n];return typeof t=="string"&&t.trim()?t.trim():null}function re(e,n){const t=Number(e[n]);return Number.isFinite(t)?t:null}function F(e,n,t=`${n}s`){return`${e} ${e===1?n:t}`}function pn(e,n){const t=$(n,"summary");if(t)return t;const r=$(n,"title"),i=$(n,"slug"),a=$(n,"status"),s=$(n,"contentType"),l=$(n,"field"),m=$(n,"mode"),u=$(n,"languageCode"),c=re(n,"blockCount"),d=re(n,"itemCount"),g=re(n,"affectedCount");if(e==="create_cms_page"||e==="create_cms_post")return`Create ${a||"draft"} ${e==="create_cms_page"?"page":"post"} "${r||i||"Untitled"}"${i?` at slug "${i}"`:""}${c!==null?` with ${F(c,"content block")}`:""}.`;if(e==="create_cms_product")return`Create ${a||"draft"} product "${r||i||"Untitled"}"${i?` at slug "${i}"`:""}.`;if(e==="update_cms_item_field")return`Update ${l||"one field"} on the ${s||"CMS item"} "${r||i||"selected item"}".`;if(e==="update_navigation_bar")return`${m==="append"?"Add":m==="update"?"Update":"Replace"} ${d!==null?F(d,"navigation item"):"navigation items"} in the ${u||"selected"} header navigation.`;if(e==="update_footer"){const p=re(n,"linkCount");return`Update the ${u||"selected"} footer${p!==null?` with ${F(p,"link")}`:""}.`}return e==="update_content_block"?`Update the selected ${$(n,"blockType")||"content"} block.`:e==="insert_content_block"?`Insert ${$(n,"blockType")||"content"} block on the ${s||"CMS item"} "${r||i||"selected item"}".`:e==="update_section_column_block"?`Update the selected nested ${$(n,"nestedBlockType")||"section"} block.`:e==="delete_cms_item"||e==="prepare_delete_cms_item"?`Delete ${g!==null?F(g,s||"CMS item"):`the selected ${s||"CMS item"}`}${r||i?` for "${r||i}"`:""}.`:"Complete the requested CMS change."}function x(e){if(e.context?.skipConfirmation)return null;const n=ct(e),t=_e(e.context?.latestUserMessage||""),r=_e(n.confirmationPhrase);return t.includes(r)?null:n}function ut(e){const n=e?.actorUserId;if(!n)throw new Error("A confirmed CMS mutation requires an authenticated admin actor.");return n}function Se(){return globalThis.crypto?.randomUUID?.()||`id-${Date.now()}-${Math.random().toString(36).slice(2)}`}function ge(e){return e.toLowerCase().trim().replace(/\s+/g,"-").replace(/[^a-z0-9-]/g,"").replace(/-+/g,"-").replace(/^-|-$/g,"").slice(0,300)}function Ee(e){return(e||"USD").trim().toUpperCase()}function Ae(e,n){const r=new Set(["BIF","CLP","DJF","GNF","JPY","KMF","KRW","MGA","PYG","RWF","UGX","VND","VUV","XAF","XOF","XPF"]).has(Ee(n))?0:2;return e/10**r}function mn(e,n){return typeof e=="number"&&Number.isFinite(e)?Ae(e,n):0}function Xe(e,n){return!e||typeof e!="object"||Array.isArray(e)?{}:Object.entries(e).reduce((t,[r,i])=>(typeof i=="number"&&Number.isFinite(i)&&(t[Ee(r||n)]=Ae(i,r||n)),t),{})}function ee(e,n){if(!L(e))throw new Error(`${n} content must be a JSON object.`);return JSON.parse(JSON.stringify(e))}function ae(e){return JSON.parse(JSON.stringify(e))}function L(e){return!!(e&&typeof e=="object"&&!Array.isArray(e))}function be(e,n){const t=ae(e);for(const[r,i]of Object.entries(n))if(i!==void 0){if(L(i)&&L(t[r])){t[r]=be(t[r],i);continue}t[r]=ae(i)}return t}function dt(e,n){if(n.contentType==="product")throw new Error("Products do not have page/post content blocks in this editor context.");const t=st(n);if((n.contentType==="page"?Number(e.page_id):Number(e.post_id))!==t)throw new Error(`Block ${e.id} does not belong to the current ${n.contentType} being edited.`)}function se(e,n){const t=typeof e=="string"?e:"";if(!en(t))throw new Error(`${n} has unsupported block type "${t||"unknown"}".`);return t}function pt(e,n,t){if(e&&e!==n)throw new Error(`${t} is a "${n}" block. Refusing to update it as "${e}".`)}function j(e,n,t,r){const i=nn(e,n,r);if(!i.isValid)throw new Error(`${t} content is invalid for block type "${e}": ${i.errors.join("; ")}`)}function mt(e){return e==="section"}function gn(e){return typeof e.html_content=="string"?"text":typeof e.text=="string"&&typeof e.url=="string"?"button":typeof e.text_content=="string"?"heading":"media_id"in e||"object_key"in e?"image":typeof e.quote=="string"&&typeof e.author_name=="string"?"testimonial":typeof e.url=="string"&&("controls"in e||"autoplay"in e||"title"in e)?"video_embed":Array.isArray(e.fields)||typeof e.recipient_email=="string"?"form":"postsPerPage"in e||"showPagination"in e?"posts_grid":typeof e.productId=="string"?"featured_product":"limit"in e&&"type"in e?"product_grid":null}function le(e){return`ai-${e}-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}function Ze(e,n,t){if(!L(e))throw new Error(`${n} must be a JSON object.`);const r=e.block_type??e.blockType,i=se(r,n);if(mt(i))throw new Error(`${n} cannot be a nested ${i} block.`);const a=bt(i,ee(e.content,n),n,t),s=e.temp_id??e.tempId,l=typeof s=="string"&&s.trim()?s:le(i);return{block_type:i,content:a,temp_id:l}}function fn(e,n){const t=[];if("append_block"in e&&t.push(Ze(e.append_block,"Nested block to append",n)),"append_blocks"in e){const r=e.append_blocks;if(!Array.isArray(r))throw new Error("append_blocks must be an array of nested block objects.");r.forEach((i,a)=>{t.push(Ze(i,`Nested block to append ${a}`,n))})}return t}function _n(e,n){if("append_block"in e||"append_blocks"in e||"background"in e||"column_blocks"in e||"column_gap"in e||"container_type"in e||"padding"in e||"responsive_columns"in e||"vertical_alignment"in e)return null;const t=gn(e);if(!t)return null;const r=ee(e,`Nested ${t} block`);return j(t,r,`Nested ${t} block`,n),{block_type:t,content:r,temp_id:le(t)}}function bn(e,n){const t=e.append_column_index??e.column_index;if(t===void 0)return 0;if(typeof t!="number"||!Number.isInteger(t)||t<0)throw new Error("append_column_index must be a non-negative integer.");if(n>0&&t>=n)throw new Error(`append_column_index ${t} is outside the existing ${n} column(s).`);return t}function hn(e,n,t,r){if(!mt(e))return be(n,t);const i={...t},a=fn(i,r),s=_n(i,r);s&&a.push(s),delete i.append_block,delete i.append_blocks,delete i.append_column_index,delete i.column_index;const l=be(n,i);if(a.length>0){const m=Array.isArray(n.column_blocks)?ae(n.column_blocks):[],u=bn(t,m.length),c=m.length>0?m:[[]];for(;c.length<=u;)c.push([]);c[u]=[...c[u]||[],...a],l.column_blocks=c}return l}function yn(e,n){return{blockType:e.block_type,content:n?e.content:void 0,id:e.id,languageId:e.language_id,order:e.order,pageId:e.page_id,postId:e.post_id}}function q(e){return typeof e=="string"?e.trim().toLowerCase():""}function et(e){return typeof e=="string"?e.trim().toLowerCase():""}function gt(e){return e.reduce((n,t)=>n+1+(t.children?.length||0),0)}function ie(e){return typeof e=="string"?e.trim().toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g,""):""}async function O(e,n){const t=n.trim(),r=ie(t),i=qt[r],{data:a,error:s}=await e.from("languages").select("id, code, name, is_active");if(s)throw new Error(`Failed to load language "${n}": ${f(s)}`);const m=(Array.isArray(a)?a:[]).filter(c=>c.is_active!==!1),u=m.find(c=>{const d=ie(c.code),g=ie(c.name);return d===r||d===i||g===r});if(!u?.id||!u?.code){const c=m.map(d=>d.code).filter(Boolean).join(", ");throw new Error(`Language "${n}" was not found.${c?` Available languages: ${c}.`:""}`)}return{code:String(u.code),id:Number(u.id)}}async function Pe(e,n){if(n)return O(e,n);const{data:t,error:r}=await e.from("languages").select("id, code, name, is_active, is_default");if(r)throw new Error(`Failed to load active languages: ${f(r)}`);const i=(Array.isArray(t)?t:[]).filter(s=>s.is_active!==!1),a=i.find(s=>s.is_default)||i.find(s=>ie(s.code)==="en")||i[0];if(!a?.id||!a?.code)throw new Error("No active CMS language is available for Cortex AI content creation.");return{code:String(a.code),id:Number(a.id)}}async function kn(e){try{const{data:n,error:t}=await e.from("currencies").select("code, is_default, is_active").eq("is_active",!0);if(t)return"USD";const r=Array.isArray(n)?n:[],i=r.find(a=>a.is_default)||r[0];return Ee(i?.code||"USD")}catch{return"USD"}}async function wn(e){const n=e.contentType==="page"?"pages":e.contentType==="post"?"posts":"products";let t="id",r=e.entityId;if(r===void 0&&e.slug&&(t="slug",r=e.slug),r===void 0&&e.title&&(t="title",r=e.title),r===void 0)throw new Error(`A ${e.contentType} target requires an id, slug, title, or current edit context.`);const{data:i,error:a}=await e.supabase.from(n).select("*").eq(t,r);if(a)throw new Error(`Failed to resolve ${e.contentType}: ${f(a)}`);const s=Array.isArray(i)?i:i?[i]:[];if(s.length!==1)throw new Error(s.length===0?`No ${e.contentType} matched ${t} "${String(r)}".`:`Multiple ${e.contentType}s matched ${t} "${String(r)}"; use an exact id.`);return s[0]}async function Be(e,n){const t=we.safeParse(n?.pageContext).success?n?.pageContext:null,r=e.contentType||t?.contentType;if(!r)throw new Error("Target contentType is required when no current CMS edit context exists.");const i=e.entityId!==void 0||!!e.slug||!!e.title,a=e.entityId??(i?void 0:t?.entityId),s=e.slug??(i?void 0:t?.slug??void 0),l=e.title??(i?void 0:t?.title??void 0),m=await wn({contentType:r,entityId:a,slug:a===void 0&&s||void 0,supabase:y(n),title:a===void 0&&!s&&l||void 0});return{contentType:r,item:m}}async function ce(e){const n=await In({item:e.item,languageId:e.languageId,menuKey:e.menuKey,supabase:e.supabase}),t={label:e.item.label,language_id:e.languageId,menu_key:e.menuKey,order:e.order,page_id:n?.pageId??null,parent_id:e.parentId??null,...n?.navigationTranslationGroupId?{translation_group_id:n.navigationTranslationGroupId}:{},url:e.item.url},{data:r,error:i}=await e.supabase.from("navigation_items").insert(t).select("id").single();if(i)throw new Error(`Failed to insert ${e.menuKey} navigation item: ${f(i)}`);return Number(r.id)}function zn(e){const n=e.trim();if(!n.startsWith("/")||n.startsWith("//"))return null;const t=n.split("?")[0]?.split("#")[0]||"",r=t==="/"?"home":t.replace(/^\/+|\/+$/g,"");return r&&!r.includes("/")?r:null}async function In(e){const n=zn(e.item.url);if(!n)return null;const{data:t,error:r}=await e.supabase.from("pages").select("id, slug, translation_group_id, language_id").eq("slug",n).eq("language_id",e.languageId);if(r)throw new Error(`Failed to resolve linked page for navigation item: ${f(r)}`);const i=Array.isArray(t)?t[0]:t;if(!i?.id)return null;let a=Se();if(i.translation_group_id){const{data:s,error:l}=await e.supabase.from("pages").select("id").eq("translation_group_id",i.translation_group_id);if(l)throw new Error(`Failed to inspect linked page translations for navigation item: ${f(l)}`);const m=new Set((Array.isArray(s)?s:[]).map(g=>String(g.id)).filter(Boolean)),{data:u,error:c}=await e.supabase.from("navigation_items").select("id, page_id, translation_group_id, menu_key").eq("menu_key",e.menuKey);if(c)throw new Error(`Failed to inspect related navigation translations: ${f(c)}`);const d=(Array.isArray(u)?u:[]).find(g=>g.translation_group_id&&m.has(String(g.page_id)));d?.translation_group_id&&(a=d.translation_group_id)}return{navigationTranslationGroupId:a,pageId:Number(i.id)}}async function ft(e){const n=await O(e.supabase,e.languageCode),{data:t,error:r}=await e.supabase.from("navigation_items").select("id, parent_id").eq("menu_key",e.menuKey).eq("language_id",n.id);if(r)throw new Error(`Failed to inspect existing ${e.menuKey} navigation items: ${f(r)}`);const i=Array.isArray(t)?t:[],a=i.filter(u=>u.parent_id==null).length,s=gt(e.items);_t({existingItemCount:i.length,existingTopLevelCount:a,languageCode:n.code,menuKey:e.menuKey,replacementItemCount:s});const{error:l}=await e.supabase.from("navigation_items").delete().eq("menu_key",e.menuKey).eq("language_id",n.id);if(l)throw new Error(`Failed to clear ${e.menuKey} navigation items: ${f(l)}`);let m=0;for(const[u,c]of e.items.entries()){const d=await ce({item:c,languageId:n.id,menuKey:e.menuKey,order:u,supabase:e.supabase});m++;for(const[g,p]of(c.children??[]).entries())await ce({item:p,languageId:n.id,menuKey:e.menuKey,order:g,parentId:d,supabase:e.supabase}),m++}return{insertedCount:m,languageCode:n.code,menuKey:e.menuKey,skippedCount:0,updatedCount:0}}function _t(e){if(!(e.existingItemCount===0||e.replacementItemCount>=e.existingItemCount))throw new Error(`Refusing destructive ${e.menuKey} navigation replacement for ${e.languageCode}: existing menu has ${e.existingItemCount} items (${e.existingTopLevelCount} top-level), but the replacement only contains ${e.replacementItemCount}. Use mode "update" for renaming or changing a single link, or provide the full menu.`)}async function Cn(e){const n=await O(e.supabase,e.languageCode),{data:t,error:r}=await e.supabase.from("navigation_items").select("id, parent_id").eq("menu_key",e.menuKey).eq("language_id",n.id);if(r)throw new Error(`Failed to inspect existing ${e.menuKey} navigation items: ${f(r)}`);const i=Array.isArray(t)?t:[];_t({existingItemCount:i.length,existingTopLevelCount:i.filter(a=>a.parent_id==null).length,languageCode:n.code,menuKey:e.menuKey,replacementItemCount:gt(e.items)})}async function xn(e){if(e.items.length!==1)throw new Error('mode "update" requires exactly one navigation item.');const n=await O(e.supabase,e.languageCode),t=e.items[0],r=q(e.match?.url)||q(t.url),i=et(e.match?.label),{data:a,error:s}=await e.supabase.from("navigation_items").select("id, label, url, parent_id, order").eq("menu_key",e.menuKey).eq("language_id",n.id);if(s)throw new Error(`Failed to load existing ${e.menuKey} navigation items: ${f(s)}`);const m=(Array.isArray(a)?a:[]).find(c=>{const d=q(c.url),g=et(c.label);return!!(r&&d===r||i&&g===i)});if(!m?.id)throw new Error(`Could not find a ${e.menuKey} navigation item to update in ${n.code}. Use a matching label or url.`);const{error:u}=await e.supabase.from("navigation_items").update({label:t.label,url:t.url}).eq("id",m.id);if(u)throw new Error(`Failed to update ${e.menuKey} navigation item: ${f(u)}`);return{insertedCount:0,languageCode:n.code,menuKey:e.menuKey,skippedCount:0,updatedCount:1}}async function Tn(e){const n=await O(e.supabase,e.languageCode),{data:t,error:r}=await e.supabase.from("navigation_items").select("id, url, parent_id, order").eq("menu_key",e.menuKey).eq("language_id",n.id);if(r)throw new Error(`Failed to load existing ${e.menuKey} navigation items: ${f(r)}`);let i=0,a=0;const s=Array.isArray(t)?t:[],l=new Set(s.map(c=>q(c.url)).filter(Boolean)),m=s.filter(c=>c.parent_id==null).map(c=>Number(c.order)).filter(Number.isFinite);let u=m.length>0?Math.max(...m)+1:s.length;for(const c of e.items){const d=q(c.url);if(d&&l.has(d)){a++;continue}const g=await ce({item:c,languageId:n.id,menuKey:e.menuKey,order:u,supabase:e.supabase});i++,u++,d&&l.add(d);let p=0;for(const _ of c.children??[]){const k=q(_.url);if(k&&l.has(k)){a++;continue}await ce({item:_,languageId:n.id,menuKey:e.menuKey,order:p,parentId:g,supabase:e.supabase}),i++,p++,k&&l.add(k)}}return{insertedCount:i,languageCode:n.code,menuKey:e.menuKey,skippedCount:a,updatedCount:0}}function b(e){return typeof e=="string"&&e.trim()?e.trim():""}function $n(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function vn(e){const n=b(e.field_type??e.fieldType??e.type??e.input_type).toLowerCase().replace(/\s+/g,"_"),t=b(e.label??e.name??e.placeholder).toLowerCase();return["email","textarea","select","radio","checkbox","text"].includes(n)?n:t.includes("email")?"email":t.includes("message")||t.includes("comment")||t.includes("details")?"textarea":"text"}function Sn(e){return(Array.isArray(e)&&e.length>0?e:[{field_type:"text",is_required:!0,label:"Name",placeholder:"Your name"},{field_type:"email",is_required:!0,label:"Email",placeholder:"you@example.com"},{field_type:"textarea",is_required:!0,label:"Message",placeholder:"How can we help?"}]).map((t,r)=>{const i=L(t)?t:{},a=b(i.label??i.name)||(r===0?"Name":r===1?"Email":"Message"),s=vn({...i,label:a}),l=i.is_required??i.isRequired??i.required;return{field_type:s,is_required:typeof l=="boolean"?l:!0,label:a,options:Array.isArray(i.options)?i.options:void 0,placeholder:b(i.placeholder)||void 0,temp_id:b(i.temp_id??i.tempId??i.id)||`field-${r+1}`}})}function bt(e,n,t,r){const i=ae(n);if(e==="heading"&&(i.text_content=b(i.text_content)||b(i.text)||b(i.title)||b(i.heading)||"Untitled",i.level=typeof i.level=="number"?i.level:1),e==="text"){const a=b(i.html_content)||b(i.html)||b(i.content)||b(i.text);a&&(i.html_content=/<\/?[a-z][\s\S]*>/i.test(a)?a:`<p>${$n(a)}</p>`)}return e==="button"&&(i.text=b(i.text)||b(i.label)||b(i.title)||"Learn More",i.url=b(i.url)||b(i.href)||b(i.link)||"#"),e==="form"&&(i.fields=Sn(i.fields),i.submit_button_text=b(i.submit_button_text??i.submitButtonText??i.button_text)||"Send Message",i.success_message=b(i.success_message??i.successMessage)||"Thanks for reaching out. We will reply as soon as possible."),j(e,i,t,r),i}function ue(e,n,t){const r=bt(e.blockType,ee(e.content,`Block ${n}`),`Block ${n}`,t);return{block_type:e.blockType,content:r,order:e.order??n}}function En(e,n="Contact Us",t){return[ue({blockType:"section",content:{is_hero:!0,background:{type:"none"},column_blocks:[[{block_type:"heading",content:{level:1,textAlign:"center",text_content:n},temp_id:le("heading")},{block_type:"text",content:{html_content:"<p>Have a question, project, or support request? Send us a note and we will get back to you soon.</p>"},temp_id:le("text")}]],column_gap:"lg",container_type:"container",padding:{bottom:"xl",top:"xl"},responsive_columns:{desktop:1,mobile:1,tablet:1},vertical_alignment:"center"}},0,t),ue({blockType:"form",content:{fields:[{field_type:"text",is_required:!0,label:"Name",placeholder:"Your name",temp_id:"field-name"},{field_type:"email",is_required:!0,label:"Email",placeholder:"you@example.com",temp_id:"field-email"},{field_type:"textarea",is_required:!0,label:"Message",placeholder:"How can we help?",temp_id:"field-message"}],recipient_email:e,submit_button_text:"Send Message",success_message:"Thanks for reaching out. We will reply as soon as possible."}},1,t)]}function ht(e,n,t,r){return(!e||e.length===0)&&n?En(n,t,r):(e||[]).map((i,a)=>ue(i,a,r))}async function Fe(e){const n=e.contentType==="page"?"pages":e.contentType==="post"?"posts":"products",{data:t,error:r}=await e.supabase.from(n).select("id, title, slug, language_id").eq("slug",e.slug).eq("language_id",e.languageId);if(r)throw new Error(`Failed to check ${e.contentType} slug uniqueness: ${f(r)}`);const i=Array.isArray(t)?t:[];return i.length>0?{duplicate:!0,existingItem:i[0],mutationExecuted:!1,success:!1,message:`A ${e.contentType} with slug "${e.slug}" already exists for this language.`}:null}async function Ne(e){if(!e.suppliedTranslationGroupId)return{translationGroupId:void 0};const n=e.contentType==="page"?"pages":e.contentType==="post"?"posts":"products",{data:t,error:r}=await e.supabase.from(n).select("id, title, slug, language_id, translation_group_id").eq("translation_group_id",e.suppliedTranslationGroupId);if(r)throw new Error(`Failed to inspect ${e.contentType} translation group: ${f(r)}`);const i=Array.isArray(t)?t:[];if(i.length===0)return{result:{message:`The ${e.contentType} translation group "${e.suppliedTranslationGroupId}" was not found.`,mutationExecuted:!1,success:!1},translationGroupId:e.suppliedTranslationGroupId};const a=i.find(s=>Number(s.language_id)===e.languageId);return a?{result:{duplicateTranslation:!0,existingItem:a,message:`A ${e.contentType} translation already exists for ${e.languageCode} in this translation group.`,mutationExecuted:!1,success:!1},translationGroupId:e.suppliedTranslationGroupId}:{translationGroupId:e.suppliedTranslationGroupId}}async function yt(e){if(e.blocks.length===0)return[];const n=e.blocks.map((i,a)=>({block_type:i.block_type,content:i.content,language_id:e.languageId,order:i.order??a,page_id:e.contentType==="page"?e.itemId:null,post_id:e.contentType==="post"?e.itemId:null})),{data:t,error:r}=await e.supabase.from("blocks").insert(n).select("*");if(r)throw new Error(`Failed to insert ${e.contentType} blocks: ${f(r)}`);return Array.isArray(t)?t:[]}async function kt(e){const n=e.contentType==="page"?"pages":"posts";await e.supabase.from(n).delete().eq("id",e.itemId)}function je(e,n){return e==="page"?`/cms/pages/${n}/edit`:e==="post"?`/cms/posts/${n}/edit`:`/cms/products/${n}/edit`}function tt(e){return e==="page"?"/cms/pages":e==="post"?"/cms/posts":"/cms/products"}async function qe(e,n){const t=G.parse(e),r=y(n);t.mode==="replace"&&await Cn({items:t.items,languageCode:t.languageCode,menuKey:"HEADER",supabase:r});const i=x({action:"UPDATE NAVIGATION",context:n,payload:{input:t,tool:"update_navigation_bar"},preview:{itemCount:t.items.length,languageCode:t.languageCode,mode:t.mode,target:"header navigation"},subject:`${t.mode} header`});if(i)return i;const a=t.mode==="update"?await xn({items:t.items,languageCode:t.languageCode,match:t.match,menuKey:"HEADER",supabase:r}):t.mode==="append"?await Tn({items:t.items,languageCode:t.languageCode,menuKey:"HEADER",supabase:r}):await ft({items:t.items,languageCode:t.languageCode,menuKey:"HEADER",supabase:r});return lt(n),{...a,mutationExecuted:!0,mode:t.mode,success:!0}}async function Oe(e,n){const t=R.parse(e);if(!t.links?.length&&!t.copyright)throw new Error("update_footer requires links or copyright.");const r=y(n),i=x({action:"UPDATE FOOTER",context:n,payload:{input:t,tool:"update_footer"},preview:{copyrightUpdated:!!t.copyright,linkCount:t.links?.length||0,languageCode:t.languageCode,target:"footer"},subject:t.languageCode});if(i)return i;let a=null;if(t.links?.length&&(a=await ft({items:t.links,languageCode:t.languageCode,menuKey:"FOOTER",supabase:r})),t.copyright){const{error:s}=await r.from("site_settings").upsert({key:"footer_copyright",value:t.copyright});if(s)throw new Error(`Failed to update footer copyright: ${f(s)}`)}return lt(n),{copyrightUpdated:!!t.copyright,footerNavigation:a,mutationExecuted:!0,success:!0}}function wt(e){return typeof e=="string"?e.toLowerCase():""}function An(e,n){const t=n.map(wt).join(" ");return e.reduce((r,i)=>r+(t.includes(i)?1:0),0)}function nt(e,n){return(e.find(t=>n.some(r=>wt(t).includes(r)))||e.find(t=>t.trim().length>0)||"No excerpt available.").slice(0,500)}async function zt(e,n){const t=de.parse(e),r=y(n),i=t.query.toLowerCase().split(/\s+/).map(c=>c.trim()).filter(Boolean),[a,s]=await Promise.all([r.from("posts").select("id, title, slug, excerpt, subtitle, meta_description, status, updated_at").eq("status","published").limit(100),r.from("pages").select("id, title, slug, meta_description, status, updated_at").eq("status","published").limit(100)]);if(a.error)throw new Error(`Failed to search documentation posts: ${f(a.error)}`);if(s.error)throw new Error(`Failed to search documentation pages: ${f(s.error)}`);const l=(a.data??[]).map(c=>({excerpt:nt([c.excerpt,c.subtitle,c.meta_description,c.slug].filter(Boolean),i),source:"post",title:c.title,url:`/article/${c.slug}`})),m=(s.data??[]).map(c=>({excerpt:nt([c.meta_description,c.slug].filter(Boolean),i),source:"page",title:c.title,url:c.slug==="home"?"/":`/${c.slug}`})),u=[...l,...m].map(c=>({...c,score:An(i,[c.title,c.excerpt,c.url])})).filter(c=>c.score>0).sort((c,d)=>d.score-c.score).slice(0,t.limit).map(c=>({excerpt:c.excerpt,source:c.source,title:c.title,url:c.url}));return{query:t.query,results:u,success:!0}}async function It(e,n,t=jt){const r=de.safeParse(e),i=r.success?r.data.query:"";return rn(zt(e,n),t,()=>({message:"Documentation search took too long to respond. Please try again or ask a more specific question.",query:i,results:[],success:!1,timedOut:!0}))}const Pn=["pending","trial","paid","shipped","cancelled","refunded","failed"],Bn={awaiting:"pending",canceled:"cancelled",cancelled:"cancelled",complete:"paid",completed:"paid",failed:"failed",paid:"paid",payment_pending:"pending",pending:"pending",refund:"refunded",refunded:"refunded",refunds:"refunded",shipped:"shipped",trial:"trial",trials:"trial"};function Fn(e){return String(e??"unknown").trim().toLowerCase()||"unknown"}function ot(e){const n=Object.fromEntries(Pn.map(t=>[t,0]));for(const t of e){const r=Fn(t.status);n[r]=(n[r]??0)+1}return n}function Nn(e){const t=e.toLowerCase().replace(/[^a-z0-9_]+/g," ").split(/\s+/).filter(Boolean);for(const r of t){const i=Bn[r];if(i)return i}return null}function M(e){const n=Number(e);return Number.isFinite(n)?n:0}async function Ct(e,n){const t=ke.parse(e),r=y(n),i=new Date;let a=null,s=null;switch(t.timeRange){case"today":a=new Date(i.getFullYear(),i.getMonth(),i.getDate());break;case"this_month":a=new Date(i.getFullYear(),i.getMonth(),1);break;case"last_7_days":a=new Date(i.getTime()-10080*60*1e3);break;case"last_30_days":a=new Date(i.getTime()-720*60*60*1e3);break;case"last_month":a=new Date(i.getFullYear(),i.getMonth()-1,1),s=new Date(i.getFullYear(),i.getMonth(),0,23,59,59,999);break;case"last_90_days":a=new Date(i.getTime()-2160*60*60*1e3);break;case"all_time":a=null;break}const l=t.currency?.toUpperCase(),m=Nn(t.query),u=r.from("orders").select("id, status, total, currency, created_at, paid_at");l&&u.eq("currency",l),a&&u.gte("created_at",a.toISOString()),s&&u.lte("created_at",s.toISOString());const d=t.reportType==="products"||t.reportType==="revenue"||t.reportType==="general"?r.from("order_items").select(`
2
+ quantity,
3
+ price_at_purchase,
4
+ products!inner (
5
+ id,
6
+ title,
7
+ product_type
8
+ ),
9
+ orders!inner (
10
+ id,
11
+ status,
12
+ paid_at,
13
+ currency
14
+ )
15
+ `).eq("orders.status","paid"):null;d&&(l&&d.eq("orders.currency",l),a&&d.gte("orders.paid_at",a.toISOString()),s&&d.lte("orders.paid_at",s.toISOString()));const p=t.timeRange!=="all_time"&&(t.reportType==="orders"||m)?r.from("orders").select("id, status, currency"):null;p&&l&&p.eq("currency",l);const[{data:_,error:k},{data:S,error:v},E]=await Promise.all([u,d??Promise.resolve({data:[],error:null}),p??Promise.resolve({data:null,error:null})]);if(k)throw new Error(`Failed to fetch ecommerce stats: ${f(k)}`);if(v)throw new Error(`Failed to fetch ecommerce stats: ${f(v)}`);if(E.error)throw new Error(`Failed to fetch ecommerce stats: ${f(E.error)}`);const h=Array.isArray(_)?_:[],z=Array.isArray(S)?S:[],A=ot(h),T=Array.isArray(E.data)?E.data:null,U=T?ot(T):null,te={};for(const I of z){const C=Array.isArray(I.orders)?I.orders[0]:I.orders,P=String(C?.currency||l||"unknown").toUpperCase();te[P]=(te[P]??0)+M(I.quantity)*M(I.price_at_purchase)/100}const ne={currency:l??null,currencyFiltered:!!l,orderStatusCounts:A,paidOrderCount:A.paid??0,query:t.query,reportType:t.reportType,revenueByCurrency:te,timeRange:t.timeRange,totalOrders:h.length,totalRevenue:Object.values(te).reduce((I,C)=>I+C,0)};if(U&&(ne.allTimeOrderStatusCounts=U),m&&(ne.matchingOrderStatus={allTimeCount:U?.[m]??A[m]??0,count:A[m]??0,status:m,timeRange:t.timeRange}),t.reportType==="products"||t.reportType==="revenue"||t.reportType==="general"){const I={};for(const C of z){const P=Array.isArray(C.products)?C.products[0]:C.products;if(!P?.id)continue;const D=P.id;I[D]||(I[D]={id:D,quantity:0,revenue:0,title:P.title,type:P.product_type}),I[D].quantity+=M(C.quantity),I[D].revenue+=M(C.quantity)*M(C.price_at_purchase)/100}ne.topProducts=Object.values(I).sort((C,P)=>P.revenue-C.revenue).slice(0,10)}return{report:ne,success:!0}}async function xt(e,n){const t=ze.parse(e),r=y(n),i=me(n),a=$e(i),s=i.contentType==="page"?"pages":i.contentType==="post"?"posts":"products",{data:l,error:m}=await r.from(s).select("*").eq("id",a).single();if(m||!l)throw new Error(`Failed to read current ${i.contentType}: ${f(m)}`);let u=[];if(t.includeBlocks&&i.contentType!=="product"){const c=i.contentType==="page"?"page_id":"post_id",{data:d,error:g}=await r.from("blocks").select("id, page_id, post_id, language_id, block_type, content, order").eq(c,a);if(g)throw new Error(`Failed to read current ${i.contentType} blocks: ${f(g)}`);u=(Array.isArray(d)?d:[]).slice().sort((p,_)=>Number(p.order)-Number(_.order)).map(p=>yn(p,t.includeBlockContent))}return{blocks:u,context:i,item:l,success:!0}}const Tt=new Set(["feature_image_id","language_id","meta_description","meta_title","slug","status","title"]),$t=new Set(["excerpt","feature_image_id","label","language_id","meta_description","meta_title","published_at","slug","status","subtitle","title"]),jn=new Set(["description_json","language_id","meta_description","meta_title","short_description","slug","status","title"]),qn=new Set(["excerpt","feature_image_id","label","meta_description","meta_title","published_at","short_description","subtitle"]);function On(e){return e==="page"?Tt:e==="post"?$t:jn}function vt(e,n){return qn.has(e)&&n===""?null:n}function he(e,n){if(typeof n!="string")return;const t=e==="product"?["active","archived","draft"]:["archived","draft","published"];if(!t.includes(n))throw new Error(`Status "${n}" is not valid for ${e}. Allowed statuses: ${t.join(", ")}.`)}function Un(e,n){const t=On(n.contentType),r={};for(const[i,a]of Object.entries(e))if(a!==void 0){if(!t.has(i))throw new Error(`Field "${i}" cannot be updated for ${n.contentType} content.`);i==="status"&&he(n.contentType,a),r[i]=vt(i,a)}return r}async function Ue(e,n){const t=K.parse(e),r=y(n),i=me(n),a=$e(i),s=Un(t.fields,i),l=Object.keys(s);if(l.length===0)throw new Error("update_current_cms_fields requires at least one supported field.");const m=x({action:"UPDATE CMS FIELDS",context:n,payload:{contentType:i.contentType,entityId:a,fields:s,tool:"update_current_cms_fields"},preview:{contentType:i.contentType,entityId:a,fields:l,slug:i.slug,title:i.title},subject:`${i.contentType} ${String(a)}`});if(m)return m;const u=i.contentType==="page"?"pages":i.contentType==="post"?"posts":"products",{data:c,error:d}=await r.from(u).update({...s,updated_at:new Date().toISOString()}).eq("id",a).select("id, language_id, slug, status, title").single();if(d||!c)throw new Error(`Failed to update current ${i.contentType}: ${f(d)}`);return B(n,i,c.slug),{contentType:i.contentType,entityId:a,mutationExecuted:!0,slug:c.slug,success:!0,updatedFields:l}}async function De(e,n){const t=V.parse(e),r=y(n),i=me(n),{data:a,error:s}=await r.from("blocks").select("id, page_id, post_id, language_id, block_type, content, order").eq("id",t.blockId).single();if(s||!a)throw new Error(`Failed to read block ${t.blockId}: ${f(s)}`);dt(a,i);const l=se(a.block_type,`Block ${t.blockId}`);pt(t.blockType,l,`Block ${t.blockId}`);const m=ee(a.content,`Block ${t.blockId}`),u=hn(l,m,t.content,n);j(l,u,`Block ${t.blockId}`,n);const c=x({action:"UPDATE CONTENT BLOCK",context:n,payload:{blockId:t.blockId,blockType:l,content:u,tool:"update_content_block"},preview:{blockId:t.blockId,blockType:l,contentType:i.contentType,entityId:$e(i)},subject:`${l} block ${t.blockId}`});if(c)return c;const{data:d,error:g}=await r.from("blocks").update({content:u,updated_at:new Date().toISOString()}).eq("id",t.blockId).select("id, block_type, order").single();if(g||!d)throw new Error(`Failed to update block ${t.blockId}: ${f(g)}`);return B(n,i),{blockId:d.id,blockType:d.block_type,contentUpdated:!0,mutationExecuted:!0,success:!0}}async function Me(e,n){const t=W.parse(e),r=y(n),i=await Be(t,n);if(i.contentType==="product")throw new Error("Products do not have page/post content blocks in this editor context.");const a=Number(i.item.id),s=i.contentType==="page"?"page_id":"post_id",l=async()=>{const{data:h,error:z}=await r.from("blocks").select("id, page_id, post_id, language_id, block_type, content, order").eq(s,a);if(z)throw new Error(`Failed to read ${i.contentType} blocks: ${f(z)}`);return(Array.isArray(h)?h:[]).sort((A,T)=>Number(A.order)-Number(T.order))},m=h=>{if(t.position==="start")return 0;if(t.position==="end"){const T=h.map(U=>Number(U.order)).filter(Number.isFinite);return T.length>0?Math.max(...T)+1:0}const z=t.anchorBlockId?h.find(T=>Number(T.id)===t.anchorBlockId):t.anchorBlockType?h.find(T=>T.block_type===t.anchorBlockType):null;if(!z)throw new Error(t.anchorBlockType?`Could not find a ${t.anchorBlockType} block to insert ${t.position}.`:`Could not find block ${t.anchorBlockId} to insert ${t.position}.`);const A=Number(z.order);return t.position==="before"?A:A+1},u=ue(t.block,0,n),c=await l(),d=m(c),g={contentType:i.contentType,entityId:i.item.id,languageId:i.item.language_id,slug:i.item.slug,title:i.item.title,translationGroupId:i.item.translation_group_id},p=x({action:"INSERT CONTENT BLOCK",context:n,payload:{block:u,order:d,target:{contentType:i.contentType,id:i.item.id,slug:i.item.slug},tool:"insert_content_block"},preview:{anchorBlockId:t.anchorBlockId,anchorBlockType:t.anchorBlockType,blockType:u.block_type,contentType:i.contentType,entityId:i.item.id,position:t.position,slug:i.item.slug,summary:`Insert ${u.block_type} block ${t.position} ${t.anchorBlockType?`the first ${t.anchorBlockType} block`:t.anchorBlockId?`block ${t.anchorBlockId}`:"the content"} on ${i.contentType} "${i.item.title||i.item.slug}".`,title:i.item.title},subject:`${u.block_type} block on ${i.contentType} ${i.item.id}`});if(p)return p;const _=await l(),k=m(_),S=_.filter(h=>Number(h.order)>=k).sort((h,z)=>Number(z.order)-Number(h.order));for(const h of S){const{error:z}=await r.from("blocks").update({order:Number(h.order)+1,updated_at:new Date().toISOString()}).eq("id",h.id);if(z)throw new Error(`Failed to shift block ${h.id}: ${f(z)}`)}const{data:v,error:E}=await r.from("blocks").insert({block_type:u.block_type,content:u.content,language_id:i.item.language_id,order:k,page_id:i.contentType==="page"?a:null,post_id:i.contentType==="post"?a:null}).select("id, block_type, order").single();if(E||!v)throw new Error(`Failed to insert content block: ${f(E)}`);return B(n,g),{blockId:v.id,blockType:v.block_type,contentType:i.contentType,entityId:i.item.id,mutationExecuted:!0,order:v.order,success:!0}}async function Le(e,n){const t=J.parse(e),r=y(n),i=me(n),{data:a,error:s}=await r.from("blocks").select("id, page_id, post_id, language_id, block_type, content, order").eq("id",t.parentBlockId).single();if(s||!a)throw new Error(`Failed to read parent block ${t.parentBlockId}: ${f(s)}`);dt(a,i);const l=se(a.block_type,`Parent block ${t.parentBlockId}`);if(l!=="section")throw new Error(`Parent block ${t.parentBlockId} must be a section block, not "${l}".`);const m=ee(a.content,`Parent block ${t.parentBlockId}`);j(l,m,`Parent block ${t.parentBlockId}`,n);const c=m.column_blocks?.[t.columnIndex]?.[t.blockIndex];if(!c)throw new Error(`Nested block was not found at column ${t.columnIndex}, index ${t.blockIndex}.`);const d=se(c.block_type,`Nested block ${t.columnIndex}:${t.blockIndex}`);pt(t.blockType,d,`Nested block ${t.columnIndex}:${t.blockIndex}`),j(d,t.content,`Nested block ${t.columnIndex}:${t.blockIndex}`,n);const g=m.column_blocks.map((v,E)=>E===t.columnIndex?v.map((h,z)=>z===t.blockIndex?{...h,content:t.content}:h):v),p={...m,column_blocks:g};j(l,p,`Updated parent block ${t.parentBlockId}`,n);const _=x({action:"UPDATE NESTED BLOCK",context:n,payload:{blockIndex:t.blockIndex,columnIndex:t.columnIndex,content:t.content,nestedBlockType:d,parentBlockId:t.parentBlockId,tool:"update_section_column_block"},preview:{blockIndex:t.blockIndex,columnIndex:t.columnIndex,nestedBlockType:d,parentBlockId:t.parentBlockId,parentBlockType:l},subject:`${d} nested block ${t.columnIndex}:${t.blockIndex}`});if(_)return _;const{data:k,error:S}=await r.from("blocks").update({content:p,updated_at:new Date().toISOString()}).eq("id",t.parentBlockId).select("id, block_type").single();if(S||!k)throw new Error(`Failed to update parent block ${t.parentBlockId}: ${f(S)}`);return B(n,i),{blockIndex:t.blockIndex,columnIndex:t.columnIndex,mutationExecuted:!0,nestedBlockType:d,parentBlockId:k.id,parentBlockType:k.block_type,success:!0}}async function Ge(e,n){const t=H.parse(e),r=y(n),i=ut(n),a=await Pe(r,t.languageCode),s=ge(t.slug||t.title),l=ht(t.blocks,t.contactEmail,t.title,n),m=await Fe({contentType:"page",languageId:a.id,slug:s,supabase:r});if(m)return m;const u=await Ne({contentType:"page",languageCode:a.code,languageId:a.id,suppliedTranslationGroupId:t.translationGroupId,supabase:r});if(u.result)return u.result;const c={blocks:l,item:{feature_image_id:t.feature_image_id??null,language_id:a.id,meta_description:t.meta_description??null,meta_title:t.meta_title??null,slug:s,status:t.status,title:t.title,translation_group_id:u.translationGroupId},tool:"create_cms_page"},d=x({action:"CREATE PAGE",context:n,payload:c,preview:{blockCount:l.length,languageCode:a.code,slug:s,status:t.status,title:t.title,translationGroupId:u.translationGroupId},subject:s});if(d)return d;const g=u.translationGroupId||Se(),{data:p,error:_}=await r.from("pages").insert({...c.item,author_id:i,translation_group_id:g}).select("id, language_id, slug, status, title, translation_group_id").single();if(_||!p?.id)throw new Error(`Failed to create page: ${f(_)}`);try{await yt({blocks:l,contentType:"page",itemId:Number(p.id),languageId:a.id,supabase:r})}catch(k){throw await kt({contentType:"page",itemId:Number(p.id),supabase:r}),k}return B(n,{contentType:"page",entityId:Number(p.id),languageId:a.id,slug:s,title:t.title},s),n?.revalidatePath?.("/cms/pages"),{blockCount:l.length,contentType:"page",editPath:je("page",p.id),entityId:p.id,mutationExecuted:!0,slug:s,success:!0,title:t.title,translationGroupId:p.translation_group_id}}async function Re(e,n){const t=Y.parse(e),r=y(n),i=ut(n),a=await Pe(r,t.languageCode),s=ge(t.slug||t.title),l=ht(t.blocks,void 0,void 0,n),m=await Fe({contentType:"post",languageId:a.id,slug:s,supabase:r});if(m)return m;const u=await Ne({contentType:"post",languageCode:a.code,languageId:a.id,suppliedTranslationGroupId:t.translationGroupId,supabase:r});if(u.result)return u.result;const c=t.published_at&&!Number.isNaN(new Date(t.published_at).getTime())?new Date(t.published_at).toISOString():t.published_at??null,d={blocks:l,item:{excerpt:t.excerpt??null,feature_image_id:t.feature_image_id??null,label:t.label??null,language_id:a.id,meta_description:t.meta_description??null,meta_title:t.meta_title??null,published_at:c,slug:s,status:t.status,subtitle:t.subtitle??null,title:t.title,translation_group_id:u.translationGroupId},tool:"create_cms_post"},g=x({action:"CREATE POST",context:n,payload:d,preview:{blockCount:l.length,languageCode:a.code,slug:s,status:t.status,title:t.title,translationGroupId:u.translationGroupId},subject:s});if(g)return g;const p=u.translationGroupId||Se(),{data:_,error:k}=await r.from("posts").insert({...d.item,author_id:i,translation_group_id:p}).select("id, language_id, slug, status, title, translation_group_id").single();if(k||!_?.id)throw new Error(`Failed to create post: ${f(k)}`);try{await yt({blocks:l,contentType:"post",itemId:Number(_.id),languageId:a.id,supabase:r})}catch(S){throw await kt({contentType:"post",itemId:Number(_.id),supabase:r}),S}return B(n,{contentType:"post",entityId:Number(_.id),languageId:a.id,slug:s,title:t.title},s),n?.revalidatePath?.("/cms/posts"),n?.revalidatePath?.("/articles"),{blockCount:l.length,contentType:"post",editPath:je("post",_.id),entityId:_.id,mutationExecuted:!0,slug:s,success:!0,title:t.title,translationGroupId:_.translation_group_id}}function Dn(e,n){return(n||ge(e)||"product").replace(/-/g,"").slice(0,24).toUpperCase()}function St(e){if(e===void 0)return;const n=on().safeParse(e);if(!n.success)throw new Error(`Product description_json failed editor document validation: ${n.error.issues.map(t=>t.message).join("; ")}`);return n.data}async function Ke(e,n){const t=Q.parse(e),r=y(n),i=await Pe(r,t.languageCode),a=ge(t.slug||t.title),s=await Fe({contentType:"product",languageId:i.id,slug:a,supabase:r});if(s)return s;const l=await Ne({contentType:"product",languageCode:i.code,languageId:i.id,suppliedTranslationGroupId:t.translationGroupId,supabase:r});if(l.result)return l.result;const{createProduct:m,productSchema:u}=await ve(),d=t.product_type==="digital"&&t.payment_provider==="freemius"?t.trial_period_days:0,g=u.parse({description_json:St(t.description_json),freemius_plan_id:t.freemius_plan_id||"",freemius_product_id:t.freemius_product_id||"",is_taxable:t.is_taxable,language_id:i.id,meta_description:t.meta_description??"",meta_title:t.meta_title??"",payment_provider:t.payment_provider,price:t.price,prices:t.prices||{},product_media:[],product_type:t.product_type,sale_price:t.sale_price??null,sale_prices:t.sale_prices||{},short_description:t.short_description??"",sku:t.sku||Dn(t.title,a),slug:a,status:t.status,stock:t.stock,title:t.title,trial_period_days:d,trial_requires_payment_method:d>0?t.trial_requires_payment_method:!1,translation_group_id:l.translationGroupId,upc:t.upc??"",variation_attributes:[],variants:[]}),p=x({action:"CREATE PRODUCT",context:n,payload:{item:g,tool:"create_cms_product"},preview:{languageCode:i.code,price:g.price,sku:g.sku,slug:a,status:g.status,stock:g.stock,title:g.title,translationGroupId:l.translationGroupId},subject:a});if(p)return p;const _=await m(r,g);if(!_?.id)throw new Error("Failed to create product.");return B(n,{contentType:"product",entityId:_.id,languageId:i.id,slug:a,title:t.title},a),n?.revalidatePath?.("/cms/products"),{contentType:"product",editPath:je("product",_.id),entityId:_.id,mutationExecuted:!0,slug:a,success:!0,title:t.title,translationGroupId:_.translation_group_id}}function Ve(e){return e.trim().replace(/[\s-]+/g,"_").toLowerCase()}function Mn(e,n){const t=typeof n=="string"?Ve(n):n;return e==="product"?t==="public"||t==="publish"||t==="published"?"active":t:t==="public"||t==="active"||t==="publish"?"published":t}function Ln(e){const n=Ve(e.field);return!!(e.startsAt||e.endsAt||n.includes("start")||n.includes("end")||n.includes("schedule")||n.includes("special_date"))}async function Gn(e,n,t){const r=await kn(n),{productSchema:i}=await ve();return i.parse({description_json:t.description_json!==void 0?St(t.description_json):e.description_json||void 0,freemius_plan_id:e.freemius_plan_id||"",freemius_product_id:e.freemius_product_id||"",is_taxable:t.is_taxable??e.is_taxable??!0,language_id:t.language_id??e.language_id,meta_description:t.meta_description??e.meta_description??"",meta_title:t.meta_title??e.meta_title??"",payment_provider:t.payment_provider??e.payment_provider??"stripe",price:t.price!==void 0?t.price:mn(e.price,r),prices:t.prices??Xe(e.prices,r),product_media:void 0,product_type:t.product_type??e.product_type??"physical",sale_price:t.sale_price!==void 0?t.sale_price:e.sale_price===null||e.sale_price===void 0?null:Ae(Number(e.sale_price),r),sale_prices:t.sale_prices??Xe(e.sale_prices,r),short_description:t.short_description??e.short_description??"",sku:t.sku??e.sku,slug:t.slug??e.slug,status:t.status??e.status??"draft",stock:t.stock??e.stock??0,title:t.title??e.title,trial_period_days:t.trial_period_days??e.trial_period_days??0,trial_requires_payment_method:t.trial_requires_payment_method??e.trial_requires_payment_method??!1,upc:t.upc??e.upc??"",variation_attributes:[],variants:[]})}function Rn(e,n){const t=Ve(e.field),r=t==="status"?Mn(n.contentType,e.value):e.value,a={description:"description_json",feature_image:"feature_image_id",feature_image_id:"feature_image_id",language:"language_id",meta_description:"meta_description",meta_title:"meta_title",payment:"payment_provider",provider:"payment_provider",regular_price:"price",sale:"sale_price",sale_price:"sale_price",short_description:"short_description",taxable:"is_taxable",trial:"trial_period_days",trial_days:"trial_period_days",trial_payment_method_required:"trial_requires_payment_method",type:"product_type"}[t]||t;if(n.contentType!=="product"){if(!(n.contentType==="page"?Tt:$t).has(a))throw new Error(`Field "${e.field}" cannot be updated for ${n.contentType}.`);return a==="status"&&he(n.contentType,r),{field:a,payload:{[a]:vt(a,r)}}}if(!new Set(["description_json","freemius_plan_id","freemius_product_id","is_taxable","language_id","meta_description","meta_title","payment_provider","price","prices","product_type","sale_price","sale_prices","short_description","sku","slug","status","stock","title","trial_period_days","trial_requires_payment_method","upc"]).has(a))throw new Error(`Field "${e.field}" cannot be updated for product.`);if(a==="status"&&he("product",r),(a==="price"||a==="sale_price")&&r!==null&&(typeof r!="number"||r<0))throw new Error(`${a} must be a non-negative number or null.`);if(a==="stock"&&(!Number.isInteger(r)||Number(r)<0))throw new Error("stock must be a non-negative integer.");if(a==="trial_period_days"&&(!Number.isInteger(r)||Number(r)<0))throw new Error("trial_period_days must be a non-negative integer.");if(a==="trial_requires_payment_method"&&typeof r!="boolean")throw new Error("trial_requires_payment_method must be a boolean.");return{field:a,payload:{[a]:r}}}async function Je(e,n){const t=X.parse(e);if(Ln(t))return{message:"Scheduled product specials are not supported by the current product schema yet. I can set or clear sale_price now, but not start/end dates.",mutationExecuted:!1,success:!1,unsupported:!0};const r=await Be(t,n),i=Rn(t,r),a=i.field;let s=i.payload;if(a==="language_id"&&typeof s.language_id=="string"){const d=await O(y(n),s.language_id);s={...s,language_id:d.id}}const l=x({action:"UPDATE FIELD",context:n,payload:{contentType:r.contentType,entityId:r.item.id,field:a,payload:s,tool:"update_cms_item_field"},preview:{contentType:r.contentType,field:a,from:r.item[a],slug:r.item.slug,title:r.item.title,to:s[a]},subject:`${r.contentType} ${r.item.slug||r.item.id} ${a}`});if(l)return l;if(r.contentType==="product"){const{updateProduct:d}=await ve(),g=await Gn(r.item,y(n),s),p=await d(y(n),String(r.item.id),g);return B(n,{contentType:"product",entityId:String(r.item.id),languageId:p?.language_id??r.item.language_id,slug:p?.slug??r.item.slug,title:p?.title??r.item.title},p?.slug??r.item.slug),{contentType:"product",entityId:r.item.id,field:a,mutationExecuted:!0,slug:p?.slug??r.item.slug,success:!0,updatedFields:[a]}}const m=r.contentType==="page"?"pages":"posts",{data:u,error:c}=await y(n).from(m).update({...s,updated_at:new Date().toISOString()}).eq("id",r.item.id).select("id, language_id, slug, status, title").single();if(c||!u)throw new Error(`Failed to update ${r.contentType}: ${f(c)}`);return B(n,{contentType:r.contentType,entityId:Number(u.id),languageId:u.language_id,slug:u.slug,title:u.title},u.slug),{contentType:r.contentType,entityId:u.id,field:a,mutationExecuted:!0,slug:u.slug,success:!0,updatedFields:[a]}}async function Et(e,n){const t=Ce.parse(e),r=await Be(t,n);if(r.contentType==="product")return{affectedCount:1,collectionPath:tt("product"),contentType:"product",item:r.item,navigationLinkCount:0,publicPaths:r.item.slug?[`/product/${r.item.slug}`]:[],targetIds:[r.item.id]};const i=r.contentType==="page"?"pages":"posts",{data:a,error:s}=await y(n).from(i).select("id, slug, title, translation_group_id").eq("translation_group_id",r.item.translation_group_id);if(s)throw new Error(`Failed to inspect related ${r.contentType}s: ${f(s)}`);const l=Array.isArray(a)?a:[],m=l.map(p=>r.contentType==="page"?p.slug==="home"?"/":`/${p.slug}`:`/article/${p.slug}`).filter(Boolean),u=new Set(m),{data:c,error:d}=await y(n).from("navigation_items").select("id, url");if(d)throw new Error(`Failed to inspect related navigation links: ${f(d)}`);const g=(Array.isArray(c)?c:[]).filter(p=>u.has(p.url)).length;return{affectedCount:l.length,collectionPath:tt(r.contentType),contentType:r.contentType,item:r.item,navigationLinkCount:g,publicPaths:m,targetIds:l.map(p=>p.id)}}function At(e){const n=e.item.title||e.item.slug||"selected item",t=e.item.slug?` (${e.item.slug})`:"";if(e.contentType==="product")return`Delete product "${n}"${t}.`;const r=[`${F(e.affectedCount,"language version")}`,e.navigationLinkCount>0?`${F(e.navigationLinkCount,"navigation link")}`:null].filter(Boolean);return`Delete ${e.contentType} "${n}"${t}, including ${r.join(" and ")}.`}async function Pt(e,n){const t=await Et(e,n);return{...ct({action:`DELETE ${t.contentType}`,payload:{affectedCount:t.affectedCount,contentType:t.contentType,targetIds:t.targetIds,tool:"delete_cms_item"},preview:{affectedCount:t.affectedCount,collectionPath:t.collectionPath,contentType:t.contentType,navigationLinkCount:t.navigationLinkCount,publicPaths:t.publicPaths,slug:t.item.slug,summary:At(t),title:t.item.title},subject:`${t.item.id} ${t.item.slug||""}`}),preparedDelete:!0}}async function We(e,n){const t=Z.parse(e),r=await Et(t,n),i=x({action:`DELETE ${r.contentType}`,context:n,payload:{affectedCount:r.affectedCount,contentType:r.contentType,targetIds:r.targetIds,tool:"delete_cms_item"},preview:{affectedCount:r.affectedCount,collectionPath:r.collectionPath,contentType:r.contentType,navigationLinkCount:r.navigationLinkCount,publicPaths:r.publicPaths,slug:r.item.slug,summary:At(r),title:r.item.title},subject:`${r.item.id} ${r.item.slug||""}`});if(i)return i;const a=y(n);if(r.contentType==="product"){const{error:l}=await a.from("products").delete().eq("id",r.item.id);if(l)throw new Error(`Failed to delete product: ${f(l)}`)}else{for(const u of r.publicPaths)await a.from("navigation_items").delete().eq("url",u);const l=r.contentType==="page"?"pages":"posts",{error:m}=await a.from(l).delete().eq("translation_group_id",r.item.translation_group_id);if(m)throw new Error(`Failed to delete ${r.contentType}: ${f(m)}`)}const s=n?.revalidatePath??Te();return s&&(s(r.collectionPath),s("/cms/navigation"),r.publicPaths.forEach(l=>s(l))),{affectedCount:r.affectedCount,collectionPath:r.collectionPath,contentType:r.contentType,mutationExecuted:!0,redirectPath:r.collectionPath,success:!0}}async function rt(e,n){switch(e.tool){case"create_cms_page":return Ge(e.input,n);case"create_cms_post":return Re(e.input,n);case"create_cms_product":return Ke(e.input,n);case"delete_cms_item":return We(e.input,n);case"update_cms_item_field":return Je(e.input,n);case"update_content_block":return De(e.input,n);case"insert_content_block":return Me(e.input,n);case"update_current_cms_fields":return Ue(e.input,n);case"update_footer":return Oe(e.input,n);case"update_navigation_bar":return qe(e.input,n);case"update_section_column_block":return Le(e.input,n)}}function Kn(e,n){if(e.tool!=="create_cms_page"&&e.tool!=="create_cms_post"&&e.tool!=="create_cms_product"||e.input.translationGroupId||!e.input.languageCode)return e;const t=n[e.tool];return t?{...e,input:{...e.input,translationGroupId:t}}:e}async function Bt(e,n){const t=xe.parse(e);if(!n?.skipConfirmation){const u=[];for(const g of t.actions){const p=await rt(g,{...n,latestUserMessage:null});if(!p||typeof p!="object")return{message:`Could not prepare action ${u.length+1}.`,mutationExecuted:!1,success:!1};if(p.success===!1||p.unsupported===!0)return p;p.requiresConfirmation===!0&&p.preview?u.push(pn(g.tool,p.preview)):u.push(`Run ${g.tool.replace(/_/g," ")}.`)}const c=t.summary||`Complete ${F(t.actions.length,"CMS action")}.`,d=x({action:"EXECUTE CMS ACTION PLAN",context:n,payload:{actions:t.actions,tool:"execute_cms_action_plan"},preview:{actionCount:t.actions.length,actionSummaries:u,summary:c},subject:`${t.actions.length} actions`});if(d)return d}const r={...n,skipConfirmation:!0},i=[];let a=!1,s=null,l=null;const m={};for(const[u,c]of t.actions.entries()){const d=Kn(c,m),g=await rt(d,r);if(i.push({output:g,tool:d.tool}),g&&typeof g=="object"){const p=g;if(p.mutationExecuted===!0&&(a=!0),!s&&typeof p.editPath=="string"&&(s=p.editPath),typeof p.redirectPath=="string"&&(l=p.redirectPath),(d.tool==="create_cms_page"||d.tool==="create_cms_post"||d.tool==="create_cms_product")&&typeof p.translationGroupId=="string"&&(m[d.tool]=p.translationGroupId),p.success===!1||p.unsupported===!0)return{actionCount:t.actions.length,failedActionIndex:u,failedTool:d.tool,message:typeof p.message=="string"?p.message:`Action ${u+1} failed.`,mutationExecuted:a,results:i,success:!1,...s?{editPath:s}:{},...l?{redirectPath:l}:{}}}}return{actionCount:t.actions.length,editPath:l?void 0:s??void 0,mutationExecuted:a,redirectPath:l??void 0,results:i,success:!0,summary:t.summary??null}}function Vn(e){return{...Ft.createCortexDatabaseAgentTools(e),...Nt.createCortexCustomBlockTools(e),fetch_ecommerce_stats:w.tool({description:"Fetch quantitative ecommerce statistics and reports from the database. Use this to answer questions about revenue, order counts, order status counts such as pending or trial, and top-selling products over a time range. This tool is read-only and does not require confirmation.",execute:n=>Ct(n,e),inputSchema:ke,strict:!0}),read_current_cms_item:w.tool({description:"Read the CMS item currently being edited. Requires pageContext and returns page/post/product metadata plus page/post block summaries or content.",execute:n=>xt(n,e),inputSchema:ze,strict:!0}),search_documentation:w.tool({description:"Search the NextBlock documentation database and return concise source snippets for factual CMS guidance.",execute:n=>It(n,e),inputSchema:de,strict:!0}),create_cms_page:w.tool({description:"Create a new CMS page with metadata and optional validated page blocks. Mutating: first returns a confirmation phrase; only executes after the user replies with the exact phrase. For translations, pass translationGroupId from the source page/post/product context so the new language is linked to the same backend translation group. For contact pages, provide contactEmail or a form block with recipient_email and fields.",execute:n=>Ge(n,e),inputSchema:H,strict:!0}),create_cms_post:w.tool({description:"Create a new CMS post with metadata and optional validated post blocks. Mutating: first returns a confirmation phrase; only executes after the user replies with the exact phrase. For translations, pass translationGroupId from the source post context so the new language is linked to the same backend translation group.",execute:n=>Re(n,e),inputSchema:Y,strict:!0}),create_cms_product:w.tool({description:"Create a new draft-capable product. Defaults missing product fields safely: physical Stripe product, generated SKU, price 0, stock 0, taxable, draft. For translations, pass translationGroupId from the source product context. Mutating: first returns a confirmation phrase; only executes after exact confirmation.",execute:n=>Ke(n,e),inputSchema:Q,strict:!0}),delete_cms_item:w.tool({description:"Delete a resolved page, post, or product after exact confirmation. Pages/posts delete all translations in the translation group and related navigation links. Mutating: refuses unless the latest user message includes the exact confirmation phrase.",execute:n=>We(n,e),inputSchema:Z,strict:!0}),prepare_delete_cms_item:w.tool({description:"Inspect the page, post, or product that would be deleted and return the exact confirmation phrase. This tool does not mutate data.",execute:n=>Pt(n,e),inputSchema:Ce,strict:!0}),update_footer:w.tool({description:"Replace the public footer links and/or footer copyright settings for a locale. Use links for footer navigation and copyright for locale text templates. Mutating: first returns a confirmation phrase; only executes after exact confirmation.",execute:n=>Oe(n,e),inputSchema:R,strict:!0}),update_content_block:w.tool({description:'Update the JSON content of an existing top-level page/post block that belongs to the current CMS edit context. Content is merged with the existing block before validation. For section blocks, add nested blocks with content.append_block or content.append_blocks using objects like { block_type: "button", content: { text: "Contact Us", url: "/contact" } }; existing column_blocks and layout fields are preserved. Mutating: first returns a confirmation phrase; only executes after exact confirmation.',execute:n=>De(n,e),inputSchema:V,strict:!0}),insert_content_block:w.tool({description:'Insert a new validated top-level page/post block before or after an existing block, or at the start/end. Use this for visible content additions like adding a rich text title and paragraph above a form. For "above the form", use position "before" with anchorBlockType "form" and blockType "text" containing html_content. Mutating: first returns a confirmation phrase; only executes after exact confirmation.',execute:n=>Me(n,e),inputSchema:W,strict:!0}),update_current_cms_fields:w.tool({description:"Update validated metadata fields on the current page, post, or product. For products, description_json must be a valid NextBlock editor document JSON object. Mutating: first returns a confirmation phrase; only executes after exact confirmation.",execute:n=>Ue(n,e),inputSchema:K,strict:!0}),update_cms_item_field:w.tool({description:"Update one field on a page, post, or product, resolving by current edit context, id, slug, or exact title. Use this for requests like changing price, stock, title, slug, status, sale_price, or meta fields. Interpret public as published for pages/posts and active for products. Scheduled sale date ranges are not supported and will be refused without mutation. Mutating: first returns a confirmation phrase; only executes after exact confirmation.",execute:n=>Je(n,e),inputSchema:X,strict:!0}),update_navigation_bar:w.tool({description:'Update the public header navigation bar for a locale. Use mode "append" when adding links while preserving existing navigation. Use mode "update" when renaming or changing an existing single link. Use mode "replace" only when the user asks to rebuild the complete header and you provide the full menu; destructive partial replacements are refused. Mutating: first returns a confirmation phrase; only executes after exact confirmation.',execute:n=>qe(n,e),inputSchema:G,strict:!0}),update_section_column_block:w.tool({description:"Update the content of one existing nested block inside a section block that belongs to the current CMS edit context. This tool must not change the nested block type. To add a new nested block, update the parent section with update_content_block and preserve existing column_blocks. Mutating: first returns a confirmation phrase; only executes after exact confirmation.",execute:n=>Le(n,e),inputSchema:J,strict:!0}),execute_cms_action_plan:w.tool({description:"Execute multiple CMS mutations as one confirmed plan. Use this whenever the user asks for more than one change in the same prompt, such as creating a page and adding a navigation link. First returns one combined confirmation preview and Confirm button; after confirmation, runs each action in order and stops on the first failure.",execute:n=>Bt(n,e),inputSchema:xe,strict:!0})}}exports.availableCortexAiBlockTypes=N;exports.buildVisibleContactIntroActionPlan=Wt;exports.cortexAiPageContextSchema=we;exports.createCmsPageInputSchema=H;exports.createCmsPostInputSchema=Y;exports.createCmsProductInputSchema=Q;exports.createCortexGlobalAgentTools=Vn;exports.deleteCmsItemInputSchema=Z;exports.executeCmsActionPlan=Bt;exports.executeCmsActionPlanInputSchema=xe;exports.executeCreateCmsPage=Ge;exports.executeCreateCmsPost=Re;exports.executeCreateCmsProduct=Ke;exports.executeDeleteCmsItem=We;exports.executeFetchEcommerceStats=Ct;exports.executeInsertContentBlock=Me;exports.executePrepareDeleteCmsItem=Pt;exports.executeReadCurrentCmsItem=xt;exports.executeSearchDocumentation=zt;exports.executeSearchDocumentationWithTimeout=It;exports.executeUpdateCmsItemField=Je;exports.executeUpdateContentBlock=De;exports.executeUpdateCurrentCmsFields=Ue;exports.executeUpdateFooter=Oe;exports.executeUpdateNavigationBar=qe;exports.executeUpdateSectionColumnBlock=Le;exports.fetchEcommerceStatsInputSchema=ke;exports.insertContentBlockInputSchema=W;exports.navigationItemInputSchema=ye;exports.prepareDeleteCmsItemInputSchema=Ce;exports.readCurrentCmsItemInputSchema=ze;exports.searchDocumentationInputSchema=de;exports.updateCmsItemFieldInputSchema=X;exports.updateContentBlockInputSchema=V;exports.updateCurrentCmsFieldsInputSchema=K;exports.updateFooterInputSchema=R;exports.updateNavigationBarInputSchema=G;exports.updateSectionColumnBlockInputSchema=J;