onnxruntime-node 1.21.0 → 1.22.0-dev.20250418-c19a49615b

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 (46) hide show
  1. package/README.md +19 -14
  2. package/__commit.txt +1 -0
  3. package/bin/{napi-v3/darwin/arm64/libonnxruntime.1.21.0.dylib → napi-v6/darwin/arm64/libonnxruntime.1.22.0.dylib} +0 -0
  4. package/bin/napi-v6/darwin/arm64/onnxruntime_binding.node +0 -0
  5. package/bin/{napi-v3/darwin/x64/libonnxruntime.1.21.0.dylib → napi-v6/darwin/x64/libonnxruntime.1.22.0.dylib} +0 -0
  6. package/bin/napi-v6/darwin/x64/onnxruntime_binding.node +0 -0
  7. package/bin/{napi-v3 → napi-v6}/linux/arm64/libonnxruntime.so.1 +0 -0
  8. package/bin/napi-v6/linux/arm64/onnxruntime_binding.node +0 -0
  9. package/bin/napi-v6/linux/x64/libonnxruntime.so.1 +0 -0
  10. package/bin/napi-v6/linux/x64/onnxruntime_binding.node +0 -0
  11. package/bin/{napi-v3 → napi-v6}/win32/arm64/DirectML.dll +0 -0
  12. package/bin/{napi-v3/linux/x64/libonnxruntime.so.1 → napi-v6/win32/arm64/dxcompiler.dll} +0 -0
  13. package/bin/napi-v6/win32/arm64/dxil.dll +0 -0
  14. package/bin/{napi-v3/linux/x64/libonnxruntime.so.1.21.0 → napi-v6/win32/arm64/onnxruntime.dll} +0 -0
  15. package/bin/napi-v6/win32/arm64/onnxruntime_binding.node +0 -0
  16. package/bin/{napi-v3 → napi-v6}/win32/x64/DirectML.dll +0 -0
  17. package/bin/{napi-v3/linux/arm64/libonnxruntime.so.1.21.0 → napi-v6/win32/x64/dxcompiler.dll} +0 -0
  18. package/bin/napi-v6/win32/x64/dxil.dll +0 -0
  19. package/bin/{napi-v3/win32/arm64 → napi-v6/win32/x64}/onnxruntime.dll +0 -0
  20. package/bin/napi-v6/win32/x64/onnxruntime_binding.node +0 -0
  21. package/dist/backend.js +71 -2
  22. package/dist/backend.js.map +1 -1
  23. package/dist/binding.d.ts +9 -2
  24. package/dist/binding.js +1 -1
  25. package/dist/binding.js.map +1 -1
  26. package/dist/version.d.ts +1 -1
  27. package/dist/version.js +1 -1
  28. package/dist/version.js.map +1 -1
  29. package/lib/backend.ts +79 -2
  30. package/lib/binding.ts +10 -3
  31. package/lib/version.ts +1 -1
  32. package/package.json +4 -6
  33. package/script/build.js +92 -69
  34. package/script/install-metadata-versions.js +12 -0
  35. package/script/install-metadata.js +58 -0
  36. package/script/install-utils.js +306 -0
  37. package/script/install.js +94 -159
  38. package/script/prepack.js +49 -32
  39. package/bin/napi-v3/darwin/arm64/onnxruntime_binding.node +0 -0
  40. package/bin/napi-v3/darwin/x64/onnxruntime_binding.node +0 -0
  41. package/bin/napi-v3/linux/arm64/onnxruntime_binding.node +0 -0
  42. package/bin/napi-v3/linux/x64/libonnxruntime_providers_shared.so +0 -0
  43. package/bin/napi-v3/linux/x64/onnxruntime_binding.node +0 -0
  44. package/bin/napi-v3/win32/arm64/onnxruntime_binding.node +0 -0
  45. package/bin/napi-v3/win32/x64/onnxruntime.dll +0 -0
  46. package/bin/napi-v3/win32/x64/onnxruntime_binding.node +0 -0
package/script/build.js CHANGED
@@ -1,49 +1,68 @@
1
- "use strict";
1
+ 'use strict';
2
2
  // Copyright (c) Microsoft Corporation. All rights reserved.
3
3
  // Licensed under the MIT License.
