kenobi-pages 0.1.17 → 0.1.18

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/bin/cli.mjs +15 -15
  2. package/package.json +1 -1
package/bin/cli.mjs CHANGED
@@ -1,23 +1,23 @@
1
1
  #!/usr/bin/env node
2
- var Oe=Object.defineProperty;var r=(t,e)=>Oe(t,"name",{value:e,configurable:!0});var k=class extends Error{static{r(this,"CliError")}exitCode;payload;constructor(e,n=1){super(e.message),this.name="CliError",this.exitCode=n,this.payload={ok:!1,...e}}},d=r((t,e)=>new k({status:null,code:"invalid_usage",message:t,details:e},2),"usageError"),C=r((t,e)=>new k({status:404,code:"not_found",message:t,details:e},3),"notFoundError"),p=r((t,e,n)=>{if(!t)throw d(e,n);return t},"assertArg"),l=r(t=>{console.log(JSON.stringify(t,null,2))},"printJson"),Z=r(t=>{console.error(JSON.stringify(t,null,2))},"writeError"),X=r(t=>{t instanceof k&&(Z(t.payload),process.exit(t.exitCode));let e=t instanceof Error?t.message:"Unknown error";Z({ok:!1,status:null,code:"runtime_error",message:e}),process.exit(1)},"handleCliError");var g=r((t,e)=>{let n=t.indexOf(e);return n!==-1?t[n+1]:void 0},"parseFlag"),m=r((t,e)=>t.includes(e),"hasFlag"),f=r((t,e,n)=>{let s=g(t,e);if(!s||s.startsWith("--"))throw d(n);return s},"parseRequiredFlag"),W=r((t,e)=>{let n=g(t,e);if(n===void 0)return;let s=Number(n);if(!Number.isInteger(s)||s<=0)throw d(`${e} must be a positive integer`);return s},"parseOptionalPositiveIntFlag"),M=r((t,e)=>{let n=g(t,e);if(n===void 0)return;let s=Number(n);if(!Number.isInteger(s)||s<0)throw d(`${e} must be a non-negative integer`);return s},"parseOptionalNonNegativeIntFlag");import{appendFileSync as Pe,existsSync as B,readFileSync as H,writeFileSync as ee}from"node:fs";import{resolve as te}from"node:path";var Te="https://kenobi.ai",w="KENOBI_PAGES_KEY",ne=[".env.local",".env",".env.development",".env.development.local"],Ce=r(()=>{let t={},e=process.cwd();for(let n of ne){let s=te(e,n);if(!B(s))continue;let o=H(s,"utf-8");for(let i of o.split(`
3
- `)){let c=i.trim();if(!c||c.startsWith("#"))continue;let a=c.match(/^([A-Z_][A-Z0-9_]*)=["']?([^"']*)["']?$/);a&&(t[a[1]]??=a[2])}}return t},"loadEnvFromCwd"),L=null,R=r(t=>process.env[t]?process.env[t]:(L??=Ce(),L[t]),"getEnvVar"),je=r(()=>{L=null},"resetEnvCache"),v=r(()=>(R("KENOBI_BASE_URL")??Te).replace(/\/+$/,""),"getBaseUrl"),se=r(()=>{let t=R(w);if(t)return t;throw new k({status:null,code:"missing_api_key",message:`No API key found. Run 'npx kenobi-pages init' or set ${w}.`},4)},"getApiKey"),oe=r(()=>R(w),"getApiKeyOptional"),U=r(()=>{let t=process.cwd();return ne.filter(e=>B(te(t,e)))},"discoverEnvFiles"),re=r((t,e,n)=>{let s=H(t,"utf-8");if(s.includes(e)){console.error(` ${e} already present in ${t.split("/").pop()}`);return}let o=s.endsWith(`
2
+ var Ce=Object.defineProperty;var r=(e,t)=>Ce(e,"name",{value:t,configurable:!0});var y=class extends Error{static{r(this,"CliError")}exitCode;payload;constructor(t,n=1){super(t.message),this.name="CliError",this.exitCode=n,this.payload={ok:!1,...t}}},d=r((e,t)=>new y({status:null,code:"invalid_usage",message:e,details:t},2),"usageError"),C=r((e,t)=>new y({status:404,code:"not_found",message:e,details:t},3),"notFoundError"),p=r((e,t,n)=>{if(!e)throw d(t,n);return e},"assertArg"),l=r(e=>{console.log(JSON.stringify(e,null,2))},"printJson"),te=r(e=>{console.error(JSON.stringify(e,null,2))},"writeError"),ne=r(e=>{e instanceof y&&(te(e.payload),process.exit(e.exitCode));let t=e instanceof Error?e.message:"Unknown error";te({ok:!1,status:null,code:"runtime_error",message:t}),process.exit(1)},"handleCliError");var g=r((e,t)=>{let n=e.indexOf(t);return n!==-1?e[n+1]:void 0},"parseFlag"),w=r((e,t)=>e.includes(t),"hasFlag"),f=r((e,t,n)=>{let o=g(e,t);if(!o||o.startsWith("--"))throw d(n);return o},"parseRequiredFlag"),L=r((e,t)=>{let n=g(e,t);if(n===void 0)return;let o=Number(n);if(!Number.isInteger(o)||o<=0)throw d(`${t} must be a positive integer`);return o},"parseOptionalPositiveIntFlag"),B=r((e,t)=>{let n=g(e,t);if(n===void 0)return;let o=Number(n);if(!Number.isInteger(o)||o<0)throw d(`${t} must be a non-negative integer`);return o},"parseOptionalNonNegativeIntFlag");import{appendFileSync as je,existsSync as G,readFileSync as V,writeFileSync as oe}from"node:fs";import{resolve as se}from"node:path";var Ae="https://kenobi.ai",h="KENOBI_PAGES_KEY",re=[".env.local",".env",".env.development",".env.development.local"],Ne=r(()=>{let e={},t=process.cwd();for(let n of re){let o=se(t,n);if(!G(o))continue;let s=V(o,"utf-8");for(let i of s.split(`
3
+ `)){let c=i.trim();if(!c||c.startsWith("#"))continue;let a=c.match(/^([A-Z_][A-Z0-9_]*)=["']?([^"']*)["']?$/);a&&(e[a[1]]??=a[2])}}return e},"loadEnvFromCwd"),H=null,R=r(e=>process.env[e]?process.env[e]:(H??=Ne(),H[e]),"getEnvVar"),Ke=r(()=>{H=null},"resetEnvCache"),S=r(()=>(R("KENOBI_BASE_URL")??Ae).replace(/\/+$/,""),"getBaseUrl"),ie=r(()=>{let e=R(h);if(e)return e;throw new y({status:null,code:"missing_api_key",message:`No API key found. Run 'npx kenobi-pages init' or set ${h}.`},4)},"getApiKey"),ae=r(()=>R(h),"getApiKeyOptional"),U=r(()=>{let e=process.cwd();return re.filter(t=>G(se(e,t)))},"discoverEnvFiles"),ce=r((e,t,n)=>{let o=V(e,"utf-8");if(o.includes(t)){console.error(` ${t} already present in ${e.split("/").pop()}`);return}let s=o.endsWith(`
4
4
  `)?"":`
5
- `;Pe(t,`${o}${e}="${n}"
6
- `),console.error(` Added ${e} to ${t.split("/").pop()}`)},"appendEnvVar"),j=r((t,e,n)=>{ee(t,`${e}="${n}"
7
- `)},"writeEnvFile"),G=r((t,e,n)=>{let s=B(t)?H(t,"utf-8"):"",o=`${e}="${n}"`,i=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),c=new RegExp(`^${i}=.*$`,"m"),a=c.test(s)?s.replace(c,o):`${s}${s.length>0&&!s.endsWith(`
5
+ `;je(e,`${s}${t}="${n}"
6
+ `),console.error(` Added ${t} to ${e.split("/").pop()}`)},"appendEnvVar"),j=r((e,t,n)=>{oe(e,`${t}="${n}"
7
+ `)},"writeEnvFile"),q=r((e,t,n)=>{let o=G(e)?V(e,"utf-8"):"",s=`${t}="${n}"`,i=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),c=new RegExp(`^${i}=.*$`,"m"),a=c.test(o)?o.replace(c,s):`${o}${o.length>0&&!o.endsWith(`
8
8
  `)?`
9
- `:""}${o}
10
- `;ee(t,a),je()},"upsertEnvVar");var Ae=r(async t=>{let e=await t.text().catch(()=>"");if(!e)return null;try{return JSON.parse(e)}catch{return e}},"parseErrorBody"),Ke=r(t=>{if(typeof t=="string")return t;if(typeof t=="object"&&t!==null&&"error"in t){let e=t.error;return typeof e=="string"?e:JSON.stringify(e)}return"Kenobi API request failed"},"errorMessageFromBody"),_e=r(t=>t===401||t===403?4:t===404?3:1,"exitCodeForStatus"),u=r(async(t,e={})=>{let n=await fetch(`${v()}${t}`,{method:e.method??"GET",headers:{"x-kenobi-key":se(),"Content-Type":"application/json"},body:e.body?JSON.stringify(e.body):void 0});if(n.ok)return await n.json();let s=await Ae(n);throw new k({status:n.status,code:n.status===401||n.status===403?"unauthorized":"api_error",message:Ke(s),details:s},_e(n.status))},"fetchKenobi"),$=r(t=>{let e=new URLSearchParams;for(let[n,s]of Object.entries(t))s!==void 0&&e.set(n,s);return e.toString()},"buildQuery");var I=r(t=>Object.keys(t??{}),"keys"),ie=r(t=>{let e=t.packJson??null,n=e?.tokens??{},s=e?.surfaces??{},o=e?.typography??{},i=e?.accents??{};return{designPack:{id:t.id,status:t.status,hostDomain:e?.hostDomain??t.hostDomain??null,raw:e},templateGuidance:{brandSummary:e?.compositionDescription??"Use the raw design pack tokens and recipes as the source of truth.",tokens:{color:n.color??{},font:n.font??{},radius:n.radius??{},container:n.container??{},section:n.section??{}},surfaces:s,typography:o,accents:i,use:["Use color, font, radius, spacing, surface, and typography recipes from this design pack before inventing new styles.","Preserve the source site's visual rhythm, density, button treatment, and section composition.","Keep the template source self-contained and accept all dynamic values through the Template content prop."],avoid:["Do not use generic SaaS gradients, decorative orbs, or unrelated stock-style visuals.","Do not introduce a new palette when the design pack already contains brand colors.","Do not hard-code personalized copy that should come from the content schema."],availableRecipes:{colors:I(n.color),fonts:I(n.font),radii:I(n.radius),surfaces:I(s),typography:I(o),accents:I(i)}}}},"exportDesignPackForAgent");var De=new Set(["COMPLETED","FAILED","CANCELED","SYSTEM_FAILURE","CRASHED"]),Ne=r(t=>new Promise(e=>setTimeout(e,t)),"sleep"),Je=r(async(t,e)=>{let n=2e3,s=15e3;for(;;){await Ne(n);let o=await u(`/api/v1/pages/evidence-bundles/${t}/design-packs/runs/${e}`),i=typeof o.status=="string"?o.status:"UNKNOWN";if(console.error(`Status: ${i}`),De.has(i)){l(o),i!=="COMPLETED"&&process.exit(1);return}n=Math.min(n*1.5,s)}},"pollDesignPack"),ae=r(async t=>{let[e,...n]=t,s=n[0];if(e==="list"){p(s,"Usage: kenobi-pages design-pack list <bundleId>"),l(await u(`/api/v1/pages/evidence-bundles/${s}/design-packs`));return}if(e==="generate"){p(s,"Usage: kenobi-pages design-pack generate <bundleId> [--wait]");let o=await u(`/api/v1/pages/evidence-bundles/${s}/design-packs`,{method:"POST",body:m(n.slice(1),"--dry-run")?{dryRun:!0}:{}});if(m(n.slice(1),"--dry-run")){l(o);return}if(!m(n.slice(1),"--wait")){l(o);return}let i=typeof o.taskId=="string"?o.taskId:void 0;if(!i){l(o);return}console.error(`Design pack generation queued: ${i}`),await Je(s,i);return}if(e==="status"){let o=p(n[1],"Usage: kenobi-pages design-pack status <bundleId> <taskId>");p(s,"Usage: kenobi-pages design-pack status <bundleId> <taskId>"),l(await u(`/api/v1/pages/evidence-bundles/${s}/design-packs/runs/${o}`));return}if(e==="get"){let o=p(n[1],"Usage: kenobi-pages design-pack get <bundleId> <designPackId>");p(s,"Usage: kenobi-pages design-pack get <bundleId> <designPackId>"),l(await u(`/api/v1/pages/evidence-bundles/${s}/design-packs/${o}`));return}if(e==="export"){let o=p(n[1],"Usage: kenobi-pages design-pack export <bundleId> <designPackId>");p(s,"Usage: kenobi-pages design-pack export <bundleId> <designPackId>");let i=await u(`/api/v1/pages/evidence-bundles/${s}/design-packs/${o}`);l(ie(i.designPack??{}));return}throw d(`Unknown design-pack command: ${t.join(" ")}`)},"handleDesignPack");import{existsSync as We,readFileSync as Me}from"node:fs";import{dirname as ce,join as Le}from"node:path";import{fileURLToPath as Be}from"node:url";var He=r(()=>{let t=ce(Be(import.meta.url));for(let e=0;e<6;e+=1){let n=Le(t,"package.json");if(We(n))try{let s=JSON.parse(Me(n,"utf-8"));if(s.name==="kenobi-pages"&&s.version)return s.version}catch{return"unknown"}t=ce(t)}return"unknown"},"findPackageVersion"),le=He();var Ge=r(async t=>{try{let e=await fetch(`${v()}/api/v1/cortex/sources`,{headers:{"x-kenobi-key":t,"Content-Type":"application/json"}});if(!e.ok)return{auth:{ok:!1,status:e.status},sources:{count:null}};let n=await e.json();return{auth:{ok:!0,status:e.status},sources:{count:Array.isArray(n.sources)?n.sources.length:0}}}catch(e){return{auth:{ok:!1,status:null,error:e instanceof Error?e.message:"Unknown error"},sources:{count:null}}}},"authCheck"),ue=r(async()=>{let t=oe(),e=U(),n=t?await Ge(t):{auth:{ok:!1,status:null,skipped:!0},sources:{count:null}},s=[];t?n.auth.ok||s.push("Check that the Kenobi API key is valid for this org."):s.push(`Run 'kenobi-pages init' or set ${w}.`),t&&n.auth.ok&&n.sources.count===0&&s.push("Connect at least one source in Kenobi before building data-backed workflows."),l({ok:!!(t&&n.auth.ok),cli:{version:le},env:{hasApiKey:!!t,apiKeyEnvVar:w,baseUrl:v(),envFiles:e},auth:n.auth,sources:n.sources,nextSteps:s})},"handleDoctor");import{readFile as pe}from"node:fs/promises";var de=r(()=>new Promise((t,e)=>{if(process.stdin.isTTY){t("");return}let n="";process.stdin.setEncoding("utf-8"),process.stdin.on("data",s=>{n+=s}),process.stdin.on("end",()=>t(n)),process.stdin.on("error",e)}),"readStdin"),y=r((t,e)=>{try{return JSON.parse(t)}catch{throw d(`Invalid JSON for ${e}`)}},"parseJson"),x=r(async(t,e)=>y(await pe(t,"utf-8"),e),"readJsonFile"),F=r(async(t,e)=>{if(!t){let n=await de();if(!n.trim())throw d(`Missing ${e}`);return y(n,e)}if(t==="-"){let n=await de();if(!n.trim())throw d(`Missing ${e} on stdin`);return y(n,e)}return t.trim().startsWith("{")||t.trim().startsWith("[")?y(t,e):x(t,e)},"readJsonSource"),O=r(async(t,e="JSON")=>{let n=g(t,"--file");if(n)return x(n,e);let s=t.find(o=>o.trim().startsWith("{")||o.trim().startsWith("["));return F(s,e)},"readJsonInput"),ge=r(async(t,e,n)=>{let s=g(t,e);if(s!==void 0)return F(s,n)},"readJsonFlag"),A=r(async(t,e,n)=>F(g(t,e),n),"readRequiredJsonFlag"),fe=r(async(t,e,n)=>{let s=g(t,e);if(!s||s.startsWith("--"))throw d(`Missing ${n}`);return pe(s,"utf-8")},"readTextFileFlag");var Ve=r((t,e)=>{let n={url:t},s=g(e,"--viewport"),o=g(e,"--headers"),i=g(e,"--wait-for-selector"),c=M(e,"--wait-timeout"),a=g(e,"--wait-until"),h=M(e,"--extra-wait-ms");return s&&(n.viewport=y(s,"--viewport")),o&&(n.headers=y(o,"--headers")),i&&(n.waitForSelector=i),c!==void 0&&(n.waitTimeout=c),a&&(n.waitUntil=a.trim().startsWith("[")?y(a,"--wait-until"):a),h!==void 0&&(n.extraWaitMs=h),m(e,"--block-annoyances")&&(n.blockAnnoyances=!0),m(e,"--dry-run")&&(n.dryRun=!0),n},"createEvidenceBody"),me=r(async t=>{let[e,...n]=t;if(e==="list"){l(await u("/api/v1/pages/evidence-bundles"));return}if(e==="create"){let s=p(n[0],"Usage: kenobi-pages evidence create <url> [flags]");l(await u("/api/v1/pages/evidence-bundles",{method:"POST",body:Ve(s,n.slice(1))}));return}if(e==="get"){let s=p(n[0],"Usage: kenobi-pages evidence get <bundleId>");l(await u(`/api/v1/pages/evidence-bundles/${s}`));return}throw d(`Unknown evidence command: ${t.join(" ")}`)},"handleEvidence");var qe="kenobi.page",Ye=r(t=>(t??qe).replace(/^https?:\/\//,"").replace(/\/+$/,"").toLowerCase(),"normalizeHostedDomain"),ze=r(()=>Ye(R("KENOBI_PAGES_HOSTED_DOMAIN")),"getHostedPagesDomain"),E=r(({siteSlug:t,templateSlug:e,itemSlug:n})=>`https://${t}.${ze()}/${e}/${n}`,"buildHostedPublicUrl"),we=r((t,e)=>{if(typeof t!="object"||t===null)return t;let n=t,s=typeof n.siteSlug=="string"?n.siteSlug:e?.siteSlug,o=typeof n.templateSlug=="string"?n.templateSlug:e?.templateSlug,i=typeof n.itemSlug=="string"?n.itemSlug:e?.itemSlug;return!s||!o||!i?t:{...t,publicUrl:E({siteSlug:s,templateSlug:o,itemSlug:i})}},"maybeDecorateHostedContent"),V=r((t,e)=>({...t,publicUrl:E(e)}),"decorateHostedContentResponse");var he=r(async t=>{let e=f(t,"--template-slug","Usage: kenobi-pages hosted draft save --template-slug <slug> --template-name <name> --source <tsx-file> --schema <json-file> --content <json-file>"),n=f(t,"--template-name","Usage: kenobi-pages hosted draft save --template-slug <slug> --template-name <name> --source <tsx-file> --schema <json-file> --content <json-file>"),s=await fe(t,"--source","--source <tsx-file>"),o=f(t,"--schema","Missing --schema <json-file>"),i=f(t,"--content","Missing --content <json-file>"),c=W(t,"--design-pack-id"),a=g(t,"--site-slug"),h=g(t,"--site-name"),b={templateSlug:e,templateName:n,sourceTsx:s,contentSchema:{title:n,schemaJson:await x(o,"--schema")},defaultContentJson:await x(i,"--content"),setCurrentDraft:!m(t,"--no-current-draft")};return c!==void 0&&(b.designPackId=c),a&&(b.site={slug:a,...h?{name:h}:{}}),b},"parseHostedDraftBody"),ke=r(t=>{let e=typeof t.previewPath=="string"?t.previewPath:null;return{...t,...e?{previewUrl:`${v()}${e}`}:{}}},"withPreviewUrl"),Qe=r(async t=>{let[e,...n]=t;if(e==="list"){l(await u("/api/v1/pages/hosted/sites"));return}if(e==="get"){let s=p(n[0],"Usage: kenobi-pages hosted site get <siteSlug>");l(await u(`/api/v1/pages/hosted/sites?${$({slug:s})}`));return}throw d(`Unknown hosted site command: ${t.join(" ")}`)},"handleHostedSite"),Ze=r(async t=>{let[e,...n]=t;if(e==="list"){let s=$({full:m(n,"--full")?"true":void 0});l(await u(`/api/v1/pages/hosted/templates${s?`?${s}`:""}`));return}if(e==="get"){let s=p(n[0],"Usage: kenobi-pages hosted template get <templateIdOrSlug> [--full]"),o=$({full:m(n.slice(1),"--full")?"true":void 0});l(await u(`/api/v1/pages/hosted/templates/${s}${o?`?${o}`:""}`));return}throw d(`Unknown hosted template command: ${t.join(" ")}`)},"handleHostedTemplate"),Xe=r(async t=>{let[e,...n]=t;if(e==="list"){let s=p(n[0],"Usage: kenobi-pages hosted publication list <templateIdOrSlug>");l(await u(`/api/v1/pages/hosted/templates/${s}/publications`));return}if(e==="get"){let s=p(n[0],"Usage: kenobi-pages hosted publication get <templateIdOrSlug> <publicationId>"),o=p(n[1],"Usage: kenobi-pages hosted publication get <templateIdOrSlug> <publicationId>");l(await u(`/api/v1/pages/hosted/templates/${s}/publications/${o}`));return}throw d(`Unknown hosted publication command: ${t.join(" ")}`)},"handleHostedPublication"),et=r(async t=>{let[e,...n]=t;if(e==="list"){let s=f(n,"--site","Usage: kenobi-pages hosted content list --site <siteSlug> [--template <templateSlug>]"),o=g(n,"--template"),i=await u(`/api/v1/pages/hosted/instances?${$({siteSlug:s,templateSlug:o})}`);l({...i,instances:(i.instances??[]).map(c=>we(c,{siteSlug:s,templateSlug:o}))});return}if(e==="get"){let s=p(n[0],"Usage: kenobi-pages hosted content get <siteSlug> <templateSlug> <itemSlug>"),o=p(n[1],"Usage: kenobi-pages hosted content get <siteSlug> <templateSlug> <itemSlug>"),i=p(n[2],"Usage: kenobi-pages hosted content get <siteSlug> <templateSlug> <itemSlug>"),c=await u(`/api/v1/pages/hosted/instances/${s}/${o}/${i}`);l(V(c,{siteSlug:s,templateSlug:o,itemSlug:i}));return}if(e==="upsert"){let s=f(n,"--site","Usage: kenobi-pages hosted content upsert --site <siteSlug> --template <templateSlug> --item <itemSlug> --content <json|file|->"),o=f(n,"--template","Missing --template <templateSlug>"),i=f(n,"--item","Missing --item <itemSlug>"),c=W(n,"--publication-id"),a=await A(n,"--content","--content"),h=await u("/api/v1/pages/hosted/instances",{method:"POST",body:{siteSlug:s,templateSlug:o,itemSlug:i,contentJson:a,...c!==void 0?{publicationId:c}:{}}});l(V(h,{siteSlug:s,templateSlug:o,itemSlug:i}));return}if(e==="verify"){let s=p(n[0],"Usage: kenobi-pages hosted content verify <siteSlug> <templateSlug> <itemSlug>"),o=p(n[1],"Usage: kenobi-pages hosted content verify <siteSlug> <templateSlug> <itemSlug>"),i=p(n[2],"Usage: kenobi-pages hosted content verify <siteSlug> <templateSlug> <itemSlug>"),c=E({siteSlug:s,templateSlug:o,itemSlug:i});try{let a=await u(`/api/v1/pages/hosted/instances/${s}/${o}/${i}`);l({ok:!0,publicUrl:c,resolved:!0,contentValid:!0,publication:a.templatePublication??null})}catch(a){if(!(a instanceof k))throw a;let b=(typeof a.payload.details=="object"&&a.payload.details!==null&&"stage"in a.payload.details?a.payload.details.stage:null)==="invalid-content"?!1:null;l({ok:!1,publicUrl:c,resolved:a.payload.status!==404,contentValid:b,publication:null,error:a.payload}),process.exit(a.exitCode)}return}throw d(`Unknown hosted content command: ${t.join(" ")}`)},"handleHostedContent"),tt=r(async t=>{let[e,...n]=t;if(e==="create"){let s=["--site-slug",f(n,"--site-slug","Missing --site-slug <siteSlug>"),...g(n,"--site-name")?["--site-name",g(n,"--site-name")]:[],"--template-slug",f(n,"--template-slug","Missing --template-slug <templateSlug>"),"--template-name",f(n,"--template-name","Missing --template-name <templateName>"),"--source",f(n,"--source","Missing --source <tsx-file>"),"--schema",f(n,"--schema","Missing --schema <json-file>"),"--content",f(n,"--content","Missing --content <json-file>"),...g(n,"--design-pack-id")?["--design-pack-id",g(n,"--design-pack-id")]:[],...m(n,"--no-current-draft")?["--no-current-draft"]:[]];l(ke(await u("/api/v1/pages/hosted/templates/drafts",{method:"POST",body:await he(s)})));return}throw d(`Unknown hosted page command: ${t.join(" ")}`)},"handleHostedPage"),ye=r(async t=>{let[e,n,...s]=t;if(e==="site")return Qe([n,...s].filter(Boolean));if(e==="template")return Ze([n,...s].filter(Boolean));if(e==="publication")return Xe([n,...s].filter(Boolean));if(e==="content")return et([n,...s].filter(Boolean));if(e==="page")return tt([n,...s].filter(Boolean));if(e==="draft"&&n==="save"){l(ke(await u("/api/v1/pages/hosted/templates/drafts",{method:"POST",body:await he(s)})));return}if(e==="publish"){let o=p(n,"Usage: kenobi-pages hosted publish <templateIdOrSlug>");l(await u(`/api/v1/pages/hosted/templates/${o}/publish`,{method:"POST"}));return}throw d(`Unknown hosted command: ${t.join(" ")}`)},"handleHosted");import{readFile as nt}from"node:fs/promises";var st=new Set(["COMPLETED","FAILED","CANCELED","SYSTEM_FAILURE","CRASHED"]),ot="Usage: kenobi-pages run <workflowIdOrSlug> [--dry-run] [--debug] [--params '<json>'|--params-file params.json] [--context <text>|--context-file notes.md]",rt=r(t=>new Promise(e=>setTimeout(e,t)),"sleep"),it=r(t=>{if(typeof t=="string")return t;if(typeof t=="object"&&t!==null&&"message"in t){let e=t.message;if(typeof e=="string")return e}return"Unknown error"},"runStatusErrorMessage"),be=r(async t=>{let e=p(t[0],ot),n=t.slice(1),s=g(n,"--params"),o=g(n,"--params-file"),i=g(n,"--context"),c=g(n,"--context-file"),a=m(n,"--dry-run"),h=m(n,"--debug");if(o?.startsWith("--"))throw d("Missing --params-file <path>");if(c?.startsWith("--"))throw d("Missing --context-file <path>");let b=o?await x(o,"--params-file"):s?y(s,"--params"):{},Q=c?await nt(c,"utf-8"):i,_={params:b};Q&&(_.context=Q),a&&(_.dryRun=!0);let D=await u(`/api/v1/cortex/workflows/${e}/run`,{method:"POST",body:_});if(a){l(D);return}let N=typeof D.runId=="string"?D.runId:void 0;if(!N)throw d("Run did not return a runId");console.error(`Run triggered: ${N}`),console.error("Polling for completion...");let J=2e3,Fe=15e3;for(;;){await rt(J);let S=await u(`/api/v1/cortex/workflows/${e}/runs/${N}${h?"?debug=true":""}`);if(console.error(`Status: ${S.status}`),st.has(S.status)){S.status!=="COMPLETED"&&(console.error(`Run failed (${S.status}): ${it(S.error)}`),l(S),process.exit(1)),l(S);return}J=Math.min(J*1.5,Fe)}},"handleRun");var K=r((t,e)=>{let n=" ".repeat(e);switch(t.type){case"string":case"url":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return t.items?.type==="object"&&t.items.fields?`Array<{
11
- ${Object.entries(t.items.fields).map(([i,c])=>`${n} ${i}: ${K(c,e+2)}`).join(`
9
+ `:""}${s}
10
+ `;oe(e,a),Ke()},"upsertEnvVar");var De=r(async e=>{let t=await e.text().catch(()=>"");if(!t)return null;try{return JSON.parse(t)}catch{return t}},"parseErrorBody"),_e=r(e=>{if(typeof e=="string")return e;if(typeof e=="object"&&e!==null&&"error"in e){let t=e.error;return typeof t=="string"?t:JSON.stringify(t)}return"Kenobi API request failed"},"errorMessageFromBody"),Je=r(e=>e===401||e===403?4:e===404?3:1,"exitCodeForStatus"),u=r(async(e,t={})=>{let n=await fetch(`${S()}${e}`,{method:t.method??"GET",headers:{"x-kenobi-key":ie(),"Content-Type":"application/json"},body:t.body?JSON.stringify(t.body):void 0});if(n.ok)return await n.json();let o=await De(n);throw new y({status:n.status,code:n.status===401||n.status===403?"unauthorized":"api_error",message:_e(o),details:o},Je(n.status))},"fetchKenobi"),v=r(e=>{let t=new URLSearchParams;for(let[n,o]of Object.entries(e))o!==void 0&&t.set(n,o);return t.toString()},"buildQuery");var $=r(e=>Object.keys(e??{}),"keys"),le=r(e=>{let t=e.packJson??null,n=t?.tokens??{},o=t?.surfaces??{},s=t?.typography??{},i=t?.accents??{};return{designPack:{id:e.id,status:e.status,hostDomain:t?.hostDomain??e.hostDomain??null,raw:t},templateGuidance:{brandSummary:t?.compositionDescription??"Use the raw design pack tokens and recipes as the source of truth.",tokens:{color:n.color??{},font:n.font??{},radius:n.radius??{},container:n.container??{},section:n.section??{}},surfaces:o,typography:s,accents:i,use:["Use color, font, radius, spacing, surface, and typography recipes from this design pack before inventing new styles.","Preserve the source site's visual rhythm, density, button treatment, and section composition.","Keep the template source self-contained and accept all dynamic values through the Template content prop."],avoid:["Do not use generic SaaS gradients, decorative orbs, or unrelated stock-style visuals.","Do not introduce a new palette when the design pack already contains brand colors.","Do not hard-code personalized copy that should come from the content schema."],availableRecipes:{colors:$(n.color),fonts:$(n.font),radii:$(n.radius),surfaces:$(o),typography:$(s),accents:$(i)}}}},"exportDesignPackForAgent");var We=new Set(["COMPLETED","FAILED","CANCELED","SYSTEM_FAILURE","CRASHED"]),Me=r(e=>new Promise(t=>setTimeout(t,e)),"sleep"),Le=r(e=>{console.error(JSON.stringify({event:"poll",taskStatus:e}))},"emitPollEvent"),Be=r((e,t)=>{if(typeof t.ok=="boolean")return{envelope:t,exitCode:t.ok?0:1};let n=typeof t.status=="string"?t.status:"UNKNOWN",o=t.designPack,i=(o!==null&&typeof o=="object"&&"id"in o&&typeof o.id=="number"?o.id:null)??(typeof t.designPackId=="number"?t.designPackId:null),c=n==="COMPLETED"&&o!==null&&typeof o=="object"&&i!==null;return{envelope:{...t,ok:c,taskStatus:n,designPackStatus:c?"ready":"failed",designPackId:i,nextCommand:c&&i!==null?`kenobi-pages design-pack export ${e} ${i}`:null},exitCode:c?0:1}},"resolveDesignPackTerminal"),He=r(async(e,t)=>{let n=2e3,o=15e3;for(;;){await Me(n);let s=await u(`/api/v1/pages/evidence-bundles/${e}/design-packs/runs/${t}`),i=typeof s.taskStatus=="string"?s.taskStatus:typeof s.status=="string"?s.status:"UNKNOWN";if(Le(i),!We.has(i)){n=Math.min(n*1.5,o);continue}let{envelope:c,exitCode:a}=Be(e,s);l(c),a!==0&&process.exit(a);return}},"pollDesignPack"),ue=r(async e=>{let[t,...n]=e,o=n[0];if(t==="list"){p(o,"Usage: kenobi-pages design-pack list <bundleId>"),l(await u(`/api/v1/pages/evidence-bundles/${o}/design-packs`));return}if(t==="generate"){p(o,"Usage: kenobi-pages design-pack generate <bundleId> [--wait]");let s=await u(`/api/v1/pages/evidence-bundles/${o}/design-packs`,{method:"POST",body:w(n.slice(1),"--dry-run")?{dryRun:!0}:{}});if(w(n.slice(1),"--dry-run")){l(s);return}if(!w(n.slice(1),"--wait")){l(s);return}let i=typeof s.taskId=="string"?s.taskId:void 0;if(!i){l(s);return}console.error(JSON.stringify({event:"queued",taskId:i})),await He(o,i);return}if(t==="status"){let s=p(n[1],"Usage: kenobi-pages design-pack status <bundleId> <taskId>");p(o,"Usage: kenobi-pages design-pack status <bundleId> <taskId>"),l(await u(`/api/v1/pages/evidence-bundles/${o}/design-packs/runs/${s}`));return}if(t==="get"){let s=p(n[1],"Usage: kenobi-pages design-pack get <bundleId> <designPackId>");p(o,"Usage: kenobi-pages design-pack get <bundleId> <designPackId>"),l(await u(`/api/v1/pages/evidence-bundles/${o}/design-packs/${s}`));return}if(t==="export"){let s=p(n[1],"Usage: kenobi-pages design-pack export <bundleId> <designPackId>");p(o,"Usage: kenobi-pages design-pack export <bundleId> <designPackId>");let i=await u(`/api/v1/pages/evidence-bundles/${o}/design-packs/${s}`);l(le(i.designPack??{}));return}throw d(`Unknown design-pack command: ${e.join(" ")}`)},"handleDesignPack");import{existsSync as Ge,readFileSync as Ve}from"node:fs";import{dirname as de,join as qe}from"node:path";import{fileURLToPath as Ye}from"node:url";var ze=r(()=>{let e=de(Ye(import.meta.url));for(let t=0;t<6;t+=1){let n=qe(e,"package.json");if(Ge(n))try{let o=JSON.parse(Ve(n,"utf-8"));if(o.name==="kenobi-pages"&&o.version)return o.version}catch{return"unknown"}e=de(e)}return"unknown"},"findPackageVersion"),pe=ze();var Qe=r(async e=>{try{let t=await fetch(`${S()}/api/v1/cortex/sources`,{headers:{"x-kenobi-key":e,"Content-Type":"application/json"}});if(!t.ok)return{auth:{ok:!1,status:t.status},sources:{count:null}};let n=await t.json();return{auth:{ok:!0,status:t.status},sources:{count:Array.isArray(n.sources)?n.sources.length:0}}}catch(t){return{auth:{ok:!1,status:null,error:t instanceof Error?t.message:"Unknown error"},sources:{count:null}}}},"authCheck"),ge=r(async()=>{let e=ae(),t=U(),n=e?await Qe(e):{auth:{ok:!1,status:null,skipped:!0},sources:{count:null}},o=[];e?n.auth.ok||o.push("Check that the Kenobi API key is valid for this org."):o.push(`Run 'kenobi-pages init' or set ${h}.`),e&&n.auth.ok&&n.sources.count===0&&o.push("Connect at least one source in Kenobi before building data-backed workflows."),l({ok:!!(e&&n.auth.ok),cli:{version:pe},env:{hasApiKey:!!e,apiKeyEnvVar:h,baseUrl:S(),envFiles:t},auth:n.auth,sources:n.sources,nextSteps:o})},"handleDoctor");import{readFile as me}from"node:fs/promises";var fe=r(()=>new Promise((e,t)=>{if(process.stdin.isTTY){e("");return}let n="";process.stdin.setEncoding("utf-8"),process.stdin.on("data",o=>{n+=o}),process.stdin.on("end",()=>e(n)),process.stdin.on("error",t)}),"readStdin"),b=r((e,t)=>{try{return JSON.parse(e)}catch{throw d(`Invalid JSON for ${t}`)}},"parseJson"),x=r(async(e,t)=>b(await me(e,"utf-8"),t),"readJsonFile"),O=r(async(e,t)=>{if(!e){let n=await fe();if(!n.trim())throw d(`Missing ${t}`);return b(n,t)}if(e==="-"){let n=await fe();if(!n.trim())throw d(`Missing ${t} on stdin`);return b(n,t)}return e.trim().startsWith("{")||e.trim().startsWith("[")?b(e,t):x(e,t)},"readJsonSource"),F=r(async(e,t="JSON")=>{let n=g(e,"--file");if(n)return x(n,t);let o=e.find(s=>s.trim().startsWith("{")||s.trim().startsWith("["));return O(o,t)},"readJsonInput"),we=r(async(e,t,n)=>{let o=g(e,t);if(o!==void 0)return O(o,n)},"readJsonFlag"),A=r(async(e,t,n)=>O(g(e,t),n),"readRequiredJsonFlag"),he=r(async(e,t,n)=>{let o=g(e,t);if(!o||o.startsWith("--"))throw d(`Missing ${n}`);return me(o,"utf-8")},"readTextFileFlag");var Ze=r((e,t)=>{let n={url:e},o=g(t,"--viewport"),s=g(t,"--headers"),i=g(t,"--wait-for-selector"),c=B(t,"--wait-timeout"),a=g(t,"--wait-until"),m=B(t,"--extra-wait-ms");return o&&(n.viewport=b(o,"--viewport")),s&&(n.headers=b(s,"--headers")),i&&(n.waitForSelector=i),c!==void 0&&(n.waitTimeout=c),a&&(n.waitUntil=a.trim().startsWith("[")?b(a,"--wait-until"):a),m!==void 0&&(n.extraWaitMs=m),w(t,"--block-annoyances")&&(n.blockAnnoyances=!0),w(t,"--dry-run")&&(n.dryRun=!0),n},"createEvidenceBody"),ke=r(async e=>{let[t,...n]=e;if(t==="list"){l(await u("/api/v1/pages/evidence-bundles"));return}if(t==="create"){let o=p(n[0],"Usage: kenobi-pages evidence create <url> [flags]");l(await u("/api/v1/pages/evidence-bundles",{method:"POST",body:Ze(o,n.slice(1))}));return}if(t==="get"){let o=p(n[0],"Usage: kenobi-pages evidence get <bundleId>");l(await u(`/api/v1/pages/evidence-bundles/${o}`));return}throw d(`Unknown evidence command: ${e.join(" ")}`)},"handleEvidence");var Xe="kenobi.page",et=r(e=>(e??Xe).replace(/^https?:\/\//,"").replace(/\/+$/,"").toLowerCase(),"normalizeHostedDomain"),tt=r(()=>et(R("KENOBI_PAGES_HOSTED_DOMAIN")),"getHostedPagesDomain"),I=r(({siteSlug:e,templateSlug:t,itemSlug:n})=>`https://${e}.${tt()}/${t}/${n}`,"buildHostedPublicUrl"),ye=r((e,t)=>{if(typeof e!="object"||e===null)return e;let n=e,o=typeof n.siteSlug=="string"?n.siteSlug:t?.siteSlug,s=typeof n.templateSlug=="string"?n.templateSlug:t?.templateSlug,i=typeof n.itemSlug=="string"?n.itemSlug:t?.itemSlug;return!o||!s||!i?e:{...e,publicUrl:I({siteSlug:o,templateSlug:s,itemSlug:i})}},"maybeDecorateHostedContent"),Y=r((e,t)=>({...e,publicUrl:I(t)}),"decorateHostedContentResponse");var be=r(async e=>{let t=f(e,"--template-slug","Usage: kenobi-pages hosted draft save --template-slug <slug> --template-name <name> --source <tsx-file> --schema <json-file> --content <json-file>"),n=f(e,"--template-name","Usage: kenobi-pages hosted draft save --template-slug <slug> --template-name <name> --source <tsx-file> --schema <json-file> --content <json-file>"),o=await he(e,"--source","--source <tsx-file>"),s=f(e,"--schema","Missing --schema <json-file>"),i=f(e,"--content","Missing --content <json-file>"),c=L(e,"--design-pack-id"),a=g(e,"--site-slug"),m=g(e,"--site-name"),k={templateSlug:t,templateName:n,sourceTsx:o,contentSchema:{title:n,schemaJson:await x(s,"--schema")},defaultContentJson:await x(i,"--content"),setCurrentDraft:!w(e,"--no-current-draft")};return c!==void 0&&(k.designPackId=c),a&&(k.site={slug:a,...m?{name:m}:{}}),k},"parseHostedDraftBody"),Se=r(e=>{let t=typeof e.previewPath=="string"?e.previewPath:null;return{...e,...t?{previewUrl:`${S()}${t}`}:{}}},"withPreviewUrl"),nt=r(async e=>{let[t,...n]=e;if(t==="list"){l(await u("/api/v1/pages/hosted/sites"));return}if(t==="get"){let o=p(n[0],"Usage: kenobi-pages hosted site get <siteSlug>");l(await u(`/api/v1/pages/hosted/sites?${v({slug:o})}`));return}throw d(`Unknown hosted site command: ${e.join(" ")}`)},"handleHostedSite"),ot=r(async e=>{let[t,...n]=e;if(t==="list"){let o=v({full:w(n,"--full")?"true":void 0});l(await u(`/api/v1/pages/hosted/templates${o?`?${o}`:""}`));return}if(t==="get"){let o=p(n[0],"Usage: kenobi-pages hosted template get <templateIdOrSlug> [--full]"),s=v({full:w(n.slice(1),"--full")?"true":void 0});l(await u(`/api/v1/pages/hosted/templates/${o}${s?`?${s}`:""}`));return}throw d(`Unknown hosted template command: ${e.join(" ")}`)},"handleHostedTemplate"),st=r(async e=>{let[t,...n]=e;if(t==="list"){let o=p(n[0],"Usage: kenobi-pages hosted publication list <templateIdOrSlug>");l(await u(`/api/v1/pages/hosted/templates/${o}/publications`));return}if(t==="get"){let o=p(n[0],"Usage: kenobi-pages hosted publication get <templateIdOrSlug> <publicationId>"),s=p(n[1],"Usage: kenobi-pages hosted publication get <templateIdOrSlug> <publicationId>");l(await u(`/api/v1/pages/hosted/templates/${o}/publications/${s}`));return}throw d(`Unknown hosted publication command: ${e.join(" ")}`)},"handleHostedPublication"),rt=r(async e=>{let[t,...n]=e;if(t==="list"){let o=f(n,"--site","Usage: kenobi-pages hosted content list --site <siteSlug> [--template <templateSlug>]"),s=g(n,"--template"),i=await u(`/api/v1/pages/hosted/instances?${v({siteSlug:o,templateSlug:s})}`);l({...i,instances:(i.instances??[]).map(c=>ye(c,{siteSlug:o,templateSlug:s}))});return}if(t==="get"){let o=p(n[0],"Usage: kenobi-pages hosted content get <siteSlug> <templateSlug> <itemSlug>"),s=p(n[1],"Usage: kenobi-pages hosted content get <siteSlug> <templateSlug> <itemSlug>"),i=p(n[2],"Usage: kenobi-pages hosted content get <siteSlug> <templateSlug> <itemSlug>"),c=await u(`/api/v1/pages/hosted/instances/${o}/${s}/${i}`);l(Y(c,{siteSlug:o,templateSlug:s,itemSlug:i}));return}if(t==="upsert"){let o=f(n,"--site","Usage: kenobi-pages hosted content upsert --site <siteSlug> --template <templateSlug> --item <itemSlug> --content <json|file|->"),s=f(n,"--template","Missing --template <templateSlug>"),i=f(n,"--item","Missing --item <itemSlug>"),c=L(n,"--publication-id"),a=await A(n,"--content","--content"),m=await u("/api/v1/pages/hosted/instances",{method:"POST",body:{siteSlug:o,templateSlug:s,itemSlug:i,contentJson:a,...c!==void 0?{publicationId:c}:{}}});l(Y(m,{siteSlug:o,templateSlug:s,itemSlug:i}));return}if(t==="verify"){let o=p(n[0],"Usage: kenobi-pages hosted content verify <siteSlug> <templateSlug> <itemSlug>"),s=p(n[1],"Usage: kenobi-pages hosted content verify <siteSlug> <templateSlug> <itemSlug>"),i=p(n[2],"Usage: kenobi-pages hosted content verify <siteSlug> <templateSlug> <itemSlug>"),c=I({siteSlug:o,templateSlug:s,itemSlug:i});try{let a=await u(`/api/v1/pages/hosted/instances/${o}/${s}/${i}`);l({ok:!0,publicUrl:c,resolved:!0,contentValid:!0,publication:a.templatePublication??null})}catch(a){if(!(a instanceof y))throw a;let k=(typeof a.payload.details=="object"&&a.payload.details!==null&&"stage"in a.payload.details?a.payload.details.stage:null)==="invalid-content"?!1:null;l({ok:!1,publicUrl:c,resolved:a.payload.status!==404,contentValid:k,publication:null,error:a.payload}),process.exit(a.exitCode)}return}throw d(`Unknown hosted content command: ${e.join(" ")}`)},"handleHostedContent"),it=r(async e=>{let[t,...n]=e;if(t==="create"){let o=["--site-slug",f(n,"--site-slug","Missing --site-slug <siteSlug>"),...g(n,"--site-name")?["--site-name",g(n,"--site-name")]:[],"--template-slug",f(n,"--template-slug","Missing --template-slug <templateSlug>"),"--template-name",f(n,"--template-name","Missing --template-name <templateName>"),"--source",f(n,"--source","Missing --source <tsx-file>"),"--schema",f(n,"--schema","Missing --schema <json-file>"),"--content",f(n,"--content","Missing --content <json-file>"),...g(n,"--design-pack-id")?["--design-pack-id",g(n,"--design-pack-id")]:[],...w(n,"--no-current-draft")?["--no-current-draft"]:[]];l(Se(await u("/api/v1/pages/hosted/templates/drafts",{method:"POST",body:await be(o)})));return}throw d(`Unknown hosted page command: ${e.join(" ")}`)},"handleHostedPage"),ve=r(async e=>{let[t,n,...o]=e;if(t==="site")return nt([n,...o].filter(Boolean));if(t==="template")return ot([n,...o].filter(Boolean));if(t==="publication")return st([n,...o].filter(Boolean));if(t==="content")return rt([n,...o].filter(Boolean));if(t==="page")return it([n,...o].filter(Boolean));if(t==="draft"&&n==="save"){l(Se(await u("/api/v1/pages/hosted/templates/drafts",{method:"POST",body:await be(o)})));return}if(t==="publish"){let s=p(n,"Usage: kenobi-pages hosted publish <templateIdOrSlug>");l(await u(`/api/v1/pages/hosted/templates/${s}/publish`,{method:"POST"}));return}throw d(`Unknown hosted command: ${e.join(" ")}`)},"handleHosted");import{readFile as at}from"node:fs/promises";var ct=new Set(["COMPLETED","FAILED","CANCELED","SYSTEM_FAILURE","CRASHED"]),lt="hosted-pages",ut="Usage: kenobi-pages run <workflowIdOrSlug> [--dry-run] [--debug] [--params '<json>'|--params-file params.json] [--context <text>|--context-file notes.md]",dt=r(e=>new Promise(t=>setTimeout(t,e)),"sleep"),pt=r(e=>{console.error(JSON.stringify({event:"poll",taskStatus:e}))},"emitPollEvent"),gt=r(e=>{if(!e||typeof e!="object")return null;let n=e.deliveries;if(!Array.isArray(n))return null;for(let o of n){if(!o||typeof o!="object")continue;let s=o;if(s.adapter!==lt)continue;let i=s.metadata;if(!i||typeof i!="object")continue;let c=i,a=c.siteSlug,m=c.templateSlug,k=c.itemSlug;if(typeof a=="string"&&typeof m=="string"&&typeof k=="string")return`kenobi-pages hosted content verify ${a} ${m} ${k}`}return null},"extractHostedPagesVerifyCommand"),ft=r(e=>e==="COMPLETED"?"completed":e==="FAILED"||e==="CANCELED"||e==="SYSTEM_FAILURE"||e==="CRASHED"?"failed":e==="QUEUED"||e==="DELAYED"||e==="FROZEN"?"queued":"running","mapWorkflowRunStatusLegacy"),mt=r(e=>{if(typeof e.ok=="boolean")return{envelope:e,exitCode:e.ok?0:1};let t=typeof e.status=="string"?e.status:"UNKNOWN",n=ft(t),o=n==="completed",s=o&&e.output!==void 0&&e.output!==null?gt(e.output):null;return{envelope:{...e,ok:o,taskStatus:t,runStatus:n,nextCommand:s},exitCode:o?0:1}},"resolveRunTerminal"),wt=r(e=>{if(typeof e=="string")return e;if(typeof e=="object"&&e!==null&&"message"in e){let t=e.message;if(typeof t=="string")return t}return"Unknown error"},"runStatusErrorMessage"),xe=r(async e=>{let t=p(e[0],ut),n=e.slice(1),o=g(n,"--params"),s=g(n,"--params-file"),i=g(n,"--context"),c=g(n,"--context-file"),a=w(n,"--dry-run"),m=w(n,"--debug");if(s?.startsWith("--"))throw d("Missing --params-file <path>");if(c?.startsWith("--"))throw d("Missing --context-file <path>");let k=s?await x(s,"--params-file"):o?b(o,"--params"):{},X=c?await at(c,"utf-8"):i,K={params:k};X&&(K.context=X),a&&(K.dryRun=!0);let D=await u(`/api/v1/cortex/workflows/${t}/run`,{method:"POST",body:K});if(a){l(D);return}let _=typeof D.runId=="string"?D.runId:void 0;if(!_)throw d("Run did not return a runId");console.error(JSON.stringify({event:"triggered",runId:_})),console.error(JSON.stringify({event:"polling_started"}));let J=2e3,Te=15e3;for(;;){await dt(J);let E=await u(`/api/v1/cortex/workflows/${t}/runs/${_}${m?"?debug=true":""}`),W=typeof E.taskStatus=="string"?E.taskStatus:typeof E.status=="string"?E.status:"UNKNOWN";if(pt(W),!ct.has(W)){J=Math.min(J*1.5,Te);continue}let{envelope:ee,exitCode:M}=mt(E);M!==0&&console.error(JSON.stringify({event:"terminal_failed",taskStatus:W,message:wt(ee.error)})),l(ee),M!==0&&process.exit(M);return}},"handleRun");var N=r((e,t)=>{let n=" ".repeat(t);switch(e.type){case"string":case"url":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return e.items?.type==="object"&&e.items.fields?`Array<{
11
+ ${Object.entries(e.items.fields).map(([i,c])=>`${n} ${i}: ${N(c,t+2)}`).join(`
12
12
  `)}
13
- ${n} }>`:`${t.items?K(t.items,e):"unknown"}[]`;case"object":return t.fields?`{
14
- ${Object.entries(t.fields).map(([o,i])=>`${n} ${o}: ${K(i,e+1)}`).join(`
13
+ ${n} }>`:`${e.items?N(e.items,t):"unknown"}[]`;case"object":return e.fields?`{
14
+ ${Object.entries(e.fields).map(([s,i])=>`${n} ${s}: ${N(i,t+1)}`).join(`
15
15
  `)}
16
- ${n}}`:"Record<string, unknown>";default:return"unknown"}},"schemaTypeToTs"),at=r(t=>`${t.replace(/[^a-zA-Z0-9\s]/g,"").split(/\s+/).filter(Boolean).map(e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()).join("")}Content`,"interfaceNameFromTitle"),ct=r(async t=>(await u(`/api/v1/cortex/workflows/${t}`)).id,"resolveWorkflowId"),lt=r(async t=>{let[e,...n]=t;if(e==="list"){l(await u("/api/v1/pages/self-hosted/schemas"));return}if(e==="get"){let s=p(n[0],"Usage: kenobi-pages self-hosted schema get <workflowIdOrSlug>");l(await u(`/api/v1/pages/self-hosted/${s}/schema`));return}if(e==="codegen"){let s=p(n[0],"Usage: kenobi-pages self-hosted schema codegen <workflowIdOrSlug>"),o=await u(`/api/v1/pages/self-hosted/${s}/schema`),i=Object.entries(o.schema).map(([c,a])=>`${a.description?` /** ${a.description} */
17
- `:""} ${c}: ${K(a,1)}`).join(`
18
- `);console.log(`export interface ${at(o.title??"KenobiPage")} {
16
+ ${n}}`:"Record<string, unknown>";default:return"unknown"}},"schemaTypeToTs"),ht=r(e=>`${e.replace(/[^a-zA-Z0-9\s]/g,"").split(/\s+/).filter(Boolean).map(t=>t.charAt(0).toUpperCase()+t.slice(1).toLowerCase()).join("")}Content`,"interfaceNameFromTitle"),kt=r(async e=>(await u(`/api/v1/cortex/workflows/${e}`)).id,"resolveWorkflowId"),yt=r(async e=>{let[t,...n]=e;if(t==="list"){l(await u("/api/v1/pages/self-hosted/schemas"));return}if(t==="get"){let o=p(n[0],"Usage: kenobi-pages self-hosted schema get <workflowIdOrSlug>");l(await u(`/api/v1/pages/self-hosted/${o}/schema`));return}if(t==="codegen"){let o=p(n[0],"Usage: kenobi-pages self-hosted schema codegen <workflowIdOrSlug>"),s=await u(`/api/v1/pages/self-hosted/${o}/schema`),i=Object.entries(s.schema).map(([c,a])=>`${a.description?` /** ${a.description} */
17
+ `:""} ${c}: ${N(a,1)}`).join(`
18
+ `);console.log(`export interface ${ht(s.title??"KenobiPage")} {
19
19
  ${i}
20
- }`);return}if(e==="push"){let s=p(n[0],"Usage: kenobi-pages self-hosted schema push <name> '<json>'"),o=await O(n.slice(1),"schema");l(await u("/api/v1/pages/self-hosted/schemas",{method:"POST",body:{title:s,schemaJson:o}}));return}throw d(`Unknown self-hosted schema command: ${t.join(" ")}`)},"handleSchema"),ut=r(async t=>{let[e,...n]=t;if(e==="list"){let s=p(n[0],"Usage: kenobi-pages self-hosted content list <workflowIdOrSlug>");l(await u(`/api/v1/pages/self-hosted/content-entries?${$({workflowId:s})}`));return}if(e==="get"){let s=p(n[0],"Usage: kenobi-pages self-hosted content get <workflowIdOrSlug> <slug>"),o=p(n[1],"Usage: kenobi-pages self-hosted content get <workflowIdOrSlug> <slug>");l(await u(`/api/v1/pages/self-hosted/${s}/${o}`));return}if(e==="upsert"){let s=f(n,"--workflow","Missing --workflow <idOrSlug>"),o=f(n,"--source-key","Missing --source-key <sourceKey>"),i=f(n,"--slug","Missing --slug <slug>"),c=await A(n,"--content","--content"),a=await ge(n,"--metadata","--metadata");l(await u("/api/v1/pages/self-hosted/content-entries",{method:"POST",body:{workflowId:await ct(s),slug:i,sourceKey:o,contentJson:c,...a!==void 0?{metadataJson:a}:{}}}));return}throw d(`Unknown self-hosted content command: ${t.join(" ")}`)},"handleContent"),Se=r(async t=>{let[e,n,...s]=t;if(e==="schema")return lt([n,...s].filter(Boolean));if(e==="content")return ut([n,...s].filter(Boolean));throw d(`Unknown self-hosted command: ${t.join(" ")}`)},"handleSelfHosted");var ve=r(async t=>{let[e,...n]=t;if(e===void 0||e==="list"){l(await u("/api/v1/cortex/sources"));return}if(e==="sample"){let s=p(n[0],"Usage: kenobi-pages sources sample <sourceKey>");l(await u(`/api/v1/cortex/sources/${encodeURIComponent(s)}/sample`));return}if(e==="schema"){let s=p(n[0],"Usage: kenobi-pages sources schema <sourceKey>"),i=(await u("/api/v1/cortex/sources")).sources.find(c=>c.sourceKey===s);if(!i)throw C(`Source not found: ${s}`);l({sourceKey:s,schema:i.schema??null});return}throw d(`Unknown sources command: ${t.join(" ")}`)},"handleSources");var dt=r(t=>{let e=t.resolution;return e?e.kind==="single"?"Use one record from this source.":e.kind==="lookup"?`Look up one record where ${e.field??"(missing field)"} equals runtime param ${e.param??"(missing param)"}.`:e.kind==="collection"?"Use this source as a collection.":`Unknown source resolution: ${e.kind??"(missing kind)"}.`:"Resolution is not configured."},"formatSourceResolution"),$e=r((t,e)=>{let n=new Set;for(let s of Object.values(t.output?.fields??{}))s.binding?.strategy==="passthrough"&&s.binding.sourceId===e&&s.binding.sourceField&&n.add(s.binding.sourceField);for(let s of t.generationGroups??[])for(let o of s.contextSources??[])o.sourceId===e&&(o.fields?o.fields.forEach(i=>n.add(i)):Object.keys((t.sources??[]).find(i=>i.id===e)?.schema??{}).forEach(i=>n.add(i)));return[...n].sort((s,o)=>s.localeCompare(o))},"fieldsForSource"),xe=r((t,e)=>Object.entries(t.output?.fields??{}).filter(([,n])=>n.binding?.groupId===e).map(([n])=>n).sort((n,s)=>n.localeCompare(s)),"producedByGroup"),pt=r(t=>{let e=t.adapterConfig??{},n=typeof e.slugField=="string"?e.slugField:null;if(t.adapter==="hosted-pages"){let s=typeof e.siteSlug=="string"?e.siteSlug:null,o=typeof e.templateSlug=="string"?e.templateSlug:null;return{id:t.id,type:t.adapter,writes:s&&o&&n?E({siteSlug:s,templateSlug:o,itemSlug:`{${n}}`}):"Hosted page URL pattern is incomplete.",slugField:n}}return t.adapter==="self-hosted-pages"?{id:t.id,type:t.adapter,writes:n?`Self-hosted page content keyed by workflowId + {${n}}.`:"Self-hosted page slug field is not configured.",slugField:n}:{id:t.id,type:t.adapter??"unknown",writes:"Destination is not a Kenobi Pages destination.",slugField:n}},"destinationSummary"),gt=r(t=>{let e=[],n=new Set((t.params??[]).map(i=>i.name)),s=t.output?.fields??{},o=new Set;for(let[i,c]of Object.entries(s)){let a=c.binding;(!a||a.strategy==="unconfigured")&&e.push(`Output field "${i}" is unconfigured.`),a?.strategy==="param"&&a.paramName&&!n.has(a.paramName)&&e.push(`Output field "${i}" references missing param "${a.paramName}".`),(a?.strategy==="generate"||a?.strategy==="generate-image")&&o.add(i)}for(let i of t.sources??[])i.resolution?.kind==="lookup"&&i.resolution.param&&(n.has(i.resolution.param)||e.push(`Source "${i.id}" lookup references missing param "${i.resolution.param}".`));for(let i of t.generationGroups??[])xe(t,i.id).length===0&&e.push(`Generation group "${i.id}" does not produce any output fields.`);for(let i of t.destinations??[]){let c=i.adapterConfig??{},a=typeof c.slugField=="string"?c.slugField:null;if(!a){e.push(`Destination "${i.id}" is missing adapterConfig.slugField.`);continue}s[a]?s[a].type!=="string"&&e.push(`Destination "${i.id}" slugField "${a}" is not a string field.`):e.push(`Destination "${i.id}" slugField "${a}" is not in output.fields.`)}return e},"collectWarnings"),Ie=r(t=>({summary:t.description??t.output?.title??t.id??"Kenobi workflow",inputs:(t.params??[]).map(e=>({name:e.name,description:e.description??null})),sources:(t.sources??[]).map(e=>({id:e.id,title:e.title??e.id,provider:e.provider??null,sourceKey:e.dataSourceKey??null,resolution:dt(e),fieldsUsed:$e(t,e.id)})),generation:(t.generationGroups??[]).map(e=>({group:e.id,strategy:e.strategy??null,uses:(e.contextSources??[]).map(n=>({sourceId:n.sourceId,fields:n.fields??$e(t,n.sourceId)})),produces:xe(t,e.id)})),output:{dataSourceKey:t.output?.dataSourceKey??null,title:t.output?.title??null,fields:Object.keys(t.output?.fields??{})},destinations:(t.destinations??[]).map(pt),warnings:gt(t)}),"explainWorkflow");var Ee=r((t,e)=>Object.fromEntries(Object.entries(t).map(([n,s])=>[n,{...s,binding:n===e?{strategy:"param",paramName:e}:{strategy:"unconfigured"}}])),"asUnconfiguredOutputFields"),Re=r((t,e)=>({...t,[e]:{type:"string",description:"URL slug for the generated page.",...t[e]}}),"ensureSlugField"),ft=r(t=>t.split(":").pop()?.replace(/[^a-z0-9]+/gi,"-").replace(/^-+|-+$/g,"").toLowerCase()||"pages-workflow","slugFromSourceKey"),q=r(async t=>{let e=g(t,"--config");if(e!==void 0){if(e.startsWith("--"))throw d("Missing --config '<json>'");return F(e,"workflow config")}return O(t,"workflow config")},"readWorkflowConfig"),mt=r(async t=>{let e=f(t,"--template-publication","Usage: kenobi-pages workflow scaffold hosted --template-publication <templateId:publicationId> --site <siteSlug> --template <templateSlug> --slug-field <field>"),[n,s]=e.split(":");if(!n||!s)throw d("--template-publication must be <templateId:publicationId>");let o=f(t,"--site","Missing --site <siteSlug>"),i=f(t,"--template","Missing --template <templateSlug>"),c=f(t,"--slug-field","Missing --slug-field <field>"),h=(await u(`/api/v1/pages/hosted/templates/${n}/publications/${s}`)).cortexOutputFieldSpecs??{},b=Ee(Re(h,c),c);l({id:`${o}-${i}`,params:[{name:c,description:"Public hosted page item slug."}],sources:[],output:{dataSourceKey:`hosted-pages:${i}`,title:`${i} hosted page`,fields:b},generationGroups:[],destinations:[{id:"hosted-pages",adapter:"hosted-pages",adapterConfig:{siteSlug:o,templateSlug:i,slugField:c,publicationId:Number(s)}}]})},"scaffoldHosted"),wt=r(async t=>{let e=f(t,"--source-key","Usage: kenobi-pages workflow scaffold self-hosted --source-key <sourceKey> --slug-field <field>"),n=f(t,"--slug-field","Missing --slug-field <field>"),o=(await u("/api/v1/cortex/sources")).sources.find(a=>a.sourceKey===e);if(!o)throw C(`Source not found: ${e}`);let i=Ee(Re(o.schema??{},n),n),c=ft(e);l({id:c,params:[{name:n,description:"URL slug for the generated page."}],sources:[],output:{dataSourceKey:e,title:o.sourceTitle??c,fields:i},generationGroups:[],destinations:[{id:"self-hosted-pages",adapter:"self-hosted-pages",adapterConfig:{slugField:n}}]})},"scaffoldSelfHosted"),ht=r(async t=>{let[e,...n]=t;if(e==="hosted")return mt(n);if(e==="self-hosted")return wt(n);throw d(`Unknown workflow scaffold command: ${t.join(" ")}`)},"handleScaffold"),Y=r(async t=>{let[e,...n]=t;if(e===void 0||e==="list"){l(await u("/api/v1/cortex/workflows"));return}if(e==="create"){let s=f(n,"--name","Missing --name <name>"),o=f(n,"--slug","Missing --slug <slug>"),i=g(n,"--description"),c=m(n,"--dry-run"),a={name:s,slug:o,config:await q(n)};i&&(a.description=i),c&&(a.dryRun=!0),l(await u("/api/v1/cortex/workflows",{method:"POST",body:a}));return}if(e==="validate"){let s=f(n,"--name","Missing --name <name>"),o=f(n,"--slug","Missing --slug <slug>"),i=g(n,"--description"),c={name:s,slug:o,config:await q(n)};i&&(c.description=i),l(await u("/api/v1/cortex/workflows/validate",{method:"POST",body:c}));return}if(e==="get"){let s=p(n[0],"Usage: kenobi-pages workflow get <workflowIdOrSlug>");l(await u(`/api/v1/cortex/workflows/${s}?full=true`));return}if(e==="update"){let s=p(n[0],"Usage: kenobi-pages workflow update <workflowIdOrSlug> [flags]"),o=n.slice(1),i={},c=m(o,"--dry-run"),a=g(o,"--name"),h=g(o,"--description");if(a&&(i.name=a),h!==void 0&&(i.description=h),(o.includes("--config")||o.includes("--file"))&&(i.config=await q(o)),c&&(i.dryRun=!0),Object.keys(i).length===(c?1:0))throw d("Nothing to update");l(await u(`/api/v1/cortex/workflows/${s}`,{method:"PUT",body:i}));return}if(e==="delete"){let s=p(n[0],"Usage: kenobi-pages workflow delete <workflowIdOrSlug>");l(await u(`/api/v1/cortex/workflows/${s}`,{method:"DELETE"}));return}if(e==="explain"){let s=await O(n,"workflow config");l(Ie(s));return}if(e==="scaffold")return ht(n);throw d(`Unknown workflow command: ${t.join(" ")}`)},"handleWorkflows");var kt=`kenobi-pages - Kenobi Pages CLI
20
+ }`);return}if(t==="push"){let o=p(n[0],"Usage: kenobi-pages self-hosted schema push <name> '<json>'"),s=await F(n.slice(1),"schema");l(await u("/api/v1/pages/self-hosted/schemas",{method:"POST",body:{title:o,schemaJson:s}}));return}throw d(`Unknown self-hosted schema command: ${e.join(" ")}`)},"handleSchema"),bt=r(async e=>{let[t,...n]=e;if(t==="list"){let o=p(n[0],"Usage: kenobi-pages self-hosted content list <workflowIdOrSlug>");l(await u(`/api/v1/pages/self-hosted/content-entries?${v({workflowId:o})}`));return}if(t==="get"){let o=p(n[0],"Usage: kenobi-pages self-hosted content get <workflowIdOrSlug> <slug>"),s=p(n[1],"Usage: kenobi-pages self-hosted content get <workflowIdOrSlug> <slug>");l(await u(`/api/v1/pages/self-hosted/${o}/${s}`));return}if(t==="upsert"){let o=f(n,"--workflow","Missing --workflow <idOrSlug>"),s=f(n,"--source-key","Missing --source-key <sourceKey>"),i=f(n,"--slug","Missing --slug <slug>"),c=await A(n,"--content","--content"),a=await we(n,"--metadata","--metadata");l(await u("/api/v1/pages/self-hosted/content-entries",{method:"POST",body:{workflowId:await kt(o),slug:i,sourceKey:s,contentJson:c,...a!==void 0?{metadataJson:a}:{}}}));return}throw d(`Unknown self-hosted content command: ${e.join(" ")}`)},"handleContent"),$e=r(async e=>{let[t,n,...o]=e;if(t==="schema")return yt([n,...o].filter(Boolean));if(t==="content")return bt([n,...o].filter(Boolean));throw d(`Unknown self-hosted command: ${e.join(" ")}`)},"handleSelfHosted");var Ie=r(async e=>{let[t,...n]=e;if(t===void 0||t==="list"){l(await u("/api/v1/cortex/sources"));return}if(t==="sample"){let o=p(n[0],"Usage: kenobi-pages sources sample <sourceKey>");l(await u(`/api/v1/cortex/sources/${encodeURIComponent(o)}/sample`));return}if(t==="schema"){let o=p(n[0],"Usage: kenobi-pages sources schema <sourceKey>"),i=(await u("/api/v1/cortex/sources")).sources.find(c=>c.sourceKey===o);if(!i)throw C(`Source not found: ${o}`);l({sourceKey:o,schema:i.schema??null});return}throw d(`Unknown sources command: ${e.join(" ")}`)},"handleSources");var St=r(e=>{let t=e.resolution;return t?t.kind==="single"?"Use one record from this source.":t.kind==="lookup"?`Look up one record where ${t.field??"(missing field)"} equals runtime param ${t.param??"(missing param)"}.`:t.kind==="collection"?"Use this source as a collection.":`Unknown source resolution: ${t.kind??"(missing kind)"}.`:"Resolution is not configured."},"formatSourceResolution"),Ee=r((e,t)=>{let n=new Set;for(let o of Object.values(e.output?.fields??{}))o.binding?.strategy==="passthrough"&&o.binding.sourceId===t&&o.binding.sourceField&&n.add(o.binding.sourceField);for(let o of e.generationGroups??[])for(let s of o.contextSources??[])s.sourceId===t&&(s.fields?s.fields.forEach(i=>n.add(i)):Object.keys((e.sources??[]).find(i=>i.id===t)?.schema??{}).forEach(i=>n.add(i)));return[...n].sort((o,s)=>o.localeCompare(s))},"fieldsForSource"),Re=r((e,t)=>Object.entries(e.output?.fields??{}).filter(([,n])=>n.binding?.groupId===t).map(([n])=>n).sort((n,o)=>n.localeCompare(o)),"producedByGroup"),vt=r(e=>{let t=e.adapterConfig??{},n=typeof t.slugField=="string"?t.slugField:null;if(e.adapter==="hosted-pages"){let o=typeof t.siteSlug=="string"?t.siteSlug:null,s=typeof t.templateSlug=="string"?t.templateSlug:null;return{id:e.id,type:e.adapter,writes:o&&s&&n?I({siteSlug:o,templateSlug:s,itemSlug:`{${n}}`}):"Hosted page URL pattern is incomplete.",slugField:n}}return e.adapter==="self-hosted-pages"?{id:e.id,type:e.adapter,writes:n?`Self-hosted page content keyed by workflowId + {${n}}.`:"Self-hosted page slug field is not configured.",slugField:n}:{id:e.id,type:e.adapter??"unknown",writes:"Destination is not a Kenobi Pages destination.",slugField:n}},"destinationSummary"),xt=r(e=>{let t=[],n=new Set((e.params??[]).map(i=>i.name)),o=e.output?.fields??{},s=new Set;for(let[i,c]of Object.entries(o)){let a=c.binding;(!a||a.strategy==="unconfigured")&&t.push(`Output field "${i}" is unconfigured.`),a?.strategy==="param"&&a.paramName&&!n.has(a.paramName)&&t.push(`Output field "${i}" references missing param "${a.paramName}".`),(a?.strategy==="generate"||a?.strategy==="generate-image")&&s.add(i)}for(let i of e.sources??[])i.resolution?.kind==="lookup"&&i.resolution.param&&(n.has(i.resolution.param)||t.push(`Source "${i.id}" lookup references missing param "${i.resolution.param}".`));for(let i of e.generationGroups??[])Re(e,i.id).length===0&&t.push(`Generation group "${i.id}" does not produce any output fields.`);for(let i of e.destinations??[]){let c=i.adapterConfig??{},a=typeof c.slugField=="string"?c.slugField:null;if(!a){t.push(`Destination "${i.id}" is missing adapterConfig.slugField.`);continue}o[a]?o[a].type!=="string"&&t.push(`Destination "${i.id}" slugField "${a}" is not a string field.`):t.push(`Destination "${i.id}" slugField "${a}" is not in output.fields.`)}return t},"collectWarnings"),Ue=r(e=>({summary:e.description??e.output?.title??e.id??"Kenobi workflow",inputs:(e.params??[]).map(t=>({name:t.name,description:t.description??null})),sources:(e.sources??[]).map(t=>({id:t.id,title:t.title??t.id,provider:t.provider??null,sourceKey:t.dataSourceKey??null,resolution:St(t),fieldsUsed:Ee(e,t.id)})),generation:(e.generationGroups??[]).map(t=>({group:t.id,strategy:t.strategy??null,uses:(t.contextSources??[]).map(n=>({sourceId:n.sourceId,fields:n.fields??Ee(e,n.sourceId)})),produces:Re(e,t.id)})),output:{dataSourceKey:e.output?.dataSourceKey??null,title:e.output?.title??null,fields:Object.keys(e.output?.fields??{})},destinations:(e.destinations??[]).map(vt),warnings:xt(e)}),"explainWorkflow");var Oe=r((e,t)=>Object.fromEntries(Object.entries(e).map(([n,o])=>[n,{...o,binding:n===t?{strategy:"param",paramName:t}:{strategy:"unconfigured"}}])),"asUnconfiguredOutputFields"),Fe=r((e,t)=>({...e,[t]:{type:"string",description:"URL slug for the generated page.",...e[t]}}),"ensureSlugField"),$t=r(e=>e.split(":").pop()?.replace(/[^a-z0-9]+/gi,"-").replace(/^-+|-+$/g,"").toLowerCase()||"pages-workflow","slugFromSourceKey"),z=r(async e=>{let t=g(e,"--config");if(t!==void 0){if(t.startsWith("--"))throw d("Missing --config '<json>'");return O(t,"workflow config")}return F(e,"workflow config")},"readWorkflowConfig"),It=r(async e=>{let t=f(e,"--template-publication","Usage: kenobi-pages workflow scaffold hosted --template-publication <templateId:publicationId> --site <siteSlug> --template <templateSlug> --slug-field <field>"),[n,o]=t.split(":");if(!n||!o)throw d("--template-publication must be <templateId:publicationId>");let s=f(e,"--site","Missing --site <siteSlug>"),i=f(e,"--template","Missing --template <templateSlug>"),c=f(e,"--slug-field","Missing --slug-field <field>"),m=(await u(`/api/v1/pages/hosted/templates/${n}/publications/${o}`)).cortexOutputFieldSpecs??{},k=Oe(Fe(m,c),c);l({id:`${s}-${i}`,params:[{name:c,description:"Public hosted page item slug."}],sources:[],output:{dataSourceKey:`hosted-pages:${i}`,title:`${i} hosted page`,fields:k},generationGroups:[],destinations:[{id:"hosted-pages",adapter:"hosted-pages",adapterConfig:{siteSlug:s,templateSlug:i,slugField:c,publicationId:Number(o)}}]})},"scaffoldHosted"),Et=r(async e=>{let t=f(e,"--source-key","Usage: kenobi-pages workflow scaffold self-hosted --source-key <sourceKey> --slug-field <field>"),n=f(e,"--slug-field","Missing --slug-field <field>"),s=(await u("/api/v1/cortex/sources")).sources.find(a=>a.sourceKey===t);if(!s)throw C(`Source not found: ${t}`);let i=Oe(Fe(s.schema??{},n),n),c=$t(t);l({id:c,params:[{name:n,description:"URL slug for the generated page."}],sources:[],output:{dataSourceKey:t,title:s.sourceTitle??c,fields:i},generationGroups:[],destinations:[{id:"self-hosted-pages",adapter:"self-hosted-pages",adapterConfig:{slugField:n}}]})},"scaffoldSelfHosted"),Rt=r(async e=>{let[t,...n]=e;if(t==="hosted")return It(n);if(t==="self-hosted")return Et(n);throw d(`Unknown workflow scaffold command: ${e.join(" ")}`)},"handleScaffold"),Q=r(async e=>{let[t,...n]=e;if(t===void 0||t==="list"){l(await u("/api/v1/cortex/workflows"));return}if(t==="create"){let o=f(n,"--name","Missing --name <name>"),s=f(n,"--slug","Missing --slug <slug>"),i=g(n,"--description"),c=w(n,"--dry-run"),a={name:o,slug:s,config:await z(n)};i&&(a.description=i),c&&(a.dryRun=!0),l(await u("/api/v1/cortex/workflows",{method:"POST",body:a}));return}if(t==="validate"){let o=f(n,"--name","Missing --name <name>"),s=f(n,"--slug","Missing --slug <slug>"),i=g(n,"--description"),c={name:o,slug:s,config:await z(n)};i&&(c.description=i),l(await u("/api/v1/cortex/workflows/validate",{method:"POST",body:c}));return}if(t==="get"){let o=p(n[0],"Usage: kenobi-pages workflow get <workflowIdOrSlug>");l(await u(`/api/v1/cortex/workflows/${o}?full=true`));return}if(t==="update"){let o=p(n[0],"Usage: kenobi-pages workflow update <workflowIdOrSlug> [flags]"),s=n.slice(1),i={},c=w(s,"--dry-run"),a=g(s,"--name"),m=g(s,"--description");if(a&&(i.name=a),m!==void 0&&(i.description=m),(s.includes("--config")||s.includes("--file"))&&(i.config=await z(s)),c&&(i.dryRun=!0),Object.keys(i).length===(c?1:0))throw d("Nothing to update");l(await u(`/api/v1/cortex/workflows/${o}`,{method:"PUT",body:i}));return}if(t==="delete"){let o=p(n[0],"Usage: kenobi-pages workflow delete <workflowIdOrSlug>");l(await u(`/api/v1/cortex/workflows/${o}`,{method:"DELETE"}));return}if(t==="explain"){let o=await F(n,"workflow config");l(Ue(o));return}if(t==="scaffold")return Rt(n);throw d(`Unknown workflow command: ${e.join(" ")}`)},"handleWorkflows");var Ut=`kenobi-pages - Kenobi Pages CLI
21
21
 
22
22
  Commands:
23
23
  doctor
@@ -92,4 +92,4 @@ Output:
92
92
  Environment:
93
93
  KENOBI_PAGES_KEY Org public key. Set via init or in your env file.
94
94
  KENOBI_BASE_URL Optional API base URL override.
95
- `,z=r(()=>{console.log(kt)},"printHelp");import{resolve as P}from"node:path";import{createInterface as yt}from"node:readline";var T=r(t=>new Promise(e=>{let n=yt({input:process.stdin,output:process.stderr});n.question(t,s=>{n.close(),e(s.trim())})}),"prompt"),bt=r(async t=>t.startsWith("pk_live_")||t.startsWith("pk_test_")?!0:(console.error(` Warning: "${t}" does not look like a Kenobi key (expected pk_live_... or pk_test_...).`),(await T(" Continue anyway? (y/N): ")).toLowerCase()==="y"),"validateKey"),St=r(()=>U()[0]??".env.local","defaultEnvFile"),vt=r(t=>{let e=g(t,"--key");if(!e||e.startsWith("--"))throw d("Usage: kenobi-pages init --key <key> [--env-file <path>] [--base-url <url>]");let n=g(t,"--env-file")??St(),s=g(t,"--base-url"),o=P(process.cwd(),n);G(o,w,e),s&&!s.startsWith("--")&&G(o,"KENOBI_BASE_URL",s),l({ok:!0,envFile:n,wrote:{[w]:!0,KENOBI_BASE_URL:!!(s&&!s.startsWith("--"))}})},"nonInteractiveInit"),Ue=r(async(t=[])=>{if(g(t,"--key")!==void 0){vt(t);return}console.error(""),console.error(" Kenobi Pages - Setup"),console.error(""),console.error(" Find your API key at: https://kenobi.ai/setup"),console.error("");let e=await T(" Paste your API key (pk_live_... or pk_test_...): ");e||(console.error(" No key provided. Aborting."),process.exit(1)),await bt(e)||(console.error(" Aborting."),process.exit(1));let n=U();if(n.length>0){console.error(""),console.error(" Found env files in this project:"),n.forEach((i,c)=>console.error(` ${c+1}. ${i}`)),console.error(` ${n.length+1}. Create a new file`),console.error(` ${n.length+2}. Skip`),console.error("");let s=await T(` Which file should ${w} be added to? [1]: `),o=s===""?0:parseInt(s,10)-1;if(o===n.length){let i=await T(" Filename (e.g. .env.local): ");i&&(j(P(process.cwd(),i),w,e),console.error(` Created ${i} with ${w}`))}else o>=0&&o<n.length&&re(P(process.cwd(),n[o]),w,e)}else{console.error("");let s=await T(" No env files found. Create one? (filename or 'n' to skip) [.env.local]: ");s.toLowerCase()!=="n"&&s!==""?(j(P(process.cwd(),s),w,e),console.error(` Created ${s} with ${w}`)):s===""&&(j(P(process.cwd(),".env.local"),w,e),console.error(` Created .env.local with ${w}`))}console.error(""),console.error(" Done. Your agent can now use kenobi-pages commands."),console.error(" Run 'npx kenobi-pages --help' to see what is available."),console.error("")},"initCommand");var $t=r(async t=>{if(t.length===0||t[0]==="--help"||t[0]==="-h"){z();return}let[e,...n]=t;if(n.includes("--help")||n.includes("-h")){z();return}if(e==="init")return Ue(n);if(e==="doctor")return ue();if(e==="evidence")return me(n);if(e==="design-pack")return ae(n);if(e==="hosted")return ye(n);if(e==="self-hosted")return Se(n);if(e==="sources")return ve(n);if(e==="workflows")return Y(["list",...n]);if(e==="workflow")return Y(n);if(e==="run")return be(n);throw d(`Unknown command: ${t.join(" ")}`)},"main");$t(process.argv.slice(2)).catch(X);
95
+ `,Z=r(()=>{console.log(Ut)},"printHelp");import{resolve as P}from"node:path";import{createInterface as Ot}from"node:readline";var T=r(e=>new Promise(t=>{let n=Ot({input:process.stdin,output:process.stderr});n.question(e,o=>{n.close(),t(o.trim())})}),"prompt"),Ft=r(async e=>e.startsWith("pk_live_")||e.startsWith("pk_test_")?!0:(console.error(` Warning: "${e}" does not look like a Kenobi key (expected pk_live_... or pk_test_...).`),(await T(" Continue anyway? (y/N): ")).toLowerCase()==="y"),"validateKey"),Pt=r(()=>U()[0]??".env.local","defaultEnvFile"),Tt=r(e=>{let t=g(e,"--key");if(!t||t.startsWith("--"))throw d("Usage: kenobi-pages init --key <key> [--env-file <path>] [--base-url <url>]");let n=g(e,"--env-file")??Pt(),o=g(e,"--base-url"),s=P(process.cwd(),n);q(s,h,t),o&&!o.startsWith("--")&&q(s,"KENOBI_BASE_URL",o),l({ok:!0,envFile:n,wrote:{[h]:!0,KENOBI_BASE_URL:!!(o&&!o.startsWith("--"))}})},"nonInteractiveInit"),Pe=r(async(e=[])=>{if(g(e,"--key")!==void 0){Tt(e);return}console.error(""),console.error(" Kenobi Pages - Setup"),console.error(""),console.error(" Find your API key at: https://kenobi.ai/setup"),console.error("");let t=await T(" Paste your API key (pk_live_... or pk_test_...): ");t||(console.error(" No key provided. Aborting."),process.exit(1)),await Ft(t)||(console.error(" Aborting."),process.exit(1));let n=U();if(n.length>0){console.error(""),console.error(" Found env files in this project:"),n.forEach((i,c)=>console.error(` ${c+1}. ${i}`)),console.error(` ${n.length+1}. Create a new file`),console.error(` ${n.length+2}. Skip`),console.error("");let o=await T(` Which file should ${h} be added to? [1]: `),s=o===""?0:parseInt(o,10)-1;if(s===n.length){let i=await T(" Filename (e.g. .env.local): ");i&&(j(P(process.cwd(),i),h,t),console.error(` Created ${i} with ${h}`))}else s>=0&&s<n.length&&ce(P(process.cwd(),n[s]),h,t)}else{console.error("");let o=await T(" No env files found. Create one? (filename or 'n' to skip) [.env.local]: ");o.toLowerCase()!=="n"&&o!==""?(j(P(process.cwd(),o),h,t),console.error(` Created ${o} with ${h}`)):o===""&&(j(P(process.cwd(),".env.local"),h,t),console.error(` Created .env.local with ${h}`))}console.error(""),console.error(" Done. Your agent can now use kenobi-pages commands."),console.error(" Run 'npx kenobi-pages --help' to see what is available."),console.error("")},"initCommand");var Ct=r(async e=>{if(e.length===0||e[0]==="--help"||e[0]==="-h"){Z();return}let[t,...n]=e;if(n.includes("--help")||n.includes("-h")){Z();return}if(t==="init")return Pe(n);if(t==="doctor")return ge();if(t==="evidence")return ke(n);if(t==="design-pack")return ue(n);if(t==="hosted")return ve(n);if(t==="self-hosted")return $e(n);if(t==="sources")return Ie(n);if(t==="workflows")return Q(["list",...n]);if(t==="workflow")return Q(n);if(t==="run")return xe(n);throw d(`Unknown command: ${e.join(" ")}`)},"main");Ct(process.argv.slice(2)).catch(ne);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "kenobi-pages",
3
- "version": "0.1.17",
3
+ "version": "0.1.18",
4
4
  "description": "Kenobi Pages SDK — fetch personalized page content from Kenobi workflows",
5
5
  "type": "module",
6
6
  "exports": {