promptlike 0.2.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.
@@ -0,0 +1,105 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.loginCommand = loginCommand;
37
+ const readline = __importStar(require("readline"));
38
+ const stream_1 = require("stream");
39
+ const api_client_1 = require("../lib/api-client");
40
+ const format_1 = require("../lib/format");
41
+ /**
42
+ * `ple login` — sign in with email + password via the web API.
43
+ *
44
+ * The password is read without echoing to the screen (a custom Writable
45
+ * wrapping stdout suppresses the keystroke output). On success the session
46
+ * tokens are written to ~/.config/promptlike/config.json with 0600 perms.
47
+ */
48
+ async function loginCommand() {
49
+ const email = await prompt('Email: ');
50
+ if (!email) {
51
+ console.error(format_1.c.error('Email is required.'));
52
+ process.exit(1);
53
+ }
54
+ const password = await promptHidden('Password: ');
55
+ if (!password) {
56
+ console.error(format_1.c.error('Password is required.'));
57
+ process.exit(1);
58
+ }
59
+ // Throws with the server's safe message on failure (wrong password, or an
60
+ // OAuth-only account that has no password set) — the global handler prints it.
61
+ const config = await (0, api_client_1.login)(email, password);
62
+ console.log(format_1.c.success(`✓ Logged in as ${config.email}`));
63
+ console.log(format_1.c.muted("Next: run 'ple list' to see your prompts."));
64
+ }
65
+ /** Read a single line with standard readline. */
66
+ function prompt(question) {
67
+ return new Promise((resolve) => {
68
+ const rl = readline.createInterface({
69
+ input: process.stdin,
70
+ output: process.stdout,
71
+ });
72
+ rl.question(question, (answer) => {
73
+ rl.close();
74
+ resolve(answer.trim());
75
+ });
76
+ });
77
+ }
78
+ /**
79
+ * Read a password without echoing it: a "muted" stdout that drops the typed
80
+ * characters. readline still reads the keystrokes, it just doesn't print them.
81
+ */
82
+ function promptHidden(question) {
83
+ return new Promise((resolve) => {
84
+ let muted = false;
85
+ const mutedStdout = new stream_1.Writable({
86
+ write(chunk, _encoding, callback) {
87
+ if (!muted)
88
+ process.stdout.write(chunk);
89
+ callback();
90
+ },
91
+ });
92
+ const rl = readline.createInterface({
93
+ input: process.stdin,
94
+ output: mutedStdout,
95
+ terminal: true,
96
+ });
97
+ rl.question(question, (answer) => {
98
+ rl.close();
99
+ process.stdout.write('\n');
100
+ resolve(answer);
101
+ });
102
+ // Mute once the prompt itself has been written.
103
+ muted = true;
104
+ });
105
+ }
@@ -0,0 +1,18 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.logoutCommand = logoutCommand;
4
+ const config_1 = require("../lib/config");
5
+ const format_1 = require("../lib/format");
6
+ /**
7
+ * `ple logout` — delete the local config file. No server call is made (the
8
+ * session expires naturally); this only clears local state.
9
+ */
10
+ async function logoutCommand() {
11
+ const existing = (0, config_1.readConfig)();
12
+ if (!existing) {
13
+ console.log(format_1.c.muted('Not logged in.'));
14
+ return;
15
+ }
16
+ (0, config_1.clearConfig)();
17
+ console.log(format_1.c.success(`✓ Logged out (${existing.email}).`));
18
+ }
@@ -0,0 +1,83 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.parseRounds = parseRounds;
4
+ exports.loopCommand = loopCommand;
5
+ const api_client_1 = require("../lib/api-client");
6
+ const promptResolver_1 = require("../lib/promptResolver");
7
+ const format_1 = require("../lib/format");
8
+ const loopApi_1 = require("../lib/loopApi");
9
+ const loopUx_1 = require("../lib/loopUx");
10
+ const improve_1 = require("./improve");
11
+ /** Parse and validate `--rounds` (default 1, must be a positive integer). */
12
+ function parseRounds(raw) {
13
+ if (raw === undefined || raw.trim() === '')
14
+ return 1;
15
+ const n = Number.parseInt(raw.trim(), 10);
16
+ if (Number.isNaN(n) || n < 1 || String(n) !== raw.trim()) {
17
+ throw new Error(`Invalid --rounds '${raw}' — expected a positive integer.`);
18
+ }
19
+ return n;
20
+ }
21
+ /**
22
+ * `ple loop <name> [--exec <cmd>] [--rounds <n>] [--focus <hint>]` —
23
+ * multi-round Loop Engineering: connect the loop to your own agent.
24
+ *
25
+ * Each round: generate variants from the prompt's current version; when
26
+ * `--exec` is given, run every variant through the user's command (prompt
27
+ * delivered as `PLE_PROMPT` env + stdin, `{}` placeholder substituted) and
28
+ * show the first ~20 lines of output under the variant card. The user picks
29
+ * a winner (0 = cancel, Ctrl-C safe), the pick is saved as a new version and
30
+ * becomes the base for the next round.
31
+ */
32
+ async function loopCommand(name, options = {}) {
33
+ const rounds = parseRounds(options.rounds);
34
+ await (0, api_client_1.ensureAuthed)();
35
+ const prompt = await (0, promptResolver_1.resolvePromptByName)(name);
36
+ if (!prompt) {
37
+ process.exitCode = 1;
38
+ return;
39
+ }
40
+ const version = (0, promptResolver_1.fetchPromptContent)(prompt);
41
+ let baseline = version ? (0, format_1.joinPromptParts)(version) : '';
42
+ for (let round = 1; round <= rounds; round++) {
43
+ console.log();
44
+ console.log(format_1.c.title(`═══ Round ${round}/${rounds} — '${prompt.title}' ═══`));
45
+ console.log(format_1.c.muted('Generating variants…'));
46
+ const { variants, tokensUsed } = await (0, loopApi_1.requestVariants)(prompt.id, {
47
+ focus: options.focus,
48
+ });
49
+ if (variants.length === 0) {
50
+ console.error(format_1.c.error('The API returned no variants. Try again in a moment.'));
51
+ process.exitCode = 1;
52
+ return;
53
+ }
54
+ for (const [i, variant] of variants.entries()) {
55
+ (0, loopUx_1.renderVariant)(variant, i + 1, baseline);
56
+ if (options.exec) {
57
+ const result = await (0, loopUx_1.runExec)(options.exec, (0, loopUx_1.variantText)(variant));
58
+ (0, loopUx_1.printExecResult)(result);
59
+ }
60
+ }
61
+ console.log();
62
+ console.log(format_1.c.muted(`${tokensUsed} AI tokens used this round.`));
63
+ const pick = await (0, loopUx_1.selectVariant)(variants.length);
64
+ if (pick === 0) {
65
+ console.log(format_1.c.muted('Cancelled — nothing saved this round.'));
66
+ return;
67
+ }
68
+ const winner = variants[pick - 1];
69
+ const result = await (0, loopApi_1.saveWinner)(prompt.id, winner, (0, improve_1.loopChangelog)(winner));
70
+ const versionLabel = result.versionNumber !== undefined ? `v${result.versionNumber}` : 'a new version';
71
+ console.log(format_1.c.success(`✓ Saved '${prompt.title}' as ${versionLabel} (${winner.strategy}).`));
72
+ // The saved winner is now the prompt's current version — the next
73
+ // round generates from it. Track it locally for size comparisons.
74
+ baseline = (0, loopUx_1.variantText)(winner);
75
+ if (round < rounds) {
76
+ const goOn = await (0, loopUx_1.confirmContinue)();
77
+ if (!goOn) {
78
+ console.log(format_1.c.muted(`Stopped after round ${round}.`));
79
+ return;
80
+ }
81
+ }
82
+ }
83
+ }
@@ -0,0 +1,35 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.searchCommand = searchCommand;
4
+ const api_client_1 = require("../lib/api-client");
5
+ const format_1 = require("../lib/format");
6
+ /**
7
+ * `ple search <keyword>` — search over title + description.
8
+ *
9
+ * Delegates to the web API's `/api/prompts?search=` (which escapes the input
10
+ * and searches title/description). Searching prompt version bodies would need
11
+ * a separate full-text index; matching titles/descriptions is fast and enough.
12
+ */
13
+ async function searchCommand(keyword) {
14
+ const trimmed = keyword.trim();
15
+ if (!trimmed) {
16
+ console.error(format_1.c.error('Search keyword is empty.'));
17
+ process.exitCode = 1;
18
+ return;
19
+ }
20
+ await (0, api_client_1.ensureAuthed)();
21
+ const rows = await (0, api_client_1.listPrompts)({ search: trimmed, limit: 30 });
22
+ if (rows.length === 0) {
23
+ console.log(format_1.c.muted(`No prompts matched '${trimmed}'.`));
24
+ return;
25
+ }
26
+ console.log(format_1.c.label(`${rows.length} result${rows.length === 1 ? '' : 's'}:`));
27
+ console.log();
28
+ for (const r of rows) {
29
+ console.log(`${format_1.c.title(r.title)} ${format_1.c.muted(`· ${(0, format_1.shortId)(r.id)} · ${(0, format_1.timeAgo)(r.updated_at)}`)}`);
30
+ if (r.description) {
31
+ console.log(` ${format_1.c.muted((0, format_1.truncate)(r.description, 80))}`);
32
+ }
33
+ }
34
+ console.log();
35
+ }
@@ -0,0 +1,62 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.showCommand = showCommand;
4
+ const api_client_1 = require("../lib/api-client");
5
+ const promptResolver_1 = require("../lib/promptResolver");
6
+ const format_1 = require("../lib/format");
7
+ /**
8
+ * `ple show <name>` — render a prompt's content to the terminal.
9
+ *
10
+ * Unlike `copy`, this doesn't touch the clipboard: it renders the three
11
+ * sections (role / description / context) under readable headers.
12
+ */
13
+ async function showCommand(name) {
14
+ await (0, api_client_1.ensureAuthed)();
15
+ const prompt = await (0, promptResolver_1.resolvePromptByName)(name);
16
+ if (!prompt) {
17
+ process.exitCode = 1;
18
+ return;
19
+ }
20
+ const version = (0, promptResolver_1.fetchPromptContent)(prompt);
21
+ if (!version) {
22
+ console.error(format_1.c.error(`'${prompt.title}' has no usable version.`));
23
+ process.exitCode = 1;
24
+ return;
25
+ }
26
+ // Header
27
+ console.log();
28
+ console.log(format_1.c.title(prompt.title));
29
+ console.log(format_1.c.muted(`${(0, format_1.shortId)(prompt.id)} · updated ${(0, format_1.timeAgo)(prompt.updated_at)}`));
30
+ if (prompt.description) {
31
+ console.log();
32
+ console.log(format_1.c.label(prompt.description));
33
+ }
34
+ // Legacy single-field content — not split into three parts.
35
+ if (version.content &&
36
+ version.content.trim() &&
37
+ !version.role_text &&
38
+ !version.description_text &&
39
+ !version.context_text) {
40
+ console.log();
41
+ console.log(version.content);
42
+ console.log();
43
+ return;
44
+ }
45
+ // 3-part view
46
+ if (version.role_text?.trim()) {
47
+ console.log();
48
+ console.log(format_1.c.accent('── ROLE ──'));
49
+ console.log(version.role_text.trim());
50
+ }
51
+ if (version.description_text?.trim()) {
52
+ console.log();
53
+ console.log(format_1.c.accent('── DESCRIPTION ──'));
54
+ console.log(version.description_text.trim());
55
+ }
56
+ if (version.context_text?.trim()) {
57
+ console.log();
58
+ console.log(format_1.c.accent('── CONTEXT ──'));
59
+ console.log(version.context_text.trim());
60
+ }
61
+ console.log();
62
+ }
package/dist/index.js ADDED
@@ -0,0 +1,85 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ /**
4
+ * promptlike CLI entry point.
5
+ *
6
+ * Registers the commands and runs `commander`. Each command's real logic lives
7
+ * under `src/commands/` — this file only does argument parsing + the global
8
+ * error wrapper.
9
+ */
10
+ Object.defineProperty(exports, "__esModule", { value: true });
11
+ const commander_1 = require("commander");
12
+ const constants_1 = require("./lib/constants");
13
+ const format_1 = require("./lib/format");
14
+ const login_1 = require("./commands/login");
15
+ const logout_1 = require("./commands/logout");
16
+ const list_1 = require("./commands/list");
17
+ const copy_1 = require("./commands/copy");
18
+ const show_1 = require("./commands/show");
19
+ const search_1 = require("./commands/search");
20
+ const get_1 = require("./commands/get");
21
+ const improve_1 = require("./commands/improve");
22
+ const loop_1 = require("./commands/loop");
23
+ /** A single global try/catch — consistent error output for every command. */
24
+ function runWithErrorHandler(fn) {
25
+ return async (...args) => {
26
+ try {
27
+ await fn(...args);
28
+ }
29
+ catch (err) {
30
+ const message = err instanceof Error ? err.message : String(err);
31
+ console.error(format_1.c.error(`✗ ${message}`));
32
+ process.exit(process.exitCode || 1);
33
+ }
34
+ };
35
+ }
36
+ const program = new commander_1.Command();
37
+ program
38
+ .name(constants_1.CLI_NAME)
39
+ .description('Terminal access to your PromptLikeEngineer prompt library')
40
+ .version(constants_1.CLI_VERSION);
41
+ program
42
+ .command('login')
43
+ .description('Sign in with email + password; store the session under ~/.config/promptlike/')
44
+ .action(runWithErrorHandler(login_1.loginCommand));
45
+ program
46
+ .command('logout')
47
+ .description('Delete the local session file')
48
+ .action(runWithErrorHandler(logout_1.logoutCommand));
49
+ program
50
+ .command('list')
51
+ .description('List your prompts')
52
+ .option('-t, --tag <name>', 'Filter by a specific tag')
53
+ .option('-l, --limit <n>', 'Max number of rows (default 30)', '30')
54
+ .action(runWithErrorHandler(list_1.listCommand));
55
+ program
56
+ .command('copy <name>')
57
+ .description('Copy a prompt to the clipboard (by title or short id)')
58
+ .action(runWithErrorHandler(copy_1.copyCommand));
59
+ program
60
+ .command('show <name>')
61
+ .description('Show a prompt in the terminal')
62
+ .action(runWithErrorHandler(show_1.showCommand));
63
+ program
64
+ .command('get <name>')
65
+ .description("Print a prompt raw to stdout; fill {{variables}} (agent/pipe friendly)")
66
+ .option('-v, --var <keyval>', 'Fill a variable — key=value (repeatable)', get_1.collectVar, {})
67
+ .option('-c, --copy', 'Also copy the output to the clipboard')
68
+ .action(runWithErrorHandler(get_1.getCommand));
69
+ program
70
+ .command('improve <name>')
71
+ .description('Generate AI variants of a prompt, pick a winner, save it as a new version (Pro)')
72
+ .option('-f, --focus <hint>', "Steer the variants (e.g. 'shorter', 'more explicit output format')")
73
+ .action(runWithErrorHandler(improve_1.improveCommand));
74
+ program
75
+ .command('loop <name>')
76
+ .description('Multi-round improve — optionally test each variant with your own agent command (Pro)')
77
+ .option('-e, --exec <cmd>', 'Test each variant: prompt passed via PLE_PROMPT env + stdin; {} placeholder substituted')
78
+ .option('-r, --rounds <n>', 'Number of improvement rounds', '1')
79
+ .option('-f, --focus <hint>', 'Steer the variants')
80
+ .action(runWithErrorHandler(loop_1.loopCommand));
81
+ program
82
+ .command('search <keyword>')
83
+ .description('Search within title and description')
84
+ .action(runWithErrorHandler(search_1.searchCommand));
85
+ program.parseAsync(process.argv);
@@ -0,0 +1,192 @@
1
+ "use strict";
2
+ /**
3
+ * Thin HTTP client for the PromptLikeEngineer web API.
4
+ *
5
+ * Replaces the old direct-Supabase client. The CLI authenticates with
6
+ * `Authorization: Bearer <access_token>` (token obtained via `ple login`,
7
+ * stored in ~/.config/promptlike/config.json). All data access goes through
8
+ * the same Next.js API the web app uses, so rate-limiting, input validation
9
+ * and safe error messages apply uniformly.
10
+ *
11
+ * Responsibilities:
12
+ * - attach the bearer token, resolve URLs against API_BASE_URL
13
+ * - proactive refresh (expiring token) + reactive refresh on 401, retry once
14
+ * - map 429 / error bodies to clean, user-facing Error messages
15
+ */
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ exports.login = login;
18
+ exports.ensureAuthed = ensureAuthed;
19
+ exports.listPrompts = listPrompts;
20
+ exports.getPromptById = getPromptById;
21
+ const constants_1 = require("./constants");
22
+ const config_1 = require("./config");
23
+ const NOT_LOGGED_IN = 'Not logged in. Run `ple login` first.';
24
+ const SESSION_EXPIRED = 'Session expired. Log in again: `ple login`';
25
+ /**
26
+ * Fallback messages for server error codes. The API almost always sends a
27
+ * human-readable `error` string; this map is only used when a response carries
28
+ * a `code` but no `error`. Kept local so the CLI stays self-contained (no
29
+ * dependency on shared/types).
30
+ */
31
+ const ERROR_FALLBACKS = {
32
+ UNAUTHORIZED: 'You are not authorized to perform this action.',
33
+ SESSION_EXPIRED: 'Your session has expired. Please sign in again.',
34
+ INVALID_CREDENTIALS: 'Invalid email or password.',
35
+ NOT_FOUND: 'The requested resource was not found.',
36
+ VALIDATION_ERROR: 'Please check your input and try again.',
37
+ INVALID_INPUT: 'The provided input is invalid.',
38
+ MISSING_REQUIRED_FIELD: 'Please fill in all required fields.',
39
+ RATE_LIMITED: 'Too many requests - please slow down and try again in a moment.',
40
+ LIMIT_EXCEEDED: 'You have reached your plan limit.',
41
+ PLAN_RESTRICTION: 'This feature is not available on your current plan.',
42
+ INTERNAL_ERROR: 'An unexpected error occurred. Please try again later.',
43
+ SERVICE_UNAVAILABLE: 'Service is temporarily unavailable.',
44
+ };
45
+ /** Build a full request URL, appending defined query params. */
46
+ function buildUrl(path, query) {
47
+ const u = new URL(constants_1.API_BASE_URL + path);
48
+ if (query) {
49
+ for (const [key, value] of Object.entries(query)) {
50
+ if (value !== undefined && value !== '') {
51
+ u.searchParams.set(key, String(value));
52
+ }
53
+ }
54
+ }
55
+ return u.toString();
56
+ }
57
+ /** Turn a non-OK response into a clean Error using the server's safe message. */
58
+ async function toError(res) {
59
+ let body = {};
60
+ try {
61
+ body = (await res.json());
62
+ }
63
+ catch {
64
+ // Non-JSON error body — fall back to a generic message below.
65
+ }
66
+ if (body.error)
67
+ return new Error(body.error);
68
+ if (body.code && ERROR_FALLBACKS[body.code]) {
69
+ return new Error(ERROR_FALLBACKS[body.code]);
70
+ }
71
+ return new Error(`Request failed (${res.status}).`);
72
+ }
73
+ function getAccessTokenOrThrow() {
74
+ const config = (0, config_1.readConfig)();
75
+ if (!config)
76
+ throw new Error(NOT_LOGGED_IN);
77
+ return config.access_token;
78
+ }
79
+ /** Persist a fresh auth payload to the local config file. */
80
+ function persist(data) {
81
+ const previous = (0, config_1.readConfig)();
82
+ const config = {
83
+ access_token: data.access_token,
84
+ refresh_token: data.refresh_token,
85
+ email: data.user?.email ?? previous?.email ?? '',
86
+ user_id: data.user?.id ?? previous?.user_id ?? '',
87
+ expires_at: data.expires_at ?? Math.floor(Date.now() / 1000) + 3600,
88
+ };
89
+ (0, config_1.writeConfig)(config);
90
+ return config;
91
+ }
92
+ /** Exchange the stored refresh token for a new session. Throws if it fails. */
93
+ async function refreshSession() {
94
+ const config = (0, config_1.readConfig)();
95
+ if (!config)
96
+ throw new Error(NOT_LOGGED_IN);
97
+ let data;
98
+ try {
99
+ data = await apiFetch('/api/auth/cli/refresh', {
100
+ method: 'POST',
101
+ body: { refresh_token: config.refresh_token },
102
+ auth: false,
103
+ });
104
+ }
105
+ catch {
106
+ throw new Error(SESSION_EXPIRED);
107
+ }
108
+ persist(data);
109
+ }
110
+ /** Core request helper. See module doc for behavior. */
111
+ async function apiFetch(path, opts = {}) {
112
+ const { method = 'GET', body, query, auth = true } = opts;
113
+ const headers = { 'Content-Type': 'application/json' };
114
+ if (auth) {
115
+ headers['Authorization'] = `Bearer ${getAccessTokenOrThrow()}`;
116
+ }
117
+ let res;
118
+ try {
119
+ res = await fetch(buildUrl(path, query), {
120
+ method,
121
+ headers,
122
+ body: body === undefined ? undefined : JSON.stringify(body),
123
+ });
124
+ }
125
+ catch (err) {
126
+ throw new Error(`Cannot reach ${constants_1.API_BASE_URL}. Check your connection. (${err instanceof Error ? err.message : String(err)})`);
127
+ }
128
+ // Reactive refresh: expired/invalid access token → refresh once, retry once.
129
+ if (res.status === 401 && auth) {
130
+ if (opts._retried)
131
+ throw new Error(SESSION_EXPIRED);
132
+ await refreshSession();
133
+ return apiFetch(path, { ...opts, _retried: true });
134
+ }
135
+ if (res.status === 429) {
136
+ const retryAfter = res.headers.get('retry-after');
137
+ throw new Error(`Rate limited. Try again${retryAfter ? ` in ${retryAfter}s` : ' in a moment'}.`);
138
+ }
139
+ if (!res.ok) {
140
+ throw await toError(res);
141
+ }
142
+ return (await res.json());
143
+ }
144
+ // ---------------------------------------------------------------------------
145
+ // Public surface used by commands / the resolver
146
+ // ---------------------------------------------------------------------------
147
+ /** `ple login` — exchange email + password for a session, store it locally. */
148
+ async function login(email, password) {
149
+ const data = await apiFetch('/api/auth/cli/login', {
150
+ method: 'POST',
151
+ body: { email, password },
152
+ auth: false,
153
+ });
154
+ return persist(data);
155
+ }
156
+ /**
157
+ * Guard for authenticated commands: throws a clear "log in" message when no
158
+ * session exists, and proactively refreshes a soon-to-expire token so the
159
+ * first real request doesn't have to round-trip through a 401.
160
+ */
161
+ async function ensureAuthed() {
162
+ const config = (0, config_1.readConfig)();
163
+ if (!config)
164
+ throw new Error(NOT_LOGGED_IN);
165
+ if ((0, config_1.isTokenExpiringSoon)(config)) {
166
+ await refreshSession();
167
+ }
168
+ }
169
+ /** GET /api/prompts — list the user's prompts (optionally by tag / search). */
170
+ async function listPrompts(params = {}) {
171
+ const res = await apiFetch('/api/prompts', {
172
+ query: {
173
+ tag: params.tag,
174
+ search: params.search,
175
+ limit: params.limit,
176
+ page: params.page,
177
+ },
178
+ });
179
+ return res.prompts ?? [];
180
+ }
181
+ /** GET /api/prompts/{id} — full detail; returns null when not found (404). */
182
+ async function getPromptById(id) {
183
+ try {
184
+ const res = await apiFetch(`/api/prompts/${id}`);
185
+ return res.prompt ?? null;
186
+ }
187
+ catch (err) {
188
+ if (err instanceof Error && /not found/i.test(err.message))
189
+ return null;
190
+ throw err;
191
+ }
192
+ }
@@ -0,0 +1,70 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.copyToClipboard = copyToClipboard;
4
+ const child_process_1 = require("child_process");
5
+ /**
6
+ * Cross-platform clipboard write.
7
+ * - macOS → pbcopy
8
+ * - Linux → xclip -selection clipboard (Wayland'da wl-copy)
9
+ * - Win32 → clip.exe
10
+ *
11
+ * Eksik komut hatası kullanıcıya açıklayıcı bir mesaj veriyor; sessizce
12
+ * başarısız olmuyor. clipboardy gibi bir dep eklemiyoruz çünkü native komut
13
+ * her sistemde zaten var ve npm bağımlılığı genişliği yaratmıyor.
14
+ */
15
+ function copyToClipboard(text) {
16
+ return new Promise((resolve, reject) => {
17
+ const platform = process.platform;
18
+ let cmd;
19
+ let args;
20
+ if (platform === 'darwin') {
21
+ cmd = 'pbcopy';
22
+ args = [];
23
+ }
24
+ else if (platform === 'win32') {
25
+ cmd = 'clip';
26
+ args = [];
27
+ }
28
+ else {
29
+ // Linux / freebsd / vs. — xclip varsayılan, yoksa wl-copy fallback
30
+ cmd = 'xclip';
31
+ args = ['-selection', 'clipboard'];
32
+ }
33
+ const child = (0, child_process_1.spawn)(cmd, args, { stdio: ['pipe', 'ignore', 'pipe'] });
34
+ let stderr = '';
35
+ child.stderr.on('data', (chunk) => {
36
+ stderr += chunk.toString();
37
+ });
38
+ child.on('error', (err) => {
39
+ // On Linux, if xclip is missing, try wl-copy.
40
+ if (platform === 'linux' && err.message.includes('ENOENT')) {
41
+ tryWlCopy(text).then(resolve, reject);
42
+ return;
43
+ }
44
+ reject(new Error(`Clipboard command (${cmd}) not found. ${platform === 'linux' ? 'Install xclip or wl-clipboard.' : ''}`));
45
+ });
46
+ child.on('close', (code) => {
47
+ if (code === 0)
48
+ resolve();
49
+ else
50
+ reject(new Error(`Clipboard command exited with code ${code}: ${stderr}`));
51
+ });
52
+ child.stdin.end(text);
53
+ });
54
+ }
55
+ /** Linux Wayland fallback. */
56
+ function tryWlCopy(text) {
57
+ return new Promise((resolve, reject) => {
58
+ const child = (0, child_process_1.spawn)('wl-copy', [], { stdio: ['pipe', 'ignore', 'pipe'] });
59
+ child.on('error', () => {
60
+ reject(new Error('Clipboard needs xclip or wl-clipboard installed. (apt install xclip or apt install wl-clipboard)'));
61
+ });
62
+ child.on('close', (code) => {
63
+ if (code === 0)
64
+ resolve();
65
+ else
66
+ reject(new Error(`wl-copy hata kodu ${code}`));
67
+ });
68
+ child.stdin.end(text);
69
+ });
70
+ }