@slim-lang/spm 1.0.0 → 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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@slim-lang/spm",
3
- "version": "1.0.0",
3
+ "version": "1.0.1",
4
4
  "description": "Slim Package Manager: installs, locks and publishes Slim packages",
5
5
  "type": "module",
6
6
  "repository": {
@@ -1,5 +1,5 @@
1
1
  import fs from "node:fs/promises";
2
- import path from "node:path";
2
+ import { createHash } from "node:crypto";
3
3
 
4
4
  export const GITHUB_API = "https://api.github.com";
5
5
  export const API_VERSION = "2026-03-10";
@@ -25,74 +25,81 @@ export async function githubRequest(token, url, options = {}) {
25
25
  const data = response.status === 204 ? null : await response.json().catch(() => null);
26
26
 
27
27
  if (!response.ok) {
28
- throw new Error(data?.message || `GitHub API error: ${response.status}`);
28
+ const error = new Error(data?.message || `GitHub API error: ${response.status}`);
29
+ error.status = response.status;
30
+ throw error;
29
31
  }
30
32
 
31
33
  return data;
32
34
  }
33
35
 
34
- async function getFiles(dir, base = dir) {
35
- const files = [];
36
+ export function gitBlobSha(content) {
37
+ return createHash("sha1").update(`blob ${content.length}\0`).update(content).digest("hex");
38
+ }
36
39
 
37
- for (const entry of await fs.readdir(dir, { withFileTypes: true })) {
38
- const fullPath = path.join(dir, entry.name);
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
+ }
39
45
 
40
- if (entry.isDirectory()) files.push(...await getFiles(fullPath, base));
41
- else if (entry.isFile()) files.push({ path: path.relative(base, fullPath).replaceAll("\\", "/"), fullPath });
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;
42
54
  }
55
+ }
43
56
 
44
- return files;
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));
45
60
  }
46
61
 
47
- async function commitDirectory({ token, repo, dir, message, branch = "main" }) {
48
- const files = await getFiles(dir);
62
+ export async function commitPackage({ token, repo, branch, parent, files, message }) {
49
63
  if (files.length === 0) throw new Error("Package directory is empty");
50
64
 
51
- const reference = await githubRequest(token, `/repos/${repo}/git/ref/heads/${branch}`);
52
- const parentSha = reference.object.sha;
53
- const parentCommit = await githubRequest(token, `/repos/${repo}/git/commits/${parentSha}`);
54
-
65
+ const existing = await remoteBlobs(token, repo, parent.tree);
55
66
  const tree = [];
67
+
56
68
  for (const file of files) {
57
- const blob = await githubRequest(token, `/repos/${repo}/git/blobs`, {
58
- method: "POST",
59
- body: JSON.stringify({ content: await fs.readFile(file.fullPath, "base64"), encoding: "base64" })
60
- });
61
- tree.push({ path: file.path, mode: "100644", type: "blob", sha: blob.sha });
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 });
62
81
  }
63
82
 
64
83
  const newTree = await githubRequest(token, `/repos/${repo}/git/trees`, {
65
84
  method: "POST",
66
- body: JSON.stringify({ base_tree: parentCommit.tree.sha, tree })
85
+ body: JSON.stringify({ tree })
67
86
  });
68
87
 
88
+ if (newTree.sha === parent.tree) {
89
+ return { commit: parent.commit, tree: newTree.sha, changed: false };
90
+ }
91
+
69
92
  const commit = await githubRequest(token, `/repos/${repo}/git/commits`, {
70
93
  method: "POST",
71
- body: JSON.stringify({ message, tree: newTree.sha, parents: [parentSha] })
94
+ body: JSON.stringify({ message, tree: newTree.sha, parents: [parent.commit] })
72
95
  });
73
96
 
