@itwin/core-mobile 4.1.0-dev.7 → 4.1.0-dev.71

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/CHANGELOG.md CHANGED
@@ -1,6 +1,89 @@
1
1
  # Change Log - @itwin/core-mobile
2
2
 
3
- This log was last generated on Tue, 25 Apr 2023 17:50:35 GMT and should not be manually modified.
3
+ This log was last generated on Mon, 24 Jul 2023 12:35:20 GMT and should not be manually modified.
4
+
5
+ ## 4.0.6
6
+ Mon, 24 Jul 2023 05:07:33 GMT
7
+
8
+ _Version update only_
9
+
10
+ ## 4.0.5
11
+ Tue, 18 Jul 2023 12:21:56 GMT
12
+
13
+ _Version update only_
14
+
15
+ ## 4.0.4
16
+ Wed, 12 Jul 2023 15:50:01 GMT
17
+
18
+ _Version update only_
19
+
20
+ ## 4.0.3
21
+ Mon, 03 Jul 2023 15:28:41 GMT
22
+
23
+ _Version update only_
24
+
25
+ ## 4.0.2
26
+ Wed, 21 Jun 2023 22:04:43 GMT
27
+
28
+ _Version update only_
29
+
30
+ ## 4.0.1
31
+ Wed, 21 Jun 2023 20:29:13 GMT
32
+
33
+ _Version update only_
34
+
35
+ ## 4.0.0
36
+ Mon, 22 May 2023 15:34:14 GMT
37
+
38
+ ### Updates
39
+
40
+ - Fix mobile getAccessToken error handling
41
+ - React to IModelApp.rpcInterfaces and BentleyCloudRpcManager changes.
42
+ - Update to eslint@8
43
+ - Drop Node 12 and Node 14.
44
+ - Drop Node 16 support.
45
+ - Removed 'deep-assign', 'qs' dependencies.
46
+ - Mobile backend access token fixes
47
+ - Stopped regsitering any rpcs by default
48
+ - Queue up pending messages until reconnected in foreground.
49
+
50
+ ## 3.7.11
51
+ Tue, 11 Jul 2023 17:17:21 GMT
52
+
53
+ _Version update only_
54
+
55
+ ## 3.7.10
56
+ Wed, 05 Jul 2023 13:41:21 GMT
57
+
58
+ _Version update only_
59
+
60
+ ## 3.7.9
61
+ Tue, 20 Jun 2023 12:51:02 GMT
62
+
63
+ _Version update only_
64
+
65
+ ## 3.7.8
66
+ Thu, 01 Jun 2023 17:00:39 GMT
67
+
68
+ _Version update only_
69
+
70
+ ## 3.7.7
71
+ Wed, 24 May 2023 17:27:09 GMT
72
+
73
+ _Version update only_
74
+
75
+ ## 3.7.6
76
+ Mon, 15 May 2023 18:23:41 GMT
77
+
78
+ _Version update only_
79
+
80
+ ## 3.7.5
81
+ Thu, 04 May 2023 19:43:18 GMT
82
+
83
+ ### Updates
84
+
85
+ - Mobile backend access token fixes
86
+ - Queue up pending messages until reconnected in foreground.
4
87
 
5
88
  ## 3.7.4
6
89
  Tue, 25 Apr 2023 17:50:35 GMT
@@ -40,7 +40,7 @@ class MobileDevice {
40
40
  }
41
41
  exports.MobileDevice = MobileDevice;
