@wcstack/eyedropper 1.20.0 → 1.21.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/dist/index.esm.js CHANGED
@@ -43,28 +43,399 @@ function setConfig(partialConfig) {
43
43
  frozenConfig = null;
44
44
  }
45
45
 
46
+ // ===========================================================================
47
+ // AUTO-GENERATED FILE - DO NOT EDIT.
48
+ // Generated from /io-core/operation-lane.ts by scripts/sync-io-core.mjs.
49
+ // Run `node scripts/sync-io-core.mjs` after editing the source.
50
+ // ===========================================================================
51
+ /**
52
+ * 1 レーン = 独立した排他単位。Core が 1 つ以上所有する (module singleton にしない —
53
+ * 複数 <wcs-fetch> 間で漏れるため)。
54
+ */
55
+ class OperationLane {
56
+ laneKey;
57
+ policy;
58
+ _ownerGeneration = 0;
59
+ _latestEpoch = 0;
60
+ _nextOperationId = 1;
61
+ // latest / queue / exhaust の単一 active。queue は head を指す。
62
+ _activeOperationId = undefined;
63
+ // overlap の active set (§5: 内部 bookkeeping のみ・observable 公開はしない)。
64
+ _activeOperationIds = new Set();
65
+ // queue policy の FIFO。
66
+ _queue = [];
67
+ _inFlightCount = 0;
68
+ // opId → 終端状態 (absence = pending)。
69
+ _terminal = new Map();
70
+ // claimTerminal で確定した outcome (finalize が 'committing' を最終値へ移す)。
71
+ _claimedOutcome = new Map();
72
+ // opId → AbortController (identity は opId が保証。cross-op clobber は構造上起きない)。
73
+ _controllers = new Map();
74
+ // opId → attempt 数。
75
+ _attempts = new Map();
76
+ _withSignal;
77
+ _trace;
78
+ constructor(laneKey, policy, options = {}) {
79
+ this.laneKey = laneKey;
80
+ this.policy = policy;
81
+ this._withSignal = options.withSignal ?? false;
82
+ this._trace = options.trace;
83
+ }
84
+ get ownerGeneration() {
85
+ return this._ownerGeneration;
86
+ }
87
+ get inFlightCount() {
88
+ return this._inFlightCount;
89
+ }
90
+ get latestEpoch() {
91
+ return this._latestEpoch;
92
+ }
93
+ get activeOperationId() {
94
+ return this._activeOperationId;
95
+ }
96
+ /**
97
+ * 新しい要求の到着。arrival policy を適用し ticket + 最初の attempt を発行する。
98
+ * exhaust で実行中の場合だけ null を返す (新要求を ticket 化せず拒否 = 冪等 no-op)。
99
+ */
100
+ begin() {
101
+ let supersedeEpoch;
102
+ switch (this.policy) {
103
+ case "latest": {
104
+ // latestEpoch を進め、旧 active を abort (可能なら)。旧 ticket は settle 時に
105
+ // eligibility 不一致で stale となる。
106
+ supersedeEpoch = ++this._latestEpoch;
107
+ if (this._activeOperationId !== undefined) {
108
+ this._abortController(this._activeOperationId);
109
+ }
110
+ break;
111
+ }
112
+ case "exhaust": {
113
+ // 実行中なら新要求を拒否 (呼び出し側は既存結果へ合流)。
114
+ if (this._activeOperationId !== undefined) {
115
+ return null;
116
+ }
117
+ break;
118
+ }
119
+ }
120
+ const operationId = this._nextOperationId++;
121
+ const ticket = {
122
+ operationId,
123
+ ownerGeneration: this._ownerGeneration,
124
+ laneKey: this.laneKey,
125
+ policy: this.policy,
126
+ supersedeEpoch,
127
+ };
128
+ switch (this.policy) {
129
+ case "latest":
130
+ case "exhaust":
131
+ this._activeOperationId = operationId;
132
+ break;
133
+ case "queue":
134
+ this._queue.push(ticket);
135
+ // 先頭だけを active にする (先行が完了するまで待つ)。
136
+ if (this._activeOperationId === undefined) {
137
+ this._activeOperationId = operationId;
138
+ }
139
+ break;
140
+ case "overlap":
141
+ this._activeOperationIds.add(operationId);
142
+ break;
143
+ }
144
+ this._inFlightCount += 1;
145
+ this._attempts.set(operationId, 1);
146
+ const attempt = this._makeAttempt(operationId, 1);
147
+ if (this._trace !== undefined) {
148
+ this._trace({ type: "io:operation-started", operationId, laneKey: this.laneKey, policy: this.policy });
149
+ }
150
+ return { ticket, attempt };
151
+ }
152
+ /**
153
+ * retry: 同じ operationId に新しい attempt を作る。attempt number と resource signal
154
+ * だけを更新する (§5)。既に終端した operation には作れない (null)。
155
+ */
156
+ retry(ticket) {
157
+ if (ticket.ownerGeneration !== this._ownerGeneration)
158
+ return null;
159
+ if (this._terminal.has(ticket.operationId))
160
+ return null;
161
+ const previous = this._attempts.get(ticket.operationId);
162
+ if (previous === undefined)
163
+ return null;
164
+ const attemptNo = previous + 1;
165
+ this._attempts.set(ticket.operationId, attemptNo);
166
+ // 前の attempt の signal は破棄し、新しい controller を張る。
167
+ this._releaseController(ticket.operationId);
168
+ const attempt = this._makeAttempt(ticket.operationId, attemptNo);
169
+ if (this._trace !== undefined) {
170
+ this._trace({ type: "io:operation-retried", operationId: ticket.operationId, laneKey: this.laneKey, attempt: attemptNo });
171
+ }
172
+ return attempt;
173
+ }
174
+ /**
175
+ * CommitGuard (§5.1)。外部可視の setter / event dispatch の直前に呼ぶ。
176
+ * (1) owner lifecycle generation 一致 (2) terminal settle 前 (3) policy eligibility。
177
+ */
178
+ canCommit(ticket) {
179
+ if (ticket.ownerGeneration !== this._ownerGeneration)
180
+ return false;
181
+ const status = this._terminal.get(ticket.operationId);
182
+ // absence = pending / 'committing' = multi-setter commit 中。どちらも settle 前。
183
+ if (status !== undefined && status !== "committing")
184
+ return false;
185
+ return this._isEligible(ticket);
186
+ }
187
+ /**
188
+ * terminal CAS (§5.1): pending → committing を claim する。勝者だけが true。
189
+ * eligibility / owner gen を満たさない場合も false。claim 後は commit 中となり、
190
+ * canCommit は各 setter の直前で再検査する (setter が同期 supersede しても取りこぼさない)。
191
+ */
192
+ claimTerminal(ticket, outcome) {
193
+ if (ticket.ownerGeneration !== this._ownerGeneration)
194
+ return false;
195
+ if (this._terminal.has(ticket.operationId))
196
+ return false; // 既に committing / 終端
197
+ if (!this._isEligible(ticket))
198
+ return false;
199
+ this._terminal.set(ticket.operationId, "committing");
200
+ this._claimedOutcome.set(ticket.operationId, outcome);
201
+ return true;
202
+ }
203
+ /** claim 済み outcome (timer が claim → catch が読む等)。未 claim なら undefined。 */
204
+ claimedOutcome(ticket) {
205
+ return this._claimedOutcome.get(ticket.operationId);
206
+ }
207
+ /**
208
+ * operation の後始末。claim 済みなら outcome を確定し、未 claim なら stale-drop。
209
+ * controller を解放し in-flight を減らし、policy の bookkeeping を進める。冪等。
210
+ */
211
+ finalize(ticket) {
212
+ const operationId = ticket.operationId;
213
+ const status = this._terminal.get(operationId);
214
+ if (status !== undefined && status !== "committing") {
215
+ // 既に確定済み。冪等に return。
216
+ return;
217
+ }
218
+ let outcome;
219
+ if (status === "committing") {
220
+ outcome = this._claimedOutcome.get(operationId) ?? "stale";
221
+ }
222
+ else {
223
+ // 一度も claim されなかった (supersede / dispose で eligibility を失った)。
224
+ outcome = "stale";
225
+ }
226
+ this._terminal.set(operationId, outcome);
227
+ this._claimedOutcome.delete(operationId);
228
+ this._releaseController(operationId);
229
+ this._attempts.delete(operationId);
230
+ if (this._inFlightCount > 0)
231
+ this._inFlightCount -= 1;
232
+ this._advanceBookkeeping(operationId);
233
+ if (this._trace !== undefined) {
234
+ if (outcome === "stale") {
235
+ this._trace({ type: "io:stale-dropped", operationId, laneKey: this.laneKey });
236
+ }
237
+ else {
238
+ this._trace({ type: "io:operation-settled", operationId, laneKey: this.laneKey, outcome });
239
+ }
240
+ }
241
+ }
242
+ /** operation の signal (resource 解放用)。withSignal でなければ undefined。 */
243
+ signalOf(ticket) {
244
+ return this._controllers.get(ticket.operationId)?.signal;
245
+ }
246
+ /** best-effort な resource 中断。正しさは owner gen / eligibility / terminal CAS が担う。 */
247
+ abort(ticket) {
248
+ this._abortController(ticket.operationId);
249
+ }
250
+ /**
251
+ * 現在 active な operation を中断する (利用者による明示キャンセル)。epoch は進めない —
252
+ * 中断された operation は eligibility を保ったまま 'aborted' を claim できる
253
+ * (loading をクリアしつつ in-flight 状態を残す)。
254
+ */
255
+ abortActive() {
256
+ if (this._activeOperationId !== undefined) {
257
+ this._abortController(this._activeOperationId);
258
+ }
259
+ for (const operationId of this._activeOperationIds) {
260
+ this._abortController(operationId);
261
+ }
262
+ }
263
+ /**
264
+ * dispose (§4.1 world generation)。owner generation を bump して全 ticket を無効化し、
265
+ * 生きている controller を全て abort する。dispose 後に settle した operation は
266
+ * owner gen 不一致で外部 commit しない。retention gate (§10.3) のため live な
267
+ * 全 operation を即時に stale として finalize し、controller / attempt を解放する。
268
+ */
269
+ disposeOwner() {
270
+ this._ownerGeneration += 1;
271
+ for (const operationId of Array.from(this._controllers.keys())) {
272
+ this._abortController(operationId);
273
+ // finalize は dispose 後 (terminal='stale') に early-return するため controller を
274
+ // 解放しない。retention gate (§10.3) を満たすためここで明示的に解放する。
275
+ this._releaseController(operationId);
276
+ }
277
+ for (const operationId of Array.from(this._attempts.keys())) {
278
+ if (!this._terminal.has(operationId)) {
279
+ this._terminal.set(operationId, "stale");
280
+ }
281
+ this._claimedOutcome.delete(operationId);
282
+ this._attempts.delete(operationId);
283
+ if (this._trace !== undefined) {
284
+ this._trace({ type: "io:stale-dropped", operationId, laneKey: this.laneKey });
285
+ }
286
+ }
287
+ this._activeOperationId = undefined;
288
+ this._activeOperationIds.clear();
289
+ this._queue.length = 0;
290
+ this._inFlightCount = 0;
291
+ }
292
+ // --- internal ---
293
+ _makeAttempt(operationId, attemptNo) {
294
+ let signal;
295
+ // AbortController 不在環境(古い runtime / 一部 SSR)では degraded: signal なしで進む。
296
+ // 正しさは owner generation / eligibility / terminal CAS が担うため、native 中断が
297
+ // 無くても supersede / dispose は機能する(best-effort resource 中断が省かれるだけ)。
298
+ if (this._withSignal && typeof AbortController === "function") {
299
+ const controller = new AbortController();
300
+ this._controllers.set(operationId, controller);
301
+ signal = controller.signal;
302
+ }
303
+ return { operationId, attempt: attemptNo, signal };
304
+ }
305
+ _isEligible(ticket) {
306
+ switch (this.policy) {
307
+ case "latest":
308
+ return ticket.supersedeEpoch === this._latestEpoch;
309
+ case "queue":
310
+ case "exhaust":
311
+ return this._activeOperationId === ticket.operationId;
312
+ case "overlap":
313
+ return this._activeOperationIds.has(ticket.operationId);
314
+ }
315
+ }
316
+ _advanceBookkeeping(operationId) {
317
+ switch (this.policy) {
318
+ case "latest":
319
+ case "exhaust":
320
+ if (this._activeOperationId === operationId) {
321
+ this._activeOperationId = undefined;
322
+ }
323
+ break;
324
+ case "queue": {
325
+ // 完了した ticket を FIFO から取り除き、次の先頭を active にする。filter で
326
+ // 「先頭 / 非先頭 / 不在」を一様に扱う (finalize は冪等ガードを通った op のみ到達)。
327
+ const remaining = this._queue.filter((t) => t.operationId !== operationId);
328
+ this._queue.length = 0;
329
+ this._queue.push(...remaining);
330
+ this._activeOperationId = this._queue.length > 0 ? this._queue[0].operationId : undefined;
331
+ break;
332
+ }
333
+ case "overlap":
334
+ this._activeOperationIds.delete(operationId);
335
+ break;
336
+ }
337
+ }
338
+ _abortController(operationId) {
339
+ const controller = this._controllers.get(operationId);
340
+ if (controller !== undefined && !controller.signal.aborted) {
341
+ controller.abort();
342
+ }
343
+ }
344
+ _releaseController(operationId) {
345
+ this._controllers.delete(operationId);
346
+ }
347
+ }
348
+
349
+ // ===========================================================================
350
+ // AUTO-GENERATED FILE - DO NOT EDIT.
351
+ // Generated from /io-core/platform-capability.ts by scripts/sync-io-core.mjs.
352
+ // Run `node scripts/sync-io-core.mjs` after editing the source.
353
+ // ===========================================================================
354
+ function isSecureContext() {
355
+ return globalThis.isSecureContext === true;
356
+ }
357
+ /**
358
+ * capability を利用直前に評価して PlatformAssessment を作る。
359
+ * required が 1 つでも欠ければ readiness は "idle"(開始不可)、
360
+ * required 揃い + optional 欠けは "degraded"、全揃いは "ready"。
361
+ */
362
+ function assessCapabilities(registry, options) {
363
+ const availability = new Map();
364
+ const evaluate = (id) => {
365
+ const spec = registry.get(id);
366
+ if (spec === undefined)
367
+ return "unknown";
368
+ return spec.probe() ? "available" : "missing";
369
+ };
370
+ let requiredAllAvailable = true;
371
+ for (const id of options.required) {
372
+ const a = evaluate(id);
373
+ availability.set(id, a);
374
+ if (a !== "available")
375
+ requiredAllAvailable = false;
376
+ }
377
+ let optionalAllAvailable = true;
378
+ for (const id of options.optional ?? []) {
379
+ const a = evaluate(id);
380
+ availability.set(id, a);
381
+ if (a !== "available")
382
+ optionalAllAvailable = false;
383
+ }
384
+ const readiness = !requiredAllAvailable ? "idle" : (optionalAllAvailable ? "ready" : "degraded");
385
+ // preconditions: 対象 capability のいずれかが要求する場合だけ評価する。
386
+ const allIds = [...options.required, ...(options.optional ?? [])];
387
+ const needsSecure = allIds.some((id) => registry.get(id)?.requiresSecureContext === true);
388
+ const needsActivation = allIds.some((id) => registry.get(id)?.requiresUserActivation === true);
389
+ const secureContext = needsSecure ? (isSecureContext() ? "satisfied" : "required") : "not-applicable";
390
+ const userActivation = needsActivation ? "required" : "not-applicable";
391
+ return {
392
+ availability,
393
+ permission: options.permission ?? "not-applicable",
394
+ readiness,
395
+ activity: options.activity ?? "inactive",
396
+ preconditions: { secureContext, userActivation },
397
+ epoch: options.epoch ?? 0,
398
+ lastError: options.lastError,
399
+ };
400
+ }
401
+ /** availability から「required がすべて available か」を判定するヘルパ(supported の最低条件)。 */
402
+ function requiredCapabilitiesAvailable(assessment, required) {
403
+ return required.every((id) => assessment.availability.get(id) === "available");
404
+ }
405
+
406
+ /**
407
+ * eyedropperCapabilities.ts
408
+ *
409
+ * EyeDropper node 固有の capability registry と error code。汎用の assess 機構・型は
410
+ * `./platformCapability.js`(/io-core/ から copy-distribution される生成ファイル)から
411
+ * import する。node 固有の宣言はこのハンドライトファイルに置き、生成コピーとは分離する。
412
+ */
413
+ /** 安定した eyedropper error code(taxonomy)。値は公開キーとして固定。 */
414
+ const WCS_EYEDROPPER_ERROR_CODE = {
415
+ CapabilityMissing: "capability-missing",
416
+ PickFailed: "pick-failed",
417
+ };
418
+ /** eyedropper node の capability registry。文字列 ID を eval せず明示 probe を持つ。 */
419
+ const EYEDROPPER_CAPABILITIES = new Map([
420
+ ["web.eyedropper", { probe: () => typeof globalThis.EyeDropper === "function", compatKey: "api.EyeDropper" }],
421
+ ]);
422
+
46
423
  /**
47
424
  * Headless EyeDropper primitive. A thin, framework-agnostic wrapper around
48
425
  * `new EyeDropper().open(options)` exposed through the wc-bindable protocol.
49
426
  *
50
- * This is a simplified derivative of `FetchCore._doFetch`
51
- * (docs/eyedropper-tag-design.md §1, docs/web-share-tag-design.md §2): it
52
- * keeps the single `_gen` generation guard, the same-value-guarded private
53
- * setters, and the never-throw try/catch wrapper — the same skeleton
54
- * `@wcstack/share`'s `ShareCore` uses.
55
- *
56
- * Unlike `ShareCore`, this Core **does** restore `AbortController`/`abort()`
57
- * (docs/eyedropper-tag-design.md §2): `EyeDropper.open()` accepts a `{signal}`
58
- * option, so — unlike Web Share — a caller has a real platform mechanism to
59
- * cancel an in-flight color pick. The shape mirrors `FetchCore.abort()`
60
- * (packages/fetch/src/core/FetchCore.ts:159-164) including the identity check
61
- * on the locally-held `AbortController` in the `finally` block
62
- * (packages/fetch/src/core/FetchCore.ts:312-314), so a fast abort()→open()
63
- * sequence never lets a stale controller null out the new call's controller.
427
+ * Concurrency is owned by the shared `OperationLane` (io-core) with the `latest`
428
+ * policy: `EyeDropper.open()` accepts a `{signal}`, so — unlike Web Share / Contact
429
+ * Picker (exhaust) — a caller has a real platform mechanism to cancel an in-flight
430
+ * pick. A new `open()` supersedes the previous one (the lane aborts its
431
+ * AbortController and the superseded completion fails the terminal CAS), and the
432
+ * `abort()` command aborts the active pick. This replaces the ad-hoc `_gen` +
433
+ * `_abortController` + finally-block identity check with the same lane FetchCore
434
+ * uses; the lane owns the per-attempt AbortController and the commit guard.
64
435
  *
65
436
  * Both the user dismissing the picker with Escape and the caller invoking
66
- * `abort()` reject `open()` with the same `AbortError` — both land on
67
- * `cancelled` without distinction (docs/eyedropper-tag-design.md §2).
437
+ * `abort()` reject `open()` with the same `AbortError` — both land on `cancelled`
438
+ * without distinction (docs/eyedropper-tag-design.md §2).
68
439
  */
