@develia/commons 0.4.9 → 0.4.12

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 (89) hide show
  1. package/dist/cjs/array.js +5 -4
  2. package/dist/cjs/array.js.map +1 -1
  3. package/dist/cjs/browser/form-utilities.js +29 -23
  4. package/dist/cjs/browser/form-utilities.js.map +1 -1
  5. package/dist/cjs/browser/geo-location.js +61 -37
  6. package/dist/cjs/browser/geo-location.js.map +1 -1
  7. package/dist/cjs/browser/index.js +46 -1
  8. package/dist/cjs/browser/index.js.map +1 -1
  9. package/dist/cjs/event-bus.js +70 -0
  10. package/dist/cjs/event-bus.js.map +1 -0
  11. package/dist/cjs/from.js +1 -1
  12. package/dist/cjs/from.js.map +1 -1
  13. package/dist/cjs/index.js +4 -1
  14. package/dist/cjs/index.js.map +1 -1
  15. package/dist/cjs/math.js +3 -2
  16. package/dist/cjs/math.js.map +1 -1
  17. package/dist/cjs/parse.js +4 -3
  18. package/dist/cjs/parse.js.map +1 -1
  19. package/dist/cjs/patch.js +3 -2
  20. package/dist/cjs/patch.js.map +1 -1
  21. package/dist/cjs/string.js +43 -3
  22. package/dist/cjs/string.js.map +1 -1
  23. package/dist/cjs/utilities.js +25 -24
  24. package/dist/cjs/utilities.js.map +1 -1
  25. package/dist/esm/browser/form-utilities.js +23 -18
  26. package/dist/esm/browser/form-utilities.js.map +1 -1
  27. package/dist/esm/browser/geo-location.js +60 -36
  28. package/dist/esm/browser/geo-location.js.map +1 -1
  29. package/dist/esm/browser/index.js +44 -0
  30. package/dist/esm/browser/index.js.map +1 -1
  31. package/dist/esm/event-bus.js +65 -0
  32. package/dist/esm/event-bus.js.map +1 -0
  33. package/dist/esm/index.js +1 -0
  34. package/dist/esm/index.js.map +1 -1
  35. package/dist/esm/string.js +34 -0
  36. package/dist/esm/string.js.map +1 -1
  37. package/dist/types/browser/form-utilities.d.ts +2 -2
  38. package/dist/types/browser/form-utilities.d.ts.map +1 -1
  39. package/dist/types/browser/geo-location.d.ts.map +1 -1
  40. package/dist/types/browser/index.d.ts +7 -0
  41. package/dist/types/browser/index.d.ts.map +1 -1
  42. package/dist/types/event-bus.d.ts +21 -0
  43. package/dist/types/event-bus.d.ts.map +1 -0
  44. package/dist/types/index.d.ts +1 -0
  45. package/dist/types/index.d.ts.map +1 -1
  46. package/dist/types/string.d.ts +5 -0
  47. package/dist/types/string.d.ts.map +1 -1
  48. package/dist/web/browser/form-utilities.js +23 -18
  49. package/dist/web/browser/form-utilities.js.map +1 -1
  50. package/dist/web/browser/geo-location.js +60 -36
  51. package/dist/web/browser/geo-location.js.map +1 -1
  52. package/dist/web/browser/index.js +44 -0
  53. package/dist/web/browser/index.js.map +1 -1
  54. package/dist/web/event-bus.js +65 -0
  55. package/dist/web/event-bus.js.map +1 -0
  56. package/dist/web/index.js +1 -0
  57. package/dist/web/index.js.map +1 -1
  58. package/dist/web/string.js +34 -0
  59. package/dist/web/string.js.map +1 -1
  60. package/package.json +56 -56
  61. package/src/array.ts +0 -0
  62. package/src/async-pool-executor.ts +0 -0
  63. package/src/browser/form-utilities.ts +179 -173
  64. package/src/browser/geo-location.ts +113 -79
  65. package/src/browser/index.ts +78 -4
  66. package/src/browser/native-bridge.ts +116 -116
  67. package/src/cancellable-promise.ts +76 -76
  68. package/src/clean-url-search-params.ts +0 -0
  69. package/src/collections/cache-dictionary.ts +0 -0
  70. package/src/collections/default-map.ts +0 -0
  71. package/src/collections/default-weak-map.ts +0 -0
  72. package/src/collections/index.ts +2 -2
  73. package/src/event-bus.ts +84 -0
  74. package/src/from.ts +0 -0
  75. package/src/index.ts +37 -36
  76. package/src/key-value-pair.ts +0 -0
  77. package/src/lazy.ts +0 -0
  78. package/src/math.ts +0 -0
  79. package/src/order.ts +0 -0
  80. package/src/parse.ts +240 -240
  81. package/src/patch.ts +0 -0
  82. package/src/stopwatch.ts +0 -0
  83. package/src/string.ts +82 -2
  84. package/src/timer.ts +0 -0
  85. package/src/timespan.ts +0 -0
  86. package/src/type-code.ts +15 -15
  87. package/src/type.ts +371 -371
  88. package/src/types.ts +30 -30
  89. package/src/utilities.ts +404 -404
