@craftland/ggpm 0.1.1 → 0.1.3

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
@@ -2,19 +2,73 @@
2
2
 
3
3
  Package Manager for Craftland Packages
4
4
 
5
- ## Install the CLI
5
+ ## Requirement
6
+ - Nodejs
6
7
 
7
- Once the CLI is published, install it with Node.js and npm:
8
+ ## Install the CLI
8
9
 
9
10
  ```powershell
10
11
  npm install -g @craftland/ggpm
11
12
  ```
12
13
 
13
- The first version supports `ggpm -v` and `ggpm --version`. Both print the
14
- installed CLI version, such as `0.1.0`.
14
+ ## Update the CLI
15
+
16
+ ```
17
+ npm install -g "@craftland/ggpm@latest" --prefer-online
18
+ ```
19
+
20
+ ## Commands
21
+
22
+ ### `ggpm -v` or `ggpm --version`
23
+
24
+ Print the installed CLI version.
25
+
26
+ ### `ggpm list`
27
+
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.
30
+
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
+
35
+ ### `ggpm publish [path]`
36
+
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.
43
+
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:
47
+
48
+ ```powershell
49
+ $env:GGPM_GITHUB_TOKEN = Read-Host -MaskInput 'GitHub token'
50
+ ggpm publish
51
+ Remove-Item Env:GGPM_GITHUB_TOKEN
52
+ ```
53
+
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.
15
67
 
16
- npm distributes the CLI. The separate `ggpm-registry` GitHub repo is the
17
- planned home for `registry.json` and the Craftland package ZIPs.
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.
18
72
 
19
73
  ## Publish a CLI release
20
74
 
@@ -38,14 +92,12 @@ publishing.
38
92
 
39
93
  ## Planned commands
40
94
 
41
- - `ggpm list` shows available packages and their latest versions.
42
95
  - `ggpm init` creates `ggpackage.json` at the root of a Craftland project.
43
96
  - `ggpm install` installs the packages declared in the project manifest.
44
97
  - `ggpm install <package-name> [version]` installs a package and records it in
45
98
  the project manifest. Omitting the version selects the latest stable release.
46
99
  - `ggpm update` updates installed packages to match the versions in the
47
100
  project manifest.
48
- - `ggpm publish` uploads a package ZIP and updates the registry index.
49
101
 
50
102
  ## Note
51
103
  Reference example packages for a package
package/bin/ggpm.cjs CHANGED
@@ -1,12 +1,24 @@
1
1
  #!/usr/bin/env node
2
2
 
3
+ const { resolve } = require('node:path');
3
4
  const { version } = require('../package.json');
4
5
 
5
6
  const [flag, ...extraArgs] = process.argv.slice(2);
6
7
 
7
8
  if (extraArgs.length === 0 && (flag === '-v' || flag === '--version')) {
8
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 === 'publish' && extraArgs.length <= 1) {
16
+ const [packagePath = '.'] = extraArgs;
17
+ require('../lib/publish.cjs').publish(resolve(packagePath)).catch((error) => {
18
+ console.error(`ggpm publish: ${error.message}`);
19
+ process.exitCode = 1;
20
+ });
9
21
  } else {
10
- console.error('Usage: ggpm -v | ggpm --version');
22
+ console.error('Usage: ggpm -v | ggpm --version | ggpm list | ggpm publish [path]');
11
23
  process.exitCode = 1;
12
24
  }
