@keepkit/core 0.28.8 → 0.28.9

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.
Files changed (2) hide show
  1. package/README.md +132 -145
  2. package/package.json +1 -1
package/README.md CHANGED
@@ -2,191 +2,178 @@
2
2
 
3
3
  [日本語](#日本語) | [English](#english)
4
4
 
5
- ## 日本語
6
-
7
- フレームワーク中立の保存・コレクションプリミティブとReactの低レベルbindingを提供します。通常のReactアプリケーションでは、より少ないコードで利用できる`@keepkit/ui`を推奨します。
5
+ Release: v0.28.9
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なしで同じ条件を適用できます。
32
-
33
- 整理状態は`organization: { collection, tags, note }`の`assigned` / `unassigned`で絞り込めます。`createInboxQuery()`は未分類アイテム向けの既定queryを返します。`useKeepList()`は一括archive、pin、collection移動を提供します。Saved Viewは`KeepSavedViewStorage` / `LocalStorageKeepSavedViewStorage`でアイテムと分けて保存できます。
34
-
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です。
36
-
37
- 未保存ガイドも含む閲覧履歴には`LocalStorageKeepHistoryStorage`を使います。`record(itemId)`は保存一覧へアイテムを追加せず、保存解除でも履歴を消しません。`getAll()`、`remove()`、`clear()`、`setLimit()`で一覧・個別削除・全消去・保持件数を管理できます。自己申告の鑑賞は`LocalStorageKeepViewingRecordStorage.add()`で開封と別の複数レコードとして記録し、`set()`で日時や個人メモを更新し、`remove()` / `removeForItem()` / `clear()`で削除できます。
38
-
39
- 保存順を巡回ルートとして管理する場合は、`reorderKeepItems` / `moveKeepItem`、Reactでは`useKeepNavigator`と`useKeepList().reorder()` / `.move()`を利用できます。`getKeepNavigationState`は現在・前・次のアイテムと進行度を返します。
40
-
41
- 同じ保存アイテムを複数コースに登録する場合は、`StorageAdapter`の`setCollectionMembership()`と`addKeepItemToCollection()`、`getKeepCollectionItems()`、`reorderKeepCollectionItems()`、`removeKeepItemFromCollection()`を使います。コースごとに順序を保持し、所属を外しても保存アイテムや共有メモは削除しません。従来の`KeepItem.collectionId`は単一分類用途として引き続き利用できます。
42
-
43
- `exportItems()`は空の定義を含むコレクションと複数コース所属をv2バックアップへ含め、`importItems()`は従来のアイテムのみのv1バックアップも読み込みます。mergeでは同じIDのコレクション名と同じコース・ガイドの順序をバックアップ側で更新し、同名でも異なるIDのコレクションは別の定義として保ちます。replaceでは既存のアイテム、定義、所属を置き換えます。復元先の独自`StorageAdapter`はコレクションと所属の各メソッドを実装する必要があります。
44
-
45
- `RemoteSyncDriver`に`pushCollection()`と`pullCollections()`を実装すると、コレクションの作成・改名・削除を永続キュー経由で同期できます。操作は`userId` / `tenantId`のscopeを持ち、フルスナップショットのpullで見つからない定義は削除として扱い、ローカル所属も削除します。未送信のローカル操作はpullで上書きせず、複数端末で同じ定義を同時変更した場合はリモートtransportが受信順で適用する「最後に受け付けた操作を採用」方針です。認証付き構成では`AuthenticatedSyncTransport`にも同じ2つの関数を指定できます。
46
-
47
- コースの再開項目やガイドごとの音声・読書位置は`LocalStorageKeepProgressStorage`で保存します。`saveCourse()` / `getCourse()`、`saveItem()` / `getItem()`、`resetCourse()` / `resetItem()`を利用できます。音声位置はミリ秒、読書位置はアプリ定義の数値として扱います。記録に言語または`contentVersion`がある場合、`getItem()`に一致する値を指定しないと位置を返しません。保存APIは再生を開始しないため、音声の再開はViewer側で利用者の操作から行ってください。
48
-
49
- `@keepkit/core/core`はフレームワーク中立、`@keepkit/core/react`はReact、`@keepkit/core/storage`はlocalStorage、IndexedDB、fallback、同期adapter、`@keepkit/core/schema`はschema処理を公開します。パッケージルートにはexportがありません。
50
-
51
- `KeepProvider`には描画エラーを局所化する`fallback`、`onBoundaryError`、`boundaryResetKey`を指定できます。より細かい境界が必要な場合は`KeepErrorBoundary`を`@keepkit/core/react`から利用できます。
52
-
53
- 保存対象の公開状態は`KeepItem.status`(`expired`、`removed`、`private`など)と`statusReason`で保持できます。`KeepProvider`の`validateItem` / `resolveItem`を指定すると、引数なしの`revalidateItems()`で検証できます。`revalidateItems`に`removeStatuses`を渡すと検出したアイテムを保存一覧から削除します。`SyncStorageAdapter`は`userId`、`tenantId`、`maxRetries`、`retryDelayMs`、`retryBackoff`に対応し、`retrySync()`で失敗後の同期を再開できます。
54
-
55
- v0.28.8では個人用リンクライブラリのデモを刷新し、ブラウザー内でのリンク保存、整理、検索、バックアップを試せます。v0.28.8ではスコープをまたぐ結合と並行所属変更を補強し、履歴・鑑賞記録・進行位置の同一キー更新を保護しました。
56
-
57
- `createAuthenticatedSyncKit`は、リクエストごとの`getAuthToken`、注入可能なpush/pull transport、401/403時の再認証callback、永続オフラインキュー、`setScope`による安全なユーザー/テナント切替を提供します。スコープを切り替えたり対象スコープのキューを削除・全消去しても、他スコープの未送信操作は保持されます。詳細は[`examples/authenticated-sync`](../../examples/authenticated-sync/README.md)を参照してください。
58
-
59
- ### 0.4.xからの変更
60
-
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`へ統一されました。
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` | スキーマの解析・検証 |
65
24
 
66
- ## English
25
+ パッケージルートにはexportがありません。React bindingはReact 18以降に対応します。
67
26
 
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.
27
+ ### Reactで使う
69
28
 
70
29
  ```tsx
71
- import { KeepButton, KeepProvider, useKeepItem, useKeepList } from "@keepkit/core/react";
30
+ import { createKeepKit } from "@keepkit/core/react";
72
31
  import { createBrowserStorageAdapter } from "@keepkit/core/storage";
73
32
 
74
- const storage = createBrowserStorageAdapter({ key: "my-app:items" });
75
- const article = { id: "article-123", targetType: "article", meta: { title: "Example", url: "/article" } };
76
-
77
- <KeepProvider storage={storage}>
78
- <KeepButton item={article} />
79
- </KeepProvider>;
80
-
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 },
33
+ type ArticleMeta = { title: string; url: string };
34
+ const keep = createKeepKit<ArticleMeta>({
35
+ storage: createBrowserStorageAdapter({ key: "my-app:items" }),
87
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
+ }
88
58
  ```
89
59
 
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.
91
-
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.
93
-
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.
95
-
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.
97
-
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.
99
-
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.
101
-
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.
103
-
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.
60
+ hooksはProvider内のコンポーネントで呼び出します。
61
+ 保存入力は`{ id, meta, targetType?, note?, tags?, order? }`が基本です。時刻とタグの正規化はKeepKitが管理します。
62
+ `keep.useItem(article)`で保存・解除・メモ更新などを、`keep.useList(query)`で一覧と一括操作を利用できます。
105
63
 
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.
64
+ ### 主な機能
107
65
 
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.
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` |
109
74
 
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.
75
+ 一覧は未アーカイブのアイテムを既定で返します。`archiveScope: "all"`で両方を、`archived: true`でアーカイブを取得できます。
76
+ 複数コレクションへの所属はアイテムと別に保存され、所属を外しても共有アイテムやメモは残ります。
111
77
 
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.
78
+ ### 保存・同期・バックアップ
113
79
 
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.
80
+ - `createBrowserStorageAdapter`はIndexedDB優先で、localStorageへフォールバックします。`scope`でユーザー/テナントを分離できます。
81
+ - `SyncStorageAdapter`と`RemoteSyncDriver`で永続オフラインキュー・再試行・競合処理を組み込みます。定義・所属の同期には、それぞれ`pushCollection` / `pullCollections`、`pushMembership` / `pullMemberships`が必要です。
82
+ - 認証方式はアプリ側で管理します。[認証付き同期の例](../../examples/authenticated-sync/README.md)でトークン取得とscope切り替えを確認できます。
83
+ - `exportItems(storage)` / `importItems(storage, json, { mode: "merge" })`で保存アイテム・コレクション定義・所属をバックアップ・復元します。閲覧履歴・鑑賞記録・進行位置は含みません。
115
84
 
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.
85
+ **Replace(置換)は空のバックアップでも対象範囲を置き換え、ロールバックしません。** 途中失敗は`KeepBackupImportError`の`failedStage`と`applied`で確認できます。スコープ付きadapterは別scopeのデータを変更前に拒否します。
117
86
 
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.
87
+ 独自の`StorageAdapter`で定義・所属を扱う場合は、`getCollections` / `setCollection` / `removeCollection`と`getCollectionMemberships` / `setCollectionMembership` / `removeCollectionMembership`を実装してください。`clear()`は保存アイテムのみを消去します。
119
88
 
120
- ## Archive, pin, and collections
89
+ 履歴・鑑賞記録・進行位置のlocalStorage書き込みには、ブラウザーでWeb Locks APIが必要です。未対応や保存先が利用できない場合はエラーを返します。SSRで初期化できますが、永続化操作はブラウザー側で行います。
90
+ 履歴・進行位置のキーはアプリ側でユーザーごとに分け、進行位置の取得には記録と一致する言語・コンテンツ版・音声IDを渡してください。
121
91
 
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.
92
+ デモと開発手順は[リポジトリREADME](../../README.md)、変更履歴は[リリースノート](../../RELEASE_NOTES.md)を参照してください。
123
93
 
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.
125
-
126
- ## アーカイブ・ピン留め・コレクション
127
-
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` 経路を利用します。
129
-
130
- 標準ブラウザーストレージは、空のコレクション、変更した名前、コース別の所属と順序をアイテムとは別に永続化します。独自の`StorageAdapter`では`getCollections`、`setCollection`、`removeCollection`と`getCollectionMemberships`、`setCollectionMembership`、`removeCollectionMembership`を実装すると保存できます。`clear()`は保存アイテムのみを消去し、JSONバックアップv2はコレクションと所属も含みます。リモート同期は任意のコレクション用transportを追加すると利用できます。
94
+ ## English
131
95
 
132
- ### v0.28.8の保存・復元補完
96
+ Framework-neutral persistence primitives and React providers and hooks.
97
+ 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.
133
98
 
134
- 同じlocalStorageキーへの履歴・鑑賞記録・進行位置の書き込みは、Web Locks APIが使えるブラウザーではタブ・インスタンス間で直列化されます。同一realm内の複数インスタンスもキーごとに直列化します。`saveItem()`は同じガイドの既存進行情報を読み、指定フィールドだけ更新して他の位置情報を保ちます。鑑賞記録・進行レコードの`set()`で古い`updatedAt`の値が届いた場合は、新しい保存値を残します。Web Locks APIがないブラウザーでは、競合上書きを避けるため書き込み前に`KeepActivityStorageError`または`KeepProgressStorageError`で失敗します。ブラウザー保存先がない場合も同じエラー型で失敗します。SSRでは初期化できますが、保存操作はブラウザー側で呼び出してください。
99
+ ### Installation and entry points
135
100
 
136
- 既存ストレージを開いた後、コース別所属を読む機能を使う前に`migrateLegacyCollectionMemberships(storage)`を実行して旧単一所属データを移行します。既存所属を上書きせず、所属保存後に旧`collectionId`を消去するため、利用者が所属を外した後の再実行で復活しません。途中でadapterの書き込みが失敗した場合はエラーを返し、再実行しても所属は重複しません。対象scopeに定義名のないIDは戻り値の`missingCollectionIds`で確認できます。項目削除時はlocalStorage、IndexedDB、スコープadapterが所属も消します。同じadapterへの`addKeepItemToCollection()`・`removeKeepItemFromCollection()`・`reorderKeepCollectionItems()`は、所属の読み取りから順序の再採番・書き込みまで直列化されます。
101
+ ```bash
102
+ pnpm add @keepkit/core
103
+ ```
137
104
 
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を変更前に拒否します。
105
+ | Import | Purpose |
106
+ | --- | --- |
107
+ | `@keepkit/core/core` | Types, store, queries, collections, and backups, with no React imports |
108
+ | `@keepkit/core/react` | `createKeepKit`, `KeepProvider`, `KeepButton`, and hooks |
109
+ | `@keepkit/core/storage` | localStorage, IndexedDB, fallback, and sync adapters |
110
+ | `@keepkit/core/schema` | Schema parsing and validation |
139
111
 
140
- 履歴の文脈には`record(itemId, viewedAt, { language: "ja" })`で言語などを保存でき、`getAll()`で履歴と一緒に取得できます。鑑賞記録は`viewedAt`と`createdAt` / `updatedAt`を分けます。日時がない旧記録は最初に更新した時刻を作成時刻として補います。読書位置は数値offsetと安定した見出しID文字列を受け付けます。`getItem()`には必要な音声ID・言語・コンテンツ版を渡して互換位置だけを取得します。
112
+ The package root has no export. React bindings support React 18 or later.
141
113
 
142
- 同期adapterに`RemoteSyncDriver.pushMembership()` / `pullMemberships()`を指定すると、所属の追加・解除・コース別順序を永続キューで同期できます。所属解除はアイテム・コレクション削除より先に送信し、pull時は存在しない親への所属を適用しません。membership transportを実装しないdriverでは所属はローカル保存のみです。コレクション定義には`revision`と`updatedAt`を保存でき、操作は`baseRevision`を送ります。driverは`KeepCollectionSyncResult`で競合と選択結果を返し、アプリは`resolveCollectionSyncConflict()`からローカルまたはリモートを選べます。削除tombstoneの保持と競合方針はdriverまたはサーバーで実装します。これらは低レベルAPIであり標準画面へ自動接続されません。
114
+ ### React usage
143
115
 
144
- ```ts
145
- import {
146
- LocalStorageKeepHistoryStorage,
147
- LocalStorageKeepProgressStorage,
148
- LocalStorageKeepViewingRecordStorage,
149
- exportItems,
150
- importItems,
151
- migrateLegacyCollectionMemberships,
152
- } from "@keepkit/core/core";
116
+ ```tsx
117
+ import { createKeepKit } from "@keepkit/core/react";
153
118
  import { createBrowserStorageAdapter } from "@keepkit/core/storage";
154
119
 
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",
120
+ type ArticleMeta = { title: string; url: string };
121
+ const keep = createKeepKit<ArticleMeta>({
122
+ storage: createBrowserStorageAdapter({ key: "my-app:items" }),
169
123
  });
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.
124
+ const article = {
125
+ id: "article-123",
126
+ targetType: "article",
127
+ meta: { title: "Example article", url: "/articles/123" },
128
+ };
129
+
130
+ function SavedArticles() {
131
+ const { items, isLoading, error } = keep.useList({ targetType: "article" });
132
+ if (isLoading) return <p>Loading…</p>;
133
+ if (error) return <p role="alert">Could not load saved items.</p>;
134
+ return <ul>{items.map((item) => <li key={item.id}>{item.meta.title}</li>)}</ul>;
135
+ }
136
+
137
+ export function App() {
138
+ return (
139
+ <keep.Provider>
140
+ <keep.Button item={article} />
141
+ <SavedArticles />
142
+ </keep.Provider>
143
+ );
144
+ }
178
145
  ```
179
146
 
180
- ### Persistence and restore improvements in v0.28.8
147
+ Call hooks inside components under the provider.
148
+ The basic save input is `{ id, meta, targetType?, note?, tags?, order? }`; KeepKit manages timestamps and tag normalization.
149
+ Use `keep.useItem(article)` for saves, removal, and note updates, and `keep.useList(query)` for lists and bulk operations.
150
+
151
+ ### Main APIs
152
+
153
+ | Task | API |
154
+ | --- | --- |
155
+ | Search and filtering | `KeepListQuery.search`, `tags`, `sort`, and `pagination`; `queryKeepItems` without React |
156
+ | Organization | Archive, pin, `collectionId`, `createInboxQuery`, and `useKeepCollections` |
157
+ | Multiple collections and ordering | `addKeepItemToCollection`, `getKeepCollectionItems`, `reorderKeepCollectionItems`, `removeKeepItemFromCollection` |
158
+ | Rediscovery | `useKeepItem(item).recordOpen()`, `createRediscoveryQuery`, and `useKeepRediscovery` |
159
+ | History, viewing records, and progress | `LocalStorageKeepHistoryStorage`, `LocalStorageKeepViewingRecordStorage`, `LocalStorageKeepProgressStorage` |
160
+ | Source revalidation | Provider `validateItem` / `resolveItem` and `revalidateItems` |
161
+
162
+ Lists return unarchived items by default. Use `archiveScope: "all"` for both or `archived: true` for archived items.
163
+ Memberships are stored separately; removing one leaves the shared item and note intact.
181
164
 
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.
165
+ ### Storage, sync, and backups
183
166
 
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.
167
+ - `createBrowserStorageAdapter` prefers IndexedDB and falls back to localStorage. Use `scope` to isolate users and tenants.
168
+ - Combine `SyncStorageAdapter` and `RemoteSyncDriver` for durable offline queues, retries, and conflicts. Definition and membership sync require `pushCollection` / `pullCollections` and `pushMembership` / `pullMemberships`, respectively.
169
+ - Authentication belongs to your app. See the [authenticated sync example](../../examples/authenticated-sync/README.md) for tokens and scope changes.
170
+ - 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.
185
171
 
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.
172
+ **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
173
 
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.
174
+ Custom `StorageAdapter` implementations need `getCollections` / `setCollection` / `removeCollection` and `getCollectionMemberships` / `setCollectionMembership` / `removeCollectionMembership` to support definitions and memberships. `clear()` clears saved items only.
189
175
 
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.
176
+ 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.
177
+ Namespace history and progress keys per account, and pass matching language, content version, and audio ID when reading progress.
191
178
 
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.
179
+ See the [repository README](../../README.md) for demos and development, and the [release notes](../../RELEASE_NOTES.md) for changes.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@keepkit/core",
3
- "version": "0.28.8",
3
+ "version": "0.28.9",
4
4
  "description": "A flexible save-and-collect toolkit for React apps.",
5
5
  "type": "module",
6
6
  "license": "MIT",