@stdout-design/cli 0.2.9 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.mjs +5 -7
  2. package/package.json +3 -2
package/dist/index.mjs CHANGED
@@ -1,10 +1,8 @@
1
1
  #!/usr/bin/env bun
2
- import{createRequire}from"node:module";import{Command}from"commander";import{AppError,ErrorCode,importTemplateForBatch,loadConfig,openCache,runBatch,zodToJsonSchemaShape}from"@stdout-design/core";import path from"node:path";import{execSync,spawnSync}from"node:child_process";import{existsSync,readFileSync}from"node:fs";import{resolveCommand}from"package-manager-detector/commands";import{detect}from"package-manager-detector/detect";import{cp,mkdir,writeFile}from"node:fs/promises";import{pathToFileURL}from"node:url";const formatBytes=bytes=>bytes<1024?`${bytes} B`:bytes<1024*1024?`${(bytes/1024).toFixed(1)} KB`:bytes<1024*1024*1024?`${(bytes/(1024*1024)).toFixed(1)} MB`:`${(bytes/(1024*1024*1024)).toFixed(2)} GB`,formatCacheStats=stats=>[``,`Cache Statistics`,`━━━━━━━━━━━━━━━━`,` Location: ${stats.cacheDir}`,` Compiled: ${stats.compiled.entries} entries (in-memory compile cache)`,` Pixel: ${stats.pixels.entries} entries`,` Disk used: ${formatBytes(stats.pixels.sizeBytes)}`,` Disk limit: ${formatBytes(stats.pixels.maxSizeBytes)}`,``].join(`
2
+ import{createRequire}from"node:module";import{Command}from"commander";import{AppError,ErrorCode,importTemplateForBatch,loadConfig,openCache,runBatch,zodToJsonSchemaShape}from"@stdout-design/core";import path from"node:path";import{execSync,spawnSync}from"node:child_process";import{existsSync,readFileSync}from"node:fs";import{resolveCommand}from"package-manager-detector/commands";import{detect}from"package-manager-detector/detect";import{z}from"zod";import{cp,mkdir,writeFile}from"node:fs/promises";const formatBytes=bytes=>bytes<1024?`${bytes} B`:bytes<1024*1024?`${(bytes/1024).toFixed(1)} KB`:bytes<1024*1024*1024?`${(bytes/(1024*1024)).toFixed(1)} MB`:`${(bytes/(1024*1024*1024)).toFixed(2)} GB`,formatCacheStats=stats=>[``,`Cache Statistics`,`━━━━━━━━━━━━━━━━`,` Location: ${stats.cacheDir}`,` Compiled: ${stats.compiled.entries} entries (in-memory compile cache)`,` Pixel: ${stats.pixels.entries} entries`,` Disk used: ${formatBytes(stats.pixels.sizeBytes)}`,` Disk limit: ${formatBytes(stats.pixels.maxSizeBytes)}`,``].join(`
3
3
  `),formatManifestSummary=manifest=>{let{completedCount,totalCount,succeeded,failed}=manifest,cacheHits=succeeded.filter(s=>s.cacheHit).length,lines=[``,`Batch Render Complete`,`━━━━━━━━━━━━━━━━━━━━`,` Status: ${manifest.status}`,` Total: ${totalCount}`,` Completed: ${completedCount}`,` Cache: ${cacheHits} hits, ${succeeded.length-cacheHits} renders`,` Failed: ${failed.length}`,``];if(succeeded.length>0&&succeeded.length<=10){lines.push(`Output files:`);for(let entry of succeeded)lines.push(` ${entry.outputPath}`);lines.push(``)}if(failed.length>0){lines.push(`Failures:`);for(let f of failed)lines.push(` Row ${f.rowIndex}, ${f.locale}, ${f.preset}: ${f.error}`);lines.push(``)}return lines.join(`
4
- `)},formatError$1=error=>error instanceof Error?`Error: ${error.message}`:`Error: ${String(error)}`,formatCacheCleanResult=freedBytes=>`Cache cleared. Freed ${formatBytes(freedBytes)}.`,cacheStats=async(rootDir,options)=>{let cache=await openCache(rootDir??process.cwd()),stats=await cache.stats();cache.close(),options.json?console.log(JSON.stringify(stats,null,2)):console.log(formatCacheStats(stats))},cacheClean=async(rootDir,options)=>{let cache=await openCache(rootDir??process.cwd()),result=await cache.clean();cache.close(),options.json?console.log(JSON.stringify(result)):console.log(formatCacheCleanResult(result.freedBytes))},findWebUiDist=()=>{try{let pkgJsonPath=createRequire(import.meta.url).resolve(`@stdout-design/web-ui/package.json`),pkgDir=path.dirname(pkgJsonPath);return path.join(pkgDir,`dist`)}catch{}},dev=async(rootDir,options)=>{let{startStandaloneServer}=await import(`@stdout-design/dev-server`).catch(()=>{throw Error([`studio dev requires a scaffolded project with @stdout-design/dev-server installed.`,"Run `studio init` to create one, or install it manually:",``,` bun add @stdout-design/dev-server`,``,`See https://stdout.design/docs for more information.`].join(`
5
- `))}),resolvedRoot=rootDir??process.cwd(),port=Number(options.port??`3000`),webUiDist=findWebUiDist();console.log(`Starting studio dev server for ${resolvedRoot}...`),await startStandaloneServer({port,rootDir:resolvedRoot,webUiDist})},isInsideGitRepo=dir=>{let current=path.resolve(dir);for(;;){if(existsSync(path.join(current,`.git`)))return!0;let parent=path.dirname(current);if(parent===current)break;current=parent}return!1},tryGitInit=dir=>{try{execSync(`git --version`,{stdio:`ignore`})}catch{return!1}if(existsSync(path.join(dir,`.git`))||isInsideGitRepo(path.dirname(dir)))return!1;try{return execSync(`git init`,{cwd:dir,stdio:`ignore`}),execSync(`git checkout -b main`,{cwd:dir,stdio:`ignore`}),execSync(`git add .`,{cwd:dir,stdio:`ignore`}),execSync(`git commit -m "Initial commit from stdout-design"`,{cwd:dir,stdio:`ignore`}),!0}catch{if(existsSync(path.join(dir,`.git`)))try{execSync(`rm -rf .git`,{cwd:dir,stdio:`ignore`})}catch{}return!1}};var _a$1;function $constructor(name,initializer,params){function init(inst,def){if(inst._zod||Object.defineProperty(inst,"_zod",{value:{def,constr:_,traits:new Set},enumerable:!1}),inst._zod.traits.has(name))return;inst._zod.traits.add(name),initializer(inst,def);let proto=_.prototype,keys=Object.keys(proto);for(let i=0;i<keys.length;i++){let k=keys[i];k in inst||(inst[k]=proto[k].bind(inst))}}let Parent=params?.Parent??Object;class Definition extends Parent{}Object.defineProperty(Definition,"name",{value:name});function _(def){var _a;let inst=params?.Parent?new Definition:this;init(inst,def),(_a=inst._zod).deferred??(_a.deferred=[]);for(let fn of inst._zod.deferred)fn();return inst}return Object.defineProperty(_,"init",{value:init}),Object.defineProperty(_,Symbol.hasInstance,{value:inst=>params?.Parent&&inst instanceof params.Parent?!0:inst?._zod?.traits?.has(name)}),Object.defineProperty(_,"name",{value:name}),_}var $ZodAsyncError=class extends Error{constructor(){super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`)}},$ZodEncodeError=class extends Error{constructor(name){super(`Encountered unidirectional transform during encode: ${name}`),this.name=`ZodEncodeError`}};(_a$1=globalThis).__zod_globalConfig??(_a$1.__zod_globalConfig={});const globalConfig=globalThis.__zod_globalConfig;function config(newConfig){return newConfig&&Object.assign(globalConfig,newConfig),globalConfig}function jsonStringifyReplacer(_,value){return typeof value==`bigint`?value.toString():value}function nullish(input){return input==null}function cleanRegex(source){let start=+!!source.startsWith(`^`),end=source.endsWith(`$`)?source.length-1:source.length;return source.slice(start,end)}const EVALUATING=Symbol(`evaluating`);function defineLazy(object,key,getter){let value;Object.defineProperty(object,key,{get(){if(value!==EVALUATING)return value===void 0&&(value=EVALUATING,value=getter()),value},set(v){Object.defineProperty(object,key,{value:v})},configurable:!0})}function mergeDefs(...defs){let mergedDescriptors={};for(let def of defs){let descriptors=Object.getOwnPropertyDescriptors(def);Object.assign(mergedDescriptors,descriptors)}return Object.defineProperties({},mergedDescriptors)}function slugify(input){return input.toLowerCase().trim().replace(/[^\w\s-]/g,``).replace(/[\s_-]+/g,`-`).replace(/^-+|-+$/g,``)}const captureStackTrace=`captureStackTrace`in Error?Error.captureStackTrace:(..._args)=>{};function isObject(data){return typeof data==`object`&&!!data&&!Array.isArray(data)}function isPlainObject(o){if(isObject(o)===!1)return!1;let ctor=o.constructor;if(ctor===void 0||typeof ctor!=`function`)return!0;let prot=ctor.prototype;return!(isObject(prot)===!1||Object.prototype.hasOwnProperty.call(prot,`isPrototypeOf`)===!1)}function shallowClone(o){return isPlainObject(o)?{...o}:Array.isArray(o)?[...o]:o instanceof Map?new Map(o):o instanceof Set?new Set(o):o}function escapeRegex(str){return str.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function clone(inst,def,params){let cl=new inst._zod.constr(def??inst._zod.def);return(!def||params?.parent)&&(cl._zod.parent=inst),cl}function normalizeParams(_params){let params=_params;if(!params)return{};if(typeof params==`string`)return{error:()=>params};if(params?.message!==void 0){if(params?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");params.error=params.message}return delete params.message,typeof params.error==`string`?{...params,error:()=>params.error}:params}-Number.MAX_VALUE,Number.MAX_VALUE;function aborted(x,startIndex=0){if(x.aborted===!0)return!0;for(let i=startIndex;i<x.issues.length;i++)if(x.issues[i]?.continue!==!0)return!0;return!1}function explicitlyAborted(x,startIndex=0){if(x.aborted===!0)return!0;for(let i=startIndex;i<x.issues.length;i++)if(x.issues[i]?.continue===!1)return!0;return!1}function prefixIssues(path,issues){return issues.map(iss=>{var _a;return(_a=iss).path??(_a.path=[]),iss.path.unshift(path),iss})}function unwrapMessage(message){return typeof message==`string`?message:message?.message}function finalizeIssue(iss,ctx,config){let message=iss.message?iss.message:unwrapMessage(iss.inst?._zod.def?.error?.(iss))??unwrapMessage(ctx?.error?.(iss))??unwrapMessage(config.customError?.(iss))??unwrapMessage(config.localeError?.(iss))??`Invalid input`,{inst:_inst,continue:_continue,input:_input,...rest}=iss;return rest.path??=[],rest.message=message,ctx?.reportInput&&(rest.input=_input),rest}function getLengthableOrigin(input){return Array.isArray(input)?`array`:typeof input==`string`?`string`:`unknown`}function issue(...args){let[iss,input,inst]=args;return typeof iss==`string`?{message:iss,code:`custom`,input,inst}:{...iss}}const initializer$1=(inst,def)=>{inst.name=`$ZodError`,Object.defineProperty(inst,"_zod",{value:inst._zod,enumerable:!1}),Object.defineProperty(inst,"issues",{value:def,enumerable:!1}),inst.message=JSON.stringify(def,jsonStringifyReplacer,2),Object.defineProperty(inst,"toString",{value:()=>inst.message,enumerable:!1})},$ZodError=$constructor(`$ZodError`,initializer$1),$ZodRealError=$constructor(`$ZodError`,initializer$1,{Parent:Error});function flattenError(error,mapper=issue=>issue.message){let fieldErrors={},formErrors=[];for(let sub of error.issues)sub.path.length>0?(fieldErrors[sub.path[0]]=fieldErrors[sub.path[0]]||[],fieldErrors[sub.path[0]].push(mapper(sub))):formErrors.push(mapper(sub));return{formErrors,fieldErrors}}function formatError(error,mapper=issue=>issue.message){let fieldErrors={_errors:[]},processError=(error,path=[])=>{for(let issue of error.issues)if(issue.code===`invalid_union`&&issue.errors.length)issue.errors.map(issues=>processError({issues},[...path,...issue.path]));else if(issue.code===`invalid_key`)processError({issues:issue.issues},[...path,...issue.path]);else if(issue.code===`invalid_element`)processError({issues:issue.issues},[...path,...issue.path]);else{let fullpath=[...path,...issue.path];if(fullpath.length===0)fieldErrors._errors.push(mapper(issue));else{let curr=fieldErrors,i=0;for(;i<fullpath.length;){let el=fullpath[i];i===fullpath.length-1?(curr[el]=curr[el]||{_errors:[]},curr[el]._errors.push(mapper(issue))):curr[el]=curr[el]||{_errors:[]},curr=curr[el],i++}}}};return processError(error),fieldErrors}const _parse=_Err=>(schema,value,_ctx,_params)=>{let ctx=_ctx?{..._ctx,async:!1}:{async:!1},result=schema._zod.run({value,issues:[]},ctx);if(result instanceof Promise)throw new $ZodAsyncError;if(result.issues.length){let e=new((_params?.Err)??_Err)(result.issues.map(iss=>finalizeIssue(iss,ctx,config())));throw captureStackTrace(e,_params?.callee),e}return result.value},_parseAsync=_Err=>async(schema,value,_ctx,params)=>{let ctx=_ctx?{..._ctx,async:!0}:{async:!0},result=schema._zod.run({value,issues:[]},ctx);if(result instanceof Promise&&(result=await result),result.issues.length){let e=new((params?.Err)??_Err)(result.issues.map(iss=>finalizeIssue(iss,ctx,config())));throw captureStackTrace(e,params?.callee),e}return result.value},_safeParse=_Err=>(schema,value,_ctx)=>{let ctx=_ctx?{..._ctx,async:!1}:{async:!1},result=schema._zod.run({value,issues:[]},ctx);if(result instanceof Promise)throw new $ZodAsyncError;return result.issues.length?{success:!1,error:new(_Err??$ZodError)(result.issues.map(iss=>finalizeIssue(iss,ctx,config())))}:{success:!0,data:result.value}},safeParse$1=_safeParse($ZodRealError),_safeParseAsync=_Err=>async(schema,value,_ctx)=>{let ctx=_ctx?{..._ctx,async:!0}:{async:!0},result=schema._zod.run({value,issues:[]},ctx);return result instanceof Promise&&(result=await result),result.issues.length?{success:!1,error:new _Err(result.issues.map(iss=>finalizeIssue(iss,ctx,config())))}:{success:!0,data:result.value}},safeParseAsync$1=_safeParseAsync($ZodRealError),_encode=_Err=>(schema,value,_ctx)=>{let ctx=_ctx?{..._ctx,direction:`backward`}:{direction:`backward`};return _parse(_Err)(schema,value,ctx)},_decode=_Err=>(schema,value,_ctx)=>_parse(_Err)(schema,value,_ctx),_encodeAsync=_Err=>async(schema,value,_ctx)=>{let ctx=_ctx?{..._ctx,direction:`backward`}:{direction:`backward`};return _parseAsync(_Err)(schema,value,ctx)},_decodeAsync=_Err=>async(schema,value,_ctx)=>_parseAsync(_Err)(schema,value,_ctx),_safeEncode=_Err=>(schema,value,_ctx)=>{let ctx=_ctx?{..._ctx,direction:`backward`}:{direction:`backward`};return _safeParse(_Err)(schema,value,ctx)},_safeDecode=_Err=>(schema,value,_ctx)=>_safeParse(_Err)(schema,value,_ctx),_safeEncodeAsync=_Err=>async(schema,value,_ctx)=>{let ctx=_ctx?{..._ctx,direction:`backward`}:{direction:`backward`};return _safeParseAsync(_Err)(schema,value,ctx)},_safeDecodeAsync=_Err=>async(schema,value,_ctx)=>_safeParseAsync(_Err)(schema,value,_ctx),cuid=/^[cC][0-9a-z]{6,}$/,cuid2=/^[0-9a-z]+$/,ulid=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,xid=/^[0-9a-vA-V]{20}$/,ksuid=/^[A-Za-z0-9]{27}$/,nanoid=/^[a-zA-Z0-9_-]{21}$/,duration$1=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,guid=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,uuid=version=>version?RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${version}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,email=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;function emoji(){return RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`)}const ipv4=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv6=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,cidrv4=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,cidrv6=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,base64url=/^[A-Za-z0-9_-]*$/,httpProtocol=/^https?$/,e164=/^\+[1-9]\d{6,14}$/,dateSource=`(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))`,date$1=RegExp(`^${dateSource}$`);function timeSource(args){let hhmm=`(?:[01]\\d|2[0-3]):[0-5]\\d`;return typeof args.precision==`number`?args.precision===-1?`${hhmm}`:args.precision===0?`${hhmm}:[0-5]\\d`:`${hhmm}:[0-5]\\d\\.\\d{${args.precision}}`:`${hhmm}(?::[0-5]\\d(?:\\.\\d+)?)?`}function time$1(args){return RegExp(`^${timeSource(args)}$`)}function datetime$1(args){let time=timeSource({precision:args.precision}),opts=[`Z`];args.local&&opts.push(``),args.offset&&opts.push(`([+-](?:[01]\\d|2[0-3]):[0-5]\\d)`);let timeRegex=`${time}(?:${opts.join(`|`)})`;return RegExp(`^${dateSource}T(?:${timeRegex})$`)}const string$1=params=>{let regex=params?`[\\s\\S]{${params?.minimum??0},${params?.maximum??``}}`:`[\\s\\S]*`;return RegExp(`^${regex}$`)},lowercase=/^[^A-Z]*$/,uppercase=/^[^a-z]*$/,$ZodCheck=$constructor(`$ZodCheck`,(inst,def)=>{var _a;inst._zod??={},inst._zod.def=def,(_a=inst._zod).onattach??(_a.onattach=[])}),$ZodCheckMaxLength=$constructor(`$ZodCheckMaxLength`,(inst,def)=>{var _a;$ZodCheck.init(inst,def),(_a=inst._zod.def).when??(_a.when=payload=>{let val=payload.value;return!nullish(val)&&val.length!==void 0}),inst._zod.onattach.push(inst=>{let curr=inst._zod.bag.maximum??1/0;def.maximum<curr&&(inst._zod.bag.maximum=def.maximum)}),inst._zod.check=payload=>{let input=payload.value;if(input.length<=def.maximum)return;let origin=getLengthableOrigin(input);payload.issues.push({origin,code:`too_big`,maximum:def.maximum,inclusive:!0,input,inst,continue:!def.abort})}}),$ZodCheckMinLength=$constructor(`$ZodCheckMinLength`,(inst,def)=>{var _a;$ZodCheck.init(inst,def),(_a=inst._zod.def).when??(_a.when=payload=>{let val=payload.value;return!nullish(val)&&val.length!==void 0}),inst._zod.onattach.push(inst=>{let curr=inst._zod.bag.minimum??-1/0;def.minimum>curr&&(inst._zod.bag.minimum=def.minimum)}),inst._zod.check=payload=>{let input=payload.value;if(input.length>=def.minimum)return;let origin=getLengthableOrigin(input);payload.issues.push({origin,code:`too_small`,minimum:def.minimum,inclusive:!0,input,inst,continue:!def.abort})}}),$ZodCheckLengthEquals=$constructor(`$ZodCheckLengthEquals`,(inst,def)=>{var _a;$ZodCheck.init(inst,def),(_a=inst._zod.def).when??(_a.when=payload=>{let val=payload.value;return!nullish(val)&&val.length!==void 0}),inst._zod.onattach.push(inst=>{let bag=inst._zod.bag;bag.minimum=def.length,bag.maximum=def.length,bag.length=def.length}),inst._zod.check=payload=>{let input=payload.value,length=input.length;if(length===def.length)return;let origin=getLengthableOrigin(input),tooBig=length>def.length;payload.issues.push({origin,...tooBig?{code:`too_big`,maximum:def.length}:{code:`too_small`,minimum:def.length},inclusive:!0,exact:!0,input:payload.value,inst,continue:!def.abort})}}),$ZodCheckStringFormat=$constructor(`$ZodCheckStringFormat`,(inst,def)=>{var _a,_b;$ZodCheck.init(inst,def),inst._zod.onattach.push(inst=>{let bag=inst._zod.bag;bag.format=def.format,def.pattern&&(bag.patterns??=new Set,bag.patterns.add(def.pattern))}),def.pattern?(_a=inst._zod).check??(_a.check=payload=>{def.pattern.lastIndex=0,!def.pattern.test(payload.value)&&payload.issues.push({origin:`string`,code:`invalid_format`,format:def.format,input:payload.value,...def.pattern?{pattern:def.pattern.toString()}:{},inst,continue:!def.abort})}):(_b=inst._zod).check??(_b.check=()=>{})}),$ZodCheckRegex=$constructor(`$ZodCheckRegex`,(inst,def)=>{$ZodCheckStringFormat.init(inst,def),inst._zod.check=payload=>{def.pattern.lastIndex=0,!def.pattern.test(payload.value)&&payload.issues.push({origin:`string`,code:`invalid_format`,format:`regex`,input:payload.value,pattern:def.pattern.toString(),inst,continue:!def.abort})}}),$ZodCheckLowerCase=$constructor(`$ZodCheckLowerCase`,(inst,def)=>{def.pattern??=lowercase,$ZodCheckStringFormat.init(inst,def)}),$ZodCheckUpperCase=$constructor(`$ZodCheckUpperCase`,(inst,def)=>{def.pattern??=uppercase,$ZodCheckStringFormat.init(inst,def)}),$ZodCheckIncludes=$constructor(`$ZodCheckIncludes`,(inst,def)=>{$ZodCheck.init(inst,def);let escapedRegex=escapeRegex(def.includes),pattern=new RegExp(typeof def.position==`number`?`^.{${def.position}}${escapedRegex}`:escapedRegex);def.pattern=pattern,inst._zod.onattach.push(inst=>{let bag=inst._zod.bag;bag.patterns??=new Set,bag.patterns.add(pattern)}),inst._zod.check=payload=>{payload.value.includes(def.includes,def.position)||payload.issues.push({origin:`string`,code:`invalid_format`,format:`includes`,includes:def.includes,input:payload.value,inst,continue:!def.abort})}}),$ZodCheckStartsWith=$constructor(`$ZodCheckStartsWith`,(inst,def)=>{$ZodCheck.init(inst,def);let pattern=RegExp(`^${escapeRegex(def.prefix)}.*`);def.pattern??=pattern,inst._zod.onattach.push(inst=>{let bag=inst._zod.bag;bag.patterns??=new Set,bag.patterns.add(pattern)}),inst._zod.check=payload=>{payload.value.startsWith(def.prefix)||payload.issues.push({origin:`string`,code:`invalid_format`,format:`starts_with`,prefix:def.prefix,input:payload.value,inst,continue:!def.abort})}}),$ZodCheckEndsWith=$constructor(`$ZodCheckEndsWith`,(inst,def)=>{$ZodCheck.init(inst,def);let pattern=RegExp(`.*${escapeRegex(def.suffix)}$`);def.pattern??=pattern,inst._zod.onattach.push(inst=>{let bag=inst._zod.bag;bag.patterns??=new Set,bag.patterns.add(pattern)}),inst._zod.check=payload=>{payload.value.endsWith(def.suffix)||payload.issues.push({origin:`string`,code:`invalid_format`,format:`ends_with`,suffix:def.suffix,input:payload.value,inst,continue:!def.abort})}}),$ZodCheckOverwrite=$constructor(`$ZodCheckOverwrite`,(inst,def)=>{$ZodCheck.init(inst,def),inst._zod.check=payload=>{payload.value=def.tx(payload.value)}}),version={major:4,minor:4,patch:3},$ZodType=$constructor(`$ZodType`,(inst,def)=>{var _a;inst??={},inst._zod.def=def,inst._zod.bag=inst._zod.bag||{},inst._zod.version=version;let checks=[...inst._zod.def.checks??[]];inst._zod.traits.has(`$ZodCheck`)&&checks.unshift(inst);for(let ch of checks)for(let fn of ch._zod.onattach)fn(inst);if(checks.length===0)(_a=inst._zod).deferred??(_a.deferred=[]),inst._zod.deferred?.push(()=>{inst._zod.run=inst._zod.parse});else{let runChecks=(payload,checks,ctx)=>{let isAborted=aborted(payload),asyncResult;for(let ch of checks){if(ch._zod.def.when){if(explicitlyAborted(payload)||!ch._zod.def.when(payload))continue}else if(isAborted)continue;let currLen=payload.issues.length,_=ch._zod.check(payload);if(_ instanceof Promise&&ctx?.async===!1)throw new $ZodAsyncError;if(asyncResult||_ instanceof Promise)asyncResult=(asyncResult??Promise.resolve()).then(async()=>{await _,payload.issues.length!==currLen&&(isAborted||=aborted(payload,currLen))});else{if(payload.issues.length===currLen)continue;isAborted||=aborted(payload,currLen)}}return asyncResult?asyncResult.then(()=>payload):payload},handleCanaryResult=(canary,payload,ctx)=>{if(aborted(canary))return canary.aborted=!0,canary;let checkResult=runChecks(payload,checks,ctx);if(checkResult instanceof Promise){if(ctx.async===!1)throw new $ZodAsyncError;return checkResult.then(checkResult=>inst._zod.parse(checkResult,ctx))}return inst._zod.parse(checkResult,ctx)};inst._zod.run=(payload,ctx)=>{if(ctx.skipChecks)return inst._zod.parse(payload,ctx);if(ctx.direction===`backward`){let canary=inst._zod.parse({value:payload.value,issues:[]},{...ctx,skipChecks:!0});return canary instanceof Promise?canary.then(canary=>handleCanaryResult(canary,payload,ctx)):handleCanaryResult(canary,payload,ctx)}let result=inst._zod.parse(payload,ctx);if(result instanceof Promise){if(ctx.async===!1)throw new $ZodAsyncError;return result.then(result=>runChecks(result,checks,ctx))}return runChecks(result,checks,ctx)}}defineLazy(inst,`~standard`,()=>({validate:value=>{try{let r=safeParse$1(inst,value);return r.success?{value:r.data}:{issues:r.error?.issues}}catch{return safeParseAsync$1(inst,value).then(r=>r.success?{value:r.data}:{issues:r.error?.issues})}},vendor:`zod`,version:1}))}),$ZodString=$constructor(`$ZodString`,(inst,def)=>{$ZodType.init(inst,def),inst._zod.pattern=[...inst?._zod.bag?.patterns??[]].pop()??string$1(inst._zod.bag),inst._zod.parse=(payload,_)=>{if(def.coerce)try{payload.value=String(payload.value)}catch{}return typeof payload.value==`string`||payload.issues.push({expected:`string`,code:`invalid_type`,input:payload.value,inst}),payload}}),$ZodStringFormat=$constructor(`$ZodStringFormat`,(inst,def)=>{$ZodCheckStringFormat.init(inst,def),$ZodString.init(inst,def)}),$ZodGUID=$constructor(`$ZodGUID`,(inst,def)=>{def.pattern??=guid,$ZodStringFormat.init(inst,def)}),$ZodUUID=$constructor(`$ZodUUID`,(inst,def)=>{if(def.version){let v={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[def.version];if(v===void 0)throw Error(`Invalid UUID version: "${def.version}"`);def.pattern??=uuid(v)}else def.pattern??=uuid();$ZodStringFormat.init(inst,def)}),$ZodEmail=$constructor(`$ZodEmail`,(inst,def)=>{def.pattern??=email,$ZodStringFormat.init(inst,def)}),$ZodURL=$constructor(`$ZodURL`,(inst,def)=>{$ZodStringFormat.init(inst,def),inst._zod.check=payload=>{try{let trimmed=payload.value.trim();if(!def.normalize&&def.protocol?.source===httpProtocol.source&&!/^https?:\/\//i.test(trimmed)){payload.issues.push({code:`invalid_format`,format:`url`,note:`Invalid URL format`,input:payload.value,inst,continue:!def.abort});return}let url=new URL(trimmed);def.hostname&&(def.hostname.lastIndex=0,def.hostname.test(url.hostname)||payload.issues.push({code:`invalid_format`,format:`url`,note:`Invalid hostname`,pattern:def.hostname.source,input:payload.value,inst,continue:!def.abort})),def.protocol&&(def.protocol.lastIndex=0,def.protocol.test(url.protocol.endsWith(`:`)?url.protocol.slice(0,-1):url.protocol)||payload.issues.push({code:`invalid_format`,format:`url`,note:`Invalid protocol`,pattern:def.protocol.source,input:payload.value,inst,continue:!def.abort})),def.normalize?payload.value=url.href:payload.value=trimmed;return}catch{payload.issues.push({code:`invalid_format`,format:`url`,input:payload.value,inst,continue:!def.abort})}}}),$ZodEmoji=$constructor(`$ZodEmoji`,(inst,def)=>{def.pattern??=emoji(),$ZodStringFormat.init(inst,def)}),$ZodNanoID=$constructor(`$ZodNanoID`,(inst,def)=>{def.pattern??=nanoid,$ZodStringFormat.init(inst,def)}),$ZodCUID=$constructor(`$ZodCUID`,(inst,def)=>{def.pattern??=cuid,$ZodStringFormat.init(inst,def)}),$ZodCUID2=$constructor(`$ZodCUID2`,(inst,def)=>{def.pattern??=cuid2,$ZodStringFormat.init(inst,def)}),$ZodULID=$constructor(`$ZodULID`,(inst,def)=>{def.pattern??=ulid,$ZodStringFormat.init(inst,def)}),$ZodXID=$constructor(`$ZodXID`,(inst,def)=>{def.pattern??=xid,$ZodStringFormat.init(inst,def)}),$ZodKSUID=$constructor(`$ZodKSUID`,(inst,def)=>{def.pattern??=ksuid,$ZodStringFormat.init(inst,def)}),$ZodISODateTime=$constructor(`$ZodISODateTime`,(inst,def)=>{def.pattern??=datetime$1(def),$ZodStringFormat.init(inst,def)}),$ZodISODate=$constructor(`$ZodISODate`,(inst,def)=>{def.pattern??=date$1,$ZodStringFormat.init(inst,def)}),$ZodISOTime=$constructor(`$ZodISOTime`,(inst,def)=>{def.pattern??=time$1(def),$ZodStringFormat.init(inst,def)}),$ZodISODuration=$constructor(`$ZodISODuration`,(inst,def)=>{def.pattern??=duration$1,$ZodStringFormat.init(inst,def)}),$ZodIPv4=$constructor(`$ZodIPv4`,(inst,def)=>{def.pattern??=ipv4,$ZodStringFormat.init(inst,def),inst._zod.bag.format=`ipv4`}),$ZodIPv6=$constructor(`$ZodIPv6`,(inst,def)=>{def.pattern??=ipv6,$ZodStringFormat.init(inst,def),inst._zod.bag.format=`ipv6`,inst._zod.check=payload=>{try{new URL(`http://[${payload.value}]`)}catch{payload.issues.push({code:`invalid_format`,format:`ipv6`,input:payload.value,inst,continue:!def.abort})}}}),$ZodCIDRv4=$constructor(`$ZodCIDRv4`,(inst,def)=>{def.pattern??=cidrv4,$ZodStringFormat.init(inst,def)}),$ZodCIDRv6=$constructor(`$ZodCIDRv6`,(inst,def)=>{def.pattern??=cidrv6,$ZodStringFormat.init(inst,def),inst._zod.check=payload=>{let parts=payload.value.split(`/`);try{if(parts.length!==2)throw Error();let[address,prefix]=parts;if(!prefix)throw Error();let prefixNum=Number(prefix);if(`${prefixNum}`!==prefix||prefixNum<0||prefixNum>128)throw Error();new URL(`http://[${address}]`)}catch{payload.issues.push({code:`invalid_format`,format:`cidrv6`,input:payload.value,inst,continue:!def.abort})}}});function isValidBase64(data){if(data===``)return!0;if(/\s/.test(data)||data.length%4!=0)return!1;try{return atob(data),!0}catch{return!1}}const $ZodBase64=$constructor(`$ZodBase64`,(inst,def)=>{def.pattern??=base64,$ZodStringFormat.init(inst,def),inst._zod.bag.contentEncoding=`base64`,inst._zod.check=payload=>{isValidBase64(payload.value)||payload.issues.push({code:`invalid_format`,format:`base64`,input:payload.value,inst,continue:!def.abort})}});function isValidBase64URL(data){if(!base64url.test(data))return!1;let base64=data.replace(/[-_]/g,c=>c===`-`?`+`:`/`);return isValidBase64(base64.padEnd(Math.ceil(base64.length/4)*4,`=`))}const $ZodBase64URL=$constructor(`$ZodBase64URL`,(inst,def)=>{def.pattern??=base64url,$ZodStringFormat.init(inst,def),inst._zod.bag.contentEncoding=`base64url`,inst._zod.check=payload=>{isValidBase64URL(payload.value)||payload.issues.push({code:`invalid_format`,format:`base64url`,input:payload.value,inst,continue:!def.abort})}}),$ZodE164=$constructor(`$ZodE164`,(inst,def)=>{def.pattern??=e164,$ZodStringFormat.init(inst,def)});function isValidJWT(token,algorithm=null){try{let tokensParts=token.split(`.`);if(tokensParts.length!==3)return!1;let[header]=tokensParts;if(!header)return!1;let parsedHeader=JSON.parse(atob(header));return!(`typ`in parsedHeader&&parsedHeader?.typ!==`JWT`||!parsedHeader.alg||algorithm&&(!(`alg`in parsedHeader)||parsedHeader.alg!==algorithm))}catch{return!1}}const $ZodJWT=$constructor(`$ZodJWT`,(inst,def)=>{$ZodStringFormat.init(inst,def),inst._zod.check=payload=>{isValidJWT(payload.value,def.alg)||payload.issues.push({code:`invalid_format`,format:`jwt`,input:payload.value,inst,continue:!def.abort})}});function handleArrayResult(result,final,index){result.issues.length&&final.issues.push(...prefixIssues(index,result.issues)),final.value[index]=result.value}const $ZodArray=$constructor(`$ZodArray`,(inst,def)=>{$ZodType.init(inst,def),inst._zod.parse=(payload,ctx)=>{let input=payload.value;if(!Array.isArray(input))return payload.issues.push({expected:`array`,code:`invalid_type`,input,inst}),payload;payload.value=Array(input.length);let proms=[];for(let i=0;i<input.length;i++){let item=input[i],result=def.element._zod.run({value:item,issues:[]},ctx);result instanceof Promise?proms.push(result.then(result=>handleArrayResult(result,payload,i))):handleArrayResult(result,payload,i)}return proms.length?Promise.all(proms).then(()=>payload):payload}});function handleUnionResults(results,final,inst,ctx){for(let result of results)if(result.issues.length===0)return final.value=result.value,final;let nonaborted=results.filter(r=>!aborted(r));return nonaborted.length===1?(final.value=nonaborted[0].value,nonaborted[0]):(final.issues.push({code:`invalid_union`,input:final.value,inst,errors:results.map(result=>result.issues.map(iss=>finalizeIssue(iss,ctx,config())))}),final)}const $ZodUnion=$constructor(`$ZodUnion`,(inst,def)=>{$ZodType.init(inst,def),defineLazy(inst._zod,`optin`,()=>def.options.some(o=>o._zod.optin===`optional`)?`optional`:void 0),defineLazy(inst._zod,`optout`,()=>def.options.some(o=>o._zod.optout===`optional`)?`optional`:void 0),defineLazy(inst._zod,`values`,()=>{if(def.options.every(o=>o._zod.values))return new Set(def.options.flatMap(option=>Array.from(option._zod.values)))}),defineLazy(inst._zod,`pattern`,()=>{if(def.options.every(o=>o._zod.pattern)){let patterns=def.options.map(o=>o._zod.pattern);return RegExp(`^(${patterns.map(p=>cleanRegex(p.source)).join(`|`)})$`)}});let first=def.options.length===1?def.options[0]._zod.run:null;inst._zod.parse=(payload,ctx)=>{if(first)return first(payload,ctx);let async=!1,results=[];for(let option of def.options){let result=option._zod.run({value:payload.value,issues:[]},ctx);if(result instanceof Promise)results.push(result),async=!0;else{if(result.issues.length===0)return result;results.push(result)}}return async?Promise.all(results).then(results=>handleUnionResults(results,payload,inst,ctx)):handleUnionResults(results,payload,inst,ctx)}}),$ZodIntersection=$constructor(`$ZodIntersection`,(inst,def)=>{$ZodType.init(inst,def),inst._zod.parse=(payload,ctx)=>{let input=payload.value,left=def.left._zod.run({value:input,issues:[]},ctx),right=def.right._zod.run({value:input,issues:[]},ctx);return left instanceof Promise||right instanceof Promise?Promise.all([left,right]).then(([left,right])=>handleIntersectionResults(payload,left,right)):handleIntersectionResults(payload,left,right)}});function mergeValues(a,b){if(a===b||a instanceof Date&&b instanceof Date&&+a==+b)return{valid:!0,data:a};if(isPlainObject(a)&&isPlainObject(b)){let bKeys=Object.keys(b),sharedKeys=Object.keys(a).filter(key=>bKeys.indexOf(key)!==-1),newObj={...a,...b};for(let key of sharedKeys){let sharedValue=mergeValues(a[key],b[key]);if(!sharedValue.valid)return{valid:!1,mergeErrorPath:[key,...sharedValue.mergeErrorPath]};newObj[key]=sharedValue.data}return{valid:!0,data:newObj}}if(Array.isArray(a)&&Array.isArray(b)){if(a.length!==b.length)return{valid:!1,mergeErrorPath:[]};let newArray=[];for(let index=0;index<a.length;index++){let itemA=a[index],itemB=b[index],sharedValue=mergeValues(itemA,itemB);if(!sharedValue.valid)return{valid:!1,mergeErrorPath:[index,...sharedValue.mergeErrorPath]};newArray.push(sharedValue.data)}return{valid:!0,data:newArray}}return{valid:!1,mergeErrorPath:[]}}function handleIntersectionResults(result,left,right){let unrecKeys=new Map,unrecIssue;for(let iss of left.issues)if(iss.code===`unrecognized_keys`){unrecIssue??=iss;for(let k of iss.keys)unrecKeys.has(k)||unrecKeys.set(k,{}),unrecKeys.get(k).l=!0}else result.issues.push(iss);for(let iss of right.issues)if(iss.code===`unrecognized_keys`)for(let k of iss.keys)unrecKeys.has(k)||unrecKeys.set(k,{}),unrecKeys.get(k).r=!0;else result.issues.push(iss);let bothKeys=[...unrecKeys].filter(([,f])=>f.l&&f.r).map(([k])=>k);if(bothKeys.length&&unrecIssue&&result.issues.push({...unrecIssue,keys:bothKeys}),aborted(result))return result;let merged=mergeValues(left.value,right.value);if(!merged.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(merged.mergeErrorPath)}`);return result.value=merged.data,result}const $ZodTransform=$constructor(`$ZodTransform`,(inst,def)=>{$ZodType.init(inst,def),inst._zod.optin=`optional`,inst._zod.parse=(payload,ctx)=>{if(ctx.direction===`backward`)throw new $ZodEncodeError(inst.constructor.name);let _out=def.transform(payload.value,payload);if(ctx.async)return(_out instanceof Promise?_out:Promise.resolve(_out)).then(output=>(payload.value=output,payload.fallback=!0,payload));if(_out instanceof Promise)throw new $ZodAsyncError;return payload.value=_out,payload.fallback=!0,payload}});function handleOptionalResult(result,input){return input===void 0&&(result.issues.length||result.fallback)?{issues:[],value:void 0}:result}const $ZodOptional=$constructor(`$ZodOptional`,(inst,def)=>{$ZodType.init(inst,def),inst._zod.optin=`optional`,inst._zod.optout=`optional`,defineLazy(inst._zod,`values`,()=>def.innerType._zod.values?new Set([...def.innerType._zod.values,void 0]):void 0),defineLazy(inst._zod,`pattern`,()=>{let pattern=def.innerType._zod.pattern;return pattern?RegExp(`^(${cleanRegex(pattern.source)})?$`):void 0}),inst._zod.parse=(payload,ctx)=>{if(def.innerType._zod.optin===`optional`){let input=payload.value,result=def.innerType._zod.run(payload,ctx);return result instanceof Promise?result.then(r=>handleOptionalResult(r,input)):handleOptionalResult(result,input)}return payload.value===void 0?payload:def.innerType._zod.run(payload,ctx)}}),$ZodExactOptional=$constructor(`$ZodExactOptional`,(inst,def)=>{$ZodOptional.init(inst,def),defineLazy(inst._zod,`values`,()=>def.innerType._zod.values),defineLazy(inst._zod,`pattern`,()=>def.innerType._zod.pattern),inst._zod.parse=(payload,ctx)=>def.innerType._zod.run(payload,ctx)}),$ZodNullable=$constructor(`$ZodNullable`,(inst,def)=>{$ZodType.init(inst,def),defineLazy(inst._zod,`optin`,()=>def.innerType._zod.optin),defineLazy(inst._zod,`optout`,()=>def.innerType._zod.optout),defineLazy(inst._zod,`pattern`,()=>{let pattern=def.innerType._zod.pattern;return pattern?RegExp(`^(${cleanRegex(pattern.source)}|null)$`):void 0}),defineLazy(inst._zod,`values`,()=>def.innerType._zod.values?new Set([...def.innerType._zod.values,null]):void 0),inst._zod.parse=(payload,ctx)=>payload.value===null?payload:def.innerType._zod.run(payload,ctx)}),$ZodDefault=$constructor(`$ZodDefault`,(inst,def)=>{$ZodType.init(inst,def),inst._zod.optin=`optional`,defineLazy(inst._zod,`values`,()=>def.innerType._zod.values),inst._zod.parse=(payload,ctx)=>{if(ctx.direction===`backward`)return def.innerType._zod.run(payload,ctx);if(payload.value===void 0)return payload.value=def.defaultValue,payload;let result=def.innerType._zod.run(payload,ctx);return result instanceof Promise?result.then(result=>handleDefaultResult(result,def)):handleDefaultResult(result,def)}});function handleDefaultResult(payload,def){return payload.value===void 0&&(payload.value=def.defaultValue),payload}const $ZodPrefault=$constructor(`$ZodPrefault`,(inst,def)=>{$ZodType.init(inst,def),inst._zod.optin=`optional`,defineLazy(inst._zod,`values`,()=>def.innerType._zod.values),inst._zod.parse=(payload,ctx)=>(ctx.direction===`backward`||payload.value===void 0&&(payload.value=def.defaultValue),def.innerType._zod.run(payload,ctx))}),$ZodNonOptional=$constructor(`$ZodNonOptional`,(inst,def)=>{$ZodType.init(inst,def),defineLazy(inst._zod,`values`,()=>{let v=def.innerType._zod.values;return v?new Set([...v].filter(x=>x!==void 0)):void 0}),inst._zod.parse=(payload,ctx)=>{let result=def.innerType._zod.run(payload,ctx);return result instanceof Promise?result.then(result=>handleNonOptionalResult(result,inst)):handleNonOptionalResult(result,inst)}});function handleNonOptionalResult(payload,inst){return!payload.issues.length&&payload.value===void 0&&payload.issues.push({code:`invalid_type`,expected:`nonoptional`,input:payload.value,inst}),payload}const $ZodCatch=$constructor(`$ZodCatch`,(inst,def)=>{$ZodType.init(inst,def),inst._zod.optin=`optional`,defineLazy(inst._zod,`optout`,()=>def.innerType._zod.optout),defineLazy(inst._zod,`values`,()=>def.innerType._zod.values),inst._zod.parse=(payload,ctx)=>{if(ctx.direction===`backward`)return def.innerType._zod.run(payload,ctx);let result=def.innerType._zod.run(payload,ctx);return result instanceof Promise?result.then(result=>(payload.value=result.value,result.issues.length&&(payload.value=def.catchValue({...payload,error:{issues:result.issues.map(iss=>finalizeIssue(iss,ctx,config()))},input:payload.value}),payload.issues=[],payload.fallback=!0),payload)):(payload.value=result.value,result.issues.length&&(payload.value=def.catchValue({...payload,error:{issues:result.issues.map(iss=>finalizeIssue(iss,ctx,config()))},input:payload.value}),payload.issues=[],payload.fallback=!0),payload)}}),$ZodPipe=$constructor(`$ZodPipe`,(inst,def)=>{$ZodType.init(inst,def),defineLazy(inst._zod,`values`,()=>def.in._zod.values),defineLazy(inst._zod,`optin`,()=>def.in._zod.optin),defineLazy(inst._zod,`optout`,()=>def.out._zod.optout),defineLazy(inst._zod,`propValues`,()=>def.in._zod.propValues),inst._zod.parse=(payload,ctx)=>{if(ctx.direction===`backward`){let right=def.out._zod.run(payload,ctx);return right instanceof Promise?right.then(right=>handlePipeResult(right,def.in,ctx)):handlePipeResult(right,def.in,ctx)}let left=def.in._zod.run(payload,ctx);return left instanceof Promise?left.then(left=>handlePipeResult(left,def.out,ctx)):handlePipeResult(left,def.out,ctx)}});function handlePipeResult(left,next,ctx){return left.issues.length?(left.aborted=!0,left):next._zod.run({value:left.value,issues:left.issues,fallback:left.fallback},ctx)}const $ZodReadonly=$constructor(`$ZodReadonly`,(inst,def)=>{$ZodType.init(inst,def),defineLazy(inst._zod,`propValues`,()=>def.innerType._zod.propValues),defineLazy(inst._zod,`values`,()=>def.innerType._zod.values),defineLazy(inst._zod,`optin`,()=>def.innerType?._zod?.optin),defineLazy(inst._zod,`optout`,()=>def.innerType?._zod?.optout),inst._zod.parse=(payload,ctx)=>{if(ctx.direction===`backward`)return def.innerType._zod.run(payload,ctx);let result=def.innerType._zod.run(payload,ctx);return result instanceof Promise?result.then(handleReadonlyResult):handleReadonlyResult(result)}});function handleReadonlyResult(payload){return payload.value=Object.freeze(payload.value),payload}const $ZodCustom=$constructor(`$ZodCustom`,(inst,def)=>{$ZodCheck.init(inst,def),$ZodType.init(inst,def),inst._zod.parse=(payload,_)=>payload,inst._zod.check=payload=>{let input=payload.value,r=def.fn(input);if(r instanceof Promise)return r.then(r=>handleRefineResult(r,payload,input,inst));handleRefineResult(r,payload,input,inst)}});function handleRefineResult(result,payload,input,inst){if(!result){let _iss={code:`custom`,input,inst,path:[...inst._zod.def.path??[]],continue:!inst._zod.def.abort};inst._zod.def.params&&(_iss.params=inst._zod.def.params),payload.issues.push(issue(_iss))}}var _a,$ZodRegistry=class{constructor(){this._map=new WeakMap,this._idmap=new Map}add(schema,..._meta){let meta=_meta[0];return this._map.set(schema,meta),meta&&typeof meta==`object`&&`id`in meta&&this._idmap.set(meta.id,schema),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(schema){let meta=this._map.get(schema);return meta&&typeof meta==`object`&&`id`in meta&&this._idmap.delete(meta.id),this._map.delete(schema),this}get(schema){let p=schema._zod.parent;if(p){let pm={...this.get(p)??{}};delete pm.id;let f={...pm,...this._map.get(schema)};return Object.keys(f).length?f:void 0}return this._map.get(schema)}has(schema){return this._map.has(schema)}};function registry(){return new $ZodRegistry}(_a=globalThis).__zod_globalRegistry??(_a.__zod_globalRegistry=registry());const globalRegistry=globalThis.__zod_globalRegistry;function _string(Class,params){return new Class({type:`string`,...normalizeParams(params)})}function _email(Class,params){return new Class({type:`string`,format:`email`,check:`string_format`,abort:!1,...normalizeParams(params)})}function _guid(Class,params){return new Class({type:`string`,format:`guid`,check:`string_format`,abort:!1,...normalizeParams(params)})}function _uuid(Class,params){return new Class({type:`string`,format:`uuid`,check:`string_format`,abort:!1,...normalizeParams(params)})}function _uuidv4(Class,params){return new Class({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v4`,...normalizeParams(params)})}function _uuidv6(Class,params){return new Class({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v6`,...normalizeParams(params)})}function _uuidv7(Class,params){return new Class({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v7`,...normalizeParams(params)})}function _url(Class,params){return new Class({type:`string`,format:`url`,check:`string_format`,abort:!1,...normalizeParams(params)})}function _emoji(Class,params){return new Class({type:`string`,format:`emoji`,check:`string_format`,abort:!1,...normalizeParams(params)})}function _nanoid(Class,params){return new Class({type:`string`,format:`nanoid`,check:`string_format`,abort:!1,...normalizeParams(params)})}function _cuid(Class,params){return new Class({type:`string`,format:`cuid`,check:`string_format`,abort:!1,...normalizeParams(params)})}function _cuid2(Class,params){return new Class({type:`string`,format:`cuid2`,check:`string_format`,abort:!1,...normalizeParams(params)})}function _ulid(Class,params){return new Class({type:`string`,format:`ulid`,check:`string_format`,abort:!1,...normalizeParams(params)})}function _xid(Class,params){return new Class({type:`string`,format:`xid`,check:`string_format`,abort:!1,...normalizeParams(params)})}function _ksuid(Class,params){return new Class({type:`string`,format:`ksuid`,check:`string_format`,abort:!1,...normalizeParams(params)})}function _ipv4(Class,params){return new Class({type:`string`,format:`ipv4`,check:`string_format`,abort:!1,...normalizeParams(params)})}function _ipv6(Class,params){return new Class({type:`string`,format:`ipv6`,check:`string_format`,abort:!1,...normalizeParams(params)})}function _cidrv4(Class,params){return new Class({type:`string`,format:`cidrv4`,check:`string_format`,abort:!1,...normalizeParams(params)})}function _cidrv6(Class,params){return new Class({type:`string`,format:`cidrv6`,check:`string_format`,abort:!1,...normalizeParams(params)})}function _base64(Class,params){return new Class({type:`string`,format:`base64`,check:`string_format`,abort:!1,...normalizeParams(params)})}function _base64url(Class,params){return new Class({type:`string`,format:`base64url`,check:`string_format`,abort:!1,...normalizeParams(params)})}function _e164(Class,params){return new Class({type:`string`,format:`e164`,check:`string_format`,abort:!1,...normalizeParams(params)})}function _jwt(Class,params){return new Class({type:`string`,format:`jwt`,check:`string_format`,abort:!1,...normalizeParams(params)})}function _isoDateTime(Class,params){return new Class({type:`string`,format:`datetime`,check:`string_format`,offset:!1,local:!1,precision:null,...normalizeParams(params)})}function _isoDate(Class,params){return new Class({type:`string`,format:`date`,check:`string_format`,...normalizeParams(params)})}function _isoTime(Class,params){return new Class({type:`string`,format:`time`,check:`string_format`,precision:null,...normalizeParams(params)})}function _isoDuration(Class,params){return new Class({type:`string`,format:`duration`,check:`string_format`,...normalizeParams(params)})}function _maxLength(maximum,params){return new $ZodCheckMaxLength({check:`max_length`,...normalizeParams(params),maximum})}function _minLength(minimum,params){return new $ZodCheckMinLength({check:`min_length`,...normalizeParams(params),minimum})}function _length(length,params){return new $ZodCheckLengthEquals({check:`length_equals`,...normalizeParams(params),length})}function _regex(pattern,params){return new $ZodCheckRegex({check:`string_format`,format:`regex`,...normalizeParams(params),pattern})}function _lowercase(params){return new $ZodCheckLowerCase({check:`string_format`,format:`lowercase`,...normalizeParams(params)})}function _uppercase(params){return new $ZodCheckUpperCase({check:`string_format`,format:`uppercase`,...normalizeParams(params)})}function _includes(includes,params){return new $ZodCheckIncludes({check:`string_format`,format:`includes`,...normalizeParams(params),includes})}function _startsWith(prefix,params){return new $ZodCheckStartsWith({check:`string_format`,format:`starts_with`,...normalizeParams(params),prefix})}function _endsWith(suffix,params){return new $ZodCheckEndsWith({check:`string_format`,format:`ends_with`,...normalizeParams(params),suffix})}function _overwrite(tx){return new $ZodCheckOverwrite({check:`overwrite`,tx})}function _normalize(form){return _overwrite(input=>input.normalize(form))}function _trim(){return _overwrite(input=>input.trim())}function _toLowerCase(){return _overwrite(input=>input.toLowerCase())}function _toUpperCase(){return _overwrite(input=>input.toUpperCase())}function _slugify(){return _overwrite(input=>slugify(input))}function _array(Class,element,params){return new Class({type:`array`,element,...normalizeParams(params)})}function _refine(Class,fn,_params){return new Class({type:`custom`,check:`custom`,fn,...normalizeParams(_params)})}function _superRefine(fn,params){let ch=_check(payload=>(payload.addIssue=issue$2=>{if(typeof issue$2==`string`)payload.issues.push(issue(issue$2,payload.value,ch._zod.def));else{let _issue=issue$2;_issue.fatal&&(_issue.continue=!1),_issue.code??=`custom`,_issue.input??=payload.value,_issue.inst??=ch,_issue.continue??=!ch._zod.def.abort,payload.issues.push(issue(_issue))}},fn(payload.value,payload)),params);return ch}function _check(fn,params){let ch=new $ZodCheck({check:`custom`,...normalizeParams(params)});return ch._zod.check=fn,ch}function initializeContext(params){let target=params?.target??`draft-2020-12`;return target===`draft-4`&&(target=`draft-04`),target===`draft-7`&&(target=`draft-07`),{processors:params.processors??{},metadataRegistry:params?.metadata??globalRegistry,target,unrepresentable:params?.unrepresentable??`throw`,override:params?.override??(()=>{}),io:params?.io??`output`,counter:0,seen:new Map,cycles:params?.cycles??`ref`,reused:params?.reused??`inline`,external:params?.external??void 0}}function process$1(schema,ctx,_params={path:[],schemaPath:[]}){var _a;let def=schema._zod.def,seen=ctx.seen.get(schema);if(seen)return seen.count++,_params.schemaPath.includes(schema)&&(seen.cycle=_params.path),seen.schema;let result={schema:{},count:1,cycle:void 0,path:_params.path};ctx.seen.set(schema,result);let overrideSchema=schema._zod.toJSONSchema?.();if(overrideSchema)result.schema=overrideSchema;else{let params={..._params,schemaPath:[..._params.schemaPath,schema],path:_params.path};if(schema._zod.processJSONSchema)schema._zod.processJSONSchema(ctx,result.schema,params);else{let _json=result.schema,processor=ctx.processors[def.type];if(!processor)throw Error(`[toJSONSchema]: Non-representable type encountered: ${def.type}`);processor(schema,ctx,_json,params)}let parent=schema._zod.parent;parent&&(result.ref||=parent,process$1(parent,ctx,params),ctx.seen.get(parent).isParent=!0)}let meta=ctx.metadataRegistry.get(schema);return meta&&Object.assign(result.schema,meta),ctx.io===`input`&&isTransforming(schema)&&(delete result.schema.examples,delete result.schema.default),ctx.io===`input`&&`_prefault`in result.schema&&((_a=result.schema).default??(_a.default=result.schema._prefault)),delete result.schema._prefault,ctx.seen.get(schema).schema}function extractDefs(ctx,schema){let root=ctx.seen.get(schema);if(!root)throw Error(`Unprocessed schema. This is a bug in Zod.`);let idToSchema=new Map;for(let entry of ctx.seen.entries()){let id=ctx.metadataRegistry.get(entry[0])?.id;if(id){let existing=idToSchema.get(id);if(existing&&existing!==entry[0])throw Error(`Duplicate schema id "${id}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);idToSchema.set(id,entry[0])}}let makeURI=entry=>{let defsSegment=ctx.target===`draft-2020-12`?`$defs`:`definitions`;if(ctx.external){let externalId=ctx.external.registry.get(entry[0])?.id,uriGenerator=ctx.external.uri??(id=>id);if(externalId)return{ref:uriGenerator(externalId)};let id=entry[1].defId??entry[1].schema.id??`schema${ctx.counter++}`;return entry[1].defId=id,{defId:id,ref:`${uriGenerator(`__shared`)}#/${defsSegment}/${id}`}}if(entry[1]===root)return{ref:`#`};let defUriPrefix=`#/${defsSegment}/`,defId=entry[1].schema.id??`__schema${ctx.counter++}`;return{defId,ref:defUriPrefix+defId}},extractToDef=entry=>{if(entry[1].schema.$ref)return;let seen=entry[1],{ref,defId}=makeURI(entry);seen.def={...seen.schema},defId&&(seen.defId=defId);let schema=seen.schema;for(let key in schema)delete schema[key];schema.$ref=ref};if(ctx.cycles===`throw`)for(let entry of ctx.seen.entries()){let seen=entry[1];if(seen.cycle)throw Error(`Cycle detected: #/${seen.cycle?.join(`/`)}/<root>
6
-
7
- Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let entry of ctx.seen.entries()){let seen=entry[1];if(schema===entry[0]){extractToDef(entry);continue}if(ctx.external){let ext=ctx.external.registry.get(entry[0])?.id;if(schema!==entry[0]&&ext){extractToDef(entry);continue}}if(ctx.metadataRegistry.get(entry[0])?.id){extractToDef(entry);continue}if(seen.cycle){extractToDef(entry);continue}if(seen.count>1&&ctx.reused===`ref`){extractToDef(entry);continue}}}function finalize(ctx,schema){let root=ctx.seen.get(schema);if(!root)throw Error(`Unprocessed schema. This is a bug in Zod.`);let flattenRef=zodSchema=>{let seen=ctx.seen.get(zodSchema);if(seen.ref===null)return;let schema=seen.def??seen.schema,_cached={...schema},ref=seen.ref;if(seen.ref=null,ref){flattenRef(ref);let refSeen=ctx.seen.get(ref),refSchema=refSeen.schema;if(refSchema.$ref&&(ctx.target===`draft-07`||ctx.target===`draft-04`||ctx.target===`openapi-3.0`)?(schema.allOf=schema.allOf??[],schema.allOf.push(refSchema)):Object.assign(schema,refSchema),Object.assign(schema,_cached),zodSchema._zod.parent===ref)for(let key in schema)key===`$ref`||key===`allOf`||key in _cached||delete schema[key];if(refSchema.$ref&&refSeen.def)for(let key in schema)key===`$ref`||key===`allOf`||key in refSeen.def&&JSON.stringify(schema[key])===JSON.stringify(refSeen.def[key])&&delete schema[key]}let parent=zodSchema._zod.parent;if(parent&&parent!==ref){flattenRef(parent);let parentSeen=ctx.seen.get(parent);if(parentSeen?.schema.$ref&&(schema.$ref=parentSeen.schema.$ref,parentSeen.def))for(let key in schema)key===`$ref`||key===`allOf`||key in parentSeen.def&&JSON.stringify(schema[key])===JSON.stringify(parentSeen.def[key])&&delete schema[key]}ctx.override({zodSchema,jsonSchema:schema,path:seen.path??[]})};for(let entry of[...ctx.seen.entries()].reverse())flattenRef(entry[0]);let result={};if(ctx.target===`draft-2020-12`?result.$schema=`https://json-schema.org/draft/2020-12/schema`:ctx.target===`draft-07`?result.$schema=`http://json-schema.org/draft-07/schema#`:ctx.target===`draft-04`?result.$schema=`http://json-schema.org/draft-04/schema#`:ctx.target,ctx.external?.uri){let id=ctx.external.registry.get(schema)?.id;if(!id)throw Error("Schema is missing an `id` property");result.$id=ctx.external.uri(id)}Object.assign(result,root.def??root.schema);let rootMetaId=ctx.metadataRegistry.get(schema)?.id;rootMetaId!==void 0&&result.id===rootMetaId&&delete result.id;let defs=ctx.external?.defs??{};for(let entry of ctx.seen.entries()){let seen=entry[1];seen.def&&seen.defId&&(seen.def.id===seen.defId&&delete seen.def.id,defs[seen.defId]=seen.def)}ctx.external||Object.keys(defs).length>0&&(ctx.target===`draft-2020-12`?result.$defs=defs:result.definitions=defs);try{let finalized=JSON.parse(JSON.stringify(result));return Object.defineProperty(finalized,"~standard",{value:{...schema[`~standard`],jsonSchema:{input:createStandardJSONSchemaMethod(schema,`input`,ctx.processors),output:createStandardJSONSchemaMethod(schema,`output`,ctx.processors)}},enumerable:!1,writable:!1}),finalized}catch{throw Error(`Error converting schema to JSON.`)}}function isTransforming(_schema,_ctx){let ctx=_ctx??{seen:new Set};if(ctx.seen.has(_schema))return!1;ctx.seen.add(_schema);let def=_schema._zod.def;if(def.type===`transform`)return!0;if(def.type===`array`)return isTransforming(def.element,ctx);if(def.type===`set`)return isTransforming(def.valueType,ctx);if(def.type===`lazy`)return isTransforming(def.getter(),ctx);if(def.type===`promise`||def.type===`optional`||def.type===`nonoptional`||def.type===`nullable`||def.type===`readonly`||def.type==="default"||def.type===`prefault`)return isTransforming(def.innerType,ctx);if(def.type===`intersection`)return isTransforming(def.left,ctx)||isTransforming(def.right,ctx);if(def.type===`record`||def.type===`map`)return isTransforming(def.keyType,ctx)||isTransforming(def.valueType,ctx);if(def.type===`pipe`)return _schema._zod.traits.has(`$ZodCodec`)?!0:isTransforming(def.in,ctx)||isTransforming(def.out,ctx);if(def.type===`object`){for(let key in def.shape)if(isTransforming(def.shape[key],ctx))return!0;return!1}if(def.type===`union`){for(let option of def.options)if(isTransforming(option,ctx))return!0;return!1}if(def.type===`tuple`){for(let item of def.items)if(isTransforming(item,ctx))return!0;return!!(def.rest&&isTransforming(def.rest,ctx))}return!1}const createToJSONSchemaMethod=(schema,processors={})=>params=>{let ctx=initializeContext({...params,processors});return process$1(schema,ctx),extractDefs(ctx,schema),finalize(ctx,schema)},createStandardJSONSchemaMethod=(schema,io,processors={})=>params=>{let{libraryOptions,target}=params??{},ctx=initializeContext({...libraryOptions??{},target,io,processors});return process$1(schema,ctx),extractDefs(ctx,schema),finalize(ctx,schema)},formatMap={guid:`uuid`,url:`uri`,datetime:`date-time`,json_string:`json-string`,regex:``},stringProcessor=(schema,ctx,_json,_params)=>{let json=_json;json.type=`string`;let{minimum,maximum,format,patterns,contentEncoding}=schema._zod.bag;if(typeof minimum==`number`&&(json.minLength=minimum),typeof maximum==`number`&&(json.maxLength=maximum),format&&(json.format=formatMap[format]??format,json.format===``&&delete json.format,format===`time`&&delete json.format),contentEncoding&&(json.contentEncoding=contentEncoding),patterns&&patterns.size>0){let regexes=[...patterns];regexes.length===1?json.pattern=regexes[0].source:regexes.length>1&&(json.allOf=[...regexes.map(regex=>({...ctx.target===`draft-07`||ctx.target===`draft-04`||ctx.target===`openapi-3.0`?{type:`string`}:{},pattern:regex.source}))])}},customProcessor=(_schema,ctx,_json,_params)=>{if(ctx.unrepresentable===`throw`)throw Error(`Custom types cannot be represented in JSON Schema`)},transformProcessor=(_schema,ctx,_json,_params)=>{if(ctx.unrepresentable===`throw`)throw Error(`Transforms cannot be represented in JSON Schema`)},arrayProcessor=(schema,ctx,_json,params)=>{let json=_json,def=schema._zod.def,{minimum,maximum}=schema._zod.bag;typeof minimum==`number`&&(json.minItems=minimum),typeof maximum==`number`&&(json.maxItems=maximum),json.type=`array`,json.items=process$1(def.element,ctx,{...params,path:[...params.path,`items`]})},unionProcessor=(schema,ctx,json,params)=>{let def=schema._zod.def,isExclusive=def.inclusive===!1,options=def.options.map((x,i)=>process$1(x,ctx,{...params,path:[...params.path,isExclusive?`oneOf`:`anyOf`,i]}));isExclusive?json.oneOf=options:json.anyOf=options},intersectionProcessor=(schema,ctx,json,params)=>{let def=schema._zod.def,a=process$1(def.left,ctx,{...params,path:[...params.path,`allOf`,0]}),b=process$1(def.right,ctx,{...params,path:[...params.path,`allOf`,1]}),isSimpleIntersection=val=>`allOf`in val&&Object.keys(val).length===1;json.allOf=[...isSimpleIntersection(a)?a.allOf:[a],...isSimpleIntersection(b)?b.allOf:[b]]},nullableProcessor=(schema,ctx,json,params)=>{let def=schema._zod.def,inner=process$1(def.innerType,ctx,params),seen=ctx.seen.get(schema);ctx.target===`openapi-3.0`?(seen.ref=def.innerType,json.nullable=!0):json.anyOf=[inner,{type:`null`}]},nonoptionalProcessor=(schema,ctx,_json,params)=>{let def=schema._zod.def;process$1(def.innerType,ctx,params);let seen=ctx.seen.get(schema);seen.ref=def.innerType},defaultProcessor=(schema,ctx,json,params)=>{let def=schema._zod.def;process$1(def.innerType,ctx,params);let seen=ctx.seen.get(schema);seen.ref=def.innerType,json.default=JSON.parse(JSON.stringify(def.defaultValue))},prefaultProcessor=(schema,ctx,json,params)=>{let def=schema._zod.def;process$1(def.innerType,ctx,params);let seen=ctx.seen.get(schema);seen.ref=def.innerType,ctx.io===`input`&&(json._prefault=JSON.parse(JSON.stringify(def.defaultValue)))},catchProcessor=(schema,ctx,json,params)=>{let def=schema._zod.def;process$1(def.innerType,ctx,params);let seen=ctx.seen.get(schema);seen.ref=def.innerType;let catchValue;try{catchValue=def.catchValue(void 0)}catch{throw Error(`Dynamic catch values are not supported in JSON Schema`)}json.default=catchValue},pipeProcessor=(schema,ctx,_json,params)=>{let def=schema._zod.def,inIsTransform=def.in._zod.traits.has(`$ZodTransform`),innerType=ctx.io===`input`?inIsTransform?def.out:def.in:def.out;process$1(innerType,ctx,params);let seen=ctx.seen.get(schema);seen.ref=innerType},readonlyProcessor=(schema,ctx,json,params)=>{let def=schema._zod.def;process$1(def.innerType,ctx,params);let seen=ctx.seen.get(schema);seen.ref=def.innerType,json.readOnly=!0},optionalProcessor=(schema,ctx,_json,params)=>{let def=schema._zod.def;process$1(def.innerType,ctx,params);let seen=ctx.seen.get(schema);seen.ref=def.innerType},ZodISODateTime=$constructor(`ZodISODateTime`,(inst,def)=>{$ZodISODateTime.init(inst,def),ZodStringFormat.init(inst,def)});function datetime(params){return _isoDateTime(ZodISODateTime,params)}const ZodISODate=$constructor(`ZodISODate`,(inst,def)=>{$ZodISODate.init(inst,def),ZodStringFormat.init(inst,def)});function date(params){return _isoDate(ZodISODate,params)}const ZodISOTime=$constructor(`ZodISOTime`,(inst,def)=>{$ZodISOTime.init(inst,def),ZodStringFormat.init(inst,def)});function time(params){return _isoTime(ZodISOTime,params)}const ZodISODuration=$constructor(`ZodISODuration`,(inst,def)=>{$ZodISODuration.init(inst,def),ZodStringFormat.init(inst,def)});function duration(params){return _isoDuration(ZodISODuration,params)}const ZodRealError=$constructor(`ZodError`,(inst,issues)=>{$ZodError.init(inst,issues),inst.name=`ZodError`,Object.defineProperties(inst,{format:{value:mapper=>formatError(inst,mapper)},flatten:{value:mapper=>flattenError(inst,mapper)},addIssue:{value:issue=>{inst.issues.push(issue),inst.message=JSON.stringify(inst.issues,jsonStringifyReplacer,2)}},addIssues:{value:issues=>{inst.issues.push(...issues),inst.message=JSON.stringify(inst.issues,jsonStringifyReplacer,2)}},isEmpty:{get(){return inst.issues.length===0}}})},{Parent:Error}),parse=_parse(ZodRealError),parseAsync=_parseAsync(ZodRealError),safeParse=_safeParse(ZodRealError),safeParseAsync=_safeParseAsync(ZodRealError),encode=_encode(ZodRealError),decode=_decode(ZodRealError),encodeAsync=_encodeAsync(ZodRealError),decodeAsync=_decodeAsync(ZodRealError),safeEncode=_safeEncode(ZodRealError),safeDecode=_safeDecode(ZodRealError),safeEncodeAsync=_safeEncodeAsync(ZodRealError),safeDecodeAsync=_safeDecodeAsync(ZodRealError),_installedGroups=new WeakMap;function _installLazyMethods(inst,group,methods){let proto=Object.getPrototypeOf(inst),installed=_installedGroups.get(proto);if(installed||(installed=new Set,_installedGroups.set(proto,installed)),!installed.has(group)){installed.add(group);for(let key in methods){let fn=methods[key];Object.defineProperty(proto,key,{configurable:!0,enumerable:!1,get(){let bound=fn.bind(this);return Object.defineProperty(this,key,{configurable:!0,writable:!0,enumerable:!0,value:bound}),bound},set(v){Object.defineProperty(this,key,{configurable:!0,writable:!0,enumerable:!0,value:v})}})}}}const ZodType=$constructor(`ZodType`,(inst,def)=>($ZodType.init(inst,def),Object.assign(inst[`~standard`],{jsonSchema:{input:createStandardJSONSchemaMethod(inst,`input`),output:createStandardJSONSchemaMethod(inst,`output`)}}),inst.toJSONSchema=createToJSONSchemaMethod(inst,{}),inst.def=def,inst.type=def.type,Object.defineProperty(inst,"_def",{value:def}),inst.parse=(data,params)=>parse(inst,data,params,{callee:inst.parse}),inst.safeParse=(data,params)=>safeParse(inst,data,params),inst.parseAsync=async(data,params)=>parseAsync(inst,data,params,{callee:inst.parseAsync}),inst.safeParseAsync=async(data,params)=>safeParseAsync(inst,data,params),inst.spa=inst.safeParseAsync,inst.encode=(data,params)=>encode(inst,data,params),inst.decode=(data,params)=>decode(inst,data,params),inst.encodeAsync=async(data,params)=>encodeAsync(inst,data,params),inst.decodeAsync=async(data,params)=>decodeAsync(inst,data,params),inst.safeEncode=(data,params)=>safeEncode(inst,data,params),inst.safeDecode=(data,params)=>safeDecode(inst,data,params),inst.safeEncodeAsync=async(data,params)=>safeEncodeAsync(inst,data,params),inst.safeDecodeAsync=async(data,params)=>safeDecodeAsync(inst,data,params),_installLazyMethods(inst,`ZodType`,{check(...chks){let def=this.def;return this.clone(mergeDefs(def,{checks:[...def.checks??[],...chks.map(ch=>typeof ch==`function`?{_zod:{check:ch,def:{check:`custom`},onattach:[]}}:ch)]}),{parent:!0})},with(...chks){return this.check(...chks)},clone(def,params){return clone(this,def,params)},brand(){return this},register(reg,meta){return reg.add(this,meta),this},refine(check,params){return this.check(refine(check,params))},superRefine(refinement,params){return this.check(superRefine(refinement,params))},overwrite(fn){return this.check(_overwrite(fn))},optional(){return optional(this)},exactOptional(){return exactOptional(this)},nullable(){return nullable(this)},nullish(){return optional(nullable(this))},nonoptional(params){return nonoptional(this,params)},array(){return array(this)},or(arg){return union([this,arg])},and(arg){return intersection(this,arg)},transform(tx){return pipe(this,transform(tx))},default(d){return _default(this,d)},prefault(d){return prefault(this,d)},catch(params){return _catch(this,params)},pipe(target){return pipe(this,target)},readonly(){return readonly(this)},describe(description){let cl=this.clone();return globalRegistry.add(cl,{description}),cl},meta(...args){if(args.length===0)return globalRegistry.get(this);let cl=this.clone();return globalRegistry.add(cl,args[0]),cl},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(fn){return fn(this)}}),Object.defineProperty(inst,"description",{get(){return globalRegistry.get(inst)?.description},configurable:!0}),inst)),_ZodString=$constructor(`_ZodString`,(inst,def)=>{$ZodString.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>stringProcessor(inst,ctx,json,params);let bag=inst._zod.bag;inst.format=bag.format??null,inst.minLength=bag.minimum??null,inst.maxLength=bag.maximum??null,_installLazyMethods(inst,`_ZodString`,{regex(...args){return this.check(_regex(...args))},includes(...args){return this.check(_includes(...args))},startsWith(...args){return this.check(_startsWith(...args))},endsWith(...args){return this.check(_endsWith(...args))},min(...args){return this.check(_minLength(...args))},max(...args){return this.check(_maxLength(...args))},length(...args){return this.check(_length(...args))},nonempty(...args){return this.check(_minLength(1,...args))},lowercase(params){return this.check(_lowercase(params))},uppercase(params){return this.check(_uppercase(params))},trim(){return this.check(_trim())},normalize(...args){return this.check(_normalize(...args))},toLowerCase(){return this.check(_toLowerCase())},toUpperCase(){return this.check(_toUpperCase())},slugify(){return this.check(_slugify())}})}),ZodString=$constructor(`ZodString`,(inst,def)=>{$ZodString.init(inst,def),_ZodString.init(inst,def),inst.email=params=>inst.check(_email(ZodEmail,params)),inst.url=params=>inst.check(_url(ZodURL,params)),inst.jwt=params=>inst.check(_jwt(ZodJWT,params)),inst.emoji=params=>inst.check(_emoji(ZodEmoji,params)),inst.guid=params=>inst.check(_guid(ZodGUID,params)),inst.uuid=params=>inst.check(_uuid(ZodUUID,params)),inst.uuidv4=params=>inst.check(_uuidv4(ZodUUID,params)),inst.uuidv6=params=>inst.check(_uuidv6(ZodUUID,params)),inst.uuidv7=params=>inst.check(_uuidv7(ZodUUID,params)),inst.nanoid=params=>inst.check(_nanoid(ZodNanoID,params)),inst.guid=params=>inst.check(_guid(ZodGUID,params)),inst.cuid=params=>inst.check(_cuid(ZodCUID,params)),inst.cuid2=params=>inst.check(_cuid2(ZodCUID2,params)),inst.ulid=params=>inst.check(_ulid(ZodULID,params)),inst.base64=params=>inst.check(_base64(ZodBase64,params)),inst.base64url=params=>inst.check(_base64url(ZodBase64URL,params)),inst.xid=params=>inst.check(_xid(ZodXID,params)),inst.ksuid=params=>inst.check(_ksuid(ZodKSUID,params)),inst.ipv4=params=>inst.check(_ipv4(ZodIPv4,params)),inst.ipv6=params=>inst.check(_ipv6(ZodIPv6,params)),inst.cidrv4=params=>inst.check(_cidrv4(ZodCIDRv4,params)),inst.cidrv6=params=>inst.check(_cidrv6(ZodCIDRv6,params)),inst.e164=params=>inst.check(_e164(ZodE164,params)),inst.datetime=params=>inst.check(datetime(params)),inst.date=params=>inst.check(date(params)),inst.time=params=>inst.check(time(params)),inst.duration=params=>inst.check(duration(params))});function string(params){return _string(ZodString,params)}const ZodStringFormat=$constructor(`ZodStringFormat`,(inst,def)=>{$ZodStringFormat.init(inst,def),_ZodString.init(inst,def)}),ZodEmail=$constructor(`ZodEmail`,(inst,def)=>{$ZodEmail.init(inst,def),ZodStringFormat.init(inst,def)}),ZodGUID=$constructor(`ZodGUID`,(inst,def)=>{$ZodGUID.init(inst,def),ZodStringFormat.init(inst,def)}),ZodUUID=$constructor(`ZodUUID`,(inst,def)=>{$ZodUUID.init(inst,def),ZodStringFormat.init(inst,def)}),ZodURL=$constructor(`ZodURL`,(inst,def)=>{$ZodURL.init(inst,def),ZodStringFormat.init(inst,def)}),ZodEmoji=$constructor(`ZodEmoji`,(inst,def)=>{$ZodEmoji.init(inst,def),ZodStringFormat.init(inst,def)}),ZodNanoID=$constructor(`ZodNanoID`,(inst,def)=>{$ZodNanoID.init(inst,def),ZodStringFormat.init(inst,def)}),ZodCUID=$constructor(`ZodCUID`,(inst,def)=>{$ZodCUID.init(inst,def),ZodStringFormat.init(inst,def)}),ZodCUID2=$constructor(`ZodCUID2`,(inst,def)=>{$ZodCUID2.init(inst,def),ZodStringFormat.init(inst,def)}),ZodULID=$constructor(`ZodULID`,(inst,def)=>{$ZodULID.init(inst,def),ZodStringFormat.init(inst,def)}),ZodXID=$constructor(`ZodXID`,(inst,def)=>{$ZodXID.init(inst,def),ZodStringFormat.init(inst,def)}),ZodKSUID=$constructor(`ZodKSUID`,(inst,def)=>{$ZodKSUID.init(inst,def),ZodStringFormat.init(inst,def)}),ZodIPv4=$constructor(`ZodIPv4`,(inst,def)=>{$ZodIPv4.init(inst,def),ZodStringFormat.init(inst,def)}),ZodIPv6=$constructor(`ZodIPv6`,(inst,def)=>{$ZodIPv6.init(inst,def),ZodStringFormat.init(inst,def)}),ZodCIDRv4=$constructor(`ZodCIDRv4`,(inst,def)=>{$ZodCIDRv4.init(inst,def),ZodStringFormat.init(inst,def)}),ZodCIDRv6=$constructor(`ZodCIDRv6`,(inst,def)=>{$ZodCIDRv6.init(inst,def),ZodStringFormat.init(inst,def)}),ZodBase64=$constructor(`ZodBase64`,(inst,def)=>{$ZodBase64.init(inst,def),ZodStringFormat.init(inst,def)}),ZodBase64URL=$constructor(`ZodBase64URL`,(inst,def)=>{$ZodBase64URL.init(inst,def),ZodStringFormat.init(inst,def)}),ZodE164=$constructor(`ZodE164`,(inst,def)=>{$ZodE164.init(inst,def),ZodStringFormat.init(inst,def)}),ZodJWT=$constructor(`ZodJWT`,(inst,def)=>{$ZodJWT.init(inst,def),ZodStringFormat.init(inst,def)}),ZodArray=$constructor(`ZodArray`,(inst,def)=>{$ZodArray.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>arrayProcessor(inst,ctx,json,params),inst.element=def.element,_installLazyMethods(inst,`ZodArray`,{min(n,params){return this.check(_minLength(n,params))},nonempty(params){return this.check(_minLength(1,params))},max(n,params){return this.check(_maxLength(n,params))},length(n,params){return this.check(_length(n,params))},unwrap(){return this.element}})});function array(element,params){return _array(ZodArray,element,params)}const ZodUnion=$constructor(`ZodUnion`,(inst,def)=>{$ZodUnion.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>unionProcessor(inst,ctx,json,params),inst.options=def.options});function union(options,params){return new ZodUnion({type:`union`,options,...normalizeParams(params)})}const ZodIntersection=$constructor(`ZodIntersection`,(inst,def)=>{$ZodIntersection.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>intersectionProcessor(inst,ctx,json,params)});function intersection(left,right){return new ZodIntersection({type:`intersection`,left,right})}const ZodTransform=$constructor(`ZodTransform`,(inst,def)=>{$ZodTransform.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>transformProcessor(inst,ctx,json,params),inst._zod.parse=(payload,_ctx)=>{if(_ctx.direction===`backward`)throw new $ZodEncodeError(inst.constructor.name);payload.addIssue=issue$1=>{if(typeof issue$1==`string`)payload.issues.push(issue(issue$1,payload.value,def));else{let _issue=issue$1;_issue.fatal&&(_issue.continue=!1),_issue.code??=`custom`,_issue.input??=payload.value,_issue.inst??=inst,payload.issues.push(issue(_issue))}};let output=def.transform(payload.value,payload);return output instanceof Promise?output.then(output=>(payload.value=output,payload.fallback=!0,payload)):(payload.value=output,payload.fallback=!0,payload)}});function transform(fn){return new ZodTransform({type:`transform`,transform:fn})}const ZodOptional=$constructor(`ZodOptional`,(inst,def)=>{$ZodOptional.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>optionalProcessor(inst,ctx,json,params),inst.unwrap=()=>inst._zod.def.innerType});function optional(innerType){return new ZodOptional({type:`optional`,innerType})}const ZodExactOptional=$constructor(`ZodExactOptional`,(inst,def)=>{$ZodExactOptional.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>optionalProcessor(inst,ctx,json,params),inst.unwrap=()=>inst._zod.def.innerType});function exactOptional(innerType){return new ZodExactOptional({type:`optional`,innerType})}const ZodNullable=$constructor(`ZodNullable`,(inst,def)=>{$ZodNullable.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>nullableProcessor(inst,ctx,json,params),inst.unwrap=()=>inst._zod.def.innerType});function nullable(innerType){return new ZodNullable({type:`nullable`,innerType})}const ZodDefault=$constructor(`ZodDefault`,(inst,def)=>{$ZodDefault.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>defaultProcessor(inst,ctx,json,params),inst.unwrap=()=>inst._zod.def.innerType,inst.removeDefault=inst.unwrap});function _default(innerType,defaultValue){return new ZodDefault({type:`default`,innerType,get defaultValue(){return typeof defaultValue==`function`?defaultValue():shallowClone(defaultValue)}})}const ZodPrefault=$constructor(`ZodPrefault`,(inst,def)=>{$ZodPrefault.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>prefaultProcessor(inst,ctx,json,params),inst.unwrap=()=>inst._zod.def.innerType});function prefault(innerType,defaultValue){return new ZodPrefault({type:`prefault`,innerType,get defaultValue(){return typeof defaultValue==`function`?defaultValue():shallowClone(defaultValue)}})}const ZodNonOptional=$constructor(`ZodNonOptional`,(inst,def)=>{$ZodNonOptional.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>nonoptionalProcessor(inst,ctx,json,params),inst.unwrap=()=>inst._zod.def.innerType});function nonoptional(innerType,params){return new ZodNonOptional({type:`nonoptional`,innerType,...normalizeParams(params)})}const ZodCatch=$constructor(`ZodCatch`,(inst,def)=>{$ZodCatch.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>catchProcessor(inst,ctx,json,params),inst.unwrap=()=>inst._zod.def.innerType,inst.removeCatch=inst.unwrap});function _catch(innerType,catchValue){return new ZodCatch({type:`catch`,innerType,catchValue:typeof catchValue==`function`?catchValue:()=>catchValue})}const ZodPipe=$constructor(`ZodPipe`,(inst,def)=>{$ZodPipe.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>pipeProcessor(inst,ctx,json,params),inst.in=def.in,inst.out=def.out});function pipe(in_,out){return new ZodPipe({type:`pipe`,in:in_,out})}const ZodReadonly=$constructor(`ZodReadonly`,(inst,def)=>{$ZodReadonly.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>readonlyProcessor(inst,ctx,json,params),inst.unwrap=()=>inst._zod.def.innerType});function readonly(innerType){return new ZodReadonly({type:`readonly`,innerType})}const ZodCustom=$constructor(`ZodCustom`,(inst,def)=>{$ZodCustom.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>customProcessor(inst,ctx,json,params)});function refine(fn,_params={}){return _refine(ZodCustom,fn,_params)}function superRefine(fn,params){return _superRefine(fn,params)}const projectNameSchema=string().min(1,`Project name cannot be empty.`).max(214,`Project name must be 214 characters or fewer.`).regex(/^[a-z0-9][a-z0-9._-]*$/u,`Project name must start with a lowercase letter or number, and can only contain letters, numbers, dots, hyphens, and underscores.`).refine(val=>!/[._-]$/u.test(val),`Project name must not end with a dot, hyphen, or underscore.`).refine(val=>!/__/u.test(val),`Project name must not contain consecutive underscores.`).refine(val=>!/[._-]{2,}/u.test(val),`Project name must not contain consecutive dots, hyphens, or underscores.`),validateProjectName=name=>{let result=projectNameSchema.safeParse(name);return result.success?null:result.error.issues[0]?.message??`Invalid project name.`},isCI=()=>process.env.CI===`true`||process.env.CI===`1`||process.env.CIRCLECI===`true`||!!process.env.GITHUB_ACTIONS||!!process.env.GITLAB_CI,ciOrYes=options=>options?.yes===!0||isCI(),promptOrSkip=async(prompt,clack)=>{let result=await prompt(clack);return clack.isCancel(result)&&(clack.cancel(`Cancelled.`),process.exit(0)),result},collectPrompts=async(clack,projectDir,options)=>{let cwd=process.cwd(),resolvedDir,projectName;projectDir?(resolvedDir=path.resolve(cwd,projectDir),projectName=path.basename(resolvedDir)):ciOrYes(options)?(projectName=`studio-project`,resolvedDir=path.resolve(cwd,projectName)):(projectName=(await promptOrSkip(p=>p.text({defaultValue:`studio-project`,message:`What's your project name?`,validate:value=>{let trimmed=value.trim();return trimmed.length===0?`Please enter a project name.`:validateProjectName(trimmed)}}),clack)).trim(),resolvedDir=path.resolve(cwd,projectName)),!ciOrYes(options)&&existsSync(resolvedDir)&&(await promptOrSkip(p=>p.confirm({initialValue:!1,message:`Directory "${projectName}" already exists. Overwrite?`}),clack)||(clack.cancel(`Cancelled.`),process.exit(0)));let templates=ciOrYes(options)?[`bento-feature`]:await promptOrSkip(p=>p.multiselect({message:`Which templates would you like to scaffold?`,options:[{hint:`Apple-style feature card`,label:`Bento Feature`,value:`bento-feature`}]}),clack),locales=ciOrYes(options)?[`en`,`ar`]:await promptOrSkip(p=>p.multiselect({message:`Which locales would you like to include?`,options:[{label:`English`,value:`en`},{label:`Arabic`,value:`ar`}]}),clack),alreadyInGitRepo=isInsideGitRepo(path.dirname(resolvedDir)),wantsGit=!alreadyInGitRepo&&ciOrYes(options);!alreadyInGitRepo&&!ciOrYes(options)&&(wantsGit=await promptOrSkip(p=>p.confirm({initialValue:!0,message:`Initialize a git repository?`}),clack));let shouldInstall=ciOrYes(options)?!0:await promptOrSkip(p=>p.confirm({initialValue:!0,message:`Install dependencies?`}),clack);return{locales,projectName,resolvedDir,shouldInstall,templates,wantsGit}},getScaffoldVersion=()=>{try{return createRequire(import.meta.url)(`@stdout-design/cli/package.json`).version}catch{return`latest`}},getDefaults=()=>({defaultPreset:`instagram-square`,presets:[{height:1080,id:`instagram-square`,platform:`instagram`,width:1080},{height:1200,id:`x-card`,platform:`x`,width:1200}],templates:{"bento-feature":{componentPath:`./templates/bento-feature`,description:`Apple-style bento feature card.`}}}),getConfigTemplate=version=>`import type { StudioConfig } from "@stdout-design/cli";
4
+ `)},formatError=error=>error instanceof Error?`Error: ${error.message}`:`Error: ${String(error)}`,formatCacheCleanResult=freedBytes=>`Cache cleared. Freed ${formatBytes(freedBytes)}.`,cacheStats=async(rootDir,options)=>{let cache=await openCache(rootDir??process.cwd()),stats=await cache.stats();cache.close(),options.json?console.log(JSON.stringify(stats,null,2)):console.log(formatCacheStats(stats))},cacheClean=async(rootDir,options)=>{let cache=await openCache(rootDir??process.cwd()),result=await cache.clean();cache.close(),options.json?console.log(JSON.stringify(result)):console.log(formatCacheCleanResult(result.freedBytes))},findWebUiDist=()=>{try{let pkgJsonPath=createRequire(import.meta.url).resolve(`@stdout-design/web-ui/package.json`),pkgDir=path.dirname(pkgJsonPath);return path.join(pkgDir,`dist`)}catch{}},dev=async(rootDir,options)=>{let{startStandaloneServer}=await import(`@stdout-design/dev-server`).catch(()=>{throw Error([`studio dev requires a scaffolded project with @stdout-design/dev-server installed.`,"Run `studio init` to create one, or install it manually:",``,` bun add @stdout-design/dev-server`,``,`See https://stdout.design/docs for more information.`].join(`
5
+ `))}),resolvedRoot=rootDir??process.cwd(),port=Number(options.port??`3000`),webUiDist=findWebUiDist();console.log(`Starting studio dev server for ${resolvedRoot}...`),await startStandaloneServer({port,rootDir:resolvedRoot,webUiDist})},isInsideGitRepo=dir=>{let current=path.resolve(dir);for(;;){if(existsSync(path.join(current,`.git`)))return!0;let parent=path.dirname(current);if(parent===current)break;current=parent}return!1},tryGitInit=dir=>{try{execSync(`git --version`,{stdio:`ignore`})}catch{return!1}if(existsSync(path.join(dir,`.git`))||isInsideGitRepo(path.dirname(dir)))return!1;try{return execSync(`git init`,{cwd:dir,stdio:`ignore`}),execSync(`git checkout -b main`,{cwd:dir,stdio:`ignore`}),execSync(`git add .`,{cwd:dir,stdio:`ignore`}),execSync(`git commit -m "Initial commit from stdout-design"`,{cwd:dir,stdio:`ignore`}),!0}catch{if(existsSync(path.join(dir,`.git`)))try{execSync(`rm -rf .git`,{cwd:dir,stdio:`ignore`})}catch{}return!1}},projectNameSchema=z.string().min(1,`Project name cannot be empty.`).max(214,`Project name must be 214 characters or fewer.`).regex(/^[a-z0-9][a-z0-9._-]*$/u,`Project name must start with a lowercase letter or number, and can only contain letters, numbers, dots, hyphens, and underscores.`).refine(val=>!/[._-]$/u.test(val),`Project name must not end with a dot, hyphen, or underscore.`).refine(val=>!/__/u.test(val),`Project name must not contain consecutive underscores.`).refine(val=>!/[._-]{2,}/u.test(val),`Project name must not contain consecutive dots, hyphens, or underscores.`),validateProjectName=name=>{let result=projectNameSchema.safeParse(name);return result.success?null:result.error.issues[0]?.message??`Invalid project name.`},isCI=()=>process.env.CI===`true`||process.env.CI===`1`||process.env.CIRCLECI===`true`||!!process.env.GITHUB_ACTIONS||!!process.env.GITLAB_CI,ciOrYes=options=>options?.yes===!0||isCI(),promptOrSkip=async(prompt,clack)=>{let result=await prompt(clack);return clack.isCancel(result)&&(clack.cancel(`Cancelled.`),process.exit(0)),result},collectPrompts=async(clack,projectDir,options)=>{let cwd=process.cwd(),resolvedDir,projectName;projectDir?(resolvedDir=path.resolve(cwd,projectDir),projectName=path.basename(resolvedDir)):ciOrYes(options)?(projectName=`studio-project`,resolvedDir=path.resolve(cwd,projectName)):(projectName=(await promptOrSkip(p=>p.text({defaultValue:`studio-project`,message:`What's your project name?`,validate:value=>{let trimmed=value.trim();return trimmed.length===0?`Please enter a project name.`:validateProjectName(trimmed)}}),clack)).trim(),resolvedDir=path.resolve(cwd,projectName)),!ciOrYes(options)&&existsSync(resolvedDir)&&(await promptOrSkip(p=>p.confirm({initialValue:!1,message:`Directory "${projectName}" already exists. Overwrite?`}),clack)||(clack.cancel(`Cancelled.`),process.exit(0)));let templates=ciOrYes(options)?[`bento-feature`]:await promptOrSkip(p=>p.multiselect({message:`Which templates would you like to scaffold?`,options:[{hint:`Apple-style feature card`,label:`Bento Feature`,value:`bento-feature`}]}),clack),locales=ciOrYes(options)?[`en`,`ar`]:await promptOrSkip(p=>p.multiselect({message:`Which locales would you like to include?`,options:[{label:`English`,value:`en`},{label:`Arabic`,value:`ar`}]}),clack),alreadyInGitRepo=isInsideGitRepo(path.dirname(resolvedDir)),wantsGit=!alreadyInGitRepo&&ciOrYes(options);!alreadyInGitRepo&&!ciOrYes(options)&&(wantsGit=await promptOrSkip(p=>p.confirm({initialValue:!0,message:`Initialize a git repository?`}),clack));let shouldInstall=ciOrYes(options)?!0:await promptOrSkip(p=>p.confirm({initialValue:!0,message:`Install dependencies?`}),clack);return{locales,projectName,resolvedDir,shouldInstall,templates,wantsGit}},getScaffoldVersion=()=>{try{return createRequire(import.meta.url)(`@stdout-design/cli/package.json`).version}catch{return`latest`}},getDefaults=()=>({defaultPreset:`instagram-square`,presets:[{height:1080,id:`instagram-square`,platform:`instagram`,width:1080},{height:1200,id:`x-card`,platform:`x`,width:1200}],templates:{"bento-feature":{componentPath:`./templates/bento-feature`,description:`Apple-style bento feature card.`}}}),getConfigTemplate=version=>`import type { StudioConfig } from "@stdout-design/cli";
8
6
 
9
7
  const config: StudioConfig = {
10
8
  scaffoldVersion: "${version}",
@@ -23,9 +21,9 @@ const config: StudioConfig = {
23
21
  };
24
22
 
25
23
  export default config;
26
- `,getPkgJson=(name,version)=>({name,private:!0,type:`module`,scripts:{build:`studio build`,dev:`studio dev`,export:`studio export`},dependencies:{"@stdout-design/cli":`^${version}`,"@stdout-design/dev-server":`^${version}`,"@stdout-design/web-ui":`^${version}`,"@types/react":`^19.2.17`}}),resolveTemplateDir=()=>{let fromDist=path.resolve(import.meta.dirname,`../template`);return existsSync(path.resolve(fromDist,`tsconfig.json`))?fromDist:path.resolve(import.meta.dirname,`../../../template`)},resolveTemplatesDir=()=>path.resolve(resolveTemplateDir(),`templates`),copyStaticAssets=async dir=>{let base=resolveTemplateDir();await Promise.all([cp(path.resolve(base,`tsconfig.json`),path.resolve(dir,`tsconfig.json`)),cp(path.resolve(base,`gitignore`),path.resolve(dir,`.gitignore`)),cp(path.resolve(base,`types.d.ts`),path.resolve(dir,`types.d.ts`))])},generateConfig=async(dir,version)=>{await writeFile(path.resolve(dir,`studio.config.ts`),getConfigTemplate(version))},generatePackageJson=async(dir,projectName,version)=>{await writeFile(path.resolve(dir,`package.json`),JSON.stringify(getPkgJson(projectName,version),null,2))},copyTemplateFiles=async(dir,templates)=>{if(templates.length===0)return;let dstTemplatesDir=path.resolve(dir,`templates`);await mkdir(dstTemplatesDir,{recursive:!0});let srcTemplatesDir=resolveTemplatesDir();for(let template of templates)if(!existsSync(path.resolve(srcTemplatesDir,`${template}.tsx`)))throw Error(`Template "${template}" not found at templates/${template}.tsx`);await Promise.all(templates.map(template=>cp(path.resolve(srcTemplatesDir,`${template}.tsx`),path.resolve(dstTemplatesDir,`${template}.tsx`))))},createLocaleFiles=async(dir,locales)=>{if(locales.length===0)return;let localesDir=path.resolve(dir,`locales`);await mkdir(localesDir,{recursive:!0});let localeData={ar:{title:`التطبيق المميز`},en:{title:`Featured App`}};await Promise.all(locales.map(locale=>writeFile(path.resolve(localesDir,`${locale}.json`),JSON.stringify(localeData[locale]??{title:`Featured App`},null,2))))},scaffold=async(dir,options)=>{if(options.projectName.trim().length===0)throw Error(`Project name cannot be empty.`);let version=getScaffoldVersion();existsSync(dir)||await mkdir(dir,{recursive:!0}),await copyStaticAssets(dir),await generateConfig(dir,version),await generatePackageJson(dir,options.projectName,version),await copyTemplateFiles(dir,options.templates),await createLocaleFiles(dir,options.locales)},detectPackageManager=async cwd=>{let detected=await detect({cwd});return detected?detected.name:`npm`},runInstall=(dir,pm)=>{let resolved=resolveCommand(pm,`install`,[]);if(!resolved)return;let{command,args}=resolved;spawnSync(command,args,{cwd:dir,stdio:`inherit`})},init=async(projectDir,options)=>{let{intro,outro,spinner}=await import(`@clack/prompts`);intro(`studio init`);let cwd=process.cwd();if(existsSync(path.resolve(cwd,projectDir??`.`,`studio.config.ts`))){console.log(`studio.config.ts already exists — skipping scaffold.`),outro(`Done`);return}let collected=await collectPrompts(await import(`@clack/prompts`),projectDir,options),s=spinner();if(s.start(`Creating project...`),await scaffold(collected.resolvedDir,{git:collected.wantsGit,install:collected.shouldInstall,locales:collected.locales,projectName:collected.projectName,templates:collected.templates}),s.stop(`Project created`),collected.wantsGit){let gitSpinner=spinner();gitSpinner.start(`Initializing git...`);let initialized=tryGitInit(collected.resolvedDir);gitSpinner.stop(initialized?`Git initialized`:`Git repo already exists or git is not available`)}let pm=await detectPackageManager(cwd);if(collected.shouldInstall){let installSpinner=spinner();installSpinner.start(`Installing dependencies...`),runInstall(collected.resolvedDir,pm),installSpinner.stop(`Dependencies installed`)}console.log(``),console.log(` Created project at ${collected.resolvedDir}`),console.log(``),console.log(` Next steps:`),console.log(` cd ${path.relative(cwd,collected.resolvedDir)||`.`}`),console.log(` ${pm} run dev`),console.log(``),outro(`Done`)},lint=_rootDir=>{console.error(`Lint command not yet implemented. Coming in a future release.`),process.exit(1)},coerceValue=(value,type,_items)=>{switch(type){case`number`:{let n=Number(value);return Number.isNaN(n)?value:n}case`boolean`:return value===`true`||value===`1`?!0:value===`false`||value===`0`?!1:value;case`array`:if(value.startsWith(`[`)&&value.endsWith(`]`))try{return JSON.parse(value)}catch{return value.split(`,`).map(s=>s.trim())}return value.split(`,`).map(s=>s.trim());default:return value}},parsePropArgs=(args,schema)=>{let props={},properties=schema.properties??{};for(let arg of args){let eqIndex=arg.indexOf(`=`);if(eqIndex===-1){props[arg]=!0;continue}let key=arg.slice(0,eqIndex),value=arg.slice(eqIndex+1),field=properties[key];props[key]=field?coerceValue(value,field.type,field.items):value}return props},mergeDefaultProps=(schema,props)=>{let properties=schema.properties??{},merged={};for(let[key,field]of Object.entries(properties))field.default!==void 0&&(merged[key]=field.default);return{...merged,...props}},levenshteinDistance=(a,b)=>{let aLen=a.length,bLen=b.length;if(aLen===0)return bLen;if(bLen===0)return aLen;let prev=Array.from({length:aLen+1},(_,j)=>j),curr=Array.from({length:aLen+1}).fill(0);for(let j=1;j<=bLen;j+=1){curr[0]=j;for(let i=1;i<=aLen;i+=1){let cost=b[j-1]===a[i-1]?0:1;curr[i]=Math.min((prev[i]??0)+1,(curr[i-1]??0)+1,(prev[i-1]??0)+cost)}let tmp=prev;prev=curr,curr=tmp}return prev[aLen]??0},suggestClosest=(input,candidates,maxDistance=3)=>{let best,bestDistance=1/0;for(let candidate of candidates){let dist=levenshteinDistance(input.toLowerCase(),candidate.toLowerCase());dist<bestDistance&&dist<=maxDistance&&(bestDistance=dist,best=candidate)}return best},resolveTemplate=(config,templateId)=>{let entry=config.templates[templateId];if(!entry){let candidates=Object.keys(config.templates),suggestion=suggestClosest(templateId,candidates),hint=suggestion?` Did you mean "${suggestion}"?`:``;throw new AppError(ErrorCode.TEMPLATE_NOT_FOUND,`Template "${templateId}" not found in studio.config.ts.${hint}`,{availableTemplates:candidates,templateId})}return{componentPath:entry.componentPath,templateId}},resolveBatchOptions=(config,options)=>{let presetIds=options?.preset?options.preset.split(`,`).map(s=>s.trim()):config.presets.map(p=>p.id),localeIds=options?.locale?options.locale.split(`,`).map(s=>s.trim()):void 0;return{concurrency:Number(options?.concurrency??`4`),dataFile:options?.data,failFast:options?.failFast,locales:localeIds,outDir:options?.outDir??config.outDir??`out`,presets:presetIds}},render=async(templateId,propArgs,options)=>{let rootDir=process.cwd(),config=await loadConfig(rootDir),{module}=await importTemplateForBatch(rootDir,resolveTemplate(config,templateId).componentPath,templateId),schema=zodToJsonSchemaShape(module.propsSchema),mergedProps=mergeDefaultProps(schema,parsePropArgs(propArgs,schema)),batchOpts=resolveBatchOptions(config,options),{manifest}=await runBatch({baseProps:mergedProps,concurrency:batchOpts.concurrency,dataFile:batchOpts.dataFile,failFast:batchOpts.failFast,locales:batchOpts.locales,outDir:batchOpts.outDir,presets:batchOpts.presets,rootDir,rows:batchOpts.dataFile?void 0:[{}],templateId});options.json?console.log(JSON.stringify(manifest,null,2)):console.log(formatManifestSummary(manifest)),manifest.failed.length>0&&process.exit(1)},updatePackageJsonDeps=(contents,currentVersion)=>{let pkg=JSON.parse(contents),deps=pkg.dependencies??={},currentRange=`^${currentVersion}`;return deps[`@stdout-design/cli`]===currentRange?{changed:!1,updated:contents}:(deps[`@stdout-design/cli`]=currentRange,{changed:!0,updated:JSON.stringify(pkg,null,2)})},mergePresets=(existing,defaults,deprecatedPresetIds)=>{let existingIds=new Set(existing.presets.map(p=>p.id)),addedPresets=[],presets=[...existing.presets];for(let defaultPreset of defaults.presets)if(!existingIds.has(defaultPreset.id)){let marked=deprecatedPresetIds.has(defaultPreset.id)?{...defaultPreset,deprecated:!0}:{...defaultPreset};presets.push(marked),addedPresets.push(defaultPreset.id)}let presetsWithDeprecation=presets.map(p=>deprecatedPresetIds.has(p.id)&&!p.deprecated?{...p,deprecated:!0}:p);return{addedPresets,deprecatedPresets:[...new Set(presetsWithDeprecation.filter(p=>p.deprecated).map(p=>p.id))],presets:presetsWithDeprecation}},mergeTemplates=(existing,defaults)=>{let addedTemplates=[],templates={...existing.templates};for(let[key,template]of Object.entries(defaults.templates))key in templates||(templates[key]={...template},addedTemplates.push(key));return{addedTemplates,templates}},resolveDefaultPreset=(presets,existing,defaults)=>{let mergedIds=new Set(presets.map(p=>p.id)),current=existing.defaultPreset;return current&&mergedIds.has(current)?current:defaults.defaultPreset??defaults.presets[0]?.id},mergeConfig=(existing,defaults,currentVersion,deprecatedPresetIds)=>{let oldVersion=existing.scaffoldVersion??null,{presets,addedPresets,deprecatedPresets}=mergePresets(existing,defaults,deprecatedPresetIds),{templates,addedTemplates}=mergeTemplates(existing,defaults);return{config:{...existing,defaultPreset:resolveDefaultPreset(presets,existing,defaults),presets,scaffoldVersion:currentVersion,templates},summary:{addedPresets,addedTemplates,deprecatedPresets,newVersion:currentVersion,oldVersion}}},DEPRECATED_PRESET_IDS=new Set,serializeConfig=config=>`import type { StudioConfig } from "@stdout-design/cli";
24
+ `,getPkgJson=(name,version)=>({name,private:!0,type:`module`,scripts:{build:`studio build`,dev:`studio dev`,export:`studio export`},dependencies:{"@stdout-design/cli":`^${version}`,"@stdout-design/dev-server":`^${version}`,"@stdout-design/web-ui":`^${version}`,"@types/react":`^19.2.17`,react:`^19.2.7`,"react-dom":`^19.2.7`,zod:`^4.4.3`}}),resolveTemplateDir=()=>{let fromDist=path.resolve(import.meta.dirname,`../template`);return existsSync(path.resolve(fromDist,`tsconfig.json`))?fromDist:path.resolve(import.meta.dirname,`../../../template`)},resolveTemplatesDir=()=>path.resolve(resolveTemplateDir(),`templates`),copyStaticAssets=async dir=>{let base=resolveTemplateDir();await Promise.all([cp(path.resolve(base,`tsconfig.json`),path.resolve(dir,`tsconfig.json`)),cp(path.resolve(base,`gitignore`),path.resolve(dir,`.gitignore`)),cp(path.resolve(base,`types.d.ts`),path.resolve(dir,`types.d.ts`))])},generateConfig=async(dir,version)=>{await writeFile(path.resolve(dir,`studio.config.ts`),getConfigTemplate(version))},generatePackageJson=async(dir,projectName,version)=>{await writeFile(path.resolve(dir,`package.json`),JSON.stringify(getPkgJson(projectName,version),null,2))},copyTemplateFiles=async(dir,templates)=>{if(templates.length===0)return;let dstTemplatesDir=path.resolve(dir,`templates`);await mkdir(dstTemplatesDir,{recursive:!0});let srcTemplatesDir=resolveTemplatesDir();for(let template of templates)if(!existsSync(path.resolve(srcTemplatesDir,`${template}.tsx`)))throw Error(`Template "${template}" not found at templates/${template}.tsx`);await Promise.all(templates.map(template=>cp(path.resolve(srcTemplatesDir,`${template}.tsx`),path.resolve(dstTemplatesDir,`${template}.tsx`))))},createLocaleFiles=async(dir,locales)=>{if(locales.length===0)return;let localesDir=path.resolve(dir,`locales`);await mkdir(localesDir,{recursive:!0});let localeData={ar:{title:`التطبيق المميز`},en:{title:`Featured App`}};await Promise.all(locales.map(locale=>writeFile(path.resolve(localesDir,`${locale}.json`),JSON.stringify(localeData[locale]??{title:`Featured App`},null,2))))},scaffold=async(dir,options)=>{if(options.projectName.trim().length===0)throw Error(`Project name cannot be empty.`);let version=getScaffoldVersion();existsSync(dir)||await mkdir(dir,{recursive:!0}),await copyStaticAssets(dir),await generateConfig(dir,version),await generatePackageJson(dir,options.projectName,version),await copyTemplateFiles(dir,options.templates),await createLocaleFiles(dir,options.locales)},detectPackageManager=async cwd=>{let detected=await detect({cwd});return detected?detected.name:`npm`},runInstall=(dir,pm)=>{let resolved=resolveCommand(pm,`install`,[]);if(!resolved)return;let{command,args}=resolved;spawnSync(command,args,{cwd:dir,stdio:`inherit`})},init=async(projectDir,options)=>{let{intro,outro,spinner}=await import(`@clack/prompts`);intro(`studio init`);let cwd=process.cwd();if(existsSync(path.resolve(cwd,projectDir??`.`,`studio.config.ts`))){console.log(`studio.config.ts already exists — skipping scaffold.`),outro(`Done`);return}let collected=await collectPrompts(await import(`@clack/prompts`),projectDir,options),s=spinner();if(s.start(`Creating project...`),await scaffold(collected.resolvedDir,{git:collected.wantsGit,install:collected.shouldInstall,locales:collected.locales,projectName:collected.projectName,templates:collected.templates}),s.stop(`Project created`),collected.wantsGit){let gitSpinner=spinner();gitSpinner.start(`Initializing git...`);let initialized=tryGitInit(collected.resolvedDir);gitSpinner.stop(initialized?`Git initialized`:`Git repo already exists or git is not available`)}let pm=await detectPackageManager(cwd);if(collected.shouldInstall){let installSpinner=spinner();installSpinner.start(`Installing dependencies...`),runInstall(collected.resolvedDir,pm),installSpinner.stop(`Dependencies installed`)}console.log(``),console.log(` Created project at ${collected.resolvedDir}`),console.log(``),console.log(` Next steps:`),console.log(` cd ${path.relative(cwd,collected.resolvedDir)||`.`}`),console.log(` ${pm} run dev`),console.log(``),outro(`Done`)},lint=_rootDir=>{console.error(`Lint command not yet implemented. Coming in a future release.`),process.exit(1)},coerceValue=(value,type,_items)=>{switch(type){case`number`:{let n=Number(value);return Number.isNaN(n)?value:n}case`boolean`:return value===`true`||value===`1`?!0:value===`false`||value===`0`?!1:value;case`array`:if(value.startsWith(`[`)&&value.endsWith(`]`))try{return JSON.parse(value)}catch{return value.split(`,`).map(s=>s.trim())}return value.split(`,`).map(s=>s.trim());default:return value}},parsePropArgs=(args,schema)=>{let props={},properties=schema.properties??{};for(let arg of args){let eqIndex=arg.indexOf(`=`);if(eqIndex===-1){props[arg]=!0;continue}let key=arg.slice(0,eqIndex),value=arg.slice(eqIndex+1),field=properties[key];props[key]=field?coerceValue(value,field.type,field.items):value}return props},mergeDefaultProps=(schema,props)=>{let properties=schema.properties??{},merged={};for(let[key,field]of Object.entries(properties))field.default!==void 0&&(merged[key]=field.default);return{...merged,...props}},levenshteinDistance=(a,b)=>{let aLen=a.length,bLen=b.length;if(aLen===0)return bLen;if(bLen===0)return aLen;let prev=Array.from({length:aLen+1},(_,j)=>j),curr=Array.from({length:aLen+1}).fill(0);for(let j=1;j<=bLen;j+=1){curr[0]=j;for(let i=1;i<=aLen;i+=1){let cost=b[j-1]===a[i-1]?0:1;curr[i]=Math.min((prev[i]??0)+1,(curr[i-1]??0)+1,(prev[i-1]??0)+cost)}let tmp=prev;prev=curr,curr=tmp}return prev[aLen]??0},suggestClosest=(input,candidates,maxDistance=3)=>{let best,bestDistance=1/0;for(let candidate of candidates){let dist=levenshteinDistance(input.toLowerCase(),candidate.toLowerCase());dist<bestDistance&&dist<=maxDistance&&(bestDistance=dist,best=candidate)}return best},resolveTemplate=(config,templateId)=>{let entry=config.templates[templateId];if(!entry){let candidates=Object.keys(config.templates),suggestion=suggestClosest(templateId,candidates),hint=suggestion?` Did you mean "${suggestion}"?`:``;throw new AppError(ErrorCode.TEMPLATE_NOT_FOUND,`Template "${templateId}" not found in studio.config.ts.${hint}`,{availableTemplates:candidates,templateId})}return{componentPath:entry.componentPath,templateId}},resolveBatchOptions=(config,options)=>{let presetIds=options?.preset?options.preset.split(`,`).map(s=>s.trim()):config.presets.map(p=>p.id),localeIds=options?.locale?options.locale.split(`,`).map(s=>s.trim()):void 0;return{concurrency:Number(options?.concurrency??`4`),dataFile:options?.data,failFast:options?.failFast,locales:localeIds,outDir:options?.outDir??config.outDir??`out`,presets:presetIds}},render=async(templateId,propArgs,options)=>{let rootDir=process.cwd(),config=await loadConfig(rootDir),{module}=await importTemplateForBatch(rootDir,resolveTemplate(config,templateId).componentPath,templateId),schema=zodToJsonSchemaShape(module.propsSchema),mergedProps=mergeDefaultProps(schema,parsePropArgs(propArgs,schema)),batchOpts=resolveBatchOptions(config,options),{manifest}=await runBatch({baseProps:mergedProps,concurrency:batchOpts.concurrency,dataFile:batchOpts.dataFile,failFast:batchOpts.failFast,locales:batchOpts.locales,outDir:batchOpts.outDir,presets:batchOpts.presets,rootDir,rows:batchOpts.dataFile?void 0:[{}],templateId});options.json?console.log(JSON.stringify(manifest,null,2)):console.log(formatManifestSummary(manifest)),manifest.failed.length>0&&process.exit(1)},updatePackageJsonDeps=(contents,currentVersion)=>{let pkg=JSON.parse(contents),deps=pkg.dependencies??={},currentRange=`^${currentVersion}`;return deps[`@stdout-design/cli`]===currentRange?{changed:!1,updated:contents}:(deps[`@stdout-design/cli`]=currentRange,{changed:!0,updated:JSON.stringify(pkg,null,2)})},mergePresets=(existing,defaults,deprecatedPresetIds)=>{let existingIds=new Set(existing.presets.map(p=>p.id)),addedPresets=[],presets=[...existing.presets];for(let defaultPreset of defaults.presets)if(!existingIds.has(defaultPreset.id)){let marked=deprecatedPresetIds.has(defaultPreset.id)?{...defaultPreset,deprecated:!0}:{...defaultPreset};presets.push(marked),addedPresets.push(defaultPreset.id)}let presetsWithDeprecation=presets.map(p=>deprecatedPresetIds.has(p.id)&&!p.deprecated?{...p,deprecated:!0}:p);return{addedPresets,deprecatedPresets:[...new Set(presetsWithDeprecation.filter(p=>p.deprecated).map(p=>p.id))],presets:presetsWithDeprecation}},mergeTemplates=(existing,defaults)=>{let addedTemplates=[],templates={...existing.templates};for(let[key,template]of Object.entries(defaults.templates))key in templates||(templates[key]={...template},addedTemplates.push(key));return{addedTemplates,templates}},resolveDefaultPreset=(presets,existing,defaults)=>{let mergedIds=new Set(presets.map(p=>p.id)),current=existing.defaultPreset;return current&&mergedIds.has(current)?current:defaults.defaultPreset??defaults.presets[0]?.id},mergeConfig=(existing,defaults,currentVersion,deprecatedPresetIds)=>{let oldVersion=existing.scaffoldVersion??null,{presets,addedPresets,deprecatedPresets}=mergePresets(existing,defaults,deprecatedPresetIds),{templates,addedTemplates}=mergeTemplates(existing,defaults);return{config:{...existing,defaultPreset:resolveDefaultPreset(presets,existing,defaults),presets,scaffoldVersion:currentVersion,templates},summary:{addedPresets,addedTemplates,deprecatedPresets,newVersion:currentVersion,oldVersion}}},getLatestVersion=async()=>{try{let response=await fetch(`https://registry.npmjs.org/@stdout-design/cli/latest`);return response.status===200?(await response.json()).version:null}catch{return null}},DEPRECATED_PRESET_IDS=new Set,compareVersions=(a,b)=>{let partsA=a.split(`.`).map(Number),partsB=b.split(`.`).map(Number),length=Math.max(partsA.length,partsB.length);for(let i=0;i<length;i+=1){let diff=(partsA[i]??0)-(partsB[i]??0);if(diff!==0)return diff}return 0},serializeConfig=config=>`import type { StudioConfig } from "@stdout-design/cli";
27
25
 
28
26
  const config: StudioConfig = ${JSON.stringify(config,null,2)};
29
27
 
30
28
  export default config;
31
- `,handlers={cache:cacheStats,cacheClean,cacheStats,dev,init,lint,render,update:async(projectDir,options)=>{let cwd=process.cwd(),dir=path.resolve(cwd,projectDir??`.`),configPath=path.resolve(dir,`studio.config.ts`);if(!existsSync(configPath))throw Error("No studio project found. Run `studio init` first.");let existingModule=await import(pathToFileURL(configPath).href),existing=existingModule.default??existingModule,existingConfig={defaultPreset:existing.defaultPreset,outDir:existing.outDir,presets:existing.presets??[],scaffoldVersion:existing.scaffoldVersion,templates:existing.templates??{}},defaults=getDefaults(),currentVersion=getScaffoldVersion(),{config:merged,summary}=mergeConfig(existingConfig,defaults,currentVersion,DEPRECATED_PRESET_IDS),{intro,outro,confirm}=await import(`@clack/prompts`);if(intro(`studio update`),!(summary.addedPresets.length>0||summary.deprecatedPresets.length>0||summary.addedTemplates.length>0||summary.oldVersion!==summary.newVersion)){console.log(`Project is already up to date.`),outro(`Done`);return}console.log(``),summary.oldVersion!==summary.newVersion&&console.log(` scaffoldVersion ${summary.oldVersion??`(none)`} -> ${summary.newVersion}`);for(let id of summary.addedPresets)console.log(` presets +${id}`);for(let id of summary.deprecatedPresets)console.log(` presets ! ${id} (deprecated)`);for(let id of summary.addedTemplates)console.log(` templates +${id}`);if(console.log(` assets tsconfig.json, .gitignore, types.d.ts (overwrite)`),console.log(` deps @stdout-design/cli ^x -> ^${currentVersion}`),console.log(``),!options?.yes&&!await confirm({initialValue:!0,message:`Apply these changes?`})){console.log(`Cancelled.`),outro(`Done`);return}await writeFile(configPath,serializeConfig(merged)),await copyStaticAssets(dir);let pkgPath=path.resolve(dir,`package.json`);if(existsSync(pkgPath)){let{updated,changed}=updatePackageJsonDeps(readFileSync(pkgPath,`utf-8`),currentVersion);changed&&await writeFile(pkgPath,updated)}console.log(``),outro(`Done`)}},run=(moduleName,handlerName)=>async(...args)=>{try{let handler=handlerName?handlers[handlerName]:handlers[moduleName];if(!handler)throw Error(`Unknown command: ${handlerName??moduleName}`);await handler(...args)}catch(error){console.error(formatError$1(error)),process.exit(1)}},pkg=createRequire(import.meta.url)(`../package.json`),program=new Command().allowExcessArguments(!0);program.name(`studio`).description(`Social media design tool — render, preview, batch`).version(pkg.version,`-v, --version`),program.command(`dev`).description(`Start the studio dev server with live preview`).argument(`[rootDir]`,`Project root directory (default: cwd)`).option(`-p, --port <number>`,`Port to run on`,`3000`).option(`--open`,`Open browser on start`).action(run(`dev`)),program.command(`render`).description(`Render a template — single or batch with --data`).argument(`<template>`,`Template ID from studio.config.ts`).argument(`[props...]`,`Props as key=value pairs (e.g. title="Hello")`).option(`--data <path>`,`CSV or JSON data file for batch rendering`).option(`--preset <ids>`,`Comma-separated preset IDs`).option(`--locale <locales>`,`Comma-separated locale codes`).option(`--out-dir <path>`,`Output directory`).option(`--concurrency <n>`,`Max concurrent renders in batch mode`,`4`).option(`--fail-fast`,`Stop batch on first error`).option(`--json`,`Output results as JSON`).action(run(`render`));const cacheCmd=program.command(`cache`).description(`Manage the render cache`);cacheCmd.command(`stats`).description(`Show cache statistics`).option(`--json`,`Output as JSON`).argument(`[rootDir]`,`Project root directory (default: cwd)`).action(run(`cache`,`cacheStats`)),cacheCmd.command(`clean`).description(`Clear the render cache`).option(`--json`,`Output as JSON`).argument(`[rootDir]`,`Project root directory (default: cwd)`).action(run(`cache`,`cacheClean`)),program.command(`lint`).description(`Check templates for compatibility (coming soon)`).argument(`[rootDir]`,`Project root directory (default: cwd)`).action(run(`lint`)),program.command(`init`).description(`Scaffold a new studio project`).argument(`[projectDir]`,`Project directory (default: cwd)`).option(`-y, --yes`,`Skip prompts, use defaults`).action(run(`init`)),program.command(`update`).description(`Update an existing studio project to the latest CLI version`).argument(`[projectDir]`,`Project directory (default: cwd)`).option(`-y, --yes`,`Skip confirmation prompts`).action(run(`update`)),program.parse();export{};
29
+ `,planUpdate=(existingConfig,defaults,installedVersion,deprecatedPresetIds)=>{let{config:mergedConfig,summary}=mergeConfig(existingConfig,defaults,installedVersion,deprecatedPresetIds);return{installedVersion,mergedConfig,summary}},resolveVersion=async deps=>{let installed=(deps?.getInstalledVersion??getScaffoldVersion)(),latest=await(deps?.getLatestVersion??getLatestVersion)();if(latest!==null&&installed!==`latest`&&compareVersions(latest,installed)>0){console.log(`CLI v${installed} is installed, but v${latest} is available.`),console.log("Run `npm install @stdout-design/cli@latest` first, then re-run `studio update`.");return}return installed},printChanges=(summary,installedVersion)=>{console.log(``),summary.oldVersion!==summary.newVersion&&console.log(` scaffoldVersion ${summary.oldVersion??`(none)`} -> ${summary.newVersion}`);for(let id of summary.addedPresets)console.log(` presets +${id}`);for(let id of summary.deprecatedPresets)console.log(` presets ! ${id} (deprecated)`);for(let id of summary.addedTemplates)console.log(` templates +${id}`);console.log(` assets tsconfig.json, .gitignore, types.d.ts (overwrite)`),console.log(` deps @stdout-design/cli ^x -> ^${installedVersion}`),console.log(``)},applyUpdate=async(dir,plan)=>{await writeFile(path.resolve(dir,`studio.config.ts`),serializeConfig(plan.mergedConfig)),await copyStaticAssets(dir);let pkgPath=path.resolve(dir,`package.json`);if(existsSync(pkgPath)){let{updated,changed}=updatePackageJsonDeps(readFileSync(pkgPath,`utf-8`),plan.installedVersion);changed&&await writeFile(pkgPath,updated)}},handlers={cache:cacheStats,cacheClean,cacheStats,dev,init,lint,render,update:async(projectDir,options,deps)=>{let cwd=process.cwd(),dir=path.resolve(cwd,projectDir??`.`),existingConfig=await loadConfig(dir),defaults=getDefaults(),installedVersion=await resolveVersion(deps);if(installedVersion===void 0)return;let plan=planUpdate(existingConfig,defaults,installedVersion,DEPRECATED_PRESET_IDS),{intro,outro,confirm}=await import(`@clack/prompts`);if(intro(`studio update`),!(plan.summary.addedPresets.length>0||plan.summary.deprecatedPresets.length>0||plan.summary.addedTemplates.length>0||plan.summary.oldVersion!==plan.summary.newVersion)){console.log(`Project is already up to date.`),outro(`Done`);return}if(printChanges(plan.summary,plan.installedVersion),!options?.yes&&!await confirm({initialValue:!0,message:`Apply these changes?`})){console.log(`Cancelled.`),outro(`Done`);return}await applyUpdate(dir,plan),console.log(``),outro(`Done`)}},run=(moduleName,handlerName)=>async(...args)=>{try{let handler=handlerName?handlers[handlerName]:handlers[moduleName];if(!handler)throw Error(`Unknown command: ${handlerName??moduleName}`);await handler(...args)}catch(error){console.error(formatError(error)),process.exit(1)}},pkg=createRequire(import.meta.url)(`../package.json`),program=new Command().allowExcessArguments(!0);program.name(`studio`).description(`Social media design tool — render, preview, batch`).version(pkg.version,`-v, --version`),program.command(`dev`).description(`Start the studio dev server with live preview`).argument(`[rootDir]`,`Project root directory (default: cwd)`).option(`-p, --port <number>`,`Port to run on`,`3000`).option(`--open`,`Open browser on start`).action(run(`dev`)),program.command(`render`).description(`Render a template — single or batch with --data`).argument(`<template>`,`Template ID from studio.config.ts`).argument(`[props...]`,`Props as key=value pairs (e.g. title="Hello")`).option(`--data <path>`,`CSV or JSON data file for batch rendering`).option(`--preset <ids>`,`Comma-separated preset IDs`).option(`--locale <locales>`,`Comma-separated locale codes`).option(`--out-dir <path>`,`Output directory`).option(`--concurrency <n>`,`Max concurrent renders in batch mode`,`4`).option(`--fail-fast`,`Stop batch on first error`).option(`--json`,`Output results as JSON`).action(run(`render`));const cacheCmd=program.command(`cache`).description(`Manage the render cache`);cacheCmd.command(`stats`).description(`Show cache statistics`).option(`--json`,`Output as JSON`).argument(`[rootDir]`,`Project root directory (default: cwd)`).action(run(`cache`,`cacheStats`)),cacheCmd.command(`clean`).description(`Clear the render cache`).option(`--json`,`Output as JSON`).argument(`[rootDir]`,`Project root directory (default: cwd)`).action(run(`cache`,`cacheClean`)),program.command(`lint`).description(`Check templates for compatibility (coming soon)`).argument(`[rootDir]`,`Project root directory (default: cwd)`).action(run(`lint`)),program.command(`init`).description(`Scaffold a new studio project`).argument(`[projectDir]`,`Project directory (default: cwd)`).option(`-y, --yes`,`Skip prompts, use defaults`).action(run(`init`)),program.command(`update`).description(`Update an existing studio project to the latest CLI version`).argument(`[projectDir]`,`Project directory (default: cwd)`).option(`-y, --yes`,`Skip confirmation prompts`).action(run(`update`)),program.parse();export{};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@stdout-design/cli",
3
- "version": "0.2.9",
3
+ "version": "0.3.0",
4
4
  "description": "stdout-design CLI — shallow front door to @stdout-design/core and @stdout-design/dev-server",
5
5
  "keywords": [
6
6
  "cli",
@@ -60,7 +60,8 @@
60
60
  },
61
61
  "peerDependencies": {
62
62
  "@stdout-design/dev-server": "^0.2.0",
63
- "@stdout-design/web-ui": "^0.2.0"
63
+ "@stdout-design/web-ui": "^0.2.0",
64
+ "zod": "^4.4.3"
64
65
  },
65
66
  "peerDependenciesMeta": {
66
67
  "@stdout-design/dev-server": {