@efolusi/meridian-cli 0.0.0-stage → 1.22.0

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/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 Efolusi
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,134 @@
1
- # Temporary Holding Version
1
+ # Meridian CLI
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
+ Copies Meridian components into your project as source you own: the `.jsx`
4
+ file, its `.d.ts` types and its `.prompt.md` usage notes, plus every Meridian
5
+ item it imports. Files come from the public registry at
6
+ `https://meridian.efolusi.com/site/registry/`.
7
+
8
+ The CLI has no runtime dependencies. It needs Node.js 20.10 or newer.
9
+
10
+ ## Usage
11
+
12
+ ```sh
13
+ npx @efolusi/meridian-cli add button
14
+ npx @efolusi/meridian-cli add dialog tabs --dir src/ui
15
+ npx @efolusi/meridian-cli list
16
+ ```
17
+
18
+ Installed as a development dependency, the command is `meridian`:
19
+
20
+ ```sh
21
+ npm install --save-dev @efolusi/meridian-cli
22
+ npx meridian add button --dry-run
23
+ ```
24
+
25
+ `add` reads each item's `registryDependencies` and adds those items too, so
26
+ `add button` also writes the shared stylesheet and tokens (`meridian-base`) and
27
+ `Icon`. Files keep their registry paths under `--dir`, for example
28
+ `components/forms/Button.jsx`, because the components import each other by
29
+ relative path. When it finishes, `add` prints the npm packages the files
30
+ import. It does not run `npm install` for you.
31
+
32
+ Import `styles.css` once, from your app's entry or root layout.
33
+
34
+ Two files differ from the repository so they work in a bundled app.
35
+ `components/icons/Icon.jsx` reads every glyph from the generated
36
+ `components/icons/_svg.js` instead of fetching SVG files. `tokens/fonts.css`
37
+ loads the brand fonts from the published `@efolusi/meridian-tokens` package
38
+ on jsDelivr, pinned to the release. To self-host the fonts, copy that package's
39
+ `assets/fonts/` into your app and change the `url()`s.
40
+
41
+ ### Server-rendered apps
42
+
43
+ Components add their CSS to the page when they render in the browser, so
44
+ server-rendered HTML (Next.js, Remix, Vite SSR) has none until it hydrates.
45
+ Add the static component stylesheet once and import it right after
46
+ `styles.css`:
47
+
48
+ ```sh
49
+ npx meridian add meridian-ssr-css
50
+ ```
51
+
52
+ ```js
53
+ import './styles.css';
54
+ import './components.css';
55
+ ```
56
+
57
+ Components skip CSS this sheet already carries, matched by a hash of the
58
+ exact rules, so nothing is added twice. A component you edit, or one copied
59
+ from a newer release, adds its own CSS as before, so an older
60
+ `components.css` never overrides it. Nothing depends on this item, so other
61
+ `add` commands never touch it; re-add it with `--overwrite` after upgrading.
62
+
63
+ ## Options
64
+
65
+ | Option | Effect |
66
+ |---|---|
67
+ | `--registry <url\|dir>` | Where to read items. An `http://` or `https://` URL of the folder that holds `<name>.json`, or a local directory with the same layout. Default: the hosted registry. |
68
+ | `--dir <path>` | Where files are written. Default: the current directory. |
69
+ | `--dry-run` | Print what `add` would write and write nothing. |
70
+ | `--overwrite` | Replace files that exist with different content. |
71
+ | `-h`, `--help` | Show help. |
72
+ | `-v`, `--version` | Show the CLI version. |
73
+
74
+ `list` reads the index `registry.json` that sits next to the item folder
75
+ (`/site/registry.json` on the hosted site). A local directory without that file
76
+ is listed by reading its items.
77
+
78
+ To work offline, point `--registry` at a checkout of the Meridian repository:
79
+
80
+ ```sh
81
+ npx @efolusi/meridian-cli add button --registry ../meridian/site/registry
82
+ ```
83
+
84
+ ## Existing files
85
+
86
+ By default `add` writes nothing if any file it needs already exists with
87
+ different content. It lists those files and exits with code `1`. A file that
88
+ already has the same content is reported as `unchanged` and left alone. Pass
89
+ `--overwrite` to replace the differing files, or `--dir` to write somewhere
90
+ else.
91
+
92
+ ## Exit codes
93
+
94
+ | Code | Meaning |
95
+ |---|---|
96
+ | `0` | Done (or the dry run finished). |
97
+ | `1` | Files exist with different content. Nothing was written. |
98
+ | `2` | Usage error: unknown command or option, missing item name, unsupported `--registry` scheme. |
99
+ | `3` | Registry error: unreachable, item not found, invalid JSON, or an item with unsafe content. |
100
+ | `4` | File system error, or a target that would leave `--dir` through a symlink. |
101
+
102
+ ## What the CLI refuses
103
+
104
+ The CLI treats registry JSON as untrusted input. It stops with an error, and
105
+ writes nothing, when:
106
+
107
+ - an item name is anything other than lowercase letters, digits and hyphens;
108
+ - a file target is absolute, starts with a drive letter, contains `..`, `.`,
109
+ an empty segment, a backslash, or a control character such as NUL;
110
+ - a folder or file name in a target uses anything other than ASCII letters,
111
+ digits and `. _ @ + -` (this rules out `%2e%2e`, lookalike dots and slashes,
112
+ bidi and zero-width characters, and `:`), ends in `.`, is `.git`, or is a
113
+ Windows device name such as `nul` or `com1`;
114
+ - a target would resolve outside `--dir`, including through a symlinked folder
115
+ inside it, or the target file is itself a symlink (writes also open the file
116
+ with `O_NOFOLLOW`, so a link swapped in after the check fails the write);
117
+ - an item names itself differently from the file it came from, or lists an
118
+ npm dependency that is not a plain package name;
119
+ - a `registryDependencies` URL points anywhere other than the registry in use or
120
+ Meridian's hosted registry;
121
+ - two items write the same path with different content;
122
+ - a response is larger than 4 MiB, or a server redirects to a different origin.
123
+ Same-origin redirects are followed, up to five.
124
+
125
+ `--registry` accepts only `http://`, `https://` or a local directory.
126
+
127
+ Registry text that reaches your terminal (`list` descriptions, error messages)
128
+ has control, bidi and zero-width characters replaced with spaces. In the
129
+ printed `npm install` line, a version range with shell operators such as
130
+ `>=1 <2` is wrapped in double quotes.
131
+
132
+ ## License
133
+
134
+ Apache-2.0. Copied component files are yours to edit; keep the license notice.
@@ -0,0 +1,15 @@
1
+ #!/usr/bin/env node
2
+ import { main } from '../src/cli.mjs';
3
+
4
+ // `meridian list | head` closes the pipe early; that is not an error.
5
+ process.stdout.on('error', error => {
6
+ if (error.code === 'EPIPE') process.exit(0);
7
+ throw error;
8
+ });
9
+
10
+ main(process.argv.slice(2)).then(code => {
11
+ process.exitCode = code;
12
+ }, error => {
13
+ process.stderr.write(`meridian: ${error.message}\n`);
14
+ process.exitCode = 4;
15
+ });
package/package.json CHANGED
@@ -1,6 +1,37 @@
1
1
  {
2
2
  "name": "@efolusi/meridian-cli",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.22.0",
4
+ "description": "Copy Meridian design system components, types and usage notes into your project from the registry.",
5
+ "license": "Apache-2.0",
6
+ "homepage": "https://meridian.efolusi.com",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/efolusi/meridian.git",
10
+ "directory": "packages/cli"
11
+ },
12
+ "type": "module",
13
+ "engines": {
14
+ "node": ">=20.10"
15
+ },
16
+ "bin": {
17
+ "meridian": "bin/meridian.js"
18
+ },
19
+ "main": "./src/index.mjs",
20
+ "exports": {
21
+ ".": "./src/index.mjs",
22
+ "./package.json": "./package.json"
23
+ },
24
+ "files": [
25
+ "bin",
26
+ "src",
27
+ "README.md",
28
+ "LICENSE"
29
+ ],
30
+ "keywords": [
31
+ "design-system",
32
+ "cli",
33
+ "registry",
34
+ "meridian",
35
+ "react"
36
+ ]
37
+ }
package/src/cli.mjs ADDED
@@ -0,0 +1,187 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { DiskError, UnsafeError } from './paths.mjs';
4
+ import { DEFAULT_REGISTRY, openRegistry, RegistryError } from './registry.mjs';
5
+ import { npmDependencies, resolveItems } from './resolve.mjs';
6
+ import { applyPlan, planWrites } from './write.mjs';
7
+
8
+ export const EXIT = Object.freeze({
9
+ OK: 0,
10
+ CONFLICT: 1,
11
+ USAGE: 2,
12
+ REGISTRY: 3,
13
+ DISK: 4,
14
+ });
15
+
16
+ const HELP = `meridian: copy Meridian components into your project
17
+
18
+ Usage:
19
+ meridian add <name...> [options] copy items and the items they depend on
20
+ meridian list [options] show every item with a one-line description
21
+
22
+ Options:
23
+ --registry <url|dir> registry folder (default ${DEFAULT_REGISTRY})
24
+ an http(s) URL or a local directory of <name>.json items
25
+ --dir <path> where files are written (default: current directory)
26
+ --dry-run show what add would write, write nothing
27
+ --overwrite replace files that exist with different content
28
+ -h, --help show this help
29
+ -v, --version show the CLI version
30
+
31
+ Exit codes:
32
+ 0 done
33
+ 1 files already exist with different content; nothing was written
34
+ 2 usage error
35
+ 3 registry error: unreachable, item not found, or unsafe item content
36
+ 4 file system error, or a target that leaves --dir through a symlink
37
+
38
+ add does not run npm install. It prints the packages to install.
39
+ `;
40
+
41
+ class UsageError extends Error {}
42
+
43
+ function parseArgs(argv) {
44
+ const options = { names: [], registry: DEFAULT_REGISTRY, dir: '.', dryRun: false, overwrite: false };
45
+ const takeValue = (flag, index) => {
46
+ const value = argv[index + 1];
47
+ if (value === undefined || value.startsWith('-')) throw new UsageError(`${flag} needs a value`);
48
+ return value;
49
+ };
50
+ for (let index = 0; index < argv.length; index += 1) {
51
+ const arg = argv[index];
52
+ if (arg === '-h' || arg === '--help') return { help: true };
53
+ if (arg === '-v' || arg === '--version') return { version: true };
54
+ if (arg === '--dry-run') options.dryRun = true;
55
+ else if (arg === '--overwrite') options.overwrite = true;
56
+ else if (arg === '--registry' || arg === '--dir') {
57
+ options[arg.slice(2)] = takeValue(arg, index);
58
+ index += 1;
59
+ } else if (arg.startsWith('--registry=')) options.registry = arg.slice('--registry='.length);
60
+ else if (arg.startsWith('--dir=')) options.dir = arg.slice('--dir='.length);
61
+ else if (arg.startsWith('-')) throw new UsageError(`unknown option ${arg}`);
62
+ else if (!options.command) options.command = arg;
63
+ else options.names.push(arg);
64
+ }
65
+ if (!options.registry) throw new UsageError('--registry needs a value');
66
+ if (!options.dir) throw new UsageError('--dir needs a value');
67
+ if (!options.command) return { help: true, missing: true };
68
+ if (options.command === 'ls') options.command = 'list';
69
+ if (options.command !== 'add' && options.command !== 'list') throw new UsageError(`unknown command ${options.command}`);
70
+ if (options.command === 'add' && options.names.length === 0) throw new UsageError('add needs at least one item name, for example: meridian add button');
71
+ if (options.command === 'list' && options.names.length) throw new UsageError('list takes no item names');
72
+ if (!/^https?:\/\//i.test(options.registry) && /^[a-z][a-z0-9+.-]+:/i.test(options.registry)) {
73
+ throw new UsageError(`--registry must be an http(s) URL or a local directory, not ${JSON.stringify(options.registry)}`);
74
+ }
75
+ return options;
76
+ }
77
+
78
+ function version() {
79
+ const pkg = JSON.parse(fs.readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
80
+ return pkg.version;
81
+ }
82
+
83
+ /**
84
+ * Registry text shown in a terminal: one line, no control characters, and
85
+ * no bidi or zero-width characters that could make it read differently.
86
+ */
87
+ function plain(text) {
88
+ return String(text)
89
+ .replace(/[\u0000-\u001f\u007f-\u009f​-‏‪-‮⁠-⁩]+/g, ' ')
90
+ .replace(/\s+/g, ' ')
91
+ .trim();
92
+ }
93
+
94
+ /**
95
+ * An npm spec for the printed install command. Ranges such as `>=1 <2` hold
96
+ * characters a shell treats as operators, so those specs are double-quoted;
97
+ * the spec pattern already excludes `"`, `$`, backtick, `\`, `!` and `%`.
98
+ */
99
+ function shellArg(spec) {
100
+ // '^' is quoted too: cmd.exe treats it as an escape and drops it unquoted.
101
+ return /^[A-Za-z0-9@/._~=+-]+$/.test(spec) ? spec : `"${spec}"`;
102
+ }
103
+
104
+ async function list(options, io) {
105
+ const registry = await openRegistry(options.registry, { fetchImpl: io.fetchImpl });
106
+ const items = await registry.index();
107
+ const width = Math.min(32, Math.max(0, ...items.map(item => item.name.length)));
108
+ for (const item of items) io.stdout.write(`${item.name.padEnd(width)} ${plain(item.description)}\n`);
109
+ return EXIT.OK;
110
+ }
111
+
112
+ async function add(options, io) {
113
+ const registry = await openRegistry(options.registry, { fetchImpl: io.fetchImpl });
114
+ const dir = path.resolve(io.cwd, options.dir);
115
+ const items = await resolveItems(options.names, registry);
116
+ const plan = await planWrites(items, dir, { overwrite: options.overwrite });
117
+ const out = line => io.stdout.write(`${line}\n`);
118
+
119
+ out(`Items: ${items.map(item => item.name).join(', ')}`);
120
+ out(`Target: ${dir}`);
121
+
122
+ const conflicts = plan.filter(entry => entry.status === 'conflict');
123
+ if (conflicts.length) {
124
+ io.stderr.write(`${conflicts.length} file(s) already exist with different content:\n`);
125
+ for (const entry of conflicts) io.stderr.write(` ${entry.target}\n`);
126
+ io.stderr.write('Nothing was written. Pass --overwrite to replace them, or --dir to write somewhere else.\n');
127
+ return EXIT.CONFLICT;
128
+ }
129
+
130
+ const verb = { create: options.dryRun ? 'would create' : 'created', overwrite: options.dryRun ? 'would replace' : 'replaced', unchanged: 'unchanged' };
131
+ const width = Math.max(...Object.values(verb).map(word => word.length));
132
+ if (!options.dryRun) {
133
+ try {
134
+ await applyPlan(plan, dir);
135
+ } catch (error) {
136
+ // Say what is already on disk, so a half-finished run is not a mystery.
137
+ for (const entry of error.written ?? []) out(` ${verb[entry.status].padEnd(width)} ${entry.target}`);
138
+ if (error.written?.length) out(`${error.written.length} file(s) were written before the error. Fix it and run add again; written files then show as unchanged.`);
139
+ throw error;
140
+ }
141
+ }
142
+ for (const entry of plan) out(` ${verb[entry.status].padEnd(width)} ${entry.target}`);
143
+
144
+ const changed = plan.filter(entry => entry.status !== 'unchanged').length;
145
+ out(options.dryRun ? `Dry run: ${changed} file(s) would be written. Nothing was written.` : `${changed} file(s) written, ${plan.length - changed} unchanged.`);
146
+
147
+ const packages = npmDependencies(items);
148
+ if (packages.length) {
149
+ out('These files import npm packages. Install them if your project does not have them yet:');
150
+ out(` npm install ${packages.map(shellArg).join(' ')}`);
151
+ }
152
+ return EXIT.OK;
153
+ }
154
+
155
+ /** Runs the CLI and resolves to its exit code. */
156
+ export async function main(argv, io = {}) {
157
+ const env = {
158
+ stdout: io.stdout ?? process.stdout,
159
+ stderr: io.stderr ?? process.stderr,
160
+ cwd: io.cwd ?? process.cwd(),
161
+ fetchImpl: io.fetchImpl ?? globalThis.fetch,
162
+ };
163
+ let options;
164
+ try {
165
+ options = parseArgs(argv);
166
+ } catch (error) {
167
+ if (!(error instanceof UsageError)) throw error;
168
+ env.stderr.write(`meridian: ${error.message}\nRun meridian --help for usage.\n`);
169
+ return EXIT.USAGE;
170
+ }
171
+ if (options.help) {
172
+ (options.missing ? env.stderr : env.stdout).write(HELP);
173
+ return options.missing ? EXIT.USAGE : EXIT.OK;
174
+ }
175
+ if (options.version) {
176
+ env.stdout.write(`${version()}\n`);
177
+ return EXIT.OK;
178
+ }
179
+ try {
180
+ return options.command === 'list' ? await list(options, env) : await add(options, env);
181
+ } catch (error) {
182
+ // Messages can quote registry text, so they get the same cleanup as list.
183
+ env.stderr.write(`meridian: ${plain(error.message)}\n`);
184
+ if (error instanceof RegistryError || error instanceof UnsafeError) return EXIT.REGISTRY;
185
+ return EXIT.DISK;
186
+ }
187
+ }
package/src/index.mjs ADDED
@@ -0,0 +1,5 @@
1
+ export { main, EXIT } from './cli.mjs';
2
+ export { checkTarget, resolveInside, assertItemName, UnsafeError, DiskError } from './paths.mjs';
3
+ export { openRegistry, parseItem, dependencyName, DEFAULT_REGISTRY, RegistryError } from './registry.mjs';
4
+ export { resolveItems, npmDependencies } from './resolve.mjs';
5
+ export { planWrites, applyPlan } from './write.mjs';
package/src/paths.mjs ADDED
@@ -0,0 +1,137 @@
1
+ import { realpath as realpathCallback } from 'node:fs';
2
+ import fs from 'node:fs/promises';
3
+ import path from 'node:path';
4
+ import { promisify } from 'node:util';
5
+
6
+ // Registry JSON is untrusted input: an item name becomes part of a URL or a
7
+ // file name, and a file target becomes a path on the user's disk. Everything
8
+ // that reaches the file system goes through the checks in this module.
9
+
10
+ const ITEM_NAME = /^[a-z0-9][a-z0-9-]{0,99}$/;
11
+ const SEGMENT = /^[A-Za-z0-9._@+-]+$/;
12
+ const WINDOWS_DEVICE = /^(con|prn|aux|nul|com[0-9]|lpt[0-9])(\.|$)/i;
13
+
14
+ /** Throws unless `name` is a plain registry item name such as `button`. */
15
+ export function assertItemName(name) {
16
+ if (typeof name !== 'string' || !ITEM_NAME.test(name)) {
17
+ throw new UnsafeError(`invalid item name ${JSON.stringify(name)}: use lowercase letters, digits and hyphens`);
18
+ }
19
+ return name;
20
+ }
21
+
22
+ /**
23
+ * Checks a file target from a registry item and returns it in normalised
24
+ * POSIX form. Rejects anything that could land outside the target directory
25
+ * before the disk is consulted: absolute paths, drive letters, backslashes,
26
+ * NUL and other control characters, `.` or `..` segments, any character
27
+ * outside `A-Za-z0-9._@+-`, names ending in `.`, `.git`, and Windows device
28
+ * names such as `nul`.
29
+ */
30
+ export function checkTarget(target) {
31
+ if (typeof target !== 'string' || target.length === 0 || target.length > 400) {
32
+ throw new UnsafeError(`invalid file target ${JSON.stringify(target)}`);
33
+ }
34
+ if (/[\u0000-\u001f\u007f]/.test(target)) throw new UnsafeError(`file target contains a control character: ${JSON.stringify(target)}`);
35
+ if (target.includes('\\')) throw new UnsafeError(`file target contains a backslash: ${JSON.stringify(target)}`);
36
+ if (target.startsWith('/') || /^[a-zA-Z]:/.test(target)) {
37
+ throw new UnsafeError(`file target is absolute: ${JSON.stringify(target)}`);
38
+ }
39
+ const segments = target.split('/');
40
+ for (const segment of segments) {
41
+ if (segment === '..' || segment === '.' || segment === '') {
42
+ throw new UnsafeError(`file target has an empty, "." or ".." segment: ${JSON.stringify(target)}`);
43
+ }
44
+ // ASCII only: no lookalike dots or slashes, no bidi or zero-width
45
+ // characters, no `%` escapes, no `:` (an NTFS stream or drive).
46
+ if (!SEGMENT.test(segment)) {
47
+ throw new UnsafeError(`file target may only use A-Z a-z 0-9 . _ @ + - in each folder or file name: ${JSON.stringify(target)}`);
48
+ }
49
+ // Windows drops trailing dots, so `...` or `x.` would not name what it seems to.
50
+ if (segment.endsWith('.')) throw new UnsafeError(`file target has a name ending in ".": ${JSON.stringify(target)}`);
51
+ if (segment.toLowerCase() === '.git') throw new UnsafeError(`file target writes into .git: ${JSON.stringify(target)}`);
52
+ if (WINDOWS_DEVICE.test(segment)) throw new UnsafeError(`file target uses a Windows device name: ${JSON.stringify(target)}`);
53
+ }
54
+ return segments.join('/');
55
+ }
56
+
57
+ function isInside(root, candidate) {
58
+ const rel = path.relative(root, candidate);
59
+ // A real parent step is '..' alone or followed by a separator; '..foo' is a
60
+ // folder name inside root.
61
+ return rel === '' || (rel !== '..' && !rel.startsWith(`..${path.sep}`) && !path.isAbsolute(rel));
62
+ }
63
+
64
+ // The native realpath fails with EISDIR on Windows volumes whose driver lacks
65
+ // GetFinalPathNameByHandle (RAM disks, some virtual and network drives). The JS
66
+ // implementation walks the path with lstat and readlink and works there.
67
+ const jsRealpath = promisify(realpathCallback);
68
+ async function realpath(p) {
69
+ try {
70
+ return await fs.realpath(p);
71
+ } catch (error) {
72
+ if (process.platform === 'win32' && (error.code === 'EISDIR' || error.code === 'EINVAL')) return jsRealpath(p);
73
+ throw error;
74
+ }
75
+ }
76
+
77
+ /**
78
+ * Resolves a checked target under `dir` and confirms that writing it stays
79
+ * inside `dir` on disk: the deepest existing ancestor must resolve (through
80
+ * any symlinks) to a place inside the real `dir`, and the file itself must
81
+ * not be a symlink. Returns the absolute path to write.
82
+ */
83
+ export async function resolveInside(dir, target) {
84
+ const rel = checkTarget(target);
85
+ const root = path.resolve(dir);
86
+ const absolute = path.resolve(root, ...rel.split('/'));
87
+ if (!isInside(root, absolute) || absolute === root) {
88
+ throw new UnsafeError(`file target resolves outside ${root}: ${JSON.stringify(target)}`);
89
+ }
90
+
91
+ let realRoot;
92
+ try {
93
+ realRoot = await realpath(root);
94
+ } catch (error) {
95
+ if (error.code !== 'ENOENT') throw error;
96
+ // The directory does not exist yet, so nothing under it can be a link.
97
+ return absolute;
98
+ }
99
+
100
+ try {
101
+ const stat = await fs.lstat(absolute);
102
+ if (stat.isSymbolicLink()) throw new DiskError(`refusing to write through a symlink: ${absolute}`);
103
+ if (!stat.isFile()) throw new DiskError(`target exists and is not a regular file: ${absolute}`);
104
+ } catch (error) {
105
+ if (error.code !== 'ENOENT') throw error;
106
+ }
107
+
108
+ let probe = path.dirname(absolute);
109
+ for (;;) {
110
+ try {
111
+ const real = await realpath(probe);
112
+ if (!isInside(realRoot, real)) {
113
+ throw new DiskError(`file target resolves outside ${root} through a symlink: ${JSON.stringify(target)}`);
114
+ }
115
+ return absolute;
116
+ } catch (error) {
117
+ if (error.code !== 'ENOENT') throw error;
118
+ probe = path.dirname(probe);
119
+ }
120
+ }
121
+ }
122
+
123
+ /** Registry content that must not be acted on. */
124
+ export class UnsafeError extends Error {
125
+ constructor(message) {
126
+ super(message);
127
+ this.name = 'UnsafeError';
128
+ }
129
+ }
130
+
131
+ /** The target directory on disk would send a write somewhere unsafe. */
132
+ export class DiskError extends Error {
133
+ constructor(message) {
134
+ super(message);
135
+ this.name = 'DiskError';
136
+ }
137
+ }
@@ -0,0 +1,252 @@
1
+ import fs from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import { assertItemName, checkTarget, UnsafeError } from './paths.mjs';
4
+
5
+ export const DEFAULT_REGISTRY = 'https://meridian.efolusi.com/site/registry/';
6
+ export const MAX_RESPONSE_BYTES = 4 * 1024 * 1024;
7
+ const MAX_REDIRECTS = 5;
8
+ const TIMEOUT_MS = 30_000;
9
+
10
+ /** The registry could not be read, or an item was not in it. */
11
+ export class RegistryError extends Error {
12
+ constructor(message) {
13
+ super(message);
14
+ this.name = 'RegistryError';
15
+ }
16
+ }
17
+
18
+ /**
19
+ * Opens a registry from `--registry`: an http(s) URL of the folder that holds
20
+ * `<name>.json` items, or a local directory with the same layout. The index
21
+ * used by `list` is `registry.json` next to that folder, which is how the
22
+ * hosted site lays it out (`/site/registry.json` beside `/site/registry/`).
23
+ */
24
+ export async function openRegistry(location = DEFAULT_REGISTRY, { fetchImpl = globalThis.fetch } = {}) {
25
+ if (typeof location !== 'string' || location.length === 0) throw new RegistryError('--registry needs a URL or a directory');
26
+ if (/^https?:\/\//i.test(location)) {
27
+ const base = new URL(location.endsWith('/') ? location : `${location}/`);
28
+ if (base.username || base.password) throw new RegistryError('--registry URL must not carry credentials');
29
+ return httpRegistry(base, fetchImpl);
30
+ }
31
+ // Any other scheme (file:, ftp:, data:, ...). One letter is a Windows drive.
32
+ if (/^[a-z][a-z0-9+.-]+:/i.test(location)) {
33
+ throw new RegistryError(`unsupported --registry ${JSON.stringify(location)}: use an http(s) URL or a local directory`);
34
+ }
35
+ const dir = path.resolve(location);
36
+ let stat;
37
+ try {
38
+ stat = await fs.stat(dir);
39
+ } catch {
40
+ throw new RegistryError(`registry directory not found: ${dir}`);
41
+ }
42
+ if (!stat.isDirectory()) throw new RegistryError(`--registry is not a directory: ${dir}`);
43
+ return localRegistry(dir);
44
+ }
45
+
46
+ function httpRegistry(base, fetchImpl) {
47
+ if (typeof fetchImpl !== 'function') throw new RegistryError('this Node.js has no global fetch; use Node.js 20.10 or newer');
48
+ return {
49
+ kind: 'url',
50
+ location: base.href,
51
+ base,
52
+ async item(name) {
53
+ assertItemName(name);
54
+ const url = new URL(`${name}.json`, base);
55
+ const text = await fetchText(url, fetchImpl, { notFound: () => new RegistryError(`"${name}" is not in the registry at ${base.href}`) });
56
+ return parseItem(text, name, url.href);
57
+ },
58
+ async index() {
59
+ const url = new URL('../registry.json', base);
60
+ const text = await fetchText(url, fetchImpl, { notFound: () => new RegistryError(`no registry index at ${url.href}`) });
61
+ return parseIndex(text, url.href);
62
+ },
63
+ };
64
+ }
65
+
66
+ function localRegistry(dir) {
67
+ return {
68
+ kind: 'dir',
69
+ location: dir,
70
+ base: null,
71
+ async item(name) {
72
+ assertItemName(name);
73
+ const file = path.join(dir, `${name}.json`);
74
+ const text = await readLocal(file, () => new RegistryError(`"${name}" is not in the registry at ${dir}`));
75
+ return parseItem(text, name, file);
76
+ },
77
+ async index() {
78
+ const file = path.join(path.dirname(dir), 'registry.json');
79
+ const hasIndex = await fs.stat(file).then(stat => stat.isFile(), () => false);
80
+ if (hasIndex) return parseIndex(await readLocal(file, () => new RegistryError(`no registry index at ${file}`)), file);
81
+ // No index beside the folder: read the items themselves.
82
+ const names = (await fs.readdir(dir))
83
+ .filter(entry => entry.endsWith('.json'))
84
+ .map(entry => entry.slice(0, -'.json'.length))
85
+ .filter(name => /^[a-z0-9][a-z0-9-]{0,99}$/.test(name))
86
+ .sort();
87
+ const items = [];
88
+ for (const name of names) {
89
+ const item = await this.item(name);
90
+ items.push({ name: item.name, type: item.type, description: item.description });
91
+ }
92
+ return items;
93
+ },
94
+ };
95
+ }
96
+
97
+ async function readLocal(file, notFound) {
98
+ let stat;
99
+ try {
100
+ stat = await fs.stat(file);
101
+ } catch (error) {
102
+ if (error.code === 'ENOENT') throw notFound();
103
+ throw new RegistryError(`cannot read ${file}: ${error.message}`);
104
+ }
105
+ if (!stat.isFile()) throw new RegistryError(`${file} is not a file`);
106
+ if (stat.size > MAX_RESPONSE_BYTES) throw new RegistryError(`${file} is larger than ${MAX_RESPONSE_BYTES} bytes`);
107
+ return fs.readFile(file, 'utf8');
108
+ }
109
+
110
+ /**
111
+ * GET with manual redirects: a redirect to the same origin is followed, a
112
+ * redirect anywhere else stops with an error naming the destination. The body
113
+ * is read in chunks and abandoned once it passes MAX_RESPONSE_BYTES.
114
+ */
115
+ export async function fetchText(url, fetchImpl, { notFound } = {}) {
116
+ let current = url;
117
+ for (let hop = 0; hop <= MAX_REDIRECTS; hop += 1) {
118
+ let response;
119
+ try {
120
+ response = await fetchImpl(current, {
121
+ redirect: 'manual',
122
+ headers: { accept: 'application/json' },
123
+ signal: AbortSignal.timeout(TIMEOUT_MS),
124
+ });
125
+ } catch (error) {
126
+ throw new RegistryError(`cannot reach ${current.href}: ${error.cause?.message ?? error.message}`);
127
+ }
128
+ if (response.status >= 300 && response.status < 400) {
129
+ const location = response.headers.get('location');
130
+ if (!location) throw new RegistryError(`${current.href} redirected without a Location header`);
131
+ const next = new URL(location, current);
132
+ if (next.origin !== url.origin) {
133
+ throw new RegistryError(`${current.href} redirects to another origin (${next.origin}); pass that URL with --registry if you trust it`);
134
+ }
135
+ current = next;
136
+ continue;
137
+ }
138
+ if (response.status === 404 && notFound) throw notFound();
139
+ if (!response.ok) throw new RegistryError(`${current.href} answered HTTP ${response.status}`);
140
+ return readCapped(response, current.href);
141
+ }
142
+ throw new RegistryError(`${url.href} redirected more than ${MAX_REDIRECTS} times`);
143
+ }
144
+
145
+ async function readCapped(response, label) {
146
+ const declared = Number(response.headers.get('content-length'));
147
+ if (Number.isFinite(declared) && declared > MAX_RESPONSE_BYTES) {
148
+ throw new RegistryError(`${label} is larger than ${MAX_RESPONSE_BYTES} bytes`);
149
+ }
150
+ if (!response.body) return '';
151
+ const reader = response.body.getReader();
152
+ const chunks = [];
153
+ let total = 0;
154
+ for (;;) {
155
+ const { done, value } = await reader.read();
156
+ if (done) break;
157
+ total += value.byteLength;
158
+ if (total > MAX_RESPONSE_BYTES) {
159
+ await reader.cancel().catch(() => {});
160
+ throw new RegistryError(`${label} is larger than ${MAX_RESPONSE_BYTES} bytes`);
161
+ }
162
+ chunks.push(value);
163
+ }
164
+ return Buffer.concat(chunks).toString('utf8');
165
+ }
166
+
167
+ function parseJson(text, label) {
168
+ try {
169
+ return JSON.parse(text);
170
+ } catch {
171
+ throw new RegistryError(`${label} is not valid JSON`);
172
+ }
173
+ }
174
+
175
+ const NPM_SPEC = /^(@[a-z0-9][a-z0-9._~-]*\/)?[a-z0-9][a-z0-9._~-]*(@[A-Za-z0-9.^~<>=| *+-]+)?$/;
176
+
177
+ /**
178
+ * Validates one registry item and returns only the fields the CLI uses.
179
+ * Unknown fields are ignored; anything malformed in a used field rejects the
180
+ * whole item.
181
+ */
182
+ export function parseItem(text, expectedName, label = expectedName) {
183
+ const raw = parseJson(text, label);
184
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) throw new UnsafeError(`${label} is not a registry item`);
185
+ if (raw.name !== expectedName) throw new UnsafeError(`${label} names itself ${JSON.stringify(raw.name)}, expected "${expectedName}"`);
186
+ const files = raw.files ?? [];
187
+ if (!Array.isArray(files)) throw new UnsafeError(`${label}: files must be an array`);
188
+ const parsedFiles = files.map((file, index) => {
189
+ if (!file || typeof file !== 'object') throw new UnsafeError(`${label}: files[${index}] is not an object`);
190
+ if (typeof file.content !== 'string') throw new UnsafeError(`${label}: files[${index}] has no content`);
191
+ const target = file.target ?? file.path;
192
+ return { target: checkTarget(target), content: file.content };
193
+ });
194
+ return {
195
+ name: raw.name,
196
+ type: typeof raw.type === 'string' ? raw.type : '',
197
+ description: typeof raw.description === 'string' ? raw.description : '',
198
+ dependencies: stringList(raw.dependencies, `${label}: dependencies`).map(spec => {
199
+ if (!NPM_SPEC.test(spec)) throw new UnsafeError(`${label}: ${JSON.stringify(spec)} is not an npm package name`);
200
+ return spec;
201
+ }),
202
+ registryDependencies: stringList(raw.registryDependencies, `${label}: registryDependencies`),
203
+ files: parsedFiles,
204
+ };
205
+ }
206
+
207
+ function parseIndex(text, label) {
208
+ const raw = parseJson(text, label);
209
+ const items = Array.isArray(raw) ? raw : raw?.items;
210
+ if (!Array.isArray(items)) throw new RegistryError(`${label} has no items list`);
211
+ return items
212
+ .filter(item => item && typeof item.name === 'string' && /^[a-z0-9][a-z0-9-]{0,99}$/.test(item.name))
213
+ .map(item => ({
214
+ name: item.name,
215
+ type: typeof item.type === 'string' ? item.type : '',
216
+ description: typeof item.description === 'string' ? item.description : '',
217
+ }));
218
+ }
219
+
220
+ function stringList(value, label) {
221
+ if (value === undefined) return [];
222
+ if (!Array.isArray(value) || value.some(entry => typeof entry !== 'string')) {
223
+ throw new UnsafeError(`${label} must be a list of strings`);
224
+ }
225
+ return value;
226
+ }
227
+
228
+ /**
229
+ * Turns a registryDependencies entry into an item name in the open registry.
230
+ * A bare name is looked up as is. A URL must point at `<name>.json` in this
231
+ * registry's folder or in Meridian's hosted folder (a local copy of the
232
+ * registry still lists hosted URLs); a URL anywhere else is refused rather
233
+ * than fetched.
234
+ */
235
+ export function dependencyName(entry, registry) {
236
+ if (!/^https?:\/\//i.test(entry)) return assertItemName(entry);
237
+ let url;
238
+ try {
239
+ url = new URL(entry);
240
+ } catch {
241
+ throw new UnsafeError(`invalid registry dependency URL ${JSON.stringify(entry)}`);
242
+ }
243
+ const folder = new URL('./', url).href;
244
+ const allowed = [DEFAULT_REGISTRY];
245
+ if (registry.base) allowed.push(registry.base.href);
246
+ if (!allowed.includes(folder) || url.search || url.hash) {
247
+ throw new UnsafeError(`registry dependency ${entry} is outside this registry`);
248
+ }
249
+ const file = url.pathname.slice(url.pathname.lastIndexOf('/') + 1);
250
+ if (!file.endsWith('.json')) throw new UnsafeError(`registry dependency ${entry} is not a .json item`);
251
+ return assertItemName(file.slice(0, -'.json'.length));
252
+ }
@@ -0,0 +1,59 @@
1
+ import { assertItemName } from './paths.mjs';
2
+ import { dependencyName, RegistryError } from './registry.mjs';
3
+
4
+ export const MAX_ITEMS = 500;
5
+
6
+ /**
7
+ * Loads the requested items and every item they depend on through
8
+ * registryDependencies. Returns them dependencies first, each once. A cycle
9
+ * is not an error (copying files has no order problem), it just stops there.
10
+ * A dependency that is not in the registry fails with the chain that asked
11
+ * for it, for example `icon (needed by button)`.
12
+ */
13
+ export async function resolveItems(names, registry) {
14
+ const ordered = [];
15
+ const seen = new Set();
16
+ const loaded = new Map();
17
+
18
+ async function load(name, chain) {
19
+ if (loaded.has(name)) return loaded.get(name);
20
+ if (loaded.size >= MAX_ITEMS) throw new RegistryError(`more than ${MAX_ITEMS} items to install; the registry looks wrong`);
21
+ try {
22
+ const item = await registry.item(name);
23
+ loaded.set(name, item);
24
+ return item;
25
+ } catch (error) {
26
+ if (error instanceof RegistryError && chain.length) {
27
+ error.message = `${error.message} (needed by ${chain.join(' <- ')})`;
28
+ }
29
+ throw error;
30
+ }
31
+ }
32
+
33
+ async function visit(name, chain) {
34
+ if (seen.has(name)) return;
35
+ seen.add(name);
36
+ const item = await load(name, chain);
37
+ for (const entry of item.registryDependencies) {
38
+ await visit(dependencyName(entry, registry), [name, ...chain]);
39
+ }
40
+ ordered.push(item);
41
+ }
42
+
43
+ for (const name of names) await visit(assertItemName(name.toLowerCase()), []);
44
+ return ordered;
45
+ }
46
+
47
+ /** npm packages the resolved items need, deduplicated, in first-seen order. */
48
+ export function npmDependencies(items) {
49
+ const specs = new Map();
50
+ for (const item of items) {
51
+ for (const spec of item.dependencies) {
52
+ const at = spec.indexOf('@', 1);
53
+ const pkg = at === -1 ? spec : spec.slice(0, at);
54
+ // Keep the first spec that carries a version range.
55
+ if (!specs.has(pkg) || (!specs.get(pkg).includes('@', 1) && at !== -1)) specs.set(pkg, spec);
56
+ }
57
+ }
58
+ return [...specs.values()];
59
+ }
package/src/write.mjs ADDED
@@ -0,0 +1,113 @@
1
+ import { constants as fsConstants } from 'node:fs';
2
+ import fs from 'node:fs/promises';
3
+ import path from 'node:path';
4
+ import { DiskError, resolveInside, UnsafeError } from './paths.mjs';
5
+
6
+ export const MAX_FILES = 2000;
7
+
8
+ // Windows has no O_NOFOLLOW (it is undefined there), so replace() also checks
9
+ // the open handle against the path before it truncates anything.
10
+ const { O_WRONLY, O_CREAT, O_EXCL, O_NOFOLLOW = 0 } = fsConstants;
11
+
12
+ // Line endings and a byte-order mark are how a checkout differs on Windows
13
+ // (git core.autocrlf, editors), not a change someone made to the file.
14
+ const comparable = text => text.replace(/^\uFEFF/, '').replace(/\r\n/g, '\n');
15
+
16
+ /**
17
+ * Works out what `add` would do for each file without touching the disk:
18
+ * create the file does not exist
19
+ * unchanged the file exists with the same content
20
+ * conflict the file exists with different content (overwrite=false)
21
+ * overwrite the file exists with different content (overwrite=true)
22
+ * Two items that ship the same target with different content are an error.
23
+ */
24
+ export async function planWrites(items, dir, { overwrite = false } = {}) {
25
+ const byPath = new Map();
26
+ for (const item of items) {
27
+ for (const file of item.files) {
28
+ const absolute = await resolveInside(dir, file.target);
29
+ // NTFS and default macOS volumes ignore case, so Button.jsx and button.jsx
30
+ // are one file there. Key on the folded path and refuse two spellings.
31
+ const key = absolute.toLowerCase();
32
+ const previous = byPath.get(key);
33
+ if (previous) {
34
+ if (previous.target !== file.target) {
35
+ throw new UnsafeError(`${previous.item} writes ${previous.target} and ${item.name} writes ${file.target}, the same file on case-insensitive disks`);
36
+ }
37
+ if (previous.content !== file.content) {
38
+ throw new UnsafeError(`${previous.item} and ${item.name} both write ${file.target} with different content`);
39
+ }
40
+ continue;
41
+ }
42
+ byPath.set(key, { path: absolute, target: file.target, item: item.name, content: file.content });
43
+ if (byPath.size > MAX_FILES) throw new UnsafeError(`more than ${MAX_FILES} files to write; the registry looks wrong`);
44
+ }
45
+ }
46
+
47
+ const plan = [];
48
+ for (const entry of byPath.values()) {
49
+ let existing = null;
50
+ try {
51
+ existing = await fs.readFile(entry.path, 'utf8');
52
+ } catch (error) {
53
+ if (error.code !== 'ENOENT') throw error;
54
+ }
55
+ const status = existing === null ? 'create'
56
+ : comparable(existing) === comparable(entry.content) ? 'unchanged'
57
+ : overwrite ? 'overwrite' : 'conflict';
58
+ plan.push({ ...entry, status });
59
+ }
60
+ return plan;
61
+ }
62
+
63
+ /**
64
+ * Writes every create and overwrite entry. Call only on a plan without conflicts.
65
+ * If a write fails (a file locked by an editor, a read-only file), the error
66
+ * carries `written`, the entries already written, so the caller can say so.
67
+ * `noFollow` exists for tests that simulate a platform without O_NOFOLLOW.
68
+ */
69
+ export async function applyPlan(plan, dir, { noFollow = O_NOFOLLOW } = {}) {
70
+ if (plan.some(entry => entry.status === 'conflict')) throw new Error('refusing to apply a plan with conflicts');
71
+ const written = [];
72
+ for (const entry of plan) {
73
+ if (entry.status !== 'create' && entry.status !== 'overwrite') continue;
74
+ try {
75
+ // Check again right before writing: a directory made for an earlier file,
76
+ // or a link created since planning, must not move the write elsewhere.
77
+ const absolute = await resolveInside(dir, entry.target);
78
+ await fs.mkdir(path.dirname(absolute), { recursive: true });
79
+ await resolveInside(dir, entry.target);
80
+ if (entry.status === 'create') {
81
+ // O_EXCL fails on anything already there, a link included.
82
+ await fs.writeFile(absolute, entry.content, { flag: O_WRONLY | O_CREAT | O_EXCL | noFollow });
83
+ } else {
84
+ await replace(absolute, entry.content, noFollow);
85
+ }
86
+ } catch (error) {
87
+ error.written = written;
88
+ throw error;
89
+ }
90
+ written.push(entry);
91
+ }
92
+ return written;
93
+ }
94
+
95
+ /**
96
+ * Overwrites an existing regular file without following a link swapped in after
97
+ * the checks. O_NOFOLLOW refuses a link at open time where the platform has it.
98
+ * Everywhere, the handle is compared with the path before anything is truncated:
99
+ * the path must still not be a link and must be the same file as the handle.
100
+ */
101
+ async function replace(absolute, content, noFollow) {
102
+ const handle = await fs.open(absolute, O_WRONLY | noFollow);
103
+ try {
104
+ const [opened, named] = await Promise.all([handle.stat(), fs.lstat(absolute)]);
105
+ if (named.isSymbolicLink() || !opened.isFile() || opened.ino !== named.ino || opened.dev !== named.dev) {
106
+ throw new DiskError(`${absolute} changed while it was being written; nothing was replaced`);
107
+ }
108
+ await handle.truncate(0);
109
+ await handle.writeFile(content);
110
+ } finally {
111
+ await handle.close();
112
+ }
113
+ }