@craftland/ggpm 0.1.3 → 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 CHANGED
@@ -23,52 +23,62 @@ npm install -g "@craftland/ggpm@latest" --prefer-online
23
23
 
24
24
  Print the installed CLI version.
25
25
 
26
+ ```powershell
27
+ ggpm --version
28
+ ```
29
+
26
30
  ### `ggpm list`
27
31
 
28
- Show packages in the registry with the latest published version of each, including
29
- prereleases. Results are sorted by package name. Run this from any directory.
32
+ List registry packages by name and show their latest published versions, including prereleases.
30
33
 
31
- A public registry needs no credentials. For a private registry, sign in with
32
- `gh auth login` or set `GGPM_GITHUB_TOKEN` with **Contents: Read** access to
33
- `FF-OGC/ggpm-registry`.
34
+ ```powershell
35
+ ggpm list
36
+ ```
34
37
 
35
- ### `ggpm publish [path]`
38
+ ### `ggpm init`
36
39
 
37
- Run `ggpm publish path/to/package` to publish a specific package folder.
38
- The path can be absolute or relative to your current directory. With no path,
39
- `ggpm publish` uses the current directory. The selected folder must contain
40
- `ggpackage.json`.
41
- The manifest needs a `Namespace/Name` package name and an exact SemVer version.
42
- Declare dependencies as exact version pins and publish those versions first.
40
+ Create `ggpackage.json` in the current project or package folder. An existing manifest is preserved.
43
41
 
44
- Set `GGPM_GITHUB_TOKEN` to a GitHub token with **Contents: Read and write**
45
- access to `FF-OGC/ggpm-registry`, including permission to update `registry.json`
46
- on the default branch. For example, from PowerShell 7:
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`.
47
49
 
48
50
  ```powershell
49
- $env:GGPM_GITHUB_TOKEN = Read-Host -MaskInput 'GitHub token'
50
- ggpm publish
51
- Remove-Item Env:GGPM_GITHUB_TOKEN
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
52
54
  ```
53
55
 
54
- For `GG/Login@1.0.0`, the command:
55
-
56
- 1. Validates the manifest and confirms that its dependencies are already in
57
- the registry and that this version is available to publish.
58
- 2. Creates a ZIP with `ggpackage.json` at its root, preserves the package's
59
- file paths, and calculates the ZIP's SHA-256 checksum. Dotfiles and dot
60
- directories, `node_modules`, OS metadata, and ZIP and TGZ files in the root
61
- are excluded.
62
- 3. Creates the `GG/Login 1.0.0` GitHub Release with tag `gg-login-v1.0.0` and
63
- uploads `gg-login-1.0.0.zip` as its asset.
64
- 4. Verifies the uploaded ZIP and commits its URL, asset ID, checksum, and
65
- dependencies to `registry.json`. If another publish updated the catalog in
66
- the meantime, the command reloads it and retries the merge.
67
-
68
- If the ZIP upload succeeds but the catalog update fails, rerun `ggpm publish`
69
- with the same package files. It reuses the uploaded ZIP when the checksum
70
- matches. For a version already listed in the catalog, bump the version in
71
- `ggpackage.json` before publishing again.
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
+ ```
72
82
 
73
83
  ## Publish a CLI release
74
84
 
@@ -90,14 +100,3 @@ The tag push starts **Publish ggpm to npm** in the repository's Actions tab.
90
100
  The workflow checks that the tag matches the version in `package.json` before
91
101
  publishing.
92
102
 
93
- ## Planned commands
94
-
95
- - `ggpm init` creates `ggpackage.json` at the root of a Craftland project.
96
- - `ggpm install` installs the packages declared in the project manifest.
97
- - `ggpm install <package-name> [version]` installs a package and records it in
98
- the project manifest. Omitting the version selects the latest stable release.
99
- - `ggpm update` updates installed packages to match the versions in the
100
- project manifest.
101
-
102
- ## Note
103
- Reference example packages for a package
package/bin/ggpm.cjs CHANGED
@@ -12,6 +12,22 @@ if (extraArgs.length === 0 && (flag === '-v' || flag === '--version')) {
12
12
  console.error(`ggpm list: ${error.message}`);
13
13
  process.exitCode = 1;
14
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
+ });
15
31
  } else if (flag === 'publish' && extraArgs.length <= 1) {
16
32
  const [packagePath = '.'] = extraArgs;
17
33
  require('../lib/publish.cjs').publish(resolve(packagePath)).catch((error) => {
@@ -19,6 +35,6 @@ if (extraArgs.length === 0 && (flag === '-v' || flag === '--version')) {
19
35
  process.exitCode = 1;
20
36
  });
21
37
  } else {
22
- console.error('Usage: ggpm -v | ggpm --version | ggpm list | 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]');
23
39
  process.exitCode = 1;
24
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 };
@@ -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 };
@@ -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 CHANGED
@@ -1,46 +1,4 @@
1
- const { isObject, parseVersion, readCatalog } = require('./registry-index.cjs');
2
-
3
- function compareText(left, right) {
4
- return left === right ? 0 : left > right ? 1 : -1;
5
- }
6
-
7
- function compareNumbers(left, right) {
8
- // Version components can exceed JavaScript's safe integer range.
9
- return left.length - right.length || compareText(left, right);
10
- }
11
-
12
- function compareVersions(left, right) {
13
- for (let i = 0; i < left.parts.length; i += 1) {
14
- const order = compareNumbers(left.parts[i], right.parts[i]);
15
- if (order !== 0) return order;
16
- }
17
- if (left.prerelease !== right.prerelease) return left.prerelease ? -1 : 1;
18
-
19
- const leftIds = left.prereleaseParts;
20
- const rightIds = right.prereleaseParts;
21
- for (let i = 0; i < Math.min(leftIds.length, rightIds.length); i += 1) {
22
- const leftIsNumeric = /^\d+$/.test(leftIds[i]);
23
- const rightIsNumeric = /^\d+$/.test(rightIds[i]);
24
- if (leftIsNumeric !== rightIsNumeric) return leftIsNumeric ? -1 : 1;
25
- const order = leftIsNumeric
26
- ? compareNumbers(leftIds[i], rightIds[i])
27
- : compareText(leftIds[i], rightIds[i]);
28
- if (order !== 0) return order;
29
- }
30
- return leftIds.length - rightIds.length;
31
- }
32
-
33
- function latestVersion(name, versions) {
34
- if (!isObject(versions)) throw new Error(`Invalid versions object for ${name} in registry.json.`);
35
-
36
- let latest = null;
37
- for (const version of Object.keys(versions).sort()) {
38
- const parsed = parseVersion(version);
39
- if (!parsed) throw new Error(`Invalid version ${JSON.stringify(version)} for ${name} in registry.json.`);
40
- if (!latest || compareVersions(parsed, latest) > 0) latest = { ...parsed, version };
41
- }
42
- return latest?.version ?? '(no releases)';
43
- }
1
+ const { latestVersion, readCatalog } = require('./registry-index.cjs');
44
2
 
