@wcstack/fetch 4.10.0 → 4.11.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.
- package/README.ja.md +25 -3
- package/README.md +27 -3
- package/dist/auto.min.js +1 -1
- package/dist/auto.min.js.map +1 -1
- package/dist/index.esm.js +68 -12
- package/dist/index.esm.js.map +1 -1
- package/package.json +1 -1
package/README.ja.md
CHANGED
|
@@ -163,8 +163,30 @@ npm install @wcstack/fetch
|
|
|
163
163
|
```
|
|
164
164
|
|
|
165
165
|
`true` を書き込んだ時点で `url` が空の場合(state 駆動の computed url が未確定など)、
|
|
166
|
-
その書き込みは
|
|
167
|
-
|
|
166
|
+
その書き込みは **無視** されます。fetch は実行されず、`trigger` は `false` のまま、
|
|
167
|
+
イベントも発火しません — 4.5 からは警告します(`[wcs/command-not-ready]`、[設計メモ](#設計メモ))。
|
|
168
|
+
先に `url` を設定してから改めて `true` を書き込んでください。
|
|
169
|
+
|
|
170
|
+
**`trigger` が送るのは、trigger が当たった時点で要素が持っているもの**です: その時点の `url`・`method`・`body`
|
|
171
|
+
と、中の `<wcs-fetch-header>` / `<wcs-fetch-body>`。1 回の更新の中で、`@wcstack/state` は束縛をパスを書いた順に
|
|
172
|
+
当てます — 要素をまたいでも同じで、getter の束縛は、それが読む最初のパスを書いたところで当たります
|
|
173
|
+
([タイミング契約 §4.4](../../docs/timing-and-firing-contract.ja.md#44-1-回の更新の中では束縛はパスを書いた順に当たる))。だからハンドラの中で書く順が、送られるものを決めます。
|
|
174
|
+
ログアウトは、終わらせるトークンをまだ運ばなければなりません — trigger を先に書きます:
|
|
175
|
+
|
|
176
|
+
```js
|
|
177
|
+
// <wcs-fetch url="/api/logout" method="POST" manual data-wcs="trigger: logoutTrigger">
|
|
178
|
+
// <wcs-fetch-header name="Authorization" data-wcs="value: authHeader"></wcs-fetch-header>
|
|
179
|
+
// </wcs-fetch>
|
|
180
|
+
// get authHeader() { const t = this["session.token"]; return t ? "Bearer " + t : null; } とする
|
|
181
|
+
logout() {
|
|
182
|
+
this.logoutTrigger = true; // ヘッダ付きで要求が出て…
|
|
183
|
+
this.session = null; // …その後でヘッダが外れる
|
|
184
|
+
},
|
|
185
|
+
```
|
|
186
|
+
|
|
187
|
+
逆の順(`this.session = null; this.logoutTrigger = true;`)では先にヘッダが外れ、ログアウトはヘッダなしで出ます:
|
|
188
|
+
サーバーはセッションを終わらせられず、何も言いません。反対の場合は、ハンドラが書くものを要る要求です —
|
|
189
|
+
`body`(や `url`)を先に、`trigger` を後に書きます。下の `submit()` がそうしています。
|
|
168
190
|
|
|
169
191
|
### 4. body 付きの POST
|
|
170
192
|
|
|
@@ -887,7 +909,7 @@ bootstrapFetch({
|
|
|
887
909
|
- `value`、`loading`、`error`、`status`、`objectURL`、`errorInfo` は **出力ステート**
|
|
888
910
|
- `url`、`body`、`response-type`、`trigger` は **入力 / コマンドサーフェス**
|
|
889
911
|
- `response-type`(既定 `auto`)はレスポンスボディの読み取り方を選ぶ。`blob` は加えて管理された `objectURL`(新しいレスポンスごと / dispose 時に revoke)を発行する。`target`(HTML リプレースモード)が優先される
|
|
890
|
-
- `trigger` は意図的に単方向: `true` を書き込むと実行、リセットで完了を通知。`url` が空のまま `true` を書き込んだ場合は無視される(fetch なし・イベントなし・フラグは `false` のまま)。4.5 から警告する(`[wcs/command-not-ready]`)。リクエストをまた送るまで 1 回(4.8 から。それまでは要素ごとに 1 回)。1 つの `data-wcs` では `trigger` を `url`
|
|
912
|
+
- `trigger` は意図的に単方向: `true` を書き込むと実行、リセットで完了を通知。`url` が空のまま `true` を書き込んだ場合は無視される(fetch なし・イベントなし・フラグは `false` のまま)。4.5 から警告する(`[wcs/command-not-ready]`)。リクエストをまた送るまで 1 回(4.8 から。それまでは要素ごとに 1 回)。1 つの `data-wcs` では `trigger` を `url` の後に書くこと(束縛は書いた順に当たる)。更新では、順はパスを書いた順で、要素をまたいでも同じ。`trigger` は当たった時点で要素が持つ入力・ヘッダ・本文を送る([`trigger` による手動実行](#3-trigger-による手動実行))
|
|
891
913
|
- HTTP エラー時(status >= 400)は `value` が `null` にリセットされ、`status` にエラーコードが入る — `value` のみのバインドでは直前の値が消えるため、失敗検知には `error` をバインドする
|
|
892
914
|
- ネットワークエラー時(HTTP レスポンスなし — DNS 失敗・オフライン・CORS など)は `value` が `null`、`status` が `0` にリセットされ、`error` に投げられた `Error` が入る。HTTP エラーと同様、直前の成功時の value/status は残らない
|
|
893
915
|
- `method="HEAD"` は仕様上ボディを持たないためレスポンスボディの読取をスキップする。`value` は `null` のままで `status` のみ通知される
|
package/README.md
CHANGED
|
@@ -163,8 +163,32 @@ auto-reset: true → false Dispatches wcs-fetch:trigger-changed
|
|
|
163
163
|
```
|
|
164
164
|
|
|
165
165
|
If `url` is empty when `true` is written (e.g. a state-driven computed url not yet
|
|
166
|
-
resolved), the write is **
|
|
167
|
-
and no event fires
|
|
166
|
+
resolved), the write is **ignored**: no fetch runs, `trigger` stays `false`,
|
|
167
|
+
and no event fires — since 4.5 it warns (`[wcs/command-not-ready]`, see [Design Notes](#design-notes)).
|
|
168
|
+
Set the `url` first, then write `true` again to execute.
|
|
169
|
+
|
|
170
|
+
**A `trigger` sends what the element has when the trigger is applied**: its `url`, `method`
|
|
171
|
+
and `body`, and the `<wcs-fetch-header>` / `<wcs-fetch-body>` inside it, as they are at that
|
|
172
|
+
moment. Within one update, `@wcstack/state` applies the bindings in the order their paths were
|
|
173
|
+
written — across elements too, and a getter's bindings where the first path it reads was written
|
|
174
|
+
([timing contract §4.4](../../docs/timing-and-firing-contract.md#44-within-one-update-bindings-apply-in-the-order-their-paths-were-written)). So the order of the writes in a handler decides
|
|
175
|
+
what goes out. A logout must still carry the token it ends — write the trigger first:
|
|
176
|
+
|
|
177
|
+
```js
|
|
178
|
+
// <wcs-fetch url="/api/logout" method="POST" manual data-wcs="trigger: logoutTrigger">
|
|
179
|
+
// <wcs-fetch-header name="Authorization" data-wcs="value: authHeader"></wcs-fetch-header>
|
|
180
|
+
// </wcs-fetch>
|
|
181
|
+
// with get authHeader() { const t = this["session.token"]; return t ? "Bearer " + t : null; }
|
|
182
|
+
logout() {
|
|
183
|
+
this.logoutTrigger = true; // the request goes out with the header…
|
|
184
|
+
this.session = null; // …and then the header is removed
|
|
185
|
+
},
|
|
186
|
+
```
|
|
187
|
+
|
|
188
|
+
Written the other way round (`this.session = null; this.logoutTrigger = true;`), the header is
|
|
189
|
+
removed first and the logout goes out without it: the server cannot end the session, and nothing
|
|
190
|
+
says so. The opposite case is a request that needs what the handler writes — write `body` (or
|
|
191
|
+
`url`) first, then `trigger`, as `submit()` does below.
|
|
168
192
|
|
|
169
193
|
### 4. POST with a body
|
|
170
194
|
|
|
@@ -895,7 +919,7 @@ bootstrapFetch({
|
|
|
895
919
|
- `value`, `loading`, `error`, `status`, `objectURL`, and `errorInfo` are **output state**
|
|
896
920
|
- `url`, `body`, `response-type`, and `trigger` are **input / command surface**
|
|
897
921
|
- `response-type` (default `auto`) selects how the response body is read; `blob` additionally publishes a managed `objectURL` (revoked on each new response / dispose). `target` (HTML-replace mode) overrides it
|
|
898
|
-
- `trigger` is intentionally one-way: writing `true` executes, reset emits completion. Writing `true` while `url` is empty is ignored (no fetch, no event, flag stays `false`); since 4.5 it warns (`[wcs/command-not-ready]`), once until a request is sent again (since 4.8; before, once per element) — in one `data-wcs`, write `trigger` after `url`, since bindings apply in the order written
|
|
922
|
+
- `trigger` is intentionally one-way: writing `true` executes, reset emits completion. Writing `true` while `url` is empty is ignored (no fetch, no event, flag stays `false`); since 4.5 it warns (`[wcs/command-not-ready]`), once until a request is sent again (since 4.8; before, once per element) — in one `data-wcs`, write `trigger` after `url`, since bindings apply in the order written. On an update the order is the one the paths were written in, across elements too, and a `trigger` sends the inputs, headers and body the element has when it is applied ([Manual execution with `trigger`](#3-manual-execution-with-trigger))
|
|
899
923
|
- on an HTTP error (status >= 400), `value` is reset to `null` while `status` carries the error code — a `value`-only binding loses its previous value, so bind `error` to detect failures
|
|
900
924
|
- on a network error (no HTTP response — DNS failure, offline, CORS, etc.), `value` is reset to `null` and `status` to `0`; `error` holds the thrown `Error`. Like HTTP errors, a previous successful value/status does not linger
|
|
901
925
|
- `method="HEAD"` skips response-body reading by spec (no body); `value` stays `null` and only `status` is surfaced
|
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"}]]),h=new Set(["GET","HEAD","OPTIONS"]);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 e("fetch","latest",{withSignal:!0});_inFlight=null;_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,u.REQUIRED_CAPABILITIES)}get platformAssessment(){return i(c,{required:u.REQUIRED_CAPABILITIES,optional:u.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,u.REQUIRED_CAPABILITIES)){const t=u.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._inFlight;null===i||h.has(i.method)||console.warn(`[@wcstack/fetch] [wcs/fetch-request-superseded] A ${i.method} request to "${i.url}" was still in flight when another request started on the same element: it was aborted and its response dropped (the server may have applied it). Give each change its own <wcs-fetch>, or wait for loading to end before starting the next request.`);const s=this._lane.begin(),{ticket:r,attempt:n}=s,c=n.signal,u={method:String(e.method??"GET").toUpperCase(),url:t};this._inFlight=u,this._commitStep(r,()=>this._setLoading(!0)),this._commitStep(r,()=>{this._commitErrorInfo(null),this._setError(null)});const{method:d="GET",body:g=null,contentType:p=null,forceText:_=!1,responseType:m="auto",timeout:f=0}=e;let b=null;f>0&&(b=setTimeout(()=>{if(!this._lane.claimTerminal(r,"timeout"))return;const t=`Request timed out after ${f}ms.`;this._commitStep(r,()=>{this._setErrorInfo(l,"execute",!0,t),this._setError({name:"TimeoutError",message:t})}),this._commitStep(r,()=>this._setResponse(null,0)),this._commitStep(r,()=>this._setLoading(!1)),this._lane.abort(r),this._lane.finalize(r)},f));const y={...e.headers??{}};try{p&&!y["Content-Type"]&&(y["Content-Type"]=p);const e={method:d,headers:y,signal:c};"GET"!==d&&"HEAD"!==d&&null!==g&&(e.body=g);const i=await globalThis.fetch(t,e);let s=null;if("HEAD"===d);else if(i.ok)if(_)s=await i.text();else if("blob"===m)s=await i.blob();else if("arrayBuffer"===m)s=await i.arrayBuffer();else if("text"===m)s=await i.text();else if("json"===m)s=await i.json();else{const t=i.headers.get("Content-Type")||"";s=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(r,"error")?(this._commitStep(r,()=>{this._setErrorInfo(a,"execute",!0,`HTTP ${i.status} ${i.statusText}`),this._setError(e)}),this._commitStep(r,()=>this._setResponse(null,i.status)),this._commitStep(r,()=>this._setLoading(!1)),null):null}if(!this._lane.claimTerminal(r,"success"))return null;const n=s instanceof Blob?this._createObjectURL(s):null;return this._commitStep(r,()=>this._setResponse(s,i.status,n)),this._commitStep(r,()=>this._setLoading(!1)),this._value}catch(t){return t&&"AbortError"===t.name?(this._lane.claimTerminal(r,"aborted")&&this._commitStep(r,()=>this._setLoading(!1)),null):this._lane.claimTerminal(r,"error")?(this._commitStep(r,()=>{const e=String(t?.message??"Network request failed.");this._setErrorInfo(o,"execute",!0,e),this._setError(t??{message:e})}),this._commitStep(r,()=>this._setResponse(null,0)),this._commitStep(r,()=>this._setLoading(!1)),null):null}finally{this._inFlight===u&&(this._inFlight=null),null!==b&&clearTimeout(b),this._lane.finalize(r)}}}let d=!1;function g(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 p(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 _=new WeakSet;function m(t,e,i){if(_.has(t))return;_.add(t);const s=t.localName??"element";console.warn(`[wcs/input-as-attribute] <${s}> has the attribute ${e}="${i}": an object was written as an attribute, so the element did not receive it. A framework does that when the property is set before the element's definition loads (React 19), or when told to (Vue's .attr). Load the definition before rendering, or assign the property through a ref (Vue: .prop). (Said once per element.)`,t)}const f=new WeakMap;function b(t,e){let i=f.get(t);return void 0===i&&(i=new Map,f.set(t,i)),i.has(e)||i.set(e,t.getAttribute(e)),i.get(e)}function y(t,e,i){null===i?t.removeAttribute(e):t.setAttribute(e,i)}function v(t,e,i){const s=b(t,e);y(t,e,void 0===i?s:null===i?null:String(i))}const w=Symbol.for("wcstack.trustedTypes.policy");function I(){const t=globalThis[w];return null===t||"object"!=typeof t?null:t}let T,A=!1;function E(t,e){try{t.innerHTML=function(t){if("string"!=typeof t)return t;const e=I(),i=e?.createHTML;return"function"!=typeof i?t:i.call(e,t)}(e)}catch(t){if(function(){if(void 0!==T)return T;if(!("trustedTypes"in globalThis))return T=!1,T;try{document.createElement("div").innerHTML="<i></i>",T=!1}catch{T=!0}return T}())return void function(){if(A)return;A=!0;const t="function"==typeof I()?.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 O extends HTMLElement{static hasConnectedCallbackPromise=!0;static hasPendingPromise=!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;_toldTriggerWithoutUrl=!1;_toldUndefinedHelper=!1;_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[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){v(this,"url",t)}get method(){return(this.getAttribute("method")||"GET").toUpperCase()}set method(t){v(this,"method",t)}get target(){return this.getAttribute("target")}set target(t){v(this,"target",t)}get responseType(){return this.getAttribute("response-type")||"auto"}set responseType(t){v(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 pendingPromise(){return this._autoPending&&!this.manual&&this.url?Promise.resolve().then(()=>this.pendingPromise??void 0):this.loading?this._core.promise.then(()=>{}):null}get manual(){return this.hasAttribute("manual")}set manual(t){!function(t,e,i){const s=b(t,e);y(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 void this._warnTriggerWithoutUrl();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 s of i)"boolean"==typeof s.hasHeader?s.hasHeader&&(e[s.headerName]=s.headerValue):this._warnUndefinedHelper(t.tagNames.fetchHeader,"header");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);if(i&&"string"!=typeof i.bodyContent)this._warnUndefinedHelper(t.tagNames.fetchBody,"body");else if(i)return{body:i.bodyContent||null,contentType:i.contentType};return{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;e||(this._lastFetchedUrl=null),this.isConnected&&!this.manual&&e&&e!==this._lastFetchedUrl?(null===t&&this._warnUnsafeAutoFetch(),this.fetch().finally(()=>t?.())):t?.()}))}_warnTriggerWithoutUrl(){this._toldTriggerWithoutUrl||(this._toldTriggerWithoutUrl=!0,console.warn("[@wcstack/fetch] [wcs/command-not-ready] trigger was refused: there is no url, so nothing is fetched. Write url before trigger (bindings apply in the order written), and write trigger again once there is one. (Said once until a request is sent again.)",this))}_warnUndefinedHelper(e,i){this._toldUndefinedHelper||(this._toldUndefinedHelper=!0,console.warn(`[@wcstack/fetch] [wcs/fetch-helper-undefined] <${e}> inside this <${t.tagNames.fetch}> is not defined, so its ${i} is not sent. Load @wcstack/fetch/auto, or define WcsFetchHeader and WcsFetchBody with WcsFetch when the page defines the tags itself. (Said once per element.)`,this))}_warnUnsafeAutoFetch(){const e=this.method;"GET"!==e&&"HEAD"!==e&&"OPTIONS"!==e&&null===this._body&&null===this.querySelector(t.tagNames.fetchBody)&&console.warn(`[@wcstack/fetch] [wcs/fetch-auto-unsafe] The url changed to "${this.url}", so this <wcs-fetch> sent a ${e} with no body (its method stays ${e}; a body is sent once). Give loading and each change its own <wcs-fetch>, or set \`manual\` on the one that changes data.`)}async fetch(){this._lastFetchedUrl=this.url,this.url&&(this._toldTriggerWithoutUrl=!1);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&&E(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)return;const s=t.getAttribute;for(const e of i){const i=e.name,r="function"==typeof s?s.call(t,i.toLowerCase()):null;if(null!==r&&r.startsWith("[object ")&&m(t,i,r),!Object.prototype.hasOwnProperty.call(t,i))continue;if(!p(t,i))continue;const n=t,o=n[i];delete n[i],n[i]=o}}(this),this.style.display="none",d||(d=!0,document.addEventListener("click",g)),!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 C 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){v(this,"name",t)}get value(){return this.getAttribute("value")??""}set value(t){v(this,"value",t)}get headerName(){return this.name}get headerValue(){return this.value}get hasHeader(){return""!==this.name&&this.hasAttribute("value")}}class L extends HTMLElement{constructor(){super(),this.attachShadow({mode:"open"})}get contentType(){return this.getAttribute("type")||"application/json"}get bodyContent(){return this.textContent?.trim()||""}}class S extends HTMLElement{static get observedAttributes(){return["target","root","root-margin","threshold","disabled"]}_observer=null;_done=!1;_warnedTarget=null;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 e=document.getElementById(this.target);e instanceof O?e.loading||(e.trigger=!0,this.once&&(this._done=!0,this._disconnectObserver())):this._warnedTarget!==this.target&&(this._warnedTarget=this.target,console.warn(`[@wcstack/fetch] [wcs/infinite-scroll-target] <${t.tagNames.infiniteScroll} target="${this.target}"> came into view, but no <${t.tagNames.fetch}> has that id, so no page was loaded.`))}}var k;!function(e=customElements){e.get(t.tagNames.fetch)||e.define(t.tagNames.fetch,O),e.get(t.tagNames.fetchHeader)||e.define(t.tagNames.fetchHeader,C),e.get(t.tagNames.fetchBody)||e.define(t.tagNames.fetchBody,L),e.get(t.tagNames.infiniteScroll)||e.define(t.tagNames.infiniteScroll,S)}(k);
|
|
1
|
+
const t={triggerAttribute:"data-fetchtarget",tagNames:{fetch:"wcs-fetch",fetchHeader:"wcs-fetch-header",fetchBody:"wcs-fetch-body",infiniteScroll:"wcs-infinite-scroll"}};var e="@wcstack/fetch",i="4.11.0";class s{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 r(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??[]],c=a.some(e=>!0===t.get(e)?.requiresSecureContext),l=a.some(e=>!0===t.get(e)?.requiresUserActivation),h=c?!0===globalThis.isSecureContext?"satisfied":"required":"not-applicable",u=l?"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 n(t,e){return e.every(e=>"available"===t.availability.get(e))}const o="capability-missing",a="invalid-argument",c="network",l="http-error",h="timeout",u=new Map([["web.fetch",{probe:()=>"function"==typeof globalThis.fetch,compatKey:"api.fetch"}],["web.abort-controller",{probe:()=>"function"==typeof globalThis.AbortController,compatKey:"api.AbortController"}]]),d=new Set(["GET","HEAD","OPTIONS"]);class p 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 s("fetch","latest",{withSignal:!0});_inFlight=null;_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 n(this.platformAssessment,p.REQUIRED_CAPABILITIES)}get platformAssessment(){return r(u,{required:p.REQUIRED_CAPABILITIES,optional:p.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(a,"start",!1,"url attribute is required."),this._setError({message:"url attribute is required."}),null;const i=this.platformAssessment;if(!n(i,p.REQUIRED_CAPABILITIES)){const t=p.REQUIRED_CAPABILITIES.find(t=>"available"!==i.availability.get(t));return this._setErrorInfo(o,"start",!1,`Required capability "${t}" is unavailable.`,t),this._setError({message:`Required capability "${t}" is unavailable.`}),null}const s=this._doFetch(t,e);return this._promise=s,s}async _doFetch(t,e){const i=this._inFlight;null===i||d.has(i.method)||console.warn(`[@wcstack/fetch] [wcs/fetch-request-superseded] A ${i.method} request to "${i.url}" was still in flight when another request started on the same element: it was aborted and its response dropped (the server may have applied it). Give each change its own <wcs-fetch>, or wait for loading to end before starting the next request.`);const s=this._lane.begin(),{ticket:r,attempt:n}=s,o=n.signal,a={method:String(e.method??"GET").toUpperCase(),url:t};this._inFlight=a,this._commitStep(r,()=>this._setLoading(!0)),this._commitStep(r,()=>{this._commitErrorInfo(null),this._setError(null)});const{method:u="GET",body:p=null,contentType:g=null,forceText:_=!1,responseType:m="auto",timeout:f=0}=e;let b=null;f>0&&(b=setTimeout(()=>{if(!this._lane.claimTerminal(r,"timeout"))return;const t=`Request timed out after ${f}ms.`;this._commitStep(r,()=>{this._setErrorInfo(h,"execute",!0,t),this._setError({name:"TimeoutError",message:t})}),this._commitStep(r,()=>this._setResponse(null,0)),this._commitStep(r,()=>this._setLoading(!1)),this._lane.abort(r),this._lane.finalize(r)},f));const y={...e.headers??{}};try{g&&!y["Content-Type"]&&(y["Content-Type"]=g);const e={method:u,headers:y,signal:o};"GET"!==u&&"HEAD"!==u&&null!==p&&(e.body=p);const i=await globalThis.fetch(t,e);let s=null;if("HEAD"===u);else if(i.ok)if(_)s=await i.text();else if("blob"===m)s=await i.blob();else if("arrayBuffer"===m)s=await i.arrayBuffer();else if("text"===m)s=await i.text();else if("json"===m)s=await i.json();else{const t=i.headers.get("Content-Type")||"";s=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(r,"error")?(this._commitStep(r,()=>{this._setErrorInfo(l,"execute",!0,`HTTP ${i.status} ${i.statusText}`),this._setError(e)}),this._commitStep(r,()=>this._setResponse(null,i.status)),this._commitStep(r,()=>this._setLoading(!1)),null):null}if(!this._lane.claimTerminal(r,"success"))return null;const n=s instanceof Blob?this._createObjectURL(s):null;return this._commitStep(r,()=>this._setResponse(s,i.status,n)),this._commitStep(r,()=>this._setLoading(!1)),this._value}catch(t){return t&&"AbortError"===t.name?(this._lane.claimTerminal(r,"aborted")&&this._commitStep(r,()=>this._setLoading(!1)),null):this._lane.claimTerminal(r,"error")?(this._commitStep(r,()=>{const e=String(t?.message??"Network request failed.");this._setErrorInfo(c,"execute",!0,e),this._setError(t??{message:e})}),this._commitStep(r,()=>this._setResponse(null,0)),this._commitStep(r,()=>this._setLoading(!1)),null):null}finally{this._inFlight===a&&(this._inFlight=null),null!==b&&clearTimeout(b),this._lane.finalize(r)}}}let g=!1;function _(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 m(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 f=new WeakSet;function b(t,e,i){if(f.has(t))return;f.add(t);const s=t.localName??"element";console.warn(`[wcs/input-as-attribute] <${s}> has the attribute ${e}="${i}": an object was written as an attribute, so the element did not receive it. A framework does that when the property is set before the element's definition loads (React 19), or when told to (Vue's .attr). Load the definition before rendering, or assign the property through a ref (Vue: .prop). (Said once per element.)`,t)}const y=new WeakMap;function v(t,e){let i=y.get(t);return void 0===i&&(i=new Map,y.set(t,i)),i.has(e)||i.set(e,t.getAttribute(e)),i.get(e)}function w(t,e,i){null===i?t.removeAttribute(e):t.setAttribute(e,i)}function I(t,e,i){const s=v(t,e);w(t,e,void 0===i?s:null===i?null:String(i))}const T=Symbol.for("wcstack.trustedTypes.policy");function A(){const t=globalThis[T];return null===t||"object"!=typeof t?null:t}let E,O=!1;function C(t,e){try{t.innerHTML=function(t){if("string"!=typeof t)return t;const e=A(),i=e?.createHTML;return"function"!=typeof i?t:i.call(e,t)}(e)}catch(t){if(function(){if(void 0!==E)return E;if(!("trustedTypes"in globalThis))return E=!1,E;try{document.createElement("div").innerHTML="<i></i>",E=!1}catch{E=!0}return E}())return void function(){if(O)return;O=!0;const t="function"==typeof A()?.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 L extends HTMLElement{static hasConnectedCallbackPromise=!0;static hasPendingPromise=!0;static wcBindable={...p.wcBindable,properties:[...p.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;_toldTriggerWithoutUrl=!1;_toldUndefinedHelper=!1;_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 p(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){I(this,"url",t)}get method(){return(this.getAttribute("method")||"GET").toUpperCase()}set method(t){I(this,"method",t)}get target(){return this.getAttribute("target")}set target(t){I(this,"target",t)}get responseType(){return this.getAttribute("response-type")||"auto"}set responseType(t){I(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 pendingPromise(){return this._autoPending&&!this.manual&&this.url?Promise.resolve().then(()=>this.pendingPromise??void 0):this.loading?this._core.promise.then(()=>{}):null}get manual(){return this.hasAttribute("manual")}set manual(t){!function(t,e,i){const s=v(t,e);w(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 void this._warnTriggerWithoutUrl();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 s of i)"boolean"==typeof s.hasHeader?s.hasHeader&&(e[s.headerName]=s.headerValue):this._warnUndefinedHelper(t.tagNames.fetchHeader,"header");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);if(i&&"string"!=typeof i.bodyContent)this._warnUndefinedHelper(t.tagNames.fetchBody,"body");else if(i)return{body:i.bodyContent||null,contentType:i.contentType};return{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;e||(this._lastFetchedUrl=null),this.isConnected&&!this.manual&&e&&e!==this._lastFetchedUrl?(null===t&&this._warnUnsafeAutoFetch(),this.fetch().finally(()=>t?.())):t?.()}))}_warnTriggerWithoutUrl(){this._toldTriggerWithoutUrl||(this._toldTriggerWithoutUrl=!0,console.warn("[@wcstack/fetch] [wcs/command-not-ready] trigger was refused: there is no url, so nothing is fetched. Write url before trigger (bindings apply in the order written), and write trigger again once there is one. (Said once until a request is sent again.)",this))}_warnUndefinedHelper(e,i){this._toldUndefinedHelper||(this._toldUndefinedHelper=!0,console.warn(`[@wcstack/fetch] [wcs/fetch-helper-undefined] <${e}> inside this <${t.tagNames.fetch}> is not defined, so its ${i} is not sent. Load @wcstack/fetch/auto, or define WcsFetchHeader and WcsFetchBody with WcsFetch when the page defines the tags itself. (Said once per element.)`,this))}_warnUnsafeAutoFetch(){const e=this.method;"GET"!==e&&"HEAD"!==e&&"OPTIONS"!==e&&null===this._body&&null===this.querySelector(t.tagNames.fetchBody)&&console.warn(`[@wcstack/fetch] [wcs/fetch-auto-unsafe] The url changed to "${this.url}", so this <wcs-fetch> sent a ${e} with no body (its method stays ${e}; a body is sent once). Give loading and each change its own <wcs-fetch>, or set \`manual\` on the one that changes data.`)}async fetch(){this._lastFetchedUrl=this.url,this.url&&(this._toldTriggerWithoutUrl=!1);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&&C(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)return;const s=t.getAttribute;for(const e of i){const i=e.name,r="function"==typeof s?s.call(t,i.toLowerCase()):null;if(null!==r&&r.startsWith("[object ")&&b(t,i,r),!Object.prototype.hasOwnProperty.call(t,i))continue;if(!m(t,i))continue;const n=t,o=n[i];delete n[i],n[i]=o}}(this),this.style.display="none",g||(g=!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 k 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){I(this,"name",t)}get value(){return this.getAttribute("value")??""}set value(t){I(this,"value",t)}get headerName(){return this.name}get headerValue(){return this.value}get hasHeader(){return""!==this.name&&this.hasAttribute("value")}}class S extends HTMLElement{constructor(){super(),this.attachShadow({mode:"open"})}get contentType(){return this.getAttribute("type")||"application/json"}get bodyContent(){return this.textContent?.trim()||""}}class R extends HTMLElement{static get observedAttributes(){return["target","root","root-margin","threshold","disabled"]}_observer=null;_done=!1;_warnedTarget=null;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 e=document.getElementById(this.target);e instanceof L?e.loading||(e.trigger=!0,this.once&&(this._done=!0,this._disconnectObserver())):this._warnedTarget!==this.target&&(this._warnedTarget=this.target,console.warn(`[@wcstack/fetch] [wcs/infinite-scroll-target] <${t.tagNames.infiniteScroll} target="${this.target}"> came into view, but no <${t.tagNames.fetch}> has that id, so no page was loaded.`))}}const U=Symbol.for("wcstack.package"),j=new WeakSet;function P(t,e){Object.defineProperty(t,U,{value:e,configurable:!0})}function q(t,e,i,s,r){if(void 0!==s&&(i===s||i.prototype instanceof s))return;const n=i[U];if(n===r||j.has(t))return;j.add(t);const o=r.slice(0,r.lastIndexOf("@"));console.warn(`[${o}] [wcs/package-twice] <${e}> is already defined by ${n??`another copy of ${o} that does not name its version`}; this copy, ${r}, does nothing. Load each package once.`)}function B(s=customElements){!function(t,e,i){for(const[s,r]of i){const i=t.get(s);void 0===i?(P(r,e),t.define(s,r)):q(t,s,i,r,e)}}(s,`${e}@${i}`,[[t.tagNames.fetch,L],[t.tagNames.fetchHeader,k],[t.tagNames.fetchBody,S],[t.tagNames.infiniteScroll,R]])}var F;B(F);
|
|
2
2
|
//# sourceMappingURL=auto.min.js.map
|