@pistonite/pure 0.28.0 → 0.29.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 (96) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +23 -4
  3. package/dist/_dts_/src/log/index.d.ts +37 -0
  4. package/dist/_dts_/src/log/index.d.ts.map +1 -0
  5. package/dist/_dts_/src/log/logger.d.ts +27 -0
  6. package/dist/_dts_/src/log/logger.d.ts.map +1 -0
  7. package/dist/_dts_/src/memory/cell.d.ts +25 -0
  8. package/dist/_dts_/src/memory/cell.d.ts.map +1 -0
  9. package/dist/_dts_/src/memory/emp.d.ts +87 -0
  10. package/dist/_dts_/src/memory/emp.d.ts.map +1 -0
  11. package/dist/_dts_/src/memory/idgen.d.ts +18 -0
  12. package/dist/_dts_/src/memory/idgen.d.ts.map +1 -0
  13. package/dist/_dts_/src/memory/index.d.ts +10 -0
  14. package/dist/_dts_/src/memory/index.d.ts.map +1 -0
  15. package/dist/_dts_/src/memory/persist.d.ts +38 -0
  16. package/dist/_dts_/src/memory/persist.d.ts.map +1 -0
  17. package/dist/_dts_/src/result/index.d.ts +191 -0
  18. package/dist/_dts_/src/result/index.d.ts.map +1 -0
  19. package/dist/_dts_/src/sync/RwLock.d.ts +30 -0
  20. package/dist/_dts_/src/sync/RwLock.d.ts.map +1 -0
  21. package/dist/_dts_/src/sync/batch.d.ts +112 -0
  22. package/dist/_dts_/src/sync/batch.d.ts.map +1 -0
  23. package/dist/_dts_/src/sync/capture.d.ts +11 -0
  24. package/dist/_dts_/src/sync/capture.d.ts.map +1 -0
  25. package/dist/_dts_/src/sync/debounce.d.ts +105 -0
  26. package/dist/_dts_/src/sync/debounce.d.ts.map +1 -0
  27. package/dist/_dts_/src/sync/index.d.ts +15 -0
  28. package/dist/_dts_/src/sync/index.d.ts.map +1 -0
  29. package/dist/_dts_/src/sync/latest.d.ts +86 -0
  30. package/dist/_dts_/src/sync/latest.d.ts.map +1 -0
  31. package/dist/_dts_/src/sync/mutex.d.ts +14 -0
  32. package/dist/_dts_/src/sync/mutex.d.ts.map +1 -0
  33. package/dist/_dts_/src/sync/once.d.ts +84 -0
  34. package/dist/_dts_/src/sync/once.d.ts.map +1 -0
  35. package/dist/_dts_/src/sync/serial.d.ts +162 -0
  36. package/dist/_dts_/src/sync/serial.d.ts.map +1 -0
  37. package/dist/_dts_/src/sync/util.d.ts +19 -0
  38. package/dist/_dts_/src/sync/util.d.ts.map +1 -0
  39. package/dist/log/index.js +57 -0
  40. package/dist/log/index.js.map +1 -0
  41. package/dist/memory/index.js +92 -0
  42. package/dist/memory/index.js.map +1 -0
  43. package/dist/result/index.js +29 -0
  44. package/dist/result/index.js.map +1 -0
  45. package/dist/sync/index.js +252 -0
  46. package/dist/sync/index.js.map +1 -0
  47. package/package.json +22 -13
  48. package/src/env.d.ts +1 -0
  49. package/src/log/index.ts +36 -11
  50. package/src/log/logger.ts +93 -115
  51. package/src/memory/cell.ts +21 -11
  52. package/src/memory/emp.ts +34 -23
  53. package/src/memory/idgen.test.ts +1 -1
  54. package/src/memory/index.ts +1 -4
  55. package/src/memory/persist.ts +9 -12
  56. package/src/result/index.ts +12 -4
  57. package/src/sync/batch.test.ts +1 -1
  58. package/src/sync/batch.ts +12 -17
  59. package/src/sync/capture.ts +2 -0
  60. package/src/sync/debounce.test.ts +1 -1
  61. package/src/sync/debounce.ts +12 -15
  62. package/src/sync/index.ts +2 -3
  63. package/src/sync/latest.test.ts +1 -1
  64. package/src/sync/latest.ts +19 -16
  65. package/src/sync/once.test.ts +1 -1
  66. package/src/sync/once.ts +13 -8
  67. package/src/sync/serial.test.ts +1 -1
  68. package/src/sync/serial.ts +14 -12
  69. package/src/sync/util.ts +2 -2
  70. package/src/fs/FsError.ts +0 -55
  71. package/src/fs/FsFile.ts +0 -67
  72. package/src/fs/FsFileImpl.ts +0 -219
  73. package/src/fs/FsFileMgr.ts +0 -29
  74. package/src/fs/FsFileStandalone.ts +0 -21
  75. package/src/fs/FsFileStandaloneImplFileAPI.ts +0 -54
  76. package/src/fs/FsFileStandaloneImplHandleAPI.ts +0 -147
  77. package/src/fs/FsFileSystem.ts +0 -71
  78. package/src/fs/FsFileSystemInternal.ts +0 -30
  79. package/src/fs/FsImplEntryAPI.ts +0 -149
  80. package/src/fs/FsImplFileAPI.ts +0 -116
  81. package/src/fs/FsImplHandleAPI.ts +0 -199
  82. package/src/fs/FsOpen.ts +0 -271
  83. package/src/fs/FsOpenFile.ts +0 -256
  84. package/src/fs/FsPath.ts +0 -137
  85. package/src/fs/FsSave.ts +0 -216
  86. package/src/fs/FsSupportStatus.ts +0 -87
  87. package/src/fs/index.ts +0 -123
  88. package/src/log/internal.ts +0 -14
  89. package/src/memory/async_erc.ts +0 -186
  90. package/src/memory/erc.test.ts +0 -258
  91. package/src/memory/erc.ts +0 -320
  92. package/src/pref/dark.ts +0 -151
  93. package/src/pref/device.ts +0 -118
  94. package/src/pref/index.ts +0 -13
  95. package/src/pref/inject_style.ts +0 -22
  96. package/src/pref/locale.ts +0 -296
