@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/src/cli.js ADDED
@@ -0,0 +1,514 @@
1
+ #!/usr/bin/env node
2
+
3
+ import { Command } from "commander";
4
+ import { formatError, formatBold, formatItalic, formatSuccess, createFolder, createFile } from "./helpers.js"
5
+ import pkg from "../package.json" with { type: "json" };
6
+ import { log, isPackageExists, isValidPackageName, rootPath, deleteDirectory, loading, delay, projectPackagesDir } from "./helpers.js";
7
+
8
+ import fs from "node:fs"
9
+ import path from "node:path"
10
+ import { getSPM } from "./parsers/spm.js";
11
+ import { loginGitHub } from "./api/github_auth.js";
12
+ import { deleteGitHubToken, getGitHubToken, saveGitHubToken } from "./api/storage.js";
13
+ import { downloadGitHubRepo, getGitHubUser, packageIntegrity } from "./api/github_get.js";
14
+
15
+ import { getPackage, removePackage } from "./api/spm.js"
16
+ import { readLock, setLockEntry, removeLockEntry } from "./api/lock.js"
17
+ import { createGitHubRepo, deleteGitHubRepo } from "./api/github_req.js";
18
+ import { APP_INSTALL_URL, preparePublish, runPublish } from "./api/publish.js";
19
+
20
+ import open from "open";
21
+
22
+ export const spm = new Command();
23
+
24
+ function spmlog(...args) {
25
+ console.log("[SPM]", ...args)
26
+ }
27
+ function errlog(...args) {
28
+ console.log(formatError(...args))
29
+ process.exitCode = 1
30
+ }
31
+
32
+ const packagesPath = projectPackagesDir()
33
+
34
+ function packageDir(name) {
35
+ if (!isValidPackageName(name)) {
36
+ throw new Error(`"${name}" is not a valid package name: use letters, digits, ".", "_" and "-"`)
37
+ }
38
+ return path.join(packagesPath, name)
39
+ }
40
+
41
+ async function installPackage(name, { version = null, latest = false } = {}) {
42
+ const target = packageDir(name)
43
+ const getPackageReq = await getPackage({ name: name })
44
+
45
+ if (!getPackageReq.success) {
46
+ return { success: false, msg: `SPM Install: ${getPackageReq.content}` }
47
+ }
48
+
49
+ const githubToken = await getGitHubToken()
50
+ const data = getPackageReq.content
51
+ const repo = data.repo
52
+ const resolvedVersion = version ?? data.latest
53
+ const entry = readLock().packages[name]
54
+ const locked = !latest && entry && entry.repo === repo && (version === null || entry.version === version) ? entry : null
55
+ const wanted = locked ? locked.version : resolvedVersion
56
+
57
+ console.log(`\nDownloading ${repo}${locked?.commit ? ` @ ${locked.commit.slice(0, 7)} (locked)` : ""}...`)
58
+
59
+ const result = await downloadGitHubRepo(githubToken, repo, target, wanted ?? null, locked, { fallbackToMain: !locked && version === null })
60
+ if (!result.success) return result
61
+
62
+ if (result.untagged) {
63
+ spmlog(`${repo} has no tag v${wanted}, installed the newest commit of main instead`)
64
+ }
65
+
66
+ if (result.rejected?.length) {
67
+ spmlog(`Skipped ${result.rejected.length} unsafe entr${result.rejected.length === 1 ? "y" : "ies"}: ${result.rejected.slice(0, 5).join(", ")}`)
68
+ }
69
+ setLockEntry(name, { version: wanted, repo, commit: result.commit, integrity: result.integrity })
70
+ return { success: true, msg: `Package @${name}:${wanted} installed (${result.commit.slice(0, 7)})` }
71
+ }
72
+
73
+ function renderObject(obj, indent = 0) {
74
+ let output = "";
75
+ const prefix = " ".repeat(indent);
76
+
77
+ Object.entries(obj).forEach(([key, value]) => {
78
+ if (value && typeof value === "object" && !Array.isArray(value)) {
79
+ output += `\n${formatItalic(prefix)}${formatBold(key)}:`;
80
+ output += renderObject(value, indent + 2);
81
+ } else {
82
+ output += `\n${formatItalic(prefix)}${formatBold(key)}: ${value}`;
83
+ }
84
+ });
85
+
86
+ return output;
87
+ }
88
+
89
+ function renderBlock({ name, content }) {
90
+ function generateSepLines(len) {
91
+ let line = `-------------------------------------`
92
+
93
+ if (len) {
94
+ for (let i = 0; i < len; i++) {
95
+ line += "-"
96
+ }
97
+ }
98
+
99
+ return line
100
+ }
101
+
102
+ const nameLen = name.length
103
+
104
+ return `${formatSuccess(name)} ${generateSepLines()}` +
105
+ content +
106
+ `\n${generateSepLines(nameLen + 1)}`
107
+ }
108
+
109
+ spm
110
+ .name("spm")
111
+ .description(`Slim Package Manager (SPM ${pkg.version})`)
112
+ .version(pkg.version);
113
+
114
+ spm
115
+ .command("list")
116
+ .action(() => {
117
+ const targetDir = packagesPath
118
+ if (!fs.existsSync(targetDir)) {
119
+ spmlog("No packages installed (the packages/ directory does not exist)")
120
+ return
121
+ }
122
+
123
+ const relativePaths = fs.readdirSync(targetDir, { withFileTypes: true })
124
+ .filter(entry => entry.isDirectory() && !/\.spm-(old-)?\d+-\d+$/.test(entry.name))
125
+ .map(entry => entry.name);
126
+
127
+ if (relativePaths.length === 0) {
128
+ spmlog("No packages installed")
129
+ return
130
+ }
131
+
132
+ function getPkgPath(pkg) {
133
+ const relative = path.relative(process.cwd(), path.join(targetDir, pkg))
134
+ return relative
135
+ }
136
+
137
+ spmlog(`List of all installed packages:\n${relativePaths.map(item => "- @" + item + ` (${getPkgPath(item)})`).join(",\n")}`)
138
+ });
139
+
140
+ spm
141
+ .command("lock")
142
+ .description("Show resolved package versions from spm.lock.json")
143
+ .action(() => {
144
+ const { packages } = readLock()
145
+ const names = Object.keys(packages)
146
+
147
+ if (names.length === 0) {
148
+ spmlog("No locked packages (spm.lock.json is empty or missing)")
149
+ return
150
+ }
151
+
152
+ spmlog(`Locked packages:\n${names.map(name => `- @${name}:${packages[name].version} (${packages[name].repo}${packages[name].commit ? ` @ ${packages[name].commit.slice(0, 7)}` : ""})`).join("\n")}`)
153
+ });
154
+
155
+ spm
156
+ .command("get")
157
+ .argument("<name>")
158
+ .action(async (name) => {
159
+ let msg = null;
160
+
161
+ if (isPackageExists(name)) {
162
+ const spmFileContent = await getSPM(name);
163
+
164
+ if (!spmFileContent.success) {
165
+ errlog(spmFileContent.content);
166
+ return;
167
+ }
168
+
169
+ const SPMContent = spmFileContent.content;
170
+ let packageName = "@" + name
171
+
172
+ const infoFromRegistryReq = await getPackage({ name: name })
173
+
174
+ if(infoFromRegistryReq.success) {
175
+ packageName = `${packageName} (${infoFromRegistryReq.content.latest})`
176
+ }
177
+
178
+ msg = renderBlock({
179
+ name: packageName,
180
+ content: renderObject(SPMContent)
181
+ })
182
+ } else {
183
+ msg =
184
+ formatError(`@${name} not installed\n`) +
185
+ `Want to install? Try ${formatItalic(`${spm.name()} i ${name}`)}`;
186
+ }
187
+
188
+ spmlog(msg);
189
+ });
190
+
191
+ spm
192
+ .command("rm")
193
+ .argument('<name>')
194
+ .option("--g", "Removes the project from the project registry and GitHub")
195
+ .action(async (name, opt) => {
196
+ await loading({
197
+ startMsg: `Removing @${name}...`,
198
+ callback: async ({ fail, ok }) => {
199
+ const isGlobally = opt.g == undefined ? false : true
200
+
201
+ if (isGlobally) {
202
+ const spmFileContent = await getSPM(name);
203
+
204
+ if (!spmFileContent.success) {
205
+ return fail("SPM Check:", spmFileContent.content);
206
+ }
207
+
208
+ const SPMContent = spmFileContent.content;
209
+ const githubRepo = SPMContent.github?.repo
210
+
211
+ if (!githubRepo) {
212
+ return fail("SPM Check: the .spm file has no @github repo")
213
+ }
214
+
215
+ const githubToken = await getGitHubToken()
216
+
217
+ const removePackageRegReq = await removePackage({
218
+ token: githubToken,
219
+ name: name
220
+ })
221
+
222
+ if (!removePackageRegReq.success) {
223
+ return fail("SPM Registry remove:", removePackageRegReq.content)
224
+ }
225
+
226
+ const removeFromGithubReq = await deleteGitHubRepo(githubToken, githubRepo)
227
+
228
+ if (!removeFromGithubReq.success) {
229
+ return fail(`${githubRepo} failed to remove from Github`)
230
+ }
231
+ else {
232
+ return ok(`${githubRepo} removed from Github and registry`)
233
+ }
234
+ }
235
+
236
+ let res = false
237
+ try {
238
+ const dir = packageDir(name)
239
+ if (!fs.existsSync(dir)) {
240
+ if (name in readLock().packages) removeLockEntry(name)
241
+ return fail(`@${name} is not installed`)
242
+ }
243
+ res = await deleteDirectory(dir)
244
+ } catch (error) {
245
+ return fail(error.message)
246
+ }
247
+
248
+ if (res) {
249
+ removeLockEntry(name)
250
+ return ok(`package @${name} successfully removed locally`)
251
+ }
252
+ else {
253
+ return fail(`Failed to remove the @${name} package`)
254
+ }
255
+ }
256
+ })
257
+ });
258
+
259
+ spm
260
+ .command("i")
261
+ .argument("[name]")
262
+ .description("Install a package, or every package in spm.lock.json when no name is given")
263
+ .option("--ver <version>", "Download a specific version")
264
+ .option("--latest", "Ignore the locked commit and take the newest one")
265
+ .action(async (name, opt) => {
266
+ const names = name ? [name] : Object.keys(readLock().packages)
267
+ if (names.length === 0) {
268
+ spmlog("Nothing to install: spm.lock.json is empty or missing")
269
+ return
270
+ }
271
+ for (const packageName of names) {
272
+ await loading({
273
+ startMsg: `Installing @${packageName}...`,
274
+ callback: async ({ fail, ok }) => {
275
+ try {
276
+ const result = await installPackage(packageName, { version: name ? opt.ver ?? null : null, latest: !!opt.latest })
277
+ return result.success ? ok(result.msg) : fail(result.msg)
278
+ } catch (error) {
279
+ return fail(error.message)
280
+ }
281
+ }
282
+ })
283
+ }
284
+ });
285
+
286
+ spm
287
+ .command("verify")
288
+ .description("Check that installed packages match spm.lock.json")
289
+ .action(() => {
290
+ const { packages } = readLock()
291
+ const names = Object.keys(packages)
292
+ if (names.length === 0) {
293
+ spmlog("No locked packages (spm.lock.json is empty or missing)")
294
+ return
295
+ }
296
+ let broken = 0
297
+ for (const name of names) {
298
+ const dir = packageDir(name)
299
+ const expected = packages[name].integrity
300
+ if (!fs.existsSync(dir)) {
301
+ broken++
302
+ errlog(`@${name}: not installed`)
303
+ } else if (!expected) {
304
+ spmlog(`@${name}: no integrity in spm.lock.json, reinstall it to record one`)
305
+ } else if (packageIntegrity(dir) !== expected) {
306
+ broken++
307
+ errlog(`@${name}: files differ from spm.lock.json`)
308
+ } else {
309
+ spmlog(`@${name}: ok`)
310
+ }
311
+ }
312
+ if (broken > 0) process.exitCode = 1
313
+ });
314
+
315
+ spm
316
+ .command("create")
317
+ .argument("<name>")
318
+
319
+ .option("--github", "Create repository on Github")
320
+ .option("--local", "Create minimum package template in packages")
321
+
322
+ .option("--github-repo <repoName>", "Fill in '@github/repo' in the configuration")
323
+ .option("--description <description>", "Fill in 'description' in the configuration")
324
+ .option("--ver <version>", "Fill in 'version' in the configuration")
325
+
326
+ .action(async (name, opt) => {
327
+ const defaultGithubRepo = opt.githubRepo == undefined ? "username/repo" : opt.githubRepo
328
+ const defaultDescription = opt.description == undefined ? "My first Slim package" : opt.description
329
+ const defaultVersion = opt.ver == undefined ? "1.0.0" : opt.ver
330
+
331
+ if (opt.local) {
332
+ const isExists = isPackageExists(name)
333
+
334
+ await loading({
335
+ startMsg: `Creating path for ${name}`,
336
+ callback: async ({ fail, ok }) => {
337
+ const packagePath = packageDir(name)
338
+ const unsafe = [defaultDescription, defaultVersion, defaultGithubRepo].find(value => /["\r\n]/.test(String(value)))
339
+
340
+ if (unsafe !== undefined) return fail(`Values cannot contain quotes or line breaks: ${unsafe}`)
341
+ if (isExists) return fail("Package is already exists")
342
+ else {
343
+ const createFolderReq = await createFolder(packagePath)
344
+
345
+ if (!createFolderReq.success) {
346
+ return fail(createFolderReq.content)
347
+ }
348
+ else {
349
+ const createSPMReq = createFile(path.join(packagePath, ".spm"), `
350
+ name = "${name}"
351
+ description = "${defaultDescription}"
352
+ version = "${defaultVersion}"
353
+
354
+ @ github
355
+ repo = "${defaultGithubRepo}"
356
+ `.trim())
357
+
358
+ if (!createSPMReq.success) {
359
+ return fail(createSPMReq.content)
360
+ }
361
+ else {
362
+ return ok("Local package created")
363
+ }
364
+ }
365
+ }
366
+ }
367
+ })
368
+ }
369
+ else if (opt.github || opt.githubRepo) {
370
+ const spmFileContent = await getSPM(name);
371
+
372
+ if (!spmFileContent.success) {
373
+ spmlog(formatError(spmFileContent.content));
374
+ return;
375
+ }
376
+
377
+ const SPMContent = spmFileContent.content;
378
+ const packageName = "@" + name;
379
+ const githubRepo = SPMContent.github?.repo
380
+ const organization = SPMContent.github?.organization === true
381
+
382
+ if (!githubRepo) {
383
+ errlog("The .spm file has no @github repo");
384
+ return;
385
+ }
386
+
387
+ await loading({
388
+ startMsg: `Creating repository for ${packageName}`,
389
+ callback: async ({ fail, ok }) => {
390
+ const githubToken = await getGitHubToken();
391
+
392
+ const createRepoReq = await createGitHubRepo(githubToken, githubRepo, organization)
393
+
394
+ if (!createRepoReq.success) {
395
+ return fail(createRepoReq.msg)
396
+ }
397
+ else {
398
+ return ok(createRepoReq.msg)
399
+ }
400
+ },
401
+ })
402
+ }
403
+ })
404
+
405
+ spm
406
+ .command("publish")
407
+ .argument('<name>')
408
+ .description("Push the package folder to its GitHub repository, register the version and tag it")
409
+ .action(async (name) => {
410
+ if (!isPackageExists(name)) {
411
+ errlog(`No package founded: ${path.relative(process.cwd(), path.join(packagesPath, name)) || name}`);
412
+ return;
413
+ }
414
+
415
+ const spmFileContent = await getSPM(name);
416
+
417
+ if (!spmFileContent.success) {
418
+ errlog(spmFileContent.content);
419
+ return;
420
+ }
421
+
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`)
441
+ }
442
+ return fail(prepared.msg)
443
+ }
444
+
445
+ return await runPublish({ token: githubToken, plan: prepared.plan })
446
+ }
447
+ })
448
+ });
449
+
450
+ spm
451
+ .command("login")
452
+ .description("Connect your GitHub account")
453
+ .option("--check", "Check if you logged in")
454
+ .action(async (opt) => {
455
+ if (opt.check) {
456
+ const token = await getGitHubToken()
457
+
458
+ if (token) {
459
+ try {
460
+ const user = await getGitHubUser(token)
461
+
462
+ spmlog(formatSuccess("Github connected"))
463
+ spmlog(`${formatBold("Account")}: ${user.name} (${user.html_url})`)
464
+ }
465
+ catch (e) {
466
+ spmlog(formatError(String(e)))
467
+ }
468
+ }
469
+ else {
470
+ spmlog(formatError(`Github NOT connected. Use ${formatItalic.underline(spm.name() + " login")} to login via Github`))
471
+ }
472
+ }
473
+ else {
474
+ await loading({
475
+ startMsg: `Waiting for GitHub authorization...`,
476
+ callback: async () => {
477
+ try {
478
+ const token = await loginGitHub();
479
+ await saveGitHubToken(token)
480
+
481
+ return {
482
+ success: true,
483
+ msg: "Github account connected"
484
+ }
485
+ }
486
+ catch (error) {
487
+ return {
488
+ success: false,
489
+ msg:`${error.message}`
490
+ }
491
+ }
492
+ }
493
+ })
494
+ }
495
+ });
496
+
497
+ spm
498
+ .command("logout")
499
+ .description("Disconnect GitHub account")
500
+ .action(async () => {
501
+ try {
502
+ await deleteGitHubToken();
503
+
504
+ spmlog(formatSuccess("GitHub account disconnected"));
505
+ } catch (error) {
506
+ spmlog(formatError(`✗ ${error.message}`));
507
+ process.exitCode = 1;
508
+ }
509
+ });
510
+
511
+ spm.parseAsync().catch(err => {
512
+ spmlog(formatError(err?.message ?? String(err)))
513
+ process.exitCode = 1
514
+ })
package/src/helpers.js ADDED
@@ -0,0 +1,157 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { rm, mkdir } from 'node:fs/promises';
4
+ import chalk from "chalk";
5
+
6
+ export function readJson(file) {
7
+ return JSON.parse(fs.readFileSync(file, "utf8").replace(/^/, ""))
8
+ }
9
+
10
+ export function projectPackagesDir() {
11
+ let config = {}
12
+ try {
13
+ config = readJson(path.join(process.cwd(), "slimconfig.json"))
14
+ } catch {}
15
+ const names = config.names && typeof config.names === "object" ? config.names : {}
16
+ const value = names.packages ?? config.packages
17
+ return path.resolve(typeof value === "string" && value.trim() ? value : "packages")
18
+ }
19
+
20
+ export const formatError = chalk.red.bold
21
+ export const formatSuccess = chalk.green.bold
22
+ export const formatItalic = chalk.italic
23
+ export const formatBold = chalk.bold
24
+ export const rootPath = process.cwd()
25
+ export const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
26
+
27
+ export function log(...text) {
28
+ console.log(`[SPM]`, ...text)
29
+ }
30
+ export function error(...text) {
31
+ console.error(`[SPM]`, ...text)
32
+ }
33
+
34
+ export function isValidPackageName(name) {
35
+ return typeof name === "string" && /^[a-zA-Z0-9][a-zA-Z0-9._-]*$/.test(name) && !name.includes("..")
36
+ }
37
+
38
+ export function isPackageExists(name) {
39
+ return isValidPackageName(name) && fs.existsSync(path.join(projectPackagesDir(), name))
40
+ }
41
+ export function getPackagePath(name) {
42
+ return path.join(projectPackagesDir(), name)
43
+ }
44
+
45
+ export async function deleteDirectory(dirPath) {
46
+ try {
47
+ await rm(dirPath, { recursive: true, force: true });
48
+ return true
49
+ } catch (err) {
50
+ return false
51
+ }
52
+ }
53
+
54
+ export async function loading({ startMsg, callback }) {
55
+ function fail(...args) {
56
+ return {
57
+ success: false,
58
+ msg: args.join(" ")
59
+ }
60
+ }
61
+ function ok(...args) {
62
+ return {
63
+ success: true,
64
+ msg: args.join(" ")
65
+ }
66
+ }
67
+
68
+ const spinChars = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];
69
+ let i = 0;
70
+
71
+ const render = (char, msg) => {
72
+ process.stdout.write(
73
+ `\r\x1b[2K${chalk.green.bold(`[SPM] ${char} ${msg}`)}`
74
+ );
75
+ };
76
+
77
+ const spinnerInterval = setInterval(() => {
78
+ render(spinChars[i++ % spinChars.length], startMsg);
79
+ }, 100);
80
+
81
+ try {
82
+ const result = await callback({ fail, ok });
83
+
84
+ clearInterval(spinnerInterval);
85
+
86
+ process.stdout.write('\r\x1b[2K');
87
+
88
+ if (!result || typeof result.success !== 'boolean') {
89
+ process.exitCode = 1;
90
+ return {
91
+ success: false,
92
+ msg: 'Invalid callback result'
93
+ };
94
+ }
95
+
96
+ if (!result.success) process.exitCode = 1;
97
+
98
+ const icon = result.success ? '✓' : '✗';
99
+
100
+ process.stdout.write(
101
+ `${chalk.green.bold(`[SPM] ${icon} ${result.msg}`)}\n`
102
+ );
103
+
104
+ return result;
105
+ } catch (error) {
106
+ clearInterval(spinnerInterval);
107
+ process.exitCode = 1;
108
+
109
+ process.stdout.write('\r\x1b[2K');
110
+
111
+ const result = {
112
+ success: false,
113
+ msg: error instanceof Error ? error.message : String(error)
114
+ };
115
+
116
+ process.stdout.write(
117
+ `${chalk.red.bold(`[SPM] ✗ ${result.msg}`)}\n`
118
+ );
119
+
120
+ return result;
121
+ }
122
+ }
123
+
124
+ export async function createFolder(path) {
125
+ try {
126
+ await mkdir(path, { recursive: true });
127
+ return { success: true }
128
+ } catch (err) {
129
+ return {
130
+ success: false,
131
+ content: err.message
132
+ }
133
+ }
134
+ }
135
+
136
+ export function createFile(filePath, content) {
137
+ try {
138
+ const normalized = content
139
+ .replace(/^\s*\n/, "")
140
+ .replace(/\n\s*$/, "")
141
+ .replace(/^[ \t]+/gm, line => {
142
+ return line.replace(/^[ \t]{0,7}/, "");
143
+ });
144
+
145
+ fs.writeFileSync(filePath, normalized);
146
+
147
+ return {
148
+ success: true
149
+ }
150
+ }
151
+ catch (err) {
152
+ return {
153
+ success: false,
154
+ content: err.message
155
+ };
156
+ }
157
+ }