@loaders.gl/loader-utils 3.1.3 → 4.0.0-alpha.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (144) hide show
  1. package/dist/index.js +26 -111
  2. package/dist/index.js.map +1 -0
  3. package/dist/json-loader.js +18 -25
  4. package/dist/json-loader.js.map +1 -0
  5. package/dist/lib/binary-utils/array-buffer-utils.js +79 -108
  6. package/dist/lib/binary-utils/array-buffer-utils.js.map +1 -0
  7. package/dist/lib/binary-utils/binary-copy-utils.js +22 -48
  8. package/dist/lib/binary-utils/binary-copy-utils.js.map +1 -0
  9. package/dist/lib/binary-utils/buffer-utils.js +13 -47
  10. package/dist/lib/binary-utils/buffer-utils.js.map +1 -0
  11. package/dist/lib/binary-utils/encode-utils.js +26 -30
  12. package/dist/lib/binary-utils/encode-utils.js.map +1 -0
  13. package/dist/lib/binary-utils/get-first-characters.js +25 -28
  14. package/dist/lib/binary-utils/get-first-characters.js.map +1 -0
  15. package/dist/lib/binary-utils/memory-copy-utils.js +24 -58
  16. package/dist/lib/binary-utils/memory-copy-utils.js.map +1 -0
  17. package/dist/lib/env-utils/assert.js +5 -12
  18. package/dist/lib/env-utils/assert.js.map +1 -0
  19. package/dist/lib/env-utils/globals.js +9 -23
  20. package/dist/lib/env-utils/globals.js.map +1 -0
  21. package/dist/lib/filesystems/node-filesystem.js +59 -68
  22. package/dist/lib/filesystems/node-filesystem.js.map +1 -0
  23. package/dist/lib/iterators/async-iteration.js +35 -49
  24. package/dist/lib/iterators/async-iteration.js.map +1 -0
  25. package/dist/lib/iterators/text-iterators.js +41 -56
  26. package/dist/lib/iterators/text-iterators.js.map +1 -0
  27. package/dist/lib/node/buffer.js +25 -33
  28. package/dist/lib/node/buffer.js.map +1 -0
  29. package/dist/lib/node/fs.js +40 -46
  30. package/dist/lib/node/fs.js.map +1 -0
  31. package/dist/lib/node/util.js +3 -25
  32. package/dist/lib/node/util.js.map +1 -0
  33. package/dist/lib/parser-utils/parse-json.js +8 -15
  34. package/dist/lib/parser-utils/parse-json.js.map +1 -0
  35. package/dist/lib/path-utils/file-aliases.js +19 -40
  36. package/dist/lib/path-utils/file-aliases.js.map +1 -0
  37. package/dist/lib/path-utils/path.js +21 -37
  38. package/dist/lib/path-utils/path.js.map +1 -0
  39. package/dist/lib/request-utils/request-scheduler.js +131 -127
  40. package/dist/lib/request-utils/request-scheduler.js.map +1 -0
  41. package/dist/lib/worker-loader-utils/create-loader-worker.js +96 -91
  42. package/dist/lib/worker-loader-utils/create-loader-worker.js.map +1 -0
  43. package/dist/lib/worker-loader-utils/parse-with-worker.js +60 -69
  44. package/dist/lib/worker-loader-utils/parse-with-worker.js.map +1 -0
  45. package/dist/types.js +2 -3
  46. package/dist/{es5/types.js.map → types.js.map} +0 -0
  47. package/dist/workers/json-worker.js +4 -5
  48. package/dist/workers/json-worker.js.map +1 -0
  49. package/package.json +5 -5
  50. package/dist/es5/index.js +0 -325
  51. package/dist/es5/index.js.map +0 -1
  52. package/dist/es5/json-loader.js +0 -57
  53. package/dist/es5/json-loader.js.map +0 -1
  54. package/dist/es5/lib/binary-utils/array-buffer-utils.js +0 -137
  55. package/dist/es5/lib/binary-utils/array-buffer-utils.js.map +0 -1
  56. package/dist/es5/lib/binary-utils/binary-copy-utils.js +0 -35
  57. package/dist/es5/lib/binary-utils/binary-copy-utils.js.map +0 -1
  58. package/dist/es5/lib/binary-utils/buffer-utils.js +0 -38
  59. package/dist/es5/lib/binary-utils/buffer-utils.js.map +0 -1
  60. package/dist/es5/lib/binary-utils/encode-utils.js +0 -42
  61. package/dist/es5/lib/binary-utils/encode-utils.js.map +0 -1
  62. package/dist/es5/lib/binary-utils/get-first-characters.js +0 -38
  63. package/dist/es5/lib/binary-utils/get-first-characters.js.map +0 -1
  64. package/dist/es5/lib/binary-utils/memory-copy-utils.js +0 -40
  65. package/dist/es5/lib/binary-utils/memory-copy-utils.js.map +0 -1
  66. package/dist/es5/lib/env-utils/assert.js +0 -13
  67. package/dist/es5/lib/env-utils/assert.js.map +0 -1
  68. package/dist/es5/lib/env-utils/globals.js +0 -33
  69. package/dist/es5/lib/env-utils/globals.js.map +0 -1
  70. package/dist/es5/lib/filesystems/node-filesystem.js +0 -267
  71. package/dist/es5/lib/filesystems/node-filesystem.js.map +0 -1
  72. package/dist/es5/lib/iterators/async-iteration.js +0 -266
  73. package/dist/es5/lib/iterators/async-iteration.js.map +0 -1
  74. package/dist/es5/lib/iterators/text-iterators.js +0 -434
  75. package/dist/es5/lib/iterators/text-iterators.js.map +0 -1
  76. package/dist/es5/lib/node/buffer.js +0 -38
  77. package/dist/es5/lib/node/buffer.js.map +0 -1
  78. package/dist/es5/lib/node/fs.js +0 -97
  79. package/dist/es5/lib/node/fs.js.map +0 -1
  80. package/dist/es5/lib/node/util.js +0 -18
  81. package/dist/es5/lib/node/util.js.map +0 -1
  82. package/dist/es5/lib/parser-utils/parse-json.js +0 -17
  83. package/dist/es5/lib/parser-utils/parse-json.js.map +0 -1
  84. package/dist/es5/lib/path-utils/file-aliases.js +0 -39
  85. package/dist/es5/lib/path-utils/file-aliases.js.map +0 -1
  86. package/dist/es5/lib/path-utils/path.js +0 -39
  87. package/dist/es5/lib/path-utils/path.js.map +0 -1
  88. package/dist/es5/lib/request-utils/request-scheduler.js +0 -182
  89. package/dist/es5/lib/request-utils/request-scheduler.js.map +0 -1
  90. package/dist/es5/lib/worker-loader-utils/create-loader-worker.js +0 -186
  91. package/dist/es5/lib/worker-loader-utils/create-loader-worker.js.map +0 -1
  92. package/dist/es5/lib/worker-loader-utils/parse-with-worker.js +0 -137
  93. package/dist/es5/lib/worker-loader-utils/parse-with-worker.js.map +0 -1
  94. package/dist/es5/types.js +0 -2
  95. package/dist/es5/workers/json-worker.js +0 -8
  96. package/dist/es5/workers/json-worker.js.map +0 -1
  97. package/dist/esm/index.js +0 -26
  98. package/dist/esm/index.js.map +0 -1
  99. package/dist/esm/json-loader.js +0 -21
  100. package/dist/esm/json-loader.js.map +0 -1
  101. package/dist/esm/lib/binary-utils/array-buffer-utils.js +0 -86
  102. package/dist/esm/lib/binary-utils/array-buffer-utils.js.map +0 -1
  103. package/dist/esm/lib/binary-utils/binary-copy-utils.js +0 -25
  104. package/dist/esm/lib/binary-utils/binary-copy-utils.js.map +0 -1
  105. package/dist/esm/lib/binary-utils/buffer-utils.js +0 -16
  106. package/dist/esm/lib/binary-utils/buffer-utils.js.map +0 -1
  107. package/dist/esm/lib/binary-utils/encode-utils.js +0 -31
  108. package/dist/esm/lib/binary-utils/encode-utils.js.map +0 -1
  109. package/dist/esm/lib/binary-utils/get-first-characters.js +0 -27
  110. package/dist/esm/lib/binary-utils/get-first-characters.js.map +0 -1
  111. package/dist/esm/lib/binary-utils/memory-copy-utils.js +0 -27
  112. package/dist/esm/lib/binary-utils/memory-copy-utils.js.map +0 -1
  113. package/dist/esm/lib/env-utils/assert.js +0 -6
  114. package/dist/esm/lib/env-utils/assert.js.map +0 -1
  115. package/dist/esm/lib/env-utils/globals.js +0 -16
  116. package/dist/esm/lib/env-utils/globals.js.map +0 -1
  117. package/dist/esm/lib/filesystems/node-filesystem.js +0 -60
  118. package/dist/esm/lib/filesystems/node-filesystem.js.map +0 -1
  119. package/dist/esm/lib/iterators/async-iteration.js +0 -39
  120. package/dist/esm/lib/iterators/async-iteration.js.map +0 -1
  121. package/dist/esm/lib/iterators/text-iterators.js +0 -46
  122. package/dist/esm/lib/iterators/text-iterators.js.map +0 -1
  123. package/dist/esm/lib/node/buffer.js +0 -28
  124. package/dist/esm/lib/node/buffer.js.map +0 -1
  125. package/dist/esm/lib/node/fs.js +0 -42
  126. package/dist/esm/lib/node/fs.js.map +0 -1
  127. package/dist/esm/lib/node/util.js +0 -3
  128. package/dist/esm/lib/node/util.js.map +0 -1
  129. package/dist/esm/lib/parser-utils/parse-json.js +0 -9
  130. package/dist/esm/lib/parser-utils/parse-json.js.map +0 -1
  131. package/dist/esm/lib/path-utils/file-aliases.js +0 -26
  132. package/dist/esm/lib/path-utils/file-aliases.js.map +0 -1
  133. package/dist/esm/lib/path-utils/path.js +0 -24
  134. package/dist/esm/lib/path-utils/path.js.map +0 -1
  135. package/dist/esm/lib/request-utils/request-scheduler.js +0 -146
  136. package/dist/esm/lib/request-utils/request-scheduler.js.map +0 -1
  137. package/dist/esm/lib/worker-loader-utils/create-loader-worker.js +0 -102
  138. package/dist/esm/lib/worker-loader-utils/create-loader-worker.js.map +0 -1
  139. package/dist/esm/lib/worker-loader-utils/parse-with-worker.js +0 -64
  140. package/dist/esm/lib/worker-loader-utils/parse-with-worker.js.map +0 -1
  141. package/dist/esm/types.js +0 -2
  142. package/dist/esm/types.js.map +0 -1
  143. package/dist/esm/workers/json-worker.js +0 -4
  144. package/dist/esm/workers/json-worker.js.map +0 -1
