@fluidframework/id-compressor 2.0.0-dev-rc.1.0.0.224419

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 (157) hide show
  1. package/.eslintrc.js +27 -0
  2. package/.mocharc.js +12 -0
  3. package/CHANGELOG.md +7 -0
  4. package/LICENSE +21 -0
  5. package/README.md +170 -0
  6. package/api-extractor-lint.json +4 -0
  7. package/api-extractor.json +4 -0
  8. package/api-report/id-compressor.api.md +139 -0
  9. package/dist/appendOnlySortedMap.cjs +318 -0
  10. package/dist/appendOnlySortedMap.cjs.map +1 -0
  11. package/dist/appendOnlySortedMap.d.ts +124 -0
  12. package/dist/appendOnlySortedMap.d.ts.map +1 -0
  13. package/dist/finalSpace.cjs +62 -0
  14. package/dist/finalSpace.cjs.map +1 -0
  15. package/dist/finalSpace.d.ts +29 -0
  16. package/dist/finalSpace.d.ts.map +1 -0
  17. package/dist/id-compressor-alpha.d.ts +320 -0
  18. package/dist/id-compressor-beta.d.ts +172 -0
  19. package/dist/id-compressor-public.d.ts +172 -0
  20. package/dist/id-compressor-untrimmed.d.ts +333 -0
  21. package/dist/idCompressor.cjs +502 -0
  22. package/dist/idCompressor.cjs.map +1 -0
  23. package/dist/idCompressor.d.ts +84 -0
  24. package/dist/idCompressor.d.ts.map +1 -0
  25. package/dist/identifiers.cjs +15 -0
  26. package/dist/identifiers.cjs.map +1 -0
  27. package/dist/identifiers.d.ts +32 -0
  28. package/dist/identifiers.d.ts.map +1 -0
  29. package/dist/index.cjs +20 -0
  30. package/dist/index.cjs.map +1 -0
  31. package/dist/index.d.ts +11 -0
  32. package/dist/index.d.ts.map +1 -0
  33. package/dist/packageVersion.cjs +12 -0
  34. package/dist/packageVersion.cjs.map +1 -0
  35. package/dist/packageVersion.d.ts +9 -0
  36. package/dist/packageVersion.d.ts.map +1 -0
  37. package/dist/persistanceUtilities.cjs +43 -0
  38. package/dist/persistanceUtilities.cjs.map +1 -0
  39. package/dist/persistanceUtilities.d.ts +22 -0
  40. package/dist/persistanceUtilities.d.ts.map +1 -0
  41. package/dist/sessionSpaceNormalizer.cjs +80 -0
  42. package/dist/sessionSpaceNormalizer.cjs.map +1 -0
  43. package/dist/sessionSpaceNormalizer.d.ts +46 -0
  44. package/dist/sessionSpaceNormalizer.d.ts.map +1 -0
  45. package/dist/sessions.cjs +305 -0
  46. package/dist/sessions.cjs.map +1 -0
  47. package/dist/sessions.d.ts +115 -0
  48. package/dist/sessions.d.ts.map +1 -0
  49. package/dist/tsdoc-metadata.json +11 -0
  50. package/dist/types/idCompressor.cjs +7 -0
  51. package/dist/types/idCompressor.cjs.map +1 -0
  52. package/dist/types/idCompressor.d.ts +139 -0
  53. package/dist/types/idCompressor.d.ts.map +1 -0
  54. package/dist/types/identifiers.cjs +7 -0
  55. package/dist/types/identifiers.cjs.map +1 -0
  56. package/dist/types/identifiers.d.ts +40 -0
  57. package/dist/types/identifiers.d.ts.map +1 -0
  58. package/dist/types/index.cjs +7 -0
  59. package/dist/types/index.cjs.map +1 -0
  60. package/dist/types/index.d.ts +8 -0
  61. package/dist/types/index.d.ts.map +1 -0
  62. package/dist/types/persisted-types/0.0.1.cjs +7 -0
  63. package/dist/types/persisted-types/0.0.1.cjs.map +1 -0
  64. package/dist/types/persisted-types/0.0.1.d.ts +52 -0
  65. package/dist/types/persisted-types/0.0.1.d.ts.map +1 -0
  66. package/dist/types/persisted-types/index.cjs +7 -0
  67. package/dist/types/persisted-types/index.cjs.map +1 -0
  68. package/dist/types/persisted-types/index.d.ts +6 -0
  69. package/dist/types/persisted-types/index.d.ts.map +1 -0
  70. package/dist/utilities.cjs +170 -0
  71. package/dist/utilities.cjs.map +1 -0
  72. package/dist/utilities.d.ts +53 -0
  73. package/dist/utilities.d.ts.map +1 -0
  74. package/lib/appendOnlySortedMap.d.mts +124 -0
  75. package/lib/appendOnlySortedMap.d.mts.map +1 -0
  76. package/lib/appendOnlySortedMap.mjs +312 -0
  77. package/lib/appendOnlySortedMap.mjs.map +1 -0
  78. package/lib/finalSpace.d.mts +29 -0
  79. package/lib/finalSpace.d.mts.map +1 -0
  80. package/lib/finalSpace.mjs +58 -0
  81. package/lib/finalSpace.mjs.map +1 -0
  82. package/lib/id-compressor-alpha.d.mts +320 -0
  83. package/lib/id-compressor-beta.d.mts +172 -0
  84. package/lib/id-compressor-public.d.mts +172 -0
  85. package/lib/id-compressor-untrimmed.d.mts +333 -0
  86. package/lib/idCompressor.d.mts +84 -0
  87. package/lib/idCompressor.d.mts.map +1 -0
  88. package/lib/idCompressor.mjs +496 -0
  89. package/lib/idCompressor.mjs.map +1 -0
  90. package/lib/identifiers.d.mts +32 -0
  91. package/lib/identifiers.d.mts.map +1 -0
  92. package/lib/identifiers.mjs +11 -0
  93. package/lib/identifiers.mjs.map +1 -0
  94. package/lib/index.d.mts +8 -0
  95. package/lib/index.d.mts.map +1 -0
  96. package/lib/index.mjs +7 -0
  97. package/lib/index.mjs.map +1 -0
  98. package/lib/packageVersion.d.mts +9 -0
  99. package/lib/packageVersion.d.mts.map +1 -0
  100. package/lib/packageVersion.mjs +9 -0
  101. package/lib/packageVersion.mjs.map +1 -0
  102. package/lib/persistanceUtilities.d.mts +22 -0
  103. package/lib/persistanceUtilities.d.mts.map +1 -0
  104. package/lib/persistanceUtilities.mjs +34 -0
  105. package/lib/persistanceUtilities.mjs.map +1 -0
  106. package/lib/sessionSpaceNormalizer.d.mts +46 -0
  107. package/lib/sessionSpaceNormalizer.d.mts.map +1 -0
  108. package/lib/sessionSpaceNormalizer.mjs +76 -0
  109. package/lib/sessionSpaceNormalizer.mjs.map +1 -0
  110. package/lib/sessions.d.mts +115 -0
  111. package/lib/sessions.d.mts.map +1 -0
  112. package/lib/sessions.mjs +290 -0
  113. package/lib/sessions.mjs.map +1 -0
  114. package/lib/types/idCompressor.d.mts +139 -0
  115. package/lib/types/idCompressor.d.mts.map +1 -0
  116. package/lib/types/idCompressor.mjs +6 -0
  117. package/lib/types/idCompressor.mjs.map +1 -0
  118. package/lib/types/identifiers.d.mts +40 -0
  119. package/lib/types/identifiers.d.mts.map +1 -0
  120. package/lib/types/identifiers.mjs +6 -0
  121. package/lib/types/identifiers.mjs.map +1 -0
  122. package/lib/types/index.d.mts +8 -0
  123. package/lib/types/index.d.mts.map +1 -0
  124. package/lib/types/index.mjs +6 -0
  125. package/lib/types/index.mjs.map +1 -0
  126. package/lib/types/persisted-types/0.0.1.d.mts +52 -0
  127. package/lib/types/persisted-types/0.0.1.d.mts.map +1 -0
  128. package/lib/types/persisted-types/0.0.1.mjs +6 -0
  129. package/lib/types/persisted-types/0.0.1.mjs.map +1 -0
  130. package/lib/types/persisted-types/index.d.mts +6 -0
  131. package/lib/types/persisted-types/index.d.mts.map +1 -0
  132. package/lib/types/persisted-types/index.mjs +6 -0
  133. package/lib/types/persisted-types/index.mjs.map +1 -0
  134. package/lib/utilities.d.mts +53 -0
  135. package/lib/utilities.d.mts.map +1 -0
  136. package/lib/utilities.mjs +151 -0
  137. package/lib/utilities.mjs.map +1 -0
  138. package/package.json +114 -0
  139. package/prettier.config.cjs +8 -0
  140. package/src/appendOnlySortedMap.ts +366 -0
  141. package/src/finalSpace.ts +67 -0
  142. package/src/idCompressor.ts +685 -0
  143. package/src/identifiers.ts +42 -0
  144. package/src/index.ts +23 -0
  145. package/src/packageVersion.ts +9 -0
  146. package/src/persistanceUtilities.ts +58 -0
  147. package/src/sessionSpaceNormalizer.ts +83 -0
  148. package/src/sessions.ts +405 -0
  149. package/src/types/idCompressor.ts +155 -0
  150. package/src/types/identifiers.ts +39 -0
  151. package/src/types/index.ts +15 -0
  152. package/src/types/persisted-types/0.0.1.ts +58 -0
  153. package/src/types/persisted-types/README.md +3 -0
  154. package/src/types/persisted-types/index.ts +11 -0
  155. package/src/utilities.ts +191 -0
  156. package/tsc-multi.test.json +4 -0
  157. package/tsconfig.json +12 -0
