@nextblock-cms/cortex 0.20.3 → 0.21.1

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 (100) hide show
  1. package/README.md +46 -0
  2. package/client.cjs +1 -0
  3. package/client.es.js +3 -7
  4. package/index.cjs +1 -0
  5. package/index.es.js +24 -277
  6. package/lib/ai-block-generation.cjs +4 -0
  7. package/lib/ai-block-generation.es.js +143 -182
  8. package/lib/ai-client.cjs +1 -0
  9. package/lib/ai-client.d.ts +1 -1
  10. package/lib/ai-client.es.js +101 -135
  11. package/lib/ai-config.cjs +1 -0
  12. package/lib/ai-config.es.js +89 -108
  13. package/lib/ai-cortex-widget-builder.cjs +1 -0
  14. package/lib/ai-cortex-widget-builder.es.js +56 -70
  15. package/lib/ai-global-agent-content-ops-tools.cjs +1 -0
  16. package/lib/ai-global-agent-content-ops-tools.d.ts +1943 -68
  17. package/lib/ai-global-agent-content-ops-tools.es.js +185 -199
  18. package/lib/ai-global-agent-custom-block-tools.cjs +1 -0
  19. package/lib/ai-global-agent-custom-block-tools.d.ts +2160 -95
  20. package/lib/ai-global-agent-custom-block-tools.es.js +226 -223
  21. package/lib/ai-global-agent-db-tools.cjs +1 -0
  22. package/lib/ai-global-agent-db-tools.d.ts +2708 -98
  23. package/lib/ai-global-agent-db-tools.es.js +1013 -986
  24. package/lib/ai-global-agent-ecommerce.cjs +1 -0
  25. package/lib/ai-global-agent-ecommerce.es.js +3 -7
  26. package/lib/ai-global-agent-site-tools.cjs +2 -0
  27. package/lib/ai-global-agent-site-tools.d.ts +10695 -500
  28. package/lib/ai-global-agent-site-tools.es.js +750 -757
  29. package/lib/ai-global-agent-theming-tools.cjs +1 -0
  30. package/lib/ai-global-agent-theming-tools.d.ts +2905 -105
  31. package/lib/ai-global-agent-theming-tools.es.js +326 -396
  32. package/lib/ai-global-agent-tools.cjs +15 -0
  33. package/lib/ai-global-agent-tools.d.ts +4 -2230
  34. package/lib/ai-global-agent-tools.es.js +3899 -4328
  35. package/lib/ai-key-crypto.cjs +1 -0
  36. package/lib/ai-key-crypto.es.js +63 -82
  37. package/lib/ai-key-verification.cjs +1 -0
  38. package/lib/ai-key-verification.es.js +74 -63
  39. package/lib/ai-model-catalog.cjs +1 -0
  40. package/lib/ai-model-catalog.es.js +18 -22
  41. package/lib/ai-model-registry.cjs +2 -0
  42. package/lib/ai-model-registry.es.js +246 -309
  43. package/lib/ai-seo-metadata.cjs +3 -0
  44. package/lib/ai-seo-metadata.es.js +143 -185
  45. package/lib/ai-vision.cjs +3 -0
  46. package/lib/ai-vision.d.ts +6 -6
  47. package/lib/ai-vision.es.js +161 -215
  48. package/lib/block-content-schemas.cjs +1 -0
  49. package/lib/block-content-schemas.es.js +324 -254
  50. package/lib/cortex-widget-registry.cjs +1 -0
  51. package/lib/cortex-widget-registry.es.js +35 -43
  52. package/lib/cortex-widget-schema.cjs +4 -0
  53. package/lib/cortex-widget-schema.es.js +280 -309
  54. package/lib/editor-document-from-html.cjs +1 -0
  55. package/lib/editor-document-from-html.es.js +334 -278
  56. package/lib/fetch-host-guard.cjs +1 -0
  57. package/lib/fetch-host-guard.d.ts +2 -0
  58. package/lib/fetch-host-guard.es.js +30 -0
  59. package/lib/mcp-server.cjs +1 -0
  60. package/lib/mcp-server.es.js +155 -173
  61. package/lib/mcp-tokens.cjs +1 -0
  62. package/lib/mcp-tokens.es.js +95 -107
  63. package/lib/mcp-tool-registry.cjs +5 -0
  64. package/lib/mcp-tool-registry.es.js +533 -411
  65. package/lib/site-brief.cjs +2 -0
  66. package/lib/site-brief.es.js +102 -108
  67. package/lib/vision-image-download.cjs +1 -0
  68. package/lib/vision-image-download.d.ts +43 -0
  69. package/lib/vision-image-download.es.js +120 -0
  70. package/lib/zod-config.cjs +1 -0
  71. package/lib/zod-config.es.js +5 -6
  72. package/package.json +13 -12
  73. package/client.cjs.js +0 -1
  74. package/index.cjs.js +0 -1
  75. package/lib/ai-block-generation.cjs.js +0 -5
  76. package/lib/ai-client.cjs.js +0 -1
  77. package/lib/ai-config.cjs.js +0 -1
  78. package/lib/ai-cortex-widget-builder.cjs.js +0 -1
  79. package/lib/ai-global-agent-content-ops-tools.cjs.js +0 -1
  80. package/lib/ai-global-agent-custom-block-tools.cjs.js +0 -1
  81. package/lib/ai-global-agent-db-tools.cjs.js +0 -1
  82. package/lib/ai-global-agent-ecommerce.cjs.js +0 -1
  83. package/lib/ai-global-agent-site-tools.cjs.js +0 -3
  84. package/lib/ai-global-agent-theming-tools.cjs.js +0 -3
  85. package/lib/ai-global-agent-tools.cjs.js +0 -15
  86. package/lib/ai-key-crypto.cjs.js +0 -1
  87. package/lib/ai-key-verification.cjs.js +0 -1
  88. package/lib/ai-model-catalog.cjs.js +0 -1
  89. package/lib/ai-model-registry.cjs.js +0 -2
  90. package/lib/ai-seo-metadata.cjs.js +0 -4
  91. package/lib/ai-vision.cjs.js +0 -3
  92. package/lib/block-content-schemas.cjs.js +0 -1
  93. package/lib/cortex-widget-registry.cjs.js +0 -1
  94. package/lib/cortex-widget-schema.cjs.js +0 -5
  95. package/lib/editor-document-from-html.cjs.js +0 -1
  96. package/lib/mcp-server.cjs.js +0 -1
  97. package/lib/mcp-tokens.cjs.js +0 -1
  98. package/lib/mcp-tool-registry.cjs.js +0 -6
  99. package/lib/site-brief.cjs.js +0 -2
  100. package/lib/zod-config.cjs.js +0 -1
