@rdlabo/ionic-angular-kit 21.5.16 → 21.5.18
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/README.md
CHANGED
|
@@ -391,11 +391,13 @@ A fleet-canonical HTTP interceptor with:
|
|
|
391
391
|
|
|
392
392
|
The optional `offline` entry point provides a user/partition-scoped local replica, durable outbox, authenticated
|
|
393
393
|
session boundary, cursor-based delta pull, aggregate-ordered replay, optimistic updates, retry classification, and a
|
|
394
|
-
|
|
395
|
-
a command executor through `provideOffline(...)`. External-source or HTTP read caches use
|
|
394
|
+
request-policy interceptor. Synchronized applications provide URL/DTO read policies, optional local-first mutation
|
|
395
|
+
policies, a replica puller, and a command executor through `provideOffline(...)`. External-source or HTTP read caches use
|
|
396
396
|
`mode: 'readCacheOnly'`; the kit then supplies the empty pull/executor boundary instead of making every product
|
|
397
397
|
declare dummy adapters.
|
|
398
|
-
Mutations
|
|
398
|
+
Mutations may still call `OfflineSyncService.enqueue` explicitly. A product that must keep ordinary HTTP services
|
|
399
|
+
offline-unaware can instead register `mutationPolicies`; a matched `POST` / `PUT` / `PATCH` / `DELETE` is prepared
|
|
400
|
+
locally before transport and returns an optimistic response while the Outbox owns remote replay.
|
|
399
401
|
Web storage uses Ionic Storage; iOS and Android use encrypted `@capacitor-community/sqlite`. Importing either the
|
|
400
402
|
primary entry point or `/offline` does not pull the optional native SQLite plugin into web-only applications.
|
|
401
403
|
|
|
@@ -447,8 +449,51 @@ returned.
|
|
|
447
449
|
|
|
448
450
|
The offline interceptor observes real transport responses to update API reachability. For matched `GET`
|
|
449
451
|
requests only, a transport failure with `status=0` may return a local replica response tagged
|
|
450
|
-
`X-Offline-Response: local`.
|
|
451
|
-
|
|
452
|
+
`X-Offline-Response: local`. A read policy's optional `projectResponse(response, source)` hook receives both remote
|
|
453
|
+
and local results, so the remote branch can persist first and both branches can return a body from one composer.
|
|
454
|
+
Matched mutation policies return `X-Offline-Response: optimistic` without starting transport. Unmatched writes go to
|
|
455
|
+
transport unchanged. Outbox replay requests bypass policy with `OFFLINE_BYPASS` while still using the same auth
|
|
456
|
+
interceptor and transport observation. Mutation policy matchers must be mutually exclusive: zero matches use normal
|
|
457
|
+
transport, exactly one match runs its `prepare()`, and multiple matches throw `OfflineMutationPolicyConflictError`
|
|
458
|
+
before either `prepare()` or transport starts. This fail-fast boundary prevents provider registration order from
|
|
459
|
+
silently selecting the wrong replica/outbox mutation.
|
|
460
|
+
|
|
461
|
+
```ts
|
|
462
|
+
@Injectable()
|
|
463
|
+
class ItemReadPolicy implements OfflineRequestPolicy {
|
|
464
|
+
resolve(request: HttpRequest<unknown>): OfflineRequestPlan | null {
|
|
465
|
+
if (request.method !== 'GET' || !request.url.endsWith('/items')) return null;
|
|
466
|
+
return {
|
|
467
|
+
kind: 'read',
|
|
468
|
+
readLocal: () => this.items.readResponse(),
|
|
469
|
+
projectResponse: async (response, source) => {
|
|
470
|
+
if (source === 'remote') await this.items.persist(response.body);
|
|
471
|
+
return response.clone({ body: await this.items.compose() });
|
|
472
|
+
},
|
|
473
|
+
};
|
|
474
|
+
}
|
|
475
|
+
}
|
|
476
|
+
|
|
477
|
+
@Injectable()
|
|
478
|
+
class ItemMutationPolicy implements OfflineMutationRequestPolicy {
|
|
479
|
+
resolve(request: HttpRequest<unknown>): OfflineMutationRequestPlan | null {
|
|
480
|
+
if (request.method !== 'POST' || !request.url.endsWith('/items')) return null;
|
|
481
|
+
return {
|
|
482
|
+
kind: 'mutation',
|
|
483
|
+
prepare: async () => {
|
|
484
|
+
const optimistic = await this.items.enqueueCreate(request.body);
|
|
485
|
+
return new HttpResponse({ status: 202, body: optimistic });
|
|
486
|
+
},
|
|
487
|
+
};
|
|
488
|
+
}
|
|
489
|
+
}
|
|
490
|
+
|
|
491
|
+
provideOffline({
|
|
492
|
+
// repository/schema/executor/puller options omitted
|
|
493
|
+
requestPolicies: [ItemReadPolicy],
|
|
494
|
+
mutationPolicies: [ItemMutationPolicy],
|
|
495
|
+
});
|
|
496
|
+
```
|
|
452
497
|
|
|
453
498
|
The native offline runtime uses `@capacitor-community/sqlite` on iOS and Android. Install the plugin in the app and
|
|
454
499
|
sync native projects:
|
|
@@ -5,9 +5,9 @@ import { toObservable } from '@angular/core/rxjs-interop';
|
|
|
5
5
|
import { map, distinctUntilChanged } from 'rxjs/operators';
|
|
6
6
|
import { App } from '@capacitor/app';
|
|
7
7
|
import { Network } from '@capacitor/network';
|
|
8
|
+
import { HttpErrorResponse, HttpContextToken, HttpResponse } from '@angular/common/http';
|
|
8
9
|
import { Capacitor } from '@capacitor/core';
|
|
9
|
-
import {
|
|
10
|
-
import { defer, catchError, throwError, tap, from, concatMap, of } from 'rxjs';
|
|
10
|
+
import { defer, catchError, throwError, concatMap, from, map as map$1, of, tap } from 'rxjs';
|
|
11
11
|
|
|
12
12
|
const MAX_OFFLINE_NATURAL_KEY_TEXT_BYTES = 1024;
|
|
13
13
|
const IDENTIFIER_PATTERN = /^[a-z][a-z0-9_]*$/;
|
|
@@ -3309,18 +3309,97 @@ function assertOfflineRemoteIdentity(identity) {
|
|
|
3309
3309
|
}
|
|
3310
3310
|
}
|
|
3311
3311
|
|
|
3312
|
+
/**
|
|
3313
|
+
* A successful HTTP response that violates the offline mutation protocol.
|
|
3314
|
+
*
|
|
3315
|
+
* Status 502 deliberately keeps the response in the retryable server-failure class.
|
|
3316
|
+
*/
|
|
3317
|
+
class OfflineMutationProtocolError extends HttpErrorResponse {
|
|
3318
|
+
constructor(message, url) {
|
|
3319
|
+
super({
|
|
3320
|
+
error: { code: 'OFFLINE_MUTATION_PROTOCOL_ERROR', message },
|
|
3321
|
+
status: 502,
|
|
3322
|
+
statusText: 'Bad Gateway',
|
|
3323
|
+
url,
|
|
3324
|
+
});
|
|
3325
|
+
}
|
|
3326
|
+
}
|
|
3327
|
+
const hasOwn = (value, key) => Object.prototype.hasOwnProperty.call(value, key);
|
|
3328
|
+
const isPositiveSafeInteger = (value) => typeof value === 'number' && Number.isSafeInteger(value) && value > 0;
|
|
3329
|
+
const isRecord = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
3330
|
+
/** Strictly parses the wire envelope returned by an offline mutation endpoint. */
|
|
3331
|
+
function parseOfflineMutationEnvelope(input, options) {
|
|
3332
|
+
const label = options.label ?? 'Offline mutation response';
|
|
3333
|
+
const invalid = (detail) => {
|
|
3334
|
+
throw new OfflineMutationProtocolError(`${label} ${detail}`, options.url);
|
|
3335
|
+
};
|
|
3336
|
+
const envelope = isRecord(input) ? input : invalid('must be an object.');
|
|
3337
|
+
let id = null;
|
|
3338
|
+
switch (options.id) {
|
|
3339
|
+
case 'required': {
|
|
3340
|
+
const rawId = envelope['id'];
|
|
3341
|
+
id = hasOwn(envelope, 'id') && isPositiveSafeInteger(rawId) ? rawId : invalid('id must be a positive safe integer.');
|
|
3342
|
+
break;
|
|
3343
|
+
}
|
|
3344
|
+
case 'optional': {
|
|
3345
|
+
if (hasOwn(envelope, 'id')) {
|
|
3346
|
+
const rawId = envelope['id'];
|
|
3347
|
+
id = isPositiveSafeInteger(rawId) ? rawId : invalid('id must be a positive safe integer when present.');
|
|
3348
|
+
}
|
|
3349
|
+
break;
|
|
3350
|
+
}
|
|
3351
|
+
case 'forbidden':
|
|
3352
|
+
if (['id', 'serverId', 'remoteId'].some((key) => hasOwn(envelope, key))) {
|
|
3353
|
+
invalid('must not contain id, serverId, or remoteId.');
|
|
3354
|
+
}
|
|
3355
|
+
break;
|
|
3356
|
+
}
|
|
3357
|
+
const rawRevision = envelope['revision'];
|
|
3358
|
+
const revision = hasOwn(envelope, 'revision') && isPositiveSafeInteger(rawRevision) ? rawRevision : invalid('revision must be a positive safe integer.');
|
|
3359
|
+
const values = envelope['values'];
|
|
3360
|
+
switch (options.values) {
|
|
3361
|
+
case 'object':
|
|
3362
|
+
if (!isRecord(values)) {
|
|
3363
|
+
invalid('values must be an object.');
|
|
3364
|
+
}
|
|
3365
|
+
break;
|
|
3366
|
+
case 'tombstone':
|
|
3367
|
+
if (values !== null) {
|
|
3368
|
+
invalid('values must be null.');
|
|
3369
|
+
}
|
|
3370
|
+
break;
|
|
3371
|
+
case 'object-or-tombstone':
|
|
3372
|
+
if (values !== null && !isRecord(values)) {
|
|
3373
|
+
invalid('values must be an object or null.');
|
|
3374
|
+
}
|
|
3375
|
+
break;
|
|
3376
|
+
case 'optional-object-or-tombstone':
|
|
3377
|
+
if (values !== undefined && values !== null && !isRecord(values)) {
|
|
3378
|
+
invalid('values must be an object, null, or undefined.');
|
|
3379
|
+
}
|
|
3380
|
+
break;
|
|
3381
|
+
}
|
|
3382
|
+
return { id, revision, values: values };
|
|
3383
|
+
}
|
|
3384
|
+
|
|
3312
3385
|
/** outbox再送時にoffline interceptorだけを迂回する。認証・retryは維持する。 */
|
|
3313
3386
|
const OFFLINE_BYPASS = new HttpContextToken(() => false);
|
|
3314
|
-
/** Header attached to
|
|
3387
|
+
/** Header attached to synthetic local or optimistic responses. */
|
|
3315
3388
|
const OFFLINE_RESPONSE_HEADER = 'X-Offline-Response';
|
|
3316
3389
|
/** Multi-provider token containing product request policies. */
|
|
3317
3390
|
const OFFLINE_REQUEST_POLICIES = new InjectionToken('OFFLINE_REQUEST_POLICIES', {
|
|
3318
3391
|
factory: () => [],
|
|
3319
3392
|
});
|
|
3393
|
+
/** Multi-provider token containing product mutation policies. */
|
|
3394
|
+
const OFFLINE_MUTATION_REQUEST_POLICIES = new InjectionToken('OFFLINE_MUTATION_REQUEST_POLICIES', { factory: () => [] });
|
|
3320
3395
|
/** Registers one product request policy with the offline interceptor. */
|
|
3321
3396
|
function provideOfflineRequestPolicy(policy) {
|
|
3322
3397
|
return [policy, { provide: OFFLINE_REQUEST_POLICIES, useExisting: policy, multi: true }];
|
|
3323
3398
|
}
|
|
3399
|
+
/** Registers one product mutation policy with the offline interceptor. */
|
|
3400
|
+
function provideOfflineMutationRequestPolicy(policy) {
|
|
3401
|
+
return [policy, { provide: OFFLINE_MUTATION_REQUEST_POLICIES, useExisting: policy, multi: true }];
|
|
3402
|
+
}
|
|
3324
3403
|
/** Resolves the first product policy matching an HTTP request. */
|
|
3325
3404
|
class OfflineRequestPolicyRegistry {
|
|
3326
3405
|
#policies = inject(OFFLINE_REQUEST_POLICIES);
|
|
@@ -3339,6 +3418,37 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.17", ngImpo
|
|
|
3339
3418
|
type: Injectable,
|
|
3340
3419
|
args: [{ providedIn: 'root' }]
|
|
3341
3420
|
}] });
|
|
3421
|
+
/** Raised when more than one mutation policy claims the same request. */
|
|
3422
|
+
class OfflineMutationPolicyConflictError extends Error {
|
|
3423
|
+
constructor(request, matchCount) {
|
|
3424
|
+
super(`${matchCount} offline mutation policies matched ${request.method} ${request.urlWithParams}`);
|
|
3425
|
+
this.name = 'OfflineMutationPolicyConflictError';
|
|
3426
|
+
}
|
|
3427
|
+
}
|
|
3428
|
+
/** Resolves the only product mutation policy matching a write request. */
|
|
3429
|
+
class OfflineMutationRequestPolicyRegistry {
|
|
3430
|
+
#policies = inject(OFFLINE_MUTATION_REQUEST_POLICIES);
|
|
3431
|
+
resolve(request) {
|
|
3432
|
+
let matched = null;
|
|
3433
|
+
let matchCount = 0;
|
|
3434
|
+
for (const policy of this.#policies) {
|
|
3435
|
+
const plan = policy.resolve(request);
|
|
3436
|
+
if (!plan)
|
|
3437
|
+
continue;
|
|
3438
|
+
matched = plan;
|
|
3439
|
+
matchCount += 1;
|
|
3440
|
+
}
|
|
3441
|
+
if (matchCount > 1)
|
|
3442
|
+
throw new OfflineMutationPolicyConflictError(request, matchCount);
|
|
3443
|
+
return matched;
|
|
3444
|
+
}
|
|
3445
|
+
static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.17", ngImport: i0, type: OfflineMutationRequestPolicyRegistry, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
|
|
3446
|
+
static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "21.2.17", ngImport: i0, type: OfflineMutationRequestPolicyRegistry, providedIn: 'root' }); }
|
|
3447
|
+
}
|
|
3448
|
+
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.17", ngImport: i0, type: OfflineMutationRequestPolicyRegistry, decorators: [{
|
|
3449
|
+
type: Injectable,
|
|
3450
|
+
args: [{ providedIn: 'root' }]
|
|
3451
|
+
}] });
|
|
3342
3452
|
|
|
3343
3453
|
/** DI token for the native community SQLite driver. */
|
|
3344
3454
|
const COMMUNITY_SQLITE = new InjectionToken('COMMUNITY_SQLITE', {
|
|
@@ -4166,26 +4276,41 @@ function provideOffline(options) {
|
|
|
4166
4276
|
: { provide: OFFLINE_REPLICA_PULLER, useValue: READ_CACHE_ONLY_REPLICA_PULLER },
|
|
4167
4277
|
...(options.commandHooks ? [options.commandHooks, { provide: OFFLINE_COMMAND_HOOKS, useExisting: options.commandHooks }] : []),
|
|
4168
4278
|
...options.requestPolicies.flatMap((policy) => provideOfflineRequestPolicy(policy)),
|
|
4279
|
+
...(options.mutationPolicies ?? []).flatMap((policy) => provideOfflineMutationRequestPolicy(policy)),
|
|
4169
4280
|
...(options.providers ?? []),
|
|
4170
4281
|
provideAppInitializer(() => inject(OfflineCoordinatorService).initialize()),
|
|
4171
4282
|
]);
|
|
4172
4283
|
}
|
|
4173
4284
|
|
|
4174
|
-
|
|
4285
|
+
const LOCAL_FIRST_MUTATION_METHODS = new Set(['POST', 'PUT', 'PATCH', 'DELETE']);
|
|
4286
|
+
/** Applies product read and local-first mutation policies while observing real API reachability. */
|
|
4175
4287
|
const offlineInterceptor = (request, next) => {
|
|
4176
4288
|
const network = inject(OfflineNetworkService);
|
|
4177
4289
|
const transport = () => observeTransport(next(request), network);
|
|
4178
4290
|
if (request.context.get(OFFLINE_BYPASS))
|
|
4179
4291
|
return transport();
|
|
4180
|
-
if (request.method
|
|
4181
|
-
|
|
4182
|
-
|
|
4183
|
-
|
|
4184
|
-
|
|
4185
|
-
|
|
4186
|
-
return transport();
|
|
4187
|
-
|
|
4292
|
+
if (request.method === 'GET') {
|
|
4293
|
+
const registry = inject(OfflineRequestPolicyRegistry);
|
|
4294
|
+
const fallback = inject(OfflineRequestFallbackService);
|
|
4295
|
+
const plan = registry.resolve(request);
|
|
4296
|
+
if (!plan)
|
|
4297
|
+
return transport();
|
|
4298
|
+
return defer(transport).pipe(catchError((error) => fallback.handle(request, error, plan) ?? throwError(() => error)), concatMap((event) => projectRemoteResponse(event, plan)));
|
|
4299
|
+
}
|
|
4300
|
+
if (LOCAL_FIRST_MUTATION_METHODS.has(request.method)) {
|
|
4301
|
+
const plan = inject(OfflineMutationRequestPolicyRegistry).resolve(request);
|
|
4302
|
+
if (plan) {
|
|
4303
|
+
return defer(() => from(plan.prepare())).pipe(map$1((response) => response.clone({ headers: response.headers.set(OFFLINE_RESPONSE_HEADER, 'optimistic') })));
|
|
4304
|
+
}
|
|
4305
|
+
}
|
|
4306
|
+
return transport();
|
|
4188
4307
|
};
|
|
4308
|
+
function projectRemoteResponse(event, plan) {
|
|
4309
|
+
if (!(event instanceof HttpResponse) || !plan.projectResponse)
|
|
4310
|
+
return of(event);
|
|
4311
|
+
const source = event.headers.get(OFFLINE_RESPONSE_HEADER) === 'local' ? 'local' : 'remote';
|
|
4312
|
+
return from(plan.projectResponse(event, source)).pipe(map$1((response) => source === 'local' ? response.clone({ headers: response.headers.set(OFFLINE_RESPONSE_HEADER, 'local') }) : response));
|
|
4313
|
+
}
|
|
4189
4314
|
function observeTransport(source, network) {
|
|
4190
4315
|
return source.pipe(tap({
|
|
4191
4316
|
next: (event) => {
|
|
@@ -4232,5 +4357,5 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.17", ngImpo
|
|
|
4232
4357
|
* Generated bundle index. Do not edit.
|
|
4233
4358
|
*/
|
|
4234
4359
|
|
|
4235
|
-
export { COMMUNITY_SQLITE, DEFAULT_OFFLINE_COMMAND_HOOKS, IonicOfflineRepository, OFFLINE_BYPASS, OFFLINE_COMMAND_EXECUTOR, OFFLINE_COMMAND_HOOKS, OFFLINE_KIT_OPTIONS, OFFLINE_REPLICA_PULLER, OFFLINE_REPOSITORY, OFFLINE_REQUEST_POLICIES, OFFLINE_RESPONSE_HEADER, OFFLINE_SCHEMA_VERSION, OFFLINE_SYNC_CONTEXT, OfflineCoordinatorService, OfflineNetworkService, OfflineOutboxCapacityError, OfflinePayloadValidationError, OfflineReplicaMutationCoordinator, OfflineReplicaPullService, OfflineRequestFallbackService, OfflineRequestPolicyRegistry, OfflineSessionService, OfflineSyncService, SqliteOfflineRepository, assertOfflineLocalId, assertOfflineReplicaGeneratedRemoteId, assertOfflineReplicaNaturalKeyBaseline, booleanColumn, canonicalOfflineCommandIdentity, canonicalOfflinePrincipalId, canonicalOfflineRemoteIdentity, canonicalOfflineReplicaIdentity, commandIdentityFromReplicaIdentity, commandIdentityMatchesReplicaRow, createCommunitySqliteDriver, createOfflineAuthBridge, createRandomOfflineEncryptionKey, datetime, decodeOfflineReplicaValues, defineOfflineReplicaSchema, defineReplicaEntity, encodeOfflineReplicaValues, generatedId, ignored, integer, isOfflineFallbackError, json, localOnly, naturalKey, normalizeOfflineNaturalKey, normalizeOfflineReplicaPullPage, nullable, offlineCommandLookupIdentity, offlineCommandTargetFromReplicaRow, offlineGeneratedReplicaIdentity, offlineInterceptor, offlineNaturalKeyFromValues, offlineNaturalReplicaIdentity, offlineReplicaRemoteIdentity, offlineSessionManifestAllows, parseOfflineCommandIdentity, parseOfflinePrincipalId, projectOfflineReplicaValues, provideOffline, provideOfflineRequestPolicy, real, replicaAddressFromIdentity, requirePositiveOfflineInteger, selectOfflineRepository, serializeOfflineCommandIdentity, sha256OfflineReplicaSchema, text };
|
|
4360
|
+
export { COMMUNITY_SQLITE, DEFAULT_OFFLINE_COMMAND_HOOKS, IonicOfflineRepository, OFFLINE_BYPASS, OFFLINE_COMMAND_EXECUTOR, OFFLINE_COMMAND_HOOKS, OFFLINE_KIT_OPTIONS, OFFLINE_MUTATION_REQUEST_POLICIES, OFFLINE_REPLICA_PULLER, OFFLINE_REPOSITORY, OFFLINE_REQUEST_POLICIES, OFFLINE_RESPONSE_HEADER, OFFLINE_SCHEMA_VERSION, OFFLINE_SYNC_CONTEXT, OfflineCoordinatorService, OfflineMutationPolicyConflictError, OfflineMutationProtocolError, OfflineMutationRequestPolicyRegistry, OfflineNetworkService, OfflineOutboxCapacityError, OfflinePayloadValidationError, OfflineReplicaMutationCoordinator, OfflineReplicaPullService, OfflineRequestFallbackService, OfflineRequestPolicyRegistry, OfflineSessionService, OfflineSyncService, SqliteOfflineRepository, assertOfflineLocalId, assertOfflineReplicaGeneratedRemoteId, assertOfflineReplicaNaturalKeyBaseline, booleanColumn, canonicalOfflineCommandIdentity, canonicalOfflinePrincipalId, canonicalOfflineRemoteIdentity, canonicalOfflineReplicaIdentity, commandIdentityFromReplicaIdentity, commandIdentityMatchesReplicaRow, createCommunitySqliteDriver, createOfflineAuthBridge, createRandomOfflineEncryptionKey, datetime, decodeOfflineReplicaValues, defineOfflineReplicaSchema, defineReplicaEntity, encodeOfflineReplicaValues, generatedId, ignored, integer, isOfflineFallbackError, json, localOnly, naturalKey, normalizeOfflineNaturalKey, normalizeOfflineReplicaPullPage, nullable, offlineCommandLookupIdentity, offlineCommandTargetFromReplicaRow, offlineGeneratedReplicaIdentity, offlineInterceptor, offlineNaturalKeyFromValues, offlineNaturalReplicaIdentity, offlineReplicaRemoteIdentity, offlineSessionManifestAllows, parseOfflineCommandIdentity, parseOfflineMutationEnvelope, parseOfflinePrincipalId, projectOfflineReplicaValues, provideOffline, provideOfflineMutationRequestPolicy, provideOfflineRequestPolicy, real, replicaAddressFromIdentity, requirePositiveOfflineInteger, selectOfflineRepository, serializeOfflineCommandIdentity, sha256OfflineReplicaSchema, text };
|
|
4236
4361
|
//# sourceMappingURL=rdlabo-ionic-angular-kit-offline.mjs.map
|