fimo 0.9.0-experimental.3 → 0.9.0-experimental.4

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.
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "bundled": true,
3
3
  "bundler": "esbuild",
4
- "bundledAt": "2026-07-24T15:03:45.172Z",
4
+ "bundledAt": "2026-07-24T15:20:57.674Z",
5
5
  "cliVersion": "0.8.0",
6
6
  "external": [
7
7
  "oxc-parser",
package/dist/cli/index.js CHANGED
@@ -1853,7 +1853,7 @@ Next step: open ${path55.join(projectRoot,result.promptPath)} and paste it to yo
1853
1853
  `));return JSON.parse(fs50.readFileSync(filePath,"utf-8"))});syncSchemas({cwd,verbose:!1});let results=[];for(let schema of sortSchemasByReferenceDependencies(schemas3)){let contentType=toApiShape(schema);try{let result=await api.createSchema(ctx.projectId,contentType);results.push(result)}catch(error){if(isAlreadyExistsError(error)){let result=await api.updateSchema(ctx.projectId,contentType.name,contentType);results.push(result)}else{if(opts.tolerateUnknownTargets&&isUnknownTargetError(error))continue;throw error}}}return results}function applyDraftAdoption(drafts,renames,drops){let finalName=__name(uid=>renames[uid]??uid,"finalName"),kept=[],dropped=[],renamed=[];for(let draft of drafts){if(drops.has(draft.uid)){dropped.push(draft.uid);continue}let uid=finalName(draft.uid);uid!==draft.uid&&renamed.push({from:draft.uid,to:uid});let fields={};for(let[name,def]of Object.entries(draft.fields)){if(def&&typeof def=="object"&&def.type==="reference"){let ref={...def};if(typeof ref.target=="string"){if(drops.has(ref.target)){fields[name]={type:"string"};continue}ref.target=finalName(ref.target)}if(Array.isArray(ref.targets)){let targets=ref.targets.filter(target=>!drops.has(target)).map(finalName);if(targets.length===0){fields[name]={type:"string"};continue}ref.targets=targets}fields[name]=ref;continue}fields[name]=def}kept.push({uid,from:draft.uid,fields})}return{kept,dropped,renamed}}async function schemaAdoptDraftsCommand(options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd,{refuseReadOnly:!0});await requireOperation("cms.schema.push",{projectId:ctx.projectId,env:ctx.env});let cwd=resolveProjectCwd(options.cwd),draftsDir=path56.join(cwd,".fimo","migration","schema-drafts");if(!fs50.existsSync(draftsDir)){ui.error({command:"schemas adopt-drafts",code:"NO_SCHEMA_DRAFTS",message:"No .fimo/migration/schema-drafts directory \u2014 run `npx fimo migrate` first."}),process.exitCode=1;return}let drafts=fs50.readdirSync(draftsDir).filter(file=>file.endsWith(".json")).map(file=>JSON.parse(fs50.readFileSync(path56.join(draftsDir,file),"utf-8"))),renames={};for(let pair of(options.rename??"").split(",").map(entry=>entry.trim()).filter(Boolean)){let[from,to]=pair.split("=").map(part=>part.trim());from&&to&&(renames[from]=to)}let drops=new Set((options.drop??"").split(",").map(entry=>entry.trim()).filter(Boolean)),adoption=applyDraftAdoption(drafts.map(draft=>({uid:draft.uid,fields:draft.fields??{}})),renames,drops),schemasDir=path56.join(cwd,"src","schemas");fs50.mkdirSync(schemasDir,{recursive:!0});for(let schema of adoption.kept){let target=path56.join(schemasDir,`${schema.uid}.json`);if(fs50.existsSync(target)&&!options.force){ui.error({command:"schemas adopt-drafts",code:"SCHEMA_FILE_EXISTS",message:`src/schemas/${schema.uid}.json already exists \u2014 rerun with --force to overwrite.`}),process.exitCode=1;return}}for(let schema of adoption.kept)fs50.writeFileSync(path56.join(schemasDir,`${schema.uid}.json`),`${JSON.stringify({uid:schema.uid,name:schema.uid,fields:schema.fields},null,2)}
1854
1854
  `);let rowsDir=path56.join(cwd,".fimo","migration","rows");if(fs50.existsSync(rowsDir)){let finalName=__name(uid=>renames[uid]??uid,"finalName");for(let file of fs50.readdirSync(rowsDir).filter(entry=>entry.endsWith(".rows.json"))){let filePath=path56.join(rowsDir,file),rowsFile=JSON.parse(fs50.readFileSync(filePath,"utf-8"));if(drops.has(rowsFile.draftUid)){fs50.rmSync(filePath);continue}let newUid=finalName(rowsFile.draftUid);rowsFile.draftUid=newUid;for(let[field,reference]of Object.entries(rowsFile.references??{})){if(typeof reference.target=="string"){if(drops.has(reference.target)){delete rowsFile.references?.[field];continue}reference.target=finalName(reference.target)}if(Array.isArray(reference.targets)){let targets=reference.targets.filter(target=>!drops.has(target)).map(finalName);if(targets.length===0){delete rowsFile.references?.[field];continue}reference.targets=targets}}fs50.rmSync(filePath),fs50.writeFileSync(path56.join(rowsDir,`${newUid}.rows.json`),`${JSON.stringify(rowsFile,null,1)}
1855
1855
  `)}}if(Object.keys(renames).length>0){let sourceDirs=["app","src","pages"].map(dir=>path56.join(cwd,dir)).filter(dir=>fs50.existsSync(dir)),renameCallSites=__name(dir=>{for(let entry of fs50.readdirSync(dir,{withFileTypes:!0})){if(entry.name==="node_modules"||entry.name.startsWith("."))continue;let full=path56.join(dir,entry.name);if(entry.isDirectory()){renameCallSites(full);continue}if(!/\.(tsx|jsx|ts|js|mjs)$/.test(entry.name))continue;let source=fs50.readFileSync(full,"utf-8");if(!source.includes("wrapCollection("))continue;let next2=source;for(let[from,to]of Object.entries(renames))next2=next2.split(`wrapCollection('${from}'`).join(`wrapCollection('${to}'`),next2=next2.split(`wrapCollection("${from}"`).join(`wrapCollection("${to}"`);next2!==source&&fs50.writeFileSync(full,next2)}},"renameCallSites");for(let dir of sourceDirs)renameCallSites(dir)}let hasReferences2=adoption.kept.some(schema=>Object.values(schema.fields).some(def=>def&&typeof def=="object"&&def.type==="reference"));await pushAllSchemas(ctx,api,cwd,void 0,{tolerateUnknownTargets:hasReferences2}),hasReferences2&&await pushAllSchemas(ctx,api,cwd);let summary2={adopted:adoption.kept.map(schema=>schema.uid),renamed:adoption.renamed,dropped:adoption.dropped,pushed:adoption.kept.length};ui.result({command:"schemas adopt-drafts",data:summary2,render:__name(()=>[`Adopted ${adoption.kept.length} schema(s) into src/schemas and pushed.`,...adoption.renamed.length>0?[`Renamed: ${adoption.renamed.map(entry=>`${entry.from}\u2192${entry.to}`).join(", ")}`]:[],...adoption.dropped.length>0?[`Dropped: ${adoption.dropped.join(", ")}`]:[]].join(`
1856
- `),"render")})}async function schemaDeleteCommand(typeName,options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd,{refuseReadOnly:!0});await requireOperation("cms.schema.delete",{projectId:ctx.projectId,env:ctx.env});let result=await api.deleteSchema(ctx.projectId,typeName);ui.result({command:"schemas delete",data:result,render:__name(()=>renderPrettyJson8(result),"render")})}var SchemaCommandError,init_schema=__esm({"src/cli/commands/schema.ts"(){init_dist();init_sync_schemas();init_validate_schemas();init_api();init_capability_guard();init_project_context();init_project();SchemaCommandError=class extends Error{static{__name(this,"SchemaCommandError")}code;constructor(code2,message){super(message),this.name="SchemaCommandError",this.code=code2}};__name(renameOperation,"renameOperation");__name(toApiShape,"toApiShape");__name(renderPrettyJson8,"renderPrettyJson");__name(schemaListCommand,"schemaListCommand");__name(schemaGetCommand,"schemaGetCommand");__name(schemaPushCommand,"schemaPushCommand");__name(isAlreadyExistsError,"isAlreadyExistsError");__name(sortSchemasByReferenceDependencies,"sortSchemasByReferenceDependencies");__name(isUnknownTargetError,"isUnknownTargetError");__name(pushAllSchemas,"pushAllSchemas");__name(applyDraftAdoption,"applyDraftAdoption");__name(schemaAdoptDraftsCommand,"schemaAdoptDraftsCommand");__name(schemaDeleteCommand,"schemaDeleteCommand")}});function kebabCase(name){return name.replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/[^a-zA-Z0-9]+/g,"-").toLowerCase().replace(/^-+|-+$/g,"")}function humanize(field){return field.replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/[_-]+/g," ").replace(/^\w/,c2=>c2.toUpperCase())}function richTextDoc(text3){return{type:"doc",content:[{type:"paragraph",content:[{type:"text",text:text3}]}]}}function placeholderMedia(label){let svg=`<svg xmlns="http://www.w3.org/2000/svg" width="1200" height="630"><rect width="100%" height="100%" fill="#e5e7eb"/><text x="50%" y="50%" font-family="sans-serif" font-size="44" fill="#9ca3af" text-anchor="middle" dominant-baseline="middle">${label}</text></svg>`;return{source:"local",url:`data:image/svg+xml;utf8,${encodeURIComponent(svg)}`,alt:`${label} placeholder`,width:1200,height:630,mime:"image/svg+xml",name:"placeholder.svg"}}function exampleDate(n){return new Date(Date.UTC(2024,0,n)).toISOString().slice(0,10)}function exampleReferenceSlug(field){let targetName=field.target??field.targets?.[0];if(!targetName)return;let slug=`${kebabCase(targetName)}-example-1`;return field.many?[slug]:slug}function fillFieldValue(field,def,ctx){let baked=def.default;if(baked!==void 0)return baked;switch(def.type){case"string":return`${humanize(field)} example ${ctx.index}${ctx.localeSuffix}`;case"richtext":return richTextDoc(`Example ${humanize(ctx.schemaName).toLowerCase()} content ${ctx.index}${ctx.localeSuffix}.`);case"number":return ctx.index;case"boolean":return ctx.index%2===1;case"date":return exampleDate(ctx.index);case"json":return{};case"media":return placeholderMedia(humanize(field));case"blocks":return fillBlocks(def,ctx);default:return}}function fillBlocks(def,ctx){if(ctx.depth>=6)return[];let childCtx={...ctx,depth:ctx.depth+1},schema=def.schema;if("oneOf"in schema)return schema.oneOf.slice(0,5).map(variant=>({_type:variant.uid,...fillItem(variant.fields,childCtx)}));let itemCount=def.max===1?1:2;return Array.from({length:itemCount},()=>fillItem(schema.fields,childCtx))}function fillItem(fields,ctx){let item={};for(let[name,def]of Object.entries(fields)){let value=fillFieldValue(name,def,ctx);value!==void 0&&(item[name]=value)}return item}function generateExampleSeed(schema,options={}){let locale=options.locale,localeSuffix=locale?` (${locale})`:"",count=schema.isSingleton?1:Math.max(1,options.count??3),references={},rows=[];for(let i=1;i<=count;i+=1){let row2={};schema.isSingleton||(row2.slug=`${kebabCase(schema.name)}-example-${i}`);for(let[field,def]of Object.entries(schema.fields)){if(schema.examples&&field in schema.examples){row2[field]=schema.examples[field];continue}if(def.type==="reference"){let value2=exampleReferenceSlug(def);value2!==void 0&&(row2[field]=value2,references[field]={...def.target?{target:def.target}:{},...def.targets?{targets:def.targets}:{},by:"slug",...def.many?{many:!0}:{}});continue}let value=fillFieldValue(field,def,{localeSuffix,index:i,schemaName:schema.name,depth:0});value!==void 0&&(row2[field]=value)}rows.push(row2)}return{name:schema.name,isSingleton:schema.isSingleton,localized:schema.localized,rows,references}}var init_example_content=__esm({"src/scripts/cms/example-content.ts"(){__name(kebabCase,"kebabCase");__name(humanize,"humanize");__name(richTextDoc,"richTextDoc");__name(placeholderMedia,"placeholderMedia");__name(exampleDate,"exampleDate");__name(exampleReferenceSlug,"exampleReferenceSlug");__name(fillFieldValue,"fillFieldValue");__name(fillBlocks,"fillBlocks");__name(fillItem,"fillItem");__name(generateExampleSeed,"generateExampleSeed")}});var cms_scaffold_exports={};__export(cms_scaffold_exports,{extractSchemaTypeNames:()=>extractSchemaTypeNames,scaffoldCms:()=>scaffoldCms});function extractSchemaTypeNames(raw){let names=new Set,list=Array.isArray(raw)?raw:raw&&typeof raw=="object"?raw.data??raw.types:null;if(Array.isArray(list))for(let item of list){let name=item&&typeof item=="object"?item.name:void 0;typeof name=="string"&&names.add(name)}return names}function withoutReferences(fields){return Object.fromEntries(Object.entries(fields).filter(([,def])=>def.type!=="reference"))}function hasReferences(fields){return Object.values(fields).some(def=>def.type==="reference")}function orderByDependency(schemas3){let byName=new Map(schemas3.map(schema=>[schema.name,schema])),visited=new Set,ordered=[],visit2=__name((schema,stack)=>{if(!(visited.has(schema.name)||stack.has(schema.name))){stack.add(schema.name);for(let field of Object.values(schema.fields))if(field.type==="reference"){let targets=field.targets??(field.target?[field.target]:[]);for(let target of targets){let dep=byName.get(target);dep&&dep.name!==schema.name&&visit2(dep,stack)}}stack.delete(schema.name),visited.add(schema.name),ordered.push(schema)}},"visit");for(let schema of schemas3)visit2(schema,new Set);return ordered}async function scaffoldCms(opts){let{schemas:schemas3,cms,ctx,api,locales,count=3,force=!1}=opts,existingTypes=opts.existingTypes??new Set,ordered=orderByDependency(schemas3),sp=spinner(`Scaffolding ${cms} content model in Fimo`,{rail:opts.rail??!1}),errorMessage3=__name(error=>error instanceof Error?error.message:String(error),"errorMessage"),schemasCreated=0,entriesCreated=0,skipped=0,failures=[],usedLocales=new Set,created=new Set;try{for(let schema of ordered){let exists=existingTypes.has(schema.name);if(exists&&!force){skipped+=1,created.add(schema.name);continue}let bare={name:schema.name,label:schema.label,isSingleton:schema.isSingleton,fields:withoutReferences(schema.fields)};try{exists?await api.updateSchema(ctx.projectId,schema.name,bare):await api.createSchema(ctx.projectId,bare),schemasCreated+=1,created.add(schema.name)}catch(error){if(isAlreadyExistsError(error))try{await api.updateSchema(ctx.projectId,schema.name,bare),schemasCreated+=1,created.add(schema.name);continue}catch(updateError){failures.push({type:schema.name,stage:"schema",message:errorMessage3(updateError)});continue}failures.push({type:schema.name,stage:"schema",message:errorMessage3(error)})}}for(let schema of ordered)if(!(!created.has(schema.name)||existingTypes.has(schema.name)&&!force||!hasReferences(schema.fields)))try{await api.updateSchema(ctx.projectId,schema.name,{name:schema.name,label:schema.label,isSingleton:schema.isSingleton,fields:schema.fields})}catch(error){failures.push({type:schema.name,stage:"schema",message:`references: ${errorMessage3(error)}`})}for(let schema of ordered){if(!created.has(schema.name))continue;let seedLocales=schema.localized&&locales.length>0?locales:[void 0];for(let locale of seedLocales){let seed=generateExampleSeed(schema,{count,locale});try{if(schema.isSingleton)await api.putDocument(ctx.projectId,schema.name,seed.rows[0]??{},locale?{locale}:{}),entriesCreated+=1;else{let result=await api.importEntries(ctx.projectId,schema.name,{entries:seed.rows.map(data2=>({data:data2})),...locale?{locale}:{},...Object.keys(seed.references).length>0?{references:seed.references}:{},allowDangling:!0});entriesCreated+=result.created?.length??0,result.failed&&result.failed.length>0&&failures.push({type:schema.name,stage:"entries",message:`${result.failed.length} entry(ies) rejected${locale?` (${locale})`:""}: ${result.failed[0]?.message??result.failed[0]?.code??"unknown"}`})}locale&&usedLocales.add(locale)}catch(error){failures.push({type:schema.name,stage:"entries",message:`${errorMessage3(error)}${locale?` (${locale})`:""}`})}}}let skips=skipped>0?`, ${skipped} already present`:"",issues=failures.length>0?`, ${failures.length} issue(s)`:"";return sp.succeed(`Scaffolded ${schemasCreated} ${cms} type(s) + ${entriesCreated} example entr${entriesCreated===1?"y":"ies"} in Fimo${skips}${issues}`),{cms,schemas:schemasCreated,entries:entriesCreated,locales:[...usedLocales],skipped,failures}}catch(error){throw sp.stop(),error}}var init_cms_scaffold=__esm({"src/cli/utils/cms-scaffold.ts"(){init_dist();init_example_content();init_schema();__name(extractSchemaTypeNames,"extractSchemaTypeNames");__name(withoutReferences,"withoutReferences");__name(hasReferences,"hasReferences");__name(orderByDependency,"orderByDependency");__name(scaffoldCms,"scaffoldCms")}});function syncStateColor(state,p2){switch(state){case"in-sync":return p2.green("in sync");case"ahead":return p2.blue("ahead");case"behind":return p2.yellow("behind");case"diverged":return p2.red("diverged");default:return p2.dim("unknown")}}function renderStatus2(report,p2,opts={}){let lines=[],sep2=opts.ascii?"|":"\xB7",header=`${p2.bold(`env: ${report.env}`)} ${p2.dim(`vs ${report.vs} ${sep2}`)} ${syncStateColor(report.syncState,p2)}`;if(lines.push(header),lines.push(""),opts.short){for(let name of SURFACE_NAMES){if(opts.surface&&opts.surface!==name)continue;let delta=report.surfaces.find(s=>s.surface===name);if(!delta)continue;let innerSep=opts.ascii?"|":"\xB7",counts=`${delta.changedCount} changed${delta.conflictCount>0?` ${innerSep} ${delta.conflictCount} conflicts`:""}`,truncatedHint=delta.truncated&&delta.items&&delta.items.length<delta.changedCount?p2.dim(` ${innerSep} ${delta.items.length} of ${delta.changedCount} shown`):"";lines.push(` ${p2.bold(name.padEnd(14))} ${p2.dim(counts)}${truncatedHint}`)}return lines.join(`
1856
+ `),"render")})}async function schemaDeleteCommand(typeName,options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd,{refuseReadOnly:!0});await requireOperation("cms.schema.delete",{projectId:ctx.projectId,env:ctx.env});let result=await api.deleteSchema(ctx.projectId,typeName);ui.result({command:"schemas delete",data:result,render:__name(()=>renderPrettyJson8(result),"render")})}var SchemaCommandError,init_schema=__esm({"src/cli/commands/schema.ts"(){init_dist();init_sync_schemas();init_validate_schemas();init_api();init_capability_guard();init_project_context();init_project();SchemaCommandError=class extends Error{static{__name(this,"SchemaCommandError")}code;constructor(code2,message){super(message),this.name="SchemaCommandError",this.code=code2}};__name(renameOperation,"renameOperation");__name(toApiShape,"toApiShape");__name(renderPrettyJson8,"renderPrettyJson");__name(schemaListCommand,"schemaListCommand");__name(schemaGetCommand,"schemaGetCommand");__name(schemaPushCommand,"schemaPushCommand");__name(isAlreadyExistsError,"isAlreadyExistsError");__name(sortSchemasByReferenceDependencies,"sortSchemasByReferenceDependencies");__name(isUnknownTargetError,"isUnknownTargetError");__name(pushAllSchemas,"pushAllSchemas");__name(applyDraftAdoption,"applyDraftAdoption");__name(schemaAdoptDraftsCommand,"schemaAdoptDraftsCommand");__name(schemaDeleteCommand,"schemaDeleteCommand")}});function kebabCase(name){return name.replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/[^a-zA-Z0-9]+/g,"-").toLowerCase().replace(/^-+|-+$/g,"")}function humanize(field){return field.replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/[_-]+/g," ").replace(/^\w/,c2=>c2.toUpperCase())}function richTextDoc(text3){return{type:"doc",content:[{type:"paragraph",content:[{type:"text",text:text3}]}]}}function placeholderMedia(label){let svg=`<svg xmlns="http://www.w3.org/2000/svg" width="1200" height="630"><rect width="100%" height="100%" fill="#e5e7eb"/><text x="50%" y="50%" font-family="sans-serif" font-size="44" fill="#9ca3af" text-anchor="middle" dominant-baseline="middle">${label}</text></svg>`;return{source:"local",url:`data:image/svg+xml;utf8,${encodeURIComponent(svg)}`,alt:`${label} placeholder`,width:1200,height:630,mime:"image/svg+xml",name:"placeholder.svg"}}function exampleDate(n){return new Date(Date.UTC(2024,0,n)).toISOString().slice(0,10)}function exampleReferenceSlug(field){let targetName=field.target??field.targets?.[0];if(!targetName)return;let slug=`${kebabCase(targetName)}-example-1`;return field.many?[slug]:slug}function fillFieldValue(field,def,ctx){let baked=def.default;if(baked!==void 0)return baked;switch(def.type){case"string":return`${humanize(field)} example ${ctx.index}${ctx.localeSuffix}`;case"richtext":return richTextDoc(`Example ${humanize(ctx.schemaName).toLowerCase()} content ${ctx.index}${ctx.localeSuffix}.`);case"number":return ctx.index;case"boolean":return ctx.index%2===1;case"date":return exampleDate(ctx.index);case"json":return{};case"media":return placeholderMedia(humanize(field));case"blocks":return fillBlocks(def,ctx);default:return}}function fillBlocks(def,ctx){if(ctx.depth>=6)return[];let childCtx={...ctx,depth:ctx.depth+1},schema=def.schema;if("oneOf"in schema)return schema.oneOf.slice(0,5).map(variant=>({_type:variant.uid,...fillItem(variant.fields,childCtx)}));let itemCount=def.max===1?1:2;return Array.from({length:itemCount},()=>fillItem(schema.fields,childCtx))}function fillItem(fields,ctx){let item={};for(let[name,def]of Object.entries(fields)){let value=fillFieldValue(name,def,ctx);value!==void 0&&(item[name]=value)}return item}function generateExampleSeed(schema,options={}){let locale=options.locale,localeSuffix=locale?` (${locale})`:"",count=schema.isSingleton?1:Math.max(1,options.count??3),references={},rows=[];for(let i=1;i<=count;i+=1){let row2={};schema.isSingleton||(row2.slug=`${kebabCase(schema.name)}-example-${i}`);for(let[field,def]of Object.entries(schema.fields)){if(schema.examples&&field in schema.examples){row2[field]=schema.examples[field];continue}if(def.type==="reference"){let value2=exampleReferenceSlug(def);value2!==void 0&&(row2[field]=value2,references[field]={...def.target?{target:def.target}:{},...def.targets?{targets:def.targets}:{},by:"slug",...def.many?{many:!0}:{}});continue}let value=fillFieldValue(field,def,{localeSuffix,index:i,schemaName:schema.name,depth:0});value!==void 0&&(row2[field]=value)}rows.push(row2)}return{name:schema.name,isSingleton:schema.isSingleton,localized:schema.localized,rows,references}}var init_example_content=__esm({"src/scripts/cms/example-content.ts"(){__name(kebabCase,"kebabCase");__name(humanize,"humanize");__name(richTextDoc,"richTextDoc");__name(placeholderMedia,"placeholderMedia");__name(exampleDate,"exampleDate");__name(exampleReferenceSlug,"exampleReferenceSlug");__name(fillFieldValue,"fillFieldValue");__name(fillBlocks,"fillBlocks");__name(fillItem,"fillItem");__name(generateExampleSeed,"generateExampleSeed")}});var cms_scaffold_exports={};__export(cms_scaffold_exports,{extractSchemaTypeNames:()=>extractSchemaTypeNames,scaffoldCms:()=>scaffoldCms});function extractSchemaTypeNames(raw){let names=new Set,list=Array.isArray(raw)?raw:raw&&typeof raw=="object"?raw.data??raw.types:null;if(Array.isArray(list))for(let item of list){let name=item&&typeof item=="object"?item.name:void 0;typeof name=="string"&&names.add(name)}return names}function withoutReferences(fields){let out={};for(let[name,def]of Object.entries(fields))def.type!=="reference"&&(out[name]=def.type==="blocks"?blocksWithoutReferences(def):def);return out}function blocksWithoutReferences(def){return"oneOf"in def.schema?{...def,schema:{oneOf:def.schema.oneOf.map(variant=>({...variant,fields:withoutReferences(variant.fields)}))}}:{...def,schema:{fields:withoutReferences(def.schema.fields)}}}function hasReferences(fields){return Object.values(fields).some(def=>def.type==="reference"?!0:def.type==="blocks"?"oneOf"in def.schema?def.schema.oneOf.some(variant=>hasReferences(variant.fields)):hasReferences(def.schema.fields):!1)}function orderByDependency(schemas3){let byName=new Map(schemas3.map(schema=>[schema.name,schema])),visited=new Set,ordered=[],visit2=__name((schema,stack)=>{if(!(visited.has(schema.name)||stack.has(schema.name))){stack.add(schema.name);for(let field of Object.values(schema.fields))if(field.type==="reference"){let targets=field.targets??(field.target?[field.target]:[]);for(let target of targets){let dep=byName.get(target);dep&&dep.name!==schema.name&&visit2(dep,stack)}}stack.delete(schema.name),visited.add(schema.name),ordered.push(schema)}},"visit");for(let schema of schemas3)visit2(schema,new Set);return ordered}async function scaffoldCms(opts){let{schemas:schemas3,cms,ctx,api,locales,count=3,force=!1}=opts,existingTypes=opts.existingTypes??new Set,ordered=orderByDependency(schemas3),sp=spinner(`Scaffolding ${cms} content model in Fimo`,{rail:opts.rail??!1}),errorMessage3=__name(error=>error instanceof Error?error.message:String(error),"errorMessage"),schemasCreated=0,entriesCreated=0,skipped=0,failures=[],usedLocales=new Set,created=new Set;try{for(let schema of ordered){let exists=existingTypes.has(schema.name);if(exists&&!force){skipped+=1,created.add(schema.name);continue}let bare={name:schema.name,label:schema.label,isSingleton:schema.isSingleton,fields:withoutReferences(schema.fields)};try{exists?await api.updateSchema(ctx.projectId,schema.name,bare):await api.createSchema(ctx.projectId,bare),schemasCreated+=1,created.add(schema.name)}catch(error){if(isAlreadyExistsError(error))try{await api.updateSchema(ctx.projectId,schema.name,bare),schemasCreated+=1,created.add(schema.name);continue}catch(updateError){failures.push({type:schema.name,stage:"schema",message:errorMessage3(updateError)});continue}failures.push({type:schema.name,stage:"schema",message:errorMessage3(error)})}}for(let schema of ordered)if(!(!created.has(schema.name)||existingTypes.has(schema.name)&&!force||!hasReferences(schema.fields)))try{await api.updateSchema(ctx.projectId,schema.name,{name:schema.name,label:schema.label,isSingleton:schema.isSingleton,fields:schema.fields})}catch(error){failures.push({type:schema.name,stage:"schema",message:`references: ${errorMessage3(error)}`})}for(let schema of ordered){if(!created.has(schema.name))continue;let seedLocales=schema.localized&&locales.length>0?locales:[void 0];for(let locale of seedLocales){let seed=generateExampleSeed(schema,{count,locale});try{if(schema.isSingleton)await api.putDocument(ctx.projectId,schema.name,seed.rows[0]??{},locale?{locale}:{}),entriesCreated+=1;else{let result=await api.importEntries(ctx.projectId,schema.name,{entries:seed.rows.map(data2=>({data:data2})),...locale?{locale}:{},...Object.keys(seed.references).length>0?{references:seed.references}:{},allowDangling:!0});entriesCreated+=result.created?.length??0,result.failed&&result.failed.length>0&&failures.push({type:schema.name,stage:"entries",message:`${result.failed.length} entry(ies) rejected${locale?` (${locale})`:""}: ${result.failed[0]?.message??result.failed[0]?.code??"unknown"}`})}locale&&usedLocales.add(locale)}catch(error){failures.push({type:schema.name,stage:"entries",message:`${errorMessage3(error)}${locale?` (${locale})`:""}`})}}}let skips=skipped>0?`, ${skipped} already present`:"",issues=failures.length>0?`, ${failures.length} issue(s)`:"";return sp.succeed(`Scaffolded ${schemasCreated} ${cms} type(s) + ${entriesCreated} example entr${entriesCreated===1?"y":"ies"} in Fimo${skips}${issues}`),{cms,schemas:schemasCreated,entries:entriesCreated,locales:[...usedLocales],skipped,failures}}catch(error){throw sp.stop(),error}}var init_cms_scaffold=__esm({"src/cli/utils/cms-scaffold.ts"(){init_dist();init_example_content();init_schema();__name(extractSchemaTypeNames,"extractSchemaTypeNames");__name(withoutReferences,"withoutReferences");__name(blocksWithoutReferences,"blocksWithoutReferences");__name(hasReferences,"hasReferences");__name(orderByDependency,"orderByDependency");__name(scaffoldCms,"scaffoldCms")}});function syncStateColor(state,p2){switch(state){case"in-sync":return p2.green("in sync");case"ahead":return p2.blue("ahead");case"behind":return p2.yellow("behind");case"diverged":return p2.red("diverged");default:return p2.dim("unknown")}}function renderStatus2(report,p2,opts={}){let lines=[],sep2=opts.ascii?"|":"\xB7",header=`${p2.bold(`env: ${report.env}`)} ${p2.dim(`vs ${report.vs} ${sep2}`)} ${syncStateColor(report.syncState,p2)}`;if(lines.push(header),lines.push(""),opts.short){for(let name of SURFACE_NAMES){if(opts.surface&&opts.surface!==name)continue;let delta=report.surfaces.find(s=>s.surface===name);if(!delta)continue;let innerSep=opts.ascii?"|":"\xB7",counts=`${delta.changedCount} changed${delta.conflictCount>0?` ${innerSep} ${delta.conflictCount} conflicts`:""}`,truncatedHint=delta.truncated&&delta.items&&delta.items.length<delta.changedCount?p2.dim(` ${innerSep} ${delta.items.length} of ${delta.changedCount} shown`):"";lines.push(` ${p2.bold(name.padEnd(14))} ${p2.dim(counts)}${truncatedHint}`)}return lines.join(`
1857
1857
  `)}let surfaceOpts={ascii:opts.ascii,...opts.all?{maxItems:Number.MAX_SAFE_INTEGER}:{}};for(let name of SURFACE_NAMES){if(opts.surface&&opts.surface!==name)continue;let delta=report.surfaces.find(s=>s.surface===name);delta&&(lines.push(renderSurface(delta,p2,surfaceOpts)),lines.push(""))}if(!opts.surface&&report.crossSurface&&report.crossSurface.length>0&&(lines.push(renderCrossSurface(report.crossSurface,p2,{ascii:opts.ascii})),lines.push("")),report.agents&&report.agents.length>0){lines.push(p2.bold("AGENTS")),lines.push(p2.dim(" declared \xB7 active \xB7 last run"));for(let agent of report.agents){let status=agent.status==="active"?p2.green("active"):agent.status==="paused"?p2.yellow("paused"):p2.red("failed"),lastRun=agent.lastRunAt?p2.dim(new Date(agent.lastRunAt).toISOString().slice(0,19)+"Z"):p2.dim("never");lines.push(` ${agent.name.padEnd(18)} ${status.padEnd(7)} ${lastRun}`)}lines.push("")}return lines.join(`
1858
1858
  `).replace(/\n+$/,"")}var init_render_status=__esm({"src/cli/utils/format/render-status.ts"(){init_esm2();init_cross_surface();init_surface();__name(syncStateColor,"syncStateColor");__name(renderStatus2,"renderStatus")}});function pickSurfaces(opts){let selected=[["code","code"],["content","content"],["i18n","translations"],["agents","activations"],["assets","assets"],["forms","forms"]].filter(([flag2])=>opts[flag2]===!0).map(([,surface])=>surface);return selected.length>0?selected:void 0}function withSoftTimeout(p2,ms){return new Promise(resolve9=>{let t2=setTimeout(()=>resolve9({kind:"timeout"}),ms);p2.then(value=>{clearTimeout(t2),resolve9({kind:"ok",value})},error=>{clearTimeout(t2),resolve9({kind:"error",error})})})}async function localCodeSurface(cwd){if(!await isGitRepo(cwd))return{surface:"code",status:"unchanged",changedCount:0,conflictCount:0,items:[]};try{let items=(await runGit2(["status","--porcelain"],cwd)).split(`
1859
1859
  `).filter(Boolean).map(line=>{let code2=line.slice(0,2),path64=line.slice(3).trim();return{verb:code2.startsWith("A")||code2.startsWith("?")?"added":code2.startsWith("D")?"removed":"changed",key:path64,origin:"local-uncommitted"}});return{surface:"code",status:items.length===0?"unchanged":"ok",changedCount:items.length,conflictCount:0,items}}catch{return{surface:"code",status:"unchanged",changedCount:0,conflictCount:0,items:[]}}}function mergeCodeSurfaces(serverCode,local){if(!serverCode)return local;if(serverCode.status==="failed"||serverCode.status==="timed_out")return{...serverCode,items:[...serverCode.items??[],...local.items??[]],changedCount:serverCode.changedCount+local.changedCount};let items=[...serverCode.items??[],...local.items??[]],changedCount=serverCode.changedCount+local.changedCount,conflictCount=serverCode.conflictCount+local.conflictCount;return{surface:"code",status:changedCount>0||conflictCount>0?"ok":"unchanged",durationMs:serverCode.durationMs,changedCount,conflictCount,items}}async function statusCommand2(arg1,maybeCmd){let cmd=maybeCmd??arg1,options=maybeCmd?arg1:cmd.opts(),program2=cmd.parent??cmd,envOverride2=envOverrideFromCommand(program2),ctx=await getProjectContext({cwd:options.cwd,envOverride:envOverride2}),api=new FimoApiClient().withEnv(ctx.env),cwd=resolveProjectCwd(options.cwd),surfaces=pickSurfaces(options),codePromise=localCodeSurface(cwd),serverPromise=withSoftTimeout(api.getEnvStatus(ctx.projectId,ctx.env,{against:options.vs,surfaces}),SOFT_TIMEOUT_MS*15),[local,serverResult]=await Promise.all([codePromise,serverPromise]);if(serverResult.kind==="timeout"){ui.error({command:"status",code:"STATUS_TIMEOUT",message:`Server did not respond within ${SOFT_TIMEOUT_MS*15/1e3}s. Try again, or run \`fimo diff\` to drill in.`});return}if(serverResult.kind==="error"){let err=serverResult.error,message=err instanceof Error?err.message:String(err);ui.error({command:"status",code:"STATUS_REQUEST_FAILED",message:`Failed to fetch status: ${message}`});return}let server=serverResult.value,serverCode=server.surfaces.find(s=>s.surface==="code"),code2=mergeCodeSurfaces(serverCode,local),merged={...server,surfaces:[code2,...server.surfaces.filter(s=>s.surface!=="code")]};ui.result({command:"status",data:merged,render:__name(rctx=>{let p2=rctx.color?palette:makeColorPalette({forceDisable:!0});return renderStatus2(merged,p2,{short:options.short,surface:surfaces?.length===1?surfaces[0]:void 0,all:options.all,ascii:rctx.ascii})},"render")})}var SOFT_TIMEOUT_MS,init_status=__esm({"src/cli/commands/status.ts"(){init_dist();init_api();init_color();init_render_status();init_git();init_project_context();init_project();SOFT_TIMEOUT_MS=2e3;__name(pickSurfaces,"pickSurfaces");__name(withSoftTimeout,"withSoftTimeout");__name(localCodeSurface,"localCodeSurface");__name(mergeCodeSurfaces,"mergeCodeSurfaces");__name(statusCommand2,"statusCommand")}});init_dist();import fs56 from"node:fs";import path63 from"node:path";var import_index=__toESM(require_commander(),1),{program,createCommand,createArgument,createOption,CommanderError,InvalidArgumentError,InvalidOptionArgumentError,Command,Argument,Option,Help}=import_index.default;init_detect_framework();init_api();init_esm();init_dist();init_api();init_config();init_project();import fs12 from"node:fs";import path13 from"node:path";init_esm();var MAX_TYPE_TO_CONFIRM_ATTEMPTS=3;async function runConsent(input){let{caps,allowShell=!1,quiet=!1,io}=input,{caps:known}=partitionCapabilities(caps);if(renderCapabilityList(known,io),quiet)return known.some(isCritical)?(io.print("! critical-tier capabilities require interactive consent (use --allow-critical only when you understand the risk)"),{decision:"denied",approved:[]}):{decision:"allowed",approved:[...known]};let highRisk=known.filter(isHighRisk);if(highRisk.length===0){let ok=await io.promptYesNo(`? Proceed with install of ${input.agentName}? [y/N]`);return{decision:ok?"allowed":"denied",approved:ok?[...known]:[]}}let approved=known.filter(cap=>!isHighRisk(cap)),denied=[];for(let cap of highRisk.filter(c2=>!isCritical(c2))){if(cap==="shell:exec"&&allowShell){approved.push(cap),io.print(` \u2713 ${cap} (--allow-shell)`);continue}await io.promptYesNo(`? Allow ${cap} for ${input.agentName}? [y/n]`)?approved.push(cap):denied.push(cap)}if(denied.length>0)return io.print(`! aborting install \u2014 denied: ${denied.join(", ")}`),{decision:"denied",approved:[]};for(let cap of highRisk.filter(isCritical)){if(!await typeToConfirm(cap,input.agentName,io))return io.print(`! aborting install \u2014 failed to confirm ${cap}`),{decision:"denied",approved:[]};approved.push(cap)}return{decision:"allowed",approved}}__name(runConsent,"runConsent");async function typeToConfirm(cap,agentName,io){io.print(""),io.print(`! ${agentName} declares the CRITICAL capability '${cap}'`),io.print(" Type the literal token to confirm; anything else aborts.");for(let attempt=1;attempt<=MAX_TYPE_TO_CONFIRM_ATTEMPTS;attempt++){if(await io.promptText(` type '${cap}' (${attempt}/${MAX_TYPE_TO_CONFIRM_ATTEMPTS}): `)===cap)return!0;io.print(" mismatch.")}return!1}__name(typeToConfirm,"typeToConfirm");function renderCapabilityList(caps,io){if(caps.length===0){io.print(" (no capabilities declared \u2014 read-only default trio will apply at runtime)");return}io.print(""),io.print("This agent declares the following capabilities:");let byTier={low:[],medium:[],high:[],critical:[]};for(let cap of caps)byTier[riskTierOf(cap)].push(cap);let ORDER=["low","medium","high","critical"];for(let tier of ORDER){let list=byTier[tier];if(list.length!==0)for(let cap of list.sort())io.print(` \u25CF ${tier.padEnd(8)} ${cap}`)}io.print("")}__name(renderCapabilityList,"renderCapabilityList");function defaultConsentIO(){return{print(line){process.stdout.write(`${line}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "fimo",
3
- "version": "0.9.0-experimental.3",
3
+ "version": "0.9.0-experimental.4",
4
4
  "description": "Fimo CLI - create, deploy, and manage Fimo projects",
5
5
  "bin": {
6
6
  "fimo": "dist/cli/index.js"
@@ -21,7 +21,7 @@
21
21
  "cmdk": "^1.1.1",
22
22
  "date-fns": "^4.1.0",
23
23
  "embla-carousel-react": "^8.6.0",
24
- "fimo": "0.9.0-experimental.3",
24
+ "fimo": "0.9.0-experimental.4",
25
25
  "input-otp": "^1.4.2",
26
26
  "isbot": "^5",
27
27
  "lucide-react": "^0.577.0",