@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.
- package/README.md +46 -0
- package/client.cjs +1 -0
- package/client.es.js +3 -7
- package/index.cjs +1 -0
- package/index.es.js +24 -277
- package/lib/ai-block-generation.cjs +4 -0
- package/lib/ai-block-generation.es.js +143 -182
- package/lib/ai-client.cjs +1 -0
- package/lib/ai-client.d.ts +1 -1
- package/lib/ai-client.es.js +101 -135
- package/lib/ai-config.cjs +1 -0
- package/lib/ai-config.es.js +89 -108
- package/lib/ai-cortex-widget-builder.cjs +1 -0
- package/lib/ai-cortex-widget-builder.es.js +56 -70
- package/lib/ai-global-agent-content-ops-tools.cjs +1 -0
- package/lib/ai-global-agent-content-ops-tools.d.ts +1943 -68
- package/lib/ai-global-agent-content-ops-tools.es.js +185 -199
- package/lib/ai-global-agent-custom-block-tools.cjs +1 -0
- package/lib/ai-global-agent-custom-block-tools.d.ts +2160 -95
- package/lib/ai-global-agent-custom-block-tools.es.js +226 -223
- package/lib/ai-global-agent-db-tools.cjs +1 -0
- package/lib/ai-global-agent-db-tools.d.ts +2708 -98
- package/lib/ai-global-agent-db-tools.es.js +1013 -986
- package/lib/ai-global-agent-ecommerce.cjs +1 -0
- package/lib/ai-global-agent-ecommerce.es.js +3 -7
- package/lib/ai-global-agent-site-tools.cjs +2 -0
- package/lib/ai-global-agent-site-tools.d.ts +10695 -500
- package/lib/ai-global-agent-site-tools.es.js +750 -757
- package/lib/ai-global-agent-theming-tools.cjs +1 -0
- package/lib/ai-global-agent-theming-tools.d.ts +2905 -105
- package/lib/ai-global-agent-theming-tools.es.js +326 -396
- package/lib/ai-global-agent-tools.cjs +15 -0
- package/lib/ai-global-agent-tools.d.ts +4 -2230
- package/lib/ai-global-agent-tools.es.js +3899 -4328
- package/lib/ai-key-crypto.cjs +1 -0
- package/lib/ai-key-crypto.es.js +63 -82
- package/lib/ai-key-verification.cjs +1 -0
- package/lib/ai-key-verification.es.js +74 -63
- package/lib/ai-model-catalog.cjs +1 -0
- package/lib/ai-model-catalog.es.js +18 -22
- package/lib/ai-model-registry.cjs +2 -0
- package/lib/ai-model-registry.es.js +246 -309
- package/lib/ai-seo-metadata.cjs +3 -0
- package/lib/ai-seo-metadata.es.js +143 -185
- package/lib/ai-vision.cjs +3 -0
- package/lib/ai-vision.d.ts +6 -6
- package/lib/ai-vision.es.js +161 -215
- package/lib/block-content-schemas.cjs +1 -0
- package/lib/block-content-schemas.es.js +324 -254
- package/lib/cortex-widget-registry.cjs +1 -0
- package/lib/cortex-widget-registry.es.js +35 -43
- package/lib/cortex-widget-schema.cjs +4 -0
- package/lib/cortex-widget-schema.es.js +280 -309
- package/lib/editor-document-from-html.cjs +1 -0
- package/lib/editor-document-from-html.es.js +334 -278
- package/lib/fetch-host-guard.cjs +1 -0
- package/lib/fetch-host-guard.d.ts +2 -0
- package/lib/fetch-host-guard.es.js +30 -0
- package/lib/mcp-server.cjs +1 -0
- package/lib/mcp-server.es.js +155 -173
- package/lib/mcp-tokens.cjs +1 -0
- package/lib/mcp-tokens.es.js +95 -107
- package/lib/mcp-tool-registry.cjs +5 -0
- package/lib/mcp-tool-registry.es.js +533 -411
- package/lib/site-brief.cjs +2 -0
- package/lib/site-brief.es.js +102 -108
- package/lib/vision-image-download.cjs +1 -0
- package/lib/vision-image-download.d.ts +43 -0
- package/lib/vision-image-download.es.js +120 -0
- package/lib/zod-config.cjs +1 -0
- package/lib/zod-config.es.js +5 -6
- package/package.json +13 -12
- package/client.cjs.js +0 -1
- package/index.cjs.js +0 -1
- package/lib/ai-block-generation.cjs.js +0 -5
- package/lib/ai-client.cjs.js +0 -1
- package/lib/ai-config.cjs.js +0 -1
- package/lib/ai-cortex-widget-builder.cjs.js +0 -1
- package/lib/ai-global-agent-content-ops-tools.cjs.js +0 -1
- package/lib/ai-global-agent-custom-block-tools.cjs.js +0 -1
- package/lib/ai-global-agent-db-tools.cjs.js +0 -1
- package/lib/ai-global-agent-ecommerce.cjs.js +0 -1
- package/lib/ai-global-agent-site-tools.cjs.js +0 -3
- package/lib/ai-global-agent-theming-tools.cjs.js +0 -3
- package/lib/ai-global-agent-tools.cjs.js +0 -15
- package/lib/ai-key-crypto.cjs.js +0 -1
- package/lib/ai-key-verification.cjs.js +0 -1
- package/lib/ai-model-catalog.cjs.js +0 -1
- package/lib/ai-model-registry.cjs.js +0 -2
- package/lib/ai-seo-metadata.cjs.js +0 -4
- package/lib/ai-vision.cjs.js +0 -3
- package/lib/block-content-schemas.cjs.js +0 -1
- package/lib/cortex-widget-registry.cjs.js +0 -1
- package/lib/cortex-widget-schema.cjs.js +0 -5
- package/lib/editor-document-from-html.cjs.js +0 -1
- package/lib/mcp-server.cjs.js +0 -1
- package/lib/mcp-tokens.cjs.js +0 -1
- package/lib/mcp-tool-registry.cjs.js +0 -6
- package/lib/site-brief.cjs.js +0 -2
- package/lib/zod-config.cjs.js +0 -1
|
@@ -1,15 +0,0 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const S=require("ai"),An=require("./ai-global-agent-db-tools.cjs.js"),zn=require("./ai-global-agent-custom-block-tools.cjs.js"),Pn=require("./ai-global-agent-content-ops-tools.cjs.js"),Nn=require("./ai-global-agent-theming-tools.cjs.js"),Un=require("./ai-global-agent-site-tools.cjs.js"),Kt=require("./editor-document-from-html.cjs.js");require("./zod-config.cjs.js");const R=require("./block-content-schemas.cjs.js"),s=require("zod");async function W(e,t,n){if(e?.recordRevision)try{return await e.recordRevision({contentType:t,entityId:n,phase:"capture"})}catch(r){console.error("Cortex AI: failed to capture revision baseline",r);return}}async function G(e,t,n,r){if(!(!e?.recordRevision||r===void 0))try{await e.recordRevision({baseline:r,contentType:t,entityId:n,phase:"commit"})}catch(o){console.error("Cortex AI: failed to record revision",o)}}const Fn=1e4,On={arabic:"ar",chinese:"zh",dutch:"nl",english:"en",french:"fr",francaise:"fr",francais:"fr",german:"de",italian:"it",japanese:"ja",korean:"ko",portuguese:"pt",russian:"ru",spanish:"es"},Vt=s.z.string().trim().min(1).max(2048).refine(e=>e.startsWith("/")||e.startsWith("#")||e.startsWith("http://")||e.startsWith("https://")||e.startsWith("mailto:")||e.startsWith("tel:"),"URL must be a relative path, hash link, http(s) URL, mailto URL, or tel URL."),Pt=s.z.strictObject({label:s.z.string().trim().min(1).max(120),target:s.z.enum(["_self","_blank"]).optional(),url:Vt}),Xe=Pt.extend({children:s.z.array(Pt).max(20).optional()}),Bn=s.z.strictObject({label:s.z.string().trim().min(1).max(120).optional(),url:Vt.optional()}).refine(e=>!!(e.label||e.url),{message:"Navigation item match requires label or url."}),ie=s.z.strictObject({items:s.z.array(Xe).min(1).max(30),languageCode:s.z.string().trim().min(2).max(80).default("en").describe('Locale code or language name, for example "en", "fr", "English", or "French".'),match:Bn.optional().describe('For mode "update", identifies the existing navigation item to update.'),mode:s.z.enum(["append","replace","update"]).default("append")}),ae=s.z.strictObject({copyright:s.z.record(s.z.string().trim().min(2).max(12),s.z.string().trim().min(1).max(500)).optional(),languageCode:s.z.string().trim().min(2).max(80).default("en").describe('Locale code or language name, for example "en", "fr", "English", or "French".'),links:s.z.array(Xe).min(1).max(30).optional()}),Pe=s.z.strictObject({limit:s.z.number().int().min(1).max(8).default(4),query:s.z.string().trim().min(2).max(300)}),Qe=s.z.object({currency:s.z.string().trim().min(3).max(3).optional().describe("Optional currency code for currency-specific monetary reports (e.g., USD, CAD). Do not set this for plain order-status counts unless the user asks for a currency."),query:s.z.string().describe("The analytical question about orders, products, or revenue."),reportType:s.z.enum(["revenue","orders","products","general"]).optional().default("general").describe("The focus area of the statistical report."),timeRange:s.z.enum(["today","this_month","last_7_days","last_30_days","last_month","last_90_days","all_time"]).optional().default("all_time").describe("The time period for the report. Use all_time for current order-status counts unless the user names a specific period.")}),Ne=s.z.strictObject({contentType:s.z.enum(["page","post","product"]),currentEditor:s.z.strictObject({blockId:s.z.union([s.z.number().int().positive(),s.z.string().trim().min(1).max(120)]).nullable().optional(),blockType:s.z.string().trim().min(1).max(80).nullable().optional(),field:s.z.string().trim().min(1).max(120).nullable().optional()}).optional(),entityId:s.z.union([s.z.number().int().positive(),s.z.string().trim().min(1).max(120)]),languageId:s.z.number().int().positive().nullable().optional(),slug:s.z.string().trim().min(1).max(300).nullable().optional(),title:s.z.string().trim().min(1).max(300).nullable().optional(),translationGroupId:s.z.string().trim().min(1).max(120).nullable().optional()}),Ln=s.z.enum(["page","post","product"]),J=s.z.strictObject({contentType:Ln.optional(),entityId:s.z.union([s.z.number().int().positive(),s.z.string().trim().min(1).max(120)]).optional(),slug:s.z.string().trim().min(1).max(300).optional(),title:s.z.string().trim().min(1).max(300).optional()}),se=J.optional().describe("Names the page, post, or product to act on when no CMS editor is open (MCP clients). Pass contentType plus one of slug, entityId, or title. Ignored when an editor is already open."),Ze=s.z.strictObject({cmsTarget:se,includeBlockContent:s.z.boolean().default(!1),includeBlocks:s.z.boolean().default(!0)}),et="The feature image: an existing media library id OR an external https:// image URL, which is downloaded into the media library automatically (pass `mainImage` from fetch_url_content or a `url` from search_stock_photos straight in). WHAT IT DOES: on a page it renders as a full-width title banner ABOVE the page's blocks (the image as a dimmed cover background, about 200-300px tall, with the page title centred over it in white); on a post it is the article's hero image above the header. It is also the social/OG preview image and the card thumbnail in post listings. RULES: give every post one. Give a page one only when a title banner above its content is wanted; NEVER set one on the home page or on any page that opens with its own hero section (the banner would stack above the hero and repeat the title) — set the site-wide social preview with update_site_identity `social_image` instead. Pick a very wide landscape image (about 3:1, at least 1600px wide): the banner crops it to a short full-width band.",ce=s.z.strictObject({cmsTarget:se,fields:s.z.strictObject({description_json:s.z.unknown().optional(),excerpt:s.z.string().max(2e3).nullable().optional(),feature_image_id:s.z.string().trim().min(1).max(2048).nullable().optional().describe(et),label:s.z.string().max(120).nullable().optional(),meta_description:s.z.string().max(500).nullable().optional(),meta_title:s.z.string().max(160).nullable().optional(),published_at:s.z.string().max(80).nullable().optional(),short_description:s.z.string().max(2e3).nullable().optional(),slug:s.z.string().trim().min(1).max(300).optional(),status:s.z.enum(["draft","published","active","archived"]).optional(),subtitle:s.z.string().max(300).nullable().optional(),title:s.z.string().trim().min(1).max(300).optional()}).partial()}),Ue=s.z.string().trim().min(1).max(120).describe(`A built-in block type (${R.availableCortexAiBlockTypes.join(", ")}) or the slug of a custom block definition from list_custom_blocks, whose content is the flat { field_key: value } map its fields describe.`),le=s.z.strictObject({blockId:s.z.number().int().positive(),blockType:Ue.optional(),cmsTarget:se,content:s.z.record(s.z.string(),s.z.unknown())}),ue=s.z.strictObject({blockIndex:s.z.number().int().min(0),blockType:Ue.optional(),cmsTarget:se,columnIndex:s.z.number().int().min(0),content:s.z.record(s.z.string(),s.z.unknown()),parentBlockId:s.z.number().int().positive()}),de=s.z.strictObject({blockType:Ue,content:s.z.record(s.z.string(),s.z.unknown()).describe('The block content, matching that block type\'s schema. For a `text` block, `html_content` is rendered as real HTML and may include an inline <style> and an inline <script> — so you can add scroll reveals, counters, hover effects, and other motion directly in a block. Inline scripts are stamped with the site CSP nonce automatically. Three rules. (1) THE PAGE IS REACT-HYDRATED. Do not change the text, classes, or attributes of surrounding server-rendered markup: React reconciles afterwards and reverts your change (a counter animates then snaps back) or logs a hydration mismatch. Waiting for `load` is NOT sufficient — hydration can still be in flight. Safe patterns instead: animate with the Web Animations API (el.animate() touches no attribute); append your own new elements and style those; use CSS for anything CSS can do; and if you must set text, render the FINAL value server-side and only animate toward it once the element scrolls into view. (2) `on*` attributes (onclick, onload, …) are stripped, so bind with addEventListener. (3) The script runs once per full page load, not on client-side navigation — for site-wide behaviour use manage_site_script. For a `section` block: `is_hero: true` marks the page hero (the editor checkbox "Hero Section (Prioritized image loading)": its background image loads with priority and its content is vertically centred); `slider: true` with a `slides` array ([{ background, column_blocks }, …], the editor checkbox "Enable Slider (Carousel layout)") renders a carousel of full sections: only the slides are drawn, but the grid track count still comes from the top-level `column_blocks`, so send one top-level column per column you want inside each slide (empty columns are fine) and give every slide that same number of columns. Add `autoplay: true` and `timeframe` in seconds (default 5) to rotate it.'),order:s.z.number().int().min(0).optional()}),pe=J.extend({images:s.z.array(s.z.string().trim().min(1).max(2048)).min(1).max(12).describe("External https image URLs (imported into the media library automatically) and/or existing media library ids. The first entry is the feature image (pages/posts) or the main product image (products).")}),me=J.extend({anchorBlockId:s.z.number().int().positive().optional(),anchorBlockType:Ue.optional(),block:de,position:s.z.enum(["before","after","start","end"]).default("end")}),ge=s.z.strictObject({blocks:s.z.array(de).max(20).optional(),contactEmail:s.z.string().email().optional(),feature_image_id:s.z.string().trim().min(1).max(2048).nullable().optional().describe(et),languageCode:s.z.string().trim().min(2).max(80).optional(),meta_description:s.z.string().max(500).nullable().optional(),meta_title:s.z.string().max(160).nullable().optional(),slug:s.z.string().trim().min(1).max(300).optional(),status:s.z.enum(["draft","published","archived"]).default("draft"),title:s.z.string().trim().min(1).max(300),translationGroupId:s.z.string().trim().min(1).max(120).optional()}),fe=s.z.strictObject({blocks:s.z.array(de).max(20).optional(),excerpt:s.z.string().max(2e3).nullable().optional(),feature_image_id:s.z.string().trim().min(1).max(2048).nullable().optional().describe(et),label:s.z.string().max(120).nullable().optional(),languageCode:s.z.string().trim().min(2).max(80).optional(),meta_description:s.z.string().max(500).nullable().optional(),meta_title:s.z.string().max(160).nullable().optional(),published_at:s.z.string().max(80).nullable().optional(),slug:s.z.string().trim().min(1).max(300).optional(),status:s.z.enum(["draft","published","archived"]).default("draft"),subtitle:s.z.string().max(300).nullable().optional(),title:s.z.string().trim().min(1).max(300),translationGroupId:s.z.string().trim().min(1).max(120).optional()}),he=s.z.strictObject({blocks:s.z.array(de).max(20).optional().describe("Content blocks for the product description area, same block vocabulary as create_cms_page. Rendered on the public product page in place of the plain description."),description_html:s.z.string().max(6e4).optional().describe("The product body as an HTML fragment (headings, paragraphs, lists, bold/italic/links). Converted to the editor document automatically. Prefer this over description_json."),description_json:s.z.unknown().optional(),freemius_plan_id:s.z.string().optional(),freemius_product_id:s.z.string().optional(),images:s.z.array(s.z.string().trim().min(1).max(2048)).max(12).optional().describe("Product images, in order: the first becomes the main product image and the rest the gallery. Each entry is either an external https image URL (imported into the media library automatically) or an existing media library id."),is_taxable:s.z.boolean().default(!0),languageCode:s.z.string().trim().min(2).max(80).optional(),meta_description:s.z.string().max(500).nullable().optional(),meta_title:s.z.string().max(160).nullable().optional(),payment_provider:s.z.enum(["stripe","freemius"]).default("stripe"),price:s.z.number().min(0).default(0),prices:s.z.record(s.z.string(),s.z.number().min(0)).optional(),product_type:s.z.enum(["physical","digital"]).default("physical"),sale_price:s.z.number().min(0).nullable().optional(),sale_prices:s.z.record(s.z.string(),s.z.number().min(0).nullable()).optional(),short_description:s.z.string().max(2e3).nullable().optional(),sku:s.z.string().trim().min(1).max(120).optional(),slug:s.z.string().trim().min(1).max(300).optional(),status:s.z.enum(["draft","active","archived"]).default("draft"),stock:s.z.number().int().min(0).default(0),title:s.z.string().trim().min(1).max(300),trial_period_days:s.z.number().int().min(0).default(0),trial_requires_payment_method:s.z.boolean().default(!1),translationGroupId:s.z.string().trim().min(1).max(120).optional(),upc:s.z.string().max(120).nullable().optional()}),ye=J.extend({currencyCode:s.z.string().trim().min(3).max(3).optional(),endsAt:s.z.string().max(80).nullable().optional(),field:s.z.string().trim().min(1).max(120),startsAt:s.z.string().max(80).nullable().optional(),value:s.z.unknown()}),tt=J,be=J,Ht=s.z.discriminatedUnion("tool",[s.z.strictObject({input:ge,tool:s.z.literal("create_cms_page")}),s.z.strictObject({input:fe,tool:s.z.literal("create_cms_post")}),s.z.strictObject({input:he,tool:s.z.literal("create_cms_product")}),s.z.strictObject({input:be,tool:s.z.literal("delete_cms_item")}),s.z.strictObject({input:ye,tool:s.z.literal("update_cms_item_field")}),s.z.strictObject({input:le,tool:s.z.literal("update_content_block")}),s.z.strictObject({input:me,tool:s.z.literal("insert_content_block")}),s.z.strictObject({input:ce,tool:s.z.literal("update_current_cms_fields")}),s.z.strictObject({input:ae,tool:s.z.literal("update_footer")}),s.z.strictObject({input:ie,tool:s.z.literal("update_navigation_bar")}),s.z.strictObject({input:ue,tool:s.z.literal("update_section_column_block")}),s.z.strictObject({input:pe,tool:s.z.literal("set_content_images")})]),Rn=s.z.union([ge.extend({tool:s.z.literal("create_cms_page")}).transform(({tool:e,...t})=>({input:t,tool:e})),fe.extend({tool:s.z.literal("create_cms_post")}).transform(({tool:e,...t})=>({input:t,tool:e})),he.extend({tool:s.z.literal("create_cms_product")}).transform(({tool:e,...t})=>({input:t,tool:e})),be.extend({tool:s.z.literal("delete_cms_item")}).transform(({tool:e,...t})=>({input:t,tool:e})),ye.extend({tool:s.z.literal("update_cms_item_field")}).transform(({tool:e,...t})=>({input:t,tool:e})),le.extend({tool:s.z.literal("update_content_block")}).transform(({tool:e,...t})=>({input:t,tool:e})),me.extend({tool:s.z.literal("insert_content_block")}).transform(({tool:e,...t})=>({input:t,tool:e})),ce.extend({tool:s.z.literal("update_current_cms_fields")}).transform(({tool:e,...t})=>({input:t,tool:e})),ae.extend({tool:s.z.literal("update_footer")}).transform(({tool:e,...t})=>({input:t,tool:e})),ie.extend({tool:s.z.literal("update_navigation_bar")}).transform(({tool:e,...t})=>({input:t,tool:e})),ue.extend({tool:s.z.literal("update_section_column_block")}).transform(({tool:e,...t})=>({input:t,tool:e})),pe.extend({tool:s.z.literal("set_content_images")}).transform(({tool:e,...t})=>({input:t,tool:e}))]),qn=s.z.string().transform((e,t)=>{const n=Kn(e);return n.success?n.action:(t.addIssue({code:"custom",message:n.message}),s.z.NEVER)}),Dn=s.z.union([Ht,Rn,qn]),nt=s.z.strictObject({actions:s.z.array(Dn).min(1).max(8),summary:s.z.string().trim().min(1).max(500).optional()});function Mn(e){const t=[];let n="",r=0,o=null,i=!1;for(const a of e){if(o){n+=a,i?i=!1:a==="\\"?i=!0:a===o&&(o=null);continue}if(a==='"'||a==="'"){o=a,n+=a;continue}if(a==="["||a==="{"||a==="("){r++,n+=a;continue}if(a==="]"||a==="}"||a===")"){r=Math.max(0,r-1),n+=a;continue}if(a===","&&r===0){n.trim()&&t.push(n.trim()),n="";continue}n+=a}return n.trim()&&t.push(n.trim()),t}function Nt(e){let t="";for(let n=0;n<e.length;n++){const r=e[n];if(r!=="'"){t+=r;continue}let o="",i=!1;for(n++;n<e.length;n++){const a=e[n];if(i){o+=a,i=!1;continue}if(a==="\\"){i=!0;continue}if(a==="'")break;o+=a}t+=JSON.stringify(o)}return t.replace(/\bTrue\b/g,"true").replace(/\bFalse\b/g,"false").replace(/\bNone\b/g,"null")}function jn(e){const t=e.trim();return t.startsWith("'")&&t.endsWith("'")||t.startsWith('"')&&t.endsWith('"')||t.startsWith("[")||t.startsWith("{")?JSON.parse(Nt(t)):/^-?\d+(?:\.\d+)?$/.test(t)?Number(t):t==="true"||t==="True"?!0:t==="false"||t==="False"?!1:t==="null"||t==="None"?null:t}function Gn(e){const t={};for(const n of Mn(e)){const r=n.indexOf("=");if(r<=0)throw new Error(`Expected key=value argument, received "${n}".`);const o=n.slice(0,r).trim();if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(o))throw new Error(`Invalid argument name "${o}".`);t[o]=jn(n.slice(r+1))}return t}function Kn(e){const n=e.trim().match(/^([a-z_]+)\(([\s\S]*)\)$/);if(!n)return{message:'Action plan actions must be JSON objects like { "tool": "create_cms_page", "input": { ... } }, not freeform text.',success:!1};const r=n[1];let o;try{o=Gn(n[2])}catch(c){return{message:c instanceof Error?c.message:"Could not parse action-plan command arguments.",success:!1}}const i={input:o,tool:r},a=Ht.safeParse(i);return a.success?{action:a.data,success:!0}:{message:`Invalid action-plan command "${r}": ${a.error.issues.map(c=>c.message).join("; ")}`,success:!1}}function Vn(e){return e.normalize("NFD").replace(/[\u0300-\u036f]/g,"").toLowerCase().replace(/\s+/g," ").trim()}function ke(e,t){return t.some(n=>e.includes(n))}function Hn(e){const t=Vn(e),n=ke(t,["add ","insert ","put ","create "]),r=ke(t,["title","heading","description","intro","copy","paragraph"]),o=t.includes("form")&&ke(t,["above","before"]),i=t.includes("contact page")||t.includes("contact pages")||t.includes("contact us")||t.includes("contactez-nous"),a=t.includes("english")&&ke(t,["french","francais","francaise"]);return!n||!r||!o||!i||!a?null:{actions:[{input:{anchorBlockType:"form",block:{blockType:"text",content:{html_content:"<h2>Let us help you move faster</h2><p>Have a question, project idea, or need help choosing the right next step? Send us a message and the NextBlock team will get back to you soon.</p>"}},contentType:"page",position:"before",slug:"contact-us"},tool:"insert_content_block"},{input:{anchorBlockType:"form",block:{blockType:"text",content:{html_content:"<h2>Parlons de votre projet</h2><p>Vous avez une question, une idee de projet ou besoin d'aide pour avancer? Envoyez-nous un message et l'equipe NextBlock vous repondra rapidement.</p>"}},contentType:"page",position:"before",slug:"contactez-nous"},tool:"insert_content_block"}],summary:"Add visible title and description copy above the forms on the English and French Contact pages."}}function Ut(){return s.z.object({content:s.z.array(s.z.any()).optional(),type:s.z.literal("doc")})}function rt(){try{const{revalidatePath:e}=require("next/cache");return e}catch{return null}}function x(e){if(!e?.supabase)throw new Error("A Supabase service client is required to execute Cortex AI global tools.");return e.supabase}function Wn(e,t,n){let r;const o=new Promise(i=>{r=setTimeout(()=>i(n()),t)});return Promise.race([e.finally(()=>{r&&clearTimeout(r)}),o])}function Jn(e){const t=Ne.safeParse(e?.pageContext);if(!t.success)throw new Error("No current CMS page context is available. Open a page, post, or product edit screen before using this editing tool.");return t.data}function Fe(e){const t=typeof e.entityId=="number"?e.entityId:Number.parseInt(e.entityId,10);if(!Number.isInteger(t)||t<=0)throw new Error(`Current ${e.contentType} id must be a positive integer.`);return t}function Wt(e){const t=String(e.entityId||"").trim();if(!t)throw new Error(`Current ${e.contentType} id is missing.`);return t}function M(e){return e.contentType==="product"?Wt(e):Fe(e)}const Yn=/^https?:\/\//i,Xn=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;async function Q(e,t,n){if(typeof e!="string")return null;const r=e.trim();if(!r)return null;if(!Yn.test(r)){if(Xn.test(r))return r;throw new Error(`"${r}" is not a usable image reference — provide an https:// image URL or a media library id.`)}const o=t?.importExternalImage;if(!o)throw new Error("I can only attach an image from a URL when media import is available here. Please pick an image from the media library instead.");const i=await o({altText:n,url:r});if("error"in i)throw new Error(`I could not import the image from that URL: ${i.error}`);return i.id}async function Jt(e,t,n){const r=[];for(let o=0;o<e.length;o+=1){const i=await Q(e[o],t,`${n} image ${o+1}`);i&&r.push(i)}return r}async function Qn(e){const t=[...new Set(e.mediaIds)],{error:n}=await e.supabase.from("product_media").delete().eq("product_id",e.productId);if(n)throw new Error(`Could not clear the product's existing images: ${_(n)}`);if(t.length>0){const{error:r}=await e.supabase.from("product_media").insert(t.map((o,i)=>({media_id:o,product_id:e.productId,sort_order:i})));if(r)throw new Error(`Could not save the product images: ${_(r)}`)}return t}async function Oe(e){if(!e.productId)return!1;const{data:t,error:n}=await e.supabase.from("product_drafts").select("id, blocks, meta").eq("product_id",e.productId).maybeSingle();if(n||!t)return!1;const r=e.patch({blocks:Array.isArray(t.blocks)?K(t.blocks):[],meta:A(t.meta)?K(t.meta):{}}),o={updated_at:new Date().toISOString()};if(r.blocks&&(o.blocks=r.blocks),r.meta&&(o.meta=r.meta),Object.keys(o).length===1)return!1;const{error:i}=await e.supabase.from("product_drafts").update(o).eq("id",t.id);if(i)throw new Error(`The product was updated, but its open draft could not be kept in sync: ${_(i)}. Publishing that draft would undo this change — publish or discard it in the product editor first.`);return!0}function Yt(e){return typeof e=="string"?e.trim().replace(/^\/+|\/+$/g,""):""}function Zn(e,t){const n=Yt(t??e.slug);return n?e.contentType==="page"?n==="home"?"/":`/${n}`:e.contentType==="post"?`/article/${n}`:`/product/${n}`:null}function er(e){const t=String(e.entityId);return e.contentType==="page"?`/cms/pages/${t}/edit`:e.contentType==="post"?`/cms/posts/${t}/edit`:`/cms/products/${t}/edit`}function U(e,t,n){const r=e?.revalidatePath??rt();if(!r)return;r(er(t));const o=Zn(t,n);o&&r(o),t.contentType==="page"&&o!=="/"&&r("/"),t.contentType==="product"&&r("/cms/products")}function Xt(e){const t=e?.revalidatePath??rt();t&&(t("/","layout"),t("/cms/navigation"))}function _(e){return e?typeof e=="object"&&"message"in e?String(e.message||"Unknown database error."):String(e):"Unknown database error."}async function tr(){return Promise.resolve().then(()=>require("./ai-global-agent-ecommerce.cjs.js"))}function Me(e){return e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?`[${e.map(t=>Me(t)).join(",")}]`:`{${Object.keys(e).filter(t=>t!=="temp_id").sort().map(t=>`${JSON.stringify(t)}:${Me(e[t])}`).join(",")}}`}function nr(e){let t=2166136261;const n=Me(e);for(let r=0;r<n.length;r++)t^=n.charCodeAt(r),t=Math.imul(t,16777619);return(t>>>0).toString(16).padStart(8,"0")}function je(e){return e.replace(/\s+/g," ").trim().toUpperCase()}function rr(e,t,n){return`${je(`CONFIRM ${e} ${t}`)} #${nr(n)}`}function Qt(e){return{confirmationPhrase:rr(e.action,e.subject,e.payload),mutationExecuted:!1,preview:e.preview,requiresConfirmation:!0,success:!0}}function B(e,t){const n=e[t];return typeof n=="string"&&n.trim()?n.trim():null}function H(e,t){const n=Number(e[t]);return Number.isFinite(n)?n:null}function N(e,t,n=`${t}s`){return`${e} ${e===1?t:n}`}function or(e,t){const n=B(t,"summary");if(n)return n;const r=B(t,"title"),o=B(t,"slug"),i=B(t,"status"),a=B(t,"contentType"),c=B(t,"field"),u=B(t,"mode"),d=B(t,"languageCode"),l=H(t,"blockCount"),m=H(t,"itemCount"),h=H(t,"affectedCount");if(e==="create_cms_page"||e==="create_cms_post")return`Create ${i||"draft"} ${e==="create_cms_page"?"page":"post"} "${r||o||"Untitled"}"${o?` at slug "${o}"`:""}${l!==null?` with ${N(l,"content block")}`:""}.`;if(e==="create_cms_product"){const g=H(t,"imageCount"),f=H(t,"blockCount"),p=[g?N(g,"image"):null,f?N(f,"description block"):H(t,"descriptionLength")?"a full description":null].filter(Boolean);return`Create ${i||"draft"} product "${r||o||"Untitled"}"${o?` at slug "${o}"`:""}${p.length?` with ${p.join(" and ")}`:""}.`}if(e==="update_cms_item_field")return`Update ${c||"one field"} on the ${a||"CMS item"} "${r||o||"selected item"}".`;if(e==="update_navigation_bar")return`${u==="append"?"Add":u==="update"?"Update":"Replace"} ${m!==null?N(m,"navigation item"):"navigation items"} in the ${d||"selected"} header navigation.`;if(e==="update_footer"){const g=H(t,"linkCount");return`Update the ${d||"selected"} footer${g!==null?` with ${N(g,"link")}`:""}.`}return e==="update_content_block"?`Update the selected ${B(t,"blockType")||"content"} block.`:e==="insert_content_block"?`Insert ${B(t,"blockType")||"content"} block on the ${a||"CMS item"} "${r||o||"selected item"}".`:e==="update_section_column_block"?`Update the selected nested ${B(t,"nestedBlockType")||"section"} block.`:e==="delete_cms_item"||e==="prepare_delete_cms_item"?`Delete ${h!==null?N(h,a||"CMS item"):`the selected ${a||"CMS item"}`}${r||o?` for "${r||o}"`:""}.`:"Complete the requested CMS change."}function P(e){if(e.context?.skipConfirmation)return null;const t=Qt(e),n=je(e.context?.latestUserMessage||""),r=je(t.confirmationPhrase);return n.includes(r)?null:t}function ot(e){const t=e?.actorUserId;if(!t)throw new Error("A confirmed CMS mutation requires an authenticated admin actor.");return t}function it(){return globalThis.crypto?.randomUUID?.()||`id-${Date.now()}-${Math.random().toString(36).slice(2)}`}function F(e){return e.normalize("NFD").replace(new RegExp("\\p{Diacritic}","gu"),"").toLowerCase().trim().replace(/\s+/g,"-").replace(/[^a-z0-9-]/g,"").replace(/-+/g,"-").replace(/^-|-$/g,"").slice(0,300)}function at(e){return(e||"USD").trim().toUpperCase()}const ir=new Set(["BIF","CLP","DJF","GNF","JPY","KMF","KRW","MGA","PYG","RWF","UGX","VND","VUV","XAF","XOF","XPF"]);function ar(e){return ir.has(at(e))?0:2}function Ce(e,t){return Math.round(e*10**ar(t))}function sr(e,t){return!e||typeof e!="object"||Array.isArray(e)?{}:Object.entries(e).reduce((n,[r,o])=>{if(typeof o=="number"&&Number.isFinite(o)&&o>=0){const i=at(r||t);n[i]=Ce(o,i)}return n},{})}function _e(e,t){if(!A(e))throw new Error(`${t} content must be a JSON object.`);return JSON.parse(JSON.stringify(e))}function K(e){return JSON.parse(JSON.stringify(e))}function A(e){return!!(e&&typeof e=="object"&&!Array.isArray(e))}function Ge(e,t){const n=K(e);for(const[r,o]of Object.entries(t))if(o!==void 0){if(A(o)&&A(n[r])){n[r]=Ge(n[r],o);continue}n[r]=K(o)}return n}function Zt(e,t){if(t.contentType==="product"){if(String(e.product_id??"")!==String(Wt(t)))throw new Error(`Block ${e.id} does not belong to the current product being edited.`);return}const n=Fe(t);if((t.contentType==="page"?Number(e.page_id):Number(e.post_id))!==n)throw new Error(`Block ${e.id} does not belong to the current ${t.contentType} being edited.`)}function st(e,t){return t?.customBlockDefinitions?.find(n=>n.slug===e)??null}function Ke(e,t=new Set,n=0){if(n>12||!e)return t;if(typeof e=="string")return t.add(e),t;if(Array.isArray(e)){for(const r of e)Ke(r,t,n+1);return t}if(typeof e=="object")for(const[r,o]of Object.entries(e))(r==="block_type"||r==="blockType"||r==="anchorBlockType")&&typeof o=="string"?t.add(o):o&&typeof o=="object"&&Ke(o,t,n+1);return t}async function V(e,t){return e?.customBlockDefinitions||!e?.supabase||![...Ke(t)].some(o=>!R.isValidBlockType(o))?e:{...e,customBlockDefinitions:await R.loadCustomBlockDefinitions(e.supabase)}}function oe(e,t,n){const r=typeof e=="string"?e.trim():"";if(R.isValidBlockType(r)||r&&st(r,n))return r;throw new Error(`${t} has unsupported block type "${r||"unknown"}". Built-in types: ${R.availableCortexAiBlockTypes.join(", ")}; a custom block must use a slug returned by list_custom_blocks.`)}function en(e,t,n){if(e&&e!==t)throw new Error(`${n} is a "${t}" block. Refusing to update it as "${e}".`)}function j(e,t,n,r){if(!R.isValidBlockType(e)){const i=st(e,r);if(!i)throw new Error(`${n} references custom block "${e}", which does not exist.`);const a=R.validateCustomBlockInstanceContent(i,t);if(!a.isValid)throw new Error(`${n} content is invalid for custom block "${e}": ${a.errors.join("; ")}`);return}const o=R.validateCortexBlockContent(e,t,r);if(!o.isValid)throw new Error(`${n} content is invalid for block type "${e}": ${o.errors.join("; ")}`)}function tn(e){return e==="section"}function cr(e){return typeof e.html_content=="string"?"text":typeof e.text=="string"&&typeof e.url=="string"?"button":typeof e.text_content=="string"?"heading":"media_id"in e||"object_key"in e||"external_url"in e?"image":typeof e.quote=="string"&&typeof e.author_name=="string"?"testimonial":typeof e.url=="string"&&("controls"in e||"autoplay"in e||"title"in e)?"video_embed":Array.isArray(e.fields)||typeof e.form_key=="string"||typeof e.recipient_email=="string"?"form":"postsPerPage"in e||"showPagination"in e?"posts_grid":typeof e.productId=="string"?"featured_product":"limit"in e&&"type"in e?"product_grid":null}function Se(e){return`ai-${e}-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}function xe(e,t,n){if(!A(e))throw new Error(`${t} must be a JSON object.`);const r=e.block_type??e.blockType,o=oe(r,t,n);if(tn(o))throw new Error(`${t} cannot be a nested ${o} block.`);const i=an(o,_e(e.content,t),t,n),a=e.temp_id??e.tempId,c=typeof a=="string"&&a.trim()?a:Se(o);return{block_type:o,content:i,temp_id:c}}function lr(e,t){const n=[];if("append_block"in e&&n.push(xe(e.append_block,"Nested block to append",t)),"append_blocks"in e){const r=e.append_blocks;if(!Array.isArray(r))throw new Error("append_blocks must be an array of nested block objects.");r.forEach((o,i)=>{n.push(xe(o,`Nested block to append ${i}`,t))})}return n}function ur(e,t){if("append_block"in e||"append_blocks"in e||"background"in e||"column_blocks"in e||"column_gap"in e||"container_type"in e||"padding"in e||"responsive_columns"in e||"vertical_alignment"in e)return null;const n=cr(e);if(!n)return null;const r=_e(e,`Nested ${n} block`);return j(n,r,`Nested ${n} block`,t),{block_type:n,content:r,temp_id:Se(n)}}function dr(e,t){const n=e.append_column_index??e.column_index;if(n===void 0)return 0;if(typeof n!="number"||!Number.isInteger(n)||n<0)throw new Error("append_column_index must be a non-negative integer.");if(t>0&&n>=t)throw new Error(`append_column_index ${n} is outside the existing ${t} column(s).`);return n}function pr(e,t,n,r){if(!tn(e))return Ge(t,n);const o={...n},i=lr(o,r),a=ur(o,r);a&&i.push(a),delete o.append_block,delete o.append_blocks,delete o.append_column_index,delete o.column_index;const c=Ge(t,o);if(i.length>0){const u=Array.isArray(t.column_blocks)?K(t.column_blocks):[],d=dr(n,u.length),l=u.length>0?u:[[]];for(;l.length<=d;)l.push([]);l[d]=[...l[d]||[],...i],c.column_blocks=l}return c}function mr(e,t){return{blockType:e.block_type,content:t?e.content:void 0,id:e.id,languageId:e.language_id,order:e.order,pageId:e.page_id,postId:e.post_id}}function X(e){return typeof e=="string"?e.trim().toLowerCase():""}function Ft(e){return typeof e=="string"?e.trim().toLowerCase():""}function nn(e){return e.reduce((t,n)=>t+1+(n.children?.length||0),0)}function ve(e){return typeof e=="string"?e.trim().toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g,""):""}async function Z(e,t){const n=t.trim(),r=ve(n),o=On[r],{data:i,error:a}=await e.from("languages").select("id, code, name, is_active");if(a)throw new Error(`Failed to load language "${t}": ${_(a)}`);const u=(Array.isArray(i)?i:[]).filter(l=>l.is_active!==!1),d=u.find(l=>{const m=ve(l.code),h=ve(l.name);return m===r||m===o||h===r});if(!d?.id||!d?.code){const l=u.map(m=>m.code).filter(Boolean).join(", ");throw new Error(`Language "${t}" was not found.${l?` Available languages: ${l}.`:""}`)}return{code:String(d.code),id:Number(d.id)}}async function Be(e,t){if(t)return Z(e,t);const{data:n,error:r}=await e.from("languages").select("id, code, name, is_active, is_default");if(r)throw new Error(`Failed to load active languages: ${_(r)}`);const o=(Array.isArray(n)?n:[]).filter(a=>a.is_active!==!1),i=o.find(a=>a.is_default)||o.find(a=>ve(a.code)==="en")||o[0];if(!i?.id||!i?.code)throw new Error("No active CMS language is available for Cortex AI content creation.");return{code:String(i.code),id:Number(i.id)}}async function Ve(e){try{const{data:t,error:n}=await e.from("currencies").select("code, is_default, is_active").eq("is_active",!0);if(n)return"USD";const r=Array.isArray(t)?t:[],o=r.find(i=>i.is_default)||r[0];return at(o?.code||"USD")}catch{return"USD"}}async function gr(e){const t=e.contentType==="page"?"pages":e.contentType==="post"?"posts":"products";let n="id",r=e.entityId;if(r===void 0&&e.slug&&(n="slug",r=e.slug),r===void 0&&e.title&&(n="title",r=e.title),r===void 0)throw new Error(`A ${e.contentType} target requires an id, slug, title, or current edit context.`);const{data:o,error:i}=await e.supabase.from(t).select("*").eq(n,r);if(i)throw new Error(`Failed to resolve ${e.contentType}: ${_(i)}`);const a=Array.isArray(o)?o:o?[o]:[];if(a.length!==1)throw new Error(a.length===0?`No ${e.contentType} matched ${n} "${String(r)}".`:`Multiple ${e.contentType}s matched ${n} "${String(r)}"; use an exact id.`);return a[0]}async function Y(e,t){const n=Ne.safeParse(t?.pageContext).success?t?.pageContext:null,r=e.contentType||n?.contentType;if(!r)throw new Error("Target contentType is required when no current CMS edit context exists.");const o=e.entityId!==void 0||!!e.slug||!!e.title,i=e.entityId??(o?void 0:n?.entityId),a=e.slug??(o?void 0:n?.slug??void 0),c=e.title??(o?void 0:n?.title??void 0),u=await gr({contentType:r,entityId:i,slug:i===void 0&&a||void 0,supabase:x(t),title:i===void 0&&!a&&c||void 0});return{contentType:r,item:u}}async function ee(e,t){const n=Ne.safeParse(t?.pageContext);if(n.success)return n.data;if(!(e!==void 0&&(e.entityId!==void 0||!!e.slug||!!e.title)))throw new Error("No current CMS page context is available. Open a page, post, or product edit screen, or pass `cmsTarget` naming the item — contentType plus one of slug, entityId, or title.");const o=await Y(e,t),i=o.item;return{contentType:o.contentType,entityId:i.id,slug:typeof i.slug=="string"?i.slug:"",title:typeof i.title=="string"?i.title:""}}async function Ee(e){const t=await hr({item:e.item,languageId:e.languageId,menuKey:e.menuKey,supabase:e.supabase}),n={label:e.item.label,language_id:e.languageId,menu_key:e.menuKey,order:e.order,page_id:t?.pageId??null,parent_id:e.parentId??null,...t?.navigationTranslationGroupId?{translation_group_id:t.navigationTranslationGroupId}:{},url:e.item.url},{data:r,error:o}=await e.supabase.from("navigation_items").insert(n).select("id").single();if(o)throw new Error(`Failed to insert ${e.menuKey} navigation item: ${_(o)}`);return Number(r.id)}function fr(e){const t=e.trim();if(!t.startsWith("/")||t.startsWith("//"))return null;const n=t.split("?")[0]?.split("#")[0]||"",r=n==="/"?"home":n.replace(/^\/+|\/+$/g,"");return r&&!r.includes("/")?r:null}async function hr(e){const t=fr(e.item.url);if(!t)return null;const{data:n,error:r}=await e.supabase.from("pages").select("id, slug, translation_group_id, language_id").eq("slug",t).eq("language_id",e.languageId);if(r)throw new Error(`Failed to resolve linked page for navigation item: ${_(r)}`);const o=Array.isArray(n)?n[0]:n;if(!o?.id)return null;let i=it();if(o.translation_group_id){const{data:a,error:c}=await e.supabase.from("pages").select("id").eq("translation_group_id",o.translation_group_id);if(c)throw new Error(`Failed to inspect linked page translations for navigation item: ${_(c)}`);const u=new Set((Array.isArray(a)?a:[]).map(h=>String(h.id)).filter(Boolean)),{data:d,error:l}=await e.supabase.from("navigation_items").select("id, page_id, translation_group_id, menu_key").eq("menu_key",e.menuKey);if(l)throw new Error(`Failed to inspect related navigation translations: ${_(l)}`);const m=(Array.isArray(d)?d:[]).find(h=>h.translation_group_id&&u.has(String(h.page_id)));m?.translation_group_id&&(i=m.translation_group_id)}return{navigationTranslationGroupId:i,pageId:Number(o.id)}}async function rn(e){const t=await Z(e.supabase,e.languageCode),{data:n,error:r}=await e.supabase.from("navigation_items").select("id, parent_id").eq("menu_key",e.menuKey).eq("language_id",t.id);if(r)throw new Error(`Failed to inspect existing ${e.menuKey} navigation items: ${_(r)}`);const o=Array.isArray(n)?n:[],i=o.filter(d=>d.parent_id==null).length,a=nn(e.items);on({existingItemCount:o.length,existingTopLevelCount:i,languageCode:t.code,menuKey:e.menuKey,replacementItemCount:a});const{error:c}=await e.supabase.from("navigation_items").delete().eq("menu_key",e.menuKey).eq("language_id",t.id);if(c)throw new Error(`Failed to clear ${e.menuKey} navigation items: ${_(c)}`);let u=0;for(const[d,l]of e.items.entries()){const m=await Ee({item:l,languageId:t.id,menuKey:e.menuKey,order:d,supabase:e.supabase});u++;for(const[h,g]of(l.children??[]).entries())await Ee({item:g,languageId:t.id,menuKey:e.menuKey,order:h,parentId:m,supabase:e.supabase}),u++}return{insertedCount:u,languageCode:t.code,menuKey:e.menuKey,skippedCount:0,updatedCount:0}}function on(e){if(!(e.existingItemCount===0||e.replacementItemCount>=e.existingItemCount))throw new Error(`Refusing destructive ${e.menuKey} navigation replacement for ${e.languageCode}: existing menu has ${e.existingItemCount} items (${e.existingTopLevelCount} top-level), but the replacement only contains ${e.replacementItemCount}. Use mode "update" for renaming or changing a single link, or provide the full menu.`)}async function yr(e){const t=await Z(e.supabase,e.languageCode),{data:n,error:r}=await e.supabase.from("navigation_items").select("id, parent_id").eq("menu_key",e.menuKey).eq("language_id",t.id);if(r)throw new Error(`Failed to inspect existing ${e.menuKey} navigation items: ${_(r)}`);const o=Array.isArray(n)?n:[];on({existingItemCount:o.length,existingTopLevelCount:o.filter(i=>i.parent_id==null).length,languageCode:t.code,menuKey:e.menuKey,replacementItemCount:nn(e.items)})}async function br(e){if(e.items.length!==1)throw new Error('mode "update" requires exactly one navigation item.');const t=await Z(e.supabase,e.languageCode),n=e.items[0],r=X(e.match?.url)||X(n.url),o=Ft(e.match?.label),{data:i,error:a}=await e.supabase.from("navigation_items").select("id, label, url, parent_id, order").eq("menu_key",e.menuKey).eq("language_id",t.id);if(a)throw new Error(`Failed to load existing ${e.menuKey} navigation items: ${_(a)}`);const u=(Array.isArray(i)?i:[]).find(l=>{const m=X(l.url),h=Ft(l.label);return!!(r&&m===r||o&&h===o)});if(!u?.id)throw new Error(`Could not find a ${e.menuKey} navigation item to update in ${t.code}. Use a matching label or url.`);const{error:d}=await e.supabase.from("navigation_items").update({label:n.label,url:n.url}).eq("id",u.id);if(d)throw new Error(`Failed to update ${e.menuKey} navigation item: ${_(d)}`);return{insertedCount:0,languageCode:t.code,menuKey:e.menuKey,skippedCount:0,updatedCount:1}}async function _r(e){const t=await Z(e.supabase,e.languageCode),{data:n,error:r}=await e.supabase.from("navigation_items").select("id, url, parent_id, order").eq("menu_key",e.menuKey).eq("language_id",t.id);if(r)throw new Error(`Failed to load existing ${e.menuKey} navigation items: ${_(r)}`);let o=0,i=0;const a=Array.isArray(n)?n:[],c=new Set(a.map(l=>X(l.url)).filter(Boolean)),u=a.filter(l=>l.parent_id==null).map(l=>Number(l.order)).filter(Number.isFinite);let d=u.length>0?Math.max(...u)+1:a.length;for(const l of e.items){const m=X(l.url);if(m&&c.has(m)){i++;continue}const h=await Ee({item:l,languageId:t.id,menuKey:e.menuKey,order:d,supabase:e.supabase});o++,d++,m&&c.add(m);let g=0;for(const f of l.children??[]){const p=X(f.url);if(p&&c.has(p)){i++;continue}await Ee({item:f,languageId:t.id,menuKey:e.menuKey,order:g,parentId:h,supabase:e.supabase}),o++,g++,p&&c.add(p)}}return{insertedCount:o,languageCode:t.code,menuKey:e.menuKey,skippedCount:i,updatedCount:0}}function $(e){return typeof e=="string"&&e.trim()?e.trim():""}function wr(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function kr(e){const t=$(e.field_type??e.fieldType??e.type??e.input_type).toLowerCase().replace(/\s+/g,"_"),n=$(e.label??e.name??e.placeholder).toLowerCase();return["email","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 Ir(e){return(Array.isArray(e)&&e.length>0?e:[{field_type:"text",is_required:!0,label:"Name",placeholder:"Your name"},{field_type:"email",is_required:!0,label:"Email",placeholder:"you@example.com"},{field_type:"textarea",is_required:!0,label:"Message",placeholder:"How can we help?"}]).map((n,r)=>{const o=A(n)?n:{},i=$(o.label??o.name)||(r===0?"Name":r===1?"Email":"Message"),a=kr({...o,label:i}),c=o.is_required??o.isRequired??o.required;return{field_type:a,is_required:typeof c=="boolean"?c:!0,label:i,options:Array.isArray(o.options)?o.options:void 0,placeholder:$(o.placeholder)||void 0,temp_id:$(o.temp_id??o.tempId??o.id)||`field-${r+1}`}})}const Tr=new Set(["none","sm","md","lg","xl"]),Ot=new Set(["none","sm","md","lg","xl"]),vr=new Set(["full-width","container","container-sm","container-lg","container-xl"]),Cr=new Set(["start","center","end","stretch"]),Sr=new Set(["none","theme","solid","gradient","image"]),xr=new Set(["primary","secondary","muted","accent","destructive"]),Er=new Set(["center","top","bottom","left","right"]);function $r(e){return typeof e=="string"&&/^https?:\/\//i.test(e.trim())}function D(e,t,n){return typeof e=="string"&&t.has(e)?e:n}function Ar(e){return Number.isFinite(e)?Math.min(4,Math.max(1,Math.round(e))):1}function zr(e){const t=[{color:"#1e3a8a",position:0},{color:"#3b82f6",position:100}];if(!A(e))return{direction:"to bottom right",stops:t,type:"linear"};const n=e.type==="radial"?"radial":"linear",r=Array.isArray(e.stops)&&e.stops.length>=2?e.stops:t;return{direction:typeof e.direction=="string"&&e.direction.trim()?e.direction:n==="radial"?"circle at center":"to bottom right",stops:r,type:n}}function Bt(e){if(!A(e))return{type:"none"};const t=D(e.type,Sr,"none"),n=typeof e.min_height=="string"&&e.min_height.trim()?{min_height:e.min_height}:{};if(t==="theme")return{theme:D(e.theme,xr,"muted"),type:t,...n};if(t==="solid")return typeof e.solid_color=="string"&&e.solid_color.trim()?{solid_color:e.solid_color,type:t,...n}:{type:"none"};if(t==="gradient")return{gradient:zr(e.gradient),type:t,...n};if(t==="image"){const r=A(e.image)?e.image:null,o=r&&$r(r.external_url)?r.external_url.trim():null,i=!!(r&&typeof r.media_id=="string"&&r.media_id.trim()&&typeof r.object_key=="string"&&r.object_key.trim());return r&&(o||i)?{image:{...r,...o?{external_url:o}:{},position:D(r.position,Er,"center"),size:r.size==="contain"?"contain":"cover"},type:t,...n}:{type:"none"}}return{type:"none",...n}}function Pr(e,t,n){const r=e.is_hero===!0;let o=Array.isArray(e.column_blocks)?e.column_blocks:[];o.length>0&&o.every(p=>A(p)&&!Array.isArray(p))&&(o=[o]);const i=o.map((p,b)=>(Array.isArray(p)?p:[]).map((w,I)=>xe(w,`${t} column ${b} block ${I}`,n))),a=i.length>0?i:[[]],c=Ar(a.length),u=A(e.responsive_columns)?e.responsive_columns:{},d=Number(u.tablet),l=Number(u.mobile),m=Number.isFinite(d)?Math.min(3,Math.max(1,Math.min(c,d))):Math.min(3,c),h=Number.isFinite(l)?Math.min(2,Math.max(1,l)):1,g=A(e.padding)?e.padding:{},f={...e,background:Bt(e.background),column_blocks:a,column_gap:D(e.column_gap,Tr,"lg"),container_type:D(e.container_type,vr,"container"),padding:{bottom:D(g.bottom,Ot,"xl"),top:D(g.top,Ot,"xl")},responsive_columns:{desktop:c,mobile:h,tablet:m},vertical_alignment:D(e.vertical_alignment,Cr,r?"center":"start")};return Array.isArray(e.slides)&&(f.slides=e.slides.filter(p=>A(p)).map((p,b)=>{let y=Array.isArray(p.column_blocks)?p.column_blocks:[];return y.length>0&&y.every(w=>A(w)&&!Array.isArray(w))&&(y=[y]),{background:Bt(p.background),column_blocks:y.map((w,I)=>(Array.isArray(w)?w:[]).map((k,v)=>xe(k,`${t} slide ${b} column ${I} block ${v}`,n)))}})),f.slider===!0&&!(Array.isArray(f.slides)&&f.slides.length>0)&&(f.slider=!1),f}function an(e,t,n,r){if(!R.isValidBlockType(e)){const i=K(t);return j(e,i,n,r),i}if(e==="section"){const i=Pr(t,n,r);return j(e,i,n,r),i}const o=K(t);if(e==="heading"&&(o.text_content=$(o.text_content)||$(o.text)||$(o.title)||$(o.heading)||"Untitled",o.level=typeof o.level=="number"?o.level:1),e==="text"){const i=$(o.html_content)||$(o.html)||$(o.content)||$(o.text);i&&(o.html_content=/<\/?[a-z][\s\S]*>/i.test(i)?i:`<p>${wr(i)}</p>`)}return e==="button"&&(o.text=$(o.text)||$(o.label)||$(o.title)||"Learn More",o.url=$(o.url)||$(o.href)||$(o.link)||"#"),e==="form"&&(o.fields=Ir(o.fields),o.submit_button_text=$(o.submit_button_text??o.submitButtonText??o.button_text)||"Send Message",o.success_message=$(o.success_message??o.successMessage)||"Thanks for reaching out. We will reply as soon as possible."),j(e,o,n,r),o}function $e(e,t,n){const r=oe(e.blockType,`Block ${t}`,n),o=an(r,_e(e.content,`Block ${t}`),`Block ${t}`,n);return{block_type:r,content:o,order:e.order??t}}function Nr(e,t="Contact Us",n){return[$e({blockType:"section",content:{is_hero:!0,background:{type:"none"},column_blocks:[[{block_type:"heading",content:{level:1,textAlign:"center",text_content:t},temp_id:Se("heading")},{block_type:"text",content:{html_content:"<p>Have a question, project, or support request? Send us a note and we will get back to you soon.</p>"},temp_id:Se("text")}]],column_gap:"lg",container_type:"container",padding:{bottom:"xl",top:"xl"},responsive_columns:{desktop:1,mobile:1,tablet:1},vertical_alignment:"center"}},0,n),$e({blockType:"form",content:{fields:[{field_type:"text",is_required:!0,label:"Name",placeholder:"Your name",temp_id:"field-name"},{field_type:"email",is_required:!0,label:"Email",placeholder:"you@example.com",temp_id:"field-email"},{field_type:"textarea",is_required:!0,label:"Message",placeholder:"How can we help?",temp_id:"field-message"}],submit_button_text:"Send Message",success_message:"Thanks for reaching out. We will reply as soon as possible."}},1,n)]}function Le(e,t,n,r){return(!e||e.length===0)&&t?Nr(t,n,r):(e||[]).map((o,i)=>$e(o,i,r))}async function ct(e){const t=e.contentType==="page"?"pages":e.contentType==="post"?"posts":"products",{data:n,error:r}=await e.supabase.from(t).select("id, title, slug, language_id").eq("slug",e.slug).eq("language_id",e.languageId);if(r)throw new Error(`Failed to check ${e.contentType} slug uniqueness: ${_(r)}`);const o=Array.isArray(n)?n:[];return o.length>0?{duplicate:!0,existingItem:o[0],mutationExecuted:!1,success:!1,message:`A ${e.contentType} with slug "${e.slug}" already exists for this language.`}:null}async function lt(e){if(!e.suppliedTranslationGroupId)return{translationGroupId:void 0};const t=e.contentType==="page"?"pages":e.contentType==="post"?"posts":"products",{data:n,error:r}=await e.supabase.from(t).select("id, title, slug, language_id, translation_group_id").eq("translation_group_id",e.suppliedTranslationGroupId);if(r)throw new Error(`Failed to inspect ${e.contentType} translation group: ${_(r)}`);const o=Array.isArray(n)?n:[];if(o.length===0)return{result:{message:`The ${e.contentType} translation group "${e.suppliedTranslationGroupId}" was not found.`,mutationExecuted:!1,success:!1},translationGroupId:e.suppliedTranslationGroupId};const i=o.find(a=>Number(a.language_id)===e.languageId);return i?{result:{duplicateTranslation:!0,existingItem:i,message:`A ${e.contentType} translation already exists for ${e.languageCode} in this translation group.`,mutationExecuted:!1,success:!1},translationGroupId:e.suppliedTranslationGroupId}:{translationGroupId:e.suppliedTranslationGroupId}}async function ut(e){if(e.blocks.length===0)return[];const t=e.blocks.map((o,i)=>({block_type:o.block_type,content:o.content,language_id:e.languageId,order:o.order??i,page_id:e.contentType==="page"?e.itemId:null,post_id:e.contentType==="post"?e.itemId:null,product_id:e.contentType==="product"?e.itemId:null})),{data:n,error:r}=await e.supabase.from("blocks").insert(t).select("*");if(r)throw new Error(`Failed to insert ${e.contentType} blocks: ${_(r)}`);return we(e.blocks,e.supabase),Array.isArray(n)?n:[]}async function dt(e){const t=e.contentType==="page"?"pages":e.contentType==="post"?"posts":"products";await e.supabase.from(t).delete().eq("id",e.itemId)}function pt(e,t){return e==="page"?`/cms/pages/${t}/edit`:e==="post"?`/cms/posts/${t}/edit`:`/cms/products/${t}/edit`}function Lt(e){return e==="page"?"/cms/pages":e==="post"?"/cms/posts":"/cms/products"}async function mt(e,t){const n=ie.parse(e),r=x(t);n.mode==="replace"&&await yr({items:n.items,languageCode:n.languageCode,menuKey:"HEADER",supabase:r});const o=P({action:"UPDATE NAVIGATION",context:t,payload:{input:n,tool:"update_navigation_bar"},preview:{itemCount:n.items.length,languageCode:n.languageCode,mode:n.mode,target:"header navigation"},subject:`${n.mode} header`});if(o)return o;const i=n.mode==="update"?await br({items:n.items,languageCode:n.languageCode,match:n.match,menuKey:"HEADER",supabase:r}):n.mode==="append"?await _r({items:n.items,languageCode:n.languageCode,menuKey:"HEADER",supabase:r}):await rn({items:n.items,languageCode:n.languageCode,menuKey:"HEADER",supabase:r});return Xt(t),{...i,mutationExecuted:!0,mode:n.mode,success:!0}}async function gt(e,t){const n=ae.parse(e);if(!n.links?.length&&!n.copyright)throw new Error("update_footer requires links or copyright.");const r=x(t),o=P({action:"UPDATE FOOTER",context:t,payload:{input:n,tool:"update_footer"},preview:{copyrightUpdated:!!n.copyright,linkCount:n.links?.length||0,languageCode:n.languageCode,target:"footer"},subject:n.languageCode});if(o)return o;let i=null;if(n.links?.length&&(i=await rn({items:n.links,languageCode:n.languageCode,menuKey:"FOOTER",supabase:r})),n.copyright){const{error:a}=await r.from("site_settings").upsert({key:"footer_copyright",value:n.copyright});if(a)throw new Error(`Failed to update footer copyright: ${_(a)}`)}return Xt(t),{copyrightUpdated:!!n.copyright,footerNavigation:i,mutationExecuted:!0,success:!0}}function sn(e){return typeof e=="string"?e.toLowerCase():""}function Ur(e,t){const n=t.map(sn).join(" ");return e.reduce((r,o)=>r+(n.includes(o)?1:0),0)}function Rt(e,t){return(e.find(n=>t.some(r=>sn(n).includes(r)))||e.find(n=>n.trim().length>0)||"No excerpt available.").slice(0,500)}async function cn(e,t){const n=Pe.parse(e),r=x(t),o=n.query.toLowerCase().split(/\s+/).map(l=>l.trim()).filter(Boolean),[i,a]=await Promise.all([r.from("posts").select("id, title, slug, excerpt, subtitle, meta_description, status, updated_at").eq("status","published").limit(100),r.from("pages").select("id, title, slug, meta_description, status, updated_at").eq("status","published").limit(100)]);if(i.error)throw new Error(`Failed to search documentation posts: ${_(i.error)}`);if(a.error)throw new Error(`Failed to search documentation pages: ${_(a.error)}`);const c=(i.data??[]).map(l=>({excerpt:Rt([l.excerpt,l.subtitle,l.meta_description,l.slug].filter(Boolean),o),source:"post",title:l.title,url:`/article/${l.slug}`})),u=(a.data??[]).map(l=>({excerpt:Rt([l.meta_description,l.slug].filter(Boolean),o),source:"page",title:l.title,url:l.slug==="home"?"/":`/${l.slug}`})),d=[...c,...u].map(l=>({...l,score:Ur(o,[l.title,l.excerpt,l.url])})).filter(l=>l.score>0).sort((l,m)=>m.score-l.score).slice(0,n.limit).map(l=>({excerpt:l.excerpt,source:l.source,title:l.title,url:l.url}));return{query:n.query,results:d,success:!0}}async function ln(e,t,n=Fn){const r=Pe.safeParse(e),o=r.success?r.data.query:"";return Wn(cn(e,t),n,()=>({message:"Documentation search took too long to respond. Please try again or ask a more specific question.",query:o,results:[],success:!1,timedOut:!0}))}const Fr=["pending","trial","paid","shipped","cancelled","refunded","failed"],Or={awaiting:"pending",canceled:"cancelled",cancelled:"cancelled",complete:"paid",completed:"paid",failed:"failed",paid:"paid",payment_pending:"pending",pending:"pending",refund:"refunded",refunded:"refunded",refunds:"refunded",shipped:"shipped",trial:"trial",trials:"trial"};function Br(e){return String(e??"unknown").trim().toLowerCase()||"unknown"}function qt(e){const t=Object.fromEntries(Fr.map(n=>[n,0]));for(const n of e){const r=Br(n.status);t[r]=(t[r]??0)+1}return t}function Lr(e){const n=e.toLowerCase().replace(/[^a-z0-9_]+/g," ").split(/\s+/).filter(Boolean);for(const r of n){const o=Or[r];if(o)return o}return null}function re(e){const t=Number(e);return Number.isFinite(t)?t:0}async function un(e,t){const n=Qe.parse(e),r=x(t),o=new Date;let i=null,a=null;switch(n.timeRange){case"today":i=new Date(o.getFullYear(),o.getMonth(),o.getDate());break;case"this_month":i=new Date(o.getFullYear(),o.getMonth(),1);break;case"last_7_days":i=new Date(o.getTime()-10080*60*1e3);break;case"last_30_days":i=new Date(o.getTime()-720*60*60*1e3);break;case"last_month":i=new Date(o.getFullYear(),o.getMonth()-1,1),a=new Date(o.getFullYear(),o.getMonth(),0,23,59,59,999);break;case"last_90_days":i=new Date(o.getTime()-2160*60*60*1e3);break;case"all_time":i=null;break}const c=n.currency?.toUpperCase(),u=Lr(n.query),d=r.from("orders").select("id, status, total, currency, created_at, paid_at");c&&d.eq("currency",c),i&&d.gte("created_at",i.toISOString()),a&&d.lte("created_at",a.toISOString());const m=n.reportType==="products"||n.reportType==="revenue"||n.reportType==="general"?r.from("order_items").select(`
|
|
2
|
-
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;m&&(c&&m.eq("orders.currency",c),i&&m.gte("orders.paid_at",i.toISOString()),a&&m.lte("orders.paid_at",a.toISOString()));const g=n.timeRange!=="all_time"&&(n.reportType==="orders"||u)?r.from("orders").select("id, status, currency"):null;g&&c&&g.eq("currency",c);const[{data:f,error:p},{data:b,error:y},w]=await Promise.all([d,m??Promise.resolve({data:[],error:null}),g??Promise.resolve({data:null,error:null})]);if(p)throw new Error(`Failed to fetch ecommerce stats: ${_(p)}`);if(y)throw new Error(`Failed to fetch ecommerce stats: ${_(y)}`);if(w.error)throw new Error(`Failed to fetch ecommerce stats: ${_(w.error)}`);const I=Array.isArray(f)?f:[],T=Array.isArray(b)?b:[],k=qt(I),v=Array.isArray(w.data)?w.data:null,E=v?qt(v):null,O={};for(const C of T){const z=Array.isArray(C.orders)?C.orders[0]:C.orders,q=String(z?.currency||c||"unknown").toUpperCase();O[q]=(O[q]??0)+re(C.quantity)*re(C.price_at_purchase)/100}const te={currency:c??null,currencyFiltered:!!c,orderStatusCounts:k,paidOrderCount:k.paid??0,query:n.query,reportType:n.reportType,revenueByCurrency:O,timeRange:n.timeRange,totalOrders:I.length,totalRevenue:Object.values(O).reduce((C,z)=>C+z,0)};if(E&&(te.allTimeOrderStatusCounts=E),u&&(te.matchingOrderStatus={allTimeCount:E?.[u]??k[u]??0,count:k[u]??0,status:u,timeRange:n.timeRange}),n.reportType==="products"||n.reportType==="revenue"||n.reportType==="general"){const C={};for(const z of T){const q=Array.isArray(z.products)?z.products[0]:z.products;if(!q?.id)continue;const ne=q.id;C[ne]||(C[ne]={id:ne,quantity:0,revenue:0,title:q.title,type:q.product_type}),C[ne].quantity+=re(z.quantity),C[ne].revenue+=re(z.quantity)*re(z.price_at_purchase)/100}te.topProducts=Object.values(C).sort((z,q)=>q.revenue-z.revenue).slice(0,10)}return{report:te,success:!0}}async function dn(e,t){const n=Ze.parse(e),r=x(t),o=await ee(n.cmsTarget,t),i=M(o),a=o.contentType==="page"?"pages":o.contentType==="post"?"posts":"products",{data:c,error:u}=await r.from(a).select("*").eq("id",i).single();if(u||!c)throw new Error(`Failed to read current ${o.contentType}: ${_(u)}`);let d=[];if(n.includeBlocks){const l=o.contentType==="page"?"page_id":o.contentType==="post"?"post_id":"product_id",{data:m,error:h}=await r.from("blocks").select("id, page_id, post_id, product_id, language_id, block_type, content, order").eq(l,i);if(h)throw new Error(`Failed to read current ${o.contentType} blocks: ${_(h)}`);d=(Array.isArray(m)?m:[]).slice().sort((g,f)=>Number(g.order)-Number(f.order)).map(g=>mr(g,n.includeBlockContent))}return{blocks:d,context:o,item:c,success:!0}}const pn=new Set(["feature_image_id","language_id","meta_description","meta_title","slug","status","title"]),mn=new Set(["excerpt","feature_image_id","label","language_id","meta_description","meta_title","published_at","slug","status","subtitle","title"]),Rr=new Set(["description_json","language_id","meta_description","meta_title","short_description","slug","status","title"]),qr=new Set(["excerpt","feature_image_id","label","meta_description","meta_title","published_at","short_description","subtitle"]);function Dr(e){return e==="page"?pn:e==="post"?mn:Rr}function gn(e,t){return qr.has(e)&&t===""?null:t}function He(e,t){if(typeof t!="string")return;const n=e==="product"?["active","archived","draft"]:["archived","draft","published"];if(!n.includes(t))throw new Error(`Status "${t}" is not valid for ${e}. Allowed statuses: ${n.join(", ")}.`)}function Mr(e,t){const n=Dr(t.contentType),r={};for(const[o,i]of Object.entries(e))if(i!==void 0){if(!n.has(o))throw new Error(`Field "${o}" cannot be updated for ${t.contentType} content.`);o==="status"&&He(t.contentType,i),r[o]=gn(o,i)}return r}async function ft(e,t){const n=ce.parse(e),r=x(t),o=await ee(n.cmsTarget,t),i=M(o),a=Mr(n.fields,o),c=Object.keys(a);if(c.length===0)throw new Error("update_current_cms_fields requires at least one supported field.");const u=P({action:"UPDATE CMS FIELDS",context:t,payload:{contentType:o.contentType,entityId:i,fields:a,tool:"update_current_cms_fields"},preview:{contentType:o.contentType,entityId:i,fields:c,slug:o.slug,title:o.title},subject:`${o.contentType} ${String(i)}`});if(u)return u;const d=await W(t,o.contentType,i);typeof a.feature_image_id=="string"&&(a.feature_image_id=await Q(a.feature_image_id,t,typeof o.title=="string"?o.title:void 0));const l=o.contentType==="page"?"pages":o.contentType==="post"?"posts":"products",{data:m,error:h}=await r.from(l).update({...a,updated_at:new Date().toISOString()}).eq("id",i).select("id, language_id, slug, status, title").single();if(h||!m)throw new Error(`Failed to update current ${o.contentType}: ${_(h)}`);return await G(t,o.contentType,i,d),U(t,o,m.slug),{contentType:o.contentType,entityId:i,mutationExecuted:!0,slug:m.slug,success:!0,updatedFields:c}}async function ht(e,t){const n=le.parse(e),r=x(t),o=await ee(n.cmsTarget,t),{data:i,error:a}=await r.from("blocks").select("id, page_id, post_id, product_id, language_id, block_type, content, order").eq("id",n.blockId).single();if(a||!i)throw new Error(`Failed to read block ${n.blockId}: ${_(a)}`);Zt(i,o),t=await V(t,[i.block_type,i.content,n.content]);const c=oe(i.block_type,`Block ${n.blockId}`,t);en(n.blockType,c,`Block ${n.blockId}`);const u=_e(i.content,`Block ${n.blockId}`),d=pr(c,u,n.content,t);j(c,d,`Block ${n.blockId}`,t);const l=P({action:"UPDATE CONTENT BLOCK",context:t,payload:{blockId:n.blockId,blockType:c,content:d,tool:"update_content_block"},preview:{blockId:n.blockId,blockType:c,contentType:o.contentType,entityId:M(o)},subject:`${c} block ${n.blockId}`});if(l)return l;const m=await W(t,o.contentType,M(o)),{data:h,error:g}=await r.from("blocks").update({content:d,updated_at:new Date().toISOString()}).eq("id",n.blockId).select("id, block_type, order").single();if(g||!h)throw new Error(`Failed to update block ${n.blockId}: ${_(g)}`);return await G(t,o.contentType,M(o),m),await Oe({patch:({blocks:f})=>({blocks:f.map(p=>String(p?.id)===String(n.blockId)?{...p,content:d}:p)}),productId:i.product_id,supabase:r}),we([{content:d}],r),U(t,o),{blockId:h.id,blockType:h.block_type,contentUpdated:!0,mutationExecuted:!0,success:!0}}async function yt(e,t){const n=me.parse(e);t=await V(t,n.block);const r=x(t),o=await Y(n,t),i=o.contentType==="product"?o.item.id:Number(o.item.id),a=o.contentType==="page"?"page_id":o.contentType==="post"?"post_id":"product_id",c=async()=>{const{data:T,error:k}=await r.from("blocks").select("id, page_id, post_id, product_id, language_id, block_type, content, order").eq(a,i);if(k)throw new Error(`Failed to read ${o.contentType} blocks: ${_(k)}`);return(Array.isArray(T)?T:[]).sort((v,E)=>Number(v.order)-Number(E.order))},u=T=>{if(n.position==="start")return 0;if(n.position==="end"){const E=T.map(O=>Number(O.order)).filter(Number.isFinite);return E.length>0?Math.max(...E)+1:0}const k=n.anchorBlockId?T.find(E=>Number(E.id)===n.anchorBlockId):n.anchorBlockType?T.find(E=>E.block_type===n.anchorBlockType):null;if(!k)throw new Error(n.anchorBlockType?`Could not find a ${n.anchorBlockType} block to insert ${n.position}.`:`Could not find block ${n.anchorBlockId} to insert ${n.position}.`);const v=Number(k.order);return n.position==="before"?v:v+1},d=$e(n.block,0,t),l=await c(),m=u(l),h={contentType:o.contentType,entityId:o.item.id,languageId:o.item.language_id,slug:o.item.slug,title:o.item.title,translationGroupId:o.item.translation_group_id},g=P({action:"INSERT CONTENT BLOCK",context:t,payload:{block:d,order:m,target:{contentType:o.contentType,id:o.item.id,slug:o.item.slug},tool:"insert_content_block"},preview:{anchorBlockId:n.anchorBlockId,anchorBlockType:n.anchorBlockType,blockType:d.block_type,contentType:o.contentType,entityId:o.item.id,position:n.position,slug:o.item.slug,summary:`Insert ${d.block_type} block ${n.position} ${n.anchorBlockType?`the first ${n.anchorBlockType} block`:n.anchorBlockId?`block ${n.anchorBlockId}`:"the content"} on ${o.contentType} "${o.item.title||o.item.slug}".`,title:o.item.title},subject:`${d.block_type} block on ${o.contentType} ${o.item.id}`});if(g)return g;const f=await c(),p=u(f),b=f.filter(T=>Number(T.order)>=p).sort((T,k)=>Number(k.order)-Number(T.order)),y=await W(t,o.contentType,i);for(const T of b){const{error:k}=await r.from("blocks").update({order:Number(T.order)+1,updated_at:new Date().toISOString()}).eq("id",T.id);if(k)throw new Error(`Failed to shift block ${T.id}: ${_(k)}`)}const{data:w,error:I}=await r.from("blocks").insert({block_type:d.block_type,content:d.content,language_id:o.item.language_id,order:p,page_id:o.contentType==="page"?i:null,post_id:o.contentType==="post"?i:null,product_id:o.contentType==="product"?i:null}).select("id, block_type, order").single();if(I||!w)throw new Error(`Failed to insert content block: ${_(I)}`);return o.contentType==="product"&&await Oe({patch:({blocks:T})=>({blocks:[...T.map(k=>Number(k?.order)>=p?{...k,order:Number(k.order)+1}:k),{block_type:d.block_type,content:d.content,id:w.id,language_id:o.item.language_id,order:p,page_id:null,post_id:null,product_id:i}].sort((k,v)=>Number(k.order)-Number(v.order))}),productId:i,supabase:r}),await G(t,o.contentType,i,y),we([d],r),U(t,h),{blockId:w.id,blockType:w.block_type,contentType:o.contentType,entityId:o.item.id,mutationExecuted:!0,order:w.order,success:!0}}async function bt(e,t){const n=ue.parse(e),r=x(t),o=await ee(n.cmsTarget,t),{data:i,error:a}=await r.from("blocks").select("id, page_id, post_id, product_id, language_id, block_type, content, order").eq("id",n.parentBlockId).single();if(a||!i)throw new Error(`Failed to read parent block ${n.parentBlockId}: ${_(a)}`);Zt(i,o),t=await V(t,[i.block_type,i.content,n.content]);const c=oe(i.block_type,`Parent block ${n.parentBlockId}`,t);if(c!=="section")throw new Error(`Parent block ${n.parentBlockId} must be a section block, not "${c}".`);const u=_e(i.content,`Parent block ${n.parentBlockId}`);j(c,u,`Parent block ${n.parentBlockId}`,t);const l=u.column_blocks?.[n.columnIndex]?.[n.blockIndex];if(!l)throw new Error(`Nested block was not found at column ${n.columnIndex}, index ${n.blockIndex}.`);const m=oe(l.block_type,`Nested block ${n.columnIndex}:${n.blockIndex}`,t);en(n.blockType,m,`Nested block ${n.columnIndex}:${n.blockIndex}`),j(m,n.content,`Nested block ${n.columnIndex}:${n.blockIndex}`,t);const h=u.column_blocks.map((w,I)=>I===n.columnIndex?w.map((T,k)=>k===n.blockIndex?{...T,content:n.content}:T):w),g={...u,column_blocks:h};j(c,g,`Updated parent block ${n.parentBlockId}`,t);const f=P({action:"UPDATE NESTED BLOCK",context:t,payload:{blockIndex:n.blockIndex,columnIndex:n.columnIndex,content:n.content,nestedBlockType:m,parentBlockId:n.parentBlockId,tool:"update_section_column_block"},preview:{blockIndex:n.blockIndex,columnIndex:n.columnIndex,nestedBlockType:m,parentBlockId:n.parentBlockId,parentBlockType:c},subject:`${m} nested block ${n.columnIndex}:${n.blockIndex}`});if(f)return f;const p=await W(t,o.contentType,M(o)),{data:b,error:y}=await r.from("blocks").update({content:g,updated_at:new Date().toISOString()}).eq("id",n.parentBlockId).select("id, block_type").single();if(y||!b)throw new Error(`Failed to update parent block ${n.parentBlockId}: ${_(y)}`);return await Oe({patch:({blocks:w})=>({blocks:w.map(I=>String(I?.id)===String(n.parentBlockId)?{...I,content:g}:I)}),productId:i.product_id,supabase:r}),await G(t,o.contentType,M(o),p),U(t,o),{blockIndex:n.blockIndex,columnIndex:n.columnIndex,mutationExecuted:!0,nestedBlockType:m,parentBlockId:b.id,parentBlockType:b.block_type,success:!0}}async function Re(e,t){const n=ge.parse(e);t=await V(t,n.blocks);const r=x(t),o=ot(t),i=await Be(r,n.languageCode),a=F(n.slug||n.title),c=Le(n.blocks,n.contactEmail,n.title,t),u=await ct({contentType:"page",languageId:i.id,slug:a,supabase:r});if(u)return u;const d=await lt({contentType:"page",languageCode:i.code,languageId:i.id,suppliedTranslationGroupId:n.translationGroupId,supabase:r});if(d.result)return d.result;const l={blocks:c,item:{feature_image_id:n.feature_image_id??null,language_id:i.id,meta_description:n.meta_description??null,meta_title:n.meta_title??null,slug:a,status:n.status,title:n.title,translation_group_id:d.translationGroupId},tool:"create_cms_page"},m=P({action:"CREATE PAGE",context:t,payload:l,preview:{blockCount:c.length,languageCode:i.code,slug:a,status:n.status,title:n.title,translationGroupId:d.translationGroupId},subject:a});if(m)return m;const h=d.translationGroupId||it(),g=await Q(l.item.feature_image_id,t,n.title),{data:f,error:p}=await r.from("pages").insert({...l.item,author_id:o,feature_image_id:g,translation_group_id:h}).select("id, language_id, slug, status, title, translation_group_id").single();if(p||!f?.id)throw new Error(`Failed to create page: ${_(p)}`);try{await ut({blocks:c,contentType:"page",itemId:Number(f.id),languageId:i.id,supabase:r})}catch(b){throw await dt({contentType:"page",itemId:Number(f.id),supabase:r}),b}return U(t,{contentType:"page",entityId:Number(f.id),languageId:i.id,slug:a,title:n.title},a),t?.revalidatePath?.("/cms/pages"),{blockCount:c.length,contentType:"page",editPath:pt("page",f.id),entityId:f.id,mutationExecuted:!0,slug:a,success:!0,title:n.title,translationGroupId:f.translation_group_id}}async function qe(e,t){const n=fe.parse(e);t=await V(t,n.blocks);const r=x(t),o=ot(t),i=await Be(r,n.languageCode),a=F(n.slug||n.title),c=Le(n.blocks,void 0,void 0,t),u=await ct({contentType:"post",languageId:i.id,slug:a,supabase:r});if(u)return u;const d=await lt({contentType:"post",languageCode:i.code,languageId:i.id,suppliedTranslationGroupId:n.translationGroupId,supabase:r});if(d.result)return d.result;const l=n.published_at&&!Number.isNaN(new Date(n.published_at).getTime())?new Date(n.published_at).toISOString():n.published_at??null,m={blocks:c,item:{excerpt:n.excerpt??null,feature_image_id:n.feature_image_id??null,label:n.label??null,language_id:i.id,meta_description:n.meta_description??null,meta_title:n.meta_title??null,published_at:l,slug:a,status:n.status,subtitle:n.subtitle??null,title:n.title,translation_group_id:d.translationGroupId},tool:"create_cms_post"},h=P({action:"CREATE POST",context:t,payload:m,preview:{blockCount:c.length,languageCode:i.code,slug:a,status:n.status,title:n.title,translationGroupId:d.translationGroupId},subject:a});if(h)return h;const g=d.translationGroupId||it(),f=await Q(m.item.feature_image_id,t,n.title),{data:p,error:b}=await r.from("posts").insert({...m.item,author_id:o,feature_image_id:f,translation_group_id:g}).select("id, language_id, slug, status, title, translation_group_id").single();if(b||!p?.id)throw new Error(`Failed to create post: ${_(b)}`);try{await ut({blocks:c,contentType:"post",itemId:Number(p.id),languageId:i.id,supabase:r})}catch(y){throw await dt({contentType:"post",itemId:Number(p.id),supabase:r}),y}return U(t,{contentType:"post",entityId:Number(p.id),languageId:i.id,slug:a,title:n.title},a),t?.revalidatePath?.("/cms/posts"),t?.revalidatePath?.("/articles"),{blockCount:c.length,contentType:"post",editPath:pt("post",p.id),entityId:p.id,mutationExecuted:!0,slug:a,success:!0,title:n.title,translationGroupId:p.translation_group_id}}function jr(e,t){return(t||F(e)||"product").replace(/-/g,"").slice(0,24).toUpperCase()}function fn(e){if(e==null)return;if(typeof e=="string")return Kt.editorDocumentFromHtml(e)??void 0;const t=Array.isArray(e)?{content:e,type:"doc"}:A(e)&&e.type!=="doc"&&Array.isArray(e.content)?{...e,type:"doc"}:e,n=Ut().safeParse(t);if(!n.success){if(A(e)&&typeof e.type=="string"){const r=Ut().safeParse({content:[e],type:"doc"});if(r.success)return r.data}throw new Error(`Product description_json must be an editor document like { "type": "doc", "content": [ { "type": "paragraph", "content": [ { "type": "text", "text": "..." } ] } ] }, or simply an HTML string. Received: ${n.error.issues.map(r=>r.message).join("; ")}`)}return n.data}function Gr(e){const t=o=>!!(o&&Array.isArray(o.content)&&o.content.length>0),n=fn(e.description_json);if(t(n))return n;const r=e.description_html?Kt.editorDocumentFromHtml(e.description_html):null;return t(r)?r:void 0}async function _t(e,t){const n=he.parse(e);t=await V(t,n.blocks);const r=x(t),o=await Be(r,n.languageCode),i=F(n.slug||n.title),a=Le(n.blocks,void 0,void 0,t),c=await ct({contentType:"product",languageId:o.id,slug:i,supabase:r});if(c)return c;const u=await lt({contentType:"product",languageCode:o.code,languageId:o.id,suppliedTranslationGroupId:n.translationGroupId,supabase:r});if(u.result)return u.result;const{createProduct:d,productSchema:l}=await tr(),h=n.product_type==="digital"&&n.payment_provider==="freemius"?n.trial_period_days:0,g=l.parse({description_json:Gr(n),freemius_plan_id:n.freemius_plan_id||"",freemius_product_id:n.freemius_product_id||"",is_taxable:n.is_taxable,language_id:o.id,meta_description:n.meta_description??"",meta_title:n.meta_title??"",payment_provider:n.payment_provider,price:n.price,prices:n.prices||{},product_media:[],product_type:n.product_type,sale_price:n.sale_price??null,sale_prices:n.sale_prices||{},short_description:n.short_description??"",sku:n.sku||jr(n.title,i),slug:i,status:n.status,stock:n.stock,title:n.title,trial_period_days:h,trial_requires_payment_method:h>0?n.trial_requires_payment_method:!1,translation_group_id:u.translationGroupId,upc:n.upc??"",variation_attributes:[],variants:[]}),f=n.images??[],p=P({action:"CREATE PRODUCT",context:t,payload:{blocks:a,images:f,item:g,tool:"create_cms_product"},preview:{blockCount:a.length,descriptionLength:g.description_json?JSON.stringify(g.description_json).length:0,imageCount:f.length,languageCode:o.code,price:g.price,sku:g.sku,slug:i,status:g.status,stock:g.stock,title:g.title,translationGroupId:u.translationGroupId},subject:i});if(p)return p;let b=[],y=null;if(f.length>0)try{if(b=[...new Set(await Jt(f,t,n.title))],b.length===0)throw new Error("None of the provided images could be resolved to a media item.")}catch(I){y=I instanceof Error?I.message:String(I)}const w=await d(r,{...g,product_media:b.map(I=>({media_id:I}))});if(!w?.id)throw new Error("Failed to create product.");try{await ut({blocks:a,contentType:"product",itemId:w.id,languageId:o.id,supabase:r})}catch(I){throw await dt({contentType:"product",itemId:w.id,supabase:r}),I}return U(t,{contentType:"product",entityId:w.id,languageId:o.id,slug:i,title:n.title},i),t?.revalidatePath?.("/cms/products"),{blockCount:a.length,contentType:"product",editPath:pt("product",w.id),entityId:w.id,imageCount:b.length,...y?{imageError:y}:{},mutationExecuted:!0,slug:i,success:!0,title:n.title,translationGroupId:w.translation_group_id}}function wt(e){return e.trim().replace(/[\s-]+/g,"_").toLowerCase()}function Kr(e,t){const n=typeof t=="string"?wt(t):t;return e==="product"?n==="public"||n==="publish"||n==="published"?"active":n:n==="public"||n==="active"||n==="publish"?"published":n}function Vr(e){const t=wt(e.field);return!!(e.startsAt||e.endsAt||t.includes("start")||t.includes("end")||t.includes("schedule")||t.includes("special_date"))}async function Hr(e,t,n){if(e==="price"||e==="sale_price"){if(t==null)return{[e]:null};const r=await Ve(n);return{[e]:Ce(Number(t),r)}}if(e==="prices"||e==="sale_prices"){const r=await Ve(n);return{[e]:sr(t,r)}}return e==="description_json"?{description_json:fn(t)}:{[e]:t}}const Wr=new Set(["language_id","price","sale_price","stock","trial_period_days"]),Jr=new Set(["is_taxable","trial_requires_payment_method"]);function Yr(e,t){if(typeof t!="string")return t;const n=t.trim();if(Wr.has(e)){if(n.toLowerCase()==="null")return null;if(n==="")return t;const r=Number(n);return Number.isFinite(r)?r:t}if(Jr.has(e)){const r=n.toLowerCase();if(r==="true")return!0;if(r==="false")return!1}return t}function Xr(e,t){const n=wt(e.field),o={description:"description_json",feature_image:"feature_image_id",feature_image_id:"feature_image_id",language:"language_id",meta_description:"meta_description",meta_title:"meta_title",payment:"payment_provider",provider:"payment_provider",regular_price:"price",sale:"sale_price",sale_price:"sale_price",short_description:"short_description",taxable:"is_taxable",trial:"trial_period_days",trial_days:"trial_period_days",trial_payment_method_required:"trial_requires_payment_method",type:"product_type"}[n]||n,i=o==="status"?Kr(t.contentType,e.value):Yr(o,e.value);if(t.contentType!=="product"){if(!(t.contentType==="page"?pn:mn).has(o))throw new Error(`Field "${e.field}" cannot be updated for ${t.contentType}.`);return o==="status"&&He(t.contentType,i),{field:o,payload:{[o]:gn(o,i)}}}if(!new Set(["description_json","freemius_plan_id","freemius_product_id","is_taxable","language_id","meta_description","meta_title","payment_provider","price","prices","product_type","sale_price","sale_prices","short_description","sku","slug","status","stock","title","trial_period_days","trial_requires_payment_method","upc"]).has(o))throw new Error(`Field "${e.field}" cannot be updated for product.`);if(o==="status"&&He("product",i),(o==="price"||o==="sale_price")&&i!==null&&(typeof i!="number"||i<0))throw new Error(`${o} must be a non-negative number or null.`);if(o==="stock"&&(!Number.isInteger(i)||Number(i)<0))throw new Error("stock must be a non-negative integer.");if(o==="trial_period_days"&&(!Number.isInteger(i)||Number(i)<0))throw new Error("trial_period_days must be a non-negative integer.");if(o==="trial_requires_payment_method"&&typeof i!="boolean")throw new Error("trial_requires_payment_method must be a boolean.");return{field:o,payload:{[o]:i}}}async function kt(e,t){const n=ye.parse(e);if(Vr(n))return{message:"Scheduled product specials are not supported by the current product schema yet. I can set or clear sale_price now, but not start/end dates.",mutationExecuted:!1,success:!1,unsupported:!0};const r=await Y(n,t),o=Xr(n,r),i=o.field;let a=o.payload;if(i==="language_id"&&typeof a.language_id=="string"){const h=await Z(x(t),a.language_id);a={...a,language_id:h.id}}const c=P({action:"UPDATE FIELD",context:t,payload:{contentType:r.contentType,entityId:r.item.id,field:i,payload:a,tool:"update_cms_item_field"},preview:{contentType:r.contentType,field:i,from:r.item[i],slug:r.item.slug,title:r.item.title,to:a[i]},subject:`${r.contentType} ${r.item.slug||r.item.id} ${i}`});if(c)return c;const u=await W(t,r.contentType,r.item.id);if(r.contentType==="product"){const h=x(t),g=await Hr(i,a[i],h),{data:f,error:p}=await h.from("products").update({...g,updated_at:new Date().toISOString()}).eq("id",r.item.id).select("id, language_id, slug, status, title").single();if(p||!f)throw new Error(`Failed to update product: ${_(p)}`);return U(t,{contentType:"product",entityId:String(f.id),languageId:f.language_id,slug:f.slug,title:f.title},f.slug),await G(t,"product",f.id,u),{contentType:"product",entityId:f.id,field:i,mutationExecuted:!0,slug:f.slug,success:!0,updatedFields:[i]}}i==="feature_image_id"&&typeof a.feature_image_id=="string"&&(a={...a,feature_image_id:await Q(a.feature_image_id,t,typeof r.item.title=="string"?r.item.title:void 0)});const d=r.contentType==="page"?"pages":"posts",{data:l,error:m}=await x(t).from(d).update({...a,updated_at:new Date().toISOString()}).eq("id",r.item.id).select("id, language_id, slug, status, title").single();if(m||!l)throw new Error(`Failed to update ${r.contentType}: ${_(m)}`);return U(t,{contentType:r.contentType,entityId:Number(l.id),languageId:l.language_id,slug:l.slug,title:l.title},l.slug),await G(t,r.contentType,l.id,u),{contentType:r.contentType,entityId:l.id,field:i,mutationExecuted:!0,slug:l.slug,success:!0,updatedFields:[i]}}async function hn(e,t){const n=tt.parse(e),r=await Y(n,t);if(r.contentType==="product")return{affectedCount:1,collectionPath:Lt("product"),contentType:"product",item:r.item,navigationLinkCount:0,publicPaths:r.item.slug?[`/product/${r.item.slug}`]:[],targetIds:[r.item.id]};const o=r.contentType==="page"?"pages":"posts",{data:i,error:a}=await x(t).from(o).select("id, slug, title, translation_group_id").eq("translation_group_id",r.item.translation_group_id);if(a)throw new Error(`Failed to inspect related ${r.contentType}s: ${_(a)}`);const c=Array.isArray(i)?i:[],u=c.map(g=>r.contentType==="page"?g.slug==="home"?"/":`/${g.slug}`:`/article/${g.slug}`).filter(Boolean),d=new Set(u),{data:l,error:m}=await x(t).from("navigation_items").select("id, url");if(m)throw new Error(`Failed to inspect related navigation links: ${_(m)}`);const h=(Array.isArray(l)?l:[]).filter(g=>d.has(g.url)).length;return{affectedCount:c.length,collectionPath:Lt(r.contentType),contentType:r.contentType,item:r.item,navigationLinkCount:h,publicPaths:u,targetIds:c.map(g=>g.id)}}function yn(e){const t=e.item.title||e.item.slug||"selected item",n=e.item.slug?` (${e.item.slug})`:"";if(e.contentType==="product")return`Delete product "${t}"${n}.`;const r=[`${N(e.affectedCount,"language version")}`,e.navigationLinkCount>0?`${N(e.navigationLinkCount,"navigation link")}`:null].filter(Boolean);return`Delete ${e.contentType} "${t}"${n}, including ${r.join(" and ")}.`}async function bn(e,t){const n=await hn(e,t);return{...Qt({action:`DELETE ${n.contentType}`,payload:{affectedCount:n.affectedCount,contentType:n.contentType,targetIds:n.targetIds,tool:"delete_cms_item"},preview:{affectedCount:n.affectedCount,collectionPath:n.collectionPath,contentType:n.contentType,navigationLinkCount:n.navigationLinkCount,publicPaths:n.publicPaths,slug:n.item.slug,summary:yn(n),title:n.item.title},subject:`${n.item.id} ${n.item.slug||""}`}),preparedDelete:!0}}async function It(e,t){const n=be.parse(e),r=await hn(n,t),o=P({action:`DELETE ${r.contentType}`,context:t,payload:{affectedCount:r.affectedCount,contentType:r.contentType,targetIds:r.targetIds,tool:"delete_cms_item"},preview:{affectedCount:r.affectedCount,collectionPath:r.collectionPath,contentType:r.contentType,navigationLinkCount:r.navigationLinkCount,publicPaths:r.publicPaths,slug:r.item.slug,summary:yn(r),title:r.item.title},subject:`${r.item.id} ${r.item.slug||""}`});if(o)return o;const i=x(t);if(r.contentType==="product"){const{error:c}=await i.from("products").delete().eq("id",r.item.id);if(c)throw new Error(`Failed to delete product: ${_(c)}`)}else{for(const d of r.publicPaths)await i.from("navigation_items").delete().eq("url",d);const c=r.contentType==="page"?"pages":"posts",{error:u}=await i.from(c).delete().eq("translation_group_id",r.item.translation_group_id);if(u)throw new Error(`Failed to delete ${r.contentType}: ${_(u)}`)}const a=t?.revalidatePath??rt();return a&&(a(r.collectionPath),a("/cms/navigation"),r.publicPaths.forEach(c=>a(c))),{affectedCount:r.affectedCount,collectionPath:r.collectionPath,contentType:r.contentType,mutationExecuted:!0,redirectPath:r.collectionPath,success:!0}}async function Dt(e,t){switch(e.tool){case"create_cms_page":return Re(e.input,t);case"create_cms_post":return qe(e.input,t);case"create_cms_product":return _t(e.input,t);case"delete_cms_item":return It(e.input,t);case"update_cms_item_field":return kt(e.input,t);case"update_content_block":return ht(e.input,t);case"insert_content_block":return yt(e.input,t);case"update_current_cms_fields":return ft(e.input,t);case"update_footer":return gt(e.input,t);case"update_navigation_bar":return mt(e.input,t);case"update_section_column_block":return bt(e.input,t);case"set_content_images":return zt(e.input,t)}}function Qr(e,t){if(e.tool!=="create_cms_page"&&e.tool!=="create_cms_post"&&e.tool!=="create_cms_product"||e.input.translationGroupId||!e.input.languageCode)return e;const n=t[e.tool];return n?{...e,input:{...e.input,translationGroupId:n}}:e}function Mt(e){return e==="create_cms_page"?"page":e==="create_cms_post"?"post":"product"}function Zr(e,t,n){if(e.tool!=="set_content_images")return e;const r=e.input;if(r.entityId!==void 0)return e;const o=r.slug?t.get(`${r.contentType||"product"}:${F(r.slug)}`):n;return o?{...e,input:{...r,contentType:o.contentType,entityId:o.entityId}}:e}async function _n(e,t){const n=nt.parse(e),r=new Set(n.actions.filter(g=>g.tool==="create_cms_page"||g.tool==="create_cms_post"||g.tool==="create_cms_product").map(g=>{const f=g.input;return`${Mt(g.tool)}:${F(f.slug||f.title||"")}`})),o=g=>{if(g.tool!=="set_content_images")return!1;const f=g.input;return f.slug?r.has(`${f.contentType||"product"}:${F(f.slug)}`):r.size>0};if(!t?.skipConfirmation){const g=[];for(const b of n.actions){if(o(b)){const w=b.input;g.push(`Set ${N(w.images.length,"image")} on the ${w.slug?`"${w.slug}"`:"new"} item created in this plan.`);continue}const y=await Dt(b,{...t,latestUserMessage:null});if(!y||typeof y!="object")return{message:`Could not prepare action ${g.length+1}.`,mutationExecuted:!1,success:!1};if(y.success===!1||y.unsupported===!0)return y;y.requiresConfirmation===!0&&y.preview?g.push(or(b.tool,y.preview)):g.push(`Run ${b.tool.replace(/_/g," ")}.`)}const f=n.summary||`Complete ${N(n.actions.length,"CMS action")}.`,p=P({action:"EXECUTE CMS ACTION PLAN",context:t,payload:{actions:n.actions,tool:"execute_cms_action_plan"},preview:{actionCount:n.actions.length,actionSummaries:g,summary:f},subject:`${n.actions.length} actions`});if(p)return p}const i={...t,skipConfirmation:!0},a=[];let c=!1,u=null,d=null;const l={},m=new Map;let h=null;for(const[g,f]of n.actions.entries()){const p=Zr(Qr(f,l),m,h),b=await Dt(p,i);if(a.push({output:b,tool:p.tool}),b&&typeof b=="object"){const y=b;if(y.mutationExecuted===!0&&(c=!0),!u&&typeof y.editPath=="string"&&(u=y.editPath),typeof y.redirectPath=="string"&&(d=y.redirectPath),(p.tool==="create_cms_page"||p.tool==="create_cms_post"||p.tool==="create_cms_product")&&(typeof y.translationGroupId=="string"&&(l[p.tool]=y.translationGroupId),y.entityId!==void 0&&y.entityId!==null)){const w=Mt(p.tool),I={contentType:w,entityId:y.entityId};h=I,typeof y.slug=="string"&&m.set(`${w}:${y.slug}`,I)}if(y.success===!1||y.unsupported===!0)return{actionCount:n.actions.length,failedActionIndex:g,failedTool:p.tool,message:typeof y.message=="string"?y.message:`Action ${g+1} failed.`,mutationExecuted:c,results:a,success:!1,...u?{editPath:u}:{},...d?{redirectPath:d}:{}}}}return{actionCount:n.actions.length,editPath:d?void 0:u??void 0,mutationExecuted:c,redirectPath:d??void 0,results:a,success:!0,summary:n.summary??null}}const Tt=s.z.strictObject({maxChars:s.z.number().int().min(500).max(2e4).default(8e3).describe("Maximum characters of readable body text to return."),url:s.z.string().trim().min(1).max(2048).refine(e=>/^https?:\/\//i.test(e),"URL must start with http:// or https://.")}),eo=12e3,jt=2e6;function to(e){const t=e.match(/^::ffff:(.+)$/i);if(!t)return null;const n=t[1];if(/^\d{1,3}(\.\d{1,3}){3}$/.test(n))return n;const r=n.match(/^([0-9a-f]{1,4}):([0-9a-f]{1,4})$/i);if(!r)return null;const o=Number.parseInt(r[1],16),i=Number.parseInt(r[2],16);return[o>>8&255,o&255,i>>8&255,i&255].join(".")}function Ae(e){const t=e.trim().toLowerCase().replace(/\.$/,"").replace(/^\[|\]$/g,"");if(!t||t==="localhost"||t.endsWith(".localhost")||t.endsWith(".local")||t.endsWith(".internal")||t==="metadata.google.internal"||t==="0.0.0.0"||t==="::"||t==="::1"||t.startsWith("fe80:")||t.startsWith("fc")||t.startsWith("fd"))return!0;const n=to(t);if(n)return Ae(n);const r=t.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/);if(r){const o=Number(r[1]),i=Number(r[2]);if(o===10||o===127||o===0||o===192&&i===168||o===169&&i===254||o===172&&i>=16&&i<=31)return!0}return!1}function Ie(e){return e.replace(/<[^>]+>/g," ").replace(/ /gi," ").replace(/&/gi,"&").replace(/</gi,"<").replace(/>/gi,">").replace(/"/gi,'"').replace(/'/gi,"'").replace(/\s+/g," ").trim()}function no(e){return e.trim().replace(/&/gi,"&").replace(/&/g,"&").replace(/"/gi,'"').replace(/'/g,"'")}const wn=/\.(avif|gif|jpe?g|png|webp)(?:[?#]|$)/i,kn=/(?:^|[/_-])(?:sprite|icon|favicon|logo|placeholder|pixel|spacer|blank|avatar|badge|flag|loader|spinner|1x1|transparent|watermark|payment|visa|mastercard|paypal|amex|social|share|facebook|twitter|instagram|youtube|pinterest|linkedin)(?:[/_.-]|$)/i;function ze(e,t){if(typeof e!="string")return null;const n=no(e);if(!n||n.startsWith("data:"))return null;try{const r=new URL(n,t);return r.protocol!=="http:"&&r.protocol!=="https:"?null:r.toString()}catch{return null}}function ro(e){let t=null;for(const n of e.split(",")){const r=n.trim().split(/\s+/),o=r[0];if(!o)continue;const i=r[1]||"",a=i.match(/^(\d+(?:\.\d+)?)w$/i),c=i.match(/^(\d+(?:\.\d+)?)x$/i),u=a?Number(a[1]):c?Number(c[1])*1e3:1;(!t||u>t.weight)&&(t={url:o,weight:u})}return t?.url??null}function L(e,t){const n=e.match(new RegExp(`\\b${t}\\s*=\\s*(?:"([^"]*)"|'([^']*)'|([^\\s>]+))`,"i"));return n?n[1]??n[2]??n[3]??null:null}function oo(e,t){const n=[],r=[],o=(c,u)=>{if(typeof c=="string"){const d=ze(c,t);d&&u.push(d);return}if(Array.isArray(c)){for(const d of c)o(d,u);return}c&&typeof c=="object"&&(o(c.url,u),o(c.contentUrl,u))},i=(c,u)=>{if(u>8||!c||typeof c!="object")return;if(Array.isArray(c)){for(const g of c)i(g,u+1);return}const d=c,l=d["@type"],h=(Array.isArray(l)?l:[l]).filter(g=>typeof g=="string").map(g=>g.toLowerCase()).some(g=>g==="product"||g==="productgroup"||g==="itempage");"image"in d&&o(d.image,h?n:r);for(const g of Object.values(d))i(g,u+1)},a=e.matchAll(/<script\b[^>]*type\s*=\s*["']application\/ld\+json["'][^>]*>([\s\S]*?)<\/script>/gi);for(const c of a){const u=(c[1]||"").trim();if(u)try{i(JSON.parse(u),0)}catch{}}return[...n,...r]}const In=/(?:^|[/_-])(?:thumbnails?|thumbs?|small|mini)(?:[/_.-]|$)/i;function Tn(e){try{const{pathname:t}=new URL(e);return decodeURIComponent(t.slice(t.lastIndexOf("/")+1)).toLowerCase()||null}catch{return null}}function io(e,t){const n=new Map;for(const r of e.matchAll(/<a\b[^>]*>/gi)){const o=ze(L(r[0],"href"),t);if(!o||!wn.test(o)||In.test(o)||kn.test(o))continue;const i=Tn(o);i&&!n.has(i)&&n.set(i,o)}return n}function ao(e,t){const n=[...oo(e,t)],r=[/<meta\b[^>]*\b(?:property|name)\s*=\s*["'](?:og:image:secure_url|og:image:url|og:image)["'][^>]*>/gi,/<meta\b[^>]*\b(?:property|name)\s*=\s*["'](?:twitter:image:src|twitter:image)["'][^>]*>/gi,/<meta\b[^>]*\bitemprop\s*=\s*["']image["'][^>]*>/gi,/<link\b[^>]*\brel\s*=\s*["']image_src["'][^>]*>/gi];for(const l of r)for(const m of e.matchAll(l)){const h=m[0],g=ze(L(h,"content")||L(h,"href"),t);g&&n.push(g)}const o=[];for(const l of e.matchAll(/<img\b[^>]*>/gi)){const m=l[0],h=L(m,"srcset")||L(m,"data-srcset"),g=[h?ro(h):null,L(m,"src"),L(m,"data-src"),L(m,"data-original"),L(m,"data-lazy-src"),L(m,"data-image")];let f=null;for(const b of g)if(f=ze(b,t),f)break;if(!f||kn.test(f))continue;const p=Number(L(m,"width"));Number.isFinite(p)&&p>0&&p<200||o.push(f)}const i=l=>wn.test(l);n.push(...o.filter(i),...o.filter(l=>!i(l)));const a=io(e,t),c=l=>{if(!In.test(l))return l;const m=Tn(l);return m&&a.get(m)||l},u=new Set,d=[];for(const l of n){const m=c(l);if(!u.has(m)&&(u.add(m),d.push(m),d.length>=12))break}return{images:d,mainImage:d[0]??null}}function so(e,t,n){const r=e.replace(/<script\b[\s\S]*?<\/script>/gi," ").replace(/<style\b[\s\S]*?<\/style>/gi," ").replace(/<noscript\b[\s\S]*?<\/noscript>/gi," ").replace(/<svg\b[\s\S]*?<\/svg>/gi," "),{images:o,mainImage:i}=ao(e,n),a=e.match(/<title\b[^>]*>([\s\S]*?)<\/title>/i),c=e.match(/<meta[^>]+name=["']description["'][^>]*content=["']([^"']*)["'][^>]*>/i)||e.match(/<meta[^>]+content=["']([^"']*)["'][^>]*name=["']description["'][^>]*>/i),u=[...r.matchAll(/<h([1-3])\b[^>]*>([\s\S]*?)<\/h\1>/gi)].map(m=>Ie(m[2])).filter(Boolean).slice(0,40),d=r.match(/<body\b[^>]*>([\s\S]*?)<\/body>/i),l=Ie(d?.[1]??r);return{description:c?Ie(c[1]):"",headings:u,images:o,mainImage:i,text:l.slice(0,t),title:a?Ie(a[1]):"",truncated:l.length>t}}async function vn(e){const t=Tt.parse(e);let n;try{n=new URL(t.url)}catch{return{message:`"${t.url}" is not a valid URL.`,success:!1,url:t.url}}if(n.protocol!=="http:"&&n.protocol!=="https:")return{message:"Only http and https URLs can be fetched.",success:!1,url:t.url};if(Ae(n.hostname))return{message:"Refusing to fetch a local, private, or internal address.",success:!1,url:t.url};const r=new AbortController,o=setTimeout(()=>r.abort(),eo);try{const i=await fetch(n.toString(),{headers:{accept:"text/html,application/xhtml+xml,text/plain","user-agent":"NextBlockCortexAI/1.0 (+https://nextblock.dev)"},redirect:"follow",signal:r.signal});if(!i.ok)return{message:`The URL responded with HTTP ${i.status}.`,status:i.status,success:!1,url:t.url};const a=i.url||n.toString();try{if(Ae(new URL(a).hostname))return{message:"The URL redirected to a blocked internal address.",success:!1,url:t.url}}catch{}const c=i.headers.get("content-type")||"";if(!/text\/html|text\/plain|application\/xhtml/i.test(c))return{contentType:c,message:`The URL is not an HTML or text page (content-type: ${c||"unknown"}).`,success:!1,url:t.url};const u=await i.text(),d=u.length>jt?u.slice(0,jt):u,l=so(d,t.maxChars,a);return!l.text&&!l.title?{message:"The URL returned no readable text content.",success:!1,url:t.url}:{description:l.description,finalUrl:a,headings:l.headings,images:l.images,mainImage:l.mainImage,success:!0,text:l.text,title:l.title,truncated:l.truncated,url:t.url}}catch(i){return{message:i instanceof Error&&(i.name==="AbortError"||/abort/i.test(i.message))?"Fetching the URL timed out.":`Failed to fetch the URL: ${_(i)}`,success:!1,url:t.url}}finally{clearTimeout(o)}}const vt=s.z.strictObject({count:s.z.number().int().min(1).max(15).default(6),orientation:s.z.enum(["landscape","portrait","square"]).optional().describe("Preferred image orientation. Use landscape for hero/section backgrounds."),query:s.z.string().trim().min(2).max(200).describe('What the photos should depict, e.g. "herbal supplements".')}),co=12e3;async function De(e){let t=null,n=null;if(e)try{const{CORTEX_AI_PEXELS_SETTING_KEY:o,CORTEX_AI_UNSPLASH_SETTING_KEY:i,decryptStoredOpenRouterApiKey:a}=await Promise.resolve().then(()=>require("./ai-config.cjs.js")),c=l=>{if(!l)return null;try{const m=a(l);return typeof m=="string"&&m.trim()?m.trim():null}catch{return null}},{data:u}=await e.from("site_settings").select("key, value").in("key",[o,i]),d=Array.isArray(u)?u:[];t=c(d.find(l=>l.key===o)?.value),n=c(d.find(l=>l.key===i)?.value)}catch{}t||(t=process.env.PEXELS_API_KEY?.trim()||null),n||(n=process.env.UNSPLASH_ACCESS_KEY?.trim()||null);const r=[];return t&&r.push({apiKey:t,provider:"pexels"}),n&&r.push({apiKey:n,provider:"unsplash"}),r}async function lo(e){return(await De(e))[0]??null}async function uo(e){if(e)try{const{CORTEX_AI_UNSPLASH_APP_NAME_SETTING_KEY:t}=await Promise.resolve().then(()=>require("./ai-config.cjs.js")),{data:n}=await e.from("site_settings").select("value").eq("key",t).maybeSingle(),r=n?.value;if(typeof r=="string"&&r.trim())return r.trim()}catch{}return process.env.UNSPLASH_APP_NAME?.trim()||null}async function Gt(e,t){const n=new AbortController,r=setTimeout(()=>n.abort(),co);try{const o=await fetch(e,{headers:t,signal:n.signal});if(!o.ok)throw new Error(`Stock photo provider responded with HTTP ${o.status}.`);return await o.json()}finally{clearTimeout(r)}}function Te(e){const t=Number(e);return Number.isFinite(t)&&t>0?t:null}function We(e,t){if(!A(e))return;const n=r=>{A(r)&&r.provider==="unsplash"&&typeof r.downloadLocation=="string"&&r.downloadLocation.trim()&&t.add(r.downloadLocation.trim())};if(n(e.attribution),A(e.background)&&A(e.background.image)&&n(e.background.image.attribution),Array.isArray(e.column_blocks)){for(const r of e.column_blocks)if(Array.isArray(r))for(const o of r)A(o)&&We(o.content,t)}if(Array.isArray(e.slides))for(const r of e.slides)We(r,t)}async function we(e,t){try{const n=new Set;for(const i of e)We(i?.content,n);if(n.size===0)return;const o=(await De(t)).find(i=>i.provider==="unsplash");if(!o)return;await Promise.all([...n].map(i=>fetch(i,{headers:{Authorization:`Client-ID ${o.apiKey}`}}).catch(()=>{})))}catch{}}async function po(e,t,n){const r=new URLSearchParams({per_page:String(t.count),query:t.query});if(t.orientation&&r.set("orientation",t.orientation),e.provider==="pexels"){const i=await Gt(`https://api.pexels.com/v1/search?${r.toString()}`,{Authorization:e.apiKey});return(Array.isArray(i?.photos)?i.photos:[]).map(a=>{const c=typeof a?.photographer=="string"?a.photographer:null;return{alt:typeof a?.alt=="string"&&a.alt.trim()?a.alt.trim():t.query,credit:c?`Photo by ${c} on Pexels`:"Photo on Pexels",downloadLocation:null,height:Te(a?.height),photographer:c,photographerUrl:typeof a?.photographer_url=="string"?a.photographer_url:null,provider:"pexels",sourceUrl:typeof a?.url=="string"?a.url:null,thumbnailUrl:a?.src?.medium||a?.src?.large||null,url:a?.src?.large2x||a?.src?.large||a?.src?.original||null,width:Te(a?.width)}}).filter(a=>typeof a.url=="string")}const o=await Gt(`https://api.unsplash.com/search/photos?${r.toString()}`,{Authorization:`Client-ID ${e.apiKey}`});return(Array.isArray(o?.results)?o.results:[]).map(i=>{const a=typeof i?.user?.name=="string"?i.user.name:null;return{alt:typeof i?.alt_description=="string"&&i.alt_description.trim()||typeof i?.description=="string"&&i.description.trim()||t.query,credit:a?`Photo by ${a} on Unsplash`:"Photo on Unsplash",downloadLocation:typeof i?.links?.download_location=="string"?i.links.download_location:null,height:Te(i?.height),photographer:a,photographerUrl:typeof i?.user?.links?.html=="string"?i.user.links.html:null,provider:"unsplash",sourceUrl:typeof i?.links?.html=="string"?i.links.html:null,thumbnailUrl:i?.urls?.small||i?.urls?.thumb||null,url:i?.urls?.regular||i?.urls?.full||i?.urls?.raw||null,utmSource:n||null,width:Te(i?.width)}}).filter(i=>typeof i.url=="string")}async function Cn(e,t){const n=vt.parse(e),r=await De(t?.supabase);if(r.length===0)return{message:"No stock photo provider is configured. Add a free Pexels or Unsplash API key in /cms/settings/cortex-ai (or set PEXELS_API_KEY / UNSPLASH_ACCESS_KEY).",photos:[],success:!1};const o=r.some(c=>c.provider==="unsplash")?await uo(t?.supabase):null,i=[];let a=null;for(const c of r){i.push(c.provider);try{const u=await po(c,n,o);if(u.length>0)return{attemptedProviders:i,photos:u,provider:c.provider,query:n.query,success:!0,usageGuidance:c.provider==="unsplash"?'Unsplash photos: keep them hotlinked (use `url` as external_url; never save an Unsplash photo to the media library) and attribute each one — copy the photo\'s attribution fields into the image content\'s `attribution` (photographer, photographerUrl, sourceUrl, downloadLocation, utmSource, provider "unsplash"). The site renders the "Photo by … on Unsplash" credit from `attribution` automatically, so do NOT also copy the credit into `caption` (leave caption empty unless you have a genuine descriptive caption). 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(u){a=u}}return{attemptedProviders:i,message:a?`Stock photo search failed across ${i.join(", ")}: ${_(a)}`:`No matching stock photos found for "${n.query}".`,photos:[],success:!1}}const Ct=J.extend({blocks:s.z.array(de).min(1).max(20),meta:s.z.strictObject({meta_description:s.z.string().max(500).nullable().optional(),meta_title:s.z.string().max(160).nullable().optional(),slug:s.z.string().trim().min(1).max(300).optional(),status:s.z.enum(["draft","published","archived"]).optional(),title:s.z.string().trim().min(1).max(300).optional()}).partial().optional()}),mo=["custom_canonical","excerpt","feature_image_id","label","language_id","meta_description","meta_title","published_at","slug","status","subtitle","title","translation_group_id"];function go(e){const t={};for(const n of mo)n in e&&e[n]!==void 0&&(t[n]=e[n]);return t}function fo(e,t){if(!t)return null;const n=e==="page"?t==="home"?"/":`/${t}`:`/article/${t}`;return`/api/draft/start?path=${encodeURIComponent(n)}`}async function Sn(e,t){const n=Ct.parse(e);t=await V(t,n.blocks);const r=x(t),o=ot(t),i=await Y(n,t);if(i.contentType==="product")throw new Error("rewrite_page_draft supports pages and posts only. Products use description_json, not page blocks.");const a=i.contentType,c=Number(i.item.id);if(!Number.isInteger(c)||c<=0)throw new Error("Could not resolve a valid page/post id for the draft rewrite.");const u=Number(i.item.language_id);if(!Number.isInteger(u)||u<=0)throw new Error("The target page/post is missing a language id.");const l=Le(n.blocks,void 0,void 0,t).map((k,v)=>({block_type:k.block_type,content:k.content,language_id:u,order:v,page_id:a==="page"?c:null,post_id:a==="post"?c:null,product_id:null})),m=go(i.item);if(n.meta)for(const[k,v]of Object.entries(n.meta))v!==void 0&&(m[k]=v);const h=Yt(typeof m.slug=="string"?m.slug:i.item.slug),g=typeof m.title=="string"&&m.title.trim()?m.title:String(i.item.title||h||"Untitled"),f=a==="page"?`/cms/pages/${c}/edit`:`/cms/posts/${c}/edit`,p=fo(a,h),y=P({action:"REWRITE DRAFT",context:t,payload:{blocks:l,meta:m,parent_id:c,parent_type:a,tool:"rewrite_page_draft"},preview:{blockCount:l.length,contentType:a,slug:h,summary:`Stage a Live Draft that replaces the ${a} "${g}" with ${N(l.length,"new block")}. Nothing goes live until you review the draft and click Publish (which also saves a revision snapshot).`,title:g},subject:`${a}-${c}`});if(y)return y;const w=Number(i.item.version)||1,{error:I}=await r.from("content_drafts").delete().eq("parent_type",a).eq("parent_id",c);if(I)throw new Error(`Failed to clear the existing draft: ${_(I)}`);const{error:T}=await r.from("content_drafts").insert({author_id:o,base_version:w,blocks:l,meta:m,parent_id:c,parent_type:a});if(T)throw new Error(`Failed to save the draft: ${_(T)}`);return we(l,r),U(t,{contentType:a,entityId:c,slug:h},h),{blockCount:l.length,contentType:a,draftPreviewPath:p,editPath:f,entityId:c,isDraft:!0,mutationExecuted:!0,slug:h,success:!0,title:g}}const St=s.z.strictObject({attributes:s.z.array(s.z.strictObject({name:s.z.string().trim().min(1).max(120).describe('Attribute name, e.g. "Size" or "Flavour".'),terms:s.z.array(s.z.string().trim().min(1).max(120)).min(1).max(50).describe('Every possible value for this attribute, e.g. ["100 ml", "500 ml"].')})).max(5).optional().describe("The option axes this product varies on. Attributes and terms are global and reused across products: an existing one with the same name is matched, never duplicated. Omit if the attributes already exist."),entityId:s.z.union([s.z.number().int().positive(),s.z.string().trim().min(1).max(120)]).optional(),mode:s.z.enum(["replace","append"]).default("replace").describe(`"replace" removes the product's existing variants first; "append" keeps them and adds these.`),slug:s.z.string().trim().min(1).max(300).optional(),title:s.z.string().trim().min(1).max(300).optional(),variants:s.z.array(s.z.strictObject({image:s.z.string().trim().min(1).max(2048).optional().describe("Variant-specific image: an https:// URL (imported automatically) or a media library id."),options:s.z.record(s.z.string(),s.z.string()).describe('Which term this variant is, per attribute, e.g. { "Size": "500 ml" }. Every attribute must be given a value.'),price:s.z.number().min(0).optional().describe("Price in major units (25 = $25.00). Defaults to the product price."),sale_price:s.z.number().min(0).nullable().optional().describe("Sale price in major units, or null for none."),sku:s.z.string().trim().min(1).max(120).describe("Unique SKU for this variant."),stock:s.z.number().int().min(0).default(0),upc:s.z.string().trim().max(120).nullable().optional()})).min(1).max(50)});async function ho(e,t){const n=F(t.name),{data:r}=await e.from("product_attributes").select("id").eq("slug",n).maybeSingle();let o=r?.id;if(!o){const{data:a,error:c}=await e.from("product_attributes").insert({name:t.name,slug:n}).select("id").single();if(c||!a?.id)throw new Error(`Could not create the "${t.name}" attribute: ${_(c)}`);o=a.id}const i=new Map;for(let a=0;a<t.terms.length;a+=1){const c=t.terms[a],u=F(c),{data:d}=await e.from("product_attribute_terms").select("id").eq("attribute_id",o).eq("slug",u).maybeSingle();if(d?.id){i.set(c,d.id);continue}const{data:l,error:m}=await e.from("product_attribute_terms").insert({attribute_id:o,slug:u,sort_order:a,value:c}).select("id").single();if(m||!l?.id)throw new Error(`Could not create the "${c}" option: ${_(m)}`);i.set(c,l.id)}return{attributeId:o,termIdByValue:i}}async function xn(e,t){const n=St.parse(e),r=x(t),i=(await Y({contentType:"product",...n.entityId!==void 0?{entityId:n.entityId}:{},...n.slug?{slug:n.slug}:{},...n.title?{title:n.title}:{}},t)).item,a=String(i.id),c=P({action:"SET VARIANTS",context:t,payload:{entityId:a,mode:n.mode,variantCount:n.variants.length},preview:{contentType:"product",slug:i.slug,summary:`${n.mode==="replace"?"Replace":"Add"} ${N(n.variants.length,"variant")} on "${i.title}". Product stock becomes the sum of variant stock.`,title:i.title},subject:`product-${a}-variants`});if(c)return c;const u=new Map;for(const p of n.attributes??[]){const{termIdByValue:b}=await ho(r,p);u.set(p.name,b)}for(const p of n.variants)for(const[b,y]of Object.entries(p.options)){if(u.get(b)?.has(y))continue;const{data:w}=await r.from("product_attributes").select("id").eq("slug",F(b)).maybeSingle();if(!w?.id)throw new Error(`Unknown attribute "${b}". Pass it in \`attributes\` with its full list of terms.`);const{data:I}=await r.from("product_attribute_terms").select("id").eq("attribute_id",w.id).eq("slug",F(y)).maybeSingle();if(!I?.id)throw new Error(`Unknown option "${y}" for attribute "${b}". Add it to that attribute's \`terms\`.`);const T=u.get(b)??new Map;T.set(y,I.id),u.set(b,T)}if(n.mode==="replace"){const{error:p}=await r.from("product_variants").delete().eq("product_id",a);if(p)throw new Error(`Could not clear the existing variants: ${_(p)}`)}const d=await Ve(r),l=Number(i.price)||0,m=[];for(const p of n.variants){const b=p.image?await Q(p.image,t,`${i.title} ${p.sku}`):null,{data:y,error:w}=await r.from("product_variants").insert({main_media_id:b,price:p.price===void 0?l:Ce(p.price,d),product_id:a,sale_price:p.sale_price===void 0||p.sale_price===null?null:Ce(p.sale_price,d),sku:p.sku,stock_quantity:p.stock,upc:p.upc??null}).select("id").single();if(w||!y?.id)throw new Error(`Could not create variant "${p.sku}": ${_(w)}`);const I=Object.entries(p.options).map(([T,k])=>({attribute_term_id:u.get(T)?.get(k),variant_id:y.id}));if(I.length>0){const{error:T}=await r.from("variant_attribute_mapping").insert(I);if(T)throw new Error(`Could not link variant "${p.sku}" to its options: ${_(T)}`)}m.push(p.sku)}const{data:h}=await r.from("product_variants").select("stock_quantity").eq("product_id",a),g=(h??[]).reduce((p,b)=>p+(Number(b?.stock_quantity)||0),0),{error:f}=await r.from("products").update({stock:g}).eq("id",a);if(f)throw new Error(`Variants saved, but the product stock total failed: ${_(f)}`);return U(t,{contentType:"product",entityId:a,slug:i.slug,title:i.title},i.slug),{contentType:"product",entityId:a,mode:n.mode,mutationExecuted:!0,skus:m,slug:i.slug,success:!0,totalStock:g,variantCount:m.length}}const xt=s.z.strictObject({items:s.z.array(s.z.strictObject({contentType:s.z.enum(["page","post"]).default("page"),slug:s.z.string().trim().min(1).max(300).describe("Slug of the source page or post."),title:s.z.string().trim().min(1).max(300).optional().describe("Translated title. Defaults to translating the source title."),translations:s.z.record(s.z.string(),s.z.string()).describe("Source string -> translated string for every visible string in THIS item.")})).min(1).max(25),targetLanguageCode:s.z.string().trim().min(2).max(80).describe('Target language code or name, e.g. "fr". The language must already exist — create it with manage_language first.')});async function En(e,t){const n=xt.parse(e),r=P({action:"TRANSLATE BULK",context:t,payload:{count:n.items.length,language:n.targetLanguageCode},preview:{contentType:"page",summary:`Create ${n.targetLanguageCode} translations of ${N(n.items.length,"item")}: ${n.items.map(a=>a.slug).join(", ")}.`,title:`Bulk translate to ${n.targetLanguageCode}`},subject:`bulk-translate-${n.targetLanguageCode}`});if(r)return r;const o=[],i=[];for(const a of n.items)try{const c=await At({cmsTarget:{contentType:a.contentType,slug:a.slug},targetLanguageCode:n.targetLanguageCode,...a.title?{title:a.title}:{},translations:a.translations},t);o.push({slug:a.slug,...c})}catch(c){i.push({error:c instanceof Error?c.message:String(c),slug:a.slug})}return{failed:i,failedCount:i.length,mutationExecuted:o.length>0,success:i.length===0,targetLanguageCode:n.targetLanguageCode,translated:o,translatedCount:o.length}}const Et=s.z.strictObject({action:s.z.enum(["publish","discard"]).default("publish").describe('"publish" applies the draft to the live page/post; "discard" deletes it and leaves the live content untouched.'),contentType:s.z.enum(["page","post"]).optional(),entityId:s.z.union([s.z.number().int().positive(),s.z.string().trim().min(1).max(120)]).optional(),slug:s.z.string().trim().min(1).max(300).optional(),title:s.z.string().trim().min(1).max(300).optional()}),yo=["title","slug"],bo=["custom_canonical","feature_image_id","meta_description","meta_title"];async function $n(e,t){const n=Et.parse(e),r=x(t),o=await ee({...n.contentType?{contentType:n.contentType}:{},...n.entityId!==void 0?{entityId:n.entityId}:{},...n.slug?{slug:n.slug}:{},...n.title?{title:n.title}:{}},t);if(o.contentType==="product")throw new Error("publish_content_draft supports pages and posts. Product drafts live in product_drafts and are published from the product editor.");const i=o.contentType,a=Fe(o),c=i==="page"?"pages":"posts",{data:u,error:d}=await r.from("content_drafts").select("*").eq("parent_type",i).eq("parent_id",a).maybeSingle();if(d)throw new Error(`Failed to read the draft: ${_(d)}`);if(!u)return{contentType:i,entityId:a,message:`No Live Draft exists for ${i} "${o.title||o.slug}". Nothing to ${n.action}.`,mutationExecuted:!1,success:!1};const l=o.title||o.slug||`${i} ${a}`,m=P({action:n.action==="publish"?"PUBLISH DRAFT":"DISCARD DRAFT",context:t,payload:{action:n.action,contentType:i,entityId:String(a)},preview:{contentType:i,slug:o.slug,summary:n.action==="publish"?`Publish the Live Draft for ${i} "${l}", replacing its live blocks. A revision snapshot is saved first, so this is reversible from Revision History.`:`Discard the Live Draft for ${i} "${l}". The live content is left untouched.`,title:o.title},subject:`${i}-${a}-draft`});if(m)return m;const h=u.meta??{},g=Array.isArray(u.blocks)?u.blocks:[];if(n.action==="discard"){const{error:k}=await r.from("content_drafts").delete().eq("id",u.id);if(k)throw new Error(`Failed to discard the draft: ${_(k)}`);return U(t,o,o.slug),{action:"discard",contentType:i,entityId:a,mutationExecuted:!0,success:!0}}const f=await W(t,i,a),p={};for(const k of yo){const v=h[k];typeof v=="string"&&v.trim()&&(p[k]=v.trim())}for(const k of bo)if(Object.prototype.hasOwnProperty.call(h,k)){const v=h[k];p[k]=typeof v=="string"&&v.trim()?v.trim():null}if(Object.keys(p).length>0){const{error:k}=await r.from(c).update(p).eq("id",a);if(k)throw new Error(`Failed to apply the draft metadata: ${_(k)}`)}const b=i==="page"?"page_id":"post_id",{error:y}=await r.from("blocks").delete().eq(b,a);if(y)throw new Error(`Failed to clear the live blocks: ${_(y)}`);const w=Number(h.language_id)||Number(o.languageId)||Number(g[0]?.language_id)||0;if(g.length>0){const k=g.map((E,O)=>({block_type:E?.block_type,content:E?.content??{},language_id:Number(E?.language_id)||w,order:Number.isFinite(E?.order)?E.order:O,page_id:i==="page"?a:null,post_id:i==="post"?a:null,product_id:null})),{error:v}=await r.from("blocks").insert(k);if(v)throw new Error(`Failed to publish the draft blocks: ${_(v)}`)}await G(t,i,a,f);const{error:I}=await r.from("content_drafts").delete().eq("id",u.id),T=typeof p.slug=="string"?p.slug:o.slug;return U(t,{...o,slug:T},T??void 0),{action:"publish",blockCount:g.length,contentType:i,entityId:a,mutationExecuted:!0,slug:T,success:!0,...I?{warning:`Published, but the draft row was not removed: ${_(I)}`}:{}}}const _o=new Set(["alt_text","author_name","author_title","caption","html_content","label","placeholder","quote","submit_button_text","success_message","text","text_content","title"]);function Je(e,t,n){if(!e)return e;if(Object.prototype.hasOwnProperty.call(t,e))return t[e];const r=e.trim();if(r!==e&&Object.prototype.hasOwnProperty.call(t,r))return e.replace(r,t[r]);let o=e;for(const[i,a]of n)i&&o.includes(i)&&(o=o.split(i).join(a));return o}function Ye(e,t,n,r){if(Array.isArray(e))return e.map(o=>Ye(o,t,n,r));if(e&&typeof e=="object"){const o={};for(const[i,a]of Object.entries(e))typeof a=="string"&&(_o.has(i)||r?.has(i))?o[i]=Je(a,t,n):a&&typeof a=="object"?o[i]=Ye(a,t,n,r):o[i]=a;return o}return e}function wo(e,t){if(typeof e!="string"||R.isValidBlockType(e))return;const n=st(e,t);if(n)return new Set(R.readCustomBlockFields(n).filter(r=>r.type==="text"||r.type==="rich-text").map(r=>r.key))}const $t=s.z.strictObject({cmsTarget:se,targetLanguageCode:s.z.string().trim().min(2).max(80).describe('Target language code or name, e.g. "fr" or "French".'),title:s.z.string().trim().min(1).max(300).optional().describe("Translated page title (defaults to translating the source title)."),translations:s.z.record(s.z.string(),s.z.string()).describe('Map of every visible source string to its translation, e.g. { "Explore Our Products": "Explorez nos produits" }. Include headings, paragraph text, button labels, image alt text, captions, and form labels.')});async function At(e,t){const n=$t.parse(e),r=await ee(n.cmsTarget,t);if(r.contentType==="product")throw new Error("translate_page supports pages and posts only.");const o=x(t),i=Fe(r),a=r.contentType==="page"?"pages":"posts",c=r.contentType==="page"?"page_id":"post_id",{data:u,error:d}=await o.from(a).select("*").eq("id",i).single();if(d||!u)throw new Error(`Could not read the source ${r.contentType} to translate: ${_(d)}`);const{data:l,error:m}=await o.from("blocks").select("id, block_type, content, order").eq(c,i);if(m)throw new Error(`Could not read the source blocks: ${_(m)}`);const h=(Array.isArray(l)?l:[]).slice().sort((C,z)=>Number(C.order)-Number(z.order));if(h.length===0)throw new Error(`The source ${r.contentType} has no content blocks to translate.`);t=await V(t,h);const g=n.translations||{},f=Object.entries(g).filter(([C])=>!!C).sort((C,z)=>z[0].length-C[0].length),p=h.map((C,z)=>({blockType:C.block_type,content:Ye(K(C.content),g,f,wo(C.block_type,t)),order:z})),b=await Be(o,n.targetLanguageCode),y=String(u.title||""),w=n.title||Je(y,g,f)||y||"Untitled",I=C=>typeof C=="string"&&C.trim()?Je(C,g,f):void 0,T=F(w)||u.slug||"translated-page",k={blocks:p,feature_image_id:u.feature_image_id??void 0,languageCode:b.code,meta_description:I(u.meta_description),meta_title:I(u.meta_title),slug:T,status:"published",title:w,translationGroupId:u.translation_group_id||void 0},v=r.contentType==="post"?{...k,excerpt:I(u.excerpt),label:I(u.label),published_at:u.published_at??new Date().toISOString(),subtitle:I(u.subtitle)}:k,E=P({action:"TRANSLATE",context:t,payload:{createInput:v,sourceId:u.id,tool:"translate_page"},preview:{blockCount:p.length,contentType:r.contentType,languageCode:b.code,slug:k.slug,status:k.status,summary:`Publish a ${b.code.toUpperCase()} translation of "${y}" — it goes live immediately, linked to the original ${r.contentType}, at /${k.slug} with ${N(p.length,"translated block")}.`,title:w},subject:`translate ${r.contentType} ${u.id} to ${b.code}`});if(E)return E;const O={...t,skipConfirmation:!0};return{...r.contentType==="post"?await qe(v,O):await Re(v,O),isTranslation:!0,languageCode:b.code}}async function zt(e,t){const n=pe.parse(e),r=n.entityId!==void 0||!!n.slug||!!n.title,o=x(t);let i,a;if(r){const p=await Y({contentType:n.contentType,entityId:n.entityId,slug:n.slug,title:n.title},t),b=p.item;a=b.id,i={contentType:p.contentType,entityId:a,slug:typeof b.slug=="string"?b.slug:"",title:typeof b.title=="string"?b.title:""}}else i=Jn(t),a=M(i);const c=i.title||i.slug||"current item",u=i.contentType==="product",d=P({action:"SET IMAGES",context:t,payload:{contentType:i.contentType,entityId:String(a),images:n.images,tool:"set_content_images"},preview:{contentType:i.contentType,imageCount:n.images.length,slug:i.slug,summary:u?`Set ${N(n.images.length,"image")} on product "${c}" (the first becomes the main product image, the rest the gallery).`:`Set the feature image on the ${i.contentType} "${c}".`,title:i.title},subject:`set images on ${i.contentType} ${String(a)}`});if(d)return d;const l=await Jt(n.images,t,c);if(l.length===0)throw new Error("None of the provided images could be resolved to a media item.");if(u){const{data:p,error:b}=await o.from("products").select("id, slug, language_id, title").eq("id",a).maybeSingle();if(b||!p)throw new Error(`Could not load the product to set images: ${_(b)}`);const y=await Qn({mediaIds:l,productId:a,supabase:o});return await Oe({patch:({meta:w})=>Array.isArray(w.product_media)?{meta:{...w,product_media:y.map((I,T)=>({media_id:I,sort_order:T}))}}:{},productId:a,supabase:o}),U(t,{contentType:"product",entityId:String(a),languageId:p.language_id,slug:p.slug,title:p.title},p.slug),t?.revalidatePath?.("/cms/products"),{contentType:"product",entityId:a,imageCount:y.length,mutationExecuted:!0,slug:p.slug,success:!0}}const m=await W(t,i.contentType,a),h=i.contentType==="page"?"pages":"posts",{data:g,error:f}=await o.from(h).update({feature_image_id:l[0],updated_at:new Date().toISOString()}).eq("id",a).select("id, language_id, slug, status, title").single();if(f||!g)throw new Error(`Failed to set the feature image: ${_(f)}`);return await G(t,i.contentType,a,m),U(t,i,g.slug),{contentType:i.contentType,entityId:a,extraImagesIgnored:l.length-1,imageCount:1,mutationExecuted:!0,slug:g.slug,success:!0}}function ko(e){return{...An.createCortexDatabaseAgentTools(e),...zn.createCortexCustomBlockTools(e),...Pn.createCortexContentOpsTools(e),...Nn.createCortexThemingTools(e),...Un.createCortexSiteTools(e),fetch_ecommerce_stats:S.tool({description:"Fetch quantitative ecommerce statistics and reports from the database. Use this to answer questions about revenue, order counts, order status counts such as pending or trial, and top-selling products over a time range. This tool is read-only and does not require confirmation.",execute:t=>un(t,e),inputSchema:Qe,strict:!0}),read_current_cms_item:S.tool({description:"Read a CMS item: page/post/product metadata plus page/post block summaries or content. Defaults to the item currently open in the CMS editor; with no editor open (MCP clients) pass `cmsTarget` with contentType plus slug, entityId, or title. Read-only.",execute:t=>dn(t,e),inputSchema:Ze,strict:!0}),search_documentation:S.tool({description:"Search the NextBlock documentation database and return concise source snippets for factual CMS guidance.",execute:t=>ln(t,e),inputSchema:Pe,strict:!0}),fetch_url_content:S.tool({description:"Fetch an external web page and return its title, meta description, headings, body text, AND its images: `mainImage` (the page's subject image — schema.org Product image, else og:image, else the best in-body <img>) plus a ranked `images` list, all as absolute URLs. Read-only, no confirmation. Use this first whenever the user references an external URL to copy, adapt, clone, or draw inspiration from. To reuse the source page's image, pass `mainImage` straight into create_cms_product `images` or a page/post `feature_image_id` — it is imported into the media library automatically. Never invent an image URL: if `mainImage` is null, the page had none.",execute:t=>vn(t),inputSchema:Tt,strict:!0}),search_stock_photos:S.tool({description:"Find relevant, free, high-quality stock photos (Unsplash/Pexels) for page imagery. Returns a list of photos each with a direct image `url`, `width`, `height`, `alt`, and `photographer`. Read-only, zero cost. Use the returned `url` directly as an image block's external_url (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:t=>Cn(t,e),inputSchema:vt,strict:!0}),manage_product_variants:S.tool({description:'Give a product sellable variations — size, flavour, colour, format — each with its own SKU, price, stock, and optional image. Define the option axes in `attributes` (name plus every term) and one entry in `variants` per purchasable combination, naming its term per attribute in `options`. Attributes and terms are global and reused across products, so an existing "Size" is matched rather than duplicated. Prices are in major units (25 = $25.00). The product\'s stock becomes the sum of its variants. Use mode "replace" to rebuild the variant set, "append" to add to it. Mutating: first returns a confirmation phrase; only executes after exact confirmation.',execute:t=>xn(t,e),inputSchema:St,strict:!0}),translate_content_bulk:S.tool({description:"Translate SEVERAL pages or posts into one language in a single call. Use this instead of repeating translate_page when making a site multilingual: pass the target language once and one entry per item, each with its own source-string -> translation map. Layout, blocks, and imagery are copied automatically and each copy is linked to its original as a translation. The language must exist first (manage_language). Items are processed independently, so one bad entry does not abandon the rest — check `failed` in the result. Mutating: first returns a confirmation phrase; only executes after exact confirmation.",execute:t=>En(t,e),inputSchema:xt,strict:!0}),publish_content_draft:S.tool({description:"Publish (or discard) the Live Draft staged on a page or post by generate_jsonb_layout / rewrite_page_draft. Publishing applies the draft blocks and metadata to the live record and snapshots a revision first, so it is reversible from Revision History; visibility (status/published_at) is never changed. Use this to finish a build that staged a draft — without it the new layout stays invisible on the public site. Target the record with contentType plus slug, entityId, or title. Mutating: first returns a confirmation phrase; only executes after exact confirmation.",execute:t=>$n(t,e),inputSchema:Et,strict:!0}),rewrite_page_draft:S.tool({description:'Replace ALL blocks of an existing page or post with a brand-new set of blocks, staged as a Live Draft (content_drafts) that the user previews before publishing. Use this for whole-page redesigns/rewrites such as "rewrite my home page with 5 sections". Provide the complete new list of top-level blocks in `blocks` (usually section blocks for a landing/home page, each with nested heading/text/button blocks). Nothing goes live until the user publishes the draft, and publishing auto-creates a revision snapshot so the change is reversible. Mutating: first returns a confirmation phrase; only stages the draft after the user replies with the exact phrase.',execute:t=>Sn(t,e),inputSchema:Ct,strict:!0}),translate_page:S.tool({description:'Translate the CURRENT page or post into another language. This copies the source page\'s entire structure, layout, and images automatically and links the new page to the original as a translation — you ONLY supply the text translations. Provide targetLanguageCode (e.g. "fr") and a `translations` map of every visible source string to its translation (headings, paragraph text, button labels, image alt text, captions, form labels). Do NOT rebuild the layout or call search_stock_photos for a translation. Targets the open page/post by default; with no editor open (MCP clients) pass `cmsTarget` with contentType plus slug, entityId, or title. Mutating: first returns a confirmation phrase; only creates the translation after exact confirmation.',execute:t=>At(t,e),inputSchema:$t,strict:!0}),set_content_images:S.tool({description:"Set the feature image for a page or post, or the image gallery for a product. Pass `images`: a list of image URLs (e.g. `mainImage` from fetch_url_content or `url` values from search_stock_photos) and/or existing media library IDs. External URLs are imported into the media library automatically — NEVER put an image URL directly into feature_image_id. The FIRST image becomes the feature image (pages/posts) or the main product image (products); for a product the remaining images become its gallery in order (this REPLACES the product's current images). On a PAGE the feature image renders as a full-width title banner above the blocks, so never set one on the home page or on a page that opens with its own hero section — use update_site_identity `social_image` for that page's share preview instead; posts should always have one. Targets the currently open page/post/product by default; to target any other item (for example a product you just created from the dashboard) pass contentType plus slug, entityId, or title — no open editor needed. Mutating: first returns a confirmation phrase; only applies after exact confirmation.",execute:t=>zt(t,e),inputSchema:pe,strict:!0}),create_cms_page:S.tool({description:"Create a new CMS page with metadata and optional validated page blocks. Mutating: first returns a confirmation phrase; only executes after the user replies with the exact phrase. For translations, pass translationGroupId from the source page/post/product context so the new language is linked to the same backend translation group. For contact pages, provide a form block with fields; the destination address is configured once in CMS -> Messages and is never stored on the block.",execute:t=>Re(t,e),inputSchema:ge,strict:!0}),create_cms_post:S.tool({description:"Create a new CMS post with metadata and optional validated post blocks. Mutating: first returns a confirmation phrase; only executes after the user replies with the exact phrase. For translations, pass translationGroupId from the source post context so the new language is linked to the same backend translation group.",execute:t=>qe(t,e),inputSchema:fe,strict:!0}),create_cms_product:S.tool({description:"Create a new draft-capable product, complete with its images and its body copy in ONE call. Pass `images` to set the main product image and gallery (external https URLs are imported into the media library automatically — use `mainImage` from fetch_url_content to reuse a source page's photo). Pass `blocks` to build the product's \"Product Description Blocks\" — the SAME block vocabulary and section-based design rules as create_cms_page, rendered on the public product page. This is the richest product body and is what you should produce whenever the user asks to copy or write real product content. Also pass `short_description` for the one-line summary shown on product cards. `description_html` is a plain-HTML fallback body used only when no blocks are supplied. Defaults missing fields safely: physical Stripe product, generated SKU, price 0, stock 0, taxable, draft. `price` is in major units (25 = $25.00). For translations, pass translationGroupId from the source product context. Mutating: first returns a confirmation phrase; only executes after exact confirmation.",execute:t=>_t(t,e),inputSchema:he,strict:!0}),delete_cms_item:S.tool({description:"Delete a resolved page, post, or product after exact confirmation. Pages/posts delete all translations in the translation group and related navigation links. Mutating: refuses unless the latest user message includes the exact confirmation phrase.",execute:t=>It(t,e),inputSchema:be,strict:!0}),prepare_delete_cms_item:S.tool({description:"Inspect the page, post, or product that would be deleted and return the exact confirmation phrase. This tool does not mutate data.",execute:t=>bn(t,e),inputSchema:tt,strict:!0}),update_footer:S.tool({description:"Replace the public footer links and/or footer copyright settings for a locale. Use links for footer navigation and copyright for locale text templates. Mutating: first returns a confirmation phrase; only executes after exact confirmation.",execute:t=>gt(t,e),inputSchema:ae,strict:!0}),update_content_block:S.tool({description:'Update the JSON content of an existing top-level page/post block. The block must belong to the item being edited — the open CMS editor, or the item named by `cmsTarget` (contentType plus slug, entityId, or title) when no editor is open, as with MCP clients. Content is merged with the existing block before validation. For section blocks, add nested blocks with content.append_block or content.append_blocks using objects like { block_type: "button", content: { text: "Contact Us", url: "/contact" } }; existing column_blocks and layout fields are preserved. Mutating: first returns a confirmation phrase; only executes after exact confirmation.',execute:t=>ht(t,e),inputSchema:le,strict:!0}),insert_content_block:S.tool({description:'Insert a new validated top-level page/post block before or after an existing block, or at the start/end. Use this for visible content additions like adding a rich text title and paragraph above a form. For "above the form", use position "before" with anchorBlockType "form" and blockType "text" containing html_content. Mutating: first returns a confirmation phrase; only executes after exact confirmation.',execute:t=>yt(t,e),inputSchema:me,strict:!0}),update_current_cms_fields:S.tool({description:"Update validated metadata fields on the current page, post, or product. For products, description_json must be a valid NextBlock editor document JSON object. Mutating: first returns a confirmation phrase; only executes after exact confirmation.",execute:t=>ft(t,e),inputSchema:ce,strict:!0}),update_cms_item_field:S.tool({description:"Update one field on a page, post, or product, resolving by current edit context, id, slug, or exact title. Use this for requests like changing price, stock, title, slug, status, sale_price, or meta fields. Interpret public as published for pages/posts and active for products. Scheduled sale date ranges are not supported and will be refused without mutation. Mutating: first returns a confirmation phrase; only executes after exact confirmation.",execute:t=>kt(t,e),inputSchema:ye,strict:!0}),update_navigation_bar:S.tool({description:'Update the public header navigation bar for a locale. Use mode "append" when adding links while preserving existing navigation. Use mode "update" when renaming or changing an existing single link. Use mode "replace" only when the user asks to rebuild the complete header and you provide the full menu; destructive partial replacements are refused. Mutating: first returns a confirmation phrase; only executes after exact confirmation.',execute:t=>mt(t,e),inputSchema:ie,strict:!0}),update_section_column_block:S.tool({description:"Update the content of one existing nested block inside a section block. The parent section must belong to the item being edited — the open CMS editor, or the item named by `cmsTarget` (contentType plus slug, entityId, or title) when no editor is open, as with MCP clients. This tool must not change the nested block type. To add a new nested block, update the parent section with update_content_block and preserve existing column_blocks. Mutating: first returns a confirmation phrase; only executes after exact confirmation.",execute:t=>bt(t,e),inputSchema:ue,strict:!0}),execute_cms_action_plan:S.tool({description:"Execute multiple CMS mutations as one confirmed plan. Use this whenever the user asks for more than one change in the same prompt, such as creating a page and adding a navigation link. First returns one combined confirmation preview and Confirm button; after confirmation, runs each action in order and stops on the first failure.",execute:t=>_n(t,e),inputSchema:nt,strict:!0})}}exports.buildVisibleContactIntroActionPlan=Hn;exports.cortexAiPageContextSchema=Ne;exports.createCmsPageInputSchema=ge;exports.createCmsPostInputSchema=fe;exports.createCmsProductInputSchema=he;exports.createCortexGlobalAgentTools=ko;exports.deleteCmsItemInputSchema=be;exports.executeCmsActionPlan=_n;exports.executeCmsActionPlanInputSchema=nt;exports.executeCreateCmsPage=Re;exports.executeCreateCmsPost=qe;exports.executeCreateCmsProduct=_t;exports.executeDeleteCmsItem=It;exports.executeFetchEcommerceStats=un;exports.executeFetchUrlContent=vn;exports.executeInsertContentBlock=yt;exports.executeManageProductVariants=xn;exports.executePrepareDeleteCmsItem=bn;exports.executePublishContentDraft=$n;exports.executeReadCurrentCmsItem=dn;exports.executeRewritePageDraft=Sn;exports.executeSearchDocumentation=cn;exports.executeSearchDocumentationWithTimeout=ln;exports.executeSearchStockPhotos=Cn;exports.executeSetContentImages=zt;exports.executeTranslateContentBulk=En;exports.executeTranslatePage=At;exports.executeUpdateCmsItemField=kt;exports.executeUpdateContentBlock=ht;exports.executeUpdateCurrentCmsFields=ft;exports.executeUpdateFooter=gt;exports.executeUpdateNavigationBar=mt;exports.executeUpdateSectionColumnBlock=bt;exports.fetchEcommerceStatsInputSchema=Qe;exports.fetchUrlContentInputSchema=Tt;exports.insertContentBlockInputSchema=me;exports.isBlockedFetchHost=Ae;exports.manageProductVariantsInputSchema=St;exports.maybeTriggerStockPhotoDownloads=we;exports.navigationItemInputSchema=Xe;exports.prepareDeleteCmsItemInputSchema=tt;exports.publishContentDraftInputSchema=Et;exports.readCurrentCmsItemInputSchema=Ze;exports.resolveCortexAiStockPhotoProvider=lo;exports.resolveCortexAiStockPhotoProviders=De;exports.rewritePageDraftInputSchema=Ct;exports.searchDocumentationInputSchema=Pe;exports.searchStockPhotosInputSchema=vt;exports.setContentImagesInputSchema=pe;exports.translateContentBulkInputSchema=xt;exports.translatePageInputSchema=$t;exports.updateCmsItemFieldInputSchema=ye;exports.updateContentBlockInputSchema=le;exports.updateCurrentCmsFieldsInputSchema=ce;exports.updateFooterInputSchema=ae;exports.updateNavigationBarInputSchema=ie;exports.updateSectionColumnBlockInputSchema=ue;
|
package/lib/ai-key-crypto.cjs.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const o=require("crypto"),n="aes-256-gcm",u=1;function c(t){const e=t.trim();if(!e)throw new Error("CORTEX_AI_ENCRYPTION_KEY is required to manage stored OpenRouter keys.");return o.createHash("sha256").update(e).digest()}function p(t){if(!t||typeof t!="object")throw new Error("Invalid encrypted OpenRouter key payload.");const e=t;if(e.algorithm!==n||e.version!==u||typeof e.authTag!="string"||typeof e.ciphertext!="string"||typeof e.iv!="string")throw new Error("Invalid encrypted OpenRouter key payload.");return{algorithm:e.algorithm,authTag:e.authTag,ciphertext:e.ciphertext,iv:e.iv,last4:typeof e.last4=="string"?e.last4:"",updatedAt:typeof e.updatedAt=="string"?e.updatedAt:"",version:e.version}}function s(t){const e=(t||"").trim();return e?`**** ${e}`:"Stored key"}function l(t){const e=t.apiKey.trim();if(!e)throw new Error("OpenRouter API key is required.");const a=c(t.encryptionSecret),r=o.randomBytes(12),i=o.createCipheriv(n,a,r),y=Buffer.concat([i.update(e,"utf8"),i.final()]),d=i.getAuthTag();return{algorithm:n,authTag:d.toString("base64"),ciphertext:y.toString("base64"),iv:r.toString("base64"),last4:e.slice(-4),updatedAt:(t.now||new Date).toISOString(),version:u}}function f(t){const e=p(t.encryptedKey),a=c(t.encryptionSecret);try{const r=o.createDecipheriv(n,a,Buffer.from(e.iv,"base64"));return r.setAuthTag(Buffer.from(e.authTag,"base64")),Buffer.concat([r.update(Buffer.from(e.ciphertext,"base64")),r.final()]).toString("utf8")}catch{throw new Error("Failed to decrypt stored OpenRouter key.")}}function h(t){try{const e=p(t);return{hasStoredKey:!0,last4:e.last4||null,maskedKey:s(e.last4),updatedAt:e.updatedAt||null}}catch{return{hasStoredKey:!1,last4:null,maskedKey:null,updatedAt:null}}}exports.CORTEX_AI_KEY_ALGORITHM=n;exports.CORTEX_AI_KEY_ENVELOPE_VERSION=u;exports.decryptOpenRouterApiKey=f;exports.encryptOpenRouterApiKey=l;exports.getMaskedOpenRouterKey=s;exports.getOpenRouterKeyEnvelopeStatus=h;
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const f=1e4,h="https://openrouter.ai/api/v1/auth/key",y="https://api.pexels.com/v1/curated?per_page=1",p="https://api.unsplash.com/photos?per_page=1";async function c(t,s,e){const n=new AbortController,u=setTimeout(()=>n.abort(),f);try{const r=await t(s,{cache:"no-store",headers:{Accept:"application/json",...e},signal:n.signal});return{body:await r.json().catch(()=>null),status:r.status}}catch(r){return{failed:r instanceof Error&&r.name==="AbortError"?"The provider did not answer within 10 seconds.":r instanceof Error?r.message:"The provider could not be reached."}}finally{clearTimeout(u)}}function a(t,s){return{message:`${t} could not be reached to check the key (${s}). Check the connection and try again.`,ok:!1,reason:"unreachable"}}function i(t){return{message:t,ok:!1,reason:"invalid"}}async function d(t){const s=t.apiKey.trim();if(!s)return i("Enter an OpenRouter API key.");if(!s.startsWith("sk-or-"))return i('That does not look like an OpenRouter key: they start with "sk-or-".');const e=await c(t.fetch||globalThis.fetch,h,{Authorization:`Bearer ${s}`});if("failed"in e)return a("OpenRouter",e.failed);if(e.status===401||e.status===403)return i("OpenRouter rejected this key. Copy it again from openrouter.ai/keys.");if(e.status<200||e.status>=300)return a("OpenRouter",`HTTP ${e.status}`);const n=e.body&&typeof e.body=="object"&&"data"in e.body?e.body.data:void 0,u=typeof n?.label=="string"?n.label.trim():"",r=n?.is_free_tier===!0,l=typeof n?.limit_remaining=="number"?n.limit_remaining:null,o=[];return u&&o.push(`key "${u}"`),r?o.push("free tier: only free models until you add credits"):l!==null&&o.push(`$${l.toFixed(2)} of credit left`),{detail:o.length>0?o.join(" · "):null,isFreeTier:n?r:null,ok:!0}}async function k(t){const s=t.apiKey.trim();if(!s)return i("Enter a Pexels API key.");const e=await c(t.fetch||globalThis.fetch,y,{Authorization:s});return"failed"in e?a("Pexels",e.failed):e.status===401||e.status===403?i("Pexels rejected this key. Copy it again from pexels.com/api."):e.status===429?{detail:"Pexels accepted the key (its hourly quota is currently exhausted).",isFreeTier:null,ok:!0}:e.status<200||e.status>=300?a("Pexels",`HTTP ${e.status}`):{detail:null,isFreeTier:null,ok:!0}}async function T(t){const s=t.accessKey.trim();if(!s)return i("Enter an Unsplash access key.");const e=await c(t.fetch||globalThis.fetch,p,{Authorization:`Client-ID ${s}`});return"failed"in e?a("Unsplash",e.failed):e.status===401?i("Unsplash rejected this key. Use the Access Key (not the Secret Key) from unsplash.com/developers."):e.status===403||e.status===429?{detail:"Unsplash accepted the key (its demo quota is currently exhausted).",isFreeTier:null,ok:!0}:e.status<200||e.status>=300?a("Unsplash",`HTTP ${e.status}`):{detail:null,isFreeTier:null,ok:!0}}exports.verifyOpenRouterApiKey=d;exports.verifyPexelsApiKey=k;exports.verifyUnsplashAccessKey=T;
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const o=require("./ai-model-registry.cjs.js"),r="Cortex AI OpenRouter model catalog can only be imported from server-side code.";function n(){if(!(typeof window>"u"))throw new Error(r)}function s(){const e=new URL(`${o.CORTEX_AI_OPENROUTER_BASE_URL}/models`);return e.searchParams.set("supported_parameters",o.CORTEX_AI_REQUIRED_MODEL_PARAMETERS.join(",")),e.searchParams.set("output_modalities","text"),e.toString()}async function i(e){n();const t=await(e?.fetch||globalThis.fetch)(s(),{cache:"no-store",headers:{Accept:"application/json"}});if(!t.ok)throw new Error(`Failed to load OpenRouter models: ${t.status} ${t.statusText}`);return o.filterCortexAiCompatibleOpenRouterModels(await t.json(),e?.now)}exports.listCortexAiCompatibleOpenRouterModels=i;
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const D=require("ai"),N="https://openrouter.ai/api/v1",b="openrouter/free",u=["nvidia/nemotron-3-super-120b-a12b:free","nvidia/nemotron-3-ultra-550b-a55b:free","thinkingmachines/inkling:free","nex-agi/nex-n2.5-pro:free","poolside/laguna-s-2.1:free","thinkingmachines/inkling-small:free","inclusionai/ling-3.0-flash-vl:free"],x=["tools","structured_outputs"],k={frequencyPenalty:"frequency_penalty",logitBias:"logit_bias",presencePenalty:"presence_penalty",seed:"seed",stopSequences:"stop",temperature:"temperature",topK:"top_k",topP:"top_p"},F={defaultFreeRouter:b,defaultStructuredOutputModel:u[0],defaultToolCallingModel:u[0],freeFallbacks:u,structuredJsonPreferred:u,toolCallingPreferred:u};class R extends Error{attempts;constructor(t,r,n){super(t),this.name="CortexAiRoutingError",this.attempts=r,this.cause=n}}function m(e){return Array.from(new Set(e.filter(Boolean)))}function c(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function d(e){return typeof e=="string"&&e.trim()?e.trim():null}function A(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.trim().length>0):[]}function f(e){const t=typeof e=="number"?e:Number(e);return Number.isFinite(t)?t:null}function C(e){const t=c(e);return t?Object.fromEntries(Object.entries(t).filter(([,r])=>r!=null).map(([r,n])=>[r,String(n)])):{}}function I(e){const t=new Set(e);return x.every(r=>t.has(r))}function w(e){const t=c(e.architecture);return A(t?.output_modalities).includes("text")}function U(e){if(e==null)return null;if(typeof e=="number")return e>1e10?e:e*1e3;if(typeof e=="string"&&e.trim()){const t=Date.parse(e);return Number.isFinite(t)?t:null}return null}function B(e,t){const r=U(e);return r!==null&&r<=t.getTime()}function q(e){const t=c(e.top_provider);return f(e.context_length)??f(e.contextLength)??f(t?.context_length)??null}function X(e){const t=e.expiration_date??e.expirationDate;return typeof t=="string"&&t.trim()?t.trim():null}function y(e){return!!(e&&u.includes(e))}function j(e){const t=c(e);if(!t)return null;const r=d(t.modelId),n=d(t.name),i=A(t.supportedParameters),s=d(t.updatedAt);return!r||!n||!s||!I(i)?null:{contextLength:f(t.contextLength),modelId:r,name:n,pricing:C(t.pricing),supportedParameters:i,updatedAt:s}}function G(e,t=new Date){return{contextLength:e.contextLength,modelId:e.id,name:e.name,pricing:e.pricing,supportedParameters:[...e.supportedParameters],updatedAt:t.toISOString()}}function K(e,t=new Date){const r=c(e),n=Array.isArray(e)?e:Array.isArray(r?.data)?r.data:[],i=[];for(const s of n){const o=c(s),l=d(o?.id),a=d(o?.name),M=A(o?.supported_parameters);!o||!l||!a||!w(o)||B(o.expiration_date,t)||!I(M)||i.push({contextLength:q(o),created:f(o.created),expirationDate:X(o),id:l,name:a,pricing:C(o.pricing),supportedParameters:M})}return i.sort((s,o)=>s.name.localeCompare(o.name))}function Y(e){return m([e?.modelId||u[0],...e?.fallbackModelIds||u])}function $(e){const t=e.requestedModelId?.trim()||null;if(e.credentialSource==="env")return{credentialSource:e.credentialSource,ignoredRequestedModelId:t&&!y(t)?t:null,modelIds:[...u],modelSelection:null};const r=m(e.fallbackModelIds?.length?e.fallbackModelIds:u),n=e.credentialSource==="stored"?e.selectedModel?.modelId||r[0]:t||e.selectedModel?.modelId||r[0];return{credentialSource:e.credentialSource,ignoredRequestedModelId:e.credentialSource==="stored"&&t&&t!==n?t:null,modelIds:m([n,...r]),modelSelection:e.selectedModel||null}}function z(e,t){const r=t.modelSelection;if(!r||r.modelId!==t.modelId)return e;const n=new Set(r.supportedParameters),i=Object.entries(k).filter(([o,l])=>o in e&&!n.has(l)).map(([o])=>o);if(i.length===0)return e;const s={...e};for(const o of i)delete s[o];return s}function p(e,t){if(!e||typeof e!="object"||!(t in e))return null;const r=e[t],n=typeof r=="number"?r:Number(r);return Number.isFinite(n)?n:null}function _(e){if(D.APICallError.isInstance(e))return e.statusCode??null;const t=p(e,"statusCode")??p(e,"status");if(t)return t;if(e&&typeof e=="object"&&"response"in e){const r=e.response,n=p(r,"status");if(n)return n}return e&&typeof e=="object"&&"cause"in e?_(e.cause):null}function h(e){return e!==null&&Number.isInteger(e)&&e>=100&&e<=599}function S(e){if(typeof e!="string"||!e.trim().startsWith("{"))return null;try{return c(JSON.parse(e))}catch{return null}}function T(e,t=0){const r=c(e);if(!r||t>8)return null;const n=[r,c(r.data),S(r.responseBody),S(r.text)];for(const i of n){const s=c(i?.error),o=p(s,"code")??p(s,"status");if(h(o))return o}return T(r.cause,t+1)}function O(e){const t=_(e);return h(t)?t:T(e)}function P(e){return O(e)===429}const H=["message","error","text","responseBody","data","cause"];function E(e,t=0){if(!e||t>8)return"";if(typeof e!="object")return String(e);const r=e,n=e instanceof Error?[e.message]:[];for(const i of H)i==="message"&&e instanceof Error||n.push(E(r[i],t+1));return Array.from(new Set(n.filter(Boolean))).join(`
|
|
2
|
-
`)}const J=/No endpoints found|no longer available|not available as a free model|transitioned to a paid model|unavailable for free|paid version is available|is not a valid model ID/i,W=/not found|does not exist|unknown model|no such model/i;function L(e){const t=O(e);if(t===429||t===404)return!0;const r=E(e);return J.test(r)?!0:t===400&&W.test(r)}function g(e,t=900){const r=e.replace(/\s+/g," ").trim();return r.length>t?`${r.slice(0,t-1).trimEnd()}...`:r}function Q(e){const t=E(e);return t?g(t):"Unknown OpenRouter error."}function V(e,t="Cortex AI request failed."){if(e instanceof R){const r=e.attempts.map(o=>o.errorMessage).filter(o=>!!o?.trim()),n=r[0],i=r[r.length-1],s=g(E(e.cause));return n&&i&&n!==i?`First model error: ${n} Last model error: ${i}`:i||n||s||e.message}return g(E(e))||t}async function Z(e){const t=m(e.modelIds),r=e.shouldRetry||L;let n=[],i=null;for(const s of t)try{const o=await e.execute(s);return n=[...n,{modelId:s,rateLimited:!1,status:"success"}],{attempts:n,modelId:s,result:o}}catch(o){const l=P(o),a=r(o);if(i=o,n=[...n,{errorMessage:Q(o),modelId:s,rateLimited:l,status:l?"rate_limited":a?"retried":"failed"}],!a)throw new R(`OpenRouter request failed for model "${s}".`,n,o)}throw new R("OpenRouter fallback exhausted all configured Cortex AI models.",n,i)}exports.CORTEX_AI_FREE_MODEL_FALLBACK_REGISTRY=u;exports.CORTEX_AI_MODEL_REGISTRY=F;exports.CORTEX_AI_OPENROUTER_BASE_URL=N;exports.CORTEX_AI_OPENROUTER_FREE_ROUTER_MODEL=b;exports.CORTEX_AI_REQUIRED_MODEL_PARAMETERS=x;exports.CortexAiRoutingError=R;exports.buildCortexAiModelFallbackChain=Y;exports.buildCortexAiRoutingPolicy=$;exports.createCortexAiStoredModelSelection=G;exports.filterCortexAiCompatibleOpenRouterModels=K;exports.getHttpStatusCode=_;exports.getOpenRouterErrorStatus=O;exports.isCortexAiFreeModelId=y;exports.isOpenRouterRateLimitError=P;exports.isOpenRouterRecoverableRoutingError=L;exports.omitUnsupportedCortexAiModelOptions=z;exports.runWithCortexAiModelFallback=Z;exports.safeParseCortexAiModelSelection=j;exports.summarizeCortexAiRoutingError=V;
|
|
@@ -1,4 +0,0 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const E=require("ai"),d=require("./ai-model-registry.cjs.js");require("./zod-config.cjs.js");const u=require("zod"),y="Cortex AI SEO metadata generation can only be imported from server-side code.";function O(){if(!(typeof window>"u"))throw new Error(y)}const g=u.z.strictObject({metaDescription:u.z.string().trim().min(1),metaTitle:u.z.string().trim().min(1),ogDescription:u.z.string().trim().min(1),ogTitle:u.z.string().trim().min(1)}),l={metaDescription:160,metaTitle:60,ogDescription:200,ogTitle:88},T=6e3,A=6e4,b=/[\s.,;:!?‐-―\-/\\|&+*_"'([{·•]+$/;function c(e,t){const n=e.trim();if(t<=0)return"";if(n.length<=t)return n;const o=n.slice(0,t),i=o.search(/\s\S*$/);return(i>0?o.slice(0,i):o).replace(b,"").trim()}function f(e){const t=e.replace(/```[a-zA-Z0-9]*/g,""),n=t.indexOf("{");if(n===-1)return null;let o=0,i=!1,r=!1;for(let s=n;s<t.length;s++){const a=t[s];if(i){r?r=!1:a==="\\"?r=!0:a==='"'&&(i=!1);continue}if(a==='"'){i=!0;continue}if(a==="{"){o++;continue}if(a==="}"&&(o--,o===0))return t.slice(n,s+1)}return null}function _(){const e=l;return["You are NextBlock Cortex AI, an SEO metadata writer for a content management system.","Return ONLY a single JSON object. No markdown fences, no commentary, no explanation, no trailing prose.",'The object must have exactly these four keys, all strings, all non-empty: "metaDescription", "metaTitle", "ogDescription", "ogTitle".',"Do not add any other key.",`metaTitle must be at most ${e.metaTitle} characters and read as a search-result headline for this specific page.`,`metaDescription must be at most ${e.metaDescription} characters, summarise what the page actually delivers, and end as a complete thought.`,`ogTitle must be at most ${e.ogTitle} characters and may be slightly more conversational than metaTitle, because it is read on a social card rather than in a results list.`,`ogDescription must be at most ${e.ogDescription} characters and should invite a click without over-promising.`,"Write plain text. No emoji, no surrounding quotation marks, no HTML, no markdown.","Describe only what the supplied content actually contains. Never invent statistics, prices, dates, awards, or claims that are not in the content.","Never keyword-stuff, never repeat the focus keyword more than twice across all four fields, and never pad a field to reach its character budget."].join(" ")}function w(e){return["Write SEO metadata for the following page.",e.title?`Page title: ${e.title}`:null,e.siteTitle?`Site name: ${e.siteTitle}. Do not append the site name to metaTitle; the site appends it separately.`:null,e.focusKeyword?`Focus keyword: ${e.focusKeyword}. Use it naturally in metaTitle and metaDescription, at most once each.`:null,e.locale?`Write every field in this locale: ${e.locale}. Match its conventions for capitalisation and punctuation.`:null,`Page content:
|
|
2
|
-
${e.content}`].filter(Boolean).join(`
|
|
3
|
-
|
|
4
|
-
`)}function D(e){const t=f(e);if(!t)throw new Error("Cortex AI returned no JSON object for the SEO metadata request.");let n;try{n=JSON.parse(t)}catch(i){throw new Error(`Cortex AI returned invalid JSON for the SEO metadata request: ${i instanceof Error?i.message:String(i)}`)}const o=g.parse(n);return{metaDescription:c(o.metaDescription,l.metaDescription),metaTitle:c(o.metaTitle,l.metaTitle),ogDescription:c(o.ogDescription,l.ogDescription),ogTitle:c(o.ogTitle,l.ogTitle)}}function v(e){const t=d.getHttpStatusCode(e);if(t===401||t===402||t===403)return!1;if(d.isOpenRouterRecoverableRoutingError(e)||t&&t>=500)return!0;const n=e instanceof Error?e.message:String(e);return/NoContentGenerated|No content generated|Provider returned error|no JSON object|invalid JSON|invalid_type|too_small|unrecognized_keys|Invalid input|aborted|abort|timeout|timed out/i.test(n)}async function x(e){O();const t=c(e.content,T);if(!t)throw new Error("Cortex AI SEO metadata generation requires non-empty page content.");const{createCortexAiOpenRouterClient:n}=await Promise.resolve().then(()=>require("./ai-client.cjs.js")),o=await n({apiKey:e.apiKey||void 0}),i=d.buildCortexAiRoutingPolicy({credentialSource:o.credentialSource,requestedModelId:e.modelId,selectedModel:o.modelSelection}),r=await d.runWithCortexAiModelFallback({modelIds:i.modelIds,shouldRetry:v,execute:async s=>{const a=new AbortController,p=setTimeout(()=>a.abort(),A),m=()=>a.abort();e.abortSignal?.addEventListener("abort",m,{once:!0}),e.abortSignal?.aborted&&a.abort();try{const S=d.omitUnsupportedCortexAiModelOptions({abortSignal:a.signal,maxOutputTokens:700,maxRetries:0,prompt:w({content:t,focusKeyword:e.focusKeyword?.trim()||null,locale:e.locale?.trim()||null,siteTitle:e.siteTitle?.trim()||null,title:e.title?.trim()||null}),system:_(),temperature:.3},{modelId:s,modelSelection:i.modelSelection}),h=await E.generateText({...S,model:o.model(s)});return D(h.text)}finally{clearTimeout(p),e.abortSignal?.removeEventListener("abort",m)}}});return{attempts:r.attempts.length,credentialSource:o.credentialSource,metaDescription:r.result.metaDescription,metaTitle:r.result.metaTitle,modelId:r.modelId,ogDescription:r.result.ogDescription,ogTitle:r.result.ogTitle}}exports.CORTEX_AI_SEO_METADATA_CONTENT_BUDGET=T;exports.CORTEX_AI_SEO_METADATA_LENGTH_BUDGETS=l;exports.cortexAiSeoMetadataOutputSchema=g;exports.extractJsonObject=f;exports.generateCortexAiSeoMetadata=x;exports.truncateOnWordBoundary=c;
|
package/lib/ai-vision.cjs.js
DELETED
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const C=require("ai"),l=require("./ai-model-registry.cjs.js"),R=require("./ai-seo-metadata.cjs.js"),S="Cortex AI vision generation can only be imported from server-side code.";function L(){if(!(typeof window>"u"))throw new Error(S)}const d=["google/gemma-4-31b-it:free","google/gemma-4-26b-a4b-it:free","google/gemini-2.5-flash-lite","qwen/qwen3-vl-32b-instruct","openai/gpt-4o-mini","google/gemini-2.5-flash"],O=[/(?:^|\/)[^/]*-vl(?:[-:]|$)/i,/vision/i,/(?:^|\/)gemini-/i,/(?:^|\/)gemma-[3-9]/i,/(?:^|\/)gpt-(?:4o|4\.1|5)/i,/(?:^|\/)claude-/i,/(?:^|\/)llama-4/i,/(?:^|\/)pixtral/i,/(?:^|\/)mistral-(?:small|medium|large)-3/i,/(?:^|\/)nova-(?:lite|pro|premier)/i],u=125,p={max:1e3,min:20},M=6e4,T=new Set(['"',"'","«","»","‘","’","‚","“","”","„","`"]),v=/^(?:here(?:'s|’s| is)\s+)?(?:the\s+)?alt(?:[-\s]?text)?\s*[:–—-]\s*/i,N=/^(?:this\s+is\s+)?(?:an?|the)?\s*(?:image|photo|photograph|picture|pic|graphic|illustration|rendering|render)\s+(?:of|showing|depicting|that\s+shows)\s+/i;function X(e){const o=new Set,t=[];for(const n of e){const r=n?.trim();!r||o.has(r)||(o.add(r),t.push(r))}return t}function A(e){const o=e?.trim();return o?d.includes(o)?!0:O.some(t=>t.test(o)):!1}function _(e){const o=e.requestedModelId?.trim()||null,t=e.selectedModel?.modelId?.trim()||null,n=e.credentialSource!=="env"&&t&&A(t)?t:null;return{modelIds:X([o,n,...d])}}function f(e){let o=e.trim();for(;o.length>=2&&T.has(o[0])&&T.has(o[o.length-1]);)o=o.slice(1,-1).trim();return o}function U(e){return!e.endsWith(".")||e.endsWith("...")||e.endsWith("…")?e:(e.match(/[.!?](?=\s|$)/g)||[]).length===1?e.slice(0,-1).trimEnd():e}function b(e,o=u){let t=e.replace(/\s+/g," ").trim(),n=!1;for(let r=0;r<2;r++){t=f(t);const a=t.replace(v,"");a!==t&&(t=a.trim(),n=!0),t=f(t);const i=t.replace(N,"");i!==t&&(t=i.trim(),n=!0)}return n&&t&&(t=t.charAt(0).toUpperCase()+t.slice(1)),R.truncateOnWordBoundary(U(t),o)}function q(e){const o=e.trim();if(!o)throw new Error("Cortex AI alt text generation requires an image URL.");let t;try{t=new URL(o)}catch{throw new Error(`Cortex AI alt text generation requires an absolute http(s) image URL, received "${o}". A storage key or site-relative path must be resolved to a publicly fetchable URL first, because the model provider downloads the image server-side.`)}if(t.protocol!=="http:"&&t.protocol!=="https:")throw new Error(`Cortex AI alt text generation requires an http(s) image URL, received the "${t.protocol}" scheme.`);return t}function P(e){return["You are NextBlock Cortex AI, writing the alt attribute for an image on a website.","You are writing for a person using a screen reader who cannot see the image at all.","Describe only what is visibly present in the image: subjects, their appearance, what they are doing, the setting, and any text that appears in the image.","Never state or guess anything you cannot see — no names, no locations, no dates, no brands, no emotions, and no backstory unless they are legible in the image itself.",`Write one short factual description of at most ${e} characters.`,'Do not begin with "image of", "photo of", "picture of", "graphic of", or any similar phrase; the screen reader already announces that this is an image.','Do not add a label such as "Alt text:" and do not wrap the description in quotation marks.',"Do not keyword-stuff, do not list search terms, and do not repeat a word for emphasis.","Return plain text only: one line, no markdown, no HTML, no JSON, no commentary, no alternatives to choose between.","If surrounding page context is supplied, use it ONLY to disambiguate what you can already see — for example to choose the right word for an object or to know which product is pictured. Never use it to add detail that is not visible in the image."].join(" ")}function D(e){return[`Write the alt attribute for this image, at most ${e.maxLength} characters.`,e.context?`Surrounding page context, for disambiguation only: ${e.context}`:null].filter(Boolean).join(`
|
|
2
|
-
|
|
3
|
-
`)}function V(e){const o=l.getHttpStatusCode(e);if(o===401||o===402||o===403)return!1;if(l.isOpenRouterRecoverableRoutingError(e)||o&&o>=500)return!0;const t=e instanceof Error?e.message:String(e);return/NoContentGenerated|No content generated|Provider returned error|empty alt text|image|modality|multimodal|not support|unsupported|aborted|abort|timeout|timed out/i.test(t)}async function k(e){L();const o=q(e.imageUrl),t=Number.isFinite(e.maxLength)?Math.round(e.maxLength):u,n=Math.min(p.max,Math.max(p.min,t)),r=e.context?.replace(/\s+/g," ").trim()||null,{createCortexAiOpenRouterClient:a}=await Promise.resolve().then(()=>require("./ai-client.cjs.js")),i=await a({apiKey:e.apiKey||void 0}),x=_({credentialSource:i.credentialSource,requestedModelId:e.modelId,selectedModel:i.modelSelection}),E=[{content:[{text:D({context:r,maxLength:n}),type:"text"},{image:o,type:"image"}],role:"user"}],c=await l.runWithCortexAiModelFallback({modelIds:x.modelIds,shouldRetry:V,execute:async m=>{const s=new AbortController,I=setTimeout(()=>s.abort(),M),g=()=>s.abort();e.abortSignal?.addEventListener("abort",g,{once:!0}),e.abortSignal?.aborted&&s.abort();try{const w=l.omitUnsupportedCortexAiModelOptions({abortSignal:s.signal,maxOutputTokens:400,maxRetries:0,messages:E,system:P(n),temperature:.2},{modelId:m,modelSelection:i.modelSelection}),y=await C.generateText({...w,model:i.model(m)}),h=b(y.text,n);if(!h)throw new Error("Cortex AI returned empty alt text.");return h}finally{clearTimeout(I),e.abortSignal?.removeEventListener("abort",g)}}});return{altText:c.result,attempts:c.attempts.length,credentialSource:i.credentialSource,modelId:c.modelId}}exports.CORTEX_AI_DEFAULT_ALT_TEXT_MAX_LENGTH=u;exports.CORTEX_AI_VISION_MODEL_FALLBACK_REGISTRY=d;exports.buildCortexAiVisionRoutingPolicy=_;exports.generateCortexAiAltText=k;exports.isKnownVisionCapableCortexAiModelId=A;exports.normalizeGeneratedAltText=b;
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});require("./zod-config.cjs.js");const t=require("zod"),u=["text","heading","image","button","posts_grid","video_embed","section","form","testimonial","product_grid","featured_product","cart","checkout","product_details"],z=t.z.enum(u),d=t.z.object({direction:t.z.string().optional(),stops:t.z.array(t.z.object({color:t.z.string(),position:t.z.number()})),type:t.z.enum(["linear","radial"])}),g=t.z.object({gradient:d.optional(),image:t.z.object({alt_text:t.z.string().optional(),blur_data_url:t.z.string().optional(),external_url:t.z.string().optional(),height:t.z.number().optional(),media_id:t.z.string().optional(),object_key:t.z.string().optional(),overlay:t.z.object({gradient:d,type:t.z.literal("gradient")}).optional(),position:t.z.enum(["center","top","bottom","left","right"]),quality:t.z.number().nullable().optional(),size:t.z.enum(["cover","contain"]),width:t.z.number().optional()}).optional(),min_height:t.z.string().optional(),solid_color:t.z.string().optional(),theme:t.z.enum(["primary","secondary","muted","accent","destructive"]).optional(),type:t.z.enum(["none","theme","solid","gradient","image"])}),p=t.z.string().regex(/^[a-z][a-z0-9-]*$/),b=t.z.object({block_type:t.z.union([z,p]),content:t.z.record(t.z.string(),t.z.any()),temp_id:t.z.string().optional()}),k=t.z.object({background:g,column_blocks:t.z.array(t.z.array(b))}),y=t.z.object({autoplay:t.z.boolean().optional(),background:g,column_blocks:t.z.array(t.z.array(b)),column_gap:t.z.enum(["none","sm","md","lg","xl"]),container_type:t.z.enum(["full-width","container","container-sm","container-lg","container-xl"]),is_hero:t.z.boolean().optional(),padding:t.z.object({bottom:t.z.enum(["none","sm","md","lg","xl"]),top:t.z.enum(["none","sm","md","lg","xl"])}),responsive_columns:t.z.object({desktop:t.z.union([t.z.literal(1),t.z.literal(2),t.z.literal(3),t.z.literal(4)]),mobile:t.z.union([t.z.literal(1),t.z.literal(2)]),tablet:t.z.union([t.z.literal(1),t.z.literal(2),t.z.literal(3)])}),slider:t.z.boolean().optional(),slides:t.z.array(k).optional(),timeframe:t.z.number().optional(),vertical_alignment:t.z.enum(["start","center","end","stretch"]).optional()}),f={button:t.z.object({position:t.z.enum(["left","center","right"]).optional(),size:t.z.enum(["default","sm","lg","full"]).optional(),text:t.z.string(),url:t.z.string(),variant:t.z.enum(["default","outline","secondary","ghost","link"]).optional()}),cart:t.z.object({}),checkout:t.z.object({}),featured_product:t.z.object({imagePosition:t.z.enum(["left","right"]).default("left"),productId:t.z.string().min(1),showBackground:t.z.boolean().default(!1)}),form:t.z.object({fields:t.z.array(t.z.object({field_type:t.z.enum(["text","email","tel","url","number","textarea","select","radio","checkbox"]),is_required:t.z.boolean(),label:t.z.string(),options:t.z.array(t.z.object({label:t.z.string(),value:t.z.string()})).optional(),placeholder:t.z.string().optional(),temp_id:t.z.string()})),form_key:t.z.string().optional(),recipient_email:t.z.string().email().optional(),submit_button_text:t.z.string(),success_message:t.z.string()}),heading:t.z.object({level:t.z.union([t.z.literal(1),t.z.literal(2),t.z.literal(3),t.z.literal(4),t.z.literal(5),t.z.literal(6)]),textAlign:t.z.enum(["left","center","right","justify"]).optional(),textColor:t.z.union([t.z.enum(["foreground","primary","secondary","accent","muted","destructive","background"]),t.z.string().regex(/^(#(?:[0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})|rgba?\([^)]+\)|hsla?\([^)]+\))$/i,"Must be a hex, rgb(a) or hsl(a) colour")]).optional().describe("Prefer a theme token so the heading adapts to dark mode; use a CSS colour only when the brand requires an exact value"),text_content:t.z.string()}),image:t.z.object({alt_text:t.z.string().optional(),caption:t.z.string().optional(),external_url:t.z.string().nullable().optional(),height:t.z.number().nullable().optional(),media_id:t.z.string().nullable().optional(),object_key:t.z.string().nullable().optional(),width:t.z.number().nullable().optional()}),posts_grid:t.z.object({columns:t.z.number().min(1).max(6),postsPerPage:t.z.number().min(1).max(50),showPagination:t.z.boolean(),title:t.z.string().optional()}),product_details:t.z.object({}),product_grid:t.z.object({categoryId:t.z.string().optional(),categoryIds:t.z.array(t.z.string()).max(20).optional(),limit:t.z.number().min(0).max(48).default(6),productIds:t.z.array(t.z.string()).max(24).optional(),showPagination:t.z.boolean().default(!1),title:t.z.string().optional(),type:t.z.enum(["latest","category","manual"]).default("latest")}),section:y,testimonial:t.z.object({author_name:t.z.string().min(1),author_title:t.z.string().optional(),image_url:t.z.string().url().optional().or(t.z.literal("")),quote:t.z.string().min(1)}),text:t.z.object({html_content:t.z.string()}),video_embed:t.z.object({autoplay:t.z.boolean().optional(),controls:t.z.boolean().optional(),title:t.z.string().optional(),url:t.z.string()})};function _(o){return u.includes(o)}function j(o){return typeof o?.validateBlockContent=="function"?o.validateBlockContent:null}function x(o,n,a){const l=j(a);if(l)return l(o,n);const i=f[o].safeParse(n);return i.success?{errors:[],isValid:!0,warnings:[]}:{errors:i.error.issues.map(s=>{const e=s.path.join(".");return e?`${e}: ${s.message}`:s.message}),isValid:!1,warnings:[]}}function h(o){return Array.isArray(o.fields)?o.fields.filter(n=>!!n&&typeof n=="object"&&typeof n.key=="string"&&typeof n.type=="string"):[]}function B(o){return o==null||typeof o=="string"&&o.trim()===""||Array.isArray(o)&&o.length===0}function S(o,n){if(!n||typeof n!="object"||Array.isArray(n))return{errors:["content must be a JSON object of { field_key: value } pairs."],isValid:!1,warnings:[]};const a=h(o),l=new Set(a.map(e=>e.key)),i=[],s=[];for(const e of Object.keys(n))l.has(e)||i.push(`Unknown field "${e}" for custom block "${o.slug}". Known fields: ${[...l].join(", ")||"(none)"}.`);for(const e of a){const r=n[e.key];if(B(r)){e.required&&i.push(`Field "${e.key}" is required.`);continue}if(e.type==="text"||e.type==="rich-text"){if(typeof r!="string"){i.push(`Field "${e.key}" must be a string${e.type==="rich-text"?" of HTML":""}.`);continue}typeof e.max_length=="number"&&r.length>e.max_length&&i.push(`Field "${e.key}" exceeds its ${e.max_length}-character limit.`),typeof e.min_length=="number"&&r.length<e.min_length&&i.push(`Field "${e.key}" is shorter than its ${e.min_length}-character minimum.`);continue}if(e.type==="image_r2"){const c=r;(typeof r!="object"||Array.isArray(r)||typeof c.object_key!="string"||typeof c.url!="string")&&i.push(`Field "${e.key}" must be an uploaded image object with object_key and url (upload it with upload_media first) or null.`);continue}if(e.type==="db_relation"){const c=m=>typeof m=="string"||typeof m=="number";e.multiple?(!Array.isArray(r)||!r.every(c))&&i.push(`Field "${e.key}" must be an array of related record ids.`):c(r)||i.push(`Field "${e.key}" must be a single related record id.`);continue}s.push(`Field "${e.key}" has an unrecognised type "${String(e.type)}"; it was not validated.`)}return{errors:i,isValid:i.length===0,warnings:s}}async function C(o){const{data:n,error:a}=await o.from("custom_block_definitions").select("slug, name, fields");if(a)throw new Error(`Could not read the custom block definitions: ${typeof a=="object"&&a&&"message"in a?String(a.message):String(a)}`);return(Array.isArray(n)?n:[]).filter(l=>!!l&&typeof l.slug=="string")}exports.availableCortexAiBlockTypes=u;exports.cortexAiBlockTypeSchema=z;exports.customBlockSlugPatternSchema=p;exports.fallbackBlockSchemas=f;exports.isValidBlockType=_;exports.loadCustomBlockDefinitions=C;exports.readCustomBlockFields=h;exports.sectionBlockFallbackSchema=y;exports.validateCortexBlockContent=x;exports.validateCustomBlockInstanceContent=S;
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const n=require("@nextblock-cms/utils/custom-blocks"),a="id, slug, name, description, fields, layout_schema, is_original";class c extends Error{code;status;constructor(e,i){super(e),this.name="CortexWidgetRegistryInsertError",this.code=i?.code,this.status=i?.status??500}}function s(t){return JSON.parse(JSON.stringify(t))}function d(t){return t==="23505"?409:t==="42501"?403:500}function u(t){const e=n.customBlockDefinitionCreateSchema.parse({...t,is_original:!0});return{description:e.description,fields:s(e.fields),is_original:!0,layout_schema:s(e.layout_schema),name:e.name,slug:e.slug}}async function l(t,e){const i=u(e),{data:o,error:r}=await t.from("custom_block_definitions").insert(i).select(a).single();if(r||!o)throw new c(r?.message??"Failed to insert Cortex custom block definition.",{code:r?.code,status:d(r?.code)});return n.customBlockDefinitionRowSchema.parse(o)}exports.CORTEX_WIDGET_DEFINITION_SELECT=a;exports.CortexWidgetRegistryInsertError=c;exports.buildCortexWidgetDefinitionInsertPayload=u;exports.insertCortexWidgetDefinition=l;
|
|
@@ -1,5 +0,0 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const o=require("@nextblock-cms/utils/custom-blocks");require("./zod-config.cjs.js");const e=require("zod"),r=["pages","posts","products","media","categories","profiles","languages"],d=e.z.enum(["article","aside","blockquote","div","figure","figcaption","h2","h3","img","p","section","span"]).describe("A safe semantic element supported by the dynamic layout renderer."),c=e.z.string().trim().max(4e3).describe("Tailwind utility classes only. Do not include CSS, style tags, or JavaScript."),l=e.z.strictObject({description:e.z.string().trim().max(500).optional(),key:o.customBlockFieldKeySchema.describe("Lowercase snake_case field key."),label:e.z.string().trim().min(1).max(120),required:e.z.boolean().default(!1)}),m=l.extend({default_value:e.z.string().max(5e3).optional(),max_length:e.z.number().int().positive().max(1e4).optional(),min_length:e.z.number().int().min(0).max(1e4).optional(),placeholder:e.z.string().max(250).optional(),type:e.z.literal("text")}),u=l.extend({default_value:e.z.string().max(5e4).optional(),placeholder:e.z.string().max(250).optional(),type:e.z.literal("rich-text")}),p=l.extend({accept:e.z.array(e.z.string().trim().min(1).max(120)).max(20).optional(),default_value:e.z.strictObject({alt:e.z.string().max(300).optional(),file_name:e.z.string().trim().min(1).max(255).optional(),file_type:e.z.string().trim().min(1).max(120).optional(),height:e.z.number().int().positive().optional(),object_key:e.z.string().trim().min(1).max(1024),size_bytes:e.z.number().int().positive().optional(),url:e.z.string().trim().min(1).max(2048),width:e.z.number().int().positive().optional()}).optional(),max_bytes:e.z.number().int().positive().max(50*1024*1024).optional(),type:e.z.literal("image_r2")}),f=l.extend({default_value:e.z.union([e.z.string(),e.z.array(e.z.string()),e.z.null()]).optional(),display_column:e.z.string().trim().min(1).max(80).default("title"),filters:e.z.record(e.z.string(),e.z.unknown()).optional(),multiple:e.z.boolean().default(!1),table:e.z.enum(r),type:e.z.literal("db_relation"),value_column:e.z.string().trim().min(1).max(80).default("id")}),y=e.z.discriminatedUnion("type",[m,u,p,f]).describe("A NextBlock custom block field. Allowed types: text, rich-text, image_r2, db_relation."),s=e.z.lazy(()=>e.z.discriminatedUnion("type",[e.z.strictObject({as:d.optional(),children:e.z.array(s).max(200).default([]),className:c.optional(),type:e.z.literal("container")}),e.z.strictObject({as:d.optional(),className:c.optional(),column:e.z.string().trim().min(1).max(80).optional().describe("For a db_relation field, the related record column to display (e.g. title, price)."),emptyFallback:e.z.string().max(300).optional(),field_key:o.customBlockFieldKeySchema,type:e.z.literal("field_render")})])),_=e.z.strictObject({context:e.z.string().trim().max(24e3).optional(),modelId:e.z.string().trim().min(1).max(200).optional(),prompt:e.z.string().trim().min(3).max(4e3)});function g(t){return t.type==="field_render"?[t.field_key]:t.children.flatMap(i=>g(i))}function k(t,i){const n=new Set;t.fields.forEach((a,b)=>{n.has(a.key)&&i.addIssue({code:"custom",message:`Duplicate field key "${a.key}".`,path:["fields",b,"key"]}),n.add(a.key)});for(const a of g(t.layout_schema))n.has(a)||i.addIssue({code:"custom",message:`Layout references unknown field "${a}".`,path:["layout_schema"]})}const h=e.z.strictObject({description:e.z.string().trim().max(1e3).default(""),fields:e.z.array(y).min(1).max(80),is_original:e.z.boolean().default(!0),layout_schema:s,name:e.z.string().trim().min(1).max(160),slug:o.customBlockSlugSchema.describe("Lowercase kebab-case slug.")}).superRefine(k).describe("A complete NextBlock custom block definition stored as database JSONB.");function x(t){const i=h.parse(t);return o.customBlockDefinitionCreateSchema.parse({...i,is_original:!0})}function z(){return["You are NextBlock Cortex, an expert web platform engineer building database-rendered custom CMS widgets.","Return ONLY one clean raw JSON object with the exact structure described in the user message. Do not include markdown fences, comments, prose, or explanatory text.","Never emit TSX, JSX, React components, JavaScript, CSS blocks, style attributes, script tags, or runtime code.","Use only these field types: text, rich-text, image_r2, db_relation.",`Use db_relation.table only from this allowlist: ${r.join(", ")}.`,"Use lowercase kebab-case for slug and lowercase snake_case for field keys.","Build layout_schema as a self-referential tree: container nodes may contain nested container or field_render nodes to any needed depth.","Use Tailwind utility classes in className strings. Use responsive utilities where helpful.",'The "as" property of any node MUST be exactly one of: article, aside, blockquote, div, figure, figcaption, h2, h3, img, p, section, span. Never use a, button, ul, ol, li, table, or any other tag. For a call-to-action or "more info" button, use a span or p styled with button-like Tailwind classes (rounded, padded, colored background).',"Every field_render.field_key must match one field key exactly.","For relation fields, set value_column to id and set display_column to a column that actually exists on the chosen table: use title for pages, posts, and products; sku for product_variants; full_name for profiles; name for categories and languages; file_name for media. Do not invent display columns.",`Entity images: when a block displays an image that belongs to a related product, page, or post (for example a product card photo or a post thumbnail), do NOT add an image_r2 upload field for it. Instead add a single db_relation field to that table (products, product_variants, pages, or posts) and add a field_render node that references it with "as": "img". The renderer automatically resolves the related record's primary image — a product or variant main_image/object_key, or a page/post feature image — so keep the table's normal display_column (for example title for a products relation).`,'You may reference the same db_relation field from more than one field_render node: for example one node with "as": "img" for the image and another text node for its title, plus the relation value to drive a "more info" link. This builds a product/page/post card from a single relation field.',`To display a SPECIFIC column of a related record (its title, price, sku, etc.), set the field_render node's "column" property to that column name. The "column" overrides the field display_column for that one node, so a single product relation can show its image (as "img"), title (column "title"), and price (column "price") from three field_render nodes.`,'Available record columns by table — only reference these in a node "column": products: title, sku, price, sale_price, stock, short_description, slug, status; product_variants: sku, price, sale_price, stock_quantity; pages: title, slug, status; posts: title, slug, excerpt, subtitle; profiles: full_name; categories: name, slug, description; media: file_name; languages: name, code. Use "as": "img" (no column) to show a record image.','Do NOT create a standalone text field for data that lives on a related record. For example, a product price must come from a products db_relation field rendered with column "price" — never a separate "text" field the editor types by hand.',"Monetary columns (price, sale_price, price_adjustment) are stored in integer cents and are automatically formatted as currency on display, so reference them directly; never multiply, divide, or add currency symbols yourself.","Only use image_r2 for standalone images uploaded directly by the editor that are not tied to any database record (for example a decorative banner or icon). Only use text or rich-text fields for free-form copy the editor writes, not for values that exist on a related record."].join(" ")}function v(t){return["Create a NextBlock custom block definition for this request:",t.prompt,t.context?`Additional CMS context:
|
|
2
|
-
${t.context}`:null,["Return ONLY a JSON object with EXACTLY these top-level keys:",'- "name": string (human-friendly block name).','- "slug": lowercase kebab-case string.','- "description": short string.','- "is_original": true.','- "fields": a non-empty array of field objects. Each field is { "key": lowercase snake_case string, "label": string, "required": boolean, "type": one of "text" | "rich-text" | "image_r2" | "db_relation" }.',` For "db_relation" fields also include "table" (one of: ${r.join(", ")}), "display_column" (e.g. title, name, full_name, file_name, code), "value_column": "id", and "multiple": boolean.`,'- "layout_schema": a single root layout node (a tree). Every node is one of:',' container: { "type": "container", "as": an HTML tag like div/section/article/figure, "className": Tailwind utility classes, "children": array of nodes }.',' field render: { "type": "field_render", "field_key": one of the field keys above, "as": an HTML tag like p/span/img/h2/h3/div, "className": Tailwind utility classes, "emptyFallback": optional placeholder string }.',' Containers may nest other containers to any depth. Every field_render.field_key MUST match one of the fields. Render image_r2 fields with "as": "img".'].join(`
|
|
3
|
-
`)].filter(Boolean).join(`
|
|
4
|
-
|
|
5
|
-
`)}function S(){return x({description:"A multi-tier profile card with an R2 image asset slot and a live customer relation list.",fields:[{accept:["image/png","image/jpeg","image/webp"],key:"profile_photo",label:"Profile Photo",max_bytes:10485760,required:!1,type:"image_r2"},{key:"profile_name",label:"Profile Name",placeholder:"Ada Lovelace",required:!0,type:"text"},{key:"profile_role",label:"Profile Role",placeholder:"Principal Architect",required:!1,type:"text"},{key:"profile_summary",label:"Profile Summary",placeholder:"<p>Short profile biography.</p>",required:!1,type:"rich-text"},{display_column:"full_name",key:"customer_list",label:"Customer List",multiple:!0,required:!1,table:"profiles",type:"db_relation",value_column:"id"}],is_original:!0,layout_schema:{as:"article",children:[{as:"div",children:[{as:"div",children:[{as:"div",children:[{as:"img",className:"h-24 w-24 rounded-full border object-cover shadow-sm",emptyFallback:"Upload profile photo",field_key:"profile_photo",type:"field_render"},{as:"span",className:"rounded-full bg-muted px-3 py-1 text-center text-xs font-medium text-muted-foreground",emptyFallback:"No customers linked",field_key:"customer_list",type:"field_render"}],className:"flex flex-col items-center gap-4 md:w-48",type:"container"},{as:"div",children:[{as:"div",children:[{as:"h2",className:"text-2xl font-semibold leading-tight",emptyFallback:"Untitled profile",field_key:"profile_name",type:"field_render"},{as:"p",className:"text-sm font-medium text-muted-foreground",emptyFallback:"Role pending",field_key:"profile_role",type:"field_render"}],className:"flex flex-col gap-1",type:"container"},{as:"div",children:[{as:"div",className:"prose prose-sm max-w-none text-muted-foreground",emptyFallback:"<p>Add a concise profile summary.</p>",field_key:"profile_summary",type:"field_render"}],className:"rounded-md border bg-muted/30 p-4",type:"container"}],className:"flex min-w-0 flex-1 flex-col gap-4",type:"container"}],className:"flex flex-col gap-6 md:flex-row",type:"container"}],className:"rounded-lg border bg-background p-6 shadow-sm",type:"container"}],className:"mx-auto max-w-3xl p-4",type:"container"},name:"Cortex Profile Card",slug:"cortex-profile-card"})}exports.CORTEX_WIDGET_ALLOWED_RELATION_TABLES=r;exports.buildCortexProfileCardVerificationDefinition=S;exports.buildCortexWidgetBuilderPrompt=v;exports.buildCortexWidgetBuilderSystemPrompt=z;exports.cortexWidgetBuildRequestSchema=_;exports.cortexWidgetDbRelationFieldSchema=f;exports.cortexWidgetDefinitionSchema=h;exports.cortexWidgetFieldSchema=y;exports.cortexWidgetImageR2FieldSchema=p;exports.cortexWidgetLayoutNodeSchema=s;exports.cortexWidgetRichTextFieldSchema=u;exports.cortexWidgetTextFieldSchema=m;exports.validateCortexWidgetDefinitionOutput=x;
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const w=new Set(["area","base","br","col","embed","hr","img","input","link","meta","param","source","track","wbr"]),I={b:"bold",code:"code",del:"strike",em:"italic",i:"italic",mark:"highlight",s:"strike",strike:"strike",strong:"bold",sub:"subscript",sup:"superscript"},S=new Set(["article","aside","body","div","footer","header","html","main","nav","section"]),h=new Set(["script","style","noscript","svg","template","iframe","form"]),b=12;function u(i){return i.replace(/ /gi," ").replace(/</gi,"<").replace(/>/gi,">").replace(/"/gi,'"').replace(/�?39;/g,"'").replace(/'/gi,"'").replace(/&#(\d+);/g,(e,t)=>String.fromCodePoint(Number(t))).replace(/&#x([0-9a-f]+);/gi,(e,t)=>String.fromCodePoint(Number.parseInt(t,16))).replace(/&/gi,"&")}function T(i,e){const t=i.match(new RegExp(`\\b${e}\\s*=\\s*(?:"([^"]*)"|'([^']*)'|([^\\s>]+))`,"i"));return t?u(t[1]??t[2]??t[3]??""):null}function A(i,e,t){const n=new RegExp(`<${t}\\b`,"gi"),o=new RegExp(`</${t}\\s*>`,"gi");let r=1,a=e;for(;r>0;){o.lastIndex=a;const c=o.exec(i);if(!c)return{end:i.length,inner:i.slice(e)};n.lastIndex=a;const s=n.exec(i);if(s&&s.index<c.index){r+=1,a=s.index+s[0].length;continue}if(r-=1,a=c.index+c[0].length,r===0)return{end:a,inner:i.slice(e,c.index)}}return{end:a,inner:i.slice(e)}}function d(i){const e=[];let t=0;for(;t<i.length;){const n=i.indexOf("<",t);if(n===-1){e.push({text:i.slice(t),type:"text"});break}n>t&&e.push({text:i.slice(t,n),type:"text"});const o=i.indexOf(">",n);if(o===-1){e.push({text:i.slice(n),type:"text"});break}const r=i.slice(n+1,o);if(r.startsWith("!")||r.startsWith("/")||r.startsWith("?")){t=o+1;continue}const a=r.match(/^([a-zA-Z][a-zA-Z0-9-]*)/);if(!a){t=o+1;continue}const c=a[1].toLowerCase();if(w.has(c)||r.trimEnd().endsWith("/")){e.push({attrs:r,inner:"",tag:c,type:"element"}),t=o+1;continue}const s=A(i,o+1,c);e.push({attrs:r,inner:s.inner,tag:c,type:"element"}),t=s.end}return e}function g(i,e,t){if(!e)return;const n=i[i.length-1];if(n&&n.type==="text"&&JSON.stringify(n.marks??[])===JSON.stringify(t)){n.text+=e;return}i.push(t.length>0?{marks:t,text:e,type:"text"}:{text:e,type:"text"})}function p(i,e,t){const n=[];if(t>b)return g(n,u(i.replace(/<[^>]*>/g,"")).replace(/\s+/g," "),e),n;for(const o of d(i)){if(o.type==="text"){g(n,u(o.text).replace(/\s+/g," "),e);continue}if(h.has(o.tag))continue;if(o.tag==="br"){n.push({type:"hardBreak"});continue}if(o.tag==="a"){const a=T(o.attrs,"href"),c=a?[...e,{attrs:{href:a,target:"_blank"},type:"link"}]:e;n.push(...p(o.inner,c,t+1));continue}const r=I[o.tag];if(r){const a=e.some(c=>c.type===r)?e:[...e,{type:r}];n.push(...p(o.inner,a,t+1));continue}n.push(...p(o.inner,e,t+1))}return n}function k(i){const e=[...i];for(;e.length>0;){const t=e[0];if(t.type==="hardBreak"){e.shift();continue}const n=t.text.replace(/^\s+/,"");if(!n){e.shift();continue}e[0]={...t,text:n};break}for(;e.length>0;){const t=e[e.length-1];if(t.type==="hardBreak"){e.pop();continue}const n=t.text.replace(/\s+$/,"");if(!n){e.pop();continue}e[e.length-1]={...t,text:n};break}return e}function y(i){const e=k(i);return e.length>0?{content:e,type:"paragraph"}:null}function $(i,e){const t=[];for(const n of d(i)){if(n.type!=="element"||n.tag!=="li")continue;const o=f(n.inner,e+1);t.push({content:o.length>0?o:[{type:"paragraph"}],type:"listItem"})}return t}function f(i,e){const t=[];if(e>b)return t;let n=[];const o=()=>{const r=y(n);r&&t.push(r),n=[]};for(const r of d(i)){if(r.type==="text"){g(n,u(r.text).replace(/\s+/g," "),[]);continue}const{attrs:a,inner:c,tag:s}=r;if(h.has(s))continue;const x=s.match(/^h([1-6])$/);if(x){o();const l=k(p(c,[],e+1));l.length>0&&t.push({attrs:{level:Number(x[1])},content:l,type:"heading"});continue}if(s==="p"){o();const l=y(p(c,[],e+1));l&&t.push(l);continue}if(s==="ul"||s==="ol"){o();const l=$(c,e);l.length>0&&t.push({content:l,type:s==="ul"?"bulletList":"orderedList"});continue}if(s==="blockquote"){o();const l=f(c,e+1);l.length>0&&t.push({content:l,type:"blockquote"});continue}if(s==="pre"){o();const l=u(c.replace(/<[^>]*>/g,"")).replace(/^\n+|\n+$/g,"");l&&t.push({content:[{text:l,type:"text"}],type:"codeBlock"});continue}if(s==="hr"){o(),t.push({type:"horizontalRule"});continue}if(s==="br"){n.push({type:"hardBreak"});continue}if(S.has(s)||s==="li"||s==="table"){o(),t.push(...f(c,e+1));continue}n.push(...p(`<${a}>${c}</${s}>`,[],e+1))}return o(),t}function m(i){return i.split(/\n\s*\n/).map(e=>e.trim()).filter(Boolean).map(e=>({content:[{text:e.replace(/\s*\n\s*/g," "),type:"text"}],type:"paragraph"}))}function E(i){const e=(typeof i=="string"?i:"").trim().replace(/^```(?:html|xml)?\s*\n?/i,"").replace(/\n?```$/,"").trim();if(!e)return null;const t=[...h].reduce((r,a)=>r.replace(new RegExp(`<${a}\\b[\\s\\S]*?</${a}\\s*>`,"gi")," "),e).trim();if(!t)return null;const o=/<[a-zA-Z!/]/.test(t)?f(t,0):m(t);if(o.length===0){const r=m(u(t.replace(/<[^>]*>/g," ")).replace(/[ \t]+/g," "));return r.length>0?{content:r,type:"doc"}:null}return{content:o,type:"doc"}}exports.editorDocumentFromHtml=E;
|
package/lib/mcp-server.cjs.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const l=require("./mcp-tool-registry.cjs.js"),C="nextblock-cortex-ai",E="NextBlock Cortex AI",M="2025-06-18",f="2025-11-25",R="2026-07-28",T=[R,f,"2025-06-18","2025-03-26","2024-11-05"],x=-32700,p=-32600,S=-32601,_=-32602,O=-32603;function u(t,o){return{body:{id:t,jsonrpc:"2.0",result:o},status:200}}function a(t,o,i,e=200,c){return{body:{error:{code:o,message:i},id:t,jsonrpc:"2.0"},status:e}}const s={body:null,status:202};function N(t){return typeof t.method=="string"&&t.id===void 0}function b(t,o){const i=t.params?._meta;if(i&&typeof i=="object"){const e=i["io.modelcontextprotocol/protocolVersion"];if(typeof e=="string"&&e>=R)return!0}return!!(o&&o>=R)}function g(t){return typeof t!="string"||!t?M:T.includes(t)?t:f}function A(t,o){const i=t.scopes.includes("write");return{capabilities:{prompts:{},resources:{},tools:{}},instructions:t.instructions??["NextBlock Cortex AI exposes this CMS through typed tools.","Call get_database_schema first when you are unsure what exists.","Conventions: a page or post feature_image_id renders as a full-width title banner above the content and is its share preview — give posts one, never the home page or a page with its own hero section (use update_site_identity social_image for the site-wide preview); mark hero sections is_hero:true; slider:true plus slides makes a carousel.",i?"Page builds should go through generate_jsonb_layout, which stages a reviewable Live Draft rather than publishing directly.":"This connection is READ-ONLY. Mutating tools are not available on this token."].join(" "),protocolVersion:g(o),serverInfo:{name:C,title:E,version:t.serverVersion,websiteUrl:"https://nextblock.dev"}}}function v(t){return{authentication:{header:"Authorization",instructions:"POST JSON-RPC 2.0 messages with `Authorization: Bearer <token>`. Create the token in the NextBlock CMS (Settings → Cortex AI → MCP server access) or set MCP_BEARER_TOKEN in the environment. Cortex AI must be active on the site.",required:!0,schemes:["bearer"]},capabilities:{prompts:{},resources:{},tools:{}},endpoint:{transport:"streamable-http",url:t.endpointUrl},name:C,protocolVersions:T,serverCard:t.serverCardUrl,status:"ok",title:E,version:t.serverVersion,websiteUrl:"https://nextblock.dev"}}function y(t){return!!(t&&t.toLowerCase().includes("text/event-stream"))}async function I(t,o){if(t===null||typeof t!="object"||Array.isArray(t))return a(null,p,"Expected a single JSON-RPC message.",400);if(typeof t.method!="string")return"result"in t||"error"in t?s:a(t.id??null,p,'Missing "method".',400);const{method:i}=t,e=t.id??null,c=N(t);if(i.startsWith("notifications/"))return s;switch(i){case"initialize":return c?s:u(e,A(o,t.params?.protocolVersion));case"ping":return c?s:u(e,{});case"tools/list":return c?s:u(e,{tools:l.buildCortexMcpToolDefinitions({context:o.context,scopes:o.scopes})});case"tools/call":{if(c)return s;const n=t.params?.name;if(typeof n!="string"||!n)return a(e,_,"tools/call requires params.name.");try{const r=await l.callCortexMcpTool({args:t.params?.arguments,context:o.context,name:n,scopes:o.scopes});return u(e,r)}catch(r){return r instanceof l.CortexMcpUnknownToolError||r instanceof l.CortexMcpForbiddenToolError?a(e,_,r.message):a(e,O,r instanceof Error?r.message:"Tool execution failed.")}}case"resources/list":return c?s:u(e,{resources:l.CORTEX_MCP_RESOURCES});case"resources/templates/list":return c?s:u(e,{resourceTemplates:[]});case"resources/read":{if(c)return s;const n=t.params?.uri;if(typeof n!="string"||!n)return a(e,_,"resources/read requires params.uri.");try{const r=await l.readCortexMcpResource({context:o.context,uri:n});return r?u(e,{contents:[r]}):a(e,_,`Unknown resource: ${n}`)}catch(r){return a(e,O,r instanceof Error?r.message:"Resource read failed.")}}case"prompts/list":return c?s:u(e,{prompts:l.CORTEX_MCP_PROMPTS});case"prompts/get":{if(c)return s;const n=t.params?.name;if(typeof n!="string"||!n)return a(e,_,"prompts/get requires params.name.");const r=t.params?.arguments,P={};if(r&&typeof r=="object")for(const[m,d]of Object.entries(r))typeof d=="string"&&(P[m]=d);const h=l.getCortexMcpPrompt({args:P,name:n});return h?u(e,h):a(e,_,`Unknown prompt: ${n}`)}default:return c?s:a(e,S,`Method not found: ${i}`)}}exports.CORTEX_MCP_DEFAULT_PROTOCOL_VERSION=M;exports.CORTEX_MCP_LATEST_LEGACY_PROTOCOL_VERSION=f;exports.CORTEX_MCP_MODERN_PROTOCOL_VERSION=R;exports.CORTEX_MCP_SERVER_NAME=C;exports.CORTEX_MCP_SERVER_TITLE=E;exports.CORTEX_MCP_SUPPORTED_PROTOCOL_VERSIONS=T;exports.JSON_RPC_INTERNAL_ERROR=O;exports.JSON_RPC_INVALID_PARAMS=_;exports.JSON_RPC_INVALID_REQUEST=p;exports.JSON_RPC_METHOD_NOT_FOUND=S;exports.JSON_RPC_PARSE_ERROR=x;exports.buildCortexMcpDiscoveryDocument=v;exports.handleCortexMcpMessage=I;exports.isJsonRpcNotification=N;exports.isModernEraMessage=b;exports.wantsMcpEventStream=y;
|
package/lib/mcp-tokens.cjs.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const i=require("node:crypto"),M="Cortex AI MCP token utilities can only be imported from server-side code.";function c(){if(!(typeof window>"u"))throw new Error(M)}const E="cortex_ai_mcp_settings",l="mcp_access_tokens",_="nbmcp_",m=32,k=8,C=["read","write"],a={allowLocalhostWithoutToken:!0,enabled:!1};function d(e){const t=e&&typeof e=="object"&&!Array.isArray(e)?e:{};return{allowLocalhostWithoutToken:typeof t.allowLocalhostWithoutToken=="boolean"?t.allowLocalhostWithoutToken:a.allowLocalhostWithoutToken,enabled:typeof t.enabled=="boolean"?t.enabled:a.enabled}}async function O(e){if(e)try{const{data:t}=await e.from("site_settings").select("value").eq("key",E).maybeSingle();if(t?.value)return d(t.value)}catch{}return{...a}}function r(e){return c(),i.createHash("sha256").update(e.trim(),"utf8").digest("hex")}function R(){c();const e=`${_}${i.randomBytes(m).toString("base64url")}`;return{token:e,tokenHash:r(e),tokenPrefix:e.slice(0,_.length+k)}}function v(e){const t=e?.trim();if(!t)return null;const o=/^Bearer\s+(.+)$/i.exec(t);return(o?o[1]:t).trim()||null}function x(e){const o=(Array.isArray(e)?e:[]).filter(n=>C.includes(n));return o.length>0?Array.from(new Set(o)):["read"]}async function I(e,t,o=new Date){c();const n=t?.trim();if(!n||n.length<16)return{reason:"malformed",valid:!1};const f=r(n),{data:T,error:p}=await e.from(l).select("id, name, scopes, token_prefix, created_at, created_by, expires_at, last_used_at, revoked_at").eq("token_hash",f).maybeSingle();if(p||!T)return{reason:"unknown",valid:!1};const S=Buffer.from(f,"utf8");if(!i.timingSafeEqual(S,Buffer.from(r(n),"utf8")))return{reason:"unknown",valid:!1};const s=T;return s.revoked_at?{reason:"revoked",valid:!1}:s.expires_at&&new Date(s.expires_at).getTime()<=o.getTime()?{reason:"expired",valid:!1}:{scopes:x(s.scopes),token:s,valid:!0}}async function N(e,t,o=new Date){try{await e.from(l).update({last_used_at:o.toISOString()}).eq("id",t)}catch{}}const y=new Set(["localhost","127.0.0.1","[::1]","::1","0.0.0.0"]);function A(e){const t=e?.trim().toLowerCase();if(!t)return!1;const o=t.startsWith("[")?t.replace(/\]:\d+$/,"]"):t.replace(/:\d+$/,"");return y.has(o)||o.endsWith(".localhost")}function P(e){return!e.settings.allowLocalhostWithoutToken||process.env.NODE_ENV==="production"?!1:A(e.hostHeader)}const h="MCP_BEARER_TOKEN",u=32;function g(e=process.env){const t=e[h]?.trim();return!t||t.length<u?null:t}function L(e,t){c();const o=e?.trim(),n=t?.trim();return!o||!n||n.length<u?!1:i.timingSafeEqual(Buffer.from(r(o),"utf8"),Buffer.from(r(n),"utf8"))}exports.CORTEX_AI_MCP_ENV_TOKEN_MIN_LENGTH=u;exports.CORTEX_AI_MCP_ENV_TOKEN_VAR=h;exports.CORTEX_AI_MCP_SCOPES=C;exports.CORTEX_AI_MCP_SETTINGS_DEFAULTS=a;exports.CORTEX_AI_MCP_SETTINGS_KEY=E;exports.CORTEX_AI_MCP_TOKENS_TABLE=l;exports.CORTEX_AI_MCP_TOKEN_PREFIX=_;exports.hashCortexAiMcpToken=r;exports.isLocalhostHost=A;exports.matchesCortexAiMcpEnvToken=L;exports.mintCortexAiMcpToken=R;exports.normalizeCortexAiMcpSettings=d;exports.parseBearerToken=v;exports.readCortexAiMcpEnvToken=g;exports.resolveCortexAiMcpSettings=O;exports.shouldTrustLocalMcpRequest=P;exports.touchCortexAiMcpToken=N;exports.verifyCortexAiMcpToken=I;
|