sanity-plugin-seofields 1.8.0 → 1.9.0
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 +437 -26
- package/dist/SeoHealthTool-2COI27KI.cjs +8 -0
- package/dist/SeoHealthTool-2COI27KI.cjs.map +1 -0
- package/dist/SeoHealthTool-CWI3KB2V.js +8 -0
- package/dist/SeoHealthTool-CWI3KB2V.js.map +1 -0
- package/dist/{SeoPreview-3EXR6FD4.cjs → SeoPreview-LMZAWWOE.cjs} +35 -38
- package/dist/SeoPreview-LMZAWWOE.cjs.map +1 -0
- package/dist/{SeoPreview-4PPAF4NO.js → SeoPreview-UNQBKTQO.js} +14 -11
- package/dist/SeoPreview-UNQBKTQO.js.map +1 -0
- package/dist/chunk-3OK3S2F7.cjs +673 -0
- package/dist/chunk-3OK3S2F7.cjs.map +1 -0
- package/dist/{chunk-B5IVI5LP.cjs → chunk-5XTQRILL.cjs} +286 -236
- package/dist/chunk-5XTQRILL.cjs.map +1 -0
- package/dist/{chunk-254YHUN3.cjs → chunk-7N4MLTMR.js} +8 -6
- package/dist/chunk-7N4MLTMR.js.map +1 -0
- package/dist/{chunk-DDAAVRWG.js → chunk-A57XNQC7.cjs} +9 -4
- package/dist/chunk-A57XNQC7.cjs.map +1 -0
- package/dist/chunk-BWLJDK5J.js +624 -0
- package/dist/chunk-BWLJDK5J.js.map +1 -0
- package/dist/chunk-FUUWBQE2.cjs +195 -0
- package/dist/chunk-FUUWBQE2.cjs.map +1 -0
- package/dist/{chunk-ZBHLMQTS.cjs → chunk-HHO2AKAP.js} +44 -17
- package/dist/chunk-HHO2AKAP.js.map +1 -0
- package/dist/chunk-KIEO6QG3.js +195 -0
- package/dist/chunk-KIEO6QG3.js.map +1 -0
- package/dist/chunk-R2U7JF7U.cjs +624 -0
- package/dist/chunk-R2U7JF7U.cjs.map +1 -0
- package/dist/{chunk-VR44E62I.js → chunk-XZKQWV2H.js} +204 -33
- package/dist/chunk-XZKQWV2H.js.map +1 -0
- package/dist/{chunk-HDZZQCH7.js → chunk-Y46ACXM4.cjs} +45 -5
- package/dist/chunk-Y46ACXM4.cjs.map +1 -0
- package/dist/chunk-Z5AOUU4H.js +673 -0
- package/dist/chunk-Z5AOUU4H.js.map +1 -0
- package/dist/cli.js +27 -27
- package/dist/{component-DEXwtemT.d.ts → component-CjT1hvxh.d.ts} +2 -2
- package/dist/{component-BzI-LHPw.d.cts → component-WYh0z8as.d.cts} +2 -2
- package/dist/define-cli.cjs +2 -4
- package/dist/define-cli.cjs.map +1 -1
- package/dist/define-cli.js +4 -4
- package/dist/define-cli.js.map +1 -1
- package/dist/head.cjs +14 -0
- package/dist/head.cjs.map +1 -0
- package/dist/head.d.cts +254 -0
- package/dist/head.d.ts +254 -0
- package/dist/head.js +14 -0
- package/dist/head.js.map +1 -0
- package/dist/index.cjs +978 -367
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +6 -374
- package/dist/index.d.ts +6 -374
- package/dist/index.js +920 -286
- package/dist/index.js.map +1 -1
- package/dist/next.cjs +204 -455
- package/dist/next.cjs.map +1 -1
- package/dist/next.d.cts +8 -206
- package/dist/next.d.ts +8 -206
- package/dist/next.js +181 -111
- package/dist/next.js.map +1 -1
- package/dist/plugin-DQdThyxG.d.ts +449 -0
- package/dist/plugin-DoGeZP79.d.cts +449 -0
- package/dist/schema/next.cjs +173 -327
- package/dist/schema/next.cjs.map +1 -1
- package/dist/schema/next.d.cts +4 -4
- package/dist/schema/next.d.ts +4 -4
- package/dist/schema/next.js +172 -8
- package/dist/schema/next.js.map +1 -1
- package/dist/schema.cjs +376 -517
- package/dist/schema.cjs.map +1 -1
- package/dist/schema.d.cts +5 -5
- package/dist/schema.d.ts +5 -5
- package/dist/schema.js +216 -11
- package/dist/schema.js.map +1 -1
- package/dist/server.cjs +149 -0
- package/dist/server.cjs.map +1 -0
- package/dist/server.d.cts +102 -0
- package/dist/server.d.ts +102 -0
- package/dist/server.js +149 -0
- package/dist/server.js.map +1 -0
- package/dist/{types-CW8qFdAn.d.ts → types-BAdN1RMu.d.ts} +2 -2
- package/dist/{types-B_vjMPtM.d.cts → types-C5i3KMgs.d.cts} +2 -2
- package/dist/{types-BXSCbl6p.d.cts → types-DP-DiW6f.d.cts} +2 -2
- package/dist/{types-C19cQx5D.d.ts → types-DRLUGLtX.d.ts} +2 -2
- package/dist/{types-yVmQfby9.d.cts → types-DxlPXihz.d.cts} +1 -1
- package/dist/{types-yVmQfby9.d.ts → types-DxlPXihz.d.ts} +1 -1
- package/package.json +25 -4
- package/dist/SeoHealthDashboard-AEKVVMUR-7NWV3C3Y.js +0 -4
- package/dist/SeoHealthDashboard-AEKVVMUR-7NWV3C3Y.js.map +0 -1
- package/dist/SeoHealthDashboard-AEKVVMUR-XWKJUH24.cjs +0 -10
- package/dist/SeoHealthDashboard-AEKVVMUR-XWKJUH24.cjs.map +0 -1
- package/dist/SeoHealthTool-2KKQJLJL.cjs +0 -11
- package/dist/SeoHealthTool-2KKQJLJL.cjs.map +0 -1
- package/dist/SeoHealthTool-3CUKGADZ.js +0 -5
- package/dist/SeoHealthTool-3CUKGADZ.js.map +0 -1
- package/dist/SeoPreview-3EXR6FD4.cjs.map +0 -1
- package/dist/SeoPreview-4PPAF4NO.js.map +0 -1
- package/dist/chunk-254YHUN3.cjs.map +0 -1
- package/dist/chunk-27XSYENH.js +0 -2215
- package/dist/chunk-27XSYENH.js.map +0 -1
- package/dist/chunk-B5IVI5LP.cjs.map +0 -1
- package/dist/chunk-BNXMFD3T.cjs +0 -431
- package/dist/chunk-BNXMFD3T.cjs.map +0 -1
- package/dist/chunk-DDAAVRWG.js.map +0 -1
- package/dist/chunk-HDZZQCH7.js.map +0 -1
- package/dist/chunk-P6IOWIO2.cjs +0 -480
- package/dist/chunk-P6IOWIO2.cjs.map +0 -1
- package/dist/chunk-UOCZFYYP.js +0 -407
- package/dist/chunk-UOCZFYYP.js.map +0 -1
- package/dist/chunk-VR44E62I.js.map +0 -1
- package/dist/chunk-WKXHX3GO.js +0 -424
- package/dist/chunk-WKXHX3GO.js.map +0 -1
- package/dist/chunk-XZDLJ2N6.cjs +0 -2224
- package/dist/chunk-XZDLJ2N6.cjs.map +0 -1
- package/dist/chunk-ZBHLMQTS.cjs.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["/Users/hardik/GITHUB/sanity-plugin-seofields/npm/dist/chunk-3OK3S2F7.cjs","../src/utils/readability.ts","../src/utils/seoPrompts.ts","../src/utils/seoContentGen.ts"],"names":[],"mappings":"AAAA;AACE;AACA;AACF,wDAA6B;AAC7B;AACA;ACYA,SAAS,cAAA,CAAe,IAAA,EAAsB;AAjB9C,EAAA,IAAA,EAAA;AAkBE,EAAA,MAAM,EAAA,EAAI,IAAA,CAAK,WAAA,CAAY,CAAA,CAAE,OAAA,CAAQ,SAAA,EAAW,EAAE,CAAA;AAClD,EAAA,GAAA,CAAI,CAAA,CAAE,OAAA,GAAU,CAAA,EAAG,OAAO,CAAA;AAG1B,EAAA,MAAM,OAAA,EAAA,CAAS,GAAA,EAAA,CAAA,CAAE,KAAA,CAAM,YAAY,CAAA,EAAA,GAApB,KAAA,EAAA,GAAA,EAAyB,CAAC,CAAA;AACzC,EAAA,IAAI,MAAA,EAAQ,MAAA,CAAO,MAAA;AAGnB,EAAA,GAAA,CAAI,CAAA,CAAE,QAAA,CAAS,GAAG,EAAA,GAAK,CAAA,CAAE,OAAA,EAAS,EAAA,GAAK,CAAC,UAAA,CAAW,IAAA,CAAK,CAAA,CAAE,CAAA,CAAE,OAAA,EAAS,CAAC,CAAC,CAAA,EAAG;AACxE,IAAA,MAAA,EAAQ,IAAA,CAAK,GAAA,CAAI,CAAA,EAAG,MAAA,EAAQ,CAAC,CAAA;AAAA,EAC/B;AAEA,EAAA,OAAO,IAAA,CAAK,GAAA,CAAI,CAAA,EAAG,KAAK,CAAA;AAC1B;AAKA,SAAS,cAAA,CAAe,IAAA,EAAsB;AAC5C,EAA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A;AAG2C,EAAA;AACrC,IAAA;AACyB,MAAA;AACuD,MAAA;AAErC,MAAA;AAChB,QAAA;AAC4C,QAAA;AACzE,MAAA;AACM,IAAA;AAER,IAAA;AACF,EAAA;AAGkD,EAAA;AAC5C,IAAA;AACyB,MAAA;AAC0C,MAAA;AAEtC,MAAA;AACF,QAAA;AAC4C,QAAA;AACzE,MAAA;AACM,IAAA;AAER,IAAA;AACF,EAAA;AAOG,EAAA;AAEG,IAAA;AACyB,MAAA;AACqC,MAAA;AAC1D,IAAA;AAER,IAAA;AACF,EAAA;AAEO,EAAA;AACT;AAamB;AAjZnB,EAAA;AAmZyD,EAAA;AAElC,EAAA;AACF,IAAA;AACf,MAAA;AACA,MAAA;AACA,MAAA;AACA,MAAA;AACA,MAAA;AACiB,MAAA;AACA,MAAA;AACE,MAAA;AACX,MAAA;AACT,IAAA;AACH,EAAA;AAEuB,EAAA;AACyC,EAAA;AAExB,EAAA;AACK,EAAA;AACH,EAAA;AAC3B,EAAA;AACD,EAAA;AAE0C,EAAA;AAC3B,IAAA;AAEN,IAAA;AACnB,MAAA;AAC+C,MAAA;AACxC,MAAA;AAC2B,MAAA;AAC3B,MAAA;AACT,IAAA;AAC6C,IAAA;AACf,IAAA;AAEkD,IAAA;AAErB,IAAA;AAChC,IAAA;AAC7B,EAAA;AAG8D,EAAA;AAChE;AHyNyF;AACA;AACA;AACA;AACA;AACA","file":"/Users/hardik/GITHUB/sanity-plugin-seofields/npm/dist/chunk-3OK3S2F7.cjs","sourcesContent":[null,"export interface ReadabilityResult {\n score: number\n gradeLevel: number\n avgWordsPerSentence: number\n words: number\n sentences: number\n label: string\n color: 'green' | 'orange' | 'red'\n}\n\n/**\n * Count vowel groups in a single word (improved — no regex stripping hacks).\n * - Lowercase, strip non-alpha\n * - If <= 3 chars -> 1 syllable\n * - Count consecutive vowel groups ([aeiouy]+ matches)\n * - Special case: silent trailing 'e' after consonant -> subtract 1 syllable, min 1\n */\nfunction countSyllables(word: string): number {\n const w = word.toLowerCase().replace(/[^a-z]/g, '')\n if (w.length <= 3) return 1\n\n // Count consecutive vowel groups\n const groups = w.match(/[aeiouy]+/g) ?? []\n let count = groups.length\n\n // Special case: silent trailing 'e' after consonant -> subtract 1 syllable, min 1\n if (w.endsWith('e') && w.length > 1 && !/[aeiouy]/.test(w[w.length - 2])) {\n count = Math.max(1, count - 1)\n }\n\n return Math.max(1, count)\n}\n\n/**\n * Split text on sentence boundaries (., !, ?)\n */\nfunction countSentences(text: string): number {\n const matches = text.match(/[.!?]+/g)\n return matches ? matches.length : 1\n}\n\n/**\n * Compute Flesch Reading Ease and Flesch-Kincaid Grade Level.\n * Returns null if text has fewer than 10 words.\n *\n * Flesch Reading Ease: 206.835 - 1.015*(words/sentences) - 84.6*(syllables/words)\n * FK Grade Level: 0.39*(words/sentences) + 11.8*(syllables/words) - 15.59\n */\nexport function analyzeReadability(text: string): ReadabilityResult | null {\n const wordList = text.trim().split(/\\s+/).filter(Boolean)\n const words = wordList.length\n if (words < 10) return null\n\n const sentences = countSentences(text)\n const syllables = wordList.reduce((acc, word) => acc + countSyllables(word), 0)\n\n const rawScore = 206.835 - 1.015 * (words / sentences) - 84.6 * (syllables / words)\n const score = Math.round(rawScore * 10) / 10\n\n const rawGrade = 0.39 * (words / sentences) + 11.8 * (syllables / words) - 15.59\n const gradeLevel = Math.round(rawGrade * 10) / 10\n\n const avgWordsPerSentence = Math.round((words / sentences) * 10) / 10\n\n let label: string\n let color: 'green' | 'orange' | 'red'\n\n if (score >= 70) {\n label = 'Easy to read'\n color = 'green'\n } else if (score >= 50) {\n label = 'Fairly easy'\n color = 'green'\n } else if (score >= 30) {\n label = 'Moderately difficult'\n color = 'orange'\n } else {\n label = 'Difficult to read'\n color = 'red'\n }\n\n return {\n score,\n gradeLevel,\n avgWordsPerSentence,\n words,\n sentences,\n label,\n color,\n }\n}\n","import type {AiIndustry} from '../plugin'\n\nexport const FREE_INDUSTRIES = [\n 'blog',\n 'restaurant',\n 'travel',\n 'ecommerce',\n 'education',\n 'fitness',\n 'hospitality',\n 'nonprofit',\n] as const\nexport const PRO_INDUSTRIES = [\n 'healthcare',\n 'pharmacy',\n 'finance',\n 'realestate',\n 'saas',\n 'legal',\n 'insurance',\n 'automotive',\n 'homeServices',\n] as const\nconst PUBLIC_ANGLE_COUNT = 4\n\nexport type SeoGenField =\n | 'title'\n | 'description'\n | 'focusKeyword'\n | 'keywords'\n | 'ogTitle'\n | 'ogDescription'\n | 'twitterTitle'\n | 'twitterDescription'\n\nexport type MetaContext = {title?: string; description?: string; slug?: string}\n\ntype PromptParams = {content: string; keyword: string; keywords: string[]; meta?: MetaContext}\ntype PromptFn = (p: PromptParams) => string\ntype AngleFn = (params: PromptParams & {ctx: string}) => string\ntype FieldAngles = Record<SeoGenField, AngleFn[]>\ntype PublicIndustry = (typeof FREE_INDUSTRIES)[number]\ntype LicensedPromptPoolResolver = (options: {\n licenseKey?: string\n projectId?: string\n field: SeoGenField\n industry?: AiIndustry\n /** Free-tier pool — returned as-is when the license fails validation or the pro package is unavailable. */\n publicPrompts: PromptFn[]\n}) => Promise<PromptFn[]>\n\nconst GENERIC_CTX = 'Write for a general web audience.'\n\nfunction buildKeywordLine(\n keyword: string,\n keywords: string[],\n keywordRequirement: string,\n fallback: string,\n): string {\n if (keywords.length > 0) {\n return `- At least one of these keywords MUST appear verbatim: ${keywords.join(', ')}`\n }\n\n if (keyword) {\n return `- The keyword \"${keyword}\" MUST appear ${keywordRequirement}`\n }\n\n return fallback\n}\n\nconst PUBLIC_INDUSTRY_CONTEXTS = {\n blog: 'Write for a blog or editorial publication. Use engaging, informative language. Appeal to curious readers seeking knowledge.',\n ecommerce:\n 'Write for an e-commerce store. Use action-oriented language that drives purchases. Highlight value, deals, and product benefits.',\n education:\n 'Write for an educational platform or course provider. Use encouraging, growth-focused language. Emphasize skills, outcomes, and career impact.',\n restaurant:\n 'Write for a restaurant, cafe, or food business. Use sensory, appetizing language. Evoke taste, ambiance, and memorable dining experience.',\n travel:\n 'Write for a travel agency or tourism brand. Use evocative, inspiring language. Paint vivid pictures of destinations and unforgettable experiences.',\n fitness:\n 'Write for a gym, studio, or personal training brand. Use motivating, energetic language. Emphasize results, transformation, and community.',\n hospitality:\n 'Write for a hotel, resort, or short-term rental brand. Use welcoming, sensory language. Evoke comfort, amenities, and a memorable stay.',\n nonprofit:\n 'Write for a nonprofit or charitable organization. Use sincere, mission-driven language. Emphasize impact, community, and the cause over sales language.',\n} satisfies Record<PublicIndustry, string>\n\n// ─── Title angles ────────────────────────────────────────────────────────────\n\n// Only the 4 free-tier angles live here — the remaining 6 per field live in `seofields-pro`\n// and are never shipped in this package's bundle. See resolvePromptPool below.\nconst TITLE_ANGLES = [\n 'Lead with a strong action verb',\n 'Lead with the key benefit to the reader',\n 'Use a how-to format (How to …)',\n 'Use a question format that the reader wants answered',\n]\n\nconst titleFns: AngleFn[] = TITLE_ANGLES.map((angle) => ({content, keyword, keywords, ctx}) => {\n const kwLine = buildKeywordLine(\n keyword,\n keywords,\n 'verbatim in the title',\n '- Make it compelling and clear without a specific keyword',\n )\n return `You are an SEO expert. ${ctx}\nGenerate one SEO-optimized meta title using this angle: ${angle}.\nRequirements:\n- Strictly 50–60 characters including spaces and punctuation\n${kwLine}\n- Apply the angle — do not deviate\n- Return ONLY the title text. No quotes, no explanation.\n\nPage content:\n${content}`\n})\n\n// ─── Description angles ───────────────────────────────────────────────────────\n\nconst DESC_ANGLES = [\n \"Open with a direct answer to the reader's likely question, then add a clear call to action\",\n 'Open with the pain point the reader has, then offer the solution this page provides',\n 'Open with a bold claim, then briefly back it up',\n 'Open with who this is for, then state what they will get',\n]\n\nconst descFns: AngleFn[] = DESC_ANGLES.map((angle) => ({content, keyword, keywords, ctx}) => {\n const kwLine = buildKeywordLine(\n keyword,\n keywords,\n 'naturally in the description',\n '- Include a clear call to action',\n )\n return `You are an SEO expert. ${ctx}\nGenerate one SEO-optimized meta description using this angle: ${angle}.\nRequirements:\n- Strictly 120–160 characters including spaces and punctuation\n${kwLine}\n- Short sentences (under 15 words each), plain everyday words, no jargon — aim for high readability\n- Apply the angle — do not deviate\n- Return ONLY the description text. No quotes, no explanation.\n\nPage content:\n${content}`\n})\n\n// ─── OG Title angles ──────────────────────────────────────────────────────────\n\nconst OG_TITLE_ANGLES = [\n 'Curiosity hook — make the reader need to click to find out',\n 'FOMO angle — what they will miss if they do not read this',\n 'Social proof angle — imply consensus, popularity, or trust',\n 'Question angle — pose the exact question the audience is thinking',\n]\n\nconst ogTitleFns: AngleFn[] = OG_TITLE_ANGLES.map(\n (angle) =>\n ({content, keyword, ctx}) =>\n `You are a social media and SEO expert. ${ctx}\nGenerate one Open Graph title for social sharing using this angle: ${angle}.\nRequirements:\n- Strictly 40–60 characters\n- Optimized for social sharing engagement, not just search\n- Include the core topic clearly${keyword ? ` (topic: \"${keyword}\")` : ''}\n- Apply the angle above — do not deviate from it\n- Return ONLY the OG title text. No quotes, no explanation.\n\nPage content:\n${content}`,\n)\n\n// ─── OG Description angles ────────────────────────────────────────────────────\n\nconst OG_DESC_ANGLES = [\n 'Focus on what the reader gets — concrete takeaways or outcomes',\n 'Transformation promise — describe the before/after state',\n 'Bold claim backed by a brief piece of evidence or context',\n 'Pain relief framing — identify the problem and promise relief',\n]\n\nconst ogDescFns: AngleFn[] = OG_DESC_ANGLES.map(\n (angle) =>\n ({content, keyword, ctx}) =>\n `You are a social media and SEO expert. ${ctx}\nGenerate one Open Graph description for social sharing using this angle: ${angle}.\nRequirements:\n- Strictly 90–120 characters\n- Compelling enough to drive clicks from social feeds\n- Include the core topic naturally${keyword ? ` (topic: \"${keyword}\")` : ''}\n- Apply the angle above — do not deviate from it\n- Return ONLY the OG description text. No quotes, no explanation.\n\nPage content:\n${content}`,\n)\n\n// ─── Twitter Title angles ─────────────────────────────────────────────────────\n\nconst TW_TITLE_ANGLES = [\n 'Punchy curiosity hook — make the reader need to click',\n 'Direct FOMO — what they miss by scrolling past',\n 'Conversational question the audience is silently asking',\n 'Bold, scroll-stopping claim in plain language',\n]\n\nconst twTitleFns: AngleFn[] = TW_TITLE_ANGLES.map(\n (angle) =>\n ({content, keyword, ctx}) =>\n `You are a social media copywriter. ${ctx}\nGenerate one X (Twitter) card title using this angle: ${angle}.\nRequirements:\n- Strictly 30–70 characters\n- Punchy and direct — Twitter audiences scroll fast\n- Include the core topic naturally${keyword ? ` (topic: \"${keyword}\")` : ''}\n- Apply the angle above — do not deviate from it\n- Return ONLY the title text. No quotes, no explanation.\n\nPage content:\n${content}`,\n)\n\n// ─── Twitter Description angles ───────────────────────────────────────────────\n\nconst TW_DESC_ANGLES = [\n 'Conversational direct answer — what the page gives you',\n 'Pain-point opener followed by relief in one sentence',\n 'Bold hook followed by the core benefit',\n 'Short-form transformation promise',\n]\n\nconst twDescFns: AngleFn[] = TW_DESC_ANGLES.map(\n (angle) =>\n ({content, keyword, ctx}) =>\n `You are a social media copywriter. ${ctx}\nGenerate one X (Twitter) card description using this angle: ${angle}.\nRequirements:\n- Strictly 50–200 characters\n- Conversational and punchy — casual Twitter tone\n- Include the core topic naturally${keyword ? ` (topic: \"${keyword}\")` : ''}\n- Apply the angle above — do not deviate from it\n- Return ONLY the description text. No quotes, no explanation.\n\nPage content:\n${content}`,\n)\n\n// ─── Focus Keyword angles ─────────────────────────────────────────────────────\n\nconst FK_ANGLES = [\n 'Identify the single keyword phrase a user would most likely search to find this page',\n 'Identify the primary search intent keyword — what the reader types when looking for this content',\n 'Extract the most commercially or informationally valuable keyword from this content',\n 'Identify the exact phrase that best captures the core topic of this page',\n]\n\nconst fkFns: AngleFn[] = FK_ANGLES.map((angle) => ({content, meta, ctx}) => {\n const hasTitle = Boolean(meta?.title)\n const hasDescription = Boolean(meta?.description)\n const hasSlug = Boolean(meta?.slug)\n\n const metaBlock =\n hasTitle || hasDescription || hasSlug\n ? `\\nExisting page fields:\n${hasTitle ? `Meta title: \"${meta!.title}\"` : ''}\n${hasDescription ? `Meta description: \"${meta!.description}\"` : ''}\n${hasSlug ? `URL slug: \"${meta!.slug}\"` : ''}\n\nCRITICAL: The keyword you return MUST appear verbatim (exact match, case-insensitive) inside the meta title${hasDescription ? ' and meta description' : ''} above.\nDo NOT invent a new keyword — extract one that already exists in those fields.\n${hasSlug ? 'Prefer a phrase that also appears in the URL slug.' : ''}\n`\n : ''\n\n return `You are an SEO expert. ${ctx}\nTask: ${angle}.\n${metaBlock}\nRequirements:\n- Return ONLY the keyword or keyword phrase (1–4 words typically)\n- It MUST appear verbatim in the meta title${hasDescription ? ' and description' : ''} provided above\n- No explanation, no quotes, no punctuation, no extra words\n- Single line response\n\nPage content:\n${content}`\n})\n\n// ─── Keywords angles ──────────────────────────────────────────────────────────\n\nconst KW_ANGLES = [\n 'Generate 8 keywords mixing high-volume short-tail and specific long-tail phrases',\n 'Generate 8 keywords that cover both the main topic and closely related subtopics',\n 'Generate 8 keywords targeting both informational and commercial search intent',\n 'Generate 8 keywords including question-based phrases people would search',\n]\n\nconst kwFns: AngleFn[] = KW_ANGLES.map(\n (angle) =>\n ({content, keyword, ctx}) =>\n `You are an SEO expert. ${ctx}\n${angle}${keyword ? ` Include \"${keyword}\" as one of the keywords.` : ''}\nRequirements:\n- Return exactly 8 keywords as a comma-separated list\n- No numbering, no explanation, no quotes around individual keywords\n- Mix short-tail (1–2 words) and long-tail (3–5 words) phrases\n- All keywords must be directly relevant to the page content\n\nPage content:\n${content}`,\n)\n\n// ─── Angle map ────────────────────────────────────────────────────────────────\n\nconst BASE_ANGLES: FieldAngles = {\n title: titleFns,\n description: descFns,\n focusKeyword: fkFns,\n keywords: kwFns,\n ogTitle: ogTitleFns,\n ogDescription: ogDescFns,\n twitterTitle: twTitleFns,\n twitterDescription: twDescFns,\n}\n\nfunction buildFieldPrompts(ctx: string, count: number): Record<SeoGenField, PromptFn[]> {\n const out = {} as Record<SeoGenField, PromptFn[]>\n for (const field of Object.keys(BASE_ANGLES) as SeoGenField[]) {\n out[field] = BASE_ANGLES[field]\n .slice(0, count)\n .map((fn) => (p: PromptParams) => fn({...p, ctx}))\n }\n return out\n}\n\nexport const INDUSTRY_PROMPTS = Object.fromEntries(\n (Object.keys(PUBLIC_INDUSTRY_CONTEXTS) as PublicIndustry[]).map((industry) => [\n industry,\n buildFieldPrompts(PUBLIC_INDUSTRY_CONTEXTS[industry], PUBLIC_ANGLE_COUNT),\n ]),\n) as Record<PublicIndustry, Record<SeoGenField, PromptFn[]>>\n\nexport const DEFAULT_PROMPTS = buildFieldPrompts(GENERIC_CTX, PUBLIC_ANGLE_COUNT)\n\nasync function resolvePromptPool(\n field: SeoGenField,\n industry?: AiIndustry,\n licenseKey?: string,\n projectId?: string,\n): Promise<PromptFn[]> {\n const isFreeIndustry = Boolean(\n industry && (FREE_INDUSTRIES as readonly string[]).includes(industry),\n )\n const publicPrompts = isFreeIndustry\n ? INDUSTRY_PROMPTS[industry as PublicIndustry][field]\n : DEFAULT_PROMPTS[field]\n\n if (!licenseKey) return publicPrompts\n\n // The remaining angles (up to 10 total) live entirely in `seofields-pro` — never shipped in\n // this package's bundle — and are only returned once the license actually validates.\n try {\n const mod = (await import('seofields-pro')) as {\n resolveLicensedPromptPool?: LicensedPromptPoolResolver\n }\n // Pro package unavailable — an unverified licenseKey alone must never unlock the pool.\n if (typeof mod.resolveLicensedPromptPool !== 'function') return publicPrompts\n\n return mod.resolveLicensedPromptPool({\n licenseKey,\n projectId,\n field,\n industry,\n publicPrompts,\n })\n } catch {\n return publicPrompts\n }\n}\n\nexport async function pickPrompt(\n field: SeoGenField,\n params: PromptParams,\n industry?: AiIndustry,\n licenseKey?: string,\n projectId?: string,\n): Promise<string> {\n const pool = await resolvePromptPool(field, industry, licenseKey, projectId)\n const fn = pool[Math.floor(Math.random() * pool.length)]\n return fn(params)\n}\n\n// ─── Test mode static outputs ─────────────────────────────────────────────────\n\nexport const TEST_MODE_OUTPUTS: Record<SeoGenField, string[]> = {\n title: [\n 'Boost Your SEO Rankings With These Proven Tips',\n 'How to Write Meta Titles That Drive More Clicks',\n '10 Strategies to Improve Your Search Visibility',\n 'Why Your Meta Title Is Killing Your Click-Through Rate',\n ],\n description: [\n 'Learn how to write SEO-optimized meta titles that rank higher and earn more clicks. Discover the exact techniques used by top SEO professionals.',\n 'Struggling with low organic traffic? Our complete guide covers everything you need to fix your meta tags and climb the search rankings fast.',\n 'Meta titles under 60 characters get the best click-through rates. Find out how to craft compelling titles that rank and convert visitors.',\n 'This guide is for content creators and marketers who want to improve search rankings without technical expertise. Start seeing results today.',\n ],\n focusKeyword: [\n 'seo meta title',\n 'on-page seo',\n 'meta tag optimization',\n 'organic traffic growth',\n ],\n keywords: [\n 'seo tips, meta title optimization, on-page seo, search rankings, click-through rate, seo guide, organic traffic, meta description, keyword placement, seo best practices',\n 'meta tags, title tag optimization, serp optimization, seo ranking factors, page title seo, seo for beginners, improve search rankings, seo checklist, meta title length, seo tools',\n 'on-page optimization, meta tag guide, seo title tips, increase organic traffic, search visibility, seo writing, title tag examples, meta description length, content seo, seo strategy',\n 'seo optimization guide, meta title examples, serp click-through rate, google ranking tips, seo content writing, page title best practices, keyword in title, seo traffic, rank higher google, search engine results',\n ],\n ogTitle: [\n 'The SEO Secret That Tripled Our Organic Traffic',\n 'Are You Making These 5 Common Meta Title Mistakes?',\n 'This One Change Can Double Your Search Click-Through Rate',\n 'Why 90% of Meta Titles Fail to Drive Clicks',\n ],\n ogDescription: [\n 'Get the exact framework top SEO teams use to write meta titles that rank higher and earn more clicks from search results.',\n 'Before: low CTR and invisible search rankings. After: consistent page-one results. Here is how to make that shift with your meta tags.',\n 'Research shows properly optimized meta titles get 30% more clicks. We show you exactly how to achieve that in under 10 minutes.',\n 'If your page is not getting clicks from search results, your meta title is likely the problem. Here is how to diagnose and fix it.',\n ],\n twitterTitle: [\n 'The Meta Title Trick That Tripled Our Traffic',\n \"You're Probably Writing Meta Titles Wrong\",\n 'One Change That Doubles Your Click-Through Rate',\n 'Why Most Meta Titles Fail (And How to Fix Yours)',\n ],\n twitterDescription: [\n \"Most pages leave clicks on the table because of weak meta titles. Here's the fix — in under 10 minutes.\",\n \"Low search CTR? Your meta title is probably the culprit. Here's how to diagnose and fix it today.\",\n 'Optimized meta titles get 30% more clicks. This guide shows you exactly how to write one that works.',\n 'Stop writing generic meta titles. This thread-worthy guide gives you templates that rank and convert.',\n ],\n}\n\nexport function pickTestOutput(field: SeoGenField): string {\n const arr = TEST_MODE_OUTPUTS[field]\n return arr[Math.floor(Math.random() * arr.length)]\n}\n","import type {AiConfig, AiIndustry} from '../plugin'\nimport {analyzeReadability} from './readability'\nimport {type MetaContext, pickPrompt, type SeoGenField} from './seoPrompts'\n\nconst DEFAULT_MAX_RETRIES = 2\n\nconst PROVIDER_DEFAULTS: Record<string, {baseUrl: string; model: string; requiresKey: boolean}> = {\n openai: {baseUrl: 'https://api.openai.com/v1', model: 'gpt-4o-mini', requiresKey: true},\n anthropic: {\n baseUrl: 'https://api.anthropic.com',\n model: 'claude-haiku-4-5-20251001',\n requiresKey: true,\n },\n groq: {\n baseUrl: 'https://api.groq.com/openai/v1',\n model: 'llama-3.3-70b-versatile',\n requiresKey: true,\n },\n gemini: {\n baseUrl: 'https://generativelanguage.googleapis.com/v1beta/openai',\n model: 'gemini-2.0-flash',\n requiresKey: true,\n },\n ollama: {baseUrl: 'http://localhost:11434/v1', model: 'llama3.2', requiresKey: false},\n}\n\n// Must exactly match validation thresholds in seoUtils.ts\nconst FIELD_CONSTRAINTS: Partial<Record<SeoGenField, {min: number; max: number}>> = {\n title: {min: 50, max: 60},\n description: {min: 120, max: 160},\n ogTitle: {min: 40, max: 60},\n ogDescription: {min: 90, max: 120},\n twitterTitle: {min: 30, max: 70},\n twitterDescription: {min: 50, max: 200},\n}\n\nfunction parseApiError(status: number, body: unknown): string {\n const msg =\n (body as {error?: {message?: string}})?.error?.message ||\n (body as {message?: string})?.message ||\n ''\n if (status === 401)\n return `Authentication failed (401). Check your API key.${msg ? ` ${msg}` : ''}`\n if (status === 429)\n return `Rate limit reached (429). Wait a moment and try again.${msg ? ` ${msg}` : ''}`\n if (status >= 500)\n return `Provider server error (${status}). Try again shortly.${msg ? ` ${msg}` : ''}`\n return msg || `Request failed with status ${status}.`\n}\n\ninterface CallOpts {\n apiKey?: string\n model: string\n temperature: number\n}\n\nasync function callOpenAICompat(\n baseUrl: string,\n opts: CallOpts,\n prompt: string,\n signal: AbortSignal,\n): Promise<string> {\n const headers: Record<string, string> = {'Content-Type': 'application/json'}\n if (opts.apiKey) headers.Authorization = `Bearer ${opts.apiKey}`\n\n const res = await fetch(`${baseUrl}/chat/completions`, {\n method: 'POST',\n headers,\n signal,\n body: JSON.stringify({\n model: opts.model,\n messages: [{role: 'user', content: prompt}],\n /* eslint-disable camelcase */\n max_tokens: 300,\n /* eslint-enable camelcase */\n temperature: opts.temperature,\n }),\n })\n const data = await res.json()\n if (!res.ok) throw new Error(parseApiError(res.status, data))\n return ((data.choices?.[0]?.message?.content as string) || '').trim()\n}\n\nasync function callAnthropic(\n opts: CallOpts,\n apiKey: string,\n prompt: string,\n signal: AbortSignal,\n): Promise<string> {\n const res = await fetch('https://api.anthropic.com/v1/messages', {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'x-api-key': apiKey,\n 'anthropic-version': '2023-06-01',\n 'anthropic-dangerous-direct-browser-access': 'true',\n },\n signal,\n body: JSON.stringify({\n model: opts.model,\n /* eslint-disable camelcase */\n max_tokens: 300,\n /* eslint-enable camelcase */\n temperature: opts.temperature,\n messages: [{role: 'user', content: prompt}],\n }),\n })\n const data = await res.json()\n if (!res.ok) throw new Error(parseApiError(res.status, data))\n return ((data.content?.[0]?.text as string) || '').trim()\n}\n\ninterface ProxyRequest {\n field: SeoGenField\n content: string\n focusKeyword: string\n keywords: string[]\n meta: MetaContext | undefined\n endpoint: string\n industry: AiIndustry | undefined\n licenseKey: string | undefined\n signal: AbortSignal\n}\n\nasync function callProxy({\n field,\n content,\n focusKeyword,\n keywords,\n meta,\n endpoint,\n industry,\n licenseKey,\n signal,\n}: ProxyRequest): Promise<string> {\n const res = await fetch(endpoint, {\n method: 'POST',\n headers: {'Content-Type': 'application/json'},\n signal,\n body: JSON.stringify({field, content, focusKeyword, keywords, meta, industry, licenseKey}),\n })\n const data = await res.json()\n if (!res.ok) throw new Error(parseApiError(res.status, data))\n const result = (data as {result?: string}).result\n if (!result) throw new Error('Proxy response missing \"result\" field.')\n return result.trim()\n}\n\n// Strip surrounding quotes that models sometimes add despite instructions\nfunction stripQuotes(text: string): string {\n return text.replace(/^[\"'\"\"]|[\"'\"\"]$/g, '').trim()\n}\n\n// Targeted fix: model sees the exact text + what's wrong — far more reliable than blind regeneration\nasync function refineLength(\n field: SeoGenField,\n raw: string,\n constraint: {min: number; max: number},\n callApi: (prompt: string) => Promise<string>,\n): Promise<string> {\n const len = raw.length\n const isTooShort = len < constraint.min\n const action = isTooShort ? 'Expand' : 'Shorten'\n const issue = isTooShort\n ? `too short at ${len} characters (minimum is ${constraint.min})`\n : `too long at ${len} characters (maximum is ${constraint.max})`\n\n const prompt = `This SEO ${field} is ${issue}. Target range: ${constraint.min}–${constraint.max} characters.\n${action} it to fit within that range. Preserve the meaning and any keywords present.\nCount every character carefully before outputting. The final text MUST be ${constraint.min}–${constraint.max} chars.\nCurrent text (${len} chars): \"${raw}\"\nReturn ONLY the rewritten text. No quotes, no labels, no character count.`\n\n return callApi(prompt)\n}\n\n// Targeted fix: insert the missing keyword while keeping length in range\nasync function refineKeyword(\n field: SeoGenField,\n raw: string,\n keywords: string[],\n constraint: {min: number; max: number} | undefined,\n callApi: (prompt: string) => Promise<string>,\n): Promise<string> {\n const kwList = keywords.join(', ')\n const rangeNote = constraint\n ? ` The final text MUST be ${constraint.min}–${constraint.max} characters.`\n : ''\n\n const prompt = `This SEO ${field} is missing a required keyword.\nRewrite it to include at least one of these keywords naturally: ${kwList}.${rangeNote}\nDo not force the keyword awkwardly — weave it in as if it was always there.\nCurrent text: \"${raw}\"\nReturn ONLY the rewritten text. No quotes, no labels, no explanation.`\n\n return callApi(prompt)\n}\n\n// Targeted fix: pick a keyword that actually exists verbatim in the existing title/description\nasync function refineFocusKeyword(\n raw: string,\n meta: MetaContext,\n callApi: (prompt: string) => Promise<string>,\n): Promise<string> {\n const missing: string[] = []\n const kw = raw.toLowerCase().trim()\n if (meta.title && !meta.title.toLowerCase().includes(kw))\n missing.push(`meta title: \"${meta.title}\"`)\n if (meta.description && !meta.description.toLowerCase().includes(kw))\n missing.push(`meta description: \"${meta.description}\"`)\n\n const prompt = `The focus keyword \"${raw}\" does not appear verbatim in the following existing page fields:\n${missing.join('\\n')}\n\nExtract a keyword or phrase (1–4 words) that appears VERBATIM in those fields.\nDo not invent a new keyword — only return a phrase already present in the text above.\n${meta.slug ? `URL slug: \"${meta.slug}\" — prefer a phrase that also matches part of this.` : ''}\n\nReturn ONLY the keyword. No quotes, no explanation, no punctuation. Single line.`\n\n return callApi(prompt)\n}\n\n// Targeted fix: simplify language to improve readability score\nasync function refineReadability(\n raw: string,\n constraint: {min: number; max: number},\n callApi: (prompt: string) => Promise<string>,\n): Promise<string> {\n const prompt = `This SEO meta description uses language that is too complex.\nRewrite it so it reads simply and clearly:\n- Use short sentences (under 15 words each)\n- Use common everyday words — no jargon or passive voice\n- Keep the same core meaning and any keywords present\n- The final text MUST be ${constraint.min}–${constraint.max} characters\nCurrent text: \"${raw}\"\nReturn ONLY the rewritten text. No quotes, no labels, no explanation.`\n\n return callApi(prompt)\n}\n\nfunction checkLength(field: SeoGenField, text: string): boolean {\n const constraint = FIELD_CONSTRAINTS[field]\n if (!constraint) return true\n return text.length >= constraint.min && text.length <= constraint.max\n}\n\nfunction checkKeywords(field: SeoGenField, text: string, keywords: string[]): boolean {\n if ((field === 'title' || field === 'description') && keywords.length > 0) {\n const lower = text.toLowerCase()\n return keywords.some((kw) => lower.includes(kw.toLowerCase().trim()))\n }\n return true\n}\n\nfunction checkReadability(field: SeoGenField, text: string): boolean {\n if (field === 'description') {\n const readability = analyzeReadability(text)\n return !readability || readability.score >= 50\n }\n return true\n}\n\nfunction checkFocusKeywordInMeta(kw: string, meta: MetaContext): boolean {\n const lower = kw.toLowerCase().trim()\n if (meta.title && !meta.title.toLowerCase().includes(lower)) return false\n if (meta.description && !meta.description.toLowerCase().includes(lower)) return false\n return true\n}\n\nfunction validateOutput(\n field: SeoGenField,\n text: string,\n keywords: string[],\n meta?: MetaContext,\n): string | null {\n if (!checkLength(field, text)) return null\n if (!checkKeywords(field, text, keywords)) return null\n if (!checkReadability(field, text)) return null\n if (field === 'focusKeyword' && meta && (meta.title || meta.description)) {\n if (!checkFocusKeywordInMeta(text, meta)) return null\n }\n return text\n}\n\nfunction warnIfKeyExposed(config: AiConfig): void {\n if (config.apiKey && typeof window !== 'undefined') {\n console.warn(\n '[sanity-plugin-seofields] \"apiKey\" is bundled into the Studio\\'s client-side JS and is readable by ' +\n 'anyone with Studio access. Use \"endpoint\" with a server-side proxy instead — see ' +\n '\"sanity-plugin-seofields/server\" for ready-made handlers.',\n )\n }\n}\n\nfunction buildCallApi(\n config: AiConfig,\n temperature: number,\n abortSignal: AbortSignal,\n): (prompt: string) => Promise<string> {\n const provider = config.provider ?? 'openai'\n const providerDef = PROVIDER_DEFAULTS[provider]\n if (!providerDef) throw new Error(`Unknown provider \"${provider}\".`)\n if (providerDef.requiresKey && !config.apiKey) {\n throw new Error(`No API key configured for \"${provider}\". Add apiKey to your ai plugin config.`)\n }\n\n const baseUrl = config.baseUrl ?? providerDef.baseUrl\n const model = config.model ?? providerDef.model\n const opts: CallOpts = {apiKey: config.apiKey, model, temperature}\n\n const useAnthropic = provider === 'anthropic' && !config.baseUrl\n return (prompt: string) =>\n useAnthropic\n ? callAnthropic(opts, config.apiKey!, prompt, abortSignal)\n : callOpenAICompat(baseUrl, opts, prompt, abortSignal)\n}\n\ninterface RefinementCtx {\n field: SeoGenField\n keywords: string[]\n meta: MetaContext | undefined\n constraint: {min: number; max: number} | undefined\n callApi: (prompt: string) => Promise<string>\n abortSignal: AbortSignal\n}\n\n// Runs passes 1-4 against a single raw response, tolerating errors/aborts by keeping the prior text.\nasync function refineRawText(raw: string, ctx: RefinementCtx): Promise<string> {\n const {field, keywords, meta, constraint, callApi, abortSignal} = ctx\n let text = raw\n\n // Pass 1 — fix length if wrong\n if (constraint && !checkLength(field, text)) {\n try {\n abortSignal.throwIfAborted()\n text = stripQuotes(await refineLength(field, text, constraint, callApi))\n } catch {\n // aborted or errored — continue with what we have\n }\n }\n\n // Pass 2 — inject missing keyword if required (title/description fields)\n if (!checkKeywords(field, text, keywords)) {\n try {\n abortSignal.throwIfAborted()\n text = stripQuotes(await refineKeyword(field, text, keywords, constraint, callApi))\n // re-fix length after keyword injection since it may have shifted\n if (constraint && !checkLength(field, text)) {\n abortSignal.throwIfAborted()\n text = stripQuotes(await refineLength(field, text, constraint, callApi))\n }\n } catch {\n // aborted or errored — continue with what we have\n }\n }\n\n // Pass 3 — simplify for readability (description only)\n if (!checkReadability(field, text) && constraint) {\n try {\n abortSignal.throwIfAborted()\n text = stripQuotes(await refineReadability(text, constraint, callApi))\n // re-fix length after rewrite\n if (!checkLength(field, text)) {\n abortSignal.throwIfAborted()\n text = stripQuotes(await refineLength(field, text, constraint, callApi))\n }\n } catch {\n // aborted or errored — continue with what we have\n }\n }\n\n // Pass 4 — ensure focus keyword exists verbatim in existing title + description\n if (\n field === 'focusKeyword' &&\n meta &&\n (meta.title || meta.description) &&\n !checkFocusKeywordInMeta(text, meta)\n ) {\n try {\n abortSignal.throwIfAborted()\n text = stripQuotes(await refineFocusKeyword(text, meta, callApi))\n } catch {\n // aborted or errored — continue with what we have\n }\n }\n\n return text\n}\n\nexport interface GenerateOpts {\n config: AiConfig\n signal?: AbortSignal\n meta?: MetaContext\n}\n\nexport async function generateSeoText(\n field: SeoGenField,\n content: string,\n focusKeyword: string,\n keywords: string[],\n {config, signal, meta}: GenerateOpts,\n): Promise<string> {\n const abortSignal = signal ?? AbortSignal.timeout(15000)\n\n if (config.endpoint) {\n return callProxy({\n field,\n content,\n focusKeyword,\n keywords,\n meta,\n endpoint: config.endpoint,\n industry: config.industry,\n licenseKey: config._licenseKey,\n signal: abortSignal,\n })\n }\n\n warnIfKeyExposed(config)\n const callApi = buildCallApi(config, config.temperature ?? 0.7, abortSignal)\n\n const maxRetries = config.maxRetries ?? DEFAULT_MAX_RETRIES\n const isLicensed = Boolean(config._licenseKey)\n const constraint = FIELD_CONSTRAINTS[field]\n let firstRaw = ''\n let lastRaw = ''\n\n for (let attempt = 0; attempt <= maxRetries; attempt++) {\n abortSignal.throwIfAborted()\n\n const prompt = await pickPrompt(\n field,\n {content, keyword: focusKeyword, keywords, meta},\n config.industry,\n isLicensed ? config._licenseKey : undefined,\n config._projectId,\n )\n const raw = stripQuotes(await callApi(prompt))\n if (attempt === 0) firstRaw = raw\n\n lastRaw = await refineRawText(raw, {field, keywords, meta, constraint, callApi, abortSignal})\n\n const valid = validateOutput(field, lastRaw, keywords, meta)\n if (valid !== null) return valid\n }\n\n // All attempts exhausted — true = keep first response, false/undefined = keep last\n return config.keepFirstOnValidationFail === true ? firstRaw : lastRaw\n}\n"]}
|