@wcstack/ambient-light-sensor 1.16.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 +138 -0
- package/README.md +139 -0
- package/dist/auto.js +3 -0
- package/dist/auto.min.js +1 -0
- package/dist/index.d.ts +211 -0
- package/dist/index.esm.js +353 -0
- package/dist/index.esm.js.map +1 -0
- package/dist/index.esm.min.js +2 -0
- package/dist/index.esm.min.js.map +1 -0
- package/package.json +72 -0
package/README.ja.md
ADDED
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
# @wcstack/ambient-light-sensor
|
|
2
|
+
|
|
3
|
+
`@wcstack/ambient-light-sensor` は wcstack エコシステム向けのヘッドレスな Generic Sensor API(AmbientLightSensor)コンポーネントです。
|
|
4
|
+
|
|
5
|
+
視覚的な UI ウィジェットではありません。周囲の明るさ読み取りをリアクティブな state に変える**非同期プリミティブノード**です。
|
|
6
|
+
|
|
7
|
+
`@wcstack/state` と組み合わせると、`<wcs-ambient-light-sensor>` はパス契約で直接バインドできます:
|
|
8
|
+
|
|
9
|
+
- **入力サーフェス**: `frequency`(サンプリングレート、Hz)
|
|
10
|
+
- **出力 state サーフェス**: `illuminance`、`error`
|
|
11
|
+
|
|
12
|
+
明るさ駆動のUI(自動ダークモード、画面減光)を、`AmbientLightSensor`/`reading`/`error`リスナーの配線コードを書かずにHTML上で宣言的に表現できます。
|
|
13
|
+
|
|
14
|
+
`@wcstack/ambient-light-sensor` は [CSBC](https://github.com/csbc-dev/arch/blob/main/README.md)(Core / Shell / Binding Contract)アーキテクチャに従います:
|
|
15
|
+
|
|
16
|
+
- **Core**(`AmbientLightSensorCore`)がプラットフォームの`AmbientLightSensor`を構築し、live な`reading`/`error`イベントを追従
|
|
17
|
+
- **Shell**(`<wcs-ambient-light-sensor>`)がその state を DOM ライフサイクルに接続
|
|
18
|
+
- **Binding Contract**(`static wcBindable`)が観測可能な`properties`と`start`/`stop`の`commands`を宣言
|
|
19
|
+
|
|
20
|
+
## なぜ存在するか — Generic Sensor族の中で最も対応が弱いメンバー
|
|
21
|
+
|
|
22
|
+
Generic Sensor API の`Accelerometer`/`Gyroscope`/`Magnetometer`/`AmbientLightSensor`族は全て共通の形状を持ちます: `.start()`/`.stop()`、サンプルごとの`'reading'`イベント、そして——注目すべき点として——失敗は例外ではなく**`'error'`イベント**で通知されます。これは wcstack の never-throw 方針と最初から噛み合っています。唯一防御的な`try/catch`が要るのは、権限拒否やPermissions-Policyブロックで**同期的に例外を投げうる**`AmbientLightSensor`のコンストラクタ自体です。
|
|
23
|
+
|
|
24
|
+
他の3兄弟と異なり、**`AmbientLightSensor`はx/y/z軸ではなく単一のスカラー値**(`illuminance`、lux単位)を報告します。
|
|
25
|
+
|
|
26
|
+
> **対応状況は狭いだけでなく悪化しています。** 他のセンサー族と共通のChromium/Android中心という制約に加え、`AmbientLightSensor`は特にfingerprinting対策を理由に複数のブラウザで無効化・削除されてきた経緯があります。採用前に現在の対応状況(MDN/caniuse)を必ず確認してください——対象ブラウザによってはこのパッケージの採用自体を見送るべき場合もあります。
|
|
27
|
+
|
|
28
|
+
> **`@wcstack/permission`との合成を推奨。** センサー自体が対応している環境では`navigator.permissions.query({name:"ambient-light-sensor"})`が存在するため、`<wcs-ambient-light-sensor>`は`<wcs-permission name="ambient-light-sensor">`と併置して`granted`/`denied`/`prompt`状態を得てください(権限状態はこのノード自身では重複実装しません、`docs/sensor-tag-design.md`参照)。
|
|
29
|
+
|
|
30
|
+
## インストール
|
|
31
|
+
|
|
32
|
+
```bash
|
|
33
|
+
npm install @wcstack/ambient-light-sensor
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
## クイックスタート
|
|
37
|
+
|
|
38
|
+
### 1. 明るさをライブ表示
|
|
39
|
+
|
|
40
|
+
`<wcs-ambient-light-sensor>`は接続時に**自動開始しません** — バインドしただけでは
|
|
41
|
+
`illuminance`は初期値`null`のままです。読み取りを流すには(例えばボタンから)
|
|
42
|
+
`start`コマンドを発火する必要があります:
|
|
43
|
+
|
|
44
|
+
```html
|
|
45
|
+
<script type="module" src="https://esm.run/@wcstack/state/auto"></script>
|
|
46
|
+
<script type="module" src="https://esm.run/@wcstack/ambient-light-sensor/auto"></script>
|
|
47
|
+
|
|
48
|
+
<wcs-state>
|
|
49
|
+
<script type="module">
|
|
50
|
+
export default {
|
|
51
|
+
$commandTokens: ["startLight"],
|
|
52
|
+
illuminance: null,
|
|
53
|
+
};
|
|
54
|
+
</script>
|
|
55
|
+
</wcs-state>
|
|
56
|
+
|
|
57
|
+
<wcs-ambient-light-sensor
|
|
58
|
+
data-wcs="illuminance: illuminance; command.start: $command.startLight"
|
|
59
|
+
></wcs-ambient-light-sensor>
|
|
60
|
+
|
|
61
|
+
<button data-wcs="onclick: $command.startLight">開始</button>
|
|
62
|
+
<p data-wcs="textContent: illuminance"></p>
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
ボタンは`<wcs-ambient-light-sensor>`に直接触れません: クリックは`startLight`コマンドトークンを発火し(`$commandTokens: ["startLight"]`で名前を宣言)、`<wcs-ambient-light-sensor>`は`command.start: $command.startLight`でそれを購読します([command-token プロトコル](../state/) — コマンドメソッドを持つ要素が*subscriber*であり、emitter ではありません)。
|
|
66
|
+
|
|
67
|
+
### 2. 権限を確認してから start する
|
|
68
|
+
|
|
69
|
+
この例では`@wcstack/permission`の登録も必要です(例1の`@wcstack/state` /
|
|
70
|
+
`@wcstack/ambient-light-sensor`の script に加えて)。`lightGranted`を宣言する
|
|
71
|
+
独立した`<wcs-state>`を持ちます:
|
|
72
|
+
|
|
73
|
+
```html
|
|
74
|
+
<script type="module" src="https://esm.run/@wcstack/permission/auto"></script>
|
|
75
|
+
|
|
76
|
+
<wcs-state>
|
|
77
|
+
<script type="module">
|
|
78
|
+
export default {
|
|
79
|
+
$commandTokens: ["startLight"],
|
|
80
|
+
lightGranted: false,
|
|
81
|
+
};
|
|
82
|
+
</script>
|
|
83
|
+
</wcs-state>
|
|
84
|
+
|
|
85
|
+
<wcs-permission name="ambient-light-sensor" data-wcs="granted: lightGranted"></wcs-permission>
|
|
86
|
+
<wcs-ambient-light-sensor data-wcs="command.start: $command.startLight"></wcs-ambient-light-sensor>
|
|
87
|
+
|
|
88
|
+
<button data-wcs="onclick: $command.startLight; disabled: lightGranted|not">開始</button>
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
バインドする state パスは事前にすべて宣言する必要があります — 未宣言のパスへのバインドは初期化時に例外を投げます。`data-wcs`パス内の否定は先頭`!`ではなく`|not`フィルタ(`lightGranted|not`)で行います。
|
|
92
|
+
|
|
93
|
+
## 属性 / 入力
|
|
94
|
+
|
|
95
|
+
| 属性 | 型 | 既定値 | 説明 |
|
|
96
|
+
| ----------- | ------ | ------ | ---- |
|
|
97
|
+
| `frequency` | number | — | サンプリングレート(Hz)。`AmbientLightSensor`コンストラクタへそのまま渡る。 |
|
|
98
|
+
|
|
99
|
+
## 観測可能プロパティ(出力)
|
|
100
|
+
|
|
101
|
+
| プロパティ | イベント | 説明 |
|
|
102
|
+
| -------------- | --------------------------------------- | ---- |
|
|
103
|
+
| `illuminance` | `wcs-ambient-light-sensor:reading` | 周囲の明るさ(lux)。初回読み取り前は`null`。 |
|
|
104
|
+
| `error` | `wcs-ambient-light-sensor:error` | 正規化された`{ error, message }`、無ければ`null`。 |
|
|
105
|
+
|
|
106
|
+
## コマンド
|
|
107
|
+
|
|
108
|
+
| コマンド | 非同期 | 説明 |
|
|
109
|
+
| -------- | ------ | ---- |
|
|
110
|
+
| `start` | いいえ | センサーを構築(never-throw: コンストラクタの同期例外はキャッチし`error`へ)し読み取りを開始する。 |
|
|
111
|
+
| `stop` | いいえ | センサーを停止しリスナーを解除する。未開始でも安全に呼べる。 |
|
|
112
|
+
|
|
113
|
+
## 注意・制限
|
|
114
|
+
|
|
115
|
+
- **`_gen`世代ガードは無し。** `start()`/`stop()`は同期的な購読/購読解除のトグルであり、`dispose()`とレースしうる非同期probeが存在しません(`docs/sensor-tag-design.md` §1.5)。
|
|
116
|
+
- **`error`は sticky(据え置き)です。** 最後に観測した失敗(`unsupported`、`SecurityError`等)を保持し、その後の`start()`成功や`reading`受信では自動クリアされません。`stop()`+`start()`でリトライが成功しても直前の`error`は残り続けます。必要なら利用側の state でクリア/再解釈してください。
|
|
117
|
+
- **生の`new AmbientLightSensor(...)`は唯一のガード付き構築ヘルパー以外では呼ばない。** 権限拒否・Permissions-Policyブロックは同期的に例外を投げます。
|
|
118
|
+
- 権限状態(`granted`/`denied`/`prompt`)は意図的にこのノードでは重複実装していません — `<wcs-permission name="ambient-light-sensor">`と合成してください。
|
|
119
|
+
- **採用前に現在のブラウザ対応状況を必ず確認してください** — 上記「なぜ存在するか」参照。
|
|
120
|
+
|
|
121
|
+
## ヘッドレス利用(`AmbientLightSensorCore`)
|
|
122
|
+
|
|
123
|
+
```typescript
|
|
124
|
+
import { AmbientLightSensorCore } from "@wcstack/ambient-light-sensor";
|
|
125
|
+
|
|
126
|
+
const core = new AmbientLightSensorCore();
|
|
127
|
+
core.addEventListener("wcs-ambient-light-sensor:reading", (e) => {
|
|
128
|
+
console.log((e as CustomEvent).detail); // { illuminance }
|
|
129
|
+
});
|
|
130
|
+
|
|
131
|
+
core.start();
|
|
132
|
+
// 後始末:
|
|
133
|
+
core.dispose();
|
|
134
|
+
```
|
|
135
|
+
|
|
136
|
+
## ライセンス
|
|
137
|
+
|
|
138
|
+
MIT
|
package/README.md
ADDED
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
# @wcstack/ambient-light-sensor
|
|
2
|
+
|
|
3
|
+
`@wcstack/ambient-light-sensor` is a headless Generic Sensor API (AmbientLightSensor) component for the wcstack ecosystem.
|
|
4
|
+
|
|
5
|
+
It is not a visual UI widget.
|
|
6
|
+
It is an **async primitive node** that turns ambient light readings into reactive state.
|
|
7
|
+
|
|
8
|
+
With `@wcstack/state`, `<wcs-ambient-light-sensor>` can be bound directly through path contracts:
|
|
9
|
+
|
|
10
|
+
- **input surface**: `frequency` (sampling rate in Hz)
|
|
11
|
+
- **output state surface**: `illuminance`, `error`
|
|
12
|
+
|
|
13
|
+
This means light-level-driven UI (auto dark mode, screen dimming) can be expressed declaratively in HTML, without writing `AmbientLightSensor`/`reading`/`error`-listener glue in your UI layer.
|
|
14
|
+
|
|
15
|
+
`@wcstack/ambient-light-sensor` follows the [CSBC](https://github.com/csbc-dev/arch/blob/main/README.md) (Core / Shell / Binding Contract) architecture:
|
|
16
|
+
|
|
17
|
+
- **Core** (`AmbientLightSensorCore`) constructs the platform `AmbientLightSensor`, tracks its live `reading`/`error` events
|
|
18
|
+
- **Shell** (`<wcs-ambient-light-sensor>`) connects that state to DOM lifecycle
|
|
19
|
+
- **Binding Contract** (`static wcBindable`) declares observable `properties` and `start`/`stop` `commands`
|
|
20
|
+
|
|
21
|
+
## Why this exists — the weakest-supported member of the Generic Sensor family
|
|
22
|
+
|
|
23
|
+
The Generic Sensor API's `Accelerometer`/`Gyroscope`/`Magnetometer`/`AmbientLightSensor` family all share one base shape: `.start()`/`.stop()`, a `'reading'` event per sample, and — notably — an `'error'` **event** for failures instead of a thrown exception. This already lines up with wcstack's never-throw convention; the one place this Core still needs a defensive `try/catch` is the synchronous `AmbientLightSensor` **constructor** itself, which can throw (`SecurityError`) on permission denial or a Permissions-Policy block.
|
|
24
|
+
|
|
25
|
+
Unlike its three siblings, **`AmbientLightSensor` reports a single scalar** (`illuminance`, in lux) rather than x/y/z axes.
|
|
26
|
+
|
|
27
|
+
> **Support is deteriorating, not just narrow.** Beyond the usual Chromium/Android-centric limits shared with the rest of the family, `AmbientLightSensor` specifically has been disabled or removed in several browsers over fingerprinting concerns. Verify current support (MDN/caniuse) before depending on this package — it may not be worth shipping at all depending on your target browsers.
|
|
28
|
+
|
|
29
|
+
> **Compose with `@wcstack/permission`.** `navigator.permissions.query({name:"ambient-light-sensor"})` exists where the sensor itself is supported — pair `<wcs-ambient-light-sensor>` with `<wcs-permission name="ambient-light-sensor">` for `granted`/`denied`/`prompt` status rather than duplicating that state here (see `docs/sensor-tag-design.md`).
|
|
30
|
+
|
|
31
|
+
## Install
|
|
32
|
+
|
|
33
|
+
```bash
|
|
34
|
+
npm install @wcstack/ambient-light-sensor
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
## Quick Start
|
|
38
|
+
|
|
39
|
+
### 1. Read live illuminance
|
|
40
|
+
|
|
41
|
+
`<wcs-ambient-light-sensor>` does **not** auto-start on connect — binding alone
|
|
42
|
+
leaves `illuminance` at its initial `null`. You must fire the `start` command
|
|
43
|
+
(e.g. from a button) before readings flow:
|
|
44
|
+
|
|
45
|
+
```html
|
|
46
|
+
<script type="module" src="https://esm.run/@wcstack/state/auto"></script>
|
|
47
|
+
<script type="module" src="https://esm.run/@wcstack/ambient-light-sensor/auto"></script>
|
|
48
|
+
|
|
49
|
+
<wcs-state>
|
|
50
|
+
<script type="module">
|
|
51
|
+
export default {
|
|
52
|
+
$commandTokens: ["startLight"],
|
|
53
|
+
illuminance: null,
|
|
54
|
+
};
|
|
55
|
+
</script>
|
|
56
|
+
</wcs-state>
|
|
57
|
+
|
|
58
|
+
<wcs-ambient-light-sensor
|
|
59
|
+
data-wcs="illuminance: illuminance; command.start: $command.startLight"
|
|
60
|
+
></wcs-ambient-light-sensor>
|
|
61
|
+
|
|
62
|
+
<button data-wcs="onclick: $command.startLight">Start</button>
|
|
63
|
+
<p data-wcs="textContent: illuminance"></p>
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
The button never touches `<wcs-ambient-light-sensor>` directly: its click emits the `startLight` command token (`$commandTokens: ["startLight"]` declares the name), and `<wcs-ambient-light-sensor>` subscribes to it via `command.start: $command.startLight` (the [command-token protocol](../state/) — the element with the command method is the *subscriber*, not the emitter).
|
|
67
|
+
|
|
68
|
+
### 2. Gate on permission, then start
|
|
69
|
+
|
|
70
|
+
This example also needs `@wcstack/permission` registered (alongside the
|
|
71
|
+
`@wcstack/state` / `@wcstack/ambient-light-sensor` scripts from example 1), with its
|
|
72
|
+
own self-contained `<wcs-state>` declaring `lightGranted`:
|
|
73
|
+
|
|
74
|
+
```html
|
|
75
|
+
<script type="module" src="https://esm.run/@wcstack/permission/auto"></script>
|
|
76
|
+
|
|
77
|
+
<wcs-state>
|
|
78
|
+
<script type="module">
|
|
79
|
+
export default {
|
|
80
|
+
$commandTokens: ["startLight"],
|
|
81
|
+
lightGranted: false,
|
|
82
|
+
};
|
|
83
|
+
</script>
|
|
84
|
+
</wcs-state>
|
|
85
|
+
|
|
86
|
+
<wcs-permission name="ambient-light-sensor" data-wcs="granted: lightGranted"></wcs-permission>
|
|
87
|
+
<wcs-ambient-light-sensor data-wcs="command.start: $command.startLight"></wcs-ambient-light-sensor>
|
|
88
|
+
|
|
89
|
+
<button data-wcs="onclick: $command.startLight; disabled: lightGranted|not">Start</button>
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
Every bound state path must be declared up front — binding an undeclared path throws at initialization. Negation in a `data-wcs` path is done with the `|not` filter (`lightGranted|not`), not a leading `!`.
|
|
93
|
+
|
|
94
|
+
## Attributes / Inputs
|
|
95
|
+
|
|
96
|
+
| Attribute | Type | Default | Description |
|
|
97
|
+
| ----------- | ------ | ------- | ------------ |
|
|
98
|
+
| `frequency` | number | — | Sampling rate in Hz, forwarded to the `AmbientLightSensor` constructor. |
|
|
99
|
+
|
|
100
|
+
## Observable Properties (outputs)
|
|
101
|
+
|
|
102
|
+
| Property | Event | Description |
|
|
103
|
+
| ------------- | -------------------------------------- | ------------ |
|
|
104
|
+
| `illuminance` | `wcs-ambient-light-sensor:reading` | Ambient light level in lux, or `null` before the first reading. |
|
|
105
|
+
| `error` | `wcs-ambient-light-sensor:error` | Normalized `{ error, message }`, or `null`. |
|
|
106
|
+
|
|
107
|
+
## Commands
|
|
108
|
+
|
|
109
|
+
| Command | Async | Description |
|
|
110
|
+
| ------- | ----- | ------------ |
|
|
111
|
+
| `start` | no | Construct the sensor (never-throw: a synchronous constructor exception is caught and surfaced via `error`) and begin reading. |
|
|
112
|
+
| `stop` | no | Stop the sensor and detach its listeners. Safe to call when not started. |
|
|
113
|
+
|
|
114
|
+
## Notes & limitations
|
|
115
|
+
|
|
116
|
+
- **No `_gen` generation guard.** `start()`/`stop()` are a synchronous subscribe/unsubscribe toggle with no asynchronous probe to race against a `dispose()` — see `docs/sensor-tag-design.md` §1.5.
|
|
117
|
+
- **`error` is sticky.** It holds the last observed failure (e.g. `unsupported`, `SecurityError`) and is **not** auto-cleared by a later successful `start()` or by incoming `reading`s. A `stop()` + `start()` retry that succeeds still leaves the previous `error` in place — clear or reinterpret it in your own state if needed.
|
|
118
|
+
- **Never call the raw `new AmbientLightSensor(...)` anywhere but the one guarded construction helper** — permission denial and Permissions-Policy blocks throw synchronously.
|
|
119
|
+
- Permission status (`granted`/`denied`/`prompt`) is intentionally not duplicated here — compose with `<wcs-permission name="ambient-light-sensor">`.
|
|
120
|
+
- **Confirm current browser support before adopting this package** — see "Why this exists" above.
|
|
121
|
+
|
|
122
|
+
## Headless usage (`AmbientLightSensorCore`)
|
|
123
|
+
|
|
124
|
+
```typescript
|
|
125
|
+
import { AmbientLightSensorCore } from "@wcstack/ambient-light-sensor";
|
|
126
|
+
|
|
127
|
+
const core = new AmbientLightSensorCore();
|
|
128
|
+
core.addEventListener("wcs-ambient-light-sensor:reading", (e) => {
|
|
129
|
+
console.log((e as CustomEvent).detail); // { illuminance }
|
|
130
|
+
});
|
|
131
|
+
|
|
132
|
+
core.start();
|
|
133
|
+
// later:
|
|
134
|
+
core.dispose();
|
|
135
|
+
```
|
|
136
|
+
|
|
137
|
+
## License
|
|
138
|
+
|
|
139
|
+
MIT
|
package/dist/auto.js
ADDED
package/dist/auto.min.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{bootstrapAmbientLightSensor}from"./index.esm.min.js";bootstrapAmbientLightSensor();
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,211 @@
|
|
|
1
|
+
interface IWcBindableProperty {
|
|
2
|
+
readonly name: string;
|
|
3
|
+
readonly event: string;
|
|
4
|
+
readonly getter?: (event: Event) => any;
|
|
5
|
+
}
|
|
6
|
+
interface IWcBindableInput {
|
|
7
|
+
readonly name: string;
|
|
8
|
+
readonly attribute?: string;
|
|
9
|
+
}
|
|
10
|
+
interface IWcBindableCommand {
|
|
11
|
+
readonly name: string;
|
|
12
|
+
readonly async?: boolean;
|
|
13
|
+
}
|
|
14
|
+
interface IWcBindable {
|
|
15
|
+
readonly protocol: "wc-bindable";
|
|
16
|
+
readonly version: 1;
|
|
17
|
+
readonly properties: readonly IWcBindableProperty[];
|
|
18
|
+
readonly inputs?: readonly IWcBindableInput[];
|
|
19
|
+
readonly commands?: readonly IWcBindableCommand[];
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
interface ITagNames {
|
|
23
|
+
readonly ambientLightSensor: string;
|
|
24
|
+
}
|
|
25
|
+
interface IWritableTagNames {
|
|
26
|
+
ambientLightSensor?: string;
|
|
27
|
+
}
|
|
28
|
+
interface IConfig {
|
|
29
|
+
readonly tagNames: ITagNames;
|
|
30
|
+
}
|
|
31
|
+
interface IWritableConfig {
|
|
32
|
+
tagNames?: IWritableTagNames;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* A single `reading` sample from the AmbientLightSensor sensor: ambient light
|
|
37
|
+
* level in lux. Unlike Accelerometer/Gyroscope/Magnetometer (x/y/z axes),
|
|
38
|
+
* AmbientLightSensor reports a single scalar (docs/sensor-tag-design.md §2).
|
|
39
|
+
*/
|
|
40
|
+
interface WcsAmbientLightSensorReading {
|
|
41
|
+
illuminance: number | null;
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* Error detail published on the `wcs-ambient-light-sensor:error` event. Mirrors the
|
|
45
|
+
* Generic Sensor API's `SensorErrorEvent.error` (a `DOMException`-like value)
|
|
46
|
+
* flattened to a plain object, plus the synthetic `"unsupported"` name used
|
|
47
|
+
* when the global `AmbientLightSensor` constructor is absent.
|
|
48
|
+
*/
|
|
49
|
+
interface WcsAmbientLightSensorErrorDetail {
|
|
50
|
+
error: string;
|
|
51
|
+
message: string;
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* Value types for AmbientLightSensorCore (headless) — the observable state
|
|
55
|
+
* properties. Use with `bind()` from a wc-bindable binding core for
|
|
56
|
+
* compile-time type checking.
|
|
57
|
+
*
|
|
58
|
+
* @example
|
|
59
|
+
* ```typescript
|
|
60
|
+
* const core = new AmbientLightSensorCore();
|
|
61
|
+
* bind(core, (name: keyof WcsAmbientLightSensorCoreValues, value) => { ... });
|
|
62
|
+
* ```
|
|
63
|
+
*/
|
|
64
|
+
interface WcsAmbientLightSensorCoreValues extends WcsAmbientLightSensorReading {
|
|
65
|
+
error: WcsAmbientLightSensorErrorDetail | null;
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* Value types for the Shell (`<wcs-ambient-light-sensor>`) — identical observable
|
|
69
|
+
* surface to the Core, plus the `frequency` attribute-backed input.
|
|
70
|
+
*/
|
|
71
|
+
type WcsAmbientLightSensorValues = WcsAmbientLightSensorCoreValues;
|
|
72
|
+
|
|
73
|
+
declare function bootstrapAmbientLightSensor(userConfig?: IWritableConfig): void;
|
|
74
|
+
|
|
75
|
+
declare function getConfig(): IConfig;
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* Headless AmbientLightSensor primitive. A thin, framework-agnostic wrapper around
|
|
79
|
+
* the Generic Sensor API's `AmbientLightSensor` class exposed through the
|
|
80
|
+
* wc-bindable protocol.
|
|
81
|
+
*
|
|
82
|
+
* The platform `Sensor` base class (shared by `Accelerometer` / `Gyroscope` /
|
|
83
|
+
* `Magnetometer` / `AmbientLightSensor`) reports failure through an `'error'`
|
|
84
|
+
* event rather than a rejected promise, so this Core can satisfy never-throw
|
|
85
|
+
* (docs/async-io-node-guidelines.md §3.6) by simply forwarding that event —
|
|
86
|
+
* see docs/sensor-tag-design.md §0. The one place a synchronous
|
|
87
|
+
* exception *can* still escape the platform API is the `AmbientLightSensor`
|
|
88
|
+
* constructor itself (e.g. `SecurityError` on permission denial or a
|
|
89
|
+
* feature-policy block); `_createSensor()` wraps that single call in
|
|
90
|
+
* try/catch, mirroring FetchCore's `_doFetch` try/catch around
|
|
91
|
+
* `globalThis.fetch` (packages/fetch/src/core/FetchCore.ts).
|
|
92
|
+
*
|
|
93
|
+
* `illuminance` is a single getter derived from the `wcs-ambient-light-sensor:reading`
|
|
94
|
+
* event (unlike Accelerometer/Gyroscope/Magnetometer's x/y/z, this sensor
|
|
95
|
+
* reports one scalar — docs/sensor-tag-design.md §2). `reading`
|
|
96
|
+
* is an event-like signal (a fresh sample every time, not a settled state) and
|
|
97
|
+
* is therefore deliberately NOT same-value guarded — every sample dispatches.
|
|
98
|
+
* `error` is state-like (denial / unsupported does not change from tick to
|
|
99
|
+
* tick) and IS same-value guarded, and is published on its own
|
|
100
|
+
* `wcs-ambient-light-sensor:error` event, independent of `reading`.
|
|
101
|
+
*
|
|
102
|
+
* No `_gen` generation guard: start()/stop() are a synchronous
|
|
103
|
+
* subscribe/unsubscribe toggle with no asynchronous probe whose stale
|
|
104
|
+
* resolution could race a dispose() — see docs/sensor-tag-design.md §1.5
|
|
105
|
+
* (the same reasoning as NetworkCore, docs/network-tag-design.md §5).
|
|
106
|
+
*
|
|
107
|
+
* Permissions: this Core does not query `navigator.permissions` itself.
|
|
108
|
+
* Compose with `<wcs-permission name="ambient-light-sensor">` instead — see
|
|
109
|
+
* docs/sensor-tag-design.md §"2番目の決定: Permissions APIとの合成".
|
|
110
|
+
*/
|
|
111
|
+
declare class AmbientLightSensorCore extends EventTarget {
|
|
112
|
+
static wcBindable: IWcBindable;
|
|
113
|
+
private _target;
|
|
114
|
+
private _reading;
|
|
115
|
+
private _error;
|
|
116
|
+
private _sensor;
|
|
117
|
+
constructor(target?: EventTarget);
|
|
118
|
+
get illuminance(): number | null;
|
|
119
|
+
get error(): WcsAmbientLightSensorErrorDetail | null;
|
|
120
|
+
/** No asynchronous probe to await: start()/stop() are synchronous
|
|
121
|
+
* (docs/async-io-node-guidelines.md §3.8 is satisfied trivially, mirroring
|
|
122
|
+
* NetworkCore). */
|
|
123
|
+
get ready(): Promise<void>;
|
|
124
|
+
private _setReading;
|
|
125
|
+
private _setError;
|
|
126
|
+
/**
|
|
127
|
+
* Start the sensor at the given `frequency` (Hz), or the platform default
|
|
128
|
+
* when omitted. Idempotent while already started: a redundant start() does
|
|
129
|
+
* not construct a second sensor instance (which would leak the first).
|
|
130
|
+
* Restart with a different frequency via stop() + start().
|
|
131
|
+
*
|
|
132
|
+
* Synchronous, mirroring the native `Sensor.start()` — never throws
|
|
133
|
+
* (docs/async-io-node-guidelines.md §3.6): both "unsupported" and a
|
|
134
|
+
* synchronous constructor exception (permission denial, feature-policy
|
|
135
|
+
* block) are converted to the `error` property instead of propagating.
|
|
136
|
+
*/
|
|
137
|
+
start(frequency?: number): void;
|
|
138
|
+
/** Stop the sensor and detach its listeners. Safe to call when not started. */
|
|
139
|
+
stop(): void;
|
|
140
|
+
/** Lifecycle alias for start(), so the Shell's connectedCallback can drive
|
|
141
|
+
* this Core the same way as other IO nodes' observe()/dispose() pair. No
|
|
142
|
+
* asynchronous probe, so the returned promise always resolves immediately. */
|
|
143
|
+
observe(frequency?: number): Promise<void>;
|
|
144
|
+
/** Lifecycle alias for stop(), invoked from the Shell's disconnectedCallback. */
|
|
145
|
+
dispose(): void;
|
|
146
|
+
private _teardownSensor;
|
|
147
|
+
/**
|
|
148
|
+
* Construct the platform `AmbientLightSensor`, guarding both non-support and a
|
|
149
|
+
* synchronous constructor exception. Never calls the raw `new AmbientLightSensor(...)`
|
|
150
|
+
* anywhere else in this class — see docs/sensor-tag-design.md §1.5.
|
|
151
|
+
*
|
|
152
|
+
* API resolution is call-time (docs/async-io-node-guidelines.md §3.7):
|
|
153
|
+
* re-checked on every start(), never cached, so tests can install/remove the
|
|
154
|
+
* global freely and an unsupported environment is always reported correctly.
|
|
155
|
+
*/
|
|
156
|
+
private _createSensor;
|
|
157
|
+
private _onReading;
|
|
158
|
+
private _onError;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/**
|
|
162
|
+
* `<wcs-ambient-light-sensor>` — declarative Generic Sensor API (`AmbientLightSensor`)
|
|
163
|
+
* monitor + start/stop control.
|
|
164
|
+
*
|
|
165
|
+
* Unlike `<wcs-network>` / `<wcs-permission>` (pure monitors), this Shell is a
|
|
166
|
+
* bidirectional node: `start`/`stop` commands (command-token: state → element)
|
|
167
|
+
* alongside the `illuminance`/`error` observable surface (event-token: element →
|
|
168
|
+
* state). The `frequency` attribute is the sole configuration input, forwarded
|
|
169
|
+
* to the platform `AmbientLightSensor` constructor's `{ frequency }` option
|
|
170
|
+
* (docs/sensor-tag-design.md §1.2). The getter normalizes it: a non-finite or
|
|
171
|
+
* non-positive value (NaN, 0, negative) reads back as `null` — meaning "no
|
|
172
|
+
* frequency specified" — so start() falls back to the platform default rather
|
|
173
|
+
* than forwarding a value the sensor would reject. Any positive finite value is
|
|
174
|
+
* passed through verbatim (no upper-bound clamping — an out-of-range-but-positive
|
|
175
|
+
* rate is still left to the browser/sensor to reject via `error`).
|
|
176
|
+
*
|
|
177
|
+
* Permission handling is intentionally NOT implemented here. Compose with
|
|
178
|
+
* `<wcs-permission name="ambient-light-sensor">` instead (see the README's permission
|
|
179
|
+
* example, "Gate on permission, then start", and docs/sensor-tag-design.md).
|
|
180
|
+
*/
|
|
181
|
+
declare class WcsAmbientLightSensor extends HTMLElement {
|
|
182
|
+
static hasConnectedCallbackPromise: boolean;
|
|
183
|
+
static wcBindable: IWcBindable;
|
|
184
|
+
private _core;
|
|
185
|
+
private _connectedCallbackPromise;
|
|
186
|
+
constructor();
|
|
187
|
+
/**
|
|
188
|
+
* Sampling frequency in Hz. Reads back `null` when unset, blank, or when the
|
|
189
|
+
* attribute does not parse to a positive finite number (NaN, `"0"`, negative)
|
|
190
|
+
* — in every such "no usable value" case the platform default applies.
|
|
191
|
+
*
|
|
192
|
+
* Note the deliberate set/get asymmetry: `set frequency(0)` (or any
|
|
193
|
+
* non-positive/non-finite value) still writes the attribute verbatim for
|
|
194
|
+
* transparency/inspectability, but the getter normalizes it back to `null`.
|
|
195
|
+
* A round-trip through a non-positive value therefore does NOT preserve it —
|
|
196
|
+
* that value carries no valid sampling meaning, so it is treated as "unset"
|
|
197
|
+
* on read. Only positive finite frequencies survive a set→get round-trip.
|
|
198
|
+
*/
|
|
199
|
+
get frequency(): number | null;
|
|
200
|
+
set frequency(value: number | null | undefined);
|
|
201
|
+
get illuminance(): number | null;
|
|
202
|
+
get error(): WcsAmbientLightSensorErrorDetail | null;
|
|
203
|
+
get connectedCallbackPromise(): Promise<void>;
|
|
204
|
+
start(): void;
|
|
205
|
+
stop(): void;
|
|
206
|
+
connectedCallback(): void;
|
|
207
|
+
disconnectedCallback(): void;
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
export { AmbientLightSensorCore, WcsAmbientLightSensor, bootstrapAmbientLightSensor, getConfig };
|
|
211
|
+
export type { IWritableConfig, IWritableTagNames, WcsAmbientLightSensorCoreValues, WcsAmbientLightSensorErrorDetail, WcsAmbientLightSensorReading, WcsAmbientLightSensorValues };
|
|
@@ -0,0 +1,353 @@
|
|
|
1
|
+
const _config = {
|
|
2
|
+
tagNames: {
|
|
3
|
+
ambientLightSensor: "wcs-ambient-light-sensor",
|
|
4
|
+
},
|
|
5
|
+
};
|
|
6
|
+
function deepFreeze(obj) {
|
|
7
|
+
if (obj === null || typeof obj !== "object")
|
|
8
|
+
return obj;
|
|
9
|
+
Object.freeze(obj);
|
|
10
|
+
for (const key of Object.keys(obj)) {
|
|
11
|
+
deepFreeze(obj[key]);
|
|
12
|
+
}
|
|
13
|
+
return obj;
|
|
14
|
+
}
|
|
15
|
+
function deepClone(obj) {
|
|
16
|
+
if (obj === null || typeof obj !== "object")
|
|
17
|
+
return obj;
|
|
18
|
+
const clone = {};
|
|
19
|
+
for (const key of Object.keys(obj)) {
|
|
20
|
+
clone[key] = deepClone(obj[key]);
|
|
21
|
+
}
|
|
22
|
+
return clone;
|
|
23
|
+
}
|
|
24
|
+
let frozenConfig = null;
|
|
25
|
+
const config = _config;
|
|
26
|
+
function getConfig() {
|
|
27
|
+
if (!frozenConfig) {
|
|
28
|
+
frozenConfig = deepFreeze(deepClone(_config));
|
|
29
|
+
}
|
|
30
|
+
return frozenConfig;
|
|
31
|
+
}
|
|
32
|
+
function setConfig(partialConfig) {
|
|
33
|
+
if (partialConfig.tagNames) {
|
|
34
|
+
Object.assign(_config.tagNames, partialConfig.tagNames);
|
|
35
|
+
}
|
|
36
|
+
frozenConfig = null;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
const NULL_READING = Object.freeze({ illuminance: null });
|
|
40
|
+
/**
|
|
41
|
+
* Headless AmbientLightSensor primitive. A thin, framework-agnostic wrapper around
|
|
42
|
+
* the Generic Sensor API's `AmbientLightSensor` class exposed through the
|
|
43
|
+
* wc-bindable protocol.
|
|
44
|
+
*
|
|
45
|
+
* The platform `Sensor` base class (shared by `Accelerometer` / `Gyroscope` /
|
|
46
|
+
* `Magnetometer` / `AmbientLightSensor`) reports failure through an `'error'`
|
|
47
|
+
* event rather than a rejected promise, so this Core can satisfy never-throw
|
|
48
|
+
* (docs/async-io-node-guidelines.md §3.6) by simply forwarding that event —
|
|
49
|
+
* see docs/sensor-tag-design.md §0. The one place a synchronous
|
|
50
|
+
* exception *can* still escape the platform API is the `AmbientLightSensor`
|
|
51
|
+
* constructor itself (e.g. `SecurityError` on permission denial or a
|
|
52
|
+
* feature-policy block); `_createSensor()` wraps that single call in
|
|
53
|
+
* try/catch, mirroring FetchCore's `_doFetch` try/catch around
|
|
54
|
+
* `globalThis.fetch` (packages/fetch/src/core/FetchCore.ts).
|
|
55
|
+
*
|
|
56
|
+
* `illuminance` is a single getter derived from the `wcs-ambient-light-sensor:reading`
|
|
57
|
+
* event (unlike Accelerometer/Gyroscope/Magnetometer's x/y/z, this sensor
|
|
58
|
+
* reports one scalar — docs/sensor-tag-design.md §2). `reading`
|
|
59
|
+
* is an event-like signal (a fresh sample every time, not a settled state) and
|
|
60
|
+
* is therefore deliberately NOT same-value guarded — every sample dispatches.
|
|
61
|
+
* `error` is state-like (denial / unsupported does not change from tick to
|
|
62
|
+
* tick) and IS same-value guarded, and is published on its own
|
|
63
|
+
* `wcs-ambient-light-sensor:error` event, independent of `reading`.
|
|
64
|
+
*
|
|
65
|
+
* No `_gen` generation guard: start()/stop() are a synchronous
|
|
66
|
+
* subscribe/unsubscribe toggle with no asynchronous probe whose stale
|
|
67
|
+
* resolution could race a dispose() — see docs/sensor-tag-design.md §1.5
|
|
68
|
+
* (the same reasoning as NetworkCore, docs/network-tag-design.md §5).
|
|
69
|
+
*
|
|
70
|
+
* Permissions: this Core does not query `navigator.permissions` itself.
|
|
71
|
+
* Compose with `<wcs-permission name="ambient-light-sensor">` instead — see
|
|
72
|
+
* docs/sensor-tag-design.md §"2番目の決定: Permissions APIとの合成".
|
|
73
|
+
*/
|
|
74
|
+
class AmbientLightSensorCore extends EventTarget {
|
|
75
|
+
static wcBindable = {
|
|
76
|
+
protocol: "wc-bindable",
|
|
77
|
+
version: 1,
|
|
78
|
+
properties: [
|
|
79
|
+
{ name: "illuminance", event: "wcs-ambient-light-sensor:reading", getter: (e) => e.detail.illuminance },
|
|
80
|
+
{ name: "error", event: "wcs-ambient-light-sensor:error" },
|
|
81
|
+
],
|
|
82
|
+
commands: [{ name: "start" }, { name: "stop" }],
|
|
83
|
+
};
|
|
84
|
+
_target;
|
|
85
|
+
_reading = NULL_READING;
|
|
86
|
+
_error = null;
|
|
87
|
+
// The live sensor instance while started (null otherwise), kept so stop()
|
|
88
|
+
// can remove its listeners precisely and so start() can detect "already
|
|
89
|
+
// started" without a separate boolean (docs/async-io-node-guidelines.md §3.5
|
|
90
|
+
// idempotency).
|
|
91
|
+
_sensor = null;
|
|
92
|
+
constructor(target) {
|
|
93
|
+
super();
|
|
94
|
+
this._target = target ?? this;
|
|
95
|
+
}
|
|
96
|
+
get illuminance() {
|
|
97
|
+
return this._reading.illuminance;
|
|
98
|
+
}
|
|
99
|
+
get error() {
|
|
100
|
+
return this._error;
|
|
101
|
+
}
|
|
102
|
+
/** No asynchronous probe to await: start()/stop() are synchronous
|
|
103
|
+
* (docs/async-io-node-guidelines.md §3.8 is satisfied trivially, mirroring
|
|
104
|
+
* NetworkCore). */
|
|
105
|
+
get ready() {
|
|
106
|
+
return Promise.resolve();
|
|
107
|
+
}
|
|
108
|
+
// --- State setters ---
|
|
109
|
+
// Deliberately NOT same-value guarded: a `reading` is a fresh sample, not a
|
|
110
|
+
// settled state, so it must dispatch every time even when the values happen
|
|
111
|
+
// to repeat (docs/sensor-tag-design.md §1.1).
|
|
112
|
+
_setReading(reading) {
|
|
113
|
+
this._reading = reading;
|
|
114
|
+
this._target.dispatchEvent(new CustomEvent("wcs-ambient-light-sensor:reading", {
|
|
115
|
+
detail: reading,
|
|
116
|
+
bubbles: true,
|
|
117
|
+
}));
|
|
118
|
+
}
|
|
119
|
+
_setError(error) {
|
|
120
|
+
// Same-value guard (by error name + message): error is state-like, unlike
|
|
121
|
+
// reading — a repeated identical error (same name and message) must not
|
|
122
|
+
// redispatch. Note `error` is also STICKY: nothing calls _setError(null),
|
|
123
|
+
// so a successful (re)start does not clear a prior failure — the monitoring
|
|
124
|
+
// sensor family deliberately keeps the last observed error (docs/sensor-tag-design.md §1.5).
|
|
125
|
+
if (this._error?.error === error?.error && this._error?.message === error?.message)
|
|
126
|
+
return;
|
|
127
|
+
this._error = error;
|
|
128
|
+
this._target.dispatchEvent(new CustomEvent("wcs-ambient-light-sensor:error", {
|
|
129
|
+
detail: error,
|
|
130
|
+
bubbles: true,
|
|
131
|
+
}));
|
|
132
|
+
}
|
|
133
|
+
// --- Public API ---
|
|
134
|
+
/**
|
|
135
|
+
* Start the sensor at the given `frequency` (Hz), or the platform default
|
|
136
|
+
* when omitted. Idempotent while already started: a redundant start() does
|
|
137
|
+
* not construct a second sensor instance (which would leak the first).
|
|
138
|
+
* Restart with a different frequency via stop() + start().
|
|
139
|
+
*
|
|
140
|
+
* Synchronous, mirroring the native `Sensor.start()` — never throws
|
|
141
|
+
* (docs/async-io-node-guidelines.md §3.6): both "unsupported" and a
|
|
142
|
+
* synchronous constructor exception (permission denial, feature-policy
|
|
143
|
+
* block) are converted to the `error` property instead of propagating.
|
|
144
|
+
*/
|
|
145
|
+
start(frequency) {
|
|
146
|
+
if (this._sensor)
|
|
147
|
+
return;
|
|
148
|
+
const sensor = this._createSensor(frequency);
|
|
149
|
+
if (!sensor)
|
|
150
|
+
return;
|
|
151
|
+
sensor.addEventListener("reading", this._onReading);
|
|
152
|
+
sensor.addEventListener("error", this._onError);
|
|
153
|
+
this._sensor = sensor;
|
|
154
|
+
try {
|
|
155
|
+
sensor.start();
|
|
156
|
+
}
|
|
157
|
+
catch (e) {
|
|
158
|
+
// Defensive: the platform contract says start()/stop() do not throw
|
|
159
|
+
// (failures surface via the 'error' event), but never-throw is a hard
|
|
160
|
+
// requirement here, so guard against a non-conformant implementation
|
|
161
|
+
// too.
|
|
162
|
+
this._teardownSensor();
|
|
163
|
+
this._setError({ error: e?.name ?? "error", message: e?.message ?? String(e) });
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
/** Stop the sensor and detach its listeners. Safe to call when not started. */
|
|
167
|
+
stop() {
|
|
168
|
+
if (!this._sensor)
|
|
169
|
+
return;
|
|
170
|
+
try {
|
|
171
|
+
this._sensor.stop();
|
|
172
|
+
}
|
|
173
|
+
catch {
|
|
174
|
+
// Never-throw defensive guard, symmetric with start(). Teardown below
|
|
175
|
+
// still runs so listeners are detached regardless.
|
|
176
|
+
}
|
|
177
|
+
this._teardownSensor();
|
|
178
|
+
}
|
|
179
|
+
/** Lifecycle alias for start(), so the Shell's connectedCallback can drive
|
|
180
|
+
* this Core the same way as other IO nodes' observe()/dispose() pair. No
|
|
181
|
+
* asynchronous probe, so the returned promise always resolves immediately. */
|
|
182
|
+
observe(frequency) {
|
|
183
|
+
this.start(frequency);
|
|
184
|
+
return this.ready;
|
|
185
|
+
}
|
|
186
|
+
/** Lifecycle alias for stop(), invoked from the Shell's disconnectedCallback. */
|
|
187
|
+
dispose() {
|
|
188
|
+
this.stop();
|
|
189
|
+
}
|
|
190
|
+
// --- Internal ---
|
|
191
|
+
// Both call sites (start()'s catch, stop()) only ever invoke this once
|
|
192
|
+
// `this._sensor` is already known non-null, so there is no null-guard here
|
|
193
|
+
// (nothing to defend against).
|
|
194
|
+
_teardownSensor() {
|
|
195
|
+
this._sensor.removeEventListener("reading", this._onReading);
|
|
196
|
+
this._sensor.removeEventListener("error", this._onError);
|
|
197
|
+
this._sensor = null;
|
|
198
|
+
}
|
|
199
|
+
/**
|
|
200
|
+
* Construct the platform `AmbientLightSensor`, guarding both non-support and a
|
|
201
|
+
* synchronous constructor exception. Never calls the raw `new AmbientLightSensor(...)`
|
|
202
|
+
* anywhere else in this class — see docs/sensor-tag-design.md §1.5.
|
|
203
|
+
*
|
|
204
|
+
* API resolution is call-time (docs/async-io-node-guidelines.md §3.7):
|
|
205
|
+
* re-checked on every start(), never cached, so tests can install/remove the
|
|
206
|
+
* global freely and an unsupported environment is always reported correctly.
|
|
207
|
+
*/
|
|
208
|
+
_createSensor(frequency) {
|
|
209
|
+
const Ctor = globalThis.AmbientLightSensor;
|
|
210
|
+
if (typeof Ctor !== "function") {
|
|
211
|
+
this._setError({ error: "unsupported", message: "AmbientLightSensor is not supported" });
|
|
212
|
+
return null;
|
|
213
|
+
}
|
|
214
|
+
try {
|
|
215
|
+
return new Ctor(frequency !== undefined ? { frequency } : undefined);
|
|
216
|
+
}
|
|
217
|
+
catch (e) {
|
|
218
|
+
// SecurityError (permission denial, feature-policy block) or any other
|
|
219
|
+
// synchronous construction failure. Mirrors the FetchCore._doFetch
|
|
220
|
+
// try/catch structure (packages/fetch/src/core/FetchCore.ts) — a
|
|
221
|
+
// synchronous constructor call here instead of an awaited fetch().
|
|
222
|
+
this._setError({ error: e?.name ?? "error", message: e?.message ?? String(e) });
|
|
223
|
+
return null;
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
_onReading = (event) => {
|
|
227
|
+
const sensor = event.target;
|
|
228
|
+
this._setReading({ illuminance: sensor.illuminance });
|
|
229
|
+
};
|
|
230
|
+
_onError = (event) => {
|
|
231
|
+
const err = event.error;
|
|
232
|
+
// Fallback is a meaningful constant, NOT String(err): a SensorErrorEvent
|
|
233
|
+
// without an `error` field would otherwise stringify `undefined` into the
|
|
234
|
+
// literal message "undefined" (aligned across the sensor family).
|
|
235
|
+
this._setError({ error: err?.name ?? "error", message: err?.message ?? "Sensor error" });
|
|
236
|
+
};
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
/**
|
|
240
|
+
* `<wcs-ambient-light-sensor>` — declarative Generic Sensor API (`AmbientLightSensor`)
|
|
241
|
+
* monitor + start/stop control.
|
|
242
|
+
*
|
|
243
|
+
* Unlike `<wcs-network>` / `<wcs-permission>` (pure monitors), this Shell is a
|
|
244
|
+
* bidirectional node: `start`/`stop` commands (command-token: state → element)
|
|
245
|
+
* alongside the `illuminance`/`error` observable surface (event-token: element →
|
|
246
|
+
* state). The `frequency` attribute is the sole configuration input, forwarded
|
|
247
|
+
* to the platform `AmbientLightSensor` constructor's `{ frequency }` option
|
|
248
|
+
* (docs/sensor-tag-design.md §1.2). The getter normalizes it: a non-finite or
|
|
249
|
+
* non-positive value (NaN, 0, negative) reads back as `null` — meaning "no
|
|
250
|
+
* frequency specified" — so start() falls back to the platform default rather
|
|
251
|
+
* than forwarding a value the sensor would reject. Any positive finite value is
|
|
252
|
+
* passed through verbatim (no upper-bound clamping — an out-of-range-but-positive
|
|
253
|
+
* rate is still left to the browser/sensor to reject via `error`).
|
|
254
|
+
*
|
|
255
|
+
* Permission handling is intentionally NOT implemented here. Compose with
|
|
256
|
+
* `<wcs-permission name="ambient-light-sensor">` instead (see the README's permission
|
|
257
|
+
* example, "Gate on permission, then start", and docs/sensor-tag-design.md).
|
|
258
|
+
*/
|
|
259
|
+
class WcsAmbientLightSensor extends HTMLElement {
|
|
260
|
+
static hasConnectedCallbackPromise = true;
|
|
261
|
+
static wcBindable = {
|
|
262
|
+
...AmbientLightSensorCore.wcBindable,
|
|
263
|
+
inputs: [{ name: "frequency" }],
|
|
264
|
+
// Core の commands をそのまま継承(単一情報源)。
|
|
265
|
+
commands: AmbientLightSensorCore.wcBindable.commands,
|
|
266
|
+
};
|
|
267
|
+
_core;
|
|
268
|
+
_connectedCallbackPromise = Promise.resolve();
|
|
269
|
+
constructor() {
|
|
270
|
+
super();
|
|
271
|
+
this._core = new AmbientLightSensorCore(this);
|
|
272
|
+
}
|
|
273
|
+
// --- Attribute accessors ---
|
|
274
|
+
/**
|
|
275
|
+
* Sampling frequency in Hz. Reads back `null` when unset, blank, or when the
|
|
276
|
+
* attribute does not parse to a positive finite number (NaN, `"0"`, negative)
|
|
277
|
+
* — in every such "no usable value" case the platform default applies.
|
|
278
|
+
*
|
|
279
|
+
* Note the deliberate set/get asymmetry: `set frequency(0)` (or any
|
|
280
|
+
* non-positive/non-finite value) still writes the attribute verbatim for
|
|
281
|
+
* transparency/inspectability, but the getter normalizes it back to `null`.
|
|
282
|
+
* A round-trip through a non-positive value therefore does NOT preserve it —
|
|
283
|
+
* that value carries no valid sampling meaning, so it is treated as "unset"
|
|
284
|
+
* on read. Only positive finite frequencies survive a set→get round-trip.
|
|
285
|
+
*/
|
|
286
|
+
get frequency() {
|
|
287
|
+
const attr = this.getAttribute("frequency");
|
|
288
|
+
if (attr === null || attr.trim() === "")
|
|
289
|
+
return null;
|
|
290
|
+
const parsed = Number(attr);
|
|
291
|
+
return Number.isFinite(parsed) && parsed > 0 ? parsed : null;
|
|
292
|
+
}
|
|
293
|
+
set frequency(value) {
|
|
294
|
+
if (value === null || value === undefined) {
|
|
295
|
+
this.removeAttribute("frequency");
|
|
296
|
+
}
|
|
297
|
+
else {
|
|
298
|
+
this.setAttribute("frequency", String(value));
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
// --- Core delegated getters ---
|
|
302
|
+
get illuminance() {
|
|
303
|
+
return this._core.illuminance;
|
|
304
|
+
}
|
|
305
|
+
get error() {
|
|
306
|
+
return this._core.error;
|
|
307
|
+
}
|
|
308
|
+
get connectedCallbackPromise() {
|
|
309
|
+
return this._connectedCallbackPromise;
|
|
310
|
+
}
|
|
311
|
+
// --- Commands ---
|
|
312
|
+
start() {
|
|
313
|
+
this._core.start(this.frequency ?? undefined);
|
|
314
|
+
}
|
|
315
|
+
stop() {
|
|
316
|
+
this._core.stop();
|
|
317
|
+
}
|
|
318
|
+
// --- Lifecycle ---
|
|
319
|
+
// Deliberately does NOT auto-start the sensor on connect. Unlike
|
|
320
|
+
// Geolocation (whose default phase acquires a fix immediately unless
|
|
321
|
+
// `manual` is set), AmbientLightSensor has no such "connect implies observing"
|
|
322
|
+
// precedent in the design doc (docs/sensor-tag-design.md §1.3):
|
|
323
|
+
// start/stop are the only commands, so connecting the element merely makes
|
|
324
|
+
// it inert until a command-token `start` (or the `start()` method) is
|
|
325
|
+
// invoked. This also keeps behavior predictable when composed with
|
|
326
|
+
// `<wcs-permission name="ambient-light-sensor">`: the caller decides when to start,
|
|
327
|
+
// typically gated on `granted`.
|
|
328
|
+
connectedCallback() {
|
|
329
|
+
this.style.display = "none";
|
|
330
|
+
// No asynchronous probe to await (§3.8); kept for SSR uniformity with
|
|
331
|
+
// other IO nodes.
|
|
332
|
+
this._connectedCallbackPromise = this._core.ready;
|
|
333
|
+
}
|
|
334
|
+
disconnectedCallback() {
|
|
335
|
+
this._core.dispose();
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
function registerComponents() {
|
|
340
|
+
if (!customElements.get(config.tagNames.ambientLightSensor)) {
|
|
341
|
+
customElements.define(config.tagNames.ambientLightSensor, WcsAmbientLightSensor);
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
function bootstrapAmbientLightSensor(userConfig) {
|
|
346
|
+
if (userConfig) {
|
|
347
|
+
setConfig(userConfig);
|
|
348
|
+
}
|
|
349
|
+
registerComponents();
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
export { AmbientLightSensorCore, WcsAmbientLightSensor, bootstrapAmbientLightSensor, getConfig };
|
|
353
|
+
//# sourceMappingURL=index.esm.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.esm.js","sources":["../src/config.ts","../src/core/AmbientLightSensorCore.ts","../src/components/AmbientLightSensor.ts","../src/registerComponents.ts","../src/bootstrapAmbientLightSensor.ts"],"sourcesContent":["import { IConfig, IWritableConfig } from \"./types.js\";\n\ninterface IInternalConfig extends IConfig {\n tagNames: {\n ambientLightSensor: string;\n };\n}\n\nconst _config: IInternalConfig = {\n tagNames: {\n ambientLightSensor: \"wcs-ambient-light-sensor\",\n },\n};\n\nfunction deepFreeze<T>(obj: T): T {\n if (obj === null || typeof obj !== \"object\") return obj;\n Object.freeze(obj);\n for (const key of Object.keys(obj)) {\n deepFreeze((obj as Record<string, unknown>)[key]);\n }\n return obj;\n}\n\nfunction deepClone<T>(obj: T): T {\n if (obj === null || typeof obj !== \"object\") return obj;\n const clone: Record<string, unknown> = {};\n for (const key of Object.keys(obj)) {\n clone[key] = deepClone((obj as Record<string, unknown>)[key]);\n }\n return clone as T;\n}\n\nlet frozenConfig: IConfig | null = null;\n\nexport const config: IConfig = _config as IConfig;\n\nexport function getConfig(): IConfig {\n if (!frozenConfig) {\n frozenConfig = deepFreeze(deepClone(_config));\n }\n return frozenConfig;\n}\n\nexport function setConfig(partialConfig: IWritableConfig): void {\n if (partialConfig.tagNames) {\n Object.assign(_config.tagNames, partialConfig.tagNames);\n }\n frozenConfig = null;\n}\n","import { IWcBindable, WcsAmbientLightSensorReading, WcsAmbientLightSensorErrorDetail } from \"../types.js\";\n\nconst NULL_READING: WcsAmbientLightSensorReading = Object.freeze({ illuminance: null });\n\n/**\n * Headless AmbientLightSensor primitive. A thin, framework-agnostic wrapper around\n * the Generic Sensor API's `AmbientLightSensor` class exposed through the\n * wc-bindable protocol.\n *\n * The platform `Sensor` base class (shared by `Accelerometer` / `Gyroscope` /\n * `Magnetometer` / `AmbientLightSensor`) reports failure through an `'error'`\n * event rather than a rejected promise, so this Core can satisfy never-throw\n * (docs/async-io-node-guidelines.md §3.6) by simply forwarding that event —\n * see docs/sensor-tag-design.md §0. The one place a synchronous\n * exception *can* still escape the platform API is the `AmbientLightSensor`\n * constructor itself (e.g. `SecurityError` on permission denial or a\n * feature-policy block); `_createSensor()` wraps that single call in\n * try/catch, mirroring FetchCore's `_doFetch` try/catch around\n * `globalThis.fetch` (packages/fetch/src/core/FetchCore.ts).\n *\n * `illuminance` is a single getter derived from the `wcs-ambient-light-sensor:reading`\n * event (unlike Accelerometer/Gyroscope/Magnetometer's x/y/z, this sensor\n * reports one scalar — docs/sensor-tag-design.md §2). `reading`\n * is an event-like signal (a fresh sample every time, not a settled state) and\n * is therefore deliberately NOT same-value guarded — every sample dispatches.\n * `error` is state-like (denial / unsupported does not change from tick to\n * tick) and IS same-value guarded, and is published on its own\n * `wcs-ambient-light-sensor:error` event, independent of `reading`.\n *\n * No `_gen` generation guard: start()/stop() are a synchronous\n * subscribe/unsubscribe toggle with no asynchronous probe whose stale\n * resolution could race a dispose() — see docs/sensor-tag-design.md §1.5\n * (the same reasoning as NetworkCore, docs/network-tag-design.md §5).\n *\n * Permissions: this Core does not query `navigator.permissions` itself.\n * Compose with `<wcs-permission name=\"ambient-light-sensor\">` instead — see\n * docs/sensor-tag-design.md §\"2番目の決定: Permissions APIとの合成\".\n */\nexport class AmbientLightSensorCore extends EventTarget {\n static wcBindable: IWcBindable = {\n protocol: \"wc-bindable\",\n version: 1,\n properties: [\n { name: \"illuminance\", event: \"wcs-ambient-light-sensor:reading\", getter: (e: Event) => (e as CustomEvent).detail.illuminance },\n { name: \"error\", event: \"wcs-ambient-light-sensor:error\" },\n ],\n commands: [{ name: \"start\" }, { name: \"stop\" }],\n };\n\n private _target: EventTarget;\n private _reading: WcsAmbientLightSensorReading = NULL_READING;\n private _error: WcsAmbientLightSensorErrorDetail | null = null;\n\n // The live sensor instance while started (null otherwise), kept so stop()\n // can remove its listeners precisely and so start() can detect \"already\n // started\" without a separate boolean (docs/async-io-node-guidelines.md §3.5\n // idempotency).\n private _sensor: (EventTarget & { start(): void; stop(): void }) | null = null;\n\n constructor(target?: EventTarget) {\n super();\n this._target = target ?? this;\n }\n\n get illuminance(): number | null {\n return this._reading.illuminance;\n }\n\n get error(): WcsAmbientLightSensorErrorDetail | null {\n return this._error;\n }\n\n /** No asynchronous probe to await: start()/stop() are synchronous\n * (docs/async-io-node-guidelines.md §3.8 is satisfied trivially, mirroring\n * NetworkCore). */\n get ready(): Promise<void> {\n return Promise.resolve();\n }\n\n // --- State setters ---\n\n // Deliberately NOT same-value guarded: a `reading` is a fresh sample, not a\n // settled state, so it must dispatch every time even when the values happen\n // to repeat (docs/sensor-tag-design.md §1.1).\n private _setReading(reading: WcsAmbientLightSensorReading): void {\n this._reading = reading;\n this._target.dispatchEvent(new CustomEvent(\"wcs-ambient-light-sensor:reading\", {\n detail: reading,\n bubbles: true,\n }));\n }\n\n private _setError(error: WcsAmbientLightSensorErrorDetail | null): void {\n // Same-value guard (by error name + message): error is state-like, unlike\n // reading — a repeated identical error (same name and message) must not\n // redispatch. Note `error` is also STICKY: nothing calls _setError(null),\n // so a successful (re)start does not clear a prior failure — the monitoring\n // sensor family deliberately keeps the last observed error (docs/sensor-tag-design.md §1.5).\n if (this._error?.error === error?.error && this._error?.message === error?.message) return;\n this._error = error;\n this._target.dispatchEvent(new CustomEvent(\"wcs-ambient-light-sensor:error\", {\n detail: error,\n bubbles: true,\n }));\n }\n\n // --- Public API ---\n\n /**\n * Start the sensor at the given `frequency` (Hz), or the platform default\n * when omitted. Idempotent while already started: a redundant start() does\n * not construct a second sensor instance (which would leak the first).\n * Restart with a different frequency via stop() + start().\n *\n * Synchronous, mirroring the native `Sensor.start()` — never throws\n * (docs/async-io-node-guidelines.md §3.6): both \"unsupported\" and a\n * synchronous constructor exception (permission denial, feature-policy\n * block) are converted to the `error` property instead of propagating.\n */\n start(frequency?: number): void {\n if (this._sensor) return;\n const sensor = this._createSensor(frequency);\n if (!sensor) return;\n sensor.addEventListener(\"reading\", this._onReading as EventListener);\n sensor.addEventListener(\"error\", this._onError as EventListener);\n this._sensor = sensor;\n try {\n sensor.start();\n } catch (e: any) {\n // Defensive: the platform contract says start()/stop() do not throw\n // (failures surface via the 'error' event), but never-throw is a hard\n // requirement here, so guard against a non-conformant implementation\n // too.\n this._teardownSensor();\n this._setError({ error: e?.name ?? \"error\", message: e?.message ?? String(e) });\n }\n }\n\n /** Stop the sensor and detach its listeners. Safe to call when not started. */\n stop(): void {\n if (!this._sensor) return;\n try {\n this._sensor.stop();\n } catch {\n // Never-throw defensive guard, symmetric with start(). Teardown below\n // still runs so listeners are detached regardless.\n }\n this._teardownSensor();\n }\n\n /** Lifecycle alias for start(), so the Shell's connectedCallback can drive\n * this Core the same way as other IO nodes' observe()/dispose() pair. No\n * asynchronous probe, so the returned promise always resolves immediately. */\n observe(frequency?: number): Promise<void> {\n this.start(frequency);\n return this.ready;\n }\n\n /** Lifecycle alias for stop(), invoked from the Shell's disconnectedCallback. */\n dispose(): void {\n this.stop();\n }\n\n // --- Internal ---\n\n // Both call sites (start()'s catch, stop()) only ever invoke this once\n // `this._sensor` is already known non-null, so there is no null-guard here\n // (nothing to defend against).\n private _teardownSensor(): void {\n this._sensor!.removeEventListener(\"reading\", this._onReading as EventListener);\n this._sensor!.removeEventListener(\"error\", this._onError as EventListener);\n this._sensor = null;\n }\n\n /**\n * Construct the platform `AmbientLightSensor`, guarding both non-support and a\n * synchronous constructor exception. Never calls the raw `new AmbientLightSensor(...)`\n * anywhere else in this class — see docs/sensor-tag-design.md §1.5.\n *\n * API resolution is call-time (docs/async-io-node-guidelines.md §3.7):\n * re-checked on every start(), never cached, so tests can install/remove the\n * global freely and an unsupported environment is always reported correctly.\n */\n private _createSensor(frequency?: number): (EventTarget & { start(): void; stop(): void }) | null {\n const Ctor = (globalThis as any).AmbientLightSensor;\n if (typeof Ctor !== \"function\") {\n this._setError({ error: \"unsupported\", message: \"AmbientLightSensor is not supported\" });\n return null;\n }\n try {\n return new Ctor(frequency !== undefined ? { frequency } : undefined);\n } catch (e: any) {\n // SecurityError (permission denial, feature-policy block) or any other\n // synchronous construction failure. Mirrors the FetchCore._doFetch\n // try/catch structure (packages/fetch/src/core/FetchCore.ts) — a\n // synchronous constructor call here instead of an awaited fetch().\n this._setError({ error: e?.name ?? \"error\", message: e?.message ?? String(e) });\n return null;\n }\n }\n\n private _onReading = (event: Event): void => {\n const sensor = event.target as unknown as { illuminance: number | null };\n this._setReading({ illuminance: sensor.illuminance });\n };\n\n private _onError = (event: Event): void => {\n const err = (event as any).error as { name?: string; message?: string } | undefined;\n // Fallback is a meaningful constant, NOT String(err): a SensorErrorEvent\n // without an `error` field would otherwise stringify `undefined` into the\n // literal message \"undefined\" (aligned across the sensor family).\n this._setError({ error: err?.name ?? \"error\", message: err?.message ?? \"Sensor error\" });\n };\n}\n","import { IWcBindable, WcsAmbientLightSensorErrorDetail } from \"../types.js\";\nimport { AmbientLightSensorCore } from \"../core/AmbientLightSensorCore.js\";\n\n/**\n * `<wcs-ambient-light-sensor>` — declarative Generic Sensor API (`AmbientLightSensor`)\n * monitor + start/stop control.\n *\n * Unlike `<wcs-network>` / `<wcs-permission>` (pure monitors), this Shell is a\n * bidirectional node: `start`/`stop` commands (command-token: state → element)\n * alongside the `illuminance`/`error` observable surface (event-token: element →\n * state). The `frequency` attribute is the sole configuration input, forwarded\n * to the platform `AmbientLightSensor` constructor's `{ frequency }` option\n * (docs/sensor-tag-design.md §1.2). The getter normalizes it: a non-finite or\n * non-positive value (NaN, 0, negative) reads back as `null` — meaning \"no\n * frequency specified\" — so start() falls back to the platform default rather\n * than forwarding a value the sensor would reject. Any positive finite value is\n * passed through verbatim (no upper-bound clamping — an out-of-range-but-positive\n * rate is still left to the browser/sensor to reject via `error`).\n *\n * Permission handling is intentionally NOT implemented here. Compose with\n * `<wcs-permission name=\"ambient-light-sensor\">` instead (see the README's permission\n * example, \"Gate on permission, then start\", and docs/sensor-tag-design.md).\n */\nexport class WcsAmbientLightSensor extends HTMLElement {\n static hasConnectedCallbackPromise = true;\n\n static wcBindable: IWcBindable = {\n ...AmbientLightSensorCore.wcBindable,\n inputs: [{ name: \"frequency\" }],\n // Core の commands をそのまま継承(単一情報源)。\n commands: AmbientLightSensorCore.wcBindable.commands,\n };\n\n private _core: AmbientLightSensorCore;\n private _connectedCallbackPromise: Promise<void> = Promise.resolve();\n\n constructor() {\n super();\n this._core = new AmbientLightSensorCore(this);\n }\n\n // --- Attribute accessors ---\n\n /**\n * Sampling frequency in Hz. Reads back `null` when unset, blank, or when the\n * attribute does not parse to a positive finite number (NaN, `\"0\"`, negative)\n * — in every such \"no usable value\" case the platform default applies.\n *\n * Note the deliberate set/get asymmetry: `set frequency(0)` (or any\n * non-positive/non-finite value) still writes the attribute verbatim for\n * transparency/inspectability, but the getter normalizes it back to `null`.\n * A round-trip through a non-positive value therefore does NOT preserve it —\n * that value carries no valid sampling meaning, so it is treated as \"unset\"\n * on read. Only positive finite frequencies survive a set→get round-trip.\n */\n get frequency(): number | null {\n const attr = this.getAttribute(\"frequency\");\n if (attr === null || attr.trim() === \"\") return null;\n const parsed = Number(attr);\n return Number.isFinite(parsed) && parsed > 0 ? parsed : null;\n }\n\n set frequency(value: number | null | undefined) {\n if (value === null || value === undefined) {\n this.removeAttribute(\"frequency\");\n } else {\n this.setAttribute(\"frequency\", String(value));\n }\n }\n\n // --- Core delegated getters ---\n\n get illuminance(): number | null {\n return this._core.illuminance;\n }\n\n get error(): WcsAmbientLightSensorErrorDetail | null {\n return this._core.error;\n }\n\n get connectedCallbackPromise(): Promise<void> {\n return this._connectedCallbackPromise;\n }\n\n // --- Commands ---\n\n start(): void {\n this._core.start(this.frequency ?? undefined);\n }\n\n stop(): void {\n this._core.stop();\n }\n\n // --- Lifecycle ---\n\n // Deliberately does NOT auto-start the sensor on connect. Unlike\n // Geolocation (whose default phase acquires a fix immediately unless\n // `manual` is set), AmbientLightSensor has no such \"connect implies observing\"\n // precedent in the design doc (docs/sensor-tag-design.md §1.3):\n // start/stop are the only commands, so connecting the element merely makes\n // it inert until a command-token `start` (or the `start()` method) is\n // invoked. This also keeps behavior predictable when composed with\n // `<wcs-permission name=\"ambient-light-sensor\">`: the caller decides when to start,\n // typically gated on `granted`.\n connectedCallback(): void {\n this.style.display = \"none\";\n // No asynchronous probe to await (§3.8); kept for SSR uniformity with\n // other IO nodes.\n this._connectedCallbackPromise = this._core.ready;\n }\n\n disconnectedCallback(): void {\n this._core.dispose();\n }\n}\n","import { WcsAmbientLightSensor } from \"./components/AmbientLightSensor.js\";\nimport { config } from \"./config.js\";\n\nexport function registerComponents(): void {\n if (!customElements.get(config.tagNames.ambientLightSensor)) {\n customElements.define(config.tagNames.ambientLightSensor, WcsAmbientLightSensor);\n }\n}\n","import { setConfig } from \"./config.js\";\nimport { registerComponents } from \"./registerComponents.js\";\nimport { IWritableConfig } from \"./types.js\";\n\nexport function bootstrapAmbientLightSensor(userConfig?: IWritableConfig): void {\n if (userConfig) {\n setConfig(userConfig);\n }\n registerComponents();\n}\n"],"names":[],"mappings":"AAQA,MAAM,OAAO,GAAoB;AAC/B,IAAA,QAAQ,EAAE;AACR,QAAA,kBAAkB,EAAE,0BAA0B;AAC/C,KAAA;CACF;AAED,SAAS,UAAU,CAAI,GAAM,EAAA;AAC3B,IAAA,IAAI,GAAG,KAAK,IAAI,IAAI,OAAO,GAAG,KAAK,QAAQ;AAAE,QAAA,OAAO,GAAG;AACvD,IAAA,MAAM,CAAC,MAAM,CAAC,GAAG,CAAC;IAClB,KAAK,MAAM,GAAG,IAAI,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE;AAClC,QAAA,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KAAK;IACzB;AAEA,IAAA,IAAI,wBAAwB,GAAA;QAC1B,OAAO,IAAI,CAAC,yBAAyB;IACvC;;IAIA,KAAK,GAAA;QACH,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,IAAI,CAAC,SAAS,IAAI,SAAS,CAAC;IAC/C;IAEA,IAAI,GAAA;AACF,QAAA,IAAI,CAAC,KAAK,CAAC,IAAI,EAAE;IACnB;;;;;;;;;;;IAaA,iBAAiB,GAAA;AACf,QAAA,IAAI,CAAC,KAAK,CAAC,OAAO,GAAG,MAAM;;;QAG3B,IAAI,CAAC,yBAAyB,GAAG,IAAI,CAAC,KAAK,CAAC,KAAK;IACnD;IAEA,oBAAoB,GAAA;AAClB,QAAA,IAAI,CAAC,KAAK,CAAC,OAAO,EAAE;IACtB;;;SC/Gc,kBAAkB,GAAA;AAChC,IAAA,IAAI,CAAC,cAAc,CAAC,GAAG,CAAC,MAAM,CAAC,QAAQ,CAAC,kBAAkB,CAAC,EAAE;QAC3D,cAAc,CAAC,MAAM,CAAC,MAAM,CAAC,QAAQ,CAAC,kBAAkB,EAAE,qBAAqB,CAAC;IAClF;AACF;;ACHM,SAAU,2BAA2B,CAAC,UAA4B,EAAA;IACtE,IAAI,UAAU,EAAE;QACd,SAAS,CAAC,UAAU,CAAC;IACvB;AACA,IAAA,kBAAkB,EAAE;AACtB;;;;"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const e={tagNames:{ambientLightSensor:"wcs-ambient-light-sensor"}};function r(e){if(null===e||"object"!=typeof e)return e;Object.freeze(e);for(const t of Object.keys(e))r(e[t]);return e}function t(e){if(null===e||"object"!=typeof e)return e;const r={};for(const s of Object.keys(e))r[s]=t(e[s]);return r}let s=null;const n=e;function i(){return s||(s=r(t(e))),s}const o=Object.freeze({illuminance:null});class a extends EventTarget{static wcBindable={protocol:"wc-bindable",version:1,properties:[{name:"illuminance",event:"wcs-ambient-light-sensor:reading",getter:e=>e.detail.illuminance},{name:"error",event:"wcs-ambient-light-sensor:error"}],commands:[{name:"start"},{name:"stop"}]};_target;_reading=o;_error=null;_sensor=null;constructor(e){super(),this._target=e??this}get illuminance(){return this._reading.illuminance}get error(){return this._error}get ready(){return Promise.resolve()}_setReading(e){this._reading=e,this._target.dispatchEvent(new CustomEvent("wcs-ambient-light-sensor:reading",{detail:e,bubbles:!0}))}_setError(e){this._error?.error===e?.error&&this._error?.message===e?.message||(this._error=e,this._target.dispatchEvent(new CustomEvent("wcs-ambient-light-sensor:error",{detail:e,bubbles:!0})))}start(e){if(this._sensor)return;const r=this._createSensor(e);if(r){r.addEventListener("reading",this._onReading),r.addEventListener("error",this._onError),this._sensor=r;try{r.start()}catch(e){this._teardownSensor(),this._setError({error:e?.name??"error",message:e?.message??String(e)})}}}stop(){if(this._sensor){try{this._sensor.stop()}catch{}this._teardownSensor()}}observe(e){return this.start(e),this.ready}dispose(){this.stop()}_teardownSensor(){this._sensor.removeEventListener("reading",this._onReading),this._sensor.removeEventListener("error",this._onError),this._sensor=null}_createSensor(e){const r=globalThis.AmbientLightSensor;if("function"!=typeof r)return this._setError({error:"unsupported",message:"AmbientLightSensor is not supported"}),null;try{return new r(void 0!==e?{frequency:e}:void 0)}catch(e){return this._setError({error:e?.name??"error",message:e?.message??String(e)}),null}}_onReading=e=>{const r=e.target;this._setReading({illuminance:r.illuminance})};_onError=e=>{const r=e.error;this._setError({error:r?.name??"error",message:r?.message??"Sensor error"})}}class c extends HTMLElement{static hasConnectedCallbackPromise=!0;static wcBindable={...a.wcBindable,inputs:[{name:"frequency"}],commands:a.wcBindable.commands};_core;_connectedCallbackPromise=Promise.resolve();constructor(){super(),this._core=new a(this)}get frequency(){const e=this.getAttribute("frequency");if(null===e||""===e.trim())return null;const r=Number(e);return Number.isFinite(r)&&r>0?r:null}set frequency(e){null==e?this.removeAttribute("frequency"):this.setAttribute("frequency",String(e))}get illuminance(){return this._core.illuminance}get error(){return this._core.error}get connectedCallbackPromise(){return this._connectedCallbackPromise}start(){this._core.start(this.frequency??void 0)}stop(){this._core.stop()}connectedCallback(){this.style.display="none",this._connectedCallbackPromise=this._core.ready}disconnectedCallback(){this._core.dispose()}}function l(r){var t;r&&((t=r).tagNames&&Object.assign(e.tagNames,t.tagNames),s=null),customElements.get(n.tagNames.ambientLightSensor)||customElements.define(n.tagNames.ambientLightSensor,c)}export{a as AmbientLightSensorCore,c as WcsAmbientLightSensor,l as bootstrapAmbientLightSensor,i as getConfig};
|
|
2
|
+
//# sourceMappingURL=index.esm.min.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.esm.min.js","sources":["../src/config.ts","../src/core/AmbientLightSensorCore.ts","../src/components/AmbientLightSensor.ts","../src/bootstrapAmbientLightSensor.ts","../src/registerComponents.ts"],"sourcesContent":["import { IConfig, IWritableConfig } from \"./types.js\";\n\ninterface IInternalConfig extends IConfig {\n tagNames: {\n ambientLightSensor: string;\n };\n}\n\nconst _config: IInternalConfig = {\n tagNames: {\n ambientLightSensor: \"wcs-ambient-light-sensor\",\n },\n};\n\nfunction deepFreeze<T>(obj: T): T {\n if (obj === null || typeof obj !== \"object\") return obj;\n Object.freeze(obj);\n for (const key of Object.keys(obj)) {\n deepFreeze((obj as Record<string, unknown>)[key]);\n }\n return obj;\n}\n\nfunction deepClone<T>(obj: T): T {\n if (obj === null || typeof obj !== \"object\") return obj;\n const clone: Record<string, unknown> = {};\n for (const key of Object.keys(obj)) {\n clone[key] = deepClone((obj as Record<string, unknown>)[key]);\n }\n return clone as T;\n}\n\nlet frozenConfig: IConfig | null = null;\n\nexport const config: IConfig = _config as IConfig;\n\nexport function getConfig(): IConfig {\n if (!frozenConfig) {\n frozenConfig = deepFreeze(deepClone(_config));\n }\n return frozenConfig;\n}\n\nexport function setConfig(partialConfig: IWritableConfig): void {\n if (partialConfig.tagNames) {\n Object.assign(_config.tagNames, partialConfig.tagNames);\n }\n frozenConfig = null;\n}\n","import { IWcBindable, WcsAmbientLightSensorReading, WcsAmbientLightSensorErrorDetail } from \"../types.js\";\n\nconst NULL_READING: WcsAmbientLightSensorReading = Object.freeze({ illuminance: null });\n\n/**\n * Headless AmbientLightSensor primitive. A thin, framework-agnostic wrapper around\n * the Generic Sensor API's `AmbientLightSensor` class exposed through the\n * wc-bindable protocol.\n *\n * The platform `Sensor` base class (shared by `Accelerometer` / `Gyroscope` /\n * `Magnetometer` / `AmbientLightSensor`) reports failure through an `'error'`\n * event rather than a rejected promise, so this Core can satisfy never-throw\n * (docs/async-io-node-guidelines.md §3.6) by simply forwarding that event —\n * see docs/sensor-tag-design.md §0. The one place a synchronous\n * exception *can* still escape the platform API is the `AmbientLightSensor`\n * constructor itself (e.g. `SecurityError` on permission denial or a\n * feature-policy block); `_createSensor()` wraps that single call in\n * try/catch, mirroring FetchCore's `_doFetch` try/catch around\n * `globalThis.fetch` (packages/fetch/src/core/FetchCore.ts).\n *\n * `illuminance` is a single getter derived from the `wcs-ambient-light-sensor:reading`\n * event (unlike Accelerometer/Gyroscope/Magnetometer's x/y/z, this sensor\n * reports one scalar — docs/sensor-tag-design.md §2). `reading`\n * is an event-like signal (a fresh sample every time, not a settled state) and\n * is therefore deliberately NOT same-value guarded — every sample dispatches.\n * `error` is state-like (denial / unsupported does not change from tick to\n * tick) and IS same-value guarded, and is published on its own\n * `wcs-ambient-light-sensor:error` event, independent of `reading`.\n *\n * No `_gen` generation guard: start()/stop() are a synchronous\n * subscribe/unsubscribe toggle with no asynchronous probe whose stale\n * resolution could race a dispose() — see docs/sensor-tag-design.md §1.5\n * (the same reasoning as NetworkCore, docs/network-tag-design.md §5).\n *\n * Permissions: this Core does not query `navigator.permissions` itself.\n * Compose with `<wcs-permission name=\"ambient-light-sensor\">` instead — see\n * docs/sensor-tag-design.md §\"2番目の決定: Permissions APIとの合成\".\n */\nexport class AmbientLightSensorCore extends EventTarget {\n static wcBindable: IWcBindable = {\n protocol: \"wc-bindable\",\n version: 1,\n properties: [\n { name: \"illuminance\", event: \"wcs-ambient-light-sensor:reading\", getter: (e: Event) => (e as CustomEvent).detail.illuminance },\n { name: \"error\", event: \"wcs-ambient-light-sensor:error\" },\n ],\n commands: [{ name: \"start\" }, { name: \"stop\" }],\n };\n\n private _target: EventTarget;\n private _reading: WcsAmbientLightSensorReading = NULL_READING;\n private _error: WcsAmbientLightSensorErrorDetail | null = null;\n\n // The live sensor instance while started (null otherwise), kept so stop()\n // can remove its listeners precisely and so start() can detect \"already\n // started\" without a separate boolean (docs/async-io-node-guidelines.md §3.5\n // idempotency).\n private _sensor: (EventTarget & { start(): void; stop(): void }) | null = null;\n\n constructor(target?: EventTarget) {\n super();\n this._target = target ?? this;\n }\n\n get illuminance(): number | null {\n return this._reading.illuminance;\n }\n\n get error(): WcsAmbientLightSensorErrorDetail | null {\n return this._error;\n }\n\n /** No asynchronous probe to await: start()/stop() are synchronous\n * (docs/async-io-node-guidelines.md §3.8 is satisfied trivially, mirroring\n * NetworkCore). */\n get ready(): Promise<void> {\n return Promise.resolve();\n }\n\n // --- State setters ---\n\n // Deliberately NOT same-value guarded: a `reading` is a fresh sample, not a\n // settled state, so it must dispatch every time even when the values happen\n // to repeat (docs/sensor-tag-design.md §1.1).\n private _setReading(reading: WcsAmbientLightSensorReading): void {\n this._reading = reading;\n this._target.dispatchEvent(new CustomEvent(\"wcs-ambient-light-sensor:reading\", {\n detail: reading,\n bubbles: true,\n }));\n }\n\n private _setError(error: WcsAmbientLightSensorErrorDetail | null): void {\n // Same-value guard (by error name + message): error is state-like, unlike\n // reading — a repeated identical error (same name and message) must not\n // redispatch. Note `error` is also STICKY: nothing calls _setError(null),\n // so a successful (re)start does not clear a prior failure — the monitoring\n // sensor family deliberately keeps the last observed error (docs/sensor-tag-design.md §1.5).\n if (this._error?.error === error?.error && this._error?.message === error?.message) return;\n this._error = error;\n this._target.dispatchEvent(new CustomEvent(\"wcs-ambient-light-sensor:error\", {\n detail: error,\n bubbles: true,\n }));\n }\n\n // --- Public API ---\n\n /**\n * Start the sensor at the given `frequency` (Hz), or the platform default\n * when omitted. Idempotent while already started: a redundant start() does\n * not construct a second sensor instance (which would leak the first).\n * Restart with a different frequency via stop() + start().\n *\n * Synchronous, mirroring the native `Sensor.start()` — never throws\n * (docs/async-io-node-guidelines.md §3.6): both \"unsupported\" and a\n * synchronous constructor exception (permission denial, feature-policy\n * block) are converted to the `error` property instead of propagating.\n */\n start(frequency?: number): void {\n if (this._sensor) return;\n const sensor = this._createSensor(frequency);\n if (!sensor) return;\n sensor.addEventListener(\"reading\", this._onReading as EventListener);\n sensor.addEventListener(\"error\", this._onError as EventListener);\n this._sensor = sensor;\n try {\n sensor.start();\n } catch (e: any) {\n // Defensive: the platform contract says start()/stop() do not throw\n // (failures surface via the 'error' event), but never-throw is a hard\n // requirement here, so guard against a non-conformant implementation\n // too.\n this._teardownSensor();\n this._setError({ error: e?.name ?? \"error\", message: e?.message ?? String(e) });\n }\n }\n\n /** Stop the sensor and detach its listeners. Safe to call when not started. */\n stop(): void {\n if (!this._sensor) return;\n try {\n this._sensor.stop();\n } catch {\n // Never-throw defensive guard, symmetric with start(). Teardown below\n // still runs so listeners are detached regardless.\n }\n this._teardownSensor();\n }\n\n /** Lifecycle alias for start(), so the Shell's connectedCallback can drive\n * this Core the same way as other IO nodes' observe()/dispose() pair. No\n * asynchronous probe, so the returned promise always resolves immediately. */\n observe(frequency?: number): Promise<void> {\n this.start(frequency);\n return this.ready;\n }\n\n /** Lifecycle alias for stop(), invoked from the Shell's disconnectedCallback. */\n dispose(): void {\n this.stop();\n }\n\n // --- Internal ---\n\n // Both call sites (start()'s catch, stop()) only ever invoke this once\n // `this._sensor` is already known non-null, so there is no null-guard here\n // (nothing to defend against).\n private _teardownSensor(): void {\n this._sensor!.removeEventListener(\"reading\", this._onReading as EventListener);\n this._sensor!.removeEventListener(\"error\", this._onError as EventListener);\n this._sensor = null;\n }\n\n /**\n * Construct the platform `AmbientLightSensor`, guarding both non-support and a\n * synchronous constructor exception. Never calls the raw `new AmbientLightSensor(...)`\n * anywhere else in this class — see docs/sensor-tag-design.md §1.5.\n *\n * API resolution is call-time (docs/async-io-node-guidelines.md §3.7):\n * re-checked on every start(), never cached, so tests can install/remove the\n * global freely and an unsupported environment is always reported correctly.\n */\n private _createSensor(frequency?: number): (EventTarget & { start(): void; stop(): void }) | null {\n const Ctor = (globalThis as any).AmbientLightSensor;\n if (typeof Ctor !== \"function\") {\n this._setError({ error: \"unsupported\", message: \"AmbientLightSensor is not supported\" });\n return null;\n }\n try {\n return new Ctor(frequency !== undefined ? { frequency } : undefined);\n } catch (e: any) {\n // SecurityError (permission denial, feature-policy block) or any other\n // synchronous construction failure. Mirrors the FetchCore._doFetch\n // try/catch structure (packages/fetch/src/core/FetchCore.ts) — a\n // synchronous constructor call here instead of an awaited fetch().\n this._setError({ error: e?.name ?? \"error\", message: e?.message ?? String(e) });\n return null;\n }\n }\n\n private _onReading = (event: Event): void => {\n const sensor = event.target as unknown as { illuminance: number | null };\n this._setReading({ illuminance: sensor.illuminance });\n };\n\n private _onError = (event: Event): void => {\n const err = (event as any).error as { name?: string; message?: string } | undefined;\n // Fallback is a meaningful constant, NOT String(err): a SensorErrorEvent\n // without an `error` field would otherwise stringify `undefined` into the\n // literal message \"undefined\" (aligned across the sensor family).\n this._setError({ error: err?.name ?? \"error\", message: err?.message ?? \"Sensor error\" });\n };\n}\n","import { IWcBindable, WcsAmbientLightSensorErrorDetail } from \"../types.js\";\nimport { AmbientLightSensorCore } from \"../core/AmbientLightSensorCore.js\";\n\n/**\n * `<wcs-ambient-light-sensor>` — declarative Generic Sensor API (`AmbientLightSensor`)\n * monitor + start/stop control.\n *\n * Unlike `<wcs-network>` / `<wcs-permission>` (pure monitors), this Shell is a\n * bidirectional node: `start`/`stop` commands (command-token: state → element)\n * alongside the `illuminance`/`error` observable surface (event-token: element →\n * state). The `frequency` attribute is the sole configuration input, forwarded\n * to the platform `AmbientLightSensor` constructor's `{ frequency }` option\n * (docs/sensor-tag-design.md §1.2). The getter normalizes it: a non-finite or\n * non-positive value (NaN, 0, negative) reads back as `null` — meaning \"no\n * frequency specified\" — so start() falls back to the platform default rather\n * than forwarding a value the sensor would reject. Any positive finite value is\n * passed through verbatim (no upper-bound clamping — an out-of-range-but-positive\n * rate is still left to the browser/sensor to reject via `error`).\n *\n * Permission handling is intentionally NOT implemented here. Compose with\n * `<wcs-permission name=\"ambient-light-sensor\">` instead (see the README's permission\n * example, \"Gate on permission, then start\", and docs/sensor-tag-design.md).\n */\nexport class WcsAmbientLightSensor extends HTMLElement {\n static hasConnectedCallbackPromise = true;\n\n static wcBindable: IWcBindable = {\n ...AmbientLightSensorCore.wcBindable,\n inputs: [{ name: \"frequency\" }],\n // Core の commands をそのまま継承(単一情報源)。\n commands: AmbientLightSensorCore.wcBindable.commands,\n };\n\n private _core: AmbientLightSensorCore;\n private _connectedCallbackPromise: Promise<void> = Promise.resolve();\n\n constructor() {\n super();\n this._core = new AmbientLightSensorCore(this);\n }\n\n // --- Attribute accessors ---\n\n /**\n * Sampling frequency in Hz. Reads back `null` when unset, blank, or when the\n * attribute does not parse to a positive finite number (NaN, `\"0\"`, negative)\n * — in every such \"no usable value\" case the platform default applies.\n *\n * Note the deliberate set/get asymmetry: `set frequency(0)` (or any\n * non-positive/non-finite value) still writes the attribute verbatim for\n * transparency/inspectability, but the getter normalizes it back to `null`.\n * A round-trip through a non-positive value therefore does NOT preserve it —\n * that value carries no valid sampling meaning, so it is treated as \"unset\"\n * on read. Only positive finite frequencies survive a set→get round-trip.\n */\n get frequency(): number | null {\n const attr = this.getAttribute(\"frequency\");\n if (attr === null || attr.trim() === \"\") return null;\n const parsed = Number(attr);\n return Number.isFinite(parsed) && parsed > 0 ? parsed : null;\n }\n\n set frequency(value: number | null | undefined) {\n if (value === null || value === undefined) {\n this.removeAttribute(\"frequency\");\n } else {\n this.setAttribute(\"frequency\", String(value));\n }\n }\n\n // --- Core delegated getters ---\n\n get illuminance(): number | null {\n return this._core.illuminance;\n }\n\n get error(): WcsAmbientLightSensorErrorDetail | null {\n return this._core.error;\n }\n\n get connectedCallbackPromise(): Promise<void> {\n return this._connectedCallbackPromise;\n }\n\n // --- Commands ---\n\n start(): void {\n this._core.start(this.frequency ?? undefined);\n }\n\n stop(): void {\n this._core.stop();\n }\n\n // --- Lifecycle ---\n\n // Deliberately does NOT auto-start the sensor on connect. Unlike\n // Geolocation (whose default phase acquires a fix immediately unless\n // `manual` is set), AmbientLightSensor has no such \"connect implies observing\"\n // precedent in the design doc (docs/sensor-tag-design.md §1.3):\n // start/stop are the only commands, so connecting the element merely makes\n // it inert until a command-token `start` (or the `start()` method) is\n // invoked. This also keeps behavior predictable when composed with\n // `<wcs-permission name=\"ambient-light-sensor\">`: the caller decides when to start,\n // typically gated on `granted`.\n connectedCallback(): void {\n this.style.display = \"none\";\n // No asynchronous probe to await (§3.8); kept for SSR uniformity with\n // other IO nodes.\n this._connectedCallbackPromise = this._core.ready;\n }\n\n disconnectedCallback(): void {\n this._core.dispose();\n }\n}\n","import { setConfig } from \"./config.js\";\nimport { registerComponents } from \"./registerComponents.js\";\nimport { IWritableConfig } from \"./types.js\";\n\nexport function bootstrapAmbientLightSensor(userConfig?: IWritableConfig): void {\n if (userConfig) {\n setConfig(userConfig);\n }\n registerComponents();\n}\n","import { WcsAmbientLightSensor } from \"./components/AmbientLightSensor.js\";\nimport { config } from \"./config.js\";\n\nexport function registerComponents(): void {\n if (!customElements.get(config.tagNames.ambientLightSensor)) {\n customElements.define(config.tagNames.ambientLightSensor, WcsAmbientLightSensor);\n }\n}\n"],"names":["_config","tagNames","ambientLightSensor","deepFreeze","obj","Object","freeze","key","keys","deepClone","clone","frozenConfig","config","getConfig","NULL_READING","illuminance","AmbientLightSensorCore","EventTarget","static","protocol","version","properties","name","event","getter","e","detail","commands","_target","_reading","_error","_sensor","constructor","target","super","this","error","ready","Promise","resolve","_setReading","reading","dispatchEvent","CustomEvent","bubbles","_setError","message","start","frequency","sensor","_createSensor","addEventListener","_onReading","_onError","_teardownSensor","String","stop","observe","dispose","removeEventListener","Ctor","globalThis","AmbientLightSensor","undefined","err","WcsAmbientLightSensor","HTMLElement","wcBindable","inputs","_core","_connectedCallbackPromise","attr","getAttribute","trim","parsed","Number","isFinite","value","removeAttribute","setAttribute","connectedCallbackPromise","connectedCallback","style","display","disconnectedCallback","bootstrapAmbientLightSensor","userConfig","partialConfig","assign","customElements","get","define"],"mappings":"AAQA,MAAMA,EAA2B,CAC/BC,SAAU,CACRC,mBAAoB,6BAIxB,SAASC,EAAcC,GACrB,GAAY,OAARA,GAA+B,iBAARA,EAAkB,OAAOA,EACpDC,OAAOC,OAAOF,GACd,IAAK,MAAMG,KAAOF,OAAOG,KAAKJ,GAC5BD,EAAYC,EAAgCG,IAE9C,OAAOH,CACT,CAEA,SAASK,EAAaL,GACpB,GAAY,OAARA,GAA+B,iBAARA,EAAkB,OAAOA,EACpD,MAAMM,EAAiC,CAAA,EACvC,IAAK,MAAMH,KAAOF,OAAOG,KAAKJ,GAC5BM,EAAMH,GAAOE,EAAWL,EAAgCG,IAE1D,OAAOG,CACT,CAEA,IAAIC,EAA+B,KAE5B,MAAMC,EAAkBZ,WAEfa,IAId,OAHKF,IACHA,EAAeR,EAAWM,EAAUT,KAE/BW,CACT,CCvCA,MAAMG,EAA6CT,OAAOC,OAAO,CAAES,YAAa,OAoC1E,MAAOC,UAA+BC,YAC1CC,kBAAiC,CAC/BC,SAAU,cACVC,QAAS,EACTC,WAAY,CACV,CAAEC,KAAM,cAAeC,MAAO,mCAAoCC,OAASC,GAAcA,EAAkBC,OAAOX,aAClH,CAAEO,KAAM,QAASC,MAAO,mCAE1BI,SAAU,CAAC,CAAEL,KAAM,SAAW,CAAEA,KAAM,UAGhCM,QACAC,SAAyCf,EACzCgB,OAAkD,KAMlDC,QAAkE,KAE1E,WAAAC,CAAYC,GACVC,QACAC,KAAKP,QAAUK,GAAUE,IAC3B,CAEA,eAAIpB,GACF,OAAOoB,KAAKN,SAASd,WACvB,CAEA,SAAIqB,GACF,OAAOD,KAAKL,MACd,CAKA,SAA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mC,0BAA4BnC,KAAKkC,MAAMhC,KAC9C,CAEA,oBAAA+C,GACEjD,KAAKkC,MAAMX,SACb,EC9GI,SAAU2B,EAA4BC,GHuCtC,IAAoBC,EGtCpBD,KHsCoBC,EGrCZD,GHsCMrF,UAChBI,OAAOmF,OAAOxF,EAAQC,SAAUsF,EAActF,UAEhDU,EAAe,MI3CV8E,eAAeC,IAAI9E,EAAOX,SAASC,qBACtCuF,eAAeE,OAAO/E,EAAOX,SAASC,mBAAoB+D,EDI9D"}
|
package/package.json
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@wcstack/ambient-light-sensor",
|
|
3
|
+
"version": "1.16.0",
|
|
4
|
+
"description": "Declarative AmbientLightSensor component for Web Components. Framework-agnostic Generic Sensor API (AmbientLightSensor) monitor via wc-bindable-protocol.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "./dist/index.esm.js",
|
|
7
|
+
"module": "./dist/index.esm.js",
|
|
8
|
+
"types": "./dist/index.d.ts",
|
|
9
|
+
"exports": {
|
|
10
|
+
".": {
|
|
11
|
+
"types": "./dist/index.d.ts",
|
|
12
|
+
"import": "./dist/index.esm.js"
|
|
13
|
+
},
|
|
14
|
+
"./auto": "./dist/auto.min.js"
|
|
15
|
+
},
|
|
16
|
+
"files": [
|
|
17
|
+
"dist"
|
|
18
|
+
],
|
|
19
|
+
"scripts": {
|
|
20
|
+
"clean": "rimraf dist .tsc-out",
|
|
21
|
+
"build": "rimraf dist .tsc-out && tsc && rollup -c",
|
|
22
|
+
"test": "vitest run",
|
|
23
|
+
"test:watch": "vitest",
|
|
24
|
+
"test:coverage": "vitest run --coverage",
|
|
25
|
+
"lint": "eslint src",
|
|
26
|
+
"version:patch": "npm version patch",
|
|
27
|
+
"version:minor": "npm version minor",
|
|
28
|
+
"version:major": "npm version major",
|
|
29
|
+
"prepublishOnly": "npm run build && npm run test:coverage"
|
|
30
|
+
},
|
|
31
|
+
"keywords": [
|
|
32
|
+
"web-components",
|
|
33
|
+
"ambient-light-sensor",
|
|
34
|
+
"generic-sensor",
|
|
35
|
+
"illuminance",
|
|
36
|
+
"light",
|
|
37
|
+
"custom-elements",
|
|
38
|
+
"wc-bindable",
|
|
39
|
+
"declarative",
|
|
40
|
+
"zero-dependencies",
|
|
41
|
+
"framework-agnostic"
|
|
42
|
+
],
|
|
43
|
+
"author": "mogera551",
|
|
44
|
+
"homepage": "https://wcstack.github.io",
|
|
45
|
+
"repository": {
|
|
46
|
+
"type": "git",
|
|
47
|
+
"url": "https://github.com/wcstack/wcstack.git",
|
|
48
|
+
"directory": "packages/ambient-light-sensor"
|
|
49
|
+
},
|
|
50
|
+
"bugs": {
|
|
51
|
+
"url": "https://github.com/wcstack/wcstack/issues"
|
|
52
|
+
},
|
|
53
|
+
"license": "MIT",
|
|
54
|
+
"devDependencies": {
|
|
55
|
+
"@eslint/js": "^9.39.1",
|
|
56
|
+
"@rollup/plugin-terser": "^0.4.4",
|
|
57
|
+
"@rollup/plugin-typescript": "^11.1.6",
|
|
58
|
+
"@vitest/coverage-v8": "^4.0.15",
|
|
59
|
+
"@vitest/ui": "^4.0.15",
|
|
60
|
+
"eslint": "^9.39.1",
|
|
61
|
+
"globals": "^16.5.0",
|
|
62
|
+
"happy-dom": "^20.0.11",
|
|
63
|
+
"rimraf": "^6.0.1",
|
|
64
|
+
"rollup": "^4.22.4",
|
|
65
|
+
"rollup-plugin-dts": "^6.1.1",
|
|
66
|
+
"rollup-plugin-copy": "^3.5.0",
|
|
67
|
+
"tslib": "^2.8.1",
|
|
68
|
+
"typescript": "^5.9.3",
|
|
69
|
+
"typescript-eslint": "^8.49.0",
|
|
70
|
+
"vitest": "^4.0.15"
|
|
71
|
+
}
|
|
72
|
+
}
|