tinkit 0.0.0-stage → 1.0.1

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 (53) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +135 -2
  3. package/dist/arrays/index.d.ts +1168 -0
  4. package/dist/arrays/index.js +1 -0
  5. package/dist/async/index.d.ts +729 -0
  6. package/dist/async/index.js +1 -0
  7. package/dist/cache/index.d.ts +165 -0
  8. package/dist/cache/index.js +1 -0
  9. package/dist/color/index.d.ts +328 -0
  10. package/dist/color/index.js +1 -0
  11. package/dist/date/index.d.ts +1152 -0
  12. package/dist/date/index.js +1 -0
  13. package/dist/decorators/index.d.ts +313 -0
  14. package/dist/decorators/index.js +1 -0
  15. package/dist/easing/index.d.ts +452 -0
  16. package/dist/easing/index.js +1 -0
  17. package/dist/emitter/index.d.ts +104 -0
  18. package/dist/emitter/index.js +1 -0
  19. package/dist/format/index.d.ts +317 -0
  20. package/dist/format/index.js +1 -0
  21. package/dist/functions/index.d.ts +648 -0
  22. package/dist/functions/index.js +1 -0
  23. package/dist/guards/index.d.ts +1009 -0
  24. package/dist/guards/index.js +1 -0
  25. package/dist/index.d.ts +28 -0
  26. package/dist/index.js +1 -0
  27. package/dist/iterables/index.d.ts +501 -0
  28. package/dist/iterables/index.js +1 -0
  29. package/dist/math/index.d.ts +670 -0
  30. package/dist/math/index.js +1 -0
  31. package/dist/objects/index.d.ts +1307 -0
  32. package/dist/objects/index.js +1 -0
  33. package/dist/random/index.d.ts +184 -0
  34. package/dist/random/index.js +1 -0
  35. package/dist/search/index.d.ts +151 -0
  36. package/dist/search/index.js +1 -0
  37. package/dist/store/index.d.ts +71 -0
  38. package/dist/store/index.js +1 -0
  39. package/dist/strings/index.d.ts +751 -0
  40. package/dist/strings/index.js +3 -0
  41. package/dist/url/index.d.ts +357 -0
  42. package/dist/url/index.js +1 -0
  43. package/dist/utils/assert.d.ts +81 -0
  44. package/dist/utils/assert.js +1 -0
  45. package/dist/utils/index.d.ts +1 -0
  46. package/dist/utils/index.js +0 -0
  47. package/dist/utils/types.d.ts +64 -0
  48. package/dist/utils/types.js +0 -0
  49. package/dist/validate/index.d.ts +409 -0
  50. package/dist/validate/index.js +1 -0
  51. package/llms-full.txt +708 -0
  52. package/llms.txt +42 -0
  53. package/package.json +144 -5
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2023 Emilio Dominguez
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 CHANGED
@@ -1,3 +1,136 @@
1
- # Temporary Holding Version
1
+ ![tinkit: Small utilities. Solid foundations. A smiling pastel building block next to the wordmark tinkit, an npm i tinkit command and four facts: ~600 typed helpers, 20 modules, 0 dependencies, tree-shakeable.](https://raw.githubusercontent.com/emiliodominguez/js-helpers/main/docs/assets/tinkit-banner.png)
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ [![CI](https://img.shields.io/github/actions/workflow/status/emiliodominguez/js-helpers/tests.yml?branch=main&style=for-the-badge&label=CI&labelColor=161b22&logo=githubactions&logoColor=white)](https://github.com/emiliodominguez/js-helpers/actions/workflows/tests.yml)
4
+ [![TypeScript: strict](https://img.shields.io/badge/TS-strict-3178c6?style=for-the-badge&labelColor=161b22&logo=typescript&logoColor=white)](./tsconfig.json)
5
+ [![Runtime dependencies: 0](https://img.shields.io/badge/deps-0-2ea44f?style=for-the-badge&labelColor=161b22&logo=npm&logoColor=white)](./package.json)
6
+ [![Property tests: fast-check](https://img.shields.io/badge/tests-fast--check-8250df?style=for-the-badge&labelColor=161b22&logo=jest&logoColor=white)](#how-its-tested)
7
+ [![License: MIT](https://img.shields.io/badge/license-MIT-3da639?style=for-the-badge&labelColor=161b22&logo=opensourceinitiative&logoColor=white)](./LICENSE)
8
+
9
+ **Strictly typed utilities for everyday JavaScript, with the edge cases handled.**
10
+
11
+ ~600 tree-shakeable helpers · 20 modules · zero dependencies · a median of 450 B per import
12
+
13
+ ```bash
14
+ npm install tinkit
15
+ ```
16
+
17
+ ```ts
18
+ import { orderBy } from 'tinkit/arrays';
19
+ import { isShape, isInteger, isString } from 'tinkit/guards';
20
+ import { retry } from 'tinkit/async';
21
+ ```
22
+
23
+ ESM, fully typed, Node 20.19+ and modern browsers. Each module is a deep import, so your bundle only contains the helpers you call.
24
+
25
+ ## The edge cases
26
+
27
+ Floats, `NaN`, emoji, daylight saving, `__proto__`: where utility functions usually break. What a popular implementation returns for each input, next to tink:
28
+
29
+ | Case | Call | A popular implementation returns | tink returns |
30
+ | ------------------- | ------------------------------------------------------- | -------------------------------- | ------------------- |
31
+ | Float sums | `sum([0.1, 0.2, 0.3])` | `0.6000000000000001` | `0.6` |
32
+ | Sorting with NaN | `orderBy(rows, ['v']) // v: 2, NaN, 1, 3` | `[2, NaN, 1, 3]` | `[1, 2, 3, NaN]` |
33
+ | Hostile keys | `zipObject(['__proto__'], [{ isAdmin: true }]).isAdmin` | `true` | `undefined` |
34
+ | Prototype pollution | `set({}, '__proto__.polluted', true); ({}).polluted` | `true` | `throws RangeError` |
35
+ | Silent data loss | `toCamelCaseKeys({ user_id: 1, userId: 2 })` | `{"userId":2}` | `throws RangeError` |
36
+ | Emoji padding | `pad('👍', 5, '*')` | `"*👍**"` | `"**👍**"` |
37
+ | Unit parsing | `parse('1KiB')` | `1` | `1024` |
38
+ | URL editing | `withTrailingSlash('/a?x=1')` | `"/a?x=1/"` | `"/a/?x=1"` |
39
+ | DST (New York) | `hours from 00:00 to 03:00 on fall-back day` | `4` | `5` |
40
+ | Async memoization | `memoize(fetcher) after one transient failure` | `throws Error` | `"ok"` |
41
+
42
+ None of these are hand-written: `yarn build && yarn compare` recomputes every row against the installed libraries and prints which library returned what. In tink each behaviour is a tested invariant, not a special case.
43
+
44
+ ## Guards are validators
45
+
46
+ Type guards narrow, compose into schemas, report every issue with its path, and plug into anything that speaks [Standard Schema](https://standardschema.dev) (tRPC, TanStack Form, React Hook Form, Hono…). No second validation library.
47
+
48
+ ```ts
49
+ import { explain, isArrayOf, isInteger, isOneOf, isShape, isString, toStandardSchema, type Infer } from 'tinkit/guards';
50
+ import { parseJson } from 'tinkit/validate';
51
+
52
+ const isUser = isShape({ id: isInteger, email: isString, roles: isArrayOf(isOneOf(['admin', 'editor'])) });
53
+ type User = Infer<typeof isUser>; // { id: number; email: string; roles: ('admin' | 'editor')[] }
54
+
55
+ explain(isUser, { id: '7', roles: ['admin', 'root'] });
56
+ // [{ path: ['id'], message: 'Invalid value (got string)' },
57
+ // { path: ['email'], message: 'Missing required property' },
58
+ // { path: ['roles', 1], message: 'Expected one of 2 allowed values (got string)' }]
59
+
60
+ const [error, user] = parseJson(body, isUser); // never throws: a typed User, or a SyntaxError / ValidationError
61
+ const schema = toStandardSchema(isUser); // for your form or RPC library
62
+ ```
63
+
64
+ ## Hostile input is a non-event
65
+
66
+ ```ts
67
+ import { deepMerge, getPath } from 'tinkit/objects';
68
+ import { isAbsoluteUrl, sanitizeUrl } from 'tinkit/url';
69
+
70
+ deepMerge(defaults, JSON.parse('{"__proto__": {"isAdmin": true}}')); // key dropped, Object.prototype untouched
71
+ getPath(permissions, 'viewer.constructor', false); // false: inherited Object members never resolve
72
+ sanitizeUrl(' JAVASCRIPT:alert(1)'); // 'about:blank': parsed the way a browser parses it
73
+ isAbsoluteUrl('/\\evil.com'); // true: browsers send it to evil.com, so it is not a safe relative redirect
74
+ ```
75
+
76
+ Every regex runs in linear time, validators reject look-alike hosts and invisible characters, and helpers whose cost grows with input size document it. See the [security policy](./SECURITY.md).
77
+
78
+ ## Async that cleans up after itself
79
+
80
+ ```ts
81
+ import { createQueue, createRateLimiter, mapWithConcurrency, memoizeAsync } from 'tinkit/async';
82
+
83
+ const getUser = memoizeAsync(fetchUser, { ttl: 60_000 }); // concurrent calls share one request; failures are never cached
84
+ const limiter = createRateLimiter({ limit: 10, interval: 1_000 }); // sliding window; calls queue instead of being dropped
85
+ const queue = createQueue({ concurrency: 4 }); // priorities, pause/resume, onIdle()
86
+
87
+ await mapWithConcurrency(urls, fetchPage, { concurrency: 8, signal }); // abort stops scheduling and rejects with signal.reason
88
+ ```
89
+
90
+ No leaked timers or listeners, no unhandled rejections: each of these is a test.
91
+
92
+ More examples, including dates, text and decorators, are in [Recipes](./docs/RECIPES.md).
93
+
94
+ ## Modules
95
+
96
+ | Module | Highlights |
97
+ | ---------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------ |
98
+ | [`arrays`](./docs/API.md#arrays) | `orderBy`, `groupBy`, `partition`, `chunk`, top-N `takeFirstBy`, `sampleSize`, combinatorics, Myers `diffSequences`, set algebra (`…By`/`…With`) |
99
+ | [`objects`](./docs/API.md#objects) | `deepClone`, `deepMerge`/`defaults`, `isEqual`/`isMatch`, immutable `updatePath`, `toCamelCaseKeys`, `stableStringify`/`hash`, `diff` |
100
+ | [`guards`](./docs/API.md#guards) | 50+ predicates, `isShape`/`isUnion`/`isLazy`/`refine` schemas, `isMatching`, `explain`/`ensure`, `toStandardSchema`, `assertNever` |
101
+ | [`strings`](./docs/API.md#strings) | every case style, grapheme-aware `padStart`/`trimChars`/`truncate`, `toSlug`, `dedent`, `wordWrap`, `levenshtein`, `mask`, `escapeHtml` |
102
+ | [`math`](./docs/API.md#math) | precise `sum`/`round`/`ceil`/`floor`, `quantile`, `variance`, `clamp`/`lerp`, `formatBytes`/`parseBytes`, Miller–Rabin `isPrime` |
103
+ | [`functions`](./docs/API.md#functions) | `debounce`/`throttle` with `cancel`/`flush`, `memoize`, exhaustive `match`, `curry`, `pipe`, `allPass`/`anyPass`, `attempt` |
104
+ | [`async`](./docs/API.md#async) | `retry`, `withTimeout`, priority `createQueue`, `createRateLimiter`, `memoizeAsync`, abortable `mapWithConcurrency`, `pollUntil` |
105
+ | [`date`](./docs/API.md#date) | DST-safe `addDuration`/`addMonths`, `intervalToDuration`, strict `parseDate`/`formatDate`, ISO weeks, `toISOStringLocal`, `eachOfInterval` |
106
+ | [`format`](./docs/API.md#format) | deterministic, cached Intl formatting: `formatCurrency`, `formatCompact`, `formatPercent`, `formatList`, `formatOrdinal`, … |
107
+ | [`validate`](./docs/API.md#validate) | ReDoS-safe predicates: `isEmail`, `isUrl` (look-alike safe), `isUuid`, `isIP`, `isSemver`, Luhn, base64, and safe `parseJson(text, guard)` |
108
+ | [`color`](./docs/API.md#color) | CSS `parseColor` (hex, `rgb()`, `hsl()`), `mix`, `lighten`/`darken`, WCAG `contrastRatio`, `getReadableTextColor`, `meetsContrast` |
109
+ | [`search`](./docs/API.md#search) | `fuzzyMatch`/`fuzzySearch` with optimal scoring and highlight ranges, `highlight` segments for rendering matches |
110
+ | [`easing`](./docs/API.md#easing) | 31 tree-shakeable easings, CSS-accurate `cubicBezier`/`steps`, analytic `spring`, `interpolate` |
111
+ | [`url`](./docs/API.md#url) | `buildQueryString`/`parseQueryString` (pollution-safe), `isSafeUrl`/`sanitizeUrl`, `withQuery`, `joinUrl`, `withBase`, slash helpers |
112
+ | [`iterables`](./docs/API.md#iterables) | lazy `map`/`filter`/`take`/`chunk`/`zip` over any (async) iterable, bounded `mapConcurrent` with backpressure |
113
+ | [`cache`](./docs/API.md#cache) | O(1) `createLRUCache` with TTL and eviction reasons, stable binary-heap `createPriorityQueue` |
114
+ | [`emitter`](./docs/API.md#emitter) | typed `createEmitter` with wildcard listeners, `once`, `waitFor` (timeout/abort) and error isolation |
115
+ | [`store`](./docs/API.md#store) | `createStore` for `useSyncExternalStore`, with equality-gated updates and cached `select()` stores |
116
+ | [`random`](./docs/API.md#random) | seeded `createRandom` (cross-platform deterministic), secure `secureRandom`/`randomId`/`randomUUID`/`randomBytes`, `weightedRandom` |
117
+ | [`decorators`](./docs/API.md#decorators) | `@memoize`/`@once` (per instance), `@bound`, `@debounced`, `@throttled`, `@retryable`, `@timeout`, `@readonly`, `@deprecated` |
118
+
119
+ ## Numbers
120
+
121
+ - **Size:** a median of 450 B per import, 2.7 kB at most, 57 kB gzipped for all 20 modules. The cost of every export is in [docs/SIZES.md](./docs/SIZES.md).
122
+ - **Speed:** benchmarked at 10, 1k and 100k items against the popular libraries with the same helpers. Results are in [docs/PERFORMANCE.md](./docs/PERFORMANCE.md) (`yarn bench`).
123
+
124
+ ## How it's tested
125
+
126
+ 3,600+ tests, run in four time zones before every push, with 100% statement and branch coverage. They include [fast-check](https://fast-check.dev) property tests for the laws behind each helper, every JSDoc example (1,400+ assertions) run against the build, and [mutation testing](./docs/mutation/README.md).
127
+
128
+ ## Docs
129
+
130
+ [API reference](./docs/API.md) · [Recipes](./docs/RECIPES.md) · [Import sizes](./docs/SIZES.md) · [Performance](./docs/PERFORMANCE.md) · [Migrating from lodash](./docs/MIGRATING-FROM-LODASH.md) · [Security](./SECURITY.md) · [Changelog](./CHANGELOG.md) · [Contributing](./CONTRIBUTING.md) · [llms.txt](./llms.txt)
131
+
132
+ Every export also carries its full JSDoc, with examples, in your editor.
133
+
134
+ ## License
135
+
136
+ [MIT](./LICENSE) © Emilio Dominguez