@app-swiss-knife/react-native-sdk 0.2.1 → 0.2.4

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 (26) hide show
  1. package/android/src/main/java/com/swissknife/crashreporting/SKCrashReportingModule.kt +9 -3
  2. package/android/vendor/java/com/appswissknife/context/DeviceContext.kt +1 -1
  3. package/android/vendor/java/com/appswissknife/net/IngestClient.kt +1 -1
  4. package/android/vendor/java/com/appswissknife/purchases/BillingClientGateway.kt +106 -16
  5. package/ios/SwissKnifeCrashReporting.swift +19 -3
  6. package/ios/vendor/SwissKnifeiOS/Context/DeviceContext.swift +1 -1
  7. package/ios/vendor/SwissKnifeiOS/CrashReporting/SKCrashReporting.swift +153 -6
  8. package/lib/commonjs/modules/crash-reporting.js +199 -15
  9. package/lib/commonjs/modules/crash-reporting.js.map +1 -1
  10. package/lib/commonjs/purchases.js +60 -6
  11. package/lib/commonjs/purchases.js.map +1 -1
  12. package/lib/module/modules/crash-reporting.js +199 -15
  13. package/lib/module/modules/crash-reporting.js.map +1 -1
  14. package/lib/module/purchases.js +60 -7
  15. package/lib/module/purchases.js.map +1 -1
  16. package/lib/typescript/commonjs/modules/crash-reporting.d.ts +89 -0
  17. package/lib/typescript/commonjs/modules/crash-reporting.d.ts.map +1 -1
  18. package/lib/typescript/commonjs/purchases.d.ts +32 -1
  19. package/lib/typescript/commonjs/purchases.d.ts.map +1 -1
  20. package/lib/typescript/module/modules/crash-reporting.d.ts +89 -0
  21. package/lib/typescript/module/modules/crash-reporting.d.ts.map +1 -1
  22. package/lib/typescript/module/purchases.d.ts +32 -1
  23. package/lib/typescript/module/purchases.d.ts.map +1 -1
  24. package/package.json +1 -1
  25. package/src/modules/crash-reporting.ts +297 -25
  26. package/src/purchases.ts +65 -7
@@ -71,7 +71,18 @@ interface SKCrashReportingNative {
71
71
  captureScreenshot?(): Promise<string | null>;
72
72
  }
73
73
 
