promptlike 0.7.0 → 0.9.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.
@@ -40,32 +40,54 @@ exports.writeConfig = writeConfig;
40
40
  exports.clearConfig = clearConfig;
41
41
  exports.isTokenExpiringSoon = isTokenExpiringSoon;
42
42
  const fs = __importStar(require("fs"));
43
- const os = __importStar(require("os"));
44
43
  const path = __importStar(require("path"));
45
- const CONFIG_DIR = path.join(os.homedir(), '.config', 'promptlike');
46
- const CONFIG_FILE = path.join(CONFIG_DIR, 'config.json');
44
+ const fsSafe_1 = require("./fsSafe");
45
+ const settings_1 = require("./settings");
46
+ /**
47
+ * Resolved lazily (not at import) so `PROMPTLIKE_CONFIG_DIR` can redirect the
48
+ * session file — the tests rely on it, and so can people who keep their dotfiles
49
+ * elsewhere. Same directory as settings.json and the library cache.
50
+ */
51
+ function configFile() {
52
+ return path.join((0, settings_1.configDir)(), 'config.json');
53
+ }
47
54
  /** Config dosyasının tam yolu — debug çıktılarında göstermek için. */
48
55
  function getConfigPath() {
49
- return CONFIG_FILE;
56
+ return configFile();
50
57
  }
