lyrcloud 0.0.0-stage → 0.1.0

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 ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Lyrcloud
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,61 @@
1
- # Temporary Holding Version
1
+ # lyrcloud
2
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.
3
+ The Lyrcloud CLI. Write a `fetch` handler, try it locally, and deploy it to `https://<name>.dev.lyr`.
4
+
5
+ ```bash
6
+ npm install -g lyrcloud
7
+ lyrcloud login
8
+ lyrcloud init hello-edge
9
+ cd hello-edge
10
+ lyrcloud dev # http://localhost:8787
11
+ lyrcloud deploy # https://hello-edge.dev.lyr
12
+ ```
13
+
14
+ Requires Node.js 20 or newer. No dependencies.
15
+
16
+ ## Your function
17
+
18
+ ```js
19
+ export default {
20
+ async fetch(request, env, ctx) {
21
+ return new Response(`${env.GREETING} from ${new URL(request.url).hostname}`);
22
+ },
23
+ };
24
+ ```
25
+
26
+ - `request` is a standard `Request`. `request.geo.ip` is the visitor's IP address.
27
+ - `env` holds the `vars` from `lyrcloud.json`.
28
+ - `ctx.waitUntil(promise)` finishes work after the response is ready.
29
+ - Return a standard `Response`.
30
+
31
+ ## lyrcloud.json
32
+
33
+ ```json
34
+ {
35
+ "name": "hello-edge",
36
+ "main": "index.js",
37
+ "vars": { "GREETING": "Hello" },
38
+ "exclude": ["fixtures"]
39
+ }
40
+ ```
41
+
42
+ `deploy` uploads the project folder plus the packages listed under `dependencies` in `package.json`. It never uploads `node_modules` dev packages, `.git` or `.env`. Uploads can be up to 4 MB zipped.
43
+
44
+ ## Commands
45
+
46
+ | Command | What it does |
47
+ |---|---|
48
+ | `lyrcloud login [--email]` | Sign in in the browser (or with email and password) |
49
+ | `lyrcloud logout` / `whoami` | Sign out / show who you're signed in as |
50
+ | `lyrcloud init <name>` | Create a project in `./<name>` |
51
+ | `lyrcloud dev [--port 8787]` | Run locally with the production runtime, reloading on edits |
52
+ | `lyrcloud deploy [--name x]` | Deploy and print the address |
53
+ | `lyrcloud list` | Your functions |
54
+ | `lyrcloud logs [name] [-f] [--since 2h]` | Recent logs; `-f` follows |
55
+ | `lyrcloud delete [name] [--yes]` | Take a function offline and free its name |
56
+
57
+ ## .lyr addresses
58
+
59
+ `.dev.lyr` is part of Lyrcloud's own `.lyr` namespace. It opens on devices that use Lyr DNS and trust the Lyr Root CA. See https://www.lyrcloud.com/lyr/ for setup.
60
+
61
+ Sign-in is stored in `~/.config/lyrcloud/credentials.json`, readable only by you. Set `LYRCLOUD_API_URL` to use a different API.
@@ -0,0 +1,312 @@
1
+ #!/usr/bin/env node
2
+ // The Lyrcloud CLI: build and deploy edge functions to https://<name>.dev.lyr.
3
+ import { fork } from 'node:child_process';
4
+ import { existsSync, mkdirSync, readdirSync, readFileSync, watch, writeFileSync } from 'node:fs';
5
+ import path from 'node:path';
6
+ import { fileURLToPath } from 'node:url';
7
+ import { ApiError, api } from '../lib/api.mjs';
8
+ import { AuthError, browserLogin, decodeJwt, passwordLogin, revoke } from '../lib/auth.mjs';
9
+ import { credentialsPath, deleteCredentials, DOCS_URL, FUNCTIONS_DOMAIN, LYR_SETUP_URL, readCredentials } from '../lib/config.mjs';
10
+ import { CONFIG_FILE, collectFiles, loadProject, nameError, ProjectError, projectSize } from '../lib/project.mjs';
11
+ import { ask, bold, cyan, dim, fail, formatBytes, ok, relativeTime, table, warn } from '../lib/ui.mjs';
12
+ import { createZip } from '../lib/zip.mjs';
13
+
14
+ const here = path.dirname(fileURLToPath(import.meta.url));
15
+ const { version } = JSON.parse(readFileSync(path.join(here, '..', 'package.json'), 'utf8'));
16
+ const MAX_ZIP = 4 * 1024 * 1024;
17
+
18
+ const HELP = `${bold('lyrcloud')} ${dim(`v${version}`)} — deploy edge functions to https://<name>.${FUNCTIONS_DOMAIN}
19
+
20
+ ${bold('Usage')}
21
+ lyrcloud <command> [options]
22
+
23
+ ${bold('Commands')}
24
+ login [--email] Sign in (opens your browser; --email for email and password)
25
+ logout Sign out on this computer
26
+ whoami Show who you're signed in as
27
+ init <name> Create a new function project in ./<name>
28
+ dev [--port 8787] Run the project locally, reloading on changes
29
+ deploy [--name <name>] Upload the project and make it live
30
+ list List your functions
31
+ logs [name] [-f] [--since 15m] Show recent logs (-f keeps following)
32
+ delete [name] [--yes] Take a function down and free its name
33
+
34
+ ${bold('Options')}
35
+ -h, --help Show help
36
+ -v, --version Show the version
37
+
38
+ Docs: ${DOCS_URL}`;
39
+
40
+ // ---------------------------------------------------------------- arguments
41
+
42
+ function parseArgs(argv) {
43
+ const positional = [];
44
+ const flags = {};
45
+ const aliases = { f: 'follow', y: 'yes', p: 'port', h: 'help', v: 'version', n: 'name' };
46
+ const valued = new Set(['port', 'since', 'name']);
47
+ for (let i = 0; i < argv.length; i += 1) {
48
+ const arg = argv[i];
49
+ if (arg === '--') {
50
+ positional.push(...argv.slice(i + 1));
51
+ break;
52
+ }
53
+ const long = /^--([^=]+)(?:=(.*))?$/.exec(arg);
54
+ const short = /^-([a-zA-Z])$/.exec(arg);
55
+ if (long || short) {
56
+ const key = long ? long[1] : aliases[short[1]] || short[1];
57
+ if (long && long[2] !== undefined) flags[key] = long[2];
58
+ else if (valued.has(key) && argv[i + 1] !== undefined && !argv[i + 1].startsWith('-')) flags[key] = argv[(i += 1)];
59
+ else flags[key] = true;
60
+ } else {
61
+ positional.push(arg);
62
+ }
63
+ }
64
+ return { command: positional[0], args: positional.slice(1), flags };
65
+ }
66
+
67
+ class UsageError extends Error {}
68
+
69
+ // ---------------------------------------------------------------- commands
70
+
71
+ async function login(_, flags) {
72
+ if (flags.email) {
73
+ const email = typeof flags.email === 'string' ? flags.email : await ask('Email: ');
74
+ const password = await ask('Password: ', { hidden: true });
75
+ if (!email || !password) throw new UsageError('Enter your email and password.');
76
+ const who = await passwordLogin(email, password);
77
+ ok(`Signed in as ${bold(who.email || email)}`);
78
+ return;
79
+ }
80
+ const provider = flags.google ? 'GoogleOIDC' : undefined;
81
+ const who = await browserLogin({ provider });
82
+ ok(`Signed in as ${bold(who.email || who.name || 'your Lyrcloud account')}`);
83
+ }
84
+
85
+ async function logout() {
86
+ await revoke();
87
+ if (deleteCredentials()) ok('Signed out.');
88
+ else console.log('You weren’t signed in.');
89
+ }
90
+
91
+ async function whoami() {
92
+ const credentials = readCredentials();
93
+ if (!credentials?.idToken) {
94
+ console.log('Not signed in. Run lyrcloud login.');
95
+ process.exitCode = 1;
96
+ return;
97
+ }
98
+ const claims = decodeJwt(credentials.idToken);
99
+ console.log(`${bold(credentials.email || claims.email || 'Signed in')}${credentials.name ? ` (${credentials.name})` : ''}`);
100
+ console.log(dim(`Credentials: ${credentialsPath()}`));
101
+ }
102
+
103
+ const TEMPLATE = `// Your edge function. Every request to https://<name>.${FUNCTIONS_DOMAIN} calls fetch().
104
+ // request is a standard Request; return a standard Response.
105
+ // env holds the "vars" from lyrcloud.json. ctx.waitUntil(promise) finishes work after responding.
106
+ export default {
107
+ async fetch(request, env, ctx) {
108
+ const url = new URL(request.url);
109
+
110
+ if (url.pathname === '/api/time') {
111
+ return Response.json({ now: new Date().toISOString() });
112
+ }
113
+
114
+ return new Response(\`\${env.GREETING} from \${url.hostname}!\\n\`, {
115
+ headers: { 'content-type': 'text/plain; charset=utf-8' },
116
+ });
117
+ },
118
+ };
119
+ `;
120
+
121
+ async function init([name], flags) {
122
+ if (!name) throw new UsageError('Give the project a name: lyrcloud init <name>');
123
+ const problem = nameError(name);
124
+ if (problem) throw new UsageError(problem);
125
+ const dir = path.resolve(name);
126
+ if (existsSync(dir) && readdirSync(dir).length && !flags.force) throw new UsageError(`${name}/ already exists and isn’t empty. Use --force to write into it.`);
127
+ mkdirSync(dir, { recursive: true });
128
+ const files = {
129
+ [CONFIG_FILE]: `${JSON.stringify({ name, main: 'index.js', vars: { GREETING: 'Hello' } }, null, 2)}\n`,
130
+ 'index.js': TEMPLATE.replace('<name>', name),
131
+ 'package.json': `${JSON.stringify({ name, version: '0.0.0', private: true, type: 'module', scripts: { dev: 'lyrcloud dev', deploy: 'lyrcloud deploy' } }, null, 2)}\n`,
132
+ '.gitignore': 'node_modules/\n.lyrcloud/\n.env\n',
133
+ };
134
+ for (const [file, content] of Object.entries(files)) {
135
+ if (existsSync(path.join(dir, file)) && !flags.force) continue;
136
+ writeFileSync(path.join(dir, file), content);
137
+ }
138
+ ok(`Created ${bold(name)} in ./${path.relative(process.cwd(), dir) || '.'}`);
139
+ console.log(`
140
+ cd ${name}
141
+ lyrcloud dev ${dim('# try it at http://localhost:8787')}
142
+ lyrcloud deploy ${dim(`# go live at https://${name}.${FUNCTIONS_DOMAIN}`)}`);
143
+ }
144
+
145
+ async function dev(_, flags) {
146
+ const { root, config } = loadProject();
147
+ const port = Number(flags.port || 8787);
148
+ if (!Number.isInteger(port) || port < 1 || port > 65535) throw new UsageError('Use a port between 1 and 65535.');
149
+ let child;
150
+ let restarting = false;
151
+ const start = (first) => {
152
+ child = fork(path.join(here, '..', 'lib', 'dev-server.mjs'), [root, String(port)], { stdio: 'inherit' });
153
+ child.once('message', () => {
154
+ if (first) {
155
+ ok(`${bold(config.name || 'Your function')} is running at ${cyan(`http://localhost:${port}`)}`);
156
+ console.log(dim('Edits reload automatically. Press Ctrl+C to stop.\n'));
157
+ } else {
158
+ console.log(dim('↻ reloaded'));
159
+ }
160
+ });
161
+ child.once('exit', (code) => {
162
+ if (!restarting && code) {
163
+ fail('The dev server stopped.');
164
+ process.exit(code);
165
+ }
166
+ });
167
+ };
168
+ start(true);
169
+ let timer;
170
+ const ignored = /(^|[/\\])(node_modules|\.git|\.lyrcloud)([/\\]|$)|\.log$|~$|\.sw[px]$/;
171
+ try {
172
+ watch(root, { recursive: true }, (_event, file) => {
173
+ if (file && ignored.test(file)) return;
174
+ clearTimeout(timer);
175
+ timer = setTimeout(() => {
176
+ restarting = true;
177
+ child.once('exit', () => {
178
+ restarting = false;
179
+ start(false);
180
+ });
181
+ child.kill();
182
+ }, 150);
183
+ });
184
+ } catch {
185
+ warn('This system can’t watch folders, so restart lyrcloud dev after editing.');
186
+ }
187
+ const stop = () => {
188
+ child?.kill();
189
+ process.exit(0);
190
+ };
191
+ process.on('SIGINT', stop);
192
+ process.on('SIGTERM', stop);
193
+ await new Promise(() => {});
194
+ }
195
+
196
+ async function deploy(_, flags) {
197
+ const { root, config } = loadProject();
198
+ const name = typeof flags.name === 'string' ? flags.name : config.name;
199
+ if (!name) throw new UsageError(`Set "name" in ${CONFIG_FILE} or pass --name.`);
200
+ const problem = nameError(name);
201
+ if (problem) throw new UsageError(problem);
202
+ const files = collectFiles(root, config);
203
+ const zip = createZip(files);
204
+ if (zip.length > MAX_ZIP) {
205
+ throw new UsageError(`The project is ${formatBytes(zip.length)} zipped; functions can be at most ${formatBytes(MAX_ZIP)}. Leave out large files with "exclude" in ${CONFIG_FILE}, or bundle your code.`);
206
+ }
207
+ console.log(dim(`Uploading ${files.length} file${files.length === 1 ? '' : 's'} (${formatBytes(projectSize(files))}, ${formatBytes(zip.length)} zipped)…`));
208
+ const started = Date.now();
209
+ const { function: fn } = await api('PUT', `/functions/${name}`, { body: { code: zip.toString('base64'), main: config.main, vars: config.vars || {} } });
210
+ ok(`Deployed ${bold(name)} ${dim(`in ${((Date.now() - started) / 1000).toFixed(1)}s`)}`);
211
+ console.log(` ${cyan(fn.url)}`);
212
+ if (fn.deploys === 1) {
213
+ console.log(dim('\n New addresses take about a minute to start answering.'));
214
+ console.log(dim(` .lyr addresses open on devices set up for Lyr DNS: ${LYR_SETUP_URL}`));
215
+ }
216
+ }
217
+
218
+ async function list() {
219
+ const { functions, limit, plan } = await api('GET', '/functions');
220
+ if (!functions.length) {
221
+ console.log(`No functions yet. Create one with ${bold('lyrcloud init <name>')}.`);
222
+ return;
223
+ }
224
+ table(functions.map((fn) => [fn.name, fn.status, fn.url, relativeTime(fn.updatedAt || fn.createdAt)]), ['NAME', 'STATUS', 'URL', 'UPDATED']);
225
+ console.log(dim(`\n${functions.length} of ${limit} functions on the ${plan} plan`));
226
+ }
227
+
228
+ function nameFor(args, flags) {
229
+ if (args[0]) return args[0];
230
+ if (typeof flags.name === 'string') return flags.name;
231
+ try {
232
+ const { config } = loadProject();
233
+ if (config.name) return config.name;
234
+ } catch {
235
+ // no project here
236
+ }
237
+ throw new UsageError('Name the function, or run this inside its project folder.');
238
+ }
239
+
240
+ async function logs(args, flags) {
241
+ const name = nameFor(args, flags);
242
+ const since = typeof flags.since === 'string' ? flags.since : '15m';
243
+ const seen = new Set();
244
+ const print = (events) => {
245
+ for (const event of events) {
246
+ if (seen.has(event.id)) continue;
247
+ seen.add(event.id);
248
+ console.log(`${dim(event.time.replace('T', ' ').slice(0, 19))} ${event.message}`);
249
+ }
250
+ };
251
+ let next = null;
252
+ let printed = 0;
253
+ do {
254
+ const page = await api('GET', `/functions/${name}/logs`, { query: { since, next } });
255
+ print(page.events);
256
+ printed += page.events.length;
257
+ next = page.next;
258
+ } while (next);
259
+ if (!flags.follow) {
260
+ if (!printed) console.log(dim(`No logs for ${name} in the last ${since}.`));
261
+ return;
262
+ }
263
+ console.log(dim(`Following ${name}… (Ctrl+C to stop)`));
264
+ let from = Date.now() - 5000;
265
+ for (;;) {
266
+ await new Promise((resolve) => setTimeout(resolve, 2000));
267
+ const page = await api('GET', `/functions/${name}/logs`, { query: { since: String(from) } });
268
+ print(page.events);
269
+ if (page.events.length) from = Math.max(from, Date.parse(page.events.at(-1).time) - 1000);
270
+ if (seen.size > 5000) seen.clear();
271
+ }
272
+ }
273
+
274
+ async function remove(args, flags) {
275
+ const name = nameFor(args, flags);
276
+ if (!flags.yes) {
277
+ if (!process.stdin.isTTY) throw new UsageError(`Add --yes to delete ${name} without a prompt.`);
278
+ const answer = await ask(`Delete ${bold(name)} and take https://${name}.${FUNCTIONS_DOMAIN} offline? Type the name to confirm: `);
279
+ if (answer !== name) {
280
+ console.log('Nothing deleted.');
281
+ return;
282
+ }
283
+ }
284
+ await api('DELETE', `/functions/${name}`);
285
+ ok(`Deleted ${bold(name)}.`);
286
+ }
287
+
288
+ const COMMANDS = { login, logout, whoami, init, dev, deploy, list, ls: list, logs, tail: logs, delete: remove, rm: remove };
289
+
290
+ // ---------------------------------------------------------------- main
291
+
292
+ const { command, args, flags } = parseArgs(process.argv.slice(2));
293
+ if (flags.version && !command) {
294
+ console.log(version);
295
+ } else if (!command || flags.help || command === 'help') {
296
+ console.log(HELP);
297
+ } else if (!COMMANDS[command]) {
298
+ fail(`Unknown command “${command}”.`);
299
+ console.log(`\n${HELP}`);
300
+ process.exitCode = 1;
301
+ } else {
302
+ try {
303
+ await COMMANDS[command](args, flags);
304
+ } catch (err) {
305
+ if (err instanceof UsageError || err instanceof ProjectError || err instanceof AuthError || err instanceof ApiError) {
306
+ fail(err.message);
307
+ } else {
308
+ fail(err.stack || String(err));
309
+ }
310
+ process.exitCode = 1;
311
+ }
312
+ }
package/lib/api.mjs ADDED
@@ -0,0 +1,38 @@
1
+ // Calls to the Edge Functions API with your sign-in attached.
2
+ import { idToken } from './auth.mjs';
3
+ import { API_URL } from './config.mjs';
4
+
5
+ export class ApiError extends Error {
6
+ constructor(status, message) {
7
+ super(message);
8
+ this.status = status;
9
+ }
10
+ }
11
+
12
+ export async function api(method, path, { body, query } = {}) {
13
+ if (API_URL.endsWith('.invalid')) throw new ApiError(0, 'This build of the CLI has no Lyrcloud API address. Update it with npm install -g lyrcloud@latest.');
14
+ const token = await idToken();
15
+ const url = new URL(API_URL + path);
16
+ for (const [key, value] of Object.entries(query || {})) if (value !== undefined && value !== null) url.searchParams.set(key, value);
17
+ let response;
18
+ try {
19
+ response = await fetch(url, {
20
+ method,
21
+ headers: { authorization: `Bearer ${token}`, ...(body ? { 'content-type': 'application/json' } : {}) },
22
+ body: body ? JSON.stringify(body) : undefined,
23
+ });
24
+ } catch (err) {
25
+ throw new ApiError(0, `Couldn’t reach Lyrcloud (${err.cause?.code || err.message}). Check your connection.`);
26
+ }
27
+ const text = await response.text();
28
+ let data = {};
29
+ try {
30
+ data = text ? JSON.parse(text) : {};
31
+ } catch {
32
+ data = { error: text.slice(0, 300) };
33
+ }
34
+ if (response.status === 401) throw new ApiError(401, 'Your sign-in was refused. Run lyrcloud login again.');
35
+ if (response.status === 413) throw new ApiError(413, data.error || 'The upload is too large.');
36
+ if (!response.ok) throw new ApiError(response.status, data.error || data.message || `Lyrcloud answered ${response.status}.`);
37
+ return data;
38
+ }
package/lib/auth.mjs ADDED
@@ -0,0 +1,192 @@
1
+ // Signing in. `lyrcloud login` opens Lyrcloud's sign-in page (Cognito Hosted UI, the same one the website
2
+ // uses) with PKCE and catches the redirect on http://localhost:5173/callback.html. `--email` signs in
3
+ // with an email and password instead. The ID token is sent to the API and refreshed with the refresh token.
4
+ import { spawn } from 'node:child_process';
5
+ import { createHash, randomBytes } from 'node:crypto';
6
+ import { createServer } from 'node:http';
7
+ import { CLIENT_ID, COGNITO_DOMAIN, COGNITO_REGION, LOGIN_PORTS, readCredentials, writeCredentials } from './config.mjs';
8
+
9
+ export class AuthError extends Error {}
10
+
11
+ const base64url = (buf) => buf.toString('base64').replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
12
+
13
+ export function decodeJwt(token) {
14
+ try {
15
+ return JSON.parse(Buffer.from(String(token).split('.')[1], 'base64url').toString('utf8'));
16
+ } catch {
17
+ return {};
18
+ }
19
+ }
20
+
21
+ function saveTokens(tokens, previous = {}) {
22
+ const claims = decodeJwt(tokens.id_token);
23
+ const credentials = {
24
+ idToken: tokens.id_token,
25
+ refreshToken: tokens.refresh_token || previous.refreshToken,
26
+ expiresAt: (claims.exp || Math.floor(Date.now() / 1000) + 3600) * 1000,
27
+ email: claims.email || previous.email || null,
28
+ name: claims.name || previous.name || null,
29
+ sub: claims.sub || previous.sub || null,
30
+ };
31
+ writeCredentials(credentials);
32
+ return credentials;
33
+ }
34
+
35
+ export function openBrowser(url) {
36
+ const [command, args] = process.platform === 'darwin' ? ['open', [url]]
37
+ : process.platform === 'win32' ? ['cmd', ['/c', 'start', '""', url.replace(/&/g, '^&')]]
38
+ : ['xdg-open', [url]];
39
+ try {
40
+ const child = spawn(command, args, { stdio: 'ignore', detached: true });
41
+ child.on('error', () => {});
42
+ child.unref();
43
+ } catch {
44
+ // The URL is printed too.
45
+ }
46
+ }
47
+
48
+ function listen(port, handler) {
49
+ return new Promise((resolve, reject) => {
50
+ const server = createServer(handler);
51
+ server.once('error', reject);
52
+ server.listen(port, '127.0.0.1', () => resolve(server));
53
+ });
54
+ }
55
+
56
+ const page = (title, text) => `<!doctype html><meta charset="utf-8"><meta name="viewport" content="width=device-width"><title>${title}</title><body style="font-family:system-ui,sans-serif;max-width:30rem;margin:20vh auto;padding:0 1rem;line-height:1.5;text-align:center"><h1>${title}</h1><p>${text}</p></body>`;
57
+
58
+ export async function browserLogin({ provider, log = console.log, timeoutMs = 5 * 60_000 } = {}) {
59
+ const verifier = base64url(randomBytes(32));
60
+ const state = base64url(randomBytes(16));
61
+ const challenge = base64url(createHash('sha256').update(verifier).digest());
62
+
63
+ let server;
64
+ let port;
65
+ let settle;
66
+ const result = new Promise((resolve, reject) => { settle = { resolve, reject }; });
67
+ const onRequest = (req, res) => {
68
+ const url = new URL(req.url, `http://localhost:${port}`);
69
+ if (url.pathname !== '/callback.html') {
70
+ res.writeHead(404).end();
71
+ return;
72
+ }
73
+ const send = (status, title, text) => res.writeHead(status, { 'content-type': 'text/html; charset=utf-8' }).end(page(title, text));
74
+ if (url.searchParams.get('state') !== state) {
75
+ send(400, 'Sign-in didn’t match', 'Run <code>lyrcloud login</code> again.');
76
+ return;
77
+ }
78
+ if (url.searchParams.get('error')) {
79
+ send(400, 'Sign-in failed', url.searchParams.get('error_description') || url.searchParams.get('error'));
80
+ settle.reject(new AuthError(url.searchParams.get('error_description') || url.searchParams.get('error')));
81
+ return;
82
+ }
83
+ const code = url.searchParams.get('code');
84
+ if (!code) {
85
+ send(400, 'Sign-in failed', 'No sign-in code came back. Run <code>lyrcloud login</code> again.');
86
+ return;
87
+ }
88
+ send(200, '✓ Signed in', 'You can close this window and return to the terminal.');
89
+ settle.resolve(code);
90
+ };
91
+ for (const candidate of LOGIN_PORTS) {
92
+ try {
93
+ server = await listen(candidate, onRequest);
94
+ port = candidate;
95
+ break;
96
+ } catch (err) {
97
+ if (err.code !== 'EADDRINUSE') throw err;
98
+ }
99
+ }
100
+ if (!server) throw new AuthError(`Ports ${LOGIN_PORTS.join(' and ')} are busy (a dev server, perhaps). Stop it and run lyrcloud login again, or use lyrcloud login --email.`);
101
+
102
+ const redirectUri = `http://localhost:${port}/callback.html`;
103
+ const authorize = new URL(`https://${COGNITO_DOMAIN}/oauth2/authorize`);
104
+ authorize.search = new URLSearchParams({
105
+ response_type: 'code',
106
+ client_id: CLIENT_ID,
107
+ redirect_uri: redirectUri,
108
+ scope: 'openid email profile',
109
+ state,
110
+ code_challenge: challenge,
111
+ code_challenge_method: 'S256',
112
+ ...(provider ? { identity_provider: provider } : {}),
113
+ }).toString();
114
+
115
+ log('Opening your browser to sign in to Lyrcloud…');
116
+ log(`If it doesn’t open, visit:\n ${authorize}\n`);
117
+ openBrowser(authorize.toString());
118
+
119
+ const timer = setTimeout(() => settle.reject(new AuthError('Sign-in timed out. Run lyrcloud login again.')), timeoutMs);
120
+ try {
121
+ const code = await result;
122
+ const response = await fetch(`https://${COGNITO_DOMAIN}/oauth2/token`, {
123
+ method: 'POST',
124
+ headers: { 'content-type': 'application/x-www-form-urlencoded' },
125
+ body: new URLSearchParams({ grant_type: 'authorization_code', client_id: CLIENT_ID, code, redirect_uri: redirectUri, code_verifier: verifier }),
126
+ });
127
+ const tokens = await response.json().catch(() => ({}));
128
+ if (!response.ok || !tokens.id_token) throw new AuthError(`Sign-in failed: ${tokens.error_description || tokens.error || response.status}`);
129
+ return saveTokens(tokens);
130
+ } finally {
131
+ clearTimeout(timer);
132
+ server.close();
133
+ }
134
+ }
135
+
136
+ async function cognito(target, body) {
137
+ const response = await fetch(`https://cognito-idp.${COGNITO_REGION}.amazonaws.com/`, {
138
+ method: 'POST',
139
+ headers: { 'content-type': 'application/x-amz-json-1.1', 'x-amz-target': `AWSCognitoIdentityProviderService.${target}` },
140
+ body: JSON.stringify(body),
141
+ });
142
+ const data = await response.json().catch(() => ({}));
143
+ if (!response.ok) {
144
+ const type = String(data.__type || '').split('#').pop();
145
+ const err = new AuthError(data.message || type || `Cognito answered ${response.status}`);
146
+ err.type = type;
147
+ throw err;
148
+ }
149
+ return data;
150
+ }
151
+
152
+ export async function passwordLogin(email, password) {
153
+ let data;
154
+ try {
155
+ data = await cognito('InitiateAuth', { ClientId: CLIENT_ID, AuthFlow: 'USER_PASSWORD_AUTH', AuthParameters: { USERNAME: email, PASSWORD: password } });
156
+ } catch (err) {
157
+ if (err.type === 'InvalidParameterException' && /USER_PASSWORD_AUTH/.test(err.message)) {
158
+ throw new AuthError('Email sign-in isn’t switched on for the CLI yet. Use lyrcloud login (browser) instead.');
159
+ }
160
+ if (err.type === 'NotAuthorizedException') throw new AuthError('Wrong email or password.');
161
+ if (err.type === 'UserNotConfirmedException') throw new AuthError('Confirm your email first: finish signing up at https://www.lyrcloud.com/sign-up/.');
162
+ throw err;
163
+ }
164
+ if (data.ChallengeName) throw new AuthError(`This account needs ${data.ChallengeName} to sign in. Use lyrcloud login (browser) instead.`);
165
+ const result = data.AuthenticationResult;
166
+ return saveTokens({ id_token: result.IdToken, refresh_token: result.RefreshToken });
167
+ }
168
+
169
+ // A valid ID token, refreshed when it's within a minute of expiring. Throws AuthError when signed out.
170
+ export async function idToken() {
171
+ const credentials = readCredentials();
172
+ if (!credentials?.idToken) throw new AuthError('You’re not signed in. Run lyrcloud login first.');
173
+ if (credentials.expiresAt - Date.now() > 60_000) return credentials.idToken;
174
+ if (!credentials.refreshToken) throw new AuthError('Your sign-in has expired. Run lyrcloud login again.');
175
+ try {
176
+ const data = await cognito('InitiateAuth', { ClientId: CLIENT_ID, AuthFlow: 'REFRESH_TOKEN_AUTH', AuthParameters: { REFRESH_TOKEN: credentials.refreshToken } });
177
+ return saveTokens({ id_token: data.AuthenticationResult.IdToken }, credentials).idToken;
178
+ } catch (err) {
179
+ if (err instanceof AuthError && err.type) throw new AuthError('Your sign-in has expired. Run lyrcloud login again.');
180
+ throw err;
181
+ }
182
+ }
183
+
184
+ export async function revoke() {
185
+ const credentials = readCredentials();
186
+ if (!credentials?.refreshToken) return;
187
+ await fetch(`https://${COGNITO_DOMAIN}/oauth2/revoke`, {
188
+ method: 'POST',
189
+ headers: { 'content-type': 'application/x-www-form-urlencoded' },
190
+ body: new URLSearchParams({ token: credentials.refreshToken, client_id: CLIENT_ID }),
191
+ }).catch(() => {});
192
+ }
package/lib/config.mjs ADDED
@@ -0,0 +1,52 @@
1
+ // Where the CLI talks to and where it keeps your sign-in.
2
+ import { chmodSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
3
+ import { homedir } from 'node:os';
4
+ import path from 'node:path';
5
+
6
+ // The Edge Functions API (stack lyrcloud-functions). LYRCLOUD_API_URL overrides it.
7
+ export const DEFAULT_API = 'https://0mxmbgsbqd.execute-api.us-east-1.amazonaws.com';
8
+ export const API_URL = (process.env.LYRCLOUD_API_URL || DEFAULT_API).replace(/\/$/, '');
9
+
10
+ // The same Cognito app the website signs in with. Its allowed callbacks include
11
+ // http://localhost:5173/callback.html and :5174, which `lyrcloud login` listens on.
12
+ export const COGNITO_DOMAIN = 'lyrcloud-auth.auth.us-east-1.amazoncognito.com';
13
+ export const COGNITO_REGION = 'us-east-1';
14
+ export const CLIENT_ID = '5h78n6dkjbhq92423lscfllj6t';
15
+ export const LOGIN_PORTS = [5173, 5174];
16
+ export const FUNCTIONS_DOMAIN = 'dev.lyr';
17
+ export const DOCS_URL = 'https://www.lyrcloud.com/developers/';
18
+ export const LYR_SETUP_URL = 'https://www.lyrcloud.com/lyr/';
19
+
20
+ const configDir = () => {
21
+ if (process.env.LYRCLOUD_CONFIG_DIR) return process.env.LYRCLOUD_CONFIG_DIR;
22
+ if (process.platform === 'win32') return path.join(process.env.APPDATA || path.join(homedir(), 'AppData', 'Roaming'), 'lyrcloud');
23
+ return path.join(process.env.XDG_CONFIG_HOME || path.join(homedir(), '.config'), 'lyrcloud');
24
+ };
25
+ export const credentialsPath = () => path.join(configDir(), 'credentials.json');
26
+
27
+ export function readCredentials() {
28
+ try {
29
+ return JSON.parse(readFileSync(credentialsPath(), 'utf8'));
30
+ } catch {
31
+ return null;
32
+ }
33
+ }
34
+
35
+ // Only you can read the file: it holds a refresh token that's good for 30 days.
36
+ export function writeCredentials(credentials) {
37
+ const file = credentialsPath();
38
+ mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
39
+ writeFileSync(file, `${JSON.stringify(credentials, null, 2)}\n`, { mode: 0o600 });
40
+ try {
41
+ chmodSync(file, 0o600);
42
+ } catch {
43
+ // Windows: permissions come from the user profile folder
44
+ }
45
+ }
46
+
47
+ export function deleteCredentials() {
48
+ const file = credentialsPath();
49
+ if (!existsSync(file)) return false;
50
+ rmSync(file);
51
+ return true;
52
+ }
@@ -0,0 +1,64 @@
1
+ // `lyrcloud dev` runs this in a child process (restarted when files change). It serves the project on
2
+ // localhost through runtime.mjs, the same runtime deployed functions use (an identical copy of
3
+ // api/functions/runtime.mjs), by turning each request into the event API Gateway would send.
4
+ import { createServer } from 'node:http';
5
+ import path from 'node:path';
6
+ import { pathToFileURL } from 'node:url';
7
+ import { loadProject } from './project.mjs';
8
+ import { run } from './runtime.mjs';
9
+
10
+ const [root, portText] = process.argv.slice(2);
11
+ const { config } = loadProject(root);
12
+ process.env.LYR_VARS = JSON.stringify(config.vars || {});
13
+
14
+ let mod;
15
+ let loadError = null;
16
+ try {
17
+ mod = await import(pathToFileURL(path.join(root, config.main)).href);
18
+ } catch (err) {
19
+ loadError = err;
20
+ console.error(`Couldn’t load ${config.main}:`, err);
21
+ }
22
+
23
+ function toEvent(req, body, port) {
24
+ const url = new URL(req.url, `http://localhost:${port}`);
25
+ const headers = {};
26
+ for (const [name, value] of Object.entries(req.headers)) headers[name] = Array.isArray(value) ? value.join(', ') : value;
27
+ const cookies = headers.cookie ? headers.cookie.split(/;\s*/) : undefined;
28
+ delete headers.cookie;
29
+ headers.host = `${config.name || 'localhost'}.dev.lyr`;
30
+ return {
31
+ version: '2.0',
32
+ rawPath: url.pathname,
33
+ rawQueryString: url.search.slice(1),
34
+ headers,
35
+ cookies,
36
+ requestContext: { domainName: headers.host, http: { method: req.method, path: url.pathname, sourceIp: req.socket.remoteAddress } },
37
+ body: body.length ? body.toString('base64') : undefined,
38
+ isBase64Encoded: body.length > 0,
39
+ };
40
+ }
41
+
42
+ const port = Number(portText);
43
+ const server = createServer(async (req, res) => {
44
+ const chunks = [];
45
+ for await (const chunk of req) chunks.push(chunk);
46
+ const started = Date.now();
47
+ let result;
48
+ if (loadError) {
49
+ result = { statusCode: 500, headers: { 'content-type': 'text/plain; charset=utf-8' }, body: `Couldn’t load ${config.main}:\n\n${loadError.stack || loadError}` };
50
+ } else {
51
+ result = await run(mod, toEvent(req, Buffer.concat(chunks), port));
52
+ }
53
+ const headers = { ...result.headers };
54
+ if (result.cookies?.length) headers['set-cookie'] = result.cookies;
55
+ res.writeHead(result.statusCode, headers);
56
+ res.end(result.isBase64Encoded ? Buffer.from(result.body || '', 'base64') : result.body || '');
57
+ const status = result.statusCode >= 500 ? `\x1b[31m${result.statusCode}\x1b[0m` : result.statusCode >= 400 ? `\x1b[33m${result.statusCode}\x1b[0m` : result.statusCode;
58
+ console.log(`${req.method} ${req.url} ${status} ${Date.now() - started}ms`);
59
+ });
60
+ server.on('error', (err) => {
61
+ console.error(err.code === 'EADDRINUSE' ? `Port ${port} is in use. Try lyrcloud dev --port ${port + 1}.` : err.message);
62
+ process.exit(1);
63
+ });
64
+ server.listen(port, '127.0.0.1', () => process.send?.({ ready: true }));
@@ -0,0 +1,103 @@
1
+ // A Lyrcloud project: a folder with lyrcloud.json ({ name, main, vars? }) and your code.
2
+ import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
3
+ import path from 'node:path';
4
+
5
+ export const CONFIG_FILE = 'lyrcloud.json';
6
+
7
+ export class ProjectError extends Error {}
8
+
9
+ const NAME_RE = /^[a-z0-9](?:[a-z0-9-]{0,38}[a-z0-9])?$/;
10
+ export const nameError = (name) => (typeof name === 'string' && NAME_RE.test(name) && name.slice(2, 4) !== '--'
11
+ ? null
12
+ : 'Names use 1–40 lowercase letters, digits and hyphens, and start and end with a letter or digit.');
13
+
14
+ // Walks up from `dir` to the folder holding lyrcloud.json.
15
+ export function findProject(dir = process.cwd()) {
16
+ let current = path.resolve(dir);
17
+ for (;;) {
18
+ if (existsSync(path.join(current, CONFIG_FILE))) return current;
19
+ const parent = path.dirname(current);
20
+ if (parent === current) return null;
21
+ current = parent;
22
+ }
23
+ }
24
+
25
+ export function loadProject(dir = process.cwd()) {
26
+ const root = findProject(dir);
27
+ if (!root) throw new ProjectError(`No ${CONFIG_FILE} here. Create a project with lyrcloud init <name>, or cd into one.`);
28
+ let config;
29
+ try {
30
+ config = JSON.parse(readFileSync(path.join(root, CONFIG_FILE), 'utf8'));
31
+ } catch (err) {
32
+ throw new ProjectError(`${CONFIG_FILE} isn’t valid JSON: ${err.message}`);
33
+ }
34
+ const main = config.main || 'index.js';
35
+ if (!existsSync(path.join(root, main))) throw new ProjectError(`The entry file ${main} (set by "main" in ${CONFIG_FILE}) doesn’t exist.`);
36
+ return { root, config: { ...config, main } };
37
+ }
38
+
39
+ // Folders and files never uploaded.
40
+ const SKIP = new Set(['.git', '.hg', '.svn', '.lyrcloud', '.DS_Store', '.env', 'node_modules']);
41
+
42
+ function walk(root, rel, out, skip) {
43
+ for (const entry of readdirSync(path.join(root, rel), { withFileTypes: true })) {
44
+ const relPath = rel ? `${rel}/${entry.name}` : entry.name;
45
+ if (SKIP.has(entry.name) || skip(relPath)) continue;
46
+ if (entry.isDirectory()) walk(root, relPath, out, skip);
47
+ else if (entry.isFile()) out.push(relPath);
48
+ }
49
+ }
50
+
51
+ // The packages listed in package.json "dependencies", and what they depend on, from node_modules.
52
+ function dependencyFolders(root) {
53
+ const folders = new Set();
54
+ const visit = (from) => {
55
+ let meta;
56
+ try {
57
+ meta = JSON.parse(readFileSync(path.join(from, 'package.json'), 'utf8'));
58
+ } catch {
59
+ return;
60
+ }
61
+ for (const dep of Object.keys({ ...meta.dependencies, ...meta.optionalDependencies })) {
62
+ // Node looks in the nearest node_modules first, then the project's.
63
+ const candidates = [path.join(from, 'node_modules', dep), path.join(root, 'node_modules', dep)];
64
+ const found = candidates.find((candidate) => existsSync(path.join(candidate, 'package.json')));
65
+ if (!found || folders.has(found)) continue;
66
+ folders.add(found);
67
+ visit(found);
68
+ }
69
+ };
70
+ visit(root);
71
+ return [...folders];
72
+ }
73
+
74
+ // Every file to upload as [{ name, data }], with a package.json that marks .js files as ES modules when
75
+ // the project has none.
76
+ export function collectFiles(root, config) {
77
+ const ignore = (config.exclude || []).map((pattern) => String(pattern).replace(/\/$/, ''));
78
+ const skip = (rel) => ignore.some((pattern) => rel === pattern || rel.startsWith(`${pattern}/`));
79
+ const names = [];
80
+ walk(root, '', names, skip);
81
+ for (const folder of dependencyFolders(root)) {
82
+ const rel = path.relative(root, folder).split(path.sep).join('/');
83
+ const inner = [];
84
+ walk(folder, '', inner, () => false);
85
+ // node_modules inside a dependency are reached by their own entries in dependencyFolders.
86
+ names.push(...inner.map((name) => `${rel}/${name}`));
87
+ }
88
+ const files = names.sort().map((name) => ({ name, data: readFileSync(path.join(root, name)) }));
89
+ if (!files.some((file) => file.name === 'package.json')) files.push({ name: 'package.json', data: Buffer.from('{ "type": "module" }\n') });
90
+ return files;
91
+ }
92
+
93
+ export function projectSize(files) {
94
+ return files.reduce((sum, file) => sum + file.data.length, 0);
95
+ }
96
+
97
+ export const isDir = (target) => {
98
+ try {
99
+ return statSync(target).isDirectory();
100
+ } catch {
101
+ return false;
102
+ }
103
+ };
@@ -0,0 +1,107 @@
1
+ // The Lyrcloud Edge Functions runtime. The API copies this file into every function's package as
2
+ // __lyrcloud/runtime.mjs, and Lambda calls its handler with the request the router passes on (an API
3
+ // Gateway HTTP API event, payload format 2.0). It loads the customer's module (LYR_MAIN), which exports
4
+ //
5
+ // export default { fetch(request, env, ctx) { return new Response('hi'); } }
6
+ //
7
+ // (or a bare function), hands it a standard Request and turns the Response it returns back into an
8
+ // API Gateway result. `env` holds the function's variables (LYR_VARS) and nothing from Lambda's own
9
+ // environment, and ctx.waitUntil(promise) work finishes before the invocation ends.
10
+ import path from 'node:path';
11
+ import { pathToFileURL } from 'node:url';
12
+
13
+ let loaded;
14
+ function load() {
15
+ const root = process.env.LAMBDA_TASK_ROOT || process.cwd();
16
+ loaded ??= import(pathToFileURL(path.join(root, process.env.LYR_MAIN || 'index.js')).href);
17
+ return loaded;
18
+ }
19
+
20
+ let vars;
21
+ const varsOf = () => (vars ??= Object.freeze(JSON.parse(process.env.LYR_VARS || '{}')));
22
+
23
+ export function toRequest(event) {
24
+ const headers = new Headers();
25
+ for (const [name, value] of Object.entries(event.headers || {})) {
26
+ if (value !== undefined && value !== null) headers.set(name, String(value));
27
+ }
28
+ if (event.cookies?.length) headers.set('cookie', event.cookies.join('; '));
29
+ const host = headers.get('host') || event.requestContext?.domainName || 'localhost';
30
+ const query = event.rawQueryString ? `?${event.rawQueryString}` : '';
31
+ const method = (event.requestContext?.http?.method || 'GET').toUpperCase();
32
+ const hasBody = event.body !== undefined && event.body !== null && event.body !== '' && method !== 'GET' && method !== 'HEAD';
33
+ const request = new Request(`https://${host}${event.rawPath || '/'}${query}`, {
34
+ method,
35
+ headers,
36
+ body: hasBody ? (event.isBase64Encoded ? Buffer.from(event.body, 'base64') : event.body) : undefined,
37
+ duplex: 'half',
38
+ });
39
+ // Lyrcloud's .lyr addresses are served without a CDN in front, so only the visitor's IP is known.
40
+ Object.defineProperty(request, 'geo', {
41
+ value: Object.freeze({ ip: event.requestContext?.http?.sourceIp || null, city: null, region: null, country: null }),
42
+ enumerable: true,
43
+ });
44
+ return request;
45
+ }
46
+
47
+ export async function toResult(response) {
48
+ const headers = {};
49
+ response.headers.forEach((value, name) => {
50
+ if (name !== 'set-cookie') headers[name] = value;
51
+ });
52
+ const cookies = typeof response.headers.getSetCookie === 'function' ? response.headers.getSetCookie() : [];
53
+ const body = Buffer.from(await response.arrayBuffer());
54
+ return {
55
+ statusCode: response.status,
56
+ headers,
57
+ ...(cookies.length ? { cookies } : {}),
58
+ body: body.toString('base64'),
59
+ isBase64Encoded: true,
60
+ };
61
+ }
62
+
63
+ const plain = (statusCode, text) => ({ statusCode, headers: { 'content-type': 'text/plain; charset=utf-8' }, body: text });
64
+
65
+ export async function run(mod, event) {
66
+ const app = mod.default ?? mod;
67
+ const fetch = typeof app === 'function' ? app : app?.fetch;
68
+ if (typeof fetch !== 'function') {
69
+ console.error('Your entry file must export default { fetch(request, env, ctx) { ... } }.');
70
+ return plain(500, 'This function has no fetch handler. Export default { fetch(request) { ... } } from your entry file.');
71
+ }
72
+ const pending = [];
73
+ const ctx = {
74
+ waitUntil(promise) {
75
+ pending.push(Promise.resolve(promise).catch((err) => console.error('waitUntil task failed:', err)));
76
+ },
77
+ passThroughOnException() {},
78
+ };
79
+ let response;
80
+ try {
81
+ response = await fetch.call(app, toRequest(event), varsOf(), ctx);
82
+ } catch (err) {
83
+ console.error('Uncaught error in fetch:', err);
84
+ response = null;
85
+ }
86
+ let result;
87
+ if (response instanceof Response) {
88
+ result = await toResult(response);
89
+ } else {
90
+ if (response !== null) console.error('fetch must return a Response, but it returned', typeof response);
91
+ result = plain(500, 'This function failed. Its owner can see why with `lyrcloud logs`.');
92
+ }
93
+ await Promise.all(pending);
94
+ return result;
95
+ }
96
+
97
+ export const handler = async (event) => {
98
+ let mod;
99
+ try {
100
+ mod = await load();
101
+ } catch (err) {
102
+ loaded = undefined;
103
+ console.error('Couldn’t load your entry file:', err);
104
+ return plain(500, 'This function couldn’t start. Its owner can see why with `lyrcloud logs`.');
105
+ }
106
+ return run(mod, event);
107
+ };
package/lib/ui.mjs ADDED
@@ -0,0 +1,55 @@
1
+ // Terminal output helpers.
2
+ import { createInterface } from 'node:readline';
3
+
4
+ const color = process.stdout.isTTY && !process.env.NO_COLOR;
5
+ const paint = (code) => (text) => (color ? `\x1b[${code}m${text}\x1b[0m` : String(text));
6
+ export const bold = paint(1);
7
+ export const dim = paint(2);
8
+ export const green = paint(32);
9
+ export const red = paint(31);
10
+ export const yellow = paint(33);
11
+ export const cyan = paint(36);
12
+
13
+ export const ok = (text) => console.log(`${green('✓')} ${text}`);
14
+ export const warn = (text) => console.error(`${yellow('!')} ${text}`);
15
+ export const fail = (text) => console.error(`${red('✗')} ${text}`);
16
+
17
+ export function formatBytes(bytes) {
18
+ if (bytes < 1024) return `${bytes} B`;
19
+ if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
20
+ return `${(bytes / 1024 / 1024).toFixed(2)} MB`;
21
+ }
22
+
23
+ export function ask(question, { hidden = false } = {}) {
24
+ return new Promise((resolve) => {
25
+ const rl = createInterface({ input: process.stdin, output: process.stdout, terminal: true });
26
+ if (hidden) {
27
+ rl._writeToOutput = (text) => {
28
+ if (text.includes(question)) rl.output.write(text);
29
+ else if (text === '\r\n' || text === '\n') rl.output.write(text);
30
+ };
31
+ }
32
+ rl.question(question, (answer) => {
33
+ rl.close();
34
+ if (hidden) process.stdout.write('\n');
35
+ resolve(answer.trim());
36
+ });
37
+ });
38
+ }
39
+
40
+ export function table(rows, headers) {
41
+ const all = [headers, ...rows].map((row) => row.map(String));
42
+ const widths = headers.map((_, i) => Math.max(...all.map((row) => row[i].length)));
43
+ const line = (row) => row.map((cell, i) => cell.padEnd(widths[i])).join(' ').trimEnd();
44
+ console.log(bold(line(all[0])));
45
+ for (const row of all.slice(1)) console.log(line(row));
46
+ }
47
+
48
+ export function relativeTime(iso) {
49
+ if (!iso) return '—';
50
+ const seconds = Math.round((Date.now() - Date.parse(iso)) / 1000);
51
+ if (seconds < 60) return 'just now';
52
+ if (seconds < 3600) return `${Math.floor(seconds / 60)}m ago`;
53
+ if (seconds < 86400) return `${Math.floor(seconds / 3600)}h ago`;
54
+ return `${Math.floor(seconds / 86400)}d ago`;
55
+ }
package/lib/zip.mjs ADDED
@@ -0,0 +1,141 @@
1
+ // A small zip writer and reader with no dependencies, shared by the Lyrcloud CLI (cli/lib/zip.mjs is an
2
+ // identical copy; a test keeps them the same) and the Edge Functions API.
3
+ //
4
+ // createZip([{ name, data }]) -> Buffer a new archive (deflated entries)
5
+ // listZip(buffer) -> [{ name, size, compressedSize }]
6
+ // addZipEntry(buffer, name, data) -> Buffer the archive with one more file, the rest copied untouched
7
+ //
8
+ // Only plain archives: no zip64, encryption or multi-disk sets (Lambda packages here are a few MB).
9
+ import { deflateRawSync } from 'node:zlib';
10
+
11
+ const CRC_TABLE = new Int32Array(256).map((_, n) => {
12
+ let c = n;
13
+ for (let k = 0; k < 8; k += 1) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
14
+ return c;
15
+ });
16
+
17
+ export function crc32(buf) {
18
+ let crc = -1;
19
+ for (let i = 0; i < buf.length; i += 1) crc = CRC_TABLE[(crc ^ buf[i]) & 0xff] ^ (crc >>> 8);
20
+ return (crc ^ -1) >>> 0;
21
+ }
22
+
23
+ // 1 January 2000, so archives built from the same files are byte-for-byte the same.
24
+ const DOS_TIME = 0;
25
+ const DOS_DATE = ((2000 - 1980) << 9) | (1 << 5) | 1;
26
+ const UTF8_FLAG = 0x0800;
27
+ const FILE_MODE = 0o100644;
28
+
29
+ function entry(name, data) {
30
+ const nameBytes = Buffer.from(name, 'utf8');
31
+ const raw = Buffer.isBuffer(data) ? data : Buffer.from(data);
32
+ const deflated = deflateRawSync(raw, { level: 9 });
33
+ const stored = deflated.length >= raw.length;
34
+ const body = stored ? raw : deflated;
35
+ const crc = crc32(raw);
36
+ const local = Buffer.alloc(30);
37
+ local.writeUInt32LE(0x04034b50, 0);
38
+ local.writeUInt16LE(20, 4);
39
+ local.writeUInt16LE(UTF8_FLAG, 6);
40
+ local.writeUInt16LE(stored ? 0 : 8, 8);
41
+ local.writeUInt16LE(DOS_TIME, 10);
42
+ local.writeUInt16LE(DOS_DATE, 12);
43
+ local.writeUInt32LE(crc, 14);
44
+ local.writeUInt32LE(body.length, 18);
45
+ local.writeUInt32LE(raw.length, 22);
46
+ local.writeUInt16LE(nameBytes.length, 26);
47
+ local.writeUInt16LE(0, 28);
48
+ const central = (offset) => {
49
+ const header = Buffer.alloc(46);
50
+ header.writeUInt32LE(0x02014b50, 0);
51
+ header.writeUInt16LE((3 << 8) | 20, 4); // made by: Unix, so the file mode below counts
52
+ header.writeUInt16LE(20, 6);
53
+ header.writeUInt16LE(UTF8_FLAG, 8);
54
+ header.writeUInt16LE(stored ? 0 : 8, 10);
55
+ header.writeUInt16LE(DOS_TIME, 12);
56
+ header.writeUInt16LE(DOS_DATE, 14);
57
+ header.writeUInt32LE(crc, 16);
58
+ header.writeUInt32LE(body.length, 20);
59
+ header.writeUInt32LE(raw.length, 24);
60
+ header.writeUInt16LE(nameBytes.length, 28);
61
+ header.writeUInt32LE(((FILE_MODE << 16) >>> 0), 38);
62
+ header.writeUInt32LE(offset, 42);
63
+ return Buffer.concat([header, nameBytes]);
64
+ };
65
+ return { local: Buffer.concat([local, nameBytes, body]), central };
66
+ }
67
+
68
+ function endRecord(count, centralSize, centralOffset) {
69
+ const end = Buffer.alloc(22);
70
+ end.writeUInt32LE(0x06054b50, 0);
71
+ end.writeUInt16LE(count, 8);
72
+ end.writeUInt16LE(count, 10);
73
+ end.writeUInt32LE(centralSize, 12);
74
+ end.writeUInt32LE(centralOffset, 16);
75
+ return end;
76
+ }
77
+
78
+ export function createZip(files) {
79
+ const locals = [];
80
+ const centrals = [];
81
+ let offset = 0;
82
+ for (const file of files) {
83
+ const built = entry(file.name, file.data);
84
+ centrals.push(built.central(offset));
85
+ locals.push(built.local);
86
+ offset += built.local.length;
87
+ }
88
+ const central = Buffer.concat(centrals);
89
+ return Buffer.concat([...locals, central, endRecord(files.length, central.length, offset)]);
90
+ }
91
+
92
+ export class ZipError extends Error {}
93
+
94
+ function findEnd(buf) {
95
+ for (let i = buf.length - 22; i >= Math.max(0, buf.length - 22 - 0xffff); i -= 1) {
96
+ if (buf.readUInt32LE(i) === 0x06054b50) {
97
+ return { at: i, count: buf.readUInt16LE(i + 10), size: buf.readUInt32LE(i + 12), offset: buf.readUInt32LE(i + 16) };
98
+ }
99
+ }
100
+ throw new ZipError('This isn’t a zip archive.');
101
+ }
102
+
103
+ function centralEntries(buf) {
104
+ if (!Buffer.isBuffer(buf) || buf.length < 22) throw new ZipError('This isn’t a zip archive.');
105
+ const end = findEnd(buf);
106
+ if (end.count === 0xffff || end.offset === 0xffffffff) throw new ZipError('Zip64 archives aren’t supported.');
107
+ if (end.offset + end.size > end.at) throw new ZipError('The zip archive is damaged.');
108
+ const entries = [];
109
+ let p = end.offset;
110
+ for (let i = 0; i < end.count; i += 1) {
111
+ if (p + 46 > end.at || buf.readUInt32LE(p) !== 0x02014b50) throw new ZipError('The zip archive is damaged.');
112
+ const nameLength = buf.readUInt16LE(p + 28);
113
+ const extraLength = buf.readUInt16LE(p + 30);
114
+ const commentLength = buf.readUInt16LE(p + 32);
115
+ entries.push({
116
+ name: buf.subarray(p + 46, p + 46 + nameLength).toString('utf8'),
117
+ compressedSize: buf.readUInt32LE(p + 20),
118
+ size: buf.readUInt32LE(p + 24),
119
+ flags: buf.readUInt16LE(p + 8),
120
+ });
121
+ p += 46 + nameLength + extraLength + commentLength;
122
+ }
123
+ return { end, entries };
124
+ }
125
+
126
+ export function listZip(buf) {
127
+ const { entries } = centralEntries(buf);
128
+ for (const item of entries) if (item.flags & 1) throw new ZipError('Encrypted zip archives aren’t supported.');
129
+ return entries.map(({ name, size, compressedSize }) => ({ name, size, compressedSize }));
130
+ }
131
+
132
+ // Appends one file: the existing file records stay where they are, the new one goes after them, and
133
+ // the central directory is written again with the new entry at the end.
134
+ export function addZipEntry(buf, name, data) {
135
+ const { end } = centralEntries(buf);
136
+ const built = entry(name, data);
137
+ const oldCentral = buf.subarray(end.offset, end.offset + end.size);
138
+ const newCentral = Buffer.concat([oldCentral, built.central(end.offset)]);
139
+ const centralOffset = end.offset + built.local.length;
140
+ return Buffer.concat([buf.subarray(0, end.offset), built.local, newCentral, endRecord(end.count + 1, newCentral.length, centralOffset)]);
141
+ }
package/package.json CHANGED
@@ -1,6 +1,27 @@
1
1
  {
2
2
  "name": "lyrcloud",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "The Lyrcloud CLI: build and deploy edge functions to <name>.dev.lyr",
5
+ "type": "module",
6
+ "bin": {
7
+ "lyrcloud": "bin/lyrcloud.mjs"
8
+ },
9
+ "files": [
10
+ "bin",
11
+ "lib",
12
+ "README.md",
13
+ "LICENSE"
14
+ ],
15
+ "engines": {
16
+ "node": ">=20"
17
+ },
18
+ "keywords": [
19
+ "lyrcloud",
20
+ "edge",
21
+ "functions",
22
+ "serverless",
23
+ "cli"
24
+ ],
25
+ "homepage": "https://www.lyrcloud.com/developers/",
26
+ "license": "MIT"
27
+ }