@e280/stz 0.0.0-8 → 0.1.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 (148) hide show
  1. package/README.md +275 -24
  2. package/package.json +13 -9
  3. package/s/coalesce.ts +1 -0
  4. package/s/constructor.ts +15 -0
  5. package/s/data/base-x.ts +170 -0
  6. package/s/data/base58.ts +15 -5
  7. package/s/data/base64.ts +15 -6
  8. package/s/data/base64url.ts +15 -6
  9. package/s/data/bytename/bytename.test.ts +12 -12
  10. package/s/data/bytename/bytename.ts +13 -6
  11. package/s/data/bytename/index.ts +1 -1
  12. package/s/data/bytename/thumbprint.test.ts +53 -0
  13. package/s/data/bytename/thumbprint.ts +112 -0
  14. package/s/data/bytes.ts +2 -2
  15. package/s/data/data.test.ts +98 -0
  16. package/s/data/hex.ts +15 -5
  17. package/s/data/txt.ts +14 -4
  18. package/s/deadline.ts +5 -6
  19. package/s/{defer-promise.ts → defer.ts} +2 -2
  20. package/s/drill.ts +2 -4
  21. package/s/ev.ts +20 -0
  22. package/s/id-counter.ts +9 -0
  23. package/s/index.ts +12 -1
  24. package/s/is.ts +10 -4
  25. package/s/map-g.ts +9 -10
  26. package/s/nap.ts +1 -0
  27. package/s/once.ts +14 -0
  28. package/s/pipe.ts +8 -8
  29. package/s/pubsub.ts +24 -6
  30. package/s/queue/queue.test.ts +67 -0
  31. package/s/queue/queue.ts +21 -0
  32. package/s/repeat.ts +25 -0
  33. package/s/scope.ts +108 -0
  34. package/s/templating.ts +22 -0
  35. package/s/tests.test.ts +14 -10
  36. package/s/time.ts +22 -0
  37. package/x/coalesce.d.ts +1 -0
  38. package/x/coalesce.js +1 -0
  39. package/x/coalesce.js.map +1 -1
  40. package/x/constructor.d.ts +3 -0
  41. package/x/constructor.js +4 -0
  42. package/x/constructor.js.map +1 -0
  43. package/x/data/base-x.d.ts +47 -0
  44. package/x/data/base-x.js +147 -0
  45. package/x/data/base-x.js.map +1 -0
  46. package/x/data/base58.d.ts +5 -1
  47. package/x/data/base58.js +13 -5
  48. package/x/data/base58.js.map +1 -1
  49. package/x/data/base64.d.ts +7 -3
  50. package/x/data/base64.js +13 -5
  51. package/x/data/base64.js.map +1 -1
  52. package/x/data/base64url.d.ts +5 -1
  53. package/x/data/base64url.js +13 -5
  54. package/x/data/base64url.js.map +1 -1
  55. package/x/data/bytename/bytename.d.ts +9 -3
  56. package/x/data/bytename/bytename.js +13 -6
  57. package/x/data/bytename/bytename.js.map +1 -1
  58. package/x/data/bytename/bytename.test.js +12 -12
  59. package/x/data/bytename/bytename.test.js.map +1 -1
  60. package/x/data/bytename/index.d.ts +1 -1
  61. package/x/data/bytename/index.js +1 -1
  62. package/x/data/bytename/index.js.map +1 -1
  63. package/x/data/bytename/thumbprint.d.ts +36 -0
  64. package/x/data/bytename/thumbprint.js +79 -0
  65. package/x/data/bytename/thumbprint.js.map +1 -0
  66. package/x/data/bytename/{badge.test.d.ts → thumbprint.test.d.ts} +2 -2
  67. package/x/data/bytename/thumbprint.test.js +45 -0
  68. package/x/data/bytename/thumbprint.test.js.map +1 -0
  69. package/x/data/bytes.d.ts +2 -2
  70. package/x/data/bytes.js +2 -2
  71. package/x/data/bytes.js.map +1 -1
  72. package/x/data/data.test.d.ts +69 -0
  73. package/x/data/data.test.js +77 -0
  74. package/x/data/data.test.js.map +1 -0
  75. package/x/data/hex.d.ts +8 -4
  76. package/x/data/hex.js +13 -5
  77. package/x/data/hex.js.map +1 -1
  78. package/x/data/txt.d.ts +6 -2
  79. package/x/data/txt.js +12 -4
  80. package/x/data/txt.js.map +1 -1
  81. package/x/deadline.d.ts +2 -2
  82. package/x/deadline.js +4 -4
  83. package/x/deadline.js.map +1 -1
  84. package/x/{defer-promise.d.ts → defer.d.ts} +2 -2
  85. package/x/{defer-promise.js → defer.js} +2 -2
  86. package/x/defer.js.map +1 -0
  87. package/x/drill.d.ts +1 -3
  88. package/x/drill.js +2 -4
  89. package/x/drill.js.map +1 -1
  90. package/x/ev.d.ts +6 -0
  91. package/x/ev.js +10 -0
  92. package/x/ev.js.map +1 -0
  93. package/x/id-counter.d.ts +5 -0
  94. package/x/id-counter.js +10 -0
  95. package/x/id-counter.js.map +1 -0
  96. package/x/index.d.ts +11 -1
  97. package/x/index.js +11 -1
  98. package/x/index.js.map +1 -1
  99. package/x/is.d.ts +6 -4
  100. package/x/is.js +6 -4
  101. package/x/is.js.map +1 -1
  102. package/x/map-g.d.ts +3 -3
  103. package/x/map-g.js +9 -8
  104. package/x/map-g.js.map +1 -1
  105. package/x/nap.d.ts +1 -0
  106. package/x/nap.js +1 -0
  107. package/x/nap.js.map +1 -1
  108. package/x/once.d.ts +1 -0
  109. package/x/once.js +12 -0
  110. package/x/once.js.map +1 -0
  111. package/x/pipe.d.ts +4 -3
  112. package/x/pipe.js +6 -5
  113. package/x/pipe.js.map +1 -1
  114. package/x/pubsub.d.ts +12 -1
  115. package/x/pubsub.js +7 -5
  116. package/x/pubsub.js.map +1 -1
  117. package/x/queue/queue.d.ts +4 -0
  118. package/x/queue/queue.js +14 -0
  119. package/x/queue/queue.js.map +1 -0
  120. package/x/queue/queue.test.d.ts +8 -0
  121. package/x/queue/queue.test.js +57 -0
  122. package/x/queue/queue.test.js.map +1 -0
  123. package/x/repeat.d.ts +5 -0
  124. package/x/repeat.js +23 -0
  125. package/x/repeat.js.map +1 -0
  126. package/x/scope.d.ts +37 -0
  127. package/x/scope.js +82 -0
  128. package/x/scope.js.map +1 -0
  129. package/x/templating.d.ts +6 -0
  130. package/x/templating.js +11 -0
  131. package/x/templating.js.map +1 -0
  132. package/x/tests.test.js +14 -10
  133. package/x/tests.test.js.map +1 -1
  134. package/x/time.d.ts +18 -0
  135. package/x/time.js +19 -0
  136. package/x/time.js.map +1 -0
  137. package/s/data/anka.ts +0 -66
  138. package/s/data/bytename/badge.test.ts +0 -53
  139. package/s/data/bytename/badge.ts +0 -81
  140. package/x/data/anka.d.ts +0 -5
  141. package/x/data/anka.js +0 -53
  142. package/x/data/anka.js.map +0 -1
  143. package/x/data/bytename/badge.d.ts +0 -27
  144. package/x/data/bytename/badge.js +0 -57
  145. package/x/data/bytename/badge.js.map +0 -1
  146. package/x/data/bytename/badge.test.js +0 -45
  147. package/x/data/bytename/badge.test.js.map +0 -1
  148. package/x/defer-promise.js.map +0 -1
