@alipay/ams-checkout 0.0.1776306844-dev.2 → 0.0.1777017092-dev.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.
@@ -20,6 +20,16 @@ export declare class EventCenter {
20
20
  * @returns
21
21
  */
22
22
  endEvent(startId: string, extra?: any): void;
23
+ /**
24
+ * Cancels a single active event and reports it as an ended event with canceled=true.
25
+ * This is used when the mount flow is terminated early (for example, on destroy or abnormal exit).
26
+ */
27
+ cancelEvent(startId: string, extra?: any): void;
28
+ /**
29
+ * Cancels all active events whose event id starts with the given prefix.
30
+ * For example, prefix 'mount' will cancel events like mount_1_start.
31
+ */
32
+ cancelByPrefix(prefix: string, extra?: any): void;
23
33
  private startHeartbeat;
24
34
  private stopHeartbeat;
25
35
  private sendHeartbeat;
@@ -89,17 +89,53 @@ export var EventCenter = /*#__PURE__*/function () {
89
89
  // 如果活动事件数量为0,则停止心跳
90
90
  if (this.activeEvents.size === 0) this.stopHeartbeat();
91
91
  }
92
+
93
+ /**
94
+ * Cancels a single active event and reports it as an ended event with canceled=true.
95
+ * This is used when the mount flow is terminated early (for example, on destroy or abnormal exit).
96
+ */
97
+ }, {
98
+ key: "cancelEvent",
99
+ value: function cancelEvent(startId, extra) {
100
+ if (!this.activeEvents.has(startId)) return;
101
+ var startTime = this.activeEvents.get(startId);
102
+ this.activeEvents.delete(startId);
103
+ var type = this.getEventNameFromStart(startId, 'end');
104
+ this.sendLog(type, _objectSpread({
105
+ eventName: this.buildIdFromStart(startId, 'end'),
106
+ startTime: startTime,
107
+ endTime: Date.now(),
108
+ canceled: true
109
+ }, extra || {}));
110
+ if (this.activeEvents.size === 0) this.stopHeartbeat();
111
+ }
112
+
113
+ /**
114
+ * Cancels all active events whose event id starts with the given prefix.
115
+ * For example, prefix 'mount' will cancel events like mount_1_start.
116
+ */
117
+ }, {
118
+ key: "cancelByPrefix",
119
+ value: function cancelByPrefix(prefix, extra) {
120
+ var _this = this;
121
+ var ids = Array.from(this.activeEvents.keys()).filter(function (id) {
122
+ return id.startsWith(prefix);
123
+ });
124
+ ids.forEach(function (id) {
125
+ return _this.cancelEvent(id, extra);
126
+ });
127
+ }
92
128
  }, {
93
129
  key: "startHeartbeat",
94
130
  value: function startHeartbeat() {
95
- var _this = this;
131
+ var _this2 = this;
96
132
  if (this.heartbeatIntervalId) return;
97
133
  this.heartbeatIntervalId = setInterval(function () {
98
- if (_this.activeEvents.size === 0) {
99
- _this.stopHeartbeat();
134
+ if (_this2.activeEvents.size === 0) {
135
+ _this2.stopHeartbeat();
100
136
  return;
101
137
  }
102
- _this.sendHeartbeat();
138
+ _this2.sendHeartbeat();
103
139
  }, this.HEARTBEAT_INTERVAL);
104
140
  }
105
141
  }, {
@@ -20,6 +20,8 @@ declare class ElementController {
20
20
  private handleInitializationError;
21
21
  private handleMountError;
22
22
  private clearAndSetInitTimeout;
23
+ private clearInitTimeout;
24
+ private clearEvents;
23
25
  private setInitTimeout;
24
26
  private initializeAndMountProcessor;
25
27
  private handleStartBizFlowError;
@@ -189,6 +189,25 @@ var ElementController = /*#__PURE__*/function () {
189
189
  this.initTimeout = this.setInitTimeout(resolve);
190
190
  }
191
191
 
192
+ // Clears the pending init timeout to avoid timeout callbacks from stale Element instances.
193
+ }, {
194
+ key: "clearInitTimeout",
195
+ value: function clearInitTimeout() {
196
+ clearTimeout(this.initTimeout);
197
+ this.initTimeout = null;
198
+ }
199
+
200
+ // Clears mount-related heartbeat events to avoid stale heartbeat reporting after abnormal exit.
201
+ }, {
202
+ key: "clearEvents",
203
+ value: function clearEvents(reason) {
204
+ var _this$elementEventCen, _this$elementEventCen2;
205
+ // antlog examples: actionName=mount_end&msg=destroy, actionName=mount_end&msg=webLaunch
206
+ (_this$elementEventCen = (_this$elementEventCen2 = this.elementEventCenter).cancelByPrefix) === null || _this$elementEventCen === void 0 || _this$elementEventCen.call(_this$elementEventCen2, 'mount', {
207
+ msg: reason
208
+ });
209
+ }
210
+
192
211
  // 设置初始化超时定时器
193
212
  }, {
194
213
  key: "setInitTimeout",
@@ -660,18 +679,22 @@ var ElementController = /*#__PURE__*/function () {
660
679
  _this5.sendReady(key, options);
661
680
  });
662
681
  }
663
- _context5.next = 24;
682
+ _context5.next = 26;
664
683
  break;
665
684
  case 20:
666
685
  _context5.prev = 20;
667
686
  _context5.t0 = _context5["catch"](1);
668
687
  this.handleInitializationError();
688
+ // Fix: when request processing enters the catch path (excluding success=false business responses),
689
+ // stale timeout and heartbeat events must be cleared to avoid duplicate error callbacks.
690
+ this.clearInitTimeout();
691
+ this.clearEvents('webLaunch');
669
692
  readyCallback({
670
693
  error: _objectSpread(_objectSpread({}, ERRORMESSAGE.INITIALIZE_TIMEOUT.API), {}, {
671
694
  traceId: _context5.t0 === null || _context5.t0 === void 0 ? void 0 : _context5.t0.traceId
672
695
  })
673
696
  });
674
- case 24:
697
+ case 26:
675
698
  case "end":
676
699
  return _context5.stop();
677
700
  }