69
440
  class EyedropperCore extends EventTarget {
70
441
  static wcBindable = {
@@ -75,24 +446,30 @@ class EyedropperCore extends EventTarget {
75
446
  { name: "loading", event: "wcs-eyedropper:loading-changed" },
76
447
  { name: "error", event: "wcs-eyedropper:error" },
77
448
  { name: "cancelled", event: "wcs-eyedropper:cancelled-changed" },
449
+ // Serializable failure taxonomy (stable code / phase / recoverable), or null.
450
+ // Additive bindable output; the existing `error` property/event are unchanged.
451
+ // Fires its own `wcs-eyedropper:error-info-changed` event; no getter, so the
452
+ // bound value is the event detail (mirrors `error` / `loading` / `cancelled`).
453
+ { name: "errorInfo", event: "wcs-eyedropper:error-info-changed" },
78
454
  ],
79
455
  commands: [
80
456
  { name: "open", async: true },
81
457
  { name: "abort" },
82
458
  ],
83
459
  };
460
+ // Required capability (probed at call time, never at module eval).
461
+ static REQUIRED_CAPABILITIES = ["web.eyedropper"];
84
462
  _target;
85
463
  _value = null;
86
464
  _loading = false;
87
465
  _error = null;
88
466
  _cancelled = false;
89
- _abortController = null;
90
- // Generation guard (§3.4 of the guidelines): bumped on dispose() (and each
91
- // open() start). An open() that settles after dispose() has a stale `gen`
92
- // and MUST NOT write state to a torn-down element. Not bumped on the
93
- // unsupported early-return — no asynchronous work is started, so there is
94
- // no generation to protect (docs/eyedropper-tag-design.md §4).
95
- _gen = 0;
467
+ _errorInfo = null;
468
+ // Concurrency lane (io-core). `latest`: a new open() supersedes + aborts the
469
+ // in-flight one (switchMap). `withSignal: true`: the lane owns the per-attempt
470
+ // AbortController whose signal is passed to EyeDropper.open(). dispose() bumps
471
+ // the owner generation and aborts.
472
+ _lane = new OperationLane("eyedropper", "latest", { withSignal: true });
96
473
  // SSR (§3.8): no asynchronous probe to await, so readiness is immediate.
97
474
  _ready = Promise.resolve();
98
475
  constructor(target) {
@@ -114,15 +491,52 @@ class EyedropperCore extends EventTarget {
114
491
  get cancelled() {
115
492
  return this._cancelled;
116
493
  }
494
+ /**
495
+ * The last failure's serializable `WcsIoErrorInfo` (stable `code` / `phase` /
496
+ * `recoverable` / `capabilityId`), or null. Exposed as an additive wc-bindable
497
+ * property (event `wcs-eyedropper:error-info-changed`); the existing `error`
498
+ * property/event are unchanged. Note user/abort cancellation is `cancelled`, not
499
+ * `errorInfo`.
500
+ */
501
+ get errorInfo() {
502
+ return this._errorInfo;
503
+ }
504
+ /**
505
+ * Whether the required platform capability (`web.eyedropper`) is available right
506
+ * now — decided by call-time feature detection, not User-Agent. Core-only,
507
+ * additive.
508
+ */
509
+ get supported() {
510
+ return requiredCapabilitiesAvailable(this.platformAssessment, EyedropperCore.REQUIRED_CAPABILITIES);
511
+ }
512
+ /**
513
+ * Full platform assessment (availability / readiness / preconditions), probed at
514
+ * call time. Core-only opt-in dev / sidecar view.
515
+ */
516
+ get platformAssessment() {
517
+ return assessCapabilities(EYEDROPPER_CAPABILITIES, {
518
+ required: EyedropperCore.REQUIRED_CAPABILITIES,
519
+ activity: this._loading ? "active" : "inactive",
520
+ lastError: this._errorInfo ?? undefined,
521
+ });
522
+ }
117
523
  // Lifecycle (§3.5). EyeDropper is command-driven with no subscription to
118
524
  // establish, so observe() is an idempotent no-op that resolves once ready;
119
- // dispose() invalidates any in-flight open() and aborts it.
525
+ // dispose() bumps the lane's owner generation (invalidating any in-flight open())
526
+ // and aborts its AbortController.
120
527
  observe() {
121
528
  return this._ready;
122
529
  }
123
530
  dispose() {
124
- this._gen++;
125
- this.abort();
531
+ this._lane.disposeOwner();
532
+ }
533
+ // CommitGuard (§5.1): external setters / event dispatch only run if the ticket
534
+ // still holds owner generation, is pre-terminal, and is the lane's latest epoch
535
+ // (a superseding open() can invalidate a ticket mid-commit).
536
+ _commitStep(ticket, step) {
537
+ if (this._lane.canCommit(ticket)) {
538
+ step();
539
+ }
126
540
  }
127
541
  _setLoading(loading) {
128
542
  if (this._loading === loading)
@@ -160,93 +574,98 @@ class EyedropperCore extends EventTarget {
160
574
  bubbles: true,
161
575
  }));
162
576
  }
163
- // API resolution is call-time, never cached (§3.7): lets tests install/remove
164
- // the global EyeDropper constructor freely and lets an unsupported
165
- // environment (non-Chromium browsers, as of 2026) be detected correctly on
166
- // every call (docs/eyedropper-tag-design.md §4).
167
- _api() {
168
- const g = globalThis;
169
- return typeof g.EyeDropper === "function" ? g.EyeDropper : undefined;
577
+ // Single mutation point for `errorInfo`, mirroring `_setError`'s same-value guard
578
+ // and event dispatch so the additive `errorInfo` wc-bindable property stays in
579
+ // sync with `error`. Each failure builds a fresh object (reference guard passes);
580
+ // the clear path passes null (suppresses a redundant null→null per open start).
581
+ _setErrorInfo(code, phase, recoverable, message, capabilityId) {
582
+ this._commitErrorInfo({ code, phase, recoverable, message, ...(capabilityId === undefined ? {} : { capabilityId }) });
583
+ }
584
+ _commitErrorInfo(info) {
585
+ if (this._errorInfo === info)
586
+ return;
587
+ this._errorInfo = info;
588
+ this._target.dispatchEvent(new CustomEvent("wcs-eyedropper:error-info-changed", {
589
+ detail: info,
590
+ bubbles: true,
591
+ }));
170
592
  }
171
593
  /**
172
- * Cancels an in-flight `open()` call, if any. A no-op when no open() is in
173
- * flight (no AbortController has been created yet, or the previous one has
174
- * already settled) — mirrors `FetchCore.abort()`
175
- * (packages/fetch/src/core/FetchCore.ts:159-164).
594
+ * Cancels an in-flight `open()` call, if any (a no-op otherwise). Aborts the
595
+ * lane's active AbortController — the in-flight open() then rejects with
596
+ * `AbortError` and lands on `cancelled`. The epoch is not advanced, so the
597
+ * aborted operation keeps eligibility to claim the `aborted` terminal.
176
598
  */
177
599
  abort() {
178
- if (this._abortController) {
179
- this._abortController.abort();
180
- this._abortController = null;
181
- }
600
+ this._lane.abortActive();
182
601
  }
183
602
  async open() {
184
- // never-throw + unsupported (§4): resolve API at call time and bail out
185
- // immediately if absent. No _gen bump — no asynchronous work is started,
186
- // so there is no generation to protect, and `new EyeDropper()` is never
187
- // constructed.
188
- const EyeDropperCtor = this._api();
189
- if (!EyeDropperCtor) {
190
- this._setError({ message: "EyeDropper API is not supported in this browser." });
603
+ // never-throw + unsupported (§4 / §7.2): probe the required capability at call
604
+ // time (non-Chromium browsers lack this API). If `web.eyedropper` is absent, do
605
+ // NOT start — surface a stable `capability-missing` taxonomy and the existing
606
+ // error message shape.
607
+ const assessment = this.platformAssessment;
608
+ if (!requiredCapabilitiesAvailable(assessment, EyedropperCore.REQUIRED_CAPABILITIES)) {
609
+ const missing = EyedropperCore.REQUIRED_CAPABILITIES.find((id) => assessment.availability.get(id) !== "available");
610
+ const message = "EyeDropper API is not supported in this browser.";
611
+ this._setErrorInfo(WCS_EYEDROPPER_ERROR_CODE.CapabilityMissing, "start", false, message, missing);
612
+ this._setError({ message });
191
613
  return null;
192
614
  }
193
- // Cancel any previous in-flight pick before starting a new one (mirrors
194
- // FetchCore._doFetch's `this.abort()` at the top).
195
- this.abort();
196
- // Hold the controller in a local so the finally block (which can run after
197
- // a subsequent open() has already replaced this._abortController) only
198
- // clears the field when it still owns it — identical identity check to
199
- // FetchCore._doFetch (packages/fetch/src/core/FetchCore.ts:312-314). This
200
- // is what keeps a fast abort()→open() sequence from letting a stale
201
- // controller null out the new call's controller.
202
- const ac = new AbortController();
203
- this._abortController = ac;
204
- const { signal } = ac;
205
- const gen = ++this._gen;
206
- this._setLoading(true);
615
+ // `latest`: advance the epoch and abort the previous in-flight pick (supersede).
616
+ // begin() never returns null for latest.
617
+ const started = this._lane.begin();
618
+ const { ticket, attempt } = started;
619
+ const signal = attempt.signal;
620
+ // Capability probed above → EyeDropper is present. Resolve the constructor at
621
+ // call time (never cached, §3.7) so tests can install/remove it freely.
622
+ const EyeDropperCtor = globalThis.EyeDropper;
623
+ this._commitStep(ticket, () => this._setLoading(true));
207
624
  // Reset the previous outcome before starting a new open() so a stale
208
- // cancelled/error does not linger into this call's result
209
- // (docs/eyedropper-tag-design.md §1, docs/web-share-tag-design.md §3).
210
- this._setError(null);
211
- this._setCancelled(false);
625
+ // cancelled/error/errorInfo does not linger into this call's result.
626
+ this._commitStep(ticket, () => {
627
+ this._commitErrorInfo(null);
628
+ this._setError(null);
629
+ this._setCancelled(false);
630
+ });
212
631
  try {
213
632
  const result = await new EyeDropperCtor().open({ signal });
214
- // Stale completion (dispose() ran, or a superseding open() ran, while
215
- // the picker was open). Drop the result without writing state.
216
- if (gen !== this._gen) {
633
+ // Terminal CAS: a stale (superseded / dispose-invalidated) completion loses
634
+ // the claim and is dropped without writing state.
635
+ if (!this._lane.claimTerminal(ticket, "success")) {
217
636
  return null;
218
637
  }
219
- // The platform's own result object ({ sRGBHex }) is used verbatim — no
220
- // synthesis needed, unlike Web Share's `value`
221
- // (docs/eyedropper-tag-design.md §3).
222
- this._setValue(result);
223
- this._setLoading(false);
638
+ // The platform's own result object ({ sRGBHex }) is used verbatim (§3).
639
+ // Separate commit steps (like FetchCore): if `_setValue`'s event listener
640
+ // synchronously supersedes this op, the following `_setLoading(false)` is
641
+ // stopped by the commit guard rather than clobbering the newer op.
642
+ this._commitStep(ticket, () => this._setValue(result));
643
+ this._commitStep(ticket, () => this._setLoading(false));
644
+ this._lane.finalize(ticket);
224
645
  return result;
225
646
  }
226
647
  catch (e) {
227
- // Stale completion (dispose() ran, or a superseding open() ran, while
228
- // the picker was open).
229
- if (gen !== this._gen) {
648
+ const cancelled = e?.name === "AbortError";
649
+ if (!this._lane.claimTerminal(ticket, cancelled ? "aborted" : "error")) {
230
650
  return null;
231
651
  }
232
- if (e?.name === "AbortError") {
233
- // Either the user dismissed the picker with Escape, or the caller
234
- // invoked abort() — both are a routine cancellation, not a platform
235
- // failure, and are not distinguished (docs/eyedropper-tag-design.md
236
- // §2). Kept out of `error`.
237
- this._setCancelled(true);
238
- }
239
- else {
240
- this._setError(e);
241
- }
242
- this._setLoading(false);
652
+ this._commitStep(ticket, () => {
653
+ if (cancelled) {
654
+ // Either the user dismissed the picker with Escape or the caller invoked
655
+ // abort() — a routine cancellation, not a platform failure, and not
656
+ // distinguished (§2). Kept out of `error`/`errorInfo`.
657
+ this._setCancelled(true);
658
+ }
659
+ else {
660
+ const message = String(e?.message ?? "Color pick failed.");
661
+ this._setErrorInfo(WCS_EYEDROPPER_ERROR_CODE.PickFailed, "execute", true, message);
662
+ this._setError(e ?? { message });
663
+ }
664
+ });
665
+ this._commitStep(ticket, () => this._setLoading(false));
666
+ this._lane.finalize(ticket);
243
667
  return null;
244
668
  }
245
- finally {
246
- if (this._abortController === ac) {
247
- this._abortController = null;
248
- }
249
- }
250
669
  }
251
670
  }
252
671
 
@@ -343,6 +762,9 @@ class WcsEyedropper extends HTMLElement {
343
762
  get cancelled() {
344
763
  return this._core.cancelled;
345
764
  }
765
+ get errorInfo() {
766
+ return this._core.errorInfo;
767
+ }
346
768
  get connectedCallbackPromise() {
347
769
  return this._connectedCallbackPromise;
348
770
  }
@@ -376,5 +798,5 @@ function bootstrapEyedropper(userConfig) {
376
798
  registerComponents();
377
799
  }
378
800
 
379
- export { EyedropperCore, WcsEyedropper, bootstrapEyedropper, getConfig };
801
+ export { EyedropperCore, WCS_EYEDROPPER_ERROR_CODE, WcsEyedropper, bootstrapEyedropper, getConfig };
380
802
  //# sourceMappingURL=index.esm.js.map