@budarin/pluggable-serviceworker 1.0.8 → 1.0.9

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@budarin/pluggable-serviceworker",
3
- "version": "1.0.8",
3
+ "version": "1.0.9",
4
4
  "description": "Extensible via plugins service worker",
5
5
  "keywords": [
6
6
  "serviceworker",
package/.prettierignore DELETED
@@ -1,3 +0,0 @@
1
- .vscode
2
- # dist
3
- node_modules
package/.prettierrc.mjs DELETED
@@ -1,14 +0,0 @@
1
- /**
2
- * @see https://prettier.io/docs/en/configuration.html
3
- * @type {import("prettier").Config}
4
- */
5
- const config = {
6
- trailingComma: 'es5',
7
- tabWidth: 4,
8
- // semi: false,
9
- singleQuote: true,
10
- plugins: [],
11
- htmlWhitespaceSensitivity: 'ignore',
12
- };
13
-
14
- export default config;
package/src/index.ts DELETED
@@ -1,290 +0,0 @@
1
- export enum ServiceWorkerErrorType {
2
- ERROR = 'error',
3
- MESSAGE_ERROR = 'messageerror',
4
- UNHANDLED_REJECTION = 'unhandledrejection',
5
- REJECTION_HANDLED = 'rejectionhandled',
6
- PLUGIN_ERROR = 'plugin_error',
7
- }
8
-
9
- interface SyncEvent extends ExtendableEvent {
10
- readonly tag: string;
11
- readonly lastChance: boolean;
12
- }
13
-
14
- interface PeriodicSyncEvent extends ExtendableEvent {
15
- readonly tag: string;
16
- }
17
-
18
- // Extend ServiceWorkerGlobalScope to include sync events
19
- declare global {
20
- interface ServiceWorkerGlobalScopeEventMap {
21
- sync: SyncEvent;
22
- periodicsync: PeriodicSyncEvent;
23
- }
24
- }
25
-
26
- interface ServiceWorkerEventHandlers {
27
- install?: (event: ExtendableEvent) => void | Promise<void>;
28
- activate?: (event: ExtendableEvent) => void | Promise<void>;
29
- fetch?: (event: FetchEvent) => Promise<Response | null>;
30
- message?: (event: MessageEvent) => void;
31
- sync?: (event: SyncEvent) => void | Promise<void>;
32
- periodicsync?: (event: PeriodicSyncEvent) => void | Promise<void>;
33
- push?: (event: PushEvent) => void | Promise<void>;
34
- }
35
-
36
- interface ServiceWorkerPlugin extends ServiceWorkerEventHandlers {
37
- name: string;
38
- order?: number;
39
- }
40
-
41
- interface ServiceWorkerConfig {
42
- plugins?: ServiceWorkerPlugin[];
43
- onError?: (
44
- error: Error | any,
45
- event: Event,
46
- errorType?: ServiceWorkerErrorType
47
- ) => void;
48
- }
49
-
50
- type FetchResponse = Promise<Response | null>;
51
-
52
- export function createEventHandlers(
53
- plugins: ServiceWorkerPlugin[],
54
- config: ServiceWorkerConfig = {}
55
- ): {
56
- install: (event: ExtendableEvent) => void;
57
- activate: (event: ExtendableEvent) => void;
58
- fetch: (event: FetchEvent) => void;
59
- message: (event: MessageEvent) => void;
60
- sync: (event: SyncEvent) => void;
61
- periodicsync: (event: PeriodicSyncEvent) => void;
62
- push: (event: PushEvent) => void;
63
- error: (event: ErrorEvent) => void;
64
- messageerror: (event: MessageEvent) => void;
65
- unhandledrejection: (event: PromiseRejectionEvent) => void;
66
- rejectionhandled: (event: PromiseRejectionEvent) => void;
67
- } {
68
- const handlers = {
69
- install: [] as ((event: ExtendableEvent) => void | Promise<void>)[],
70
- activate: [] as ((event: ExtendableEvent) => void | Promise<void>)[],
71
- fetch: [] as ((event: FetchEvent) => FetchResponse)[],
72
- message: [] as ((event: MessageEvent) => void)[],
73
- sync: [] as ((event: SyncEvent) => void | Promise<void>)[],
74
- periodicsync: [] as ((
75
- event: PeriodicSyncEvent
76
- ) => void | Promise<void>)[],
77
- push: [] as ((event: PushEvent) => void | Promise<void>)[],
78
- };
79
-
80
- // Сортировка плагинов по порядку выполнения:
81
- // 1. Сначала выполняются ВСЕ плагины без order (undefined) в том порядке, в котором они были добавлены
82
- // 2. Затем выполняются плагины с order в порядке возрастания значений order
83
- const sortedPlugins = [
84
- ...plugins.filter((plugin) => plugin.order === undefined),
85
- ...plugins
86
- .filter((plugin) => plugin.order !== undefined)
87
- .sort((a, b) => (a.order ?? 0) - (b.order ?? 0)),
88
- ];
89
-
90
- sortedPlugins.forEach((plugin) => {
91
- if (plugin.install) handlers.install.push(plugin.install);
92
- if (plugin.activate) handlers.activate.push(plugin.activate);
93
- if (plugin.fetch) handlers.fetch.push(plugin.fetch);
94
- if (plugin.message) handlers.message.push(plugin.message);
95
- if (plugin.sync) handlers.sync.push(plugin.sync);
96
- if (plugin.periodicsync)
97
- handlers.periodicsync.push(plugin.periodicsync);
98
- if (plugin.push) handlers.push.push(plugin.push);
99
- });
100
-
101
- return {
102
- install: (event: ExtendableEvent): void => {
103
- event.waitUntil(
104
- Promise.all(
105
- handlers.install.map((handler) =>
106
- Promise.resolve(handler(event)).catch(
107
- (error: unknown) =>
108
- config.onError?.(
109
- error as Error,
110
- event,
111
- ServiceWorkerErrorType.PLUGIN_ERROR
112
- )
113
- )
114
- )
115
- )
116
- );
117
- },
118
-
119
- activate: (event: ExtendableEvent): void => {
120
- event.waitUntil(
121
- Promise.all(
122
- handlers.activate.map((handler) =>
123
- Promise.resolve(handler(event)).catch(
124
- (error: unknown) =>
125
- config.onError?.(
126
- error as Error,
127
- event,
128
- ServiceWorkerErrorType.PLUGIN_ERROR
129
- )
130
- )
131
- )
132
- )
133
- );
134
- },
135
-
136
- fetch: (event: FetchEvent): void => {
137
- event.respondWith(
138
- (async (): Promise<Response> => {
139
- for (const handler of handlers.fetch) {
140
- try {
141
- const result = await handler(event);
142
- if (result) {
143
- return result;
144
- }
145
- } catch (error) {
146
- config.onError?.(
147
- error as Error,
148
- event,
149
- ServiceWorkerErrorType.PLUGIN_ERROR
150
- );
151
- }
152
- }
153
- return fetch(event.request);
154
- })()
155
- );
156
- },
157
-
158
- message: (event: MessageEvent): void => {
159
- handlers.message.forEach((handler) => {
160
- try {
161
- handler(event);
162
- } catch (error) {
163
- config.onError?.(error as Error, event);
164
- }
165
- });
166
- },
167
-
168
- sync: (event: SyncEvent): void => {
169
- event.waitUntil(
170
- Promise.all(
171
- handlers.sync.map((handler) =>
172
- Promise.resolve(handler(event)).catch(
173
- (error: unknown) =>
174
- config.onError?.(
175
- error as Error,
176
- event,
177
- ServiceWorkerErrorType.PLUGIN_ERROR
178
- )
179
- )
180
- )
181
- )
182
- );
183
- },
184
-
185
- periodicsync: (event: PeriodicSyncEvent): void => {
186
- event.waitUntil(
187
- Promise.all(
188
- handlers.periodicsync.map((handler) =>
189
- Promise.resolve(handler(event)).catch(
190
- (error: unknown) =>
191
- config.onError?.(
192
- error as Error,
193
- event,
194
- ServiceWorkerErrorType.PLUGIN_ERROR
195
- )
196
- )
197
- )
198
- )
199
- );
200
- },
201
-
202
- push: (event: PushEvent): void => {
203
- event.waitUntil(
204
- (async (): Promise<void> => {
205
- for (const handler of handlers.push) {
206
- try {
207
- await Promise.resolve(handler(event));
208
- } catch (error) {
209
- config.onError?.(
210
- error as Error,
211
- event,
212
- ServiceWorkerErrorType.PLUGIN_ERROR
213
- );
214
- }
215
- }
216
- })()
217
- );
218
- },
219
-
220
- error: (event: ErrorEvent): void => {
221
- try {
222
- config.onError?.(
223
- event.error,
224
- event,
225
- ServiceWorkerErrorType.ERROR
226
- );
227
- } catch (error) {
228
- console.error('Error in error handler:', error);
229
- }
230
- },
231
-
232
- messageerror: (event: MessageEvent): void => {
233
- try {
234
- config.onError?.(
235
- event.data,
236
- event,
237
- ServiceWorkerErrorType.MESSAGE_ERROR
238
- );
239
- } catch (error) {
240
- console.error('Error in messageerror handler:', error);
241
- }
242
- },
243
-
244
- unhandledrejection: (event: PromiseRejectionEvent): void => {
245
- try {
246
- config.onError?.(
247
- event.reason,
248
- event,
249
- ServiceWorkerErrorType.UNHANDLED_REJECTION
250
- );
251
- } catch (error) {
252
- console.error('Error in unhandledrejection handler:', error);
253
- }
254
- },
255
-
256
- rejectionhandled: (event: PromiseRejectionEvent): void => {
257
- try {
258
- config.onError?.(
259
- event.reason,
260
- event,
261
- ServiceWorkerErrorType.REJECTION_HANDLED
262
- );
263
- } catch (error) {
264
- console.error('Error in rejectionhandled handler:', error);
265
- }
266
- },
267
- };
268
- }
269
-
270
- export function initializeServiceWorker(
271
- plugins: ServiceWorkerPlugin[],
272
- config?: ServiceWorkerConfig
273
- ): void {
274
- const handlers = createEventHandlers(plugins, config);
275
-
276
- // Регистрируем стандартные обработчики событий Service Worker
277
- self.addEventListener('install', handlers.install);
278
- self.addEventListener('activate', handlers.activate);
279
- self.addEventListener('fetch', handlers.fetch);
280
- self.addEventListener('message', handlers.message);
281
- self.addEventListener('sync', handlers.sync);
282
- self.addEventListener('periodicsync', handlers.periodicsync);
283
- self.addEventListener('push', handlers.push);
284
-
285
- // Регистрируем глобальные обработчики ошибок
286
- self.addEventListener('error', handlers.error);
287
- self.addEventListener('messageerror', handlers.messageerror);
288
- self.addEventListener('unhandledrejection', handlers.unhandledrejection);
289
- self.addEventListener('rejectionhandled', handlers.rejectionhandled);
290
- }
package/tsconfig.json DELETED
@@ -1,44 +0,0 @@
1
- {
2
- // Visit https://aka.ms/tsconfig to read more about this file
3
- "compilerOptions": {
4
- // File Layout
5
- "rootDir": "./src",
6
- "outDir": "./dist",
7
-
8
- // Environment Settings
9
- // See also https://aka.ms/tsconfig/module
10
- "module": "nodenext",
11
- "target": "esnext",
12
- // For nodejs:
13
- "lib": ["esnext"],
14
- "types": ["node", "serviceworker", "web"],
15
- // and npm install -D @types/node
16
-
17
- // Other Outputs
18
- "sourceMap": true,
19
- "declaration": true,
20
- "declarationMap": true,
21
-
22
- // Stricter Typechecking Options
23
- "noUncheckedIndexedAccess": true,
24
- "exactOptionalPropertyTypes": true,
25
-
26
- // Style Options
27
- "noImplicitReturns": true,
28
- "noImplicitOverride": true,
29
- "noUnusedLocals": true,
30
- "noUnusedParameters": true,
31
- "noFallthroughCasesInSwitch": true,
32
- "noPropertyAccessFromIndexSignature": true,
33
-
34
- // Recommended Options
35
- "strict": true,
36
- "jsx": "react-jsx",
37
- "verbatimModuleSyntax": true,
38
- "isolatedModules": true,
39
- "noUncheckedSideEffectImports": true,
40
- "moduleDetection": "force",
41
- "skipLibCheck": true,
42
- "removeComments": true
43
- }
44
- }