@codebit-programando-solucoes/codebit-web 1.1.19 → 1.1.21

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.
package/dist/api/api.d.ts CHANGED
@@ -12,6 +12,8 @@ export interface RequestConfig {
12
12
  signal?: AbortSignal;
13
13
  /** Desired response format */
14
14
  responseType?: 'json' | 'text' | 'blob' | 'arraybuffer' | 'stream';
15
+ /** Callback for upload progress events */
16
+ onUploadProgress?: (progressEvent: ProgressEvent) => void;
15
17
  }
16
18
 
17
19
  /** API response object. */
package/dist/index.cjs CHANGED
@@ -24,17 +24,22 @@ var __webpack_require__ = {};
24
24
  var __webpack_exports__ = {};
25
25
  __webpack_require__.r(__webpack_exports__);
26
26
  __webpack_require__.d(__webpack_exports__, {
27
- fetchImageAsBlob: ()=>fetchImageAsBlob,
28
- getScrollbarWidth: ()=>getScrollbarWidth,
29
- loadImage: ()=>loadImage,
27
+ removeHashParam: ()=>removeHashParam,
30
28
  markdownItBrEmptyLines: ()=>markdownItBrEmptyLines,
31
- ErrorCode: ()=>ErrorCode,
29
+ getHashParams: ()=>getHashParams,
32
30
  ApiNetworkError: ()=>ApiNetworkError,
33
- Logger: ()=>Logger,
34
31
  copyToClipboard: ()=>copyToClipboard,
32
+ loadImage: ()=>loadImage,
33
+ createAdvancedPartialRegex: ()=>createAdvancedPartialRegex,
34
+ hasHashParam: ()=>hasHashParam,
35
+ ErrorCode: ()=>ErrorCode,
36
+ addHashParam: ()=>addHashParam,
37
+ getScrollbarWidth: ()=>getScrollbarWidth,
38
+ Logger: ()=>Logger,
39
+ getHashParamValue: ()=>getHashParamValue,
35
40
  Api: ()=>Api,
36
41
  ApiError: ()=>ApiError,
37
- createAdvancedPartialRegex: ()=>createAdvancedPartialRegex
42
+ fetchImageAsBlob: ()=>fetchImageAsBlob
38
43
  });
