@wcstack/fetch 4.0.4 → 4.1.1

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.
package/README.ja.md CHANGED
@@ -50,8 +50,8 @@ npm install @wcstack/fetch
50
50
  既にリクエストが進行中の場合、前のリクエストは abort されます。
51
51
 
52
52
  ```html
53
- <script type="module" src="https://esm.run/@wcstack/state/auto"></script>
54
53
  <script type="module" src="https://esm.run/@wcstack/fetch/auto"></script>
54
+ <script type="module" src="https://esm.run/@wcstack/state/auto"></script>
55
55
 
56
56
  <wcs-state>
57
57
  <script type="module">
@@ -219,6 +219,20 @@ npm install @wcstack/fetch
219
219
 
220
220
  `body` は**使い捨て**の入力です。`<wcs-fetch>` は送信すると `body` を `null` に戻します([設計メモ](#設計メモ))。だから本文は要求を始めるハンドラで作り、毎回新しいオブジェクトを代入します。フォームのオブジェクトそのもの(`body: newUser`)を束ねると、送られるのは 1 回だけです。入力は束ねたパスの*下*の `newUser.name` に書くので束縛は当て直されず、2 回目の送信は本文なしになります。エラーは出ません。`wcs-validate` はこの形を `wcs/input-nested-write` で報告します。
221
221
 
222
+ **要素 1 つは、一度に要求 1 本。** 同じ `<wcs-fetch>` で新しい要求を始めると実行中の要求は中断され、`true` のままの `trigger` に 2 回目の `true` を書いても同じ値として捨てられます。だから重なりうる要求には、それぞれ要素を用意します — 変更の種類(作成・更新・削除)ごとに 1 つ。全部の変更で 1 つを共有すると、素早い 2 回の変更の片方が黙って失われます。
223
+
224
+ **サーバーのフィールドのエラー**(`{ errors: { name: "…" } }` 付きの `422`)は `error` に届きます。HTTP のエラーでは `error` は `{ status, statusText, body }` で、`body` は応答の本文のテキストです。getter で読みます:
225
+
226
+ ```js
227
+ get fieldErrors() {
228
+ const e = this.submitError;
229
+ if (!e?.body) return {};
230
+ try { return JSON.parse(e.body).errors ?? {}; } catch { return {}; }
231
+ },
232
+ ```
233
+
234
+ フィールドの隣に `textContent: fieldErrors.name` を束ねます。次の要求が成功すると `error` は `null` に戻ります。
235
+
222
236
  ### 5. `<wcs-infinite-scroll>` による無限スクロール
223
237
 
224
238
  `<wcs-infinite-scroll>` は、sentinel 要素が表示領域に入ったときに既存の `<wcs-fetch>` を実行します。
@@ -557,12 +571,23 @@ wcstack アプリケーションでは、**`trigger` によるステート駆動
557
571
 
558
572
  ### `<wcs-fetch-header>`
559
573
 
560
- リクエストヘッダを定義。`<wcs-fetch>` の子要素として配置。
574
+ リクエストヘッダを定義。`<wcs-fetch>` の子要素として配置。要求を始めるときに読まれる。
561
575
 
562
- | 属性 | 型 | 説明 |
576
+ | 属性 / プロパティ | 型 | 説明 |
563
577
  |------|------|------|
564
578
  | `name` | `string` | ヘッダ名 |
565
- | `value` | `string` | ヘッダ値 |
579
+ | `value` | `string` | ヘッダ値。`value` 属性が無ければヘッダは送らない(空の `value=""` は送る) |
580
+
581
+ `name` と `value` はプロパティでもあり、属性へ反映する(`null` は属性を外し、`undefined` はマークアップの値に戻す)。だからヘッダを state から渡せる:
582
+
583
+ ```html
584
+ <wcs-fetch url="/api/me" data-wcs="...: me">
585
+ <wcs-fetch-header name="Authorization" data-wcs="value: authHeader"></wcs-fetch-header>
586
+ </wcs-fetch>
587
+ <!-- get authHeader() { return this.token ? `Bearer ${this.token}` : null; } -->
588
+ ```
589
+
590
+ `authHeader` が `null` の間、要求は `Authorization` ヘッダ無しで出る。**state の値(トークンや id)が要る要求は、`url` も state から渡す**(`data-wcs="url: meUrl"` と、トークンが揃うまで `null` を返す getter)。I/O のパッケージは `@wcstack/state` より先に読み込まれるので、`url` をリテラルで書いた `<wcs-fetch>` は、ページの読み込みで state がヘッダを入れる前に要求を出す — ルートの中身の中でも同じ。
566
591
 
567
592
  ### `<wcs-fetch-body>`
568
593
 
package/README.md CHANGED
@@ -50,8 +50,8 @@ When `url` changes, `<wcs-fetch>` automatically runs a new request.
50
50
  If another request is already in flight, it aborts the previous one.
51
51
 
52
52
  ```html
