@wcstack/storage 1.25.0 → 1.27.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 +1 -1
- package/dist/auto.min.js +2 -3
- package/dist/auto.min.js.map +1 -0
- package/package.json +1 -1
- package/dist/auto.js +0 -3
- package/dist/index.esm.min.js +0 -2
- package/dist/index.esm.min.js.map +0 -1
package/README.ja.md
CHANGED
|
@@ -333,7 +333,7 @@ unbind();
|
|
|
333
333
|
| 数値 / boolean | `JSON.stringify()` 結果 | `JSON.parse()` 結果 |
|
|
334
334
|
| `null` / `undefined` | キーを削除 | `null` |
|
|
335
335
|
|
|
336
|
-
Core の構造サーフェスは wcstack I/O ノード横断の規範です([async-io-node-guidelines §3.9](../../docs/async-io-node-guidelines.md))。要素なしで signals に束縛するには [@wcstack/signals — Core を直接束縛する](../signals/README.ja.md#core-を直接束縛する要素なし) を参照。
|
|
336
|
+
Core の構造サーフェスは wcstack I/O ノード横断の規範です([async-io-node-guidelines §3.9](../../docs/async-io-node-guidelines.ja.md))。要素なしで signals に束縛するには [@wcstack/signals — Core を直接束縛する](../signals/README.ja.md#core-を直接束縛する要素なし) を参照。
|
|
337
337
|
|
|
338
338
|
## 要素一覧
|
|
339
339
|
|
package/dist/auto.min.js
CHANGED
|
@@ -1,3 +1,2 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
bootstrapStorage();
|
|
1
|
+
const e={triggerAttribute:"data-storagetarget",tagNames:{storage:"wcs-storage"}},t="wcs-storage:value-changed",s="wcs-storage:loading-changed",r="wcs-storage:error",i="wcs-storage:error-info-changed",n="wcs-storage:trigger-changed",a="invalid-argument",o="quota-exceeded",l="not-allowed",c="storage-error";class h extends EventTarget{static wcBindable={protocol:"wc-bindable",version:1,properties:[{name:"value",event:t,semantics:"state",getter:e=>e.detail},{name:"loading",event:s,semantics:"state"},{name:"error",event:r,semantics:"state"},{name:"errorInfo",event:i,semantics:"state"}],inputs:[{name:"key"},{name:"type"}],commands:[{name:"load"},{name:"save"},{name:"remove"}]};_target;_value=null;_loading=!1;_error=null;_errorInfo=null;_key="";_type="local";_storageListener=null;_gen=0;_ready=Promise.resolve();constructor(e){super(),this._target=e??this}get ready(){return this._ready}observe(){return this._ready}dispose(){this._gen++,this.stopSync()}get value(){return this._value}set value(e){Object.is(e,this._value)||this._setValue(e)}get loading(){return this._loading}get error(){return this._error}get errorInfo(){return this._errorInfo}get key(){return this._key}set key(e){this._key=String(e)}get type(){return this._type}set type(e){"local"===e||"session"===e?this._type=e:this._setError({operation:"type",message:`Invalid storage type: "${e}". Must be "local" or "session".`})}_getStorage(){return"session"===this._type?sessionStorage:localStorage}_setLoading(e){this._loading=e,this._target.dispatchEvent(new CustomEvent(s,{detail:e,bubbles:!0}))}_setError(e,t){this._error!==e&&(this._error=e,this._commitErrorInfo(null===e?null:function(e,t){return void 0===t?{code:a,phase:"start",recoverable:!1,message:e.message}:"QuotaExceededError"===t?{code:o,phase:"execute",recoverable:!0,message:e.message}:"SecurityError"===t?{code:l,phase:"execute",recoverable:!1,message:e.message}:{code:c,phase:"execute",recoverable:!0,message:e.message}}(e,t)),this._target.dispatchEvent(new CustomEvent(r,{detail:e,bubbles:!0})))}_commitErrorInfo(e){this._errorInfo=e,this._target.dispatchEvent(new CustomEvent(i,{detail:e,bubbles:!0}))}_toStorageError(e,t){return{operation:e,message:t instanceof Error?t.message:String(t)}}_errName(e){return e instanceof Error?e.name:""}_setValue(e){this._value=e,this._target.dispatchEvent(new CustomEvent(t,{detail:e,bubbles:!0}))}load(){if(!this._key)return this._setError({operation:"load",message:"key is required."}),null;this._setLoading(!0),this._setError(null);try{const e=this._getStorage().getItem(this._key);if(null===e)this._setValue(null);else try{this._setValue(JSON.parse(e))}catch{this._setValue(e)}return this._setLoading(!1),this._value}catch(e){return this._setError(this._toStorageError("load",e),this._errName(e)),this._setLoading(!1),null}}save(e){if(this._key){this._setLoading(!0),this._setError(null);try{const t=this._getStorage();null==e?(t.removeItem(this._key),this._setValue(null)):"string"==typeof e?(t.setItem(this._key,e),this._setValue(e)):(t.setItem(this._key,JSON.stringify(e)),this._setValue(e)),this._setLoading(!1)}catch(e){this._setError(this._toStorageError("save",e),this._errName(e)),this._setLoading(!1)}}else this._setError({operation:"save",message:"key is required."})}remove(){if(this._key){this._setLoading(!0),this._setError(null);try{this._getStorage().removeItem(this._key),this._setValue(null),this._setLoading(!1)}catch(e){this._setError(this._toStorageError("remove",e),this._errName(e)),this._setLoading(!1)}}else this._setError({operation:"remove",message:"key is required."})}startSync(){if(this._storageListener)return;const e=++this._gen;this._storageListener=t=>{if(e===this._gen&&t.key===this._key&&"session"!==this._type)if(this._setError(null),null===t.newValue)this._setValue(null);else try{this._setValue(JSON.parse(t.newValue))}catch{this._setValue(t.newValue)}},globalThis.addEventListener("storage",this._storageListener)}stopSync(){this._storageListener&&(globalThis.removeEventListener("storage",this._storageListener),this._storageListener=null)}}let u=!1;function g(t){const s=t.target;if(!(s instanceof Element))return;const r=s.closest(`[${e.triggerAttribute}]`);if(!r)return;const i=r.getAttribute(e.triggerAttribute);if(!i)return;const n=customElements.get(e.tagNames.storage),a=document.getElementById(i);n&&a instanceof n&&(t.preventDefault(),a.save())}function _(e,t){let s=Object.getPrototypeOf(e);for(;null!==s;){const e=Object.getOwnPropertyDescriptor(s,t);if(void 0!==e)return"function"==typeof e.get||"function"==typeof e.set;s=Object.getPrototypeOf(s)}return!1}class d extends HTMLElement{static hasConnectedCallbackPromise=!0;static wcBindable={...h.wcBindable,properties:[...h.wcBindable.properties,{name:"trigger",event:n,semantics:"state"}],inputs:[{name:"key"},{name:"type"},{name:"value"},{name:"manual"},{name:"trigger"}]};static get observedAttributes(){return["key","type"]}_core;_trigger=!1;_connectedCallbackPromise=Promise.resolve();_internals=null;constructor(){super(),this._core=new h(this),this._internals=this._initInternals(),this._wireStates({[s]:e=>({loading:!0===e}),[r]:e=>({error:null!=e})})}get debugStates(){return this._internals?[...this._internals.states]:[]}_initInternals(){try{if("function"!=typeof this.attachInternals)return null;const e=this.attachInternals();return e.states.add("wcs-probe"),e.states.delete("wcs-probe"),e}catch{return null}}_wireStates(e){if(null===this._internals)return;const t=this._internals.states;for(const[s,r]of Object.entries(e))this.addEventListener(s,e=>{const s=this.hasAttribute("debug-states");for(const[i,n]of Object.entries(r(e.detail))){try{n?t.add(i):t.delete(i)}catch{}s&&this.toggleAttribute(`data-wcs-state-${i}`,n)}})}_syncCore(){this._core.key=this.key,this._core.type=this.type}get key(){return this.getAttribute("key")||""}set key(e){this.setAttribute("key",e)}get type(){return"session"===this.getAttribute("type")?"session":"local"}set type(e){this.setAttribute("type",e)}get value(){return this._core.value}set value(e){this.manual?this._core.value=e:(this._syncCore(),this._core.save(e))}get loading(){return this._core.loading}get error(){return this._core.error}get errorInfo(){return this._core.errorInfo}get connectedCallbackPromise(){return this._connectedCallbackPromise}get manual(){return this.hasAttribute("manual")}set manual(e){e?this.setAttribute("manual",""):this.removeAttribute("manual")}get trigger(){return this._trigger}set trigger(e){if(!!e){this._trigger=!0;try{this.save()}finally{this._trigger=!1,this.dispatchEvent(new CustomEvent(n,{detail:!1,bubbles:!0}))}}}load(){return this._syncCore(),this._core.load()}save(){this._syncCore(),this._core.save(this._core.value)}remove(){this._syncCore(),this._core.remove()}attributeChangedCallback(e,t,s){this.isConnected&&("key"===e&&(this._syncCore(),s&&!this.manual&&this.load()),"type"===e&&this._syncCore())}connectedCallback(){!function(e){const t=e.constructor?.wcBindable,s=t?.inputs;if(void 0!==s)for(const t of s){const s=t.name;if(!Object.prototype.hasOwnProperty.call(e,s))continue;if(!_(e,s))continue;const r=e,i=r[s];delete r[s],r[s]=i}}(this),this.style.display="none",u||(u=!0,document.addEventListener("click",g)),!this.manual&&this.key&&this.load(),this._syncCore(),this._core.startSync()}disconnectedCallback(){this._core.stopSync()}}customElements.get(e.tagNames.storage)||customElements.define(e.tagNames.storage,d);
|
|
2
|
+
//# sourceMappingURL=auto.min.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"auto.min.js","sources":["../src/config.ts","../src/events.ts","../src/core/storageCapabilities.ts","../src/core/StorageCore.ts","../src/autoTrigger.ts","../src/protocol/upgradeProperties.ts","../src/components/Storage.ts","../src/registerComponents.ts"],"sourcesContent":["import { IConfig, IWritableConfig } from \"./types.js\";\n\ninterface IInternalConfig extends IConfig {\n autoTrigger: boolean;\n triggerAttribute: string;\n tagNames: {\n storage: string;\n };\n}\n\nconst _config: IInternalConfig = {\n autoTrigger: true,\n triggerAttribute: \"data-storagetarget\",\n tagNames: {\n storage: \"wcs-storage\",\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 (typeof partialConfig.autoTrigger === \"boolean\") {\n _config.autoTrigger = partialConfig.autoTrigger;\n }\n if (typeof partialConfig.triggerAttribute === \"string\") {\n _config.triggerAttribute = partialConfig.triggerAttribute;\n }\n if (partialConfig.tagNames) {\n // Validate each tagNames entry individually instead of a blanket\n // Object.assign: a non-string (e.g. { storage: undefined }) would otherwise\n // poison the config and make customElements.define(undefined, …) throw at\n // registration time. Mirrors the typeof guards on autoTrigger / triggerAttribute.\n for (const [key, value] of Object.entries(partialConfig.tagNames)) {\n if (typeof value === \"string\") {\n (_config.tagNames as Record<string, string>)[key] = value;\n }\n }\n }\n frozenConfig = null;\n}\n","// Single source of truth for the custom event names dispatched by StorageCore /\n// Storage. These names appear in two places that must stay in lock-step:\n// 1. the `wcBindable.properties[].event` declarations (consumed by bind())\n// 2. the `dispatchEvent(new CustomEvent(...))` calls that emit them\n// Hard-coding the same string literal in both places risks a silent typo that\n// makes bind() listen for an event no one ever fires. Referencing these\n// constants from both sites keeps them in sync.\nexport const STORAGE_EVENTS = {\n valueChanged: \"wcs-storage:value-changed\",\n loadingChanged: \"wcs-storage:loading-changed\",\n error: \"wcs-storage:error\",\n errorInfoChanged: \"wcs-storage:error-info-changed\",\n triggerChanged: \"wcs-storage:trigger-changed\",\n} as const;\n","/**\n * storageCapabilities.ts\n *\n * Storage node 固有の error code(taxonomy)と derivation。汎用の error info 型は\n * `./platformCapability.js`(/io-core/ から copy-distribution される生成ファイル)から\n * import する。storage の load / save / remove は同期で互いに競合しないため lane は\n * 持たず、error taxonomy(errorInfo)のみを採用する。\n */\n\nimport type { WcsIoErrorInfo } from \"./platformCapability.js\";\nimport type { WcsStorageError } from \"../types.js\";\n\n/** 安定した storage error code(taxonomy)。値は公開キーとして固定。 */\nexport const WCS_STORAGE_ERROR_CODE = {\n /** `key` 未設定 / 不正な `type` などの入力不備。retry では回復しない。 */\n InvalidArgument: \"invalid-argument\",\n /** `QuotaExceededError` — 容量超過。空きを作れば回復しうる(環境要因)。 */\n QuotaExceeded: \"quota-exceeded\",\n /** `SecurityError` — storage アクセス拒否(cookie 無効 / third-party context 等)。retry では回復しない。 */\n NotAllowed: \"not-allowed\",\n /** その他の caught 例外。 */\n StorageError: \"storage-error\",\n} as const;\n\n/**\n * storage の失敗を serializable な error taxonomy に写す。\n *\n * `name` は caught 例外の `Error.name`(load / save / remove の catch から渡る)。\n * 未指定(undefined)は inline 構築の validation error(不正 `type` / `key` 未設定)を意味し、\n * これは開始前の入力不備なので phase=\"start\" / `invalid-argument` / recoverable=false。\n * caught 例外は実行中の失敗なので phase=\"execute\"。`QuotaExceededError` は環境要因で\n * 空きを作れば回復しうる(recoverable=true)、`SecurityError` は retry で回復しない。\n */\nexport function deriveStorageErrorInfo(error: WcsStorageError, name?: string): WcsIoErrorInfo {\n if (name === undefined) {\n return {\n code: WCS_STORAGE_ERROR_CODE.InvalidArgument,\n phase: \"start\",\n recoverable: false,\n message: error.message,\n };\n }\n if (name === \"QuotaExceededError\") {\n return { code: WCS_STORAGE_ERROR_CODE.QuotaExceeded, phase: \"execute\", recoverable: true, message: error.message };\n }\n if (name === \"SecurityError\") {\n return { code: WCS_STORAGE_ERROR_CODE.NotAllowed, phase: \"execute\", recoverable: false, message: error.message };\n }\n return { code: WCS_STORAGE_ERROR_CODE.StorageError, phase: \"execute\", recoverable: true, message: error.message };\n}\n","import { STORAGE_EVENTS } from \"../events.js\";\nimport { IWcBindable, StorageType, WcsStorageError } from \"../types.js\";\nimport { WcsIoErrorInfo } from \"./platformCapability.js\";\nimport { deriveStorageErrorInfo } from \"./storageCapabilities.js\";\n\nexport class StorageCore extends EventTarget {\n static wcBindable: IWcBindable = {\n protocol: \"wc-bindable\",\n version: 1,\n properties: [\n { name: \"value\", event: STORAGE_EVENTS.valueChanged, semantics: \"state\", getter: (e: Event) => (e as CustomEvent).detail },\n { name: \"loading\", event: STORAGE_EVENTS.loadingChanged, semantics: \"state\" },\n { name: \"error\", event: STORAGE_EVENTS.error, semantics: \"state\" },\n // Serializable failure taxonomy (stable code / phase / recoverable), or null.\n // Additive bindable output derived from `error` (invalid-argument / quota-exceeded\n // / not-allowed / storage-error); the existing `error` property/event are unchanged.\n // Fires wcs-storage:error-info-changed. No lane — load/save/remove don't compete.\n { name: \"errorInfo\", event: STORAGE_EVENTS.errorInfoChanged, semantics: \"state\" },\n ],\n inputs: [\n { name: \"key\" },\n { name: \"type\" },\n ],\n // load / save / remove are synchronous, so none carry the `async` hint.\n commands: [\n { name: \"load\" },\n { name: \"save\" },\n { name: \"remove\" },\n ],\n };\n\n private _target: EventTarget;\n private _value: any = null;\n private _loading: boolean = false;\n private _error: any = null;\n private _errorInfo: WcsIoErrorInfo | null = null;\n private _key: string = \"\";\n private _type: StorageType = \"local\";\n private _storageListener: ((e: StorageEvent) => void) | null = null;\n // Generation guard: bumped on dispose(). The cross-tab `storage` listener\n // captures the generation active when startSync() ran; a callback that fires\n // after dispose() (or a teardown→re-setup) has a stale gen and MUST NOT write\n // state to a torn-down element. A boolean flag is insufficient (dispose→observe\n // would let a stale listener slip through).\n private _gen = 0;\n // SSR: storage access is synchronous, so there is no asynchronous probe to\n // await — readiness is immediate.\n private _ready: Promise<void> = Promise.resolve();\n\n constructor(target?: EventTarget) {\n super();\n this._target = target ?? this;\n }\n\n get ready(): Promise<void> {\n return this._ready;\n }\n\n // Lifecycle (§3.5). Storage sync is command-driven (the Shell calls startSync()\n // from connectedCallback), so observe() is an idempotent no-op that resolves\n // once ready; dispose() tears down the cross-tab listener and invalidates any\n // in-flight listener callback.\n observe(): Promise<void> {\n return this._ready;\n }\n\n dispose(): void {\n this._gen++;\n this.stopSync();\n }\n\n get value(): any {\n return this._value;\n }\n\n // Set the current value *without* persisting it. Persistence happens only via\n // save() / remove() / a cross-tab storage event. This setter exists so the\n // Shell (manual mode) can stage a value handed in via a `value` binding and\n // then commit it later with save()/trigger. It mirrors the value to observers\n // through the same `value-changed` event load()/save() use (CSBC: a Core value\n // change is observable), but it deliberately does not touch storage.\n //\n // Same-value writes are skipped to break a potential feedback loop:\n // value-changed → state binding → value setter → value-changed → …\n set value(v: any) {\n if (Object.is(v, this._value)) return;\n this._setValue(v);\n }\n\n get loading(): boolean {\n return this._loading;\n }\n\n get error(): any {\n return this._error;\n }\n\n /**\n * The last failure's serializable `WcsIoErrorInfo` (stable `code` / `phase` /\n * `recoverable`), or null. Additive wc-bindable property (event\n * `wcs-storage:error-info-changed`), derived from `error`; the existing `error`\n * property/event are unchanged.\n */\n get errorInfo(): WcsIoErrorInfo | null {\n return this._errorInfo;\n }\n\n get key(): string {\n return this._key;\n }\n\n set key(value: string) {\n // Defensive normalization for direct Core use (the Shell already passes a\n // string via `getAttribute(\"key\") || \"\"`). Coercing to String keeps a\n // non-string assignment from poisoning the cross-tab `e.key !== _key`\n // comparison; empty keys are still rejected at operation time.\n this._key = String(value);\n }\n\n get type(): StorageType {\n return this._type;\n }\n\n set type(value: StorageType) {\n if (value !== \"local\" && value !== \"session\") {\n // never-throw: an invalid type is routed to the error property and the\n // current type is kept (the safe default), rather than throwing out of the\n // setter / setAttribute / connectedCallback.\n this._setError({ operation: \"type\", message: `Invalid storage type: \"${value}\". Must be \"local\" or \"session\".` });\n return;\n }\n this._type = value;\n }\n\n private _getStorage(): globalThis.Storage {\n return this._type === \"session\" ? sessionStorage : localStorage;\n }\n\n private _setLoading(loading: boolean): void {\n this._loading = loading;\n this._target.dispatchEvent(new CustomEvent(STORAGE_EVENTS.loadingChanged, {\n detail: loading,\n bubbles: true,\n }));\n }\n\n // `name` is the caught exception's `Error.name` (passed only from the\n // load/save/remove catch blocks); it stays out of the public `error` shape and\n // is used solely to classify errorInfo (quota vs security vs generic). Inline\n // validation errors (invalid type / missing key) pass no name → invalid-argument.\n private _setError(error: any, name?: string): void {\n // Same-value guard (async-io-node-guidelines.md §3.3). `error` is state-ish,\n // so suppressing redundant null→null dispatches (every load/save/remove start\n // clears a usually-already-null error) avoids a spurious error event per\n // successful operation. Reference identity is sufficient: each failure builds\n // a fresh object, and the clear path always passes null.\n if (this._error === error) return;\n this._error = error;\n // Keep the additive `errorInfo` taxonomy in sync with `error`: derive from the\n // error (or null on clear). Fires before the `error` event so an observer\n // binding both sees the classification first, mirroring the io-node family.\n this._commitErrorInfo(error === null ? null : deriveStorageErrorInfo(error, name));\n this._target.dispatchEvent(new CustomEvent(STORAGE_EVENTS.error, {\n detail: error,\n bubbles: true,\n }));\n }\n\n // Called only from _setError (which already same-value-guards on the error\n // reference), so errorInfo transitions exactly when error does — no separate\n // guard needed here.\n private _commitErrorInfo(info: WcsIoErrorInfo | null): void {\n this._errorInfo = info;\n this._target.dispatchEvent(new CustomEvent(STORAGE_EVENTS.errorInfoChanged, {\n detail: info,\n bubbles: true,\n }));\n }\n\n // Wrap a caught storage exception into the documented WcsStorageError shape,\n // tagging it with the failing operation so consumers know which call failed.\n private _toStorageError(operation: WcsStorageError[\"operation\"], e: unknown): WcsStorageError {\n return {\n operation,\n message: e instanceof Error ? e.message : String(e),\n };\n }\n\n // The caught exception's `Error.name` for errorInfo classification (quota vs\n // security vs generic), or \"\" for a non-Error throw (→ storage-error). Returning\n // a string (never undefined) keeps a caught exception in the execute phase; only\n // inline validation errors, which pass no name to _setError, become start-phase\n // invalid-argument. Single chokepoint so the ternary is covered in one place.\n private _errName(e: unknown): string {\n return e instanceof Error ? e.name : \"\";\n }\n\n private _setValue(value: any): void {\n this._value = value;\n this._target.dispatchEvent(new CustomEvent(STORAGE_EVENTS.valueChanged, {\n detail: value,\n bubbles: true,\n }));\n }\n\n load(): any {\n if (!this._key) {\n // never-throw: a missing key is routed to the error property and a\n // sanitized null is returned, rather than throwing.\n this._setError({ operation: \"load\", message: \"key is required.\" });\n return null;\n }\n\n this._setLoading(true);\n this._setError(null);\n\n try {\n const storage = this._getStorage();\n const raw = storage.getItem(this._key);\n\n if (raw === null) {\n this._setValue(null);\n } else {\n try {\n this._setValue(JSON.parse(raw));\n } catch {\n this._setValue(raw);\n }\n }\n\n this._setLoading(false);\n return this._value;\n } catch (e: any) {\n this._setError(this._toStorageError(\"load\", e), this._errName(e));\n this._setLoading(false);\n return null;\n }\n }\n\n save(value: any): void {\n if (!this._key) {\n // never-throw: a missing key is routed to the error property instead of\n // throwing. No return value to sanitize (save returns void).\n this._setError({ operation: \"save\", message: \"key is required.\" });\n return;\n }\n\n this._setLoading(true);\n this._setError(null);\n\n try {\n const storage = this._getStorage();\n\n if (value === null || value === undefined) {\n storage.removeItem(this._key);\n // Normalize the removed value to null (matching remove() and load() of a\n // missing key) so saving `undefined` does not leave the getter returning\n // `undefined`. README's serialization table documents null/undefined as\n // \"null\" on read-back.\n this._setValue(null);\n } else if (typeof value === \"string\") {\n storage.setItem(this._key, value);\n this._setValue(value);\n } else {\n storage.setItem(this._key, JSON.stringify(value));\n this._setValue(value);\n }\n\n this._setLoading(false);\n } catch (e: any) {\n this._setError(this._toStorageError(\"save\", e), this._errName(e));\n this._setLoading(false);\n }\n }\n\n remove(): void {\n if (!this._key) {\n // never-throw: a missing key is routed to the error property instead of\n // throwing. No return value to sanitize (remove returns void).\n this._setError({ operation: \"remove\", message: \"key is required.\" });\n return;\n }\n\n this._setLoading(true);\n this._setError(null);\n\n try {\n const storage = this._getStorage();\n storage.removeItem(this._key);\n this._setValue(null);\n this._setLoading(false);\n } catch (e: any) {\n this._setError(this._toStorageError(\"remove\", e), this._errName(e));\n this._setLoading(false);\n }\n }\n\n startSync(): void {\n if (this._storageListener) return;\n\n // Capture the generation active when sync starts. A `storage` event that\n // fires after dispose() (which bumps _gen and removes the listener) carries a\n // stale gen and must not write state to a torn-down element. stopSync()\n // already detaches the listener, but the gen guard also covers a queued event\n // delivered between dispose()'s bump and the actual removeEventListener.\n const gen = ++this._gen;\n\n this._storageListener = (e: StorageEvent) => {\n if (gen !== this._gen) return;\n if (e.key !== this._key) return;\n if (this._type === \"session\") return;\n\n // A fresh value arriving from another tab supersedes any stale error from\n // a prior failed load/save/remove. Clearing it here keeps the sync path\n // consistent with load()/save()/remove(), which all reset error to null at\n // the start of a successful operation — otherwise an \"error present + fresh\n // value\" inconsistency could persist after a cross-tab update.\n this._setError(null);\n\n if (e.newValue === null) {\n this._setValue(null);\n } else {\n try {\n this._setValue(JSON.parse(e.newValue));\n } catch {\n this._setValue(e.newValue);\n }\n }\n };\n\n globalThis.addEventListener(\"storage\", this._storageListener);\n }\n\n stopSync(): void {\n if (!this._storageListener) return;\n globalThis.removeEventListener(\"storage\", this._storageListener);\n this._storageListener = null;\n }\n}\n","import { config } from \"./config.js\";\nimport type { Storage } from \"./components/Storage.js\";\n\nlet registered = false;\n\nfunction handleClick(event: Event): void {\n const target = event.target;\n if (!(target instanceof Element)) return;\n\n const triggerElement = target.closest<Element>(`[${config.triggerAttribute}]`);\n if (!triggerElement) return;\n\n const storageId = triggerElement.getAttribute(config.triggerAttribute);\n if (!storageId) return;\n\n // Resolve the registered constructor at call time instead of importing Storage\n // as a value. The value import created a components/Storage.ts ⇄ autoTrigger.ts\n // cycle (Storage.connectedCallback() calls registerAutoTrigger()). instanceof\n // against the customElements registry keeps the exact same identity guarantee\n // — only the registered <wcs-storage> class matches — without the import cycle.\n const StorageCtor = customElements.get(config.tagNames.storage);\n const storageElement = document.getElementById(storageId);\n if (!StorageCtor || !(storageElement instanceof StorageCtor)) return;\n\n event.preventDefault();\n (storageElement as Storage).save();\n}\n\nexport function registerAutoTrigger(): void {\n if (registered) return;\n registered = true;\n document.addEventListener(\"click\", handleClick);\n}\n\nexport function unregisterAutoTrigger(): void {\n if (!registered) return;\n registered = false;\n document.removeEventListener(\"click\", handleClick);\n}\n","// ===========================================================================\n// AUTO-GENERATED FILE - DO NOT EDIT.\n// Generated from /protocol/upgrade-properties.ts by scripts/sync-protocol-types.mjs.\n// Run `node scripts/sync-protocol-types.mjs` after editing the source.\n// ===========================================================================\n\n// custom element の property upgrade — `static wcBindable.inputs` に宣言した入力のうち、\n// 要素が upgrade される前に代入された own データプロパティを取り込み直す。\n//\n// なぜ必要か:\n// 未定義タグの要素は素の HTMLElement なので、`el.url = \"...\"` は own データプロパティを作る。\n// upgrade 後にクラスの accessor が prototype へ入っても own プロパティが優先されるため、\n// setter は二度と呼ばれず、値は要素へ届かないまま消える(エラーも警告も出ない)。\n// 常にプロパティ代入を行う framework(Angular の `[prop]`、Lit の `.prop=`、\n// Solid の `prop:`、Vue の `.prop` 修飾子)× 遅延定義(autoloader / CDN / code-split)で\n// 常態的に起きる。docs/architecture-hardening/13-framework-adapter-binding-constraints.md §1.2。\n//\n// 安全側の判定:\n// own プロパティがあっても、prototype チェーンに accessor が無ければ「シャドウ」ではなく\n// その own プロパティ自体が正規の格納先なので触らない(public class field を壊さない)。\n//\n// SINGLE SOURCE OF TRUTH: edit only this file (/protocol/upgrade-properties.ts), then run\n// `node scripts/sync-protocol-types.mjs` to regenerate the per-package copies\n// (packages/<pkg>/src/protocol/upgradeProperties.ts). Those copies are generated — do not edit them.\nimport { IWcBindable } from \"./wcBindable.js\";\n\nfunction hasAccessorOnPrototype(target: object, name: string): boolean {\n let proto = Object.getPrototypeOf(target);\n while (proto !== null) {\n const descriptor = Object.getOwnPropertyDescriptor(proto, name);\n if (descriptor !== undefined) {\n return typeof descriptor.get === \"function\" || typeof descriptor.set === \"function\";\n }\n proto = Object.getPrototypeOf(proto);\n }\n return false;\n}\n\n/**\n * `connectedCallback` の先頭で呼ぶ。宣言済み input のうち upgrade 前の代入で\n * accessor をシャドウしている own プロパティを、delete → 再代入で setter に通し直す。\n *\n * - 冪等: 再代入は accessor を通るので own プロパティは残らず、2 回目以降は no-op。\n * - 宣言に `inputs` が無い要素、`wcBindable` を持たない要素では何もしない。\n * - 値の意味は変えない。今まで捨てられていた代入が届くようになる一方向の変化。\n */\nexport function upgradeProperties(element: object): void {\n const declaration = (element as { constructor?: { wcBindable?: IWcBindable } }).constructor?.wcBindable;\n const inputs = declaration?.inputs;\n if (inputs === undefined) return;\n for (const input of inputs) {\n const name = input.name;\n if (!Object.prototype.hasOwnProperty.call(element, name)) continue;\n if (!hasAccessorOnPrototype(element, name)) continue;\n const record = element as Record<string, unknown>;\n const value = record[name];\n delete record[name];\n record[name] = value;\n }\n}\n","import { config } from \"../config.js\";\nimport { STORAGE_EVENTS } from \"../events.js\";\nimport { IWcBindable, StorageType } from \"../types.js\";\nimport { StorageCore } from \"../core/StorageCore.js\";\nimport { WcsIoErrorInfo } from \"../core/platformCapability.js\";\nimport { registerAutoTrigger } from \"../autoTrigger.js\";\nimport { upgradeProperties } from \"../protocol/upgradeProperties.js\";\n\nexport class Storage extends HTMLElement {\n static hasConnectedCallbackPromise = true;\n static wcBindable: IWcBindable = {\n ...StorageCore.wcBindable,\n properties: [\n ...StorageCore.wcBindable.properties,\n { name: \"trigger\", event: STORAGE_EVENTS.triggerChanged, semantics: \"state\" },\n ],\n // Shell-level input surface. The Core declares only the portable `key` / `type`;\n // the Shell adds the DOM-driven settable surface. No `attribute` hints are given:\n // the `key` / `type` / `manual` setters already reflect to their attributes, so a\n // binding system that mirrors inputs[].attribute would set the attribute twice\n // (`value` / `trigger` are not attribute-backed). `commands` (load / save / remove)\n // are inherited unchanged from the Core via the spread above.\n inputs: [\n { name: \"key\" },\n { name: \"type\" },\n { name: \"value\" },\n { name: \"manual\" },\n { name: \"trigger\" },\n ],\n };\n static get observedAttributes(): string[] { return [\"key\", \"type\"]; }\n\n private _core: StorageCore;\n private _trigger: boolean = false;\n // Storage load()/save() are synchronous, so connection work never defers.\n // This stays an already-resolved Promise for the whole lifecycle; it exists\n // only to satisfy the `hasConnectedCallbackPromise` protocol (consumers may\n // `await el.connectedCallbackPromise`). connectedCallback intentionally does\n // not reassign it — there is nothing async to wait for, unlike <wcs-fetch>.\n private _connectedCallbackPromise: Promise<void> = Promise.resolve();\n private _internals: ElementInternals | null = null;\n\n constructor() {\n super();\n this._core = new StorageCore(this);\n this._internals = this._initInternals();\n this._wireStates({\n [STORAGE_EVENTS.loadingChanged]: (d) => ({ loading: d === true }),\n [STORAGE_EVENTS.error]: (d) => ({ error: d != null }),\n });\n }\n\n // CSS state reflection (:state()) — debug-only snapshot getter. NOT part of\n // wc-bindable (not a bind target); see README \"CSS styling with :state()\".\n // MUST NOT return the live CustomStateSet (that would let callers write\n // states from outside, defeating the point of :state() being read-only).\n get debugStates(): string[] {\n return this._internals ? [...this._internals.states] : [];\n }\n\n private _initInternals(): ElementInternals | null {\n // never-throw (async-io-node-guidelines.md §3.6): attachInternals is absent\n // in happy-dom / older environments, and pre-125 Chromium rejects\n // non-dashed state names from states.add() (probed and discarded here).\n // Either case silently disables reflection — the component still works,\n // it just doesn't expose :state() selectors.\n try {\n if (typeof this.attachInternals !== \"function\") return null;\n const internals = this.attachInternals();\n internals.states.add(\"wcs-probe\");\n internals.states.delete(\"wcs-probe\");\n return internals;\n } catch {\n return null;\n }\n }\n\n private _wireStates(map: Record<string, (detail: any) => Record<string, boolean>>): void {\n if (this._internals === null) return;\n const states = this._internals.states;\n for (const [event, toStates] of Object.entries(map)) {\n this.addEventListener(event, (e) => {\n const debug = this.hasAttribute(\"debug-states\");\n for (const [name, on] of Object.entries(toStates((e as CustomEvent).detail))) {\n try {\n if (on) { states.add(name); } else { states.delete(name); }\n } catch { /* never-throw */ }\n if (debug) this.toggleAttribute(`data-wcs-state-${name}`, on);\n }\n });\n }\n }\n\n // Push the Shell's current attribute-derived key / type down into the Core.\n // Every operation (load / save / remove / value setter) and every lifecycle\n // hook that may run a Core operation or cross-tab sync must do this first, so\n // the Core never acts on a stale key / type. Centralizing it here avoids the\n // previous pattern of repeating `_core.key = …; _core.type = …;` at each call\n // site, which risked a future call site forgetting one of the two.\n private _syncCore(): void {\n this._core.key = this.key;\n this._core.type = this.type;\n }\n\n get key(): string {\n return this.getAttribute(\"key\") || \"\";\n }\n\n set key(value: string) {\n this.setAttribute(\"key\", value);\n }\n\n get type(): StorageType {\n // Normalize at the Shell boundary: any attribute value other than the\n // exact \"session\" falls back to \"local\". This keeps an invalid attribute\n // (e.g. type=\"foo\") from reaching the Core's validating setter and throwing\n // out of setAttribute / connectedCallback.\n return this.getAttribute(\"type\") === \"session\" ? \"session\" : \"local\";\n }\n\n set type(value: StorageType) {\n this.setAttribute(\"type\", value);\n }\n\n get value(): any {\n return this._core.value;\n }\n\n set value(v: any) {\n // Non-manual mode: assigning `value` auto-saves the *assigned* argument `v`\n // (write-through). Note this differs from save()/trigger, which persist the\n // *current* `_core.value` (which load() or a cross-tab `storage` event may\n // have updated). See README \"Design Notes\" for the rationale.\n //\n // Manual mode: assigning `value` does NOT persist — it only stages the value\n // into the Core (no storage write). This keeps the getter/setter consistent\n // (`el.value = x; el.value === x`) and lets a later save()/trigger commit the\n // staged value, so a `value: …` + `trigger: …` binding pair works as\n // documented. The actual write still happens only via save()/trigger.\n if (!this.manual) {\n this._syncCore();\n this._core.save(v);\n } else {\n this._core.value = v;\n }\n }\n\n get loading(): boolean {\n return this._core.loading;\n }\n\n get error(): any {\n return this._core.error;\n }\n\n get errorInfo(): WcsIoErrorInfo | null {\n return this._core.errorInfo;\n }\n\n get connectedCallbackPromise(): Promise<void> {\n return this._connectedCallbackPromise;\n }\n\n get manual(): boolean {\n return this.hasAttribute(\"manual\");\n }\n\n set manual(value: boolean) {\n if (value) {\n this.setAttribute(\"manual\", \"\");\n } else {\n this.removeAttribute(\"manual\");\n }\n }\n\n get trigger(): boolean {\n return this._trigger;\n }\n\n set trigger(value: boolean) {\n const v = !!value;\n if (v) {\n this._trigger = true;\n // save() is never-throw (a failure — e.g. key unset — is routed to the\n // `error` property, not thrown), but the try/finally is kept defensively\n // to guarantee the trigger resets to false and the completion event fires\n // even in the unexpected event of a throw, so the trigger never gets stuck\n // in the `true` state.\n try {\n this.save();\n } finally {\n this._trigger = false;\n this.dispatchEvent(new CustomEvent(STORAGE_EVENTS.triggerChanged, {\n detail: false,\n bubbles: true,\n }));\n }\n }\n }\n\n load(): any {\n this._syncCore();\n return this._core.load();\n }\n\n // The `save` command differs in arity between the two CSBC surfaces:\n // - Core: save(value) — caller supplies the value to persist\n // - Shell: save() — persists the current `_core.value` (no argument)\n // Both are exposed under the same `commands` entry name \"save\". The protocol\n // `commands` list is descriptive metadata only and carries no arity, so this\n // is not a protocol violation; the difference is contractual and documented\n // in the README (\"Design Notes\").\n save(): void {\n this._syncCore();\n this._core.save(this._core.value);\n }\n\n remove(): void {\n this._syncCore();\n this._core.remove();\n }\n\n attributeChangedCallback(name: string, _oldValue: string | null, newValue: string | null): void {\n if (!this.isConnected) return;\n if (name === \"key\") {\n // Always keep the Core's key in sync with the attribute, regardless of\n // mode or whether the new value is empty. The cross-tab `storage` listener\n // compares `e.key !== _core.key`, so a stale Core key would make sync watch\n // the wrong (old/empty) key after a runtime key change. load() (which also\n // syncs the Core) only runs for non-manual mode with a non-empty key.\n this._syncCore();\n if (newValue && !this.manual) {\n this.load();\n }\n }\n if (name === \"type\") {\n // Route through the normalizing getter so an invalid attribute value\n // (e.g. type=\"foo\") falls back to \"local\" instead of throwing.\n this._syncCore();\n }\n }\n\n connectedCallback(): void {\n // upgrade 前に代入された input を取り込み直す(doc 13 §1.2 / Phase A1)\n upgradeProperties(this);\n this.style.display = \"none\";\n if (config.autoTrigger) {\n registerAutoTrigger();\n }\n if (!this.manual && this.key) {\n this.load();\n }\n // Always bind the cross-tab watcher to the Shell's current key/type before\n // starting sync. In paths where load()/save() never run (e.g. manual mode,\n // or key set via JS without a load), _core.key/_core.type would otherwise\n // keep a stale/empty value and the storage listener's `e.key !== _key`\n // check would compare against the wrong key. This also covers detach →\n // re-attach: stale Core key from a previous session is overwritten here.\n this._syncCore();\n this._core.startSync();\n }\n\n disconnectedCallback(): void {\n this._core.stopSync();\n }\n}\n","import { Storage } from \"./components/Storage.js\";\nimport { config } from \"./config.js\";\n\nexport function registerComponents(): void {\n if (!customElements.get(config.tagNames.storage)) {\n customElements.define(config.tagNames.storage, Storage);\n }\n}\n"],"names":["config","triggerAttribute","tagNames","storage","STORAGE_EVENTS","WCS_STORAGE_ERROR_CODE","StorageCore","EventTarget","static","protocol","version","properties","name","event","semantics","getter","e","detail","inputs","commands","_target","_value","_loading","_error","_errorInfo","_key","_type","_storageListener","_gen","_ready","Promise","resolve","constructor","target","super","this","ready","observe","dispose","stopSync","value","v","Object","is","_setValue","loading","error","errorInfo","key","String","type","_setError","operation","message","_getStorage","sessionStorage","localStorage","_setLoading","dispatchEvent","CustomEvent","bubbles","_commitErrorInfo","undefined","code","phase","recoverable","deriveStorageErrorInfo","info","_toStorageError","Error","_errName","load","raw","getItem","JSON","parse","save","removeItem","setItem","stringify","remove","startSync","gen","newValue","globalThis","addEventListener","removeEventListener","registered","handleClick","Element","triggerElement","closest","storageId","getAttribute","StorageCtor","customElements","get","storageElement","document","getElementById","preventDefault","hasAccessorOnPrototype","proto","getPrototypeOf","descriptor","getOwnPropertyDescriptor","set","Storage","HTMLElement","wcBindable","observedAttributes","_core","_trigger","_connectedCallbackPromise","_internals","_initInternals","_wireStates","STORAGE_EVENTS_loadingChanged","d","STORAGE_EVENTS_error","debugStates","states","attachInternals","internals","add","delete","map","toStates","entries","debug","hasAttribute","on","toggleAttribute","_syncCore","setAttribute","manual","connectedCallbackPromise","removeAttribute","trigger","attributeChangedCallback","_oldValue","isConnected","connectedCallback","element","declaration","input","prototype","hasOwnProperty","call","record","upgradeProperties","style","display","disconnectedCallback","define"],"mappings":"AAUA,MA4BaA,EA5BoB,CAE/BC,iBAAkB,qBAClBC,SAAU,CACRC,QAAS,gBCPAC,EACG,4BADHA,EAEK,8BAFLA,EAGJ,oBAHIA,EAIO,iCAJPA,EAKK,8BCCLC,EAEM,mBAFNA,EAII,iBAJJA,EAMC,cANDA,EAQG,gBChBV,MAAOC,UAAoBC,YAC/BC,kBAAiC,CAC/BC,SAAU,cACVC,QAAS,EACTC,WAAY,CACV,CAAEC,KAAM,QAASC,MAAOT,EAA6BU,UAAW,QAASC,OAASC,GAAcA,EAAkBC,QAClH,CAAEL,KAAM,UAAWC,MAAOT,EAA+BU,UAAW,SACpE,CAAEF,KAAM,QAASC,MAAOT,EAAsBU,UAAW,SAKzD,CAAEF,KAAM,YAAaC,MAAOT,EAAiCU,UAAW,UAE1EI,OAAQ,CACN,CAAEN,KAAM,OACR,CAAEA,KAAM,SAGVO,SAAU,CACR,CAAEP,KAAM,QACR,CAAEA,KAAM,QACR,CAAEA,KAAM,YAIJQ,QACAC,OAAc,KACdC,UAAoB,EACpBC,OAAc,KACdC,WAAoC,KACpCC,KAAe,GACfC,MAAqB,QACrBC,iBAAuD,KAMvDC,KAAO,EAGPC,OAAwBC,QAAQC,UAExC,WAAAC,CAAYC,GACVC,QACAC,KAAKf,QAAUa,GAAUE,IAC3B,CAEA,SAAIC,GACF,OAAOD,KAAKN,M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N,EAAOqI,EAAMrI,KACnB,IAAK8B,OAAOwG,UAAUC,eAAeC,KAAKL,EAASnI,GAAO,SAC1D,IAAKyF,EAAuB0C,EAASnI,GAAO,SAC5C,MAAMyI,EAASN,EACTvG,EAAQ6G,EAAOzI,UACdyI,EAAOzI,GACdyI,EAAOzI,GAAQ4B,CACjB,CACF,CCyLI8G,CAAkBnH,MAClBA,KAAKoH,MAAMC,QAAU,OFxNnBjE,IACJA,GAAa,EACbW,SAASb,iBAAiB,QAASG,KE0N5BrD,KAAKoG,QAAUpG,KAAKa,KACvBb,KAAKoC,OAQPpC,KAAKkG,YACLlG,KAAK4E,MAAM9B,WACb,CAEA,oBAAAwE,GACEtH,KAAK4E,MAAMxE,UACb,ECpQKwD,eAAeC,IAAIhG,EAAOE,SAASC,UACtC4F,eAAe2D,OAAO1J,EAAOE,SAASC,QAASwG"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@wcstack/storage",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.27.0",
|
|
4
4
|
"description": "Declarative persistent storage component for Web Components. Framework-agnostic localStorage/sessionStorage via wc-bindable-protocol.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.esm.js",
|
package/dist/auto.js
DELETED
package/dist/index.esm.min.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
const e={autoTrigger:!0,triggerAttribute:"data-storagetarget",tagNames:{storage:"wcs-storage"}};function t(e){if(null===e||"object"!=typeof e)return e;Object.freeze(e);for(const r of Object.keys(e))t(e[r]);return e}function r(e){if(null===e||"object"!=typeof e)return e;const t={};for(const s of Object.keys(e))t[s]=r(e[s]);return t}let s=null;const i=e;function n(){return s||(s=t(r(e))),s}const o="wcs-storage:value-changed",a="wcs-storage:loading-changed",l="wcs-storage:error",c="wcs-storage:error-info-changed",u="wcs-storage:trigger-changed",g={InvalidArgument:"invalid-argument",QuotaExceeded:"quota-exceeded",NotAllowed:"not-allowed",StorageError:"storage-error"};class h extends EventTarget{static wcBindable={protocol:"wc-bindable",version:1,properties:[{name:"value",event:o,semantics:"state",getter:e=>e.detail},{name:"loading",event:a,semantics:"state"},{name:"error",event:l,semantics:"state"},{name:"errorInfo",event:c,semantics:"state"}],inputs:[{name:"key"},{name:"type"}],commands:[{name:"load"},{name:"save"},{name:"remove"}]};_target;_value=null;_loading=!1;_error=null;_errorInfo=null;_key="";_type="local";_storageListener=null;_gen=0;_ready=Promise.resolve();constructor(e){super(),this._target=e??this}get ready(){return this._ready}observe(){return this._ready}dispose(){this._gen++,this.stopSync()}get value(){return this._value}set value(e){Object.is(e,this._value)||this._setValue(e)}get loading(){return this._loading}get error(){return this._error}get errorInfo(){return this._errorInfo}get key(){return this._key}set key(e){this._key=String(e)}get type(){return this._type}set type(e){"local"===e||"session"===e?this._type=e:this._setError({operation:"type",message:`Invalid storage type: "${e}". Must be "local" or "session".`})}_getStorage(){return"session"===this._type?sessionStorage:localStorage}_setLoading(e){this._loading=e,this._target.dispatchEvent(new CustomEvent(a,{detail:e,bubbles:!0}))}_setError(e,t){this._error!==e&&(this._error=e,this._commitErrorInfo(null===e?null:function(e,t){return void 0===t?{code:g.InvalidArgument,phase:"start",recoverable:!1,message:e.message}:"QuotaExceededError"===t?{code:g.QuotaExceeded,phase:"execute",recoverable:!0,message:e.message}:"SecurityError"===t?{code:g.NotAllowed,phase:"execute",recoverable:!1,message:e.message}:{code:g.StorageError,phase:"execute",recoverable:!0,message:e.message}}(e,t)),this._target.dispatchEvent(new CustomEvent(l,{detail:e,bubbles:!0})))}_commitErrorInfo(e){this._errorInfo=e,this._target.dispatchEvent(new CustomEvent(c,{detail:e,bubbles:!0}))}_toStorageError(e,t){return{operation:e,message:t instanceof Error?t.message:String(t)}}_errName(e){return e instanceof Error?e.name:""}_setValue(e){this._value=e,this._target.dispatchEvent(new CustomEvent(o,{detail:e,bubbles:!0}))}load(){if(!this._key)return this._setError({operation:"load",message:"key is required."}),null;this._setLoading(!0),this._setError(null);try{const e=this._getStorage().getItem(this._key);if(null===e)this._setValue(null);else try{this._setValue(JSON.parse(e))}catch{this._setValue(e)}return this._setLoading(!1),this._value}catch(e){return this._setError(this._toStorageError("load",e),this._errName(e)),this._setLoading(!1),null}}save(e){if(this._key){this._setLoading(!0),this._setError(null);try{const t=this._getStorage();null==e?(t.removeItem(this._key),this._setValue(null)):"string"==typeof e?(t.setItem(this._key,e),this._setValue(e)):(t.setItem(this._key,JSON.stringify(e)),this._setValue(e)),this._setLoading(!1)}catch(e){this._setError(this._toStorageError("save",e),this._errName(e)),this._setLoading(!1)}}else this._setError({operation:"save",message:"key is required."})}remove(){if(this._key){this._setLoading(!0),this._setError(null);try{this._getStorage().removeItem(this._key),this._setValue(null),this._setLoading(!1)}catch(e){this._setError(this._toStorageError("remove",e),this._errName(e)),this._setLoading(!1)}}else this._setError({operation:"remove",message:"key is required."})}startSync(){if(this._storageListener)return;const e=++this._gen;this._storageListener=t=>{if(e===this._gen&&t.key===this._key&&"session"!==this._type)if(this._setError(null),null===t.newValue)this._setValue(null);else try{this._setValue(JSON.parse(t.newValue))}catch{this._setValue(t.newValue)}},globalThis.addEventListener("storage",this._storageListener)}stopSync(){this._storageListener&&(globalThis.removeEventListener("storage",this._storageListener),this._storageListener=null)}}let _=!1;function d(e){const t=e.target;if(!(t instanceof Element))return;const r=t.closest(`[${i.triggerAttribute}]`);if(!r)return;const s=r.getAttribute(i.triggerAttribute);if(!s)return;const n=customElements.get(i.tagNames.storage),o=document.getElementById(s);n&&o instanceof n&&(e.preventDefault(),o.save())}function m(e,t){let r=Object.getPrototypeOf(e);for(;null!==r;){const e=Object.getOwnPropertyDescriptor(r,t);if(void 0!==e)return"function"==typeof e.get||"function"==typeof e.set;r=Object.getPrototypeOf(r)}return!1}class y extends HTMLElement{static hasConnectedCallbackPromise=!0;static wcBindable={...h.wcBindable,properties:[...h.wcBindable.properties,{name:"trigger",event:u,semantics:"state"}],inputs:[{name:"key"},{name:"type"},{name:"value"},{name:"manual"},{name:"trigger"}]};static get observedAttributes(){return["key","type"]}_core;_trigger=!1;_connectedCallbackPromise=Promise.resolve();_internals=null;constructor(){super(),this._core=new h(this),this._internals=this._initInternals(),this._wireStates({[a]:e=>({loading:!0===e}),[l]:e=>({error:null!=e})})}get debugStates(){return this._internals?[...this._internals.states]:[]}_initInternals(){try{if("function"!=typeof this.attachInternals)return null;const e=this.attachInternals();return e.states.add("wcs-probe"),e.states.delete("wcs-probe"),e}catch{return null}}_wireStates(e){if(null===this._internals)return;const t=this._internals.states;for(const[r,s]of Object.entries(e))this.addEventListener(r,e=>{const r=this.hasAttribute("debug-states");for(const[i,n]of Object.entries(s(e.detail))){try{n?t.add(i):t.delete(i)}catch{}r&&this.toggleAttribute(`data-wcs-state-${i}`,n)}})}_syncCore(){this._core.key=this.key,this._core.type=this.type}get key(){return this.getAttribute("key")||""}set key(e){this.setAttribute("key",e)}get type(){return"session"===this.getAttribute("type")?"session":"local"}set type(e){this.setAttribute("type",e)}get value(){return this._core.value}set value(e){this.manual?this._core.value=e:(this._syncCore(),this._core.save(e))}get loading(){return this._core.loading}get error(){return this._core.error}get errorInfo(){return this._core.errorInfo}get connectedCallbackPromise(){return this._connectedCallbackPromise}get manual(){return this.hasAttribute("manual")}set manual(e){e?this.setAttribute("manual",""):this.removeAttribute("manual")}get trigger(){return this._trigger}set trigger(e){if(!!e){this._trigger=!0;try{this.save()}finally{this._trigger=!1,this.dispatchEvent(new CustomEvent(u,{detail:!1,bubbles:!0}))}}}load(){return this._syncCore(),this._core.load()}save(){this._syncCore(),this._core.save(this._core.value)}remove(){this._syncCore(),this._core.remove()}attributeChangedCallback(e,t,r){this.isConnected&&("key"===e&&(this._syncCore(),r&&!this.manual&&this.load()),"type"===e&&this._syncCore())}connectedCallback(){!function(e){const t=e.constructor?.wcBindable,r=t?.inputs;if(void 0!==r)for(const t of r){const r=t.name;if(!Object.prototype.hasOwnProperty.call(e,r))continue;if(!m(e,r))continue;const s=e,i=s[r];delete s[r],s[r]=i}}(this),this.style.display="none",i.autoTrigger&&(_||(_=!0,document.addEventListener("click",d))),!this.manual&&this.key&&this.load(),this._syncCore(),this._core.startSync()}disconnectedCallback(){this._core.stopSync()}}function f(t){t&&function(t){if("boolean"==typeof t.autoTrigger&&(e.autoTrigger=t.autoTrigger),"string"==typeof t.triggerAttribute&&(e.triggerAttribute=t.triggerAttribute),t.tagNames)for(const[r,s]of Object.entries(t.tagNames))"string"==typeof s&&(e.tagNames[r]=s);s=null}(t),customElements.get(i.tagNames.storage)||customElements.define(i.tagNames.storage,y)}export{h as StorageCore,g as WCS_STORAGE_ERROR_CODE,y as WcsStorage,f as bootstrapStorage,n as getConfig};
|
|
2
|
-
//# sourceMappingURL=index.esm.min.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index.esm.min.js","sources":["../src/config.ts","../src/events.ts","../src/core/storageCapabilities.ts","../src/core/StorageCore.ts","../src/autoTrigger.ts","../src/protocol/upgradeProperties.ts","../src/components/Storage.ts","../src/bootstrapStorage.ts","../src/registerComponents.ts"],"sourcesContent":["import { IConfig, IWritableConfig } from \"./types.js\";\n\ninterface IInternalConfig extends IConfig {\n autoTrigger: boolean;\n triggerAttribute: string;\n tagNames: {\n storage: string;\n };\n}\n\nconst _config: IInternalConfig = {\n autoTrigger: true,\n triggerAttribute: \"data-storagetarget\",\n tagNames: {\n storage: \"wcs-storage\",\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 (typeof partialConfig.autoTrigger === \"boolean\") {\n _config.autoTrigger = partialConfig.autoTrigger;\n }\n if (typeof partialConfig.triggerAttribute === \"string\") {\n _config.triggerAttribute = partialConfig.triggerAttribute;\n }\n if (partialConfig.tagNames) {\n // Validate each tagNames entry individually instead of a blanket\n // Object.assign: a non-string (e.g. { storage: undefined }) would otherwise\n // poison the config and make customElements.define(undefined, …) throw at\n // registration time. Mirrors the typeof guards on autoTrigger / triggerAttribute.\n for (const [key, value] of Object.entries(partialConfig.tagNames)) {\n if (typeof value === \"string\") {\n (_config.tagNames as Record<string, string>)[key] = value;\n }\n }\n }\n frozenConfig = null;\n}\n","// Single source of truth for the custom event names dispatched by StorageCore /\n// Storage. These names appear in two places that must stay in lock-step:\n// 1. the `wcBindable.properties[].event` declarations (consumed by bind())\n// 2. the `dispatchEvent(new CustomEvent(...))` calls that emit them\n// Hard-coding the same string literal in both places risks a silent typo that\n// makes bind() listen for an event no one ever fires. Referencing these\n// constants from both sites keeps them in sync.\nexport const STORAGE_EVENTS = {\n valueChanged: \"wcs-storage:value-changed\",\n loadingChanged: \"wcs-storage:loading-changed\",\n error: \"wcs-storage:error\",\n errorInfoChanged: \"wcs-storage:error-info-changed\",\n triggerChanged: \"wcs-storage:trigger-changed\",\n} as const;\n","/**\n * storageCapabilities.ts\n *\n * Storage node 固有の error code(taxonomy)と derivation。汎用の error info 型は\n * `./platformCapability.js`(/io-core/ から copy-distribution される生成ファイル)から\n * import する。storage の load / save / remove は同期で互いに競合しないため lane は\n * 持たず、error taxonomy(errorInfo)のみを採用する。\n */\n\nimport type { WcsIoErrorInfo } from \"./platformCapability.js\";\nimport type { WcsStorageError } from \"../types.js\";\n\n/** 安定した storage error code(taxonomy)。値は公開キーとして固定。 */\nexport const WCS_STORAGE_ERROR_CODE = {\n /** `key` 未設定 / 不正な `type` などの入力不備。retry では回復しない。 */\n InvalidArgument: \"invalid-argument\",\n /** `QuotaExceededError` — 容量超過。空きを作れば回復しうる(環境要因)。 */\n QuotaExceeded: \"quota-exceeded\",\n /** `SecurityError` — storage アクセス拒否(cookie 無効 / third-party context 等)。retry では回復しない。 */\n NotAllowed: \"not-allowed\",\n /** その他の caught 例外。 */\n StorageError: \"storage-error\",\n} as const;\n\n/**\n * storage の失敗を serializable な error taxonomy に写す。\n *\n * `name` は caught 例外の `Error.name`(load / save / remove の catch から渡る)。\n * 未指定(undefined)は inline 構築の validation error(不正 `type` / `key` 未設定)を意味し、\n * これは開始前の入力不備なので phase=\"start\" / `invalid-argument` / recoverable=false。\n * caught 例外は実行中の失敗なので phase=\"execute\"。`QuotaExceededError` は環境要因で\n * 空きを作れば回復しうる(recoverable=true)、`SecurityError` は retry で回復しない。\n */\nexport function deriveStorageErrorInfo(error: WcsStorageError, name?: string): WcsIoErrorInfo {\n if (name === undefined) {\n return {\n code: WCS_STORAGE_ERROR_CODE.InvalidArgument,\n phase: \"start\",\n recoverable: false,\n message: error.message,\n };\n }\n if (name === \"QuotaExceededError\") {\n return { code: WCS_STORAGE_ERROR_CODE.QuotaExceeded, phase: \"execute\", recoverable: true, message: error.message };\n }\n if (name === \"SecurityError\") {\n return { code: WCS_STORAGE_ERROR_CODE.NotAllowed, phase: \"execute\", recoverable: false, message: error.message };\n }\n return { code: WCS_STORAGE_ERROR_CODE.StorageError, phase: \"execute\", recoverable: true, message: error.message };\n}\n","import { STORAGE_EVENTS } from \"../events.js\";\nimport { IWcBindable, StorageType, WcsStorageError } from \"../types.js\";\nimport { WcsIoErrorInfo } from \"./platformCapability.js\";\nimport { deriveStorageErrorInfo } from \"./storageCapabilities.js\";\n\nexport class StorageCore extends EventTarget {\n static wcBindable: IWcBindable = {\n protocol: \"wc-bindable\",\n version: 1,\n properties: [\n { name: \"value\", event: STORAGE_EVENTS.valueChanged, semantics: \"state\", getter: (e: Event) => (e as CustomEvent).detail },\n { name: \"loading\", event: STORAGE_EVENTS.loadingChanged, semantics: \"state\" },\n { name: \"error\", event: STORAGE_EVENTS.error, semantics: \"state\" },\n // Serializable failure taxonomy (stable code / phase / recoverable), or null.\n // Additive bindable output derived from `error` (invalid-argument / quota-exceeded\n // / not-allowed / storage-error); the existing `error` property/event are unchanged.\n // Fires wcs-storage:error-info-changed. No lane — load/save/remove don't compete.\n { name: \"errorInfo\", event: STORAGE_EVENTS.errorInfoChanged, semantics: \"state\" },\n ],\n inputs: [\n { name: \"key\" },\n { name: \"type\" },\n ],\n // load / save / remove are synchronous, so none carry the `async` hint.\n commands: [\n { name: \"load\" },\n { name: \"save\" },\n { name: \"remove\" },\n ],\n };\n\n private _target: EventTarget;\n private _value: any = null;\n private _loading: boolean = false;\n private _error: any = null;\n private _errorInfo: WcsIoErrorInfo | null = null;\n private _key: string = \"\";\n private _type: StorageType = \"local\";\n private _storageListener: ((e: StorageEvent) => void) | null = null;\n // Generation guard: bumped on dispose(). The cross-tab `storage` listener\n // captures the generation active when startSync() ran; a callback that fires\n // after dispose() (or a teardown→re-setup) has a stale gen and MUST NOT write\n // state to a torn-down element. A boolean flag is insufficient (dispose→observe\n // would let a stale listener slip through).\n private _gen = 0;\n // SSR: storage access is synchronous, so there is no asynchronous probe to\n // await — readiness is immediate.\n private _ready: Promise<void> = Promise.resolve();\n\n constructor(target?: EventTarget) {\n super();\n this._target = target ?? this;\n }\n\n get ready(): Promise<void> {\n return this._ready;\n }\n\n // Lifecycle (§3.5). Storage sync is command-driven (the Shell calls startSync()\n // from connectedCallback), so observe() is an idempotent no-op that resolves\n // once ready; dispose() tears down the cross-tab listener and invalidates any\n // in-flight listener callback.\n observe(): Promise<void> {\n return this._ready;\n }\n\n dispose(): void {\n this._gen++;\n this.stopSync();\n }\n\n get value(): any {\n return this._value;\n }\n\n // Set the current value *without* persisting it. Persistence happens only via\n // save() / remove() / a cross-tab storage event. This setter exists so the\n // Shell (manual mode) can stage a value handed in via a `value` binding and\n // then commit it later with save()/trigger. It mirrors the value to observers\n // through the same `value-changed` event load()/save() use (CSBC: a Core value\n // change is observable), but it deliberately does not touch storage.\n //\n // Same-value writes are skipped to break a potential feedback loop:\n // value-changed → state binding → value setter → value-changed → …\n set value(v: any) {\n if (Object.is(v, this._value)) return;\n this._setValue(v);\n }\n\n get loading(): boolean {\n return this._loading;\n }\n\n get error(): any {\n return this._error;\n }\n\n /**\n * The last failure's serializable `WcsIoErrorInfo` (stable `code` / `phase` /\n * `recoverable`), or null. Additive wc-bindable property (event\n * `wcs-storage:error-info-changed`), derived from `error`; the existing `error`\n * property/event are unchanged.\n */\n get errorInfo(): WcsIoErrorInfo | null {\n return this._errorInfo;\n }\n\n get key(): string {\n return this._key;\n }\n\n set key(value: string) {\n // Defensive normalization for direct Core use (the Shell already passes a\n // string via `getAttribute(\"key\") || \"\"`). Coercing to String keeps a\n // non-string assignment from poisoning the cross-tab `e.key !== _key`\n // comparison; empty keys are still rejected at operation time.\n this._key = String(value);\n }\n\n get type(): StorageType {\n return this._type;\n }\n\n set type(value: StorageType) {\n if (value !== \"local\" && value !== \"session\") {\n // never-throw: an invalid type is routed to the error property and the\n // current type is kept (the safe default), rather than throwing out of the\n // setter / setAttribute / connectedCallback.\n this._setError({ operation: \"type\", message: `Invalid storage type: \"${value}\". Must be \"local\" or \"session\".` });\n return;\n }\n this._type = value;\n }\n\n private _getStorage(): globalThis.Storage {\n return this._type === \"session\" ? sessionStorage : localStorage;\n }\n\n private _setLoading(loading: boolean): void {\n this._loading = loading;\n this._target.dispatchEvent(new CustomEvent(STORAGE_EVENTS.loadingChanged, {\n detail: loading,\n bubbles: true,\n }));\n }\n\n // `name` is the caught exception's `Error.name` (passed only from the\n // load/save/remove catch blocks); it stays out of the public `error` shape and\n // is used solely to classify errorInfo (quota vs security vs generic). Inline\n // validation errors (invalid type / missing key) pass no name → invalid-argument.\n private _setError(error: any, name?: string): void {\n // Same-value guard (async-io-node-guidelines.md §3.3). `error` is state-ish,\n // so suppressing redundant null→null dispatches (every load/save/remove start\n // clears a usually-already-null error) avoids a spurious error event per\n // successful operation. Reference identity is sufficient: each failure builds\n // a fresh object, and the clear path always passes null.\n if (this._error === error) return;\n this._error = error;\n // Keep the additive `errorInfo` taxonomy in sync with `error`: derive from the\n // error (or null on clear). Fires before the `error` event so an observer\n // binding both sees the classification first, mirroring the io-node family.\n this._commitErrorInfo(error === null ? null : deriveStorageErrorInfo(error, name));\n this._target.dispatchEvent(new CustomEvent(STORAGE_EVENTS.error, {\n detail: error,\n bubbles: true,\n }));\n }\n\n // Called only from _setError (which already same-value-guards on the error\n // reference), so errorInfo transitions exactly when error does — no separate\n // guard needed here.\n private _commitErrorInfo(info: WcsIoErrorInfo | null): void {\n this._errorInfo = info;\n this._target.dispatchEvent(new CustomEvent(STORAGE_EVENTS.errorInfoChanged, {\n detail: info,\n bubbles: true,\n }));\n }\n\n // Wrap a caught storage exception into the documented WcsStorageError shape,\n // tagging it with the failing operation so consumers know which call failed.\n private _toStorageError(operation: WcsStorageError[\"operation\"], e: unknown): WcsStorageError {\n return {\n operation,\n message: e instanceof Error ? e.message : String(e),\n };\n }\n\n // The caught exception's `Error.name` for errorInfo classification (quota vs\n // security vs generic), or \"\" for a non-Error throw (→ storage-error). Returning\n // a string (never undefined) keeps a caught exception in the execute phase; only\n // inline validation errors, which pass no name to _setError, become start-phase\n // invalid-argument. Single chokepoint so the ternary is covered in one place.\n private _errName(e: unknown): string {\n return e instanceof Error ? e.name : \"\";\n }\n\n private _setValue(value: any): void {\n this._value = value;\n this._target.dispatchEvent(new CustomEvent(STORAGE_EVENTS.valueChanged, {\n detail: value,\n bubbles: true,\n }));\n }\n\n load(): any {\n if (!this._key) {\n // never-throw: a missing key is routed to the error property and a\n // sanitized null is returned, rather than throwing.\n this._setError({ operation: \"load\", message: \"key is required.\" });\n return null;\n }\n\n this._setLoading(true);\n this._setError(null);\n\n try {\n const storage = this._getStorage();\n const raw = storage.getItem(this._key);\n\n if (raw === null) {\n this._setValue(null);\n } else {\n try {\n this._setValue(JSON.parse(raw));\n } catch {\n this._setValue(raw);\n }\n }\n\n this._setLoading(false);\n return this._value;\n } catch (e: any) {\n this._setError(this._toStorageError(\"load\", e), this._errName(e));\n this._setLoading(false);\n return null;\n }\n }\n\n save(value: any): void {\n if (!this._key) {\n // never-throw: a missing key is routed to the error property instead of\n // throwing. No return value to sanitize (save returns void).\n this._setError({ operation: \"save\", message: \"key is required.\" });\n return;\n }\n\n this._setLoading(true);\n this._setError(null);\n\n try {\n const storage = this._getStorage();\n\n if (value === null || value === undefined) {\n storage.removeItem(this._key);\n // Normalize the removed value to null (matching remove() and load() of a\n // missing key) so saving `undefined` does not leave the getter returning\n // `undefined`. README's serialization table documents null/undefined as\n // \"null\" on read-back.\n this._setValue(null);\n } else if (typeof value === \"string\") {\n storage.setItem(this._key, value);\n this._setValue(value);\n } else {\n storage.setItem(this._key, JSON.stringify(value));\n this._setValue(value);\n }\n\n this._setLoading(false);\n } catch (e: any) {\n this._setError(this._toStorageError(\"save\", e), this._errName(e));\n this._setLoading(false);\n }\n }\n\n remove(): void {\n if (!this._key) {\n // never-throw: a missing key is routed to the error property instead of\n // throwing. No return value to sanitize (remove returns void).\n this._setError({ operation: \"remove\", message: \"key is required.\" });\n return;\n }\n\n this._setLoading(true);\n this._setError(null);\n\n try {\n const storage = this._getStorage();\n storage.removeItem(this._key);\n this._setValue(null);\n this._setLoading(false);\n } catch (e: any) {\n this._setError(this._toStorageError(\"remove\", e), this._errName(e));\n this._setLoading(false);\n }\n }\n\n startSync(): void {\n if (this._storageListener) return;\n\n // Capture the generation active when sync starts. A `storage` event that\n // fires after dispose() (which bumps _gen and removes the listener) carries a\n // stale gen and must not write state to a torn-down element. stopSync()\n // already detaches the listener, but the gen guard also covers a queued event\n // delivered between dispose()'s bump and the actual removeEventListener.\n const gen = ++this._gen;\n\n this._storageListener = (e: StorageEvent) => {\n if (gen !== this._gen) return;\n if (e.key !== this._key) return;\n if (this._type === \"session\") return;\n\n // A fresh value arriving from another tab supersedes any stale error from\n // a prior failed load/save/remove. Clearing it here keeps the sync path\n // consistent with load()/save()/remove(), which all reset error to null at\n // the start of a successful operation — otherwise an \"error present + fresh\n // value\" inconsistency could persist after a cross-tab update.\n this._setError(null);\n\n if (e.newValue === null) {\n this._setValue(null);\n } else {\n try {\n this._setValue(JSON.parse(e.newValue));\n } catch {\n this._setValue(e.newValue);\n }\n }\n };\n\n globalThis.addEventListener(\"storage\", this._storageListener);\n }\n\n stopSync(): void {\n if (!this._storageListener) return;\n globalThis.removeEventListener(\"storage\", this._storageListener);\n this._storageListener = null;\n }\n}\n","import { config } from \"./config.js\";\nimport type { Storage } from \"./components/Storage.js\";\n\nlet registered = false;\n\nfunction handleClick(event: Event): void {\n const target = event.target;\n if (!(target instanceof Element)) return;\n\n const triggerElement = target.closest<Element>(`[${config.triggerAttribute}]`);\n if (!triggerElement) return;\n\n const storageId = triggerElement.getAttribute(config.triggerAttribute);\n if (!storageId) return;\n\n // Resolve the registered constructor at call time instead of importing Storage\n // as a value. The value import created a components/Storage.ts ⇄ autoTrigger.ts\n // cycle (Storage.connectedCallback() calls registerAutoTrigger()). instanceof\n // against the customElements registry keeps the exact same identity guarantee\n // — only the registered <wcs-storage> class matches — without the import cycle.\n const StorageCtor = customElements.get(config.tagNames.storage);\n const storageElement = document.getElementById(storageId);\n if (!StorageCtor || !(storageElement instanceof StorageCtor)) return;\n\n event.preventDefault();\n (storageElement as Storage).save();\n}\n\nexport function registerAutoTrigger(): void {\n if (registered) return;\n registered = true;\n document.addEventListener(\"click\", handleClick);\n}\n\nexport function unregisterAutoTrigger(): void {\n if (!registered) return;\n registered = false;\n document.removeEventListener(\"click\", handleClick);\n}\n","// ===========================================================================\n// AUTO-GENERATED FILE - DO NOT EDIT.\n// Generated from /protocol/upgrade-properties.ts by scripts/sync-protocol-types.mjs.\n// Run `node scripts/sync-protocol-types.mjs` after editing the source.\n// ===========================================================================\n\n// custom element の property upgrade — `static wcBindable.inputs` に宣言した入力のうち、\n// 要素が upgrade される前に代入された own データプロパティを取り込み直す。\n//\n// なぜ必要か:\n// 未定義タグの要素は素の HTMLElement なので、`el.url = \"...\"` は own データプロパティを作る。\n// upgrade 後にクラスの accessor が prototype へ入っても own プロパティが優先されるため、\n// setter は二度と呼ばれず、値は要素へ届かないまま消える(エラーも警告も出ない)。\n// 常にプロパティ代入を行う framework(Angular の `[prop]`、Lit の `.prop=`、\n// Solid の `prop:`、Vue の `.prop` 修飾子)× 遅延定義(autoloader / CDN / code-split)で\n// 常態的に起きる。docs/architecture-hardening/13-framework-adapter-binding-constraints.md §1.2。\n//\n// 安全側の判定:\n// own プロパティがあっても、prototype チェーンに accessor が無ければ「シャドウ」ではなく\n// その own プロパティ自体が正規の格納先なので触らない(public class field を壊さない)。\n//\n// SINGLE SOURCE OF TRUTH: edit only this file (/protocol/upgrade-properties.ts), then run\n// `node scripts/sync-protocol-types.mjs` to regenerate the per-package copies\n// (packages/<pkg>/src/protocol/upgradeProperties.ts). Those copies are generated — do not edit them.\nimport { IWcBindable } from \"./wcBindable.js\";\n\nfunction hasAccessorOnPrototype(target: object, name: string): boolean {\n let proto = Object.getPrototypeOf(target);\n while (proto !== null) {\n const descriptor = Object.getOwnPropertyDescriptor(proto, name);\n if (descriptor !== undefined) {\n return typeof descriptor.get === \"function\" || typeof descriptor.set === \"function\";\n }\n proto = Object.getPrototypeOf(proto);\n }\n return false;\n}\n\n/**\n * `connectedCallback` の先頭で呼ぶ。宣言済み input のうち upgrade 前の代入で\n * accessor をシャドウしている own プロパティを、delete → 再代入で setter に通し直す。\n *\n * - 冪等: 再代入は accessor を通るので own プロパティは残らず、2 回目以降は no-op。\n * - 宣言に `inputs` が無い要素、`wcBindable` を持たない要素では何もしない。\n * - 値の意味は変えない。今まで捨てられていた代入が届くようになる一方向の変化。\n */\nexport function upgradeProperties(element: object): void {\n const declaration = (element as { constructor?: { wcBindable?: IWcBindable } }).constructor?.wcBindable;\n const inputs = declaration?.inputs;\n if (inputs === undefined) return;\n for (const input of inputs) {\n const name = input.name;\n if (!Object.prototype.hasOwnProperty.call(element, name)) continue;\n if (!hasAccessorOnPrototype(element, name)) continue;\n const record = element as Record<string, unknown>;\n const value = record[name];\n delete record[name];\n record[name] = value;\n }\n}\n","import { config } from \"../config.js\";\nimport { STORAGE_EVENTS } from \"../events.js\";\nimport { IWcBindable, StorageType } from \"../types.js\";\nimport { StorageCore } from \"../core/StorageCore.js\";\nimport { WcsIoErrorInfo } from \"../core/platformCapability.js\";\nimport { registerAutoTrigger } from \"../autoTrigger.js\";\nimport { upgradeProperties } from \"../protocol/upgradeProperties.js\";\n\nexport class Storage extends HTMLElement {\n static hasConnectedCallbackPromise = true;\n static wcBindable: IWcBindable = {\n ...StorageCore.wcBindable,\n properties: [\n ...StorageCore.wcBindable.properties,\n { name: \"trigger\", event: STORAGE_EVENTS.triggerChanged, semantics: \"state\" },\n ],\n // Shell-level input surface. The Core declares only the portable `key` / `type`;\n // the Shell adds the DOM-driven settable surface. No `attribute` hints are given:\n // the `key` / `type` / `manual` setters already reflect to their attributes, so a\n // binding system that mirrors inputs[].attribute would set the attribute twice\n // (`value` / `trigger` are not attribute-backed). `commands` (load / save / remove)\n // are inherited unchanged from the Core via the spread above.\n inputs: [\n { name: \"key\" },\n { name: \"type\" },\n { name: \"value\" },\n { name: \"manual\" },\n { name: \"trigger\" },\n ],\n };\n static get observedAttributes(): string[] { return [\"key\", \"type\"]; }\n\n private _core: StorageCore;\n private _trigger: boolean = false;\n // Storage load()/save() are synchronous, so connection work never defers.\n // This stays an already-resolved Promise for the whole lifecycle; it exists\n // only to satisfy the `hasConnectedCallbackPromise` protocol (consumers may\n // `await el.connectedCallbackPromise`). connectedCallback intentionally does\n // not reassign it — there is nothing async to wait for, unlike <wcs-fetch>.\n private _connectedCallbackPromise: Promise<void> = Promise.resolve();\n private _internals: ElementInternals | null = null;\n\n constructor() {\n super();\n this._core = new StorageCore(this);\n this._internals = this._initInternals();\n this._wireStates({\n [STORAGE_EVENTS.loadingChanged]: (d) => ({ loading: d === true }),\n [STORAGE_EVENTS.error]: (d) => ({ error: d != null }),\n });\n }\n\n // CSS state reflection (:state()) — debug-only snapshot getter. NOT part of\n // wc-bindable (not a bind target); see README \"CSS styling with :state()\".\n // MUST NOT return the live CustomStateSet (that would let callers write\n // states from outside, defeating the point of :state() being read-only).\n get debugStates(): string[] {\n return this._internals ? [...this._internals.states] : [];\n }\n\n private _initInternals(): ElementInternals | null {\n // never-throw (async-io-node-guidelines.md §3.6): attachInternals is absent\n // in happy-dom / older environments, and pre-125 Chromium rejects\n // non-dashed state names from states.add() (probed and discarded here).\n // Either case silently disables reflection — the component still works,\n // it just doesn't expose :state() selectors.\n try {\n if (typeof this.attachInternals !== \"function\") return null;\n const internals = this.attachInternals();\n internals.states.add(\"wcs-probe\");\n internals.states.delete(\"wcs-probe\");\n return internals;\n } catch {\n return null;\n }\n }\n\n private _wireStates(map: Record<string, (detail: any) => Record<string, boolean>>): void {\n if (this._internals === null) return;\n const states = this._internals.states;\n for (const [event, toStates] of Object.entries(map)) {\n this.addEventListener(event, (e) => {\n const debug = this.hasAttribute(\"debug-states\");\n for (const [name, on] of Object.entries(toStates((e as CustomEvent).detail))) {\n try {\n if (on) { states.add(name); } else { states.delete(name); }\n } catch { /* never-throw */ }\n if (debug) this.toggleAttribute(`data-wcs-state-${name}`, on);\n }\n });\n }\n }\n\n // Push the Shell's current attribute-derived key / type down into the Core.\n // Every operation (load / save / remove / value setter) and every lifecycle\n // hook that may run a Core operation or cross-tab sync must do this first, so\n // the Core never acts on a stale key / type. Centralizing it here avoids the\n // previous pattern of repeating `_core.key = …; _core.type = …;` at each call\n // site, which risked a future call site forgetting one of the two.\n private _syncCore(): void {\n this._core.key = this.key;\n this._core.type = this.type;\n }\n\n get key(): string {\n return this.getAttribute(\"key\") || \"\";\n }\n\n set key(value: string) {\n this.setAttribute(\"key\", value);\n }\n\n get type(): StorageType {\n // Normalize at the Shell boundary: any attribute value other than the\n // exact \"session\" falls back to \"local\". This keeps an invalid attribute\n // (e.g. type=\"foo\") from reaching the Core's validating setter and throwing\n // out of setAttribute / connectedCallback.\n return this.getAttribute(\"type\") === \"session\" ? \"session\" : \"local\";\n }\n\n set type(value: StorageType) {\n this.setAttribute(\"type\", value);\n }\n\n get value(): any {\n return this._core.value;\n }\n\n set value(v: any) {\n // Non-manual mode: assigning `value` auto-saves the *assigned* argument `v`\n // (write-through). Note this differs from save()/trigger, which persist the\n // *current* `_core.value` (which load() or a cross-tab `storage` event may\n // have updated). See README \"Design Notes\" for the rationale.\n //\n // Manual mode: assigning `value` does NOT persist — it only stages the value\n // into the Core (no storage write). This keeps the getter/setter consistent\n // (`el.value = x; el.value === x`) and lets a later save()/trigger commit the\n // staged value, so a `value: …` + `trigger: …` binding pair works as\n // documented. The actual write still happens only via save()/trigger.\n if (!this.manual) {\n this._syncCore();\n this._core.save(v);\n } else {\n this._core.value = v;\n }\n }\n\n get loading(): boolean {\n return this._core.loading;\n }\n\n get error(): any {\n return this._core.error;\n }\n\n get errorInfo(): WcsIoErrorInfo | null {\n return this._core.errorInfo;\n }\n\n get connectedCallbackPromise(): Promise<void> {\n return this._connectedCallbackPromise;\n }\n\n get manual(): boolean {\n return this.hasAttribute(\"manual\");\n }\n\n set manual(value: boolean) {\n if (value) {\n this.setAttribute(\"manual\", \"\");\n } else {\n this.removeAttribute(\"manual\");\n }\n }\n\n get trigger(): boolean {\n return this._trigger;\n }\n\n set trigger(value: boolean) {\n const v = !!value;\n if (v) {\n this._trigger = true;\n // save() is never-throw (a failure — e.g. key unset — is routed to the\n // `error` property, not thrown), but the try/finally is kept defensively\n // to guarantee the trigger resets to false and the completion event fires\n // even in the unexpected event of a throw, so the trigger never gets stuck\n // in the `true` state.\n try {\n this.save();\n } finally {\n this._trigger = false;\n this.dispatchEvent(new CustomEvent(STORAGE_EVENTS.triggerChanged, {\n detail: false,\n bubbles: true,\n }));\n }\n }\n }\n\n load(): any {\n this._syncCore();\n return this._core.load();\n }\n\n // The `save` command differs in arity between the two CSBC surfaces:\n // - Core: save(value) — caller supplies the value to persist\n // - Shell: save() — persists the current `_core.value` (no argument)\n // Both are exposed under the same `commands` entry name \"save\". The protocol\n // `commands` list is descriptive metadata only and carries no arity, so this\n // is not a protocol violation; the difference is contractual and documented\n // in the README (\"Design Notes\").\n save(): void {\n this._syncCore();\n this._core.save(this._core.value);\n }\n\n remove(): void {\n this._syncCore();\n this._core.remove();\n }\n\n attributeChangedCallback(name: string, _oldValue: string | null, newValue: string | null): void {\n if (!this.isConnected) return;\n if (name === \"key\") {\n // Always keep the Core's key in sync with the attribute, regardless of\n // mode or whether the new value is empty. The cross-tab `storage` listener\n // compares `e.key !== _core.key`, so a stale Core key would make sync watch\n // the wrong (old/empty) key after a runtime key change. load() (which also\n // syncs the Core) only runs for non-manual mode with a non-empty key.\n this._syncCore();\n if (newValue && !this.manual) {\n this.load();\n }\n }\n if (name === \"type\") {\n // Route through the normalizing getter so an invalid attribute value\n // (e.g. type=\"foo\") falls back to \"local\" instead of throwing.\n this._syncCore();\n }\n }\n\n connectedCallback(): void {\n // upgrade 前に代入された input を取り込み直す(doc 13 §1.2 / Phase A1)\n upgradeProperties(this);\n this.style.display = \"none\";\n if (config.autoTrigger) {\n registerAutoTrigger();\n }\n if (!this.manual && this.key) {\n this.load();\n }\n // Always bind the cross-tab watcher to the Shell's current key/type before\n // starting sync. In paths where load()/save() never run (e.g. manual mode,\n // or key set via JS without a load), _core.key/_core.type would otherwise\n // keep a stale/empty value and the storage listener's `e.key !== _key`\n // check would compare against the wrong key. This also covers detach →\n // re-attach: stale Core key from a previous session is overwritten here.\n this._syncCore();\n this._core.startSync();\n }\n\n disconnectedCallback(): void {\n this._core.stopSync();\n }\n}\n","import { setConfig } from \"./config.js\";\nimport { registerComponents } from \"./registerComponents.js\";\nimport { IWritableConfig } from \"./types.js\";\n\nexport function bootstrapStorage(userConfig?: IWritableConfig): void {\n if (userConfig) {\n setConfig(userConfig);\n }\n registerComponents();\n}\n","import { Storage } from \"./components/Storage.js\";\nimport { config } from \"./config.js\";\n\nexport function registerComponents(): void {\n if (!customElements.get(config.tagNames.storage)) {\n customElements.define(config.tagNames.storage, Storage);\n }\n}\n"],"names":["_config","autoTrigger","triggerAttribute","tagNames","storage","deepFreeze","obj","Object","freeze","key","keys","deepClone","clone","frozenConfig","config","getConfig","STORAGE_EVENTS","WCS_STORAGE_ERROR_CODE","InvalidArgument","QuotaExceeded","NotAllowed","StorageError","StorageCore","EventTarget","static","protocol","version","properties","name","event","semantics","getter","e","detail","inputs","commands","_target","_value","_loading","_error","_errorInfo","_key","_type","_storageListener","_gen","_ready","Promise","resolve","constructor","target","super","this","ready","observe","dispose","stopSync","value","v","is","_setValue","loading","error","errorInfo","String","type","_setError","operation","message","_getStorage","sessionStorage","localStorage","_setLoading","dispatchEvent","CustomEvent","bubbles","_commitErrorInfo","undefined","code","phase","recoverable","deriveStorageErrorInfo","info","_toStorageError","Error","_errName","load","raw","getItem","JSON","parse","save","removeItem","setItem","stringify","remove","startSync","gen","newValue","globalThis","addEventListener","removeEventListener","registered","handleClick","Element","triggerElement","closest","storageId","getAttribute","StorageCtor","customElements","get","storageElement","document","getElementById","preventDefault","hasAccessorOnPrototype","proto","getPrototypeOf","descriptor","getOwnPropertyDescriptor","set","Storage","HTMLElement","wcBindable","observedAttributes","_core","_trigger","_connectedCallbackPromise","_internals","_initInternals","_wireStates","STORAGE_EVENTS_loadingChanged","d","STORAGE_EVENTS_error","debugStates","states","attachInternals","internals","add","delete","map","toStates","entries","debug","hasAttribute","on","toggleAttribute","_syncCore","setAttribute","manual","connectedCallbackPromise","removeAttribute","trigger","attributeChangedCallback","_oldValue","isConnected","connectedCallback","element","declaration","input","prototype","hasOwnProperty","call","record","upgradeProperties","style","display","disconnectedCallback","bootstrapStorage","userConfig","partialConfig","setConfig","define"],"mappings":"AAUA,MAAMA,EAA2B,CAC/BC,aAAa,EACbC,iBAAk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