Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .github/dependabot.yml
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,11 @@ updates:
interval: weekly
day: monday
open-pull-requests-limit: 10
# vite-plugin-dts / unplugin-dts still need the TS 5/6 JS Compiler API.
# TypeScript 7+ breaks config load unless @typescript/typescript6 is added.
ignore:
- dependency-name: typescript
update-types: ["version-update:semver-major"]
groups:
npm-production:
dependency-type: production
Expand Down
14 changes: 14 additions & 0 deletions .github/workflows/publish.yml
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,20 @@ jobs:
- name: Install dependencies
run: npm ci

- name: Require package.json version matches tag
env:
TAG: ${{ steps.meta.outputs.tag }}
run: |
set -euo pipefail
expected="${TAG#v}"
actual="$(node -p "require('./package.json').version")"
if [ "$actual" != "$expected" ]; then
echo "Tag ${TAG} does not match package.json version ${actual} (expected ${expected})."
echo "Bump package.json before tagging, or move the tag to the version bump commit."
exit 1
fi
echo "Tag ${TAG} matches package.json version ${actual}."

- name: Test
if: steps.ci_history.outputs.skip_verify != 'true'
run: npm test
Expand Down
71 changes: 46 additions & 25 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,11 @@

[日本語](./README_ja.md)

Universal **browser-only** cache helper with **localStorage** (default) and **IndexedDB** backends, TTL, and a small async API.
Tree-shakeable **browser-only** cache helper. Pick a **driver** (localStorage / IndexedDB) and only the **methods** you need (`get` / `set` / `remove` / …).