@@ -0,0 +1,155 @@
1
+ /*!
2
+ * Copyright (c) Microsoft Corporation and contributors. All rights reserved.
3
+ * Licensed under the MIT License.
4
+ */
5
+
6
+ import { SessionSpaceCompressedId, OpSpaceCompressedId, SessionId, StableId } from "./identifiers";
7
+ import {
8
+ IdCreationRange,
9
+ SerializedIdCompressorWithNoSession,
10
+ SerializedIdCompressorWithOngoingSession,
11
+ } from "./persisted-types";
12
+
13
+ /**
14
+ * @alpha
15
+ */
16
+ export interface IIdCompressorCore {
17
+ /**
18
+ * Returns a range of IDs created by this session in a format for sending to the server for finalizing.
19
+ * The range will include all IDs generated via calls to `generateCompressedId` since the last time this method was called.
20
+ * @returns the range of IDs, which may be empty. This range must be sent to the server for ordering before
21
+ * it is finalized. Ranges must be sent to the server in the order that they are taken via calls to this method.
22
+ */
23
+ takeNextCreationRange(): IdCreationRange;
24
+
25
+ /**
26
+ * Finalizes the supplied range of IDs (which may be from either a remote or local session).
27
+ * @param range - the range of session-local IDs to finalize.
28
+ */
29
+ finalizeCreationRange(range: IdCreationRange): void;
30
+
31
+ /**
32
+ * Returns a persistable form of the current state of this `IdCompressor` which can be rehydrated via `IdCompressor.deserialize()`.
33
+ * This includes finalized state as well as un-finalized state and is therefore suitable for use in offline scenarios.
34
+ */
35
+ serialize(withSession: true): SerializedIdCompressorWithOngoingSession;
36
+
37
+ /**
38
+ * Returns a persistable form of the current state of this `IdCompressor` which can be rehydrated via `IdCompressor.deserialize()`.
39
+ * This only includes finalized state and is therefore suitable for use in summaries.
40
+ */
41
+ serialize(withSession: false): SerializedIdCompressorWithNoSession;
42
+ }
43
+
44
+ /**
45
+ * A distributed UUID generator and compressor.
46
+ *
47
+ * Generates arbitrary non-colliding v4 UUIDs, called stable IDs, for multiple "sessions" (which can be distributed across the network),
48
+ * providing each session with the ability to map these UUIDs to `numbers`.
49
+ *
50
+ * A session is a unique identifier that denotes a single compressor. New IDs are created through a single compressor API
51
+ * which should then sent in ranges to the server for total ordering (and are subsequently relayed to other clients). When a new ID is
52
+ * created it is said to be created by the compressor's "local" session.
53
+ *
54
+ * For each stable ID created, two numeric IDs are provided by the compressor:
55
+ *
56
+ * 1. A session-local ID, which is stable for the lifetime of the session (which could be longer than that of the compressor object, as it may
57
+ * be serialized for offline usage). Available as soon as the stable ID is allocated. These IDs are session-unique and are thus only
58
+ * safely usable within the scope of the compressor that created it.
59
+ *
60
+ * 2. A final ID, which is stable across serialization and deserialization of an IdCompressor. Available as soon as the range containing
61
+ * the corresponding session-local ID is totally ordered (via consensus) with respect to other sessions' allocations.
62
+ * Final IDs are known to and publicly usable by any compressor that has received them.
63
+ *
64
+ * Compressors will allocate UUIDs in non-random ways to reduce entropy allowing for optimized storage of the data needed
65
+ * to map the UUIDs to the numbers.
66
+ *
67
+ * The following invariants are upheld by IdCompressor:
68
+ *
69
+ * 1. Session-local IDs will always decompress to the same UUIDs for the lifetime of the session.
70
+ *
71
+ * 2. Final IDs will always decompress to the same UUIDs.
72
+ *
73
+ * 3. After a server-processed range of session-local IDs (from any session) is received by a compressor, any of those session-local IDs may be
74
+ * translated by the compressor into the corresponding final ID. For any given session-local ID, this translation will always yield the
75
+ * same final ID.
76
+ *
77
+ * 4. A UUID will always compress into the same session-local ID for the lifetime of the session.
78
+ *
79
+ * Session-local IDs are sent across the wire in efficiently-represented ranges. These ranges are created by querying the compressor, and *must*
80
+ * be ordered (i.e. sent to the server) in the order they are created in order to preserve the above invariants.
81
+ *
82
+ * Session-local IDs can be used immediately after creation, but will eventually (after being sequenced) have a corresponding final ID. This
83
+ * could make reasoning about equality of those two forms difficult. For example, if a cache is keyed off of a
84
+ * session-local ID but is later queried using the final ID (which is semantically equal, as it decompresses to the same UUID/string) it will
85
+ * produce a cache miss. In order to make using collections of both remotely created and locally created IDs easy, regardless of whether the
86
+ * session-local IDs have been finalized, the compressor defines two "spaces" of IDs:
87
+ *
88
+ * 1. Session space: in this space, all IDs are normalized to their "most local form". This means that all IDs created by the local session
89
+ * will be in local form, regardless of if they have been finalized. Remotely created IDs, which could only have been received after
90
+ * finalizing and will never have a local form for the compressor, will of course be final IDs. This space should be used with consumer APIs
91
+ * and data structures, as the lifetime of the IDs is guaranteed to be the same as the compressor object. Care must be taken to not use
92
+ * these IDs across compressor objects, as the local IDs are specific to the compressor that created them.
93
+ *
94
+ * 2. Op space: in this space, all IDs are normalized to their "most final form". This means that all IDs except session-local IDs that
95
+ * have not yet been finalized will be in final ID form. This space is useful for serialization in ops (e.g. references), as other clients
96
+ * that receive them need not do any work to normalize them to *their* session-space in the common case. Note that IDs in op space may move
97
+ * out of Op space over time, namely, when a session-local ID in this space becomes finalized, and thereafter has a "more final form".
98
+ * Consequentially, it may be useful to restrict parameters of a persisted type to this space (to optimize perf), but it is potentially
99
+ * incorrect to use this type for a runtime variable. This is an asymmetry that does not affect session space, as local IDs are always as
100
+ * "local as possible".
101
+ *
102
+ * These two spaces naturally define a rule: consumers of compressed IDs should use session-space IDs, but serialized forms such as ops
103
+ * should use op-space IDs.
104
+ * @public
105
+ */
106
+ export interface IIdCompressor {
107
+ localSessionId: SessionId;
108
+
109
+ /**
110
+ * Generates a new compressed ID or returns an existing one.
111
+ * This should ONLY be called to generate IDs for local operations.
112
+ * @returns A new local ID in session space.
113
+ */
114
+ generateCompressedId(): SessionSpaceCompressedId;
115
+ /**
116
+ * Normalizes a session space ID into op space.
117
+ * @param id - the local ID to normalize.
118
+ * @returns the ID in op space.
119
+ */
120
+ normalizeToOpSpace(id: SessionSpaceCompressedId): OpSpaceCompressedId;
121
+ /**
122
+ * Normalizes an ID into session space.
123
+ * @param id - the ID to normalize. If it is a local ID, it is assumed to have been created by the session corresponding
124
+ * to `sessionId`.
125
+ * @param originSessionId - the session from which `id` originated
126
+ * @returns the session-space ID corresponding to `id`, which might not have been a final ID if the client that created it had not yet
127
+ * finalized it. This can occur when a client references an ID during the window of time in which it is waiting to receive the ordered
128
+ * range that contained it from the server.
129
+ */
130
+ normalizeToSessionSpace(
131
+ id: OpSpaceCompressedId,
132
+ originSessionId: SessionId,
133
+ ): SessionSpaceCompressedId;
134
+
135
+ /**
136
+ * Decompresses a previously compressed ID into a UUID.
137
+ * @param id - the compressed ID to be decompressed.
138
+ * @returns the UUID associated with the compressed ID. Fails if the ID was not generated by this compressor.
139
+ */
140
+ decompress(id: SessionSpaceCompressedId): StableId;
141
+
142
+ /**
143
+ * Recompresses a UUID.
144
+ * @param uncompressed - the UUID to recompress.
145
+ * @returns the `CompressedId` associated with `uncompressed`. Fails if it has not been previously compressed by this compressor.
146
+ */
147
+ recompress(uncompressed: StableId): SessionSpaceCompressedId;
148
+
149
+ /**
150
+ * Attempts to recompresses a UUID.
151
+ * @param uncompressed - the UUID to recompress,
152
+ * @returns the `CompressedId` associated with `uncompressed` or undefined if it has not been previously compressed by this compressor.
153
+ */
154
+ tryRecompress(uncompressed: StableId): SessionSpaceCompressedId | undefined;
155
+ }
@@ -0,0 +1,39 @@
1
+ /*!
2
+ * Copyright (c) Microsoft Corporation and contributors. All rights reserved.
3
+ * Licensed under the MIT License.
4
+ */
5
+
6
+ /**
7
+ * A compressed ID that has been normalized into "session space" (see `IdCompressor` for more).
8
+ * Consumer-facing APIs and data structures should use session-space IDs as their lifetime and equality is stable and tied to
9
+ * the scope of the session (i.e. compressor) that produced them.
10
+ * @public
11
+ */
12
+ export type SessionSpaceCompressedId = number & {
13
+ readonly SessionUnique: "cea55054-6b82-4cbf-ad19-1fa645ea3b3e";
14
+ };
15
+
16
+ /**
17
+ * A compressed ID that has been normalized into "op space".
18
+ * Serialized/persisted structures (e.g. ops) should use op-space IDs as a performance optimization, as they require less normalizing when
19
+ * received by a remote client due to the fact that op space for a given compressor is session space for all other compressors.
20
+ * @public
21
+ */
22
+ export type OpSpaceCompressedId = number & {
23
+ readonly OpNormalized: "9209432d-a959-4df7-b2ad-767ead4dbcae";
24
+ };
25
+
26
+ /**
27
+ * A version 4, variant 1 uuid (https://datatracker.ietf.org/doc/html/rfc4122).
28
+ * A 128-bit Universally Unique IDentifier. Represented here
29
+ * with a string of the form xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx,
30
+ * where x is a lowercase hex digit.
31
+ * @public
32
+ */
33
+ export type StableId = string & { readonly StableId: "53172b0d-a3d5-41ea-bd75-b43839c97f5a" };
34
+
35
+ /**
36
+ * A StableId which is suitable for use as a session identifier
37
+ * @public
38
+ */
39
+ export type SessionId = StableId & { readonly SessionId: "4498f850-e14e-4be9-8db0-89ec00997e58" };
@@ -0,0 +1,15 @@
1
+ /*!
2
+ * Copyright (c) Microsoft Corporation and contributors. All rights reserved.
3
+ * Licensed under the MIT License.
4
+ */
5
+
6
+ export {
7
+ IdCreationRange,
8
+ SerializedIdCompressor,
9
+ SerializedIdCompressorWithNoSession,
10
+ SerializedIdCompressorWithOngoingSession,
11
+ } from "./persisted-types";
12
+
13
+ export { IIdCompressorCore, IIdCompressor } from "./idCompressor";
14
+
15
+ export { SessionSpaceCompressedId, OpSpaceCompressedId, SessionId, StableId } from "./identifiers";
@@ -0,0 +1,58 @@
1
+ /*!
2
+ * Copyright (c) Microsoft Corporation and contributors. All rights reserved.
3
+ * Licensed under the MIT License.
4
+ */
5
+
6
+ import type { SessionId } from "../identifiers";
7
+
8
+ /**
9
+ * The serialized contents of an IdCompressor, suitable for persistence in a summary.
10
+ * @alpha
11
+ */
12
+ export type SerializedIdCompressor = string & {
13
+ readonly _serializedIdCompressor: "8c73c57c-1cf4-4278-8915-6444cb4f6af5";
14
+ };
15
+
16
+ /**
17
+ * The serialized contents of an IdCompressor, suitable for persistence in a summary.
18
+ * @alpha
19
+ */
20
+ export type SerializedIdCompressorWithNoSession = SerializedIdCompressor & {
21
+ readonly _noLocalState: "3aa2e1e8-cc28-4ea7-bc1a-a11dc3f26dfb";
22
+ };
23
+
24
+ /**
25
+ * The serialized contents of an IdCompressor, suitable for persistence in a summary.
26
+ * @alpha
27
+ */
28
+ export type SerializedIdCompressorWithOngoingSession = SerializedIdCompressor & {
29
+ readonly _hasLocalState: "1281acae-6d14-47e7-bc92-71c8ee0819cb";
30
+ };
31
+
32
+ /**
33
+ * Data describing a range of session-local IDs (from a remote or local session).
34
+ *
35
+ * A range is composed of local IDs that were generated.
36
+ * @alpha
37
+ */
38
+ export interface IdCreationRange {
39
+ readonly sessionId: SessionId;
40
+ readonly ids?: {
41
+ /**
42
+ * The gen count of the first ID in the range created by `sessionId.`
43
+ */
44
+ readonly firstGenCount: number;
45
+
46
+ /**
47
+ * The number of IDs created in the range created by `sessionId.`
48
+ */
49
+ readonly count: number;
50
+
51
+ /**
52
+ * The size of the ID cluster to create if `count` overflows the existing cluster for
53
+ * `sessionId`, if one exists. This request will be respected, and the size of the cluster
54
+ * will be equal to overflow + `requestedClusterSize`.
55
+ */
56
+ readonly requestedClusterSize: number;
57
+ };
58
+ }
@@ -0,0 +1,3 @@
1
+ # Persisted Types
2
+
3
+ The types in this folder inherit all requirements outlined in [the experimental SharedTree persisted types README](../../../../../../experimental/dds/tree/src/persisted-types/README.md).
@@ -0,0 +1,11 @@
1
+ /*!
2
+ * Copyright (c) Microsoft Corporation and contributors. All rights reserved.
3
+ * Licensed under the MIT License.
4
+ */
5
+
6
+ export {
7
+ IdCreationRange,
8
+ SerializedIdCompressor,
9
+ SerializedIdCompressorWithNoSession,
10
+ SerializedIdCompressorWithOngoingSession,
11
+ } from "./0.0.1";
@@ -0,0 +1,191 @@
1
+ /*!
2
+ * Copyright (c) Microsoft Corporation and contributors. All rights reserved.
3
+ * Licensed under the MIT License.
4
+ */
5
+
6
+ /* eslint-disable no-bitwise */
7
+ import { assert } from "@fluidframework/core-utils";
8
+ import { v4 } from "uuid";
9
+ import { SessionId, StableId } from "./types";
10
+ import { LocalCompressedId, NumericUuid } from "./identifiers";
11
+
12
+ const hexadecimalCharCodes = Array.from("09afAF").map((c) => c.charCodeAt(0)) as [
13
+ zero: number,
14
+ nine: number,
15
+ a: number,
16
+ f: number,
17
+ A: number,
18
+ F: number,
19
+ ];
20
+
21
+ function isHexadecimalCharacter(charCode: number): boolean {
22
+ return (
23
+ (charCode >= hexadecimalCharCodes[0] && charCode <= hexadecimalCharCodes[1]) ||
24
+ (charCode >= hexadecimalCharCodes[2] && charCode <= hexadecimalCharCodes[3]) ||
25
+ (charCode >= hexadecimalCharCodes[4] && charCode <= hexadecimalCharCodes[5])
26
+ );
27
+ }
28
+
29
+ /**
30
+ * Generate a random session ID
31
+ * @alpha
32
+ */
33
+ export function createSessionId(): SessionId {
34
+ return assertIsStableId(v4()) as SessionId;
35
+ }
36
+
37
+ /**
38
+ * Asserts that the given string is a stable ID.
39
+ * @internal
40
+ */
41
+ export function assertIsStableId(stableId: string): StableId {
42
+ assert(isStableId(stableId), 0x4a3 /* Expected a StableId */);
43
+ return stableId;
44
+ }
45
+
46
+ /**
47
+ * Asserts that the given string is a stable ID.
48
+ */
49
+ export function assertIsSessionId(stableId: string): SessionId {
50
+ assertIsStableId(stableId);
51
+ return stableId as SessionId;
52
+ }
53
+
54
+ /**
55
+ * Generate a random stable ID
56
+ * @internal
57
+ */
58
+ export function generateStableId(): StableId {
59
+ return assertIsStableId(v4());
60
+ }
61
+
62
+ /**
63
+ * Returns true iff the given string is a valid Version 4, variant 2 UUID
64
+ * 'xxxxxxxx-xxxx-4xxx-vxxx-xxxxxxxxxxxx'
65
+ * @internal
66
+ */
67
+ export function isStableId(str: string): str is StableId {
68
+ if (str.length !== 36) {
69
+ return false;
70
+ }
71
+
72
+ for (let i = 0; i < str.length; i++) {
73
+ switch (i) {
74
+ case 8:
75
+ case 13:
76
+ case 18:
77
+ case 23:
78
+ if (str.charAt(i) !== "-") {
79
+ return false;
80
+ }
81
+ break;
82
+
83
+ case 14:
84
+ if (str.charAt(i) !== "4") {
85
+ return false;
86
+ }
87
+ break;
88
+
89
+ case 19: {
90
+ const char = str.charAt(i);
91
+ if (char !== "8" && char !== "9" && char !== "a" && char !== "b") {
92
+ return false;
93
+ }
94
+ break;
95
+ }
96
+
97
+ default:
98
+ if (!isHexadecimalCharacter(str.charCodeAt(i))) {
99
+ return false;
100
+ }
101
+ break;
102
+ }
103
+ }
104
+
105
+ return true;
106
+ }
107
+
108
+ /**
109
+ * A numeric comparator used for sorting in ascending order.
110
+ *
111
+ * Handles +/-0 like Map: -0 is equal to +0.
112
+ */
113
+ export function compareFiniteNumbers<T extends number>(a: T, b: T): number {
114
+ return a - b;
115
+ }
116
+
117
+ /**
118
+ * Compares strings lexically to form a strict partial ordering.
119
+ */
120
+ export function compareStrings<T extends string>(a: T, b: T): number {
121
+ return a > b ? 1 : a === b ? 0 : -1;
122
+ }
123
+
124
+ /**
125
+ * Compares bigints to form a strict partial ordering.
126
+ */
127
+ export function compareBigints<T extends bigint>(a: T, b: T): number {
128
+ return a > b ? 1 : a === b ? 0 : -1;
129
+ }
130
+
131
+ export function genCountFromLocalId(localId: LocalCompressedId): number {
132
+ return -localId;
133
+ }
134
+
135
+ export function localIdFromGenCount(genCount: number): LocalCompressedId {
136
+ return -genCount as LocalCompressedId;
137
+ }
138
+
139
+ // xxxxxxxx-xxxx-Mxxx-Nxxx-xxxxxxxxxxxx
140
+ const versionMask = 0x4n << (19n * 4n); // Version 4
141
+ const variantMask = 0x8n << (15n * 4n); // Variant RFC4122 (1 0 x x)
142
+ const upperMask = 0xffffffffffffn << (20n * 4n);
143
+ // Upper mask when version/variant bits are removed
144
+ const strippedUpperMask = upperMask >> 6n;
145
+ const middieBittiesMask = 0xfffn << (16n * 4n);
146
+ // Middie mask when version/variant bits are removed
147
+ const strippedMiddieBittiesMask = middieBittiesMask >> 2n;
148
+ // Note: leading character should be 3 to mask at 0011
149
+ // The more-significant half of the N nibble is used to denote the variant (10xx)
150
+ const lowerMask = 0x3fffffffffffffffn;
151
+
152
+ export function numericUuidFromStableId(stableId: StableId): NumericUuid {
153
+ const uuidU128 = BigInt(`0x${stableId.replace(/-/g, "")}`);
154
+ const upperMasked = uuidU128 & upperMask;
155
+ const middieBittiesMasked = uuidU128 & middieBittiesMask;
156
+ const lowerMasked = uuidU128 & lowerMask;
157
+
158
+ const upperMaskedPlaced = upperMasked >> 6n;
159
+ const middieBittiesMaskedPlaced = middieBittiesMasked >> 2n;
160
+
161
+ const id = upperMaskedPlaced | middieBittiesMaskedPlaced | lowerMasked;
162
+ return id as NumericUuid;
163
+ }
164
+
165
+ export function stableIdFromNumericUuid(numericUuid: NumericUuid): StableId {
166
+ // bitwise reverse transform
167
+ const upperMasked = (numericUuid & strippedUpperMask) << 6n;
168
+ const middieBittiesMasked = (numericUuid & strippedMiddieBittiesMask) << 2n;
169
+ const lowerMasked = numericUuid & lowerMask;
170
+ const uuidU128 = upperMasked | versionMask | middieBittiesMasked | variantMask | lowerMasked;
171
+ // Pad to 32 characters, inserting leading zeroes if needed
172
+ const uuidString = uuidU128.toString(16).padStart(32, "0");
173
+ return `${uuidString.substring(0, 8)}-${uuidString.substring(8, 12)}-${uuidString.substring(
174
+ 12,
175
+ 16,
176
+ )}-${uuidString.substring(16, 20)}-${uuidString.substring(20, 32)}` as StableId;
177
+ }
178
+
179
+ export function offsetNumericUuid(numericUuid: NumericUuid, offset: number): NumericUuid {
180
+ // eslint-disable-next-line @typescript-eslint/restrict-plus-operands
181
+ return (numericUuid + BigInt(offset)) as NumericUuid;
182
+ }
183
+
184
+ export function subtractNumericUuids(a: NumericUuid, b: NumericUuid): NumericUuid {
185
+ return (a - b) as NumericUuid;
186
+ }
187
+
188
+ export function addNumericUuids(a: NumericUuid, b: NumericUuid): NumericUuid {
189
+ // eslint-disable-next-line @typescript-eslint/restrict-plus-operands
190
+ return (a + b) as NumericUuid;
191
+ }
@@ -0,0 +1,4 @@
1
+ {
2
+ "targets": [{ "extname": ".cjs", "module": "CommonJS", "moduleResolution": "Node16" }],
3
+ "projects": ["./tsconfig.json", "./src/test/tsconfig.json"]
4
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,12 @@
1
+ {
2
+ "extends": [
3
+ "../../../common/build/build-common/tsconfig.base.json",
4
+ "../../../common/build/build-common/tsconfig.cjs.json",
5
+ ],
6
+ "compilerOptions": {
7
+ "rootDir": "./src",
8
+ "outDir": "./dist",
9
+ },
10
+ "include": ["src/**/*"],
11
+ "exclude": ["src/test/**/*"],
12
+ }