@lunora/solid 1.0.0-alpha.30 → 1.0.0-alpha.32

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 (44) hide show
  1. package/dist/index.mjs +1 -19
  2. package/dist/packem_shared/AuthLoading-D6A1mBRs.mjs +1 -0
  3. package/dist/packem_shared/LunoraContext-CVOsskhY.mjs +1 -0
  4. package/dist/packem_shared/LunoraProvider-cifsrLab.mjs +1 -0
  5. package/dist/packem_shared/createAgent-BbHVxEpf.mjs +1 -0
  6. package/dist/packem_shared/createAgentChat-O-PgJtWE.mjs +1 -0
  7. package/dist/packem_shared/createAgentState-CbE2MP_H.mjs +1 -0
  8. package/dist/packem_shared/createAgentToolEvents-DOU_J3JT.mjs +1 -0
  9. package/dist/packem_shared/createConnectionStatus-B9ly5m1x.mjs +1 -0
  10. package/dist/packem_shared/createFlag-qBxuQ5hP.mjs +1 -0
  11. package/dist/packem_shared/createInfiniteQuery-CDLk3UVQ.mjs +1 -0
  12. package/dist/packem_shared/createMutation-9i34uh8U.mjs +1 -0
  13. package/dist/packem_shared/createMutator-zzxMk2QQ.mjs +1 -0
  14. package/dist/packem_shared/createPresence-DNVSvTzP.mjs +1 -0
  15. package/dist/packem_shared/createQuery-CFb7mUGW.mjs +1 -0
  16. package/dist/packem_shared/createRateLimit-BdVo3eNW.mjs +1 -0
  17. package/dist/packem_shared/createStream-DozkYNOc.mjs +1 -0
  18. package/dist/packem_shared/createSubscription-KbQk0ohZ.mjs +1 -0
  19. package/dist/packem_shared/createVoiceAgent-CzXF9acz.mjs +1 -0
  20. package/dist/packem_shared/hydratePreloaded-BbGFlPEb.mjs +1 -0
  21. package/dist/packem_shared/stable-key-BSG0zK_E.mjs +1 -0
  22. package/dist/server.mjs +1 -1
  23. package/dist/upload.mjs +1 -2
  24. package/package.json +3 -3
  25. package/dist/packem_shared/AuthLoading-u5QJoV-J.mjs +0 -73
  26. package/dist/packem_shared/LunoraContext-C59PzHhN.mjs +0 -13
  27. package/dist/packem_shared/LunoraProvider-CzB3zGhy.mjs +0 -17
  28. package/dist/packem_shared/createAgent-D7EZBeql.mjs +0 -55
  29. package/dist/packem_shared/createAgentChat-Bq-wzSxv.mjs +0 -166
  30. package/dist/packem_shared/createAgentState-DckYu3G8.mjs +0 -21
  31. package/dist/packem_shared/createAgentToolEvents-UavTO16u.mjs +0 -99
  32. package/dist/packem_shared/createConnectionStatus-1poqwqR9.mjs +0 -14
  33. package/dist/packem_shared/createFlag-DQoGdUMB.mjs +0 -78
  34. package/dist/packem_shared/createInfiniteQuery-CD2GT1_O.mjs +0 -339
  35. package/dist/packem_shared/createMutation-LkrbhItI.mjs +0 -36
  36. package/dist/packem_shared/createMutator-foSnPJPt.mjs +0 -24
  37. package/dist/packem_shared/createPresence-DM2cVkiG.mjs +0 -85
  38. package/dist/packem_shared/createQuery-BUldvZXj.mjs +0 -28
  39. package/dist/packem_shared/createRateLimit-BA2f8XyF.mjs +0 -76
  40. package/dist/packem_shared/createStream-D9ONbGAw.mjs +0 -70
  41. package/dist/packem_shared/createSubscription-D3HbChGe.mjs +0 -41
  42. package/dist/packem_shared/createVoiceAgent-hu59SaDl.mjs +0 -418
  43. package/dist/packem_shared/hydratePreloaded-CWny5-2J.mjs +0 -25
  44. package/dist/packem_shared/stable-key-DePnevIy.mjs +0 -38