42
42
  class MobileAppHandler extends core_backend_1.IpcHandler {
43
- get channelName() { return MobileAppChannel_1.mobileAppChannel; }
43
+ get channelName() { return MobileAppChannel_1.mobileAppStrings.mobileAppChannel; }
44
44
  async reconnect(connection) {
45
45
  MobileHost.reconnect(connection);
46
46
  }
@@ -55,7 +55,7 @@ class MobileHost {
55
55
  static get device() { return this._device; }
56
56
  /** Send a notification to the MobileApp connected to this MobileHost. */
57
57
  static notifyMobileFrontend(methodName, ...args) {
58
- return core_backend_1.IpcHost.send(MobileAppChannel_1.mobileAppNotify, methodName, ...args);
58
+ return core_backend_1.IpcHost.send(MobileAppChannel_1.mobileAppStrings.mobileAppNotify, methodName, ...args);
59
59
  }
60
60
  /** @internal */
61
61
  static reconnect(connection) {
@@ -1 +1 @@
1
- {"version":3,"file":"MobileHost.js","sourceRoot":"","sources":["../../../src/backend/MobileHost.ts"],"names":[],"mappings":";AAAA;;;+FAG+F;;;AAE/F,sDAA4E;AAC5E,sDAAsF;AACtF,oDAAiF;AACjF,2DAAwF;AAExF,iEAA+E;AAE/E,iEAA8D;AAC9D,6EAA0E;AAC1E,uDAAmD;AAwBnD,YAAY;AACZ,MAAsB,YAAY;IACzB,IA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D,MAAM,yBAAU,CAAC,OAAO,CAAC,EAAE,GAAG,GAAG,EAAE,UAAU,EAAE,CAAC,CAAC;QAEjD,IAAI,sBAAO,CAAC,OAAO;YACjB,gBAAgB,CAAC,QAAQ,EAAE,CAAC;QAE9B,MAAM,aAAa,GAAG,GAAG,EAAE,UAAU,EAAE,aAAa,IAAI,EAAE,CAAC;QAE3D,mCAAgB,CAAC,cAAc,CAAC,aAAa,CAAC,CAAC;IACjD,CAAC;;AA1GsB,0BAAe,GAAG,IAAI,sBAAO,EAAE,CAAC;AAChC,+BAAoB,GAAG,IAAI,sBAAO,EAAE,CAAC;AACrC,4BAAiB,GAAG,IAAI,sBAAO,EAAE,CAAC;AAClC,4BAAiB,GAAG,IAAI,sBAAO,EAAE,CAAC;AAClC,0BAAe,GAAG,IAAI,sBAAO,EAAE,CAAC;AAChC,mCAAwB,GAAG,IAAI,sBAAO,EAAiF,CAAC;AARpI,gCAAU","sourcesContent":["/*---------------------------------------------------------------------------------------------\r\n* Copyright (c) Bentley Systems, Incorporated. All rights reserved.\r\n* See LICENSE.md in the project root for license terms and full copyright notice.\r\n*--------------------------------------------------------------------------------------------*/\r\n\r\nimport { AccessToken, BeEvent, BriefcaseStatus } from \"@itwin/core-bentley\";\r\nimport { IpcHandler, IpcHost, NativeHost, NativeHostOpts } from \"@itwin/core-backend\";\r\nimport { IpcWebSocketBackend, RpcInterfaceDefinition } from \"@itwin/core-common\";\r\nimport { CancelRequest, DownloadFailed, UserCancelledError } from \"./MobileFileHandler\";\r\nimport { ProgressCallback } from \"./Request\";\r\nimport { mobileAppChannel, mobileAppNotify } from \"../common/MobileAppChannel\";\r\nimport { BatteryState, DeviceEvents, MobileAppFunctions, MobileNotifications, Orientation } from \"../common/MobileAppProps\";\r\nimport { MobileRpcManager } from \"../common/MobileRpcManager\";\r\nimport { MobileAuthorizationBackend } from \"./MobileAuthorizationBackend\";\r\nimport { setupMobileRpc } from \"./MobileRpcServer\";\r\n\r\n/** @beta */\r\nexport type MobileCompletionCallback = (downloadUrl: string, downloadFileUrl: string, cancelled: boolean, err?: string) => void;\r\n/** @beta */\r\nexport type MobileProgressCallback = (bytesWritten: number, totalBytesWritten: number, totalBytesExpectedToWrite: number) => void;\r\n/** @beta */\r\nexport type MobileCancelCallback = () => boolean;\r\n\r\n/** @beta */\r\nexport interface DownloadTask {\r\n url: string;\r\n downloadPath: string;\r\n isDetached: boolean;\r\n isRunning: boolean;\r\n totalBytes?: number;\r\n doneBytes?: number;\r\n cancelId?: number;\r\n isBackground?: boolean;\r\n cancel?: MobileCancelCallback;\r\n toBackground: () => boolean;\r\n toForeground: () => boolean;\r\n}\r\n\r\n/** @beta */\r\nexport abstract class MobileDevice {\r\n public emit(eventName: DeviceEvents, ...args: any[]) {\r\n switch (eventName) {\r\n case \"memoryWarning\":\r\n MobileHost.onMemoryWarning.raiseEvent(...args);\r\n break;\r\n case \"orientationChanged\":\r\n MobileHost.onOrientationChanged.raiseEvent(...args);\r\n break;\r\n case \"enterForeground\":\r\n MobileHost.onEnterForeground.raiseEvent(...args);\r\n break;\r\n case \"enterBackground\":\r\n MobileHost.onEnterBackground.raiseEvent(...args);\r\n break;\r\n case \"willTerminate\":\r\n MobileHost.onWillTerminate.raiseEvent(...args);\r\n break;\r\n case \"authAccessTokenChanged\":\r\n MobileHost.onAuthAccessTokenChanged.raiseEvent(args[0], args[1]);\r\n break;\r\n }\r\n }\r\n\r\n public abstract getOrientation(): Orientation;\r\n public abstract getBatteryState(): BatteryState;\r\n public abstract getBatteryLevel(): number;\r\n public abstract createDownloadTask(downloadUrl: string, isBackground: boolean, downloadTo: string, completion: MobileCompletionCallback, progress?: MobileProgressCallback): number;\r\n public abstract cancelDownloadTask(cancelId: number): boolean;\r\n public abstract getDownloadTasks(): DownloadTask[];\r\n public abstract resumeDownloadInForeground(requestId: number): boolean;\r\n public abstract resumeDownloadInBackground(requestId: number): boolean;\r\n public abstract reconnect(connection: number): void;\r\n public abstract authGetAccessToken(callback: (accessToken?: string, expirationDate?: string, err?: string) => void): void;\r\n}\r\n\r\nclass MobileAppHandler extends IpcHandler implements MobileAppFunctions {\r\n public get channelName() { return mobileAppChannel; }\r\n public async reconnect(connection: number) {\r\n MobileHost.reconnect(connection);\r\n }\r\n public async getAccessToken() {\r\n return MobileHost.authGetAccessToken();\r\n }\r\n}\r\n\r\n/** @beta */\r\nexport interface MobileHostOpts extends NativeHostOpts {\r\n mobileHost?: {\r\n device?: MobileDevice;\r\n /** list of RPC interface definitions to register */\r\n rpcInterfaces?: RpcInterfaceDefinition[];\r\n };\r\n}\r\n\r\n/**\r\n * @beta\r\n */\r\nexport class MobileHost {\r\n private static _device?: MobileDevice;\r\n public static get device() { return this._device!; }\r\n public static readonly onMemoryWarning = new BeEvent();\r\n public static readonly onOrientationChanged = new BeEvent();\r\n public static readonly onEnterForeground = new BeEvent();\r\n public static readonly onEnterBackground = new BeEvent();\r\n public static readonly onWillTerminate = new BeEvent();\r\n public static readonly onAuthAccessTokenChanged = new BeEvent<(accessToken: string | undefined, expirationDate: string | undefined) => void>();\r\n\r\n /** Send a notification to the MobileApp connected to this MobileHost. */\r\n public static notifyMobileFrontend<T extends keyof MobileNotifications>(methodName: T, ...args: Parameters<MobileNotifications[T]>) {\r\n return IpcHost.send(mobileAppNotify, methodName, ...args);\r\n }\r\n\r\n /** @internal */\r\n public static reconnect(connection: number) {\r\n this.device.reconnect(connection);\r\n }\r\n\r\n /** @internal */\r\n public static async authGetAccessToken() {\r\n return new Promise<[AccessToken, string]>((resolve, reject) => {\r\n this.device.authGetAccessToken((tokenString?: AccessToken, expirationDate?: string, error?: string) => {\r\n if (error) {\r\n reject(error);\r\n } else {\r\n resolve([tokenString ?? \"\", expirationDate ?? \"\"]);\r\n }\r\n });\r\n });\r\n }\r\n\r\n /** @internal */\r\n public static async downloadFile(downloadUrl: string, downloadTo: string, progress?: ProgressCallback, cancelRequest?: CancelRequest): Promise<void> {\r\n return new Promise<void>((resolve, reject) => {\r\n\r\n let progressCb: MobileProgressCallback | undefined;\r\n let lastReportedOn = Date.now();\r\n const minTimeBeforeReportingProgress = 1000;\r\n if (progress) {\r\n progressCb = (_bytesWritten: number, totalBytesWritten: number, totalBytesExpectedToWrite: number) => {\r\n const currentTime = Date.now();\r\n const timeSinceLastEvent = currentTime - lastReportedOn;\r\n // report all event for last 5 Mbs so we never miss 100% progress event\r\n const lastEvent = (totalBytesExpectedToWrite - totalBytesWritten) < 1024 * 1024 * 5;\r\n if (timeSinceLastEvent < minTimeBeforeReportingProgress && !lastEvent)\r\n return;\r\n\r\n lastReportedOn = currentTime;\r\n const percent = Number((100 * (totalBytesWritten / totalBytesExpectedToWrite)).toFixed(2));\r\n progress({ total: totalBytesExpectedToWrite, loaded: totalBytesWritten, percent });\r\n };\r\n }\r\n const requestId = this.device.createDownloadTask(downloadUrl, false, downloadTo, (_downloadUrl: string, _downloadFileUrl: string, cancelled: boolean, err?: string) => {\r\n if (cancelled)\r\n reject(new UserCancelledError(BriefcaseStatus.DownloadCancelled, \"User cancelled download\"));\r\n else if (err)\r\n reject(new DownloadFailed(400, \"Download failed\"));\r\n else\r\n resolve();\r\n }, progressCb);\r\n if (cancelRequest) {\r\n // eslint-disable-next-line @typescript-eslint/unbound-method\r\n cancelRequest.cancel = () => this.device.cancelDownloadTask(requestId);\r\n }\r\n });\r\n }\r\n\r\n public static get isValid() { return undefined !== this._device; }\r\n\r\n /** Start the backend of a mobile app. */\r\n public static async startup(opt?: MobileHostOpts): Promise<void> {\r\n const authorizationClient = new MobileAuthorizationBackend();\r\n if (!this.isValid) {\r\n this._device = opt?.mobileHost?.device ?? new (MobileDevice as any)();\r\n // set global device interface.\r\n (global as any).__iTwinJsNativeBridge = this._device;\r\n this.onMemoryWarning.addListener(() => {\r\n MobileHost.notifyMobileFrontend(\"notifyMemoryWarning\");\r\n });\r\n this.onOrientationChanged.addListener(() => {\r\n MobileHost.notifyMobileFrontend(\"notifyOrientationChanged\");\r\n });\r\n this.onWillTerminate.addListener(() => {\r\n MobileHost.notifyMobileFrontend(\"notifyWillTerminate\");\r\n });\r\n this.onAuthAccessTokenChanged.addListener((accessToken: string | undefined, expirationDate: string | undefined) => {\r\n authorizationClient.setAccessToken(accessToken, expirationDate);\r\n MobileHost.notifyMobileFrontend(\"notifyAuthAccessTokenChanged\", accessToken, expirationDate);\r\n });\r\n\r\n // following will provide impl for device specific api.\r\n setupMobileRpc();\r\n }\r\n\r\n const socket = opt?.ipcHost?.socket ?? new IpcWebSocketBackend();\r\n opt = { ...opt, mobileHost: { ...opt?.mobileHost }, ipcHost: { ...opt?.ipcHost, socket } };\r\n\r\n const iModelHost = opt?.iModelHost ?? {};\r\n iModelHost.authorizationClient = authorizationClient;\r\n await NativeHost.startup({ ...opt, iModelHost });\r\n\r\n if (IpcHost.isValid)\r\n MobileAppHandler.register();\r\n\r\n const rpcInterfaces = opt?.mobileHost?.rpcInterfaces ?? [];\r\n\r\n MobileRpcManager.initializeImpl(rpcInterfaces);\r\n }\r\n}\r\n"]}
1
+ {"version":3,"file":"MobileHost.js","sourceRoot":"","sources":["../../../src/backend/MobileHost.ts"],"names":[],"mappings":";AAAA;;;+FAG+F;;;AAE/F,sDAA4E;AAC5E,sDAAsF;AACtF,oDAAiF;AACjF,2DAAwF;AAExF,iEAA8D;AAE9D,iEAA8D;AAC9D,6EAA0E;AAC1E,uDAAmD;AAwBnD,YAAY;AACZ,MAAsB,YAAY;IACzB,IAAI,CAAC,SAAuB,EAAE,GAAG,IAAW;QACjD,QAAQ,SAAS,EAAE;YACjB,KAAK,eAAe;gBAClB,UAAU,CAAC,eAAe,CAAC,UAAU,CAAC,GAAG,IAAI,CAAC,CAAC;gBAC/C,MAAM;YACR,KAAK,oBAAoB;gBACvB,UAAU,CAAC,oBAAoB,CAAC,UAAU,CAAC,GAAG,IAAI,CAAC,CAAC;gBACpD,MAAM;YACR,KAAK,iBAAiB;gBACpB,UAAU,CAAC,iBAAiB,CAAC,UAAU,CAAC,GAAG,IAAI,CAAC,CAAC;gBACjD,MA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CAAC;AAChC,+BAAoB,GAAG,IAAI,sBAAO,EAAE,CAAC;AACrC,4BAAiB,GAAG,IAAI,sBAAO,EAAE,CAAC;AAClC,4BAAiB,GAAG,IAAI,sBAAO,EAAE,CAAC;AAClC,0BAAe,GAAG,IAAI,sBAAO,EAAE,CAAC;AAChC,mCAAwB,GAAG,IAAI,sBAAO,EAAiF,CAAC;AARpI,gCAAU","sourcesContent":["/*---------------------------------------------------------------------------------------------\r\n* Copyright (c) Bentley Systems, Incorporated. All rights reserved.\r\n* See LICENSE.md in the project root for license terms and full copyright notice.\r\n*--------------------------------------------------------------------------------------------*/\r\n\r\nimport { AccessToken, BeEvent, BriefcaseStatus } from \"@itwin/core-bentley\";\r\nimport { IpcHandler, IpcHost, NativeHost, NativeHostOpts } from \"@itwin/core-backend\";\r\nimport { IpcWebSocketBackend, RpcInterfaceDefinition } from \"@itwin/core-common\";\r\nimport { CancelRequest, DownloadFailed, UserCancelledError } from \"./MobileFileHandler\";\r\nimport { ProgressCallback } from \"./Request\";\r\nimport { mobileAppStrings } from \"../common/MobileAppChannel\";\r\nimport { BatteryState, DeviceEvents, MobileAppFunctions, MobileNotifications, Orientation } from \"../common/MobileAppProps\";\r\nimport { MobileRpcManager } from \"../common/MobileRpcManager\";\r\nimport { MobileAuthorizationBackend } from \"./MobileAuthorizationBackend\";\r\nimport { setupMobileRpc } from \"./MobileRpcServer\";\r\n\r\n/** @beta */\r\nexport type MobileCompletionCallback = (downloadUrl: string, downloadFileUrl: string, cancelled: boolean, err?: string) => void;\r\n/** @beta */\r\nexport type MobileProgressCallback = (bytesWritten: number, totalBytesWritten: number, totalBytesExpectedToWrite: number) => void;\r\n/** @beta */\r\nexport type MobileCancelCallback = () => boolean;\r\n\r\n/** @beta */\r\nexport interface DownloadTask {\r\n url: string;\r\n downloadPath: string;\r\n isDetached: boolean;\r\n isRunning: boolean;\r\n totalBytes?: number;\r\n doneBytes?: number;\r\n cancelId?: number;\r\n isBackground?: boolean;\r\n cancel?: MobileCancelCallback;\r\n toBackground: () => boolean;\r\n toForeground: () => boolean;\r\n}\r\n\r\n/** @beta */\r\nexport abstract class MobileDevice {\r\n public emit(eventName: DeviceEvents, ...args: any[]) {\r\n switch (eventName) {\r\n case \"memoryWarning\":\r\n MobileHost.onMemoryWarning.raiseEvent(...args);\r\n break;\r\n case \"orientationChanged\":\r\n MobileHost.onOrientationChanged.raiseEvent(...args);\r\n break;\r\n case \"enterForeground\":\r\n MobileHost.onEnterForeground.raiseEvent(...args);\r\n break;\r\n case \"enterBackground\":\r\n MobileHost.onEnterBackground.raiseEvent(...args);\r\n break;\r\n case \"willTerminate\":\r\n MobileHost.onWillTerminate.raiseEvent(...args);\r\n break;\r\n case \"authAccessTokenChanged\":\r\n MobileHost.onAuthAccessTokenChanged.raiseEvent(args[0], args[1]);\r\n break;\r\n }\r\n }\r\n\r\n public abstract getOrientation(): Orientation;\r\n public abstract getBatteryState(): BatteryState;\r\n public abstract getBatteryLevel(): number;\r\n public abstract createDownloadTask(downloadUrl: string, isBackground: boolean, downloadTo: string, completion: MobileCompletionCallback, progress?: MobileProgressCallback): number;\r\n public abstract cancelDownloadTask(cancelId: number): boolean;\r\n public abstract getDownloadTasks(): DownloadTask[];\r\n public abstract resumeDownloadInForeground(requestId: number): boolean;\r\n public abstract resumeDownloadInBackground(requestId: number): boolean;\r\n public abstract reconnect(connection: number): void;\r\n public abstract authGetAccessToken(callback: (accessToken?: string, expirationDate?: string, err?: string) => void): void;\r\n}\r\n\r\nclass MobileAppHandler extends IpcHandler implements MobileAppFunctions {\r\n public get channelName() { return mobileAppStrings.mobileAppChannel; }\r\n public async reconnect(connection: number) {\r\n MobileHost.reconnect(connection);\r\n }\r\n public async getAccessToken() {\r\n return MobileHost.authGetAccessToken();\r\n }\r\n}\r\n\r\n/** @beta */\r\nexport interface MobileHostOpts extends NativeHostOpts {\r\n mobileHost?: {\r\n device?: MobileDevice;\r\n /** list of RPC interface definitions to register */\r\n rpcInterfaces?: RpcInterfaceDefinition[];\r\n };\r\n}\r\n\r\n/**\r\n * @beta\r\n */\r\nexport class MobileHost {\r\n private static _device?: MobileDevice;\r\n public static get device() { return this._device!; }\r\n public static readonly onMemoryWarning = new BeEvent();\r\n public static readonly onOrientationChanged = new BeEvent();\r\n public static readonly onEnterForeground = new BeEvent();\r\n public static readonly onEnterBackground = new BeEvent();\r\n public static readonly onWillTerminate = new BeEvent();\r\n public static readonly onAuthAccessTokenChanged = new BeEvent<(accessToken: string | undefined, expirationDate: string | undefined) => void>();\r\n\r\n /** Send a notification to the MobileApp connected to this MobileHost. */\r\n public static notifyMobileFrontend<T extends keyof MobileNotifications>(methodName: T, ...args: Parameters<MobileNotifications[T]>) {\r\n return IpcHost.send(mobileAppStrings.mobileAppNotify, methodName, ...args);\r\n }\r\n\r\n /** @internal */\r\n public static reconnect(connection: number) {\r\n this.device.reconnect(connection);\r\n }\r\n\r\n /** @internal */\r\n public static async authGetAccessToken() {\r\n return new Promise<[AccessToken, string]>((resolve, reject) => {\r\n this.device.authGetAccessToken((tokenString?: AccessToken, expirationDate?: string, error?: string) => {\r\n if (error) {\r\n reject(error);\r\n } else {\r\n resolve([tokenString ?? \"\", expirationDate ?? \"\"]);\r\n }\r\n });\r\n });\r\n }\r\n\r\n /** @internal */\r\n public static async downloadFile(downloadUrl: string, downloadTo: string, progress?: ProgressCallback, cancelRequest?: CancelRequest): Promise<void> {\r\n return new Promise<void>((resolve, reject) => {\r\n\r\n let progressCb: MobileProgressCallback | undefined;\r\n let lastReportedOn = Date.now();\r\n const minTimeBeforeReportingProgress = 1000;\r\n if (progress) {\r\n progressCb = (_bytesWritten: number, totalBytesWritten: number, totalBytesExpectedToWrite: number) => {\r\n const currentTime = Date.now();\r\n const timeSinceLastEvent = currentTime - lastReportedOn;\r\n // report all event for last 5 Mbs so we never miss 100% progress event\r\n const lastEvent = (totalBytesExpectedToWrite - totalBytesWritten) < 1024 * 1024 * 5;\r\n if (timeSinceLastEvent < minTimeBeforeReportingProgress && !lastEvent)\r\n return;\r\n\r\n lastReportedOn = currentTime;\r\n const percent = Number((100 * (totalBytesWritten / totalBytesExpectedToWrite)).toFixed(2));\r\n progress({ total: totalBytesExpectedToWrite, loaded: totalBytesWritten, percent });\r\n };\r\n }\r\n const requestId = this.device.createDownloadTask(downloadUrl, false, downloadTo, (_downloadUrl: string, _downloadFileUrl: string, cancelled: boolean, err?: string) => {\r\n if (cancelled)\r\n reject(new UserCancelledError(BriefcaseStatus.DownloadCancelled, \"User cancelled download\"));\r\n else if (err)\r\n reject(new DownloadFailed(400, \"Download failed\"));\r\n else\r\n resolve();\r\n }, progressCb);\r\n if (cancelRequest) {\r\n // eslint-disable-next-line @typescript-eslint/unbound-method\r\n cancelRequest.cancel = () => this.device.cancelDownloadTask(requestId);\r\n }\r\n });\r\n }\r\n\r\n public static get isValid() { return undefined !== this._device; }\r\n\r\n /** Start the backend of a mobile app. */\r\n public static async startup(opt?: MobileHostOpts): Promise<void> {\r\n const authorizationClient = new MobileAuthorizationBackend();\r\n if (!this.isValid) {\r\n this._device = opt?.mobileHost?.device ?? new (MobileDevice as any)();\r\n // set global device interface.\r\n (global as any).__iTwinJsNativeBridge = this._device;\r\n this.onMemoryWarning.addListener(() => {\r\n MobileHost.notifyMobileFrontend(\"notifyMemoryWarning\");\r\n });\r\n this.onOrientationChanged.addListener(() => {\r\n MobileHost.notifyMobileFrontend(\"notifyOrientationChanged\");\r\n });\r\n this.onWillTerminate.addListener(() => {\r\n MobileHost.notifyMobileFrontend(\"notifyWillTerminate\");\r\n });\r\n this.onAuthAccessTokenChanged.addListener((accessToken: string | undefined, expirationDate: string | undefined) => {\r\n authorizationClient.setAccessToken(accessToken, expirationDate);\r\n MobileHost.notifyMobileFrontend(\"notifyAuthAccessTokenChanged\", accessToken, expirationDate);\r\n });\r\n\r\n // following will provide impl for device specific api.\r\n setupMobileRpc();\r\n }\r\n\r\n const socket = opt?.ipcHost?.socket ?? new IpcWebSocketBackend();\r\n opt = { ...opt, mobileHost: { ...opt?.mobileHost }, ipcHost: { ...opt?.ipcHost, socket } };\r\n\r\n const iModelHost = opt?.iModelHost ?? {};\r\n iModelHost.authorizationClient = authorizationClient;\r\n await NativeHost.startup({ ...opt, iModelHost });\r\n\r\n if (IpcHost.isValid)\r\n MobileAppHandler.register();\r\n\r\n const rpcInterfaces = opt?.mobileHost?.rpcInterfaces ?? [];\r\n\r\n MobileRpcManager.initializeImpl(rpcInterfaces);\r\n }\r\n}\r\n"]}
@@ -163,7 +163,7 @@ async function request(url, options) {
163
163
  }
164
164
  });
165
165
  }
