@jsprismarine/native-library 0.0.0 → 0.24.0-unstable-20261121104535
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +19 -0
- package/LICENSE +21 -0
- package/README.md +56 -43
- package/dist/NativeLibrary.d.ts +186 -0
- package/dist/NativeLibrary.d.ts.map +1 -0
- package/dist/NativeLibrary.js +316 -0
- package/dist/NativeLibrary.js.map +1 -0
- package/dist/isRecord.d.ts +3 -0
- package/dist/isRecord.d.ts.map +1 -0
- package/dist/isRecord.js +6 -0
- package/dist/isRecord.js.map +1 -0
- package/dist/manifest.d.ts +40 -0
- package/dist/manifest.d.ts.map +1 -0
- package/dist/manifest.js +46 -0
- package/dist/manifest.js.map +1 -0
- package/dist/nativeHash.d.ts +18 -0
- package/dist/nativeHash.d.ts.map +1 -0
- package/dist/nativeHash.js +48 -0
- package/dist/nativeHash.js.map +1 -0
- package/dist/platform.d.ts +46 -0
- package/dist/platform.d.ts.map +1 -0
- package/dist/platform.js +66 -0
- package/dist/platform.js.map +1 -0
- package/package.json +71 -7
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
# @jsprismarine/native-library
|
|
2
|
+
|
|
3
|
+
## 0.24.0-unstable-20261121104535
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- [#3513](https://github.com/JSPrismarine/JSPrismarine/pull/3513) [`cce50d8`](https://github.com/JSPrismarine/JSPrismarine/commit/cce50d8d16917a3ad6843be08c35e15af5aab7c4) Thanks [@filiphsps](https://github.com/filiphsps)! - Add `@jsprismarine/native-library`, which finds, checks and installs a package's prebuilt native library. `@jsprismarine/native-network` and `@jsprismarine/script-host` now load their libraries through it, so both behave the same way.
|
|
8
|
+
|
|
9
|
+
Breaking changes:
|
|
10
|
+
|
|
11
|
+
- The errors for a missing, unverified or undownloadable library, and for a malformed native manifest (`InvalidNativeManifest`, `InvalidNativeManifestEntry`), moved from `NativeNetworkErrors` and `ScriptHostErrors` to `NativeLibraryErrors` in `@jsprismarine/errors/native-library`, and their codes now start with `NATIVE_LIBRARY_`.
|
|
12
|
+
- `NativeLibraryError` is now exported only from `@jsprismarine/errors/native-library`, so one `instanceof` check catches loading errors from either package.
|
|
13
|
+
- `@jsprismarine/script-host/library` no longer exports `localBuildDigest`, `recordLocalBuild` or the `LocateOptions` type. `LocateOptions` comes from `@jsprismarine/native-library`, and `NativeLibrary` covers what the other two did.
|
|
14
|
+
- `@jsprismarine/script-host/manifest` is removed. Import the manifest parser from `@jsprismarine/native-library/manifest`.
|
|
15
|
+
- In a checkout, `@jsprismarine/native-network` on a platform without a published build now says how to build the library instead of saying no build is published.
|
|
16
|
+
|
|
17
|
+
A packager's `libraryForPlatform` now replaces an installed file that fails its digest check with the published build instead of throwing.
|
|
18
|
+
- Updated dependencies [[`54ae4dd`](https://github.com/JSPrismarine/JSPrismarine/commit/54ae4dd998002a49935182a1c32a301a9c9a1c3a), [`1f3b347`](https://github.com/JSPrismarine/JSPrismarine/commit/1f3b347d94e934767993eb3506a412b01d334a0b), [`3c19f11`](https://github.com/JSPrismarine/JSPrismarine/commit/3c19f11b712b228563d7af7fc5f6df6995726fe3), [`f4eb592`](https://github.com/JSPrismarine/JSPrismarine/commit/f4eb5921862accbb5e07749c38bd1c63495587a0), [`b30a127`](https://github.com/JSPrismarine/JSPrismarine/commit/b30a1272d2d0ebee7e6c73c69d6b2c87ba06e9fa), [`cce50d8`](https://github.com/JSPrismarine/JSPrismarine/commit/cce50d8d16917a3ad6843be08c35e15af5aab7c4)]:
|
|
19
|
+
- @jsprismarine/errors@0.24.0-unstable-20261121104535
|
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 JSPrismarine Contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,45 +1,58 @@
|
|
|
1
1
|
# @jsprismarine/native-library
|
|
2
2
|
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
3
|
+
[](https://github.com/JSPrismarine/JSPrismarine#readme)
|
|
4
|
+
[](https://discord.gg/kZZCDyCBbW)
|
|
5
|
+
[](https://www.npmjs.com/package/@jsprismarine/native-library)
|
|
6
|
+
|
|
7
|
+
Finds, verifies and installs the prebuilt native libraries JSPrismarine's packages load.
|
|
8
|
+
|
|
9
|
+
JSPrismarine's packages that call C through `node:ffi`, such as
|
|
10
|
+
[`@jsprismarine/native-network`](../native-network/README.md) and
|
|
11
|
+
[`@jsprismarine/script-host`](../script-host/README.md), publish their library as one prebuilt file
|
|
12
|
+
per platform on a GitHub release. This package holds what they share to get that file onto a
|
|
13
|
+
machine and check it before it is loaded.
|
|
14
|
+
|
|
15
|
+
## What a package gets
|
|
16
|
+
|
|
17
|
+
A package describes its library once:
|
|
18
|
+
|
|
19
|
+
```ts
|
|
20
|
+
import { NativeLibrary } from '@jsprismarine/native-library';
|
|
21
|
+
|
|
22
|
+
import manifest from '../native/manifest.json' with { type: 'json' };
|
|
23
|
+
|
|
24
|
+
export const library = new NativeLibrary({
|
|
25
|
+
packageName: '@jsprismarine/example',
|
|
26
|
+
library: 'libjsp_example',
|
|
27
|
+
envPrefix: 'JSP_EXAMPLE',
|
|
28
|
+
packageDir: packageRoot(),
|
|
29
|
+
manifest,
|
|
30
|
+
buildScripts: ['scripts/build-native.mts']
|
|
31
|
+
});
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
From that, `library.install({ packageDir: library.packageDir })` is the package's install script: it downloads the build for the
|
|
35
|
+
machine from the release the manifest names, checks its SHA-256, and stores it under
|
|
36
|
+
`prebuilds/<platform>/`. `library.locate()` finds that file, or the one the package's `_LIBRARY`
|
|
37
|
+
variable names, and checks its digest against the manifest or the `build.json` a local
|
|
38
|
+
`build:native` wrote beside it. Locating never downloads. When there is no file, the error says
|
|
39
|
+
how to let the install script run under npm, pnpm and Bun.
|
|
40
|
+
|
|
41
|
+
`library.forPlatform()` and `library.provideEmbedded()` let a single-file executable carry the
|
|
42
|
+
library and write it out on first start.
|
|
43
|
+
|
|
44
|
+
| Variable | What it does |
|
|
45
|
+
| ----------------------------- | --------------------------------------------------------------- |
|
|
46
|
+
| `<envPrefix>_LIBRARY` | Loads this file instead of the installed build, checked as well. |
|
|
47
|
+
| `<envPrefix>_SKIP_DOWNLOAD=1` | The install script downloads nothing. |
|
|
48
|
+
| `<envPrefix>_BASE_URL` | Downloads from another host, or reads from a directory. |
|
|
49
|
+
|
|
50
|
+
## Other modules
|
|
51
|
+
|
|
52
|
+
- `@jsprismarine/native-library/platform` names a machine's platform key, such as
|
|
53
|
+
`linux-x64-musl`, and a library's file names on each operating system.
|
|
54
|
+
- `@jsprismarine/native-library/manifest` parses a package's `native/manifest.json`.
|
|
55
|
+
- `@jsprismarine/native-library/nativeHash` hashes a checkout's native sources, the hash a
|
|
56
|
+
release of builds is named after.
|
|
57
|
+
|
|
58
|
+
[The error reference](../../docs/errors/native-library.md) lists what it throws.
|
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
import type { NativeManifest } from './manifest.js';
|
|
2
|
+
/** What a package that ships a native library tells {@link NativeLibrary} about it. */
|
|
3
|
+
export interface NativeLibraryOptions {
|
|
4
|
+
/** The npm name, as the messages tell a user to approve or build it. */
|
|
5
|
+
readonly packageName: string;
|
|
6
|
+
/** The library's file name without its extension, such as `libjsp_native_network`. */
|
|
7
|
+
readonly library: string;
|
|
8
|
+
/**
|
|
9
|
+
* The prefix of the package's environment variables, such as `JSP_NATIVE_NETWORK`: `_LIBRARY`
|
|
10
|
+
* names a library to load, `_SKIP_DOWNLOAD` skips the install's download, and `_BASE_URL`
|
|
11
|
+
* downloads from a mirror.
|
|
12
|
+
*/
|
|
13
|
+
readonly envPrefix: string;
|
|
14
|
+
/** The package's root, which holds `native/` in a checkout and `prebuilds/` once installed. */
|
|
15
|
+
readonly packageDir: string;
|
|
16
|
+
/**
|
|
17
|
+
* The package's `native/manifest.json`, as imported JSON. It is imported rather than read from
|
|
18
|
+
* disk, so a bundled executable carries it.
|
|
19
|
+
*/
|
|
20
|
+
readonly manifest: unknown;
|
|
21
|
+
/** The files outside `native/` the package's build reads, which its source hash covers. */
|
|
22
|
+
readonly buildScripts: readonly string[];
|
|
23
|
+
}
|
|
24
|
+
/** How {@link NativeLibrary.locate} looks; tests replace each part. */
|
|
25
|
+
export interface LocateOptions {
|
|
26
|
+
readonly env?: NodeJS.ProcessEnv;
|
|
27
|
+
readonly packageDir?: string;
|
|
28
|
+
readonly platform?: string;
|
|
29
|
+
readonly manifest?: NativeManifest;
|
|
30
|
+
}
|
|
31
|
+
/** What an install did. */
|
|
32
|
+
export type InstallOutcome = {
|
|
33
|
+
readonly kind: 'installed';
|
|
34
|
+
readonly path: string;
|
|
35
|
+
readonly bytes: number;
|
|
36
|
+
} | {
|
|
37
|
+
readonly kind: 'present';
|
|
38
|
+
readonly path: string;
|
|
39
|
+
} | {
|
|
40
|
+
readonly kind: 'no-build';
|
|
41
|
+
readonly platform: string;
|
|
42
|
+
} | {
|
|
43
|
+
readonly kind: 'skipped';
|
|
44
|
+
} | {
|
|
45
|
+
readonly kind: 'local-sources';
|
|
46
|
+
readonly sourceHash: string;
|
|
47
|
+
};
|
|
48
|
+
/** How {@link NativeLibrary.install} finds and fetches the build; tests replace the network and the platform. */
|
|
49
|
+
export interface InstallOptions {
|
|
50
|
+
readonly packageDir: string;
|
|
51
|
+
readonly platform?: string;
|
|
52
|
+
readonly env?: NodeJS.ProcessEnv;
|
|
53
|
+
readonly fetch?: (url: string) => Promise<Response>;
|
|
54
|
+
readonly manifest?: NativeManifest;
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* The digest a local build recorded in the `build.json` beside it, which `build:native` writes.
|
|
58
|
+
* @param path - The library file.
|
|
59
|
+
* @returns The digest, or undefined when there is no readable record.
|
|
60
|
+
*/
|
|
61
|
+
export declare const localBuildDigest: (path: string) => string | undefined;
|
|
62
|
+
/**
|
|
63
|
+
* Records a library's digest in a `build.json` beside it, as `build:native` does, so that
|
|
64
|
+
* {@link NativeLibrary.verify} accepts the file. Only for bytes that were checked before they were
|
|
65
|
+
* written there, such as a library an executable embedded.
|
|
66
|
+
* @param path - The library file.
|
|
67
|
+
* @param digest - Its SHA-256.
|
|
68
|
+
*/
|
|
69
|
+
export declare const recordLocalBuild: (path: string, digest: string) => void;
|
|
70
|
+
/**
|
|
71
|
+
* One package's prebuilt native library: where it is installed, how a release publishes it, and
|
|
72
|
+
* how it is found and checked before a runtime loads it.
|
|
73
|
+
*
|
|
74
|
+
* A release attaches a build for each platform to a GitHub release, and the package's
|
|
75
|
+
* `native/manifest.json` records each file's SHA-256. The package's install script downloads the
|
|
76
|
+
* build for the machine; loading only finds the file and checks its digest, and never downloads.
|
|
77
|
+
*/
|
|
78
|
+
export declare class NativeLibrary {
|
|
79
|
+
/** The npm name. */
|
|
80
|
+
readonly packageName: string;
|
|
81
|
+
/** The library's file name without its extension. */
|
|
82
|
+
readonly library: string;
|
|
83
|
+
/** The package's root. */
|
|
84
|
+
readonly packageDir: string;
|
|
85
|
+
/** Names a library file to load in place of the installed build. */
|
|
86
|
+
readonly libraryEnv: string;
|
|
87
|
+
/** Skips the install's download, for an install that brings its own library. */
|
|
88
|
+
readonly skipDownloadEnv: string;
|
|
89
|
+
/** Downloads from another release host or a directory, such as a mirror or a test's fixtures. */
|
|
90
|
+
readonly baseUrlEnv: string;
|
|
91
|
+
private readonly manifestJson;
|
|
92
|
+
private readonly buildScripts;
|
|
93
|
+
private manifest;
|
|
94
|
+
constructor(options: NativeLibraryOptions);
|
|
95
|
+
/**
|
|
96
|
+
* The manifest the package was built with.
|
|
97
|
+
* @returns The manifest, parsed once.
|
|
98
|
+
*/
|
|
99
|
+
bundledManifest(): NativeManifest;
|
|
100
|
+
/**
|
|
101
|
+
* The file name of the shared library on an operating system.
|
|
102
|
+
* @param platform - The operating system, as `process.platform` names it.
|
|
103
|
+
* @returns The file name.
|
|
104
|
+
*/
|
|
105
|
+
sharedLibraryName(platform?: NodeJS.Platform): string;
|
|
106
|
+
/**
|
|
107
|
+
* The file name of the static archive the scriptc build links.
|
|
108
|
+
* @param platform - The operating system, as `process.platform` names it.
|
|
109
|
+
* @returns The file name.
|
|
110
|
+
*/
|
|
111
|
+
staticLibraryName(platform?: NodeJS.Platform): string;
|
|
112
|
+
/**
|
|
113
|
+
* Where a platform's library goes in the package, whether `build:native` built it or the
|
|
114
|
+
* install script downloaded it.
|
|
115
|
+
* @param packageDir - The package's directory.
|
|
116
|
+
* @param platform - The platform key; this machine's by default.
|
|
117
|
+
* @returns `prebuilds/<platform>/<library>` under it.
|
|
118
|
+
*/
|
|
119
|
+
installedLibraryPath(packageDir: string, platform?: string): string;
|
|
120
|
+
/**
|
|
121
|
+
* The hash of the package's native sources in a checkout, which names a release of builds.
|
|
122
|
+
* @param packageDir - The package's directory, holding `native/`.
|
|
123
|
+
* @returns The first 16 hex digits of the SHA-256 over the build's inputs.
|
|
124
|
+
*/
|
|
125
|
+
sourceHash(packageDir?: string): string;
|
|
126
|
+
/**
|
|
127
|
+
* What to tell a user whose install did not fetch the library: the package managers that hold
|
|
128
|
+
* install scripts back, how to let this one run, and the way around it.
|
|
129
|
+
* @param platform - The platform key.
|
|
130
|
+
* @returns The advice, as sentences.
|
|
131
|
+
*/
|
|
132
|
+
approvalAdvice(platform: string): string;
|
|
133
|
+
/**
|
|
134
|
+
* Checks a library file against the digest the manifest publishes for the platform, or the one
|
|
135
|
+
* a local `build:native` recorded beside it.
|
|
136
|
+
* @param path - The file.
|
|
137
|
+
* @param platform - The platform key.
|
|
138
|
+
* @param manifest - The package's manifest.
|
|
139
|
+
* @throws {NativeLibraryError} When neither digest matches.
|
|
140
|
+
*/
|
|
141
|
+
verify(path: string, platform: string, manifest: NativeManifest): void;
|
|
142
|
+
/** Whether {@link verify} accepts a file. */
|
|
143
|
+
private verifies;
|
|
144
|
+
/**
|
|
145
|
+
* Where the library for this machine is, checked against its published digest: the file the
|
|
146
|
+
* `_LIBRARY` variable names, or the build the install script or `build:native` put in the
|
|
147
|
+
* package. Finding it builds and downloads nothing.
|
|
148
|
+
* @param options - The environment, package, platform and manifest; the defaults are this process's.
|
|
149
|
+
* @returns The file's path.
|
|
150
|
+
* @throws {NativeLibraryError} When there is no file, or it is neither the published build nor a local one.
|
|
151
|
+
*/
|
|
152
|
+
locate(options?: LocateOptions): string;
|
|
153
|
+
/**
|
|
154
|
+
* Downloads the build for this machine into the package, once, and checks its SHA-256 against
|
|
155
|
+
* the manifest. It is what the package's `postinstall` runs; loading the library never downloads.
|
|
156
|
+
* @param options - The package and, for tests, the platform, environment and network.
|
|
157
|
+
* @returns What it did.
|
|
158
|
+
* @throws {NativeLibraryErrors.DownloadFailed} When the download fails.
|
|
159
|
+
* @throws {NativeLibraryErrors.DownloadDigestMismatch} When its digest or size differ from the manifest's.
|
|
160
|
+
*/
|
|
161
|
+
install(options: InstallOptions): Promise<InstallOutcome>;
|
|
162
|
+
/**
|
|
163
|
+
* The bytes of a platform's library, for a packager to embed in an executable: the build in the
|
|
164
|
+
* package if it is the published one or a local `build:native`, else the published build,
|
|
165
|
+
* downloaded and checked.
|
|
166
|
+
* @param platform - The platform key the executable is for.
|
|
167
|
+
* @returns The library, or undefined when there is no build for that platform.
|
|
168
|
+
*/
|
|
169
|
+
forPlatform(platform: string): Promise<Uint8Array | undefined>;
|
|
170
|
+
/**
|
|
171
|
+
* Writes an embedded library to a cache directory under its digest, and points the `_LIBRARY`
|
|
172
|
+
* variable at it, unless the user already set it. An operating system loads a shared library
|
|
173
|
+
* only from a file, so an executable has to write it once; a copy already there with the right
|
|
174
|
+
* digest is used as it is.
|
|
175
|
+
*
|
|
176
|
+
* The digest is recorded beside the file as a local build's is, because {@link forPlatform}
|
|
177
|
+
* checked the bytes when they were embedded. A library built from native sources the manifest
|
|
178
|
+
* does not publish yet would otherwise be refused by the executable it was embedded in.
|
|
179
|
+
* @param library - The embedded bytes.
|
|
180
|
+
* @param cacheDir - A writable directory.
|
|
181
|
+
* @param env - The environment to set the variable in.
|
|
182
|
+
* @returns The file's path.
|
|
183
|
+
*/
|
|
184
|
+
provideEmbedded(library: Uint8Array, cacheDir: string, env?: NodeJS.ProcessEnv): string;
|
|
185
|
+
}
|
|
186
|
+
//# sourceMappingURL=NativeLibrary.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"NativeLibrary.d.ts","sources":["../src/NativeLibrary.ts"],"names":[],"mappings":"AAOA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;AAIjD,uFAAuF;AACvF,MAAM,WAAW,oBAAoB;IACjC,wEAAwE;IACxE,QAAQ,CAAC,WAAW,EAAE,MAAM,CAAC;IAC7B,sFAAsF;IACtF,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IACzB;;;;OAIG;IACH,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B,+FAA+F;IAC/F,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC;IAC5B;;;OAGG;IACH,QAAQ,CAAC,QAAQ,EAAE,OAAO,CAAC;IAC3B,2FAA2F;IAC3F,QAAQ,CAAC,YAAY,EAAE,SAAS,MAAM,EAAE,CAAC;CAC5C;AAED,uEAAuE;AACvE,MAAM,WAAW,aAAa;IAC1B,QAAQ,CAAC,GAAG,CAAC,EAAE,MAAM,CAAC,UAAU,CAAC;IACjC,QAAQ,CAAC,UAAU,CAAC,EAAE,MAAM,CAAC;IAC7B,QAAQ,CAAC,QAAQ,CAAC,EAAE,MAAM,CAAC;IAC3B,QAAQ,CAAC,QAAQ,CAAC,EAAE,cAAc,CAAC;CACtC;AAED,2BAA2B;AAC3B,MAAM,MAAM,cAAc,GACpB;IAAE,QAAQ,CAAC,IAAI,EAAE,WAAW,CAAC;IAAC,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IAAC,QAAQ,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CACJ"}
|
|
@@ -0,0 +1,316 @@
|
|
|
1
|
+
import { isRecord } from "./isRecord.js";
|
|
2
|
+
import { parseManifest, sha256 } from "./manifest.js";
|
|
3
|
+
import { hasNativeSources, nativeSourceHash } from "./nativeHash.js";
|
|
4
|
+
import { installedLibraryFile, platformKey, sharedLibraryFile, staticLibraryFile } from "./platform.js";
|
|
5
|
+
import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
|
|
6
|
+
import { dirname, join, resolve } from "node:path";
|
|
7
|
+
import { NativeLibraryErrors } from "@jsprismarine/errors/native-library";
|
|
8
|
+
// src/NativeLibrary.ts
|
|
9
|
+
/** The report `build:native` writes beside a local build, which records the build's digest. */
|
|
10
|
+
var buildReportOf = (path) => join(dirname(path), "build.json");
|
|
11
|
+
/**
|
|
12
|
+
* The digest a local build recorded in the `build.json` beside it, which `build:native` writes.
|
|
13
|
+
* @param path - The library file.
|
|
14
|
+
* @returns The digest, or undefined when there is no readable record.
|
|
15
|
+
*/
|
|
16
|
+
var localBuildDigest = (path) => {
|
|
17
|
+
const report = buildReportOf(path);
|
|
18
|
+
if (!existsSync(report)) return void 0;
|
|
19
|
+
try {
|
|
20
|
+
const parsed = JSON.parse(readFileSync(report, "utf8"));
|
|
21
|
+
const shared = isRecord(parsed) && isRecord(parsed.shared) ? parsed.shared : void 0;
|
|
22
|
+
return typeof shared?.sha256 === "string" ? shared.sha256 : void 0;
|
|
23
|
+
} catch {
|
|
24
|
+
return;
|
|
25
|
+
}
|
|
26
|
+
};
|
|
27
|
+
/**
|
|
28
|
+
* Records a library's digest in a `build.json` beside it, as `build:native` does, so that
|
|
29
|
+
* {@link NativeLibrary.verify} accepts the file. Only for bytes that were checked before they were
|
|
30
|
+
* written there, such as a library an executable embedded.
|
|
31
|
+
* @param path - The library file.
|
|
32
|
+
* @param digest - Its SHA-256.
|
|
33
|
+
*/
|
|
34
|
+
var recordLocalBuild = (path, digest) => {
|
|
35
|
+
writeFileSync(buildReportOf(path), `${JSON.stringify({ shared: { sha256: digest } }, null, 4)}\n`);
|
|
36
|
+
};
|
|
37
|
+
/** Writes bytes beside the target and renames them over it, so a failure never leaves half a library. */
|
|
38
|
+
var writeWhole = (path, bytes) => {
|
|
39
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
40
|
+
const partial = `${path}.${process.pid}.part`;
|
|
41
|
+
try {
|
|
42
|
+
writeFileSync(partial, bytes);
|
|
43
|
+
renameSync(partial, path);
|
|
44
|
+
} finally {
|
|
45
|
+
rmSync(partial, { force: true });
|
|
46
|
+
}
|
|
47
|
+
};
|
|
48
|
+
/** A URL without the slashes it ends in, trimmed by index: a regular expression would backtrack on a long run of them. */
|
|
49
|
+
var withoutTrailingSlashes = (url) => {
|
|
50
|
+
let end = url.length;
|
|
51
|
+
while (end > 0 && url[end - 1] === "/") end--;
|
|
52
|
+
return url.slice(0, end);
|
|
53
|
+
};
|
|
54
|
+
var readSource = async (base, file, fetchImpl) => {
|
|
55
|
+
if (!/^[a-z]+:\/\//i.test(base)) return readFileSync(join(base, file));
|
|
56
|
+
const url = `${withoutTrailingSlashes(base)}/${encodeURIComponent(file)}`;
|
|
57
|
+
const response = await fetchImpl(url);
|
|
58
|
+
if (!response.ok) throw new NativeLibraryErrors.DownloadFailed({
|
|
59
|
+
url,
|
|
60
|
+
status: response.status
|
|
61
|
+
});
|
|
62
|
+
return new Uint8Array(await response.arrayBuffer());
|
|
63
|
+
};
|
|
64
|
+
/**
|
|
65
|
+
* One package's prebuilt native library: where it is installed, how a release publishes it, and
|
|
66
|
+
* how it is found and checked before a runtime loads it.
|
|
67
|
+
*
|
|
68
|
+
* A release attaches a build for each platform to a GitHub release, and the package's
|
|
69
|
+
* `native/manifest.json` records each file's SHA-256. The package's install script downloads the
|
|
70
|
+
* build for the machine; loading only finds the file and checks its digest, and never downloads.
|
|
71
|
+
*/
|
|
72
|
+
var NativeLibrary = class {
|
|
73
|
+
/** The npm name. */
|
|
74
|
+
packageName;
|
|
75
|
+
/** The library's file name without its extension. */
|
|
76
|
+
library;
|
|
77
|
+
/** The package's root. */
|
|
78
|
+
packageDir;
|
|
79
|
+
/** Names a library file to load in place of the installed build. */
|
|
80
|
+
libraryEnv;
|
|
81
|
+
/** Skips the install's download, for an install that brings its own library. */
|
|
82
|
+
skipDownloadEnv;
|
|
83
|
+
/** Downloads from another release host or a directory, such as a mirror or a test's fixtures. */
|
|
84
|
+
baseUrlEnv;
|
|
85
|
+
manifestJson;
|
|
86
|
+
buildScripts;
|
|
87
|
+
manifest;
|
|
88
|
+
constructor(options) {
|
|
89
|
+
this.packageName = options.packageName;
|
|
90
|
+
this.library = options.library;
|
|
91
|
+
this.packageDir = options.packageDir;
|
|
92
|
+
this.libraryEnv = `${options.envPrefix}_LIBRARY`;
|
|
93
|
+
this.skipDownloadEnv = `${options.envPrefix}_SKIP_DOWNLOAD`;
|
|
94
|
+
this.baseUrlEnv = `${options.envPrefix}_BASE_URL`;
|
|
95
|
+
this.manifestJson = options.manifest;
|
|
96
|
+
this.buildScripts = options.buildScripts;
|
|
97
|
+
}
|
|
98
|
+
/**
|
|
99
|
+
* The manifest the package was built with.
|
|
100
|
+
* @returns The manifest, parsed once.
|
|
101
|
+
*/
|
|
102
|
+
bundledManifest() {
|
|
103
|
+
this.manifest ??= parseManifest(this.manifestJson);
|
|
104
|
+
return this.manifest;
|
|
105
|
+
}
|
|
106
|
+
/**
|
|
107
|
+
* The file name of the shared library on an operating system.
|
|
108
|
+
* @param platform - The operating system, as `process.platform` names it.
|
|
109
|
+
* @returns The file name.
|
|
110
|
+
*/
|
|
111
|
+
sharedLibraryName(platform = process.platform) {
|
|
112
|
+
return sharedLibraryFile(this.library, platform);
|
|
113
|
+
}
|
|
114
|
+
/**
|
|
115
|
+
* The file name of the static archive the scriptc build links.
|
|
116
|
+
* @param platform - The operating system, as `process.platform` names it.
|
|
117
|
+
* @returns The file name.
|
|
118
|
+
*/
|
|
119
|
+
staticLibraryName(platform = process.platform) {
|
|
120
|
+
return staticLibraryFile(this.library, platform);
|
|
121
|
+
}
|
|
122
|
+
/**
|
|
123
|
+
* Where a platform's library goes in the package, whether `build:native` built it or the
|
|
124
|
+
* install script downloaded it.
|
|
125
|
+
* @param packageDir - The package's directory.
|
|
126
|
+
* @param platform - The platform key; this machine's by default.
|
|
127
|
+
* @returns `prebuilds/<platform>/<library>` under it.
|
|
128
|
+
*/
|
|
129
|
+
installedLibraryPath(packageDir, platform = platformKey()) {
|
|
130
|
+
return installedLibraryFile(packageDir, platform, this.library);
|
|
131
|
+
}
|
|
132
|
+
/**
|
|
133
|
+
* The hash of the package's native sources in a checkout, which names a release of builds.
|
|
134
|
+
* @param packageDir - The package's directory, holding `native/`.
|
|
135
|
+
* @returns The first 16 hex digits of the SHA-256 over the build's inputs.
|
|
136
|
+
*/
|
|
137
|
+
sourceHash(packageDir = this.packageDir) {
|
|
138
|
+
return nativeSourceHash(packageDir, this.buildScripts);
|
|
139
|
+
}
|
|
140
|
+
/**
|
|
141
|
+
* What to tell a user whose install did not fetch the library: the package managers that hold
|
|
142
|
+
* install scripts back, how to let this one run, and the way around it.
|
|
143
|
+
* @param platform - The platform key.
|
|
144
|
+
* @returns The advice, as sentences.
|
|
145
|
+
*/
|
|
146
|
+
approvalAdvice(platform) {
|
|
147
|
+
const name = this.packageName;
|
|
148
|
+
return `${name} downloads the build for ${platform} in its install script, which has not run. Under npm, run \`npm install-scripts approve ${name}\`, then \`npm rebuild ${name}\`. Under pnpm, run \`pnpm approve-builds\` or add \`allowBuilds: { '${name}': true }\` to pnpm-workspace.yaml, then reinstall. Under Bun, add "${name}" to "trustedDependencies" in package.json, then reinstall. Or set ${this.libraryEnv} to a build of the library.`;
|
|
149
|
+
}
|
|
150
|
+
/**
|
|
151
|
+
* Checks a library file against the digest the manifest publishes for the platform, or the one
|
|
152
|
+
* a local `build:native` recorded beside it.
|
|
153
|
+
* @param path - The file.
|
|
154
|
+
* @param platform - The platform key.
|
|
155
|
+
* @param manifest - The package's manifest.
|
|
156
|
+
* @throws {NativeLibraryError} When neither digest matches.
|
|
157
|
+
*/
|
|
158
|
+
verify(path, platform, manifest) {
|
|
159
|
+
if (this.verifies(path, platform, manifest)) return;
|
|
160
|
+
const digest = sha256(readFileSync(path));
|
|
161
|
+
const published = manifest.platforms[platform]?.shared.sha256;
|
|
162
|
+
const packageName = this.packageName;
|
|
163
|
+
throw published === void 0 ? new NativeLibraryErrors.NoPublishedBuildToCheck({
|
|
164
|
+
path,
|
|
165
|
+
digest,
|
|
166
|
+
packageName,
|
|
167
|
+
platform
|
|
168
|
+
}) : new NativeLibraryErrors.DigestDoesNotMatchPublishedBuild({
|
|
169
|
+
path,
|
|
170
|
+
digest,
|
|
171
|
+
published,
|
|
172
|
+
packageName,
|
|
173
|
+
platform
|
|
174
|
+
});
|
|
175
|
+
}
|
|
176
|
+
/** Whether {@link verify} accepts a file. */
|
|
177
|
+
verifies(path, platform, manifest) {
|
|
178
|
+
const digest = sha256(readFileSync(path));
|
|
179
|
+
return digest === manifest.platforms[platform]?.shared.sha256 || digest === localBuildDigest(path);
|
|
180
|
+
}
|
|
181
|
+
/**
|
|
182
|
+
* Where the library for this machine is, checked against its published digest: the file the
|
|
183
|
+
* `_LIBRARY` variable names, or the build the install script or `build:native` put in the
|
|
184
|
+
* package. Finding it builds and downloads nothing.
|
|
185
|
+
* @param options - The environment, package, platform and manifest; the defaults are this process's.
|
|
186
|
+
* @returns The file's path.
|
|
187
|
+
* @throws {NativeLibraryError} When there is no file, or it is neither the published build nor a local one.
|
|
188
|
+
*/
|
|
189
|
+
locate(options = {}) {
|
|
190
|
+
const env = options.env ?? process.env;
|
|
191
|
+
const packageDir = options.packageDir ?? this.packageDir;
|
|
192
|
+
const platform = options.platform ?? platformKey();
|
|
193
|
+
const manifest = options.manifest ?? this.bundledManifest();
|
|
194
|
+
const packageName = this.packageName;
|
|
195
|
+
const override = env[this.libraryEnv];
|
|
196
|
+
if (override !== void 0 && override !== "") {
|
|
197
|
+
if (!existsSync(override)) throw new NativeLibraryErrors.LibraryOverrideMissing({
|
|
198
|
+
libraryEnv: this.libraryEnv,
|
|
199
|
+
override
|
|
200
|
+
});
|
|
201
|
+
this.verify(resolve(override), platform, manifest);
|
|
202
|
+
return resolve(override);
|
|
203
|
+
}
|
|
204
|
+
const installed = this.installedLibraryPath(packageDir, platform);
|
|
205
|
+
if (existsSync(installed)) {
|
|
206
|
+
this.verify(installed, platform, manifest);
|
|
207
|
+
return installed;
|
|
208
|
+
}
|
|
209
|
+
const checkout = hasNativeSources(packageDir);
|
|
210
|
+
if (manifest.build !== "" && manifest.platforms[platform] === void 0 && !checkout) throw new NativeLibraryErrors.NoBuildForPlatform({
|
|
211
|
+
packageName,
|
|
212
|
+
platform
|
|
213
|
+
});
|
|
214
|
+
const advice = checkout ? `In a checkout, \`pnpm --filter ${packageName} run build:native\` builds it, or \`pnpm install\` downloads the published one when the native sources match it.` : this.approvalAdvice(platform);
|
|
215
|
+
throw new NativeLibraryErrors.LibraryNotInstalled({
|
|
216
|
+
packageName,
|
|
217
|
+
platform,
|
|
218
|
+
installed,
|
|
219
|
+
advice
|
|
220
|
+
});
|
|
221
|
+
}
|
|
222
|
+
/**
|
|
223
|
+
* Downloads the build for this machine into the package, once, and checks its SHA-256 against
|
|
224
|
+
* the manifest. It is what the package's `postinstall` runs; loading the library never downloads.
|
|
225
|
+
* @param options - The package and, for tests, the platform, environment and network.
|
|
226
|
+
* @returns What it did.
|
|
227
|
+
* @throws {NativeLibraryErrors.DownloadFailed} When the download fails.
|
|
228
|
+
* @throws {NativeLibraryErrors.DownloadDigestMismatch} When its digest or size differ from the manifest's.
|
|
229
|
+
*/
|
|
230
|
+
async install(options) {
|
|
231
|
+
const env = options.env ?? process.env;
|
|
232
|
+
if (env[this.skipDownloadEnv] === "1") return { kind: "skipped" };
|
|
233
|
+
const packageDir = resolve(options.packageDir);
|
|
234
|
+
const manifest = options.manifest ?? this.bundledManifest();
|
|
235
|
+
const platform = options.platform ?? platformKey();
|
|
236
|
+
if (hasNativeSources(packageDir)) {
|
|
237
|
+
const sourceHash = this.sourceHash(packageDir);
|
|
238
|
+
if (sourceHash !== manifest.build) return {
|
|
239
|
+
kind: "local-sources",
|
|
240
|
+
sourceHash
|
|
241
|
+
};
|
|
242
|
+
}
|
|
243
|
+
const entry = manifest.platforms[platform];
|
|
244
|
+
if (entry === void 0) return {
|
|
245
|
+
kind: "no-build",
|
|
246
|
+
platform
|
|
247
|
+
};
|
|
248
|
+
const path = this.installedLibraryPath(packageDir, platform);
|
|
249
|
+
if (existsSync(path) && sha256(readFileSync(path)) === entry.shared.sha256) return {
|
|
250
|
+
kind: "present",
|
|
251
|
+
path
|
|
252
|
+
};
|
|
253
|
+
const bytes = await readSource(env[this.baseUrlEnv] || manifest.baseUrl, entry.shared.file, options.fetch ?? fetch);
|
|
254
|
+
const digest = sha256(bytes);
|
|
255
|
+
if (digest !== entry.shared.sha256 || bytes.byteLength !== entry.shared.bytes) throw new NativeLibraryErrors.DownloadDigestMismatch({
|
|
256
|
+
file: entry.shared.file,
|
|
257
|
+
digest,
|
|
258
|
+
byteLength: bytes.byteLength,
|
|
259
|
+
sha256: entry.shared.sha256,
|
|
260
|
+
bytes: entry.shared.bytes
|
|
261
|
+
});
|
|
262
|
+
writeWhole(path, bytes);
|
|
263
|
+
return {
|
|
264
|
+
kind: "installed",
|
|
265
|
+
path,
|
|
266
|
+
bytes: bytes.byteLength
|
|
267
|
+
};
|
|
268
|
+
}
|
|
269
|
+
/**
|
|
270
|
+
* The bytes of a platform's library, for a packager to embed in an executable: the build in the
|
|
271
|
+
* package if it is the published one or a local `build:native`, else the published build,
|
|
272
|
+
* downloaded and checked.
|
|
273
|
+
* @param platform - The platform key the executable is for.
|
|
274
|
+
* @returns The library, or undefined when there is no build for that platform.
|
|
275
|
+
*/
|
|
276
|
+
async forPlatform(platform) {
|
|
277
|
+
const packageDir = this.packageDir;
|
|
278
|
+
const manifest = this.bundledManifest();
|
|
279
|
+
const path = this.installedLibraryPath(packageDir, platform);
|
|
280
|
+
if (!existsSync(path) || !this.verifies(path, platform, manifest)) await this.install({
|
|
281
|
+
packageDir,
|
|
282
|
+
platform,
|
|
283
|
+
manifest
|
|
284
|
+
});
|
|
285
|
+
if (!existsSync(path)) return void 0;
|
|
286
|
+
this.verify(path, platform, manifest);
|
|
287
|
+
return readFileSync(path);
|
|
288
|
+
}
|
|
289
|
+
/**
|
|
290
|
+
* Writes an embedded library to a cache directory under its digest, and points the `_LIBRARY`
|
|
291
|
+
* variable at it, unless the user already set it. An operating system loads a shared library
|
|
292
|
+
* only from a file, so an executable has to write it once; a copy already there with the right
|
|
293
|
+
* digest is used as it is.
|
|
294
|
+
*
|
|
295
|
+
* The digest is recorded beside the file as a local build's is, because {@link forPlatform}
|
|
296
|
+
* checked the bytes when they were embedded. A library built from native sources the manifest
|
|
297
|
+
* does not publish yet would otherwise be refused by the executable it was embedded in.
|
|
298
|
+
* @param library - The embedded bytes.
|
|
299
|
+
* @param cacheDir - A writable directory.
|
|
300
|
+
* @param env - The environment to set the variable in.
|
|
301
|
+
* @returns The file's path.
|
|
302
|
+
*/
|
|
303
|
+
provideEmbedded(library, cacheDir, env = process.env) {
|
|
304
|
+
const digest = sha256(library);
|
|
305
|
+
const unscoped = this.packageName.slice(this.packageName.lastIndexOf("/") + 1);
|
|
306
|
+
const path = join(cacheDir, unscoped, digest, this.sharedLibraryName());
|
|
307
|
+
if (!existsSync(path) || sha256(readFileSync(path)) !== digest) writeWhole(path, library);
|
|
308
|
+
if (localBuildDigest(path) !== digest) recordLocalBuild(path, digest);
|
|
309
|
+
const current = env[this.libraryEnv];
|
|
310
|
+
if (current === void 0 || current === "") env[this.libraryEnv] = path;
|
|
311
|
+
return path;
|
|
312
|
+
}
|
|
313
|
+
};
|
|
314
|
+
export { NativeLibrary, localBuildDigest, recordLocalBuild };
|
|
315
|
+
|
|
316
|
+
//# sourceMappingURL=NativeLibrary.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"NativeLibrary.js","names":[],"sources":["../src/NativeLibrary.ts"],"sourcesContent":["import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';\nimport { dirname, join, resolve } from 'node:path';\n\nimport { NativeLibraryErrors } from '@jsprismarine/errors/native-library';\n\nimport { isRecord } from './isRecord';\nimport { parseManifest, sha256 } from './manifest';\nimport type { NativeManifest } from './manifest';\nimport { hasNativeSources, nativeSourceHash } from './nativeHash';\nimport { installedLibraryFile, platformKey, sharedLibraryFile, staticLibraryFile } from './platform';\n\n/** What a package that ships a native library tells {@link NativeLibrary} about it. */\nexport interface NativeLibraryOptions {\n /** The npm name, as the messages tell a user to approve or build it. */\n readonly packageName: string;\n /** The library's file name without its extension, such as `libjsp_native_network`. */\n readonly library: string;\n /**\n * The prefix of the package's environment variables, such as `JSP_NATIVE_NETWORK`: `_LIBRARY`\n * names a library to load, `_SKIP_DOWNLOAD` skips the install's download, and `_BASE_URL`\n * downloads from a mirror.\n */\n readonly envPrefix: string;\n /** The package's root, which holds `native/` in a checkout and `prebuilds/` once installed. */\n readonly packageDir: string;\n /**\n * The package's `native/manifest.json`, as imported JSON. It is imported rather than read from\n * disk, so a bundled executable carries it.\n */\n readonly manifest: unknown;\n /** The files outside `native/` the package's build reads, which its source hash covers. */\n readonly buildScripts: readonly string[];\n}\n\n/** How {@link NativeLibrary.locate} looks; tests replace each part. */\nexport interface LocateOptions {\n readonly env?: NodeJS.ProcessEnv;\n readonly packageDir?: string;\n readonly platform?: string;\n readonly manifest?: NativeManifest;\n}\n\n/** What an install did. */\nexport type InstallOutcome =\n | { readonly kind: 'installed'; readonly path: string; readonly bytes: number }\n | { readonly kind: 'present'; readonly path: string }\n | { readonly kind: 'no-build'; readonly platform: string }\n | { readonly kind: 'skipped' }\n | { readonly kind: 'local-sources'; readonly sourceHash: string };\n\n/** How {@link NativeLibrary.install} finds and fetches the build; tests replace the network and the platform. */\nexport interface InstallOptions {\n readonly packageDir: string;\n readonly platform?: string;\n readonly env?: NodeJS.ProcessEnv;\n readonly fetch?: (url: string) => Promise<Response>;\n readonly manifest?: NativeManifest;\n}\n\n/** The report `build:native` writes beside a local build, which records the build's digest. */\nconst buildReportOf = (path: string): string => join(dirname(path), 'build.json');\n\n/**\n * The digest a local build recorded in the `build.json` beside it, which `build:native` writes.\n * @param path - The library file.\n * @returns The digest, or undefined when there is no readable record.\n */\nexport const localBuildDigest = (path: string): string | undefined => {\n const report = buildReportOf(path);\n if (!existsSync(report)) return undefined;\n try {\n const parsed: unknown = JSON.parse(readFileSync(report, 'utf8'));\n const shared = isRecord(parsed) && isRecord(parsed.shared) ? parsed.shared : undefined;\n return typeof shared?.sha256 === 'string' ? shared.sha256 : undefined;\n } catch {\n return undefined;\n }\n};\n\n/**\n * Records a library's digest in a `build.json` beside it, as `build:native` does, so that\n * {@link NativeLibrary.verify} accepts the file. Only for bytes that were checked before they were\n * written there, such as a library an executable embedded.\n * @param path - The library file.\n * @param digest - Its SHA-256.\n */\nexport const recordLocalBuild = (path: string, digest: string): void => {\n writeFileSync(buildReportOf(path), `${JSON.stringify({ shared: { sha256: digest } }, null, 4)}\\n`);\n};\n\n/** Writes bytes beside the target and renames them over it, so a failure never leaves half a library. */\nconst writeWhole = (path: string, bytes: Uint8Array): void => {\n mkdirSync(dirname(path), { recursive: true });\n const partial = `${path}.${process.pid}.part`;\n try {\n writeFileSync(partial, bytes);\n renameSync(partial, path);\n } finally {\n rmSync(partial, { force: true });\n }\n};\n\n/** A URL without the slashes it ends in, trimmed by index: a regular expression would backtrack on a long run of them. */\nconst withoutTrailingSlashes = (url: string): string => {\n let end = url.length;\n while (end > 0 && url[end - 1] === '/') end--;\n return url.slice(0, end);\n};\n\nconst readSource = async (\n base: string,\n file: string,\n fetchImpl: (url: string) => Promise<Response>\n): Promise<Uint8Array> => {\n // A base that is not a URL is a directory, as a test or an offline mirror gives.\n if (!/^[a-z]+:\\/\\//i.test(base)) return readFileSync(join(base, file));\n const url = `${withoutTrailingSlashes(base)}/${encodeURIComponent(file)}`;\n const response = await fetchImpl(url);\n if (!response.ok) throw new NativeLibraryErrors.DownloadFailed({ url, status: response.status });\n return new Uint8Array(await response.arrayBuffer());\n};\n\n/**\n * One package's prebuilt native library: where it is installed, how a release publishes it, and\n * how it is found and checked before a runtime loads it.\n *\n * A release attaches a build for each platform to a GitHub release, and the package's\n * `native/manifest.json` records each file's SHA-256. The package's install script downloads the\n * build for the machine; loading only finds the file and checks its digest, and never downloads.\n */\nexport class NativeLibrary {\n /** The npm name. */\n public readonly packageName: string;\n /** The library's file name without its extension. */\n public readonly library: string;\n /** The package's root. */\n public readonly packageDir: string;\n /** Names a library file to load in place of the installed build. */\n public readonly libraryEnv: string;\n /** Skips the install's download, for an install that brings its own library. */\n public readonly skipDownloadEnv: string;\n /** Downloads from another release host or a directory, such as a mirror or a test's fixtures. */\n public readonly baseUrlEnv: string;\n\n private readonly manifestJson: unknown;\n private readonly buildScripts: readonly string[];\n private manifest: NativeManifest | undefined;\n\n public constructor(options: NativeLibraryOptions) {\n this.packageName = options.packageName;\n this.library = options.library;\n this.packageDir = options.packageDir;\n this.libraryEnv = `${options.envPrefix}_LIBRARY`;\n this.skipDownloadEnv = `${options.envPrefix}_SKIP_DOWNLOAD`;\n this.baseUrlEnv = `${options.envPrefix}_BASE_URL`;\n this.manifestJson = options.manifest;\n this.buildScripts = options.buildScripts;\n }\n\n /**\n * The manifest the package was built with.\n * @returns The manifest, parsed once.\n */\n public bundledManifest(): NativeManifest {\n this.manifest ??= parseManifest(this.manifestJson);\n return this.manifest;\n }\n\n /**\n * The file name of the shared library on an operating system.\n * @param platform - The operating system, as `process.platform` names it.\n * @returns The file name.\n */\n public sharedLibraryName(platform: NodeJS.Platform = process.platform): string {\n return sharedLibraryFile(this.library, platform);\n }\n\n /**\n * The file name of the static archive the scriptc build links.\n * @param platform - The operating system, as `process.platform` names it.\n * @returns The file name.\n */\n public staticLibraryName(platform: NodeJS.Platform = process.platform): string {\n return staticLibraryFile(this.library, platform);\n }\n\n /**\n * Where a platform's library goes in the package, whether `build:native` built it or the\n * install script downloaded it.\n * @param packageDir - The package's directory.\n * @param platform - The platform key; this machine's by default.\n * @returns `prebuilds/<platform>/<library>` under it.\n */\n public installedLibraryPath(packageDir: string, platform: string = platformKey()): string {\n return installedLibraryFile(packageDir, platform, this.library);\n }\n\n /**\n * The hash of the package's native sources in a checkout, which names a release of builds.\n * @param packageDir - The package's directory, holding `native/`.\n * @returns The first 16 hex digits of the SHA-256 over the build's inputs.\n */\n public sourceHash(packageDir: string = this.packageDir): string {\n return nativeSourceHash(packageDir, this.buildScripts);\n }\n\n /**\n * What to tell a user whose install did not fetch the library: the package managers that hold\n * install scripts back, how to let this one run, and the way around it.\n * @param platform - The platform key.\n * @returns The advice, as sentences.\n */\n public approvalAdvice(platform: string): string {\n const name = this.packageName;\n return (\n `${name} downloads the build for ${platform} in its install script, which has not run. ` +\n `Under npm, run \\`npm install-scripts approve ${name}\\`, then \\`npm rebuild ${name}\\`. ` +\n `Under pnpm, run \\`pnpm approve-builds\\` or add \\`allowBuilds: { '${name}': true }\\` to pnpm-workspace.yaml, then reinstall. ` +\n `Under Bun, add \"${name}\" to \"trustedDependencies\" in package.json, then reinstall. ` +\n `Or set ${this.libraryEnv} to a build of the library.`\n );\n }\n\n /**\n * Checks a library file against the digest the manifest publishes for the platform, or the one\n * a local `build:native` recorded beside it.\n * @param path - The file.\n * @param platform - The platform key.\n * @param manifest - The package's manifest.\n * @throws {NativeLibraryError} When neither digest matches.\n */\n public verify(path: string, platform: string, manifest: NativeManifest): void {\n if (this.verifies(path, platform, manifest)) return;\n const digest = sha256(readFileSync(path));\n const published = manifest.platforms[platform]?.shared.sha256;\n const packageName = this.packageName;\n throw published === undefined\n ? new NativeLibraryErrors.NoPublishedBuildToCheck({ path, digest, packageName, platform })\n : new NativeLibraryErrors.DigestDoesNotMatchPublishedBuild({\n path,\n digest,\n published,\n packageName,\n platform\n });\n }\n\n /** Whether {@link verify} accepts a file. */\n private verifies(path: string, platform: string, manifest: NativeManifest): boolean {\n const digest = sha256(readFileSync(path));\n return digest === manifest.platforms[platform]?.shared.sha256 || digest === localBuildDigest(path);\n }\n\n /**\n * Where the library for this machine is, checked against its published digest: the file the\n * `_LIBRARY` variable names, or the build the install script or `build:native` put in the\n * package. Finding it builds and downloads nothing.\n * @param options - The environment, package, platform and manifest; the defaults are this process's.\n * @returns The file's path.\n * @throws {NativeLibraryError} When there is no file, or it is neither the published build nor a local one.\n */\n public locate(options: LocateOptions = {}): string {\n const env = options.env ?? process.env;\n const packageDir = options.packageDir ?? this.packageDir;\n const platform = options.platform ?? platformKey();\n const manifest = options.manifest ?? this.bundledManifest();\n const packageName = this.packageName;\n\n const override = env[this.libraryEnv];\n if (override !== undefined && override !== '') {\n if (!existsSync(override)) {\n throw new NativeLibraryErrors.LibraryOverrideMissing({ libraryEnv: this.libraryEnv, override });\n }\n this.verify(resolve(override), platform, manifest);\n return resolve(override);\n }\n\n const installed = this.installedLibraryPath(packageDir, platform);\n if (existsSync(installed)) {\n this.verify(installed, platform, manifest);\n return installed;\n }\n // A checkout builds its own on any platform, so it gets the build advice below.\n const checkout = hasNativeSources(packageDir);\n if (manifest.build !== '' && manifest.platforms[platform] === undefined && !checkout) {\n throw new NativeLibraryErrors.NoBuildForPlatform({ packageName, platform });\n }\n const advice = checkout\n ? `In a checkout, \\`pnpm --filter ${packageName} run build:native\\` builds it, or \\`pnpm install\\` downloads the published one when the native sources match it.`\n : this.approvalAdvice(platform);\n throw new NativeLibraryErrors.LibraryNotInstalled({ packageName, platform, installed, advice });\n }\n\n /**\n * Downloads the build for this machine into the package, once, and checks its SHA-256 against\n * the manifest. It is what the package's `postinstall` runs; loading the library never downloads.\n * @param options - The package and, for tests, the platform, environment and network.\n * @returns What it did.\n * @throws {NativeLibraryErrors.DownloadFailed} When the download fails.\n * @throws {NativeLibraryErrors.DownloadDigestMismatch} When its digest or size differ from the manifest's.\n */\n public async install(options: InstallOptions): Promise<InstallOutcome> {\n const env = options.env ?? process.env;\n if (env[this.skipDownloadEnv] === '1') return { kind: 'skipped' };\n const packageDir = resolve(options.packageDir);\n const manifest = options.manifest ?? this.bundledManifest();\n const platform = options.platform ?? platformKey();\n\n // A checkout whose native sources changed since the published builds builds its own.\n if (hasNativeSources(packageDir)) {\n const sourceHash = this.sourceHash(packageDir);\n if (sourceHash !== manifest.build) return { kind: 'local-sources', sourceHash };\n }\n\n const entry = manifest.platforms[platform];\n if (entry === undefined) return { kind: 'no-build', platform };\n\n const path = this.installedLibraryPath(packageDir, platform);\n if (existsSync(path) && sha256(readFileSync(path)) === entry.shared.sha256) return { kind: 'present', path };\n\n const bytes = await readSource(\n env[this.baseUrlEnv] || manifest.baseUrl,\n entry.shared.file,\n options.fetch ?? fetch\n );\n const digest = sha256(bytes);\n if (digest !== entry.shared.sha256 || bytes.byteLength !== entry.shared.bytes) {\n throw new NativeLibraryErrors.DownloadDigestMismatch({\n file: entry.shared.file,\n digest,\n byteLength: bytes.byteLength,\n sha256: entry.shared.sha256,\n bytes: entry.shared.bytes\n });\n }\n writeWhole(path, bytes);\n return { kind: 'installed', path, bytes: bytes.byteLength };\n }\n\n /**\n * The bytes of a platform's library, for a packager to embed in an executable: the build in the\n * package if it is the published one or a local `build:native`, else the published build,\n * downloaded and checked.\n * @param platform - The platform key the executable is for.\n * @returns The library, or undefined when there is no build for that platform.\n */\n public async forPlatform(platform: string): Promise<Uint8Array | undefined> {\n const packageDir = this.packageDir;\n const manifest = this.bundledManifest();\n const path = this.installedLibraryPath(packageDir, platform);\n // A file that is neither the published build nor a recorded local one, such as one left by\n // an older version, is replaced by the published build when there is one.\n if (!existsSync(path) || !this.verifies(path, platform, manifest)) {\n await this.install({ packageDir, platform, manifest });\n }\n if (!existsSync(path)) return undefined;\n this.verify(path, platform, manifest);\n return readFileSync(path);\n }\n\n /**\n * Writes an embedded library to a cache directory under its digest, and points the `_LIBRARY`\n * variable at it, unless the user already set it. An operating system loads a shared library\n * only from a file, so an executable has to write it once; a copy already there with the right\n * digest is used as it is.\n *\n * The digest is recorded beside the file as a local build's is, because {@link forPlatform}\n * checked the bytes when they were embedded. A library built from native sources the manifest\n * does not publish yet would otherwise be refused by the executable it was embedded in.\n * @param library - The embedded bytes.\n * @param cacheDir - A writable directory.\n * @param env - The environment to set the variable in.\n * @returns The file's path.\n */\n public provideEmbedded(library: Uint8Array, cacheDir: string, env: NodeJS.ProcessEnv = process.env): string {\n const digest = sha256(library);\n const unscoped = this.packageName.slice(this.packageName.lastIndexOf('/') + 1);\n const path = join(cacheDir, unscoped, digest, this.sharedLibraryName());\n if (!existsSync(path) || sha256(readFileSync(path)) !== digest) writeWhole(path, library);\n if (localBuildDigest(path) !== digest) recordLocalBuild(path, digest);\n const current = env[this.libraryEnv];\n if (current === undefined || current === '') env[this.libraryEnv] = path;\n return path;\n }\n}\n"],"mappings":";;;;;;;;;AA4DA,IAAM,iBAAiB,SAAyB,KAAK,QAAQ,IAAI,GAAG,YAAY;;;;;;AAOhF,IAAa,oBAAoB,SAAqC;CAClE,MAAM,SAAS,cAAc,IAAI;CACjC,IAAI,CAAC,WAAW,MAAM,GAAG,OAAO,KAAA;CAChC,IAAI;EACA,MAAM,SAAkB,KAAK,MAAM,aAAa,QAAQ,MAAM,CAAC;EAC/D,MAAM,SAAS,SAAS,MAAM,KAAK,SAAS,OAAO,MAAM,IAAI,OAAO,SAAS,KAAA;EAC7E,OAAO,OAAO,QAAQ,WAAW,WAAW,OAAO,SAAS,KAAA;CAChE,QAAQ;EACJ;CACJ;AACJ;;;;;;;;AASA,IAAa,oBAAoB,MAAc,WAAyB;CACpE,cAAc,cAAc,IAAI,GAAG,GAAG,KAAK,UAAU,EAAE,QAAQ,EAAE,QAAQ,OAAO,EAAE,GAAG,MAAM,CAAC,EAAE,GAAG;AACrG;;AAGA,IAAM,cAAc,MAAc,UAA4B;CAC1D,UAAU,QAAQ,IAAI,GAAG,EAAE,WAAW,KAAK,CAAC;CAC5C,MAAM,UAAU,GAAG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AM;EACpE,MAAM,UAAU,IAAI,KAAK;EACzB,IAAI,YAAY,KAAA,KAAa,YAAY,IAAI,IAAI,KAAK,cAAc;EACpE,OAAO;CACX;AACJ"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"isRecord.d.ts","sources":["../src/isRecord.ts"],"names":[],"mappings":"AAAA,4GAA4G;AAC5G,eAAO,MAAM,QAAQ,UAAW,OAAO,KAAG,KAAK,IAAI,MAAM,CAAC,MAAM,EAAE,OAAO,CACD,CAAC"}
|
package/dist/isRecord.js
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
// src/isRecord.ts
|
|
2
|
+
/** Whether a value is a non-null object, which is what parsed JSON has to be before its fields are read. */
|
|
3
|
+
var isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
4
|
+
export { isRecord };
|
|
5
|
+
|
|
6
|
+
//# sourceMappingURL=isRecord.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"isRecord.js","names":[],"sources":["../src/isRecord.ts"],"sourcesContent":["/** Whether a value is a non-null object, which is what parsed JSON has to be before its fields are read. */\nexport const isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === 'object' && value !== null && !Array.isArray(value);\n"],"mappings":";;AACA,IAAa,YAAY,UACrB,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK"}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
/** One published file: its name in the release, its size and its SHA-256. */
|
|
2
|
+
export interface ManifestFile {
|
|
3
|
+
readonly file: string;
|
|
4
|
+
readonly bytes: number;
|
|
5
|
+
readonly sha256: string;
|
|
6
|
+
}
|
|
7
|
+
/** One platform's builds: the shared library the runtimes load, and the scriptc archive when there is one. */
|
|
8
|
+
export interface ManifestPlatform {
|
|
9
|
+
readonly shared: ManifestFile;
|
|
10
|
+
readonly static?: ManifestFile;
|
|
11
|
+
}
|
|
12
|
+
/** The builds a version of a package downloads, from its `native/manifest.json`. */
|
|
13
|
+
export interface NativeManifest {
|
|
14
|
+
/** The native sources' hash the builds were made from; empty before the first publish. */
|
|
15
|
+
readonly build: string;
|
|
16
|
+
/** Where the files are: a release's download URL, joined with each file's name. */
|
|
17
|
+
readonly baseUrl: string;
|
|
18
|
+
readonly platforms: Readonly<Record<string, ManifestPlatform>>;
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* Checks parsed JSON against the manifest's shape.
|
|
22
|
+
* @param value - The parsed file.
|
|
23
|
+
* @returns The manifest.
|
|
24
|
+
* @throws {NativeLibraryErrors.InvalidNativeManifest} When `build` or `baseUrl` is missing.
|
|
25
|
+
* @throws {NativeLibraryErrors.InvalidNativeManifestEntry} When a platform's entry is malformed.
|
|
26
|
+
*/
|
|
27
|
+
export declare const parseManifest: (value: unknown) => NativeManifest;
|
|
28
|
+
/**
|
|
29
|
+
* Reads a package's manifest from disk, as a script that rewrote it does.
|
|
30
|
+
* @param packageDir - The package's directory.
|
|
31
|
+
* @returns The manifest.
|
|
32
|
+
*/
|
|
33
|
+
export declare const readManifest: (packageDir: string) => NativeManifest;
|
|
34
|
+
/**
|
|
35
|
+
* The SHA-256 of bytes, as lowercase hex.
|
|
36
|
+
* @param bytes - The bytes.
|
|
37
|
+
* @returns The digest.
|
|
38
|
+
*/
|
|
39
|
+
export declare const sha256: (bytes: Uint8Array) => string;
|
|
40
|
+
//# sourceMappingURL=manifest.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"manifest.d.ts","sources":["../src/manifest.ts"],"names":[],"mappings":"AAQA,6EAA6E;AAC7E,MAAM,WAAW,YAAY;IACzB,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;IACvB,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;CAC3B;AAED,8GAA8G;AAC9G,MAAM,WAAW,gBAAgB;IAC7B,QAAQ,CAAC,MAAM,EAAE,YAAY,CAAC;IAC9B,QAAQ,CAAC,MAAM,CAAC,EAAE,YAAY,CAAC;CAClC;AAED,oFAAoF;AACpF,MAAM,WAAW,cAAc;IAC3B,0FAA0F;IAC1F,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;IACvB,mFAAmF;IACnF,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IACzB,QAAQ,CAAC,SAAS,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,gBAAgB,CAAC,CAAC,CAAC;CAClE;AASD;;;;;;GAMG;AACH,eAAO,MAAM,aAAa,UAAW,OAAO,KAAG,cAiB9C,CAAC;AAEF;;;;GAIG;AACH,eAAO,MAAM,YAAY,eAAgB,MAAM,KAAG,cAC8C,CAAC;AAEjG;;;;GAIG;AACH,eAAO,MAAM,MAAM,UAAW,UAAU,KAAG,MAA0D,CAAC"}
|
package/dist/manifest.js
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { isRecord } from "./isRecord.js";
|
|
2
|
+
import { readFileSync } from "node:fs";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import { createHash } from "node:crypto";
|
|
5
|
+
import { NativeLibraryErrors } from "@jsprismarine/errors/native-library";
|
|
6
|
+
// src/manifest.ts
|
|
7
|
+
var isFile = (value) => isRecord(value) && typeof value.file === "string" && typeof value.bytes === "number" && typeof value.sha256 === "string" && /^[0-9a-f]{64}$/.test(value.sha256);
|
|
8
|
+
/**
|
|
9
|
+
* Checks parsed JSON against the manifest's shape.
|
|
10
|
+
* @param value - The parsed file.
|
|
11
|
+
* @returns The manifest.
|
|
12
|
+
* @throws {NativeLibraryErrors.InvalidNativeManifest} When `build` or `baseUrl` is missing.
|
|
13
|
+
* @throws {NativeLibraryErrors.InvalidNativeManifestEntry} When a platform's entry is malformed.
|
|
14
|
+
*/
|
|
15
|
+
var parseManifest = (value) => {
|
|
16
|
+
if (!isRecord(value) || typeof value.build !== "string" || typeof value.baseUrl !== "string") throw new NativeLibraryErrors.InvalidNativeManifest();
|
|
17
|
+
const platforms = isRecord(value.platforms) ? value.platforms : {};
|
|
18
|
+
const checked = {};
|
|
19
|
+
for (const [key, platform] of Object.entries(platforms)) {
|
|
20
|
+
if (!isRecord(platform) || !isFile(platform.shared) || platform.static !== void 0 && !isFile(platform.static)) throw new NativeLibraryErrors.InvalidNativeManifestEntry({ key });
|
|
21
|
+
checked[key] = {
|
|
22
|
+
shared: platform.shared,
|
|
23
|
+
...isFile(platform.static) ? { static: platform.static } : {}
|
|
24
|
+
};
|
|
25
|
+
}
|
|
26
|
+
return {
|
|
27
|
+
build: value.build,
|
|
28
|
+
baseUrl: value.baseUrl,
|
|
29
|
+
platforms: checked
|
|
30
|
+
};
|
|
31
|
+
};
|
|
32
|
+
/**
|
|
33
|
+
* Reads a package's manifest from disk, as a script that rewrote it does.
|
|
34
|
+
* @param packageDir - The package's directory.
|
|
35
|
+
* @returns The manifest.
|
|
36
|
+
*/
|
|
37
|
+
var readManifest = (packageDir) => parseManifest(JSON.parse(readFileSync(join(packageDir, "native", "manifest.json"), "utf8")));
|
|
38
|
+
/**
|
|
39
|
+
* The SHA-256 of bytes, as lowercase hex.
|
|
40
|
+
* @param bytes - The bytes.
|
|
41
|
+
* @returns The digest.
|
|
42
|
+
*/
|
|
43
|
+
var sha256 = (bytes) => createHash("sha256").update(bytes).digest("hex");
|
|
44
|
+
export { parseManifest, readManifest, sha256 };
|
|
45
|
+
|
|
46
|
+
//# sourceMappingURL=manifest.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"manifest.js","names":[],"sources":["../src/manifest.ts"],"sourcesContent":["import { createHash } from 'node:crypto';\nimport { readFileSync } from 'node:fs';\nimport { join } from 'node:path';\n\nimport { NativeLibraryErrors } from '@jsprismarine/errors/native-library';\n\nimport { isRecord } from './isRecord';\n\n/** One published file: its name in the release, its size and its SHA-256. */\nexport interface ManifestFile {\n readonly file: string;\n readonly bytes: number;\n readonly sha256: string;\n}\n\n/** One platform's builds: the shared library the runtimes load, and the scriptc archive when there is one. */\nexport interface ManifestPlatform {\n readonly shared: ManifestFile;\n readonly static?: ManifestFile;\n}\n\n/** The builds a version of a package downloads, from its `native/manifest.json`. */\nexport interface NativeManifest {\n /** The native sources' hash the builds were made from; empty before the first publish. */\n readonly build: string;\n /** Where the files are: a release's download URL, joined with each file's name. */\n readonly baseUrl: string;\n readonly platforms: Readonly<Record<string, ManifestPlatform>>;\n}\n\nconst isFile = (value: unknown): value is ManifestFile =>\n isRecord(value) &&\n typeof value.file === 'string' &&\n typeof value.bytes === 'number' &&\n typeof value.sha256 === 'string' &&\n /^[0-9a-f]{64}$/.test(value.sha256);\n\n/**\n * Checks parsed JSON against the manifest's shape.\n * @param value - The parsed file.\n * @returns The manifest.\n * @throws {NativeLibraryErrors.InvalidNativeManifest} When `build` or `baseUrl` is missing.\n * @throws {NativeLibraryErrors.InvalidNativeManifestEntry} When a platform's entry is malformed.\n */\nexport const parseManifest = (value: unknown): NativeManifest => {\n if (!isRecord(value) || typeof value.build !== 'string' || typeof value.baseUrl !== 'string') {\n throw new NativeLibraryErrors.InvalidNativeManifest();\n }\n const platforms = isRecord(value.platforms) ? value.platforms : {};\n const checked: Record<string, ManifestPlatform> = {};\n for (const [key, platform] of Object.entries(platforms)) {\n if (\n !isRecord(platform) ||\n !isFile(platform.shared) ||\n (platform.static !== undefined && !isFile(platform.static))\n ) {\n throw new NativeLibraryErrors.InvalidNativeManifestEntry({ key });\n }\n checked[key] = { shared: platform.shared, ...(isFile(platform.static) ? { static: platform.static } : {}) };\n }\n return { build: value.build, baseUrl: value.baseUrl, platforms: checked };\n};\n\n/**\n * Reads a package's manifest from disk, as a script that rewrote it does.\n * @param packageDir - The package's directory.\n * @returns The manifest.\n */\nexport const readManifest = (packageDir: string): NativeManifest =>\n parseManifest(JSON.parse(readFileSync(join(packageDir, 'native', 'manifest.json'), 'utf8')));\n\n/**\n * The SHA-256 of bytes, as lowercase hex.\n * @param bytes - The bytes.\n * @returns The digest.\n */\nexport const sha256 = (bytes: Uint8Array): string => createHash('sha256').update(bytes).digest('hex');\n"],"mappings":";;;;;;AA8BA,IAAM,UAAU,UACZ,SAAS,KAAK,KACd,OAAO,MAAM,SAAS,YACtB,OAAO,MAAM,UAAU,YACvB,OAAO,MAAM,WAAW,YACxB,iBAAiB,KAAK,MAAM,MAAM;;;;;;;;AAStC,IAAa,iBAAiB,UAAmC;CAC7D,IAAI,CAAC,SAAS,KAAK,KAAK,OAAO,MAAM,UAAU,YAAY,OAAO,MAAM,YAAY,UAChF,MAAM,IAAI,oBAAoB,sBAAsB;CAExD,MAAM,YAAY,SAAS,MAAM,SAAS,IAAI,MAAM,YAAY,CAAC;CACjE,MAAM,UAA4C,CAAC;CACnD,KAAK,MAAM,CAAC,KAAK,aAAa,OAAO,QAAQ,SAAS,GAAG;EACrD,IACI,CAAC,SAAS,QAAQ,KAClB,CAAC,OAAO,SAAS,MAAM,KACtB,SAAS,WAAW,KAAA,KAAa,CAAC,OAAO,SAAS,MAAM,GAEzD,MAAM,IAAI,oBAAoB,2BAA2B,EAAE,IAAI,CAAC;EAEpE,QAAQ,OAAO;GAAE,QAAQ,SAAS;GAAQ,GAAI,OAAO,SAAS,MAAM,IAAI,EAAE,QAAQ,SAAS,OAAO,IAAI,CAAC;EAAG;CAC9G;CACA,OAAO;EAAE,OAAO,MAAM;EAAO,SAAS,MAAM;EAAS,WAAW;CAAQ;AAC5E;;;;;;AAOA,IAAa,gBAAgB,eACzB,cAAc,KAAK,MAAM,aAAa,KAAK,YAAY,UAAU,eAAe,GAAG,MAAM,CAAC,CAAC;;;;;;AAO/F,IAAa,UAAU,UAA8B,WAAW,QAAQ,CAAC,CAAC,OAAO,KAAK,CAAC,CAAC,OAAO,KAAK"}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Whether a package directory holds the native sources, which a checkout does and a published
|
|
3
|
+
* package does not.
|
|
4
|
+
* @param packageDir - The package's directory.
|
|
5
|
+
* @returns True in a checkout.
|
|
6
|
+
*/
|
|
7
|
+
export declare const hasNativeSources: (packageDir: string) => boolean;
|
|
8
|
+
/**
|
|
9
|
+
* The hash that names a build of a native library. A release of builds is tagged with it, and the
|
|
10
|
+
* manifest records the hash its builds were made from, so a checkout can tell whether its native
|
|
11
|
+
* sources still match the published builds.
|
|
12
|
+
* @param packageDir - The package's directory, holding `native/`.
|
|
13
|
+
* @param buildScripts - The files outside `native/` the build reads, relative to the package,
|
|
14
|
+
* such as its build script.
|
|
15
|
+
* @returns The first 16 hex digits of the SHA-256 over the build's inputs.
|
|
16
|
+
*/
|
|
17
|
+
export declare const nativeSourceHash: (packageDir: string, buildScripts: readonly string[]) => string;
|
|
18
|
+
//# sourceMappingURL=nativeHash.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"nativeHash.d.ts","sources":["../src/nativeHash.ts"],"names":[],"mappings":"AAsBA;;;;;GAKG;AACH,eAAO,MAAM,gBAAgB,eAAgB,MAAM,KAAG,OAAiE,CAAC;AAExH;;;;;;;;GAQG;AACH,eAAO,MAAM,gBAAgB,eAAgB,MAAM,gBAAgB,SAAS,MAAM,EAAE,KAAG,MAQtF,CAAC"}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import { existsSync, readFileSync, readdirSync } from "node:fs";
|
|
2
|
+
import { join, relative, sep } from "node:path";
|
|
3
|
+
import { createHash } from "node:crypto";
|
|
4
|
+
// src/nativeHash.ts
|
|
5
|
+
/**
|
|
6
|
+
* Every file the native build reads, relative to the package, sorted: `native/` but its manifest,
|
|
7
|
+
* and the files outside it the package names.
|
|
8
|
+
*/
|
|
9
|
+
var buildInputs = (packageDir, buildScripts) => {
|
|
10
|
+
const files = [];
|
|
11
|
+
const walk = (dir) => {
|
|
12
|
+
for (const entry of readdirSync(dir, { withFileTypes: true })) {
|
|
13
|
+
const path = join(dir, entry.name);
|
|
14
|
+
if (entry.isDirectory()) walk(path);
|
|
15
|
+
else if (entry.name !== "manifest.json") files.push(relative(packageDir, path).split(sep).join("/"));
|
|
16
|
+
}
|
|
17
|
+
};
|
|
18
|
+
walk(join(packageDir, "native"));
|
|
19
|
+
files.push(...buildScripts);
|
|
20
|
+
return files.sort();
|
|
21
|
+
};
|
|
22
|
+
/**
|
|
23
|
+
* Whether a package directory holds the native sources, which a checkout does and a published
|
|
24
|
+
* package does not.
|
|
25
|
+
* @param packageDir - The package's directory.
|
|
26
|
+
* @returns True in a checkout.
|
|
27
|
+
*/
|
|
28
|
+
var hasNativeSources = (packageDir) => existsSync(join(packageDir, "native", "sources.json"));
|
|
29
|
+
/**
|
|
30
|
+
* The hash that names a build of a native library. A release of builds is tagged with it, and the
|
|
31
|
+
* manifest records the hash its builds were made from, so a checkout can tell whether its native
|
|
32
|
+
* sources still match the published builds.
|
|
33
|
+
* @param packageDir - The package's directory, holding `native/`.
|
|
34
|
+
* @param buildScripts - The files outside `native/` the build reads, relative to the package,
|
|
35
|
+
* such as its build script.
|
|
36
|
+
* @returns The first 16 hex digits of the SHA-256 over the build's inputs.
|
|
37
|
+
*/
|
|
38
|
+
var nativeSourceHash = (packageDir, buildScripts) => {
|
|
39
|
+
const hash = createHash("sha256");
|
|
40
|
+
for (const file of buildInputs(packageDir, buildScripts)) {
|
|
41
|
+
const text = readFileSync(join(packageDir, file), "utf8").replace(/\r\n/g, "\n");
|
|
42
|
+
hash.update(file).update("\0").update(text).update("\0");
|
|
43
|
+
}
|
|
44
|
+
return hash.digest("hex").slice(0, 16);
|
|
45
|
+
};
|
|
46
|
+
export { hasNativeSources, nativeSourceHash };
|
|
47
|
+
|
|
48
|
+
//# sourceMappingURL=nativeHash.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"nativeHash.js","names":[],"sources":["../src/nativeHash.ts"],"sourcesContent":["import { createHash } from 'node:crypto';\nimport { existsSync, readdirSync, readFileSync } from 'node:fs';\nimport { join, relative, sep } from 'node:path';\n\n/**\n * Every file the native build reads, relative to the package, sorted: `native/` but its manifest,\n * and the files outside it the package names.\n */\nconst buildInputs = (packageDir: string, buildScripts: readonly string[]): string[] => {\n const files: string[] = [];\n const walk = (dir: string): void => {\n for (const entry of readdirSync(dir, { withFileTypes: true })) {\n const path = join(dir, entry.name);\n if (entry.isDirectory()) walk(path);\n else if (entry.name !== 'manifest.json') files.push(relative(packageDir, path).split(sep).join('/'));\n }\n };\n walk(join(packageDir, 'native'));\n files.push(...buildScripts);\n return files.sort();\n};\n\n/**\n * Whether a package directory holds the native sources, which a checkout does and a published\n * package does not.\n * @param packageDir - The package's directory.\n * @returns True in a checkout.\n */\nexport const hasNativeSources = (packageDir: string): boolean => existsSync(join(packageDir, 'native', 'sources.json'));\n\n/**\n * The hash that names a build of a native library. A release of builds is tagged with it, and the\n * manifest records the hash its builds were made from, so a checkout can tell whether its native\n * sources still match the published builds.\n * @param packageDir - The package's directory, holding `native/`.\n * @param buildScripts - The files outside `native/` the build reads, relative to the package,\n * such as its build script.\n * @returns The first 16 hex digits of the SHA-256 over the build's inputs.\n */\nexport const nativeSourceHash = (packageDir: string, buildScripts: readonly string[]): string => {\n const hash = createHash('sha256');\n for (const file of buildInputs(packageDir, buildScripts)) {\n // Line endings are normalized, so a Windows checkout hashes the same.\n const text = readFileSync(join(packageDir, file), 'utf8').replace(/\\r\\n/g, '\\n');\n hash.update(file).update('\\0').update(text).update('\\0');\n }\n return hash.digest('hex').slice(0, 16);\n};\n"],"mappings":";;;;;;;;AAQA,IAAM,eAAe,YAAoB,iBAA8C;CACnF,MAAM,QAAkB,CAAC;CACzB,MAAM,QAAQ,QAAsB;EAChC,KAAK,MAAM,SAAS,YAAY,KAAK,EAAE,eAAe,KAAK,CAAC,GAAG;GAC3D,MAAM,OAAO,KAAK,KAAK,MAAM,IAAI;GACjC,IAAI,MAAM,YAAY,GAAG,KAAK,IAAI;QAC7B,IAAI,MAAM,SAAS,iBAAiB,MAAM,KAAK,SAAS,YAAY,IAAI,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC,KAAK,GAAG,CAAC;EACvG;CACJ;CACA,KAAK,KAAK,YAAY,QAAQ,CAAC;CAC/B,MAAM,KAAK,GAAG,YAAY;CAC1B,OAAO,MAAM,KAAK;AACtB;;;;;;;AAQA,IAAa,oBAAoB,eAAgC,WAAW,KAAK,YAAY,UAAU,cAAc,CAAC;;;;;;;;;;AAWtH,IAAa,oBAAoB,YAAoB,iBAA4C;CAC7F,MAAM,OAAO,WAAW,QAAQ;CAChC,KAAK,MAAM,QAAQ,YAAY,YAAY,YAAY,GAAG;EAEtD,MAAM,OAAO,aAAa,KAAK,YAAY,IAAI,GAAG,MAAM,CAAC,CAAC,QAAQ,SAAS,IAAI;EAC/E,KAAK,OAAO,IAAI,CAAC,CAAC,OAAO,IAAI,CAAC,CAAC,OAAO,IAAI,CAAC,CAAC,OAAO,IAAI;CAC3D;CACA,OAAO,KAAK,OAAO,KAAK,CAAC,CAAC,MAAM,GAAG,EAAE;AACzC"}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
/** The C library a Linux build is linked against. */
|
|
2
|
+
export type LinuxLibc = 'gnu' | 'musl';
|
|
3
|
+
/**
|
|
4
|
+
* Which C library this Linux process runs on. Node.js reports glibc's version in its process
|
|
5
|
+
* report and leaves it out under musl; Bun has no report, so the loader's name decides there.
|
|
6
|
+
* @returns `gnu` or `musl`.
|
|
7
|
+
*/
|
|
8
|
+
export declare const linuxLibc: () => LinuxLibc;
|
|
9
|
+
/**
|
|
10
|
+
* The key a build of a native library is published under, such as `linux-x64-gnu`.
|
|
11
|
+
* @param platform - The operating system, as `process.platform` names it.
|
|
12
|
+
* @param arch - The processor, as `process.arch` names it.
|
|
13
|
+
* @param libc - The C library, for Linux; ignored elsewhere.
|
|
14
|
+
* @returns The key.
|
|
15
|
+
*/
|
|
16
|
+
export declare const platformKey: (platform?: NodeJS.Platform, arch?: string, libc?: LinuxLibc) => string;
|
|
17
|
+
/**
|
|
18
|
+
* The operating system a platform key is for.
|
|
19
|
+
* @param key - A key from {@link platformKey}, such as `linux-x64-gnu`.
|
|
20
|
+
* @returns The operating system, as `process.platform` names it.
|
|
21
|
+
*/
|
|
22
|
+
export declare const operatingSystemOf: (key: string) => NodeJS.Platform;
|
|
23
|
+
/**
|
|
24
|
+
* The file name of a shared library on an operating system.
|
|
25
|
+
* @param library - The library's name without its extension, such as `libjsp_native_network`.
|
|
26
|
+
* @param platform - The operating system, as `process.platform` names it.
|
|
27
|
+
* @returns The file name.
|
|
28
|
+
*/
|
|
29
|
+
export declare const sharedLibraryFile: (library: string, platform?: NodeJS.Platform) => string;
|
|
30
|
+
/**
|
|
31
|
+
* The file name of the static archive a scriptc build links.
|
|
32
|
+
* @param library - The library's name without its extension.
|
|
33
|
+
* @param platform - The operating system, as `process.platform` names it.
|
|
34
|
+
* @returns The file name.
|
|
35
|
+
*/
|
|
36
|
+
export declare const staticLibraryFile: (library: string, platform?: NodeJS.Platform) => string;
|
|
37
|
+
/**
|
|
38
|
+
* Where a platform's library goes in its package, whether `build:native` built it or the install
|
|
39
|
+
* script downloaded it.
|
|
40
|
+
* @param packageDir - The package's directory.
|
|
41
|
+
* @param platform - The platform key.
|
|
42
|
+
* @param library - The library's name without its extension.
|
|
43
|
+
* @returns `prebuilds/<platform>/<library file>` under it.
|
|
44
|
+
*/
|
|
45
|
+
export declare const installedLibraryFile: (packageDir: string, platform: string, library: string) => string;
|
|
46
|
+
//# sourceMappingURL=platform.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"platform.d.ts","sources":["../src/platform.ts"],"names":[],"mappings":"AAGA,qDAAqD;AACrD,MAAM,MAAM,SAAS,GAAG,KAAK,GAAG,MAAM,CAAC;AAEvC;;;;GAIG;AACH,eAAO,MAAM,SAAS,QAAO,SAc5B,CAAC;AAEF;;;;;;GAMG;AACH,eAAO,MAAM,WAAW,cACV,MAAM,CAAC,QAAQ,SACnB,MAAM,SACN,SAAS,KAChB,MAAkF,CAAC;AAEtF;;;;GAIG;AACH,eAAO,MAAM,iBAAiB,QAAS,MAAM,KAAG,MAAM,CAAC,QAGtD,CAAC;AAEF;;;;;GAKG;AACH,eAAO,MAAM,iBAAiB,YAAa,MAAM,aAAY,MAAM,CAAC,QAAQ,KAAsB,MAIjG,CAAC;AAEF;;;;;GAKG;AACH,eAAO,MAAM,iBAAiB,YAAa,MAAM,aAAY,MAAM,CAAC,QAAQ,KAAsB,MACtC,CAAC;AAE7D;;;;;;;GAOG;AACH,eAAO,MAAM,oBAAoB,eAAgB,MAAM,YAAY,MAAM,WAAW,MAAM,KAAG,MACO,CAAC"}
|
package/dist/platform.js
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
// src/platform.ts
|
|
4
|
+
/**
|
|
5
|
+
* Which C library this Linux process runs on. Node.js reports glibc's version in its process
|
|
6
|
+
* report and leaves it out under musl; Bun has no report, so the loader's name decides there.
|
|
7
|
+
* @returns `gnu` or `musl`.
|
|
8
|
+
*/
|
|
9
|
+
var linuxLibc = () => {
|
|
10
|
+
const report = process.report?.getReport?.();
|
|
11
|
+
const header = typeof report === "object" && report !== null && "header" in report ? report.header : void 0;
|
|
12
|
+
if (typeof header === "object" && header !== null && "glibcVersionRuntime" in header) return "gnu";
|
|
13
|
+
for (const loader of ["/lib/ld-musl-x86_64.so.1", "/lib/ld-musl-aarch64.so.1"]) if (existsSync(loader)) return "musl";
|
|
14
|
+
try {
|
|
15
|
+
return readFileSync("/usr/bin/ldd", "latin1").includes("musl") ? "musl" : "gnu";
|
|
16
|
+
} catch {
|
|
17
|
+
return "gnu";
|
|
18
|
+
}
|
|
19
|
+
};
|
|
20
|
+
/**
|
|
21
|
+
* The key a build of a native library is published under, such as `linux-x64-gnu`.
|
|
22
|
+
* @param platform - The operating system, as `process.platform` names it.
|
|
23
|
+
* @param arch - The processor, as `process.arch` names it.
|
|
24
|
+
* @param libc - The C library, for Linux; ignored elsewhere.
|
|
25
|
+
* @returns The key.
|
|
26
|
+
*/
|
|
27
|
+
var platformKey = (platform = process.platform, arch = process.arch, libc = platform === "linux" ? linuxLibc() : "gnu") => platform === "linux" ? `linux-${arch}-${libc}` : `${platform}-${arch}`;
|
|
28
|
+
/**
|
|
29
|
+
* The operating system a platform key is for.
|
|
30
|
+
* @param key - A key from {@link platformKey}, such as `linux-x64-gnu`.
|
|
31
|
+
* @returns The operating system, as `process.platform` names it.
|
|
32
|
+
*/
|
|
33
|
+
var operatingSystemOf = (key) => {
|
|
34
|
+
const os = key.slice(0, key.indexOf("-"));
|
|
35
|
+
return os === "win32" || os === "darwin" || os === "android" ? os : "linux";
|
|
36
|
+
};
|
|
37
|
+
/**
|
|
38
|
+
* The file name of a shared library on an operating system.
|
|
39
|
+
* @param library - The library's name without its extension, such as `libjsp_native_network`.
|
|
40
|
+
* @param platform - The operating system, as `process.platform` names it.
|
|
41
|
+
* @returns The file name.
|
|
42
|
+
*/
|
|
43
|
+
var sharedLibraryFile = (library, platform = process.platform) => {
|
|
44
|
+
if (platform === "win32") return `${library}.dll`;
|
|
45
|
+
if (platform === "darwin") return `${library}.dylib`;
|
|
46
|
+
return `${library}.so`;
|
|
47
|
+
};
|
|
48
|
+
/**
|
|
49
|
+
* The file name of the static archive a scriptc build links.
|
|
50
|
+
* @param library - The library's name without its extension.
|
|
51
|
+
* @param platform - The operating system, as `process.platform` names it.
|
|
52
|
+
* @returns The file name.
|
|
53
|
+
*/
|
|
54
|
+
var staticLibraryFile = (library, platform = process.platform) => platform === "win32" ? `${library}.lib` : `${library}.a`;
|
|
55
|
+
/**
|
|
56
|
+
* Where a platform's library goes in its package, whether `build:native` built it or the install
|
|
57
|
+
* script downloaded it.
|
|
58
|
+
* @param packageDir - The package's directory.
|
|
59
|
+
* @param platform - The platform key.
|
|
60
|
+
* @param library - The library's name without its extension.
|
|
61
|
+
* @returns `prebuilds/<platform>/<library file>` under it.
|
|
62
|
+
*/
|
|
63
|
+
var installedLibraryFile = (packageDir, platform, library) => join(packageDir, "prebuilds", platform, sharedLibraryFile(library, operatingSystemOf(platform)));
|
|
64
|
+
export { installedLibraryFile, linuxLibc, operatingSystemOf, platformKey, sharedLibraryFile, staticLibraryFile };
|
|
65
|
+
|
|
66
|
+
//# sourceMappingURL=platform.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"platform.js","names":[],"sources":["../src/platform.ts"],"sourcesContent":["import { existsSync, readFileSync } from 'node:fs';\nimport { join } from 'node:path';\n\n/** The C library a Linux build is linked against. */\nexport type LinuxLibc = 'gnu' | 'musl';\n\n/**\n * Which C library this Linux process runs on. Node.js reports glibc's version in its process\n * report and leaves it out under musl; Bun has no report, so the loader's name decides there.\n * @returns `gnu` or `musl`.\n */\nexport const linuxLibc = (): LinuxLibc => {\n const report = process.report?.getReport?.();\n // The report's type is not exported, so read it as the plain object it is.\n const header: unknown =\n typeof report === 'object' && report !== null && 'header' in report ? report.header : undefined;\n if (typeof header === 'object' && header !== null && 'glibcVersionRuntime' in header) return 'gnu';\n for (const loader of ['/lib/ld-musl-x86_64.so.1', '/lib/ld-musl-aarch64.so.1']) {\n if (existsSync(loader)) return 'musl';\n }\n try {\n return readFileSync('/usr/bin/ldd', 'latin1').includes('musl') ? 'musl' : 'gnu';\n } catch {\n return 'gnu';\n }\n};\n\n/**\n * The key a build of a native library is published under, such as `linux-x64-gnu`.\n * @param platform - The operating system, as `process.platform` names it.\n * @param arch - The processor, as `process.arch` names it.\n * @param libc - The C library, for Linux; ignored elsewhere.\n * @returns The key.\n */\nexport const platformKey = (\n platform: NodeJS.Platform = process.platform,\n arch: string = process.arch,\n libc: LinuxLibc = platform === 'linux' ? linuxLibc() : 'gnu'\n): string => (platform === 'linux' ? `linux-${arch}-${libc}` : `${platform}-${arch}`);\n\n/**\n * The operating system a platform key is for.\n * @param key - A key from {@link platformKey}, such as `linux-x64-gnu`.\n * @returns The operating system, as `process.platform` names it.\n */\nexport const operatingSystemOf = (key: string): NodeJS.Platform => {\n const os = key.slice(0, key.indexOf('-'));\n return os === 'win32' || os === 'darwin' || os === 'android' ? os : 'linux';\n};\n\n/**\n * The file name of a shared library on an operating system.\n * @param library - The library's name without its extension, such as `libjsp_native_network`.\n * @param platform - The operating system, as `process.platform` names it.\n * @returns The file name.\n */\nexport const sharedLibraryFile = (library: string, platform: NodeJS.Platform = process.platform): string => {\n if (platform === 'win32') return `${library}.dll`;\n if (platform === 'darwin') return `${library}.dylib`;\n return `${library}.so`;\n};\n\n/**\n * The file name of the static archive a scriptc build links.\n * @param library - The library's name without its extension.\n * @param platform - The operating system, as `process.platform` names it.\n * @returns The file name.\n */\nexport const staticLibraryFile = (library: string, platform: NodeJS.Platform = process.platform): string =>\n platform === 'win32' ? `${library}.lib` : `${library}.a`;\n\n/**\n * Where a platform's library goes in its package, whether `build:native` built it or the install\n * script downloaded it.\n * @param packageDir - The package's directory.\n * @param platform - The platform key.\n * @param library - The library's name without its extension.\n * @returns `prebuilds/<platform>/<library file>` under it.\n */\nexport const installedLibraryFile = (packageDir: string, platform: string, library: string): string =>\n join(packageDir, 'prebuilds', platform, sharedLibraryFile(library, operatingSystemOf(platform)));\n"],"mappings":";;;;;;;;AAWA,IAAa,kBAA6B;CACtC,MAAM,SAAS,QAAQ,QAAQ,YAAY;CAE3C,MAAM,SACF,OAAO,WAAW,YAAY,WAAW,QAAQ,YAAY,SAAS,OAAO,SAAS,KAAA;CAC1F,IAAI,OAAO,WAAW,YAAY,WAAW,QAAQ,yBAAyB,QAAQ,OAAO;CAC7F,KAAK,MAAM,UAAU,CAAC,4BAA4B,2BAA2B,GACzE,IAAI,WAAW,MAAM,GAAG,OAAO;CAEnC,IAAI;EACA,OAAO,aAAa,gBAAgB,QAAQ,CAAC,CAAC,SAAS,MAAM,IAAI,SAAS;CAC9E,QAAQ;EACJ,OAAO;CACX;AACJ;;;;;;;;AASA,IAAa,eACT,WAA4B,QAAQ,UACpC,OAAe,QAAQ,MACvB,OAAkB,aAAa,UAAU,UAAU,IAAI,UAC7C,aAAa,UAAU,SAAS,KAAK,GAAG,SAAS,GAAG,SAAS,GAAG;;;;;;AAO9E,IAAa,qBAAqB,QAAiC;CAC/D,MAAM,KAAK,IAAI,MAAM,GAAG,IAAI,QAAQ,GAAG,CAAC;CACxC,OAAO,OAAO,WAAW,OAAO,YAAY,OAAO,YAAY,KAAK;AACxE;;;;;;;AAQA,IAAa,qBAAqB,SAAiB,WAA4B,QAAQ,aAAqB;CACxG,IAAI,aAAa,SAAS,OAAO,GAAG,QAAQ;CAC5C,IAAI,aAAa,UAAU,OAAO,GAAG,QAAQ;CAC7C,OAAO,GAAG,QAAQ;AACtB;;;;;;;AAQA,IAAa,qBAAqB,SAAiB,WAA4B,QAAQ,aACnF,aAAa,UAAU,GAAG,QAAQ,QAAQ,GAAG,QAAQ;;;;;;;;;AAUzD,IAAa,wBAAwB,YAAoB,UAAkB,YACvE,KAAK,YAAY,aAAa,UAAU,kBAAkB,SAAS,kBAAkB,QAAQ,CAAC,CAAC"}
|
package/package.json
CHANGED
|
@@ -1,10 +1,74 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@jsprismarine/native-library",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "
|
|
3
|
+
"version": "0.24.0-unstable-20261121104535",
|
|
4
|
+
"description": "Finds, verifies and installs the prebuilt native libraries JSPrismarine's packages load",
|
|
5
|
+
"sideEffects": false,
|
|
6
|
+
"publishConfig": {
|
|
7
|
+
"access": "public"
|
|
8
|
+
},
|
|
9
|
+
"type": "module",
|
|
10
|
+
"files": [
|
|
11
|
+
"dist",
|
|
12
|
+
"CHANGELOG.md",
|
|
13
|
+
"README.md"
|
|
14
|
+
],
|
|
15
|
+
"module": "./dist/NativeLibrary.js",
|
|
16
|
+
"types": "./dist/NativeLibrary.d.ts",
|
|
17
|
+
"exports": {
|
|
18
|
+
".": {
|
|
19
|
+
"types": "./dist/NativeLibrary.d.ts",
|
|
20
|
+
"import": "./dist/NativeLibrary.js",
|
|
21
|
+
"module": "./dist/NativeLibrary.js"
|
|
22
|
+
},
|
|
23
|
+
"./manifest": {
|
|
24
|
+
"types": "./dist/manifest.d.ts",
|
|
25
|
+
"import": "./dist/manifest.js",
|
|
26
|
+
"module": "./dist/manifest.js"
|
|
27
|
+
},
|
|
28
|
+
"./nativeHash": {
|
|
29
|
+
"types": "./dist/nativeHash.d.ts",
|
|
30
|
+
"import": "./dist/nativeHash.js",
|
|
31
|
+
"module": "./dist/nativeHash.js"
|
|
32
|
+
},
|
|
33
|
+
"./platform": {
|
|
34
|
+
"types": "./dist/platform.d.ts",
|
|
35
|
+
"import": "./dist/platform.js",
|
|
36
|
+
"module": "./dist/platform.js"
|
|
37
|
+
},
|
|
38
|
+
"./package.json": "./package.json"
|
|
39
|
+
},
|
|
40
|
+
"repository": {
|
|
41
|
+
"type": "git",
|
|
42
|
+
"url": "git+https://github.com/JSPrismarine/JSPrismarine.git"
|
|
43
|
+
},
|
|
5
44
|
"keywords": [
|
|
6
|
-
"
|
|
7
|
-
"
|
|
8
|
-
"
|
|
9
|
-
|
|
10
|
-
|
|
45
|
+
"jsprismarine",
|
|
46
|
+
"native",
|
|
47
|
+
"ffi",
|
|
48
|
+
"prebuilds"
|
|
49
|
+
],
|
|
50
|
+
"author": "JSPrismarine",
|
|
51
|
+
"license": "(MIT OR MPL-2.0)",
|
|
52
|
+
"bugs": {
|
|
53
|
+
"url": "https://github.com/JSPrismarine/JSPrismarine/issues"
|
|
54
|
+
},
|
|
55
|
+
"homepage": "https://github.com/JSPrismarine/JSPrismarine/tree/master/packages/native-library",
|
|
56
|
+
"devDependencies": {
|
|
57
|
+
"@types/node": "26.6.6",
|
|
58
|
+
"glob": "14.0.6",
|
|
59
|
+
"rimraf": "6.1.4",
|
|
60
|
+
"typescript": "7.0.2",
|
|
61
|
+
"vite": "8.3.8",
|
|
62
|
+
"vitest": "5.1.1"
|
|
63
|
+
},
|
|
64
|
+
"dependencies": {
|
|
65
|
+
"@jsprismarine/errors": "0.24.0-unstable-20261121104535"
|
|
66
|
+
},
|
|
67
|
+
"scripts": {
|
|
68
|
+
"clean": "rimraf dist jsp *.tsbuildinfo vite.config.ts.timestamp-* .tsup .turbo",
|
|
69
|
+
"build": "vite build && node ../../scripts/emit-dts.mts",
|
|
70
|
+
"build:watch": "vite build --watch",
|
|
71
|
+
"test": "vitest run",
|
|
72
|
+
"typecheck": "tsc-ts --noEmit && tsc-ts --noEmit -p tsconfig.test.json"
|
|
73
|
+
}
|
|
74
|
+
}
|