@memrosetta/cli 0.4.3 → 0.4.4

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/dist/index.js CHANGED
@@ -56,12 +56,16 @@ Global Options:
56
56
  --version, -v Show version
57
57
 
58
58
  Sync Subcommands:
59
- memrosetta sync enable --server <url> # Enable sync, hidden API key prompt
60
- memrosetta sync enable --server <url> --key-stdin # Read API key from stdin
61
- memrosetta sync disable # Disable sync (keeps server/key)
59
+ memrosetta sync enable --server <url> [key-source]
60
+ Key sources (mutually exclusive, exactly one):
61
+ --key <value> Direct (visible in shell history)
62
+ --key-stdin Read from stdin (echo key | memrosetta ...)
63
+ --key-file <path> Read from file
64
+ MEMROSETTA_SYNC_API_KEY Environment variable (fallback)
65
+ (no flag) POSIX TTY only: hidden prompt
66
+ memrosetta sync disable # Disable (keeps server/key)
62
67
  memrosetta sync status # Show sync state + pending ops
63
- memrosetta sync now # Push + pull now
64
- memrosetta sync now --push-only # Push only
68
+ memrosetta sync now [--push-only | --pull-only]
65
69
  memrosetta sync device-id # Print current device id
66
70
 
67
71
  Examples:
@@ -185,7 +189,7 @@ async function main() {
185
189
  break;
186
190
  }
187
191
  case "sync": {
188
- const mod = await import("./sync-7TONPJBY.js");
192
+ const mod = await import("./sync-GMGC66NK.js");
189
193
  await mod.run(commandOptions);
190
194
  break;
191
195
  }
