as-free 0.0.1-beta.0 → 0.0.2-beta.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.
Files changed (3) hide show
  1. package/README.ja.md +153 -0
  2. package/README.md +111 -56
  3. package/package.json +1 -1
package/README.ja.md ADDED
@@ -0,0 +1,153 @@
1
+ # as-free
2
+
3
+ [![CI](https://github.com/9wick/as-free/actions/workflows/ci.yml/badge.svg)](https://github.com/9wick/as-free/actions/workflows/ci.yml)
4
+ [![npm version](https://img.shields.io/npm/v/as-free)](https://www.npmjs.com/package/as-free)
5
+ [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE)
6
+
7
+ [English](README.md) | 日本語
8
+
9
+ **アプリケーションコードから `as` をなくすための、型を保つ TypeScript ユーティリティ集。**
10
+
11
+ ## 概要
12
+
13
+ TypeScript では、`Object.fromEntries()` や `JSON.parse()`、型付きストア、オーバーロードを持つ関数の転送など、**「実行時には型が保証されているのに、言語機能の制約で型が失われる」** 場面があります。
14
+
15
+ `as-free` は、そうした不可避な型アサーションを契約付きの小さなユーティリティ内に閉じ込めます。呼び出し側は `as` を書かずに、通常の型検査だけで精密な型を受け取れます。
16
+
17
+ > **対象外:** 根拠のないキャスト、外部入力のバリデーション境界、テストモック、サードパーティ `@types` の回避策。対象スコープの分類と採用基準の詳細は [スコープと採用基準](docs/scope.ja.md) をご覧ください。
18
+
19
+ ## インストール
20
+
21
+ ```bash
22
+ npm install as-free
23
+ # または
24
+ pnpm add as-free
25
+ ```
26
+
27
+ ESM 専用パッケージです(`.d.mts` 型定義同梱)。
28
+
29
+ ## 使い方
30
+
31
+ ### キーと値の型を保つ変換 (`fromEntries`, `mapValues`)
32
+
33
+ `fromEntries` や `mapValues` を使っても、キーと値のリテラル型やプロパティごとの型を失いません。
34
+
35
+ ```ts
36
+ import { fromEntries, mapValues } from "as-free";
37
+
38
+ const product = fromEntries([
39
+ ["name", "ノート"],
40
+ ["price", 300],
41
+ ] as const);
42
+ product.name; // "ノート"
43
+ product.price; // 300
44
+
45
+ const boxes = { price: { value: 300 }, title: { value: "ノート" } };
46
+ const values = mapValues(boxes, (box) => box.value);
47
+ values.price; // number
48
+ values.title; // string
49
+ ```
50
+
51
+ ### 型を保った JSON 保管 (`createJsonStore`)
52
+
53
+ JSON 往復できる型 `T` で `set` と `get` を結び付け、結果を `Result` で返します。
54
+
55
+ ```ts
56
+ import { createJsonStore } from "as-free";
57
+
58
+ type Product = { name: string; price: number };
59
+
60
+ const products = createJsonStore<Product>({
61
+ readString: (key) => redis.get(`product:${key}`),
62
+ writeString: (key, text) => redis.set(`product:${key}`, text),
63
+ });
64
+
65
+ await products.set("note", { name: "ノート", price: 300 });
66
+
67
+ const result = await products.get("note");
68
+ if (result.type === "Success") {
69
+ result.value; // Product
70
+ }
71
+ ```
72
+
73
+ ### 型付きキーストアと有効期間付き参照 (`KeyedValueStore`, `createKeyedValueView`)
74
+
75
+ 不変な型パラメータを持つ `ValueKey<T>` で異なる型の値を 1 つのストアに保管したり、有効期間を検査する Proxy を作れます。
76
+
77
+ ```ts
78
+ import { KeyedValueStore, ValueKey } from "as-free";
79
+
80
+ const store = new KeyedValueStore();
81
+ const title = new ValueKey<string>();
82
+ const quantity = new ValueKey<number>();
83
+
84
+ store.set(title, "ノート");
85
+ store.set(quantity, 12);
86
+
87
+ store.get(title); // string | undefined
88
+ store.get(quantity); // number | undefined
89
+ ```
90
+
91
+ ### オーバーロードを保つ関数転送 (`defineForwarder`, `whenArg`, `isFunction`)
92
+
93
+ オーバーロードやジェネリクスを失わずに、関数呼び出しをラップ・振り分けできます。
94
+
95
+ ```ts
96
+ import { defineForwarder } from "as-free";
97
+
98
+ type Format = {
99
+ (value: number, digits: number): string;
100
+ (value: Date): string;
101
+ };
102
+
103
+ declare const format: Format;
104
+
105
+ const countedFormat = defineForwarder<[Format]>((args, forward) => {
106
+ return forward(format, args);
107
+ });
108
+
109
+ countedFormat(3.14159, 2); // string
110
+ countedFormat(new Date()); // string
111
+ ```
112
+
113
+ ### 実行時のコンストラクタ判定 (`as-free/runtime`)
114
+
115
+ 対象を呼び出さず、`prototype` にも触れずに `[[Construct]]` を持つか判定します。
116
+
117
+ ```ts
118
+ import { isConstructor } from "as-free/runtime";
119
+
120
+ const candidate: unknown = Date;
121
+
122
+ if (isConstructor(candidate)) {
123
+ console.log(new Date(0) instanceof candidate); // true
124
+ }
125
+ ```
126
+
127
+ ## モジュール一覧
128
+
129
+ | モジュール | インポート | 用途 | ドキュメント |
130
+ | ------------- | ----------------- | -------------------------------------------------------- | ------------------------------------------- |
131
+ | `keyed-value` | `as-free` | キーと値の型対応を保つ `fromEntries` / `mapValues` | [keyed-value](src/keyed-value/README.ja.md) |
132
+ | `json` | `as-free` | JSON 経由で `T` を保つ `createJsonStore` | [json](src/json/README.ja.md) |
133
+ | `value-store` | `as-free` | `KeyedValueStore` / `ValueKey` と `createKeyedValueView` | [value-store](src/value-store/README.ja.md) |
134
+ | `callable` | `as-free` | `defineForwarder`, `whenArg`, `isFunction` | [callable](src/callable/README.ja.md) |
135
+ | `runtime` | `as-free/runtime` | `isConstructor` によるコンストラクタ判定 | [runtime](src/runtime/README.ja.md) |
136
+
137
+ ## ドキュメント
138
+
139
+ - [スコープと採用基準](docs/scope.ja.md) — このパッケージが対象とする `as` の分類と採用基準
140
+ - 各モジュール詳細: [keyed-value](src/keyed-value/README.ja.md) · [json](src/json/README.ja.md) · [value-store](src/value-store/README.ja.md) · [callable](src/callable/README.ja.md) · [runtime](src/runtime/README.ja.md)
141
+
142
+ ## 開発
143
+
144
+ ```bash
145
+ pnpm install
146
+ vp check # リント・フォーマット・型チェック
147
+ vp run test # テスト実行
148
+ vp run build # dist/ のビルド
149
+ ```
150
+
151
+ ## ライセンス
152
+
153
+ [MIT](LICENSE)
package/README.md CHANGED
@@ -1,98 +1,153 @@
1
1
  # as-free
2
2
 
3
- このパッケージは **「型安全だとわかっているのに、言語機能が足りなくて安全にできない」** 場合に使うものです。
4
- 必要な型アサーションをユーティリティの中に閉じ込め、アプリは `as` を書かずに精密な型を受け取れます。
3
+ [![CI](https://github.com/9wick/as-free/actions/workflows/ci.yml/badge.svg)](https://github.com/9wick/as-free/actions/workflows/ci.yml)
4
+ [![npm version](https://img.shields.io/npm/v/as-free)](https://www.npmjs.com/package/as-free)
5
+ [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE)
5
6
 
6
- 典型例:
7
+ English | [日本語](README.ja.md)
7
8
 
8
- - `Object.entries()` / `Object.fromEntries()` すると型が消える
9
- - `JSON.parse()` の戻り値が `unknown` になる
10
- - DI コンテナが返す値の型パラメータが消える
9
+ **Type-preserving TypeScript utilities so your application code needs no `as`.**
11
10
 
12
- ### 1. 何の保証もない `as`
11
+ ## Overview
13
12
 
14
- 型が合わないのでとりあえず黙らせるキャスト。最も危険。
13
+ In TypeScript, there are cases where you _know_ a value's exact type at runtime, yet the type system loses it—such as `Object.fromEntries()`, `JSON.parse()` round-trips, typed heterogenous stores, or forwarding overloaded functions.
15
14
 
16
- ```ts
17
- const value = someFunction() as MyType; // 根拠なし
18
- ```
15
+ `as-free` encapsulates the unavoidable `as` assertions inside small, contract-enforced utilities so your application code gets precise types through normal type checking alone.
19
16
 
20
- ### 2. 信頼境界の `as`
17
+ > **Out of scope:** Unchecked casts, validation-boundary casts, test mocks, and broken third-party `@types` workarounds. For the full taxonomy of `as` casts and our utility acceptance criteria, see [Scope & Design Criteria](docs/scope.md).
21
18
 
22
- 外部入力(API レスポンス、JSON など)にバリデーション付きで型を与えるキャスト。
23
- バリデーションの正しさに依存する。
19
+ ## Installation
24
20
 
25
- ```ts
26
- const parsed = schema.parse(JSON.parse(raw)) as Config;
21
+ ```bash
22
+ npm install as-free
23
+ # or
24
+ pnpm add as-free
27
25
  ```
28
26
 
29
- ### 3. 言語機能不足を補う `as`
27
+ `as-free` is ESM-only and ships bundled `.d.mts` type declarations.
30
28
 
31
- ランタイムでは正しいことが保証されているが、TypeScript の型システムが表現できないキャスト。
32
- **このパッケージが対象とするスコープ。**
29
+ ## Usage
33
30
 
34
- いくつかの小分類がある:
31
+ ### Type-preserving object transforms (`fromEntries`, `mapValues`)
35
32
 
36
- #### 3a. 型推論の限界
37
-
38
- ジェネリクスや高階型の推論が追いつかないケース。
33
+ Keep literal key and value types across `fromEntries` and `mapValues`:
39
34
 
40
35
  ```ts
41
- // Object.entries() はキーを string に拡げてしまう
42
- const entries = Object.entries(record) as [keyof T, T[keyof T]][];
36
+ import { fromEntries, mapValues } from "as-free";
37
+
38
+ const product = fromEntries([
39
+ ["name", "Notebook"],
40
+ ["price", 300],
41
+ ] as const);
42
+ product.name; // "Notebook"
43
+ product.price; // 300
44
+
45
+ const boxes = { price: { value: 300 }, title: { value: "Notebook" } };
46
+ const values = mapValues(boxes, (box) => box.value);
47
+ values.price; // number
48
+ values.title; // string
43
49
  ```
44
50
 
45
- #### 3b. ナローイング補助
51
+ ### Typed JSON storage (`createJsonStore`)
46
52
 
47
- 型ガードや discriminated union で絞り込んだ後、コンパイラが推論しきれないケース。
53
+ Pair `set` and `get` under a single JSON-round-trippable type `T` with `Result`-based error handling:
48
54
 
49
55
  ```ts
50
- // switch で全ケースを網羅しているが、コンパイラが絞りきれない末端
51
- function handle(action: Action) {
52
- switch (action.type) {
53
- case "create":
54
- return processCreate(action as CreateAction);
55
- // ...
56
- }
56
+ import { createJsonStore } from "as-free";
57
+
58
+ type Product = { name: string; price: number };
59
+
60
+ const products = createJsonStore<Product>({
61
+ readString: (key) => redis.get(`product:${key}`),
62
+ writeString: (key, text) => redis.set(`product:${key}`, text),
63
+ });
64
+
65
+ await products.set("note", { name: "Notebook", price: 300 });
66
+
67
+ const result = await products.get("note");
68
+ if (result.type === "Success") {
69
+ result.value; // Product
57
70
  }
58
71
  ```
59
72
 
60
- > **推奨:** このケースは `ts-pattern` の `match().exhaustive()` を使えば `as` なしで型安全にナローイングできる。標準の `switch` 構文の制約であり、言語機能自体の不足ではないため、`as` ではなく `ts-pattern` の利用を推奨する。
73
+ ### Typed key-value store & lifetime views (`KeyedValueStore`, `createKeyedValueView`)
74
+
75
+ Store differently typed values in one store using invariant `ValueKey<T>` tokens, or guard object access with a lifetime check:
76
+
77
+ ```ts
78
+ import { KeyedValueStore, ValueKey } from "as-free";
79
+
80
+ const store = new KeyedValueStore();
81
+ const title = new ValueKey<string>();
82
+ const quantity = new ValueKey<number>();
61
83
 
62
- ### 4. テストモックの `as`
84
+ store.set(title, "Notebook");
85
+ store.set(quantity, 12);
63
86
 
64
- テストでオブジェクトの一部だけ用意するためのキャスト。プロダクションコードには入らない。
87
+ store.get(title); // string | undefined
88
+ store.get(quantity); // number | undefined
89
+ ```
90
+
91
+ ### Overload-preserving forwarding (`defineForwarder`, `whenArg`, `isFunction`)
92
+
93
+ Wrap or dispatch calls without losing overload signatures or generic parameters:
65
94
 
66
95
  ```ts
67
- const mockUser = { name: "test" } as User;
96
+ import { defineForwarder } from "as-free";
97
+
98
+ type Format = {
99
+ (value: number, digits: number): string;
100
+ (value: Date): string;
101
+ };
102
+
103
+ declare const format: Format;
104
+
105
+ const countedFormat = defineForwarder<[Format]>((args, forward) => {
106
+ return forward(format, args);
107
+ });
108
+
109
+ countedFormat(3.14159, 2); // string
110
+ countedFormat(new Date()); // string
68
111
  ```
69
112
 
70
- ### 5. ライブラリ型定義の不備を回避する `as`
113
+ ### Runtime constructor check (`as-free/runtime`)
71
114
 
72
- サードパーティの `@types` が不正確・古い場合に正しい型へ矯正するキャスト。
73
- 外部要因に依存するため、型定義の更新で不要になることがある。
115
+ Check whether an `unknown` value has `[[Construct]]` without invoking it or touching `prototype`:
74
116
 
75
117
  ```ts
76
- // @types/xxx が返り値を string としているが、実際は string | null
77
- const result = lib.getValue() as string | null;
118
+ import { isConstructor } from "as-free/runtime";
119
+
120
+ const candidate: unknown = Date;
121
+
122
+ if (isConstructor(candidate)) {
123
+ console.log(new Date(0) instanceof candidate); // true
124
+ }
78
125
  ```
79
126
 
80
- ---
127
+ ## Modules
128
+
129
+ | Module | Import | Purpose | Docs |
130
+ | ------------- | ----------------- | ---------------------------------------------------------- | ---------------------------------------- |
131
+ | `keyed-value` | `as-free` | `fromEntries`, `mapValues` preserving key/value types | [keyed-value](src/keyed-value/README.md) |
132
+ | `json` | `as-free` | `createJsonStore` preserving `T` across JSON serialization | [json](src/json/README.md) |
133
+ | `value-store` | `as-free` | `KeyedValueStore` / `ValueKey` and `createKeyedValueView` | [value-store](src/value-store/README.md) |
134
+ | `callable` | `as-free` | `defineForwarder`, `whenArg`, `isFunction` | [callable](src/callable/README.md) |
135
+ | `runtime` | `as-free/runtime` | `isConstructor` runtime check | [runtime](src/runtime/README.md) |
81
136
 
82
- **このパッケージは分類 3(言語機能不足を補う `as`)のみを対象とする。** それ以外の `as` は、それぞれ適切な場所(バリデーション層、テストユーティリティなど)で管理すべきである。
137
+ ## Documentation
83
138
 
84
- ## 採用基準
139
+ - [Scope & Design Criteria](docs/scope.md) — Which `as` casts this package targets and how utilities are evaluated
140
+ - Module guides: [keyed-value](src/keyed-value/README.md) · [json](src/json/README.md) · [value-store](src/value-store/README.md) · [callable](src/callable/README.md) · [runtime](src/runtime/README.md)
85
141
 
86
- 型アサーションを使うユーティリティには、以下のすべてが必要です。
142
+ ## Development
87
143
 
88
- 1. 受け付ける入力の契約と実装から、宣言した戻り値型が実行時に成立することを説明できる。
89
- 2. TypeScript の型検査だけでは、その型の関係を保ったまま処理を書けない。
90
- 3. 型アサーションを関数内に閉じ込めることで、アプリは通常の型検査が効く呼び出しだけで使える。
144
+ ```bash
145
+ pnpm install
146
+ vp check # lint, format, and type check
147
+ vp run test # run tests
148
+ vp run build # build dist/
149
+ ```
91
150
 
92
- ## モジュール
151
+ ## License
93
152
 
94
- - [keyed-value](src/keyed-value/README.md) は、キーと値の型の対応を保つ変換を扱います。
95
- - [json](src/json/README.md) は、JSON にして保管した値を、同じ型で取り出します。
96
- - [value-store](src/value-store/README.md) は、有効期間を持つ参照と、型付きキーでの保管を扱います。
97
- - [callable](src/callable/README.md) は、オーバーロードを保ったまま関数の呼び出しを転送します。
98
- - [runtime](src/runtime/README.md) は、コンストラクタの判定を扱います。
153
+ [MIT](LICENSE)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "as-free",
3
- "version": "0.0.1-beta.0",
3
+ "version": "0.0.2-beta.0",
4
4
  "description": "Type-preserving utilities so your code needs no `as`.",
5
5
  "license": "MIT",
6
6
  "repository": {