@wcstack/fetch 1.22.6 → 1.24.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,2 +1,2 @@
1
- const t={autoTrigger:!0,triggerAttribute:"data-fetchtarget",tagNames:{fetch:"wcs-fetch",fetchHeader:"wcs-fetch-header",fetchBody:"wcs-fetch-body",infiniteScroll:"wcs-infinite-scroll"}};function e(t){if(null===t||"object"!=typeof t)return t;Object.freeze(t);for(const r of Object.keys(t))e(t[r]);return t}function r(t){if(null===t||"object"!=typeof t)return t;const e={};for(const i of Object.keys(t))e[i]=r(t[i]);return e}let i=null;const s=t;function n(){return i||(i=e(r(t))),i}class o{laneKey;policy;_ownerGeneration=0;_latestEpoch=0;_nextOperationId=1;_activeOperationId=void 0;_activeOperationIds=new Set;_queue=[];_inFlightCount=0;_terminal=new Map;_claimedOutcome=new Map;_controllers=new Map;_attempts=new Map;_withSignal;_trace;constructor(t,e,r={}){this.laneKey=t,this.policy=e,this._withSignal=r.withSignal??!1,this._trace=r.trace}get ownerGeneration(){return this._ownerGeneration}get inFlightCount(){return this._inFlightCount}get latestEpoch(){return this._latestEpoch}get activeOperationId(){return this._activeOperationId}begin(){let t;switch(this.policy){case"latest":t=++this._latestEpoch,void 0!==this._activeOperationId&&this._abortController(this._activeOperationId);break;case"exhaust":if(void 0!==this._activeOperationId)return null}const e=this._nextOperationId++,r={operationId:e,ownerGeneration:this._ownerGeneration,laneKey:this.laneKey,policy:this.policy,supersedeEpoch:t};switch(this.policy){case"latest":case"exhaust":this._activeOperationId=e;break;case"queue":this._queue.push(r),void 0===this._activeOperationId&&(this._activeOperationId=e);break;case"overlap":this._activeOperationIds.add(e)}this._inFlightCount+=1,this._attempts.set(e,1);const i=this._makeAttempt(e,1);return void 0!==this._trace&&this._trace({type:"io:operation-started",operationId:e,laneKey:this.laneKey,policy:this.policy}),{ticket:r,attempt:i}}retry(t){if(t.ownerGeneration!==this._ownerGeneration)return null;if(this._terminal.has(t.operationId))return null;const e=this._attempts.get(t.operationId);if(void 0===e)return null;const r=e+1;this._attempts.set(t.operationId,r),this._releaseController(t.operationId);const i=this._makeAttempt(t.operationId,r);return void 0!==this._trace&&this._trace({type:"io:operation-retried",operationId:t.operationId,laneKey:this.laneKey,attempt:r}),i}canCommit(t){if(t.ownerGeneration!==this._ownerGeneration)return!1;const e=this._terminal.get(t.operationId);return(void 0===e||"committing"===e)&&this._isEligible(t)}claimTerminal(t,e){return t.ownerGeneration===this._ownerGeneration&&(!this._terminal.has(t.operationId)&&(!!this._isEligible(t)&&(this._terminal.set(t.operationId,"committing"),this._claimedOutcome.set(t.operationId,e),!0)))}claimedOutcome(t){return this._claimedOutcome.get(t.operationId)}finalize(t){const e=t.operationId,r=this._terminal.get(e);if(void 0!==r&&"committing"!==r)return;let i;i="committing"===r?this._claimedOutcome.get(e)??"stale":"stale",this._terminal.set(e,i),this._claimedOutcome.delete(e),this._releaseController(e),this._attempts.delete(e),this._inFlightCount>0&&(this._inFlightCount-=1),this._advanceBookkeeping(e),void 0!==this._trace&&("stale"===i?this._trace({type:"io:stale-dropped",operationId:e,laneKey:this.laneKey}):this._trace({type:"io:operation-settled",operationId:e,laneKey:this.laneKey,outcome:i}))}signalOf(t){return this._controllers.get(t.operationId)?.signal}abort(t){this._abortController(t.operationId)}abortActive(){void 0!==this._activeOperationId&&this._abortController(this._activeOperationId);for(const t of this._activeOperationIds)this._abortController(t)}disposeOwner(){this._ownerGeneration+=1;for(const t of Array.from(this._controllers.keys()))this._abortController(t),this._releaseController(t);for(const t of Array.from(this._attempts.keys()))this._terminal.has(t)||this._terminal.set(t,"stale"),this._claimedOutcome.delete(t),this._attempts.delete(t),void 0!==this._trace&&this._trace({type:"io:stale-dropped",operationId:t,laneKey:this.laneKey});this._activeOperationId=void 0,this._activeOperationIds.clear(),this._queue.length=0,this._inFlightCount=0}_makeAttempt(t,e){let r;if(this._withSignal&&"function"==typeof AbortController){const e=new AbortController;this._controllers.set(t,e),r=e.signal}return{operationId:t,attempt:e,signal:r}}_isEligible(t){switch(this.policy){case"latest":return t.supersedeEpoch===this._latestEpoch;case"queue":case"exhaust":return this._activeOperationId===t.operationId;case"overlap":return this._activeOperationIds.has(t.operationId)}}_advanceBookkeeping(t){switch(this.policy){case"latest":case"exhaust":this._activeOperationId===t&&(this._activeOperationId=void 0);break;case"queue":{const e=this._queue.filter(e=>e.operationId!==t);this._queue.length=0,this._queue.push(...e),this._activeOperationId=this._queue.length>0?this._queue[0].operationId:void 0;break}case"overlap":this._activeOperationIds.delete(t)}}_abortController(t){const e=this._controllers.get(t);void 0===e||e.signal.aborted||e.abort()}_releaseController(t){this._controllers.delete(t)}}function a(t,e){const r=new Map,i=e=>{const r=t.get(e);return void 0===r?"unknown":r.probe()?"available":"missing"};let s=!0;for(const t of e.required){const e=i(t);r.set(t,e),"available"!==e&&(s=!1)}let n=!0;for(const t of e.optional??[]){const e=i(t);r.set(t,e),"available"!==e&&(n=!1)}const o=s?n?"ready":"degraded":"idle",a=[...e.required,...e.optional??[]],l=a.some(e=>!0===t.get(e)?.requiresSecureContext),c=a.some(e=>!0===t.get(e)?.requiresUserActivation),h=l?!0===globalThis.isSecureContext?"satisfied":"required":"not-applicable",u=c?"required":"not-applicable";return{availability:r,permission:e.permission??"not-applicable",readiness:o,activity:e.activity??"inactive",preconditions:{secureContext:h,userActivation:u},epoch:e.epoch??0,lastError:e.lastError}}function l(t,e){return e.every(e=>"available"===t.availability.get(e))}const c={CapabilityMissing:"capability-missing",InvalidArgument:"invalid-argument",Network:"network",HttpError:"http-error",Timeout:"timeout",Aborted:"aborted"},h=new Map([["web.fetch",{probe:()=>"function"==typeof globalThis.fetch,compatKey:"api.fetch"}],["web.abort-controller",{probe:()=>"function"==typeof globalThis.AbortController,compatKey:"api.AbortController"}]]);class u extends EventTarget{static wcBindable={protocol:"wc-bindable",version:1,properties:[{name:"value",event:"wcs-fetch:response",getter:t=>t.detail.value},{name:"loading",event:"wcs-fetch:loading-changed"},{name:"error",event:"wcs-fetch:error"},{name:"status",event:"wcs-fetch:response",getter:t=>t.detail.status},{name:"objectURL",event:"wcs-fetch:response",getter:t=>t.detail.objectURL},{name:"errorInfo",event:"wcs-fetch:error-info-changed"}],inputs:[{name:"url"},{name:"method"}],commands:[{name:"fetch",async:!0},{name:"abort"}]};_target;_value=null;_loading=!1;_error=null;_status=0;_objectURL=null;_promise=Promise.resolve(null);_lane=new o("fetch","latest",{withSignal:!0});_ready=Promise.resolve();_errorInfo=null;static REQUIRED_CAPABILITIES=["web.fetch"];static OPTIONAL_CAPABILITIES=["web.abort-controller"];constructor(t){super(),this._target=t??this}get ready(){return this._ready}observe(){return this._ready}dispose(){this._lane.disposeOwner(),null!==this._objectURL&&(this._revokeObjectURL(this._objectURL),this._objectURL=null)}get value(){return this._value}get loading(){return this._loading}get error(){return this._error}get status(){return this._status}get objectURL(){return this._objectURL}get promise(){return this._promise}get errorInfo(){return this._errorInfo}get supported(){return l(this.platformAssessment,u.REQUIRED_CAPABILITIES)}get platformAssessment(){return a(h,{required:u.REQUIRED_CAPABILITIES,optional:u.OPTIONAL_CAPABILITIES,activity:this._loading?"active":"inactive",lastError:this._errorInfo??void 0})}_setErrorInfo(t,e,r,i,s){this._commitErrorInfo({code:t,phase:e,recoverable:r,message:i,...void 0===s?{}:{capabilityId:s}})}_commitErrorInfo(t){this._errorInfo!==t&&(this._errorInfo=t,this._target.dispatchEvent(new CustomEvent("wcs-fetch:error-info-changed",{detail:t,bubbles:!0})))}_setLoading(t){this._loading=t,this._target.dispatchEvent(new CustomEvent("wcs-fetch:loading-changed",{detail:t,bubbles:!0}))}_setError(t){this._error!==t&&(this._error=t,this._target.dispatchEvent(new CustomEvent("wcs-fetch:error",{detail:t,bubbles:!0})))}_setResponse(t,e,r=null){null!==this._objectURL&&this._revokeObjectURL(this._objectURL),this._objectURL=r,this._value=t,this._status=e,this._target.dispatchEvent(new CustomEvent("wcs-fetch:response",{detail:{value:t,status:e,objectURL:r},bubbles:!0}))}_createObjectURL(t){return"undefined"!=typeof URL&&"function"==typeof URL.createObjectURL?URL.createObjectURL(t):null}_revokeObjectURL(t){"undefined"!=typeof URL&&"function"==typeof URL.revokeObjectURL&&URL.revokeObjectURL(t)}abort(){this._lane.abortActive()}_commitStep(t,e){this._lane.canCommit(t)&&e()}async fetch(t,e={}){if(!t)return this._setErrorInfo(c.InvalidArgument,"start",!1,"url attribute is required."),this._setError({message:"url attribute is required."}),null;const r=this.platformAssessment;if(!l(r,u.REQUIRED_CAPABILITIES)){const t=u.REQUIRED_CAPABILITIES.find(t=>"available"!==r.availability.get(t));return this._setErrorInfo(c.CapabilityMissing,"start",!1,`Required capability "${t}" is unavailable.`,t),this._setError({message:`Required capability "${t}" is unavailable.`}),null}const i=this._doFetch(t,e);return this._promise=i,i}async _doFetch(t,e){const r=this._lane.begin(),{ticket:i,attempt:s}=r,n=s.signal;this._commitStep(i,()=>this._setLoading(!0)),this._commitStep(i,()=>{this._commitErrorInfo(null),this._setError(null)});const{method:o="GET",body:a=null,contentType:l=null,forceText:h=!1,responseType:u="auto",timeout:d=0}=e;let _=null;d>0&&(_=setTimeout(()=>{if(!this._lane.claimTerminal(i,"timeout"))return;const t=`Request timed out after ${d}ms.`;this._commitStep(i,()=>{this._setErrorInfo(c.Timeout,"execute",!0,t),this._setError({name:"TimeoutError",message:t})}),this._commitStep(i,()=>this._setResponse(null,0)),this._commitStep(i,()=>this._setLoading(!1)),this._lane.abort(i),this._lane.finalize(i)},d));const m={...e.headers??{}};try{l&&!m["Content-Type"]&&(m["Content-Type"]=l);const e={method:o,headers:m,signal:n};"GET"!==o&&"HEAD"!==o&&null!==a&&(e.body=a);const r=await globalThis.fetch(t,e);let s=null;if("HEAD"===o);else if(r.ok)if(h)s=await r.text();else if("blob"===u)s=await r.blob();else if("arrayBuffer"===u)s=await r.arrayBuffer();else if("text"===u)s=await r.text();else if("json"===u)s=await r.json();else{const t=r.headers.get("Content-Type")||"";s=t.includes("application/json")?await r.json():await r.text()}else;if(!r.ok){const t=await r.text().catch(()=>""),e={status:r.status,statusText:r.statusText,body:t};return this._lane.claimTerminal(i,"error")?(this._commitStep(i,()=>{this._setErrorInfo(c.HttpError,"execute",!0,`HTTP ${r.status} ${r.statusText}`),this._setError(e)}),this._commitStep(i,()=>this._setResponse(null,r.status)),this._commitStep(i,()=>this._setLoading(!1)),null):null}if(!this._lane.claimTerminal(i,"success"))return null;const d=s instanceof Blob?this._createObjectURL(s):null;return this._commitStep(i,()=>this._setResponse(s,r.status,d)),this._commitStep(i,()=>this._setLoading(!1)),this._value}catch(t){return t&&"AbortError"===t.name?(this._lane.claimTerminal(i,"aborted")&&this._commitStep(i,()=>this._setLoading(!1)),null):this._lane.claimTerminal(i,"error")?(this._commitStep(i,()=>{const e=String(t?.message??"Network request failed.");this._setErrorInfo(c.Network,"execute",!0,e),this._setError(t??{message:e})}),this._commitStep(i,()=>this._setResponse(null,0)),this._commitStep(i,()=>this._setLoading(!1)),null):null}finally{null!==_&&clearTimeout(_),this._lane.finalize(i)}}}let d=!1;function _(t){const e=t.target;if(!(e instanceof Element))return;const r=e.closest(`[${s.triggerAttribute}]`);if(!r)return;const i=r.getAttribute(s.triggerAttribute);if(!i)return;const n=customElements.get(s.tagNames.fetch),o=document.getElementById(i);if(!(n&&o instanceof n))return;const a=o;a.url&&(t.preventDefault(),a.fetch())}class m extends HTMLElement{static hasConnectedCallbackPromise=!0;static wcBindable={...u.wcBindable,properties:[...u.wcBindable.properties,{name:"trigger",event:"wcs-fetch:trigger-changed"}],inputs:[{name:"url"},{name:"method"},{name:"target"},{name:"manual"},{name:"body"},{name:"responseType"},{name:"trigger"}]};static get observedAttributes(){return["url"]}_core;_body=null;_trigger=!1;_connectedCallbackPromise=Promise.resolve();_autoPending=!1;_connectResolve=null;_lastFetchedUrl=null;_internals=null;constructor(){super(),this._internals=this._initInternals(),this._wireStates({"wcs-fetch:loading-changed":t=>({loading:!0===t}),"wcs-fetch:error":t=>({error:null!=t})}),this._core=new u(this)}get debugStates(){return this._internals?[...this._internals.states]:[]}_initInternals(){try{if("function"!=typeof this.attachInternals)return null;const t=this.attachInternals();return t.states.add("wcs-probe"),t.states.delete("wcs-probe"),t}catch{return null}}_wireStates(t){if(null===this._internals)return;const e=this._internals.states;for(const[r,i]of Object.entries(t))this.addEventListener(r,t=>{const r=this.hasAttribute("debug-states");for(const[s,n]of Object.entries(i(t.detail))){try{n?e.add(s):e.delete(s)}catch{}r&&this.toggleAttribute(`data-wcs-state-${s}`,n)}})}get url(){return this.getAttribute("url")||""}set url(t){null==t?this.removeAttribute("url"):this.setAttribute("url",t)}get method(){return(this.getAttribute("method")||"GET").toUpperCase()}set method(t){null==t?this.removeAttribute("method"):this.setAttribute("method",t)}get target(){return this.getAttribute("target")}set target(t){null==t?this.removeAttribute("target"):this.setAttribute("target",t)}get responseType(){return this.getAttribute("response-type")||"auto"}set responseType(t){null==t?this.removeAttribute("response-type"):this.setAttribute("response-type",t)}get value(){return this._core.value}get loading(){return this._core.loading}get error(){return this._core.error}get status(){return this._core.status}get objectURL(){return this._core.objectURL}get errorInfo(){return this._core.errorInfo}get promise(){return this._core.promise}get connectedCallbackPromise(){return this._connectedCallbackPromise}get manual(){return this.hasAttribute("manual")}set manual(t){t?this.setAttribute("manual",""):this.removeAttribute("manual")}get body(){return this._body}set body(t){this._body=t??null}get trigger(){return this._trigger}set trigger(t){if(!!t){if(!this.url)return;this._trigger=!0,this.fetch().finally(()=>{this._trigger=!1,this.dispatchEvent(new CustomEvent("wcs-fetch:trigger-changed",{detail:!1,bubbles:!0}))})}}_collectHeaders(){const t={},e=this.querySelectorAll(s.tagNames.fetchHeader);for(const r of e){const e=r.headerName,i=r.headerValue;e&&(t[e]=i)}return t}_isNativeBodyInit(t){return t instanceof Blob||t instanceof FormData||t instanceof URLSearchParams||t instanceof ArrayBuffer||ArrayBuffer.isView(t)}_collectBody(t){if(null!==t)return"string"==typeof t||this._isNativeBodyInit(t)?{body:t,contentType:null}:{body:JSON.stringify(t),contentType:"application/json"};const e=this.querySelector(s.tagNames.fetchBody);return e?{body:e.bodyContent||null,contentType:e.contentType}:{body:null,contentType:null}}abort(){this._core.abort()}_scheduleAutoFetch(){this._autoPending||(this._autoPending=!0,queueMicrotask(()=>{this._autoPending=!1;const t=this._connectResolve;this._connectResolve=null;const e=this.url;this.isConnected&&!this.manual&&e&&e!==this._lastFetchedUrl?this.fetch().finally(()=>t?.()):t?.()}))}async fetch(){this._lastFetchedUrl=this.url;const t=this._collectHeaders(),e=this._body;this._body=null;const{body:r,contentType:i}=this._collectBody(e);r instanceof FormData&&Object.keys(t).some(t=>"content-type"===t.toLowerCase())&&console.warn("[@wcstack/fetch] A manual Content-Type header was set alongside a FormData body. This drops the multipart boundary the browser adds automatically; remove the Content-Type header (e.g. the <wcs-fetch-header>) to fix multipart uploads.");const s=await this._core.fetch(this.url,{method:this.method,headers:t,body:r,contentType:i,forceText:!!this.target,responseType:this.responseType});if(this.target&&null!==s){const t=document.getElementById(this.target);t&&(t.innerHTML=s)}return s}attributeChangedCallback(t,e,r){"url"===t&&this._scheduleAutoFetch()}connectedCallback(){this.style.display="none",s.autoTrigger&&(d||(d=!0,document.addEventListener("click",_))),!this.manual&&this.url&&(this._connectedCallbackPromise=new Promise(t=>{this._connectResolve=t})),this._scheduleAutoFetch()}disconnectedCallback(){this.abort(),this._lastFetchedUrl=null,this._connectResolve?.(),this._connectResolve=null}}class g extends HTMLElement{connectedCallback(){this.style.display="none"}get headerName(){return this.getAttribute("name")||""}get headerValue(){return this.getAttribute("value")||""}}class p extends HTMLElement{constructor(){super(),this.attachShadow({mode:"open"})}get contentType(){return this.getAttribute("type")||"application/json"}get bodyContent(){return this.textContent?.trim()||""}}class b extends HTMLElement{static get observedAttributes(){return["target","root","root-margin","threshold","disabled"]}_observer=null;_done=!1;get target(){return this.getAttribute("target")||""}set target(t){this.setAttribute("target",t)}get root(){return this.getAttribute("root")}set root(t){null===t?this.removeAttribute("root"):this.setAttribute("root",t)}get rootMargin(){return this.getAttribute("root-margin")||"0px"}set rootMargin(t){this.setAttribute("root-margin",t)}get threshold(){const t=Number(this.getAttribute("threshold")??"0");return Number.isFinite(t)?t:0}set threshold(t){this.setAttribute("threshold",String(t))}get disabled(){return this.hasAttribute("disabled")}set disabled(t){t?this.setAttribute("disabled",""):this.removeAttribute("disabled")}get once(){return this.hasAttribute("once")}set once(t){t?this.setAttribute("once",""):this.removeAttribute("once")}connectedCallback(){this._observe()}disconnectedCallback(){this._disconnectObserver()}attributeChangedCallback(){this.isConnected&&this._observe()}_observe(){this._disconnectObserver(),this._done||this.disabled||!this.target||"undefined"==typeof IntersectionObserver||(this._observer=new IntersectionObserver(t=>{t.some(t=>t.isIntersecting)&&this._triggerFetch()},{root:this._resolveRoot(),rootMargin:this.rootMargin,threshold:this.threshold}),this._observer.observe(this))}_disconnectObserver(){this._observer&&(this._observer.disconnect(),this._observer=null)}_resolveRoot(){return this.root&&document.getElementById(this.root)||null}_triggerFetch(){const t=document.getElementById(this.target);t instanceof m&&(t.loading||(t.trigger=!0,this.once&&(this._done=!0,this._disconnectObserver())))}}function f(e){var r;e&&("boolean"==typeof(r=e).autoTrigger&&(t.autoTrigger=r.autoTrigger),"string"==typeof r.triggerAttribute&&(t.triggerAttribute=r.triggerAttribute),r.tagNames&&Object.assign(t.tagNames,r.tagNames),i=null),customElements.get(s.tagNames.fetch)||customElements.define(s.tagNames.fetch,m),customElements.get(s.tagNames.fetchHeader)||customElements.define(s.tagNames.fetchHeader,g),customElements.get(s.tagNames.fetchBody)||customElements.define(s.tagNames.fetchBody,p),customElements.get(s.tagNames.infiniteScroll)||customElements.define(s.tagNames.infiniteScroll,b)}export{u as FetchCore,c as WCS_FETCH_ERROR_CODE,m as WcsFetch,b as WcsInfiniteScroll,f as bootstrapFetch,n as getConfig};
1
+ const t={autoTrigger:!0,triggerAttribute:"data-fetchtarget",tagNames:{fetch:"wcs-fetch",fetchHeader:"wcs-fetch-header",fetchBody:"wcs-fetch-body",infiniteScroll:"wcs-infinite-scroll"}};function e(t){if(null===t||"object"!=typeof t)return t;Object.freeze(t);for(const r of Object.keys(t))e(t[r]);return t}function r(t){if(null===t||"object"!=typeof t)return t;const e={};for(const i of Object.keys(t))e[i]=r(t[i]);return e}let i=null;const s=t;function n(){return i||(i=e(r(t))),i}class o{laneKey;policy;_ownerGeneration=0;_latestEpoch=0;_nextOperationId=1;_activeOperationId=void 0;_activeOperationIds=new Set;_queue=[];_inFlightCount=0;_terminal=new Map;_claimedOutcome=new Map;_controllers=new Map;_attempts=new Map;_withSignal;_trace;constructor(t,e,r={}){this.laneKey=t,this.policy=e,this._withSignal=r.withSignal??!1,this._trace=r.trace}get ownerGeneration(){return this._ownerGeneration}get inFlightCount(){return this._inFlightCount}get latestEpoch(){return this._latestEpoch}get activeOperationId(){return this._activeOperationId}begin(){let t;switch(this.policy){case"latest":t=++this._latestEpoch,void 0!==this._activeOperationId&&this._abortController(this._activeOperationId);break;case"exhaust":if(void 0!==this._activeOperationId)return null}const e=this._nextOperationId++,r={operationId:e,ownerGeneration:this._ownerGeneration,laneKey:this.laneKey,policy:this.policy,supersedeEpoch:t};switch(this.policy){case"latest":case"exhaust":this._activeOperationId=e;break;case"queue":this._queue.push(r),void 0===this._activeOperationId&&(this._activeOperationId=e);break;case"overlap":this._activeOperationIds.add(e)}this._inFlightCount+=1,this._attempts.set(e,1);const i=this._makeAttempt(e,1);return void 0!==this._trace&&this._trace({type:"io:operation-started",operationId:e,laneKey:this.laneKey,policy:this.policy}),{ticket:r,attempt:i}}retry(t){if(t.ownerGeneration!==this._ownerGeneration)return null;if(this._terminal.has(t.operationId))return null;const e=this._attempts.get(t.operationId);if(void 0===e)return null;const r=e+1;this._attempts.set(t.operationId,r),this._releaseController(t.operationId);const i=this._makeAttempt(t.operationId,r);return void 0!==this._trace&&this._trace({type:"io:operation-retried",operationId:t.operationId,laneKey:this.laneKey,attempt:r}),i}canCommit(t){if(t.ownerGeneration!==this._ownerGeneration)return!1;const e=this._terminal.get(t.operationId);return(void 0===e||"committing"===e)&&this._isEligible(t)}claimTerminal(t,e){return t.ownerGeneration===this._ownerGeneration&&(!this._terminal.has(t.operationId)&&(!!this._isEligible(t)&&(this._terminal.set(t.operationId,"committing"),this._claimedOutcome.set(t.operationId,e),!0)))}claimedOutcome(t){return this._claimedOutcome.get(t.operationId)}finalize(t){const e=t.operationId,r=this._terminal.get(e);if(void 0!==r&&"committing"!==r)return;let i;i="committing"===r?this._claimedOutcome.get(e)??"stale":"stale",this._terminal.set(e,i),this._claimedOutcome.delete(e),this._releaseController(e),this._attempts.delete(e),this._inFlightCount>0&&(this._inFlightCount-=1),this._advanceBookkeeping(e),void 0!==this._trace&&("stale"===i?this._trace({type:"io:stale-dropped",operationId:e,laneKey:this.laneKey}):this._trace({type:"io:operation-settled",operationId:e,laneKey:this.laneKey,outcome:i}))}signalOf(t){return this._controllers.get(t.operationId)?.signal}abort(t){this._abortController(t.operationId)}abortActive(){void 0!==this._activeOperationId&&this._abortController(this._activeOperationId);for(const t of this._activeOperationIds)this._abortController(t)}disposeOwner(){this._ownerGeneration+=1;for(const t of Array.from(this._controllers.keys()))this._abortController(t),this._releaseController(t);for(const t of Array.from(this._attempts.keys()))this._terminal.has(t)||this._terminal.set(t,"stale"),this._claimedOutcome.delete(t),this._attempts.delete(t),void 0!==this._trace&&this._trace({type:"io:stale-dropped",operationId:t,laneKey:this.laneKey});this._activeOperationId=void 0,this._activeOperationIds.clear(),this._queue.length=0,this._inFlightCount=0}_makeAttempt(t,e){let r;if(this._withSignal&&"function"==typeof AbortController){const e=new AbortController;this._controllers.set(t,e),r=e.signal}return{operationId:t,attempt:e,signal:r}}_isEligible(t){switch(this.policy){case"latest":return t.supersedeEpoch===this._latestEpoch;case"queue":case"exhaust":return this._activeOperationId===t.operationId;case"overlap":return this._activeOperationIds.has(t.operationId)}}_advanceBookkeeping(t){switch(this.policy){case"latest":case"exhaust":this._activeOperationId===t&&(this._activeOperationId=void 0);break;case"queue":{const e=this._queue.filter(e=>e.operationId!==t);this._queue.length=0,this._queue.push(...e),this._activeOperationId=this._queue.length>0?this._queue[0].operationId:void 0;break}case"overlap":this._activeOperationIds.delete(t)}}_abortController(t){const e=this._controllers.get(t);void 0===e||e.signal.aborted||e.abort()}_releaseController(t){this._controllers.delete(t)}}function a(t,e){const r=new Map,i=e=>{const r=t.get(e);return void 0===r?"unknown":r.probe()?"available":"missing"};let s=!0;for(const t of e.required){const e=i(t);r.set(t,e),"available"!==e&&(s=!1)}let n=!0;for(const t of e.optional??[]){const e=i(t);r.set(t,e),"available"!==e&&(n=!1)}const o=s?n?"ready":"degraded":"idle",a=[...e.required,...e.optional??[]],l=a.some(e=>!0===t.get(e)?.requiresSecureContext),c=a.some(e=>!0===t.get(e)?.requiresUserActivation),h=l?!0===globalThis.isSecureContext?"satisfied":"required":"not-applicable",u=c?"required":"not-applicable";return{availability:r,permission:e.permission??"not-applicable",readiness:o,activity:e.activity??"inactive",preconditions:{secureContext:h,userActivation:u},epoch:e.epoch??0,lastError:e.lastError}}function l(t,e){return e.every(e=>"available"===t.availability.get(e))}const c={CapabilityMissing:"capability-missing",InvalidArgument:"invalid-argument",Network:"network",HttpError:"http-error",Timeout:"timeout",Aborted:"aborted"},h=new Map([["web.fetch",{probe:()=>"function"==typeof globalThis.fetch,compatKey:"api.fetch"}],["web.abort-controller",{probe:()=>"function"==typeof globalThis.AbortController,compatKey:"api.AbortController"}]]);class u extends EventTarget{static wcBindable={protocol:"wc-bindable",version:1,properties:[{name:"value",event:"wcs-fetch:response",semantics:"state",getter:t=>t.detail.value},{name:"loading",event:"wcs-fetch:loading-changed",semantics:"state"},{name:"error",event:"wcs-fetch:error",semantics:"state"},{name:"status",event:"wcs-fetch:response",semantics:"state",getter:t=>t.detail.status},{name:"objectURL",event:"wcs-fetch:response",semantics:"state",getter:t=>t.detail.objectURL},{name:"errorInfo",event:"wcs-fetch:error-info-changed",semantics:"state"}],inputs:[{name:"url"},{name:"method"}],commands:[{name:"fetch",async:!0},{name:"abort"}]};_target;_value=null;_loading=!1;_error=null;_status=0;_objectURL=null;_promise=Promise.resolve(null);_lane=new o("fetch","latest",{withSignal:!0});_ready=Promise.resolve();_errorInfo=null;static REQUIRED_CAPABILITIES=["web.fetch"];static OPTIONAL_CAPABILITIES=["web.abort-controller"];constructor(t){super(),this._target=t??this}get ready(){return this._ready}observe(){return this._ready}dispose(){this._lane.disposeOwner(),null!==this._objectURL&&(this._revokeObjectURL(this._objectURL),this._objectURL=null)}get value(){return this._value}get loading(){return this._loading}get error(){return this._error}get status(){return this._status}get objectURL(){return this._objectURL}get promise(){return this._promise}get errorInfo(){return this._errorInfo}get supported(){return l(this.platformAssessment,u.REQUIRED_CAPABILITIES)}get platformAssessment(){return a(h,{required:u.REQUIRED_CAPABILITIES,optional:u.OPTIONAL_CAPABILITIES,activity:this._loading?"active":"inactive",lastError:this._errorInfo??void 0})}_setErrorInfo(t,e,r,i,s){this._commitErrorInfo({code:t,phase:e,recoverable:r,message:i,...void 0===s?{}:{capabilityId:s}})}_commitErrorInfo(t){this._errorInfo!==t&&(this._errorInfo=t,this._target.dispatchEvent(new CustomEvent("wcs-fetch:error-info-changed",{detail:t,bubbles:!0})))}_setLoading(t){this._loading=t,this._target.dispatchEvent(new CustomEvent("wcs-fetch:loading-changed",{detail:t,bubbles:!0}))}_setError(t){this._error!==t&&(this._error=t,this._target.dispatchEvent(new CustomEvent("wcs-fetch:error",{detail:t,bubbles:!0})))}_setResponse(t,e,r=null){null!==this._objectURL&&this._revokeObjectURL(this._objectURL),this._objectURL=r,this._value=t,this._status=e,this._target.dispatchEvent(new CustomEvent("wcs-fetch:response",{detail:{value:t,status:e,objectURL:r},bubbles:!0}))}_createObjectURL(t){return"undefined"!=typeof URL&&"function"==typeof URL.createObjectURL?URL.createObjectURL(t):null}_revokeObjectURL(t){"undefined"!=typeof URL&&"function"==typeof URL.revokeObjectURL&&URL.revokeObjectURL(t)}abort(){this._lane.abortActive()}_commitStep(t,e){this._lane.canCommit(t)&&e()}async fetch(t,e={}){if(!t)return this._setErrorInfo(c.InvalidArgument,"start",!1,"url attribute is required."),this._setError({message:"url attribute is required."}),null;const r=this.platformAssessment;if(!l(r,u.REQUIRED_CAPABILITIES)){const t=u.REQUIRED_CAPABILITIES.find(t=>"available"!==r.availability.get(t));return this._setErrorInfo(c.CapabilityMissing,"start",!1,`Required capability "${t}" is unavailable.`,t),this._setError({message:`Required capability "${t}" is unavailable.`}),null}const i=this._doFetch(t,e);return this._promise=i,i}async _doFetch(t,e){const r=this._lane.begin(),{ticket:i,attempt:s}=r,n=s.signal;this._commitStep(i,()=>this._setLoading(!0)),this._commitStep(i,()=>{this._commitErrorInfo(null),this._setError(null)});const{method:o="GET",body:a=null,contentType:l=null,forceText:h=!1,responseType:u="auto",timeout:d=0}=e;let _=null;d>0&&(_=setTimeout(()=>{if(!this._lane.claimTerminal(i,"timeout"))return;const t=`Request timed out after ${d}ms.`;this._commitStep(i,()=>{this._setErrorInfo(c.Timeout,"execute",!0,t),this._setError({name:"TimeoutError",message:t})}),this._commitStep(i,()=>this._setResponse(null,0)),this._commitStep(i,()=>this._setLoading(!1)),this._lane.abort(i),this._lane.finalize(i)},d));const m={...e.headers??{}};try{l&&!m["Content-Type"]&&(m["Content-Type"]=l);const e={method:o,headers:m,signal:n};"GET"!==o&&"HEAD"!==o&&null!==a&&(e.body=a);const r=await globalThis.fetch(t,e);let s=null;if("HEAD"===o);else if(r.ok)if(h)s=await r.text();else if("blob"===u)s=await r.blob();else if("arrayBuffer"===u)s=await r.arrayBuffer();else if("text"===u)s=await r.text();else if("json"===u)s=await r.json();else{const t=r.headers.get("Content-Type")||"";s=t.includes("application/json")?await r.json():await r.text()}else;if(!r.ok){const t=await r.text().catch(()=>""),e={status:r.status,statusText:r.statusText,body:t};return this._lane.claimTerminal(i,"error")?(this._commitStep(i,()=>{this._setErrorInfo(c.HttpError,"execute",!0,`HTTP ${r.status} ${r.statusText}`),this._setError(e)}),this._commitStep(i,()=>this._setResponse(null,r.status)),this._commitStep(i,()=>this._setLoading(!1)),null):null}if(!this._lane.claimTerminal(i,"success"))return null;const d=s instanceof Blob?this._createObjectURL(s):null;return this._commitStep(i,()=>this._setResponse(s,r.status,d)),this._commitStep(i,()=>this._setLoading(!1)),this._value}catch(t){return t&&"AbortError"===t.name?(this._lane.claimTerminal(i,"aborted")&&this._commitStep(i,()=>this._setLoading(!1)),null):this._lane.claimTerminal(i,"error")?(this._commitStep(i,()=>{const e=String(t?.message??"Network request failed.");this._setErrorInfo(c.Network,"execute",!0,e),this._setError(t??{message:e})}),this._commitStep(i,()=>this._setResponse(null,0)),this._commitStep(i,()=>this._setLoading(!1)),null):null}finally{null!==_&&clearTimeout(_),this._lane.finalize(i)}}}let d=!1;function _(t){const e=t.target;if(!(e instanceof Element))return;const r=e.closest(`[${s.triggerAttribute}]`);if(!r)return;const i=r.getAttribute(s.triggerAttribute);if(!i)return;const n=customElements.get(s.tagNames.fetch),o=document.getElementById(i);if(!(n&&o instanceof n))return;const a=o;a.url&&(t.preventDefault(),a.fetch())}function m(t,e){let r=Object.getPrototypeOf(t);for(;null!==r;){const t=Object.getOwnPropertyDescriptor(r,e);if(void 0!==t)return"function"==typeof t.get||"function"==typeof t.set;r=Object.getPrototypeOf(r)}return!1}class g extends HTMLElement{static hasConnectedCallbackPromise=!0;static wcBindable={...u.wcBindable,properties:[...u.wcBindable.properties,{name:"trigger",event:"wcs-fetch:trigger-changed",semantics:"state"}],inputs:[{name:"url"},{name:"method"},{name:"target"},{name:"manual"},{name:"body"},{name:"responseType"},{name:"trigger"}]};static get observedAttributes(){return["url"]}_core;_body=null;_trigger=!1;_connectedCallbackPromise=Promise.resolve();_autoPending=!1;_connectResolve=null;_lastFetchedUrl=null;_internals=null;constructor(){super(),this._internals=this._initInternals(),this._wireStates({"wcs-fetch:loading-changed":t=>({loading:!0===t}),"wcs-fetch:error":t=>({error:null!=t})}),this._core=new u(this)}get debugStates(){return this._internals?[...this._internals.states]:[]}_initInternals(){try{if("function"!=typeof this.attachInternals)return null;const t=this.attachInternals();return t.states.add("wcs-probe"),t.states.delete("wcs-probe"),t}catch{return null}}_wireStates(t){if(null===this._internals)return;const e=this._internals.states;for(const[r,i]of Object.entries(t))this.addEventListener(r,t=>{const r=this.hasAttribute("debug-states");for(const[s,n]of Object.entries(i(t.detail))){try{n?e.add(s):e.delete(s)}catch{}r&&this.toggleAttribute(`data-wcs-state-${s}`,n)}})}get url(){return this.getAttribute("url")||""}set url(t){null==t?this.removeAttribute("url"):this.setAttribute("url",t)}get method(){return(this.getAttribute("method")||"GET").toUpperCase()}set method(t){null==t?this.removeAttribute("method"):this.setAttribute("method",t)}get target(){return this.getAttribute("target")}set target(t){null==t?this.removeAttribute("target"):this.setAttribute("target",t)}get responseType(){return this.getAttribute("response-type")||"auto"}set responseType(t){null==t?this.removeAttribute("response-type"):this.setAttribute("response-type",t)}get value(){return this._core.value}get loading(){return this._core.loading}get error(){return this._core.error}get status(){return this._core.status}get objectURL(){return this._core.objectURL}get errorInfo(){return this._core.errorInfo}get promise(){return this._core.promise}get connectedCallbackPromise(){return this._connectedCallbackPromise}get manual(){return this.hasAttribute("manual")}set manual(t){t?this.setAttribute("manual",""):this.removeAttribute("manual")}get body(){return this._body}set body(t){this._body=t??null}get trigger(){return this._trigger}set trigger(t){if(!!t){if(!this.url)return;this._trigger=!0,this.fetch().finally(()=>{this._trigger=!1,this.dispatchEvent(new CustomEvent("wcs-fetch:trigger-changed",{detail:!1,bubbles:!0}))})}}_collectHeaders(){const t={},e=this.querySelectorAll(s.tagNames.fetchHeader);for(const r of e){const e=r.headerName,i=r.headerValue;e&&(t[e]=i)}return t}_isNativeBodyInit(t){return t instanceof Blob||t instanceof FormData||t instanceof URLSearchParams||t instanceof ArrayBuffer||ArrayBuffer.isView(t)}_collectBody(t){if(null!==t)return"string"==typeof t||this._isNativeBodyInit(t)?{body:t,contentType:null}:{body:JSON.stringify(t),contentType:"application/json"};const e=this.querySelector(s.tagNames.fetchBody);return e?{body:e.bodyContent||null,contentType:e.contentType}:{body:null,contentType:null}}abort(){this._core.abort()}_scheduleAutoFetch(){this._autoPending||(this._autoPending=!0,queueMicrotask(()=>{this._autoPending=!1;const t=this._connectResolve;this._connectResolve=null;const e=this.url;this.isConnected&&!this.manual&&e&&e!==this._lastFetchedUrl?this.fetch().finally(()=>t?.()):t?.()}))}async fetch(){this._lastFetchedUrl=this.url;const t=this._collectHeaders(),e=this._body;this._body=null;const{body:r,contentType:i}=this._collectBody(e);r instanceof FormData&&Object.keys(t).some(t=>"content-type"===t.toLowerCase())&&console.warn("[@wcstack/fetch] A manual Content-Type header was set alongside a FormData body. This drops the multipart boundary the browser adds automatically; remove the Content-Type header (e.g. the <wcs-fetch-header>) to fix multipart uploads.");const s=await this._core.fetch(this.url,{method:this.method,headers:t,body:r,contentType:i,forceText:!!this.target,responseType:this.responseType});if(this.target&&null!==s){const t=document.getElementById(this.target);t&&(t.innerHTML=s)}return s}attributeChangedCallback(t,e,r){"url"===t&&this._scheduleAutoFetch()}connectedCallback(){!function(t){const e=t.constructor?.wcBindable,r=e?.inputs;if(void 0!==r)for(const e of r){const r=e.name;if(!Object.prototype.hasOwnProperty.call(t,r))continue;if(!m(t,r))continue;const i=t,s=i[r];delete i[r],i[r]=s}}(this),this.style.display="none",s.autoTrigger&&(d||(d=!0,document.addEventListener("click",_))),!this.manual&&this.url&&(this._connectedCallbackPromise=new Promise(t=>{this._connectResolve=t})),this._scheduleAutoFetch()}disconnectedCallback(){this.abort(),this._lastFetchedUrl=null,this._connectResolve?.(),this._connectResolve=null}}class p extends HTMLElement{connectedCallback(){this.style.display="none"}get headerName(){return this.getAttribute("name")||""}get headerValue(){return this.getAttribute("value")||""}}class b extends HTMLElement{constructor(){super(),this.attachShadow({mode:"open"})}get contentType(){return this.getAttribute("type")||"application/json"}get bodyContent(){return this.textContent?.trim()||""}}class f extends HTMLElement{static get observedAttributes(){return["target","root","root-margin","threshold","disabled"]}_observer=null;_done=!1;get target(){return this.getAttribute("target")||""}set target(t){this.setAttribute("target",t)}get root(){return this.getAttribute("root")}set root(t){null===t?this.removeAttribute("root"):this.setAttribute("root",t)}get rootMargin(){return this.getAttribute("root-margin")||"0px"}set rootMargin(t){this.setAttribute("root-margin",t)}get threshold(){const t=Number(this.getAttribute("threshold")??"0");return Number.isFinite(t)?t:0}set threshold(t){this.setAttribute("threshold",String(t))}get disabled(){return this.hasAttribute("disabled")}set disabled(t){t?this.setAttribute("disabled",""):this.removeAttribute("disabled")}get once(){return this.hasAttribute("once")}set once(t){t?this.setAttribute("once",""):this.removeAttribute("once")}connectedCallback(){this._observe()}disconnectedCallback(){this._disconnectObserver()}attributeChangedCallback(){this.isConnected&&this._observe()}_observe(){this._disconnectObserver(),this._done||this.disabled||!this.target||"undefined"==typeof IntersectionObserver||(this._observer=new IntersectionObserver(t=>{t.some(t=>t.isIntersecting)&&this._triggerFetch()},{root:this._resolveRoot(),rootMargin:this.rootMargin,threshold:this.threshold}),this._observer.observe(this))}_disconnectObserver(){this._observer&&(this._observer.disconnect(),this._observer=null)}_resolveRoot(){return this.root&&document.getElementById(this.root)||null}_triggerFetch(){const t=document.getElementById(this.target);t instanceof g&&(t.loading||(t.trigger=!0,this.once&&(this._done=!0,this._disconnectObserver())))}}function y(e){var r;e&&("boolean"==typeof(r=e).autoTrigger&&(t.autoTrigger=r.autoTrigger),"string"==typeof r.triggerAttribute&&(t.triggerAttribute=r.triggerAttribute),r.tagNames&&Object.assign(t.tagNames,r.tagNames),i=null),customElements.get(s.tagNames.fetch)||customElements.define(s.tagNames.fetch,g),customElements.get(s.tagNames.fetchHeader)||customElements.define(s.tagNames.fetchHeader,p),customElements.get(s.tagNames.fetchBody)||customElements.define(s.tagNames.fetchBody,b),customElements.get(s.tagNames.infiniteScroll)||customElements.define(s.tagNames.infiniteScroll,f)}export{u as FetchCore,c as WCS_FETCH_ERROR_CODE,g as WcsFetch,f as WcsInfiniteScroll,y as bootstrapFetch,n as getConfig};
2
2
  //# sourceMappingURL=index.esm.min.js.map