promptlike 0.3.0 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md ADDED
@@ -0,0 +1,69 @@
1
+ # Changelog
2
+
3
+ ## 0.4.1 — 2026-08-15
4
+
5
+ Data-integrity fix — **update recommended for every 0.4.0 install.**
6
+
7
+ - **Fixed: empty frontmatter fields swallowed the next line on read.** A prompt
8
+ saved without `-d`/`-t` (the most common form) read back with
9
+ `description: "tags:"` and a phantom tag like `created: <timestamp>`;
10
+ `--force` re-saves made the corruption permanent and `ple sync` could upload
11
+ the phantom tag to your account. Root cause: a `\s*` in the parser crossed
12
+ line endings. Files written by 0.4.0 are re-read correctly after this fix
13
+ unless they were re-saved with `--force` (open the file and delete the stray
14
+ text from `description:`/`tags:` lines if so).
15
+ - `ple sync` now reports partial success when a later batch hits the plan
16
+ limit, instead of dying with a bare error after silently uploading a batch.
17
+ The server also accounts for records dropped mid-loop by the limit trigger,
18
+ so uploaded + failed + skipped + truncated always adds up.
19
+ - Out-of-tokens (402) now says what it means: top up with a $3 MicroBoost or
20
+ wait for the monthly reset — instead of a generic "temporarily unavailable".
21
+ - Duplicate-slug error now shows the existing prompt's actual title (two
22
+ different titles can slugify to the same name).
23
+ - A single `--tag "a,b"` is stored as two tags instead of silently splitting
24
+ on the next read.
25
+ - `ple search --help` now says local mode also searches bodies and tags.
26
+
27
+ ## 0.4.0 — 2026-08-10
28
+
29
+ The install is no longer a dead end.
30
+
31
+ ### Local-first mode — no account needed
32
+
33
+ - **`ple save <title>`** writes a prompt to `~/.promptlike/prompts/<slug>.md`
34
+ (body via `-m` or stdin). Plain Markdown with a small frontmatter block —
35
+ greppable, diffable, git-committable.
36
+ - **`list` / `show` / `get` / `copy` / `search` work signed out**, reading the
37
+ local store. Signed in, the same commands read your account library — the
38
+ commands don't change, only where they read from.
39
+ - **`ple sync [--dry-run]`** uploads local prompts into your account — one-way,
40
+ explicit, never automatic on login. Tags travel too when the server supports
41
+ them; when it doesn't, the CLI says so instead of dropping them silently.
42
+ Sync copies; local files are kept.
43
+
44
+ ### Fixes (from the 2026-08-10 audit)
45
+
46
+ - `ple login` now tells you when local prompts exist and how to bring them up
47
+ (`ple sync --dry-run`) — previously they silently disappeared from view
48
+ after signing in.
49
+ - A corrupt session file now warns and falls back to local mode instead of
50
+ silently pretending you never logged in.
51
+ - `ple save` enforces the same limits as the account API (title 200 chars,
52
+ body 100K, description 1000) with clear errors, instead of a raw
53
+ `ENAMETOOLONG` or a silent server-side truncation on sync.
54
+ - Overwriting with `--force` keeps tags and the description you didn't repeat —
55
+ it used to wipe them, unrecoverably.
56
+ - `--project` prints a note when ignored in signed-out mode instead of
57
+ silently returning different results.
58
+
59
+ ### Notes
60
+
61
+ - Local store root is overridable with `PROMPTLIKE_HOME`.
62
+ - `ple get` keeps stdout machine-clean in both modes (warnings go to stderr),
63
+ so piping into an agent behaves identically signed in or out.
64
+
65
+ ## 0.3.x
66
+
67
+ - CLI moved from direct Supabase access to the web API (bearer auth).
68
+ - `ple loop`: test prompt variants against your own agent.
69
+ - `--project` scoping, `ple get --var`, usage recording for Most Used.
package/README.md CHANGED
@@ -6,18 +6,29 @@
6
6
  [![License: MIT](https://img.shields.io/badge/License-MIT-green.svg)](LICENSE)
7
7
  [![Node](https://img.shields.io/badge/node-%E2%89%A518-brightgreen)](https://nodejs.org/)
8
8
 
9
- `ple` lets you reach the prompts you've saved on
10
- [promptlikeengineer.com](https://promptlikeengineer.com) without leaving your
11
- terminal. Search, read, copy. That's it.
9
+ `ple` keeps your prompts one command away. Save, search, read, copy — **no
10
+ account required to start.**
12
11
 
13
12
  ```bash
14
- ple list # see every prompt you've saved
15
- ple copy "code review" # find by title and copy to clipboard
13
+ npm i -g promptlike
14
+ ple save "code review" -m "Review this diff and flag risks: {{diff}}"
15
+ ple get "code review" --var diff="$(git diff)" | claude
16
16
  ```
17
17
 
18
- The CLI talks to the same PromptLikeEngineer web API your account uses, so
19
- anything you save on the web is instantly available here. You need a (free)
20
- PromptLikeEngineer account to log in.
18
+ Prompts live as plain Markdown files in `~/.promptlike/prompts/` — greppable,
19
+ diffable, and yours. Nothing leaves your machine until you ask it to.
20
+
21
+ **Signing in is the upgrade, not the door.** A free
22
+ [promptlikeengineer.com](https://promptlikeengineer.com) account adds version
23
+ history with diff and rollback, the web editor, the Chrome extension, and the
24
+ same library inside any MCP client. Bring your local prompts up with one
25
+ explicit command:
26
+
27
+ ```bash
28
+ ple login
29
+ ple sync --dry-run # see exactly what would be uploaded
30
+ ple sync # one-way, local → account; local files are kept
31
+ ```
21
32
 
22
33
  ---
23
34
 
@@ -66,6 +77,38 @@ Cursor, your shell, anywhere — `ple` doesn't know or care.
66
77
 
67
78
  ## Commands
68
79
 
80
+ > **Signed out, every read command uses the local store; signed in, the same
81
+ > command uses your account library.** The commands do not change — only where
82
+ > they read from.
83
+
84
+ ### `ple save <title>` — no account needed
85
+
86
+ Writes a prompt to `~/.promptlike/prompts/<slug>.md`. Body comes from
87
+ `-m/--message` or from stdin.
88
+
89
+ ```bash
90
+ $ ple save "code review" -m "Review this diff: {{diff}}" -t review
91
+ ✓ Saved: code review (code-review)
92
+ ~/.promptlike/prompts/code-review.md
93
+ variables: {{diff}}
94
+ use it: ple get "code-review" --var diff=...
95
+
96
+ $ pbpaste | ple save "bug triage" # or pipe it in
97
+ ```
98
+
99
+ Saving over an existing prompt needs `--force`, because the local store keeps
100
+ no version history. Tags and the description you do not repeat are carried
101
+ over rather than wiped.
102
+
103
+ ### `ple sync [--dry-run]`
104
+
105
+ Uploads local prompts into your signed-in account. **Explicit on purpose** —
106
+ nothing is uploaded when you log in, only when you ask.
107
+
108
+ One-way (local → account) and it *copies*: your local files stay where they
109
+ are, so running it twice uploads twice. `--dry-run` prints the list and
110
+ changes nothing.
111
+
69
112
  ### `ple login`
70
113
 
71
114
  Authenticates with email + password and stores the session at
@@ -2,6 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.copyCommand = copyCommand;
4
4
  const api_client_1 = require("../lib/api-client");
5
+ const local_1 = require("./local");
5
6
  const promptResolver_1 = require("../lib/promptResolver");
6
7
  const clipboard_1 = require("../lib/clipboard");
7
8
  const format_1 = require("../lib/format");
@@ -10,6 +11,11 @@ const format_1 = require("../lib/format");
10
11
  * content to the system clipboard.
11
12
  */
12
13
  async function copyCommand(name, options = {}) {
14
+ if ((0, local_1.isSignedOut)()) {
15
+ (0, local_1.noteIgnoredProject)(options.project);
16
+ await (0, local_1.localCopy)(name);
17
+ return;
18
+ }
13
19
  await (0, api_client_1.ensureAuthed)();
14
20
  const projectId = options.project ? await (0, promptResolver_1.resolveProjectId)(options.project) : undefined;
15
21
  const prompt = await (0, promptResolver_1.resolvePromptByName)(name, { projectId });
@@ -3,6 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.getCommand = getCommand;
4
4
  exports.collectVar = collectVar;
5
5
  const api_client_1 = require("../lib/api-client");
6
+ const local_1 = require("./local");
6
7
  const promptResolver_1 = require("../lib/promptResolver");
7
8
  const clipboard_1 = require("../lib/clipboard");
8
9
  const format_1 = require("../lib/format");
@@ -20,6 +21,11 @@ const promptVariables_1 = require("../lib/promptVariables");
20
21
  * ple get "code review" --var lang=python | claude # pipe to an agent
21
22
  */
22
23
  async function getCommand(name, options = {}) {
24
+ if ((0, local_1.isSignedOut)()) {
25
+ (0, local_1.noteIgnoredProject)(options.project);
26
+ await (0, local_1.localGet)(name, options.var ?? {}, options.copy === true);
27
+ return;
28
+ }
23
29
  await (0, api_client_1.ensureAuthed)();
24
30
  const projectId = options.project ? await (0, promptResolver_1.resolveProjectId)(options.project) : undefined;
25
31
  const prompt = await (0, promptResolver_1.resolvePromptByName)(name, { projectId });
@@ -2,6 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.listCommand = listCommand;
4
4
  const api_client_1 = require("../lib/api-client");
5
+ const local_1 = require("./local");
5
6
  const constants_1 = require("../lib/constants");
6
7
  const format_1 = require("../lib/format");
7
8
  /**
@@ -13,6 +14,11 @@ const format_1 = require("../lib/format");
13
14
  */
14
15
  async function listCommand(options) {
15
16
  const limit = Math.max(1, Math.min(100, parseInt(options.limit ?? '30', 10) || 30));
17
+ // Signed out → the local store. The install has to be useful on its own.
18
+ if ((0, local_1.isSignedOut)()) {
19
+ (0, local_1.localList)({ tag: options.tag, limit });
20
+ return;
21
+ }
16
22
  await (0, api_client_1.ensureAuthed)();
17
23
  const prompts = await (0, api_client_1.listPrompts)({ tag: options.tag, limit });
18
24
  if (prompts.length === 0) {
@@ -0,0 +1,204 @@
1
+ "use strict";
2
+ /**
3
+ * Logged-out implementations of the read commands.
4
+ *
5
+ * Every read command routes here when there is no session, so the CLI does
6
+ * real work the moment it is installed. The signed-in behaviour is untouched.
7
+ */
8
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
9
+ if (k2 === undefined) k2 = k;
10
+ var desc = Object.getOwnPropertyDescriptor(m, k);
11
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
12
+ desc = { enumerable: true, get: function() { return m[k]; } };
13
+ }
14
+ Object.defineProperty(o, k2, desc);
15
+ }) : (function(o, m, k, k2) {
16
+ if (k2 === undefined) k2 = k;
17
+ o[k2] = m[k];
18
+ }));
19
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
20
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
21
+ }) : function(o, v) {
22
+ o["default"] = v;
23
+ });
24
+ var __importStar = (this && this.__importStar) || (function () {
25
+ var ownKeys = function(o) {
26
+ ownKeys = Object.getOwnPropertyNames || function (o) {
27
+ var ar = [];
28
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
29
+ return ar;
30
+ };
31
+ return ownKeys(o);
32
+ };
33
+ return function (mod) {
34
+ if (mod && mod.__esModule) return mod;
35
+ var result = {};
36
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
37
+ __setModuleDefault(result, mod);
38
+ return result;
39
+ };
40
+ })();
41
+ Object.defineProperty(exports, "__esModule", { value: true });
42
+ exports.isSignedOut = isSignedOut;
43
+ exports.noteIgnoredProject = noteIgnoredProject;
44
+ exports.emptyHint = emptyHint;
45
+ exports.localList = localList;
46
+ exports.localShow = localShow;
47
+ exports.localGet = localGet;
48
+ exports.localCopy = localCopy;
49
+ exports.localSearch = localSearch;
50
+ const store = __importStar(require("../lib/localStore"));
51
+ const config_1 = require("../lib/config");
52
+ const clipboard_1 = require("../lib/clipboard");
53
+ const format_1 = require("../lib/format");
54
+ const promptVariables_1 = require("../lib/promptVariables");
55
+ /**
56
+ * Routing guard for the read commands: true → use the local store.
57
+ *
58
+ * A corrupt session file routes local like an absent one, but says so first —
59
+ * a signed-in user silently dropped into an (often empty) local list reads it
60
+ * as data loss.
61
+ */
62
+ function isSignedOut() {
63
+ const status = (0, config_1.configStatus)();
64
+ if (status === 'invalid') {
65
+ console.error(format_1.c.warn('⚠ Session file exists but is unreadable — showing local prompts instead.'));
66
+ console.error(format_1.c.muted(' Fix it by signing in again: ple login'));
67
+ }
68
+ return status !== 'valid';
69
+ }
70
+ /**
71
+ * `--project` scopes account repos; local prompts have no projects. Saying so
72
+ * beats silently returning different results than the user asked for.
73
+ */
74
+ function noteIgnoredProject(project) {
75
+ if (project) {
76
+ console.error(format_1.c.muted(`(--project '${project}' is ignored while signed out — local prompts have no projects)`));
77
+ }
78
+ }
79
+ /** Shown once when a command finds nothing locally — never nags mid-flow. */
80
+ function emptyHint() {
81
+ console.log(format_1.c.muted('No local prompts yet.'));
82
+ console.log(format_1.c.muted(' Save one: ple save "code review" -m "Review this diff: {{diff}}"'));
83
+ console.log(format_1.c.muted(' Or sign in to use your account library: ple login'));
84
+ }
85
+ /** Resolve or explain. Returns null when the caller should stop (exit code set). */
86
+ function resolveOrExplain(name) {
87
+ const hit = store.resolve(name);
88
+ if (hit === null) {
89
+ console.error(format_1.c.error(`No local prompt matched '${name}'.`));
90
+ console.error(format_1.c.muted("Run `ple list` to see what you have, or `ple login` for your account library."));
91
+ process.exitCode = 1;
92
+ return null;
93
+ }
94
+ if ('candidates' in hit) {
95
+ console.error(format_1.c.error(`'${name}' matches ${hit.candidates.length} prompts:`));
96
+ for (const p of hit.candidates)
97
+ console.error(format_1.c.muted(` ${p.slug} ${p.title}`));
98
+ console.error(format_1.c.muted('Re-run with the exact name on the left.'));
99
+ process.exitCode = 1;
100
+ return null;
101
+ }
102
+ return hit.prompt;
103
+ }
104
+ function localList(options) {
105
+ let rows = store.list();
106
+ if (options.tag) {
107
+ const tag = options.tag.toLowerCase();
108
+ rows = rows.filter((p) => p.tags.some((t) => t.toLowerCase() === tag));
109
+ }
110
+ if (rows.length === 0) {
111
+ if (options.tag)
112
+ console.log(format_1.c.muted(`No local prompts tagged '${options.tag}'.`));
113
+ else
114
+ emptyHint();
115
+ return;
116
+ }
117
+ rows = rows.slice(0, options.limit);
118
+ console.log(format_1.c.label('NAME TITLE UPDATED'));
119
+ console.log(format_1.c.label('──────────────────────── ──────────────────────────────────────── ──────────'));
120
+ for (const p of rows) {
121
+ const slug = format_1.c.muted((0, format_1.truncate)(p.slug, 24).padEnd(24));
122
+ const title = (0, format_1.truncate)(p.title, 40).padEnd(40);
123
+ const updated = format_1.c.muted(p.updated ? (0, format_1.timeAgo)(p.updated) : '');
124
+ console.log(`${slug} ${title} ${updated}`);
125
+ }
126
+ console.log(format_1.c.muted(`\n${rows.length} local prompt${rows.length === 1 ? '' : 's'} · stored in ${store.promptsDir()}`));
127
+ }
128
+ function localShow(name) {
129
+ const p = resolveOrExplain(name);
130
+ if (!p)
131
+ return;
132
+ console.log();
133
+ console.log(format_1.c.title(p.title));
134
+ const meta = [p.slug, p.updated ? `updated ${(0, format_1.timeAgo)(p.updated)}` : ''].filter(Boolean).join(' · ');
135
+ console.log(format_1.c.muted(meta));
136
+ if (p.description) {
137
+ console.log();
138
+ console.log(format_1.c.label(p.description));
139
+ }
140
+ console.log();
141
+ console.log(p.body);
142
+ console.log();
143
+ if (p.tags.length > 0)
144
+ console.log(format_1.c.muted(`tags: ${p.tags.join(', ')}`));
145
+ }
146
+ async function localGet(name, values, copy) {
147
+ const p = resolveOrExplain(name);
148
+ if (!p)
149
+ return;
150
+ if (!p.body.trim()) {
151
+ console.error(format_1.c.error(`'${p.title}' has empty content.`));
152
+ process.exitCode = 1;
153
+ return;
154
+ }
155
+ const { text } = store.fillVariables(p.body, values);
156
+ // stdout stays machine-clean; warnings go to stderr (same contract as the
157
+ // signed-in `ple get`, so piping behaves identically either way).
158
+ const remaining = (0, promptVariables_1.extractVariables)(text);
159
+ if (remaining.length > 0) {
160
+ console.error(format_1.c.warn(`⚠ Unfilled variables: ${remaining.map((v) => `{{${v}}}`).join(', ')}`));
161
+ }
162
+ process.stdout.write(text.endsWith('\n') ? text : `${text}\n`);
163
+ if (copy) {
164
+ try {
165
+ await (0, clipboard_1.copyToClipboard)(text);
166
+ console.error(format_1.c.success('✓ Copied to clipboard'));
167
+ }
168
+ catch {
169
+ console.error(format_1.c.warn('⚠ Could not copy to clipboard'));
170
+ }
171
+ }
172
+ }
173
+ async function localCopy(name) {
174
+ const p = resolveOrExplain(name);
175
+ if (!p)
176
+ return;
177
+ if (!p.body.trim()) {
178
+ console.error(format_1.c.error(`'${p.title}' has empty content.`));
179
+ process.exitCode = 1;
180
+ return;
181
+ }
182
+ try {
183
+ await (0, clipboard_1.copyToClipboard)(p.body);
184
+ console.log(format_1.c.success(`✓ Copied: ${p.title}`) + format_1.c.muted(` (${p.slug}, ${p.body.length} chars)`));
185
+ }
186
+ catch {
187
+ console.error(format_1.c.error('Could not access the clipboard.'));
188
+ process.exitCode = 1;
189
+ }
190
+ }
191
+ function localSearch(keyword) {
192
+ const rows = store.search(keyword);
193
+ if (rows.length === 0) {
194
+ console.log(format_1.c.muted(`No local prompts matched '${keyword}'.`));
195
+ return;
196
+ }
197
+ console.log(format_1.c.label(`${rows.length} result${rows.length === 1 ? '' : 's'}:`));
198
+ console.log();
199
+ for (const p of rows) {
200
+ console.log(`${format_1.c.title(p.title)} ${format_1.c.muted(`· ${p.slug}${p.updated ? ` · ${(0, format_1.timeAgo)(p.updated)}` : ''}`)}`);
201
+ if (p.description)
202
+ console.log(format_1.c.muted(` ${(0, format_1.truncate)(p.description, 80)}`));
203
+ }
204
+ }
@@ -37,6 +37,7 @@ exports.loginCommand = loginCommand;
37
37
  const readline = __importStar(require("readline"));
38
38
  const stream_1 = require("stream");
39
39
  const api_client_1 = require("../lib/api-client");
40
+ const store = __importStar(require("../lib/localStore"));
40
41
  const format_1 = require("../lib/format");
41
42
  /**
42
43
  * `ple login` — sign in with email + password via the web API.
@@ -61,6 +62,14 @@ async function loginCommand() {
61
62
  const config = await (0, api_client_1.login)(email, password);
62
63
  console.log(format_1.c.success(`✓ Logged in as ${config.email}`));
63
64
  console.log(format_1.c.muted("Next: run 'ple list' to see your prompts."));
65
+ // The commands now read from the ACCOUNT library, so prompts saved while
66
+ // signed out stop showing up. Without this line that reads as data loss —
67
+ // the files are fine, the bridge is `ple sync`, but nothing said so.
68
+ const localCount = store.list().length;
69
+ if (localCount > 0) {
70
+ console.log(format_1.c.muted(`${localCount} local prompt${localCount === 1 ? '' : 's'} on this machine are not shown while signed in — ` +
71
+ 'bring them into your account: ple sync --dry-run'));
72
+ }
64
73
  }
65
74
  /** Read a single line with standard readline. */
66
75
  function prompt(question) {
@@ -0,0 +1,148 @@
1
+ "use strict";
2
+ /**
3
+ * `ple save <title>` — write a prompt to the local store. **No account needed.**
4
+ *
5
+ * This is the command that makes `npm i -g promptlike` worth something on its
6
+ * own. Body comes from `-m/--message`, or from stdin when piped:
7
+ *
8
+ * ple save "code review" -m "Review this diff: {{diff}}"
9
+ * pbpaste | ple save "code review"
10
+ * cat prompt.txt | ple save "code review" --tag review
11
+ */
12
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
13
+ if (k2 === undefined) k2 = k;
14
+ var desc = Object.getOwnPropertyDescriptor(m, k);
15
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
16
+ desc = { enumerable: true, get: function() { return m[k]; } };
17
+ }
18
+ Object.defineProperty(o, k2, desc);
19
+ }) : (function(o, m, k, k2) {
20
+ if (k2 === undefined) k2 = k;
21
+ o[k2] = m[k];
22
+ }));
23
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
24
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
25
+ }) : function(o, v) {
26
+ o["default"] = v;
27
+ });
28
+ var __importStar = (this && this.__importStar) || (function () {
29
+ var ownKeys = function(o) {
30
+ ownKeys = Object.getOwnPropertyNames || function (o) {
31
+ var ar = [];
32
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
33
+ return ar;
34
+ };
35
+ return ownKeys(o);
36
+ };
37
+ return function (mod) {
38
+ if (mod && mod.__esModule) return mod;
39
+ var result = {};
40
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
41
+ __setModuleDefault(result, mod);
42
+ return result;
43
+ };
44
+ })();
45
+ Object.defineProperty(exports, "__esModule", { value: true });
46
+ exports.collectTag = collectTag;
47
+ exports.saveCommand = saveCommand;
48
+ const store = __importStar(require("../lib/localStore"));
49
+ const format_1 = require("../lib/format");
50
+ const promptVariables_1 = require("../lib/promptVariables");
51
+ /**
52
+ * Same caps the web API enforces (title 200 / body 100K / description 1000).
53
+ * The CLI mirrors them instead of letting `ple sync` discover the mismatch:
54
+ * the server would silently slice, and local ≠ account is exactly the kind of
55
+ * divergence this tool exists to prevent. A too-long title also has a second
56
+ * failure mode of its own — the 255-byte filename limit throws a raw
57
+ * ENAMETOOLONG with no explanation.
58
+ */
59
+ const MAX_TITLE = 200;
60
+ const MAX_BODY = 100000;
61
+ const MAX_DESCRIPTION = 1000;
62
+ /** Collector for repeatable `--tag`. */
63
+ function collectTag(value, previous) {
64
+ return [...previous, value];
65
+ }
66
+ /** Read piped stdin. Returns '' when the CLI is attached to a terminal. */
67
+ function readStdin() {
68
+ if (process.stdin.isTTY)
69
+ return Promise.resolve('');
70
+ return new Promise((resolve) => {
71
+ let data = '';
72
+ let overflowed = false;
73
+ process.stdin.setEncoding('utf-8');
74
+ process.stdin.on('data', (chunk) => {
75
+ // Stop buffering once the input cannot possibly be valid — a
76
+ // mistakenly piped log file must not be read into memory whole.
77
+ // One chunk past the cap is kept so the size check can report
78
+ // "too long" instead of an off-by-one "just fits".
79
+ if (overflowed)
80
+ return;
81
+ data += chunk;
82
+ if (data.length > MAX_BODY + 1)
83
+ overflowed = true;
84
+ });
85
+ process.stdin.on('end', () => resolve(data));
86
+ process.stdin.on('error', () => resolve(''));
87
+ });
88
+ }
89
+ async function saveCommand(title, options = {}) {
90
+ const cleanTitle = title.trim();
91
+ if (!cleanTitle) {
92
+ console.error(format_1.c.error('Title is empty.'));
93
+ process.exitCode = 1;
94
+ return;
95
+ }
96
+ if (cleanTitle.length > MAX_TITLE) {
97
+ console.error(format_1.c.error(`Title is too long (${cleanTitle.length} chars, max ${MAX_TITLE}).`));
98
+ process.exitCode = 1;
99
+ return;
100
+ }
101
+ if (options.description && options.description.length > MAX_DESCRIPTION) {
102
+ console.error(format_1.c.error(`Description is too long (max ${MAX_DESCRIPTION} chars).`));
103
+ process.exitCode = 1;
104
+ return;
105
+ }
106
+ const body = (options.message ?? (await readStdin())).trim();
107
+ if (body.length > MAX_BODY) {
108
+ console.error(format_1.c.error(`Prompt body is too long (over ${MAX_BODY.toLocaleString('en-US')} chars).`));
109
+ console.error(format_1.c.muted('That limit matches the account API — a bigger body could never sync.'));
110
+ process.exitCode = 1;
111
+ return;
112
+ }
113
+ if (!body) {
114
+ console.error(format_1.c.error('No prompt body.'));
115
+ console.error(format_1.c.muted(' ple save "code review" -m "Review this diff: {{diff}}"'));
116
+ console.error(format_1.c.muted(' pbpaste | ple save "code review"'));
117
+ process.exitCode = 1;
118
+ return;
119
+ }
120
+ const slug = store.slugify(cleanTitle);
121
+ const previous = store.read(slug);
122
+ // Overwriting someone's prompt silently is the one unrecoverable thing this
123
+ // command could do — the local store keeps no versions. Farklı başlıklar
124
+ // aynı slug'a inebilir ("a/b" ve "a:b" → "ab"); mesaj bu yüzden mevcut
125
+ // kaydın GERÇEK başlığını söyler, kullanıcının hiç yazmadığı slug'ı değil.
126
+ if (previous && !options.force) {
127
+ console.error(format_1.c.error(`'${slug}' already exists (saved as "${previous.title}").`));
128
+ console.error(format_1.c.muted('Overwrite it with --force, or pick a different title.'));
129
+ process.exitCode = 1;
130
+ return;
131
+ }
132
+ // On --force, fields the user did not re-specify are CARRIED OVER.
133
+ // Overwriting the body must not silently wipe tags and the description —
134
+ // the local store keeps no versions, so that loss is unrecoverable.
135
+ const tags = options.tag && options.tag.length > 0 ? options.tag : (previous?.tags ?? []);
136
+ const description = options.description?.trim() ?? previous?.description ?? '';
137
+ const saved = store.save({ slug, title: cleanTitle, description, tags, body });
138
+ console.log(format_1.c.success(`✓ Saved: ${saved.title}`) + format_1.c.muted(` (${saved.slug})`));
139
+ console.log(format_1.c.muted(` ${store.filePath(saved.slug)}`));
140
+ const vars = (0, promptVariables_1.extractVariables)(saved.body);
141
+ if (vars.length > 0) {
142
+ console.log(format_1.c.muted(` variables: ${vars.map((v) => `{{${v}}}`).join(', ')}`));
143
+ console.log(format_1.c.muted(` use it: ple get "${saved.slug}" --var ${vars[0]}=...`));
144
+ }
145
+ else {
146
+ console.log(format_1.c.muted(` use it: ple copy "${saved.slug}"`));
147
+ }
148
+ }
@@ -2,6 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.searchCommand = searchCommand;
4
4
  const api_client_1 = require("../lib/api-client");