package/s/pipe.ts CHANGED
@@ -1,20 +1,20 @@
1
1
 
2
- export type PipeFun<I, O> = (input: I) => O
2
+ export type Piper<I, O> = (input: I) => O
3
3
 
4
- export class Pipe<I> {
5
-
6
- static with<I>(input: I) {
7
- return new this(input)
8
- }
4
+ export function pipe<I>(input: I) {
5
+ return new Pipe(input)
6
+ }
9
7
 
8
+ export class Pipe<I> {
10
9
  #input: I
10
+ static with = pipe
11
11
 
12
12
  constructor(input: I) {
13
13
  this.#input = input
14
14
  }
15
15
 
16
- to<O>(fun: PipeFun<I, O>) {
17
- return new Pipe(fun(this.#input))
16
+ to<O>(fn: Piper<I, O>) {
17
+ return new Pipe(fn(this.#input))
18
18
  }
19
19
 
20
20
  done() {
package/s/pubsub.ts CHANGED
@@ -1,19 +1,35 @@
1
1
 
2
- import {deferPromise} from "./defer-promise.js"
2
+ import {defer} from "./defer.js"
3
3
 
4
4
  export type Listener<A extends any[]> = (...a: A) => (void | Promise<void>)
5
5
 
6
6
  export interface Xub<A extends any[] = []> {
7
+
8
+ /** publish to all subscribed listeners. */
7
9
  pub(...a: A): Promise<void>
10
+
11
+ /** subscribe a listener function. */
8
12
  sub(fn: Listener<A>): () => void
9
- once(): Promise<A>
13
+
14
+ /**
15
+ * subscribe a listener function.
16
+ * @alias sub
17
+ */
18
+ on(fn: Listener<A>): () => void
19
+
20
+ /** wait for the next published value */
21
+ next(): Promise<A>
22
+
23
+ /** wipe all listeners attached to this. */
10
24
  clear(): void
11
25
  }
12
26
 
27
+ /** subscriber fn that can be published to. */
13
28
  export interface Sub<A extends any[] = []> extends Xub<A> {
14
29
  (fn: Listener<A>): () => void
15
30
  }
16
31
 
32
+ /** publisher fn that can be published to. */
17
33
  export interface Pub<A extends any[] = []> extends Xub<A> {
18
34
  (...a: A): Promise<void>
19
35
  }
@@ -30,8 +46,8 @@ export function xub<A extends any[] = []>() {
30
46
  await Promise.all([...set].map(fn => fn(...a)))
31
47
  }
32
48
 
33
- async function once() {
34
- const {promise, resolve} = deferPromise<A>()
49
+ async function next() {
50
+ const {promise, resolve} = defer<A>()
35
51
  const unsubscribe = sub((...a) => {
36
52
  resolve(a)
37
53
  unsubscribe()
@@ -45,12 +61,14 @@ export function xub<A extends any[] = []>() {
45
61
 
46
62
  sub.pub = pub
47
63
  sub.sub = sub
48
- sub.once = once
64
+ sub.on = sub
65
+ sub.next = next
49
66
  sub.clear = clear
50
67
 
51
68
  pub.pub = pub
52
69
  pub.sub = sub
53
- pub.once = once
70
+ pub.on = sub
71
+ pub.next = next
54
72
  pub.clear = clear
55
73
 
56
74
  return [pub, sub] as [Pub<A>, Sub<A>]
@@ -0,0 +1,67 @@
1
+
2
+ import {Science, expect} from "@e280/science"
3
+
4
+ import {nap} from "../nap.js"
5
+ import {queue} from "./queue.js"
6
+
7
+ export default Science.suite({
8
+ "job runs": Science.test(async() => {
9
+ let concurrent = 0
10
+ const job = queue(async() => {
11
+ concurrent++
12
+ await nap(100)
13
+ concurrent--
14
+ })
15
+ const promise1 = job()
16
+ await nap(50)
17
+ expect(concurrent).is(1)
18
+ await promise1
19
+ expect(concurrent).is(0)
20
+ }),
21
+
22
+ "sequencing is enforced": Science.test(async() => {
23
+ let concurrent = 0
24
+ const job = queue(async() => {
25
+ concurrent++
26
+ await nap(100)
27
+ concurrent--
28
+ })
29
+
30
+ const promise1 = job()
31
+ const promise2 = job()
32
+
33
+ await nap(50)
34
+ expect(concurrent).is(1)
35
+
36
+ await promise1
37
+ await nap(50)
38
+ expect(concurrent).is(1)
39
+
40
+ await promise2
41
+ expect(concurrent).is(0)
42
+ }),
43
+
44
+ "params and return values seem to work": Science.test(async() => {
45
+ const add = queue(async(a: number, b: number) => {
46
+ await nap(100)
47
+ return a + b
48
+ })
49
+ const promise1 = add(1, 2)
50
+ const promise2 = add(10, 20)
51
+ expect(await promise1).is(3)
52
+ expect(await promise2).is(30)
53
+ }),
54
+
55
+ "first job throws, second job unaffected": Science.test(async() => {
56
+ let run = 0
57
+ const job = queue(async() => {
58
+ run++
59
+ await nap(100)
60
+ if (run === 1)
61
+ throw new Error("first job failed")
62
+ })
63
+ expect(async() => job()).throwsAsync()
64
+ expect(async() => job()).not.throwsAsync()
65
+ }),
66
+ })
67
+
@@ -0,0 +1,21 @@
1
+
2
+ /**
3
+ * create a job queue that ensures the given fn is always called in sequence (not concurrently).
4
+ */
5
+ export function queue<Args extends any[], Result>(
6
+ fn: (...args: Args) => Promise<Result>
7
+ ): (...args: Args) => Promise<Result> {
8
+
9
+ let last: Promise<any> = Promise.resolve()
10
+
11
+ return (...args: Args): Promise<Result> => {
12
+ const job = () => fn(...args)
13
+ const current = last.then(job)
14
+
15
+ // prevent unhandled rejection breaking the chain
16
+ last = current.catch(() => {})
17
+
18
+ return current
19
+ }
20
+ }
21
+
package/s/repeat.ts ADDED
@@ -0,0 +1,25 @@
1
+
2
+ /**
3
+ * repeat the given async function over and over.
4
+ * - consider using `nap` in your fn to create a delay
5
+ */
6
+ export function repeat(fn: (stop: () => void) => Promise<void>) {
7
+ let timeout: any
8
+ let stopped = false
9
+
10
+ const stop = () => {
11
+ stopped = true
12
+ clearTimeout(timeout)
13
+ }
14
+
15
+ const tick = async() => {
16
+ if (stopped) return
17
+ await fn(stop)
18
+ if (stopped) return
19
+ timeout = setTimeout(tick, 0)
20
+ }
21
+
22
+ tick()
23
+ return stop
24
+ }
25
+
package/s/scope.ts ADDED
@@ -0,0 +1,108 @@
1
+
2
+ import {Constructor} from "./constructor.js"
3
+
4
+ export type Scoped<Item> = [item: Item, dispose: () => void]
5
+ export type Disposable = {dispose(): void}
6
+
7
+ export function scoped<Item>(item: Item, dispose: () => void) {
8
+ return [item, dispose] as Scoped<Item>
9
+ }
10
+
11
+ /**
12
+ * a trashcan you can fill with garbage, then call `scope.dispose()` to dump it all
13
+ * - `add/stow/scoped` methods are for dealing with disposer fns
14
+ * - `keep` methods are for dealing with disposable objects (with a dispose method)
15
+ * - `sub` for creating nested sub-scopes
16
+ */
17
+ export class Scope implements Disposable {
18
+ #disposers: (() => void)[] = []
19
+
20
+ /** add disposer fn */
21
+ add(dispose: () => void) {
22
+ this.#disposers.push(dispose)
23
+ return this
24
+ }
25
+
26
+ /** add disposer, return item */
27
+ stow<Item>(item: Item, dispose: () => void) {
28
+ this.add(dispose)
29
+ return item
30
+ }
31
+
32
+ /** add scoped disposer, return item */
33
+ scoped<Item>([item, dispose]: Scoped<Item>) {
34
+ this.add(dispose)
35
+ return item
36
+ }
37
+
38
+ /** add and return a disposable object */
39
+ keep<D extends Disposable>(disposable: D) {
40
+ this.add(() => disposable.dispose())
41
+ return disposable
42
+ }
43
+
44
+ /** wrap a fn, auto-add returned disposers */
45
+ scopedFn<Params extends any[], Item>(
46
+ fn: (...params: Params) => Scoped<Item>
47
+ ) {
48
+ return (...a: Params) => {
49
+ const scoped = fn(...a)
50
+ return this.scoped(scoped)
51
+ }
52
+ }
53
+
54
+ /** wrap an async fn, auto-add returned disposers */
55
+ scopedFnAsync<Params extends any[], Item>(
56
+ fn: (...params: Params) => Promise<Scoped<Item>>
57
+ ) {
58
+ return async(...a: Params) => {
59
+ const scoped = await fn(...a)
60
+ return this.scoped(scoped)
61
+ }
62
+ }
63
+
64
+ /** wrap a fn, auto-add returned disposables */
65
+ keepFn<Params extends any[], D extends Disposable>(
66
+ fn: (...params: Params) => D
67
+ ) {
68
+ return (...a: Params) => {
69
+ const disposable = fn(...a)
70
+ return this.keep(disposable)
71
+ }
72
+ }
73
+
74
+ /** wrap an async fn, auto-add returned disposables */
75
+ keepFnAsync<Params extends any[], D extends Disposable>(
76
+ fn: (...params: Params) => Promise<D>
77
+ ) {
78
+ return async(...a: Params) => {
79
+ const disposable = await fn(...a)
80
+ return this.keep(disposable)
81
+ }
82
+ }
83
+
84
+ /** wrap a constructor, auto-add returned disposables */
85
+ keepConstructor<C extends Constructor<Disposable>>(Ctor: C) {
86
+ const scope = this
87
+ return class extends Ctor {
88
+ constructor(...p: any[]) {
89
+ super(...p)
90
+ scope.keep(this)
91
+ }
92
+ } as C
93
+ }
94
+
95
+ /** create a subscope, child gets disposed when parent does */
96
+ sub() {
97
+ const subscope = new Scope()
98
+ return this.stow(subscope, () => subscope.dispose())
99
+ }
100
+
101
+ /** dispose everything in this scope, in reverse order */
102
+ dispose() {
103
+ for (const fn of this.#disposers.reverse())
104
+ fn()
105
+ this.#disposers = []
106
+ }
107
+ }
108
+
@@ -0,0 +1,22 @@
1
+
2
+ export type TemplateParts = {
3
+ strings: TemplateStringsArray
4
+ values: any[]
5
+ }
6
+
7
+ export function templateParts(
8
+ strings: TemplateStringsArray,
9
+ ...values: any[]
10
+ ): TemplateParts {
11
+
12
+ return {strings, values}
13
+ }
14
+
15
+ export function templateString(strings: TemplateStringsArray, ...values: any[]) {
16
+ const lastIndex = strings.length - 1
17
+ return strings
18
+ .slice(0, lastIndex)
19
+ .reduce((a, b, c) => a + b + values[c], "")
20
+ + strings[lastIndex]
21
+ }
22
+
package/s/tests.test.ts CHANGED
@@ -1,17 +1,21 @@
1
1
 
2
2
  import {Science} from "@e280/science"
3
3
 
4
- import cloneTest from "./clone/clone.test.js"
5
- import badgeTest from "./data/bytename/badge.test.js"
6
- import debounceTest from "./debounce/debounce.test.js"
7
- import bytenameTest from "./data/bytename/bytename.test.js"
8
- import deepTest from "./deep/deep.test.js"
4
+ import clone from "./clone/clone.test.js"
5
+ import thumbprint from "./data/bytename/thumbprint.test.js"
6
+ import debounce from "./debounce/debounce.test.js"
7
+ import bytename from "./data/bytename/bytename.test.js"
8
+ import deep from "./deep/deep.test.js"
9
+ import data from "./data/data.test.js"
10
+ import queue from "./queue/queue.test.js"
9
11
 
10
12
  await Science.run({
11
- clone: cloneTest,
12
- bytename: bytenameTest,
13
- badge: badgeTest,
14
- debounce: debounceTest,
15
- deep: deepTest,
13
+ clone,
14
+ bytename,
15
+ thumbprint,
16
+ debounce,
17
+ deep,
18
+ data,
19
+ queue,
16
20
  })
17
21
 
package/s/time.ts ADDED
@@ -0,0 +1,22 @@
1
+
2
+ export const Time = {
3
+ seconds: (n: number) => (n * 1000),
4
+ minutes: (n: number) => (n * Time.seconds(60)),
5
+ hours: (n: number) => (n * Time.minutes(60)),
6
+ days: (n: number) => (n * Time.hours(24)),
7
+
8
+ future: {
9
+ seconds: (n: number) => (Date.now() + Time.seconds(n)),
10
+ minutes: (n: number) => (Date.now() + Time.minutes(n)),
11
+ hours: (n: number) => (Date.now() + Time.hours(n)),
12
+ days: (n: number) => (Date.now() + Time.days(n)),
13
+ },
14
+
15
+ past: {
16
+ seconds: (n: number) => (Date.now() - Time.seconds(n)),
17
+ minutes: (n: number) => (Date.now() - Time.minutes(n)),
18
+ hours: (n: number) => (Date.now() - Time.hours(n)),
19
+ days: (n: number) => (Date.now() - Time.days(n)),
20
+ },
21
+ }
22
+
package/x/coalesce.d.ts CHANGED
@@ -1 +1,2 @@
1
+ /** return a single function that calls all the provided functions */
1
2
  export declare function coalesce<A extends any[] = []>(...fns: ((...a: A) => void)[]): (...a: A) => void;
package/x/coalesce.js CHANGED
@@ -1,3 +1,4 @@
1
+ /** return a single function that calls all the provided functions */
1
2
  export function coalesce(...fns) {
2
3
  return (...a) => fns.forEach(fn => fn(...a));
3
4
  }
package/x/coalesce.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"coalesce.js","sourceRoot":"","sources":["../s/coalesce.ts"],"names":[],"mappings":"AACA,MAAM,UAAU,QAAQ,CAAuB,GAAG,GAA0B;IAC3E,OAAO,CAAC,GAAG,CAAI,EAAE,EAAE,CAAC,GAAG,CAAC,OAAO,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,CAAA;AAChD,CAAC"}
1
+ {"version":3,"file":"coalesce.js","sourceRoot":"","sources":["../s/coalesce.ts"],"names":[],"mappings":"AACA,qEAAqE;AACrE,MAAM,UAAU,QAAQ,CAAuB,GAAG,GAA0B;IAC3E,OAAO,CAAC,GAAG,CAAI,EAAE,EAAE,CAAC,GAAG,CAAC,OAAO,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,CAAA;AAChD,CAAC"}
@@ -0,0 +1,3 @@
1
+ export type Constructor<T extends {} = {}> = new (...args: any[]) => T;
2
+ export type Ctor<Params extends any[] = any[], Instance extends {} = {}> = new (...params: Params) => Instance;
3
+ export declare function denew<Params extends any[] = any[], Instance extends {} = {}>(C: Ctor<Params, Instance>): (...p: Params) => Instance;
@@ -0,0 +1,4 @@
1
+ export function denew(C) {
2
+ return (...p) => new C(...p);
3
+ }
4
+ //# sourceMappingURL=constructor.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"constructor.js","sourceRoot":"","sources":["../s/constructor.ts"],"names":[],"mappings":"AAQA,MAAM,UAAU,KAAK,CAGlB,CAAyB;IAC3B,OAAO,CAAC,GAAG,CAAS,EAAE,EAAE,CAAC,IAAI,CAAC,CAAC,GAAG,CAAC,CAAC,CAAA;AACrC,CAAC"}
@@ -0,0 +1,47 @@
1
+ export type Lexicon = {
2
+ characters: string;
3
+ negativePrefix?: string;
4
+ padding?: {
5
+ character: string;
6
+ size: number;
7
+ };
8
+ };
9
+ export declare class BaseX {
10
+ lexicon: Lexicon;
11
+ static lexicons: Readonly<{
12
+ base2: {
13
+ characters: string;
14
+ };
15
+ hex: {
16
+ characters: string;
17
+ };
18
+ base36: {
19
+ characters: string;
20
+ };
21
+ base58: {
22
+ characters: string;
23
+ };
24
+ base62: {
25
+ characters: string;
26
+ };
27
+ base64url: {
28
+ negativePrefix: string;
29
+ characters: string;
30
+ };
31
+ base64: {
32
+ characters: string;
33
+ padding: {
34
+ character: string;
35
+ size: number;
36
+ };
37
+ };
38
+ }>;
39
+ private lookup;
40
+ private negativePrefix;
41
+ constructor(lexicon: Lexicon);
42
+ toBytes(s: string): Uint8Array;
43
+ fromBytes(bytes: Uint8Array): string;
44
+ toInteger(s: string): number;
45
+ fromInteger(n: number): string;
46
+ random(count?: number): string;
47
+ }
@@ -0,0 +1,147 @@
1
+ import { Bytes } from "./bytes.js";
2
+ export class BaseX {
3
+ lexicon;
4
+ static lexicons = Object.freeze({
5
+ base2: { characters: "01" },
6
+ hex: { characters: "0123456789abcdef" },
7
+ base36: { characters: "0123456789abcdefghijklmnopqrstuvwxyz" },
8
+ base58: { characters: "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" },
9
+ base62: { characters: "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" },
10
+ base64url: {
11
+ negativePrefix: "~",
12
+ characters: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",
13
+ },
14
+ base64: {
15
+ characters: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",
16
+ padding: { character: "=", size: 4 },
17
+ },
18
+ });
19
+ lookup;
20
+ negativePrefix;
21
+ constructor(lexicon) {
22
+ this.lexicon = lexicon;
23
+ this.lookup = Object.fromEntries([...lexicon.characters].map((char, i) => [char, i]));
24
+ this.negativePrefix = lexicon.negativePrefix ?? "-";
25
+ }
26
+ toBytes(s) {
27
+ const bitsPerChar = Math.log2(this.lexicon.characters.length);
28
+ if (Number.isInteger(bitsPerChar)) {
29
+ // Bitstream mode (for power-of-2 lexicons)
30
+ let bitBuffer = 0;
31
+ let bitCount = 0;
32
+ const output = [];
33
+ for (const char of s) {
34
+ if (char === this.lexicon.padding?.character)
35
+ continue;
36
+ const val = this.lookup[char];
37
+ if (val === undefined)
38
+ throw new Error(`Invalid character: ${char}`);
39
+ bitBuffer = (bitBuffer << bitsPerChar) | val;
40
+ bitCount += bitsPerChar;
41
+ while (bitCount >= 8) {
42
+ bitCount -= 8;
43
+ output.push((bitBuffer >> bitCount) & 0xFF);
44
+ }
45
+ }
46
+ return new Uint8Array(output);
47
+ }
48
+ // Radix mode fallback
49
+ let num = 0n;
50
+ const base = BigInt(this.lexicon.characters.length);
51
+ let negative = false;
52
+ if (s.startsWith(this.negativePrefix)) {
53
+ s = s.slice(this.negativePrefix.length);
54
+ negative = true;
55
+ }
56
+ for (const char of s) {
57
+ const val = this.lookup[char];
58
+ if (val === undefined)
59
+ throw new Error(`Invalid character: ${char}`);
60
+ num = num * base + BigInt(val);
61
+ }
62
+ const out = [];
63
+ while (num > 0n) {
64
+ out.unshift(Number(num % 256n));
65
+ num = num / 256n;
66
+ }
67
+ return new Uint8Array(out);
68
+ }
69
+ fromBytes(bytes) {
70
+ const bitsPerChar = Math.log2(this.lexicon.characters.length);
71
+ if (Number.isInteger(bitsPerChar)) {
72
+ // Bitstream mode (for power-of-2 lexicons)
73
+ let bitBuffer = 0;
74
+ let bitCount = 0;
75
+ let out = "";
76
+ for (const byte of bytes) {
77
+ bitBuffer = (bitBuffer << 8) | byte;
78
+ bitCount += 8;
79
+ while (bitCount >= bitsPerChar) {
80
+ bitCount -= bitsPerChar;
81
+ const index = (bitBuffer >> bitCount) & ((1 << bitsPerChar) - 1);
82
+ out += this.lexicon.characters[index];
83
+ }
84
+ }
85
+ // 🩹 flush remaining bits
86
+ if (bitCount > 0) {
87
+ const index = (bitBuffer << (bitsPerChar - bitCount)) & ((1 << bitsPerChar) - 1);
88
+ out += this.lexicon.characters[index];
89
+ }
90
+ // Add padding if applicable
91
+ if (this.lexicon.padding) {
92
+ while (out.length % this.lexicon.padding.size !== 0)
93
+ out += this.lexicon.padding.character;
94
+ }
95
+ return out;
96
+ }
97
+ // Radix mode fallback
98
+ let num = 0n;
99
+ for (const byte of bytes)
100
+ num = (num << 8n) + BigInt(byte);
101
+ if (num === 0n)
102
+ return this.lexicon.characters[0];
103
+ const base = BigInt(this.lexicon.characters.length);
104
+ let out = "";
105
+ while (num > 0n) {
106
+ out = this.lexicon.characters[Number(num % base)] + out;
107
+ num = num / base;
108
+ }
109
+ return out;
110
+ }
111
+ toInteger(s) {
112
+ if (!s)
113
+ return 0;
114
+ let n = 0n;
115
+ let negative = false;
116
+ const base = BigInt(this.lexicon.characters.length);
117
+ if (s.startsWith(this.negativePrefix)) {
118
+ s = s.slice(this.negativePrefix.length);
119
+ negative = true;
120
+ }
121
+ for (const char of s) {
122
+ const value = this.lookup[char];
123
+ if (value === undefined)
124
+ throw new Error(`Invalid character: ${char}`);
125
+ n = n * base + BigInt(value);
126
+ }
127
+ return Number(negative ? -n : n);
128
+ }
129
+ fromInteger(n) {
130
+ n = Math.floor(n);
131
+ const negative = n < 0;
132
+ let num = BigInt(negative ? -n : n);
133
+ if (num === 0n)
134
+ return this.lexicon.characters[0];
135
+ const base = BigInt(this.lexicon.characters.length);
136
+ let out = "";
137
+ while (num > 0n) {
138
+ out = this.lexicon.characters[Number(num % base)] + out;
139
+ num = num / base;
140
+ }
141
+ return negative ? `${this.negativePrefix}${out}` : out;
142
+ }
143
+ random(count = 32) {
144
+ return this.fromBytes(Bytes.random(count));
145
+ }
146
+ }
147
+ //# sourceMappingURL=base-x.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"base-x.js","sourceRoot":"","sources":["../../s/data/base-x.ts"],"names":[],"mappings":"AACA,OAAO,EAAC,KAAK,EAAC,MAAM,YAAY,CAAA;AAWhC,MAAM,OAAO,KAAK;IAoBE;IAnBnB,MAAM,CAAC,QAAQ,GAAG,MAAM,CAAC,MAAM,CAAC;QAC/B,KAAK,EAAE,EAAC,UAAU,EAAE,IAAI,EAAC;QACzB,GAAG,EAAE,EAAC,UAAU,EAAE,kBAAkB,EAAC;QACrC,MAAM,EAAE,EAAC,UAAU,EAAE,sCAAsC,EAAC;QAC5D,MAAM,EAAE,EAAC,UAAU,EAAE,4DAA4D,EAAC;QAClF,MAAM,EAAE,EAAC,UAAU,EAAE,gEAA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,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAA;IAC3C,CAAC"}
@@ -1,5 +1,9 @@
1
1
  export declare const Base58: Readonly<{
2
+ fromBytes(bytes: Uint8Array): string;
3
+ toBytes(string: string): Uint8Array<ArrayBuffer>;
4
+ random(count?: number): string;
5
+ /** @deprecated renamed to `fromBytes` */
2
6
  string(bytes: Uint8Array): string;
7
+ /** @deprecated renamed to `toBytes` */
3
8
  bytes(string: string): Uint8Array<ArrayBuffer>;
4
- random(count?: number): string;
5
9
  }>;