51
- /**
52
- * Config'i diskten oku. Yoksa null döner — login gerekli demektir.
53
- * Bozuk JSON varsa null döner ve dosyayı silmiyoruz; kullanıcı `ple logout`
54
- * çağırsın diye log'ı sessiz tutuyoruz.
55
- */
56
- function readConfig() {
58
+ /** Parse + shape-check the session file. Anything unexpected → null (never throws). */
59
+ function parseConfig(raw) {
60
+ let parsed;
57
61
  try {
58
- if (!fs.existsSync(CONFIG_FILE))
59
- return null;
60
- const raw = fs.readFileSync(CONFIG_FILE, 'utf-8');
61
- const parsed = JSON.parse(raw);
62
- if (!parsed.access_token || !parsed.refresh_token)
63
- return null;
64
- return parsed;
62
+ parsed = JSON.parse(raw);
65
63
  }
66
64
  catch {
67
65
  return null;
68
66
  }
67
+ if (typeof parsed !== 'object' || parsed === null)
68
+ return null;
69
+ const o = parsed;
70
+ if (typeof o.access_token !== 'string' || !o.access_token)
71
+ return null;
72
+ if (typeof o.refresh_token !== 'string' || !o.refresh_token)
73
+ return null;
74
+ return {
75
+ access_token: o.access_token,
76
+ refresh_token: o.refresh_token,
77
+ email: typeof o.email === 'string' ? o.email : '',
78
+ user_id: typeof o.user_id === 'string' ? o.user_id : '',
79
+ expires_at: typeof o.expires_at === 'number' && Number.isFinite(o.expires_at) ? o.expires_at : 0,
80
+ };
81
+ }
82
+ /**
83
+ * Config'i diskten oku. Yoksa null döner — login gerekli demektir.
84
+ * Bozuk JSON, symlink ya da düzenli olmayan dosya varsa null döner ve dosyaya
85
+ * dokunulmaz; kullanıcı `ple logout` çağırsın diye log'ı sessiz tutuyoruz.
86
+ * Grup/dünya erişimi açık bir dosya okunurken 0600'e sıkılaştırılır.
87
+ */
88
+ function readConfig() {
89
+ const raw = (0, fsSafe_1.readPrivateFile)(configFile());
90
+ return raw === null ? null : parseConfig(raw);
69
91
  }
70
92
  /**
71
93
  * Three-way session state, for callers that must NOT treat "file is corrupt"
@@ -75,27 +97,28 @@ function readConfig() {
75
97
  * gone. 'invalid' lets the router warn first.
76
98
  */
77
99
  function configStatus() {
78
- if (!fs.existsSync(CONFIG_FILE))
100
+ if (!(0, fsSafe_1.pathExists)(configFile()))
79
101
  return 'absent';
80
102
  return readConfig() ? 'valid' : 'invalid';
81
103
  }
82
104
  /**
83
- * Config'i diske yaz. Klasör yoksa oluştur, dosya izinlerini 0600 yap
84
- * (sadece kullanıcı okuyabilir — token sızıntısı önlemi).
105
+ * Config'i diske yaz: atomik (geçici dosya + rename), 0600, klasör 0700.
106
+ * Hedefte bir symlink varsa onun üzerinden YAZILMAZ — link rename ile değiştirilir.
85
107
  */
86
108
  function writeConfig(config) {
87
- if (!fs.existsSync(CONFIG_DIR)) {
88
- fs.mkdirSync(CONFIG_DIR, { recursive: true, mode: 0o700 });
89
- }
90
- fs.writeFileSync(CONFIG_FILE, JSON.stringify(config, null, 2), {
91
- mode: 0o600,
92
- });
109
+ (0, fsSafe_1.writePrivateFile)(configFile(), JSON.stringify(config, null, 2));
93
110
  }
94
- /** `ple logout` için: config dosyasını ve klasörünü sil. */
111
+ /**
112
+ * `ple logout` için: oturum dosyasını sil. Bozuk ya da symlink olsa bile silinir
113
+ * (symlink'te yalnız bağlantının kendisi; hedefe dokunulmaz). Silinen bir şey
114
+ * varsa true döner.
115
+ */
95
116
  function clearConfig() {
96
- if (fs.existsSync(CONFIG_FILE)) {
97
- fs.unlinkSync(CONFIG_FILE);
98
- }
117
+ const file = configFile();
118
+ if (!(0, fsSafe_1.pathExists)(file))
119
+ return false;
120
+ fs.unlinkSync(file);
121
+ return true;
99
122
  }
100
123
  /** Token'ın 60 saniye içinde sona erecek olup olmadığını kontrol et. */
101
124
  function isTokenExpiringSoon(config) {
@@ -0,0 +1,53 @@
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.confirm = confirm;
37
+ const readline = __importStar(require("readline"));
38
+ /**
39
+ * Ask a yes/no question on the terminal. Only `y` / `yes` count as yes; Enter,
40
+ * anything else and Ctrl-D are no. Callers decide what a non-interactive run does
41
+ * (scripts must pass `--yes`) before calling this.
42
+ */
43
+ function confirm(question) {
44
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
45
+ return new Promise((resolve) => {
46
+ rl.once('close', () => resolve(false));
47
+ rl.question(question, (answer) => {
48
+ rl.removeAllListeners('close');
49
+ rl.close();
50
+ resolve(/^y(es)?$/i.test(answer.trim()));
51
+ });
52
+ });
53
+ }
@@ -11,8 +11,45 @@
11
11
  * 2. `BAKED_API_URL` below — the public production URL.
12
12
  */
13
13
  Object.defineProperty(exports, "__esModule", { value: true });
14
- exports.WEB_APP_URL = exports.CLI_VERSION = exports.CLI_NAME = exports.API_BASE_URL = void 0;
14
+ exports.WEB_APP_URL = exports.CLI_VERSION = exports.CLI_NAME = exports.API_BASE_URL = exports.API_BASE_URL_ERROR = void 0;
15
+ exports.validateApiBaseUrl = validateApiBaseUrl;
15
16
  const BAKED_API_URL = 'https://promptlikeengineer.com';
17
+ /** Hosts for which plain http is allowed (local development only). */
18
+ const LOOPBACK_HOSTS = new Set(['localhost', '127.0.0.1', '[::1]']);
19
+ /**
20
+ * Validate an API base URL before ANY request is built from it. The CLI sends a
21
+ * bearer token and a refresh token to this origin, so a typo or a hostile
22
+ * `PROMPTLIKE_API_URL` must not turn into a plaintext token leak.
23
+ *
24
+ * - https is required; http is accepted ONLY for localhost / 127.0.0.1 / [::1].
25
+ * - No credentials in the URL (`https://user:pw@host`), no query or fragment.
26
+ * - Only the origin plus an optional path prefix is kept (trailing slashes dropped).
27
+ *
28
+ * Returns the cleaned URL, or an error message that says how to fix it.
29
+ */
30
+ function validateApiBaseUrl(raw) {
31
+ let u;
32
+ try {
33
+ u = new URL(raw);
34
+ }
35
+ catch {
36
+ return { error: `PROMPTLIKE_API_URL is not a valid URL: '${raw}'. Example: https://promptlikeengineer.com` };
37
+ }
38
+ const loopback = LOOPBACK_HOSTS.has(u.hostname);
39
+ if (u.protocol !== 'https:' && !(u.protocol === 'http:' && loopback)) {
40
+ return {
41
+ error: `PROMPTLIKE_API_URL must use https (plain http is allowed only for localhost): '${raw}'. ` +
42
+ 'Your login token would otherwise travel unencrypted.',
43
+ };
44
+ }
45
+ if (u.username || u.password) {
46
+ return { error: 'PROMPTLIKE_API_URL must not contain a username or password.' };
47
+ }
48
+ if (u.search || u.hash) {
49
+ return { error: 'PROMPTLIKE_API_URL must not contain a query string or fragment.' };
50
+ }
51
+ return { url: (u.origin + u.pathname).replace(/\/+$/, '') };
52
+ }
16
53
  function resolveEnv(key, fallback) {
17
54
  const value = process.env[key];
18
55
  if (typeof value === 'string' && value.trim().length > 0) {
@@ -20,8 +57,16 @@ function resolveEnv(key, fallback) {
20
57
  }
21
58
  return fallback;
22
59
  }
60
+ const resolvedApi = validateApiBaseUrl(resolveEnv('PROMPTLIKE_API_URL', BAKED_API_URL));
61
+ /**
62
+ * Set when `PROMPTLIKE_API_URL` is unusable. The API client throws it before it
63
+ * builds a request, so nothing — least of all a token — is ever sent to a URL
64
+ * that failed validation. (Not thrown here: an import-time crash would print a
65
+ * stack trace and break `--help`/`--version` and the offline commands.)
66
+ */
67
+ exports.API_BASE_URL_ERROR = 'error' in resolvedApi ? resolvedApi.error : null;
23
68
  /** Base URL of the web API the CLI calls (no trailing slash). */
24
- exports.API_BASE_URL = resolveEnv('PROMPTLIKE_API_URL', BAKED_API_URL).replace(/\/+$/, '');
69
+ exports.API_BASE_URL = 'url' in resolvedApi ? resolvedApi.url : BAKED_API_URL;
25
70
  exports.CLI_NAME = 'ple';
26
71
  /**
27
72
  * Sürüm TEK KAYNAKTAN: package.json. Eskiden elle yazılan sabitti ve kayıyordu
@@ -0,0 +1,17 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.exitCodeFor = exitCodeFor;
4
+ /**
5
+ * Exit codes — one place, documented in the README:
6
+ * 0 success
7
+ * 1 you can fix it: bad input, not signed in, not found, not allowed, plan limit, conflict
8
+ * 2 not your fault / try again: no network, timeout, rate limit, server error (5xx)
9
+ */
10
+ const api_client_1 = require("./api-client");
11
+ function exitCodeFor(err) {
12
+ if (err instanceof api_client_1.NetworkError || err instanceof api_client_1.RequestTimeoutError)
13
+ return 2;
14
+ if (err instanceof api_client_1.ApiError && (err.status >= 500 || err.status === 429))
15
+ return 2;
16
+ return 1;
17
+ }
@@ -8,6 +8,7 @@ exports.timeAgo = timeAgo;
8
8
  exports.shortId = shortId;
9
9
  exports.truncate = truncate;
10
10
  exports.joinPromptParts = joinPromptParts;
11
+ exports.safeText = safeText;
11
12
  const chalk_1 = __importDefault(require("chalk"));
12
13
  /**
13
14
  * Tutarlı renk paleti — komutlar arasında aynı vurguları kullanmak için.
@@ -70,3 +71,18 @@ function joinPromptParts(parts) {
70
71
  return segments.join('\n\n---\n\n');
71
72
  return parts.content && parts.content.trim() ? parts.content.trim() : '';
72
73
  }
74
+ /**
75
+ * Make server- or file-provided text safe to print on a terminal. A title such
76
+ * as "\u001b]0;pwned\u0007" or "\u001b[2J" would otherwise be interpreted by the
77
+ * terminal (retitle the window, clear the screen, hide earlier output). ANSI
78
+ * escape sequences and control characters are removed; with `keepNewlines`
79
+ * line breaks and tabs survive (for multi-line bodies).
80
+ */
81
+ function safeText(input, keepNewlines = false) {
82
+ const noAnsi = input
83
+ // OSC (… BEL | ST), CSI (… final byte), and any other lone ESC sequence
84
+ .replace(/\u001b\][^\u0007\u001b]*(?:\u0007|\u001b\\)?/g, '')
85
+ .replace(/\u001b\[[0-?]*[ -/]*[@-~]/g, '')
86
+ .replace(/\u001b[@-~]?/g, '');
87
+ return noAnsi.replace(/[\u0000-\u001f\u007f-\u009f]/g, (ch) => (keepNewlines && (ch === '\n' || ch === '\t') ? ch : ''));
88
+ }
@@ -0,0 +1,171 @@
1
+ "use strict";
2
+ /**
3
+ * Safe file helpers for everything the CLI keeps on disk (session, settings,
4
+ * cache, local prompts, history, exports).
5
+ *
6
+ * Threats covered (each has a test in fsSafe.test.ts):
7
+ * - SYMLINK: a link planted at the target path (e.g. `config.json -> ~/.bashrc`)
8
+ * must never make the CLI write through it. Writes go to a fresh temp file
9
+ * that is `rename`d over the target; rename replaces the link itself and
10
+ * never follows it.
11
+ * - LOOSE PERMISSIONS: `mkdir`/`writeFile` modes only apply on creation. A
12
+ * directory or file that already exists with group/world access is tightened
13
+ * to 0700 / 0600 on the next write.
14
+ * - TORN WRITES: a crash mid-write must not leave a half token file (the temp
15
+ * file is only renamed once fully written).
16
+ *
17
+ * POSIX permission bits do not exist on Windows; chmod there is a no-op and the
18
+ * checks are skipped (the per-user profile ACLs apply instead).
19
+ */
20
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
21
+ if (k2 === undefined) k2 = k;
22
+ var desc = Object.getOwnPropertyDescriptor(m, k);
23
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
24
+ desc = { enumerable: true, get: function() { return m[k]; } };
25
+ }
26
+ Object.defineProperty(o, k2, desc);
27
+ }) : (function(o, m, k, k2) {
28
+ if (k2 === undefined) k2 = k;
29
+ o[k2] = m[k];
30
+ }));
31
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
32
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
33
+ }) : function(o, v) {
34
+ o["default"] = v;
35
+ });
36
+ var __importStar = (this && this.__importStar) || (function () {
37
+ var ownKeys = function(o) {
38
+ ownKeys = Object.getOwnPropertyNames || function (o) {
39
+ var ar = [];
40
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
41
+ return ar;
42
+ };
43
+ return ownKeys(o);
44
+ };
45
+ return function (mod) {
46
+ if (mod && mod.__esModule) return mod;
47
+ var result = {};
48
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
49
+ __setModuleDefault(result, mod);
50
+ return result;
51
+ };
52
+ })();
53
+ Object.defineProperty(exports, "__esModule", { value: true });
54
+ exports.isSymlink = isSymlink;
55
+ exports.pathExists = pathExists;
56
+ exports.ensurePrivateDir = ensurePrivateDir;
57
+ exports.writePrivateFile = writePrivateFile;
58
+ exports.createPrivateFileExclusive = createPrivateFileExclusive;
59
+ exports.readPrivateFile = readPrivateFile;
60
+ exports.assertNotSymlink = assertNotSymlink;
61
+ const fs = __importStar(require("fs"));
62
+ const path = __importStar(require("path"));
63
+ const IS_WINDOWS = process.platform === 'win32';
64
+ /** True when `p` exists and is itself a symbolic link (does not follow it). */
65
+ function isSymlink(p) {
66
+ try {
67
+ return fs.lstatSync(p).isSymbolicLink();
68
+ }
69
+ catch {
70
+ return false;
71
+ }
72
+ }
73
+ /** True when anything (file, dir, link — even a dangling link) exists at `p`. */
74
+ function pathExists(p) {
75
+ try {
76
+ fs.lstatSync(p);
77
+ return true;
78
+ }
79
+ catch {
80
+ return false;
81
+ }
82
+ }
83
+ /**
84
+ * Create `dir` (and parents) with mode 0700, and tighten it when it already
85
+ * exists with group/world bits. Only the LEAF directory is tightened — parents
86
+ * such as `~/.config` belong to the user and other tools.
87
+ */
88
+ function ensurePrivateDir(dir) {
89
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
90
+ if (IS_WINDOWS)
91
+ return;
92
+ try {
93
+ const st = fs.statSync(dir);
94
+ if (st.isDirectory() && (st.mode & 0o077) !== 0)
95
+ fs.chmodSync(dir, 0o700);
96
+ }
97
+ catch {
98
+ /* a directory we cannot stat is reported by the write that follows */
99
+ }
100
+ }
101
+ /**
102
+ * Write `data` to `file` atomically with mode 0600 (replaces an existing file
103
+ * or symlink; never writes through a link). The parent directory is created
104
+ * 0700 and tightened if needed.
105
+ */
106
+ function writePrivateFile(file, data) {
107
+ ensurePrivateDir(path.dirname(file));
108
+ const tmp = `${file}.${process.pid}.${Date.now()}.tmp`;
109
+ // 'wx' = create exclusively, so an attacker-planted file or link at the temp
110
+ // name makes the write fail instead of being followed.
111
+ fs.writeFileSync(tmp, data, { mode: 0o600, flag: 'wx' });
112
+ try {
113
+ fs.renameSync(tmp, file);
114
+ }
115
+ catch (err) {
116
+ try {
117
+ fs.unlinkSync(tmp);
118
+ }
119
+ catch {
120
+ /* best effort */
121
+ }
122
+ throw err;
123
+ }
124
+ }
125
+ /**
126
+ * Create `file` with mode 0600 only if it does not exist; fails with EEXIST
127
+ * otherwise, and never follows a link (O_EXCL). Used for append-only history.
128
+ */
129
+ function createPrivateFileExclusive(file, data) {
130
+ ensurePrivateDir(path.dirname(file));
131
+ fs.writeFileSync(file, data, { flag: 'wx', mode: 0o600 });
132
+ }
133
+ /**
134
+ * Read a private file without following a symlink at the final path component.
135
+ * Returns null when the file is missing, is a link, or is not a regular file.
136
+ * A regular file that is group/world accessible is tightened to 0600.
137
+ */
138
+ function readPrivateFile(file) {
139
+ let st;
140
+ try {
141
+ st = fs.lstatSync(file);
142
+ }
143
+ catch {
144
+ return null;
145
+ }
146
+ if (st.isSymbolicLink() || !st.isFile())
147
+ return null;
148
+ if (!IS_WINDOWS && (st.mode & 0o077) !== 0) {
149
+ try {
150
+ fs.chmodSync(file, 0o600);
151
+ }
152
+ catch {
153
+ /* read-only filesystem: still readable */
154
+ }
155
+ }
156
+ try {
157
+ return fs.readFileSync(file, 'utf-8');
158
+ }
159
+ catch {
160
+ return null;
161
+ }
162
+ }
163
+ /**
164
+ * Refuse to write an export over a symlink. `existsSync` follows links, so a
165
+ * dangling link looked like "nothing there" and the write created its target.
166
+ */
167
+ function assertNotSymlink(target) {
168
+ if (isSymlink(target)) {
169
+ throw new Error(`${target} is a symbolic link — refusing to write through it. Remove the link or choose another path.`);
170
+ }
171
+ }
@@ -69,6 +69,7 @@ const path = __importStar(require("path"));
69
69
  const format_1 = require("./format");
