@stream-io/feeds-client 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 (96) hide show
  1. package/@react-bindings/index.ts +2 -0
  2. package/CHANGELOG.md +44 -0
  3. package/LICENSE +219 -0
  4. package/README.md +9 -0
  5. package/dist/@react-bindings/hooks/useComments.d.ts +12 -0
  6. package/dist/@react-bindings/hooks/useStateStore.d.ts +3 -0
  7. package/dist/@react-bindings/index.d.ts +2 -0
  8. package/dist/index-react-bindings.browser.cjs +56 -0
  9. package/dist/index-react-bindings.browser.cjs.map +1 -0
  10. package/dist/index-react-bindings.browser.js +53 -0
  11. package/dist/index-react-bindings.browser.js.map +1 -0
  12. package/dist/index-react-bindings.node.cjs +56 -0
  13. package/dist/index-react-bindings.node.cjs.map +1 -0
  14. package/dist/index-react-bindings.node.js +53 -0
  15. package/dist/index-react-bindings.node.js.map +1 -0
  16. package/dist/index.browser.cjs +5799 -0
  17. package/dist/index.browser.cjs.map +1 -0
  18. package/dist/index.browser.js +5782 -0
  19. package/dist/index.browser.js.map +1 -0
  20. package/dist/index.d.ts +13 -0
  21. package/dist/index.node.cjs +5799 -0
  22. package/dist/index.node.cjs.map +1 -0
  23. package/dist/index.node.js +5782 -0
  24. package/dist/index.node.js.map +1 -0
  25. package/dist/src/Feed.d.ts +109 -0
  26. package/dist/src/FeedsClient.d.ts +63 -0
  27. package/dist/src/ModerationClient.d.ts +3 -0
  28. package/dist/src/common/ActivitySearchSource.d.ts +17 -0
  29. package/dist/src/common/ApiClient.d.ts +20 -0
  30. package/dist/src/common/BaseSearchSource.d.ts +87 -0
  31. package/dist/src/common/ConnectionIdManager.d.ts +11 -0
  32. package/dist/src/common/EventDispatcher.d.ts +11 -0
  33. package/dist/src/common/FeedSearchSource.d.ts +17 -0
  34. package/dist/src/common/Poll.d.ts +34 -0
  35. package/dist/src/common/SearchController.d.ts +41 -0
  36. package/dist/src/common/StateStore.d.ts +124 -0
  37. package/dist/src/common/TokenManager.d.ts +29 -0
  38. package/dist/src/common/UserSearchSource.d.ts +17 -0
  39. package/dist/src/common/gen-imports.d.ts +2 -0
  40. package/dist/src/common/rate-limit.d.ts +2 -0
  41. package/dist/src/common/real-time/StableWSConnection.d.ts +144 -0
  42. package/dist/src/common/real-time/event-models.d.ts +36 -0
  43. package/dist/src/common/types.d.ts +29 -0
  44. package/dist/src/common/utils.d.ts +54 -0
  45. package/dist/src/gen/feeds/FeedApi.d.ts +26 -0
  46. package/dist/src/gen/feeds/FeedsApi.d.ts +237 -0
  47. package/dist/src/gen/model-decoders/decoders.d.ts +3 -0
  48. package/dist/src/gen/model-decoders/event-decoder-mapping.d.ts +6 -0
  49. package/dist/src/gen/models/index.d.ts +3437 -0
  50. package/dist/src/gen/moderation/ModerationApi.d.ts +21 -0
  51. package/dist/src/gen-imports.d.ts +3 -0
  52. package/dist/src/state-updates/activity-reaction-utils.d.ts +10 -0
  53. package/dist/src/state-updates/activity-utils.d.ts +13 -0
  54. package/dist/src/state-updates/bookmark-utils.d.ts +14 -0
  55. package/dist/src/types-internal.d.ts +4 -0
  56. package/dist/src/types.d.ts +13 -0
  57. package/dist/src/utils.d.ts +1 -0
  58. package/dist/tsconfig.tsbuildinfo +1 -0
  59. package/index.ts +13 -0
  60. package/package.json +85 -0
  61. package/src/Feed.ts +1070 -0
  62. package/src/FeedsClient.ts +352 -0
  63. package/src/ModerationClient.ts +3 -0
  64. package/src/common/ActivitySearchSource.ts +46 -0
  65. package/src/common/ApiClient.ts +197 -0
  66. package/src/common/BaseSearchSource.ts +238 -0
  67. package/src/common/ConnectionIdManager.ts +51 -0
  68. package/src/common/EventDispatcher.ts +52 -0
  69. package/src/common/FeedSearchSource.ts +94 -0
  70. package/src/common/Poll.ts +313 -0
  71. package/src/common/SearchController.ts +152 -0
  72. package/src/common/StateStore.ts +314 -0
  73. package/src/common/TokenManager.ts +112 -0
  74. package/src/common/UserSearchSource.ts +93 -0
  75. package/src/common/gen-imports.ts +2 -0
  76. package/src/common/rate-limit.ts +23 -0
  77. package/src/common/real-time/StableWSConnection.ts +761 -0
  78. package/src/common/real-time/event-models.ts +38 -0
  79. package/src/common/types.ts +40 -0
  80. package/src/common/utils.ts +194 -0
  81. package/src/gen/feeds/FeedApi.ts +129 -0
  82. package/src/gen/feeds/FeedsApi.ts +2192 -0
  83. package/src/gen/model-decoders/decoders.ts +1877 -0
  84. package/src/gen/model-decoders/event-decoder-mapping.ts +150 -0
  85. package/src/gen/models/index.ts +5882 -0
  86. package/src/gen/moderation/ModerationApi.ts +270 -0
  87. package/src/gen-imports.ts +3 -0
  88. package/src/state-updates/activity-reaction-utils.test.ts +348 -0
  89. package/src/state-updates/activity-reaction-utils.ts +107 -0
  90. package/src/state-updates/activity-utils.test.ts +257 -0
  91. package/src/state-updates/activity-utils.ts +80 -0
  92. package/src/state-updates/bookmark-utils.test.ts +383 -0
  93. package/src/state-updates/bookmark-utils.ts +157 -0
  94. package/src/types-internal.ts +5 -0
  95. package/src/types.ts +20 -0
  96. package/src/utils.ts +4 -0