5
+ const local_1 = require("./local");
5
6
  const format_1 = require("../lib/format");
6
7
  /**
7
8
  * `ple search <keyword>` — search over title + description.
@@ -17,6 +18,10 @@ async function searchCommand(keyword) {
17
18
  process.exitCode = 1;
18
19
  return;
19
20
  }
21
+ if ((0, local_1.isSignedOut)()) {
22
+ (0, local_1.localSearch)(trimmed);
23
+ return;
24
+ }
20
25
  await (0, api_client_1.ensureAuthed)();
21
26
  const rows = await (0, api_client_1.listPrompts)({ search: trimmed, limit: 30 });
22
27
  if (rows.length === 0) {
@@ -2,6 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.showCommand = showCommand;
4
4
  const api_client_1 = require("../lib/api-client");
5
+ const local_1 = require("./local");
5
6
  const promptResolver_1 = require("../lib/promptResolver");
6
7
  const format_1 = require("../lib/format");
7
8
  /**
@@ -11,6 +12,11 @@ const format_1 = require("../lib/format");
11
12
  * sections (role / description / context) under readable headers.
12
13
  */
13
14
  async function showCommand(name, options = {}) {
15
+ if ((0, local_1.isSignedOut)()) {
16
+ (0, local_1.noteIgnoredProject)(options.project);
17
+ (0, local_1.localShow)(name);
18
+ return;
19
+ }
14
20
  await (0, api_client_1.ensureAuthed)();
15
21
  const projectId = options.project ? await (0, promptResolver_1.resolveProjectId)(options.project) : undefined;
16
22
  const prompt = await (0, promptResolver_1.resolvePromptByName)(name, { projectId });
@@ -0,0 +1,130 @@
1
+ "use strict";
2
+ /**
3
+ * `ple sync` — upload the local store into the signed-in account.
4
+ *
5
+ * DELIBERATELY EXPLICIT, never automatic on login. Silently uploading files a
6
+ * developer keeps on their own machine is the kind of surprise that costs
7
+ * trust permanently, and this audience notices. So local stays local until
8
+ * someone asks for it.
9
+ *
10
+ * One-way (local → account) on purpose. Pulling the account library down would
11
+ * need conflict rules the local store cannot express — it keeps no versions —
12
+ * and a half-correct merge silently losing an edit is worse than no pull.
13
+ */
14
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
15
+ if (k2 === undefined) k2 = k;
16
+ var desc = Object.getOwnPropertyDescriptor(m, k);
17
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
18
+ desc = { enumerable: true, get: function() { return m[k]; } };
19
+ }
20
+ Object.defineProperty(o, k2, desc);
21
+ }) : (function(o, m, k, k2) {
22
+ if (k2 === undefined) k2 = k;
23
+ o[k2] = m[k];
24
+ }));
25
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
26
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
27
+ }) : function(o, v) {
28
+ o["default"] = v;
29
+ });
30
+ var __importStar = (this && this.__importStar) || (function () {
31
+ var ownKeys = function(o) {
32
+ ownKeys = Object.getOwnPropertyNames || function (o) {
33
+ var ar = [];
34
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
35
+ return ar;
36
+ };
37
+ return ownKeys(o);
38
+ };
39
+ return function (mod) {
40
+ if (mod && mod.__esModule) return mod;
41
+ var result = {};
42
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
43
+ __setModuleDefault(result, mod);
44
+ return result;
45
+ };
46
+ })();
47
+ Object.defineProperty(exports, "__esModule", { value: true });
48
+ exports.syncCommand = syncCommand;
49
+ const store = __importStar(require("../lib/localStore"));
50
+ const api_client_1 = require("../lib/api-client");
51
+ const format_1 = require("../lib/format");
52
+ /** The import endpoint caps one request at 50 records. */
53
+ const BATCH = 50;
54
+ async function syncCommand(options = {}) {
55
+ const local = store.list().filter((p) => p.body.trim());
56
+ if (local.length === 0) {
57
+ console.log(format_1.c.muted('Nothing to sync — the local store is empty.'));
58
+ console.log(format_1.c.muted(' ple save "code review" -m "Review this diff: {{diff}}"'));
59
+ return;
60
+ }
61
+ if (options.dryRun) {
62
+ console.log(format_1.c.label(`${local.length} local prompt${local.length === 1 ? '' : 's'} would be uploaded:`));
63
+ for (const p of local)
64
+ console.log(format_1.c.muted(` ${p.slug} ${p.title}`));
65
+ console.log(format_1.c.muted('\nRun `ple sync` without --dry-run to upload.'));
66
+ return;
67
+ }
68
+ await (0, api_client_1.ensureAuthed)();
69
+ const payload = local.map((p) => ({
70
+ title: p.title,
71
+ description: p.description,
72
+ content: p.body,
73
+ tags: p.tags,
74
+ }));
75
+ let imported = 0;
76
+ let failed = 0;
77
+ let skippedInvalid = 0;
78
+ let truncatedByQuota = 0;
79
+ let tagsApplied = 0;
80
+ let serverCarriesTags = true;
81
+ // Batch hatası (ör. 2. batch'te plan limiti → HTTP 429) yükseltilirse bile
82
+ // 1. batch'in SONUCU raporlanmak zorunda: "✗ limit" tek satırıyla susmak,
83
+ // yüklenmiş 50 prompt'u yok saymaktı (denetim bulgusu 2a).
84
+ let abortMessage = null;
85
+ for (let i = 0; i < payload.length; i += BATCH) {
86
+ try {
87
+ const res = await (0, api_client_1.importPrompts)(payload.slice(i, i + BATCH));
88
+ imported += res.imported;
89
+ failed += res.failed;
90
+ skippedInvalid += res.skippedInvalid;
91
+ truncatedByQuota += res.truncatedByQuota;
92
+ if (res.tagsApplied === undefined)
93
+ serverCarriesTags = false;
94
+ else
95
+ tagsApplied += res.tagsApplied;
96
+ }
97
+ catch (err) {
98
+ abortMessage = err instanceof Error ? err.message : String(err);
99
+ truncatedByQuota += payload.length - i; // bu ve sonraki batch'ler gitmedi
100
+ break;
101
+ }
102
+ }
103
+ const tagNote = serverCarriesTags && tagsApplied > 0 ? ` (+${tagsApplied} tag link${tagsApplied === 1 ? '' : 's'})` : '';
104
+ console.log(format_1.c.success(`✓ Uploaded ${imported} prompt${imported === 1 ? '' : 's'}${tagNote}`));
105
+ // Each shortfall gets its own line with its own fix — "12 of 20 synced"
106
+ // with no reason is the kind of message that sends people to support.
107
+ if (abortMessage) {
108
+ console.log(format_1.c.warn(`⚠ Stopped early: ${abortMessage}`));
109
+ }
110
+ if (truncatedByQuota > 0) {
111
+ console.log(format_1.c.warn(`⚠ ${truncatedByQuota} not uploaded — plan prompt limit reached.`));
112
+ console.log(format_1.c.muted(' Upgrade for unlimited prompts, then run `ple sync` again.'));
113
+ }
114
+ if (skippedInvalid > 0) {
115
+ console.log(format_1.c.warn(`⚠ ${skippedInvalid} skipped — missing a title or body.`));
116
+ }
117
+ if (failed > 0) {
118
+ console.log(format_1.c.warn(`⚠ ${failed} failed to import. Re-run \`ple sync\` to retry those.`));
119
+ }
120
+ // Tags travel since the server started answering with `tagsApplied`. An
121
+ // older deployment ignores the field silently — that is the one case where
122
+ // losing tags without a word would betray the "local ≠ account" promise.
123
+ if (!serverCarriesTags && local.some((p) => p.tags.length > 0)) {
124
+ console.log(format_1.c.muted('Note: tags stayed local — this server does not carry them yet.'));
125
+ }
126
+ // Local files are NOT deleted: sync copies, it does not move. Re-running
127
+ // would duplicate, so say so rather than letting someone find out.
128
+ console.log(format_1.c.muted(`\nLocal files kept in ${store.promptsDir()} (sync copies, it does not move).`));
129
+ console.log(format_1.c.muted('Re-running would upload them again — delete the local copies first if that is not what you want.'));
130
+ }
package/dist/index.js CHANGED
@@ -20,6 +20,8 @@ const search_1 = require("./commands/search");
20
20
  const get_1 = require("./commands/get");
