create-gamecn 0.0.4-1 → 0.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/index.js +2 -2
  2. package/package.json +1 -1
package/index.js CHANGED
@@ -111,8 +111,8 @@ ${import_picocolors.default.gray(d2)} ${t}
111
111
  }
112
112
 
113
113
  `)}}doc.write(`payload.value = newResult;`);doc.write(`return payload;`);const fn=doc.compile();return(payload,ctx)=>fn(shape,payload,ctx)};let fastpass;const isObject2=isObject;const jit=!globalConfig.jitless;const allowsEval2=allowsEval;const fastEnabled=jit&&allowsEval2.value;const catchall=def.catchall;let value;inst._zod.parse=(payload,ctx)=>{value??(value=_normalized.value);const input=payload.value;if(!isObject2(input)){payload.issues.push({expected:"object",code:"invalid_type",input,inst});return payload}if(jit&&fastEnabled&&ctx?.async===false&&ctx.jitless!==true){if(!fastpass)fastpass=generateFastpass(def.shape);payload=fastpass(payload,ctx);if(!catchall)return payload;return handleCatchall([],input,payload,ctx,value,inst)}return superParse(payload,ctx)}});function handleUnionResults(results,final,inst,ctx){for(const result of results){if(result.issues.length===0){final.value=result.value;return final}}const nonaborted=results.filter((r2)=>!aborted(r2));if(nonaborted.length===1){final.value=nonaborted[0].value;return nonaborted[0]}final.issues.push({code:"invalid_union",input:final.value,inst,errors:results.map((result)=>result.issues.map((iss)=>finalizeIssue(iss,ctx,config())))});return final}var $ZodUnion=$constructor("$ZodUnion",(inst,def)=>{$ZodType.init(inst,def);defineLazy(inst._zod,"optin",()=>def.options.some((o2)=>o2._zod.optin==="optional")?"optional":undefined);defineLazy(inst._zod,"optout",()=>def.options.some((o2)=>o2._zod.optout==="optional")?"optional":undefined);defineLazy(inst._zod,"values",()=>{if(def.options.every((o2)=>o2._zod.values)){return new Set(def.options.flatMap((option)=>Array.from(option._zod.values)))}return});defineLazy(inst._zod,"pattern",()=>{if(def.options.every((o2)=>o2._zod.pattern)){const patterns=def.options.map((o2)=>o2._zod.pattern);return new RegExp(`^(${patterns.map((p2)=>cleanRegex(p2.source)).join("|")})$`)}return});const first=def.options.length===1?def.options[0]._zod.run:null;inst._zod.parse=(payload,ctx)=>{if(first){return first(payload,ctx)}let async=false;const results=[];for(const option of def.options){const result=option._zod.run({value:payload.value,issues:[]},ctx);if(result instanceof Promise){results.push(result);async=true}else{if(result.issues.length===0)return result;results.push(result)}}if(!async)return handleUnionResults(results,payload,inst,ctx);return Promise.all(results).then((results2)=>{return handleUnionResults(results2,payload,inst,ctx)})}});var $ZodDiscriminatedUnion=$constructor("$ZodDiscriminatedUnion",(inst,def)=>{def.inclusive=false;$ZodUnion.init(inst,def);const _super=inst._zod.parse;defineLazy(inst._zod,"propValues",()=>{const propValues={};for(const option of def.options){const pv=option._zod.propValues;if(!pv||Object.keys(pv).length===0)throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(option)}"`);for(const[k3,v]of Object.entries(pv)){if(!propValues[k3])propValues[k3]=new Set;for(const val of v){propValues[k3].add(val)}}}return propValues});const disc=cached(()=>{const opts=def.options;const map=new Map;for(const o2 of opts){const values=o2._zod.propValues?.[def.discriminator];if(!values||values.size===0)throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(o2)}"`);for(const v of values){if(map.has(v)){throw new Error(`Duplicate discriminator value "${String(v)}"`)}map.set(v,o2)}}return map});inst._zod.parse=(payload,ctx)=>{const input=payload.value;if(!isObject(input)){payload.issues.push({code:"invalid_type",expected:"object",input,inst});return payload}const opt=disc.value.get(input?.[def.discriminator]);if(opt){return opt._zod.run(payload,ctx)}if(def.unionFallback||ctx.direction==="backward"){return _super(payload,ctx)}payload.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:def.discriminator,options:Array.from(disc.value.keys()),input,path:[def.discriminator],inst});return payload}});var $ZodIntersection=$constructor("$ZodIntersection",(inst,def)=>{$ZodType.init(inst,def);inst._zod.parse=(payload,ctx)=>{const input=payload.value;const left=def.left._zod.run({value:input,issues:[]},ctx);const right=def.right._zod.run({value:input,issues:[]},ctx);const async=left instanceof Promise||right instanceof Promise;if(async){return Promise.all([left,right]).then(([left2,right2])=>{return handleIntersectionResults(payload,left2,right2)})}return handleIntersectionResults(payload,left,right)}});function mergeValues(a,b3){if(a===b3){return{valid:true,data:a}}if(a instanceof Date&&b3 instanceof Date&&+a===+b3){return{valid:true,data:a}}if(isPlainObject(a)&&isPlainObject(b3)){const bKeys=Object.keys(b3);const sharedKeys=Object.keys(a).filter((key)=>bKeys.indexOf(key)!==-1);const newObj={...a,...b3};for(const key of sharedKeys){const sharedValue=mergeValues(a[key],b3[key]);if(!sharedValue.valid){return{valid:false,mergeErrorPath:[key,...sharedValue.mergeErrorPath]}}newObj[key]=sharedValue.data}return{valid:true,data:newObj}}if(Array.isArray(a)&&Array.isArray(b3)){if(a.length!==b3.length){return{valid:false,mergeErrorPath:[]}}const newArray=[];for(let index=0;index<a.length;index++){const itemA=a[index];const itemB=b3[index];const sharedValue=mergeValues(itemA,itemB);if(!sharedValue.valid){return{valid:false,mergeErrorPath:[index,...sharedValue.mergeErrorPath]}}newArray.push(sharedValue.data)}return{valid:true,data:newArray}}return{valid:false,mergeErrorPath:[]}}function handleIntersectionResults(result,left,right){const unrecKeys=new Map;let unrecIssue;for(const iss of left.issues){if(iss.code==="unrecognized_keys"){unrecIssue??(unrecIssue=iss);for(const k3 of iss.keys){if(!unrecKeys.has(k3))unrecKeys.set(k3,{});unrecKeys.get(k3).l=true}}else{result.issues.push(iss)}}for(const iss of right.issues){if(iss.code==="unrecognized_keys"){for(const k3 of iss.keys){if(!unrecKeys.has(k3))unrecKeys.set(k3,{});unrecKeys.get(k3).r=true}}else{result.issues.push(iss)}}const bothKeys=[...unrecKeys].filter(([,f])=>f.l&&f.r).map(([k3])=>k3);if(bothKeys.length&&unrecIssue){result.issues.push({...unrecIssue,keys:bothKeys})}if(aborted(result))return result;const merged=mergeValues(left.value,right.value);if(!merged.valid){throw new Error(`Unmergable intersection. Error path: `+`${JSON.stringify(merged.mergeErrorPath)}`)}result.value=merged.data;return result}var $ZodRecord=$constructor("$ZodRecord",(inst,def)=>{$ZodType.init(inst,def);inst._zod.parse=(payload,ctx)=>{const input=payload.value;if(!isPlainObject(input)){payload.issues.push({expected:"record",code:"invalid_type",input,inst});return payload}const proms=[];const values=def.keyType._zod.values;if(values){payload.value={};const recordKeys=new Set;for(const key of values){if(typeof key==="string"||typeof key==="number"||typeof key==="symbol"){recordKeys.add(typeof key==="number"?key.toString():key);const keyResult=def.keyType._zod.run({value:key,issues:[]},ctx);if(keyResult instanceof Promise){throw new Error("Async schemas not supported in object keys currently")}if(keyResult.issues.length){payload.issues.push({code:"invalid_key",origin:"record",issues:keyResult.issues.map((iss)=>finalizeIssue(iss,ctx,config())),input:key,path:[key],inst});continue}const outKey=keyResult.value;const result=def.valueType._zod.run({value:input[key],issues:[]},ctx);if(result instanceof Promise){proms.push(result.then((result2)=>{if(result2.issues.length){payload.issues.push(...prefixIssues(key,result2.issues))}payload.value[outKey]=result2.value}))}else{if(result.issues.length){payload.issues.push(...prefixIssues(key,result.issues))}payload.value[outKey]=result.value}}}let unrecognized;for(const key in input){if(!recordKeys.has(key)){unrecognized=unrecognized??[];unrecognized.push(key)}}if(unrecognized&&unrecognized.length>0){payload.issues.push({code:"unrecognized_keys",input,inst,keys:unrecognized})}}else{payload.value={};for(const key of Reflect.ownKeys(input)){if(key==="__proto__")continue;if(!Object.prototype.propertyIsEnumerable.call(input,key))continue;let keyResult=def.keyType._zod.run({value:key,issues:[]},ctx);if(keyResult instanceof Promise){throw new Error("Async schemas not supported in object keys currently")}const checkNumericKey=typeof key==="string"&&number.test(key)&&keyResult.issues.length;if(checkNumericKey){const retryResult=def.keyType._zod.run({value:Number(key),issues:[]},ctx);if(retryResult instanceof Promise){throw new Error("Async schemas not supported in object keys currently")}if(retryResult.issues.length===0){keyResult=retryResult}}if(keyResult.issues.length){if(def.mode==="loose"){payload.value[key]=input[key]}else{payload.issues.push({code:"invalid_key",origin:"record",issues:keyResult.issues.map((iss)=>finalizeIssue(iss,ctx,config())),input:key,path:[key],inst})}continue}const result=def.valueType._zod.run({value:input[key],issues:[]},ctx);if(result instanceof Promise){proms.push(result.then((result2)=>{if(result2.issues.length){payload.issues.push(...prefixIssues(key,result2.issues))}payload.value[keyResult.value]=result2.value}))}else{if(result.issues.length){payload.issues.push(...prefixIssues(key,result.issues))}payload.value[keyResult.value]=result.value}}}if(proms.length){return Promise.all(proms).then(()=>payload)}return payload}});var $ZodEnum=$constructor("$ZodEnum",(inst,def)=>{$ZodType.init(inst,def);const values=getEnumValues(def.entries);const valuesSet=new Set(values);inst._zod.values=valuesSet;inst._zod.pattern=new RegExp(`^(${values.filter((k3)=>propertyKeyTypes.has(typeof k3)).map((o2)=>typeof o2==="string"?escapeRegex(o2):o2.toString()).join("|")})$`);inst._zod.parse=(payload,_ctx)=>{const input=payload.value;if(valuesSet.has(input)){return payload}payload.issues.push({code:"invalid_value",values,input,inst});return payload}});var $ZodLiteral=$constructor("$ZodLiteral",(inst,def)=>{$ZodType.init(inst,def);if(def.values.length===0){throw new Error("Cannot create literal schema with no valid values")}const values=new Set(def.values);inst._zod.values=values;inst._zod.pattern=new RegExp(`^(${def.values.map((o2)=>typeof o2==="string"?escapeRegex(o2):o2?escapeRegex(o2.toString()):String(o2)).join("|")})$`);inst._zod.parse=(payload,_ctx)=>{const input=payload.value;if(values.has(input)){return payload}payload.issues.push({code:"invalid_value",values:def.values,input,inst});return payload}});var $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)}const _out=def.transform(payload.value,payload);if(ctx.async){const output=_out instanceof Promise?_out:Promise.resolve(_out);return output.then((output2)=>{payload.value=output2;payload.fallback=true;return payload})}if(_out instanceof Promise){throw new $ZodAsyncError}payload.value=_out;payload.fallback=true;return payload}});function handleOptionalResult(result,input){if(input===undefined&&(result.issues.length||result.fallback)){return{issues:[],value:undefined}}return result}var $ZodOptional=$constructor("$ZodOptional",(inst,def)=>{$ZodType.init(inst,def);inst._zod.optin="optional";inst._zod.optout="optional";defineLazy(inst._zod,"values",()=>{return def.innerType._zod.values?new Set([...def.innerType._zod.values,undefined]):undefined});defineLazy(inst._zod,"pattern",()=>{const pattern=def.innerType._zod.pattern;return pattern?new RegExp(`^(${cleanRegex(pattern.source)})?$`):undefined});inst._zod.parse=(payload,ctx)=>{if(def.innerType._zod.optin==="optional"){const input=payload.value;const result=def.innerType._zod.run(payload,ctx);if(result instanceof Promise)return result.then((r2)=>handleOptionalResult(r2,input));return handleOptionalResult(result,input)}if(payload.value===undefined){return payload}return def.innerType._zod.run(payload,ctx)}});var $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)=>{return def.innerType._zod.run(payload,ctx)}});var $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",()=>{const pattern=def.innerType._zod.pattern;return pattern?new RegExp(`^(${cleanRegex(pattern.source)}|null)$`):undefined});defineLazy(inst._zod,"values",()=>{return def.innerType._zod.values?new Set([...def.innerType._zod.values,null]):undefined});inst._zod.parse=(payload,ctx)=>{if(payload.value===null)return payload;return def.innerType._zod.run(payload,ctx)}});var $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===undefined){payload.value=def.defaultValue;return payload}const result=def.innerType._zod.run(payload,ctx);if(result instanceof Promise){return result.then((result2)=>handleDefaultResult(result2,def))}return handleDefaultResult(result,def)}});function handleDefaultResult(payload,def){if(payload.value===undefined){payload.value=def.defaultValue}return payload}var $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)=>{if(ctx.direction==="backward"){return def.innerType._zod.run(payload,ctx)}if(payload.value===undefined){payload.value=def.defaultValue}return def.innerType._zod.run(payload,ctx)}});var $ZodNonOptional=$constructor("$ZodNonOptional",(inst,def)=>{$ZodType.init(inst,def);defineLazy(inst._zod,"values",()=>{const v=def.innerType._zod.values;return v?new Set([...v].filter((x2)=>x2!==undefined)):undefined});inst._zod.parse=(payload,ctx)=>{const result=def.innerType._zod.run(payload,ctx);if(result instanceof Promise){return result.then((result2)=>handleNonOptionalResult(result2,inst))}return handleNonOptionalResult(result,inst)}});function handleNonOptionalResult(payload,inst){if(!payload.issues.length&&payload.value===undefined){payload.issues.push({code:"invalid_type",expected:"nonoptional",input:payload.value,inst})}return payload}var $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)}const result=def.innerType._zod.run(payload,ctx);if(result instanceof Promise){return result.then((result2)=>{payload.value=result2.value;if(result2.issues.length){payload.value=def.catchValue({...payload,error:{issues:result2.issues.map((iss)=>finalizeIssue(iss,ctx,config()))},input:payload.value});payload.issues=[];payload.fallback=true}return payload})}payload.value=result.value;if(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=true}return payload}});var $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"){const right=def.out._zod.run(payload,ctx);if(right instanceof Promise){return right.then((right2)=>handlePipeResult(right2,def.in,ctx))}return handlePipeResult(right,def.in,ctx)}const left=def.in._zod.run(payload,ctx);if(left instanceof Promise){return left.then((left2)=>handlePipeResult(left2,def.out,ctx))}return handlePipeResult(left,def.out,ctx)}});function handlePipeResult(left,next,ctx){if(left.issues.length){left.aborted=true;return left}return next._zod.run({value:left.value,issues:left.issues,fallback:left.fallback},ctx)}var $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)}const result=def.innerType._zod.run(payload,ctx);if(result instanceof Promise){return result.then(handleReadonlyResult)}return handleReadonlyResult(result)}});function handleReadonlyResult(payload){payload.value=Object.freeze(payload.value);return payload}var $ZodCustom=$constructor("$ZodCustom",(inst,def)=>{$ZodCheck.init(inst,def);$ZodType.init(inst,def);inst._zod.parse=(payload,_3)=>{return payload};inst._zod.check=(payload)=>{const input=payload.value;const r2=def.fn(input);if(r2 instanceof Promise){return r2.then((r3)=>handleRefineResult(r3,payload,input,inst))}handleRefineResult(r2,payload,input,inst);return}});function handleRefineResult(result,payload,input,inst){if(!result){const _iss={code:"custom",input,inst,path:[...inst._zod.def.path??[]],continue:!inst._zod.def.abort};if(inst._zod.def.params)_iss.params=inst._zod.def.params;payload.issues.push(issue(_iss))}}var _a2;var $output=Symbol("ZodOutput");var $input=Symbol("ZodInput");class $ZodRegistry{constructor(){this._map=new WeakMap;this._idmap=new Map}add(schema,..._meta){const meta=_meta[0];this._map.set(schema,meta);if(meta&&typeof meta==="object"&&"id"in meta){this._idmap.set(meta.id,schema)}return this}clear(){this._map=new WeakMap;this._idmap=new Map;return this}remove(schema){const meta=this._map.get(schema);if(meta&&typeof meta==="object"&&"id"in meta){this._idmap.delete(meta.id)}this._map.delete(schema);return this}get(schema){const p2=schema._zod.parent;if(p2){const pm={...this.get(p2)??{}};delete pm.id;const f={...pm,...this._map.get(schema)};return Object.keys(f).length?f:undefined}return this._map.get(schema)}has(schema){return this._map.has(schema)}}function registry(){return new $ZodRegistry}(_a2=globalThis).__zod_globalRegistry??(_a2.__zod_globalRegistry=registry());var globalRegistry=globalThis.__zod_globalRegistry;function _string(Class2,params){return new Class2({type:"string",...normalizeParams(params)})}function _email(Class2,params){return new Class2({type:"string",format:"email",check:"string_format",abort:false,...normalizeParams(params)})}function _guid(Class2,params){return new Class2({type:"string",format:"guid",check:"string_format",abort:false,...normalizeParams(params)})}function _uuid(Class2,params){return new Class2({type:"string",format:"uuid",check:"string_format",abort:false,...normalizeParams(params)})}function _uuidv4(Class2,params){return new Class2({type:"string",format:"uuid",check:"string_format",abort:false,version:"v4",...normalizeParams(params)})}function _uuidv6(Class2,params){return new Class2({type:"string",format:"uuid",check:"string_format",abort:false,version:"v6",...normalizeParams(params)})}function _uuidv7(Class2,params){return new Class2({type:"string",format:"uuid",check:"string_format",abort:false,version:"v7",...normalizeParams(params)})}function _url(Class2,params){return new Class2({type:"string",format:"url",check:"string_format",abort:false,...normalizeParams(params)})}function _emoji2(Class2,params){return new Class2({type:"string",format:"emoji",check:"string_format",abort:false,...normalizeParams(params)})}function _nanoid(Class2,params){return new Class2({type:"string",format:"nanoid",check:"string_format",abort:false,...normalizeParams(params)})}function _cuid(Class2,params){return new Class2({type:"string",format:"cuid",check:"string_format",abort:false,...normalizeParams(params)})}function _cuid2(Class2,params){return new Class2({type:"string",format:"cuid2",check:"string_format",abort:false,...normalizeParams(params)})}function _ulid(Class2,params){return new Class2({type:"string",format:"ulid",check:"string_format",abort:false,...normalizeParams(params)})}function _xid(Class2,params){return new Class2({type:"string",format:"xid",check:"string_format",abort:false,...normalizeParams(params)})}function _ksuid(Class2,params){return new Class2({type:"string",format:"ksuid",check:"string_format",abort:false,...normalizeParams(params)})}function _ipv4(Class2,params){return new Class2({type:"string",format:"ipv4",check:"string_format",abort:false,...normalizeParams(params)})}function _ipv6(Class2,params){return new Class2({type:"string",format:"ipv6",check:"string_format",abort:false,...normalizeParams(params)})}function _cidrv4(Class2,params){return new Class2({type:"string",format:"cidrv4",check:"string_format",abort:false,...normalizeParams(params)})}function _cidrv6(Class2,params){return new Class2({type:"string",format:"cidrv6",check:"string_format",abort:false,...normalizeParams(params)})}function _base64(Class2,params){return new Class2({type:"string",format:"base64",check:"string_format",abort:false,...normalizeParams(params)})}function _base64url(Class2,params){return new Class2({type:"string",format:"base64url",check:"string_format",abort:false,...normalizeParams(params)})}function _e164(Class2,params){return new Class2({type:"string",format:"e164",check:"string_format",abort:false,...normalizeParams(params)})}function _jwt(Class2,params){return new Class2({type:"string",format:"jwt",check:"string_format",abort:false,...normalizeParams(params)})}function _isoDateTime(Class2,params){return new Class2({type:"string",format:"datetime",check:"string_format",offset:false,local:false,precision:null,...normalizeParams(params)})}function _isoDate(Class2,params){return new Class2({type:"string",format:"date",check:"string_format",...normalizeParams(params)})}function _isoTime(Class2,params){return new Class2({type:"string",format:"time",check:"string_format",precision:null,...normalizeParams(params)})}function _isoDuration(Class2,params){return new Class2({type:"string",format:"duration",check:"string_format",...normalizeParams(params)})}function _number(Class2,params){return new Class2({type:"number",checks:[],...normalizeParams(params)})}function _int(Class2,params){return new Class2({type:"number",check:"number_format",abort:false,format:"safeint",...normalizeParams(params)})}function _boolean(Class2,params){return new Class2({type:"boolean",...normalizeParams(params)})}function _unknown(Class2){return new Class2({type:"unknown"})}function _never(Class2,params){return new Class2({type:"never",...normalizeParams(params)})}function _lt(value,params){return new $ZodCheckLessThan({check:"less_than",...normalizeParams(params),value,inclusive:false})}function _lte(value,params){return new $ZodCheckLessThan({check:"less_than",...normalizeParams(params),value,inclusive:true})}function _gt(value,params){return new $ZodCheckGreaterThan({check:"greater_than",...normalizeParams(params),value,inclusive:false})}function _gte(value,params){return new $ZodCheckGreaterThan({check:"greater_than",...normalizeParams(params),value,inclusive:true})}function _multipleOf(value,params){return new $ZodCheckMultipleOf({check:"multiple_of",...normalizeParams(params),value})}function _maxLength(maximum,params){const ch=new $ZodCheckMaxLength({check:"max_length",...normalizeParams(params),maximum});return ch}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(Class2,element,params){return new Class2({type:"array",element,...normalizeParams(params)})}function _refine(Class2,fn,_params){const schema=new Class2({type:"custom",check:"custom",fn,...normalizeParams(_params)});return schema}function _superRefine(fn,params){const ch=_check((payload)=>{payload.addIssue=(issue2)=>{if(typeof issue2==="string"){payload.issues.push(issue(issue2,payload.value,ch._zod.def))}else{const _issue=issue2;if(_issue.fatal)_issue.continue=false;_issue.code??(_issue.code="custom");_issue.input??(_issue.input=payload.value);_issue.inst??(_issue.inst=ch);_issue.continue??(_issue.continue=!ch._zod.def.abort);payload.issues.push(issue(_issue))}};return fn(payload.value,payload)},params);return ch}function _check(fn,params){const ch=new $ZodCheck({check:"custom",...normalizeParams(params)});ch._zod.check=fn;return ch}function initializeContext(params){let target=params?.target??"draft-2020-12";if(target==="draft-4")target="draft-04";if(target==="draft-7")target="draft-07";return{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??undefined}}function process2(schema,ctx,_params={path:[],schemaPath:[]}){var _a3;const def=schema._zod.def;const seen=ctx.seen.get(schema);if(seen){seen.count++;const isCycle=_params.schemaPath.includes(schema);if(isCycle){seen.cycle=_params.path}return seen.schema}const result={schema:{},count:1,cycle:undefined,path:_params.path};ctx.seen.set(schema,result);const overrideSchema=schema._zod.toJSONSchema?.();if(overrideSchema){result.schema=overrideSchema}else{const params={..._params,schemaPath:[..._params.schemaPath,schema],path:_params.path};if(schema._zod.processJSONSchema){schema._zod.processJSONSchema(ctx,result.schema,params)}else{const _json=result.schema;const processor=ctx.processors[def.type];if(!processor){throw new Error(`[toJSONSchema]: Non-representable type encountered: ${def.type}`)}processor(schema,ctx,_json,params)}const parent=schema._zod.parent;if(parent){if(!result.ref)result.ref=parent;process2(parent,ctx,params);ctx.seen.get(parent).isParent=true}}const meta=ctx.metadataRegistry.get(schema);if(meta)Object.assign(result.schema,meta);if(ctx.io==="input"&&isTransforming(schema)){delete result.schema.examples;delete result.schema.default}if(ctx.io==="input"&&"_prefault"in result.schema)(_a3=result.schema).default??(_a3.default=result.schema._prefault);delete result.schema._prefault;const _result=ctx.seen.get(schema);return _result.schema}function extractDefs(ctx,schema){const root=ctx.seen.get(schema);if(!root)throw new Error("Unprocessed schema. This is a bug in Zod.");const idToSchema=new Map;for(const entry of ctx.seen.entries()){const id=ctx.metadataRegistry.get(entry[0])?.id;if(id){const existing=idToSchema.get(id);if(existing&&existing!==entry[0]){throw new 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])}}const makeURI=(entry)=>{const defsSegment=ctx.target==="draft-2020-12"?"$defs":"definitions";if(ctx.external){const externalId=ctx.external.registry.get(entry[0])?.id;const uriGenerator=ctx.external.uri??((id2)=>id2);if(externalId){return{ref:uriGenerator(externalId)}}const id=entry[1].defId??entry[1].schema.id??`schema${ctx.counter++}`;entry[1].defId=id;return{defId:id,ref:`${uriGenerator("__shared")}#/${defsSegment}/${id}`}}if(entry[1]===root){return{ref:"#"}}const uriPrefix=`#`;const defUriPrefix=`${uriPrefix}/${defsSegment}/`;const defId=entry[1].schema.id??`__schema${ctx.counter++}`;return{defId,ref:defUriPrefix+defId}};const extractToDef=(entry)=>{if(entry[1].schema.$ref){return}const seen=entry[1];const{ref,defId}=makeURI(entry);seen.def={...seen.schema};if(defId)seen.defId=defId;const schema2=seen.schema;for(const key in schema2){delete schema2[key]}schema2.$ref=ref};if(ctx.cycles==="throw"){for(const entry of ctx.seen.entries()){const seen=entry[1];if(seen.cycle){throw new Error("Cycle detected: "+`#/${seen.cycle?.join("/")}/<root>`+'\n\nSet the `cycles` parameter to `"ref"` to resolve cyclical schemas with defs.')}}}for(const entry of ctx.seen.entries()){const seen=entry[1];if(schema===entry[0]){extractToDef(entry);continue}if(ctx.external){const ext=ctx.external.registry.get(entry[0])?.id;if(schema!==entry[0]&&ext){extractToDef(entry);continue}}const id=ctx.metadataRegistry.get(entry[0])?.id;if(id){extractToDef(entry);continue}if(seen.cycle){extractToDef(entry);continue}if(seen.count>1){if(ctx.reused==="ref"){extractToDef(entry);continue}}}}function finalize(ctx,schema){const root=ctx.seen.get(schema);if(!root)throw new Error("Unprocessed schema. This is a bug in Zod.");const flattenRef=(zodSchema)=>{const seen=ctx.seen.get(zodSchema);if(seen.ref===null)return;const schema2=seen.def??seen.schema;const _cached={...schema2};const ref=seen.ref;seen.ref=null;if(ref){flattenRef(ref);const refSeen=ctx.seen.get(ref);const refSchema=refSeen.schema;if(refSchema.$ref&&(ctx.target==="draft-07"||ctx.target==="draft-04"||ctx.target==="openapi-3.0")){schema2.allOf=schema2.allOf??[];schema2.allOf.push(refSchema)}else{Object.assign(schema2,refSchema)}Object.assign(schema2,_cached);const isParentRef=zodSchema._zod.parent===ref;if(isParentRef){for(const key in schema2){if(key==="$ref"||key==="allOf")continue;if(!(key in _cached)){delete schema2[key]}}}if(refSchema.$ref&&refSeen.def){for(const key in schema2){if(key==="$ref"||key==="allOf")continue;if(key in refSeen.def&&JSON.stringify(schema2[key])===JSON.stringify(refSeen.def[key])){delete schema2[key]}}}}const parent=zodSchema._zod.parent;if(parent&&parent!==ref){flattenRef(parent);const parentSeen=ctx.seen.get(parent);if(parentSeen?.schema.$ref){schema2.$ref=parentSeen.schema.$ref;if(parentSeen.def){for(const key in schema2){if(key==="$ref"||key==="allOf")continue;if(key in parentSeen.def&&JSON.stringify(schema2[key])===JSON.stringify(parentSeen.def[key])){delete schema2[key]}}}}}ctx.override({zodSchema,jsonSchema:schema2,path:seen.path??[]})};for(const entry of[...ctx.seen.entries()].reverse()){flattenRef(entry[0])}const result={};if(ctx.target==="draft-2020-12"){result.$schema="https://json-schema.org/draft/2020-12/schema"}else if(ctx.target==="draft-07"){result.$schema="http://json-schema.org/draft-07/schema#"}else if(ctx.target==="draft-04"){result.$schema="http://json-schema.org/draft-04/schema#"}else if(ctx.target==="openapi-3.0"){}else{}if(ctx.external?.uri){const id=ctx.external.registry.get(schema)?.id;if(!id)throw new Error("Schema is missing an `id` property");result.$id=ctx.external.uri(id)}Object.assign(result,root.def??root.schema);const rootMetaId=ctx.metadataRegistry.get(schema)?.id;if(rootMetaId!==undefined&&result.id===rootMetaId)delete result.id;const defs=ctx.external?.defs??{};for(const entry of ctx.seen.entries()){const seen=entry[1];if(seen.def&&seen.defId){if(seen.def.id===seen.defId)delete seen.def.id;defs[seen.defId]=seen.def}}if(ctx.external){}else{if(Object.keys(defs).length>0){if(ctx.target==="draft-2020-12"){result.$defs=defs}else{result.definitions=defs}}}try{const finalized=JSON.parse(JSON.stringify(result));Object.defineProperty(finalized,"~standard",{value:{...schema["~standard"],jsonSchema:{input:createStandardJSONSchemaMethod(schema,"input",ctx.processors),output:createStandardJSONSchemaMethod(schema,"output",ctx.processors)}},enumerable:false,writable:false});return finalized}catch(_err){throw new Error("Error converting schema to JSON.")}}function isTransforming(_schema,_ctx){const ctx=_ctx??{seen:new Set};if(ctx.seen.has(_schema))return false;ctx.seen.add(_schema);const def=_schema._zod.def;if(def.type==="transform")return true;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"){if(_schema._zod.traits.has("$ZodCodec"))return true;return isTransforming(def.in,ctx)||isTransforming(def.out,ctx)}if(def.type==="object"){for(const key in def.shape){if(isTransforming(def.shape[key],ctx))return true}return false}if(def.type==="union"){for(const option of def.options){if(isTransforming(option,ctx))return true}return false}if(def.type==="tuple"){for(const item of def.items){if(isTransforming(item,ctx))return true}if(def.rest&&isTransforming(def.rest,ctx))return true;return false}return false}var createToJSONSchemaMethod=(schema,processors={})=>(params)=>{const ctx=initializeContext({...params,processors});process2(schema,ctx);extractDefs(ctx,schema);return finalize(ctx,schema)};var createStandardJSONSchemaMethod=(schema,io,processors={})=>(params)=>{const{libraryOptions,target}=params??{};const ctx=initializeContext({...libraryOptions??{},target,io,processors});process2(schema,ctx);extractDefs(ctx,schema);return finalize(ctx,schema)};var formatMap={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""};var stringProcessor=(schema,ctx,_json,_params)=>{const json=_json;json.type="string";const{minimum,maximum,format,patterns,contentEncoding}=schema._zod.bag;if(typeof minimum==="number")json.minLength=minimum;if(typeof maximum==="number")json.maxLength=maximum;if(format){json.format=formatMap[format]??format;if(json.format==="")delete json.format;if(format==="time"){delete json.format}}if(contentEncoding)json.contentEncoding=contentEncoding;if(patterns&&patterns.size>0){const regexes=[...patterns];if(regexes.length===1)json.pattern=regexes[0].source;else if(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}))]}}};var numberProcessor=(schema,ctx,_json,_params)=>{const json=_json;const{minimum,maximum,format,multipleOf,exclusiveMaximum,exclusiveMinimum}=schema._zod.bag;if(typeof format==="string"&&format.includes("int"))json.type="integer";else json.type="number";const exMin=typeof exclusiveMinimum==="number"&&exclusiveMinimum>=(minimum??Number.NEGATIVE_INFINITY);const exMax=typeof exclusiveMaximum==="number"&&exclusiveMaximum<=(maximum??Number.POSITIVE_INFINITY);const legacy=ctx.target==="draft-04"||ctx.target==="openapi-3.0";if(exMin){if(legacy){json.minimum=exclusiveMinimum;json.exclusiveMinimum=true}else{json.exclusiveMinimum=exclusiveMinimum}}else if(typeof minimum==="number"){json.minimum=minimum}if(exMax){if(legacy){json.maximum=exclusiveMaximum;json.exclusiveMaximum=true}else{json.exclusiveMaximum=exclusiveMaximum}}else if(typeof maximum==="number"){json.maximum=maximum}if(typeof multipleOf==="number")json.multipleOf=multipleOf};var booleanProcessor=(_schema,_ctx,json,_params)=>{json.type="boolean"};var neverProcessor=(_schema,_ctx,json,_params)=>{json.not={}};var unknownProcessor=(_schema,_ctx,_json,_params)=>{};var enumProcessor=(schema,_ctx,json,_params)=>{const def=schema._zod.def;const values=getEnumValues(def.entries);if(values.every((v)=>typeof v==="number"))json.type="number";if(values.every((v)=>typeof v==="string"))json.type="string";json.enum=values};var literalProcessor=(schema,ctx,json,_params)=>{const def=schema._zod.def;const vals=[];for(const val of def.values){if(val===undefined){if(ctx.unrepresentable==="throw"){throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else{}}else if(typeof val==="bigint"){if(ctx.unrepresentable==="throw"){throw new Error("BigInt literals cannot be represented in JSON Schema")}else{vals.push(Number(val))}}else{vals.push(val)}}if(vals.length===0){}else if(vals.length===1){const val=vals[0];json.type=val===null?"null":typeof val;if(ctx.target==="draft-04"||ctx.target==="openapi-3.0"){json.enum=[val]}else{json.const=val}}else{if(vals.every((v)=>typeof v==="number"))json.type="number";if(vals.every((v)=>typeof v==="string"))json.type="string";if(vals.every((v)=>typeof v==="boolean"))json.type="boolean";if(vals.every((v)=>v===null))json.type="null";json.enum=vals}};var customProcessor=(_schema,ctx,_json,_params)=>{if(ctx.unrepresentable==="throw"){throw new Error("Custom types cannot be represented in JSON Schema")}};var transformProcessor=(_schema,ctx,_json,_params)=>{if(ctx.unrepresentable==="throw"){throw new Error("Transforms cannot be represented in JSON Schema")}};var arrayProcessor=(schema,ctx,_json,params)=>{const json=_json;const def=schema._zod.def;const{minimum,maximum}=schema._zod.bag;if(typeof minimum==="number")json.minItems=minimum;if(typeof maximum==="number")json.maxItems=maximum;json.type="array";json.items=process2(def.element,ctx,{...params,path:[...params.path,"items"]})};var objectProcessor=(schema,ctx,_json,params)=>{const json=_json;const def=schema._zod.def;json.type="object";json.properties={};const shape=def.shape;for(const key in shape){json.properties[key]=process2(shape[key],ctx,{...params,path:[...params.path,"properties",key]})}const allKeys=new Set(Object.keys(shape));const requiredKeys=new Set([...allKeys].filter((key)=>{const v=def.shape[key]._zod;if(ctx.io==="input"){return v.optin===undefined}else{return v.optout===undefined}}));if(requiredKeys.size>0){json.required=Array.from(requiredKeys)}if(def.catchall?._zod.def.type==="never"){json.additionalProperties=false}else if(!def.catchall){if(ctx.io==="output")json.additionalProperties=false}else if(def.catchall){json.additionalProperties=process2(def.catchall,ctx,{...params,path:[...params.path,"additionalProperties"]})}};var unionProcessor=(schema,ctx,json,params)=>{const def=schema._zod.def;const isExclusive=def.inclusive===false;const options=def.options.map((x2,i)=>process2(x2,ctx,{...params,path:[...params.path,isExclusive?"oneOf":"anyOf",i]}));if(isExclusive){json.oneOf=options}else{json.anyOf=options}};var intersectionProcessor=(schema,ctx,json,params)=>{const def=schema._zod.def;const a=process2(def.left,ctx,{...params,path:[...params.path,"allOf",0]});const b3=process2(def.right,ctx,{...params,path:[...params.path,"allOf",1]});const isSimpleIntersection=(val)=>("allOf"in val)&&Object.keys(val).length===1;const allOf=[...isSimpleIntersection(a)?a.allOf:[a],...isSimpleIntersection(b3)?b3.allOf:[b3]];json.allOf=allOf};var recordProcessor=(schema,ctx,_json,params)=>{const json=_json;const def=schema._zod.def;json.type="object";const keyType=def.keyType;const keyBag=keyType._zod.bag;const patterns=keyBag?.patterns;if(def.mode==="loose"&&patterns&&patterns.size>0){const valueSchema=process2(def.valueType,ctx,{...params,path:[...params.path,"patternProperties","*"]});json.patternProperties={};for(const pattern of patterns){json.patternProperties[pattern.source]=valueSchema}}else{if(ctx.target==="draft-07"||ctx.target==="draft-2020-12"){json.propertyNames=process2(def.keyType,ctx,{...params,path:[...params.path,"propertyNames"]})}json.additionalProperties=process2(def.valueType,ctx,{...params,path:[...params.path,"additionalProperties"]})}const keyValues=keyType._zod.values;if(keyValues){const validKeyValues=[...keyValues].filter((v)=>typeof v==="string"||typeof v==="number");if(validKeyValues.length>0){json.required=validKeyValues}}};var nullableProcessor=(schema,ctx,json,params)=>{const def=schema._zod.def;const inner=process2(def.innerType,ctx,params);const seen=ctx.seen.get(schema);if(ctx.target==="openapi-3.0"){seen.ref=def.innerType;json.nullable=true}else{json.anyOf=[inner,{type:"null"}]}};var nonoptionalProcessor=(schema,ctx,_json,params)=>{const def=schema._zod.def;process2(def.innerType,ctx,params);const seen=ctx.seen.get(schema);seen.ref=def.innerType};var defaultProcessor=(schema,ctx,json,params)=>{const def=schema._zod.def;process2(def.innerType,ctx,params);const seen=ctx.seen.get(schema);seen.ref=def.innerType;json.default=JSON.parse(JSON.stringify(def.defaultValue))};var prefaultProcessor=(schema,ctx,json,params)=>{const def=schema._zod.def;process2(def.innerType,ctx,params);const seen=ctx.seen.get(schema);seen.ref=def.innerType;if(ctx.io==="input")json._prefault=JSON.parse(JSON.stringify(def.defaultValue))};var catchProcessor=(schema,ctx,json,params)=>{const def=schema._zod.def;process2(def.innerType,ctx,params);const seen=ctx.seen.get(schema);seen.ref=def.innerType;let catchValue;try{catchValue=def.catchValue(undefined)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}json.default=catchValue};var pipeProcessor=(schema,ctx,_json,params)=>{const def=schema._zod.def;const inIsTransform=def.in._zod.traits.has("$ZodTransform");const innerType=ctx.io==="input"?inIsTransform?def.out:def.in:def.out;process2(innerType,ctx,params);const seen=ctx.seen.get(schema);seen.ref=innerType};var readonlyProcessor=(schema,ctx,json,params)=>{const def=schema._zod.def;process2(def.innerType,ctx,params);const seen=ctx.seen.get(schema);seen.ref=def.innerType;json.readOnly=true};var optionalProcessor=(schema,ctx,_json,params)=>{const def=schema._zod.def;process2(def.innerType,ctx,params);const seen=ctx.seen.get(schema);seen.ref=def.innerType};var ZodISODateTime=$constructor("ZodISODateTime",(inst,def)=>{$ZodISODateTime.init(inst,def);ZodStringFormat.init(inst,def)});function datetime2(params){return _isoDateTime(ZodISODateTime,params)}var ZodISODate=$constructor("ZodISODate",(inst,def)=>{$ZodISODate.init(inst,def);ZodStringFormat.init(inst,def)});function date2(params){return _isoDate(ZodISODate,params)}var ZodISOTime=$constructor("ZodISOTime",(inst,def)=>{$ZodISOTime.init(inst,def);ZodStringFormat.init(inst,def)});function time2(params){return _isoTime(ZodISOTime,params)}var ZodISODuration=$constructor("ZodISODuration",(inst,def)=>{$ZodISODuration.init(inst,def);ZodStringFormat.init(inst,def)});function duration2(params){return _isoDuration(ZodISODuration,params)}var initializer2=(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:(issue2)=>{inst.issues.push(issue2);inst.message=JSON.stringify(inst.issues,jsonStringifyReplacer,2)}},addIssues:{value:(issues2)=>{inst.issues.push(...issues2);inst.message=JSON.stringify(inst.issues,jsonStringifyReplacer,2)}},isEmpty:{get(){return inst.issues.length===0}}})};var ZodRealError=$constructor("ZodError",initializer2,{Parent:Error});var parse3=_parse(ZodRealError);var parseAsync2=_parseAsync(ZodRealError);var safeParse2=_safeParse(ZodRealError);var safeParseAsync2=_safeParseAsync(ZodRealError);var encode=_encode(ZodRealError);var decode=_decode(ZodRealError);var encodeAsync=_encodeAsync(ZodRealError);var decodeAsync=_decodeAsync(ZodRealError);var safeEncode=_safeEncode(ZodRealError);var safeDecode=_safeDecode(ZodRealError);var safeEncodeAsync=_safeEncodeAsync(ZodRealError);var safeDecodeAsync=_safeDecodeAsync(ZodRealError);var _installedGroups=new WeakMap;function _installLazyMethods(inst,group,methods){const proto=Object.getPrototypeOf(inst);let installed=_installedGroups.get(proto);if(!installed){installed=new Set;_installedGroups.set(proto,installed)}if(installed.has(group))return;installed.add(group);for(const key in methods){const fn=methods[key];Object.defineProperty(proto,key,{configurable:true,enumerable:false,get(){const bound=fn.bind(this);Object.defineProperty(this,key,{configurable:true,writable:true,enumerable:true,value:bound});return bound},set(v){Object.defineProperty(this,key,{configurable:true,writable:true,enumerable:true,value:v})}})}}var 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)=>parse3(inst,data,params,{callee:inst.parse});inst.safeParse=(data,params)=>safeParse2(inst,data,params);inst.parseAsync=async(data,params)=>parseAsync2(inst,data,params,{callee:inst.parseAsync});inst.safeParseAsync=async(data,params)=>safeParseAsync2(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){const def2=this.def;return this.clone(exports_util.mergeDefs(def2,{checks:[...def2.checks??[],...chks.map((ch)=>typeof ch==="function"?{_zod:{check:ch,def:{check:"custom"},onattach:[]}}:ch)]}),{parent:true})},with(...chks){return this.check(...chks)},clone(def2,params){return clone(this,def2,params)},brand(){return this},register(reg,meta2){reg.add(this,meta2);return 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(d3){return _default(this,d3)},prefault(d3){return prefault(this,d3)},catch(params){return _catch(this,params)},pipe(target){return pipe(this,target)},readonly(){return readonly(this)},describe(description){const cl=this.clone();globalRegistry.add(cl,{description});return cl},meta(...args){if(args.length===0)return globalRegistry.get(this);const cl=this.clone();globalRegistry.add(cl,args[0]);return cl},isOptional(){return this.safeParse(undefined).success},isNullable(){return this.safeParse(null).success},apply(fn){return fn(this)}});Object.defineProperty(inst,"description",{get(){return globalRegistry.get(inst)?.description},configurable:true});return inst});var _ZodString=$constructor("_ZodString",(inst,def)=>{$ZodString.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json,params)=>stringProcessor(inst,ctx,json,params);const 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())}})});var 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(_emoji2(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(datetime2(params));inst.date=(params)=>inst.check(date2(params));inst.time=(params)=>inst.check(time2(params));inst.duration=(params)=>inst.check(duration2(params))});function string2(params){return _string(ZodString,params)}var ZodStringFormat=$constructor("ZodStringFormat",(inst,def)=>{$ZodStringFormat.init(inst,def);_ZodString.init(inst,def)});var ZodEmail=$constructor("ZodEmail",(inst,def)=>{$ZodEmail.init(inst,def);ZodStringFormat.init(inst,def)});var ZodGUID=$constructor("ZodGUID",(inst,def)=>{$ZodGUID.init(inst,def);ZodStringFormat.init(inst,def)});var ZodUUID=$constructor("ZodUUID",(inst,def)=>{$ZodUUID.init(inst,def);ZodStringFormat.init(inst,def)});var ZodURL=$constructor("ZodURL",(inst,def)=>{$ZodURL.init(inst,def);ZodStringFormat.init(inst,def)});function url(params){return _url(ZodURL,params)}var ZodEmoji=$constructor("ZodEmoji",(inst,def)=>{$ZodEmoji.init(inst,def);ZodStringFormat.init(inst,def)});var ZodNanoID=$constructor("ZodNanoID",(inst,def)=>{$ZodNanoID.init(inst,def);ZodStringFormat.init(inst,def)});var ZodCUID=$constructor("ZodCUID",(inst,def)=>{$ZodCUID.init(inst,def);ZodStringFormat.init(inst,def)});var ZodCUID2=$constructor("ZodCUID2",(inst,def)=>{$ZodCUID2.init(inst,def);ZodStringFormat.init(inst,def)});var ZodULID=$constructor("ZodULID",(inst,def)=>{$ZodULID.init(inst,def);ZodStringFormat.init(inst,def)});var ZodXID=$constructor("ZodXID",(inst,def)=>{$ZodXID.init(inst,def);ZodStringFormat.init(inst,def)});var ZodKSUID=$constructor("ZodKSUID",(inst,def)=>{$ZodKSUID.init(inst,def);ZodStringFormat.init(inst,def)});var ZodIPv4=$constructor("ZodIPv4",(inst,def)=>{$ZodIPv4.init(inst,def);ZodStringFormat.init(inst,def)});var ZodIPv6=$constructor("ZodIPv6",(inst,def)=>{$ZodIPv6.init(inst,def);ZodStringFormat.init(inst,def)});var ZodCIDRv4=$constructor("ZodCIDRv4",(inst,def)=>{$ZodCIDRv4.init(inst,def);ZodStringFormat.init(inst,def)});var ZodCIDRv6=$constructor("ZodCIDRv6",(inst,def)=>{$ZodCIDRv6.init(inst,def);ZodStringFormat.init(inst,def)});var ZodBase64=$constructor("ZodBase64",(inst,def)=>{$ZodBase64.init(inst,def);ZodStringFormat.init(inst,def)});var ZodBase64URL=$constructor("ZodBase64URL",(inst,def)=>{$ZodBase64URL.init(inst,def);ZodStringFormat.init(inst,def)});var ZodE164=$constructor("ZodE164",(inst,def)=>{$ZodE164.init(inst,def);ZodStringFormat.init(inst,def)});var ZodJWT=$constructor("ZodJWT",(inst,def)=>{$ZodJWT.init(inst,def);ZodStringFormat.init(inst,def)});var ZodNumber=$constructor("ZodNumber",(inst,def)=>{$ZodNumber.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json,params)=>numberProcessor(inst,ctx,json,params);_installLazyMethods(inst,"ZodNumber",{gt(value,params){return this.check(_gt(value,params))},gte(value,params){return this.check(_gte(value,params))},min(value,params){return this.check(_gte(value,params))},lt(value,params){return this.check(_lt(value,params))},lte(value,params){return this.check(_lte(value,params))},max(value,params){return this.check(_lte(value,params))},int(params){return this.check(int(params))},safe(params){return this.check(int(params))},positive(params){return this.check(_gt(0,params))},nonnegative(params){return this.check(_gte(0,params))},negative(params){return this.check(_lt(0,params))},nonpositive(params){return this.check(_lte(0,params))},multipleOf(value,params){return this.check(_multipleOf(value,params))},step(value,params){return this.check(_multipleOf(value,params))},finite(){return this}});const bag=inst._zod.bag;inst.minValue=Math.max(bag.minimum??Number.NEGATIVE_INFINITY,bag.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null;inst.maxValue=Math.min(bag.maximum??Number.POSITIVE_INFINITY,bag.exclusiveMaximum??Number.POSITIVE_INFINITY)??null;inst.isInt=(bag.format??"").includes("int")||Number.isSafeInteger(bag.multipleOf??0.5);inst.isFinite=true;inst.format=bag.format??null});function number2(params){return _number(ZodNumber,params)}var ZodNumberFormat=$constructor("ZodNumberFormat",(inst,def)=>{$ZodNumberFormat.init(inst,def);ZodNumber.init(inst,def)});function int(params){return _int(ZodNumberFormat,params)}var ZodBoolean=$constructor("ZodBoolean",(inst,def)=>{$ZodBoolean.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json,params)=>booleanProcessor(inst,ctx,json,params)});function boolean2(params){return _boolean(ZodBoolean,params)}var ZodUnknown=$constructor("ZodUnknown",(inst,def)=>{$ZodUnknown.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json,params)=>unknownProcessor(inst,ctx,json,params)});function unknown(){return _unknown(ZodUnknown)}var ZodNever=$constructor("ZodNever",(inst,def)=>{$ZodNever.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json,params)=>neverProcessor(inst,ctx,json,params)});function never(params){return _never(ZodNever,params)}var 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)}var ZodObject=$constructor("ZodObject",(inst,def)=>{$ZodObjectJIT.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json,params)=>objectProcessor(inst,ctx,json,params);exports_util.defineLazy(inst,"shape",()=>{return def.shape});_installLazyMethods(inst,"ZodObject",{keyof(){return _enum(Object.keys(this._zod.def.shape))},catchall(catchall){return this.clone({...this._zod.def,catchall})},passthrough(){return this.clone({...this._zod.def,catchall:unknown()})},loose(){return this.clone({...this._zod.def,catchall:unknown()})},strict(){return this.clone({...this._zod.def,catchall:never()})},strip(){return this.clone({...this._zod.def,catchall:undefined})},extend(incoming){return exports_util.extend(this,incoming)},safeExtend(incoming){return exports_util.safeExtend(this,incoming)},merge(other){return exports_util.merge(this,other)},pick(mask){return exports_util.pick(this,mask)},omit(mask){return exports_util.omit(this,mask)},partial(...args){return exports_util.partial(ZodOptional,this,args[0])},required(...args){return exports_util.required(ZodNonOptional,this,args[0])}})});function object(shape,params){const def={type:"object",shape:shape??{},...exports_util.normalizeParams(params)};return new ZodObject(def)}var 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,...exports_util.normalizeParams(params)})}var ZodDiscriminatedUnion=$constructor("ZodDiscriminatedUnion",(inst,def)=>{ZodUnion.init(inst,def);$ZodDiscriminatedUnion.init(inst,def)});function discriminatedUnion(discriminator,options,params){return new ZodDiscriminatedUnion({type:"union",options,discriminator,...exports_util.normalizeParams(params)})}var 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})}var ZodRecord=$constructor("ZodRecord",(inst,def)=>{$ZodRecord.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json,params)=>recordProcessor(inst,ctx,json,params);inst.keyType=def.keyType;inst.valueType=def.valueType});function record(keyType,valueType,params){if(!valueType||!valueType._zod){return new ZodRecord({type:"record",keyType:string2(),valueType:keyType,...exports_util.normalizeParams(valueType)})}return new ZodRecord({type:"record",keyType,valueType,...exports_util.normalizeParams(params)})}var ZodEnum=$constructor("ZodEnum",(inst,def)=>{$ZodEnum.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json,params)=>enumProcessor(inst,ctx,json,params);inst.enum=def.entries;inst.options=Object.values(def.entries);const keys=new Set(Object.keys(def.entries));inst.extract=(values,params)=>{const newEntries={};for(const value of values){if(keys.has(value)){newEntries[value]=def.entries[value]}else throw new Error(`Key ${value} not found in enum`)}return new ZodEnum({...def,checks:[],...exports_util.normalizeParams(params),entries:newEntries})};inst.exclude=(values,params)=>{const newEntries={...def.entries};for(const value of values){if(keys.has(value)){delete newEntries[value]}else throw new Error(`Key ${value} not found in enum`)}return new ZodEnum({...def,checks:[],...exports_util.normalizeParams(params),entries:newEntries})}});function _enum(values,params){const entries=Array.isArray(values)?Object.fromEntries(values.map((v)=>[v,v])):values;return new ZodEnum({type:"enum",entries,...exports_util.normalizeParams(params)})}var ZodLiteral=$constructor("ZodLiteral",(inst,def)=>{$ZodLiteral.init(inst,def);ZodType.init(inst,def);inst._zod.processJSONSchema=(ctx,json,params)=>literalProcessor(inst,ctx,json,params);inst.values=new Set(def.values);Object.defineProperty(inst,"value",{get(){if(def.values.length>1){throw new Error("This schema contains multiple valid literal values. Use `.values` instead.")}return def.values[0]}})});function literal(value,params){return new ZodLiteral({type:"literal",values:Array.isArray(value)?value:[value],...exports_util.normalizeParams(params)})}var 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=(issue2)=>{if(typeof issue2==="string"){payload.issues.push(exports_util.issue(issue2,payload.value,def))}else{const _issue=issue2;if(_issue.fatal)_issue.continue=false;_issue.code??(_issue.code="custom");_issue.input??(_issue.input=payload.value);_issue.inst??(_issue.inst=inst);payload.issues.push(exports_util.issue(_issue))}};const output=def.transform(payload.value,payload);if(output instanceof Promise){return output.then((output2)=>{payload.value=output2;payload.fallback=true;return payload})}payload.value=output;payload.fallback=true;return payload}});function transform(fn){return new ZodTransform({type:"transform",transform:fn})}var 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})}var 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})}var 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})}var 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():exports_util.shallowClone(defaultValue)}})}var 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():exports_util.shallowClone(defaultValue)}})}var 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,...exports_util.normalizeParams(params)})}var 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})}var 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})}var 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})}var 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)}var ImageAssetSchema=object({id:string2().min(1),type:literal("image"),path:string2().min(1),width:number2().int().positive().optional(),height:number2().int().positive().optional()});var SpritesheetAssetSchema=object({id:string2().min(1),type:literal("spritesheet"),path:string2().min(1),width:number2().int().positive().optional(),height:number2().int().positive().optional(),frameWidth:number2().int().positive(),frameHeight:number2().int().positive(),animations:array(object({key:string2().min(1),frames:array(number2().int().nonnegative()),frameRate:number2().positive().optional(),repeat:number2().int().optional()})).optional()});var AudioAssetSchema=object({id:string2().min(1),type:literal("audio"),path:string2().min(1),duration:number2().nonnegative().optional(),formats:array(_enum(["wav","mp3","ogg","m4a","webm"])).optional()});var ModelAssetSchema=object({id:string2().min(1),type:literal("model"),path:string2().min(1),format:_enum(["glb","gltf","obj","fbx"]),triangles:number2().int().positive().optional(),animations:array(string2()).optional()});var ShaderAssetSchema=object({id:string2().min(1),type:literal("shader"),path:string2().min(1),stage:_enum(["vertex","fragment","compute"])});var TilesetAssetSchema=object({id:string2().min(1),type:literal("tileset"),path:string2().min(1),tileWidth:number2().int().positive(),tileHeight:number2().int().positive(),columns:number2().int().positive().optional(),rows:number2().int().positive().optional()});var AssetSchema=discriminatedUnion("type",[ImageAssetSchema,SpritesheetAssetSchema,AudioAssetSchema,ModelAssetSchema,ShaderAssetSchema,TilesetAssetSchema]);var RegistryConfigSchema=union([string2().min(1),object({url:string2().min(1),index:string2().min(1).optional(),headers:record(string2(),string2()).optional()})]);var DepSpecRegex=/^(?:@[a-z0-9][a-z0-9_-]*\/[a-z0-9][a-z0-9_./-]*|[a-z0-9][a-z0-9_-]*|https?:\/\/[^\s]+|gh:[^\s]+|github:[^\s]+|\.{1,2}\/[^\s]+)$/i;var GamecnConfigSchema=object({$schema:string2().optional(),engine:_enum(["phaser","three","pixi","vanilla"]),framework:_enum(["vanilla","react"]),language:_enum(["typescript","javascript"]),packageManager:_enum(["npm","pnpm","yarn","bun"]).optional().default("npm"),paths:object({src:string2().min(1),assets:string2().min(1),components:string2().optional(),systems:string2().optional(),scenes:string2().optional(),shaders:string2().optional(),ui:string2().optional()}),registries:record(string2(),RegistryConfigSchema).optional(),deps:array(string2().regex(DepSpecRegex,{error:"Each `deps[]` entry must be a registry spec — e.g. `event-bus`, `@main/event-bus`, or `https://...`."})).optional()});var ITEM_TYPES=["registry:template","registry:scene","registry:component","registry:system","registry:asset","registry:shader","registry:audio","registry:model","registry:tileset","registry:ui","registry:hook","registry:utility","registry:config","registry:recipe","registry:plugin"];var LockedFileSchema=object({path:string2().min(1),sha256:string2().regex(/^[a-f0-9]{64}$/,{error:"sha256 must be a 64-character lowercase hex string."})});var LockedItemSchema=object({name:string2().min(1),version:string2().min(1),registry:string2().min(1),resolved:string2().min(1),installedAt:string2(),files:array(LockedFileSchema)});var LockfileSchema=object({$schema:string2().optional(),version:literal(1),items:record(string2(),LockedItemSchema)});var ItemSummarySchema=object({name:string2().min(1),type:_enum(ITEM_TYPES),title:string2(),description:string2(),version:string2().min(1),engines:array(string2()).optional(),frameworks:array(string2()).optional(),languages:array(string2()).optional(),tags:array(string2()).optional()});var RegistryIndexSchema=object({$schema:string2().optional(),name:string2().min(1),homepage:url().optional(),items:array(ItemSummarySchema)});var GENRE_TAGS=["endless-runner","dodger","platformer","top-down-shooter","twin-stick","tower-defense","survivors","racing","puzzle","arcade","simulation","fighter","rpg","blank"];var STYLE_TAGS=["pixel","flat-2d","hand-drawn","low-poly-3d","voxel","photoreal-3d"];var PLATFORM_TAGS=["web","mobile-web","desktop"];var NAMESPACE_VALUES={genre:new Set(GENRE_TAGS),style:new Set(STYLE_TAGS),platform:new Set(PLATFORM_TAGS)};var CONTROLLED_PREFIXES=Object.keys(NAMESPACE_VALUES);function isControlledTag(tag){const idx=tag.indexOf(":");if(idx<=0)return false;const ns=tag.slice(0,idx);const value=tag.slice(idx+1);const allowed=NAMESPACE_VALUES[ns];return allowed!==undefined&&allowed.has(value)}function hasControlledPrefix(tag){for(const ns of CONTROLLED_PREFIXES){if(tag.startsWith(ns+":"))return true}return false}var semverRegex=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$/;var numericIdentifier="(?:0|[1-9]\\d*)";var prereleaseIdentifier=[numericIdentifier,"\\d*[a-zA-Z-][0-9a-zA-Z-]*"].join("|");var prerelease=`(?:${prereleaseIdentifier})(?:\\.(?:${prereleaseIdentifier}))*`;var build="[0-9a-zA-Z-]+(?:\\.[0-9a-zA-Z-]+)*";var concretePatch=`${numericIdentifier}(?:-${prerelease})?(?:\\+${build})?`;var patch=`(?:[xX*]|${concretePatch})`;var minor=`(?:[xX*]|${numericIdentifier}(?:\\.${patch})?)`;var rangeVersion=`(?:[xX*]|${numericIdentifier}(?:\\.${minor})?)`;var comparatorOperator="(?:<=|>=|<|>|=|~>|~|\\^)";var comparator=`(?:(?:${comparatorOperator})\\s*)?${rangeVersion}`;var comparatorSet=`${comparator}(?:\\s+${comparator})*`;var hyphenRange=`${rangeVersion}\\s+-\\s+${rangeVersion}`;var simpleRange=`(?:${hyphenRange}|${comparatorSet})`;var semverRangeRegex=new RegExp(`^\\s*${simpleRange}(?:\\s*\\|\\|\\s*${simpleRange})*\\s*$`);var FILE_TYPES=["source","asset","documentation"];var integrityRegex=/^sha256-[A-Za-z0-9+/=]+$/;var FileSpecSchema=object({path:string2().min(1),target:string2().min(1),type:_enum(FILE_TYPES),language:_enum(["typescript","javascript"]).optional(),content:string2().optional(),url:url().optional(),integrity:string2().regex(integrityRegex,{error:"Integrity must be a Subresource Integrity string (sha256-...)."}).optional()}).refine((obj)=>!(obj.content!==undefined&&obj.url!==undefined),{error:"File spec cannot have both `content` and `url`."});var PreloadInstructionSchema=object({kind:string2().min(1),key:string2().min(1),path:string2().min(1),frameWidth:number2().int().positive().optional(),frameHeight:number2().int().positive().optional()}).catchall(unknown());var IntegrationBlockSchema=object({preload:array(PreloadInstructionSchema).optional(),usage:array(string2()).optional()});var AuthorSchema=union([string2().min(1),object({name:string2().min(1),url:url().optional(),email:string2().optional()})]);var RegistryItemSchema=object({$schema:string2().optional(),name:string2().min(1),type:_enum(ITEM_TYPES),title:string2(),description:string2(),version:string2().regex(semverRegex,{error:"Invalid SemVer string."}),license:string2().optional(),licenseUrl:url().optional(),author:AuthorSchema,tags:array(string2().refine((s)=>!hasControlledPrefix(s)||isControlledTag(s),{error:"Namespaced tag (genre:/style:/platform:) suffix is not in the controlled vocabulary."})).optional(),attributionRequired:boolean2().optional(),commercialUse:boolean2().optional(),redistribution:boolean2().optional(),aiGenerated:boolean2().optional(),compatibility:object({engines:record(string2(),string2().regex(semverRangeRegex)),frameworks:array(_enum(["vanilla","react"])),languages:array(_enum(["typescript","javascript"])),bundlers:array(string2()),libraries:record(string2(),string2().regex(semverRangeRegex)).optional(),platforms:array(string2()).optional()}).optional(),dependencies:object({npm:array(string2()).optional(),registry:array(string2()).optional()}).optional(),files:array(FileSpecSchema),assets:array(AssetSchema).optional(),integration:record(string2(),IntegrationBlockSchema).optional(),preview:object({thumbnail:url().optional(),demo:url().optional(),gif:url().optional()}).optional()});class GamecnError extends Error{constructor(message,name="GamecnError"){super(message);this.name=name}}class ItemNotFoundError extends GamecnError{spec;constructor(spec,reason){super(`Could not resolve item "${spec}": ${reason}`,"ItemNotFoundError");this.spec=spec}}class IntegrityError extends GamecnError{path;expected;actual;constructor(path,expected,actual){super(`Integrity check failed for ${path} (expected ${expected}, got ${actual})`,"IntegrityError");this.path=path;this.expected=expected;this.actual=actual}}class ConflictError extends GamecnError{path;constructor(path){super(`File already exists: ${path}`,"ConflictError");this.path=path}}class IncompatibleError extends GamecnError{constructor(message){super(message,"IncompatibleError")}}class IncompatibleVersionError extends GamecnError{itemName;engine;required;installed;constructor(itemName,engine,required2,installed){super(`${itemName} requires ${engine} ${required2}, but ${installed} is installed.`,"IncompatibleVersionError");this.itemName=itemName;this.engine=engine;this.required=required2;this.installed=installed}}class PathEscapeError extends GamecnError{constructor(target,resolved){super(`File target "${target}" resolves outside the project root (${resolved})`,"PathEscapeError")}}class UnsupportedSourceError extends GamecnError{constructor(message){super(message,"UnsupportedSourceError")}}class HttpError extends GamecnError{url;status;statusText;constructor(url2,status,statusText){super(`HTTP ${status} ${statusText}: ${url2}`,"HttpError");this.url=url2;this.status=status;this.statusText=statusText}}class MissingEnvVarError extends GamecnError{variable;constructor(variable){super(`Required environment variable not set: ${variable}`,"MissingEnvVarError");this.variable=variable}}function resolveTargetPath(config2,target,cwd){const paths=config2.paths;const placeholders={"{src}":paths.src,"{assets}":paths.assets,"{components}":paths.components??join(paths.src,"components"),"{systems}":paths.systems??join(paths.src,"systems"),"{scenes}":paths.scenes??join(paths.src,"scenes"),"{shaders}":paths.shaders??join(paths.src,"shaders"),"{ui}":paths.ui??join(paths.src,"ui")};let interpolated=target;for(const[k3,v]of Object.entries(placeholders)){interpolated=interpolated.split(k3).join(v)}const absCwd=resolve(cwd);const absTarget=isAbsolute(interpolated)?resolve(interpolated):resolve(absCwd,interpolated);if(absTarget!==absCwd&&!absTarget.startsWith(absCwd+sep)){throw new PathEscapeError(target,absTarget)}return absTarget}import{createHash}from"node:crypto";import{readFile,writeFile}from"node:fs/promises";import{join as join2}from"node:path";var LOCKFILE_NAME="gamecn-lock.json";async function loadLockfile(cwd){const path=join2(cwd,LOCKFILE_NAME);try{const raw=await readFile(path,"utf8");return LockfileSchema.parse(JSON.parse(raw))}catch(err){if(err.code==="ENOENT"){return{version:1,items:{}}}throw err}}async function saveLockfile(cwd,lock){const path=join2(cwd,LOCKFILE_NAME);await writeFile(path,JSON.stringify(lock,null,2)+`