39
44
  class ApiError extends Error {
40
45
  constructor(response, request = null){
@@ -174,8 +179,39 @@ function isBinaryContent(contentType) {
174
179
  ];
175
180
  return binaryTypes.some((type)=>contentType.startsWith(type));
176
181
  }
182
+ function parseResponseHeaders(headerStr) {
183
+ const headers = new Headers();
184
+ if (!headerStr) return headers;
185
+ const lines = headerStr.split('\r\n').filter((line)=>!!line);
186
+ lines.forEach((line)=>{
187
+ const [key, value] = line.split(': ');
188
+ if (key && value) headers.append(key, value);
189
+ });
190
+ return headers;
191
+ }
192
+ async function createApiErrorFromXhr(xhr, request) {
193
+ let responseData;
194
+ try {
195
+ const contentType = xhr.getResponseHeader('content-type');
196
+ responseData = contentType?.includes('application/json') ? JSON.parse(xhr.responseText) : xhr.responseText;
197
+ } catch {
198
+ responseData = xhr.responseText;
199
+ }
200
+ const responseObject = {
201
+ status: xhr.status,
202
+ statusText: xhr.statusText || '',
203
+ headers: parseResponseHeaders(xhr.getAllResponseHeaders()),
204
+ data: responseData
205
+ };
206
+ return new ApiError(responseObject, request);
207
+ }
177
208
  async function makeRequest(url, options = {}) {
178
- const { signal: externalSignal, timeout = API_CONFIG.timeout, headers, responseType, ...restOptions } = options;
209
+ const { signal: externalSignal, timeout = API_CONFIG.timeout, headers, responseType, onUploadProgress, ...restOptions } = options;
210
+ if (onUploadProgress && restOptions.method && [
211
+ 'POST',
212
+ 'PUT',
213
+ 'PATCH'
214
+ ].includes(restOptions.method.toUpperCase()) && options.body) return makeRequestWithProgress(url, options);
179
215
  const { timeoutController, timer, fullUrl } = setupRequestControl(url, externalSignal, timeout);
180
216
  const config = {
181
217
  credentials: 'include',
@@ -205,6 +241,77 @@ async function makeRequest(url, options = {}) {
205
241
  headers: response.headers
206
242
  };
207
243
  }
244
+ function makeRequestWithProgress(url, options) {
245
+ return new Promise((resolve, reject)=>{
246
+ const { signal: externalSignal, timeout = API_CONFIG.timeout, headers, responseType, onUploadProgress, method = 'POST', body } = options;
247
+ const fullUrl = url.startsWith('http') ? url : `${API_CONFIG.baseURL}${url}`;
248
+ const xhr = new XMLHttpRequest();
249
+ if ('blob' === responseType || 'arraybuffer' === responseType) xhr.responseType = responseType;
250
+ else if ('stream' === responseType) console.warn('Stream responseType is not supported with XMLHttpRequest');
251
+ const { timeoutController, timer } = setupRequestControl(fullUrl, externalSignal, timeout);
252
+ const originalAbort = timeoutController.abort;
253
+ timeoutController.abort = function(reason) {
254
+ originalAbort.call(this, reason);
255
+ xhr.abort();
256
+ };
257
+ xhr.open(method, fullUrl, true);
258
+ xhr.withCredentials = true;
259
+ const finalHeaders = buildHeaders(headers);
260
+ Object.keys(finalHeaders).forEach((key)=>{
261
+ if ('content-type' === key.toLowerCase() && body instanceof FormData) return;
262
+ xhr.setRequestHeader(key, finalHeaders[key]);
263
+ });
264
+ const config = {
265
+ headers: finalHeaders,
266
+ body
267
+ };
268
+ prepareBodyAndContentType(config);
269
+ const requestBody = config.body;
270
+ if (onUploadProgress) xhr.upload.addEventListener('progress', onUploadProgress);
271
+ xhr.onload = function() {
272
+ if (timer) clearTimeout(timer);
273
+ if (xhr.status >= 200 && xhr.status < 300) {
274
+ const contentType = xhr.getResponseHeader('content-type');
275
+ let data;
276
+ let inferredResponseType;
277
+ inferredResponseType = contentType?.includes('application/json') ? 'json' : isBinaryContent(contentType) ? 'blob' : 'text';
278
+ const finalResponseType = responseType || inferredResponseType;
279
+ if ('json' === finalResponseType) try {
280
+ data = JSON.parse(xhr.responseText);
281
+ } catch {
282
+ data = xhr.responseText;
283
+ }
284
+ else data = 'blob' === finalResponseType ? xhr.response : 'arraybuffer' === finalResponseType ? xhr.response : xhr.responseText;
285
+ resolve({
286
+ data,
287
+ status: xhr.status,
288
+ headers: parseResponseHeaders(xhr.getAllResponseHeaders())
289
+ });
290
+ } else createApiErrorFromXhr(xhr, options).then(reject);
291
+ };
292
+ xhr.onerror = function() {
293
+ if (timer) clearTimeout(timer);
294
+ const networkError = new Error('Network Error');
295
+ networkError.name = 'TypeError';
296
+ const errorCode = analyzeNetworkError(networkError);
297
+ const apiNetworkError = new ApiNetworkError(networkError);
298
+ apiNetworkError.errorCode = errorCode;
299
+ reject(apiNetworkError);
300
+ };
301
+ xhr.ontimeout = function() {
302
+ if (timer) clearTimeout(timer);
303
+ const timeoutError = new ApiError({
304
+ status: 0,
305
+ statusText: 'TIMEOUT',
306
+ headers: new Headers(),
307
+ data: null
308
+ }, options);
309
+ timeoutError.code = ErrorCode.ERR_TIMEOUT;
310
+ reject(timeoutError);
311
+ };
312
+ xhr.send(requestBody);
313
+ });
314
+ }
208
315
  const Api = {
209
316
  configure: (config)=>{
210
317
  if (void 0 !== config.baseURL) API_CONFIG.baseURL = config.baseURL;
@@ -429,29 +536,79 @@ function getScrollbarWidth(scrollbarWidth = 'auto') {
429
536
  if ('none' === scrollbarWidth) return 0;
430
537
  return 16;
431
538
  }
539
+ const getHashParams = ()=>{
540
+ const hash = globalThis.location.hash.substring(1);
541
+ return new URLSearchParams(hash);
542
+ };
543
+ const hasHashParam = (param)=>{
544
+ const params = getHashParams();
545
+ return params.has(param);
546
+ };
547
+ const getHashParamValue = (param)=>{
548
+ const params = getHashParams();
549
+ return params.get(param);
550
+ };
551
+ const addHashParam = (param, value)=>{
552
+ const params = getHashParams();
553
+ if (null == value) {
554
+ if (!params.has(param)) {
555
+ const paramString = params.toString();
556
+ const separator = paramString ? '&' : '';
557
+ globalThis.location.hash = paramString + separator + encodeURIComponent(param);
558
+ }
559
+ } else if ('' === value) {
560
+ params.set(param, '');
561
+ const paramEntries = [];
562
+ for (const [key, val] of params.entries())if ('' === val) paramEntries.push(encodeURIComponent(key));
563
+ else paramEntries.push(encodeURIComponent(key) + '=' + encodeURIComponent(val));
564
+ globalThis.location.hash = paramEntries.join('&');
565
+ } else {
566
+ params.set(param, value);
567
+ globalThis.location.hash = params.toString();
568
+ }
569
+ };
570
+ const removeHashParam = (param)=>{
571
+ const params = getHashParams();
572
+ params.delete(param);
573
+ const paramEntries = [];
574
+ for (const [key, value] of params.entries())if ('' === value) paramEntries.push(encodeURIComponent(key));
575
+ else paramEntries.push(encodeURIComponent(key) + '=' + encodeURIComponent(value));
576
+ if (paramEntries.length > 0) globalThis.location.hash = paramEntries.join('&');
577
+ else globalThis.history.replaceState(null, '', globalThis.location.pathname + globalThis.location.search);
578
+ };
432
579
  exports.Api = __webpack_exports__.Api;
433
580
  exports.ApiError = __webpack_exports__.ApiError;
434
581
  exports.ApiNetworkError = __webpack_exports__.ApiNetworkError;
435
582
  exports.ErrorCode = __webpack_exports__.ErrorCode;
436
583
  exports.Logger = __webpack_exports__.Logger;
584
+ exports.addHashParam = __webpack_exports__.addHashParam;
437
585
  exports.copyToClipboard = __webpack_exports__.copyToClipboard;
438
586
  exports.createAdvancedPartialRegex = __webpack_exports__.createAdvancedPartialRegex;
439
587
  exports.fetchImageAsBlob = __webpack_exports__.fetchImageAsBlob;
588
+ exports.getHashParamValue = __webpack_exports__.getHashParamValue;
589
+ exports.getHashParams = __webpack_exports__.getHashParams;
440
590
  exports.getScrollbarWidth = __webpack_exports__.getScrollbarWidth;
591
+ exports.hasHashParam = __webpack_exports__.hasHashParam;
441
592
  exports.loadImage = __webpack_exports__.loadImage;
442
593
  exports.markdownItBrEmptyLines = __webpack_exports__.markdownItBrEmptyLines;
594
+ exports.removeHashParam = __webpack_exports__.removeHashParam;
443
595
  for(var __rspack_i in __webpack_exports__)if (-1 === [
444
596
  "Api",
445
597
  "ApiError",
446
598
  "ApiNetworkError",
447
599
  "ErrorCode",
448
600
  "Logger",
601
+ "addHashParam",
449
602
  "copyToClipboard",
450
603
  "createAdvancedPartialRegex",
451
604
  "fetchImageAsBlob",
605
+ "getHashParamValue",
606
+ "getHashParams",
452
607
  "getScrollbarWidth",
608
+ "hasHashParam",
453
609
  "loadImage",
454
- "markdownItBrEmptyLines"
610
+ "markdownItBrEmptyLines",
611
+ "removeHashParam"
455
612
  ].indexOf(__rspack_i)) exports[__rspack_i] = __webpack_exports__[__rspack_i];
456
613
  Object.defineProperty(exports, '__esModule', {
457
614
  value: true
@@ -0,0 +1,36 @@
1
+ /**
2
+ * Utility functions for hash parameter manipulation
3
+ */
4
+
5
+ /**
6
+ * Helper function to get URLSearchParams from hash
7
+ * @returns URLSearchParams object containing hash parameters
8
+ */
9
+ export declare function getHashParams(): URLSearchParams;
10
+
11
+ /**
12
+ * Helper function to check if a parameter exists in hash
13
+ * @param param - Parameter to check
14
+ * @returns true if parameter exists, false otherwise
15
+ */
16
+ export declare function hasHashParam(param: string): boolean;
17
+
18
+ /**
19
+ * Helper function to get the value of a parameter from hash
20
+ * @param param - Parameter to get value for
21
+ * @returns Value of the parameter or null if not found
22
+ */
23
+ export declare function getHashParamValue(param: string): string | null;
24
+
25
+ /**
26
+ * Helper function to add a parameter to hash with optional value
27
+ * @param param - Parameter to add
28
+ * @param value - Optional value for the parameter
29
+ */
30
+ export declare function addHashParam(param: string, value?: string): void;
31
+
32
+ /**
33
+ * Helper function to remove a parameter from hash
34
+ * @param param - Parameter to remove
35
+ */
36
+ export declare function removeHashParam(param: string): void;
@@ -4,3 +4,4 @@ export * from './Image';
4
4
  export * from './Logger';
5
5
  export * from './markdown-it';
6
6
  export * from './Layout';
7
+ export * from './HashUtils';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@codebit-programando-solucoes/codebit-web",
3
- "version": "1.1.19",
3
+ "version": "1.1.21",
4
4
  "main": "./dist/index.cjs",
5
5
  "type": "module",
6
6
  "types": "./dist/index.d.ts",