21
21
  const improve_1 = require("./commands/improve");
22
22
  const loop_1 = require("./commands/loop");
23
+ const save_1 = require("./commands/save");
24
+ const sync_1 = require("./commands/sync");
23
25
  /** A single global try/catch — consistent error output for every command. */
24
26
  function runWithErrorHandler(fn) {
25
27
  return async (...args) => {
@@ -38,6 +40,19 @@ program
38
40
  .name(constants_1.CLI_NAME)
39
41
  .description('Terminal access to your PromptLikeEngineer prompt library')
40
42
  .version(constants_1.CLI_VERSION);
43
+ program
44
+ .command('save <title>')
45
+ .description('Save a prompt locally — no account needed')
46
+ .option('-m, --message <text>', 'Prompt body (or pipe it via stdin)')
47
+ .option('-d, --description <text>', 'Short description')
48
+ .option('-t, --tag <name>', 'Tag (repeatable)', save_1.collectTag, [])
49
+ .option('-f, --force', 'Overwrite an existing local prompt')
50
+ .action(runWithErrorHandler(save_1.saveCommand));
51
+ program
52
+ .command('sync')
53
+ .description('Upload your local prompts to your account (one-way, explicit)')
54
+ .option('--dry-run', 'List what would be uploaded, change nothing')
55
+ .action(runWithErrorHandler(sync_1.syncCommand));
41
56
  program
42
57
  .command('login')
43
58
  .description('Sign in with email + password; store the session under ~/.config/promptlike/')
@@ -87,6 +102,6 @@ program
87
102
  .action(runWithErrorHandler(loop_1.loopCommand));
88
103
  program
89
104
  .command('search <keyword>')
90
- .description('Search within title and description')
105
+ .description('Search titles and descriptions (signed out: also local prompt bodies and tags)')
91
106
  .action(runWithErrorHandler(search_1.searchCommand));
92
107
  program.parseAsync(process.argv);
@@ -17,6 +17,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
17
17
  exports.login = login;
18
18
  exports.ensureAuthed = ensureAuthed;
19
19
  exports.listPrompts = listPrompts;
20
+ exports.importPrompts = importPrompts;
20
21
  exports.listProjects = listProjects;
21
22
  exports.getPromptById = getPromptById;
22
23
  exports.recordPromptUse = recordPromptUse;
@@ -186,6 +187,27 @@ async function listPrompts(params = {}) {
186
187
  });
187
188
  return res.prompts ?? [];
188
189
  }