@@ -0,0 +1,50 @@
1
+ const registryRepo = 'FF-OGC/ggpm-registry';
2
+
3
+ function githubRegistry(token) {
4
+ async function request(path, { method = 'GET', json, bytes, upload = false } = {}) {
5
+ const host = upload ? 'uploads.github.com' : 'api.github.com';
6
+ const response = await fetch(`https://${host}/repos/${registryRepo}${path}`, {
7
+ method,
8
+ headers: {
9
+ accept: 'application/vnd.github+json',
10
+ ...(token ? { authorization: `Bearer ${token}` } : {}),
11
+ 'x-github-api-version': '2026-03-10',
12
+ ...(json ? { 'content-type': 'application/json' } : {}),
13
+ ...(bytes ? { 'content-type': 'application/zip' } : {}),
14
+ },
15
+ body: json ? JSON.stringify(json) : bytes,
16
+ redirect: 'error',
17
+ signal: AbortSignal.timeout(120_000),
18
+ }).catch((error) => {
19
+ throw new Error(`GitHub ${method} ${path} failed: ${error.cause?.message ?? error.message}`);
20
+ });
21
+ const result = await response.json().catch(() => null);
22
+ if (!response.ok) {
23
+ const detail = result?.message ?? response.statusText;
24
+ throw Object.assign(new Error(`GitHub ${method} ${path} (${response.status}): ${detail}`), {
25
+ status: response.status,
26
+ });
27
+ }
28
+ return result;
29
+ }
30
+
31
+ return {
32
+ getIndex: () => request('/contents/registry.json'),
33
+ updateIndex: (json) => request('/contents/registry.json', { method: 'PUT', json }),
34
+ async findRelease(tag) {
35
+ try {
36
+ return await request(`/releases/tags/${encodeURIComponent(tag)}`);
37
+ } catch (error) {
38
+ if (error.status === 404) return null;
39
+ throw error;
40
+ }
41
+ },
42
+ createRelease: (json) => request('/releases', { method: 'POST', json }),
43
+ uploadZip: (releaseId, name, bytes) => request(
44
+ `/releases/${releaseId}/assets?${new URLSearchParams({ name })}`,
45
+ { method: 'POST', bytes, upload: true },
46
+ ),
47
+ };
48
+ }
49
+
50
+ module.exports = { githubRegistry, registryRepo };
package/lib/list.cjs ADDED
@@ -0,0 +1,60 @@
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
+ }
44
+
45
+ async function listPackages() {
46
+ const { packages } = await readCatalog();
47
+ const names = Object.keys(packages).sort((left, right) => left.localeCompare(right, 'en'));
48
+ if (names.length === 0) {
49
+ console.log('No packages have been published yet.');
50
+ return;
51
+ }
52
+
53
+ const rows = names.map((name) => [name, latestVersion(name, packages[name]?.versions)]);
54
+ const width = names.reduce((max, name) => Math.max(max, name.length), 'PACKAGE'.length);
55
+ console.log([['PACKAGE', 'LATEST'], ...rows]
56
+ .map(([name, version]) => `${name.padEnd(width)} ${version}`)
57
+ .join('\n'));
58
+ }
59
+
60
+ module.exports = { listPackages };
@@ -0,0 +1,192 @@
1
+ const { createHash } = require('node:crypto');
2
+ const { lstat, readFile, readdir } = require('node:fs/promises');
3
+ const { join } = require('node:path');
4
+ const { Zip, ZipDeflate } = require('fflate');
5
+ const { githubRegistry, registryRepo } = require('./github-registry.cjs');
6
+ const { isObject, parseJson, parseVersion, readIndex } = require('./registry-index.cjs');
7
+
8
+ const manifestFile = 'ggpackage.json';
9
+ const packageName = /^[a-z0-9][a-z0-9._-]*\/[a-z0-9][a-z0-9._-]*$/i;
10
+
11
+ async function loadPackage(root) {
12
+ const path = join(root, manifestFile);
13
+ const info = await lstat(path).catch((error) => {
14
+ if (error.code === 'ENOENT' || error.code === 'ENOTDIR') {
15
+ throw new Error(`Could not find ${manifestFile} in package folder ${root}.`);
16
+ }
17
+ throw error;
18
+ });
19
+ if (!info.isFile()) throw new Error(`${manifestFile} must be a regular file.`);
20
+
21
+ const bytes = await readFile(path);
22
+ const manifest = parseJson(bytes, manifestFile);
23
+ if (!isObject(manifest)) throw new Error(`${manifestFile} must contain an object.`);
24
+
25
+ const { name, version, dependencies = {} } = manifest;
26
+ if (typeof name !== 'string' || name !== name.trim() || !packageName.test(name)) {
27
+ throw new Error(`${manifestFile} needs a package name in Namespace/Name format, such as GG/Login.`);
28
+ }
29
+ const parsed = parseVersion(version);
30
+ if (!parsed) throw new Error(`${manifestFile} needs an exact SemVer version, such as 1.0.0.`);
31
+ if (!isObject(dependencies)) throw new Error(`${manifestFile} dependencies must be an object.`);
32
+ for (const [dependency, pin] of Object.entries(dependencies)) {
33
+ if (dependency !== dependency.trim() || !packageName.test(dependency) || !parseVersion(pin)) {
34
+ throw new Error(`Invalid dependency ${JSON.stringify(dependency)}. Use Namespace/Name and an exact version.`);
35
+ }
36
+ if (dependency.toLowerCase() === name.toLowerCase()) {
37
+ throw new Error(`${name} cannot depend on itself.`);
38
+ }
39
+ }
40
+
41
+ // Escape separators within a name segment so A-B/C and A/B-C produce distinct tags.
42
+ const slug = name.toLowerCase().split('/').map((part) =>
43
+ part.replace(/[^a-z0-9]/g, (character) => `_${character.charCodeAt(0).toString(16)}`),
44
+ ).join('-');
45
+ return {
46
+ name, version, dependencies, bytes, prerelease: parsed.prerelease,
47
+ description: typeof manifest.description === 'string' ? manifest.description : '',
48
+ tag: `${slug}-v${version}`,
49
+ assetName: `${slug}-${version.replace('+', '_')}.zip`,
50
+ };
51
+ }
52
+
53
+ async function archivePackage(root, manifest) {
54
+ const chunks = [];
55
+ const zip = new Zip((error, data) => {
56
+ if (error) throw error;
57
+ chunks.push(data);
58
+ });
59
+ // Stable timestamps and entry order let an unchanged package reuse an uploaded ZIP.
60
+ const mtime = new Date(2000, 0, 1, 12);
61
+
62
+ function addFile(name, bytes) {
63
+ const file = new ZipDeflate(name);
64
+ file.mtime = mtime;
65
+ zip.add(file);
66
+ file.push(bytes, true);
67
+ }
68
+
69
+ async function addFolder(folder, prefix = '') {
70
+ const entries = await readdir(folder, { withFileTypes: true });
71
+ entries.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
72
+ for (const entry of entries) {
73
+ 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
+
78
+ const path = join(folder, name);
79
+ const archivePath = `${prefix}${name}`;
80
+ if (/[\\:<>"|?*]/.test(name)) throw new Error(`Invalid Windows package path: ${archivePath}`);
81
+ if (entry.isDirectory()) await addFolder(path, `${archivePath}/`);
82
+ else if (entry.isFile()) addFile(archivePath, await readFile(path));
83
+ else throw new Error(`Cannot package ${archivePath}: expected a regular file or directory.`);
84
+ }
85
+ }
86
+
87
+ addFile(manifestFile, manifest.bytes);
88
+ await addFolder(root);
89
+ zip.end();
90
+ return Buffer.concat(chunks);
91
+ }
92
+
93
+ function packageRecord(index, { name, dependencies }) {
94
+ const existingName = Object.keys(index.packages).find((key) => key.toLowerCase() === name.toLowerCase());
95
+ if (existingName && existingName !== name) {
96
+ throw new Error(`Use the existing registry spelling ${existingName} instead of ${name}.`);
97
+ }
98
+ const record = index.packages[name] ?? { versions: {} };
99
+ if (!isObject(record.versions)) throw new Error(`Invalid versions object for ${name} in registry.json.`);
100
+ for (const [dependency, pin] of Object.entries(dependencies)) {
101
+ const versions = index.packages[dependency]?.versions;
102
+ if (!isObject(versions) || !Object.hasOwn(versions, pin)) {
103
+ throw new Error(`Publish ${dependency}@${pin} before publishing ${name}.`);
104
+ }
105
+ }
106
+ return record;
107
+ }
108
+
109
+ async function publishAsset(registry, manifest, archive, sha256) {
110
+ const { tag, assetName, name, version, prerelease } = manifest;
111
+ let release = await registry.findRelease(tag);
112
+ if (!release) {
113
+ try {
114
+ release = await registry.createRelease({ tag_name: tag, name: `${name} ${version}`, prerelease, make_latest: 'false' });
115
+ } catch (error) {
116
+ if (error.status !== 422) throw error;
117
+ release = await registry.findRelease(tag);
118
+ if (!release) throw error;
119
+ }
120
+ }
121
+ if (!release?.id || release.draft) throw new Error(`Release ${tag} must be published before use.`);
122
+
123
+ let asset = release.assets?.find((item) => item.name === assetName);
124
+ if (!asset) {
125
+ try {
126
+ asset = await registry.uploadZip(release.id, assetName, archive);
127
+ } catch (error) {
128
+ if (error.status !== 422) throw error;
129
+ release = await registry.findRelease(tag);
130
+ asset = release?.assets?.find((item) => item.name === assetName);
131
+ if (!asset) throw error;
132
+ }
133
+ }
134
+ if (asset?.state === 'starter') {
135
+ throw new Error(`Release ${tag} has an incomplete upload for ${assetName}. Remove the empty asset on GitHub and retry.`);
136
+ }
137
+ if (asset?.state !== 'uploaded' || asset.digest !== `sha256:${sha256}` || !asset.id || !asset.browser_download_url) {
138
+ throw new Error(`Could not verify the uploaded ZIP for ${tag}. Existing assets are never overwritten.`);
139
+ }
140
+ return { releaseTag: tag, assetId: asset.id, url: asset.browser_download_url, sha256 };
141
+ }
142
+
143
+ async function updateIndex(registry, snapshot, manifest, asset) {
144
+ const { name, version, dependencies, description } = manifest;
145
+ for (let attempt = 0; attempt < 3; attempt += 1) {
146
+ const { index, sha } = snapshot;
147
+ const record = packageRecord(index, manifest);
148
+ if (Object.hasOwn(record.versions, version)) {
149
+ const existing = record.versions[version];
150
+ if (existing?.sha256 === asset.sha256 && existing.assetId === asset.assetId) return;
151
+ throw new Error(`${name}@${version} already exists in the registry. Bump the package version.`);
152
+ }
153
+ record.versions[version] = { ...asset, dependencies, ...(description ? { description } : {}) };
154
+ index.packages[name] = record;
155
+ try {
156
+ await registry.updateIndex({
157
+ sha,
158
+ message: `Publish ${name}@${version}`,
159
+ content: Buffer.from(`${JSON.stringify(index, null, 2)}\n`).toString('base64'),
160
+ });
161
+ return;
162
+ } catch (error) {
163
+ if (![409, 422].includes(error.status) || attempt === 2) throw error;
164
+ snapshot = await readIndex(registry);
165
+ if (snapshot.sha === sha) throw error;
166
+ }
167
+ }
168
+ }
169
+
170
+ async function publish(root, token = process.env.GGPM_GITHUB_TOKEN?.trim()) {
171
+ const manifest = await loadPackage(root);
172
+ if (!token) throw new Error(`Set GGPM_GITHUB_TOKEN with Contents write access to ${registryRepo}.`);
173
+
174
+ const registry = githubRegistry(token);
175
+ const snapshot = await readIndex(registry);
176
+ const { name, version, tag } = manifest;
177
+ if (Object.hasOwn(packageRecord(snapshot.index, manifest).versions, version)) {
178
+ throw new Error(`${name}@${version} already exists in the registry. Bump the package version.`);
179
+ }
180
+
181
+ const archive = await archivePackage(root, manifest);
182
+ const sha256 = createHash('sha256').update(archive).digest('hex');
183
+ const asset = await publishAsset(registry, manifest, archive, sha256);
184
+ try {
185
+ await updateIndex(registry, snapshot, manifest, asset);
186
+ } catch (error) {
187
+ throw new Error(`The ZIP is available on release ${tag}, but registry.json could not be updated. Rerun ggpm publish with the same package files. ${error.message}`);
188
+ }
189
+ console.log(`Published ${name}@${version} to ${registryRepo}\n${asset.url}`);
190
+ }
191
+
192
+ module.exports = { publish };
@@ -0,0 +1,58 @@
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 readCatalog() {
39
+ const token = process.env.GGPM_GITHUB_TOKEN?.trim();
40
+ try {
41
+ return (await readIndex(githubRegistry(token))).index;
42
+ } catch (error) {
43
+ if (token || ![403, 404, 429].includes(error.status)) throw error;
44
+
45
+ // Public reads need no GitHub CLI session. Try it only when GitHub denies anonymous access.
46
+ const login = await execFileAsync('gh', ['auth', 'token', '--hostname', 'github.com'], {
47
+ timeout: 5_000,
48
+ windowsHide: true,
49
+ }).catch(() => null);
50
+ const githubToken = login?.stdout.trim();
51
+ if (!githubToken) {
52
+ throw new Error(`${error.message}. For an authenticated read, run gh auth login or set GGPM_GITHUB_TOKEN with Contents read access.`);
53
+ }
54
+ return (await readIndex(githubRegistry(githubToken))).index;
55
+ }
56
+ }
57
+
58
+ module.exports = { isObject, parseJson, parseVersion, readIndex, readCatalog };
package/package.json CHANGED
@@ -1,14 +1,21 @@
1
1
  {
2
2
  "name": "@craftland/ggpm",
3
- "version": "0.1.1",
3
+ "version": "0.1.3",
4
4
  "description": "Package manager for Craftland projects",
5
5
  "bin": {
6
6
  "ggpm": "bin/ggpm.cjs"
7
7
  },
8
8
  "files": [
9
- "bin/ggpm.cjs"
9
+ "bin/ggpm.cjs",
10
+ "lib/"
10
11
  ],
12
+ "engines": {
13
+ "node": ">=18"
14
+ },
11
15
  "publishConfig": {
12
16
  "access": "public"
17
+ },
18
+ "dependencies": {
19
+ "fflate": "0.8.3"
13
20
  }
14
21
  }