@osdlc/npm-binary 0.0.0-stage → 0.0.1-stage

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 ADDED
@@ -0,0 +1,25 @@
1
+ # @osdlc/npm-binary
2
+
3
+ ## History before the first public release
4
+
5
+ These versions were never published. The first release of `@osdlc/npm-binary`
6
+ on npm is 0.1.1, and the entry for it is added above this section when it is
7
+ released.
8
+
9
+ ### [0.1.0] - 2026-10-06 (unpublished)
10
+
11
+ #### Added
12
+
13
+ - Ship a compiled binary through npm as one launcher package plus one
14
+ `os`/`cpu`-gated package per platform.
15
+ - Platform helpers: `platformKey`, `platformPackageName`, `binaryExt`,
16
+ `binaryFileName`, `binaryPathInPackage`, `findPlatform`, `hostPlatform`,
17
+ `NPM_PLATFORMS`.
18
+ - `platformManifest` and `launcherManifest` package.json builders, which keep
19
+ a product's template key order; `writeJson` and `copyExecutable`.
20
+ - `renderLauncher`: a Node launcher shim that resolves the platform package,
21
+ runs the binary with inherited stdio, forwards signals to it and re-raises
22
+ the binary's signal or exits `128 + signal`.
23
+ - `publishPackages`: platform packages first, the launcher last, skipping
24
+ versions already published.
25
+ - `cargoTargetDir`: cargo's target directory from `cargo metadata`.
@@ -0,0 +1,61 @@
1
+ # Contributing
2
+
3
+ Thanks for your interest in `@osdlc/npm-binary`.
4
+
5
+ ## Issues
6
+
7
+ Report bugs and ask for features in the
8
+ [issue tracker](https://github.com/osdlc/osdlc/issues). For a bug, include the
9
+ library version, your Node and npm (or pnpm, Yarn, Bun) versions, your
10
+ operating system and CPU, and a minimal example: the product names you pass
11
+ and the package.json or launcher output you got. Report security problems privately. See
12
+ [SECURITY.md](./SECURITY.md).
13
+
14
+ ## Pull requests
15
+
16
+ This package lives in [osdlc/osdlc](https://github.com/osdlc/osdlc) under
17
+ `packages/ts/npm-binary`. Open pull requests there. They are reviewed and
18
+ merged there.
19
+
20
+ ## Running the tests
21
+
22
+ The repository is a pnpm workspace. Install from the repository root, then
23
+ work in the package directory. The tests run on Vitest under Node 22 or
24
+ later. Build first: the workspace packages and the examples resolve each other
25
+ through `dist/`.
26
+
27
+ ```sh
28
+ pnpm install
29
+ cd packages/ts/npm-binary
30
+ pnpm run build
31
+ pnpm test
32
+ ```
33
+
34
+ `pnpm run smoke` runs `tests/smoke.mjs`, a short check of the built package
35
+ under Node. It is not published. `examples/readme.test.ts` installs the
36
+ README's packages in a temporary `node_modules` and runs the launcher with
37
+ Node, so a launcher change is tested end to end on Linux and macOS.
38
+ `pnpm run coverage` reports test coverage.
39
+
40
+ Other checks:
41
+
42
+ ```sh
43
+ pnpm run typecheck
44
+ pnpm run lint
45
+ pnpm run format:check
46
+ ```
47
+
48
+ ## Code style
49
+
50
+ - TypeScript, ES modules, and explicit `.ts` import paths.
51
+ - Prettier formats the code and oxlint checks it. Run `pnpm run format` and
52
+ `pnpm run lint` before you commit.
53
+ - Add a test for each behaviour change or bug fix.
54
+ - A new export gets TSDoc and a use in `examples/`, which imports the package
55
+ by name. A test fails if an export has no example.
56
+ - An experimental export carries `@experimental` and is listed in the
57
+ README's Stability section. A test checks that the two agree.
58
+ - For a change users can see, add a changeset: run `pnpm changeset` at the
59
+ repository root. Start a breaking change's summary with `**Breaking:**`.
60
+ Do not edit `CHANGELOG.md` or `version` by hand; the release writes them.
61
+ See [packages/README.md](https://github.com/osdlc/osdlc/blob/main/packages/README.md).
package/LICENSE-APACHE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright 2026 Sizer LLC
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/LICENSE-MIT ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 SK Sizer
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,3 +1,234 @@
1
- # Temporary Holding Version
1
+ # @osdlc/npm-binary
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Ship a compiled binary through npm the way esbuild and Biome do: one launcher
4
+ package that users install, plus one package per platform. Each platform
5
+ package is gated by `os` and `cpu`, and the launcher lists them all as
6
+ `optionalDependencies`, so npm downloads only the one that matches the host.
7
+ `npx your-tool` and `npm install -g your-tool` then run a native executable,
8
+ with no install script and no download from anywhere but the registry.
9
+
10
+ ## Why
11
+
12
+ A tool written in Rust, Go, Zig or compiled with `bun build --compile` has
13
+ one executable per platform. Getting it onto a JavaScript developer's machine
14
+ through npm takes the same handful of pieces every time: the platform names,
15
+ two `package.json` shapes, a small Node script that finds and runs the right
16
+ executable, and a publish order that keeps the launcher from pointing at
17
+ packages that do not exist yet. Each piece has edge cases (Windows `.exe`,
18
+ Yarn Plug'n'Play, Ctrl-C delivered twice, a launcher re-raising its child's
19
+ signal). This library holds those pieces, so your release script keeps only
20
+ its build step and its names.
21
+
22
+ It is for the author of a CLI who already builds the executables, in CI or
23
+ locally, and wants npm as one more channel.
24
+
25
+ Do not use it when:
26
+
27
+ - your binary is a Node-API addon (`.node`) loaded with `require`. Use
28
+ [`@napi-rs/cli`](https://www.npmjs.com/package/@napi-rs/cli), which builds
29
+ platform packages for addons.
30
+ - you want one tool to own the whole release (versions, tags, every
31
+ registry). A release orchestrator such as
32
+ [putitoutthere](https://www.npmjs.com/package/putitoutthere) or
33
+ [dist](https://github.com/axodotdev/cargo-dist) does that; this library is
34
+ the npm layout only, called from a script you own.
35
+ - you would rather download the executable from a release page at install
36
+ time (`binary-install` and similar). That needs install scripts, which many
37
+ CI setups disable with `--ignore-scripts`; this layout does not.
38
+
39
+ ## Install
40
+
41
+ ```sh
42
+ npm install --save-dev @osdlc/npm-binary
43
+ ```
44
+
45
+ ESM only, Node 22 or later, with types. The launcher it writes is plain
46
+ CommonJS with no dependencies and runs on Node 18 or later on the user's
47
+ machine.
48
+
49
+ ## Use
50
+
51
+ Your release script builds the binaries, then writes one directory per
52
+ package and publishes them. This writes every package for a tool named
53
+ `tool`, with a stand-in for each platform's build:
54
+
55
+ ```ts
56
+ import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
57
+ import { tmpdir } from 'node:os'
58
+ import { join } from 'node:path'
59
+
60
+ import {
61
+ type BinaryProduct,
62
+ binaryPathInPackage,
63
+ copyExecutable,
64
+ launcherManifest,
65
+ NPM_PLATFORMS,
66
+ platformKey,
67
+ platformManifest,
68
+ renderLauncher,
69
+ writeJson,
70
+ } from '@osdlc/npm-binary'
71
+
72
+ const product: BinaryProduct = {
73
+ binary: 'tool', // the command on PATH
74
+ launcher: '@acme/tool', // the package users install
75
+ scope: '@acme', // platform packages are @acme/tool-<os>-<cpu>
76
+ platformPrefix: 'tool',
77
+ binaryDir: 'bin', // where the binary sits inside a platform package
78
+ }
79
+ const version = '1.0.0'
80
+ const out = mkdtempSync(join(tmpdir(), 'tool-npm-'))
81
+ const built = join(out, 'stand-in') // your build output for each platform
82
+ writeFileSync(built, '#!/bin/sh\necho hello\n')
83
+
84
+ const platformDirs = NPM_PLATFORMS.map((platform) => {
85
+ const dir = join(out, platformKey(platform))
86
+ mkdirSync(join(dir, 'bin'), { recursive: true })
87
+ writeJson(
88
+ join(dir, 'package.json'),
89
+ platformManifest(product, platform, {
90
+ version,
91
+ description: `The tool binary for ${platformKey(platform)}.`,
92
+ // Platform packages are scoped, and npm publishes a new scoped package
93
+ // as private unless publishConfig.access says public.
94
+ template: { license: 'MIT', publishConfig: { access: 'public' } },
95
+ }),
96
+ )
97
+ copyExecutable(built, join(dir, binaryPathInPackage(product, platform)))
98
+ return dir
99
+ })
100
+
101
+ const launcherDir = join(out, 'tool')
102
+ mkdirSync(join(launcherDir, 'bin'), { recursive: true })
103
+ writeJson(
104
+ join(launcherDir, 'package.json'),
105
+ launcherManifest(product, NPM_PLATFORMS, {
106
+ version,
107
+ description: 'The tool CLI.',
108
+ launcherPath: 'bin/tool.js',
109
+ }),
110
+ )
111
+ writeFileSync(join(launcherDir, 'bin', 'tool.js'), renderLauncher(product, NPM_PLATFORMS))
112
+
113
+ // Then, logged in to npm:
114
+ // await publishPackages({ platformDirs, launcherDir })
115
+ console.log(`${platformDirs.length} platform packages and the launcher in ${out}`)
116
+ rmSync(out, { recursive: true, force: true })
117
+ ```
118
+
119
+ [`examples/readme.test.ts`](examples/readme.test.ts) installs those packages
120
+ the way npm lays them out and runs the launcher.
121
+
122
+ ## Guide
123
+
124
+ - [Getting started](docs/guide/getting-started.md): publish a CLI for five
125
+ platforms, step by step, with the `package.json` files it writes.
126
+ - [How the launcher works](docs/guide/how-the-launcher-works.md): what runs on
127
+ the user's machine, signals and exit codes.
128
+ - [Troubleshooting](docs/guide/troubleshooting.md): the errors users can hit,
129
+ their causes and fixes.
130
+
131
+ ## How the launcher behaves
132
+
133
+ `renderLauncher` returns the launcher script. On the user's machine it finds
134
+ the platform package npm installed for that host, runs its binary with the
135
+ same arguments and the terminal, passes signals through, and exits with the
136
+ binary's exit code. A host with no build, or a missing platform package, gets
137
+ an error that names the cause. Every name is written into the script as a
138
+ JavaScript string literal, so quotes and backslashes in names are safe.
139
+
140
+ [How the launcher works](docs/guide/how-the-launcher-works.md) has the
141
+ details: the lookup, when Ctrl-C is and is not forwarded, and the exit codes.
142
+
143
+ ## API
144
+
145
+ Names and platforms:
146
+
147
+ - `BinaryProduct`: the names one product ships under (`binary`, `launcher`,
148
+ `scope`, `platformPrefix`, `binaryDir`).
149
+ - `NpmPlatform`: an `os` and a `cpu`, as `process.platform` and
150
+ `process.arch` name them. Any value Node reports is accepted; `darwin`,
151
+ `linux`, `win32`, `arm64` and `x64` are named for completion.
152
+ - `NPM_PLATFORMS`: the default list, in publish order: `darwin-arm64`,
153
+ `darwin-x64`, `linux-x64`, `linux-arm64`, `win32-x64`.
154
+ - `platformKey(platform)`: `darwin-arm64`.
155
+ - `platformPackageName(product, platform)`: `@acme/tool-darwin-arm64`.
156
+ - `binaryExt(platform)`: `.exe` on Windows, empty elsewhere.
157
+ - `binaryFileName(product, platform)`: `tool` or `tool.exe`.
158
+ - `binaryPathInPackage(product, platform)`: `bin/tool`, or `tool` when
159
+ `binaryDir` is `''`.
160
+ - `findPlatform(platforms, key)`: the entry for a key; throws, naming the
161
+ known keys, for any other.
162
+ - `hostPlatform(platforms)`: the entry for the machine this runs on.
163
+
164
+ Package shapes:
165
+
166
+ - `platformManifest(product, platform, options)`: a platform package's
167
+ `package.json`, with `os`, `cpu`, `preferUnplugged: true` (so Yarn PnP keeps
168
+ the binary a real file) and `files` defaulting to the binary (a
169
+ template's `files` gets the binary added).
170
+ - `launcherManifest(product, platforms, options)`: the launcher's
171
+ `package.json`, with `bin`, every platform package in
172
+ `optionalDependencies` at the same version, `files` defaulting to the
173
+ launcher and `README.md` (a template's `files` gets the launcher added),
174
+ and `engines.node` defaulting to `>=18`. A launcher template with
175
+ `"type": "module"` is refused: the launcher is CommonJS.
176
+ - `PlatformManifestOptions` and `LauncherManifestOptions`: `version`,
177
+ `description`, the launcher's `launcherPath`, and an optional `template`
178
+ with fields to carry (`license`, `author`, `publishConfig`, ...). Template
179
+ fields keep their position, and the fields the library sets that the
180
+ template does not name are appended, so your template controls the key
181
+ order and the bytes written. `name`, `version` and `description` always
182
+ come from the arguments; naming them in the template only fixes their
183
+ position.
184
+ - `Manifest`: a `package.json` as a plain object.
185
+ - `writeJson(path, value)`: two-space JSON with a final newline.
186
+ - `copyExecutable(src, dest)`: copies a file and sets mode `0o755`.
187
+
188
+ The launcher:
189
+
190
+ - `renderLauncher(product, platforms, options?)`: the launcher script's
191
+ source, described above. `LauncherOptions` has `debugEnv`.
192
+
193
+ Publishing and cargo:
194
+
195
+ - `publishPackages(options)`: `npm publish` in each platform directory, then
196
+ the launcher's, with the npm on `PATH` and its login. It asks the registry
197
+ first and skips every `name@version` already published, so a half-finished
198
+ run is safe to run again. `PublishOptions` has `platformDirs`,
199
+ `launcherDir`, `dryRun`, and `viewRunner` and `publishRunner` to replace the
200
+ `npm` it runs (for tests). It returns a `PublishResult`: the `published` and
201
+ `skipped` packages as `name@version`.
202
+ - `cargoTargetDir(options)`: cargo's target directory, from
203
+ `cargo metadata --no-deps`, for a release script that builds with cargo.
204
+ `CargoTargetDirOptions` has `cwd`, an optional `manifestPath` for a crate
205
+ outside the workspace at `cwd`, and a `runner` for tests.
206
+
207
+ ## Platforms
208
+
209
+ The library runs anywhere Node 22 runs. The launcher it writes runs on every
210
+ platform in the list you pass. What it does not do:
211
+
212
+ - tell glibc from musl. It sets no `libc` field, so one `linux-x64` package
213
+ installs on glibc and musl (Alpine) hosts alike, and a glibc build fails on
214
+ Alpine. Ship a static (musl) Linux build.
215
+ - fall back to an emulated build. On Windows on Arm, `process.arch` is `arm64`,
216
+ so the launcher reports no build unless your list has `win32-arm64`, even
217
+ though an x64 build would run under emulation.
218
+ - forward SIGHUP on Windows. Node raises it there when the console window
219
+ closes, and the binary gets that close event itself.
220
+ - forward SIGINT on Windows. The binary gets the console's Ctrl-C itself,
221
+ and Node's `kill` on Windows is a hard kill rather than a signal.
222
+
223
+ The tests run on Linux and macOS. The launcher's Windows paths (`.exe`, no
224
+ SIGHUP, no SIGINT forwarding, a signal that cannot be re-raised) are covered
225
+ by unit tests, not by a Windows run.
226
+
227
+ ## Stability
228
+
229
+ Every export is stable within the 0.x line: a breaking change bumps the minor
230
+ version and is listed in the CHANGELOG. No export is experimental.
231
+
232
+ ## Licence
233
+
234
+ `MIT OR Apache-2.0`, at your option. See [LICENSE-MIT](./LICENSE-MIT) and [LICENSE-APACHE](./LICENSE-APACHE).
package/SECURITY.md ADDED
@@ -0,0 +1,23 @@
1
+ # Security policy
2
+
3
+ ## Reporting a vulnerability
4
+
5
+ Please report vulnerabilities privately. Do not open a public issue.
6
+
7
+ Use GitHub private vulnerability reporting on the repository: open the
8
+ [Security tab](https://github.com/osdlc/osdlc/security) and choose
9
+ "Report a vulnerability".
10
+
11
+ Include the version, a short description, and steps to reproduce. A minimal
12
+ code sample helps.
13
+
14
+ ## Supported versions
15
+
16
+ Only the latest `0.x` release gets security fixes. The library is pre-1.0, so
17
+ older `0.x` releases are not patched. Upgrade to the latest release.
18
+
19
+ ## What to expect
20
+
21
+ This is a small project. We aim to reply within a week. We will tell you
22
+ whether we accept the report and keep you updated until a fix is released.
23
+ We will credit you in the release notes if you want that.
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Where cargo writes build output, asked of cargo rather than derived from a
3
+ * path: workspace membership decides it.
4
+ */
5
+ import { type CommandRunner } from '@osdlc/command-seam';
6
+ /** Options for {@link cargoTargetDir}. */
7
+ export interface CargoTargetDirOptions {
8
+ /** The directory cargo runs in. */
9
+ cwd: string;
10
+ /** A crate outside the workspace at `cwd` has its own target dir. */
11
+ manifestPath?: string;
12
+ /** Runs `cargo`. Defaults to spawning it; a test passes a fake. */
13
+ runner?: CommandRunner;
14
+ }
15
+ /**
16
+ * Cargo's target directory, from `cargo metadata --no-deps`. Throws when cargo
17
+ * fails, or when its output has no `target_directory`.
18
+ */
19
+ export declare function cargoTargetDir({ cwd, manifestPath, runner, }: CargoTargetDirOptions): string;
package/dist/cargo.js ADDED
@@ -0,0 +1,20 @@
1
+ /**
2
+ * Where cargo writes build output, asked of cargo rather than derived from a
3
+ * path: workspace membership decides it.
4
+ */
5
+ import { runChecked, spawnRunner } from '@osdlc/command-seam';
6
+ /**
7
+ * Cargo's target directory, from `cargo metadata --no-deps`. Throws when cargo
8
+ * fails, or when its output has no `target_directory`.
9
+ */
10
+ export function cargoTargetDir({ cwd, manifestPath, runner = spawnRunner('cargo'), }) {
11
+ const argv = ['metadata', '--no-deps', '--format-version', '1'];
12
+ if (manifestPath !== undefined)
13
+ argv.push('--manifest-path', manifestPath);
14
+ const { stdout } = runChecked(runner, argv, { cwd });
15
+ const dir = JSON.parse(stdout).target_directory;
16
+ if (typeof dir !== 'string' || dir === '') {
17
+ throw new Error('cargo metadata printed no target_directory');
18
+ }
19
+ return dir;
20
+ }
@@ -0,0 +1,5 @@
1
+ export * from './cargo.ts';
2
+ export * from './launcher.ts';
3
+ export * from './manifest.ts';
4
+ export * from './platform.ts';
5
+ export * from './publish.ts';
package/dist/index.js ADDED
@@ -0,0 +1,5 @@
1
+ export * from "./cargo.js";
2
+ export * from "./launcher.js";
3
+ export * from "./manifest.js";
4
+ export * from "./platform.js";
5
+ export * from "./publish.js";
@@ -0,0 +1,106 @@
1
+ #!/usr/bin/env node
2
+ // Runs the native binary from the platform package npm installed alongside
3
+ // this one. Generated by @osdlc/npm-binary, which replaces each quoted
4
+ // placeholder below with a string literal.
5
+ //
6
+ // It runs on the consumer's machine before any compiled binary is available,
7
+ // so it stays CommonJS and dependency-free.
8
+ 'use strict'
9
+
10
+ const { spawn } = require('node:child_process')
11
+ const fs = require('node:fs')
12
+ const os = require('node:os')
13
+ const path = require('node:path')
14
+
15
+ const PLATFORM_PACKAGES = JSON.parse('{{platformPackages}}')
16
+ const BINARY = '{{binary}}'
17
+ const LAUNCHER = '{{launcher}}'
18
+ const DEBUG_ENV = '{{debugEnv}}'
19
+
20
+ function binaryPath() {
21
+ const key = `${process.platform}-${process.arch}`
22
+ const target = PLATFORM_PACKAGES[key]
23
+ if (!target) {
24
+ throw new Error(
25
+ `${BINARY} has no build for ${key}. Supported: ${Object.keys(PLATFORM_PACKAGES).join(', ')}.`,
26
+ )
27
+ }
28
+ const { package: pkg, binary: file } = target
29
+ let bin
30
+ try {
31
+ // Through package.json: always resolvable, never blocked by an "exports" map.
32
+ bin = path.join(path.dirname(require.resolve(`${pkg}/package.json`)), file)
33
+ } catch {
34
+ throw new Error(
35
+ `${BINARY}: the platform package ${pkg} is not installed. ` +
36
+ `It is an optional dependency of ${LAUNCHER}, so it is skipped when optional dependencies are ` +
37
+ 'turned off (--omit=optional, --no-optional) or when the lockfile was made on another platform. ' +
38
+ `Reinstall without those, or add ${pkg} directly.`,
39
+ )
40
+ }
41
+ if (!fs.existsSync(bin)) {
42
+ throw new Error(
43
+ `${BINARY}: ${pkg} is installed but its binary ${bin} is missing; try reinstalling.`,
44
+ )
45
+ }
46
+ return { bin, pkg }
47
+ }
48
+
49
+ let bin, pkg
50
+ try {
51
+ ;({ bin, pkg } = binaryPath())
52
+ } catch (error) {
53
+ process.stderr.write(`${error.message}\n`)
54
+ process.exit(1)
55
+ }
56
+
57
+ if (DEBUG_ENV && process.env[DEBUG_ENV]) {
58
+ process.stderr.write(
59
+ `${BINARY} launcher: platform=${process.platform}-${process.arch} package=${pkg} binary=${bin}\n`,
60
+ )
61
+ }
62
+
63
+ // Inherited stdio, so the binary owns the terminal. In a terminal, Ctrl-C already
64
+ // reaches the child through its process group, so SIGINT is forwarded only when
65
+ // no standard stream is a terminal; forwarding it too would read as a second
66
+ // Ctrl-C. On Windows the child gets the console's Ctrl-C itself and kill() is a
67
+ // hard kill, so SIGINT is never forwarded there. SIGTERM and SIGHUP (not on
68
+ // Windows) are always forwarded.
69
+ //
70
+ // The handlers go in before the spawn: the child starts running inside spawn(),
71
+ // and a signal that arrived before them would end the launcher and orphan it.
72
+ // A handler runs on a later tick, after spawn() has returned and set `child`.
73
+ const forwardSigint =
74
+ process.platform !== 'win32' &&
75
+ ![process.stdin, process.stdout, process.stderr].some((stream) => stream.isTTY === true)
76
+ const signals = ['SIGINT', 'SIGTERM', ...(process.platform === 'win32' ? [] : ['SIGHUP'])]
77
+ let child
78
+ for (const signal of signals) {
79
+ process.on(signal, () => {
80
+ if (signal === 'SIGINT' && !forwardSigint) return
81
+ try {
82
+ child.kill(signal)
83
+ } catch {
84
+ // Child already gone; its exit handler finishes up.
85
+ }
86
+ })
87
+ }
88
+ child = spawn(bin, process.argv.slice(2), { stdio: 'inherit' })
89
+ child.on('error', (error) => {
90
+ process.stderr.write(`${BINARY}: could not run ${bin}: ${error.message}\n`)
91
+ process.exit(1)
92
+ })
93
+ child.on('exit', (code, signal) => {
94
+ if (signal) {
95
+ // Restore default handling so the re-raise ends this process like the child.
96
+ process.removeAllListeners(signal)
97
+ try {
98
+ process.kill(process.pid, signal)
99
+ } catch {
100
+ // Not raisable here (Windows); fall through to the exit code.
101
+ }
102
+ // A signal Node ignores (SIGPIPE) leaves us running: exit the shell way.
103
+ process.exit(128 + (os.constants.signals[signal] ?? 0))
104
+ }
105
+ process.exit(code ?? 1)
106
+ })
@@ -0,0 +1,24 @@
1
+ import { type BinaryProduct, type NpmPlatform } from './platform.ts';
2
+ /** Options for {@link renderLauncher}. */
3
+ export interface LauncherOptions {
4
+ /**
5
+ * The name of an environment variable. When it is set to a non-empty value,
6
+ * the launcher prints the platform, package and binary it resolved to stderr.
7
+ * Empty (the default) turns the debug line off.
8
+ */
9
+ debugEnv?: string;
10
+ }
11
+ /**
12
+ * The launcher script's source: a dependency-free CommonJS file for the
13
+ * launcher package's `bin`. On the user's machine it finds the platform package
14
+ * npm installed for the host, runs its binary with inherited stdio, passes
15
+ * signals through and exits with the binary's code (or `128 + signal`).
16
+ *
17
+ * Every value is written into the script as a JavaScript string literal, so a
18
+ * name with quotes or backslashes is safe.
19
+ *
20
+ * @param product - The names the product ships under.
21
+ * @param platforms - The platforms the launcher knows. A host outside this list
22
+ * gets an error that names the supported ones.
23
+ */
24
+ export declare function renderLauncher(product: BinaryProduct, platforms: readonly NpmPlatform[], { debugEnv }?: LauncherOptions): string;
@@ -0,0 +1,44 @@
1
+ /**
2
+ * Render the Node launcher shim from `launcher-template.cjs`.
3
+ */
4
+ import { readFileSync } from 'node:fs';
5
+ import { fileURLToPath } from 'node:url';
6
+ import { binaryPathInPackage, platformKey, platformPackageName, } from "./platform.js";
7
+ const TEMPLATE = fileURLToPath(new URL('./launcher-template.cjs', import.meta.url));
8
+ /**
9
+ * The launcher script's source: a dependency-free CommonJS file for the
10
+ * launcher package's `bin`. On the user's machine it finds the platform package
11
+ * npm installed for the host, runs its binary with inherited stdio, passes
12
+ * signals through and exits with the binary's code (or `128 + signal`).
13
+ *
14
+ * Every value is written into the script as a JavaScript string literal, so a
15
+ * name with quotes or backslashes is safe.
16
+ *
17
+ * @param product - The names the product ships under.
18
+ * @param platforms - The platforms the launcher knows. A host outside this list
19
+ * gets an error that names the supported ones.
20
+ */
21
+ export function renderLauncher(product, platforms, { debugEnv = '' } = {}) {
22
+ const values = {
23
+ platformPackages: JSON.stringify(launcherTable(product, platforms)),
24
+ binary: product.binary,
25
+ launcher: product.launcher,
26
+ debugEnv,
27
+ };
28
+ // The template holds each placeholder as a quoted string, `'{{name}}'`, so it
29
+ // stays valid JavaScript. The whole quoted token becomes a JSON string
30
+ // literal, which is also a valid JavaScript string literal.
31
+ return readFileSync(TEMPLATE, 'utf8').replace(/'\{\{(\w+)\}\}'/g, (_, key) => {
32
+ const value = values[key];
33
+ if (value === undefined)
34
+ throw new Error(`launcher template has an unknown placeholder: ${key}`);
35
+ return JSON.stringify(value);
36
+ });
37
+ }
38
+ /** The launcher's lookup table: platform key to package and binary path. */
39
+ function launcherTable(product, platforms) {
40
+ return Object.fromEntries(platforms.map((p) => [
41
+ platformKey(p),
42
+ { package: platformPackageName(product, p), binary: binaryPathInPackage(product, p) },
43
+ ]));
44
+ }
@@ -0,0 +1,45 @@
1
+ import { type BinaryProduct, type NpmPlatform } from './platform.ts';
2
+ /** A package.json as a plain object. */
3
+ export type Manifest = Record<string, unknown>;
4
+ /** Options for {@link platformManifest}. */
5
+ export interface PlatformManifestOptions {
6
+ version: string;
7
+ description: string;
8
+ /**
9
+ * Fields to carry, such as `license`, `author` or `publishConfig`. Each keeps
10
+ * its position. `name`, `version` and `description` here only fix their
11
+ * position: their values come from the arguments. The template is copied,
12
+ * so the result shares no objects with it.
13
+ */
14
+ template?: Manifest;
15
+ }
16
+ /**
17
+ * One platform package's package.json: gated by `os` and `cpu`, so npm
18
+ * installs it only on a matching host. `files` defaults to the binary alone;
19
+ * a template's `files` gets the binary added when it lacks it.
20
+ * `preferUnplugged` keeps the binary a real file under Yarn PnP, so the
21
+ * launcher can run it.
22
+ */
23
+ export declare function platformManifest(product: BinaryProduct, platform: NpmPlatform, { version, description, template }: PlatformManifestOptions): Manifest;
24
+ /** Options for {@link launcherManifest}. */
25
+ export interface LauncherManifestOptions {
26
+ version: string;
27
+ description: string;
28
+ /** The launcher script's path inside the package, e.g. `bin/launcher.js`. */
29
+ launcherPath: string;
30
+ /** As {@link PlatformManifestOptions.template}. */
31
+ template?: Manifest;
32
+ }
33
+ /**
34
+ * The launcher package's package.json. Lists every platform package as an
35
+ * optional dependency at the same version, built or not. `files` defaults to
36
+ * the launcher and the README; a template's `files` gets the launcher added
37
+ * when it lacks it. `engines.node` defaults to `>=18`. The launcher is
38
+ * CommonJS, so a template with `"type": "module"` is refused unless
39
+ * `launcherPath` ends in `.cjs`.
40
+ */
41
+ export declare function launcherManifest(product: BinaryProduct, platforms: readonly NpmPlatform[], { version, description, launcherPath, template }: LauncherManifestOptions): Manifest;
42
+ /** Writes `value` as JSON with two-space indent and a final newline, as npm does. */
43
+ export declare function writeJson(path: string, value: unknown): void;
44
+ /** Copies a binary into a package and marks it executable (mode `0o755`). */
45
+ export declare function copyExecutable(src: string, dest: string): void;
@@ -0,0 +1,74 @@
1
+ /**
2
+ * The package.json of a platform package and of the launcher.
3
+ *
4
+ * `template` fields keep the position they have in the template. Fields this
5
+ * module sets that the template does not name are appended, so a product
6
+ * controls key order (and with it the bytes written) through its template.
7
+ */
8
+ import { chmodSync, copyFileSync, writeFileSync } from 'node:fs';
9
+ import { binaryPathInPackage, platformPackageName, } from "./platform.js";
10
+ /**
11
+ * One platform package's package.json: gated by `os` and `cpu`, so npm
12
+ * installs it only on a matching host. `files` defaults to the binary alone;
13
+ * a template's `files` gets the binary added when it lacks it.
14
+ * `preferUnplugged` keeps the binary a real file under Yarn PnP, so the
15
+ * launcher can run it.
16
+ */
17
+ export function platformManifest(product, platform, { version, description, template = {} }) {
18
+ const m = withIdentity(platformPackageName(product, platform), version, description, template);
19
+ m.os = [platform.os];
20
+ m.cpu = [platform.cpu];
21
+ m.files = withFile(m.files, binaryPathInPackage(product, platform), []);
22
+ m.preferUnplugged = true;
23
+ return m;
24
+ }
25
+ /**
26
+ * The launcher package's package.json. Lists every platform package as an
27
+ * optional dependency at the same version, built or not. `files` defaults to
28
+ * the launcher and the README; a template's `files` gets the launcher added
29
+ * when it lacks it. `engines.node` defaults to `>=18`. The launcher is
30
+ * CommonJS, so a template with `"type": "module"` is refused unless
31
+ * `launcherPath` ends in `.cjs`.
32
+ */
33
+ export function launcherManifest(product, platforms, { version, description, launcherPath, template = {} }) {
34
+ if (template.type === 'module' && !launcherPath.endsWith('.cjs')) {
35
+ throw new Error('launcherManifest: the template sets "type": "module", but the launcher is CommonJS; leave "type" out of the launcher template or give launcherPath a .cjs extension');
36
+ }
37
+ const m = withIdentity(product.launcher, version, description, template);
38
+ m.bin = { [product.binary]: launcherPath };
39
+ m.files = withFile(m.files, launcherPath, ['README.md']);
40
+ m.optionalDependencies = Object.fromEntries(platforms.map((p) => [platformPackageName(product, p), version]));
41
+ m.engines ??= { node: '>=18' };
42
+ return m;
43
+ }
44
+ /**
45
+ * The template's fields in order, with `name`, `version` and `description`
46
+ * set from the arguments. An identity field the template names keeps the
47
+ * template's position; one it does not name goes first.
48
+ */
49
+ function withIdentity(name, version, description, template) {
50
+ const identity = { name, version, description };
51
+ const first = Object.fromEntries(Object.entries(identity).filter(([key]) => !Object.hasOwn(template, key)));
52
+ return Object.assign(first, structuredClone(template), identity);
53
+ }
54
+ /**
55
+ * The `files` list with `file` in it: the template's list, plus `file` when no
56
+ * entry names it or a directory that holds it; or `file` and `rest` when the
57
+ * template has no list.
58
+ */
59
+ function withFile(files, file, rest) {
60
+ if (!Array.isArray(files))
61
+ return [file, ...rest];
62
+ const covers = (entry) => typeof entry === 'string' &&
63
+ (entry === file || file.startsWith(`${entry.replace(/\/+$/, '')}/`));
64
+ return files.some(covers) ? files : [...files, file];
65
+ }
66
+ /** Writes `value` as JSON with two-space indent and a final newline, as npm does. */
67
+ export function writeJson(path, value) {
68
+ writeFileSync(path, `${JSON.stringify(value, null, 2)}\n`);
69
+ }
70
+ /** Copies a binary into a package and marks it executable (mode `0o755`). */
71
+ export function copyExecutable(src, dest) {
72
+ copyFileSync(src, dest);
73
+ chmodSync(dest, 0o755);
74
+ }
@@ -0,0 +1,58 @@
1
+ /**
2
+ * The platforms a binary ships for, and the names derived from them.
3
+ */
4
+ /**
5
+ * A platform as npm sees it: an `os` from `process.platform` and a `cpu` from
6
+ * `process.arch`. The common values are named for completion; any other value
7
+ * Node reports, such as `freebsd` or `ia32`, is accepted too.
8
+ */
9
+ export interface NpmPlatform {
10
+ readonly os: 'darwin' | 'linux' | 'win32' | (string & {});
11
+ readonly cpu: 'arm64' | 'x64' | (string & {});
12
+ }
13
+ /**
14
+ * The default platform list, in publish and listing order: macOS on Apple
15
+ * silicon and Intel, Linux on x64 and arm64, and Windows on x64. Linux
16
+ * packages carry no `libc` gate, so one Linux build serves glibc and musl
17
+ * hosts alike: ship a static (musl) build. A product that ships for fewer or
18
+ * more passes its own list.
19
+ */
20
+ export declare const NPM_PLATFORMS: readonly NpmPlatform[];
21
+ /** The names one product ships under. */
22
+ export interface BinaryProduct {
23
+ /** The executable name, on the user's PATH and inside each platform package. */
24
+ readonly binary: string;
25
+ /** The launcher package users install. */
26
+ readonly launcher: string;
27
+ /** The npm scope platform packages are published under, such as `@acme`. */
28
+ readonly scope: string;
29
+ /**
30
+ * Platform packages are `<scope>/<platformPrefix>-<os>-<cpu>`, such as
31
+ * `@acme/tool-linux-x64`. With `''` they are `<scope>/<os>-<cpu>`, the way
32
+ * esbuild names them (`@esbuild/linux-x64`).
33
+ */
34
+ readonly platformPrefix: string;
35
+ /** Directory inside a platform package that holds the binary; `''` is the package root. */
36
+ readonly binaryDir: string;
37
+ }
38
+ /** `darwin-arm64`: the key a platform goes by in directories and in the launcher. */
39
+ export declare function platformKey(p: NpmPlatform): string;
40
+ /**
41
+ * `<scope>/<platformPrefix>-<os>-<cpu>`, e.g. `@acme/tool-linux-x64`, or
42
+ * `<scope>/<os>-<cpu>` when `platformPrefix` is `''`. Throws when `scope` is
43
+ * not an npm scope.
44
+ */
45
+ export declare function platformPackageName(product: BinaryProduct, p: NpmPlatform): string;
46
+ /** The executable's extension, with its dot: `.exe` on Windows, empty elsewhere. */
47
+ export declare function binaryExt(p: Pick<NpmPlatform, 'os'>): string;
48
+ /** The executable's file name on that platform: `tool`, or `tool.exe` on Windows. */
49
+ export declare function binaryFileName(product: BinaryProduct, p: Pick<NpmPlatform, 'os'>): string;
50
+ /** The binary's path inside its platform package, `/`-separated. */
51
+ export declare function binaryPathInPackage(product: BinaryProduct, p: Pick<NpmPlatform, 'os'>): string;
52
+ /** The entry in `platforms` whose key is `key`. Throws, naming the known keys, when none is. */
53
+ export declare function findPlatform<P extends NpmPlatform>(platforms: readonly P[], key: string): P;
54
+ /**
55
+ * The entry for the machine this runs on, from `process.platform` and
56
+ * `process.arch`. Throws when the host is not in `platforms`.
57
+ */
58
+ export declare function hostPlatform<P extends NpmPlatform>(platforms: readonly P[]): P;
@@ -0,0 +1,61 @@
1
+ /**
2
+ * The platforms a binary ships for, and the names derived from them.
3
+ */
4
+ /**
5
+ * The default platform list, in publish and listing order: macOS on Apple
6
+ * silicon and Intel, Linux on x64 and arm64, and Windows on x64. Linux
7
+ * packages carry no `libc` gate, so one Linux build serves glibc and musl
8
+ * hosts alike: ship a static (musl) build. A product that ships for fewer or
9
+ * more passes its own list.
10
+ */
11
+ export const NPM_PLATFORMS = [
12
+ { os: 'darwin', cpu: 'arm64' },
13
+ { os: 'darwin', cpu: 'x64' },
14
+ { os: 'linux', cpu: 'x64' },
15
+ { os: 'linux', cpu: 'arm64' },
16
+ { os: 'win32', cpu: 'x64' },
17
+ ];
18
+ /** `darwin-arm64`: the key a platform goes by in directories and in the launcher. */
19
+ export function platformKey(p) {
20
+ return `${p.os}-${p.cpu}`;
21
+ }
22
+ /**
23
+ * `<scope>/<platformPrefix>-<os>-<cpu>`, e.g. `@acme/tool-linux-x64`, or
24
+ * `<scope>/<os>-<cpu>` when `platformPrefix` is `''`. Throws when `scope` is
25
+ * not an npm scope.
26
+ */
27
+ export function platformPackageName(product, p) {
28
+ if (!/^@[^/@\s]+$/.test(product.scope)) {
29
+ throw new Error(`scope must be an npm scope such as "@acme", got ${JSON.stringify(product.scope)}`);
30
+ }
31
+ const prefix = product.platformPrefix === '' ? '' : `${product.platformPrefix}-`;
32
+ return `${product.scope}/${prefix}${platformKey(p)}`;
33
+ }
34
+ /** The executable's extension, with its dot: `.exe` on Windows, empty elsewhere. */
35
+ export function binaryExt(p) {
36
+ return p.os === 'win32' ? '.exe' : '';
37
+ }
38
+ /** The executable's file name on that platform: `tool`, or `tool.exe` on Windows. */
39
+ export function binaryFileName(product, p) {
40
+ return `${product.binary}${binaryExt(p)}`;
41
+ }
42
+ /** The binary's path inside its platform package, `/`-separated. */
43
+ export function binaryPathInPackage(product, p) {
44
+ const file = binaryFileName(product, p);
45
+ return product.binaryDir === '' ? file : `${product.binaryDir}/${file}`;
46
+ }
47
+ /** The entry in `platforms` whose key is `key`. Throws, naming the known keys, when none is. */
48
+ export function findPlatform(platforms, key) {
49
+ const found = platforms.find((p) => platformKey(p) === key);
50
+ if (!found) {
51
+ throw new Error(`unknown platform "${key}"; known: ${platforms.map(platformKey).join(', ')}`);
52
+ }
53
+ return found;
54
+ }
55
+ /**
56
+ * The entry for the machine this runs on, from `process.platform` and
57
+ * `process.arch`. Throws when the host is not in `platforms`.
58
+ */
59
+ export function hostPlatform(platforms) {
60
+ return findPlatform(platforms, `${process.platform}-${process.arch}`);
61
+ }
@@ -0,0 +1,36 @@
1
+ import { type AsyncCommandRunner, type StreamRunner } from '@osdlc/command-seam';
2
+ /** What {@link publishPackages} did, as `name@version` in publish order. */
3
+ export interface PublishResult {
4
+ /** Published by this run (or, with `dryRun`, that would be). */
5
+ published: string[];
6
+ /** Already on the registry, so not published again. */
7
+ skipped: string[];
8
+ }
9
+ /** Options for {@link publishPackages}. */
10
+ export interface PublishOptions {
11
+ /** The platform package directories, each with its package.json. */
12
+ platformDirs: readonly string[];
13
+ /** The launcher package directory. Published last. */
14
+ launcherDir: string;
15
+ /** Runs `npm publish --dry-run` instead. */
16
+ dryRun?: boolean;
17
+ /** Runs `npm view`. Defaults to the `npm` on `PATH`; a test passes a fake. */
18
+ viewRunner?: AsyncCommandRunner;
19
+ /**
20
+ * Runs `npm publish` with npm's output shown live. Defaults to the `npm` on
21
+ * `PATH`; a test passes a fake.
22
+ */
23
+ publishRunner?: StreamRunner;
24
+ }
25
+ /**
26
+ * Publishes each package with `npm publish` from its directory, the platform
27
+ * packages in order and the launcher last. It first asks the registry
28
+ * (`npm view <name>@<version> version`, on the package's
29
+ * `publishConfig.registry` when it sets one) for every package at once, and
30
+ * skips the ones already there. Throws before publishing anything when a
31
+ * lookup fails for any reason but "not found" (E404), and on the first failed
32
+ * publish. npm uses its own login and each package's `publishConfig`, so set
33
+ * `publishConfig.tag` to publish a prerelease under a tag other than `latest`.
34
+ * Returns which packages were published and which were skipped.
35
+ */
36
+ export declare function publishPackages({ platformDirs, launcherDir, dryRun, viewRunner, publishRunner, }: PublishOptions): Promise<PublishResult>;
@@ -0,0 +1,51 @@
1
+ /**
2
+ * Publish a product's packages: platform packages first, the launcher last, so
3
+ * its optional dependencies already exist on the registry when it lands.
4
+ * A version the registry already has is skipped, so a half-finished run is
5
+ * safe to re-run.
6
+ */
7
+ import { readFileSync } from 'node:fs';
8
+ import { join } from 'node:path';
9
+ import { spawnRunnerAsync, streamRunner, } from '@osdlc/command-seam';
10
+ /**
11
+ * Publishes each package with `npm publish` from its directory, the platform
12
+ * packages in order and the launcher last. It first asks the registry
13
+ * (`npm view <name>@<version> version`, on the package's
14
+ * `publishConfig.registry` when it sets one) for every package at once, and
15
+ * skips the ones already there. Throws before publishing anything when a
16
+ * lookup fails for any reason but "not found" (E404), and on the first failed
17
+ * publish. npm uses its own login and each package's `publishConfig`, so set
18
+ * `publishConfig.tag` to publish a prerelease under a tag other than `latest`.
19
+ * Returns which packages were published and which were skipped.
20
+ */
21
+ export async function publishPackages({ platformDirs, launcherDir, dryRun = false, viewRunner = spawnRunnerAsync('npm'), publishRunner = streamRunner('npm'), }) {
22
+ const packages = await Promise.all([...platformDirs, launcherDir].map(async (dir) => {
23
+ const { name, version, publishConfig } = JSON.parse(readFileSync(join(dir, 'package.json'), 'utf8'));
24
+ // `npm publish` reads publishConfig.registry; `npm view` does not, so ask the same registry.
25
+ const registry = publishConfig?.registry;
26
+ const viewArgv = ['view', `${name}@${version}`, 'version'];
27
+ if (registry !== undefined)
28
+ viewArgv.push('--registry', registry);
29
+ const view = await viewRunner.run(viewArgv, { cwd: dir });
30
+ // E404 means this version (or the whole package) is not there. Any other
31
+ // failure, such as no network or no login, leaves it unknown, so stop.
32
+ if (view.exitCode !== 0 && !view.stderr.includes('E404')) {
33
+ throw new Error(`npm ${viewArgv.join(' ')} failed in ${dir}: ${view.stderr.trim()}`);
34
+ }
35
+ const published = view.exitCode === 0 && view.stdout.trim() === version;
36
+ return { dir, name, version, published };
37
+ }));
38
+ const argv = ['publish', ...(dryRun ? ['--dry-run'] : [])];
39
+ const result = { published: [], skipped: [] };
40
+ for (const { dir, name, version, published } of packages) {
41
+ if (published) {
42
+ result.skipped.push(`${name}@${version}`);
43
+ continue;
44
+ }
45
+ const run = publishRunner.run(argv, { cwd: dir });
46
+ if (run.exitCode !== 0)
47
+ throw new Error(`npm ${argv.join(' ')} failed in ${dir}`);
48
+ result.published.push(`${name}@${version}`);
49
+ }
50
+ return result;
51
+ }
package/package.json CHANGED
@@ -1,6 +1,73 @@
1
1
  {
2
2
  "name": "@osdlc/npm-binary",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.0.1-stage",
4
+ "description": "Ship a compiled binary through npm: one launcher package plus one os/cpu-gated package per platform, selected through optionalDependencies. Platform names, the two package.json shapes, a dependency-free Node launcher shim, platform-first publishing and the cargo target-dir lookup.",
5
+ "license": "MIT OR Apache-2.0",
6
+ "author": "sksizer",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/osdlc/osdlc.git",
10
+ "directory": "packages/ts/npm-binary"
11
+ },
12
+ "homepage": "https://github.com/osdlc/osdlc/tree/main/packages/ts/npm-binary#readme",
13
+ "bugs": "https://github.com/osdlc/osdlc/issues",
14
+ "keywords": [
15
+ "npm",
16
+ "binary",
17
+ "native",
18
+ "optionalDependencies",
19
+ "platform-packages",
20
+ "launcher",
21
+ "cli",
22
+ "cargo",
23
+ "rust",
24
+ "distribution"
25
+ ],
26
+ "publishConfig": {
27
+ "access": "public"
28
+ },
29
+ "type": "module",
30
+ "sideEffects": false,
31
+ "engines": {
32
+ "node": ">=22"
33
+ },
34
+ "exports": {
35
+ ".": {
36
+ "types": "./dist/index.d.ts",
37
+ "default": "./dist/index.js"
38
+ }
39
+ },
40
+ "files": [
41
+ "dist/",
42
+ "README.md",
43
+ "CHANGELOG.md",
44
+ "LICENSE-MIT",
45
+ "LICENSE-APACHE",
46
+ "SECURITY.md",
47
+ "CONTRIBUTING.md"
48
+ ],
49
+ "dependencies": {
50
+ "@osdlc/command-seam": "^0.14.0"
51
+ },
52
+ "devDependencies": {
53
+ "@types/node": "^26.1.0",
54
+ "@vitest/coverage-v8": "^5.0.5",
55
+ "oxlint": "^1.65.0",
56
+ "prettier": "3.9.6",
57
+ "typescript": "~6.0.3",
58
+ "vitest": "^5.0.5",
59
+ "@osdlc/tsconfig": "^0.4.1",
60
+ "@osdlc/prettier-config": "^0.3.1"
61
+ },
62
+ "scripts": {
63
+ "build": "tsc -p tsconfig.build.json && node -e \"require('node:fs').copyFileSync('src/launcher-template.cjs', 'dist/launcher-template.cjs')\"",
64
+ "clean": "node -e \"require('node:fs').rmSync('dist', { recursive: true, force: true })\"",
65
+ "test": "vitest run",
66
+ "coverage": "vitest run --coverage",
67
+ "smoke": "node tests/smoke.mjs",
68
+ "format": "prettier --write .",
69
+ "format:check": "prettier --check .",
70
+ "lint": "oxlint .",
71
+ "typecheck": "tsc --noEmit && tsc -p tsconfig.build.json --noEmit"
72
+ }
6
73
  }