53
- <script type="module" src="https://esm.run/@wcstack/state/auto"></script>
54
53
  <script type="module" src="https://esm.run/@wcstack/fetch/auto"></script>
54
+ <script type="module" src="https://esm.run/@wcstack/state/auto"></script>
55
55
 
56
56
  <wcs-state>
57
57
  <script type="module">
@@ -219,6 +219,20 @@ and no event fires. Set the `url` first, then write `true` again to execute.
219
219
 
220
220
  `body` is a **one-shot** input: `<wcs-fetch>` sends it and resets it to `null` (see [Design Notes](#design-notes)). So build the body in the handler that starts the request, and assign a new object every time. Binding the form object itself (`body: newUser`) sends it once: typing writes `newUser.name`, a path *below* the bound one, which never re-applies the binding, so the second submit goes without a body — no error. `wcs-validate` reports that form as `wcs/input-nested-write`.
221
221
 
222
+ **One element is one request at a time.** A new request on the same `<wcs-fetch>` aborts the one in flight, and a `trigger` that is still `true` drops a second `true` (the same value). So give each request that can overlap its own element — one per kind of change (create / update / delete), not one shared by every mutation — or two quick changes lose one of them silently.
223
+
224
+ **Field errors from the server** (a `422` with `{ errors: { name: "…" } }`) arrive in `error`: on an HTTP error `error` is `{ status, statusText, body }`, with the response body as text. Read them with a getter:
225
+
226
+ ```js
227
+ get fieldErrors() {
228
+ const e = this.submitError;
229
+ if (!e?.body) return {};
230
+ try { return JSON.parse(e.body).errors ?? {}; } catch { return {}; }
231
+ },
232
+ ```
233
+
234
+ and bind `textContent: fieldErrors.name` next to the field. `error` goes back to `null` when the next request succeeds.
235
+
222
236
  ### 5. Infinite scroll with `<wcs-infinite-scroll>`
223
237
 
224
238
  `<wcs-infinite-scroll>` runs an existing `<wcs-fetch>` when its sentinel element enters the viewport.
@@ -565,12 +579,23 @@ In wcstack applications, **state-driven triggering via `trigger`** is usually th
565
579
 
566
580
  ### `<wcs-fetch-header>`
567
581
 
568
- Defines a request header. Place it as a child of `<wcs-fetch>`.
582
+ Defines a request header. Place it as a child of `<wcs-fetch>`. It is read when a request starts.
569
583
 
570
- | Attribute | Type | Description |
584
+ | Attribute / property | Type | Description |
571
585
  |-----------|------|-------------|
572
586
  | `name` | `string` | Header name |
573
- | `value` | `string` | Header value |
587
+ | `value` | `string` | Header value. Without a `value` attribute the header is not sent (an empty `value=""` is) |
588
+
589
+ `name` and `value` are also properties, reflected to the attributes (`null` removes the attribute, `undefined` restores the one in the markup), so a header can come from state:
590
+
591
+ ```html
592
+ <wcs-fetch url="/api/me" data-wcs="...: me">
593
+ <wcs-fetch-header name="Authorization" data-wcs="value: authHeader"></wcs-fetch-header>
594
+ </wcs-fetch>
595
+ <!-- get authHeader() { return this.token ? `Bearer ${this.token}` : null; } -->
596
+ ```
597
+
598
+ While `authHeader` is `null` the request goes out with no `Authorization` header at all. **A request that needs state — a token, an id — should also get its `url` from state** (`data-wcs="url: meUrl"` with a getter that is `null` until the token is there): the I/O packages load before `@wcstack/state`, so a `<wcs-fetch>` with a literal `url` fetches on a page load before state has set the header — inside route content too.
574
599
 
575
600
  ### `<wcs-fetch-body>`
576
601
 
package/dist/auto.min.js CHANGED
@@ -1,2 +1,2 @@
1
- const t={triggerAttribute:"data-fetchtarget",tagNames:{fetch:"wcs-fetch",fetchHeader:"wcs-fetch-header",fetchBody:"wcs-fetch-body",infiniteScroll:"wcs-infinite-scroll"}};class e{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,i={}){this.laneKey=t,this.policy=e,this._withSignal=i.withSignal??!1,this._trace=i.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++,i={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(i),void 0===this._activeOperationId&&(this._activeOperationId=e);break;case"overlap":this._activeOperationIds.add(e)}this._inFlightCount+=1,this._attempts.set(e,1);const s=this._makeAttempt(e,1);return void 0!==this._trace&&this._trace({type:"io:operation-started",operationId:e,laneKey:this.laneKey,policy:this.policy}),{ticket:i,attempt:s}}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 i=e+1;this._attempts.set(t.operationId,i),this._releaseController(t.operationId);const s=this._makeAttempt(t.operationId,i);return void 0!==this._trace&&this._trace({type:"io:operation-retried",operationId:t.operationId,laneKey:this.laneKey,attempt:i}),s}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,i=this._terminal.get(e);if(void 0!==i&&"committing"!==i)return;let s;s="committing"===i?this._claimedOutcome.get(e)??"stale":"stale",this._terminal.set(e,s),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"===s?this._trace({type:"io:stale-dropped",operationId:e,laneKey:this.laneKey}):this._trace({type:"io:operation-settled",operationId:e,laneKey:this.laneKey,outcome:s}))}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 i;if(this._withSignal&&"function"==typeof AbortController){const e=new AbortController;this._controllers.set(t,e),i=e.signal}return{operationId:t,attempt:e,signal:i}}_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 i(t,e){const i=new Map,s=e=>{const i=t.get(e);return void 0===i?"unknown":i.probe()?"available":"missing"};let r=!0;for(const t of e.required){const e=s(t);i.set(t,e),"available"!==e&&(r=!1)}let n=!0;for(const t of e.optional??[]){const e=s(t);i.set(t,e),"available"!==e&&(n=!1)}const o=r?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:i,permission:e.permission??"not-applicable",readiness:o,activity:e.activity??"inactive",preconditions:{secureContext:h,userActivation:u},epoch:e.epoch??0,lastError:e.lastError}}function s(t,e){return e.every(e=>"available"===t.availability.get(e))}const r="capability-missing",n="invalid-argument",o="network",a="http-error",l="timeout",c=new Map([["web.fetch",{probe:()=>"function"==typeof globalThis.fetch,compatKey:"api.fetch"}],["web.abort-controller",{probe:()=>"function"==typeof globalThis.AbortController,compatKey:"api.AbortController"}]]);class h 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 e("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 s(this.platformAssessment,h.REQUIRED_CAPABILITIES)}get platformAssessment(){return i(c,{required:h.REQUIRED_CAPABILITIES,optional:h.OPTIONAL_CAPABILITIES,activity:this._loading?"active":"inactive",lastError:this._errorInfo??void 0})}_setErrorInfo(t,e,i,s,r){this._commitErrorInfo({code:t,phase:e,recoverable:i,message:s,...void 0===r?{}:{capabilityId:r}})}_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,i=null){null!==this._objectURL&&this._revokeObjectURL(this._objectURL),this._objectURL=i,this._value=t,this._status=e,this._target.dispatchEvent(new CustomEvent("wcs-fetch:response",{detail:{value:t,status:e,objectURL:i},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(n,"start",!1,"url attribute is required."),this._setError({message:"url attribute is required."}),null;const i=this.platformAssessment;if(!s(i,h.REQUIRED_CAPABILITIES)){const t=h.REQUIRED_CAPABILITIES.find(t=>"available"!==i.availability.get(t));return this._setErrorInfo(r,"start",!1,`Required capability "${t}" is unavailable.`,t),this._setError({message:`Required capability "${t}" is unavailable.`}),null}const o=this._doFetch(t,e);return this._promise=o,o}async _doFetch(t,e){const i=this._lane.begin(),{ticket:s,attempt:r}=i,n=r.signal;this._commitStep(s,()=>this._setLoading(!0)),this._commitStep(s,()=>{this._commitErrorInfo(null),this._setError(null)});const{method:c="GET",body:h=null,contentType:u=null,forceText:d=!1,responseType:_="auto",timeout:p=0}=e;let g=null;p>0&&(g=setTimeout(()=>{if(!this._lane.claimTerminal(s,"timeout"))return;const t=`Request timed out after ${p}ms.`;this._commitStep(s,()=>{this._setErrorInfo(l,"execute",!0,t),this._setError({name:"TimeoutError",message:t})}),this._commitStep(s,()=>this._setResponse(null,0)),this._commitStep(s,()=>this._setLoading(!1)),this._lane.abort(s),this._lane.finalize(s)},p));const m={...e.headers??{}};try{u&&!m["Content-Type"]&&(m["Content-Type"]=u);const e={method:c,headers:m,signal:n};"GET"!==c&&"HEAD"!==c&&null!==h&&(e.body=h);const i=await globalThis.fetch(t,e);let r=null;if("HEAD"===c);else if(i.ok)if(d)r=await i.text();else if("blob"===_)r=await i.blob();else if("arrayBuffer"===_)r=await i.arrayBuffer();else if("text"===_)r=await i.text();else if("json"===_)r=await i.json();else{const t=i.headers.get("Content-Type")||"";r=t.includes("application/json")?await i.json():await i.text()}else;if(!i.ok){const t=await i.text().catch(()=>""),e={status:i.status,statusText:i.statusText,body:t};return this._lane.claimTerminal(s,"error")?(this._commitStep(s,()=>{this._setErrorInfo(a,"execute",!0,`HTTP ${i.status} ${i.statusText}`),this._setError(e)}),this._commitStep(s,()=>this._setResponse(null,i.status)),this._commitStep(s,()=>this._setLoading(!1)),null):null}if(!this._lane.claimTerminal(s,"success"))return null;const o=r instanceof Blob?this._createObjectURL(r):null;return this._commitStep(s,()=>this._setResponse(r,i.status,o)),this._commitStep(s,()=>this._setLoading(!1)),this._value}catch(t){return t&&"AbortError"===t.name?(this._lane.claimTerminal(s,"aborted")&&this._commitStep(s,()=>this._setLoading(!1)),null):this._lane.claimTerminal(s,"error")?(this._commitStep(s,()=>{const e=String(t?.message??"Network request failed.");this._setErrorInfo(o,"execute",!0,e),this._setError(t??{message:e})}),this._commitStep(s,()=>this._setResponse(null,0)),this._commitStep(s,()=>this._setLoading(!1)),null):null}finally{null!==g&&clearTimeout(g),this._lane.finalize(s)}}}let u=!1;function d(e){const i=e.target;if(!(i instanceof Element))return;const s=i.closest(`[${t.triggerAttribute}]`);if(!s)return;const r=s.getAttribute(t.triggerAttribute);if(!r)return;const n=customElements.get(t.tagNames.fetch),o=document.getElementById(r);if(!(n&&o instanceof n))return;const a=o;a.url&&(e.preventDefault(),a.fetch())}function _(t,e){let i=Object.getPrototypeOf(t);for(;null!==i;){const t=Object.getOwnPropertyDescriptor(i,e);if(void 0!==t)return"function"==typeof t.get||"function"==typeof t.set;i=Object.getPrototypeOf(i)}return!1}const p=new WeakMap;function g(t,e){let i=p.get(t);return void 0===i&&(i=new Map,p.set(t,i)),i.has(e)||i.set(e,t.getAttribute(e)),i.get(e)}function m(t,e,i){null===i?t.removeAttribute(e):t.setAttribute(e,i)}function b(t,e,i){const s=g(t,e);m(t,e,void 0===i?s:null===i?null:String(i))}const f=Symbol.for("wcstack.trustedTypes.policy");function y(){const t=globalThis[f];return null===t||"object"!=typeof t?null:t}let v,I=!1;function w(t,e){try{t.innerHTML=function(t){if("string"!=typeof t)return t;const e=y(),i=e?.createHTML;return"function"!=typeof i?t:i.call(e,t)}(e)}catch(t){if(function(){if(void 0!==v)return v;if(!("trustedTypes"in globalThis))return v=!1,v;try{document.createElement("div").innerHTML="<i></i>",v=!1}catch{v=!0}return v}())return void function(){if(I)return;I=!0;const t="function"==typeof y()?.createHTML?"The injected policy's createHTML() did not return a TrustedHTML.":"No sanitizing policy is installed, and @wcstack/fetch deliberately does not pass responses through an identity policy — that would defeat the CSP.";console.error(`[@wcstack/fetch] The "target" HTML replace mode was blocked by Trusted Types (require-trusted-types-for 'script'). ${t}\nInstall a sanitizing policy before the first fetch:\n globalThis[Symbol.for("wcstack.trustedTypes.policy")] =\n trustedTypes.createPolicy("my-app", { createHTML: (s) => DOMPurify.sanitize(s) });\nOr drop "target" and bind the response through @wcstack/state. See docs/csp.md section 7.`)}();throw t}}class E extends HTMLElement{static hasConnectedCallbackPromise=!0;static wcBindable={...h.wcBindable,properties:[...h.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 h(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[i,s]of Object.entries(t))this.addEventListener(i,t=>{const i=this.hasAttribute("debug-states");for(const[r,n]of Object.entries(s(t.detail))){try{n?e.add(r):e.delete(r)}catch{}i&&this.toggleAttribute(`data-wcs-state-${r}`,n)}})}get url(){return this.getAttribute("url")||""}set url(t){b(this,"url",t)}get method(){return(this.getAttribute("method")||"GET").toUpperCase()}set method(t){b(this,"method",t)}get target(){return this.getAttribute("target")}set target(t){b(this,"target",t)}get responseType(){return this.getAttribute("response-type")||"auto"}set responseType(t){b(this,"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){!function(t,e,i){const s=g(t,e);m(t,e,void 0===i?s:i?"":null)}(this,"manual",t)}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 e={},i=this.querySelectorAll(t.tagNames.fetchHeader);for(const t of i){const i=t.headerName,s=t.headerValue;i&&(e[i]=s)}return e}_isNativeBodyInit(t){return t instanceof Blob||t instanceof FormData||t instanceof URLSearchParams||t instanceof ArrayBuffer||ArrayBuffer.isView(t)}_collectBody(e){if(null!==e)return"string"==typeof e||this._isNativeBodyInit(e)?{body:e,contentType:null}:{body:JSON.stringify(e),contentType:"application/json"};const i=this.querySelector(t.tagNames.fetchBody);return i?{body:i.bodyContent||null,contentType:i.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:i,contentType:s}=this._collectBody(e);i 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 r=await this._core.fetch(this.url,{method:this.method,headers:t,body:i,contentType:s,forceText:!!this.target,responseType:this.responseType});if(this.target&&null!==r){const t=document.getElementById(this.target);t&&w(t,r)}return r}attributeChangedCallback(t,e,i){"url"===t&&this._scheduleAutoFetch()}connectedCallback(){!function(t){const e=t.constructor?.wcBindable,i=e?.inputs;if(void 0!==i)for(const e of i){const i=e.name;if(!Object.prototype.hasOwnProperty.call(t,i))continue;if(!_(t,i))continue;const s=t,r=s[i];delete s[i],s[i]=r}}(this),this.style.display="none",u||(u=!0,document.addEventListener("click",d)),!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 T extends HTMLElement{connectedCallback(){this.style.display="none"}get headerName(){return this.getAttribute("name")||""}get headerValue(){return this.getAttribute("value")||""}}class A extends HTMLElement{constructor(){super(),this.attachShadow({mode:"open"})}get contentType(){return this.getAttribute("type")||"application/json"}get bodyContent(){return this.textContent?.trim()||""}}class O 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 E&&(t.loading||(t.trigger=!0,this.once&&(this._done=!0,this._disconnectObserver())))}}var C;!function(e=customElements){e.get(t.tagNames.fetch)||e.define(t.tagNames.fetch,E),e.get(t.tagNames.fetchHeader)||e.define(t.tagNames.fetchHeader,T),e.get(t.tagNames.fetchBody)||e.define(t.tagNames.fetchBody,A),e.get(t.tagNames.infiniteScroll)||e.define(t.tagNames.infiniteScroll,O)}(C);
1
+ const t={triggerAttribute:"data-fetchtarget",tagNames:{fetch:"wcs-fetch",fetchHeader:"wcs-fetch-header",fetchBody:"wcs-fetch-body",infiniteScroll:"wcs-infinite-scroll"}};class e{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,s={}){this.laneKey=t,this.policy=e,this._withSignal=s.withSignal??!1,this._trace=s.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++,s={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(s),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:s,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 s=e+1;this._attempts.set(t.operationId,s),this._releaseController(t.operationId);const i=this._makeAttempt(t.operationId,s);return void 0!==this._trace&&this._trace({type:"io:operation-retried",operationId:t.operationId,laneKey:this.laneKey,attempt:s}),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,s=this._terminal.get(e);if(void 0!==s&&"committing"!==s)return;let i;i="committing"===s?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 s;if(this._withSignal&&"function"==typeof AbortController){const e=new AbortController;this._controllers.set(t,e),s=e.signal}return{operationId:t,attempt:e,signal:s}}_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 s(t,e){const s=new Map,i=e=>{const s=t.get(e);return void 0===s?"unknown":s.probe()?"available":"missing"};let r=!0;for(const t of e.required){const e=i(t);s.set(t,e),"available"!==e&&(r=!1)}let n=!0;for(const t of e.optional??[]){const e=i(t);s.set(t,e),"available"!==e&&(n=!1)}const o=r?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:s,permission:e.permission??"not-applicable",readiness:o,activity:e.activity??"inactive",preconditions:{secureContext:h,userActivation:u},epoch:e.epoch??0,lastError:e.lastError}}function i(t,e){return e.every(e=>"available"===t.availability.get(e))}const r="capability-missing",n="invalid-argument",o="network",a="http-error",l="timeout",c=new Map([["web.fetch",{probe:()=>"function"==typeof globalThis.fetch,compatKey:"api.fetch"}],["web.abort-controller",{probe:()=>"function"==typeof globalThis.AbortController,compatKey:"api.AbortController"}]]);class h 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 e("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 i(this.platformAssessment,h.REQUIRED_CAPABILITIES)}get platformAssessment(){return s(c,{required:h.REQUIRED_CAPABILITIES,optional:h.OPTIONAL_CAPABILITIES,activity:this._loading?"active":"inactive",lastError:this._errorInfo??void 0})}_setErrorInfo(t,e,s,i,r){this._commitErrorInfo({code:t,phase:e,recoverable:s,message:i,...void 0===r?{}:{capabilityId:r}})}_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,s=null){null!==this._objectURL&&this._revokeObjectURL(this._objectURL),this._objectURL=s,this._value=t,this._status=e,this._target.dispatchEvent(new CustomEvent("wcs-fetch:response",{detail:{value:t,status:e,objectURL:s},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(n,"start",!1,"url attribute is required."),this._setError({message:"url attribute is required."}),null;const s=this.platformAssessment;if(!i(s,h.REQUIRED_CAPABILITIES)){const t=h.REQUIRED_CAPABILITIES.find(t=>"available"!==s.availability.get(t));return this._setErrorInfo(r,"start",!1,`Required capability "${t}" is unavailable.`,t),this._setError({message:`Required capability "${t}" is unavailable.`}),null}const o=this._doFetch(t,e);return this._promise=o,o}async _doFetch(t,e){const s=this._lane.begin(),{ticket:i,attempt:r}=s,n=r.signal;this._commitStep(i,()=>this._setLoading(!0)),this._commitStep(i,()=>{this._commitErrorInfo(null),this._setError(null)});const{method:c="GET",body:h=null,contentType:u=null,forceText:d=!1,responseType:_="auto",timeout:p=0}=e;let m=null;p>0&&(m=setTimeout(()=>{if(!this._lane.claimTerminal(i,"timeout"))return;const t=`Request timed out after ${p}ms.`;this._commitStep(i,()=>{this._setErrorInfo(l,"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)},p));const g={...e.headers??{}};try{u&&!g["Content-Type"]&&(g["Content-Type"]=u);const e={method:c,headers:g,signal:n};"GET"!==c&&"HEAD"!==c&&null!==h&&(e.body=h);const s=await globalThis.fetch(t,e);let r=null;if("HEAD"===c);else if(s.ok)if(d)r=await s.text();else if("blob"===_)r=await s.blob();else if("arrayBuffer"===_)r=await s.arrayBuffer();else if("text"===_)r=await s.text();else if("json"===_)r=await s.json();else{const t=s.headers.get("Content-Type")||"";r=t.includes("application/json")?await s.json():await s.text()}else;if(!s.ok){const t=await s.text().catch(()=>""),e={status:s.status,statusText:s.statusText,body:t};return this._lane.claimTerminal(i,"error")?(this._commitStep(i,()=>{this._setErrorInfo(a,"execute",!0,`HTTP ${s.status} ${s.statusText}`),this._setError(e)}),this._commitStep(i,()=>this._setResponse(null,s.status)),this._commitStep(i,()=>this._setLoading(!1)),null):null}if(!this._lane.claimTerminal(i,"success"))return null;const o=r instanceof Blob?this._createObjectURL(r):null;return this._commitStep(i,()=>this._setResponse(r,s.status,o)),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(o,"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!==m&&clearTimeout(m),this._lane.finalize(i)}}}let u=!1;function d(e){const s=e.target;if(!(s instanceof Element))return;const i=s.closest(`[${t.triggerAttribute}]`);if(!i)return;const r=i.getAttribute(t.triggerAttribute);if(!r)return;const n=customElements.get(t.tagNames.fetch),o=document.getElementById(r);if(!(n&&o instanceof n))return;const a=o;a.url&&(e.preventDefault(),a.fetch())}function _(t,e){let s=Object.getPrototypeOf(t);for(;null!==s;){const t=Object.getOwnPropertyDescriptor(s,e);if(void 0!==t)return"function"==typeof t.get||"function"==typeof t.set;s=Object.getPrototypeOf(s)}return!1}const p=new WeakMap;function m(t,e){let s=p.get(t);return void 0===s&&(s=new Map,p.set(t,s)),s.has(e)||s.set(e,t.getAttribute(e)),s.get(e)}function g(t,e,s){null===s?t.removeAttribute(e):t.setAttribute(e,s)}function b(t,e,s){const i=m(t,e);g(t,e,void 0===s?i:null===s?null:String(s))}const f=Symbol.for("wcstack.trustedTypes.policy");function y(){const t=globalThis[f];return null===t||"object"!=typeof t?null:t}let v,I=!1;function w(t,e){try{t.innerHTML=function(t){if("string"!=typeof t)return t;const e=y(),s=e?.createHTML;return"function"!=typeof s?t:s.call(e,t)}(e)}catch(t){if(function(){if(void 0!==v)return v;if(!("trustedTypes"in globalThis))return v=!1,v;try{document.createElement("div").innerHTML="<i></i>",v=!1}catch{v=!0}return v}())return void function(){if(I)return;I=!0;const t="function"==typeof y()?.createHTML?"The injected policy's createHTML() did not return a TrustedHTML.":"No sanitizing policy is installed, and @wcstack/fetch deliberately does not pass responses through an identity policy — that would defeat the CSP.";console.error(`[@wcstack/fetch] The "target" HTML replace mode was blocked by Trusted Types (require-trusted-types-for 'script'). ${t}\nInstall a sanitizing policy before the first fetch:\n globalThis[Symbol.for("wcstack.trustedTypes.policy")] =\n trustedTypes.createPolicy("my-app", { createHTML: (s) => DOMPurify.sanitize(s) });\nOr drop "target" and bind the response through @wcstack/state. See docs/csp.md section 7.`)}();throw t}}class E extends HTMLElement{static hasConnectedCallbackPromise=!0;static wcBindable={...h.wcBindable,properties:[...h.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 h(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[s,i]of Object.entries(t))this.addEventListener(s,t=>{const s=this.hasAttribute("debug-states");for(const[r,n]of Object.entries(i(t.detail))){try{n?e.add(r):e.delete(r)}catch{}s&&this.toggleAttribute(`data-wcs-state-${r}`,n)}})}get url(){return this.getAttribute("url")||""}set url(t){b(this,"url",t)}get method(){return(this.getAttribute("method")||"GET").toUpperCase()}set method(t){b(this,"method",t)}get target(){return this.getAttribute("target")}set target(t){b(this,"target",t)}get responseType(){return this.getAttribute("response-type")||"auto"}set responseType(t){b(this,"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){!function(t,e,s){const i=m(t,e);g(t,e,void 0===s?i:s?"":null)}(this,"manual",t)}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 e={},s=this.querySelectorAll(t.tagNames.fetchHeader);for(const t of s)t.hasHeader&&(e[t.headerName]=t.headerValue);return e}_isNativeBodyInit(t){return t instanceof Blob||t instanceof FormData||t instanceof URLSearchParams||t instanceof ArrayBuffer||ArrayBuffer.isView(t)}_collectBody(e){if(null!==e)return"string"==typeof e||this._isNativeBodyInit(e)?{body:e,contentType:null}:{body:JSON.stringify(e),contentType:"application/json"};const s=this.querySelector(t.tagNames.fetchBody);return s?{body:s.bodyContent||null,contentType:s.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:s,contentType:i}=this._collectBody(e);s 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 r=await this._core.fetch(this.url,{method:this.method,headers:t,body:s,contentType:i,forceText:!!this.target,responseType:this.responseType});if(this.target&&null!==r){const t=document.getElementById(this.target);t&&w(t,r)}return r}attributeChangedCallback(t,e,s){"url"===t&&this._scheduleAutoFetch()}connectedCallback(){!function(t){const e=t.constructor?.wcBindable,s=e?.inputs;if(void 0!==s)for(const e of s){const s=e.name;if(!Object.prototype.hasOwnProperty.call(t,s))continue;if(!_(t,s))continue;const i=t,r=i[s];delete i[s],i[s]=r}}(this),this.style.display="none",u||(u=!0,document.addEventListener("click",d)),!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 T extends HTMLElement{connectedCallback(){for(const t of["name","value"])if(Object.prototype.hasOwnProperty.call(this,t)){const e=this[t];delete this[t],this[t]=e}this.style.display="none"}get name(){return this.getAttribute("name")??""}set name(t){b(this,"name",t)}get value(){return this.getAttribute("value")??""}set value(t){b(this,"value",t)}get headerName(){return this.name}get headerValue(){return this.value}get hasHeader(){return""!==this.name&&this.hasAttribute("value")}}class A extends HTMLElement{constructor(){super(),this.attachShadow({mode:"open"})}get contentType(){return this.getAttribute("type")||"application/json"}get bodyContent(){return this.textContent?.trim()||""}}class O 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 E&&(t.loading||(t.trigger=!0,this.once&&(this._done=!0,this._disconnectObserver())))}}var C;!function(e=customElements){e.get(t.tagNames.fetch)||e.define(t.tagNames.fetch,E),e.get(t.tagNames.fetchHeader)||e.define(t.tagNames.fetchHeader,T),e.get(t.tagNames.fetchBody)||e.define(t.tagNames.fetchBody,A),e.get(t.tagNames.infiniteScroll)||e.define(t.tagNames.infiniteScroll,O)}(C);
2
2
  //# sourceMappingURL=auto.min.js.map