@vrtmrz/livesync-commonlib 0.1.23 → 0.1.25

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 (53) hide show
  1. package/dist/API/processSetting.d.ts +1 -1
  2. package/dist/API/processSetting.js +10 -6
  3. package/dist/common/ConnectionString.js +15 -8
  4. package/dist/common/models/setting.const.qr.js +5 -0
  5. package/dist/common/models/setting.lifecycle.js +5 -3
  6. package/dist/common/models/setting.p2p.d.ts +10 -0
  7. package/dist/common/models/setting.p2p.js +13 -0
  8. package/dist/common/models/setting.type.d.ts +10 -0
  9. package/dist/common/models/tweak.compatibility.d.ts +34 -0
  10. package/dist/common/models/tweak.compatibility.js +110 -0
  11. package/dist/common/models/tweak.definition.d.ts +110 -19
  12. package/dist/common/models/tweak.definition.js +62 -29
  13. package/dist/common/settingConstants.d.ts +5 -0
  14. package/dist/common/types.d.ts +6 -3
  15. package/dist/common/types.js +6 -0
  16. package/dist/common/utils.js +4 -1
  17. package/dist/p2p/P2PService.d.ts +7 -1
  18. package/dist/p2p/P2PService.js +13 -7
  19. package/dist/p2p/index.d.ts +3 -1
  20. package/dist/p2p/index.js +6 -0
  21. package/dist/pouchdb/LiveSyncDBFunctions.d.ts +3 -3
  22. package/dist/pouchdb/LiveSyncDBFunctions.js +9 -15
  23. package/dist/replication/CentralCompatibility.d.ts +4 -2
  24. package/dist/replication/CentralCompatibility.js +5 -3
  25. package/dist/replication/couchdb/LiveSyncReplicator.js +10 -2
  26. package/dist/replication/journal/LiveSyncJournalReplicator.d.ts +2 -2
  27. package/dist/replication/journal/LiveSyncJournalReplicator.js +18 -4
  28. package/dist/replication/trystero/P2PRoomSessionOwner.d.ts +22 -1
  29. package/dist/replication/trystero/P2PRoomSessionOwner.js +193 -13
  30. package/dist/replication/trystero/TrysteroReplicator.js +12 -7
  31. package/dist/replication/trystero/TrysteroReplicatorP2PServer.d.ts +1 -0
  32. package/dist/replication/trystero/TrysteroReplicatorP2PServer.js +10 -3
  33. package/dist/replication/trystero/p2pReplicatorConfigurationIdentity.js +6 -3
  34. package/dist/replication/trystero/useP2PReplicatorFeature.d.ts +6 -1
  35. package/dist/replication/trystero/useP2PReplicatorFeature.js +7 -4
  36. package/dist/rpc/transports/trysteroUtils.d.ts +2 -2
  37. package/dist/rpc/transports/trysteroUtils.js +32 -2
  38. package/dist/serviceFeatures/remoteConfig.js +3 -0
  39. package/dist/services/base/IService.d.ts +3 -3
  40. package/dist/services/base/ReplicationService.d.ts +2 -2
  41. package/dist/services/base/ReplicationService.js +14 -11
  42. package/dist/services/base/SettingService.d.ts +1 -0
  43. package/dist/services/base/SettingService.js +37 -9
  44. package/dist/services/base/TweakValueService.d.ts +5 -3
  45. package/dist/services/implements/injectable/InjectableTweakValueService.d.ts +5 -5
  46. package/dist/settings.d.ts +3 -0
  47. package/dist/settings.js +2 -0
  48. package/dist/worker/bgWorker.js +1 -1
  49. package/docs/development.md +3 -3
  50. package/docs/p2p-transport-lifecycle.md +86 -4
  51. package/docs/proven-in-use.md +32 -0
  52. package/docs/settings-lifecycle.md +20 -1
  53. package/package.json +1 -1
@@ -1,33 +1,63 @@
1
1
  import { ChunkAlgorithms, E2EEAlgorithms } from "./setting.const.js";
2
2
  import { DEFAULT_SETTINGS } from "./setting.const.defaults.js";
3
- const TweakValuesShouldMatchedTemplate = {
4
- minimumChunkSize: 20,
5
- longLineThreshold: 250,
6
- encrypt: false,
7
- usePathObfuscation: false,
8
- enableCompression: false,
9
- useEden: false,
10
- customChunkSize: 0,
11
- useDynamicIterationCount: false,
12
- hashAlg: "xxhash64",
13
- enableChunkSplitterV2: false,
14
- maxChunksInEden: 10,
15
- maxTotalLengthInEden: 1024,
16
- maxAgeInEden: 10,
17
- usePluginSyncV2: false,
18
- handleFilenameCaseSensitive: false,
19
- useSegmenter: false,
20
- E2EEAlgorithm: E2EEAlgorithms.V2,
21
- chunkSplitterVersion: ChunkAlgorithms.RabinKarp
22
- };
3
+ const TweakCompatibilityRules = Object.freeze([
4
+ { key: "minimumChunkSize", templateValue: 20, reconstruction: "none" },
5
+ { key: "longLineThreshold", templateValue: 250, reconstruction: "none" },
6
+ { key: "encrypt", templateValue: false, reconstruction: "required" },
7
+ { key: "usePathObfuscation", templateValue: false, reconstruction: "required" },
8
+ { key: "enableCompression", templateValue: false, reconstruction: "none" },
9
+ { key: "useEden", templateValue: false, reconstruction: "none" },
10
+ { key: "customChunkSize", templateValue: 0, reconstruction: "recommended", compatibleLossyOrder: 1 },
11
+ { key: "useDynamicIterationCount", templateValue: false, reconstruction: "required" },
12
+ { key: "hashAlg", templateValue: "xxhash64", reconstruction: "recommended", compatibleLossyOrder: 0 },
13
+ { key: "enableChunkSplitterV2", templateValue: false, reconstruction: "none" },
14
+ { key: "maxChunksInEden", templateValue: 10, reconstruction: "none" },
15
+ { key: "maxTotalLengthInEden", templateValue: 1024, reconstruction: "none" },
16
+ { key: "maxAgeInEden", templateValue: 10, reconstruction: "none" },
17
+ {
18
+ key: "usePluginSyncV2",
19
+ templateValue: false,
20
+ reconstruction: "none",
21
+ knownDefault: false
22
+ },
23
+ {
24
+ key: "handleFilenameCaseSensitive",
25
+ templateValue: false,
26
+ reconstruction: "required",
27
+ knownDefault: false
28
+ },
29
+ { key: "useSegmenter", templateValue: false, reconstruction: "none" },
30
+ {
31
+ key: "E2EEAlgorithm",
32
+ templateValue: E2EEAlgorithms.V2,
33
+ reconstruction: "none",
34
+ knownDefault: DEFAULT_SETTINGS.E2EEAlgorithm
35
+ },
36
+ {
37
+ key: "chunkSplitterVersion",
38
+ templateValue: ChunkAlgorithms.RabinKarp,
39
+ reconstruction: "recommended",
40
+ knownDefault: DEFAULT_SETTINGS.chunkSplitterVersion,
41
+ compatibleLossyOrder: 2
42
+ }
43
+ ]);
44
+ const TweakValuesShouldMatchedTemplate = Object.fromEntries(
45
+ TweakCompatibilityRules.map(({ key, templateValue }) => [key, templateValue])
46
+ );
23
47
  const IncompatibleChanges = [
24
- "encrypt",
25
- "usePathObfuscation",
26
- "useDynamicIterationCount",
27
- "handleFilenameCaseSensitive"
48
+ ...TweakCompatibilityRules.filter(({ reconstruction }) => reconstruction === "required").map(({ key }) => key)
28
49
  ];
