@slim-lang/spm 0.0.0-stage → 1.0.1

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
@@ -1,3 +1,42 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
1
+ # slim-spm
2
+
3
+ The package manager of [Slim](https://github.com/cdmtn/slim-lang): installs packages from GitHub into a project, locks their versions and publishes your own.
4
+
5
+ ## Setup
6
+
7
+ ```console
8
+ npm i -g @slim-lang/spm
9
+ spm --version
10
+ ```
11
+
12
+ Requires Node.js 22.12+ and Git. The compiler (`@slim-lang/core`) is a separate package and doesn't need spm.
13
+
14
+ ## Quick example
15
+
16
+ ```console
17
+ spm i std
18
+ ```
19
+
20
+ ```js
21
+ use { positive } from @std/types/numerical
22
+ use { int } from @std/converters
23
+
24
+ let pages: positive = int("12")
25
+ ```
26
+
27
+ `spm i std` downloads the `std` package into `packages/std` and records the exact commit in `spm.lock.json`.
28
+
29
+ ## Documentation
30
+
31
+ The full guide is in [`docs/`](docs/index.md):
32
+
33
+ - [Getting started](docs/01-start.md): installing spm and a package, what happens on the way
34
+ - [Commands](docs/02-commands.md): every command and option
35
+ - [Versions and the lockfile](docs/03-versions.md): `spm.lock.json`, `verify`, `--latest`
36
+ - [Publishing](docs/04-publishing.md): the `.spm` file, `create`, `publish`, the registry
37
+
38
+ ## Tests
39
+
40
+ ```console
41
+ npm test
42
+ ```
package/package.json CHANGED
@@ -1,6 +1,38 @@
1
- {
2
- "name": "@slim-lang/spm",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
1
+ {
2
+ "name": "@slim-lang/spm",
3
+ "version": "1.0.1",
4
+ "description": "Slim Package Manager: installs, locks and publishes Slim packages",
5
+ "type": "module",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/cdmtn/slim-spm.git"
9
+ },
10
+ "engines": {
11
+ "node": ">=22.12.0"
12
+ },
13
+ "bin": {
14
+ "spm": "./src/cli.js"
15
+ },
16
+ "files": [
17
+ "src",
18
+ "README.md"
19
+ ],
20
+ "scripts": {
21
+ "test": "node --test test/*.test.mjs",
22
+ "release:patch": "npm version patch && git push --follow-tags && npm publish",
23
+ "release:minor": "npm version minor && git push --follow-tags && npm publish",
24
+ "release:major": "npm version major && git push --follow-tags && npm publish"
25
+ },
26
+ "keywords": [
27
+ "slim",
28
+ "package-manager"
29
+ ],
30
+ "license": "ISC",
31
+ "dependencies": {
32
+ "chalk": "^6.0.0",
33
+ "commander": "^15.0.0",
34
+ "keytar": "^7.9.0",
35
+ "open": "^11.0.1",
36
+ "tar": "^7.5.22"
37
+ }
38
+ }
@@ -0,0 +1,89 @@
1
+ import { formatBold, formatItalic } from "../helpers.js";
2
+
3
+ const CLIENT_ID = "Iv23lijjcVMtJwfS18dj";
4
+
5
+ const DEVICE_URL = "https://github.com/login/device/code";
6
+ const TOKEN_URL = "https://github.com/login/oauth/access_token";
7
+
8
+ export async function loginGitHub() {
9
+ if (!CLIENT_ID) {
10
+ throw new Error("GITHUB_CLIENT_ID is not configured");
11
+ }
12
+
13
+ const response = await fetch(DEVICE_URL, {
14
+ method: "POST",
15
+ headers: {
16
+ "Accept": "application/json",
17
+ "Content-Type": "application/x-www-form-urlencoded"
18
+ },
19
+ body: new URLSearchParams({
20
+ client_id: CLIENT_ID
21
+ })
22
+ });
23
+
24
+ if (!response.ok) {
25
+ throw new Error("Failed to start GitHub authorization");
26
+ }
27
+
28
+ const data = await response.json();
29
+
30
+ console.log("\n");
31
+ console.log("Open:", formatItalic.underline(data.verification_uri));
32
+ console.log(`Code: ${formatBold(data.user_code)}`);
33
+ console.log("");
34
+ console.log("Open the link and paste the code into the fields you see. Then, follow the steps");
35
+
36
+ let interval = data.interval || 5;
37
+
38
+ while (true) {
39
+ await sleep(interval * 1000);
40
+
41
+ const tokenResponse = await fetch(TOKEN_URL, {
42
+ method: "POST",
43
+ headers: {
44
+ "Accept": "application/json",
45
+ "Content-Type": "application/x-www-form-urlencoded"
46
+ },
47
+ body: new URLSearchParams({
48
+ client_id: CLIENT_ID,
49
+ device_code: data.device_code,
50
+ grant_type:
51
+ "urn:ietf:params:oauth:grant-type:device_code"
52
+ })
53
+ });
54
+
55
+ const tokenData = await tokenResponse.json();
56
+
57
+ if (tokenData.access_token) {
58
+ return tokenData.access_token;
59
+ }
60
+
61
+ if (tokenData.error === "authorization_pending") {
62
+ continue;
63
+ }
64
+
65
+ if (tokenData.error === "slow_down") {
66
+ interval += 5;
67
+ continue;
68
+ }
69
+
70
+ if (tokenData.error === "access_denied") {
71
+ throw new Error("GitHub authorization denied");
72
+ }
73
+
74
+ if (
75
+ tokenData.error === "expired_token"
76
+ ) {
77
+ throw new Error("GitHub authorization expired");
78
+ }
79
+
80
+ throw new Error(
81
+ tokenData.error_description ||
82
+ "GitHub authorization failed"
83
+ );
84
+ }
85
+ }
86
+
87
+ function sleep(ms) {
88
+ return new Promise(resolve => setTimeout(resolve, ms));
89
+ }
@@ -0,0 +1,244 @@
1
+ import { GITHUB_API, githubHeaders } from "./github_req.js";
2
+
3
+ import fs from "node:fs";
4
+ import path from "node:path";
5
+ import os from "node:os";
6
+ import { pipeline } from "node:stream/promises";
7
+ import { createWriteStream } from "node:fs";
8
+ import { createHash } from "node:crypto";
9
+ import * as tar from 'tar'
10
+
11
+ export async function getGitHubUser(token) {
12
+ const response = await fetch(
13
+ `${GITHUB_API}/user`,
14
+ {
15
+ headers: githubHeaders(token)
16
+ }
17
+ );
18
+
19
+ if (!response.ok) {
20
+ throw new Error("GitHub token is invalid");
21
+ }
22
+
23
+ return response.json();
24
+ }
25
+
26
+ export async function getGitHubRepo(token, repo) {
27
+ const response = await fetch(
28
+ `${GITHUB_API}/repos/${repo}`,
29
+ {
30
+ headers: githubHeaders(token)
31
+ }
32
+ );
33
+
34
+ if (!response.ok) {
35
+ throw new Error(
36
+ `GitHub repository "${repo}" not found`
37
+ );
38
+ }
39
+
40
+ return response.json();
41
+ }
42
+
43
+ export async function getPermission(token, repo, username) {
44
+ const response = await fetch(
45
+ `${GITHUB_API}/repos/${repo}/collaborators/${username}/permission`,
46
+ {
47
+ headers: githubHeaders(token)
48
+ }
49
+ );
50
+
51
+ if (!response.ok) {
52
+ throw new Error(
53
+ "Unable to verify repository permissions"
54
+ );
55
+ }
56
+
57
+ return response.json();
58
+ }
59
+
60
+ const MAX_PACKAGE_BYTES = 200 * 1024 * 1024
61
+ const MAX_PACKAGE_FILES = 20000
62
+ const SAFE_ENTRY_TYPES = new Set(["File", "OldFile", "ContiguousFile", "Directory"])
63
+
64
+ function isInside(root, target) {
65
+ const relative = path.relative(root, target)
66
+ return relative === "" || (!relative.startsWith("..") && !path.isAbsolute(relative))
67
+ }
68
+
69
+ export async function extractTarGz(file, destination) {
70
+ const root = path.resolve(destination)
71
+ const rejected = []
72
+ let bytes = 0
73
+ let files = 0
74
+
75
+ await tar.x({
76
+ file,
77
+ cwd: root,
78
+ strip: 1,
79
+ strict: true,
80
+ preservePaths: false,
81
+ filter: (entryPath, entry) => {
82
+ const parts = entryPath.split(/[\\/]+/).slice(1)
83
+ const target = path.resolve(root, ...parts)
84
+ if (!SAFE_ENTRY_TYPES.has(entry.type)) {
85
+ rejected.push(`${entryPath} (${entry.type})`)
86
+ return false
87
+ }
88
+ if (parts.includes("..") || path.isAbsolute(entryPath) || !isInside(root, target)) {
89
+ rejected.push(entryPath)
90
+ return false
91
+ }
92
+ bytes += entry.size ?? 0
93
+ files++
94
+ return bytes <= MAX_PACKAGE_BYTES && files <= MAX_PACKAGE_FILES
95
+ }
96
+ });
97
+
98
+ if (bytes > MAX_PACKAGE_BYTES || files > MAX_PACKAGE_FILES) {
99
+ throw new Error(`The package is too large (${files} files, ${Math.round(bytes / 1024 / 1024)} MB)`)
100
+ }
101
+ return rejected
102
+ }
103
+
104
+ function listFiles(dir, base = dir, found = []) {
105
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
106
+ const full = path.join(dir, entry.name)
107
+ if (entry.isDirectory()) listFiles(full, base, found)
108
+ else if (entry.isFile()) found.push(path.relative(base, full).split(path.sep).join("/"))
109
+ }
110
+ return found
111
+ }
112
+
113
+ export function packageIntegrity(dir) {
114
+ const total = createHash("sha256")
115
+ for (const file of listFiles(dir).sort()) {
116
+ const content = createHash("sha256").update(fs.readFileSync(path.join(dir, file))).digest("hex")
117
+ total.update(`${file}\0${content}\n`)
118
+ }
119
+ return `sha256-${total.digest("base64")}`
120
+ }
121
+
122
+ async function resolveCommit(token, owner, repo, ref) {
123
+ const response = await fetch(
124
+ `${GITHUB_API}/repos/${owner}/${repo}/commits/${encodeURIComponent(ref)}`,
125
+ {
126
+ headers: githubHeaders(token)
127
+ }
128
+ );
129
+
130
+ if (!response.ok) {
131
+ const data = await response.json().catch(() => null);
132
+ const failure = new Error(data?.message ? `${ref}: ${data.message}` : `Can't find ${ref} in ${owner}/${repo}`);
133
+ failure.missing = response.status === 404 || response.status === 422;
134
+ throw failure;
135
+ }
136
+
137
+ const data = await response.json();
138
+ if (typeof data?.sha !== "string" || !/^[0-9a-f]{40}$/.test(data.sha)) throw new Error(`GitHub returned no commit for ${ref}`);
139
+ return data.sha;
140
+ }
141
+
142
+ export async function downloadGitHubRepo(
143
+ token,
144
+ repository,
145
+ destination,
146
+ version = null,
147
+ locked = null,
148
+ { fallbackToMain = false } = {}
149
+ ) {
150
+ const match = repository.match(
151
+ /^([a-zA-Z0-9-]+)\/([a-zA-Z0-9._-]+)$/
152
+ );
153
+
154
+ if (!match) {
155
+ return {
156
+ success: false,
157
+ msg: "Repository must have format user/repo"
158
+ };
159
+ }
160
+
161
+ const [, owner, repo] = match;
162
+ const target = path.resolve(destination);
163
+ const staging = `${target}.spm-${process.pid}-${Date.now()}`;
164
+ const tempFile = path.join(
165
+ os.tmpdir(),
166
+ `spm-${owner}-${repo}-${Date.now()}.tar.gz`
167
+ );
168
+
169
+ try {
170
+ let untagged = false;
171
+ let commit = locked?.commit && /^[0-9a-f]{40}$/.test(locked.commit) ? locked.commit : null;
172
+ if (!commit && version) {
173
+ try {
174
+ commit = await resolveCommit(token, owner, repo, `v${version}`);
175
+ }
176
+ catch (tagError) {
177
+ if (!tagError.missing || !fallbackToMain) throw tagError;
178
+ untagged = true;
179
+ }
180
+ }
181
+ if (!commit) commit = await resolveCommit(token, owner, repo, "main");
182
+
183
+ const response = await fetch(
184
+ `${GITHUB_API}/repos/${owner}/${repo}/tarball/${commit}`,
185
+ {
186
+ headers: githubHeaders(token)
187
+ }
188
+ );
189
+
190
+ if (!response.ok) {
191
+ const data = await response.json().catch(() => null);
192
+
193
+ return {
194
+ success: false,
195
+ msg: data?.message || `GitHub API error: ${response.status}`
196
+ };
197
+ }
198
+
199
+ await pipeline(response.body, createWriteStream(tempFile));
200
+ await fs.promises.mkdir(staging, { recursive: true });
201
+ const rejected = await extractTarGz(tempFile, staging);
202
+ const integrity = packageIntegrity(staging);
203
+
204
+ if (locked?.integrity && locked.integrity !== integrity) {
205
+ return {
206
+ success: false,
207
+ msg: `Integrity check failed for ${repository}@${commit.slice(0, 7)}: expected ${locked.integrity}, got ${integrity}. The package changed since it was locked; remove it from spm.lock.json to accept the new contents`
208
+ };
209
+ }
210
+
211
+ const backup = fs.existsSync(target) ? `${target}.spm-old-${process.pid}-${Date.now()}` : null;
212
+ if (backup) await fs.promises.rename(target, backup);
213
+ try {
214
+ await fs.promises.rename(staging, target);
215
+ }
216
+ catch (swapError) {
217
+ if (backup) await fs.promises.rename(backup, target).catch(() => {});
218
+ throw swapError;
219
+ }
220
+ if (backup) await fs.promises.rm(backup, { recursive: true, force: true }).catch(() => {});
221
+
222
+ return {
223
+ success: true,
224
+ msg: `Repository ${repository} downloaded`,
225
+ path: target,
226
+ commit,
227
+ integrity,
228
+ rejected,
229
+ untagged
230
+ };
231
+ }
232
+ catch (error) {
233
+ return {
234
+ success: false,
235
+ msg: error instanceof Error
236
+ ? error.message
237
+ : String(error)
238
+ };
239
+ }
240
+ finally {
241
+ await fs.promises.rm(tempFile, { force: true });
242
+ await fs.promises.rm(staging, { recursive: true, force: true });
243
+ }
244
+ }
@@ -0,0 +1,272 @@
1
+ import fs from "node:fs/promises";
2
+ import { createHash } from "node:crypto";
3
+
4
+ export const GITHUB_API = "https://api.github.com";
5
+ export const API_VERSION = "2026-03-10";
6
+
7
+ export function githubHeaders(token, extra = {}) {
8
+ return {
9
+ Accept: "application/vnd.github+json",
10
+ ...(token ? { Authorization: `Bearer ${token}` } : {}),
11
+ "X-GitHub-Api-Version": API_VERSION,
12
+ ...extra
13
+ };
14
+ }
15
+
16
+ export async function githubRequest(token, url, options = {}) {
17
+ const response = await fetch(`${GITHUB_API}${url}`, {
18
+ ...options,
19
+ headers: githubHeaders(token, {
20
+ "Content-Type": "application/json",
21
+ ...options.headers
22
+ })
23
+ });
24
+
25
+ const data = response.status === 204 ? null : await response.json().catch(() => null);
26
+
27
+ if (!response.ok) {
28
+ const error = new Error(data?.message || `GitHub API error: ${response.status}`);
29
+ error.status = response.status;
30
+ throw error;
31
+ }
32
+
33
+ return data;
34
+ }
35
+
36
+ export function gitBlobSha(content) {
37
+ return createHash("sha1").update(`blob ${content.length}\0`).update(content).digest("hex");
38
+ }
39
+
40
+ export async function getBranchHead(token, repo, branch) {
41
+ const reference = await githubRequest(token, `/repos/${repo}/git/ref/heads/${encodeURIComponent(branch)}`);
42
+ const commit = await githubRequest(token, `/repos/${repo}/git/commits/${reference.object.sha}`);
43
+ return { commit: commit.sha, tree: commit.tree.sha };
44
+ }
45
+
46
+ export async function tagExists(token, repo, tag) {
47
+ try {
48
+ await githubRequest(token, `/repos/${repo}/git/ref/tags/${encodeURIComponent(tag)}`);
49
+ return true;
50
+ }
51
+ catch (error) {
52
+ if (error.status === 404) return false;
53
+ throw error;
54
+ }
55
+ }
56
+
57
+ async function remoteBlobs(token, repo, treeSha) {
58
+ const tree = await githubRequest(token, `/repos/${repo}/git/trees/${treeSha}?recursive=1`);
59
+ return new Set((tree?.tree ?? []).filter(entry => entry.type === "blob").map(entry => entry.sha));
60
+ }
61
+
62
+ export async function commitPackage({ token, repo, branch, parent, files, message }) {
63
+ if (files.length === 0) throw new Error("Package directory is empty");
64
+
65
+ const existing = await remoteBlobs(token, repo, parent.tree);
66
+ const tree = [];
67
+
68
+ for (const file of files) {
69
+ const content = await fs.readFile(file.fullPath);
70
+ let sha = gitBlobSha(content);
71
+
72
+ if (!existing.has(sha)) {
73
+ const blob = await githubRequest(token, `/repos/${repo}/git/blobs`, {
74
+ method: "POST",
75
+ body: JSON.stringify({ content: content.toString("base64"), encoding: "base64" })
76
+ });
77
+ sha = blob.sha;
78
+ }
79
+
80
+ tree.push({ path: file.path, mode: "100644", type: "blob", sha });
81
+ }
82
+
83
+ const newTree = await githubRequest(token, `/repos/${repo}/git/trees`, {
84
+ method: "POST",
85
+ body: JSON.stringify({ tree })
86
+ });
87
+
88
+ if (newTree.sha === parent.tree) {
89
+ return { commit: parent.commit, tree: newTree.sha, changed: false };
90
+ }
91
+
92
+ const commit = await githubRequest(token, `/repos/${repo}/git/commits`, {
93
+ method: "POST",
94
+ body: JSON.stringify({ message, tree: newTree.sha, parents: [parent.commit] })
95
+ });
96
+
97
+ await githubRequest(token, `/repos/${repo}/git/refs/heads/${encodeURIComponent(branch)}`, {
98
+ method: "PATCH",
99
+ body: JSON.stringify({ sha: commit.sha })
100
+ });
101
+
102
+ return { commit: commit.sha, tree: newTree.sha, changed: true };
103
+ }
104
+
105
+ export async function createGitHubTag(token, repo, version, commit) {
106
+ try {
107
+ await githubRequest(token, `/repos/${repo}/git/refs`, {
108
+ method: "POST",
109
+ body: JSON.stringify({ ref: `refs/tags/v${version}`, sha: commit })
110
+ });
111
+ return { success: true, tag: `v${version}` };
112
+ }
113
+ catch (error) {
114
+ return { success: false, msg: error instanceof Error ? error.message : String(error) };
115
+ }
116
+ }
117
+
118
+ export async function createGitHubRepo(token, repository, organization = false) {
119
+ const match = repository.match(
120
+ /^([a-zA-Z0-9-]+)\/([a-zA-Z0-9._-]+)$/
121
+ );
122
+
123
+ if (!match) {
124
+ return {
125
+ success: false,
126
+ msg: "Repository must have format user/repo"
127
+ };
128
+ }
129
+
130
+ const [, owner, repo] = match;
131
+
132
+ try {
133
+ const check = await fetch(
134
+ `${GITHUB_API}/repos/${owner}/${repo}`,
135
+ {
136
+ headers: githubHeaders(token)
137
+ }
138
+ );
139
+
140
+ if (check.ok) {
141
+ return {
142
+ success: false,
143
+ msg: `Repository ${repository} already exists`
144
+ };
145
+ }
146
+
147
+ if (check.status !== 404) {
148
+ const data = await check.json();
149
+
150
+ return {
151
+ success: false,
152
+ msg: data.message || `GitHub API error: ${check.status}`
153
+ };
154
+ }
155
+
156
+ if (!organization) {
157
+ const userResponse = await fetch(
158
+ `${GITHUB_API}/user`,
159
+ {
160
+ headers: githubHeaders(token)
161
+ }
162
+ );
163
+
164
+ if (!userResponse.ok) {
165
+ const data = await userResponse.json();
166
+
167
+ return {
168
+ success: false,
169
+ msg: data.message || "Failed to get GitHub user"
170
+ };
171
+ }
172
+
173
+ const user = await userResponse.json();
174
+
175
+ if (user.login.toLowerCase() !== owner.toLowerCase()) {
176
+ return {
177
+ success: false,
178
+ msg: `You cannot create ${repository}. Your GitHub account is ${user.login}`
179
+ };
180
+ }
181
+ }
182
+
183
+ const createUrl = organization
184
+ ? `${GITHUB_API}/orgs/${owner}/repos`
185
+ : `${GITHUB_API}/user/repos`;
186
+
187
+ const response = await fetch(
188
+ createUrl,
189
+ {
190
+ method: "POST",
191
+ headers: githubHeaders(token, {
192
+ "Content-Type": "application/json"
193
+ }),
194
+ body: JSON.stringify({
195
+ name: repo,
196
+ private: false,
197
+ auto_init: true
198
+ })
199
+ }
200
+ );
201
+
202
+ const data = await response.json();
203
+
204
+ if (!response.ok) {
205
+ return {
206
+ success: false,
207
+ msg: data.message || `GitHub API error: ${response.status}`
208
+ };
209
+ }
210
+
211
+ return {
212
+ success: true,
213
+ msg: `Repository ${repository} created`,
214
+ repo: data
215
+ };
216
+ }
217
+ catch (error) {
218
+ return {
219
+ success: false,
220
+ msg: error instanceof Error
221
+ ? error.message
222
+ : String(error)
223
+ };
224
+ }
225
+ }
226
+
227
+ export async function deleteGitHubRepo(token, repository) {
228
+ const match = repository.match(
229
+ /^([a-zA-Z0-9-]+)\/([a-zA-Z0-9._-]+)$/
230
+ );
231
+
232
+ if (!match) {
233
+ return {
234
+ success: false,
235
+ msg: "Repository must have format user/repo"
236
+ };
237
+ }
238
+
239
+ const [, owner, repo] = match;
240
+
241
+ try {
242
+ const response = await fetch(
243
+ `${GITHUB_API}/repos/${owner}/${repo}`,
244
+ {
245
+ method: "DELETE",
246
+ headers: githubHeaders(token)
247
+ }
248
+ );
249
+
250
+ if (response.status === 204) {
251
+ return {
252
+ success: true,
253
+ msg: `Repository ${repository} deleted`
254
+ };
255
+ }
256
+
257
+ const data = await response.json().catch(() => null);
258
+
259
+ return {
260
+ success: false,
261
+ msg: data?.message || `GitHub API error: ${response.status}`
262
+ };
263
+ }
264
+ catch (error) {
265
+ return {
266
+ success: false,
267
+ msg: error instanceof Error
268
+ ? error.message
269
+ : String(error)
270
+ };
271
+ }
272
+ }