@@ -0,0 +1,15 @@
1
+ require("./zod-config.cjs");const e=require("./ai-global-agent-custom-block-tools.cjs"),t=require("./block-content-schemas.cjs"),n=require("./ai-global-agent-db-tools.cjs"),r=require("./ai-global-agent-theming-tools.cjs"),i=require("./ai-global-agent-site-tools.cjs"),a=require("./fetch-host-guard.cjs"),o=require("./ai-global-agent-content-ops-tools.cjs"),s=require("./editor-document-from-html.cjs");let c=require("ai"),l=require("next/cache"),u=require("zod");async function d(e,t,n){if(e?.recordRevision)try{return await e.recordRevision({contentType:t,entityId:n,phase:`capture`})}catch(e){console.error(`Cortex AI: failed to capture revision baseline`,e);return}}async function f(e,t,n,r){if(e?.recordRevision&&r!==void 0)try{await e.recordRevision({baseline:r,contentType:t,entityId:n,phase:`commit`})}catch(e){console.error(`Cortex AI: failed to record revision`,e)}}var p=1e4,m={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`},h=u.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.`),g=u.z.strictObject({label:u.z.string().trim().min(1).max(120),target:u.z.enum([`_self`,`_blank`]).optional(),url:h}),_=g.extend({children:u.z.array(g).max(20).optional()}),v=u.z.strictObject({label:u.z.string().trim().min(1).max(120).optional(),url:h.optional()}).refine(e=>!!(e.label||e.url),{message:`Navigation item match requires label or url.`}),y=u.z.strictObject({items:u.z.array(_).min(1).max(30),languageCode:u.z.string().trim().min(2).max(80).default(`en`).describe(`Locale code or language name, for example "en", "fr", "English", or "French".`),match:v.optional().describe(`For mode "update", identifies the existing navigation item to update.`),mode:u.z.enum([`append`,`replace`,`update`]).default(`append`)}),b=u.z.strictObject({copyright:u.z.record(u.z.string().trim().min(2).max(12),u.z.string().trim().min(1).max(500)).optional(),languageCode:u.z.string().trim().min(2).max(80).default(`en`).describe(`Locale code or language name, for example "en", "fr", "English", or "French".`),links:u.z.array(_).min(1).max(30).optional()}),x=u.z.strictObject({limit:u.z.number().int().min(1).max(8).default(4),query:u.z.string().trim().min(2).max(300)}),S=u.z.object({currency:u.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:u.z.string().describe(`The analytical question about orders, products, or revenue.`),reportType:u.z.enum([`revenue`,`orders`,`products`,`general`]).optional().default(`general`).describe(`The focus area of the statistical report.`),timeRange:u.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.`)}),C=u.z.strictObject({contentType:u.z.enum([`page`,`post`,`product`]),currentEditor:u.z.strictObject({blockId:u.z.union([u.z.number().int().positive(),u.z.string().trim().min(1).max(120)]).nullable().optional(),blockType:u.z.string().trim().min(1).max(80).nullable().optional(),field:u.z.string().trim().min(1).max(120).nullable().optional()}).optional(),entityId:u.z.union([u.z.number().int().positive(),u.z.string().trim().min(1).max(120)]),languageId:u.z.number().int().positive().nullable().optional(),slug:u.z.string().trim().min(1).max(300).nullable().optional(),title:u.z.string().trim().min(1).max(300).nullable().optional(),translationGroupId:u.z.string().trim().min(1).max(120).nullable().optional()}),w=u.z.enum([`page`,`post`,`product`]),T=u.z.strictObject({contentType:w.optional(),entityId:u.z.union([u.z.number().int().positive(),u.z.string().trim().min(1).max(120)]).optional(),slug:u.z.string().trim().min(1).max(300).optional(),title:u.z.string().trim().min(1).max(300).optional()}),E=T.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.`),ee=u.z.strictObject({cmsTarget:E,includeBlockContent:u.z.boolean().default(!1),includeBlocks:u.z.boolean().default(!0)}),te="The feature image: an existing media library id OR an external https:// image URL, which is downloaded into the media library automatically (pass `mainImage` from fetch_url_content or a `url` from search_stock_photos straight in). WHAT IT DOES: on a page it renders as a full-width title banner ABOVE the page's blocks (the image as a dimmed cover background, about 200-300px tall, with the page title centred over it in white); on a post it is the article's hero image above the header. It is also the social/OG preview image and the card thumbnail in post listings. RULES: give every post one. Give a page one only when a title banner above its content is wanted; NEVER set one on the home page or on any page that opens with its own hero section (the banner would stack above the hero and repeat the title) — set the site-wide social preview with update_site_identity `social_image` instead. Pick a very wide landscape image (about 3:1, at least 1600px wide): the banner crops it to a short full-width band.",D=u.z.strictObject({cmsTarget:E,fields:u.z.strictObject({description_json:u.z.unknown().optional(),excerpt:u.z.string().max(2e3).nullable().optional(),feature_image_id:u.z.string().trim().min(1).max(2048).nullable().optional().describe(te),label:u.z.string().max(120).nullable().optional(),meta_description:u.z.string().max(500).nullable().optional(),meta_title:u.z.string().max(160).nullable().optional(),published_at:u.z.string().max(80).nullable().optional(),short_description:u.z.string().max(2e3).nullable().optional(),slug:u.z.string().trim().min(1).max(300).optional(),status:u.z.enum([`draft`,`published`,`active`,`archived`]).optional(),subtitle:u.z.string().max(300).nullable().optional(),title:u.z.string().trim().min(1).max(300).optional()}).partial()}),ne=u.z.string().trim().min(1).max(120).describe(`A built-in block type (${t.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.`),O=u.z.strictObject({blockId:u.z.number().int().positive(),blockType:ne.optional(),cmsTarget:E,content:u.z.record(u.z.string(),u.z.unknown())}),k=u.z.strictObject({blockIndex:u.z.number().int().min(0),blockType:ne.optional(),cmsTarget:E,columnIndex:u.z.number().int().min(0),content:u.z.record(u.z.string(),u.z.unknown()),parentBlockId:u.z.number().int().positive()}),A=u.z.strictObject({blockType:ne,content:u.z.record(u.z.string(),u.z.unknown()).describe('The block content, matching that block type\'s schema. For a `text` block, `html_content` is rendered as real HTML and may include an inline <style> and an inline <script> — so you can add scroll reveals, counters, hover effects, and other motion directly in a block. Inline scripts are stamped with the site CSP nonce automatically. Three rules. (1) THE PAGE IS REACT-HYDRATED. Do not change the text, classes, or attributes of surrounding server-rendered markup: React reconciles afterwards and reverts your change (a counter animates then snaps back) or logs a hydration mismatch. Waiting for `load` is NOT sufficient — hydration can still be in flight. Safe patterns instead: animate with the Web Animations API (el.animate() touches no attribute); append your own new elements and style those; use CSS for anything CSS can do; and if you must set text, render the FINAL value server-side and only animate toward it once the element scrolls into view. (2) `on*` attributes (onclick, onload, …) are stripped, so bind with addEventListener. (3) The script runs once per full page load, not on client-side navigation — for site-wide behaviour use manage_site_script. For a `section` block: `is_hero: true` marks the page hero (the editor checkbox "Hero Section (Prioritized image loading)": its background image loads with priority and its content is vertically centred); `slider: true` with a `slides` array ([{ background, column_blocks }, …], the editor checkbox "Enable Slider (Carousel layout)") renders a carousel of full sections: only the slides are drawn, but the grid track count still comes from the top-level `column_blocks`, so send one top-level column per column you want inside each slide (empty columns are fine) and give every slide that same number of columns. Add `autoplay: true` and `timeframe` in seconds (default 5) to rotate it.'),order:u.z.number().int().min(0).optional()}),j=T.extend({images:u.z.array(u.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).`)}),re=T.extend({anchorBlockId:u.z.number().int().positive().optional(),anchorBlockType:ne.optional(),block:A,position:u.z.enum([`before`,`after`,`start`,`end`]).default(`end`)}),ie=u.z.strictObject({blocks:u.z.array(A).max(20).optional(),contactEmail:u.z.string().email().optional(),feature_image_id:u.z.string().trim().min(1).max(2048).nullable().optional().describe(te),languageCode:u.z.string().trim().min(2).max(80).optional(),meta_description:u.z.string().max(500).nullable().optional(),meta_title:u.z.string().max(160).nullable().optional(),slug:u.z.string().trim().min(1).max(300).optional(),status:u.z.enum([`draft`,`published`,`archived`]).default(`draft`),title:u.z.string().trim().min(1).max(300),translationGroupId:u.z.string().trim().min(1).max(120).optional()}),ae=u.z.strictObject({blocks:u.z.array(A).max(20).optional(),excerpt:u.z.string().max(2e3).nullable().optional(),feature_image_id:u.z.string().trim().min(1).max(2048).nullable().optional().describe(te),label:u.z.string().max(120).nullable().optional(),languageCode:u.z.string().trim().min(2).max(80).optional(),meta_description:u.z.string().max(500).nullable().optional(),meta_title:u.z.string().max(160).nullable().optional(),published_at:u.z.string().max(80).nullable().optional(),slug:u.z.string().trim().min(1).max(300).optional(),status:u.z.enum([`draft`,`published`,`archived`]).default(`draft`),subtitle:u.z.string().max(300).nullable().optional(),title:u.z.string().trim().min(1).max(300),translationGroupId:u.z.string().trim().min(1).max(120).optional()}),oe=u.z.strictObject({blocks:u.z.array(A).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:u.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:u.z.unknown().optional(),freemius_plan_id:u.z.string().optional(),freemius_product_id:u.z.string().optional(),images:u.z.array(u.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:u.z.boolean().default(!0),languageCode:u.z.string().trim().min(2).max(80).optional(),meta_description:u.z.string().max(500).nullable().optional(),meta_title:u.z.string().max(160).nullable().optional(),payment_provider:u.z.enum([`stripe`,`freemius`]).default(`stripe`),price:u.z.number().min(0).default(0),prices:u.z.record(u.z.string(),u.z.number().min(0)).optional(),product_type:u.z.enum([`physical`,`digital`]).default(`physical`),sale_price:u.z.number().min(0).nullable().optional(),sale_prices:u.z.record(u.z.string(),u.z.number().min(0).nullable()).optional(),short_description:u.z.string().max(2e3).nullable().optional(),sku:u.z.string().trim().min(1).max(120).optional(),slug:u.z.string().trim().min(1).max(300).optional(),status:u.z.enum([`draft`,`active`,`archived`]).default(`draft`),stock:u.z.number().int().min(0).default(0),title:u.z.string().trim().min(1).max(300),trial_period_days:u.z.number().int().min(0).default(0),trial_requires_payment_method:u.z.boolean().default(!1),translationGroupId:u.z.string().trim().min(1).max(120).optional(),upc:u.z.string().max(120).nullable().optional()}),se=T.extend({currencyCode:u.z.string().trim().min(3).max(3).optional(),endsAt:u.z.string().max(80).nullable().optional(),field:u.z.string().trim().min(1).max(120),startsAt:u.z.string().max(80).nullable().optional(),value:u.z.unknown()}),ce=T,le=T,ue=u.z.discriminatedUnion(`tool`,[u.z.strictObject({input:ie,tool:u.z.literal(`create_cms_page`)}),u.z.strictObject({input:ae,tool:u.z.literal(`create_cms_post`)}),u.z.strictObject({input:oe,tool:u.z.literal(`create_cms_product`)}),u.z.strictObject({input:le,tool:u.z.literal(`delete_cms_item`)}),u.z.strictObject({input:se,tool:u.z.literal(`update_cms_item_field`)}),u.z.strictObject({input:O,tool:u.z.literal(`update_content_block`)}),u.z.strictObject({input:re,tool:u.z.literal(`insert_content_block`)}),u.z.strictObject({input:D,tool:u.z.literal(`update_current_cms_fields`)}),u.z.strictObject({input:b,tool:u.z.literal(`update_footer`)}),u.z.strictObject({input:y,tool:u.z.literal(`update_navigation_bar`)}),u.z.strictObject({input:k,tool:u.z.literal(`update_section_column_block`)}),u.z.strictObject({input:j,tool:u.z.literal(`set_content_images`)})]),de=u.z.union([ie.extend({tool:u.z.literal(`create_cms_page`)}).transform(({tool:e,...t})=>({input:t,tool:e})),ae.extend({tool:u.z.literal(`create_cms_post`)}).transform(({tool:e,...t})=>({input:t,tool:e})),oe.extend({tool:u.z.literal(`create_cms_product`)}).transform(({tool:e,...t})=>({input:t,tool:e})),le.extend({tool:u.z.literal(`delete_cms_item`)}).transform(({tool:e,...t})=>({input:t,tool:e})),se.extend({tool:u.z.literal(`update_cms_item_field`)}).transform(({tool:e,...t})=>({input:t,tool:e})),O.extend({tool:u.z.literal(`update_content_block`)}).transform(({tool:e,...t})=>({input:t,tool:e})),re.extend({tool:u.z.literal(`insert_content_block`)}).transform(({tool:e,...t})=>({input:t,tool:e})),D.extend({tool:u.z.literal(`update_current_cms_fields`)}).transform(({tool:e,...t})=>({input:t,tool:e})),b.extend({tool:u.z.literal(`update_footer`)}).transform(({tool:e,...t})=>({input:t,tool:e})),y.extend({tool:u.z.literal(`update_navigation_bar`)}).transform(({tool:e,...t})=>({input:t,tool:e})),k.extend({tool:u.z.literal(`update_section_column_block`)}).transform(({tool:e,...t})=>({input:t,tool:e})),j.extend({tool:u.z.literal(`set_content_images`)}).transform(({tool:e,...t})=>({input:t,tool:e}))]),fe=u.z.string().transform((e,t)=>{let n=ye(e);return n.success?n.action:(t.addIssue({code:`custom`,message:n.message}),u.z.NEVER)}),pe=u.z.union([ue,de,fe]),me=u.z.strictObject({actions:u.z.array(pe).min(1).max(8),summary:u.z.string().trim().min(1).max(500).optional()});function he(e){let t=[],n=``,r=0,i=null,a=!1;for(let o of e){if(i){n+=o,a?a=!1:o===`\\`?a=!0:o===i&&(i=null);continue}if(o===`"`||o===`'`){i=o,n+=o;continue}if(o===`[`||o===`{`||o===`(`){r++,n+=o;continue}if(o===`]`||o===`}`||o===`)`){r=Math.max(0,r-1),n+=o;continue}if(o===`,`&&r===0){n.trim()&&t.push(n.trim()),n=``;continue}n+=o}return n.trim()&&t.push(n.trim()),t}function ge(e){let t=``;for(let n=0;n<e.length;n++){let r=e[n];if(r!==`'`){t+=r;continue}let i=``,a=!1;for(n++;n<e.length;n++){let t=e[n];if(a){i+=t,a=!1;continue}if(t===`\\`){a=!0;continue}if(t===`'`)break;i+=t}t+=JSON.stringify(i)}return t.replace(/\bTrue\b/g,`true`).replace(/\bFalse\b/g,`false`).replace(/\bNone\b/g,`null`)}function _e(e){let t=e.trim();return t.startsWith(`'`)&&t.endsWith(`'`)||t.startsWith(`"`)&&t.endsWith(`"`)||t.startsWith(`[`)||t.startsWith(`{`)?JSON.parse(ge(t)):/^-?\d+(?:\.\d+)?$/.test(t)?Number(t):t===`true`||t===`True`?!0:t===`false`||t===`False`?!1:t===`null`||t===`None`?null:t}function ve(e){let t={};for(let n of he(e)){let e=n.indexOf(`=`);if(e<=0)throw Error(`Expected key=value argument, received "${n}".`);let r=n.slice(0,e).trim();if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(r))throw Error(`Invalid argument name "${r}".`);t[r]=_e(n.slice(e+1))}return t}function ye(e){let 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};let n=t[1],r;try{r=ve(t[2])}catch(e){return{message:e instanceof Error?e.message:`Could not parse action-plan command arguments.`,success:!1}}let i={input:r,tool:n},a=ue.safeParse(i);return a.success?{action:a.data,success:!0}:{message:`Invalid action-plan command "${n}": ${a.error.issues.map(e=>e.message).join(`; `)}`,success:!1}}function be(e){return e.normalize(`NFD`).replace(/[\u0300-\u036f]/g,``).toLowerCase().replace(/\s+/g,` `).trim()}function xe(e,t){return t.some(t=>e.includes(t))}function Se(e){let t=be(e),n=xe(t,[`add `,`insert `,`put `,`create `]),r=xe(t,[`title`,`heading`,`description`,`intro`,`copy`,`paragraph`]),i=t.includes(`form`)&&xe(t,[`above`,`before`]),a=t.includes(`contact page`)||t.includes(`contact pages`)||t.includes(`contact us`)||t.includes(`contactez-nous`),o=t.includes(`english`)&&xe(t,[`french`,`francais`,`francaise`]);return!n||!r||!i||!a||!o?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 Ce(){return u.z.object({content:u.z.array(u.z.any()).optional(),type:u.z.literal(`doc`)})}function we(){return l.revalidatePath}function M(e){if(!e?.supabase)throw Error(`A Supabase service client is required to execute Cortex AI global tools.`);return e.supabase}function Te(e,t,n){let r,i=new Promise(e=>{r=setTimeout(()=>e(n()),t)});return Promise.race([e.finally(()=>{r&&clearTimeout(r)}),i])}function Ee(e){let t=C.safeParse(e?.pageContext);if(!t.success)throw Error(`No current CMS page context is available. Open a page, post, or product edit screen before using this editing tool.`);return t.data}function De(e){let t=typeof e.entityId==`number`?e.entityId:Number.parseInt(e.entityId,10);if(!Number.isInteger(t)||t<=0)throw Error(`Current ${e.contentType} id must be a positive integer.`);return t}function Oe(e){let t=String(e.entityId||``).trim();if(!t)throw Error(`Current ${e.contentType} id is missing.`);return t}function N(e){return e.contentType===`product`?Oe(e):De(e)}var ke=/^https?:\/\//i,Ae=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;async function P(e,t,n){if(typeof e!=`string`)return null;let r=e.trim();if(!r)return null;if(!ke.test(r)){if(Ae.test(r))return r;throw Error(`"${r}" is not a usable image reference — provide an https:// image URL or a media library id.`)}let i=t?.importExternalImage;if(!i)throw 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.`);let a=await i({altText:n,url:r});if(`error`in a)throw Error(`I could not import the image from that URL: ${a.error}`);return a.id}async function je(e,t,n){let r=[];for(let i=0;i<e.length;i+=1){let a=await P(e[i],t,`${n} image ${i+1}`);a&&r.push(a)}return r}async function Me(e){let t=[...new Set(e.mediaIds)],{error:n}=await e.supabase.from(`product_media`).delete().eq(`product_id`,e.productId);if(n)throw Error(`Could not clear the product's existing images: ${I(n)}`);if(t.length>0){let{error:n}=await e.supabase.from(`product_media`).insert(t.map((t,n)=>({media_id:t,product_id:e.productId,sort_order:n})));if(n)throw Error(`Could not save the product images: ${I(n)}`)}return t}async function Ne(e){if(!e.productId)return!1;let{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;let r=e.patch({blocks:Array.isArray(t.blocks)?U(t.blocks):[],meta:W(t.meta)?U(t.meta):{}}),i={updated_at:new Date().toISOString()};if(r.blocks&&(i.blocks=r.blocks),r.meta&&(i.meta=r.meta),Object.keys(i).length===1)return!1;let{error:a}=await e.supabase.from(`product_drafts`).update(i).eq(`id`,t.id);if(a)throw Error(`The product was updated, but its open draft could not be kept in sync: ${I(a)}. Publishing that draft would undo this change — publish or discard it in the product editor first.`);return!0}function Pe(e){return typeof e==`string`?e.trim().replace(/^\/+|\/+$/g,``):``}function Fe(e,t){let n=Pe(t??e.slug);return n?e.contentType===`page`?n===`home`?`/`:`/${n}`:e.contentType===`post`?`/article/${n}`:`/product/${n}`:null}function Ie(e){let t=String(e.entityId);return e.contentType===`page`?`/cms/pages/${t}/edit`:e.contentType===`post`?`/cms/posts/${t}/edit`:`/cms/products/${t}/edit`}function F(e,t,n){let r=e?.revalidatePath??we();if(!r)return;r(Ie(t));let i=Fe(t,n);i&&r(i),t.contentType===`page`&&i!==`/`&&r(`/`),t.contentType===`product`&&r(`/cms/products`)}function Le(e){let t=e?.revalidatePath??we();t&&(t(`/`,`layout`),t(`/cms/navigation`))}function I(e){return e?typeof e==`object`&&`message`in e?String(e.message||`Unknown database error.`):String(e):`Unknown database error.`}async function Re(){return Promise.resolve().then(()=>require("./ai-global-agent-ecommerce.cjs"))}function ze(e){return typeof e!=`object`||!e?JSON.stringify(e):Array.isArray(e)?`[${e.map(e=>ze(e)).join(`,`)}]`:`{${Object.keys(e).filter(e=>e!==`temp_id`).sort().map(t=>`${JSON.stringify(t)}:${ze(e[t])}`).join(`,`)}}`}function Be(e){let t=2166136261,n=ze(e);for(let e=0;e<n.length;e++)t^=n.charCodeAt(e),t=Math.imul(t,16777619);return(t>>>0).toString(16).padStart(8,`0`)}function Ve(e){return e.replace(/\s+/g,` `).trim().toUpperCase()}function He(e,t,n){return`${Ve(`CONFIRM ${e} ${t}`)} #${Be(n)}`}function Ue(e){return{confirmationPhrase:He(e.action,e.subject,e.payload),mutationExecuted:!1,preview:e.preview,requiresConfirmation:!0,success:!0}}function L(e,t){let n=e[t];return typeof n==`string`&&n.trim()?n.trim():null}function R(e,t){let n=Number(e[t]);return Number.isFinite(n)?n:null}function z(e,t,n=`${t}s`){return`${e} ${e===1?t:n}`}function We(e,t){let n=L(t,`summary`);if(n)return n;let r=L(t,`title`),i=L(t,`slug`),a=L(t,`status`),o=L(t,`contentType`),s=L(t,`field`),c=L(t,`mode`),l=L(t,`languageCode`),u=R(t,`blockCount`),d=R(t,`itemCount`),f=R(t,`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}"`:``}${u===null?``:` with ${z(u,`content block`)}`}.`;if(e===`create_cms_product`){let e=R(t,`imageCount`),n=R(t,`blockCount`),o=[e?z(e,`image`):null,n?z(n,`description block`):R(t,`descriptionLength`)?`a full description`:null].filter(Boolean);return`Create ${a||`draft`} product "${r||i||`Untitled`}"${i?` at slug "${i}"`:``}${o.length?` with ${o.join(` and `)}`:``}.`}if(e===`update_cms_item_field`)return`Update ${s||`one field`} on the ${o||`CMS item`} "${r||i||`selected item`}".`;if(e===`update_navigation_bar`)return`${c===`append`?`Add`:c===`update`?`Update`:`Replace`} ${d===null?`navigation items`:z(d,`navigation item`)} in the ${l||`selected`} header navigation.`;if(e===`update_footer`){let e=R(t,`linkCount`);return`Update the ${l||`selected`} footer${e===null?``:` with ${z(e,`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 ${o||`CMS item`} "${r||i||`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 ${f===null?`the selected ${o||`CMS item`}`:z(f,o||`CMS item`)}${r||i?` for "${r||i}"`:``}.`:`Complete the requested CMS change.`}function B(e){if(e.context?.skipConfirmation)return null;let t=Ue(e),n=Ve(e.context?.latestUserMessage||``),r=Ve(t.confirmationPhrase);return n.includes(r)?null:t}function Ge(e){let t=e?.actorUserId;if(!t)throw Error(`A confirmed CMS mutation requires an authenticated admin actor.`);return t}function Ke(){return globalThis.crypto?.randomUUID?.()||`id-${Date.now()}-${Math.random().toString(36).slice(2)}`}function V(e){return e.normalize(`NFD`).replace(/\p{Diacritic}/gu,``).toLowerCase().trim().replace(/\s+/g,`-`).replace(/[^a-z0-9-]/g,``).replace(/-+/g,`-`).replace(/^-|-$/g,``).slice(0,300)}function qe(e){return(e||`USD`).trim().toUpperCase()}var Je=new Set([`BIF`,`CLP`,`DJF`,`GNF`,`JPY`,`KMF`,`KRW`,`MGA`,`PYG`,`RWF`,`UGX`,`VND`,`VUV`,`XAF`,`XOF`,`XPF`]);function Ye(e){return Je.has(qe(e))?0:2}function Xe(e,t){return Math.round(e*10**Ye(t))}function Ze(e,t){return!e||typeof e!=`object`||Array.isArray(e)?{}:Object.entries(e).reduce((e,[n,r])=>{if(typeof r==`number`&&Number.isFinite(r)&&r>=0){let i=qe(n||t);e[i]=Xe(r,i)}return e},{})}function H(e,t){if(!W(e))throw Error(`${t} content must be a JSON object.`);return JSON.parse(JSON.stringify(e))}function U(e){return JSON.parse(JSON.stringify(e))}function W(e){return!(!e||typeof e!=`object`||Array.isArray(e))}function Qe(e,t){let n=U(e);for(let[e,r]of Object.entries(t))if(r!==void 0){if(W(r)&&W(n[e])){n[e]=Qe(n[e],r);continue}n[e]=U(r)}return n}function $e(e,t){if(t.contentType===`product`){if(String(e.product_id??``)!==String(Oe(t)))throw Error(`Block ${e.id} does not belong to the current product being edited.`);return}let n=De(t);if((t.contentType===`page`?Number(e.page_id):Number(e.post_id))!==n)throw Error(`Block ${e.id} does not belong to the current ${t.contentType} being edited.`)}function et(e,t){return t?.customBlockDefinitions?.find(t=>t.slug===e)??null}function tt(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(let r of e)tt(r,t,n+1);return t}if(typeof e==`object`)for(let[r,i]of Object.entries(e))(r===`block_type`||r===`blockType`||r===`anchorBlockType`)&&typeof i==`string`?t.add(i):i&&typeof i==`object`&&tt(i,t,n+1);return t}async function G(e,n){return e?.customBlockDefinitions||!e?.supabase||![...tt(n)].some(e=>!t.isValidBlockType(e))?e:{...e,customBlockDefinitions:await t.loadCustomBlockDefinitions(e.supabase)}}function nt(e,n,r){let i=typeof e==`string`?e.trim():``;if(t.isValidBlockType(i)||i&&et(i,r))return i;throw Error(`${n} has unsupported block type "${i||`unknown`}". Built-in types: ${t.availableCortexAiBlockTypes.join(`, `)}; a custom block must use a slug returned by list_custom_blocks.`)}function rt(e,t,n){if(e&&e!==t)throw Error(`${n} is a "${t}" block. Refusing to update it as "${e}".`)}function K(e,n,r,i){if(!t.isValidBlockType(e)){let a=et(e,i);if(!a)throw Error(`${r} references custom block "${e}", which does not exist.`);let o=t.validateCustomBlockInstanceContent(a,n);if(!o.isValid)throw Error(`${r} content is invalid for custom block "${e}": ${o.errors.join(`; `)}`);return}let a=t.validateCortexBlockContent(e,n,i);if(!a.isValid)throw Error(`${r} content is invalid for block type "${e}": ${a.errors.join(`; `)}`)}function it(e){return e===`section`}function at(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 ot(e){return`ai-${e}-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}function st(e,t,n){if(!W(e))throw Error(`${t} must be a JSON object.`);let r=nt(e.block_type??e.blockType,t,n);if(it(r))throw Error(`${t} cannot be a nested ${r} block.`);let i=Ht(r,H(e.content,t),t,n),a=e.temp_id??e.tempId;return{block_type:r,content:i,temp_id:typeof a==`string`&&a.trim()?a:ot(r)}}function ct(e,t){let n=[];if(`append_block`in e&&n.push(st(e.append_block,`Nested block to append`,t)),`append_blocks`in e){let r=e.append_blocks;if(!Array.isArray(r))throw Error(`append_blocks must be an array of nested block objects.`);r.forEach((e,r)=>{n.push(st(e,`Nested block to append ${r}`,t))})}return n}function lt(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;let n=at(e);if(!n)return null;let r=H(e,`Nested ${n} block`);return K(n,r,`Nested ${n} block`,t),{block_type:n,content:r,temp_id:ot(n)}}function ut(e,t){let n=e.append_column_index??e.column_index;if(n===void 0)return 0;if(typeof n!=`number`||!Number.isInteger(n)||n<0)throw Error(`append_column_index must be a non-negative integer.`);if(t>0&&n>=t)throw Error(`append_column_index ${n} is outside the existing ${t} column(s).`);return n}function dt(e,t,n,r){if(!it(e))return Qe(t,n);let i={...n},a=ct(i,r),o=lt(i,r);o&&a.push(o),delete i.append_block,delete i.append_blocks,delete i.append_column_index,delete i.column_index;let s=Qe(t,i);if(a.length>0){let e=Array.isArray(t.column_blocks)?U(t.column_blocks):[],r=ut(n,e.length),i=e.length>0?e:[[]];for(;i.length<=r;)i.push([]);i[r]=[...i[r]||[],...a],s.column_blocks=i}return s}function ft(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 q(e){return typeof e==`string`?e.trim().toLowerCase():``}function pt(e){return typeof e==`string`?e.trim().toLowerCase():``}function mt(e){return e.reduce((e,t)=>e+1+(t.children?.length||0),0)}function ht(e){return typeof e==`string`?e.trim().toLowerCase().normalize(`NFD`).replace(/[\u0300-\u036f]/g,``):``}async function J(e,t){let n=ht(t.trim()),r=m[n],{data:i,error:a}=await e.from(`languages`).select(`id, code, name, is_active`);if(a)throw Error(`Failed to load language "${t}": ${I(a)}`);let o=(Array.isArray(i)?i:[]).filter(e=>e.is_active!==!1),s=o.find(e=>{let t=ht(e.code),i=ht(e.name);return t===n||t===r||i===n});if(!s?.id||!s?.code){let e=o.map(e=>e.code).filter(Boolean).join(`, `);throw Error(`Language "${t}" was not found.${e?` Available languages: ${e}.`:``}`)}return{code:String(s.code),id:Number(s.id)}}async function gt(e,t){if(t)return J(e,t);let{data:n,error:r}=await e.from(`languages`).select(`id, code, name, is_active, is_default`);if(r)throw Error(`Failed to load active languages: ${I(r)}`);let i=(Array.isArray(n)?n:[]).filter(e=>e.is_active!==!1),a=i.find(e=>e.is_default)||i.find(e=>ht(e.code)===`en`)||i[0];if(!a?.id||!a?.code)throw Error(`No active CMS language is available for Cortex AI content creation.`);return{code:String(a.code),id:Number(a.id)}}async function _t(e){try{let{data:t,error:n}=await e.from(`currencies`).select(`code, is_default, is_active`).eq(`is_active`,!0);if(n)return`USD`;let r=Array.isArray(t)?t:[];return qe((r.find(e=>e.is_default)||r[0])?.code||`USD`)}catch{return`USD`}}async function vt(e){let t=e.contentType===`page`?`pages`:e.contentType===`post`?`posts`:`products`,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 Error(`A ${e.contentType} target requires an id, slug, title, or current edit context.`);let{data:i,error:a}=await e.supabase.from(t).select(`*`).eq(n,r);if(a)throw Error(`Failed to resolve ${e.contentType}: ${I(a)}`);let o=Array.isArray(i)?i:i?[i]:[];if(o.length!==1)throw Error(o.length===0?`No ${e.contentType} matched ${n} "${String(r)}".`:`Multiple ${e.contentType}s matched ${n} "${String(r)}"; use an exact id.`);return o[0]}async function Y(e,t){let n=C.safeParse(t?.pageContext).success?t?.pageContext:null,r=e.contentType||n?.contentType;if(!r)throw Error(`Target contentType is required when no current CMS edit context exists.`);let i=e.entityId!==void 0||!!e.slug||!!e.title,a=e.entityId??(i?void 0:n?.entityId),o=e.slug??(i?void 0:n?.slug??void 0),s=e.title??(i?void 0:n?.title??void 0);return{contentType:r,item:await vt({contentType:r,entityId:a,slug:a===void 0&&o||void 0,supabase:M(t),title:a===void 0&&!o&&s||void 0})}}async function X(e,t){let n=C.safeParse(t?.pageContext);if(n.success)return n.data;if(e===void 0||e.entityId===void 0&&!e.slug&&!e.title)throw 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.");let r=await Y(e,t),i=r.item;return{contentType:r.contentType,entityId:i.id,slug:typeof i.slug==`string`?i.slug:``,title:typeof i.title==`string`?i.title:``}}async function yt(e){let t=await xt({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:i}=await e.supabase.from(`navigation_items`).insert(n).select(`id`).single();if(i)throw Error(`Failed to insert ${e.menuKey} navigation item: ${I(i)}`);return Number(r.id)}function bt(e){let t=e.trim();if(!t.startsWith(`/`)||t.startsWith(`//`))return null;let n=t.split(`?`)[0]?.split(`#`)[0]||``,r=n===`/`?`home`:n.replace(/^\/+|\/+$/g,``);return r&&!r.includes(`/`)?r:null}async function xt(e){let t=bt(e.item.url);if(!t)return null;let{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 Error(`Failed to resolve linked page for navigation item: ${I(r)}`);let i=Array.isArray(n)?n[0]:n;if(!i?.id)return null;let a=Ke();if(i.translation_group_id){let{data:t,error:n}=await e.supabase.from(`pages`).select(`id`).eq(`translation_group_id`,i.translation_group_id);if(n)throw Error(`Failed to inspect linked page translations for navigation item: ${I(n)}`);let r=new Set((Array.isArray(t)?t:[]).map(e=>String(e.id)).filter(Boolean)),{data:o,error:s}=await e.supabase.from(`navigation_items`).select(`id, page_id, translation_group_id, menu_key`).eq(`menu_key`,e.menuKey);if(s)throw Error(`Failed to inspect related navigation translations: ${I(s)}`);let c=(Array.isArray(o)?o:[]).find(e=>e.translation_group_id&&r.has(String(e.page_id)));c?.translation_group_id&&(a=c.translation_group_id)}return{navigationTranslationGroupId:a,pageId:Number(i.id)}}async function St(e){let t=await J(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 Error(`Failed to inspect existing ${e.menuKey} navigation items: ${I(r)}`);let i=Array.isArray(n)?n:[],a=i.filter(e=>e.parent_id==null).length,o=mt(e.items);Ct({existingItemCount:i.length,existingTopLevelCount:a,languageCode:t.code,menuKey:e.menuKey,replacementItemCount:o});let{error:s}=await e.supabase.from(`navigation_items`).delete().eq(`menu_key`,e.menuKey).eq(`language_id`,t.id);if(s)throw Error(`Failed to clear ${e.menuKey} navigation items: ${I(s)}`);let c=0;for(let[n,r]of e.items.entries()){let i=await yt({item:r,languageId:t.id,menuKey:e.menuKey,order:n,supabase:e.supabase});c++;for(let[n,a]of(r.children??[]).entries())await yt({item:a,languageId:t.id,menuKey:e.menuKey,order:n,parentId:i,supabase:e.supabase}),c++}return{insertedCount:c,languageCode:t.code,menuKey:e.menuKey,skippedCount:0,updatedCount:0}}function Ct(e){if(!(e.existingItemCount===0||e.replacementItemCount>=e.existingItemCount))throw 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 wt(e){let t=await J(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 Error(`Failed to inspect existing ${e.menuKey} navigation items: ${I(r)}`);let i=Array.isArray(n)?n:[];Ct({existingItemCount:i.length,existingTopLevelCount:i.filter(e=>e.parent_id==null).length,languageCode:t.code,menuKey:e.menuKey,replacementItemCount:mt(e.items)})}async function Tt(e){if(e.items.length!==1)throw Error(`mode "update" requires exactly one navigation item.`);let t=await J(e.supabase,e.languageCode),n=e.items[0],r=q(e.match?.url)||q(n.url),i=pt(e.match?.label),{data:a,error:o}=await e.supabase.from(`navigation_items`).select(`id, label, url, parent_id, order`).eq(`menu_key`,e.menuKey).eq(`language_id`,t.id);if(o)throw Error(`Failed to load existing ${e.menuKey} navigation items: ${I(o)}`);let s=(Array.isArray(a)?a:[]).find(e=>{let t=q(e.url),n=pt(e.label);return!!(r&&t===r||i&&n===i)});if(!s?.id)throw Error(`Could not find a ${e.menuKey} navigation item to update in ${t.code}. Use a matching label or url.`);let{error:c}=await e.supabase.from(`navigation_items`).update({label:n.label,url:n.url}).eq(`id`,s.id);if(c)throw Error(`Failed to update ${e.menuKey} navigation item: ${I(c)}`);return{insertedCount:0,languageCode:t.code,menuKey:e.menuKey,skippedCount:0,updatedCount:1}}async function Et(e){let t=await J(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 Error(`Failed to load existing ${e.menuKey} navigation items: ${I(r)}`);let i=0,a=0,o=Array.isArray(n)?n:[],s=new Set(o.map(e=>q(e.url)).filter(Boolean)),c=o.filter(e=>e.parent_id==null).map(e=>Number(e.order)).filter(Number.isFinite),l=c.length>0?Math.max(...c)+1:o.length;for(let n of e.items){let r=q(n.url);if(r&&s.has(r)){a++;continue}let o=await yt({item:n,languageId:t.id,menuKey:e.menuKey,order:l,supabase:e.supabase});i++,l++,r&&s.add(r);let c=0;for(let r of n.children??[]){let n=q(r.url);if(n&&s.has(n)){a++;continue}await yt({item:r,languageId:t.id,menuKey:e.menuKey,order:c,parentId:o,supabase:e.supabase}),i++,c++,n&&s.add(n)}}return{insertedCount:i,languageCode:t.code,menuKey:e.menuKey,skippedCount:a,updatedCount:0}}function Z(e){return typeof e==`string`&&e.trim()?e.trim():``}function Dt(e){return e.replace(/&/g,`&amp;`).replace(/</g,`&lt;`).replace(/>/g,`&gt;`).replace(/"/g,`&quot;`).replace(/'/g,`&#39;`)}function Ot(e){let t=Z(e.field_type??e.fieldType??e.type??e.input_type).toLowerCase().replace(/\s+/g,`_`),n=Z(e.label??e.name??e.placeholder).toLowerCase();return[`email`,`tel`,`url`,`number`,`textarea`,`select`,`radio`,`checkbox`,`text`].includes(t)?t:[`phone`,`telephone`,`phone_number`,`mobile`].includes(t)?`tel`:[`website`,`link`,`uri`].includes(t)?`url`:[`numeric`,`integer`,`quantity`].includes(t)?`number`:n.includes(`email`)||n.includes(`courriel`)?`email`:n.includes(`phone`)||n.includes(`téléphone`)||n.includes(`telephone`)?`tel`:n.includes(`website`)||n.includes(`site web`)?`url`:n.includes(`message`)||n.includes(`comment`)||n.includes(`details`)?`textarea`:`text`}function kt(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((e,t)=>{let n=W(e)?e:{},r=Z(n.label??n.name)||(t===0?`Name`:t===1?`Email`:`Message`),i=Ot({...n,label:r}),a=n.is_required??n.isRequired??n.required;return{field_type:i,is_required:typeof a!=`boolean`||a,label:r,options:Array.isArray(n.options)?n.options:void 0,placeholder:Z(n.placeholder)||void 0,temp_id:Z(n.temp_id??n.tempId??n.id)||`field-${t+1}`}})}var At=new Set([`none`,`sm`,`md`,`lg`,`xl`]),jt=new Set([`none`,`sm`,`md`,`lg`,`xl`]),Mt=new Set([`full-width`,`container`,`container-sm`,`container-lg`,`container-xl`]),Nt=new Set([`start`,`center`,`end`,`stretch`]),Pt=new Set([`none`,`theme`,`solid`,`gradient`,`image`]),Ft=new Set([`primary`,`secondary`,`muted`,`accent`,`destructive`]),It=new Set([`center`,`top`,`bottom`,`left`,`right`]);function Lt(e){return typeof e==`string`&&/^https?:\/\//i.test(e.trim())}function Q(e,t,n){return typeof e==`string`&&t.has(e)?e:n}function Rt(e){return Number.isFinite(e)?Math.min(4,Math.max(1,Math.round(e))):1}function zt(e){let t=[{color:`#1e3a8a`,position:0},{color:`#3b82f6`,position:100}];if(!W(e))return{direction:`to bottom right`,stops:t,type:`linear`};let n=e.type===`radial`?`radial`:`linear`,r=Array.isArray(e.stops)&&e.stops.length>=2?e.stops:t;return{direction:typeof e.direction==`string`&&e.direction.trim()?e.direction:n===`radial`?`circle at center`:`to bottom right`,stops:r,type:n}}function Bt(e){if(!W(e))return{type:`none`};let t=Q(e.type,Pt,`none`),n=typeof e.min_height==`string`&&e.min_height.trim()?{min_height:e.min_height}:{};if(t===`theme`)return{theme:Q(e.theme,Ft,`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:zt(e.gradient),type:t,...n};if(t===`image`){let r=W(e.image)?e.image:null,i=r&&Lt(r.external_url)?r.external_url.trim():null,a=!!(r&&typeof r.media_id==`string`&&r.media_id.trim()&&typeof r.object_key==`string`&&r.object_key.trim());return r&&(i||a)?{image:{...r,...i?{external_url:i}:{},position:Q(r.position,It,`center`),size:r.size===`contain`?`contain`:`cover`},type:t,...n}:{type:`none`}}return{type:`none`,...n}}function Vt(e,t,n){let r=e.is_hero===!0,i=Array.isArray(e.column_blocks)?e.column_blocks:[];i.length>0&&i.every(e=>W(e)&&!Array.isArray(e))&&(i=[i]);let a=i.map((e,r)=>(Array.isArray(e)?e:[]).map((e,i)=>st(e,`${t} column ${r} block ${i}`,n))),o=a.length>0?a:[[]],s=Rt(o.length),c=W(e.responsive_columns)?e.responsive_columns:{},l=Number(c.tablet),u=Number(c.mobile),d=Number.isFinite(l)?Math.min(3,Math.max(1,Math.min(s,l))):Math.min(3,s),f=Number.isFinite(u)?Math.min(2,Math.max(1,u)):1,p=W(e.padding)?e.padding:{},m={...e,background:Bt(e.background),column_blocks:o,column_gap:Q(e.column_gap,At,`lg`),container_type:Q(e.container_type,Mt,`container`),padding:{bottom:Q(p.bottom,jt,`xl`),top:Q(p.top,jt,`xl`)},responsive_columns:{desktop:s,mobile:f,tablet:d},vertical_alignment:Q(e.vertical_alignment,Nt,r?`center`:`start`)};return Array.isArray(e.slides)&&(m.slides=e.slides.filter(e=>W(e)).map((e,r)=>{let i=Array.isArray(e.column_blocks)?e.column_blocks:[];return i.length>0&&i.every(e=>W(e)&&!Array.isArray(e))&&(i=[i]),{background:Bt(e.background),column_blocks:i.map((e,i)=>(Array.isArray(e)?e:[]).map((e,a)=>st(e,`${t} slide ${r} column ${i} block ${a}`,n)))}})),m.slider===!0&&!(Array.isArray(m.slides)&&m.slides.length>0)&&(m.slider=!1),m}function Ht(e,n,r,i){if(!t.isValidBlockType(e)){let t=U(n);return K(e,t,r,i),t}if(e===`section`){let t=Vt(n,r,i);return K(e,t,r,i),t}let a=U(n);if(e===`heading`&&(a.text_content=Z(a.text_content)||Z(a.text)||Z(a.title)||Z(a.heading)||`Untitled`,a.level=typeof a.level==`number`?a.level:1),e===`text`){let e=Z(a.html_content)||Z(a.html)||Z(a.content)||Z(a.text);e&&(a.html_content=/<\/?[a-z][\s\S]*>/i.test(e)?e:`<p>${Dt(e)}</p>`)}return e===`button`&&(a.text=Z(a.text)||Z(a.label)||Z(a.title)||`Learn More`,a.url=Z(a.url)||Z(a.href)||Z(a.link)||`#`),e===`form`&&(a.fields=kt(a.fields),a.submit_button_text=Z(a.submit_button_text??a.submitButtonText??a.button_text)||`Send Message`,a.success_message=Z(a.success_message??a.successMessage)||`Thanks for reaching out. We will reply as soon as possible.`),K(e,a,r,i),a}function Ut(e,t,n){let r=nt(e.blockType,`Block ${t}`,n);return{block_type:r,content:Ht(r,H(e.content,`Block ${t}`),`Block ${t}`,n),order:e.order??t}}function Wt(e,t=`Contact Us`,n){return[Ut({blockType:`section`,content:{is_hero:!0,background:{type:`none`},column_blocks:[[{block_type:`heading`,content:{level:1,textAlign:`center`,text_content:t},temp_id:ot(`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:ot(`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),Ut({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 Gt(e,t,n,r){return(!e||e.length===0)&&t?Wt(t,n,r):(e||[]).map((e,t)=>Ut(e,t,r))}async function Kt(e){let 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 Error(`Failed to check ${e.contentType} slug uniqueness: ${I(r)}`);let i=Array.isArray(n)?n:[];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 qt(e){if(!e.suppliedTranslationGroupId)return{translationGroupId:void 0};let 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 Error(`Failed to inspect ${e.contentType} translation group: ${I(r)}`);let i=Array.isArray(n)?n:[];if(i.length===0)return{result:{message:`The ${e.contentType} translation group "${e.suppliedTranslationGroupId}" was not found.`,mutationExecuted:!1,success:!1},translationGroupId:e.suppliedTranslationGroupId};let a=i.find(t=>Number(t.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 Jt(e){if(e.blocks.length===0)return[];let t=e.blocks.map((t,n)=>({block_type:t.block_type,content:t.content,language_id:e.languageId,order:t.order??n,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 Error(`Failed to insert ${e.contentType} blocks: ${I(r)}`);return br(e.blocks,e.supabase),Array.isArray(n)?n:[]}async function Yt(e){let t=e.contentType===`page`?`pages`:e.contentType===`post`?`posts`:`products`;await e.supabase.from(t).delete().eq(`id`,e.itemId)}function Xt(e,t){return e===`page`?`/cms/pages/${t}/edit`:e===`post`?`/cms/posts/${t}/edit`:`/cms/products/${t}/edit`}function Zt(e){return e===`page`?`/cms/pages`:e===`post`?`/cms/posts`:`/cms/products`}async function Qt(e,t){let n=y.parse(e),r=M(t);n.mode===`replace`&&await wt({items:n.items,languageCode:n.languageCode,menuKey:`HEADER`,supabase:r});let i=B({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(i)return i;let a=n.mode===`update`?await Tt({items:n.items,languageCode:n.languageCode,match:n.match,menuKey:`HEADER`,supabase:r}):n.mode===`append`?await Et({items:n.items,languageCode:n.languageCode,menuKey:`HEADER`,supabase:r}):await St({items:n.items,languageCode:n.languageCode,menuKey:`HEADER`,supabase:r});return Le(t),{...a,mutationExecuted:!0,mode:n.mode,success:!0}}async function $t(e,t){let n=b.parse(e);if(!n.links?.length&&!n.copyright)throw Error(`update_footer requires links or copyright.`);let r=M(t),i=B({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(i)return i;let a=null;if(n.links?.length&&(a=await St({items:n.links,languageCode:n.languageCode,menuKey:`FOOTER`,supabase:r})),n.copyright){let{error:e}=await r.from(`site_settings`).upsert({key:`footer_copyright`,value:n.copyright});if(e)throw Error(`Failed to update footer copyright: ${I(e)}`)}return Le(t),{copyrightUpdated:!!n.copyright,footerNavigation:a,mutationExecuted:!0,success:!0}}function en(e){return typeof e==`string`?e.toLowerCase():``}function tn(e,t){let n=t.map(en).join(` `);return e.reduce((e,t)=>e+ +!!n.includes(t),0)}function nn(e,t){return(e.find(e=>t.some(t=>en(e).includes(t)))||e.find(e=>e.trim().length>0)||`No excerpt available.`).slice(0,500)}async function rn(e,t){let n=x.parse(e),r=M(t),i=n.query.toLowerCase().split(/\s+/).map(e=>e.trim()).filter(Boolean),[a,o]=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 Error(`Failed to search documentation posts: ${I(a.error)}`);if(o.error)throw Error(`Failed to search documentation pages: ${I(o.error)}`);let s=(a.data??[]).map(e=>({excerpt:nn([e.excerpt,e.subtitle,e.meta_description,e.slug].filter(Boolean),i),source:`post`,title:e.title,url:`/article/${e.slug}`})),c=(o.data??[]).map(e=>({excerpt:nn([e.meta_description,e.slug].filter(Boolean),i),source:`page`,title:e.title,url:e.slug===`home`?`/`:`/${e.slug}`})),l=[...s,...c].map(e=>({...e,score:tn(i,[e.title,e.excerpt,e.url])})).filter(e=>e.score>0).sort((e,t)=>t.score-e.score).slice(0,n.limit).map(e=>({excerpt:e.excerpt,source:e.source,title:e.title,url:e.url}));return{query:n.query,results:l,success:!0}}async function an(e,t,n=p){let r=x.safeParse(e),i=r.success?r.data.query:``;return Te(rn(e,t),n,()=>({message:`Documentation search took too long to respond. Please try again or ask a more specific question.`,query:i,results:[],success:!1,timedOut:!0}))}var on=[`pending`,`trial`,`paid`,`shipped`,`cancelled`,`refunded`,`failed`],sn={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 cn(e){return String(e??`unknown`).trim().toLowerCase()||`unknown`}function ln(e){let t=Object.fromEntries(on.map(e=>[e,0]));for(let n of e){let e=cn(n.status);t[e]=(t[e]??0)+1}return t}function un(e){let t=e.toLowerCase().replace(/[^a-z0-9_]+/g,` `).split(/\s+/).filter(Boolean);for(let e of t){let t=sn[e];if(t)return t}return null}function dn(e){let t=Number(e);return Number.isFinite(t)?t:0}async function fn(e,t){let n=S.parse(e),r=M(t),i=new Date,a=null,o=null;switch(n.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()-6048e5);break;case`last_30_days`:a=new Date(i.getTime()-2592e6);break;case`last_month`:a=new Date(i.getFullYear(),i.getMonth()-1,1),o=new Date(i.getFullYear(),i.getMonth(),0,23,59,59,999);break;case`last_90_days`:a=new Date(i.getTime()-7776e6);break;case`all_time`:a=null}let s=n.currency?.toUpperCase(),c=un(n.query),l=r.from(`orders`).select(`id, status, total, currency, created_at, paid_at`);s&&l.eq(`currency`,s),a&&l.gte(`created_at`,a.toISOString()),o&&l.lte(`created_at`,o.toISOString());let u=n.reportType===`products`||n.reportType===`revenue`||n.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;u&&(s&&u.eq(`orders.currency`,s),a&&u.gte(`orders.paid_at`,a.toISOString()),o&&u.lte(`orders.paid_at`,o.toISOString()));let d=n.timeRange!==`all_time`&&(n.reportType===`orders`||c)?r.from(`orders`).select(`id, status, currency`):null;d&&s&&d.eq(`currency`,s);let[{data:f,error:p},{data:m,error:h},g]=await Promise.all([l,u??Promise.resolve({data:[],error:null}),d??Promise.resolve({data:null,error:null})]);if(p)throw Error(`Failed to fetch ecommerce stats: ${I(p)}`);if(h)throw Error(`Failed to fetch ecommerce stats: ${I(h)}`);if(g.error)throw Error(`Failed to fetch ecommerce stats: ${I(g.error)}`);let _=Array.isArray(f)?f:[],v=Array.isArray(m)?m:[],y=ln(_),b=Array.isArray(g.data)?g.data:null,x=b?ln(b):null,C={};for(let e of v){let t=Array.isArray(e.orders)?e.orders[0]:e.orders,n=String(t?.currency||s||`unknown`).toUpperCase();C[n]=(C[n]??0)+dn(e.quantity)*dn(e.price_at_purchase)/100}let w={currency:s??null,currencyFiltered:!!s,orderStatusCounts:y,paidOrderCount:y.paid??0,query:n.query,reportType:n.reportType,revenueByCurrency:C,timeRange:n.timeRange,totalOrders:_.length,totalRevenue:Object.values(C).reduce((e,t)=>e+t,0)};if(x&&(w.allTimeOrderStatusCounts=x),c&&(w.matchingOrderStatus={allTimeCount:x?.[c]??y[c]??0,count:y[c]??0,status:c,timeRange:n.timeRange}),n.reportType===`products`||n.reportType===`revenue`||n.reportType===`general`){let e={};for(let t of v){let n=Array.isArray(t.products)?t.products[0]:t.products;if(!n?.id)continue;let r=n.id;e[r]||(e[r]={id:r,quantity:0,revenue:0,title:n.title,type:n.product_type}),e[r].quantity+=dn(t.quantity),e[r].revenue+=dn(t.quantity)*dn(t.price_at_purchase)/100}w.topProducts=Object.values(e).sort((e,t)=>t.revenue-e.revenue).slice(0,10)}return{report:w,success:!0}}async function pn(e,t){let n=ee.parse(e),r=M(t),i=await X(n.cmsTarget,t),a=N(i),o=i.contentType===`page`?`pages`:i.contentType===`post`?`posts`:`products`,{data:s,error:c}=await r.from(o).select(`*`).eq(`id`,a).single();if(c||!s)throw Error(`Failed to read current ${i.contentType}: ${I(c)}`);let l=[];if(n.includeBlocks){let e=i.contentType===`page`?`page_id`:i.contentType===`post`?`post_id`:`product_id`,{data:t,error:o}=await r.from(`blocks`).select(`id, page_id, post_id, product_id, language_id, block_type, content, order`).eq(e,a);if(o)throw Error(`Failed to read current ${i.contentType} blocks: ${I(o)}`);l=(Array.isArray(t)?t:[]).slice().sort((e,t)=>Number(e.order)-Number(t.order)).map(e=>ft(e,n.includeBlockContent))}return{blocks:l,context:i,item:s,success:!0}}var mn=new Set([`feature_image_id`,`language_id`,`meta_description`,`meta_title`,`slug`,`status`,`title`]),hn=new Set([`excerpt`,`feature_image_id`,`label`,`language_id`,`meta_description`,`meta_title`,`published_at`,`slug`,`status`,`subtitle`,`title`]),gn=new Set([`description_json`,`language_id`,`meta_description`,`meta_title`,`short_description`,`slug`,`status`,`title`]),_n=new Set([`excerpt`,`feature_image_id`,`label`,`meta_description`,`meta_title`,`published_at`,`short_description`,`subtitle`]);function vn(e){return e===`page`?mn:e===`post`?hn:gn}function yn(e,t){return _n.has(e)&&t===``?null:t}function bn(e,t){if(typeof t!=`string`)return;let n=e===`product`?[`active`,`archived`,`draft`]:[`archived`,`draft`,`published`];if(!n.includes(t))throw Error(`Status "${t}" is not valid for ${e}. Allowed statuses: ${n.join(`, `)}.`)}function xn(e,t){let n=vn(t.contentType),r={};for(let[i,a]of Object.entries(e))if(a!==void 0){if(!n.has(i))throw Error(`Field "${i}" cannot be updated for ${t.contentType} content.`);i===`status`&&bn(t.contentType,a),r[i]=yn(i,a)}return r}async function Sn(e,t){let n=D.parse(e),r=M(t),i=await X(n.cmsTarget,t),a=N(i),o=xn(n.fields,i),s=Object.keys(o);if(s.length===0)throw Error(`update_current_cms_fields requires at least one supported field.`);let c=B({action:`UPDATE CMS FIELDS`,context:t,payload:{contentType:i.contentType,entityId:a,fields:o,tool:`update_current_cms_fields`},preview:{contentType:i.contentType,entityId:a,fields:s,slug:i.slug,title:i.title},subject:`${i.contentType} ${String(a)}`});if(c)return c;let l=await d(t,i.contentType,a);typeof o.feature_image_id==`string`&&(o.feature_image_id=await P(o.feature_image_id,t,typeof i.title==`string`?i.title:void 0));let u=i.contentType===`page`?`pages`:i.contentType===`post`?`posts`:`products`,{data:p,error:m}=await r.from(u).update({...o,updated_at:new Date().toISOString()}).eq(`id`,a).select(`id, language_id, slug, status, title`).single();if(m||!p)throw Error(`Failed to update current ${i.contentType}: ${I(m)}`);return await f(t,i.contentType,a,l),F(t,i,p.slug),{contentType:i.contentType,entityId:a,mutationExecuted:!0,slug:p.slug,success:!0,updatedFields:s}}async function Cn(e,t){let n=O.parse(e),r=M(t),i=await X(n.cmsTarget,t),{data:a,error:o}=await r.from(`blocks`).select(`id, page_id, post_id, product_id, language_id, block_type, content, order`).eq(`id`,n.blockId).single();if(o||!a)throw Error(`Failed to read block ${n.blockId}: ${I(o)}`);$e(a,i),t=await G(t,[a.block_type,a.content,n.content]);let s=nt(a.block_type,`Block ${n.blockId}`,t);rt(n.blockType,s,`Block ${n.blockId}`);let c=dt(s,H(a.content,`Block ${n.blockId}`),n.content,t);K(s,c,`Block ${n.blockId}`,t);let l=B({action:`UPDATE CONTENT BLOCK`,context:t,payload:{blockId:n.blockId,blockType:s,content:c,tool:`update_content_block`},preview:{blockId:n.blockId,blockType:s,contentType:i.contentType,entityId:N(i)},subject:`${s} block ${n.blockId}`});if(l)return l;let u=await d(t,i.contentType,N(i)),{data:p,error:m}=await r.from(`blocks`).update({content:c,updated_at:new Date().toISOString()}).eq(`id`,n.blockId).select(`id, block_type, order`).single();if(m||!p)throw Error(`Failed to update block ${n.blockId}: ${I(m)}`);return await f(t,i.contentType,N(i),u),await Ne({patch:({blocks:e})=>({blocks:e.map(e=>String(e?.id)===String(n.blockId)?{...e,content:c}:e)}),productId:a.product_id,supabase:r}),br([{content:c}],r),F(t,i),{blockId:p.id,blockType:p.block_type,contentUpdated:!0,mutationExecuted:!0,success:!0}}async function wn(e,t){let n=re.parse(e);t=await G(t,n.block);let r=M(t),i=await Y(n,t),a=i.contentType===`product`?i.item.id:Number(i.item.id),o=i.contentType===`page`?`page_id`:i.contentType===`post`?`post_id`:`product_id`,s=async()=>{let{data:e,error:t}=await r.from(`blocks`).select(`id, page_id, post_id, product_id, language_id, block_type, content, order`).eq(o,a);if(t)throw Error(`Failed to read ${i.contentType} blocks: ${I(t)}`);return(Array.isArray(e)?e:[]).sort((e,t)=>Number(e.order)-Number(t.order))},c=e=>{if(n.position===`start`)return 0;if(n.position===`end`){let t=e.map(e=>Number(e.order)).filter(Number.isFinite);return t.length>0?Math.max(...t)+1:0}let t=n.anchorBlockId?e.find(e=>Number(e.id)===n.anchorBlockId):n.anchorBlockType?e.find(e=>e.block_type===n.anchorBlockType):null;if(!t)throw Error(n.anchorBlockType?`Could not find a ${n.anchorBlockType} block to insert ${n.position}.`:`Could not find block ${n.anchorBlockId} to insert ${n.position}.`);let r=Number(t.order);return n.position===`before`?r:r+1},l=Ut(n.block,0,t),u=c(await s()),p={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},m=B({action:`INSERT CONTENT BLOCK`,context:t,payload:{block:l,order:u,target:{contentType:i.contentType,id:i.item.id,slug:i.item.slug},tool:`insert_content_block`},preview:{anchorBlockId:n.anchorBlockId,anchorBlockType:n.anchorBlockType,blockType:l.block_type,contentType:i.contentType,entityId:i.item.id,position:n.position,slug:i.item.slug,summary:`Insert ${l.block_type} block ${n.position} ${n.anchorBlockType?`the first ${n.anchorBlockType} block`:n.anchorBlockId?`block ${n.anchorBlockId}`:`the content`} on ${i.contentType} "${i.item.title||i.item.slug}".`,title:i.item.title},subject:`${l.block_type} block on ${i.contentType} ${i.item.id}`});if(m)return m;let h=await s(),g=c(h),_=h.filter(e=>Number(e.order)>=g).sort((e,t)=>Number(t.order)-Number(e.order)),v=await d(t,i.contentType,a);for(let e of _){let{error:t}=await r.from(`blocks`).update({order:Number(e.order)+1,updated_at:new Date().toISOString()}).eq(`id`,e.id);if(t)throw Error(`Failed to shift block ${e.id}: ${I(t)}`)}let{data:y,error:b}=await r.from(`blocks`).insert({block_type:l.block_type,content:l.content,language_id:i.item.language_id,order:g,page_id:i.contentType===`page`?a:null,post_id:i.contentType===`post`?a:null,product_id:i.contentType===`product`?a:null}).select(`id, block_type, order`).single();if(b||!y)throw Error(`Failed to insert content block: ${I(b)}`);return i.contentType===`product`&&await Ne({patch:({blocks:e})=>({blocks:[...e.map(e=>Number(e?.order)>=g?{...e,order:Number(e.order)+1}:e),{block_type:l.block_type,content:l.content,id:y.id,language_id:i.item.language_id,order:g,page_id:null,post_id:null,product_id:a}].sort((e,t)=>Number(e.order)-Number(t.order))}),productId:a,supabase:r}),await f(t,i.contentType,a,v),br([l],r),F(t,p),{blockId:y.id,blockType:y.block_type,contentType:i.contentType,entityId:i.item.id,mutationExecuted:!0,order:y.order,success:!0}}async function Tn(e,t){let n=k.parse(e),r=M(t),i=await X(n.cmsTarget,t),{data:a,error:o}=await r.from(`blocks`).select(`id, page_id, post_id, product_id, language_id, block_type, content, order`).eq(`id`,n.parentBlockId).single();if(o||!a)throw Error(`Failed to read parent block ${n.parentBlockId}: ${I(o)}`);$e(a,i),t=await G(t,[a.block_type,a.content,n.content]);let s=nt(a.block_type,`Parent block ${n.parentBlockId}`,t);if(s!==`section`)throw Error(`Parent block ${n.parentBlockId} must be a section block, not "${s}".`);let c=H(a.content,`Parent block ${n.parentBlockId}`);K(s,c,`Parent block ${n.parentBlockId}`,t);let l=c.column_blocks?.[n.columnIndex]?.[n.blockIndex];if(!l)throw Error(`Nested block was not found at column ${n.columnIndex}, index ${n.blockIndex}.`);let u=nt(l.block_type,`Nested block ${n.columnIndex}:${n.blockIndex}`,t);rt(n.blockType,u,`Nested block ${n.columnIndex}:${n.blockIndex}`),K(u,n.content,`Nested block ${n.columnIndex}:${n.blockIndex}`,t);let p=c.column_blocks.map((e,t)=>t===n.columnIndex?e.map((e,t)=>t===n.blockIndex?{...e,content:n.content}:e):e),m={...c,column_blocks:p};K(s,m,`Updated parent block ${n.parentBlockId}`,t);let h=B({action:`UPDATE NESTED BLOCK`,context:t,payload:{blockIndex:n.blockIndex,columnIndex:n.columnIndex,content:n.content,nestedBlockType:u,parentBlockId:n.parentBlockId,tool:`update_section_column_block`},preview:{blockIndex:n.blockIndex,columnIndex:n.columnIndex,nestedBlockType:u,parentBlockId:n.parentBlockId,parentBlockType:s},subject:`${u} nested block ${n.columnIndex}:${n.blockIndex}`});if(h)return h;let g=await d(t,i.contentType,N(i)),{data:_,error:v}=await r.from(`blocks`).update({content:m,updated_at:new Date().toISOString()}).eq(`id`,n.parentBlockId).select(`id, block_type`).single();if(v||!_)throw Error(`Failed to update parent block ${n.parentBlockId}: ${I(v)}`);return await Ne({patch:({blocks:e})=>({blocks:e.map(e=>String(e?.id)===String(n.parentBlockId)?{...e,content:m}:e)}),productId:a.product_id,supabase:r}),await f(t,i.contentType,N(i),g),F(t,i),{blockIndex:n.blockIndex,columnIndex:n.columnIndex,mutationExecuted:!0,nestedBlockType:u,parentBlockId:_.id,parentBlockType:_.block_type,success:!0}}async function En(e,t){let n=ie.parse(e);t=await G(t,n.blocks);let r=M(t),i=Ge(t),a=await gt(r,n.languageCode),o=V(n.slug||n.title),s=Gt(n.blocks,n.contactEmail,n.title,t),c=await Kt({contentType:`page`,languageId:a.id,slug:o,supabase:r});if(c)return c;let l=await qt({contentType:`page`,languageCode:a.code,languageId:a.id,suppliedTranslationGroupId:n.translationGroupId,supabase:r});if(l.result)return l.result;let u={blocks:s,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:o,status:n.status,title:n.title,translation_group_id:l.translationGroupId},tool:`create_cms_page`},d=B({action:`CREATE PAGE`,context:t,payload:u,preview:{blockCount:s.length,languageCode:a.code,slug:o,status:n.status,title:n.title,translationGroupId:l.translationGroupId},subject:o});if(d)return d;let f=l.translationGroupId||Ke(),p=await P(u.item.feature_image_id,t,n.title),{data:m,error:h}=await r.from(`pages`).insert({...u.item,author_id:i,feature_image_id:p,translation_group_id:f}).select(`id, language_id, slug, status, title, translation_group_id`).single();if(h||!m?.id)throw Error(`Failed to create page: ${I(h)}`);try{await Jt({blocks:s,contentType:`page`,itemId:Number(m.id),languageId:a.id,supabase:r})}catch(e){throw await Yt({contentType:`page`,itemId:Number(m.id),supabase:r}),e}return F(t,{contentType:`page`,entityId:Number(m.id),languageId:a.id,slug:o,title:n.title},o),t?.revalidatePath?.(`/cms/pages`),{blockCount:s.length,contentType:`page`,editPath:Xt(`page`,m.id),entityId:m.id,mutationExecuted:!0,slug:o,success:!0,title:n.title,translationGroupId:m.translation_group_id}}async function Dn(e,t){let n=ae.parse(e);t=await G(t,n.blocks);let r=M(t),i=Ge(t),a=await gt(r,n.languageCode),o=V(n.slug||n.title),s=Gt(n.blocks,void 0,void 0,t),c=await Kt({contentType:`post`,languageId:a.id,slug:o,supabase:r});if(c)return c;let l=await qt({contentType:`post`,languageCode:a.code,languageId:a.id,suppliedTranslationGroupId:n.translationGroupId,supabase:r});if(l.result)return l.result;let u=n.published_at&&!Number.isNaN(new Date(n.published_at).getTime())?new Date(n.published_at).toISOString():n.published_at??null,d={blocks:s,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:u,slug:o,status:n.status,subtitle:n.subtitle??null,title:n.title,translation_group_id:l.translationGroupId},tool:`create_cms_post`},f=B({action:`CREATE POST`,context:t,payload:d,preview:{blockCount:s.length,languageCode:a.code,slug:o,status:n.status,title:n.title,translationGroupId:l.translationGroupId},subject:o});if(f)return f;let p=l.translationGroupId||Ke(),m=await P(d.item.feature_image_id,t,n.title),{data:h,error:g}=await r.from(`posts`).insert({...d.item,author_id:i,feature_image_id:m,translation_group_id:p}).select(`id, language_id, slug, status, title, translation_group_id`).single();if(g||!h?.id)throw Error(`Failed to create post: ${I(g)}`);try{await Jt({blocks:s,contentType:`post`,itemId:Number(h.id),languageId:a.id,supabase:r})}catch(e){throw await Yt({contentType:`post`,itemId:Number(h.id),supabase:r}),e}return F(t,{contentType:`post`,entityId:Number(h.id),languageId:a.id,slug:o,title:n.title},o),t?.revalidatePath?.(`/cms/posts`),t?.revalidatePath?.(`/articles`),{blockCount:s.length,contentType:`post`,editPath:Xt(`post`,h.id),entityId:h.id,mutationExecuted:!0,slug:o,success:!0,title:n.title,translationGroupId:h.translation_group_id}}function On(e,t){return(t||V(e)||`product`).replace(/-/g,``).slice(0,24).toUpperCase()}function kn(e){if(e==null)return;if(typeof e==`string`)return s.editorDocumentFromHtml(e)??void 0;let t=Array.isArray(e)?{content:e,type:`doc`}:W(e)&&e.type!==`doc`&&Array.isArray(e.content)?{...e,type:`doc`}:e,n=Ce().safeParse(t);if(!n.success){if(W(e)&&typeof e.type==`string`){let t=Ce().safeParse({content:[e],type:`doc`});if(t.success)return t.data}throw 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(e=>e.message).join(`; `)}`)}return n.data}function An(e){let t=e=>!!(e&&Array.isArray(e.content)&&e.content.length>0),n=kn(e.description_json);if(t(n))return n;let r=e.description_html?s.editorDocumentFromHtml(e.description_html):null;return t(r)?r:void 0}async function jn(e,t){let n=oe.parse(e);t=await G(t,n.blocks);let r=M(t),i=await gt(r,n.languageCode),a=V(n.slug||n.title),o=Gt(n.blocks,void 0,void 0,t),s=await Kt({contentType:`product`,languageId:i.id,slug:a,supabase:r});if(s)return s;let c=await qt({contentType:`product`,languageCode:i.code,languageId:i.id,suppliedTranslationGroupId:n.translationGroupId,supabase:r});if(c.result)return c.result;let{createProduct:l,productSchema:u}=await Re(),d=n.product_type===`digital`&&n.payment_provider===`freemius`?n.trial_period_days:0,f=u.parse({description_json:An(n),freemius_plan_id:n.freemius_plan_id||``,freemius_product_id:n.freemius_product_id||``,is_taxable:n.is_taxable,language_id:i.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||On(n.title,a),slug:a,status:n.status,stock:n.stock,title:n.title,trial_period_days:d,trial_requires_payment_method:d>0&&n.trial_requires_payment_method,translation_group_id:c.translationGroupId,upc:n.upc??``,variation_attributes:[],variants:[]}),p=n.images??[],m=B({action:`CREATE PRODUCT`,context:t,payload:{blocks:o,images:p,item:f,tool:`create_cms_product`},preview:{blockCount:o.length,descriptionLength:f.description_json?JSON.stringify(f.description_json).length:0,imageCount:p.length,languageCode:i.code,price:f.price,sku:f.sku,slug:a,status:f.status,stock:f.stock,title:f.title,translationGroupId:c.translationGroupId},subject:a});if(m)return m;let h=[],g=null;if(p.length>0)try{if(h=[...new Set(await je(p,t,n.title))],h.length===0)throw Error(`None of the provided images could be resolved to a media item.`)}catch(e){g=e instanceof Error?e.message:String(e)}let _=await l(r,{...f,product_media:h.map(e=>({media_id:e}))});if(!_?.id)throw Error(`Failed to create product.`);try{await Jt({blocks:o,contentType:`product`,itemId:_.id,languageId:i.id,supabase:r})}catch(e){throw await Yt({contentType:`product`,itemId:_.id,supabase:r}),e}return F(t,{contentType:`product`,entityId:_.id,languageId:i.id,slug:a,title:n.title},a),t?.revalidatePath?.(`/cms/products`),{blockCount:o.length,contentType:`product`,editPath:Xt(`product`,_.id),entityId:_.id,imageCount:h.length,...g?{imageError:g}:{},mutationExecuted:!0,slug:a,success:!0,title:n.title,translationGroupId:_.translation_group_id}}function Mn(e){return e.trim().replace(/[\s-]+/g,`_`).toLowerCase()}function Nn(e,t){let n=typeof t==`string`?Mn(t):t;return e===`product`?n===`public`||n===`publish`||n===`published`?`active`:n:n===`public`||n===`active`||n===`publish`?`published`:n}function Pn(e){let t=Mn(e.field);return!!(e.startsAt||e.endsAt||t.includes(`start`)||t.includes(`end`)||t.includes(`schedule`)||t.includes(`special_date`))}async function Fn(e,t,n){if(e===`price`||e===`sale_price`){if(t==null)return{[e]:null};let r=await _t(n);return{[e]:Xe(Number(t),r)}}if(e===`prices`||e===`sale_prices`){let r=await _t(n);return{[e]:Ze(t,r)}}return e===`description_json`?{description_json:kn(t)}:{[e]:t}}var In=new Set([`language_id`,`price`,`sale_price`,`stock`,`trial_period_days`]),Ln=new Set([`is_taxable`,`trial_requires_payment_method`]);function Rn(e,t){if(typeof t!=`string`)return t;let n=t.trim();if(In.has(e)){if(n.toLowerCase()===`null`)return null;if(n===``)return t;let e=Number(n);return Number.isFinite(e)?e:t}if(Ln.has(e)){let e=n.toLowerCase();if(e===`true`)return!0;if(e===`false`)return!1}return t}function zn(e,t){let n=Mn(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,i=r===`status`?Nn(t.contentType,e.value):Rn(r,e.value);if(t.contentType!==`product`){if(!(t.contentType===`page`?mn:hn).has(r))throw Error(`Field "${e.field}" cannot be updated for ${t.contentType}.`);return r===`status`&&bn(t.contentType,i),{field:r,payload:{[r]:yn(r,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(r))throw Error(`Field "${e.field}" cannot be updated for product.`);if(r===`status`&&bn(`product`,i),(r===`price`||r===`sale_price`)&&i!==null&&(typeof i!=`number`||i<0))throw Error(`${r} must be a non-negative number or null.`);if(r===`stock`&&(!Number.isInteger(i)||Number(i)<0))throw Error(`stock must be a non-negative integer.`);if(r===`trial_period_days`&&(!Number.isInteger(i)||Number(i)<0))throw Error(`trial_period_days must be a non-negative integer.`);if(r===`trial_requires_payment_method`&&typeof i!=`boolean`)throw Error(`trial_requires_payment_method must be a boolean.`);return{field:r,payload:{[r]:i}}}async function Bn(e,t){let n=se.parse(e);if(Pn(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};let r=await Y(n,t),i=zn(n,r),a=i.field,o=i.payload;if(a===`language_id`&&typeof o.language_id==`string`){let e=await J(M(t),o.language_id);o={...o,language_id:e.id}}let s=B({action:`UPDATE FIELD`,context:t,payload:{contentType:r.contentType,entityId:r.item.id,field:a,payload:o,tool:`update_cms_item_field`},preview:{contentType:r.contentType,field:a,from:r.item[a],slug:r.item.slug,title:r.item.title,to:o[a]},subject:`${r.contentType} ${r.item.slug||r.item.id} ${a}`});if(s)return s;let c=await d(t,r.contentType,r.item.id);if(r.contentType===`product`){let e=M(t),n=await Fn(a,o[a],e),{data:i,error:s}=await e.from(`products`).update({...n,updated_at:new Date().toISOString()}).eq(`id`,r.item.id).select(`id, language_id, slug, status, title`).single();if(s||!i)throw Error(`Failed to update product: ${I(s)}`);return F(t,{contentType:`product`,entityId:String(i.id),languageId:i.language_id,slug:i.slug,title:i.title},i.slug),await f(t,`product`,i.id,c),{contentType:`product`,entityId:i.id,field:a,mutationExecuted:!0,slug:i.slug,success:!0,updatedFields:[a]}}a===`feature_image_id`&&typeof o.feature_image_id==`string`&&(o={...o,feature_image_id:await P(o.feature_image_id,t,typeof r.item.title==`string`?r.item.title:void 0)});let l=r.contentType===`page`?`pages`:`posts`,{data:u,error:p}=await M(t).from(l).update({...o,updated_at:new Date().toISOString()}).eq(`id`,r.item.id).select(`id, language_id, slug, status, title`).single();if(p||!u)throw Error(`Failed to update ${r.contentType}: ${I(p)}`);return F(t,{contentType:r.contentType,entityId:Number(u.id),languageId:u.language_id,slug:u.slug,title:u.title},u.slug),await f(t,r.contentType,u.id,c),{contentType:r.contentType,entityId:u.id,field:a,mutationExecuted:!0,slug:u.slug,success:!0,updatedFields:[a]}}async function Vn(e,t){let n=await Y(ce.parse(e),t);if(n.contentType===`product`)return{affectedCount:1,collectionPath:Zt(`product`),contentType:`product`,item:n.item,navigationLinkCount:0,publicPaths:n.item.slug?[`/product/${n.item.slug}`]:[],targetIds:[n.item.id]};let r=n.contentType===`page`?`pages`:`posts`,{data:i,error:a}=await M(t).from(r).select(`id, slug, title, translation_group_id`).eq(`translation_group_id`,n.item.translation_group_id);if(a)throw Error(`Failed to inspect related ${n.contentType}s: ${I(a)}`);let o=Array.isArray(i)?i:[],s=o.map(e=>n.contentType===`page`?e.slug===`home`?`/`:`/${e.slug}`:`/article/${e.slug}`).filter(Boolean),c=new Set(s),{data:l,error:u}=await M(t).from(`navigation_items`).select(`id, url`);if(u)throw Error(`Failed to inspect related navigation links: ${I(u)}`);let d=(Array.isArray(l)?l:[]).filter(e=>c.has(e.url)).length;return{affectedCount:o.length,collectionPath:Zt(n.contentType),contentType:n.contentType,item:n.item,navigationLinkCount:d,publicPaths:s,targetIds:o.map(e=>e.id)}}function Hn(e){let 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}.`;let r=[`${z(e.affectedCount,`language version`)}`,e.navigationLinkCount>0?`${z(e.navigationLinkCount,`navigation link`)}`:null].filter(Boolean);return`Delete ${e.contentType} "${t}"${n}, including ${r.join(` and `)}.`}async function Un(e,t){let n=await Vn(e,t);return{...Ue({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:Hn(n),title:n.item.title},subject:`${n.item.id} ${n.item.slug||``}`}),preparedDelete:!0}}async function Wn(e,t){let n=await Vn(le.parse(e),t),r=B({action:`DELETE ${n.contentType}`,context:t,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:Hn(n),title:n.item.title},subject:`${n.item.id} ${n.item.slug||``}`});if(r)return r;let i=M(t);if(n.contentType===`product`){let{error:e}=await i.from(`products`).delete().eq(`id`,n.item.id);if(e)throw Error(`Failed to delete product: ${I(e)}`)}else{for(let e of n.publicPaths)await i.from(`navigation_items`).delete().eq(`url`,e);let e=n.contentType===`page`?`pages`:`posts`,{error:t}=await i.from(e).delete().eq(`translation_group_id`,n.item.translation_group_id);if(t)throw Error(`Failed to delete ${n.contentType}: ${I(t)}`)}let a=t?.revalidatePath??we();return a&&(a(n.collectionPath),a(`/cms/navigation`),n.publicPaths.forEach(e=>a(e))),{affectedCount:n.affectedCount,collectionPath:n.collectionPath,contentType:n.contentType,mutationExecuted:!0,redirectPath:n.collectionPath,success:!0}}async function Gn(e,t){switch(e.tool){case`create_cms_page`:return En(e.input,t);case`create_cms_post`:return Dn(e.input,t);case`create_cms_product`:return jn(e.input,t);case`delete_cms_item`:return Wn(e.input,t);case`update_cms_item_field`:return Bn(e.input,t);case`update_content_block`:return Cn(e.input,t);case`insert_content_block`:return wn(e.input,t);case`update_current_cms_fields`:return Sn(e.input,t);case`update_footer`:return $t(e.input,t);case`update_navigation_bar`:return Qt(e.input,t);case`update_section_column_block`:return Tn(e.input,t);case`set_content_images`:return Ur(e.input,t)}}function Kn(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;let n=t[e.tool];return n?{...e,input:{...e.input,translationGroupId:n}}:e}function qn(e){return e===`create_cms_page`?`page`:e===`create_cms_post`?`post`:`product`}function Jn(e,t,n){if(e.tool!==`set_content_images`)return e;let r=e.input;if(r.entityId!==void 0)return e;let i=r.slug?t.get(`${r.contentType||`product`}:${V(r.slug)}`):n;return i?{...e,input:{...r,contentType:i.contentType,entityId:i.entityId}}:e}async function Yn(e,t){let n=me.parse(e),r=new Set(n.actions.filter(e=>e.tool===`create_cms_page`||e.tool===`create_cms_post`||e.tool===`create_cms_product`).map(e=>{let t=e.input;return`${qn(e.tool)}:${V(t.slug||t.title||``)}`})),i=e=>{if(e.tool!==`set_content_images`)return!1;let t=e.input;return t.slug?r.has(`${t.contentType||`product`}:${V(t.slug)}`):r.size>0};if(!t?.skipConfirmation){let e=[];for(let r of n.actions){if(i(r)){let t=r.input;e.push(`Set ${z(t.images.length,`image`)} on the ${t.slug?`"${t.slug}"`:`new`} item created in this plan.`);continue}let n=await Gn(r,{...t,latestUserMessage:null});if(!n||typeof n!=`object`)return{message:`Could not prepare action ${e.length+1}.`,mutationExecuted:!1,success:!1};if(n.success===!1||n.unsupported===!0)return n;n.requiresConfirmation===!0&&n.preview?e.push(We(r.tool,n.preview)):e.push(`Run ${r.tool.replace(/_/g,` `)}.`)}let r=n.summary||`Complete ${z(n.actions.length,`CMS action`)}.`,a=B({action:`EXECUTE CMS ACTION PLAN`,context:t,payload:{actions:n.actions,tool:`execute_cms_action_plan`},preview:{actionCount:n.actions.length,actionSummaries:e,summary:r},subject:`${n.actions.length} actions`});if(a)return a}let a={...t,skipConfirmation:!0},o=[],s=!1,c=null,l=null,u={},d=new Map,f=null;for(let[e,t]of n.actions.entries()){let r=Jn(Kn(t,u),d,f),i=await Gn(r,a);if(o.push({output:i,tool:r.tool}),i&&typeof i==`object`){let t=i;if(t.mutationExecuted===!0&&(s=!0),!c&&typeof t.editPath==`string`&&(c=t.editPath),typeof t.redirectPath==`string`&&(l=t.redirectPath),(r.tool===`create_cms_page`||r.tool===`create_cms_post`||r.tool===`create_cms_product`)&&(typeof t.translationGroupId==`string`&&(u[r.tool]=t.translationGroupId),t.entityId!==void 0&&t.entityId!==null)){let e=qn(r.tool),n={contentType:e,entityId:t.entityId};f=n,typeof t.slug==`string`&&d.set(`${e}:${t.slug}`,n)}if(t.success===!1||t.unsupported===!0)return{actionCount:n.actions.length,failedActionIndex:e,failedTool:r.tool,message:typeof t.message==`string`?t.message:`Action ${e+1} failed.`,mutationExecuted:s,results:o,success:!1,...c?{editPath:c}:{},...l?{redirectPath:l}:{}}}}return{actionCount:n.actions.length,editPath:l?void 0:c??void 0,mutationExecuted:s,redirectPath:l??void 0,results:o,success:!0,summary:n.summary??null}}var Xn=u.z.strictObject({maxChars:u.z.number().int().min(500).max(2e4).default(8e3).describe(`Maximum characters of readable body text to return.`),url:u.z.string().trim().min(1).max(2048).refine(e=>/^https?:\/\//i.test(e),`URL must start with http:// or https://.`)}),Zn=12e3,Qn=2e6;function $n(e){return e.replace(/<[^>]+>/g,` `).replace(/&nbsp;/gi,` `).replace(/&amp;/gi,`&`).replace(/&lt;/gi,`<`).replace(/&gt;/gi,`>`).replace(/&quot;/gi,`"`).replace(/&#39;/gi,`'`).replace(/\s+/g,` `).trim()}function er(e){return e.trim().replace(/&amp;/gi,`&`).replace(/&#38;/g,`&`).replace(/&quot;/gi,`"`).replace(/&#39;/g,`'`)}var tr=/\.(avif|gif|jpe?g|png|webp)(?:[?#]|$)/i,nr=/(?:^|[/_-])(?: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 rr(e,t){if(typeof e!=`string`)return null;let n=er(e);if(!n||n.startsWith(`data:`))return null;try{let e=new URL(n,t);return e.protocol!==`http:`&&e.protocol!==`https:`?null:e.toString()}catch{return null}}function ir(e){let t=null;for(let n of e.split(`,`)){let e=n.trim().split(/\s+/),r=e[0];if(!r)continue;let i=e[1]||``,a=i.match(/^(\d+(?:\.\d+)?)w$/i),o=i.match(/^(\d+(?:\.\d+)?)x$/i),s=a?Number(a[1]):o?Number(o[1])*1e3:1;(!t||s>t.weight)&&(t={url:r,weight:s})}return t?.url??null}function $(e,t){let n=e.match(RegExp(`\\b${t}\\s*=\\s*(?:"([^"]*)"|'([^']*)'|([^\\s>]+))`,`i`));return n?n[1]??n[2]??n[3]??null:null}function ar(e,t){let n=[],r=[],i=(e,n)=>{if(typeof e==`string`){let r=rr(e,t);r&&n.push(r);return}if(Array.isArray(e)){for(let t of e)i(t,n);return}e&&typeof e==`object`&&(i(e.url,n),i(e.contentUrl,n))},a=(e,t)=>{if(t>8||!e||typeof e!=`object`)return;if(Array.isArray(e)){for(let n of e)a(n,t+1);return}let o=e,s=o[`@type`],c=(Array.isArray(s)?s:[s]).filter(e=>typeof e==`string`).map(e=>e.toLowerCase()).some(e=>e===`product`||e===`productgroup`||e===`itempage`);`image`in o&&i(o.image,c?n:r);for(let e of Object.values(o))a(e,t+1)},o=e.matchAll(/<script\b[^>]*type\s*=\s*["']application\/ld\+json["'][^>]*>([\s\S]*?)<\/script>/gi);for(let e of o){let t=(e[1]||``).trim();if(t)try{a(JSON.parse(t),0)}catch{}}return[...n,...r]}var or=/(?:^|[/_-])(?:thumbnails?|thumbs?|small|mini)(?:[/_.-]|$)/i;function sr(e){try{let{pathname:t}=new URL(e);return decodeURIComponent(t.slice(t.lastIndexOf(`/`)+1)).toLowerCase()||null}catch{return null}}function cr(e,t){let n=new Map;for(let r of e.matchAll(/<a\b[^>]*>/gi)){let e=rr($(r[0],`href`),t);if(!e||!tr.test(e)||or.test(e)||nr.test(e))continue;let i=sr(e);i&&!n.has(i)&&n.set(i,e)}return n}function lr(e,t){let n=[...ar(e,t)];for(let r of[/<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(let i of e.matchAll(r)){let e=i[0],r=rr($(e,`content`)||$(e,`href`),t);r&&n.push(r)}let r=[];for(let n of e.matchAll(/<img\b[^>]*>/gi)){let e=n[0],i=$(e,`srcset`)||$(e,`data-srcset`),a=[i?ir(i):null,$(e,`src`),$(e,`data-src`),$(e,`data-original`),$(e,`data-lazy-src`),$(e,`data-image`)],o=null;for(let e of a)if(o=rr(e,t),o)break;if(!o||nr.test(o))continue;let s=Number($(e,`width`));Number.isFinite(s)&&s>0&&s<200||r.push(o)}let i=e=>tr.test(e);n.push(...r.filter(i),...r.filter(e=>!i(e)));let a=cr(e,t),o=e=>{if(!or.test(e))return e;let t=sr(e);return t&&a.get(t)||e},s=new Set,c=[];for(let e of n){let t=o(e);if(!s.has(t)&&(s.add(t),c.push(t),c.length>=12))break}return{images:c,mainImage:c[0]??null}}function ur(e,t,n){let 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:i,mainImage:a}=lr(e,n),o=e.match(/<title\b[^>]*>([\s\S]*?)<\/title>/i),s=e.match(/<meta[^>]+name=["']description["'][^>]*content=["']([^"']*)["'][^>]*>/i)||e.match(/<meta[^>]+content=["']([^"']*)["'][^>]*name=["']description["'][^>]*>/i),c=[...r.matchAll(/<h([1-3])\b[^>]*>([\s\S]*?)<\/h\1>/gi)].map(e=>$n(e[2])).filter(Boolean).slice(0,40),l=$n(r.match(/<body\b[^>]*>([\s\S]*?)<\/body>/i)?.[1]??r);return{description:s?$n(s[1]):``,headings:c,images:i,mainImage:a,text:l.slice(0,t),title:o?$n(o[1]):``,truncated:l.length>t}}async function dr(e){let t=Xn.parse(e),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(a.isBlockedFetchHost(n.hostname))return{message:`Refusing to fetch a local, private, or internal address.`,success:!1,url:t.url};let r=new AbortController,i=setTimeout(()=>r.abort(),Zn);try{let e=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(!e.ok)return{message:`The URL responded with HTTP ${e.status}.`,status:e.status,success:!1,url:t.url};let i=e.url||n.toString();try{if(a.isBlockedFetchHost(new URL(i).hostname))return{message:`The URL redirected to a blocked internal address.`,success:!1,url:t.url}}catch{}let o=e.headers.get(`content-type`)||``;if(!/text\/html|text\/plain|application\/xhtml/i.test(o))return{contentType:o,message:`The URL is not an HTML or text page (content-type: ${o||`unknown`}).`,success:!1,url:t.url};let s=await e.text(),c=ur(s.length>Qn?s.slice(0,Qn):s,t.maxChars,i);return!c.text&&!c.title?{message:`The URL returned no readable text content.`,success:!1,url:t.url}:{description:c.description,finalUrl:i,headings:c.headings,images:c.images,mainImage:c.mainImage,success:!0,text:c.text,title:c.title,truncated:c.truncated,url:t.url}}catch(e){return{message:e instanceof Error&&(e.name===`AbortError`||/abort/i.test(e.message))?`Fetching the URL timed out.`:`Failed to fetch the URL: ${I(e)}`,success:!1,url:t.url}}finally{clearTimeout(i)}}var fr=u.z.strictObject({count:u.z.number().int().min(1).max(15).default(6),orientation:u.z.enum([`landscape`,`portrait`,`square`]).optional().describe(`Preferred image orientation. Use landscape for hero/section backgrounds.`),query:u.z.string().trim().min(2).max(200).describe(`What the photos should depict, e.g. "herbal supplements".`)}),pr=12e3;async function mr(e){let t=null,n=null;if(e)try{let{CORTEX_AI_PEXELS_SETTING_KEY:r,CORTEX_AI_UNSPLASH_SETTING_KEY:i,decryptStoredOpenRouterApiKey:a}=await Promise.resolve().then(()=>require("./ai-config.cjs")),o=e=>{if(!e)return null;try{let t=a(e);return typeof t==`string`&&t.trim()?t.trim():null}catch{return null}},{data:s}=await e.from(`site_settings`).select(`key, value`).in(`key`,[r,i]),c=Array.isArray(s)?s:[];t=o(c.find(e=>e.key===r)?.value),n=o(c.find(e=>e.key===i)?.value)}catch{}t||=process.env.PEXELS_API_KEY?.trim()||null,n||=process.env.UNSPLASH_ACCESS_KEY?.trim()||null;let r=[];return t&&r.push({apiKey:t,provider:`pexels`}),n&&r.push({apiKey:n,provider:`unsplash`}),r}async function hr(e){return(await mr(e))[0]??null}async function gr(e){if(e)try{let{CORTEX_AI_UNSPLASH_APP_NAME_SETTING_KEY:t}=await Promise.resolve().then(()=>require("./ai-config.cjs")),{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 _r(e,t){let n=new AbortController,r=setTimeout(()=>n.abort(),pr);try{let r=await fetch(e,{headers:t,signal:n.signal});if(!r.ok)throw Error(`Stock photo provider responded with HTTP ${r.status}.`);return await r.json()}finally{clearTimeout(r)}}function vr(e){let t=Number(e);return Number.isFinite(t)&&t>0?t:null}function yr(e,t){if(!W(e))return;let n=e=>{W(e)&&e.provider===`unsplash`&&typeof e.downloadLocation==`string`&&e.downloadLocation.trim()&&t.add(e.downloadLocation.trim())};if(n(e.attribution),W(e.background)&&W(e.background.image)&&n(e.background.image.attribution),Array.isArray(e.column_blocks)){for(let n of e.column_blocks)if(Array.isArray(n))for(let e of n)W(e)&&yr(e.content,t)}if(Array.isArray(e.slides))for(let n of e.slides)yr(n,t)}async function br(e,t){try{let n=new Set;for(let t of e)yr(t?.content,n);if(n.size===0)return;let r=(await mr(t)).find(e=>e.provider===`unsplash`);if(!r)return;await Promise.all([...n].map(e=>fetch(e,{headers:{Authorization:`Client-ID ${r.apiKey}`}}).catch(()=>void 0)))}catch{}}async function xr(e,t,n){let r=new URLSearchParams({per_page:String(t.count),query:t.query});if(t.orientation&&r.set(`orientation`,t.orientation),e.provider===`pexels`){let n=await _r(`https://api.pexels.com/v1/search?${r.toString()}`,{Authorization:e.apiKey});return(Array.isArray(n?.photos)?n.photos:[]).map(e=>{let n=typeof e?.photographer==`string`?e.photographer:null;return{alt:typeof e?.alt==`string`&&e.alt.trim()?e.alt.trim():t.query,credit:n?`Photo by ${n} on Pexels`:`Photo on Pexels`,downloadLocation:null,height:vr(e?.height),photographer:n,photographerUrl:typeof e?.photographer_url==`string`?e.photographer_url:null,provider:`pexels`,sourceUrl:typeof e?.url==`string`?e.url:null,thumbnailUrl:e?.src?.medium||e?.src?.large||null,url:e?.src?.large2x||e?.src?.large||e?.src?.original||null,width:vr(e?.width)}}).filter(e=>typeof e.url==`string`)}let i=await _r(`https://api.unsplash.com/search/photos?${r.toString()}`,{Authorization:`Client-ID ${e.apiKey}`});return(Array.isArray(i?.results)?i.results:[]).map(e=>{let r=typeof e?.user?.name==`string`?e.user.name:null;return{alt:typeof e?.alt_description==`string`&&e.alt_description.trim()||typeof e?.description==`string`&&e.description.trim()||t.query,credit:r?`Photo by ${r} on Unsplash`:`Photo on Unsplash`,downloadLocation:typeof e?.links?.download_location==`string`?e.links.download_location:null,height:vr(e?.height),photographer:r,photographerUrl:typeof e?.user?.links?.html==`string`?e.user.links.html:null,provider:`unsplash`,sourceUrl:typeof e?.links?.html==`string`?e.links.html:null,thumbnailUrl:e?.urls?.small||e?.urls?.thumb||null,url:e?.urls?.regular||e?.urls?.full||e?.urls?.raw||null,utmSource:n||null,width:vr(e?.width)}}).filter(e=>typeof e.url==`string`)}async function Sr(e,t){let n=fr.parse(e),r=await mr(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};let i=r.some(e=>e.provider===`unsplash`)?await gr(t?.supabase):null,a=[],o=null;for(let e of r){a.push(e.provider);try{let t=await xr(e,n,i);if(t.length>0)return{attemptedProviders:a,photos:t,provider:e.provider,query:n.query,success:!0,usageGuidance:e.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). Also copy the photo\'s `width` and `height` into the image content: the page then reserves the right space before the file loads instead of shifting.':'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. Also copy each photo `width` and `height` into the image content: the page then reserves the right space before the file loads instead of shifting.'}}catch(e){o=e}}return{attemptedProviders:a,message:o?`Stock photo search failed across ${a.join(`, `)}: ${I(o)}`:`No matching stock photos found for "${n.query}".`,photos:[],success:!1}}var Cr=T.extend({blocks:u.z.array(A).min(1).max(20),meta:u.z.strictObject({meta_description:u.z.string().max(500).nullable().optional(),meta_title:u.z.string().max(160).nullable().optional(),slug:u.z.string().trim().min(1).max(300).optional(),status:u.z.enum([`draft`,`published`,`archived`]).optional(),title:u.z.string().trim().min(1).max(300).optional()}).partial().optional()}),wr=[`custom_canonical`,`excerpt`,`feature_image_id`,`label`,`language_id`,`meta_description`,`meta_title`,`published_at`,`slug`,`status`,`subtitle`,`title`,`translation_group_id`];function Tr(e){let t={};for(let n of wr)n in e&&e[n]!==void 0&&(t[n]=e[n]);return t}function Er(e,t){if(!t)return null;let n=e===`page`?t===`home`?`/`:`/${t}`:`/article/${t}`;return`/api/draft/start?path=${encodeURIComponent(n)}`}async function Dr(e,t){let n=Cr.parse(e);t=await G(t,n.blocks);let r=M(t),i=Ge(t),a=await Y(n,t);if(a.contentType===`product`)throw Error(`rewrite_page_draft supports pages and posts only. Products use description_json, not page blocks.`);let o=a.contentType,s=Number(a.item.id);if(!Number.isInteger(s)||s<=0)throw Error(`Could not resolve a valid page/post id for the draft rewrite.`);let c=Number(a.item.language_id);if(!Number.isInteger(c)||c<=0)throw Error(`The target page/post is missing a language id.`);let l=Gt(n.blocks,void 0,void 0,t).map((e,t)=>({block_type:e.block_type,content:e.content,language_id:c,order:t,page_id:o===`page`?s:null,post_id:o===`post`?s:null,product_id:null})),u=Tr(a.item);if(n.meta)for(let[e,t]of Object.entries(n.meta))t!==void 0&&(u[e]=t);let d=Pe(typeof u.slug==`string`?u.slug:a.item.slug),f=typeof u.title==`string`&&u.title.trim()?u.title:String(a.item.title||d||`Untitled`),p=o===`page`?`/cms/pages/${s}/edit`:`/cms/posts/${s}/edit`,m=Er(o,d),h=B({action:`REWRITE DRAFT`,context:t,payload:{blocks:l,meta:u,parent_id:s,parent_type:o,tool:`rewrite_page_draft`},preview:{blockCount:l.length,contentType:o,slug:d,summary:`Stage a Live Draft that replaces the ${o} "${f}" with ${z(l.length,`new block`)}. Nothing goes live until you review the draft and click Publish (which also saves a revision snapshot).`,title:f},subject:`${o}-${s}`});if(h)return h;let g=Number(a.item.version)||1,{error:_}=await r.from(`content_drafts`).delete().eq(`parent_type`,o).eq(`parent_id`,s);if(_)throw Error(`Failed to clear the existing draft: ${I(_)}`);let{error:v}=await r.from(`content_drafts`).insert({author_id:i,base_version:g,blocks:l,meta:u,parent_id:s,parent_type:o});if(v)throw Error(`Failed to save the draft: ${I(v)}`);return br(l,r),F(t,{contentType:o,entityId:s,languageId:c,slug:d,title:f},d),{blockCount:l.length,contentType:o,draftPreviewPath:m,editPath:p,entityId:s,isDraft:!0,mutationExecuted:!0,slug:d,success:!0,title:f}}var Or=u.z.strictObject({attributes:u.z.array(u.z.strictObject({name:u.z.string().trim().min(1).max(120).describe(`Attribute name, e.g. "Size" or "Flavour".`),terms:u.z.array(u.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:u.z.union([u.z.number().int().positive(),u.z.string().trim().min(1).max(120)]).optional(),mode:u.z.enum([`replace`,`append`]).default(`replace`).describe(`"replace" removes the product's existing variants first; "append" keeps them and adds these.`),slug:u.z.string().trim().min(1).max(300).optional(),title:u.z.string().trim().min(1).max(300).optional(),variants:u.z.array(u.z.strictObject({image:u.z.string().trim().min(1).max(2048).optional().describe(`Variant-specific image: an https:// URL (imported automatically) or a media library id.`),options:u.z.record(u.z.string(),u.z.string()).describe(`Which term this variant is, per attribute, e.g. { "Size": "500 ml" }. Every attribute must be given a value.`),price:u.z.number().min(0).optional().describe(`Price in major units (25 = $25.00). Defaults to the product price.`),sale_price:u.z.number().min(0).nullable().optional().describe(`Sale price in major units, or null for none.`),sku:u.z.string().trim().min(1).max(120).describe(`Unique SKU for this variant.`),stock:u.z.number().int().min(0).default(0),upc:u.z.string().trim().max(120).nullable().optional()})).min(1).max(50)});async function kr(e,t){let n=V(t.name),{data:r}=await e.from(`product_attributes`).select(`id`).eq(`slug`,n).maybeSingle(),i=r?.id;if(!i){let{data:r,error:a}=await e.from(`product_attributes`).insert({name:t.name,slug:n}).select(`id`).single();if(a||!r?.id)throw Error(`Could not create the "${t.name}" attribute: ${I(a)}`);i=r.id}let a=new Map;for(let n=0;n<t.terms.length;n+=1){let r=t.terms[n],o=V(r),{data:s}=await e.from(`product_attribute_terms`).select(`id`).eq(`attribute_id`,i).eq(`slug`,o).maybeSingle();if(s?.id){a.set(r,s.id);continue}let{data:c,error:l}=await e.from(`product_attribute_terms`).insert({attribute_id:i,slug:o,sort_order:n,value:r}).select(`id`).single();if(l||!c?.id)throw Error(`Could not create the "${r}" option: ${I(l)}`);a.set(r,c.id)}return{attributeId:i,termIdByValue:a}}async function Ar(e,t){let n=Or.parse(e),r=M(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),o=B({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`} ${z(n.variants.length,`variant`)} on "${i.title}". Product stock becomes the sum of variant stock.`,title:i.title},subject:`product-${a}-variants`});if(o)return o;let s=new Map;for(let e of n.attributes??[]){let{termIdByValue:t}=await kr(r,e);s.set(e.name,t)}for(let e of n.variants)for(let[t,n]of Object.entries(e.options)){if(s.get(t)?.has(n))continue;let{data:e}=await r.from(`product_attributes`).select(`id`).eq(`slug`,V(t)).maybeSingle();if(!e?.id)throw Error(`Unknown attribute "${t}". Pass it in \`attributes\` with its full list of terms.`);let{data:i}=await r.from(`product_attribute_terms`).select(`id`).eq(`attribute_id`,e.id).eq(`slug`,V(n)).maybeSingle();if(!i?.id)throw Error(`Unknown option "${n}" for attribute "${t}". Add it to that attribute's \`terms\`.`);let a=s.get(t)??new Map;a.set(n,i.id),s.set(t,a)}if(n.mode===`replace`){let{error:e}=await r.from(`product_variants`).delete().eq(`product_id`,a);if(e)throw Error(`Could not clear the existing variants: ${I(e)}`)}let c=await _t(r),l=Number(i.price)||0,u=[];for(let e of n.variants){let n=e.image?await P(e.image,t,`${i.title} ${e.sku}`):null,{data:o,error:d}=await r.from(`product_variants`).insert({main_media_id:n,price:e.price===void 0?l:Xe(e.price,c),product_id:a,sale_price:e.sale_price===void 0||e.sale_price===null?null:Xe(e.sale_price,c),sku:e.sku,stock_quantity:e.stock,upc:e.upc??null}).select(`id`).single();if(d||!o?.id)throw Error(`Could not create variant "${e.sku}": ${I(d)}`);let f=Object.entries(e.options).map(([e,t])=>({attribute_term_id:s.get(e)?.get(t),variant_id:o.id}));if(f.length>0){let{error:t}=await r.from(`variant_attribute_mapping`).insert(f);if(t)throw Error(`Could not link variant "${e.sku}" to its options: ${I(t)}`)}u.push(e.sku)}let{data:d}=await r.from(`product_variants`).select(`stock_quantity`).eq(`product_id`,a),f=(d??[]).reduce((e,t)=>e+(Number(t?.stock_quantity)||0),0),{error:p}=await r.from(`products`).update({stock:f}).eq(`id`,a);if(p)throw Error(`Variants saved, but the product stock total failed: ${I(p)}`);return F(t,{contentType:`product`,entityId:a,slug:i.slug,title:i.title},i.slug),{contentType:`product`,entityId:a,mode:n.mode,mutationExecuted:!0,skus:u,slug:i.slug,success:!0,totalStock:f,variantCount:u.length}}var jr=u.z.strictObject({items:u.z.array(u.z.strictObject({contentType:u.z.enum([`page`,`post`]).default(`page`),slug:u.z.string().trim().min(1).max(300).describe(`Slug of the source page or post.`),title:u.z.string().trim().min(1).max(300).optional().describe(`Translated title. Defaults to translating the source title.`),translations:u.z.record(u.z.string(),u.z.string()).describe(`Source string -> translated string for every visible string in THIS item.`)})).min(1).max(25),targetLanguageCode:u.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 Mr(e,t){let n=jr.parse(e),r=B({action:`TRANSLATE BULK`,context:t,payload:{count:n.items.length,language:n.targetLanguageCode},preview:{contentType:`page`,summary:`Create ${n.targetLanguageCode} translations of ${z(n.items.length,`item`)}: ${n.items.map(e=>e.slug).join(`, `)}.`,title:`Bulk translate to ${n.targetLanguageCode}`},subject:`bulk-translate-${n.targetLanguageCode}`});if(r)return r;let i=[],a=[];for(let e of n.items)try{let r=await Hr({cmsTarget:{contentType:e.contentType,slug:e.slug},targetLanguageCode:n.targetLanguageCode,...e.title?{title:e.title}:{},translations:e.translations},t);i.push({slug:e.slug,...r})}catch(t){a.push({error:t instanceof Error?t.message:String(t),slug:e.slug})}return{failed:a,failedCount:a.length,mutationExecuted:i.length>0,success:a.length===0,targetLanguageCode:n.targetLanguageCode,translated:i,translatedCount:i.length}}var Nr=u.z.strictObject({action:u.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:u.z.enum([`page`,`post`]).optional(),entityId:u.z.union([u.z.number().int().positive(),u.z.string().trim().min(1).max(120)]).optional(),slug:u.z.string().trim().min(1).max(300).optional(),title:u.z.string().trim().min(1).max(300).optional()}),Pr=[`title`,`slug`],Fr=[`custom_canonical`,`feature_image_id`,`meta_description`,`meta_title`];async function Ir(e,t){let n=Nr.parse(e),r=M(t),i=await X({...n.contentType?{contentType:n.contentType}:{},...n.entityId===void 0?{}:{entityId:n.entityId},...n.slug?{slug:n.slug}:{},...n.title?{title:n.title}:{}},t);if(i.contentType===`product`)throw Error(`publish_content_draft supports pages and posts. Product drafts live in product_drafts and are published from the product editor.`);let a=i.contentType,o=De(i),s=a===`page`?`pages`:`posts`,{data:c,error:l}=await r.from(`content_drafts`).select(`*`).eq(`parent_type`,a).eq(`parent_id`,o).maybeSingle();if(l)throw Error(`Failed to read the draft: ${I(l)}`);if(!c)return{contentType:a,entityId:o,message:`No Live Draft exists for ${a} "${i.title||i.slug}". Nothing to ${n.action}.`,mutationExecuted:!1,success:!1};let u=i.title||i.slug||`${a} ${o}`,p=B({action:n.action===`publish`?`PUBLISH DRAFT`:`DISCARD DRAFT`,context:t,payload:{action:n.action,contentType:a,entityId:String(o)},preview:{contentType:a,slug:i.slug,summary:n.action===`publish`?`Publish the Live Draft for ${a} "${u}", replacing its live blocks. A revision snapshot is saved first, so this is reversible from Revision History.`:`Discard the Live Draft for ${a} "${u}". The live content is left untouched.`,title:i.title},subject:`${a}-${o}-draft`});if(p)return p;let m=c.meta??{},h=Array.isArray(c.blocks)?c.blocks:[];if(n.action===`discard`){let{error:e}=await r.from(`content_drafts`).delete().eq(`id`,c.id);if(e)throw Error(`Failed to discard the draft: ${I(e)}`);return F(t,i,i.slug),{action:`discard`,contentType:a,entityId:o,mutationExecuted:!0,success:!0}}let g=await d(t,a,o),_={};for(let e of Pr){let t=m[e];typeof t==`string`&&t.trim()&&(_[e]=t.trim())}for(let e of Fr)if(Object.prototype.hasOwnProperty.call(m,e)){let t=m[e];_[e]=typeof t==`string`&&t.trim()?t.trim():null}if(Object.keys(_).length>0){let{error:e}=await r.from(s).update(_).eq(`id`,o);if(e)throw Error(`Failed to apply the draft metadata: ${I(e)}`)}let v=a===`page`?`page_id`:`post_id`,{error:y}=await r.from(`blocks`).delete().eq(v,o);if(y)throw Error(`Failed to clear the live blocks: ${I(y)}`);let b=Number(m.language_id)||Number(i.languageId)||Number(h[0]?.language_id)||0;if(h.length>0){let e=h.map((e,t)=>({block_type:e?.block_type,content:e?.content??{},language_id:Number(e?.language_id)||b,order:Number.isFinite(e?.order)?e.order:t,page_id:a===`page`?o:null,post_id:a===`post`?o:null,product_id:null})),{error:t}=await r.from(`blocks`).insert(e);if(t)throw Error(`Failed to publish the draft blocks: ${I(t)}`)}await f(t,a,o,g);let{error:x}=await r.from(`content_drafts`).delete().eq(`id`,c.id),S=typeof _.slug==`string`?_.slug:i.slug;return F(t,{...i,slug:S},S??void 0),{action:`publish`,blockCount:h.length,contentType:a,entityId:o,mutationExecuted:!0,slug:S,success:!0,...x?{warning:`Published, but the draft row was not removed: ${I(x)}`}:{}}}var Lr=new Set([`alt_text`,`author_name`,`author_title`,`caption`,`html_content`,`label`,`placeholder`,`quote`,`submit_button_text`,`success_message`,`text`,`text_content`,`title`]);function Rr(e,t,n){if(!e)return e;if(Object.prototype.hasOwnProperty.call(t,e))return t[e];let r=e.trim();if(r!==e&&Object.prototype.hasOwnProperty.call(t,r))return e.replace(r,t[r]);let i=e;for(let[e,t]of n)e&&i.includes(e)&&(i=i.split(e).join(t));return i}function zr(e,t,n,r){if(Array.isArray(e))return e.map(e=>zr(e,t,n,r));if(e&&typeof e==`object`){let i={};for(let[a,o]of Object.entries(e))i[a]=typeof o==`string`&&(Lr.has(a)||r?.has(a))?Rr(o,t,n):o&&typeof o==`object`?zr(o,t,n,r):o;return i}return e}function Br(e,n){if(typeof e!=`string`||t.isValidBlockType(e))return;let r=et(e,n);if(r)return new Set(t.readCustomBlockFields(r).filter(e=>e.type===`text`||e.type===`rich-text`).map(e=>e.key))}var Vr=u.z.strictObject({cmsTarget:E,targetLanguageCode:u.z.string().trim().min(2).max(80).describe(`Target language code or name, e.g. "fr" or "French".`),title:u.z.string().trim().min(1).max(300).optional().describe(`Translated page title (defaults to translating the source title).`),translations:u.z.record(u.z.string(),u.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 Hr(e,t){let n=Vr.parse(e),r=await X(n.cmsTarget,t);if(r.contentType===`product`)throw Error(`translate_page supports pages and posts only.`);let i=M(t),a=De(r),o=r.contentType===`page`?`pages`:`posts`,s=r.contentType===`page`?`page_id`:`post_id`,{data:c,error:l}=await i.from(o).select(`*`).eq(`id`,a).single();if(l||!c)throw Error(`Could not read the source ${r.contentType} to translate: ${I(l)}`);let{data:u,error:d}=await i.from(`blocks`).select(`id, block_type, content, order`).eq(s,a);if(d)throw Error(`Could not read the source blocks: ${I(d)}`);let f=(Array.isArray(u)?u:[]).slice().sort((e,t)=>Number(e.order)-Number(t.order));if(f.length===0)throw Error(`The source ${r.contentType} has no content blocks to translate.`);t=await G(t,f);let p=n.translations||{},m=Object.entries(p).filter(([e])=>!!e).sort((e,t)=>t[0].length-e[0].length),h=f.map((e,n)=>({blockType:e.block_type,content:zr(U(e.content),p,m,Br(e.block_type,t)),order:n})),g=await gt(i,n.targetLanguageCode),_=String(c.title||``),v=n.title||Rr(_,p,m)||_||`Untitled`,y=e=>typeof e==`string`&&e.trim()?Rr(e,p,m):void 0,b=V(v)||c.slug||`translated-page`,x={blocks:h,feature_image_id:c.feature_image_id??void 0,languageCode:g.code,meta_description:y(c.meta_description),meta_title:y(c.meta_title),slug:b,status:`published`,title:v,translationGroupId:c.translation_group_id||void 0},S=r.contentType===`post`?{...x,excerpt:y(c.excerpt),label:y(c.label),published_at:c.published_at??new Date().toISOString(),subtitle:y(c.subtitle)}:x,C=B({action:`TRANSLATE`,context:t,payload:{createInput:S,sourceId:c.id,tool:`translate_page`},preview:{blockCount:h.length,contentType:r.contentType,languageCode:g.code,slug:x.slug,status:x.status,summary:`Publish a ${g.code.toUpperCase()} translation of "${_}" — it goes live immediately, linked to the original ${r.contentType}, at /${x.slug} with ${z(h.length,`translated block`)}.`,title:v},subject:`translate ${r.contentType} ${c.id} to ${g.code}`});if(C)return C;let w={...t,skipConfirmation:!0};return{...r.contentType===`post`?await Dn(S,w):await En(S,w),isTranslation:!0,languageCode:g.code}}async function Ur(e,t){let n=j.parse(e),r=n.entityId!==void 0||!!n.slug||!!n.title,i=M(t),a,o;if(r){let e=await Y({contentType:n.contentType,entityId:n.entityId,slug:n.slug,title:n.title},t),r=e.item;o=r.id,a={contentType:e.contentType,entityId:o,slug:typeof r.slug==`string`?r.slug:``,title:typeof r.title==`string`?r.title:``}}else a=Ee(t),o=N(a);let s=a.title||a.slug||`current item`,c=a.contentType===`product`,l=B({action:`SET IMAGES`,context:t,payload:{contentType:a.contentType,entityId:String(o),images:n.images,tool:`set_content_images`},preview:{contentType:a.contentType,imageCount:n.images.length,slug:a.slug,summary:c?`Set ${z(n.images.length,`image`)} on product "${s}" (the first becomes the main product image, the rest the gallery).`:`Set the feature image on the ${a.contentType} "${s}".`,title:a.title},subject:`set images on ${a.contentType} ${String(o)}`});if(l)return l;let u=await je(n.images,t,s);if(u.length===0)throw Error(`None of the provided images could be resolved to a media item.`);if(c){let{data:e,error:n}=await i.from(`products`).select(`id, slug, language_id, title`).eq(`id`,o).maybeSingle();if(n||!e)throw Error(`Could not load the product to set images: ${I(n)}`);let r=await Me({mediaIds:u,productId:o,supabase:i});return await Ne({patch:({meta:e})=>Array.isArray(e.product_media)?{meta:{...e,product_media:r.map((e,t)=>({media_id:e,sort_order:t}))}}:{},productId:o,supabase:i}),F(t,{contentType:`product`,entityId:String(o),languageId:e.language_id,slug:e.slug,title:e.title},e.slug),t?.revalidatePath?.(`/cms/products`),{contentType:`product`,entityId:o,imageCount:r.length,mutationExecuted:!0,slug:e.slug,success:!0}}let p=await d(t,a.contentType,o),m=a.contentType===`page`?`pages`:`posts`,{data:h,error:g}=await i.from(m).update({feature_image_id:u[0],updated_at:new Date().toISOString()}).eq(`id`,o).select(`id, language_id, slug, status, title`).single();if(g||!h)throw Error(`Failed to set the feature image: ${I(g)}`);return await f(t,a.contentType,o,p),F(t,a,h.slug),{contentType:a.contentType,entityId:o,extraImagesIgnored:u.length-1,imageCount:1,mutationExecuted:!0,slug:h.slug,success:!0}}function Wr(t){return{...n.createCortexDatabaseAgentTools(t),...e.createCortexCustomBlockTools(t),...o.createCortexContentOpsTools(t),...r.createCortexThemingTools(t),...i.createCortexSiteTools(t),fetch_ecommerce_stats:(0,c.tool)({description:`Fetch quantitative ecommerce statistics and reports from the database. Use this to answer questions about revenue, order counts, order status counts such as pending or trial, and top-selling products over a time range. This tool is read-only and does not require confirmation.`,execute:e=>fn(e,t),inputSchema:S,strict:!0}),read_current_cms_item:(0,c.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:e=>pn(e,t),inputSchema:ee,strict:!0}),search_documentation:(0,c.tool)({description:`Search the NextBlock documentation database and return concise source snippets for factual CMS guidance.`,execute:e=>an(e,t),inputSchema:x,strict:!0}),fetch_url_content:(0,c.tool)({description:"Fetch an external web page and return its title, meta description, headings, body text, AND its images: `mainImage` (the page's subject image — schema.org Product image, else og:image, else the best in-body <img>) plus a ranked `images` list, all as absolute URLs. Read-only, no confirmation. Use this first whenever the user references an external URL to copy, adapt, clone, or draw inspiration from. To reuse the source page's image, pass `mainImage` straight into create_cms_product `images` or a page/post `feature_image_id` — it is imported into the media library automatically. Never invent an image URL: if `mainImage` is null, the page had none.",execute:e=>dr(e),inputSchema:Xn,strict:!0}),search_stock_photos:(0,c.tool)({description:"Find relevant, free, high-quality stock photos (Unsplash/Pexels) for page imagery. Returns a list of photos each with a direct image `url`, `width`, `height`, `alt`, and `photographer`. Read-only, zero cost. Use the returned `url` directly as an image block's external_url (copy `width` and `height` into the same image content, so the page does not shift while the photo loads) 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:e=>Sr(e,t),inputSchema:fr,strict:!0}),manage_product_variants:(0,c.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:e=>Ar(e,t),inputSchema:Or,strict:!0}),translate_content_bulk:(0,c.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:e=>Mr(e,t),inputSchema:jr,strict:!0}),publish_content_draft:(0,c.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:e=>Ir(e,t),inputSchema:Nr,strict:!0}),rewrite_page_draft:(0,c.tool)({description:'Replace ALL blocks of an existing page or post with a brand-new set of blocks, staged as a Live Draft (content_drafts) that the user previews before publishing. Use this for whole-page redesigns/rewrites such as "rewrite my home page with 5 sections". Provide the complete new list of top-level blocks in `blocks` (usually section blocks for a landing/home page, each with nested heading/text/button blocks). Nothing goes live until the user publishes the draft, and publishing auto-creates a revision snapshot so the change is reversible. Mutating: first returns a confirmation phrase; only stages the draft after the user replies with the exact phrase.',execute:e=>Dr(e,t),inputSchema:Cr,strict:!0}),translate_page:(0,c.tool)({description:'Translate the CURRENT page or post into another language. This copies the source page\'s entire structure, layout, and images automatically and links the new page to the original as a translation — you ONLY supply the text translations. Provide targetLanguageCode (e.g. "fr") and a `translations` map of every visible source string to its translation (headings, paragraph text, button labels, image alt text, captions, form labels). Do NOT rebuild the layout or call search_stock_photos for a translation. 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:e=>Hr(e,t),inputSchema:Vr,strict:!0}),set_content_images:(0,c.tool)({description:"Set the feature image for a page or post, or the image gallery for a product. Pass `images`: a list of image URLs (e.g. `mainImage` from fetch_url_content or `url` values from search_stock_photos) and/or existing media library IDs. External URLs are imported into the media library automatically — NEVER put an image URL directly into feature_image_id. The FIRST image becomes the feature image (pages/posts) or the main product image (products); for a product the remaining images become its gallery in order (this REPLACES the product's current images). On a PAGE the feature image renders as a full-width title banner above the blocks, so never set one on the home page or on a page that opens with its own hero section — use update_site_identity `social_image` for that page's share preview instead; posts should always have one. Targets the currently open page/post/product by default; to target any other item (for example a product you just created from the dashboard) pass contentType plus slug, entityId, or title — no open editor needed. Mutating: first returns a confirmation phrase; only applies after exact confirmation.",execute:e=>Ur(e,t),inputSchema:j,strict:!0}),create_cms_page:(0,c.tool)({description:`Create a new CMS page with metadata and optional validated page blocks. Mutating: first returns a confirmation phrase; only executes after the user replies with the exact phrase. For translations, pass translationGroupId from the source page/post/product context so the new language is linked to the same backend translation group. For contact pages, provide a form block with fields; the destination address is configured once in CMS -> Messages and is never stored on the block.`,execute:e=>En(e,t),inputSchema:ie,strict:!0}),create_cms_post:(0,c.tool)({description:`Create a new CMS post with metadata and optional validated post blocks. Mutating: first returns a confirmation phrase; only executes after the user replies with the exact phrase. For translations, pass translationGroupId from the source post context so the new language is linked to the same backend translation group.`,execute:e=>Dn(e,t),inputSchema:ae,strict:!0}),create_cms_product:(0,c.tool)({description:"Create a new draft-capable product, complete with its images and its body copy in ONE call. Pass `images` to set the main product image and gallery (external https URLs are imported into the media library automatically — use `mainImage` from fetch_url_content to reuse a source page's photo). Pass `blocks` to build the product's \"Product Description Blocks\" — the SAME block vocabulary and section-based design rules as create_cms_page, rendered on the public product page. This is the richest product body and is what you should produce whenever the user asks to copy or write real product content. Also pass `short_description` for the one-line summary shown on product cards. `description_html` is a plain-HTML fallback body used only when no blocks are supplied. Defaults missing fields safely: physical Stripe product, generated SKU, price 0, stock 0, taxable, draft. `price` is in major units (25 = $25.00). For translations, pass translationGroupId from the source product context. Mutating: first returns a confirmation phrase; only executes after exact confirmation.",execute:e=>jn(e,t),inputSchema:oe,strict:!0}),delete_cms_item:(0,c.tool)({description:`Delete a resolved page, post, or product after exact confirmation. Pages/posts delete all translations in the translation group and related navigation links. Mutating: refuses unless the latest user message includes the exact confirmation phrase.`,execute:e=>Wn(e,t),inputSchema:le,strict:!0}),prepare_delete_cms_item:(0,c.tool)({description:`Inspect the page, post, or product that would be deleted and return the exact confirmation phrase. This tool does not mutate data.`,execute:e=>Un(e,t),inputSchema:ce,strict:!0}),update_footer:(0,c.tool)({description:`Replace the public footer links and/or footer copyright settings for a locale. Use links for footer navigation and copyright for locale text templates. Mutating: first returns a confirmation phrase; only executes after exact confirmation.`,execute:e=>$t(e,t),inputSchema:b,strict:!0}),update_content_block:(0,c.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:e=>Cn(e,t),inputSchema:O,strict:!0}),insert_content_block:(0,c.tool)({description:`Insert a new validated top-level page/post block before or after an existing block, or at the start/end. Use this for visible content additions like adding a rich text title and paragraph above a form. For "above the form", use position "before" with anchorBlockType "form" and blockType "text" containing html_content. Mutating: first returns a confirmation phrase; only executes after exact confirmation.`,execute:e=>wn(e,t),inputSchema:re,strict:!0}),update_current_cms_fields:(0,c.tool)({description:`Update validated metadata fields on the current page, post, or product. For products, description_json must be a valid NextBlock editor document JSON object. Mutating: first returns a confirmation phrase; only executes after exact confirmation.`,execute:e=>Sn(e,t),inputSchema:D,strict:!0}),update_cms_item_field:(0,c.tool)({description:`Update one field on a page, post, or product, resolving by current edit context, id, slug, or exact title. Use this for requests like changing price, stock, title, slug, status, sale_price, or meta fields. Interpret public as published for pages/posts and active for products. Scheduled sale date ranges are not supported and will be refused without mutation. Mutating: first returns a confirmation phrase; only executes after exact confirmation.`,execute:e=>Bn(e,t),inputSchema:se,strict:!0}),update_navigation_bar:(0,c.tool)({description:`Update the public header navigation bar for a locale. Use mode "append" when adding links while preserving existing navigation. Use mode "update" when renaming or changing an existing single link. Use mode "replace" only when the user asks to rebuild the complete header and you provide the full menu; destructive partial replacements are refused. Mutating: first returns a confirmation phrase; only executes after exact confirmation.`,execute:e=>Qt(e,t),inputSchema:y,strict:!0}),update_section_column_block:(0,c.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:e=>Tn(e,t),inputSchema:k,strict:!0}),execute_cms_action_plan:(0,c.tool)({description:`Execute multiple CMS mutations as one confirmed plan. Use this whenever the user asks for more than one change in the same prompt, such as creating a page and adding a navigation link. First returns one combined confirmation preview and Confirm button; after confirmation, runs each action in order and stops on the first failure.`,execute:e=>Yn(e,t),inputSchema:me,strict:!0})}}exports.buildVisibleContactIntroActionPlan=Se,exports.cortexAiPageContextSchema=C,exports.createCmsPageInputSchema=ie,exports.createCmsPostInputSchema=ae,exports.createCmsProductInputSchema=oe,exports.createCortexGlobalAgentTools=Wr,exports.deleteCmsItemInputSchema=le,exports.executeCmsActionPlan=Yn,exports.executeCmsActionPlanInputSchema=me,exports.executeCreateCmsPage=En,exports.executeCreateCmsPost=Dn,exports.executeCreateCmsProduct=jn,exports.executeDeleteCmsItem=Wn,exports.executeFetchEcommerceStats=fn,exports.executeFetchUrlContent=dr,exports.executeInsertContentBlock=wn,exports.executeManageProductVariants=Ar,exports.executePrepareDeleteCmsItem=Un,exports.executePublishContentDraft=Ir,exports.executeReadCurrentCmsItem=pn,exports.executeRewritePageDraft=Dr,exports.executeSearchDocumentation=rn,exports.executeSearchDocumentationWithTimeout=an,exports.executeSearchStockPhotos=Sr,exports.executeSetContentImages=Ur,exports.executeTranslateContentBulk=Mr,exports.executeTranslatePage=Hr,exports.executeUpdateCmsItemField=Bn,exports.executeUpdateContentBlock=Cn,exports.executeUpdateCurrentCmsFields=Sn,exports.executeUpdateFooter=$t,exports.executeUpdateNavigationBar=Qt,exports.executeUpdateSectionColumnBlock=Tn,exports.fetchEcommerceStatsInputSchema=S,exports.fetchUrlContentInputSchema=Xn,exports.insertContentBlockInputSchema=re,exports.isBlockedFetchHost=a.isBlockedFetchHost,exports.manageProductVariantsInputSchema=Or,exports.maybeTriggerStockPhotoDownloads=br,exports.navigationItemInputSchema=_,exports.prepareDeleteCmsItemInputSchema=ce,exports.publishContentDraftInputSchema=Nr,exports.readCurrentCmsItemInputSchema=ee,exports.resolveCortexAiStockPhotoProvider=hr,exports.resolveCortexAiStockPhotoProviders=mr,exports.rewritePageDraftInputSchema=Cr,exports.searchDocumentationInputSchema=x,exports.searchStockPhotosInputSchema=fr,exports.setContentImagesInputSchema=j,exports.translateContentBulkInputSchema=jr,exports.translatePageInputSchema=Vr,exports.updateCmsItemFieldInputSchema=se,exports.updateContentBlockInputSchema=O,exports.updateCurrentCmsFieldsInputSchema=D,exports.updateFooterInputSchema=b,exports.updateNavigationBarInputSchema=y,exports.updateSectionColumnBlockInputSchema=k;