29
- const CompatibleButLossyChanges = ["hashAlg", "customChunkSize", "chunkSplitterVersion"];
30
- const IncompatibleChangesInSpecificPattern = [];
50
+ const CompatibleButLossyChanges = TweakCompatibilityRules.filter(
51
+ (rule) => "compatibleLossyOrder" in rule
52
+ ).slice().sort((left, right) => left.compatibleLossyOrder - right.compatibleLossyOrder).map(({ key }) => key);
53
+ const IncompatibleChangesInSpecificPattern = TweakCompatibilityRules.flatMap(
54
+ (rule) => (rule.specificPatterns ?? []).map((pattern) => ({
55
+ key: rule.key,
56
+ ...Object.prototype.hasOwnProperty.call(pattern, "from") ? { from: pattern.from } : {},
57
+ ...Object.prototype.hasOwnProperty.call(pattern, "to") ? { to: pattern.to } : {},
58
+ ...pattern.reconstruction === "recommended" ? { isRecommendation: true } : {}
59
+ }))
60
+ );
31
61
  const TweakValuesRecommendedTemplate = {
32
62
  useIgnoreFiles: false,
33
63
  useCustomRequestHandler: false,
@@ -49,9 +79,11 @@ const TweakValuesRecommendedTemplate = {
49
79
  chunkSplitterVersion: ChunkAlgorithms.RabinKarp
50
80
  };
51
81
  const TweakValuesDefault = {
52
- usePluginSyncV2: false,
53
- E2EEAlgorithm: DEFAULT_SETTINGS.E2EEAlgorithm,
54
- chunkSplitterVersion: DEFAULT_SETTINGS.chunkSplitterVersion,
82
+ ...Object.fromEntries(
83
+ TweakCompatibilityRules.filter((rule) => "knownDefault" in rule && rule.key !== "handleFilenameCaseSensitive").map(
84
+ ({ key, knownDefault }) => [key, knownDefault]
85
+ )
86
+ ),
55
87
  tweakModified: DEFAULT_SETTINGS.tweakModified
56
88
  };
57
89
  const TweakValuesTemplate = {
@@ -77,6 +109,7 @@ export {
77
109
  IncompatibleChangesInSpecificPattern,
78
110
  RemotePreferredTweakNotConfiguredReasons,
79
111
  RemotePreferredTweakStatuses,
112
+ TweakCompatibilityRules,
80
113
  TweakValuesDefault,
81
114
  TweakValuesRecommendedTemplate,
82
115
  TweakValuesShouldMatchedTemplate,
@@ -185,6 +185,8 @@ export declare const AllSettingDefault: {
185
185
  P2P_AutoAcceptingPeers: string;
186
186
  P2P_AutoDenyingPeers: string;
187
187
  P2P_IsHeadless?: boolean;
188
+ P2P_iceServers?: readonly RTCIceServer[];
189
+ P2P_iceServersExpiresAt?: number;
188
190
  P2P_Enabled: boolean;
189
191
  P2P_relays: string;
190
192
  P2P_roomID: string;
@@ -196,6 +198,9 @@ export declare const AllSettingDefault: {
196
198
  P2P_turnServers: string;
197
199
  P2P_turnUsername: string;
198
200
  P2P_turnCredential: string;
201
+ P2P_managedType?: string;
202
+ P2P_managedId?: string;
203
+ P2P_managedToken?: string;
199
204
  P2P_maxWirePayloadBytes?: number;
200
205
  P2P_connectionPath?: import("./types.js").P2PConnectionPath;
201
206
  P2P_useDiagRTC?: boolean;
@@ -9,7 +9,7 @@ import { AUTO_MERGED, CANCELLED, LEAVE_TO_SUBSEQUENT, MISSING_OR_ERROR, NOT_CONF
9
9
  import { IDPrefixes, LEAF_WAIT_ONLY_REMOTE, LEAF_WAIT_TIMEOUT, LEAF_WAIT_TIMEOUT_SEQUENTIAL_REPLICATOR, MAX_DOC_SIZE, MAX_DOC_SIZE_BIN, PREFIX_CHUNK, PREFIX_ENCRYPTED_CHUNK, PREFIX_OBFUSCATED, RECENT_MODIFIED_DOCS_QTY, REPLICATION_BUSY_TIMEOUT, SALT_OF_ID, SALT_OF_PASSPHRASE, SEED_MURMURHASH, VER } from "./models/shared.const.behabiour.js";
10
10
  import { AutoAccepting, type BucketSyncSetting, type ChunkSplitterVersion, type ConfigPassphraseStore, type CouchDBConnection, type E2EEAlgorithm, type EncryptionSettings, type HashAlgorithm, type HasSettings, type LocalDBSettings, type ObsidianLiveSyncSettings, type P2PConnectionInfo, type P2PSyncSetting, type PluginSyncSettingEntry, type RemoteDBSettings, type RemoteType, type RemoteTypeSettings, type SYNC_MODE } from "./models/setting.type.js";
11
11
  import { ChunkAlgorithmNames, ChunkAlgorithms, CURRENT_SETTING_VERSION, E2EEAlgorithmNames, E2EEAlgorithms, HashAlgorithms, REMOTE_COUCHDB, REMOTE_MINIO, REMOTE_P2P, RemoteTypes, SETTING_VERSION_INITIAL, SETTING_VERSION_SUPPORT_CASE_INSENSITIVE, MODE_AUTOMATIC, MODE_PAUSED, MODE_SELECTIVE, MODE_SHINY, P2PConnectionPaths, P2PMessageSizePresets, type P2PConnectionPath } from "./models/setting.const.js";
12
- import { hasValidP2PTurnServerUrl, isValidP2PTurnServerUrl, normaliseP2PConnectionPath, normaliseP2PMaxWirePayloadBytes, splitP2PTurnServerUrls } from "./models/setting.p2p.js";
12
+ import { hasManagedP2PTurnConfiguration, hasP2PTurnConfiguration, hasValidP2PTurnServerUrl, omitP2PRuntimeSettings, isValidP2PTurnServerUrl, normaliseP2PConnectionPath, normaliseP2PMaxWirePayloadBytes, splitP2PTurnServerUrls } from "./models/setting.p2p.js";
13
13
  import { PREFERRED_BASE, PREFERRED_JOURNAL_SYNC, PREFERRED_SETTING_CLOUDANT, PREFERRED_SETTING_SELF_HOSTED } from "./models/setting.const.preferred.js";
14
14
  import { P2P_DEFAULT_SETTINGS, DEFAULT_SETTINGS, NEW_VAULT_SETTINGS, SETTINGS_SCHEMA_DEFAULTS, createNewVaultSettings } from "./models/setting.const.defaults.js";
15
15
  import { prepareSettingsForLoad, SettingsMigrationReviewCodes, type PreparedSettings, type SettingsMigrationReviewCode, type SettingsMigrationReviewReason, type SettingsMigrationState } from "./models/setting.lifecycle.js";
@@ -23,6 +23,8 @@ import { configurationNames, LEVEL_ADVANCED, LEVEL_POWER_USER, LEVEL_EDGE_CASE,
23
23
  import type { CustomRegExpSource, CustomRegExpSourceList, ParsedCustomRegExp, Prettify } from "./models/shared.type.util.js";
24
24
  import { ProtocolVersions, type ProtocolVersion, DOCID_SYNC_PARAMETERS, DOCID_JOURNAL_SYNC_PARAMETERS, type SyncParameters, DEFAULT_SYNC_PARAMETERS } from "./models/sync.definition.js";
25
25
  import { TweakValuesShouldMatchedTemplate, IncompatibleChanges, CompatibleButLossyChanges, IncompatibleChangesInSpecificPattern, TweakValuesRecommendedTemplate, TweakValuesDefault, TweakValuesTemplate, type TweakValues, DEVICE_ID_PREFERRED, RemotePreferredTweakStatuses, type RemotePreferredTweakStatus, RemotePreferredTweakNotConfiguredReasons, type RemotePreferredTweakNotConfiguredReason, type RemotePreferredTweakResult } from "./models/tweak.definition.js";
26
+ import type { TweakAssessment, TweakAssessmentEntry, TweakAssessmentRelation, TweakAssessmentValue, TweakTransition, TweakTransitionReason } from "./models/tweak.compatibility.js";
27
+ import type { TweakReconstruction } from "./models/tweak.definition.js";
26
28
  import type { diff_result_leaf, dmp_result, diff_result, DIFF_CHECK_RESULT_AUTO, diff_check_result } from "./models/diff.definition.js";
27
29
  import { PREFIXMD_LOGFILE, PREFIXMD_LOGFILE_UC, FlagFilesOriginal, FlagFilesHumanReadable, FLAGMD_REDFLAG, FLAGMD_REDFLAG2, FLAGMD_REDFLAG2_HR, FLAGMD_REDFLAG3, FLAGMD_REDFLAG3_HR } from "./models/redflag.const.js";
28
30
  import { DatabaseConnectingStatuses, type DatabaseConnectingStatus } from "./models/shared.definition.js";
@@ -37,7 +39,7 @@ export { SETTING_VERSION_INITIAL, SETTING_VERSION_SUPPORT_CASE_INSENSITIVE, CURR
37
39
  export type { BucketSyncSetting, LocalDBSettings };
38
40
  export { RemoteTypes, REMOTE_COUCHDB, REMOTE_MINIO, REMOTE_P2P, P2PConnectionPaths, P2PMessageSizePresets, type RemoteType, AutoAccepting, };
39
41
  export type { P2PConnectionInfo, P2PConnectionPath, P2PSyncSetting };
40
- export { hasValidP2PTurnServerUrl, isValidP2PTurnServerUrl, normaliseP2PConnectionPath, normaliseP2PMaxWirePayloadBytes, splitP2PTurnServerUrls, };
42
+ export { hasManagedP2PTurnConfiguration, hasP2PTurnConfiguration, hasValidP2PTurnServerUrl, omitP2PRuntimeSettings, isValidP2PTurnServerUrl, normaliseP2PConnectionPath, normaliseP2PMaxWirePayloadBytes, splitP2PTurnServerUrls, };
41
43
  export { P2P_DEFAULT_SETTINGS };
42
44
  export type { RemoteTypeSettings };
43
45
  export { E2EEAlgorithmNames, E2EEAlgorithms, type E2EEAlgorithm };
@@ -69,6 +71,7 @@ export { confName };
69
71
  export { confDesc };
70
72
  export { TweakValuesTemplate };
71
73
  export type { TweakValues };
74
+ export type { TweakAssessment, TweakAssessmentEntry, TweakAssessmentRelation, TweakAssessmentValue, TweakReconstruction, TweakTransition, TweakTransitionReason, };
72
75
  export { DEVICE_ID_PREFERRED };
73
76
  export { RemotePreferredTweakStatuses };
74
77
  export type { RemotePreferredTweakStatus };
@@ -113,4 +116,4 @@ export { DOCID_SYNC_PARAMETERS };
113
116
  export { DOCID_JOURNAL_SYNC_PARAMETERS };
114
117
  export type { SyncParameters };
115
118
  export { DEFAULT_SYNC_PARAMETERS };
116
- export { SETTING_KEY_P2P_DEVICE_NAME, configURIBase, configURIBaseQR, SuffixDatabaseName, ExtraSuffixIndexedDB };
119
+ export { SETTING_KEY_P2P_DEVICE_NAME, configURIBase, configURIBaseQR, SuffixDatabaseName, ExtraSuffixIndexedDB, };
@@ -64,7 +64,10 @@ import {
64
64
  P2PMessageSizePresets
65
65
  } from "./models/setting.const.js";
66
66
  import {
67
+ hasManagedP2PTurnConfiguration,
68
+ hasP2PTurnConfiguration,
67
69
  hasValidP2PTurnServerUrl,
70
+ omitP2PRuntimeSettings,
68
71
  isValidP2PTurnServerUrl,
69
72
  normaliseP2PConnectionPath,
70
73
  normaliseP2PMaxWirePayloadBytes,
@@ -236,11 +239,14 @@ export {
236
239
  configURIBaseQR,
237
240
  configurationNames,
238
241
  createNewVaultSettings,
242
+ hasManagedP2PTurnConfiguration,
243
+ hasP2PTurnConfiguration,
239
244
  hasValidP2PTurnServerUrl,
240
245
  isMetaEntry,
241
246
  isValidP2PTurnServerUrl,
242
247
  normaliseP2PConnectionPath,
243
248
  normaliseP2PMaxWirePayloadBytes,
249
+ omitP2PRuntimeSettings,
244
250
  prepareSettingsForLoad,
245
251
  splitP2PTurnServerUrls,
246
252
  statusDisplay
@@ -462,7 +462,10 @@ function pickP2PSyncSettings(setting) {
462
462
  P2P_turnUsername: setting.P2P_turnUsername,
463
463
  P2P_turnCredential: setting.P2P_turnCredential,
464
464
  P2P_maxWirePayloadBytes: normaliseP2PMaxWirePayloadBytes(setting.P2P_maxWirePayloadBytes),
465
- P2P_connectionPath: normaliseP2PConnectionPath(setting.P2P_connectionPath)
465
+ P2P_connectionPath: normaliseP2PConnectionPath(setting.P2P_connectionPath),
466
+ P2P_managedType: setting.P2P_managedType,
467
+ P2P_managedId: setting.P2P_managedId,
468
+ P2P_managedToken: setting.P2P_managedToken
466
469
  };
467
470
  }
468
471
  function wrapByDefault(func, onError) {
@@ -5,6 +5,7 @@ import { LiveSyncTrysteroReplicator, type LiveSyncTrysteroReplicatorEnv } from "
5
5
  import type { P2PReplicationResult } from "../replication/trystero/TrysteroReplicator.js";
6
6
  import type { AcceptanceDecision, RevokeAcceptanceDecision } from "../replication/trystero/TrysteroReplicatorP2PServer.js";
7
7
  import type { Advertisement } from "../replication/trystero/types.js";
8
+ import { type PrepareP2PSettings } from "../replication/trystero/P2PRoomSessionOwner.js";
8
9
  import { type ReplicationOutcome } from "../replication/ReplicatorProvider.js";
9
10
  import type { P2PConnectionProbeAdmission } from "../replication/trystero/P2PConnectionProbeAdmission.js";
10
11
  export { ACTIVE_P2P_RELAY_BINDING_CONFLICT } from "../replication/trystero/P2PConnectionProbeAdmission.js";
@@ -114,10 +115,15 @@ export interface P2PServiceComposition {
114
115
  /** Create a non-owning adapter for the active Replicator selection. */
115
116
  createActiveReplicator(): ReplicatorInstance;
116
117
  }
118
+ /** Optional host dependencies used by the private P2P service composition. */
119
+ export interface P2PServiceOptions {
120
+ readonly prepareP2PSettings?: PrepareP2PSettings;
121
+ }
122
+ export type { PrepareP2PSettings };
117
123
  /**
118
124
  * Compose stable capability views over one private P2P service context.
119
125
  *
120
126
  * `P2PRoomSessionOwner` remains the resource owner. The returned composition
121
127
  * object is host wiring, not a capability façade for ordinary consumers.
122
128
  */
123
- export declare function createP2PService(env: LiveSyncTrysteroReplicatorEnv): P2PServiceComposition;
129
+ export declare function createP2PService(env: LiveSyncTrysteroReplicatorEnv, options?: P2PServiceOptions): P2PServiceComposition;
@@ -2,7 +2,9 @@ import { getPeerConnectionStats } from "../rpc/transports/DiagRTCPeerConnections
2
2
  import {
3
3
  LiveSyncTrysteroReplicator
4
4
  } from "../replication/trystero/LiveSyncTrysteroReplicator.js";
5
- import { P2PRoomSessionOwner } from "../replication/trystero/P2PRoomSessionOwner.js";
5
+ import {
6
+ P2PRoomSessionOwner
7
+ } from "../replication/trystero/P2PRoomSessionOwner.js";
6
8
  import { compatGlobal } from "../common/coreEnvFunctions.js";
7
9
  import {
8
10
  REPLICATION_CANCELLED,
@@ -75,12 +77,16 @@ function closeForLifecycle(owner, state) {
75
77
  cancelDelayedAutomation(owner, state);
76
78
  return owner.close();
77
79
  }
78
- function reconcileAutoStart(context, settings) {
80
+ async function reconcileAutoStart(context, settings) {
79
81
  if (!settings.P2P_Enabled || !settings.P2P_AutoStart) {
80
- return context.roomSessionOwner.setPersistentDemand("automatic", false);
82
+ await context.roomSessionOwner.setPersistentDemand("automatic", false);
83
+ return;
84
+ }
85
+ if (context.state.explicitDisconnectVeto || context.state.lifecycleClosed) return;
86
+ try {
87
+ await context.roomSessionOwner.setPersistentDemand("automatic", true);
88
+ } catch {
81
89
  }
82
- if (context.state.explicitDisconnectVeto || context.state.lifecycleClosed) return Promise.resolve();
83
- return context.roomSessionOwner.setPersistentDemand("automatic", true);
84
90
  }
85
91
  function scheduleAutoStart(context, delayMs = 100) {
86
92
  clearDelayedAutoStart(context.state);
@@ -224,8 +230,8 @@ function createServiceLifecycle(context) {
224
230
  scheduleAutoStart: (delayMs) => scheduleAutoStart(context, delayMs)
225
231
  };
226
232
  }
227
- function createP2PService(env) {
228
- const roomSessionOwner = new P2PRoomSessionOwner(env);
233
+ function createP2PService(env, options = {}) {
234
+ const roomSessionOwner = new P2PRoomSessionOwner(env, void 0, options);
229
235
  const state = {
230
236
  explicitDisconnectVeto: false,
231
237
  lifecycleClosed: false,
@@ -1,4 +1,4 @@
1
- export type { P2PCandidateSummary, P2PChangeRelay, P2PConfigurationExchange, P2PDiagnostics, P2PPeerConnectionMetrics, P2PPeerAdmission, P2PPeerDirectory, P2PServiceViews, P2PTargetedTransfer, P2PTransportLifecycle, P2PConnectionProbeAdmission, P2PConnectionProbeAdmissionResult, P2PConnectionProbeSettings, } from "./P2PService.js";
1
+ export type { P2PCandidateSummary, P2PChangeRelay, P2PConfigurationExchange, P2PDiagnostics, P2PPeerConnectionMetrics, P2PPeerAdmission, P2PPeerDirectory, P2PServiceViews, P2PTargetedTransfer, P2PTransportLifecycle, P2PConnectionProbeAdmission, P2PConnectionProbeAdmissionResult, P2PConnectionProbeSettings, P2PServiceOptions, PrepareP2PSettings, } from "./P2PService.js";
2
2
  export { ACTIVE_P2P_RELAY_BINDING_CONFLICT } from "./P2PService.js";
3
3
  export { useP2PReplicatorCommands } from "../replication/trystero/useP2PReplicatorCommands.js";
4
4
  export { useP2PReplicatorFeature } from "../replication/trystero/useP2PReplicatorFeature.js";
@@ -6,3 +6,5 @@ export type { OpenRebuildUIFactory, OpenReplicationUIFactory, } from "../replica
6
6
  export type { UseP2PReplicatorResult } from "../replication/trystero/UseP2PReplicatorResult.js";
7
7
  export type { P2PReplicationResult } from "../replication/trystero/TrysteroReplicator.js";
8
8
  export type { Advertisement } from "../replication/trystero/types.js";
9
+ export { P2P_ICE_SERVER_EXPIRY_MARGIN_MS, P2P_SETTINGS_PREPARATION_TIMEOUT_MS, } from "../replication/trystero/P2PRoomSessionOwner.js";
10
+ export type { P2PReplicatorFeatureOptions } from "../replication/trystero/useP2PReplicatorFeature.js";
package/dist/p2p/index.js CHANGED
@@ -1,8 +1,14 @@
1
1
  import { ACTIVE_P2P_RELAY_BINDING_CONFLICT } from "./P2PService.js";
2
2
  import { useP2PReplicatorCommands } from "../replication/trystero/useP2PReplicatorCommands.js";
3
3
  import { useP2PReplicatorFeature } from "../replication/trystero/useP2PReplicatorFeature.js";
4
+ import {
5
+ P2P_ICE_SERVER_EXPIRY_MARGIN_MS,
6
+ P2P_SETTINGS_PREPARATION_TIMEOUT_MS
7
+ } from "../replication/trystero/P2PRoomSessionOwner.js";
4
8
  export {
5
9
  ACTIVE_P2P_RELAY_BINDING_CONFLICT,
10
+ P2P_ICE_SERVER_EXPIRY_MARGIN_MS,
11
+ P2P_SETTINGS_PREPARATION_TIMEOUT_MS,
6
12
  useP2PReplicatorCommands,
7
13
  useP2PReplicatorFeature
8
14
  };
@@ -1,4 +1,4 @@
1
- import { type EntryDoc, type EntryMilestoneInfo, type RemoteDBSettings, type ChunkVersionRange, type TweakValues, type DeviceInfo } from "../common/types.js";
1
+ import { type EntryDoc, type EntryMilestoneInfo, type RemoteDBSettings, type ChunkVersionRange, type TweakValues, type DeviceInfo, type TweakAssessment } from "../common/types.js";
2
2
  export type ENSURE_DB_RESULT = "OK" | "INCOMPATIBLE" | "LOCKED" | "NODE_LOCKED" | "NODE_CLEANED" | ["MISMATCHED", TweakValues];
3
3
  /**
4
4
  * Ensures that the remote database is compatible with the current device.
@@ -10,5 +10,5 @@ export type ENSURE_DB_RESULT = "OK" | "INCOMPATIBLE" | "LOCKED" | "NODE_LOCKED"
10
10
  * @param updateCallback - The callback function to update the remote milestone.
11
11
  * @returns A promise that resolves to the result of ensuring compatibility.
12
12
  */
13
- export declare function ensureRemoteIsCompatible(infoSrc: EntryMilestoneInfo | false, setting: RemoteDBSettings, deviceNodeID: string, currentVersionRange: ChunkVersionRange, nodeDeviceInfo: DeviceInfo, updateCallback: (info: EntryMilestoneInfo) => Promise<void>): Promise<ENSURE_DB_RESULT>;
14
- export declare function ensureDatabaseIsCompatible(db: PouchDB.Database<EntryDoc>, setting: RemoteDBSettings, deviceNodeID: string, currentVersionRange: ChunkVersionRange, nodeDeviceInfo: DeviceInfo): Promise<ENSURE_DB_RESULT>;
13
+ export declare function ensureRemoteIsCompatible(infoSrc: EntryMilestoneInfo | false, setting: RemoteDBSettings, deviceNodeID: string, currentVersionRange: ChunkVersionRange, nodeDeviceInfo: DeviceInfo, updateCallback: (info: EntryMilestoneInfo) => Promise<void>, recordTweakAssessment?: (assessment: TweakAssessment) => void): Promise<ENSURE_DB_RESULT>;
14
+ export declare function ensureDatabaseIsCompatible(db: PouchDB.Database<EntryDoc>, setting: RemoteDBSettings, deviceNodeID: string, currentVersionRange: ChunkVersionRange, nodeDeviceInfo: DeviceInfo, recordTweakAssessment?: (assessment: TweakAssessment) => void): Promise<ENSURE_DB_RESULT>;
@@ -1,12 +1,11 @@
1
1
  import {
2
2
  MILESTONE_DOCID as MILESTONE_DOC_ID,
3
- TweakValuesShouldMatchedTemplate,
4
3
  TweakValuesTemplate,
5
- DEVICE_ID_PREFERRED,
6
- TweakValuesDefault
4
+ DEVICE_ID_PREFERRED
7
5
  } from "../common/types.js";
8
6
  import { extractObject, isObjectDifferent, resolveWithIgnoreKnownError } from "../common/utils.js";
9
- async function ensureRemoteIsCompatible(infoSrc, setting, deviceNodeID, currentVersionRange, nodeDeviceInfo, updateCallback) {
7
+ import { assessTweakCompatibility } from "../common/models/tweak.compatibility.js";
8
+ async function ensureRemoteIsCompatible(infoSrc, setting, deviceNodeID, currentVersionRange, nodeDeviceInfo, updateCallback, recordTweakAssessment) {
10
9
  const now = Date.now();
11
10
  const baseMilestone = {
12
11
  _id: MILESTONE_DOC_ID,
@@ -83,15 +82,9 @@ async function ensureRemoteIsCompatible(infoSrc, setting, deviceNodeID, currentV
83
82
  if (!setting.disableCheckingConfigMismatch) {
84
83
  const preferred_tweak = remoteMilestone.tweak_values?.[DEVICE_ID_PREFERRED] ?? currentTweakValues;
85
84
  const current_tweak = currentTweakValues;
86
- const preferred_should_matched = extractObject(TweakValuesShouldMatchedTemplate, {
87
- ...TweakValuesDefault,
88
- ...preferred_tweak
89
- });
90
- const current_should_matched = extractObject(TweakValuesShouldMatchedTemplate, {
91
- ...TweakValuesDefault,
92
- ...current_tweak
93
- });
94
- if (isObjectDifferent(preferred_should_matched, current_should_matched, true)) {
85
+ const tweakAssessment = assessTweakCompatibility(current_tweak, preferred_tweak);
86
+ recordTweakAssessment?.(tweakAssessment);
87
+ if (tweakAssessment.alignment === "mismatched") {
95
88
  return ["MISMATCHED", preferred_tweak];
96
89
  }
97
90
  }
@@ -106,7 +99,7 @@ async function ensureRemoteIsCompatible(infoSrc, setting, deviceNodeID, currentV
106
99
  }
107
100
  return "OK";
108
101
  }
109
- async function ensureDatabaseIsCompatible(db, setting, deviceNodeID, currentVersionRange, nodeDeviceInfo) {
102
+ async function ensureDatabaseIsCompatible(db, setting, deviceNodeID, currentVersionRange, nodeDeviceInfo, recordTweakAssessment) {
110
103
  const remoteMilestone = await resolveWithIgnoreKnownError(
111
104
  db.get(MILESTONE_DOC_ID),
112
105
  false
@@ -119,7 +112,8 @@ async function ensureDatabaseIsCompatible(db, setting, deviceNodeID, currentVers
119
112
  nodeDeviceInfo,
120
113
  async (info) => {
121
114
  await db.put(info);
122
- }
115
+ },
116
+ recordTweakAssessment
123
117
  );
124
118
  return ret;
125
119
  }
@@ -1,4 +1,4 @@
1
- import type { TweakValues } from "../common/types.js";
1
+ import type { TweakAssessment, TweakValues } from "../common/types.js";
2
2
  /** Stable machine states for one central-remote compatibility assessment. */
3
3
  export declare const CENTRAL_COMPATIBILITY_STATUSES: Readonly<{
4
4
  readonly NOT_ASSESSED: "not-assessed";
@@ -23,6 +23,7 @@ export interface CentralCompatibilityRejected {
23
23
  readonly status: typeof CENTRAL_COMPATIBILITY_STATUSES.REJECTED;
24
24
  readonly reason: CentralCompatibilityRejectionReason;
25
25
  readonly preferredTweakValue?: Readonly<TweakValues>;
26
+ readonly tweakAssessment?: TweakAssessment;
26
27
  }
27
28
  /** Immutable result produced by one provider-local compatibility assessment. */
28
29
  export type CentralCompatibilityDecision = typeof CENTRAL_COMPATIBILITY_NOT_ASSESSED | typeof CENTRAL_COMPATIBILITY_ACCEPTED | CentralCompatibilityRejected;
@@ -32,7 +33,8 @@ export type CentralCompatibilityDecisionRecorder = (decision: CentralCompatibili
32
33
  export interface CentralCompatibilityRecoveryHint {
33
34
  readonly reason: CentralCompatibilityRejectionReason;
34
35
  readonly preferredTweakValue?: Readonly<TweakValues>;
36
+ readonly tweakAssessment?: TweakAssessment;
35
37
  }
36
- export declare function centralCompatibilityRejected(reason: CentralCompatibilityRejectionReason, preferredTweakValue?: TweakValues): CentralCompatibilityRejected;
38
+ export declare function centralCompatibilityRejected(reason: CentralCompatibilityRejectionReason, preferredTweakValue?: Readonly<TweakValues>, tweakAssessment?: TweakAssessment): CentralCompatibilityRejected;
37
39
  /** Project only a rejected decision into the generic replication failure path. */
38
40
  export declare function centralCompatibilityRecoveryHint(decision: CentralCompatibilityDecision): CentralCompatibilityRecoveryHint | undefined;
@@ -15,18 +15,20 @@ const CENTRAL_COMPATIBILITY_NOT_ASSESSED = Object.freeze({
15
15
  const CENTRAL_COMPATIBILITY_ACCEPTED = Object.freeze({
16
16
  status: CENTRAL_COMPATIBILITY_STATUSES.ACCEPTED
17
17
  });
18
- function centralCompatibilityRejected(reason, preferredTweakValue) {
18
+ function centralCompatibilityRejected(reason, preferredTweakValue, tweakAssessment) {
19
19
  return Object.freeze({
20
20
  status: CENTRAL_COMPATIBILITY_STATUSES.REJECTED,
21
21
  reason,
22
- ...preferredTweakValue === void 0 ? {} : { preferredTweakValue: Object.freeze({ ...preferredTweakValue }) }
22
+ ...preferredTweakValue === void 0 ? {} : { preferredTweakValue: Object.freeze({ ...preferredTweakValue }) },
23
+ ...tweakAssessment === void 0 ? {} : { tweakAssessment }
23
24
  });
24
25
  }
25
26
  function centralCompatibilityRecoveryHint(decision) {
26
27
  if (decision.status !== CENTRAL_COMPATIBILITY_STATUSES.REJECTED) return void 0;
27
28
  return Object.freeze({
28
29
  reason: decision.reason,
29
- ...decision.preferredTweakValue === void 0 ? {} : { preferredTweakValue: decision.preferredTweakValue }
30
+ ...decision.preferredTweakValue === void 0 ? {} : { preferredTweakValue: decision.preferredTweakValue },
31
+ ...decision.tweakAssessment === void 0 ? {} : { tweakAssessment: decision.tweakAssessment }
30
32
  });
31
33
  }
32
34
  export {
@@ -903,12 +903,16 @@ ${sendingDocs}/(${sentDocsCount} done)`,
903
903
  device_name: this.env.services.vault.getVaultName(),
904
904
  progress
905
905
  };
906
+ let tweakAssessment;
906
907
  const ensure = await ensureDatabaseIsCompatible(
907
908
  dbRet.db,
908
909
  setting,
909
910
  this.nodeid,
910
911
  currentVersionRange,
911
- info
912
+ info,
913
+ (assessment) => {
914
+ tweakAssessment = assessment;
915
+ }
912
916
  );
913
917
  if (ensure == "INCOMPATIBLE") {
914
918
  recordCompatibilityDecision?.(
@@ -951,7 +955,11 @@ ${sendingDocs}/(${sentDocsCount} done)`,
951
955
  } else if (ensure == "OK") {
952
956
  } else if (ensure[0] == "MISMATCHED") {
953
957
  recordCompatibilityDecision?.(
954
- centralCompatibilityRejected(CENTRAL_COMPATIBILITY_REJECTION_REASONS.TWEAK_MISMATCH, ensure[1])
958
+ centralCompatibilityRejected(
959
+ CENTRAL_COMPATIBILITY_REJECTION_REASONS.TWEAK_MISMATCH,
960
+ ensure[1],
961
+ tweakAssessment
962
+ )
955
963
  );
956
964
  Logger(this.translate("liveSyncReplicator.mismatchedTweakDetected"), LOG_LEVEL_NOTICE);
957
965
  this.tweakSettingsMismatched = true;
@@ -1,4 +1,4 @@
1
- import { type RemoteDBSettings, type ChunkVersionRange, type NodeData, type RemotePreferredTweakResult } from "../../common/types.js";
1
+ import { type RemoteDBSettings, type ChunkVersionRange, type NodeData, type RemotePreferredTweakResult, type TweakAssessment } from "../../common/types.js";
2
2
  import { JournalSyncCore } from "./JournalSyncCore.js";
3
3
  import { LiveSyncAbstractReplicator, type RemoteDBStatus } from "../LiveSyncAbstractReplicator.js";
4
4
  import { type ENSURE_DB_RESULT } from "../../pouchdb/LiveSyncDBFunctions.js";
@@ -22,7 +22,7 @@ export declare class LiveSyncJournalReplicator extends LiveSyncAbstractReplicato
22
22
  private journalTransferStopGeneration;
23
23
  getReplicationPBKDF2Salt(setting: RemoteDBSettings, refresh?: boolean): Promise<Uint8Array<ArrayBuffer>>;
24
24
  setupJournalSyncClient(settings?: RemoteDBSettings): JournalSyncCore;
25
- ensureBucketIsCompatible(deviceNodeID: string, currentVersionRange: ChunkVersionRange, setting?: RemoteDBSettings, client?: Pick<JournalSyncCore, "downloadJsonWithResult" | "getCheckpointInfo" | "uploadJson">): Promise<ENSURE_DB_RESULT>;
25
+ ensureBucketIsCompatible(deviceNodeID: string, currentVersionRange: ChunkVersionRange, setting?: RemoteDBSettings, client?: Pick<JournalSyncCore, "downloadJsonWithResult" | "getCheckpointInfo" | "uploadJson">, recordTweakAssessment?: (assessment: TweakAssessment) => void): Promise<ENSURE_DB_RESULT>;
26
26
  constructor(env: LiveSyncJournalReplicatorEnv);
27
27
  migrate(from: number, to: number): Promise<boolean>;
28
28
  /**
@@ -69,7 +69,7 @@ class LiveSyncJournalReplicator extends LiveSyncAbstractReplicator {
69
69
  }
70
70
  return this._client;
71
71
  }
72
- async ensureBucketIsCompatible(deviceNodeID, currentVersionRange2, setting = this.currentSettings, client = this.setupJournalSyncClient(setting)) {
72
+ async ensureBucketIsCompatible(deviceNodeID, currentVersionRange2, setting = this.currentSettings, client = this.setupJournalSyncClient(setting), recordTweakAssessment) {
73
73
  const milestoneResult = await client.downloadJsonWithResult(MILSTONE_DOCID);
74
74
  if (milestoneResult.status === JournalStorageReadStatuses.UNAVAILABLE) {
75
75
  throw milestoneResult.error;
@@ -93,7 +93,8 @@ class LiveSyncJournalReplicator extends LiveSyncAbstractReplicator {
93
93
  if (!await client.uploadJson(MILSTONE_DOCID, info)) {
94
94
  throw new Error("Could not upload remote milestone");
95
95
  }
96
- }
96
+ },
97
+ recordTweakAssessment
97
98
  );
98
99
  }
99
100
  constructor(env) {
@@ -259,7 +260,16 @@ class LiveSyncJournalReplicator extends LiveSyncAbstractReplicator {
259
260
  this.remoteLockedAndDeviceNotAccepted = false;
260
261
  this.tweakSettingsMismatched = false;
261
262
  this.preferredTweakValue = void 0;
262
- const ensure = await this.ensureBucketIsCompatible(this.nodeid, currentVersionRange, setting, client);
263
+ let tweakAssessment;
264
+ const ensure = await this.ensureBucketIsCompatible(
265
+ this.nodeid,
266
+ currentVersionRange,
267
+ setting,
268
+ client,
269
+ (assessment) => {
270
+ tweakAssessment = assessment;
271
+ }
272
+ );
263
273
  if (ensure == "INCOMPATIBLE") {
264
274
  recordCompatibilityDecision?.(
265
275
  centralCompatibilityRejected(CENTRAL_COMPATIBILITY_REJECTION_REASONS.INCOMPATIBLE_VERSION)
@@ -301,7 +311,11 @@ class LiveSyncJournalReplicator extends LiveSyncAbstractReplicator {
301
311
  } else if (ensure == "OK") {
302
312
  } else if (ensure[0] == "MISMATCHED") {
303
313
  recordCompatibilityDecision?.(
304
- centralCompatibilityRejected(CENTRAL_COMPATIBILITY_REJECTION_REASONS.TWEAK_MISMATCH, ensure[1])
314
+ centralCompatibilityRejected(
315
+ CENTRAL_COMPATIBILITY_REJECTION_REASONS.TWEAK_MISMATCH,
316
+ ensure[1],
317
+ tweakAssessment
318
+ )
305
319
  );
306
320
  Logger(this.translate("liveSyncReplicator.mismatchedTweakDetected"), LOG_LEVEL_NOTICE);
307
321
  this.tweakSettingsMismatched = true;
@@ -1,8 +1,16 @@
1
+ import { type P2PSyncSetting } from "../../common/types.js";
1
2
  import type { LiveSyncReplicatorEnv } from "../LiveSyncAbstractReplicator.js";
2
3
  import { P2PRoomSession } from "./P2PRoomSession.js";
3
4
  import type { ReplicatorHostEnv } from "./types.js";
4
5
  import { type P2PConnectionProbeAdmissionResult, type P2PConnectionProbeSettings } from "./P2PConnectionProbeAdmission.js";
5
6
  type P2PRoomSessionFactory = (env: ReplicatorHostEnv) => P2PRoomSession;
7
+ /** Prepare connection-only P2P settings for one room generation. */
8
+ export type PrepareP2PSettings = (settings: Readonly<P2PSyncSetting>, signal: AbortSignal) => Promise<P2PSyncSetting>;
9
+ export interface P2PRoomSessionOwnerOptions {
10
+ readonly prepareP2PSettings?: PrepareP2PSettings;
11
+ }
12
+ export declare const P2P_SETTINGS_PREPARATION_TIMEOUT_MS = 30000;
13
+ export declare const P2P_ICE_SERVER_EXPIRY_MARGIN_MS = 30000;
6
14
  /** Session operations shared by the stable service and its compatibility facade. */
7
15
  export interface P2PRoomSessionAccess {
8
16
  readonly currentSession: P2PRoomSession | undefined;
@@ -22,13 +30,16 @@ export type P2PPersistentRoomDemand = "explicit" | "automatic" | "rebuild-contin
22
30
  export declare class P2PRoomSessionOwner implements P2PRoomSessionAccess {
23
31
  private readonly env;
24
32
  private readonly createSession;
33
+ private readonly options;
25
34
  private current?;
26
35
  private lifecycleOperation;
27
36
  private readonly persistentDemands;
28
37
  private readonly finiteDemands;
29
38
  private readonly automationCoordinator;
30
39
  private activeBinding?;
31
- constructor(env: LiveSyncReplicatorEnv, createSession?: P2PRoomSessionFactory);
40
+ private pendingPreparation?;
41
+ private runtimeGeneration;
42
+ constructor(env: LiveSyncReplicatorEnv, createSession?: P2PRoomSessionFactory, options?: P2PRoomSessionOwnerOptions);
32
43
  get currentSession(): P2PRoomSession | undefined;
33
44
  get isConnected(): boolean;
34
45
  cancelActiveTransfers(): void;
@@ -52,6 +63,16 @@ export declare class P2PRoomSessionOwner implements P2PRoomSessionAccess {
52
63
  private enqueueLifecycleOperation;
53
64
  private closeTransport;
54
65
  private bindingsMatch;
66
+ private connectionSettingsRemainUsable;
67
+ private fencePreparationForCurrentSettings;
68
+ private invalidatePreparation;
69
+ private prepareConnectionSettings;
70
+ private prepareWithDeadline;
71
+ private copyPreparedIceServers;
72
+ private hasUsableIceServer;
73
+ private hasUsableTurnServer;
74
+ private withRoomOpenDeadline;
75
+ private assertReconciliationCurrent;
55
76
  /** Capture immutable session inputs while keeping policy live. */
56
77
  private getEffectiveBinding;
57
78
  /** Apply policy which can change without retiring the room session. */