@rdlabo/ionic-angular-kit 22.0.0 → 22.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.
@@ -11,10 +11,29 @@ Applications that prefetch every executable application chunk can opt into a non
11
11
  provideKitAppUpdate({ strategy: 'background' });
12
12
  ```
13
13
 
14
- The background strategy reloads only before Angular completes its first render. A later update is left for the next natural page
15
- load so user input is not discarded. It never calls `activateUpdate()`, which could mix a running shell with lazy chunks from
16
- another version. An unrecoverable startup generation is retried once with `ngsw-bypass`; the current history state and an
17
- offline-safe loop guard are retained.
14
+ The existing background strategy reloads only before Angular completes its first render. A later update is left for the next
15
+ natural page load so user input is not discarded.
16
+
17
+ Applications can select the separate `confirm` strategy to offer an immediate, user-controlled update. The prompt runs after
18
+ the first render and in an Angular injection context. Resolve dependencies synchronously before crossing an async boundary.
19
+ Resolving `true` reloads into the complete downloaded version, `false` leaves it for the next natural page load, and `undefined`
20
+ retries later because the prompt could not be presented (for example, while another alert is active).
21
+
22
+ ```ts
23
+ provideKitAppUpdate({
24
+ strategy: 'confirm',
25
+ promptForUpdate: () =>
26
+ inject(KitOverlayController).tryAlertConfirm({
27
+ header: 'The latest version is ready',
28
+ message: 'Reload now to update?',
29
+ okText: 'Reload and update',
30
+ }),
31
+ });
32
+ ```
33
+
34
+ Neither non-blocking strategy calls `activateUpdate()`, which could mix a running shell with lazy chunks from another version.
35
+ An unrecoverable startup generation is retried once with `ngsw-bypass`; the current history state and an offline-safe loop guard
36
+ are retained.
18
37
 
19
38
  ## Theme and review
20
39
 
@@ -1,12 +1,13 @@
1
1
  import { DOCUMENT } from '@angular/common';
2
2
  import * as i0 from '@angular/core';
3
- import { inject, Injectable, provideAppInitializer, afterNextRender, makeEnvironmentProviders } from '@angular/core';
3
+ import { inject, Injectable, makeEnvironmentProviders, provideAppInitializer, EnvironmentInjector, runInInjectionContext, afterNextRender } from '@angular/core';
4
4
  import { SwUpdate } from '@angular/service-worker';
5
5
  import { filter, take } from 'rxjs';
6
6
 
7
7
  const UPDATE_CHECK_TIMEOUT_MS = 10_000;
8
+ const UPDATE_PROMPT_RETRY_MS = 1_000;
8
9
  const UNRECOVERABLE_RELOAD_KEY = 'kit_sw_unrecoverable_reload';
9
- /** Checks for a complete Angular service-worker update before users can interact with the application. */
10
+ /** Coordinates complete Angular service-worker updates using blocking, background, or user-confirmed application. */
10
11
  class KitAppUpdateService {
11
12
  #document = inject(DOCUMENT);
12
13
  #updates = inject(SwUpdate);
@@ -14,6 +15,11 @@ class KitAppUpdateService {
14
15
  #backgroundStarted = false;
15
16
  #interactive = false;
16
17
  #reloading = false;
18
+ #updateReady = false;
19
+ #prompting = false;
20
+ #prompted = false;
21
+ #promptRetryScheduled = false;
22
+ #promptForUpdate;
17
23
  /** Runs one startup update check and reloads directly into a downloaded version when one is available. */
18
24
  initialize() {
19
25
  this.#initialization ??= this.#initialize();
@@ -33,13 +39,21 @@ class KitAppUpdateService {
33
39
  }
34
40
  /** Starts an update check that never blocks bootstrap or reloads after the application becomes interactive. */
35
41
  startBackground() {
42
+ this.#startNonBlocking();
43
+ }
44
+ /** Starts a non-blocking update check and asks after the first render before applying a ready update. */
45
+ startConfirm(promptForUpdate) {
46
+ this.#startNonBlocking(promptForUpdate);
47
+ }
48
+ #startNonBlocking(promptForUpdate) {
36
49
  if (this.#backgroundStarted || !this.#canCheckForUpdate()) {
37
50
  return;
38
51
  }
39
52
  this.#backgroundStarted = true;
53
+ this.#promptForUpdate = promptForUpdate;
40
54
  this.#updates.versionUpdates
41
55
  .pipe(filter((event) => event.type === 'VERSION_READY'), take(1))
42
- .subscribe(() => this.#reloadBeforeInteraction());
56
+ .subscribe(() => this.#handleUpdateReady());
43
57
  this.#updates.unrecoverable.pipe(take(1)).subscribe((event) => {
44
58
  console.error('Angular service-worker state is unrecoverable', event.reason);
45
59
  this.#recoverBeforeInteraction(event.reason);
@@ -48,7 +62,7 @@ class KitAppUpdateService {
48
62
  .checkForUpdate()
49
63
  .then((available) => {
50
64
  if (available) {
51
- this.#reloadBeforeInteraction();
65
+ this.#handleUpdateReady();
52
66
  }
53
67
  })
54
68
  .catch((error) => console.error('Angular service-worker update check failed', error));
@@ -59,6 +73,7 @@ class KitAppUpdateService {
59
73
  if (!this.#reloading) {
60
74
  this.#clearRecoveryBypass();
61
75
  }
76
+ this.#promptWhenReady();
62
77
  }
63
78
  #canCheckForUpdate() {
64
79
  return this.#updates.isEnabled && Boolean(this.#document.defaultView?.navigator.serviceWorker?.controller);
@@ -70,6 +85,59 @@ class KitAppUpdateService {
70
85
  this.#reloading = true;
71
86
  this.#document.location?.reload();
72
87
  }
88
+ #handleUpdateReady() {
89
+ if (!this.#promptForUpdate) {
90
+ this.#reloadBeforeInteraction();
91
+ return;
92
+ }
93
+ this.#updateReady = true;
94
+ this.#promptWhenReady();
95
+ }
96
+ #promptWhenReady() {
97
+ const promptForUpdate = this.#promptForUpdate;
98
+ if (!this.#interactive ||
99
+ !this.#updateReady ||
100
+ !promptForUpdate ||
101
+ this.#prompting ||
102
+ this.#prompted ||
103
+ this.#promptRetryScheduled ||
104
+ this.#reloading) {
105
+ return;
106
+ }
107
+ this.#prompting = true;
108
+ void runUpdatePrompt(promptForUpdate)
109
+ .then((confirmed) => {
110
+ this.#prompting = false;
111
+ if (confirmed === undefined) {
112
+ this.#schedulePromptRetry();
113
+ return;
114
+ }
115
+ this.#prompted = true;
116
+ this.#applyPromptResult(confirmed);
117
+ })
118
+ .catch((error) => {
119
+ this.#prompting = false;
120
+ this.#prompted = true;
121
+ console.error('Angular service-worker update prompt failed', error);
122
+ });
123
+ }
124
+ #schedulePromptRetry() {
125
+ if (this.#promptRetryScheduled || this.#prompted || this.#reloading) {
126
+ return;
127
+ }
128
+ this.#promptRetryScheduled = true;
129
+ globalThis.setTimeout(() => {
130
+ this.#promptRetryScheduled = false;
131
+ this.#promptWhenReady();
132
+ }, UPDATE_PROMPT_RETRY_MS);
133
+ }
134
+ #applyPromptResult(confirmed) {
135
+ if (!confirmed || this.#reloading) {
136
+ return;
137
+ }
138
+ this.#reloading = true;
139
+ this.#document.location?.reload();
140
+ }
73
141
  #recoverBeforeInteraction(reason) {
74
142
  const location = this.#document.location;
75
143
  if (this.#interactive || this.#reloading || !location) {
@@ -156,22 +224,46 @@ function clearFailure(storage) {
156
224
  }
157
225
  }
158
226
  /**
159
- * Provides a startup check that reloads into the latest complete web application version.
227
+ * Provides blocking, background, or user-confirmed adoption of complete Angular service-worker updates.
160
228
  *
161
229
  * @remarks
162
- * The check finishes before application bootstrap so a delayed update cannot discard user input. It times out rather
163
- * than preventing offline startup. API deployments must remain backward compatible while a newly adopted updater is
164
- * rolling out because code already running in older application versions cannot gain this behavior retroactively.
230
+ * The default `blocking` strategy checks before bootstrap and times out rather than preventing offline startup. The
231
+ * existing `background` strategy never delays bootstrap and reloads only before the first render. The opt-in `confirm`
232
+ * strategy also checks in the background, but waits until after the first render and reloads only with user approval.
233
+ * API deployments must remain backward compatible while an updater is rolling out because already-running older code
234
+ * cannot gain this behavior retroactively.
165
235
  */
166
236
  function provideKitAppUpdate(options = {}) {
167
- const initializer = options.strategy === 'background'
168
- ? provideAppInitializer(() => {
169
- const updates = inject(KitAppUpdateService);
170
- updates.startBackground();
171
- afterNextRender(() => updates.markInteractive());
172
- })
173
- : provideAppInitializer(() => inject(KitAppUpdateService).initialize());
174
- return makeEnvironmentProviders([initializer]);
237
+ if (options.strategy === 'confirm') {
238
+ const promptForUpdate = options.promptForUpdate;
239
+ if (typeof promptForUpdate !== 'function') {
240
+ throw new Error('provideKitAppUpdate confirm strategy requires promptForUpdate');
241
+ }
242
+ return makeEnvironmentProviders([
243
+ provideAppInitializer(() => {
244
+ const updates = inject(KitAppUpdateService);
245
+ const injector = inject(EnvironmentInjector);
246
+ updates.startConfirm(() => runInInjectionContext(injector, promptForUpdate));
247
+ afterNextRender(() => updates.markInteractive());
248
+ }),
249
+ ]);
250
+ }
251
+ if (options.promptForUpdate !== undefined) {
252
+ throw new Error('provideKitAppUpdate promptForUpdate is only valid with the confirm strategy');
253
+ }
254
+ if (options.strategy === 'background') {
255
+ return makeEnvironmentProviders([
256
+ provideAppInitializer(() => {
257
+ const updates = inject(KitAppUpdateService);
258
+ updates.startBackground();
259
+ afterNextRender(() => updates.markInteractive());
260
+ }),
261
+ ]);
262
+ }
263
+ return makeEnvironmentProviders([provideAppInitializer(() => inject(KitAppUpdateService).initialize())]);
264
+ }
265
+ async function runUpdatePrompt(promptForUpdate) {
266
+ return promptForUpdate();
175
267
  }
176
268
  function withTimeout(promise, timeoutMs) {
177
269
  return new Promise((resolve, reject) => {
@@ -1 +1 @@
1
- {"version":3,"file":"rdlabo-ionic-angular-kit-app-update.mjs","sources":["../../../projects/kit/app-update/src/lib/kit-app-update.provider.ts","../../../projects/kit/app-update/src/public-api.ts","../../../projects/kit/app-update/src/rdlabo-ionic-angular-kit-app-update.ts"],"sourcesContent":["import { DOCUMENT } from '@angular/common';\nimport type { EnvironmentProviders } from '@angular/core';\nimport { Injectable, afterNextRender, inject, makeEnvironmentProviders, provideAppInitializer } from '@angular/core';\nimport { SwUpdate } from '@angular/service-worker';\nimport type { UnrecoverableStateEvent, VersionEvent } from '@angular/service-worker';\nimport { filter, take } from 'rxjs';\n\nconst UPDATE_CHECK_TIMEOUT_MS = 10_000;\nconst UNRECOVERABLE_RELOAD_KEY = 'kit_sw_unrecoverable_reload';\n\n/** Configuration for Angular service-worker application updates. */\nexport interface KitAppUpdateOptions {\n /** `blocking` preserves startup safety; `background` never delays bootstrap and reloads only before interaction. */\n strategy?: 'blocking' | 'background';\n}\n\n/** Checks for a complete Angular service-worker update before users can interact with the application. */\n@Injectable({ providedIn: 'root' })\nexport class KitAppUpdateService {\n readonly #document = inject(DOCUMENT);\n readonly #updates = inject(SwUpdate);\n #initialization: Promise<void> | null = null;\n #backgroundStarted = false;\n #interactive = false;\n #reloading = false;\n\n /** Runs one startup update check and reloads directly into a downloaded version when one is available. */\n initialize(): Promise<void> {\n this.#initialization ??= this.#initialize();\n return this.#initialization;\n }\n\n async #initialize(): Promise<void> {\n if (!this.#canCheckForUpdate()) {\n return;\n }\n const checkForUpdate = async (): Promise<boolean | undefined> => withTimeout(this.#updates.checkForUpdate(), UPDATE_CHECK_TIMEOUT_MS);\n await checkForUpdate()\n .then((available) => {\n if (available) this.#document.location?.reload();\n })\n .catch((error: unknown) => console.error('Angular service-worker update check failed', error));\n }\n\n /** Starts an update check that never blocks bootstrap or reloads after the application becomes interactive. */\n startBackground(): void {\n if (this.#backgroundStarted || !this.#canCheckForUpdate()) {\n return;\n }\n this.#backgroundStarted = true;\n this.#updates.versionUpdates\n .pipe(\n filter((event: VersionEvent) => event.type === 'VERSION_READY'),\n take(1),\n )\n .subscribe(() => this.#reloadBeforeInteraction());\n this.#updates.unrecoverable.pipe(take(1)).subscribe((event: UnrecoverableStateEvent) => {\n console.error('Angular service-worker state is unrecoverable', event.reason);\n this.#recoverBeforeInteraction(event.reason);\n });\n void this.#updates\n .checkForUpdate()\n .then((available) => {\n if (available) {\n this.#reloadBeforeInteraction();\n }\n })\n .catch((error: unknown) => console.error('Angular service-worker update check failed', error));\n }\n\n /** Marks the first rendered application as interactive. Used by the provider's render hook. */\n markInteractive(): void {\n this.#interactive = true;\n if (!this.#reloading) {\n this.#clearRecoveryBypass();\n }\n }\n\n #canCheckForUpdate(): boolean {\n return this.#updates.isEnabled && Boolean(this.#document.defaultView?.navigator.serviceWorker?.controller);\n }\n\n #reloadBeforeInteraction(): void {\n if (this.#interactive || this.#reloading) {\n return;\n }\n this.#reloading = true;\n this.#document.location?.reload();\n }\n\n #recoverBeforeInteraction(reason: string): void {\n const location = this.#document.location;\n if (this.#interactive || this.#reloading || !location) {\n return;\n }\n const url = new URL(location.href);\n if (url.searchParams.has('sw_reload')) {\n return;\n }\n const storage = this.#document.defaultView?.sessionStorage;\n const remembered = rememberFailure(storage, reason);\n if (remembered === 'same') {\n return;\n }\n url.searchParams.set('ngsw-bypass', 'true');\n url.searchParams.set('sw_reload', '1');\n this.#reloading = true;\n location.replace(url.toString());\n }\n\n #clearRecoveryBypass(): void {\n const location = this.#document.location;\n const history = this.#document.defaultView?.history;\n if (!location || !history) {\n return;\n }\n const url = new URL(location.href);\n if (!url.searchParams.has('sw_reload')) {\n return;\n }\n url.searchParams.delete('ngsw-bypass');\n const storage = this.#document.defaultView?.sessionStorage;\n if (readFailure(storage)) {\n url.searchParams.delete('sw_reload');\n clearFailure(storage);\n }\n history.replaceState(history.state, '', url.toString());\n }\n}\n\nfunction rememberFailure(storage: Storage | undefined, reason: string): 'stored' | 'same' | 'unavailable' {\n if (!storage) {\n return 'unavailable';\n }\n let existing: string | null;\n try {\n existing = storage.getItem(UNRECOVERABLE_RELOAD_KEY);\n } catch {\n return 'unavailable';\n }\n if (existing === reason) {\n return 'same';\n }\n try {\n storage.setItem(UNRECOVERABLE_RELOAD_KEY, reason);\n return 'stored';\n } catch {\n return 'unavailable';\n }\n}\n\nfunction readFailure(storage: Storage | undefined): string | null {\n if (!storage) {\n return null;\n }\n try {\n return storage.getItem(UNRECOVERABLE_RELOAD_KEY);\n } catch {\n return null;\n }\n}\n\nfunction clearFailure(storage: Storage | undefined): void {\n try {\n storage?.removeItem(UNRECOVERABLE_RELOAD_KEY);\n } catch {\n // A retained value only suppresses the same recovery reason in this tab.\n }\n}\n\n/**\n * Provides a startup check that reloads into the latest complete web application version.\n *\n * @remarks\n * The check finishes before application bootstrap so a delayed update cannot discard user input. It times out rather\n * than preventing offline startup. API deployments must remain backward compatible while a newly adopted updater is\n * rolling out because code already running in older application versions cannot gain this behavior retroactively.\n */\nexport function provideKitAppUpdate(options: KitAppUpdateOptions = {}): EnvironmentProviders {\n const initializer =\n options.strategy === 'background'\n ? provideAppInitializer(() => {\n const updates = inject(KitAppUpdateService);\n updates.startBackground();\n afterNextRender(() => updates.markInteractive());\n })\n : provideAppInitializer(() => inject(KitAppUpdateService).initialize());\n return makeEnvironmentProviders([initializer]);\n}\n\nfunction withTimeout<T>(promise: Promise<T>, timeoutMs: number): Promise<T | undefined> {\n return new Promise((resolve, reject) => {\n const timeout = window.setTimeout(() => resolve(undefined), timeoutMs);\n void promise.then(\n (value) => {\n window.clearTimeout(timeout);\n resolve(value);\n },\n (error: unknown) => {\n window.clearTimeout(timeout);\n reject(error instanceof Error ? error : new Error(String(error)));\n },\n );\n });\n}\n","/** Automatic startup updates for Angular service-worker web applications. */\nexport * from './lib/kit-app-update.provider';\n","/**\n * Generated bundle index. Do not edit.\n */\n\nexport * from './public-api';\n"],"names":[],"mappings":";;;;;;AAOA,MAAM,uBAAuB,GAAG,MAAM;AACtC,MAAM,wBAAwB,GAAG,6BAA6B;AAQ9D;MAEa,mBAAmB,CAAA;AACrB,IAAA,SAAS,GAAG,MAAM,CAAC,QAAQ,CAAC;AAC5B,IAAA,QAAQ,GAAG,MAAM,CAAC,QAAQ,CAAC;IACpC,eAAe,GAAyB,IAAI;IAC5C,kBAAkB,GAAG,KAAK;IAC1B,YAAY,GAAG,KAAK;IACpB,UAAU,GAAG,KAAK;;IAGlB,UAAU,GAAA;AACR,QAAA,IAAI,CAAC,eAAe,KAAK,IAAI,CAAC,WAAW,EAAE;QAC3C,OAAO,IAAI,CAAC,eAAe;IAC7B;AAEA,IAAA,MAAM,WAAW,GAAA;AACf,QAAA,IAAI,CAAC,IAAI,CAAC,kBAAkB,EAAE,EAAE;YAC9B;QACF;AACA,QAAA,MAAM,cAAc,GAAG,YAA0C,WAAW,CAAC,IAAI,CAAC,QAAQ,CAAC,cAAc,EAAE,EAAE,uBAAuB,CAAC;AACrI,QAAA,MAAM,cAAc;AACjB,aAAA,IAAI,CAAC,CAAC,SAAS,KAAI;AAClB,YAAA,IAAI,SAAS;AAAE,gBAAA,IAAI,CAAC,SAAS,CAAC,QAAQ,EAAE,MAAM,EAAE;AAClD,QAAA,CAAC;AACA,aAAA,KAAK,CAAC,CAAC,KAAc,KAAK,OAAO,CAAC,KAAK,CAAC,4CAA4C,EAAE,KAAK,CAAC,CAAC;I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AACR,YAAA,MAAM,CAAC,YAAY,CAAC,OAAO,CAAC;YAC5B,OAAO,CAAC,KAAK,CAAC;AAChB,QAAA,CAAC,EACD,CAAC,KAAc,KAAI;AACjB,YAAA,MAAM,CAAC,YAAY,CAAC,OAAO,CAAC;YAC5B,MAAM,CAAC,KAAK,YAAY,KAAK,GAAG,KAAK,GAAG,IAAI,KAAK,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC;AACnE,QAAA,CAAC,CACF;AACH,IAAA,CAAC,CAAC;AACJ;;AC5MA;;ACAA;;AAEG;;;;"}
1
+ {"version":3,"file":"rdlabo-ionic-angular-kit-app-update.mjs","sources":["../../../projects/kit/app-update/src/lib/kit-app-update.provider.ts","../../../projects/kit/app-update/src/public-api.ts","../../../projects/kit/app-update/src/rdlabo-ionic-angular-kit-app-update.ts"],"sourcesContent":["import { DOCUMENT } from '@angular/common';\nimport type { EnvironmentProviders } from '@angular/core';\nimport {\n EnvironmentInjector,\n Injectable,\n afterNextRender,\n inject,\n makeEnvironmentProviders,\n provideAppInitializer,\n runInInjectionContext,\n} from '@angular/core';\nimport { SwUpdate } from '@angular/service-worker';\nimport type { UnrecoverableStateEvent, VersionEvent } from '@angular/service-worker';\nimport { filter, take } from 'rxjs';\n\nconst UPDATE_CHECK_TIMEOUT_MS = 10_000;\nconst UPDATE_PROMPT_RETRY_MS = 1_000;\nconst UNRECOVERABLE_RELOAD_KEY = 'kit_sw_unrecoverable_reload';\n\n/** Asks whether a downloaded service-worker update should be applied now. `undefined` requests a later retry. */\nexport type KitAppUpdatePrompt = () => Promise<boolean | undefined>;\n\n/** Existing configuration for startup-blocking or background service-worker updates. */\nexport interface KitAppUpdateOptions {\n strategy?: 'blocking' | 'background';\n}\n\n/** Uses a non-blocking update check and asks the user before reloading. */\nexport interface KitConfirmAppUpdateOptions {\n strategy: 'confirm';\n /**\n * Runs after the first render when a complete update is ready.\n *\n * Resolve `true` to reload, `false` when the user explicitly defers, or `undefined` when UI could not be presented and\n * should be retried. The provider supplies an Angular injection context only for the callback's synchronous execution,\n * so resolve injected dependencies before crossing an async boundary.\n */\n promptForUpdate: KitAppUpdatePrompt;\n}\n\n/** Configuration accepted by {@link provideKitAppUpdate}. */\nexport type KitAppUpdateProviderOptions = (KitAppUpdateOptions & { promptForUpdate?: never }) | KitConfirmAppUpdateOptions;\n\n/** Coordinates complete Angular service-worker updates using blocking, background, or user-confirmed application. */\n@Injectable({ providedIn: 'root' })\nexport class KitAppUpdateService {\n readonly #document = inject(DOCUMENT);\n readonly #updates = inject(SwUpdate);\n #initialization: Promise<void> | null = null;\n #backgroundStarted = false;\n #interactive = false;\n #reloading = false;\n #updateReady = false;\n #prompting = false;\n #prompted = false;\n #promptRetryScheduled = false;\n #promptForUpdate: KitAppUpdatePrompt | undefined;\n\n /** Runs one startup update check and reloads directly into a downloaded version when one is available. */\n initialize(): Promise<void> {\n this.#initialization ??= this.#initialize();\n return this.#initialization;\n }\n\n async #initialize(): Promise<void> {\n if (!this.#canCheckForUpdate()) {\n return;\n }\n const checkForUpdate = async (): Promise<boolean | undefined> => withTimeout(this.#updates.checkForUpdate(), UPDATE_CHECK_TIMEOUT_MS);\n await checkForUpdate()\n .then((available) => {\n if (available) this.#document.location?.reload();\n })\n .catch((error: unknown) => console.error('Angular service-worker update check failed', error));\n }\n\n /** Starts an update check that never blocks bootstrap or reloads after the application becomes interactive. */\n startBackground(): void {\n this.#startNonBlocking();\n }\n\n /** Starts a non-blocking update check and asks after the first render before applying a ready update. */\n startConfirm(promptForUpdate: KitAppUpdatePrompt): void {\n this.#startNonBlocking(promptForUpdate);\n }\n\n #startNonBlocking(promptForUpdate?: KitAppUpdatePrompt): void {\n if (this.#backgroundStarted || !this.#canCheckForUpdate()) {\n return;\n }\n this.#backgroundStarted = true;\n this.#promptForUpdate = promptForUpdate;\n this.#updates.versionUpdates\n .pipe(\n filter((event: VersionEvent) => event.type === 'VERSION_READY'),\n take(1),\n )\n .subscribe(() => this.#handleUpdateReady());\n this.#updates.unrecoverable.pipe(take(1)).subscribe((event: UnrecoverableStateEvent) => {\n console.error('Angular service-worker state is unrecoverable', event.reason);\n this.#recoverBeforeInteraction(event.reason);\n });\n void this.#updates\n .checkForUpdate()\n .then((available) => {\n if (available) {\n this.#handleUpdateReady();\n }\n })\n .catch((error: unknown) => console.error('Angular service-worker update check failed', error));\n }\n\n /** Marks the first rendered application as interactive. Used by the provider's render hook. */\n markInteractive(): void {\n this.#interactive = true;\n if (!this.#reloading) {\n this.#clearRecoveryBypass();\n }\n this.#promptWhenReady();\n }\n\n #canCheckForUpdate(): boolean {\n return this.#updates.isEnabled && Boolean(this.#document.defaultView?.navigator.serviceWorker?.controller);\n }\n\n #reloadBeforeInteraction(): void {\n if (this.#interactive || this.#reloading) {\n return;\n }\n this.#reloading = true;\n this.#document.location?.reload();\n }\n\n #handleUpdateReady(): void {\n if (!this.#promptForUpdate) {\n this.#reloadBeforeInteraction();\n return;\n }\n this.#updateReady = true;\n this.#promptWhenReady();\n }\n\n #promptWhenReady(): void {\n const promptForUpdate = this.#promptForUpdate;\n if (\n !this.#interactive ||\n !this.#updateReady ||\n !promptForUpdate ||\n this.#prompting ||\n this.#prompted ||\n this.#promptRetryScheduled ||\n this.#reloading\n ) {\n return;\n }\n this.#prompting = true;\n void runUpdatePrompt(promptForUpdate)\n .then((confirmed) => {\n this.#prompting = false;\n if (confirmed === undefined) {\n this.#schedulePromptRetry();\n return;\n }\n this.#prompted = true;\n this.#applyPromptResult(confirmed);\n })\n .catch((error: unknown) => {\n this.#prompting = false;\n this.#prompted = true;\n console.error('Angular service-worker update prompt failed', error);\n });\n }\n\n #schedulePromptRetry(): void {\n if (this.#promptRetryScheduled || this.#prompted || this.#reloading) {\n return;\n }\n this.#promptRetryScheduled = true;\n globalThis.setTimeout(() => {\n this.#promptRetryScheduled = false;\n this.#promptWhenReady();\n }, UPDATE_PROMPT_RETRY_MS);\n }\n\n #applyPromptResult(confirmed: boolean): void {\n if (!confirmed || this.#reloading) {\n return;\n }\n this.#reloading = true;\n this.#document.location?.reload();\n }\n\n #recoverBeforeInteraction(reason: string): void {\n const location = this.#document.location;\n if (this.#interactive || this.#reloading || !location) {\n return;\n }\n const url = new URL(location.href);\n if (url.searchParams.has('sw_reload')) {\n return;\n }\n const storage = this.#document.defaultView?.sessionStorage;\n const remembered = rememberFailure(storage, reason);\n if (remembered === 'same') {\n return;\n }\n url.searchParams.set('ngsw-bypass', 'true');\n url.searchParams.set('sw_reload', '1');\n this.#reloading = true;\n location.replace(url.toString());\n }\n\n #clearRecoveryBypass(): void {\n const location = this.#document.location;\n const history = this.#document.defaultView?.history;\n if (!location || !history) {\n return;\n }\n const url = new URL(location.href);\n if (!url.searchParams.has('sw_reload')) {\n return;\n }\n url.searchParams.delete('ngsw-bypass');\n const storage = this.#document.defaultView?.sessionStorage;\n if (readFailure(storage)) {\n url.searchParams.delete('sw_reload');\n clearFailure(storage);\n }\n history.replaceState(history.state, '', url.toString());\n }\n}\n\nfunction rememberFailure(storage: Storage | undefined, reason: string): 'stored' | 'same' | 'unavailable' {\n if (!storage) {\n return 'unavailable';\n }\n let existing: string | null;\n try {\n existing = storage.getItem(UNRECOVERABLE_RELOAD_KEY);\n } catch {\n return 'unavailable';\n }\n if (existing === reason) {\n return 'same';\n }\n try {\n storage.setItem(UNRECOVERABLE_RELOAD_KEY, reason);\n return 'stored';\n } catch {\n return 'unavailable';\n }\n}\n\nfunction readFailure(storage: Storage | undefined): string | null {\n if (!storage) {\n return null;\n }\n try {\n return storage.getItem(UNRECOVERABLE_RELOAD_KEY);\n } catch {\n return null;\n }\n}\n\nfunction clearFailure(storage: Storage | undefined): void {\n try {\n storage?.removeItem(UNRECOVERABLE_RELOAD_KEY);\n } catch {\n // A retained value only suppresses the same recovery reason in this tab.\n }\n}\n\n/**\n * Provides blocking, background, or user-confirmed adoption of complete Angular service-worker updates.\n *\n * @remarks\n * The default `blocking` strategy checks before bootstrap and times out rather than preventing offline startup. The\n * existing `background` strategy never delays bootstrap and reloads only before the first render. The opt-in `confirm`\n * strategy also checks in the background, but waits until after the first render and reloads only with user approval.\n * API deployments must remain backward compatible while an updater is rolling out because already-running older code\n * cannot gain this behavior retroactively.\n */\nexport function provideKitAppUpdate(options: KitAppUpdateProviderOptions = {}): EnvironmentProviders {\n if (options.strategy === 'confirm') {\n const promptForUpdate = options.promptForUpdate;\n if (typeof promptForUpdate !== 'function') {\n throw new Error('provideKitAppUpdate confirm strategy requires promptForUpdate');\n }\n return makeEnvironmentProviders([\n provideAppInitializer(() => {\n const updates = inject(KitAppUpdateService);\n const injector = inject(EnvironmentInjector);\n updates.startConfirm(() => runInInjectionContext(injector, promptForUpdate));\n afterNextRender(() => updates.markInteractive());\n }),\n ]);\n }\n if (options.promptForUpdate !== undefined) {\n throw new Error('provideKitAppUpdate promptForUpdate is only valid with the confirm strategy');\n }\n if (options.strategy === 'background') {\n return makeEnvironmentProviders([\n provideAppInitializer(() => {\n const updates = inject(KitAppUpdateService);\n updates.startBackground();\n afterNextRender(() => updates.markInteractive());\n }),\n ]);\n }\n return makeEnvironmentProviders([provideAppInitializer(() => inject(KitAppUpdateService).initialize())]);\n}\n\nasync function runUpdatePrompt(promptForUpdate: KitAppUpdatePrompt): Promise<boolean | undefined> {\n return promptForUpdate();\n}\n\nfunction withTimeout<T>(promise: Promise<T>, timeoutMs: number): Promise<T | undefined> {\n return new Promise((resolve, reject) => {\n const timeout = window.setTimeout(() => resolve(undefined), timeoutMs);\n void promise.then(\n (value) => {\n window.clearTimeout(timeout);\n resolve(value);\n },\n (error: unknown) => {\n window.clearTimeout(timeout);\n reject(error instanceof Error ? error : new Error(String(error)));\n },\n );\n });\n}\n","/** Automatic startup updates for Angular service-worker web applications. */\nexport * from './lib/kit-app-update.provider';\n","/**\n * Generated bundle index. Do not edit.\n */\n\nexport * from './public-api';\n"],"names":[],"mappings":";;;;;;AAeA,MAAM,uBAAuB,GAAG,MAAM;AACtC,MAAM,sBAAsB,GAAG,KAAK;AACpC,MAAM,wBAAw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C;AAChB,QAAA,CAAC,EACD,CAAC,KAAc,KAAI;AACjB,YAAA,MAAM,CAAC,YAAY,CAAC,OAAO,CAAC;YAC5B,MAAM,CAAC,KAAK,YAAY,KAAK,GAAG,KAAK,GAAG,IAAI,KAAK,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC;AACnE,QAAA,CAAC,CACF;AACH,IAAA,CAAC,CAAC;AACJ;;AC1UA;;ACAA;;AAEG;;;;"}
@@ -941,22 +941,36 @@ class OfflineReplicaTransientWriteError extends Error {
941
941
  this.name = 'OfflineReplicaTransientWriteError';
942
942
  }
943
943
  }
944
- function normalizeOfflineReplicaTransientWriteError(error) {
945
- if (error instanceof OfflineReplicaTransientWriteError)
946
- return error;
944
+ function transientSqliteLockReason(error) {
947
945
  const code = typeof error === 'object' && error !== null && typeof error.code === 'string'
948
946
  ? error.code.toUpperCase()
949
947
  : '';
950
948
  const message = error instanceof Error ? error.message : typeof error === 'string' ? error : '';
951
949
  const normalizedMessage = message.toUpperCase();
952
950
  if (code.includes('SQLITE_BUSY') || normalizedMessage.includes('SQLITE_BUSY')) {
953
- return new OfflineReplicaTransientWriteError('sqlite_busy', message || 'SQLite is busy.', { cause: error });
951
+ return 'sqlite_busy';
954
952
  }
955
953
  if (code.includes('SQLITE_LOCKED') ||
956
954
  normalizedMessage.includes('SQLITE_LOCKED') ||
957
955
  message.includes('database is locked') ||
958
956
  message.includes('database table is locked')) {
959
- return new OfflineReplicaTransientWriteError('sqlite_locked', message || 'SQLite database is locked.', { cause: error });
957
+ return 'sqlite_locked';
958
+ }
959
+ return null;
960
+ }
961
+ /** Returns whether SQLite reported a transient busy/locked condition in any supported error shape. */
962
+ function isTransientSqliteLockError(error) {
963
+ return error instanceof OfflineReplicaTransientWriteError
964
+ ? error.reason === 'sqlite_busy' || error.reason === 'sqlite_locked'
965
+ : transientSqliteLockReason(error) !== null;
966
+ }
967
+ function normalizeOfflineReplicaTransientWriteError(error) {
968
+ if (error instanceof OfflineReplicaTransientWriteError)
969
+ return error;
970
+ const reason = transientSqliteLockReason(error);
971
+ if (reason) {
972
+ const message = error instanceof Error ? error.message : typeof error === 'string' ? error : '';
973
+ return new OfflineReplicaTransientWriteError(reason, message || (reason === 'sqlite_busy' ? 'SQLite is busy.' : 'SQLite database is locked.'), { cause: error });
960
974
  }
961
975
  return error;
962
976
  }
@@ -5771,6 +5785,7 @@ async function createRandomOfflineEncryptionKey() {
5771
5785
  return Array.from(bytes, (byte) => byte.toString(16).padStart(2, '0')).join('');
5772
5786
  }
5773
5787
  const settledSqliteOperation = async () => undefined;
5788
+ const COMMUNITY_SQLITE_OPEN_RETRY_DELAYS_MS = [50, 150, 300];
5774
5789
  const communitySqliteDrivers = new WeakMap();
5775
5790
  function sqliteErrorMessage(error) {
5776
5791
  if (error instanceof Error)
@@ -5780,6 +5795,17 @@ function sqliteErrorMessage(error) {
5780
5795
  }
5781
5796
  return String(error);
5782
5797
  }
5798
+ async function openCommunitySqliteDatabase(database) {
5799
+ for (const delayMs of COMMUNITY_SQLITE_OPEN_RETRY_DELAYS_MS) {
5800
+ const result = await database.open().then(() => ({ ok: true }), (error) => ({ ok: false, error }));
5801
+ if (result.ok)
5802
+ return;
5803
+ if (!isTransientSqliteLockError(result.error))
5804
+ throw result.error;
5805
+ await new Promise((resolve) => setTimeout(resolve, delayMs));
5806
+ }
5807
+ await database.open();
5808
+ }
5783
5809
  function normalizeCommunitySqliteDatabaseName(database) {
5784
5810
  return database.endsWith('.db') ? database.slice(0, -3) : database;
5785
5811
  }
@@ -5862,7 +5888,7 @@ function createCommunitySqliteDriver(connection, encrypted = COMMUNITY_SQLITE_EN
5862
5888
  const opening = (async () => {
5863
5889
  await ensureSecret(createEncryptionKey);
5864
5890
  const value = await createReloadSafeCommunitySqliteDatabase(connection, databaseName, encrypted);
5865
- await value.open();
5891
+ await openCommunitySqliteDatabase(value);
5866
5892
  databases.set(databaseKey, value);
5867
5893
  return value;
5868
5894
  })();