4
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
5
- if (k2 === undefined) k2 = k;
6
- var desc = Object.getOwnPropertyDescriptor(m, k);
7
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
8
- desc = { enumerable: true, get: function() { return m[k]; } };
9
- }
10
- Object.defineProperty(o, k2, desc);
11
- }) : (function(o, m, k, k2) {
12
- if (k2 === undefined) k2 = k;
13
- o[k2] = m[k];
14
- }));
15
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
16
- Object.defineProperty(o, "default", { enumerable: true, value: v });
17
- }) : function(o, v) {
18
- o["default"] = v;
19
- });
20
- var __importStar = (this && this.__importStar) || function (mod) {
4
+ var __createBinding =
5
+ (this && this.__createBinding) ||
6
+ (Object.create
7
+ ? function (o, m, k, k2) {
8
+ if (k2 === undefined) k2 = k;
9
+ var desc = Object.getOwnPropertyDescriptor(m, k);
10
+ if (!desc || ('get' in desc ? !m.__esModule : desc.writable || desc.configurable)) {
11
+ desc = {
12
+ enumerable: true,
13
+ get: function () {
14
+ return m[k];
15
+ },
16
+ };
17
+ }
18
+ Object.defineProperty(o, k2, desc);
19
+ }
20
+ : function (o, m, k, k2) {
21
+ if (k2 === undefined) k2 = k;
22
+ o[k2] = m[k];
23
+ });
24
+ var __setModuleDefault =
25
+ (this && this.__setModuleDefault) ||
26
+ (Object.create
27
+ ? function (o, v) {
28
+ Object.defineProperty(o, 'default', { enumerable: true, value: v });
29
+ }
30
+ : function (o, v) {
31
+ o['default'] = v;
32
+ });
33
+ var __importStar =
34
+ (this && this.__importStar) ||
35
+ function (mod) {
21
36
  if (mod && mod.__esModule) return mod;
22
37
  var result = {};
23
- if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
38
+ if (mod != null)
39
+ for (var k in mod)
40
+ if (k !== 'default' && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
24
41
  __setModuleDefault(result, mod);
25
42
  return result;
26
- };
27
- var __importDefault = (this && this.__importDefault) || function (mod) {
28
- return (mod && mod.__esModule) ? mod : { "default": mod };
29
- };
30
- Object.defineProperty(exports, "__esModule", { value: true });
31
- const child_process_1 = require("child_process");
32
- const fs = __importStar(require("fs-extra"));
33
- const minimist_1 = __importDefault(require("minimist"));
34
- const os = __importStar(require("os"));
35
- const path = __importStar(require("path"));
43
+ };
44
+ var __importDefault =
45
+ (this && this.__importDefault) ||
46
+ function (mod) {
47
+ return mod && mod.__esModule ? mod : { default: mod };
48
+ };
49
+ Object.defineProperty(exports, '__esModule', { value: true });
50
+ const child_process_1 = require('child_process');
51
+ const fs = __importStar(require('fs-extra'));
52
+ const minimist_1 = __importDefault(require('minimist'));
53
+ const os = __importStar(require('os'));
54
+ const path = __importStar(require('path'));
36
55
  // command line flags
37
56
  const buildArgs = (0, minimist_1.default)(process.argv.slice(2));
38
57
  // --config=Debug|Release|RelWithDebInfo
39
58
  const CONFIG = buildArgs.config || (os.platform() === 'win32' ? 'RelWithDebInfo' : 'Release');
40
59
  if (CONFIG !== 'Debug' && CONFIG !== 'Release' && CONFIG !== 'RelWithDebInfo') {
41
- throw new Error(`unrecognized config: ${CONFIG}`);
60
+ throw new Error(`unrecognized config: ${CONFIG}`);
42
61
  }
43
62
  // --arch=x64|ia32|arm64|arm
44
63
  const ARCH = buildArgs.arch || os.arch();
45
64
  if (ARCH !== 'x64' && ARCH !== 'ia32' && ARCH !== 'arm64' && ARCH !== 'arm') {
46
- throw new Error(`unrecognized architecture: ${ARCH}`);
65
+ throw new Error(`unrecognized architecture: ${ARCH}`);
47
66
  }
48
67
  // --onnxruntime-build-dir=
49
68
  const ONNXRUNTIME_BUILD_DIR = buildArgs['onnxruntime-build-dir'];
@@ -71,78 +90,82 @@ const BIN_FOLDER = path.join(ROOT_FOLDER, 'bin');
71
90
  const BUILD_FOLDER = path.join(ROOT_FOLDER, 'build');
72
91
  // if rebuild, clean up the dist folders
73
92
  if (REBUILD) {
74
- fs.removeSync(BIN_FOLDER);
75
- fs.removeSync(BUILD_FOLDER);
93
+ fs.removeSync(BIN_FOLDER);
94
+ fs.removeSync(BUILD_FOLDER);
76
95
  }
77
96
  const args = [
78
- 'cmake-js',
79
- REBUILD ? 'reconfigure' : 'configure',
80
- `--arch=${ARCH}`,
81
- '--CDnapi_build_version=6',
82
- `--CDCMAKE_BUILD_TYPE=${CONFIG}`,
97
+ 'cmake-js',
98
+ REBUILD ? 'reconfigure' : 'configure',
99
+ `--arch=${ARCH}`,
100
+ '--CDnapi_build_version=6',
101
+ `--CDCMAKE_BUILD_TYPE=${CONFIG}`,
83
102
  ];
84
103
  if (ONNXRUNTIME_BUILD_DIR && typeof ONNXRUNTIME_BUILD_DIR === 'string') {
85
- args.push(`--CDONNXRUNTIME_BUILD_DIR=${ONNXRUNTIME_BUILD_DIR}`);
104
+ args.push(`--CDONNXRUNTIME_BUILD_DIR=${ONNXRUNTIME_BUILD_DIR}`);
86
105
  }
87
106
  if (ONNXRUNTIME_GENERATOR && typeof ONNXRUNTIME_GENERATOR === 'string') {
88
- args.push(`--CDONNXRUNTIME_GENERATOR=${ONNXRUNTIME_GENERATOR}`);
107
+ args.push(`--CDONNXRUNTIME_GENERATOR=${ONNXRUNTIME_GENERATOR}`);
89
108
  }
90
109
  if (USE_DML) {
91
- args.push('--CDUSE_DML=ON');
110
+ args.push('--CDUSE_DML=ON');
92
111
  }
93
112
  if (USE_WEBGPU) {
94
- args.push('--CDUSE_WEBGPU=ON');
113
+ args.push('--CDUSE_WEBGPU=ON');
95
114
  }
96
115
  if (USE_CUDA) {
97
- args.push('--CDUSE_CUDA=ON');
116
+ args.push('--CDUSE_CUDA=ON');
98
117
  }
99
118
  if (USE_TENSORRT) {
100
- args.push('--CDUSE_TENSORRT=ON');
119
+ args.push('--CDUSE_TENSORRT=ON');
101
120
  }
102
121
  if (USE_COREML) {
103
- args.push('--CDUSE_COREML=ON');
122
+ args.push('--CDUSE_COREML=ON');
104
123
  }
105
124
  if (USE_QNN) {
106
- args.push('--CDUSE_QNN=ON');
125
+ args.push('--CDUSE_QNN=ON');
107
126
  }
108
127
  if (DLL_DEPS) {
109
- args.push(`--CDORT_NODEJS_DLL_DEPS=${DLL_DEPS}`);
128
+ args.push(`--CDORT_NODEJS_DLL_DEPS=${DLL_DEPS}`);
110
129
  }
111
130
  // set CMAKE_OSX_ARCHITECTURES for macOS build
112
131
  if (os.platform() === 'darwin') {
113
- if (ARCH === 'x64') {
114
- args.push('--CDCMAKE_OSX_ARCHITECTURES=x86_64');
115
- }
116
- else if (ARCH === 'arm64') {
117
- args.push('--CDCMAKE_OSX_ARCHITECTURES=arm64');
118
- }
119
- else {
120
- throw new Error(`architecture not supported for macOS build: ${ARCH}`);
121
- }
132
+ if (ARCH === 'x64') {
133
+ args.push('--CDCMAKE_OSX_ARCHITECTURES=x86_64');
134
+ } else if (ARCH === 'arm64') {
135
+ args.push('--CDCMAKE_OSX_ARCHITECTURES=arm64');
136
+ } else {
137
+ throw new Error(`architecture not supported for macOS build: ${ARCH}`);
138
+ }
122
139
  }
123
140
  // In Windows, "npx cmake-js configure" uses a powershell script to detect the Visual Studio installation.
124
141
  // The script uses the environment variable LIB. If an invalid path is specified in LIB, the script will fail.
125
142
  // So we override the LIB environment variable to remove invalid paths.
126
- const envOverride = os.platform() === 'win32' && process.env.LIB
143
+ const envOverride =
144
+ os.platform() === 'win32' && process.env.LIB
127
145
  ? { ...process.env, LIB: process.env.LIB.split(';').filter(fs.existsSync).join(';') }
128
146
  : process.env;
129
147
  // launch cmake-js configure
130
- const procCmakejs = (0, child_process_1.spawnSync)('npx', args, { shell: true, stdio: 'inherit', cwd: ROOT_FOLDER, env: envOverride });
148
+ const procCmakejs = (0, child_process_1.spawnSync)('npx', args, {
149
+ shell: true,
150
+ stdio: 'inherit',
151
+ cwd: ROOT_FOLDER,
152
+ env: envOverride,
153
+ });
131
154
  if (procCmakejs.status !== 0) {
132
- if (procCmakejs.error) {
133
- console.error(procCmakejs.error);
134
- }
135
- process.exit(procCmakejs.status === null ? undefined : procCmakejs.status);
155
+ if (procCmakejs.error) {
156
+ console.error(procCmakejs.error);
157
+ }
158
+ process.exit(procCmakejs.status === null ? undefined : procCmakejs.status);
136
159
  }
137
160
  // launch cmake to build
138
161
  const procCmake = (0, child_process_1.spawnSync)('cmake', ['--build', '.', '--config', CONFIG], {
139
- shell: true,
140
- stdio: 'inherit',
141
- cwd: BUILD_FOLDER,
162
+ shell: true,
163
+ stdio: 'inherit',
164
+ cwd: BUILD_FOLDER,
142
165
  });
143
166
  if (procCmake.status !== 0) {
144
- if (procCmake.error) {
145
- console.error(procCmake.error);
146
- }
147
- process.exit(procCmake.status === null ? undefined : procCmake.status);
167
+ if (procCmake.error) {
168
+ console.error(procCmake.error);
169
+ }
170
+ process.exit(procCmake.status === null ? undefined : procCmake.status);
148
171
  }
@@ -0,0 +1,12 @@
1
+ // Copyright (c) Microsoft Corporation. All rights reserved.
2
+ // Licensed under the MIT License.
3
+
4
+ // This file is generated by /js/scripts/update-version.ts
5
+ // Do not modify file content manually.
6
+
7
+ module.exports = {
8
+ nuget: [
9
+ { feed: 'nuget_nightly', version: '1.22.0-dev-20250418-1104-c19a49615b' },
10
+ { feed: 'nuget_nightly', version: '1.22.0-dev-20250409-0707-89f8206ba4' },
11
+ ],
12
+ };
@@ -0,0 +1,58 @@
1
+ // Copyright (c) Microsoft Corporation. All rights reserved.
2
+ // Licensed under the MIT License.
3
+
4
+ 'use strict';
5
+
6
+ const metadataVersions = require('./install-metadata-versions.js');
7
+
8
+ const metadata = {
9
+ // Requirements defines a list of manifest to install for a specific platform/architecture combination.
10
+ requirements: {
11
+ 'win32/x64': [],
12
+ 'win32/arm64': [],
13
+ 'linux/x64': ['cuda12'],
14
+ 'linux/arm64': [],
15
+ 'darwin/x64': [],
16
+ 'darwin/arm64': [],
17
+ },
18
+ // Each manifest defines a list of files to install
19
+ manifests: {
20
+ 'linux/x64:cuda12': {
21
+ './libonnxruntime_providers_cuda.so': {
22
+ package: 'nuget:linux/x64:cuda12',
23
+ path: 'runtimes/win-x64/native/libonnxruntime_providers_cuda.so',
24
+ },
25
+ './libonnxruntime_providers_shared.so': {
26
+ package: 'nuget:linux/x64:cuda12',
27
+ path: 'runtimes/win-x64/native/libonnxruntime_providers_shared.so',
28
+ },
29
+ './libonnxruntime_providers_tensorrt.so': {
30
+ package: 'nuget:linux/x64:cuda12',
31
+ path: 'runtimes/win-x64/native/libonnxruntime_providers_tensorrt.so',
32
+ },
33
+ },
34
+ },
35
+ // Each package defines a list of package metadata. The first available package will be used.
36
+ packages: {
37
+ 'nuget:win32/x64:cuda12': {
38
+ name: 'Microsoft.ML.OnnxRuntime.Gpu.Windows',
39
+ versions: metadataVersions.nuget,
40
+ },
41
+ 'nuget:linux/x64:cuda12': {
42
+ name: 'Microsoft.ML.OnnxRuntime.Gpu.Linux',
43
+ versions: metadataVersions.nuget,
44
+ },
45
+ },
46
+ feeds: {
47
+ nuget: {
48
+ type: 'nuget',
49
+ index: 'https://api.nuget.org/v3/index.json',
50
+ },
51
+ nuget_nightly: {
52
+ type: 'nuget',
53
+ index: 'https://aiinfra.pkgs.visualstudio.com/PublicPackages/_packaging/ORT-Nightly/nuget/v3/index.json',
54
+ },
55
+ },
56
+ };
57
+
58
+ module.exports = metadata;
@@ -0,0 +1,306 @@
1
+ // Copyright (c) Microsoft Corporation. All rights reserved.
2
+ // Licensed under the MIT License.
3
+
4
+ 'use strict';
5
+
6
+ const fs = require('fs');
7
+ const https = require('https');
8
+ const { execFileSync } = require('child_process');
9
+ const path = require('path');
10
+ const os = require('os');
11
+ const AdmZip = require('adm-zip'); // Use adm-zip instead of spawn
12
+
13
+ async function downloadFile(url, dest) {
14
+ return new Promise((resolve, reject) => {
15
+ const file = fs.createWriteStream(dest);
16
+ https
17
+ .get(url, (res) => {
18
+ if (res.statusCode !== 200) {
19
+ file.close();
20
+ fs.unlinkSync(dest);
21
+ reject(new Error(`Failed to download from ${url}. HTTP status code = ${res.statusCode}`));
22
+ return;
23
+ }
24
+
25
+ res.pipe(file);
26
+ file.on('finish', () => {
27
+ file.close();
28
+ resolve();
29
+ });
30
+ file.on('error', (err) => {
31
+ fs.unlinkSync(dest);
32
+ reject(err);
33
+ });
34
+ })
35
+ .on('error', (err) => {
36
+ fs.unlinkSync(dest);
37
+ reject(err);
38
+ });
39
+ });
40
+ }
41
+
42
+ async function downloadJson(url) {
43
+ return new Promise((resolve, reject) => {
44
+ https
45
+ .get(url, (res) => {
46
+ const { statusCode } = res;
47
+ const contentType = res.headers['content-type'];
48
+
49
+ if (!statusCode) {
50
+ reject(new Error('No response statud code from server.'));
51
+ return;
52
+ }
53
+ if (statusCode >= 400 && statusCode < 500) {
54
+ resolve(null);
55
+ return;
56
+ } else if (statusCode !== 200) {
57
+ reject(new Error(`Failed to download build list. HTTP status code = ${statusCode}`));
58
+ return;
59
+ }
60
+ if (!contentType || !/^application\/json/.test(contentType)) {
61
+ reject(new Error(`unexpected content type: ${contentType}`));
62
+ return;
63
+ }
64
+ res.setEncoding('utf8');
65
+ let rawData = '';
66
+ res.on('data', (chunk) => {
67
+ rawData += chunk;
68
+ });
69
+ res.on('end', () => {
70
+ try {
71
+ resolve(JSON.parse(rawData));
72
+ } catch (e) {
73
+ reject(e);
74
+ }
75
+ });
76
+ res.on('error', (err) => {
77
+ reject(err);
78
+ });
79
+ })
80
+ .on('error', (err) => {
81
+ reject(err);
82
+ });
83
+ });
84
+ }
85
+
86
+ async function installPackages(packages, manifests, feeds) {
87
+ // Step.1: resolve packages
88
+ const resolvedPackages = new Map();
89
+ for (const packageCandidates of packages) {
90
+ // iterate all candidates from packagesInfo and try to find the first one that exists
91
+ for (const { feed, version } of packageCandidates.versions) {
92
+ const { type, index } = feeds[feed];
93
+ const pkg = await resolvePackage(type, index, packageCandidates.name, version);
94
+ if (pkg) {
95
+ resolvedPackages.set(packageCandidates, pkg);
96
+ break;
97
+ }
98
+ }
99
+ if (!resolvedPackages.has(packageCandidates)) {
100
+ throw new Error(`Failed to resolve package. No package exists for: ${JSON.stringify(packageCandidates)}`);
101
+ }
102
+ }
103
+
104
+ // Step.2: download packages
105
+ for (const [pkgInfo, pkg] of resolvedPackages) {
106
+ const manifestsForPackage = manifests.filter((x) => x.packagesInfo === pkgInfo);
107
+ await pkg.download(manifestsForPackage);
108
+ }
109
+ }
110
+
111
+ async function resolvePackage(type, index, packageName, version) {
112
+ // https://learn.microsoft.com/en-us/nuget/api/overview
113
+ const nugetPackageUrlResolver = async (index, packageName, version) => {
114
+ // STEP.1 - get Nuget package index
115
+ const nugetIndex = await downloadJson(index);
116
+ if (!nugetIndex) {
117
+ throw new Error(`Failed to download Nuget index from ${index}`);
118
+ }
119
+
120
+ // STEP.2 - get the base url of "PackageBaseAddress/3.0.0"
121
+ const packageBaseUrl = nugetIndex.resources.find((x) => x['@type'] === 'PackageBaseAddress/3.0.0')?.['@id'];
122
+ if (!packageBaseUrl) {
123
+ throw new Error(`Failed to find PackageBaseAddress in Nuget index`);
124
+ }
125
+
126
+ // STEP.3 - get the package version info
127
+ const packageInfo = await downloadJson(`${packageBaseUrl}${packageName.toLowerCase()}/index.json`);
128
+ if (!packageInfo.versions.includes(version.toLowerCase())) {
129
+ throw new Error(`Failed to find specific package versions for ${packageName} in ${index}`);
130
+ }
131
+
132
+ // STEP.4 - generate the package URL
133
+ const packageUrl = `${packageBaseUrl}${packageName.toLowerCase()}/${version.toLowerCase()}/${packageName.toLowerCase()}.${version.toLowerCase()}.nupkg`;
134
+ const packageFileName = `${packageName.toLowerCase()}.${version.toLowerCase()}.nupkg`;
135
+
136
+ return {
137
+ download: async (manifests) => {
138
+ if (manifests.length === 0) {
139
+ return;
140
+ }
141
+
142
+ // Create a temporary directory
143
+ const tempDir = path.join(os.tmpdir(), `onnxruntime-node-pkgs_${Date.now()}`);
144
+ fs.mkdirSync(tempDir, { recursive: true });
145
+
146
+ try {
147
+ const packageFilePath = path.join(tempDir, packageFileName);
148
+
149
+ // Download the NuGet package
150
+ console.log(`Downloading ${packageUrl}`);
151
+ await downloadFile(packageUrl, packageFilePath);
152
+
153
+ // Load the NuGet package (which is a ZIP file)
154
+ let zip;
155
+ try {
156
+ zip = new AdmZip(packageFilePath);
157
+ } catch (err) {
158
+ throw new Error(`Failed to open NuGet package: ${err.message}`);
159
+ }
160
+
161
+ // Extract only the needed files from the package
162
+ const extractDir = path.join(tempDir, 'extracted');
163
+ fs.mkdirSync(extractDir, { recursive: true });
164
+
165
+ // Process each manifest and extract/copy files to their destinations
166
+ for (const manifest of manifests) {
167
+ const { filepath, pathInPackage } = manifest;
168
+
169
+ // Create directory for the target file
170
+ const targetDir = path.dirname(filepath);
171
+ fs.mkdirSync(targetDir, { recursive: true });
172
+
173
+ // Check if the file exists directly in the zip
174
+ const zipEntry = zip.getEntry(pathInPackage);
175
+ if (!zipEntry) {
176
+ throw new Error(`Failed to find ${pathInPackage} in NuGet package`);
177
+ }
178
+
179
+ console.log(`Extracting ${pathInPackage} to ${filepath}`);
180
+
181
+ // Extract just this entry to a temporary location
182
+ const extractedFilePath = path.join(extractDir, path.basename(pathInPackage));
183
+ zip.extractEntryTo(zipEntry, extractDir, false, true);
184
+
185
+ // Copy to the final destination
186
+ fs.copyFileSync(extractedFilePath, filepath);
187
+ }
188
+ } finally {
189
+ // Clean up the temporary directory - always runs even if an error occurs
190
+ try {
191
+ fs.rmSync(tempDir, { recursive: true });
192
+ } catch (e) {
193
+ console.warn(`Failed to clean up temporary directory: ${tempDir}`, e);
194
+ // Don't rethrow this error as it would mask the original error
195
+ }
196
+ }
197
+ },
198
+ };
199
+ };
200
+
201
+ switch (type) {
202
+ case 'nuget':
203
+ return await nugetPackageUrlResolver(index, packageName, version);
204
+ default:
205
+ throw new Error(`Unsupported package type: ${type}`);
206
+ }
207
+ }
208
+
209
+ function tryGetCudaVersion() {
210
+ // Should only return 11 or 12.
211
+
212
+ // try to get the CUDA version from the system ( `nvcc --version` )
213
+ let ver = 12;
214
+ try {
215
+ const nvccVersion = execFileSync('nvcc', ['--version'], { encoding: 'utf8' });
216
+ const match = nvccVersion.match(/release (\d+)/);
217
+ if (match) {
218
+ ver = parseInt(match[1]);
219
+ if (ver !== 11 && ver !== 12) {
220
+ throw new Error(`Unsupported CUDA version: ${ver}`);
221
+ }
222
+ }
223
+ } catch (e) {
224
+ if (e?.code === 'ENOENT') {
225
+ console.warn('`nvcc` not found. Assuming CUDA 12.');
226
+ } else {
227
+ console.warn('Failed to detect CUDA version from `nvcc --version`:', e.message);
228
+ }
229
+ }
230
+
231
+ // assume CUDA 12 if failed to detect
232
+ return ver;
233
+ }
234
+
235
+ function parseInstallFlag() {
236
+ let flag = process.env.ONNXRUNTIME_NODE_INSTALL || process.env.npm_config_onnxruntime_node_install;
237
+ if (!flag) {
238
+ for (let i = 0; i < process.argv.length; i++) {
239
+ if (process.argv[i].startsWith('--onnxruntime-node-install=')) {
240
+ flag = process.argv[i].split('=')[1];
241
+ break;
242
+ } else if (process.argv[i] === '--onnxruntime-node-install') {
243
+ flag = 'true';
244
+ }
245
+ }
246
+ }
247
+ switch (flag) {
248
+ case 'true':
249
+ case '1':
250
+ case 'ON':
251
+ return true;
252
+ case 'skip':
253
+ return false;
254
+ case undefined: {
255
+ flag = parseInstallCudaFlag();
256
+ if (flag === 'skip') {
257
+ return false;
258
+ }
259
+ if (flag === 11) {
260
+ throw new Error('CUDA 11 is no longer supported. Please consider using CPU or upgrade to CUDA 12.');
261
+ }
262
+ if (flag === 12) {
263
+ return 'cuda12';
264
+ }
265
+ return undefined;
266
+ }
267
+ default:
268
+ if (!flag || typeof flag !== 'string') {
269
+ throw new Error(`Invalid value for --onnxruntime-node-install: ${flag}`);
270
+ }
271
+ }
272
+ }
273
+
274
+ function parseInstallCudaFlag() {
275
+ let flag = process.env.ONNXRUNTIME_NODE_INSTALL_CUDA || process.env.npm_config_onnxruntime_node_install_cuda;
276
+ if (!flag) {
277
+ for (let i = 0; i < process.argv.length; i++) {
278
+ if (process.argv[i].startsWith('--onnxruntime-node-install-cuda=')) {
279
+ flag = process.argv[i].split('=')[1];
280
+ break;
281
+ } else if (process.argv[i] === '--onnxruntime-node-install-cuda') {
282
+ flag = 'true';
283
+ }
284
+ }
285
+ }
286
+ switch (flag) {
287
+ case 'true':
288
+ case '1':
289
+ case 'ON':
290
+ return tryGetCudaVersion();
291
+ case 'v11':
292
+ return 11;
293
+ case 'v12':
294
+ return 12;
295
+ case 'skip':
296
+ case undefined:
297
+ return flag;
298
+ default:
299
+ throw new Error(`Invalid value for --onnxruntime-node-install-cuda: ${flag}`);
300
+ }
301
+ }
302
+
303
+ module.exports = {
304
+ installPackages,
305
+ parseInstallFlag,
306
+ };