@wcstack/fetch 1.20.0 → 1.21.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/dist/index.esm.js CHANGED
@@ -47,6 +47,388 @@ function setConfig(partialConfig) {
47
47
  frozenConfig = null;
48
48
  }
49
49
 
50
+ // ===========================================================================
51
+ // AUTO-GENERATED FILE - DO NOT EDIT.
52
+ // Generated from /io-core/operation-lane.ts by scripts/sync-io-core.mjs.
53
+ // Run `node scripts/sync-io-core.mjs` after editing the source.
54
+ // ===========================================================================
55
+ /**
56
+ * 1 レーン = 独立した排他単位。Core が 1 つ以上所有する (module singleton にしない —
57
+ * 複数 <wcs-fetch> 間で漏れるため)。
58
+ */
59
+ class OperationLane {
60
+ laneKey;
61
+ policy;
62
+ _ownerGeneration = 0;
63
+ _latestEpoch = 0;
64
+ _nextOperationId = 1;
65
+ // latest / queue / exhaust の単一 active。queue は head を指す。
66
+ _activeOperationId = undefined;
67
+ // overlap の active set (§5: 内部 bookkeeping のみ・observable 公開はしない)。
68
+ _activeOperationIds = new Set();
69
+ // queue policy の FIFO。
70
+ _queue = [];
71
+ _inFlightCount = 0;
72
+ // opId → 終端状態 (absence = pending)。
73
+ _terminal = new Map();
74
+ // claimTerminal で確定した outcome (finalize が 'committing' を最終値へ移す)。
75
+ _claimedOutcome = new Map();
76
+ // opId → AbortController (identity は opId が保証。cross-op clobber は構造上起きない)。
77
+ _controllers = new Map();
78
+ // opId → attempt 数。
79
+ _attempts = new Map();
80
+ _withSignal;
81
+ _trace;
82
+ constructor(laneKey, policy, options = {}) {
83
+ this.laneKey = laneKey;
84
+ this.policy = policy;
85
+ this._withSignal = options.withSignal ?? false;
86
+ this._trace = options.trace;
87
+ }
88
+ get ownerGeneration() {
89
+ return this._ownerGeneration;
90
+ }
91
+ get inFlightCount() {
92
+ return this._inFlightCount;
93
+ }
94
+ get latestEpoch() {
95
+ return this._latestEpoch;
96
+ }
97
+ get activeOperationId() {
98
+ return this._activeOperationId;
99
+ }
100
+ /**
101
+ * 新しい要求の到着。arrival policy を適用し ticket + 最初の attempt を発行する。
102
+ * exhaust で実行中の場合だけ null を返す (新要求を ticket 化せず拒否 = 冪等 no-op)。
103
+ */
104
+ begin() {
105
+ let supersedeEpoch;
106
+ switch (this.policy) {
107
+ case "latest": {
108
+ // latestEpoch を進め、旧 active を abort (可能なら)。旧 ticket は settle 時に
109
+ // eligibility 不一致で stale となる。
110
+ supersedeEpoch = ++this._latestEpoch;
111
+ if (this._activeOperationId !== undefined) {
112
+ this._abortController(this._activeOperationId);
113
+ }
114
+ break;
115
+ }
116
+ case "exhaust": {
117
+ // 実行中なら新要求を拒否 (呼び出し側は既存結果へ合流)。
118
+ if (this._activeOperationId !== undefined) {
119
+ return null;
120
+ }
121
+ break;
122
+ }
123
+ }
124
+ const operationId = this._nextOperationId++;
125
+ const ticket = {
126
+ operationId,
127
+ ownerGeneration: this._ownerGeneration,
128
+ laneKey: this.laneKey,
129
+ policy: this.policy,
130
+ supersedeEpoch,
131
+ };
132
+ switch (this.policy) {
133
+ case "latest":
134
+ case "exhaust":
135
+ this._activeOperationId = operationId;
136
+ break;
137
+ case "queue":
138
+ this._queue.push(ticket);
139
+ // 先頭だけを active にする (先行が完了するまで待つ)。
140
+ if (this._activeOperationId === undefined) {
141
+ this._activeOperationId = operationId;
142
+ }
143
+ break;
144
+ case "overlap":
145
+ this._activeOperationIds.add(operationId);
146
+ break;
147
+ }
148
+ this._inFlightCount += 1;
149
+ this._attempts.set(operationId, 1);
150
+ const attempt = this._makeAttempt(operationId, 1);
151
+ if (this._trace !== undefined) {
152
+ this._trace({ type: "io:operation-started", operationId, laneKey: this.laneKey, policy: this.policy });
153
+ }
154
+ return { ticket, attempt };
155
+ }
156
+ /**
157
+ * retry: 同じ operationId に新しい attempt を作る。attempt number と resource signal
158
+ * だけを更新する (§5)。既に終端した operation には作れない (null)。
159
+ */
160
+ retry(ticket) {
161
+ if (ticket.ownerGeneration !== this._ownerGeneration)
162
+ return null;
163
+ if (this._terminal.has(ticket.operationId))
164
+ return null;
165
+ const previous = this._attempts.get(ticket.operationId);
166
+ if (previous === undefined)
167
+ return null;
168
+ const attemptNo = previous + 1;
169
+ this._attempts.set(ticket.operationId, attemptNo);
170
+ // 前の attempt の signal は破棄し、新しい controller を張る。
171
+ this._releaseController(ticket.operationId);
172
+ const attempt = this._makeAttempt(ticket.operationId, attemptNo);
173
+ if (this._trace !== undefined) {
174
+ this._trace({ type: "io:operation-retried", operationId: ticket.operationId, laneKey: this.laneKey, attempt: attemptNo });
175
+ }
176
+ return attempt;
177
+ }
178
+ /**
179
+ * CommitGuard (§5.1)。外部可視の setter / event dispatch の直前に呼ぶ。
180
+ * (1) owner lifecycle generation 一致 (2) terminal settle 前 (3) policy eligibility。
181
+ */
182
+ canCommit(ticket) {
183
+ if (ticket.ownerGeneration !== this._ownerGeneration)
184
+ return false;
185
+ const status = this._terminal.get(ticket.operationId);
186
+ // absence = pending / 'committing' = multi-setter commit 中。どちらも settle 前。
187
+ if (status !== undefined && status !== "committing")
188
+ return false;
189
+ return this._isEligible(ticket);
190
+ }
191
+ /**
192
+ * terminal CAS (§5.1): pending → committing を claim する。勝者だけが true。
193
+ * eligibility / owner gen を満たさない場合も false。claim 後は commit 中となり、
194
+ * canCommit は各 setter の直前で再検査する (setter が同期 supersede しても取りこぼさない)。
195
+ */
196
+ claimTerminal(ticket, outcome) {
197
+ if (ticket.ownerGeneration !== this._ownerGeneration)
198
+ return false;
199
+ if (this._terminal.has(ticket.operationId))
200
+ return false; // 既に committing / 終端
201
+ if (!this._isEligible(ticket))
202
+ return false;
203
+ this._terminal.set(ticket.operationId, "committing");
204
+ this._claimedOutcome.set(ticket.operationId, outcome);
205
+ return true;
206
+ }
207
+ /** claim 済み outcome (timer が claim → catch が読む等)。未 claim なら undefined。 */
208
+ claimedOutcome(ticket) {
209
+ return this._claimedOutcome.get(ticket.operationId);
210
+ }
211
+ /**
212
+ * operation の後始末。claim 済みなら outcome を確定し、未 claim なら stale-drop。
213
+ * controller を解放し in-flight を減らし、policy の bookkeeping を進める。冪等。
214
+ */
215
+ finalize(ticket) {
216
+ const operationId = ticket.operationId;
217
+ const status = this._terminal.get(operationId);
218
+ if (status !== undefined && status !== "committing") {
219
+ // 既に確定済み。冪等に return。
220
+ return;
221
+ }
222
+ let outcome;
223
+ if (status === "committing") {
224
+ outcome = this._claimedOutcome.get(operationId) ?? "stale";
225
+ }
226
+ else {
227
+ // 一度も claim されなかった (supersede / dispose で eligibility を失った)。
228
+ outcome = "stale";
229
+ }
230
+ this._terminal.set(operationId, outcome);
231
+ this._claimedOutcome.delete(operationId);
232
+ this._releaseController(operationId);
233
+ this._attempts.delete(operationId);
234
+ if (this._inFlightCount > 0)
235
+ this._inFlightCount -= 1;
236
+ this._advanceBookkeeping(operationId);
237
+ if (this._trace !== undefined) {
238
+ if (outcome === "stale") {
239
+ this._trace({ type: "io:stale-dropped", operationId, laneKey: this.laneKey });
240
+ }
241
+ else {
242
+ this._trace({ type: "io:operation-settled", operationId, laneKey: this.laneKey, outcome });
243
+ }
244
+ }
245
+ }
246
+ /** operation の signal (resource 解放用)。withSignal でなければ undefined。 */
247
+ signalOf(ticket) {
248
+ return this._controllers.get(ticket.operationId)?.signal;
249
+ }
250
+ /** best-effort な resource 中断。正しさは owner gen / eligibility / terminal CAS が担う。 */
251
+ abort(ticket) {
252
+ this._abortController(ticket.operationId);
253
+ }
254
+ /**
255
+ * 現在 active な operation を中断する (利用者による明示キャンセル)。epoch は進めない —
256
+ * 中断された operation は eligibility を保ったまま 'aborted' を claim できる
257
+ * (loading をクリアしつつ in-flight 状態を残す)。
258
+ */
259
+ abortActive() {
260
+ if (this._activeOperationId !== undefined) {
261
+ this._abortController(this._activeOperationId);
262
+ }
263
+ for (const operationId of this._activeOperationIds) {
264
+ this._abortController(operationId);
265
+ }
266
+ }
267
+ /**
268
+ * dispose (§4.1 world generation)。owner generation を bump して全 ticket を無効化し、
269
+ * 生きている controller を全て abort する。dispose 後に settle した operation は
270
+ * owner gen 不一致で外部 commit しない。retention gate (§10.3) のため live な
271
+ * 全 operation を即時に stale として finalize し、controller / attempt を解放する。
272
+ */
273
+ disposeOwner() {
274
+ this._ownerGeneration += 1;
275
+ for (const operationId of Array.from(this._controllers.keys())) {
276
+ this._abortController(operationId);
277
+ // finalize は dispose 後 (terminal='stale') に early-return するため controller を
278
+ // 解放しない。retention gate (§10.3) を満たすためここで明示的に解放する。
279
+ this._releaseController(operationId);
280
+ }
281
+ for (const operationId of Array.from(this._attempts.keys())) {
282
+ if (!this._terminal.has(operationId)) {
283
+ this._terminal.set(operationId, "stale");
284
+ }
285
+ this._claimedOutcome.delete(operationId);
286
+ this._attempts.delete(operationId);
287
+ if (this._trace !== undefined) {
288
+ this._trace({ type: "io:stale-dropped", operationId, laneKey: this.laneKey });
289
+ }
290
+ }
291
+ this._activeOperationId = undefined;
292
+ this._activeOperationIds.clear();
293
+ this._queue.length = 0;
294
+ this._inFlightCount = 0;
295
+ }
296
+ // --- internal ---
297
+ _makeAttempt(operationId, attemptNo) {
298
+ let signal;
299
+ // AbortController 不在環境(古い runtime / 一部 SSR)では degraded: signal なしで進む。
300
+ // 正しさは owner generation / eligibility / terminal CAS が担うため、native 中断が
301
+ // 無くても supersede / dispose は機能する(best-effort resource 中断が省かれるだけ)。
302
+ if (this._withSignal && typeof AbortController === "function") {
303
+ const controller = new AbortController();
304
+ this._controllers.set(operationId, controller);
305
+ signal = controller.signal;
306
+ }
307
+ return { operationId, attempt: attemptNo, signal };
308
+ }
309
+ _isEligible(ticket) {
310
+ switch (this.policy) {
311
+ case "latest":
312
+ return ticket.supersedeEpoch === this._latestEpoch;
313
+ case "queue":
314
+ case "exhaust":
315
+ return this._activeOperationId === ticket.operationId;
316
+ case "overlap":
317
+ return this._activeOperationIds.has(ticket.operationId);
318
+ }
319
+ }
320
+ _advanceBookkeeping(operationId) {
321
+ switch (this.policy) {
322
+ case "latest":
323
+ case "exhaust":
324
+ if (this._activeOperationId === operationId) {
325
+ this._activeOperationId = undefined;
326
+ }
327
+ break;
328
+ case "queue": {
329
+ // 完了した ticket を FIFO から取り除き、次の先頭を active にする。filter で
330
+ // 「先頭 / 非先頭 / 不在」を一様に扱う (finalize は冪等ガードを通った op のみ到達)。
331
+ const remaining = this._queue.filter((t) => t.operationId !== operationId);
332
+ this._queue.length = 0;
333
+ this._queue.push(...remaining);
334
+ this._activeOperationId = this._queue.length > 0 ? this._queue[0].operationId : undefined;
335
+ break;
336
+ }
337
+ case "overlap":
338
+ this._activeOperationIds.delete(operationId);
339
+ break;
340
+ }
341
+ }
342
+ _abortController(operationId) {
343
+ const controller = this._controllers.get(operationId);
344
+ if (controller !== undefined && !controller.signal.aborted) {
345
+ controller.abort();
346
+ }
347
+ }
348
+ _releaseController(operationId) {
349
+ this._controllers.delete(operationId);
350
+ }
351
+ }
352
+
353
+ // ===========================================================================
354
+ // AUTO-GENERATED FILE - DO NOT EDIT.
355
+ // Generated from /io-core/platform-capability.ts by scripts/sync-io-core.mjs.
356
+ // Run `node scripts/sync-io-core.mjs` after editing the source.
357
+ // ===========================================================================
358
+ function isSecureContext() {
359
+ return globalThis.isSecureContext === true;
360
+ }
361
+ /**
362
+ * capability を利用直前に評価して PlatformAssessment を作る。
363
+ * required が 1 つでも欠ければ readiness は "idle"(開始不可)、
364
+ * required 揃い + optional 欠けは "degraded"、全揃いは "ready"。
365
+ */
366
+ function assessCapabilities(registry, options) {
367
+ const availability = new Map();
368
+ const evaluate = (id) => {
369
+ const spec = registry.get(id);
370
+ if (spec === undefined)
371
+ return "unknown";
372
+ return spec.probe() ? "available" : "missing";
373
+ };
374
+ let requiredAllAvailable = true;
375
+ for (const id of options.required) {
376
+ const a = evaluate(id);
377
+ availability.set(id, a);
378
+ if (a !== "available")
379
+ requiredAllAvailable = false;
380
+ }
381
+ let optionalAllAvailable = true;
382
+ for (const id of options.optional ?? []) {
383
+ const a = evaluate(id);
384
+ availability.set(id, a);
385
+ if (a !== "available")
386
+ optionalAllAvailable = false;
387
+ }
388
+ const readiness = !requiredAllAvailable ? "idle" : (optionalAllAvailable ? "ready" : "degraded");
389
+ // preconditions: 対象 capability のいずれかが要求する場合だけ評価する。
390
+ const allIds = [...options.required, ...(options.optional ?? [])];
391
+ const needsSecure = allIds.some((id) => registry.get(id)?.requiresSecureContext === true);
392
+ const needsActivation = allIds.some((id) => registry.get(id)?.requiresUserActivation === true);
393
+ const secureContext = needsSecure ? (isSecureContext() ? "satisfied" : "required") : "not-applicable";
394
+ const userActivation = needsActivation ? "required" : "not-applicable";
395
+ return {
396
+ availability,
397
+ permission: options.permission ?? "not-applicable",
398
+ readiness,
399
+ activity: options.activity ?? "inactive",
400
+ preconditions: { secureContext, userActivation },
401
+ epoch: options.epoch ?? 0,
402
+ lastError: options.lastError,
403
+ };
404
+ }
405
+ /** availability から「required がすべて available か」を判定するヘルパ(supported の最低条件)。 */
406
+ function requiredCapabilitiesAvailable(assessment, required) {
407
+ return required.every((id) => assessment.availability.get(id) === "available");
408
+ }
409
+
410
+ /**
411
+ * fetchCapabilities.ts
412
+ *
413
+ * fetch node 固有の capability registry と error code。汎用の assess 機構・型は
414
+ * `./platformCapability.js`(/io-core/ から copy-distribution される生成ファイル)から
415
+ * import する。node 固有の宣言はこのハンドライトファイルに置き、生成コピーとは分離する。
416
+ */
417
+ /** 安定した fetch error code(taxonomy)。値は公開キーとして固定。 */
418
+ const WCS_FETCH_ERROR_CODE = {
419
+ CapabilityMissing: "capability-missing",
420
+ InvalidArgument: "invalid-argument",
421
+ Network: "network",
422
+ HttpError: "http-error",
423
+ Timeout: "timeout",
424
+ Aborted: "aborted",
425
+ };
426
+ /** fetch node の capability registry。文字列 ID を eval せず明示 probe を持つ。 */
427
+ const FETCH_CAPABILITIES = new Map([
428
+ ["web.fetch", { probe: () => typeof globalThis.fetch === "function", compatKey: "api.fetch" }],
429
+ ["web.abort-controller", { probe: () => typeof globalThis.AbortController === "function", compatKey: "api.AbortController" }],
430
+ ]);
431
+
50
432
  class FetchCore extends EventTarget {
51
433
  static wcBindable = {
52
434
  protocol: "wc-bindable",
@@ -60,6 +442,11 @@ class FetchCore extends EventTarget {
60
442
  // The Core revokes the previous URL on each new response and on dispose, so
61
443
  // a consumer can bind it straight into <img src> without lifecycle glue.
62
444
  { name: "objectURL", event: "wcs-fetch:response", getter: (e) => e.detail.objectURL },
445
+ // Serializable failure taxonomy (stable code / phase / recoverable), or null.
446
+ // Additive bindable output — the existing `error` property/event are unchanged.
447
+ // Fires on its own `wcs-fetch:error-info-changed` event; no getter, so the
448
+ // bound value is the event detail (mirrors `error` / `loading`).
449
+ { name: "errorInfo", event: "wcs-fetch:error-info-changed" },
63
450
  ],
64
451
  inputs: [
65
452
  { name: "url" },
@@ -76,15 +463,28 @@ class FetchCore extends EventTarget {
76
463
  _error = null;
77
464
  _status = 0;
78
465
  _objectURL = null;
79
- _abortController = null;
80
466
  _promise = Promise.resolve(null);
81
- // Generation guard (§3.4): bumped on dispose() (and each fetch start). An
82
- // in-flight request that settles after dispose / a superseding start has a
83
- // stale `gen` and MUST NOT write state to a torn-down element. A boolean flag
84
- // is insufficient (dispose→observe would let stale work slip through).
85
- _gen = 0;
467
+ // Phase 4 (09-remediation-design.md §5): the request lane. `latest` policy —
468
+ // a new fetch supersedes the in-flight one (switchMap). The lane owns the
469
+ // per-operation AbortController, the owner generation (dispose lifecycle) and
470
+ // the terminal CAS / CommitGuard that decide which completion may write state.
471
+ // This replaces the ad-hoc `_gen` counter + single `_abortController`: a
472
+ // superseded operation now fails the CommitGuard's epoch check instead of
473
+ // relying on a coarse generation recheck, closing the "completion racing an
474
+ // abort commits stale state" gap during body reads.
475
+ _lane = new OperationLane("fetch", "latest", { withSignal: true });
86
476
  // SSR (§3.8): no asynchronous probe to await, so readiness is immediate.
87
477
  _ready = Promise.resolve();
478
+ // Phase 6 (§7.2): error taxonomy. The existing `error` property/event shape is
479
+ // unchanged; `errorInfo` projects the serializable WcsIoErrorInfo as an additive
480
+ // wc-bindable output (event `wcs-fetch:error-info-changed`) so DevTools / adopters
481
+ // can classify failures without a breaking change.
482
+ _errorInfo = null;
483
+ // Capability IDs (probed at call time, never at module eval / never eval'd as a
484
+ // global path). `web.fetch` required; `web.abort-controller` optional (its
485
+ // absence degrades to a fetch without an abort signal).
486
+ static REQUIRED_CAPABILITIES = ["web.fetch"];
487
+ static OPTIONAL_CAPABILITIES = ["web.abort-controller"];
88
488
  constructor(target) {
89
489
  super();
90
490
  this._target = target ?? this;
@@ -99,8 +499,8 @@ class FetchCore extends EventTarget {
99
499
  return this._ready;
100
500
  }
101
501
  dispose() {
102
- this._gen++;
103
- this.abort();
502
+ // world generation bump (§4.1): invalidates + aborts every in-flight request.
503
+ this._lane.disposeOwner();
104
504
  // Release any outstanding blob object URL on teardown (the other revoke point
105
505
  // is _setResponse, which drops the previous URL when a new response arrives).
106
506
  if (this._objectURL !== null) {
@@ -126,6 +526,52 @@ class FetchCore extends EventTarget {
126
526
  get promise() {
127
527
  return this._promise;
128
528
  }
529
+ /**
530
+ * The last failure's serializable `WcsIoErrorInfo` (stable `code` / `phase` /
531
+ * `recoverable` / `capabilityId`), or null. Exposed as an additive wc-bindable
532
+ * property (event `wcs-fetch:error-info-changed`); the existing `error`
533
+ * property/event are unchanged.
534
+ */
535
+ get errorInfo() {
536
+ return this._errorInfo;
537
+ }
538
+ /**
539
+ * Whether the required platform capabilities (`web.fetch`) are available right
540
+ * now — the minimal "supported" signal, decided by call-time feature detection,
541
+ * not User-Agent. Additive.
542
+ */
543
+ get supported() {
544
+ return requiredCapabilitiesAvailable(this.platformAssessment, FetchCore.REQUIRED_CAPABILITIES);
545
+ }
546
+ /**
547
+ * Full platform assessment (availability / readiness / preconditions), probed
548
+ * at call time. `readiness` is `degraded` when only the optional
549
+ * `web.abort-controller` is missing. Dev / sidecar view.
550
+ */
551
+ get platformAssessment() {
552
+ return assessCapabilities(FETCH_CAPABILITIES, {
553
+ required: FetchCore.REQUIRED_CAPABILITIES,
554
+ optional: FetchCore.OPTIONAL_CAPABILITIES,
555
+ activity: this._loading ? "active" : "inactive",
556
+ lastError: this._errorInfo ?? undefined,
557
+ });
558
+ }
559
+ _setErrorInfo(code, phase, recoverable, message, capabilityId) {
560
+ this._commitErrorInfo({ code, phase, recoverable, message, ...(capabilityId === undefined ? {} : { capabilityId }) });
561
+ }
562
+ // Single mutation point for `errorInfo`, mirroring `_setError`'s same-value guard
563
+ // and event dispatch so the additive `errorInfo` wc-bindable property stays in sync
564
+ // with `error`. Each failure builds a fresh object (reference guard passes); the
565
+ // clear path passes null (suppresses a redundant null→null per successful fetch).
566
+ _commitErrorInfo(info) {
567
+ if (this._errorInfo === info)
568
+ return;
569
+ this._errorInfo = info;
570
+ this._target.dispatchEvent(new CustomEvent("wcs-fetch:error-info-changed", {
571
+ detail: info,
572
+ bubbles: true,
573
+ }));
574
+ }
129
575
  _setLoading(loading) {
130
576
  this._loading = loading;
131
577
  this._target.dispatchEvent(new CustomEvent("wcs-fetch:loading-changed", {
@@ -179,9 +625,20 @@ class FetchCore extends EventTarget {
179
625
  }
180
626
  }
181
627
  abort() {
182
- if (this._abortController) {
183
- this._abortController.abort();
184
- this._abortController = null;
628
+ // Explicit user cancel: abort the active operation WITHOUT advancing the lane
629
+ // epoch, so the aborted operation stays eligible and its AbortError branch may
630
+ // commit loading=false (leaving the in-flight value/status). A superseding
631
+ // fetch() instead advances the epoch (via the lane's begin()), which makes the
632
+ // predecessor ineligible so its abort commits nothing (loading does not flicker).
633
+ this._lane.abortActive();
634
+ }
635
+ // Run one guarded commit step (§5.1). The CommitGuard is re-checked before every
636
+ // setter because a setter that synchronously dispatches an event can supersede
637
+ // the same lane; an invalidation between setters stops the remaining commits
638
+ // without rolling back what already fired.
639
+ _commitStep(ticket, step) {
640
+ if (this._lane.canCommit(ticket)) {
641
+ step();
185
642
  }
186
643
  }
187
644
  async fetch(url, options = {}) {
@@ -189,30 +646,60 @@ class FetchCore extends EventTarget {
189
646
  // 流し、サニタイズ値(null)を返す。command-token 経路からの呼び出しが unhandled
190
647
  // rejection にならず、「fetch() は全終了ケースで resolve」契約とも整合する。
191
648
  if (!url) {
649
+ // Existing `error` shape is unchanged (§7.2 / 07 §互換性); the taxonomy is
650
+ // projected only through the additive `errorInfo`.
651
+ this._setErrorInfo(WCS_FETCH_ERROR_CODE.InvalidArgument, "start", false, "url attribute is required.");
192
652
  this._setError({ message: "url attribute is required." });
193
653
  return null;
194
654
  }
655
+ // Phase 6 (§7.2): probe required capabilities just before starting. If the
656
+ // `web.fetch` API is absent (SSR / headless / very old runtime), do NOT start
657
+ // the operation — surface a stable `capability-missing` taxonomy without
658
+ // attempting the call (and without the generic network-error path).
659
+ const assessment = this.platformAssessment;
660
+ if (!requiredCapabilitiesAvailable(assessment, FetchCore.REQUIRED_CAPABILITIES)) {
661
+ const missing = FetchCore.REQUIRED_CAPABILITIES.find((id) => assessment.availability.get(id) !== "available");
662
+ this._setErrorInfo(WCS_FETCH_ERROR_CODE.CapabilityMissing, "start", false, `Required capability "${missing}" is unavailable.`, missing);
663
+ this._setError({ message: `Required capability "${missing}" is unavailable.` });
664
+ return null;
665
+ }
195
666
  const p = this._doFetch(url, options);
196
667
  this._promise = p;
197
668
  return p;
198
669
  }
199
670
  async _doFetch(url, options) {
200
- // 進行中のリクエストをキャンセル
201
- this.abort();
202
- // Hold the controller in a local so the finally block (which can run after a
203
- // subsequent fetch has already replaced this._abortController) only clears the
204
- // field when it still owns it. Without the identity check, an aborted earlier
205
- // request's finally would null out the controller of the request that superseded
206
- // it, leaving the later request un-abortable.
207
- const ac = new AbortController();
208
- this._abortController = ac;
209
- const { signal } = ac;
210
- // Capture the generation at async start (§3.4). A completion that runs after
211
- // dispose() (which bumps _gen) is stale and must not write state.
212
- const gen = ++this._gen;
213
- this._setLoading(true);
214
- this._setError(null);
215
- const { method = "GET", body = null, contentType = null, forceText = false, responseType = "auto", } = options;
671
+ // Issue a lane ticket. For the `latest` policy this advances the epoch and
672
+ // aborts the previous in-flight request (supersede), returning a ticket +
673
+ // attempt whose `signal` is the lane-owned AbortController for this operation.
674
+ // `attempt.signal` is undefined when `web.abort-controller` is missing
675
+ // (degraded): the request runs without a native abort signal.
676
+ const started = this._lane.begin();
677
+ // `latest` begin never returns null (exhaust is the only rejecting policy).
678
+ const { ticket, attempt } = started;
679
+ const signal = attempt.signal;
680
+ this._commitStep(ticket, () => this._setLoading(true));
681
+ this._commitStep(ticket, () => { this._commitErrorInfo(null); this._setError(null); });
682
+ const { method = "GET", body = null, contentType = null, forceText = false, responseType = "auto", timeout = 0, } = options;
683
+ // Timeout terminal (§5.1 / §7): a timer claims the `timeout` outcome via the
684
+ // same terminal CAS as success/error, commits a guarded TimeoutError, THEN
685
+ // aborts the native request and releases the lane — never "invalidate first".
686
+ // A completion that arrives after the timer loses the CAS and writes nothing.
687
+ let timeoutTimer = null;
688
+ if (timeout > 0) {
689
+ timeoutTimer = setTimeout(() => {
690
+ if (!this._lane.claimTerminal(ticket, "timeout"))
691
+ return;
692
+ const message = `Request timed out after ${timeout}ms.`;
693
+ this._commitStep(ticket, () => {
694
+ this._setErrorInfo(WCS_FETCH_ERROR_CODE.Timeout, "execute", true, message);
695
+ this._setError({ name: "TimeoutError", message });
696
+ });
697
+ this._commitStep(ticket, () => this._setResponse(null, 0));
698
+ this._commitStep(ticket, () => this._setLoading(false));
699
+ this._lane.abort(ticket);
700
+ this._lane.finalize(ticket);
701
+ }, timeout);
702
+ }
216
703
  // Copy the caller's headers so the contentType injection below never mutates
217
704
  // the object passed in by a headless consumer (the Shell already builds a
218
705
  // fresh object, but direct FetchCore users may reuse theirs).
@@ -230,97 +717,121 @@ class FetchCore extends EventTarget {
230
717
  requestInit.body = body;
231
718
  }
232
719
  const response = await globalThis.fetch(url, requestInit);
233
- // A stale generation means dispose() (or a superseding fetch) ran while the
234
- // request was in flight. Drop the result without touching torn-down state.
235
- if (gen !== this._gen) {
236
- return null;
237
- }
238
- if (!response.ok) {
239
- const errorBody = await response.text().catch(() => "");
240
- const error = { status: response.status, statusText: response.statusText, body: errorBody };
241
- this._setError(error);
242
- // Notify `status` observers on HTTP errors too. The `status` property is
243
- // surfaced via the `wcs-fetch:response` event (getter reads detail.status),
244
- // so without dispatching it here a bind() subscriber would never see the
245
- // error status (404, 500, ...). `value` is reset to null on error.
246
- this._setResponse(null, response.status);
247
- this._setLoading(false);
248
- return null;
249
- }
720
+ // Read the body first, then atomically claim the terminal at the commit
721
+ // point. Claiming AFTER the body read closes the stale-write race: a fetch
722
+ // that was superseded (or timed out) during the body read fails the
723
+ // CommitGuard's epoch/CAS check and writes nothing, even if the body still
724
+ // resolved. HEAD carries no body by spec.
725
+ let value = null;
250
726
  if (method === "HEAD") {
251
- // HEAD responses carry no body by spec. Reading it as JSON would throw a
252
- // parse error on the empty body (and end up as a spurious `error`), so skip
253
- // body reading entirely and surface only the status with a null value.
254
- this._setResponse(null, response.status);
727
+ // HEAD responses carry no body — reading it would throw a parse error.
728
+ }
729
+ else if (!response.ok) {
730
+ // HTTP error: read the body text for the error envelope. Handled below.
255
731
  }
256
732
  else if (forceText) {
257
733
  // HTML-replace mode (the Shell sets forceText when `target` is present)
258
734
  // always reads text and takes priority over responseType.
259
- const text = await response.text();
260
- this._setResponse(text, response.status);
735
+ value = await response.text();
261
736
  }
262
737
  else if (responseType === "blob") {
263
- const blob = await response.blob();
264
- // Publish a managed object URL alongside the Blob so consumers can bind it
265
- // directly into <img src> etc.
266
- this._setResponse(blob, response.status, this._createObjectURL(blob));
738
+ // Only buffer the Blob here; the managed object URL is created AFTER the
739
+ // terminal claim wins (below). Creating it before the claim would leak a
740
+ // blob: URL when this operation loses the claim (supersede / timeout /
741
+ // dispose during the body read) — it would never reach _setResponse and
742
+ // never be revoked.
743
+ value = await response.blob();
267
744
  }
268
745
  else if (responseType === "arrayBuffer") {
269
- const buffer = await response.arrayBuffer();
270
- this._setResponse(buffer, response.status);
746
+ value = await response.arrayBuffer();
271
747
  }
272
748
  else if (responseType === "text") {
273
- const text = await response.text();
274
- this._setResponse(text, response.status);
749
+ value = await response.text();
275
750
  }
276
751
  else if (responseType === "json") {
277
- const data = await response.json();
278
- this._setResponse(data, response.status);
752
+ value = await response.json();
279
753
  }
280
754
  else {
281
755
  // "auto" (default): sniff Content-Type — JSON when it says so, else text.
282
756
  const responseContentType = response.headers.get("Content-Type") || "";
283
757
  if (responseContentType.includes("application/json")) {
284
- const data = await response.json();
285
- this._setResponse(data, response.status);
758
+ value = await response.json();
286
759
  }
287
760
  else {
288
- const text = await response.text();
289
- this._setResponse(text, response.status);
761
+ value = await response.text();
290
762
  }
291
763
  }
292
- this._setLoading(false);
764
+ if (!response.ok) {
765
+ const errorBody = await response.text().catch(() => "");
766
+ const error = { status: response.status, statusText: response.statusText, body: errorBody };
767
+ if (!this._lane.claimTerminal(ticket, "error")) {
768
+ return null;
769
+ }
770
+ this._commitStep(ticket, () => {
771
+ this._setErrorInfo(WCS_FETCH_ERROR_CODE.HttpError, "execute", true, `HTTP ${response.status} ${response.statusText}`);
772
+ this._setError(error);
773
+ });
774
+ // Notify `status` observers on HTTP errors too. The `status` property is
775
+ // surfaced via the `wcs-fetch:response` event (getter reads detail.status),
776
+ // so without dispatching it here a bind() subscriber would never see the
777
+ // error status (404, 500, ...). `value` is reset to null on error.
778
+ this._commitStep(ticket, () => this._setResponse(null, response.status));
779
+ this._commitStep(ticket, () => this._setLoading(false));
780
+ return null;
781
+ }
782
+ if (!this._lane.claimTerminal(ticket, "success")) {
783
+ return null;
784
+ }
785
+ // Create the blob object URL only now that this operation owns the terminal,
786
+ // so a dropped operation never allocates one (leak-free). HEAD/non-blob keep
787
+ // value non-Blob → objectURL stays null.
788
+ const objectURL = value instanceof Blob ? this._createObjectURL(value) : null;
789
+ this._commitStep(ticket, () => this._setResponse(value, response.status, objectURL));
790
+ this._commitStep(ticket, () => this._setLoading(false));
293
791
  return this._value;
294
792
  }
295
793
  catch (e) {
296
- // Stale completion (dispose / superseding fetch ran during a later await
297
- // such as response.json()). Drop the result without writing state.
298
- if (gen !== this._gen) {
794
+ if (e && e.name === "AbortError") {
795
+ // AbortError with a still-eligible ticket is an explicit user abort() of
796
+ // the current request: claim the `aborted` terminal and clear loading,
797
+ // leaving the in-flight value/status untouched. A superseding fetch or
798
+ // dispose() advanced the epoch / owner generation, so their predecessors
799
+ // fail the claim (return without writing = stale-drop). A timeout already
800
+ // claimed the terminal in its timer, so this branch also no-ops there.
801
+ if (this._lane.claimTerminal(ticket, "aborted")) {
802
+ this._commitStep(ticket, () => this._setLoading(false));
803
+ }
299
804
  return null;
300
805
  }
301
- if (e.name === "AbortError") {
302
- // A matching generation means this is an explicit abort() of the current
303
- // request (a superseding fetch bumps _gen and is caught by the stale guard
304
- // above; dispose() likewise bumps _gen). Explicit abort clears loading so
305
- // observers leave the in-flight state.
306
- this._setLoading(false);
806
+ // Network error. A superseded/disposed request fails the claim and drops.
807
+ if (!this._lane.claimTerminal(ticket, "error")) {
307
808
  return null;
308
809
  }
309
- this._setError(e);
310
- // Reset value/status on network errors too, mirroring the HTTP-error path
311
- // (`_setResponse(null, response.status)`). Without this, a prior successful
312
- // request's value/status would linger while `error` is non-null, showing
313
- // observers an inconsistent state (e.g. status=200 alongside a network
314
- // error). status=0 is the web-platform convention for "no HTTP response"
315
- // (matches XMLHttpRequest.status on network failure) and the initial value.
316
- this._setResponse(null, 0);
317
- this._setLoading(false);
810
+ this._commitStep(ticket, () => {
811
+ const message = String(e?.message ?? "Network request failed.");
812
+ this._setErrorInfo(WCS_FETCH_ERROR_CODE.Network, "execute", true, message);
813
+ // Coalesce a falsy rejection (Promise.reject(null)/throw null) to a non-null
814
+ // envelope so the `error` same-value guard (cleared to null at start) cannot
815
+ // suppress a genuine terminal error — keeping `error`/`wcs-fetch:error` in sync
816
+ // with `errorInfo`. Truthy errors (real TypeErrors) pass through unchanged.
817
+ this._setError(e ?? { message });
818
+ });
819
+ // Reset value/status on network errors too, mirroring the HTTP-error path.
820
+ // Without this, a prior successful request's value/status would linger while
821
+ // `error` is non-null. status=0 is the web-platform convention for "no HTTP
822
+ // response" (matches XMLHttpRequest.status on network failure).
823
+ this._commitStep(ticket, () => this._setResponse(null, 0));
824
+ this._commitStep(ticket, () => this._setLoading(false));
318
825
  return null;
319
826
  }
320
827
  finally {
321
- if (this._abortController === ac) {
322
- this._abortController = null;
828
+ if (timeoutTimer !== null) {
829
+ clearTimeout(timeoutTimer);
323
830
  }
831
+ // Release the operation (identity-safe: keyed by operationId, so a
832
+ // late-settling superseded request never disarms the successor). Idempotent
833
+ // with the timeout timer's own finalize().
834
+ this._lane.finalize(ticket);
324
835
  }
325
836
  }
326
837
  }
@@ -528,6 +1039,9 @@ class Fetch extends HTMLElement {
528
1039
  get objectURL() {
529
1040
  return this._core.objectURL;
530
1041
  }
1042
+ get errorInfo() {
1043
+ return this._core.errorInfo;
1044
+ }
531
1045
  get promise() {
532
1046
  return this._core.promise;
533
1047
  }
@@ -928,5 +1442,5 @@ function bootstrapFetch(userConfig) {
928
1442
  registerComponents();
929
1443
  }
930
1444
 
931
- export { FetchCore, Fetch as WcsFetch, InfiniteScroll as WcsInfiniteScroll, bootstrapFetch, getConfig };
1445
+ export { FetchCore, WCS_FETCH_ERROR_CODE, Fetch as WcsFetch, InfiniteScroll as WcsInfiniteScroll, bootstrapFetch, getConfig };
932
1446
  //# sourceMappingURL=index.esm.js.map