@copio/sdk 0.1.4 → 0.1.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (116) hide show
  1. package/THIRD_PARTY_NOTICES.md +34 -0
  2. package/dist/adapters/edge/index.js +2 -0
  3. package/dist/adapters/edge/index.js.map +7 -0
  4. package/dist/adapters/edge/null-edge-detector-adapter.js +2 -0
  5. package/dist/adapters/edge/null-edge-detector-adapter.js.map +7 -0
  6. package/dist/adapters/edge/scanic-wasm-adapter.js +2 -0
  7. package/dist/adapters/edge/scanic-wasm-adapter.js.map +7 -0
  8. package/dist/adapters/image/canvas2d-adapter.js +1 -1
  9. package/dist/adapters/image/index.js +1 -1
  10. package/dist/adapters/image/null-image-processor-adapter.js +1 -1
  11. package/dist/adapters/index.js +1 -1
  12. package/dist/adapters/indexeddb-adapter.js +1 -1
  13. package/dist/adapters/memory-adapter.js +1 -1
  14. package/dist/adapters/ocr/index.js +1 -1
  15. package/dist/adapters/ocr/null-ocr-adapter.js +1 -1
  16. package/dist/adapters/ocr/tesseract-wasm-adapter.js +1 -1
  17. package/dist/adapters/pdf/index.js +1 -1
  18. package/dist/adapters/pdf/null-pdf-adapter.js +1 -1
  19. package/dist/adapters/pdf/pdfkit-adapter.js +1 -1
  20. package/dist/adapters/storage/index.js +1 -1
  21. package/dist/adapters/storage/indexeddb-adapter.js +1 -1
  22. package/dist/adapters/storage/memory-adapter.js +1 -1
  23. package/dist/adapters/sync/index.js +1 -1
  24. package/dist/adapters/sync/null-sync-adapter.js +1 -1
  25. package/dist/adapters/sync/peerjs-adapter.js +1 -1
  26. package/dist/canvas-GKLGWNAJ.js +2 -0
  27. package/dist/cdn.js +189 -1409
  28. package/dist/chunk-25WAHT3G.js +2 -0
  29. package/dist/chunk-2VH2NPXW.js +175 -0
  30. package/dist/{chunk-DIU5BGU5.js → chunk-4D6GC55I.js} +2 -2
  31. package/dist/chunk-6QK7337A.js +2 -0
  32. package/dist/chunk-GLY5CGCY.js +2 -0
  33. package/dist/chunk-GU6OQMYK.js +4 -0
  34. package/dist/chunk-HCCNUPKB.js +2 -0
  35. package/dist/chunk-JIPKWRBK.js +2 -0
  36. package/dist/{chunk-GGERQ3CJ.js → chunk-NM4YYZYB.js} +3 -3
  37. package/dist/chunk-NNSM2I5L.js +2 -0
  38. package/dist/chunk-PBF7V4Z6.js +2 -0
  39. package/dist/chunk-PSGIWIRH.js +2 -0
  40. package/dist/chunk-Q3AWHANC.js +2 -0
  41. package/dist/chunk-R6Q4OXDG.js +2 -0
  42. package/dist/chunk-SZHKZARU.js +2 -0
  43. package/dist/{chunk-J7HWZNIP.js → chunk-T5CPA7B2.js} +2 -2
  44. package/dist/chunk-TK5N67RB.js +2 -0
  45. package/dist/chunk-V2D55DVU.js +1 -0
  46. package/dist/chunk-VPSUKD6F.js +2 -0
  47. package/dist/chunk-ZILTJGT2.js +2 -0
  48. package/dist/core.js +1 -1
  49. package/dist/custom-elements.json +2316 -135
  50. package/dist/export.js +1 -1
  51. package/dist/fs-Y7NMZRBK.js +2 -0
  52. package/dist/handoff-transport-7YFK4RYL.js +2 -0
  53. package/dist/handoff.js +2 -0
  54. package/dist/http-CYZIMVXQ.js +2 -0
  55. package/dist/https-OLG7KUSR.js +2 -0
  56. package/dist/index.js +11 -11
  57. package/dist/ocr.js +1 -1
  58. package/dist/path2d-HD3LU76S.js +2 -0
  59. package/dist/scanic-mlDetector-BCSVQYFV.js +2 -0
  60. package/dist/scanic-ort.wasm.min-MU4NYSP2.js +2 -0
  61. package/dist/scanner.js +3 -1396
  62. package/dist/sync.js +1 -1
  63. package/dist/types/js/adapters/edge/edge-detector-port.d.ts +183 -0
  64. package/dist/types/js/adapters/edge/index.d.ts +3 -0
  65. package/dist/types/js/adapters/edge/null-edge-detector-adapter.d.ts +35 -0
  66. package/dist/types/js/adapters/edge/scanic-wasm-adapter.d.ts +54 -0
  67. package/dist/types/js/adapters/storage/indexeddb-adapter.d.ts +11 -0
  68. package/dist/types/js/adapters/storage/memory-adapter.d.ts +11 -0
  69. package/dist/types/js/adapters/storage/opfs-adapter.d.ts +11 -0
  70. package/dist/types/js/adapters/storage/storage-port.d.ts +27 -0
  71. package/dist/types/js/services/doc-repository.d.ts +6 -1
  72. package/dist/types/js/services/handoff-crypto.d.ts +84 -0
  73. package/dist/types/js/services/handoff-session.d.ts +257 -0
  74. package/dist/types/js/services/handoff-transport.d.ts +51 -0
  75. package/dist/types/js/services/ice-servers.d.ts +33 -1
  76. package/dist/types/js/services/migration-runner.d.ts +100 -0
  77. package/dist/types/js/utils/perspective.d.ts +70 -0
  78. package/dist/types/js/utils/utils.d.ts +19 -1
  79. package/dist/types/sdk/core.d.ts +52 -6
  80. package/dist/types/sdk/elements.d.ts +2 -0
  81. package/dist/types/sdk/events.d.ts +42 -0
  82. package/dist/types/sdk/handoff-session.d.ts +4 -0
  83. package/dist/types/sdk/handoff-styles.d.ts +9 -0
  84. package/dist/types/sdk/handoff.d.ts +108 -0
  85. package/dist/types/sdk/index.d.ts +5 -1
  86. package/dist/types/sdk/models.d.ts +248 -1
  87. package/dist/types/sdk/scanner.d.ts +94 -1
  88. package/dist/types/sdk/styles.d.ts +1 -1
  89. package/dist/types/sdk/version.d.ts +1 -1
  90. package/dist/url-NYR4TEJV.js +2 -0
  91. package/package.json +9 -2
  92. package/sdk/core.js +219 -12
  93. package/sdk/events.js +14 -0
  94. package/sdk/handoff-session.js +26 -0
  95. package/sdk/handoff-styles.js +531 -0
  96. package/sdk/handoff.js +1079 -0
  97. package/sdk/index.js +38 -1
  98. package/sdk/models.js +116 -4
  99. package/sdk/scanner.js +1517 -151
  100. package/sdk/styles.js +297 -17
  101. package/sdk/version.js +1 -1
  102. package/dist/canvas-FAXPLPXN.js +0 -2
  103. package/dist/chunk-4C666HHU.js +0 -2
  104. package/dist/chunk-FFRDPFTS.js +0 -1395
  105. package/dist/chunk-FQRADJY6.js +0 -2
  106. package/dist/chunk-G5EUMLYT.js +0 -4
  107. package/dist/chunk-IBF5HCYT.js +0 -2
  108. package/dist/chunk-K4NR6OAC.js +0 -2
  109. package/dist/chunk-L4OVZN23.js +0 -2
  110. package/dist/chunk-MEE2NNYB.js +0 -2
  111. package/dist/chunk-WETG2JD7.js +0 -2
  112. package/dist/fs-HJ6WWW73.js +0 -2
  113. package/dist/http-FKJJMT2N.js +0 -2
  114. package/dist/https-MUBFLDZM.js +0 -2
  115. package/dist/path2d-QWN6DFCC.js +0 -2
  116. package/dist/url-ABJ6S2Y6.js +0 -2