@@ -1,80 +1,114 @@
1
- // ─── Tipos ───────────────────────────────────────────────
2
-
3
- export interface GeoLocation {
4
- latitude: number;
5
- longitude: number;
6
- accuracy: number; // metros
7
- altitude: number | null;
8
- altitudeAccuracy: number | null;
9
- heading: number | null; // grados desde el norte
10
- speed: number | null; // m/s
11
- timestamp: number;
12
- }
13
-
14
- export interface GeoLocationOptions {
15
- enableHighAccuracy?: boolean; // GPS real vs torres/wifi
16
- timeout?: number; // ms máximo de espera
17
- maximumAge?: number; // ms cache válida
18
- }
19
-
20
- // ─── Función ─────────────────────────────────────────────
21
-
22
- export default async function getGeoLocation(options: GeoLocationOptions = {}): Promise<GeoLocation> {
23
-
24
- // ── Soporte del navegador ────────────────────────────
25
- if (!navigator.geolocation) {
26
- throw new Error('Tu navegador no soporta geolocalización.');
27
- }
28
-
29
- // ── Comprobar permisos (API Permissions) ─────────────
30
- if (navigator.permissions) {
31
- const permission = await navigator.permissions.query({ name: 'geolocation' });
32
-
33
- if (permission.state === 'denied') {
34
- throw new Error(
35
- 'Permiso de ubicación denegado. Actívalo en la configuración del navegador.'
36
- );
37
- }
38
- }
39
-
40
- // ── Pedir ubicación ──────────────────────────────────
41
- const defaultOptions: PositionOptions = {
42
- enableHighAccuracy: options.enableHighAccuracy ?? true,
43
- timeout: options.timeout ?? 10000,
44
- maximumAge: options.maximumAge ?? 0,
45
- };
46
-
47
- return new Promise<GeoLocation>((resolve, reject) => {
48
- navigator.geolocation.getCurrentPosition(
49
- (position) => {
50
- const { coords, timestamp } = position;
51
- resolve({
52
- latitude: coords.latitude,
53
- longitude: coords.longitude,
54
- accuracy: coords.accuracy,
55
- altitude: coords.altitude,
56
- altitudeAccuracy: coords.altitudeAccuracy,
57
- heading: coords.heading,
58
- speed: coords.speed,
59
- timestamp,
60
- });
61
- },
62
- (error) => {
63
- switch (error.code) {
64
- case error.PERMISSION_DENIED:
65
- reject(new Error('Has denegado el permiso de ubicación.'));
66
- break;
67
- case error.POSITION_UNAVAILABLE:
68
- reject(new Error('No se pudo determinar tu ubicación.'));
69
- break;
70
- case error.TIMEOUT:
71
- reject(new Error('Tiempo de espera agotado al obtener la ubicación.'));
72
- break;
73
- default:
74
- reject(new Error('Error desconocido al obtener la ubicación.'));
75
- }
76
- },
77
- defaultOptions,
78
- );
79
- });
1
+ // ─── Tipos ───────────────────────────────────────────────
2
+
3
+ export interface GeoLocation {
4
+ latitude: number;
5
+ longitude: number;
6
+ accuracy: number;
7
+ altitude: number | null;
8
+ altitudeAccuracy: number | null;
9
+ heading: number | null;
10
+ speed: number | null;
11
+ timestamp: number;
12
+ }
13
+
14
+ export interface GeoLocationOptions {
15
+ enableHighAccuracy?: boolean;
16
+ timeout?: number;
17
+ maximumAge?: number;
18
+ }
19
+
20
+ // ─── Helpers ─────────────────────────────────────────────
21
+
22
+ function positionToGeoLocation(position: GeolocationPosition): GeoLocation {
23
+ const {coords, timestamp} = position;
24
+ return {
25
+ latitude: coords.latitude,
26
+ longitude: coords.longitude,
27
+ accuracy: coords.accuracy,
28
+ altitude: coords.altitude,
29
+ altitudeAccuracy: coords.altitudeAccuracy,
30
+ heading: coords.heading,
31
+ speed: coords.speed,
32
+ timestamp,
33
+ };
34
+ }
35
+
36
+ function geolocationError(error: GeolocationPositionError): Error {
37
+ switch (error.code) {
38
+ case error.PERMISSION_DENIED:
39
+ return new Error('Has denegado el permiso de ubicación.');
40
+ case error.POSITION_UNAVAILABLE:
41
+ return new Error('No se pudo determinar tu ubicación.');
42
+ case error.TIMEOUT:
43
+ return new Error('Tiempo de espera agotado al obtener la ubicación.');
44
+ default:
45
+ return new Error('Error desconocido al obtener la ubicación.');
46
+ }
47
+ }
48
+
49
+ function requestPosition(options: PositionOptions): Promise<GeoLocation> {
50
+ return new Promise((resolve, reject) => {
51
+ navigator.geolocation.getCurrentPosition(
52
+ (position) => resolve(positionToGeoLocation(position)),
53
+ (error) => reject(geolocationError(error)),
54
+ options,
55
+ );
56
+ });
57
+ }
58
+
59
+ async function ensurePermission(): Promise<void> {
60
+ if (!navigator.permissions) return;
61
+
62
+ const permission = await navigator.permissions.query({name: 'geolocation'});
63
+
64
+ if (permission.state === 'denied') {
65
+ throw new Error(
66
+ 'Permiso de ubicación denegado. Actívalo en la configuración del navegador.',
67
+ );
68
+ }
69
+
70
+ if (permission.state === 'prompt') {
71
+ await new Promise<void>((resolve, reject) => {
72
+ // Escuchar cambio de estado del permiso
73
+ permission.onchange = () => {
74
+ permission.onchange = null;
75
+ if (permission.state === 'granted') {
76
+ resolve();
77
+ } else {
78
+ reject(new Error('Has denegado el permiso de ubicación.'));
79
+ }
80
+ };
81
+
82
+ // Forzar el diálogo nativo del navegador
83
+ navigator.geolocation.getCurrentPosition(
84
+ () => {
85
+ permission.onchange = null;
86
+ resolve();
87
+ },
88
+ (error) => {
89
+ permission.onchange = null;
90
+ reject(geolocationError(error));
91
+ },
92
+ {timeout: 30000},
93
+ );
94
+ });
95
+ }
96
+ }
97
+
98
+ // ─── Función principal ──────────────────────────────────
99
+
100
+ export default async function getGeoLocation(
101
+ options: GeoLocationOptions = {},
102
+ ): Promise<GeoLocation> {
103
+ if (!navigator.geolocation) {
104
+ throw new Error('Tu navegador no soporta geolocalización.');
105
+ }
106
+
107
+ await ensurePermission();
108
+
109
+ return requestPosition({
110
+ enableHighAccuracy: options.enableHighAccuracy ?? true,
111
+ timeout: options.timeout ?? 10000,
112
+ maximumAge: options.maximumAge ?? 0,
113
+ });
80
114
  }
@@ -1,5 +1,79 @@
1
- export * from './form-utilities.js'
2
-
3
- export {default as NativeBridge} from "./native-bridge.js"
4
-
1
+ interface FetchIntoOptions {
2
+ url?: string;
3
+ fetchOptions?: RequestInit;
4
+ runScripts?: boolean;
5
+ transition?: string;
6
+ }
7
+
8
+ export async function fetchInto(
9
+ selector: string,
10
+ options: FetchIntoOptions = {}
11
+ ): Promise<number> {
12
+ const {
13
+ url = window.location.href,
14
+ fetchOptions = {},
15
+ runScripts = false,
16
+ transition = null,
17
+ } = options;
18
+
19
+ const response = await fetch(url, fetchOptions);
20
+
21
+ if (!response.ok) {
22
+ throw new Error(`HTTP ${response.status}: ${response.statusText}`);
23
+ }
24
+
25
+ const html = await response.text();
26
+ const doc = new DOMParser().parseFromString(html, "text/html");
27
+ const oldElements = document.querySelectorAll(selector);
28
+ let replacedCount = 0;
29
+
30
+ for (let i = 0; i < oldElements.length; i++) {
31
+ const oldEl = oldElements[i];
32
+ const newEl = doc.querySelector(selector);
33
+
34
+ if (!newEl) continue;
35
+
36
+ if (transition) {
37
+ oldEl.classList.add(transition);
38
+ await new Promise<void>((r) =>
39
+ requestAnimationFrame(() => requestAnimationFrame(() => r()))
40
+ );
41
+ }
42
+
43
+ oldEl.replaceWith(newEl.cloneNode(true));
44
+
45
+ if (runScripts) {
46
+ const scripts = newEl.querySelectorAll("script");
47
+
48
+ for (let j = 0; j < scripts.length; j++) {
49
+ const script = scripts[j];
50
+ const fresh = document.createElement("script");
51
+
52
+ if (script.src) {
53
+ fresh.src = script.src;
54
+ } else {
55
+ fresh.textContent = script.textContent;
56
+ }
57
+
58
+ const attrs = script.attributes;
59
+ for (let k = 0; k < attrs.length; k++) {
60
+ if (attrs[k].name !== "src") {
61
+ fresh.setAttribute(attrs[k].name, attrs[k].value);
62
+ }
63
+ }
64
+
65
+ script.replaceWith(fresh);
66
+ }
67
+ }
68
+
69
+ replacedCount++;
70
+ }
71
+
72
+ return replacedCount;
73
+ }
74
+
75
+ export * from './form-utilities.js'
76
+
77
+ export {default as NativeBridge} from "./native-bridge.js"
78
+
5
79
  export {default as getGeoLocation} from './geo-location.js';
@@ -1,117 +1,117 @@
1
- // ─── Tipos ───────────────────────────────────────────────
2
- interface BridgeOptions {
3
- channel: Channel;
4
- timeout?: number | null;
5
- callbackName?: string; // ← nuevo
6
- }
7
- interface PendingCall {
8
- resolve: (value: unknown) => void;
9
- reject: (reason: Error) => void;
10
- timer: ReturnType<typeof setTimeout> | null;
11
- }
12
-
13
- interface Channel {
14
- postMessage: (message: string) => void;
15
- }
16
-
17
-
18
-
19
- // ─── Clase ──────────────────────────────────────────────
20
-
21
- export default class NativeBridge {
22
- private _pending = new Map<number, PendingCall>();
23
- private _callId = 0;
24
- private readonly _defaultTimeout: number | null;
25
- private readonly _channel: Channel;
26
-
27
-
28
- constructor({ channel, timeout = 3000, callbackName = '__nativeResponseHandler' }: BridgeOptions) {
29
- this._defaultTimeout = timeout;
30
- this._channel = channel;
31
-
32
- if (!this._channel) {
33
- throw new Error('Channel not found');
34
- }
35
-
36
- (window as any)[callbackName] = this._callback;
37
-
38
- // Proxy: cualquier propiedad no existente se convierte en call()
39
- return new Proxy(this, {
40
- get(target: NativeBridge, prop: string | symbol) {
41
- if (prop in target) {
42
- return (target as any)[prop];
43
- }
44
- return (data?: unknown, timeout?: number | null) => target.call(String(prop), data, timeout);
45
- },
46
- }) as unknown as NativeBridge;
47
- }
48
-
49
-
50
- private _callback(id: number, error: any, result: any) {
51
-
52
- const pending = this._pending.get(id);
53
- if (!pending) {
54
- return;
55
- }
56
-
57
- if (pending.timer !== null) {
58
- clearTimeout(pending.timer);
59
- }
60
-
61
- this._pending.delete(id);
62
-
63
- if (error) {
64
- pending.reject(error instanceof Error? error : new Error(String(error)));
65
- } else {
66
- pending.resolve(result);
67
- }
68
- }
69
-
70
- call(method: string, data: unknown = null, timeout?: number | null): Promise<unknown> {
71
-
72
-
73
- const effectiveTimeout = timeout !== undefined ? timeout : this._defaultTimeout;
74
-
75
- return new Promise<unknown>((resolve, reject) => {
76
- const id = this._callId++;
77
-
78
- let timer: ReturnType<typeof setTimeout> | null = null;
79
-
80
- // Solo crear timer si hay timeout
81
- if (effectiveTimeout !== null && effectiveTimeout > 0) {
82
- timer = setTimeout(() => {
83
- this._pending.delete(id);
84
- reject(new Error(`Timeout (${effectiveTimeout}ms): ${method}`));
85
- }, effectiveTimeout);
86
- }
87
-
88
- this._pending.set(id, { resolve, reject, timer });
89
- this._channel!.postMessage(JSON.stringify({ id, method, data }));
90
- });
91
- }
92
-
93
-
94
- send(method: string, data: unknown = null): void {
95
- this._channel!.postMessage(JSON.stringify({ method, data }));
96
- }
97
-
98
- /**
99
- * Número de llamadas pendientes
100
- */
101
- get pendingCount(): number {
102
- return this._pending.size;
103
- }
104
-
105
- /**
106
- * Cancela todas las llamadas pendientes
107
- */
108
- cancelAll(): void {
109
- for (const [, { reject, timer }] of this._pending) {
110
- if (timer !== null) {
111
- clearTimeout(timer);
112
- }
113
- reject(new Error('Cancelled'));
114
- }
115
- this._pending.clear();
116
- }
1
+ // ─── Tipos ───────────────────────────────────────────────
2
+ interface BridgeOptions {
3
+ channel: Channel;
4
+ timeout?: number | null;
5
+ callbackName?: string; // ← nuevo
6
+ }
7
+ interface PendingCall {
8
+ resolve: (value: unknown) => void;
9
+ reject: (reason: Error) => void;
10
+ timer: ReturnType<typeof setTimeout> | null;
11
+ }
12
+
13
+ interface Channel {
14
+ postMessage: (message: string) => void;
15
+ }
16
+
17
+
18
+
19
+ // ─── Clase ──────────────────────────────────────────────
20
+
21
+ export default class NativeBridge {
22
+ private _pending = new Map<number, PendingCall>();
23
+ private _callId = 0;
24
+ private readonly _defaultTimeout: number | null;
25
+ private readonly _channel: Channel;
26
+
27
+
28
+ constructor({ channel, timeout = 3000, callbackName = '__nativeResponseHandler' }: BridgeOptions) {
29
+ this._defaultTimeout = timeout;
30
+ this._channel = channel;
31
+
32
+ if (!this._channel) {
33
+ throw new Error('Channel not found');
34
+ }
35
+
36
+ (window as any)[callbackName] = this._callback;
37
+
38
+ // Proxy: cualquier propiedad no existente se convierte en call()
39
+ return new Proxy(this, {
40
+ get(target: NativeBridge, prop: string | symbol) {
41
+ if (prop in target) {
42
+ return (target as any)[prop];
43
+ }
44
+ return (data?: unknown, timeout?: number | null) => target.call(String(prop), data, timeout);
45
+ },
46
+ }) as unknown as NativeBridge;
47
+ }
48
+
49
+
50
+ private _callback(id: number, error: any, result: any) {
51
+
52
+ const pending = this._pending.get(id);
53
+ if (!pending) {
54
+ return;
55
+ }
56
+
57
+ if (pending.timer !== null) {
58
+ clearTimeout(pending.timer);
59
+ }
60
+
61
+ this._pending.delete(id);
62
+
63
+ if (error) {
64
+ pending.reject(error instanceof Error? error : new Error(String(error)));
65
+ } else {
66
+ pending.resolve(result);
67
+ }
68
+ }
69
+
70
+ call(method: string, data: unknown = null, timeout?: number | null): Promise<unknown> {
71
+
72
+
73
+ const effectiveTimeout = timeout !== undefined ? timeout : this._defaultTimeout;
74
+
75
+ return new Promise<unknown>((resolve, reject) => {
76
+ const id = this._callId++;
77
+
78
+ let timer: ReturnType<typeof setTimeout> | null = null;
79
+
80
+ // Solo crear timer si hay timeout
81
+ if (effectiveTimeout !== null && effectiveTimeout > 0) {
82
+ timer = setTimeout(() => {
83
+ this._pending.delete(id);
84
+ reject(new Error(`Timeout (${effectiveTimeout}ms): ${method}`));
85
+ }, effectiveTimeout);
86
+ }
87
+
88
+ this._pending.set(id, { resolve, reject, timer });
89
+ this._channel!.postMessage(JSON.stringify({ id, method, data }));
90
+ });
91
+ }
92
+
93
+
94
+ send(method: string, data: unknown = null): void {
95
+ this._channel!.postMessage(JSON.stringify({ method, data }));
96
+ }
97
+
98
+ /**
99
+ * Número de llamadas pendientes
100
+ */
101
+ get pendingCount(): number {
102
+ return this._pending.size;
103
+ }
104
+
105
+ /**
106
+ * Cancela todas las llamadas pendientes
107
+ */
108
+ cancelAll(): void {
109
+ for (const [, { reject, timer }] of this._pending) {
110
+ if (timer !== null) {
111
+ clearTimeout(timer);
112
+ }
113
+ reject(new Error('Cancelled'));
114
+ }
115
+ this._pending.clear();
116
+ }
117
117
  }
@@ -1,77 +1,77 @@
1
- type CancellablePromiseExecutor<T> = (
2
- resolve: (value: T | PromiseLike<T>) => void,
3
- reject: (reason?: unknown) => void,
4
- signal: AbortSignal
5
- ) => void;
6
-
7
- export default class CancellablePromise<T> extends Promise<T> {
8
-
9
- private _controller: AbortController;
10
-
11
- static get [Symbol.species]() {
12
- return Promise;
13
- }
14
-
15
- constructor(executor: CancellablePromiseExecutor<T>) {
16
- const controller = new AbortController();
17
-
18
- super((resolve, reject) => {
19
- controller.signal.addEventListener("abort", () => {
20
- reject(controller.signal.reason);
21
- });
22
-
23
- executor(resolve, reject, controller.signal);
24
- });
25
-
26
- this._controller = controller;
27
- }
28
-
29
- get cancelled(): boolean {
30
- return this._controller.signal.aborted;
31
- }
32
-
33
- cancel(reason: unknown = new Error("Promesa cancelada")): void {
34
- if (!this.cancelled) {
35
- this._controller.abort(reason);
36
- }
37
- }
38
-
39
- static async compete<T>(promises: CancellablePromise<T>[]): Promise<T> {
40
- return await Promise.race(promises).then(
41
- (resultado) => {
42
- for (const p of promises) {
43
- p.cancel();
44
- }
45
- return resultado;
46
- },
47
- (error) => {
48
- for (const p of promises) {
49
- p.cancel();
50
- }
51
- throw error;
52
- }
53
- );
54
- }
55
-
56
- static async cooperate<T>(promises: CancellablePromise<T>[]): Promise<T[]> {
57
- try {
58
- return await Promise.all(promises);
59
- } catch (error) {
60
- for (const p of promises) {
61
- p.cancel();
62
- }
63
- throw error;
64
- }
65
- }
66
-
67
- static withTimeout<T>(executor: CancellablePromiseExecutor<T>, ms: number): CancellablePromise<T> {
68
- return new CancellablePromise<T>((resolve, reject, signal) => {
69
- const timer = setTimeout(() => {
70
- reject(new Error(`Timeout: ${ms}ms`));
71
- }, ms);
72
-
73
- signal.addEventListener("abort", () => clearTimeout(timer));
74
- executor(resolve, reject, signal);
75
- });
76
- }
1
+ type CancellablePromiseExecutor<T> = (
2
+ resolve: (value: T | PromiseLike<T>) => void,
3
+ reject: (reason?: unknown) => void,
4
+ signal: AbortSignal
5
+ ) => void;
6
+
7
+ export default class CancellablePromise<T> extends Promise<T> {
8
+
9
+ private _controller: AbortController;
10
+
11
+ static get [Symbol.species]() {
12
+ return Promise;
13
+ }
14
+
15
+ constructor(executor: CancellablePromiseExecutor<T>) {
16
+ const controller = new AbortController();
17
+
18
+ super((resolve, reject) => {
19
+ controller.signal.addEventListener("abort", () => {
20
+ reject(controller.signal.reason);
21
+ });
22
+
23
+ executor(resolve, reject, controller.signal);
24
+ });
25
+
26
+ this._controller = controller;
27
+ }
28
+
29
+ get cancelled(): boolean {
30
+ return this._controller.signal.aborted;
31
+ }
32
+
33
+ cancel(reason: unknown = new Error("Promesa cancelada")): void {
34
+ if (!this.cancelled) {
35
+ this._controller.abort(reason);
36
+ }
37
+ }
38
+
39
+ static async compete<T>(promises: CancellablePromise<T>[]): Promise<T> {
40
+ return await Promise.race(promises).then(
41
+ (resultado) => {
42
+ for (const p of promises) {
43
+ p.cancel();
44
+ }
45
+ return resultado;
46
+ },
47
+ (error) => {
48
+ for (const p of promises) {
49
+ p.cancel();
50
+ }
51
+ throw error;
52
+ }
53
+ );
54
+ }
55
+
56
+ static async cooperate<T>(promises: CancellablePromise<T>[]): Promise<T[]> {
57
+ try {
58
+ return await Promise.all(promises);
59
+ } catch (error) {
60
+ for (const p of promises) {
61
+ p.cancel();
62
+ }
63
+ throw error;
64
+ }
65
+ }
66
+
67
+ static withTimeout<T>(executor: CancellablePromiseExecutor<T>, ms: number): CancellablePromise<T> {
68
+ return new CancellablePromise<T>((resolve, reject, signal) => {
69
+ const timer = setTimeout(() => {
70
+ reject(new Error(`Timeout: ${ms}ms`));
71
+ }, ms);
72
+
73
+ signal.addEventListener("abort", () => clearTimeout(timer));
74
+ executor(resolve, reject, signal);
75
+ });
76
+ }
77
77
  }
File without changes
File without changes
File without changes