@@ -0,0 +1,386 @@
1
+ import {
2
+ hasFlag,
3
+ optionalOption,
4
+ requireOption
5
+ } from "./chunk-NU5ZJJXP.js";
6
+ import {
7
+ output,
8
+ outputError
9
+ } from "./chunk-ET6TNQOJ.js";
10
+ import {
11
+ getConfig,
12
+ getDefaultDbPath,
13
+ writeConfig
14
+ } from "./chunk-SEPYQK3J.js";
15
+
16
+ // src/commands/sync.ts
17
+ import { randomUUID } from "crypto";
18
+ import { readFileSync } from "fs";
19
+ import { userInfo, platform } from "os";
20
+ import { createInterface } from "readline";
21
+ var ENV_API_KEY = "MEMROSETTA_SYNC_API_KEY";
22
+ var KEY_SOURCE_HINT = [
23
+ "API key required. Use exactly one of:",
24
+ " --key <value> (direct, visible in history)",
25
+ " --key-stdin (pipe from stdin)",
26
+ " --key-file <path> (read from file)",
27
+ ` ${ENV_API_KEY}=<value> (environment variable)`,
28
+ "",
29
+ "On POSIX TTYs an interactive hidden prompt is also available.",
30
+ "See: memrosetta sync enable --help"
31
+ ].join("\n");
32
+ function parseSubcommand(args) {
33
+ const first = args[0];
34
+ if (!first || first.startsWith("--")) return null;
35
+ if (first === "enable" || first === "disable" || first === "status" || first === "now" || first === "device-id") {
36
+ return first;
37
+ }
38
+ return null;
39
+ }
40
+ var CONTROL_CHAR_REGEX = /[\x00-\x1F\x7F]/;
41
+ function validateApiKey(key, sourceLabel) {
42
+ const trimmed = key.trim();
43
+ if (trimmed.length === 0) {
44
+ throw new Error(`API key from ${sourceLabel} is empty.`);
45
+ }
46
+ if (CONTROL_CHAR_REGEX.test(trimmed)) {
47
+ throw new Error(
48
+ `API key from ${sourceLabel} contains control characters. Try --key-file or MEMROSETTA_SYNC_API_KEY instead.`
49
+ );
50
+ }
51
+ return trimmed;
52
+ }
53
+ function readKeyFile(path) {
54
+ try {
55
+ return readFileSync(path, "utf-8");
56
+ } catch (err) {
57
+ const msg = err instanceof Error ? err.message : String(err);
58
+ throw new Error(`Could not read --key-file '${path}': ${msg}`);
59
+ }
60
+ }
61
+ async function resolveApiKey(args) {
62
+ const directKey = optionalOption(args, "--key");
63
+ const keyFile = optionalOption(args, "--key-file");
64
+ const useStdin = hasFlag(args, "--key-stdin");
65
+ const explicitCount = [directKey !== void 0, keyFile !== void 0, useStdin].filter(Boolean).length;
66
+ if (explicitCount > 1) {
67
+ throw new Error(
68
+ "Specify only one of --key, --key-stdin, --key-file."
69
+ );
70
+ }
71
+ if (directKey !== void 0) {
72
+ return validateApiKey(directKey, "--key");
73
+ }
74
+ if (useStdin) {
75
+ const raw = await readStdinKey();
76
+ if (!raw) {
77
+ throw new Error(
78
+ "--key-stdin produced no input. On Windows PowerShell, prefer --key-file or MEMROSETTA_SYNC_API_KEY."
79
+ );
80
+ }
81
+ return validateApiKey(raw, "--key-stdin");
82
+ }
83
+ if (keyFile !== void 0) {
84
+ return validateApiKey(readKeyFile(keyFile), `--key-file ${keyFile}`);
85
+ }
86
+ const envKey = process.env[ENV_API_KEY];
87
+ if (envKey !== void 0 && envKey.length > 0) {
88
+ return validateApiKey(envKey, ENV_API_KEY);
89
+ }
90
+ if (platform() !== "win32" && process.stdin.isTTY) {
91
+ const raw = await readHiddenInput("API key: ");
92
+ return validateApiKey(raw, "hidden prompt");
93
+ }
94
+ throw new Error(KEY_SOURCE_HINT);
95
+ }
96
+ async function readHiddenInput(prompt) {
97
+ const stdin = process.stdin;
98
+ const stdout = process.stdout;
99
+ if (!stdin.isTTY) {
100
+ throw new Error("Interactive input requires a TTY. Use --key-stdin to pipe the key instead.");
101
+ }
102
+ stdout.write(prompt);
103
+ const originalWrite = stdout.write.bind(stdout);
104
+ let muted = true;
105
+ stdout.write = (chunk, ...rest) => {
106
+ if (!muted) {
107
+ return originalWrite(chunk, ...rest);
108
+ }
109
+ const str = typeof chunk === "string" ? chunk : chunk?.toString?.("utf-8") ?? "";
110
+ if (str === "\n" || str === "\r\n" || str === "\r") {
111
+ return originalWrite(chunk, ...rest);
112
+ }
113
+ return true;
114
+ };
115
+ const rl = createInterface({
116
+ input: stdin,
117
+ output: stdout,
118
+ terminal: true
119
+ });
120
+ try {
121
+ const answer = await new Promise((resolve, reject) => {
122
+ rl.once("close", () => {
123
+ reject(new Error("Aborted"));
124
+ });
125
+ rl.question("", (value) => {
126
+ resolve(value);
127
+ });
128
+ });
129
+ return answer;
130
+ } finally {
131
+ muted = false;
132
+ stdout.write = originalWrite;
133
+ rl.close();
134
+ }
135
+ }
136
+ async function readStdinKey() {
137
+ const chunks = [];
138
+ for await (const chunk of process.stdin) {
139
+ chunks.push(chunk);
140
+ }
141
+ return Buffer.concat(chunks).toString("utf-8").trim();
142
+ }
143
+ async function testConnection(serverUrl, apiKey) {
144
+ const url = `${serverUrl.replace(/\/$/, "")}/sync/health`;
145
+ try {
146
+ const res = await fetch(url, {
147
+ headers: { Authorization: `Bearer ${apiKey}` }
148
+ });
149
+ if (!res.ok) {
150
+ throw new Error(`HTTP ${res.status} ${res.statusText}`);
151
+ }
152
+ } catch (err) {
153
+ const msg = err instanceof Error ? err.message : String(err);
154
+ throw new Error(`Sync server health check failed: ${msg}`);
155
+ }
156
+ }
157
+ async function withSyncClient(dbPath, config, fn) {
158
+ const Database = (await import("better-sqlite3")).default;
159
+ const { SyncClient, ensureSyncSchema } = await import("@memrosetta/sync-client");
160
+ if (!config.syncServerUrl || !config.syncApiKey || !config.syncDeviceId) {
161
+ throw new Error("Sync is not configured. Run: memrosetta sync enable --server <url>");
162
+ }
163
+ if (CONTROL_CHAR_REGEX.test(config.syncApiKey)) {
164
+ throw new Error(
165
+ `Stored API key is invalid (contains control characters from a previous terminal input). Re-run with one of:
166
+ memrosetta sync enable --server ${config.syncServerUrl} --key <api-key>
167
+ memrosetta sync enable --server ${config.syncServerUrl} --key-file path/to/key
168
+ $env:${ENV_API_KEY}='<api-key>'; memrosetta sync enable --server ${config.syncServerUrl}`
169
+ );
170
+ }
171
+ const db = new Database(dbPath);
172
+ try {
173
+ ensureSyncSchema(db);
174
+ const client = new SyncClient(db, {
175
+ serverUrl: config.syncServerUrl,
176
+ apiKey: config.syncApiKey,
177
+ deviceId: config.syncDeviceId,
178
+ userId: userInfo().username
179
+ });
180
+ return await fn(client, db);
181
+ } finally {
182
+ db.close();
183
+ }
184
+ }
185
+ async function runEnable(options) {
186
+ const { args, format } = options;
187
+ let serverUrl;
188
+ try {
189
+ serverUrl = requireOption(args, "--server", "server URL");
190
+ } catch (err) {
191
+ outputError(err instanceof Error ? err.message : String(err), format);
192
+ process.exitCode = 1;
193
+ return;
194
+ }
195
+ let apiKey;
196
+ try {
197
+ apiKey = await resolveApiKey(args);
198
+ } catch (err) {
199
+ outputError(err instanceof Error ? err.message : String(err), format);
200
+ process.exitCode = 1;
201
+ return;
202
+ }
203
+ const skipTest = hasFlag(args, "--no-test");
204
+ if (!skipTest) {
205
+ try {
206
+ await testConnection(serverUrl, apiKey);
207
+ } catch (err) {
208
+ outputError(
209
+ `${err instanceof Error ? err.message : String(err)}
210
+ Use --no-test to skip the health check.`,
211
+ format
212
+ );
213
+ process.exitCode = 1;
214
+ return;
215
+ }
216
+ }
217
+ const existing = getConfig();
218
+ const deviceId = existing.syncDeviceId ?? `device-${randomUUID().slice(0, 8)}`;
219
+ writeConfig({
220
+ ...existing,
221
+ syncEnabled: true,
222
+ syncServerUrl: serverUrl,
223
+ syncApiKey: apiKey,
224
+ syncDeviceId: deviceId
225
+ });
226
+ if (format === "text") {
227
+ process.stdout.write("Sync enabled.\n");
228
+ process.stdout.write(` Server: ${serverUrl}
229
+ `);
230
+ process.stdout.write(` DeviceId: ${deviceId}
231
+ `);
232
+ if (skipTest) {
233
+ process.stdout.write(" (health check skipped)\n");
234
+ }
235
+ return;
236
+ }
237
+ output({ enabled: true, serverUrl, deviceId, healthCheckSkipped: skipTest }, format);
238
+ }
239
+ function runDisable(options) {
240
+ const { format } = options;
241
+ const existing = getConfig();
242
+ writeConfig({
243
+ ...existing,
244
+ syncEnabled: false
245
+ });
246
+ if (format === "text") {
247
+ process.stdout.write("Sync disabled. (server URL and API key preserved for re-enable)\n");
248
+ return;
249
+ }
250
+ output({ enabled: false }, format);
251
+ }
252
+ async function runStatus(options) {
253
+ const { format, db } = options;
254
+ const config = getConfig();
255
+ const dbPath = db ?? config.dbPath ?? getDefaultDbPath();
256
+ if (!config.syncEnabled) {
257
+ if (format === "text") {
258
+ process.stdout.write("Sync: disabled\n");
259
+ if (config.syncServerUrl) {
260
+ process.stdout.write(` Server: ${config.syncServerUrl}
261
+ `);
262
+ }
263
+ if (config.syncDeviceId) {
264
+ process.stdout.write(` DeviceId: ${config.syncDeviceId}
265
+ `);
266
+ }
267
+ return;
268
+ }
269
+ output(
270
+ {
271
+ enabled: false,
272
+ serverUrl: config.syncServerUrl ?? null,
273
+ deviceId: config.syncDeviceId ?? null
274
+ },
275
+ format
276
+ );
277
+ return;
278
+ }
279
+ try {
280
+ const status = await withSyncClient(dbPath, config, async (client) => client.getStatus());
281
+ if (format === "text") {
282
+ process.stdout.write("Sync: enabled\n");
283
+ process.stdout.write(` Server: ${status.serverUrl}
284
+ `);
285
+ process.stdout.write(` DeviceId: ${status.deviceId}
286
+ `);
287
+ process.stdout.write(` Pending ops: ${status.pendingOps}
288
+ `);
289
+ process.stdout.write(` Current cursor: ${status.cursor}
290
+ `);
291
+ process.stdout.write(
292
+ ` Last push: ${status.lastPush.successAt ?? "never"}` + (status.lastPush.attemptAt && status.lastPush.attemptAt !== status.lastPush.successAt ? ` (last attempt: ${status.lastPush.attemptAt})` : "") + "\n"
293
+ );
294
+ process.stdout.write(
295
+ ` Last pull: ${status.lastPull.successAt ?? "never"}` + (status.lastPull.attemptAt && status.lastPull.attemptAt !== status.lastPull.successAt ? ` (last attempt: ${status.lastPull.attemptAt})` : "") + "\n"
296
+ );
297
+ return;
298
+ }
299
+ output(status, format);
300
+ } catch (err) {
301
+ outputError(err instanceof Error ? err.message : String(err), format);
302
+ process.exitCode = 1;
303
+ }
304
+ }
305
+ async function runNow(options) {
306
+ const { args, format, db } = options;
307
+ const config = getConfig();
308
+ const dbPath = db ?? config.dbPath ?? getDefaultDbPath();
309
+ if (!config.syncEnabled) {
310
+ outputError("Sync is disabled. Run: memrosetta sync enable --server <url>", format);
311
+ process.exitCode = 1;
312
+ return;
313
+ }
314
+ const pushOnly = hasFlag(args, "--push-only");
315
+ const pullOnly = hasFlag(args, "--pull-only");
316
+ try {
317
+ const result = await withSyncClient(dbPath, config, async (client) => {
318
+ let pushed = 0;
319
+ let pulled = 0;
320
+ if (!pullOnly) {
321
+ const pushResult = await client.push();
322
+ pushed = pushResult.pushed;
323
+ }
324
+ if (!pushOnly) {
325
+ pulled = await client.pull();
326
+ }
327
+ return { pushed, pulled };
328
+ });
329
+ if (format === "text") {
330
+ process.stdout.write(`Sync complete. pushed=${result.pushed} pulled=${result.pulled}
331
+ `);
332
+ return;
333
+ }
334
+ output(result, format);
335
+ } catch (err) {
336
+ outputError(err instanceof Error ? err.message : String(err), format);
337
+ process.exitCode = 1;
338
+ }
339
+ }
340
+ function runDeviceId(options) {
341
+ const { format } = options;
342
+ const config = getConfig();
343
+ if (!config.syncDeviceId) {
344
+ outputError("No deviceId set. Run: memrosetta sync enable --server <url>", format);
345
+ process.exitCode = 1;
346
+ return;
347
+ }
348
+ if (format === "text") {
349
+ process.stdout.write(`${config.syncDeviceId}
350
+ `);
351
+ return;
352
+ }
353
+ output({ deviceId: config.syncDeviceId }, format);
354
+ }
355
+ async function run(options) {
356
+ const sub = parseSubcommand(options.args);
357
+ if (!sub) {
358
+ outputError(
359
+ "Usage: memrosetta sync <enable|disable|status|now|device-id>\n\n enable --server <url> [--key <key> | --key-stdin] [--no-test]\n disable\n status\n now [--push-only | --pull-only]\n device-id\n",
360
+ options.format
361
+ );
362
+ process.exitCode = 1;
363
+ return;
364
+ }
365
+ const rest = { ...options, args: options.args.slice(1) };
366
+ switch (sub) {
367
+ case "enable":
368
+ await runEnable(rest);
369
+ return;
370
+ case "disable":
371
+ runDisable(rest);
372
+ return;
373
+ case "status":
374
+ await runStatus(rest);
375
+ return;
376
+ case "now":
377
+ await runNow(rest);
378
+ return;
379
+ case "device-id":
380
+ runDeviceId(rest);
381
+ return;
382
+ }
383
+ }
384
+ export {
385
+ run
386
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@memrosetta/cli",
3
- "version": "0.4.3",
3
+ "version": "0.4.4",
4
4
  "type": "module",
5
5
  "main": "./dist/index.js",
6
6
  "bin": {