@@ -828,6 +851,10 @@ var ElementController = /*#__PURE__*/function () {
828
851
  }, {
829
852
  key: "destroyHandle",
830
853
  value: function destroyHandle() {
854
+ // Fix: when a failed mount is destroyed and a new mount succeeds within the 16s timeout window,
855
+ // clear stale timeout and heartbeat events from the destroyed instance.
856
+ this.clearEvents('destroy');
857
+ this.clearInitTimeout();
831
858
  this.elementContainer.destroy();
832
859
  cleanMockup();
833
860
  removeRetentionPopup();
@@ -281,6 +281,11 @@ var PaymentProcessor = /*#__PURE__*/function (_BaseElementProcessor) {
281
281
  }, 100);
282
282
  return;
283
283
  }
284
+ _this3.getLogger().logInfo({
285
+ title: 'sdk_action_query_start'
286
+ }, {
287
+ config: safeStringify(paymentSessionConfig)
288
+ });
284
289
  var sdkRequestData = {
285
290
  paymentSessionConfig: paymentSessionConfig,
286
291
  paymentSessionData: paymentSession,
@@ -11,6 +11,7 @@ import type { AMSCheckoutOptions, IAppendParams, InitSecurityConfig, IoptionsPar
11
11
  import { EventCenter } from '../../util/index';
12
12
  import { Logger } from '../../util/logger';
13
13
  import { Security } from '../../util/security';
14
+ import type { ISecurity } from '../../util/security-registry';
14
15
  export default class AMSSDK {
15
16
  options: AMSCheckoutOptions;
16
17
  originOptions: IoptionsParams;
@@ -37,13 +38,20 @@ export default class AMSSDK {
37
38
  scene?: string;
38
39
  }): void;
39
40
  /**
40
- * @description Obtain security SDK through scenario identification
41
+ * @description Obtain security SDK through scenario identification (async-aware)
42
+ * Handles three states: ready, loading, not found
41
43
  */
42
- _getSecuritySDKByProductScene(securityConfig: InitSecurityConfig): Security;
44
+ _getSecuritySDKByProductScene(securityConfig: InitSecurityConfig): ISecurity;
43
45
  /**
44
- * @description New security SDK through scenario identification
46
+ * @description Await security SDK by product scene (async)
47
+ * Returns the Security instance even if currently loading
45
48
  */
46
- _newSecuritySDKByScene(securityConfig: InitSecurityConfig, successCallback?: () => void, failCallback?: (errMsg?: string) => void): Security;
49
+ _awaitSecuritySDKByProductScene(securityConfig: InitSecurityConfig): Promise<Security | undefined>;
50
+ /**
51
+ * @description New security SDK through scenario identification (async-aware)
52
+ * Uses shared SecuritySdkRegistry and triggers ApdidLoader
53
+ */
54
+ _newSecuritySDKByScene(securityConfig: InitSecurityConfig, successCallback?: () => void, failCallback?: (errMsg?: string) => void): void;
47
55
  /**
48
56
  * @description Obtain risk control configuration in local storage
49
57
  */
@@ -28,7 +28,9 @@ import { EnvironmentEnum, modeEnum, networkModeEnum, osTypeEnum, ProductSceneEnu
28
28
  import { checkTimeElapsed, device, EventCenter, getOrSetStorageId, getType, queryParse, safeJson } from "../../util/index";
29
29
  import CallApp from "../../util/intl-callapp/es/main";
30
30
  import { LogConfig, Logger } from "../../util/logger";
31
- import { getSecurityConfigStorageKey, getSecurityHost, getSecurityScene, Security, SecurityRegionEnum } from "../../util/security";
31
+ import { getSecurityConfigStorageKey, getSecurityHost, getSecurityScene, Security, SecurityRegionEnum, mapEnvironment } from "../../util/security";
32
+ import { SecuritySdkRegistry } from "../../util/security-registry";
33
+ import { ApdidLoader } from "../../util/jshield-apdid";
32
34
  import { compareVersion } from "../../util/versionCompare";
33
35
  import { BusManager, BusMessage } from "../bus";
34
36
  import PreloadHelper from "../../foundation/utils/preload_helper";
@@ -166,15 +168,44 @@ var AMSSDK = /*#__PURE__*/function () {
166
168
  }, {
167
169
  productScene: product
168
170
  }).send();
169
- var sdk = this._getSecuritySDKByProductScene({
170
- product: product || scene
171
- });
172
- if (sdk) {
173
- console.log('[web-sdk] skip init security sdk because it is already loaded');
174
- return;
171
+ var effectiveProduct = product || scene;
172
+ var storage = this.getSecurityConfigStorage(effectiveProduct);
173
+ var securityScene = storage.scene || getSecurityScene(effectiveProduct);
174
+
175
+ // Check shared registry for all states
176
+ var registryEntry = SecuritySdkRegistry.get(securityScene);
177
+ if (registryEntry) {
178
+ if (registryEntry.status === 'ready') {
179
+ console.log('[web-sdk] skip init security sdk because it is already loaded');
180
+ this.logger.logInfo({
181
+ title: 'sdk_event_securitySdkPreInitSuccess'
182
+ }, {
183
+ productScene: product
184
+ }).send();
185
+ return;
186
+ }
187
+ if (registryEntry.status === 'loading') {
188
+ console.log('[web-sdk] security sdk is already loading, waiting...');
189
+ registryEntry.loadingPromise.then(function () {
190
+ _this.logger.logInfo({
191
+ title: 'sdk_event_securitySdkPreInitSuccess'
192
+ }, {
193
+ productScene: product
194
+ }).send();
195
+ }).catch(function (err) {
196
+ _this.logger.logError({
197
+ title: 'sdk_error_securitySdkInitFailed',
198
+ msg: err === null || err === void 0 ? void 0 : err.message
199
+ }, {
200
+ productScene: product,
201
+ sign: 'Active initialization'
202
+ }).send();
203
+ });
204
+ return;
205
+ }
175
206
  }
176
207
  this._newSecuritySDKByScene({
177
- product: product || scene,
208
+ product: effectiveProduct,
178
209
  region: SecurityRegionEnum.SG
179
210
  }, function () {
180
211
  _this.logger.logInfo({
@@ -193,13 +224,27 @@ var AMSSDK = /*#__PURE__*/function () {
193
224
  });
194
225
  }
195
226
  /**
196
- * @description Obtain security SDK through scenario identification
227
+ * @description Obtain security SDK through scenario identification (async-aware)
228
+ * Handles three states: ready, loading, not found
197
229
  */
198
230
  }, {
199
231
  key: "_getSecuritySDKByProductScene",
200
232
  value: function _getSecuritySDKByProductScene(securityConfig) {
201
233
  var storage = this.getSecurityConfigStorage(securityConfig.product);
202
234
  var scene = storage.scene || getSecurityScene(securityConfig.product);
235
+
236
+ // First check the shared registry (handles ready/loading/failed states)
237
+ var registryEntry = SecuritySdkRegistry.get(scene);
238
+ if (registryEntry) {
239
+ if (registryEntry.status === 'ready') {
240
+ return registryEntry.instance;
241
+ }
242
+ // Loading or failed - return undefined for backward compatibility
243
+ // Callers should use _awaitSecuritySDKByProductScene for async access
244
+ return undefined;
245
+ }
246
+
247
+ // Fallback: check legacy map and preload helper
203
248
  var securitySdk = this.securitySdkMap.get(scene);
204
249
  if (!securitySdk) {
205
250
  securitySdk = PreloadHelper.getSecuritySdk(scene);
@@ -210,24 +255,105 @@ var AMSSDK = /*#__PURE__*/function () {
210
255
  }
211
256
  return securitySdk;
212
257
  }
258
+
259
+ /**
260
+ * @description Await security SDK by product scene (async)
261
+ * Returns the Security instance even if currently loading
262
+ */
263
+ }, {
264
+ key: "_awaitSecuritySDKByProductScene",
265
+ value: (function () {
266
+ var _awaitSecuritySDKByProductScene2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(securityConfig) {
267
+ var storage, scene, instance;
268
+ return _regeneratorRuntime().wrap(function _callee$(_context) {
269
+ while (1) switch (_context.prev = _context.next) {
270
+ case 0:
271
+ storage = this.getSecurityConfigStorage(securityConfig.product);
272
+ scene = storage.scene || getSecurityScene(securityConfig.product);
273
+ _context.next = 4;
274
+ return SecuritySdkRegistry.getInstance(scene);
275
+ case 4:
276
+ instance = _context.sent;
277
+ return _context.abrupt("return", instance);
278
+ case 6:
279
+ case "end":
280
+ return _context.stop();
281
+ }
282
+ }, _callee, this);
283
+ }));
284
+ function _awaitSecuritySDKByProductScene(_x) {
285
+ return _awaitSecuritySDKByProductScene2.apply(this, arguments);
286
+ }
287
+ return _awaitSecuritySDKByProductScene;
288
+ }()
213
289
  /**
214
- * @description New security SDK through scenario identification
290
+ * @description New security SDK through scenario identification (async-aware)
291
+ * Uses shared SecuritySdkRegistry and triggers ApdidLoader
215
292
  */
293
+ )
216
294
  }, {
217
295
  key: "_newSecuritySDKByScene",
218
296
  value: function _newSecuritySDKByScene(securityConfig, successCallback, failCallback) {
297
+ var _this$options2;
219
298
  var storage = this.getSecurityConfigStorage(securityConfig.product);
220
299
  var scene = storage.scene || getSecurityScene(securityConfig.product);
221
300
  var h5gateway = storage.h5gateway || getSecurityHost(securityConfig.region);
301
+
302
+ // Check if already exists in registry (avoid duplicates)
303
+ var existingEntry = SecuritySdkRegistry.get(scene);
304
+ if (existingEntry) {
305
+ if (existingEntry.status === 'ready') {
306
+ successCallback && successCallback();
307
+ return;
308
+ }
309
+ if (existingEntry.status === 'loading') {
310
+ // Wait for existing loading to complete
311
+ existingEntry.loadingPromise.then(function () {
312
+ successCallback && successCallback();
313
+ }).catch(function (err) {
314
+ failCallback && failCallback(err === null || err === void 0 ? void 0 : err.message);
315
+ });
316
+ return;
317
+ }
318
+ // failed status - allow retry by proceeding below
319
+ }
320
+
321
+ // 非阻塞调度 ApdidLoader 加载,不阻塞 SDK 初始化
322
+ // Security 内部的 ensureApdidLoaded() 会在需要 token 时按需等待加载完成
323
+ var apdidEnv = mapEnvironment((_this$options2 = this.options) === null || _this$options2 === void 0 || (_this$options2 = _this$options2.env) === null || _this$options2 === void 0 ? void 0 : _this$options2.environment);
324
+ var loader = ApdidLoader.getInstance();
325
+ loader.scheduleLoad({
326
+ environment: apdidEnv
327
+ });
222
328
  try {
329
+ var _this$options3;
330
+ var environment = (_this$options3 = this.options) === null || _this$options3 === void 0 || (_this$options3 = _this$options3.env) === null || _this$options3 === void 0 ? void 0 : _this$options3.environment;
223
331
  var securitySdk = new Security({
224
332
  scene: scene,
225
- h5gateway: h5gateway
333
+ h5gateway: h5gateway,
334
+ environment: environment
335
+ });
336
+
337
+ // Create loading promise and register in registry
338
+ var loadingPromise = new Promise(function (resolveLoading, rejectLoading) {
339
+ securitySdk.initSecurity(function () {
340
+ SecuritySdkRegistry.setReady(scene, securitySdk);
341
+ successCallback && successCallback();
342
+ resolveLoading(securitySdk);
343
+ }, function (msg) {
344
+ SecuritySdkRegistry.setFailed(scene, new Error(msg || 'Security init failed'));
345
+ failCallback && failCallback(msg);
346
+ rejectLoading(new Error(msg || 'Security init failed'));
347
+ });
226
348
  });
349
+
350
+ // Register as loading in the shared registry
351
+ SecuritySdkRegistry.setLoading(scene, loadingPromise);
352
+
353
+ // Also keep reference in the legacy map for backward compatibility
227
354
  this.securitySdkMap.set(scene, securitySdk);
228
- securitySdk.initSecurity(successCallback, failCallback);
229
- return securitySdk;
230
355
  } catch (error) {
356
+ SecuritySdkRegistry.setFailed(scene, new Error(error === null || error === void 0 ? void 0 : error.toString()));
231
357
  failCallback && failCallback(error === null || error === void 0 ? void 0 : error.toString());
232
358
  }
233
359
  }
@@ -333,17 +459,17 @@ var AMSSDK = /*#__PURE__*/function () {
333
459
  if (options !== null && options !== void 0 && options.onBeforeSubmit) {
334
460
  if (typeof (options === null || options === void 0 ? void 0 : options.onBeforeSubmit) !== 'function') throw new Error(ERRORMESSAGE.INIT_PARAMETER_ERROR.EVENT_ERROR.message);
335
461
  this._overrideSubscription(EVENT.beforeSubmit.name, /*#__PURE__*/function () {
336
- var _ref2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(payload) {
462
+ var _ref2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(payload) {
337
463
  var eventCallbackId, res;
338
- return _regeneratorRuntime().wrap(function _callee$(_context) {
339
- while (1) switch (_context.prev = _context.next) {
464
+ return _regeneratorRuntime().wrap(function _callee2$(_context2) {
465
+ while (1) switch (_context2.prev = _context2.next) {
340
466
  case 0:
341
467
  eventCallbackId = uuid();
342
- _context.prev = 1;
343
- _context.next = 4;
468
+ _context2.prev = 1;
469
+ _context2.next = 4;
344
470
  return options.onBeforeSubmit(payload);
345
471
  case 4:
346
- res = _context.sent;
472
+ res = _context2.sent;
347
473
  _this2._componentApp.dispatchToApp({
348
474
  context: {
349
475
  event: EVENT.beforeSubmitDone.name,
@@ -351,11 +477,11 @@ var AMSSDK = /*#__PURE__*/function () {
351
477
  data: res
352
478
  }
353
479
  });
354
- _context.next = 12;
480
+ _context2.next = 12;
355
481
  break;
356
482
  case 8:
357
- _context.prev = 8;
358
- _context.t0 = _context["catch"](1);
483
+ _context2.prev = 8;
484
+ _context2.t0 = _context2["catch"](1);
359
485
  _this2._componentApp.dispatchToApp({
360
486
  context: {
361
487
  event: EVENT.beforeSubmitDone.name,
@@ -367,15 +493,15 @@ var AMSSDK = /*#__PURE__*/function () {
367
493
  });
368
494
  _this2.logger.logError({
369
495
  title: 'sdk_error_before_submit',
370
- msg: JSON.stringify(_context.t0)
496
+ msg: JSON.stringify(_context2.t0)
371
497
  }).send();
372
498
  case 12:
373
499
  case "end":
374
- return _context.stop();
500
+ return _context2.stop();
375
501
  }
376
- }, _callee, null, [[1, 8]]);
502
+ }, _callee2, null, [[1, 8]]);
377
503
  }));
378
- return function (_x) {
504
+ return function (_x2) {
379
505
  return _ref2.apply(this, arguments);
380
506
  };
381
507
  }(), EVENT.beforeSubmit.uniqueKey);
@@ -1,10 +1,9 @@
1
1
  import { DeviceIdParameter, IoptionsParams } from '../../../types';
2
2
  import { PaymentContext, SDKMetaData, Service } from '../../index';
3
- import { Security } from './security';
4
3
  export declare class SecurityService implements Service {
5
4
  private logger;
6
5
  private productScene;
7
- static securitySdkMap: Map<string, Security>;
6
+ private environment?;
8
7
  init(initOptions: IoptionsParams, instanceId: string, sdkMetaData: SDKMetaData): void;
9
8
  update(paymentContext: PaymentContext): void;
10
9
  destroy(): void;
@@ -14,11 +13,17 @@ export declare class SecurityService implements Service {
14
13
  private _initSecurity;
15
14
  private logDeviceId;
16
15
  /**
17
- * @description Obtain security SDK through scenario identification
16
+ * Get the scene string from product enum
17
+ */
18
+ private _getSceneByProduct;
19
+ /**
20
+ * @description Obtain security SDK through scenario identification (async-aware)
21
+ * Handles three states: ready, loading, not found
18
22
  */
19
23
  private _getSecuritySDKByProductScene;
20
24
  /**
21
- * @description New security SDK through scenario identification
25
+ * @description New security SDK through scenario identification (async)
26
+ * Uses shared SecuritySdkRegistry to avoid duplicate initialization
22
27
  */
23
28
  private _newSecuritySDKByScene;
24
29
  /**