or-tools-wasm 0.5.0 → 0.7.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +206 -54
- package/build/javascript/browser/cp_sat_module_loader.js +53 -0
- package/build/javascript/browser/cpsat_worker.js +135 -0
- package/build/javascript/browser/cpsat_worker_types.js +0 -0
- package/build/javascript/browser/index.js +5910 -0
- package/build/javascript/lib/assets/cp_sat_runtime-BcQ-oG9G.js +2568 -0
- package/build/javascript/lib/assets/cp_sat_runtime-BcQ-oG9G.js.map +1 -0
- package/build/javascript/lib/assets/{cp_sat_runtime-BUuF8d7w.wasm → cp_sat_runtime.wasm} +0 -0
- package/build/javascript/lib/assets/cp_sat_runtime.wasm.map +1 -0
- package/build/javascript/lib/assets/cp_sat_runtime_asyncify-CebveWgj.js +2642 -0
- package/build/javascript/lib/assets/cp_sat_runtime_asyncify-CebveWgj.js.map +1 -0
- package/build/javascript/lib/assets/{cp_sat_runtime_asyncify-CjMVqM1A.wasm → cp_sat_runtime_asyncify.wasm} +0 -0
- package/build/javascript/lib/assets/cp_sat_runtime_asyncify.wasm.map +1 -0
- package/build/javascript/lib/assets/cpsat_worker-CxyMtsph.js +145 -0
- package/build/javascript/lib/assets/cpsat_worker-CxyMtsph.js.map +1 -0
- package/build/javascript/lib/chunks/cp_sat_runtime-D-Bi0Puh.js +2568 -0
- package/build/javascript/lib/chunks/cp_sat_runtime-D-Bi0Puh.js.map +1 -0
- package/build/javascript/lib/chunks/cp_sat_runtime_asyncify-pyd1qgFK.js +2642 -0
- package/build/javascript/lib/chunks/cp_sat_runtime_asyncify-pyd1qgFK.js.map +1 -0
- package/build/javascript/lib/cp_sat_api.d.ts +277 -98
- package/build/javascript/lib/cp_sat_api.js +3364 -219
- package/build/javascript/lib/cp_sat_api.js.map +1 -1
- package/build/javascript/wasm/cp_sat_runtime.d.ts +51 -0
- package/build/javascript/wasm/cp_sat_runtime.js +10 -0
- package/build/javascript/wasm/cp_sat_runtime.wasm +0 -0
- package/build/javascript/wasm/cp_sat_runtime.wasm.map +1 -0
- package/build/javascript/wasm/cp_sat_runtime_asyncify.js +10 -0
- package/build/javascript/wasm/cp_sat_runtime_asyncify.wasm +0 -0
- package/build/javascript/wasm/cp_sat_runtime_asyncify.wasm.map +1 -0
- package/javascript/lib/cp_sat_api.ts +475 -0
- package/javascript/lib/cp_sat_module_loader.bundled.ts +58 -0
- package/javascript/lib/cp_sat_module_loader.ts +57 -0
- package/javascript/lib/cpsat_worker.ts +160 -0
- package/javascript/lib/cpsat_worker_types.ts +32 -0
- package/javascript/lib/generated/sat_parameters.ts +2760 -0
- package/javascript/lib/index.ts +8 -0
- package/javascript/lib/internal_wasm_asyncify.d.ts +15 -0
- package/javascript/lib/vite-shims.d.ts +25 -0
- package/javascript/lib/webassembly_promising.d.ts +7 -0
- package/package.json +46 -7
- package/build/javascript/lib/assets/cp_sat_runtime-N6mpxHFm.js +0 -2565
- package/build/javascript/lib/assets/cp_sat_runtime-N6mpxHFm.js.map +0 -1
- package/build/javascript/lib/assets/cp_sat_runtime_asyncify-DAFhCUmM.js +0 -2639
- package/build/javascript/lib/assets/cp_sat_runtime_asyncify-DAFhCUmM.js.map +0 -1
- package/build/javascript/lib/assets/cpsat_worker-Bc6EW-gj.js +0 -139
- package/build/javascript/lib/assets/cpsat_worker-Bc6EW-gj.js.map +0 -1
- package/build/javascript/lib/chunks/cp_sat_runtime-B9zhYjnh.js +0 -2565
- package/build/javascript/lib/chunks/cp_sat_runtime-B9zhYjnh.js.map +0 -1
- package/build/javascript/lib/chunks/cp_sat_runtime_asyncify-BaxdGqjW.js +0 -2639
- package/build/javascript/lib/chunks/cp_sat_runtime_asyncify-BaxdGqjW.js.map +0 -1
- package/build/javascript/lib/chunks/index-Cq3lJx2c.js +0 -3815
- package/build/javascript/lib/chunks/index-Cq3lJx2c.js.map +0 -1
package/README.md
CHANGED
|
@@ -1,29 +1,27 @@
|
|
|
1
|
-
# or-tools-wasm
|
|
1
|
+
# or-tools-wasm - solve complex constraint problems in browser
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Solve complex models directly in the browser with Google OR-Tools CP-SAT
|
|
4
|
+
running as multithreaded WebAssembly.
|
|
4
5
|
|
|
5
|
-
|
|
6
|
+
## [Try Online](https://axelwickman.com/or-tools-wasm)
|
|
6
7
|
|
|
7
|
-
|
|
8
|
-
wraps it with a TypeScript API, worker bridge, generated SAT parameter types,
|
|
9
|
-
and Vite-powered demos.
|
|
8
|
+
Used in [PragmaPlanner.com](https://pragmaplanner.com/?utm_source=or-tools-wasm&utm_medium=readme&utm_campaign=used_in).
|
|
10
9
|
|
|
11
|
-
|
|
12
|
-
[
|
|
10
|
+
[GitHub](https://github.com/Axelwickm/or-tools-wasm)
|
|
11
|
+
[npm](https://www.npmjs.com/package/or-tools-wasm)
|
|
13
12
|
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
-
|
|
26
|
-
inspection.
|
|
13
|
+
[](https://github.com/Axelwickm/or-tools-wasm/actions/workflows/package.yml)
|
|
14
|
+
[](https://github.com/Axelwickm/or-tools-wasm/actions/workflows/package.yml)
|
|
15
|
+
[](https://github.com/Axelwickm/or-tools-wasm/actions/workflows/package.yml)
|
|
16
|
+
[](https://github.com/Axelwickm/or-tools-wasm/actions/workflows/package.yml)
|
|
17
|
+
[](https://github.com/Axelwickm/or-tools-wasm/actions/workflows/package.yml)
|
|
18
|
+
[](https://github.com/Axelwickm/or-tools-wasm/actions/workflows/package.yml)
|
|
19
|
+
[](https://github.com/Axelwickm/or-tools-wasm/actions/workflows/package.yml)
|
|
20
|
+
[](https://github.com/Axelwickm/or-tools-wasm/actions/workflows/package.yml)
|
|
21
|
+
[](https://github.com/Axelwickm/or-tools-wasm/actions/workflows/package.yml)
|
|
22
|
+
[](https://github.com/Axelwickm/or-tools-wasm/actions/workflows/package.yml)
|
|
23
|
+
[](https://github.com/Axelwickm/or-tools-wasm/actions/workflows/package.yml)
|
|
24
|
+
[](https://github.com/Axelwickm/or-tools-wasm/actions/workflows/package.yml)
|
|
27
25
|
|
|
28
26
|
## Install
|
|
29
27
|
|
|
@@ -31,26 +29,32 @@ This repository currently vendors OR-Tools 9.14 pre-release sources
|
|
|
31
29
|
npm install or-tools-wasm
|
|
32
30
|
```
|
|
33
31
|
|
|
34
|
-
Then import it normally:
|
|
35
|
-
|
|
36
32
|
```ts
|
|
37
33
|
import { CpSat } from 'or-tools-wasm';
|
|
38
34
|
```
|
|
39
35
|
|
|
40
|
-
|
|
41
|
-
emitted automatically from the package import, with no manual copying into
|
|
42
|
-
`public/` or `static/` required.
|
|
36
|
+
Currently supported solvers: CP-SAT.
|
|
43
37
|
|
|
44
|
-
|
|
45
|
-
asset emission, but that is not yet officially verified.
|
|
38
|
+
Verified with:
|
|
46
39
|
|
|
47
|
-
|
|
48
|
-
|
|
40
|
+
- Vite 7 in browser contexts
|
|
41
|
+
- Webpack 5 in browser contexts
|
|
42
|
+
- Rollup 4 static browser builds
|
|
43
|
+
- Deno runtime solves
|
|
49
44
|
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
45
|
+
## What is included
|
|
46
|
+
|
|
47
|
+
- A CP-SAT WebAssembly runtime built with Emscripten pthread support.
|
|
48
|
+
- A TypeScript API for solving, validating models, interrupting solves, and
|
|
49
|
+
reading embedded proto schemas.
|
|
50
|
+
- A worker bridge for keeping browser UI threads responsive while solving.
|
|
51
|
+
- Generated TypeScript definitions for SAT parameters.
|
|
52
|
+
- Demo pages for Magic Square, Sports Scheduling, Steel Mill Slab, and schema
|
|
53
|
+
inspection.
|
|
54
|
+
|
|
55
|
+
This flow is verified with Vite, Webpack, and Rollup. The worker script and
|
|
56
|
+
WebAssembly files are emitted automatically from the package import, with no
|
|
57
|
+
manual copying into `public/` or `static/` required.
|
|
54
58
|
|
|
55
59
|
## Usage
|
|
56
60
|
|
|
@@ -91,10 +95,171 @@ const result = await CpSat.solve(modelBytes, {
|
|
|
91
95
|
console.log(result.response);
|
|
92
96
|
```
|
|
93
97
|
|
|
94
|
-
##
|
|
98
|
+
## Browser hosting requirements
|
|
99
|
+
|
|
100
|
+
This package uses a threaded WebAssembly runtime. Browser pages that load it
|
|
101
|
+
must be served with cross-origin isolation enabled:
|
|
102
|
+
|
|
103
|
+
```http
|
|
104
|
+
Cross-Origin-Opener-Policy: same-origin
|
|
105
|
+
Cross-Origin-Embedder-Policy: require-corp
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
Without these headers, browsers may block the `SharedArrayBuffer` APIs required
|
|
109
|
+
by Emscripten pthreads, and solving can fail during WebAssembly runtime or
|
|
110
|
+
worker startup.
|
|
111
|
+
|
|
112
|
+
For Vite dev and preview servers, set the headers in `vite.config.ts`:
|
|
113
|
+
|
|
114
|
+
```ts
|
|
115
|
+
// vite.config.ts
|
|
116
|
+
import { defineConfig } from 'vite';
|
|
117
|
+
|
|
118
|
+
export default defineConfig({
|
|
119
|
+
server: {
|
|
120
|
+
headers: {
|
|
121
|
+
'Cross-Origin-Opener-Policy': 'same-origin',
|
|
122
|
+
'Cross-Origin-Embedder-Policy': 'require-corp',
|
|
123
|
+
},
|
|
124
|
+
},
|
|
125
|
+
preview: {
|
|
126
|
+
headers: {
|
|
127
|
+
'Cross-Origin-Opener-Policy': 'same-origin',
|
|
128
|
+
'Cross-Origin-Embedder-Policy': 'require-corp',
|
|
129
|
+
},
|
|
130
|
+
},
|
|
131
|
+
});
|
|
132
|
+
```
|
|
133
|
+
|
|
134
|
+
## Bundler configuration
|
|
135
|
+
|
|
136
|
+
### Vite
|
|
137
|
+
|
|
138
|
+
For Vite apps, keep `or-tools-wasm` out of dependency optimization so Vite
|
|
139
|
+
handles the worker and WebAssembly URLs through its normal asset pipeline.
|
|
140
|
+
`protobufjs` is CommonJS, so include it in dependency optimization. The worker
|
|
141
|
+
runtime also needs ES module worker output:
|
|
142
|
+
|
|
143
|
+
```ts
|
|
144
|
+
// vite.config.ts
|
|
145
|
+
import { defineConfig } from 'vite';
|
|
146
|
+
|
|
147
|
+
export default defineConfig({
|
|
148
|
+
optimizeDeps: {
|
|
149
|
+
include: ['protobufjs'],
|
|
150
|
+
exclude: ['or-tools-wasm'],
|
|
151
|
+
},
|
|
152
|
+
worker: {
|
|
153
|
+
format: 'es',
|
|
154
|
+
},
|
|
155
|
+
});
|
|
156
|
+
```
|
|
157
|
+
|
|
158
|
+
### Webpack
|
|
159
|
+
|
|
160
|
+
For Webpack 5, enable async WebAssembly, emit `.wasm` files as resources, and
|
|
161
|
+
use `publicPath: 'auto'` so worker and WebAssembly URLs resolve from the emitted
|
|
162
|
+
bundle location:
|
|
163
|
+
|
|
164
|
+
```js
|
|
165
|
+
// webpack.config.cjs
|
|
166
|
+
const headers = {
|
|
167
|
+
'Cross-Origin-Opener-Policy': 'same-origin',
|
|
168
|
+
'Cross-Origin-Embedder-Policy': 'require-corp',
|
|
169
|
+
};
|
|
170
|
+
|
|
171
|
+
module.exports = {
|
|
172
|
+
output: {
|
|
173
|
+
publicPath: 'auto',
|
|
174
|
+
},
|
|
175
|
+
experiments: {
|
|
176
|
+
asyncWebAssembly: true,
|
|
177
|
+
},
|
|
178
|
+
module: {
|
|
179
|
+
rules: [
|
|
180
|
+
{
|
|
181
|
+
test: /\.wasm$/,
|
|
182
|
+
type: 'asset/resource',
|
|
183
|
+
},
|
|
184
|
+
],
|
|
185
|
+
},
|
|
186
|
+
devServer: {
|
|
187
|
+
headers,
|
|
188
|
+
},
|
|
189
|
+
};
|
|
190
|
+
```
|
|
191
|
+
|
|
192
|
+
### Rollup
|
|
193
|
+
|
|
194
|
+
Rollup core does not bundle module workers or emit `new URL(...,
|
|
195
|
+
import.meta.url)` assets by itself. The verified fixture uses Rollup's standard
|
|
196
|
+
plugin surface for those features:
|
|
197
|
+
|
|
198
|
+
```js
|
|
199
|
+
// rollup.config.mjs
|
|
200
|
+
import { nodeResolve } from '@rollup/plugin-node-resolve';
|
|
201
|
+
import OMT from '@surma/rollup-plugin-off-main-thread';
|
|
202
|
+
import { importMetaAssets } from '@web/rollup-plugin-import-meta-assets';
|
|
203
|
+
|
|
204
|
+
function moduleRelativeFileUrls() {
|
|
205
|
+
return {
|
|
206
|
+
name: 'module-relative-file-urls',
|
|
207
|
+
resolveFileUrl({ fileName }) {
|
|
208
|
+
return `new URL(${JSON.stringify(fileName)}, import.meta.url).href`;
|
|
209
|
+
},
|
|
210
|
+
};
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
export default {
|
|
214
|
+
input: 'src/main.js',
|
|
215
|
+
output: {
|
|
216
|
+
dir: 'dist',
|
|
217
|
+
format: 'es',
|
|
218
|
+
},
|
|
219
|
+
plugins: [
|
|
220
|
+
nodeResolve({ browser: true }),
|
|
221
|
+
moduleRelativeFileUrls(),
|
|
222
|
+
OMT(),
|
|
223
|
+
importMetaAssets(),
|
|
224
|
+
],
|
|
225
|
+
};
|
|
226
|
+
```
|
|
227
|
+
|
|
228
|
+
Other modern bundlers may also work if they support module workers and
|
|
229
|
+
WebAssembly asset emission, but they are not yet officially verified.
|
|
230
|
+
|
|
231
|
+
## Threading model
|
|
232
|
+
|
|
233
|
+
The WebAssembly runtime is built with Emscripten pthread support. When the
|
|
234
|
+
runtime starts, Emscripten creates a pthread worker pool sized from
|
|
235
|
+
`navigator.hardwareConcurrency`. This pool is separate from CP-SAT's own search
|
|
236
|
+
worker setting.
|
|
237
|
+
|
|
238
|
+
`SatParameters.numSearchWorkers` controls how many CP-SAT search workers the
|
|
239
|
+
solver should use for a solve. It does not change how many Emscripten pthread
|
|
240
|
+
workers are created when the WebAssembly runtime is initialized.
|
|
241
|
+
|
|
242
|
+
By default, `CpSat.solve` runs through the package's worker bridge. The bridge
|
|
243
|
+
loads the CP-SAT runtime in a dedicated JavaScript worker, so the browser's main
|
|
244
|
+
thread remains available for rendering, input, progress UI, and cancellation.
|
|
245
|
+
If the worker bridge is disabled, solving runs directly on the main thread. The
|
|
246
|
+
solver still works, but the GUI can freeze until CP-SAT returns because the
|
|
247
|
+
browser cannot repaint or process UI events during the synchronous WebAssembly
|
|
248
|
+
call.
|
|
249
|
+
|
|
250
|
+
## Local development
|
|
95
251
|
|
|
96
252
|
```sh
|
|
97
253
|
npm install
|
|
254
|
+
npm run dev
|
|
255
|
+
```
|
|
256
|
+
|
|
257
|
+
`npm run dev` / `npm run start` builds the library and launches the Vite dev
|
|
258
|
+
server for the demo site.
|
|
259
|
+
|
|
260
|
+
## Build
|
|
261
|
+
|
|
262
|
+
```sh
|
|
98
263
|
npm run build
|
|
99
264
|
npm run preview
|
|
100
265
|
```
|
|
@@ -109,26 +274,11 @@ run `npm run build` directly after `npm install`. If you prefer to fetch
|
|
|
109
274
|
submodules up front, clone with `--recurse-submodules` or run
|
|
110
275
|
`git submodule update --init --recursive`.
|
|
111
276
|
|
|
112
|
-
## Browser hosting requirements
|
|
113
|
-
|
|
114
|
-
This package uses a threaded WebAssembly runtime. Browser pages that load it
|
|
115
|
-
must be served with cross-origin isolation enabled:
|
|
116
|
-
|
|
117
|
-
```http
|
|
118
|
-
Cross-Origin-Opener-Policy: same-origin
|
|
119
|
-
Cross-Origin-Embedder-Policy: require-corp
|
|
120
|
-
```
|
|
121
|
-
|
|
122
|
-
Without these headers, browsers may block the `SharedArrayBuffer` APIs required
|
|
123
|
-
by Emscripten pthreads, and solving can fail during WebAssembly runtime or
|
|
124
|
-
worker startup.
|
|
125
|
-
|
|
126
277
|
## npm scripts
|
|
127
278
|
|
|
128
279
|
- `npm run build:wasm` rebuilds the `cp_sat_runtime` wasm/js bundle via emsdk + CMake.
|
|
129
280
|
- `npm run build:lib` regenerates SAT parameter types, type-checks with `tsc`, and builds the library bundle with `vite.lib.config.ts`.
|
|
130
281
|
- `npm run build:site` builds the demo site with `vite.site.config.ts`. The site imports `or-tools-wasm` directly, so Vite emits the worker/runtime/wasm assets from the package bundle automatically.
|
|
131
|
-
- `npm run dev` / `npm run start` builds the library and launches the Vite dev server for the demo site.
|
|
132
282
|
- `npm run build` runs `build:wasm`, `build:lib`, and `build:site`.
|
|
133
283
|
- `npm run preview` serves the already-built Vite site from `build/javascript/site`.
|
|
134
284
|
- `npm run clean` removes the entire `build/` tree.
|
|
@@ -146,10 +296,8 @@ worker startup.
|
|
|
146
296
|
|
|
147
297
|
## Demos
|
|
148
298
|
|
|
149
|
-
- The Magic Square and Sports Scheduling pages let users pick a worker count; that value becomes `SatParameters.num_search_workers`, clamped to `min(navigator.hardwareConcurrency, 8)`.
|
|
150
|
-
- Each demo exposes a "Use worker bridge" checkbox.
|
|
151
|
-
- When the worker bridge is disabled, the solve runs directly on the main thread. The solver still works, but long solves can freeze the page until CP-SAT returns because the browser cannot repaint or process UI events while the synchronous WebAssembly call is running.
|
|
152
|
-
- The WebAssembly build caps the pthread pool at 8 and scales down on low-core devices.
|
|
299
|
+
- The Magic Square and Sports Scheduling pages let users pick a CP-SAT search worker count; that value becomes `SatParameters.num_search_workers`, clamped to `min(navigator.hardwareConcurrency, 8)`.
|
|
300
|
+
- Each demo exposes a "Use worker bridge" checkbox. Keep it enabled for interactive use; disabling it runs the solve on the main browser thread and can freeze the GUI until CP-SAT returns.
|
|
153
301
|
- Schema Viewer imports the bundled `CpSat` API automatically; no extra script ordering is required.
|
|
154
302
|
|
|
155
303
|
## JSPI and Asyncify
|
|
@@ -179,6 +327,10 @@ Upstream project:
|
|
|
179
327
|
- Documentation: [developers.google.com/optimization](https://developers.google.com/optimization/)
|
|
180
328
|
- License: Apache License 2.0
|
|
181
329
|
|
|
330
|
+
## Maintainer
|
|
331
|
+
|
|
332
|
+
Maintained by [Axel Wickman](https://axelwickman.com).
|
|
333
|
+
|
|
182
334
|
## License
|
|
183
335
|
|
|
184
336
|
This project is licensed under the Apache License 2.0. See [LICENSE](LICENSE).
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
let modulePromise = null;
|
|
2
|
+
let selectedFlavor = null;
|
|
3
|
+
|
|
4
|
+
const cpSatRuntimeWasmUrl = new URL('../wasm/cp_sat_runtime.wasm', import.meta.url).href;
|
|
5
|
+
const cpSatRuntimeAsyncifyWasmUrl = new URL('../wasm/cp_sat_runtime_asyncify.wasm', import.meta.url).href;
|
|
6
|
+
|
|
7
|
+
function isJspiSupported() {
|
|
8
|
+
const wasm = WebAssembly;
|
|
9
|
+
return typeof wasm !== 'undefined' && typeof wasm.promising === 'function';
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
function selectRuntimeFlavor() {
|
|
13
|
+
if (selectedFlavor) {
|
|
14
|
+
return selectedFlavor;
|
|
15
|
+
}
|
|
16
|
+
selectedFlavor = isJspiSupported() ? 'jspi' : 'asyncify';
|
|
17
|
+
if (selectedFlavor === 'jspi') {
|
|
18
|
+
console.log('JSPI is supported. Using ASYNCIFY=2.');
|
|
19
|
+
} else {
|
|
20
|
+
console.log('JSPI not found. Falling back to ASYNCIFY=1.');
|
|
21
|
+
}
|
|
22
|
+
return selectedFlavor;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
async function loadFactory() {
|
|
26
|
+
const flavor = selectRuntimeFlavor();
|
|
27
|
+
if (flavor === 'jspi') {
|
|
28
|
+
const { default: createModule } = await import('../wasm/cp_sat_runtime.js');
|
|
29
|
+
return createModule;
|
|
30
|
+
}
|
|
31
|
+
const { default: createModule } = await import('../wasm/cp_sat_runtime_asyncify.js');
|
|
32
|
+
return createModule;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function locateCpSatRuntimeFile(fileName) {
|
|
36
|
+
if (fileName === 'cp_sat_runtime.wasm') {
|
|
37
|
+
return cpSatRuntimeWasmUrl;
|
|
38
|
+
}
|
|
39
|
+
if (fileName === 'cp_sat_runtime_asyncify.wasm') {
|
|
40
|
+
return cpSatRuntimeAsyncifyWasmUrl;
|
|
41
|
+
}
|
|
42
|
+
return fileName;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export async function loadCpSat() {
|
|
46
|
+
if (!modulePromise) {
|
|
47
|
+
modulePromise = (async () => {
|
|
48
|
+
const createModule = await loadFactory();
|
|
49
|
+
return createModule({ locateFile: locateCpSatRuntimeFile });
|
|
50
|
+
})();
|
|
51
|
+
}
|
|
52
|
+
return modulePromise;
|
|
53
|
+
}
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
// javascript/lib/cpsat_worker.ts
|
|
2
|
+
import { loadCpSat } from "./cp_sat_module_loader.js";
|
|
3
|
+
var workerScope = self;
|
|
4
|
+
var moduleInstance = null;
|
|
5
|
+
var moduleReady = loadCpSat().then((module) => {
|
|
6
|
+
moduleInstance = module;
|
|
7
|
+
workerScope.postMessage({ type: "ready" });
|
|
8
|
+
return module;
|
|
9
|
+
}).catch((error) => {
|
|
10
|
+
console.error("[cpsat_worker] cpSatModule init failed:", error);
|
|
11
|
+
workerScope.postMessage({
|
|
12
|
+
type: "error",
|
|
13
|
+
id: 0,
|
|
14
|
+
error: String(error)
|
|
15
|
+
});
|
|
16
|
+
throw error;
|
|
17
|
+
});
|
|
18
|
+
var readUint32LE = (buffer, ptr) => new DataView(buffer, ptr, 4).getUint32(0, true);
|
|
19
|
+
var copyBytesToHeap = (bytes) => {
|
|
20
|
+
if (!moduleInstance || !bytes?.length) {
|
|
21
|
+
return 0;
|
|
22
|
+
}
|
|
23
|
+
const ptr = moduleInstance._malloc(bytes.length);
|
|
24
|
+
moduleInstance.HEAPU8.set(bytes, ptr);
|
|
25
|
+
return ptr;
|
|
26
|
+
};
|
|
27
|
+
async function solveModel(modelBytes, paramsBytes) {
|
|
28
|
+
if (!moduleInstance) {
|
|
29
|
+
throw new Error("Module not initialized.");
|
|
30
|
+
}
|
|
31
|
+
const lenPtr = moduleInstance._malloc(4);
|
|
32
|
+
const modelPtr = copyBytesToHeap(modelBytes);
|
|
33
|
+
const paramsPtr = copyBytesToHeap(paramsBytes ?? null);
|
|
34
|
+
let responsePtr = 0;
|
|
35
|
+
try {
|
|
36
|
+
responsePtr = await moduleInstance.ccall(
|
|
37
|
+
"solve_model",
|
|
38
|
+
"number",
|
|
39
|
+
["number", "number", "number", "number", "number"],
|
|
40
|
+
[
|
|
41
|
+
modelPtr,
|
|
42
|
+
modelBytes.length,
|
|
43
|
+
paramsPtr,
|
|
44
|
+
paramsBytes ? paramsBytes.length : 0,
|
|
45
|
+
lenPtr
|
|
46
|
+
],
|
|
47
|
+
{ async: true }
|
|
48
|
+
);
|
|
49
|
+
} finally {
|
|
50
|
+
if (modelPtr) moduleInstance._free(modelPtr);
|
|
51
|
+
if (paramsPtr) moduleInstance._free(paramsPtr);
|
|
52
|
+
}
|
|
53
|
+
const len = readUint32LE(moduleInstance.HEAPU8.buffer, lenPtr);
|
|
54
|
+
moduleInstance._free(lenPtr);
|
|
55
|
+
if (!responsePtr || len === 0) {
|
|
56
|
+
if (responsePtr) moduleInstance._free_buffer(responsePtr);
|
|
57
|
+
return new Uint8Array();
|
|
58
|
+
}
|
|
59
|
+
const bytes = moduleInstance.HEAPU8.slice(responsePtr, responsePtr + len);
|
|
60
|
+
moduleInstance._free_buffer(responsePtr);
|
|
61
|
+
return bytes;
|
|
62
|
+
}
|
|
63
|
+
async function validateModel(modelBytes) {
|
|
64
|
+
if (!moduleInstance) {
|
|
65
|
+
throw new Error("Module not initialized.");
|
|
66
|
+
}
|
|
67
|
+
const lenPtr = moduleInstance._malloc(4);
|
|
68
|
+
const modelPtr = copyBytesToHeap(modelBytes);
|
|
69
|
+
let msgPtr = 0;
|
|
70
|
+
try {
|
|
71
|
+
msgPtr = moduleInstance.ccall(
|
|
72
|
+
"validate_model",
|
|
73
|
+
"number",
|
|
74
|
+
["number", "number", "number"],
|
|
75
|
+
[modelPtr, modelBytes.length, lenPtr]
|
|
76
|
+
);
|
|
77
|
+
} finally {
|
|
78
|
+
if (modelPtr) moduleInstance._free(modelPtr);
|
|
79
|
+
}
|
|
80
|
+
const len = readUint32LE(moduleInstance.HEAPU8.buffer, lenPtr);
|
|
81
|
+
moduleInstance._free(lenPtr);
|
|
82
|
+
if (!msgPtr || len === 0) {
|
|
83
|
+
if (msgPtr) moduleInstance._free_buffer(msgPtr);
|
|
84
|
+
return { ok: true, message: "" };
|
|
85
|
+
}
|
|
86
|
+
const messageBytes = moduleInstance.HEAPU8.slice(msgPtr, msgPtr + len);
|
|
87
|
+
moduleInstance._free_buffer(msgPtr);
|
|
88
|
+
const message = new TextDecoder().decode(messageBytes);
|
|
89
|
+
return { ok: false, message };
|
|
90
|
+
}
|
|
91
|
+
workerScope.onmessage = async (event) => {
|
|
92
|
+
const message = event.data;
|
|
93
|
+
try {
|
|
94
|
+
await moduleReady;
|
|
95
|
+
if (!moduleInstance) {
|
|
96
|
+
throw new Error("Module not initialized.");
|
|
97
|
+
}
|
|
98
|
+
if (message.type === "validate") {
|
|
99
|
+
const validation = await validateModel(message.modelBytes);
|
|
100
|
+
workerScope.postMessage({
|
|
101
|
+
type: "validateResult",
|
|
102
|
+
id: message.id,
|
|
103
|
+
ok: validation.ok,
|
|
104
|
+
message: validation.message
|
|
105
|
+
});
|
|
106
|
+
return;
|
|
107
|
+
} else if (message.type === "solve") {
|
|
108
|
+
const bytes = await solveModel(message.modelBytes, message.paramsBytes);
|
|
109
|
+
workerScope.postMessage({
|
|
110
|
+
type: "solveResult",
|
|
111
|
+
id: message.id,
|
|
112
|
+
bytes
|
|
113
|
+
});
|
|
114
|
+
return;
|
|
115
|
+
} else if (message.type === "getSchemas") {
|
|
116
|
+
const schemas = {
|
|
117
|
+
cp_model: moduleInstance.ccall("get_cp_model_schema", "string", [], []),
|
|
118
|
+
sat_parameters: moduleInstance.ccall("get_sat_parameters_schema", "string", [], [])
|
|
119
|
+
};
|
|
120
|
+
self.postMessage({ type: "schemaResult", id: message.id, schemas });
|
|
121
|
+
return;
|
|
122
|
+
} else if (message.type === "cancel_solve") {
|
|
123
|
+
moduleInstance.ccall("interrupt_solve", "void", [], []);
|
|
124
|
+
self.postMessage({ type: "solved_cancelled", id: message.id });
|
|
125
|
+
return;
|
|
126
|
+
}
|
|
127
|
+
} catch (error) {
|
|
128
|
+
console.error("[cpsat_worker] request failed", message?.type, error);
|
|
129
|
+
workerScope.postMessage({
|
|
130
|
+
type: "error",
|
|
131
|
+
id: message?.id ?? 0,
|
|
132
|
+
error: String(error)
|
|
133
|
+
});
|
|
134
|
+
}
|
|
135
|
+
};
|
|
File without changes
|