@@ -1,2 +0,0 @@
1
- import{a as c}from"./chunk-DIU5BGU5.js";var a=class extends c{#e=new Map;#s=new Map;#n=new Set;constructor(){super()}async init(){return{kind:"memory",persistent:!1}}listDocsSync(){return Array.from(this.#e.values()).map(e=>({id:e.id,name:e.name,pages:Array.isArray(e.pages)?[...e.pages]:[]}))}async listDocs(){return this.listDocsSync()}getDocSync(e){let s=this.#e.get(e);return s?{id:s.id,name:s.name,pages:Array.isArray(s.pages)?[...s.pages]:[]}:null}async getDoc(e){return this.getDocSync(e)}async saveDoc(e,s){if(!e)throw new Error("Cannot save document without an ID");let t=[];if(Array.isArray(s.pages))t=[...s.pages];else if(typeof s.pages=="string")try{t=JSON.parse(s.pages)}catch{t=[]}this.#e.set(e,{id:e,name:s.name||"",pages:t}),this.#t()}async deleteDoc(e){this.#e.delete(e);let s=`${e}/`;for(let t of this.#s.keys())t.startsWith(s)&&this.#s.delete(t);this.#t()}async renameDoc(e,s){let t=this.#e.get(e);if(!t)throw new Error(`Document "${e}" not found`);t.name=s,this.#t()}async savePage(e,s,t){this.#s.set(`${e}/${s}`,t);let n=this.#e.get(e);if(n){let r=n.pages.findIndex(i=>i.id===s);if(r>=0)typeof t=="object"&&t!==null&&!(t instanceof Blob)?n.pages[r]={...n.pages[r],...t}:n.pages[r]={...n.pages[r],src:t};else{let i=typeof t=="object"&&t!==null&&!(t instanceof Blob)?{id:s,...t}:{id:s,src:t};n.pages.push(i)}}this.#t()}async getPage(e,s){if(this.#s.has(`${e}/${s}`))return this.#s.get(`${e}/${s}`);let t=this.#e.get(e);if(t){let n=t.pages.find(r=>r.id===s);if(n)return n.src??n}return null}async deletePage(e,s){this.#s.delete(`${e}/${s}`);let t=this.#e.get(e);t&&(t.pages=t.pages.filter(n=>n.id!==s)),this.#t()}subscribe(e){return this.#n.add(e),()=>{this.#n.delete(e)}}clear(){this.#e.clear(),this.#s.clear(),this.#t()}#t(){for(let e of this.#n)try{e()}catch(s){console.error("Error in MemoryStorageAdapter subscriber:",s)}}};export{a};
2
- //# sourceMappingURL=chunk-FQRADJY6.js.map
@@ -1,4 +0,0 @@
1
- import{a as Et}from"./chunk-ULTSZWZO.js";function c(s,t,e){return t in s?Object.defineProperty(s,t,{value:e,enumerable:!0,configurable:!0,writable:!0}):s[t]=e,s}var At=typeof self<"u"?self:global,q=typeof navigator<"u",me=q&&typeof HTMLImageElement>"u",Nt=!(typeof global>"u"||typeof process>"u"||!process.versions||!process.versions.node),It=At.Buffer,tt=At.BigInt,Ut=!!It,et=s=>Yt(s)?void 0:s,ye=s=>s!==void 0;function Yt(s){return s===void 0||(s instanceof Map?s.size===0:Object.values(s).filter(ye).length===0)}function m(s){let t=new Error(s);throw delete t.stack,t}function qt(s){return(s=(function(t){for(;t.endsWith("\0");)t=t.slice(0,-1);return t})(s).trim())===""?void 0:s}function zt(s){let t=(function(e){let i=0;return e.ifd0.enabled&&(i+=1024),e.exif.enabled&&(i+=2048),e.makerNote&&(i+=2048),e.userComment&&(i+=1024),e.gps.enabled&&(i+=512),e.interop.enabled&&(i+=100),e.ifd1.enabled&&(i+=1024),i+2048})(s);return s.jfif.enabled&&(t+=50),s.xmp.enabled&&(t+=2e4),s.iptc.enabled&&(t+=14e3),s.icc.enabled&&(t+=6e3),t}var yt=s=>String.fromCharCode.apply(null,s),Vt=typeof TextDecoder<"u"?new TextDecoder("utf-8"):void 0;function Zt(s){return Vt?Vt.decode(s):Ut?Buffer.from(s).toString("utf8"):decodeURIComponent(escape(yt(s)))}var O=class s{static from(t,e){return t instanceof this&&t.le===e?t:new s(t,void 0,void 0,e)}constructor(t,e=0,i,n){if(typeof n=="boolean"&&(this.le=n),Array.isArray(t)&&(t=new Uint8Array(t)),t===0)this.byteOffset=0,this.byteLength=0;else if(t instanceof ArrayBuffer){i===void 0&&(i=t.byteLength-e);let r=new DataView(t,e,i);this._swapDataView(r)}else if(t instanceof Uint8Array||t instanceof DataView||t instanceof s){i===void 0&&(i=t.byteLength-e),(e+=t.byteOffset)+i>t.byteOffset+t.byteLength&&m("Creating view outside of available memory in ArrayBuffer");let r=new DataView(t.buffer,e,i);this._swapDataView(r)}else if(typeof t=="number"){let r=new DataView(new ArrayBuffer(t));this._swapDataView(r)}else m("Invalid input argument for BufferView: "+t)}_swapArrayBuffer(t){this._swapDataView(new DataView(t))}_swapBuffer(t){this._swapDataView(new DataView(t.buffer,t.byteOffset,t.byteLength))}_swapDataView(t){this.dataView=t,this.buffer=t.buffer,this.byteOffset=t.byteOffset,this.byteLength=t.byteLength}_lengthToEnd(t){return this.byteLength-t}set(t,e,i=s){return t instanceof DataView||t instanceof s?t=new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t instanceof ArrayBuffer&&(t=new Uint8Array(t)),t instanceof Uint8Array||m("BufferView.set(): Invalid data argument."),this.toUint8().set(t,e),new i(this,e,t.byteLength)}subarray(t,e){return e=e||this._lengthToEnd(t),new s(this,t,e)}toUint8(){return new Uint8Array(this.buffer,this.byteOffset,this.byteLength)}getUint8Array(t,e){return new Uint8Array(this.buffer,this.byteOffset+t,e)}getString(t=0,e=this.byteLength){return Zt(this.getUint8Array(t,e))}getLatin1String(t=0,e=this.byteLength){let i=this.getUint8Array(t,e);return yt(i)}getUnicodeString(t=0,e=this.byteLength){let i=[];for(let n=0;n<e&&t+n<this.byteLength;n+=2)i.push(this.getUint16(t+n));return yt(i)}getInt8(t){return this.dataView.getInt8(t)}getUint8(t){return this.dataView.getUint8(t)}getInt16(t,e=this.le){return this.dataView.getInt16(t,e)}getInt32(t,e=this.le){return this.dataView.getInt32(t,e)}getUint16(t,e=this.le){return this.dataView.getUint16(t,e)}getUint32(t,e=this.le){return this.dataView.getUint32(t,e)}getFloat32(t,e=this.le){return this.dataView.getFloat32(t,e)}getFloat64(t,e=this.le){return this.dataView.getFloat64(t,e)}getFloat(t,e=this.le){return this.dataView.getFloat32(t,e)}getDouble(t,e=this.le){return this.dataView.getFloat64(t,e)}getUintBytes(t,e,i){switch(e){case 1:return this.getUint8(t,i);case 2:return this.getUint16(t,i);case 4:return this.getUint32(t,i);case 8:return this.getUint64&&this.getUint64(t,i)}}getUint(t,e,i){switch(e){case 8:return this.getUint8(t,i);case 16:return this.getUint16(t,i);case 32:return this.getUint32(t,i);case 64:return this.getUint64&&this.getUint64(t,i)}}toString(t){return this.dataView.toString(t,this.constructor.name)}ensureChunk(){}};function bt(s,t){m(`${s} '${t}' was not loaded, try using full build of exifr.`)}var Z=class extends Map{constructor(t){super(),this.kind=t}get(t,e){return this.has(t)||bt(this.kind,t),e&&(t in e||(function(i,n){m(`Unknown ${i} '${n}'.`)})(this.kind,t),e[t].enabled||bt(this.kind,t)),super.get(t)}keyList(){return Array.from(this.keys())}},z=new Z("file parser"),b=new Z("segment parser"),V=new Z("file reader"),Jt=At.fetch;function Rt(s,t){return(e=s).startsWith("data:")||e.length>1e4?St(s,t,"base64"):Nt&&s.includes("://")?wt(s,t,"url",G):Nt?St(s,t,"fs"):q?wt(s,t,"url",G):void m("Invalid input argument");var e}async function wt(s,t,e,i){return V.has(e)?St(s,t,e):i?(async function(n,r){let a=await r(n);return new O(a)})(s,i):void m(`Parser ${e} is not loaded`)}async function St(s,t,e){let i=new(V.get(e))(s,t);return await i.read(),i}var G=s=>Jt(s).then((t=>t.arrayBuffer())),H=s=>new Promise(((t,e)=>{let i=new FileReader;i.onloadend=()=>t(i.result||new ArrayBuffer),i.onerror=e,i.readAsArrayBuffer(s)})),kt=class extends Map{get tagKeys(){return this.allKeys||(this.allKeys=Array.from(this.keys())),this.allKeys}get tagValues(){return this.allValues||(this.allValues=Array.from(this.values())),this.allValues}};function k(s,t,e){let i=new kt;for(let[n,r]of e)i.set(n,r);if(Array.isArray(t))for(let n of t)s.set(n,i);else s.set(t,i);return i}function Bt(s,t,e){let i,n=s.get(t);for(i of e)n.set(i[0],i[1])}var C=new Map,$=new Map,N=new Map,D=["chunked","firstChunkSize","firstChunkSizeNode","firstChunkSizeBrowser","chunkSize","chunkLimit"],J=["jfif","xmp","icc","iptc","ihdr"],W=["tiff",...J],p=["ifd0","ifd1","exif","gps","interop"],F=[...W,...p],T=["makerNote","userComment"],Q=["translateKeys","translateValues","reviveValues","multiSegment"],E=[...Q,"sanitize","mergeOutput","silentErrors"],it=class{get translate(){return this.translateKeys||this.translateValues||this.reviveValues}},L=class extends it{get needed(){return this.enabled||this.deps.size>0}constructor(t,e,i,n){if(super(),c(this,"enabled",!1),c(this,"skip",new Set),c(this,"pick",new Set),c(this,"deps",new Set),c(this,"translateKeys",!1),c(this,"translateValues",!1),c(this,"reviveValues",!1),this.key=t,this.enabled=e,this.parse=this.enabled,this.applyInheritables(n),this.canBeFiltered=p.includes(t),this.canBeFiltered&&(this.dict=C.get(t)),i!==void 0)if(Array.isArray(i))this.parse=this.enabled=!0,this.canBeFiltered&&i.length>0&&this.translateTagSet(i,this.pick);else if(typeof i=="object"){if(this.enabled=!0,this.parse=i.parse!==!1,this.canBeFiltered){let{pick:r,skip:a}=i;r&&r.length>0&&this.translateTagSet(r,this.pick),a&&a.length>0&&this.translateTagSet(a,this.skip)}this.applyInheritables(i)}else i===!0||i===!1?this.parse=this.enabled=i:m(`Invalid options argument: ${i}`)}applyInheritables(t){let e,i;for(e of Q)i=t[e],i!==void 0&&(this[e]=i)}translateTagSet(t,e){if(this.dict){let i,n,{tagKeys:r,tagValues:a}=this.dict;for(i of t)typeof i=="string"?(n=a.indexOf(i),n===-1&&(n=r.indexOf(Number(i))),n!==-1&&e.add(Number(r[n]))):e.add(i)}else for(let i of t)e.add(i)}finalizeFilters(){!this.enabled&&this.deps.size>0?(this.enabled=!0,st(this.pick,this.deps)):this.enabled&&this.pick.size>0&&st(this.pick,this.deps)}},y={jfif:!1,tiff:!0,xmp:!1,icc:!1,iptc:!1,ifd0:!0,ifd1:!1,exif:!0,gps:!0,interop:!1,ihdr:void 0,makerNote:!1,userComment:!1,multiSegment:!1,skip:[],pick:[],translateKeys:!0,translateValues:!0,reviveValues:!0,sanitize:!0,mergeOutput:!0,silentErrors:!0,chunked:!0,firstChunkSize:void 0,firstChunkSizeNode:512,firstChunkSizeBrowser:65536,chunkSize:65536,chunkLimit:5},jt=new Map,I=class extends it{static useCached(t){let e=jt.get(t);return e!==void 0||(e=new this(t),jt.set(t,e)),e}constructor(t){super(),t===!0?this.setupFromTrue():t===void 0?this.setupFromUndefined():Array.isArray(t)?this.setupFromArray(t):typeof t=="object"?this.setupFromObject(t):m(`Invalid options argument ${t}`),this.firstChunkSize===void 0&&(this.firstChunkSize=q?this.firstChunkSizeBrowser:this.firstChunkSizeNode),this.mergeOutput&&(this.ifd1.enabled=!1),this.filterNestedSegmentTags(),this.traverseTiffDependencyTree(),this.checkLoadedPlugins()}setupFromUndefined(){let t;for(t of D)this[t]=y[t];for(t of E)this[t]=y[t];for(t of T)this[t]=y[t];for(t of F)this[t]=new L(t,y[t],void 0,this)}setupFromTrue(){let t;for(t of D)this[t]=y[t];for(t of E)this[t]=y[t];for(t of T)this[t]=!0;for(t of F)this[t]=new L(t,!0,void 0,this)}setupFromArray(t){let e;for(e of D)this[e]=y[e];for(e of E)this[e]=y[e];for(e of T)this[e]=y[e];for(e of F)this[e]=new L(e,!1,void 0,this);this.setupGlobalFilters(t,void 0,p)}setupFromObject(t){let e;for(e of(p.ifd0=p.ifd0||p.image,p.ifd1=p.ifd1||p.thumbnail,Object.assign(this,t),D))this[e]=gt(t[e],y[e]);for(e of E)this[e]=gt(t[e],y[e]);for(e of T)this[e]=gt(t[e],y[e]);for(e of W)this[e]=new L(e,y[e],t[e],this);for(e of p)this[e]=new L(e,y[e],t[e],this.tiff);this.setupGlobalFilters(t.pick,t.skip,p,F),t.tiff===!0?this.batchEnableWithBool(p,!0):t.tiff===!1?this.batchEnableWithUserValue(p,t):Array.isArray(t.tiff)?this.setupGlobalFilters(t.tiff,void 0,p):typeof t.tiff=="object"&&this.setupGlobalFilters(t.tiff.pick,t.tiff.skip,p)}batchEnableWithBool(t,e){for(let i of t)this[i].enabled=e}batchEnableWithUserValue(t,e){for(let i of t){let n=e[i];this[i].enabled=n!==!1&&n!==void 0}}setupGlobalFilters(t,e,i,n=i){if(t&&t.length){for(let a of n)this[a].enabled=!1;let r=Gt(t,i);for(let[a,o]of r)st(this[a].pick,o),this[a].enabled=!0}else if(e&&e.length){let r=Gt(e,i);for(let[a,o]of r)st(this[a].skip,o)}}filterNestedSegmentTags(){let{ifd0:t,exif:e,xmp:i,iptc:n,icc:r}=this;this.makerNote?e.deps.add(37500):e.skip.add(37500),this.userComment?e.deps.add(37510):e.skip.add(37510),i.enabled||t.skip.add(700),n.enabled||t.skip.add(33723),r.enabled||t.skip.add(34675)}traverseTiffDependencyTree(){let{ifd0:t,exif:e,gps:i,interop:n}=this;n.needed&&(e.deps.add(40965),t.deps.add(40965)),e.needed&&t.deps.add(34665),i.needed&&t.deps.add(34853),this.tiff.enabled=p.some((r=>this[r].enabled===!0))||this.makerNote||this.userComment;for(let r of p)this[r].finalizeFilters()}get onlyTiff(){return!J.map((t=>this[t].enabled)).some((t=>t===!0))&&this.tiff.enabled}checkLoadedPlugins(){for(let t of W)this[t].enabled&&!b.has(t)&&bt("segment parser",t)}};function Gt(s,t){let e,i,n,r,a=[];for(n of t){for(r of(e=C.get(n),i=[],e))(s.includes(r[0])||s.includes(r[1]))&&i.push(r[0]);i.length&&a.push([n,i])}return a}function gt(s,t){return s!==void 0?s:t!==void 0?t:void 0}function st(s,t){for(let e of t)s.add(e)}c(I,"default",y);var P=class{constructor(t){c(this,"parsers",{}),c(this,"output",{}),c(this,"errors",[]),c(this,"pushToErrors",(e=>this.errors.push(e))),this.options=I.useCached(t)}async read(t){this.file=await(function(e,i){return typeof e=="string"?Rt(e,i):q&&!me&&e instanceof HTMLImageElement?Rt(e.src,i):e instanceof Uint8Array||e instanceof ArrayBuffer||e instanceof DataView?new O(e):q&&e instanceof Blob?wt(e,i,"blob",H):void m("Invalid input argument")})(t,this.options)}setup(){if(this.fileParser)return;let{file:t}=this,e=t.getUint16(0);for(let[i,n]of z)if(n.canHandle(t,e))return this.fileParser=new n(this.options,this.file,this.parsers),t[i]=!0;this.file.close&&this.file.close(),m("Unknown file format")}async parse(){let{output:t,errors:e}=this;return this.setup(),this.options.silentErrors?(await this.executeParsers().catch(this.pushToErrors),e.push(...this.fileParser.errors)):await this.executeParsers(),this.file.close&&this.file.close(),this.options.silentErrors&&e.length>0&&(t.errors=e),et(t)}async executeParsers(){let{output:t}=this;await this.fileParser.parse();let e=Object.values(this.parsers).map((async i=>{let n=await i.parse();i.assignToOutput(t,n)}));this.options.silentErrors&&(e=e.map((i=>i.catch(this.pushToErrors)))),await Promise.all(e)}async extractThumbnail(){this.setup();let{options:t,file:e}=this,i=b.get("tiff",t);var n;if(e.tiff?n={start:0,type:"tiff"}:e.jpeg&&(n=await this.fileParser.getOrFindSegment("tiff")),n===void 0)return;let r=await this.fileParser.ensureSegmentChunk(n),a=this.parsers.tiff=new i(r,t,e),o=await a.extractThumbnail();return e.close&&e.close(),o}};async function Mt(s,t){let e=new P(t);return await e.read(s),e.parse()}var be=Object.freeze({__proto__:null,parse:Mt,Exifr:P,fileParsers:z,segmentParsers:b,fileReaders:V,tagKeys:C,tagValues:$,tagRevivers:N,createDictionary:k,extendDictionary:Bt,fetchUrlAsArrayBuffer:G,readBlobAsArrayBuffer:H,chunkedProps:D,otherSegments:J,segments:W,tiffBlocks:p,segmentsAndBlocks:F,tiffExtractables:T,inheritables:Q,allFormatters:E,Options:I}),nt=class{constructor(t,e,i){c(this,"errors",[]),c(this,"ensureSegmentChunk",(async n=>{let r=n.start,a=n.size||65536;if(this.file.chunked)if(this.file.available(r,a))n.chunk=this.file.subarray(r,a);else try{n.chunk=await this.file.readChunk(r,a)}catch(o){m(`Couldn't read segment: ${JSON.stringify(n)}. ${o.message}`)}else this.file.byteLength>r+a?n.chunk=this.file.subarray(r,a):n.size===void 0?n.chunk=this.file.subarray(r):m("Segment unreachable: "+JSON.stringify(n));return n.chunk})),this.extendOptions&&this.extendOptions(t),this.options=t,this.file=e,this.parsers=i}injectSegment(t,e){this.options[t].enabled&&this.createParser(t,e)}createParser(t,e){let i=new(b.get(t))(e,this.options,this.file);return this.parsers[t]=i}createParsers(t){for(let e of t){let{type:i,chunk:n}=e,r=this.options[i];if(r&&r.enabled){let a=this.parsers[i];a&&a.append||a||this.createParser(i,n)}}}async readSegments(t){let e=t.map(this.ensureSegmentChunk);await Promise.all(e)}},v=class{static findPosition(t,e){let i=t.getUint16(e+2)+2,n=typeof this.headerLength=="function"?this.headerLength(t,e,i):this.headerLength,r=e+n,a=i-n;return{offset:e,length:i,headerLength:n,start:r,size:a,end:r+a}}static parse(t,e={}){return new this(t,new I({[this.type]:e}),t).parse()}normalizeInput(t){return t instanceof O?t:new O(t)}constructor(t,e={},i){c(this,"errors",[]),c(this,"raw",new Map),c(this,"handleError",(n=>{if(!this.options.silentErrors)throw n;this.errors.push(n.message)})),this.chunk=this.normalizeInput(t),this.file=i,this.type=this.constructor.type,this.globalOptions=this.options=e,this.localOptions=e[this.type],this.canTranslate=this.localOptions&&this.localOptions.translate}translate(){this.canTranslate&&(this.translated=this.translateBlock(this.raw,this.type))}get output(){return this.translated?this.translated:this.raw?Object.fromEntries(this.raw):void 0}translateBlock(t,e){let i=N.get(e),n=$.get(e),r=C.get(e),a=this.options[e],o=a.reviveValues&&!!i,h=a.translateValues&&!!n,l=a.translateKeys&&!!r,u={};for(let[d,f]of t)o&&i.has(d)?f=i.get(d)(f):h&&n.has(d)&&(f=this.translateValue(f,n.get(d))),l&&r.has(d)&&(d=r.get(d)||d),u[d]=f;return u}translateValue(t,e){return e[t]||e.DEFAULT||t}assignToOutput(t,e){this.assignObjectToOutput(t,this.constructor.type,e)}assignObjectToOutput(t,e,i){if(this.globalOptions.mergeOutput)return Object.assign(t,i);t[e]?Object.assign(t[e],i):t[e]=i}};c(v,"headerLength",4),c(v,"type",void 0),c(v,"multiSegment",!1),c(v,"canHandle",(()=>!1));function we(s){return s===192||s===194||s===196||s===219||s===221||s===218||s===254}function Se(s){return s>=224&&s<=239}function ke(s,t,e){for(let[i,n]of b)if(n.canHandle(s,t,e))return i}var rt=class extends nt{constructor(...t){super(...t),c(this,"appSegments",[]),c(this,"jpegSegments",[]),c(this,"unknownSegments",[])}static canHandle(t,e){return e===65496}async parse(){await this.findAppSegments(),await this.readSegments(this.appSegments),this.mergeMultiSegments(),this.createParsers(this.mergedAppSegments||this.appSegments)}setupSegmentFinderArgs(t){t===!0?(this.findAll=!0,this.wanted=new Set(b.keyList())):(t=t===void 0?b.keyList().filter((e=>this.options[e].enabled)):t.filter((e=>this.options[e].enabled&&b.has(e))),this.findAll=!1,this.remaining=new Set(t),this.wanted=new Set(t)),this.unfinishedMultiSegment=!1}async findAppSegments(t=0,e){this.setupSegmentFinderArgs(e);let{file:i,findAll:n,wanted:r,remaining:a}=this;if(!n&&this.file.chunked&&(n=Array.from(r).some((o=>{let h=b.get(o),l=this.options[o];return h.multiSegment&&l.multiSegment})),n&&await this.file.readWhole()),t=this.findAppSegmentsInRange(t,i.byteLength),!this.options.onlyTiff&&i.chunked){let o=!1;for(;a.size>0&&!o&&(i.canReadNextChunk||this.unfinishedMultiSegment);){let{nextChunkOffset:h}=i,l=this.appSegments.some((u=>!this.file.available(u.offset||u.start,u.length||u.size)));if(o=t>h&&!l?!await i.readNextChunk(t):!await i.readNextChunk(h),(t=this.findAppSegmentsInRange(t,i.byteLength))===void 0)return}}}findAppSegmentsInRange(t,e){e-=2;let i,n,r,a,o,h,{file:l,findAll:u,wanted:d,remaining:f,options:g}=this;for(;t<e;t++)if(l.getUint8(t)===255){if(i=l.getUint8(t+1),Se(i)){if(n=l.getUint16(t+2),r=ke(l,t,n),r&&d.has(r)&&(a=b.get(r),o=a.findPosition(l,t),h=g[r],o.type=r,this.appSegments.push(o),!u&&(a.multiSegment&&h.multiSegment?(this.unfinishedMultiSegment=o.chunkNumber<o.chunkCount,this.unfinishedMultiSegment||f.delete(r)):f.delete(r),f.size===0)))break;g.recordUnknownSegments&&(o=v.findPosition(l,t),o.marker=i,this.unknownSegments.push(o)),t+=n+1}else if(we(i)){if(n=l.getUint16(t+2),i===218&&g.stopAfterSos!==!1)return;g.recordJpegSegments&&this.jpegSegments.push({offset:t,length:n,marker:i}),t+=n+1}}return t}mergeMultiSegments(){if(!this.appSegments.some((e=>e.multiSegment)))return;let t=(function(e,i){let n,r,a,o=new Map;for(let h=0;h<e.length;h++)n=e[h],r=n[i],o.has(r)?a=o.get(r):o.set(r,a=[]),a.push(n);return Array.from(o)})(this.appSegments,"type");this.mergedAppSegments=t.map((([e,i])=>{let n=b.get(e,this.options);return n.handleMultiSegments?{type:e,chunk:n.handleMultiSegments(i)}:i[0]}))}getSegment(t){return this.appSegments.find((e=>e.type===t))}async getOrFindSegment(t){let e=this.getSegment(t);return e===void 0&&(await this.findAppSegments(0,[t]),e=this.getSegment(t)),e}};c(rt,"type","jpeg"),z.set("jpeg",rt);var xe=[void 0,1,1,2,4,8,1,1,2,4,8,4,8,4],xt=class extends v{parseHeader(){var t=this.chunk.getUint16();t===18761?this.le=!0:t===19789&&(this.le=!1),this.chunk.le=this.le,this.headerParsed=!0}parseTags(t,e,i=new Map){let{pick:n,skip:r}=this.options[e];n=new Set(n);let a=n.size>0,o=r.size===0,h=this.chunk.getUint16(t);t+=2;for(let l=0;l<h;l++){let u=this.chunk.getUint16(t);if(a){if(n.has(u)&&(i.set(u,this.parseTag(t,u,e)),n.delete(u),n.size===0))break}else!o&&r.has(u)||i.set(u,this.parseTag(t,u,e));t+=12}return i}parseTag(t,e,i){let{chunk:n}=this,r=n.getUint16(t+2),a=n.getUint32(t+4),o=xe[r];if(o*a<=4?t+=8:t=n.getUint32(t+8),(r<1||r>13)&&m(`Invalid TIFF value type. block: ${i.toUpperCase()}, tag: ${e.toString(16)}, type: ${r}, offset ${t}`),t>n.byteLength&&m(`Invalid TIFF value offset. block: ${i.toUpperCase()}, tag: ${e.toString(16)}, type: ${r}, offset ${t} is outside of chunk size ${n.byteLength}`),r===1)return n.getUint8Array(t,a);if(r===2)return qt(n.getString(t,a));if(r===7)return n.getUint8Array(t,a);if(a===1)return this.parseTagValue(r,t);{let h=new((function(u){switch(u){case 1:return Uint8Array;case 3:return Uint16Array;case 4:return Uint32Array;case 5:return Array;case 6:return Int8Array;case 8:return Int16Array;case 9:return Int32Array;case 10:return Array;case 11:return Float32Array;case 12:return Float64Array;default:return Array}})(r))(a),l=o;for(let u=0;u<a;u++)h[u]=this.parseTagValue(r,t),t+=l;return h}}parseTagValue(t,e){let{chunk:i}=this;switch(t){case 1:return i.getUint8(e);case 3:return i.getUint16(e);case 4:return i.getUint32(e);case 5:return i.getUint32(e)/i.getUint32(e+4);case 6:return i.getInt8(e);case 8:return i.getInt16(e);case 9:return i.getInt32(e);case 10:return i.getInt32(e)/i.getInt32(e+4);case 11:return i.getFloat(e);case 12:return i.getDouble(e);case 13:return i.getUint32(e);default:m(`Invalid tiff type ${t}`)}}},X=class extends xt{static canHandle(t,e){return t.getUint8(e+1)===225&&t.getUint32(e+4)===1165519206&&t.getUint16(e+8)===0}async parse(){this.parseHeader();let{options:t}=this;return t.ifd0.enabled&&await this.parseIfd0Block(),t.exif.enabled&&await this.safeParse("parseExifBlock"),t.gps.enabled&&await this.safeParse("parseGpsBlock"),t.interop.enabled&&await this.safeParse("parseInteropBlock"),t.ifd1.enabled&&await this.safeParse("parseThumbnailBlock"),this.createOutput()}safeParse(t){let e=this[t]();return e.catch!==void 0&&(e=e.catch(this.handleError)),e}findIfd0Offset(){this.ifd0Offset===void 0&&(this.ifd0Offset=this.chunk.getUint32(4))}findIfd1Offset(){if(this.ifd1Offset===void 0){this.findIfd0Offset();let t=this.chunk.getUint16(this.ifd0Offset),e=this.ifd0Offset+2+12*t;this.ifd1Offset=this.chunk.getUint32(e)}}parseBlock(t,e){let i=new Map;return this[e]=i,this.parseTags(t,e,i),i}async parseIfd0Block(){if(this.ifd0)return;let{file:t}=this;this.findIfd0Offset(),this.ifd0Offset<8&&m("Malformed EXIF data"),!t.chunked&&this.ifd0Offset>t.byteLength&&m(`IFD0 offset points to outside of file.
2
- this.ifd0Offset: ${this.ifd0Offset}, file.byteLength: ${t.byteLength}`),t.tiff&&await t.ensureChunk(this.ifd0Offset,zt(this.options));let e=this.parseBlock(this.ifd0Offset,"ifd0");return e.size!==0?(this.exifOffset=e.get(34665),this.interopOffset=e.get(40965),this.gpsOffset=e.get(34853),this.xmp=e.get(700),this.iptc=e.get(33723),this.icc=e.get(34675),this.options.sanitize&&(e.delete(34665),e.delete(40965),e.delete(34853),e.delete(700),e.delete(33723),e.delete(34675)),e):void 0}async parseExifBlock(){if(this.exif||(this.ifd0||await this.parseIfd0Block(),this.exifOffset===void 0))return;this.file.tiff&&await this.file.ensureChunk(this.exifOffset,zt(this.options));let t=this.parseBlock(this.exifOffset,"exif");return this.interopOffset||(this.interopOffset=t.get(40965)),this.makerNote=t.get(37500),this.userComment=t.get(37510),this.options.sanitize&&(t.delete(40965),t.delete(37500),t.delete(37510)),this.unpack(t,41728),this.unpack(t,41729),t}unpack(t,e){let i=t.get(e);i&&i.length===1&&t.set(e,i[0])}async parseGpsBlock(){if(this.gps||(this.ifd0||await this.parseIfd0Block(),this.gpsOffset===void 0))return;let t=this.parseBlock(this.gpsOffset,"gps");return t&&t.has(2)&&t.has(4)&&(t.set("latitude",Ht(...t.get(2),t.get(1))),t.set("longitude",Ht(...t.get(4),t.get(3)))),t}async parseInteropBlock(){if(!this.interop&&(this.ifd0||await this.parseIfd0Block(),this.interopOffset!==void 0||this.exif||await this.parseExifBlock(),this.interopOffset!==void 0))return this.parseBlock(this.interopOffset,"interop")}async parseThumbnailBlock(t=!1){if(!this.ifd1&&!this.ifd1Parsed&&(!this.options.mergeOutput||t))return this.findIfd1Offset(),this.ifd1Offset>0&&(this.parseBlock(this.ifd1Offset,"ifd1"),this.ifd1Parsed=!0),this.ifd1}async extractThumbnail(){if(this.headerParsed||this.parseHeader(),this.ifd1Parsed||await this.parseThumbnailBlock(!0),this.ifd1===void 0)return;let t=this.ifd1.get(513),e=this.ifd1.get(514);return this.chunk.getUint8Array(t,e)}get image(){return this.ifd0}get thumbnail(){return this.ifd1}createOutput(){let t,e,i,n={};for(e of p)if(t=this[e],!Yt(t))if(i=this.canTranslate?this.translateBlock(t,e):Object.fromEntries(t),this.options.mergeOutput){if(e==="ifd1")continue;Object.assign(n,i)}else n[e]=i;return this.makerNote&&(n.makerNote=this.makerNote),this.userComment&&(n.userComment=this.userComment),n}assignToOutput(t,e){if(this.globalOptions.mergeOutput)Object.assign(t,e);else for(let[i,n]of Object.entries(e))this.assignObjectToOutput(t,i,n)}};function Ht(s,t,e,i){var n=s+t/60+e/3600;return i!=="S"&&i!=="W"||(n*=-1),n}c(X,"type","tiff"),c(X,"headerLength",10),b.set("tiff",X);var ve=Object.freeze({__proto__:null,default:be,Exifr:P,fileParsers:z,segmentParsers:b,fileReaders:V,tagKeys:C,tagValues:$,tagRevivers:N,createDictionary:k,extendDictionary:Bt,fetchUrlAsArrayBuffer:G,readBlobAsArrayBuffer:H,chunkedProps:D,otherSegments:J,segments:W,tiffBlocks:p,segmentsAndBlocks:F,tiffExtractables:T,inheritables:Q,allFormatters:E,Options:I,parse:Mt}),Lt={ifd0:!1,ifd1:!1,exif:!1,gps:!1,interop:!1,sanitize:!1,reviveValues:!0,translateKeys:!1,translateValues:!1,mergeOutput:!1},Qt=Object.assign({},Lt,{firstChunkSize:4e4,gps:[1,2,3,4]});async function Ce(s){let t=new P(Qt);await t.read(s);let e=await t.parse();if(e&&e.gps){let{latitude:i,longitude:n}=e.gps;return{latitude:i,longitude:n}}}var te=Object.assign({},Lt,{tiff:!1,ifd1:!0,mergeOutput:!1});async function Oe(s){let t=new P(te);await t.read(s);let e=await t.extractThumbnail();return e&&Ut?It.from(e):e}async function Pe(s){let t=await this.thumbnail(s);if(t!==void 0){let e=new Blob([t]);return URL.createObjectURL(e)}}var ee=Object.assign({},Lt,{firstChunkSize:4e4,ifd0:[274]});async function ie(s){let t=new P(ee);await t.read(s);let e=await t.parse();if(e&&e.ifd0)return e.ifd0[274]}var se=Object.freeze({1:{dimensionSwapped:!1,scaleX:1,scaleY:1,deg:0,rad:0},2:{dimensionSwapped:!1,scaleX:-1,scaleY:1,deg:0,rad:0},3:{dimensionSwapped:!1,scaleX:1,scaleY:1,deg:180,rad:180*Math.PI/180},4:{dimensionSwapped:!1,scaleX:-1,scaleY:1,deg:180,rad:180*Math.PI/180},5:{dimensionSwapped:!0,scaleX:1,scaleY:-1,deg:90,rad:90*Math.PI/180},6:{dimensionSwapped:!0,scaleX:1,scaleY:1,deg:90,rad:90*Math.PI/180},7:{dimensionSwapped:!0,scaleX:1,scaleY:-1,deg:270,rad:270*Math.PI/180},8:{dimensionSwapped:!0,scaleX:1,scaleY:1,deg:270,rad:270*Math.PI/180}}),R=!0,j=!0;if(typeof navigator=="object"){let s=navigator.userAgent;if(s.includes("iPad")||s.includes("iPhone")){let t=s.match(/OS (\d+)_(\d+)/);if(t){let[,e,i]=t;R=Number(e)+.1*Number(i)<13.4,j=!1}}else if(s.includes("OS X 10")){let[,t]=s.match(/OS X 10[_.](\d+)/);R=j=Number(t)<15}if(s.includes("Chrome/")){let[,t]=s.match(/Chrome\/(\d+)/);R=j=Number(t)<81}else if(s.includes("Firefox/")){let[,t]=s.match(/Firefox\/(\d+)/);R=j=Number(t)<77}}async function Ae(s){let t=await ie(s);return Object.assign({canvas:R,css:j},se[t])}var vt=class extends O{constructor(...t){super(...t),c(this,"ranges",new Ct),this.byteLength!==0&&this.ranges.add(0,this.byteLength)}_tryExtend(t,e,i){if(t===0&&this.byteLength===0&&i){let n=new DataView(i.buffer||i,i.byteOffset,i.byteLength);this._swapDataView(n)}else{let n=t+e;if(n>this.byteLength){let{dataView:r}=this._extend(n);this._swapDataView(r)}}}_extend(t){let e;e=Ut?It.allocUnsafe(t):new Uint8Array(t);let i=new DataView(e.buffer,e.byteOffset,e.byteLength);return e.set(new Uint8Array(this.buffer,this.byteOffset,this.byteLength),0),{uintView:e,dataView:i}}subarray(t,e,i=!1){return e=e||this._lengthToEnd(t),i&&this._tryExtend(t,e),this.ranges.add(t,e),super.subarray(t,e)}set(t,e,i=!1){i&&this._tryExtend(e,t.byteLength,t);let n=super.set(t,e);return this.ranges.add(e,n.byteLength),n}async ensureChunk(t,e){this.chunked&&(this.ranges.available(t,e)||await this.readChunk(t,e))}available(t,e){return this.ranges.available(t,e)}},Ct=class{constructor(){c(this,"list",[])}get length(){return this.list.length}add(t,e,i=0){let n=t+e,r=this.list.filter((a=>Wt(t,a.offset,n)||Wt(t,a.end,n)));if(r.length>0){t=Math.min(t,...r.map((o=>o.offset))),n=Math.max(n,...r.map((o=>o.end))),e=n-t;let a=r.shift();a.offset=t,a.length=e,a.end=n,this.list=this.list.filter((o=>!r.includes(o)))}else this.list.push({offset:t,length:e,end:n})}available(t,e){let i=t+e;return this.list.some((n=>n.offset<=t&&i<=n.end))}};function Wt(s,t,e){return s<=t&&t<=e}var at=class extends vt{constructor(t,e){super(0),c(this,"chunksRead",0),this.input=t,this.options=e}async readWhole(){this.chunked=!1,await this.readChunk(this.nextChunkOffset)}async readChunked(){this.chunked=!0,await this.readChunk(0,this.options.firstChunkSize)}async readNextChunk(t=this.nextChunkOffset){if(this.fullyRead)return this.chunksRead++,!1;let e=this.options.chunkSize,i=await this.readChunk(t,e);return!!i&&i.byteLength===e}async readChunk(t,e){if(this.chunksRead++,(e=this.safeWrapAddress(t,e))!==0)return this._readChunk(t,e)}safeWrapAddress(t,e){return this.size!==void 0&&t+e>this.size?Math.max(0,this.size-t):e}get nextChunkOffset(){if(this.ranges.list.length!==0)return this.ranges.list[0].length}get canReadNextChunk(){return this.chunksRead<this.options.chunkLimit}get fullyRead(){return this.size!==void 0&&this.nextChunkOffset===this.size}read(){return this.options.chunked?this.readChunked():this.readWhole()}close(){}};V.set("blob",class extends at{async readWhole(){this.chunked=!1;let s=await H(this.input);this._swapArrayBuffer(s)}readChunked(){return this.chunked=!0,this.size=this.input.size,super.readChunked()}async _readChunk(s,t){let e=t?s+t:void 0,i=this.input.slice(s,e),n=await H(i);return this.set(n,s,!0)}});var Ie=Object.freeze({__proto__:null,default:ve,Exifr:P,fileParsers:z,segmentParsers:b,fileReaders:V,tagKeys:C,tagValues:$,tagRevivers:N,createDictionary:k,extendDictionary:Bt,fetchUrlAsArrayBuffer:G,readBlobAsArrayBuffer:H,chunkedProps:D,otherSegments:J,segments:W,tiffBlocks:p,segmentsAndBlocks:F,tiffExtractables:T,inheritables:Q,allFormatters:E,Options:I,parse:Mt,gpsOnlyOptions:Qt,gps:Ce,thumbnailOnlyOptions:te,thumbnail:Oe,thumbnailUrl:Pe,orientationOnlyOptions:ee,orientation:ie,rotations:se,get rotateCanvas(){return R},get rotateCss(){return j},rotation:Ae});V.set("url",class extends at{async readWhole(){this.chunked=!1;let s=await G(this.input);s instanceof ArrayBuffer?this._swapArrayBuffer(s):s instanceof Uint8Array&&this._swapBuffer(s)}async _readChunk(s,t){let e=t?s+t-1:void 0,i=this.options.httpHeaders||{};(s||e)&&(i.range=`bytes=${[s,e].join("-")}`);let n=await Jt(this.input,{headers:i}),r=await n.arrayBuffer(),a=r.byteLength;if(n.status!==416)return a!==t&&(this.size=s+a),this.set(r,s,!0)}});O.prototype.getUint64=function(s){let t=this.getUint32(s),e=this.getUint32(s+4);return t<1048575?t<<32|e:typeof tt!==void 0?(console.warn("Using BigInt because of type 64uint but JS can only handle 53b numbers."),tt(t)<<tt(32)|tt(e)):void m("Trying to read 64b value but JS can only handle 53b numbers.")};var Ot=class extends nt{parseBoxes(t=0){let e=[];for(;t<this.file.byteLength-4;){let i=this.parseBoxHead(t);if(e.push(i),i.length===0)break;t+=i.length}return e}parseSubBoxes(t){t.boxes=this.parseBoxes(t.start)}findBox(t,e){return t.boxes===void 0&&this.parseSubBoxes(t),t.boxes.find((i=>i.kind===e))}parseBoxHead(t){let e=this.file.getUint32(t),i=this.file.getString(t+4,4),n=t+8;return e===1&&(e=this.file.getUint64(t+8),n+=8),{offset:t,length:e,kind:i,start:n}}parseBoxFullHead(t){if(t.version!==void 0)return;let e=this.file.getUint32(t.start);t.version=e>>24,t.start+=4}},ot=class extends Ot{static canHandle(t,e){if(e!==0)return!1;let i=t.getUint16(2);if(i>50)return!1;let n=16,r=[];for(;n<i;)r.push(t.getString(n,4)),n+=4;return r.includes(this.type)}async parse(){let t=this.file.getUint32(0),e=this.parseBoxHead(t);for(;e.kind!=="meta";)t+=e.length,await this.file.ensureChunk(t,16),e=this.parseBoxHead(t);await this.file.ensureChunk(e.offset,e.length),this.parseBoxFullHead(e),this.parseSubBoxes(e),this.options.icc.enabled&&await this.findIcc(e),this.options.tiff.enabled&&await this.findExif(e)}async registerSegment(t,e,i){await this.file.ensureChunk(e,i);let n=this.file.subarray(e,i);this.createParser(t,n)}async findIcc(t){let e=this.findBox(t,"iprp");if(e===void 0)return;let i=this.findBox(e,"ipco");if(i===void 0)return;let n=this.findBox(i,"colr");n!==void 0&&await this.registerSegment("icc",n.offset+12,n.length)}async findExif(t){let e=this.findBox(t,"iinf");if(e===void 0)return;let i=this.findBox(t,"iloc");if(i===void 0)return;let n=this.findExifLocIdInIinf(e),r=this.findExtentInIloc(i,n);if(r===void 0)return;let[a,o]=r;await this.file.ensureChunk(a,o);let h=4+this.file.getUint32(a);a+=h,o-=h,await this.registerSegment("tiff",a,o)}findExifLocIdInIinf(t){this.parseBoxFullHead(t);let e,i,n,r,a=t.start,o=this.file.getUint16(a);for(a+=2;o--;){if(e=this.parseBoxHead(a),this.parseBoxFullHead(e),i=e.start,e.version>=2&&(n=e.version===3?4:2,r=this.file.getString(i+n+2,4),r==="Exif"))return this.file.getUintBytes(i,n);a+=e.length}}get8bits(t){let e=this.file.getUint8(t);return[e>>4,15&e]}findExtentInIloc(t,e){this.parseBoxFullHead(t);let i=t.start,[n,r]=this.get8bits(i++),[a,o]=this.get8bits(i++),h=t.version===2?4:2,l=t.version===1||t.version===2?2:0,u=o+n+r,d=t.version===2?4:2,f=this.file.getUintBytes(i,d);for(i+=d;f--;){let g=this.file.getUintBytes(i,h);i+=h+l+2+a;let S=this.file.getUint16(i);if(i+=2,g===e)return S>1&&console.warn(`ILOC box has more than one extent but we're only processing one
3
- Please create an issue at https://github.com/MikeKovarik/exifr with this file`),[this.file.getUintBytes(i+o,n),this.file.getUintBytes(i+o+n,r)];i+=S*u}}},ht=class extends ot{};c(ht,"type","heic");var lt=class extends ot{};c(lt,"type","avif"),z.set("heic",ht),z.set("avif",lt),k(C,["ifd0","ifd1"],[[256,"ImageWidth"],[257,"ImageHeight"],[258,"BitsPerSample"],[259,"Compression"],[262,"PhotometricInterpretation"],[270,"ImageDescription"],[271,"Make"],[272,"Model"],[273,"StripOffsets"],[274,"Orientation"],[277,"SamplesPerPixel"],[278,"RowsPerStrip"],[279,"StripByteCounts"],[282,"XResolution"],[283,"YResolution"],[284,"PlanarConfiguration"],[296,"ResolutionUnit"],[301,"TransferFunction"],[305,"Software"],[306,"ModifyDate"],[315,"Artist"],[316,"HostComputer"],[317,"Predictor"],[318,"WhitePoint"],[319,"PrimaryChromaticities"],[513,"ThumbnailOffset"],[514,"ThumbnailLength"],[529,"YCbCrCoefficients"],[530,"YCbCrSubSampling"],[531,"YCbCrPositioning"],[532,"ReferenceBlackWhite"],[700,"ApplicationNotes"],[33432,"Copyright"],[33723,"IPTC"],[34665,"ExifIFD"],[34675,"ICC"],[34853,"GpsIFD"],[330,"SubIFD"],[40965,"InteropIFD"],[40091,"XPTitle"],[40092,"XPComment"],[40093,"XPAuthor"],[40094,"XPKeywords"],[40095,"XPSubject"]]),k(C,"exif",[[33434,"ExposureTime"],[33437,"FNumber"],[34850,"ExposureProgram"],[34852,"SpectralSensitivity"],[34855,"ISO"],[34858,"TimeZoneOffset"],[34859,"SelfTimerMode"],[34864,"SensitivityType"],[34865,"StandardOutputSensitivity"],[34866,"RecommendedExposureIndex"],[34867,"ISOSpeed"],[34868,"ISOSpeedLatitudeyyy"],[34869,"ISOSpeedLatitudezzz"],[36864,"ExifVersion"],[36867,"DateTimeOriginal"],[36868,"CreateDate"],[36873,"GooglePlusUploadCode"],[36880,"OffsetTime"],[36881,"OffsetTimeOriginal"],[36882,"OffsetTimeDigitized"],[37121,"ComponentsConfiguration"],[37122,"CompressedBitsPerPixel"],[37377,"ShutterSpeedValue"],[37378,"ApertureValue"],[37379,"BrightnessValue"],[37380,"ExposureCompensation"],[37381,"MaxApertureValue"],[37382,"SubjectDistance"],[37383,"MeteringMode"],[37384,"LightSource"],[37385,"Flash"],[37386,"FocalLength"],[37393,"ImageNumber"],[37394,"SecurityClassification"],[37395,"ImageHistory"],[37396,"SubjectArea"],[37500,"MakerNote"],[37510,"UserComment"],[37520,"SubSecTime"],[37521,"SubSecTimeOriginal"],[37522,"SubSecTimeDigitized"],[37888,"AmbientTemperature"],[37889,"Humidity"],[37890,"Pressure"],[37891,"WaterDepth"],[37892,"Acceleration"],[37893,"CameraElevationAngle"],[40960,"FlashpixVersion"],[40961,"ColorSpace"],[40962,"ExifImageWidth"],[40963,"ExifImageHeight"],[40964,"RelatedSoundFile"],[41483,"FlashEnergy"],[41486,"FocalPlaneXResolution"],[41487,"FocalPlaneYResolution"],[41488,"FocalPlaneResolutionUnit"],[41492,"SubjectLocation"],[41493,"ExposureIndex"],[41495,"SensingMethod"],[41728,"FileSource"],[41729,"SceneType"],[41730,"CFAPattern"],[41985,"CustomRendered"],[41986,"ExposureMode"],[41987,"WhiteBalance"],[41988,"DigitalZoomRatio"],[41989,"FocalLengthIn35mmFormat"],[41990,"SceneCaptureType"],[41991,"GainControl"],[41992,"Contrast"],[41993,"Saturation"],[41994,"Sharpness"],[41996,"SubjectDistanceRange"],[42016,"ImageUniqueID"],[42032,"OwnerName"],[42033,"SerialNumber"],[42034,"LensInfo"],[42035,"LensMake"],[42036,"LensModel"],[42037,"LensSerialNumber"],[42080,"CompositeImage"],[42081,"CompositeImageCount"],[42082,"CompositeImageExposureTimes"],[42240,"Gamma"],[59932,"Padding"],[59933,"OffsetSchema"],[65e3,"OwnerName"],[65001,"SerialNumber"],[65002,"Lens"],[65100,"RawFile"],[65101,"Converter"],[65102,"WhiteBalance"],[65105,"Exposure"],[65106,"Shadows"],[65107,"Brightness"],[65108,"Contrast"],[65109,"Saturation"],[65110,"Sharpness"],[65111,"Smoothness"],[65112,"MoireFilter"],[40965,"InteropIFD"]]),k(C,"gps",[[0,"GPSVersionID"],[1,"GPSLatitudeRef"],[2,"GPSLatitude"],[3,"GPSLongitudeRef"],[4,"GPSLongitude"],[5,"GPSAltitudeRef"],[6,"GPSAltitude"],[7,"GPSTimeStamp"],[8,"GPSSatellites"],[9,"GPSStatus"],[10,"GPSMeasureMode"],[11,"GPSDOP"],[12,"GPSSpeedRef"],[13,"GPSSpeed"],[14,"GPSTrackRef"],[15,"GPSTrack"],[16,"GPSImgDirectionRef"],[17,"GPSImgDirection"],[18,"GPSMapDatum"],[19,"GPSDestLatitudeRef"],[20,"GPSDestLatitude"],[21,"GPSDestLongitudeRef"],[22,"GPSDestLongitude"],[23,"GPSDestBearingRef"],[24,"GPSDestBearing"],[25,"GPSDestDistanceRef"],[26,"GPSDestDistance"],[27,"GPSProcessingMethod"],[28,"GPSAreaInformation"],[29,"GPSDateStamp"],[30,"GPSDifferential"],[31,"GPSHPositioningError"]]),k($,["ifd0","ifd1"],[[274,{1:"Horizontal (normal)",2:"Mirror horizontal",3:"Rotate 180",4:"Mirror vertical",5:"Mirror horizontal and rotate 270 CW",6:"Rotate 90 CW",7:"Mirror horizontal and rotate 90 CW",8:"Rotate 270 CW"}],[296,{1:"None",2:"inches",3:"cm"}]]);var K=k($,"exif",[[34850,{0:"Not defined",1:"Manual",2:"Normal program",3:"Aperture priority",4:"Shutter priority",5:"Creative program",6:"Action program",7:"Portrait mode",8:"Landscape mode"}],[37121,{0:"-",1:"Y",2:"Cb",3:"Cr",4:"R",5:"G",6:"B"}],[37383,{0:"Unknown",1:"Average",2:"CenterWeightedAverage",3:"Spot",4:"MultiSpot",5:"Pattern",6:"Partial",255:"Other"}],[37384,{0:"Unknown",1:"Daylight",2:"Fluorescent",3:"Tungsten (incandescent light)",4:"Flash",9:"Fine weather",10:"Cloudy weather",11:"Shade",12:"Daylight fluorescent (D 5700 - 7100K)",13:"Day white fluorescent (N 4600 - 5400K)",14:"Cool white fluorescent (W 3900 - 4500K)",15:"White fluorescent (WW 3200 - 3700K)",17:"Standard light A",18:"Standard light B",19:"Standard light C",20:"D55",21:"D65",22:"D75",23:"D50",24:"ISO studio tungsten",255:"Other"}],[37385,{0:"Flash did not fire",1:"Flash fired",5:"Strobe return light not detected",7:"Strobe return light detected",9:"Flash fired, compulsory flash mode",13:"Flash fired, compulsory flash mode, return light not detected",15:"Flash fired, compulsory flash mode, return light detected",16:"Flash did not fire, compulsory flash mode",24:"Flash did not fire, auto mode",25:"Flash fired, auto mode",29:"Flash fired, auto mode, return light not detected",31:"Flash fired, auto mode, return light detected",32:"No flash function",65:"Flash fired, red-eye reduction mode",69:"Flash fired, red-eye reduction mode, return light not detected",71:"Flash fired, red-eye reduction mode, return light detected",73:"Flash fired, compulsory flash mode, red-eye reduction mode",77:"Flash fired, compulsory flash mode, red-eye reduction mode, return light not detected",79:"Flash fired, compulsory flash mode, red-eye reduction mode, return light detected",89:"Flash fired, auto mode, red-eye reduction mode",93:"Flash fired, auto mode, return light not detected, red-eye reduction mode",95:"Flash fired, auto mode, return light detected, red-eye reduction mode"}],[41495,{1:"Not defined",2:"One-chip color area sensor",3:"Two-chip color area sensor",4:"Three-chip color area sensor",5:"Color sequential area sensor",7:"Trilinear sensor",8:"Color sequential linear sensor"}],[41728,{1:"Film Scanner",2:"Reflection Print Scanner",3:"Digital Camera"}],[41729,{1:"Directly photographed"}],[41985,{0:"Normal",1:"Custom",2:"HDR (no original saved)",3:"HDR (original saved)",4:"Original (for HDR)",6:"Panorama",7:"Portrait HDR",8:"Portrait"}],[41986,{0:"Auto",1:"Manual",2:"Auto bracket"}],[41987,{0:"Auto",1:"Manual"}],[41990,{0:"Standard",1:"Landscape",2:"Portrait",3:"Night",4:"Other"}],[41991,{0:"None",1:"Low gain up",2:"High gain up",3:"Low gain down",4:"High gain down"}],[41996,{0:"Unknown",1:"Macro",2:"Close",3:"Distant"}],[42080,{0:"Unknown",1:"Not a Composite Image",2:"General Composite Image",3:"Composite Image Captured While Shooting"}]]),$t={1:"No absolute unit of measurement",2:"Inch",3:"Centimeter"};K.set(37392,$t),K.set(41488,$t);var pt={0:"Normal",1:"Low",2:"High"};function _t(s){return typeof s=="object"&&s.length!==void 0?s[0]:s}function Xt(s){let t=Array.from(s).slice(1);return t[1]>15&&(t=t.map((e=>String.fromCharCode(e)))),t[2]!=="0"&&t[2]!==0||t.pop(),t.join(".")}function mt(s){if(typeof s=="string"){var[t,e,i,n,r,a]=s.trim().split(/[-: ]/g).map(Number),o=new Date(t,e-1,i);return Number.isNaN(n)||Number.isNaN(r)||Number.isNaN(a)||(o.setHours(n),o.setMinutes(r),o.setSeconds(a)),Number.isNaN(+o)?s:o}}function _(s){if(typeof s=="string")return s;let t=[];if(s[1]===0&&s[s.length-1]===0)for(let e=0;e<s.length;e+=2)t.push(Kt(s[e+1],s[e]));else for(let e=0;e<s.length;e+=2)t.push(Kt(s[e],s[e+1]));return qt(String.fromCodePoint(...t))}function Kt(s,t){return s<<8|t}K.set(41992,pt),K.set(41993,pt),K.set(41994,pt),k(N,["ifd0","ifd1"],[[50827,function(s){return typeof s!="string"?Zt(s):s}],[306,mt],[40091,_],[40092,_],[40093,_],[40094,_],[40095,_]]),k(N,"exif",[[40960,Xt],[36864,Xt],[36867,mt],[36868,mt],[40962,_t],[40963,_t]]),k(N,"gps",[[0,s=>Array.from(s).join(".")],[7,s=>Array.from(s).join(":")]]);var Y=class extends v{static canHandle(t,e){return t.getUint8(e+1)===225&&t.getUint32(e+4)===1752462448&&t.getString(e+4,20)==="http://ns.adobe.com/"}static headerLength(t,e){return t.getString(e+4,34)==="http://ns.adobe.com/xmp/extension/"?79:33}static findPosition(t,e){let i=super.findPosition(t,e);return i.multiSegment=i.extended=i.headerLength===79,i.multiSegment?(i.chunkCount=t.getUint8(e+72),i.chunkNumber=t.getUint8(e+76),t.getUint8(e+77)!==0&&i.chunkNumber++):(i.chunkCount=1/0,i.chunkNumber=-1),i}static handleMultiSegments(t){return t.map((e=>e.chunk.getString())).join("")}normalizeInput(t){return typeof t=="string"?t:O.from(t).getString()}parse(t=this.chunk){if(!this.localOptions.parse)return t;t=(function(r){let a={},o={};for(let h of oe)a[h]=[],o[h]=0;return r.replace(Le,((h,l,u)=>{if(l==="<"){let d=++o[u];return a[u].push(d),`${h}#${d}`}return`${h}#${a[u].pop()}`}))})(t);let e=ft.findAll(t,"rdf","Description");e.length===0&&e.push(new ft("rdf","Description",void 0,t));let i,n={};for(let r of e)for(let a of r.properties)i=Me(a.ns,n),ne(a,i);return(function(r){let a;for(let o in r)a=r[o]=et(r[o]),a===void 0&&delete r[o];return et(r)})(n)}assignToOutput(t,e){if(this.localOptions.parse)for(let[i,n]of Object.entries(e))switch(i){case"tiff":this.assignObjectToOutput(t,"ifd0",n);break;case"exif":this.assignObjectToOutput(t,"exif",n);break;case"xmlns":break;default:this.assignObjectToOutput(t,i,n)}else t.xmp=e}};c(Y,"type","xmp"),c(Y,"multiSegment",!0),b.set("xmp",Y);var Pt=class s{static findAll(t){return re(t,/([a-zA-Z0-9-]+):([a-zA-Z0-9-]+)=("[^"]*"|'[^']*')/gm).map(s.unpackMatch)}static unpackMatch(t){let e=t[1],i=t[2],n=t[3].slice(1,-1);return n=ae(n),new s(e,i,n)}constructor(t,e,i){this.ns=t,this.name=e,this.value=i}serialize(){return this.value}},ft=class s{static findAll(t,e,i){if(e!==void 0||i!==void 0){e=e||"[\\w\\d-]+",i=i||"[\\w\\d-]+";var n=new RegExp(`<(${e}):(${i})(#\\d+)?((\\s+?[\\w\\d-:]+=("[^"]*"|'[^']*'))*\\s*)(\\/>|>([\\s\\S]*?)<\\/\\1:\\2\\3>)`,"gm")}else n=/<([\w\d-]+):([\w\d-]+)(#\d+)?((\s+?[\w\d-:]+=("[^"]*"|'[^']*'))*\s*)(\/>|>([\s\S]*?)<\/\1:\2\3>)/gm;return re(t,n).map(s.unpackMatch)}static unpackMatch(t){let e=t[1],i=t[2],n=t[4],r=t[8];return new s(e,i,n,r)}constructor(t,e,i,n){this.ns=t,this.name=e,this.attrString=i,this.innerXml=n,this.attrs=Pt.findAll(i),this.children=s.findAll(n),this.value=this.children.length===0?ae(n):void 0,this.properties=[...this.attrs,...this.children]}get isPrimitive(){return this.value!==void 0&&this.attrs.length===0&&this.children.length===0}get isListContainer(){return this.children.length===1&&this.children[0].isList}get isList(){let{ns:t,name:e}=this;return t==="rdf"&&(e==="Seq"||e==="Bag"||e==="Alt")}get isListItem(){return this.ns==="rdf"&&this.name==="li"}serialize(){if(this.properties.length===0&&this.value===void 0)return;if(this.isPrimitive)return this.value;if(this.isListContainer)return this.children[0].serialize();if(this.isList)return Be(this.children.map(Ue));if(this.isListItem&&this.children.length===1&&this.attrs.length===0)return this.children[0].serialize();let t={};for(let e of this.properties)ne(e,t);return this.value!==void 0&&(t.value=this.value),et(t)}};function ne(s,t){let e=s.serialize();e!==void 0&&(t[s.name]=e)}var Ue=s=>s.serialize(),Be=s=>s.length===1?s[0]:s,Me=(s,t)=>t[s]?t[s]:t[s]={};function re(s,t){let e,i=[];if(!s)return i;for(;(e=t.exec(s))!==null;)i.push(e);return i}function ae(s){if((function(i){return i==null||i==="null"||i==="undefined"||i===""||i.trim()===""})(s))return;let t=Number(s);if(!Number.isNaN(t))return t;let e=s.toLowerCase();return e==="true"||e!=="false"&&s.trim()}var oe=["rdf:li","rdf:Seq","rdf:Bag","rdf:Alt","rdf:Description"],Le=new RegExp(`(<|\\/)(${oe.join("|")})`,"g"),he=Ie;async function Ve(s){try{return await he.parse(s)||null}catch{return null}}function Re(){return Array.from(crypto.getRandomValues(new Uint8Array(16)),s=>s.toString(16).padStart(2,"0")).join("")}async function je(s){if(typeof createImageBitmap>"u"||typeof document>"u"){if(s&&typeof s.arrayBuffer=="function"){let o=await s.arrayBuffer(),h=globalThis.Buffer,l=typeof h<"u"?h.from(o).toString("base64"):btoa(String.fromCharCode(...new Uint8Array(o)));return`data:${s.type||"image/png"};base64,${l}`}if(typeof s=="string")return s}let t=await createImageBitmap(s),n=Math.min(1,1654/t.width,2339/t.height);if(n===1&&(s.type==="image/jpeg"||s.type==="image/jpg"||s.type==="image/png"||s.type==="image/webp"))return t.close(),new Promise((o,h)=>{let l=new FileReader;l.onload=()=>o(l.result),l.onerror=h,l.readAsDataURL(s)});let r=document.createElement("canvas");r.width=Math.round(t.width*n),r.height=Math.round(t.height*n),r.getContext("2d").drawImage(t,0,0,r.width,r.height),t.close();let a=s.type==="image/png"?"image/png":"image/jpeg";return r.toDataURL(a,a==="image/png"?void 0:.82)}function le(s,t=21,e=.2,i=128){let{data:n,width:r,height:a}=s,o=r+1,h=new Float64Array((r+1)*(a+1)),l=new Float64Array((r+1)*(a+1)),u=new Uint8Array(r*a);for(let f=0;f<a;f++){let g=0,S=0,U=f*r,B=(f+1)*o,A=f*o;for(let w=0;w<r;w++){let x=(U+w)*4,M=n[x]*77+n[x+1]*150+n[x+2]*29>>8;u[U+w]=M,g+=M,S+=M*M,h[B+w+1]=h[A+w+1]+g,l[B+w+1]=l[A+w+1]+S}}let d=Math.floor(t/2);for(let f=0;f<a;f++){let g=Math.max(0,f-d),S=Math.min(a-1,f+d),U=g*o,B=(S+1)*o;for(let A=0;A<r;A++){let w=Math.max(0,A-d),x=Math.min(r-1,A+d),M=(x-w+1)*(S-g+1),ue=h[B+x+1]-h[U+x+1]-h[B+w]+h[U+w],de=l[B+x+1]-l[U+x+1]-l[B+w]+l[U+w],ut=ue/M,ce=Math.max(0,de/M-ut*ut),ge=Math.sqrt(ce),pe=ut*(1+e*(ge/i-1)),Tt=f*r+A,dt=u[Tt]<pe?0:255,ct=Tt*4;n[ct]=dt,n[ct+1]=dt,n[ct+2]=dt}}return s}function Ge(s,t=21,e=.2,i=128){return new Promise(n=>{let r=new Image;r.onload=()=>{let a=document.createElement("canvas");a.width=r.width,a.height=r.height;let o=a.getContext("2d");o.drawImage(r,0,0);let h=o.getImageData(0,0,a.width,a.height);le(h,t,e,i),o.putImageData(h,0,0);let l=s.startsWith("data:image/png"),u=l?"image/png":"image/jpeg";n(a.toDataURL(u,l?void 0:.82))},r.src=s})}function He(s){return new Promise(t=>{let e=new Image;e.onload=()=>{let i=document.createElement("canvas");i.width=e.height,i.height=e.width;let n=i.getContext("2d");n.translate(i.width/2,i.height/2),n.rotate(Math.PI/2),n.drawImage(e,-e.width/2,-e.height/2);let r=s.startsWith("data:image/png"),a=r?"image/png":"image/jpeg";t(i.toDataURL(a,r?void 0:.82))},e.src=s})}function We(s,t=""){if(!s)return"";let e=s.getCroppedCanvas(),i=t.startsWith("data:image/png"),n=i?"image/png":"image/jpeg";return e.toDataURL(n,i?void 0:.82)}function Dt(s){if(!s||typeof s!="object")return{crop:null,rotation:0,filter:"none"};let t=null;s.crop&&typeof s.crop=="object"&&(s.crop.width>0&&s.crop.height>0?t={x:Math.round(s.crop.x||0),y:Math.round(s.crop.y||0),width:Math.round(s.crop.width),height:Math.round(s.crop.height)}:s.crop.w>0&&s.crop.h>0&&(t={x:Number(s.crop.x)||0,y:Number(s.crop.y)||0,w:Number(s.crop.w)||1,h:Number(s.crop.h)||1}));let e=s.rotation!==void 0?s.rotation:s.rotate,i=(Math.round(Number(e)||0)%360+360)%360,n=s.filter==="bw"?"bw":"none";return{crop:t,rotation:i,filter:n}}function De(s){if(!s)return!1;let t=Dt(s);return!!(t.crop||t.rotation!==0||t.filter!=="none")}function Ft(s,t){let e=Dt(t),i=s.naturalWidth||s.width||0,n=s.naturalHeight||s.height||0,r=document.createElement("canvas"),a=i,o=n,h=0,l=0;if(e.crop){let f=e.crop;"w"in f&&!("width"in f)?(h=Math.max(0,Math.min(Math.round(f.x*i),i)),l=Math.max(0,Math.min(Math.round(f.y*n),n)),a=Math.max(1,Math.min(Math.round(f.w*i),i-h)),o=Math.max(1,Math.min(Math.round(f.h*n),n-l))):(h=Math.max(0,Math.min(f.x,i)),l=Math.max(0,Math.min(f.y,n)),a=Math.max(1,Math.min(f.width,i-h)),o=Math.max(1,Math.min(f.height,n-l)))}r.width=a,r.height=o,r.getContext("2d").drawImage(s,h,l,a,o,0,0,a,o);let d=r;if(e.rotation!==0){let f=e.rotation,g=document.createElement("canvas");f===90||f===270?(g.width=d.height,g.height=d.width):(g.width=d.width,g.height=d.height);let S=g.getContext("2d");S.translate(g.width/2,g.height/2),S.rotate(f*Math.PI/180),S.drawImage(d,-d.width/2,-d.height/2),d=g}if(e.filter==="bw"){let f=d.getContext("2d"),g=f.getImageData(0,0,d.width,d.height);le(g),f.putImageData(g,0,0)}return d}function $e(s,t){if(!s)return Promise.resolve("");let e=Dt(t);return De(e)?new Promise((i,n)=>{let r=new Image;r.onload=()=>{try{let a=s.startsWith("data:image/png"),o=a?"image/png":"image/jpeg",h=Ft(r,e);i(h.toDataURL(o,a?void 0:.82))}catch(a){n(a)}},r.onerror=n,r.src=s}):Promise.resolve(s)}function Fe(s){return new Promise((t,e)=>{let i=new Image;i.onload=()=>t(i),i.onerror=e,i.src=s})}var fe=class extends Et{async renderEdits(t,e={}){if(!t)return"";if(typeof document>"u")return t;try{let i=await Fe(t),n={...e};return e?.crop&&"w"in e.crop&&(n.crop={x:Math.round((e.crop.x||0)*i.naturalWidth),y:Math.round((e.crop.y||0)*i.naturalHeight),width:Math.round((e.crop.w||1)*i.naturalWidth),height:Math.round((e.crop.h||1)*i.naturalHeight)}),e?.rotate!==void 0&&(n.rotation=e.rotate),Ft(i,n).toDataURL("image/jpeg",.92)}catch{return t}}async crop(t,e){return this.renderEdits(t,{crop:e})}async rotate(t,e){return this.renderEdits(t,{rotate:e})}async applyFilter(t,e){return this.renderEdits(t,{filter:e})}};export{Ve as a,Re as b,je as c,le as d,Ge as e,He as f,We as g,Dt as h,Ft as i,$e as j,fe as k};
4
- //# sourceMappingURL=chunk-G5EUMLYT.js.map
@@ -1,2 +0,0 @@
1
- import{a as F,b as m,c as O,j as R,k as L}from"./chunk-G5EUMLYT.js";import{a as N}from"./chunk-KH5JE65X.js";import{c as D}from"./chunk-K4NR6OAC.js";import{c as P}from"./chunk-L4OVZN23.js";import{a as f}from"./chunk-U3V3VZGO.js";import{a as w}from"./chunk-5OTO5WFV.js";import{a as B,b as v}from"./chunk-ZT72PD2C.js";var g=class{#e=null;#t=new Map;#i=new Map;constructor(e=D()){this.#e=e}get adapter(){return this.#e}get store(){return this.#e?.store??null}async init(){return this.#e.init()}listDocsSync(){return typeof this.#e.listDocsSync=="function"?this.#e.listDocsSync().map(t=>{let s=this.#r(t.pages);return{id:t.id,name:t.name||"",pageCount:s.length,pages:s}}):[]}async listDocs(){return(await this.#e.listDocs()).map(t=>{let s=this.#r(t.pages);return{id:t.id,name:t.name||"",pageCount:s.length,pages:s}})}getDocSync(e){if(!e)return null;if(typeof this.#e.getDocSync=="function"){let r=this.#e.getDocSync(e);return r?{id:r.id,name:r.name||"",pages:this.#r(r.pages)}:null}let s=this.listDocsSync().find(r=>r.id===e);return s?{id:s.id,name:s.name,pages:s.pages||[]}:null}async getDoc(e){if(!e)return null;if(typeof this.#e.getDoc=="function"){let t=await this.#e.getDoc(e);return t?{id:t.id,name:t.name||"",pages:this.#r(t.pages)}:null}return this.getDocSync(e)}async createDoc(e="Untitled Document",t=[]){let s=m(),r=this.#r(t),o={id:s,name:e||"Untitled Document",pages:r};return await this.#e.saveDoc(s,o),o}async saveDoc(e,t){if(!e)throw new Error("Cannot save document without an ID");let s=this.#r(t.pages);await this.#e.saveDoc(e,{id:e,name:t.name||"",pages:s})}async renameDoc(e,t){if(typeof this.#e.renameDoc=="function")return this.#e.renameDoc(e,t);let s=await this.getDoc(e);if(!s)throw new Error(`Document "${e}" not found`);s.name=t,await this.saveDoc(e,s)}async deleteDoc(e,{soft:t=!0,timeoutMs:s=5e3}={}){if(!e)return;let r=this.getDocSync(e);if(r){if(this.#n(e),await this.#e.deleteDoc(e),t&&s>0){let o=setTimeout(async()=>{this.#t.delete(e)},s);this.#t.set(e,{doc:r,timerId:o})}return{id:e,name:r.name,undo:()=>this.undoDeleteDoc(e)}}}#n(e){if(this.#t.has(e)){let t=this.#t.get(e);clearTimeout(t.timerId),this.#t.delete(e)}}async undoDeleteDoc(e){let t=this.#t.get(e);return t?(clearTimeout(t.timerId),this.#t.delete(e),await this.#e.saveDoc(e,t.doc),t.doc):null}isSoftDeletedDoc(e){return this.#t.has(e)}async addPages(e,t){let s=await this.getDoc(e);if(!s)throw new Error(`Document "${e}" not found`);let r=Array.isArray(t)?t:[t];s.pages.push(...r),await this.saveDoc(e,s)}async updatePage(e,t,s){let r=await this.getDoc(e);if(!r)throw new Error(`Document "${e}" not found`);let o=r.pages.findIndex(i=>i.id===t);if(o===-1)throw new Error(`Page "${t}" not found in document "${e}"`);r.pages[o]={...r.pages[o],...s},await this.saveDoc(e,r)}async reorderPages(e,t){let s=await this.getDoc(e);if(!s)throw new Error(`Document "${e}" not found`);let r=new Map(s.pages.map(i=>[i.id,i])),o=[];for(let i of t)r.has(i)&&(o.push(r.get(i)),r.delete(i));for(let i of r.values())o.push(i);s.pages=o,await this.saveDoc(e,s)}async deletePage(e,t,{soft:s=!0,timeoutMs:r=5e3}={}){let o=await this.getDoc(e);if(!o)throw new Error(`Document "${e}" not found`);let i=o.pages.findIndex(h=>h.id===t);if(i===-1)return;let[a]=o.pages.splice(i,1);await this.saveDoc(e,o);let u=`${e}:${t}`;if(this.#d(u),!s||r<=0){if(typeof this.#e.deletePage=="function")try{await this.#e.deletePage(e,t)}catch(h){console.warn("[DocRepository] Adapter deletePage error:",h)}return}let c=setTimeout(async()=>{if(this.#i.delete(u),typeof this.#e.deletePage=="function")try{await this.#e.deletePage(e,t)}catch(h){console.warn("[DocRepository] Adapter deletePage error:",h)}},r);return this.#i.set(u,{docId:e,pageId:t,page:a,index:i,timerId:c}),{docId:e,pageId:t,undo:()=>this.undoDeletePage(e,t)}}#d(e){if(this.#i.has(e)){let t=this.#i.get(e);clearTimeout(t.timerId),this.#i.delete(e)}}async undoDeletePage(e,t){let s=`${e}:${t}`,r=this.#i.get(s);if(!r)return null;clearTimeout(r.timerId),this.#i.delete(s);let o=await this.getDoc(e);if(!o)return null;let i=Math.min(r.index,o.pages.length);return o.pages.splice(i,0,r.page),await this.saveDoc(e,o),r.page}isSoftDeletedPage(e,t){return this.#i.has(`${e}:${t}`)}subscribe(e){return this.#e.subscribe(e)}async getAllDocs(){let e=await this.listDocs(),t={};for(let s of e)t[s.id]=s;return t}async exportAll(){let e=await this.listDocs(),t={};for(let s of e){let r=await this.getDoc(s.id),o=[];for(let i of r?.pages||[]){if(!i){o.push(i);continue}let a={...i},u=a.blob instanceof Blob?a.blob:null;if(!u&&typeof a.src=="string"&&a.src.startsWith("blob:"))try{u=await(await fetch(a.src)).blob()}catch{}u&&(a.src=await P(u));let c=a.originalBlob instanceof Blob?a.originalBlob:null;if(!c&&typeof a.originalSrc=="string"&&a.originalSrc.startsWith("blob:"))try{c=await(await fetch(a.originalSrc)).blob()}catch{}c&&(a.originalSrc=await P(c)),delete a.blob,delete a.originalBlob,o.push(a)}t[s.id]={name:s.name,pages:JSON.stringify(o)}}return t}async importDocs(e){let t=0;for(let[s,r]of Object.entries(e||{})){await this.getDoc(s)||t++;let i=this.#r(r.pages);await this.saveDoc(s,{name:r.name||"",pages:i})}return t}#r(e){if(Array.isArray(e))return[...e];if(typeof e=="string")try{return JSON.parse(e)}catch{return[]}return[]}},W=new g;var k="2026-11-06T14:30:44.258Z",z="0.1.4";function S(n={}){let e=n&&n.crop&&typeof n.crop=="object"?{x:Math.max(0,Math.min(1,Number(n.crop.x)||0)),y:Math.max(0,Math.min(1,Number(n.crop.y)||0)),w:Math.max(0,Math.min(1,Number(n.crop.w)||1)),h:Math.max(0,Math.min(1,Number(n.crop.h)||1))}:null,t=0,s=n?.rotate!==void 0?n.rotate:n?.rotation;if(s!==void 0){let o=(Math.round(Number(s)/90)*90%360+360)%360;(o===90||o===180||o===270)&&(t=o)}let r=n&&n.filter==="bw"?"bw":"none";return{crop:e,rotate:t,filter:r}}function U(n){if(!n)return!1;let e=n.rotate!==void 0?n.rotate:n.rotation;return!!(n.crop||e&&e!==0||n.filter&&n.filter!=="none")}var d=n=>Math.round(n*1e6)/1e6;function M(n,e=0){if(!n)return null;let t=(Math.round(Number(e)/90)*90%360+360)%360,{x:s,y:r,w:o,h:i}=n;return t===90?{x:d(Math.max(0,Math.min(1,1-r-i))),y:d(Math.max(0,Math.min(1,s))),w:d(Math.max(.01,Math.min(1,i))),h:d(Math.max(.01,Math.min(1,o)))}:t===180?{x:d(Math.max(0,Math.min(1,1-s-o))),y:d(Math.max(0,Math.min(1,1-r-i))),w:d(Math.max(.01,Math.min(1,o))),h:d(Math.max(.01,Math.min(1,i)))}:t===270?{x:d(Math.max(0,Math.min(1,r))),y:d(Math.max(0,Math.min(1,1-s-o))),w:d(Math.max(.01,Math.min(1,i))),h:d(Math.max(.01,Math.min(1,o)))}:{x:d(Math.max(0,Math.min(1,s))),y:d(Math.max(0,Math.min(1,r))),w:d(Math.max(.01,Math.min(1,o))),h:d(Math.max(.01,Math.min(1,i)))}}function j(n,e=0){return M(n,e)}function G(n,e=0){return M(n,-e)}var y=class{constructor(e){this.id=e.id,this.src=e.src,this.originalSrc=e.originalSrc||e.src,this.edits=S(e.edits),this.name=e.name||"Page",this.type=e.type||"image",this.orientation=e.orientation||1,this.ocrText=e.ocrText||null,this.ocrConfidence=e.ocrConfidence??null,this.ocrWords=Array.isArray(e.ocrWords)?e.ocrWords:null,this.ocrWidth=typeof e.ocrWidth=="number"?e.ocrWidth:null,this.ocrHeight=typeof e.ocrHeight=="number"?e.ocrHeight:null}get isModified(){return U(this.edits)}toJSON(){return{id:this.id,src:this.src,originalSrc:this.originalSrc,edits:this.edits,name:this.name,type:this.type,orientation:this.orientation,ocrText:this.ocrText,ocrConfidence:this.ocrConfidence,ocrWords:this.ocrWords,ocrWidth:this.ocrWidth,ocrHeight:this.ocrHeight}}},A=class{constructor(e){this.id=e.id,this.name=e.name||"Untitled Document",this.pages=Array.isArray(e.pages)?e.pages.map(t=>t instanceof y?t:new y(t)):[],this.createdAt=e.createdAt||Date.now(),this.updatedAt=e.updatedAt||Date.now()}get pageCount(){return this.pages.length}toJSON(){return{id:this.id,name:this.name,pages:this.pages.map(e=>e.toJSON()),createdAt:this.createdAt,updatedAt:this.updatedAt}}},b=class{constructor(e={}){this.mode=e.mode==="single"?"single":"batch",this.aspect=e.aspect||"auto",this.docId=e.docId||null,this.maxPages=Math.max(0,Number(e.maxPages)||0),this.stage="viewfinder",this.activePageIndex=0,this.history=[],this.future=[]}pushHistory(e){this.history.push(e),this.future=[],this.history.length>50&&this.history.shift()}undo(){if(this.history.length===0)return null;let e=this.history.pop();return this.future.push(e),e}redo(){if(this.future.length===0)return null;let e=this.future.pop();return this.history.push(e),e}};var H={PAGE_ADDED:"copio:page-added",PAGE_REMOVED:"copio:page-removed",PAGES_CHANGED:"copio:pages-changed",SCAN_COMPLETE:"copio:scan-complete",EXPORT_PROGRESS:"copio:export-progress",EXPORT_COMPLETE:"copio:export-complete",OCR_COMPLETE:"copio:ocr-complete",SYNC_CONNECTED:"copio:sync-connected",ERROR:"copio:error"};function J(n,e,t={}){let s=new CustomEvent(e,{bubbles:!0,composed:!0,cancelable:!0,detail:t});return n&&typeof n.dispatchEvent=="function"&&n.dispatchEvent(s),s}var I=["crop","rotate","filter","ocr","export","sync"],_=["pdf","zip","png","jpg"],T=["eng"],C={};function Se(n,e){!n||!e||(C[n]=e,typeof globalThis<"u"&&(globalThis.__copio_services__=globalThis.__copio_services__||{},globalThis.__copio_services__[n]=e))}function p(n){return C[n]?C[n]:typeof globalThis<"u"&&globalThis.__copio_services__?.[n]?globalThis.__copio_services__[n]:null}function K(n){return n?n instanceof Set?new Set(n):Array.isArray(n)?new Set(n.map(e=>String(e).trim().toLowerCase()).filter(Boolean)):typeof n=="string"?new Set(n.split(/[\s,]+/).map(e=>e.trim().toLowerCase()).filter(Boolean)):new Set(I):new Set(I)}function x(n,e){return n?Array.isArray(n)?n.map(t=>String(t).trim().toLowerCase()).filter(Boolean):typeof n=="string"?n.split(/[\s,]+/).map(t=>t.trim().toLowerCase()).filter(Boolean):[...e]:[...e]}var $=class{#e=new Set(I);#t=[..._];#i=[...T];#n=0;#d="";#r=null;#s=null;#l={};#a=!0;#h=!0;#o=null;#c=new Map;#u=new Map;constructor(e={}){this.#r=e.storage||D(e),this.#s=e.repository||new g(this.#r),e.services&&(this.#l={...e.services}),e.imageProcessor?(this.#o=e.imageProcessor,this.#l.imageProcessor=e.imageProcessor):this.getService("imageProcessor")?this.#o=this.getService("imageProcessor"):typeof document<"u"?this.#o=new L:this.#o=new N,e.features!==void 0&&this.setFeatures(e.features),e.exportFormats!==void 0&&(this.#t=x(e.exportFormats,_)),e.ocrLanguages!==void 0&&(this.#i=x(e.ocrLanguages,T)),e.maxPages!==void 0&&(this.#n=Math.max(0,Number(e.maxPages)||0)),e.assetBase!==void 0&&v(e.assetBase),e.licenseKey!==void 0&&(this.#d=String(e.licenseKey||"")),e.ocr!==void 0?this.ocr=!!e.ocr:e.features!==void 0&&!this.hasFeature("ocr")&&(this.ocr=!1),e.pdf!==void 0?this.pdf=!!e.pdf:e.exportFormats!==void 0&&!this.#t.includes("pdf")&&(this.pdf=!1)}async init(){return this.#r.init()}setService(e,t){this.#l[e]=t}getService(e){return this.#l[e]||p(e)}hasFeature(e){return e?this.#e.has(String(e).trim().toLowerCase()):!1}get features(){return Array.from(this.#e)}setFeatures(e){this.#e=K(e),this.hasFeature("ocr")?(this.#a=!0,this.getService("ocr")instanceof f&&this.setService("ocr",p("ocr"))):(this.#a=!1,this.setService("ocr",new f))}enableFeature(e){if(e){let t=String(e).trim().toLowerCase();this.#e.add(t),t==="ocr"&&(this.#a=!0,this.getService("ocr")instanceof f&&this.setService("ocr",p("ocr")))}}disableFeature(e){if(e){let t=String(e).trim().toLowerCase();this.#e.delete(t),t==="ocr"&&(this.#a=!1,this.setService("ocr",new f))}}get ocr(){return this.#a&&this.hasFeature("ocr")}set ocr(e){this.#a=!!e,this.#a?(this.enableFeature("ocr"),this.getService("ocr")instanceof f&&this.setService("ocr",p("ocr"))):(this.disableFeature("ocr"),this.setService("ocr",new f))}get pdf(){return this.#h&&this.#t.includes("pdf")}set pdf(e){this.#h=!!e,this.#h?(this.#t.includes("pdf")||this.#t.push("pdf"),this.getService("pdf")instanceof w&&this.setService("pdf",p("pdf"))):(this.#t=this.#t.filter(t=>t!=="pdf"),this.setService("pdf",new w))}get exportFormats(){return[...this.#t]}set exportFormats(e){this.#t=x(e,_),this.#t.includes("pdf")?(this.#h=!0,this.getService("pdf")instanceof w&&this.setService("pdf",p("pdf"))):(this.#h=!1,this.setService("pdf",new w))}get ocrLanguages(){return[...this.#i]}set ocrLanguages(e){this.#i=x(e,T)}get maxPages(){return this.#n}set maxPages(e){this.#n=Math.max(0,Number(e)||0)}get assetBase(){return B()}set assetBase(e){v(e)}get licenseKey(){return this.#d}set licenseKey(e){this.#d=String(e||"")}get storage(){return this.#r}setStorage(e){e&&(this.#r=e,this.#s=new g(this.#r))}#f(e,t){this.#c.has(e)||this.#c.set(e,[]);let s=this.#c.get(e);s.push(t),s.length>50&&s.shift(),this.#u.has(e)&&(this.#u.get(e).length=0)}get imageProcessor(){return this.#o}setImageProcessor(e){e&&(this.#o=e,this.setService("imageProcessor",e))}async renderEdits(e,t){if(!e)return"";let s=S(t);return this.#o?this.#o.renderEdits(e,s):R(e,s)}get docs(){return this.#s}async listDocuments(){return this.#s.listDocs()}async getDocument(e){return this.#s.getDoc(e)}async createDocument(e,t){return this.#s.createDoc(e,t)}async deleteDocument(e,t={}){return this.#s.deleteDoc(e,t)}async undoDeleteDocument(e){return this.#s.undoDeleteDoc(e)}async renameDocument(e,t){return this.#s.renameDoc(e,t)}async addPages(e,t){return this.#s.addPages(e,t)}async deletePage(e,t,s={}){return this.#f(e,{type:"delete",pageId:t}),this.#s.deletePage(e,t,s)}async undoDeletePage(e,t){return this.#s.undoDeletePage(e,t)}async updatePage(e,t,s){return this.#s.updatePage(e,t,s)}async reorderPages(e,t){let s=await this.getDocument(e),r=s?.pages?s.pages.map(o=>o.id):[];return this.#f(e,{type:"reorder",priorOrder:r,newOrder:[...t]}),this.#s.reorderPages(e,t)}async#g(e){if(e)return e;let t=await this.listDocuments();return t.length>0?t[0].id:null}async applyEdit(e,t,s){let r=await this.#g(e),o=r?await this.getDocument(r):null;if(!o||!o.pages)throw new Error(`Document with ID "${r||e}" not found`);let i=o.pages.find(E=>E.id===t);if(!i)throw new Error(`Page with ID "${t}" not found in document "${r}"`);let a={...i.edits||{crop:null,rotate:0,filter:"none"}},u=i.src,c=S({...a,...s}),h=i.originalSrc||i.src,l=h;return this.#o&&(l=await this.#o.renderEdits(h,c)),await this.updatePage(r,t,{originalSrc:h,src:l,edits:c}),this.#f(r,{type:"edit",pageId:t,priorEdits:a,priorSrc:u,newEdits:c,newSrc:l}),{...i,originalSrc:h,src:l,edits:c}}async undo(e){let t=await this.#g(e),s=t?this.#c.get(t):null;if(!s||s.length===0)return null;let r=s.pop();return this.#u.has(t)||this.#u.set(t,[]),this.#u.get(t).push(r),r.type==="edit"?(await this.updatePage(t,r.pageId,{edits:r.priorEdits,src:r.priorSrc}),{type:"edit",pageId:r.pageId,restoredEdits:r.priorEdits}):r.type==="delete"?(await this.undoDeletePage(t,r.pageId),{type:"delete",pageId:r.pageId}):r.type==="reorder"?(await this.#s.reorderPages(t,r.priorOrder),{type:"reorder",priorOrder:r.priorOrder}):r}async redo(e){let t=await this.#g(e),s=t?this.#u.get(t):null;if(!s||s.length===0)return null;let r=s.pop();return this.#c.has(t)||this.#c.set(t,[]),this.#c.get(t).push(r),r.type==="edit"?(await this.updatePage(t,r.pageId,{edits:r.newEdits,src:r.newSrc}),{type:"edit",pageId:r.pageId,appliedEdits:r.newEdits}):r.type==="delete"?(await this.deletePage(t,r.pageId),{type:"delete",pageId:r.pageId}):r.type==="reorder"?(await this.reorderPages(t,r.newOrder),{type:"reorder",newOrder:r.newOrder}):r}subscribe(e){return this.#s.subscribe(e)}async addFiles(e,t=null){if(!e||e.length===0)return[];let s=Array.from(e),r=[];for(let i of s)if(i.type==="application/pdf"){let a=this.getService("pdf");if(a&&typeof a.renderPdfPagesToDataUrls=="function"){let u=await a.renderPdfPagesToDataUrls(i);for(let c of u)r.push({id:m(),src:c,originalSrc:c,edits:{crop:null,rotation:0,filter:"none"},type:"image",name:i.name||"PDF Page"})}else console.warn("PDF import service (PdfPort) not registered. Skipping PDF file.")}else if(i.type&&i.type.startsWith("image/")){let a=await O(i),u=null;try{u=await F(i)}catch{}r.push({id:m(),src:a,originalSrc:a,edits:{crop:null,rotation:0,filter:"none"},type:"image",name:i.name||"Captured Image",orientation:u})}if(r.length===0)return[];await this.init();let o=t;if(o)await this.getDocument(o)||await this.#s.saveDoc(o,{name:"Scanned Document",pages:[]});else{let i=await this.listDocuments();i.length>0?o=i[0].id:o=(await this.createDocument("Scanned Document",[])).id}if(this.#n>0){let i=(await this.getDocument(o))?.pages||[],a=Math.max(0,this.#n-i.length);if(a<=0)throw new Error(`Maximum page limit (${this.#n}) reached`);r.splice(a)}return await this.addPages(o,r),r}async getPages(e=null){let t=e;if(!t){let r=await this.listDocuments();if(r.length===0)return[];t=r[0].id}return(await this.getDocument(t))?.pages||[]}async clear(e=null){let t=e;if(!t){let r=await this.listDocuments();if(r.length===0)return;t=r[0].id}let s=await this.getDocument(t);if(!(!s||!s.pages))for(let r of s.pages)await this.deletePage(t,r.id)}async#p(e){if(Array.isArray(e))return{docName:"document",pages:e,docId:null};if(typeof e=="string"){let s=await this.getDocument(e);return{docName:s?.name||"document",pages:s?.pages||[],docId:e}}let t=await this.listDocuments();if(t.length>0){let s=await this.getDocument(t[0].id);return{docName:s?.name||"document",pages:s?.pages||[],docId:t[0].id}}return{docName:"document",pages:[],docId:null}}async exportPdf(e,t={}){if(!this.hasFeature("export")){let i=new Error('Feature "export" is disabled');throw Object.assign(i,{code:"FEATURE_DISABLED"}),i}if(!this.#h||!this.#t.includes("pdf")){let i=new Error('Feature "pdf" is disabled');throw Object.assign(i,{code:"FEATURE_DISABLED"}),i}let{docName:s,pages:r}=await this.#p(e),o=this.getService("pdf")||this.getService("export");if(!o||typeof o.exportDocumentAsPdf!="function")throw new Error("Export service (PdfPort) is not registered. Import @copio/sdk or register an exportService.");return o.exportDocumentAsPdf(s,r,{download:!1,showProgress:!1,onOcrComplete:async()=>{if(typeof e=="string"){let i=await this.#r.getDoc(e);i&&(i.pages=r,await this.#r.saveDoc(e,i))}},...t})}async exportZip(e,t={}){if(!this.hasFeature("export")){let i=new Error('Feature "export" is disabled');throw Object.assign(i,{code:"FEATURE_DISABLED"}),i}let{docName:s,pages:r}=await this.#p(e),o=this.getService("export");if(!o||typeof o.exportDocumentAsImages!="function")throw new Error("Export service is not registered. Import @copio/sdk or register an exportService.");return o.exportDocumentAsImages(s,r,{download:!1,showProgress:!1,...t})}async runOcr(e,t=null,s={}){if(!this.#a||!this.hasFeature("ocr")){let c=new Error('Feature "ocr" is disabled');throw Object.assign(c,{code:"FEATURE_DISABLED"}),c}let{pages:r}=await this.#p(e),o=r;t&&(o=r.filter(c=>c.id===t));let i=this.getService("ocr");if(!i||typeof i.recognizeDocumentPages!="function")throw new Error("OCR service (OcrPort) is not registered. Import @copio/sdk or register an ocrService.");let a=s.lang||this.#i[0]||"eng",u=await i.recognizeDocumentPages(o,{lang:a,...s});if(Array.isArray(u.pagesResults)){for(let c of u.pagesResults){let h=o.find(l=>l.id===c.pageId)||o[c.pageIndex];h&&(h.ocrText=c.text,h.ocrConfidence=c.confidence,h.ocrWords=c.words)}if(typeof e=="string"){let c=await this.#r.getDoc(e);if(c&&Array.isArray(c.pages)){for(let h of u.pagesResults){let l=c.pages.find(E=>E.id===h.pageId)||c.pages[h.pageIndex];l&&(l.ocrText=h.text,l.ocrConfidence=h.confidence,l.ocrWords=h.words)}await this.#r.saveDoc(e,c)}}}return{text:u.combinedText,...u}}async sync(e={}){if(!this.hasFeature("sync")){let s=new Error('Feature "sync" is disabled');throw Object.assign(s,{code:"FEATURE_DISABLED"}),s}let t=this.getService("sync");if(!t)throw new Error("Sync service (SyncPort) is not registered. Import @copio/sdk or register a syncService.");return new t(this.#s,e.onStateChange)}};export{g as a,W as b,k as c,z as d,S as e,U as f,M as g,j as h,G as i,y as j,A as k,b as l,H as m,J as n,I as o,_ as p,T as q,Se as r,p as s,$ as t};
2
- //# sourceMappingURL=chunk-IBF5HCYT.js.map
@@ -1,2 +0,0 @@
1
- import{a as L,b as S,d as m}from"./chunk-L4OVZN23.js";import{a as U}from"./chunk-FQRADJY6.js";import{a as D}from"./chunk-DIU5BGU5.js";async function $(){if(typeof location<"u"&&location.search&&(new URLSearchParams(location.search).has("no-opfs")||new URLSearchParams(location.search).get("storage")==="indexeddb")||typeof navigator>"u"||!navigator.storage||typeof navigator.storage.getDirectory!="function")return!1;try{let l=await navigator.storage.getDirectory();if(!l)return!1;let t=`.copio-probe-${Date.now()}-${Math.random().toString(36).slice(2)}.tmp`,r=await l.getFileHandle(t,{create:!0}),i=await r.createWritable();if(await i.write(new Uint8Array([1,2,3,4])),await i.close(),(await r.getFile()).size!==4)throw new Error("OPFS probe size mismatch");return await l.removeEntry(t),!0}catch{return!1}}function j(l,t,r="store.json"){let i=0,s=null,n=Promise.resolve(),a=0,o=()=>typeof t=="function"?t():t,e=async()=>{await n;let f=o();if(f){i=1;try{let u=await(await(await f.getFileHandle(r)).getFile()).text();u&&u.trim().length>0&&l.setJson(u)}catch{}finally{i=0}}},c=()=>{let f=o();return f?(a++,i=2,n=n.catch(()=>{}).then(async()=>{try{let w=l.getJson(),u=await(await f.getFileHandle(r,{create:!0})).createWritable();await u.write(w),await u.close()}catch(w){console.warn("[OpfsPersister] Failed to save store.json:",w)}finally{a--,a<=0&&(a=0,i=0)}}),n):Promise.resolve()};return{load:e,save:c,startAutoSave:()=>{s||(s=l.addDidFinishTransactionListener(()=>{c()}))},stopAutoSave:()=>{s&&(l.delListener(s),s=null)},getStatus:()=>i,getStore:()=>l}}async function O(l){let t=[];try{if(typeof l.entries=="function")for await(let r of l.entries())t.push(r);else if(typeof l.values=="function")for await(let r of l.values())t.push([r.name,r])}catch(r){console.warn("[OpfsAdapter] Error reading directory entries:",r)}return t}var v=class extends D{#p;#d="copio";#b=null;#g=null;#r=null;#i=null;#u=null;#t=!1;#e=null;#c=new Set;#l=new Map;#s=new Map;#a=new Map;#n=new Map;#w=null;constructor(t={}){super(),this.#p=t,this.#d=t.dirName||"copio",t.store?this.#i=t.store:(this.#i=L(),this.#i.setTable("docs",{})),this.#u=t.persister||j(this.#i,()=>this.#g,"store.json")}get store(){return this.#t?this.#e?.store:this.#i}get persister(){return this.#t?this.#e?.persister:this.#u}get isFallback(){return this.#t}get fallbackAdapter(){return this.#e}async#o(){if(this.#t)return!1;if(this.#r&&this.#g)return!0;if(typeof navigator<"u"&&navigator.storage&&typeof navigator.storage.getDirectory=="function")try{return this.#b=await navigator.storage.getDirectory(),this.#g=await this.#b.getDirectoryHandle(this.#d,{create:!0}),this.#r=await this.#g.getDirectoryHandle("docs",{create:!0}),!0}catch(t){return console.warn("[OpfsAdapter] OPFS directory access failed, switching to fallback:",t),await this.#h(),!1}else return await this.#h(),!1}#y(t,r){return typeof r=="string"&&r.startsWith("blob:")&&(this.#c.add(r),this.#l.has(t)||this.#l.set(t,[]),this.#l.get(t).push(r)),r}revokeDocUrls(t){if(this.#t){this.#e?.revokeDocUrls(t);return}let r=this.#l.get(t);if(r){for(let i of r){try{URL.revokeObjectURL(i)}catch{}this.#c.delete(i)}this.#l.delete(t)}for(let[i,s]of this.#s.entries())if(i.startsWith(`${t}:`)){try{URL.revokeObjectURL(s)}catch{}this.#s.delete(i)}for(let[i,s]of this.#a.entries())if(i.startsWith(`${t}:`)){try{URL.revokeObjectURL(s)}catch{}this.#a.delete(i)}this.#n.delete(t)}revokeAllUrls(){if(this.#t){this.#e?.revokeAllUrls();return}for(let t of this.#c)try{URL.revokeObjectURL(t)}catch{}this.#c.clear(),this.#l.clear(),this.#s.clear(),this.#a.clear(),this.#n.clear()}async init(){return this.#w?this.#w:(this.#w=(async()=>{if(this.#p.forceFallback)return this.#h();if(!await $())return this.#h();try{await this.#o(),await this.#u.load(),this.#u.startAutoSave(),await this.sweepOrphans();let r=!1;if(typeof navigator<"u"&&navigator.storage&&navigator.storage.persisted)try{r=await navigator.storage.persisted()}catch{}return{kind:"opfs",persistent:r}}catch(r){return console.warn("[OpfsAdapter] OPFS initialization failed, switching to IndexedDB fallback:",r),this.#h()}})(),this.#w)}async#h(){return this.#t=!0,this.#e=new m(this.#p),{kind:"indexeddb",persistent:(await this.#e.init()).persistent}}async sweepOrphans(){if(this.#t)return this.#e?.sweepOrphans();if(await this.#o(),!this.#r)return 0;let t=0,r=this.#i.getTable("docs")||{},i=new Set(Object.keys(r)),s=new Map;for(let[a,o]of Object.entries(r)){let e=this.#f(o.pages);s.set(a,new Set(e.map(c=>c.id)))}let n=await O(this.#r);for(let[a,o]of n)if(o.kind==="directory")if(i.has(a)){let e=s.get(a)||new Set,c=o,g=await O(c);for(let[y]of g){let f=y.replace(/-original\.bin$/,"").replace(/\.bin$/,"");if(!e.has(f))try{await c.removeEntry(y),t++}catch{}}}else try{await this.#r.removeEntry(a,{recursive:!0}),t++}catch{}return t}listDocsSync(){if(this.#t)return this.#e?.listDocsSync();let t=this.#i.getTable("docs");return Object.entries(t||{}).map(([r,i])=>({id:r,name:i.name||"",pages:this.#f(i.pages)}))}async listDocs(){return this.#t?this.#e?.listDocs():this.listDocsSync()}getDocSync(t){if(this.#t)return this.#e?.getDocSync(t);if(this.#n.has(t))return this.#n.get(t);if(!this.#i.hasRow("docs",t))return null;let r=this.#i.getRow("docs",t);return{id:t,name:r.name||"",pages:this.#f(r.pages)}}async getDoc(t){if(this.#t)return this.#e?.getDoc(t);if(await this.#o(),!this.#i.hasRow("docs",t))return null;let r=this.#i.getRow("docs",t),i=this.#f(r.pages),s=null;if(this.#r)try{s=await this.#r.getDirectoryHandle(t)}catch{}let n=await Promise.all(i.map(async o=>{if(!o||!s)return o;let e={...o},c=`${t}:${o.id}`;try{let f=await(await s.getFileHandle(`${o.id}.bin`)).getFile();e.blob=f,this.#s.has(c)?e.src=this.#s.get(c):(e.src=this.#y(t,URL.createObjectURL(f)),this.#s.set(c,e.src))}catch{}let g=`${t}:${o.id}:orig`;try{let f=await(await s.getFileHandle(`${o.id}-original.bin`)).getFile();e.originalBlob=f,this.#a.has(g)?e.originalSrc=this.#a.get(g):(e.originalSrc=this.#y(t,URL.createObjectURL(f)),this.#a.set(g,e.originalSrc))}catch{e.blob&&(e.originalBlob=e.blob,e.originalSrc=e.src)}return e})),a={id:t,name:r.name||"",pages:n};return this.#n.set(t,a),a}async saveDoc(t,r){if(this.#t)return this.#e?.saveDoc(t,r);if(!t)throw new Error("Cannot save document without an ID");let i=Array.isArray(r.pages)?r.pages:this.#f(r.pages),s=[],n=[],a=[];for(let e of i){if(!e)continue;let c=S(e.src)||(e.src instanceof Blob?e.src:null)||(e.blob instanceof Blob?e.blob:null),g=c?.type||"image/jpeg",y={id:e.id,name:e.name||"",type:e.type||"image",hasBlob:!0,mimeType:g,edits:e.edits,exif:e.exif,content:e.content,ocrText:e.ocrText??null,ocrConfidence:e.ocrConfidence??null,ocrWords:Array.isArray(e.ocrWords)?e.ocrWords:null,ocrWidth:e.ocrWidth??null,ocrHeight:e.ocrHeight??null};s.push(y);let f=`${t}:${e.id}`,w=`${t}:${e.id}:orig`,h={...e},u=this.#s.get(f),k=typeof e.src=="string"&&e.src.startsWith("data:")||e.src instanceof Blob||e.src&&u&&e.src!==u;if(c)if(h.blob=c,k||!u){if(u){try{URL.revokeObjectURL(u)}catch{}this.#c.delete(u)}let b=this.#y(t,URL.createObjectURL(c));this.#s.set(f,b),h.src=b}else h.src=u;let d=S(e.originalSrc)||(e.originalSrc instanceof Blob?e.originalSrc:null)||(e.originalBlob instanceof Blob?e.originalBlob:null),p=this.#a.get(w),R=!p&&!d&&(!e.originalSrc||e.originalSrc===e.src);R&&c&&(d=c);let H=typeof e.originalSrc=="string"&&e.originalSrc.startsWith("data:")||e.originalSrc instanceof Blob||R&&!!d;if(d)if(h.originalBlob=d,H||!p){if(p&&H){try{URL.revokeObjectURL(p)}catch{}this.#c.delete(p)}let b=this.#y(t,URL.createObjectURL(d));this.#a.set(w,b),h.originalSrc=b}else h.originalSrc=p;else p?h.originalSrc=p:e.originalSrc?h.originalSrc=e.originalSrc:(h.originalSrc=h.src,h.blob&&(h.originalBlob=h.blob));n.push(h),a.push({pageId:e.id,page:e,srcBlob:c,origBlob:d})}if(this.#i.setRow("docs",t,{name:r.name||"",pages:JSON.stringify(s)}),this.#n.set(t,{id:t,name:r.name||"",pages:n}),await this.#o(),this.#t)return this.#e?.saveDoc(t,r);let o=null;if(this.#r)try{o=await this.#r.getDirectoryHandle(t,{create:!0})}catch(e){console.warn(`[OpfsAdapter] Failed to get doc directory "${t}":`,e)}if(o)for(let e of a){let{pageId:c,page:g,srcBlob:y,origBlob:f}=e;if(!y&&typeof g.src=="string"&&g.src.startsWith("blob:"))try{y=await(await fetch(g.src)).blob()}catch{}if(y)try{let h=await(await o.getFileHandle(`${c}.bin`,{create:!0})).createWritable();await h.write(y),await h.close()}catch(w){console.warn(`[OpfsAdapter] Failed writing page file "${c}.bin":`,w)}if(!f&&typeof g.originalSrc=="string"&&g.originalSrc.startsWith("blob:"))try{f=await(await fetch(g.originalSrc)).blob()}catch{}if(f)try{let h=await(await o.getFileHandle(`${c}-original.bin`,{create:!0})).createWritable();await h.write(f),await h.close()}catch{}}}async deleteDoc(t){if(this.#t)return this.#e?.deleteDoc(t);if(this.#i.delRow("docs",t),this.#n.delete(t),this.revokeDocUrls(t),await this.#o(),this.#r)try{await this.#r.removeEntry(t,{recursive:!0})}catch{}}async renameDoc(t,r){if(this.#t)return this.#e?.renameDoc(t,r);if(!this.#i.hasRow("docs",t))throw new Error(`Document "${t}" not found`);this.#i.setCell("docs",t,"name",r),this.#n.has(t)&&(this.#n.get(t).name=r)}async savePage(t,r,i){if(this.#t)return this.#e?.savePage(t,r,i);await this.#o();let s=await this.getDoc(t);if(!s)throw new Error(`Document ${t} not found`);let n=s.pages.findIndex(e=>e.id===r),a;if(n>=0)typeof i=="object"&&i!==null&&!(i instanceof Blob)?s.pages[n]={...s.pages[n],...i}:s.pages[n]={...s.pages[n],src:i,blob:i instanceof Blob?i:void 0},a=s.pages[n];else{let e=typeof i=="object"&&i!==null&&!(i instanceof Blob)?{id:r,...i}:{id:r,src:i,blob:i instanceof Blob?i:void 0};s.pages.push(e),a=e}let o=S(a.src)||(a.src instanceof Blob?a.src:null)||(a.blob instanceof Blob?a.blob:null);if(!o&&typeof a.src=="string"&&a.src.startsWith("blob:"))try{o=await(await fetch(a.src)).blob()}catch{}if(o&&this.#r)try{let g=await(await(await this.#r.getDirectoryHandle(t,{create:!0})).getFileHandle(`${r}.bin`,{create:!0})).createWritable();await g.write(o),await g.close()}catch(e){console.warn(`[OpfsAdapter] Failed writing page file "${r}.bin":`,e)}await this.saveDoc(t,s)}async getPage(t,r){if(this.#t)return this.#e?.getPage(t,r);if(await this.#o(),this.#r)try{return await(await(await this.#r.getDirectoryHandle(t)).getFileHandle(`${r}.bin`)).getFile()}catch{}let i=this.getDocSync(t);if(!i)return null;let s=i.pages.find(n=>n.id===r);return s?s.content??s.src??s:null}async deletePage(t,r){if(this.#t)return this.#e?.deletePage(t,r);await this.#o();let i=this.getDocSync(t);if(!i)return;if(i.pages=i.pages.filter(a=>a.id!==r),this.#i.setRow("docs",t,{name:i.name||"",pages:JSON.stringify(i.pages)}),this.#r){try{await(await this.#r.getDirectoryHandle(t)).removeEntry(`${r}.bin`)}catch{}try{await(await this.#r.getDirectoryHandle(t)).removeEntry(`${r}-original.bin`)}catch{}}let s=`${t}:${r}`;if(this.#s.has(s)){try{URL.revokeObjectURL(this.#s.get(s))}catch{}this.#s.delete(s)}let n=`${t}:${r}:orig`;if(this.#a.has(n)){try{URL.revokeObjectURL(this.#a.get(n))}catch{}this.#a.delete(n)}this.#n.delete(t)}subscribe(t){if(this.#t)return this.#e?.subscribe(t);let r=this.#i.addTableListener("docs",t);return()=>{this.#i.delListener(r)}}#f(t){if(Array.isArray(t))return t;if(typeof t=="string")try{return JSON.parse(t)}catch{return[]}return[]}};function M(l={}){return l.forceMemory?new U:l.forceIndexedDb?new m(l):l.forceOpfs?new v(l):typeof navigator<"u"&&navigator.storage&&typeof navigator.storage.getDirectory=="function"?new v(l):typeof indexedDB<"u"?new m(l):new U}export{$ as a,v as b,M as c};
2
- //# sourceMappingURL=chunk-K4NR6OAC.js.map
@@ -1,2 +0,0 @@
1
- import{a as xr}from"./chunk-DIU5BGU5.js";var Ft=t=>typeof t;var Er=Ft(""),gn=Ft(!0),Hr=Ft(0),fn=Ft(Ft),Fe="type",Qt="default",vs="Listener",Mr="Result",Cs="add",zt="Has",me="Ids",Jt="Table",jr=Jt+"s",bn=Jt+me,ae="Row",Ar=ae+"Count",Or=ae+me,wn="Sorted"+ae+me,Se="Cell",ze=Se+me,_e="Value",Dr=_e+"s",pn=_e+me,at=t=>""+t;var yn=(t,e="",r)=>t.split(e,r),Ts=globalThis,ts=Math,ps=ts.max,ys=ts.min,Sn=ts.floor,Wr=isFinite,B=t=>t==null,it=(t,e,r)=>B(t)?r?.():e(t),Nr=t=>t==Er||t==gn,Ln=t=>Ft(t)==Er,jt=t=>Ft(t)==fn,ie=t=>Array.isArray(t),Is=(t,e,r)=>t.slice(e,r),xt=t=>t.length,Jr=()=>{};var Ss=async(t,e,r)=>{try{return await t()}catch(o){e?.(o)}},ks=(t,e)=>t.includes(e),Ge=(t,e)=>t.every(e),Fr=(t,e)=>xt(t)===xt(e)&&Ge(t,((r,o)=>e[o]===r)),Vr=(t,e)=>Ge(t,((r,o)=>o==0||e(t[o-1],r)<=0)),xs=(t,e)=>t.sort(e),Tt=(t,e)=>t.forEach(e),Yt=(t,e)=>t.map(e),$r=t=>Kr(t,((e,r)=>e+r),0),Le=t=>xt(t)==0,Kr=(t,e,r)=>t.reduce(e,r),Ct=(t,...e)=>t.push(...e),Ur=t=>t.pop(),qr=t=>t.shift(),ne=t=>{let e=Ft(t);return Nr(e)||e==Hr&&Wr(t)?e:void 0};var Ye=(t,e,r,o,l)=>B(l)?t.delCell(e,r,o,!0):t.setCell(e,r,o,l),Ms=(t,e,r)=>B(r)?t.delValue(e):t.setValue(e,r),$s=t=>e=>Kr(le(e),((r,o)=>r+t(o)),0),ce=t=>t?.size??0,Xt=$s(ce),Bt=$s(Xt),Ls=$s(Bt),dt=(t,e)=>t?.has(e)??!1,$=t=>B(t)||ce(t)==0,le=t=>[...t?.values()??[]],oe=t=>t.clear(),V=(t,e)=>t?.forEach(e),Vt=(t,e)=>t?.delete(e),Kt=Object,Pr=t=>Kt.getPrototypeOf(t),Rn=Kt.isFrozen,Qr=Kt.entries,Xe=t=>!B(t)&&it(Pr(t),(e=>e==Kt.prototype||B(Pr(e))),(()=>!0)),mn=Kt.keys,de=Kt.freeze,vn=(t=[])=>Kt.fromEntries(t),ye=(t,e)=>e in t,zr=(t,e)=>(delete t[e],t),Cn=(t,e)=>Tt(Qr(t),(([r,o])=>e(o,r))),Pt=(t,e)=>vn(((r,o)=>Yt(Qr(r),(([l,c])=>o(c,l))))(t,((r,o)=>[o,e(r,o)]))),Dt=t=>Xe(t)&&(e=>xt(mn(e)))(t)==0;var Wt=(t,e,r,o=0)=>B(t)||!Xe(t)||!o&&Dt(t)||Rn(t)?(r?.(),!1):(Cn(t,((l,c)=>{e(l,c)||zr(t,c)})),!!o||!Dt(t)),w=t=>new Map(t),Gt=t=>[...t?.keys()??[]],g=(t,e)=>t?.get(e),wt=(t,e)=>V(t,((r,o)=>e(o,r))),k=(t,e,r)=>B(r)?(Vt(t,e),t):t?.set(e,r),ct=(t,e,r,o)=>(dt(t,e)?o?.(g(t,e)):k(t,e,r()),g(t,e)),_t=(t,e,r,o=k)=>(Pt(e,((l,c)=>r(t,c,l))),wt(t,(l=>ye(e,l)?0:o(t,l))),t),vt=(t,e,r,o)=>{let l={};return V(t,((c,u)=>{if(!r?.(c,u)){let i=e?e(c,u):c;o?.(i)||(l[u]=i)}})),l},js=(t,e,r)=>vt(t,(o=>vt(o,e,r)),$,Dt),Ke=(t,e,r)=>vt(t,(o=>js(o,e,r)),$,Dt),Nt=(t,e)=>{let r=w();return V(t,((o,l)=>r.set(l,e?.(o)??o))),r},Ds=t=>Nt(t,Nt),Rs=t=>Nt(t,Ds),Re=(t,e,r,o,l=0)=>it((r?ct:g)(t,e[l],l>xt(e)-2?r:w),(c=>{if(l>xt(e)-2)return o?.(c)&&k(t,e[l]),c;let u=Re(c,e,r,o,l+1);return $(c)&&k(t,e[l]),u})),pt=t=>new Set(ie(t)||B(t)?t:[t]),ut=(t,e)=>t?.add(e),es=(t,e,r,o,l)=>{let c=t.hasRow,u=w(),i=w(),p=w(),S=w(),m=w(),b=w(),E=(L,x,..._)=>{let I=ct(b,L,pt);return Tt(_,(A=>ut(I,A)&&x&&t.callListener(A))),_},T=(L,...x)=>it(g(b,L),(_=>{Tt(Le(x)?le(_):x,(I=>{t.delListener(I),Vt(_,I)})),$(_)&&k(b,L)})),F=(L,x)=>{k(u,L,x),dt(i,L)||(k(i,L,e()),k(S,L,w()),k(m,L,w()),l(p))},Z=L=>{k(u,L),k(i,L),k(S,L),k(m,L),T(L),l(p)};return[()=>t,()=>Gt(u),L=>wt(i,L),L=>dt(i,L),L=>g(u,L),L=>g(i,L),(L,x)=>k(i,L,x),F,(L,x,_,I,A)=>{F(L,x);let st=w(),y=w(),h=g(S,L),C=g(m,L),W=P=>{let q=lt=>t.getCell(x,P,lt),nt=g(h,P),ot=c(x,P)?r(I(q,P)):void 0;if(nt===ot||ie(nt)&&ie(ot)&&Fr(nt,ot)||k(st,P,[nt,ot]),!B(A)){let lt=g(C,P),N=c(x,P)?A(q,P):void 0;lt!=N&&k(y,P,N)}},K=P=>{_((()=>{V(st,(([,q],nt)=>k(h,nt,q))),V(y,((q,nt)=>k(C,nt,q)))}),st,y,h,C,P),oe(st),oe(y)};wt(h,W),t.hasTable(x)&&Tt(t.getRowIds(x),(P=>{dt(h,P)||W(P)})),K(!0),T(L),E(L,0,t.addRowListener(x,null,((P,q,nt)=>W(nt))),t.addTableListener(x,(()=>K())))},Z,L=>o(L,p),()=>wt(b,Z),E,T]},Ze=(t,e)=>Ln(t)?r=>r(t):t??(()=>e??""),ve=(t,e)=>{let r=new WeakMap;return o=>{r.has(o)||r.set(o,t(o));let l=r.get(o);return e?.(l),l}},Tn=/^\d+$/,_r=()=>{let t=[],e=0;return[r=>(r?qr(t):null)??""+e++,r=>{Tn.test(r)&&xt(t)<1e3&&Ct(t,r)}]},Ce=t=>{let e,[r,o]=_r(),l=w();return[(c,u,i,p=[],S=()=>[])=>{e??=t();let m=r(1);return k(l,m,[c,u,i,p,S]),ut(Re(u,i??[""],pt),m),m},(c,u,...i)=>Tt(((p,S=[""])=>{let m=[],b=(E,T)=>T==xt(S)?Ct(m,E):S[T]===null?V(E,(F=>b(F,T+1))):Tt([S[T],null],(F=>b(g(E,F),T+1)));return b(p,0),m})(c,u),(p=>V(p,(S=>g(l,S)[0](e,...u??[],...i))))),c=>it(g(l,c),(([,u,i])=>(Re(u,i??[""],void 0,(p=>(Vt(p,c),$(p)?1:0))),k(l,c),o(c),i))),c=>it(g(l,c),(([u,,i=[],p,S])=>{let m=(...b)=>{let E=xt(b);E==xt(i)?u(e,...b,...S(b)):B(i[E])?Tt(p[E]?.(...b)??[],(T=>m(...b,T))):m(...b,i[E])};m()}))]},to=ve((t=>{let e,r,o,l=100,c=w(),u=w(),i=1,p=w(),S=w(),[m,b,E]=Ce((()=>N)),T=w(),F=w(),Z=[],L=[],x=(R,D)=>{i=0,t.transaction((()=>{let[et,G]=g(T,D);V(et,((j,H)=>V(j,((J,Y)=>V(J,((O,Q)=>Ye(t,H,Y,Q,O[R]))))))),V(G,((j,H)=>Ms(t,H,j[R])))})),i=1},_=R=>{k(T,R),k(F,R),b(S,[R])},I=(R,D)=>Tt(((et,G)=>et.splice(0,G))(R,D??xt(R)),_),A=()=>I(Z,xt(Z)-l),st=()=>it(e,(()=>{Ct(Z,e),A(),I(L),e=void 0,o=1})),y=()=>{e=Ur(Z),o=1},h,C,W=(R="")=>(B(e)&&(e=""+r++,k(T,e,[c,u]),ot(e,R),c=w(),u=w(),o=1),e),K=()=>{Le(Z)||(((R,...D)=>{R.unshift(...D)})(L,W()),x(0,e),e=Ur(Z),o=1)},P=()=>{Le(L)||(Ct(Z,e),e=qr(L),x(1,e),o=1)},q=()=>{o&&(b(p),o=0)},nt=R=>{let D=W(R);return q(),D},ot=(R,D)=>(lt(R)&&g(F,R)!==D&&(k(F,R,D),b(S,[R])),N),lt=R=>dt(T,R),N={setSize:R=>(l=R,A(),N),addCheckpoint:nt,setCheckpoint:ot,getStore:()=>t,getCheckpointIds:()=>[[...Z],e,[...L]],forEachCheckpoint:R=>wt(F,R),hasCheckpoint:lt,getCheckpoint:R=>g(F,R),goBackward:()=>(K(),q(),N),goForward:()=>(P(),q(),N),goTo:R=>{let D=ks(Z,R)?K:ks(L,R)?P:null;for(;!B(D)&&R!=e;)D();return q(),N},addCheckpointIdsListener:R=>m(R,p),addCheckpointListener:(R,D)=>m(D,S,[R]),delListener:R=>(E(R),N),clear:()=>(I(Z),I(L),B(e)||_(e),e=void 0,r=0,nt(),N),clearForward:()=>(Le(L)||(I(L),b(p)),N),destroy:()=>{t.delListener(h),t.delListener(C)},getListenerStats:()=>({checkpointIds:Xt(p),checkpoint:Xt(S)}),_registerListeners:()=>{h=t.addCellListener(null,null,null,((R,D,et,G,j,H)=>{if(i){st();let J=ct(c,D,w),Y=ct(J,et,w),O=ct(Y,G,(()=>[H,void 0]));O[1]=j,O[0]===j&&$(k(Y,G))&&$(k(J,et))&&$(k(c,D))&&y(),q()}})),C=t.addValueListener(null,((R,D,et,G)=>{if(i){st();let j=ct(u,D,(()=>[G,void 0]));j[1]=et,j[0]===et&&$(k(u,D))&&y(),q()}}))}};return de(N.clear())}),(t=>t._registerListeners())),In=yn("-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz"),eo=w(Yt(In,((t,e)=>[t,e])));var so=Ts.crypto?t=>Ts.crypto.getRandomValues(t):t=>Yt(t,(()=>Sn(256*ts.random())));var kn=JSON.stringify,ms=JSON.parse,re=t=>kn(t,((e,r)=>{return o=Map,r instanceof o?Kt.fromEntries([...r]):r;var o})),ro=new Ts.TextEncoder;var no=2**36,oo=2**30,ao=2**24,io=2**18;var Gr=(t,e)=>(t??0)<(e??0)?-1:1,lo=ve((t=>{let e=w(),r=w(),[o,l,c]=Ce((()=>_)),[u,i,p,S,m,b,E,,T,F,Z,L]=es(t,w,(I=>B(I)?"":ie(I)?Yt(I,at):at(I)),o,l),x=(I,A,st)=>{let y=m(I);V(st,((h,C)=>A(C,(W=>V(h,(K=>W(K,(P=>t.forEachCell(y,K,P)))))))))},_={setIndexDefinition:(I,A,st,y,h,C=Gr)=>{let W=B(h)?void 0:([K],[P])=>h(K,P);return T(I,A,((K,P,q,nt,ot,lt)=>{let N=0,R=pt(),D=pt(),et=b(I);if(V(P,(([G,j],H)=>{let J=pt(G),Y=pt(j);V(J,(O=>Vt(Y,O)?Vt(J,O):0)),V(J,(O=>{ut(R,O),it(g(et,O),(Q=>{Vt(Q,H),$(Q)&&(k(et,O),N=1)}))})),V(Y,(O=>{ut(R,O),dt(et,O)||(k(et,O,pt()),N=1),ut(g(et,O),H),B(y)||ut(D,O)}))})),K(),$(ot)||(lt?wt(et,(G=>ut(D,G))):wt(q,(G=>it(g(nt,G),(j=>Tt(ie(j)?j:[j],(H=>ut(D,H))))))),V(D,(G=>{let j=(J,Y)=>C(g(ot,J),g(ot,Y),G),H=[...g(et,G)];Vr(H,j)||(k(et,G,pt(xs(H,j))),ut(R,G))}))),(N||lt)&&!B(W)){let G=[...et];Vr(G,W)||(E(I,w(xs(G,W))),N=1)}N&&l(e,[I]),V(R,(G=>l(r,[I,G])))}),Ze(st),it(y,Ze)),_},delIndexDefinition:I=>(F(I),_),getStore:u,getIndexIds:i,forEachIndex:I=>p(((A,st)=>I(A,(y=>x(A,y,st))))),forEachSlice:(I,A)=>x(I,A,b(I)),hasIndex:S,hasSlice:(I,A)=>dt(b(I),A),getTableId:m,getSliceIds:I=>Gt(b(I)),getSliceRowIds:(I,A)=>le(g(b(I),A)),addIndexIdsListener:Z,addSliceIdsListener:(I,A)=>o(A,e,[I]),addSliceRowIdsListener:(I,A,st)=>o(st,r,[I,A]),delListener:I=>(c(I),_),destroy:L,getListenerStats:()=>({sliceIds:Xt(e),sliceRowIds:Bt(r)})};return de(_)}));var qe=t=>[t,t],ft=(t,e=Xt)=>e(t[0])+e(t[1]),bt=()=>[w(),w()],Br=t=>[...t],Qe=([t,e])=>t===e,pe=(t,e,r)=>k(t,e,g(t,e)==-r?void 0:r),Us=()=>{let t,e,r=!1,o=!1,l=0,c=[],u=w(),i=w(),p=w(),S=w(),m=w(),b=w(),E=w(),T=w(),F=w(),Z=w(),L=w(),x=w(),_=w(),I=w(),A=pt(),st=w(),y=w(),h=w(),C=w(),W=bt(),K=bt(),P=bt(),q=bt(),nt=bt(),ot=bt(),lt=bt(),N=bt(),R=bt(),D=bt(),et=bt(),G=bt(),j=bt(),H=bt(),J=bt(),Y=bt(),O=bt(),Q=bt(),M=bt(),rt=bt(),ht=bt(),mt=bt(),St=w(),Lt=bt(),[yt,tt,It,Et]=Ce((()=>Rt)),Ht=s=>{if(!Wt(s,((a,d)=>ks([Fe,Qt],d))))return!1;let n=s[Fe];return!(!Nr(n)&&n!=Hr)&&(ne(s[Qt])!=n&&zr(s,Qt),!0)},cs=ie,ke=(s,n)=>(!t||dt(L,n)||At(n))&&Wt(s,((a,d)=>qt(n,d,a)),(()=>At(n))),qt=(s,n,a,d)=>Wt(d?a:Ns(a,s,n),((f,v)=>it(xe(s,n,v,f),(U=>(a[v]=U,!0)),(()=>!1))),(()=>At(s,n))),xe=(s,n,a,d)=>t?it(g(g(L,s),a),(f=>ne(d)!=f[Fe]?At(s,n,a,d,f[Qt]):d),(()=>At(s,n,a,d))):B(ne(d))?At(s,n,a,d):d,ue=(s,n)=>Wt(n?s:hn(s),((a,d)=>it(Ws(d,a),(f=>(s[d]=f,!0)),(()=>!1))),(()=>fe())),Ws=(s,n)=>e?it(g(_,s),(a=>ne(n)!=a[Fe]?fe(s,n,a[Qt]):n),(()=>fe(s,n))):B(ne(n))?fe(s,n):n,Ns=(s,n,a)=>(it(g(x,n),(([d,f])=>{V(d,((v,U)=>{ye(s,U)||(s[U]=v)})),V(f,(v=>{ye(s,v)||At(n,a,v)}))})),s),hn=s=>(e&&(V(I,((n,a)=>{ye(s,a)||(s[a]=n)})),V(A,(n=>{ye(s,n)||fe(n)}))),s),Js=s=>_t(L,s,((n,a,d)=>{let f=w(),v=pt();_t(ct(L,a,w),d,((U,z,X)=>{k(U,z,X),it(X[Qt],(Ut=>k(f,z,Ut)),(()=>ut(v,z)))})),k(x,a,[f,v])}),((n,a)=>{k(L,a),k(x,a)})),Fs=s=>_t(_,s,((n,a,d)=>{k(_,a,d),it(d[Qt],(f=>k(I,a,f)),(()=>ut(A,a)))}),((n,a)=>{k(_,a),k(I,a),Vt(A,a)})),Ks=s=>Dt(s)?Oe():He(s),qs=s=>_t(h,s,((n,a,d)=>Me(a,d)),((n,a)=>Gs(a))),Me=(s,n)=>_t(ct(h,s,(()=>(tr(s,1),k(st,s,_r()),k(y,s,w()),w()))),n,((a,d,f)=>ge(s,a,d,f)),((a,d)=>Ys(s,a,d))),ge=(s,n,a,d,f)=>_t(ct(n,a,(()=>(er(s,a,1),w()))),d,((v,U,z)=>ds(s,a,v,U,z)),((v,U)=>Xs(s,n,a,v,U,f))),ds=(s,n,a,d,f)=>{dt(a,d)||sr(s,n,d,1);let v=g(a,d);f!==v&&(rr(s,n,d,v,f),k(a,d,f))},Qs=(s,n,a,d,f)=>it(g(n,a),(v=>ds(s,a,v,d,f)),(()=>ge(s,n,a,Ns({[d]:f},s,a)))),zs=s=>Dt(s)?We():Ae(s),_s=s=>_t(C,s,((n,a,d)=>je(a,d)),((n,a)=>Zs(a))),je=(s,n)=>{dt(C,s)||nr(s,1);let a=g(C,s);n!==a&&(or(s,a,n),k(C,s,n))},De=s=>g(h,s)??Me(s,{}),Gs=s=>Me(s,{}),Ys=(s,n,a)=>{let[,d]=g(st,s);d(a),ge(s,n,a,{},!0)},Xs=(s,n,a,d,f,v)=>{let U=g(g(x,s)?.[0],f);if(!B(U)&&!v)return ds(s,a,d,f,U);let z=X=>{rr(s,a,X,g(d,X)),sr(s,a,X,-1),k(d,X)};B(U)?z(f):wt(d,z),$(d)&&(er(s,a,-1),$(k(n,a))&&(tr(s,-1),k(h,s),k(st,s),k(y,s)))},Zs=s=>{let n=g(I,s);if(!B(n))return je(s,n);or(s,g(C,s)),nr(s,-1),k(C,s)},tr=(s,n)=>pe(u,s,n),er=(s,n,a)=>pe(ct(S,s,w),n,a)&&k(p,s,ct(p,s,(()=>0))+a),sr=(s,n,a,d)=>{let f=g(y,s),v=g(f,a)??0;(v==0&&d==1||v==1&&d==-1)&&pe(ct(i,s,w),a,d),k(f,a,v!=-d?v+d:null),pe(ct(ct(m,s,w),n,w),a,d)},rr=(s,n,a,d,f)=>{ct(ct(ct(b,s,w),n,w),a,(()=>[d,0]))[1]=f,c[3]?.(s,n,a,f)},nr=(s,n)=>pe(E,s,n),or=(s,n,a)=>{ct(T,s,(()=>[n,0]))[1]=a,c[4]?.(s,a)},At=(s,n,a,d,f)=>(Ct(ct(ct(ct(F,s,w),n,w),a,(()=>[])),d),f),fe=(s,n,a)=>(Ct(ct(Z,s,(()=>[])),n),a),Ve=(s,n,a)=>it(g(g(g(b,s),n),a),(([d,f])=>[!0,d,f]),(()=>[!1,...qe(Ue(s,n,a))])),ar=s=>it(g(T,s),(([n,a])=>[!0,n,a]),(()=>[!1,...qe(Pe(s))])),ir=s=>$(F)||$(Y[s])?0:V(s?Rs(F):F,((n,a)=>V(n,((d,f)=>V(d,((v,U)=>tt(Y[s],[a,f,U],v))))))),lr=s=>$(Z)||$(O[s])?0:V(s?Nt(Z):Z,((n,a)=>tt(O[s],[a],n))),be=(s,n,a,d)=>{if(!$(s))return tt(n,d,(()=>vt(s))),wt(s,((f,v)=>tt(a,[...d??[],f],v==1))),1},cr=s=>{let n=Be();n!=r&&tt(W[s],void 0,n);let a=$(D[s]),d=$(j[s])&&$(H[s])&&$(R[s])&&$(et[s])&&$(ot[s])&&$(lt[s])&&$(N[s])&&a&&$(P[s])&&$(q[s]),f=$(J[s])&&$(G[s])&&$(nt[s])&&$(K[s]);if(!d||!f){let v=s?[Nt(u),Ds(i),Nt(p),Ds(S),Rs(m),Rs(b)]:[u,i,p,S,m,b];if(!d){be(v[0],P[s],q[s]),V(v[1],((z,X)=>be(z,ot[s],lt[s],[X]))),V(v[2],((z,X)=>{z!=0&&tt(N[s],[X],gr(X))}));let U=pt();V(v[3],((z,X)=>{be(z,R[s],et[s],[X])&&!a&&(tt(D[s],[X,null]),ut(U,X))})),a||V(v[5],((z,X)=>{if(!dt(U,X)){let Ut=pt();V(z,(Ot=>V(Ot,(([Ne,Je],we)=>Je!==Ne?ut(Ut,we):Vt(Ot,we))))),V(Ut,(Ot=>tt(D[s],[X,Ot])))}})),V(v[4],((z,X)=>V(z,((Ut,Ot)=>be(Ut,j[s],H[s],[X,Ot])))))}if(!f){let U;V(v[5],((z,X)=>{let Ut;V(z,((Ot,Ne)=>{let Je;V(Ot,(([we,kr],un)=>{kr!==we&&(tt(J[s],[X,Ne,un],kr,we,Ve),U=Ut=Je=1)})),Je&&tt(G[s],[X,Ne],Ve)})),Ut&&tt(nt[s],[X],Ve)})),U&&tt(K[s],void 0,Ve)}}},dr=s=>{let n=Ee();n!=o&&tt(Q[s],void 0,n);let a=$(rt[s])&&$(ht[s]),d=$(mt[s])&&$(M[s]);if(!a||!d){let f=s?[Nt(E),Nt(T)]:[E,T];if(a||be(f[0],rt[s],ht[s]),!d){let v;V(f[1],(([U,z],X)=>{z!==U&&(tt(mt[s],[X],z,U,ar),v=1)})),v&&tt(M[s],void 0,ar)}}},gt=(s,...n)=>(ws((()=>s(...Yt(n,at)))),Rt),hr=(s,n,a,d,f)=>{let v=$e(s,n,...a);return yt((()=>{let U=$e(s,n,...a);Fr(U,v)||(v=U,d(Rt,s,n,...a,v))}),D[f?1:0],[s,n],[kt])},hs=()=>Ke(h),kt=()=>Gt(h),ur=s=>Gt(g(y,at(s))),gr=s=>ce(g(h,at(s))),se=s=>Gt(g(h,at(s))),$e=(s,n,a,d=0,f)=>{return Xe(s)?$e(s.tableId,s.cellId,s.descending,s.offset,s.limit):Yt(Is(xs((v=g(h,at(s)),U=(z,X)=>[B(n)?X:g(z,at(n)),X],Yt([...v?.entries()??[]],(([z,X])=>U(X,z)))),(([z],[X])=>Gr(z,X)*(a?-1:1))),d,B(f)?f:d+f),(([,z])=>z));var v,U},us=(s,n)=>Gt(g(g(h,at(s)),at(n))),Ue=(s,n,a)=>g(g(g(h,at(s)),at(n)),at(a)),gs=()=>vt(C),fs=()=>Gt(C),Pe=s=>g(C,at(s)),Be=()=>!$(h),fr=s=>dt(h,at(s)),br=(s,n)=>dt(g(y,at(s)),at(n)),wr=(s,n)=>dt(g(h,at(s)),at(n)),pr=(s,n,a)=>dt(g(g(h,at(s)),at(n)),at(a)),Ee=()=>!$(C),yr=s=>dt(C,at(s)),He=s=>gt((()=>(n=>Wt(n,ke,At))(s)?qs(s):0)),Ae=s=>gt((()=>ue(s)?_s(s):0)),Sr=s=>(Ss((()=>Ks(ms(s)))),Rt),Lr=s=>gt((()=>{if((t=Wt(s,(n=>Wt(n,Ht))))&&(Js(s),!$(h))){let n=hs();Oe(),He(n)}})),Rr=s=>gt((()=>{if(e=(n=>Wt(n,Ht))(s)){let n=gs();bs(),We(),e=!0,Fs(s),Ae(n)}})),Oe=()=>gt((()=>qs({}))),mr=s=>gt((n=>dt(h,n)?Gs(n):0),s),vr=(s,n)=>gt(((a,d)=>it(g(h,a),(f=>dt(f,d)?Ys(a,f,d):0))),s,n),We=()=>gt((()=>_s({}))),Cr=()=>gt((()=>{Js({}),t=!1})),bs=()=>gt((()=>{Fs({}),e=!1})),ws=(s,n)=>{if(l!=-1){Tr();let a=s();return Ir(n),a}},Tr=()=>(l!=-1&&l++,l==1&&(c[0]?.(),tt(St)),Rt),Ir=s=>(l>0&&(l--,l==0&&(l=1,ir(1),$(b)||cr(1),lr(1),$(T)||dr(1),s?.(Rt)&&(V(b,((n,a)=>V(n,((d,f)=>V(d,(([v],U)=>Ye(Rt,a,f,U,v))))))),oe(b),V(T,(([n],a)=>Ms(Rt,a,n))),oe(T)),tt(Lt[0],void 0),l=-1,ir(0),$(b)||cr(0),lr(0),$(T)||dr(0),c[1]?.(),tt(Lt[1],void 0),c[2]?.(),l=0,r=Be(),o=Ee(),Tt([u,i,p,S,m,b,F,E,T,Z],oe))),Rt),Rt={getContent:()=>[hs(),gs()],getTables:hs,getTableIds:kt,getTable:s=>js(g(h,at(s))),getTableCellIds:ur,getRowCount:gr,getRowIds:se,getSortedRowIds:$e,getRow:(s,n)=>vt(g(g(h,at(s)),at(n))),getCellIds:us,getCell:Ue,getValues:gs,getValueIds:fs,getValue:Pe,hasTables:Be,hasTable:fr,hasTableCell:br,hasRow:wr,hasCell:pr,hasValues:Ee,hasValue:yr,getTablesJson:()=>re(h),getValuesJson:()=>re(C),getJson:()=>re([h,C]),getTablesSchemaJson:()=>re(L),getValuesSchemaJson:()=>re(_),getSchemaJson:()=>re([L,_]),hasTablesSchema:()=>t,hasValuesSchema:()=>e,setContent:s=>gt((()=>{let n=jt(s)?s():s;cs(n)&&(([a,d])=>{(Dt(a)?Oe:He)(a),(Dt(d)?We:Ae)(d)})(n)})),setTables:He,setTable:(s,n)=>gt((a=>ke(n,a)?Me(a,n):0),s),setRow:(s,n,a)=>gt(((d,f)=>qt(d,f,a)?ge(d,De(d),f,a):0),s,n),addRow:(s,n,a=!0)=>ws((()=>{let d;return qt(s,d,n)&&(s=at(s),ge(s,De(s),d=((f,v)=>{let[U]=g(st,f),z;do z=U(v);while(dt(g(h,f),z));return z})(s,a?1:0),n)),d})),setPartialRow:(s,n,a)=>gt(((d,f)=>{if(qt(d,f,a,1)){let v=De(d);Pt(a,((U,z)=>Qs(d,v,f,z,U)))}}),s,n),setCell:(s,n,a,d)=>gt(((f,v,U)=>it(xe(f,v,U,jt(d)?d(Ue(f,v,U)):d),(z=>Qs(f,De(f),v,U,z)))),s,n,a),setValues:Ae,setPartialValues:s=>gt((()=>ue(s,1)?Pt(s,((n,a)=>je(a,n))):0)),setValue:(s,n)=>gt((a=>it(Ws(a,jt(n)?n(Pe(a)):n),(d=>je(a,d)))),s),applyChanges:s=>gt((()=>{Pt(s[0],((n,a)=>B(n)?mr(a):Pt(n,((d,f)=>B(d)?vr(a,f):Pt(d,((v,U)=>Ye(Rt,a,f,U,v))))))),Pt(s[1],((n,a)=>Ms(Rt,a,n)))})),setTablesJson:Sr,setValuesJson:s=>(Ss((()=>zs(ms(s)))),Rt),setJson:s=>gt((()=>Ss((()=>{let[n,a]=ms(s);Ks(n),zs(a)}),(()=>Sr(s))))),setTablesSchema:Lr,setValuesSchema:Rr,setSchema:(s,n)=>gt((()=>{Lr(s),Rr(n)})),delTables:Oe,delTable:mr,delRow:vr,delCell:(s,n,a,d)=>gt(((f,v,U)=>it(g(h,f),(z=>it(g(z,v),(X=>dt(X,U)?Xs(f,z,v,X,U,d):0))))),s,n,a),delValues:We,delValue:s=>gt((n=>dt(C,n)?Zs(n):0),s),delTablesSchema:Cr,delValuesSchema:bs,delSchema:()=>gt((()=>{Cr(),bs()})),transaction:ws,startTransaction:Tr,getTransactionChanges:()=>[vt(b,((s,n)=>g(u,n)===-1?void 0:vt(s,((a,d)=>g(g(S,n),d)===-1?void 0:vt(a,(([,f])=>f),(f=>Qe(f)))),$,Dt)),$,Dt),vt(T,(([,s])=>s),(s=>Qe(s))),1],getTransactionLog:()=>[!$(b),!$(T),Ke(b,Br,Qe),Ke(F),vt(T,Br,Qe),vt(Z),vt(u),js(S),Ke(m),vt(E)],finishTransaction:Ir,forEachTable:s=>V(h,((n,a)=>s(a,(d=>V(n,((f,v)=>d(v,(U=>wt(f,U))))))))),forEachTableCell:(s,n)=>wt(g(y,at(s)),n),forEachRow:(s,n)=>V(g(h,at(s)),((a,d)=>n(d,(f=>wt(a,f))))),forEachCell:(s,n,a)=>wt(g(g(h,at(s)),at(n)),a),forEachValue:s=>wt(C,s),addSortedRowIdsListener:(s,n,a,d,f,v,U)=>Xe(s)?hr(s.tableId,s.cellId,[s.descending??!1,s.offset??0,s.limit],n,a):hr(s,n,[a,d,f],v,U),addStartTransactionListener:s=>yt(s,St),addWillFinishTransactionListener:s=>yt(s,Lt[0]),addDidFinishTransactionListener:s=>yt(s,Lt[1]),callListener:s=>(Et(s),Rt),delListener:s=>(It(s),Rt),getListenerStats:()=>({hasTables:ft(W),tables:ft(K),tableIds:ft(P),hasTable:ft(q),table:ft(nt),tableCellIds:ft(ot),hasTableCell:ft(lt,Bt),rowCount:ft(N),rowIds:ft(R),sortedRowIds:ft(D),hasRow:ft(et,Bt),row:ft(G,Bt),cellIds:ft(j,Bt),hasCell:ft(H,Ls),cell:ft(J,Ls),invalidCell:ft(Y,Ls),hasValues:ft(Q),values:ft(M),valueIds:ft(rt),hasValue:ft(ht),value:ft(mt),invalidValue:ft(O),transaction:Xt(St)+ft(Lt)}),isMergeable:()=>!1,createStore:Us,addListener:yt,callListeners:tt,setInternalListeners:(s,n,a,d,f)=>c=[s,n,a,d,f]};return Pt({[zt+jr]:[0,W,[],()=>[Be()]],[jr]:[0,K],[bn]:[0,P],[zt+Jt]:[1,q,[kt],s=>[fr(...s)]],[Jt]:[1,nt,[kt]],[Jt+ze]:[1,ot,[kt]],[zt+Jt+Se]:[2,lt,[kt,ur],s=>[br(...s)]],[Ar]:[1,N,[kt]],[Or]:[1,R,[kt]],[zt+ae]:[2,et,[kt,se],s=>[wr(...s)]],[ae]:[2,G,[kt,se]],[ze]:[2,j,[kt,se]],[zt+Se]:[3,H,[kt,se,us],s=>[pr(...s)]],[Se]:[3,J,[kt,se,us],s=>qe(Ue(...s))],InvalidCell:[3,Y],[zt+Dr]:[0,Q,[],()=>[Ee()]],[Dr]:[0,M],[pn]:[0,rt],[zt+_e]:[1,ht,[fs],s=>[yr(...s)]],[_e]:[1,mt,[fs],s=>qe(Pe(s[0]))],InvalidValue:[1,O]},(([s,n,a,d],f)=>{Rt[Cs+f+vs]=(...v)=>yt(v[s],n[v[s+1]?1:0],s>0?Is(v,0,s):void 0,a,d)})),de(Rt)};var Vs=w([["avg",[(t,e)=>$r(t)/e,(t,e,r)=>t+(e-t)/(r+1),(t,e,r)=>t+(t-e)/(r-1),(t,e,r,o)=>t+(e-r)/o]],["max",[t=>ps(...t),(t,e)=>ps(e,t),(t,e)=>e==t?void 0:t,(t,e,r)=>r==t?void 0:ps(e,t)]],["min",[t=>ys(...t),(t,e)=>ys(e,t),(t,e)=>e==t?void 0:t,(t,e,r)=>r==t?void 0:ys(e,t)]],["sum",[t=>$r(t),(t,e)=>t+e,(t,e)=>t-e,(t,e,r)=>t-r+e]]]),Yr=(t,e,r,o,l,c=!1)=>{if($(r))return;let[u,i,p,S]=l;return c||=B(t),V(o,(([m,b])=>{c||(t=B(m)?i?.(t,b,e++):B(b)?p?.(t,m,e--):S?.(t,b,m,e),c||=B(t))})),c?u(le(r),ce(r)):t},co=ve((t=>{let e=w(),[r,o,l]=Ce((()=>L)),[c,u,i,p,S,m,b,,E,T,F,Z]=es(t,Jr,(x=>isNaN(x)||B(x)||x===!0||x===!1||x===""?void 0:1*x),r,o),L={setMetricDefinition:(x,_,I,A,st,y,h)=>{let C=jt(I)?[I,st,y,h]:g(Vs,I)??g(Vs,"sum");return E(x,_,((W,K,P,q,nt,ot)=>{let lt=m(x),N=ce(q);ot||=B(lt),W();let R=Yr(lt,N,q,K,C,ot);Wr(R)||(R=void 0),R!=lt&&(b(x,R),o(e,[x],R,lt))}),Ze(A,1)),L},delMetricDefinition:x=>(T(x),L),getStore:c,getMetricIds:u,forEachMetric:i,hasMetric:p,getTableId:S,getMetric:m,addMetricIdsListener:F,addMetricListener:(x,_)=>r(_,e,[x]),delListener:x=>(l(x),L),destroy:Z,getListenerStats:()=>({metric:Xt(e)})};return de(L)})),ho=ve((t=>{let e=t.createStore,r=e(),o=e(),l=w(),{addListener:c,callListeners:u,delListener:i}=o,[p,S,m,b,E,,,T,,F,Z,L,x,_]=es(t,(()=>!0),Jr,c,u),I=(h,C,...W)=>Tt(W,(K=>ut(ct(ct(l,C,w),h,pt),K))),A=h=>{it(g(l,h),(C=>{wt(C,((W,K)=>V(K,(P=>W.delListener(P))))),oe(C)})),Tt([o,r],(C=>C.delTable(h)))},st=(h,C,W)=>I(C,h,C.addStartTransactionListener(W.startTransaction),C.addDidFinishTransactionListener((()=>W.finishTransaction()))),y={setQueryDefinition:(h,C,W)=>{T(h,C),A(h);let K=[],P=[[null,[C,null,null,[],w()]]],q=[],nt=[],ot=[];W({select:(j,H)=>{let J=jt(j)?[xt(K)+"",j]:[B(H)?j:H,Y=>Y(j,H)];return Ct(K,J),{as:Y=>J[0]=Y}},join:(j,H,J)=>{let Y=B(J)||jt(H)?null:H,O=B(Y)?H:J,Q=[j,[j,Y,jt(O)?O:M=>M(O),[],w()]];return Ct(P,Q),{as:M=>Q[0]=M}},where:(j,H,J)=>Ct(q,jt(j)?j:B(J)?Y=>Y(j)===H:Y=>Y(j,H)===J),group:(j,H,J,Y,O)=>{let Q=[j,[j,jt(H)?[H,J,Y,O]:g(Vs,H)??[(M,rt)=>rt]]];return Ct(nt,Q),{as:M=>Q[0]=M}},having:(j,H)=>Ct(ot,jt(j)?j:J=>J(j)===H)});let lt=w(K);if($(lt))return y;let N=w(P);wt(N,((j,[,H])=>it(g(N,H),(({3:J})=>B(j)?0:Ct(J,j)))));let R=w(nt),D=r;if($(R)&&Le(ot))D=o;else{st(h,D,o);let j=w();wt(R,((O,[Q,M])=>ut(ct(j,Q,pt),[O,M])));let H=pt();wt(lt,(O=>dt(j,O)?0:ut(H,O)));let J=w(),Y=(O,Q,M,rt)=>it(O,(([ht,mt,St,Lt])=>{wt(Q,((yt,[tt])=>{let It=ct(ht,yt,w),Et=g(It,M),Ht=rt?void 0:tt;if(Et!==Ht){let cs=pt([[Et,Ht]]),ke=ce(It);k(It,M,Ht),V(g(j,yt),(([qt,xe])=>{let ue=Yr(Lt[qt],ke,It,cs,xe);Lt[qt]=B(ne(ue))?null:ue}))}})),$(mt)||!Ge(ot,(yt=>yt((tt=>Lt[tt]))))?o.delRow(h,St):B(St)?O[2]=o.addRow(h,Lt):o.setRow(h,St,Lt)}));I(D,h,D.addRowListener(h,null,((O,Q,M,rt)=>{let ht=[],mt=[],St=w(),Lt=D.hasRow(h,M),yt=!Lt;V(H,(tt=>{let[It,Et,Ht]=rt(h,M,tt);Ct(ht,Et),Ct(mt,Ht),yt||=It})),wt(j,(tt=>{let[It,,Et]=rt(h,M,tt);(yt||It)&&k(St,tt,[Et])})),yt&&Y(Re(J,ht,void 0,(([,tt])=>(Vt(tt,M),$(tt)))),St,M,1),Lt&&Y(Re(J,mt,(()=>{let tt={};return V(H,(It=>tt[It]=D.getCell(h,M,It))),[w(),pt(),void 0,tt]}),(([,tt])=>{ut(tt,M)})),St,M)})))}st(h,t,D);let et=(j,H,J,Y)=>{let O=Q=>t.getCell(H,J,Q);Tt(Y,(Q=>{let[M,,rt,ht,mt]=g(N,Q),St=rt?.(O,j),[Lt,yt]=g(mt,j)??[];St!=Lt&&(B(yt)||_(h,yt),k(mt,j,B(St)?null:[St,...x(h,1,t.addRowListener(M,St,(()=>et(j,M,St,ht))))]))})),(Q=>{let M=(rt,ht)=>t.getCell(...B(ht)?[C,Q,rt]:rt===C?[C,Q,ht]:[g(N,rt)?.[0],g(g(N,rt)?.[4],Q)?.[0],ht]);D.transaction((()=>Ge(q,(rt=>rt(M)))?wt(lt,((rt,ht)=>Ye(D,h,Q,rt,ht(M,Q)))):D.delRow(h,Q)))})(j)},{3:G}=g(N,null);return D.transaction((()=>x(h,1,t.addRowListener(C,null,((j,H,J)=>{t.hasRow(C,J)?et(J,C,J,G):(D.delRow(h,J),V(N,(({4:Y})=>it(g(Y,J),(([,O])=>{_(h,O),k(Y,J)})))))}))))),y},delQueryDefinition:h=>(A(h),F(h),y),getStore:p,getQueryIds:S,forEachQuery:m,hasQuery:b,getTableId:E,addQueryIdsListener:h=>Z((()=>h(y))),delListener:h=>(i(h),y),destroy:L,getListenerStats:()=>{let{tables:h,tableIds:C,transaction:W,...K}=o.getListenerStats();return K}};return Pt({[Jt]:[1,1],[Jt+ze]:[0,1],[Ar]:[0,1],[Or]:[0,1],[wn]:[0,5],[ae]:[1,2],[ze]:[0,2],[Se]:[1,3]},(([h,C],W)=>{Tt(h?["get","has","forEach"]:["get"],(K=>y[K+Mr+W]=(...P)=>o[K+W](...P))),y[Cs+Mr+W+vs]=(...K)=>o[Cs+W+vs](...Is(K,0,C),((P,...q)=>K[C](y,...q)),!0)})),de(y)})),uo=ve((t=>{let e=w(),r=w(),o=w(),l=w(),[c,u,i]=Ce((()=>st)),[p,S,m,b,E,T,,,F,Z,L,x]=es(t,(()=>[w(),w(),w(),w()]),(y=>B(y)?void 0:y+""),c,u),_=(y,h,C)=>it(T(y),(([W,,K])=>{if(!dt(K,h)){let P=pt();if(E(y)!=A(y))ut(P,h);else{let q=h;for(;!B(q)&&!dt(P,q);)ut(P,q),q=g(W,q)}if(C)return P;k(K,h,P)}return g(K,h)})),I=(y,h)=>it(T(y),(([,,C])=>k(C,h))),A=y=>g(e,y),st={setRelationshipDefinition:(y,h,C,W)=>(k(e,y,C),F(y,h,((K,P)=>{let q=pt(),nt=pt(),ot=pt(),[lt,N]=T(y);V(P,(([R,D],et)=>{B(R)||(ut(nt,R),it(g(N,R),(G=>{Vt(G,et),$(G)&&k(N,R)}))),B(D)||(ut(nt,D),dt(N,D)||k(N,D,pt()),ut(g(N,D),et)),ut(q,et),k(lt,et,D),wt(g(l,y),(G=>{dt(_(y,G),et)&&ut(ot,G)}))})),K(),V(q,(R=>u(r,[y,R]))),V(nt,(R=>u(o,[y,R]))),V(ot,(R=>{I(y,R),u(l,[y,R])}))}),Ze(W)),st),delRelationshipDefinition:y=>(k(e,y),Z(y),st),getStore:p,getRelationshipIds:S,forEachRelationship:y=>m((h=>y(h,(C=>t.forEachRow(E(h),C))))),hasRelationship:b,getLocalTableId:E,getRemoteTableId:A,getRemoteRowId:(y,h)=>g(T(y)?.[0],h),getLocalRowIds:(y,h)=>le(g(T(y)?.[1],h)),getLinkedRowIds:(y,h)=>B(T(y))?[h]:le(_(y,h,!0)),addRelationshipIdsListener:L,addRemoteRowIdListener:(y,h,C)=>c(C,r,[y,h]),addLocalRowIdsListener:(y,h,C)=>c(C,o,[y,h]),addLinkedRowIdsListener:(y,h,C)=>(_(y,h),c(C,l,[y,h])),delListener:y=>(I(...i(y)??[]),st),destroy:x,getListenerStats:()=>({remoteRowId:Bt(r),localRowIds:Bt(o),linkedRowIds:Bt(l)})};return de(st)}));var tn=Promise,xn=globalThis,Xr=xn.window,Mn=1e3,jn=(t,e,r)=>setInterval(t,e*Mn),Dn=clearInterval,$t=t=>t==null,as=(t,e,r)=>$t(t)?r?.():e(t),Bs=t=>Array.isArray(t),te=t=>t.length,Vn=(t,e)=>t.test(e),en=t=>new tn(t),sn=async t=>tn.all(t),rn=t=>{throw new Error(t)},Zt=async(t,e,r)=>{try{return await t()}catch(o){e?.(o)}},Es=(t,e)=>t.forEach(e),Te=(t,e)=>t.map(e),$n=(t,e)=>t.splice(0,e),is=(t,...e)=>t.push(...e),nn=t=>t.shift(),he=Object,Zr=t=>he.getPrototypeOf(t),Un=he.entries,Pn=t=>!$t(t)&&as(Zr(t),e=>e==he.prototype||$t(Zr(e)),()=>!0),Bn=he.keys,En=he.freeze,Hn=(t=[])=>he.fromEntries(t),An=(t,e)=>e in t,On=(t,e)=>Te(Un(t),([r,o])=>e(o,r)),Wn=t=>te(Bn(t)),ss=t=>Pn(t)&&Wn(t)==0,Nn=t=>t?.size??0,Jn=(t,e)=>t?.has(e)??!1,on=t=>$t(t)||Nn(t)==0,an=(t,e)=>t?.forEach(e),ln=(t,e)=>t?.delete(e),Ie=t=>new Map(t),Mt=(t,e)=>t?.get(e),ee=(t,e,r)=>$t(r)?(ln(t,e),t):t?.set(e,r),Hs=(t,e,r,o)=>(Jn(t,e)?o?.(Mt(t,e)):ee(t,e,r()),Mt(t,e)),As=(t,e,r,o,l=0)=>as((r?Hs:Mt)(t,e[l],l>te(e)-2?r:Ie),c=>{if(l>te(e)-2)return o?.(c)&&ee(t,e[l]),c;let u=As(c,e,r,o,l+1);return on(c)&&ee(t,e[l]),u}),Fn=/^\d+$/,Kn=()=>{let t=[],e=0;return[r=>(r?nn(t):null)??""+e++,r=>{Vn(Fn,r)&&te(t)<1e3&&is(t,r)}]},qn=t=>new Set(Bs(t)||$t(t)?t:[t]),Qn=(t,e)=>t?.add(e),zn=(t,e=[""])=>{let r=[],o=(l,c)=>c==te(e)?is(r,l):e[c]===null?an(l,u=>o(u,c+1)):Es([e[c],null],u=>o(Mt(l,u),c+1));return o(t,0),r},_n=t=>{let e,[r,o]=Kn(),l=Ie();return[(c,u,i,p=[],S=()=>[])=>{e??=t();let m=r(1);return ee(l,m,[c,u,i,p,S]),Qn(As(u,i??[""],qn),m),m},(c,u,...i)=>Es(zn(c,u),p=>an(p,S=>Mt(l,S)[0](e,...u??[],...i))),c=>as(Mt(l,c),([,u,i])=>(As(u,i??[""],void 0,p=>(ln(p,c),on(p)?1:0)),ee(l,c),o(c),i)),c=>as(Mt(l,c),([u,,i=[],p,S])=>{let m=(...b)=>{let E=te(b);E==te(i)?u(e,...b,...S(b)):$t(i[E])?Es(p[E]?.(...b)??[],T=>m(...b,T)):m(...b,i[E])};m()})]},rs=Ie(),ns=Ie(),Gn=(t=1,e,r)=>t!=1&&e.isMergeable()?[1,e.getMergeableContent,()=>e.getTransactionMergeableChanges(!r),([[o],[l]])=>!ss(o)||!ss(l),e.setDefaultContent]:t!=2?[0,e.getContent,e.getTransactionChanges,([o,l])=>!ss(o)||!ss(l),e.setContent]:rn("Store type not supported by this Persister"),Yn=(t,e,r,o,l,c,u,i={},p=0,S=[])=>{let m=0,b=0,E=0,T,F,Z;Hs(rs,S,()=>0),Hs(ns,S,()=>[]);let L=Ie(),[x,_,I,A,st]=Gn(u,t,p),[y,h,C]=_n(()=>Q),W=M=>{M!=m&&(m=M,h(L,void 0,m))},K=async()=>{if(!Mt(rs,S)){for(ee(rs,S,1);!$t(T=nn(Mt(ns,S)));)await Zt(T,c);ee(rs,S,0)}},P=M=>{(x&&Bs(M?.[0])?M?.[2]===1?t.applyMergeableChanges:t.setMergeableContent:M?.[2]===1?t.applyChanges:t.setContent)(M)},q=async M=>(m!=2&&(W(1),b++,await O(async()=>{await Zt(async()=>{let rt=await e();Bs(rt)?P(rt):M?st(M):rn(`Content is not an array: ${rt}`)},()=>{M&&st(M)}),W(0)})),Q),nt=async M=>(ot(),await q(M),await Zt(async()=>F=await o(async(rt,ht)=>{ht||rt?m!=2&&(W(1),b++,P(ht??rt),W(0)):await q()}),c),Q),ot=async()=>(F&&(await Zt(()=>l(F),c),F=void 0),Q),lt=()=>!$t(F),N=async M=>(m!=1&&(W(2),E++,await O(async()=>{await Zt(()=>r(_,M),c),W(0)})),Q),R=async()=>(D(),await N(),Z=t.addDidFinishTransactionListener(()=>{let M=I();A(M)&&N(M)}),Q),D=async()=>(Z&&(t.delListener(Z),Z=void 0),Q),et=()=>!$t(Z),G=async(M,rt=!1)=>{let[ht,mt]=rt?[R,nt]:[nt,R];return await ht(M),await mt(M),Q},j=async(M=!1)=>{let[rt,ht]=M?[D,ot]:[ot,D];return await rt(),await ht(),Q},H=()=>m,J=M=>y(M,L),Y=M=>(C(M),t),O=async(...M)=>(is(Mt(ns,S),...M),await K(),Q),Q={load:q,startAutoLoad:nt,stopAutoLoad:ot,isAutoLoading:lt,save:N,startAutoSave:R,stopAutoSave:D,isAutoSaving:et,startAutoPersisting:G,stopAutoPersisting:j,getStatus:H,addStatusListener:J,delListener:Y,schedule:O,getStore:()=>t,destroy:()=>($n(Mt(ns,S)),j()),getStats:()=>({loads:b,saves:E}),...i};return En(Q)},Ps=["t","v"],Xn={keyPath:"k"},Zn=async(t,e)=>{let r=On(e,(o,l)=>os(t,"put",{k:l,v:o}));Te(await os(t,"getAllKeys"),o=>An(e,o)?0:is(r,os(t,"delete",o))),await sn(r)},os=async(t,e,r)=>en((o,l)=>{let c=t[e](r);c.onsuccess=()=>o(c.result),c.onerror=()=>l(`objectStore.${e} error`)}),cn=(t,e,r=1,o)=>{let l=async(c,u=[],i=0)=>en((p,S)=>{let m=(Xr?Xr.indexedDB:indexedDB).open(e,i?2:void 0);m.onupgradeneeded=()=>i&&Te(Ps,b=>Zt(()=>m.result.createObjectStore(b,Xn))),m.onsuccess=()=>Zt(async()=>{let b=m.result.transaction(Ps,"readwrite"),E=await sn(Te(Ps,(T,F)=>c(b.objectStore(T),u[F])));m.result.close(),p(E)},b=>{m.result.close(),S(b)}),m.onerror=()=>S("indexedDB.open error")});return Yn(t,async()=>await l(async c=>Hn(Te(await os(c,"getAll"),({k:u,v:i})=>[u,i]))),c=>l((u,i)=>Zn(u,i),c(),1),c=>jn(c,r),c=>Dn(c),o,1,{getDbName:()=>e})};var ls=class{#t;#s="blobs";#e=null;constructor(e="copio-blobs"){this.#t=e}async#a(){return this.#e?this.#e:(this.#e=new Promise((e,r)=>{if(typeof indexedDB>"u"){r(new Error("IndexedDB is not available"));return}let o=indexedDB.open(this.#t,1);o.onupgradeneeded=()=>{let l=o.result;l.objectStoreNames.contains(this.#s)||l.createObjectStore(this.#s)},o.onsuccess=()=>e(o.result),o.onerror=()=>r(o.error||new Error("Failed to open blob db"))}),this.#e)}async put(e,r){let o=await this.#a();return new Promise((l,c)=>{let p=o.transaction(this.#s,"readwrite").objectStore(this.#s).put(r,e);p.onsuccess=()=>l(),p.onerror=()=>c(p.error)})}async get(e){let r=await this.#a();return new Promise((o,l)=>{let i=r.transaction(this.#s,"readonly").objectStore(this.#s).get(e);i.onsuccess=()=>o(i.result||null),i.onerror=()=>l(i.error)})}async delete(e){let r=await this.#a();return new Promise((o,l)=>{let i=r.transaction(this.#s,"readwrite").objectStore(this.#s).delete(e);i.onsuccess=()=>o(),i.onerror=()=>l(i.error)})}async deleteByPrefix(e){let r=await this.#a();return new Promise((o,l)=>{let u=r.transaction(this.#s,"readwrite").objectStore(this.#s),i=u.openKeyCursor();i.onsuccess=p=>{let S=p.target.result;S?(typeof S.key=="string"&&S.key.startsWith(e)&&u.delete(S.key),S.continue()):o()},i.onerror=()=>l(i.error)})}async sweepOrphans(e){let r=new Set(e),o=await this.#a(),l=0;return new Promise((c,u)=>{let p=o.transaction(this.#s,"readwrite").objectStore(this.#s),S=p.openKeyCursor();S.onsuccess=m=>{let b=m.target.result;if(b){if(typeof b.key=="string"){let E=b.key.split(":")[0];r.has(E)||(p.delete(b.key),l++)}b.continue()}else c(l)},S.onerror=()=>u(S.error)})}async close(){if(this.#e){try{(await this.#e).close()}catch{}this.#e=null}}};function Os(t,e="image/jpeg"){if(t instanceof Blob)return t;if(typeof t!="string"||!t.startsWith("data:"))return null;let r=t.match(/^data:([^;]+);base64,(.*)$/),o=r?r[1]:e,l=r?r[2]:t.split(",")[1],c=atob(l),u=new Uint8Array(c.length);for(let i=0;i<c.length;i++)u[i]=c.charCodeAt(i);return new Blob([u],{type:o})}async function Lo(t){return new Promise((e,r)=>{let o=new FileReader;o.onloadend=()=>e(o.result),o.onerror=r,o.readAsDataURL(t)})}var dn=class extends xr{#t=null;#s=null;#e=null;#a="copio-db";#u=!1;#i=new Set;#l=new Map;#r=new Map;#n=new Map;#o=new Map;#c=null;constructor(e={}){super(),this.#a=e.dbName||"copio-db",e.dbName&&e.dbName!=="copio-db"&&(this.#u=!0),this.#t=e.store||Us(),this.#t.hasTable("docs")||this.#t.setTable("docs",{}),this.#s=e.persister||cn(this.#t,this.#a),this.#e=new ls(`${this.#a}-blobs`)}get store(){return this.#t}get persister(){return this.#s}get blobStore(){return this.#e}#d(e,r){return typeof r=="string"&&r.startsWith("blob:")&&(this.#i.add(r),this.#l.has(e)||this.#l.set(e,[]),this.#l.get(e).push(r)),r}revokeDocUrls(e){let r=this.#l.get(e);if(r){for(let o of r){try{URL.revokeObjectURL(o)}catch{}this.#i.delete(o)}this.#l.delete(e)}for(let[o,l]of this.#r.entries())if(o.startsWith(`${e}:`)){try{URL.revokeObjectURL(l)}catch{}this.#r.delete(o)}for(let[o,l]of this.#n.entries())if(o.startsWith(`${e}:`)){try{URL.revokeObjectURL(l)}catch{}this.#n.delete(o)}this.#o.delete(e)}revokeAllUrls(){for(let e of this.#i)try{URL.revokeObjectURL(e)}catch{}this.#i.clear(),this.#l.clear(),this.#r.clear(),this.#n.clear(),this.#o.clear()}async init(){return this.#c?this.#c:(this.#c=(async()=>{this.#u?(await this.#s.load(),this.#s.startAutoLoad(),this.#s.startAutoSave()):await this.#s.load(),await this.sweepOrphans();let e=!0;if(typeof navigator<"u"&&navigator.storage&&navigator.storage.persisted)try{e=await navigator.storage.persisted()}catch{}return{kind:"indexeddb",persistent:e}})(),this.#c)}async sweepOrphans(){let e=Object.keys(this.#t.getTable("docs")||{});return this.#e.sweepOrphans(e)}listDocsSync(){let e=this.#t.getTable("docs");return Object.entries(e||{}).map(([r,o])=>({id:r,name:o.name||"",pages:this.#h(o.pages)}))}async listDocs(){return this.listDocsSync()}getDocSync(e){if(this.#o.has(e))return this.#o.get(e);if(!this.#t.hasRow("docs",e))return null;let r=this.#t.getRow("docs",e);return{id:e,name:r.name||"",pages:this.#h(r.pages)}}async getDoc(e){if(!this.#t.hasRow("docs",e))return null;let r=this.#t.getRow("docs",e),o=this.#h(r.pages),l=await Promise.all(o.map(async u=>{if(!u)return u;let i={...u},p=`${e}:${u.id}`,S=await this.#e.get(`${e}:${u.id}`);S&&(i.blob=S,this.#r.has(p)?i.src=this.#r.get(p):(i.src=this.#d(e,URL.createObjectURL(S)),this.#r.set(p,i.src)));let m=`${e}:${u.id}:orig`,b=await this.#e.get(`${e}:${u.id}:original`);return b?(i.originalBlob=b,this.#n.has(m)?i.originalSrc=this.#n.get(m):(i.originalSrc=this.#d(e,URL.createObjectURL(b)),this.#n.set(m,i.originalSrc))):i.blob&&(i.originalBlob=i.blob,i.originalSrc=i.src),i})),c={id:e,name:r.name||"",pages:l};return this.#o.set(e,c),c}async saveDoc(e,r){if(!e)throw new Error("Cannot save document without an ID");let o=Array.isArray(r.pages)?r.pages:this.#h(r.pages),l=[],c=[],u=[];for(let i of o){if(!i)continue;let p=Os(i.src)||(i.src instanceof Blob?i.src:null)||(i.blob instanceof Blob?i.blob:null),S=p?.type||"image/jpeg",m={id:i.id,name:i.name||"",type:i.type||"image",hasBlob:!0,mimeType:S,edits:i.edits,exif:i.exif,content:i.content,ocrText:i.ocrText??null,ocrConfidence:i.ocrConfidence??null,ocrWords:Array.isArray(i.ocrWords)?i.ocrWords:null,ocrWidth:i.ocrWidth??null,ocrHeight:i.ocrHeight??null};l.push(m);let b=`${e}:${i.id}`,E=`${e}:${i.id}:orig`,T={...i},F=this.#r.get(b),Z=typeof i.src=="string"&&i.src.startsWith("data:")||i.src instanceof Blob||i.src&&F&&i.src!==F;if(p)if(T.blob=p,Z||!F){if(F){try{URL.revokeObjectURL(F)}catch{}this.#i.delete(F)}let A=this.#d(e,URL.createObjectURL(p));this.#r.set(b,A),T.src=A}else T.src=F;let L=Os(i.originalSrc)||(i.originalSrc instanceof Blob?i.originalSrc:null)||(i.originalBlob instanceof Blob?i.originalBlob:null),x=this.#n.get(E),_=!x&&!L&&(!i.originalSrc||i.originalSrc===i.src);_&&p&&(L=p);let I=typeof i.originalSrc=="string"&&i.originalSrc.startsWith("data:")||i.originalSrc instanceof Blob||_&&!!L;if(L)if(T.originalBlob=L,I||!x){if(x&&I){try{URL.revokeObjectURL(x)}catch{}this.#i.delete(x)}let A=this.#d(e,URL.createObjectURL(L));this.#n.set(E,A),T.originalSrc=A}else T.originalSrc=x;else x?T.originalSrc=x:i.originalSrc?T.originalSrc=i.originalSrc:(T.originalSrc=T.src,T.blob&&(T.originalBlob=T.blob));c.push(T),u.push({pageId:i.id,page:i,srcBlob:p,origBlob:L})}this.#t.setRow("docs",e,{name:r.name||"",pages:JSON.stringify(l)}),this.#o.set(e,{id:e,name:r.name||"",pages:c});for(let i of u){let{pageId:p,page:S,srcBlob:m,origBlob:b}=i;if(!m&&typeof S.src=="string"&&S.src.startsWith("blob:"))try{m=await(await fetch(S.src)).blob()}catch{}if(m&&await this.#e.put(`${e}:${p}`,m),!b&&typeof S.originalSrc=="string"&&S.originalSrc.startsWith("blob:"))try{b=await(await fetch(S.originalSrc)).blob()}catch{}b&&await this.#e.put(`${e}:${p}:original`,b)}}async deleteDoc(e){this.#t.delRow("docs",e),await this.#e.deleteByPrefix(`${e}:`),this.revokeDocUrls(e),this.#o.delete(e)}async renameDoc(e,r){if(!this.#t.hasRow("docs",e))throw new Error(`Document "${e}" not found`);this.#t.setCell("docs",e,"name",r),this.#o.has(e)&&(this.#o.get(e).name=r)}async savePage(e,r,o){let l=await this.getDoc(e);if(!l)throw new Error(`Document ${e} not found`);let c=l.pages.findIndex(p=>p.id===r),u;if(c>=0)typeof o=="object"&&o!==null&&!(o instanceof Blob)?l.pages[c]={...l.pages[c],...o}:l.pages[c]={...l.pages[c],src:o,blob:o instanceof Blob?o:void 0},u=l.pages[c];else{let p=typeof o=="object"&&o!==null&&!(o instanceof Blob)?{id:r,...o}:{id:r,src:o,blob:o instanceof Blob?o:void 0};l.pages.push(p),u=p}let i=Os(u.src)||(u.src instanceof Blob?u.src:null)||(u.blob instanceof Blob?u.blob:null);if(!i&&typeof u.src=="string"&&u.src.startsWith("blob:"))try{i=await(await fetch(u.src)).blob()}catch{}i&&await this.#e.put(`${e}:${r}`,i),await this.saveDoc(e,l)}async getPage(e,r){let o=await this.#e.get(`${e}:${r}`);if(o)return o;let l=this.getDocSync(e);if(!l)return null;let c=l.pages.find(u=>u.id===r);return c?c.content??c.src??c:null}async deletePage(e,r){let o=this.getDocSync(e);if(!o)return;o.pages=o.pages.filter(u=>u.id!==r),this.#t.setRow("docs",e,{name:o.name||"",pages:JSON.stringify(o.pages)}),await this.#e.delete(`${e}:${r}`),await this.#e.delete(`${e}:${r}:original`);let l=`${e}:${r}`;if(this.#r.has(l)){try{URL.revokeObjectURL(this.#r.get(l))}catch{}this.#r.delete(l)}let c=`${e}:${r}:orig`;if(this.#n.has(c)){try{URL.revokeObjectURL(this.#n.get(c))}catch{}this.#n.delete(c)}this.#o.delete(e)}subscribe(e){let r=this.#t.addTableListener("docs",e);return()=>{this.#t.delListener(r)}}#h(e){if(Array.isArray(e))return e;if(typeof e=="string")try{return JSON.parse(e)}catch{return[]}return[]}};export{Us as a,Os as b,Lo as c,dn as d};
2
- //# sourceMappingURL=chunk-L4OVZN23.js.map
@@ -1,2 +0,0 @@
1
- import{d as w}from"./chunk-YNY65JUJ.js";import{f as Y,g as _}from"./chunk-ZT72PD2C.js";import{a as te}from"./chunk-4C666HHU.js";var re={};te(re,{exportDocumentAsImages:()=>ne,exportDocumentAsPdf:()=>oe});async function oe(b,s,z={}){let{onProgress:u,showProgress:j=!0,download:B=!0,searchable:d=!1,lang:R="eng",onOcrComplete:C=null}=z;if(!s||s.length===0){w.warning("No images to export");return}let c=null,a=s.length;try{j&&a>1&&(c=await w.progress({message:`Exporting "${b||"document"}.pdf"...`,total:a,done:0}));let x=null;if(typeof window<"u"&&!window.PDFDocument){typeof u=="function"&&u(0,a,"Downloading PDF engine...");try{x=await w.progress({message:"Downloading PDF engine...",total:100,done:0})}catch{}}let m;try{m=await Y()}finally{x?.close()}let E=595.28,o=841.89,n=new m({autoFirstPage:!1}),p=[];n.on("data",t=>p.push(t));let h=new Promise((t,e)=>{n.on("end",()=>{try{let r=new Blob(p,{type:"application/pdf"});if(B!==!1){let i=URL.createObjectURL(r),g=document.createElement("a");g.href=i,g.download=`${b||"document"}.pdf`,g.click(),URL.revokeObjectURL(i),w.success(`Exported "${b||"document"}.pdf"`)}c?.close(),typeof window<"u"&&typeof window.dispatchEvent=="function"&&window.dispatchEvent(new CustomEvent("copio:export-complete",{bubbles:!0,composed:!0,detail:{type:"pdf",format:"pdf",blob:r,docName:b||"document",searchable:!!d}})),t(r)}catch(r){e(r)}}),n.on("error",e)});for(let t=0;t<s.length;t++){let e=s[t],r=t+1;if(e.src||e.blob){let i=new Image,g=null,l=e.src;if(e.blob instanceof Blob&&(!l||l instanceof Blob)?(l=URL.createObjectURL(e.blob),g=l):e.src instanceof Blob&&(l=URL.createObjectURL(e.src),g=l),await new Promise(f=>{i.onload=f,i.onerror=$=>{console.warn("Page image failed to load for PDF:",$),f(void 0)},i.src=l}),i.width&&i.height){n.addPage({size:"A4"});let f=E/i.width,$=o/i.height,O=Math.min(f,$),W=i.width*O,F=i.height*O,k=(E-W)/2,A=(o-F)/2,v=null;if(e.blob instanceof Blob)v=await e.blob.arrayBuffer();else if(e.src instanceof Blob)v=await e.src.arrayBuffer();else if(typeof e.src=="string"&&e.src.startsWith("blob:"))try{v=await(await(await fetch(e.src)).blob()).arrayBuffer()}catch{}if(v?n.image(v,k,A,{width:W,height:F}):n.image(l,k,A,{width:W,height:F}),d){let y=Array.isArray(e.ocrWords)&&e.ocrWords.length>0?e.ocrWords:null;if(!y&&(e.src||e.blob)){typeof u=="function"&&u(r,a,`Recognizing text for page ${r} of ${a}...`),c&&c.update({done:r,total:a,message:`Recognizing text for page ${r} of ${a}...`});try{let L=await(z.recognizeImageText||(await import("./ocr.js")).recognizeImageText)(e.blob||e.src,{lang:R});y=L?.words||[],e.ocrText=L?.text||"",e.ocrConfidence=L?.confidence??0,e.ocrWords=y,e.ocrWidth=i.width,e.ocrHeight=i.height}catch(P){console.warn(`On-demand OCR failed for page ${r}:`,P)}}if(y&&y.length>0){n.save(),n.font("Helvetica");let P=e.ocrWidth||i.width,L=e.ocrHeight||i.height,H=W/P,I=F/L;for(let N of y){let U=(N.text||"").trim();if(!U)continue;let S=N.bbox||{},T=S.x0??0,M=S.y0??0,J=Math.max(1,(S.x1??0)-T),G=Math.max(1,(S.y1??0)-M),K=k+T*H,q=A+M*I,Q=J*H,V=G*I,ee=Math.max(1,V);n.fontSize(ee);let Z=n.widthOfString(U),X=0;Z>0&&U.length>1&&(X=(Q-Z)/(U.length-1)),n.text(U,K,q,{renderingMode:3,lineBreak:!1,characterSpacing:X})}n.restore()}}}if(g)try{URL.revokeObjectURL(g)}catch{}}typeof u=="function"&&u(r,a),c&&c.update({done:r,total:a,message:`Exporting PDF: page ${r} of ${a}...`}),typeof window<"u"&&typeof window.dispatchEvent=="function"&&window.dispatchEvent(new CustomEvent("copio:export-progress",{detail:{type:"pdf",done:r,total:a,docName:b||"document"}})),await new Promise(i=>setTimeout(i,0))}if(d&&typeof C=="function")try{await C(s)}catch(t){console.warn("onOcrComplete error:",t)}return n.end(),await h}catch(x){c?.close(),console.error("Error generating PDF:",x),w.error("Failed to generate PDF")}}async function ne(b,s,z={}){let{onProgress:u,showProgress:j=!0,download:B=!0}=z;if(!s||s.length===0){w.warning("No images to export");return}let d=null;try{let R=(b||"document").trim(),c=(o=>o.replace(/[/\\?%*:|"<>]/g,"_"))(R)||"document";if(s.length===1){let o=s[0],n="jpg",p="",h=!1,t=null;if(o.blob instanceof Blob)t=o.blob,t.type&&t.type.includes("png")&&(n="png"),p=URL.createObjectURL(t),h=!0;else if(o.src instanceof Blob)t=o.src,t.type&&t.type.includes("png")&&(n="png"),p=URL.createObjectURL(t),h=!0;else if(typeof o.src=="string")if(p=o.src,o.src.startsWith("data:")){let e=o.src.match(/^data:(image\/[a-zA-Z+]+);base64,/);e&&e[1].includes("png")&&(n="png");try{t=await(await fetch(o.src)).blob()}catch{t=new Blob([o.src],{type:`image/${n}`})}}else if(o.src.startsWith("blob:"))try{t=await(await fetch(o.src)).blob(),t.type&&t.type.includes("png")&&(n="png")}catch{}else try{t=await(await fetch(o.src)).blob(),p=URL.createObjectURL(t),h=!0}catch{}if(typeof u=="function"&&u(1,1),typeof window<"u"&&typeof window.dispatchEvent=="function"&&window.dispatchEvent(new CustomEvent("copio:export-progress",{detail:{type:"image",done:1,total:1,docName:c}})),B!==!1){let e=document.createElement("a");e.href=p,e.download=`${c}.${n}`,e.click(),w.success(`Exported "${c}.${n}"`)}return h&&URL.revokeObjectURL(p),typeof window<"u"&&typeof window.dispatchEvent=="function"&&window.dispatchEvent(new CustomEvent("copio:export-complete",{bubbles:!0,composed:!0,detail:{type:"image",format:n,blob:t,docName:c}})),t}let a=s.length;j&&a>1&&(d=await w.progress({message:`Exporting "${c}.zip"...`,total:a,done:0}));let x=await _(),D=new x,m=0;for(let o=0;o<s.length;o++){let n=s[o],p=[n.blob||n.src],h=Math.max(2,String(s.length*p.length).length);for(let e=0;e<p.length;e++){let r=p[e],i="jpg",g=null;if(r instanceof Blob)r.type&&r.type.includes("png")&&(i="png"),g=await r.arrayBuffer();else if(typeof r=="string"&&r.startsWith("data:")){let l=r.match(/^data:(image\/[a-zA-Z+]+);base64,(.*)$/),f="";l?(l[1].includes("png")&&(i="png"),f=l[2]):f=r.replace(/^data:[^;]+;base64,/,"");let $=String(m+1).padStart(h,"0"),O=`${c}-${$}.${i}`;D.file(O,f,{base64:!0}),m++;continue}else if(typeof r=="string")try{let f=await(await fetch(r)).blob();f.type&&f.type.includes("png")&&(i="png"),g=await f.arrayBuffer()}catch{}if(g){let l=String(m+1).padStart(h,"0"),f=`${c}-${l}.${i}`;D.file(f,g),m++}}let t=o+1;typeof u=="function"&&u(t,a),d&&d.update({done:t,total:a,message:`Exporting ZIP: page ${t} of ${a}...`}),typeof window<"u"&&typeof window.dispatchEvent=="function"&&window.dispatchEvent(new CustomEvent("copio:export-progress",{detail:{type:"zip",done:t,total:a,docName:c}})),await new Promise(e=>setTimeout(e,0))}d&&d.update({message:"Compressing archive..."});let E=await D.generateAsync({type:"blob"},o=>{d&&o.percent&&d.update({value:Math.round(o.percent),message:`Compressing ZIP: ${Math.round(o.percent)}%...`})});if(B!==!1){let o=URL.createObjectURL(E),n=document.createElement("a");n.href=o,n.download=`${c}.zip`,n.click(),URL.revokeObjectURL(o),w.success(`Exported "${c}.zip"`)}return d?.close(),typeof window<"u"&&typeof window.dispatchEvent=="function"&&window.dispatchEvent(new CustomEvent("copio:export-complete",{bubbles:!0,composed:!0,detail:{type:"zip",format:"zip",blob:E,docName:c}})),E}catch(R){d?.close(),console.error("Error downloading images:",R),w.error("Failed to download images")}}export{oe as a,ne as b,re as c};
2
- //# sourceMappingURL=chunk-MEE2NNYB.js.map
@@ -1,2 +0,0 @@
1
- import{d as r}from"./chunk-YNY65JUJ.js";import{h as c,i as a}from"./chunk-ZT72PD2C.js";var u="https://copio.metered.live/api/v1/turn/credentials?apiKey=d90f0b0b6bdf180ea68238f5c2185074ce37",f=[{urls:"stun:stun.l.google.com:19302"},{urls:"stun:stun.relay.metered.ca:80"}],p=5e3;async function h(){let i=new AbortController,e=setTimeout(()=>i.abort(),p);try{let t=await fetch(u,{signal:i.signal,cache:"no-store"});if(!t.ok)throw new Error(`HTTP ${t.status}`);let s=await t.json();if(!Array.isArray(s)||s.length===0)throw new Error("Empty ICE server list");return[{urls:"stun:stun.l.google.com:19302"},...s]}catch(t){return console.warn("[Sync] Failed to fetch TURN credentials, using STUN only:",t),f}finally{clearTimeout(e)}}var m=3e4,l=class{#i=null;#t=null;#r=null;#e=null;#c=0;#n=null;constructor(e,t){this.#t=e,this.#r=t}get state(){return this.#e}#s(e){this.#e=e,this.#r&&this.#r(this.#e)}#o(e){clearTimeout(this.#n),this.#e&&this.#s({...this.#e,step:"error",message:e})}async#a(){let e=++this.#c,[t,s]=await Promise.all([h(),c()]);return e!==this.#c?null:new s({config:{iceServers:t}})}#h(e){e.on("error",s=>this.#o(s.message));let t=e.peerConnection;t&&t.addEventListener("iceconnectionstatechange",()=>{console.log("[Sync] ICE state:",t.iceConnectionState),t.iceConnectionState==="failed"&&this.#o("Could not connect to the other device. Check both are online and try again.")})}#l(){clearTimeout(this.#n),this.#n=setTimeout(()=>{let e=this.#e?.step;e&&e!=="done"&&e!=="error"&&this.#o("Connection timed out. Try again.")},m)}#d(e){let t=()=>{clearTimeout(this.#n),this.#s({...this.#e,step:"syncing"}),this.#p(e)};e.open?t():e.on("open",t)}startHost(){if(this.#e?.mode!=="host"){if(!navigator.onLine){r.warning("An internet connection is needed to link devices.",{icon:"wifi-off",duration:4e3});return}this.#s({mode:"host",step:"init"}),this.#u().catch(e=>{this.#s({mode:"host",step:"error",message:e.message})})}}async#u(){let e=await this.#a();e&&(this.#i=e,e.on("error",t=>this.#o(t.message)),e.on("open",async t=>{let s=`${location.origin}${location.pathname}?peer=${t}`,o=(await a())(0,"M");o.addData(s),o.make(),this.#s({mode:"host",step:"waiting",qrSvg:o.createSvgTag(4,8),url:s,peerId:t})}),e.on("connection",t=>{this.#l(),this.#h(t),this.#d(t)}))}startJoiner(e){this.#e?.mode!=="joiner"&&(this.#s({mode:"joiner",step:"connecting"}),this.#l(),this.#f(e).catch(t=>{this.#s({mode:"joiner",step:"error",message:t.message})}))}async#f(e){let t=await this.#a();t&&(this.#i=t,t.on("error",s=>this.#o(s.message)),t.on("open",()=>{let s=t.connect(e);this.#h(s),this.#d(s)}))}#p(e){e.on("data",async t=>{let s;try{s=typeof t=="string"?JSON.parse(t):t}catch(o){console.error("Failed to parse sync data:",o);return}let n=0;typeof this.#t?.importDocs=="function"?n=await this.#t.importDocs(s):typeof this.#t?.transaction=="function"&&this.#t.transaction(()=>{for(let[o,d]of Object.entries(s||{}))this.#t.hasRow("docs",o)||n++,this.#t.setRow("docs",o,d)}),this.#s({...this.#e,step:"done",added:n}),r.success(`Sync complete \u2014 ${n} doc${n!==1?"s":""} added`)}),(async()=>{try{let t;typeof this.#t?.exportAll=="function"?t=await this.#t.exportAll():typeof this.#t?.getTable=="function"?t=this.#t.getTable("docs"):t={},e.send(JSON.stringify(t))}catch(t){console.error("Failed to send sync data:",t),this.#o(t.message)}})()}close(){this.#c++,clearTimeout(this.#n),this.#i?.destroy(),this.#i=null,this.#s(null)}};export{h as a,l as b};
2
- //# sourceMappingURL=chunk-WETG2JD7.js.map
@@ -1,2 +0,0 @@
1
- import"./chunk-4C666HHU.js";var t={},a=()=>null,e=globalThis.Path2D||class{};export{e as Path2D,a as createCanvas,t as default};
2
- //# sourceMappingURL=fs-HJ6WWW73.js.map
@@ -1,2 +0,0 @@
1
- import"./chunk-4C666HHU.js";var t={},a=()=>null,e=globalThis.Path2D||class{};export{e as Path2D,a as createCanvas,t as default};
2
- //# sourceMappingURL=http-FKJJMT2N.js.map
@@ -1,2 +0,0 @@
1
- import"./chunk-4C666HHU.js";var t={},a=()=>null,e=globalThis.Path2D||class{};export{e as Path2D,a as createCanvas,t as default};
2
- //# sourceMappingURL=https-MUBFLDZM.js.map
@@ -1,2 +0,0 @@
1
- import"./chunk-4C666HHU.js";var t={},a=()=>null,e=globalThis.Path2D||class{};export{e as Path2D,a as createCanvas,t as default};
2
- //# sourceMappingURL=path2d-QWN6DFCC.js.map
@@ -1,2 +0,0 @@
1
- import"./chunk-4C666HHU.js";var t={},a=()=>null,e=globalThis.Path2D||class{};export{e as Path2D,a as createCanvas,t as default};
2
- //# sourceMappingURL=url-ABJ6S2Y6.js.map