190
+ /**
191
+ * POST /api/prompts/import — bulk-upload prompts into the account.
192
+ *
193
+ * Used by `ple sync` to carry the local store up after someone signs in. The
194
+ * endpoint caps a request at 50 records and enforces plan limits itself, so
195
+ * the caller batches and reports whatever came back rather than assuming
196
+ * everything landed.
197
+ */
198
+ async function importPrompts(prompts) {
199
+ const res = await apiFetch('/api/prompts/import', {
200
+ method: 'POST',
201
+ body: { prompts },
202
+ });
203
+ return {
204
+ imported: res.imported ?? 0,
205
+ failed: res.failed ?? 0,
206
+ skippedInvalid: res.skippedInvalid ?? 0,
207
+ truncatedByQuota: res.truncatedByQuota ?? 0,
208
+ tagsApplied: res.tagsApplied,
209
+ };
210
+ }
189
211
  /** GET /api/projects — list the user's accessible repos (for --project resolution). */
190
212
  async function listProjects() {
191
213
  const res = await apiFetch('/api/projects', {
@@ -35,6 +35,7 @@ var __importStar = (this && this.__importStar) || (function () {
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
36
  exports.getConfigPath = getConfigPath;
37
37
  exports.readConfig = readConfig;
38
+ exports.configStatus = configStatus;
38
39
  exports.writeConfig = writeConfig;
39
40
  exports.clearConfig = clearConfig;
40
41
  exports.isTokenExpiringSoon = isTokenExpiringSoon;
@@ -66,6 +67,18 @@ function readConfig() {
66
67
  return null;
67
68
  }
68
69
  }
70
+ /**
71
+ * Three-way session state, for callers that must NOT treat "file is corrupt"
72
+ * the same as "never logged in". The read commands fall back to the local
73
+ * store when signed out; doing that silently on a truncated config file made
74
+ * a logged-in user stare at an empty local list thinking their prompts were
75
+ * gone. 'invalid' lets the router warn first.
76
+ */
77
+ function configStatus() {
78
+ if (!fs.existsSync(CONFIG_FILE))
79
+ return 'absent';
80
+ return readConfig() ? 'valid' : 'invalid';
81
+ }
69
82
  /**
70
83
  * Config'i diske yaz. Klasör yoksa oluştur, dosya izinlerini 0600 yap
71
84
  * (sadece kullanıcı okuyabilir — token sızıntısı önlemi).
@@ -23,6 +23,25 @@ function resolveEnv(key, fallback) {
23
23
  /** Base URL of the web API the CLI calls (no trailing slash). */
24
24
  exports.API_BASE_URL = resolveEnv('PROMPTLIKE_API_URL', BAKED_API_URL).replace(/\/+$/, '');
25
25
  exports.CLI_NAME = 'ple';
26
- exports.CLI_VERSION = '0.2.2';
26
+ /**
27
+ * Sürüm TEK KAYNAKTAN: package.json. Eskiden elle yazılan sabitti ve kayıyordu
28
+ * — yayınlanan 0.3.0 kendini '0.2.2' sanıyordu (`ple --version` yanlış cevap
29
+ * veriyor, destek/hata ayıklamayı yanıltıyordu). `src/lib` ve `dist/lib` aynı
30
+ * derinlikte olduğu için '../../package.json' her iki durumda da paket köküne
31
+ * denk gelir. Yol değişken üzerinden verilir ki tsc JSON'u programa dahil edip
32
+ * rootDir'i bozmasın.
33
+ */
34
+ function readVersion() {
35
+ try {
36
+ const pkgPath = '../../package.json';
37
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
38
+ const pkg = require(pkgPath);
39
+ return pkg.version ?? '0.0.0';
40
+ }
41
+ catch {
42
+ return '0.0.0';
43
+ }
44
+ }
45
+ exports.CLI_VERSION = readVersion();
27
46
  /** Web app URL — shown to the user when their prompt list is empty. */
28
47
  exports.WEB_APP_URL = 'https://promptlikeengineer.com';
@@ -0,0 +1,278 @@
1
+ "use strict";
2
+ /**
3
+ * Local-first prompt store — `~/.promptlike/prompts/*.md`.
4
+ *
5
+ * WHY THIS EXISTS: before this, every CLI command answered
6
+ * `Not logged in. Run 'ple login' first.` A person who ran `npm i -g promptlike`
7
+ * hit a wall before the tool did anything useful, so the install was a dead end.
8
+ * Competing Claude Code plugins deliver value in about five seconds with no
9
+ * account at all.
10
+ *
11
+ * So the account is no longer the door — it is the upgrade. Prompts start as
12
+ * plain files on your machine; signing in adds sync, history and the web app.
13
+ *
14
+ * FORMAT: Markdown with a small YAML-ish frontmatter block. Deliberately not
15
+ * JSON — these files are meant to be greppable, diffable and git-committable,
16
+ * which is the same promise the product makes about prompts.
17
+ *
18
+ * ---
19
+ * title: Code review
20
+ * description: Reviews a diff
21
+ * tags: review, git
22
+ * created: 2026-08-10T12:00:00.000Z
23
+ * updated: 2026-08-10T12:00:00.000Z
24
+ * ---
25
+ * <prompt body>
26
+ */
27
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
28
+ if (k2 === undefined) k2 = k;
29
+ var desc = Object.getOwnPropertyDescriptor(m, k);
30
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
31
+ desc = { enumerable: true, get: function() { return m[k]; } };
32
+ }
33
+ Object.defineProperty(o, k2, desc);
34
+ }) : (function(o, m, k, k2) {
35
+ if (k2 === undefined) k2 = k;
36
+ o[k2] = m[k];
37
+ }));
38
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
39
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
40
+ }) : function(o, v) {
41
+ o["default"] = v;
42
+ });
43
+ var __importStar = (this && this.__importStar) || (function () {
44
+ var ownKeys = function(o) {
45
+ ownKeys = Object.getOwnPropertyNames || function (o) {
46
+ var ar = [];
47
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
48
+ return ar;
49
+ };
50
+ return ownKeys(o);
51
+ };
52
+ return function (mod) {
53
+ if (mod && mod.__esModule) return mod;
54
+ var result = {};
55
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
56
+ __setModuleDefault(result, mod);
57
+ return result;
58
+ };
59
+ })();
60
+ Object.defineProperty(exports, "__esModule", { value: true });
61
+ exports.localRoot = localRoot;
62
+ exports.promptsDir = promptsDir;
63
+ exports.slugify = slugify;
64
+ exports.serialize = serialize;
65
+ exports.parse = parse;
66
+ exports.filePath = filePath;
67
+ exports.exists = exists;
68
+ exports.save = save;
69
+ exports.read = read;
70
+ exports.remove = remove;
71
+ exports.list = list;
72
+ exports.resolve = resolve;
73
+ exports.search = search;
74
+ exports.fillVariables = fillVariables;
75
+ const fs = __importStar(require("fs"));
76
+ const os = __importStar(require("os"));
77
+ const path = __importStar(require("path"));
78
+ /** Root of the local store. Overridable for tests and for people who relocate it. */
79
+ function localRoot() {
80
+ const override = process.env.PROMPTLIKE_HOME;
81
+ if (override && override.trim())
82
+ return override.trim();
83
+ return path.join(os.homedir(), '.promptlike');
84
+ }
85
+ function promptsDir() {
86
+ return path.join(localRoot(), 'prompts');
87
+ }
88
+ /**
89
+ * Turn a title into a filename-safe slug.
90
+ *
91
+ * Unicode letters are kept (`ş`, `ğ`, `é` are valid in filenames on every
92
+ * platform we support), so a Turkish title does not collapse into gibberish.
93
+ * Only path-hostile characters are removed.
94
+ */
95
+ function slugify(input) {
96
+ const cleaned = input
97
+ .toLowerCase()
98
+ .trim()
99
+ .replace(/[/\\:*?"<>|.]+/g, '') // path-hostile on macOS/Linux/Windows
100
+ .replace(/\s+/g, '-')
101
+ .replace(/-{2,}/g, '-')
102
+ .replace(/^-+|-+$/g, '');
103
+ return cleaned || 'prompt';
104
+ }
105
+ function escapeValue(v) {
106
+ // Frontmatter is one value per line; a newline would silently truncate it.
107
+ return v.replace(/\r?\n/g, ' ').trim();
108
+ }
109
+ function serialize(p) {
110
+ // Empty fields are written without a trailing space — these files are meant
111
+ // to be read and diffed by a human, and trailing whitespace shows up in diffs.
112
+ const field = (key, value) => value ? `${key}: ${value}` : `${key}:`;
113
+ const lines = [
114
+ '---',
115
+ field('title', escapeValue(p.title)),
116
+ field('description', escapeValue(p.description)),
117
+ field('tags', p.tags.map(escapeValue).filter(Boolean).join(', ')),
118
+ field('created', p.created),
119
+ field('updated', p.updated),
120
+ '---',
121
+ '',
122
+ ];
123
+ return `${lines.join('\n')}${p.body.replace(/\s+$/, '')}\n`;
124
+ }
125
+ /**
126
+ * Parse a stored file. Tolerant on purpose: a hand-edited file with a missing
127
+ * field or no frontmatter at all still loads, because these are the user's own
128
+ * files and refusing to read them would be the worst possible failure mode.
129
+ */
130
+ function parse(slug, raw) {
131
+ const fallback = {
132
+ slug,
133
+ title: slug,
134
+ description: '',
135
+ tags: [],
136
+ body: raw.trim(),
137
+ created: '',
138
+ updated: '',
139
+ };
140
+ if (!raw.startsWith('---'))
141
+ return fallback;
142
+ const end = raw.indexOf('\n---', 3);
143
+ if (end === -1)
144
+ return fallback;
145
+ const header = raw.slice(3, end);
146
+ const body = raw.slice(end + 4).replace(/^\r?\n/, '');
147
+ const field = (name) => {
148
+ // [ \t]* — ASLA \s* değil: \s satır sonunu da eşler; alan boşken
149
+ // (`description:`) bir SONRAKİ frontmatter satırını yutuyordu. 0.4.0'da
150
+ // yayınlanan veri-bozma hatası buydu: bayraksız `ple save` sonrası
151
+ // description "tags:" oluyor, tags ["created: <ts>"] oluyor; --force
152
+ // taşıması çöpü dosyaya kalıcı yazıyor, sync hesaba sızdırıyordu.
153
+ const m = header.match(new RegExp(`^${name}:[ \\t]*(.*)$`, 'm'));
154
+ return m ? m[1].trim() : '';
155
+ };
156
+ const tags = field('tags')
157
+ .split(',')
158
+ .map((t) => t.trim())
159
+ .filter(Boolean);
160
+ return {
161
+ slug,
162
+ title: field('title') || slug,
163
+ description: field('description'),
164
+ tags,
165
+ body: body.trim(),
166
+ created: field('created'),
167
+ updated: field('updated'),
168
+ };
169
+ }
170
+ function ensureDir() {
171
+ const dir = promptsDir();
172
+ if (!fs.existsSync(dir))
173
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
174
+ }
175
+ function filePath(slug) {
176
+ return path.join(promptsDir(), `${slug}.md`);
177
+ }
178
+ function exists(slug) {
179
+ return fs.existsSync(filePath(slug));
180
+ }
181
+ function save(p) {
182
+ ensureDir();
183
+ const now = new Date().toISOString();
184
+ const previous = exists(p.slug) ? read(p.slug) : null;
185
+ // Etiketler virgülde bölünür: serialize ', ' ile birleştirip parse virgülden
186
+ // böldüğü için virgül içeren tek etiket zaten round-trip edemez — sessiz
187
+ // bölünme yerine kayıtta normalize edilir.
188
+ const tags = p.tags
189
+ .flatMap((t) => t.split(','))
190
+ .map((t) => t.trim())
191
+ .filter(Boolean);
192
+ const record = {
193
+ ...p,
194
+ tags,
195
+ // Overwriting keeps the original creation time — the file has a history
196
+ // even though this store does not keep versions.
197
+ created: p.created || previous?.created || now,
198
+ updated: now,
199
+ };
200
+ fs.writeFileSync(filePath(record.slug), serialize(record), { mode: 0o600 });
201
+ return record;
202
+ }
203
+ function read(slug) {
204
+ const file = filePath(slug);
205
+ if (!fs.existsSync(file))
206
+ return null;
207
+ return parse(slug, fs.readFileSync(file, 'utf-8'));
208
+ }
209
+ function remove(slug) {
210
+ const file = filePath(slug);
211
+ if (!fs.existsSync(file))
212
+ return false;
213
+ fs.unlinkSync(file);
214
+ return true;
215
+ }
216
+ function list() {
217
+ const dir = promptsDir();
218
+ if (!fs.existsSync(dir))
219
+ return [];
220
+ return fs
221
+ .readdirSync(dir)
222
+ .filter((f) => f.endsWith('.md'))
223
+ .map((f) => {
224
+ const slug = f.slice(0, -3);
225
+ try {
226
+ return parse(slug, fs.readFileSync(path.join(dir, f), 'utf-8'));
227
+ }
228
+ catch {
229
+ return null; // unreadable file must not take down `ple list`
230
+ }
231
+ })
232
+ .filter((p) => p !== null)
233
+ .sort((a, b) => (b.updated || '').localeCompare(a.updated || ''));
234
+ }
235
+ /**
236
+ * Resolve a user-typed name to one prompt: exact slug, then exact title,
237
+ * then unique case-insensitive partial. Ambiguity is reported, never guessed.
238
+ */
239
+ function resolve(name) {
240
+ const all = list();
241
+ if (all.length === 0)
242
+ return null;
243
+ const needle = name.toLowerCase().trim();
244
+ const bySlug = all.find((p) => p.slug.toLowerCase() === needle);
245
+ if (bySlug)
246
+ return { prompt: bySlug };
247
+ const byTitle = all.filter((p) => p.title.toLowerCase() === needle);
248
+ if (byTitle.length === 1)
249
+ return { prompt: byTitle[0] };
250
+ if (byTitle.length > 1)
251
+ return { candidates: byTitle };
252
+ const partial = all.filter((p) => p.slug.toLowerCase().includes(needle) || p.title.toLowerCase().includes(needle));
253
+ if (partial.length === 1)
254
+ return { prompt: partial[0] };
255
+ if (partial.length > 1)
256
+ return { candidates: partial };
257
+ return null;
258
+ }
259
+ /** Free-text search over title, description, tags and body. */
260
+ function search(query) {
261
+ const needle = query.toLowerCase().trim();
262
+ if (!needle)
263
+ return [];
264
+ return list().filter((p) => [p.title, p.description, p.tags.join(' '), p.body].join('\n').toLowerCase().includes(needle));
265
+ }
266
+ /** Fill `{{variables}}`; report the ones left unfilled rather than shipping them. */
267
+ function fillVariables(body, values) {
268
+ const missing = new Set();
269
+ const text = body.replace(/\{\{\s*([\w.-]+)\s*\}\}/g, (match, key) => {
270
+ const value = values[key];
271
+ if (value === undefined) {
272
+ missing.add(key);
273
+ return match;
274
+ }
275
+ return value;
276
+ });
277
+ return { text, missing: [...missing] };
278
+ }
@@ -56,8 +56,9 @@ async function bearerPost(path, body) {
56
56
  if (res.status === 403)
57
57
  throw new Error(proMessage(parsed.error));
58
58
  if (res.status === 402) {
59
- const base = parsed.error?.trim() || 'You are out of AI tokens';
60
- throw new Error(`${base} — top up or wait for your monthly reset: ${constants_1.API_BASE_URL}/settings`);
59
+ // Satış anı, hata anı değil: MicroBoost adıyla ve fiyatıyla anılır.
60
+ const base = parsed.error?.trim() || "You've used this month's AI tokens";
61
+ throw new Error(`${base}\n Top up: $3 MicroBoost (600K tokens) → ${constants_1.API_BASE_URL}/dashboard/settings`);
61
62
  }
62
63
  if (res.status === 429) {
63
64
  const retryAfter = res.headers.get('retry-after');
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "promptlike",
3
- "version": "0.3.0",
3
+ "version": "0.4.1",
4
4
  "description": "Terminal access to your PromptLikeEngineer prompt library - search, read, and copy your saved prompts without leaving the shell.",
5
5
  "bin": {
6
6
  "ple": "dist/index.js"
@@ -9,6 +9,7 @@
9
9
  "files": [
10
10
  "dist",
11
11
  "README.md",
12
+ "CHANGELOG.md",
12
13
  "LICENSE"
13
14
  ],
14
15
  "scripts": {