ts-strategy 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +121 -0
- package/dist/createStrategy.d.ts +48 -0
- package/dist/index.cjs +71 -0
- package/dist/index.d.cts +1 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.js +29 -0
- package/package.json +70 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025 eli0shin
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
# ts-strategy
|
|
2
|
+
|
|
3
|
+
Type-safe strategy pattern for TypeScript. Register named strategy variants and execute them with compile-time type safety.
|
|
4
|
+
|
|
5
|
+
## Install
|
|
6
|
+
|
|
7
|
+
```sh
|
|
8
|
+
npm install ts-strategy
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
Requires TypeScript 5+.
|
|
12
|
+
|
|
13
|
+
## Usage
|
|
14
|
+
|
|
15
|
+
```ts
|
|
16
|
+
import { createStrategy } from 'ts-strategy';
|
|
17
|
+
|
|
18
|
+
const pricing = createStrategy(
|
|
19
|
+
{ variant: 'flat', toExecute: (amount: number) => amount },
|
|
20
|
+
{ variant: 'percentage', toExecute: (amount: number) => amount * 0.1 }
|
|
21
|
+
);
|
|
22
|
+
|
|
23
|
+
pricing.variant('flat').execute(100); // 100
|
|
24
|
+
pricing.variant('percentage').execute(100); // 10
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
## API
|
|
28
|
+
|
|
29
|
+
### `createStrategy(...config)`
|
|
30
|
+
|
|
31
|
+
```ts
|
|
32
|
+
function createStrategy<VariantId extends string, StrategyFn>(
|
|
33
|
+
...config: { variant: VariantId | VariantId[]; toExecute: StrategyFn }[]
|
|
34
|
+
): {
|
|
35
|
+
variant: (id: VariantId) => { execute: (...args) => ReturnType<StrategyFn> };
|
|
36
|
+
};
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
Each config object maps one or more variant IDs to a `toExecute` function. Returns a strategy object with a `.variant(id).execute(...args)` chain.
|
|
40
|
+
|
|
41
|
+
**Parameters**
|
|
42
|
+
|
|
43
|
+
- `config` — Rest arguments. Each is an object with:
|
|
44
|
+
- `variant` — A string or array of strings identifying this variant.
|
|
45
|
+
- `toExecute` — The function to run when this variant is selected.
|
|
46
|
+
|
|
47
|
+
**Returns** an object with:
|
|
48
|
+
|
|
49
|
+
- `.variant(id)` — Selects a variant by ID. Returns an object with `.execute()`.
|
|
50
|
+
- `.execute(...args)` — Calls the variant's `toExecute` function with the provided arguments and returns its result.
|
|
51
|
+
|
|
52
|
+
## Type safety
|
|
53
|
+
|
|
54
|
+
All `toExecute` functions must have compatible signatures. TypeScript infers a single shared function type from all config entries:
|
|
55
|
+
|
|
56
|
+
```ts
|
|
57
|
+
// This compiles — both functions take (name: string) and return string
|
|
58
|
+
const strategy = createStrategy(
|
|
59
|
+
{ variant: 'a', toExecute: (name: string) => `Hello ${name}` },
|
|
60
|
+
{ variant: 'b', toExecute: (name: string) => `Goodbye ${name}` }
|
|
61
|
+
);
|
|
62
|
+
|
|
63
|
+
// This does NOT compile — (string) => string and (number) => number are incompatible
|
|
64
|
+
const strategy = createStrategy(
|
|
65
|
+
{ variant: 'a', toExecute: (x: string) => x },
|
|
66
|
+
{ variant: 'b', toExecute: (x: number) => x } // Type error
|
|
67
|
+
);
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
Variant IDs are narrowed to string literals. Passing an unregistered ID to `.variant()` is a compile-time error:
|
|
71
|
+
|
|
72
|
+
```ts
|
|
73
|
+
const strategy = createStrategy(
|
|
74
|
+
{ variant: 'a', toExecute: () => 1 },
|
|
75
|
+
{ variant: 'b', toExecute: () => 2 }
|
|
76
|
+
);
|
|
77
|
+
|
|
78
|
+
strategy.variant('a'); // OK
|
|
79
|
+
strategy.variant('c'); // Type error: '"c"' is not assignable to '"a" | "b"'
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
## Array variants
|
|
83
|
+
|
|
84
|
+
Map multiple variant IDs to the same function:
|
|
85
|
+
|
|
86
|
+
```ts
|
|
87
|
+
const strategy = createStrategy(
|
|
88
|
+
{ variant: 'a', toExecute: () => 'solo' },
|
|
89
|
+
{ variant: ['b', 'c'], toExecute: () => 'shared' }
|
|
90
|
+
);
|
|
91
|
+
|
|
92
|
+
strategy.variant('b').execute(); // 'shared'
|
|
93
|
+
strategy.variant('c').execute(); // 'shared'
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
## Error handling
|
|
97
|
+
|
|
98
|
+
Errors are deferred to `.execute()`. Calling `.variant(id)` with an unregistered ID does not throw — the error surfaces when `.execute()` is called:
|
|
99
|
+
|
|
100
|
+
```ts
|
|
101
|
+
// At runtime (e.g. via type assertion or dynamic input):
|
|
102
|
+
strategy.variant('unknown' as any).execute();
|
|
103
|
+
// throws Error: "No function defined for variant unknown"
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
## Duplicate variant IDs
|
|
107
|
+
|
|
108
|
+
If the same variant ID appears in multiple config entries, the last one wins:
|
|
109
|
+
|
|
110
|
+
```ts
|
|
111
|
+
const strategy = createStrategy(
|
|
112
|
+
{ variant: 'a', toExecute: () => 'first' },
|
|
113
|
+
{ variant: 'a', toExecute: () => 'second' }
|
|
114
|
+
);
|
|
115
|
+
|
|
116
|
+
strategy.variant('a').execute(); // 'second'
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
## License
|
|
120
|
+
|
|
121
|
+
MIT
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
type StringOrStringArray<Value extends string> = Value | Value[];
|
|
2
|
+
type AbstractStrategyFn = (...args: any[]) => any;
|
|
3
|
+
type StrategyConfig<VariantId, StrategyFn> = {
|
|
4
|
+
variant: VariantId;
|
|
5
|
+
toExecute: StrategyFn;
|
|
6
|
+
}[];
|
|
7
|
+
type Strategy<VariantId, StrategyFn extends AbstractStrategyFn> = {
|
|
8
|
+
variant: (variant: VariantId) => StrategyVariant<StrategyFn>;
|
|
9
|
+
};
|
|
10
|
+
type StrategyVariant<StrategyFn extends AbstractStrategyFn> = {
|
|
11
|
+
execute: (...args: Parameters<StrategyFn>) => ReturnType<StrategyFn>;
|
|
12
|
+
};
|
|
13
|
+
/**
|
|
14
|
+
* `createStrategy` creates a strategy with different `variant`s and their corresponding functions `toExecute`.
|
|
15
|
+
*
|
|
16
|
+
* The `toExecute` function's arguments and return
|
|
17
|
+
* type must be compatible between all variants.
|
|
18
|
+
* This means that if 1 variant accepts 3 args and
|
|
19
|
+
* 1 only 2, all three args must be passed.
|
|
20
|
+
* Similarly, if 1 returns keys `a` and `b`, and 1
|
|
21
|
+
* only returns `a`, only `a` will be available in
|
|
22
|
+
* the result's type.
|
|
23
|
+
*
|
|
24
|
+
* @example
|
|
25
|
+
* // Define the strategy functions
|
|
26
|
+
* const strategyA = (name: string) => `Result from strategy A ${name}`;
|
|
27
|
+
* const strategyB = (name: string) => `Result from strategy B ${name}`;
|
|
28
|
+
*
|
|
29
|
+
* // Create the strategy with variants
|
|
30
|
+
* // In this example, variants 'B', and 'C' will have the same behavior
|
|
31
|
+
* // but variant 'A' will have a different behavior.
|
|
32
|
+
* const myStrategy = createStrategy(
|
|
33
|
+
* { variant: 'A', toExecute: strategyA },
|
|
34
|
+
* { variant: ['B', 'C'], toExecute: strategyB }
|
|
35
|
+
* );
|
|
36
|
+
*
|
|
37
|
+
* // Select and execute a strategy variant
|
|
38
|
+
* const resultA = myStrategy.variant('A').execute('Bob');
|
|
39
|
+
* console.log(resultA); // Output: 'Result from strategy A Bob'
|
|
40
|
+
*
|
|
41
|
+
* const resultB = myStrategy.variant('B').execute('Bob');
|
|
42
|
+
* console.log(resultB); // Output: 'Result from strategy B Bob'
|
|
43
|
+
*
|
|
44
|
+
* const resultC = myStrategy.variant('C').execute('Bob');
|
|
45
|
+
* console.log(resultC); // Output: 'Result from strategy B Bob'
|
|
46
|
+
*/
|
|
47
|
+
export declare function createStrategy<VariantId extends string, StrategyFn extends AbstractStrategyFn>(...config: StrategyConfig<StringOrStringArray<VariantId>, StrategyFn>): Strategy<VariantId, StrategyFn>;
|
|
48
|
+
export {};
|
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
var __defProp = Object.defineProperty;
|
|
2
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
5
|
+
function __accessProp(key) {
|
|
6
|
+
return this[key];
|
|
7
|
+
}
|
|
8
|
+
var __toCommonJS = (from) => {
|
|
9
|
+
var entry = (__moduleCache ??= new WeakMap).get(from), desc;
|
|
10
|
+
if (entry)
|
|
11
|
+
return entry;
|
|
12
|
+
entry = __defProp({}, "__esModule", { value: true });
|
|
13
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
14
|
+
for (var key of __getOwnPropNames(from))
|
|
15
|
+
if (!__hasOwnProp.call(entry, key))
|
|
16
|
+
__defProp(entry, key, {
|
|
17
|
+
get: __accessProp.bind(from, key),
|
|
18
|
+
enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
|
|
19
|
+
});
|
|
20
|
+
}
|
|
21
|
+
__moduleCache.set(from, entry);
|
|
22
|
+
return entry;
|
|
23
|
+
};
|
|
24
|
+
var __moduleCache;
|
|
25
|
+
var __returnValue = (v) => v;
|
|
26
|
+
function __exportSetter(name, newValue) {
|
|
27
|
+
this[name] = __returnValue.bind(null, newValue);
|
|
28
|
+
}
|
|
29
|
+
var __export = (target, all) => {
|
|
30
|
+
for (var name in all)
|
|
31
|
+
__defProp(target, name, {
|
|
32
|
+
get: all[name],
|
|
33
|
+
enumerable: true,
|
|
34
|
+
configurable: true,
|
|
35
|
+
set: __exportSetter.bind(all, name)
|
|
36
|
+
});
|
|
37
|
+
};
|
|
38
|
+
|
|
39
|
+
// src/index.ts
|
|
40
|
+
var exports_src = {};
|
|
41
|
+
__export(exports_src, {
|
|
42
|
+
createStrategy: () => createStrategy
|
|
43
|
+
});
|
|
44
|
+
module.exports = __toCommonJS(exports_src);
|
|
45
|
+
|
|
46
|
+
// src/createStrategy.ts
|
|
47
|
+
function createStrategy(...config) {
|
|
48
|
+
const variantsById = new Map;
|
|
49
|
+
config.forEach((variantConfig) => {
|
|
50
|
+
if (typeof variantConfig.variant === "string") {
|
|
51
|
+
variantsById.set(variantConfig.variant, variantConfig.toExecute);
|
|
52
|
+
} else {
|
|
53
|
+
variantConfig.variant.forEach((variantId) => {
|
|
54
|
+
variantsById.set(variantId, variantConfig.toExecute);
|
|
55
|
+
});
|
|
56
|
+
}
|
|
57
|
+
});
|
|
58
|
+
return {
|
|
59
|
+
variant: function variant(variantId) {
|
|
60
|
+
return {
|
|
61
|
+
execute: function execute(...args) {
|
|
62
|
+
const variantFn = variantsById.get(variantId);
|
|
63
|
+
if (!variantFn) {
|
|
64
|
+
throw new Error(`No function defined for variant ${variantId}`);
|
|
65
|
+
}
|
|
66
|
+
return variantFn(...args);
|
|
67
|
+
}
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
};
|
|
71
|
+
}
|
package/dist/index.d.cts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * from './createStrategy';
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * from './createStrategy';
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
// src/createStrategy.ts
|
|
2
|
+
function createStrategy(...config) {
|
|
3
|
+
const variantsById = new Map;
|
|
4
|
+
config.forEach((variantConfig) => {
|
|
5
|
+
if (typeof variantConfig.variant === "string") {
|
|
6
|
+
variantsById.set(variantConfig.variant, variantConfig.toExecute);
|
|
7
|
+
} else {
|
|
8
|
+
variantConfig.variant.forEach((variantId) => {
|
|
9
|
+
variantsById.set(variantId, variantConfig.toExecute);
|
|
10
|
+
});
|
|
11
|
+
}
|
|
12
|
+
});
|
|
13
|
+
return {
|
|
14
|
+
variant: function variant(variantId) {
|
|
15
|
+
return {
|
|
16
|
+
execute: function execute(...args) {
|
|
17
|
+
const variantFn = variantsById.get(variantId);
|
|
18
|
+
if (!variantFn) {
|
|
19
|
+
throw new Error(`No function defined for variant ${variantId}`);
|
|
20
|
+
}
|
|
21
|
+
return variantFn(...args);
|
|
22
|
+
}
|
|
23
|
+
};
|
|
24
|
+
}
|
|
25
|
+
};
|
|
26
|
+
}
|
|
27
|
+
export {
|
|
28
|
+
createStrategy
|
|
29
|
+
};
|
package/package.json
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "ts-strategy",
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "Type-safe strategy pattern for TypeScript. Register named strategy variants and execute them with compile-time type safety.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"author": "eli0shin",
|
|
7
|
+
"repository": {
|
|
8
|
+
"type": "git",
|
|
9
|
+
"url": "https://github.com/eli0shin/ts-strategy.git"
|
|
10
|
+
},
|
|
11
|
+
"homepage": "https://github.com/eli0shin/ts-strategy#readme",
|
|
12
|
+
"bugs": {
|
|
13
|
+
"url": "https://github.com/eli0shin/ts-strategy/issues"
|
|
14
|
+
},
|
|
15
|
+
"keywords": [
|
|
16
|
+
"strategy",
|
|
17
|
+
"typescript",
|
|
18
|
+
"type-safe"
|
|
19
|
+
],
|
|
20
|
+
"type": "module",
|
|
21
|
+
"exports": {
|
|
22
|
+
".": {
|
|
23
|
+
"import": {
|
|
24
|
+
"types": "./dist/index.d.ts",
|
|
25
|
+
"default": "./dist/index.js"
|
|
26
|
+
},
|
|
27
|
+
"require": {
|
|
28
|
+
"types": "./dist/index.d.cts",
|
|
29
|
+
"default": "./dist/index.cjs"
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
},
|
|
33
|
+
"files": [
|
|
34
|
+
"dist"
|
|
35
|
+
],
|
|
36
|
+
"scripts": {
|
|
37
|
+
"build": "bun run build:esm && bun run build:cjs && bun run build:types",
|
|
38
|
+
"build:esm": "bun build src/index.ts --outdir dist --format esm --target node",
|
|
39
|
+
"build:cjs": "bun build src/index.ts --outfile dist/index.cjs --format cjs --target node",
|
|
40
|
+
"build:types": "tsc --project tsconfig.build.json && cp dist/index.d.ts dist/index.d.cts",
|
|
41
|
+
"test": "vitest run --typecheck",
|
|
42
|
+
"type:check": "tsc --noEmit",
|
|
43
|
+
"format": "prettier --write .",
|
|
44
|
+
"format:check": "prettier --check .",
|
|
45
|
+
"lint": "eslint .",
|
|
46
|
+
"lint:fix": "eslint . --fix",
|
|
47
|
+
"prepare": "husky"
|
|
48
|
+
},
|
|
49
|
+
"devDependencies": {
|
|
50
|
+
"@changesets/changelog-github": "^0.5.2",
|
|
51
|
+
"@changesets/cli": "^2.29.7",
|
|
52
|
+
"@types/bun": "latest",
|
|
53
|
+
"@typescript-eslint/parser": "^8.50.1",
|
|
54
|
+
"@typescript-eslint/utils": "^8.50.1",
|
|
55
|
+
"eslint": "^9.39.2",
|
|
56
|
+
"eslint-for-ai": "^1.0.8",
|
|
57
|
+
"eslint-import-resolver-typescript": "^4.4.4",
|
|
58
|
+
"husky": "^9.1.7",
|
|
59
|
+
"lint-staged": "^16.2.7",
|
|
60
|
+
"prettier": "^3.6.2",
|
|
61
|
+
"typescript-eslint": "^8.50.1",
|
|
62
|
+
"vitest": "^4.0.13"
|
|
63
|
+
},
|
|
64
|
+
"peerDependencies": {
|
|
65
|
+
"typescript": "^5"
|
|
66
|
+
},
|
|
67
|
+
"lint-staged": {
|
|
68
|
+
"*.{ts,tsx,js,jsx,json,md,yml,yaml}": "prettier --write"
|
|
69
|
+
}
|
|
70
|
+
}
|