@itwin/core-frontend 4.0.0-dev.22 → 4.0.0-dev.24
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/lib/cjs/GeoServices.d.ts +57 -5
- package/lib/cjs/GeoServices.d.ts.map +1 -1
- package/lib/cjs/GeoServices.js +182 -155
- package/lib/cjs/GeoServices.js.map +1 -1
- package/lib/cjs/request/Request.d.ts.map +1 -1
- package/lib/cjs/request/Request.js.map +1 -1
- package/lib/cjs/tile/GltfReader.js +1 -1
- package/lib/cjs/tile/GltfReader.js.map +1 -1
- package/lib/cjs/tile/map/ArcGisUtilities.d.ts.map +1 -1
- package/lib/cjs/tile/map/ArcGisUtilities.js.map +1 -1
- package/lib/cjs/tile/map/ImageryProviders/ArcGISMapLayerImageryProvider.d.ts.map +1 -1
- package/lib/cjs/tile/map/ImageryProviders/ArcGISMapLayerImageryProvider.js +1 -2
- package/lib/cjs/tile/map/ImageryProviders/ArcGISMapLayerImageryProvider.js.map +1 -1
- package/lib/esm/GeoServices.d.ts +57 -5
- package/lib/esm/GeoServices.d.ts.map +1 -1
- package/lib/esm/GeoServices.js +180 -154
- package/lib/esm/GeoServices.js.map +1 -1
- package/lib/esm/request/Request.d.ts.map +1 -1
- package/lib/esm/request/Request.js.map +1 -1
- package/lib/esm/tile/GltfReader.js +1 -1
- package/lib/esm/tile/GltfReader.js.map +1 -1
- package/lib/esm/tile/map/ArcGisUtilities.d.ts.map +1 -1
- package/lib/esm/tile/map/ArcGisUtilities.js.map +1 -1
- package/lib/esm/tile/map/ImageryProviders/ArcGISMapLayerImageryProvider.d.ts.map +1 -1
- package/lib/esm/tile/map/ImageryProviders/ArcGISMapLayerImageryProvider.js +1 -2
- package/lib/esm/tile/map/ImageryProviders/ArcGISMapLayerImageryProvider.js.map +1 -1
- package/package.json +18 -20
package/lib/esm/GeoServices.js
CHANGED
|
@@ -1,156 +1,163 @@
|
|
|
1
|
+
/*---------------------------------------------------------------------------------------------
|
|
2
|
+
* Copyright (c) Bentley Systems, Incorporated. All rights reserved.
|
|
3
|
+
* See LICENSE.md in the project root for license terms and full copyright notice.
|
|
4
|
+
*--------------------------------------------------------------------------------------------*/
|
|
5
|
+
// cspell:ignore GCRS
|
|
6
|
+
import { assert, BeEvent, Dictionary, Logger, SortedArray, } from "@itwin/core-bentley";
|
|
1
7
|
import { GeoCoordStatus, IModelReadRpcInterface, } from "@itwin/core-common";
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
+
import { FrontendLoggerCategory } from "./FrontendLoggerCategory";
|
|
9
|
+
function compareXYAndZ(lhs, rhs) {
|
|
10
|
+
return lhs.x - rhs.x || lhs.y - rhs.y || lhs.z - rhs.z;
|
|
11
|
+
}
|
|
12
|
+
function cloneXYAndZ(xyz) {
|
|
13
|
+
return { x: xyz.x, y: xyz.y, z: xyz.z };
|
|
14
|
+
}
|
|
15
|
+
/** Performs conversion of coordinates from one coordinate system to another.
|
|
16
|
+
* A [[GeoConverter]] has a pair of these for converting between iModel coordinates and geographic coordinates.
|
|
17
|
+
* Uses a cache to avoid repeatedly requesting the same points, and a batching strategy to avoid making frequent small requests.
|
|
18
|
+
* The cache stores every point that was ever converted by [[convert]]. It is currently permitted to grow to unbounded size.
|
|
19
|
+
* The batching works as follows:
|
|
20
|
+
* When a conversion is requested via [[convert]], if all the requested points are in the cache, they are returned immediately.
|
|
21
|
+
* Otherwise, any points not in the cache and not in the current in-flight request (if any) are placed onto the queue of pending requests.
|
|
22
|
+
* A pending request is scheduled if one hasn't already been scheduled, via requestAnimationFrame.
|
|
23
|
+
* In the animation frame callback, the pending requests are split into batches of no more than options.maxPointsPerRequest and dispatched to the backend.
|
|
24
|
+
* Once the response is received, the results are loaded into and returned from the cache.
|
|
25
|
+
* If more calls to convert occurred while the request was in flight, another request is dispatched.
|
|
26
|
+
* @internal exported strictly for tests.
|
|
27
|
+
*/
|
|
28
|
+
export class CoordinateConverter {
|
|
29
|
+
constructor(opts) {
|
|
30
|
+
var _a;
|
|
31
|
+
this._state = "idle";
|
|
32
|
+
// An event fired when the next request completes.
|
|
33
|
+
this._onCompleted = new BeEvent();
|
|
34
|
+
// Used for creating cache keys (XYAndZ) from XYZProps without having to allocate temporary objects.
|
|
35
|
+
this._scratchXYZ = { x: 0, y: 0, z: 0 };
|
|
36
|
+
this._maxPointsPerRequest = Math.max(1, (_a = opts.maxPointsPerRequest) !== null && _a !== void 0 ? _a : 300);
|
|
37
|
+
this._iModel = opts.iModel;
|
|
38
|
+
this._requestPoints = opts.requestPoints;
|
|
39
|
+
this._cache = new Dictionary(compareXYAndZ, cloneXYAndZ);
|
|
40
|
+
this._pending = new SortedArray(compareXYAndZ, false, cloneXYAndZ);
|
|
41
|
+
this._inflight = new SortedArray(compareXYAndZ, false, cloneXYAndZ);
|
|
8
42
|
}
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
const imodelCoord = this._cache[key];
|
|
16
|
-
result.push(imodelCoord);
|
|
17
|
-
if (undefined === imodelCoord) {
|
|
18
|
-
if (undefined === missing)
|
|
19
|
-
missing = [];
|
|
20
|
-
missing.push(geoPoint);
|
|
21
|
-
}
|
|
43
|
+
toXYAndZ(input, output) {
|
|
44
|
+
var _a, _b, _c, _d, _e, _f;
|
|
45
|
+
if (Array.isArray(input)) {
|
|
46
|
+
output.x = (_a = input[0]) !== null && _a !== void 0 ? _a : 0;
|
|
47
|
+
output.y = (_b = input[1]) !== null && _b !== void 0 ? _b : 0;
|
|
48
|
+
output.z = (_c = input[2]) !== null && _c !== void 0 ? _c : 0;
|
|
22
49
|
}
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
let missing;
|
|
28
|
-
// Index by cache key to obtain index in input array.
|
|
29
|
-
const originalPositions = {};
|
|
30
|
-
for (let iPoint = 0; iPoint < request.geoCoords.length; ++iPoint) {
|
|
31
|
-
const thisGeoCoord = request.geoCoords[iPoint];
|
|
32
|
-
// we use the JSON string as the key into our cache of previously returned results.
|
|
33
|
-
const thisCacheKey = JSON.stringify(thisGeoCoord);
|
|
34
|
-
// put something in each output that corresponds to the input.
|
|
35
|
-
if (this._cache[thisCacheKey]) {
|
|
36
|
-
response.iModelCoords.push(this._cache[thisCacheKey]);
|
|
37
|
-
}
|
|
38
|
-
else {
|
|
39
|
-
if (undefined === missing)
|
|
40
|
-
missing = [];
|
|
41
|
-
// add this geoCoord to the request we are going to send.
|
|
42
|
-
missing.push(thisGeoCoord);
|
|
43
|
-
// keep track of the original position of this point.
|
|
44
|
-
if (originalPositions.hasOwnProperty(thisCacheKey)) {
|
|
45
|
-
// it is a duplicate of an earlier point (or points)
|
|
46
|
-
if (Array.isArray(originalPositions[thisCacheKey])) {
|
|
47
|
-
originalPositions[thisCacheKey].push(iPoint);
|
|
48
|
-
}
|
|
49
|
-
else {
|
|
50
|
-
const list = [originalPositions[thisCacheKey], iPoint];
|
|
51
|
-
originalPositions[thisCacheKey] = list;
|
|
52
|
-
}
|
|
53
|
-
}
|
|
54
|
-
else {
|
|
55
|
-
originalPositions[thisCacheKey] = iPoint;
|
|
56
|
-
}
|
|
57
|
-
// mark the response as pending.
|
|
58
|
-
response.iModelCoords.push({ p: [0, 0, 0], s: GeoCoordStatus.Pending });
|
|
59
|
-
}
|
|
50
|
+
else {
|
|
51
|
+
output.x = (_d = input.x) !== null && _d !== void 0 ? _d : 0;
|
|
52
|
+
output.y = (_e = input.y) !== null && _e !== void 0 ? _e : 0;
|
|
53
|
+
output.z = (_f = input.z) !== null && _f !== void 0 ? _f : 0;
|
|
60
54
|
}
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
55
|
+
return output;
|
|
56
|
+
}
|
|
57
|
+
async dispatch() {
|
|
58
|
+
assert(this._state === "scheduled");
|
|
59
|
+
if (this._iModel.isClosed || this._pending.isEmpty) {
|
|
60
|
+
this._state = "idle";
|
|
61
|
+
this._onCompleted.raiseEvent();
|
|
62
|
+
return;
|
|
64
63
|
}
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
}
|
|
92
|
-
});
|
|
93
|
-
promises.push(promise);
|
|
94
|
-
}
|
|
95
|
-
await Promise.all(promises);
|
|
64
|
+
this._state = "in-flight";
|
|
65
|
+
// Ensure subsequently-enqueued requests listen for the *next* response to be received.
|
|
66
|
+
const onCompleted = this._onCompleted;
|
|
67
|
+
this._onCompleted = new BeEvent();
|
|
68
|
+
// Pending requests are now in flight. Start a new list of pending requests. It's cheaper to swap than to allocate new objects.
|
|
69
|
+
const inflight = this._pending;
|
|
70
|
+
this._pending = this._inflight;
|
|
71
|
+
assert(this._pending.isEmpty);
|
|
72
|
+
this._inflight = inflight;
|
|
73
|
+
// Split requests if necessary to avoid requesting more than the maximum allowed number of points.
|
|
74
|
+
const promises = [];
|
|
75
|
+
for (let i = 0; i < inflight.length; i += this._maxPointsPerRequest) {
|
|
76
|
+
const requests = inflight.slice(i, i + this._maxPointsPerRequest).extractArray();
|
|
77
|
+
const promise = this._requestPoints(requests).then((results) => {
|
|
78
|
+
if (this._iModel.isClosed)
|
|
79
|
+
return;
|
|
80
|
+
if (results.length !== requests.length)
|
|
81
|
+
Logger.logError(`${FrontendLoggerCategory.Package}.geoservices`, `requested conversion of ${requests.length} points, but received ${results.length} points`);
|
|
82
|
+
for (let j = 0; j < results.length; j++) {
|
|
83
|
+
if (j < requests.length)
|
|
84
|
+
this._cache.set(requests[j], results[j]);
|
|
85
|
+
}
|
|
86
|
+
}).catch((err) => {
|
|
87
|
+
Logger.logException(`${FrontendLoggerCategory.Package}.geoservices`, err);
|
|
88
|
+
});
|
|
89
|
+
promises.push(promise);
|
|
96
90
|
}
|
|
97
|
-
|
|
91
|
+
await Promise.all(promises);
|
|
92
|
+
assert(this._state === "in-flight");
|
|
93
|
+
this._state = "idle";
|
|
94
|
+
this._inflight.clear();
|
|
95
|
+
// If any more pending conversions arrived while awaiting this request, schedule another request.
|
|
96
|
+
if (!this._pending.isEmpty)
|
|
97
|
+
this.scheduleDispatch(); // eslint-disable-line @typescript-eslint/no-floating-promises
|
|
98
|
+
// Resolve promises of all callers who were awaiting this request.
|
|
99
|
+
onCompleted.raiseEvent();
|
|
98
100
|
}
|
|
99
|
-
|
|
100
|
-
//
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
101
|
+
// Add any points not present in cache to pending request list.
|
|
102
|
+
// Return the number of points present in cache.
|
|
103
|
+
enqueue(points) {
|
|
104
|
+
let numInCache = 0;
|
|
105
|
+
for (const point of points) {
|
|
106
|
+
const xyz = this.toXYAndZ(point, this._scratchXYZ);
|
|
107
|
+
if (this._cache.get(xyz))
|
|
108
|
+
++numInCache;
|
|
109
|
+
else if (!this._inflight.contains(xyz))
|
|
110
|
+
this._pending.insert(xyz);
|
|
111
|
+
}
|
|
112
|
+
return numInCache;
|
|
106
113
|
}
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
const
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
if (this._cache[thisCacheKey]) {
|
|
118
|
-
response.geoCoords.push(this._cache[thisCacheKey]);
|
|
119
|
-
}
|
|
120
|
-
else {
|
|
121
|
-
if (!remainingRequest)
|
|
122
|
-
remainingRequest = { target: this._target, iModelCoords: [] };
|
|
123
|
-
// add this geoCoord to the request we are going to send.
|
|
124
|
-
remainingRequest.iModelCoords.push(thisIModelCoord);
|
|
125
|
-
// keep track of the original position of this point.
|
|
126
|
-
originalPositions.push(iPoint);
|
|
127
|
-
// mark the response as pending.
|
|
128
|
-
response.geoCoords.push({ p: [0, 0, 0], s: GeoCoordStatus.Pending });
|
|
129
|
-
missing = true;
|
|
130
|
-
}
|
|
114
|
+
// Obtain converted points from the cache. The assumption is that every point in `inputs` is already present in the cache.
|
|
115
|
+
// Any point not present will be returned unconverted with an error status.
|
|
116
|
+
getFromCache(inputs) {
|
|
117
|
+
const outputs = [];
|
|
118
|
+
for (const input of inputs) {
|
|
119
|
+
const xyz = this.toXYAndZ(input, this._scratchXYZ);
|
|
120
|
+
let output = this._cache.get(xyz);
|
|
121
|
+
if (!output)
|
|
122
|
+
output = { p: { ...xyz }, s: GeoCoordStatus.CSMapError };
|
|
123
|
+
outputs.push(output);
|
|
131
124
|
}
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
125
|
+
return outputs;
|
|
126
|
+
}
|
|
127
|
+
async scheduleDispatch() {
|
|
128
|
+
if ("idle" === this._state) {
|
|
129
|
+
this._state = "scheduled";
|
|
130
|
+
requestAnimationFrame(() => {
|
|
131
|
+
this.dispatch(); // eslint-disable-line @typescript-eslint/no-floating-promises
|
|
132
|
+
});
|
|
136
133
|
}
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
134
|
+
return new Promise((resolve) => {
|
|
135
|
+
this._onCompleted.addOnce(() => resolve());
|
|
136
|
+
});
|
|
137
|
+
}
|
|
138
|
+
async convert(inputs) {
|
|
139
|
+
const fromCache = this.enqueue(inputs);
|
|
140
|
+
assert(fromCache >= 0);
|
|
141
|
+
assert(fromCache <= inputs.length);
|
|
142
|
+
if (fromCache === inputs.length)
|
|
143
|
+
return { points: this.getFromCache(inputs), fromCache };
|
|
144
|
+
await this.scheduleDispatch();
|
|
145
|
+
return { points: this.getFromCache(inputs), fromCache };
|
|
146
|
+
}
|
|
147
|
+
findCached(inputs) {
|
|
148
|
+
const result = [];
|
|
149
|
+
let missing;
|
|
150
|
+
for (const input of inputs) {
|
|
151
|
+
const key = this.toXYAndZ(input, this._scratchXYZ);
|
|
152
|
+
const output = this._cache.get(key);
|
|
153
|
+
result.push(output);
|
|
154
|
+
if (!output) {
|
|
155
|
+
if (!missing)
|
|
156
|
+
missing = [];
|
|
157
|
+
missing.push(input);
|
|
151
158
|
}
|
|
152
|
-
return response;
|
|
153
159
|
}
|
|
160
|
+
return { result, missing };
|
|
154
161
|
}
|
|
155
162
|
}
|
|
156
163
|
/** The GeoConverter class communicates with the backend to convert longitude/latitude coordinates to iModel coordinates and vice-versa
|
|
@@ -158,23 +165,42 @@ class IMCtoGCResultCache {
|
|
|
158
165
|
*/
|
|
159
166
|
export class GeoConverter {
|
|
160
167
|
constructor(iModel, datumOrGCRS) {
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
168
|
+
const datum = typeof datumOrGCRS === "object" ? JSON.stringify(datumOrGCRS) : datumOrGCRS;
|
|
169
|
+
this._geoToIModel = new CoordinateConverter({
|
|
170
|
+
iModel,
|
|
171
|
+
requestPoints: async (geoCoords) => {
|
|
172
|
+
const request = { source: datum, geoCoords };
|
|
173
|
+
const rpc = IModelReadRpcInterface.getClientForRouting(iModel.routingContext.token);
|
|
174
|
+
const response = await rpc.getIModelCoordinatesFromGeoCoordinates(iModel.getRpcProps(), request);
|
|
175
|
+
return response.iModelCoords;
|
|
176
|
+
},
|
|
177
|
+
});
|
|
178
|
+
this._iModelToGeo = new CoordinateConverter({
|
|
179
|
+
iModel,
|
|
180
|
+
requestPoints: async (iModelCoords) => {
|
|
181
|
+
const request = { target: datum, iModelCoords };
|
|
182
|
+
const rpc = IModelReadRpcInterface.getClientForRouting(iModel.routingContext.token);
|
|
183
|
+
const response = await rpc.getGeoCoordinatesFromIModelCoordinates(iModel.getRpcProps(), request);
|
|
184
|
+
return response.geoCoords;
|
|
185
|
+
},
|
|
186
|
+
});
|
|
167
187
|
}
|
|
168
188
|
async getIModelCoordinatesFromGeoCoordinates(geoPoints) {
|
|
169
|
-
const
|
|
170
|
-
return
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
189
|
+
const result = await this._geoToIModel.convert(geoPoints);
|
|
190
|
+
return {
|
|
191
|
+
iModelCoords: result.points,
|
|
192
|
+
fromCache: result.fromCache,
|
|
193
|
+
};
|
|
174
194
|
}
|
|
175
195
|
async getGeoCoordinatesFromIModelCoordinates(iModelPoints) {
|
|
176
|
-
const
|
|
177
|
-
return
|
|
196
|
+
const result = await this._iModelToGeo.convert(iModelPoints);
|
|
197
|
+
return {
|
|
198
|
+
geoCoords: result.points,
|
|
199
|
+
fromCache: result.fromCache,
|
|
200
|
+
};
|
|
201
|
+
}
|
|
202
|
+
getCachedIModelCoordinatesFromGeoCoordinates(geoPoints) {
|
|
203
|
+
return this._geoToIModel.findCached(geoPoints);
|
|
178
204
|
}
|
|
179
205
|
}
|
|
180
206
|
/** The Geographic Services available for an [[IModelConnection]].
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"GeoServices.js","sourceRoot":"","sources":["../../src/GeoServices.ts"],"names":[],"mappings":"AAMA,OAAO,EACoD,cAAc,EACvE,sBAAsB,GACvB,MAAM,oBAAoB,CAAC;AAa5B,8FAA8F;AAC9F,MAAM,kBAAkB;IAOtB,YAAY,MAAwB,EAAE,MAAc;QAClD,IAAI,CAAC,OAAO,GAAG,MAAM,CAAC;QACtB,IAAI,CAAC,MAAM,GAAG,EAAE,CAAC;QACjB,IAAI,CAAC,OAAO,GAAG,MAAM,CAAC;IACxB,CAAC;IAED,gBAAgB;IACT,WAAW,CAAC,SAAqB;QACtC,MAAM,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C;IAC1G,CAAC;CACF","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// cspell:ignore GCRS\r\nimport { XYZProps } from \"@itwin/core-geometry\";\r\nimport {\r\n GeoCoordinatesRequestProps, GeoCoordinatesResponseProps, GeoCoordStatus, GeographicCRSProps, IModelCoordinatesRequestProps, IModelCoordinatesResponseProps,\r\n IModelReadRpcInterface, PointWithStatus,\r\n} from \"@itwin/core-common\";\r\nimport { IModelConnection } from \"./IModelConnection\";\r\n\r\n/** Response to a request to obtain imodel coordinates from cache.\r\n * @internal\r\n */\r\nexport interface CachedIModelCoordinatesResponseProps {\r\n /** An array of the same length as the input array, with undefined entries at indices corresponding to points not found in cache. */\r\n result: Array<PointWithStatus | undefined>;\r\n /** An array of points in the input array which were not found in the cache, or undefined if all points were found in the cache. */\r\n missing?: XYZProps[];\r\n}\r\n\r\n// this class is used to cache results from conversion of geoCoordinates to IModelCoordinates.\r\nclass GCtoIMCResultCache {\r\n // see fast-memoize npm package where the author demonstrated that an object is the fastest\r\n // lookup (faster than Map), and JSON.stringify is the fastest serializer.\r\n private _cache: any;\r\n private _iModel: IModelConnection;\r\n private _source: string;\r\n\r\n constructor(iModel: IModelConnection, source: string) {\r\n this._iModel = iModel;\r\n this._cache = {};\r\n this._source = source;\r\n }\r\n\r\n /** @internal */\r\n public findInCache(geoPoints: XYZProps[]): CachedIModelCoordinatesResponseProps {\r\n const result: Array<PointWithStatus | undefined> = [];\r\n let missing: XYZProps[] | undefined;\r\n for (const geoPoint of geoPoints) {\r\n const key = JSON.stringify(geoPoint);\r\n const imodelCoord = this._cache[key];\r\n result.push(imodelCoord);\r\n if (undefined === imodelCoord) {\r\n if (undefined === missing)\r\n missing = [];\r\n\r\n missing.push(geoPoint);\r\n }\r\n }\r\n\r\n return { result, missing };\r\n }\r\n\r\n public async findInCacheOrRequest(request: IModelCoordinatesRequestProps): Promise<IModelCoordinatesResponseProps> {\r\n const response: IModelCoordinatesResponseProps = { iModelCoords: [], fromCache: 0 };\r\n let missing: XYZProps[] | undefined;\r\n\r\n // Index by cache key to obtain index in input array.\r\n const originalPositions: any = {};\r\n\r\n for (let iPoint: number = 0; iPoint < request.geoCoords.length; ++iPoint) {\r\n const thisGeoCoord: XYZProps = request.geoCoords[iPoint];\r\n\r\n // we use the JSON string as the key into our cache of previously returned results.\r\n const thisCacheKey: string = JSON.stringify(thisGeoCoord);\r\n\r\n // put something in each output that corresponds to the input.\r\n if (this._cache[thisCacheKey]) {\r\n response.iModelCoords.push(this._cache[thisCacheKey]);\r\n } else {\r\n if (undefined === missing)\r\n missing = [];\r\n\r\n // add this geoCoord to the request we are going to send.\r\n missing.push(thisGeoCoord);\r\n\r\n // keep track of the original position of this point.\r\n if (originalPositions.hasOwnProperty(thisCacheKey)) {\r\n // it is a duplicate of an earlier point (or points)\r\n if (Array.isArray(originalPositions[thisCacheKey])) {\r\n originalPositions[thisCacheKey].push(iPoint);\r\n } else {\r\n const list: number[] = [originalPositions[thisCacheKey], iPoint];\r\n originalPositions[thisCacheKey] = list;\r\n }\r\n } else {\r\n originalPositions[thisCacheKey] = iPoint;\r\n }\r\n\r\n // mark the response as pending.\r\n response.iModelCoords.push({ p: [0, 0, 0], s: GeoCoordStatus.Pending });\r\n }\r\n }\r\n\r\n // if none are missing from the cache, resolve the promise immediately\r\n if (undefined === missing) {\r\n response.fromCache = request.geoCoords.length;\r\n } else {\r\n // keep track of how many came from the cache (mostly for tests).\r\n response.fromCache = request.geoCoords.length - missing.length;\r\n\r\n // Avoiding requesting too many points at once, exceeding max request length (this definition of \"too many\" should be safely conservative) - but enough to load 4 levels of tile corners.\r\n const maxPointsPerRequest = 300;\r\n const promises: Array<Promise<void>> = [];\r\n for (let i = 0; i < missing.length; i += maxPointsPerRequest) {\r\n const remainingRequest = { source: this._source, geoCoords: missing.slice(i, i + maxPointsPerRequest) };\r\n const promise = IModelReadRpcInterface.getClientForRouting(this._iModel.routingContext.token).getIModelCoordinatesFromGeoCoordinates(this._iModel.getRpcProps(), remainingRequest).then((remainingResponse) => {\r\n // put the responses into the cache, and fill in the output response for each\r\n for (let iResponse: number = 0; iResponse < remainingResponse.iModelCoords.length; ++iResponse) {\r\n const thisPoint: PointWithStatus = remainingResponse.iModelCoords[iResponse];\r\n\r\n // put the answer in the cache.\r\n const thisGeoCoord: XYZProps = remainingRequest.geoCoords[iResponse];\r\n const thisCacheKey: string = JSON.stringify(thisGeoCoord);\r\n this._cache[thisCacheKey] = thisPoint;\r\n\r\n // transfer the answer stored in remainingResponse to the correct position in the overall response.\r\n const responseIndex = originalPositions[thisCacheKey];\r\n if (Array.isArray(responseIndex)) {\r\n for (const thisIndex of responseIndex) {\r\n response.iModelCoords[thisIndex] = thisPoint;\r\n }\r\n } else {\r\n response.iModelCoords[responseIndex] = thisPoint;\r\n }\r\n }\r\n });\r\n\r\n promises.push(promise);\r\n }\r\n\r\n await Promise.all(promises);\r\n }\r\n\r\n return response;\r\n }\r\n}\r\n\r\n// this class is used to cache results from conversion of IModelCoordinates to GeoCoordinates.\r\nclass IMCtoGCResultCache {\r\n // see fast-memoize npm package where the author demonstrated that an object is the fastest\r\n // lookup (faster than Map), and JSON.stringify is the fastest serializer.\r\n private _cache: any;\r\n private _iModel: IModelConnection;\r\n private _target: string;\r\n\r\n constructor(iModel: IModelConnection, target: string) {\r\n this._iModel = iModel;\r\n this._cache = {};\r\n this._target = target;\r\n }\r\n\r\n public async findInCacheOrRequest(request: GeoCoordinatesRequestProps): Promise<GeoCoordinatesResponseProps> {\r\n let missing: boolean = false;\r\n const response: GeoCoordinatesResponseProps = { geoCoords: [], fromCache: 0 };\r\n let remainingRequest: GeoCoordinatesRequestProps | undefined;\r\n const originalPositions: number[] = [];\r\n\r\n for (let iPoint = 0; iPoint < request.iModelCoords.length; ++iPoint) {\r\n const thisIModelCoord = request.iModelCoords[iPoint];\r\n\r\n // we use the JSON string as the key into our cache of previously returned results.\r\n const thisCacheKey = JSON.stringify(thisIModelCoord);\r\n\r\n // put something in each output that corresponds to the input.\r\n if (this._cache[thisCacheKey]) {\r\n response.geoCoords.push(this._cache[thisCacheKey]);\r\n } else {\r\n if (!remainingRequest)\r\n remainingRequest = { target: this._target, iModelCoords: [] };\r\n\r\n // add this geoCoord to the request we are going to send.\r\n remainingRequest.iModelCoords.push(thisIModelCoord);\r\n // keep track of the original position of this point.\r\n originalPositions.push(iPoint);\r\n\r\n // mark the response as pending.\r\n response.geoCoords.push({ p: [0, 0, 0], s: GeoCoordStatus.Pending });\r\n\r\n missing = true;\r\n }\r\n }\r\n\r\n // if none are missing from the cache, resolve the promise immediately\r\n if (!missing) {\r\n response.fromCache = request.iModelCoords.length;\r\n return response;\r\n } else {\r\n // keep track of how many came from the cache (mostly for tests).\r\n response.fromCache = request.iModelCoords.length - originalPositions.length;\r\n const remainingResponse = await IModelReadRpcInterface.getClientForRouting(this._iModel.routingContext.token).getGeoCoordinatesFromIModelCoordinates(this._iModel.getRpcProps(), remainingRequest!);\r\n // put the responses into the cache, and fill in the output response for each\r\n for (let iResponse = 0; iResponse < remainingResponse.geoCoords.length; ++iResponse) {\r\n const thisPoint: PointWithStatus = remainingResponse.geoCoords[iResponse];\r\n\r\n // transfer the answer stored in remainingResponse to the correct position in the overall response.\r\n const responseIndex = originalPositions[iResponse];\r\n response.geoCoords[responseIndex] = thisPoint;\r\n\r\n // put the answer in the cache.\r\n const thisIModelCoord = remainingRequest!.iModelCoords[iResponse];\r\n const thisCacheKey = JSON.stringify(thisIModelCoord);\r\n this._cache[thisCacheKey] = thisPoint;\r\n }\r\n return response;\r\n }\r\n }\r\n}\r\n\r\n/** The GeoConverter class communicates with the backend to convert longitude/latitude coordinates to iModel coordinates and vice-versa\r\n * @internal\r\n */\r\nexport class GeoConverter {\r\n private _datumOrGCRS: string;\r\n private _gCtoIMCResultCache: GCtoIMCResultCache;\r\n private _iMCtoGCResultCache: IMCtoGCResultCache;\r\n constructor(iModel: IModelConnection, datumOrGCRS: string | GeographicCRSProps) {\r\n if (typeof (datumOrGCRS) === \"object\")\r\n this._datumOrGCRS = JSON.stringify(datumOrGCRS);\r\n else\r\n this._datumOrGCRS = datumOrGCRS;\r\n this._gCtoIMCResultCache = new GCtoIMCResultCache(iModel, this._datumOrGCRS);\r\n this._iMCtoGCResultCache = new IMCtoGCResultCache(iModel, this._datumOrGCRS);\r\n }\r\n\r\n public async getIModelCoordinatesFromGeoCoordinates(geoPoints: XYZProps[]): Promise<IModelCoordinatesResponseProps> {\r\n const requestProps: IModelCoordinatesRequestProps = { source: this._datumOrGCRS, geoCoords: geoPoints };\r\n return this._gCtoIMCResultCache.findInCacheOrRequest(requestProps);\r\n }\r\n\r\n public getCachedIModelCoordinatesFromGeoCoordinates(geoPoints: XYZProps[]): CachedIModelCoordinatesResponseProps {\r\n return this._gCtoIMCResultCache.findInCache(geoPoints);\r\n }\r\n\r\n public async getGeoCoordinatesFromIModelCoordinates(iModelPoints: XYZProps[]): Promise<GeoCoordinatesResponseProps> {\r\n const requestProps: GeoCoordinatesRequestProps = { target: this._datumOrGCRS, iModelCoords: iModelPoints };\r\n return this._iMCtoGCResultCache.findInCacheOrRequest(requestProps);\r\n }\r\n}\r\n\r\n/** The Geographic Services available for an [[IModelConnection]].\r\n * @internal\r\n */\r\nexport class GeoServices {\r\n private _iModel: IModelConnection;\r\n\r\n constructor(iModel: IModelConnection) {\r\n this._iModel = iModel;\r\n }\r\n\r\n public getConverter(datumOrGCRS?: string | GeographicCRSProps): GeoConverter | undefined {\r\n return this._iModel.isOpen ? new GeoConverter(this._iModel, datumOrGCRS ? datumOrGCRS : \"\") : undefined;\r\n }\r\n}\r\n"]}
|
|
1
|
+
{"version":3,"file":"GeoServices.js","sourceRoot":"","sources":["../../src/GeoServices.ts"],"names":[],"mappings":"AAAA;;;+FAG+F;AAC/F,qBAAqB;AACrB,OAAO,EACL,MAAM,EAAE,OAAO,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AAC,WAAW,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;IAC1G,CAAC;CACF","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// cspell:ignore GCRS\r\nimport {\r\n assert, BeEvent, Dictionary, Logger, SortedArray,\r\n} from \"@itwin/core-bentley\";\r\nimport { WritableXYAndZ, XYAndZ, XYZProps } from \"@itwin/core-geometry\";\r\nimport {\r\n GeoCoordinatesResponseProps, GeoCoordStatus, GeographicCRSProps, IModelCoordinatesResponseProps, IModelReadRpcInterface, PointWithStatus,\r\n} from \"@itwin/core-common\";\r\nimport { IModelConnection } from \"./IModelConnection\";\r\nimport { FrontendLoggerCategory } from \"./FrontendLoggerCategory\";\r\n\r\n/** Options used to create a [[CoordinateConverter]].\r\n * @internal exported strictly for tests.\r\n */\r\nexport interface CoordinateConverterOptions {\r\n /** The iModel for which to perform the conversions. */\r\n iModel: IModelConnection;\r\n /** Asynchronously convert each point. The resultant array should have the same number and order of points as the input. */\r\n requestPoints: (points: XYAndZ[]) => Promise<PointWithStatus[]>;\r\n /** Maximum number of points to include in each request. Default: 300. */\r\n maxPointsPerRequest?: number;\r\n}\r\n\r\nfunction compareXYAndZ(lhs: XYAndZ, rhs: XYAndZ): number {\r\n return lhs.x - rhs.x || lhs.y - rhs.y || lhs.z - rhs.z;\r\n}\r\n\r\nfunction cloneXYAndZ(xyz: XYAndZ): XYAndZ {\r\n return { x: xyz.x, y: xyz.y, z: xyz.z };\r\n}\r\n\r\ntype CoordinateConverterState =\r\n // No pending requests.\r\n \"idle\" |\r\n // We have scheduled a requestAnimationFrame to dispatch all pending requests.\r\n \"scheduled\" |\r\n // We have dispatched all requests that were pending at the most recent requestAnimationFrame callback.\r\n \"in-flight\";\r\n\r\n/** Performs conversion of coordinates from one coordinate system to another.\r\n * A [[GeoConverter]] has a pair of these for converting between iModel coordinates and geographic coordinates.\r\n * Uses a cache to avoid repeatedly requesting the same points, and a batching strategy to avoid making frequent small requests.\r\n * The cache stores every point that was ever converted by [[convert]]. It is currently permitted to grow to unbounded size.\r\n * The batching works as follows:\r\n * When a conversion is requested via [[convert]], if all the requested points are in the cache, they are returned immediately.\r\n * Otherwise, any points not in the cache and not in the current in-flight request (if any) are placed onto the queue of pending requests.\r\n * A pending request is scheduled if one hasn't already been scheduled, via requestAnimationFrame.\r\n * In the animation frame callback, the pending requests are split into batches of no more than options.maxPointsPerRequest and dispatched to the backend.\r\n * Once the response is received, the results are loaded into and returned from the cache.\r\n * If more calls to convert occurred while the request was in flight, another request is dispatched.\r\n * @internal exported strictly for tests.\r\n */\r\nexport class CoordinateConverter {\r\n protected readonly _cache: Dictionary<XYAndZ, PointWithStatus>;\r\n protected _state: CoordinateConverterState = \"idle\";\r\n // The accumulated set of points to be converted by the next request.\r\n protected _pending: SortedArray<XYAndZ>;\r\n // The set of points that were included in the current in-flight request, if any.\r\n protected _inflight: SortedArray<XYAndZ>;\r\n // An event fired when the next request completes.\r\n protected _onCompleted = new BeEvent<() => void>();\r\n // Used for creating cache keys (XYAndZ) from XYZProps without having to allocate temporary objects.\r\n protected readonly _scratchXYZ = { x: 0, y: 0, z: 0 };\r\n protected readonly _maxPointsPerRequest: number;\r\n protected readonly _iModel: IModelConnection;\r\n protected readonly _requestPoints: (points: XYAndZ[]) => Promise<PointWithStatus[]>;\r\n\r\n protected toXYAndZ(input: XYZProps, output: WritableXYAndZ): XYAndZ {\r\n if (Array.isArray(input)) {\r\n output.x = input[0] ?? 0;\r\n output.y = input[1] ?? 0;\r\n output.z = input[2] ?? 0;\r\n } else {\r\n output.x = input.x ?? 0;\r\n output.y = input.y ?? 0;\r\n output.z = input.z ?? 0;\r\n }\r\n\r\n return output;\r\n }\r\n\r\n public constructor(opts: CoordinateConverterOptions) {\r\n this._maxPointsPerRequest = Math.max(1, opts.maxPointsPerRequest ?? 300);\r\n this._iModel = opts.iModel;\r\n this._requestPoints = opts.requestPoints;\r\n\r\n this._cache = new Dictionary<XYAndZ, PointWithStatus>(compareXYAndZ, cloneXYAndZ);\r\n this._pending = new SortedArray<XYAndZ>(compareXYAndZ, false, cloneXYAndZ);\r\n this._inflight = new SortedArray<XYAndZ>(compareXYAndZ, false, cloneXYAndZ);\r\n }\r\n\r\n protected async dispatch(): Promise<void> {\r\n assert(this._state === \"scheduled\");\r\n if (this._iModel.isClosed || this._pending.isEmpty) {\r\n this._state = \"idle\";\r\n this._onCompleted.raiseEvent();\r\n return;\r\n }\r\n\r\n this._state = \"in-flight\";\r\n\r\n // Ensure subsequently-enqueued requests listen for the *next* response to be received.\r\n const onCompleted = this._onCompleted;\r\n this._onCompleted = new BeEvent<() => void>();\r\n\r\n // Pending requests are now in flight. Start a new list of pending requests. It's cheaper to swap than to allocate new objects.\r\n const inflight = this._pending;\r\n this._pending = this._inflight;\r\n assert(this._pending.isEmpty);\r\n this._inflight = inflight;\r\n\r\n // Split requests if necessary to avoid requesting more than the maximum allowed number of points.\r\n const promises: Array<Promise<void>> = [];\r\n for (let i = 0; i < inflight.length; i += this._maxPointsPerRequest) {\r\n const requests = inflight.slice(i, i + this._maxPointsPerRequest).extractArray();\r\n const promise = this._requestPoints(requests).then((results) => {\r\n if (this._iModel.isClosed)\r\n return;\r\n\r\n if (results.length !== requests.length)\r\n Logger.logError(`${FrontendLoggerCategory.Package}.geoservices`, `requested conversion of ${requests.length} points, but received ${results.length} points`);\r\n\r\n for (let j = 0; j < results.length; j++) {\r\n if (j < requests.length)\r\n this._cache.set(requests[j], results[j]);\r\n }\r\n }).catch((err) => {\r\n Logger.logException(`${FrontendLoggerCategory.Package}.geoservices`, err);\r\n });\r\n\r\n promises.push(promise);\r\n }\r\n\r\n await Promise.all(promises);\r\n\r\n assert(this._state === \"in-flight\");\r\n this._state = \"idle\";\r\n this._inflight.clear();\r\n\r\n // If any more pending conversions arrived while awaiting this request, schedule another request.\r\n if (!this._pending.isEmpty)\r\n this.scheduleDispatch(); // eslint-disable-line @typescript-eslint/no-floating-promises\r\n\r\n // Resolve promises of all callers who were awaiting this request.\r\n onCompleted.raiseEvent();\r\n }\r\n\r\n // Add any points not present in cache to pending request list.\r\n // Return the number of points present in cache.\r\n protected enqueue(points: XYZProps[]): number {\r\n let numInCache = 0;\r\n for (const point of points) {\r\n const xyz = this.toXYAndZ(point, this._scratchXYZ);\r\n if (this._cache.get(xyz))\r\n ++numInCache;\r\n else if (!this._inflight.contains(xyz))\r\n this._pending.insert(xyz);\r\n }\r\n\r\n return numInCache;\r\n }\r\n\r\n // Obtain converted points from the cache. The assumption is that every point in `inputs` is already present in the cache.\r\n // Any point not present will be returned unconverted with an error status.\r\n protected getFromCache(inputs: XYZProps[]): PointWithStatus[] {\r\n const outputs: PointWithStatus[] = [];\r\n for (const input of inputs) {\r\n const xyz = this.toXYAndZ(input, this._scratchXYZ);\r\n let output = this._cache.get(xyz);\r\n if (!output)\r\n output = { p: { ...xyz }, s: GeoCoordStatus.CSMapError };\r\n\r\n outputs.push(output);\r\n }\r\n\r\n return outputs;\r\n }\r\n\r\n protected async scheduleDispatch(): Promise<void> {\r\n if (\"idle\" === this._state) {\r\n this._state = \"scheduled\";\r\n requestAnimationFrame(() => {\r\n this.dispatch(); // eslint-disable-line @typescript-eslint/no-floating-promises\r\n });\r\n }\r\n\r\n return new Promise((resolve) => {\r\n this._onCompleted.addOnce(() => resolve());\r\n });\r\n }\r\n\r\n public async convert(inputs: XYZProps[]): Promise<{ points: PointWithStatus[], fromCache: number }> {\r\n const fromCache = this.enqueue(inputs);\r\n assert(fromCache >= 0);\r\n assert(fromCache <= inputs.length);\r\n\r\n if (fromCache === inputs.length)\r\n return { points: this.getFromCache(inputs), fromCache };\r\n\r\n await this.scheduleDispatch();\r\n\r\n return { points: this.getFromCache(inputs), fromCache };\r\n }\r\n\r\n public findCached(inputs: XYZProps[]): CachedIModelCoordinatesResponseProps {\r\n const result: Array<PointWithStatus | undefined> = [];\r\n let missing: XYZProps[] | undefined;\r\n for (const input of inputs) {\r\n const key = this.toXYAndZ(input, this._scratchXYZ);\r\n const output = this._cache.get(key);\r\n result.push(output);\r\n if (!output) {\r\n if (!missing)\r\n missing = [];\r\n\r\n missing.push(input);\r\n }\r\n }\r\n\r\n return { result, missing };\r\n }\r\n}\r\n\r\n/** Response to a request to obtain imodel coordinates from cache.\r\n * @internal\r\n */\r\nexport interface CachedIModelCoordinatesResponseProps {\r\n /** An array of the same length as the input array, with undefined entries at indices corresponding to points not found in cache. */\r\n result: Array<PointWithStatus | undefined>;\r\n /** An array of points in the input array which were not found in the cache, or undefined if all points were found in the cache. */\r\n missing?: XYZProps[];\r\n}\r\n\r\n/** The GeoConverter class communicates with the backend to convert longitude/latitude coordinates to iModel coordinates and vice-versa\r\n * @internal\r\n */\r\nexport class GeoConverter {\r\n private readonly _geoToIModel: CoordinateConverter;\r\n private readonly _iModelToGeo: CoordinateConverter;\r\n\r\n constructor(iModel: IModelConnection, datumOrGCRS: string | GeographicCRSProps) {\r\n const datum = typeof datumOrGCRS === \"object\" ? JSON.stringify(datumOrGCRS) : datumOrGCRS;\r\n\r\n this._geoToIModel = new CoordinateConverter({\r\n iModel,\r\n requestPoints: async (geoCoords: XYAndZ[]) => {\r\n const request = { source: datum, geoCoords };\r\n const rpc = IModelReadRpcInterface.getClientForRouting(iModel.routingContext.token);\r\n const response = await rpc.getIModelCoordinatesFromGeoCoordinates(iModel.getRpcProps(), request);\r\n return response.iModelCoords;\r\n },\r\n });\r\n\r\n this._iModelToGeo = new CoordinateConverter({\r\n iModel,\r\n requestPoints: async (iModelCoords: XYAndZ[]) => {\r\n const request = { target: datum, iModelCoords };\r\n const rpc = IModelReadRpcInterface.getClientForRouting(iModel.routingContext.token);\r\n const response = await rpc.getGeoCoordinatesFromIModelCoordinates(iModel.getRpcProps(), request);\r\n return response.geoCoords;\r\n },\r\n });\r\n }\r\n\r\n public async getIModelCoordinatesFromGeoCoordinates(geoPoints: XYZProps[]): Promise<IModelCoordinatesResponseProps> {\r\n const result = await this._geoToIModel.convert(geoPoints);\r\n return {\r\n iModelCoords: result.points,\r\n fromCache: result.fromCache,\r\n };\r\n }\r\n\r\n public async getGeoCoordinatesFromIModelCoordinates(iModelPoints: XYZProps[]): Promise<GeoCoordinatesResponseProps> {\r\n const result = await this._iModelToGeo.convert(iModelPoints);\r\n return {\r\n geoCoords: result.points,\r\n fromCache: result.fromCache,\r\n };\r\n }\r\n\r\n public getCachedIModelCoordinatesFromGeoCoordinates(geoPoints: XYZProps[]): CachedIModelCoordinatesResponseProps {\r\n return this._geoToIModel.findCached(geoPoints);\r\n }\r\n}\r\n\r\n/** The Geographic Services available for an [[IModelConnection]].\r\n * @internal\r\n */\r\nexport class GeoServices {\r\n private _iModel: IModelConnection;\r\n\r\n constructor(iModel: IModelConnection) {\r\n this._iModel = iModel;\r\n }\r\n\r\n public getConverter(datumOrGCRS?: string | GeographicCRSProps): GeoConverter | undefined {\r\n return this._iModel.isOpen ? new GeoConverter(this._iModel, datumOrGCRS ? datumOrGCRS : \"\") : undefined;\r\n }\r\n}\r\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Request.d.ts","sourceRoot":"","sources":["../../../src/request/Request.ts"],"names":[],"mappings":";
|
|
1
|
+
{"version":3,"file":"Request.d.ts","sourceRoot":"","sources":["../../../src/request/Request.ts"],"names":[],"mappings":";AAQA,OAAO,KAAK,KAAK,MAAM,OAAO,CAAC;AAG/B,OAAO,EAAE,YAAY,EAAE,mBAAmB,EAAE,UAAU,EAAoB,MAAM,qBAAqB,CAAC;AAQtG,gBAAgB;AAChB,eAAO,MAAM,mBAAmB,qBAAqB,CAAC;AAEtD,gBAAgB;AAChB,MAAM,WAAW,uBAAuB;IACtC,IAAI,EAAE,MAAM,CAAC;IACb,QAAQ,EAAE,MAAM,CAAC;CAClB;AAED;;;GAGG;AACH,MAAM,WAAW,mBAAmB;IAClC;;;O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AAK,CAAC,CAAC;QACzC,MAAM,WAAW,CAAC;KACnB;AACH,CAAC;AAED;;;;GAIG;AACH,MAAM,CAAC,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","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 deepAssign from \"deep-assign\";\r\nimport * as _ from \"lodash\";\r\nimport * as https from \"https\";\r\nimport { IStringifyOptions, stringify } from \"qs\";\r\nimport * as sarequest from \"superagent\";\r\nimport { BentleyError, GetMetaDataFunction, HttpStatus, Logger, LogLevel } from \"@itwin/core-bentley\";\r\nimport { FrontendLoggerCategory } from \"../FrontendLoggerCategory\";\r\n\r\nconst loggerCategory: string = FrontendLoggerCategory.Request;\r\n\r\n// CMS TODO: Move this entire wrapper to the frontend for use in the map/tile requests. Replace it with\r\n// just using fetch directly as it is only ever used browser side.\r\n\r\n/** @internal */\r\nexport const requestIdHeaderName = \"X-Correlation-Id\";\r\n\r\n/** @internal */\r\nexport interface RequestBasicCredentials { // axios: AxiosBasicCredentials\r\n user: string; // axios: username\r\n password: string; // axios: password\r\n}\r\n\r\n/** Typical option to query REST API. Note that services may not quite support these fields,\r\n * and the interface is only provided as a hint.\r\n * @internal\r\n */\r\nexport interface RequestQueryOptions {\r\n /**\r\n * Select string used by the query (use the mapped EC property names, and not TypeScript property names)\r\n * Example: \"Name,Size,Description\"\r\n */\r\n $select?: string;\r\n\r\n /**\r\n * Filter string used by the query (use the mapped EC property names, and not TypeScript property names)\r\n * Example: \"Name like '*.pdf' and Size lt 1000\"\r\n */\r\n $filter?: string;\r\n\r\n /** Sets the limit on the number of entries to be returned by the query */\r\n $top?: number;\r\n\r\n /** Sets the number of entries to be skipped */\r\n $skip?: number;\r\n\r\n /**\r\n * Orders the return values (use the mapped EC property names, and not TypeScript property names)\r\n * Example: \"Size desc\"\r\n */\r\n $orderby?: string;\r\n\r\n /**\r\n * Sets the limit on the number of entries to be returned by a single response.\r\n * Can be used with a Top option. For example if Top is set to 1000 and PageSize\r\n * is set to 100 then 10 requests will be performed to get result.\r\n */\r\n $pageSize?: number;\r\n}\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 auth?: RequestBasicCredentials;\r\n body?: any;\r\n qs?: any | RequestQueryOptions;\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/** @internal */\r\nexport class RequestGlobalOptions {\r\n public static httpsProxy?: https.Agent = undefined;\r\n /** Creates an agent for any user defined proxy using the supplied additional options. Returns undefined if user hasn't defined a proxy.\r\n * @internal\r\n */\r\n public static createHttpsProxy: (additionalOptions?: https.AgentOptions) => https.Agent | undefined = (_additionalOptions?: https.AgentOptions) => undefined;\r\n public static maxRetries: number = 4;\r\n public static timeout: RequestTimeoutOptions = {\r\n deadline: 25000,\r\n response: 10000,\r\n };\r\n // Assume application is online or offline. This hint skip retry/timeout\r\n public static online: boolean = true;\r\n}\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 deepAssign.default(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 if (!RequestGlobalOptions.online) {\r\n throw new ResponseError(503, \"Service unavailable\");\r\n }\r\n\r\n let sareq: sarequest.SuperAgentRequest = sarequest.default(options.method, url);\r\n const retries = typeof options.retries === \"undefined\" ? RequestGlobalOptions.maxRetries : options.retries;\r\n sareq = sareq.retry(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 let queryStr: string = \"\";\r\n let fullUrl: string = \"\";\r\n if (options.qs && Object.keys(options.qs).length > 0) {\r\n const stringifyOptions: IStringifyOptions = { delimiter: \"&\", encode: false };\r\n queryStr = stringify(options.qs, stringifyOptions);\r\n sareq = sareq.query(queryStr);\r\n fullUrl = `${url}?${queryStr}`;\r\n } else {\r\n fullUrl = url;\r\n }\r\n\r\n Logger.logInfo(loggerCategory, fullUrl);\r\n\r\n if (options.auth)\r\n sareq = sareq.auth(options.auth.user, options.auth.password);\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 else\r\n sareq = sareq.timeout(RequestGlobalOptions.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 else if (RequestGlobalOptions.httpsProxy)\r\n sareq = sareq.agent(RequestGlobalOptions.httpsProxy);\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/request/Request.ts"],"names":[],"mappings":"AAAA;;;+FAG+F;AAC/F;;GAEG;AACH,OAAO,KAAK,UAAU,MAAM,aAAa,CAAC;AAE1C,OAAO,EAAqB,SAAS,EAAE,MAAM,IAAI,CAAC;AAClD,OAAO,KAAK,SAAS,MAAM,YAAY,CAAC;AACxC,OAAO,EAAE,YAAY,EAAuB,UAAU,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,qBAAqB,CAAC;AACtG,OAAO,EAAE,sBAAsB,EAAE,MAAM,2BAA2B,CAAC;AAEnE,MAAM,cAAc,GAAW,sBAAsB,CAAC,OAAO,CAAC;AAE9D,uGAAuG;AACvG,kEAAkE;AAElE,gBAAgB;AAChB,MAAM,CAAC,MAAM,mBAAmB,GAAG,kBA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AQ,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;AAED;;;;GAIG;AACH,MAAM,CAAC,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","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 deepAssign from \"deep-assign\";\r\nimport * as https from \"https\";\r\nimport { IStringifyOptions, stringify } from \"qs\";\r\nimport * as sarequest from \"superagent\";\r\nimport { BentleyError, GetMetaDataFunction, HttpStatus, Logger, LogLevel } from \"@itwin/core-bentley\";\r\nimport { FrontendLoggerCategory } from \"../FrontendLoggerCategory\";\r\n\r\nconst loggerCategory: string = FrontendLoggerCategory.Request;\r\n\r\n// CMS TODO: Move this entire wrapper to the frontend for use in the map/tile requests. Replace it with\r\n// just using fetch directly as it is only ever used browser side.\r\n\r\n/** @internal */\r\nexport const requestIdHeaderName = \"X-Correlation-Id\";\r\n\r\n/** @internal */\r\nexport interface RequestBasicCredentials { // axios: AxiosBasicCredentials\r\n user: string; // axios: username\r\n password: string; // axios: password\r\n}\r\n\r\n/** Typical option to query REST API. Note that services may not quite support these fields,\r\n * and the interface is only provided as a hint.\r\n * @internal\r\n */\r\nexport interface RequestQueryOptions {\r\n /**\r\n * Select string used by the query (use the mapped EC property names, and not TypeScript property names)\r\n * Example: \"Name,Size,Description\"\r\n */\r\n $select?: string;\r\n\r\n /**\r\n * Filter string used by the query (use the mapped EC property names, and not TypeScript property names)\r\n * Example: \"Name like '*.pdf' and Size lt 1000\"\r\n */\r\n $filter?: string;\r\n\r\n /** Sets the limit on the number of entries to be returned by the query */\r\n $top?: number;\r\n\r\n /** Sets the number of entries to be skipped */\r\n $skip?: number;\r\n\r\n /**\r\n * Orders the return values (use the mapped EC property names, and not TypeScript property names)\r\n * Example: \"Size desc\"\r\n */\r\n $orderby?: string;\r\n\r\n /**\r\n * Sets the limit on the number of entries to be returned by a single response.\r\n * Can be used with a Top option. For example if Top is set to 1000 and PageSize\r\n * is set to 100 then 10 requests will be performed to get result.\r\n */\r\n $pageSize?: number;\r\n}\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 auth?: RequestBasicCredentials;\r\n body?: any;\r\n qs?: any | RequestQueryOptions;\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/** @internal */\r\nexport class RequestGlobalOptions {\r\n public static httpsProxy?: https.Agent = undefined;\r\n /** Creates an agent for any user defined proxy using the supplied additional options. Returns undefined if user hasn't defined a proxy.\r\n * @internal\r\n */\r\n public static createHttpsProxy: (additionalOptions?: https.AgentOptions) => https.Agent | undefined = (_additionalOptions?: https.AgentOptions) => undefined;\r\n public static maxRetries: number = 4;\r\n public static timeout: RequestTimeoutOptions = {\r\n deadline: 25000,\r\n response: 10000,\r\n };\r\n // Assume application is online or offline. This hint skip retry/timeout\r\n public static online: boolean = true;\r\n}\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 deepAssign.default(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 if (!RequestGlobalOptions.online) {\r\n throw new ResponseError(503, \"Service unavailable\");\r\n }\r\n\r\n let sareq: sarequest.SuperAgentRequest = sarequest.default(options.method, url);\r\n const retries = typeof options.retries === \"undefined\" ? RequestGlobalOptions.maxRetries : options.retries;\r\n sareq = sareq.retry(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 let queryStr: string = \"\";\r\n let fullUrl: string = \"\";\r\n if (options.qs && Object.keys(options.qs).length > 0) {\r\n const stringifyOptions: IStringifyOptions = { delimiter: \"&\", encode: false };\r\n queryStr = stringify(options.qs, stringifyOptions);\r\n sareq = sareq.query(queryStr);\r\n fullUrl = `${url}?${queryStr}`;\r\n } else {\r\n fullUrl = url;\r\n }\r\n\r\n Logger.logInfo(loggerCategory, fullUrl);\r\n\r\n if (options.auth)\r\n sareq = sareq.auth(options.auth.user, options.auth.password);\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 else\r\n sareq = sareq.timeout(RequestGlobalOptions.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 else if (RequestGlobalOptions.httpsProxy)\r\n sareq = sareq.agent(RequestGlobalOptions.httpsProxy);\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"]}
|
|
@@ -803,7 +803,7 @@ export class GltfReader {
|
|
|
803
803
|
readMeshPrimitive(primitive, featureTable, pseudoRtcBias) {
|
|
804
804
|
var _a, _b, _c, _d, _e, _f, _g, _h, _j;
|
|
805
805
|
const materialName = JsonUtils.asString(primitive.material);
|
|
806
|
-
const material = 0 < materialName.length ? this._materials[materialName] :
|
|
806
|
+
const material = 0 < materialName.length ? this._materials[materialName] : {};
|
|
807
807
|
if (!material)
|
|
808
808
|
return undefined;
|
|
809
809
|
const hasBakedLighting = undefined === primitive.attributes.NORMAL || undefined !== ((_a = material.extensions) === null || _a === void 0 ? void 0 : _a.KHR_materials_unlit);
|