@keepkit/core 0.28.8 → 0.28.10

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.md CHANGED
@@ -2,191 +2,226 @@
2
2
 
3
3
  [日本語](#日本語) | [English](#english)
4
4
 
5
- ## 日本語
6
-
7
- フレームワーク中立の保存・コレクションプリミティブとReactの低レベルbindingを提供します。通常のReactアプリケーションでは、より少ないコードで利用できる`@keepkit/ui`を推奨します。
5
+ Release: v0.28.10
8
6
 
9
- ```tsx
10
- import { KeepButton, KeepProvider, useKeepItem, useKeepList } from "@keepkit/core/react";
11
- import { createBrowserStorageAdapter } from "@keepkit/core/storage";
7
+ ## 日本語
12
8
 
13
- const storage = createBrowserStorageAdapter({ key: "my-app:items" });
14
- const article = { id: "article-123", targetType: "article", meta: { title: "Example", url: "/article" } };
9
+ フレームワーク中立の保存処理と、React向けのProvider・hooksを提供します。
10
+ 標準の一覧UIが必要な場合は[@keepkit/ui](../keepkit-ui/README.md)を使ってください。記事向けの`presentation="reading"`と行内選択はUIパッケージの追加機能で、Coreの型・保存形式は変更しません。未訪問の判定には既存の`lastOpenedAt`と`recordOpen()`を使います。
15
11
 
16
- <KeepProvider storage={storage}>
17
- <KeepButton item={article} />
18
- </KeepProvider>;
12
+ ### インストールと入口
19
13
 
20
- const item = useKeepItem(article);
21
- const list = useKeepList({
22
- targetType: "article",
23
- search: { query: "react" },
24
- sort: { by: "updatedAt", direction: "desc" },
25
- pagination: { page: 1, pageSize: 20 },
26
- });
14
+ ```bash
15
+ pnpm add @keepkit/core
27
16
  ```
28
17
 
29
- `KeepItemInput`は`id`、`meta`、`targetType`、`note`、`tags`、`order`を持つ入力です。保存時刻・更新時刻・タグ正規化は内部で処理されます。
30
-
31
- `KeepListQuery`は`targetType`、`tags`、`search`、`sort`、`pagination`、`filter`、`savedBetween`で構成されます。`queryKeepItems`はReactなしで同じ条件を適用できます。
18
+ | import先 | 用途 |
19
+ | --- | --- |
20
+ | `@keepkit/core/core` | 型、ストア、検索、コレクション、バックアップなど。Reactへの依存なし |
21
+ | `@keepkit/core/react` | `createKeepKit`、`KeepProvider`、`KeepButton`、hooks |
22
+ | `@keepkit/core/storage` | localStorage・IndexedDB・fallback・同期adapter |
23
+ | `@keepkit/core/schema` | スキーマの解析・検証 |
32
24
 
33
- 整理状態は`organization: { collection, tags, note }`の`assigned` / `unassigned`で絞り込めます。`createInboxQuery()`は未分類アイテム向けの既定queryを返します。`useKeepList()`は一括archive、pin、collection移動を提供します。Saved Viewは`KeepSavedViewStorage` / `LocalStorageKeepSavedViewStorage`でアイテムと分けて保存できます。
25
+ パッケージルートにはexportがありません。React bindingはReact 18以降に対応します。
34
26
 
35
- 再発見には`useKeepItem(item).recordOpen()`で`lastOpenedAt`を記録し、`activity`の`opened`、`lastOpenedBefore`、`lastOpenedAfter`、`inactiveForMs`で絞り込めます。`inactiveForMs`は開封済みなら`lastOpenedAt`、未開封なら`savedAt`を基準に判定します。開封記録だけでは`updatedAt`を変更せず、同期・mergeでは新しいActivityを保持します。`createRediscoveryQuery()`は`never-opened`、`forgotten`、`recently-opened`のCore向けプリセットを提供し、`useKeepRediscovery()`はReact向けの一覧hookです。
27
+ ### Reactで使う
36
28
 
37
- 未保存ガイドも含む閲覧履歴には`LocalStorageKeepHistoryStorage`を使います。`record(itemId)`は保存一覧へアイテムを追加せず、保存解除でも履歴を消しません。`getAll()`、`remove()`、`clear()`、`setLimit()`で一覧・個別削除・全消去・保持件数を管理できます。自己申告の鑑賞は`LocalStorageKeepViewingRecordStorage.add()`で開封と別の複数レコードとして記録し、`set()`で日時や個人メモを更新し、`remove()` / `removeForItem()` / `clear()`で削除できます。
29
+ ```tsx
30
+ import { createKeepKit } from "@keepkit/core/react";
31
+ import { createBrowserStorageAdapter } from "@keepkit/core/storage";
38
32
 
39
- 保存順を巡回ルートとして管理する場合は、`reorderKeepItems` / `moveKeepItem`、Reactでは`useKeepNavigator`と`useKeepList().reorder()` / `.move()`を利用できます。`getKeepNavigationState`は現在・前・次のアイテムと進行度を返します。
33
+ type ArticleMeta = { title: string; url: string };
34
+ const keep = createKeepKit<ArticleMeta>({
35
+ storage: createBrowserStorageAdapter({ key: "my-app:items" }),
36
+ });
37
+ const article = {
38
+ id: "article-123",
39
+ targetType: "article",
40
+ meta: { title: "Example article", url: "/articles/123" },
41
+ };
42
+
43
+ function SavedArticles() {
44
+ const { items, isLoading, error } = keep.useList({ targetType: "article" });
45
+ if (isLoading) return <p>読み込み中…</p>;
46
+ if (error) return <p role="alert">保存一覧を読み込めませんでした。</p>;
47
+ return <ul>{items.map((item) => <li key={item.id}>{item.meta.title}</li>)}</ul>;
48
+ }
49
+
50
+ export function App() {
51
+ return (
52
+ <keep.Provider>
53
+ <keep.Button item={article} />
54
+ <SavedArticles />
55
+ </keep.Provider>
56
+ );
57
+ }
58
+ ```
40
59
 
41
- 同じ保存アイテムを複数コースに登録する場合は、`StorageAdapter`の`setCollectionMembership()`と`addKeepItemToCollection()`、`getKeepCollectionItems()`、`reorderKeepCollectionItems()`、`removeKeepItemFromCollection()`を使います。コースごとに順序を保持し、所属を外しても保存アイテムや共有メモは削除しません。従来の`KeepItem.collectionId`は単一分類用途として引き続き利用できます。
60
+ hooksはProvider内のコンポーネントで呼び出します。
61
+ 保存入力は`{ id, meta, targetType?, note?, tags?, order? }`が基本です。時刻とタグの正規化はKeepKitが管理します。
62
+ `keep.useItem(article)`で保存・解除・メモ更新などを、`keep.useList(query)`で一覧と一括操作を利用できます。
42
63
 
43
- `exportItems()`は空の定義を含むコレクションと複数コース所属をv2バックアップへ含め、`importItems()`は従来のアイテムのみのv1バックアップも読み込みます。mergeでは同じIDのコレクション名と同じコース・ガイドの順序をバックアップ側で更新し、同名でも異なるIDのコレクションは別の定義として保ちます。replaceでは既存のアイテム、定義、所属を置き換えます。復元先の独自`StorageAdapter`はコレクションと所属の各メソッドを実装する必要があります。
64
+ ### 主な機能
44
65
 
45
- `RemoteSyncDriver`に`pushCollection()`と`pullCollections()`を実装すると、コレクションの作成・改名・削除を永続キュー経由で同期できます。操作は`userId` / `tenantId`のscopeを持ち、フルスナップショットのpullで見つからない定義は削除として扱い、ローカル所属も削除します。未送信のローカル操作はpullで上書きせず、複数端末で同じ定義を同時変更した場合はリモートtransportが受信順で適用する「最後に受け付けた操作を採用」方針です。認証付き構成では`AuthenticatedSyncTransport`にも同じ2つの関数を指定できます。
66
+ | 用途 | API |
67
+ | --- | --- |
68
+ | 検索・絞り込み | `KeepListQuery`の`search`、`tags`、`sort`、`pagination`。Reactなしでは`queryKeepItems` |
69
+ | 整理 | archive・pin・`collectionId`、`createInboxQuery`、`useKeepCollections` |
70
+ | 複数コレクションへの所属・順序 | `addKeepItemToCollection`、`getKeepCollectionItems`、`reorderKeepCollectionItems`、`removeKeepItemFromCollection` |
71
+ | 再発見 | `useKeepItem(item).recordOpen()`、`createRediscoveryQuery`、`useKeepRediscovery` |
72
+ | 閲覧履歴・鑑賞記録・進行位置 | `LocalStorageKeepHistoryStorage`、`LocalStorageKeepViewingRecordStorage`、`LocalStorageKeepProgressStorage` |
73
+ | 保存対象の再検証 | Providerの`validateItem` / `resolveItem`、`revalidateItems` |
46
74
 
47
- コースの再開項目やガイドごとの音声・読書位置は`LocalStorageKeepProgressStorage`で保存します。`saveCourse()` / `getCourse()`、`saveItem()` / `getItem()`、`resetCourse()` / `resetItem()`を利用できます。音声位置はミリ秒、読書位置はアプリ定義の数値として扱います。記録に言語または`contentVersion`がある場合、`getItem()`に一致する値を指定しないと位置を返しません。保存APIは再生を開始しないため、音声の再開はViewer側で利用者の操作から行ってください。
75
+ 一覧は未アーカイブのアイテムを既定で返します。`archiveScope: "all"`で両方を、`archived: true`でアーカイブを取得できます。
76
+ 複数コレクションへの所属はアイテムと別に保存され、所属を外しても共有アイテムやメモは残ります。
48
77
 
49
- `@keepkit/core/core`はフレームワーク中立、`@keepkit/core/react`はReact、`@keepkit/core/storage`はlocalStorage、IndexedDB、fallback、同期adapter、`@keepkit/core/schema`はschema処理を公開します。パッケージルートにはexportがありません。
78
+ `before`プラグインや永続化の失敗は保存操作を拒否します。保存成功後のコールバック、`after`プラグイン、`onChange`の例外は`onError(error, { action, id, phase: "notification" })`で報告し、保存済み状態とUndoを維持します。通知例外でも保存操作のPromiseは成功し、後続通知は継続します。
50
79
 
51
- `KeepProvider`には描画エラーを局所化する`fallback`、`onBoundaryError`、`boundaryResetKey`を指定できます。より細かい境界が必要な場合は`KeepErrorBoundary`を`@keepkit/core/react`から利用できます。
80
+ ### 保存・同期・バックアップ
52
81
 
53
- 保存対象の公開状態は`KeepItem.status`(`expired`、`removed`、`private`など)と`statusReason`で保持できます。`KeepProvider`の`validateItem` / `resolveItem`を指定すると、引数なしの`revalidateItems()`で検証できます。`revalidateItems`に`removeStatuses`を渡すと検出したアイテムを保存一覧から削除します。`SyncStorageAdapter`は`userId`、`tenantId`、`maxRetries`、`retryDelayMs`、`retryBackoff`に対応し、`retrySync()`で失敗後の同期を再開できます。
82
+ - `createBrowserStorageAdapter`はIndexedDB優先で、localStorageへフォールバックします。`scope`でユーザー/テナントを分離できます。
83
+ - `SyncStorageAdapter`と`RemoteSyncDriver`で永続オフラインキュー・再試行・競合処理を組み込みます。定義・所属の同期には、それぞれ`pushCollection` / `pullCollections`、`pushMembership` / `pullMemberships`が必要です。
84
+ - 認証方式はアプリ側で管理します。[認証付き同期の例](../../examples/authenticated-sync/README.md)でトークン取得とscope切り替えを確認できます。
85
+ - `exportItems(storage)` / `importItems(storage, json, { mode: "merge" })`で保存アイテム・コレクション定義・所属をバックアップ・復元します。閲覧履歴・鑑賞記録・進行位置は含みません。
54
86
 
55
- v0.28.8では個人用リンクライブラリのデモを刷新し、ブラウザー内でのリンク保存、整理、検索、バックアップを試せます。v0.28.8ではスコープをまたぐ結合と並行所属変更を補強し、履歴・鑑賞記録・進行位置の同一キー更新を保護しました。
87
+ fallbackの更新・削除・全消去・コレクション・所属操作は、ストレージとscopeごとのlocalStorage journalに記録します。journal保存が成功判定です。実データへの反映が失敗しても記録から変更を読み取り、再起動後も復旧を試します。全操作をprimaryへ再生し、読み取りとjournal消去が成功した後にIndexedDBへ戻ります。`clear()`はアイテムと所属を消去し、コレクション定義を保持します。
56
88
 
57
- `createAuthenticatedSyncKit`は、リクエストごとの`getAuthToken`、注入可能なpush/pull transport、401/403時の再認証callback、永続オフラインキュー、`setScope`による安全なユーザー/テナント切替を提供します。スコープを切り替えたり対象スコープのキューを削除・全消去しても、他スコープの未送信操作は保持されます。詳細は[`examples/authenticated-sync`](../../examples/authenticated-sync/README.md)を参照してください。
89
+ fallbackへの書き込みと復旧にはWeb Locks APIとJSON保存可能なメタデータが必要です。journal保存失敗はデータ変更前にエラーを返します。Web Locks未対応でも、未反映操作がなくIndexedDBが正常なら従来の保存が使えます。正常なIndexedDBのメタデータにJSON制約は追加しません。
58
90
 
59
- ### 0.4.xからの変更
91
+ journal v2は完全なアイテム・コレクション・所属のスナップショットと取得時刻を保存します。v1の保留操作も読み込み、空primaryへの既存データ移行後にスナップショットを作ります。障害中の読み取りは最後の永続スナップショットと保留操作を使います。primary保存後のスナップショット更新失敗は保存成功を維持し、`storage.recovery?.getState()`で`snapshotStale`と`issue`を報告します。次の正常読み取りで更新を再試行します。
60
92
 
61
- - `createKeepKit`は`Provider`、`Button`、`useContext`、`useItem`、`useList`、`useShortcut`を返します。
62
- - `useKeepItem(id, payload)`は`useKeepItem(item)`に変わりました。
63
- - `useKeepShortcut({ id, itemPayload })`は`useKeepShortcut({ item })`に変わりました。
64
- - `KeepListOptions`は`KeepListQuery`に変わり、一覧条件は`search`、`sort`、`pagination`へ統一されました。
93
+ 標準browser factoryは旧v1保存キーからも読み込み、新しい記録の永続化後に旧キーを削除します。旧キーだけではbackendやscopeを一意に判定できない場合は、記録を保持してエラーを返します。独自の`createRecoveryJournal`を使う場合は、その実装で旧キーを移行してください。
65
94
 
66
- ## English
95
+ `StorageAdapter.recovery`は任意です。`getState()` / `subscribe()`で状態を観察し、`inspect({ selections })`で書き込みなしに保存元と退避済み旧fallbackを比較します。異なるIDは両方保持し、同じIDの競合は明示選択が必要です。`apply({ token, selections })`は適用直前に再照合し、古い確認を拒否します。修復前のバックアップv2と承認済み操作を一回のjournal保存で確定します。`status: "pending"`は修復内容を保存済み・反映待ちなので、再提出せず`retry()`で続行してください。バックアップは自動削除しません。後続の`inspect()`が返す`retainedBackups`から修復前のJSONバックアップv2を取得できます。項目・所属・コレクションは対象scopeだけを比較・変更します。
67
96
 
68
- `@keepkit/core` provides framework-neutral saved-collection primitives and low-level React bindings. For standard React applications, use `@keepkit/ui` for the shortest integration path.
97
+ `KeepFallbackRecovery`はこの能力を明示的に渡すUIです。[UIガイド](../keepkit-ui/README.md)を参照してください。`SyncStorageAdapter.recovery`は状態表示だけを公開します。分岐の修復は同期を開始する前のstandalone local adapterで行います。
69
98
 
70
- ```tsx
71
- import { KeepButton, KeepProvider, useKeepItem, useKeepList } from "@keepkit/core/react";
72
- import { createBrowserStorageAdapter } from "@keepkit/core/storage";
99
+ 独自の`FallbackStorageAdapter`には`recoveryJournal: FallbackRecoveryJournal<TMeta>`を渡せます。`read` / `write`でv1またはv2の状態を永続化し、`runExclusive`で同じbackendへのアクセスを排他します。任意の`subscribe`は別タブの変更を通知します。browser factoryの`createRecoveryJournal`には保存キー・排他キー・scopeが渡されます。独自排他機構を接続でき、標準実装は排他なしのjournal変更・復旧を拒否します。同一backendの全scopeで排他キーを共有してください。localStorageを使う独自実装は、読み取り前と書き込み後のタスク終了までロックを保持します。標準`LocalStorageRecoveryJournal`はこの待機を含みます。
73
100
 
74
- const storage = createBrowserStorageAdapter({ key: "my-app:items" });
75
- const article = { id: "article-123", targetType: "article", meta: { title: "Example", url: "/article" } };
101
+ JSON保存するmetadata・バックアップ・localStorage同期キューは、Date、Map/Set、非有限数、undefined、function、symbol、BigInt、循環参照などを`KeepStorageSerializationError`で拒否します。既知の任意フィールドのundefinedは省略できます。正常なIndexedDB保存はJSON互換性を要求しませんが、予備スナップショットの更新やJSON出力は失敗し得ます。
76
102
 
77
- <KeepProvider storage={storage}>
78
- <KeepButton item={article} />
79
- </KeepProvider>;
103
+ scope付きadapterを別のscopeで包み直しても書き込み先は切り替わりません。その構成の変更操作は保存前に拒否します。切替先のscopeからadapterを作成してください。
80
104
 
81
- const item = useKeepItem(article);
82
- const list = useKeepList({
83
- targetType: "article",
84
- search: { query: "react" },
85
- sort: { by: "updatedAt", direction: "desc" },
86
- pagination: { page: 1, pageSize: 20 },
87
- });
88
- ```
105
+ 導入時は旧実装のタブをすべて更新してください。記録のない削除意図や失われた内容は自動復元できません。スナップショット保存自体が失敗した期間の完全な障害時表示と、排他機構のない環境での安全な書き込みは保証できません。
89
106
 
90
- `KeepItemInput` contains `id`, `meta`, `targetType`, `note`, `tags`, and the optional persisted `order`. KeepKit owns persistence timestamps and tag normalization. `KeepListQuery` uses the canonical `targetType`, `tags`, `search`, `sort`, `pagination`, `filter`, and `savedBetween` fields.
107
+ 既存IndexedDBのコレクション保存先は`databaseName:storeName:collections`です。たとえば`("a:b", "c")`と`("a", "b:c")`は同じ保存先になるため、同じscopeで併用しないでください。この既存形式の曖昧なデータは、journal移行では自動分離できません。
91
108
 
92
- Filter organization with `organization: { collection, tags, note }`, each set to `assigned` or `unassigned`. `createInboxQuery()` returns the default unassigned query. `useKeepList()` includes batch archive, pin, and collection mutations. Saved Views use `KeepSavedViewStorage` and `LocalStorageKeepSavedViewStorage`, separate from item storage.
109
+ **Replace(置換)は空のバックアップでも対象範囲を置き換え、ロールバックしません。** 途中失敗は`KeepBackupImportError`の`failedStage`と`applied`で確認できます。スコープ付きadapterは別scopeのデータを変更前に拒否します。
93
110
 
94
- For rediscovery, call `useKeepItem(item).recordOpen()` to persist `lastOpenedAt`, then filter with `activity.opened`, `lastOpenedBefore`, `lastOpenedAfter`, or `inactiveForMs`. `inactiveForMs` uses `lastOpenedAt` for opened items and `savedAt` for never-opened items. Recording an open does not change `updatedAt`, and sync/merge preserves newer activity independently. `createRediscoveryQuery()` provides framework-neutral `never-opened`, `forgotten`, and `recently-opened` presets, while `useKeepRediscovery()` provides the React list hook.
111
+ 独自の`StorageAdapter`で定義・所属を扱う場合は、`getCollections` / `setCollection` / `removeCollection`と`getCollectionMemberships` / `setCollectionMembership` / `removeCollectionMembership`を実装してください。Providerのコレクション作成・改名・削除は定義メソッドが揃わない場合に拒否し、アイテムの所属も変更しません。
95
112
 
96
- Use `LocalStorageKeepHistoryStorage` when recently opened guides should include unsaved items. `record(itemId)` never adds an item to the saved list, and removing a saved item does not clear its history. Use `getAll()`, `remove()`, `clear()`, and `setLimit()` to list, delete one entry, clear history, and configure retention. Self-reported viewing events use `LocalStorageKeepViewingRecordStorage.add()` and remain distinct from opens; `set()` updates a timestamp or personal note, and `remove()`, `removeForItem()`, and `clear()` delete records.
113
+ 履歴・鑑賞記録・進行位置のlocalStorage書き込みには、ブラウザーでWeb Locks APIが必要です。未対応や保存先が利用できない場合はエラーを返します。SSRで初期化できますが、永続化操作はブラウザー側で行います。
114
+ 履歴・進行位置のキーはアプリ側でユーザーごとに分け、進行位置の取得には記録と一致する言語・コンテンツ版・音声IDを渡してください。
97
115
 
98
- Use `reorderKeepItems` / `moveKeepItem` for framework-neutral route ordering, or `useKeepNavigator` with `useKeepList().reorder()` / `.move()` in React. `getKeepNavigationState` returns the current, previous, next, and progress state.
116
+ デモと開発手順は[リポジトリREADME](../../README.md)、変更履歴は[リリースノート](../../RELEASE_NOTES.md)を参照してください。
99
117
 
100
- To place one saved guide in several courses, use `StorageAdapter.setCollectionMembership()` with `addKeepItemToCollection()`, `getKeepCollectionItems()`, `reorderKeepCollectionItems()`, and `removeKeepItemFromCollection()`. Each course keeps its own order; removing a membership leaves the shared saved item and note intact. The existing `KeepItem.collectionId` remains available for single-category organization.
118
+ ## English
101
119
 
102
- `exportItems()` writes backup v2 with collection definitions, including empty ones, and course memberships. `importItems()` also reads existing item-only v1 backups. In merge mode, a backup definition replaces the name for the same collection ID, and a backup membership replaces the order for the same course/item pair; a different ID with the same name remains a separate collection. Replace mode replaces items, definitions, and memberships. Custom storage adapters must implement the collection and membership methods to restore backups that contain this data.
120
+ Framework-neutral persistence primitives and React providers and hooks.
121
+ Use [@keepkit/ui](../keepkit-ui/README.md) when you want a ready-made collection UI. Its opt-in `presentation="reading"` and inline selection add UI behavior without changing Core types or storage formats. Unvisited uses the existing `lastOpenedAt` and `recordOpen()` contracts.
103
122
 
104
- Implement `RemoteSyncDriver.pushCollection()` and `pullCollections()` to sync collection creation, rename, and deletion through the durable queue. Operations carry the configured `userId` / `tenantId` scope. A full pull snapshot is authoritative: a missing definition is treated as deleted and its local memberships are removed. Pending local operations take precedence during pull. For simultaneous changes, the remote transport applies operations in arrival order, so the last accepted operation wins. `AuthenticatedSyncTransport` exposes the same two hooks.
123
+ ### Installation and entry points
105
124
 
106
- Use `LocalStorageKeepProgressStorage` for a course's current guide and per-guide audio or reading positions. Call `saveCourse()` / `getCourse()`, `saveItem()` / `getItem()`, and `resetCourse()` / `resetItem()`. Audio positions use milliseconds; reading positions are application-defined numbers. When a record has a language or `contentVersion`, pass matching values to `getItem()`; the offset is withheld if the expected value is missing or differs. The storage API never starts playback; the Viewer should resume audio only after a user action.
125
+ ```bash
126
+ pnpm add @keepkit/core
127
+ ```
107
128
 
108
- Use `@keepkit/core/core` for framework-neutral code, `@keepkit/core/react` for React bindings, `@keepkit/core/storage` for browser/fallback/sync adapters, and `@keepkit/core/schema` for schema validation. The package root has no export.
129
+ | Import | Purpose |
130
+ | --- | --- |
131
+ | `@keepkit/core/core` | Types, store, queries, collections, and backups, with no React imports |
132
+ | `@keepkit/core/react` | `createKeepKit`, `KeepProvider`, `KeepButton`, and hooks |
133
+ | `@keepkit/core/storage` | localStorage, IndexedDB, fallback, and sync adapters |
134
+ | `@keepkit/core/schema` | Schema parsing and validation |
109
135
 
110
- `KeepProvider` accepts `fallback`, `onBoundaryError`, and `boundaryResetKey` to isolate unexpected render errors. Use the standalone `KeepErrorBoundary` from `@keepkit/core/react` when a smaller boundary is appropriate.
136
+ The package root has no export. React bindings support React 18 or later.
111
137
 
112
- `KeepItem.status` and `statusReason` preserve source availability such as `expired`, `removed`, and `private`. Configure `KeepProvider` with `validateItem` / `resolveItem` to make `revalidateItems()` use those hooks by default. Pass `removeStatuses` to remove detected items from storage. `SyncStorageAdapter` supports scoped queues with `userId` and `tenantId`, configurable retries/backoff, and explicit `retrySync()` recovery.
138
+ ### React usage
113
139
 
114
- v0.28.8 refreshes the personal link library demo for browser-local saving, organization, search, and backups. v0.28.8 strengthened scope-aware merging, concurrent membership changes, and same-key updates to history, viewing records, and progress.
140
+ ```tsx
141
+ import { createKeepKit } from "@keepkit/core/react";
142
+ import { createBrowserStorageAdapter } from "@keepkit/core/storage";
115
143
 
116
- `createAuthenticatedSyncKit` provides a per-request `getAuthToken`, injectable push/pull transport, 401/403 reauthentication callbacks, persistent offline queues, and `setScope` for safe user or tenant changes. Scope changes and scoped queue removal or clearing preserve pending operations for other scopes. See [`examples/authenticated-sync`](../../examples/authenticated-sync/README.md) for a recipe.
144
+ type ArticleMeta = { title: string; url: string };
145
+ const keep = createKeepKit<ArticleMeta>({
146
+ storage: createBrowserStorageAdapter({ key: "my-app:items" }),
147
+ });
148
+ const article = {
149
+ id: "article-123",
150
+ targetType: "article",
151
+ meta: { title: "Example article", url: "/articles/123" },
152
+ };
153
+
154
+ function SavedArticles() {
155
+ const { items, isLoading, error } = keep.useList({ targetType: "article" });
156
+ if (isLoading) return <p>Loading…</p>;
157
+ if (error) return <p role="alert">Could not load saved items.</p>;
158
+ return <ul>{items.map((item) => <li key={item.id}>{item.meta.title}</li>)}</ul>;
159
+ }
160
+
161
+ export function App() {
162
+ return (
163
+ <keep.Provider>
164
+ <keep.Button item={article} />
165
+ <SavedArticles />
166
+ </keep.Provider>
167
+ );
168
+ }
169
+ ```
117
170
 
118
- The v0.5 factory returns `Provider`, `Button`, `useContext`, `useItem`, `useList`, and `useShortcut`. Existing v0.4 applications should follow the migration guide in the repository root.
171
+ Call hooks inside components under the provider.
172
+ The basic save input is `{ id, meta, targetType?, note?, tags?, order? }`; KeepKit manages timestamps and tag normalization.
173
+ Use `keep.useItem(article)` for saves, removal, and note updates, and `keep.useList(query)` for lists and bulk operations.
119
174
 
120
- ## Archive, pin, and collections
175
+ ### Main APIs
121
176
 
122
- `KeepItem` and `KeepItemInput` accept optional `archived`, `pinned`, and `collectionId` fields. `useKeepList` defaults to unarchived items; pass `archived: true` for the archive, `archiveScope: "all"` for both scopes, `collectionId` for an exact collection filter, and `pinnedFirst: true` to stably promote pinned items without changing the existing order inside either group. `useKeepCollections({ targetType, orderBy })` derives de-duplicated collection IDs, names, and counts from the complete saved-item snapshot. `useKeepItem` and the provider expose `toggleArchive`, `archiveItem`, `unarchiveItem`, `togglePin`, and `moveToCollection` operations. Each operation updates `updatedAt`, removes an empty collection ID, and uses the normal persistence, rollback, plugin, and `onChange` pipeline.
177
+ | Task | API |
178
+ | --- | --- |
179
+ | Search and filtering | `KeepListQuery.search`, `tags`, `sort`, and `pagination`; `queryKeepItems` without React |
180
+ | Organization | Archive, pin, `collectionId`, `createInboxQuery`, and `useKeepCollections` |
181
+ | Multiple collections and ordering | `addKeepItemToCollection`, `getKeepCollectionItems`, `reorderKeepCollectionItems`, `removeKeepItemFromCollection` |
182
+ | Rediscovery | `useKeepItem(item).recordOpen()`, `createRediscoveryQuery`, and `useKeepRediscovery` |
183
+ | History, viewing records, and progress | `LocalStorageKeepHistoryStorage`, `LocalStorageKeepViewingRecordStorage`, `LocalStorageKeepProgressStorage` |
184
+ | Source revalidation | Provider `validateItem` / `resolveItem` and `revalidateItems` |
123
185
 
124
- The standard browser adapters persist explicit collection definitions and course memberships separately from items. A custom `StorageAdapter` can opt in by implementing `getCollections`, `setCollection`, `removeCollection`, `getCollectionMemberships`, `setCollectionMembership`, and `removeCollectionMembership`. `clear()` still clears saved items only. JSON backup v2 includes definitions and memberships, and remote sync can include definitions through optional collection transport hooks.
186
+ Lists return unarchived items by default. Use `archiveScope: "all"` for both or `archived: true` for archived items.
187
+ Memberships are stored separately; removing one leaves the shared item and note intact.
125
188
 
126
- ## アーカイブ・ピン留め・コレクション
189
+ Failures in `before` plugins or persistence reject the mutation. Errors from post-save callbacks, `after` plugins, and `onChange` are reported through `onError(error, { action, id, phase: "notification" })`, preserving committed state and Undo. The mutation resolves successfully and later notifications still run.
127
190
 
128
- `KeepItem` と `KeepItemInput` は `archived`、`pinned`、`collectionId` を任意で受け取れます。`useKeepList` は未アーカイブを既定とし、`archived: true` でアーカイブを、`archiveScope: "all"` で両方を、`collectionId` で完全一致のコレクションを取得できます。`useKeepCollections({ targetType, orderBy })` は全保存アイテムからコレクションID・名前・件数を重複なく導出します。`pinnedFirst: true` は既存の順序を保ったままピン留め項目を先頭へ安定移動します。`useKeepItem` と Provider には `toggleArchive`、`archiveItem`、`unarchiveItem`、`togglePin`、`moveToCollection` を追加しました。各操作は `updatedAt` を更新し、空のコレクション ID はプロパティを削除して、既存の永続化・rollback・plugin・`onChange` 経路を利用します。
191
+ ### Storage, sync, and backups
129
192
 
130
- 標準ブラウザーストレージは、空のコレクション、変更した名前、コース別の所属と順序をアイテムとは別に永続化します。独自の`StorageAdapter`では`getCollections`、`setCollection`、`removeCollection`と`getCollectionMemberships`、`setCollectionMembership`、`removeCollectionMembership`を実装すると保存できます。`clear()`は保存アイテムのみを消去し、JSONバックアップv2はコレクションと所属も含みます。リモート同期は任意のコレクション用transportを追加すると利用できます。
193
+ - `createBrowserStorageAdapter` prefers IndexedDB and falls back to localStorage. Use `scope` to isolate users and tenants.
194
+ - Combine `SyncStorageAdapter` and `RemoteSyncDriver` for durable offline queues, retries, and conflicts. Definition and membership sync require `pushCollection` / `pullCollections` and `pushMembership` / `pullMemberships`, respectively.
195
+ - Authentication belongs to your app. See the [authenticated sync example](../../examples/authenticated-sync/README.md) for tokens and scope changes.
196
+ - Use `exportItems(storage)` / `importItems(storage, json, { mode: "merge" })` to back up and restore saved items, collection definitions, and memberships. History, viewing records, and progress are excluded.
131
197
 
132
- ### v0.28.8の保存・復元補完
198
+ Fallback updates, removals, clears, collection changes, and memberships enter a localStorage journal isolated by storage configuration and scope. Saving the journal commits the mutation. Reads apply recorded changes even if their projection into fallback storage fails, and recovery retries after restart. The adapter returns to IndexedDB after replaying every operation, reading the primary successfully, and clearing the journal. `clear()` removes items and memberships, preserving collection definitions.
133
199
 
134
- 同じlocalStorageキーへの履歴・鑑賞記録・進行位置の書き込みは、Web Locks APIが使えるブラウザーではタブ・インスタンス間で直列化されます。同一realm内の複数インスタンスもキーごとに直列化します。`saveItem()`は同じガイドの既存進行情報を読み、指定フィールドだけ更新して他の位置情報を保ちます。鑑賞記録・進行レコードの`set()`で古い`updatedAt`の値が届いた場合は、新しい保存値を残します。Web Locks APIがないブラウザーでは、競合上書きを避けるため書き込み前に`KeepActivityStorageError`または`KeepProgressStorageError`で失敗します。ブラウザー保存先がない場合も同じエラー型で失敗します。SSRでは初期化できますが、保存操作はブラウザー側で呼び出してください。
200
+ Fallback writes and recovery require the Web Locks API and JSON-compatible metadata. Journal write failures reject before changing data. Browsers without Web Locks can still save to a healthy IndexedDB primary when no operations are pending. Healthy IndexedDB metadata gains no JSON restriction.
135
201
 
136
- 既存ストレージを開いた後、コース別所属を読む機能を使う前に`migrateLegacyCollectionMemberships(storage)`を実行して旧単一所属データを移行します。既存所属を上書きせず、所属保存後に旧`collectionId`を消去するため、利用者が所属を外した後の再実行で復活しません。途中でadapterの書き込みが失敗した場合はエラーを返し、再実行しても所属は重複しません。対象scopeに定義名のないIDは戻り値の`missingCollectionIds`で確認できます。項目削除時はlocalStorage、IndexedDB、スコープadapterが所属も消します。同じadapterへの`addKeepItemToCollection()`・`removeKeepItemFromCollection()`・`reorderKeepCollectionItems()`は、所属の読み取りから順序の再採番・書き込みまで直列化されます。
202
+ Journal v2 stores complete item, collection, and membership snapshots with their capture time. It also reads pending v1 operations and creates its first snapshot after migrating legacy data into an empty primary. Outage reads use the last durable snapshot plus pending operations. Failure to refresh the snapshot after a primary commit preserves mutation success and reports `snapshotStale` and `issue` through `storage.recovery?.getState()`. The next healthy read retries the refresh.
137
203
 
138
- バックアップには保存アイテム・コレクション定義・所属のみが含まれ、閲覧履歴・鑑賞記録・進行位置は含まれません。`importItems()`の置換モードは空のバックアップでも対象範囲を空にします。v2バックアップと戻り値の`scopes`は含まれる利用者・テナント範囲を示し、`includedData`はデータ種別を示します。`imported`、`failed`、`total`は保存アイテムの件数で、`applied`は項目・定義・所属の適用数を個別に示します。スコープ付きadapterは別scopeを含むbackupを変更前に拒否します。v1の`collectionId`は名前を復元できないため`missingCollectionIds`で通知します。途中失敗は`KeepBackupImportError.failedStage`と`applied`で確認します。置換にrollbackはありません。merge時の同ID名は既定でバックアップ側を採用し、`collectionNameConflict: "existing"`を指定すると既存名を維持します。共有adapterでは項目・コレクションのIDと`tenantId`・`userId`で識別するため、別scopeの同IDデータは別に保たれます。scope未指定と`{}`は同じ扱いで、空文字列の`userId`または`tenantId`は明示値として別scopeです。複数scopeのバックアップは共有adapterへ復元でき、スコープ付きadapterは別scopeを変更前に拒否します。
204
+ The standard browser factory also reads the original v1 storage key and removes it only after persisting the new record. If the old key cannot identify the backend or scope unambiguously, it preserves the record and reports an error. Custom `createRecoveryJournal` implementations must migrate their own older keys.
139
205
 
140
- 履歴の文脈には`record(itemId, viewedAt, { language: "ja" })`で言語などを保存でき、`getAll()`で履歴と一緒に取得できます。鑑賞記録は`viewedAt`と`createdAt` / `updatedAt`を分けます。日時がない旧記録は最初に更新した時刻を作成時刻として補います。読書位置は数値offsetと安定した見出しID文字列を受け付けます。`getItem()`には必要な音声ID・言語・コンテンツ版を渡して互換位置だけを取得します。
206
+ `StorageAdapter.recovery` is optional. Observe status through `getState()` / `subscribe()`, and compare storage sources and archived legacy fallback through `inspect({ selections })` without writing. Distinct IDs are retained together; conflicting records with the same identity need an explicit choice. `apply({ token, selections })` rechecks the data immediately before applying and rejects stale confirmation. It commits pre-repair v2 backups and the approved operation list in one journal write. A `status: "pending"` result means the repair is saved and awaiting projection: continue through `retry()` instead of submitting it again. Backups are never automatically deleted. Later `inspect()` results expose earlier v2 JSON backups through `retainedBackups`. Comparisons and changes include only the active scope.
141
207
 
142
- 同期adapterに`RemoteSyncDriver.pushMembership()` / `pullMemberships()`を指定すると、所属の追加・解除・コース別順序を永続キューで同期できます。所属解除はアイテム・コレクション削除より先に送信し、pull時は存在しない親への所属を適用しません。membership transportを実装しないdriverでは所属はローカル保存のみです。コレクション定義には`revision`と`updatedAt`を保存でき、操作は`baseRevision`を送ります。driverは`KeepCollectionSyncResult`で競合と選択結果を返し、アプリは`resolveCollectionSyncConflict()`からローカルまたはリモートを選べます。削除tombstoneの保持と競合方針はdriverまたはサーバーで実装します。これらは低レベルAPIであり標準画面へ自動接続されません。
208
+ `KeepFallbackRecovery` accepts this capability explicitly; see the [UI guide](../keepkit-ui/README.md). `SyncStorageAdapter.recovery` exposes status only. Repair existing branches through a standalone local adapter before starting synchronization.
143
209
 
144
- ```ts
145
- import {
146
- LocalStorageKeepHistoryStorage,
147
- LocalStorageKeepProgressStorage,
148
- LocalStorageKeepViewingRecordStorage,
149
- exportItems,
150
- importItems,
151
- migrateLegacyCollectionMemberships,
152
- } from "@keepkit/core/core";
153
- import { createBrowserStorageAdapter } from "@keepkit/core/storage";
210
+ Custom `FallbackStorageAdapter` instances can accept `recoveryJournal: FallbackRecoveryJournal<TMeta>`. Persist v1 or v2 state through `read` / `write` and provide exclusive access to the same backend through `runExclusive`. Optional `subscribe` notifies consumers of other tabs' changes. The browser factory's `createRecoveryJournal` receives the storage key, lock key, and scope. It supports a custom lock implementation; the default rejects journal changes and recovery without exclusive access. Share the lock key across all scopes using the same backend. Custom localStorage journals must hold the lock across task boundaries before reads and after writes. The standard `LocalStorageRecoveryJournal` includes these waits.
154
211
 
155
- const storage = createBrowserStorageAdapter({ key: "my-app:items", scope: { userId: "user-1" } });
156
- const history = new LocalStorageKeepHistoryStorage({ key: "my-app:user-1:history" });
157
- await history.record("guide-1", Date.now(), { language: "ja" });
158
- await migrateLegacyCollectionMemberships(storage);
159
- const backup = await exportItems(storage);
160
- await importItems(storage, backup, { mode: "replace" });
161
-
162
- const progress = new LocalStorageKeepProgressStorage({ key: "my-app:user-1:progress" });
163
- await progress.saveItem("guide-1", {
164
- audioId: "guide-1-ja",
165
- audioPositionMs: 1250,
166
- readingPosition: "heading-intro",
167
- language: "ja",
168
- contentVersion: "v2",
169
- });
170
- const resume = await progress.getItem("guide-1", {
171
- audioId: "guide-1-ja",
172
- language: "ja",
173
- contentVersion: "v2",
174
- });
175
- const viewings = new LocalStorageKeepViewingRecordStorage({ key: "my-app:user-1:viewings" });
176
- const record = { id: "viewing-1", itemId: "guide-1", viewedAt: Date.now(), note: "Finished" };
177
- await viewings.set(record); // Reuse this stable ID when retrying the write.
178
- ```
212
+ JSON metadata, backups, and localStorage sync queues reject Date, Map/Set, non-finite numbers, undefined, functions, symbols, BigInt, and circular references through `KeepStorageSerializationError`. Known optional fields may omit undefined. Healthy IndexedDB saves do not require JSON compatibility, but reserve snapshots and JSON exports may consequently fail.
179
213
 
180
- ### Persistence and restore improvements in v0.28.8
214
+ Wrapping an already scoped adapter with a different scope does not switch its write destination. Such mutations reject before persistence. Create an adapter for the destination scope when switching accounts.
181
215
 
182
- Writes to history, viewing records, and progress using the same localStorage key are serialized across tabs and instances when the browser provides the Web Locks API. Separate instances in one realm are also serialized by key. `saveItem()` reads existing progress for the same guide and updates only the supplied fields, preserving other positions. For viewing records and progress, `set()` does not replace a newer record with a value whose `updatedAt` is older. In a browser without Web Locks, writes fail before mutation with `KeepActivityStorageError` or `KeepProgressStorageError` to avoid silently overwriting concurrent data. The same error types report unavailable browser storage. Construction is SSR-safe; call persistent writes in the browser.
216
+ Refresh all tabs running the older implementation when adopting this journal. Missing deletion intent and already lost content cannot be reconstructed automatically. Complete outage views during snapshot-write failures and safe writes without an exclusive-access mechanism cannot be guaranteed.
183
217
 
184
- After opening existing storage and before reading course-specific memberships, run `migrateLegacyCollectionMemberships(storage)`. Existing memberships are never overwritten, and the legacy `collectionId` is cleared after migration so a later run will not recreate a membership the user removed. Adapter write errors are returned; rerunning after a partial failure is safe and does not duplicate memberships. IDs with no same-scope definition name are listed in `missingCollectionIds`. Removing a saved item also removes its memberships in localStorage, IndexedDB, and scoped adapters. `addKeepItemToCollection()`, `removeKeepItemFromCollection()`, and `reorderKeepCollectionItems()` serialize their read, reindex, and write steps when called concurrently with the same adapter instance.
218
+ The existing IndexedDB collection database is named `databaseName:storeName:collections`. For example, `("a:b", "c")` and `("a", "b:c")` share that database, so do not combine them within the same scope. Journal migration cannot automatically separate ambiguous data in this existing format.
185
219
 
186
- Backups include saved items, collection definitions, and memberships. They exclude history, viewing records, and progress. Replace imports clear the target scope even for an empty backup. Version 2 backups and results expose represented `scopes`; scoped adapters reject data from a different scope before mutation. `imported`, `failed`, and `total` count saved items; `applied` reports items, definitions, and memberships separately. `includedData` identifies data types, and v1 collection IDs whose names cannot be restored are returned in `missingCollectionIds`. `KeepBackupImportError.failedStage` and `applied` describe partial application. Replace has no rollback. Merge keeps the backup name for a same-ID collision by default; choose `collectionNameConflict: "existing"` to retain the stored name. Shared adapters identify items and collections by ID plus `tenantId` and `userId`, keeping same-ID records in different scopes independent. An omitted scope and `{}` are equivalent; an empty-string `userId` or `tenantId` is an explicit, distinct scope. Shared adapters accept multi-scope backups, while scoped adapters reject another scope before mutation.
220
+ **Replace imports overwrite the target data, even with an empty backup, and do not roll back.** Inspect `KeepBackupImportError.failedStage` and `applied` after partial failure. Scoped adapters reject data from another scope before mutation.
187
221
 
188
- History context can be recorded with `record(itemId, viewedAt, { language: "ja" })` and retrieved with each entry from `getAll()`. Viewing records distinguish the self-reported `viewedAt` from `createdAt` / `updatedAt`. A legacy record without these timestamps receives its first-update time as its creation timestamp. Reading positions accept numeric offsets and stable heading ID strings; pass expected audio ID, language, and content version to `getItem()` to reject incompatible positions.
222
+ Custom `StorageAdapter` implementations need `getCollections` / `setCollection` / `removeCollection` and `getCollectionMemberships` / `setCollectionMembership` / `removeCollectionMembership` to support definitions and memberships. Provider collection creation, renaming, and removal reject before changing item assignments when definition methods are incomplete.
189
223
 
190
- Implement `RemoteSyncDriver.pushMembership()` / `pullMemberships()` to sync membership changes and course-specific order through the durable queue. Membership removals are sent before item or collection deletions, and pulls skip memberships whose parent is missing. Without membership transport hooks, membership changes remain local. Collection definitions can store `revision` and `updatedAt`, and operations send `baseRevision`. Drivers return `KeepCollectionSyncResult` for conflicts and outcomes; the app can choose local or remote with `resolveCollectionSyncConflict()`. The server or driver owns deletion tombstones and conflict policy. These are low-level APIs and are not automatically connected to the standard UI.
224
+ Browser writes to localStorage history, viewing records, and progress require the Web Locks API. Unsupported locks or unavailable storage produce errors. Construction is SSR-safe; persistent operations run in the browser.
225
+ Namespace history and progress keys per account, and pass matching language, content version, and audio ID when reading progress.
191
226
 
192
- The example above imports the persistence APIs from `@keepkit/core/core` and browser adapters from `@keepkit/core/storage`. Keep history and progress keys scoped by the host app's account or tenant when those records should not cross users. Reuse a viewing-record ID with `set()` when retrying so the event is not duplicated.
227
+ See the [repository README](../../README.md) for demos and development, and the [release notes](../../RELEASE_NOTES.md) for changes.