package/LICENSE CHANGED
@@ -1,6 +1,6 @@
1
1
  MIT License
2
2
 
3
- Copyright (c) 2024-2025 Michael
3
+ Copyright (c) 2024-2026 Michael
4
4
 
5
5
  Permission is hereby granted, free of charge, to any person obtaining a copy
6
6
  of this software and associated documentation files (the "Software"), to deal
package/README.md CHANGED
@@ -1,8 +1,27 @@
1
1
  # pure
2
2
 
3
- Pure TypeScript utility library for browsers.
3
+ Pure TypeScript utility libraries for my projects
4
4
 
5
- These are meant to be only used by my projects so they
6
- are not stable by any means. However, feel free to use or reference them.
5
+ ## Documentation
7
6
 
8
- See [GitHub](https://github.com/Pistonite/pure) for more information.
7
+ https://pure.pistonite.dev
8
+
9
+ ## Setup
10
+
11
+ Install the package from NPM
12
+
13
+ ```bash
14
+ npm install @pistonite/pure
15
+ ```
16
+
17
+ For React hooks
18
+
19
+ ```bash
20
+ npm install @pistonite/pure-react
21
+ ```
22
+
23
+ Import the things you need
24
+
25
+ ```typescript
26
+ import type { Result } from "@pistonite/pure/result";
27
+ ```
@@ -0,0 +1,37 @@
1
+ /**
2
+ * Client side log util
3
+ *
4
+ * This is rather simple logging stuff with the primary focus
5
+ * being easy-to-debug, instead of optimized for bundle size or performance.
6
+ *
7
+ * Because this library doesn't have global states, there is no "global" logger
8
+ * or any global logger settings. Instead, each library or component of the
9
+ * application can create their own instance of the logger, which stores
10
+ * settings like the name, color and level of that logger.
11
+ *
12
+ * ```typescript
13
+ * import { logger } from "@pistonite/pure";
14
+ *
15
+ * export const myLogger = logger("my-library", {
16
+ * color: "#ff8800", // any CSS color (note that styling only works in browser)
17
+ * });
18
+ * ```
19
+ *
20
+ * It's recommended that a library exports the logger object
21
+ * so downstream app can modify the logging level if needed for debugging.
22
+ * ```typescript
23
+ * import { myLogger } from "my-library";
24
+ *
25
+ * myLogger.setLevel("debug");
26
+ * ```
27
+ *
28
+ * Due to the nature of JS, all logging calls, even when turned off, will incur
29
+ * some small runtime overhead. While we could remove debug calls
30
+ * for release build, that's currently not done (and it would require
31
+ * bundler to inline the call to remove the call completely, which might
32
+ * not be the case)
33
+ *
34
+ * @module
35
+ */
36
+ export { type LogLevelStr, type LoggerConstructor, type Logger, logger } from "./logger.ts";
37
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../src/log/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAkCG;AACH,OAAO,EAAE,KAAK,WAAW,EAAE,KAAK,iBAAiB,EAAE,KAAK,MAAM,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC"}
@@ -0,0 +1,27 @@
1
+ export type LogLevelStr = "off" | "default" | "info" | "debug";
2
+ /** Args for constructing a logger */
3
+ export interface LoggerConstructor {
4
+ /** CSS Color for the logger, default is 'gray' */
5
+ color?: string;
6
+ /**
7
+ * Logging level, default is "default".
8
+ * The level can still be changed later with setLevel
9
+ */
10
+ level?: LogLevelStr;
11
+ }
12
+ /** The logger type */
13
+ export interface Logger {
14
+ /** Set the level of the logger */
15
+ setLevel(level: LogLevelStr): void;
16
+ /** Log a debug message */
17
+ debug(obj: unknown): void;
18
+ /** Log an info message */
19
+ info(obj: unknown): void;
20
+ /** Log a warning message */
21
+ warn(obj: unknown): void;
22
+ /** Log an error message */
23
+ error(obj: unknown): void;
24
+ }
25
+ /** Create a logger creator. Use the factory methods to finish making the logger */
26
+ export declare const logger: (name: string, args: LoggerConstructor) => Logger;
27
+ //# sourceMappingURL=logger.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"logger.d.ts","sourceRoot":"","sources":["../../../../src/log/logger.ts"],"names":[],"mappings":"AAYA,MAAM,MAAM,WAAW,GAAG,KAAK,GAAG,SAAS,GAAG,MAAM,GAAG,OAAO,CAAC;AAS/D,qCAAqC;AACrC,MAAM,WAAW,iBAAiB;IAC9B,kDAAkD;IAClD,KAAK,CAAC,EAAE,MAAM,CAAC;IACf;;;OAGG;IACH,KAAK,CAAC,EAAE,WAAW,CAAC;CACvB;AAED,sBAAsB;AACtB,MAAM,WAAW,MAAM;IACnB,kCAAkC;IAClC,QAAQ,CAAC,KAAK,EAAE,WAAW,GAAG,IAAI,CAAC;IACnC,0BAA0B;IAC1B,KAAK,CAAC,GAAG,EAAE,OAAO,GAAG,IAAI,CAAC;IAC1B,0BAA0B;IAC1B,IAAI,CAAC,GAAG,EAAE,OAAO,GAAG,IAAI,CAAC;IACzB,4BAA4B;IAC5B,IAAI,CAAC,GAAG,EAAE,OAAO,GAAG,IAAI,CAAC;IACzB,2BAA2B;IAC3B,KAAK,CAAC,GAAG,EAAE,OAAO,GAAG,IAAI,CAAC;CAC7B;AAED,mFAAmF;AACnF,eAAO,MAAM,MAAM,GAAI,MAAM,MAAM,EAAE,MAAM,iBAAiB,KAAG,MAS9D,CAAC"}
@@ -0,0 +1,25 @@
1
+ /** Create a {@link Cell} */
2
+ export declare const cell: <T>(args: CellConstructor<T>) => Cell<T>;
3
+ /** Args for constructing a cell */
4
+ export interface CellConstructor<T> {
5
+ /** Initial value */
6
+ initial: T;
7
+ }
8
+ /**
9
+ * A light weight storage wrapper around a value
10
+ * that can be subscribed to for changes
11
+ *
12
+ * Created via `cell()`
13
+ *
14
+ * ```typescript
15
+ * import { cell } from "@pistonite/pure/memory";
16
+ *
17
+ * const myCell = cell(true);
18
+ * ```
19
+ */
20
+ export interface Cell<T> {
21
+ get(): T;
22
+ set(value: T): void;
23
+ subscribe(callback: (value: T) => void, notifyImmediately?: boolean): () => void;
24
+ }
25
+ //# sourceMappingURL=cell.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cell.d.ts","sourceRoot":"","sources":["../../../../src/memory/cell.ts"],"names":[],"mappings":"AAAA,4BAA4B;AAC5B,eAAO,MAAM,IAAI,GAAI,CAAC,EAAE,MAAM,eAAe,CAAC,CAAC,CAAC,KAAG,IAAI,CAAC,CAAC,CAExD,CAAC;AAEF,mCAAmC;AACnC,MAAM,WAAW,eAAe,CAAC,CAAC;IAC9B,oBAAoB;IACpB,OAAO,EAAE,CAAC,CAAC;CACd;AAED;;;;;;;;;;;GAWG;AACH,MAAM,WAAW,IAAI,CAAC,CAAC;IACnB,GAAG,IAAI,CAAC,CAAC;IACT,GAAG,CAAC,KAAK,EAAE,CAAC,GAAG,IAAI,CAAC;IACpB,SAAS,CAAC,QAAQ,EAAE,CAAC,KAAK,EAAE,CAAC,KAAK,IAAI,EAAE,iBAAiB,CAAC,EAAE,OAAO,GAAG,MAAM,IAAI,CAAC;CACpF"}
@@ -0,0 +1,87 @@
1
+ /**
2
+ * A non-null, **E**ngine-**m**anaged **P**ointer
3
+ *
4
+ * This uses the ECMA FinalizationRegistry, to free the resource,
5
+ * once this object is garbage-collected.
6
+ *
7
+ * The free function may be async.
8
+ *
9
+ * ## Use case
10
+ * When JS interoperates with a system language like C/C++ or Rust,
11
+ * it is often needed to transfer objects into JS context. If the object
12
+ * is big, copy-transfer could be expensive, so the more ideal solution
13
+ * is to transfer a "handle", or a pointer, to JS, and leaving the actual
14
+ * object in the native memory. Then, JS code and pass the pointer to external
15
+ * code to use or extract data from the object when needed.
16
+ *
17
+ * This approach is just like passing raw pointers in C, which means it is
18
+ * extremely succeptible to memory corruption bugs like double-free or
19
+ * use-after-free. Unlike C++ or Rust, JS also doesn't have destructors
20
+ * that run when an object leaves the scope (proposal for the `using` keyword exists,
21
+ * but you can actually double-free the object with `using`).
22
+ *
23
+ * C-style manual memory management might be sufficient for simple bindings,
24
+ * but for more complex scenarios, automatic memory management is needed,
25
+ * by tying the free call to the GC of a JS object.
26
+ *
27
+ * ## Recommended practice
28
+ * 1. The external code should transfer the ownership of the object
29
+ * to JS when passing it to JS. JS will then put the handle into an Emp
30
+ * to be automatically managed. This means the external code should now
31
+ * never free the object, and let JS free it instead.
32
+ * 2. The inner value of the Emp must only be used for calling
33
+ * external code, and the Emp must be kept alive for all runtimes, including
34
+ * those with heavy optimization that may reclaim the Emp during the call,
35
+ * if it's not referenced afterwards. See {@link scopedCapture}.
36
+ * The inner value must not dangle around outside of the Emp that owns it.
37
+ *
38
+ * ## Pointer Size
39
+ * In 32-bit context like WASM32, the inner value can be a `number`.
40
+ * In 64-bit context, `number` might be fine for some systems, but `bigint`
41
+ * is recommended.
42
+ *
43
+ * ## Usage
44
+ *
45
+ * ```typescript
46
+ * // First create a marker to distinguish between different Emp types for TypeScript.
47
+ * // This is not used at runtime
48
+ * const MyNativeType = Symbol("MyNativeType");
49
+ * export type MyNativeType = typeof MyNativeType;
50
+ *
51
+ * // Then use makeEmpType to create a factory function
52
+ * const makeMyNativeTypeEmp = makeEmpType({
53
+ * marker: MyNativeType,
54
+ * free: (ptr) => freeMyNativeType(ptr),
55
+ * });
56
+ *
57
+ * // Now acquire ownership of an object from external native code
58
+ * // and assign it to an Emp
59
+ * const myObjRawPtr = allocMyNativeType();
60
+ * const myObj = makeMyNativeTypeEmp(myObjRawPtr);
61
+ *
62
+ * // when myObj is GC'ed, it will be freed by calling freeMyNativeType
63
+ * ```
64
+ */
65
+ export interface Emp<T, TRepr> {
66
+ /** The type marker for T. This only marks the type for TypeScript and does not exist at runtime */
67
+ readonly __phantom: T;
68
+ /** The underlying pointer value */
69
+ readonly value: TRepr;
70
+ }
71
+ /** Args for constructing a Emp type */
72
+ export interface EmpConstructor<T, TRepr> {
73
+ /**
74
+ * The marker for the Emp type, used to distinguish between multiple Emp types
75
+ * in TypeScript
76
+ */
77
+ marker?: T;
78
+ /**
79
+ * Function to free the underlying object. Called when this Emp is garbage-collected
80
+ */
81
+ free: (ptr: TRepr) => void | Promise<void>;
82
+ }
83
+ /**
84
+ * Create a factory function for an Emp type. See {@link Emp}
85
+ */
86
+ export declare const makeEmpType: <T, TRepr>(args: EmpConstructor<T, TRepr>) => ((ptr: TRepr) => Emp<T, TRepr>);
87
+ //# sourceMappingURL=emp.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"emp.d.ts","sourceRoot":"","sources":["../../../../src/memory/emp.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+DG;AACH,MAAM,WAAW,GAAG,CAAC,CAAC,EAAE,KAAK;IACzB,mGAAmG;IACnG,QAAQ,CAAC,SAAS,EAAE,CAAC,CAAC;IACtB,mCAAmC;IACnC,QAAQ,CAAC,KAAK,EAAE,KAAK,CAAC;CACzB;AAED,uCAAuC;AACvC,MAAM,WAAW,cAAc,CAAC,CAAC,EAAE,KAAK;IACpC;;;OAGG;IACH,MAAM,CAAC,EAAE,CAAC,CAAC;IAEX;;OAEG;IACH,IAAI,EAAE,CAAC,GAAG,EAAE,KAAK,KAAK,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;CAC9C;AAED;;GAEG;AACH,eAAO,MAAM,WAAW,GAAI,CAAC,EAAE,KAAK,EAChC,MAAM,cAAc,CAAC,CAAC,EAAE,KAAK,CAAC,KAC/B,CAAC,CAAC,GAAG,EAAE,KAAK,KAAK,GAAG,CAAC,CAAC,EAAE,KAAK,CAAC,CAQhC,CAAC"}
@@ -0,0 +1,18 @@
1
+ /**
2
+ * Return an id generator that will generate ids in order
3
+ * from 1 to n, wrapping around to 1 when it's n
4
+ */
5
+ export declare const safeidgen: (n: number) => (() => number);
6
+ /**
7
+ * Return an id generator that returns bigint,
8
+ * starting from 1n, and will always return a new bigint
9
+ */
10
+ export declare const bidgen: () => (() => bigint);
11
+ /**
12
+ * Returns an id generator that returns number staring from 1
13
+ * and always increasing. The number could become inaccurate
14
+ * (not integer) when exceeding Number.MAX_SAFE_INTEGER (which
15
+ * is 2^53 - 1
16
+ */
17
+ export declare const idgen: () => (() => number);
18
+ //# sourceMappingURL=idgen.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"idgen.d.ts","sourceRoot":"","sources":["../../../../src/memory/idgen.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,eAAO,MAAM,SAAS,GAAI,GAAG,MAAM,KAAG,CAAC,MAAM,MAAM,CASlD,CAAC;AAEF;;;GAGG;AACH,eAAO,MAAM,MAAM,QAAO,CAAC,MAAM,MAAM,CAMtC,CAAC;AAEF;;;;;GAKG;AACH,eAAO,MAAM,KAAK,QAAO,CAAC,MAAM,MAAM,CAMrC,CAAC"}
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Memory utilities
3
+ *
4
+ * @module
5
+ */
6
+ export { cell, type CellConstructor, type Cell } from "./cell.ts";
7
+ export { persist, type PersistConstructor, type Persist } from "./persist.ts";
8
+ export * from "./emp.ts";
9
+ export * from "./idgen.ts";
10
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../src/memory/index.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,EAAE,IAAI,EAAE,KAAK,eAAe,EAAE,KAAK,IAAI,EAAE,MAAM,WAAW,CAAC;AAClE,OAAO,EAAE,OAAO,EAAE,KAAK,kBAAkB,EAAE,KAAK,OAAO,EAAE,MAAM,cAAc,CAAC;AAC9E,cAAc,UAAU,CAAC;AACzB,cAAc,YAAY,CAAC"}
@@ -0,0 +1,38 @@
1
+ import { type Cell, type CellConstructor } from "./cell.ts";
2
+ /**
3
+ * Create a cell that persists its value to a web storage
4
+ */
5
+ export declare function persist<T>(args: PersistConstructor<T>): Persist<T>;
6
+ /** Args for creating a persisted cell */
7
+ export interface PersistConstructor<T> extends CellConstructor<T> {
8
+ /** The web storage to use */
9
+ storage: Storage;
10
+ /** The key to use in the storage */
11
+ key: string;
12
+ /**
13
+ * Serialize the value to store in the storage
14
+ *
15
+ * By default, it will use `JSON.stringify`
16
+ */
17
+ serialize?(value: T): string;
18
+ /**
19
+ * Deserialize the value from the storage
20
+ *
21
+ * By default, it will use `JSON.parse` wrapped with try-catch
22
+ */
23
+ deserialize?(value: string): T | null;
24
+ }
25
+ /** A cell that also persists its value */
26
+ export interface Persist<T> extends Cell<T> {
27
+ /**
28
+ * Load the value initially, and notify all the current subscribers
29
+ *
30
+ * Optionally, you can pass an initial value to override the current value
31
+ */
32
+ init(initial?: T): T;
33
+ /** Clear the value from the storage */
34
+ clear(): void;
35
+ /** Clear the value and disable the persistence */
36
+ disable(): void;
37
+ }
38
+ //# sourceMappingURL=persist.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"persist.d.ts","sourceRoot":"","sources":["../../../../src/memory/persist.ts"],"names":[],"mappings":"AAAA,OAAO,EAAQ,KAAK,IAAI,EAAE,KAAK,eAAe,EAAE,MAAM,WAAW,CAAC;AAElE;;GAEG;AACH,wBAAgB,OAAO,CAAC,CAAC,EAAE,IAAI,EAAE,kBAAkB,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC,CAYlE;AAED,yCAAyC;AACzC,MAAM,WAAW,kBAAkB,CAAC,CAAC,CAAE,SAAQ,eAAe,CAAC,CAAC,CAAC;IAC7D,6BAA6B;IAC7B,OAAO,EAAE,OAAO,CAAC;IAEjB,oCAAoC;IACpC,GAAG,EAAE,MAAM,CAAC;IAEZ;;;;OAIG;IACH,SAAS,CAAC,CAAC,KAAK,EAAE,CAAC,GAAG,MAAM,CAAC;IAC7B;;;;OAIG;IACH,WAAW,CAAC,CAAC,KAAK,EAAE,MAAM,GAAG,CAAC,GAAG,IAAI,CAAC;CACzC;AAED,0CAA0C;AAC1C,MAAM,WAAW,OAAO,CAAC,CAAC,CAAE,SAAQ,IAAI,CAAC,CAAC,CAAC;IACvC;;;;OAIG;IACH,IAAI,CAAC,OAAO,CAAC,EAAE,CAAC,GAAG,CAAC,CAAC;IACrB,uCAAuC;IACvC,KAAK,IAAI,IAAI,CAAC;IACd,kDAAkD;IAClD,OAAO,IAAI,IAAI,CAAC;CACnB"}
@@ -0,0 +1,191 @@
1
+ /**
2
+ * Rust-like `Result<T, E>` type and error handling utils
3
+ *
4
+ * **I once had a fancy error object with TypeScript magic that tries
5
+ * to reduce allocation while maintaining Result-safety. It turns out
6
+ * that was slower than allocating plain objects for every return, because
7
+ * of how V8 optimizes things.**
8
+ *
9
+ * Don't even use `isErr()` helper functions to abstract. They are slower than
10
+ * directly property access in my testing.
11
+ *
12
+ * ## Function that can fail
13
+ * Instead of having functions `throw`, make it `return` instead.
14
+ * ```typescript
15
+ * // Instead of
16
+ * function doSomethingCanFail() {
17
+ * if (Math.random() < 0.5) {
18
+ * return 42;
19
+ * }
20
+ * throw "oops";
21
+ * }
22
+ * // Do this
23
+ * import type { Result } from "pure/result";
24
+ *
25
+ * function doSomethingCanFail(): Result<number, string> {
26
+ * if (Math.random() < 0.5) {
27
+ * return { val: 42 };
28
+ * }
29
+ * return { err: "oops" };
30
+ * }
31
+ * ```
32
+ * This is similar to Rust:
33
+ * ```rust
34
+ * fn do_something_can_fail() -> Result<u32, String> {
35
+ * if ... {
36
+ * return Ok(42);
37
+ * }
38
+ *
39
+ * Err("oops".to_string())
40
+ * }
41
+ * ```
42
+ *
43
+ * ## Calling function that can fail
44
+ * The recommended pattern is
45
+ * ```typescript
46
+ * const x = doTheCall(); // x is Result<T, E>;
47
+ * if (x.err) {
48
+ * // x.err is E, handle it
49
+ * return ...
50
+ * }
51
+ * // x.val is T
52
+ * // ...
53
+ * ```
54
+ * If your `E` type covers falsy values that are valid, use `"err" in x` instead of `x.err`.
55
+ * A well-known case is `Result<T, unknown>`. `if(r.err)` cannot narrow the else case to `Ok`,
56
+ * but `if("err" in r)` can.
57
+ *
58
+ * A full example:
59
+ * ```typescript
60
+ * function getParam(name: string): Result<number, Error> {
61
+ * if (name === "a") {
62
+ * return { val: 13 };
63
+ * }
64
+ * if (name === "b") {
65
+ * return { val: 42 };
66
+ * }
67
+ * return { err: new Error("bad name") };
68
+ * }
69
+ *
70
+ * function multiplyFormat(
71
+ * name1: string,
72
+ * name2: string,
73
+ * prefix: string
74
+ * ): Result<string, Error> {
75
+ * const v1 = getParam(name1);
76
+ * if (v1.err) {
77
+ * console.error(v1.err);
78
+ * return v1;
79
+ * }
80
+ * const v2 = getParam(name1);
81
+ * if (v2.err) {
82
+ * console.error(v2.err);
83
+ * return v2;
84
+ * }
85
+ *
86
+ * const formatted = `${prefix}${v1.val * v2.val}`;
87
+ * return { val: formatted };
88
+ * }
89
+ * ```
90
+ *
91
+ * ## Interop with throwing functions
92
+ * This library also has `tryCatch` to interop with throwing functions,
93
+ * and `tryAsync` for async functions.
94
+ *
95
+ * ```typescript
96
+ * import { tryCatch, tryAsync } from "pure/result";
97
+ *
98
+ * // synchronous
99
+ * const result1: Result<MyData, unknown> = tryCatch(() => JSON.parse<MyData>(...));
100
+ * // or you can specify the error type:
101
+ * const result2 = tryCatch<MyData, SyntaxError>(() => JSON.parse(...));
102
+ *
103
+ * // asynchronous
104
+ * async function doSomethingCanFail() {
105
+ * if (Math.random() < 0.5) {
106
+ * return 42;
107
+ * }
108
+ * throw "oops";
109
+ * }
110
+ * const result = await tryAsync<number, string>(() => doStuff);
111
+ * ```
112
+ *
113
+ * ## Returning void
114
+ * Use `Void<E>` as the return type if the function returns `void` on success
115
+ * ```typescript
116
+ * const x = doSomethingThatVoidsOnSuccess();
117
+ * if (x.err) {
118
+ * return x;
119
+ * }
120
+ * // type of x is Record<string, never>, i.e. empty object
121
+ * ```
122
+ *
123
+ * ## Why is there no `match`/`map`/`mapErr`, etc?
124
+ *
125
+ * If you are thinking this is a great idea:
126
+ * ```typescript
127
+ * const result = foo(bar);
128
+ * match(result,
129
+ * (okValue) => {
130
+ * // handle ok case
131
+ * },
132
+ * (errValue) => {
133
+ * // handle err case
134
+ * },
135
+ * );
136
+ * ```
137
+ * The vanilla `if` doesn't allocate the closures, and has less code, and you can
138
+ * control the flow properly inside the blocks with `return`/`break`/`continue`
139
+ * ```typescript
140
+ * const result = foo(bar);
141
+ * if (result.err) {
142
+ * // handle err case
143
+ * } else {
144
+ * // handle ok case
145
+ * }
146
+ * ```
147
+ *
148
+ * As for the other utility functions from Rust's Result type, they really only benefit
149
+ * because you can early return with `?` AND those abstractions are zero-cost in Rust.
150
+ * Neither is true in JavaScript.
151
+ *
152
+ * You can also easily write them yourself if you really want to.
153
+ *
154
+ * @module
155
+ */
156
+ /**
157
+ * A value that either a success (Ok) or an error (Err)
158
+ *
159
+ * Construct a success with { val: ... } and an error with { err: ... }
160
+ */
161
+ export type Result<T, E> = Ok<T> | Err<E>;
162
+ /** A success value */
163
+ export interface Ok<T> {
164
+ val: T;
165
+ err?: never;
166
+ }
167
+ /** An error value */
168
+ export interface Err<E> {
169
+ err: E;
170
+ val?: never;
171
+ }
172
+ /**
173
+ * A value that is either `void` or an error
174
+ *
175
+ * Construct success with `{}` and an error with `{ err: ... }`
176
+ */
177
+ export type Void<E> = {
178
+ val?: never;
179
+ err?: never;
180
+ } | {
181
+ err: E;
182
+ };
183
+ /** A value that is a success `void` */
184
+ export type VoidOk = Record<string, never>;
185
+ /** Wrap a function with try-catch and return a Result. */
186
+ export declare function tryCatch<T, E = Error>(fn: () => T): Result<T, E>;
187
+ /** Wrap an async function with try-catch and return a Promise<Result>. */
188
+ export declare function tryAsync<T, E = Error>(fn: () => Promise<T>): Promise<Result<T, E>>;
189
+ /** Try best effort converting an error to a string */
190
+ export declare function errstr(e: unknown, recursing?: boolean): string;
191
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../src/result/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA0JG;AAEH;;;;GAIG;AACH,MAAM,MAAM,MAAM,CAAC,CAAC,EAAE,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC,GAAG,GAAG,CAAC,CAAC,CAAC,CAAC;AAK1C,sBAAsB;AACtB,MAAM,WAAW,EAAE,CAAC,CAAC;IACjB,GAAG,EAAE,CAAC,CAAC;IACP,GAAG,CAAC,EAAE,KAAK,CAAC;CACf;AACD,qBAAqB;AACrB,MAAM,WAAW,GAAG,CAAC,CAAC;IAClB,GAAG,EAAE,CAAC,CAAC;IACP,GAAG,CAAC,EAAE,KAAK,CAAC;CACf;AAED;;;;GAIG;AACH,MAAM,MAAM,IAAI,CAAC,CAAC,IAAI;IAAE,GAAG,CAAC,EAAE,KAAK,CAAC;IAAC,GAAG,CAAC,EAAE,KAAK,CAAA;CAAE,GAAG;IAAE,GAAG,EAAE,CAAC,CAAA;CAAE,CAAC;AAChE,uCAAuC;AACvC,MAAM,MAAM,MAAM,GAAG,MAAM,CAAC,MAAM,EAAE,KAAK,CAAC,CAAC;AAE3C,0DAA0D;AAC1D,wBAAgB,QAAQ,CAAC,CAAC,EAAE,CAAC,GAAG,KAAK,EAAE,EAAE,EAAE,MAAM,CAAC,GAAG,MAAM,CAAC,CAAC,EAAE,CAAC,CAAC,CAMhE;AAED,0EAA0E;AAC1E,wBAAsB,QAAQ,CAAC,CAAC,EAAE,CAAC,GAAG,KAAK,EAAE,EAAE,EAAE,MAAM,OAAO,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAMxF;AAED,sDAAsD;AACtD,wBAAgB,MAAM,CAAC,CAAC,EAAE,OAAO,EAAE,SAAS,CAAC,EAAE,OAAO,GAAG,MAAM,CAkC9D"}
@@ -0,0 +1,30 @@
1
+ /**
2
+ * Ensure you have exclusive access in concurrent code
3
+ *
4
+ * Only guaranteed if no one else has reference to the inner object
5
+ *
6
+ * It can take a second type parameter to specify interface with write methods
7
+ *
8
+ * @deprecated unstable API
9
+ */
10
+ export declare class RwLock<TRead, TWrite extends TRead = TRead> {
11
+ /**
12
+ * This is public so inner object can be accessed directly
13
+ * ONLY SAFE in sync context
14
+ */
15
+ inner: TWrite;
16
+ private readers;
17
+ private isWriting;
18
+ private readWaiters;
19
+ private writeWaiters;
20
+ constructor(t: TWrite);
21
+ /** Acquire a read (shared) lock and call fn with the value. Release the lock when fn returns or throws. */
22
+ scopedRead<R>(fn: (t: TRead) => Promise<R>): Promise<R>;
23
+ /**
24
+ * Acquire a write (exclusive) lock and call fn with the value. Release the lock when fn returns or throws.
25
+ *
26
+ * fn takes a setter function as second parameter, which you can use to update the value like `x = set(newX)`
27
+ */
28
+ scopedWrite<R>(fn: (t: TWrite, setter: (t: TWrite) => TWrite) => Promise<R>): Promise<R>;
29
+ }
30
+ //# sourceMappingURL=RwLock.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"RwLock.d.ts","sourceRoot":"","sources":["../../../../src/sync/RwLock.ts"],"names":[],"mappings":"AAEA;;;;;;;;GAQG;AACH,qBAAa,MAAM,CAAC,KAAK,EAAE,MAAM,SAAS,KAAK,GAAG,KAAK;IACnD;;;OAGG;IACI,KAAK,EAAE,MAAM,CAAC;IAErB,OAAO,CAAC,OAAO,CAAa;IAC5B,OAAO,CAAC,SAAS,CAAkB;IACnC,OAAO,CAAC,WAAW,CAAkC;IACrD,OAAO,CAAC,YAAY,CAAkC;gBAE1C,CAAC,EAAE,MAAM;IAIrB,2GAA2G;IAC9F,UAAU,CAAC,CAAC,EAAE,EAAE,EAAE,CAAC,CAAC,EAAE,KAAK,KAAK,OAAO,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC;IAkCpE;;;;OAIG;IACU,WAAW,CAAC,CAAC,EACtB,EAAE,EAAE,CAAC,CAAC,EAAE,MAAM,EAAE,MAAM,EAAE,CAAC,CAAC,EAAE,MAAM,KAAK,MAAM,KAAK,OAAO,CAAC,CAAC,CAAC,GAC7D,OAAO,CAAC,CAAC,CAAC;CA+BhB"}
@@ -0,0 +1,112 @@
1
+ import { type AnyFn, type AwaitRet } from "./util.ts";
2
+ /** Factory for batched function. See {@link BatchConstructor} for usage. */
3
+ export declare function batch<TFn extends AnyFn>(args: BatchConstructor<TFn>): (...args: Parameters<TFn>) => Promise<AwaitRet<TFn>>;
4
+ /**
5
+ * Options to construct a `batch` function
6
+ *
7
+ * A batch function is an async event wrapper that allows multiple calls in an interval
8
+ * to be batched together, and only call the underlying function once.
9
+ *
10
+ * Optionally, the output can be unbatched to match the inputs.
11
+ *
12
+ * ## Example
13
+ * The API is a lot like `debounce`, but with an additional `batch` function
14
+ * and an optional `unbatch` function.
15
+ * ```typescript
16
+ * import { batch } from "@pistonite/pure/sync";
17
+ *
18
+ * const execute = batch({
19
+ * fn: (n: number) => {
20
+ * console.log(n);
21
+ * },
22
+ * interval: 100,
23
+ * // batch receives all the inputs and returns a single input
24
+ * // here we just sums the inputs
25
+ * batch: (args: [number][]): [number] => [args.reduce((acc, [n]) => acc + n, 0)],
26
+ * });
27
+ *
28
+ * await execute(1); // logs 1 immediately
29
+ * const p1 = execute(2); // will be resolved at 100ms
30
+ * const p2 = execute(3); // will be resolved at 100ms
31
+ * await Promise.all([p1, p2]); // logs 5 after 100ms
32
+ * ```
33
+ *
34
+ * ## Unbatching
35
+ * The optional `unbatch` function allows the output to be unbatched,
36
+ * so the promises are resolved as if the underlying function is called
37
+ * directly.
38
+ *
39
+ * Note that unbatching is usually slow and not required.
40
+ *
41
+ * ```typescript
42
+ * import { batch } from "@pistonite/pure/sync";
43
+ *
44
+ * type Message = {
45
+ * id: number;
46
+ * payload: string;
47
+ * }
48
+ *
49
+ * const execute = batch({
50
+ * fn: (messages: Message[]): Message[] => {
51
+ * console.log(messages.length);
52
+ * return messages.map((m) => ({
53
+ * id: m.id,
54
+ * payload: m.payload + "out",
55
+ * }));
56
+ * },
57
+ * batch: (args: [Message[]][]): [Message[]] => {
58
+ * const out: Message[] = [];
59
+ * for (const [messages] of args) {
60
+ * out.push(...messages);
61
+ * }
62
+ * return [out];
63
+ * },
64
+ * unbatch: (inputs: [Message[]][], output: Message[]): Message[][] => {
65
+ * // not efficient, but just for demonstration
66
+ * const idToOutput = new Map();
67
+ * for (const o of output) {
68
+ * idToOutput.set(o.id, o);
69
+ * }
70
+ * return inputs.map(([messages]) => {
71
+ * return messages.map(({id}) => {
72
+ * return idToOutput.get(m.id)!;
73
+ * });
74
+ * });
75
+ * },
76
+ * interval: 100,
77
+ * });
78
+ *
79
+ * const r1 = await execute([{id: 1, payload: "a"}]); // logs 1 immediately
80
+ * // r1 is [ {id: 1, payload: "aout"} ]
81
+ *
82
+ * const p1 = execute([{id: 2, payload: "b"}]); // will be resolved at 100ms
83
+ * const p2 = execute([{id: 3, payload: "c"}]); // will be resolved at 100ms
84
+ *
85
+ * const r2 = await p2; // 2 is logged
86
+ * // r1 is [ {id: 2, payload: "bout"} ]
87
+ * const r3 = await p3; // nothing is logged, as it's already resolved
88
+ * // r2 is [ {id: 3, payload: "cout"} ]
89
+ *
90
+ * ```
91
+ *
92
+ */
93
+ export interface BatchConstructor<TFn extends AnyFn> {
94
+ /** Function to be wrapped */
95
+ fn: TFn;
96
+ /** Function to batch the inputs across multiple calls */
97
+ batch: (args: Parameters<TFn>[]) => Parameters<TFn>;
98
+ /**
99
+ * If provided, unbatch the output according to the inputs,
100
+ * so each call receives its own output.
101
+ *
102
+ * By default, each input will receive the same output from the batched call
103
+ */
104
+ unbatch?: (inputs: Parameters<TFn>[], output: AwaitRet<TFn>) => AwaitRet<TFn>[];
105
+ /**
106
+ * Interval between each batched call
107
+ */
108
+ interval: number;
109
+ /** See `debounce` for more information */
110
+ disregardExecutionTime?: boolean;
111
+ }
112
+ //# sourceMappingURL=batch.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"batch.d.ts","sourceRoot":"","sources":["../../../../src/sync/batch.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,KAAK,EAAmC,KAAK,QAAQ,EAAE,MAAM,WAAW,CAAC;AAEvF,4EAA4E;AAC5E,wBAAgB,KAAK,CAAC,GAAG,SAAS,KAAK,EAAE,IAAI,EAAE,gBAAgB,CAAC,GAAG,CAAC,IAGxD,GAAG,MAAM,UAAU,CAAC,GAAG,CAAC,4BACnC;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAwFG;AACH,MAAM,WAAW,gBAAgB,CAAC,GAAG,SAAS,KAAK;IAC/C,6BAA6B;IAC7B,EAAE,EAAE,GAAG,CAAC;IACR,yDAAyD;IACzD,KAAK,EAAE,CAAC,IAAI,EAAE,UAAU,CAAC,GAAG,CAAC,EAAE,KAAK,UAAU,CAAC,GAAG,CAAC,CAAC;IAEpD;;;;;OAKG;IACH,OAAO,CAAC,EAAE,CAAC,MAAM,EAAE,UAAU,CAAC,GAAG,CAAC,EAAE,EAAE,MAAM,EAAE,QAAQ,CAAC,GAAG,CAAC,KAAK,QAAQ,CAAC,GAAG,CAAC,EAAE,CAAC;IAEhF;;OAEG;IACH,QAAQ,EAAE,MAAM,CAAC;IAEjB,0CAA0C;IAC1C,sBAAsB,CAAC,EAAE,OAAO,CAAC;CACpC"}