70
70
  const rank_1 = require("./rank");
71
71
  const settings_1 = require("./settings");
72
+ const fsSafe_1 = require("./fsSafe");
72
73
  exports.CACHE_TTL_MS = 10 * 60 * 1000;
73
74
  /** Background refreshes are at most one per minute (lock file mtime). */
74
75
  const REFRESH_LOCK_MS = 60 * 1000;
@@ -83,11 +84,9 @@ function cacheFile() {
83
84
  return path.join(cacheDir(), 'library.json');
84
85
  }
85
86
  function writePrivate(file, data) {
86
- fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
87
- // Write-then-rename: a hook reading mid-write never sees half a file.
88
- const tmp = `${file}.${process.pid}.tmp`;
89
- fs.writeFileSync(tmp, JSON.stringify(data), { mode: 0o600 });
90
- fs.renameSync(tmp, file);
87
+ // Atomic (temp + rename): a hook reading mid-write never sees half a file,
88
+ // and a symlink planted at `file` is replaced, never written through.
89
+ (0, fsSafe_1.writePrivateFile)(file, JSON.stringify(data));
91
90
  }
92
91
  /** Cached library for `userId`, or null (missing, corrupt, or another account's). */
93
92
  function readCache(userId) {
@@ -171,8 +170,8 @@ function startBackgroundRefresh(opts = {}) {
171
170
  }
172
171
  }