@@ -1,78 +0,0 @@
1
- import { createSignal, createEffect, on, onCleanup } from 'solid-js';
2
- import { s as stableStringify } from './stable-key-DePnevIy.mjs';
3
- import { useLunora } from './LunoraContext-C59PzHhN.mjs';
4
-
5
- const FLAGS_EVAL_PATH = "__lunora_flags__:eval";
6
- const flagKind = (value) => {
7
- const kind = typeof value;
8
- if (kind === "boolean" || kind === "number" || kind === "string") {
9
- return kind;
10
- }
11
- return "object";
12
- };
13
- const flagsReference = {
14
- __lunoraRef: FLAGS_EVAL_PATH
15
- };
16
- const resolveMaybe = (value) => typeof value === "function" ? value() : value;
17
- const serializeContext = (context) => context === void 0 ? "" : stableStringify(context);
18
- const createFlag = (key, defaultValue, context) => {
19
- const client = useLunora();
20
- const type = flagKind(defaultValue);
21
- const [value, setValue] = createSignal(defaultValue);
22
- createEffect(on(() => `${resolveMaybe(key)} ${serializeContext(resolveMaybe(context))}`, () => {
23
- const currentKey = resolveMaybe(key);
24
- const currentContext = resolveMaybe(context);
25
- setValue(() => defaultValue);
26
- let unsubscribe;
27
- try {
28
- unsubscribe = client.subscribe(flagsReference, {
29
- context: currentContext,
30
- default: defaultValue,
31
- key: currentKey,
32
- type
33
- }, (next) => {
34
- setValue(() => next);
35
- });
36
- } catch {
37
- return;
38
- }
39
- onCleanup(unsubscribe);
40
- }));
41
- return value;
42
- };
43
- const createFlags = (flags, context) => {
44
- const client = useLunora();
45
- const [values, setValues] = createSignal(flags);
46
- const spec = stableStringify(flags);
47
- createEffect(on(() => `${spec} ${serializeContext(resolveMaybe(context))}`, () => {
48
- const currentContext = resolveMaybe(context);
49
- setValues(() => flags);
50
- const unsubscribes = [];
51
- for (const [key, defaultValue] of Object.entries(flags)) {
52
- try {
53
- unsubscribes.push(client.subscribe(flagsReference, {
54
- context: currentContext,
55
- default: defaultValue,
56
- key,
57
- type: flagKind(defaultValue)
58
- }, (next) => {
59
- setValues((previous) => {
60
- return {
61
- ...previous,
62
- [key]: next
63
- };
64
- });
65
- }));
66
- } catch {
67
- }
68
- }
69
- onCleanup(() => {
70
- for (const unsubscribe of unsubscribes) {
71
- unsubscribe();
72
- }
73
- });
74
- }));
75
- return values;
76
- };
77
-
78
- export { createFlag, createFlags };
@@ -1,339 +0,0 @@
1
- import { initialPages, derivePaginationStatus, applyLoadMore, rebalance } from '@lunora/client/pagination';
2
- import { createMemo, createSignal, createEffect, on, onCleanup } from 'solid-js';
3
- import { s as stableStringify } from './stable-key-DePnevIy.mjs';
4
- import { useLunora } from './LunoraContext-C59PzHhN.mjs';
5
-
6
- const toBase64 = (bytes) => {
7
- let binary = "";
8
- const chunk = 32768;
9
- for (let index = 0; index < bytes.length; index += chunk) {
10
- binary += String.fromCharCode(...bytes.subarray(index, index + chunk));
11
- }
12
- return btoa(binary);
13
- };
14
-
15
- const TAG = "$lunora.wire$";
16
- const MAX_DEPTH = 64;
17
- const encodeWire = (value, depth = 0) => {
18
- if (depth > MAX_DEPTH) {
19
- throw new RangeError(`wire-codec: value nesting exceeds the ${MAX_DEPTH}-level limit`);
20
- }
21
- if (value === void 0) {
22
- return [TAG, "undefined"];
23
- }
24
- if (value === null) {
25
- return null;
26
- }
27
- const kind = typeof value;
28
- if (kind === "bigint") {
29
- return [TAG, "bigint", value.toString()];
30
- }
31
- if (kind === "number") {
32
- const numeric = value;
33
- if (Number.isNaN(numeric)) {
34
- return [TAG, "nan"];
35
- }
36
- if (numeric === Infinity) {
37
- return [TAG, "inf"];
38
- }
39
- if (numeric === -Infinity) {
40
- return [TAG, "-inf"];
41
- }
42
- return numeric;
43
- }
44
- if (kind !== "object") {
45
- return value;
46
- }
47
- if (value instanceof Date) {
48
- return [TAG, "date", encodeWire(value.getTime(), depth + 1)];
49
- }
50
- if (value instanceof Error) {
51
- const error = value;
52
- const properties = {};
53
- for (const key of Object.keys(error)) {
54
- if (error[key] !== void 0) {
55
- properties[key] = encodeWire(error[key], depth + 1);
56
- }
57
- }
58
- const encodedError = [TAG, "error", error.name, error.message, properties];
59
- if (error.cause !== void 0) {
60
- encodedError.push(encodeWire(error.cause, depth + 1));
61
- }
62
- return encodedError;
63
- }
64
- if (value instanceof URL) {
65
- return [TAG, "url", value.href];
66
- }
67
- if (value instanceof Map) {
68
- return [TAG, "map", [...value.entries()].map(([k, v]) => [encodeWire(k, depth + 1), encodeWire(v, depth + 1)])];
69
- }
70
- if (value instanceof Set) {
71
- return [TAG, "set", [...value].map((item) => encodeWire(item, depth + 1))];
72
- }
73
- if (value instanceof ArrayBuffer) {
74
- return [TAG, "bytes", toBase64(new Uint8Array(value)), "ArrayBuffer"];
75
- }
76
- if (ArrayBuffer.isView(value)) {
77
- const view = value;
78
- const ctorName = view.constructor.name;
79
- const bytes = new Uint8Array(view.buffer, view.byteOffset, view.byteLength);
80
- return ctorName === "Uint8Array" ? [TAG, "bytes", toBase64(bytes)] : [TAG, "bytes", toBase64(bytes), ctorName];
81
- }
82
- if (Array.isArray(value)) {
83
- const encoded = value.map((item) => encodeWire(item, depth + 1));
84
- return encoded.length > 0 && encoded[0] === TAG ? [TAG, "arr", encoded] : encoded;
85
- }
86
- const proto = Object.getPrototypeOf(value);
87
- if (proto !== null && proto !== Object.prototype) {
88
- const name = value.constructor?.name ?? "value";
89
- throw new TypeError(`wire-codec: cannot encode a ${name} over the Lunora wire — only plain objects, arrays, and the supported built-ins (Date, Error, URL, Map, Set, ArrayBuffer/typed arrays, bigint) round-trip`);
90
- }
91
- const source = value;
92
- const result = {};
93
- for (const key of Object.keys(source)) {
94
- const field = source[key];
95
- if (field !== void 0) {
96
- result[key] = encodeWire(field, depth + 1);
97
- }
98
- }
99
- return result;
100
- };
101
-
102
- const stableWireKey = (value) => stableStringify(encodeWire(value));
103
-
104
- const buildPageArgs = (page, baseArgs) => {
105
- return {
106
- ...baseArgs,
107
- paginationOpts: {
108
- cursor: page.lower,
109
- endCursor: page.upper,
110
- numItems: page.numItems
111
- }
112
- };
113
- };
114
- const buildPageKey = (functionPath, pageArgs) => `${functionPath}::${stableWireKey(pageArgs)}`;
115
- const createPaginatedCore = (function_, args, options) => {
116
- const client = useLunora();
117
- const {
118
- initialNumItems,
119
- shardKey
120
- } = options;
121
- const resolveArgs = () => typeof args === "function" ? args() : args;
122
- const [pages, setPages] = createSignal(initialPages(initialNumItems));
123
- const resultsByKey = /* @__PURE__ */ new Map();
124
- const [pageResults, setPageResults] = createSignal([]);
125
- const activeSubs = /* @__PURE__ */ new Map();
126
- const pendingPageKeys = /* @__PURE__ */ new Set();
127
- const rebuildPageResults = (currentPages, baseArgs) => {
128
- const updated = currentPages.map((page) => {
129
- const key = buildPageKey(function_["__lunoraRef"], buildPageArgs(page, baseArgs));
130
- return resultsByKey.get(key);
131
- });
132
- setPageResults(updated);
133
- };
134
- const migrateResultsForRebalance = (oldPages, newPages, baseArgs) => {
135
- const keyOf = (page) => buildPageKey(function_["__lunoraRef"], buildPageArgs(page, baseArgs));
136
- for (const newPage of newPages) {
137
- const newKey = keyOf(newPage);
138
- if (resultsByKey.has(newKey)) {
139
- continue;
140
- }
141
- const donor = oldPages.find((oldPage) => oldPage.lower === newPage.lower);
142
- if (donor) {
143
- const carried = resultsByKey.get(keyOf(donor));
144
- if (carried) {
145
- resultsByKey.set(newKey, carried);
146
- }
147
- }
148
- }
149
- };
150
- const syncPass = (currentPages, baseArgs) => {
151
- const wantedKeys = /* @__PURE__ */ new Set();
152
- for (const page of currentPages) {
153
- wantedKeys.add(buildPageKey(function_["__lunoraRef"], buildPageArgs(page, baseArgs)));
154
- }
155
- for (const [key, unsub] of activeSubs) {
156
- if (!wantedKeys.has(key)) {
157
- unsub();
158
- activeSubs.delete(key);
159
- pendingPageKeys.delete(key);
160
- resultsByKey.delete(key);
161
- }
162
- }
163
- for (const page of currentPages) {
164
- const pageArgs = buildPageArgs(page, baseArgs);
165
- const key = buildPageKey(function_["__lunoraRef"], pageArgs);
166
- if (activeSubs.has(key)) {
167
- continue;
168
- }
169
- pendingPageKeys.add(key);
170
- const unsub = client.subscribe(function_, pageArgs, (value) => {
171
- resultsByKey.set(key, value);
172
- pendingPageKeys.delete(key);
173
- const currentArgs = resolveArgs();
174
- if (currentArgs === "skip") {
175
- return;
176
- }
177
- rebuildPageResults(pages(), currentArgs);
178
- if (pendingPageKeys.size === 0) {
179
- const latestPages = pages();
180
- const next = rebalance(latestPages, pageResults());
181
- if (next) {
182
- migrateResultsForRebalance(latestPages, next, currentArgs);
183
- setPages(next);
184
- }
185
- }
186
- }, {
187
- shardKey
188
- });
189
- activeSubs.set(key, unsub);
190
- }
191
- };
192
- let syncing = false;
193
- let resyncRequested = false;
194
- const syncSubscriptions = (currentPages, baseArgs) => {
195
- if (syncing) {
196
- resyncRequested = true;
197
- return;
198
- }
199
- syncing = true;
200
- try {
201
- let pagesToSync = currentPages;
202
- let argsToSync = baseArgs;
203
- do {
204
- resyncRequested = false;
205
- syncPass(pagesToSync, argsToSync);
206
- const latestArgs = resolveArgs();
207
- if (latestArgs === "skip") {
208
- break;
209
- }
210
- pagesToSync = pages();
211
- argsToSync = latestArgs;
212
- } while (resyncRequested);
213
- } finally {
214
- syncing = false;
215
- }
216
- };
217
- const teardownAll = () => {
218
- for (const unsub of activeSubs.values()) {
219
- unsub();
220
- }
221
- activeSubs.clear();
222
- resultsByKey.clear();
223
- pendingPageKeys.clear();
224
- };
225
- createEffect(on(resolveArgs, (current) => {
226
- teardownAll();
227
- setPages(initialPages(initialNumItems));
228
- setPageResults([]);
229
- if (current !== "skip") {
230
- syncSubscriptions(pages(), current);
231
- rebuildPageResults(pages(), current);
232
- }
233
- onCleanup(teardownAll);
234
- }));
235
- createEffect(on(pages, (currentPages) => {
236
- const current = resolveArgs();
237
- if (current !== "skip") {
238
- syncSubscriptions(currentPages, current);
239
- rebuildPageResults(currentPages, current);
240
- }
241
- }));
242
- const status = createMemo(() => {
243
- const skipped = resolveArgs() === "skip";
244
- return derivePaginationStatus(skipped, pageResults()).status;
245
- });
246
- const loadMore = (numberItems) => {
247
- const current = resolveArgs();
248
- if (current === "skip") {
249
- return;
250
- }
251
- const {
252
- nextCursor,
253
- status: currentStatus
254
- } = derivePaginationStatus(false, pageResults());
255
- if (currentStatus !== "CanLoadMore") {
256
- return;
257
- }
258
- const next = applyLoadMore(pages(), nextCursor, numberItems);
259
- if (!next) {
260
- return;
261
- }
262
- const oldTail = pages().at(-1);
263
- const newPinnedPage = next.at(-2);
264
- if (oldTail && newPinnedPage) {
265
- const oldKey = buildPageKey(function_["__lunoraRef"], buildPageArgs(oldTail, current));
266
- const newKey = buildPageKey(function_["__lunoraRef"], buildPageArgs(newPinnedPage, current));
267
- if (oldKey !== newKey) {
268
- const carried = resultsByKey.get(oldKey);
269
- if (carried) {
270
- resultsByKey.set(newKey, carried);
271
- }
272
- }
273
- }
274
- setPages(next);
275
- };
276
- return {
277
- loadMore,
278
- pageResults,
279
- status
280
- };
281
- };
282
- const createPaginatedQuery = (function_, args, options) => {
283
- const {
284
- loadMore,
285
- pageResults,
286
- status
287
- } = createPaginatedCore(function_, args, options);
288
- const results = createMemo(() => {
289
- const items = [];
290
- for (const page of pageResults()) {
291
- if (page) {
292
- items.push(...page.page);
293
- }
294
- }
295
- return items;
296
- });
297
- const isLoading = createMemo(() => status() === "LoadingFirstPage" || status() === "LoadingMore");
298
- return {
299
- isLoading,
300
- loadMore,
301
- results,
302
- status
303
- };
304
- };
305
- const createInfiniteQuery = (function_, args, options) => {
306
- const {
307
- initialNumItems
308
- } = options;
309
- const {
310
- loadMore,
311
- pageResults,
312
- status
313
- } = createPaginatedCore(function_, args, options);
314
- const pages = createMemo(() => {
315
- const result = [];
316
- for (const page of pageResults()) {
317
- if (page) {
318
- result.push(page.page);
319
- }
320
- }
321
- return result;
322
- });
323
- const isLoading = createMemo(() => status() === "LoadingFirstPage");
324
- const hasNextPage = createMemo(() => status() === "CanLoadMore");
325
- const isFetchingNextPage = createMemo(() => status() === "LoadingMore");
326
- const fetchNextPage = (numberItems) => {
327
- loadMore(numberItems ?? initialNumItems);
328
- };
329
- return {
330
- fetchNextPage,
331
- hasNextPage,
332
- isFetchingNextPage,
333
- isLoading,
334
- pages,
335
- status
336
- };
337
- };
338
-
339
- export { createInfiniteQuery, createPaginatedQuery };
@@ -1,36 +0,0 @@
1
- import { createMutationRunner } from '@lunora/client';
2
- import { createSignal } from 'solid-js';
3
- import { useLunora } from './LunoraContext-C59PzHhN.mjs';
4
-
5
- const createMutationForClient = (client, function_) => {
6
- const [data, setData] = createSignal(void 0);
7
- const [error, setError] = createSignal(void 0);
8
- const [pending, setPending] = createSignal(false);
9
- const mutate = createMutationRunner(client, function_, {
10
- setError,
11
- setPending,
12
- setResult: (result) => {
13
- setData(() => result);
14
- setError(void 0);
15
- }
16
- });
17
- const reset = () => {
18
- setData(() => void 0);
19
- setError(void 0);
20
- };
21
- return {
22
- data,
23
- error,
24
- mutate,
25
- pending,
26
- reset
27
- };
28
- };
29
- const createMutation = (function_) => {
30
- const client = useLunora();
31
- return createMutationForClient({
32
- mutation: (reference, args, options) => client.mutation(reference, args, options)
33
- }, function_);
34
- };
35
-
36
- export { createMutation, createMutationForClient };
@@ -1,24 +0,0 @@
1
- import { createMutatorRunner } from '@lunora/client';
2
- import { createSignal } from 'solid-js';
3
-
4
- const createMutator = (handle) => {
5
- const [error, setError] = createSignal(void 0);
6
- const [pending, setPending] = createSignal(false);
7
- const {
8
- mutate,
9
- reset
10
- } = createMutatorRunner(handle, {
11
- setError,
12
- setPending
13
- });
14
- const isError = () => error() !== void 0;
15
- return {
16
- error,
17
- isError,
18
- mutate,
19
- pending,
20
- reset
21
- };
22
- };
23
-
24
- export { createMutator };
@@ -1,85 +0,0 @@
1
- import { createSignal, onMount, onCleanup } from 'solid-js';
2
- import { useLunora } from './LunoraContext-C59PzHhN.mjs';
3
-
4
- const randomSessionId = (prefix = "sess") => {
5
- if (typeof crypto !== "undefined") {
6
- if (typeof crypto.randomUUID === "function") {
7
- return crypto.randomUUID();
8
- }
9
- if (typeof crypto.getRandomValues === "function") {
10
- const bytes = crypto.getRandomValues(new Uint8Array(16));
11
- return `${prefix}-${Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("")}`;
12
- }
13
- }
14
- return `${prefix}-${Date.now().toString(36)}`;
15
- };
16
-
17
- const DEFAULT_INTERVAL_MS = 1e4;
18
- const createPresence = (roomId, options) => {
19
- const client = useLunora();
20
- const {
21
- heartbeat,
22
- intervalMs = DEFAULT_INTERVAL_MS,
23
- listPresent,
24
- shardKey
25
- } = options;
26
- const sessionId = options.sessionId ?? randomSessionId();
27
- const [present, setPresent] = createSignal(void 0);
28
- let latestData = options.data;
29
- const sendHeartbeat = () => {
30
- const args = {
31
- roomId,
32
- sessionId,
33
- ...latestData === void 0 ? {} : {
34
- data: latestData
35
- }
36
- };
37
- client.mutation(heartbeat, args, {
38
- shardKey
39
- }).catch(() => void 0);
40
- };
41
- const setData = (next) => {
42
- latestData = next;
43
- sendHeartbeat();
44
- };
45
- onMount(() => {
46
- sendHeartbeat();
47
- const intervalHandle = setInterval(sendHeartbeat, intervalMs);
48
- const onVisible = () => {
49
- if (typeof document !== "undefined" && document.visibilityState === "visible") {
50
- sendHeartbeat();
51
- }
52
- };
53
- if (typeof document !== "undefined") {
54
- document.addEventListener("visibilitychange", onVisible);
55
- }
56
- const releaseConnectionContext = client.acquireConnectionContext({
57
- roomId,
58
- sessionId
59
- }, {
60
- shardKey
61
- });
62
- const unsubscribe = client.subscribe(listPresent, {
63
- roomId
64
- }, (value) => {
65
- setPresent(() => value);
66
- }, {
67
- shardKey
68
- });
69
- onCleanup(() => {
70
- clearInterval(intervalHandle);
71
- if (typeof document !== "undefined") {
72
- document.removeEventListener("visibilitychange", onVisible);
73
- }
74
- releaseConnectionContext();
75
- unsubscribe();
76
- });
77
- });
78
- return {
79
- present,
80
- sessionId,
81
- setData
82
- };
83
- };
84
-
85
- export { createPresence };
@@ -1,28 +0,0 @@
1
- import { createQuerySubscription } from '@lunora/client/query';
2
- import { createSignal, createEffect, on, onCleanup } from 'solid-js';
3
- import { useLunora } from './LunoraContext-C59PzHhN.mjs';
4
-
5
- const createQuery = (function_, args, options = {}) => {
6
- const client = useLunora();
7
- const {
8
- shardKey
9
- } = options;
10
- const [value, setValue] = createSignal(void 0);
11
- const resolveArgs = () => typeof args === "function" ? args() : args;
12
- createEffect(on(resolveArgs, (current) => {
13
- const unsubscribe = createQuerySubscription(client, function_, current, {
14
- onData: (next) => {
15
- setValue(() => next);
16
- },
17
- onReset: () => {
18
- setValue(() => void 0);
19
- }
20
- }, {
21
- shardKey
22
- });
23
- onCleanup(unsubscribe);
24
- }));
25
- return value;
26
- };
27
-
28
- export { createQuery };
@@ -1,76 +0,0 @@
1
- import { evaluate } from '@lunora/ratelimit';
2
- import { createSignal, createMemo, onCleanup } from 'solid-js';
3
-
4
- const createRateLimit = (config, options = {}) => {
5
- const now = options.now ?? Date.now;
6
- const tickMs = options.tickMs ?? 1e3;
7
- let value;
8
- const [epoch, setEpoch] = createSignal(0);
9
- const bump = () => {
10
- setEpoch((n) => n + 1);
11
- };
12
- const status = createMemo(() => {
13
- const ts = now() + epoch() * 0;
14
- return evaluate(config, value, {
15
- consume: false,
16
- count: 1,
17
- now: ts,
18
- reserve: false
19
- }).status;
20
- });
21
- let intervalHandle;
22
- const stopInterval = () => {
23
- if (intervalHandle !== void 0) {
24
- clearInterval(intervalHandle);
25
- intervalHandle = void 0;
26
- }
27
- };
28
- const startIntervalIfThrottled = () => {
29
- if (status().ok || intervalHandle !== void 0) {
30
- return;
31
- }
32
- intervalHandle = setInterval(() => {
33
- bump();
34
- if (status().ok) {
35
- stopInterval();
36
- }
37
- }, tickMs);
38
- };
39
- onCleanup(stopInterval);
40
- startIntervalIfThrottled();
41
- const consume = (count = 1) => {
42
- const result = evaluate(config, value, {
43
- consume: true,
44
- count,
45
- now: now(),
46
- reserve: false
47
- });
48
- if (result.value !== void 0) {
49
- value = result.value;
50
- }
51
- bump();
52
- startIntervalIfThrottled();
53
- return result.status;
54
- };
55
- const check = (count = 1) => evaluate(config, value, {
56
- consume: false,
57
- count,
58
- now: now(),
59
- reserve: false
60
- }).status.ok;
61
- const reset = () => {
62
- value = void 0;
63
- stopInterval();
64
- bump();
65
- };
66
- return {
67
- check,
68
- consume,
69
- disabled: () => !status().ok,
70
- ok: () => status().ok,
71
- reset,
72
- retryAfter: () => status().retryAfter
73
- };
74
- };
75
-
76
- export { createRateLimit };