74
- await githubRequest(token, `/repos/${repo}/git/refs/heads/${branch}`, {
97
+ await githubRequest(token, `/repos/${repo}/git/refs/heads/${encodeURIComponent(branch)}`, {
75
98
  method: "PATCH",
76
99
  body: JSON.stringify({ sha: commit.sha })
77
100
  });
78
101
 
79
- return { commit: commit.sha, tree: newTree.sha };
80
- }
81
-
82
- export async function publishToGitHub({ token, repo, contentPath, branch = "main" }) {
83
- if (!/^[^/]+\/[^/]+$/.test(repo)) {
84
- return { success: false, msg: `Invalid GitHub repository: ${repo}` };
85
- }
86
-
87
- try {
88
- const repository = await githubRequest(token, `/repos/${repo}`);
89
- const { commit } = await commitDirectory({ token, repo, dir: contentPath, message: "Publish package", branch });
90
-
91
- return { success: true, msg: `Published ${repo}`, repo: repository.full_name, commit };
92
- }
93
- catch (error) {
94
- return { success: false, msg: error instanceof Error ? error.message : String(error) };
95
- }
102
+ return { commit: commit.sha, tree: newTree.sha, changed: true };
96
103
  }
97
104
 
98
105
  export async function createGitHubTag(token, repo, version, commit) {
@@ -108,22 +115,6 @@ export async function createGitHubTag(token, repo, version, commit) {
108
115
  }
109
116
  }
110
117
 
111
- export async function updateGitHubRepo({ token, repo, packagePath, version, message = `Release ${version}` }) {
112
- try {
113
- const { commit, tree } = await commitDirectory({ token, repo, dir: packagePath, message });
114
-
115
- await githubRequest(token, `/repos/${repo}/git/refs`, {
116
- method: "POST",
117
- body: JSON.stringify({ ref: `refs/tags/v${version}`, sha: commit })
118
- });
119
-
120
- return { success: true, commit, tree, version, tag: `v${version}` };
121
- }
122
- catch (error) {
123
- return { success: false, msg: error instanceof Error ? error.message : String(error) };
124
- }
125
- }
126
-
127
118
  export async function createGitHubRepo(token, repository, organization = false) {
128
119
  const match = repository.match(
129
120
  /^([a-zA-Z0-9-]+)\/([a-zA-Z0-9._-]+)$/
@@ -0,0 +1,134 @@
1
+ import fs from "node:fs/promises"
2
+ import path from "node:path"
3
+
4
+ export const DEFAULT_IGNORES = ["node_modules/", "slim-dist/", "spm.lock.json", ".DS_Store", "Thumbs.db"]
5
+
6
+ function escapeRegex(char) {
7
+ return /[.*+?^${}()|[\]\\/]/.test(char) ? `\\${char}` : char
8
+ }
9
+
10
+ function globToRegex(glob, anchored) {
11
+ let source = ""
12
+
13
+ for (let i = 0; i < glob.length; i++) {
14
+ const char = glob[i]
15
+
16
+ if (char === "*") {
17
+ if (glob[i + 1] === "*" && (i === 0 || glob[i - 1] === "/")) {
18
+ if (i + 2 === glob.length) {
19
+ source += ".*"
20
+ i += 1
21
+ continue
22
+ }
23
+ if (glob[i + 2] === "/") {
24
+ source += "(?:.*/)?"
25
+ i += 2
26
+ continue
27
+ }
28
+ }
29
+ source += "[^/]*"
30
+ }
31
+ else if (char === "?") {
32
+ source += "[^/]"
33
+ }
34
+ else if (char === "[") {
35
+ const end = glob.indexOf("]", i + 2)
36
+ if (end === -1) {
37
+ source += "\\["
38
+ continue
39
+ }
40
+ let set = glob.slice(i + 1, end).replaceAll("\\", "\\\\")
41
+ if (set[0] === "!") set = "^" + set.slice(1)
42
+ source += `[${set}]`
43
+ i = end
44
+ }
45
+ else if (char === "\\" && i + 1 < glob.length) {
46
+ source += escapeRegex(glob[++i])
47
+ }
48
+ else {
49
+ source += escapeRegex(char)
50
+ }
51
+ }
52
+
53
+ return new RegExp(`^${anchored ? "" : "(?:.*/)?"}${source}$`)
54
+ }
55
+
56
+ export function parseIgnore(content, base = "") {
57
+ const rules = []
58
+
59
+ for (const raw of content.split(/\r?\n/)) {
60
+ let line = raw.replace(/(?<!\\)\s+$/, "")
61
+ if (!line || line.startsWith("#")) continue
62
+
63
+ let negate = false
64
+ if (line.startsWith("!")) {
65
+ negate = true
66
+ line = line.slice(1)
67
+ }
68
+ else if (line.startsWith("\\!") || line.startsWith("\\#")) {
69
+ line = line.slice(1)
70
+ }
71
+
72
+ let dirOnly = false
73
+ if (line.endsWith("/")) {
74
+ dirOnly = true
75
+ line = line.replace(/\/+$/, "")
76
+ }
77
+ if (!line) continue
78
+
79
+ const anchored = line.includes("/")
80
+ line = line.replace(/^\/+/, "")
81
+ if (!line) continue
82
+
83
+ rules.push({ base, negate, dirOnly, regex: globToRegex(line, anchored) })
84
+ }
85
+
86
+ return rules
87
+ }
88
+
89
+ export function isIgnored(rules, relPath, isDir) {
90
+ let ignored = false
91
+
92
+ for (const rule of rules) {
93
+ if (rule.dirOnly && !isDir) continue
94
+ if (rule.base && !relPath.startsWith(rule.base)) continue
95
+ if (rule.regex.test(relPath.slice(rule.base.length))) ignored = !rule.negate
96
+ }
97
+
98
+ return ignored
99
+ }
100
+
101
+ async function readIgnoreFile(file, base) {
102
+ try {
103
+ return parseIgnore(await fs.readFile(file, "utf8"), base)
104
+ }
105
+ catch (error) {
106
+ if (error.code === "ENOENT" || error.code === "EISDIR") return []
107
+ throw error
108
+ }
109
+ }
110
+
111
+ export async function getPackageFiles(dir) {
112
+ const files = []
113
+
114
+ async function walk(absDir, relDir, inherited) {
115
+ const own = await readIgnoreFile(path.join(absDir, ".gitignore"), relDir ? `${relDir}/` : "")
116
+ const rules = own.length ? [...inherited, ...own] : inherited
117
+ const entries = await fs.readdir(absDir, { withFileTypes: true })
118
+ entries.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0))
119
+
120
+ for (const entry of entries) {
121
+ if (entry.name === ".git") continue
122
+
123
+ const relPath = relDir ? `${relDir}/${entry.name}` : entry.name
124
+ const isDir = entry.isDirectory()
125
+ if (isIgnored(rules, relPath, isDir)) continue
126
+
127
+ if (isDir) await walk(path.join(absDir, entry.name), relPath, rules)
128
+ else if (entry.isFile()) files.push({ path: relPath, fullPath: path.join(absDir, entry.name) })
129
+ }
130
+ }
131
+
132
+ await walk(dir, "", parseIgnore(DEFAULT_IGNORES.join("\n")))
133
+ return files
134
+ }
@@ -0,0 +1,120 @@
1
+ import { commitPackage, createGitHubTag, getBranchHead, githubRequest, tagExists } from "./github_req.js"
2
+ import { getPackage, publishPackage, updatePackage } from "./spm.js"
3
+ import { getPackageFiles } from "./package_files.js"
4
+
5
+ export const APP_INSTALL_URL = "https://github.com/apps/slim-package-manager/installations/new"
6
+
7
+ const VERSION = /^(\d+(?:\.\d+)*)(?:-([0-9A-Za-z.-]+))?$/
8
+
9
+ export function parseVersion(value) {
10
+ const match = VERSION.exec(String(value ?? ""))
11
+ if (!match) return null
12
+ return { parts: match[1].split(".").map(Number), pre: match[2] ? match[2].split(".") : [] }
13
+ }
14
+
15
+ export function compareVersions(a, b) {
16
+ const left = parseVersion(a)
17
+ const right = parseVersion(b)
18
+ if (!left || !right) throw new Error(`Cannot compare versions "${a}" and "${b}"`)
19
+
20
+ for (let i = 0; i < Math.max(left.parts.length, right.parts.length); i++) {
21
+ const diff = (left.parts[i] ?? 0) - (right.parts[i] ?? 0)
22
+ if (diff !== 0) return Math.sign(diff)
23
+ }
24
+
25
+ if (!left.pre.length || !right.pre.length) return Math.sign(right.pre.length - left.pre.length)
26
+
27
+ for (let i = 0; i < Math.max(left.pre.length, right.pre.length); i++) {
28
+ const x = left.pre[i]
29
+ const y = right.pre[i]
30
+ if (x === undefined) return -1
31
+ if (y === undefined) return 1
32
+ if (x === y) continue
33
+ const xn = /^\d+$/.test(x)
34
+ const yn = /^\d+$/.test(y)
35
+ if (xn && yn) return Math.sign(Number(x) - Number(y))
36
+ if (xn) return -1
37
+ if (yn) return 1
38
+ return x < y ? -1 : 1
39
+ }
40
+
41
+ return 0
42
+ }
43
+
44
+ function fail(msg, extra = {}) {
45
+ return { success: false, msg, ...extra }
46
+ }
47
+
48
+ export async function preparePublish({ token, name, dir, spm }) {
49
+ const repo = spm.github?.repo
50
+ const version = spm.version
51
+ const tag = `v${version}`
52
+
53
+ if (!repo) return fail("The .spm file has no @github repo")
54
+ if (!parseVersion(version)) return fail(`version "${version}" in .spm is not a version like 1.2.0`)
55
+ if (!token) return fail("Not signed in to GitHub: run spm login")
56
+
57
+ const installations = await githubRequest(token, "/user/installations")
58
+ if (!installations?.total_count) {
59
+ return fail(`The slim-package-manager GitHub App is not installed on "${repo}"`, { appMissing: true })
60
+ }
61
+
62
+ const repository = await githubRequest(token, `/repos/${repo}`)
63
+ const branch = repository.default_branch || "main"
64
+
65
+ let parent
66
+ try {
67
+ parent = await getBranchHead(token, repo, branch)
68
+ }
69
+ catch (error) {
70
+ throw new Error(`Cannot read branch ${branch} of ${repo}: ${error.message}`)
71
+ }
72
+
73
+ const registry = await getPackage({ name })
74
+ const existing = registry.success ? registry.content : null
75
+ let registryUpToDate = false
76
+
77
+ if (existing?.latest) {
78
+ const order = compareVersions(version, existing.latest)
79
+ if (order < 0) return fail(`version ${version} is below the registry's latest ${existing.latest}: raise version in .spm`)
80
+ registryUpToDate = order === 0
81
+ }
82
+
83
+ if (await tagExists(token, repo, tag)) {
84
+ return fail(`${repo} already has the tag ${tag}: raise version in .spm`)
85
+ }
86
+
87
+ const files = await getPackageFiles(dir)
88
+ if (files.length === 0) return fail("Package directory is empty")
89
+
90
+ return {
91
+ success: true,
92
+ plan: { name, repo, branch, parent, version, tag, description: spm.description, files, existing: !!existing, registryUpToDate }
93
+ }
94
+ }
95
+
96
+ export async function runPublish({ token, plan }) {
97
+ const { name, repo, branch, parent, version, tag, description, files } = plan
98
+
99
+ const pushed = await commitPackage({ token, repo, branch, parent, files, message: `Release ${version}` })
100
+ const pushedNote = pushed.changed ? `${repo} now has the commit ${pushed.commit.slice(0, 7)}, ` : ""
101
+
102
+ if (!plan.registryUpToDate) {
103
+ const request = plan.existing ? updatePackage : publishPackage
104
+ const registry = await request({ token, name, description, version, github: repo })
105
+ if (!registry.success) {
106
+ return fail(`SPM registry: ${registry.content ?? "request failed"} (${pushedNote}nothing tagged; run spm publish again)`, { pushed })
107
+ }
108
+ }
109
+
110
+ const tagged = await createGitHubTag(token, repo, version, pushed.commit)
111
+ if (!tagged.success) {
112
+ return fail(`@${name} ${version} is in the registry, but tagging ${tag} on GitHub failed: ${tagged.msg} (run spm publish again)`, { pushed })
113
+ }
114
+
115
+ return {
116
+ success: true,
117
+ msg: `@${name} ${version} published: ${repo} ${tag} @ ${pushed.commit.slice(0, 7)}${pushed.changed ? "" : " (files unchanged, no new commit)"}`,
118
+ pushed
119
+ }
120
+ }
package/src/cli.js CHANGED
@@ -12,9 +12,10 @@ import { loginGitHub } from "./api/github_auth.js";
12
12
  import { deleteGitHubToken, getGitHubToken, saveGitHubToken } from "./api/storage.js";
13
13
  import { downloadGitHubRepo, getGitHubUser, packageIntegrity } from "./api/github_get.js";
14
14
 
15
- import { getPackage, publishPackage, removePackage, updatePackage } from "./api/spm.js"
15
+ import { getPackage, removePackage } from "./api/spm.js"
16
16
  import { readLock, setLockEntry, removeLockEntry } from "./api/lock.js"
17
- import { createGitHubRepo, createGitHubTag, deleteGitHubRepo, githubHeaders, publishToGitHub, updateGitHubRepo } from "./api/github_req.js";
17
+ import { createGitHubRepo, deleteGitHubRepo } from "./api/github_req.js";
18
+ import { APP_INSTALL_URL, preparePublish, runPublish } from "./api/publish.js";
18
19
 
19
20
  import open from "open";
20
21
 
@@ -404,132 +405,46 @@ spm
404
405
  spm
405
406
  .command("publish")
406
407
  .argument('<name>')
408
+ .description("Push the package folder to its GitHub repository, register the version and tag it")
407
409
  .action(async (name) => {
408
- if (isPackageExists(name)) {
409
- const spmFileContent = await getSPM(name);
410
+ if (!isPackageExists(name)) {
411
+ errlog(`No package founded: ${path.relative(process.cwd(), path.join(packagesPath, name)) || name}`);
412
+ return;
413
+ }
410
414
 
411
- if (!spmFileContent.success) {
412
- spmlog(formatError(spmFileContent.content));
413
- return;
414
- }
415
+ const spmFileContent = await getSPM(name);
415
416
 
416
- const SPMContent = spmFileContent.content;
417
- const packageName = "@" + name;
417
+ if (!spmFileContent.success) {
418
+ errlog(spmFileContent.content);
419
+ return;
420
+ }
418
421
 
419
- const githubRepo = SPMContent.github?.repo
420
- const version = SPMContent.version
421
- const description = SPMContent.description
422
- const packagePath = packageDir(name)
423
-
424
- if (githubRepo) {
425
- await loading({
426
- startMsg: `Publishing ${packageName}`,
427
- callback: async ({ fail, ok }) => {
428
- const githubToken = await getGitHubToken()
429
-
430
- const installationsReq = await fetch(
431
- "https://api.github.com/user/installations",
432
- {
433
- headers: githubHeaders(githubToken),
434
- },
435
- );
436
-
437
- const installations = await installationsReq.json()
438
-
439
- if ("total_count" in installations) {
440
- if (installations.total_count == 0) {
441
- await open(
442
- "https://github.com/apps/slim-package-manager/installations/new",
443
- );
444
-
445
- console.log("\n")
446
- spmlog(formatError(`No application has been installed on the "${githubRepo}" repository\n`))
447
- spmlog("Open:", formatBold.underline("https://github.com/apps/slim-package-manager/installations/new"))
448
- spmlog(`Install the app, then run ${formatItalic(`${spm.name()} publish ${name}`)} again\n`)
449
-
450
- return fail(`No application has been installed on the "${githubRepo}" repository`)
451
- }
452
- else {
453
- const githubPublishReq = await publishToGitHub({
454
- token: githubToken,
455
- repo: githubRepo,
456
- contentPath: packagePath
457
- })
458
-
459
- if (!githubPublishReq.success) {
460
- return fail("Github publish:", githubPublishReq.msg)
461
- }
462
- else {
463
- const isPackagesExists = (await getPackage({ name })).success
464
-
465
- if (isPackagesExists) {
466
- console.log("\nPackage is already exists... updating")
467
-
468
- const updatePackageReq = await updatePackage({
469
- token: githubToken,
470
- name: name,
471
- description: description,
472
- version: version,
473
- github: githubRepo
474
- })
475
-
476
- if (!updatePackageReq.success) {
477
- return fail("Something went wrong while requesting a package update. Please try again later")
478
- }
479
- else {
480
- console.log("\nUpdating package on Github...")
481
-
482
- const updateReq = await updateGitHubRepo({
483
- token: githubToken,
484
- repo: githubRepo,
485
- packagePath: packagePath,
486
- version: updatePackageReq.content.latest
487
- })
488
-
489
- if (!updateReq.success) {
490
- return fail("Failed to push the new version to GitHub:", updateReq.msg)
491
- }
492
- else {
493
- const publishedVer = updateReq.version
494
- return ok(`@${name} ${publishedVer} published on Github`)
495
- }
496
- }
497
- }
498
- else {
499
- const publishReq = await publishPackage({
500
- token: githubToken,
501
- name: name,
502
- version: version,
503
- github: githubRepo,
504
- description: description
505
- })
506
-
507
- if (!publishReq.success) {
508
- return fail("SPM Registry publishing:", publishReq.content)
509
- }
510
- else {
511
- const tagReq = await createGitHubTag(githubToken, githubRepo, version, githubPublishReq.commit)
512
- if (!tagReq.success) {
513
- return fail(`${packageName} registered, but tagging v${version} on GitHub failed:`, tagReq.msg)
514
- }
515
- return ok(`${packageName} published and registred: ${name} v${version}`)
516
- }
517
- }
518
- }
519
- }
520
- }
521
- else {
522
- return fail("Installations:", installations.message)
523
- }
422
+ const SPMContent = spmFileContent.content;
423
+
424
+ if (!SPMContent.github?.repo) {
425
+ errlog("No GitHub repository specified");
426
+ return;
427
+ }
428
+
429
+ await loading({
430
+ startMsg: `Publishing @${name}`,
431
+ callback: async ({ fail }) => {
432
+ const githubToken = await getGitHubToken()
433
+ const prepared = await preparePublish({ token: githubToken, name, dir: packageDir(name), spm: SPMContent })
434
+
435
+ if (!prepared.success) {
436
+ if (prepared.appMissing) {
437
+ await open(APP_INSTALL_URL).catch(() => {})
438
+ console.log("\n")
439
+ spmlog("Open:", formatBold.underline(APP_INSTALL_URL))
440
+ spmlog(`Install the app, then run ${formatItalic(`${spm.name()} publish ${name}`)} again\n`)
524
441
  }
525
- })
526
- }
527
- else {
528
- errlog("No GitHub repository specified");
442
+ return fail(prepared.msg)
443
+ }
444
+
445
+ return await runPublish({ token: githubToken, plan: prepared.plan })
529
446
  }
530
- } else {
531
- errlog(`No package founded: ${path.relative(process.cwd(), path.join(packagesPath, name)) || name}`);
532
- }
447
+ })
533
448
  });
534
449
 
535
450
  spm