@@ -0,0 +1,38 @@
1
+ import { OwnUser } from '../../gen/models';
2
+
3
+ export interface ConnectionChangedEvent {
4
+ type: 'connection.changed';
5
+ online: boolean;
6
+ }
7
+
8
+ /**
9
+ * This event is sent when the WS connection is established and authenticated, this event contains the full user object as it is stored on the server
10
+ * @export
11
+ * @interface ConnectedEvent
12
+ */
13
+ export interface ConnectedEvent {
14
+ /**
15
+ * The connection_id for this client
16
+ * @type {string}
17
+ * @memberof ConnectedEvent
18
+ */
19
+ connection_id: string;
20
+ /**
21
+ *
22
+ * @type {string}
23
+ * @memberof ConnectedEvent
24
+ */
25
+ created_at: string;
26
+ /**
27
+ *
28
+ * @type {OwnUserResponse}
29
+ * @memberof ConnectedEvent
30
+ */
31
+ me: OwnUser;
32
+ /**
33
+ * The type of event: "connection.ok" in this case
34
+ * @type {string}
35
+ * @memberof ConnectedEvent
36
+ */
37
+ type: string;
38
+ }
@@ -0,0 +1,40 @@
1
+ export type FeedsClientOptions = {
2
+ base_url?: string;
3
+ timeout?: number;
4
+ };
5
+
6
+ export type RateLimit = {
7
+ rate_limit?: number;
8
+ rate_limit_remaining?: number;
9
+ rate_limit_reset?: Date;
10
+ };
11
+
12
+ export type RequestMetadata = {
13
+ response_headers: Record<string, string>;
14
+ rate_limit: RateLimit;
15
+ response_code: number;
16
+ client_request_id: string;
17
+ };
18
+
19
+ export type StreamResponse<T> = T & {
20
+ metadata: RequestMetadata;
21
+ };
22
+
23
+ export class StreamApiError extends Error {
24
+ public name = 'StreamApiError';
25
+ constructor(
26
+ message: string,
27
+ public metadata?: Partial<RequestMetadata>,
28
+ public code?: number,
29
+ errorOptions?: ErrorOptions,
30
+ ) {
31
+ super(message, errorOptions);
32
+ }
33
+ }
34
+
35
+ export type LogLevel = 'trace' | 'debug' | 'info' | 'warn' | 'error';
36
+
37
+ export interface NetworkChangedEvent {
38
+ type: 'network.changed';
39
+ online: boolean;
40
+ }
@@ -0,0 +1,194 @@
1
+ export const sleep = (m: number): Promise<void> =>
2
+ new Promise((resolve) => setTimeout(resolve, m));
3
+
4
+ export function isFunction<T>(value: Function | T): value is Function {
5
+ return (
6
+ value &&
7
+ (Object.prototype.toString.call(value) === '[object Function]' ||
8
+ typeof value === 'function' ||
9
+ value instanceof Function)
10
+ );
11
+ }
12
+
13
+ /**
14
+ * A map of known error codes.
15
+ */
16
+ export const KnownCodes = {
17
+ TOKEN_EXPIRED: 40,
18
+ WS_CLOSED_SUCCESS: 1000,
19
+ WS_CLOSED_ABRUPTLY: 1006,
20
+ WS_POLICY_VIOLATION: 1008,
21
+ };
22
+
23
+ /**
24
+ * retryInterval - A retry interval which increases acc to number of failures
25
+ *
26
+ * @return {number} Duration to wait in milliseconds
27
+ */
28
+ export function retryInterval(numberOfFailures: number) {
29
+ // try to reconnect in 0.25-5 seconds (random to spread out the load from failures)
30
+ const max = Math.min(500 + numberOfFailures * 2000, 5000);
31
+ const min = Math.min(Math.max(250, (numberOfFailures - 1) * 2000), 5000);
32
+ return Math.floor(Math.random() * (max - min) + min);
33
+ }
34
+
35
+ export function randomId() {
36
+ return generateUUIDv4();
37
+ }
38
+
39
+ // https://tools.ietf.org/html/rfc4122
40
+ export function generateUUIDv4() {
41
+ const bytes = getRandomBytes(16);
42
+ bytes[6] = (bytes[6] & 0x0f) | 0x40; // version
43
+ bytes[8] = (bytes[8] & 0xbf) | 0x80; // variant
44
+
45
+ return (
46
+ hex(bytes.subarray(0, 4)) +
47
+ '-' +
48
+ hex(bytes.subarray(4, 6)) +
49
+ '-' +
50
+ hex(bytes.subarray(6, 8)) +
51
+ '-' +
52
+ hex(bytes.subarray(8, 10)) +
53
+ '-' +
54
+ hex(bytes.subarray(10, 16))
55
+ );
56
+ }
57
+
58
+ function hex(bytes: Uint8Array): string {
59
+ let s = '';
60
+ for (let i = 0; i < bytes.length; i++) {
61
+ s += bytes[i].toString(16).padStart(2, '0');
62
+ }
63
+ return s;
64
+ }
65
+
66
+ function getRandomValuesWithMathRandom(bytes: Uint8Array): void {
67
+ const max = Math.pow(2, (8 * bytes.byteLength) / bytes.length);
68
+ for (let i = 0; i < bytes.length; i++) {
69
+ bytes[i] = Math.random() * max;
70
+ }
71
+ }
72
+ declare const msCrypto: Crypto;
73
+
74
+ const getRandomValues = (() => {
75
+ if (typeof crypto?.getRandomValues !== 'undefined') {
76
+ return crypto.getRandomValues.bind(crypto);
77
+ } else if (typeof msCrypto !== 'undefined') {
78
+ return msCrypto.getRandomValues.bind(msCrypto);
79
+ } else {
80
+ return getRandomValuesWithMathRandom;
81
+ }
82
+ })();
83
+
84
+ function getRandomBytes(length: number): Uint8Array {
85
+ const bytes = new Uint8Array(length);
86
+ getRandomValues(bytes);
87
+ return bytes;
88
+ }
89
+
90
+ /**
91
+ * listenForConnectionChanges - Adds an event listener fired on browser going online or offline
92
+ */
93
+ export function addConnectionEventListeners(cb: (e: Event) => void) {
94
+ if (typeof window !== 'undefined' && window.addEventListener) {
95
+ window.addEventListener('offline', cb);
96
+ window.addEventListener('online', cb);
97
+ }
98
+ }
99
+
100
+ export function removeConnectionEventListeners(cb: (e: Event) => void) {
101
+ if (typeof window !== 'undefined' && window.removeEventListener) {
102
+ window.removeEventListener('offline', cb);
103
+ window.removeEventListener('online', cb);
104
+ }
105
+ }
106
+
107
+ export const streamDevToken = (userId: string) => {
108
+ return [
109
+ 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9', // {"alg": "HS256", "typ": "JWT"}
110
+ window.btoa(JSON.stringify({ user_id: userId })),
111
+ 'devtoken', // hardcoded signature
112
+ ].join('.');
113
+ };
114
+
115
+
116
+ export interface DebouncedFunc<T extends (...args: any[]) => any> {
117
+ /**
118
+ * Call the original function, but applying the debounce rules.
119
+ *
120
+ * If the debounced function can be run immediately, this calls it and returns its return
121
+ * value.
122
+ *
123
+ * Otherwise, it returns the return value of the last invocation, or undefined if the debounced
124
+ * function was not invoked yet.
125
+ */
126
+ (...args: Parameters<T>): ReturnType<T> | undefined;
127
+
128
+ /**
129
+ * Throw away any pending invocation of the debounced function.
130
+ */
131
+ cancel(): void;
132
+
133
+ /**
134
+ * If there is a pending invocation of the debounced function, invoke it immediately and return
135
+ * its return value.
136
+ *
137
+ * Otherwise, return the value from the last invocation, or undefined if the debounced function
138
+ * was never invoked.
139
+ */
140
+ flush(): ReturnType<T> | undefined;
141
+ }
142
+
143
+ export const debounce = <T extends (...args: any[]) => any>(
144
+ fn: T,
145
+ timeout = 0,
146
+ {
147
+ leading = false,
148
+ trailing = true,
149
+ }: { leading?: boolean; trailing?: boolean } = {},
150
+ ): DebouncedFunc<T> => {
151
+ let runningTimeout: null | NodeJS.Timeout = null;
152
+ let argsForTrailingExecution: Parameters<T> | null = null;
153
+ let lastResult: ReturnType<T> | undefined;
154
+
155
+ const debouncedFn = (...args: Parameters<T>) => {
156
+ if (runningTimeout) {
157
+ clearTimeout(runningTimeout);
158
+ } else if (leading) {
159
+ lastResult = fn(...args);
160
+ }
161
+ if (trailing) argsForTrailingExecution = args;
162
+
163
+ const timeoutHandler = () => {
164
+ if (argsForTrailingExecution) {
165
+ lastResult = fn(...argsForTrailingExecution);
166
+ argsForTrailingExecution = null;
167
+ }
168
+ runningTimeout = null;
169
+ };
170
+
171
+ runningTimeout = setTimeout(timeoutHandler, timeout);
172
+ return lastResult;
173
+ };
174
+
175
+ debouncedFn.cancel = () => {
176
+ if (runningTimeout) clearTimeout(runningTimeout);
177
+ };
178
+
179
+ debouncedFn.flush = () => {
180
+ if (runningTimeout) {
181
+ clearTimeout(runningTimeout);
182
+ runningTimeout = null;
183
+ if (argsForTrailingExecution) {
184
+ lastResult = fn(...argsForTrailingExecution);
185
+ }
186
+ }
187
+ return lastResult;
188
+ };
189
+ return debouncedFn;
190
+ };
191
+
192
+ export const capitalize = <T extends string>(s: T) => {
193
+ return `${s.charAt(0).toLocaleUpperCase()}${s.slice(1)}` as Capitalize<T>;
194
+ };
@@ -0,0 +1,129 @@
1
+ import { StreamResponse, FeedsApi } from '../../gen-imports';
2
+ import {
3
+ AcceptFeedMemberInviteRequest,
4
+ AcceptFeedMemberInviteResponse,
5
+ DeleteFeedResponse,
6
+ GetOrCreateFeedRequest,
7
+ GetOrCreateFeedResponse,
8
+ MarkActivityRequest,
9
+ PinActivityRequest,
10
+ PinActivityResponse,
11
+ QueryFeedMembersRequest,
12
+ QueryFeedMembersResponse,
13
+ RejectFeedMemberInviteRequest,
14
+ RejectFeedMemberInviteResponse,
15
+ Response,
16
+ UnpinActivityResponse,
17
+ UpdateFeedMembersRequest,
18
+ UpdateFeedMembersResponse,
19
+ UpdateFeedRequest,
20
+ UpdateFeedResponse,
21
+ } from '../models';
22
+
23
+ export class FeedApi {
24
+ constructor(
25
+ protected feedsApi: FeedsApi,
26
+ public readonly group: string,
27
+ public readonly id: string,
28
+ ) {}
29
+
30
+ delete(request?: {
31
+ hard_delete?: boolean;
32
+ }): Promise<StreamResponse<DeleteFeedResponse>> {
33
+ return this.feedsApi.deleteFeed({
34
+ feed_id: this.id,
35
+ feed_group_id: this.group,
36
+ ...request,
37
+ });
38
+ }
39
+
40
+ getOrCreate(
41
+ request?: GetOrCreateFeedRequest & { connection_id?: string },
42
+ ): Promise<StreamResponse<GetOrCreateFeedResponse>> {
43
+ return this.feedsApi.getOrCreateFeed({
44
+ feed_id: this.id,
45
+ feed_group_id: this.group,
46
+ ...request,
47
+ });
48
+ }
49
+
50
+ update(
51
+ request?: UpdateFeedRequest,
52
+ ): Promise<StreamResponse<UpdateFeedResponse>> {
53
+ return this.feedsApi.updateFeed({
54
+ feed_id: this.id,
55
+ feed_group_id: this.group,
56
+ ...request,
57
+ });
58
+ }
59
+
60
+ markActivity(
61
+ request?: MarkActivityRequest,
62
+ ): Promise<StreamResponse<Response>> {
63
+ return this.feedsApi.markActivity({
64
+ feed_id: this.id,
65
+ feed_group_id: this.group,
66
+ ...request,
67
+ });
68
+ }
69
+
70
+ unpinActivity(request: {
71
+ activity_id: string;
72
+ }): Promise<StreamResponse<UnpinActivityResponse>> {
73
+ return this.feedsApi.unpinActivity({
74
+ feed_id: this.id,
75
+ feed_group_id: this.group,
76
+ ...request,
77
+ });
78
+ }
79
+
80
+ pinActivity(
81
+ request: PinActivityRequest & { activity_id: string },
82
+ ): Promise<StreamResponse<PinActivityResponse>> {
83
+ return this.feedsApi.pinActivity({
84
+ feed_id: this.id,
85
+ feed_group_id: this.group,
86
+ ...request,
87
+ });
88
+ }
89
+
90
+ updateFeedMembers(
91
+ request: UpdateFeedMembersRequest,
92
+ ): Promise<StreamResponse<UpdateFeedMembersResponse>> {
93
+ return this.feedsApi.updateFeedMembers({
94
+ feed_id: this.id,
95
+ feed_group_id: this.group,
96
+ ...request,
97
+ });
98
+ }
99
+
100
+ acceptFeedMemberInvite(
101
+ request?: AcceptFeedMemberInviteRequest,
102
+ ): Promise<StreamResponse<AcceptFeedMemberInviteResponse>> {
103
+ return this.feedsApi.acceptFeedMemberInvite({
104
+ feed_id: this.id,
105
+ feed_group_id: this.group,
106
+ ...request,
107
+ });
108
+ }
109
+
110
+ queryFeedMembers(
111
+ request?: QueryFeedMembersRequest,
112
+ ): Promise<StreamResponse<QueryFeedMembersResponse>> {
113
+ return this.feedsApi.queryFeedMembers({
114
+ feed_id: this.id,
115
+ feed_group_id: this.group,
116
+ ...request,
117
+ });
118
+ }
119
+
120
+ rejectFeedMemberInvite(
121
+ request?: RejectFeedMemberInviteRequest,
122
+ ): Promise<StreamResponse<RejectFeedMemberInviteResponse>> {
123
+ return this.feedsApi.rejectFeedMemberInvite({
124
+ feed_id: this.id,
125
+ feed_group_id: this.group,
126
+ ...request,
127
+ });
128
+ }
129
+ }