Extracted and generalized from the cache logic in [`@b4moss/jp-local-gov-id`](https://github.com/b4moss/jp-local-gov-id).

CI/CD direction: [docs/ci-cd.md](./docs/ci-cd.md)
CI/CD: [docs/ci-cd.md](./docs/ci-cd.md)

## Install

Expand All @@ -25,37 +25,57 @@ npm install @b4moss/cachian

```ts
import { createCache } from "@b4moss/cachian";
import { localStorageDriver } from "@b4moss/cachian/drivers/localStorage";
import { get } from "@b4moss/cachian/methods/get";
import { set } from "@b4moss/cachian/methods/set";
import { remove } from "@b4moss/cachian/methods/remove";

const cache = createCache(); // localStorage by default
const cache = createCache({
driver: localStorageDriver(),
methods: [get, set, remove],
});

await cache.set("https://example.com/data.json", { hello: "world" });
const data = await cache.get("https://example.com/data.json");
```

Browser only: `createCache()` throws `CachianEnvironmentError` when the chosen backend API (`localStorage` / `indexedDB`) is unavailable (e.g. Node / SSR). Importing the module alone is safe — call `createCache()` only in the browser (or guard with `typeof window !== "undefined"`).
Browser only: drivers throw `CachianEnvironmentError` when the backend API is unavailable (e.g. Node / SSR). Importing modules alone is safe — create the driver / cache only in the browser (or guard with `typeof window !== "undefined"`).

### IndexedDB

```ts
import { indexedDBDriver } from "@b4moss/cachian/drivers/indexedDB";

const cache = createCache({
storage: "indexedDB",
dbName: "my-app",
storeName: "cache",
driver: indexedDBDriver({ dbName: "my-app", storeName: "cache" }),
methods: [get, set, remove],
});
```

### Options
### Options (`createCache`)

| Option | Default | Description |
|--------|---------|-------------|
| `storage` | `"localStorage"` | `"localStorage"` or `"indexedDB"` |
| `driver` | _(required)_ | Storage adapter from a driver factory |
| `methods` | _(required)_ | Non-empty list of method defs to attach |
| `enabled` | `true` | When `false`, reads miss and writes are no-ops |
| `ttlSeconds` | `31536000` (1 year) | Default TTL for `set` |
| `keyPrefix` | `""` | Prefix for physical keys |
| `dbName` | `"cachian"` | IndexedDB database name |
| `storeName` | `"entries"` | IndexedDB object store name |

Entry shape in storage: `{ expiresAt: number, data: unknown, createdAt?: number }` (localStorage stores JSON strings; IndexedDB stores objects). New writes always include `createdAt`.
### Methods (subpath imports)

| Import | Attaches |
|--------|----------|
| `@b4moss/cachian/methods/get` | `get` |
| `@b4moss/cachian/methods/set` | `set` |
| `@b4moss/cachian/methods/update` | `update` |
| `@b4moss/cachian/methods/upsert` | `upsert` |
| `@b4moss/cachian/methods/remove` | `remove` |
| `@b4moss/cachian/methods/has` | `has` |
| `@b4moss/cachian/methods/clear` | `clear` |
| `@b4moss/cachian/methods/purge` | `purge` |

Entry shape in storage: `{ expiresAt: number, data: unknown, createdAt?: number }` (localStorage stores JSON strings; IndexedDB stores objects). New `set` writes always include `createdAt`.

### Writes: `set` / `update` / `upsert`

Expand All @@ -70,25 +90,26 @@ await cache.upsert("k", value); // set on miss, update on hit
### Purge

```ts
// Remove everything managed by this instance
await cache.purge({ all: true });
import { purge } from "@b4moss/cachian/methods/purge";

// Remove specific logical keys
await cache.purge({ keys: ["a", "b"] });
const cache = createCache({
driver: localStorageDriver(),
methods: [get, set, purge],
});

// Remove entries older than the given age (fixed: year=365d, month=30d)
await cache.purge({ all: true });
await cache.purge({ keys: ["a", "b"] });
await cache.purge({ olderThan: { hours: 1, mins: 30 } });

// Absolute time (ISO 8601, or epoch seconds/ms number)
await cache.purge({ createdBefore: "2024-06-01T00:00:00.000Z" });
await cache.purge({ createdAfter: 1_700_000_000_000 });
await cache.purge({
createdAfter: "2024-01-01T00:00:00.000Z",
createdBefore: "2024-12-01T00:00:00.000Z",
});
```

Legacy entries without `createdAt` are left alone by `olderThan` and absolute-time modes (use `all` or `keys` to remove them). Mixing `olderThan` with `createdBefore` / `createdAfter` throws `TypeError`.
Legacy entries without `createdAt` are left alone by `olderThan` and absolute-time modes. Mixing `olderThan` with `createdBefore` / `createdAfter` throws `TypeError`.

## Breaking changes (v0.4)

- `createCache()` no longer returns a fixed full API; pass `driver` + `methods`.
- `storage: "localStorage" | "indexedDB"` string option removed — use driver factories.
- Drivers and methods are **not** re-exported from the package root (import subpaths).

## License

Expand Down
69 changes: 45 additions & 24 deletions README_ja.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,11 @@

[English](./README.md)

**localStorage**(既定)と **IndexedDB** を切り替えられる、TTL 付きの小さな非同期 **ブラウザ専用** キャッシュヘルパーです。
ツリーシェイク可能な **ブラウザ専用** キャッシュヘルパーです。**ドライバ**(localStorage / IndexedDB)と必要な **メソッド**(`get` / `set` / `remove` / …)だけを選んで組み立てます。

[`@b4moss/jp-local-gov-id`](https://github.com/b4moss/jp-local-gov-id) のキャッシュロジックを外出し・汎用化したものです。

CI/CD 方針: [docs/ci-cd.ja.md](./docs/ci-cd.ja.md)
CI/CD: [docs/ci-cd.ja.md](./docs/ci-cd.ja.md)

## インストール

Expand All @@ -25,35 +25,55 @@ npm install @b4moss/cachian

```ts
import { createCache } from "@b4moss/cachian";
import { localStorageDriver } from "@b4moss/cachian/drivers/localStorage";
import { get } from "@b4moss/cachian/methods/get";
import { set } from "@b4moss/cachian/methods/set";
import { remove } from "@b4moss/cachian/methods/remove";

const cache = createCache(); // 既定は localStorage
const cache = createCache({
driver: localStorageDriver(),
methods: [get, set, remove],
});

await cache.set("https://example.com/data.json", { hello: "world" });
const data = await cache.get("https://example.com/data.json");
```

ブラウザ専用です。選んだバックエンド API(`localStorage` / `indexedDB`)が無い環境(Node / SSR など)で `createCache()` を呼ぶと `CachianEnvironmentError` になります。モジュールの import だけなら問題ありません — `createCache()` はブラウザで呼ぶか、`typeof window !== "undefined"` などでガードしてください。
ブラウザ専用です。バックエンド API が無い環境(Node / SSR など)ではドライバ生成時に `CachianEnvironmentError` になります。モジュールの import だけなら安全です — ドライバ / `createCache` はブラウザで呼ぶか、`typeof window !== "undefined"` などでガードしてください。

### IndexedDB

```ts
import { indexedDBDriver } from "@b4moss/cachian/drivers/indexedDB";

const cache = createCache({
storage: "indexedDB",
dbName: "my-app",
storeName: "cache",
driver: indexedDBDriver({ dbName: "my-app", storeName: "cache" }),
methods: [get, set, remove],
});
```

### オプション
### オプション(`createCache`)

| オプション | 既定 | 説明 |
|------------|------|------|
| `storage` | `"localStorage"` | `"localStorage"` または `"indexedDB"` |
| `driver` | (必須) | ドライバ factory が返すストレージアダプタ |
| `methods` | (必須) | 付与する MethodDef の非空配列 |
| `enabled` | `true` | `false` のとき読み取りは miss、書き込みは no-op |
| `ttlSeconds` | `31536000`(1 年) | `set` の既定 TTL(秒) |
| `keyPrefix` | `""` | 物理キーの接頭辞 |
| `dbName` | `"cachian"` | IndexedDB の DB 名 |
| `storeName` | `"entries"` | IndexedDB の object store 名 |

### メソッド(サブパス import)

| import | 付与されるメソッド |
|--------|--------------------|
| `@b4moss/cachian/methods/get` | `get` |
| `@b4moss/cachian/methods/set` | `set` |
| `@b4moss/cachian/methods/update` | `update` |
| `@b4moss/cachian/methods/upsert` | `upsert` |
| `@b4moss/cachian/methods/remove` | `remove` |
| `@b4moss/cachian/methods/has` | `has` |
| `@b4moss/cachian/methods/clear` | `clear` |
| `@b4moss/cachian/methods/purge` | `purge` |

保存形式は `{ expiresAt: number, data: unknown, createdAt?: number }`(localStorage は JSON 文字列、IndexedDB はオブジェクト)。新規 `set` では必ず `createdAt` を付与します。

Expand All @@ -70,25 +90,26 @@ await cache.upsert("k", value); // 無ければ set、有れば update
### パージ

```ts
// このインスタンスが管理する範囲をすべて削除
await cache.purge({ all: true });
import { purge } from "@b4moss/cachian/methods/purge";

// 指定した論理キーだけ削除
await cache.purge({ keys: ["a", "b"] });
const cache = createCache({
driver: localStorageDriver(),
methods: [get, set, purge],
});

// 指定期間より古いエントリだけ削除(固定換算: year=365日, month=30日)
await cache.purge({ all: true });
await cache.purge({ keys: ["a", "b"] });
await cache.purge({ olderThan: { hours: 1, mins: 30 } });

// 絶対時刻(ISO 8601、またはエポック秒/ミリ秒の数値)
await cache.purge({ createdBefore: "2024-06-01T00:00:00.000Z" });
await cache.purge({ createdAfter: 1_700_000_000_000 });
await cache.purge({
createdAfter: "2024-01-01T00:00:00.000Z",
createdBefore: "2024-12-01T00:00:00.000Z",
});
```

`createdAt` の無い旧エントリは `olderThan` および絶対時刻モードでは残ります(消す場合は `all` または `keys` を使います)。`olderThan` と `createdBefore` / `createdAfter` の混在は `TypeError` になります。
`createdAt` の無い旧エントリは `olderThan` および絶対時刻モードでは残ります。`olderThan` と `createdBefore` / `createdAfter` の混在は `TypeError` になります。

## 破壊的変更(v0.4)

- `createCache()` は固定フル API を返さず、`driver` + `methods` の指定が必須
- `storage: "localStorage" | "indexedDB"` 文字列オプションは削除(ドライバ factory を使用)
- drivers / methods はルートから再エクスポートしない(サブパスから import)

## ライセンス

Expand Down
Loading