@@ -1,142 +1,146 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- const stats_1 = require("@probe.gl/stats");
1
+ import _defineProperty from "@babel/runtime/helpers/esm/defineProperty";
2
+ import { Stats } from '@probe.gl/stats';
4
3
  const STAT_QUEUED_REQUESTS = 'Queued Requests';
5
4
  const STAT_ACTIVE_REQUESTS = 'Active Requests';
6
5
  const STAT_CANCELLED_REQUESTS = 'Cancelled Requests';
7
6
  const STAT_QUEUED_REQUESTS_EVER = 'Queued Requests Ever';
8
7
  const STAT_ACTIVE_REQUESTS_EVER = 'Active Requests Ever';
9
8
  const DEFAULT_PROPS = {
10
- id: 'request-scheduler',
11
- // Specifies if the request scheduler should throttle incoming requests, mainly for comparative testing
12
- throttleRequests: true,
13
- // The maximum number of simultaneous active requests. Un-throttled requests do not observe this limit.
14
- maxRequests: 6
9
+ id: 'request-scheduler',
10
+ throttleRequests: true,
11
+ maxRequests: 6
15
12
  };
16
- /**
17
- * Used to issue a request, without having them "deeply queued" by the browser.
18
- * @todo - Track requests globally, across multiple servers
19
- */
20
- class RequestScheduler {
21
- constructor(props = {}) {
22
- this.activeRequestCount = 0;
23
- /** Tracks the number of active requests and prioritizes/cancels queued requests. */
24
- this.requestQueue = [];
25
- this.requestMap = new Map();
26
- this.deferredUpdate = null;
27
- this.props = { ...DEFAULT_PROPS, ...props };
28
- // Returns the statistics used by the request scheduler.
29
- this.stats = new stats_1.Stats({ id: this.props.id });
30
- this.stats.get(STAT_QUEUED_REQUESTS);
31
- this.stats.get(STAT_ACTIVE_REQUESTS);
32
- this.stats.get(STAT_CANCELLED_REQUESTS);
33
- this.stats.get(STAT_QUEUED_REQUESTS_EVER);
34
- this.stats.get(STAT_ACTIVE_REQUESTS_EVER);
13
+ export default class RequestScheduler {
14
+ constructor(props = {}) {
15
+ _defineProperty(this, "props", void 0);
16
+
17
+ _defineProperty(this, "stats", void 0);
18
+
19
+ _defineProperty(this, "activeRequestCount", 0);
20
+
21
+ _defineProperty(this, "requestQueue", []);
22
+
23
+ _defineProperty(this, "requestMap", new Map());
24
+
25
+ _defineProperty(this, "deferredUpdate", null);
26
+
27
+ this.props = { ...DEFAULT_PROPS,
28
+ ...props
29
+ };
30
+ this.stats = new Stats({
31
+ id: this.props.id
32
+ });
33
+ this.stats.get(STAT_QUEUED_REQUESTS);
34
+ this.stats.get(STAT_ACTIVE_REQUESTS);
35
+ this.stats.get(STAT_CANCELLED_REQUESTS);
36
+ this.stats.get(STAT_QUEUED_REQUESTS_EVER);
37
+ this.stats.get(STAT_ACTIVE_REQUESTS_EVER);
38
+ }
39
+
40
+ scheduleRequest(handle, getPriority = () => 0) {
41
+ if (!this.props.throttleRequests) {
42
+ return Promise.resolve({
43
+ done: () => {}
44
+ });
35
45
  }
36
- /**
37
- * Called by an application that wants to issue a request, without having it deeply queued by the browser
38
- *
39
- * When the returned promise resolved, it is OK for the application to issue a request.
40
- * The promise resolves to an object that contains a `done` method.
41
- * When the application's request has completed (or failed), the application must call the `done` function
42
- *
43
- * @param handle
44
- * @param getPriority will be called when request "slots" open up,
45
- * allowing the caller to update priority or cancel the request
46
- * Highest priority executes first, priority < 0 cancels the request
47
- * @returns a promise
48
- * - resolves to a object (with a `done` field) when the request can be issued without queueing,
49
- * - resolves to `null` if the request has been cancelled (by the callback return < 0).
50
- * In this case the application should not issue the request
51
- */
52
- scheduleRequest(handle, getPriority = () => 0) {
53
- // Allows throttling to be disabled
54
- if (!this.props.throttleRequests) {
55
- return Promise.resolve({ done: () => { } });
56
- }
57
- // dedupe
58
- if (this.requestMap.has(handle)) {
59
- return this.requestMap.get(handle);
60
- }
61
- const request = { handle, priority: 0, getPriority };
62
- const promise = new Promise((resolve) => {
63
- // @ts-ignore
64
- request.resolve = resolve;
65
- return request;
66
- });
67
- this.requestQueue.push(request);
68
- this.requestMap.set(handle, promise);
69
- this._issueNewRequests();
70
- return promise;
46
+
47
+ if (this.requestMap.has(handle)) {
48
+ return this.requestMap.get(handle);
71
49
  }
72
- // PRIVATE
73
- _issueRequest(request) {
74
- const { handle, resolve } = request;
75
- let isDone = false;
76
- const done = () => {
77
- // can only be called once
78
- if (!isDone) {
79
- isDone = true;
80
- // Stop tracking a request - it has completed, failed, cancelled etc
81
- this.requestMap.delete(handle);
82
- this.activeRequestCount--;
83
- // A slot just freed up, see if any queued requests are waiting
84
- this._issueNewRequests();
85
- }
86
- };
87
- // Track this request
88
- this.activeRequestCount++;
89
- return resolve ? resolve({ done }) : Promise.resolve({ done });
50
+
51
+ const request = {
52
+ handle,
53
+ priority: 0,
54
+ getPriority
55
+ };
56
+ const promise = new Promise(resolve => {
57
+ request.resolve = resolve;
58
+ return request;
59
+ });
60
+ this.requestQueue.push(request);
61
+ this.requestMap.set(handle, promise);
62
+
63
+ this._issueNewRequests();
64
+
65
+ return promise;
66
+ }
67
+
68
+ _issueRequest(request) {
69
+ const {
70
+ handle,
71
+ resolve
72
+ } = request;
73
+ let isDone = false;
74
+
75
+ const done = () => {
76
+ if (!isDone) {
77
+ isDone = true;
78
+ this.requestMap.delete(handle);
79
+ this.activeRequestCount--;
80
+
81
+ this._issueNewRequests();
82
+ }
83
+ };
84
+
85
+ this.activeRequestCount++;
86
+ return resolve ? resolve({
87
+ done
88
+ }) : Promise.resolve({
89
+ done
90
+ });
91
+ }
92
+
93
+ _issueNewRequests() {
94
+ if (!this.deferredUpdate) {
95
+ this.deferredUpdate = setTimeout(() => this._issueNewRequestsAsync(), 0);
90
96
  }
91
- /** We check requests asynchronously, to prevent multiple updates */
92
- _issueNewRequests() {
93
- if (!this.deferredUpdate) {
94
- this.deferredUpdate = setTimeout(() => this._issueNewRequestsAsync(), 0);
95
- }
97
+ }
98
+
99
+ _issueNewRequestsAsync() {
100
+ this.deferredUpdate = null;
101
+ const freeSlots = Math.max(this.props.maxRequests - this.activeRequestCount, 0);
102
+
103
+ if (freeSlots === 0) {
104
+ return;
96
105
  }
97
- /** Refresh all requests */
98
- _issueNewRequestsAsync() {
99
- // TODO - shouldn't we clear the timeout?
100
- this.deferredUpdate = null;
101
- const freeSlots = Math.max(this.props.maxRequests - this.activeRequestCount, 0);
102
- if (freeSlots === 0) {
103
- return;
104
- }
105
- this._updateAllRequests();
106
- // Resolve pending promises for the top-priority requests
107
- for (let i = 0; i < freeSlots; ++i) {
108
- const request = this.requestQueue.shift();
109
- if (request) {
110
- this._issueRequest(request); // eslint-disable-line @typescript-eslint/no-floating-promises
111
- }
112
- }
113
- // Uncomment to debug
114
- // console.log(`${freeSlots} free slots, ${this.requestQueue.length} queued requests`);
106
+
107
+ this._updateAllRequests();
108
+
109
+ for (let i = 0; i < freeSlots; ++i) {
110
+ const request = this.requestQueue.shift();
111
+
112
+ if (request) {
113
+ this._issueRequest(request);
114
+ }
115
115
  }
116
- /** Ensure all requests have updated priorities, and that no longer valid requests are cancelled */
117
- _updateAllRequests() {
118
- const requestQueue = this.requestQueue;
119
- for (let i = 0; i < requestQueue.length; ++i) {
120
- const request = requestQueue[i];
121
- if (!this._updateRequest(request)) {
122
- // Remove the element and make sure to adjust the counter to account for shortened array
123
- requestQueue.splice(i, 1);
124
- this.requestMap.delete(request.handle);
125
- i--;
126
- }
127
- }
128
- // Sort the remaining requests based on priority
129
- requestQueue.sort((a, b) => a.priority - b.priority);
116
+ }
117
+
118
+ _updateAllRequests() {
119
+ const requestQueue = this.requestQueue;
120
+
121
+ for (let i = 0; i < requestQueue.length; ++i) {
122
+ const request = requestQueue[i];
123
+
124
+ if (!this._updateRequest(request)) {
125
+ requestQueue.splice(i, 1);
126
+ this.requestMap.delete(request.handle);
127
+ i--;
128
+ }
130
129
  }
131
- /** Update a single request by calling the callback */
132
- _updateRequest(request) {
133
- request.priority = request.getPriority(request.handle); // eslint-disable-line callback-return
134
- // by returning a negative priority, the callback cancels the request
135
- if (request.priority < 0) {
136
- request.resolve(null);
137
- return false;
138
- }
139
- return true;
130
+
131
+ requestQueue.sort((a, b) => a.priority - b.priority);
132
+ }
133
+
134
+ _updateRequest(request) {
135
+ request.priority = request.getPriority(request.handle);
136
+
137
+ if (request.priority < 0) {
138
+ request.resolve(null);
139
+ return false;
140
140
  }
141
+
142
+ return true;
143
+ }
144
+
141
145
  }
142
- exports.default = RequestScheduler;
146
+ //# sourceMappingURL=request-scheduler.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../src/lib/request-utils/request-scheduler.ts"],"names":["Stats","STAT_QUEUED_REQUESTS","STAT_ACTIVE_REQUESTS","STAT_CANCELLED_REQUESTS","STAT_QUEUED_REQUESTS_EVER","STAT_ACTIVE_REQUESTS_EVER","DEFAULT_PROPS","id","throttleRequests","maxRequests","RequestScheduler","constructor","props","Map","stats","get","scheduleRequest","handle","getPriority","Promise","resolve","done","requestMap","has","request","priority","promise","requestQueue","push","set","_issueNewRequests","_issueRequest","isDone","delete","activeRequestCount","deferredUpdate","setTimeout","_issueNewRequestsAsync","freeSlots","Math","max","_updateAllRequests","i","shift","length","_updateRequest","splice","sort","a","b"],"mappings":";AAAA,SAAQA,KAAR,QAAoB,iBAApB;AAgBA,MAAMC,oBAAoB,GAAG,iBAA7B;AACA,MAAMC,oBAAoB,GAAG,iBAA7B;AACA,MAAMC,uBAAuB,GAAG,oBAAhC;AACA,MAAMC,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ype DoneFunction = () => any;\ntype GetPriorityFunction = () => number;\ntype RequestResult = {\n done: DoneFunction;\n} | null;\n\n/** RequestScheduler Options */\nexport type RequestSchedulerProps = {\n id?: string;\n throttleRequests?: boolean;\n maxRequests?: number;\n};\n\nconst STAT_QUEUED_REQUESTS = 'Queued Requests';\nconst STAT_ACTIVE_REQUESTS = 'Active Requests';\nconst STAT_CANCELLED_REQUESTS = 'Cancelled Requests';\nconst STAT_QUEUED_REQUESTS_EVER = 'Queued Requests Ever';\nconst STAT_ACTIVE_REQUESTS_EVER = 'Active Requests Ever';\n\nconst DEFAULT_PROPS: Required<RequestSchedulerProps> = {\n id: 'request-scheduler',\n // Specifies if the request scheduler should throttle incoming requests, mainly for comparative testing\n throttleRequests: true,\n // The maximum number of simultaneous active requests. Un-throttled requests do not observe this limit.\n maxRequests: 6\n};\n\n/** Tracks one request */\ntype Request = {\n handle: Handle;\n priority: number;\n getPriority: GetPriorityFunction;\n resolve?: (value: any) => any;\n};\n\n/**\n * Used to issue a request, without having them \"deeply queued\" by the browser.\n * @todo - Track requests globally, across multiple servers\n */\nexport default class RequestScheduler {\n readonly props: Required<RequestSchedulerProps>;\n readonly stats: Stats;\n activeRequestCount: number = 0;\n\n /** Tracks the number of active requests and prioritizes/cancels queued requests. */\n private requestQueue: Request[] = [];\n private requestMap: Map<Handle, Promise<RequestResult>> = new Map();\n private deferredUpdate: any = null;\n\n constructor(props: RequestSchedulerProps = {}) {\n this.props = {...DEFAULT_PROPS, ...props};\n\n // Returns the statistics used by the request scheduler.\n this.stats = new Stats({id: this.props.id});\n this.stats.get(STAT_QUEUED_REQUESTS);\n this.stats.get(STAT_ACTIVE_REQUESTS);\n this.stats.get(STAT_CANCELLED_REQUESTS);\n this.stats.get(STAT_QUEUED_REQUESTS_EVER);\n this.stats.get(STAT_ACTIVE_REQUESTS_EVER);\n }\n\n /**\n * Called by an application that wants to issue a request, without having it deeply queued by the browser\n *\n * When the returned promise resolved, it is OK for the application to issue a request.\n * The promise resolves to an object that contains a `done` method.\n * When the application's request has completed (or failed), the application must call the `done` function\n *\n * @param handle\n * @param getPriority will be called when request \"slots\" open up,\n * allowing the caller to update priority or cancel the request\n * Highest priority executes first, priority < 0 cancels the request\n * @returns a promise\n * - resolves to a object (with a `done` field) when the request can be issued without queueing,\n * - resolves to `null` if the request has been cancelled (by the callback return < 0).\n * In this case the application should not issue the request\n */\n scheduleRequest(\n handle: Handle,\n getPriority: GetPriorityFunction = () => 0\n ): Promise<RequestResult> {\n // Allows throttling to be disabled\n if (!this.props.throttleRequests) {\n return Promise.resolve({done: () => {}});\n }\n\n // dedupe\n if (this.requestMap.has(handle)) {\n return this.requestMap.get(handle) as Promise<any>;\n }\n\n const request: Request = {handle, priority: 0, getPriority};\n const promise = new Promise<RequestResult>((resolve) => {\n // @ts-ignore\n request.resolve = resolve;\n return request;\n });\n\n this.requestQueue.push(request);\n this.requestMap.set(handle, promise);\n this._issueNewRequests();\n return promise;\n }\n\n // PRIVATE\n\n _issueRequest(request: Request): Promise<any> {\n const {handle, resolve} = request;\n let isDone = false;\n\n const done = () => {\n // can only be called once\n if (!isDone) {\n isDone = true;\n\n // Stop tracking a request - it has completed, failed, cancelled etc\n this.requestMap.delete(handle);\n this.activeRequestCount--;\n // A slot just freed up, see if any queued requests are waiting\n this._issueNewRequests();\n }\n };\n\n // Track this request\n this.activeRequestCount++;\n\n return resolve ? resolve({done}) : Promise.resolve({done});\n }\n\n /** We check requests asynchronously, to prevent multiple updates */\n _issueNewRequests(): void {\n if (!this.deferredUpdate) {\n this.deferredUpdate = setTimeout(() => this._issueNewRequestsAsync(), 0);\n }\n }\n\n /** Refresh all requests */\n _issueNewRequestsAsync() {\n // TODO - shouldn't we clear the timeout?\n this.deferredUpdate = null;\n\n const freeSlots = Math.max(this.props.maxRequests - this.activeRequestCount, 0);\n\n if (freeSlots === 0) {\n return;\n }\n\n this._updateAllRequests();\n\n // Resolve pending promises for the top-priority requests\n for (let i = 0; i < freeSlots; ++i) {\n const request = this.requestQueue.shift();\n if (request) {\n this._issueRequest(request); // eslint-disable-line @typescript-eslint/no-floating-promises\n }\n }\n\n // Uncomment to debug\n // console.log(`${freeSlots} free slots, ${this.requestQueue.length} queued requests`);\n }\n\n /** Ensure all requests have updated priorities, and that no longer valid requests are cancelled */\n _updateAllRequests() {\n const requestQueue = this.requestQueue;\n for (let i = 0; i < requestQueue.length; ++i) {\n const request = requestQueue[i];\n if (!this._updateRequest(request)) {\n // Remove the element and make sure to adjust the counter to account for shortened array\n requestQueue.splice(i, 1);\n this.requestMap.delete(request.handle);\n i--;\n }\n }\n\n // Sort the remaining requests based on priority\n requestQueue.sort((a, b) => a.priority - b.priority);\n }\n\n /** Update a single request by calling the callback */\n _updateRequest(request) {\n request.priority = request.getPriority(request.handle); // eslint-disable-line callback-return\n\n // by returning a negative priority, the callback cancels the request\n if (request.priority < 0) {\n request.resolve(null);\n return false;\n }\n return true;\n }\n}\n"],"file":"request-scheduler.js"}
@@ -1,97 +1,102 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.createLoaderWorker = void 0;
4
- const worker_utils_1 = require("@loaders.gl/worker-utils");
5
- // import {validateLoaderVersion} from './validate-loader-version.js';
1
+ import { WorkerBody } from '@loaders.gl/worker-utils';
6
2
  let requestId = 0;
7
- /**
8
- * Set up a WebWorkerGlobalScope to talk with the main thread
9
- * @param loader
10
- */
11
- function createLoaderWorker(loader) {
12
- // Check that we are actually in a worker thread
13
- if (typeof self === 'undefined') {
14
- return;
15
- }
16
- worker_utils_1.WorkerBody.onmessage = async (type, payload) => {
17
- switch (type) {
18
- case 'process':
19
- try {
20
- // validateLoaderVersion(loader, data.source.split('@')[1]);
21
- const { input, options = {} } = payload;
22
- const result = await parseData({
23
- loader,
24
- arrayBuffer: input,
25
- options,
26
- context: {
27
- parse: parseOnMainThread
28
- }
29
- });
30
- worker_utils_1.WorkerBody.postMessage('done', { result });
31
- }
32
- catch (error) {
33
- const message = error instanceof Error ? error.message : '';
34
- worker_utils_1.WorkerBody.postMessage('error', { error: message });
35
- }
36
- break;
37
- default:
3
+ export function createLoaderWorker(loader) {
4
+ if (typeof self === 'undefined') {
5
+ return;
6
+ }
7
+
8
+ WorkerBody.onmessage = async (type, payload) => {
9
+ switch (type) {
10
+ case 'process':
11
+ try {
12
+ const {
13
+ input,
14
+ options = {}
15
+ } = payload;
16
+ const result = await parseData({
17
+ loader,
18
+ arrayBuffer: input,
19
+ options,
20
+ context: {
21
+ parse: parseOnMainThread
22
+ }
23
+ });
24
+ WorkerBody.postMessage('done', {
25
+ result
26
+ });
27
+ } catch (error) {
28
+ const message = error instanceof Error ? error.message : '';
29
+ WorkerBody.postMessage('error', {
30
+ error: message
31
+ });
38
32
  }
39
- };
33
+
34
+ break;
35
+
36
+ default:
37
+ }
38
+ };
40
39
  }
41
- exports.createLoaderWorker = createLoaderWorker;
40
+
42
41
  function parseOnMainThread(arrayBuffer, options) {
43
- return new Promise((resolve, reject) => {
44
- const id = requestId++;
45
- /**
46
- */
47
- const onMessage = (type, payload) => {
48
- if (payload.id !== id) {
49
- // not ours
50
- return;
51
- }
52
- switch (type) {
53
- case 'done':
54
- worker_utils_1.WorkerBody.removeEventListener(onMessage);
55
- resolve(payload.result);
56
- break;
57
- case 'error':
58
- worker_utils_1.WorkerBody.removeEventListener(onMessage);
59
- reject(payload.error);
60
- break;
61
- default:
62
- // ignore
63
- }
64
- };
65
- worker_utils_1.WorkerBody.addEventListener(onMessage);
66
- // Ask the main thread to decode data
67
- const payload = { id, input: arrayBuffer, options };
68
- worker_utils_1.WorkerBody.postMessage('process', payload);
69
- });
70
- }
71
- // TODO - Support byteOffset and byteLength (enabling parsing of embedded binaries without copies)
72
- // TODO - Why not support async loader.parse* funcs here?
73
- // TODO - Why not reuse a common function instead of reimplementing loader.parse* selection logic? Keeping loader small?
74
- // TODO - Lack of appropriate parser functions can be detected when we create worker, no need to wait until parse
75
- async function parseData({ loader, arrayBuffer, options, context }) {
76
- let data;
77
- let parser;
78
- if (loader.parseSync || loader.parse) {
79
- data = arrayBuffer;
80
- parser = loader.parseSync || loader.parse;
81
- }
82
- else if (loader.parseTextSync) {
83
- const textDecoder = new TextDecoder();
84
- data = textDecoder.decode(arrayBuffer);
85
- parser = loader.parseTextSync;
86
- }
87
- else {
88
- throw new Error(`Could not load data with ${loader.name} loader`);
89
- }
90
- // TODO - proper merge in of loader options...
91
- options = {
92
- ...options,
93
- modules: (loader && loader.options && loader.options.modules) || {},
94
- worker: false
42
+ return new Promise((resolve, reject) => {
43
+ const id = requestId++;
44
+
45
+ const onMessage = (type, payload) => {
46
+ if (payload.id !== id) {
47
+ return;
48
+ }
49
+
50
+ switch (type) {
51
+ case 'done':
52
+ WorkerBody.removeEventListener(onMessage);
53
+ resolve(payload.result);
54
+ break;
55
+
56
+ case 'error':
57
+ WorkerBody.removeEventListener(onMessage);
58
+ reject(payload.error);
59
+ break;
60
+
61
+ default:
62
+ }
63
+ };
64
+
65
+ WorkerBody.addEventListener(onMessage);
66
+ const payload = {
67
+ id,
68
+ input: arrayBuffer,
69
+ options
95
70
  };
96
- return await parser(data, { ...options }, context, loader);
71
+ WorkerBody.postMessage('process', payload);
72
+ });
73
+ }
74
+
75
+ async function parseData({
76
+ loader,
77
+ arrayBuffer,
78
+ options,
79
+ context
80
+ }) {
81
+ let data;
82
+ let parser;
83
+
84
+ if (loader.parseSync || loader.parse) {
85
+ data = arrayBuffer;
86
+ parser = loader.parseSync || loader.parse;
87
+ } else if (loader.parseTextSync) {
88
+ const textDecoder = new TextDecoder();
89
+ data = textDecoder.decode(arrayBuffer);
90
+ parser = loader.parseTextSync;
91
+ } else {
92
+ throw new Error("Could not load data with ".concat(loader.name, " loader"));
93
+ }
94
+
95
+ options = { ...options,
96
+ modules: loader && loader.options && loader.options.modules || {},
97
+ worker: false
98
+ };
99
+ return await parser(data, { ...options
100
+ }, context, loader);
97
101
  }
102
+ //# sourceMappingURL=create-loader-worker.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../src/lib/worker-loader-utils/create-loader-worker.ts"],"names":["WorkerBody","requestId","createLoaderWorker","loader","self","onmessage","type","payload","input","options","result","parseData","arrayBuffer","context","parse","parseOnMainThread","postMessage","error","message","Error","Promise","resolve","reject","id","onMessage","removeEventListener","addEventListener","data","parser","parseSync","parseTextSync","textDecoder","TextDecoder","decode","name","modules","worker"],"mappings":"AAEA,SAAQA,UAAR,QAAyB,0BAAzB;AAGA,IAAIC,SAAS,GAAG,CAAhB;AAMA,OAAO,SAASC,kBAAT,CAA4BC,MAA5B,EAAsD;AAE3D,MAAI,OAAOC,IAAP,KAAgB,WAApB,EAAiC;AAC/B;AACD;;AAEDJ,EAAAA,UAAU,CAACK,SAAX,GAAuB,OAAOC,IAAP,EAAaC,OAAb,KAAyB;AAC9C,YAAQD,IAAR;AACE,WAAK,SAAL;AACE,YAAI;AAGF,gBAAM;AAACE,YAAAA,KAAD;AAAQC,YAAAA,OAAO,GAAG;AAAlB,cAAwBF,OAA9B;AAEA,gBAAMG,MAAM,GAAG,MAAMC,SAAS,CAAC;AAC7BR,YAAAA,MAD6B;AAE7BS,YAAAA,WAAW,EAAEJ,KAFgB;AAG7BC,YAAAA,OAH6B;AAI7BI,YAAAA,OAAO,EAAE;AACPC,cAAAA,KAAK,EAAEC;AADA;AAJoB,WAAD,CAA9B;AAQAf,UAAAA,UAAU,CAACgB,WAAX,CAAuB,MAAvB,EAA+B;AAACN,YAAAA;AAAD,WAA/B;AACD,SAdD,CAcE,OAAOO,KAAP,EAAc;AACd,gBAAMC,OAAO,GAAGD,KAAK,YAAYE,KAAjB,GAAyBF,KAAK,CAACC,OAA/B,GAAyC,EAAzD;AACAlB,UAAAA,UAAU,CAACgB,WAAX,CAAuB,OAAvB,EAAgC;AAACC,YAAAA,KAAK,EAAEC;AAAR,WAAhC;AACD;;AACD;;AACF;AArBF;AAuBD,GAxBD;AAyBD;;AAED,SAASH,iBAAT,CAA2BH,WAA3B,EAAqDH,OAArD,EAAmG;AACj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AAI,GAAGI,WAAW,CAACE,MAAZ,CAAmBrB,WAAnB,CAAP;AACAgB,IAAAA,MAAM,GAAGzB,MAAM,CAAC2B,aAAhB;AACD,GAJM,MAIA;AACL,UAAM,IAAIX,KAAJ,oCAAsChB,MAAM,CAAC+B,IAA7C,aAAN;AACD;;AAGDzB,EAAAA,OAAO,GAAG,EACR,GAAGA,OADK;AAER0B,IAAAA,OAAO,EAAGhC,MAAM,IAAIA,MAAM,CAACM,OAAjB,IAA4BN,MAAM,CAACM,OAAP,CAAe0B,OAA5C,IAAwD,EAFzD;AAGRC,IAAAA,MAAM,EAAE;AAHA,GAAV;AAMA,SAAO,MAAMR,MAAM,CAACD,IAAD,EAAO,EAAC,GAAGlB;AAAJ,GAAP,EAAqBI,OAArB,EAA8BV,MAA9B,CAAnB;AACD","sourcesContent":["/* eslint-disable no-restricted-globals */\nimport type {LoaderWithParser} from '../../types';\nimport {WorkerBody} from '@loaders.gl/worker-utils';\n// import {validateLoaderVersion} from './validate-loader-version';\n\nlet requestId = 0;\n\n/**\n * Set up a WebWorkerGlobalScope to talk with the main thread\n * @param loader\n */\nexport function createLoaderWorker(loader: LoaderWithParser) {\n // Check that we are actually in a worker thread\n if (typeof self === 'undefined') {\n return;\n }\n\n WorkerBody.onmessage = async (type, payload) => {\n switch (type) {\n case 'process':\n try {\n // validateLoaderVersion(loader, data.source.split('@')[1]);\n\n const {input, options = {}} = payload;\n\n const result = await parseData({\n loader,\n arrayBuffer: input,\n options,\n context: {\n parse: parseOnMainThread\n }\n });\n WorkerBody.postMessage('done', {result});\n } catch (error) {\n const message = error instanceof Error ? error.message : '';\n WorkerBody.postMessage('error', {error: message});\n }\n break;\n default:\n }\n };\n}\n\nfunction parseOnMainThread(arrayBuffer: ArrayBuffer, options: {[key: string]: any}): Promise<void> {\n return new Promise((resolve, reject) => {\n const id = requestId++;\n\n /**\n */\n const onMessage = (type, payload) => {\n if (payload.id !== id) {\n // not ours\n return;\n }\n\n switch (type) {\n case 'done':\n WorkerBody.removeEventListener(onMessage);\n resolve(payload.result);\n break;\n\n case 'error':\n WorkerBody.removeEventListener(onMessage);\n reject(payload.error);\n break;\n\n default:\n // ignore\n }\n };\n\n WorkerBody.addEventListener(onMessage);\n\n // Ask the main thread to decode data\n const payload = {id, input: arrayBuffer, options};\n WorkerBody.postMessage('process', payload);\n });\n}\n\n// TODO - Support byteOffset and byteLength (enabling parsing of embedded binaries without copies)\n// TODO - Why not support async loader.parse* funcs here?\n// TODO - Why not reuse a common function instead of reimplementing loader.parse* selection logic? Keeping loader small?\n// TODO - Lack of appropriate parser functions can be detected when we create worker, no need to wait until parse\nasync function parseData({loader, arrayBuffer, options, context}) {\n let data;\n let parser;\n if (loader.parseSync || loader.parse) {\n data = arrayBuffer;\n parser = loader.parseSync || loader.parse;\n } else if (loader.parseTextSync) {\n const textDecoder = new TextDecoder();\n data = textDecoder.decode(arrayBuffer);\n parser = loader.parseTextSync;\n } else {\n throw new Error(`Could not load data with ${loader.name} loader`);\n }\n\n // TODO - proper merge in of loader options...\n options = {\n ...options,\n modules: (loader && loader.options && loader.options.modules) || {},\n worker: false\n };\n\n return await parser(data, {...options}, context, loader);\n}\n"],"file":"create-loader-worker.js"}
@@ -1,73 +1,64 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.parseWithWorker = exports.canParseWithWorker = void 0;
4
- const worker_utils_1 = require("@loaders.gl/worker-utils");
5
- /**
6
- * Determines if a loader can parse with worker
7
- * @param loader
8
- * @param options
9
- */
10
- function canParseWithWorker(loader, options) {
11
- if (!worker_utils_1.WorkerFarm.isSupported()) {
12
- return false;
13
- }
14
- return loader.worker && options?.worker;
1
+ import { WorkerFarm, getWorkerURL } from '@loaders.gl/worker-utils';
2
+ export function canParseWithWorker(loader, options) {
3
+ if (!WorkerFarm.isSupported()) {
4
+ return false;
5
+ }
6
+
7
+ return loader.worker && (options === null || options === void 0 ? void 0 : options.worker);
15
8
  }
16
- exports.canParseWithWorker = canParseWithWorker;
17
- /**
18
- * this function expects that the worker function sends certain messages,
19
- * this can be automated if the worker is wrapper by a call to createLoaderWorker in @loaders.gl/loader-utils.
20
- */
21
- async function parseWithWorker(loader, data, options, context, parseOnMainThread) {
22
- const name = loader.id; // TODO
23
- const url = (0, worker_utils_1.getWorkerURL)(loader, options);
24
- const workerFarm = worker_utils_1.WorkerFarm.getWorkerFarm(options);
25
- const workerPool = workerFarm.getWorkerPool({ name, url });
26
- // options.log object contains functions which cannot be transferred
27
- // TODO - decide how to handle logging on workers
28
- options = JSON.parse(JSON.stringify(options));
29
- const job = await workerPool.startJob('process-on-worker',
30
- // @ts-expect-error
31
- onMessage.bind(null, parseOnMainThread) // eslint-disable-line @typescript-eslint/no-misused-promises
32
- );
33
- job.postMessage('process', {
34
- // @ts-ignore
35
- input: data,
36
- options
37
- });
38
- const result = await job.result;
39
- // TODO - what is going on here?
40
- return await result.result;
9
+ export async function parseWithWorker(loader, data, options, context, parseOnMainThread) {
10
+ const name = loader.id;
11
+ const url = getWorkerURL(loader, options);
12
+ const workerFarm = WorkerFarm.getWorkerFarm(options);
13
+ const workerPool = workerFarm.getWorkerPool({
14
+ name,
15
+ url
16
+ });
17
+ options = JSON.parse(JSON.stringify(options));
18
+ const job = await workerPool.startJob('process-on-worker', onMessage.bind(null, parseOnMainThread));
19
+ job.postMessage('process', {
20
+ input: data,
21
+ options
22
+ });
23
+ const result = await job.result;
24
+ return await result.result;
41
25
  }
42
- exports.parseWithWorker = parseWithWorker;
43
- /**
44
- * Handle worker's responses to the main thread
45
- * @param job
46
- * @param type
47
- * @param payload
48
- */
26
+
49
27
  async function onMessage(parseOnMainThread, job, type, payload) {
50
- switch (type) {
51
- case 'done':
52
- job.done(payload);
53
- break;
54
- case 'error':
55
- job.error(new Error(payload.error));
56
- break;
57
- case 'process':
58
- // Worker is asking for main thread to parseO
59
- const { id, input, options } = payload;
60
- try {
61
- const result = await parseOnMainThread(input, options);
62
- job.postMessage('done', { id, result });
63
- }
64
- catch (error) {
65
- const message = error instanceof Error ? error.message : 'unknown error';
66
- job.postMessage('error', { id, error: message });
67
- }
68
- break;
69
- default:
70
- // eslint-disable-next-line
71
- console.warn(`parse-with-worker unknown message ${type}`);
72
- }
28
+ switch (type) {
29
+ case 'done':
30
+ job.done(payload);
31
+ break;
32
+
33
+ case 'error':
34
+ job.error(new Error(payload.error));
35
+ break;
36
+
37
+ case 'process':
38
+ const {
39
+ id,
40
+ input,
41
+ options
42
+ } = payload;
43
+
44
+ try {
45
+ const result = await parseOnMainThread(input, options);
46
+ job.postMessage('done', {
47
+ id,
48
+ result
49
+ });
50
+ } catch (error) {
51
+ const message = error instanceof Error ? error.message : 'unknown error';
52
+ job.postMessage('error', {
53
+ id,
54
+ error: message
55
+ });
56
+ }
57
+
58
+ break;
59
+
60
+ default:
61
+ console.warn("parse-with-worker unknown message ".concat(type));
62
+ }
73
63
  }
64
+ //# sourceMappingURL=parse-with-worker.js.map