45
3
  async function listPackages() {
46
4
  const { packages } = await readCatalog();
@@ -50,7 +8,7 @@ async function listPackages() {
50
8
  return;
51
9
  }
52
10
 
53
- const rows = names.map((name) => [name, latestVersion(name, packages[name]?.versions)]);
11
+ const rows = names.map((name) => [name, latestVersion(name, packages[name]?.versions) ?? '(no releases)']);
54
12
  const width = names.reduce((max, name) => Math.max(max, name.length), 'PACKAGE'.length);
55
13
  console.log([['PACKAGE', 'LATEST'], ...rows]
56
14
  .map(([name, version]) => `${name.padEnd(width)} ${version}`)
@@ -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,10 +2,12 @@ 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');
6
7
  const { isObject, parseJson, parseVersion, readIndex } = require('./registry-index.cjs');
7
8
 
8
9
  const manifestFile = 'ggpackage.json';
10
+ const publishIgnoreFile = join(__dirname, '..', 'templates', 'publish.ignore');
9
11
  const packageName = /^[a-z0-9][a-z0-9._-]*\/[a-z0-9][a-z0-9._-]*$/i;
10
12
 
11
13
  async function loadPackage(root) {
@@ -51,6 +53,7 @@ async function loadPackage(root) {
51
53
  }
52
54
 
53
55
  async function archivePackage(root, manifest) {
56
+ const exclusions = ignore().add(await readFile(publishIgnoreFile, 'utf8'));
54
57
  const chunks = [];
55
58
  const zip = new Zip((error, data) => {
56
59
  if (error) throw error;
@@ -71,14 +74,14 @@ async function archivePackage(root, manifest) {
71
74
  entries.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
72
75
  for (const entry of entries) {
73
76
  const { name } = entry;
74
- const lowerName = name.toLowerCase();
75
- if (name.startsWith('.') || ['node_modules', '__macosx', 'thumbs.db', 'desktop.ini'].includes(lowerName)) continue;
76
- if (!prefix && (lowerName === manifestFile || /\.(zip|tgz)$/i.test(name))) continue;
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;
77
81
 
78
82
  const path = join(folder, name);
79
- const archivePath = `${prefix}${name}`;
80
83
  if (/[\\:<>"|?*]/.test(name)) throw new Error(`Invalid Windows package path: ${archivePath}`);
81
- if (entry.isDirectory()) await addFolder(path, `${archivePath}/`);
84
+ if (directory) await addFolder(path, `${archivePath}/`);
82
85
  else if (entry.isFile()) addFile(archivePath, await readFile(path));
83
86
  else throw new Error(`Cannot package ${archivePath}: expected a regular file or directory.`);
84
87
  }
@@ -35,10 +35,11 @@ async function readIndex(registry) {
35
35
  return { sha: file.sha, index };
36
36
  }
37
37
 
38
- async function readCatalog() {
38
+ async function openCatalog() {
39
39
  const token = process.env.GGPM_GITHUB_TOKEN?.trim();
40
+ const registry = githubRegistry(token);
40
41
  try {
41
- return (await readIndex(githubRegistry(token))).index;
42
+ return { registry, index: (await readIndex(registry)).index };
42
43
  } catch (error) {
43
44
  if (token || ![403, 404, 429].includes(error.status)) throw error;
44
45
 
@@ -51,8 +52,55 @@ async function readCatalog() {
51
52
  if (!githubToken) {
52
53
  throw new Error(`${error.message}. For an authenticated read, run gh auth login or set GGPM_GITHUB_TOKEN with Contents read access.`);
53
54
  }
54
- return (await readIndex(githubRegistry(githubToken))).index;
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 };
55
102
  }
103
+ return latest?.version ?? null;
56
104
  }
57
105
 
58
- module.exports = { isObject, parseJson, parseVersion, readIndex, readCatalog };
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.1.3",
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,6 @@
1
+ {
2
+ "name": "",
3
+ "version": "0.0.1",
4
+ "description": "",
5
+ "dependencies": {}
6
+ }
@@ -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