@lordcat/claw 0.0.0-stage → 1.0.0-alpha.2
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/LICENSE +686 -0
- package/README.md +19 -2
- package/bin/claw.js +2 -0
- package/dist/assets/927d672925e7b99f7813735c484c6922.svg +3 -0
- package/dist/commands/build.js +59 -0
- package/dist/commands/ci.js +25 -0
- package/dist/commands/init.js +47 -0
- package/dist/commands/install.js +210 -0
- package/dist/commands/login.js +109 -0
- package/dist/commands/logout.js +6 -0
- package/dist/commands/publish.js +91 -0
- package/dist/commands/uninstall.js +40 -0
- package/dist/compiler/src/assets/927d672925e7b99f7813735c484c6922.svg +3 -0
- package/dist/compiler/src/compiler.js +8829 -0
- package/dist/compiler/src/extension-metadata-worker.js +2439 -0
- package/dist/config.js +11 -0
- package/dist/index.js +72 -0
- package/dist/internal/lists.claw +263 -0
- package/dist/schemas.js +57 -0
- package/dist/util/claw-file.js +26 -0
- package/dist/util/claw-lock.js +23 -0
- package/dist/util/credentials.js +65 -0
- package/dist/util/oauth.js +20 -0
- package/package.json +45 -4
package/README.md
CHANGED
|
@@ -1,3 +1,20 @@
|
|
|
1
|
-
|
|
1
|
+
<div align="center">
|
|
2
|
+
<img
|
|
3
|
+
height="100"
|
|
4
|
+
src="https://claw.lordcat.dev/images/wordmark.png"
|
|
5
|
+
>
|
|
6
|
+
<p>
|
|
7
|
+
<img src="https://img.shields.io/badge/latest%20version-alpha--1-orange">
|
|
8
|
+
</p>
|
|
9
|
+
<p>
|
|
10
|
+
<strong>A programming language and package manager that compiles to scratch projects.</strong>
|
|
11
|
+
</p>
|
|
12
|
+
<p>
|
|
13
|
+
Claw let's you build your Scratch projects using traditional text programming, allowing you to utilize version control, among many other things. There's also a package manager, letting you install packages made by other people.
|
|
14
|
+
</p>
|
|
15
|
+
</div>
|
|
2
16
|
|
|
3
|
-
|
|
17
|
+
## Helpful links
|
|
18
|
+
|
|
19
|
+
- [Discover packages](https://claw.lordcat.dev/)
|
|
20
|
+
- [Documentation](https://claw.lordcat.dev/docs)
|
package/bin/claw.js
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import { existsSync, readFileSync } from 'node:fs';
|
|
2
|
+
import { writeFile } from 'node:fs/promises';
|
|
3
|
+
import { join, resolve } from 'node:path';
|
|
4
|
+
import chalk from 'chalk';
|
|
5
|
+
import { packageDirectory } from '../config.js';
|
|
6
|
+
import { packageSchema } from '../schemas.js';
|
|
7
|
+
import { getClawFile } from '../util/claw-file.js';
|
|
8
|
+
import Compiler from '../compiler/src/compiler.js';
|
|
9
|
+
const objectLen = (object) => Object.keys(object).length;
|
|
10
|
+
export default async function build() {
|
|
11
|
+
const clawFile = getClawFile();
|
|
12
|
+
if (clawFile.type === 'package') {
|
|
13
|
+
throw new Error('Packages cannot be built into projects.');
|
|
14
|
+
}
|
|
15
|
+
const start = Date.now();
|
|
16
|
+
const output = clawFile.output || 'project.sb3';
|
|
17
|
+
const compiler = new Compiler();
|
|
18
|
+
compiler.on('resolveImport', ({ source, resolve }) => {
|
|
19
|
+
const directory = join(packageDirectory, source);
|
|
20
|
+
const manifestPath = join(directory, 'claw.json');
|
|
21
|
+
if (!existsSync(directory)) {
|
|
22
|
+
throw new Error(`Package is not installed. Run claw install ${source}.`);
|
|
23
|
+
}
|
|
24
|
+
if (!existsSync(manifestPath)) {
|
|
25
|
+
throw new Error('Its claw.json file is missing.');
|
|
26
|
+
}
|
|
27
|
+
const contents = readFileSync(manifestPath, 'utf8');
|
|
28
|
+
let manifest;
|
|
29
|
+
try {
|
|
30
|
+
manifest = JSON.parse(contents);
|
|
31
|
+
}
|
|
32
|
+
catch {
|
|
33
|
+
throw new Error('Its claw.json file is invalid.');
|
|
34
|
+
}
|
|
35
|
+
const result = packageSchema.safeParse(manifest);
|
|
36
|
+
if (!result.success) {
|
|
37
|
+
throw new Error('Its claw.json file is invalid.');
|
|
38
|
+
}
|
|
39
|
+
const main = join(directory, result.data.main);
|
|
40
|
+
if (existsSync(main)) {
|
|
41
|
+
resolve(main);
|
|
42
|
+
return;
|
|
43
|
+
}
|
|
44
|
+
throw new Error(`Its main file '${result.data.main}' does not exist.`);
|
|
45
|
+
});
|
|
46
|
+
await compiler.compile(clawFile.sprites);
|
|
47
|
+
const archive = await compiler.generateZip('nodebuffer');
|
|
48
|
+
await writeFile(output, archive);
|
|
49
|
+
let totalBlocks = 0;
|
|
50
|
+
for (const target of compiler.targets) {
|
|
51
|
+
totalBlocks += Object.keys(target.blocks).length;
|
|
52
|
+
}
|
|
53
|
+
const totalSprites = objectLen(clawFile.sprites);
|
|
54
|
+
const totalExtensions = compiler.extensions.length +
|
|
55
|
+
objectLen(compiler.extensionURLs);
|
|
56
|
+
const elapsed = Date.now() - start;
|
|
57
|
+
console.log(`Built ${chalk.greenBright(totalSprites)} sprite(s), ${chalk.greenBright(totalBlocks)} blocks, ${chalk.greenBright(totalExtensions)} extensions in ${chalk.yellowBright(elapsed + 'ms')}`);
|
|
58
|
+
console.log(`Project saved to ${chalk.underline(resolve(output))}`);
|
|
59
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { rm } from 'node:fs/promises';
|
|
2
|
+
import chalk from 'chalk';
|
|
3
|
+
import { packageDirectory } from '../config.js';
|
|
4
|
+
import { installLockedPackages, lockMatches } from './install.js';
|
|
5
|
+
import { getClawFile } from '../util/claw-file.js';
|
|
6
|
+
import { getClawLock } from '../util/claw-lock.js';
|
|
7
|
+
export default async function ci() {
|
|
8
|
+
const clawFile = getClawFile();
|
|
9
|
+
const lockFile = getClawLock();
|
|
10
|
+
if (!lockFile) {
|
|
11
|
+
throw new Error('claw-lock.json not found. Run claw install.');
|
|
12
|
+
}
|
|
13
|
+
if (!lockMatches(clawFile.dependencies || {}, lockFile)) {
|
|
14
|
+
throw new Error('claw.json and claw-lock.json are out of sync. Run claw install.');
|
|
15
|
+
}
|
|
16
|
+
const start = Date.now();
|
|
17
|
+
await rm(packageDirectory, {
|
|
18
|
+
recursive: true,
|
|
19
|
+
force: true
|
|
20
|
+
});
|
|
21
|
+
await installLockedPackages(lockFile);
|
|
22
|
+
const elapsed = Date.now() - start;
|
|
23
|
+
console.log(`Installed ${chalk.greenBright(Object.keys(lockFile.dependencies).length)} `
|
|
24
|
+
+ `package(s) in ${chalk.yellowBright(elapsed + 'ms')}`);
|
|
25
|
+
}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { existsSync } from 'node:fs';
|
|
2
|
+
import { copyFile, mkdir, writeFile } from 'node:fs/promises';
|
|
3
|
+
import { basename, dirname, resolve } from 'node:path';
|
|
4
|
+
import chalk from 'chalk';
|
|
5
|
+
import { packageNameSchema } from '../schemas.js';
|
|
6
|
+
const defaultClawFile = 'print("Hello world!");';
|
|
7
|
+
const defaultCostume = new URL('../assets/927d672925e7b99f7813735c484c6922.svg', import.meta.url);
|
|
8
|
+
export default async function init(args) {
|
|
9
|
+
const [type = 'project', name = basename(resolve()), extra] = args;
|
|
10
|
+
if (!['project', 'package'].includes(type) || extra) {
|
|
11
|
+
throw new Error('Run claw init [project|package] [name].');
|
|
12
|
+
}
|
|
13
|
+
if (type === 'package' && !packageNameSchema.safeParse(name).success) {
|
|
14
|
+
throw new Error('Package names must use lowercase letters, numbers, - or _.');
|
|
15
|
+
}
|
|
16
|
+
const script = type === 'project'
|
|
17
|
+
? 'sprites/stage.claw' : 'index.claw';
|
|
18
|
+
const costume = 'sprites/stage.svg';
|
|
19
|
+
if (['claw.json', 'claw_modules', 'claw-lock.json']
|
|
20
|
+
.some(file => existsSync(file))) {
|
|
21
|
+
throw new Error('A Claw project already exists here.');
|
|
22
|
+
}
|
|
23
|
+
const manifest = type === 'project'
|
|
24
|
+
? {
|
|
25
|
+
name,
|
|
26
|
+
version: '1.0.0',
|
|
27
|
+
type,
|
|
28
|
+
sprites: {
|
|
29
|
+
Stage: {
|
|
30
|
+
costume,
|
|
31
|
+
script
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
} : {
|
|
35
|
+
name,
|
|
36
|
+
version: '1.0.0',
|
|
37
|
+
type,
|
|
38
|
+
main: script
|
|
39
|
+
};
|
|
40
|
+
await mkdir(dirname(script), { recursive: true });
|
|
41
|
+
await writeFile(script, defaultClawFile);
|
|
42
|
+
if (type === 'project') {
|
|
43
|
+
await copyFile(defaultCostume, costume);
|
|
44
|
+
}
|
|
45
|
+
await writeFile('claw.json', `${JSON.stringify(manifest, null, 2)}\n`);
|
|
46
|
+
console.log(chalk.green(`Created ${name}.`));
|
|
47
|
+
}
|
|
@@ -0,0 +1,210 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { createWriteStream } from 'node:fs';
|
|
3
|
+
import { mkdir, rm } from 'node:fs/promises';
|
|
4
|
+
import { dirname, join, resolve, sep } from 'node:path';
|
|
5
|
+
import { Readable } from 'node:stream';
|
|
6
|
+
import { pipeline } from 'node:stream/promises';
|
|
7
|
+
import { createGunzip } from 'node:zlib';
|
|
8
|
+
import chalk from 'chalk';
|
|
9
|
+
import { extract } from 'tar-stream';
|
|
10
|
+
import { rcompare, satisfies } from 'semver';
|
|
11
|
+
import { getBackendURL, packageDirectory } from '../config.js';
|
|
12
|
+
import { packageNameSchema, packageVersionSchema, packageVersionsSchema } from '../schemas.js';
|
|
13
|
+
import { getClawLock, writeClawLock } from '../util/claw-lock.js';
|
|
14
|
+
import { getClawFile, writeClawFile } from '../util/claw-file.js';
|
|
15
|
+
const satisfiesAll = (version, constraints) => constraints.every(specifier => satisfies(version, specifier === 'latest' ? '*' : specifier));
|
|
16
|
+
async function resolveDependency(name, specifier, constraints) {
|
|
17
|
+
const registryURL = getBackendURL();
|
|
18
|
+
let requested = specifier;
|
|
19
|
+
if (constraints.length > 1) {
|
|
20
|
+
const response = await fetch(`${registryURL}/packages/${encodeURIComponent(name)}`);
|
|
21
|
+
if (!response.ok) {
|
|
22
|
+
throw new Error(`HTTP ${response.status} while resolving package ${name}`);
|
|
23
|
+
}
|
|
24
|
+
const metadata = packageVersionsSchema.parse(await response.json());
|
|
25
|
+
requested = metadata.versions
|
|
26
|
+
.sort(rcompare)
|
|
27
|
+
.find(version => satisfiesAll(version, constraints)) || '';
|
|
28
|
+
if (!requested) {
|
|
29
|
+
throw new Error(`Conflicting versions requested for package ${name}.`);
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
const response = await fetch(`${registryURL}/packages/${encodeURIComponent(name)}`
|
|
33
|
+
+ `/${encodeURIComponent(requested)}`);
|
|
34
|
+
if (response.status === 404) {
|
|
35
|
+
throw new Error(`Package ${name}@${specifier} was not found.`);
|
|
36
|
+
}
|
|
37
|
+
if (!response.ok) {
|
|
38
|
+
throw new Error(`HTTP ${response.status} while resolving package ${name}@${specifier}`);
|
|
39
|
+
}
|
|
40
|
+
const result = packageVersionSchema.safeParse(await response.json());
|
|
41
|
+
if (!result.success) {
|
|
42
|
+
throw new Error(`Invalid metadata for package ${name}@${specifier}.`);
|
|
43
|
+
}
|
|
44
|
+
return {
|
|
45
|
+
specifier,
|
|
46
|
+
version: result.data.version,
|
|
47
|
+
license: result.data.license,
|
|
48
|
+
dependencies: result.data.dependencies,
|
|
49
|
+
integrity: result.data.dist.integrity
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
async function resolveLock(dependencies, currentLock, refresh = []) {
|
|
53
|
+
const resolved = Object.create(null);
|
|
54
|
+
const resolving = [];
|
|
55
|
+
async function addDependency(name) {
|
|
56
|
+
const reachable = pruneLock(dependencies, {
|
|
57
|
+
lockfileVersion: 1,
|
|
58
|
+
dependencies: resolved
|
|
59
|
+
});
|
|
60
|
+
const direct = Object.hasOwn(dependencies, name)
|
|
61
|
+
? dependencies[name]
|
|
62
|
+
: undefined;
|
|
63
|
+
const constraints = [
|
|
64
|
+
direct,
|
|
65
|
+
...Object.values(reachable.dependencies).map(dependency => {
|
|
66
|
+
const children = dependency.dependencies || {};
|
|
67
|
+
return Object.hasOwn(children, name) ? children[name] : undefined;
|
|
68
|
+
})
|
|
69
|
+
].filter((value, index, values) => Boolean(value) && values.indexOf(value) === index);
|
|
70
|
+
if (!constraints.length) {
|
|
71
|
+
return;
|
|
72
|
+
}
|
|
73
|
+
const specifier = direct || constraints[0];
|
|
74
|
+
const existing = resolved[name];
|
|
75
|
+
if (existing && satisfiesAll(existing.version, constraints)) {
|
|
76
|
+
existing.specifier = specifier;
|
|
77
|
+
return;
|
|
78
|
+
}
|
|
79
|
+
if (resolving.includes(name)) {
|
|
80
|
+
throw new Error(`Conflicting versions requested for package ${name}.`);
|
|
81
|
+
}
|
|
82
|
+
const locked = currentLock?.dependencies[name];
|
|
83
|
+
const dependency = locked?.specifier === specifier
|
|
84
|
+
&& locked.dependencies !== undefined
|
|
85
|
+
&& !refresh.includes(name)
|
|
86
|
+
&& satisfiesAll(locked.version, constraints)
|
|
87
|
+
? locked
|
|
88
|
+
: await resolveDependency(name, specifier, constraints);
|
|
89
|
+
resolved[name] = dependency;
|
|
90
|
+
resolving.push(name);
|
|
91
|
+
for (const child of Object.keys(dependency.dependencies || {})) {
|
|
92
|
+
await addDependency(child);
|
|
93
|
+
}
|
|
94
|
+
resolving.pop();
|
|
95
|
+
}
|
|
96
|
+
for (const name of Object.keys(dependencies)) {
|
|
97
|
+
await addDependency(name);
|
|
98
|
+
}
|
|
99
|
+
return pruneLock(dependencies, {
|
|
100
|
+
lockfileVersion: 1,
|
|
101
|
+
dependencies: resolved
|
|
102
|
+
});
|
|
103
|
+
}
|
|
104
|
+
export function lockMatches(dependencies, lockFile) {
|
|
105
|
+
const pending = Object.keys(dependencies);
|
|
106
|
+
const checked = Object.create(null);
|
|
107
|
+
for (const name of pending) {
|
|
108
|
+
const locked = lockFile.dependencies[name];
|
|
109
|
+
if (!locked) {
|
|
110
|
+
return false;
|
|
111
|
+
}
|
|
112
|
+
if (checked[name]) {
|
|
113
|
+
continue;
|
|
114
|
+
}
|
|
115
|
+
if (Object.hasOwn(dependencies, name)
|
|
116
|
+
&& locked.specifier !== dependencies[name]) {
|
|
117
|
+
return false;
|
|
118
|
+
}
|
|
119
|
+
checked[name] = true;
|
|
120
|
+
pending.push(...Object.keys(locked.dependencies || {}));
|
|
121
|
+
}
|
|
122
|
+
return Object.keys(checked).length
|
|
123
|
+
=== Object.keys(lockFile.dependencies).length;
|
|
124
|
+
}
|
|
125
|
+
export function pruneLock(dependencies, lockFile) {
|
|
126
|
+
const pruned = {
|
|
127
|
+
lockfileVersion: 1,
|
|
128
|
+
dependencies: Object.create(null)
|
|
129
|
+
};
|
|
130
|
+
const pending = Object.keys(dependencies);
|
|
131
|
+
for (const name of pending) {
|
|
132
|
+
if (pruned.dependencies[name]) {
|
|
133
|
+
continue;
|
|
134
|
+
}
|
|
135
|
+
const locked = lockFile.dependencies[name];
|
|
136
|
+
if (!locked) {
|
|
137
|
+
continue;
|
|
138
|
+
}
|
|
139
|
+
pruned.dependencies[name] = locked;
|
|
140
|
+
pending.push(...Object.keys(locked.dependencies || {}));
|
|
141
|
+
}
|
|
142
|
+
return pruned;
|
|
143
|
+
}
|
|
144
|
+
async function installPackage(name, dependency) {
|
|
145
|
+
const response = await fetch(`${getBackendURL()}/packages/${encodeURIComponent(name)}`
|
|
146
|
+
+ `/${encodeURIComponent(dependency.version)}/download`);
|
|
147
|
+
if (!response.ok) {
|
|
148
|
+
throw new Error(`HTTP ${response.status} while fetching package ${name}@${dependency.version}`);
|
|
149
|
+
}
|
|
150
|
+
const content = Buffer.from(await response.arrayBuffer());
|
|
151
|
+
const integrity = `sha512-${createHash('sha512')
|
|
152
|
+
.update(content)
|
|
153
|
+
.digest('base64')}`;
|
|
154
|
+
if (integrity !== dependency.integrity) {
|
|
155
|
+
throw new Error(`Integrity check failed for package ${name}.`);
|
|
156
|
+
}
|
|
157
|
+
const directory = join(packageDirectory, name);
|
|
158
|
+
await rm(directory, {
|
|
159
|
+
recursive: true,
|
|
160
|
+
force: true
|
|
161
|
+
});
|
|
162
|
+
const archive = extract();
|
|
163
|
+
archive.on('entry', (header, stream, next) => {
|
|
164
|
+
const path = resolve(directory, header.name);
|
|
165
|
+
if (header.type !== 'file' || !path.startsWith(directory + sep)) {
|
|
166
|
+
archive.destroy(new Error(`Invalid archive entry: ${header.name}`));
|
|
167
|
+
return;
|
|
168
|
+
}
|
|
169
|
+
mkdir(dirname(path), { recursive: true })
|
|
170
|
+
.then(() => pipeline(stream, createWriteStream(path, { flags: 'wx' })))
|
|
171
|
+
.then(() => next(), next);
|
|
172
|
+
});
|
|
173
|
+
await pipeline(Readable.from([content]), createGunzip(), archive);
|
|
174
|
+
}
|
|
175
|
+
export async function installLockedPackages(lockFile) {
|
|
176
|
+
await Promise.all(Object.entries(lockFile.dependencies).map(([name, dependency]) => (installPackage(name, dependency))));
|
|
177
|
+
}
|
|
178
|
+
export default async function install(packages) {
|
|
179
|
+
const clawFile = getClawFile();
|
|
180
|
+
const dependencies = clawFile.dependencies || {};
|
|
181
|
+
const refresh = [];
|
|
182
|
+
const requested = {};
|
|
183
|
+
for (const specifier of packages) {
|
|
184
|
+
const [name, version = 'latest', extra] = specifier.split('@');
|
|
185
|
+
if (!packageNameSchema.safeParse(name).success
|
|
186
|
+
|| !version || extra !== undefined) {
|
|
187
|
+
throw new Error(`Invalid package specifier: ${specifier}`);
|
|
188
|
+
}
|
|
189
|
+
dependencies[name] = version;
|
|
190
|
+
refresh.push(name);
|
|
191
|
+
requested[name] = version;
|
|
192
|
+
}
|
|
193
|
+
const start = Date.now();
|
|
194
|
+
const lockFile = await resolveLock(dependencies, getClawLock(), refresh);
|
|
195
|
+
for (const [name, specifier] of Object.entries(requested)) {
|
|
196
|
+
if (specifier === 'latest') {
|
|
197
|
+
dependencies[name] = lockFile.dependencies[name].version;
|
|
198
|
+
lockFile.dependencies[name].specifier = dependencies[name];
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
await installLockedPackages(lockFile);
|
|
202
|
+
clawFile.dependencies = dependencies;
|
|
203
|
+
await Promise.all([
|
|
204
|
+
writeClawFile(clawFile),
|
|
205
|
+
writeClawLock(lockFile)
|
|
206
|
+
]);
|
|
207
|
+
const elapsed = Date.now() - start;
|
|
208
|
+
console.log(`Installed ${chalk.greenBright(Object.keys(dependencies).length)} `
|
|
209
|
+
+ `package(s) in ${chalk.yellowBright(elapsed + 'ms')}`);
|
|
210
|
+
}
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
import { createHash, randomBytes } from 'node:crypto';
|
|
2
|
+
import { createServer } from 'node:http';
|
|
3
|
+
import { spawn } from 'node:child_process';
|
|
4
|
+
import chalk from 'chalk';
|
|
5
|
+
import { getClerkOAuthConfig } from '../config.js';
|
|
6
|
+
import { writeCredential } from '../util/credentials.js';
|
|
7
|
+
import { requestOAuthToken } from '../util/oauth.js';
|
|
8
|
+
function openBrowser(url, onError) {
|
|
9
|
+
let command = 'xdg-open';
|
|
10
|
+
let args = [url];
|
|
11
|
+
if (process.platform === 'darwin') {
|
|
12
|
+
command = 'open';
|
|
13
|
+
}
|
|
14
|
+
if (process.platform === 'win32') {
|
|
15
|
+
command = 'cmd';
|
|
16
|
+
args = ['/c', 'start', '', url];
|
|
17
|
+
}
|
|
18
|
+
const browser = spawn(command, args, {
|
|
19
|
+
detached: true,
|
|
20
|
+
stdio: 'ignore'
|
|
21
|
+
});
|
|
22
|
+
browser.once('error', onError);
|
|
23
|
+
browser.unref();
|
|
24
|
+
}
|
|
25
|
+
export default async function login() {
|
|
26
|
+
const clerkOAuth = await getClerkOAuthConfig();
|
|
27
|
+
const authorizationURL = new URL('/oauth/authorize', clerkOAuth.issuer);
|
|
28
|
+
const tokenEndpoint = new URL('/oauth/token', clerkOAuth.issuer).toString();
|
|
29
|
+
const state = randomBytes(32).toString('base64url');
|
|
30
|
+
const codeVerifier = randomBytes(32).toString('base64url');
|
|
31
|
+
const codeChallenge = createHash('sha256')
|
|
32
|
+
.update(codeVerifier)
|
|
33
|
+
.digest('base64url');
|
|
34
|
+
let rejectLogin = () => { };
|
|
35
|
+
let timeout;
|
|
36
|
+
// create a temporary server to recieve the tokens.
|
|
37
|
+
const server = createServer();
|
|
38
|
+
const code = new Promise((resolve, reject) => {
|
|
39
|
+
rejectLogin = reject;
|
|
40
|
+
server.on('request', (request, response) => {
|
|
41
|
+
const url = new URL(request.url || '/', 'http://127.0.0.1');
|
|
42
|
+
const loginCode = url.searchParams.get('code');
|
|
43
|
+
const loginError = url.searchParams.get('error_description')
|
|
44
|
+
|| url.searchParams.get('error');
|
|
45
|
+
if (url.pathname !== '/callback' || url.searchParams.get('state') !== state
|
|
46
|
+
|| (!loginCode && !loginError)) {
|
|
47
|
+
response.writeHead(400).end('Invalid login response');
|
|
48
|
+
return;
|
|
49
|
+
}
|
|
50
|
+
response.writeHead(200, {
|
|
51
|
+
'Content-Type': 'text/html; charset=utf-8',
|
|
52
|
+
'Cache-Control': 'no-store'
|
|
53
|
+
});
|
|
54
|
+
response.end('<!doctype html><title>Claw login</title>'
|
|
55
|
+
+ '<p>Login complete, you can close this window.</p>'
|
|
56
|
+
+ '<script>window.close()</script>', () => {
|
|
57
|
+
if (loginError) {
|
|
58
|
+
reject(new Error(loginError));
|
|
59
|
+
return;
|
|
60
|
+
}
|
|
61
|
+
resolve(loginCode);
|
|
62
|
+
});
|
|
63
|
+
});
|
|
64
|
+
server.once('error', reject);
|
|
65
|
+
});
|
|
66
|
+
await new Promise((resolve, reject) => {
|
|
67
|
+
server.listen(0, '127.0.0.1', resolve);
|
|
68
|
+
server.once('error', reject);
|
|
69
|
+
});
|
|
70
|
+
const address = server.address();
|
|
71
|
+
const redirectURI = `http://127.0.0.1:${address.port}/callback`;
|
|
72
|
+
authorizationURL.searchParams.set('response_type', 'code');
|
|
73
|
+
authorizationURL.searchParams.set('client_id', clerkOAuth.clientId);
|
|
74
|
+
authorizationURL.searchParams.set('redirect_uri', redirectURI);
|
|
75
|
+
authorizationURL.searchParams.set('scope', 'profile offline_access');
|
|
76
|
+
authorizationURL.searchParams.set('state', state);
|
|
77
|
+
authorizationURL.searchParams.set('code_challenge', codeChallenge);
|
|
78
|
+
authorizationURL.searchParams.set('code_challenge_method', 'S256');
|
|
79
|
+
timeout = setTimeout(() => {
|
|
80
|
+
rejectLogin(new Error('Login timed out.'));
|
|
81
|
+
}, 10 * 60 * 1000);
|
|
82
|
+
openBrowser(authorizationURL.toString(), rejectLogin);
|
|
83
|
+
console.log(chalk.yellow('Complete the login in your browser.'));
|
|
84
|
+
try {
|
|
85
|
+
const loginCode = await code;
|
|
86
|
+
const token = await requestOAuthToken(tokenEndpoint, new URLSearchParams({
|
|
87
|
+
grant_type: 'authorization_code',
|
|
88
|
+
client_id: clerkOAuth.clientId,
|
|
89
|
+
redirect_uri: redirectURI,
|
|
90
|
+
code: loginCode,
|
|
91
|
+
code_verifier: codeVerifier
|
|
92
|
+
}));
|
|
93
|
+
if (!token.refreshToken) {
|
|
94
|
+
throw new Error('Clerk did not return a refresh token.');
|
|
95
|
+
}
|
|
96
|
+
await writeCredential({
|
|
97
|
+
accessToken: token.accessToken,
|
|
98
|
+
refreshToken: token.refreshToken,
|
|
99
|
+
expiresAt: Date.now() + token.expiresIn * 1000,
|
|
100
|
+
clientId: clerkOAuth.clientId,
|
|
101
|
+
tokenEndpoint
|
|
102
|
+
});
|
|
103
|
+
console.log(chalk.green('Logged in.'));
|
|
104
|
+
}
|
|
105
|
+
finally {
|
|
106
|
+
clearTimeout(timeout);
|
|
107
|
+
server.close();
|
|
108
|
+
}
|
|
109
|
+
}
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
import { existsSync } from 'node:fs';
|
|
2
|
+
import { readdir, readFile } from 'node:fs/promises';
|
|
3
|
+
import { join, matchesGlob, posix } from 'node:path';
|
|
4
|
+
import { buffer } from 'node:stream/consumers';
|
|
5
|
+
import { pipeline } from 'node:stream/promises';
|
|
6
|
+
import { createGzip } from 'node:zlib';
|
|
7
|
+
import chalk from 'chalk';
|
|
8
|
+
import { pack } from 'tar-stream';
|
|
9
|
+
import { getBackendURL } from '../config.js';
|
|
10
|
+
import { getAccessToken } from '../util/credentials.js';
|
|
11
|
+
async function readIgnoreRules() {
|
|
12
|
+
if (!existsSync('.clawignore')) {
|
|
13
|
+
return [];
|
|
14
|
+
}
|
|
15
|
+
return (await readFile('.clawignore', 'utf8'))
|
|
16
|
+
.split(/\r?\n/)
|
|
17
|
+
.map(line => line.trim())
|
|
18
|
+
.filter(line => line && !line.startsWith('#'))
|
|
19
|
+
.map((line) => {
|
|
20
|
+
const ignored = !line.startsWith('!');
|
|
21
|
+
const original = ignored ? line : line.slice(1);
|
|
22
|
+
const anchored = original.startsWith('/');
|
|
23
|
+
const pattern = original.replace(/^\//, '').replace(/\/$/, '');
|
|
24
|
+
const patterns = anchored || pattern.includes('/')
|
|
25
|
+
? [pattern]
|
|
26
|
+
: [pattern, `**/${pattern}`];
|
|
27
|
+
return {
|
|
28
|
+
ignored,
|
|
29
|
+
patterns: [...patterns, ...patterns.map(value => `${value}/**`)]
|
|
30
|
+
};
|
|
31
|
+
});
|
|
32
|
+
}
|
|
33
|
+
function isIgnored(path, rules) {
|
|
34
|
+
let ignored = false;
|
|
35
|
+
for (const rule of rules) {
|
|
36
|
+
if (rule.patterns.some(pattern => matchesGlob(path, pattern))) {
|
|
37
|
+
ignored = rule.ignored;
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
return ignored;
|
|
41
|
+
}
|
|
42
|
+
async function readPackageFiles(rules, directory = '.', prefix = '') {
|
|
43
|
+
const files = {};
|
|
44
|
+
for (const entry of await readdir(directory, { withFileTypes: true })) {
|
|
45
|
+
if (entry.name.startsWith('.')
|
|
46
|
+
|| ['claw_modules', 'node_modules'].includes(entry.name)) {
|
|
47
|
+
continue;
|
|
48
|
+
}
|
|
49
|
+
const path = join(directory, entry.name);
|
|
50
|
+
const name = posix.join(prefix, entry.name);
|
|
51
|
+
if (entry.isDirectory()) {
|
|
52
|
+
Object.assign(files, await readPackageFiles(rules, path, name));
|
|
53
|
+
}
|
|
54
|
+
else if (entry.isFile() && !isIgnored(name, rules)) {
|
|
55
|
+
files[name] = await readFile(path);
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
return files;
|
|
59
|
+
}
|
|
60
|
+
export default async function publish() {
|
|
61
|
+
const registryURL = getBackendURL();
|
|
62
|
+
const files = await readPackageFiles(await readIgnoreRules());
|
|
63
|
+
files['claw.json'] = await readFile('claw.json');
|
|
64
|
+
if (existsSync('README.md')) {
|
|
65
|
+
files['README.md'] = await readFile('README.md');
|
|
66
|
+
}
|
|
67
|
+
const packageArchive = pack();
|
|
68
|
+
const compressed = pipeline(packageArchive, createGzip(), buffer);
|
|
69
|
+
for (const [path, content] of Object.entries(files)) {
|
|
70
|
+
packageArchive.entry({
|
|
71
|
+
name: path,
|
|
72
|
+
mtime: new Date(0)
|
|
73
|
+
}, content);
|
|
74
|
+
}
|
|
75
|
+
packageArchive.finalize();
|
|
76
|
+
const archive = await compressed;
|
|
77
|
+
const token = await getAccessToken();
|
|
78
|
+
const response = await fetch(`${registryURL}/packages`, {
|
|
79
|
+
method: 'POST',
|
|
80
|
+
headers: {
|
|
81
|
+
Authorization: `Bearer ${token}`,
|
|
82
|
+
'Content-Type': 'application/gzip'
|
|
83
|
+
},
|
|
84
|
+
body: archive
|
|
85
|
+
});
|
|
86
|
+
const body = await response.json();
|
|
87
|
+
if (!response.ok) {
|
|
88
|
+
throw new Error(body.error || `Publish failed with HTTP ${response.status}.`);
|
|
89
|
+
}
|
|
90
|
+
console.log(chalk.green(`Published ${body.name}@${body.version}.`));
|
|
91
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { rm } from 'node:fs/promises';
|
|
2
|
+
import chalk from 'chalk';
|
|
3
|
+
import { packageDirectory } from '../config.js';
|
|
4
|
+
import { pruneLock } from './install.js';
|
|
5
|
+
import { getClawFile, writeClawFile } from '../util/claw-file.js';
|
|
6
|
+
import { getClawLock, writeClawLock } from '../util/claw-lock.js';
|
|
7
|
+
export default async function uninstall(packages) {
|
|
8
|
+
if (packages.length === 0) {
|
|
9
|
+
throw new Error('No packages specified. Run claw uninstall <package>.');
|
|
10
|
+
}
|
|
11
|
+
const clawFile = getClawFile();
|
|
12
|
+
if (!clawFile.dependencies) {
|
|
13
|
+
throw new Error('No packages are installed.');
|
|
14
|
+
}
|
|
15
|
+
const dependencies = clawFile.dependencies;
|
|
16
|
+
const missingPackage = packages.find(name => !Object.hasOwn(dependencies, name));
|
|
17
|
+
if (missingPackage) {
|
|
18
|
+
throw new Error(`Package '${missingPackage}' is not installed.`);
|
|
19
|
+
}
|
|
20
|
+
const start = Date.now();
|
|
21
|
+
const lockFile = getClawLock();
|
|
22
|
+
for (const name of packages) {
|
|
23
|
+
delete dependencies[name];
|
|
24
|
+
}
|
|
25
|
+
const nextLockFile = lockFile && pruneLock(dependencies, lockFile);
|
|
26
|
+
const removed = lockFile
|
|
27
|
+
? Object.keys(lockFile.dependencies).filter(name => !nextLockFile?.dependencies[name])
|
|
28
|
+
: packages;
|
|
29
|
+
await Promise.all(removed.map(name => rm(`${packageDirectory}/${name}`, {
|
|
30
|
+
recursive: true,
|
|
31
|
+
force: true
|
|
32
|
+
})));
|
|
33
|
+
await Promise.all([
|
|
34
|
+
writeClawFile(clawFile),
|
|
35
|
+
nextLockFile && writeClawLock(nextLockFile)
|
|
36
|
+
]);
|
|
37
|
+
const elapsed = Date.now() - start;
|
|
38
|
+
console.log(`Uninstalled ${chalk.greenBright(packages.length)} packages in `
|
|
39
|
+
+ chalk.yellowBright(elapsed + 'ms'));
|
|
40
|
+
}
|