@craftland/ggpm 0.1.2 → 1.0.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/README.md +58 -48
- package/bin/ggpm.cjs +22 -1
- package/lib/dependency-plan.cjs +78 -0
- package/lib/github-registry.cjs +56 -1
- package/lib/install-archive.cjs +75 -0
- package/lib/install.cjs +192 -0
- package/lib/list.cjs +18 -0
- package/lib/project.cjs +76 -0
- package/lib/publish.cjs +9 -34
- package/lib/registry-index.cjs +106 -0
- package/lib/uninstall.cjs +143 -0
- package/package.json +6 -3
- package/templates/ggpackage.json +6 -0
- package/templates/publish.ignore +17 -0
package/README.md
CHANGED
|
@@ -2,17 +2,20 @@
|
|
|
2
2
|
|
|
3
3
|
Package Manager for Craftland Packages
|
|
4
4
|
|
|
5
|
-
##
|
|
5
|
+
## Requirement
|
|
6
|
+
- Nodejs
|
|
6
7
|
|
|
7
|
-
|
|
8
|
+
## Install the CLI
|
|
8
9
|
|
|
9
10
|
```powershell
|
|
10
11
|
npm install -g @craftland/ggpm
|
|
11
12
|
```
|
|
12
13
|
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
14
|
+
## Update the CLI
|
|
15
|
+
|
|
16
|
+
```
|
|
17
|
+
npm install -g "@craftland/ggpm@latest" --prefer-online
|
|
18
|
+
```
|
|
16
19
|
|
|
17
20
|
## Commands
|
|
18
21
|
|
|
@@ -20,43 +23,62 @@ hosts `registry.json` and the Craftland package ZIPs.
|
|
|
20
23
|
|
|
21
24
|
Print the installed CLI version.
|
|
22
25
|
|
|
23
|
-
|
|
26
|
+
```powershell
|
|
27
|
+
ggpm --version
|
|
28
|
+
```
|
|
24
29
|
|
|
25
|
-
|
|
26
|
-
The path can be absolute or relative to your current directory. With no path,
|
|
27
|
-
`ggpm publish` uses the current directory. The selected folder must contain
|
|
28
|
-
`ggpackage.json`.
|
|
29
|
-
The manifest needs a `Namespace/Name` package name and an exact SemVer version.
|
|
30
|
-
Declare dependencies as exact version pins and publish those versions first.
|
|
30
|
+
### `ggpm list`
|
|
31
31
|
|
|
32
|
-
|
|
33
|
-
access to `FF-OGC/ggpm-registry`, including permission to update `registry.json`
|
|
34
|
-
on the default branch. For example, from PowerShell 7:
|
|
32
|
+
List registry packages by name and show their latest published versions, including prereleases.
|
|
35
33
|
|
|
36
34
|
```powershell
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
35
|
+
ggpm list
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
### `ggpm init`
|
|
39
|
+
|
|
40
|
+
Create `ggpackage.json` in the current project or package folder. An existing manifest is preserved.
|
|
41
|
+
|
|
42
|
+
```powershell
|
|
43
|
+
ggpm init
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
### `ggpm install [<package> [version]]`
|
|
47
|
+
|
|
48
|
+
Install all packages in the project manifest or install a named package and its dependencies. Omit the named package's version to use the latest one shown by `ggpm list`.
|
|
49
|
+
|
|
50
|
+
```powershell
|
|
51
|
+
ggpm install # install all packages in ggpackage.json
|
|
52
|
+
ggpm install GG/Login # install latest version of GG/Login package
|
|
53
|
+
ggpm install GG/Login 0.0.1 # install GG/Login v0.0.1
|
|
40
54
|
```
|
|
41
55
|
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
56
|
+
### `ggpm update [<package> [version]]`
|
|
57
|
+
|
|
58
|
+
Apply the versions pinned in `ggpackage.json`, or change the pin for one declared package. For a named update, omit the version to use the latest one shown by `ggpm list`.
|
|
59
|
+
|
|
60
|
+
```powershell
|
|
61
|
+
ggpm update
|
|
62
|
+
ggpm update GG/Login
|
|
63
|
+
ggpm update GG/Login 0.0.2
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
### `ggpm uninstall <package>`
|
|
67
|
+
|
|
68
|
+
Remove an installed package and its entry in the project manifest. If another installed package requires it, the command reports the dependents and stops.
|
|
69
|
+
|
|
70
|
+
```powershell
|
|
71
|
+
ggpm uninstall GG/Login
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
### `ggpm publish [path]`
|
|
75
|
+
|
|
76
|
+
Upload a package ZIP to GitHub Releases and add its version to the registry. Omit the path to publish the current folder.
|
|
77
|
+
|
|
78
|
+
```powershell
|
|
79
|
+
ggpm publish
|
|
80
|
+
ggpm publish ./packages/GG/Login
|
|
81
|
+
```
|
|
60
82
|
|
|
61
83
|
## Publish a CLI release
|
|
62
84
|
|
|
@@ -78,15 +100,3 @@ The tag push starts **Publish ggpm to npm** in the repository's Actions tab.
|
|
|
78
100
|
The workflow checks that the tag matches the version in `package.json` before
|
|
79
101
|
publishing.
|
|
80
102
|
|
|
81
|
-
## Planned commands
|
|
82
|
-
|
|
83
|
-
- `ggpm list` shows available packages and their latest versions.
|
|
84
|
-
- `ggpm init` creates `ggpackage.json` at the root of a Craftland project.
|
|
85
|
-
- `ggpm install` installs the packages declared in the project manifest.
|
|
86
|
-
- `ggpm install <package-name> [version]` installs a package and records it in
|
|
87
|
-
the project manifest. Omitting the version selects the latest stable release.
|
|
88
|
-
- `ggpm update` updates installed packages to match the versions in the
|
|
89
|
-
project manifest.
|
|
90
|
-
|
|
91
|
-
## Note
|
|
92
|
-
Reference example packages for a package
|
package/bin/ggpm.cjs
CHANGED
|
@@ -7,6 +7,27 @@ const [flag, ...extraArgs] = process.argv.slice(2);
|
|
|
7
7
|
|
|
8
8
|
if (extraArgs.length === 0 && (flag === '-v' || flag === '--version')) {
|
|
9
9
|
console.log(version);
|
|
10
|
+
} else if (flag === 'list' && extraArgs.length === 0) {
|
|
11
|
+
require('../lib/list.cjs').listPackages().catch((error) => {
|
|
12
|
+
console.error(`ggpm list: ${error.message}`);
|
|
13
|
+
process.exitCode = 1;
|
|
14
|
+
});
|
|
15
|
+
} else if (flag === 'init' && extraArgs.length === 0) {
|
|
16
|
+
require('../lib/project.cjs').init(process.cwd()).catch((error) => {
|
|
17
|
+
console.error(`ggpm init: ${error.message}`);
|
|
18
|
+
process.exitCode = 1;
|
|
19
|
+
});
|
|
20
|
+
} else if ((flag === 'install' || flag === 'update') && extraArgs.length <= 2) {
|
|
21
|
+
const [name, requestedVersion] = extraArgs;
|
|
22
|
+
require('../lib/install.cjs')[flag](process.cwd(), name, requestedVersion).catch((error) => {
|
|
23
|
+
console.error(`ggpm ${flag}: ${error.message}`);
|
|
24
|
+
process.exitCode = 1;
|
|
25
|
+
});
|
|
26
|
+
} else if (flag === 'uninstall' && extraArgs.length === 1) {
|
|
27
|
+
require('../lib/uninstall.cjs').uninstall(process.cwd(), extraArgs[0]).catch((error) => {
|
|
28
|
+
console.error(`ggpm uninstall: ${error.message}`);
|
|
29
|
+
process.exitCode = 1;
|
|
30
|
+
});
|
|
10
31
|
} else if (flag === 'publish' && extraArgs.length <= 1) {
|
|
11
32
|
const [packagePath = '.'] = extraArgs;
|
|
12
33
|
require('../lib/publish.cjs').publish(resolve(packagePath)).catch((error) => {
|
|
@@ -14,6 +35,6 @@ if (extraArgs.length === 0 && (flag === '-v' || flag === '--version')) {
|
|
|
14
35
|
process.exitCode = 1;
|
|
15
36
|
});
|
|
16
37
|
} else {
|
|
17
|
-
console.error('Usage: ggpm -v | ggpm --version | ggpm publish [path]');
|
|
38
|
+
console.error('Usage: ggpm -v | ggpm --version | ggpm list | ggpm init | ggpm install [<package> [version]] | ggpm update [<package> [version]] | ggpm uninstall <package> | ggpm publish [path]');
|
|
18
39
|
process.exitCode = 1;
|
|
19
40
|
}
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
const { isObject, parseVersion, latestVersion } = require('./registry-index.cjs');
|
|
2
|
+
|
|
3
|
+
const reservedWindowsName = /^(?:con|prn|aux|nul|com[1-9¹²³]|lpt[1-9¹²³])(?:\.|$)/i;
|
|
4
|
+
const packagePart = /^[a-z0-9][a-z0-9._-]*$/i;
|
|
5
|
+
|
|
6
|
+
function packageParts(name) {
|
|
7
|
+
const parts = typeof name === 'string' ? name.split('/') : [];
|
|
8
|
+
if (parts.length !== 2 || parts.some((part) => !packagePart.test(part)
|
|
9
|
+
|| part.trim() !== part || part.endsWith('.') || reservedWindowsName.test(part))) {
|
|
10
|
+
throw new Error('Invalid package name ' + JSON.stringify(name) + '. Use Namespace/Name.');
|
|
11
|
+
}
|
|
12
|
+
return parts;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
function dependencyEntries(dependencies, source) {
|
|
16
|
+
if (!isObject(dependencies)) throw new Error(source + ' dependencies must be an object.');
|
|
17
|
+
return Object.entries(dependencies).map(([name, version]) => {
|
|
18
|
+
packageParts(name);
|
|
19
|
+
if (!parseVersion(version)) {
|
|
20
|
+
throw new Error(source + ' must pin ' + name + ' to an exact version.');
|
|
21
|
+
}
|
|
22
|
+
return [name, version];
|
|
23
|
+
});
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
function versionsFor(packages, name) {
|
|
27
|
+
if (!Object.hasOwn(packages, name)) throw new Error('Package not found in registry: ' + name);
|
|
28
|
+
const versions = packages[name]?.versions;
|
|
29
|
+
if (!isObject(versions)) throw new Error('Invalid versions object for ' + name + ' in registry.json.');
|
|
30
|
+
return versions;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function targetVersion(packages, name, version) {
|
|
34
|
+
packageParts(name);
|
|
35
|
+
if (version !== undefined) {
|
|
36
|
+
if (!parseVersion(version)) throw new Error('Use an exact version, such as 1.0.0.');
|
|
37
|
+
return version;
|
|
38
|
+
}
|
|
39
|
+
const latest = latestVersion(name, versionsFor(packages, name));
|
|
40
|
+
if (latest === null) throw new Error('No releases found for ' + name + '.');
|
|
41
|
+
return latest;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function resolvePackages(packages, dependencies) {
|
|
45
|
+
const chosen = new Map();
|
|
46
|
+
const pending = dependencyEntries(dependencies, 'The project manifest')
|
|
47
|
+
.map(([name, version]) => ({ name, version, chain: ['project'] }));
|
|
48
|
+
|
|
49
|
+
for (let i = 0; i < pending.length; i += 1) {
|
|
50
|
+
const { name, version, chain } = pending[i];
|
|
51
|
+
const label = name + '@' + version;
|
|
52
|
+
const request = [...chain, label];
|
|
53
|
+
const key = name.toLowerCase();
|
|
54
|
+
const previous = chosen.get(key);
|
|
55
|
+
if (previous) {
|
|
56
|
+
if (previous.name !== name || previous.version !== version) {
|
|
57
|
+
throw new Error('Dependency conflict for ' + name + ':\n '
|
|
58
|
+
+ previous.chain.join(' -> ') + '\n ' + request.join(' -> ')
|
|
59
|
+
+ '\nThe project was not changed.');
|
|
60
|
+
}
|
|
61
|
+
continue;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
const versions = versionsFor(packages, name);
|
|
65
|
+
const asset = versions[version];
|
|
66
|
+
if (!Object.hasOwn(versions, version) || !isObject(asset)) {
|
|
67
|
+
throw new Error('Release not found in registry: ' + request.join(' -> '));
|
|
68
|
+
}
|
|
69
|
+
chosen.set(key, { name, version, parts: packageParts(name), asset, chain: request });
|
|
70
|
+
for (const [depName, pin] of dependencyEntries(asset.dependencies === undefined ? {} : asset.dependencies, label)) {
|
|
71
|
+
pending.push({ name: depName, version: pin, chain: request });
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
return [...chosen.values()];
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
module.exports = { packageParts, dependencyEntries, resolvePackages, targetVersion, reservedWindowsName };
|
package/lib/github-registry.cjs
CHANGED
|
@@ -7,7 +7,7 @@ function githubRegistry(token) {
|
|
|
7
7
|
method,
|
|
8
8
|
headers: {
|
|
9
9
|
accept: 'application/vnd.github+json',
|
|
10
|
-
authorization: `Bearer ${token}
|
|
10
|
+
...(token ? { authorization: `Bearer ${token}` } : {}),
|
|
11
11
|
'x-github-api-version': '2026-03-10',
|
|
12
12
|
...(json ? { 'content-type': 'application/json' } : {}),
|
|
13
13
|
...(bytes ? { 'content-type': 'application/zip' } : {}),
|
|
@@ -28,7 +28,62 @@ function githubRegistry(token) {
|
|
|
28
28
|
return result;
|
|
29
29
|
}
|
|
30
30
|
|
|
31
|
+
async function downloadZip(asset) {
|
|
32
|
+
let url;
|
|
33
|
+
const headers = { accept: 'application/octet-stream' };
|
|
34
|
+
if (token) {
|
|
35
|
+
if (!Number.isSafeInteger(asset.assetId) || asset.assetId <= 0) {
|
|
36
|
+
throw new Error('Missing or invalid GitHub release asset ID.');
|
|
37
|
+
}
|
|
38
|
+
url = new URL('https://api.github.com/repos/' + registryRepo + '/releases/assets/' + asset.assetId);
|
|
39
|
+
headers.authorization = 'Bearer ' + token;
|
|
40
|
+
headers['x-github-api-version'] = '2026-03-10';
|
|
41
|
+
} else {
|
|
42
|
+
url = new URL(asset.url);
|
|
43
|
+
const prefix = '/' + registryRepo.toLowerCase() + '/releases/download/';
|
|
44
|
+
if (url.origin !== 'https://github.com' || !url.pathname.toLowerCase().startsWith(prefix)
|
|
45
|
+
|| url.username || url.password) {
|
|
46
|
+
throw new Error('Expected a package ZIP URL from the GitHub registry releases.');
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
const signal = AbortSignal.timeout(120_000);
|
|
51
|
+
const maxZipBytes = 256 * 1024 * 1024;
|
|
52
|
+
for (let redirects = 0; redirects < 5; redirects += 1) {
|
|
53
|
+
const response = await fetch(url, { headers, redirect: 'manual', signal });
|
|
54
|
+
if ([301, 302, 303, 307, 308].includes(response.status)) {
|
|
55
|
+
await response.body?.cancel();
|
|
56
|
+
const location = response.headers.get('location');
|
|
57
|
+
if (!location) throw new Error('GitHub did not provide a ZIP download location.');
|
|
58
|
+
url = new URL(location, url);
|
|
59
|
+
if (url.protocol !== 'https:' || url.username || url.password
|
|
60
|
+
|| (url.hostname !== 'github.com' && !url.hostname.endsWith('.githubusercontent.com'))) {
|
|
61
|
+
throw new Error('Unexpected GitHub ZIP download host.');
|
|
62
|
+
}
|
|
63
|
+
// A signed release download URL does not need the GitHub API token.
|
|
64
|
+
delete headers.authorization;
|
|
65
|
+
delete headers['x-github-api-version'];
|
|
66
|
+
continue;
|
|
67
|
+
}
|
|
68
|
+
if (!response.ok || !response.body || response.headers.get('content-type')?.includes('application/json')) {
|
|
69
|
+
await response.body?.cancel();
|
|
70
|
+
throw new Error('GitHub did not return a package ZIP (HTTP ' + response.status + ').');
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
const chunks = [];
|
|
74
|
+
let length = 0;
|
|
75
|
+
for await (const chunk of response.body) {
|
|
76
|
+
length += chunk.length;
|
|
77
|
+
if (length > maxZipBytes) throw new Error('Package ZIP exceeds 256 MiB.');
|
|
78
|
+
chunks.push(chunk);
|
|
79
|
+
}
|
|
80
|
+
return Buffer.concat(chunks, length);
|
|
81
|
+
}
|
|
82
|
+
throw new Error('Too many redirects downloading the package ZIP.');
|
|
83
|
+
}
|
|
84
|
+
|
|
31
85
|
return {
|
|
86
|
+
downloadZip,
|
|
32
87
|
getIndex: () => request('/contents/registry.json'),
|
|
33
88
|
updateIndex: (json) => request('/contents/registry.json', { method: 'PUT', json }),
|
|
34
89
|
async findRelease(tag) {
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
const { createHash } = require('node:crypto');
|
|
2
|
+
const { mkdir, writeFile } = require('node:fs/promises');
|
|
3
|
+
const { dirname, join } = require('node:path');
|
|
4
|
+
const { unzipSync } = require('fflate');
|
|
5
|
+
const { parseJson } = require('./registry-index.cjs');
|
|
6
|
+
const { reservedWindowsName } = require('./dependency-plan.cjs');
|
|
7
|
+
|
|
8
|
+
const manifestFile = 'ggpackage.json';
|
|
9
|
+
const maxUnpackedBytes = 512 * 1024 * 1024;
|
|
10
|
+
|
|
11
|
+
function safeParts(entryName) {
|
|
12
|
+
const parts = entryName.replace(/\/$/, '').split('/');
|
|
13
|
+
if (parts.some((part) => !part || /[\\:<>\"|?*\u0000-\u001f]/.test(part)
|
|
14
|
+
|| /[. ]$/.test(part) || reservedWindowsName.test(part) || part === '__proto__')) {
|
|
15
|
+
throw new Error('Unsafe ZIP path: ' + JSON.stringify(entryName));
|
|
16
|
+
}
|
|
17
|
+
return parts;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
function unpack(archive) {
|
|
21
|
+
const paths = new Map();
|
|
22
|
+
let total = 0;
|
|
23
|
+
return unzipSync(archive, {
|
|
24
|
+
filter({ name, size, originalSize, compression }) {
|
|
25
|
+
const parts = safeParts(name);
|
|
26
|
+
const directory = name.endsWith('/');
|
|
27
|
+
// Check implicit directories too, so a ZIP behaves the same on Windows and Linux.
|
|
28
|
+
for (let i = 1; i <= parts.length; i += 1) {
|
|
29
|
+
const entry = parts.slice(0, i).join('/');
|
|
30
|
+
const key = entry.toLowerCase();
|
|
31
|
+
const isDirectory = i < parts.length || directory;
|
|
32
|
+
const existing = paths.get(key);
|
|
33
|
+
if (existing && (existing.entry !== entry || !existing.isDirectory || !isDirectory)) {
|
|
34
|
+
throw new Error('Conflicting ZIP path: ' + JSON.stringify(name));
|
|
35
|
+
}
|
|
36
|
+
paths.set(key, { entry, isDirectory });
|
|
37
|
+
}
|
|
38
|
+
if (directory) return false;
|
|
39
|
+
const unpackedSize = compression === 0 ? size : originalSize;
|
|
40
|
+
if (!Number.isSafeInteger(unpackedSize) || unpackedSize < 0) throw new Error('Invalid ZIP entry size.');
|
|
41
|
+
total += unpackedSize;
|
|
42
|
+
if (!Number.isSafeInteger(total) || total > maxUnpackedBytes) {
|
|
43
|
+
throw new Error('Unpacked package exceeds 512 MiB.');
|
|
44
|
+
}
|
|
45
|
+
return true;
|
|
46
|
+
},
|
|
47
|
+
});
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
async function stagePackage(registry, entry, stage) {
|
|
51
|
+
const { name, version, asset } = entry;
|
|
52
|
+
const label = name + '@' + version;
|
|
53
|
+
if (typeof asset.sha256 !== 'string' || !/^[a-f0-9]{64}$/i.test(asset.sha256)) {
|
|
54
|
+
throw new Error('Missing or invalid SHA-256 in the registry for ' + label + '.');
|
|
55
|
+
}
|
|
56
|
+
const archive = await registry.downloadZip(asset);
|
|
57
|
+
if (createHash('sha256').update(archive).digest('hex') !== asset.sha256.toLowerCase()) {
|
|
58
|
+
throw new Error('SHA-256 mismatch for ' + label + '.');
|
|
59
|
+
}
|
|
60
|
+
const files = unpack(archive);
|
|
61
|
+
if (!Object.hasOwn(files, manifestFile)) throw new Error(label + ' ZIP is missing ' + manifestFile + '.');
|
|
62
|
+
const manifest = parseJson(Buffer.from(files[manifestFile]), label + ' ' + manifestFile);
|
|
63
|
+
if (manifest?.name !== name || manifest?.version !== version) {
|
|
64
|
+
throw new Error('The ZIP manifest does not match the registry entry for ' + label + '.');
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
await mkdir(stage);
|
|
68
|
+
for (const [path, bytes] of Object.entries(files)) {
|
|
69
|
+
const destination = join(stage, ...safeParts(path));
|
|
70
|
+
await mkdir(dirname(destination), { recursive: true });
|
|
71
|
+
await writeFile(destination, bytes, { flag: 'wx' });
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
module.exports = { stagePackage };
|
package/lib/install.cjs
ADDED
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
const { mkdir, mkdtemp, rename, rm, rmdir, writeFile } = require('node:fs/promises');
|
|
2
|
+
const { dirname, join } = require('node:path');
|
|
3
|
+
const { isObject, parseJson, parseVersion, openCatalog } = require('./registry-index.cjs');
|
|
4
|
+
const { packageParts, dependencyEntries, resolvePackages, targetVersion } = require('./dependency-plan.cjs');
|
|
5
|
+
const { stagePackage } = require('./install-archive.cjs');
|
|
6
|
+
|
|
7
|
+
const {
|
|
8
|
+
manifestFile, infoAt, directoryAt, manifestAt, requireAssets, openProject, checkProjectManifest, lockProject,
|
|
9
|
+
} = require('./project.cjs');
|
|
10
|
+
|
|
11
|
+
async function packagesToInstall(packageRoot, plan) {
|
|
12
|
+
await directoryAt(packageRoot);
|
|
13
|
+
const needed = [];
|
|
14
|
+
for (const entry of plan) {
|
|
15
|
+
const namespace = join(packageRoot, entry.parts[0]);
|
|
16
|
+
await directoryAt(namespace);
|
|
17
|
+
const destination = join(namespace, entry.parts[1]);
|
|
18
|
+
if (!await directoryAt(destination)) {
|
|
19
|
+
needed.push({ ...entry, namespace, destination });
|
|
20
|
+
continue;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
const bytes = await manifestAt(join(destination, manifestFile));
|
|
24
|
+
const existing = bytes ? parseJson(bytes, join(destination, manifestFile)) : null;
|
|
25
|
+
if (existing?.name !== entry.name || !parseVersion(existing?.version)) {
|
|
26
|
+
throw new Error('Install conflict at ' + destination + ': expected a manifest for '
|
|
27
|
+
+ entry.name + ' with a valid version. The project was not changed.');
|
|
28
|
+
}
|
|
29
|
+
if (existing.version !== entry.version) {
|
|
30
|
+
needed.push({ ...entry, namespace, destination, previousManifest: bytes });
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
return needed;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
async function ensureDirectory(path, created) {
|
|
37
|
+
try {
|
|
38
|
+
await mkdir(path);
|
|
39
|
+
created.push(path);
|
|
40
|
+
} catch (error) {
|
|
41
|
+
if (error.code !== 'EEXIST') throw error;
|
|
42
|
+
if (!await directoryAt(path)) throw error;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
async function applyInstall(paths, projectBytes, nextProject, plan, registry, command) {
|
|
47
|
+
const { root, assets, packageRoot, projectPath } = paths;
|
|
48
|
+
const unlock = await lockProject(root);
|
|
49
|
+
|
|
50
|
+
const moved = [];
|
|
51
|
+
const replaced = [];
|
|
52
|
+
const created = [];
|
|
53
|
+
let stage;
|
|
54
|
+
let keepStage = false;
|
|
55
|
+
try {
|
|
56
|
+
await checkProjectManifest(projectPath, projectBytes, command);
|
|
57
|
+
await requireAssets(assets);
|
|
58
|
+
const needed = await packagesToInstall(packageRoot, plan);
|
|
59
|
+
if (needed.length === 0 && !nextProject) return { installed: 0, updated: 0 };
|
|
60
|
+
|
|
61
|
+
stage = await mkdtemp(join(root, '.ggpm-install-'));
|
|
62
|
+
for (const [i, entry] of needed.entries()) {
|
|
63
|
+
entry.stagedPath = join(stage, 'new-' + i);
|
|
64
|
+
entry.backupPath = join(stage, 'old-' + i);
|
|
65
|
+
await stagePackage(registry, entry, entry.stagedPath);
|
|
66
|
+
}
|
|
67
|
+
const stagedManifest = join(stage, manifestFile);
|
|
68
|
+
if (nextProject) {
|
|
69
|
+
await writeFile(stagedManifest, JSON.stringify(nextProject, null, 2) + '\n', { flag: 'wx' });
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
await checkProjectManifest(projectPath, projectBytes, command);
|
|
73
|
+
await requireAssets(assets);
|
|
74
|
+
if (needed.length > 0) await ensureDirectory(packageRoot, created);
|
|
75
|
+
for (const entry of needed) {
|
|
76
|
+
await ensureDirectory(entry.namespace, created);
|
|
77
|
+
if (entry.previousManifest) {
|
|
78
|
+
if (!await directoryAt(entry.destination)) {
|
|
79
|
+
throw new Error('Package folder disappeared during installation: ' + entry.destination);
|
|
80
|
+
}
|
|
81
|
+
const current = await manifestAt(join(entry.destination, manifestFile));
|
|
82
|
+
if (!current?.equals(entry.previousManifest)) {
|
|
83
|
+
throw new Error('Package manifest changed during installation: ' + entry.destination);
|
|
84
|
+
}
|
|
85
|
+
await rename(entry.destination, entry.backupPath);
|
|
86
|
+
replaced.push(entry);
|
|
87
|
+
}
|
|
88
|
+
if (await infoAt(entry.destination)) {
|
|
89
|
+
throw new Error('Another process created ' + entry.destination + ' during installation.');
|
|
90
|
+
}
|
|
91
|
+
await rename(entry.stagedPath, entry.destination);
|
|
92
|
+
moved.push(entry);
|
|
93
|
+
}
|
|
94
|
+
if (nextProject) {
|
|
95
|
+
await checkProjectManifest(projectPath, projectBytes, command);
|
|
96
|
+
await rename(stagedManifest, projectPath);
|
|
97
|
+
}
|
|
98
|
+
return { installed: moved.length, updated: replaced.length };
|
|
99
|
+
} catch (error) {
|
|
100
|
+
const rollbackErrors = [];
|
|
101
|
+
for (const entry of moved.reverse()) {
|
|
102
|
+
try {
|
|
103
|
+
await rename(entry.destination, entry.stagedPath);
|
|
104
|
+
} catch (rollbackError) {
|
|
105
|
+
rollbackErrors.push(rollbackError.message);
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
for (const entry of replaced.reverse()) {
|
|
109
|
+
try {
|
|
110
|
+
if (await infoAt(entry.destination)) {
|
|
111
|
+
throw new Error('Cannot restore ' + entry.destination + ': the destination is occupied.');
|
|
112
|
+
}
|
|
113
|
+
await rename(entry.backupPath, entry.destination);
|
|
114
|
+
} catch (rollbackError) {
|
|
115
|
+
rollbackErrors.push(rollbackError.message);
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
for (const path of created.reverse()) {
|
|
119
|
+
try {
|
|
120
|
+
await rmdir(path);
|
|
121
|
+
} catch (rollbackError) {
|
|
122
|
+
rollbackErrors.push(rollbackError.message);
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
if (rollbackErrors.length > 0) {
|
|
126
|
+
keepStage = true;
|
|
127
|
+
throw new Error(error.message + '\nRollback needs attention: ' + rollbackErrors.join('\n') + '\nStaging folder: ' + stage);
|
|
128
|
+
}
|
|
129
|
+
throw error;
|
|
130
|
+
} finally {
|
|
131
|
+
if (stage && dirname(stage) === root && !keepStage) {
|
|
132
|
+
await rm(stage, { recursive: true, force: true }).catch((error) => {
|
|
133
|
+
console.error('Could not clean the install staging folder: ' + error.message);
|
|
134
|
+
});
|
|
135
|
+
}
|
|
136
|
+
await unlock();
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
async function syncPackages(rootPath, name, version, action) {
|
|
141
|
+
const paths = await openProject(rootPath);
|
|
142
|
+
const { packageRoot, projectPath } = paths;
|
|
143
|
+
const projectBytes = await manifestAt(projectPath);
|
|
144
|
+
if (!projectBytes) throw new Error('No ' + manifestFile + ' found. Run ggpm init first.');
|
|
145
|
+
const project = parseJson(projectBytes, projectPath);
|
|
146
|
+
if (!isObject(project)) throw new Error(projectPath + ' must contain a JSON object.');
|
|
147
|
+
const { dependencies: pins = {} } = project;
|
|
148
|
+
const dependencies = Object.fromEntries(dependencyEntries(pins, projectPath));
|
|
149
|
+
if (name === undefined && Object.keys(dependencies).length === 0) {
|
|
150
|
+
console.log('No packages declared in ' + manifestFile + '.');
|
|
151
|
+
return;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
if (action === 'update' && name !== undefined) {
|
|
155
|
+
packageParts(name);
|
|
156
|
+
if (!Object.hasOwn(dependencies, name)) {
|
|
157
|
+
throw new Error(name + ' is not declared in ' + manifestFile + '. Use ggpm install to add it.');
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
const { index, registry } = await openCatalog();
|
|
162
|
+
const requested = name === undefined ? undefined : targetVersion(index.packages, name, version);
|
|
163
|
+
let nextProject;
|
|
164
|
+
if (name && dependencies[name] !== requested) {
|
|
165
|
+
dependencies[name] = requested;
|
|
166
|
+
nextProject = { ...project, dependencies };
|
|
167
|
+
}
|
|
168
|
+
const plan = resolvePackages(index.packages, dependencies);
|
|
169
|
+
|
|
170
|
+
// Complete every dependency and local path check before creating a lock or downloading ZIPs.
|
|
171
|
+
const needed = await packagesToInstall(packageRoot, plan);
|
|
172
|
+
const { installed, updated } = needed.length > 0 || nextProject
|
|
173
|
+
? await applyInstall(paths, projectBytes, nextProject, plan, registry, 'ggpm ' + action)
|
|
174
|
+
: { installed: 0, updated: 0 };
|
|
175
|
+
if (installed > 0) {
|
|
176
|
+
const summary = 'Installed ' + installed + ' package' + (installed === 1 ? '' : 's');
|
|
177
|
+
console.log(summary + (updated > 0 ? ' (' + updated + ' replaced)' : '') + '.');
|
|
178
|
+
} else {
|
|
179
|
+
console.log('All requested packages are already installed.');
|
|
180
|
+
}
|
|
181
|
+
if (nextProject) console.log('Saved ' + name + '@' + requested + ' to ' + manifestFile + '.');
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
function install(rootPath, name, version) {
|
|
185
|
+
return syncPackages(rootPath, name, version, 'install');
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
function update(rootPath, name, version) {
|
|
189
|
+
return syncPackages(rootPath, name, version, 'update');
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
module.exports = { install, update };
|
package/lib/list.cjs
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
const { latestVersion, readCatalog } = require('./registry-index.cjs');
|
|
2
|
+
|
|
3
|
+
async function listPackages() {
|
|
4
|
+
const { packages } = await readCatalog();
|
|
5
|
+
const names = Object.keys(packages).sort((left, right) => left.localeCompare(right, 'en'));
|
|
6
|
+
if (names.length === 0) {
|
|
7
|
+
console.log('No packages have been published yet.');
|
|
8
|
+
return;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
const rows = names.map((name) => [name, latestVersion(name, packages[name]?.versions) ?? '(no releases)']);
|
|
12
|
+
const width = names.reduce((max, name) => Math.max(max, name.length), 'PACKAGE'.length);
|
|
13
|
+
console.log([['PACKAGE', 'LATEST'], ...rows]
|
|
14
|
+
.map(([name, version]) => `${name.padEnd(width)} ${version}`)
|
|
15
|
+
.join('\n'));
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
module.exports = { listPackages };
|
package/lib/project.cjs
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
const { constants } = require('node:fs');
|
|
2
|
+
const { copyFile, lstat, mkdir, readFile, realpath, rmdir } = require('node:fs/promises');
|
|
3
|
+
const { join } = require('node:path');
|
|
4
|
+
|
|
5
|
+
const manifestFile = 'ggpackage.json';
|
|
6
|
+
const manifestTemplate = join(__dirname, '..', 'templates', manifestFile);
|
|
7
|
+
|
|
8
|
+
async function infoAt(path) {
|
|
9
|
+
return lstat(path).catch((error) => {
|
|
10
|
+
if (error.code === 'ENOENT') return null;
|
|
11
|
+
throw error;
|
|
12
|
+
});
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
async function directoryAt(path) {
|
|
16
|
+
const info = await infoAt(path);
|
|
17
|
+
if (info && !info.isDirectory()) throw new Error('Expected a real directory at ' + path + '.');
|
|
18
|
+
return Boolean(info);
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
async function manifestAt(path) {
|
|
22
|
+
const info = await infoAt(path);
|
|
23
|
+
if (!info) return null;
|
|
24
|
+
if (!info.isFile()) throw new Error('Expected a regular manifest file at ' + path + '.');
|
|
25
|
+
return readFile(path);
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
async function requireAssets(assets) {
|
|
29
|
+
if (!await directoryAt(assets)) {
|
|
30
|
+
throw new Error('No Assets folder found at ' + assets + '. Run this command from a Craftland project root.');
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
async function openProject(rootPath) {
|
|
35
|
+
const root = await realpath(rootPath);
|
|
36
|
+
const assets = join(root, 'Assets');
|
|
37
|
+
await requireAssets(assets);
|
|
38
|
+
return { root, assets, packageRoot: join(assets, 'GGPackages'), projectPath: join(root, manifestFile) };
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
async function checkProjectManifest(path, expected, command) {
|
|
42
|
+
const current = await manifestAt(path);
|
|
43
|
+
if (!current?.equals(expected)) {
|
|
44
|
+
throw new Error('The project manifest changed during the operation. Rerun ' + command + '.');
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
async function lockProject(root) {
|
|
49
|
+
const lock = join(root, '.ggpm-install.lock');
|
|
50
|
+
await mkdir(lock).catch((error) => {
|
|
51
|
+
if (error.code === 'EEXIST') throw new Error('Another ggpm package operation may be running in ' + root + '.');
|
|
52
|
+
throw error;
|
|
53
|
+
});
|
|
54
|
+
return async () => {
|
|
55
|
+
await rmdir(lock).catch((error) => {
|
|
56
|
+
console.error('Could not remove the ggpm project lock: ' + error.message);
|
|
57
|
+
});
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
async function init(rootPath) {
|
|
62
|
+
const projectPath = join(await realpath(rootPath), manifestFile);
|
|
63
|
+
try {
|
|
64
|
+
await copyFile(manifestTemplate, projectPath, constants.COPYFILE_EXCL);
|
|
65
|
+
} catch (error) {
|
|
66
|
+
if (error.code !== 'EEXIST') throw error;
|
|
67
|
+
if (!(await infoAt(projectPath))?.isFile()) {
|
|
68
|
+
throw new Error('Expected a regular manifest file at ' + projectPath + '.');
|
|
69
|
+
}
|
|
70
|
+
console.log(manifestFile + ' already exists at ' + projectPath + '.');
|
|
71
|
+
return;
|
|
72
|
+
}
|
|
73
|
+
console.log('Created ' + projectPath + '.');
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
module.exports = { manifestFile, infoAt, directoryAt, manifestAt, requireAssets, openProject, checkProjectManifest, lockProject, init };
|
package/lib/publish.cjs
CHANGED
|
@@ -2,27 +2,13 @@ const { createHash } = require('node:crypto');
|
|
|
2
2
|
const { lstat, readFile, readdir } = require('node:fs/promises');
|
|
3
3
|
const { join } = require('node:path');
|
|
4
4
|
const { Zip, ZipDeflate } = require('fflate');
|
|
5
|
+
const ignore = require('ignore');
|
|
5
6
|
const { githubRegistry, registryRepo } = require('./github-registry.cjs');
|
|
7
|
+
const { isObject, parseJson, parseVersion, readIndex } = require('./registry-index.cjs');
|
|
6
8
|
|
|
7
9
|
const manifestFile = 'ggpackage.json';
|
|
10
|
+
const publishIgnoreFile = join(__dirname, '..', 'templates', 'publish.ignore');
|
|
8
11
|
const packageName = /^[a-z0-9][a-z0-9._-]*\/[a-z0-9][a-z0-9._-]*$/i;
|
|
9
|
-
const versionPattern = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-([a-z\d-]+(?:\.[a-z\d-]+)*))?(?:\+[a-z\d-]+(?:\.[a-z\d-]+)*)?$/i;
|
|
10
|
-
const isObject = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
11
|
-
|
|
12
|
-
function parseVersion(value) {
|
|
13
|
-
if (typeof value !== 'string' || value !== value.trim()) return null;
|
|
14
|
-
const match = versionPattern.exec(value);
|
|
15
|
-
if (!match || match[4]?.split('.').some((part) => /^0\d+$/.test(part))) return null;
|
|
16
|
-
return { prerelease: Boolean(match[4]) };
|
|
17
|
-
}
|
|
18
|
-
|
|
19
|
-
function parseJson(bytes, label) {
|
|
20
|
-
try {
|
|
21
|
-
return JSON.parse(bytes.toString('utf8').replace(/^\uFEFF/, ''));
|
|
22
|
-
} catch (error) {
|
|
23
|
-
throw new Error(`${label} is not valid JSON: ${error.message}`);
|
|
24
|
-
}
|
|
25
|
-
}
|
|
26
12
|
|
|
27
13
|
async function loadPackage(root) {
|
|
28
14
|
const path = join(root, manifestFile);
|
|
@@ -67,6 +53,7 @@ async function loadPackage(root) {
|
|
|
67
53
|
}
|
|
68
54
|
|
|
69
55
|
async function archivePackage(root, manifest) {
|
|
56
|
+
const exclusions = ignore().add(await readFile(publishIgnoreFile, 'utf8'));
|
|
70
57
|
const chunks = [];
|
|
71
58
|
const zip = new Zip((error, data) => {
|
|
72
59
|
if (error) throw error;
|
|
@@ -87,14 +74,14 @@ async function archivePackage(root, manifest) {
|
|
|
87
74
|
entries.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
|
|
88
75
|
for (const entry of entries) {
|
|
89
76
|
const { name } = entry;
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
77
|
+
if (!prefix && name.toLowerCase() === manifestFile) continue;
|
|
78
|
+
const archivePath = `${prefix}${name}`;
|
|
79
|
+
const directory = entry.isDirectory();
|
|
80
|
+
if (exclusions.ignores(directory ? `${archivePath}/` : archivePath)) continue;
|
|
93
81
|
|
|
94
82
|
const path = join(folder, name);
|
|
95
|
-
const archivePath = `${prefix}${name}`;
|
|
96
83
|
if (/[\\:<>"|?*]/.test(name)) throw new Error(`Invalid Windows package path: ${archivePath}`);
|
|
97
|
-
if (
|
|
84
|
+
if (directory) await addFolder(path, `${archivePath}/`);
|
|
98
85
|
else if (entry.isFile()) addFile(archivePath, await readFile(path));
|
|
99
86
|
else throw new Error(`Cannot package ${archivePath}: expected a regular file or directory.`);
|
|
100
87
|
}
|
|
@@ -106,18 +93,6 @@ async function archivePackage(root, manifest) {
|
|
|
106
93
|
return Buffer.concat(chunks);
|
|
107
94
|
}
|
|
108
95
|
|
|
109
|
-
async function readIndex(registry) {
|
|
110
|
-
const file = await registry.getIndex();
|
|
111
|
-
if (!file?.sha || file.encoding !== 'base64' || typeof file.content !== 'string') {
|
|
112
|
-
throw new Error(`Expected registry.json on the default branch of ${registryRepo}.`);
|
|
113
|
-
}
|
|
114
|
-
const index = parseJson(Buffer.from(file.content, 'base64'), 'registry.json');
|
|
115
|
-
if (index?.schemaVersion !== 1 || !isObject(index.packages)) {
|
|
116
|
-
throw new Error('registry.json must have schemaVersion 1 and a packages object.');
|
|
117
|
-
}
|
|
118
|
-
return { sha: file.sha, index };
|
|
119
|
-
}
|
|
120
|
-
|
|
121
96
|
function packageRecord(index, { name, dependencies }) {
|
|
122
97
|
const existingName = Object.keys(index.packages).find((key) => key.toLowerCase() === name.toLowerCase());
|
|
123
98
|
if (existingName && existingName !== name) {
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
const { execFile } = require('node:child_process');
|
|
2
|
+
const { promisify } = require('node:util');
|
|
3
|
+
const { githubRegistry, registryRepo } = require('./github-registry.cjs');
|
|
4
|
+
|
|
5
|
+
const execFileAsync = promisify(execFile);
|
|
6
|
+
const versionPattern = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-([a-z\d-]+(?:\.[a-z\d-]+)*))?(?:\+[a-z\d-]+(?:\.[a-z\d-]+)*)?$/i;
|
|
7
|
+
const isObject = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
8
|
+
|
|
9
|
+
function parseVersion(value) {
|
|
10
|
+
if (typeof value !== 'string' || value !== value.trim()) return null;
|
|
11
|
+
const match = versionPattern.exec(value);
|
|
12
|
+
if (!match) return null;
|
|
13
|
+
const prereleaseParts = match[4]?.split('.') ?? [];
|
|
14
|
+
if (prereleaseParts.some((part) => /^0\d+$/.test(part))) return null;
|
|
15
|
+
return { parts: match.slice(1, 4), prerelease: prereleaseParts.length > 0, prereleaseParts };
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
function parseJson(bytes, label) {
|
|
19
|
+
try {
|
|
20
|
+
return JSON.parse(bytes.toString('utf8').replace(/^\uFEFF/, ''));
|
|
21
|
+
} catch (error) {
|
|
22
|
+
throw new Error(`${label} is not valid JSON: ${error.message}`);
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
async function readIndex(registry) {
|
|
27
|
+
const file = await registry.getIndex();
|
|
28
|
+
if (!file?.sha || file.encoding !== 'base64' || typeof file.content !== 'string') {
|
|
29
|
+
throw new Error(`Expected registry.json on the default branch of ${registryRepo}.`);
|
|
30
|
+
}
|
|
31
|
+
const index = parseJson(Buffer.from(file.content, 'base64'), 'registry.json');
|
|
32
|
+
if (index?.schemaVersion !== 1 || !isObject(index.packages)) {
|
|
33
|
+
throw new Error('registry.json must have schemaVersion 1 and a packages object.');
|
|
34
|
+
}
|
|
35
|
+
return { sha: file.sha, index };
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
async function openCatalog() {
|
|
39
|
+
const token = process.env.GGPM_GITHUB_TOKEN?.trim();
|
|
40
|
+
const registry = githubRegistry(token);
|
|
41
|
+
try {
|
|
42
|
+
return { registry, index: (await readIndex(registry)).index };
|
|
43
|
+
} catch (error) {
|
|
44
|
+
if (token || ![403, 404, 429].includes(error.status)) throw error;
|
|
45
|
+
|
|
46
|
+
// Public reads need no GitHub CLI session. Try it only when GitHub denies anonymous access.
|
|
47
|
+
const login = await execFileAsync('gh', ['auth', 'token', '--hostname', 'github.com'], {
|
|
48
|
+
timeout: 5_000,
|
|
49
|
+
windowsHide: true,
|
|
50
|
+
}).catch(() => null);
|
|
51
|
+
const githubToken = login?.stdout.trim();
|
|
52
|
+
if (!githubToken) {
|
|
53
|
+
throw new Error(`${error.message}. For an authenticated read, run gh auth login or set GGPM_GITHUB_TOKEN with Contents read access.`);
|
|
54
|
+
}
|
|
55
|
+
const authenticated = githubRegistry(githubToken);
|
|
56
|
+
return { registry: authenticated, index: (await readIndex(authenticated)).index };
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
async function readCatalog() {
|
|
61
|
+
return (await openCatalog()).index;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function compareText(left, right) {
|
|
65
|
+
return left === right ? 0 : left > right ? 1 : -1;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
function compareNumbers(left, right) {
|
|
69
|
+
// Version components can exceed JavaScript's safe integer range.
|
|
70
|
+
return left.length - right.length || compareText(left, right);
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
function compareVersions(left, right) {
|
|
74
|
+
for (let i = 0; i < left.parts.length; i += 1) {
|
|
75
|
+
const order = compareNumbers(left.parts[i], right.parts[i]);
|
|
76
|
+
if (order !== 0) return order;
|
|
77
|
+
}
|
|
78
|
+
if (left.prerelease !== right.prerelease) return left.prerelease ? -1 : 1;
|
|
79
|
+
|
|
80
|
+
const leftIds = left.prereleaseParts;
|
|
81
|
+
const rightIds = right.prereleaseParts;
|
|
82
|
+
for (let i = 0; i < Math.min(leftIds.length, rightIds.length); i += 1) {
|
|
83
|
+
const leftIsNumeric = /^\d+$/.test(leftIds[i]);
|
|
84
|
+
const rightIsNumeric = /^\d+$/.test(rightIds[i]);
|
|
85
|
+
if (leftIsNumeric !== rightIsNumeric) return leftIsNumeric ? -1 : 1;
|
|
86
|
+
const order = leftIsNumeric
|
|
87
|
+
? compareNumbers(leftIds[i], rightIds[i])
|
|
88
|
+
: compareText(leftIds[i], rightIds[i]);
|
|
89
|
+
if (order !== 0) return order;
|
|
90
|
+
}
|
|
91
|
+
return leftIds.length - rightIds.length;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
function latestVersion(name, versions) {
|
|
95
|
+
if (!isObject(versions)) throw new Error(`Invalid versions object for ${name} in registry.json.`);
|
|
96
|
+
|
|
97
|
+
let latest = null;
|
|
98
|
+
for (const version of Object.keys(versions).sort()) {
|
|
99
|
+
const parsed = parseVersion(version);
|
|
100
|
+
if (!parsed) throw new Error(`Invalid version ${JSON.stringify(version)} for ${name} in registry.json.`);
|
|
101
|
+
if (!latest || compareVersions(parsed, latest) > 0) latest = { ...parsed, version };
|
|
102
|
+
}
|
|
103
|
+
return latest?.version ?? null;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
module.exports = { isObject, parseJson, parseVersion, latestVersion, readIndex, readCatalog, openCatalog };
|
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
const { mkdtemp, readdir, rename, rm, writeFile } = require('node:fs/promises');
|
|
2
|
+
const { dirname, join } = require('node:path');
|
|
3
|
+
const { isObject, parseJson, parseVersion } = require('./registry-index.cjs');
|
|
4
|
+
const { packageParts, dependencyEntries } = require('./dependency-plan.cjs');
|
|
5
|
+
const {
|
|
6
|
+
manifestFile, infoAt, directoryAt, manifestAt, checkProjectManifest, lockProject, requireAssets, openProject,
|
|
7
|
+
} = require('./project.cjs');
|
|
8
|
+
|
|
9
|
+
async function findDependents(packageRoot, name) {
|
|
10
|
+
if (!await directoryAt(packageRoot)) return [];
|
|
11
|
+
const target = name.toLowerCase();
|
|
12
|
+
const dependents = [];
|
|
13
|
+
|
|
14
|
+
for (const namespace of await readdir(packageRoot, { withFileTypes: true })) {
|
|
15
|
+
if (!namespace.isDirectory()) continue;
|
|
16
|
+
const namespacePath = join(packageRoot, namespace.name);
|
|
17
|
+
if (!await directoryAt(namespacePath)) continue;
|
|
18
|
+
for (const folder of await readdir(namespacePath, { withFileTypes: true })) {
|
|
19
|
+
if (!folder.isDirectory()) continue;
|
|
20
|
+
const installedName = namespace.name + '/' + folder.name;
|
|
21
|
+
if (installedName.toLowerCase() === target) continue;
|
|
22
|
+
|
|
23
|
+
const folderPath = join(namespacePath, folder.name);
|
|
24
|
+
if (!await directoryAt(folderPath)) continue;
|
|
25
|
+
const path = join(folderPath, manifestFile);
|
|
26
|
+
const bytes = await manifestAt(path);
|
|
27
|
+
if (!bytes) continue;
|
|
28
|
+
const manifest = parseJson(bytes, path);
|
|
29
|
+
if (!isObject(manifest)) throw new Error(path + ' must contain a JSON object.');
|
|
30
|
+
const { dependencies = {} } = manifest;
|
|
31
|
+
const needed = dependencyEntries(dependencies, path);
|
|
32
|
+
if (needed.some(([dependency]) => dependency.toLowerCase() === target)) {
|
|
33
|
+
dependents.push(installedName + (parseVersion(manifest.version) ? '@' + manifest.version : ''));
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
return dependents.sort();
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
async function readTarget(paths, name, parts) {
|
|
41
|
+
await requireAssets(paths.assets);
|
|
42
|
+
await directoryAt(paths.packageRoot);
|
|
43
|
+
const namespace = join(paths.packageRoot, parts[0]);
|
|
44
|
+
await directoryAt(namespace);
|
|
45
|
+
const destination = join(namespace, parts[1]);
|
|
46
|
+
if (!await directoryAt(destination)) return { destination, bytes: null };
|
|
47
|
+
|
|
48
|
+
const path = join(destination, manifestFile);
|
|
49
|
+
const bytes = await manifestAt(path);
|
|
50
|
+
const installed = bytes ? parseJson(bytes, path) : null;
|
|
51
|
+
if (installed?.name !== name || !parseVersion(installed?.version)) {
|
|
52
|
+
throw new Error('Uninstall conflict at ' + destination + ': expected a manifest for '
|
|
53
|
+
+ name + ' with a valid version. The project was not changed.');
|
|
54
|
+
}
|
|
55
|
+
return { destination, bytes };
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
async function removePackage(paths, name, parts) {
|
|
59
|
+
const { root, packageRoot, projectPath } = paths;
|
|
60
|
+
const projectBytes = await manifestAt(projectPath);
|
|
61
|
+
if (!projectBytes) throw new Error('No ' + manifestFile + ' found. Run ggpm init first.');
|
|
62
|
+
const project = parseJson(projectBytes, projectPath);
|
|
63
|
+
if (!isObject(project)) throw new Error(projectPath + ' must contain a JSON object.');
|
|
64
|
+
const { dependencies: pins = {} } = project;
|
|
65
|
+
const dependencies = Object.fromEntries(dependencyEntries(pins, projectPath));
|
|
66
|
+
const caseAlias = Object.keys(dependencies).find((pin) => pin !== name && pin.toLowerCase() === name.toLowerCase());
|
|
67
|
+
if (caseAlias) throw new Error('Use the exact package name ' + caseAlias + ' from ' + manifestFile + '.');
|
|
68
|
+
const pinned = Object.hasOwn(dependencies, name);
|
|
69
|
+
|
|
70
|
+
const target = await readTarget(paths, name, parts);
|
|
71
|
+
if (!target.bytes && !pinned) {
|
|
72
|
+
console.log(name + ' is not installed or declared in ' + manifestFile + '.');
|
|
73
|
+
return;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
const dependents = await findDependents(packageRoot, name);
|
|
77
|
+
if (dependents.length > 0) {
|
|
78
|
+
throw new Error('Cannot uninstall ' + name + '. Required by: ' + dependents.join(', ')
|
|
79
|
+
+ '. The project was not changed.');
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
const stage = await mkdtemp(join(root, '.ggpm-uninstall-'));
|
|
83
|
+
const backup = join(stage, 'removed-package');
|
|
84
|
+
const stagedManifest = join(stage, manifestFile);
|
|
85
|
+
let moved = false;
|
|
86
|
+
let keepStage = false;
|
|
87
|
+
try {
|
|
88
|
+
if (pinned) {
|
|
89
|
+
delete dependencies[name];
|
|
90
|
+
const content = JSON.stringify({ ...project, dependencies }, null, 2) + '\n';
|
|
91
|
+
await writeFile(stagedManifest, content, { flag: 'wx' });
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
await checkProjectManifest(projectPath, projectBytes, 'ggpm uninstall');
|
|
95
|
+
if (target.bytes) {
|
|
96
|
+
const current = await readTarget(paths, name, parts);
|
|
97
|
+
if (!current.bytes?.equals(target.bytes)) {
|
|
98
|
+
throw new Error('Package manifest changed during uninstall: ' + target.destination);
|
|
99
|
+
}
|
|
100
|
+
await rename(target.destination, backup);
|
|
101
|
+
moved = true;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
if (pinned) {
|
|
105
|
+
await checkProjectManifest(projectPath, projectBytes, 'ggpm uninstall');
|
|
106
|
+
await rename(stagedManifest, projectPath);
|
|
107
|
+
}
|
|
108
|
+
} catch (error) {
|
|
109
|
+
if (moved) {
|
|
110
|
+
try {
|
|
111
|
+
if (await infoAt(target.destination)) throw new Error('The original destination is occupied.');
|
|
112
|
+
await rename(backup, target.destination);
|
|
113
|
+
} catch (restoreError) {
|
|
114
|
+
keepStage = true;
|
|
115
|
+
throw new Error(error.message + '\nCould not restore ' + name + ': '
|
|
116
|
+
+ restoreError.message + '\nBackup: ' + backup);
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
throw error;
|
|
120
|
+
} finally {
|
|
121
|
+
if (!keepStage && dirname(stage) === root) {
|
|
122
|
+
await rm(stage, { recursive: true, force: true }).catch((error) => {
|
|
123
|
+
console.error('Could not clean the uninstall staging folder: ' + error.message);
|
|
124
|
+
});
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
if (moved) console.log('Uninstalled ' + name + '.');
|
|
129
|
+
if (pinned) console.log('Removed ' + name + ' from ' + manifestFile + '.');
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
async function uninstall(rootPath, name) {
|
|
133
|
+
const parts = packageParts(name);
|
|
134
|
+
const paths = await openProject(rootPath);
|
|
135
|
+
const unlock = await lockProject(paths.root);
|
|
136
|
+
try {
|
|
137
|
+
await removePackage(paths, name, parts);
|
|
138
|
+
} finally {
|
|
139
|
+
await unlock();
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
module.exports = { uninstall };
|
package/package.json
CHANGED
|
@@ -1,13 +1,15 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@craftland/ggpm",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "1.0.0",
|
|
4
4
|
"description": "Package manager for Craftland projects",
|
|
5
5
|
"bin": {
|
|
6
6
|
"ggpm": "bin/ggpm.cjs"
|
|
7
7
|
},
|
|
8
8
|
"files": [
|
|
9
9
|
"bin/ggpm.cjs",
|
|
10
|
-
"lib/"
|
|
10
|
+
"lib/",
|
|
11
|
+
"templates/ggpackage.json",
|
|
12
|
+
"templates/publish.ignore"
|
|
11
13
|
],
|
|
12
14
|
"engines": {
|
|
13
15
|
"node": ">=18"
|
|
@@ -16,6 +18,7 @@
|
|
|
16
18
|
"access": "public"
|
|
17
19
|
},
|
|
18
20
|
"dependencies": {
|
|
19
|
-
"fflate": "0.8.3"
|
|
21
|
+
"fflate": "0.8.3",
|
|
22
|
+
"ignore": "7.0.17"
|
|
20
23
|
}
|
|
21
24
|
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
# Git ignore patterns applied relative to the package root.
|
|
2
|
+
|
|
3
|
+
# Craftland metadata
|
|
4
|
+
*.meta
|
|
5
|
+
|
|
6
|
+
# Local files and directories
|
|
7
|
+
.*
|
|
8
|
+
node_modules
|
|
9
|
+
|
|
10
|
+
# OS metadata
|
|
11
|
+
__MACOSX
|
|
12
|
+
Thumbs.db
|
|
13
|
+
Desktop.ini
|
|
14
|
+
|
|
15
|
+
# Archives left at the package root
|
|
16
|
+
/*.zip
|
|
17
|
+
/*.tgz
|