166
- const errorCallback = options.errorCallback ? options.errorCallback : ResponseError.parse;
166
+ const errorCallback = options.errorCallback ? options.errorCallback : (response) => ResponseError.parse(response);
167
167
  if (options.readStream) {
168
168
  if (typeof window !== "undefined")
169
169
  throw new Error("This option is not supported on browsers");
@@ -1 +1 @@
1
- {"version":3,"file":"Request.js","sourceRoot":"","sources":["../../../src/backend/Request.ts"],"names":[],"mappings":";;;AAAA;;;+FAG+F;AAC/F;;GAEG;AACH,4BAA4B;AAE5B,wCAAwC;AACxC,sDAAsG;AAEtG,MAAM,cAAc,GAAW,6BAA6B,CAAC;AAE7D,gBAAgB;AACH,QAAA,mBAAmB,GAAG,kBAAkB,CAAC;AAoEtD;;GAEG;AACH,MAAa,aAAc,SAAQ,2BAAY;IAI7C,YAAmB,WAAgC,EAAE,OAAgB,EAAE,WAAiC;QACtG,KAAK,CAAC,WAAW,EAAE,OAAO,EAAE,WAAW,CAAC,CAAC;IAC3C,CAAC;IAED;;;;;OAKG;IACI,MAAM,CAAC,KAAK,CAAC,QAAa,EAAE,GAAG,GAAG,IAAI;QAC3C,MAAM,KAAK,GAAG,IAAI,aAAa,CAAC,aAAa,CAAC,eAAe,CAAC,QAAQ,CAAC,UAAU,CAAC,CAAC,CAAC;QACpF,IAAI,CAAC,QAAQ,EAAE;YACb,KAAK,CAAC,OAAO,GAAG,+BAA+B,CAAC;YAChD,OAAO,KAAK,CAAC;SACd;QAED,IAAI,QAA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AAC;iBACpB,EAAE,CAAC,OAAO,EAAE,CAAC,KAAU,EAAE,EAAE;gBAC1B,MAAM,WAAW,GAAG,aAAa,CAAC,KAAK,CAAC,CAAC;gBACzC,MAAM,CAAC,WAAW,CAAC,CAAC;YACtB,CAAC,CAAC;iBACD,EAAE,CAAC,QAAQ,EAAE,GAAG,EAAE;gBACjB,MAAM,WAAW,GAAa;oBAC5B,MAAM,EAAE,GAAG;oBACX,MAAM,EAAE,SAAS;oBACjB,IAAI,EAAE,SAAS;oBACf,IAAI,EAAE,SAAS;iBAChB,CAAC;gBACF,OAAO,CAAC,WAAW,CAAC,CAAC;YACvB,CAAC,CAAC,CAAC;QACP,CAAC,CAAC,CAAC;KACJ;IAED,0DAA0D;IAE1D;;;;;;MAME;IACF,IAAI;QACF,MAAM,QAAQ,GAAG,MAAM,KAAK,CAAC;QAC7B,MAAM,WAAW,GAAa;YAC5B,IAAI,EAAE,QAAQ,CAAC,IAAI;YACnB,IAAI,EAAE,QAAQ,CAAC,IAAI;YACnB,MAAM,EAAE,QAAQ,CAAC,MAAM;YACvB,MAAM,EAAE,QAAQ,CAAC,MAAM;SACxB,CAAC;QACF,OAAO,WAAW,CAAC;KACpB;IAAC,OAAO,KAAK,EAAE;QACd,MAAM,WAAW,GAAG,aAAa,CAAC,KAAK,CAAC,CAAC;QACzC,MAAM,WAAW,CAAC;KACnB;AACH,CAAC;AAnID,0BAmIC;AAED;;;;GAIG;AACI,KAAK,UAAU,OAAO,CAAC,GAAW;IACvC,MAAM,OAAO,GAAmB;QAC9B,MAAM,EAAE,KAAK;QACb,YAAY,EAAE,MAAM;KACrB,CAAC;IACF,MAAM,IAAI,GAAG,MAAM,OAAO,CAAC,GAAG,EAAE,OAAO,CAAC,CAAC;IACzC,OAAO,IAAI,CAAC,IAAI,CAAC;AACnB,CAAC;AAPD,0BAOC","sourcesContent":["/*---------------------------------------------------------------------------------------------\r\n* Copyright (c) Bentley Systems, Incorporated. All rights reserved.\r\n* See LICENSE.md in the project root for license terms and full copyright notice.\r\n*--------------------------------------------------------------------------------------------*/\r\n/** @packageDocumentation\r\n * @module iTwinServiceClients\r\n */\r\nimport * as _ from \"lodash\";\r\nimport * as https from \"https\";\r\nimport * as sarequest from \"superagent\";\r\nimport { BentleyError, GetMetaDataFunction, HttpStatus, Logger, LogLevel } from \"@itwin/core-bentley\";\r\n\r\nconst loggerCategory: string = \"core-mobile-backend.Request\";\r\n\r\n/** @internal */\r\nexport const requestIdHeaderName = \"X-Correlation-Id\";\r\n\r\n/** @internal */\r\nexport interface RequestQueryStringifyOptions {\r\n delimiter?: string;\r\n encode?: boolean;\r\n}\r\n\r\n/** Option to control the time outs\r\n * Use a short response timeout to detect unresponsive networks quickly, and a long deadline to give time for downloads on slow,\r\n * but reliable, networks. Note that both of these timers limit how long uploads of attached files are allowed to take. Use long\r\n * timeouts if you're uploading files.\r\n * @internal\r\n */\r\nexport interface RequestTimeoutOptions {\r\n /** Sets a deadline (in milliseconds) for the entire request (including all uploads, redirects, server processing time) to complete.\r\n * If the response isn't fully downloaded within that time, the request will be aborted\r\n */\r\n deadline?: number;\r\n\r\n /** Sets maximum time (in milliseconds) to wait for the first byte to arrive from the server, but it does not limit how long the entire\r\n * download can take. Response timeout should be at least few seconds longer than just the time it takes the server to respond, because\r\n * it also includes time to make DNS lookup, TCP/IP and TLS connections, and time to upload request data.\r\n */\r\n response?: number;\r\n}\r\n\r\n/** @internal */\r\nexport interface RequestOptions {\r\n method: string;\r\n headers?: any; // {Mas-App-Guid, Mas-UUid, User-Agent}\r\n body?: any;\r\n responseType?: string;\r\n timeout?: RequestTimeoutOptions; // Optional timeouts. If unspecified, an arbitrary default is setup.\r\n stream?: any; // Optional stream to read the response to/from (only for NodeJs applications)\r\n readStream?: any; // Optional stream to read input from (only for NodeJs applications)\r\n buffer?: any;\r\n parser?: any;\r\n accept?: string;\r\n redirects?: number;\r\n errorCallback?: (response: any) => ResponseError;\r\n retryCallback?: (error: any, response: any) => boolean;\r\n progressCallback?: ProgressCallback;\r\n agent?: https.Agent;\r\n retries?: number;\r\n useCorsProxy?: boolean;\r\n}\r\n\r\n/** Response object if the request was successful. Note that the status within the range of 200-299 are considered as a success.\r\n * @internal\r\n */\r\nexport interface Response {\r\n body: any; // Parsed body of response\r\n text: string | undefined; // Returned for responseType:text\r\n header: any; // Parsed headers of response\r\n status: number; // Status code of response\r\n}\r\n\r\n/** @internal */\r\nexport interface ProgressInfo {\r\n percent?: number;\r\n total?: number;\r\n loaded: number;\r\n}\r\n\r\n/** @internal */\r\nexport type ProgressCallback = (progress: ProgressInfo) => void;\r\n\r\n/** Error object that's thrown/rejected if the Request fails due to a network error, or if the status is *not* in the range of 200-299 (inclusive)\r\n * @internal\r\n */\r\nexport class ResponseError extends BentleyError {\r\n protected _data?: any;\r\n public status?: number;\r\n public description?: string;\r\n public constructor(errorNumber: number | HttpStatus, message?: string, getMetaData?: GetMetaDataFunction) {\r\n super(errorNumber, message, getMetaData);\r\n }\r\n\r\n /**\r\n * Parses error from server's response\r\n * @param response Http response from the server.\r\n * @returns Parsed error.\r\n * @internal\r\n */\r\n public static parse(response: any, log = true): ResponseError {\r\n const error = new ResponseError(ResponseError.parseHttpStatus(response.statusType));\r\n if (!response) {\r\n error.message = \"Couldn't get response object.\";\r\n return error;\r\n }\r\n\r\n if (response.response) {\r\n if (response.response.error) {\r\n error.name = response.response.error.name || error.name;\r\n error.description = response.response.error.message;\r\n }\r\n if (response.response.res) {\r\n error.message = response.response.res.statusMessage;\r\n }\r\n if (response.response.body && Object.keys(response.response.body).length > 0) {\r\n error._data = {};\r\n _.merge(error._data, response.response.body);\r\n } else {\r\n error._data = response.response.text;\r\n }\r\n }\r\n\r\n error.status = response.status || response.statusCode;\r\n error.name = response.code || response.name || error.name;\r\n error.message = error.message || response.message || response.statusMessage;\r\n\r\n if (log)\r\n error.log();\r\n\r\n return error;\r\n }\r\n\r\n /**\r\n * Decides whether request should be retried or not\r\n * @param error Error returned by request\r\n * @param response Response returned by request\r\n * @internal\r\n */\r\n public static shouldRetry(error: any, response: any): boolean {\r\n if (error !== undefined && error !== null) {\r\n if ((error.status === undefined || error.status === null) && (error.res === undefined || error.res === null)) {\r\n return true;\r\n }\r\n }\r\n return (response !== undefined && response.statusType === HttpStatus.ServerError);\r\n }\r\n\r\n /**\r\n * @internal\r\n */\r\n public static parseHttpStatus(statusType: number): HttpStatus {\r\n switch (statusType) {\r\n case 1:\r\n return HttpStatus.Info;\r\n case 2:\r\n return HttpStatus.Success;\r\n case 3:\r\n return HttpStatus.Redirection;\r\n case 4:\r\n return HttpStatus.ClientError;\r\n case 5:\r\n return HttpStatus.ServerError;\r\n default:\r\n return HttpStatus.Success;\r\n }\r\n }\r\n\r\n /**\r\n * @internal\r\n */\r\n public logMessage(): string {\r\n return `${this.status} ${this.name}: ${this.message}`;\r\n }\r\n\r\n /**\r\n * Logs this error\r\n * @internal\r\n */\r\n public log(): void {\r\n Logger.logError(loggerCategory, this.logMessage(), () => this.getMetaData());\r\n }\r\n}\r\n\r\nconst logResponse = (req: sarequest.SuperAgentRequest, startTime: number) => (res: sarequest.Response) => {\r\n const elapsed = new Date().getTime() - startTime;\r\n const elapsedTime = `${elapsed}ms`;\r\n Logger.logTrace(loggerCategory, `${req.method.toUpperCase()} ${res.status} ${req.url} (${elapsedTime})`);\r\n};\r\n\r\n// eslint-disable-next-line @typescript-eslint/promise-function-async\r\nconst logRequest = (req: sarequest.SuperAgentRequest): sarequest.SuperAgentRequest => {\r\n const startTime = new Date().getTime();\r\n return req.on(\"response\", logResponse(req, startTime));\r\n};\r\n\r\n/** Wrapper around making HTTP requests with the specific options.\r\n *\r\n * Usable in both a browser and node based environment.\r\n *\r\n * @param url Server URL to address the request\r\n * @param options Options to pass to the request\r\n * @returns Resolves to the response from the server\r\n * @throws ResponseError if the request fails due to network issues, or if the returned status is *outside* the range of 200-299 (inclusive)\r\n * @internal\r\n */\r\nexport async function request(url: string, options: RequestOptions): Promise<Response> {\r\n let sareq: sarequest.SuperAgentRequest = sarequest(options.method, url);\r\n if (options.retries)\r\n sareq = sareq.retry(options.retries, options.retryCallback);\r\n\r\n if (Logger.isEnabled(loggerCategory, LogLevel.Trace))\r\n sareq = sareq.use(logRequest);\r\n\r\n if (options.headers)\r\n sareq = sareq.set(options.headers);\r\n\r\n Logger.logInfo(loggerCategory, url);\r\n\r\n if (options.accept)\r\n sareq = sareq.accept(options.accept);\r\n\r\n if (options.body)\r\n sareq = sareq.send(options.body);\r\n\r\n if (options.timeout)\r\n sareq = sareq.timeout(options.timeout);\r\n\r\n if (options.responseType)\r\n sareq = sareq.responseType(options.responseType);\r\n\r\n if (options.redirects)\r\n sareq = sareq.redirects(options.redirects);\r\n else\r\n sareq = sareq.redirects(0);\r\n\r\n if (options.buffer)\r\n sareq = sareq.buffer(options.buffer);\r\n\r\n if (options.parser)\r\n sareq = sareq.parse(options.parser);\r\n\r\n /** Default to any globally supplied proxy, unless an agent is specified in this call */\r\n if (options.agent)\r\n sareq = sareq.agent(options.agent);\r\n\r\n if (options.progressCallback) {\r\n sareq = sareq.on(\"progress\", (event: sarequest.ProgressEvent) => {\r\n if (event) {\r\n options.progressCallback!({\r\n loaded: event.loaded,\r\n total: event.total,\r\n percent: event.percent,\r\n });\r\n }\r\n });\r\n }\r\n\r\n const errorCallback = options.errorCallback ? options.errorCallback : ResponseError.parse;\r\n\r\n if (options.readStream) {\r\n if (typeof window !== \"undefined\")\r\n throw new Error(\"This option is not supported on browsers\");\r\n\r\n return new Promise<Response>((resolve, reject) => {\r\n sareq = sareq.type(\"blob\");\r\n options\r\n .readStream\r\n .pipe(sareq)\r\n .on(\"error\", (error: any) => {\r\n const parsedError = errorCallback(error);\r\n reject(parsedError);\r\n })\r\n .on(\"end\", () => {\r\n const retResponse: Response = {\r\n status: 201,\r\n header: undefined,\r\n body: undefined,\r\n text: undefined,\r\n };\r\n resolve(retResponse);\r\n });\r\n });\r\n }\r\n\r\n if (options.stream) {\r\n if (typeof window !== \"undefined\")\r\n throw new Error(\"This option is not supported on browsers\");\r\n\r\n return new Promise<Response>((resolve, reject) => {\r\n sareq\r\n .on(\"response\", (res: any) => {\r\n if (res.statusCode !== 200) {\r\n const parsedError = errorCallback(res);\r\n reject(parsedError);\r\n return;\r\n }\r\n })\r\n .pipe(options.stream)\r\n .on(\"error\", (error: any) => {\r\n const parsedError = errorCallback(error);\r\n reject(parsedError);\r\n })\r\n .on(\"finish\", () => {\r\n const retResponse: Response = {\r\n status: 200,\r\n header: undefined,\r\n body: undefined,\r\n text: undefined,\r\n };\r\n resolve(retResponse);\r\n });\r\n });\r\n }\r\n\r\n // console.log(\"%s %s %s\", url, options.method, queryStr);\r\n\r\n /**\r\n * Note:\r\n * Javascript's fetch returns status.OK if error is between 200-299 inclusive, and doesn't reject in this case.\r\n * Fetch only rejects if there's some network issue (permissions issue or similar)\r\n * Superagent rejects network issues, and errors outside the range of 200-299. We are currently using\r\n * superagent, but may eventually switch to JavaScript's fetch library.\r\n */\r\n try {\r\n const response = await sareq;\r\n const retResponse: Response = {\r\n body: response.body,\r\n text: response.text,\r\n header: response.header,\r\n status: response.status,\r\n };\r\n return retResponse;\r\n } catch (error) {\r\n const parsedError = errorCallback(error);\r\n throw parsedError;\r\n }\r\n}\r\n\r\n/**\r\n * fetch json from HTTP request\r\n * @param url server URL to address the request\r\n * @internal\r\n */\r\nexport async function getJson(url: string): Promise<any> {\r\n const options: RequestOptions = {\r\n method: \"GET\",\r\n responseType: \"json\",\r\n };\r\n const data = await request(url, options);\r\n return data.body;\r\n}\r\n"]}
1
+ {"version":3,"file":"Request.js","sourceRoot":"","sources":["../../../src/backend/Request.ts"],"names":[],"mappings":";;;AAAA;;;+FAG+F;AAC/F;;GAEG;AACH,4BAA4B;AAE5B,wCAAwC;AACxC,sDAAsG;AAEtG,MAAM,cAAc,GAAW,6BAA6B,CAAC;AAE7D,gBAAgB;AACH,QAAA,mBAAmB,GAAG,kBAAkB,CAAC;AAoEtD;;GAEG;AACH,MAAa,aAAc,SAAQ,2BAAY;I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E;QACd,MAAM,WAAW,GAAG,aAAa,CAAC,KAAK,CAAC,CAAC;QACzC,MAAM,WAAW,CAAC;KACnB;AACH,CAAC;AAnID,0BAmIC;AAED;;;;GAIG;AACI,KAAK,UAAU,OAAO,CAAC,GAAW;IACvC,MAAM,OAAO,GAAmB;QAC9B,MAAM,EAAE,KAAK;QACb,YAAY,EAAE,MAAM;KACrB,CAAC;IACF,MAAM,IAAI,GAAG,MAAM,OAAO,CAAC,GAAG,EAAE,OAAO,CAAC,CAAC;IACzC,OAAO,IAAI,CAAC,IAAI,CAAC;AACnB,CAAC;AAPD,0BAOC","sourcesContent":["/*---------------------------------------------------------------------------------------------\r\n* Copyright (c) Bentley Systems, Incorporated. All rights reserved.\r\n* See LICENSE.md in the project root for license terms and full copyright notice.\r\n*--------------------------------------------------------------------------------------------*/\r\n/** @packageDocumentation\r\n * @module iTwinServiceClients\r\n */\r\nimport * as _ from \"lodash\";\r\nimport * as https from \"https\";\r\nimport * as sarequest from \"superagent\";\r\nimport { BentleyError, GetMetaDataFunction, HttpStatus, Logger, LogLevel } from \"@itwin/core-bentley\";\r\n\r\nconst loggerCategory: string = \"core-mobile-backend.Request\";\r\n\r\n/** @internal */\r\nexport const requestIdHeaderName = \"X-Correlation-Id\";\r\n\r\n/** @internal */\r\nexport interface RequestQueryStringifyOptions {\r\n delimiter?: string;\r\n encode?: boolean;\r\n}\r\n\r\n/** Option to control the time outs\r\n * Use a short response timeout to detect unresponsive networks quickly, and a long deadline to give time for downloads on slow,\r\n * but reliable, networks. Note that both of these timers limit how long uploads of attached files are allowed to take. Use long\r\n * timeouts if you're uploading files.\r\n * @internal\r\n */\r\nexport interface RequestTimeoutOptions {\r\n /** Sets a deadline (in milliseconds) for the entire request (including all uploads, redirects, server processing time) to complete.\r\n * If the response isn't fully downloaded within that time, the request will be aborted\r\n */\r\n deadline?: number;\r\n\r\n /** Sets maximum time (in milliseconds) to wait for the first byte to arrive from the server, but it does not limit how long the entire\r\n * download can take. Response timeout should be at least few seconds longer than just the time it takes the server to respond, because\r\n * it also includes time to make DNS lookup, TCP/IP and TLS connections, and time to upload request data.\r\n */\r\n response?: number;\r\n}\r\n\r\n/** @internal */\r\nexport interface RequestOptions {\r\n method: string;\r\n headers?: any; // {Mas-App-Guid, Mas-UUid, User-Agent}\r\n body?: any;\r\n responseType?: string;\r\n timeout?: RequestTimeoutOptions; // Optional timeouts. If unspecified, an arbitrary default is setup.\r\n stream?: any; // Optional stream to read the response to/from (only for NodeJs applications)\r\n readStream?: any; // Optional stream to read input from (only for NodeJs applications)\r\n buffer?: any;\r\n parser?: any;\r\n accept?: string;\r\n redirects?: number;\r\n errorCallback?: (response: any) => ResponseError;\r\n retryCallback?: (error: any, response: any) => boolean;\r\n progressCallback?: ProgressCallback;\r\n agent?: https.Agent;\r\n retries?: number;\r\n useCorsProxy?: boolean;\r\n}\r\n\r\n/** Response object if the request was successful. Note that the status within the range of 200-299 are considered as a success.\r\n * @internal\r\n */\r\nexport interface Response {\r\n body: any; // Parsed body of response\r\n text: string | undefined; // Returned for responseType:text\r\n header: any; // Parsed headers of response\r\n status: number; // Status code of response\r\n}\r\n\r\n/** @internal */\r\nexport interface ProgressInfo {\r\n percent?: number;\r\n total?: number;\r\n loaded: number;\r\n}\r\n\r\n/** @internal */\r\nexport type ProgressCallback = (progress: ProgressInfo) => void;\r\n\r\n/** Error object that's thrown/rejected if the Request fails due to a network error, or if the status is *not* in the range of 200-299 (inclusive)\r\n * @internal\r\n */\r\nexport class ResponseError extends BentleyError {\r\n protected _data?: any;\r\n public status?: number;\r\n public description?: string;\r\n public constructor(errorNumber: number | HttpStatus, message?: string, getMetaData?: GetMetaDataFunction) {\r\n super(errorNumber, message, getMetaData);\r\n }\r\n\r\n /**\r\n * Parses error from server's response\r\n * @param response Http response from the server.\r\n * @returns Parsed error.\r\n * @internal\r\n */\r\n public static parse(response: any, log = true): ResponseError {\r\n const error = new ResponseError(ResponseError.parseHttpStatus(response.statusType));\r\n if (!response) {\r\n error.message = \"Couldn't get response object.\";\r\n return error;\r\n }\r\n\r\n if (response.response) {\r\n if (response.response.error) {\r\n error.name = response.response.error.name || error.name;\r\n error.description = response.response.error.message;\r\n }\r\n if (response.response.res) {\r\n error.message = response.response.res.statusMessage;\r\n }\r\n if (response.response.body && Object.keys(response.response.body).length > 0) {\r\n error._data = {};\r\n _.merge(error._data, response.response.body);\r\n } else {\r\n error._data = response.response.text;\r\n }\r\n }\r\n\r\n error.status = response.status || response.statusCode;\r\n error.name = response.code || response.name || error.name;\r\n error.message = error.message || response.message || response.statusMessage;\r\n\r\n if (log)\r\n error.log();\r\n\r\n return error;\r\n }\r\n\r\n /**\r\n * Decides whether request should be retried or not\r\n * @param error Error returned by request\r\n * @param response Response returned by request\r\n * @internal\r\n */\r\n public static shouldRetry(error: any, response: any): boolean {\r\n if (error !== undefined && error !== null) {\r\n if ((error.status === undefined || error.status === null) && (error.res === undefined || error.res === null)) {\r\n return true;\r\n }\r\n }\r\n return (response !== undefined && response.statusType === HttpStatus.ServerError);\r\n }\r\n\r\n /**\r\n * @internal\r\n */\r\n public static parseHttpStatus(statusType: number): HttpStatus {\r\n switch (statusType) {\r\n case 1:\r\n return HttpStatus.Info;\r\n case 2:\r\n return HttpStatus.Success;\r\n case 3:\r\n return HttpStatus.Redirection;\r\n case 4:\r\n return HttpStatus.ClientError;\r\n case 5:\r\n return HttpStatus.ServerError;\r\n default:\r\n return HttpStatus.Success;\r\n }\r\n }\r\n\r\n /**\r\n * @internal\r\n */\r\n public logMessage(): string {\r\n return `${this.status} ${this.name}: ${this.message}`;\r\n }\r\n\r\n /**\r\n * Logs this error\r\n * @internal\r\n */\r\n public log(): void {\r\n Logger.logError(loggerCategory, this.logMessage(), () => this.getMetaData());\r\n }\r\n}\r\n\r\nconst logResponse = (req: sarequest.SuperAgentRequest, startTime: number) => (res: sarequest.Response) => {\r\n const elapsed = new Date().getTime() - startTime;\r\n const elapsedTime = `${elapsed}ms`;\r\n Logger.logTrace(loggerCategory, `${req.method.toUpperCase()} ${res.status} ${req.url} (${elapsedTime})`);\r\n};\r\n\r\n// eslint-disable-next-line @typescript-eslint/promise-function-async\r\nconst logRequest = (req: sarequest.SuperAgentRequest): sarequest.SuperAgentRequest => {\r\n const startTime = new Date().getTime();\r\n return req.on(\"response\", logResponse(req, startTime));\r\n};\r\n\r\n/** Wrapper around making HTTP requests with the specific options.\r\n *\r\n * Usable in both a browser and node based environment.\r\n *\r\n * @param url Server URL to address the request\r\n * @param options Options to pass to the request\r\n * @returns Resolves to the response from the server\r\n * @throws ResponseError if the request fails due to network issues, or if the returned status is *outside* the range of 200-299 (inclusive)\r\n * @internal\r\n */\r\nexport async function request(url: string, options: RequestOptions): Promise<Response> {\r\n let sareq: sarequest.SuperAgentRequest = sarequest(options.method, url);\r\n if (options.retries)\r\n sareq = sareq.retry(options.retries, options.retryCallback);\r\n\r\n if (Logger.isEnabled(loggerCategory, LogLevel.Trace))\r\n sareq = sareq.use(logRequest);\r\n\r\n if (options.headers)\r\n sareq = sareq.set(options.headers);\r\n\r\n Logger.logInfo(loggerCategory, url);\r\n\r\n if (options.accept)\r\n sareq = sareq.accept(options.accept);\r\n\r\n if (options.body)\r\n sareq = sareq.send(options.body);\r\n\r\n if (options.timeout)\r\n sareq = sareq.timeout(options.timeout);\r\n\r\n if (options.responseType)\r\n sareq = sareq.responseType(options.responseType);\r\n\r\n if (options.redirects)\r\n sareq = sareq.redirects(options.redirects);\r\n else\r\n sareq = sareq.redirects(0);\r\n\r\n if (options.buffer)\r\n sareq = sareq.buffer(options.buffer);\r\n\r\n if (options.parser)\r\n sareq = sareq.parse(options.parser);\r\n\r\n /** Default to any globally supplied proxy, unless an agent is specified in this call */\r\n if (options.agent)\r\n sareq = sareq.agent(options.agent);\r\n\r\n if (options.progressCallback) {\r\n sareq = sareq.on(\"progress\", (event: sarequest.ProgressEvent) => {\r\n if (event) {\r\n options.progressCallback!({\r\n loaded: event.loaded,\r\n total: event.total,\r\n percent: event.percent,\r\n });\r\n }\r\n });\r\n }\r\n\r\n const errorCallback = options.errorCallback ? options.errorCallback : (response: any) => ResponseError.parse(response);\r\n\r\n if (options.readStream) {\r\n if (typeof window !== \"undefined\")\r\n throw new Error(\"This option is not supported on browsers\");\r\n\r\n return new Promise<Response>((resolve, reject) => {\r\n sareq = sareq.type(\"blob\");\r\n options\r\n .readStream\r\n .pipe(sareq)\r\n .on(\"error\", (error: any) => {\r\n const parsedError = errorCallback(error);\r\n reject(parsedError);\r\n })\r\n .on(\"end\", () => {\r\n const retResponse: Response = {\r\n status: 201,\r\n header: undefined,\r\n body: undefined,\r\n text: undefined,\r\n };\r\n resolve(retResponse);\r\n });\r\n });\r\n }\r\n\r\n if (options.stream) {\r\n if (typeof window !== \"undefined\")\r\n throw new Error(\"This option is not supported on browsers\");\r\n\r\n return new Promise<Response>((resolve, reject) => {\r\n sareq\r\n .on(\"response\", (res: any) => {\r\n if (res.statusCode !== 200) {\r\n const parsedError = errorCallback(res);\r\n reject(parsedError);\r\n return;\r\n }\r\n })\r\n .pipe(options.stream)\r\n .on(\"error\", (error: any) => {\r\n const parsedError = errorCallback(error);\r\n reject(parsedError);\r\n })\r\n .on(\"finish\", () => {\r\n const retResponse: Response = {\r\n status: 200,\r\n header: undefined,\r\n body: undefined,\r\n text: undefined,\r\n };\r\n resolve(retResponse);\r\n });\r\n });\r\n }\r\n\r\n // console.log(\"%s %s %s\", url, options.method, queryStr);\r\n\r\n /**\r\n * Note:\r\n * Javascript's fetch returns status.OK if error is between 200-299 inclusive, and doesn't reject in this case.\r\n * Fetch only rejects if there's some network issue (permissions issue or similar)\r\n * Superagent rejects network issues, and errors outside the range of 200-299. We are currently using\r\n * superagent, but may eventually switch to JavaScript's fetch library.\r\n */\r\n try {\r\n const response = await sareq;\r\n const retResponse: Response = {\r\n body: response.body,\r\n text: response.text,\r\n header: response.header,\r\n status: response.status,\r\n };\r\n return retResponse;\r\n } catch (error) {\r\n const parsedError = errorCallback(error);\r\n throw parsedError;\r\n }\r\n}\r\n\r\n/**\r\n * fetch json from HTTP request\r\n * @param url server URL to address the request\r\n * @internal\r\n */\r\nexport async function getJson(url: string): Promise<any> {\r\n const options: RequestOptions = {\r\n method: \"GET\",\r\n responseType: \"json\",\r\n };\r\n const data = await request(url, options);\r\n return data.body;\r\n}\r\n"]}
@@ -1,5 +1,6 @@
1
1
  /** @internal */
2
- export declare const mobileAppChannel = "mobileApp";
3
- /** @internal */
4
- export declare const mobileAppNotify = "mobileApp-notify";
2
+ export declare const mobileAppStrings: {
3
+ readonly mobileAppChannel: "itwinjs-core/mobileApp";
4
+ readonly mobileAppNotify: "itwinjs-core/mobileApp-notify";
5
+ };
5
6
  //# sourceMappingURL=MobileAppChannel.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"MobileAppChannel.d.ts","sourceRoot":"","sources":["../../../src/common/MobileAppChannel.ts"],"names":[],"mappings":"AAKA,gBAAgB;AAChB,eAAO,MAAM,gBAAgB,cAAc,CAAC;AAC5C,gBAAgB;AAChB,eAAO,MAAM,eAAe,qBAAqB,CAAC"}
1
+ {"version":3,"file":"MobileAppChannel.d.ts","sourceRoot":"","sources":["../../../src/common/MobileAppChannel.ts"],"names":[],"mappings":"AAKA,gBAAgB;AAChB,eAAO,MAAM,gBAAgB;;;CAGnB,CAAC"}
@@ -4,9 +4,10 @@
4
4
  * See LICENSE.md in the project root for license terms and full copyright notice.
5
5
  *--------------------------------------------------------------------------------------------*/
6
6
  Object.defineProperty(exports, "__esModule", { value: true });
7
- exports.mobileAppNotify = exports.mobileAppChannel = void 0;
7
+ exports.mobileAppStrings = void 0;
8
8
  /** @internal */
9
- exports.mobileAppChannel = "mobileApp";
10
- /** @internal */
11
- exports.mobileAppNotify = "mobileApp-notify";
9
+ exports.mobileAppStrings = {
10
+ mobileAppChannel: "itwinjs-core/mobileApp",
11
+ mobileAppNotify: "itwinjs-core/mobileApp-notify",
12
+ };
12
13
  //# sourceMappingURL=MobileAppChannel.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"MobileAppChannel.js","sourceRoot":"","sources":["../../../src/common/MobileAppChannel.ts"],"names":[],"mappings":";AAAA;;;+FAG+F;;;AAE/F,gBAAgB;AACH,QAAA,gBAAgB,GAAG,WAAW,CAAC;AAC5C,gBAAgB;AACH,QAAA,eAAe,GAAG,kBAAkB,CAAC","sourcesContent":["/*---------------------------------------------------------------------------------------------\r\n* Copyright (c) Bentley Systems, Incorporated. All rights reserved.\r\n* See LICENSE.md in the project root for license terms and full copyright notice.\r\n*--------------------------------------------------------------------------------------------*/\r\n\r\n/** @internal */\r\nexport const mobileAppChannel = \"mobileApp\";\r\n/** @internal */\r\nexport const mobileAppNotify = \"mobileApp-notify\";\r\n"]}
1
+ {"version":3,"file":"MobileAppChannel.js","sourceRoot":"","sources":["../../../src/common/MobileAppChannel.ts"],"names":[],"mappings":";AAAA;;;+FAG+F;;;AAE/F,gBAAgB;AACH,QAAA,gBAAgB,GAAG;IAC9B,gBAAgB,EAAE,wBAAwB;IAC1C,eAAe,EAAE,+BAA+B;CACxC,CAAC","sourcesContent":["/*---------------------------------------------------------------------------------------------\r\n* Copyright (c) Bentley Systems, Incorporated. All rights reserved.\r\n* See LICENSE.md in the project root for license terms and full copyright notice.\r\n*--------------------------------------------------------------------------------------------*/\r\n\r\n/** @internal */\r\nexport const mobileAppStrings = {\r\n mobileAppChannel: \"itwinjs-core/mobileApp\",\r\n mobileAppNotify: \"itwinjs-core/mobileApp-notify\",\r\n} as const;\r\n"]}
@@ -13,7 +13,7 @@ const MobileRpcManager_1 = require("../common/MobileRpcManager");
13
13
  const MobileAuthorizationFrontend_1 = require("./MobileAuthorizationFrontend");
14
14
  /** receive notifications from backend */
15
15
  class MobileAppNotifyHandler extends core_frontend_1.NotificationHandler {
16
- get channelName() { return MobileAppChannel_1.mobileAppNotify; }
16
+ get channelName() { return MobileAppChannel_1.mobileAppStrings.mobileAppNotify; }
17
17
  notifyMemoryWarning() {
18
18
  core_bentley_1.Logger.logWarning("mobileApp", "Low memory warning");
19
19
  if (MobileApp.onMemoryWarning.numberOfListeners === 0) {
@@ -30,7 +30,7 @@ class MobileAppNotifyHandler extends core_frontend_1.NotificationHandler {
30
30
  /** @beta */
31
31
  class MobileApp {
32
32
  static async callBackend(methodName, ...args) {
33
- return core_frontend_1.IpcApp.callIpcChannel(MobileAppChannel_1.mobileAppChannel, methodName, ...args);
33
+ return core_frontend_1.IpcApp.callIpcChannel(MobileAppChannel_1.mobileAppStrings.mobileAppChannel, methodName, ...args);
34
34
  }
35
35
  static get isValid() { return this._isValid; }
36
36
  /** @beta */
@@ -1 +1 @@
1
- {"version":3,"file":"MobileApp.js","sourceRoot":"","sources":["../../../src/frontend/MobileApp.ts"],"names":[],"mappings":";AAAA;;;+FAG+F;;;AAE/F,sDAAyF;AACzF,oDAA0G;AAC1G,wDAA+G;AAC/G,iEAA+E;AAE/E,iEAA8D;AAC9D,+EAA4E;AAK5E,yCAAyC;AACzC,MAAM,sBAAuB,SAAQ,mCAAmB;IACtD,IAAW,WAAW,KAAK,OAAO,kCAAe,CAAC,CAAC,CAAC;IAE7C,mBAAmB;QACxB,qBAAM,CAAC,UAAU,CAAC,WAAW,EAAE,oBAAoB,CAAC,CAAC;QACrD,IAAI,SAAS,CAAC,eAAe,CAAC,iBAAiB,KAAK,CAAC,EAAE;YACrD,KAAK,CAAC,oBAAoB,CAAC,CAAC;SAC7B;QACD,SAAS,CAAC,eAAe,CAAC,UAAU,EAAE,CAAC;IACzC,CAAC;IACM,wBAAwB,KAAK,SAAS,CAAC,oBAAoB,CAAC,UAAU,EAAE,CAAC,CAAC,CAAC;IAC3E,mBAAmB,KAAK,SAAS,CAAC,eAAe,CAAC,UAAU,EAAE,CAAC,CAAC,CAAC;IACjE,4BAA4B,CAAC,WAA+B,EAAE,cAAkC;QACrG,SAAS,CAAC,wBAAwB,CAAC,UAAU,CAAC,WAAW,EAAE,cAAc,CAAC,CAAC;IAC7E,CAAC;CACF;AAED,YAAY;AACZ,MAAa,SAAS;IAOb,MAAM,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,sBAAO,EAAc,CAAC;AACjD,2BAAiB,GAAG,IAAI,sBAAO,EAAc,CAAC;AAC9C,2BAAiB,GAAG,IAAI,sBAAO,EAAc,CAAC;AAC9C,yBAAe,GAAG,IAAI,sBAAO,EAAc,CAAC;AAC5C,kCAAwB,GAAG,IAAI,sBAAO,EAAiF,CAAC;AAKvH,kBAAQ,GAAG,KAAK,CAAC;AAXrB,8BAAS;AAwCtB;;;;EAIE;AACF,SAAS,0BAA0B;IAChC,MAAc,CAAC,uBAAuB,GAAG,CAAC,GAAyB,EAAE,EAAE;QACtE,IAAI,GAAG,KAAK,SAAS,EAAE;YACrB,SAAS,CAAC,iBAAiB,CAAC,UAAU,EAAE,CAAC;SAC1C;aAAM,IAAI,GAAG,KAAK,QAAQ,EAAE;YAC3B,SAAS,CAAC,iBAAiB,CAAC,UAAU,EAAE,CAAC;SAC1C;IACH,CAAC,CAAC;AACJ,CAAC","sourcesContent":["/*---------------------------------------------------------------------------------------------\r\n* Copyright (c) Bentley Systems, Incorporated. All rights reserved.\r\n* See LICENSE.md in the project root for license terms and full copyright notice.\r\n*--------------------------------------------------------------------------------------------*/\r\n\r\nimport { AsyncMethodsOf, BeEvent, Logger, PromiseReturnType } from \"@itwin/core-bentley\";\r\nimport { IModelReadRpcInterface, IModelTileRpcInterface, IpcWebSocketFrontend } from \"@itwin/core-common\";\r\nimport { IModelAppOptions, IpcApp, NativeApp, NativeAppOpts, NotificationHandler } from \"@itwin/core-frontend\";\r\nimport { mobileAppChannel, mobileAppNotify } from \"../common/MobileAppChannel\";\r\nimport { MobileAppFunctions, MobileNotifications } from \"../common/MobileAppProps\";\r\nimport { MobileRpcManager } from \"../common/MobileRpcManager\";\r\nimport { MobileAuthorizationFrontend } from \"./MobileAuthorizationFrontend\";\r\n\r\n/** @beta */\r\nexport type MobileAppOpts = NativeAppOpts & { iModelApp: { authorizationClient?: never } };\r\n\r\n/** receive notifications from backend */\r\nclass MobileAppNotifyHandler extends NotificationHandler implements MobileNotifications {\r\n public get channelName() { return mobileAppNotify; }\r\n\r\n public notifyMemoryWarning() {\r\n Logger.logWarning(\"mobileApp\", \"Low memory warning\");\r\n if (MobileApp.onMemoryWarning.numberOfListeners === 0) {\r\n alert(\"Low memory warning\");\r\n }\r\n MobileApp.onMemoryWarning.raiseEvent();\r\n }\r\n public notifyOrientationChanged() { MobileApp.onOrientationChanged.raiseEvent(); }\r\n public notifyWillTerminate() { MobileApp.onWillTerminate.raiseEvent(); }\r\n public notifyAuthAccessTokenChanged(accessToken: string | undefined, expirationDate: string | undefined) {\r\n MobileApp.onAuthAccessTokenChanged.raiseEvent(accessToken, expirationDate);\r\n }\r\n}\r\n\r\n/** @beta */\r\nexport class MobileApp {\r\n public static onMemoryWarning = new BeEvent<() => void>();\r\n public static onOrientationChanged = new BeEvent<() => void>();\r\n public static onEnterForeground = new BeEvent<() => void>();\r\n public static onEnterBackground = new BeEvent<() => void>();\r\n public static onWillTerminate = new BeEvent<() => void>();\r\n public static onAuthAccessTokenChanged = new BeEvent<(accessToken: string | undefined, expirationDate: string | undefined) => void>();\r\n public static async callBackend<T extends AsyncMethodsOf<MobileAppFunctions>>(methodName: T, ...args: Parameters<MobileAppFunctions[T]>) {\r\n return IpcApp.callIpcChannel(mobileAppChannel, methodName, ...args) as PromiseReturnType<MobileAppFunctions[T]>;\r\n }\r\n\r\n private static _isValid = false;\r\n public static get isValid() { return this._isValid; }\r\n /** @beta */\r\n public static async startup(opts?: MobileAppOpts) {\r\n attachDirectEventCallbacks();\r\n\r\n const iModelAppOpts: IModelAppOptions = {\r\n ...opts?.iModelApp,\r\n };\r\n const authorizationClient = new MobileAuthorizationFrontend();\r\n iModelAppOpts.authorizationClient = authorizationClient;\r\n\r\n if (!this._isValid) {\r\n this.onAuthAccessTokenChanged.addListener((accessToken: string | undefined, expirationDate: string | undefined) => {\r\n authorizationClient.setAccessToken(accessToken, expirationDate);\r\n });\r\n\r\n const rpcInterfaces = opts?.iModelApp?.rpcInterfaces ?? [IModelReadRpcInterface, IModelTileRpcInterface]; // eslint-disable-line deprecation/deprecation\r\n MobileRpcManager.initializeClient(rpcInterfaces);\r\n this._isValid = true;\r\n }\r\n\r\n const socket = new IpcWebSocketFrontend(); // needs work\r\n await NativeApp.startup(socket, { ...opts, iModelApp: iModelAppOpts });\r\n\r\n MobileAppNotifyHandler.register(); // receives notifications from backend\r\n }\r\n}\r\n\r\n/*\r\n The suspend/resume lifecycle events cannot be reliably sent from the backend due to timing issues that arise when\r\n inter-operating with the actual suspend and resume behavior on the native side.\r\n Instead, they are sent directly to the browser here from platform-specific code.\r\n*/\r\nfunction attachDirectEventCallbacks() {\r\n (window as any)._imodeljs_rpc_lifecycle = (evt: \"suspend\" | \"resume\") => {\r\n if (evt === \"suspend\") {\r\n MobileApp.onEnterBackground.raiseEvent();\r\n } else if (evt === \"resume\") {\r\n MobileApp.onEnterForeground.raiseEvent();\r\n }\r\n };\r\n}\r\n"]}
1
+ {"version":3,"file":"MobileApp.js","sourceRoot":"","sources":["../../../src/frontend/MobileApp.ts"],"names":[],"mappings":";AAAA;;;+FAG+F;;;AAE/F,sDAAyF;AACzF,oDAA0G;AAC1G,wDAA+G;AAC/G,iEAA8D;AAE9D,iEAA8D;AAC9D,+EAA4E;AAK5E,yCAAyC;AACzC,MAAM,sBAAuB,SAAQ,mCAAmB;IACtD,IAAW,WAAW,KAAK,OAAO,mCAAgB,CAAC,eAAe,CAAC,CAAC,CAAC;IAE9D,mBAAmB;QACxB,qBAAM,CAAC,UAAU,CAAC,WAAW,EAAE,oBAAoB,CAAC,CAAC;QACrD,IAAI,SAAS,CAAC,eAAe,CAAC,iBAAiB,KAAK,CAAC,EAAE;YACrD,KAAK,CAAC,oBAAoB,CAAC,CAAC;SAC7B;QACD,SAAS,CAAC,eAAe,CAAC,UAAU,EAAE,CAAC;IACzC,CAAC;IACM,wBAAwB,KAAK,SAAS,CAAC,oBAAoB,CAAC,UAAU,EAAE,CAAC,CAAC,CAAC;IAC3E,mBAAmB,KAAK,S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AM,yBAAS,CAAC,OAAO,CAAC,MAAM,EAAE,EAAE,GAAG,IAAI,EAAE,SAAS,EAAE,aAAa,EAAE,CAAC,CAAC;QAEvE,sBAAsB,CAAC,QAAQ,EAAE,CAAC,CAAC,sCAAsC;IAC3E,CAAC;;AApCa,yBAAe,GAAG,IAAI,sBAAO,EAAc,CAAC;AAC5C,8BAAoB,GAAG,IAAI,sBAAO,EAAc,CAAC;AACjD,2BAAiB,GAAG,IAAI,sBAAO,EAAc,CAAC;AAC9C,2BAAiB,GAAG,IAAI,sBAAO,EAAc,CAAC;AAC9C,yBAAe,GAAG,IAAI,sBAAO,EAAc,CAAC;AAC5C,kCAAwB,GAAG,IAAI,sBAAO,EAAiF,CAAC;AAKvH,kBAAQ,GAAG,KAAK,CAAC;AAXrB,8BAAS;AAwCtB;;;;EAIE;AACF,SAAS,0BAA0B;IAChC,MAAc,CAAC,uBAAuB,GAAG,CAAC,GAAyB,EAAE,EAAE;QACtE,IAAI,GAAG,KAAK,SAAS,EAAE;YACrB,SAAS,CAAC,iBAAiB,CAAC,UAAU,EAAE,CAAC;SAC1C;aAAM,IAAI,GAAG,KAAK,QAAQ,EAAE;YAC3B,SAAS,CAAC,iBAAiB,CAAC,UAAU,EAAE,CAAC;SAC1C;IACH,CAAC,CAAC;AACJ,CAAC","sourcesContent":["/*---------------------------------------------------------------------------------------------\r\n* Copyright (c) Bentley Systems, Incorporated. All rights reserved.\r\n* See LICENSE.md in the project root for license terms and full copyright notice.\r\n*--------------------------------------------------------------------------------------------*/\r\n\r\nimport { AsyncMethodsOf, BeEvent, Logger, PromiseReturnType } from \"@itwin/core-bentley\";\r\nimport { IModelReadRpcInterface, IModelTileRpcInterface, IpcWebSocketFrontend } from \"@itwin/core-common\";\r\nimport { IModelAppOptions, IpcApp, NativeApp, NativeAppOpts, NotificationHandler } from \"@itwin/core-frontend\";\r\nimport { mobileAppStrings } from \"../common/MobileAppChannel\";\r\nimport { MobileAppFunctions, MobileNotifications } from \"../common/MobileAppProps\";\r\nimport { MobileRpcManager } from \"../common/MobileRpcManager\";\r\nimport { MobileAuthorizationFrontend } from \"./MobileAuthorizationFrontend\";\r\n\r\n/** @beta */\r\nexport type MobileAppOpts = NativeAppOpts & { iModelApp: { authorizationClient?: never } };\r\n\r\n/** receive notifications from backend */\r\nclass MobileAppNotifyHandler extends NotificationHandler implements MobileNotifications {\r\n public get channelName() { return mobileAppStrings.mobileAppNotify; }\r\n\r\n public notifyMemoryWarning() {\r\n Logger.logWarning(\"mobileApp\", \"Low memory warning\");\r\n if (MobileApp.onMemoryWarning.numberOfListeners === 0) {\r\n alert(\"Low memory warning\");\r\n }\r\n MobileApp.onMemoryWarning.raiseEvent();\r\n }\r\n public notifyOrientationChanged() { MobileApp.onOrientationChanged.raiseEvent(); }\r\n public notifyWillTerminate() { MobileApp.onWillTerminate.raiseEvent(); }\r\n public notifyAuthAccessTokenChanged(accessToken: string | undefined, expirationDate: string | undefined) {\r\n MobileApp.onAuthAccessTokenChanged.raiseEvent(accessToken, expirationDate);\r\n }\r\n}\r\n\r\n/** @beta */\r\nexport class MobileApp {\r\n public static onMemoryWarning = new BeEvent<() => void>();\r\n public static onOrientationChanged = new BeEvent<() => void>();\r\n public static onEnterForeground = new BeEvent<() => void>();\r\n public static onEnterBackground = new BeEvent<() => void>();\r\n public static onWillTerminate = new BeEvent<() => void>();\r\n public static onAuthAccessTokenChanged = new BeEvent<(accessToken: string | undefined, expirationDate: string | undefined) => void>();\r\n public static async callBackend<T extends AsyncMethodsOf<MobileAppFunctions>>(methodName: T, ...args: Parameters<MobileAppFunctions[T]>) {\r\n return IpcApp.callIpcChannel(mobileAppStrings.mobileAppChannel, methodName, ...args) as PromiseReturnType<MobileAppFunctions[T]>;\r\n }\r\n\r\n private static _isValid = false;\r\n public static get isValid() { return this._isValid; }\r\n /** @beta */\r\n public static async startup(opts?: MobileAppOpts) {\r\n attachDirectEventCallbacks();\r\n\r\n const iModelAppOpts: IModelAppOptions = {\r\n ...opts?.iModelApp,\r\n };\r\n const authorizationClient = new MobileAuthorizationFrontend();\r\n iModelAppOpts.authorizationClient = authorizationClient;\r\n\r\n if (!this._isValid) {\r\n this.onAuthAccessTokenChanged.addListener((accessToken: string | undefined, expirationDate: string | undefined) => {\r\n authorizationClient.setAccessToken(accessToken, expirationDate);\r\n });\r\n\r\n const rpcInterfaces = opts?.iModelApp?.rpcInterfaces ?? [IModelReadRpcInterface, IModelTileRpcInterface]; // eslint-disable-line deprecation/deprecation\r\n MobileRpcManager.initializeClient(rpcInterfaces);\r\n this._isValid = true;\r\n }\r\n\r\n const socket = new IpcWebSocketFrontend(); // needs work\r\n await NativeApp.startup(socket, { ...opts, iModelApp: iModelAppOpts });\r\n\r\n MobileAppNotifyHandler.register(); // receives notifications from backend\r\n }\r\n}\r\n\r\n/*\r\n The suspend/resume lifecycle events cannot be reliably sent from the backend due to timing issues that arise when\r\n inter-operating with the actual suspend and resume behavior on the native side.\r\n Instead, they are sent directly to the browser here from platform-specific code.\r\n*/\r\nfunction attachDirectEventCallbacks() {\r\n (window as any)._imodeljs_rpc_lifecycle = (evt: \"suspend\" | \"resume\") => {\r\n if (evt === \"suspend\") {\r\n MobileApp.onEnterBackground.raiseEvent();\r\n } else if (evt === \"resume\") {\r\n MobileApp.onEnterForeground.raiseEvent();\r\n }\r\n };\r\n}\r\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@itwin/core-mobile",
3
- "version": "4.1.0-dev.7",
3
+ "version": "4.1.0-dev.71",
4
4
  "description": "iTwin.js MobileHost and MobileApp",
5
5
  "license": "MIT",
6
6
  "engines": {
@@ -22,10 +22,10 @@
22
22
  "url": "http://www.bentley.com"
23
23
  },
24
24
  "peerDependencies": {
25
- "@itwin/core-backend": "^4.1.0-dev.7",
26
- "@itwin/core-bentley": "^4.1.0-dev.7",
27
- "@itwin/core-common": "^4.1.0-dev.7",
28
- "@itwin/core-frontend": "^4.1.0-dev.7"
25
+ "@itwin/core-backend": "^4.1.0-dev.71",
26
+ "@itwin/core-bentley": "^4.1.0-dev.71",
27
+ "@itwin/core-common": "^4.1.0-dev.71",
28
+ "@itwin/core-frontend": "^4.1.0-dev.71"
29
29
  },
30
30
  "dependencies": {
31
31
  "lodash": "^4.17.10",
@@ -33,33 +33,27 @@
33
33
  "ws": "^7.5.3"
34
34
  },
35
35
  "devDependencies": {
36
- "@itwin/eslint-plugin": "^4.0.0-dev.33",
36
+ "@itwin/eslint-plugin": "4.0.0-dev.44",
37
37
  "@types/chai": "4.3.1",
38
38
  "@types/fs-extra": "^4.0.7",
39
39
  "@types/lodash": "^4.14.0",
40
40
  "@types/mocha": "^8.2.2",
41
- "@types/node": "^18.11.5",
41
+ "@types/node": "18.16.1",
42
42
  "@types/superagent": "^4.1.14",
43
43
  "@types/ws": "^7.0.0",
44
44
  "chai": "^4.1.2",
45
45
  "chai-as-promised": "^7",
46
46
  "dotenv": "^10.0.0",
47
47
  "dotenv-expand": "^5.1.0",
48
- "eslint": "^8.36.0",
48
+ "eslint": "^8.44.0",
49
49
  "mocha": "^10.0.0",
50
50
  "rimraf": "^3.0.2",
51
51
  "typescript": "~5.0.2",
52
- "@itwin/build-tools": "4.1.0-dev.7",
53
- "@itwin/core-backend": "4.1.0-dev.7",
54
- "@itwin/core-frontend": "4.1.0-dev.7",
55
- "@itwin/core-common": "4.1.0-dev.7",
56
- "@itwin/core-bentley": "4.1.0-dev.7"
57
- },
58
- "eslintConfig": {
59
- "plugins": [
60
- "@itwin"
61
- ],
62
- "extends": "plugin:@itwin/itwinjs-recommended"
52
+ "@itwin/build-tools": "4.1.0-dev.71",
53
+ "@itwin/core-backend": "4.1.0-dev.71",
54
+ "@itwin/core-frontend": "4.1.0-dev.71",
55
+ "@itwin/core-common": "4.1.0-dev.71",
56
+ "@itwin/core-bentley": "4.1.0-dev.71"
63
57
  },
64
58
  "scripts": {
65
59
  "build": "npm run -s build:cjs",