Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
perf(images): set explicit loading hints and stop the codemod rewriting comments
nirholas7645c99c8145
diff --git a/mcp-server/src/ui/commerce-receipt.html b/mcp-server/src/ui/commerce-receipt.htmlindex 509eb99fb..edad6581f 100644--- a/mcp-server/src/ui/commerce-receipt.html+++ b/mcp-server/src/ui/commerce-receipt.html@@ -93,7 +93,7 @@<pre id="response"></pre></div></main>-<script>"use strict";(()=>{var Uc=Object.defineProperty;var id=(t,r,n)=>r in t?Uc(t,r,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[r]=n;var Te=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(r,n)=>(typeof require<"u"?require:r)[n]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var k=(t,r)=>()=>(t&&(r=t(t=0)),r);var xe=(t,r)=>{for(var n in r)Uc(t,n,{get:r[n],enumerable:!0})};var C=(t,r,n)=>id(t,typeof r!="symbol"?r+"":r,n);function u(t,r,n){function i(c,l){var h;Object.defineProperty(c,"_zod",{value:c._zod??{},enumerable:!1}),(h=c._zod).traits??(h.traits=new Set),c._zod.traits.add(t),r(c,l);for(let g in a.prototype)g in c||Object.defineProperty(c,g,{value:a.prototype[g].bind(c)});c._zod.constr=a,c._zod.def=l}let e=n?.Parent??Object;class o extends e{}Object.defineProperty(o,"name",{value:t});function a(c){var l;let h=n?.Parent?new o:this;i(h,c),(l=h._zod).deferred??(l.deferred=[]);for(let g of h._zod.deferred)g();return h}return Object.defineProperty(a,"init",{value:i}),Object.defineProperty(a,Symbol.hasInstance,{value:c=>n?.Parent&&c instanceof n.Parent?!0:c?._zod?.traits?.has(t)}),Object.defineProperty(a,"name",{value:t}),a}function W(t){return t&&Object.assign(kt,t),kt}var _r,yr,pe,kt,qe=k(()=>{_r=Object.freeze({status:"aborted"});yr=Symbol("zod_brand"),pe=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},kt={}});var y={};xe(y,{BIGINT_FORMAT_RANGES:()=>Po,Class:()=>$o,NUMBER_FORMAT_RANGES:()=>jo,aborted:()=>Ne,allowsEval:()=>So,assert:()=>ld,assertEqual:()=>ad,assertIs:()=>cd,assertNever:()=>ud,assertNotEqual:()=>sd,assignProp:()=>ko,cached:()=>It,captureStackTrace:()=>$r,cleanEnum:()=>zd,cleanRegex:()=>jt,clone:()=>oe,createTransparentProxy:()=>hd,defineLazy:()=>R,esc:()=>Oe,escapeRegex:()=>_e,extend:()=>_d,finalizeIssue:()=>se,floatSafeRemainder:()=>zo,getElementAtPath:()=>md,getEnumValues:()=>wt,getLengthableOrigin:()=>Ot,getParsedType:()=>gd,getSizableOrigin:()=>Tt,isObject:()=>Ve,isPlainObject:()=>Fe,issue:()=>To,joinValues:()=>f,jsonStringifyReplacer:()=>xo,merge:()=>yd,normalizeParams:()=>v,nullish:()=>ze,numKeys:()=>fd,omit:()=>bd,optionalKeys:()=>Io,partial:()=>$d,pick:()=>vd,prefixIssues:()=>ie,primitiveTypes:()=>wo,promiseAllObject:()=>dd,propertyKeyTypes:()=>Pt,randomString:()=>pd,required:()=>xd,stringifyPrimitive:()=>_,unwrapMessage:()=>St});function ad(t){return t}function sd(t){return t}function cd(t){}function ud(t){throw new Error}function ld(t){}function wt(t){let r=Object.values(t).filter(i=>typeof i=="number");return Object.entries(t).filter(([i,e])=>r.indexOf(+i)===-1).map(([i,e])=>e)}function f(t,r="|"){return t.map(n=>_(n)).join(r)}function xo(t,r){return typeof r=="bigint"?r.toString():r}function It(t){return{get value(){{let n=t();return Object.defineProperty(this,"value",{value:n}),n}throw new Error("cached value already set")}}}function ze(t){return t==null}function jt(t){let r=t.startsWith("^")?1:0,n=t.endsWith("$")?t.length-1:t.length;return t.slice(r,n)}function zo(t,r){let n=(t.toString().split(".")[1]||"").length,i=(r.toString().split(".")[1]||"").length,e=n>i?n:i,o=Number.parseInt(t.toFixed(e).replace(".","")),a=Number.parseInt(r.toFixed(e).replace(".",""));return o%a/10**e}function R(t,r,n){Object.defineProperty(t,r,{get(){{let e=n();return t[r]=e,e}throw new Error("cached value already set")},set(e){Object.defineProperty(t,r,{value:e})},configurable:!0})}function ko(t,r,n){Object.defineProperty(t,r,{value:n,writable:!0,enumerable:!0,configurable:!0})}function md(t,r){return r?r.reduce((n,i)=>n?.[i],t):t}function dd(t){let r=Object.keys(t),n=r.map(i=>t[i]);return Promise.all(n).then(i=>{let e={};for(let o=0;o<r.length;o++)e[r[o]]=i[o];return e})}function pd(t=10){let r="abcdefghijklmnopqrstuvwxyz",n="";for(let i=0;i<t;i++)n+=r[Math.floor(Math.random()*r.length)];return n}function Oe(t){return JSON.stringify(t)}function Ve(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Fe(t){if(Ve(t)===!1)return!1;let r=t.constructor;if(r===void 0)return!0;let n=r.prototype;return!(Ve(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}function fd(t){let r=0;for(let n in t)Object.prototype.hasOwnProperty.call(t,n)&&r++;return r}function _e(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function oe(t,r,n){let i=new t._zod.constr(r??t._zod.def);return(!r||n?.parent)&&(i._zod.parent=t),i}function v(t){let r=t;if(!r)return{};if(typeof r=="string")return{error:()=>r};if(r?.message!==void 0){if(r?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");r.error=r.message}return delete r.message,typeof r.error=="string"?{...r,error:()=>r.error}:r}function hd(t){let r;return new Proxy({},{get(n,i,e){return r??(r=t()),Reflect.get(r,i,e)},set(n,i,e,o){return r??(r=t()),Reflect.set(r,i,e,o)},has(n,i){return r??(r=t()),Reflect.has(r,i)},deleteProperty(n,i){return r??(r=t()),Reflect.deleteProperty(r,i)},ownKeys(n){return r??(r=t()),Reflect.ownKeys(r)},getOwnPropertyDescriptor(n,i){return r??(r=t()),Reflect.getOwnPropertyDescriptor(r,i)},defineProperty(n,i,e){return r??(r=t()),Reflect.defineProperty(r,i,e)}})}function _(t){return typeof t=="bigint"?t.toString()+"n":typeof t=="string"?`"${t}"`:`${t}`}function Io(t){return Object.keys(t).filter(r=>t[r]._zod.optin==="optional"&&t[r]._zod.optout==="optional")}function vd(t,r){let n={},i=t._zod.def;for(let e in r){if(!(e in i.shape))throw new Error(`Unrecognized key: "${e}"`);r[e]&&(n[e]=i.shape[e])}return oe(t,{...t._zod.def,shape:n,checks:[]})}function bd(t,r){let n={...t._zod.def.shape},i=t._zod.def;for(let e in r){if(!(e in i.shape))throw new Error(`Unrecognized key: "${e}"`);r[e]&&delete n[e]}return oe(t,{...t._zod.def,shape:n,checks:[]})}function _d(t,r){if(!Fe(r))throw new Error("Invalid input to extend: expected a plain object");let n={...t._zod.def,get shape(){let i={...t._zod.def.shape,...r};return ko(this,"shape",i),i},checks:[]};return oe(t,n)}function yd(t,r){return oe(t,{...t._zod.def,get shape(){let n={...t._zod.def.shape,...r._zod.def.shape};return ko(this,"shape",n),n},catchall:r._zod.def.catchall,checks:[]})}function $d(t,r,n){let i=r._zod.def.shape,e={...i};if(n)for(let o in n){if(!(o in i))throw new Error(`Unrecognized key: "${o}"`);n[o]&&(e[o]=t?new t({type:"optional",innerType:i[o]}):i[o])}else for(let o in i)e[o]=t?new t({type:"optional",innerType:i[o]}):i[o];return oe(r,{...r._zod.def,shape:e,checks:[]})}function xd(t,r,n){let i=r._zod.def.shape,e={...i};if(n)for(let o in n){if(!(o in e))throw new Error(`Unrecognized key: "${o}"`);n[o]&&(e[o]=new t({type:"nonoptional",innerType:i[o]}))}else for(let o in i)e[o]=new t({type:"nonoptional",innerType:i[o]});return oe(r,{...r._zod.def,shape:e,checks:[]})}function Ne(t,r=0){for(let n=r;n<t.issues.length;n++)if(t.issues[n]?.continue!==!0)return!0;return!1}function ie(t,r){return r.map(n=>{var i;return(i=n).path??(i.path=[]),n.path.unshift(t),n})}function St(t){return typeof t=="string"?t:t?.message}function se(t,r,n){let i={...t,path:t.path??[]};if(!t.message){let e=St(t.inst?._zod.def?.error?.(t))??St(r?.error?.(t))??St(n.customError?.(t))??St(n.localeError?.(t))??"Invalid input";i.message=e}return delete i.inst,delete i.continue,r?.reportInput||delete i.input,i}function Tt(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}function Ot(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function To(...t){let[r,n,i]=t;return typeof r=="string"?{message:r,code:"custom",input:n,inst:i}:{...r}}function zd(t){return Object.entries(t).filter(([r,n])=>Number.isNaN(Number.parseInt(r,10))).map(r=>r[1])}var $r,So,gd,Pt,wo,jo,Po,$o,P=k(()=>{$r=Error.captureStackTrace?Error.captureStackTrace:(...t)=>{};So=It(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let t=Function;return new t(""),!0}catch{return!1}});gd=t=>{let r=typeof t;switch(r){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(t)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(t)?"array":t===null?"null":t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?"promise":typeof Map<"u"&&t instanceof Map?"map":typeof Set<"u"&&t instanceof Set?"set":typeof Date<"u"&&t instanceof Date?"date":typeof File<"u"&&t instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${r}`)}},Pt=new Set(["string","number","symbol"]),wo=new Set(["string","number","bigint","boolean","symbol","undefined"]);jo={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},Po={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};$o=class{constructor(...r){}}});function Je(t,r=n=>n.message){let n={},i=[];for(let e of t.issues)e.path.length>0?(n[e.path[0]]=n[e.path[0]]||[],n[e.path[0]].push(r(e))):i.push(r(e));return{formErrors:i,fieldErrors:n}}function Be(t,r){let n=r||function(o){return o.message},i={_errors:[]},e=o=>{for(let a of o.issues)if(a.code==="invalid_union"&&a.errors.length)a.errors.map(c=>e({issues:c}));else if(a.code==="invalid_key")e({issues:a.issues});else if(a.code==="invalid_element")e({issues:a.issues});else if(a.path.length===0)i._errors.push(n(a));else{let c=i,l=0;for(;l<a.path.length;){let h=a.path[l];l===a.path.length-1?(c[h]=c[h]||{_errors:[]},c[h]._errors.push(n(a))):c[h]=c[h]||{_errors:[]},c=c[h],l++}}};return e(t),i}function xr(t,r){let n=r||function(o){return o.message},i={errors:[]},e=(o,a=[])=>{var c,l;for(let h of o.issues)if(h.code==="invalid_union"&&h.errors.length)h.errors.map(g=>e({issues:g},h.path));else if(h.code==="invalid_key")e({issues:h.issues},h.path);else if(h.code==="invalid_element")e({issues:h.issues},h.path);else{let g=[...a,...h.path];if(g.length===0){i.errors.push(n(h));continue}let m=i,$=0;for(;$<g.length;){let b=g[$],p=$===g.length-1;typeof b=="string"?(m.properties??(m.properties={}),(c=m.properties)[b]??(c[b]={errors:[]}),m=m.properties[b]):(m.items??(m.items=[]),(l=m.items)[b]??(l[b]={errors:[]}),m=m.items[b]),p&&m.errors.push(n(h)),$++}}};return e(t),i}function Dc(t){let r=[];for(let n of t)typeof n=="number"?r.push(`[${n}]`):typeof n=="symbol"?r.push(`[${JSON.stringify(String(n))}]`):/[^\w$]/.test(n)?r.push(`[${JSON.stringify(n)}]`):(r.length&&r.push("."),r.push(n));return r.join("")}function zr(t){let r=[],n=[...t.issues].sort((i,e)=>i.path.length-e.path.length);for(let i of n)r.push(`\u2716 ${i.message}`),i.path?.length&&r.push(` \u2192 at ${Dc(i.path)}`);return r.join(`+<script>"use strict";(()=>{var Uc=Object.defineProperty;var id=(t,r,n)=>r in t?Uc(t,r,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[r]=n;var Te=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(r,n)=>(typeof require<"u"?require:r)[n]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var k=(t,r,n)=>()=>{if(n)throw n[0];try{return t&&(r=t(t=0)),r}catch(i){throw n=[i],i}};var xe=(t,r)=>{for(var n in r)Uc(t,n,{get:r[n],enumerable:!0})};var C=(t,r,n)=>id(t,typeof r!="symbol"?r+"":r,n);function u(t,r,n){function i(c,l){var h;Object.defineProperty(c,"_zod",{value:c._zod??{},enumerable:!1}),(h=c._zod).traits??(h.traits=new Set),c._zod.traits.add(t),r(c,l);for(let g in a.prototype)g in c||Object.defineProperty(c,g,{value:a.prototype[g].bind(c)});c._zod.constr=a,c._zod.def=l}let e=n?.Parent??Object;class o extends e{}Object.defineProperty(o,"name",{value:t});function a(c){var l;let h=n?.Parent?new o:this;i(h,c),(l=h._zod).deferred??(l.deferred=[]);for(let g of h._zod.deferred)g();return h}return Object.defineProperty(a,"init",{value:i}),Object.defineProperty(a,Symbol.hasInstance,{value:c=>n?.Parent&&c instanceof n.Parent?!0:c?._zod?.traits?.has(t)}),Object.defineProperty(a,"name",{value:t}),a}function W(t){return t&&Object.assign(kt,t),kt}var _r,yr,pe,kt,qe=k(()=>{_r=Object.freeze({status:"aborted"});yr=Symbol("zod_brand"),pe=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},kt={}});var y={};xe(y,{BIGINT_FORMAT_RANGES:()=>Po,Class:()=>$o,NUMBER_FORMAT_RANGES:()=>jo,aborted:()=>Ne,allowsEval:()=>So,assert:()=>ld,assertEqual:()=>ad,assertIs:()=>cd,assertNever:()=>ud,assertNotEqual:()=>sd,assignProp:()=>ko,cached:()=>It,captureStackTrace:()=>$r,cleanEnum:()=>zd,cleanRegex:()=>jt,clone:()=>oe,createTransparentProxy:()=>hd,defineLazy:()=>R,esc:()=>Oe,escapeRegex:()=>_e,extend:()=>_d,finalizeIssue:()=>se,floatSafeRemainder:()=>zo,getElementAtPath:()=>md,getEnumValues:()=>wt,getLengthableOrigin:()=>Ot,getParsedType:()=>gd,getSizableOrigin:()=>Tt,isObject:()=>Ve,isPlainObject:()=>Fe,issue:()=>To,joinValues:()=>f,jsonStringifyReplacer:()=>xo,merge:()=>yd,normalizeParams:()=>v,nullish:()=>ze,numKeys:()=>fd,omit:()=>bd,optionalKeys:()=>Io,partial:()=>$d,pick:()=>vd,prefixIssues:()=>ie,primitiveTypes:()=>wo,promiseAllObject:()=>dd,propertyKeyTypes:()=>Pt,randomString:()=>pd,required:()=>xd,stringifyPrimitive:()=>_,unwrapMessage:()=>St});function ad(t){return t}function sd(t){return t}function cd(t){}function ud(t){throw new Error}function ld(t){}function wt(t){let r=Object.values(t).filter(i=>typeof i=="number");return Object.entries(t).filter(([i,e])=>r.indexOf(+i)===-1).map(([i,e])=>e)}function f(t,r="|"){return t.map(n=>_(n)).join(r)}function xo(t,r){return typeof r=="bigint"?r.toString():r}function It(t){return{get value(){{let n=t();return Object.defineProperty(this,"value",{value:n}),n}throw new Error("cached value already set")}}}function ze(t){return t==null}function jt(t){let r=t.startsWith("^")?1:0,n=t.endsWith("$")?t.length-1:t.length;return t.slice(r,n)}function zo(t,r){let n=(t.toString().split(".")[1]||"").length,i=(r.toString().split(".")[1]||"").length,e=n>i?n:i,o=Number.parseInt(t.toFixed(e).replace(".","")),a=Number.parseInt(r.toFixed(e).replace(".",""));return o%a/10**e}function R(t,r,n){Object.defineProperty(t,r,{get(){{let e=n();return t[r]=e,e}throw new Error("cached value already set")},set(e){Object.defineProperty(t,r,{value:e})},configurable:!0})}function ko(t,r,n){Object.defineProperty(t,r,{value:n,writable:!0,enumerable:!0,configurable:!0})}function md(t,r){return r?r.reduce((n,i)=>n?.[i],t):t}function dd(t){let r=Object.keys(t),n=r.map(i=>t[i]);return Promise.all(n).then(i=>{let e={};for(let o=0;o<r.length;o++)e[r[o]]=i[o];return e})}function pd(t=10){let r="abcdefghijklmnopqrstuvwxyz",n="";for(let i=0;i<t;i++)n+=r[Math.floor(Math.random()*r.length)];return n}function Oe(t){return JSON.stringify(t)}function Ve(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Fe(t){if(Ve(t)===!1)return!1;let r=t.constructor;if(r===void 0)return!0;let n=r.prototype;return!(Ve(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}function fd(t){let r=0;for(let n in t)Object.prototype.hasOwnProperty.call(t,n)&&r++;return r}function _e(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function oe(t,r,n){let i=new t._zod.constr(r??t._zod.def);return(!r||n?.parent)&&(i._zod.parent=t),i}function v(t){let r=t;if(!r)return{};if(typeof r=="string")return{error:()=>r};if(r?.message!==void 0){if(r?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");r.error=r.message}return delete r.message,typeof r.error=="string"?{...r,error:()=>r.error}:r}function hd(t){let r;return new Proxy({},{get(n,i,e){return r??(r=t()),Reflect.get(r,i,e)},set(n,i,e,o){return r??(r=t()),Reflect.set(r,i,e,o)},has(n,i){return r??(r=t()),Reflect.has(r,i)},deleteProperty(n,i){return r??(r=t()),Reflect.deleteProperty(r,i)},ownKeys(n){return r??(r=t()),Reflect.ownKeys(r)},getOwnPropertyDescriptor(n,i){return r??(r=t()),Reflect.getOwnPropertyDescriptor(r,i)},defineProperty(n,i,e){return r??(r=t()),Reflect.defineProperty(r,i,e)}})}function _(t){return typeof t=="bigint"?t.toString()+"n":typeof t=="string"?`"${t}"`:`${t}`}function Io(t){return Object.keys(t).filter(r=>t[r]._zod.optin==="optional"&&t[r]._zod.optout==="optional")}function vd(t,r){let n={},i=t._zod.def;for(let e in r){if(!(e in i.shape))throw new Error(`Unrecognized key: "${e}"`);r[e]&&(n[e]=i.shape[e])}return oe(t,{...t._zod.def,shape:n,checks:[]})}function bd(t,r){let n={...t._zod.def.shape},i=t._zod.def;for(let e in r){if(!(e in i.shape))throw new Error(`Unrecognized key: "${e}"`);r[e]&&delete n[e]}return oe(t,{...t._zod.def,shape:n,checks:[]})}function _d(t,r){if(!Fe(r))throw new Error("Invalid input to extend: expected a plain object");let n={...t._zod.def,get shape(){let i={...t._zod.def.shape,...r};return ko(this,"shape",i),i},checks:[]};return oe(t,n)}function yd(t,r){return oe(t,{...t._zod.def,get shape(){let n={...t._zod.def.shape,...r._zod.def.shape};return ko(this,"shape",n),n},catchall:r._zod.def.catchall,checks:[]})}function $d(t,r,n){let i=r._zod.def.shape,e={...i};if(n)for(let o in n){if(!(o in i))throw new Error(`Unrecognized key: "${o}"`);n[o]&&(e[o]=t?new t({type:"optional",innerType:i[o]}):i[o])}else for(let o in i)e[o]=t?new t({type:"optional",innerType:i[o]}):i[o];return oe(r,{...r._zod.def,shape:e,checks:[]})}function xd(t,r,n){let i=r._zod.def.shape,e={...i};if(n)for(let o in n){if(!(o in e))throw new Error(`Unrecognized key: "${o}"`);n[o]&&(e[o]=new t({type:"nonoptional",innerType:i[o]}))}else for(let o in i)e[o]=new t({type:"nonoptional",innerType:i[o]});return oe(r,{...r._zod.def,shape:e,checks:[]})}function Ne(t,r=0){for(let n=r;n<t.issues.length;n++)if(t.issues[n]?.continue!==!0)return!0;return!1}function ie(t,r){return r.map(n=>{var i;return(i=n).path??(i.path=[]),n.path.unshift(t),n})}function St(t){return typeof t=="string"?t:t?.message}function se(t,r,n){let i={...t,path:t.path??[]};if(!t.message){let e=St(t.inst?._zod.def?.error?.(t))??St(r?.error?.(t))??St(n.customError?.(t))??St(n.localeError?.(t))??"Invalid input";i.message=e}return delete i.inst,delete i.continue,r?.reportInput||delete i.input,i}function Tt(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}function Ot(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function To(...t){let[r,n,i]=t;return typeof r=="string"?{message:r,code:"custom",input:n,inst:i}:{...r}}function zd(t){return Object.entries(t).filter(([r,n])=>Number.isNaN(Number.parseInt(r,10))).map(r=>r[1])}var $r,So,gd,Pt,wo,jo,Po,$o,P=k(()=>{$r=Error.captureStackTrace?Error.captureStackTrace:(...t)=>{};So=It(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let t=Function;return new t(""),!0}catch{return!1}});gd=t=>{let r=typeof t;switch(r){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(t)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(t)?"array":t===null?"null":t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?"promise":typeof Map<"u"&&t instanceof Map?"map":typeof Set<"u"&&t instanceof Set?"set":typeof Date<"u"&&t instanceof Date?"date":typeof File<"u"&&t instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${r}`)}},Pt=new Set(["string","number","symbol"]),wo=new Set(["string","number","bigint","boolean","symbol","undefined"]);jo={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},Po={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};$o=class{constructor(...r){}}});function Je(t,r=n=>n.message){let n={},i=[];for(let e of t.issues)e.path.length>0?(n[e.path[0]]=n[e.path[0]]||[],n[e.path[0]].push(r(e))):i.push(r(e));return{formErrors:i,fieldErrors:n}}function Be(t,r){let n=r||function(o){return o.message},i={_errors:[]},e=o=>{for(let a of o.issues)if(a.code==="invalid_union"&&a.errors.length)a.errors.map(c=>e({issues:c}));else if(a.code==="invalid_key")e({issues:a.issues});else if(a.code==="invalid_element")e({issues:a.issues});else if(a.path.length===0)i._errors.push(n(a));else{let c=i,l=0;for(;l<a.path.length;){let h=a.path[l];l===a.path.length-1?(c[h]=c[h]||{_errors:[]},c[h]._errors.push(n(a))):c[h]=c[h]||{_errors:[]},c=c[h],l++}}};return e(t),i}function xr(t,r){let n=r||function(o){return o.message},i={errors:[]},e=(o,a=[])=>{var c,l;for(let h of o.issues)if(h.code==="invalid_union"&&h.errors.length)h.errors.map(g=>e({issues:g},h.path));else if(h.code==="invalid_key")e({issues:h.issues},h.path);else if(h.code==="invalid_element")e({issues:h.issues},h.path);else{let g=[...a,...h.path];if(g.length===0){i.errors.push(n(h));continue}let m=i,$=0;for(;$<g.length;){let b=g[$],p=$===g.length-1;typeof b=="string"?(m.properties??(m.properties={}),(c=m.properties)[b]??(c[b]={errors:[]}),m=m.properties[b]):(m.items??(m.items=[]),(l=m.items)[b]??(l[b]={errors:[]}),m=m.items[b]),p&&m.errors.push(n(h)),$++}}};return e(t),i}function Dc(t){let r=[];for(let n of t)typeof n=="number"?r.push(`[${n}]`):typeof n=="symbol"?r.push(`[${JSON.stringify(String(n))}]`):/[^\w$]/.test(n)?r.push(`[${JSON.stringify(n)}]`):(r.length&&r.push("."),r.push(n));return r.join("")}function zr(t){let r=[],n=[...t.issues].sort((i,e)=>i.path.length-e.path.length);for(let i of n)r.push(`\u2716 ${i.message}`),i.path?.length&&r.push(` \u2192 at ${Dc(i.path)}`);return r.join(``)}var Ec,Nt,He,Oo=k(()=>{qe();P();Ec=(t,r)=>{t.name="$ZodError",Object.defineProperty(t,"_zod",{value:t._zod,enumerable:!1}),Object.defineProperty(t,"issues",{value:r,enumerable:!1}),Object.defineProperty(t,"message",{get(){return JSON.stringify(r,xo,2)},enumerable:!0}),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},Nt=u("$ZodError",Ec),He=u("$ZodError",Ec,{Parent:Error})});var kr,Ut,Sr,Et,wr,We,Ir,Dt,jr=k(()=>{qe();Oo();P();kr=t=>(r,n,i,e)=>{let o=i?Object.assign(i,{async:!1}):{async:!1},a=r._zod.run({value:n,issues:[]},o);if(a instanceof Promise)throw new pe;if(a.issues.length){let c=new(e?.Err??t)(a.issues.map(l=>se(l,o,W())));throw $r(c,e?.callee),c}return a.value},Ut=kr(He),Sr=t=>async(r,n,i,e)=>{let o=i?Object.assign(i,{async:!0}):{async:!0},a=r._zod.run({value:n,issues:[]},o);if(a instanceof Promise&&(a=await a),a.issues.length){let c=new(e?.Err??t)(a.issues.map(l=>se(l,o,W())));throw $r(c,e?.callee),c}return a.value},Et=Sr(He),wr=t=>(r,n,i)=>{let e=i?{...i,async:!1}:{async:!1},o=r._zod.run({value:n,issues:[]},e);if(o instanceof Promise)throw new pe;return o.issues.length?{success:!1,error:new(t??Nt)(o.issues.map(a=>se(a,e,W())))}:{success:!0,data:o.value}},We=wr(He),Ir=t=>async(r,n,i)=>{let e=i?Object.assign(i,{async:!0}):{async:!0},o=r._zod.run({value:n,issues:[]},e);return o instanceof Promise&&(o=await o),o.issues.length?{success:!1,error:new t(o.issues.map(a=>se(a,e,W())))}:{success:!0,data:o.value}},Dt=Ir(He)});var ke={};xe(ke,{_emoji:()=>Zc,base64:()=>Jo,base64url:()=>Pr,bigint:()=>Xo,boolean:()=>ri,browserEmail:()=>Nd,cidrv4:()=>Fo,cidrv6:()=>Ho,cuid:()=>No,cuid2:()=>Uo,date:()=>Ko,datetime:()=>Qo,domain:()=>Ud,duration:()=>Ao,e164:()=>Wo,email:()=>Mo,emoji:()=>Lo,extendedDuration:()=>Sd,guid:()=>Co,hostname:()=>Bo,html5Email:()=>Pd,integer:()=>ei,ipv4:()=>qo,ipv6:()=>Vo,ksuid:()=>Zo,lowercase:()=>ii,nanoid:()=>Ro,null:()=>ni,number:()=>ti,rfc5322Email:()=>Td,string:()=>Yo,time:()=>Go,ulid:()=>Eo,undefined:()=>oi,unicodeEmail:()=>Od,uppercase:()=>ai,uuid:()=>Ue,uuid4:()=>wd,uuid6:()=>Id,uuid7:()=>jd,xid:()=>Do});function Lo(){return new RegExp(Zc,"u")}function Ac(t){let r="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof t.precision=="number"?t.precision===-1?`${r}`:t.precision===0?`${r}:[0-5]\\d`:`${r}:[0-5]\\d\\.\\d{${t.precision}}`:`${r}(?::[0-5]\\d(?:\\.\\d+)?)?`}function Go(t){return new RegExp(`^${Ac(t)}$`)}function Qo(t){let r=Ac({precision:t.precision}),n=["Z"];t.local&&n.push(""),t.offset&&n.push("([+-]\\d{2}:\\d{2})");let i=`${r}(?:${n.join("|")})`;return new RegExp(`^${Rc}T(?:${i})$`)}var No,Uo,Eo,Do,Zo,Ro,Ao,Sd,Co,Ue,wd,Id,jd,Mo,Pd,Td,Od,Nd,Zc,qo,Vo,Fo,Ho,Jo,Pr,Bo,Ud,Wo,Rc,Ko,Yo,Xo,ei,ti,ri,ni,oi,ii,ai,Tr=k(()=>{No=/^[cC][^\s-]{8,}$/,Uo=/^[0-9a-z]+$/,Eo=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Do=/^[0-9a-vA-V]{20}$/,Zo=/^[A-Za-z0-9]{27}$/,Ro=/^[a-zA-Z0-9_-]{21}$/,Ao=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,Sd=/^[-+]?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)?)??$/,Co=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,Ue=t=>t?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${t}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000)$/,wd=Ue(4),Id=Ue(6),jd=Ue(7),Mo=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,Pd=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,Td=/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,Od=/^[^\s@"]{1,64}@[^\s@]{1,255}$/u,Nd=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,Zc="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";qo=/^(?:(?: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])$/,Vo=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})$/,Fo=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,Ho=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Jo=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Pr=/^[A-Za-z0-9_-]*$/,Bo=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,Ud=/^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/,Wo=/^\+(?:[0-9]){6,14}[0-9]$/,Rc="(?:(?:\\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])))",Ko=new RegExp(`^${Rc}$`);Yo=t=>{let r=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${r}$`)},Xo=/^\d+n?$/,ei=/^\d+$/,ti=/^-?\d+(?:\.\d+)?/i,ri=/true|false/i,ni=/null/i,oi=/undefined/i,ii=/^[^A-Z]*$/,ai=/^[^a-z]*$/});function Cc(t,r,n){t.issues.length&&r.issues.push(...ie(n,t.issues))}var B,Mc,Or,Nr,si,ci,ui,li,mi,di,pi,fi,gi,Ke,hi,vi,bi,_i,yi,$i,xi,zi,ki,Ur=k(()=>{qe();Tr();P();B=u("$ZodCheck",(t,r)=>{var n;t._zod??(t._zod={}),t._zod.def=r,(n=t._zod).onattach??(n.onattach=[])}),Mc={number:"number",bigint:"bigint",object:"date"},Or=u("$ZodCheckLessThan",(t,r)=>{B.init(t,r);let n=Mc[typeof r.value];t._zod.onattach.push(i=>{let e=i._zod.bag,o=(r.inclusive?e.maximum:e.exclusiveMaximum)??Number.POSITIVE_INFINITY;r.value<o&&(r.inclusive?e.maximum=r.value:e.exclusiveMaximum=r.value)}),t._zod.check=i=>{(r.inclusive?i.value<=r.value:i.value<r.value)||i.issues.push({origin:n,code:"too_big",maximum:r.value,input:i.value,inclusive:r.inclusive,inst:t,continue:!r.abort})}}),Nr=u("$ZodCheckGreaterThan",(t,r)=>{B.init(t,r);let n=Mc[typeof r.value];t._zod.onattach.push(i=>{let e=i._zod.bag,o=(r.inclusive?e.minimum:e.exclusiveMinimum)??Number.NEGATIVE_INFINITY;r.value>o&&(r.inclusive?e.minimum=r.value:e.exclusiveMinimum=r.value)}),t._zod.check=i=>{(r.inclusive?i.value>=r.value:i.value>r.value)||i.issues.push({origin:n,code:"too_small",minimum:r.value,input:i.value,inclusive:r.inclusive,inst:t,continue:!r.abort})}}),si=u("$ZodCheckMultipleOf",(t,r)=>{B.init(t,r),t._zod.onattach.push(n=>{var i;(i=n._zod.bag).multipleOf??(i.multipleOf=r.value)}),t._zod.check=n=>{if(typeof n.value!=typeof r.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof n.value=="bigint"?n.value%r.value===BigInt(0):zo(n.value,r.value)===0)||n.issues.push({origin:typeof n.value,code:"not_multiple_of",divisor:r.value,input:n.value,inst:t,continue:!r.abort})}}),ci=u("$ZodCheckNumberFormat",(t,r)=>{B.init(t,r),r.format=r.format||"float64";let n=r.format?.includes("int"),i=n?"int":"number",[e,o]=jo[r.format];t._zod.onattach.push(a=>{let c=a._zod.bag;c.format=r.format,c.minimum=e,c.maximum=o,n&&(c.pattern=ei)}),t._zod.check=a=>{let c=a.value;if(n){if(!Number.isInteger(c)){a.issues.push({expected:i,format:r.format,code:"invalid_type",input:c,inst:t});return}if(!Number.isSafeInteger(c)){c>0?a.issues.push({input:c,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:i,continue:!r.abort}):a.issues.push({input:c,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:i,continue:!r.abort});return}}c<e&&a.issues.push({origin:"number",input:c,code:"too_small",minimum:e,inclusive:!0,inst:t,continue:!r.abort}),c>o&&a.issues.push({origin:"number",input:c,code:"too_big",maximum:o,inst:t})}}),ui=u("$ZodCheckBigIntFormat",(t,r)=>{B.init(t,r);let[n,i]=Po[r.format];t._zod.onattach.push(e=>{let o=e._zod.bag;o.format=r.format,o.minimum=n,o.maximum=i}),t._zod.check=e=>{let o=e.value;o<n&&e.issues.push({origin:"bigint",input:o,code:"too_small",minimum:n,inclusive:!0,inst:t,continue:!r.abort}),o>i&&e.issues.push({origin:"bigint",input:o,code:"too_big",maximum:i,inst:t})}}),li=u("$ZodCheckMaxSize",(t,r)=>{var n;B.init(t,r),(n=t._zod.def).when??(n.when=i=>{let e=i.value;return!ze(e)&&e.size!==void 0}),t._zod.onattach.push(i=>{let e=i._zod.bag.maximum??Number.POSITIVE_INFINITY;r.maximum<e&&(i._zod.bag.maximum=r.maximum)}),t._zod.check=i=>{let e=i.value;e.size<=r.maximum||i.issues.push({origin:Tt(e),code:"too_big",maximum:r.maximum,input:e,inst:t,continue:!r.abort})}}),mi=u("$ZodCheckMinSize",(t,r)=>{var n;B.init(t,r),(n=t._zod.def).when??(n.when=i=>{let e=i.value;return!ze(e)&&e.size!==void 0}),t._zod.onattach.push(i=>{let e=i._zod.bag.minimum??Number.NEGATIVE_INFINITY;r.minimum>e&&(i._zod.bag.minimum=r.minimum)}),t._zod.check=i=>{let e=i.value;e.size>=r.minimum||i.issues.push({origin:Tt(e),code:"too_small",minimum:r.minimum,input:e,inst:t,continue:!r.abort})}}),di=u("$ZodCheckSizeEquals",(t,r)=>{var n;B.init(t,r),(n=t._zod.def).when??(n.when=i=>{let e=i.value;return!ze(e)&&e.size!==void 0}),t._zod.onattach.push(i=>{let e=i._zod.bag;e.minimum=r.size,e.maximum=r.size,e.size=r.size}),t._zod.check=i=>{let e=i.value,o=e.size;if(o===r.size)return;let a=o>r.size;i.issues.push({origin:Tt(e),...a?{code:"too_big",maximum:r.size}:{code:"too_small",minimum:r.size},inclusive:!0,exact:!0,input:i.value,inst:t,continue:!r.abort})}}),pi=u("$ZodCheckMaxLength",(t,r)=>{var n;B.init(t,r),(n=t._zod.def).when??(n.when=i=>{let e=i.value;return!ze(e)&&e.length!==void 0}),t._zod.onattach.push(i=>{let e=i._zod.bag.maximum??Number.POSITIVE_INFINITY;r.maximum<e&&(i._zod.bag.maximum=r.maximum)}),t._zod.check=i=>{let e=i.value;if(e.length<=r.maximum)return;let a=Ot(e);i.issues.push({origin:a,code:"too_big",maximum:r.maximum,inclusive:!0,input:e,inst:t,continue:!r.abort})}}),fi=u("$ZodCheckMinLength",(t,r)=>{var n;B.init(t,r),(n=t._zod.def).when??(n.when=i=>{let e=i.value;return!ze(e)&&e.length!==void 0}),t._zod.onattach.push(i=>{let e=i._zod.bag.minimum??Number.NEGATIVE_INFINITY;r.minimum>e&&(i._zod.bag.minimum=r.minimum)}),t._zod.check=i=>{let e=i.value;if(e.length>=r.minimum)return;let a=Ot(e);i.issues.push({origin:a,code:"too_small",minimum:r.minimum,inclusive:!0,input:e,inst:t,continue:!r.abort})}}),gi=u("$ZodCheckLengthEquals",(t,r)=>{var n;B.init(t,r),(n=t._zod.def).when??(n.when=i=>{let e=i.value;return!ze(e)&&e.length!==void 0}),t._zod.onattach.push(i=>{let e=i._zod.bag;e.minimum=r.length,e.maximum=r.length,e.length=r.length}),t._zod.check=i=>{let e=i.value,o=e.length;if(o===r.length)return;let a=Ot(e),c=o>r.length;i.issues.push({origin:a,...c?{code:"too_big",maximum:r.length}:{code:"too_small",minimum:r.length},inclusive:!0,exact:!0,input:i.value,inst:t,continue:!r.abort})}}),Ke=u("$ZodCheckStringFormat",(t,r)=>{var n,i;B.init(t,r),t._zod.onattach.push(e=>{let o=e._zod.bag;o.format=r.format,r.pattern&&(o.patterns??(o.patterns=new Set),o.patterns.add(r.pattern))}),r.pattern?(n=t._zod).check??(n.check=e=>{r.pattern.lastIndex=0,!r.pattern.test(e.value)&&e.issues.push({origin:"string",code:"invalid_format",format:r.format,input:e.value,...r.pattern?{pattern:r.pattern.toString()}:{},inst:t,continue:!r.abort})}):(i=t._zod).check??(i.check=()=>{})}),hi=u("$ZodCheckRegex",(t,r)=>{Ke.init(t,r),t._zod.check=n=>{r.pattern.lastIndex=0,!r.pattern.test(n.value)&&n.issues.push({origin:"string",code:"invalid_format",format:"regex",input:n.value,pattern:r.pattern.toString(),inst:t,continue:!r.abort})}}),vi=u("$ZodCheckLowerCase",(t,r)=>{r.pattern??(r.pattern=ii),Ke.init(t,r)}),bi=u("$ZodCheckUpperCase",(t,r)=>{r.pattern??(r.pattern=ai),Ke.init(t,r)}),_i=u("$ZodCheckIncludes",(t,r)=>{B.init(t,r);let n=_e(r.includes),i=new RegExp(typeof r.position=="number"?`^.{${r.position}}${n}`:n);r.pattern=i,t._zod.onattach.push(e=>{let o=e._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(i)}),t._zod.check=e=>{e.value.includes(r.includes,r.position)||e.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:r.includes,input:e.value,inst:t,continue:!r.abort})}}),yi=u("$ZodCheckStartsWith",(t,r)=>{B.init(t,r);let n=new RegExp(`^${_e(r.prefix)}.*`);r.pattern??(r.pattern=n),t._zod.onattach.push(i=>{let e=i._zod.bag;e.patterns??(e.patterns=new Set),e.patterns.add(n)}),t._zod.check=i=>{i.value.startsWith(r.prefix)||i.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:r.prefix,input:i.value,inst:t,continue:!r.abort})}}),$i=u("$ZodCheckEndsWith",(t,r)=>{B.init(t,r);let n=new RegExp(`.*${_e(r.suffix)}$`);r.pattern??(r.pattern=n),t._zod.onattach.push(i=>{let e=i._zod.bag;e.patterns??(e.patterns=new Set),e.patterns.add(n)}),t._zod.check=i=>{i.value.endsWith(r.suffix)||i.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:r.suffix,input:i.value,inst:t,continue:!r.abort})}});xi=u("$ZodCheckProperty",(t,r)=>{B.init(t,r),t._zod.check=n=>{let i=r.schema._zod.run({value:n.value[r.property],issues:[]},{});if(i instanceof Promise)return i.then(e=>Cc(e,n,r.property));Cc(i,n,r.property)}}),zi=u("$ZodCheckMimeType",(t,r)=>{B.init(t,r);let n=new Set(r.mime);t._zod.onattach.push(i=>{i._zod.bag.mime=r.mime}),t._zod.check=i=>{n.has(i.value.type)||i.issues.push({code:"invalid_value",values:r.mime,input:i.value.type,inst:t})}}),ki=u("$ZodCheckOverwrite",(t,r)=>{B.init(t,r),t._zod.check=n=>{n.value=r.tx(n.value)}})});var Zt,Si=k(()=>{Zt=class{constructor(r=[]){this.content=[],this.indent=0,this&&(this.args=r)}indented(r){this.indent+=1,r(this),this.indent-=1}write(r){if(typeof r=="function"){r(this,{execution:"sync"}),r(this,{execution:"async"});return}let i=r.split(``).filter(a=>a),e=Math.min(...i.map(a=>a.length-a.trimStart().length)),o=i.map(a=>a.slice(e)).map(a=>" ".repeat(this.indent*2)+a);for(let a of o)this.content.push(a)}compile(){let r=Function,n=this?.args,e=[...(this?.content??[""]).map(o=>` ${o}`)];return new r(...n,e.join(``))}}});var wi,Ii=k(()=>{wi={major:4,minor:0,patch:0}});function Wi(t){if(t==="")return!0;if(t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}function Xc(t){if(!Pr.test(t))return!1;let r=t.replace(/[-_]/g,i=>i==="-"?"+":"/"),n=r.padEnd(Math.ceil(r.length/4)*4,"=");return Wi(n)}function eu(t,r=null){try{let n=t.split(".");if(n.length!==3)return!1;let[i]=n;if(!i)return!1;let e=JSON.parse(atob(i));return!("typ"in e&&e?.typ!=="JWT"||!e.alg||r&&(!("alg"in e)||e.alg!==r))}catch{return!1}}function qc(t,r,n){t.issues.length&&r.issues.push(...ie(n,t.issues)),r.value[n]=t.value}function Er(t,r,n){t.issues.length&&r.issues.push(...ie(n,t.issues)),r.value[n]=t.value}function Vc(t,r,n,i){t.issues.length?i[n]===void 0?n in i?r.value[n]=void 0:r.value[n]=t.value:r.issues.push(...ie(n,t.issues)):t.value===void 0?n in i&&(r.value[n]=void 0):r.value[n]=t.value}function Fc(t,r,n,i){for(let e of t)if(e.issues.length===0)return r.value=e.value,r;return r.issues.push({code:"invalid_union",input:r.value,inst:n,errors:t.map(e=>e.issues.map(o=>se(o,i,W())))}),r}function ji(t,r){if(t===r)return{valid:!0,data:t};if(t instanceof Date&&r instanceof Date&&+t==+r)return{valid:!0,data:t};if(Fe(t)&&Fe(r)){let n=Object.keys(r),i=Object.keys(t).filter(o=>n.indexOf(o)!==-1),e={...t,...r};for(let o of i){let a=ji(t[o],r[o]);if(!a.valid)return{valid:!1,mergeErrorPath:[o,...a.mergeErrorPath]};e[o]=a.data}return{valid:!0,data:e}}if(Array.isArray(t)&&Array.isArray(r)){if(t.length!==r.length)return{valid:!1,mergeErrorPath:[]};let n=[];for(let i=0;i<t.length;i++){let e=t[i],o=r[i],a=ji(e,o);if(!a.valid)return{valid:!1,mergeErrorPath:[i,...a.mergeErrorPath]};n.push(a.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function Hc(t,r,n){if(r.issues.length&&t.issues.push(...r.issues),n.issues.length&&t.issues.push(...n.issues),Ne(t))return t;let i=ji(r.value,n.value);if(!i.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(i.mergeErrorPath)}`);return t.value=i.data,t}function Dr(t,r,n){t.issues.length&&r.issues.push(...ie(n,t.issues)),r.value[n]=t.value}function Jc(t,r,n,i,e,o,a){t.issues.length&&(Pt.has(typeof i)?n.issues.push(...ie(i,t.issues)):n.issues.push({origin:"map",code:"invalid_key",input:e,inst:o,issues:t.issues.map(c=>se(c,a,W()))})),r.issues.length&&(Pt.has(typeof i)?n.issues.push(...ie(i,r.issues)):n.issues.push({origin:"map",code:"invalid_element",input:e,inst:o,key:i,issues:r.issues.map(c=>se(c,a,W()))})),n.value.set(t.value,r.value)}function Bc(t,r){t.issues.length&&r.issues.push(...t.issues),r.value.add(t.value)}function Wc(t,r){return t.value===void 0&&(t.value=r.defaultValue),t}function Kc(t,r){return!t.issues.length&&t.value===void 0&&t.issues.push({code:"invalid_type",expected:"nonoptional",input:t.value,inst:r}),t}function Gc(t,r,n){return Ne(t)?t:r.out._zod.run({value:t.value,issues:t.issues},n)}function Qc(t){return t.value=Object.freeze(t.value),t}function Yc(t,r,n,i){if(!t){let e={code:"custom",input:n,inst:i,path:[...i._zod.def.path??[]],continue:!i._zod.def.abort};i._zod.def.params&&(e.params=i._zod.def.params),r.issues.push(To(e))}}var T,Ee,V,Pi,Ti,Oi,Ni,Ui,Ei,Di,Zi,Ri,Ai,Ci,Mi,Li,qi,Vi,Fi,Hi,Ji,Bi,Ki,Gi,Qi,Yi,Xi,Zr,ea,Rt,Rr,ta,ra,na,oa,ia,Ge,aa,sa,ca,At,ua,Ar,la,ma,De,da,pa,fa,ga,ha,va,Ct,ba,_a,ya,$a,xa,za,ka,Sa,Mt,wa,Ia,ja,Pa,Ta,Lt=k(()=>{Ur();qe();Si();jr();Tr();P();Ii();P();T=u("$ZodType",(t,r)=>{var n;t??(t={}),t._zod.def=r,t._zod.bag=t._zod.bag||{},t._zod.version=wi;let i=[...t._zod.def.checks??[]];t._zod.traits.has("$ZodCheck")&&i.unshift(t);for(let e of i)for(let o of e._zod.onattach)o(t);if(i.length===0)(n=t._zod).deferred??(n.deferred=[]),t._zod.deferred?.push(()=>{t._zod.run=t._zod.parse});else{let e=(o,a,c)=>{let l=Ne(o),h;for(let g of a){if(g._zod.def.when){if(!g._zod.def.when(o))continue}else if(l)continue;let m=o.issues.length,$=g._zod.check(o);if($ instanceof Promise&&c?.async===!1)throw new pe;if(h||$ instanceof Promise)h=(h??Promise.resolve()).then(async()=>{await $,o.issues.length!==m&&(l||(l=Ne(o,m)))});else{if(o.issues.length===m)continue;l||(l=Ne(o,m))}}return h?h.then(()=>o):o};t._zod.run=(o,a)=>{let c=t._zod.parse(o,a);if(c instanceof Promise){if(a.async===!1)throw new pe;return c.then(l=>e(l,i,a))}return e(c,i,a)}}t["~standard"]={validate:e=>{try{let o=We(t,e);return o.success?{value:o.data}:{issues:o.error?.issues}}catch{return Dt(t,e).then(a=>a.success?{value:a.data}:{issues:a.error?.issues})}},vendor:"zod",version:1}}),Ee=u("$ZodString",(t,r)=>{T.init(t,r),t._zod.pattern=[...t?._zod.bag?.patterns??[]].pop()??Yo(t._zod.bag),t._zod.parse=(n,i)=>{if(r.coerce)try{n.value=String(n.value)}catch{}return typeof n.value=="string"||n.issues.push({expected:"string",code:"invalid_type",input:n.value,inst:t}),n}}),V=u("$ZodStringFormat",(t,r)=>{Ke.init(t,r),Ee.init(t,r)}),Pi=u("$ZodGUID",(t,r)=>{r.pattern??(r.pattern=Co),V.init(t,r)}),Ti=u("$ZodUUID",(t,r)=>{if(r.version){let i={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[r.version];if(i===void 0)throw new Error(`Invalid UUID version: "${r.version}"`);r.pattern??(r.pattern=Ue(i))}else r.pattern??(r.pattern=Ue());V.init(t,r)}),Oi=u("$ZodEmail",(t,r)=>{r.pattern??(r.pattern=Mo),V.init(t,r)}),Ni=u("$ZodURL",(t,r)=>{V.init(t,r),t._zod.check=n=>{try{let i=n.value,e=new URL(i),o=e.href;r.hostname&&(r.hostname.lastIndex=0,r.hostname.test(e.hostname)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:Bo.source,input:n.value,inst:t,continue:!r.abort})),r.protocol&&(r.protocol.lastIndex=0,r.protocol.test(e.protocol.endsWith(":")?e.protocol.slice(0,-1):e.protocol)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:r.protocol.source,input:n.value,inst:t,continue:!r.abort})),!i.endsWith("/")&&o.endsWith("/")?n.value=o.slice(0,-1):n.value=o;return}catch{n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:t,continue:!r.abort})}}}),Ui=u("$ZodEmoji",(t,r)=>{r.pattern??(r.pattern=Lo()),V.init(t,r)}),Ei=u("$ZodNanoID",(t,r)=>{r.pattern??(r.pattern=Ro),V.init(t,r)}),Di=u("$ZodCUID",(t,r)=>{r.pattern??(r.pattern=No),V.init(t,r)}),Zi=u("$ZodCUID2",(t,r)=>{r.pattern??(r.pattern=Uo),V.init(t,r)}),Ri=u("$ZodULID",(t,r)=>{r.pattern??(r.pattern=Eo),V.init(t,r)}),Ai=u("$ZodXID",(t,r)=>{r.pattern??(r.pattern=Do),V.init(t,r)}),Ci=u("$ZodKSUID",(t,r)=>{r.pattern??(r.pattern=Zo),V.init(t,r)}),Mi=u("$ZodISODateTime",(t,r)=>{r.pattern??(r.pattern=Qo(r)),V.init(t,r)}),Li=u("$ZodISODate",(t,r)=>{r.pattern??(r.pattern=Ko),V.init(t,r)}),qi=u("$ZodISOTime",(t,r)=>{r.pattern??(r.pattern=Go(r)),V.init(t,r)}),Vi=u("$ZodISODuration",(t,r)=>{r.pattern??(r.pattern=Ao),V.init(t,r)}),Fi=u("$ZodIPv4",(t,r)=>{r.pattern??(r.pattern=qo),V.init(t,r),t._zod.onattach.push(n=>{let i=n._zod.bag;i.format="ipv4"})}),Hi=u("$ZodIPv6",(t,r)=>{r.pattern??(r.pattern=Vo),V.init(t,r),t._zod.onattach.push(n=>{let i=n._zod.bag;i.format="ipv6"}),t._zod.check=n=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:t,continue:!r.abort})}}}),Ji=u("$ZodCIDRv4",(t,r)=>{r.pattern??(r.pattern=Fo),V.init(t,r)}),Bi=u("$ZodCIDRv6",(t,r)=>{r.pattern??(r.pattern=Ho),V.init(t,r),t._zod.check=n=>{let[i,e]=n.value.split("/");try{if(!e)throw new Error;let o=Number(e);if(`${o}`!==e)throw new Error;if(o<0||o>128)throw new Error;new URL(`http://[${i}]`)}catch{n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:t,continue:!r.abort})}}});Ki=u("$ZodBase64",(t,r)=>{r.pattern??(r.pattern=Jo),V.init(t,r),t._zod.onattach.push(n=>{n._zod.bag.contentEncoding="base64"}),t._zod.check=n=>{Wi(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:t,continue:!r.abort})}});Gi=u("$ZodBase64URL",(t,r)=>{r.pattern??(r.pattern=Pr),V.init(t,r),t._zod.onattach.push(n=>{n._zod.bag.contentEncoding="base64url"}),t._zod.check=n=>{Xc(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:t,continue:!r.abort})}}),Qi=u("$ZodE164",(t,r)=>{r.pattern??(r.pattern=Wo),V.init(t,r)});Yi=u("$ZodJWT",(t,r)=>{V.init(t,r),t._zod.check=n=>{eu(n.value,r.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:t,continue:!r.abort})}}),Xi=u("$ZodCustomStringFormat",(t,r)=>{V.init(t,r),t._zod.check=n=>{r.fn(n.value)||n.issues.push({code:"invalid_format",format:r.format,input:n.value,inst:t,continue:!r.abort})}}),Zr=u("$ZodNumber",(t,r)=>{T.init(t,r),t._zod.pattern=t._zod.bag.pattern??ti,t._zod.parse=(n,i)=>{if(r.coerce)try{n.value=Number(n.value)}catch{}let e=n.value;if(typeof e=="number"&&!Number.isNaN(e)&&Number.isFinite(e))return n;let o=typeof e=="number"?Number.isNaN(e)?"NaN":Number.isFinite(e)?void 0:"Infinity":void 0;return n.issues.push({expected:"number",code:"invalid_type",input:e,inst:t,...o?{received:o}:{}}),n}}),ea=u("$ZodNumber",(t,r)=>{ci.init(t,r),Zr.init(t,r)}),Rt=u("$ZodBoolean",(t,r)=>{T.init(t,r),t._zod.pattern=ri,t._zod.parse=(n,i)=>{if(r.coerce)try{n.value=!!n.value}catch{}let e=n.value;return typeof e=="boolean"||n.issues.push({expected:"boolean",code:"invalid_type",input:e,inst:t}),n}}),Rr=u("$ZodBigInt",(t,r)=>{T.init(t,r),t._zod.pattern=Xo,t._zod.parse=(n,i)=>{if(r.coerce)try{n.value=BigInt(n.value)}catch{}return typeof n.value=="bigint"||n.issues.push({expected:"bigint",code:"invalid_type",input:n.value,inst:t}),n}}),ta=u("$ZodBigInt",(t,r)=>{ui.init(t,r),Rr.init(t,r)}),ra=u("$ZodSymbol",(t,r)=>{T.init(t,r),t._zod.parse=(n,i)=>{let e=n.value;return typeof e=="symbol"||n.issues.push({expected:"symbol",code:"invalid_type",input:e,inst:t}),n}}),na=u("$ZodUndefined",(t,r)=>{T.init(t,r),t._zod.pattern=oi,t._zod.values=new Set([void 0]),t._zod.optin="optional",t._zod.optout="optional",t._zod.parse=(n,i)=>{let e=n.value;return typeof e>"u"||n.issues.push({expected:"undefined",code:"invalid_type",input:e,inst:t}),n}}),oa=u("$ZodNull",(t,r)=>{T.init(t,r),t._zod.pattern=ni,t._zod.values=new Set([null]),t._zod.parse=(n,i)=>{let e=n.value;return e===null||n.issues.push({expected:"null",code:"invalid_type",input:e,inst:t}),n}}),ia=u("$ZodAny",(t,r)=>{T.init(t,r),t._zod.parse=n=>n}),Ge=u("$ZodUnknown",(t,r)=>{T.init(t,r),t._zod.parse=n=>n}),aa=u("$ZodNever",(t,r)=>{T.init(t,r),t._zod.parse=(n,i)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:t}),n)}),sa=u("$ZodVoid",(t,r)=>{T.init(t,r),t._zod.parse=(n,i)=>{let e=n.value;return typeof e>"u"||n.issues.push({expected:"void",code:"invalid_type",input:e,inst:t}),n}}),ca=u("$ZodDate",(t,r)=>{T.init(t,r),t._zod.parse=(n,i)=>{if(r.coerce)try{n.value=new Date(n.value)}catch{}let e=n.value,o=e instanceof Date;return o&&!Number.isNaN(e.getTime())||n.issues.push({expected:"date",code:"invalid_type",input:e,...o?{received:"Invalid Date"}:{},inst:t}),n}});At=u("$ZodArray",(t,r)=>{T.init(t,r),t._zod.parse=(n,i)=>{let e=n.value;if(!Array.isArray(e))return n.issues.push({expected:"array",code:"invalid_type",input:e,inst:t}),n;n.value=Array(e.length);let o=[];for(let a=0;a<e.length;a++){let c=e[a],l=r.element._zod.run({value:c,issues:[]},i);l instanceof Promise?o.push(l.then(h=>qc(h,n,a))):qc(l,n,a)}return o.length?Promise.all(o).then(()=>n):n}});ua=u("$ZodObject",(t,r)=>{T.init(t,r);let n=It(()=>{let m=Object.keys(r.shape);for(let b of m)if(!(r.shape[b]instanceof T))throw new Error(`Invalid element at key "${b}": expected a Zod schema`);let $=Io(r.shape);return{shape:r.shape,keys:m,keySet:new Set(m),numKeys:m.length,optionalKeys:new Set($)}});R(t._zod,"propValues",()=>{let m=r.shape,$={};for(let b in m){let p=m[b]._zod;if(p.values){$[b]??($[b]=new Set);for(let x of p.values)$[b].add(x)}}return $});let i=m=>{let $=new Zt(["shape","payload","ctx"]),b=n.value,p=w=>{let j=Oe(w);return`shape[${j}]._zod.run({ value: input[${j}], issues: [] }, ctx)`};$.write("const input = payload.value;");let x=Object.create(null),S=0;for(let w of b.keys)x[w]=`key_${S++}`;$.write("const newResult = {}");for(let w of b.keys)if(b.optionalKeys.has(w)){let j=x[w];$.write(`const ${j} = ${p(w)};`);let U=Oe(w);$.write(`diff --git a/scripts/audit-image-loading.mjs b/scripts/audit-image-loading.mjsindex 9d28f0c41..a5dfeb366 100644--- a/scripts/audit-image-loading.mjs+++ b/scripts/audit-image-loading.mjs@@ -22,14 +22,16 @@import { readFileSync, readdirSync } from 'node:fs';import { resolve, dirname, join, relative } from 'node:path';import { fileURLToPath } from 'node:url';+import { maskComments } from './lib/js-comment-ranges.mjs';const root = resolve(dirname(fileURLToPath(import.meta.url)), '..');const SRC_DIR = resolve(root, 'src');const strict = process.argv.includes('--strict');-// A real <img> tag: `<img` + whitespace + an attribute name. Excludes bare-// `<img>` that appears as literal text inside code comments.-const IMG_TAG = /<img(\s+[a-zA-Z][^>]*?)?>/g;+// A real <img> tag: `<img` + whitespace + an attribute name. Comments are+// masked out before matching (see maskComments), so prose that quotes a tag,+// such as an XSS note about `<img onerror=…>`, is never mistaken for markup+// this codebase renders.const REAL_IMG = /<img(?=\s+[a-zA-Z])([^>]*?)>/g;function walk(dir) {@@ -44,7 +46,7 @@ function walk(dir) {const offenders = [];for (const file of walk(SRC_DIR)) {- const src = readFileSync(file, 'utf8');+ const src = maskComments(readFileSync(file, 'utf8'));let m;REAL_IMG.lastIndex = 0;while ((m = REAL_IMG.exec(src)) !== null) {diff --git a/scripts/codemod-lazy-images.mjs b/scripts/codemod-lazy-images.mjsindex bbdb82d57..e3427293e 100644--- a/scripts/codemod-lazy-images.mjs+++ b/scripts/codemod-lazy-images.mjs@@ -17,6 +17,7 @@import { readFileSync, writeFileSync } from 'node:fs';import { execSync } from 'node:child_process';+import { commentRanges, isInsideComment } from './lib/js-comment-ranges.mjs';const dryRun = process.argv.includes('--dry-run');const files = execSync('grep -rlE "<img\\b" src/', { encoding: 'utf8' })@@ -31,11 +32,14 @@ for (const file of files) {const src = readFileSync(file, 'utf8');let edits = 0;// Match a REAL <img tag: `<img` + whitespace + an attribute name (a letter).- // This excludes bare `<img>` that appears as literal text inside code- // comments. Skip any tag that already declares loading=. We insert the two- // attributes immediately after `<img`, preserving the original whitespace- // and all existing attributes verbatim.- const out = src.replace(/<img(?![^>]*\bloading=)(\s+[a-zA-Z])/g, (_m, next) => {+ // Matches inside comments are left alone: prose that quotes a tag, such as+ // an XSS note about `<img onerror=…>`, renders nothing, and rewriting it+ // would corrupt the explanation. Skip any tag that already declares+ // loading=. We insert the two attributes immediately after `<img`,+ // preserving the original whitespace and all existing attributes verbatim.+ const comments = commentRanges(src);+ const out = src.replace(/<img(?![^>]*\bloading=)(\s+[a-zA-Z])/g, (m, next, offset) => {+ if (isInsideComment(comments, offset)) return m;edits++;return `<img loading="lazy" decoding="async"${next}`;});diff --git a/scripts/lib/js-comment-ranges.mjs b/scripts/lib/js-comment-ranges.mjsnew file mode 100644index 000000000..5623f64cc--- /dev/null+++ b/scripts/lib/js-comment-ranges.mjs@@ -0,0 +1,180 @@+/**+ * js-comment-ranges.mjs: locate the comment spans of a JavaScript source file.+ *+ * Source-scanning guards match patterns with a regular expression, and a bare+ * regex cannot tell code from prose. A security comment that quotes the very+ * markup it defends against (`<img onerror=…>` in an XSS note) reads to a+ * pattern matcher exactly like a shipped tag, so a guard reports it and the+ * matching codemod rewrites it, corrupting the explanation. Comments describe+ * code, they never render, so every such scanner wants the same primitive:+ * where do the comments start and end.+ *+ * The scanner walks the source character by character and tracks the four+ * contexts where a `/` is not a comment: quoted strings, template literals+ * (including the code inside `${}`, arbitrarily nested), and regular-expression+ * literals. Regex-versus-division is decided from the previous significant+ * token, the same heuristic every JS tokenizer uses.+ */++// Tokens after which a `/` opens a regular expression rather than dividing.+const REGEX_PRECEDING_CHARS = new Set(['', '(', ',', '=', ':', '[', '!', '&', '|', '?', '{', '}', ';', '+', '-', '*', '%', '~', '^', '<', '>']);+const REGEX_PRECEDING_WORDS = new Set(['return', 'typeof', 'instanceof', 'in', 'of', 'new', 'delete', 'void', 'throw', 'case', 'do', 'else', 'yield', 'await']);++const IDENT_START = /[A-Za-z_$]/;+const IDENT_PART = /[A-Za-z0-9_$]/;++function skipQuoted(src, start) {+ const quote = src[start];+ let i = start + 1;+ while (i < src.length) {+ const c = src[i];+ if (c === '\\') { i += 2; continue; }+ if (c === quote || c === '\n') return i + 1;+ i++;+ }+ return i;+}++function skipRegex(src, start) {+ let i = start + 1;+ let inClass = false;+ while (i < src.length) {+ const c = src[i];+ if (c === '\\') { i += 2; continue; }+ if (c === '\n') return i;+ if (c === '[') inClass = true;+ else if (c === ']') inClass = false;+ else if (c === '/' && !inClass) { i++; break; }+ i++;+ }+ while (i < src.length && IDENT_PART.test(src[i])) i++;+ return i;+}++/**+ * Every comment in `src`, as `{ start, end }` half-open index ranges, in order.+ */+export function commentRanges(src) {+ const ranges = [];+ const templateBraces = [];+ let braceDepth = 0;+ let inTemplate = false;+ let prevChar = '';+ let prevWord = '';+ let i = 0;++ while (i < src.length) {+ const c = src[i];+ const d = src[i + 1];++ if (inTemplate) {+ if (c === '\\') { i += 2; continue; }+ if (c === '`') { inTemplate = false; prevChar = '`'; prevWord = ''; i++; continue; }+ if (c === '$' && d === '{') {+ templateBraces.push(braceDepth);+ braceDepth++;+ inTemplate = false;+ prevChar = '{';+ prevWord = '';+ i += 2;+ continue;+ }+ i++;+ continue;+ }++ if (c === '/' && d === '/') {+ const start = i;+ i += 2;+ while (i < src.length && src[i] !== '\n') i++;+ ranges.push({ start, end: i });+ continue;+ }+ if (c === '/' && d === '*') {+ const start = i;+ i += 2;+ while (i < src.length && !(src[i] === '*' && src[i + 1] === '/')) i++;+ i = Math.min(i + 2, src.length);+ ranges.push({ start, end: i });+ continue;+ }+ if (c === '"' || c === "'") {+ i = skipQuoted(src, i);+ prevChar = c;+ prevWord = '';+ continue;+ }+ if (c === '`') {+ inTemplate = true;+ i++;+ continue;+ }+ if (c === '/') {+ if (REGEX_PRECEDING_CHARS.has(prevChar) || REGEX_PRECEDING_WORDS.has(prevWord)) {+ i = skipRegex(src, i);+ prevChar = '/';+ prevWord = '';+ continue;+ }+ prevChar = '/';+ prevWord = '';+ i++;+ continue;+ }+ if (IDENT_START.test(c)) {+ const start = i;+ while (i < src.length && IDENT_PART.test(src[i])) i++;+ prevWord = src.slice(start, i);+ prevChar = src[i - 1];+ continue;+ }+ if (c === '{') { braceDepth++; prevChar = '{'; prevWord = ''; i++; continue; }+ if (c === '}') {+ if (templateBraces.length > 0 && braceDepth === templateBraces[templateBraces.length - 1] + 1) {+ templateBraces.pop();+ braceDepth--;+ inTemplate = true;+ i++;+ continue;+ }+ braceDepth--;+ prevChar = '}';+ prevWord = '';+ i++;+ continue;+ }+ if (!/\s/.test(c)) { prevChar = c; prevWord = ''; }+ i++;+ }++ return ranges;+}++/** True when `index` falls inside one of the ranges from `commentRanges`. */+export function isInsideComment(ranges, index) {+ for (const { start, end } of ranges) {+ if (index < start) return false;+ if (index < end) return true;+ }+ return false;+}++/**+ * `src` with every comment character replaced by a space, newlines kept. Index+ * and line numbers stay identical to the original, so a scanner can match+ * against the masked text and report positions against the real file.+ */+export function maskComments(src) {+ const ranges = commentRanges(src);+ if (ranges.length === 0) return src;+ // Sliced by UTF-16 code unit, never by code point: an emoji in a comment is+ // two units, and blanking it as one character would shift every index after+ // it, silently masking real code in any file that contains one.+ let out = '';+ let cursor = 0;+ for (const { start, end } of ranges) {+ out += src.slice(cursor, start) + src.slice(start, end).replace(/[^\n]/g, ' ');+ cursor = end;+ }+ return out + src.slice(cursor);+}diff --git a/src/render-lab.js b/src/render-lab.jsindex b163235e2..100389ef4 100644--- a/src/render-lab.js+++ b/src/render-lab.js@@ -395,7 +395,7 @@ function codeFor(lang) {return `<script type="module" src="${origin}/agent-3d/latest/agent-3d.js"><\/script>\n<agent-3d\n src="${state.source.url}"\n style="width: ${state.size}px; height: ${state.size}px; display: block;"\n></agent-3d>`;}if (lang === 'html') {- return `<!-- POST /api/render/avatar-clip returns image bytes, so render it\n server-side and serve the result, or fetch it into an object URL. -->\n<img src="/your-cached-render.png" alt="" width="${state.size}" height="${state.size}" />`;+ return `<!-- POST /api/render/avatar-clip returns image bytes, so render it\n server-side and serve the result, or fetch it into an object URL. -->\n<img src="/your-cached-render.png" alt="" width="${state.size}" height="${state.size}" loading="lazy" />`;}return `POST ${origin}/api/render/avatar-clip\n\n${body}`;}diff --git a/src/walkthrough.js b/src/walkthrough.jsindex 7a2f24008..2fa57f745 100644--- a/src/walkthrough.js+++ b/src/walkthrough.js@@ -70,7 +70,7 @@ function shellHtml(w) {<span aria-hidden="true">‹</span></button><figure class="wt-stage" id="wt-stage" role="group" aria-roledescription="walkthrough" aria-label="${esc(w.title)}">- <img class="wt-frame" id="wt-frame" alt="" decoding="async" />+ <img class="wt-frame" id="wt-frame" alt="" decoding="async" loading="eager" /><div class="wt-spot" id="wt-spot" aria-hidden="true"></div><div class="wt-callout" id="wt-callout" data-side="right"><p class="wt-callout-count" id="wt-count"></p>diff --git a/tests/js-comment-ranges.test.js b/tests/js-comment-ranges.test.jsnew file mode 100644index 000000000..8272f354a--- /dev/null+++ b/tests/js-comment-ranges.test.js@@ -0,0 +1,87 @@+// Source-scanning guards read this codebase with regular expressions, and a+// regex cannot tell code from prose. The image-loading guard proved it: it+// reported three offenders that do not exist, because a security comment in+// src/game/combat-system.js quotes `<img onerror=…>` while explaining why the+// tombstone prompt is built with textContent, and src/ipfs.js names `<img src>`+// while explaining its scheme allowlist. Worse, the codemod the guard tells you+// to run would have rewritten both explanations in place.+//+// commentRanges is the primitive that fixes that class of bug for every such+// scanner, so what it must get right is exactly the places a `/` is not a+// comment: quoted strings, template literals, the code inside `${}`, and+// regular-expression literals. Each of those is a real pattern in src/, and+// each would silently corrupt a scan if the walker lost track of it.++import { describe, it, expect } from 'vitest';+import { commentRanges, isInsideComment, maskComments } from '../scripts/lib/js-comment-ranges.mjs';++/** The comment text the scanner found, for readable assertions. */+function comments(src) {+ return commentRanges(src).map(({ start, end }) => src.slice(start, end));+}++describe('commentRanges', () => {+ it('finds line and block comments', () => {+ expect(comments('const a = 1; // trailing\n/* block */ const b = 2;')).toEqual(['// trailing', '/* block */']);+ });++ it('ignores comment markers inside quoted strings', () => {+ expect(comments(`const url = 'https://three.ws/a'; // real\n`)).toEqual(['// real']);+ expect(comments('const s = "/* not a comment */";')).toEqual([]);+ });++ it('ignores comment markers inside template literals and their expressions', () => {+ expect(comments('const t = `https://three.ws/${id}/img`;')).toEqual([]);+ expect(comments('const t = `${obj["//"]}`; // real')).toEqual(['// real']);+ });++ it('tracks nested template expressions', () => {+ const src = 'const t = `a${ `b${ c["//x"] }d` }e`; // real';+ expect(comments(src)).toEqual(['// real']);+ });++ it('ignores comment markers inside regular-expression literals', () => {+ expect(comments('const re = /^https:\\/\\//; // real')).toEqual(['// real']);+ expect(comments('src.replace(/\\/\\*x\\*\\//g, "");')).toEqual([]);+ });++ it('does not mistake division for a regular expression', () => {+ expect(comments('const ratio = (a) / (b) / (c); // real')).toEqual(['// real']);+ });++ it('leaves an unterminated block comment closed at end of file', () => {+ expect(comments('const a = 1;\n/* never closed')).toEqual(['/* never closed']);+ });+});++describe('maskComments', () => {+ it('preserves length and line numbers so positions stay reportable', () => {+ const src = 'const a = 1; // note\nconst b = 2;\n';+ const masked = maskComments(src);+ expect(masked.length).toBe(src.length);+ expect(masked.split('\n').length).toBe(src.split('\n').length);+ expect(masked).toBe(`const a = 1;${' '.repeat(8)}\nconst b = 2;\n`);+ });++ it('hides a tag quoted in prose but keeps the one the code renders', () => {+ const src = [+ '// A display name like `<img onerror=alert(1)>` must render as text.',+ 'export const thumb = (u) => `<img src="${u}" alt="" loading="lazy">`;',+ ].join('\n');+ const masked = maskComments(src);+ expect(masked).not.toContain('<img onerror');+ expect(masked).toContain('<img src="${u}" alt="" loading="lazy">');+ });+});++describe('isInsideComment', () => {+ it('answers for positions before, inside and after each range', () => {+ const src = 'a; // one\nb; /* two */ c;';+ const ranges = commentRanges(src);+ expect(isInsideComment(ranges, src.indexOf('a'))).toBe(false);+ expect(isInsideComment(ranges, src.indexOf('one'))).toBe(true);+ expect(isInsideComment(ranges, src.indexOf('b'))).toBe(false);+ expect(isInsideComment(ranges, src.indexOf('two'))).toBe(true);+ expect(isInsideComment(ranges, src.indexOf('c'))).toBe(false);+ });+});