@tokmizer/plugin 0.9.54 → 0.9.55
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/plugin.json +1 -1
- package/codex-plugin/plugin.json +1 -1
- package/dist/bin/tkr-codex-hook.js +29 -29
- package/dist/bin/tkr-daemon.js +38 -38
- package/dist/bin/tkr-exec +31 -31
- package/dist/bin/tkr-exec.js +31 -31
- package/dist/bin/tkr-shim.js +28 -28
- package/dist/bin/tkr.js +93 -93
- package/dist/hooks-host/post-tool-use.js +41 -41
- package/dist/index.js +34 -34
- package/dist/native/manifest.json +8 -8
- package/dist/native/tkr-exec-darwin-arm64 +0 -0
- package/dist/native/tkr-exec-darwin-x64 +0 -0
- package/dist/native/tkr-exec-linux-arm64 +0 -0
- package/dist/native/tkr-exec-linux-x64 +0 -0
- package/package.json +1 -1
package/dist/bin/tkr.js
CHANGED
|
@@ -1,41 +1,41 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { createRequire as __tkrCreateRequire } from "node:module"; const require = __tkrCreateRequire(import.meta.url);
|
|
3
|
-
var Ki=Object.defineProperty;var E=(t,e,r)=>()=>{if(r)throw r[0];try{return t&&(e=t(t=0)),e}catch(n){throw r=[n],n}};var te=(t,e)=>{for(var r in e)Ki(t,r,{get:e[r],enumerable:!0})};var S,jr,p,oe,yt=E(()=>{(function(t){t.assertEqual=s=>{};function e(s){}t.assertIs=e;function r(s){throw new Error}t.assertNever=r,t.arrayToEnum=s=>{let o={};for(let i of s)o[i]=i;return o},t.getValidEnumValues=s=>{let o=t.objectKeys(s).filter(a=>typeof s[s[a]]!="number"),i={};for(let a of o)i[a]=s[a];return t.objectValues(i)},t.objectValues=s=>t.objectKeys(s).map(function(o){return s[o]}),t.objectKeys=typeof Object.keys=="function"?s=>Object.keys(s):s=>{let o=[];for(let i in s)Object.prototype.hasOwnProperty.call(s,i)&&o.push(i);return o},t.find=(s,o)=>{for(let i of s)if(o(i))return i},t.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&Number.isFinite(s)&&Math.floor(s)===s;function n(s,o=" | "){return s.map(i=>typeof i=="string"?`'${i}'`:i).join(o)}t.joinValues=n,t.jsonStringifyReplacer=(s,o)=>typeof o=="bigint"?o.toString():o})(S||(S={}));(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(jr||(jr={}));p=S.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),oe=t=>{switch(typeof t){case"undefined":return p.undefined;case"string":return p.string;case"number":return Number.isNaN(t)?p.nan:p.number;case"boolean":return p.boolean;case"function":return p.function;case"bigint":return p.bigint;case"symbol":return p.symbol;case"object":return Array.isArray(t)?p.array:t===null?p.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?p.promise:typeof Map<"u"&&t instanceof Map?p.map:typeof Set<"u"&&t instanceof Set?p.set:typeof Date<"u"&&t instanceof Date?p.date:p.object;default:return p.unknown}}});var d,Gi,F,Vt=E(()=>{yt();d=S.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),Gi=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),F=class t extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};let r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=e}format(e){let r=e||function(o){return o.message},n={_errors:[]},s=o=>{for(let i of o.issues)if(i.code==="invalid_union")i.unionErrors.map(s);else if(i.code==="invalid_return_type")s(i.returnTypeError);else if(i.code==="invalid_arguments")s(i.argumentsError);else if(i.path.length===0)n._errors.push(r(i));else{let a=n,c=0;for(;c<i.path.length;){let u=i.path[c];c===i.path.length-1?(a[u]=a[u]||{_errors:[]},a[u]._errors.push(r(i))):a[u]=a[u]||{_errors:[]},a=a[u],c++}}};return s(this),n}static assert(e){if(!(e instanceof t))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,S.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=r=>r.message){let r={},n=[];for(let s of this.issues)if(s.path.length>0){let o=s.path[0];r[o]=r[o]||[],r[o].push(e(s))}else n.push(e(s));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}};F.create=t=>new F(t)});var Ji,le,zr=E(()=>{Vt();yt();Ji=(t,e)=>{let r;switch(t.code){case d.invalid_type:t.received===p.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case d.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,S.jsonStringifyReplacer)}`;break;case d.unrecognized_keys:r=`Unrecognized key(s) in object: ${S.joinValues(t.keys,", ")}`;break;case d.invalid_union:r="Invalid input";break;case d.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${S.joinValues(t.options)}`;break;case d.invalid_enum_value:r=`Invalid enum value. Expected ${S.joinValues(t.options)}, received '${t.received}'`;break;case d.invalid_arguments:r="Invalid function arguments";break;case d.invalid_return_type:r="Invalid function return type";break;case d.invalid_date:r="Invalid date";break;case d.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(r=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?r=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?r=`Invalid input: must end with "${t.validation.endsWith}"`:S.assertNever(t.validation):t.validation!=="regex"?r=`Invalid ${t.validation}`:r="Invalid";break;case d.too_small:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:r="Invalid input";break;case d.too_big:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?r=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:r="Invalid input";break;case d.custom:r="Invalid input";break;case d.invalid_intersection_types:r="Intersection results could not be merged";break;case d.not_multiple_of:r=`Number must be a multiple of ${t.multipleOf}`;break;case d.not_finite:r="Number must be finite";break;default:r=e.defaultError,S.assertNever(t)}return{message:r}},le=Ji});function Wi(t){os=t}function Ye(){return os}var os,Kt=E(()=>{zr();os=le});function m(t,e){let r=Ye(),n=wt({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===le?void 0:le].filter(s=>!!s)});t.common.issues.push(n)}var wt,Yi,I,w,Ae,M,Gt,Jt,ye,qe,Ur=E(()=>{Kt();zr();wt=t=>{let{data:e,path:r,errorMaps:n,issueData:s}=t,o=[...r,...s.path||[]],i={...s,path:o};if(s.message!==void 0)return{...s,path:o,message:s.message};let a="",c=n.filter(u=>!!u).slice().reverse();for(let u of c)a=u(i,{data:e,defaultError:a}).message;return{...s,path:o,message:a}},Yi=[];I=class t{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,r){let n=[];for(let s of r){if(s.status==="aborted")return w;s.status==="dirty"&&e.dirty(),n.push(s.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,r){let n=[];for(let s of r){let o=await s.key,i=await s.value;n.push({key:o,value:i})}return t.mergeObjectSync(e,n)}static mergeObjectSync(e,r){let n={};for(let s of r){let{key:o,value:i}=s;if(o.status==="aborted"||i.status==="aborted")return w;o.status==="dirty"&&e.dirty(),i.status==="dirty"&&e.dirty(),o.value!=="__proto__"&&(typeof i.value<"u"||s.alwaysSet)&&(n[o.value]=i.value)}return{status:e.value,value:n}}},w=Object.freeze({status:"aborted"}),Ae=t=>({status:"dirty",value:t}),M=t=>({status:"valid",value:t}),Gt=t=>t.status==="aborted",Jt=t=>t.status==="dirty",ye=t=>t.status==="valid",qe=t=>typeof Promise<"u"&&t instanceof Promise});var is=E(()=>{});var h,as=E(()=>{(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(h||(h={}))});function _(t){if(!t)return{};let{errorMap:e,invalid_type_error:r,required_error:n,description:s}=t;if(e&&(r||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:s}:{errorMap:(i,a)=>{let{message:c}=t;return i.code==="invalid_enum_value"?{message:c??a.defaultError}:typeof a.data>"u"?{message:c??n??a.defaultError}:i.code!=="invalid_type"?{message:a.defaultError}:{message:c??r??a.defaultError}},description:s}}function ds(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);let r=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${r}`}function ma(t){return new RegExp(`^${ds(t)}$`)}function fs(t){let e=`${ls}T${ds(t)}`,r=[];return r.push(t.local?"Z?":"Z"),t.offset&&r.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${r.join("|")})`,new RegExp(`^${e}$`)}function pa(t,e){return!!((e==="v4"||!e)&&ia.test(t)||(e==="v6"||!e)&&ca.test(t))}function ha(t,e){if(!ra.test(t))return!1;try{let[r]=t.split(".");if(!r)return!1;let n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),s=JSON.parse(atob(n));return!(typeof s!="object"||s===null||"typ"in s&&s?.typ!=="JWT"||!s.alg||e&&s.alg!==e)}catch{return!1}}function ga(t,e){return!!((e==="v4"||!e)&&aa.test(t)||(e==="v6"||!e)&&ua.test(t))}function ya(t,e){let r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,s=r>n?r:n,o=Number.parseInt(t.toFixed(s).replace(".","")),i=Number.parseInt(e.toFixed(s).replace(".",""));return o%i/10**s}function Xe(t){if(t instanceof j){let e={};for(let r in t.shape){let n=t.shape[r];e[r]=J.create(Xe(n))}return new j({...t._def,shape:()=>e})}else return t instanceof me?new me({...t._def,type:Xe(t.element)}):t instanceof J?J.create(Xe(t.unwrap())):t instanceof ae?ae.create(Xe(t.unwrap())):t instanceof ie?ie.create(t.items.map(e=>Xe(e))):t}function Hr(t,e){let r=oe(t),n=oe(e);if(t===e)return{valid:!0,data:t};if(r===p.object&&n===p.object){let s=S.objectKeys(e),o=S.objectKeys(t).filter(a=>s.indexOf(a)!==-1),i={...t,...e};for(let a of o){let c=Hr(t[a],e[a]);if(!c.valid)return{valid:!1};i[a]=c.data}return{valid:!0,data:i}}else if(r===p.array&&n===p.array){if(t.length!==e.length)return{valid:!1};let s=[];for(let o=0;o<t.length;o++){let i=t[o],a=e[o],c=Hr(i,a);if(!c.valid)return{valid:!1};s.push(c.data)}return{valid:!0,data:s}}else return r===p.date&&n===p.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}function ms(t,e){return new Fe({values:t,typeName:b.ZodEnum,..._(e)})}function us(t,e){let r=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof r=="string"?{message:r}:r}function ps(t,e={},r){return t?be.create().superRefine((n,s)=>{let o=t(n);if(o instanceof Promise)return o.then(i=>{if(!i){let a=us(e,n),c=a.fatal??r??!0;s.addIssue({code:"custom",...a,fatal:c})}});if(!o){let i=us(e,n),a=i.fatal??r??!0;s.addIssue({code:"custom",...i,fatal:a})}}):be.create()}var W,cs,x,qi,Xi,Qi,ea,ta,ra,na,sa,oa,Zr,ia,aa,ca,ua,la,da,ls,fa,we,Re,Ce,$e,Pe,Qe,Oe,Ie,be,fe,re,et,me,j,De,de,Wt,Ne,ie,Yt,tt,rt,qt,Me,Le,Fe,je,ve,Y,J,ae,ze,Ue,nt,wa,bt,vt,Ze,ba,b,va,hs,gs,ka,_a,ys,xa,Sa,Ea,Ta,Aa,Ra,Ca,$a,Pa,Oa,Ia,Da,Na,Ma,La,Fa,ja,za,Ua,Za,Ha,Ba,Va,Ka,Ga,Ja,Wa,Ya,qa,Xa,Qa,ec,tc,rc,ws=E(()=>{Vt();Kt();as();Ur();yt();W=class{constructor(e,r,n,s){this._cachedPath=[],this.parent=e,this.data=r,this._path=n,this._key=s}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},cs=(t,e)=>{if(ye(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let r=new F(t.common.issues);return this._error=r,this._error}}};x=class{get description(){return this._def.description}_getType(e){return oe(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:oe(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new I,ctx:{common:e.parent.common,data:e.data,parsedType:oe(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let r=this._parse(e);if(qe(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(e){let r=this._parse(e);return Promise.resolve(r)}parse(e,r){let n=this.safeParse(e,r);if(n.success)return n.data;throw n.error}safeParse(e,r){let n={common:{issues:[],async:r?.async??!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:oe(e)},s=this._parseSync({data:e,path:n.path,parent:n});return cs(n,s)}"~validate"(e){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:oe(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:r});return ye(n)?{value:n.value}:{issues:r.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:r}).then(n=>ye(n)?{value:n.value}:{issues:r.common.issues})}async parseAsync(e,r){let n=await this.safeParseAsync(e,r);if(n.success)return n.data;throw n.error}async safeParseAsync(e,r){let n={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:oe(e)},s=this._parse({data:e,path:n.path,parent:n}),o=await(qe(s)?s:Promise.resolve(s));return cs(n,o)}refine(e,r){let n=s=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(s):r;return this._refinement((s,o)=>{let i=e(s),a=()=>o.addIssue({code:d.custom,...n(s)});return typeof Promise<"u"&&i instanceof Promise?i.then(c=>c?!0:(a(),!1)):i?!0:(a(),!1)})}refinement(e,r){return this._refinement((n,s)=>e(n)?!0:(s.addIssue(typeof r=="function"?r(n,s):r),!1))}_refinement(e){return new Y({schema:this,typeName:b.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:r=>this["~validate"](r)}}optional(){return J.create(this,this._def)}nullable(){return ae.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return me.create(this)}promise(){return ve.create(this,this._def)}or(e){return De.create([this,e],this._def)}and(e){return Ne.create(this,e,this._def)}transform(e){return new Y({..._(this._def),schema:this,typeName:b.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let r=typeof e=="function"?e:()=>e;return new ze({..._(this._def),innerType:this,defaultValue:r,typeName:b.ZodDefault})}brand(){return new bt({typeName:b.ZodBranded,type:this,..._(this._def)})}catch(e){let r=typeof e=="function"?e:()=>e;return new Ue({..._(this._def),innerType:this,catchValue:r,typeName:b.ZodCatch})}describe(e){let r=this.constructor;return new r({...this._def,description:e})}pipe(e){return vt.create(this,e)}readonly(){return Ze.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},qi=/^c[^\s-]{8,}$/i,Xi=/^[0-9a-z]+$/,Qi=/^[0-9A-HJKMNP-TV-Z]{26}$/i,ea=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,ta=/^[a-z0-9_-]{21}$/i,ra=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,na=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,sa=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,oa="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",ia=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,aa=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ca=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,ua=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,la=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,da=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,ls="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",fa=new RegExp(`^${ls}$`);we=class t extends x{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==p.string){let o=this._getOrReturnCtx(e);return m(o,{code:d.invalid_type,expected:p.string,received:o.parsedType}),w}let n=new I,s;for(let o of this._def.checks)if(o.kind==="min")e.data.length<o.value&&(s=this._getOrReturnCtx(e,s),m(s,{code:d.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),n.dirty());else if(o.kind==="max")e.data.length>o.value&&(s=this._getOrReturnCtx(e,s),m(s,{code:d.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),n.dirty());else if(o.kind==="length"){let i=e.data.length>o.value,a=e.data.length<o.value;(i||a)&&(s=this._getOrReturnCtx(e,s),i?m(s,{code:d.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}):a&&m(s,{code:d.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}),n.dirty())}else if(o.kind==="email")sa.test(e.data)||(s=this._getOrReturnCtx(e,s),m(s,{validation:"email",code:d.invalid_string,message:o.message}),n.dirty());else if(o.kind==="emoji")Zr||(Zr=new RegExp(oa,"u")),Zr.test(e.data)||(s=this._getOrReturnCtx(e,s),m(s,{validation:"emoji",code:d.invalid_string,message:o.message}),n.dirty());else if(o.kind==="uuid")ea.test(e.data)||(s=this._getOrReturnCtx(e,s),m(s,{validation:"uuid",code:d.invalid_string,message:o.message}),n.dirty());else if(o.kind==="nanoid")ta.test(e.data)||(s=this._getOrReturnCtx(e,s),m(s,{validation:"nanoid",code:d.invalid_string,message:o.message}),n.dirty());else if(o.kind==="cuid")qi.test(e.data)||(s=this._getOrReturnCtx(e,s),m(s,{validation:"cuid",code:d.invalid_string,message:o.message}),n.dirty());else if(o.kind==="cuid2")Xi.test(e.data)||(s=this._getOrReturnCtx(e,s),m(s,{validation:"cuid2",code:d.invalid_string,message:o.message}),n.dirty());else if(o.kind==="ulid")Qi.test(e.data)||(s=this._getOrReturnCtx(e,s),m(s,{validation:"ulid",code:d.invalid_string,message:o.message}),n.dirty());else if(o.kind==="url")try{new URL(e.data)}catch{s=this._getOrReturnCtx(e,s),m(s,{validation:"url",code:d.invalid_string,message:o.message}),n.dirty()}else o.kind==="regex"?(o.regex.lastIndex=0,o.regex.test(e.data)||(s=this._getOrReturnCtx(e,s),m(s,{validation:"regex",code:d.invalid_string,message:o.message}),n.dirty())):o.kind==="trim"?e.data=e.data.trim():o.kind==="includes"?e.data.includes(o.value,o.position)||(s=this._getOrReturnCtx(e,s),m(s,{code:d.invalid_string,validation:{includes:o.value,position:o.position},message:o.message}),n.dirty()):o.kind==="toLowerCase"?e.data=e.data.toLowerCase():o.kind==="toUpperCase"?e.data=e.data.toUpperCase():o.kind==="startsWith"?e.data.startsWith(o.value)||(s=this._getOrReturnCtx(e,s),m(s,{code:d.invalid_string,validation:{startsWith:o.value},message:o.message}),n.dirty()):o.kind==="endsWith"?e.data.endsWith(o.value)||(s=this._getOrReturnCtx(e,s),m(s,{code:d.invalid_string,validation:{endsWith:o.value},message:o.message}),n.dirty()):o.kind==="datetime"?fs(o).test(e.data)||(s=this._getOrReturnCtx(e,s),m(s,{code:d.invalid_string,validation:"datetime",message:o.message}),n.dirty()):o.kind==="date"?fa.test(e.data)||(s=this._getOrReturnCtx(e,s),m(s,{code:d.invalid_string,validation:"date",message:o.message}),n.dirty()):o.kind==="time"?ma(o).test(e.data)||(s=this._getOrReturnCtx(e,s),m(s,{code:d.invalid_string,validation:"time",message:o.message}),n.dirty()):o.kind==="duration"?na.test(e.data)||(s=this._getOrReturnCtx(e,s),m(s,{validation:"duration",code:d.invalid_string,message:o.message}),n.dirty()):o.kind==="ip"?pa(e.data,o.version)||(s=this._getOrReturnCtx(e,s),m(s,{validation:"ip",code:d.invalid_string,message:o.message}),n.dirty()):o.kind==="jwt"?ha(e.data,o.alg)||(s=this._getOrReturnCtx(e,s),m(s,{validation:"jwt",code:d.invalid_string,message:o.message}),n.dirty()):o.kind==="cidr"?ga(e.data,o.version)||(s=this._getOrReturnCtx(e,s),m(s,{validation:"cidr",code:d.invalid_string,message:o.message}),n.dirty()):o.kind==="base64"?la.test(e.data)||(s=this._getOrReturnCtx(e,s),m(s,{validation:"base64",code:d.invalid_string,message:o.message}),n.dirty()):o.kind==="base64url"?da.test(e.data)||(s=this._getOrReturnCtx(e,s),m(s,{validation:"base64url",code:d.invalid_string,message:o.message}),n.dirty()):S.assertNever(o);return{status:n.value,value:e.data}}_regex(e,r,n){return this.refinement(s=>e.test(s),{validation:r,code:d.invalid_string,...h.errToObj(n)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...h.errToObj(e)})}url(e){return this._addCheck({kind:"url",...h.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...h.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...h.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...h.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...h.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...h.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...h.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...h.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...h.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...h.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...h.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...h.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...h.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...h.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...h.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...h.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r?.position,...h.errToObj(r?.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...h.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...h.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...h.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...h.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...h.errToObj(r)})}nonempty(e){return this.min(1,h.errToObj(e))}trim(){return new t({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxLength(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};we.create=t=>new we({checks:[],typeName:b.ZodString,coerce:t?.coerce??!1,..._(t)});Re=class t extends x{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==p.number){let o=this._getOrReturnCtx(e);return m(o,{code:d.invalid_type,expected:p.number,received:o.parsedType}),w}let n,s=new I;for(let o of this._def.checks)o.kind==="int"?S.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),m(n,{code:d.invalid_type,expected:"integer",received:"float",message:o.message}),s.dirty()):o.kind==="min"?(o.inclusive?e.data<o.value:e.data<=o.value)&&(n=this._getOrReturnCtx(e,n),m(n,{code:d.too_small,minimum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),s.dirty()):o.kind==="max"?(o.inclusive?e.data>o.value:e.data>=o.value)&&(n=this._getOrReturnCtx(e,n),m(n,{code:d.too_big,maximum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),s.dirty()):o.kind==="multipleOf"?ya(e.data,o.value)!==0&&(n=this._getOrReturnCtx(e,n),m(n,{code:d.not_multiple_of,multipleOf:o.value,message:o.message}),s.dirty()):o.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),m(n,{code:d.not_finite,message:o.message}),s.dirty()):S.assertNever(o);return{status:s.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,h.toString(r))}gt(e,r){return this.setLimit("min",e,!1,h.toString(r))}lte(e,r){return this.setLimit("max",e,!0,h.toString(r))}lt(e,r){return this.setLimit("max",e,!1,h.toString(r))}setLimit(e,r,n,s){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:h.toString(s)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:h.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:h.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:h.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:h.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:h.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:h.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:h.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:h.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:h.toString(e)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&S.isInteger(e.value))}get isFinite(){let e=null,r=null;for(let n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(r===null||n.value>r)&&(r=n.value):n.kind==="max"&&(e===null||n.value<e)&&(e=n.value)}return Number.isFinite(r)&&Number.isFinite(e)}};Re.create=t=>new Re({checks:[],typeName:b.ZodNumber,coerce:t?.coerce||!1,..._(t)});Ce=class t extends x{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==p.bigint)return this._getInvalidInput(e);let n,s=new I;for(let o of this._def.checks)o.kind==="min"?(o.inclusive?e.data<o.value:e.data<=o.value)&&(n=this._getOrReturnCtx(e,n),m(n,{code:d.too_small,type:"bigint",minimum:o.value,inclusive:o.inclusive,message:o.message}),s.dirty()):o.kind==="max"?(o.inclusive?e.data>o.value:e.data>=o.value)&&(n=this._getOrReturnCtx(e,n),m(n,{code:d.too_big,type:"bigint",maximum:o.value,inclusive:o.inclusive,message:o.message}),s.dirty()):o.kind==="multipleOf"?e.data%o.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),m(n,{code:d.not_multiple_of,multipleOf:o.value,message:o.message}),s.dirty()):S.assertNever(o);return{status:s.value,value:e.data}}_getInvalidInput(e){let r=this._getOrReturnCtx(e);return m(r,{code:d.invalid_type,expected:p.bigint,received:r.parsedType}),w}gte(e,r){return this.setLimit("min",e,!0,h.toString(r))}gt(e,r){return this.setLimit("min",e,!1,h.toString(r))}lte(e,r){return this.setLimit("max",e,!0,h.toString(r))}lt(e,r){return this.setLimit("max",e,!1,h.toString(r))}setLimit(e,r,n,s){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:h.toString(s)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:h.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:h.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:h.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:h.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:h.toString(r)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};Ce.create=t=>new Ce({checks:[],typeName:b.ZodBigInt,coerce:t?.coerce??!1,..._(t)});$e=class extends x{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==p.boolean){let n=this._getOrReturnCtx(e);return m(n,{code:d.invalid_type,expected:p.boolean,received:n.parsedType}),w}return M(e.data)}};$e.create=t=>new $e({typeName:b.ZodBoolean,coerce:t?.coerce||!1,..._(t)});Pe=class t extends x{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==p.date){let o=this._getOrReturnCtx(e);return m(o,{code:d.invalid_type,expected:p.date,received:o.parsedType}),w}if(Number.isNaN(e.data.getTime())){let o=this._getOrReturnCtx(e);return m(o,{code:d.invalid_date}),w}let n=new I,s;for(let o of this._def.checks)o.kind==="min"?e.data.getTime()<o.value&&(s=this._getOrReturnCtx(e,s),m(s,{code:d.too_small,message:o.message,inclusive:!0,exact:!1,minimum:o.value,type:"date"}),n.dirty()):o.kind==="max"?e.data.getTime()>o.value&&(s=this._getOrReturnCtx(e,s),m(s,{code:d.too_big,message:o.message,inclusive:!0,exact:!1,maximum:o.value,type:"date"}),n.dirty()):S.assertNever(o);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}min(e,r){return this._addCheck({kind:"min",value:e.getTime(),message:h.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:h.toString(r)})}get minDate(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e!=null?new Date(e):null}};Pe.create=t=>new Pe({checks:[],coerce:t?.coerce||!1,typeName:b.ZodDate,..._(t)});Qe=class extends x{_parse(e){if(this._getType(e)!==p.symbol){let n=this._getOrReturnCtx(e);return m(n,{code:d.invalid_type,expected:p.symbol,received:n.parsedType}),w}return M(e.data)}};Qe.create=t=>new Qe({typeName:b.ZodSymbol,..._(t)});Oe=class extends x{_parse(e){if(this._getType(e)!==p.undefined){let n=this._getOrReturnCtx(e);return m(n,{code:d.invalid_type,expected:p.undefined,received:n.parsedType}),w}return M(e.data)}};Oe.create=t=>new Oe({typeName:b.ZodUndefined,..._(t)});Ie=class extends x{_parse(e){if(this._getType(e)!==p.null){let n=this._getOrReturnCtx(e);return m(n,{code:d.invalid_type,expected:p.null,received:n.parsedType}),w}return M(e.data)}};Ie.create=t=>new Ie({typeName:b.ZodNull,..._(t)});be=class extends x{constructor(){super(...arguments),this._any=!0}_parse(e){return M(e.data)}};be.create=t=>new be({typeName:b.ZodAny,..._(t)});fe=class extends x{constructor(){super(...arguments),this._unknown=!0}_parse(e){return M(e.data)}};fe.create=t=>new fe({typeName:b.ZodUnknown,..._(t)});re=class extends x{_parse(e){let r=this._getOrReturnCtx(e);return m(r,{code:d.invalid_type,expected:p.never,received:r.parsedType}),w}};re.create=t=>new re({typeName:b.ZodNever,..._(t)});et=class extends x{_parse(e){if(this._getType(e)!==p.undefined){let n=this._getOrReturnCtx(e);return m(n,{code:d.invalid_type,expected:p.void,received:n.parsedType}),w}return M(e.data)}};et.create=t=>new et({typeName:b.ZodVoid,..._(t)});me=class t extends x{_parse(e){let{ctx:r,status:n}=this._processInputParams(e),s=this._def;if(r.parsedType!==p.array)return m(r,{code:d.invalid_type,expected:p.array,received:r.parsedType}),w;if(s.exactLength!==null){let i=r.data.length>s.exactLength.value,a=r.data.length<s.exactLength.value;(i||a)&&(m(r,{code:i?d.too_big:d.too_small,minimum:a?s.exactLength.value:void 0,maximum:i?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),n.dirty())}if(s.minLength!==null&&r.data.length<s.minLength.value&&(m(r,{code:d.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),n.dirty()),s.maxLength!==null&&r.data.length>s.maxLength.value&&(m(r,{code:d.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((i,a)=>s.type._parseAsync(new W(r,i,r.path,a)))).then(i=>I.mergeArray(n,i));let o=[...r.data].map((i,a)=>s.type._parseSync(new W(r,i,r.path,a)));return I.mergeArray(n,o)}get element(){return this._def.type}min(e,r){return new t({...this._def,minLength:{value:e,message:h.toString(r)}})}max(e,r){return new t({...this._def,maxLength:{value:e,message:h.toString(r)}})}length(e,r){return new t({...this._def,exactLength:{value:e,message:h.toString(r)}})}nonempty(e){return this.min(1,e)}};me.create=(t,e)=>new me({type:t,minLength:null,maxLength:null,exactLength:null,typeName:b.ZodArray,..._(e)});j=class t extends x{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),r=S.objectKeys(e);return this._cached={shape:e,keys:r},this._cached}_parse(e){if(this._getType(e)!==p.object){let u=this._getOrReturnCtx(e);return m(u,{code:d.invalid_type,expected:p.object,received:u.parsedType}),w}let{status:n,ctx:s}=this._processInputParams(e),{shape:o,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof re&&this._def.unknownKeys==="strip"))for(let u in s.data)i.includes(u)||a.push(u);let c=[];for(let u of i){let l=o[u],g=s.data[u];c.push({key:{status:"valid",value:u},value:l._parse(new W(s,g,s.path,u)),alwaysSet:u in s.data})}if(this._def.catchall instanceof re){let u=this._def.unknownKeys;if(u==="passthrough")for(let l of a)c.push({key:{status:"valid",value:l},value:{status:"valid",value:s.data[l]}});else if(u==="strict")a.length>0&&(m(s,{code:d.unrecognized_keys,keys:a}),n.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let u=this._def.catchall;for(let l of a){let g=s.data[l];c.push({key:{status:"valid",value:l},value:u._parse(new W(s,g,s.path,l)),alwaysSet:l in s.data})}}return s.common.async?Promise.resolve().then(async()=>{let u=[];for(let l of c){let g=await l.key,v=await l.value;u.push({key:g,value:v,alwaysSet:l.alwaysSet})}return u}).then(u=>I.mergeObjectSync(n,u)):I.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(e){return h.errToObj,new t({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(r,n)=>{let s=this._def.errorMap?.(r,n).message??n.defaultError;return r.code==="unrecognized_keys"?{message:h.errToObj(e).message??s}:{message:s}}}:{}})}strip(){return new t({...this._def,unknownKeys:"strip"})}passthrough(){return new t({...this._def,unknownKeys:"passthrough"})}extend(e){return new t({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new t({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:b.ZodObject})}setKey(e,r){return this.augment({[e]:r})}catchall(e){return new t({...this._def,catchall:e})}pick(e){let r={};for(let n of S.objectKeys(e))e[n]&&this.shape[n]&&(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}omit(e){let r={};for(let n of S.objectKeys(this.shape))e[n]||(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}deepPartial(){return Xe(this)}partial(e){let r={};for(let n of S.objectKeys(this.shape)){let s=this.shape[n];e&&!e[n]?r[n]=s:r[n]=s.optional()}return new t({...this._def,shape:()=>r})}required(e){let r={};for(let n of S.objectKeys(this.shape))if(e&&!e[n])r[n]=this.shape[n];else{let o=this.shape[n];for(;o instanceof J;)o=o._def.innerType;r[n]=o}return new t({...this._def,shape:()=>r})}keyof(){return ms(S.objectKeys(this.shape))}};j.create=(t,e)=>new j({shape:()=>t,unknownKeys:"strip",catchall:re.create(),typeName:b.ZodObject,..._(e)});j.strictCreate=(t,e)=>new j({shape:()=>t,unknownKeys:"strict",catchall:re.create(),typeName:b.ZodObject,..._(e)});j.lazycreate=(t,e)=>new j({shape:t,unknownKeys:"strip",catchall:re.create(),typeName:b.ZodObject,..._(e)});De=class extends x{_parse(e){let{ctx:r}=this._processInputParams(e),n=this._def.options;function s(o){for(let a of o)if(a.result.status==="valid")return a.result;for(let a of o)if(a.result.status==="dirty")return r.common.issues.push(...a.ctx.common.issues),a.result;let i=o.map(a=>new F(a.ctx.common.issues));return m(r,{code:d.invalid_union,unionErrors:i}),w}if(r.common.async)return Promise.all(n.map(async o=>{let i={...r,common:{...r.common,issues:[]},parent:null};return{result:await o._parseAsync({data:r.data,path:r.path,parent:i}),ctx:i}})).then(s);{let o,i=[];for(let c of n){let u={...r,common:{...r.common,issues:[]},parent:null},l=c._parseSync({data:r.data,path:r.path,parent:u});if(l.status==="valid")return l;l.status==="dirty"&&!o&&(o={result:l,ctx:u}),u.common.issues.length&&i.push(u.common.issues)}if(o)return r.common.issues.push(...o.ctx.common.issues),o.result;let a=i.map(c=>new F(c));return m(r,{code:d.invalid_union,unionErrors:a}),w}}get options(){return this._def.options}};De.create=(t,e)=>new De({options:t,typeName:b.ZodUnion,..._(e)});de=t=>t instanceof Me?de(t.schema):t instanceof Y?de(t.innerType()):t instanceof Le?[t.value]:t instanceof Fe?t.options:t instanceof je?S.objectValues(t.enum):t instanceof ze?de(t._def.innerType):t instanceof Oe?[void 0]:t instanceof Ie?[null]:t instanceof J?[void 0,...de(t.unwrap())]:t instanceof ae?[null,...de(t.unwrap())]:t instanceof bt||t instanceof Ze?de(t.unwrap()):t instanceof Ue?de(t._def.innerType):[],Wt=class t extends x{_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==p.object)return m(r,{code:d.invalid_type,expected:p.object,received:r.parsedType}),w;let n=this.discriminator,s=r.data[n],o=this.optionsMap.get(s);return o?r.common.async?o._parseAsync({data:r.data,path:r.path,parent:r}):o._parseSync({data:r.data,path:r.path,parent:r}):(m(r,{code:d.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),w)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,r,n){let s=new Map;for(let o of r){let i=de(o.shape[e]);if(!i.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let a of i){if(s.has(a))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(a)}`);s.set(a,o)}}return new t({typeName:b.ZodDiscriminatedUnion,discriminator:e,options:r,optionsMap:s,..._(n)})}};Ne=class extends x{_parse(e){let{status:r,ctx:n}=this._processInputParams(e),s=(o,i)=>{if(Gt(o)||Gt(i))return w;let a=Hr(o.value,i.value);return a.valid?((Jt(o)||Jt(i))&&r.dirty(),{status:r.value,value:a.data}):(m(n,{code:d.invalid_intersection_types}),w)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([o,i])=>s(o,i)):s(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};Ne.create=(t,e,r)=>new Ne({left:t,right:e,typeName:b.ZodIntersection,..._(r)});ie=class t extends x{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==p.array)return m(n,{code:d.invalid_type,expected:p.array,received:n.parsedType}),w;if(n.data.length<this._def.items.length)return m(n,{code:d.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),w;!this._def.rest&&n.data.length>this._def.items.length&&(m(n,{code:d.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());let o=[...n.data].map((i,a)=>{let c=this._def.items[a]||this._def.rest;return c?c._parse(new W(n,i,n.path,a)):null}).filter(i=>!!i);return n.common.async?Promise.all(o).then(i=>I.mergeArray(r,i)):I.mergeArray(r,o)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};ie.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new ie({items:t,typeName:b.ZodTuple,rest:null,..._(e)})};Yt=class t extends x{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==p.object)return m(n,{code:d.invalid_type,expected:p.object,received:n.parsedType}),w;let s=[],o=this._def.keyType,i=this._def.valueType;for(let a in n.data)s.push({key:o._parse(new W(n,a,n.path,a)),value:i._parse(new W(n,n.data[a],n.path,a)),alwaysSet:a in n.data});return n.common.async?I.mergeObjectAsync(r,s):I.mergeObjectSync(r,s)}get element(){return this._def.valueType}static create(e,r,n){return r instanceof x?new t({keyType:e,valueType:r,typeName:b.ZodRecord,..._(n)}):new t({keyType:we.create(),valueType:e,typeName:b.ZodRecord,..._(r)})}},tt=class extends x{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==p.map)return m(n,{code:d.invalid_type,expected:p.map,received:n.parsedType}),w;let s=this._def.keyType,o=this._def.valueType,i=[...n.data.entries()].map(([a,c],u)=>({key:s._parse(new W(n,a,n.path,[u,"key"])),value:o._parse(new W(n,c,n.path,[u,"value"]))}));if(n.common.async){let a=new Map;return Promise.resolve().then(async()=>{for(let c of i){let u=await c.key,l=await c.value;if(u.status==="aborted"||l.status==="aborted")return w;(u.status==="dirty"||l.status==="dirty")&&r.dirty(),a.set(u.value,l.value)}return{status:r.value,value:a}})}else{let a=new Map;for(let c of i){let u=c.key,l=c.value;if(u.status==="aborted"||l.status==="aborted")return w;(u.status==="dirty"||l.status==="dirty")&&r.dirty(),a.set(u.value,l.value)}return{status:r.value,value:a}}}};tt.create=(t,e,r)=>new tt({valueType:e,keyType:t,typeName:b.ZodMap,..._(r)});rt=class t extends x{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==p.set)return m(n,{code:d.invalid_type,expected:p.set,received:n.parsedType}),w;let s=this._def;s.minSize!==null&&n.data.size<s.minSize.value&&(m(n,{code:d.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),r.dirty()),s.maxSize!==null&&n.data.size>s.maxSize.value&&(m(n,{code:d.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),r.dirty());let o=this._def.valueType;function i(c){let u=new Set;for(let l of c){if(l.status==="aborted")return w;l.status==="dirty"&&r.dirty(),u.add(l.value)}return{status:r.value,value:u}}let a=[...n.data.values()].map((c,u)=>o._parse(new W(n,c,n.path,u)));return n.common.async?Promise.all(a).then(c=>i(c)):i(a)}min(e,r){return new t({...this._def,minSize:{value:e,message:h.toString(r)}})}max(e,r){return new t({...this._def,maxSize:{value:e,message:h.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}};rt.create=(t,e)=>new rt({valueType:t,minSize:null,maxSize:null,typeName:b.ZodSet,..._(e)});qt=class t extends x{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==p.function)return m(r,{code:d.invalid_type,expected:p.function,received:r.parsedType}),w;function n(a,c){return wt({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,Ye(),le].filter(u=>!!u),issueData:{code:d.invalid_arguments,argumentsError:c}})}function s(a,c){return wt({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,Ye(),le].filter(u=>!!u),issueData:{code:d.invalid_return_type,returnTypeError:c}})}let o={errorMap:r.common.contextualErrorMap},i=r.data;if(this._def.returns instanceof ve){let a=this;return M(async function(...c){let u=new F([]),l=await a._def.args.parseAsync(c,o).catch(k=>{throw u.addIssue(n(c,k)),u}),g=await Reflect.apply(i,this,l);return await a._def.returns._def.type.parseAsync(g,o).catch(k=>{throw u.addIssue(s(g,k)),u})})}else{let a=this;return M(function(...c){let u=a._def.args.safeParse(c,o);if(!u.success)throw new F([n(c,u.error)]);let l=Reflect.apply(i,this,u.data),g=a._def.returns.safeParse(l,o);if(!g.success)throw new F([s(l,g.error)]);return g.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new t({...this._def,args:ie.create(e).rest(fe.create())})}returns(e){return new t({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,r,n){return new t({args:e||ie.create([]).rest(fe.create()),returns:r||fe.create(),typeName:b.ZodFunction,..._(n)})}},Me=class extends x{get schema(){return this._def.getter()}_parse(e){let{ctx:r}=this._processInputParams(e);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}};Me.create=(t,e)=>new Me({getter:t,typeName:b.ZodLazy,..._(e)});Le=class extends x{_parse(e){if(e.data!==this._def.value){let r=this._getOrReturnCtx(e);return m(r,{received:r.data,code:d.invalid_literal,expected:this._def.value}),w}return{status:"valid",value:e.data}}get value(){return this._def.value}};Le.create=(t,e)=>new Le({value:t,typeName:b.ZodLiteral,..._(e)});Fe=class t extends x{_parse(e){if(typeof e.data!="string"){let r=this._getOrReturnCtx(e),n=this._def.values;return m(r,{expected:S.joinValues(n),received:r.parsedType,code:d.invalid_type}),w}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let r=this._getOrReturnCtx(e),n=this._def.values;return m(r,{received:r.data,code:d.invalid_enum_value,options:n}),w}return M(e.data)}get options(){return this._def.values}get enum(){let e={};for(let r of this._def.values)e[r]=r;return e}get Values(){let e={};for(let r of this._def.values)e[r]=r;return e}get Enum(){let e={};for(let r of this._def.values)e[r]=r;return e}extract(e,r=this._def){return t.create(e,{...this._def,...r})}exclude(e,r=this._def){return t.create(this.options.filter(n=>!e.includes(n)),{...this._def,...r})}};Fe.create=ms;je=class extends x{_parse(e){let r=S.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==p.string&&n.parsedType!==p.number){let s=S.objectValues(r);return m(n,{expected:S.joinValues(s),received:n.parsedType,code:d.invalid_type}),w}if(this._cache||(this._cache=new Set(S.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let s=S.objectValues(r);return m(n,{received:n.data,code:d.invalid_enum_value,options:s}),w}return M(e.data)}get enum(){return this._def.values}};je.create=(t,e)=>new je({values:t,typeName:b.ZodNativeEnum,..._(e)});ve=class extends x{unwrap(){return this._def.type}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==p.promise&&r.common.async===!1)return m(r,{code:d.invalid_type,expected:p.promise,received:r.parsedType}),w;let n=r.parsedType===p.promise?r.data:Promise.resolve(r.data);return M(n.then(s=>this._def.type.parseAsync(s,{path:r.path,errorMap:r.common.contextualErrorMap})))}};ve.create=(t,e)=>new ve({type:t,typeName:b.ZodPromise,..._(e)});Y=class extends x{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===b.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:r,ctx:n}=this._processInputParams(e),s=this._def.effect||null,o={addIssue:i=>{m(n,i),i.fatal?r.abort():r.dirty()},get path(){return n.path}};if(o.addIssue=o.addIssue.bind(o),s.type==="preprocess"){let i=s.transform(n.data,o);if(n.common.async)return Promise.resolve(i).then(async a=>{if(r.value==="aborted")return w;let c=await this._def.schema._parseAsync({data:a,path:n.path,parent:n});return c.status==="aborted"?w:c.status==="dirty"?Ae(c.value):r.value==="dirty"?Ae(c.value):c});{if(r.value==="aborted")return w;let a=this._def.schema._parseSync({data:i,path:n.path,parent:n});return a.status==="aborted"?w:a.status==="dirty"?Ae(a.value):r.value==="dirty"?Ae(a.value):a}}if(s.type==="refinement"){let i=a=>{let c=s.refinement(a,o);if(n.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(n.common.async===!1){let a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?w:(a.status==="dirty"&&r.dirty(),i(a.value),{status:r.value,value:a.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(a=>a.status==="aborted"?w:(a.status==="dirty"&&r.dirty(),i(a.value).then(()=>({status:r.value,value:a.value}))))}if(s.type==="transform")if(n.common.async===!1){let i=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!ye(i))return w;let a=s.transform(i.value,o);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:a}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(i=>ye(i)?Promise.resolve(s.transform(i.value,o)).then(a=>({status:r.value,value:a})):w);S.assertNever(s)}};Y.create=(t,e,r)=>new Y({schema:t,typeName:b.ZodEffects,effect:e,..._(r)});Y.createWithPreprocess=(t,e,r)=>new Y({schema:e,effect:{type:"preprocess",transform:t},typeName:b.ZodEffects,..._(r)});J=class extends x{_parse(e){return this._getType(e)===p.undefined?M(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};J.create=(t,e)=>new J({innerType:t,typeName:b.ZodOptional,..._(e)});ae=class extends x{_parse(e){return this._getType(e)===p.null?M(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};ae.create=(t,e)=>new ae({innerType:t,typeName:b.ZodNullable,..._(e)});ze=class extends x{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return r.parsedType===p.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};ze.create=(t,e)=>new ze({innerType:t,typeName:b.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,..._(e)});Ue=class extends x{_parse(e){let{ctx:r}=this._processInputParams(e),n={...r,common:{...r.common,issues:[]}},s=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return qe(s)?s.then(o=>({status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new F(n.common.issues)},input:n.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new F(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};Ue.create=(t,e)=>new Ue({innerType:t,typeName:b.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,..._(e)});nt=class extends x{_parse(e){if(this._getType(e)!==p.nan){let n=this._getOrReturnCtx(e);return m(n,{code:d.invalid_type,expected:p.nan,received:n.parsedType}),w}return{status:"valid",value:e.data}}};nt.create=t=>new nt({typeName:b.ZodNaN,..._(t)});wa=Symbol("zod_brand"),bt=class extends x{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return this._def.type._parse({data:n,path:r.path,parent:r})}unwrap(){return this._def.type}},vt=class t extends x{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let o=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?w:o.status==="dirty"?(r.dirty(),Ae(o.value)):this._def.out._parseAsync({data:o.value,path:n.path,parent:n})})();{let s=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?w:s.status==="dirty"?(r.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:n.path,parent:n})}}static create(e,r){return new t({in:e,out:r,typeName:b.ZodPipeline})}},Ze=class extends x{_parse(e){let r=this._def.innerType._parse(e),n=s=>(ye(s)&&(s.value=Object.freeze(s.value)),s);return qe(r)?r.then(s=>n(s)):n(r)}unwrap(){return this._def.innerType}};Ze.create=(t,e)=>new Ze({innerType:t,typeName:b.ZodReadonly,..._(e)});ba={object:j.lazycreate};(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(b||(b={}));va=(t,e={message:`Input not instance of ${t.name}`})=>ps(r=>r instanceof t,e),hs=we.create,gs=Re.create,ka=nt.create,_a=Ce.create,ys=$e.create,xa=Pe.create,Sa=Qe.create,Ea=Oe.create,Ta=Ie.create,Aa=be.create,Ra=fe.create,Ca=re.create,$a=et.create,Pa=me.create,Oa=j.create,Ia=j.strictCreate,Da=De.create,Na=Wt.create,Ma=Ne.create,La=ie.create,Fa=Yt.create,ja=tt.create,za=rt.create,Ua=qt.create,Za=Me.create,Ha=Le.create,Ba=Fe.create,Va=je.create,Ka=ve.create,Ga=Y.create,Ja=J.create,Wa=ae.create,Ya=Y.createWithPreprocess,qa=vt.create,Xa=()=>hs().optional(),Qa=()=>gs().optional(),ec=()=>ys().optional(),tc={string:(t=>we.create({...t,coerce:!0})),number:(t=>Re.create({...t,coerce:!0})),boolean:(t=>$e.create({...t,coerce:!0})),bigint:(t=>Ce.create({...t,coerce:!0})),date:(t=>Pe.create({...t,coerce:!0}))},rc=w});var f={};te(f,{BRAND:()=>wa,DIRTY:()=>Ae,EMPTY_PATH:()=>Yi,INVALID:()=>w,NEVER:()=>rc,OK:()=>M,ParseStatus:()=>I,Schema:()=>x,ZodAny:()=>be,ZodArray:()=>me,ZodBigInt:()=>Ce,ZodBoolean:()=>$e,ZodBranded:()=>bt,ZodCatch:()=>Ue,ZodDate:()=>Pe,ZodDefault:()=>ze,ZodDiscriminatedUnion:()=>Wt,ZodEffects:()=>Y,ZodEnum:()=>Fe,ZodError:()=>F,ZodFirstPartyTypeKind:()=>b,ZodFunction:()=>qt,ZodIntersection:()=>Ne,ZodIssueCode:()=>d,ZodLazy:()=>Me,ZodLiteral:()=>Le,ZodMap:()=>tt,ZodNaN:()=>nt,ZodNativeEnum:()=>je,ZodNever:()=>re,ZodNull:()=>Ie,ZodNullable:()=>ae,ZodNumber:()=>Re,ZodObject:()=>j,ZodOptional:()=>J,ZodParsedType:()=>p,ZodPipeline:()=>vt,ZodPromise:()=>ve,ZodReadonly:()=>Ze,ZodRecord:()=>Yt,ZodSchema:()=>x,ZodSet:()=>rt,ZodString:()=>we,ZodSymbol:()=>Qe,ZodTransformer:()=>Y,ZodTuple:()=>ie,ZodType:()=>x,ZodUndefined:()=>Oe,ZodUnion:()=>De,ZodUnknown:()=>fe,ZodVoid:()=>et,addIssueToContext:()=>m,any:()=>Aa,array:()=>Pa,bigint:()=>_a,boolean:()=>ys,coerce:()=>tc,custom:()=>ps,date:()=>xa,datetimeRegex:()=>fs,defaultErrorMap:()=>le,discriminatedUnion:()=>Na,effect:()=>Ga,enum:()=>Ba,function:()=>Ua,getErrorMap:()=>Ye,getParsedType:()=>oe,instanceof:()=>va,intersection:()=>Ma,isAborted:()=>Gt,isAsync:()=>qe,isDirty:()=>Jt,isValid:()=>ye,late:()=>ba,lazy:()=>Za,literal:()=>Ha,makeIssue:()=>wt,map:()=>ja,nan:()=>ka,nativeEnum:()=>Va,never:()=>Ca,null:()=>Ta,nullable:()=>Wa,number:()=>gs,object:()=>Oa,objectUtil:()=>jr,oboolean:()=>ec,onumber:()=>Qa,optional:()=>Ja,ostring:()=>Xa,pipeline:()=>qa,preprocess:()=>Ya,promise:()=>Ka,quotelessJson:()=>Gi,record:()=>Fa,set:()=>za,setErrorMap:()=>Wi,strictObject:()=>Ia,string:()=>hs,symbol:()=>Sa,transformer:()=>Ga,tuple:()=>La,undefined:()=>Ea,union:()=>Da,unknown:()=>Ra,util:()=>S,void:()=>$a});var Br=E(()=>{Kt();Ur();is();yt();ws();Vt()});var st=E(()=>{Br();Br()});import{createHash as nc}from"node:crypto";function ke(t){let e=bs.get(t);return e||(e=nc("sha256").update(`tkr:${t}`).digest("hex").slice(0,16),bs.set(t,e)),e}var sc,oc,ot,bs,kt=E(()=>{"use strict";st();sc=f.enum(["normal","compact","minimal"]),oc=f.enum(["off","light","balanced","max"]),ot=f.object({enabled:f.boolean().default(!0),telemetryOptIn:f.boolean().default(!0),outputVerbosity:sc.default("compact"),reducer:oc.default("off"),filters:f.object({enableAll:f.boolean().default(!0),disabled:f.array(f.string().max(64)).max(100).default([])}).default({enableAll:!0,disabled:[]})}),bs=new Map});var ks={};te(ks,{bundleRefreshFile:()=>_t,claudeCommandFile:()=>xe,claudeCommandsDir:()=>er,contentCacheDir:()=>St,contentCacheFile:()=>Xt,enrollCooldownFile:()=>Vr,installIdFile:()=>it,managedCommandsFile:()=>Qt,skillFile:()=>_e,skillsDir:()=>xt,stateFile:()=>ic,tokmizerHome:()=>y});import vs from"node:os";import{join as q}from"node:path";function y(){return process.env.TOKMIZER_HOME||q(vs.homedir(),".tokmizer")}function ic(){return q(y(),"state.json")}function it(){return q(y(),"install-id")}function Vr(){return q(y(),"enroll-cooldown")}function _t(){return q(y(),"bundle-refresh.json")}function xt(){return q(y(),"skills")}function _e(t){return q(xt(),`${t}.md`)}function St(){return q(y(),"content-cache")}function Xt(t){return q(St(),t)}function Qt(){return q(y(),"managed-commands.json")}function er(){return process.env.TOKMIZER_CLAUDE_COMMANDS_DIR||q(vs.homedir(),".claude","commands")}function xe(t){return q(er(),`${t}.md`)}var D=E(()=>{"use strict"});import at from"node:os";import{createHash as ac,randomUUID as cc}from"node:crypto";import{readFile as _s,writeFile as xs,mkdir as uc}from"node:fs/promises";async function tr(){try{let r=(await _s(it(),"utf8")).trim();if(/^[0-9a-f-]{36}$/i.test(r))return r}catch{}await uc(y(),{recursive:!0});let t=cc();try{return await xs(it(),t,{mode:384,flag:"wx"}),t}catch{try{let e=(await _s(it(),"utf8")).trim();if(/^[0-9a-f-]{36}$/i.test(e))return e}catch{}return await xs(it(),t,{mode:384}),t}}function Kr(t){return ac("sha256").update(t).digest("hex")}function lc(){let t=at.networkInterfaces();for(let e of Object.keys(t))for(let r of t[e]??[])if(!r.internal&&r.mac&&r.mac!=="00:00:00:00:00:00")return r.mac;return"no-mac"}async function X(){let t=await tr(),e=at.hostname(),r=at.platform(),n=at.release(),s=at.cpus(),o=s[0]?.model??"unknown",i=s.length,a=Kr(lc()),c=Kr(at.userInfo().username),u=[e,r,n,o,String(i),a,c,t].join("|");return{fingerprint:Kr(u),installId:t,hostname:e,os:r,osVersion:n,cpuModel:o,cpuCores:i,macHash:a,usernameHash:c}}var He=E(()=>{"use strict";D()});import{join as Gr}from"node:path";import{mkdir as dc,readFile as fc,writeFile as mc,unlink as Ss,rename as pc}from"node:fs/promises";function Et(){try{let t=Intl.DateTimeFormat().resolvedOptions().timeZone;return t&&t.length>0?t:"Etc/UTC"}catch{return"Etc/UTC"}}function Wr(t){return t?.dir??y()}async function T(t){let e=Wr(t);try{let r=await fc(Gr(e,Jr),"utf8"),n=JSON.parse(r),s=n.timeZone;return{...n,lastSettingsRevision:n.lastSettingsRevision??0,get timeZone(){return s??=Et()},bonusActive:n.bonusActive??!1,...n.bonusResetAt!==void 0?{bonusResetAt:n.bonusResetAt}:{}}}catch{return null}}async function rr(t,e){let r=Wr(e);await dc(r,{recursive:!0}),t.installedAt==null&&(t.installedAt=Math.floor(Date.now()/1e3));let n=Gr(r,Jr),s=`${n}.tmp-${process.pid}-${process.hrtime.bigint()}`;await mc(s,JSON.stringify(t,null,2),{mode:384});try{await pc(s,n)}catch(o){try{await Ss(s)}catch{}throw o}}async function nr(t){let e=Wr(t);try{await Ss(Gr(e,Jr))}catch{return}}var Jr,pe=E(()=>{"use strict";D();Jr="state.json"});import{createRequire as hc}from"node:module";function yc(){for(let t of["../package.json","../../package.json"])try{let e=gc(t).version;if(typeof e=="string"&&e)return e}catch{}return"0.0.0"}function ct(t,e){if(!t||!e)return!1;let r=t.split(".").map(s=>parseInt(s,10)),n=e.split(".").map(s=>parseInt(s,10));for(let s=0;s<3;s+=1){let o=r[s]??0,i=n[s]??0;if(Number.isNaN(o)||Number.isNaN(i))return!1;if(o<i)return!0;if(o>i)return!1}return!1}var gc,Q,ut=E(()=>{"use strict";gc=hc(import.meta.url);Q=yc()});var Es,Ts=E(()=>{"use strict";Es=`-----BEGIN PUBLIC KEY-----
|
|
3
|
+
var Gi=Object.defineProperty;var E=(t,e,r)=>()=>{if(r)throw r[0];try{return t&&(e=t(t=0)),e}catch(n){throw r=[n],n}};var te=(t,e)=>{for(var r in e)Gi(t,r,{get:e[r],enumerable:!0})};var S,zr,p,ie,yt=E(()=>{(function(t){t.assertEqual=s=>{};function e(s){}t.assertIs=e;function r(s){throw new Error}t.assertNever=r,t.arrayToEnum=s=>{let o={};for(let i of s)o[i]=i;return o},t.getValidEnumValues=s=>{let o=t.objectKeys(s).filter(a=>typeof s[s[a]]!="number"),i={};for(let a of o)i[a]=s[a];return t.objectValues(i)},t.objectValues=s=>t.objectKeys(s).map(function(o){return s[o]}),t.objectKeys=typeof Object.keys=="function"?s=>Object.keys(s):s=>{let o=[];for(let i in s)Object.prototype.hasOwnProperty.call(s,i)&&o.push(i);return o},t.find=(s,o)=>{for(let i of s)if(o(i))return i},t.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&Number.isFinite(s)&&Math.floor(s)===s;function n(s,o=" | "){return s.map(i=>typeof i=="string"?`'${i}'`:i).join(o)}t.joinValues=n,t.jsonStringifyReplacer=(s,o)=>typeof o=="bigint"?o.toString():o})(S||(S={}));(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(zr||(zr={}));p=S.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),ie=t=>{switch(typeof t){case"undefined":return p.undefined;case"string":return p.string;case"number":return Number.isNaN(t)?p.nan:p.number;case"boolean":return p.boolean;case"function":return p.function;case"bigint":return p.bigint;case"symbol":return p.symbol;case"object":return Array.isArray(t)?p.array:t===null?p.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?p.promise:typeof Map<"u"&&t instanceof Map?p.map:typeof Set<"u"&&t instanceof Set?p.set:typeof Date<"u"&&t instanceof Date?p.date:p.object;default:return p.unknown}}});var d,Ji,F,Kt=E(()=>{yt();d=S.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),Ji=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),F=class t extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};let r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=e}format(e){let r=e||function(o){return o.message},n={_errors:[]},s=o=>{for(let i of o.issues)if(i.code==="invalid_union")i.unionErrors.map(s);else if(i.code==="invalid_return_type")s(i.returnTypeError);else if(i.code==="invalid_arguments")s(i.argumentsError);else if(i.path.length===0)n._errors.push(r(i));else{let a=n,c=0;for(;c<i.path.length;){let u=i.path[c];c===i.path.length-1?(a[u]=a[u]||{_errors:[]},a[u]._errors.push(r(i))):a[u]=a[u]||{_errors:[]},a=a[u],c++}}};return s(this),n}static assert(e){if(!(e instanceof t))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,S.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=r=>r.message){let r={},n=[];for(let s of this.issues)if(s.path.length>0){let o=s.path[0];r[o]=r[o]||[],r[o].push(e(s))}else n.push(e(s));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}};F.create=t=>new F(t)});var Wi,le,Ur=E(()=>{Kt();yt();Wi=(t,e)=>{let r;switch(t.code){case d.invalid_type:t.received===p.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case d.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,S.jsonStringifyReplacer)}`;break;case d.unrecognized_keys:r=`Unrecognized key(s) in object: ${S.joinValues(t.keys,", ")}`;break;case d.invalid_union:r="Invalid input";break;case d.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${S.joinValues(t.options)}`;break;case d.invalid_enum_value:r=`Invalid enum value. Expected ${S.joinValues(t.options)}, received '${t.received}'`;break;case d.invalid_arguments:r="Invalid function arguments";break;case d.invalid_return_type:r="Invalid function return type";break;case d.invalid_date:r="Invalid date";break;case d.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(r=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?r=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?r=`Invalid input: must end with "${t.validation.endsWith}"`:S.assertNever(t.validation):t.validation!=="regex"?r=`Invalid ${t.validation}`:r="Invalid";break;case d.too_small:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:r="Invalid input";break;case d.too_big:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?r=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:r="Invalid input";break;case d.custom:r="Invalid input";break;case d.invalid_intersection_types:r="Intersection results could not be merged";break;case d.not_multiple_of:r=`Number must be a multiple of ${t.multipleOf}`;break;case d.not_finite:r="Number must be finite";break;default:r=e.defaultError,S.assertNever(t)}return{message:r}},le=Wi});function Yi(t){cs=t}function qe(){return cs}var cs,Gt=E(()=>{Ur();cs=le});function m(t,e){let r=qe(),n=wt({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===le?void 0:le].filter(s=>!!s)});t.common.issues.push(n)}var wt,qi,I,w,Re,M,Jt,Wt,ye,Xe,Zr=E(()=>{Gt();Ur();wt=t=>{let{data:e,path:r,errorMaps:n,issueData:s}=t,o=[...r,...s.path||[]],i={...s,path:o};if(s.message!==void 0)return{...s,path:o,message:s.message};let a="",c=n.filter(u=>!!u).slice().reverse();for(let u of c)a=u(i,{data:e,defaultError:a}).message;return{...s,path:o,message:a}},qi=[];I=class t{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,r){let n=[];for(let s of r){if(s.status==="aborted")return w;s.status==="dirty"&&e.dirty(),n.push(s.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,r){let n=[];for(let s of r){let o=await s.key,i=await s.value;n.push({key:o,value:i})}return t.mergeObjectSync(e,n)}static mergeObjectSync(e,r){let n={};for(let s of r){let{key:o,value:i}=s;if(o.status==="aborted"||i.status==="aborted")return w;o.status==="dirty"&&e.dirty(),i.status==="dirty"&&e.dirty(),o.value!=="__proto__"&&(typeof i.value<"u"||s.alwaysSet)&&(n[o.value]=i.value)}return{status:e.value,value:n}}},w=Object.freeze({status:"aborted"}),Re=t=>({status:"dirty",value:t}),M=t=>({status:"valid",value:t}),Jt=t=>t.status==="aborted",Wt=t=>t.status==="dirty",ye=t=>t.status==="valid",Xe=t=>typeof Promise<"u"&&t instanceof Promise});var us=E(()=>{});var g,ls=E(()=>{(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(g||(g={}))});function _(t){if(!t)return{};let{errorMap:e,invalid_type_error:r,required_error:n,description:s}=t;if(e&&(r||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:s}:{errorMap:(i,a)=>{let{message:c}=t;return i.code==="invalid_enum_value"?{message:c??a.defaultError}:typeof a.data>"u"?{message:c??n??a.defaultError}:i.code!=="invalid_type"?{message:a.defaultError}:{message:c??r??a.defaultError}},description:s}}function ps(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);let r=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${r}`}function pa(t){return new RegExp(`^${ps(t)}$`)}function hs(t){let e=`${ms}T${ps(t)}`,r=[];return r.push(t.local?"Z?":"Z"),t.offset&&r.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${r.join("|")})`,new RegExp(`^${e}$`)}function ha(t,e){return!!((e==="v4"||!e)&&aa.test(t)||(e==="v6"||!e)&&ua.test(t))}function ga(t,e){if(!na.test(t))return!1;try{let[r]=t.split(".");if(!r)return!1;let n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),s=JSON.parse(atob(n));return!(typeof s!="object"||s===null||"typ"in s&&s?.typ!=="JWT"||!s.alg||e&&s.alg!==e)}catch{return!1}}function ya(t,e){return!!((e==="v4"||!e)&&ca.test(t)||(e==="v6"||!e)&&la.test(t))}function wa(t,e){let r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,s=r>n?r:n,o=Number.parseInt(t.toFixed(s).replace(".","")),i=Number.parseInt(e.toFixed(s).replace(".",""));return o%i/10**s}function Qe(t){if(t instanceof j){let e={};for(let r in t.shape){let n=t.shape[r];e[r]=W.create(Qe(n))}return new j({...t._def,shape:()=>e})}else return t instanceof me?new me({...t._def,type:Qe(t.element)}):t instanceof W?W.create(Qe(t.unwrap())):t instanceof ce?ce.create(Qe(t.unwrap())):t instanceof ae?ae.create(t.items.map(e=>Qe(e))):t}function Br(t,e){let r=ie(t),n=ie(e);if(t===e)return{valid:!0,data:t};if(r===p.object&&n===p.object){let s=S.objectKeys(e),o=S.objectKeys(t).filter(a=>s.indexOf(a)!==-1),i={...t,...e};for(let a of o){let c=Br(t[a],e[a]);if(!c.valid)return{valid:!1};i[a]=c.data}return{valid:!0,data:i}}else if(r===p.array&&n===p.array){if(t.length!==e.length)return{valid:!1};let s=[];for(let o=0;o<t.length;o++){let i=t[o],a=e[o],c=Br(i,a);if(!c.valid)return{valid:!1};s.push(c.data)}return{valid:!0,data:s}}else return r===p.date&&n===p.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}function gs(t,e){return new je({values:t,typeName:v.ZodEnum,..._(e)})}function fs(t,e){let r=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof r=="string"?{message:r}:r}function ys(t,e={},r){return t?ve.create().superRefine((n,s)=>{let o=t(n);if(o instanceof Promise)return o.then(i=>{if(!i){let a=fs(e,n),c=a.fatal??r??!0;s.addIssue({code:"custom",...a,fatal:c})}});if(!o){let i=fs(e,n),a=i.fatal??r??!0;s.addIssue({code:"custom",...i,fatal:a})}}):ve.create()}var Y,ds,x,Xi,Qi,ea,ta,ra,na,sa,oa,ia,Hr,aa,ca,ua,la,da,fa,ms,ma,we,Ce,$e,Pe,Oe,et,Ie,De,ve,fe,re,tt,me,j,Ne,de,Yt,Me,ae,qt,rt,nt,Xt,Le,Fe,je,ze,be,q,W,ce,Ue,Ze,st,va,vt,bt,He,ba,v,ka,ws,vs,_a,xa,bs,Sa,Ea,Ta,Aa,Ra,Ca,$a,Pa,Oa,Ia,Da,Na,Ma,La,Fa,ja,za,Ua,Za,Ha,Ba,Va,Ka,Ga,Ja,Wa,Ya,qa,Xa,Qa,ec,tc,rc,nc,ks=E(()=>{Kt();Gt();ls();Zr();yt();Y=class{constructor(e,r,n,s){this._cachedPath=[],this.parent=e,this.data=r,this._path=n,this._key=s}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},ds=(t,e)=>{if(ye(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let r=new F(t.common.issues);return this._error=r,this._error}}};x=class{get description(){return this._def.description}_getType(e){return ie(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:ie(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new I,ctx:{common:e.parent.common,data:e.data,parsedType:ie(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let r=this._parse(e);if(Xe(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(e){let r=this._parse(e);return Promise.resolve(r)}parse(e,r){let n=this.safeParse(e,r);if(n.success)return n.data;throw n.error}safeParse(e,r){let n={common:{issues:[],async:r?.async??!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ie(e)},s=this._parseSync({data:e,path:n.path,parent:n});return ds(n,s)}"~validate"(e){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ie(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:r});return ye(n)?{value:n.value}:{issues:r.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:r}).then(n=>ye(n)?{value:n.value}:{issues:r.common.issues})}async parseAsync(e,r){let n=await this.safeParseAsync(e,r);if(n.success)return n.data;throw n.error}async safeParseAsync(e,r){let n={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ie(e)},s=this._parse({data:e,path:n.path,parent:n}),o=await(Xe(s)?s:Promise.resolve(s));return ds(n,o)}refine(e,r){let n=s=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(s):r;return this._refinement((s,o)=>{let i=e(s),a=()=>o.addIssue({code:d.custom,...n(s)});return typeof Promise<"u"&&i instanceof Promise?i.then(c=>c?!0:(a(),!1)):i?!0:(a(),!1)})}refinement(e,r){return this._refinement((n,s)=>e(n)?!0:(s.addIssue(typeof r=="function"?r(n,s):r),!1))}_refinement(e){return new q({schema:this,typeName:v.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:r=>this["~validate"](r)}}optional(){return W.create(this,this._def)}nullable(){return ce.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return me.create(this)}promise(){return be.create(this,this._def)}or(e){return Ne.create([this,e],this._def)}and(e){return Me.create(this,e,this._def)}transform(e){return new q({..._(this._def),schema:this,typeName:v.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let r=typeof e=="function"?e:()=>e;return new Ue({..._(this._def),innerType:this,defaultValue:r,typeName:v.ZodDefault})}brand(){return new vt({typeName:v.ZodBranded,type:this,..._(this._def)})}catch(e){let r=typeof e=="function"?e:()=>e;return new Ze({..._(this._def),innerType:this,catchValue:r,typeName:v.ZodCatch})}describe(e){let r=this.constructor;return new r({...this._def,description:e})}pipe(e){return bt.create(this,e)}readonly(){return He.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},Xi=/^c[^\s-]{8,}$/i,Qi=/^[0-9a-z]+$/,ea=/^[0-9A-HJKMNP-TV-Z]{26}$/i,ta=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,ra=/^[a-z0-9_-]{21}$/i,na=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,sa=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,oa=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,ia="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",aa=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ca=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ua=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,la=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,da=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,fa=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,ms="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",ma=new RegExp(`^${ms}$`);we=class t extends x{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==p.string){let o=this._getOrReturnCtx(e);return m(o,{code:d.invalid_type,expected:p.string,received:o.parsedType}),w}let n=new I,s;for(let o of this._def.checks)if(o.kind==="min")e.data.length<o.value&&(s=this._getOrReturnCtx(e,s),m(s,{code:d.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),n.dirty());else if(o.kind==="max")e.data.length>o.value&&(s=this._getOrReturnCtx(e,s),m(s,{code:d.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),n.dirty());else if(o.kind==="length"){let i=e.data.length>o.value,a=e.data.length<o.value;(i||a)&&(s=this._getOrReturnCtx(e,s),i?m(s,{code:d.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}):a&&m(s,{code:d.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}),n.dirty())}else if(o.kind==="email")oa.test(e.data)||(s=this._getOrReturnCtx(e,s),m(s,{validation:"email",code:d.invalid_string,message:o.message}),n.dirty());else if(o.kind==="emoji")Hr||(Hr=new RegExp(ia,"u")),Hr.test(e.data)||(s=this._getOrReturnCtx(e,s),m(s,{validation:"emoji",code:d.invalid_string,message:o.message}),n.dirty());else if(o.kind==="uuid")ta.test(e.data)||(s=this._getOrReturnCtx(e,s),m(s,{validation:"uuid",code:d.invalid_string,message:o.message}),n.dirty());else if(o.kind==="nanoid")ra.test(e.data)||(s=this._getOrReturnCtx(e,s),m(s,{validation:"nanoid",code:d.invalid_string,message:o.message}),n.dirty());else if(o.kind==="cuid")Xi.test(e.data)||(s=this._getOrReturnCtx(e,s),m(s,{validation:"cuid",code:d.invalid_string,message:o.message}),n.dirty());else if(o.kind==="cuid2")Qi.test(e.data)||(s=this._getOrReturnCtx(e,s),m(s,{validation:"cuid2",code:d.invalid_string,message:o.message}),n.dirty());else if(o.kind==="ulid")ea.test(e.data)||(s=this._getOrReturnCtx(e,s),m(s,{validation:"ulid",code:d.invalid_string,message:o.message}),n.dirty());else if(o.kind==="url")try{new URL(e.data)}catch{s=this._getOrReturnCtx(e,s),m(s,{validation:"url",code:d.invalid_string,message:o.message}),n.dirty()}else o.kind==="regex"?(o.regex.lastIndex=0,o.regex.test(e.data)||(s=this._getOrReturnCtx(e,s),m(s,{validation:"regex",code:d.invalid_string,message:o.message}),n.dirty())):o.kind==="trim"?e.data=e.data.trim():o.kind==="includes"?e.data.includes(o.value,o.position)||(s=this._getOrReturnCtx(e,s),m(s,{code:d.invalid_string,validation:{includes:o.value,position:o.position},message:o.message}),n.dirty()):o.kind==="toLowerCase"?e.data=e.data.toLowerCase():o.kind==="toUpperCase"?e.data=e.data.toUpperCase():o.kind==="startsWith"?e.data.startsWith(o.value)||(s=this._getOrReturnCtx(e,s),m(s,{code:d.invalid_string,validation:{startsWith:o.value},message:o.message}),n.dirty()):o.kind==="endsWith"?e.data.endsWith(o.value)||(s=this._getOrReturnCtx(e,s),m(s,{code:d.invalid_string,validation:{endsWith:o.value},message:o.message}),n.dirty()):o.kind==="datetime"?hs(o).test(e.data)||(s=this._getOrReturnCtx(e,s),m(s,{code:d.invalid_string,validation:"datetime",message:o.message}),n.dirty()):o.kind==="date"?ma.test(e.data)||(s=this._getOrReturnCtx(e,s),m(s,{code:d.invalid_string,validation:"date",message:o.message}),n.dirty()):o.kind==="time"?pa(o).test(e.data)||(s=this._getOrReturnCtx(e,s),m(s,{code:d.invalid_string,validation:"time",message:o.message}),n.dirty()):o.kind==="duration"?sa.test(e.data)||(s=this._getOrReturnCtx(e,s),m(s,{validation:"duration",code:d.invalid_string,message:o.message}),n.dirty()):o.kind==="ip"?ha(e.data,o.version)||(s=this._getOrReturnCtx(e,s),m(s,{validation:"ip",code:d.invalid_string,message:o.message}),n.dirty()):o.kind==="jwt"?ga(e.data,o.alg)||(s=this._getOrReturnCtx(e,s),m(s,{validation:"jwt",code:d.invalid_string,message:o.message}),n.dirty()):o.kind==="cidr"?ya(e.data,o.version)||(s=this._getOrReturnCtx(e,s),m(s,{validation:"cidr",code:d.invalid_string,message:o.message}),n.dirty()):o.kind==="base64"?da.test(e.data)||(s=this._getOrReturnCtx(e,s),m(s,{validation:"base64",code:d.invalid_string,message:o.message}),n.dirty()):o.kind==="base64url"?fa.test(e.data)||(s=this._getOrReturnCtx(e,s),m(s,{validation:"base64url",code:d.invalid_string,message:o.message}),n.dirty()):S.assertNever(o);return{status:n.value,value:e.data}}_regex(e,r,n){return this.refinement(s=>e.test(s),{validation:r,code:d.invalid_string,...g.errToObj(n)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...g.errToObj(e)})}url(e){return this._addCheck({kind:"url",...g.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...g.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...g.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...g.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...g.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...g.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...g.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...g.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...g.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...g.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...g.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...g.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...g.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...g.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...g.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...g.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r?.position,...g.errToObj(r?.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...g.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...g.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...g.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...g.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...g.errToObj(r)})}nonempty(e){return this.min(1,g.errToObj(e))}trim(){return new t({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxLength(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};we.create=t=>new we({checks:[],typeName:v.ZodString,coerce:t?.coerce??!1,..._(t)});Ce=class t extends x{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==p.number){let o=this._getOrReturnCtx(e);return m(o,{code:d.invalid_type,expected:p.number,received:o.parsedType}),w}let n,s=new I;for(let o of this._def.checks)o.kind==="int"?S.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),m(n,{code:d.invalid_type,expected:"integer",received:"float",message:o.message}),s.dirty()):o.kind==="min"?(o.inclusive?e.data<o.value:e.data<=o.value)&&(n=this._getOrReturnCtx(e,n),m(n,{code:d.too_small,minimum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),s.dirty()):o.kind==="max"?(o.inclusive?e.data>o.value:e.data>=o.value)&&(n=this._getOrReturnCtx(e,n),m(n,{code:d.too_big,maximum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),s.dirty()):o.kind==="multipleOf"?wa(e.data,o.value)!==0&&(n=this._getOrReturnCtx(e,n),m(n,{code:d.not_multiple_of,multipleOf:o.value,message:o.message}),s.dirty()):o.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),m(n,{code:d.not_finite,message:o.message}),s.dirty()):S.assertNever(o);return{status:s.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,g.toString(r))}gt(e,r){return this.setLimit("min",e,!1,g.toString(r))}lte(e,r){return this.setLimit("max",e,!0,g.toString(r))}lt(e,r){return this.setLimit("max",e,!1,g.toString(r))}setLimit(e,r,n,s){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:g.toString(s)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:g.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:g.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:g.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:g.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:g.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:g.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:g.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:g.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:g.toString(e)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&S.isInteger(e.value))}get isFinite(){let e=null,r=null;for(let n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(r===null||n.value>r)&&(r=n.value):n.kind==="max"&&(e===null||n.value<e)&&(e=n.value)}return Number.isFinite(r)&&Number.isFinite(e)}};Ce.create=t=>new Ce({checks:[],typeName:v.ZodNumber,coerce:t?.coerce||!1,..._(t)});$e=class t extends x{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==p.bigint)return this._getInvalidInput(e);let n,s=new I;for(let o of this._def.checks)o.kind==="min"?(o.inclusive?e.data<o.value:e.data<=o.value)&&(n=this._getOrReturnCtx(e,n),m(n,{code:d.too_small,type:"bigint",minimum:o.value,inclusive:o.inclusive,message:o.message}),s.dirty()):o.kind==="max"?(o.inclusive?e.data>o.value:e.data>=o.value)&&(n=this._getOrReturnCtx(e,n),m(n,{code:d.too_big,type:"bigint",maximum:o.value,inclusive:o.inclusive,message:o.message}),s.dirty()):o.kind==="multipleOf"?e.data%o.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),m(n,{code:d.not_multiple_of,multipleOf:o.value,message:o.message}),s.dirty()):S.assertNever(o);return{status:s.value,value:e.data}}_getInvalidInput(e){let r=this._getOrReturnCtx(e);return m(r,{code:d.invalid_type,expected:p.bigint,received:r.parsedType}),w}gte(e,r){return this.setLimit("min",e,!0,g.toString(r))}gt(e,r){return this.setLimit("min",e,!1,g.toString(r))}lte(e,r){return this.setLimit("max",e,!0,g.toString(r))}lt(e,r){return this.setLimit("max",e,!1,g.toString(r))}setLimit(e,r,n,s){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:g.toString(s)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:g.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:g.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:g.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:g.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:g.toString(r)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};$e.create=t=>new $e({checks:[],typeName:v.ZodBigInt,coerce:t?.coerce??!1,..._(t)});Pe=class extends x{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==p.boolean){let n=this._getOrReturnCtx(e);return m(n,{code:d.invalid_type,expected:p.boolean,received:n.parsedType}),w}return M(e.data)}};Pe.create=t=>new Pe({typeName:v.ZodBoolean,coerce:t?.coerce||!1,..._(t)});Oe=class t extends x{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==p.date){let o=this._getOrReturnCtx(e);return m(o,{code:d.invalid_type,expected:p.date,received:o.parsedType}),w}if(Number.isNaN(e.data.getTime())){let o=this._getOrReturnCtx(e);return m(o,{code:d.invalid_date}),w}let n=new I,s;for(let o of this._def.checks)o.kind==="min"?e.data.getTime()<o.value&&(s=this._getOrReturnCtx(e,s),m(s,{code:d.too_small,message:o.message,inclusive:!0,exact:!1,minimum:o.value,type:"date"}),n.dirty()):o.kind==="max"?e.data.getTime()>o.value&&(s=this._getOrReturnCtx(e,s),m(s,{code:d.too_big,message:o.message,inclusive:!0,exact:!1,maximum:o.value,type:"date"}),n.dirty()):S.assertNever(o);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}min(e,r){return this._addCheck({kind:"min",value:e.getTime(),message:g.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:g.toString(r)})}get minDate(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e!=null?new Date(e):null}};Oe.create=t=>new Oe({checks:[],coerce:t?.coerce||!1,typeName:v.ZodDate,..._(t)});et=class extends x{_parse(e){if(this._getType(e)!==p.symbol){let n=this._getOrReturnCtx(e);return m(n,{code:d.invalid_type,expected:p.symbol,received:n.parsedType}),w}return M(e.data)}};et.create=t=>new et({typeName:v.ZodSymbol,..._(t)});Ie=class extends x{_parse(e){if(this._getType(e)!==p.undefined){let n=this._getOrReturnCtx(e);return m(n,{code:d.invalid_type,expected:p.undefined,received:n.parsedType}),w}return M(e.data)}};Ie.create=t=>new Ie({typeName:v.ZodUndefined,..._(t)});De=class extends x{_parse(e){if(this._getType(e)!==p.null){let n=this._getOrReturnCtx(e);return m(n,{code:d.invalid_type,expected:p.null,received:n.parsedType}),w}return M(e.data)}};De.create=t=>new De({typeName:v.ZodNull,..._(t)});ve=class extends x{constructor(){super(...arguments),this._any=!0}_parse(e){return M(e.data)}};ve.create=t=>new ve({typeName:v.ZodAny,..._(t)});fe=class extends x{constructor(){super(...arguments),this._unknown=!0}_parse(e){return M(e.data)}};fe.create=t=>new fe({typeName:v.ZodUnknown,..._(t)});re=class extends x{_parse(e){let r=this._getOrReturnCtx(e);return m(r,{code:d.invalid_type,expected:p.never,received:r.parsedType}),w}};re.create=t=>new re({typeName:v.ZodNever,..._(t)});tt=class extends x{_parse(e){if(this._getType(e)!==p.undefined){let n=this._getOrReturnCtx(e);return m(n,{code:d.invalid_type,expected:p.void,received:n.parsedType}),w}return M(e.data)}};tt.create=t=>new tt({typeName:v.ZodVoid,..._(t)});me=class t extends x{_parse(e){let{ctx:r,status:n}=this._processInputParams(e),s=this._def;if(r.parsedType!==p.array)return m(r,{code:d.invalid_type,expected:p.array,received:r.parsedType}),w;if(s.exactLength!==null){let i=r.data.length>s.exactLength.value,a=r.data.length<s.exactLength.value;(i||a)&&(m(r,{code:i?d.too_big:d.too_small,minimum:a?s.exactLength.value:void 0,maximum:i?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),n.dirty())}if(s.minLength!==null&&r.data.length<s.minLength.value&&(m(r,{code:d.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),n.dirty()),s.maxLength!==null&&r.data.length>s.maxLength.value&&(m(r,{code:d.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((i,a)=>s.type._parseAsync(new Y(r,i,r.path,a)))).then(i=>I.mergeArray(n,i));let o=[...r.data].map((i,a)=>s.type._parseSync(new Y(r,i,r.path,a)));return I.mergeArray(n,o)}get element(){return this._def.type}min(e,r){return new t({...this._def,minLength:{value:e,message:g.toString(r)}})}max(e,r){return new t({...this._def,maxLength:{value:e,message:g.toString(r)}})}length(e,r){return new t({...this._def,exactLength:{value:e,message:g.toString(r)}})}nonempty(e){return this.min(1,e)}};me.create=(t,e)=>new me({type:t,minLength:null,maxLength:null,exactLength:null,typeName:v.ZodArray,..._(e)});j=class t extends x{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),r=S.objectKeys(e);return this._cached={shape:e,keys:r},this._cached}_parse(e){if(this._getType(e)!==p.object){let u=this._getOrReturnCtx(e);return m(u,{code:d.invalid_type,expected:p.object,received:u.parsedType}),w}let{status:n,ctx:s}=this._processInputParams(e),{shape:o,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof re&&this._def.unknownKeys==="strip"))for(let u in s.data)i.includes(u)||a.push(u);let c=[];for(let u of i){let l=o[u],h=s.data[u];c.push({key:{status:"valid",value:u},value:l._parse(new Y(s,h,s.path,u)),alwaysSet:u in s.data})}if(this._def.catchall instanceof re){let u=this._def.unknownKeys;if(u==="passthrough")for(let l of a)c.push({key:{status:"valid",value:l},value:{status:"valid",value:s.data[l]}});else if(u==="strict")a.length>0&&(m(s,{code:d.unrecognized_keys,keys:a}),n.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let u=this._def.catchall;for(let l of a){let h=s.data[l];c.push({key:{status:"valid",value:l},value:u._parse(new Y(s,h,s.path,l)),alwaysSet:l in s.data})}}return s.common.async?Promise.resolve().then(async()=>{let u=[];for(let l of c){let h=await l.key,b=await l.value;u.push({key:h,value:b,alwaysSet:l.alwaysSet})}return u}).then(u=>I.mergeObjectSync(n,u)):I.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(e){return g.errToObj,new t({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(r,n)=>{let s=this._def.errorMap?.(r,n).message??n.defaultError;return r.code==="unrecognized_keys"?{message:g.errToObj(e).message??s}:{message:s}}}:{}})}strip(){return new t({...this._def,unknownKeys:"strip"})}passthrough(){return new t({...this._def,unknownKeys:"passthrough"})}extend(e){return new t({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new t({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:v.ZodObject})}setKey(e,r){return this.augment({[e]:r})}catchall(e){return new t({...this._def,catchall:e})}pick(e){let r={};for(let n of S.objectKeys(e))e[n]&&this.shape[n]&&(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}omit(e){let r={};for(let n of S.objectKeys(this.shape))e[n]||(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}deepPartial(){return Qe(this)}partial(e){let r={};for(let n of S.objectKeys(this.shape)){let s=this.shape[n];e&&!e[n]?r[n]=s:r[n]=s.optional()}return new t({...this._def,shape:()=>r})}required(e){let r={};for(let n of S.objectKeys(this.shape))if(e&&!e[n])r[n]=this.shape[n];else{let o=this.shape[n];for(;o instanceof W;)o=o._def.innerType;r[n]=o}return new t({...this._def,shape:()=>r})}keyof(){return gs(S.objectKeys(this.shape))}};j.create=(t,e)=>new j({shape:()=>t,unknownKeys:"strip",catchall:re.create(),typeName:v.ZodObject,..._(e)});j.strictCreate=(t,e)=>new j({shape:()=>t,unknownKeys:"strict",catchall:re.create(),typeName:v.ZodObject,..._(e)});j.lazycreate=(t,e)=>new j({shape:t,unknownKeys:"strip",catchall:re.create(),typeName:v.ZodObject,..._(e)});Ne=class extends x{_parse(e){let{ctx:r}=this._processInputParams(e),n=this._def.options;function s(o){for(let a of o)if(a.result.status==="valid")return a.result;for(let a of o)if(a.result.status==="dirty")return r.common.issues.push(...a.ctx.common.issues),a.result;let i=o.map(a=>new F(a.ctx.common.issues));return m(r,{code:d.invalid_union,unionErrors:i}),w}if(r.common.async)return Promise.all(n.map(async o=>{let i={...r,common:{...r.common,issues:[]},parent:null};return{result:await o._parseAsync({data:r.data,path:r.path,parent:i}),ctx:i}})).then(s);{let o,i=[];for(let c of n){let u={...r,common:{...r.common,issues:[]},parent:null},l=c._parseSync({data:r.data,path:r.path,parent:u});if(l.status==="valid")return l;l.status==="dirty"&&!o&&(o={result:l,ctx:u}),u.common.issues.length&&i.push(u.common.issues)}if(o)return r.common.issues.push(...o.ctx.common.issues),o.result;let a=i.map(c=>new F(c));return m(r,{code:d.invalid_union,unionErrors:a}),w}}get options(){return this._def.options}};Ne.create=(t,e)=>new Ne({options:t,typeName:v.ZodUnion,..._(e)});de=t=>t instanceof Le?de(t.schema):t instanceof q?de(t.innerType()):t instanceof Fe?[t.value]:t instanceof je?t.options:t instanceof ze?S.objectValues(t.enum):t instanceof Ue?de(t._def.innerType):t instanceof Ie?[void 0]:t instanceof De?[null]:t instanceof W?[void 0,...de(t.unwrap())]:t instanceof ce?[null,...de(t.unwrap())]:t instanceof vt||t instanceof He?de(t.unwrap()):t instanceof Ze?de(t._def.innerType):[],Yt=class t extends x{_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==p.object)return m(r,{code:d.invalid_type,expected:p.object,received:r.parsedType}),w;let n=this.discriminator,s=r.data[n],o=this.optionsMap.get(s);return o?r.common.async?o._parseAsync({data:r.data,path:r.path,parent:r}):o._parseSync({data:r.data,path:r.path,parent:r}):(m(r,{code:d.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),w)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,r,n){let s=new Map;for(let o of r){let i=de(o.shape[e]);if(!i.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let a of i){if(s.has(a))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(a)}`);s.set(a,o)}}return new t({typeName:v.ZodDiscriminatedUnion,discriminator:e,options:r,optionsMap:s,..._(n)})}};Me=class extends x{_parse(e){let{status:r,ctx:n}=this._processInputParams(e),s=(o,i)=>{if(Jt(o)||Jt(i))return w;let a=Br(o.value,i.value);return a.valid?((Wt(o)||Wt(i))&&r.dirty(),{status:r.value,value:a.data}):(m(n,{code:d.invalid_intersection_types}),w)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([o,i])=>s(o,i)):s(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};Me.create=(t,e,r)=>new Me({left:t,right:e,typeName:v.ZodIntersection,..._(r)});ae=class t extends x{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==p.array)return m(n,{code:d.invalid_type,expected:p.array,received:n.parsedType}),w;if(n.data.length<this._def.items.length)return m(n,{code:d.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),w;!this._def.rest&&n.data.length>this._def.items.length&&(m(n,{code:d.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());let o=[...n.data].map((i,a)=>{let c=this._def.items[a]||this._def.rest;return c?c._parse(new Y(n,i,n.path,a)):null}).filter(i=>!!i);return n.common.async?Promise.all(o).then(i=>I.mergeArray(r,i)):I.mergeArray(r,o)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};ae.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new ae({items:t,typeName:v.ZodTuple,rest:null,..._(e)})};qt=class t extends x{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==p.object)return m(n,{code:d.invalid_type,expected:p.object,received:n.parsedType}),w;let s=[],o=this._def.keyType,i=this._def.valueType;for(let a in n.data)s.push({key:o._parse(new Y(n,a,n.path,a)),value:i._parse(new Y(n,n.data[a],n.path,a)),alwaysSet:a in n.data});return n.common.async?I.mergeObjectAsync(r,s):I.mergeObjectSync(r,s)}get element(){return this._def.valueType}static create(e,r,n){return r instanceof x?new t({keyType:e,valueType:r,typeName:v.ZodRecord,..._(n)}):new t({keyType:we.create(),valueType:e,typeName:v.ZodRecord,..._(r)})}},rt=class extends x{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==p.map)return m(n,{code:d.invalid_type,expected:p.map,received:n.parsedType}),w;let s=this._def.keyType,o=this._def.valueType,i=[...n.data.entries()].map(([a,c],u)=>({key:s._parse(new Y(n,a,n.path,[u,"key"])),value:o._parse(new Y(n,c,n.path,[u,"value"]))}));if(n.common.async){let a=new Map;return Promise.resolve().then(async()=>{for(let c of i){let u=await c.key,l=await c.value;if(u.status==="aborted"||l.status==="aborted")return w;(u.status==="dirty"||l.status==="dirty")&&r.dirty(),a.set(u.value,l.value)}return{status:r.value,value:a}})}else{let a=new Map;for(let c of i){let u=c.key,l=c.value;if(u.status==="aborted"||l.status==="aborted")return w;(u.status==="dirty"||l.status==="dirty")&&r.dirty(),a.set(u.value,l.value)}return{status:r.value,value:a}}}};rt.create=(t,e,r)=>new rt({valueType:e,keyType:t,typeName:v.ZodMap,..._(r)});nt=class t extends x{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==p.set)return m(n,{code:d.invalid_type,expected:p.set,received:n.parsedType}),w;let s=this._def;s.minSize!==null&&n.data.size<s.minSize.value&&(m(n,{code:d.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),r.dirty()),s.maxSize!==null&&n.data.size>s.maxSize.value&&(m(n,{code:d.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),r.dirty());let o=this._def.valueType;function i(c){let u=new Set;for(let l of c){if(l.status==="aborted")return w;l.status==="dirty"&&r.dirty(),u.add(l.value)}return{status:r.value,value:u}}let a=[...n.data.values()].map((c,u)=>o._parse(new Y(n,c,n.path,u)));return n.common.async?Promise.all(a).then(c=>i(c)):i(a)}min(e,r){return new t({...this._def,minSize:{value:e,message:g.toString(r)}})}max(e,r){return new t({...this._def,maxSize:{value:e,message:g.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}};nt.create=(t,e)=>new nt({valueType:t,minSize:null,maxSize:null,typeName:v.ZodSet,..._(e)});Xt=class t extends x{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==p.function)return m(r,{code:d.invalid_type,expected:p.function,received:r.parsedType}),w;function n(a,c){return wt({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,qe(),le].filter(u=>!!u),issueData:{code:d.invalid_arguments,argumentsError:c}})}function s(a,c){return wt({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,qe(),le].filter(u=>!!u),issueData:{code:d.invalid_return_type,returnTypeError:c}})}let o={errorMap:r.common.contextualErrorMap},i=r.data;if(this._def.returns instanceof be){let a=this;return M(async function(...c){let u=new F([]),l=await a._def.args.parseAsync(c,o).catch(k=>{throw u.addIssue(n(c,k)),u}),h=await Reflect.apply(i,this,l);return await a._def.returns._def.type.parseAsync(h,o).catch(k=>{throw u.addIssue(s(h,k)),u})})}else{let a=this;return M(function(...c){let u=a._def.args.safeParse(c,o);if(!u.success)throw new F([n(c,u.error)]);let l=Reflect.apply(i,this,u.data),h=a._def.returns.safeParse(l,o);if(!h.success)throw new F([s(l,h.error)]);return h.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new t({...this._def,args:ae.create(e).rest(fe.create())})}returns(e){return new t({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,r,n){return new t({args:e||ae.create([]).rest(fe.create()),returns:r||fe.create(),typeName:v.ZodFunction,..._(n)})}},Le=class extends x{get schema(){return this._def.getter()}_parse(e){let{ctx:r}=this._processInputParams(e);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}};Le.create=(t,e)=>new Le({getter:t,typeName:v.ZodLazy,..._(e)});Fe=class extends x{_parse(e){if(e.data!==this._def.value){let r=this._getOrReturnCtx(e);return m(r,{received:r.data,code:d.invalid_literal,expected:this._def.value}),w}return{status:"valid",value:e.data}}get value(){return this._def.value}};Fe.create=(t,e)=>new Fe({value:t,typeName:v.ZodLiteral,..._(e)});je=class t extends x{_parse(e){if(typeof e.data!="string"){let r=this._getOrReturnCtx(e),n=this._def.values;return m(r,{expected:S.joinValues(n),received:r.parsedType,code:d.invalid_type}),w}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let r=this._getOrReturnCtx(e),n=this._def.values;return m(r,{received:r.data,code:d.invalid_enum_value,options:n}),w}return M(e.data)}get options(){return this._def.values}get enum(){let e={};for(let r of this._def.values)e[r]=r;return e}get Values(){let e={};for(let r of this._def.values)e[r]=r;return e}get Enum(){let e={};for(let r of this._def.values)e[r]=r;return e}extract(e,r=this._def){return t.create(e,{...this._def,...r})}exclude(e,r=this._def){return t.create(this.options.filter(n=>!e.includes(n)),{...this._def,...r})}};je.create=gs;ze=class extends x{_parse(e){let r=S.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==p.string&&n.parsedType!==p.number){let s=S.objectValues(r);return m(n,{expected:S.joinValues(s),received:n.parsedType,code:d.invalid_type}),w}if(this._cache||(this._cache=new Set(S.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let s=S.objectValues(r);return m(n,{received:n.data,code:d.invalid_enum_value,options:s}),w}return M(e.data)}get enum(){return this._def.values}};ze.create=(t,e)=>new ze({values:t,typeName:v.ZodNativeEnum,..._(e)});be=class extends x{unwrap(){return this._def.type}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==p.promise&&r.common.async===!1)return m(r,{code:d.invalid_type,expected:p.promise,received:r.parsedType}),w;let n=r.parsedType===p.promise?r.data:Promise.resolve(r.data);return M(n.then(s=>this._def.type.parseAsync(s,{path:r.path,errorMap:r.common.contextualErrorMap})))}};be.create=(t,e)=>new be({type:t,typeName:v.ZodPromise,..._(e)});q=class extends x{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===v.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:r,ctx:n}=this._processInputParams(e),s=this._def.effect||null,o={addIssue:i=>{m(n,i),i.fatal?r.abort():r.dirty()},get path(){return n.path}};if(o.addIssue=o.addIssue.bind(o),s.type==="preprocess"){let i=s.transform(n.data,o);if(n.common.async)return Promise.resolve(i).then(async a=>{if(r.value==="aborted")return w;let c=await this._def.schema._parseAsync({data:a,path:n.path,parent:n});return c.status==="aborted"?w:c.status==="dirty"?Re(c.value):r.value==="dirty"?Re(c.value):c});{if(r.value==="aborted")return w;let a=this._def.schema._parseSync({data:i,path:n.path,parent:n});return a.status==="aborted"?w:a.status==="dirty"?Re(a.value):r.value==="dirty"?Re(a.value):a}}if(s.type==="refinement"){let i=a=>{let c=s.refinement(a,o);if(n.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(n.common.async===!1){let a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?w:(a.status==="dirty"&&r.dirty(),i(a.value),{status:r.value,value:a.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(a=>a.status==="aborted"?w:(a.status==="dirty"&&r.dirty(),i(a.value).then(()=>({status:r.value,value:a.value}))))}if(s.type==="transform")if(n.common.async===!1){let i=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!ye(i))return w;let a=s.transform(i.value,o);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:a}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(i=>ye(i)?Promise.resolve(s.transform(i.value,o)).then(a=>({status:r.value,value:a})):w);S.assertNever(s)}};q.create=(t,e,r)=>new q({schema:t,typeName:v.ZodEffects,effect:e,..._(r)});q.createWithPreprocess=(t,e,r)=>new q({schema:e,effect:{type:"preprocess",transform:t},typeName:v.ZodEffects,..._(r)});W=class extends x{_parse(e){return this._getType(e)===p.undefined?M(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};W.create=(t,e)=>new W({innerType:t,typeName:v.ZodOptional,..._(e)});ce=class extends x{_parse(e){return this._getType(e)===p.null?M(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};ce.create=(t,e)=>new ce({innerType:t,typeName:v.ZodNullable,..._(e)});Ue=class extends x{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return r.parsedType===p.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};Ue.create=(t,e)=>new Ue({innerType:t,typeName:v.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,..._(e)});Ze=class extends x{_parse(e){let{ctx:r}=this._processInputParams(e),n={...r,common:{...r.common,issues:[]}},s=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return Xe(s)?s.then(o=>({status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new F(n.common.issues)},input:n.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new F(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};Ze.create=(t,e)=>new Ze({innerType:t,typeName:v.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,..._(e)});st=class extends x{_parse(e){if(this._getType(e)!==p.nan){let n=this._getOrReturnCtx(e);return m(n,{code:d.invalid_type,expected:p.nan,received:n.parsedType}),w}return{status:"valid",value:e.data}}};st.create=t=>new st({typeName:v.ZodNaN,..._(t)});va=Symbol("zod_brand"),vt=class extends x{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return this._def.type._parse({data:n,path:r.path,parent:r})}unwrap(){return this._def.type}},bt=class t extends x{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let o=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?w:o.status==="dirty"?(r.dirty(),Re(o.value)):this._def.out._parseAsync({data:o.value,path:n.path,parent:n})})();{let s=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?w:s.status==="dirty"?(r.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:n.path,parent:n})}}static create(e,r){return new t({in:e,out:r,typeName:v.ZodPipeline})}},He=class extends x{_parse(e){let r=this._def.innerType._parse(e),n=s=>(ye(s)&&(s.value=Object.freeze(s.value)),s);return Xe(r)?r.then(s=>n(s)):n(r)}unwrap(){return this._def.innerType}};He.create=(t,e)=>new He({innerType:t,typeName:v.ZodReadonly,..._(e)});ba={object:j.lazycreate};(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(v||(v={}));ka=(t,e={message:`Input not instance of ${t.name}`})=>ys(r=>r instanceof t,e),ws=we.create,vs=Ce.create,_a=st.create,xa=$e.create,bs=Pe.create,Sa=Oe.create,Ea=et.create,Ta=Ie.create,Aa=De.create,Ra=ve.create,Ca=fe.create,$a=re.create,Pa=tt.create,Oa=me.create,Ia=j.create,Da=j.strictCreate,Na=Ne.create,Ma=Yt.create,La=Me.create,Fa=ae.create,ja=qt.create,za=rt.create,Ua=nt.create,Za=Xt.create,Ha=Le.create,Ba=Fe.create,Va=je.create,Ka=ze.create,Ga=be.create,Ja=q.create,Wa=W.create,Ya=ce.create,qa=q.createWithPreprocess,Xa=bt.create,Qa=()=>ws().optional(),ec=()=>vs().optional(),tc=()=>bs().optional(),rc={string:(t=>we.create({...t,coerce:!0})),number:(t=>Ce.create({...t,coerce:!0})),boolean:(t=>Pe.create({...t,coerce:!0})),bigint:(t=>$e.create({...t,coerce:!0})),date:(t=>Oe.create({...t,coerce:!0}))},nc=w});var f={};te(f,{BRAND:()=>va,DIRTY:()=>Re,EMPTY_PATH:()=>qi,INVALID:()=>w,NEVER:()=>nc,OK:()=>M,ParseStatus:()=>I,Schema:()=>x,ZodAny:()=>ve,ZodArray:()=>me,ZodBigInt:()=>$e,ZodBoolean:()=>Pe,ZodBranded:()=>vt,ZodCatch:()=>Ze,ZodDate:()=>Oe,ZodDefault:()=>Ue,ZodDiscriminatedUnion:()=>Yt,ZodEffects:()=>q,ZodEnum:()=>je,ZodError:()=>F,ZodFirstPartyTypeKind:()=>v,ZodFunction:()=>Xt,ZodIntersection:()=>Me,ZodIssueCode:()=>d,ZodLazy:()=>Le,ZodLiteral:()=>Fe,ZodMap:()=>rt,ZodNaN:()=>st,ZodNativeEnum:()=>ze,ZodNever:()=>re,ZodNull:()=>De,ZodNullable:()=>ce,ZodNumber:()=>Ce,ZodObject:()=>j,ZodOptional:()=>W,ZodParsedType:()=>p,ZodPipeline:()=>bt,ZodPromise:()=>be,ZodReadonly:()=>He,ZodRecord:()=>qt,ZodSchema:()=>x,ZodSet:()=>nt,ZodString:()=>we,ZodSymbol:()=>et,ZodTransformer:()=>q,ZodTuple:()=>ae,ZodType:()=>x,ZodUndefined:()=>Ie,ZodUnion:()=>Ne,ZodUnknown:()=>fe,ZodVoid:()=>tt,addIssueToContext:()=>m,any:()=>Ra,array:()=>Oa,bigint:()=>xa,boolean:()=>bs,coerce:()=>rc,custom:()=>ys,date:()=>Sa,datetimeRegex:()=>hs,defaultErrorMap:()=>le,discriminatedUnion:()=>Ma,effect:()=>Ja,enum:()=>Va,function:()=>Za,getErrorMap:()=>qe,getParsedType:()=>ie,instanceof:()=>ka,intersection:()=>La,isAborted:()=>Jt,isAsync:()=>Xe,isDirty:()=>Wt,isValid:()=>ye,late:()=>ba,lazy:()=>Ha,literal:()=>Ba,makeIssue:()=>wt,map:()=>za,nan:()=>_a,nativeEnum:()=>Ka,never:()=>$a,null:()=>Aa,nullable:()=>Ya,number:()=>vs,object:()=>Ia,objectUtil:()=>zr,oboolean:()=>tc,onumber:()=>ec,optional:()=>Wa,ostring:()=>Qa,pipeline:()=>Xa,preprocess:()=>qa,promise:()=>Ga,quotelessJson:()=>Ji,record:()=>ja,set:()=>Ua,setErrorMap:()=>Yi,strictObject:()=>Da,string:()=>ws,symbol:()=>Ea,transformer:()=>Ja,tuple:()=>Fa,undefined:()=>Ta,union:()=>Na,unknown:()=>Ca,util:()=>S,void:()=>Pa});var Vr=E(()=>{Gt();Zr();us();yt();ks();Kt()});var ot=E(()=>{Vr();Vr()});import{createHash as sc}from"node:crypto";function ke(t){let e=_s.get(t);return e||(e=sc("sha256").update(`tkr:${t}`).digest("hex").slice(0,16),_s.set(t,e)),e}var oc,ic,it,_s,kt=E(()=>{"use strict";ot();oc=f.enum(["normal","compact","minimal"]),ic=f.enum(["off","light","balanced","max"]),it=f.object({enabled:f.boolean().default(!0),telemetryOptIn:f.boolean().default(!0),outputVerbosity:oc.default("compact"),reducer:ic.default("off"),filters:f.object({enableAll:f.boolean().default(!0),disabled:f.array(f.string().max(64)).max(100).default([])}).default({enableAll:!0,disabled:[]})}),_s=new Map});var Ss={};te(Ss,{bundleRefreshFile:()=>_t,claudeCommandFile:()=>xe,claudeCommandsDir:()=>tr,contentCacheDir:()=>St,contentCacheFile:()=>Qt,enrollCooldownFile:()=>Kr,installIdFile:()=>at,managedCommandsFile:()=>er,skillFile:()=>_e,skillsDir:()=>xt,stateFile:()=>ac,tokmizerHome:()=>y});import xs from"node:os";import{join as X}from"node:path";function y(){return process.env.TOKMIZER_HOME||X(xs.homedir(),".tokmizer")}function ac(){return X(y(),"state.json")}function at(){return X(y(),"install-id")}function Kr(){return X(y(),"enroll-cooldown")}function _t(){return X(y(),"bundle-refresh.json")}function xt(){return X(y(),"skills")}function _e(t){return X(xt(),`${t}.md`)}function St(){return X(y(),"content-cache")}function Qt(t){return X(St(),t)}function er(){return X(y(),"managed-commands.json")}function tr(){return process.env.TOKMIZER_CLAUDE_COMMANDS_DIR||X(xs.homedir(),".claude","commands")}function xe(t){return X(tr(),`${t}.md`)}var D=E(()=>{"use strict"});import ct from"node:os";import{createHash as cc,randomUUID as uc}from"node:crypto";import{readFile as Es,writeFile as Ts,mkdir as lc}from"node:fs/promises";async function rr(){try{let r=(await Es(at(),"utf8")).trim();if(/^[0-9a-f-]{36}$/i.test(r))return r}catch{}await lc(y(),{recursive:!0});let t=uc();try{return await Ts(at(),t,{mode:384,flag:"wx"}),t}catch{try{let e=(await Es(at(),"utf8")).trim();if(/^[0-9a-f-]{36}$/i.test(e))return e}catch{}return await Ts(at(),t,{mode:384}),t}}function Gr(t){return cc("sha256").update(t).digest("hex")}function dc(){let t=ct.networkInterfaces();for(let e of Object.keys(t))for(let r of t[e]??[])if(!r.internal&&r.mac&&r.mac!=="00:00:00:00:00:00")return r.mac;return"no-mac"}async function Q(){let t=await rr(),e=ct.hostname(),r=ct.platform(),n=ct.release(),s=ct.cpus(),o=s[0]?.model??"unknown",i=s.length,a=Gr(dc()),c=Gr(ct.userInfo().username),u=[e,r,n,o,String(i),a,c,t].join("|");return{fingerprint:Gr(u),installId:t,hostname:e,os:r,osVersion:n,cpuModel:o,cpuCores:i,macHash:a,usernameHash:c}}var Be=E(()=>{"use strict";D()});import{join as Jr}from"node:path";import{mkdir as fc,readFile as mc,writeFile as pc,unlink as As,rename as hc}from"node:fs/promises";function Et(){try{let t=Intl.DateTimeFormat().resolvedOptions().timeZone;return t&&t.length>0?t:"Etc/UTC"}catch{return"Etc/UTC"}}function Yr(t){return t?.dir??y()}async function T(t){let e=Yr(t);try{let r=await mc(Jr(e,Wr),"utf8"),n=JSON.parse(r),s=n.timeZone;return{...n,lastSettingsRevision:n.lastSettingsRevision??0,get timeZone(){return s??=Et()},bonusActive:n.bonusActive??!1,...n.bonusResetAt!==void 0?{bonusResetAt:n.bonusResetAt}:{}}}catch{return null}}async function nr(t,e){let r=Yr(e);await fc(r,{recursive:!0}),t.installedAt==null&&(t.installedAt=Math.floor(Date.now()/1e3));let n=Jr(r,Wr),s=`${n}.tmp-${process.pid}-${process.hrtime.bigint()}`;await pc(s,JSON.stringify(t,null,2),{mode:384});try{await hc(s,n)}catch(o){try{await As(s)}catch{}throw o}}async function sr(t){let e=Yr(t);try{await As(Jr(e,Wr))}catch{return}}var Wr,pe=E(()=>{"use strict";D();Wr="state.json"});import{createRequire as gc}from"node:module";function wc(){for(let t of["../package.json","../../package.json"])try{let e=yc(t).version;if(typeof e=="string"&&e)return e}catch{}return"0.0.0"}function Se(t,e){if(!t||!e)return!1;let r=t.split(".").map(s=>parseInt(s,10)),n=e.split(".").map(s=>parseInt(s,10));for(let s=0;s<3;s+=1){let o=r[s]??0,i=n[s]??0;if(Number.isNaN(o)||Number.isNaN(i))return!1;if(o<i)return!0;if(o>i)return!1}return!1}var yc,V,ut=E(()=>{"use strict";yc=gc(import.meta.url);V=wc()});var Rs,Cs=E(()=>{"use strict";Rs=`-----BEGIN PUBLIC KEY-----
|
|
4
4
|
MCowBQYDK2VwAyEAj/kMlXlhTIGHRKxOKMuGFa1S1ybxxwgdYcAE0YM9fgU=
|
|
5
5
|
-----END PUBLIC KEY-----
|
|
6
|
-
`});import{createHmac as
|
|
7
|
-
`)}function
|
|
8
|
-
`,
|
|
9
|
-
`)}catch{}}function
|
|
10
|
-
`).filter(a=>a.trim()!==""),s=[],o=0;for(let a=n.length-1;a>=0;a-=1){let c=n[a],u=Buffer.byteLength(c)+1;if(o+u>r)break;s.push(c),o+=u}s.reverse();let i=`${t}.tmp-${process.pid}`;
|
|
6
|
+
`});import{createHmac as vc,createPublicKey as bc,verify as kc}from"node:crypto";function Tt(){return((process.env.TOKMIZER_DEV==="1"?process.env.TOKMIZER_RESP_SIGNING_PUBLIC_KEY_PEM:void 0)??Rs).replace(/\\n/g,`
|
|
7
|
+
`)}function xc(t,e,r,n){try{let s=bc({key:n,format:"pem"});return kc(null,Buffer.from(`${e}.${t}`,"utf8"),s,Buffer.from(r,"base64url"))}catch{return!1}}async function Te(t){let e=await t.text(),r=Tt(),n=t.headers?.get?.("x-tokmizer-resp-ts")??null;if(n!==null){let i=Number(n);if(!Number.isFinite(i)||Date.now()-i>_c)throw new Ee("http","stale server response (resp-ts outside freshness window)")}if(!r||!r.includes("BEGIN PUBLIC KEY"))throw new Ee("http","no signing public key configured; refusing to trust server response");let s=t.headers?.get?.("x-tokmizer-resp-sig")??null,o=Number(n);if(!s||n===null||!Number.isFinite(o))throw new Ee("http","missing server response signature");if(!xc(e,o,s,r))throw new Ee("http","invalid server response signature");return JSON.parse(e)}function Sc(t,e,r){return vc("sha256",r).update(`${e}.${t}`).digest("hex")}async function z(t,e,r,n){let s=Date.now(),o=r===void 0?"":JSON.stringify(r),i=n.signingSecret?Sc(o,s,n.signingSecret):"0".repeat(64),a={"content-type":"application/json","x-tokmizer-fingerprint":n.fingerprint,"x-tokmizer-install-id":n.installId,"x-tokmizer-sig":i,"x-tokmizer-ts":String(s),"x-tokmizer-plugin-version":V};n.bearer&&(a.authorization=`Bearer ${n.bearer}`);let c=n.timeoutMs??5e3,u=t!=="GET"&&t!=="DELETE",l={method:t,headers:a,signal:AbortSignal.timeout(c)};u&&(l.body=o);try{return await fetch(`${n.baseUrl}${e}`,l)}catch(h){let b=h.name;throw b==="TimeoutError"||b==="AbortError"?new Ee("timeout",`${t} ${e} timed out after ${c}ms`):new Ee("network",`${t} ${e} failed: ${h.message}`)}}var _c,Ee,Ve=E(()=>{"use strict";ut();Cs();_c=300*1e3;Ee=class extends Error{constructor(r,n,s){super(n);this.kind=r;this.status=s;this.name="TransportError"}kind;status}});import{readFile as qs,writeFile as Xs,mkdir as Qs,chmod as Hc,rm as $t,rename as eo,readdir as Bc}from"node:fs/promises";import{randomUUID as Vc}from"node:crypto";import{join as dt}from"node:path";import{setTimeout as Js}from"node:timers/promises";async function U(){try{let t=await qs(dt(y(),nn),"utf8"),e=JSON.parse(t);return it.parse({...Ws,...e})}catch{return Ws}}async function sn(t){await Qs(y(),{recursive:!0});let e=dt(y(),nn),r=`${e}.tmp-${process.pid}-${process.hrtime.bigint()}`;await Xs(r,JSON.stringify(t,null,2),{mode:384});try{await Hc(r,384),await eo(r,e)}catch(n){try{await $t(r,{force:!0})}catch{}throw n}}async function Ys(t){let e=[];for(let r of await Bc(t)){let n=/^([1-9]\d*)-[0-9a-f-]{36}\.json$/.exec(r);if(!n)continue;let s=dt(t,r);try{process.kill(Number(n[1]),0)}catch(o){let i=o.code;if(i==="ESRCH"){await $t(s,{force:!0});continue}if(i!=="EPERM")throw o}try{let o=JSON.parse(await qs(s,"utf8"));if(!Number.isSafeInteger(o)||o<0)throw new Error("Invalid local settings lock");e.push({id:r,ticket:o})}catch(o){if(o.code!=="ENOENT")throw o}}return e}async function to(t){let e=Kc.parse(t),r=dt(y(),"settings-cache-locks");await Qs(r,{recursive:!0,mode:448});let n=`${process.pid}-${Vc()}.json`,s=dt(r,n),o=`${s}.tmp`,i=performance.now()+3e3,a=async c=>{for(await Xs(o,String(c),{mode:384});;)try{await eo(o,s);return}catch(u){let l=u.code;if(process.platform!=="win32"||l!=="EPERM"&&l!=="EBUSY"||performance.now()>=i)throw u;await Js(10)}};try{await a(0);let c=Math.max(0,...(await Ys(r)).map(u=>u.ticket))+1;if(!Number.isSafeInteger(c))throw new Error("Invalid local settings lock");for(await a(c);;){if(!(await Ys(r)).some(l=>l.id!==n&&(l.ticket===0||l.ticket<c||l.ticket===c&&l.id<n))){let l=await U(),h=it.parse({...l,...e,filters:{...l.filters,...e.filters}});return await sn(h),h}if(performance.now()>=i)throw new Error("Timed out waiting for local settings lock after 3 seconds; another process may still be updating settings");await Js(10)}}finally{await Promise.all([$t(s,{force:!0}),$t(o,{force:!0})])}}async function ro(){try{await $t(dt(y(),nn),{force:!0})}catch{}}var nn,Ws,Kc,Pt=E(()=>{"use strict";kt();D();nn="settings-cache.json",Ws=it.parse({}),Kc=it.partial().extend({filters:it.shape.filters.removeDefault().partial().optional()})});var ur,on=E(()=>{"use strict";ot();ur=f.object({slug:f.string().min(1).max(64),description:f.string().max(255).optional(),match_command:f.string().min(1),priority:f.number().int().default(50),strip_ansi:f.boolean().default(!1),strip_lines_matching:f.array(f.string()).default([]),keep_failures:f.boolean().default(!1),fold_passing:f.boolean().default(!1),fold_passing_threshold:f.number().int().positive().max(1e3).optional(),mask_abs_paths:f.boolean().default(!1),preserve_exact:f.boolean().default(!1),truncate_lines_at:f.number().int().positive().max(1e4).optional(),max_lines:f.number().int().positive().max(1e5).optional(),scale_with_level:f.boolean().default(!0),transform:f.string().max(64).optional(),on_empty:f.string().max(255).optional()})});function an(t){return JSON.stringify(t)+lr}function*io(t){let e=0;for(;;){let r=t.indexOf(lr,e);if(r<0)return;yield t.slice(e,r),e=r+1}}function Ot(){return`${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}var Yc,qc,Xc,Qc,xm,Sm,Em,oo,lr,Tm,ao=E(()=>{"use strict";ot();on();Yc=f.object({id:f.string().min(1).max(64),op:f.literal("filter"),cmd:f.string().min(1).max(2048),plan:f.enum(["trial","smart","pro"]),allowed:f.array(f.string().min(1).max(64)).max(512).optional(),installId:f.string().min(1).max(64).optional()}),qc=f.object({id:f.string().min(1).max(64),op:f.literal("ping")}),Xc=f.object({id:f.string().min(1).max(64),op:f.literal("shutdown"),installId:f.string().min(1).max(64)}),Qc=f.object({id:f.string().min(1).max(64),op:f.literal("reload"),installId:f.string().min(1).max(64).optional()}),xm=f.discriminatedUnion("op",[Yc,qc,Xc,Qc]),Sm=f.object({id:f.string(),ok:f.literal(!0),data:f.unknown()}),Em=f.object({id:f.string(),ok:f.literal(!1),err:f.string(),retryAfterMs:f.number().int().nonnegative().optional()}),oo=f.object({filter:ur.nullable(),cacheHit:f.boolean().optional()}),lr=`
|
|
8
|
+
`,Tm=64*1024});var lo={};te(lo,{IDLE_TIMEOUT_MS:()=>lu,PARENT_WATCH_INTERVAL_MS:()=>uu,cleanupStaleSocket:()=>dr,isParentAlive:()=>du,socketPath:()=>ft});import eu from"node:os";import{join as It}from"node:path";import{existsSync as tu,statSync as ru,lstatSync as co,unlinkSync as nu,mkdirSync as su,chmodSync as ou}from"node:fs";import{createHash as iu}from"node:crypto";function au(t){let e=iu("sha256").update(y()).digest("hex").slice(0,8),r=It(eu.tmpdir(),`tkr-${t}-${e}`),n=It(r,"d.sock");if(Buffer.byteLength(n)>cn)throw new Error("Temporary directory path is too long for IPC");return uo(r,t),n}function cu(t,e){try{let r=co(t);return r.isDirectory()&&r.uid===e&&(r.mode&63)===0}catch{return!1}}function uo(t,e){su(t,{recursive:!0,mode:448});let r=co(t);if(!r.isDirectory()||r.uid!==e)throw new Error("Unsafe IPC directory");ou(t,448)}function ft(){if(process.platform==="win32")return{path:`\\\\.\\pipe\\tokmizer-${process.env.USERNAME??"tokmizer"}`,isPipe:!0};let t=typeof process.getuid=="function"?process.getuid():0,e=process.env.XDG_RUNTIME_DIR;if(e&&cu(e,t)){let s=It(e,`tokmizer-${t}.sock`);if(Buffer.byteLength(s)<=cn)return{path:s,isPipe:!1}}let r=It(y(),"run"),n=It(r,"daemon.sock");return Buffer.byteLength(n)>cn?{path:au(t),isPipe:!1}:(uo(r,t),{path:n,isPipe:!1})}async function dr(){let{path:t,isPipe:e}=ft();if(e||!tu(t))return;try{if(!ru(t).isSocket())return}catch{return}let r=await import("node:net");if(!await new Promise(s=>{let o=r.createConnection(t),i=a=>{o.removeAllListeners();try{o.destroy()}catch{}s(a)};o.once("connect",()=>i(!0)),o.once("error",a=>{let c=a.code;i(c!=="ECONNREFUSED"&&c!=="ENOENT")}),setTimeout(()=>i(!0),250)}))try{nu(t)}catch{}}function du(){let t=process.ppid;if(!t||t===1)return!1;try{return process.kill(t,0),!0}catch{return!1}}var cn,uu,lu,un=E(()=>{"use strict";D();cn=100;uu=3e4,lu=5*6e4});var mt={};te(mt,{connectDaemon:()=>yo,shutdownDaemon:()=>go});import{createConnection as fu}from"node:net";import{spawn as mu}from"node:child_process";import{existsSync as po,openSync as ln,closeSync as fo,unlinkSync as fn,writeFileSync as mn,mkdirSync as pn,readFileSync as pu,appendFileSync as hu,rmSync as gu,statSync as yu}from"node:fs";import{dirname as wu,join as hn}from"node:path";import{fileURLToPath as vu}from"node:url";function gn(){return hn(y(),"daemon.spawn.fail")}function yn(){return hn(y(),"daemon.log")}function xu(){try{let t=Number(pu(gn(),"utf8"));return Number.isFinite(t)&&Date.now()-t<ku}catch{return!1}}function Su(t){try{pn(y(),{recursive:!0});let e=yn();try{yu(e).size>_u&&fn(e)}catch{}hu(e,`${new Date().toISOString()} ${t}
|
|
9
|
+
`)}catch{}}function Eu(t){try{pn(y(),{recursive:!0}),mn(gn(),String(Date.now()))}catch{}Su(`spawn failed: ${t.message}`)}function Tu(){try{gu(gn(),{force:!0})}catch{}}async function fr(t,e){return new Promise((r,n)=>{let s=fu(t),o=a=>{if(s.removeAllListeners("connect"),s.removeAllListeners("error"),clearTimeout(i),a){try{s.destroy()}catch{}n(a)}else r(s)},i=setTimeout(()=>o(new Error("connect timeout")),e);s.once("connect",()=>o(null)),s.once("error",a=>o(a))})}function Au(){return process.env.TOKMIZER_DAEMON_BIN?process.env.TOKMIZER_DAEMON_BIN:vu(new URL("../bin/tkr-daemon.js",import.meta.url))}async function dn(t,e=3e3){let r=Math.ceil(e/75),n=process.platform==="win32";for(let s=0;s<r;s++){if(n)try{return(await fr(t,75)).destroy(),!0}catch{}else if(po(t))return!0;await new Promise(o=>setTimeout(o,75))}return!1}async function Ru(t){let e=Au();if(!po(e))throw new Error(`tkr-daemon binary not found at ${e}`);let{path:r}=ft(),n=process.platform==="win32"?y():wu(r);try{pn(n,{recursive:!0})}catch{}let s=hn(n,"daemon.spawn.lock"),o=null;try{o=ln(s,"wx"),mn(o,String(process.pid))}catch(i){if(i.code==="EEXIST"){if(await dn(r,5e3))return;try{fn(s)}catch{}try{o=ln(s,"wx"),mn(o,String(process.pid))}catch(c){if(c.code==="EEXIST"){await dn(r,5e3);return}throw c}}else throw i}try{let i=null;try{i=ln(yn(),"a")}catch{}if(mu(process.execPath,[e],{detached:!0,stdio:["ignore","ignore",i??"ignore"],env:{...process.env,TOKMIZER_DAEMON_INSTALL_ID:t}}).unref(),i!==null)try{fo(i)}catch{}if(!await dn(r,3e3))throw new Error("tkr-daemon failed to bind socket within 3s")}finally{if(o!==null){try{fo(o)}catch{}try{fn(s)}catch{}}}}async function go(t={}){let{path:e}=t.socketPath?{path:t.socketPath}:ft(),r=await rr();try{let n=await fr(e,ho);n.write(an({id:Ot(),op:"shutdown",installId:r})),await new Promise(s=>setTimeout(s,150));try{n.destroy()}catch{}return!0}catch{return!1}}async function Cu(t,e){let r=Date.now()+e;for(;Date.now()<r;){try{(await fr(t,250)).destroy()}catch{return!0}await new Promise(n=>setTimeout(n,100))}return!1}async function yo(t={}){let{path:e}=t.socketPath?{path:t.socketPath}:ft(),r=await rr(),n=null,s=0,o=!1;for(;s<=mo;)try{n=await fr(e,ho),Tu();break}catch{if(s+=1,s>mo)throw new Error(`tkr-daemon unreachable at ${e}`);if(xu())throw new Error(`tkr-daemon spawn on cooldown (see ${yn()})`);await dr();try{await Ru(r),o=!0}catch(l){throw Eu(l),l}}if(!n)throw new Error("tkr-daemon: socket setup failed");let i=new Map,a="";n.setEncoding("utf8"),n.on("data",l=>{a+=l;let h=-1;for(let k=0;k<a.length;k++)a[k]===lr&&(h=k);if(h<0)return;let b=[];for(let k of io(a.slice(0,h+1)))b.push(k);a=a.slice(h+1);for(let k of b)if(k)try{let $=JSON.parse(k),O=i.get($.id);if(!O)continue;clearTimeout(O.timer),i.delete($.id),O.resolve($)}catch{}}),n.on("close",()=>{for(let l of i.values())clearTimeout(l.timer),l.reject(new Error("daemon socket closed"));i.clear()}),n.on("error",()=>{});function c(l){return new Promise((h,b)=>{if(n.destroyed||!n.writable){b(new Error("daemon socket closed"));return}let k=setTimeout(()=>{i.delete(l.id),b(new Error(`daemon request timeout (${l.op})`))},bu);i.set(l.id,{resolve:h,reject:b,timer:k}),n.write(an(l))})}let u={filter:async(l,h,b)=>{let k=await c({id:Ot(),op:"filter",cmd:l.slice(0,2048),plan:h,...b&&b.length>0?{allowed:b.slice(0,512)}:{},installId:r});if(!k.ok)return null;let $=oo.safeParse(k.data);return $.success?$.data.filter:null},ping:async()=>{let l=await c({id:Ot(),op:"ping"});if(!l.ok)throw new Error(l.err);return l.data},reload:async()=>{let l=await c({id:Ot(),op:"reload",installId:r});if(!l.ok)throw new Error(l.err);return l.data},close:()=>{try{n.destroy()}catch{}}};if(!t.skipVersionCheck&&!o){let l=!1;try{let h=await u.ping();if(h.version&&Se(V,h.version))throw new Error(`newer daemon ${h.version} already running`);l=h.version!==V}catch(h){throw u.close(),h}if(l){try{await go(t.socketPath?{socketPath:t.socketPath}:{})}catch{}u.close();let h=await Cu(e,2e3);if(await dr(),!h)throw new Error("stale daemon still running after shutdown request");return yo({...t,skipVersionCheck:!0})}}return u}var ho,bu,mo,ku,_u,pt=E(()=>{"use strict";ao();un();D();Be();ut();ho=500,bu=3e3,mo=1,ku=6e4,_u=256*1024});import{readFileSync as $u,renameSync as Pu,statSync as Ou,writeFileSync as Iu}from"node:fs";function wn(t,e,r){try{if(Ou(t).size<=e)return;let n=$u(t,"utf8").split(`
|
|
10
|
+
`).filter(a=>a.trim()!==""),s=[],o=0;for(let a=n.length-1;a>=0;a-=1){let c=n[a],u=Buffer.byteLength(c)+1;if(o+u>r)break;s.push(c),o+=u}s.reverse();let i=`${t}.tmp-${process.pid}`;Iu(i,s.length?`${s.join(`
|
|
11
11
|
`)}
|
|
12
|
-
`:"",{mode:384})
|
|
13
|
-
`),await
|
|
14
|
-
`,{mode:384}),
|
|
15
|
-
`,{mode:384}),
|
|
16
|
-
`).filter(s=>s.trim()),r=0,n=[];for(let s=e.length-1;s>=0;s--){let o=e[s]??"";if(r+=Buffer.byteLength(o,"utf8")+1,r>
|
|
12
|
+
`:"",{mode:384}),Pu(i,t)}catch{}}var vn=E(()=>{"use strict"});var _o={};te(_o,{codexHookCommand:()=>_n,codexHookInstalled:()=>bn,codexHooksFile:()=>ht,ensureCodexHook:()=>kn});import{readFile as Du,writeFile as Nu,rename as Mu,mkdir as Lu,copyFile as Fu}from"node:fs/promises";import{existsSync as wo,readFileSync as ju,accessSync as zu,constants as Uu}from"node:fs";import{join as mr}from"node:path";import Zu from"node:os";function ht(){return mr(process.env.CODEX_HOME||mr(Zu.homedir(),".codex"),"hooks.json")}function ko(t){return(t.hooks??[]).find(e=>typeof e.command=="string"&&e.command.includes(bo))}function bn(){try{return(JSON.parse(ju(ht(),"utf8")).hooks?.PreToolUse??[]).some(e=>ko(e)!=null)}catch{return!1}}async function kn(t){let e=ht(),r={},n=wo(e);if(n)try{if(r=JSON.parse(await Du(e,"utf8")),!r||typeof r!="object"||Array.isArray(r))return"error"}catch{return"error"}let s=r.hooks&&typeof r.hooks=="object"?r.hooks:{},o=Array.isArray(s.PreToolUse)?s.PreToolUse:[],i="added",a=o.map(ko).find(c=>c!=null);if(a){if(a.command===t)return"present";a.command=t,i="updated"}else o.push({matcher:"Bash",hooks:[{type:"command",command:t,timeout:10}]});s.PreToolUse=o,r.hooks=s;try{await Lu(mr(e,".."),{recursive:!0});let c=`${e}.tkr-bak`;n&&!wo(c)&&await Fu(e,c);let u=`${e}.tmp-${process.pid}`;await Nu(u,`${JSON.stringify(r,null,2)}
|
|
13
|
+
`),await Mu(u,e)}catch{return"error"}return i}function vo(t){return`'${t.replace(/'/g,"'\\''")}'`}function _n(t,e){if(process.platform!=="win32")for(let r of t.split(":")){if(!r||r.includes("node_modules"))continue;let n=mr(r,bo);try{return zu(n,Uu.X_OK),vo(n)}catch{}}return`node ${vo(e)}`}var bo,xn=E(()=>{"use strict";bo="tkr-codex-hook"});var pr={};te(pr,{autoUpdateEnabled:()=>Tn,claimSelfUpdateSlot:()=>$o,defaultDeps:()=>tl,maybeSpawnSelfUpdate:()=>nl,selfUpdate:()=>Qu,setAutoUpdate:()=>qu});import{spawn as Ao}from"node:child_process";import{accessSync as Hu,constants as Bu,existsSync as Dt,mkdirSync as Ro,readFileSync as Co,rmSync as Vu,writeFileSync as En,appendFileSync as Ku}from"node:fs";import{fileURLToPath as Gu}from"node:url";import{join as ne}from"node:path";import Ju from"node:os";function Tn(){return process.env.TOKMIZER_AUTO_UPDATE==="0"?!1:!Dt(Sn())}function qu(t){if(t){Vu(Sn(),{force:!0});return}Ro(y(),{recursive:!0,mode:448}),En(Sn(),String(Date.now()))}function $o(t=Date.now()){try{let e=Number(Co(Eo(),"utf8"));if(Number.isFinite(e)&&t-e<Wu)return!1}catch{}try{Ro(y(),{recursive:!0,mode:448}),En(Eo(),String(t))}catch{return!1}return!0}function Xu(t){try{let e=ne(y(),"self-update.log");Ku(e,`${new Date().toISOString()} ${t}
|
|
14
|
+
`,{mode:384}),wn(e,So,So/2)}catch{}}async function Qu(t){if(!Tn())return["disabled"];let e=t.latest;if(!e||!xo.test(e))return["no-version"];let r=[],n=[],s=(await t.run("npm",["root","-g"]).catch(()=>({code:1,stdout:""}))).stdout.trim(),o=s?t.npmVersion(s):void 0;if(o)if(!Se(o,e))n.push(o);else if(!t.writable(s))r.push("npm needs permission");else{let a=await t.run("npm",["i","-g",`@tokmizer/plugin@${e}`,"--no-audit","--no-fund"]).catch(()=>({code:1,stdout:""})),c=t.npmVersion(s);a.code===0&&c===e?(r.push(`npm ${o} -> ${e}`),n.push(e)):r.push(`npm failed (${o})`)}if(process.platform!=="win32"){let a=await t.run("brew",["list","--versions","tokmizer"]).catch(()=>({code:1,stdout:""})),c=a.code===0?a.stdout.trim().split(/\s+/)[1]:void 0;if(c&&xo.test(c))if(!Se(c,e))n.push(c);else{let u=await t.run("brew",["upgrade","tokmizer"],{...process.env,HOMEBREW_NO_INSTALL_CLEANUP:"1"}).catch(()=>({code:1,stdout:""}));u.code===0?(r.push(`brew ${c} -> ${e}`),n.push(e)):/untrusted tap/i.test(u.stderr??"")?r.push("brew tap not trusted: run brew trust norwelltw/tokmizer"):r.push(`brew failed (${c})`)}}if(r.some(a=>a.includes("->"))&&await t.run("tkr",["shims-refresh"]).catch(()=>({code:1,stdout:""})),n.some(a=>!Se(a,Yu))&&t.codexInstalled()&&!Dt(To())){let a=await t.ensureCodexHook(s).catch(()=>"error");if(a!=="error"){try{En(To(),String(Date.now()))}catch{}r.push(`codex hook ${a}`)}}for(let a of r)Xu(a);return r}function el(t,e,r){return new Promise(n=>{let s=Ao(t,e,{env:r??process.env,shell:process.platform==="win32",stdio:["ignore","pipe","pipe"],windowsHide:!0}),o="",i="";s.stdout?.on("data",c=>{o+=c.toString("utf8")}),s.stderr?.on("data",c=>{i.length<8192&&(i+=c.toString("utf8"))});let a=setTimeout(()=>s.kill("SIGTERM"),10*6e4);s.on("error",()=>{clearTimeout(a),n({code:127,stdout:""})}),s.on("close",c=>{clearTimeout(a),n({code:c??1,stdout:o,stderr:i})})})}function tl(t){return{latest:t,run:el,npmVersion:e=>{try{let r=JSON.parse(Co(ne(e,"@tokmizer","plugin","package.json"),"utf8")).version;return typeof r=="string"?r:void 0}catch{return}},writable:e=>{try{return Hu(e,Bu.W_OK),!0}catch{return!1}},codexInstalled:()=>Dt(process.env.CODEX_HOME||ne(Ju.homedir(),".codex")),ensureCodexHook:async e=>{let{ensureCodexHook:r,codexHookCommand:n}=await Promise.resolve().then(()=>(xn(),_o)),s=ne(e,"@tokmizer","plugin","dist","bin","tkr-codex-hook.js"),o=n(process.env.PATH??"",s);return o.startsWith("node ")&&!Dt(s)?"error":r(o)}}}function rl(){let t=Gu(new URL(".",import.meta.url));for(let e of[ne(t),ne(t,"..")])if(Dt(ne(e,"bin","tkr.js")))return e;return null}function nl(){try{if(!Tn())return;let t=rl();if(!t||!$o())return;let e=Ao(process.execPath,[ne(t,"bin","tkr.js"),"self-update"],{detached:!0,stdio:"ignore",windowsHide:!0,env:{...process.env,TOKMIZER_SELF_UPDATE_CHILD:"1"}});e.on("error",()=>{}),e.unref()}catch{}}var xo,Wu,Yu,So,Sn,Eo,To,hr=E(()=>{"use strict";D();ut();vn();xo=/^\d+\.\d+\.\d+$/,Wu=6*36e5,Yu="0.9.34",So=64*1024,Sn=()=>ne(y(),"auto-update-off"),Eo=()=>ne(y(),"self-update-last"),To=()=>ne(y(),"codex-hook-offered")});function Nt(t){let e=t;for(let[r,n]of sl)e=e.replace(r,n);return e}var sl,An=E(()=>{"use strict";sl=[[/(authorization\s*:\s*)([A-Za-z][A-Za-z0-9._-]*)\s+[^\s'"]+/gi,"$1$2 [REDACTED]"],[/(authorization\s*:\s*)[A-Za-z0-9._\-+/=]{8,}/gi,"$1[REDACTED]"],[/(bearer\s+)[A-Za-z0-9._\-+/=]{8,}/gi,"$1[REDACTED]"],[/((?:^|\s)(?:-b|--cookie)[=\s]+['"]?)[^\s'";=]+=[^\s'";]+(?:\s*;\s*[^\s'";=]+=[^\s'";]+)*/gi,"$1[REDACTED]"],[/((?:^|[\s'"])(?:Set-)?Cookie\s*:\s*)[^\s'";=]+=[^\s'";]+(?:\s*;\s*[^\s'";=]+=[^\s'";]+)*/gi,"$1[REDACTED]"],[/(--?(?:password|passwd|passphrase|apipass|pass|pwd|token|api[-_]?key|secret|bearer|cookie|jwt)(?:-[a-z0-9]+)*[=\s]+)\S+/gi,"$1[REDACTED]"],[/((?:^|\s)-b[=\s]?['"]?)[^\s'"=]+=[^\s'"]+/gi,"$1[REDACTED]"],[/((?:^|\s)(?:-u[=\s]?|(?:--user|-a)[=\s])['"]?[^\s:/'"]*:)(\/[^/\s'"][^\s'"]*|[^\s/'"0-9][^\s'"]*|[0-9][^\s'"]*[^\s'"0-9][^\s'"]*)/gi,"$1[REDACTED]"],[/((?:^|\s)(?:-u[=\s]?|(?:--user|-a)[=\s])['"]?[^\s:/'"]*[^\s:/'"0-9][^\s:/'"]*:)(?:\/[^/\s'"]|[^\s/'"])[^\s'"]*/gi,"$1[REDACTED]"],[/((?:^|\s)(?:-u[=\s]?|(?:--user|-a)[=\s])['"]?:)(?:\/[^/\s'"]|[^\s/'"])[^\s'"]*/gi,"$1[REDACTED]"],[/((?:[A-Za-z0-9]+-){0,8}(?:X-Api-Key|Private-Token|[A-Za-z0-9]+-(?:Token|Key|Auth|Secret))\s*:\s*)[^\s'"]+/gi,"$1[REDACTED]"],[/((?:^|[\s'"])(?:Set-)?Cookie\s*:\s*)[^\s'"]+/gi,"$1[REDACTED]"],[/(-i\s+)(\/[^\s]+|~\/[^\s]+|[A-Z]:\\[^\s]+)/g,"$1[REDACTED]"],[/([a-zA-Z][a-zA-Z0-9+.-]{0,31}:\/\/[^:/\s@]*:)[^\s@]+(@[^@/\s]+)/g,"$1[REDACTED]$2"],[/(AWS_(?:ACCESS_KEY_ID|SECRET_ACCESS_KEY|SESSION_TOKEN)\s*=\s*)\S+/g,"$1[REDACTED]"],[/(GOOGLE_APPLICATION_CREDENTIALS\s*=\s*)\S+/g,"$1[REDACTED]"],[/(AZURE_(?:CLIENT_SECRET|TENANT_ID|CLIENT_ID)\s*=\s*)\S+/g,"$1[REDACTED]"],[/(sk-(?:proj-)?[A-Za-z0-9_-]{20,})/g,"sk-[REDACTED]"],[/\b(OPENAI_API_KEY\s*=\s*)\S+/g,"$1[REDACTED]"],[/\b(ANTHROPIC_API_KEY\s*=\s*)\S+/g,"$1[REDACTED]"],[/(sk-ant-[A-Za-z0-9_-]{20,})/g,"sk-ant-[REDACTED]"],[/\b(GH(?:_|ITHUB_)?TOKEN\s*=\s*)\S+/g,"$1[REDACTED]"],[/\b(GITLAB_TOKEN\s*=\s*)\S+/g,"$1[REDACTED]"],[/\b(SLACK_(?:BOT_)?TOKEN\s*=\s*)\S+/g,"$1[REDACTED]"],[/(xox[bpsoa]-[A-Za-z0-9-]{10,})/g,"xox[REDACTED]"],[/(xapp-[A-Za-z0-9-]{10,})/g,"[REDACTED]"],[/(sk_(?:test|live)_[A-Za-z0-9]{16,})/g,"sk_[REDACTED]"],[/(gh[a-z])_[A-Za-z0-9]{20,}/g,"$1_[REDACTED]"],[/(github_pat)_[A-Za-z0-9_]{20,}/g,"$1_[REDACTED]"],[/(gl(?:pat|rt|soat|imt|dt|ft|agent|oas|cbt|ptt))-[A-Za-z0-9_-]{16,}/g,"$1-[REDACTED]"],[/(npm_[A-Za-z0-9_-]{20,})/g,"npm_[REDACTED]"],[/(?:AKIA|ASIA|AGPA|AIDA|AROA|ANPA)[0-9A-Z]{16,}/g,"[REDACTED_AWS_KEY]"],[/AIza[A-Za-z0-9_-]{35}/g,"[REDACTED_GOOGLE_KEY]"],[/hv[sb]\.[A-Za-z0-9_-]{20,}/g,"[REDACTED_VAULT_TOKEN]"],[/dop_v1_[A-Za-z0-9]{40,}/g,"[REDACTED]"],[/dckr_pat_[A-Za-z0-9_-]{20,}/g,"[REDACTED]"],[/pypi-[A-Za-z0-9_-]{16,}/g,"[REDACTED]"],[/rk_(?:live|test)_[A-Za-z0-9]{16,}/g,"[REDACTED]"],[/whsec_[A-Za-z0-9]{16,}/g,"[REDACTED]"],[/SG\.[A-Za-z0-9_-]{20,}\.[A-Za-z0-9_-]{20,}/g,"[REDACTED]"],[/(eyJ[A-Za-z0-9_-]{6,}(?:\.[A-Za-z0-9_-]{4,}){1,2})/g,"[REDACTED_JWT]"],[/-----BEGIN [A-Z ]*PRIVATE KEY-----(?:[\s\S]*?-----END[^\n]*-----|\r?\n[A-Za-z0-9+/=][A-Za-z0-9+/=\r\n]*)?/g,"[REDACTED_PEM]"],[/\b((?:--?)?[A-Za-z0-9_]*(?:TOKEN|SECRET|PASSWORD|PASSWD|PASS|APIKEY|KEY|CRED|CREDS|CREDENTIAL|CREDENTIALS|AUTH|_PWD)[A-Za-z0-9_]*['"]?\s*=\s*)(?:"[^"]*"|'[^']*'|[^"'\s]\S*)/gi,"$1[REDACTED]"],[/\b([A-Za-z0-9_]*(?:TOKEN|SECRET|PASSWORD|PASSWD|PASS|APIKEY|KEY|CRED|CREDS|CREDENTIAL|CREDENTIALS|_PWD)[A-Za-z0-9_]*['"]?\s*:\s*)(?:"[^"]*"|'[^']*'|[^\s'",}]+)/gi,"$1[REDACTED]"],[/((?:^|[\s'"{,])['"]?(?:[A-Za-z0-9_]+_)?auth['"]?\s*:\s*)(?:"[^"]*"|'[^']*'|[^\s'",}]+)/gi,"$1[REDACTED]"],[/(\bpwd\s*[=:]\s*)(?:"[^"]*"|'[^']*'|[^/~\s][^\s;'"]*)/gi,"$1[REDACTED]"],[/([=:]\s*["']?)[A-Za-z0-9_\-+/=]{40,}/g,"$1[REDACTED]"]]});import{join as yr}from"node:path";import{appendFileSync as Oo,chmodSync as ol,existsSync as Mt,mkdirSync as $n,readFileSync as In,renameSync as Pn,rmdirSync as Io,statSync as Dn,unlinkSync as gt,utimesSync as il,writeFileSync as Nn}from"node:fs";function Mn(t){return yr(Ft(),`${t}.lock`)}function cl(t){let e=Mn(t);try{return $n(Ft(),{recursive:!0,mode:448}),$n(e),!0}catch{try{Date.now()-Dn(e).mtimeMs>al&&Io(e)}catch{return!1}return!1}}function ul(t){try{il(Mn(t),new Date,new Date)}catch{return}}function ll(t){try{Io(Mn(t))}catch{return}}function Ft(){return yr(y(),"spool")}function gr(t){return yr(Ft(),`${t}.jsonl`)}function wr(t){return yr(Ft(),`${t}.pending.jsonl`)}function vr(t,e){try{$n(Ft(),{recursive:!0,mode:448});let r=gr(t);if(Mt(r)&&Dn(r).size>=On)return;Oo(r,JSON.stringify(e)+`
|
|
15
|
+
`,{mode:384}),ol(r,384)}catch{return}}function Po(t,e){Oo(t,In(e,"utf8"),{mode:384}),Nn(e,"",{mode:384});try{gt(e)}catch{return}}function dl(t){if(Dn(t).size<=On)return;let e=In(t,"utf8").split(`
|
|
16
|
+
`).filter(s=>s.trim()),r=0,n=[];for(let s=e.length-1;s>=0;s--){let o=e[s]??"";if(r+=Buffer.byteLength(o,"utf8")+1,r>On)break;n.unshift(o)}Nn(t,n.length?n.join(`
|
|
17
17
|
`)+`
|
|
18
|
-
`:"",{mode:384})}function
|
|
19
|
-
`))if(o.trim())try{s.push(JSON.parse(o))}catch{continue}return s.length===0?(gt(e),[]):s}catch{return[]}}function
|
|
18
|
+
`:"",{mode:384})}function fl(t){try{let e=wr(t),r=gr(t),n=`${r}.merging`;if(Mt(n)&&Po(e,n),Mt(e))Mt(r)&&(Pn(r,n),Po(e,n));else{if(!Mt(r))return[];Pn(r,e)}dl(e);let s=[];for(let o of In(e,"utf8").split(`
|
|
19
|
+
`))if(o.trim())try{s.push(JSON.parse(o))}catch{continue}return s.length===0?(gt(e),[]):s}catch{return[]}}function Do(t){try{gt(wr(t))}catch{return}}function ml(t,e){if(e.length===0){Do(t);return}let r=wr(t),n=`${r}.tmp`;Nn(n,e.map(s=>JSON.stringify(s)).join(`
|
|
20
20
|
`)+`
|
|
21
|
-
`,{mode:384})
|
|
22
|
-
`)}async function
|
|
23
|
-
`)}async function
|
|
21
|
+
`,{mode:384}),Pn(n,r)}async function br(t,e,r={}){if(Cn.has(t)||!cl(t))return"fail";Cn.add(t);try{if(!(await U()).telemetryOptIn)return Lt(t),"empty";let n=fl(t);if(n.length===0)return"empty";let s=await T();if(!s)return"fail";if(r.requirePro&&s.plan!=="pro")return Do(t),"ok";let o=r.baseUrl??process.env.TOKMIZER_BASE_URL??"https://tokmizer.com",i=await Q();for(let a=0;a<n.length;a+=Rn){if(!(await U()).telemetryOptIn)return Lt(t),"empty";ul(t);let c=await z("POST",e,{events:n.slice(a,a+Rn)},{baseUrl:o,bearer:s.jwt,signingSecret:s.signingSecret,fingerprint:i.fingerprint,installId:i.installId});if(!c.ok)return c.status===401||c.status===403?"auth":"fail";ml(t,n.slice(a+Rn))}return"ok"}catch{return"fail"}finally{Cn.delete(t),ll(t)}}function Lt(t){try{gt(gr(t))}catch{}try{gt(`${gr(t)}.merging`)}catch{}try{gt(wr(t))}catch{return}}var On,Rn,al,Cn,kr=E(()=>{"use strict";D();pe();Be();Ve();Pt();On=512*1024,Rn=100,al=12e4,Cn=new Set});var Mo={};te(Mo,{commandName:()=>_r,flushTelemetry:()=>kl,recordTelemetry:()=>Ln});function No(t){let e=t.toLowerCase();return e.startsWith("git")||yl.has(e)}function _r(t){let e=t.trim().split(/\s+/).filter(a=>a.length>0),r=0;for(;r<e.length&&gl.test(e[r]??"");)r+=1;let n=e[r];if(!n||!pl.test(n)||n.length>vl||No(n)||wl.test(n)||Nt(n)!==n)return"";let s=e[r+1];return s&&No(s)?"":(s&&bl.has(n.toLowerCase())&&hl.test(s)?`${n} ${s}`:n).slice(0,64)}async function Ln(t){if(!t.telemetryOptIn)return;let e=_r(t.cmd),r=e&&Nt(e)===e?e:"other",n=t.sessionId?t.sessionId.replace(/[^A-Za-z0-9._-]/g,"").slice(0,64):"";vr("telemetry",{cmd:r,tokensSaved:Math.max(0,Math.round(t.tokensSaved)),...t.tokensRestored?{tokensRestored:Math.max(0,Math.round(t.tokensRestored))}:{},...t.rawTokens!=null?{rawTokens:Math.max(0,Math.round(t.rawTokens))}:{},optimized:t.optimized,...n?{sessionId:n}:{},...t.host?{host:t.host}:{}})}async function kl(t){return br("telemetry","/api/v1/telemetry",{baseUrl:t})}var pl,hl,gl,yl,wl,vl,bl,xr=E(()=>{"use strict";An();kr();pl=/^[a-z0-9][a-z0-9._-]*$/i,hl=/^[a-z][a-z-]+$/,gl=/^[A-Za-z_][A-Za-z0-9_]*=/,yl=new Set(["gh","glab","gup","hub","gist"]),wl=/^(gh[a-z]_|github_pat_|gl(?:pat|rt|soat|imt|dt|ft|agent|oas)-|npm_|xox|sk-|sk_|eyj|a(?:kia|sia|gpa|ida|roa|npa)|aiza|hv[sb]\.)/i,vl=24,bl=new Set(["docker","podman","npm","pnpm","yarn","npx","bun","deno","cargo","rustup","go","pip","pip3","uv","poetry","brew","apt","apt-get","dnf","yum","pacman","kubectl","helm","terraform","aws","gcloud","az","systemctl","composer","bundle","gem","dotnet","prisma","tkr","rtk","token"])});var Lo={};te(Lo,{flush:()=>xl,recordEvent:()=>_l});async function _l(t){if(t.plan!=="pro"||!(await U()).telemetryOptIn)return;let e=_r(t.cmd);!e||Nt(e)!==e||vr("learn",{cmd:e,filterId:t.filterId==null?null:ke(t.filterId),rawBytes:t.rawBytes,filteredBytes:t.filteredBytes})}async function xl(t){return br("learn","/api/v1/learn",{baseUrl:t,requirePro:!0})}var Fo=E(()=>{"use strict";xr();An();kr();kt();Pt()});function Vn(t){return Hn.filter(e=>Bn.has(e.host)===t).flatMap(e=>e.vars)}function Rr(t=process.env){let e=process.platform,r=e==="darwin"||e==="linux"||e==="win32"?e:"other",n=process.arch;for(let s of Hn)if(s.vars.some(o=>t[o]))return{host:s.host,source:"env",os:r,arch:n,shimRecommended:!Bn.has(s.host)};return{host:"shell",source:"fallback",os:r,arch:n,shimRecommended:!0}}function Ko(t){return Bn.has(t)?"native-hooks":"shell-shim"}var Hn,Hp,Bn,Kn=E(()=>{"use strict";Hn=[{host:"claude-code",vars:["CLAUDECODE","CLAUDE_CODE_ENTRYPOINT","CLAUDE_CODE","CLAUDE_CODE_VERSION","ANTHROPIC_CLAUDE_CODE"]},{host:"codex",vars:["CODEX_VERSION","CODEX_CLI","OPENAI_CODEX","CODEX_THREAD_ID","CODEX_SESSION_ID"]},{host:"cursor",vars:["CURSOR_VERSION","CURSOR_TRACE_ID"]},{host:"cline",vars:["CLINE_VERSION","CLINE_API_KEY"]},{host:"aider",vars:["AIDER_VERSION","AIDER_MODEL"]},{host:"gemini-cli",vars:["GEMINI_CLI_VERSION","GEMINI_API_KEY"]},{host:"windsurf",vars:["WINDSURF_VERSION","WINDSURF_USER"]},{host:"copilot",vars:["GITHUB_COPILOT_VERSION","COPILOT_INTEGRATION_ID"]}],Hp=[...Hn.map(t=>t.host),"shell"],Bn=new Set(["claude-code","codex"])});var ei={};te(ei,{ensurePathInRc:()=>Zt,ensureShimPath:()=>Dr,envWithoutShimDir:()=>Hl,installShims:()=>We,listShimmableCommands:()=>Bl,powershellProfilePath:()=>Qo,powershellProfileSnippet:()=>Xo,refreshShimsIfStale:()=>Vl,refreshStaleShims:()=>Yo,resolveShimJsPath:()=>ue,shellRcLine:()=>ge,shimsDir:()=>N,shimsInstalled:()=>Ht,uninstallShims:()=>Wn,unixWrapperScript:()=>Or,windowsWrapperScript:()=>qo});import{mkdir as Gn,writeFile as Ut,readFile as $r,unlink as Jn,chmod as Wo,rename as zl}from"node:fs/promises";import{existsSync as Je}from"node:fs";import{delimiter as Go,join as L,dirname as Cr}from"node:path";import{fileURLToPath as Ul}from"node:url";import{execFileSync as Zl}from"node:child_process";import K from"node:os";function N(){return L(y(),"shims")}function Hl(){let t=N(),e={...process.env},r=process.platform==="win32"?"Path":"PATH",s=(e[r]??e.PATH??"").split(Go).filter(o=>o&&o!==t);return e[r]=s.join(Go),r==="Path"&&(e.PATH=e[r]),e}function Ht(){try{let t=K.platform()==="win32";return Je(L(N(),t?"git.cmd":"git"))}catch{return!1}}function Bl(){return[...Pr]}function zt(t){return`'${t.replace(/'/g,"'\\''")}'`}function Jo(t){return`"${t.map(e=>`\${${e}:-}`).join("")}"`}function Or(t,e){return["#!/bin/sh",`if [ -n ${Jo(Vn(!0))} ] || { [ -z ${Jo(Vn(!1))} ] && [ ! -t 1 ]; }; then`," set -f",` _tk_d=${zt(N())}`,` _tk_c=${zt(e)}`," _tk_o=$IFS; IFS=:; _tk_p=; _tk_x="," for _tk_e in $PATH; do",' [ -n "$_tk_e" ] || continue',' [ "$_tk_e" -ef "$_tk_d" ] && continue'," _tk_p=${_tk_p:+$_tk_p:}$_tk_e",' [ -z "$_tk_x" ] && [ -f "$_tk_e/$_tk_c" ] && [ -x "$_tk_e/$_tk_c" ] && _tk_x=$_tk_e/$_tk_c'," done"," IFS=$_tk_o; PATH=$_tk_p; export PATH; set +f",' [ -n "$_tk_x" ] || { echo "$_tk_c: command not found" >&2; exit 127; }',' exec "$_tk_x" "$@"',"fi",`exec node ${zt(t)} --as ${zt(e)} "$@"`,""].join(`
|
|
22
|
+
`)}async function Vl(t,e){if(K.platform()==="win32")return 0;try{if(await $r(L(N(),e),"utf8")===Or(t,e))return 0}catch{return 0}return Yo(t)}async function Yo(t){if(K.platform()==="win32")return 0;let e=N();if(!Je(e))return 0;let r=0;for(let n of Pr){let s=L(e,n),o=Or(t,n),i;try{i=await $r(s,"utf8")}catch{continue}if(i===o)continue;let a=`${s}.${process.pid}.tmp`;try{await Ut(a,o,{mode:493}),await Wo(a,493),await zl(a,s),r+=1}catch{try{await Jn(a)}catch{}}}return r}function qo(t,e){return["@echo off",`node "${t}" --as "${e}" %*`,""].join(`\r
|
|
23
|
+
`)}async function We(t){let e=N();await Gn(e,{recursive:!0,mode:448});let r=[],n=K.platform()==="win32";for(let s of Pr){let o=n?L(e,`${s}.cmd`):L(e,s);if(Je(o))try{await Jn(o)}catch{}n?await Ut(o,qo(t,s)):(await Ut(o,Or(t,s),{mode:493}),await Wo(o,493)),r.push(s)}return r}async function Wn(){let t=N();if(!Je(t))return 0;let e=0,r=K.platform()==="win32";for(let n of Pr){let s=r?L(t,`${n}.cmd`):L(t,n);try{await Jn(s),e+=1}catch{}}return e}function ge(t=!1){let e=t?`'${N().replace(/\\/g,"\\\\").replace(/'/g,"\\'")}'`:zt(N());return`${Ir}
|
|
24
24
|
${t?`set -gx PATH ${e} $PATH`:`export PATH=${e}:"$PATH"`}
|
|
25
|
-
`}async function Zt(t,e=!1){try{await
|
|
25
|
+
`}async function Zt(t,e=!1){try{await Gn(Cr(t),{recursive:!0});let r=Je(t)?await $r(t,"utf8"):"";return r.includes(Ir)?"present":(await Ut(t,`${r.replace(/\n*$/,`
|
|
26
26
|
`)}
|
|
27
|
-
${ge(e)}`,{mode:384}),"added")}catch{return"missing"}}function
|
|
27
|
+
${ge(e)}`,{mode:384}),"added")}catch{return"missing"}}function Xo(){return`${Ir}
|
|
28
28
|
$env:Path = '${N().replace(/'/g,"''")};' + $env:Path
|
|
29
|
-
`}function
|
|
29
|
+
`}function Qo(){let t=K.platform()==="win32"?Zl("powershell.exe",["-NoProfile","-NonInteractive","-Command","[Environment]::GetFolderPath('MyDocuments')"],{encoding:"utf8",windowsHide:!0}).trim():L(K.homedir(),"Documents");return L(t||L(K.homedir(),"Documents"),"PowerShell","profile.ps1")}async function Dr(){if(K.platform()==="win32"){let o=L(K.homedir(),"Documents","PowerShell","profile.ps1"),i=Xo();try{o=Qo();let a=!1;for(let c of[o,L(Cr(Cr(o)),"WindowsPowerShell","profile.ps1")]){await Gn(Cr(c),{recursive:!0});let u=Je(c)?await $r(c,"utf8"):"";u.includes(Ir)||(await Ut(c,`${u.replace(/\n*$/,`
|
|
30
30
|
`)}
|
|
31
|
-
${i}`),a=!0)}return{status:a?"added":"present",target:o,manual:i}}catch{return{status:"missing",target:o,manual:i}}}let t=process.env.SHELL??"",e=t.endsWith("/fish"),r=e?".config/fish/config.fish":t.endsWith("/zsh")?".zshrc":t.endsWith("/bash")?".bashrc":".profile",n=L(
|
|
31
|
+
${i}`),a=!0)}return{status:a?"added":"present",target:o,manual:i}}catch{return{status:"missing",target:o,manual:i}}}let t=process.env.SHELL??"",e=t.endsWith("/fish"),r=e?".config/fish/config.fish":t.endsWith("/zsh")?".zshrc":t.endsWith("/bash")?".bashrc":".profile",n=L(K.homedir(),r),s=await Zt(n,e);if(t.endsWith("/bash")&&s!=="missing"){let o=[".bash_profile",".bash_login",".profile"].map(a=>L(K.homedir(),a)).find(Je)??L(K.homedir(),".bash_profile"),i=await Zt(o);if(i==="missing")return{status:"missing",target:o,manual:ge()};if(i==="added")return{status:"added",target:o,manual:ge()}}return{status:s,target:n,manual:ge(e)}}function ue(){return process.env.TOKMIZER_SHIM_JS?process.env.TOKMIZER_SHIM_JS:Ul(new URL("../bin/tkr-shim.js",import.meta.url))}var Pr,Ir,Nr=E(()=>{"use strict";D();Kn();Pr=["git","npm","yarn","pnpm","docker","kubectl","terraform","tofu","cargo","go","mvn","gradle","rg","grep","find","ls","cat","tail","head","ps","lsof","ssh","scp","rsync","curl","wget","jq","yq","make"];Ir="# tokmizer-shim PATH (managed by tokmizer)"});var Ni={};te(Ni,{TAP_FORMULA_PATHS:()=>Ii,brewTapStatus:()=>md,formulaWedged:()=>Di});import{readFileSync as dd}from"node:fs";function Di(t){return/^(?:<{7}|={7}|>{7})/m.test(t)}function md(t=Ii){for(let e of t)try{return{path:e,wedged:Di(dd(e,"utf8"))}}catch{}return null}var fd,Ii,Mi=E(()=>{"use strict";fd=["/opt/homebrew/Library/Taps","/usr/local/Homebrew/Library/Taps","/home/linuxbrew/.linuxbrew/Homebrew/Library/Taps"],Ii=fd.map(t=>`${t}/norwelltw/homebrew-tokmizer/Formula/tokmizer.rb`)});function Fi(t,e,r,n=e){let s=Li.get(n);s||(s=new Map,Li.set(n,s));let o=JSON.stringify([t,r?[...r].sort():null]),i=s.get(o);if(i!==void 0)return i;let a=null;for(let c of e)r&&!r.has(ke(c.slug))||c.matchRegex.test(t)&&(!a||c.priority>a.priority)&&(a=c);if(s.size>=pd){let c=s.keys().next().value;c&&s.delete(c)}return s.set(o,a),a}var Li,pd,ji=E(()=>{"use strict";kt();Li=new WeakMap,pd=256});import{createCipheriv as $h,createDecipheriv as hd,hkdfSync as gd,randomBytes as Ph}from"node:crypto";function vd(t){return Buffer.from(gd("sha256",Buffer.from(t,"utf8"),yd,wd,32))}function zi(t,e){let r=vd(e),n=Buffer.from(t,"base64url"),s=n.subarray(0,12),o=n.subarray(12,28),i=n.subarray(28),a=hd("aes-256-gcm",r,s);return a.setAuthTag(o),Buffer.concat([a.update(i),a.final()]).toString("utf8")}var yd,wd,Ui=E(()=>{"use strict";yd=Buffer.from("tokmizer-bundle-enc-v1"),wd=Buffer.from("rules-bundle")});import{chmodSync as bd,readFileSync as kd,writeFileSync as _d,mkdirSync as xd,renameSync as Sd}from"node:fs";import{join as Zi}from"node:path";function ns(){return Zi(y(),"bundle-cache.json")}function Hi(t){try{let e=y();xd(e,{recursive:!0});let r={...t,fetchedAt:Date.now()},n=Zi(e,`bundle-cache.${process.pid}.tmp`);_d(n,JSON.stringify(r),{mode:384}),Sd(n,ns()),bd(ns(),384)}catch{}}function Bi(){try{let t=kd(ns(),"utf8"),e=Ed.safeParse(JSON.parse(t));return e.success?e.data:null}catch{return null}}var Ed,Vi=E(()=>{"use strict";ot();D();Ed=f.object({payload:f.string().min(1),signature:f.string().min(1),enc:f.literal("v1"),fetchedAt:f.number().int().nonnegative()})});var is={};te(is,{BundleFetchError:()=>Bt,bundleExpired:()=>Pd,fetchBundle:()=>Dd,healOn401:()=>Id,maxBundleAgeMs:()=>ss,runtimeFromCache:()=>Nd,runtimeFromEnvelope:()=>os});import{createPublicKey as Td,verify as Ad}from"node:crypto";function ss(){let t=Number(process.env.TOKMIZER_MAX_BUNDLE_AGE_MS);return Number.isFinite(t)&&t>0?t:$d}function Pd(t,e=Date.now()){return e-t.fetchedAt>ss()}function Od(t,e){let r=Tt();if(!r||!r.includes("BEGIN PUBLIC KEY"))throw new Error("tkr-daemon: no valid signing public key configured (set TOKMIZER_RESP_SIGNING_PUBLIC_KEY_PEM at build time).");let n=Td({key:r,format:"pem"});if(!Ad(null,Buffer.from(t.payload,"utf8"),n,Buffer.from(t.signature,"base64url")))throw new Error("tkr-daemon: rules bundle signature invalid");return JSON.parse(zi(t.payload,e))}async function Id(t,e,r){if(t instanceof Bt&&(t.status===401||t.status===403))try{return await r.heartbeat(e),await r.fetchBundle(e)}catch(n){return r.log(`initial fetch failed after heartbeat: ${n.message}`),null}return r.log(`initial fetch failed: ${t.message}`),null}async function Dd(t){let e=await T();if(!e||!e.jwt)throw new Error("tkr-daemon: not activated (no JWT)");if(!e.signingSecret)throw new Error("tkr-daemon: not activated (no signing secret)");let r=await z("GET","/api/v1/rules/bundle",void 0,{baseUrl:t,bearer:e.jwt,signingSecret:e.signingSecret,fingerprint:e.fingerprint??"0".repeat(64),installId:e.installId,timeoutMs:1e4});if(!r.ok)throw new Bt(r.status);let n=Cd.parse(await r.json()),s=os(n,e.signingSecret);return Hi(n),s}function os(t,e){let r=Od(t,e),n=Rd.parse(r);if(Date.now()-n.signedAt>ss())throw new Error("tkr-daemon: rules bundle is stale");let s=new Map;for(let o of n.filters)s.set(o.slug,{...o,matchRegex:new RegExp(o.match_command)});return{bundleVersion:n.bundleVersion,signedAt:n.signedAt,ruleCount:s.size,startedAt:Date.now(),fetchedAt:Date.now(),selectFor:(o,i,a)=>Fi(o,s.values(),a?new Set(a):null,s)}}async function Nd(){try{let t=Bi();if(!t)return null;let e=await T();return e?.signingSecret?os(t,e.signingSecret):null}catch{return null}}var Rd,Cd,$d,Bt,as=E(()=>{"use strict";ot();on();ji();pe();Ve();Ui();Vi();Rd=f.object({bundleVersion:f.number().int().nonnegative(),signedAt:f.number().int(),filters:f.array(ur)}),Cd=f.object({payload:f.string().min(1),signature:f.string().min(1),enc:f.literal("v1")}),$d=10080*60*1e3;Bt=class extends Error{status;constructor(e){super(`tkr-daemon: bundle fetch failed ${e}`),this.status=e}}});import ti from"node:readline/promises";import{stdin as Yn,stdout as G}from"node:process";import Kl from"node:os";import{join as Gl}from"node:path";var B={welcome:"Link your Tokmizer account.",needToken:"Tokmizer already works on this device. Linking attaches it to your account.",getToken:"Sign in at tokmizer.com, then grab your key from your dashboard.",askToken:"Paste your dashboard key, then press Enter:",activating:"Linking...",activated:t=>`Linked. You are on the ${t} plan.`,failed:t=>`Activation failed: ${t}`,suspended:t=>`Your token is suspended. ${t}`,revoked:"Your token has been revoked. Contact support at tokmizer.com/contact",rotated:"Token rotated. Paste your new token from tokmizer.com/dashboard/token",offline:"Network required. Tokmizer needs an internet connection.",deviceCap:"Device limit reached. Manage devices at tokmizer.com/dashboard/devices"};function jr(t,e){return t===null?e!==null?` \u26A0 engine offline \u2014 compression continues on ${e} cached rules (details: tkr doctor)
|
|
32
32
|
`:` \u26A0 optimizer engine offline \u2014 run: tkr doctor
|
|
33
|
-
`:t===0
|
|
34
|
-
`:""}kt();
|
|
33
|
+
`:t===0?e!==null&&e>0?"":` \u26A0 optimizer engine reconnecting \u2014 savings resume shortly (details: tkr doctor)
|
|
34
|
+
`:""}kt();Be();pe();Ve();D();import{readFile as Sl,writeFile as Uo,mkdir as El}from"node:fs/promises";Ve();pe();Be();import{createPublicKey as Ec,verify as Tc}from"node:crypto";function Ac(t,e){let r=Tt();if(!r||!r.includes("BEGIN PUBLIC KEY"))throw new Error("Tokmizer plugin: no valid signing public key. Set TOKMIZER_RESP_SIGNING_PUBLIC_KEY_PEM or rebuild plugin against a prod key.");let n=Ec({key:r,format:"pem"});try{let s=Buffer.from(e,"base64url");return Tc(null,Buffer.from(t,"utf8"),n,s)}catch{return!1}}var Rc=/^[a-z0-9][a-z0-9-]*$/;async function $s(t){let e=await T();if(!e)throw new Error("Plugin not activated.");let r=await Q(),n=await z("GET","/api/v1/skills/bundle",void 0,{baseUrl:t,bearer:e.jwt,signingSecret:e.signingSecret,fingerprint:r.fingerprint,installId:r.installId,timeoutMs:8e3});if(!n.ok)throw new Error(`bundle fetch failed ${n.status}`);let s=await Te(n),o=[];for(let i of s.bundles){if(!Rc.test(i.slug))throw new Error(`invalid bundle slug ${i.slug}`);let a=[...i.fragments].sort((c,u)=>c.position-u.position);for(let c of a)if(!Ac(c.body,c.hash))throw new Error(`fragment signature mismatch on ${i.slug}[${c.position}]`);o.push({slug:i.slug,version:i.version,body:a.map(c=>c.body).join(`
|
|
35
35
|
|
|
36
|
-
`)})}return o}D();import{chmod as
|
|
37
|
-
`,code:1};let e=await
|
|
38
|
-
`,code:1,restoredTokens:0}:{stdout:e,code:0,restoredTokens:Math.round(Buffer.byteLength(e,"utf8")/4)}}async function
|
|
36
|
+
`)})}return o}D();import{chmod as Xr,mkdir as or,readFile as At,writeFile as ir,stat as Qr,readdir as Cc,rm as Os}from"node:fs/promises";var Is="managed-by: tokmizer",qr=["tkr","tkr-gain","tkr-status","tkr-link","tkr-unlink","tkr-compression","tkr-telemetry","tkr-update","tkr-yolo"],$c=["power","tkr-reducer"];async function Ds(){try{let t=JSON.parse(await At(er(),"utf8"));return Array.isArray(t)?t.filter(e=>typeof e=="string"):[]}catch{return[]}}async function Ns(t){try{await or(y(),{recursive:!0}),await ir(er(),JSON.stringify(t),{mode:384})}catch{}}var Pc=3600*1e3,Ps=10080*60*1e3;function Ms(){let t=Number(process.env.TOKMIZER_MAX_BUNDLE_AGE_MS);return Number.isFinite(t)&&t>0?Math.min(t,Ps):Ps}async function Ls(t){try{let e=await Qr(_e(t)),r=Date.now()-e.mtimeMs;return r<Pc&&r<=Ms()}catch{return!1}}async function Fs(t,e){await or(xt(),{recursive:!0}),await ir(_e(t),e,{mode:384}),await Xr(_e(t),384)}async function Rt(t){let e=new Set(t),r;try{r=await Cc(xt())}catch{return}for(let n of r){if(!n.endsWith(".md"))continue;let s=n.slice(0,-3);if(!e.has(s))try{await Os(_e(s))}catch{}}}async function js(t,e){await or(tr(),{recursive:!0});try{if(!(await At(xe(t),"utf8")).includes(Is))return}catch{}await ir(xe(t),e,{mode:384}),await Xr(xe(t),384);let r=await Ds();r.includes(t)||await Ns([...r,t])}async function Ct(t){let e=new Set([...t,...qr]),r=await Ds(),n=new Set([...r,...$c]);for(let s of n)if(!e.has(s))try{if(!(await At(xe(s),"utf8")).includes(Is))continue;await Os(xe(s))}catch{}await Ns(r.filter(s=>e.has(s)))}async function zs(){let t=0;for(let e of qr)await en(e)&&t++;return{installed:t,total:qr.length}}async function en(t){try{return await Qr(xe(t)),!0}catch{return!1}}async function tn(t){try{await or(y(),{recursive:!0}),await ir(_t(),JSON.stringify({at:Date.now(),error:t}),{mode:384}),await Xr(_t(),384)}catch{}}async function ar(){try{return JSON.parse(await At(_t(),"utf8"))}catch{return null}}async function cr(t){try{let e=await Qr(_e(t));return Date.now()-e.mtimeMs>Ms()?null:await At(_e(t),"utf8")}catch{return null}}import{chmod as Xf,mkdir as Qf,readFile as Lc,writeFile as em,stat as Bs,readdir as Fc,rm as Hs,rename as tm}from"node:fs/promises";D();import{join as jc}from"node:path";D();import{randomUUID as Oc}from"node:crypto";import{readFileSync as Ic}from"node:fs";import{mkdir as Dc,rename as Nc,rm as Us,writeFile as Mc}from"node:fs/promises";import{join as Zs}from"node:path";function lt(){try{return Ic(Zs(y(),"yolo-mode"),"utf8")==="on"}catch{return!1}}async function Ke(t){let e=y(),r=Zs(e,"yolo-mode");if(!t){await Us(r,{force:!0});return}await Dc(e,{recursive:!0,mode:448});let n=`${r}.tmp-${process.pid}-${Oc()}`;try{await Mc(n,"on",{mode:384,flag:"wx"}),await Nc(n,r)}finally{await Us(n,{force:!0})}}var Vs=10080*60*1e3,zc=100*1024*1024,om=2*1024*1024,Uc=/^[0-9a-f]{8,64}$/i;function rn(t,e,r=process.env){let n=Number(r[t]);return Number.isFinite(n)&&n>0?n:e}async function Ks(t){if(!t)return{stderr:`usage: tkr restore <hash>
|
|
37
|
+
`,code:1};let e=await Zc(t);return e==null?{stderr:`tkr restore: no cached content for ${t}
|
|
38
|
+
`,code:1,restoredTokens:0}:{stdout:e,code:0,restoredTokens:Math.round(Buffer.byteLength(e,"utf8")/4)}}async function Zc(t){if(!Uc.test(t))return null;try{let e=await Bs(Qt(t));return Date.now()-e.mtimeMs>rn("TOKMIZER_CCR_MAX_AGE_MS",Vs)?null:await Lc(Qt(t),"utf8")}catch{return null}}async function Gs(){let t;try{t=await Fc(St())}catch{return}let e=rn("TOKMIZER_CCR_MAX_AGE_MS",Vs),r=rn("TOKMIZER_CCR_DIR_CAP_BYTES",zc),n=Date.now(),s=[];for(let i of t){let a=jc(St(),i);try{let c=await Bs(a);n-c.mtimeMs>e?await Hs(a):s.push({path:a,mtimeMs:c.mtimeMs,size:c.size})}catch{}}let o=s.reduce((i,a)=>i+a.size,0);if(!(o<=r)){s.sort((i,a)=>i.mtimeMs-a.mtimeMs);for(let i of s){if(o<=r)break;try{await Hs(i.path),o-=i.size}catch{}}}}pe();Be();Ve();Pt();async function no(t,e){let r=await T();if(!r)throw new Error("Not activated. Run: tkr link");if(r.linked===!1){if(t==="GET")return{plan:r.plan,settings:await U()};let a=await to(e);return{plan:r.plan,settings:a}}let n=process.env.TOKMIZER_BASE_URL??"https://tokmizer.com",s=await Q(),o=await z(t,"/api/v1/settings",e,{baseUrl:n,bearer:r.jwt,signingSecret:r.signingSecret,fingerprint:s.fingerprint,installId:s.installId,timeoutMs:8e3});if(!o.ok)throw new Error(`Settings ${t} failed: ${o.status}`);let i=await Te(o);return await sn(i.settings),i}async function Ge(){return no("GET")}async function Ae(t){return no("PATCH",t)}var Gc=new Set(["__proto__","constructor","prototype"]);function Jc(t,e,r){let n=e.split(".");if(n.some(o=>Gc.has(o)))throw new Error(`invalid settings key: ${e}`);let s=t;for(let o=0;o<n.length-1;o++){let i=n[o];(typeof s[i]!="object"||s[i]===null)&&(s[i]={}),s=s[i]}s[n[n.length-1]]=r}function Wc(t){if(t==="true")return!0;if(t==="false")return!1;if(/^-?\d+$/.test(t))return Number.parseInt(t,10);if(t.startsWith("[")||t.startsWith("{"))try{return JSON.parse(t)}catch{}return t}function so(t,e){let r=Wc(e),n={};return Jc(n,t,r),n}ut();var jo="-command",zo=3;async function Fn(){try{let{connectDaemon:t}=await Promise.resolve().then(()=>(pt(),mt)),e=await t();try{await e.reload()}finally{e.close()}}catch{}}async function jn(t,e){if(!(!e&&await Ls("power"))){try{let r=await $s(t),n=[],s=[];for(let o of r)if(o.slug.endsWith(jo)){let i=o.slug.slice(0,-jo.length);await js(i,o.body),s.push(i)}else await Fs(o.slug,o.body),n.push(o.slug);await Rt(n),await Ct(s),await tn(null)}catch(r){await tn(r instanceof Error?r.message:String(r))}try{await Gs()}catch{}}}async function Tl(t,e){let r;for(let n=0;n<e.attempts;n++)try{return await t()}catch(s){if(r=s,n===e.attempts-1)break;let o=500*Math.pow(3,n)+Math.floor(Math.random()*300);await new Promise(i=>setTimeout(i,o))}throw r}async function Sr(t){let e=await Q(),r=Et(),n={token:t.token,...t.email?{email:t.email}:{},pluginVersion:V,timeZone:r,...e},s=await Tl(()=>z("POST","/api/v1/license/activate",n,{baseUrl:t.baseUrl,bearer:t.token,fingerprint:e.fingerprint,installId:e.installId,timeoutMs:1e4}),{attempts:3});if(!s.ok){if(s.status>=500)throw new Error("Tokmizer servers are temporarily unreachable. Try again in a minute.");let a=await s.text();throw Al(a)==="device_cap"?new Error(B.deviceCap):new Error(B.failed(`${s.status} ${a}`))}let o=await Te(s),i={token:t.token,jwt:o.jwt,signingSecret:o.signingSecret,plan:o.plan,status:o.status,trialEndsAt:o.trialEndsAt,subEndsAt:o.subEndsAt,jwtVersion:o.jwtVersion,installId:e.installId,fingerprint:e.fingerprint,pluginVersion:V,...t.email||o.boundEmail?{email:t.email??o.boundEmail??""}:{},timeZone:r,bonusActive:!1,linked:!0,lastHeartbeatOkAt:Date.now(),...Array.isArray(o.allowedFilters)&&o.allowedFilters.length>0?{allowedFilters:o.allowedFilters.map(ke)}:{}};return await nr(i),await Fn(),await jn(t.baseUrl,!0),i}function Al(t){try{let e=JSON.parse(t);return typeof e.code=="string"?e.code:null}catch{return null}}function Rl(t){try{return new Intl.DateTimeFormat("en-CA",{timeZone:t,year:"numeric",month:"2-digit",day:"2-digit"}).format(new Date)}catch{return new Date().toISOString().slice(0,10)}}async function jt(t,e){let r=await T();return r&&r.token!==t.token?!1:(await nr(e),!0)}async function zn(t){let e=await T();if(!e)return null;let r=await Q(),n=e.timeZone??Et(),s={ts:Date.now(),localDate:Rl(n),timeZone:n},o;try{o=await z("POST","/api/v1/license/heartbeat",s,{baseUrl:t,bearer:e.jwt,signingSecret:e.signingSecret,fingerprint:r.fingerprint,installId:r.installId,timeoutMs:5e3})}catch{return e}if(o.status===401){let b=(e.heartbeatAuthFails??0)+1,k={...e,heartbeatAuthFails:b},$=e.linked??(!!e.email||e.plan==="smart"||e.plan==="pro");if(b>=zo&&$&&(k.relinkRequired=!0),!await jt(e,k))return null;if(b>=zo&&!$){try{await Uo(`${y()}/state.replaced.json`,JSON.stringify(e),{mode:384})}catch{}try{return await Zo(t)}catch{return null}}return null}if(o.status===451){let b=await T();if(b&&b.token!==e.token)return null;await sr();try{await Rt([]),await Ct([])}catch{}return null}if(o.status===426)return await jt(e,{...e,updateRequired:!0}),null;if(o.status===423)return await jt(e,{...e,relinkRequired:!0}),null;if(!o.ok){if(o.status===400)try{(await o.json())?.code==="stale_ts"&&await jt(e,{...e,clockSkewDetected:!0})}catch{}return e}let i;try{i=await Te(o)}catch{return e}let a=i.settingsRevision??0,c=e.lastSettingsRevision??0,u=a>c,l=i.plan!==e.plan,h={...e,jwt:i.jwt,plan:i.plan,status:i.status,trialEndsAt:i.trialEndsAt,subEndsAt:i.subEndsAt,jwtVersion:i.jwtVersion,lastSettingsRevision:c,lastHeartbeatOkAt:Date.now(),heartbeatAuthFails:0,relinkRequired:!1,updateRequired:!1,clockSkewDetected:!1,timeZone:n,bonusActive:i.bonusActive??!1,...i.bonusResetAt!==void 0?{bonusResetAt:i.bonusResetAt}:{},...i.latestPluginVersion?{latestPluginVersion:i.latestPluginVersion}:{},...Array.isArray(i.allowedFilters)?{allowedFilters:i.allowedFilters.map(ke)}:{}};if(u)try{await Ge(),h.lastSettingsRevision=a}catch{}if(!await jt(e,h))return T();if(process.env.TOKMIZER_SELF_UPDATE_CHILD!=="1")try{let{maybeSpawnSelfUpdate:b}=await Promise.resolve().then(()=>(hr(),pr));b()}catch{}(u||l)&&await Fn(),await jn(t,u||l);try{let{flushTelemetry:b}=await Promise.resolve().then(()=>(xr(),Mo)),{flush:k}=await Promise.resolve().then(()=>(Fo(),Lo));await b(t),await k(t)}catch{}return h}var Cl=5*6e4;function $l(){return process.env.TOKMIZER_BASE_URL??"https://tokmizer.com"}async function Zo(t){let e=await Q(),r=Et(),n={pluginVersion:V,timeZone:r,...e},s=await z("POST","/api/v1/license/enroll",n,{baseUrl:t,fingerprint:e.fingerprint,installId:e.installId,timeoutMs:4e3});if(!s.ok)throw new Error(`enroll failed ${s.status}`);let o=await Te(s),i={token:o.token,jwt:o.jwt,signingSecret:o.signingSecret,plan:o.plan,status:o.status,trialEndsAt:o.trialEndsAt,subEndsAt:o.subEndsAt,jwtVersion:o.jwtVersion,installId:e.installId,fingerprint:e.fingerprint,pluginVersion:V,email:"",timeZone:r,bonusActive:!1,linked:!1,lastHeartbeatOkAt:Date.now(),...Array.isArray(o.allowedFilters)&&o.allowedFilters.length>0?{allowedFilters:o.allowedFilters.map(ke)}:{}};return await nr(i),await Fn(),await jn(t,!0),i}function Pl(){let t=process.env.CI;return t&&t!=="false"&&t!=="0"?!0:!!process.env.GITHUB_ACTIONS}async function he(t){let e=await T();if(e)return e;if(Pl())return null;let r=Kr();try{let n=await Sl(r,"utf8"),s=Number(n);if(Number.isFinite(s)&&Date.now()-s<Cl)return null}catch{}try{return await Zo(t??$l())}catch{return await El(y(),{recursive:!0}),await Uo(r,String(Date.now()),{mode:384}),null}}pe();import Il from"node:readline/promises";import{stdin as Dl,stdout as Z}from"node:process";function Er(t,e=!1){return!0}pe();function Ol(){let t=Number(process.env.TOKMIZER_OFFLINE_GRACE_MS);return Number.isFinite(t)&&t>0?t:6048e5}function Ho(t,e=Date.now()){let r=t.lastHeartbeatOkAt;if(typeof r=="number"&&e-r>Ol())return!0;if(t.subEndsAt){let n=Date.parse(t.subEndsAt);if(Number.isFinite(n)&&e>n)return!0}return!1}function Tr(t,e=Date.now()){return t.plan}function Ar(t,e=Date.now()){return t.bonusActive??!1}var Nl={enabled:!0,outputVerbosity:"compact",filters:{enableAll:!0,disabled:[]}},Ml=`
|
|
39
39
|
Help improve Tokmizer
|
|
40
40
|
We can collect the NAME of the commands you run, like "git" or "docker",
|
|
41
41
|
and whether we managed to compress them. Never their arguments, your output,
|
|
@@ -43,129 +43,129 @@ your file paths, or anything inside them. It just shows us which commands to
|
|
|
43
43
|
optimize next, so you save even more over time. You can change this anytime
|
|
44
44
|
in your settings.
|
|
45
45
|
|
|
46
|
-
`;async function
|
|
46
|
+
`;async function Ll(t){return Z.write(Ml),Un(t,"Share anonymous command names to help improve filters?",!0)}async function Bo(t,e,r){let n=(await t.question(`${e} [${r}]: `)).trim();return n.length===0?r:n}async function Un(t,e,r){let n=r?"Y/n":"y/N",s=(await t.question(`${e} [${n}]: `)).trim().toLowerCase();return s===""?r:s==="y"||s==="yes"}async function Fl(t,e,r,n){let s=(await t.question(`${e} (${r.join(" / ")}) [${n}]: `)).trim().toLowerCase();return s.length===0?n:r.find(i=>i===s)??n}async function jl(t,e,r){Z.write(`
|
|
47
47
|
Let us walk through each setting. Press Enter to keep the default.
|
|
48
48
|
|
|
49
|
-
`);let n=await
|
|
49
|
+
`);let n=await Un(t,"Enable Tokmizer optimizations?",!0),s=await Fl(t,"Output verbosity",["normal","compact","minimal"],"normal"),o=await Un(t,"Enable all built-in filters?",!0),i=[];o||(i=(await Bo(t,"Comma-separated slugs to DISABLE (e.g. git,grep)","")).split(",").map(u=>u.trim()).filter(u=>u.length>0));let a={enabled:n,outputVerbosity:s,filters:{enableAll:o,disabled:i}};return Er(e,r)?Z.write(`
|
|
50
50
|
/power is available right now on this token.
|
|
51
51
|
`):e==="smart"&&Z.write(`
|
|
52
52
|
/power is included with Pro.
|
|
53
53
|
It is NOT available on this token today.
|
|
54
|
-
`),a}async function
|
|
54
|
+
`),a}async function Zn(t,e=!1){let r=Il.createInterface({input:Dl,output:Z});try{let n=e?" (bonus window active)":"";Z.write(`
|
|
55
55
|
Configure Tokmizer (current plan: ${t}${n})
|
|
56
56
|
|
|
57
57
|
`),Z.write(` 1) Recommended - sane defaults, ready to go
|
|
58
58
|
`),Z.write(` 2) Custom - walk through each option
|
|
59
59
|
|
|
60
|
-
`);let o=await
|
|
60
|
+
`);let o=await Bo(r,"Choose 1 or 2","1")==="2"?await jl(r,t,e):{...Nl},i=await Ll(r),a={...o,telemetryOptIn:i};Z.write(`
|
|
61
61
|
Saving...
|
|
62
|
-
`);let c=await
|
|
62
|
+
`);let c=await Ae(a);await Ke(!1),Z.write(`Done.
|
|
63
63
|
`),Z.write(`YOLO: off (this machine only)
|
|
64
64
|
`),Z.write(`${JSON.stringify(c.settings,null,2)}
|
|
65
65
|
`),Z.write(`
|
|
66
66
|
You can re-run this any time with: tkr settings configure
|
|
67
67
|
`),Z.write((await T())?.linked===!1?`These settings are saved only on this machine.
|
|
68
68
|
`:`Or edit at: https://tokmizer.com/dashboard/settings
|
|
69
|
-
`)}finally{r.close()}}async function
|
|
70
|
-
`);return}let r=
|
|
69
|
+
`)}finally{r.close()}}async function Vo(){let t=await Ge(),e=await T(),r=e?Tr({...e,plan:t.plan}):t.plan,n=e?Ar(e):!1;await Zn(r,n)}Nr();async function ri(t){let e=await T();if(e){G.write(B.activated(e.plan)+`
|
|
70
|
+
`);return}let r=ti.createInterface({input:Yn,output:G}),n=null,s=!1;try{G.write(`${B.welcome}
|
|
71
71
|
${B.needToken}
|
|
72
72
|
${B.getToken}
|
|
73
73
|
|
|
74
|
-
`);let o=(await r.question(`${B.askToken} `)).trim();
|
|
75
|
-
`);let i=await
|
|
76
|
-
`),n=i.plan,s=i.bonusActive??!1}catch(o){let i=o instanceof Error?o.message:String(o);
|
|
77
|
-
`),process.exitCode=1}finally{r.close()}n&&(await
|
|
78
|
-
`);let n=Kl
|
|
79
|
-
`):s==="missing"&&
|
|
80
|
-
${ge()}`)}}finally{t.close()}}}catch{}try{let{connectDaemon:t}=await Promise.resolve().then(()=>(pt(),mt)),e=await t();await e.ping(),e.close(),
|
|
81
|
-
`)}catch{
|
|
82
|
-
`)}
|
|
74
|
+
`);let o=(await r.question(`${B.askToken} `)).trim();G.write(`${B.activating}
|
|
75
|
+
`);let i=await Sr({token:o,baseUrl:t});G.write(B.activated(i.plan)+`
|
|
76
|
+
`),n=i.plan,s=i.bonusActive??!1}catch(o){let i=o instanceof Error?o.message:String(o);G.write(`${i}
|
|
77
|
+
`),process.exitCode=1}finally{r.close()}n&&(await Zn(n,s),await Jl())}async function Jl(){try{if(Yn.isTTY){let t=ti.createInterface({input:Yn,output:G});try{let e=(await t.question("Also optimize your commands outside the agent (terminal)? [y/N] ")).trim().toLowerCase();if(e==="y"||e==="yes"){let r=await We(ue());G.write(`Installed ${r.length} shims.
|
|
78
|
+
`);let n=Gl(Kl.homedir(),(process.env.SHELL??"").includes("zsh")?".zshrc":".bashrc"),s=await Zt(n);s==="added"?G.write(`Added PATH to ${n}. Open a new terminal.
|
|
79
|
+
`):s==="missing"&&G.write(`Add this to your shell rc:
|
|
80
|
+
${ge()}`)}}finally{t.close()}}}catch{}try{let{connectDaemon:t}=await Promise.resolve().then(()=>(pt(),mt)),e=await t();await e.ping(),e.close(),G.write(` Engine: \u2705 active
|
|
81
|
+
`)}catch{G.write(` Engine: starts on first use
|
|
82
|
+
`)}G.write(`
|
|
83
83
|
\u2705 Ready. tokmizer optimizes your commands automatically.
|
|
84
84
|
Run "tkr gain" anytime to see your savings.
|
|
85
|
-
`)}pe();ut();
|
|
86
|
-
`).filter(u=>u.trim()!==""),o=s.length,i=0;for(;o>0;){let u=Buffer.byteLength(s[o-1])+1;if(i+u>r)break;i+=u,o-=1}let a=
|
|
85
|
+
`)}pe();ut();Be();Ve();Kn();D();import{readFile as ai,rm as si}from"node:fs/promises";import{appendFileSync as Yl,chmodSync as ql,mkdirSync as Xl,readFileSync as ci,renameSync as ui,rmSync as li,statSync as di,writeFileSync as Qn}from"node:fs";import{dirname as Ql,join as fi}from"node:path";var qn={anthropic:3,openai:2.5,google:2,vertex:3.3,bedrock:3.5,openrouter:3.5},Wl={"claude-code":"anthropic",codex:"openai",copilot:"openai","gemini-cli":"google",cursor:"anthropic",windsurf:"anthropic",cline:"anthropic",aider:"anthropic",shell:"anthropic"};function ni(t){return t?Wl[t]??"anthropic":"anthropic"}function Xn(t){let e=0,r=0;for(let n of Object.keys(t)){let s=t[n]??0;s<=0||(e+=s,r+=s/1e6*(qn[n]??qn.anthropic))}return e<=0?qn.anthropic:r/(e/1e6)}var ed="stats.jsonl",td="stats-ledger.json",oi=2*1024*1024,rd=3e4;function Lr(){return{n:0,nc:0,r:0,f:0,or:0,of:0,x:0,sn:0,sr:0,sf:0,mr:0,mf:0,rn:0,rb:0,tn:0,tr:0,tf:0,t0:null,t1:null,cmds:{},prov:{}}}function mi(t){let e=t.trim();if(!e)return null;try{let r=JSON.parse(e);return typeof r.t!="number"||!Number.isFinite(r.t)||r.t<0||r.t>864e10||typeof r.r!="number"||!Number.isSafeInteger(r.r)||r.r<0||typeof r.f!="number"||!Number.isSafeInteger(r.f)||r.f<0||r.r+r.f===0?null:{t:r.t,r:r.r,f:r.f,m:r.m===1,...typeof r.h=="string"?{h:r.h}:{},...typeof r.k=="string"?{k:r.k}:{},...typeof r.c=="string"&&r.c?{c:r.c}:{}}}catch{return null}}function pi(t,e){if(e.m){t.mr+=e.r,t.mf+=e.f;return}if(e.k==="restore"&&(t.rn+=1,t.rb+=e.f),t.n+=1,t.or+=e.r,t.of+=e.f,e.f>e.r&&(t.x+=1),e.h==="shell"&&(t.tn+=1,t.tr+=e.r,t.tf+=e.f),t.t0=t.t0==null?e.t:Math.min(t.t0,e.t),t.t1=t.t1==null?e.t:Math.max(t.t1,e.t),e.c){let r=t.cmds[e.c]??{n:0,nc:0,r:0,f:0,sh:!1};r.n+=1,e.f<e.r&&(r.nc+=1,r.rr=(r.rr??0)+e.r,r.rf=(r.rf??0)+e.f),(e.k==="sh"||e.k==="restore")&&(r.sh=!0),r.r+=e.r,r.f+=e.f,t.cmds[e.c]=r}if(e.f<e.r){t.nc+=1,t.r+=e.r,t.f+=e.f,e.k==="sh"&&(t.sn+=1,t.sr+=e.r,t.sf+=e.f);let r=ni(e.h),n=t.prov[r]??{r:0,f:0};n.r+=e.r,n.f+=e.f,t.prov[r]=n}}function nd(t,e){for(let r of["n","nc","r","f","or","of","x","sn","sr","sf","mr","mf","rn","rb","tn","tr","tf"])t[r]+=e[r];e.t0!=null&&(t.t0=t.t0==null?e.t0:Math.min(t.t0,e.t0)),e.t1!=null&&(t.t1=t.t1==null?e.t1:Math.max(t.t1,e.t1));for(let[r,n]of Object.entries(e.cmds)){let s=t.cmds[r]??{n:0,nc:0,r:0,f:0,sh:!1};s.n+=n.n,s.nc+=n.nc,s.r+=n.r,s.f+=n.f,s.rr=(s.rr??0)+(n.rr??0),s.rf=(s.rf??0)+(n.rf??0),s.sh=s.sh||n.sh,t.cmds[r]=s}for(let[r,n]of Object.entries(e.prov)){let s=t.prov[r]??{r:0,f:0};s.r+=n.r,s.f+=n.f,t.prov[r]=s}}function es(t){let e=new Date(t*1e3);return`${e.getFullYear()}-${String(e.getMonth()+1).padStart(2,"0")}-${String(e.getDate()).padStart(2,"0")}`}function rs(t){return fi(Ql(t),td)}function hi(t){let e=rs(t),r;try{r=ci(e,"utf8")}catch{return{}}try{let n=JSON.parse(r);if(!n.days||typeof n.days!="object")throw new Error("invalid ledger");let s={};for(let[o,i]of Object.entries(n.days))!/^\d{4}-\d{2}-\d{2}$/.test(o)||!i||typeof i!="object"||(s[o]={...Lr(),...i});return s}catch{try{ui(e,`${e}.corrupt-${Date.now()}`)}catch{}return{}}}function ii(t,e){let r=`${t}.tmp-${process.pid}`;Qn(r,e,{mode:384}),ui(r,t)}function sd(t){try{return Qn(t,String(process.pid),{flag:"wx",mode:384}),!0}catch{}try{return Date.now()-di(t).mtimeMs<rd?!1:(li(t,{force:!0}),Qn(t,String(process.pid),{flag:"wx",mode:384}),!0)}catch{return!1}}function od(t,e=oi,r=oi/2){try{if(di(t).size<=e)return}catch{return}let n=`${t}.lock`;if(sd(n))try{let s=ci(t,"utf8").split(`
|
|
86
|
+
`).filter(u=>u.trim()!==""),o=s.length,i=0;for(;o>0;){let u=Buffer.byteLength(s[o-1])+1;if(i+u>r)break;i+=u,o-=1}let a=hi(t);for(let u of s.slice(0,o)){let l=mi(u);if(!l)continue;let h=es(l.t),b=a[h]??Lr();pi(b,l),a[h]=b}let c=s.slice(o);ii(t,c.length?`${c.join(`
|
|
87
87
|
`)}
|
|
88
|
-
`:""),
|
|
89
|
-
`)){let i=
|
|
90
|
-
`).filter(n=>n.trim()!=="").length;return await
|
|
91
|
-
`;try{
|
|
92
|
-
Watch this session live: tkr session`;let r=t.observed?.savedTokens??t.savedTokens,n=
|
|
93
|
-
`)}async function
|
|
94
|
-
`)}D();
|
|
95
|
-
`).filter(r=>r.trim()!=="").length;return
|
|
96
|
-
`).filter(o=>o.trim()!=="")}catch{return{sessionId:null,total:0,routed:0,pct:0}}e.length>
|
|
97
|
-
`)}
|
|
98
|
-
`))}async function
|
|
88
|
+
`:""),ii(rs(t),JSON.stringify({v:1,days:a}))}catch{return}finally{li(n,{force:!0})}}async function gi(t,e){let r=e>0?es(e):"",n=new Map;for(let[o,i]of Object.entries(hi(t)))o>=r&&n.set(o,i);let s="";try{s=await ai(t,"utf8")}catch{}for(let o of s.split(`
|
|
89
|
+
`)){let i=mi(o);if(!i||i.t<e)continue;let a=es(i.t),c=n.get(a)??Lr();pi(c,i),n.set(a,c)}return n}function Fr(){return fi(y(),ed)}async function yi(t=Fr()){try{let r=(await ai(t,"utf8")).split(`
|
|
90
|
+
`).filter(n=>n.trim()!=="").length;return await si(t,{force:!0}),await si(rs(t),{force:!0}),r}catch{return 0}}function wi(t,e,r=Fr(),n=!1,s,o,i){if(!Number.isSafeInteger(t)||!Number.isSafeInteger(e)||t<0||e<0||t+e===0)return;let a=s?`,"h":${JSON.stringify(s)}`:"",c=o?`,"k":${JSON.stringify(o)}`:"",u=i?`,"c":${JSON.stringify(i.slice(0,24))}`:"",l=`{"t":${Math.floor(Date.now()/1e3)},"r":${t},"f":${e}${n?',"m":1':""}${a}${c}${u}}
|
|
91
|
+
`;try{Xl(y(),{recursive:!0,mode:448}),Yl(r,l,{mode:384}),ql(r,384),od(r)}catch{return}}function C(t){return Math.ceil(t/4)}function vi(t){if(!t.count)return null;let e=Math.round(t.compressedCount/t.count*100),r=(t.byCommand??[]).filter(s=>!s.native&&s.compressedCount===0).sort((s,o)=>o.count-s.count).slice(0,3).map(s=>s.cmd),n=r.length?` \xB7 top unchanged: ${r.join(", ")}`:"";return`${e}% of recorded outputs reduced (${t.compressedCount}/${t.count})${n}`}async function Ye(t=Fr(),e=0){let r=Lr();for(let P of(await gi(t,e)).values())nd(r,P);let n=C(r.r),s=C(r.f),o=Math.max(0,n-s),i=n?Math.round(o/n*100):0,a=Math.floor(Date.now()/1e3),c=r.t0!=null?Math.max(1,Math.ceil((a-r.t0)/86400)):1,u=Math.max(0,C(r.mr)-C(r.mf)),l={};for(let[P,A]of Object.entries(r.prov))l[P]=Math.max(0,C(A.r)-C(A.f));let h=Object.entries(r.cmds).map(([P,A])=>{let R=C(A.r),se=R-C(A.f),oe=C(A.rr??0),Vt=oe?Math.round((oe-C(A.rf??0))/oe*100):0;return{cmd:P,count:A.n,compressedCount:A.nc,savedTokens:se,avgPct:R?Math.round(se/R*100):0,reducedPct:Vt,native:!A.sh}}).sort((P,A)=>A.savedTokens-P.savedTokens).slice(0,10),b=C(r.sr),k=b?Math.round((b-C(r.sf))/b*100):0,$=C(r.or),O=C(r.of);return{count:r.n,compressedCount:r.nc,rawTokens:n,filteredTokens:s,savedTokens:o,modeledSavedTokens:u,savedPct:i,sinceDays:c,savedByProvider:l,shellCompressedCount:r.sn,shellSavedPct:k,byCommand:h,observed:{count:r.n,rawTokens:$,filteredTokens:O,savedTokens:$-O,savedPct:r.or?Math.round((r.or-r.of)/r.or*1e4)/100:null,expandedCount:r.x},agent:{count:r.n-r.tn,rawTokens:C(r.or-r.tr),filteredTokens:C(r.of-r.tf),savedPct:r.or-r.tr?Math.round((r.or-r.tr-(r.of-r.tf))/(r.or-r.tr)*1e4)/100:null},terminal:{count:r.tn,rawTokens:C(r.tr),savedTokens:C(r.tr)-C(r.tf)},restoration:{count:r.rn,tokens:C(r.rb)},window:{firstAt:r.t0,lastAt:r.t1},measurement:{scope:"tool-output",legacyScope:"reduced-outputs",tokenMethod:"bytes/4",tokenCounts:"estimated",billing:"not-measured"}}}function H(t){return t<0?`-${H(-t)}`:t>=1e6?(t/1e6).toFixed(1)+"M":t>=1e3?(t/1e3).toFixed(1)+"K":String(t)}function bi(t){return t<0?`-${bi(-t)}`:t>0&&t<.01?"<$0.01":`$${t.toFixed(2)}`}function ee(t){return String(t).replace(/\B(?=(\d{3})+(?!\d))/g,",")}var ki="\x1B[38;2;245;176;65m",_i="\x1B[0m",Mr=32;function ts(t,e){let r="\u2588".repeat(t);return e?`${ki}${r}${_i}`:r}function xi(t,e){if(t.count===0)return` No data yet. Run a few commands to measure your output savings.
|
|
92
|
+
Watch this session live: tkr session`;let r=t.observed?.savedTokens??t.savedTokens,n=bi(r/1e6*e.pricePerMtok),s=H(t.rawTokens)+" tokens",o=H(t.filteredTokens)+" tokens",i=Mr,a=t.rawTokens>0?Math.max(1,Math.round(Mr*(t.filteredTokens/t.rawTokens))):1,c=" ".repeat(Mr-i),u=" ".repeat(Mr-a),l=" tokmizer \xB7 output savings",h=e.subtitle??"all time",b=" "+"\u2500".repeat(61),k=t.observed,$=k?.savedPct!=null?k.savedPct<0?`+${Math.abs(k.savedPct)}`:`${k.savedPct}`:null,O=t.window,P=R=>new Date(R*1e3).toISOString().slice(0,16).replace("T"," "),A=t.count-t.compressedCount-(k?.expandedCount??0);return[`${l}${" ".repeat(Math.max(2,40-l.length))}${h}`,b,"",` ${r>=0?"Saved":"Added"} ${H(Math.abs(r))} estimated tokens in tool output`,"",...e.periods?.length?[...e.periods.map(R=>` ${R.label.padEnd(12)}${(H(R.savedTokens)+" saved").padStart(14)} \xB7 ${ee(R.count)} commands`),""]:[],...t.compressedCount>0?[` ${t.savedPct} % on reduced outputs \xB7 ${ee(t.compressedCount)} commands`,` ${"Without tokmizer".padEnd(16)} ${ts(i,e.color)}${c} ${s}`,` ${"With tokmizer".padEnd(16)} ${ts(a,e.color)}${u} ${o}`]:[],...t.shellCompressedCount?[` Shell: ${t.shellSavedPct} % on reduced shell outputs \xB7 ${ee(t.shellCompressedCount)} commands`]:[],...k&&!t.terminal?.count?[...$!=null?[` ${$} % across all observed outputs${k.savedPct<0?" (increase)":" (reduction)"}`]:[],` ${H(k.rawTokens)} \u2192 ${H(k.filteredTokens)} estimated tokens across ${ee(k.count)} commands`]:[],...t.agent&&t.terminal?.count?[...t.agent.savedPct!=null?[` ${Math.abs(t.agent.savedPct)} % across agent tool outputs${t.agent.savedPct<0?" (increase)":" (reduction)"}`]:[],` ${H(t.agent.rawTokens)} \u2192 ${H(t.agent.filteredTokens)} estimated tokens across ${ee(t.agent.count)} agent commands`,` Terminal, no agent detected: ${H(t.terminal.savedTokens)} saved across ${ee(t.terminal.count)} commands, shown apart`]:[],...t.restoration?.count?[` Restored: ${H(t.restoration.tokens)} estimated tokens across ${ee(t.restoration.count)} calls, deducted above`]:[],"",` API equivalent: ${n} at reference $${e.pricePerMtok.toFixed(2)}/M input tokens`," Estimate only, not your bill. Model, caching and subscription change the cost.",...t.modeledSavedTokens>0?[` Reducer (est.): ${H(t.modeledSavedTokens)} tokens modeled separately, excluded above`]:[],...id(t.byCommand,e.color),"",` ${ee(t.compressedCount)} of ${ee(t.count)} recorded commands reduced \xB7 ${ee(A)} unchanged${k?.expandedCount?` \xB7 ${ee(k.expandedCount)} expanded`:""}`,...O?.firstAt!=null&&O.lastAt!=null?[` Observed: ${P(O.firstAt)} \u2192 ${P(O.lastAt)} UTC`]:[]," Tokens estimated from output bytes / 4; prompts, replies and replayed context are not counted."," Percentages measure bytes, not tokenizer counts. Restorations before this update are not deducted."," Inspect retained output: tkr restore",""].join(`
|
|
93
|
+
`)}async function Si(t=Fr(),e=0){return[...(await gi(t,e)).entries()].filter(([,r])=>r.n>0).sort(([r],[n])=>r<n?-1:r>n?1:0).map(([r,n])=>({day:r,count:n.n,savedTokens:C(n.or)-C(n.of)}))}function id(t,e){let r=(t??[]).filter(o=>o.savedTokens>0).slice(0,8);if(r.length===0)return[];let n=r[0].savedTokens,s=[""," By command \xB7 reduced/runs \xB7 % when reduced \xB7 % over all runs"," "+"\u2500".repeat(70)];for(let o of r){let i=Math.max(1,Math.round(o.savedTokens/n*10)),a=ts(i,e)+"\u2591".repeat(10-i),c=o.native?`${o.cmd} (native)`:o.cmd,u=`${o.compressedCount}/${o.count}`;s.push(` ${c.padEnd(24)} ${u.padStart(7)} ${(H(o.savedTokens)+" saved").padStart(13)} ${String(o.reducedPct??o.avgPct).padStart(3)} % ${String(o.avgPct).padStart(3)} % ${a}`)}return s}function Ei(t,e){if(t.length===0)return"";let r=(u,l,h)=>` ${u.padEnd(11)}${ee(l).padStart(4)}${H(h).padStart(13)}`,n=" "+"Day".padEnd(11)+"Cmds".padStart(4)+"Saved".padStart(13),s=" "+"\u2500".repeat(31),o=t.map(u=>r(`${u.day.slice(8,10)}/${u.day.slice(5,7)}`,u.count,u.savedTokens)),i=t.reduce((u,l)=>u+l.count,0),a=t.reduce((u,l)=>u+l.savedTokens,0),c=r("Total",i,a);return[n,s,...o,s,e.color?`${ki}${c}${_i}`:c,""].join(`
|
|
94
|
+
`)}D();vn();import{appendFileSync as yh,chmodSync as wh,mkdirSync as vh,existsSync as ad,readFileSync as Ri,rmSync as cd}from"node:fs";import{dirname as kh,join as ud}from"node:path";var ld="usage.jsonl",Ti=2e4,Sh=2*1024*1024;function Ci(){return ud(y(),ld)}function $i(t=Ci()){try{if(!ad(t))return 0;let e=Ri(t,"utf8").split(`
|
|
95
|
+
`).filter(r=>r.trim()!=="").length;return cd(t,{force:!0}),e}catch{return 0}}function Ai(t){let e=t.trim();if(!e)return null;try{let r=JSON.parse(e);return typeof r.t!="number"||typeof r.s!="string"||typeof r.o!="number"?null:{s:r.s,o:r.o}}catch{return null}}function Pi(t=Ci()){let e;try{e=Ri(t,"utf8").split(`
|
|
96
|
+
`).filter(o=>o.trim()!=="")}catch{return{sessionId:null,total:0,routed:0,pct:0}}e.length>Ti&&(e=e.slice(e.length-Ti));let r=null;for(let o=e.length-1;o>=0;o-=1){let i=Ai(e[o]??"");if(i){r=i.s;break}}if(r===null)return{sessionId:null,total:0,routed:0,pct:0};let n=0,s=0;for(let o of e){let i=Ai(o);!i||i.s!==r||(n+=1,i.o===1&&(s+=1))}return{sessionId:r,total:n,routed:s,pct:n?Math.round(s/n*100):0}}function Oi(t){return t.total===0?" No commands yet this session.":[" This session"," "+"\u2500".repeat(40),` ${t.total} commands \xB7 ${t.routed} handled by tkr (${t.pct} %)`," The rest (cd, echo\u2026) has nothing to optimize.",""].join(`
|
|
97
|
+
`)}kr();xr();Pt();Nr();xn();import{fileURLToPath as Md}from"node:url";var J=process.env.TOKMIZER_BASE_URL??"https://tokmizer.com";function Ld(){process.stdout.write(["Usage: tkr <command>",""," link link your account (optional; paste your key)"," link <key> link without prompts"," link --shim [--shim-runner P] install shell-shims (universal compat)"," unlink unlink this machine from your account"," status show current plan + status"," gain [--day|--week|--month|--json] estimated tool-output savings (today / 7 days / 30 days / all time)"," session this session's tkr coverage"," restore <hash> re-fetch the full output behind a [tkr restore \u2026] hint"," discover what's covered (agent + terminal)"," setup-codex one-command setup for OpenAI Codex"," auto-update [on|off|status] keep the tkr CLI up to date on its own (on by default)"," doctor print detected host, OS, adapter"," shim install [--runner P] install shell-shims into ~/.tokmizer/shims"," shim uninstall remove shell-shims"," heartbeat refresh JWT + bundle"," settings show print current settings"," settings set <key> <value> update one setting (key uses dot path, e.g. filters.enableAll true)"," settings configure interactive wizard (recommended or custom)"," settings reset reset all settings to defaults"," compression [level] show or set compression level (light, balanced, max)"," yolo [on|off|status] local aggressive output reduction; content can be lost"," reducer [level] show or set response reducer (off, light, balanced, max)"," telemetry status show telemetry on/off + local record count"," telemetry on | off turn anonymous telemetry on or off"," telemetry forget erase telemetry data stored on this machine",""].join(`
|
|
98
|
+
`))}async function Fd(t){let e=t[0]??"show";if(e==="show"){try{let r=await Ge();process.stdout.write(`Plan: ${r.plan}
|
|
99
99
|
`),process.stdout.write(`${JSON.stringify(r.settings,null,2)}
|
|
100
100
|
`)}catch(r){process.stdout.write(`Settings unavailable; showing local cached settings: ${r instanceof Error?r.message:String(r)}
|
|
101
101
|
`),process.stdout.write(`${JSON.stringify(await U(),null,2)}
|
|
102
102
|
`)}return}if(e==="set"){let r=t[1],n=t[2];if(!r||n===void 0){process.stderr.write(`Usage: tkr settings set <key> <value>
|
|
103
|
-
`),process.exitCode=1;return}let s=
|
|
103
|
+
`),process.exitCode=1;return}let s=so(r,n),o=await Ae(s);process.stdout.write(`Updated. ${r} = ${JSON.stringify(n)}
|
|
104
104
|
`),process.stdout.write(`Current: ${JSON.stringify(o.settings,null,2)}
|
|
105
|
-
`);return}if(e==="configure"){await
|
|
105
|
+
`);return}if(e==="configure"){await Vo();return}if(e==="reset"){let r=await Ae({enabled:!0,telemetryOptIn:!0,outputVerbosity:"compact",reducer:"off",filters:{enableAll:!0,disabled:[]}});await Ke(!1),process.stdout.write(`Settings reset to defaults.
|
|
106
106
|
`),process.stdout.write(`YOLO: off (this machine only)
|
|
107
107
|
`),process.stdout.write(`${JSON.stringify(r.settings,null,2)}
|
|
108
108
|
`);return}process.stderr.write(`Unknown settings subcommand: ${e}
|
|
109
|
-
`),process.exitCode=1}async function
|
|
109
|
+
`),process.exitCode=1}async function jd(t){let e=t[0]??"status";if(e==="on"||e==="off"){let r=e==="on";try{let n=await Ae({telemetryOptIn:r});process.stdout.write(`Telemetry ${n.settings.telemetryOptIn?"on":"off"}.
|
|
110
110
|
`)}catch(n){process.stdout.write(`${n instanceof Error?n.message:String(n)}
|
|
111
|
-
`),process.exitCode=1}return}if(e==="forget"){Lt("telemetry"),Lt("learn");let r=await
|
|
112
|
-
`);return}if(e==="status"){let r;try{r=(await
|
|
111
|
+
`),process.exitCode=1}return}if(e==="forget"){Lt("telemetry"),Lt("learn");let r=await yi()+$i();process.stdout.write(`Cleared ${r} local telemetry record${r===1?"":"s"} from this machine.
|
|
112
|
+
`);return}if(e==="status"){let r;try{r=(await Ge()).settings.telemetryOptIn?"on":"off"}catch{r=`${(await U()).telemetryOptIn?"on":"off"} (offline; last known)`}let n=await Ye();process.stdout.write(`Telemetry: ${r}
|
|
113
113
|
${n.count} commands recorded locally.
|
|
114
114
|
Manage: tkr telemetry on | off | forget
|
|
115
115
|
`);return}process.stderr.write(`Unknown telemetry subcommand: ${e}
|
|
116
|
-
`),process.exitCode=1}async function
|
|
116
|
+
`),process.exitCode=1}async function zd(){let t=process.argv[2]??"help",e=process.argv.slice(3);if(t==="yolo"){let r=e[0]??"status";if(e.length>1||!["on","off","status"].includes(r)){process.stderr.write(`Usage: tkr yolo [on|off|status]
|
|
117
117
|
`),process.exitCode=1;return}r==="on"?(process.stderr.write(`Warning: YOLO can discard content and diagnostics. Lost output cannot be restored; command exit codes are preserved.
|
|
118
|
-
`),await
|
|
119
|
-
`);return}if(t==="init"||t==="link"){if(t==="init"&&process.stdout.write("`tkr init` is now `tkr link`. Running link...\n"),e.includes("--shim")){let i=e.indexOf("--shim-runner"),a=i>=0?e[i+1]:
|
|
118
|
+
`),await Ke(!0)):r==="off"&&await Ke(!1),process.stdout.write(`YOLO: ${lt()?"on":"off"} (this machine only)
|
|
119
|
+
`);return}if(t==="init"||t==="link"){if(t==="init"&&process.stdout.write("`tkr init` is now `tkr link`. Running link...\n"),e.includes("--shim")){let i=e.indexOf("--shim-runner"),a=i>=0?e[i+1]:ue(),c=await We(a??ue());process.stdout.write(`Installed ${c.length} shims into ${N()}
|
|
120
120
|
`),process.stdout.write(`Add this line to your shell rc if not already:
|
|
121
121
|
${ge()}`);return}let r=e.indexOf("--email"),n=e.indexOf("--token"),s=e.find(i=>i.startsWith("tokmizer_")),o=n>=0?e[n+1]??"":s??"";if(e.length>0){if(!o){process.stdout.write(`Usage: tkr link <key> (the key from tokmizer.com/dashboard/token, starts with tokmizer_)
|
|
122
|
-
`),process.exitCode=1;return}let i=r>=0?e[r+1]:"";try{let a=await
|
|
122
|
+
`),process.exitCode=1;return}let i=r>=0?e[r+1]:"";try{let a=await Sr({token:o,baseUrl:J,...i?{email:i}:{}});process.stdout.write(B.activated(a.plan)+`
|
|
123
123
|
`),process.stdout.write(`Review this account's settings: tkr settings show. Adjust them with: tkr settings configure
|
|
124
|
-
`);let c=await
|
|
124
|
+
`);let c=await ar();c?.error&&process.stdout.write(`Note: feature sync failed (${c.error}). Run "tkr heartbeat" to retry.
|
|
125
125
|
`)}catch(a){process.stdout.write(`${a instanceof Error?a.message:String(a)}
|
|
126
|
-
`),process.exitCode=1}return}await
|
|
127
|
-
`);return}if(t==="doctor"){let r=
|
|
128
|
-
`),A=JSON.parse(P[P.length-1]);a.push(`Drift: ${P.length} unrecognized hook payload shape(s), last on ${A.tool??"?"} (${O})`,"")}}catch{}try{let c=
|
|
129
|
-
`));return}if(t==="auto-update"){let{autoUpdateEnabled:r,setAutoUpdate:n}=await Promise.resolve().then(()=>(
|
|
126
|
+
`),process.exitCode=1}return}await ri(J);return}if(t==="unlink"){let r=await T();if(r?.jwt&&r.signingSecret)try{let s=await Q();await z("POST","/api/v1/license/unlink",{ts:Date.now()},{baseUrl:J,bearer:r.jwt,signingSecret:r.signingSecret,fingerprint:s.fingerprint,installId:s.installId,timeoutMs:4e3})}catch{}await sr();try{await Rt([]),await Ct([])}catch{}await ro();try{let{shutdownDaemon:s}=await Promise.resolve().then(()=>(pt(),mt));await s()}catch{}let n=r?.email?` from ${r.email}`:"";process.stdout.write(`Unlinked this machine${n}. The plugin keeps working without an account; a fresh anonymous token starts on the next online run. Link another account with: tkr link
|
|
127
|
+
`);return}if(t==="doctor"){let r=Rr(),n=await zs(),{brewTapStatus:s}=await Promise.resolve().then(()=>(Mi(),Ni)),o=s(),i=o?.wedged?o.path.replace(/\/Formula\/tokmizer\.rb$/,""):null,a=[`Host: ${r.host} (source: ${r.source})`,`OS: ${r.os}`,`Arch: ${r.arch}`,`Adapter: ${Ko(r.host)}`,`Shim dir: ${N()}`,`Shim: ${Ht()?"installed":"not installed \u2014 run: tkr setup-codex"}`,`Codex: ${bn()?"hook installed":"hook not installed \u2014 run: tkr setup-codex"}`,`Commands: ${n.installed}/${n.total} unprefixed slash commands${n.installed<n.total?" \u2014 restart Claude Code to reinstall":""}`,`Restore: ${process.env.TOKMIZER_CCR_DISABLED==="1"||process.env.TOKMIZER_CCR_DISABLED==="true"?"disabled (TOKMIZER_CCR_DISABLED)":"active"}`,...i?[`Homebrew: tap clone conflicted \u2014 updates are stuck. Fix: git -C ${i} fetch origin && git -C ${i} reset --hard origin/main && brew upgrade tokmizer`]:[],""];try{let{connectDaemon:c}=await Promise.resolve().then(()=>(pt(),mt)),{socketPath:u}=await Promise.resolve().then(()=>(un(),lo)),{path:l}=u(),h=await c(),b=await h.ping();h.close(),a.push(`Daemon: running (pid ${b.pid})`,` socket: ${l}`,` uptime: ${Math.floor(b.uptimeMs/1e3)}s`,` ruleCount: ${b.ruleCount}`,` bundleVersion: ${b.bundleVersion}`,"")}catch(c){a.push(`Daemon: not running (${c.message})`,"")}try{let{readFileSync:c,existsSync:u,statSync:l}=await import("node:fs"),{join:h}=await import("node:path"),{tokmizerHome:b}=await Promise.resolve().then(()=>(D(),Ss)),k=b(),$=h(k,"daemon.spawn.fail");if(u($)){let P=Number(c($,"utf8"));a.push(` last spawn failure: ${Number.isFinite(P)?new Date(P).toISOString():"unknown"} (details: ${h(k,"daemon.log")})`)}let O=h(k,"drift.jsonl");if(u(O)&&l(O).size>0){let P=c(O,"utf8").trim().split(`
|
|
128
|
+
`),A=JSON.parse(P[P.length-1]);a.push(`Drift: ${P.length} unrecognized hook payload shape(s), last on ${A.tool??"?"} (${O})`,"")}}catch{}try{let c=vi(await Ye());c&&a.push(`Coverage: ${c}`,"")}catch{}process.stdout.write(a.join(`
|
|
129
|
+
`));return}if(t==="auto-update"){let{autoUpdateEnabled:r,setAutoUpdate:n}=await Promise.resolve().then(()=>(hr(),pr)),s=e[0]??"status";if(s==="on"||s==="off")n(s==="on");else if(s!=="status"){process.stderr.write(`Usage: tkr auto-update [on|off|status]
|
|
130
130
|
`),process.exitCode=1;return}process.stdout.write(`auto-update: ${r()?"on":"off"}
|
|
131
|
-
`);return}if(t==="self-update"){let{selfUpdate:r,defaultDeps:n}=await Promise.resolve().then(()=>(
|
|
131
|
+
`);return}if(t==="self-update"){let{selfUpdate:r,defaultDeps:n}=await Promise.resolve().then(()=>(hr(),pr)),s=await T(),o=await r(n(s?.latestPluginVersion));process.stdout.write(`${o.length?o.join(`
|
|
132
132
|
`):"up to date"}
|
|
133
|
-
`);return}if(t==="shims-refresh"){let{refreshStaleShims:r}=await Promise.resolve().then(()=>(
|
|
134
|
-
`);return}if(t==="setup-codex"){await he(
|
|
133
|
+
`);return}if(t==="shims-refresh"){let{refreshStaleShims:r}=await Promise.resolve().then(()=>(Nr(),ei)),n=await r(ue());process.stdout.write(`shims refreshed: ${n}
|
|
134
|
+
`);return}if(t==="setup-codex"){await he(J);let r=await We(ue()),n=await Dr(),s=Md(new URL("./tkr-codex-hook.js",import.meta.url)),o=await kn(_n(process.env.PATH??"",s)),i=o==="error"?`Could not update ${ht()}: it is not valid JSON. Fix it, then run tkr setup-codex again.`:`${o==="present"?"Codex hook already set":"Added the tokmizer hook"} in ${ht()}. In Codex, run /hooks once and approve it.`,a=n.status==="added"?`Added the shim path to ${n.target}.`:n.status==="present"?`Shim path already set in ${n.target}.`:`Could not update ${n.target}. Add this to your shell profile:
|
|
135
135
|
${n.manual}`;process.stdout.write([`Installed ${r.length} command shims into ${N()}.`,i,a,"","Last step: open a new terminal and restart Codex so it picks up the change.","Check coverage anytime with: tkr discover","Tokmizer is free. No account is required.",""].join(`
|
|
136
|
-
`)),(o==="error"||n.status==="missing")&&(process.exitCode=1);return}if(t==="shim"){let r=e[0]??"install";if(r==="install"){let n=e.indexOf("--runner"),s=n>=0?e[n+1]:
|
|
137
|
-
`);let i=await
|
|
136
|
+
`)),(o==="error"||n.status==="missing")&&(process.exitCode=1);return}if(t==="shim"){let r=e[0]??"install";if(r==="install"){let n=e.indexOf("--runner"),s=n>=0?e[n+1]:ue(),o=await We(s??ue());process.stdout.write(`Installed ${o.length} shims into ${N()}
|
|
137
|
+
`);let i=await Dr();if(i.status==="added"?process.stdout.write(`Added PATH to ${i.target}. Open a new terminal to activate.
|
|
138
138
|
`):i.status==="present"?process.stdout.write(`PATH already set in ${i.target}. Open a new terminal if not active.
|
|
139
139
|
`):process.stdout.write(`Add this to your shell profile, then open a new terminal:
|
|
140
|
-
${i.manual}`),i.status==="missing"){process.exitCode=1;return}let a=await T()??await he(
|
|
140
|
+
${i.manual}`),i.status==="missing"){process.exitCode=1;return}let a=await T()??await he(J);process.stdout.write(a?`Free access is ready. No account is required.
|
|
141
141
|
`:`Free activation is pending. When online, run: tkr status
|
|
142
|
-
`);return}if(r==="uninstall"){let n=await
|
|
142
|
+
`);return}if(r==="uninstall"){let n=await Wn();process.stdout.write(`Removed ${n} shims from ${N()}
|
|
143
143
|
`);return}process.stderr.write(`Unknown shim subcommand: ${r}
|
|
144
144
|
`),process.exitCode=1;return}if(t==="status"){process.stdout.write(`YOLO: ${lt()?"on":"off"} (this machine only)
|
|
145
|
-
`);let r=await T()??await he(
|
|
146
|
-
`);return}let n=
|
|
145
|
+
`);let r=await T()??await he(J);if(!r){process.stdout.write(`Free tier starts automatically on the first online run. Could not reach tokmizer.com right now. Retry later, or run: tkr link
|
|
146
|
+
`);return}let n=Er(Tr(r),Ar(r));if(process.stdout.write(`Plan ${r.plan} | Status ${r.status}${r.email?` | Email ${r.email}`:r.plan==="free"?" | Anonymous":""}
|
|
147
147
|
`),process.stdout.write(`power: ${n?"available":"locked"}
|
|
148
|
-
`),n){let s=await
|
|
149
|
-
`)}}
|
|
148
|
+
`),n){let s=await en("power"),o=await cr("power")!==null;if(!s||!o){let i=await ar(),a=i?.error?` (last sync failed: ${i.error})`:"";process.stdout.write(`/power not synced yet${a} \u2014 run: tkr heartbeat
|
|
149
|
+
`)}}Ho(r)&&process.stdout.write(`Offline too long \u2014 reconnect (tkr heartbeat) to refresh your local state.
|
|
150
150
|
`),process.stdout.write(`Everything is included on this token.
|
|
151
151
|
`);return}if(t==="gain"){let r=e[0]??"";if(e.length>1||!["","--json","--jour","--day","--semaine","--week","--mois","--month"].includes(r)){process.stderr.write(`Usage: tkr gain [--day|--week|--month|--json]
|
|
152
|
-
`),process.exitCode=1;return}let n=0,s,o=!1;if(r==="--json"){let[R,se]=await Promise.all([
|
|
153
|
-
`);return}let i=new Date,a=R=>Math.floor(new Date(i.getFullYear(),i.getMonth(),i.getDate()-R).getTime()/1e3);r==="--jour"||r==="--day"?(n=a(0),s="today"):r==="--semaine"||r==="--week"?(n=a(6),s="last 7 days",o=!0):(r==="--mois"||r==="--month")&&(n=a(29),s="last 30 days",o=!0);let[c,u,l,
|
|
154
|
-
`+
|
|
152
|
+
`),process.exitCode=1;return}let n=0,s,o=!1;if(r==="--json"){let[R,se]=await Promise.all([Ye(void 0,0),T()]),oe=Xn(R.savedByProvider);process.stdout.write(JSON.stringify({...R,savedUsd:Number((R.savedTokens/1e6*oe).toFixed(2)),savedUsdBasis:"reference-input-price",savedUsdScope:"reduced-outputs",netSavedUsd:Number(((R.observed?.savedTokens??R.savedTokens)/1e6*oe).toFixed(2)),netSavedUsdScope:"all-observed-outputs",referencePricePerMtok:oe,plan:se?.plan??"free"})+`
|
|
153
|
+
`);return}let i=new Date,a=R=>Math.floor(new Date(i.getFullYear(),i.getMonth(),i.getDate()-R).getTime()/1e3);r==="--jour"||r==="--day"?(n=a(0),s="today"):r==="--semaine"||r==="--week"?(n=a(6),s="last 7 days",o=!0):(r==="--mois"||r==="--month")&&(n=a(29),s="last 30 days",o=!0);let[c,u,l,h]=await Promise.all([Ye(void 0,n),T(),r===""?Ye(void 0,a(0)):void 0,r===""?Ye(void 0,a(6)):void 0]),b=l&&h?[{label:"Today",savedTokens:l.observed?.savedTokens??l.savedTokens,count:l.count},{label:"Last 7 days",savedTokens:h.observed?.savedTokens??h.savedTokens,count:h.count},{label:"All time",savedTokens:c.observed?.savedTokens??c.savedTokens,count:c.count}]:void 0,k=Xn(c.savedByProvider),$=u?.linked??(!!u?.jwt&&u?.plan!=="free"),O=!u||!$?"not linked \xB7 anonymous free tier (run tkr link to send these to your dashboard)":u.email?`${u.email} \xB7 ${u.plan}`:`linked \xB7 ${u.plan}`,P=!!process.stdout.isTTY&&!process.env.NO_COLOR,A=` Account: ${O}
|
|
154
|
+
`+xi(c,{color:P,pricePerMtok:k,subtitle:s,periods:b});if(o){let R=Ei(await Si(void 0,n),{color:P});R&&(A+=`
|
|
155
155
|
`+R)}c.count>0&&!Ht()&&(A+=` To include commands from every terminal: tkr shim install
|
|
156
156
|
`),u?.relinkRequired&&(A+=` \u26A0 dashboard link lost \u2014 run: tkr link <your-token> (from tokmizer.com/dashboard)
|
|
157
157
|
`),u?.updateRequired?A+=` \u26A0 plugin update required \u2014 run: /tkr-update
|
|
158
|
-
`:
|
|
158
|
+
`:Se(V,u?.latestPluginVersion)&&(A+=` \u26A0 you run v${V}, v${u?.latestPluginVersion} is out \u2014 older versions undercount savings. Run /tkr-update, then RESTART Claude Code.
|
|
159
159
|
`),u?.clockSkewDetected&&(A+=` \u26A0 system clock looks off \u2014 sync it, then run: tkr heartbeat
|
|
160
|
-
`);try{let{connectDaemon:R}=await Promise.resolve().then(()=>(pt(),mt)),se=await R(),
|
|
161
|
-
`);return}if(t==="session"){process.stdout.write(
|
|
160
|
+
`);try{let{connectDaemon:R}=await Promise.resolve().then(()=>(pt(),mt)),se=await R(),oe=await se.ping();se.close();let Vt=null;if(oe.ruleCount===0){let{runtimeFromCache:Ki}=await Promise.resolve().then(()=>(as(),is));Vt=(await Ki())?.ruleCount??null}A+=jr(oe.ruleCount,Vt)}catch{let{runtimeFromCache:R}=await Promise.resolve().then(()=>(as(),is)),se=await R();A+=jr(null,se?se.ruleCount:null)}process.stdout.write(A+`
|
|
161
|
+
`);return}if(t==="session"){process.stdout.write(Oi(Pi())+`
|
|
162
162
|
`);return}if(t==="discover"){let r=Ht(),n=[" tokmizer coverage"," "+"\u2500".repeat(40)," Agent (Claude/Codex) \u2705 optimized automatically",r?" Your terminal \u2705 covered (shims installed)":" Your terminal \u26A0\uFE0F not covered"];r||n.push("",' \u2192 run "tkr shim install" to also cover your commands outside the agent.'),n.push(""),process.stdout.write(n.join(`
|
|
163
163
|
`)+`
|
|
164
|
-
`);return}if(t==="restore"){let r=await
|
|
164
|
+
`);return}if(t==="restore"){let r=await Ks(e[0]);if(r.stdout&&process.stdout.write(r.stdout),r.stderr&&process.stderr.write(r.stderr),r.code===0&&r.stdout&&wi(0,Buffer.byteLength(r.stdout,"utf8"),void 0,!1,Rr().host,"restore","tkr restore"),r.code===0&&r.restoredTokens){let n=await U();await Ln({cmd:"restore",tokensSaved:0,tokensRestored:r.restoredTokens,optimized:!1,telemetryOptIn:n.telemetryOptIn,host:Rr().host})}process.exitCode=r.code;return}if(t==="heartbeat"){await he(J);let r=Date.now(),n=await zn(J);if(!n||(n.lastHeartbeatOkAt??0)<r){process.stderr.write(`Heartbeat failed
|
|
165
165
|
`),process.exitCode=1;return}process.stdout.write(`OK plan=${n.plan} status=${n.status}
|
|
166
|
-
`);let s=await
|
|
166
|
+
`);let s=await ar();s?.error&&process.stdout.write(`Note: feature sync failed: ${s.error}
|
|
167
167
|
`);return}if(t==="settings"){(e[0]??"show")==="show"&&process.stdout.write(`YOLO: ${lt()?"on":"off"} (this machine only)
|
|
168
|
-
`),await he(
|
|
168
|
+
`),await he(J),await Fd(e);return}if(t==="telemetry"){await he(J),await jd(e);return}if(t==="reducer"){let r=["off","light","balanced","max"],n={off:"default: responses untouched",light:"trims padding, keeps natural prose",balanced:"dense and direct, answer first",max:"telegraphic, every token earns its place"},s=e[0]?.toLowerCase();if(!s){let o=await U(),i=o.reducer==="off"?"":o.enabled?await cr(`reducer-${o.reducer}`)?`Ready for the next Claude Code session.
|
|
169
169
|
`:`Reducer ruleset unavailable; reconnect and run: tkr heartbeat
|
|
170
170
|
`:`Tokmizer is disabled; the reducer is inactive.
|
|
171
171
|
`;process.stdout.write(`Reducer: ${o.reducer}
|
|
@@ -174,9 +174,9 @@ ${i.manual}`),i.status==="missing"){process.exitCode=1;return}let a=await T()??a
|
|
|
174
174
|
Reducer guides Claude Code response style; command output compression is separate.
|
|
175
175
|
`+i+`Change it: tkr reducer <off|light|balanced|max>
|
|
176
176
|
`);return}if(!r.includes(s)){process.stderr.write(`Unknown level: ${e[0]}. Use off, light, balanced or max.
|
|
177
|
-
`),process.exitCode=1;return}await he(
|
|
177
|
+
`),process.exitCode=1;return}await he(J);try{let o=await Ae({reducer:s});if(o.settings.reducer==="off")process.stdout.write(`Reducer off. Claude Code responses back to normal next session.
|
|
178
178
|
`);else if(!o.settings.enabled)process.stdout.write(`Reducer saved as ${o.settings.reducer} for Claude Code. Tokmizer is disabled; enable it with: tkr settings set enabled true
|
|
179
|
-
`);else{if(await
|
|
179
|
+
`);else{if(await zn(J),!await cr(`reducer-${o.settings.reducer}`)){process.stderr.write(`Reducer saved as ${o.settings.reducer}, but its ruleset is unavailable. Reconnect and run: tkr heartbeat before starting a new Claude Code session.
|
|
180
180
|
`),process.exitCode=1;return}process.stdout.write(`Reducer set to ${o.settings.reducer} for Claude Code. Its response-style instructions load next session.
|
|
181
181
|
`)}}catch(o){let i=o instanceof Error?o.message:String(o);i.includes("plan_required")||i.toLowerCase().includes("smart and pro")?process.stdout.write(`Reducer is not available on this token right now.
|
|
182
182
|
`):process.stdout.write(`${i}
|
|
@@ -192,8 +192,8 @@ Content and diagnostics can be lost; discarded output cannot be restored.
|
|
|
192
192
|
Change standard level and leave YOLO: tkr compression <light|balanced|max>
|
|
193
193
|
Local mode: tkr yolo <on|off|status>
|
|
194
194
|
`);return}let o=Object.hasOwn(r,s.toLowerCase())?r[s.toLowerCase()]:void 0;if(!o){process.stderr.write(`Unknown level: ${s}. Use light, balanced or max.
|
|
195
|
-
`),process.exitCode=1;return}await
|
|
196
|
-
`);try{await he(
|
|
195
|
+
`),process.exitCode=1;return}await Ke(!1),process.stdout.write(`YOLO: off (this machine only)
|
|
196
|
+
`);try{await he(J);let i=await Ae({outputVerbosity:o});process.stdout.write(`Compression set to ${n[i.settings.outputVerbosity]}. Applies to your next commands.
|
|
197
197
|
`)}catch(i){process.stderr.write(`Could not update standard compression: ${i instanceof Error?i.message:String(i)}
|
|
198
|
-
`),process.exitCode=1}return}
|
|
198
|
+
`),process.exitCode=1}return}Ld(),process.exitCode=["help","--help","-h"].includes(t)?0:1}zd().catch(t=>{process.stderr.write(`${t.message??t}
|
|
199
199
|
`),process.exitCode=1});
|