@enslo/sd-metadata 2.3.0 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- var sdMetadata=(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:`Module`});let t=(e,t)=>t===void 0?[]:[{type:`tEXt`,keyword:e,text:t}],n=(e,t)=>t===void 0?[]:[{type:`iTXt`,keyword:e,compressionFlag:0,compressionMethod:0,languageTag:``,translatedKeyword:``,text:t}],r=(e,t)=>e.find(e=>e.source.type===t),i=e=>{if(e!==void 0)return typeof e==`string`?e:JSON.stringify(e)};function a(e){return e.replace(/[\u0100-\uffff]/g,e=>`\\u${e.charCodeAt(0).toString(16).padStart(4,`0`)}`)}function o(e){return e.replace(/\\u([0-9a-fA-F]{4})/g,(e,t)=>String.fromCharCode(Number.parseInt(t,16)))}function s(e){return/[^\x00-\xFF]/.test(e)}function c(e,r,i){if(r===void 0)return[];switch(i){case`dynamic`:return(s(r)?`iTXt`:`tEXt`)==`iTXt`?n(e,r):t(e,r);case`text-unicode-escape`:return t(e,a(r));case`text-utf8-raw`:return t(e,r)}}function l(e,t){return e.flatMap(([e,n])=>c(e,n,t[e]??t.default))}let u={ok:e=>({ok:!0,value:e}),error:e=>({ok:!1,error:e})};function d(e){return e instanceof ArrayBuffer?new Uint8Array(e):e}function f(e){return e.length<8?!1:e[0]===137&&e[1]===80&&e[2]===78&&e[3]===71&&e[4]===13&&e[5]===10&&e[6]===26&&e[7]===10}function p(e){return e.length<2?!1:e[0]===255&&e[1]===216}function m(e){return e.length<12?!1:e[0]===82&&e[1]===73&&e[2]===70&&e[3]===70&&e[8]===87&&e[9]===69&&e[10]===66&&e[11]===80}function h(e){return f(e)?`png`:p(e)?`jpeg`:m(e)?`webp`:null}function g(e,t){return new DataView(e.buffer,e.byteOffset,e.byteLength).getUint16(t)}function _(e,t,n){return new DataView(e.buffer,e.byteOffset,e.byteLength).getUint16(t,n)}function v(e,t){return(e[t]??0)|(e[t+1]??0)<<8|(e[t+2]??0)<<16}function y(e,t){return new DataView(e.buffer,e.byteOffset,e.byteLength).getUint32(t)}function b(e,t){return new DataView(e.buffer,e.byteOffset,e.byteLength).getUint32(t,!0)}function x(e,t,n){return new DataView(e.buffer,e.byteOffset,e.byteLength).getUint32(t,n)}function S(e,t){return String.fromCharCode(e[t]??0,e[t+1]??0,e[t+2]??0,e[t+3]??0)}function C(e,t,n){new DataView(e.buffer,e.byteOffset,e.byteLength).setUint16(t,n)}function w(e,t,n,r){new DataView(e.buffer,e.byteOffset,e.byteLength).setUint16(t,n,r)}function ee(e,t,n){new DataView(e.buffer,e.byteOffset,e.byteLength).setUint32(t,n)}function te(e,t,n){new DataView(e.buffer,e.byteOffset,e.byteLength).setUint32(t,n,!0)}function T(e,t,n,r){new DataView(e.buffer,e.byteOffset,e.byteLength).setUint32(t,n,r)}let E=new TextEncoder().encode(`http://ns.adobe.com/xap/1.0/\0`);function ne(e,t){if(t+E.length>e.length)return!1;for(let n=0;n<E.length;n++)if(e[t+n]!==E[n])return!1;return!0}function re(e){return e===`XML:com.adobe.xmp`}function ie(e){if(e.length>65535)return null;let t=[[`CreatorTool`,ae(e,`xmp`,`CreatorTool`)],[`UserComment`,oe(e,`exif`,`UserComment`)],[`parameters`,oe(e,`dc`,`description`)]].filter(e=>e[1]!==void 0);return t.length>0?Object.fromEntries(t):null}function ae(e,t,n){let r=RegExp(`<${t}:${n}>([^<]*)</${t}:${n}>`),i=e.match(r);return i?.[1]?se(i[1]):void 0}function oe(e,t,n){let r=RegExp(`<${t}:${n}>[\\s\\S]*?<rdf:li[^>]*(?<!/)>([\\s\\S]*?)</rdf:li>[\\s\\S]*?</${t}:${n}>`),i=e.match(r);return i?.[1]?se(i[1]):void 0}function se(e){return e.replace(/&#x([0-9a-fA-F]+);/g,(e,t)=>{try{return String.fromCodePoint(parseInt(t,16))}catch{return e}}).replace(/&#(\d+);/g,(e,t)=>{try{return String.fromCodePoint(parseInt(t,10))}catch{return e}}).replace(/&lt;/g,`<`).replace(/&gt;/g,`>`).replace(/&quot;/g,`"`).replace(/&apos;/g,`'`).replace(/&amp;/g,`&`)}let ce=34665;function le(e){let t=e.filter(e=>e.source.type===`exifImageDescription`||e.source.type===`exifMake`),n=e.filter(e=>e.source.type===`exifUserComment`);if(t.length===0&&n.length===0)return new Uint8Array;let r=[],i=[];for(let e of t)if(e.source.type===`exifImageDescription`){let t=pe(e.data,e.source.prefix);r.push({tag:270,type:2,data:t})}else if(e.source.type===`exifMake`){let t=pe(e.data,e.source.prefix);r.push({tag:271,type:2,data:t})}for(let e of n)if(e.source.type===`exifUserComment`){let t=fe(e.data);i.push({tag:37510,type:7,data:t})}let a=i.length>0;a&&r.push({tag:ce,type:4,data:new Uint8Array(4)}),r.sort((e,t)=>e.tag-t.tag),i.sort((e,t)=>e.tag-t.tag);let o=r.length,s=2+12*o+4,c=i.length,l=a?2+12*c+4:0,u=8+s,d=u+l;if(a){let e=r.find(e=>e.tag===ce);e&&T(e.data,0,u,!0)}let f=new Map;for(let e of[...r,...i])e.data.length>4&&(f.set(e,d),d+=e.data.length,e.data.length%2!=0&&(d+=1));let p=new Uint8Array(d);p[0]=73,p[1]=73,w(p,2,42,!0),T(p,4,8,!0);let m=8;w(p,m,o,!0),m+=2;for(let e of r)ue(p,m,e,f.get(e),!0),m+=12;if(T(p,m,0,!0),m+=4,a){w(p,m,c,!0),m+=2;for(let e of i)ue(p,m,e,f.get(e),!0),m+=12;T(p,m,0,!0)}for(let[e,t]of f)p.set(e.data,t);return p}function ue(e,t,n,r,i){w(e,t,n.tag,i),w(e,t+2,n.type,i),T(e,t+4,n.data.length,i),n.data.length<=4?e.set(n.data,t+8):T(e,t+8,r??0,i)}let de=new Uint8Array([85,78,73,67,79,68,69,0]);function fe(e){let t=new Uint8Array(8+e.length*2),n=new DataView(t.buffer);t.set(de);for(let t=0;t<e.length;t++)n.setUint16(8+t*2,e.charCodeAt(t),!0);return t}function pe(e,t){let n=t?`${t}: ${e}`:e,r=new TextEncoder().encode(n),i=new Uint8Array(r.length+1);return i.set(r,0),i[r.length]=0,i}let D=new Uint8Array([69,120,105,102,0,0]);function O(e,t){if(!p(e))return u.error({type:`invalidSignature`});let n=t.filter(e=>e.source.type===`jpegCom`),r=t.filter(e=>e.source.type===`xmpPacket`),i=t.filter(e=>e.source.type===`exifUserComment`||e.source.type===`exifImageDescription`||e.source.type===`exifMake`),a=me(e);if(!a.ok)return a;let{beforeSos:o,scanData:s}=a.value,c=i.length>0?he(i):null,l=r[0],d=l?ge(l.data):null,f=n.map(e=>_e(e.data)).filter(e=>e!==null),m=2;c&&(m+=c.length),d&&(m+=d.length);for(let e of o)m+=e.length;for(let e of f)m+=e.length;m+=s.length;let h=new Uint8Array(m),g=0;h[g++]=255,h[g++]=216,c&&(h.set(c,g),g+=c.length),d&&(h.set(d,g),g+=d.length);for(let e of o)h.set(e,g),g+=e.length;for(let e of f)h.set(e,g),g+=e.length;return h.set(s,g),u.ok(h)}function me(e){let t=[],n=2;for(;n<e.length-1;){if(e[n]!==255)return u.error({type:`corruptedStructure`,message:`Expected marker at offset ${n}`});for(;e[n]===255&&n<e.length-1;)n++;let r=e[n];if(n++,r===218){let r=e.slice(n-2);return u.ok({beforeSos:t,scanData:r})}if(r===217)return u.ok({beforeSos:t,scanData:new Uint8Array([255,217])});if(n+2>e.length)return u.error({type:`corruptedStructure`,message:`Unexpected end of file`});let i=g(e,n),a=n-2,o=n+i;if(o>e.length)return u.error({type:`corruptedStructure`,message:`Segment extends beyond file`});let s=r===225&&n+2+6<=e.length&&e[n+2]===69&&e[n+3]===120&&e[n+4]===105&&e[n+5]===102&&e[n+6]===0&&e[n+7]===0,c=r===225&&!s&&ne(e,n+2);!s&&!c&&r!==254&&t.push(e.slice(a,o)),n=o}return u.error({type:`corruptedStructure`,message:`No SOS marker found`})}function he(e){let t=le(e);if(t.length===0)return new Uint8Array;let n=2+D.length+t.length,r=new Uint8Array(2+n);return r[0]=255,r[1]=225,C(r,2,n),r.set(D,4),r.set(t,4+D.length),r}function ge(e){let t=new TextEncoder().encode(e),n=2+E.length+t.length;if(n>65535)return null;let r=new Uint8Array(2+n);return r[0]=255,r[1]=225,C(r,2,n),r.set(E,4),r.set(t,4+E.length),r}function _e(e){let t=new TextEncoder().encode(e),n=2+t.length;if(n>65535)return null;let r=new Uint8Array(2+n);return r[0]=255,r[1]=254,C(r,2,n),r.set(t,4),r}let k=new Uint8Array([137,80,78,71,13,10,26,10]);function A(e,t){if(!f(e))return u.error({type:`invalidSignature`});if(ve(e)===-1)return u.error({type:`noIhdrChunk`});let n=ye(e),r=t.map(e=>e.type===`tEXt`?be(e):xe(e)),i=k.length+n.ihdr.length+r.reduce((e,t)=>e+t.length,0)+n.others.reduce((e,t)=>e+t.length,0),a=new Uint8Array(i),o=0;a.set(k,o),o+=k.length,a.set(n.ihdr,o),o+=n.ihdr.length;for(let e of r)a.set(e,o),o+=e.length;for(let e of n.others)a.set(e,o),o+=e.length;return u.ok(a)}function ve(e){let t=k.length;if(t+8>e.length)return-1;let n=y(e,t);return S(e,t+4)===`IHDR`?t+4+4+n+4:-1}function ye(e){let t=[],n=k.length,r=new Uint8Array;for(;n<e.length;){let i=n;if(n+4>e.length)break;let a=y(e,n);if(n+=4,n+4>e.length)break;let o=S(e,n);if(n+=4,n+a+4>e.length)break;n+=a,n+=4;let s=n,c=e.slice(i,s);if(o===`IHDR`?r=c:o!==`tEXt`&&o!==`iTXt`&&t.push(c),o===`IEND`)break}return{ihdr:r,others:t}}function be(e){let t=Ce(e.keyword),n=j(e.text),r=new Uint8Array(t.length+1+n.length);return r.set(t,0),r[t.length]=0,r.set(n,t.length+1),Se(`tEXt`,r)}function xe(e){let t=j(e.keyword),n=j(e.languageTag),r=j(e.translatedKeyword),i=j(e.text),a=t.length+1+1+1+n.length+1+r.length+1+i.length,o=new Uint8Array(a),s=0;return o.set(t,s),s+=t.length,o[s++]=0,o[s++]=e.compressionFlag,o[s++]=e.compressionMethod,o.set(n,s),s+=n.length,o[s++]=0,o.set(r,s),s+=r.length,o[s++]=0,o.set(i,s),Se(`iTXt`,o)}function Se(e,t){let n=new Uint8Array(8+t.length+4);ee(n,0,t.length),n.set(new TextEncoder().encode(e),4),n.set(t,8);let r=Ee(n.slice(4,8+t.length));return ee(n,8+t.length,r),n}function Ce(e){let t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n)&255;return t}function j(e){return new TextEncoder().encode(e)}let we=Te();function Te(){let e=new Uint32Array(256);for(let t=0;t<256;t++){let n=t;for(let e=0;e<8;e++)n&1?n=3988292384^n>>>1:n>>>=1;e[t]=n>>>0}return e}function Ee(e){let t=4294967295;for(let n=0;n<e.length;n++)t=(we[(t^(e[n]??0))&255]??0)^t>>>8;return(t^4294967295)>>>0}let De=new Uint8Array([82,73,70,70]),Oe=new Uint8Array([87,69,66,80]);function ke(e,t){if(!m(e))return u.error({type:`invalidSignature`});let n=t.filter(e=>e.source.type===`xmpPacket`),r=t.filter(e=>e.source.type!==`xmpPacket`),i=je(e);if(!i.ok)return i;let{chunks:a}=i.value,o=Me(r),s=n[0],c=s?Ne(s.data):null,l=[];o&&l.push(o),c&&l.push(c);let d=4;for(let e of a)d+=e.length;for(let e of l)d+=e.length;let f=new Uint8Array(8+d),p=0;f.set(De,p),p+=4,te(f,p,d),p+=4,f.set(Oe,p),p+=4;let h=!1;for(let e of a)if(f.set(e,p),p+=e.length,!h&&l.length>0&&Ae(e)){for(let e of l)f.set(e,p),p+=e.length;h=!0}if(!h)for(let e of l)f.set(e,p),p+=e.length;return u.ok(f)}function Ae(e){if(e.length<4)return!1;let t=S(e,0);return t===`VP8 `||t===`VP8L`||t===`VP8X`}function je(e){let t=[],n=``,r=12;for(;r<e.length-8;){let i=S(e,r),a=b(e,r+4);if(n||=i,r+8+a>e.length)return u.error({type:`invalidRiffStructure`,message:`Chunk extends beyond file at offset ${r}`});if(i!==`EXIF`&&i!==`XMP `){let n=a+a%2,i=e.slice(r,r+8+n);t.push(i)}let o=a+a%2;r+=8+o}return u.ok({chunks:t,firstChunkType:n})}function Me(e){if(e.length===0)return null;let t=le(e);if(t.length===0)return null;let n=t.length,r=n+n%2,i=new Uint8Array(8+r);return i.set(new TextEncoder().encode(`EXIF`)),te(i,4,n),i.set(t,8),i}function Ne(e){let t=new TextEncoder().encode(e),n=t.length,r=n+n%2,i=new Uint8Array(8+r);return i.set(new TextEncoder().encode(`XMP `)),te(i,4,n),i.set(t,8),i}function M(e){return e.replace(/\r\n/g,`
1
+ var sdMetadata=(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:`Module`});let t=(e,t)=>t===void 0?[]:[{type:`tEXt`,keyword:e,text:t}],n=(e,t)=>t===void 0?[]:[{type:`iTXt`,keyword:e,compressionFlag:0,compressionMethod:0,languageTag:``,translatedKeyword:``,text:t}],r=(e,t)=>e.find(e=>e.source.type===t),i=e=>{if(e!==void 0)return typeof e==`string`?e:JSON.stringify(e)};function a(e){return e.replace(/[\u0100-\uffff]/g,e=>`\\u${e.charCodeAt(0).toString(16).padStart(4,`0`)}`)}function o(e){return e.replace(/\\u([0-9a-fA-F]{4})/g,(e,t)=>String.fromCharCode(Number.parseInt(t,16)))}function s(e){return/[^\x00-\xFF]/.test(e)}function c(e,r,i){if(r===void 0)return[];switch(i){case`dynamic`:return(s(r)?`iTXt`:`tEXt`)==`iTXt`?n(e,r):t(e,r);case`text-unicode-escape`:return t(e,a(r));case`text-utf8-raw`:return t(e,r)}}function l(e,t){return e.flatMap(([e,n])=>c(e,n,t[e]??t.default))}let u={ok:e=>({ok:!0,value:e}),error:e=>({ok:!1,error:e})};function d(e){return e instanceof ArrayBuffer?new Uint8Array(e):e}function f(e){return e.length<8?!1:e[0]===137&&e[1]===80&&e[2]===78&&e[3]===71&&e[4]===13&&e[5]===10&&e[6]===26&&e[7]===10}function p(e){return e.length<2?!1:e[0]===255&&e[1]===216}function m(e){return e.length<12?!1:e[0]===82&&e[1]===73&&e[2]===70&&e[3]===70&&e[8]===87&&e[9]===69&&e[10]===66&&e[11]===80}function h(e){return f(e)?`png`:p(e)?`jpeg`:m(e)?`webp`:null}function g(e,t){return new DataView(e.buffer,e.byteOffset,e.byteLength).getUint16(t)}function _(e,t,n){return new DataView(e.buffer,e.byteOffset,e.byteLength).getUint16(t,n)}function v(e,t){return(e[t]??0)|(e[t+1]??0)<<8|(e[t+2]??0)<<16}function y(e,t){return new DataView(e.buffer,e.byteOffset,e.byteLength).getUint32(t)}function b(e,t){return new DataView(e.buffer,e.byteOffset,e.byteLength).getUint32(t,!0)}function x(e,t,n){return new DataView(e.buffer,e.byteOffset,e.byteLength).getUint32(t,n)}function S(e,t){return String.fromCharCode(e[t]??0,e[t+1]??0,e[t+2]??0,e[t+3]??0)}function C(e,t,n){new DataView(e.buffer,e.byteOffset,e.byteLength).setUint16(t,n)}function w(e,t,n,r){new DataView(e.buffer,e.byteOffset,e.byteLength).setUint16(t,n,r)}function ee(e,t,n){new DataView(e.buffer,e.byteOffset,e.byteLength).setUint32(t,n)}function te(e,t,n){new DataView(e.buffer,e.byteOffset,e.byteLength).setUint32(t,n,!0)}function T(e,t,n,r){new DataView(e.buffer,e.byteOffset,e.byteLength).setUint32(t,n,r)}let E=new TextEncoder().encode(`http://ns.adobe.com/xap/1.0/\0`);function ne(e,t){if(t+E.length>e.length)return!1;for(let n=0;n<E.length;n++)if(e[t+n]!==E[n])return!1;return!0}function re(e){return e===`XML:com.adobe.xmp`}function ie(e){if(e.length>65535)return null;let t=[[`CreatorTool`,ae(e,`xmp`,`CreatorTool`)],[`UserComment`,oe(e,`exif`,`UserComment`)],[`parameters`,oe(e,`dc`,`description`)]].filter(e=>e[1]!==void 0);return t.length>0?Object.fromEntries(t):null}function ae(e,t,n){let r=RegExp(`<${t}:${n}>([^<]*)</${t}:${n}>`),i=e.match(r);return i?.[1]?se(i[1]):void 0}function oe(e,t,n){let r=`<${t}:${n}>`,i=`</${t}:${n}>`,a=e.indexOf(r);if(a===-1)return;let o=e.indexOf(i,a);if(o===-1)return;let s=e.slice(a+r.length,o),c=0;for(;c<s.length;){let e=s.indexOf(`<rdf:li`,c);if(e===-1)return;let t=s.indexOf(`>`,e);if(t===-1)return;if(s[t-1]===`/`){c=t+1;continue}let n=t+1,r=s.indexOf(`</rdf:li>`,n);if(r===-1)return;let i=s.slice(n,r);return i?se(i):void 0}}function se(e){return e.replace(/&#x([0-9a-fA-F]+);/g,(e,t)=>{try{return String.fromCodePoint(parseInt(t,16))}catch{return e}}).replace(/&#(\d+);/g,(e,t)=>{try{return String.fromCodePoint(parseInt(t,10))}catch{return e}}).replace(/&lt;/g,`<`).replace(/&gt;/g,`>`).replace(/&quot;/g,`"`).replace(/&apos;/g,`'`).replace(/&amp;/g,`&`)}let ce=34665;function le(e){let t=e.filter(e=>e.source.type===`exifImageDescription`||e.source.type===`exifMake`),n=e.filter(e=>e.source.type===`exifUserComment`);if(t.length===0&&n.length===0)return new Uint8Array;let r=[],i=[];for(let e of t)if(e.source.type===`exifImageDescription`){let t=pe(e.data,e.source.prefix);r.push({tag:270,type:2,data:t})}else if(e.source.type===`exifMake`){let t=pe(e.data,e.source.prefix);r.push({tag:271,type:2,data:t})}for(let e of n)if(e.source.type===`exifUserComment`){let t=fe(e.data);i.push({tag:37510,type:7,data:t})}let a=i.length>0;a&&r.push({tag:ce,type:4,data:new Uint8Array(4)}),r.sort((e,t)=>e.tag-t.tag),i.sort((e,t)=>e.tag-t.tag);let o=r.length,s=2+12*o+4,c=i.length,l=a?2+12*c+4:0,u=8+s,d=u+l;if(a){let e=r.find(e=>e.tag===ce);e&&T(e.data,0,u,!0)}let f=new Map;for(let e of[...r,...i])e.data.length>4&&(f.set(e,d),d+=e.data.length,e.data.length%2!=0&&(d+=1));let p=new Uint8Array(d);p[0]=73,p[1]=73,w(p,2,42,!0),T(p,4,8,!0);let m=8;w(p,m,o,!0),m+=2;for(let e of r)ue(p,m,e,f.get(e),!0),m+=12;if(T(p,m,0,!0),m+=4,a){w(p,m,c,!0),m+=2;for(let e of i)ue(p,m,e,f.get(e),!0),m+=12;T(p,m,0,!0)}for(let[e,t]of f)p.set(e.data,t);return p}function ue(e,t,n,r,i){w(e,t,n.tag,i),w(e,t+2,n.type,i),T(e,t+4,n.data.length,i),n.data.length<=4?e.set(n.data,t+8):T(e,t+8,r??0,i)}let de=new Uint8Array([85,78,73,67,79,68,69,0]);function fe(e){let t=new Uint8Array(8+e.length*2),n=new DataView(t.buffer);t.set(de);for(let t=0;t<e.length;t++)n.setUint16(8+t*2,e.charCodeAt(t),!0);return t}function pe(e,t){let n=t?`${t}: ${e}`:e,r=new TextEncoder().encode(n),i=new Uint8Array(r.length+1);return i.set(r,0),i[r.length]=0,i}let D=new Uint8Array([69,120,105,102,0,0]);function O(e,t){if(!p(e))return u.error({type:`invalidSignature`});let n=t.filter(e=>e.source.type===`jpegCom`),r=t.filter(e=>e.source.type===`xmpPacket`),i=t.filter(e=>e.source.type===`exifUserComment`||e.source.type===`exifImageDescription`||e.source.type===`exifMake`),a=me(e);if(!a.ok)return a;let{beforeSos:o,scanData:s}=a.value,c=i.length>0?he(i):null,l=r[0],d=l?ge(l.data):null,f=n.map(e=>_e(e.data)).filter(e=>e!==null),m=2;c&&(m+=c.length),d&&(m+=d.length);for(let e of o)m+=e.length;for(let e of f)m+=e.length;m+=s.length;let h=new Uint8Array(m),g=0;h[g++]=255,h[g++]=216,c&&(h.set(c,g),g+=c.length),d&&(h.set(d,g),g+=d.length);for(let e of o)h.set(e,g),g+=e.length;for(let e of f)h.set(e,g),g+=e.length;return h.set(s,g),u.ok(h)}function me(e){let t=[],n=2;for(;n<e.length-1;){if(e[n]!==255)return u.error({type:`corruptedStructure`,message:`Expected marker at offset ${n}`});for(;e[n]===255&&n<e.length-1;)n++;let r=e[n];if(n++,r===218){let r=e.slice(n-2);return u.ok({beforeSos:t,scanData:r})}if(r===217)return u.ok({beforeSos:t,scanData:new Uint8Array([255,217])});if(n+2>e.length)return u.error({type:`corruptedStructure`,message:`Unexpected end of file`});let i=g(e,n),a=n-2,o=n+i;if(o>e.length)return u.error({type:`corruptedStructure`,message:`Segment extends beyond file`});let s=r===225&&n+2+6<=e.length&&e[n+2]===69&&e[n+3]===120&&e[n+4]===105&&e[n+5]===102&&e[n+6]===0&&e[n+7]===0,c=r===225&&!s&&ne(e,n+2);!s&&!c&&r!==254&&t.push(e.slice(a,o)),n=o}return u.error({type:`corruptedStructure`,message:`No SOS marker found`})}function he(e){let t=le(e);if(t.length===0)return new Uint8Array;let n=2+D.length+t.length,r=new Uint8Array(2+n);return r[0]=255,r[1]=225,C(r,2,n),r.set(D,4),r.set(t,4+D.length),r}function ge(e){let t=new TextEncoder().encode(e),n=2+E.length+t.length;if(n>65535)return null;let r=new Uint8Array(2+n);return r[0]=255,r[1]=225,C(r,2,n),r.set(E,4),r.set(t,4+E.length),r}function _e(e){let t=new TextEncoder().encode(e),n=2+t.length;if(n>65535)return null;let r=new Uint8Array(2+n);return r[0]=255,r[1]=254,C(r,2,n),r.set(t,4),r}let k=new Uint8Array([137,80,78,71,13,10,26,10]);function A(e,t){if(!f(e))return u.error({type:`invalidSignature`});if(ve(e)===-1)return u.error({type:`noIhdrChunk`});let n=ye(e),r=t.map(e=>e.type===`tEXt`?be(e):xe(e)),i=k.length+n.ihdr.length+r.reduce((e,t)=>e+t.length,0)+n.others.reduce((e,t)=>e+t.length,0),a=new Uint8Array(i),o=0;a.set(k,o),o+=k.length,a.set(n.ihdr,o),o+=n.ihdr.length;for(let e of r)a.set(e,o),o+=e.length;for(let e of n.others)a.set(e,o),o+=e.length;return u.ok(a)}function ve(e){let t=k.length;if(t+8>e.length)return-1;let n=y(e,t);return S(e,t+4)===`IHDR`?t+4+4+n+4:-1}function ye(e){let t=[],n=k.length,r=new Uint8Array;for(;n<e.length;){let i=n;if(n+4>e.length)break;let a=y(e,n);if(n+=4,n+4>e.length)break;let o=S(e,n);if(n+=4,n+a+4>e.length)break;n+=a,n+=4;let s=n,c=e.slice(i,s);if(o===`IHDR`?r=c:o!==`tEXt`&&o!==`iTXt`&&t.push(c),o===`IEND`)break}return{ihdr:r,others:t}}function be(e){let t=Ce(e.keyword),n=j(e.text),r=new Uint8Array(t.length+1+n.length);return r.set(t,0),r[t.length]=0,r.set(n,t.length+1),Se(`tEXt`,r)}function xe(e){let t=j(e.keyword),n=j(e.languageTag),r=j(e.translatedKeyword),i=j(e.text),a=t.length+1+1+1+n.length+1+r.length+1+i.length,o=new Uint8Array(a),s=0;return o.set(t,s),s+=t.length,o[s++]=0,o[s++]=e.compressionFlag,o[s++]=e.compressionMethod,o.set(n,s),s+=n.length,o[s++]=0,o.set(r,s),s+=r.length,o[s++]=0,o.set(i,s),Se(`iTXt`,o)}function Se(e,t){let n=new Uint8Array(8+t.length+4);ee(n,0,t.length),n.set(new TextEncoder().encode(e),4),n.set(t,8);let r=Ee(n.slice(4,8+t.length));return ee(n,8+t.length,r),n}function Ce(e){let t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n)&255;return t}function j(e){return new TextEncoder().encode(e)}let we=Te();function Te(){let e=new Uint32Array(256);for(let t=0;t<256;t++){let n=t;for(let e=0;e<8;e++)n&1?n=3988292384^n>>>1:n>>>=1;e[t]=n>>>0}return e}function Ee(e){let t=4294967295;for(let n=0;n<e.length;n++)t=(we[(t^(e[n]??0))&255]??0)^t>>>8;return(t^4294967295)>>>0}let De=new Uint8Array([82,73,70,70]),Oe=new Uint8Array([87,69,66,80]);function ke(e,t){if(!m(e))return u.error({type:`invalidSignature`});let n=t.filter(e=>e.source.type===`xmpPacket`),r=t.filter(e=>e.source.type!==`xmpPacket`),i=je(e);if(!i.ok)return i;let{chunks:a}=i.value,o=Me(r),s=n[0],c=s?Ne(s.data):null,l=[];o&&l.push(o),c&&l.push(c);let d=4;for(let e of a)d+=e.length;for(let e of l)d+=e.length;let f=new Uint8Array(8+d),p=0;f.set(De,p),p+=4,te(f,p,d),p+=4,f.set(Oe,p),p+=4;let h=!1;for(let e of a)if(f.set(e,p),p+=e.length,!h&&l.length>0&&Ae(e)){for(let e of l)f.set(e,p),p+=e.length;h=!0}if(!h)for(let e of l)f.set(e,p),p+=e.length;return u.ok(f)}function Ae(e){if(e.length<4)return!1;let t=S(e,0);return t===`VP8 `||t===`VP8L`||t===`VP8X`}function je(e){let t=[],n=``,r=12;for(;r<e.length-8;){let i=S(e,r),a=b(e,r+4);if(n||=i,r+8+a>e.length)return u.error({type:`invalidRiffStructure`,message:`Chunk extends beyond file at offset ${r}`});if(i!==`EXIF`&&i!==`XMP `){let n=a+a%2,i=e.slice(r,r+8+n);t.push(i)}let o=a+a%2;r+=8+o}return u.ok({chunks:t,firstChunkType:n})}function Me(e){if(e.length===0)return null;let t=le(e);if(t.length===0)return null;let n=t.length,r=n+n%2,i=new Uint8Array(8+r);return i.set(new TextEncoder().encode(`EXIF`)),te(i,4,n),i.set(t,8),i}function Ne(e){let t=new TextEncoder().encode(e),n=t.length,r=n+n%2,i=new Uint8Array(8+r);return i.set(new TextEncoder().encode(`XMP `)),te(i,4,n),i.set(t,8),i}function M(e){return e.replace(/\r\n/g,`
2
2
  `).replace(/\r/g,`
3
3
  `)}function Pe(e){return e.flatMap((e,t)=>{let n=e.center?` [${e.center.x}, ${e.center.y}]`:``;return[`# Character ${t+1}${n}:`,M(e.prompt)]})}function Fe(e,t){let n=e.hires??e.upscale,r={Steps:e.sampling?.steps,Sampler:e.sampling?.sampler,"Schedule type":e.sampling?.scheduler,"CFG scale":e.sampling?.cfg,Seed:e.sampling?.seed,Size:e.width>0&&e.height>0?`${e.width}x${e.height}`:void 0,"Model hash":e.model?.hash,Model:e.model?.name,"Clip skip":e.sampling?.clipSkip,"Denoising strength":n?.denoise,"Hires upscale":n?.scale,"Hires steps":n?.steps,"Hires upscaler":n?.upscaler};return Object.entries({...r,...t}).filter(([,e])=>e!==void 0).map(([e,t])=>`${e}: ${t}`).join(`, `)}function N(e){return[M(e.prompt),e.characterPrompts?.length?Pe(e.characterPrompts).join(`
4
4
  `):void 0,e.negativePrompt?`Negative prompt: ${M(e.negativePrompt)}`:void 0,Fe(e,e.extras)||void 0].filter(e=>e!==void 0).join(`
@@ -6,6 +6,6 @@ var sdMetadata=(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:`M
6
6
 
7
7
  `);case`jpeg`:case`webp`:return e.segments.map(e=>e.data).join(`
8
8
 
9
- `)}}function Le(e){if(`status`in e)switch(e.status){case`success`:return N(e.metadata);case`unrecognized`:return Ie(e.raw);case`empty`:case`invalid`:return``}return N(e)}function Re(e,t){let n=d(e),r=h(n);if(!r)return u.error({type:`unsupportedFormat`});let i=ze(r,n,N(t));return i.ok?u.ok(i.value):u.error({type:`writeFailed`,message:i.error.type})}function ze(e,t,n){switch(e){case`png`:return A(t,c(`parameters`,n,`dynamic`));case`jpeg`:return O(t,[{source:{type:`exifUserComment`},data:n}]);case`webp`:return ke(t,[{source:{type:`exifUserComment`},data:n}])}}function P(e){let t=Object.fromEntries(Object.entries(e).filter(([,e])=>e!==void 0));return Object.keys(t).length===0?void 0:t}function F(e,t){let n=e.parameters??e.UserComment;if(!n)return u.error({type:`unsupportedFormat`});let{prompt:r,negativePrompt:i,settings:a}=Be(n),o=Ve(a),[s,c]=He(o.get(`Size`)??`0x0`),l=o.get(`Model`),d=o.get(`Model hash`),f=o.get(`Sampler`),p=o.get(`Schedule type`),m=I(o.get(`Steps`)),h=I(o.get(`CFG scale`)??o.get(`CFG Scale`)),g=I(o.get(`Seed`)),_=I(o.get(`Clip skip`)),v=I(o.get(`Hires upscale`)),y=o.get(`Hires upscaler`),b=I(o.get(`Hires steps`)),x=I(o.get(`Denoising strength`)),[S]=He(o.get(`Hires size`)??``),C=v??(S>0?S/s:void 0);return u.ok({software:t,prompt:r,negativePrompt:i,width:s,height:c,model:P({name:l,hash:d}),sampling:P({sampler:f,scheduler:p,steps:m,cfg:h,seed:g,clipSkip:_}),hires:P({scale:C,upscaler:y,steps:b,denoise:x})})}function Be(e){let t=e.indexOf(`Negative prompt:`),n=e.indexOf(`Steps:`);if(t===-1&&n===-1)return{prompt:e.trim(),negativePrompt:``,settings:``};if(t===-1){let t=e.lastIndexOf(`
9
+ `)}}function Le(e){if(`status`in e)switch(e.status){case`success`:return N(e.metadata);case`c2pa`:return e.c2pa.claimGenerator??``;case`unrecognized`:return Ie(e.raw);case`empty`:case`invalid`:return``}return N(e)}function Re(e,t){let n=d(e),r=h(n);if(!r)return u.error({type:`unsupportedFormat`});let i=ze(r,n,N(t));return i.ok?u.ok(i.value):u.error({type:`writeFailed`,message:i.error.type})}function ze(e,t,n){switch(e){case`png`:return A(t,c(`parameters`,n,`dynamic`));case`jpeg`:return O(t,[{source:{type:`exifUserComment`},data:n}]);case`webp`:return ke(t,[{source:{type:`exifUserComment`},data:n}])}}function P(e){let t=Object.fromEntries(Object.entries(e).filter(([,e])=>e!==void 0));return Object.keys(t).length===0?void 0:t}function F(e,t){let n=e.parameters??e.UserComment;if(!n)return u.error({type:`unsupportedFormat`});let{prompt:r,negativePrompt:i,settings:a}=Be(n),o=Ve(a),[s,c]=He(o.get(`Size`)??`0x0`),l=o.get(`Model`),d=o.get(`Model hash`),f=o.get(`Sampler`),p=o.get(`Schedule type`),m=I(o.get(`Steps`)),h=I(o.get(`CFG scale`)??o.get(`CFG Scale`)),g=I(o.get(`Seed`)),_=I(o.get(`Clip skip`)),v=I(o.get(`Hires upscale`)),y=o.get(`Hires upscaler`),b=I(o.get(`Hires steps`)),x=I(o.get(`Denoising strength`)),[S]=He(o.get(`Hires size`)??``),C=v??(S>0?S/s:void 0);return u.ok({software:t,prompt:r,negativePrompt:i,width:s,height:c,model:P({name:l,hash:d}),sampling:P({sampler:f,scheduler:p,steps:m,cfg:h,seed:g,clipSkip:_}),hires:P({scale:C,upscaler:y,steps:b,denoise:x})})}function Be(e){let t=e.indexOf(`Negative prompt:`),n=e.indexOf(`Steps:`);if(t===-1&&n===-1)return{prompt:e.trim(),negativePrompt:``,settings:``};if(t===-1){let t=e.lastIndexOf(`
10
10
  `,n);return{prompt:e.slice(0,t).trim(),negativePrompt:``,settings:e.slice(t).trim()}}if(n===-1)return{prompt:e.slice(0,t).trim(),negativePrompt:e.slice(t+16).trim(),settings:``};let r=e.lastIndexOf(`
11
- `,n);return{prompt:e.slice(0,t).trim(),negativePrompt:e.slice(t+16,r).trim(),settings:e.slice(r).trim()}}function Ve(e){let t=new Map;if(!e||e.length>1e4)return t;for(let n of e.matchAll(/([A-Za-z][A-Za-z0-9 ]*?):\s*([^,]+?)(?=,\s*[A-Za-z][A-Za-z0-9 ]*?:|$)/g)){let e=(n[1]??``).trim(),r=(n[2]??``).trim();t.set(e,r)}return t}function He(e){let t=e.match(/(\d+)x(\d+)/);return t?[Number.parseInt(t[1]??`0`,10),Number.parseInt(t[2]??`0`,10)]:[0,0]}function I(e){if(e===void 0)return;let t=Number.parseFloat(e);return Number.isNaN(t)?void 0:t}function L(e){try{return Ue(JSON.parse(e))}catch{return{ok:!1,error:{type:`parseError`,message:`Invalid JSON`}}}}function Ue(e){if(e===null)return{ok:!0,type:`null`,value:null};if(Array.isArray(e))return{ok:!0,type:`array`,value:e};switch(typeof e){case`object`:return{ok:!0,type:`object`,value:e};case`string`:return{ok:!0,type:`string`,value:e};case`number`:return{ok:!0,type:`number`,value:e};case`boolean`:return{ok:!0,type:`boolean`,value:e};default:return{ok:!1,error:{type:`parseError`,message:`Unexpected JSON type`}}}}let We=[`KSampler`,`KSamplerAdvanced`,`SamplerCustomAdvanced`,`SamplerCustom`,`DetailerForEach`],Ge=[`EmptyLatentImage`],Ke=[`SDXL Empty Latent Image (rgthree)`],qe=[`CheckpointLoaderSimple`,`CheckpointLoader`],Je=[`UNETLoader`],Ye=[`CLIPSetLastLayer`],Xe=[`UpscaleModelLoader`],Ze=[`ImageScale`,`ImageScaleBy`],Qe=[`LatentUpscale`,`LatentUpscaleBy`],$e=[`VAEEncode`,`VAEEncodeTiled`];function et(e){let t={};for(let n of Object.values(e)){let e=n.class_type;!t.sampler&&We.includes(e)?t.sampler=n:!t.latentImage&&Ge.includes(e)?t.latentImage=n:!t.latentImageRgthree&&Ke.includes(e)?t.latentImageRgthree=n:!t.checkpoint&&qe.includes(e)?t.checkpoint=n:!t.unetLoader&&Je.includes(e)?t.unetLoader=n:!t.clipSetLastLayer&&Ye.includes(e)?t.clipSetLastLayer=n:!t.hiresModelUpscale&&Xe.includes(e)?t.hiresModelUpscale=n:!t.hiresImageScale&&Ze.includes(e)?t.hiresImageScale=n:!t.latentUpscale&&Qe.includes(e)?t.latentUpscale=n:!t.vaeEncode&&$e.includes(e)&&(t.vaeEncode=n)}return t}function R(e,t){if(z(t))return e[String(t[0])]}function z(e){return Array.isArray(e)&&e.length===2&&(typeof e[0]==`string`||typeof e[0]==`number`)&&typeof e[1]==`number`}function tt(e,t,n=10){if(n<=0)return``;let r=e[t];if(!r)return``;let i=r.inputs.text??r.inputs.prompt??r.inputs.Text??r.inputs.prompt_text;if(typeof i==`string`)return i;if(z(i)){let t=tt(e,String(i[0]),n-1);if(t)return t}return typeof r.inputs.text_0==`string`?r.inputs.text_0:``}function nt(e,t){return R(e,t.inputs.guider)||t}function rt(e,t){if(!t)return{promptText:``,negativeText:``};let n=nt(e,t);return{promptText:B(e,n.inputs.positive,`positive`),negativeText:B(e,n.inputs.negative,`negative`)}}function B(e,t,n,r=10){if(r<=0||!z(t))return``;let i=String(t[0]),a=tt(e,i);if(a)return a;let o=e[i];if(!o)return``;let s=o.inputs[n];return B(e,s,n,r-1)}function it(e,t){if(e){let t=Number(e.inputs.width)||0,n=Number(e.inputs.height)||0;if(t>0&&n>0)return{width:t,height:n}}if(t&&typeof t.inputs.dimensions==`string`){let e=t.inputs.dimensions.match(/^(\d+)\s*x\s*(\d+)/);if(e?.[1]&&e[2])return{width:Number.parseInt(e[1],10),height:Number.parseInt(e[2],10)}}return{width:0,height:0}}function at(e,t){if(!t)return;if(t.class_type===`SamplerCustomAdvanced`)return ot(e,t);if(t.class_type===`SamplerCustom`)return st(e,t);let n=t.inputs.seed;return z(n)&&(n=e[String(n[0])]?.inputs.seed),{seed:n,steps:t.inputs.steps,cfg:t.inputs.cfg,sampler:t.inputs.sampler_name,scheduler:t.inputs.scheduler,denoise:t.inputs.denoise}}function ot(e,t){let n=R(e,t.inputs.noise),r=R(e,t.inputs.guider),i=R(e,t.inputs.sampler),a=R(e,t.inputs.sigmas);return{seed:n?.inputs.noise_seed,steps:a?.inputs.steps,cfg:r?.inputs.cfg,sampler:i?.inputs.sampler_name,scheduler:a?.inputs.scheduler,denoise:a?.inputs.denoise}}function st(e,t){let n=R(e,t.inputs.sampler),r=R(e,t.inputs.sigmas),i=t.inputs.noise_seed;return z(i)&&(i=e[String(i[0])]?.inputs.seed),{seed:i,steps:r?.inputs.steps,cfg:t.inputs.cfg,sampler:n?.inputs.sampler_name,scheduler:r?.inputs.scheduler,denoise:r?.inputs.denoise}}function ct(e,t){let n=e?.inputs?.ckpt_name;if(typeof n==`string`&&n)return{name:n};let r=t?.inputs?.unet_name;if(typeof r==`string`&&r)return{name:r}}function lt(e){if(!e)return;let t=e.inputs.stop_at_clip_layer;if(typeof t==`number`)return-t}function ut(e,t){if(!(t<=0||e<=0))return Math.round(e/t*100)/100}function dt(e,t){let n=t.inputs.latent_image;if(!z(n))return!1;let r=e[String(n[0])];if(!r)return!1;if(Qe.includes(r.class_type))return!0;if(!$e.includes(r.class_type))return!1;let i=r.inputs.pixels;if(!z(i))return!1;let a=e[String(i[0])];return a?Ze.includes(a.class_type):!1}function ft(e){return Object.values(e).find(t=>We.includes(t.class_type)&&dt(e,t))}function pt(e,t){let n=e.extraMetadata;if(typeof n==`string`){let e=L(n);if(e.ok&&e.type===`object`)return e.value}if(t?.extraMetadata){let e=L(t.extraMetadata);if(e.ok&&e.type===`object`)return e.value}}function mt(e){if(!e)return;let t=ht(e),n=gt(e);return P({prompt:e.prompt,negativePrompt:e.negativePrompt,width:e.width,height:e.height,model:e.baseModel?{name:e.baseModel}:void 0,...n,...t})}function ht(e){if(!e.transformations)return{};let t=e.transformations.find(e=>e.type===`upscale`);if(!t?.upscaleWidth)return{};let n=ut(t.upscaleWidth,e.width??0);return n===void 0?{}:{upscale:{scale:n}}}function gt(e){return e.seed===void 0&&e.steps===void 0&&e.cfgScale===void 0&&e.sampler===void 0?{}:{sampling:{seed:e.seed,steps:e.steps,cfg:e.cfgScale,sampler:e.sampler}}}let _t=/Text(Encode|.?Box)|ShowText|PromptStash/,vt=/neg/i;function V(e){return typeof e==`string`?e:``}function H(e){if(typeof e==`number`)return Number.isFinite(e)?e:void 0;if(typeof e==`string`){let t=Number(e);return Number.isFinite(t)?t:void 0}}function yt(e){let t,n,r,i,a,o,s,c,l,u;for(let d of Object.values(e)){if(!d||typeof d!=`object`)continue;let e=d.class_type,f=d.inputs;if(!(!e||!f)){if(_t.test(e)){let r=V(f.text)||V(f.prompt)||V(f.Text)||V(f.prompt_text)||V(f.text_0);r&&(vt.test(e)||t?n||=r:t=r)}e.includes(`Sampler`)&&(r===void 0&&(r=H(f.seed)??H(f.noise_seed)),i===void 0&&(i=H(f.steps)),a===void 0&&(a=H(f.cfg)),o||=V(f.sampler_name),s||=V(f.scheduler)),c||=V(f.ckpt_name)||V(f.unet_name),l===void 0&&(l=H(f.width)),u===void 0&&(u=H(f.height))}}let d={};r!==void 0&&(d.seed=r),i!==void 0&&(d.steps=i),a!==void 0&&(d.cfg=a),o&&(d.sampler=o),s&&(d.scheduler=s);let f={};return t&&(f.prompt=t),n&&(f.negativePrompt=n),l!==void 0&&l>0&&(f.width=l),u!==void 0&&u>0&&(f.height=u),c&&(f.model={name:c}),Object.keys(d).length>0&&(f.sampling=d),f}let bt=[`extra`,`extraMetadata`,`resource-stack`];function U(e){let t=St(e);if(!t)return Ct(e)?u.ok({software:`comfyui`,nodes:{},prompt:``,negativePrompt:``,width:0,height:0}):u.error({type:`unsupportedFormat`});let n=L(t);if(!n.ok||n.type!==`object`)return u.error({type:`parseError`,message:`Invalid JSON in prompt entry`});let r=n.value,i=Dt(yt(r),mt(pt(r,e)),wt(r));return u.ok({software:`comfyui`,nodes:Object.fromEntries(Object.entries(r).filter(([e])=>!bt.includes(e))),...i})}function xt(e){if(!e||typeof e.denoise!=`number`)return e;if(e.denoise>=1){let{denoise:t,...n}=e;return n}return e}function W(e){return e.replace(/\0+$/,``).replace(/([:,[])\s*NaN\b/g,`$1null`)}function St(e){if(e.prompt)return W(e.prompt);let t=[e.UserComment,e.ImageDescription,e.Make,e.Prompt,e.Workflow];for(let e of t)if(e&&e.startsWith(`{`)){let t=W(e),n=L(t);if(!n.ok||n.type!==`object`)continue;if(n.value.prompt&&typeof n.value.prompt==`object`)return JSON.stringify(n.value.prompt);if(Object.values(n.value).some(e=>e&&typeof e==`object`&&`class_type`in e))return t}}function Ct(e){for(let t of[e.workflow,e.Workflow]){if(!t?.startsWith(`{`))continue;let e=L(W(t));if(e.ok&&e.type===`object`&&Array.isArray(e.value.nodes))return!0}return!1}function wt(e){let t=et(e),{promptText:n,negativeText:r}=rt(e,t.sampler),{width:i,height:a}=it(t.latentImage,t.latentImageRgthree),o=ft(e),s=xt(o?at(e,o):void 0),c=Tt(e,t,i),l=t.hiresModelUpscale?.inputs.model_name,u=xt(at(e,t.sampler)),d=lt(t.clipSetLastLayer);return P({prompt:n||void 0,negativePrompt:r||void 0,width:i>0?i:void 0,height:a>0?a:void 0,model:ct(t.checkpoint,t.unetLoader),sampling:P({...u,clipSkip:d}),...Et(l,c,s)})}function Tt(e,t,n){let r=t.latentUpscale?.inputs;if(r?.scale_by!==void 0)return r.scale_by;let i=t.hiresImageScale?.inputs.width;if(i!==void 0){if(z(i)){let t=e[String(i[0])];return typeof t?.inputs.clip_scale==`number`?t.inputs.clip_scale:void 0}if(typeof i==`number`)return ut(i,n)}}function Et(e,t,n){return!e&&t===void 0&&!n?{}:n?{hires:{upscaler:e,scale:t,steps:n.steps,denoise:n.denoise}}:e?{upscale:{upscaler:e,scale:t}}:{}}function G(...e){let t={};for(let n of e)if(n)for(let[e,r]of Object.entries(n))r!==void 0&&(t[e]=r);return Object.keys(t).length>0?t:void 0}function Dt(...e){let t=[...e].reverse(),n=e=>t.find(t=>t?.[e])?.[e];return{prompt:n(`prompt`)??``,negativePrompt:n(`negativePrompt`)??``,width:n(`width`)??0,height:n(`height`)??0,...P({model:G(...e.map(e=>e?.model)),sampling:G(...e.map(e=>e?.sampling)),hires:G(...e.map(e=>e?.hires)),upscale:G(...e.map(e=>e?.upscale))})}}let K=`extraMetadata`,q=`sui_image_params`,Ot=`swarm_version`,kt=`noise_schedule`,At=`v4_prompt`,jt=`RuinedFooocus`;function Mt(e){let t=Pt(e);if(t)return t;let n=It(e);if(n)return n;let r=e.parameters??e.UserComment??e.Comment;return r?Lt(r):null}function Nt(e){return`invokeai_metadata`in e?`invokeai`:`generation_data`in e?`tensorart`:`smproj`in e?`stability-matrix`:K in e?`civitai`:null}function Pt(e){if(e.Software?.startsWith(`NovelAI`))return`novelai`;if(e.CreatorTool?.startsWith(`Draw Things`))return`draw-things`;let t=Nt(e);if(t)return t;if(`fooocus_scheme`in e)return`fooocus`;if(`use_stable_diffusion_model`in e)return`easydiffusion`;if(e.parameters?.includes(q))return`swarmui`;let n=e.UserComment??e.Comment;return n?.startsWith(`{`)?Ft(n):null}function Ft(e){let t=L(e);if(!t.ok||t.type!==`object`)return null;let n=t.value,r=Nt(n);if(r)return r;if(`prompt`in n&&`workflow`in n){let e=n.workflow,t=n.prompt,r=typeof e==`object`||typeof t==`object`,i=typeof e==`string`&&e.startsWith(`{`)||typeof t==`string`&&t.startsWith(`{`);if(r||i)return`comfyui`}if(q in n)return`swarmui`;if(`prompt`in n&&`parameters`in n){let e=String(n.parameters||``);if(e.includes(q)||e.includes(Ot))return`swarmui`}return null}function It(e){if(`prompt`in e&&`workflow`in e||`Prompt`in e&&`Workflow`in e||`workflow`in e||`Workflow`in e)return`comfyui`;let t=e.prompt??e.Prompt;if(t?.startsWith(`{`)){if(t.includes(q))return`swarmui`;if(t.includes(`"${K}"`))return`civitai`;if(t.includes(`class_type`))return`comfyui`}return null}function Lt(e){return e.startsWith(`{`)?Rt(e):zt(e)}function Rt(e){return e.includes(q)?`swarmui`:e.includes(`"software":"${jt}"`)||e.includes(`"software": "${jt}"`)?`ruined-fooocus`:e.includes(`"use_stable_diffusion_model"`)?`easydiffusion`:e.includes(`civitai:`)||e.includes(`"${K}"`)?`civitai`:e.includes(`"${At}"`)||e.includes(`"${kt}"`)||e.includes(`"uncond_scale"`)||e.includes(`"Software":"NovelAI"`)||e.includes(`\\"${kt}\\"`)||e.includes(`\\"${At}\\"`)?`novelai`:e.includes(`"Model"`)&&e.includes(`"resolution"`)?`hf-space`:e.includes(`"prompt"`)&&e.includes(`"base_model"`)?`fooocus`:e.includes(`"prompt"`)||e.includes(`"nodes"`)?`comfyui`:null}function zt(e){if(e.includes(q)||e.includes(Ot))return`swarmui`;let t=e.match(/Version:\s*([^\s,]+)/);if(t){let e=t[1];if(e&&/^v\d/.test(e))return`sd-webui`;if(e===`classic`)return`forge-classic`;if(e===`neo`||e?.startsWith(`neo`))return`forge-neo`;if(e?.startsWith(`f`)&&/^f\d/.test(e))return/^f\d+\.\d+(\.\d+)?-v/.test(e)?`easy-reforge`:/^f\d+\.\d+(\.\d+)?v\d+-v/.test(e)?`reforge`:`forge`;if(e?.startsWith(`Fooocus`))return`fooocus`;if(e===`ComfyUI`)return`comfyui`}return e.includes(`App: SD.Next`)||e.includes(`App:SD.Next`)?`sd-next`:e.includes(`Civitai resources:`)?`civitai`:e.includes(`Steps:`)||e.includes(`Sampler:`)||e.includes(`Negative prompt:`)?`sd-webui`:null}function Bt(e){let t=e.UserComment?.startsWith(`{`)?e.UserComment:e.Comment?.startsWith(`{`)?e.Comment:void 0;if(!t)return u.error({type:`unsupportedFormat`});let n=L(t);return!n.ok||n.type!==`object`?u.error({type:`parseError`,message:`Invalid JSON in Draw Things metadata`}):Ht(n.value)}function Vt(e){if(typeof e!=`string`)return{width:0,height:0};let t=e.match(/^(\d+)x(\d+)$/);return t?{width:Number(t[1]),height:Number(t[2])}:{width:0,height:0}}function Ht(e){let t=t=>{let n=e[t];return typeof n==`string`?n:void 0},n=t=>{let n=e[t];if(typeof n==`number`&&n!==0)return n},r=(t(`c`)??``).trim(),i=(t(`uc`)??``).trim(),{width:a,height:o}=Vt(e.size),s={software:`draw-things`,prompt:r,negativePrompt:i,width:a,height:o,model:P({name:t(`model`)}),sampling:P({sampler:t(`sampler`),steps:n(`steps`),cfg:n(`scale`),seed:n(`seed`),denoise:n(`strength`)})};return u.ok(s)}function Ut(e){if(!e)return;let t=e.replace(/\\/g,`/`).split(`/`);return t[t.length-1]}function Wt(e){if(`use_stable_diffusion_model`in e)return Gt(e);let t=e.UserComment?.startsWith(`{`)?e.UserComment:e.parameters?.startsWith(`{`)?e.parameters:void 0;if(!t)return u.error({type:`unsupportedFormat`});let n=L(t);return!n.ok||n.type!==`object`?u.error({type:`parseError`,message:`Invalid JSON in Easy Diffusion metadata`}):Gt(n.value)}function Gt(e){let t=t=>{let n=e[t];return typeof n==`string`?n:void 0},n=t=>Number(e[t])||void 0,r=(t(`prompt`)??``).trim(),i=(t(`negative_prompt`)??``).trim(),a=t(`use_stable_diffusion_model`),o=P({upscaler:t(`use_upscale`),scale:n(`upscale_amount`)}),s={software:`easydiffusion`,prompt:r,negativePrompt:i,width:n(`width`)??0,height:n(`height`)??0,model:P({name:Ut(a),vae:t(`use_vae_model`)}),sampling:P({sampler:t(`sampler_name`),steps:n(`num_inference_steps`),cfg:n(`guidance_scale`),seed:n(`seed`),clipSkip:n(`clip_skip`),denoise:n(`prompt_strength`)}),...o?{upscale:o}:{}};return u.ok(s)}function Kt(e){if(!e)return{width:0,height:0};let t=e.match(/\(\s*(\d+)\s*,\s*(\d+)\s*\)/);return!t?.[1]||!t[2]?{width:0,height:0}:{width:Number(t[1]),height:Number(t[2])}}function qt(e){let t=e.parameters??e.UserComment;if(!t||!t.startsWith(`{`))return u.error({type:`unsupportedFormat`});let n=L(t);if(!n.ok||n.type!==`object`)return u.error({type:`parseError`,message:`Invalid JSON in Fooocus metadata`});let r=n.value,{width:i,height:a}=Kt(r.resolution),o={software:`fooocus`,prompt:r.prompt?.trim()??``,negativePrompt:r.negative_prompt?.trim()??``,width:i,height:a,model:P({name:r.base_model,hash:r.base_model_hash,vae:r.vae}),sampling:P({sampler:r.sampler,scheduler:r.scheduler,steps:r.steps,cfg:r.guidance_scale,seed:r.seed,clipSkip:r.clip_skip})};return u.ok(o)}function Jt(e){let t=e.parameters??e.UserComment;if(!t)return u.error({type:`unsupportedFormat`});let n=L(t);if(!n.ok||n.type!==`object`)return u.error({type:`parseError`,message:`Invalid JSON in parameters entry`});let r=n.value,{width:i,height:a}=(e=>{let t=e?.match(/(\d+)\s*x\s*(\d+)/);return t?.[1]&&t?.[2]?{width:Number.parseInt(t[1],10),height:Number.parseInt(t[2],10)}:{width:0,height:0}})(r.resolution),o={software:`hf-space`,prompt:r.prompt??``,negativePrompt:r.negative_prompt??``,width:i,height:a,model:P({name:r.Model,hash:r[`Model hash`]}),sampling:P({sampler:r.sampler,steps:r.num_inference_steps,cfg:r.guidance_scale,seed:r.seed}),hires:r.use_upscaler?P({upscaler:r.use_upscaler.upscale_method,denoise:r.use_upscaler.upscaler_strength,scale:r.use_upscaler.upscale_by,steps:r.use_upscaler.upscale_steps}):void 0};return u.ok(o)}function J(e,t){if(!e.UserComment?.startsWith(`{`))return;let n=L(e.UserComment);if(!n.ok||n.type!==`object`)return;let r=n.value[t];if(typeof r==`string`)return r;if(typeof r==`object`&&r)return JSON.stringify(r)}function Yt(e){return e.invokeai_metadata??J(e,`invokeai_metadata`)}function Xt(e){let t=Yt(e);if(!t)return u.error({type:`unsupportedFormat`});let n=L(t);if(!n.ok||n.type!==`object`)return u.error({type:`parseError`,message:`Invalid JSON in invokeai_metadata entry`});let r=n.value,i=r.width??0,a=r.height??0,o=Zt(r);return u.ok({software:`invokeai`,prompt:r.positive_prompt??``,negativePrompt:r.negative_prompt??``,width:i,height:a,model:P({name:r.model?.name,hash:r.model?.hash}),sampling:P({seed:r.seed,steps:r.steps,cfg:r.cfg_scale,sampler:r.scheduler}),...o})}function Zt(e){if(!e.upscale_model?.name&&e.upscale_scale===void 0)return{};let t=P({upscaler:e.upscale_model?.name,scale:e.upscale_scale});return t?{upscale:t}:{}}function Qt(e){let t=e.UserComment??e.Comment;if(!t)return u.error({type:`parseError`,message:`Missing Comment/UserComment entry`});let n=L(t);if(!n.ok||n.type!==`object`)return u.error({type:`parseError`,message:`Invalid JSON in Comment entry`});let r=n.value,i=r.width??0,a=r.height??0,o=r.v4_prompt?.caption?.base_caption??r.prompt??``,s=r.v4_negative_prompt?.caption?.base_caption??r.uc??``,c=r.v4_prompt?.caption?.char_captions,l=c&&c.length>0?c.map(e=>e.char_caption?{prompt:e.char_caption,center:e.centers?.[0]}:null).filter(e=>e!==null):void 0;return u.ok({software:`novelai`,prompt:o,negativePrompt:s,width:i,height:a,sampling:P({steps:r.steps,cfg:r.scale,seed:r.seed,sampler:r.sampler,scheduler:r.noise_schedule}),characterPrompts:l,useCoords:l?r.v4_prompt?.use_coords:void 0,useOrder:l?r.v4_prompt?.use_order:void 0})}function $t(e){let t=e.parameters??e.UserComment;if(!t||!t.startsWith(`{`))return u.error({type:`unsupportedFormat`});let n=L(t);if(!n.ok||n.type!==`object`)return u.error({type:`parseError`,message:`Invalid JSON in Ruined Fooocus metadata`});let r=n.value,i={software:`ruined-fooocus`,prompt:r.Prompt?.trim()??``,negativePrompt:r.Negative?.trim()??``,width:r.width??0,height:r.height??0,model:{name:r.base_model_name,hash:r.base_model_hash},sampling:{sampler:r.sampler_name,scheduler:r.scheduler,steps:r.steps,cfg:r.cfg,seed:r.seed,clipSkip:r.clip_skip}};return u.ok(i)}function en(e){let t=U(e);if(!t.ok||t.value.software!==`comfyui`)return u.error({type:`unsupportedFormat`});let n=e[`parameters-json`]??J(e,`parameters-json`),r=n?L(n):void 0,i=r?.ok&&r.type===`object`?r.value:void 0;return u.ok({...t.value,software:`stability-matrix`,prompt:i?.PositivePrompt??t.value.prompt,negativePrompt:i?.NegativePrompt??t.value.negativePrompt,model:i?.ModelName!==void 0||i?.ModelHash!==void 0?{name:i?.ModelName,hash:i?.ModelHash}:t.value.model})}function tn(e){if(e.parameters)return e.parameters;if(!e.UserComment)return;let t=L(e.UserComment);if(!(!t.ok||t.type!==`object`)&&`sui_image_params`in t.value)return e.UserComment}function nn(e){let t=tn(e);if(!t)return u.error({type:`unsupportedFormat`});let n=L(t);if(!n.ok||n.type!==`object`)return u.error({type:`parseError`,message:`Invalid JSON in parameters entry`});let r=n.value.sui_image_params;if(!r)return u.error({type:`unsupportedFormat`});let i=r.width??0,a=r.height??0,o=e.prompt||e.Make,s=o?L(o):void 0,c=s?.ok&&s.type===`object`?s.value:void 0;return u.ok({software:`swarmui`,prompt:r.prompt??``,negativePrompt:r.negativeprompt??``,width:i,height:a,nodes:c,model:P({name:r.model}),sampling:P({seed:r.seed,steps:r.steps,cfg:r.cfgscale,sampler:r.sampler,scheduler:r.scheduler}),hires:P({scale:r.refinerupscale,upscaler:r.refinerupscalemethod,denoise:r.refinercontrolpercentage})})}function rn(e){let t=e.generation_data??J(e,`generation_data`),n=e.prompt??J(e,`prompt`);if(!t)return u.error({type:`unsupportedFormat`});let r=L(t.replace(/\0+$/,``));if(!r.ok||r.type!==`object`)return u.error({type:`parseError`,message:`Invalid JSON in generation_data entry`});let i=r.value;if(!n)return u.error({type:`unsupportedFormat`});let a=L(n);if(!a.ok||a.type!==`object`)return u.error({type:`parseError`,message:`Invalid JSON in prompt chunk`});let o=a.value,s=wt(o),c=P({name:i.baseModel?.modelFileName,hash:i.baseModel?.hash});return u.ok({software:`tensorart`,nodes:o,prompt:i.prompt??s?.prompt??``,negativePrompt:i.negativePrompt??s?.negativePrompt??``,width:s?.width??0,height:s?.height??0,model:c??s?.model,sampling:s?.sampling,hires:s?.hires,upscale:s?.upscale})}function an(e){let t=Mt(e);switch(t){case`novelai`:return Qt(e);case`sd-webui`:case`forge`:case`forge-classic`:case`forge-neo`:case`reforge`:case`easy-reforge`:case`sd-next`:return F(e,t);case`hf-space`:return Jt(e);case`civitai`:{let t=U(e);return t.ok?u.ok({...t.value,software:`civitai`}):F(e,`civitai`)}case`comfyui`:{let t=U(e);return t.ok?t:F(e,`sd-webui`)}case`invokeai`:return Xt(e);case`swarmui`:return nn(e);case`tensorart`:return rn(e);case`stability-matrix`:return en(e);case`easydiffusion`:return Wt(e);case`fooocus`:{let t=e.fooocus_scheme,n=e.parameters??e.UserComment;return t===`a1111`||n&&!n.startsWith(`{`)?F(e,`fooocus`):qt(e)}case`ruined-fooocus`:return $t(e);case`draw-things`:return Bt(e);default:return u.error({type:`unsupportedFormat`})}}function on(e,t){return t===`png`?sn(e):t===`jpeg`?cn(e):ln(e)}function sn(e){return e.length<24?null:{width:y(e,16),height:y(e,20)}}function cn(e){let t=2;for(;t<e.length-4;){if(e[t]!==255){t++;continue}let n=e[t+1]??0;if(n===255){t++;continue}let r=g(e,t+2);if(n>=192&&n<=207&&n!==196&&n!==200&&n!==204){let n=g(e,t+5);return{width:g(e,t+7),height:n}}if(t+=2+r,n===218)break}return null}function ln(e){let t=12;for(;t<e.length&&!(t+8>e.length);){let n=S(e,t),r=b(e,t+4),i=r+r%2;if(n===`VP8X`){let n=v(e,t+12),r=v(e,t+15);return{width:n+1,height:r+1}}if(n===`VP8 `){let n=t+8;if(!(v(e,n)&1)&&e[n+3]===157&&e[n+4]===1&&e[n+5]===42){let t=_(e,n+6,!0),r=_(e,n+8,!0);return{width:t&16383,height:r&16383}}}if(n===`VP8L`&&e[t+8]===47){let n=b(e,t+9);return{width:(n&16383)+1,height:(n>>14&16383)+1}}t+=8+i}return null}function un(e){if(e.length<8)return[];let t=e[0]===73&&e[1]===73,n=e[0]===77&&e[1]===77;if(!t&&!n||_(e,2,t)!==42)return[];let r=x(e,4,t),i=dn(e,r,t),a=hn(e,r,t),o=a===null?[]:dn(e,a,t);return[...i,...o]}function dn(e,t,n){let r=[];if(t+2>e.length)return r;let i=_(e,t,n),a=t+2;for(let t=0;t<i;t++){if(a+12>e.length)return r;let t=_(e,a,n),i=_(e,a+2,n),o=x(e,a+4,n)*pn(i);if(o>e.length){a+=12;continue}let s;if(s=o<=4?a+8:x(e,a+8,n),s+o>e.length){a+=12;continue}let c=e.slice(s,s+o);if(t===270){let e=mn(c);if(e){let t=fn(e);r.push({source:{type:`exifImageDescription`,prefix:t??void 0},data:t?e.slice(t.length+2):e})}}else if(t===271){let e=mn(c);if(e){let t=fn(e);r.push({source:{type:`exifMake`,prefix:t??void 0},data:t?e.slice(t.length+2):e})}}else if(t===37510){let e=gn(c);e&&r.push({source:{type:`exifUserComment`},data:e})}a+=12}return r}function fn(e){return e.match(/^([A-Za-z]+):\s/)?.[1]??null}function pn(e){switch(e){case 1:return 1;case 2:return 1;case 3:return 2;case 4:return 4;case 5:return 8;case 7:return 1;default:return 1}}function mn(e){try{let t=new TextDecoder(`utf-8`,{fatal:!1}).decode(e);return t.endsWith(`\0`)&&(t=t.slice(0,-1)),t.trim()||null}catch{return null}}function hn(e,t,n){if(t+2>e.length)return null;let r=_(e,t,n),i=t+2;for(let t=0;t<r;t++){if(i+12>e.length)return null;if(_(e,i,n)===34665)return x(e,i+8,n);i+=12}return null}function gn(e){if(e.length<8)return null;if(e[0]===85&&e[1]===78&&e[2]===73&&e[3]===67&&e[4]===79&&e[5]===68&&e[6]===69&&e[7]===0){let t=e.slice(8);return t.length>=2&&t[0]!==0&&t[1]===0?vn(t):_n(t)}if(e[0]===65&&e[1]===83&&e[2]===67&&e[3]===73&&e[4]===73&&e[5]===0&&e[6]===0&&e[7]===0)return yn(e.slice(8));try{let t=new TextDecoder(`utf-8`,{fatal:!0}).decode(e);return t.endsWith(`\0`)&&(t=t.slice(0,-1)),t}catch{return null}}function _n(e){let t=new TextDecoder(`utf-16be`).decode(e),n=t.indexOf(`\0`);return n>=0?t.slice(0,n):t}function vn(e){let t=new TextDecoder(`utf-16le`).decode(e),n=t.indexOf(`\0`);return n>=0?t.slice(0,n):t}function yn(e){let t=e.indexOf(0),n=t>=0?e.subarray(0,t):e;return new TextDecoder(`ascii`).decode(n)}function bn(e,t){return e[t]===69&&e[t+1]===120&&e[t+2]===105&&e[t+3]===102&&e[t+4]===0&&e[t+5]===0}function xn(e){if(!p(e))return u.error({type:`invalidSignature`});let t=[],n=Sn(e);if(n){let r=un(e.slice(n.offset,n.offset+n.length));t.push(...r)}let r=Cn(e);if(r){let n=e.slice(r.offset,r.offset+r.length),i=new TextDecoder(`utf-8`).decode(n);t.push({source:{type:`xmpPacket`},data:i})}let i=wn(e);if(i){let n=Tn(e.slice(i.offset,i.offset+i.length));n!==null&&t.push({source:{type:`jpegCom`},data:n})}return u.ok(t)}function Sn(e){let t=2;for(;t<e.length-4;){if(e[t]!==255){t++;continue}let n=e[t+1];if(n===255){t++;continue}let r=g(e,t+2);if(n===225&&r>=8){let n=t+4;if(n+6<=e.length&&bn(e,n))return{offset:n+6,length:r-8}}if(t+=2+r,n===218||n===217)break}return null}function Cn(e){let t=2;for(;t<e.length-4;){if(e[t]!==255){t++;continue}let n=e[t+1];if(n===255){t++;continue}let r=g(e,t+2);if(n===225&&r>=E.length+2){let n=t+4;if(ne(e,n))return{offset:n+E.length,length:r-2-E.length}}if(t+=2+r,n===218||n===217)break}return null}function wn(e){let t=2;for(;t<e.length-4;){if(e[t]!==255){t++;continue}let n=e[t+1];if(n===255){t++;continue}let r=g(e,t+2);if(n===254&&r>=2)return{offset:t+4,length:r-2};if(t+=2+r,n===218||n===217)break}return null}function Tn(e){try{return new TextDecoder(`utf-8`,{fatal:!0}).decode(e)}catch{return null}}function En(e){if(!f(e))return u.error({type:`invalidSignature`});let t=Dn(e);return t.ok?u.ok(t.value):t}function Dn(e){let t=[],n=8;for(;n<e.length;){if(n+4>e.length)return u.error({type:`corruptedChunk`,message:`Unexpected end of file while reading chunk length`});let r=y(e,n);if(n+=4,n+4>e.length)return u.error({type:`corruptedChunk`,message:`Unexpected end of file while reading chunk type`});let i=S(e,n);if(n+=4,n+r>e.length)return u.error({type:`corruptedChunk`,message:`Unexpected end of file while reading chunk data (${i})`});let a=e.slice(n,n+r);if(n+=r,n+=4,i===`tEXt`){let e=On(a);e&&t.push(e)}else if(i===`iTXt`){let e=An(a);e&&t.push(e)}if(i===`IEND`)break}return u.ok(t)}function On(e){let t=e.indexOf(0);if(t===-1)return null;let n=jn(e.slice(0,t)),r=e.slice(t+1);return{type:`tEXt`,keyword:n,text:kn(r)??jn(r)}}function kn(e){try{return new TextDecoder(`utf-8`,{fatal:!0}).decode(e)}catch{return null}}function An(e){let t=0,n=e.indexOf(0,t);if(n===-1)return null;let r=Y(e.slice(t,n));if(t=n+1,t>=e.length)return null;let i=e[t]??0;if(t+=1,t>=e.length)return null;let a=e[t]??0;t+=1;let o=e.indexOf(0,t);if(o===-1)return null;let s=Y(e.slice(t,o));t=o+1;let c=e.indexOf(0,t);if(c===-1)return null;let l=Y(e.slice(t,c));t=c+1;let u;if(i===1){let n=Mn(e.slice(t));if(!n)return null;u=Y(n)}else u=Y(e.slice(t));return{type:`iTXt`,keyword:r,compressionFlag:i,compressionMethod:a,languageTag:s,translatedKeyword:l,text:u}}function jn(e){return new TextDecoder(`iso-8859-1`).decode(e)}function Y(e){return new TextDecoder(`utf-8`).decode(e)}function Mn(e){return null}function Nn(e){if(!m(e))return u.error({type:`invalidSignature`});let t=[],n=Pn(e);if(n){let r=e.slice(n.offset,n.offset+n.length);t.push(...un(r))}let r=Fn(e);if(r){let n=e.slice(r.offset,r.offset+r.length),i=new TextDecoder(`utf-8`).decode(n);t.push({source:{type:`xmpPacket`},data:i})}return u.ok(t)}function Pn(e){let t=12;for(;t+8<=e.length;){let n=b(e,t+4);if(S(e,t)===`EXIF`)return t+8+n>e.length?null:{offset:t+8,length:n};let r=n+n%2;t+=8+r}return null}function Fn(e){let t=12;for(;t+8<=e.length;){let n=b(e,t+4);if(S(e,t)===`XMP `)return t+8+n>e.length?null:{offset:t+8,length:n};let r=n+n%2;t+=8+r}return null}function In(e){return Object.fromEntries(e.flatMap(e=>{if(re(e.keyword)){let t=ie(e.text);if(t)return Object.entries(t)}return[[e.keyword,e.text]]}))}function Ln(e){let t={};for(let n of e){let e=zn(n.source),r=n.data;if(n.source.type===`xmpPacket`){let e=ie(r);if(e){Object.assign(t,e);continue}}if(n.source.type===`exifUserComment`&&r.startsWith(`{`)){let e=Rn(r);if(e){Object.assign(t,e);continue}}t[e]=r}return t}function Rn(e){let t=L(e);if(!t.ok||t.type!==`object`)return null;let n=t.value;if(typeof n.Software==`string`&&!n.Software.startsWith(`NovelAI`)||typeof n.Comment!=`string`)return null;let r=L(n.Comment);return{Software:typeof n.Software==`string`?n.Software:`NovelAI`,Comment:r.ok?JSON.stringify(r.value):n.Comment}}function zn(e){switch(e.type){case`jpegCom`:return`Comment`;case`exifUserComment`:return`UserComment`;case`exifImageDescription`:return e.prefix??`ImageDescription`;case`exifMake`:return e.prefix??`Make`;case`xmpPacket`:return`XML:com.adobe.xmp`}}function Bn(e,t){let n=d(e),r=h(n);if(!r)return{status:`invalid`,message:`Unknown image format`};let i=Vn(n,r);if(i.status!==`success`)return i;let a=i.raw,o=an(a.format===`png`?In(a.chunks):Ln(a.segments));if(!o.ok)return{status:`unrecognized`,raw:a};let s=o.value;if(!t?.strict&&(s.width===0||s.height===0)){let e=on(n,r);e&&(s.width=s.width||e.width,s.height=s.height||e.height)}return{status:`success`,metadata:s,raw:a}}function Vn(e,t){let n=t===`png`?En(e):t===`jpeg`?xn(e):Nn(e);return n.ok?n.value.length===0?{status:`empty`}:t===`png`?{status:`success`,raw:{format:`png`,chunks:n.value}}:{status:`success`,raw:{format:t,segments:n.value}}:{status:`invalid`,message:n.error.type===`invalidSignature`?`Invalid ${t.toUpperCase()} signature`:n.error.message}}function Hn(e){let t=e.find(e=>e.keyword===`parameters`);return t?[{source:{type:`exifUserComment`},data:t.text}]:[]}function Un(e){let t=e.find(e=>e.source.type===`exifUserComment`);return t?c(`parameters`,t.data,`dynamic`):[]}function Wn(e){let t=e.find(e=>e.keyword===`parameters`);if(t&&!t.text.trimStart().startsWith(`{`))return Hn(e);let n={};for(let t of e)if(t.keyword===`prompt`){let e=L(t.text);e.ok&&e.type===`object`&&Object.assign(n,e.value)}else if(t.keyword===`extraMetadata`)n[t.keyword]=t.text;else{let e=L(t.text);n[t.keyword]=e.ok?e.value:t.text}return[{source:{type:`exifUserComment`},data:JSON.stringify(n)}]}function Gn(e){let t=r(e,`exifUserComment`);return t?t.data.trimStart().startsWith(`{`)?c(`prompt`,t.data,`text-unicode-escape`):Un(e):[]}function Kn(e){let t={};for(let n of e){let e=L(n.text);e.ok?t[n.keyword]=e.value:t[n.keyword]=n.text}return[{source:{type:`exifUserComment`},data:JSON.stringify(t)}]}function qn(e,t){let n=r(e,`exifUserComment`);if(!n)return[];let a=L(n.data);return!a.ok||a.type!==`object`?[]:Object.entries(a.value).flatMap(([e,n])=>{let r=i(n);return c(e,r===void 0?void 0:o(r),t)})}function Jn(e){return Kn(e)}let Yn=e=>{let t=r(e,`exifImageDescription`),n=r(e,`exifMake`);return!t&&!n?null:[...c(`prompt`,n?.data,`text-unicode-escape`),...c(`workflow`,t?.data,`text-unicode-escape`)]},Xn=e=>{let t=qn(e,`text-unicode-escape`);return t.length>0?t:null};function Zn(e){return Yn(e)??Xn(e)??[]}function Qn(e){let t=e.find(e=>re(e.keyword));return t?[{source:{type:`xmpPacket`},data:t.text}]:[]}function $n(e){let t=r(e,`xmpPacket`);return t?n(`XML:com.adobe.xmp`,t.data):[]}function er(e){let t=Object.fromEntries(e.map(e=>[e.keyword,e.text]));return[{source:{type:`exifUserComment`},data:JSON.stringify(t)}]}function tr(e){let t=r(e,`exifUserComment`);if(!t)return[];let n=L(t.data);return!n.ok||n.type!==`object`?[]:Object.entries(n.value).flatMap(([e,t])=>c(e,i(t),`dynamic`))}function nr(e){return Kn(e)}function rr(e){return qn(e,`dynamic`)}function ir(e){let t=e.find(e=>e.keyword===`Description`),n=t&&{source:{type:`exifImageDescription`},data:`\0\0\0\0${t.text}`},r=ar(e);return[n,{source:{type:`exifUserComment`},data:JSON.stringify(r)}].filter(e=>e!==void 0)}function ar(e){return Object.fromEntries(or.flatMap(t=>{let n=e.find(e=>e.keyword===t);return n?[[t,n.text]]:[]}))}let or=[`Comment`,`Description`,`Generation time`,`Software`,`Source`,`Title`];function sr(e){return cr(r(e,`exifUserComment`),r(e,`exifImageDescription`))}function cr(e,n){if(!e||!n)return[];let r=L(e.data);if(!r.ok||r.type!==`object`)return t(`Comment`,e.data);let a=r.value,o=lr(n,i(a.Description));return[t(`Title`,i(a.Title)??`NovelAI generated image`),c(`Description`,o,`dynamic`),t(`Software`,i(a.Software)??`NovelAI`),t(`Source`,i(a.Source)),t(`Generation time`,i(a[`Generation time`])),t(`Comment`,i(a.Comment))].flat()}function lr(e,t){if(e?.data){let t=e.data;return t.startsWith(`\0\0\0\0`)?t.slice(4):t}if(t)return t.startsWith(`\0\0\0\0`)?t.slice(4):t}function X(e){return t=>{let n=t.find(t=>t.keyword===e);return n?[{source:{type:`exifUserComment`},data:n.text}]:[]}}function Z(e,t){return n=>{let r=n.find(e=>e.source.type===`exifUserComment`);return r?c(e,r.data,t):[]}}let ur={parameters:`text-utf8-raw`,default:`text-unicode-escape`};function dr(e){let t={};for(let n of e){let e=L(n.text);t[n.keyword]=e.ok?e.value:n.text}return[{source:{type:`exifUserComment`},data:JSON.stringify(t)}]}function fr(e){let t=r(e,`exifUserComment`);if(!t)return[];let n=L(t.data);if(!n.ok||n.type!==`object`)return[];let a=n.value;return l(Object.entries(a).map(([e,t])=>{let n=i(t);return[e,n===void 0?void 0:o(n)]}),ur)}function pr(e){let t=e.find(e=>e.keyword===`parameters`);if(!t)return[];let n=L(t.text),r=[{source:{type:`exifUserComment`},data:n.ok?JSON.stringify(n.value):t.text}],i=e.find(e=>e.keyword===`prompt`);return i&&r.push({source:{type:`exifMake`},data:i.text}),r}function mr(e){let t=r(e,`exifUserComment`);return[c(`prompt`,r(e,`exifMake`)?.data,`text-unicode-escape`),c(`parameters`,t?.data,`text-unicode-escape`)].flat()}let hr={generation_data:`text-utf8-raw`,default:`text-unicode-escape`};function gr(e){let t={};for(let n of e){let e=L(n.text);t[n.keyword]=e.ok?e.value:n.text}return[{source:{type:`exifUserComment`},data:JSON.stringify(t)}]}function _r(e){let t=r(e,`exifUserComment`);if(!t)return[];let n=L(t.data);if(!n.ok||n.type!==`object`)return[];let a=n.value;return l(Object.entries(a).map(([e,t])=>{let n=i(t);return[e,n===void 0?void 0:o(n)]}),hr)}function vr(e,t){if(e.status===`empty`)return u.error({type:`missingRawData`});if(e.status===`invalid`)return u.error({type:`invalidParseResult`,status:e.status});if(e.status===`unrecognized`)return u.error({type:`unsupportedSoftware`,software:`unknown`});let n=e.raw;if(n.format===t)return u.ok(n);let r=e.metadata.software,i=Ar[r];return i?i(n,t):u.error({type:`unsupportedSoftware`,software:r})}function Q(e,t){return(n,r)=>{if(n.format===`png`){if(r===`png`)return u.ok(n);let t=e(n.chunks);return u.ok({format:r,segments:t})}if(r===`jpeg`||r===`webp`)return u.ok({format:r,segments:n.segments});let i=t(n.segments);return u.ok({format:`png`,chunks:i})}}let yr=Q(ir,sr),$=Q(Hn,Un),br=Q(Jn,Zn),xr=Q(er,tr),Sr=Q(X(`parameters`),Z(`parameters`,`text-unicode-escape`)),Cr=Q(X(`parameters`),Z(`parameters`,`text-unicode-escape`)),wr=Q(pr,mr),Tr=Q(nr,rr),Er=Q(X(`parameters`),Z(`parameters`,`text-unicode-escape`)),Dr=Q(Qn,$n),Or=Q(Wn,Gn),kr=Q(dr,fr),Ar={novelai:yr,"sd-webui":$,"sd-next":$,forge:$,"forge-classic":$,"forge-neo":$,reforge:$,"easy-reforge":$,civitai:Or,comfyui:br,tensorart:Q(gr,_r),"stability-matrix":kr,easydiffusion:xr,fooocus:Sr,"ruined-fooocus":Cr,swarmui:wr,invokeai:Tr,"hf-space":Er,"draw-things":Dr};function jr(e,t){let n=d(e),r=h(n);if(!r)return{ok:!1,error:{type:`unsupportedFormat`}};if(t.status===`empty`){let e=Nr[r].writeEmpty(n,[]);return e.ok?{ok:!0,value:e.value}:{ok:!1,error:{type:`writeFailed`,message:e.error.type}}}if(t.status===`invalid`)return{ok:!1,error:{type:`writeFailed`,message:`Cannot write invalid metadata`}};if(t.status===`unrecognized`){if(t.raw.format===r)return Mr(n,r,t.raw);let e=Nr[r].writeEmpty(n,[]);return e.ok?{ok:!0,value:e.value,warning:{type:`metadataDropped`,reason:`unrecognizedCrossFormat`}}:{ok:!1,error:{type:`writeFailed`,message:e.error.type}}}let i=vr(t,r);return i.ok?Mr(n,r,i.value):{ok:!1,error:{type:`conversionFailed`,message:`Failed to convert metadata: ${i.error.type}`}}}function Mr(e,t,n){if(t===`png`&&n.format===`png`){let t=A(e,n.chunks);return t.ok?{ok:!0,value:t.value}:{ok:!1,error:{type:`writeFailed`,message:t.error.type}}}if(t===`jpeg`&&n.format===`jpeg`){let t=O(e,n.segments);return t.ok?{ok:!0,value:t.value}:{ok:!1,error:{type:`writeFailed`,message:t.error.type}}}if(t===`webp`&&n.format===`webp`){let t=ke(e,n.segments);return t.ok?{ok:!0,value:t.value}:{ok:!1,error:{type:`writeFailed`,message:t.error.type}}}return{ok:!1,error:{type:`writeFailed`,message:`Internal error: format mismatch after conversion`}}}let Nr={png:{writeEmpty:A},jpeg:{writeEmpty:O},webp:{writeEmpty:ke}},Pr=Object.freeze({novelai:`NovelAI`,comfyui:`ComfyUI`,swarmui:`SwarmUI`,tensorart:`TensorArt`,"stability-matrix":`Stability Matrix`,invokeai:`InvokeAI`,"sd-webui":`Stable Diffusion WebUI`,forge:`Forge`,"forge-classic":`Forge - Classic`,"forge-neo":`Forge - Neo`,reforge:`reForge`,"easy-reforge":`EasyReforge`,"sd-next":`SD.Next`,civitai:`Civitai`,"hf-space":`Hugging Face Space`,easydiffusion:`Easy Diffusion`,fooocus:`Fooocus`,"ruined-fooocus":`Ruined Fooocus`,"draw-things":`Draw Things`});return e.embed=Re,e.writeAsWebUI=Re,e.formatAsWebUI=N,e.formatRaw=Ie,e.read=Bn,e.softwareLabels=Pr,e.stringify=Le,e.write=jr,e})({});
11
+ `,n);return{prompt:e.slice(0,t).trim(),negativePrompt:e.slice(t+16,r).trim(),settings:e.slice(r).trim()}}function Ve(e){let t=new Map;if(!e||e.length>1e4)return t;for(let n of e.matchAll(/([A-Za-z][A-Za-z0-9 ]*?):\s*([^,]+?)(?=,\s*[A-Za-z][A-Za-z0-9 ]*?:|$)/g)){let e=(n[1]??``).trim(),r=(n[2]??``).trim();t.set(e,r)}return t}function He(e){let t=e.match(/(\d+)x(\d+)/);return t?[Number.parseInt(t[1]??`0`,10),Number.parseInt(t[2]??`0`,10)]:[0,0]}function I(e){if(e===void 0)return;let t=Number.parseFloat(e);return Number.isNaN(t)?void 0:t}function L(e){try{return Ue(JSON.parse(e))}catch{return{ok:!1,error:{type:`parseError`,message:`Invalid JSON`}}}}function Ue(e){if(e===null)return{ok:!0,type:`null`,value:null};if(Array.isArray(e))return{ok:!0,type:`array`,value:e};switch(typeof e){case`object`:return{ok:!0,type:`object`,value:e};case`string`:return{ok:!0,type:`string`,value:e};case`number`:return{ok:!0,type:`number`,value:e};case`boolean`:return{ok:!0,type:`boolean`,value:e};default:return{ok:!1,error:{type:`parseError`,message:`Unexpected JSON type`}}}}let We=[`KSampler`,`KSamplerAdvanced`,`SamplerCustomAdvanced`,`SamplerCustom`,`DetailerForEach`],Ge=[`EmptyLatentImage`],Ke=[`SDXL Empty Latent Image (rgthree)`],qe=[`CheckpointLoaderSimple`,`CheckpointLoader`],Je=[`UNETLoader`],Ye=[`CLIPSetLastLayer`],Xe=[`UpscaleModelLoader`],Ze=[`ImageScale`,`ImageScaleBy`],Qe=[`LatentUpscale`,`LatentUpscaleBy`],$e=[`VAEEncode`,`VAEEncodeTiled`];function et(e){let t={};for(let n of Object.values(e)){let e=n.class_type;!t.sampler&&We.includes(e)?t.sampler=n:!t.latentImage&&Ge.includes(e)?t.latentImage=n:!t.latentImageRgthree&&Ke.includes(e)?t.latentImageRgthree=n:!t.checkpoint&&qe.includes(e)?t.checkpoint=n:!t.unetLoader&&Je.includes(e)?t.unetLoader=n:!t.clipSetLastLayer&&Ye.includes(e)?t.clipSetLastLayer=n:!t.hiresModelUpscale&&Xe.includes(e)?t.hiresModelUpscale=n:!t.hiresImageScale&&Ze.includes(e)?t.hiresImageScale=n:!t.latentUpscale&&Qe.includes(e)?t.latentUpscale=n:!t.vaeEncode&&$e.includes(e)&&(t.vaeEncode=n)}return t}function R(e,t){if(z(t))return e[String(t[0])]}function z(e){return Array.isArray(e)&&e.length===2&&(typeof e[0]==`string`||typeof e[0]==`number`)&&typeof e[1]==`number`}function tt(e,t,n=10){if(n<=0)return``;let r=e[t];if(!r)return``;let i=r.inputs.text??r.inputs.prompt??r.inputs.Text??r.inputs.prompt_text;if(typeof i==`string`)return i;if(z(i)){let t=tt(e,String(i[0]),n-1);if(t)return t}return typeof r.inputs.text_0==`string`?r.inputs.text_0:``}function nt(e,t){return R(e,t.inputs.guider)||t}function rt(e,t){if(!t)return{promptText:``,negativeText:``};let n=nt(e,t);return{promptText:B(e,n.inputs.positive,`positive`),negativeText:B(e,n.inputs.negative,`negative`)}}function B(e,t,n,r=10){if(r<=0||!z(t))return``;let i=String(t[0]),a=tt(e,i);if(a)return a;let o=e[i];if(!o)return``;let s=o.inputs[n];return B(e,s,n,r-1)}function it(e,t){if(e){let t=Number(e.inputs.width)||0,n=Number(e.inputs.height)||0;if(t>0&&n>0)return{width:t,height:n}}if(t&&typeof t.inputs.dimensions==`string`){let e=t.inputs.dimensions.match(/^(\d+)\s*x\s*(\d+)/);if(e?.[1]&&e[2])return{width:Number.parseInt(e[1],10),height:Number.parseInt(e[2],10)}}return{width:0,height:0}}function at(e,t){if(!t)return;if(t.class_type===`SamplerCustomAdvanced`)return ot(e,t);if(t.class_type===`SamplerCustom`)return st(e,t);let n=t.inputs.seed;return z(n)&&(n=e[String(n[0])]?.inputs.seed),{seed:n,steps:t.inputs.steps,cfg:t.inputs.cfg,sampler:t.inputs.sampler_name,scheduler:t.inputs.scheduler,denoise:t.inputs.denoise}}function ot(e,t){let n=R(e,t.inputs.noise),r=R(e,t.inputs.guider),i=R(e,t.inputs.sampler),a=R(e,t.inputs.sigmas);return{seed:n?.inputs.noise_seed,steps:a?.inputs.steps,cfg:r?.inputs.cfg,sampler:i?.inputs.sampler_name,scheduler:a?.inputs.scheduler,denoise:a?.inputs.denoise}}function st(e,t){let n=R(e,t.inputs.sampler),r=R(e,t.inputs.sigmas),i=t.inputs.noise_seed;return z(i)&&(i=e[String(i[0])]?.inputs.seed),{seed:i,steps:r?.inputs.steps,cfg:t.inputs.cfg,sampler:n?.inputs.sampler_name,scheduler:r?.inputs.scheduler,denoise:r?.inputs.denoise}}function ct(e,t){let n=e?.inputs?.ckpt_name;if(typeof n==`string`&&n)return{name:n};let r=t?.inputs?.unet_name;if(typeof r==`string`&&r)return{name:r}}function lt(e){if(!e)return;let t=e.inputs.stop_at_clip_layer;if(typeof t==`number`)return-t}function ut(e,t){if(!(t<=0||e<=0))return Math.round(e/t*100)/100}function dt(e,t){let n=t.inputs.latent_image;if(!z(n))return!1;let r=e[String(n[0])];if(!r)return!1;if(Qe.includes(r.class_type))return!0;if(!$e.includes(r.class_type))return!1;let i=r.inputs.pixels;if(!z(i))return!1;let a=e[String(i[0])];return a?Ze.includes(a.class_type):!1}function ft(e){return Object.values(e).find(t=>We.includes(t.class_type)&&dt(e,t))}function pt(e,t){let n=e.extraMetadata;if(typeof n==`string`){let e=L(n);if(e.ok&&e.type===`object`)return e.value}if(t?.extraMetadata){let e=L(t.extraMetadata);if(e.ok&&e.type===`object`)return e.value}}function mt(e){if(!e)return;let t=ht(e),n=gt(e);return P({prompt:e.prompt,negativePrompt:e.negativePrompt,width:e.width,height:e.height,model:e.baseModel?{name:e.baseModel}:void 0,...n,...t})}function ht(e){if(!e.transformations)return{};let t=e.transformations.find(e=>e.type===`upscale`);if(!t?.upscaleWidth)return{};let n=ut(t.upscaleWidth,e.width??0);return n===void 0?{}:{upscale:{scale:n}}}function gt(e){return e.seed===void 0&&e.steps===void 0&&e.cfgScale===void 0&&e.sampler===void 0?{}:{sampling:{seed:e.seed,steps:e.steps,cfg:e.cfgScale,sampler:e.sampler}}}let _t=/Text(Encode|.?Box)|ShowText|PromptStash/,vt=/neg/i;function V(e){return typeof e==`string`?e:``}function H(e){if(typeof e==`number`)return Number.isFinite(e)?e:void 0;if(typeof e==`string`){let t=Number(e);return Number.isFinite(t)?t:void 0}}function yt(e){let t,n,r,i,a,o,s,c,l,u;for(let d of Object.values(e)){if(!d||typeof d!=`object`)continue;let e=d.class_type,f=d.inputs;if(!(!e||!f)){if(_t.test(e)){let r=V(f.text)||V(f.prompt)||V(f.Text)||V(f.prompt_text)||V(f.text_0);r&&(vt.test(e)||t?n||=r:t=r)}e.includes(`Sampler`)&&(r===void 0&&(r=H(f.seed)??H(f.noise_seed)),i===void 0&&(i=H(f.steps)),a===void 0&&(a=H(f.cfg)),o||=V(f.sampler_name),s||=V(f.scheduler)),c||=V(f.ckpt_name)||V(f.unet_name),l===void 0&&(l=H(f.width)),u===void 0&&(u=H(f.height))}}let d={};r!==void 0&&(d.seed=r),i!==void 0&&(d.steps=i),a!==void 0&&(d.cfg=a),o&&(d.sampler=o),s&&(d.scheduler=s);let f={};return t&&(f.prompt=t),n&&(f.negativePrompt=n),l!==void 0&&l>0&&(f.width=l),u!==void 0&&u>0&&(f.height=u),c&&(f.model={name:c}),Object.keys(d).length>0&&(f.sampling=d),f}let bt=[`extra`,`extraMetadata`,`resource-stack`];function U(e){let t=St(e);if(!t)return Ct(e)?u.ok({software:`comfyui`,nodes:{},prompt:``,negativePrompt:``,width:0,height:0}):u.error({type:`unsupportedFormat`});let n=L(t);if(!n.ok||n.type!==`object`)return u.error({type:`parseError`,message:`Invalid JSON in prompt entry`});let r=n.value,i=Dt(yt(r),mt(pt(r,e)),wt(r));return u.ok({software:`comfyui`,nodes:Object.fromEntries(Object.entries(r).filter(([e])=>!bt.includes(e))),...i})}function xt(e){if(!e||typeof e.denoise!=`number`)return e;if(e.denoise>=1){let{denoise:t,...n}=e;return n}return e}function W(e){return e.replace(/\0+$/,``).replace(/([:,[])\s*NaN\b/g,`$1null`)}function St(e){if(e.prompt)return W(e.prompt);let t=[e.UserComment,e.ImageDescription,e.Make,e.Prompt,e.Workflow];for(let e of t)if(e&&e.startsWith(`{`)){let t=W(e),n=L(t);if(!n.ok||n.type!==`object`)continue;if(n.value.prompt&&typeof n.value.prompt==`object`)return JSON.stringify(n.value.prompt);if(Object.values(n.value).some(e=>e&&typeof e==`object`&&`class_type`in e))return t}}function Ct(e){for(let t of[e.workflow,e.Workflow]){if(!t?.startsWith(`{`))continue;let e=L(W(t));if(e.ok&&e.type===`object`&&Array.isArray(e.value.nodes))return!0}return!1}function wt(e){let t=et(e),{promptText:n,negativeText:r}=rt(e,t.sampler),{width:i,height:a}=it(t.latentImage,t.latentImageRgthree),o=ft(e),s=xt(o?at(e,o):void 0),c=Tt(e,t,i),l=t.hiresModelUpscale?.inputs.model_name,u=xt(at(e,t.sampler)),d=lt(t.clipSetLastLayer);return P({prompt:n||void 0,negativePrompt:r||void 0,width:i>0?i:void 0,height:a>0?a:void 0,model:ct(t.checkpoint,t.unetLoader),sampling:P({...u,clipSkip:d}),...Et(l,c,s)})}function Tt(e,t,n){let r=t.latentUpscale?.inputs;if(r?.scale_by!==void 0)return r.scale_by;let i=t.hiresImageScale?.inputs.width;if(i!==void 0){if(z(i)){let t=e[String(i[0])];return typeof t?.inputs.clip_scale==`number`?t.inputs.clip_scale:void 0}if(typeof i==`number`)return ut(i,n)}}function Et(e,t,n){return!e&&t===void 0&&!n?{}:n?{hires:{upscaler:e,scale:t,steps:n.steps,denoise:n.denoise}}:e?{upscale:{upscaler:e,scale:t}}:{}}function G(...e){let t={};for(let n of e)if(n)for(let[e,r]of Object.entries(n))r!==void 0&&(t[e]=r);return Object.keys(t).length>0?t:void 0}function Dt(...e){let t=[...e].reverse(),n=e=>t.find(t=>t?.[e])?.[e];return{prompt:n(`prompt`)??``,negativePrompt:n(`negativePrompt`)??``,width:n(`width`)??0,height:n(`height`)??0,...P({model:G(...e.map(e=>e?.model)),sampling:G(...e.map(e=>e?.sampling)),hires:G(...e.map(e=>e?.hires)),upscale:G(...e.map(e=>e?.upscale))})}}let K=`extraMetadata`,q=`sui_image_params`,Ot=`swarm_version`,kt=`noise_schedule`,At=`v4_prompt`,jt=`RuinedFooocus`;function Mt(e){let t=Pt(e);if(t)return t;let n=It(e);if(n)return n;let r=e.parameters??e.UserComment??e.Comment;return r?Lt(r):null}function Nt(e){return`invokeai_metadata`in e?`invokeai`:`generation_data`in e?`tensorart`:`smproj`in e?`stability-matrix`:K in e?`civitai`:null}function Pt(e){if(e.Software?.startsWith(`NovelAI`))return`novelai`;if(e.CreatorTool?.startsWith(`Draw Things`))return`draw-things`;let t=Nt(e);if(t)return t;if(`fooocus_scheme`in e)return`fooocus`;if(`use_stable_diffusion_model`in e)return`easydiffusion`;if(e.parameters?.includes(q))return`swarmui`;let n=e.UserComment??e.Comment;return n?.startsWith(`{`)?Ft(n):null}function Ft(e){let t=L(e);if(!t.ok||t.type!==`object`)return null;let n=t.value,r=Nt(n);if(r)return r;if(`prompt`in n&&`workflow`in n){let e=n.workflow,t=n.prompt,r=typeof e==`object`||typeof t==`object`,i=typeof e==`string`&&e.startsWith(`{`)||typeof t==`string`&&t.startsWith(`{`);if(r||i)return`comfyui`}if(q in n)return`swarmui`;if(`prompt`in n&&`parameters`in n){let e=String(n.parameters||``);if(e.includes(q)||e.includes(Ot))return`swarmui`}return null}function It(e){if(`prompt`in e&&`workflow`in e||`Prompt`in e&&`Workflow`in e||`workflow`in e||`Workflow`in e)return`comfyui`;let t=e.prompt??e.Prompt;if(t?.startsWith(`{`)){if(t.includes(q))return`swarmui`;if(t.includes(`"${K}"`))return`civitai`;if(t.includes(`class_type`))return`comfyui`}return null}function Lt(e){return e.startsWith(`{`)?Rt(e):zt(e)}function Rt(e){return e.includes(q)?`swarmui`:e.includes(`"software":"${jt}"`)||e.includes(`"software": "${jt}"`)?`ruined-fooocus`:e.includes(`"use_stable_diffusion_model"`)?`easydiffusion`:e.includes(`civitai:`)||e.includes(`"${K}"`)?`civitai`:e.includes(`"${At}"`)||e.includes(`"${kt}"`)||e.includes(`"uncond_scale"`)||e.includes(`"Software":"NovelAI"`)||e.includes(`\\"${kt}\\"`)||e.includes(`\\"${At}\\"`)?`novelai`:e.includes(`"Model"`)&&e.includes(`"resolution"`)?`hf-space`:e.includes(`"prompt"`)&&e.includes(`"base_model"`)?`fooocus`:e.includes(`"prompt"`)||e.includes(`"nodes"`)?`comfyui`:null}function zt(e){if(e.includes(q)||e.includes(Ot))return`swarmui`;let t=e.match(/Version:\s*([^\s,]+)/);if(t){let e=t[1];if(e&&/^v\d/.test(e))return`sd-webui`;if(e===`classic`)return`forge-classic`;if(e===`neo`||e?.startsWith(`neo`))return`forge-neo`;if(e?.startsWith(`f`)&&/^f\d/.test(e))return/^f\d+\.\d+(\.\d+)?-v/.test(e)?`easy-reforge`:/^f\d+\.\d+(\.\d+)?v\d+-v/.test(e)?`reforge`:`forge`;if(e?.startsWith(`Fooocus`))return`fooocus`;if(e===`ComfyUI`)return`comfyui`}return e.includes(`App: SD.Next`)||e.includes(`App:SD.Next`)?`sd-next`:e.includes(`Civitai resources:`)?`civitai`:e.includes(`Steps:`)||e.includes(`Sampler:`)||e.includes(`Negative prompt:`)?`sd-webui`:null}function Bt(e){let t=e.UserComment?.startsWith(`{`)?e.UserComment:e.Comment?.startsWith(`{`)?e.Comment:void 0;if(!t)return u.error({type:`unsupportedFormat`});let n=L(t);return!n.ok||n.type!==`object`?u.error({type:`parseError`,message:`Invalid JSON in Draw Things metadata`}):Ht(n.value)}function Vt(e){if(typeof e!=`string`)return{width:0,height:0};let t=e.match(/^(\d+)x(\d+)$/);return t?{width:Number(t[1]),height:Number(t[2])}:{width:0,height:0}}function Ht(e){let t=t=>{let n=e[t];return typeof n==`string`?n:void 0},n=t=>{let n=e[t];if(typeof n==`number`&&n!==0)return n},r=(t(`c`)??``).trim(),i=(t(`uc`)??``).trim(),{width:a,height:o}=Vt(e.size),s={software:`draw-things`,prompt:r,negativePrompt:i,width:a,height:o,model:P({name:t(`model`)}),sampling:P({sampler:t(`sampler`),steps:n(`steps`),cfg:n(`scale`),seed:n(`seed`),denoise:n(`strength`)})};return u.ok(s)}function Ut(e){if(!e)return;let t=e.replace(/\\/g,`/`).split(`/`);return t[t.length-1]}function Wt(e){if(`use_stable_diffusion_model`in e)return Gt(e);let t=e.UserComment?.startsWith(`{`)?e.UserComment:e.parameters?.startsWith(`{`)?e.parameters:void 0;if(!t)return u.error({type:`unsupportedFormat`});let n=L(t);return!n.ok||n.type!==`object`?u.error({type:`parseError`,message:`Invalid JSON in Easy Diffusion metadata`}):Gt(n.value)}function Gt(e){let t=t=>{let n=e[t];return typeof n==`string`?n:void 0},n=t=>Number(e[t])||void 0,r=(t(`prompt`)??``).trim(),i=(t(`negative_prompt`)??``).trim(),a=t(`use_stable_diffusion_model`),o=P({upscaler:t(`use_upscale`),scale:n(`upscale_amount`)}),s={software:`easydiffusion`,prompt:r,negativePrompt:i,width:n(`width`)??0,height:n(`height`)??0,model:P({name:Ut(a),vae:t(`use_vae_model`)}),sampling:P({sampler:t(`sampler_name`),steps:n(`num_inference_steps`),cfg:n(`guidance_scale`),seed:n(`seed`),clipSkip:n(`clip_skip`),denoise:n(`prompt_strength`)}),...o?{upscale:o}:{}};return u.ok(s)}function Kt(e){if(!e)return{width:0,height:0};let t=e.match(/\(\s*(\d+)\s*,\s*(\d+)\s*\)/);return!t?.[1]||!t[2]?{width:0,height:0}:{width:Number(t[1]),height:Number(t[2])}}function qt(e){let t=e.parameters??e.UserComment;if(!t||!t.startsWith(`{`))return u.error({type:`unsupportedFormat`});let n=L(t);if(!n.ok||n.type!==`object`)return u.error({type:`parseError`,message:`Invalid JSON in Fooocus metadata`});let r=n.value,{width:i,height:a}=Kt(r.resolution),o={software:`fooocus`,prompt:r.prompt?.trim()??``,negativePrompt:r.negative_prompt?.trim()??``,width:i,height:a,model:P({name:r.base_model,hash:r.base_model_hash,vae:r.vae}),sampling:P({sampler:r.sampler,scheduler:r.scheduler,steps:r.steps,cfg:r.guidance_scale,seed:r.seed,clipSkip:r.clip_skip})};return u.ok(o)}function Jt(e){let t=e.parameters??e.UserComment;if(!t)return u.error({type:`unsupportedFormat`});let n=L(t);if(!n.ok||n.type!==`object`)return u.error({type:`parseError`,message:`Invalid JSON in parameters entry`});let r=n.value,{width:i,height:a}=(e=>{let t=e?.match(/(\d+)\s*x\s*(\d+)/);return t?.[1]&&t?.[2]?{width:Number.parseInt(t[1],10),height:Number.parseInt(t[2],10)}:{width:0,height:0}})(r.resolution),o={software:`hf-space`,prompt:r.prompt??``,negativePrompt:r.negative_prompt??``,width:i,height:a,model:P({name:r.Model,hash:r[`Model hash`]}),sampling:P({sampler:r.sampler,steps:r.num_inference_steps,cfg:r.guidance_scale,seed:r.seed}),hires:r.use_upscaler?P({upscaler:r.use_upscaler.upscale_method,denoise:r.use_upscaler.upscaler_strength,scale:r.use_upscaler.upscale_by,steps:r.use_upscaler.upscale_steps}):void 0};return u.ok(o)}function J(e,t){if(!e.UserComment?.startsWith(`{`))return;let n=L(e.UserComment);if(!n.ok||n.type!==`object`)return;let r=n.value[t];if(typeof r==`string`)return r;if(typeof r==`object`&&r)return JSON.stringify(r)}function Yt(e){return e.invokeai_metadata??J(e,`invokeai_metadata`)}function Xt(e){let t=Yt(e);if(!t)return u.error({type:`unsupportedFormat`});let n=L(t);if(!n.ok||n.type!==`object`)return u.error({type:`parseError`,message:`Invalid JSON in invokeai_metadata entry`});let r=n.value,i=r.width??0,a=r.height??0,o=Zt(r);return u.ok({software:`invokeai`,prompt:r.positive_prompt??``,negativePrompt:r.negative_prompt??``,width:i,height:a,model:P({name:r.model?.name,hash:r.model?.hash}),sampling:P({seed:r.seed,steps:r.steps,cfg:r.cfg_scale,sampler:r.scheduler}),...o})}function Zt(e){if(!e.upscale_model?.name&&e.upscale_scale===void 0)return{};let t=P({upscaler:e.upscale_model?.name,scale:e.upscale_scale});return t?{upscale:t}:{}}function Qt(e){let t=e.UserComment??e.Comment;if(!t)return u.error({type:`parseError`,message:`Missing Comment/UserComment entry`});let n=L(t);if(!n.ok||n.type!==`object`)return u.error({type:`parseError`,message:`Invalid JSON in Comment entry`});let r=n.value,i=r.width??0,a=r.height??0,o=r.v4_prompt?.caption?.base_caption??r.prompt??``,s=r.v4_negative_prompt?.caption?.base_caption??r.uc??``,c=r.v4_prompt?.caption?.char_captions,l=c&&c.length>0?c.map(e=>e.char_caption?{prompt:e.char_caption,center:e.centers?.[0]}:null).filter(e=>e!==null):void 0;return u.ok({software:`novelai`,prompt:o,negativePrompt:s,width:i,height:a,sampling:P({steps:r.steps,cfg:r.scale,seed:r.seed,sampler:r.sampler,scheduler:r.noise_schedule}),characterPrompts:l,useCoords:l?r.v4_prompt?.use_coords:void 0,useOrder:l?r.v4_prompt?.use_order:void 0})}function $t(e){let t=e.parameters??e.UserComment;if(!t||!t.startsWith(`{`))return u.error({type:`unsupportedFormat`});let n=L(t);if(!n.ok||n.type!==`object`)return u.error({type:`parseError`,message:`Invalid JSON in Ruined Fooocus metadata`});let r=n.value,i={software:`ruined-fooocus`,prompt:r.Prompt?.trim()??``,negativePrompt:r.Negative?.trim()??``,width:r.width??0,height:r.height??0,model:{name:r.base_model_name,hash:r.base_model_hash},sampling:{sampler:r.sampler_name,scheduler:r.scheduler,steps:r.steps,cfg:r.cfg,seed:r.seed,clipSkip:r.clip_skip}};return u.ok(i)}function en(e){let t=U(e);if(!t.ok||t.value.software!==`comfyui`)return u.error({type:`unsupportedFormat`});let n=e[`parameters-json`]??J(e,`parameters-json`),r=n?L(n):void 0,i=r?.ok&&r.type===`object`?r.value:void 0;return u.ok({...t.value,software:`stability-matrix`,prompt:i?.PositivePrompt??t.value.prompt,negativePrompt:i?.NegativePrompt??t.value.negativePrompt,model:i?.ModelName!==void 0||i?.ModelHash!==void 0?{name:i?.ModelName,hash:i?.ModelHash}:t.value.model})}function tn(e){if(e.parameters)return e.parameters;if(!e.UserComment)return;let t=L(e.UserComment);if(!(!t.ok||t.type!==`object`)&&`sui_image_params`in t.value)return e.UserComment}function nn(e){let t=tn(e);if(!t)return u.error({type:`unsupportedFormat`});let n=L(t);if(!n.ok||n.type!==`object`)return u.error({type:`parseError`,message:`Invalid JSON in parameters entry`});let r=n.value.sui_image_params;if(!r)return u.error({type:`unsupportedFormat`});let i=r.width??0,a=r.height??0,o=e.prompt||e.Make,s=o?L(o):void 0,c=s?.ok&&s.type===`object`?s.value:void 0;return u.ok({software:`swarmui`,prompt:r.prompt??``,negativePrompt:r.negativeprompt??``,width:i,height:a,nodes:c,model:P({name:r.model}),sampling:P({seed:r.seed,steps:r.steps,cfg:r.cfgscale,sampler:r.sampler,scheduler:r.scheduler}),hires:P({scale:r.refinerupscale,upscaler:r.refinerupscalemethod,denoise:r.refinercontrolpercentage})})}function rn(e){let t=e.generation_data??J(e,`generation_data`),n=e.prompt??J(e,`prompt`);if(!t)return u.error({type:`unsupportedFormat`});let r=L(t.replace(/\0+$/,``));if(!r.ok||r.type!==`object`)return u.error({type:`parseError`,message:`Invalid JSON in generation_data entry`});let i=r.value;if(!n)return u.error({type:`unsupportedFormat`});let a=L(n);if(!a.ok||a.type!==`object`)return u.error({type:`parseError`,message:`Invalid JSON in prompt chunk`});let o=a.value,s=wt(o),c=P({name:i.baseModel?.modelFileName,hash:i.baseModel?.hash});return u.ok({software:`tensorart`,nodes:o,prompt:i.prompt??s?.prompt??``,negativePrompt:i.negativePrompt??s?.negativePrompt??``,width:s?.width??0,height:s?.height??0,model:c??s?.model,sampling:s?.sampling,hires:s?.hires,upscale:s?.upscale})}function an(e){let t=Mt(e);switch(t){case`novelai`:return Qt(e);case`sd-webui`:case`forge`:case`forge-classic`:case`forge-neo`:case`reforge`:case`easy-reforge`:case`sd-next`:return F(e,t);case`hf-space`:return Jt(e);case`civitai`:{let t=U(e);return t.ok?u.ok({...t.value,software:`civitai`}):F(e,`civitai`)}case`comfyui`:{let t=U(e);return t.ok?t:F(e,`sd-webui`)}case`invokeai`:return Xt(e);case`swarmui`:return nn(e);case`tensorart`:return rn(e);case`stability-matrix`:return en(e);case`easydiffusion`:return Wt(e);case`fooocus`:{let t=e.fooocus_scheme,n=e.parameters??e.UserComment;return t===`a1111`||n&&!n.startsWith(`{`)?F(e,`fooocus`):qt(e)}case`ruined-fooocus`:return $t(e);case`draw-things`:return Bt(e);default:return u.error({type:`unsupportedFormat`})}}let on=new Set([`trainedAlgorithmicMedia`,`compositeWithTrainedAlgorithmicMedia`,`algorithmicMedia`,`compositeSynthetic`]),sn=/https?:\/\/cv\.iptc\.org\/newscodes\/digitalsourcetype\/([A-Za-z]+)/g,cn=[{marker:`OpenAI Media Service API`,vendor:`openai`},{marker:`Google LLC`,vendor:`google`},{marker:`Google C2PA`,vendor:`google`},{marker:`Google Media Processing Services`,vendor:`google`}];function ln(e,t){let n=un(e,t);if(!n)return null;let r=hn(n),i=[...r.matchAll(sn)],a=i.find(e=>on.has(e[1]??``)),o=(a??i[0])?.[0],s=a!==void 0,c=cn.find(({marker:e})=>r.includes(e))?.vendor??`unknown`,l=fn(n,r);return{vendor:c,aiGenerated:s,...o?{digitalSourceType:o}:{},...l?{claimGenerator:l}:{}}}function un(e,t){return t===`png`?dn(e):null}function dn(e){let t=8;for(;t+8<=e.length;){let n=y(e,t),r=S(e,t+4),i=t+8;if(i+n>e.length)return null;if(r===`caBX`){let t=Math.min(n,8388608);return e.slice(i,i+t)}if(r===`IEND`)return null;t=i+n+4}return null}function fn(e,t){let n=t.indexOf(`claim_generator_info`);if(n<0)return;let r=Math.min(t.length,n+256);for(let i=t.indexOf(`dname`,n);i>=0&&i<r;i=t.indexOf(`dname`,i+1)){let t=pn(e,i+5);if(t)return t}}function pn(e,t){let n=e[t];if(n===void 0||n<96||n>123)return null;let r=mn(e,t,n&31);if(!r)return null;let{length:i,dataPos:a}=r;return i<0||i>4096||a+i>e.length?null:new TextDecoder(`utf-8`).decode(e.slice(a,a+i))}function mn(e,t,n){return n<24?{length:n,dataPos:t+1}:n===24?{length:e[t+1]??-1,dataPos:t+2}:n===25?{length:(e[t+1]??0)<<8|(e[t+2]??0),dataPos:t+3}:null}function hn(e){return new TextDecoder(`iso-8859-1`).decode(e)}function gn(e,t){return t===`png`?_n(e):t===`jpeg`?vn(e):yn(e)}function _n(e){return e.length<24?null:{width:y(e,16),height:y(e,20)}}function vn(e){let t=2;for(;t<e.length-4;){if(e[t]!==255){t++;continue}let n=e[t+1]??0;if(n===255){t++;continue}let r=g(e,t+2);if(n>=192&&n<=207&&n!==196&&n!==200&&n!==204){if(t+9>e.length)return null;let n=g(e,t+5);return{width:g(e,t+7),height:n}}if(t+=2+r,n===218)break}return null}function yn(e){let t=12;for(;t<e.length&&!(t+8>e.length);){let n=S(e,t),r=b(e,t+4),i=r+r%2;if(n===`VP8X`){let n=v(e,t+12),r=v(e,t+15);return{width:n+1,height:r+1}}if(n===`VP8 `){let n=t+8;if(n+10>e.length)return null;if(!(v(e,n)&1)&&e[n+3]===157&&e[n+4]===1&&e[n+5]===42){let t=_(e,n+6,!0),r=_(e,n+8,!0);return{width:t&16383,height:r&16383}}}if(n===`VP8L`){if(t+13>e.length)return null;if(e[t+8]===47){let n=b(e,t+9);return{width:(n&16383)+1,height:(n>>14&16383)+1}}}t+=8+i}return null}function bn(e){if(e.length<8)return[];let t=e[0]===73&&e[1]===73,n=e[0]===77&&e[1]===77;if(!t&&!n||_(e,2,t)!==42)return[];let r=x(e,4,t),i=xn(e,r,t),a=Tn(e,r,t),o=a===null?[]:xn(e,a,t);return[...i,...o]}function xn(e,t,n){let r=[];if(t+2>e.length)return r;let i=_(e,t,n),a=t+2;for(let t=0;t<i;t++){if(a+12>e.length)return r;let t=_(e,a,n),i=_(e,a+2,n),o=x(e,a+4,n)*Cn(i);if(o>e.length){a+=12;continue}let s;if(s=o<=4?a+8:x(e,a+8,n),s+o>e.length){a+=12;continue}let c=e.slice(s,s+o);if(t===270){let e=wn(c);if(e){let t=Sn(e);r.push({source:{type:`exifImageDescription`,prefix:t??void 0},data:t?e.slice(t.length+2):e})}}else if(t===271){let e=wn(c);if(e){let t=Sn(e);r.push({source:{type:`exifMake`,prefix:t??void 0},data:t?e.slice(t.length+2):e})}}else if(t===37510){let e=En(c);e&&r.push({source:{type:`exifUserComment`},data:e})}a+=12}return r}function Sn(e){return e.match(/^([A-Za-z]+):\s/)?.[1]??null}function Cn(e){switch(e){case 1:return 1;case 2:return 1;case 3:return 2;case 4:return 4;case 5:return 8;case 7:return 1;default:return 1}}function wn(e){try{let t=new TextDecoder(`utf-8`,{fatal:!1}).decode(e);return t.endsWith(`\0`)&&(t=t.slice(0,-1)),t.trim()||null}catch{return null}}function Tn(e,t,n){if(t+2>e.length)return null;let r=_(e,t,n),i=t+2;for(let t=0;t<r;t++){if(i+12>e.length)return null;if(_(e,i,n)===34665)return x(e,i+8,n);i+=12}return null}function En(e){if(e.length<8)return null;if(e[0]===85&&e[1]===78&&e[2]===73&&e[3]===67&&e[4]===79&&e[5]===68&&e[6]===69&&e[7]===0){let t=e.slice(8);return t.length>=2&&t[0]!==0&&t[1]===0?On(t):Dn(t)}if(e[0]===65&&e[1]===83&&e[2]===67&&e[3]===73&&e[4]===73&&e[5]===0&&e[6]===0&&e[7]===0)return kn(e.slice(8));try{let t=new TextDecoder(`utf-8`,{fatal:!0}).decode(e);return t.endsWith(`\0`)&&(t=t.slice(0,-1)),t}catch{return null}}function Dn(e){let t=new TextDecoder(`utf-16be`).decode(e),n=t.indexOf(`\0`);return n>=0?t.slice(0,n):t}function On(e){let t=new TextDecoder(`utf-16le`).decode(e),n=t.indexOf(`\0`);return n>=0?t.slice(0,n):t}function kn(e){let t=e.indexOf(0),n=t>=0?e.subarray(0,t):e;return new TextDecoder(`ascii`).decode(n)}function An(e,t){return e[t]===69&&e[t+1]===120&&e[t+2]===105&&e[t+3]===102&&e[t+4]===0&&e[t+5]===0}function jn(e){if(!p(e))return u.error({type:`invalidSignature`});let t=[],n=Mn(e);if(n){let r=bn(e.slice(n.offset,n.offset+n.length));t.push(...r)}let r=Nn(e);if(r){let n=e.slice(r.offset,r.offset+r.length),i=new TextDecoder(`utf-8`).decode(n);t.push({source:{type:`xmpPacket`},data:i})}let i=Pn(e);if(i){let n=Fn(e.slice(i.offset,i.offset+i.length));n!==null&&t.push({source:{type:`jpegCom`},data:n})}return u.ok(t)}function Mn(e){let t=2;for(;t<e.length-4;){if(e[t]!==255){t++;continue}let n=e[t+1];if(n===255){t++;continue}let r=g(e,t+2);if(n===225&&r>=8){let n=t+4;if(n+6<=e.length&&An(e,n))return{offset:n+6,length:r-8}}if(t+=2+r,n===218||n===217)break}return null}function Nn(e){let t=2;for(;t<e.length-4;){if(e[t]!==255){t++;continue}let n=e[t+1];if(n===255){t++;continue}let r=g(e,t+2);if(n===225&&r>=E.length+2){let n=t+4;if(ne(e,n))return{offset:n+E.length,length:r-2-E.length}}if(t+=2+r,n===218||n===217)break}return null}function Pn(e){let t=2;for(;t<e.length-4;){if(e[t]!==255){t++;continue}let n=e[t+1];if(n===255){t++;continue}let r=g(e,t+2);if(n===254&&r>=2)return{offset:t+4,length:r-2};if(t+=2+r,n===218||n===217)break}return null}function Fn(e){try{return new TextDecoder(`utf-8`,{fatal:!0}).decode(e)}catch{return null}}function In(e){if(!f(e))return u.error({type:`invalidSignature`});let t=Ln(e);return t.ok?u.ok(t.value):t}function Ln(e){let t=[],n=8;for(;n<e.length;){if(n+4>e.length)return u.error({type:`corruptedChunk`,message:`Unexpected end of file while reading chunk length`});let r=y(e,n);if(n+=4,n+4>e.length)return u.error({type:`corruptedChunk`,message:`Unexpected end of file while reading chunk type`});let i=S(e,n);if(n+=4,n+r>e.length)return u.error({type:`corruptedChunk`,message:`Unexpected end of file while reading chunk data (${i})`});let a=e.slice(n,n+r);if(n+=r,n+=4,i===`tEXt`){let e=Rn(a);e&&t.push(e)}else if(i===`iTXt`){let e=Bn(a);e&&t.push(e)}if(i===`IEND`)break}return u.ok(t)}function Rn(e){let t=e.indexOf(0);if(t===-1)return null;let n=Vn(e.slice(0,t)),r=e.slice(t+1);return{type:`tEXt`,keyword:n,text:zn(r)??Vn(r)}}function zn(e){try{return new TextDecoder(`utf-8`,{fatal:!0}).decode(e)}catch{return null}}function Bn(e){let t=0,n=e.indexOf(0,t);if(n===-1)return null;let r=Y(e.slice(t,n));if(t=n+1,t>=e.length)return null;let i=e[t]??0;if(t+=1,t>=e.length)return null;let a=e[t]??0;t+=1;let o=e.indexOf(0,t);if(o===-1)return null;let s=Y(e.slice(t,o));t=o+1;let c=e.indexOf(0,t);if(c===-1)return null;let l=Y(e.slice(t,c));t=c+1;let u;if(i===1){let n=Hn(e.slice(t));if(!n)return null;u=Y(n)}else u=Y(e.slice(t));return{type:`iTXt`,keyword:r,compressionFlag:i,compressionMethod:a,languageTag:s,translatedKeyword:l,text:u}}function Vn(e){return new TextDecoder(`iso-8859-1`).decode(e)}function Y(e){return new TextDecoder(`utf-8`).decode(e)}function Hn(e){return null}function Un(e){if(!m(e))return u.error({type:`invalidSignature`});let t=[],n=Wn(e);if(n){let r=e.slice(n.offset,n.offset+n.length);t.push(...bn(r))}let r=Gn(e);if(r){let n=e.slice(r.offset,r.offset+r.length),i=new TextDecoder(`utf-8`).decode(n);t.push({source:{type:`xmpPacket`},data:i})}return u.ok(t)}function Wn(e){let t=12;for(;t+8<=e.length;){let n=b(e,t+4);if(S(e,t)===`EXIF`)return t+8+n>e.length?null:{offset:t+8,length:n};let r=n+n%2;t+=8+r}return null}function Gn(e){let t=12;for(;t+8<=e.length;){let n=b(e,t+4);if(S(e,t)===`XMP `)return t+8+n>e.length?null:{offset:t+8,length:n};let r=n+n%2;t+=8+r}return null}function Kn(e){return Object.fromEntries(e.flatMap(e=>{if(re(e.keyword)){let t=ie(e.text);if(t)return Object.entries(t)}return[[e.keyword,e.text]]}))}function qn(e){let t={};for(let n of e){let e=Yn(n.source),r=n.data;if(n.source.type===`xmpPacket`){let e=ie(r);if(e){Object.assign(t,e);continue}}if(n.source.type===`exifUserComment`&&r.startsWith(`{`)){let e=Jn(r);if(e){Object.assign(t,e);continue}}t[e]=r}return t}function Jn(e){let t=L(e);if(!t.ok||t.type!==`object`)return null;let n=t.value;if(typeof n.Software==`string`&&!n.Software.startsWith(`NovelAI`)||typeof n.Comment!=`string`)return null;let r=L(n.Comment);return{Software:typeof n.Software==`string`?n.Software:`NovelAI`,Comment:r.ok?JSON.stringify(r.value):n.Comment}}function Yn(e){switch(e.type){case`jpegCom`:return`Comment`;case`exifUserComment`:return`UserComment`;case`exifImageDescription`:return e.prefix??`ImageDescription`;case`exifMake`:return e.prefix??`Make`;case`xmpPacket`:return`XML:com.adobe.xmp`}}function Xn(e,t){let n=d(e),r=h(n);if(!r)return{status:`invalid`,message:`Unknown image format`};let i=Zn(n,r);if(i.status===`invalid`)return i;if(i.status===`success`){let{raw:e}=i,a=an(e.format===`png`?Kn(e.chunks):qn(e.segments));if(a.ok){let i=a.value;if(!t?.strict&&(i.width===0||i.height===0))try{let e=gn(n,r);e&&(i.width=i.width||e.width,i.height=i.height||e.height)}catch{}return{status:`success`,metadata:i,raw:e}}}let a=ln(n,r);return a?{status:`c2pa`,c2pa:a}:i.status===`empty`?{status:`empty`}:{status:`unrecognized`,raw:i.raw}}function Zn(e,t){let n=t===`png`?In(e):t===`jpeg`?jn(e):Un(e);return n.ok?n.value.length===0?{status:`empty`}:t===`png`?{status:`success`,raw:{format:`png`,chunks:n.value}}:{status:`success`,raw:{format:t,segments:n.value}}:{status:`invalid`,message:n.error.type===`invalidSignature`?`Invalid ${t.toUpperCase()} signature`:n.error.message}}function Qn(e){let t=e.find(e=>e.keyword===`parameters`);return t?[{source:{type:`exifUserComment`},data:t.text}]:[]}function $n(e){let t=e.find(e=>e.source.type===`exifUserComment`);return t?c(`parameters`,t.data,`dynamic`):[]}function er(e){let t=e.find(e=>e.keyword===`parameters`);if(t&&!t.text.trimStart().startsWith(`{`))return Qn(e);let n={};for(let t of e)if(t.keyword===`prompt`){let e=L(t.text);e.ok&&e.type===`object`&&Object.assign(n,e.value)}else if(t.keyword===`extraMetadata`)n[t.keyword]=t.text;else{let e=L(t.text);n[t.keyword]=e.ok?e.value:t.text}return[{source:{type:`exifUserComment`},data:JSON.stringify(n)}]}function tr(e){let t=r(e,`exifUserComment`);return t?t.data.trimStart().startsWith(`{`)?c(`prompt`,t.data,`text-unicode-escape`):$n(e):[]}function nr(e){let t={};for(let n of e){let e=L(n.text);e.ok?t[n.keyword]=e.value:t[n.keyword]=n.text}return[{source:{type:`exifUserComment`},data:JSON.stringify(t)}]}function rr(e,t){let n=r(e,`exifUserComment`);if(!n)return[];let a=L(n.data);return!a.ok||a.type!==`object`?[]:Object.entries(a.value).flatMap(([e,n])=>{let r=i(n);return c(e,r===void 0?void 0:o(r),t)})}function ir(e){return nr(e)}let ar=e=>{let t=r(e,`exifImageDescription`),n=r(e,`exifMake`);return!t&&!n?null:[...c(`prompt`,n?.data,`text-unicode-escape`),...c(`workflow`,t?.data,`text-unicode-escape`)]},or=e=>{let t=rr(e,`text-unicode-escape`);return t.length>0?t:null};function sr(e){return ar(e)??or(e)??[]}function cr(e){let t=e.find(e=>re(e.keyword));return t?[{source:{type:`xmpPacket`},data:t.text}]:[]}function lr(e){let t=r(e,`xmpPacket`);return t?n(`XML:com.adobe.xmp`,t.data):[]}function ur(e){let t=Object.fromEntries(e.map(e=>[e.keyword,e.text]));return[{source:{type:`exifUserComment`},data:JSON.stringify(t)}]}function dr(e){let t=r(e,`exifUserComment`);if(!t)return[];let n=L(t.data);return!n.ok||n.type!==`object`?[]:Object.entries(n.value).flatMap(([e,t])=>c(e,i(t),`dynamic`))}function fr(e){return nr(e)}function pr(e){return rr(e,`dynamic`)}function mr(e){let t=e.find(e=>e.keyword===`Description`),n=t&&{source:{type:`exifImageDescription`},data:`\0\0\0\0${t.text}`},r=hr(e);return[n,{source:{type:`exifUserComment`},data:JSON.stringify(r)}].filter(e=>e!==void 0)}function hr(e){return Object.fromEntries(gr.flatMap(t=>{let n=e.find(e=>e.keyword===t);return n?[[t,n.text]]:[]}))}let gr=[`Comment`,`Description`,`Generation time`,`Software`,`Source`,`Title`];function _r(e){return vr(r(e,`exifUserComment`),r(e,`exifImageDescription`))}function vr(e,n){if(!e||!n)return[];let r=L(e.data);if(!r.ok||r.type!==`object`)return t(`Comment`,e.data);let a=r.value,o=yr(n,i(a.Description));return[t(`Title`,i(a.Title)??`NovelAI generated image`),c(`Description`,o,`dynamic`),t(`Software`,i(a.Software)??`NovelAI`),t(`Source`,i(a.Source)),t(`Generation time`,i(a[`Generation time`])),t(`Comment`,i(a.Comment))].flat()}function yr(e,t){if(e?.data){let t=e.data;return t.startsWith(`\0\0\0\0`)?t.slice(4):t}if(t)return t.startsWith(`\0\0\0\0`)?t.slice(4):t}function X(e){return t=>{let n=t.find(t=>t.keyword===e);return n?[{source:{type:`exifUserComment`},data:n.text}]:[]}}function Z(e,t){return n=>{let r=n.find(e=>e.source.type===`exifUserComment`);return r?c(e,r.data,t):[]}}let br={parameters:`text-utf8-raw`,default:`text-unicode-escape`};function xr(e){let t={};for(let n of e){let e=L(n.text);t[n.keyword]=e.ok?e.value:n.text}return[{source:{type:`exifUserComment`},data:JSON.stringify(t)}]}function Sr(e){let t=r(e,`exifUserComment`);if(!t)return[];let n=L(t.data);if(!n.ok||n.type!==`object`)return[];let a=n.value;return l(Object.entries(a).map(([e,t])=>{let n=i(t);return[e,n===void 0?void 0:o(n)]}),br)}function Cr(e){let t=e.find(e=>e.keyword===`parameters`);if(!t)return[];let n=L(t.text),r=[{source:{type:`exifUserComment`},data:n.ok?JSON.stringify(n.value):t.text}],i=e.find(e=>e.keyword===`prompt`);return i&&r.push({source:{type:`exifMake`},data:i.text}),r}function wr(e){let t=r(e,`exifUserComment`);return[c(`prompt`,r(e,`exifMake`)?.data,`text-unicode-escape`),c(`parameters`,t?.data,`text-unicode-escape`)].flat()}let Tr={generation_data:`text-utf8-raw`,default:`text-unicode-escape`};function Er(e){let t={};for(let n of e){let e=L(n.text);t[n.keyword]=e.ok?e.value:n.text}return[{source:{type:`exifUserComment`},data:JSON.stringify(t)}]}function Dr(e){let t=r(e,`exifUserComment`);if(!t)return[];let n=L(t.data);if(!n.ok||n.type!==`object`)return[];let a=n.value;return l(Object.entries(a).map(([e,t])=>{let n=i(t);return[e,n===void 0?void 0:o(n)]}),Tr)}function Or(e,t){if(e.status===`empty`)return u.error({type:`missingRawData`});if(e.status===`invalid`)return u.error({type:`invalidParseResult`,status:e.status});if(e.status===`unrecognized`)return u.error({type:`unsupportedSoftware`,software:`unknown`});if(e.status===`c2pa`)return u.error({type:`invalidParseResult`,status:`c2pa`});let n=e.raw;if(n.format===t)return u.ok(n);let r=e.metadata.software,i=Br[r];return i?i(n,t):u.error({type:`unsupportedSoftware`,software:r})}function Q(e,t){return(n,r)=>{if(n.format===`png`){if(r===`png`)return u.ok(n);let t=e(n.chunks);return u.ok({format:r,segments:t})}if(r===`jpeg`||r===`webp`)return u.ok({format:r,segments:n.segments});let i=t(n.segments);return u.ok({format:`png`,chunks:i})}}let kr=Q(mr,_r),$=Q(Qn,$n),Ar=Q(ir,sr),jr=Q(ur,dr),Mr=Q(X(`parameters`),Z(`parameters`,`text-unicode-escape`)),Nr=Q(X(`parameters`),Z(`parameters`,`text-unicode-escape`)),Pr=Q(Cr,wr),Fr=Q(fr,pr),Ir=Q(X(`parameters`),Z(`parameters`,`text-unicode-escape`)),Lr=Q(cr,lr),Rr=Q(er,tr),zr=Q(xr,Sr),Br={novelai:kr,"sd-webui":$,"sd-next":$,forge:$,"forge-classic":$,"forge-neo":$,reforge:$,"easy-reforge":$,civitai:Rr,comfyui:Ar,tensorart:Q(Er,Dr),"stability-matrix":zr,easydiffusion:jr,fooocus:Mr,"ruined-fooocus":Nr,swarmui:Pr,invokeai:Fr,"hf-space":Ir,"draw-things":Lr};function Vr(e,t){let n=d(e),r=h(n);if(!r)return{ok:!1,error:{type:`unsupportedFormat`}};if(t.status===`empty`){let e=Ur[r].writeEmpty(n,[]);return e.ok?{ok:!0,value:e.value}:{ok:!1,error:{type:`writeFailed`,message:e.error.type}}}if(t.status===`invalid`)return{ok:!1,error:{type:`writeFailed`,message:`Cannot write invalid metadata`}};if(t.status===`c2pa`)return{ok:!1,error:{type:`writeFailed`,message:`Cannot write Content Credentials (C2PA) metadata`}};if(t.status===`unrecognized`){if(t.raw.format===r)return Hr(n,r,t.raw);let e=Ur[r].writeEmpty(n,[]);return e.ok?{ok:!0,value:e.value,warning:{type:`metadataDropped`,reason:`unrecognizedCrossFormat`}}:{ok:!1,error:{type:`writeFailed`,message:e.error.type}}}let i=Or(t,r);return i.ok?Hr(n,r,i.value):{ok:!1,error:{type:`conversionFailed`,message:`Failed to convert metadata: ${i.error.type}`}}}function Hr(e,t,n){if(t===`png`&&n.format===`png`){let t=A(e,n.chunks);return t.ok?{ok:!0,value:t.value}:{ok:!1,error:{type:`writeFailed`,message:t.error.type}}}if(t===`jpeg`&&n.format===`jpeg`){let t=O(e,n.segments);return t.ok?{ok:!0,value:t.value}:{ok:!1,error:{type:`writeFailed`,message:t.error.type}}}if(t===`webp`&&n.format===`webp`){let t=ke(e,n.segments);return t.ok?{ok:!0,value:t.value}:{ok:!1,error:{type:`writeFailed`,message:t.error.type}}}return{ok:!1,error:{type:`writeFailed`,message:`Internal error: format mismatch after conversion`}}}let Ur={png:{writeEmpty:A},jpeg:{writeEmpty:O},webp:{writeEmpty:ke}},Wr=Object.freeze({novelai:`NovelAI`,comfyui:`ComfyUI`,swarmui:`SwarmUI`,tensorart:`TensorArt`,"stability-matrix":`Stability Matrix`,invokeai:`InvokeAI`,"sd-webui":`Stable Diffusion WebUI`,forge:`Forge`,"forge-classic":`Forge - Classic`,"forge-neo":`Forge - Neo`,reforge:`reForge`,"easy-reforge":`EasyReforge`,"sd-next":`SD.Next`,civitai:`Civitai`,"hf-space":`Hugging Face Space`,easydiffusion:`Easy Diffusion`,fooocus:`Fooocus`,"ruined-fooocus":`Ruined Fooocus`,"draw-things":`Draw Things`});return e.c2paVendorLabels=Object.freeze({openai:`OpenAI (ChatGPT)`,google:`Google (Gemini)`,unknown:`AI-generated (Content Credentials)`}),e.embed=Re,e.writeAsWebUI=Re,e.formatAsWebUI=N,e.formatRaw=Ie,e.read=Xn,e.softwareLabels=Wr,e.stringify=Le,e.write=Vr,e})({});
package/dist/index.js CHANGED
@@ -318,9 +318,29 @@ function extractSimpleElement(xmp, ns, field) {
318
318
  * </ns:field>
319
319
  */
320
320
  function extractAltElement(xmp, ns, field) {
321
- const pattern = new RegExp(`<${ns}:${field}>[\\s\\S]*?<rdf:li[^>]*(?<!/)>([\\s\\S]*?)</rdf:li>[\\s\\S]*?</${ns}:${field}>`);
322
- const match = xmp.match(pattern);
323
- return match?.[1] ? decodeXmlEntities(match[1]) : void 0;
321
+ const openTag = `<${ns}:${field}>`;
322
+ const closeTag = `</${ns}:${field}>`;
323
+ const start = xmp.indexOf(openTag);
324
+ if (start === -1) return void 0;
325
+ const end = xmp.indexOf(closeTag, start);
326
+ if (end === -1) return void 0;
327
+ const inner = xmp.slice(start + openTag.length, end);
328
+ let pos = 0;
329
+ while (pos < inner.length) {
330
+ const liStart = inner.indexOf("<rdf:li", pos);
331
+ if (liStart === -1) return void 0;
332
+ const tagEnd = inner.indexOf(">", liStart);
333
+ if (tagEnd === -1) return void 0;
334
+ if (inner[tagEnd - 1] === "/") {
335
+ pos = tagEnd + 1;
336
+ continue;
337
+ }
338
+ const contentStart = tagEnd + 1;
339
+ const liClose = inner.indexOf("</rdf:li>", contentStart);
340
+ if (liClose === -1) return void 0;
341
+ const content = inner.slice(contentStart, liClose);
342
+ return content ? decodeXmlEntities(content) : void 0;
343
+ }
324
344
  }
325
345
  /**
326
346
  * Decode XML character entities to their string equivalents
@@ -1088,6 +1108,7 @@ function formatRaw(raw) {
1088
1108
  function stringify(input) {
1089
1109
  if ("status" in input) switch (input.status) {
1090
1110
  case "success": return buildEmbedText(input.metadata);
1111
+ case "c2pa": return input.c2pa.claimGenerator ?? "";
1091
1112
  case "unrecognized": return formatRaw(input.raw);
1092
1113
  case "empty":
1093
1114
  case "invalid": return "";
@@ -2962,6 +2983,173 @@ function parseMetadata(entries) {
2962
2983
  }
2963
2984
  }
2964
2985
  //#endregion
2986
+ //#region src/parsers/c2pa.ts
2987
+ const PNG_SIGNATURE_LENGTH$1 = 8;
2988
+ /** Maximum claim-generator length we will read (defensive cap on malformed input). */
2989
+ const MAX_CLAIM_GENERATOR_LENGTH = 4096;
2990
+ /**
2991
+ * Maximum caBX chunk bytes scanned. Real Content Credentials manifests are far
2992
+ * smaller, and every detection marker sits near the start of the uncompressed
2993
+ * box, so clamping bounds memory use against a maliciously oversized chunk.
2994
+ */
2995
+ const MAX_CABX_SCAN_LENGTH = 8 * 1024 * 1024;
2996
+ /** How far past `claim_generator_info` to look for its `name` value. */
2997
+ const CLAIM_GENERATOR_SCAN_WINDOW = 256;
2998
+ /**
2999
+ * IPTC DigitalSourceType concept-ids that mean "made by a trained AI model".
3000
+ *
3001
+ * Matched exactly (never by URI prefix) so camera/scan source types such as
3002
+ * `digitalCapture` are not mistaken for AI generation.
3003
+ */
3004
+ const AI_DIGITAL_SOURCE_TYPES = new Set([
3005
+ "trainedAlgorithmicMedia",
3006
+ "compositeWithTrainedAlgorithmicMedia",
3007
+ "algorithmicMedia",
3008
+ "compositeSynthetic"
3009
+ ]);
3010
+ /**
3011
+ * Captures the full IPTC DigitalSourceType URI and its trailing concept-id.
3012
+ * Global: a manifest can carry several DigitalSourceType-shaped tokens (e.g. an
3013
+ * assertion label), so callers iterate and prefer an allowlisted concept-id.
3014
+ */
3015
+ const DIGITAL_SOURCE_TYPE_RE = /https?:\/\/cv\.iptc\.org\/newscodes\/digitalsourcetype\/([A-Za-z]+)/g;
3016
+ /**
3017
+ * Stable manifest substrings mapped to a coarse vendor.
3018
+ *
3019
+ * Kept as data so a new C2PA-signing vendor is a one-line addition. Order
3020
+ * matters only in that the first match wins; the markers are vendor-exclusive.
3021
+ */
3022
+ const VENDOR_MARKERS = [
3023
+ {
3024
+ marker: "OpenAI Media Service API",
3025
+ vendor: "openai"
3026
+ },
3027
+ {
3028
+ marker: "Google LLC",
3029
+ vendor: "google"
3030
+ },
3031
+ {
3032
+ marker: "Google C2PA",
3033
+ vendor: "google"
3034
+ },
3035
+ {
3036
+ marker: "Google Media Processing Services",
3037
+ vendor: "google"
3038
+ }
3039
+ ];
3040
+ /**
3041
+ * Detect C2PA Content Credentials in an image.
3042
+ *
3043
+ * @param data - Full image bytes
3044
+ * @param format - Detected image format
3045
+ * @returns C2paMetadata when a manifest is found, otherwise `null`
3046
+ */
3047
+ function detectC2pa(data, format) {
3048
+ const manifest = extractManifest(data, format);
3049
+ if (!manifest) return null;
3050
+ const text = latin1Decode$1(manifest);
3051
+ const dstMatches = [...text.matchAll(DIGITAL_SOURCE_TYPE_RE)];
3052
+ const aiMatch = dstMatches.find((m) => AI_DIGITAL_SOURCE_TYPES.has(m[1] ?? ""));
3053
+ const digitalSourceType = (aiMatch ?? dstMatches[0])?.[0];
3054
+ const aiGenerated = aiMatch !== void 0;
3055
+ const vendor = VENDOR_MARKERS.find(({ marker }) => text.includes(marker))?.vendor ?? "unknown";
3056
+ const claimGenerator = extractClaimGenerator(manifest, text);
3057
+ return {
3058
+ vendor,
3059
+ aiGenerated,
3060
+ ...digitalSourceType ? { digitalSourceType } : {},
3061
+ ...claimGenerator ? { claimGenerator } : {}
3062
+ };
3063
+ }
3064
+ /**
3065
+ * Extract the raw C2PA manifest bytes for the given format.
3066
+ *
3067
+ * Only PNG (`caBX` chunk) is supported today. JPEG (APP11/JUMBF) and WebP
3068
+ * (RIFF `C2PA` chunk) are deferred until real sample images are available.
3069
+ */
3070
+ function extractManifest(data, format) {
3071
+ if (format === "png") return extractPngCaBX(data);
3072
+ return null;
3073
+ }
3074
+ /**
3075
+ * Find the PNG `caBX` ancillary chunk that holds the C2PA manifest store.
3076
+ */
3077
+ function extractPngCaBX(data) {
3078
+ let offset = PNG_SIGNATURE_LENGTH$1;
3079
+ while (offset + 8 <= data.length) {
3080
+ const length = readUint32BE(data, offset);
3081
+ const chunkType = readChunkType(data, offset + 4);
3082
+ const dataStart = offset + 8;
3083
+ if (dataStart + length > data.length) return null;
3084
+ if (chunkType === "caBX") {
3085
+ const scanLength = Math.min(length, MAX_CABX_SCAN_LENGTH);
3086
+ return data.slice(dataStart, dataStart + scanLength);
3087
+ }
3088
+ if (chunkType === "IEND") return null;
3089
+ offset = dataStart + length + 4;
3090
+ }
3091
+ return null;
3092
+ }
3093
+ /**
3094
+ * Extract `claim_generator_info.name` from the manifest.
3095
+ *
3096
+ * Reads the single CBOR text string that follows the `name` key, without a full
3097
+ * CBOR decoder: locate the `claim_generator_info` marker, find the CBOR-encoded
3098
+ * `name` key after it, then read the length-prefixed text string value.
3099
+ */
3100
+ function extractClaimGenerator(manifest, text) {
3101
+ const cgiIndex = text.indexOf("claim_generator_info");
3102
+ if (cgiIndex < 0) return void 0;
3103
+ const windowEnd = Math.min(text.length, cgiIndex + CLAIM_GENERATOR_SCAN_WINDOW);
3104
+ for (let p = text.indexOf("dname", cgiIndex); p >= 0 && p < windowEnd; p = text.indexOf("dname", p + 1)) {
3105
+ const value = readCborTextString(manifest, p + 5);
3106
+ if (value) return value;
3107
+ }
3108
+ }
3109
+ /**
3110
+ * Read a single CBOR text string (major type 3) at `pos`.
3111
+ *
3112
+ * Handles inline (0-23), 1-byte, and 2-byte length encodings — enough for any
3113
+ * realistic generator name. Returns `null` for anything else.
3114
+ */
3115
+ function readCborTextString(bytes, pos) {
3116
+ const initial = bytes[pos];
3117
+ if (initial === void 0 || initial < 96 || initial > 123) return null;
3118
+ const header = readCborLength(bytes, pos, initial & 31);
3119
+ if (!header) return null;
3120
+ const { length, dataPos } = header;
3121
+ if (length < 0 || length > MAX_CLAIM_GENERATOR_LENGTH) return null;
3122
+ if (dataPos + length > bytes.length) return null;
3123
+ return new TextDecoder("utf-8").decode(bytes.slice(dataPos, dataPos + length));
3124
+ }
3125
+ /**
3126
+ * Resolve a CBOR major-type-3 length header into `{ length, dataPos }`.
3127
+ *
3128
+ * Handles inline (0-23), 1-byte (24), and 2-byte (25) length encodings; returns
3129
+ * `null` for 4/8-byte or indefinite lengths (not used by real generator names).
3130
+ */
3131
+ function readCborLength(bytes, pos, additional) {
3132
+ if (additional < 24) return {
3133
+ length: additional,
3134
+ dataPos: pos + 1
3135
+ };
3136
+ if (additional === 24) return {
3137
+ length: bytes[pos + 1] ?? -1,
3138
+ dataPos: pos + 2
3139
+ };
3140
+ if (additional === 25) return {
3141
+ length: (bytes[pos + 1] ?? 0) << 8 | (bytes[pos + 2] ?? 0),
3142
+ dataPos: pos + 3
3143
+ };
3144
+ return null;
3145
+ }
3146
+ /**
3147
+ * Decode bytes as Latin-1 (ISO-8859-1): a lossless 1:1 byte-to-char mapping.
3148
+ */
3149
+ function latin1Decode$1(data) {
3150
+ return new TextDecoder("iso-8859-1").decode(data);
3151
+ }
3152
+ //#endregion
2965
3153
  //#region src/readers/dimensions.ts
2966
3154
  /**
2967
3155
  * Read image dimensions from binary data based on format
@@ -2998,6 +3186,7 @@ function readJpegDimensions(data) {
2998
3186
  }
2999
3187
  const length = readUint16BE(data, offset + 2);
3000
3188
  if (marker >= 192 && marker <= 207 && marker !== 196 && marker !== 200 && marker !== 204) {
3189
+ if (offset + 9 > data.length) return null;
3001
3190
  const height = readUint16BE(data, offset + 5);
3002
3191
  return {
3003
3192
  width: readUint16BE(data, offset + 7),
@@ -3029,6 +3218,7 @@ function readWebpDimensions(data) {
3029
3218
  }
3030
3219
  if (chunkType === "VP8 ") {
3031
3220
  const start = offset + 8;
3221
+ if (start + 10 > data.length) return null;
3032
3222
  if (!(readUint24LE(data, start) & 1)) {
3033
3223
  if (data[start + 3] === 157 && data[start + 4] === 1 && data[start + 5] === 42) {
3034
3224
  const wRaw = readUint16(data, start + 6, true);
@@ -3041,6 +3231,7 @@ function readWebpDimensions(data) {
3041
3231
  }
3042
3232
  }
3043
3233
  if (chunkType === "VP8L") {
3234
+ if (offset + 13 > data.length) return null;
3044
3235
  if (data[offset + 8] === 47) {
3045
3236
  const bits = readUint32LE(data, offset + 9);
3046
3237
  return {
@@ -3729,25 +3920,34 @@ function read(input, options) {
3729
3920
  message: "Unknown image format"
3730
3921
  };
3731
3922
  const rawResult = readRawMetadata(data, format);
3732
- if (rawResult.status !== "success") return rawResult;
3733
- const raw = rawResult.raw;
3734
- const parseResult = parseMetadata(raw.format === "png" ? pngChunksToRecord(raw.chunks) : segmentsToRecord(raw.segments));
3735
- if (!parseResult.ok) return {
3736
- status: "unrecognized",
3737
- raw
3738
- };
3739
- const metadata = parseResult.value;
3740
- if (!options?.strict && (metadata.width === 0 || metadata.height === 0)) {
3741
- const dims = readImageDimensions(data, format);
3742
- if (dims) {
3743
- metadata.width = metadata.width || dims.width;
3744
- metadata.height = metadata.height || dims.height;
3923
+ if (rawResult.status === "invalid") return rawResult;
3924
+ if (rawResult.status === "success") {
3925
+ const { raw } = rawResult;
3926
+ const parseResult = parseMetadata(raw.format === "png" ? pngChunksToRecord(raw.chunks) : segmentsToRecord(raw.segments));
3927
+ if (parseResult.ok) {
3928
+ const metadata = parseResult.value;
3929
+ if (!options?.strict && (metadata.width === 0 || metadata.height === 0)) try {
3930
+ const dims = readImageDimensions(data, format);
3931
+ if (dims) {
3932
+ metadata.width = metadata.width || dims.width;
3933
+ metadata.height = metadata.height || dims.height;
3934
+ }
3935
+ } catch {}
3936
+ return {
3937
+ status: "success",
3938
+ metadata,
3939
+ raw
3940
+ };
3745
3941
  }
3746
3942
  }
3747
- return {
3748
- status: "success",
3749
- metadata,
3750
- raw
3943
+ const c2pa = detectC2pa(data, format);
3944
+ if (c2pa) return {
3945
+ status: "c2pa",
3946
+ c2pa
3947
+ };
3948
+ return rawResult.status === "empty" ? { status: "empty" } : {
3949
+ status: "unrecognized",
3950
+ raw: rawResult.raw
3751
3951
  };
3752
3952
  }
3753
3953
  /**
@@ -4313,6 +4513,10 @@ function convertMetadata(parseResult, targetFormat) {
4313
4513
  type: "unsupportedSoftware",
4314
4514
  software: "unknown"
4315
4515
  });
4516
+ if (parseResult.status === "c2pa") return Result.error({
4517
+ type: "invalidParseResult",
4518
+ status: "c2pa"
4519
+ });
4316
4520
  const raw = parseResult.raw;
4317
4521
  if (raw.format === targetFormat) return Result.ok(raw);
4318
4522
  const software = parseResult.metadata.software;
@@ -4435,6 +4639,13 @@ function write(input, metadata) {
4435
4639
  message: "Cannot write invalid metadata"
4436
4640
  }
4437
4641
  };
4642
+ if (metadata.status === "c2pa") return {
4643
+ ok: false,
4644
+ error: {
4645
+ type: "writeFailed",
4646
+ message: "Cannot write Content Credentials (C2PA) metadata"
4647
+ }
4648
+ };
4438
4649
  if (metadata.status === "unrecognized") {
4439
4650
  if (metadata.raw.format === targetFormat) return writeRaw(data, targetFormat, metadata.raw);
4440
4651
  const result = HELPERS[targetFormat].writeEmpty(data, []);
@@ -4561,7 +4772,26 @@ const softwareLabels = Object.freeze({
4561
4772
  "ruined-fooocus": "Ruined Fooocus",
4562
4773
  "draw-things": "Draw Things"
4563
4774
  });
4775
+ /**
4776
+ * Human-readable display labels for each C2PA Content Credentials vendor.
4777
+ *
4778
+ * @example
4779
+ * ```typescript
4780
+ * import { c2paVendorLabels } from '@enslo/sd-metadata';
4781
+ *
4782
+ * const result = read(imageData);
4783
+ * if (result.status === 'c2pa') {
4784
+ * console.log(c2paVendorLabels[result.c2pa.vendor]);
4785
+ * // => "OpenAI (ChatGPT)", "Google (Gemini)", ...
4786
+ * }
4787
+ * ```
4788
+ */
4789
+ const c2paVendorLabels = Object.freeze({
4790
+ openai: "OpenAI (ChatGPT)",
4791
+ google: "Google (Gemini)",
4792
+ unknown: "AI-generated (Content Credentials)"
4793
+ });
4564
4794
  //#endregion
4565
- export { embed, embed as writeAsWebUI, buildEmbedText as formatAsWebUI, formatRaw, read, softwareLabels, stringify, write };
4795
+ export { c2paVendorLabels, embed, embed as writeAsWebUI, buildEmbedText as formatAsWebUI, formatRaw, read, softwareLabels, stringify, write };
4566
4796
 
4567
4797
  //# sourceMappingURL=index.js.map