@veltdev/sdk 6.0.27 → 6.0.28

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 (59) hide show
  1. package/{chunk-4GWTY2QW.js → chunk-3BCXNETY.js} +1 -1
  2. package/{chunk-PIBUTN6R.js → chunk-3Q5TRC4E.js} +1 -1
  3. package/{chunk-T32PAZYN.js → chunk-4HAFXUDN.js} +1 -1
  4. package/chunk-4P3GYHGY.js +1 -0
  5. package/{chunk-Z7CCKSEO.js → chunk-5ACPKO6C.js} +1 -1
  6. package/{chunk-PBA6NIAI.js → chunk-67RGQF3Z.js} +1 -1
  7. package/{chunk-2MYJTN75.js → chunk-CR275X25.js} +1 -1
  8. package/{chunk-FHFEI7VF.js → chunk-EB7SHB2S.js} +1 -1
  9. package/{chunk-WWK6NPFJ.js → chunk-FWIDRPYU.js} +1 -1
  10. package/{chunk-K6LCTVYG.js → chunk-GAWI762G.js} +1 -1
  11. package/{chunk-DKI2JSNJ.js → chunk-GHN6NWBT.js} +1 -1
  12. package/{chunk-UKCZENKX.js → chunk-HCM2TAE7.js} +1 -1
  13. package/{chunk-IVZBIMXH.js → chunk-HIEV42PB.js} +1 -1
  14. package/{chunk-CXZSNTWV.js → chunk-IS7ZDK65.js} +1 -1
  15. package/{chunk-7J6SWBKB.js → chunk-J35LMO3C.js} +1 -1
  16. package/{chunk-V2VL4H4R.js → chunk-J3IQ7DYW.js} +1 -1
  17. package/{chunk-ABA7YQYU.js → chunk-JQZKADOA.js} +1 -1
  18. package/{chunk-KHGHU7FE.js → chunk-JWSICAW6.js} +1 -1
  19. package/{chunk-2C7WPTQD.js → chunk-JZCDUWAA.js} +1 -1
  20. package/{chunk-NZUJK3CJ.js → chunk-KNYRVMQK.js} +1 -1
  21. package/{chunk-ZVRUGR3J.js → chunk-MP2SDO2E.js} +1 -1
  22. package/{chunk-KWZM6CNH.js → chunk-N3IQEYGG.js} +1 -1
  23. package/{chunk-72TEWHMQ.js → chunk-NTFMMZRZ.js} +1 -1
  24. package/{chunk-4CPJN52I.js → chunk-R7EWRVMV.js} +1 -1
  25. package/{chunk-JR3BVUP3.js → chunk-R7PIAWZF.js} +1 -1
  26. package/{chunk-YI3LAD3Z.js → chunk-RPLZXBLF.js} +1 -1
  27. package/{chunk-M3XIT6ZY.js → chunk-SN6HOFPK.js} +1 -1
  28. package/{chunk-QQIKH4VS.js → chunk-SYLJZSJP.js} +1 -1
  29. package/{chunk-WBOPOSCN.js → chunk-TLEK2ADO.js} +1 -1
  30. package/{chunk-YUGCY3BB.js → chunk-TSC5TWPQ.js} +1 -1
  31. package/{chunk-HV37SAIK.js → chunk-URKI6WZP.js} +1 -1
  32. package/{chunk-J3DYWDYQ.js → chunk-VESMHAEV.js} +1 -1
  33. package/{chunk-DF2C2V7B.js → chunk-VJPZ6E4S.js} +1 -1
  34. package/{chunk-WNH4SCIB.js → chunk-XEXFF5FD.js} +1 -1
  35. package/{chunk-BTJTZEPV.js → chunk-YBLQ2JHR.js} +1 -1
  36. package/{chunk-G6V3RCTP.js → chunk-ZRITZXNF.js} +1 -1
  37. package/package.json +1 -1
  38. package/velt-activity-log.js +1 -1
  39. package/velt-area.js +1 -1
  40. package/velt-arrow.js +1 -1
  41. package/velt-comment.js +7 -7
  42. package/velt-crdt.js +1 -1
  43. package/velt-cursor.js +1 -1
  44. package/velt-huddle.js +1 -1
  45. package/velt-live-state-sync.js +1 -1
  46. package/velt-notification.js +1 -1
  47. package/velt-portable.js +1 -1
  48. package/velt-presence.js +1 -1
  49. package/velt-reaction.js +1 -1
  50. package/velt-recorder.js +1 -1
  51. package/velt-rewriter.js +1 -1
  52. package/velt-selection.js +1 -1
  53. package/velt-tag.js +1 -1
  54. package/velt-user-invite.js +1 -1
  55. package/velt-user-request.js +1 -1
  56. package/velt-video-player.js +1 -1
  57. package/velt-views.js +1 -1
  58. package/velt.js +2 -2
  59. package/chunk-4JE45AVC.js +0 -1