114
- `,"utf8")}function sha256OfBuffer(buf){const hash=createHash("sha256");hash.update(buf);return hash.digest("hex")}function recordInstall(lock,item,registry2,resolved,files){lock.items[item.name]={name:item.name,version:item.version,registry:registry2,resolved,installedAt:new Date().toISOString(),files}}var import_semver=__toESM(require_semver2(),1);import{readFile as readFile2,stat}from"node:fs/promises";import{join as join3,relative,resolve as resolve2}from"node:path";async function fileExists(path){try{await stat(path);return true}catch{return false}}function planFileSource(spec,baseDir,headers){if(spec.content!==undefined){return{kind:"inline",content:spec.content}}if(spec.url!==undefined){return{kind:"remote",url:spec.url,integrity:spec.integrity,...headers?{headers}:{}}}if(baseDir===undefined){throw new UnsupportedSourceError(`File "${spec.path}" has neither content nor url, and no baseDir is set for resolution.`)}return{kind:"local",absolutePath:resolve2(baseDir,spec.path)}}async function readPackageJson(cwd){try{const raw=await readFile2(join3(cwd,"package.json"),"utf8");return JSON.parse(raw)}catch{return}}function depName(spec){if(spec.startsWith("@")){const at2=spec.indexOf("@",1);return at2===-1?spec:spec.slice(0,at2)}const at=spec.indexOf("@");return at===-1?spec:spec.slice(0,at)}function normalizePath(p2){return p2.split(/[\\/]/).join("/")}async function plan(resolved,config2,lock,cwd){const item=resolved.item;const lockEntry=lock.items[item.name];const alreadyInstalled=lockEntry!==undefined&&lockEntry.version===item.version;const files=[];const conflicts=[];for(const spec of item.files){const target=resolveTargetPath(config2,spec.target,cwd);const source=planFileSource(spec,resolved.baseDir,resolved.headers);files.push({spec,source,target});if(await fileExists(target)){const targetRel=normalizePath(relative(cwd,target));const existingOwner=Object.values(lock.items).find((entry)=>entry.files.some((f)=>normalizePath(f.path)===targetRel));if(existingOwner===undefined||existingOwner.name!==item.name){conflicts.push({target,reason:"exists",ownedBy:existingOwner?.name})}}}const pkg=await readPackageJson(cwd);const allDeps={...pkg?.dependencies,...pkg?.devDependencies,...pkg?.peerDependencies};const npmDeps=(item.dependencies?.npm??[]).filter((d3)=>{const name=depName(d3);return!(name in allDeps)});const registryDeps=item.dependencies?.registry??[];const incompatibilities=checkEngineCompatibility(item,allDeps);return{item,resolved,files,conflicts,incompatibilities,npmDeps,registryDeps,alreadyInstalled}}function checkEngineCompatibility(item,allDeps){const required2=item.compatibility?.engines;if(!required2)return[];const out=[];for(const[engine,range]of Object.entries(required2)){const installed=allDeps[engine];if(!installed)continue;const minInstalled=import_semver.default.minVersion(installed);if(!minInstalled)continue;if(!import_semver.default.satisfies(minInstalled,range,{includePrerelease:true})){out.push({itemName:item.name,engine,required:range,installed,message:`${item.name} requires ${engine} ${range}, but ${installed} is installed.`})}}return out}import{randomBytes}from"node:crypto";import{mkdir,readFile as readFile3,rename,writeFile as writeFile2}from"node:fs/promises";import{dirname,relative as relative2}from"node:path";async function readSource(file,fetcher){switch(file.source.kind){case"inline":return file.source.content;case"local":return readFile3(file.source.absolutePath);case"remote":if(!fetcher){throw new UnsupportedSourceError(`Remote file "${file.spec.path}" requires an AssetFetcher. Pass one to executePlan via the fetcher argument.`)}return fetcher.fetch(file.source.url,file.source.integrity,file.source.headers)}}async function writeAtomic(target,data){await mkdir(dirname(target),{recursive:true});const tmp=`${target}.tmp.${randomBytes(6).toString("hex")}`;await writeFile2(tmp,data);await rename(tmp,target)}function normalizeRelPath(absPath,cwd){return relative2(cwd,absPath).split(/[\\/]/).join("/")}async function executePlan(plan2,lock,cwd,options={},fetcher){const result={itemName:plan2.item.name,installed:[],skipped:[]};if(options.dryRun){return result}if(plan2.incompatibilities.length>0&&!options.force){const first=plan2.incompatibilities[0];throw new IncompatibleVersionError(first.itemName,first.engine,first.required,first.installed)}if(plan2.conflicts.length>0&&!options.force){const first=plan2.conflicts[0];throw new ConflictError(first.target)}for(const file of plan2.files){const data=await readSource(file,fetcher);await writeAtomic(file.target,data);const buf=typeof data==="string"?Buffer.from(data,"utf8"):data;const sha=sha256OfBuffer(buf);result.installed.push({path:normalizeRelPath(file.target,cwd),sha256:sha})}recordInstall(lock,plan2.item,plan2.resolved.registry,plan2.resolved.resolved,result.installed);return result}import{createHash as createHash3}from"node:crypto";import{mkdir as mkdir2,readFile as readFile4,rename as rename2,writeFile as writeFile3}from"node:fs/promises";import{homedir}from"node:os";import{dirname as dirname2,join as join4}from"node:path";import{createHash as createHash2}from"node:crypto";var SRI_RE=/^sha256-([A-Za-z0-9+/]+={0,2})$/;function parseSriSha256(sri){const m2=SRI_RE.exec(sri);if(!m2){throw new Error(`Invalid SRI string (expected "sha256-<base64>"): ${sri}`)}return Buffer.from(m2[1],"base64")}function sriOfBuffer(data){return"sha256-"+createHash2("sha256").update(data).digest("base64")}function hexOfSri(sri){return parseSriSha256(sri).toString("hex")}function verifyIntegrity(sri,data,label){const expected=parseSriSha256(sri);const actual=createHash2("sha256").update(data).digest();if(!expected.equals(actual)){throw new IntegrityError(label,sri,sriOfBuffer(data))}}function defaultCacheDir(){return process.env.GAMECN_CACHE_DIR??join4(homedir(),".gamecn","cache")}function sha1(s){return createHash3("sha1").update(s).digest("hex")}async function sleep(ms){return new Promise((res)=>setTimeout(res,ms))}async function fetchWithRetry(url2,init,opts={}){const attempts=opts.attempts??3;const initialDelayMs=opts.initialDelayMs??250;const fetcher=init.fetcher??fetch;const{fetcher:_3,...rest}=init;let lastErr;for(let i=0;i<attempts;i++){try{const res=await fetcher(url2,rest);if(res.status>=500&&res.status<600&&i<attempts-1){await sleep(initialDelayMs*2**i);continue}return res}catch(err){lastErr=err;if(i<attempts-1){await sleep(initialDelayMs*2**i);continue}}}throw lastErr??new Error(`fetch failed after ${attempts} attempts: ${url2}`)}async function readJsonIfExists(path){try{return JSON.parse(await readFile4(path,"utf8"))}catch(err){if(err.code==="ENOENT")return;throw err}}class ManifestCache{dir;fetcher;constructor(cacheDir,fetcher=fetch){this.dir=join4(cacheDir,"manifests");this.fetcher=fetcher}async getOrFetch(url2,headers={}){const key=sha1(url2);const file=join4(this.dir,`${key}.json`);const metaFile=join4(this.dir,`${key}.meta.json`);const meta2=await readJsonIfExists(metaFile);const reqHeaders={...headers};if(meta2?.etag)reqHeaders["If-None-Match"]=meta2.etag;const res=await fetchWithRetry(url2,{method:"GET",headers:reqHeaders,fetcher:this.fetcher});if(res.status===304){const cached2=await readJsonIfExists(file);if(cached2!==undefined)return cached2;const refetch=await fetchWithRetry(url2,{method:"GET",headers,fetcher:this.fetcher});return parseAndCache(refetch,url2,file,metaFile)}if(!res.ok){throw new HttpError(url2,res.status,res.statusText)}return parseAndCache(res,url2,file,metaFile)}}async function parseAndCache(res,url2,file,metaFile){const text=await res.text();let json;try{json=JSON.parse(text)}catch(err){throw new HttpError(url2,res.status,`invalid JSON: ${err.message}`)}await mkdir2(dirname2(file),{recursive:true});await writeFile3(file,text,"utf8");const meta2={etag:res.headers.get("etag")??undefined,fetchedAt:new Date().toISOString()};await writeFile3(metaFile,JSON.stringify(meta2),"utf8");return json}class AssetCache{dir;fetcher;constructor(cacheDir,fetcher=fetch){this.dir=join4(cacheDir,"assets");this.fetcher=fetcher}async getOrFetch(url2,integrity,headers={}){if(integrity){const hex2=hexOfSri(integrity);const cached2=join4(this.dir,hex2);try{const buf2=await readFile4(cached2);verifyIntegrity(integrity,buf2,cached2);return buf2}catch(err){if(err.code!=="ENOENT"){}}}const res=await fetchWithRetry(url2,{method:"GET",headers,fetcher:this.fetcher});if(!res.ok){throw new HttpError(url2,res.status,res.statusText)}const buf=Buffer.from(await res.arrayBuffer());if(integrity){verifyIntegrity(integrity,buf,url2)}const hex=createHash3("sha256").update(buf).digest("hex");const target=join4(this.dir,hex);await mkdir2(dirname2(target),{recursive:true});const tmp=`${target}.tmp.${createHash3("sha1").update(`${url2}${Date.now()}`).digest("hex").slice(0,8)}`;await writeFile3(tmp,buf);try{await rename2(tmp,target)}catch{}return buf}}import{isAbsolute as isAbsolute2}from"node:path";var ENV_VAR_RE=/\$\{([A-Za-z_][A-Za-z0-9_]*)\}/g;function interpolateHeaders(headers,env=process.env){const out={};for(const[k3,v]of Object.entries(headers)){out[k3]=interpolate(v,env)}return out}function interpolate(template,env=process.env){return template.replace(ENV_VAR_RE,(_3,name)=>{const value=env[name];if(value===undefined){throw new MissingEnvVarError(name)}return value})}var DEFAULT_REGISTRY_URL="https://gamecn.dev/r/{name}.json";var BARE_NAME_RE=/^[a-z0-9][a-z0-9_-]{0,213}$/i;class DefaultRegistryResolver{config;cache;env;constructor(config2,cache,env=process.env){this.config=config2;this.cache=cache;this.env=env}canResolve(spec){if(spec.startsWith("@"))return false;if(spec.startsWith("http://")||spec.startsWith("https://"))return false;if(spec.startsWith("gh:")||spec.startsWith("github:"))return false;if(spec.startsWith("./")||spec.startsWith("../"))return false;if(isAbsolute2(spec))return false;if(spec.endsWith(".json"))return false;if(spec.includes("/")||spec.includes("\\"))return false;return BARE_NAME_RE.test(spec)}async resolve(spec,_ctx){const reg=this.config.registries?.["@main"];const urlTemplate=!reg?DEFAULT_REGISTRY_URL:typeof reg==="string"?reg:reg.url;const rawHeaders=typeof reg==="object"&&reg.headers?reg.headers:{};const headers=interpolateHeaders(rawHeaders,this.env);const url2=urlTemplate.replace(/\{name\}/g,spec);try{const json=await this.cache.getOrFetch(url2,headers);const item=RegistryItemSchema.parse(json);return{item,spec,registry:"@main",resolved:url2,headers:Object.keys(headers).length>0?headers:undefined}}catch(err){if(err instanceof HttpError&&err.status===404){throw new ItemNotFoundError(spec,`not found in the default @main registry (${url2}). Either configure 'registries["@main"]' in gamecn.json to point at a different registry, or use a fully-qualified spec (\`@scope/name\`, \`./local.json\`, \`gh:owner/repo/path\`, or \`https://...\`).`)}throw err}}}var GH_PREFIX_RE=/^(gh|github):/;function parseGitHubSpec(spec){if(!GH_PREFIX_RE.test(spec)){throw new ItemNotFoundError(spec,"not a GitHub spec")}const stripped=spec.replace(GH_PREFIX_RE,"");const hashIdx=stripped.indexOf("#");const pathPart=hashIdx===-1?stripped:stripped.slice(0,hashIdx);const ref=hashIdx===-1?"HEAD":stripped.slice(hashIdx+1)||"HEAD";const segs=pathPart.split("/").filter(Boolean);if(segs.length<3){throw new ItemNotFoundError(spec,"expected gh:owner/repo/path/to/item.json")}const[owner,repo,...rest]=segs;return{owner,repo,path:rest.join("/"),ref,hasExplicitRef:hashIdx!==-1}}function githubSpecToUrl(spec){const p2=parseGitHubSpec(spec);return`https://raw.githubusercontent.com/${p2.owner}/${p2.repo}/${p2.ref}/${p2.path}`}class GitHubResolver{cache;env;warn;constructor(cache,env=process.env,warn=(m2)=>console.warn(m2)){this.cache=cache;this.env=env;this.warn=warn}canResolve(spec){return GH_PREFIX_RE.test(spec)}async resolve(spec,_ctx){const parsed=parseGitHubSpec(spec);if(!parsed.hasExplicitRef){this.warn(`[gamecn] ${spec} has no ref; using HEAD (non-reproducible). Pin a ref with #v1.2.0 or #commit-sha.`)}const url2=githubSpecToUrl(spec);const headers={};const token=this.env["GITHUB_TOKEN"];if(token)headers["Authorization"]=`token ${token}`;const json=await this.cache.getOrFetch(url2,headers);const item=RegistryItemSchema.parse(json);return{item,spec,registry:"github",resolved:url2,headers:Object.keys(headers).length>0?headers:undefined}}}class HttpsResolver{cache;headers;constructor(cache,headers={}){this.cache=cache;this.headers=headers}canResolve(spec){return spec.startsWith("http://")||spec.startsWith("https://")}async resolve(spec,_ctx){const json=await this.cache.getOrFetch(spec,this.headers);const item=RegistryItemSchema.parse(json);return{item,spec,registry:"https",resolved:spec,headers:Object.keys(this.headers).length>0?this.headers:undefined}}}import{readFile as readFile5}from"node:fs/promises";import{dirname as dirname3,isAbsolute as isAbsolute3,resolve as resolve3}from"node:path";class LocalFileResolver{canResolve(spec){if(spec.startsWith("./")||spec.startsWith("../"))return true;if(spec.startsWith("/")||spec.startsWith("~/"))return true;if(/^[A-Za-z]:[\\/]/.test(spec))return true;if(spec.endsWith(".json"))return true;return false}async resolve(spec,ctx){const absSpec=isAbsolute3(spec)?spec:resolve3(ctx.cwd,spec);let raw;try{raw=await readFile5(absSpec,"utf8")}catch(err){const code=err.code;throw new ItemNotFoundError(spec,code==="ENOENT"?"file not found":`read failed: ${err.message}`)}let json;try{json=JSON.parse(raw)}catch(err){throw new ItemNotFoundError(spec,`JSON parse error: ${err.message}`)}const item=RegistryItemSchema.parse(json);return{item,spec,registry:"local",resolved:absSpec,baseDir:dirname3(absSpec)}}}var NAMESPACE_RE=/^(@[A-Za-z0-9_-]+)\/(.+)$/;class NamespaceResolver{config;cache;env;constructor(config2,cache,env=process.env){this.config=config2;this.cache=cache;this.env=env}canResolve(spec){return NAMESPACE_RE.test(spec)}async resolve(spec,_ctx){const m2=NAMESPACE_RE.exec(spec);if(!m2)throw new ItemNotFoundError(spec,"not a namespaced spec");const namespace=m2[1];const name=m2[2];const reg=this.config.registries?.[namespace];if(!reg){throw new ItemNotFoundError(spec,`unknown registry namespace "${namespace}". Add it to gamecn.json#registries.`)}const urlTemplate=typeof reg==="string"?reg:reg.url;const rawHeaders=typeof reg==="string"?{}:reg.headers??{};const headers=interpolateHeaders(rawHeaders,this.env);const url2=urlTemplate.replace(/\{name\}/g,name);const json=await this.cache.getOrFetch(url2,headers);const item=RegistryItemSchema.parse(json);return{item,spec,registry:namespace,resolved:url2,headers:Object.keys(headers).length>0?headers:undefined}}}function createResolver(config2,opts={}){const cacheDir=opts.cacheDir??defaultCacheDir();const fetcher=opts.fetcher??fetch;const env=opts.env??process.env;const manifestCache=new ManifestCache(cacheDir,fetcher);const resolvers=[new NamespaceResolver(config2,manifestCache,env),new GitHubResolver(manifestCache,env),new DefaultRegistryResolver(config2,manifestCache,env),new HttpsResolver(manifestCache),new LocalFileResolver];return{canResolve(spec){return resolvers.some((r2)=>r2.canResolve(spec))},async resolve(spec,ctx){for(const r2 of resolvers){if(r2.canResolve(spec))return r2.resolve(spec,ctx)}throw new ItemNotFoundError(spec,"no resolver matches this spec")}}}function createAssetFetcher(opts={}){const cacheDir=opts.cacheDir??defaultCacheDir();const fetcher=opts.fetcher??fetch;const cache=new AssetCache(cacheDir,fetcher);return{fetch:(url2,integrity,headers)=>cache.getOrFetch(url2,integrity,headers)}}var TEXT_EXTS=new Set([".ts",".tsx",".js",".jsx",".mjs",".cjs"]);var MAX_SCAN_BYTES=256*1024;var SKIP_DIRS=new Set(["node_modules",".git","dist",".turbo",".cache","registry-dist"]);var DEFAULT_REGISTRY="https://gamecn.dev/r/{name}.json";function detectPackageManager2(){const ua=process.env.npm_config_user_agent;if(ua){const name=ua.split(" ")[0]?.split("/")[0];if(name==="bun"||name==="pnpm"||name==="yarn"||name==="npm"){return name}}return"pnpm"}var NAME_RE=/^[a-z0-9][a-z0-9._-]{0,213}$/i;var RESERVED=new Set(["node_modules","favicon.ico"]);function validateProjectName(name){if(!NAME_RE.test(name)){throw new Error(`Invalid project name "${name}". Use lowercase letters, numbers, dot, underscore, or hyphen.`)}if(RESERVED.has(name)||name.startsWith(".")||name.startsWith("_")){throw new Error(`Reserved or invalid project name: "${name}".`)}}async function dirIsEmptyOrMissing(path){try{const entries=await readdir(path);return entries.length===0}catch(err){if(err.code==="ENOENT")return true;throw err}}function resolveTemplateSpec(template){if(template.startsWith("@")||template.startsWith("http://")||template.startsWith("https://")||template.startsWith("gh:")||template.startsWith("github:")||template.startsWith("./")||template.startsWith("/")||/^[A-Za-z]:[\\/]/.test(template)){return template}return`@main/${template}`}async function defaultInstallRunner(cwd,pm){await new Promise((res,rej)=>{const proc=spawn(pm,["install"],{cwd,stdio:"inherit",shell:process.platform==="win32"});proc.on("exit",(code)=>{if(code===0)res();else rej(new Error(`${pm} install exited with code ${code}`))});proc.on("error",rej)})}async function scaffold(opts){validateProjectName(opts.name);const parentDir=opts.parentDir??process.cwd();const cwd=resolve4(parentDir,opts.name);if(!await dirIsEmptyOrMissing(cwd)&&!opts.force){throw new Error(`Directory "${opts.name}" already exists and is not empty. Pass --force to overwrite.`)}await mkdir3(cwd,{recursive:true});const pm=opts.packageManager??detectPackageManager2();const config2={engine:"phaser",framework:"vanilla",language:"typescript",packageManager:pm,paths:{src:"src",assets:"public/assets"},registries:{"@main":opts.registry??DEFAULT_REGISTRY}};const resolverOpts=opts.cacheDir?{cacheDir:opts.cacheDir}:{};const resolver=createResolver(config2,resolverOpts);const fetcher=createAssetFetcher(resolverOpts);const spec=resolveTemplateSpec(opts.template);const resolved=await resolver.resolve(spec,{cwd,config:config2});if(resolved.item.type!=="registry:template"){throw new IncompatibleError(`"${spec}" is type ${resolved.item.type}, not registry:template.`)}const lock=await loadLockfile(cwd);const p2=await plan(resolved,config2,lock,cwd);const result=await executePlan(p2,lock,cwd,{force:opts.force??false},fetcher);await saveLockfile(cwd,lock);const pkgPath=resolve4(cwd,"package.json");try{const raw=await readFile6(pkgPath,"utf8");const pkg=JSON.parse(raw);pkg.name=opts.name;await writeFile4(pkgPath,JSON.stringify(pkg,null,2)+`
115
- `,"utf8")}catch(err){if(err.code!=="ENOENT")throw err}const postScaffoldDeps=await installPostScaffoldDeps(cwd,opts.registry,opts.cacheDir,opts.force??false);let installed=false;if(!opts.skipInstall){const runner=opts.installRunner??defaultInstallRunner;await runner(cwd,pm);installed=true}return{cwd,packageManager:pm,installed,templateName:resolved.item.name,filesWritten:result.installed.length+postScaffoldDeps.length,postScaffoldDeps:postScaffoldDeps.map((d3)=>d3.spec)}}async function installPostScaffoldDeps(cwd,registryOverride,cacheDir,force){const cfgPath=resolve4(cwd,"gamecn.json");let raw;try{raw=await readFile6(cfgPath,"utf8")}catch(err){if(err.code==="ENOENT")return[];throw err}const projectConfig=GamecnConfigSchema.parse(JSON.parse(raw));const deps=projectConfig.deps??[];if(deps.length===0)return[];const config2=registryOverride?{...projectConfig,registries:{...projectConfig.registries,"@main":registryOverride}}:projectConfig;const resolverOpts=cacheDir?{cacheDir}:{};const resolver=createResolver(config2,resolverOpts);const fetcher=createAssetFetcher(resolverOpts);const lock=await loadLockfile(cwd);const installed=[];for(const spec of deps){const resolvedDep=await resolver.resolve(spec,{cwd,config:config2});if(resolvedDep.item.type==="registry:template"){throw new IncompatibleError(`Template's gamecn.json#deps entry "${spec}" resolved to a registry:template — deps[] is for components/systems/assets, not templates.`)}const p2=await plan(resolvedDep,config2,lock,cwd);const r2=await executePlan(p2,lock,cwd,{force},fetcher);installed.push({spec,fileCount:r2.installed.length})}await saveLockfile(cwd,lock);return installed}var TEMPLATES=[{value:"phaser-endless-runner",label:"Phaser Endless Runner",hint:"Vite + TypeScript + Phaser 3"}];async function pickTemplate(opts){if(opts.template)return opts.template;if(opts.yes){throw new Error("--template is required when --yes is set.")}const choice=await ve({message:"Template?",options:TEMPLATES});if(pD(choice)){xe("Cancelled.");process.exit(1)}return choice}var program2=new Command;program2.name("create-gamecn").description("Scaffold a new gamecn project from a template").version("0.0.1").argument("<name>","project directory name").option("--template <name>","template name or full spec").option("--registry <url>","registry URL with {name} placeholder",DEFAULT_REGISTRY).option("--package-manager <pm>","package manager (npm|pnpm|yarn|bun); defaults to the one that invoked this command").option("--yes","skip prompts").option("--force","overwrite a non-empty target directory").option("--no-install","skip dependency install").action(async(name,opts)=>{try{if(!opts.yes)Ie(import_picocolors2.default.cyan(`create-gamecn ${name}`));const template=await pickTemplate(opts);const pm=opts.packageManager??detectPackageManager2();const scaffoldOpts={name,template,registry:opts.registry,packageManager:pm,skipInstall:opts.install===false,force:opts.force};const result=await scaffold(scaffoldOpts);const next=result.installed?`cd ${name}
114
+ `,"utf8")}function sha256OfBuffer(buf){const hash=createHash("sha256");hash.update(buf);return hash.digest("hex")}function recordInstall(lock,item,registry2,resolved,files){lock.items[item.name]={name:item.name,version:item.version,registry:registry2,resolved,installedAt:new Date().toISOString(),files}}var import_semver=__toESM(require_semver2(),1);import{readFile as readFile2,stat}from"node:fs/promises";import{join as join3,relative,resolve as resolve2}from"node:path";async function fileExists(path){try{await stat(path);return true}catch{return false}}function planFileSource(spec,baseDir,headers){if(spec.content!==undefined){return{kind:"inline",content:spec.content}}if(spec.url!==undefined){return{kind:"remote",url:spec.url,integrity:spec.integrity,...headers?{headers}:{}}}if(baseDir===undefined){throw new UnsupportedSourceError(`File "${spec.path}" has neither content nor url, and no baseDir is set for resolution.`)}return{kind:"local",absolutePath:resolve2(baseDir,spec.path)}}async function readPackageJson(cwd){try{const raw=await readFile2(join3(cwd,"package.json"),"utf8");return JSON.parse(raw)}catch{return}}function depName(spec){if(spec.startsWith("@")){const at2=spec.indexOf("@",1);return at2===-1?spec:spec.slice(0,at2)}const at=spec.indexOf("@");return at===-1?spec:spec.slice(0,at)}function normalizePath(p2){return p2.split(/[\\/]/).join("/")}async function plan(resolved,config2,lock,cwd){const item=resolved.item;const lockEntry=lock.items[item.name];const alreadyInstalled=lockEntry!==undefined&&lockEntry.version===item.version;const files=[];const conflicts=[];for(const spec of item.files){const target=resolveTargetPath(config2,spec.target,cwd);const source=planFileSource(spec,resolved.baseDir,resolved.headers);files.push({spec,source,target});if(await fileExists(target)){const targetRel=normalizePath(relative(cwd,target));const existingOwner=Object.values(lock.items).find((entry)=>entry.files.some((f)=>normalizePath(f.path)===targetRel));if(existingOwner===undefined||existingOwner.name!==item.name){conflicts.push({target,reason:"exists",ownedBy:existingOwner?.name})}}}const pkg=await readPackageJson(cwd);const allDeps={...pkg?.dependencies,...pkg?.devDependencies,...pkg?.peerDependencies};const npmDeps=(item.dependencies?.npm??[]).filter((d3)=>{const name=depName(d3);return!(name in allDeps)});const registryDeps=item.dependencies?.registry??[];const incompatibilities=checkEngineCompatibility(item,allDeps);return{item,resolved,files,conflicts,incompatibilities,npmDeps,registryDeps,alreadyInstalled}}function checkEngineCompatibility(item,allDeps){const required2=item.compatibility?.engines;if(!required2)return[];const out=[];for(const[engine,range]of Object.entries(required2)){const installed=allDeps[engine];if(!installed)continue;const minInstalled=import_semver.default.minVersion(installed);if(!minInstalled)continue;if(!import_semver.default.satisfies(minInstalled,range,{includePrerelease:true})){out.push({itemName:item.name,engine,required:range,installed,message:`${item.name} requires ${engine} ${range}, but ${installed} is installed.`})}}return out}import{randomBytes}from"node:crypto";import{mkdir,readFile as readFile3,rename,writeFile as writeFile2}from"node:fs/promises";import{dirname,relative as relative2}from"node:path";async function readSource(file,fetcher){switch(file.source.kind){case"inline":return file.source.content;case"local":return readFile3(file.source.absolutePath);case"remote":if(!fetcher){throw new UnsupportedSourceError(`Remote file "${file.spec.path}" requires an AssetFetcher. Pass one to executePlan via the fetcher argument.`)}return fetcher.fetch(file.source.url,file.source.integrity,file.source.headers)}}async function writeAtomic(target,data){await mkdir(dirname(target),{recursive:true});const tmp=`${target}.tmp.${randomBytes(6).toString("hex")}`;await writeFile2(tmp,data);await rename(tmp,target)}function normalizeRelPath(absPath,cwd){return relative2(cwd,absPath).split(/[\\/]/).join("/")}async function executePlan(plan2,lock,cwd,options={},fetcher){const result={itemName:plan2.item.name,installed:[],skipped:[]};if(options.dryRun){return result}if(plan2.incompatibilities.length>0&&!options.force){const first=plan2.incompatibilities[0];throw new IncompatibleVersionError(first.itemName,first.engine,first.required,first.installed)}if(plan2.conflicts.length>0&&!options.force){const first=plan2.conflicts[0];throw new ConflictError(first.target)}for(const file of plan2.files){const data=await readSource(file,fetcher);await writeAtomic(file.target,data);const buf=typeof data==="string"?Buffer.from(data,"utf8"):data;const sha=sha256OfBuffer(buf);result.installed.push({path:normalizeRelPath(file.target,cwd),sha256:sha})}recordInstall(lock,plan2.item,plan2.resolved.registry,plan2.resolved.resolved,result.installed);return result}import{createHash as createHash3}from"node:crypto";import{mkdir as mkdir2,readFile as readFile4,rename as rename2,writeFile as writeFile3}from"node:fs/promises";import{homedir}from"node:os";import{dirname as dirname2,join as join4}from"node:path";import{createHash as createHash2}from"node:crypto";var SRI_RE=/^sha256-([A-Za-z0-9+/]+={0,2})$/;function parseSriSha256(sri){const m2=SRI_RE.exec(sri);if(!m2){throw new Error(`Invalid SRI string (expected "sha256-<base64>"): ${sri}`)}return Buffer.from(m2[1],"base64")}function sriOfBuffer(data){return"sha256-"+createHash2("sha256").update(data).digest("base64")}function hexOfSri(sri){return parseSriSha256(sri).toString("hex")}function verifyIntegrity(sri,data,label){const expected=parseSriSha256(sri);const actual=createHash2("sha256").update(data).digest();if(!expected.equals(actual)){throw new IntegrityError(label,sri,sriOfBuffer(data))}}function defaultCacheDir(){return process.env.GAMECN_CACHE_DIR??join4(homedir(),".gamecn","cache")}function sha1(s){return createHash3("sha1").update(s).digest("hex")}async function sleep(ms){return new Promise((res)=>setTimeout(res,ms))}async function fetchWithRetry(url2,init,opts={}){const attempts=opts.attempts??3;const initialDelayMs=opts.initialDelayMs??250;const fetcher=init.fetcher??fetch;const{fetcher:_3,...rest}=init;let lastErr;for(let i=0;i<attempts;i++){try{const res=await fetcher(url2,rest);if(res.status>=500&&res.status<600&&i<attempts-1){await sleep(initialDelayMs*2**i);continue}return res}catch(err){lastErr=err;if(i<attempts-1){await sleep(initialDelayMs*2**i);continue}}}throw lastErr??new Error(`fetch failed after ${attempts} attempts: ${url2}`)}async function readJsonIfExists(path){try{return JSON.parse(await readFile4(path,"utf8"))}catch(err){if(err.code==="ENOENT")return;throw err}}class ManifestCache{dir;fetcher;constructor(cacheDir,fetcher=fetch){this.dir=join4(cacheDir,"manifests");this.fetcher=fetcher}async getOrFetch(url2,headers={}){const key=sha1(url2);const file=join4(this.dir,`${key}.json`);const metaFile=join4(this.dir,`${key}.meta.json`);const meta2=await readJsonIfExists(metaFile);const reqHeaders={...headers};if(meta2?.etag)reqHeaders["If-None-Match"]=meta2.etag;const res=await fetchWithRetry(url2,{method:"GET",headers:reqHeaders,fetcher:this.fetcher});if(res.status===304){const cached2=await readJsonIfExists(file);if(cached2!==undefined)return cached2;const refetch=await fetchWithRetry(url2,{method:"GET",headers,fetcher:this.fetcher});return parseAndCache(refetch,url2,file,metaFile)}if(!res.ok){throw new HttpError(url2,res.status,res.statusText)}return parseAndCache(res,url2,file,metaFile)}}async function parseAndCache(res,url2,file,metaFile){const text=await res.text();let json;try{json=JSON.parse(text)}catch(err){throw new HttpError(url2,res.status,`invalid JSON: ${err.message}`)}await mkdir2(dirname2(file),{recursive:true});await writeFile3(file,text,"utf8");const meta2={etag:res.headers.get("etag")??undefined,fetchedAt:new Date().toISOString()};await writeFile3(metaFile,JSON.stringify(meta2),"utf8");return json}class AssetCache{dir;fetcher;constructor(cacheDir,fetcher=fetch){this.dir=join4(cacheDir,"assets");this.fetcher=fetcher}async getOrFetch(url2,integrity,headers={}){if(integrity){const hex2=hexOfSri(integrity);const cached2=join4(this.dir,hex2);try{const buf2=await readFile4(cached2);verifyIntegrity(integrity,buf2,cached2);return buf2}catch(err){if(err.code!=="ENOENT"){}}}const res=await fetchWithRetry(url2,{method:"GET",headers,fetcher:this.fetcher});if(!res.ok){throw new HttpError(url2,res.status,res.statusText)}const buf=Buffer.from(await res.arrayBuffer());if(integrity){verifyIntegrity(integrity,buf,url2)}const hex=createHash3("sha256").update(buf).digest("hex");const target=join4(this.dir,hex);await mkdir2(dirname2(target),{recursive:true});const tmp=`${target}.tmp.${createHash3("sha1").update(`${url2}${Date.now()}`).digest("hex").slice(0,8)}`;await writeFile3(tmp,buf);try{await rename2(tmp,target)}catch{}return buf}}import{isAbsolute as isAbsolute2}from"node:path";var ENV_VAR_RE=/\$\{([A-Za-z_][A-Za-z0-9_]*)\}/g;function interpolateHeaders(headers,env=process.env){const out={};for(const[k3,v]of Object.entries(headers)){out[k3]=interpolate(v,env)}return out}function interpolate(template,env=process.env){return template.replace(ENV_VAR_RE,(_3,name)=>{const value=env[name];if(value===undefined){throw new MissingEnvVarError(name)}return value})}var DEFAULT_REGISTRY_URL="https://gamecn.dev/r/{name}.json";var BARE_NAME_RE=/^[a-z0-9][a-z0-9_-]{0,213}$/i;class DefaultRegistryResolver{config;cache;env;constructor(config2,cache,env=process.env){this.config=config2;this.cache=cache;this.env=env}canResolve(spec){if(spec.startsWith("@"))return false;if(spec.startsWith("http://")||spec.startsWith("https://"))return false;if(spec.startsWith("gh:")||spec.startsWith("github:"))return false;if(spec.startsWith("./")||spec.startsWith("../"))return false;if(isAbsolute2(spec))return false;if(spec.endsWith(".json"))return false;if(spec.includes("/")||spec.includes("\\"))return false;return BARE_NAME_RE.test(spec)}async resolve(spec,_ctx){const reg=this.config.registries?.["@main"];const urlTemplate=!reg?DEFAULT_REGISTRY_URL:typeof reg==="string"?reg:reg.url;const rawHeaders=typeof reg==="object"&&reg.headers?reg.headers:{};const headers=interpolateHeaders(rawHeaders,this.env);const url2=urlTemplate.replace(/\{name\}/g,spec);try{const json=await this.cache.getOrFetch(url2,headers);const item=RegistryItemSchema.parse(json);return{item,spec,registry:"@main",resolved:url2,headers:Object.keys(headers).length>0?headers:undefined}}catch(err){if(err instanceof HttpError&&err.status===404){throw new ItemNotFoundError(spec,`not found in the default @main registry (${url2}). Either configure 'registries["@main"]' in gamecn.json to point at a different registry, or use a fully-qualified spec (\`@scope/name\`, \`./local.json\`, \`gh:owner/repo/path\`, or \`https://...\`).`)}throw err}}}var GH_PREFIX_RE=/^(gh|github):/;function parseGitHubSpec(spec){if(!GH_PREFIX_RE.test(spec)){throw new ItemNotFoundError(spec,"not a GitHub spec")}const stripped=spec.replace(GH_PREFIX_RE,"");const hashIdx=stripped.indexOf("#");const pathPart=hashIdx===-1?stripped:stripped.slice(0,hashIdx);const ref=hashIdx===-1?"HEAD":stripped.slice(hashIdx+1)||"HEAD";const segs=pathPart.split("/").filter(Boolean);if(segs.length<3){throw new ItemNotFoundError(spec,"expected gh:owner/repo/path/to/item.json")}const[owner,repo,...rest]=segs;return{owner,repo,path:rest.join("/"),ref,hasExplicitRef:hashIdx!==-1}}function githubSpecToUrl(spec){const p2=parseGitHubSpec(spec);return`https://raw.githubusercontent.com/${p2.owner}/${p2.repo}/${p2.ref}/${p2.path}`}class GitHubResolver{cache;env;warn;constructor(cache,env=process.env,warn=(m2)=>console.warn(m2)){this.cache=cache;this.env=env;this.warn=warn}canResolve(spec){return GH_PREFIX_RE.test(spec)}async resolve(spec,_ctx){const parsed=parseGitHubSpec(spec);if(!parsed.hasExplicitRef){this.warn(`[gamecn] ${spec} has no ref; using HEAD (non-reproducible). Pin a ref with #v1.2.0 or #commit-sha.`)}const url2=githubSpecToUrl(spec);const headers={};const token=this.env["GITHUB_TOKEN"];if(token)headers["Authorization"]=`token ${token}`;const json=await this.cache.getOrFetch(url2,headers);const item=RegistryItemSchema.parse(json);return{item,spec,registry:"github",resolved:url2,headers:Object.keys(headers).length>0?headers:undefined}}}class HttpsResolver{cache;headers;constructor(cache,headers={}){this.cache=cache;this.headers=headers}canResolve(spec){return spec.startsWith("http://")||spec.startsWith("https://")}async resolve(spec,_ctx){const json=await this.cache.getOrFetch(spec,this.headers);const item=RegistryItemSchema.parse(json);return{item,spec,registry:"https",resolved:spec,headers:Object.keys(this.headers).length>0?this.headers:undefined}}}import{readFile as readFile5}from"node:fs/promises";import{dirname as dirname3,isAbsolute as isAbsolute3,resolve as resolve3}from"node:path";class LocalFileResolver{canResolve(spec){if(spec.startsWith("./")||spec.startsWith("../"))return true;if(spec.startsWith("/")||spec.startsWith("~/"))return true;if(/^[A-Za-z]:[\\/]/.test(spec))return true;if(spec.endsWith(".json"))return true;return false}async resolve(spec,ctx){const absSpec=isAbsolute3(spec)?spec:resolve3(ctx.cwd,spec);let raw;try{raw=await readFile5(absSpec,"utf8")}catch(err){const code=err.code;throw new ItemNotFoundError(spec,code==="ENOENT"?"file not found":`read failed: ${err.message}`)}let json;try{json=JSON.parse(raw)}catch(err){throw new ItemNotFoundError(spec,`JSON parse error: ${err.message}`)}const item=RegistryItemSchema.parse(json);return{item,spec,registry:"local",resolved:absSpec,baseDir:dirname3(absSpec)}}}var NAMESPACE_RE=/^(@[A-Za-z0-9_-]+)\/(.+)$/;class NamespaceResolver{config;cache;env;constructor(config2,cache,env=process.env){this.config=config2;this.cache=cache;this.env=env}canResolve(spec){return NAMESPACE_RE.test(spec)}async resolve(spec,_ctx){const m2=NAMESPACE_RE.exec(spec);if(!m2)throw new ItemNotFoundError(spec,"not a namespaced spec");const namespace=m2[1];const name=m2[2];const reg=this.config.registries?.[namespace];if(!reg){throw new ItemNotFoundError(spec,`unknown registry namespace "${namespace}". Add it to gamecn.json#registries.`)}const urlTemplate=typeof reg==="string"?reg:reg.url;const rawHeaders=typeof reg==="string"?{}:reg.headers??{};const headers=interpolateHeaders(rawHeaders,this.env);const url2=urlTemplate.replace(/\{name\}/g,name);const json=await this.cache.getOrFetch(url2,headers);const item=RegistryItemSchema.parse(json);return{item,spec,registry:namespace,resolved:url2,headers:Object.keys(headers).length>0?headers:undefined}}}function createResolver(config2,opts={}){const cacheDir=opts.cacheDir??defaultCacheDir();const fetcher=opts.fetcher??fetch;const env=opts.env??process.env;const manifestCache=new ManifestCache(cacheDir,fetcher);const resolvers=[new NamespaceResolver(config2,manifestCache,env),new GitHubResolver(manifestCache,env),new DefaultRegistryResolver(config2,manifestCache,env),new HttpsResolver(manifestCache),new LocalFileResolver];return{canResolve(spec){return resolvers.some((r2)=>r2.canResolve(spec))},async resolve(spec,ctx){for(const r2 of resolvers){if(r2.canResolve(spec))return r2.resolve(spec,ctx)}throw new ItemNotFoundError(spec,"no resolver matches this spec")}}}function createAssetFetcher(opts={}){const cacheDir=opts.cacheDir??defaultCacheDir();const fetcher=opts.fetcher??fetch;const cache=new AssetCache(cacheDir,fetcher);return{fetch:(url2,integrity,headers)=>cache.getOrFetch(url2,integrity,headers)}}var TEXT_EXTS=new Set([".ts",".tsx",".js",".jsx",".mjs",".cjs"]);var MAX_SCAN_BYTES=256*1024;var SKIP_DIRS=new Set(["node_modules",".git","dist",".turbo",".cache","registry-dist"]);var DEFAULT_REGISTRY="https://gamecn.dev/r/{name}.json";var NAME_RE=/^[a-z0-9][a-z0-9._-]{0,213}$/i;var RESERVED=new Set(["node_modules","favicon.ico"]);function validateProjectName(name){if(!NAME_RE.test(name)){throw new Error(`Invalid project name "${name}". Use lowercase letters, numbers, dot, underscore, or hyphen.`)}if(RESERVED.has(name)||name.startsWith(".")||name.startsWith("_")){throw new Error(`Reserved or invalid project name: "${name}".`)}}async function dirIsEmptyOrMissing(path){try{const entries=await readdir(path);return entries.length===0}catch(err){if(err.code==="ENOENT")return true;throw err}}function resolveTemplateSpec(template){if(template.startsWith("@")||template.startsWith("http://")||template.startsWith("https://")||template.startsWith("gh:")||template.startsWith("github:")||template.startsWith("./")||template.startsWith("/")||/^[A-Za-z]:[\\/]/.test(template)){return template}return`@main/${template}`}async function defaultInstallRunner(cwd,pm){await new Promise((res,rej)=>{const proc=spawn(pm,["install"],{cwd,stdio:"inherit",shell:process.platform==="win32"});proc.on("exit",(code)=>{if(code===0)res();else rej(new Error(`${pm} install exited with code ${code}`))});proc.on("error",rej)})}async function scaffold(opts){validateProjectName(opts.name);const parentDir=opts.parentDir??process.cwd();const cwd=resolve4(parentDir,opts.name);if(!await dirIsEmptyOrMissing(cwd)&&!opts.force){throw new Error(`Directory "${opts.name}" already exists and is not empty. Pass --force to overwrite.`)}await mkdir3(cwd,{recursive:true});const pm=opts.packageManager??"pnpm";const config2={engine:"phaser",framework:"vanilla",language:"typescript",packageManager:pm,paths:{src:"src",assets:"public/assets"},registries:{"@main":opts.registry??DEFAULT_REGISTRY}};const resolverOpts=opts.cacheDir?{cacheDir:opts.cacheDir}:{};const resolver=createResolver(config2,resolverOpts);const fetcher=createAssetFetcher(resolverOpts);const spec=resolveTemplateSpec(opts.template);const resolved=await resolver.resolve(spec,{cwd,config:config2});if(resolved.item.type!=="registry:template"){throw new IncompatibleError(`"${spec}" is type ${resolved.item.type}, not registry:template.`)}const lock=await loadLockfile(cwd);const p2=await plan(resolved,config2,lock,cwd);const result=await executePlan(p2,lock,cwd,{force:opts.force??false},fetcher);await saveLockfile(cwd,lock);const pkgPath=resolve4(cwd,"package.json");try{const raw=await readFile6(pkgPath,"utf8");const pkg=JSON.parse(raw);pkg.name=opts.name;await writeFile4(pkgPath,JSON.stringify(pkg,null,2)+`
115
+ `,"utf8")}catch(err){if(err.code!=="ENOENT")throw err}const postScaffoldDeps=await installPostScaffoldDeps(cwd,opts.registry,opts.cacheDir,opts.force??false);let installed=false;if(!opts.skipInstall){const runner=opts.installRunner??defaultInstallRunner;await runner(cwd,pm);installed=true}return{cwd,packageManager:pm,installed,templateName:resolved.item.name,filesWritten:result.installed.length+postScaffoldDeps.length,postScaffoldDeps:postScaffoldDeps.map((d3)=>d3.spec)}}async function installPostScaffoldDeps(cwd,registryOverride,cacheDir,force){const cfgPath=resolve4(cwd,"gamecn.json");let raw;try{raw=await readFile6(cfgPath,"utf8")}catch(err){if(err.code==="ENOENT")return[];throw err}const projectConfig=GamecnConfigSchema.parse(JSON.parse(raw));const deps=projectConfig.deps??[];if(deps.length===0)return[];const config2=registryOverride?{...projectConfig,registries:{...projectConfig.registries,"@main":registryOverride}}:projectConfig;const resolverOpts=cacheDir?{cacheDir}:{};const resolver=createResolver(config2,resolverOpts);const fetcher=createAssetFetcher(resolverOpts);const lock=await loadLockfile(cwd);const installed=[];for(const spec of deps){const resolvedDep=await resolver.resolve(spec,{cwd,config:config2});if(resolvedDep.item.type==="registry:template"){throw new IncompatibleError(`Template's gamecn.json#deps entry "${spec}" resolved to a registry:template — deps[] is for components/systems/assets, not templates.`)}const p2=await plan(resolvedDep,config2,lock,cwd);const r2=await executePlan(p2,lock,cwd,{force},fetcher);installed.push({spec,fileCount:r2.installed.length})}await saveLockfile(cwd,lock);return installed}var TEMPLATES=[{value:"phaser-endless-runner",label:"Phaser Endless Runner",hint:"Vite + TypeScript + Phaser 3"}];async function pickTemplate(opts){if(opts.template)return opts.template;if(opts.yes){throw new Error("--template is required when --yes is set.")}const choice=await ve({message:"Template?",options:TEMPLATES});if(pD(choice)){xe("Cancelled.");process.exit(1)}return choice}var program2=new Command;program2.name("create-gamecn").description("Scaffold a new gamecn project from a template").version("0.0.1").argument("<name>","project directory name").option("--template <name>","template name or full spec").option("--registry <url>","registry URL with {name} placeholder",DEFAULT_REGISTRY).option("--package-manager <pm>","package manager (npm|pnpm|yarn|bun)","pnpm").option("--yes","skip prompts").option("--force","overwrite a non-empty target directory").option("--no-install","skip dependency install").action(async(name,opts)=>{try{if(!opts.yes)Ie(import_picocolors2.default.cyan(`create-gamecn ${name}`));const template=await pickTemplate(opts);const scaffoldOpts={name,template,registry:opts.registry,packageManager:opts.packageManager,skipInstall:opts.install===false,force:opts.force};const result=await scaffold(scaffoldOpts);const next=result.installed?`cd ${name}
116
116
  ${result.packageManager} dev`:`cd ${name}
117
117
  ${result.packageManager} install
118
118
  ${result.packageManager} dev`;if(!opts.yes){Se(import_picocolors2.default.green(`Done!
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "create-gamecn",
3
- "version": "0.0.4-1",
3
+ "version": "0.0.4",
4
4
  "type": "module",
5
5
  "main": "index.js",
6
6
  "bin": {