radar-sdk-js 4.5.8 → 5.0.0-beta.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.
package/README.md CHANGED
@@ -56,7 +56,7 @@ Radar.initialize('prj_test_pk_...', { /* options */ });
56
56
 
57
57
  Add the following script in your `html` file
58
58
  ```html
59
- <script src="https://js.radar.com/v4.5.8/radar.min.js"></script>
59
+ <script src="https://js.radar.com/v5.0.0-beta.0/radar.min.js"></script>
60
60
  ```
61
61
 
62
62
  Then initialize the Radar SDK
@@ -73,8 +73,8 @@ To create a map, first initialize the Radar SDK with your publishable key. Then
73
73
  ```html
74
74
  <html>
75
75
  <head>
76
- <link href="https://js.radar.com/v4.5.8/radar.css" rel="stylesheet">
77
- <script src="https://js.radar.com/v4.5.8/radar.min.js"></script>
76
+ <link href="https://js.radar.com/v5.0.0-beta.0/radar.css" rel="stylesheet">
77
+ <script src="https://js.radar.com/v5.0.0-beta.0/radar.min.js"></script>
78
78
  </head>
79
79
 
80
80
  <body>
@@ -98,8 +98,8 @@ To create an autocomplete input, first initialize the Radar SDK with your publis
98
98
  ```html
99
99
  <html>
100
100
  <head>
101
- <link href="https://js.radar.com/v4.5.8/radar.css" rel="stylesheet">
102
- <script src="https://js.radar.com/v4.5.8/radar.min.js"></script>
101
+ <link href="https://js.radar.com/v5.0.0-beta.0/radar.css" rel="stylesheet">
102
+ <script src="https://js.radar.com/v5.0.0-beta.0/radar.min.js"></script>
103
103
  </head>
104
104
 
105
105
  <body>