@@ -1 +1 @@
1
- import{B as s,K as a,ba as c,ea as n,l as o,pj as h}from"./chunk-J3DYWDYQ.js";var u=(()=>{let r=class r{constructor(t){this.loggingService=t,this.toasts$=new o([])}setToast(t){try{t.id||(t.id=Math.random()),this.toasts$.next([...this.toasts$.value,t]),t.duration&&t.duration>0&&s(t.duration).pipe(a(1)).subscribe(()=>{this.removeToast(t)},i=>{this.loggingService.catch("Error in ToastService setToast timer subscription: ",i)})}catch(i){this.loggingService.catch("Error in ToastService setToast: ",i)}}removeToast(t){try{this.toasts$.next(this.toasts$.value.filter(i=>i.id!==t.id))}catch(i){this.loggingService.catch("Error in ToastService removeToast: ",i)}}getToasts$(){return this.toasts$.asObservable()}};r.\u0275fac=function(i){return new(i||r)(n(h))},r.\u0275prov=c({token:r,factory:r.\u0275fac,providedIn:"root"});let e=r;return e})();export{u as a};
1
+ import{B as s,K as a,ba as c,ea as n,l as o,pj as h}from"./chunk-VESMHAEV.js";var u=(()=>{let r=class r{constructor(t){this.loggingService=t,this.toasts$=new o([])}setToast(t){try{t.id||(t.id=Math.random()),this.toasts$.next([...this.toasts$.value,t]),t.duration&&t.duration>0&&s(t.duration).pipe(a(1)).subscribe(()=>{this.removeToast(t)},i=>{this.loggingService.catch("Error in ToastService setToast timer subscription: ",i)})}catch(i){this.loggingService.catch("Error in ToastService setToast: ",i)}}removeToast(t){try{this.toasts$.next(this.toasts$.value.filter(i=>i.id!==t.id))}catch(i){this.loggingService.catch("Error in ToastService removeToast: ",i)}}getToasts$(){return this.toasts$.asObservable()}};r.\u0275fac=function(i){return new(i||r)(n(h))},r.\u0275prov=c({token:r,factory:r.\u0275fac,providedIn:"root"});let e=r;return e})();export{u as a};
@@ -1 +1 @@
1
- import{b as $,c as z,d as U,e as H,f as j}from"./chunk-IVZBIMXH.js";import{B as ee,b as Z,o as O,r as J}from"./chunk-72TEWHMQ.js";import{He as K,Hi as k,Ie as V,Mj as G,Nj as q,Oj as W,Rj as _,Sj as X,Yd as S,_d as E,_j as M,a as b,ba as A,bf as x,ea as g,ee as R,g as p,i as L,na as N,nk as Q,ok as Y,pj as y,qj as w,rj as C,sa as P,sk as T,vg as F}from"./chunk-J3DYWDYQ.js";var pe=1e4,ge=6e4,te=3e4,me=3e4,fe=900*1e3;function re(s){let n=Math.max(0,Math.min(Math.floor(Number.isFinite(s)?s:1)-1,16));return Math.min(me*2**n,fe)}var Ae=3600*1e3,ie=250,ne=1200*1e3,Se=1024,ve={fetch:(s,n)=>fetch(s,n)},be="The browser could not send the file to the storage URL the gateway signed. The usual cause is the CORS rules of that storage (its storage account or bucket), which must allow this page's origin for PUT; they are set by the operator of the deployment, not by the SDK.",se="The browser could not read the file from the storage URL the gateway signed. The usual cause is the CORS rules of that storage (its storage account or bucket), which must allow this page's origin for GET; they are set by the operator of the deployment, not by the SDK.",m=class extends Error{constructor(n,d){super(d),this.code=n,this.name="PortableAttachmentError"}};function v(s){return!!s&&!s.url&&s.isAttachmentResolverUsed!==!0&&typeof s.bucketPath=="string"&&s.bucketPath.length>0&&s.attachmentId!==void 0&&s.attachmentId!==null&&String(s.attachmentId).length>0}function ye(s,n,d){let e={organizationId:n,documentId:d};return typeof s?.name=="string"&&s.name.length>0&&s.name.length<=Se&&(e.fileName=s.name),typeof s?.type=="string"&&s.type.length>0&&(e.contentType=s.type),Number.isInteger(s?.size)&&s.size>=0&&(e.sizeBytes=s.size),e}function we(s){return typeof s=="string"&&/^[A-Za-z0-9._-]{1,128}$/.test(s)&&!/^\.+$/.test(s)}function Te(s){return!!s&&typeof s=="object"&&!Array.isArray(s)&&Object.values(s).every(n=>typeof n=="string")}function Ie(s){let n=s;return!n||typeof n!="object"||!we(n.attachmentId)||typeof n.key!="string"||!n.key||typeof n.url!="string"||!C(n.url)||n.method!=="PUT"||!Te(n.headers)?null:{attachmentId:n.attachmentId,key:n.key,url:n.url,method:"PUT",headers:b({},n.headers),expiresAtMs:typeof n.expiresAtMs=="number"?n.expiresAtMs:0}}function Pe(s){let n=s;return!n||typeof n!="object"||typeof n.url!="string"||!C(n.url)?null:{key:typeof n.key=="string"?n.key:"",url:n.url,expiresAtMs:typeof n.expiresAtMs=="number"&&Number.isFinite(n.expiresAtMs)?n.expiresAtMs:0}}function Ue(s,n,d){let e=Number.isFinite(s)?s-(n+(Number.isFinite(d)?d:0)):0;return n+Math.min(Math.max(e,0),Ae)}var ae=(()=>{let n=class n{constructor(e,t){this.injector=e,this.loggingService=t,this.urlGeneration=P(0),this.urlKeyVersions=new Map,this.userWatched=!1,this.watchedUserId=null,this.urlCache=new Map,this.urlInFlight=new Map,this.urlFailures=new Map,this.urlMissing=new Set,this.cacheOwner=null,this.attachmentsAnnounced=!1,this.hookedRealtime=null,this.offCapabilities=null,this.availabilityListeners=new Set,this.veltStorageRefusalsReported=new Set,this.reportedOpFailures=new Set,this.invalidReadUrlReported=!1,this.hotPathReported=new Set,this.portableSessionSeen=!1}get selector(){return this._selector??=this.injector.get(X)}get auth(){return this._auth??=this.injector.get(T)}get config(){return this._config??=this.injector.get(w)}isPortableSession(){try{if(!this.auth.getPortableBackend?.())return!1;let e=this.selector.isPortableSession()===!0;return e&&(this.portableSessionSeen=!0),e}catch(e){return this.loggingService.catch("Error in PortableAttachmentStorageService isPortableSession: ",e,void 0,!0),!1}}isPortableAttachmentDeployment(){if(this.isPortableSession())return!0;if(!this.portableSessionSeen)return!1;try{return this.config.getEnablePortableBackend()===!0}catch(e){return this.loggingService.catch("Error in PortableAttachmentStorageService isPortableAttachmentDeployment: ",e,void 0,!0),!0}}captureSessionUser(){return this.isPortableSession()?this.currentUserId():null}isSameSessionUser(e){return this.isSameSession(e??null)}isPortableAttachment(e){return v(e)&&this.isPortableSession()}upload(l){return p(this,arguments,function*({attachment:e,file:t,scope:r,sessionUserId:i}){let o=this.scopeIds(r);if(!o)throw this.notSent("upload","the comment has no organization or document id");let c=i===void 0?this.currentUserId():i;if(!c)throw this.notSent("upload","no user is signed in");if(!this.isSameSession(c))throw this.notSent("upload","the session changed before the upload started");if(!(yield this.waitForActiveBackend())||!this.isSameSession(c))throw this.notSent("upload","the portable backend is not active");let a=yield this.callOp("getUploadUrl",ye(t,o.organizationId,o.documentId));if(!this.isSameSession(c))throw this.dropped("the session changed while getUploadUrl ran; the file was not uploaded");if(!a?.ok){this.reportOpFailure("getUploadUrl",a);let u=`${a?.code??"unknown"}${a?.message?` (${a.message})`:""}`;throw new m(a?.code??"failed-precondition",O(a)?`Tier B comment attachments are not available on this deployment: getUploadUrl answered ${u}`:`Tier B getUploadUrl failed: ${u}`)}let h=Ie(a.data);if(!h){let u=new m("failed-precondition",'Tier B getUploadUrl answered a signed upload this SDK will not use (it needs method PUT, an https URL, string headers, an attachmentId of 1-128 letters, digits, ".", "_" or "-", and a key); the file was not uploaded');throw this.loggingService.catch(u.message,void 0,void 0,!0),u}if(yield this.putSignedUpload(h,t),!this.isSameSession(c))throw this.dropped("the session changed while the file uploaded; the attachment is not added");return e.attachmentId=h.attachmentId,e.bucketPath=h.key,e.url="",e.clientOrganizationId=o.organizationId,e.clientDocumentId=o.documentId,e})}putSignedUpload(e,t){return p(this,null,function*(){let r=typeof AbortController=="function"?new AbortController:null,i=null,l=new Promise((o,c)=>{i=setTimeout(()=>{r?.abort(),c(new m("put-failed",`Tier B attachment upload failed: the storage did not answer the PUT within ${ne/6e4} minutes`))},ne)});try{let o=yield Promise.race([ve.fetch(e.url,b({method:"PUT",headers:b({},e.headers),body:t.slice(0,t.size,""),redirect:"error",credentials:"omit",referrerPolicy:"no-referrer"},r?{signal:r.signal}:{})),l]);if(!o?.ok)throw new m("put-failed",`Tier B attachment upload failed: the storage answered the PUT with HTTP ${o?.status}`)}catch(o){let c=o instanceof m?o:new m("put-failed",`Tier B attachment upload failed in transport: ${o?.message??o}. ${be}`);throw this.loggingService.catch(c.message,void 0,void 0,!0),c}finally{i!==null&&clearTimeout(i)}})}refuseVeltStorage(e){let t=new m("unimplemented",`Tier B ${e} was not sent: media outside comment attachments (recorder, tag) is not served by the portable backend, and Velt's storage is never used on a portable deployment`);try{this.veltStorageRefusalsReported.has(e)?this.loggingService.log(t.message):(this.veltStorageRefusalsReported.add(e),this.loggingService.catch(t.message,void 0,void 0,!0))}catch{}return t}delete(r){return p(this,arguments,function*({attachment:e,scope:t}){try{let i=this.attachmentIds(e,t),l=e?.attachmentId;if(!i||l===void 0||l===null||String(l).length===0){this.loggingService.catch("Tier B deleteAttachment was not sent: the attachment has no id, or the comment no organization or document id",void 0,void 0,!0);return}let o=this.currentUserId();if(!o||!(yield this.waitForActiveBackend())||!this.isSameSession(o)){this.loggingService.catch("Tier B deleteAttachment was not sent: the portable backend is not active",void 0,void 0,!0);return}let c=yield this.callOp("deleteAttachment",{organizationId:i.organizationId,documentId:i.documentId,attachmentId:String(l)});c?.ok||this.reportOpFailure("deleteAttachment",c)}catch(i){this.loggingService.catch("Error in PortableAttachmentStorageService delete: ",i,void 0,!0)}})}resolveDownloadUrl(e,t){try{if(!this.isPortableAttachment(e))return Promise.resolve(e?.url||null);let r=this.urlContext(e,t);if(!r||this.urlMissing.has(r.key))return Promise.resolve(null);let i=this.urlCache.get(r.key);return i&&this.isFresh(i,Date.now())?Promise.resolve(i.url):this.fetchDownloadUrl(r.key,e,r.ids,r.userId,!1)}catch(r){return this.loggingService.catch("Error in PortableAttachmentStorageService resolveDownloadUrl: ",r,void 0,!0),Promise.resolve(null)}}getDisplayUrl(e,t){if(!v(e))return e?.url;if(this.urlGeneration(),this.watchUser(),!this.isPortableSession())return e.url;try{let r=this.urlContext(e,t);if(!r)return e.url;if(this.keyVersion(r.key),this.urlMissing.has(r.key))return"";let i=Date.now(),l=this.urlCache.get(r.key);return l&&this.isFresh(l,i)?l.url:(this.inFailureBackoff(r.key,i)||this.fetchDownloadUrl(r.key,e,r.ids,r.userId,!1),l&&i<l.expiresAtMs?l.url:"")}catch(r){return this.loggingService.catch("Error in PortableAttachmentStorageService getDisplayUrl: ",r,void 0,!0),e.url}}isDisplayPending(e,t){if(!v(e)||!this.isPortableSession())return!1;try{if(this.getDisplayUrl(e,t))return!1;let r=this.urlContext(e,t);return!!r&&!this.urlMissing.has(r.key)&&!this.inFailureBackoff(r.key,Date.now())}catch(r){return this.loggingService.catch("Error in PortableAttachmentStorageService isDisplayPending: ",r,void 0,!0),!1}}reportLoadError(e,t,r){try{if(!this.isPortableAttachment(e))return;let i=this.urlContext(e,t),l=i?this.urlCache.get(i.key):void 0;if(!i||!l||l.afterLoadError||!r||l.url!==r)return;this.urlCache.delete(i.key),this.fetchDownloadUrl(i.key,e,i.ids,i.userId,!0),this.bumpKey(i.key)}catch(i){this.loggingService.catch("Error in PortableAttachmentStorageService reportLoadError: ",i,void 0,!0)}}fetchDownloadUrl(e,t,r,i,l){let o=this.urlInFlight.get(e);if(o)return o;let c;return c=p(this,null,function*(){try{if(!(yield this.waitForActiveBackend()))return this.recordUrlFailure(e),null;if(!this.isSameSession(i))return null;let a=this.serverTimeOffsetMs(),h=yield this.callOp("getDownloadUrl",{organizationId:r.organizationId,documentId:r.documentId,attachmentId:String(t.attachmentId)}),u=yield a;if(!this.isSameSession(i))return null;if(!h?.ok)return this.reportOpFailure("getDownloadUrl",h,!0),h?.code==="not-found"?(this.urlMissing.add(e),this.urlCache.delete(e),null):(this.recordUrlFailure(e),null);let f=Pe(h.data);if(!f)return this.invalidReadUrlReported||(this.invalidReadUrlReported=!0,console.error("Velt [portable backend]: getDownloadUrl answered a read URL that is not https (loopback http excepted); the attachment is not shown. Check the storage endpoint the gateway signs URLs for.")),this.recordUrlFailure(e),null;let I=Date.now();return this.pruneUrlCache(I),this.urlCache.set(e,{url:f.url,expiresAtMs:Ue(f.expiresAtMs,I,u),receivedAtMs:I,afterLoadError:l}),this.urlFailures.delete(e),f.url}catch(a){return this.loggingService.catch("Error in PortableAttachmentStorageService getDownloadUrl: ",a,void 0,!0),this.recordUrlFailure(e),null}finally{this.urlInFlight.get(e)===c&&this.urlInFlight.delete(e),this.bumpKey(e)}}),this.urlInFlight.set(e,c),c}isFresh(e,t){return t<e.expiresAtMs-ge||t-e.receivedAtMs<te}inFailureBackoff(e,t){let r=this.urlFailures.get(e);return r!==void 0&&t-r.at<re(r.count)}keyVersion(e){let t=this.urlKeyVersions.get(e);return t||(t=P(0),this.urlKeyVersions.set(e,t)),t()}bumpKey(e){this.urlKeyVersions.get(e)?.update(t=>t+1)}recordUrlFailure(e){let t=(this.urlFailures.get(e)?.count??0)+1;this.urlFailures.set(e,{at:Date.now(),count:t}),setTimeout(()=>this.bumpKey(e),re(t)+50)}pruneUrlCache(e){if(!(this.urlCache.size<ie)){for(let[t,r]of Array.from(this.urlCache))e>=r.expiresAtMs&&e-r.receivedAtMs>=te&&this.urlCache.delete(t);for(let t of Array.from(this.urlCache.keys())){if(this.urlCache.size<2*ie)break;this.urlCache.delete(t)}}}watchUser(){if(!this.userWatched){this.userWatched=!0;try{let e=!0;this.watchedUserId=this.currentUserId(),this.auth.getUser$().subscribe(t=>{let r=typeof t?.userId=="string"&&t.userId.length>0?t.userId:null;if(e||r===this.watchedUserId){this.watchedUserId=r;return}this.watchedUserId=r,this.urlCache.clear(),this.urlFailures.clear(),this.urlMissing.clear(),this.urlKeyVersions.clear(),this.cacheOwner=r,queueMicrotask(()=>this.urlGeneration.update(i=>i+1))}),e=!1}catch(e){this.loggingService.catch("Error in PortableAttachmentStorageService watchUser: ",e,void 0,!0)}}}serverTimeOffsetMs(){return p(this,null,function*(){try{let e=yield _()?.realtime?.getServerTimeOffset?.();return typeof e=="number"&&Number.isFinite(e)?e:0}catch{return 0}})}urlContext(e,t){let r=this.attachmentIds(e,t),i=this.currentUserId();return!r||!i?null:(this.cacheOwner!==i&&(this.urlCache.clear(),this.urlFailures.clear(),this.urlMissing.clear(),this.cacheOwner=i),{ids:r,userId:i,key:`${i}\0${r.organizationId}\0${r.documentId}\0${String(e.attachmentId)}`})}attachmentsAvailable$(){return new L(e=>{let t,r=()=>{try{let o=this.evaluateAvailability();o!==t&&(t=o,e.next(o))}catch(o){this.loggingService.catch("Error in PortableAttachmentStorageService attachmentsAvailable$: ",o,void 0,!0)}};this.hookRealtime(),this.availabilityListeners.add(r);let i=q(()=>{this.hookRealtime(),r()});r();let l=null;try{l=this.auth.getUser$().subscribe(()=>r())}catch(o){this.loggingService.catch("Error in PortableAttachmentStorageService attachmentsAvailable$ user stream: ",o,void 0,!0)}return()=>{this.availabilityListeners.delete(r),i(),l?.unsubscribe()}})}isUploadUnavailable(){try{this.hookRealtime()}catch(e){this.loggingService.catch("Error in PortableAttachmentStorageService isUploadUnavailable: ",e,void 0,!0)}return!this.evaluateAvailability()}evaluateAvailability(){return this.isPortableSession()?this.attachmentsAnnounced:!this.isPortableAttachmentDeployment()}hookRealtime(){try{let e=_()?.realtime??null;if(!e||e===this.hookedRealtime)return;this.offCapabilities?.(),this.hookedRealtime=e,this.attachmentsAnnounced=e.hasCapability?.(M)===!0,this.offCapabilities=e.onCapabilitiesChanged?.(t=>{this.attachmentsAnnounced=!!t&&typeof t.has=="function"&&t.has(M),this.notifyAvailability()})??null}catch(e){this.loggingService.catch("Error in PortableAttachmentStorageService hookRealtime: ",e,void 0,!0)}}notifyAvailability(){for(let e of Array.from(this.availabilityListeners))e()}attachmentIds(e,t){return this.scopeIds({organizationId:e?.clientOrganizationId,documentId:e?.clientDocumentId})??this.scopeIds(t)}scopeIds(e){let t=typeof e?.organizationId=="string"&&e.organizationId.length>0?e.organizationId:null,r=typeof e?.documentId=="string"&&e.documentId.length>0?e.documentId:null;return t&&r?{organizationId:t,documentId:r}:null}currentUserId(){try{let e=this.auth.getUser()?.userId;return typeof e=="string"&&e.length>0?e:null}catch{return null}}isSameSession(e){return!!e&&this.isPortableSession()&&this.currentUserId()===e}waitForActiveBackend(){return p(this,null,function*(){try{return this.selector.isPortableBackendActive()===!0?!0:(this.selector.isPortableBackendPending?.()===!0&&(yield W(pe)),this.selector.isPortableBackendActive()===!0)}catch(e){return this.loggingService.catch("Error in PortableAttachmentStorageService waitForActiveBackend: ",e,void 0,!0),!1}})}callOp(e,t){return G(this.selector.resolveDbAdapter(),e,{scope:"doc",data:t})}reportOpFailure(e,t,r=!1){try{if(O(t)){let i=t?.code??"unknown";this.loggingService.log(`Tier B ${e} is not served by this deployment (${i}): comment attachments are not available`);return}if(r){let i=t?.code??"unknown",l=`${e}:${i}`;if(this.hotPathReported.has(l)){this.loggingService.log(`Tier B ${e} refused again: ${i}`);return}this.hotPathReported.add(l)}Z(e,t,{logCatch:(i,l)=>this.loggingService.catch(i,l,void 0,!0),reported:this.reportedOpFailures,isOutcomeUnknown:ee})}catch{}}notSent(e,t){let r=new m("failed-precondition",`Tier B attachment ${e} was not sent: ${t}`);return this.loggingService.catch(r.message,void 0,void 0,!0),r}dropped(e){let t=new m("failed-precondition",`Tier B attachment upload was dropped: ${e}`);return this.loggingService.catch(t.message,void 0,void 0,!0),t}};n.\u0275fac=function(t){return new(t||n)(g(N),g(y))},n.\u0275prov=A({token:n,factory:n.\u0275fac,providedIn:"root"});let s=n;return s})();var le=s=>{try{let n={USE_PROFILES:{svg:!0,svgFilters:!0},FORBID_ATTR:["onerror","onload","onclick","onmouseover","onmouseout","onmouseenter","onmouseleave","onmousemove","onmousedown","onmouseup","onwheel","onscroll","onkeydown","onkeyup","onkeypress","onfocus","onblur","onchange","onsubmit","on*"],FORBID_TAGS:["script","style","iframe","object","embed","form"]};return Y.sanitize(s,n)}catch(n){return S.catch("Error in File utils sanitizeSvg: ",n),""}},ce=s=>{try{return s.name.split(".").slice(0,-1).join(".")}catch(n){S.catch("Error in File utils getFileName: ",n);return}},D=s=>{try{return/(?:\.([^.]+))?$/.exec(s?.name)[1]}catch(n){S.catch("Error in File utils getFileExtension: ",n);return}},he=(s,n)=>{try{let d=s.slice(0,-1,s.type);return new File([d],n+"."+D(s),{type:s.type})}catch(d){S.catch("Error in File utils updateFile: ",d);return}};var B={mp4:"video/mp4",mov:"video/quicktime",avi:"video/x-msvideo",wmv:"video/x-ms-wmv",flv:"video/x-flv",mp3:"audio/mpeg",wav:"audio/wav",ogg:"audio/ogg",webm:"video/webm",mkv:"video/x-matroska",m4v:"video/x-m4v",m4a:"audio/x-m4a",aac:"audio/aac","3gp":"video/3gpp","3g2":"video/3gpp2",jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",gif:"image/gif",bmp:"image/bmp",svg:"image/svg+xml",webp:"image/webp",pdf:"application/pdf",doc:"application/msword",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document",xls:"application/vnd.ms-excel",xlsx:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",ppt:"application/vnd.ms-powerpoint",pptx:"application/vnd.openxmlformats-officedocument.presentationml.presentation",odt:"application/vnd.oasis.opendocument.text",ods:"application/vnd.oasis.opendocument.spreadsheet",zip:"application/zip",rar:"application/x-rar-compressed",txt:"text/plain",rtf:"application/rtf",html:"text/html",htm:"text/html",csv:"text/csv",ics:"text/calendar",vcf:"text/x-vcard",js:"application/javascript",css:"text/css",json:"application/json",xml:"application/xml",swf:"application/x-shockwave-flash"};var ue=(()=>{let n=class n{getStorageInstance(e){return e?U(void 0,e):U()}ref(e,t){return H(e,t)}uploadBytesResumable(e,t,r){return j(e,t,r)}getDownloadURL(e){return z(e)}deleteObject(e){return $(e)}};n.\u0275fac=function(t){return new(t||n)},n.\u0275prov=A({token:n,factory:n.\u0275fac,providedIn:"root"});let s=n;return s})();var it=(()=>{let n=class n{constructor(e,t,r,i,l,o,c){this.authService=e,this.configService=t,this.coreActionsService=r,this.loggingService=i,this.attachmentResolverService=l,this.storageAdapter=o,this.portableAttachments=c,this.storage=this.storageAdapter.getStorageInstance();try{this.configService.getApiKey$().subscribe(a=>{this.apiKey=a}),this.authService.getFirebaseConfig$().subscribe(a=>{if(a&&a.firebaseOptions?.storageBucket){this.storage=this.storageAdapter.getStorageInstance(a?.firebaseOptions?.storageBucket);let h=this.configService.getProxyConfig();h?.storageHost&&(this.storage.host=h.storageHost)}},a=>{this.loggingService.catch("Error in StorageService constructor: ",a)})}catch(a){this.loggingService.catch("Error in StorageService constructor:",a)}}createAttachment({path:e,file:t}){try{let r=new V;r.name=t.name;let i=he(t,`${r.attachmentId}_${ce(t)}`),l=`${this.apiKey}/${e}/${i?.name}`;return r.bucketPath=l,r.size=t.size,r.type=D(t),r?.type&&(r.mimeType=B[r?.type]),r}catch(r){return this.loggingService.catch("Error in StorageService createAttachment: ",r),null}}sanitizeSvgFile(e){return p(this,null,function*(){if(e.type===B.svg)try{let t=yield e.text(),r=le(t);return new File([r],e.name,{type:e.type})}catch(t){return this.loggingService.catch("Error in StorageService sanitizeSvgFile: ",t),e}return e})}uploadAttachmentToStorage(l){return p(this,arguments,function*({attachment:e,file:t,resolve:r,reject:i}){try{let o=this.storageAdapter.ref(this.storage,e.bucketPath),c=this.storageAdapter.uploadBytesResumable(o,t,{cacheControl:"public,max-age=3600"});c.on("state_changed",a=>{let h=a.bytesTransferred/a.totalBytes*100},a=>{i(a)},()=>{this.storageAdapter.getDownloadURL(c.snapshot.ref).then(a=>{e.url=a,r(e)})})}catch(o){this.loggingService.catch("Error in StorageService uploadAttachmentToStorage: ",o),i(o)}})}uploadToResolver(c){return p(this,arguments,function*({file:e,attachment:t,metadata:r,resolve:i,reject:l,scope:o}){try{r.attachmentId=t.attachmentId;let a={attachmentId:t.attachmentId,name:t.name,file:e,metadata:r,mimeType:t.mimeType},h=F();this.coreActionsService.triggerAction(R.ATTACHMENT_RESOLVER,{event:k.Events.Resolver.ATTACHMENT_SAVE_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:h,methodName:x.UPLOAD_TO_RESOLVER,source:"internal",payload:{attachment:a,eventType:E.ATTACHMENT_ADD}});let u=yield this.attachmentResolverService.saveAttachment({attachment:a,eventType:E.ATTACHMENT_ADD},h,o);u&&u.data?.url?(t.url=u.data?.url,i(t)):l(new Error("Failed to upload attachment to resolver"))}catch(a){this.loggingService.catch("Error in StorageService uploadToResolver: ",a),l(a)}})}uploadFile({path:e,file:t,useAttachmentResolver:r,metadata:i,attachmentScope:l,portableScope:o}){return new Promise((c,a)=>p(this,null,function*(){try{if(!this.apiKey)throw new Error("API key not configured");let h=o&&!r?this.portableAttachments.captureSessionUser():null,u=yield this.sanitizeSvgFile(t),f=this.createAttachment({path:e,file:u});if(!f)throw new Error("Attachment not created");r?this.uploadToResolver({file:u,attachment:f,metadata:i,resolve:c,reject:a,scope:l}):o&&(h||this.portableAttachments.isPortableAttachmentDeployment())?this.portableAttachments.upload({attachment:f,file:u,scope:o,sessionUserId:h??void 0}).then(c,a):this.portableAttachments.isPortableAttachmentDeployment()?a(this.portableAttachments.refuseVeltStorage("uploadFile")):this.uploadAttachmentToStorage({attachment:f,file:u,resolve:c,reject:a})}catch(h){this.loggingService.catch("Error in StorageService uploadFile:",h),a(h)}}))}uploadChunk(e,t,r,i){return new Promise((l,o)=>{try{if(i?.useAttachmentResolver){let c=this.createAttachment({path:e,file:t});if(!c){o(new Error("Attachment not created for chunk upload"));return}this.uploadToResolver({file:t,attachment:c,metadata:i.metadata,resolve:a=>l(a.url),reject:o,scope:i.attachmentScope});return}if(this.portableAttachments.isPortableAttachmentDeployment()){o(this.portableAttachments.refuseVeltStorage("uploadChunk"));return}if(this.apiKey){let c=`${this.apiKey}/${e}/${t.name}`,a=this.storageAdapter.ref(this.storage,c),h=this.storageAdapter.uploadBytesResumable(a,t,{cacheControl:"public,max-age=3600"});h.on("state_changed",u=>{let f=u.bytesTransferred/u.totalBytes*100},u=>{o(u)},()=>{this.storageAdapter.getDownloadURL(h.snapshot.ref).then(u=>{l(u)}).catch(u=>{this.loggingService.catch(`[uploadChunk] Error getting download URL for chunk ${r}:`,u),o(u)})})}else{let c=new Error("API key not available");this.loggingService.catch("[uploadChunk] API key not available",c),o(c)}}catch(c){this.loggingService.catch(`[uploadChunk] Error in StorageService uploadChunk for chunk ${r}: `,c),o(c)}})}downloadAttachment(e,t){try{if(this.portableAttachments.isPortableAttachment(e)){let r=this.portableAttachments.captureSessionUser();this.portableAttachments.resolveDownloadUrl(e,t).then(i=>{i&&this.portableAttachments.isSameSessionUser(r)?this.downloadFromUrl(e,i,!0):i||this.loggingService.catch("Tier B attachment download: no read URL could be resolved; nothing was downloaded")}).catch(i=>{this.loggingService.catch("Error in StorageService downloadAttachment (Tier B): ",i)});return}e.url&&this.downloadFromUrl(e,e.url)}catch(r){this.loggingService.catch("Error in StorageService downloadAttachment: ",r)}}downloadFromUrl(e,t,r=!1){try{let i=new XMLHttpRequest;i.responseType="blob",i.onload=()=>{if(r&&(i.status<200||i.status>=300)){this.loggingService.catch(`Tier B attachment download failed: the storage answered HTTP ${i.status}`);return}let l=i.response,o=document.createElement("a"),c=window.URL.createObjectURL(l);o.setAttribute("type","hidden"),o.setAttribute(K.ATTRIBUTES.VELT_DOWNLOAD_BUTTON,"true"),o.classList.add("snippyly-overlay-panel"),o.href=c,e?.name&&(o.download=e?.name),document.body.appendChild(o);let a=new MouseEvent("click",{view:window,bubbles:!0,cancelable:!1});o.dispatchEvent(a),window.URL.revokeObjectURL(c),o.remove()},i.onerror=()=>{r?(this.loggingService.catch(`Tier B attachment download failed in transport; opening it in a new tab instead. ${se}`),window.open(t,"_blank","noopener,noreferrer")):window.open(t,"_blank")},i.open("GET",t),i.send()}catch(i){this.loggingService.catch("Error in StorageService downloadAttachment: ",i)}}deleteAttachment({attachment:e,metadata:t,useAttachmentResolver:r,attachmentScope:i,portableScope:l}){return new Promise((o,c)=>{if(r){let a=F();this.coreActionsService.triggerAction(R.ATTACHMENT_RESOLVER,{event:k.Events.Resolver.ATTACHMENT_DELETE_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:a,methodName:x.DELETE_ATTACHMENT,source:"internal",payload:{attachmentId:e.attachmentId,metadata:t}}),this.attachmentResolverService.deleteAttachment({attachmentId:e.attachmentId,metadata:t},a,i).then(()=>{o(null)}).catch(h=>{c(h)})}else if((l||v(e))&&this.portableAttachments.isPortableAttachmentDeployment())this.portableAttachments.delete({attachment:e,scope:l}).then(()=>o(null),()=>o(null));else if(this.portableAttachments.isPortableAttachmentDeployment())this.portableAttachments.refuseVeltStorage("deleteAttachment"),o(null);else{let a=this.storageAdapter.ref(this.storage,e.bucketPath);this.storageAdapter.deleteObject(a).then(()=>{o(null)}).catch(h=>{o(null)})}})}getAttachmentDisplayUrl(e,t){return this.portableAttachments.getDisplayUrl(e,t)}isAttachmentDisplayPending(e,t){return this.portableAttachments.isDisplayPending(e,t)}isPortableAttachment(e){return this.portableAttachments.isPortableAttachment(e)}resolveAttachmentUrl(e,t){return this.portableAttachments.resolveDownloadUrl(e,t)}reportAttachmentLoadError(e,t,r){this.portableAttachments.reportLoadError(e,t,r)}deleteFileFromPath(e){return new Promise((t,r)=>{if(this.portableAttachments.isPortableAttachmentDeployment()){r(this.portableAttachments.refuseVeltStorage("deleteFileFromPath"));return}let i=this.storageAdapter.ref(this.storage,e);this.storageAdapter.deleteObject(i).then(()=>{t(null)}).catch(l=>{r(l)})})}};n.\u0275fac=function(t){return new(t||n)(g(T),g(w),g(Q),g(y),g(J),g(ue),g(ae))},n.\u0275prov=A({token:n,factory:n.\u0275fac,providedIn:"root"});let s=n;return s})();export{ae as a,it as b};
1
+ import{b as $,c as z,d as U,e as H,f as j}from"./chunk-HIEV42PB.js";import{B as ee,b as Z,o as O,r as J}from"./chunk-NTFMMZRZ.js";import{He as K,Hi as k,Ie as V,Mj as G,Nj as q,Oj as W,Rj as _,Sj as X,Yd as S,_d as E,_j as M,a as b,ba as A,bf as x,ea as g,ee as R,g as p,i as L,na as N,nk as Q,ok as Y,pj as y,qj as w,rj as C,sa as P,sk as T,vg as F}from"./chunk-VESMHAEV.js";var pe=1e4,ge=6e4,te=3e4,me=3e4,fe=900*1e3;function re(s){let n=Math.max(0,Math.min(Math.floor(Number.isFinite(s)?s:1)-1,16));return Math.min(me*2**n,fe)}var Ae=3600*1e3,ie=250,ne=1200*1e3,Se=1024,ve={fetch:(s,n)=>fetch(s,n)},be="The browser could not send the file to the storage URL the gateway signed. The usual cause is the CORS rules of that storage (its storage account or bucket), which must allow this page's origin for PUT; they are set by the operator of the deployment, not by the SDK.",se="The browser could not read the file from the storage URL the gateway signed. The usual cause is the CORS rules of that storage (its storage account or bucket), which must allow this page's origin for GET; they are set by the operator of the deployment, not by the SDK.",m=class extends Error{constructor(n,d){super(d),this.code=n,this.name="PortableAttachmentError"}};function v(s){return!!s&&!s.url&&s.isAttachmentResolverUsed!==!0&&typeof s.bucketPath=="string"&&s.bucketPath.length>0&&s.attachmentId!==void 0&&s.attachmentId!==null&&String(s.attachmentId).length>0}function ye(s,n,d){let e={organizationId:n,documentId:d};return typeof s?.name=="string"&&s.name.length>0&&s.name.length<=Se&&(e.fileName=s.name),typeof s?.type=="string"&&s.type.length>0&&(e.contentType=s.type),Number.isInteger(s?.size)&&s.size>=0&&(e.sizeBytes=s.size),e}function we(s){return typeof s=="string"&&/^[A-Za-z0-9._-]{1,128}$/.test(s)&&!/^\.+$/.test(s)}function Te(s){return!!s&&typeof s=="object"&&!Array.isArray(s)&&Object.values(s).every(n=>typeof n=="string")}function Ie(s){let n=s;return!n||typeof n!="object"||!we(n.attachmentId)||typeof n.key!="string"||!n.key||typeof n.url!="string"||!C(n.url)||n.method!=="PUT"||!Te(n.headers)?null:{attachmentId:n.attachmentId,key:n.key,url:n.url,method:"PUT",headers:b({},n.headers),expiresAtMs:typeof n.expiresAtMs=="number"?n.expiresAtMs:0}}function Pe(s){let n=s;return!n||typeof n!="object"||typeof n.url!="string"||!C(n.url)?null:{key:typeof n.key=="string"?n.key:"",url:n.url,expiresAtMs:typeof n.expiresAtMs=="number"&&Number.isFinite(n.expiresAtMs)?n.expiresAtMs:0}}function Ue(s,n,d){let e=Number.isFinite(s)?s-(n+(Number.isFinite(d)?d:0)):0;return n+Math.min(Math.max(e,0),Ae)}var ae=(()=>{let n=class n{constructor(e,t){this.injector=e,this.loggingService=t,this.urlGeneration=P(0),this.urlKeyVersions=new Map,this.userWatched=!1,this.watchedUserId=null,this.urlCache=new Map,this.urlInFlight=new Map,this.urlFailures=new Map,this.urlMissing=new Set,this.cacheOwner=null,this.attachmentsAnnounced=!1,this.hookedRealtime=null,this.offCapabilities=null,this.availabilityListeners=new Set,this.veltStorageRefusalsReported=new Set,this.reportedOpFailures=new Set,this.invalidReadUrlReported=!1,this.hotPathReported=new Set,this.portableSessionSeen=!1}get selector(){return this._selector??=this.injector.get(X)}get auth(){return this._auth??=this.injector.get(T)}get config(){return this._config??=this.injector.get(w)}isPortableSession(){try{if(!this.auth.getPortableBackend?.())return!1;let e=this.selector.isPortableSession()===!0;return e&&(this.portableSessionSeen=!0),e}catch(e){return this.loggingService.catch("Error in PortableAttachmentStorageService isPortableSession: ",e,void 0,!0),!1}}isPortableAttachmentDeployment(){if(this.isPortableSession())return!0;if(!this.portableSessionSeen)return!1;try{return this.config.getEnablePortableBackend()===!0}catch(e){return this.loggingService.catch("Error in PortableAttachmentStorageService isPortableAttachmentDeployment: ",e,void 0,!0),!0}}captureSessionUser(){return this.isPortableSession()?this.currentUserId():null}isSameSessionUser(e){return this.isSameSession(e??null)}isPortableAttachment(e){return v(e)&&this.isPortableSession()}upload(l){return p(this,arguments,function*({attachment:e,file:t,scope:r,sessionUserId:i}){let o=this.scopeIds(r);if(!o)throw this.notSent("upload","the comment has no organization or document id");let c=i===void 0?this.currentUserId():i;if(!c)throw this.notSent("upload","no user is signed in");if(!this.isSameSession(c))throw this.notSent("upload","the session changed before the upload started");if(!(yield this.waitForActiveBackend())||!this.isSameSession(c))throw this.notSent("upload","the portable backend is not active");let a=yield this.callOp("getUploadUrl",ye(t,o.organizationId,o.documentId));if(!this.isSameSession(c))throw this.dropped("the session changed while getUploadUrl ran; the file was not uploaded");if(!a?.ok){this.reportOpFailure("getUploadUrl",a);let u=`${a?.code??"unknown"}${a?.message?` (${a.message})`:""}`;throw new m(a?.code??"failed-precondition",O(a)?`Tier B comment attachments are not available on this deployment: getUploadUrl answered ${u}`:`Tier B getUploadUrl failed: ${u}`)}let h=Ie(a.data);if(!h){let u=new m("failed-precondition",'Tier B getUploadUrl answered a signed upload this SDK will not use (it needs method PUT, an https URL, string headers, an attachmentId of 1-128 letters, digits, ".", "_" or "-", and a key); the file was not uploaded');throw this.loggingService.catch(u.message,void 0,void 0,!0),u}if(yield this.putSignedUpload(h,t),!this.isSameSession(c))throw this.dropped("the session changed while the file uploaded; the attachment is not added");return e.attachmentId=h.attachmentId,e.bucketPath=h.key,e.url="",e.clientOrganizationId=o.organizationId,e.clientDocumentId=o.documentId,e})}putSignedUpload(e,t){return p(this,null,function*(){let r=typeof AbortController=="function"?new AbortController:null,i=null,l=new Promise((o,c)=>{i=setTimeout(()=>{r?.abort(),c(new m("put-failed",`Tier B attachment upload failed: the storage did not answer the PUT within ${ne/6e4} minutes`))},ne)});try{let o=yield Promise.race([ve.fetch(e.url,b({method:"PUT",headers:b({},e.headers),body:t.slice(0,t.size,""),redirect:"error",credentials:"omit",referrerPolicy:"no-referrer"},r?{signal:r.signal}:{})),l]);if(!o?.ok)throw new m("put-failed",`Tier B attachment upload failed: the storage answered the PUT with HTTP ${o?.status}`)}catch(o){let c=o instanceof m?o:new m("put-failed",`Tier B attachment upload failed in transport: ${o?.message??o}. ${be}`);throw this.loggingService.catch(c.message,void 0,void 0,!0),c}finally{i!==null&&clearTimeout(i)}})}refuseVeltStorage(e){let t=new m("unimplemented",`Tier B ${e} was not sent: media outside comment attachments (recorder, tag) is not served by the portable backend, and Velt's storage is never used on a portable deployment`);try{this.veltStorageRefusalsReported.has(e)?this.loggingService.log(t.message):(this.veltStorageRefusalsReported.add(e),this.loggingService.catch(t.message,void 0,void 0,!0))}catch{}return t}delete(r){return p(this,arguments,function*({attachment:e,scope:t}){try{let i=this.attachmentIds(e,t),l=e?.attachmentId;if(!i||l===void 0||l===null||String(l).length===0){this.loggingService.catch("Tier B deleteAttachment was not sent: the attachment has no id, or the comment no organization or document id",void 0,void 0,!0);return}let o=this.currentUserId();if(!o||!(yield this.waitForActiveBackend())||!this.isSameSession(o)){this.loggingService.catch("Tier B deleteAttachment was not sent: the portable backend is not active",void 0,void 0,!0);return}let c=yield this.callOp("deleteAttachment",{organizationId:i.organizationId,documentId:i.documentId,attachmentId:String(l)});c?.ok||this.reportOpFailure("deleteAttachment",c)}catch(i){this.loggingService.catch("Error in PortableAttachmentStorageService delete: ",i,void 0,!0)}})}resolveDownloadUrl(e,t){try{if(!this.isPortableAttachment(e))return Promise.resolve(e?.url||null);let r=this.urlContext(e,t);if(!r||this.urlMissing.has(r.key))return Promise.resolve(null);let i=this.urlCache.get(r.key);return i&&this.isFresh(i,Date.now())?Promise.resolve(i.url):this.fetchDownloadUrl(r.key,e,r.ids,r.userId,!1)}catch(r){return this.loggingService.catch("Error in PortableAttachmentStorageService resolveDownloadUrl: ",r,void 0,!0),Promise.resolve(null)}}getDisplayUrl(e,t){if(!v(e))return e?.url;if(this.urlGeneration(),this.watchUser(),!this.isPortableSession())return e.url;try{let r=this.urlContext(e,t);if(!r)return e.url;if(this.keyVersion(r.key),this.urlMissing.has(r.key))return"";let i=Date.now(),l=this.urlCache.get(r.key);return l&&this.isFresh(l,i)?l.url:(this.inFailureBackoff(r.key,i)||this.fetchDownloadUrl(r.key,e,r.ids,r.userId,!1),l&&i<l.expiresAtMs?l.url:"")}catch(r){return this.loggingService.catch("Error in PortableAttachmentStorageService getDisplayUrl: ",r,void 0,!0),e.url}}isDisplayPending(e,t){if(!v(e)||!this.isPortableSession())return!1;try{if(this.getDisplayUrl(e,t))return!1;let r=this.urlContext(e,t);return!!r&&!this.urlMissing.has(r.key)&&!this.inFailureBackoff(r.key,Date.now())}catch(r){return this.loggingService.catch("Error in PortableAttachmentStorageService isDisplayPending: ",r,void 0,!0),!1}}reportLoadError(e,t,r){try{if(!this.isPortableAttachment(e))return;let i=this.urlContext(e,t),l=i?this.urlCache.get(i.key):void 0;if(!i||!l||l.afterLoadError||!r||l.url!==r)return;this.urlCache.delete(i.key),this.fetchDownloadUrl(i.key,e,i.ids,i.userId,!0),this.bumpKey(i.key)}catch(i){this.loggingService.catch("Error in PortableAttachmentStorageService reportLoadError: ",i,void 0,!0)}}fetchDownloadUrl(e,t,r,i,l){let o=this.urlInFlight.get(e);if(o)return o;let c;return c=p(this,null,function*(){try{if(!(yield this.waitForActiveBackend()))return this.recordUrlFailure(e),null;if(!this.isSameSession(i))return null;let a=this.serverTimeOffsetMs(),h=yield this.callOp("getDownloadUrl",{organizationId:r.organizationId,documentId:r.documentId,attachmentId:String(t.attachmentId)}),u=yield a;if(!this.isSameSession(i))return null;if(!h?.ok)return this.reportOpFailure("getDownloadUrl",h,!0),h?.code==="not-found"?(this.urlMissing.add(e),this.urlCache.delete(e),null):(this.recordUrlFailure(e),null);let f=Pe(h.data);if(!f)return this.invalidReadUrlReported||(this.invalidReadUrlReported=!0,console.error("Velt [portable backend]: getDownloadUrl answered a read URL that is not https (loopback http excepted); the attachment is not shown. Check the storage endpoint the gateway signs URLs for.")),this.recordUrlFailure(e),null;let I=Date.now();return this.pruneUrlCache(I),this.urlCache.set(e,{url:f.url,expiresAtMs:Ue(f.expiresAtMs,I,u),receivedAtMs:I,afterLoadError:l}),this.urlFailures.delete(e),f.url}catch(a){return this.loggingService.catch("Error in PortableAttachmentStorageService getDownloadUrl: ",a,void 0,!0),this.recordUrlFailure(e),null}finally{this.urlInFlight.get(e)===c&&this.urlInFlight.delete(e),this.bumpKey(e)}}),this.urlInFlight.set(e,c),c}isFresh(e,t){return t<e.expiresAtMs-ge||t-e.receivedAtMs<te}inFailureBackoff(e,t){let r=this.urlFailures.get(e);return r!==void 0&&t-r.at<re(r.count)}keyVersion(e){let t=this.urlKeyVersions.get(e);return t||(t=P(0),this.urlKeyVersions.set(e,t)),t()}bumpKey(e){this.urlKeyVersions.get(e)?.update(t=>t+1)}recordUrlFailure(e){let t=(this.urlFailures.get(e)?.count??0)+1;this.urlFailures.set(e,{at:Date.now(),count:t}),setTimeout(()=>this.bumpKey(e),re(t)+50)}pruneUrlCache(e){if(!(this.urlCache.size<ie)){for(let[t,r]of Array.from(this.urlCache))e>=r.expiresAtMs&&e-r.receivedAtMs>=te&&this.urlCache.delete(t);for(let t of Array.from(this.urlCache.keys())){if(this.urlCache.size<2*ie)break;this.urlCache.delete(t)}}}watchUser(){if(!this.userWatched){this.userWatched=!0;try{let e=!0;this.watchedUserId=this.currentUserId(),this.auth.getUser$().subscribe(t=>{let r=typeof t?.userId=="string"&&t.userId.length>0?t.userId:null;if(e||r===this.watchedUserId){this.watchedUserId=r;return}this.watchedUserId=r,this.urlCache.clear(),this.urlFailures.clear(),this.urlMissing.clear(),this.urlKeyVersions.clear(),this.cacheOwner=r,queueMicrotask(()=>this.urlGeneration.update(i=>i+1))}),e=!1}catch(e){this.loggingService.catch("Error in PortableAttachmentStorageService watchUser: ",e,void 0,!0)}}}serverTimeOffsetMs(){return p(this,null,function*(){try{let e=yield _()?.realtime?.getServerTimeOffset?.();return typeof e=="number"&&Number.isFinite(e)?e:0}catch{return 0}})}urlContext(e,t){let r=this.attachmentIds(e,t),i=this.currentUserId();return!r||!i?null:(this.cacheOwner!==i&&(this.urlCache.clear(),this.urlFailures.clear(),this.urlMissing.clear(),this.cacheOwner=i),{ids:r,userId:i,key:`${i}\0${r.organizationId}\0${r.documentId}\0${String(e.attachmentId)}`})}attachmentsAvailable$(){return new L(e=>{let t,r=()=>{try{let o=this.evaluateAvailability();o!==t&&(t=o,e.next(o))}catch(o){this.loggingService.catch("Error in PortableAttachmentStorageService attachmentsAvailable$: ",o,void 0,!0)}};this.hookRealtime(),this.availabilityListeners.add(r);let i=q(()=>{this.hookRealtime(),r()});r();let l=null;try{l=this.auth.getUser$().subscribe(()=>r())}catch(o){this.loggingService.catch("Error in PortableAttachmentStorageService attachmentsAvailable$ user stream: ",o,void 0,!0)}return()=>{this.availabilityListeners.delete(r),i(),l?.unsubscribe()}})}isUploadUnavailable(){try{this.hookRealtime()}catch(e){this.loggingService.catch("Error in PortableAttachmentStorageService isUploadUnavailable: ",e,void 0,!0)}return!this.evaluateAvailability()}evaluateAvailability(){return this.isPortableSession()?this.attachmentsAnnounced:!this.isPortableAttachmentDeployment()}hookRealtime(){try{let e=_()?.realtime??null;if(!e||e===this.hookedRealtime)return;this.offCapabilities?.(),this.hookedRealtime=e,this.attachmentsAnnounced=e.hasCapability?.(M)===!0,this.offCapabilities=e.onCapabilitiesChanged?.(t=>{this.attachmentsAnnounced=!!t&&typeof t.has=="function"&&t.has(M),this.notifyAvailability()})??null}catch(e){this.loggingService.catch("Error in PortableAttachmentStorageService hookRealtime: ",e,void 0,!0)}}notifyAvailability(){for(let e of Array.from(this.availabilityListeners))e()}attachmentIds(e,t){return this.scopeIds({organizationId:e?.clientOrganizationId,documentId:e?.clientDocumentId})??this.scopeIds(t)}scopeIds(e){let t=typeof e?.organizationId=="string"&&e.organizationId.length>0?e.organizationId:null,r=typeof e?.documentId=="string"&&e.documentId.length>0?e.documentId:null;return t&&r?{organizationId:t,documentId:r}:null}currentUserId(){try{let e=this.auth.getUser()?.userId;return typeof e=="string"&&e.length>0?e:null}catch{return null}}isSameSession(e){return!!e&&this.isPortableSession()&&this.currentUserId()===e}waitForActiveBackend(){return p(this,null,function*(){try{return this.selector.isPortableBackendActive()===!0?!0:(this.selector.isPortableBackendPending?.()===!0&&(yield W(pe)),this.selector.isPortableBackendActive()===!0)}catch(e){return this.loggingService.catch("Error in PortableAttachmentStorageService waitForActiveBackend: ",e,void 0,!0),!1}})}callOp(e,t){return G(this.selector.resolveDbAdapter(),e,{scope:"doc",data:t})}reportOpFailure(e,t,r=!1){try{if(O(t)){let i=t?.code??"unknown";this.loggingService.log(`Tier B ${e} is not served by this deployment (${i}): comment attachments are not available`);return}if(r){let i=t?.code??"unknown",l=`${e}:${i}`;if(this.hotPathReported.has(l)){this.loggingService.log(`Tier B ${e} refused again: ${i}`);return}this.hotPathReported.add(l)}Z(e,t,{logCatch:(i,l)=>this.loggingService.catch(i,l,void 0,!0),reported:this.reportedOpFailures,isOutcomeUnknown:ee})}catch{}}notSent(e,t){let r=new m("failed-precondition",`Tier B attachment ${e} was not sent: ${t}`);return this.loggingService.catch(r.message,void 0,void 0,!0),r}dropped(e){let t=new m("failed-precondition",`Tier B attachment upload was dropped: ${e}`);return this.loggingService.catch(t.message,void 0,void 0,!0),t}};n.\u0275fac=function(t){return new(t||n)(g(N),g(y))},n.\u0275prov=A({token:n,factory:n.\u0275fac,providedIn:"root"});let s=n;return s})();var le=s=>{try{let n={USE_PROFILES:{svg:!0,svgFilters:!0},FORBID_ATTR:["onerror","onload","onclick","onmouseover","onmouseout","onmouseenter","onmouseleave","onmousemove","onmousedown","onmouseup","onwheel","onscroll","onkeydown","onkeyup","onkeypress","onfocus","onblur","onchange","onsubmit","on*"],FORBID_TAGS:["script","style","iframe","object","embed","form"]};return Y.sanitize(s,n)}catch(n){return S.catch("Error in File utils sanitizeSvg: ",n),""}},ce=s=>{try{return s.name.split(".").slice(0,-1).join(".")}catch(n){S.catch("Error in File utils getFileName: ",n);return}},D=s=>{try{return/(?:\.([^.]+))?$/.exec(s?.name)[1]}catch(n){S.catch("Error in File utils getFileExtension: ",n);return}},he=(s,n)=>{try{let d=s.slice(0,-1,s.type);return new File([d],n+"."+D(s),{type:s.type})}catch(d){S.catch("Error in File utils updateFile: ",d);return}};var B={mp4:"video/mp4",mov:"video/quicktime",avi:"video/x-msvideo",wmv:"video/x-ms-wmv",flv:"video/x-flv",mp3:"audio/mpeg",wav:"audio/wav",ogg:"audio/ogg",webm:"video/webm",mkv:"video/x-matroska",m4v:"video/x-m4v",m4a:"audio/x-m4a",aac:"audio/aac","3gp":"video/3gpp","3g2":"video/3gpp2",jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",gif:"image/gif",bmp:"image/bmp",svg:"image/svg+xml",webp:"image/webp",pdf:"application/pdf",doc:"application/msword",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document",xls:"application/vnd.ms-excel",xlsx:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",ppt:"application/vnd.ms-powerpoint",pptx:"application/vnd.openxmlformats-officedocument.presentationml.presentation",odt:"application/vnd.oasis.opendocument.text",ods:"application/vnd.oasis.opendocument.spreadsheet",zip:"application/zip",rar:"application/x-rar-compressed",txt:"text/plain",rtf:"application/rtf",html:"text/html",htm:"text/html",csv:"text/csv",ics:"text/calendar",vcf:"text/x-vcard",js:"application/javascript",css:"text/css",json:"application/json",xml:"application/xml",swf:"application/x-shockwave-flash"};var ue=(()=>{let n=class n{getStorageInstance(e){return e?U(void 0,e):U()}ref(e,t){return H(e,t)}uploadBytesResumable(e,t,r){return j(e,t,r)}getDownloadURL(e){return z(e)}deleteObject(e){return $(e)}};n.\u0275fac=function(t){return new(t||n)},n.\u0275prov=A({token:n,factory:n.\u0275fac,providedIn:"root"});let s=n;return s})();var it=(()=>{let n=class n{constructor(e,t,r,i,l,o,c){this.authService=e,this.configService=t,this.coreActionsService=r,this.loggingService=i,this.attachmentResolverService=l,this.storageAdapter=o,this.portableAttachments=c,this.storage=this.storageAdapter.getStorageInstance();try{this.configService.getApiKey$().subscribe(a=>{this.apiKey=a}),this.authService.getFirebaseConfig$().subscribe(a=>{if(a&&a.firebaseOptions?.storageBucket){this.storage=this.storageAdapter.getStorageInstance(a?.firebaseOptions?.storageBucket);let h=this.configService.getProxyConfig();h?.storageHost&&(this.storage.host=h.storageHost)}},a=>{this.loggingService.catch("Error in StorageService constructor: ",a)})}catch(a){this.loggingService.catch("Error in StorageService constructor:",a)}}createAttachment({path:e,file:t}){try{let r=new V;r.name=t.name;let i=he(t,`${r.attachmentId}_${ce(t)}`),l=`${this.apiKey}/${e}/${i?.name}`;return r.bucketPath=l,r.size=t.size,r.type=D(t),r?.type&&(r.mimeType=B[r?.type]),r}catch(r){return this.loggingService.catch("Error in StorageService createAttachment: ",r),null}}sanitizeSvgFile(e){return p(this,null,function*(){if(e.type===B.svg)try{let t=yield e.text(),r=le(t);return new File([r],e.name,{type:e.type})}catch(t){return this.loggingService.catch("Error in StorageService sanitizeSvgFile: ",t),e}return e})}uploadAttachmentToStorage(l){return p(this,arguments,function*({attachment:e,file:t,resolve:r,reject:i}){try{let o=this.storageAdapter.ref(this.storage,e.bucketPath),c=this.storageAdapter.uploadBytesResumable(o,t,{cacheControl:"public,max-age=3600"});c.on("state_changed",a=>{let h=a.bytesTransferred/a.totalBytes*100},a=>{i(a)},()=>{this.storageAdapter.getDownloadURL(c.snapshot.ref).then(a=>{e.url=a,r(e)})})}catch(o){this.loggingService.catch("Error in StorageService uploadAttachmentToStorage: ",o),i(o)}})}uploadToResolver(c){return p(this,arguments,function*({file:e,attachment:t,metadata:r,resolve:i,reject:l,scope:o}){try{r.attachmentId=t.attachmentId;let a={attachmentId:t.attachmentId,name:t.name,file:e,metadata:r,mimeType:t.mimeType},h=F();this.coreActionsService.triggerAction(R.ATTACHMENT_RESOLVER,{event:k.Events.Resolver.ATTACHMENT_SAVE_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:h,methodName:x.UPLOAD_TO_RESOLVER,source:"internal",payload:{attachment:a,eventType:E.ATTACHMENT_ADD}});let u=yield this.attachmentResolverService.saveAttachment({attachment:a,eventType:E.ATTACHMENT_ADD},h,o);u&&u.data?.url?(t.url=u.data?.url,i(t)):l(new Error("Failed to upload attachment to resolver"))}catch(a){this.loggingService.catch("Error in StorageService uploadToResolver: ",a),l(a)}})}uploadFile({path:e,file:t,useAttachmentResolver:r,metadata:i,attachmentScope:l,portableScope:o}){return new Promise((c,a)=>p(this,null,function*(){try{if(!this.apiKey)throw new Error("API key not configured");let h=o&&!r?this.portableAttachments.captureSessionUser():null,u=yield this.sanitizeSvgFile(t),f=this.createAttachment({path:e,file:u});if(!f)throw new Error("Attachment not created");r?this.uploadToResolver({file:u,attachment:f,metadata:i,resolve:c,reject:a,scope:l}):o&&(h||this.portableAttachments.isPortableAttachmentDeployment())?this.portableAttachments.upload({attachment:f,file:u,scope:o,sessionUserId:h??void 0}).then(c,a):this.portableAttachments.isPortableAttachmentDeployment()?a(this.portableAttachments.refuseVeltStorage("uploadFile")):this.uploadAttachmentToStorage({attachment:f,file:u,resolve:c,reject:a})}catch(h){this.loggingService.catch("Error in StorageService uploadFile:",h),a(h)}}))}uploadChunk(e,t,r,i){return new Promise((l,o)=>{try{if(i?.useAttachmentResolver){let c=this.createAttachment({path:e,file:t});if(!c){o(new Error("Attachment not created for chunk upload"));return}this.uploadToResolver({file:t,attachment:c,metadata:i.metadata,resolve:a=>l(a.url),reject:o,scope:i.attachmentScope});return}if(this.portableAttachments.isPortableAttachmentDeployment()){o(this.portableAttachments.refuseVeltStorage("uploadChunk"));return}if(this.apiKey){let c=`${this.apiKey}/${e}/${t.name}`,a=this.storageAdapter.ref(this.storage,c),h=this.storageAdapter.uploadBytesResumable(a,t,{cacheControl:"public,max-age=3600"});h.on("state_changed",u=>{let f=u.bytesTransferred/u.totalBytes*100},u=>{o(u)},()=>{this.storageAdapter.getDownloadURL(h.snapshot.ref).then(u=>{l(u)}).catch(u=>{this.loggingService.catch(`[uploadChunk] Error getting download URL for chunk ${r}:`,u),o(u)})})}else{let c=new Error("API key not available");this.loggingService.catch("[uploadChunk] API key not available",c),o(c)}}catch(c){this.loggingService.catch(`[uploadChunk] Error in StorageService uploadChunk for chunk ${r}: `,c),o(c)}})}downloadAttachment(e,t){try{if(this.portableAttachments.isPortableAttachment(e)){let r=this.portableAttachments.captureSessionUser();this.portableAttachments.resolveDownloadUrl(e,t).then(i=>{i&&this.portableAttachments.isSameSessionUser(r)?this.downloadFromUrl(e,i,!0):i||this.loggingService.catch("Tier B attachment download: no read URL could be resolved; nothing was downloaded")}).catch(i=>{this.loggingService.catch("Error in StorageService downloadAttachment (Tier B): ",i)});return}e.url&&this.downloadFromUrl(e,e.url)}catch(r){this.loggingService.catch("Error in StorageService downloadAttachment: ",r)}}downloadFromUrl(e,t,r=!1){try{let i=new XMLHttpRequest;i.responseType="blob",i.onload=()=>{if(r&&(i.status<200||i.status>=300)){this.loggingService.catch(`Tier B attachment download failed: the storage answered HTTP ${i.status}`);return}let l=i.response,o=document.createElement("a"),c=window.URL.createObjectURL(l);o.setAttribute("type","hidden"),o.setAttribute(K.ATTRIBUTES.VELT_DOWNLOAD_BUTTON,"true"),o.classList.add("snippyly-overlay-panel"),o.href=c,e?.name&&(o.download=e?.name),document.body.appendChild(o);let a=new MouseEvent("click",{view:window,bubbles:!0,cancelable:!1});o.dispatchEvent(a),window.URL.revokeObjectURL(c),o.remove()},i.onerror=()=>{r?(this.loggingService.catch(`Tier B attachment download failed in transport; opening it in a new tab instead. ${se}`),window.open(t,"_blank","noopener,noreferrer")):window.open(t,"_blank")},i.open("GET",t),i.send()}catch(i){this.loggingService.catch("Error in StorageService downloadAttachment: ",i)}}deleteAttachment({attachment:e,metadata:t,useAttachmentResolver:r,attachmentScope:i,portableScope:l}){return new Promise((o,c)=>{if(r){let a=F();this.coreActionsService.triggerAction(R.ATTACHMENT_RESOLVER,{event:k.Events.Resolver.ATTACHMENT_DELETE_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:a,methodName:x.DELETE_ATTACHMENT,source:"internal",payload:{attachmentId:e.attachmentId,metadata:t}}),this.attachmentResolverService.deleteAttachment({attachmentId:e.attachmentId,metadata:t},a,i).then(()=>{o(null)}).catch(h=>{c(h)})}else if((l||v(e))&&this.portableAttachments.isPortableAttachmentDeployment())this.portableAttachments.delete({attachment:e,scope:l}).then(()=>o(null),()=>o(null));else if(this.portableAttachments.isPortableAttachmentDeployment())this.portableAttachments.refuseVeltStorage("deleteAttachment"),o(null);else{let a=this.storageAdapter.ref(this.storage,e.bucketPath);this.storageAdapter.deleteObject(a).then(()=>{o(null)}).catch(h=>{o(null)})}})}getAttachmentDisplayUrl(e,t){return this.portableAttachments.getDisplayUrl(e,t)}isAttachmentDisplayPending(e,t){return this.portableAttachments.isDisplayPending(e,t)}isPortableAttachment(e){return this.portableAttachments.isPortableAttachment(e)}resolveAttachmentUrl(e,t){return this.portableAttachments.resolveDownloadUrl(e,t)}reportAttachmentLoadError(e,t,r){this.portableAttachments.reportLoadError(e,t,r)}deleteFileFromPath(e){return new Promise((t,r)=>{if(this.portableAttachments.isPortableAttachmentDeployment()){r(this.portableAttachments.refuseVeltStorage("deleteFileFromPath"));return}let i=this.storageAdapter.ref(this.storage,e);this.storageAdapter.deleteObject(i).then(()=>{t(null)}).catch(l=>{r(l)})})}};n.\u0275fac=function(t){return new(t||n)(g(T),g(w),g(Q),g(y),g(J),g(ue),g(ae))},n.\u0275prov=A({token:n,factory:n.\u0275fac,providedIn:"root"});let s=n;return s})();export{ae as a,it as b};