docpouch-client 0.8.15 → 0.8.17

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.
@@ -0,0 +1,342 @@
1
+ import { Socket } from "socket.io-client";
2
+ /**
3
+ * Client for interacting with docPouch API.
4
+ */
5
+ export default class docPouchClient {
6
+ /**
7
+ * The base URL of the server.
8
+ *
9
+ * @type {string}
10
+ */
11
+ baseUrl: string;
12
+ /**
13
+ * Socket.IO socket instance for real-time communication with the server.
14
+ *
15
+ * @type {Socket}
16
+ */
17
+ socket: Socket;
18
+ /**
19
+ * Callback function to handle socket events.
20
+ *
21
+ * @type {(event: I_EventString, data: I_WsMessage) => void}
22
+ */
23
+ callbackFunction: ((event: I_EventString, data: I_WsMessage) => void) | undefined;
24
+ /**
25
+ * Flag indicating whether real-time synchronization is enabled.
26
+ *
27
+ * @type {boolean}
28
+ */
29
+ realTimeSync: boolean;
30
+ /**
31
+ * Authentication token used to authorize requests.
32
+ *
33
+ * @private
34
+ * @type {string | null}
35
+ */
36
+ private authToken;
37
+ /**
38
+ * Flag indicating whether a connection attempt is in progress.
39
+ *
40
+ * @private
41
+ * @type {boolean}
42
+ */
43
+ private connectionInProgress;
44
+ /**
45
+ * Creates an instance of docPouchClient.
46
+ *
47
+ * @param {string} host - The base URL for the server.
48
+ * @param {number} [port=80] - The port number to connect to (default is 80).
49
+ * @param {(event: I_EventString, data: I_WsMessage) => void} [callback] - Optional callback function for socket events.
50
+ */
51
+ constructor(host: string, port?: number, callback?: (event: I_EventString, data: I_WsMessage) => void);
52
+ /**
53
+ * Sets the real-time synchronization status.
54
+ *
55
+ * @param {boolean} newRealTimeSync - The new real-time sync setting (true/false).
56
+ */
57
+ setRealTimeSync(newRealTimeSync: boolean): void;
58
+ /**
59
+ * Authenticates a user and stores the returned token for subsequent requests.
60
+ *
61
+ * @param {I_UserLogin} credentials - Username and password credentials.
62
+ * @returns {Promise<I_LoginResponse | null>} Login payload when successful, otherwise null.
63
+ */
64
+ login(credentials: I_UserLogin): Promise<I_LoginResponse | null>;
65
+ /**
66
+ * Retrieves all users visible to the authenticated user.
67
+ *
68
+ * @returns {Promise<I_UserEntry[]>} A list of user entries.
69
+ */
70
+ listUsers(): Promise<I_UserEntry[]>;
71
+ /**
72
+ * Updates a user by ID.
73
+ *
74
+ * @param {string} userID - The ID of the user to update.
75
+ * @param {I_UserUpdate} userData - Partial user fields to update.
76
+ * @returns {Promise<void>}
77
+ */
78
+ updateUser(userID: string, userData: I_UserUpdate): Promise<void>;
79
+ /**
80
+ * Creates a new user.
81
+ *
82
+ * @param {I_UserCreation} userData - Data used to create the user.
83
+ * @returns {Promise<I_UserDisplay>} The created user payload returned by the API.
84
+ */
85
+ createUser(userData: I_UserCreation): Promise<I_UserDisplay>;
86
+ /**
87
+ * Removes a user by ID.
88
+ *
89
+ * @param {string} userID - The ID of the user to remove.
90
+ * @returns {Promise<void>}
91
+ */
92
+ removeUser(userID: string): Promise<void>;
93
+ /**
94
+ * Creates a new document.
95
+ *
96
+ * @param {I_DocumentEntry} document - The document payload to create.
97
+ * @returns {Promise<I_DocumentEntry>} The created document.
98
+ */
99
+ createDocument(document: I_DocumentEntry): Promise<I_DocumentEntry>;
100
+ /**
101
+ * Retrieves all documents visible to the authenticated user.
102
+ *
103
+ * @returns {Promise<I_DocumentEntry[]>} A list of document entries.
104
+ */
105
+ listDocuments(): Promise<I_DocumentEntry[]>;
106
+ /**
107
+ * Fetches documents matching a query object.
108
+ *
109
+ * @param {I_DocumentQuery} queryObject - Query fields used for filtering.
110
+ * @returns {Promise<I_DocumentEntry[]>} Matching documents.
111
+ */
112
+ fetchDocuments(queryObject: I_DocumentQuery): Promise<I_DocumentEntry[]>;
113
+ /**
114
+ * Updates a document by ID.
115
+ *
116
+ * @param {string} documentID - The ID of the document to update.
117
+ * @param {I_DocumentEntry} documentData - Updated document payload.
118
+ * @returns {Promise<void>}
119
+ */
120
+ updateDocument(documentID: string, documentData: I_DocumentEntry): Promise<void>;
121
+ /**
122
+ * Removes a document by ID.
123
+ *
124
+ * @param {string} documentID - The ID of the document to remove.
125
+ * @returns {Promise<void>}
126
+ */
127
+ removeDocument(documentID: string): Promise<void>;
128
+ /**
129
+ * Creates a new data structure.
130
+ *
131
+ * @param {I_StructureCreation} structure - Data structure payload to create.
132
+ * @returns {Promise<I_DataStructure>} The created data structure.
133
+ */
134
+ createStructure(structure: I_StructureCreation): Promise<I_DataStructure>;
135
+ /**
136
+ * Retrieves all data structures.
137
+ *
138
+ * @returns {Promise<I_DataStructure[]>} A list of data structures.
139
+ */
140
+ getStructures(): Promise<I_DataStructure[]>;
141
+ /**
142
+ * Updates a data structure by ID.
143
+ *
144
+ * @param {string} structureID - The ID of the structure to update.
145
+ * @param {I_DataStructure} structureData - Updated structure payload.
146
+ * @returns {Promise<void>}
147
+ */
148
+ updateStructure(structureID: string, structureData: I_DataStructure): Promise<void>;
149
+ /**
150
+ * Removes a data structure by ID.
151
+ *
152
+ * @param {string} structureID - The ID of the structure to remove.
153
+ * @returns {Promise<void>}
154
+ */
155
+ removeStructure(structureID: string): Promise<void>;
156
+ /**
157
+ * Creates or writes a document type.
158
+ *
159
+ * @param {I_DocumentType} type - The type payload.
160
+ * @returns {Promise<I_DocumentType>} The created or updated type.
161
+ */
162
+ createType(type: I_DocumentType): Promise<I_DocumentType>;
163
+ /**
164
+ * Removes a document type by ID.
165
+ *
166
+ * @param {string} typeID - The ID of the type to remove.
167
+ * @returns {Promise<void>}
168
+ */
169
+ removeType(typeID: string): Promise<void>;
170
+ /**
171
+ * Retrieves all document types.
172
+ *
173
+ * @returns {Promise<I_DocumentType[]>} A list of document types.
174
+ */
175
+ getTypes(): Promise<I_DocumentType[]>;
176
+ /**
177
+ * Updates a document type.
178
+ *
179
+ * @param {I_DocumentType} updatedType - The full type payload to persist.
180
+ * @returns {Promise<void>}
181
+ */
182
+ updateType(updatedType: I_DocumentType): Promise<void>;
183
+ /**
184
+ * Sets or clears the authentication token used for API and WebSocket auth.
185
+ *
186
+ * @param {string | null} token - Bearer token to use, or null to clear it.
187
+ */
188
+ setToken(token: string | null): void;
189
+ /**
190
+ * Returns the package version of this client.
191
+ *
192
+ * @returns {string} The semantic version string.
193
+ */
194
+ getVersion(): string;
195
+ /**
196
+ * Logs socket diagnostics and attempts a reconnect when possible.
197
+ *
198
+ * @returns {void}
199
+ */
200
+ debugSocketConnection(): void;
201
+ /**
202
+ * Sets up permanent socket listeners for the client.
203
+ *
204
+ * @private
205
+ */
206
+ private setupPermanentSocketListeners;
207
+ /**
208
+ * Initializes the WebSocket connection with the server.
209
+ *
210
+ * @private
211
+ */
212
+ private initWebSocket;
213
+ /**
214
+ * Sends an HTTP request to the configured docPouch backend.
215
+ *
216
+ * @template T
217
+ * @param {string} endpoint - Relative API endpoint (with or without leading slash).
218
+ * @param {string} method - HTTP method.
219
+ * @param {any} [body] - Optional JSON body.
220
+ * @param {boolean} [requiresAuth=true] - Whether the Authorization header should be attached.
221
+ * @returns {Promise<T>} Parsed JSON response body.
222
+ * @private
223
+ */
224
+ private request;
225
+ }
226
+ export interface I_UserEntry extends I_UserCreation {
227
+ _id: string;
228
+ }
229
+ export interface I_UserLogin {
230
+ name: string;
231
+ password: string;
232
+ }
233
+ export interface I_UserCreation {
234
+ name: string;
235
+ password: string;
236
+ email?: string;
237
+ department: string;
238
+ group: string;
239
+ isAdmin: boolean;
240
+ }
241
+ export interface I_UserUpdate {
242
+ _id?: string;
243
+ name?: string;
244
+ password?: string;
245
+ email?: string;
246
+ department?: string;
247
+ group?: string;
248
+ isAdmin?: boolean;
249
+ }
250
+ export interface I_UserDisplay {
251
+ _id: string;
252
+ username: string;
253
+ department: string;
254
+ group: string;
255
+ email?: string;
256
+ }
257
+ export interface I_LoginResponse {
258
+ token: string;
259
+ isAdmin: boolean;
260
+ userName: string;
261
+ }
262
+ export interface I_DocumentEntry extends I_DocumentCreationOwned {
263
+ _id: string;
264
+ }
265
+ export interface I_DocumentCreation {
266
+ title: string;
267
+ description?: string;
268
+ type: number;
269
+ subType: number;
270
+ content: any;
271
+ shareWithGroup: boolean;
272
+ shareWithDepartment: boolean;
273
+ public: boolean;
274
+ }
275
+ export interface I_DocumentCreationOwned extends I_DocumentCreation {
276
+ owner: string;
277
+ }
278
+ export interface I_DocumentUpdate extends I_DocumentQuery {
279
+ content?: any;
280
+ description?: string;
281
+ }
282
+ export interface I_DocumentQuery {
283
+ _id?: string;
284
+ owner?: string;
285
+ title?: string;
286
+ type?: number;
287
+ subType?: number;
288
+ shareWithGroup?: boolean;
289
+ shareWithDepartment?: boolean;
290
+ public?: boolean;
291
+ }
292
+ export interface I_DataStructure {
293
+ _id?: string | undefined;
294
+ name: string;
295
+ description: string;
296
+ fields: I_StructureField[];
297
+ }
298
+ export interface I_StructureField {
299
+ name: string;
300
+ type: string;
301
+ items?: string;
302
+ }
303
+ export interface I_StructureEntry {
304
+ _id?: string;
305
+ name: string;
306
+ description: string;
307
+ fields: I_StructureField[];
308
+ }
309
+ export interface I_StructureCreation {
310
+ name: string;
311
+ description?: string;
312
+ fields: I_StructureField[];
313
+ }
314
+ export interface I_StructureUpdate {
315
+ _id?: string;
316
+ name?: string;
317
+ description?: string;
318
+ fields?: I_StructureField[];
319
+ }
320
+ export interface I_DocumentType {
321
+ _id?: string;
322
+ type: number;
323
+ subType: number;
324
+ name: string;
325
+ description?: string;
326
+ defaultStructureID?: string;
327
+ }
328
+ export type I_EventString = 'heartbeatPong' | "heartbeatPing" | "newDocument" | "newStructure" | "newUser" | "newType" | "removedID" | "changedDocument" | "changedStructure" | "changedUser" | "changedType" | "removedUser" | "removedStructure" | "removedDocument" | "removedType";
329
+ export interface I_WsMessage {
330
+ newDocument?: I_DocumentEntry;
331
+ newStructure?: I_StructureEntry;
332
+ newUser?: I_UserEntry;
333
+ removedID?: string;
334
+ changedDocument?: I_DocumentUpdate;
335
+ changedStructure?: I_StructureUpdate;
336
+ changedUser?: I_UserUpdate;
337
+ confirmSubscription?: boolean;
338
+ confirmUnsubscription?: boolean;
339
+ heartbeatPing?: number;
340
+ heartbeatPong?: number;
341
+ newType?: I_DocumentType;
342
+ }
package/dist/index.js ADDED
@@ -0,0 +1,441 @@
1
+ import { io } from "socket.io-client";
2
+ import packetJson from '../package.json';
3
+ /**
4
+ * Client for interacting with docPouch API.
5
+ */
6
+ export default class docPouchClient {
7
+ /**
8
+ * Creates an instance of docPouchClient.
9
+ *
10
+ * @param {string} host - The base URL for the server.
11
+ * @param {number} [port=80] - The port number to connect to (default is 80).
12
+ * @param {(event: I_EventString, data: I_WsMessage) => void} [callback] - Optional callback function for socket events.
13
+ */
14
+ constructor(host, port = 80, callback) {
15
+ /**
16
+ * Flag indicating whether real-time synchronization is enabled.
17
+ *
18
+ * @type {boolean}
19
+ */
20
+ this.realTimeSync = false;
21
+ /**
22
+ * Authentication token used to authorize requests.
23
+ *
24
+ * @private
25
+ * @type {string | null}
26
+ */
27
+ this.authToken = null;
28
+ /**
29
+ * Flag indicating whether a connection attempt is in progress.
30
+ *
31
+ * @private
32
+ * @type {boolean}
33
+ */
34
+ this.connectionInProgress = false;
35
+ this.baseUrl = host;
36
+ const socketUrl = host.includes('://') ? host : `https://${host}`;
37
+ const socketUrlWithPort = socketUrl.includes(':') && !socketUrl.endsWith(':')
38
+ ? socketUrl
39
+ : `${socketUrl}:${port}`;
40
+ console.log(`Initializing Socket.IO with URL: ${socketUrlWithPort}, path: /socket.io`);
41
+ this.socket = io(`${socketUrlWithPort}`, {
42
+ autoConnect: false,
43
+ transports: ['websocket'], // Try websocket only first
44
+ reconnection: true,
45
+ reconnectionAttempts: 5,
46
+ reconnectionDelay: 1000,
47
+ forceNew: true, // Force a new connection
48
+ auth: {
49
+ token: null // Will be set later
50
+ },
51
+ path: '/socket.io'
52
+ });
53
+ this.callbackFunction = callback;
54
+ this.setupPermanentSocketListeners();
55
+ }
56
+ /**
57
+ * Sets the real-time synchronization status.
58
+ *
59
+ * @param {boolean} newRealTimeSync - The new real-time sync setting (true/false).
60
+ */
61
+ setRealTimeSync(newRealTimeSync) {
62
+ console.log(`Setting realtime sync to: ${newRealTimeSync}. Current setting: ${this.realTimeSync}`);
63
+ // Skip if the setting isn't changing
64
+ if (newRealTimeSync === this.realTimeSync) {
65
+ console.log("Realtime sync setting unchanged, skipping");
66
+ return;
67
+ }
68
+ this.realTimeSync = newRealTimeSync;
69
+ if (newRealTimeSync && this.authToken) {
70
+ console.log("Activating realtime updates");
71
+ // Ensure we're not in the middle of another connection attempt
72
+ if (this.connectionInProgress) {
73
+ console.log("Connection already in progress, waiting before initializing");
74
+ setTimeout(() => this.initWebSocket(), 500);
75
+ }
76
+ else {
77
+ this.initWebSocket();
78
+ }
79
+ }
80
+ else if (!newRealTimeSync) {
81
+ console.log("Deactivating realtime updates");
82
+ if (this.socket.connected) {
83
+ console.log("Disconnecting socket");
84
+ this.socket.disconnect();
85
+ }
86
+ }
87
+ }
88
+ // User Administration Endpoints
89
+ /**
90
+ * Authenticates a user and stores the returned token for subsequent requests.
91
+ *
92
+ * @param {I_UserLogin} credentials - Username and password credentials.
93
+ * @returns {Promise<I_LoginResponse | null>} Login payload when successful, otherwise null.
94
+ */
95
+ async login(credentials) {
96
+ const response = await this.request('/users/login', 'POST', credentials, false);
97
+ if (response.token) {
98
+ this.authToken = response.token;
99
+ // Reconnect websocket with new token if realtime sync is enabled
100
+ if (this.realTimeSync) {
101
+ this.initWebSocket();
102
+ }
103
+ return { token: response.token, isAdmin: response.isAdmin, userName: response.userName };
104
+ }
105
+ return null;
106
+ }
107
+ /**
108
+ * Retrieves all users visible to the authenticated user.
109
+ *
110
+ * @returns {Promise<I_UserEntry[]>} A list of user entries.
111
+ */
112
+ async listUsers() {
113
+ return await this.request('/users/list', 'GET');
114
+ }
115
+ /**
116
+ * Updates a user by ID.
117
+ *
118
+ * @param {string} userID - The ID of the user to update.
119
+ * @param {I_UserUpdate} userData - Partial user fields to update.
120
+ * @returns {Promise<void>}
121
+ */
122
+ async updateUser(userID, userData) {
123
+ await this.request(`/users/update/${userID}`, 'PATCH', userData);
124
+ }
125
+ /**
126
+ * Creates a new user.
127
+ *
128
+ * @param {I_UserCreation} userData - Data used to create the user.
129
+ * @returns {Promise<I_UserDisplay>} The created user payload returned by the API.
130
+ */
131
+ async createUser(userData) {
132
+ return await this.request('/users/create', 'POST', userData);
133
+ }
134
+ /**
135
+ * Removes a user by ID.
136
+ *
137
+ * @param {string} userID - The ID of the user to remove.
138
+ * @returns {Promise<void>}
139
+ */
140
+ async removeUser(userID) {
141
+ await this.request(`/users/remove/${userID}`, 'DELETE');
142
+ }
143
+ // Document Management Endpoints
144
+ /**
145
+ * Creates a new document.
146
+ *
147
+ * @param {I_DocumentEntry} document - The document payload to create.
148
+ * @returns {Promise<I_DocumentEntry>} The created document.
149
+ */
150
+ async createDocument(document) {
151
+ return await this.request('/docs/create', 'POST', document);
152
+ }
153
+ /**
154
+ * Retrieves all documents visible to the authenticated user.
155
+ *
156
+ * @returns {Promise<I_DocumentEntry[]>} A list of document entries.
157
+ */
158
+ async listDocuments() {
159
+ return await this.request('/docs/list', 'GET');
160
+ }
161
+ /**
162
+ * Fetches documents matching a query object.
163
+ *
164
+ * @param {I_DocumentQuery} queryObject - Query fields used for filtering.
165
+ * @returns {Promise<I_DocumentEntry[]>} Matching documents.
166
+ */
167
+ async fetchDocuments(queryObject) {
168
+ return await this.request(`/docs/fetch/`, 'POST', queryObject);
169
+ }
170
+ /**
171
+ * Updates a document by ID.
172
+ *
173
+ * @param {string} documentID - The ID of the document to update.
174
+ * @param {I_DocumentEntry} documentData - Updated document payload.
175
+ * @returns {Promise<void>}
176
+ */
177
+ async updateDocument(documentID, documentData) {
178
+ await this.request(`/docs/update/${documentID}`, 'PATCH', documentData);
179
+ }
180
+ /**
181
+ * Removes a document by ID.
182
+ *
183
+ * @param {string} documentID - The ID of the document to remove.
184
+ * @returns {Promise<void>}
185
+ */
186
+ async removeDocument(documentID) {
187
+ await this.request(`/docs/remove/${documentID}`, 'DELETE');
188
+ }
189
+ // Data Structure Endpoints
190
+ /**
191
+ * Creates a new data structure.
192
+ *
193
+ * @param {I_StructureCreation} structure - Data structure payload to create.
194
+ * @returns {Promise<I_DataStructure>} The created data structure.
195
+ */
196
+ async createStructure(structure) {
197
+ return await this.request('/structures/create', 'POST', structure);
198
+ }
199
+ /**
200
+ * Retrieves all data structures.
201
+ *
202
+ * @returns {Promise<I_DataStructure[]>} A list of data structures.
203
+ */
204
+ async getStructures() {
205
+ return await this.request('/structures/list', 'GET');
206
+ }
207
+ /**
208
+ * Updates a data structure by ID.
209
+ *
210
+ * @param {string} structureID - The ID of the structure to update.
211
+ * @param {I_DataStructure} structureData - Updated structure payload.
212
+ * @returns {Promise<void>}
213
+ */
214
+ async updateStructure(structureID, structureData) {
215
+ await this.request(`/structures/update/${structureID}`, 'PATCH', structureData);
216
+ }
217
+ /**
218
+ * Removes a data structure by ID.
219
+ *
220
+ * @param {string} structureID - The ID of the structure to remove.
221
+ * @returns {Promise<void>}
222
+ */
223
+ async removeStructure(structureID) {
224
+ await this.request(`/structures/remove/${structureID}`, 'DELETE');
225
+ }
226
+ // Data Type Endpoints
227
+ /**
228
+ * Creates or writes a document type.
229
+ *
230
+ * @param {I_DocumentType} type - The type payload.
231
+ * @returns {Promise<I_DocumentType>} The created or updated type.
232
+ */
233
+ async createType(type) {
234
+ return await this.request('/types/write', 'POST', type);
235
+ }
236
+ /**
237
+ * Removes a document type by ID.
238
+ *
239
+ * @param {string} typeID - The ID of the type to remove.
240
+ * @returns {Promise<void>}
241
+ */
242
+ async removeType(typeID) {
243
+ return await this.request(`/types/remove/${typeID}`, 'DELETE');
244
+ }
245
+ /**
246
+ * Retrieves all document types.
247
+ *
248
+ * @returns {Promise<I_DocumentType[]>} A list of document types.
249
+ */
250
+ async getTypes() {
251
+ return await this.request('/types/list', 'GET');
252
+ }
253
+ /**
254
+ * Updates a document type.
255
+ *
256
+ * @param {I_DocumentType} updatedType - The full type payload to persist.
257
+ * @returns {Promise<void>}
258
+ */
259
+ async updateType(updatedType) {
260
+ await this.request(`/types/write`, 'POST', updatedType);
261
+ }
262
+ /**
263
+ * Sets or clears the authentication token used for API and WebSocket auth.
264
+ *
265
+ * @param {string | null} token - Bearer token to use, or null to clear it.
266
+ */
267
+ setToken(token) {
268
+ console.log("Setting token to:", token ? "***token***" : "null");
269
+ const tokenChanged = this.authToken !== token;
270
+ this.authToken = token;
271
+ if (!tokenChanged) {
272
+ console.log("Token unchanged, no need to reconnect");
273
+ return;
274
+ }
275
+ // If we have a new token and realtime sync is enabled
276
+ if (token && this.realTimeSync) {
277
+ console.log("New token set, will initialize WebSocket");
278
+ // Ensure any existing connection is closed first
279
+ if (this.socket.connected) {
280
+ console.log("Disconnecting existing socket before reconnecting with new token");
281
+ this.socket.disconnect();
282
+ }
283
+ // Wait a moment for the disconnect to complete
284
+ setTimeout(() => {
285
+ console.log("Initializing WebSocket with new token");
286
+ this.initWebSocket();
287
+ }, 300);
288
+ }
289
+ // If token was cleared or realtime sync is disabled
290
+ else if (this.socket.connected) {
291
+ console.log("Token cleared or realtime sync disabled, disconnecting");
292
+ this.socket.disconnect();
293
+ }
294
+ }
295
+ /**
296
+ * Returns the package version of this client.
297
+ *
298
+ * @returns {string} The semantic version string.
299
+ */
300
+ getVersion() {
301
+ return packetJson.version;
302
+ }
303
+ /**
304
+ * Logs socket diagnostics and attempts a reconnect when possible.
305
+ *
306
+ * @returns {void}
307
+ */
308
+ debugSocketConnection() {
309
+ console.log("Socket connection debug info:");
310
+ console.log("- Connected:", this.socket.connected);
311
+ console.log("- Socket ID:", this.socket.id);
312
+ console.log("- Auth token present:", !!this.authToken);
313
+ console.log("- Connection in progress:", this.connectionInProgress);
314
+ console.log("- Realtime sync enabled:", this.realTimeSync);
315
+ console.log("- Socket options:", this.socket.io.opts);
316
+ // Try to force reconnection
317
+ if (!this.socket.connected && this.authToken && this.realTimeSync) {
318
+ console.log("Attempting to force reconnection...");
319
+ this.socket.auth = { token: this.authToken };
320
+ this.socket.connect();
321
+ }
322
+ }
323
+ /**
324
+ * Sets up permanent socket listeners for the client.
325
+ *
326
+ * @private
327
+ */
328
+ setupPermanentSocketListeners() {
329
+ // These are permanent listeners that won't be removed
330
+ this.socket.on('connect_error', (error) => {
331
+ console.error('Socket connection error:', error.message);
332
+ this.connectionInProgress = false;
333
+ });
334
+ this.socket.on('connect', () => {
335
+ console.log('Socket connected successfully with ID:', this.socket.id);
336
+ this.connectionInProgress = false;
337
+ });
338
+ this.socket.on('disconnect', (reason) => {
339
+ console.log('Socket disconnected. Reason:', reason);
340
+ this.connectionInProgress = false;
341
+ });
342
+ this.socket.on('error', (error) => {
343
+ console.error('Socket error:', error);
344
+ this.connectionInProgress = false;
345
+ });
346
+ }
347
+ /**
348
+ * Initializes the WebSocket connection with the server.
349
+ *
350
+ * @private
351
+ */
352
+ initWebSocket() {
353
+ console.log("initWebSocket called. Auth token present:", !!this.authToken, "Connection in progress:", this.connectionInProgress, "Socket connected:", this.socket.connected);
354
+ if (!this.authToken) {
355
+ console.log("Skipping WebSocket initialization: No auth token");
356
+ return;
357
+ }
358
+ if (this.connectionInProgress) {
359
+ console.log("Connection already in progress, skipping initialization");
360
+ return;
361
+ }
362
+ if (this.socket.connected) {
363
+ console.log("Socket already connected with ID:", this.socket.id);
364
+ return;
365
+ }
366
+ this.connectionInProgress = true;
367
+ try {
368
+ console.log("Setting up WebSocket connection with token");
369
+ // Update the auth token
370
+ this.socket.auth = { token: this.authToken };
371
+ // Remove any dynamic event listeners that might have been added
372
+ this.socket.offAny();
373
+ // Set up event handler for application events
374
+ this.socket.onAny((event, data) => {
375
+ if (event === "heartbeatPing") {
376
+ console.log("Ping event received:", data);
377
+ this.socket.emit("heartbeatPong", Date.now());
378
+ }
379
+ else if (this.callbackFunction) {
380
+ this.callbackFunction(event, data);
381
+ }
382
+ });
383
+ // Connect to the server
384
+ console.log("Connecting socket with auth token");
385
+ this.socket.connect();
386
+ // Add a timeout to detect if connection is taking too long
387
+ setTimeout(() => {
388
+ if (this.connectionInProgress) {
389
+ console.warn("Socket connection attempt timed out after 5 seconds");
390
+ this.connectionInProgress = false;
391
+ // If we're still not connected after the timeout, try again with polling
392
+ if (!this.socket.connected) {
393
+ console.log("Retrying connection with polling transport");
394
+ this.socket.io.opts.transports = ['polling', 'websocket'];
395
+ this.socket.connect();
396
+ }
397
+ }
398
+ }, 5000);
399
+ }
400
+ catch (error) {
401
+ console.error('Error in initWebSocket:', error);
402
+ this.connectionInProgress = false;
403
+ }
404
+ }
405
+ /**
406
+ * Sends an HTTP request to the configured docPouch backend.
407
+ *
408
+ * @template T
409
+ * @param {string} endpoint - Relative API endpoint (with or without leading slash).
410
+ * @param {string} method - HTTP method.
411
+ * @param {any} [body] - Optional JSON body.
412
+ * @param {boolean} [requiresAuth=true] - Whether the Authorization header should be attached.
413
+ * @returns {Promise<T>} Parsed JSON response body.
414
+ * @private
415
+ */
416
+ async request(endpoint, method, body, requiresAuth = true) {
417
+ const headers = {
418
+ 'Content-Type': 'application/json',
419
+ };
420
+ if (requiresAuth && this.authToken)
421
+ headers['Authorization'] = `Bearer ${this.authToken}`;
422
+ if (this.socket.id)
423
+ headers['X-Socket-ID'] = this.socket.id;
424
+ const options = {
425
+ method,
426
+ headers,
427
+ body: body ? JSON.stringify(body) : undefined
428
+ };
429
+ const normalizedEndpoint = endpoint.startsWith('/') ? endpoint : `/${endpoint}`;
430
+ const normalizedBaseUrl = this.baseUrl.endsWith('/') ? this.baseUrl.slice(0, -1) : this.baseUrl;
431
+ const url = `${normalizedBaseUrl}${normalizedEndpoint}`;
432
+ const response = await fetch(url, options);
433
+ if (!response.ok) {
434
+ if (response.status === 401 || response.status === 403) {
435
+ this.authToken = null;
436
+ }
437
+ throw new Error(`API error: ${response.status} ${response.statusText}`);
438
+ }
439
+ return await response.json();
440
+ }
441
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "docpouch-client",
3
- "version": "0.8.15",
3
+ "version": "0.8.17",
4
4
  "main": "dist/index.js",
5
5
  "types": "dist/index.d.ts",
6
6
  "exports": {
@@ -27,12 +27,12 @@
27
27
  },
28
28
  "devDependencies": {
29
29
  "@types/jest": "^30.0.0",
30
- "@types/node": "^24.3.0",
31
- "jest": "^30.0.5",
32
- "ts-jest": "^29.4.1",
33
- "typescript": "^5.9.2"
30
+ "@types/node": "^24.12.0",
31
+ "jest": "^30.3.0",
32
+ "ts-jest": "^29.4.6",
33
+ "typescript": "^5.9.3"
34
34
  },
35
35
  "dependencies": {
36
- "socket.io-client": "^4.8.1"
36
+ "socket.io-client": "^4.8.3"
37
37
  }
38
38
  }
package/src/index.ts CHANGED
@@ -576,6 +576,7 @@ export interface I_DocumentCreation {
576
576
  content: any;
577
577
  shareWithGroup: boolean;
578
578
  shareWithDepartment: boolean;
579
+ public: boolean;
579
580
  }
580
581
 
581
582
 
@@ -596,6 +597,7 @@ export interface I_DocumentQuery {
596
597
  subType?: number;
597
598
  shareWithGroup?: boolean;
598
599
  shareWithDepartment?: boolean;
600
+ public?: boolean;
599
601
  }
600
602
 
601
603