173
172
  try {
174
- fs.mkdirSync(cacheDir(), { recursive: true, mode: 0o700 });
175
- fs.writeFileSync(lock, String(now), { mode: 0o600 });
173
+ (0, fsSafe_1.ensurePrivateDir)(cacheDir());
174
+ (0, fsSafe_1.writePrivateFile)(lock, String(now));
176
175
  (opts.spawner ?? defaultSpawner)(process.execPath, [script, 'suggest', '--refresh-cache']);
177
176
  return true;
178
177
  }
@@ -59,6 +59,7 @@ exports.findVersion = findVersion;
59
59
  const fs = __importStar(require("fs"));
60
60
  const path = __importStar(require("path"));
61
61
  const store = __importStar(require("./localStore"));
62
+ const fsSafe_1 = require("./fsSafe");
62
63
  function historyRoot() {
63
64
  return path.join(store.localRoot(), 'history');
64
65
  }
@@ -111,7 +112,7 @@ function latestVersion(slug) {
111
112
  /** Append one version. Never overwrites: on a number clash it takes the next one. */
112
113
  function append(slug, snap, note) {
113
114
  const dir = historyDir(slug);
114
- fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
115
+ (0, fsSafe_1.ensurePrivateDir)(dir);
115
116
  const saved = new Date().toISOString();
116
117
  const base = store.serialize({ slug, ...snap, created: saved, updated: saved });
117
118
  const extra = [`version: __N__`, `saved: ${saved}`, ...(note ? [`note: ${oneLine(note)}`] : [])];
@@ -119,7 +120,7 @@ function append(slug, snap, note) {
119
120
  for (;;) {
120
121
  const text = base.replace(/^---\n/, `---\n${extra.join('\n').replace('__N__', String(n))}\n`);
121
122
  try {
122
- fs.writeFileSync(versionFile(slug, n), text, { flag: 'wx', mode: 0o600 });
123
+ (0, fsSafe_1.createPrivateFileExclusive)(versionFile(slug, n), text);
123
124
  return parseVersion(n, text, slug);
124
125
  }
125
126
  catch (err) {
@@ -75,6 +75,8 @@ exports.fillVariables = fillVariables;
75
75
  const fs = __importStar(require("fs"));
76
76
  const os = __importStar(require("os"));
77
77
  const path = __importStar(require("path"));
78
+ const fsSafe_1 = require("./fsSafe");
79
+ const promptTemplate_1 = require("./promptTemplate");
78
80
  /** Root of the local store. Overridable for tests and for people who relocate it. */
79
81
  function localRoot() {
80
82
  const override = process.env.PROMPTLIKE_HOME;
@@ -168,9 +170,7 @@ function parse(slug, raw) {
168
170
  };
169
171
  }
170
172
  function ensureDir() {
171
- const dir = promptsDir();
172
- if (!fs.existsSync(dir))
173
- fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
173
+ (0, fsSafe_1.ensurePrivateDir)(promptsDir());
174
174
  }
175
175
  function filePath(slug) {
176
176
  return path.join(promptsDir(), `${slug}.md`);
@@ -197,7 +197,8 @@ function save(p) {
197
197
  created: p.created || previous?.created || now,
198
198
  updated: now,
199
199
  };
200
- fs.writeFileSync(filePath(record.slug), serialize(record), { mode: 0o600 });
200
+ // Atomic + 0600; a symlink at the target is replaced, never written through.
201
+ (0, fsSafe_1.writePrivateFile)(filePath(record.slug), serialize(record));
201
202
  return record;
202
203
  }
203
204
  function read(slug) {
@@ -265,14 +266,6 @@ function search(query) {
265
266
  }
266
267
  /** Fill `{{variables}}`; report the ones left unfilled rather than shipping them. */
267
268
  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] };
269
+ const text = (0, promptTemplate_1.fillVariables)(body, values);
270
+ return { text, missing: (0, promptTemplate_1.extractVariables)(text) };
278
271
  }
@@ -28,7 +28,17 @@ async function resolveProjectId(value) {
28
28
  if (matches.length === 1)
29
29
  return matches[0].id;
30
30
  if (matches.length === 0) {
31
- throw new Error(`No repo matched '${trimmed}'. Run 'ple list' or use the repo's exact name, slug, or id.`);
31
+ // Same short id `ple repo list` prints (8+ hex characters).
32
+ if (SHORT_ID_RE.test(trimmed)) {
33
+ const byPrefix = projects.filter((p) => p.id.toLowerCase().startsWith(lower));
34
+ if (byPrefix.length === 1)
35
+ return byPrefix[0].id;
36
+ if (byPrefix.length > 1) {
37
+ const hint = byPrefix.map((p) => `${(0, format_1.shortId)(p.id)} ${p.name}`).join(', ');
38
+ throw new Error(`'${trimmed}' matched multiple repos (${hint}). Use the full repo id.`);
39
+ }
40
+ }
41
+ throw new Error(`No repo matched '${trimmed}'. Run 'ple repo list' and use the repo's exact name, slug, or id.`);
32
42
  }
33
43
  // Multiple repos share this name — ask for the id.
34
44
  const hint = matches.map((p) => `${(0, format_1.shortId)(p.id)} ${p.name}`).join(', ');