74
+ /** Test seam (same shape as `_screenshotCaptureOverride`): `undefined` =
75
+ * resolve from NativeModules, `null` = pretend the native module is absent.
76
+ * Needed because `require("react-native")` under vitest reaches the real
77
+ * Flow-syntax entry point and throws, so the native branch is otherwise
78
+ * unreachable — and "we did not start the native handler" would pass
79
+ * vacuously. */
80
+ let _nativeCrashModuleOverride: SKCrashReportingNative | null | undefined;
81
+
74
82
  function getNativeCrashModule(): SKCrashReportingNative | null {
83
+ if (_nativeCrashModuleOverride !== undefined) {
84
+ return _nativeCrashModuleOverride;
85
+ }
75
86
  try {
76
87
  // Dynamic require to avoid vitest/bundler trying to parse react-native Flow code
77
88
  // eslint-disable-next-line @typescript-eslint/no-require-imports
@@ -98,6 +109,54 @@ export interface CrashReportingConfig {
98
109
  dist?: string;
99
110
  maxBreadcrumbs?: number;
100
111
  enableAutoBreadcrumbs?: boolean;
112
+ /**
113
+ * Take over `ErrorUtils`' global JS error handler. Default **true**.
114
+ *
115
+ * We chain — the handler that was installed before us is still invoked —
116
+ * so leaving this on is safe alongside another reporter. Set false if the
117
+ * host wants Swiss Knife's manual APIs (`captureException`, breadcrumbs,
118
+ * sessions) without us touching the global slot at all.
119
+ */
120
+ enableGlobalErrorHandler?: boolean;
121
+ /**
122
+ * Track unhandled promise rejections. Default **true**.
123
+ *
124
+ * ⚠️ Unlike every other handler in this SDK, this one CANNOT be chained
125
+ * reliably. Both engines expose a single-slot switch with no getter:
126
+ * Hermes' `HermesInternal.enablePromiseRejectionTracker(options)` and JSC's
127
+ * `promise/setimmediate/rejection-tracking`.`enable(options)` each replace
128
+ * whatever was registered, and neither offers a way to read the incumbent
129
+ * back out. Sentry React Native calls exactly the same APIs.
130
+ *
131
+ * What we do about it:
132
+ * - We install a composing wrapper over the engine's `enable` entry point,
133
+ * so a reporter that initialises AFTER us is merged with us instead of
134
+ * replacing us. Both handlers then run.
135
+ * - The reverse order is unfixable. If another reporter installed BEFORE
136
+ * Swiss Knife and did not itself chain, its handler is unreachable and
137
+ * ours replaces it. Either initialise Swiss Knife first, or set this to
138
+ * false — the rest of the SDK (manual captures, breadcrumbs, sessions,
139
+ * the global error handler, native crashes) is unaffected either way.
140
+ */
141
+ enablePromiseRejectionTracking?: boolean;
142
+ /**
143
+ * Subscribe to `AppState` to open/close crash-reporting sessions on
144
+ * foreground/background. Default **true**. Purely additive (RN's AppState
145
+ * is a multi-listener emitter — no slot to fight over); the opt-out exists
146
+ * for hosts that drive session boundaries themselves.
147
+ */
148
+ enableAppStateTracking?: boolean;
149
+ /**
150
+ * Start the NATIVE crash handler (iOS Mach/signal + NSException, Android
151
+ * NDK + system ANR) via the native module. Default **true**.
152
+ *
153
+ * Our native handlers chain (they capture and re-invoke the previous
154
+ * `NSSetUncaughtExceptionHandler` / `signal()` / Java
155
+ * `UncaughtExceptionHandler`), so coexisting with Sentry or Crashlytics is
156
+ * supported. Set false if the host's incumbent owns native crash reporting
157
+ * outright and you only want Swiss Knife's JS-level features.
158
+ */
159
+ enableNativeCrashHandler?: boolean;
101
160
  /** Called before sending each event. Return null to drop the event. */
102
161
  beforeSend?: (event: SKCrashEvent) => SKCrashEvent | null;
103
162
  /**
@@ -603,8 +662,20 @@ function handleAppStateChange(nextState: string): void {
603
662
  }
604
663
  }
605
664
 
665
+ /** Test seam — see `_nativeCrashModuleOverride` for why. `undefined` =
666
+ * resolve from react-native. */
667
+ let _appStateOverride:
668
+ | { addEventListener: (e: string, h: (s: string) => void) => { remove: () => void } }
669
+ | null
670
+ | undefined;
671
+
606
672
  function installAppStateListener(): void {
607
673
  if (_appStateSubscription) return; // double-init guard
674
+ if (_appStateOverride !== undefined) {
675
+ _appStateSubscription =
676
+ _appStateOverride?.addEventListener("change", handleAppStateChange) ?? null;
677
+ return;
678
+ }
608
679
  // AppState is a React Native API. Guard so tests/Node imports don't blow up.
609
680
  try {
610
681
  // eslint-disable-next-line @typescript-eslint/no-require-imports
@@ -1021,10 +1092,133 @@ function onUnhandledRejection(_id: number, rejection: unknown): void {
1021
1092
  }
1022
1093
  }
1023
1094
 
1095
+ interface RejectionTrackingOptions {
1096
+ allRejections: boolean;
1097
+ onUnhandled: (id: number, rejection: unknown) => void;
1098
+ onHandled?: (id: number) => void;
1099
+ }
1100
+
1101
+ type RejectionEnableFn = (opts: RejectionTrackingOptions) => void;
1102
+
1103
+ /**
1104
+ * Run a global-slot installer so that a failure costs that one feature and
1105
+ * nothing else. Crash reporting is strictly an add-on to the host app; there
1106
+ * is no failure here worth taking the app down for.
1107
+ */
1108
+ function neverThrow(what: string, fn: () => void): void {
1109
+ try {
1110
+ fn();
1111
+ } catch (e) {
1112
+ console.warn(`[SwissKnife CrashReporting] ${what} unavailable:`, e);
1113
+ }
1114
+ }
1115
+
1116
+ /**
1117
+ * Replace a property on an object we do not own, without ever throwing.
1118
+ *
1119
+ * A bare `target.key = value` is not safe on host objects. `HermesInternal` is
1120
+ * **frozen** on every real Hermes build, so its properties are non-writable
1121
+ * and non-configurable; because this module is strict-mode (ES module), the
1122
+ * assignment throws `TypeError: Cannot assign to read-only property` rather
1123
+ * than failing silently. That throw propagated out of `CrashReporting.init`
1124
+ * and — since `initSwissKnife()` is normally called in module scope — aborted
1125
+ * evaluation of the host's root module, so the app never booted. Frozen host
1126
+ * globals must be *probed*, and a refusal must degrade, never escalate.
1127
+ *
1128
+ * Returns true only if the slot genuinely now holds `value`.
1129
+ */
1130
+ function trySetHostProperty(
1131
+ target: object,
1132
+ key: string,
1133
+ value: unknown
1134
+ ): boolean {
1135
+ try {
1136
+ if (Object.isFrozen(target)) return false;
1137
+ const desc = Object.getOwnPropertyDescriptor(target, key);
1138
+ // Non-configurable data property with writable:false — nothing can
1139
+ // replace it. Bail before we provoke a TypeError.
1140
+ if (desc && !desc.configurable && !desc.writable) return false;
1141
+ if (desc === undefined || desc.configurable) {
1142
+ // defineProperty also covers own accessor properties (a getter with no
1143
+ // setter would silently swallow a plain assignment), and never walks
1144
+ // the prototype chain the way `=` does.
1145
+ Object.defineProperty(target, key, {
1146
+ value,
1147
+ writable: desc?.writable ?? true,
1148
+ enumerable: desc?.enumerable ?? true,
1149
+ configurable: true,
1150
+ });
1151
+ } else {
1152
+ // Non-configurable but writable — assignment is the only route.
1153
+ (target as Record<string, unknown>)[key] = value;
1154
+ }
1155
+ // Confirm it actually took. Proxies and exotic host objects can accept a
1156
+ // write and keep the old value; treating that as success would leave us
1157
+ // believing we own a slot we do not.
1158
+ return (target as Record<string, unknown>)[key] === value;
1159
+ } catch {
1160
+ return false;
1161
+ }
1162
+ }
1163
+
1164
+ /**
1165
+ * Build a wrapper around a single-slot `enable(options)` entry point so a
1166
+ * LATER caller composes with us instead of evicting us.
1167
+ *
1168
+ * Promise-rejection tracking is the one global in this SDK that offers no way
1169
+ * to read the incumbent handler back out — see
1170
+ * `CrashReportingConfig.enablePromiseRejectionTracking`. Since we cannot
1171
+ * capture what came before, we defend the other direction: after we install,
1172
+ * anyone else calling `enable` (Sentry RN, RN core's LogBox re-arm, the host
1173
+ * itself) is routed through this wrapper, which re-registers a merged
1174
+ * handler. Ours runs first and is isolated behind try/catch so a throw on our
1175
+ * side cannot swallow theirs.
1176
+ *
1177
+ * `allRejections: false` is treated as a disable request and passed straight
1178
+ * through unwrapped — that is how both engines spell "stop tracking", and
1179
+ * silently forcing it back to true would make the API a lie (our own
1180
+ * `_disableRejectionTracking` uses it).
1181
+ *
1182
+ * Installing the returned wrapper is the caller's job and is strictly an
1183
+ * enhancement: tracking is already live from the direct `original(options)`
1184
+ * call, so a host that refuses the swap keeps full rejection capture and only
1185
+ * loses the compose-with-a-later-reporter nicety.
1186
+ */
1187
+ function makeComposingRejectionEnable(
1188
+ original: RejectionEnableFn,
1189
+ ours: RejectionTrackingOptions
1190
+ ): RejectionEnableFn {
1191
+ return (theirs: RejectionTrackingOptions) => {
1192
+ if (!theirs || theirs.allRejections === false) {
1193
+ original(theirs);
1194
+ return;
1195
+ }
1196
+ original({
1197
+ allRejections: true,
1198
+ onUnhandled: (id: number, rejection: unknown) => {
1199
+ try {
1200
+ ours.onUnhandled(id, rejection);
1201
+ } catch {
1202
+ // never let our reporting break the other tracker
1203
+ }
1204
+ theirs.onUnhandled?.(id, rejection);
1205
+ },
1206
+ onHandled: (id: number) => {
1207
+ try {
1208
+ ours.onHandled?.(id);
1209
+ } catch {
1210
+ /* ignore */
1211
+ }
1212
+ theirs.onHandled?.(id);
1213
+ },
1214
+ });
1215
+ };
1216
+ }
1217
+
1024
1218
  function installPromiseRejectionTracking(): void {
1025
1219
  if (_rejectionTrackingInstalled) return; // double-init guard
1026
1220
 
1027
- const options = {
1221
+ const options: RejectionTrackingOptions = {
1028
1222
  allRejections: true,
1029
1223
  onUnhandled: onUnhandledRejection,
1030
1224
  onHandled: () => {},
@@ -1034,22 +1228,34 @@ function installPromiseRejectionTracking(): void {
1034
1228
  const hermes = (
1035
1229
  globalThis as {
1036
1230
  HermesInternal?: {
1037
- enablePromiseRejectionTracker?: (opts: {
1038
- allRejections: boolean;
1039
- onUnhandled: (id: number, rejection: unknown) => void;
1040
- onHandled?: (id: number) => void;
1041
- }) => void;
1231
+ enablePromiseRejectionTracker?: RejectionEnableFn;
1042
1232
  };
1043
1233
  }
1044
1234
  ).HermesInternal;
1045
1235
  if (hermes?.enablePromiseRejectionTracker) {
1046
- hermes.enablePromiseRejectionTracker(options);
1236
+ // Keep the un-bound reference for restoration — teardown must put the
1237
+ // host's own function object back, not a bound copy of it.
1238
+ const engineEnable = hermes.enablePromiseRejectionTracker;
1239
+ const original = engineEnable.bind(hermes);
1240
+ // This one call IS the tracking. Everything below is enhancement.
1241
+ original(options);
1047
1242
  _rejectionTrackingInstalled = true;
1243
+
1244
+ // `HermesInternal` is frozen on real devices, so this swap usually fails —
1245
+ // that is expected and harmless. Never let it throw out of init().
1246
+ const composed = trySetHostProperty(
1247
+ hermes,
1248
+ "enablePromiseRejectionTracker",
1249
+ makeComposingRejectionEnable(original, options)
1250
+ );
1251
+
1048
1252
  _disableRejectionTracking = () => {
1049
- hermes.enablePromiseRejectionTracker?.({
1050
- allRejections: false,
1051
- onUnhandled: () => {},
1052
- });
1253
+ // Mirror image of the install: only restore what we managed to replace,
1254
+ // and go through the same non-throwing path.
1255
+ if (composed) {
1256
+ trySetHostProperty(hermes, "enablePromiseRejectionTracker", engineEnable);
1257
+ }
1258
+ original({ allRejections: false, onUnhandled: () => {} });
1053
1259
  };
1054
1260
  return;
1055
1261
  }
@@ -1059,12 +1265,30 @@ function installPromiseRejectionTracking(): void {
1059
1265
  try {
1060
1266
  // eslint-disable-next-line @typescript-eslint/no-require-imports
1061
1267
  const tracking = require("promise/setimmediate/rejection-tracking") as {
1062
- enable: (opts: typeof options) => void;
1268
+ enable: RejectionEnableFn;
1063
1269
  disable: () => void;
1064
1270
  };
1065
- tracking.enable(options);
1271
+ const moduleEnable = tracking.enable;
1272
+ const original = moduleEnable.bind(tracking);
1273
+ // As above: this call is the tracking; the swap below is enhancement.
1274
+ original(options);
1066
1275
  _rejectionTrackingInstalled = true;
1067
- _disableRejectionTracking = () => tracking.disable();
1276
+
1277
+ // Metro hands back a mutable CommonJS `module.exports` here, but any
1278
+ // bundler that gives this module ES-namespace semantics makes `enable`
1279
+ // read-only — same failure mode as HermesInternal, so same guard.
1280
+ const composed = trySetHostProperty(
1281
+ tracking,
1282
+ "enable",
1283
+ makeComposingRejectionEnable(original, options)
1284
+ );
1285
+
1286
+ _disableRejectionTracking = () => {
1287
+ if (composed) {
1288
+ trySetHostProperty(tracking, "enable", moduleEnable);
1289
+ }
1290
+ tracking.disable();
1291
+ };
1068
1292
  } catch {
1069
1293
  // promise polyfill unavailable (plain Node/tests) — no rejection capture
1070
1294
  }
@@ -1151,23 +1375,41 @@ function installConsoleBreadcrumbs(): void {
1151
1375
 
1152
1376
  export const CrashReporting = {
1153
1377
  init(config: CrashReportingConfig): void {
1378
+ // Defaults keep today's behaviour byte-for-byte: every handler is on
1379
+ // unless the host explicitly opts out. The opt-outs exist for apps whose
1380
+ // incumbent reporter owns a given global — see each field's doc comment
1381
+ // on CrashReportingConfig for which ones we chain and which we can't.
1154
1382
  _config = {
1155
1383
  maxBreadcrumbs: 100,
1156
1384
  environment: "production",
1157
1385
  enableAutoBreadcrumbs: true,
1386
+ enableGlobalErrorHandler: true,
1387
+ enablePromiseRejectionTracking: true,
1388
+ enableAppStateTracking: true,
1389
+ enableNativeCrashHandler: true,
1158
1390
  ...config,
1159
1391
  };
1160
1392
  _breadcrumbs = new RingBuffer(_config.maxBreadcrumbs!);
1161
- installGlobalHandler();
1162
- installPromiseRejectionTracking();
1393
+ // Every global-slot install is best-effort. `initSwissKnife()` is normally
1394
+ // called in module scope, so anything that throws here takes the host's
1395
+ // root module down with it and the app never boots (v0.2.3 did exactly
1396
+ // that against frozen `HermesInternal`). Degrade the feature, not the app.
1397
+ if (_config.enableGlobalErrorHandler) {
1398
+ neverThrow("global error handler", installGlobalHandler);
1399
+ }
1400
+ if (_config.enablePromiseRejectionTracking) {
1401
+ neverThrow("promise rejection tracking", installPromiseRejectionTracking);
1402
+ }
1163
1403
  restorePersistedState();
1164
1404
  startSession();
1165
- installAppStateListener();
1405
+ if (_config.enableAppStateTracking) installAppStateListener();
1166
1406
 
1167
1407
  // Initialize native crash handler if the native module is linked.
1168
1408
  // This catches Mach exceptions + signal crashes (iOS) and NDK native
1169
1409
  // crashes + system ANRs (Android) that pure JS cannot observe.
1170
- const nativeMod = getNativeCrashModule();
1410
+ const nativeMod = _config.enableNativeCrashHandler
1411
+ ? getNativeCrashModule()
1412
+ : null;
1171
1413
  if (nativeMod) {
1172
1414
  try {
1173
1415
  nativeMod.start({
@@ -1185,8 +1427,8 @@ export const CrashReporting = {
1185
1427
 
1186
1428
  // Install automatic breadcrumbs
1187
1429
  if (_config.enableAutoBreadcrumbs) {
1188
- installHTTPBreadcrumbs();
1189
- installConsoleBreadcrumbs();
1430
+ neverThrow("http breadcrumbs", installHTTPBreadcrumbs);
1431
+ neverThrow("console breadcrumbs", installConsoleBreadcrumbs);
1190
1432
  }
1191
1433
  },
1192
1434
 
@@ -1463,7 +1705,10 @@ export const CrashReporting = {
1463
1705
  _backoffMs = BACKOFF_INITIAL_MS;
1464
1706
  _backoffUntil = 0;
1465
1707
  if (_disableRejectionTracking) {
1466
- _disableRejectionTracking();
1708
+ // Teardown is the mirror image of install and can fail the same way —
1709
+ // restoring a slot on a frozen host object, or an engine `enable` that
1710
+ // throws. Drop the reference either way so a failure can't wedge reset.
1711
+ neverThrow("promise rejection teardown", _disableRejectionTracking);
1467
1712
  _disableRejectionTracking = null;
1468
1713
  }
1469
1714
  _rejectionTrackingInstalled = false;
@@ -1472,21 +1717,25 @@ export const CrashReporting = {
1472
1717
  _screenshotPromises = new Map();
1473
1718
  _offlineScreenshots = [];
1474
1719
  _screenshotCaptureOverride = undefined;
1720
+ _nativeCrashModuleOverride = undefined;
1721
+ _appStateOverride = undefined;
1475
1722
  if (_appStateSubscription) {
1476
1723
  _appStateSubscription.remove();
1477
1724
  _appStateSubscription = null;
1478
1725
  }
1479
- // Restore patched globals
1726
+ // Restore patched globals. These three slots are writable everywhere RN
1727
+ // runs (RN itself repatches them), but restoring is still a write to an
1728
+ // object we do not own, so it goes through the same non-throwing path.
1480
1729
  if (_originalFetch) {
1481
- globalThis.fetch = _originalFetch;
1730
+ trySetHostProperty(globalThis, "fetch", _originalFetch);
1482
1731
  _originalFetch = null;
1483
1732
  }
1484
1733
  if (_originalConsoleWarn) {
1485
- console.warn = _originalConsoleWarn;
1734
+ trySetHostProperty(console, "warn", _originalConsoleWarn);
1486
1735
  _originalConsoleWarn = null;
1487
1736
  }
1488
1737
  if (_originalConsoleError) {
1489
- console.error = _originalConsoleError;
1738
+ trySetHostProperty(console, "error", _originalConsoleError);
1490
1739
  _originalConsoleError = null;
1491
1740
  }
1492
1741
  },
@@ -1530,6 +1779,29 @@ export const CrashReporting = {
1530
1779
  _simulateAppState(nextState: string): void {
1531
1780
  handleAppStateChange(nextState);
1532
1781
  },
1782
+
1783
+ /** Test seam: stand in for `NativeModules.SKCrashReporting`.
1784
+ * `null` = native absent; `undefined` = resolve from react-native. */
1785
+ _setNativeCrashModuleForTests(
1786
+ mod: SKCrashReportingNative | null | undefined
1787
+ ): void {
1788
+ _nativeCrashModuleOverride = mod;
1789
+ },
1790
+
1791
+ /** Test seam: stand in for react-native's `AppState`. */
1792
+ _setAppStateForTests(
1793
+ appState:
1794
+ | {
1795
+ addEventListener: (
1796
+ e: string,
1797
+ h: (s: string) => void
1798
+ ) => { remove: () => void };
1799
+ }
1800
+ | null
1801
+ | undefined
1802
+ ): void {
1803
+ _appStateOverride = appState;
1804
+ },
1533
1805
  };
1534
1806
 
1535
1807
  // MARK: - React Error Boundary
package/src/purchases.ts CHANGED
@@ -56,12 +56,51 @@ const customerInfoSubscriptions = new Map<
56
56
  EmitterSubscription
57
57
  >();
58
58
 
59
+ /**
60
+ * Guard for surfaces that genuinely need the PURCHASE engine — the store APIs
61
+ * and the RC-parity identity aliases that route through the store gateway on
62
+ * Android. Checks the JS "configure was called" flag.
63
+ */
59
64
  function throwIfNotConfigured(): void {
60
65
  if (!configured) {
61
66
  throw new UninitializedPurchasesError();
62
67
  }
63
68
  }
64
69
 
70
+ /**
71
+ * Guard for surfaces that only need CORE — the subscriber-attribute setters.
72
+ *
73
+ * Attributes describe the *person*, not the purchase: natively they land in
74
+ * `AttributesClient` → `POST /api/sdk/users/attributes` → `app_users.properties`,
75
+ * which is what the dashboard person card reads. Neither platform's attributes
76
+ * path touches StoreKit or Play Billing — iOS gates on `SwissKnife.isCoreConfigured`
77
+ * (`SwissKnife.currentAnonymousIdForAttributes`), and Android's `configureCore`
78
+ * wires `AttributesClient` with an `Identity`-snapshot id fallback precisely so a
79
+ * store-less app still resolves ids. Gating these on the purchase flag left an app
80
+ * that uses `configureCore` (because another library owns the store) with **no way
81
+ * at all** to populate the person card.
82
+ *
83
+ * Two-step check, and the second step is load-bearing:
84
+ *
85
+ * 1. The JS flag, set by `configure` / `configureCore`. Free, no bridge hop.
86
+ * 2. Native truth. `Analytics.init(...)` wires core natively via
87
+ * `configureObservability` and touches no JS flag, so an analytics-only app
88
+ * has core configured while every JS flag reads `false` — exactly the case
89
+ * {@link isCoreConfigured} documents. Skipping this step would keep the most
90
+ * common core-only integration broken.
91
+ *
92
+ * Never consults the purchase flag. Strictly more permissive than
93
+ * {@link throwIfNotConfigured}, so no existing caller can break.
94
+ */
95
+ async function throwIfCoreNotConfigured(): Promise<void> {
96
+ if (coreConfigured) return;
97
+ if (await nativeBoolean((native) => native.isCoreConfigured())) return;
98
+ throw new UninitializedPurchasesError(
99
+ "Purchases core is not configured. Call Purchases.configure(), " +
100
+ "Purchases.configureCore(), or Analytics.init() first."
101
+ );
102
+ }
103
+
65
104
  /**
66
105
  * RC-compatible subscriptions SDK entry point. Process-wide singleton; call
67
106
  * `Purchases.configure(...)` once at app start, then use the static methods.
@@ -206,6 +245,18 @@ export class Purchases {
206
245
  return getNativeModule().restorePurchases();
207
246
  }
208
247
 
248
+ // The four RC-parity identity aliases below stay on the PURCHASE guard on
249
+ // purpose, even though identity is a core concern natively. The two platforms
250
+ // disagree about what this specific surface does: the iOS bridge's `logIn`
251
+ // reaches `SwissKnife.logIn` → `Identity.logIn`, which is core-gated and POSTs
252
+ // `/api/sdk/users/identify`; the Android bridge's `logIn` reaches
253
+ // `SwissKnife.logIn` → the purchases `gateway`, which only rebinds the local
254
+ // user id and refreshes entitlements. Loosening the guard here would let a
255
+ // core-only app call a method that means different things per platform and
256
+ // silently skips the identify POST on Android. `Identity.logIn` / `logOut` /
257
+ // `current` are the core-safe surface — they route to the unified native
258
+ // Identity on both platforms and carry no configure guard in JS at all.
259
+
209
260
  /**
210
261
  * Identify the user. Aliases/merges anonymous purchases server-side.
211
262
  *
@@ -241,33 +292,37 @@ export class Purchases {
241
292
  return getNativeModule().isAnonymous();
242
293
  }
243
294
 
295
+ // Subscriber attributes. CORE, not store — see {@link throwIfCoreNotConfigured}.
296
+ // These work in an app that only called `configureCore` (another library owns
297
+ // the store) or only `Analytics.init`.
298
+
244
299
  /** Set arbitrary subscriber attributes. null clears an attribute. */
245
300
  static async setAttributes(attributes: Record<string, string | null>): Promise<void> {
246
- throwIfNotConfigured();
301
+ await throwIfCoreNotConfigured();
247
302
  return getNativeModule().setAttributes(attributes);
248
303
  }
249
304
 
250
305
  /** Reserved attribute: email. */
251
306
  static async setEmail(email: string | null): Promise<void> {
252
- throwIfNotConfigured();
307
+ await throwIfCoreNotConfigured();
253
308
  return getNativeModule().setEmail(email);
254
309
  }
255
310
 
256
311
  /** Reserved attribute: display name. */
257
312
  static async setDisplayName(displayName: string | null): Promise<void> {
258
- throwIfNotConfigured();
313
+ await throwIfCoreNotConfigured();
259
314
  return getNativeModule().setDisplayName(displayName);
260
315
  }
261
316
 
262
317
  /** Reserved attribute: phone number. */
263
318
  static async setPhoneNumber(phoneNumber: string | null): Promise<void> {
264
- throwIfNotConfigured();
319
+ await throwIfCoreNotConfigured();
265
320
  return getNativeModule().setPhoneNumber(phoneNumber);
266
321
  }
267
322
 
268
323
  /** Reserved attribute: push token. */
269
324
  static async setPushToken(pushToken: string | null): Promise<void> {
270
- throwIfNotConfigured();
325
+ await throwIfCoreNotConfigured();
271
326
  return getNativeModule().setPushToken(pushToken);
272
327
  }
273
328
 
@@ -307,7 +362,10 @@ export class Purchases {
307
362
  }
308
363
  }
309
364
 
310
- // Internal helper shared with the rest of the class (defined across SP-2a tasks).
311
- export { throwIfNotConfigured as __throwIfNotConfigured };
365
+ // Internal helpers shared with the rest of the class (defined across SP-2a tasks).
366
+ export {
367
+ throwIfNotConfigured as __throwIfNotConfigured,
368
+ throwIfCoreNotConfigured as __throwIfCoreNotConfigured,
369
+ };
312
370
 
313
371
  export default Purchases;