@@ -130,8 +130,8 @@ To power [geofencing](https://radar.com/documentation/geofencing/overview) exper
130
130
  ```html
131
131
  <html>
132
132
  <head>
133
- <link href="https://js.radar.com/v4.5.8/radar.css" rel="stylesheet">
134
- <script src="https://js.radar.com/v4.5.8/radar.min.js"></script>
133
+ <link href="https://js.radar.com/v5.0.0-beta.0/radar.css" rel="stylesheet">
134
+ <script src="https://js.radar.com/v5.0.0-beta.0/radar.min.js"></script>
135
135
  </head>
136
136
 
137
137
  <body>
package/dist/api.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { RadarError } from './errors';
2
- import type { Location, RadarAutocompleteParams, RadarConversionParams, RadarDistanceParams, RadarForwardGeocodeParams, RadarMatrixParams, RadarMetadata, RadarOptions, RadarReverseGeocodeParams, RadarSearchGeofencesParams, RadarSearchPlacesParams, RadarStartTrackingVerifiedParams, RadarTrackParams, RadarTrackVerifiedParams, RadarTrackVerifiedResponse, RadarTripOptions, RadarValidateAddressParams } from './types';
2
+ import type { Location, RadarAutocompleteParams, RadarConversionParams, RadarDistanceParams, RadarForwardGeocodeParams, RadarMatrixParams, RadarMetadata, RadarOptions, RadarReverseGeocodeParams, RadarSearchGeofencesParams, RadarSearchPlacesParams, RadarTrackParams, RadarTripOptions, RadarValidateAddressParams } from './types';
3
3
  declare class Radar {
4
4
  static get VERSION(): string;
5
5
  static initialize(publishableKey: string, options?: RadarOptions): void;
@@ -9,12 +9,6 @@ declare class Radar {
9
9
  static setMetadata(metadata?: RadarMetadata): void;
10
10
  static getLocation(): Promise<import("./types").NavigatorPosition>;
11
11
  static trackOnce(params?: RadarTrackParams): Promise<import("./types").RadarTrackResponse>;
12
- static trackVerified(params?: RadarTrackVerifiedParams): Promise<RadarTrackVerifiedResponse>;
13
- static startTrackingVerified(params: RadarStartTrackingVerifiedParams): void;
14
- static stopTrackingVerified(): void;
15
- static getVerifiedLocationToken(params?: RadarTrackVerifiedParams): Promise<RadarTrackVerifiedResponse | null>;
16
- static clearVerifiedLocationToken(): void;
17
- static setExpectedJurisdiction(countryCode?: string, stateCode?: string): void;
18
12
  static getContext(params: Location): Promise<import("./types").RadarContextResponse>;
19
13
  static setTripOptions(tripOptions?: RadarTripOptions): void;
20
14
  static clearTripOptions(): void;
@@ -25,7 +19,6 @@ declare class Radar {
25
19
  static cancelTrip(): Promise<import("./types").RadarTripResponse>;
26
20
  static logConversion(params: RadarConversionParams): Promise<import("./types").RadarConversionResponse>;
27
21
  static setProduct(product?: string): void;
28
- static onTokenUpdated(callback: (token: RadarTrackVerifiedResponse) => void): void;
29
22
  static onError(callback: (error: RadarError) => void): void;
30
23
  static forwardGeocode(params: RadarForwardGeocodeParams): Promise<import("./types").RadarGeocodeResponse>;
31
24
  static reverseGeocode(params: RadarReverseGeocodeParams): Promise<import("./types").RadarGeocodeResponse>;
package/dist/radar.js CHANGED
@@ -174,7 +174,7 @@ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
174
174
  OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
175
175
  PERFORMANCE OF THIS SOFTWARE.
176
176
  ***************************************************************************** */
177
- /* global Reflect, Promise */
177
+ /* global Reflect, Promise, SuppressedError, Symbol, Iterator */
178
178
 
179
179
 
180
180
  function __awaiter(thisArg, _arguments, P, generator) {
@@ -185,7 +185,12 @@ function __awaiter(thisArg, _arguments, P, generator) {
185
185
  function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
186
186
  step((generator = generator.apply(thisArg, _arguments || [])).next());
187
187
  });
188
- }
188
+ }
189
+
190
+ typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
191
+ var e = new Error(message);
192
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
193
+ };
189
194
 
190
195
  class RadarError extends Error {
191
196
  constructor(message) {
@@ -421,7 +426,7 @@ class Navigator {
421
426
  }
422
427
  }
423
428
 
424
- var SDK_VERSION = '4.5.8';
429
+ var SDK_VERSION = '5.0.0-beta.0';
425
430
 
426
431
  const inFlightRequests = new Map();
427
432
  class Http {
@@ -1180,27 +1185,11 @@ class TripsAPI {
1180
1185
  }
1181
1186
  }
1182
1187
 
1183
- const base64Encode = (str) => btoa(str).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
1184
- const signJWT = (payload, key) => __awaiter(void 0, void 0, void 0, function* () {
1185
- const encoder = new TextEncoder();
1186
- const encodedHeader = base64Encode(JSON.stringify({
1187
- alg: 'HS256',
1188
- typ: 'JWT',
1189
- }));
1190
- const encodedPayload = base64Encode(JSON.stringify(payload));
1191
- const keyData = encoder.encode(key);
1192
- const messageData = encoder.encode(`${encodedHeader}.${encodedPayload}`);
1193
- const cryptoKey = yield crypto.subtle.importKey('raw', keyData, { name: 'HMAC', hash: { name: 'SHA-256' } }, false, ['sign']);
1194
- const signatureArrayBuffer = yield crypto.subtle.sign('HMAC', cryptoKey, messageData);
1195
- const signature = base64Encode(String.fromCharCode(...Array.from(new Uint8Array(signatureArrayBuffer))));
1196
- return `${encodedHeader}.${encodedPayload}.${signature}`;
1197
- });
1198
-
1199
1188
  class TrackAPI {
1200
1189
  static trackOnce(params) {
1201
1190
  return __awaiter(this, void 0, void 0, function* () {
1202
1191
  const options = Config.get();
1203
- let { latitude, longitude, accuracy, desiredAccuracy, fraud } = params;
1192
+ let { latitude, longitude, accuracy, desiredAccuracy } = params;
1204
1193
  // if latitude & longitude are not provided,
1205
1194
  // try and retrieve device location (will prompt for location permissions)
1206
1195
  if (!latitude || !longitude) {
@@ -1255,62 +1244,7 @@ class TrackAPI {
1255
1244
  metadata, sdkVersion: SDK_VERSION, stopped: true, userId,
1256
1245
  tripOptions,
1257
1246
  timeZone });
1258
- let response;
1259
- if (fraud) {
1260
- const host = 'https://api-verified.radar.io';
1261
- const lang = navigator.language;
1262
- const langs = navigator.languages;
1263
- const { dk } = yield Http.request({
1264
- host,
1265
- method: 'GET',
1266
- path: 'config',
1267
- data: {
1268
- deviceId,
1269
- installId,
1270
- sessionId,
1271
- locationAuthorization,
1272
- },
1273
- headers: {
1274
- 'X-Radar-Desktop-Device-Type': 'Web',
1275
- },
1276
- });
1277
- const payload = {
1278
- payload: JSON.stringify(Object.assign(Object.assign({}, body), { lang,
1279
- langs })),
1280
- };
1281
- const reqToken = yield signJWT(payload, dk);
1282
- headers['X-Radar-Body-Is-Token'] = 'true';
1283
- response = yield Http.request({
1284
- host,
1285
- method: 'POST',
1286
- path: 'track',
1287
- data: {
1288
- token: reqToken,
1289
- },
1290
- headers,
1291
- });
1292
- let { user, events, token, expiresAt, expiresIn, passed, failureReasons, _id } = response;
1293
- const location = { latitude, longitude, accuracy };
1294
- if (expiresAt) {
1295
- expiresAt = new Date(expiresAt);
1296
- }
1297
- const trackRes = {
1298
- user,
1299
- events,
1300
- location,
1301
- token,
1302
- expiresAt,
1303
- expiresIn,
1304
- passed,
1305
- failureReasons,
1306
- _id,
1307
- };
1308
- if (options.debug) {
1309
- trackRes.response = response;
1310
- }
1311
- return trackRes;
1312
- }
1313
- response = yield Http.request({
1247
+ const response = yield Http.request({
1314
1248
  method: 'POST',
1315
1249
  path: 'track',
1316
1250
  data: body,
@@ -1331,213 +1265,6 @@ class TrackAPI {
1331
1265
  }
1332
1266
  }
1333
1267
 
1334
- let tokenTimeoutId = null;
1335
- let ipChangesIntervalId = null;
1336
- let isTrackingVerified = true;
1337
- let tokenCallback = null;
1338
- let lastToken = null;
1339
- let lastTokenNow = 0;
1340
- let expectedCountryCode = null;
1341
- let expectedStateCode = null;
1342
- let lastIp = null;
1343
- class VerifyAPI {
1344
- static checkIpChanges() {
1345
- return __awaiter(this, void 0, void 0, function* () {
1346
- try {
1347
- const { ip } = yield Http.request({
1348
- method: 'GET',
1349
- path: 'ping',
1350
- });
1351
- const ipChanged = lastIp && ip !== lastIp;
1352
- if (ipChanged) {
1353
- Logger.info(`IP changed from ${lastIp} to ${ip}`);
1354
- lastToken = null;
1355
- }
1356
- lastIp = ip;
1357
- return ipChanged;
1358
- }
1359
- catch (err) {
1360
- Logger.error(`Error checking IP: ${err}`);
1361
- }
1362
- return false;
1363
- });
1364
- }
1365
- static trackVerified(params, encrypted = false) {
1366
- return __awaiter(this, void 0, void 0, function* () {
1367
- try {
1368
- const options = Config.get();
1369
- const { skipVerifyApp, reason } = params;
1370
- // user indentification fields
1371
- const userId = params.userId || Storage.getItem(Storage.USER_ID);
1372
- const deviceId = Device.getDeviceId();
1373
- const installId = Device.getInstallId();
1374
- const sessionId = Session.getSessionId();
1375
- const description = params.description || Storage.getItem(Storage.DESCRIPTION);
1376
- // save userId
1377
- if (!userId) {
1378
- Logger.warn('userId not provided for trackVerified.');
1379
- }
1380
- else {
1381
- Storage.setItem(Storage.USER_ID, userId);
1382
- }
1383
- // other info
1384
- const metadata = params.metadata || Storage.getJSON(Storage.METADATA);
1385
- let trackRes;
1386
- if (skipVerifyApp) {
1387
- trackRes = yield TrackAPI.trackOnce({
1388
- userId: userId !== null && userId !== void 0 ? userId : undefined,
1389
- description: description !== null && description !== void 0 ? description : undefined,
1390
- metadata: metadata,
1391
- fraud: true,
1392
- reason,
1393
- });
1394
- }
1395
- else {
1396
- const body = Object.assign(Object.assign({}, params), { description,
1397
- deviceId, foreground: true, installId,
1398
- sessionId,
1399
- metadata, sdkVersion: SDK_VERSION, stopped: true, userId,
1400
- encrypted,
1401
- expectedCountryCode,
1402
- expectedStateCode });
1403
- let userAgent = navigator.userAgent;
1404
- const apple = userAgent && (userAgent.toLowerCase().includes('mac') || userAgent.toLowerCase().includes('iphone') || userAgent.toLowerCase().includes('ipod') || userAgent.toLowerCase().includes('ipad'));
1405
- const response = yield Http.request({
1406
- method: 'GET',
1407
- path: 'verify',
1408
- data: body,
1409
- host: apple ? 'https://radar-verify.com:52516' : 'http://localhost:52516',
1410
- });
1411
- let { user, events, token, expiresAt, expiresIn, passed, failureReasons, _id } = response;
1412
- let location;
1413
- if (user && user.location && user.location.coordinates && user.locationAccuracy) {
1414
- location = {
1415
- latitude: user.location.coordinates[1],
1416
- longitude: user.location.coordinates[0],
1417
- accuracy: user.locationAccuracy,
1418
- };
1419
- }
1420
- if (expiresAt) {
1421
- expiresAt = new Date(expiresAt);
1422
- }
1423
- trackRes = {
1424
- user,
1425
- events,
1426
- location,
1427
- token,
1428
- expiresAt,
1429
- expiresIn,
1430
- passed,
1431
- failureReasons,
1432
- _id,
1433
- };
1434
- if (options.debug) {
1435
- trackRes.response = response;
1436
- }
1437
- }
1438
- lastToken = trackRes;
1439
- lastTokenNow = performance.now();
1440
- if (tokenCallback) {
1441
- tokenCallback(trackRes);
1442
- }
1443
- return trackRes;
1444
- }
1445
- catch (err) {
1446
- Config.sendError(err);
1447
- throw err;
1448
- }
1449
- });
1450
- }
1451
- static startTrackingVerified(params) {
1452
- isTrackingVerified = true;
1453
- const scheduleNextIntervalWithLastToken = () => __awaiter(this, void 0, void 0, function* () {
1454
- let { interval } = params;
1455
- if (!interval) {
1456
- interval = 20;
1457
- }
1458
- let minInterval = interval;
1459
- if (lastToken) {
1460
- const lastTokenElapsed = (performance.now() - lastTokenNow) / 1000;
1461
- const expiresIn = (lastToken.expiresIn || 0);
1462
- // if expiresIn is shorter than interval, override interval
1463
- // re-request early to maximize the likelihood that a cached token is available
1464
- minInterval = Math.min(expiresIn - lastTokenElapsed, interval);
1465
- }
1466
- minInterval = minInterval - 10;
1467
- // min interval is 10 seconds
1468
- if (minInterval < 10) {
1469
- minInterval = 10;
1470
- }
1471
- if (tokenTimeoutId) {
1472
- clearTimeout(tokenTimeoutId);
1473
- }
1474
- if (isTrackingVerified) {
1475
- tokenTimeoutId = setTimeout(doTrackVerified, minInterval * 1000);
1476
- }
1477
- });
1478
- const doTrackVerified = () => __awaiter(this, void 0, void 0, function* () {
1479
- try {
1480
- yield this.trackVerified(params);
1481
- }
1482
- catch (err) {
1483
- Logger.error(`trackVerified error: ${err.message}`);
1484
- }
1485
- scheduleNextIntervalWithLastToken();
1486
- });
1487
- if (params === null || params === void 0 ? void 0 : params.ipChanges) {
1488
- if (ipChangesIntervalId) {
1489
- clearInterval(ipChangesIntervalId);
1490
- }
1491
- ipChangesIntervalId = setInterval(() => __awaiter(this, void 0, void 0, function* () {
1492
- const ipChanged = yield VerifyAPI.checkIpChanges();
1493
- if (ipChanged) {
1494
- doTrackVerified();
1495
- }
1496
- }), 10000);
1497
- }
1498
- if (this.isLastTokenValid()) {
1499
- scheduleNextIntervalWithLastToken();
1500
- }
1501
- else {
1502
- doTrackVerified();
1503
- }
1504
- }
1505
- static stopTrackingVerified() {
1506
- isTrackingVerified = false;
1507
- if (tokenTimeoutId) {
1508
- clearTimeout(tokenTimeoutId);
1509
- }
1510
- if (ipChangesIntervalId) {
1511
- clearInterval(ipChangesIntervalId);
1512
- }
1513
- }
1514
- static getVerifiedLocationToken(params) {
1515
- return __awaiter(this, void 0, void 0, function* () {
1516
- if (this.isLastTokenValid()) {
1517
- return lastToken;
1518
- }
1519
- return this.trackVerified(params);
1520
- });
1521
- }
1522
- static clearVerifiedLocationToken() {
1523
- lastToken = null;
1524
- }
1525
- static isLastTokenValid() {
1526
- if (!lastToken) {
1527
- return false;
1528
- }
1529
- const lastTokenElapsed = (performance.now() - lastTokenNow) / 1000;
1530
- return lastToken.passed && lastTokenElapsed < (lastToken.expiresIn || 0);
1531
- }
1532
- static setExpectedJurisdiction(countryCode, stateCode) {
1533
- expectedCountryCode = countryCode || null;
1534
- expectedStateCode = stateCode || null;
1535
- }
1536
- static onTokenUpdated(callback) {
1537
- tokenCallback = callback;
1538
- }
1539
- }
1540
-
1541
1268
  const isSecretKey = (key) => (key.includes('_sk_'));
1542
1269
  const isLiveKey = (key) => (key.includes('_live_'));
1543
1270
  let Radar$1 = class Radar {
@@ -1610,24 +1337,6 @@ let Radar$1 = class Radar {
1610
1337
  ConfigAPI.getConfig(params); // call with updated permissions
1611
1338
  }
1612
1339
  }
1613
- static trackVerified(params = {}) {
1614
- return VerifyAPI.trackVerified(params);
1615
- }
1616
- static startTrackingVerified(params) {
1617
- VerifyAPI.startTrackingVerified(params);
1618
- }
1619
- static stopTrackingVerified() {
1620
- VerifyAPI.stopTrackingVerified();
1621
- }
1622
- static getVerifiedLocationToken(params = {}) {
1623
- return VerifyAPI.getVerifiedLocationToken(params);
1624
- }
1625
- static clearVerifiedLocationToken() {
1626
- VerifyAPI.clearVerifiedLocationToken();
1627
- }
1628
- static setExpectedJurisdiction(countryCode, stateCode) {
1629
- VerifyAPI.setExpectedJurisdiction(countryCode, stateCode);
1630
- }
1631
1340
  static getContext(params) {
1632
1341
  return ContextAPI.getContext(params);
1633
1342
  }
@@ -1665,9 +1374,6 @@ let Radar$1 = class Radar {
1665
1374
  ///////////////////////
1666
1375
  // Listeners
1667
1376
  ///////////////////////
1668
- static onTokenUpdated(callback) {
1669
- VerifyAPI.onTokenUpdated(callback);
1670
- }
1671
1377
  static onError(callback) {
1672
1378
  Config.onError(callback);
1673
1379
  }
@@ -2141,21 +1847,20 @@ class RadarMap extends maplibregl.Map {
2141
1847
  showZoom: mapOptions.showZoomControls,
2142
1848
  });
2143
1849
  this.addControl(nav, 'bottom-right');
2144
- // handle map resize actions
2145
- const onResize = () => {
2146
- const attrib = document.querySelector('.maplibregl-ctrl-attrib');
2147
- if (attrib) {
2148
- const width = this.getContainer().clientWidth;
2149
- if (width < 380) {
2150
- attrib.classList.add('hidden');
2151
- }
2152
- else {
2153
- attrib.classList.remove('hidden');
2154
- }
1850
+ this.on('resize', this._onResize.bind(this));
1851
+ this.on('load', this._onResize.bind(this));
1852
+ }
1853
+ _onResize() {
1854
+ const attrib = document.querySelector('.maplibregl-ctrl-attrib');
1855
+ if (attrib) {
1856
+ const width = this.getContainer().clientWidth; // Memory leak here
1857
+ if (width < 380) {
1858
+ attrib.classList.add('hidden');
2155
1859
  }
2156
- };
2157
- this.on('resize', onResize);
2158
- this.on('load', onResize);
1860
+ else {
1861
+ attrib.classList.remove('hidden');
1862
+ }
1863
+ }
2159
1864
  }
2160
1865
  addMarker(marker) {
2161
1866
  this._markers.push(marker);
package/dist/radar.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"radar.js","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
package/dist/types.d.ts CHANGED
@@ -2,7 +2,10 @@ export type LogLevel = 'none' | 'info' | 'warn' | 'error';
2
2
  export interface Location {
3
3
  latitude: number;
4
4
  longitude: number;
5
+ /** Meters */
5
6
  accuracy?: number;
7
+ /** Unix time in seconds */
8
+ timestamp?: number;
6
9
  }
7
10
  export interface NavigatorPosition {
8
11
  latitude: number;
@@ -52,8 +55,8 @@ export interface RadarTrackParams {
52
55
  metadata?: RadarMetadata;
53
56
  tripOptions?: RadarTripOptions;
54
57
  desiredAccuracy?: 'high' | 'medium' | 'low';
55
- fraud?: boolean;
56
58
  reason?: string;
59
+ transactionId?: string;
57
60
  }
58
61
  export interface RadarTrackVerifiedParams {
59
62
  userId?: string;
@@ -61,6 +64,7 @@ export interface RadarTrackVerifiedParams {
61
64
  metadata?: RadarMetadata;
62
65
  skipVerifyApp?: boolean;
63
66
  reason?: string;
67
+ transactionId?: string;
64
68
  }
65
69
  export interface RadarStartTrackingVerifiedParams {
66
70
  interval: number;
@@ -151,13 +155,19 @@ export interface RadarUser {
151
155
  postalCode?: RadarRegion;
152
156
  fraud?: RadarFraud;
153
157
  }
158
+ export interface RadarConfigResponse extends RadarResponse {
159
+ nonce?: string;
160
+ googleCloudProjectNumber?: number;
161
+ dk?: string;
162
+ scl?: number;
163
+ }
154
164
  export interface RadarTrackResponse extends RadarResponse {
155
165
  location?: Location;
156
166
  user?: RadarUser;
157
167
  events?: RadarEvent[];
158
168
  }
159
169
  export interface RadarTrackVerifiedResponse extends RadarTrackResponse {
160
- token?: String;
170
+ token?: string;
161
171
  expiresAt?: Date;
162
172
  expiresIn?: number;
163
173
  passed?: boolean;
@@ -347,7 +357,7 @@ export interface RadarMatrixRoute {
347
357
  export interface RadarMatrixResponse extends RadarResponse {
348
358
  origins: Location[];
349
359
  destinations: Location[];
350
- matrix: RadarMatrixRoute[];
360
+ matrix: RadarMatrixRoute[][];
351
361
  }
352
362
  export interface RadarValidateAddressParams {
353
363
  city: string;
@@ -8,6 +8,7 @@ declare class RadarMap extends maplibregl.Map {
8
8
  _markers: RadarMarker[];
9
9
  _features: RadarMapFeature[];
10
10
  constructor(radarMapOptions: RadarMapOptions);
11
+ private _onResize;
11
12
  addMarker(marker: RadarMarker): void;
12
13
  removeMarker(marker: RadarMarker): void;
13
14
  getMarkers(): RadarMarker[];
package/dist/version.d.ts CHANGED
@@ -1,2 +1,2 @@
1
- declare const _default: "4.5.8";
1
+ declare const _default: "5.0.0-beta.0";
2
2
  export default _default;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "radar-sdk-js",
3
- "version": "4.5.8",
3
+ "version": "5.0.0-beta.0",
4
4
  "description": "Web Javascript SDK for Radar, location infrastructure for mobile and web apps.",
5
5
  "homepage": "https://radar.com",
6
6
  "type": "module",
@@ -30,6 +30,7 @@
30
30
  "author": "",
31
31
  "license": "ISC",
32
32
  "devDependencies": {
33
+ "@rollup/plugin-alias": "^5.1.1",
33
34
  "@rollup/plugin-commonjs": "^25.0.2",
34
35
  "@rollup/plugin-json": "^6.0.0",
35
36
  "@rollup/plugin-node-resolve": "^15.1.0",
@@ -48,6 +49,7 @@
48
49
  "nodemon": "^2.0.22",
49
50
  "rollup": "^3.23.0",
50
51
  "rollup-plugin-copy": "^3.4.0",
52
+ "rollup-plugin-obfuscator": "^1.1.0",
51
53
  "rollup-plugin-postcss": "^4.0.2",
52
54
  "rollup-plugin-typescript2": "^0.34.1",
53
55
  "ts-jest": "^29.1.0",
package/src/api/track.ts CHANGED
@@ -7,12 +7,10 @@ import Navigator from '../navigator';
7
7
  import Session from '../session';
8
8
  import Storage from '../storage';
9
9
  import TripsAPI from './trips';
10
- import { signJWT } from '../util/jwt';
11
10
 
12
- import type { RadarTrackParams, RadarTrackResponse, RadarTrackVerifiedResponse } from '../types';
11
+ import type { RadarTrackParams, RadarTrackResponse } from '../types';
13
12
 
14
13
  type TrackRequestHeaders = {
15
- 'X-Radar-Body-Is-Token'?: string;
16
14
  'X-Radar-Product'?: string;
17
15
  }
18
16
 
@@ -20,7 +18,7 @@ class TrackAPI {
20
18
  static async trackOnce(params: RadarTrackParams) {
21
19
  const options = Config.get();
22
20
 
23
- let { latitude, longitude, accuracy, desiredAccuracy, fraud } = params;
21
+ let { latitude, longitude, accuracy, desiredAccuracy } = params;
24
22
 
25
23
  // if latitude & longitude are not provided,
26
24
  // try and retrieve device location (will prompt for location permissions)
@@ -92,75 +90,7 @@ class TrackAPI {
92
90
  timeZone,
93
91
  };
94
92
 
95
- let response: any;
96
- if (fraud) {
97
- const host = 'https://api-verified.radar.io';
98
-
99
- const lang = navigator.language;
100
- const langs = navigator.languages;
101
-
102
- const { dk }: any = await Http.request({
103
- host,
104
- method: 'GET',
105
- path: 'config',
106
- data: {
107
- deviceId,
108
- installId,
109
- sessionId,
110
- locationAuthorization,
111
- },
112
- headers: {
113
- 'X-Radar-Desktop-Device-Type': 'Web',
114
- },
115
- });
116
-
117
- const payload = {
118
- payload: JSON.stringify({
119
- ...body,
120
- lang,
121
- langs,
122
- }),
123
- };
124
-
125
- const reqToken = await signJWT(payload, dk);
126
- headers['X-Radar-Body-Is-Token'] = 'true'
127
-
128
- response = await Http.request({
129
- host,
130
- method: 'POST',
131
- path: 'track',
132
- data: {
133
- token: reqToken,
134
- },
135
- headers,
136
- });
137
-
138
- let { user, events, token, expiresAt, expiresIn, passed, failureReasons, _id } = response;
139
- const location = { latitude, longitude, accuracy };
140
- if (expiresAt) {
141
- expiresAt = new Date(expiresAt);
142
- }
143
-
144
- const trackRes = {
145
- user,
146
- events,
147
- location,
148
- token,
149
- expiresAt,
150
- expiresIn,
151
- passed,
152
- failureReasons,
153
- _id,
154
- } as RadarTrackVerifiedResponse;
155
-
156
- if (options.debug) {
157
- trackRes.response = response;
158
- }
159
-
160
- return trackRes;
161
- }
162
-
163
- response = await Http.request({
93
+ const response: any = await Http.request({
164
94
  method: 'POST',
165
95
  path: 'track',
166
96
  data: body,
package/src/api.ts CHANGED
@@ -13,7 +13,6 @@ import RoutingAPI from './api/routing';
13
13
  import SearchAPI from './api/search';
14
14
  import TrackAPI from './api/track';
15
15
  import TripsAPI from './api/trips';
16
- import VerifyAPI from './api/verify';
17
16
 
18
17
  import SDK_VERSION from './version';
19
18
 
@@ -29,10 +28,7 @@ import type {
29
28
  RadarReverseGeocodeParams,
30
29
  RadarSearchGeofencesParams,
31
30
  RadarSearchPlacesParams,
32
- RadarStartTrackingVerifiedParams,
33
31
  RadarTrackParams,
34
- RadarTrackVerifiedParams,
35
- RadarTrackVerifiedResponse,
36
32
  RadarTripOptions,
37
33
  RadarValidateAddressParams,
38
34
  } from './types';
@@ -130,30 +126,6 @@ class Radar {
130
126
  }
131
127
  }
132
128
 
133
- public static trackVerified(params: RadarTrackVerifiedParams = {}) {
134
- return VerifyAPI.trackVerified(params);
135
- }
136
-
137
- public static startTrackingVerified(params: RadarStartTrackingVerifiedParams) {
138
- VerifyAPI.startTrackingVerified(params);
139
- }
140
-
141
- public static stopTrackingVerified() {
142
- VerifyAPI.stopTrackingVerified();
143
- }
144
-
145
- public static getVerifiedLocationToken(params: RadarTrackVerifiedParams = {}) {
146
- return VerifyAPI.getVerifiedLocationToken(params);
147
- }
148
-
149
- public static clearVerifiedLocationToken() {
150
- VerifyAPI.clearVerifiedLocationToken();
151
- }
152
-
153
- public static setExpectedJurisdiction(countryCode?: string, stateCode?: string) {
154
- VerifyAPI.setExpectedJurisdiction(countryCode, stateCode);
155
- }
156
-
157
129
  public static getContext(params: Location) {
158
130
  return ContextAPI.getContext(params);
159
131
  }
@@ -202,10 +174,6 @@ class Radar {
202
174
  // Listeners
203
175
  ///////////////////////
204
176
 
205
- public static onTokenUpdated(callback: (token: RadarTrackVerifiedResponse) => void) {
206
- VerifyAPI.onTokenUpdated(callback);
207
- }
208
-
209
177
  public static onError(callback: (error: RadarError) => void) {
210
178
  Config.onError(callback);
211
179
  }
package/src/types.ts CHANGED
@@ -3,7 +3,10 @@ export type LogLevel = 'none' | 'info' | 'warn' | 'error'
3
3
  export interface Location {
4
4
  latitude: number;
5
5
  longitude: number;
6
+ /** Meters */
6
7
  accuracy?: number;
8
+ /** Unix time in seconds */
9
+ timestamp?: number;
7
10
  }
8
11
 
9
12
  export interface NavigatorPosition {
@@ -74,8 +77,8 @@ export interface RadarTrackParams {
74
77
  metadata?: RadarMetadata;
75
78
  tripOptions?: RadarTripOptions;
76
79
  desiredAccuracy?: 'high' | 'medium' | 'low';
77
- fraud?: boolean;
78
80
  reason?: string;
81
+ transactionId?: string;
79
82
  }
80
83
 
81
84
  export interface RadarTrackVerifiedParams {
@@ -84,6 +87,7 @@ export interface RadarTrackVerifiedParams {
84
87
  metadata?: RadarMetadata;
85
88
  skipVerifyApp?: boolean;
86
89
  reason?: string;
90
+ transactionId?: string;
87
91
  }
88
92
 
89
93
  export interface RadarStartTrackingVerifiedParams {
@@ -223,6 +227,14 @@ export interface RadarUser {
223
227
  fraud?: RadarFraud;
224
228
  }
225
229
 
230
+ export interface RadarConfigResponse extends RadarResponse {
231
+ nonce?: string;
232
+ googleCloudProjectNumber?: number;
233
+ // desktop key for signing trackVerified requests
234
+ dk?: string;
235
+ scl?: number;
236
+ }
237
+
226
238
  export interface RadarTrackResponse extends RadarResponse {
227
239
  location?: Location;
228
240
  user?: RadarUser;
@@ -230,7 +242,7 @@ export interface RadarTrackResponse extends RadarResponse {
230
242
  }
231
243
 
232
244
  export interface RadarTrackVerifiedResponse extends RadarTrackResponse {
233
- token?: String;
245
+ token?: string;
234
246
  expiresAt?: Date;
235
247
  expiresIn?: number;
236
248
  passed?: boolean;
@@ -464,7 +476,7 @@ export interface RadarMatrixRoute {
464
476
  export interface RadarMatrixResponse extends RadarResponse {
465
477
  origins: Location[];
466
478
  destinations: Location[];
467
- matrix: RadarMatrixRoute[];
479
+ matrix: RadarMatrixRoute[][];
468
480
  }
469
481
 
470
482
  export interface RadarValidateAddressParams {
@@ -138,20 +138,20 @@ class RadarMap extends maplibregl.Map {
138
138
  });
139
139
  this.addControl(nav, 'bottom-right');
140
140
 
141
- // handle map resize actions
142
- const onResize = () => {
143
- const attrib = document.querySelector('.maplibregl-ctrl-attrib');
144
- if (attrib) {
145
- const width = this.getContainer().clientWidth;
146
- if (width < 380) {
147
- attrib.classList.add('hidden');
148
- } else {
149
- attrib.classList.remove('hidden');
150
- }
141
+ this.on('resize', this._onResize.bind(this));
142
+ this.on('load', this._onResize.bind(this));
143
+ }
144
+
145
+ private _onResize(): void {
146
+ const attrib = document.querySelector('.maplibregl-ctrl-attrib');
147
+ if (attrib) {
148
+ const width = this.getContainer().clientWidth; // Memory leak here
149
+ if (width < 380) {
150
+ attrib.classList.add('hidden');
151
+ } else {
152
+ attrib.classList.remove('hidden');
151
153
  }
152
- };
153
- this.on('resize', onResize);
154
- this.on('load', onResize);
154
+ }
155
155
  }
156
156
 
157
157
  addMarker(marker: RadarMarker) {
package/src/version.ts CHANGED
@@ -1 +1 @@
1
- export default '4.5.8';
1
+ export default '5.0.0-beta.0';
@@ -1,13 +0,0 @@
1
- import type { RadarStartTrackingVerifiedParams, RadarTrackVerifiedParams, RadarTrackVerifiedResponse } from '../types';
2
- declare class VerifyAPI {
3
- static checkIpChanges(): Promise<boolean | "" | null>;
4
- static trackVerified(params: RadarTrackVerifiedParams, encrypted?: Boolean): Promise<RadarTrackVerifiedResponse>;
5
- static startTrackingVerified(params: RadarStartTrackingVerifiedParams): void;
6
- static stopTrackingVerified(): void;
7
- static getVerifiedLocationToken(params: RadarTrackVerifiedParams): Promise<RadarTrackVerifiedResponse | null>;
8
- static clearVerifiedLocationToken(): void;
9
- static isLastTokenValid(): boolean | undefined;
10
- static setExpectedJurisdiction(countryCode?: string, stateCode?: string): void;
11
- static onTokenUpdated(callback: (token: RadarTrackVerifiedResponse) => void): void;
12
- }
13
- export default VerifyAPI;
@@ -1 +0,0 @@
1
- export declare const signJWT: (payload: object, key: string) => Promise<string>;
package/src/api/verify.ts DELETED
@@ -1,263 +0,0 @@
1
- import SDK_VERSION from '../version';
2
- import Config from '../config';
3
- import Device from '../device';
4
- import Http from '../http';
5
- import Logger from '../logger';
6
- import Session from '../session';
7
- import Storage from '../storage';
8
- import TrackAPI from './track';
9
-
10
- import type { RadarStartTrackingVerifiedParams, RadarTrackVerifiedParams, RadarTrackVerifiedResponse } from '../types';
11
-
12
- let tokenTimeoutId: any | null = null;
13
- let ipChangesIntervalId: any | null = null;
14
- let isTrackingVerified = true;
15
- let tokenCallback: ((token: RadarTrackVerifiedResponse) => void) | null = null;
16
- let lastToken: RadarTrackVerifiedResponse | null = null;
17
- let lastTokenNow: number = 0;
18
- let expectedCountryCode: string | null = null;
19
- let expectedStateCode: string | null = null;
20
- let lastIp: string | null = null;
21
-
22
- class VerifyAPI {
23
- static async checkIpChanges() {
24
- try {
25
- const { ip }: any = await Http.request({
26
- method: 'GET',
27
- path: 'ping',
28
- });
29
-
30
- const ipChanged = lastIp && ip !== lastIp;
31
- if (ipChanged) {
32
- Logger.info(`IP changed from ${lastIp} to ${ip}`);
33
-
34
- lastToken = null;
35
- }
36
-
37
- lastIp = ip;
38
-
39
- return ipChanged;
40
- } catch (err) {
41
- Logger.error(`Error checking IP: ${err}`);
42
- }
43
-
44
- return false;
45
- }
46
-
47
- static async trackVerified(params: RadarTrackVerifiedParams, encrypted: Boolean = false) {
48
- try {
49
- const options = Config.get();
50
-
51
- const { skipVerifyApp, reason } = params;
52
-
53
- // user indentification fields
54
- const userId = params.userId || Storage.getItem(Storage.USER_ID);
55
- const deviceId = Device.getDeviceId();
56
- const installId = Device.getInstallId();
57
- const sessionId = Session.getSessionId();
58
- const description = params.description || Storage.getItem(Storage.DESCRIPTION);
59
-
60
- // save userId
61
- if (!userId) {
62
- Logger.warn('userId not provided for trackVerified.');
63
- } else {
64
- Storage.setItem(Storage.USER_ID, userId);
65
- }
66
-
67
- // other info
68
- const metadata = params.metadata || Storage.getJSON(Storage.METADATA);
69
-
70
- let trackRes: RadarTrackVerifiedResponse;
71
- if (skipVerifyApp) {
72
- trackRes = await TrackAPI.trackOnce({
73
- userId: userId ?? undefined,
74
- description: description ?? undefined,
75
- metadata: metadata,
76
- fraud: true,
77
- reason,
78
- });
79
- } else {
80
- const body = {
81
- ...params,
82
- description,
83
- deviceId,
84
- foreground: true,
85
- installId,
86
- sessionId,
87
- metadata,
88
- sdkVersion: SDK_VERSION,
89
- stopped: true,
90
- userId,
91
- encrypted,
92
- expectedCountryCode,
93
- expectedStateCode,
94
- };
95
-
96
- let userAgent = navigator.userAgent;
97
- const apple = userAgent && (userAgent.toLowerCase().includes('mac') || userAgent.toLowerCase().includes('iphone') || userAgent.toLowerCase().includes('ipod') || userAgent.toLowerCase().includes('ipad'));
98
-
99
- const response: any = await Http.request({
100
- method: 'GET',
101
- path: 'verify',
102
- data: body,
103
- host: apple ? 'https://radar-verify.com:52516' : 'http://localhost:52516',
104
- });
105
-
106
- let { user, events, token, expiresAt, expiresIn, passed, failureReasons, _id } = response;
107
- let location;
108
- if (user && user.location && user.location.coordinates && user.locationAccuracy) {
109
- location = {
110
- latitude: user.location.coordinates[1],
111
- longitude: user.location.coordinates[0],
112
- accuracy: user.locationAccuracy,
113
- };
114
- }
115
- if (expiresAt) {
116
- expiresAt = new Date(expiresAt);
117
- }
118
-
119
- trackRes = {
120
- user,
121
- events,
122
- location,
123
- token,
124
- expiresAt,
125
- expiresIn,
126
- passed,
127
- failureReasons,
128
- _id,
129
- } as RadarTrackVerifiedResponse;
130
-
131
- if (options.debug) {
132
- trackRes.response = response;
133
- }
134
- }
135
-
136
- lastToken = trackRes;
137
- lastTokenNow = performance.now();
138
-
139
- if (tokenCallback) {
140
- tokenCallback(trackRes);
141
- }
142
-
143
- return trackRes;
144
- } catch (err: any) {
145
- Config.sendError(err);
146
- throw err;
147
- }
148
- }
149
-
150
- static startTrackingVerified(params: RadarStartTrackingVerifiedParams) {
151
- isTrackingVerified = true;
152
-
153
- const scheduleNextIntervalWithLastToken = async () => {
154
- let { interval } = params;
155
-
156
- if (!interval) {
157
- interval = 20;
158
- }
159
-
160
- let minInterval = interval;
161
-
162
- if (lastToken) {
163
- const lastTokenElapsed = (performance.now() - lastTokenNow) / 1000;
164
-
165
- const expiresIn = (lastToken.expiresIn || 0);
166
-
167
- // if expiresIn is shorter than interval, override interval
168
- // re-request early to maximize the likelihood that a cached token is available
169
- minInterval = Math.min(expiresIn - lastTokenElapsed, interval);
170
- }
171
-
172
- minInterval = minInterval - 10;
173
-
174
- // min interval is 10 seconds
175
- if (minInterval < 10) {
176
- minInterval = 10;
177
- }
178
-
179
- if (tokenTimeoutId) {
180
- clearTimeout(tokenTimeoutId);
181
- }
182
-
183
- if (isTrackingVerified) {
184
- tokenTimeoutId = setTimeout(doTrackVerified, minInterval * 1000);
185
- }
186
- };
187
-
188
- const doTrackVerified = async () => {
189
- try {
190
- await this.trackVerified(params);
191
- } catch (err: any) {
192
- Logger.error(`trackVerified error: ${err.message}`);
193
- }
194
-
195
- scheduleNextIntervalWithLastToken();
196
- };
197
-
198
- if (params?.ipChanges) {
199
- if (ipChangesIntervalId) {
200
- clearInterval(ipChangesIntervalId);
201
- }
202
-
203
- ipChangesIntervalId = setInterval(async () => {
204
- const ipChanged = await VerifyAPI.checkIpChanges();
205
-
206
- if (ipChanged) {
207
- doTrackVerified();
208
- }
209
- }, 10000);
210
- }
211
-
212
- if (this.isLastTokenValid()) {
213
- scheduleNextIntervalWithLastToken();
214
- } else {
215
- doTrackVerified();
216
- }
217
- }
218
-
219
- static stopTrackingVerified() {
220
- isTrackingVerified = false;
221
-
222
- if (tokenTimeoutId) {
223
- clearTimeout(tokenTimeoutId);
224
- }
225
-
226
- if (ipChangesIntervalId) {
227
- clearInterval(ipChangesIntervalId);
228
- }
229
- }
230
-
231
- static async getVerifiedLocationToken(params: RadarTrackVerifiedParams) {
232
- if (this.isLastTokenValid()) {
233
- return lastToken;
234
- }
235
-
236
- return this.trackVerified(params);
237
- }
238
-
239
- static clearVerifiedLocationToken() {
240
- lastToken = null;
241
- }
242
-
243
- static isLastTokenValid() {
244
- if (!lastToken) {
245
- return false;
246
- }
247
-
248
- const lastTokenElapsed = (performance.now() - lastTokenNow) / 1000;
249
-
250
- return lastToken.passed && lastTokenElapsed < (lastToken.expiresIn || 0);
251
- }
252
-
253
- static setExpectedJurisdiction(countryCode?: string, stateCode?: string) {
254
- expectedCountryCode = countryCode || null;
255
- expectedStateCode = stateCode || null;
256
- }
257
-
258
- static onTokenUpdated(callback: (token: RadarTrackVerifiedResponse) => void) {
259
- tokenCallback = callback;
260
- }
261
- }
262
-
263
- export default VerifyAPI;
package/src/util/jwt.ts DELETED
@@ -1,28 +0,0 @@
1
- const base64Encode = (str: string): string =>
2
- btoa(str).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
3
-
4
- export const signJWT = async (payload: object, key: string): Promise<string> => {
5
- const encoder = new TextEncoder();
6
-
7
- const encodedHeader = base64Encode(JSON.stringify({
8
- alg: 'HS256',
9
- typ: 'JWT',
10
- }));
11
- const encodedPayload = base64Encode(JSON.stringify(payload));
12
-
13
- const keyData = encoder.encode(key);
14
- const messageData = encoder.encode(`${encodedHeader}.${encodedPayload}`);
15
-
16
- const cryptoKey = await crypto.subtle.importKey(
17
- 'raw',
18
- keyData,
19
- { name: 'HMAC', hash: { name: 'SHA-256' } },
20
- false,
21
- ['sign']
22
- );
23
-
24
- const signatureArrayBuffer = await crypto.subtle.sign('HMAC', cryptoKey, messageData);
25
- const signature = base64Encode(String.fromCharCode(...Array.from(new Uint8Array(signatureArrayBuffer))));
26
-
27
- return `${encodedHeader}.${encodedPayload}.${signature}`;
28
- };