promptlike 0.4.1 → 0.6.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,378 @@
1
+ "use strict";
2
+ /**
3
+ * Agent formatlarına dışa aktarma — AGENTS.md bölümü + Agent Skills (SKILL.md) + zip.
4
+ *
5
+ * ⚠️ İKİ KOPYA, BİREBİR AYNI: web `src/lib/export/agent-export.ts` ve CLI
6
+ * `cli/src/lib/agentExport.ts`. CLI ayrı npm paketi, web'den import edemez
7
+ * (emsal: promptVariables). `agent-export.sync.test.ts` iki dosyanın byte-byte
8
+ * aynı olduğunu doğrular — birini değiştirince diğerine kopyala.
9
+ * Bu yüzden dosya HİÇBİR ŞEY import etmez ve DOM/Node API'sine dayanmaz.
10
+ *
11
+ * Format kaynakları (2026-09-27 doğrulandı):
12
+ * - Agent Skills spec (agentskills.io/specification) + Anthropic docs
13
+ * (platform.claude.com/docs/en/agents-and-tools/agent-skills/overview):
14
+ * `name` 1-64, [a-z0-9-], baş/son tire yok, `--` yok, klasör adıyla aynı,
15
+ * "anthropic"/"claude" içeremez, XML etiketi yok. `description` 1-1024,
16
+ * ne yaptığını + NE ZAMAN kullanılacağını söyler, `<`/`>` yok (Anthropic
17
+ * skill-creator quick_validate.py). İzinli frontmatter: name, description,
18
+ * license, compatibility, metadata (string→string), allowed-tools.
19
+ * - claude.ai yükleme: zip'in kökünde skill KLASÖRÜ olmalı
20
+ * (`my-skill.zip └── my-skill/SKILL.md`), dosyalar doğrudan kökte değil.
21
+ * - AGENTS.md (agents.md): serbest Markdown, zorunlu alan yok → prompt başına
22
+ * bir `##` bölümü; gövdedeki başlıklar bir seviye aşağı itilir.
23
+ */
24
+ Object.defineProperty(exports, "__esModule", { value: true });
25
+ exports.AGENT_EXPORT_FORMATS = void 0;
26
+ exports.toSkillName = toSkillName;
27
+ exports.listVariables = listVariables;
28
+ exports.demoteHeadings = demoteHeadings;
29
+ exports.composePromptMarkdown = composePromptMarkdown;
30
+ exports.buildAgentsMdSection = buildAgentsMdSection;
31
+ exports.buildAgentsMdDocument = buildAgentsMdDocument;
32
+ exports.buildSkillDescription = buildSkillDescription;
33
+ exports.buildPromptSkill = buildPromptSkill;
34
+ exports.buildProjectSkill = buildProjectSkill;
35
+ exports.createZip = createZip;
36
+ exports.AGENT_EXPORT_FORMATS = ['agents-md', 'skill'];
37
+ const SKILL_NAME_MAX = 64;
38
+ const SKILL_DESCRIPTION_MAX = 1024;
39
+ const RESERVED_WORDS = ['anthropic', 'claude'];
40
+ const SOURCE = 'promptlikeengineer.com';
41
+ const TURKISH_MAP = {
42
+ ı: 'i', İ: 'i', ş: 's', Ş: 's', ğ: 'g', Ğ: 'g', ü: 'u', Ü: 'u', ö: 'o', Ö: 'o', ç: 'c', Ç: 'c',
43
+ };
44
+ // ---------------------------------------------------------------------------
45
+ // Metin yardımcıları
46
+ // ---------------------------------------------------------------------------
47
+ function toAsciiSlug(input) {
48
+ return input
49
+ .replace(/[ıİşŞğĞüÜöÖçÇ]/g, (ch) => TURKISH_MAP[ch] ?? ch)
50
+ .normalize('NFKD')
51
+ .replace(/[̀-ͯ]/g, '')
52
+ .toLowerCase()
53
+ .replace(/[^a-z0-9]+/g, '-')
54
+ .replace(/^-+|-+$/g, '');
55
+ }
56
+ /**
57
+ * Başlığı spec-uyumlu skill adına çevirir. Rezerve kelimeler ("claude",
58
+ * "anthropic") çıkarılır — Anthropic yüklemesi bunları reddeder.
59
+ */
60
+ function toSkillName(title, fallback = 'prompt') {
61
+ let slug = toAsciiSlug(title);
62
+ for (const word of RESERVED_WORDS)
63
+ slug = slug.split(word).join('-');
64
+ slug = slug.replace(/-{2,}/g, '-').replace(/^-+|-+$/g, '');
65
+ if (slug.length > SKILL_NAME_MAX)
66
+ slug = slug.slice(0, SKILL_NAME_MAX).replace(/-+$/g, '');
67
+ return slug || fallback;
68
+ }
69
+ /** `<`/`>` ve satır sonlarını temizler (frontmatter tek satır kalsın). */
70
+ function sanitizeInline(text) {
71
+ return text.replace(/[<>]/g, '').replace(/\s+/g, ' ').trim();
72
+ }
73
+ function truncate(text, max) {
74
+ if (text.length <= max)
75
+ return text;
76
+ return `${text.slice(0, max - 1).trimEnd()}…`;
77
+ }
78
+ /** YAML çift tırnaklı skaler — ters bölü ve tırnak kaçışlı. */
79
+ function yamlString(value) {
80
+ return `"${value.replace(/\\/g, '\\\\').replace(/"/g, '\\"')}"`;
81
+ }
82
+ /** Metindeki benzersiz {{değişken}} adları (promptVariables ile aynı desen). */
83
+ function listVariables(text) {
84
+ const seen = new Set();
85
+ for (const m of text.matchAll(/\{\{\s*([\p{L}\p{N}_.-]+)\s*\}\}/gu))
86
+ seen.add(m[1]);
87
+ return [...seen];
88
+ }
89
+ /**
90
+ * Markdown başlıklarını `levels` kadar aşağı iter (fenced code içini atlar,
91
+ * en fazla h6). AGENTS.md'de prompt başlığı `##` olduğu için gövde `###`'ten başlar.
92
+ */
93
+ function demoteHeadings(markdown, levels) {
94
+ let inFence = false;
95
+ return markdown
96
+ .split('\n')
97
+ .map((line) => {
98
+ if (/^\s*(```|~~~)/.test(line)) {
99
+ inFence = !inFence;
100
+ return line;
101
+ }
102
+ if (inFence)
103
+ return line;
104
+ const m = /^(#{1,6})(\s.*)$/.exec(line);
105
+ if (!m)
106
+ return line;
107
+ return `${'#'.repeat(Math.min(6, m[1].length + levels))}${m[2]}`;
108
+ })
109
+ .join('\n');
110
+ }
111
+ /**
112
+ * Yapısal parçalardan Markdown gövde — web `composeMarkdown` ile aynı düzen
113
+ * (## Role / ## Context / ## Instructions). Parçalar boşsa legacy `content`.
114
+ */
115
+ function composePromptMarkdown(parts) {
116
+ const blocks = [];
117
+ if (parts.role?.trim())
118
+ blocks.push(`## Role\n\n${parts.role.trim()}`);
119
+ if (parts.context?.trim())
120
+ blocks.push(`## Context\n\n${parts.context.trim()}`);
121
+ const desc = parts.description?.trim();
122
+ if (desc)
123
+ blocks.push(desc.startsWith('#') ? desc : `## Instructions\n\n${desc}`);
124
+ if (blocks.length > 0)
125
+ return blocks.join('\n\n');
126
+ return parts.content?.trim() ?? '';
127
+ }
128
+ // ---------------------------------------------------------------------------
129
+ // AGENTS.md
130
+ // ---------------------------------------------------------------------------
131
+ function provenance(p, exportedAt) {
132
+ const parts = [SOURCE];
133
+ if (p.projectName)
134
+ parts.push(`repo: ${p.projectName}`);
135
+ if (p.version != null)
136
+ parts.push(`v${p.version}`);
137
+ parts.push(`exported ${exportedAt.slice(0, 10)}`);
138
+ return `<!-- ${parts.join(' · ').replace(/--/g, '-')} -->`;
139
+ }
140
+ /** Tek prompt → mevcut bir AGENTS.md'ye yapıştırılacak `##` bölümü. */
141
+ function buildAgentsMdSection(p, exportedAt) {
142
+ const lines = [`## ${sanitizeInline(p.title) || 'Untitled prompt'}`, '', provenance(p, exportedAt), ''];
143
+ const desc = sanitizeInline(p.description ?? '');
144
+ if (desc)
145
+ lines.push(`> ${desc}`, '');
146
+ const vars = listVariables(p.body);
147
+ if (vars.length > 0) {
148
+ lines.push(`Placeholders to fill before use: ${vars.map((v) => `\`{{${v}}}\``).join(', ')}.`, '');
149
+ }
150
+ lines.push(demoteHeadings(p.body.trim(), 1));
151
+ return `${lines.join('\n').trimEnd()}\n`;
152
+ }
153
+ /** Bir repo → tam AGENTS.md belgesi (repo başlığı + prompt başına bölüm). */
154
+ function buildAgentsMdDocument(projectName, projectDescription, prompts, exportedAt) {
155
+ const head = [`# ${sanitizeInline(projectName) || 'Prompts'}`, ''];
156
+ const desc = sanitizeInline(projectDescription ?? '');
157
+ if (desc)
158
+ head.push(desc, '');
159
+ head.push(`Reusable prompts exported from ${SOURCE} on ${exportedAt.slice(0, 10)}. ` +
160
+ 'Each section is one prompt; follow it when the task matches its title.', '');
161
+ const sections = prompts.map((p) => buildAgentsMdSection(p, exportedAt).trimEnd());
162
+ return `${[head.join('\n').trimEnd(), ...sections].join('\n\n')}\n`;
163
+ }
164
+ // ---------------------------------------------------------------------------
165
+ // Agent Skills (SKILL.md)
166
+ // ---------------------------------------------------------------------------
167
+ /** "Ne yapar + ne zaman kullanılır" — spec'in iki şartı; 1024 sınırı, `<>` yok. */
168
+ function buildSkillDescription(p) {
169
+ const title = sanitizeInline(p.title) || 'this prompt';
170
+ const what = sanitizeInline(p.description ?? '').replace(/[.\s]+$/, '');
171
+ const whatPart = what ? `${what}.` : `Applies the saved prompt "${title}".`;
172
+ const when = ` Use when the user asks for "${title}" or a task that matches it.`;
173
+ return truncate(`${whatPart}${when}`, SKILL_DESCRIPTION_MAX);
174
+ }
175
+ function frontmatter(name, description, meta) {
176
+ const lines = ['---', `name: ${name}`, `description: ${yamlString(description)}`, 'metadata:'];
177
+ for (const [k, v] of Object.entries(meta))
178
+ lines.push(` ${k}: ${yamlString(v)}`);
179
+ lines.push('---');
180
+ return lines.join('\n');
181
+ }
182
+ function inputsSection(vars) {
183
+ if (vars.length === 0)
184
+ return '';
185
+ return [
186
+ '## Inputs',
187
+ '',
188
+ 'This prompt has placeholders. Take each value from the conversation, or ask the user once for the missing ones, then substitute them before following the instructions:',
189
+ '',
190
+ ...vars.map((v) => `- \`{{${v}}}\``),
191
+ '',
192
+ ].join('\n');
193
+ }
194
+ /** Tek prompt → `<name>/SKILL.md`. */
195
+ function buildPromptSkill(p, exportedAt) {
196
+ const name = toSkillName(p.title);
197
+ const meta = { source: SOURCE, exported: exportedAt.slice(0, 10) };
198
+ if (p.projectName)
199
+ meta.repo = sanitizeInline(p.projectName);
200
+ if (p.version != null)
201
+ meta.version = String(p.version);
202
+ const body = [
203
+ frontmatter(name, buildSkillDescription(p), meta),
204
+ '',
205
+ `# ${sanitizeInline(p.title) || name}`,
206
+ '',
207
+ inputsSection(listVariables(p.body)),
208
+ p.body.trim(),
209
+ ]
210
+ .filter((s, i, arr) => !(s === '' && arr[i - 1] === ''))
211
+ .join('\n');
212
+ return { name, files: [{ path: `${name}/SKILL.md`, content: `${body.trimEnd()}\n` }] };
213
+ }
214
+ /**
215
+ * Bir repo → TEK skill: SKILL.md bir dizin (progressive disclosure), her prompt
216
+ * `references/<ad>.md`. Claude yalnız eşleşen referansı okur → bağlam şişmez.
217
+ */
218
+ function buildProjectSkill(projectName, projectDescription, prompts, exportedAt) {
219
+ const name = toSkillName(projectName, 'prompt-library');
220
+ const used = new Set();
221
+ const refs = prompts.map((p) => {
222
+ let file = toSkillName(p.title);
223
+ let n = 2;
224
+ while (used.has(file))
225
+ file = `${toSkillName(p.title)}-${n++}`;
226
+ used.add(file);
227
+ return { p, file };
228
+ });
229
+ const desc = sanitizeInline(projectDescription ?? '').replace(/[.\s]+$/, '');
230
+ // Benzersiz başlıklar (aynı adlı prompt'lar açıklamada tekrar etmesin), ilk 8.
231
+ const uniqueTitles = [...new Set(prompts.map((p) => sanitizeInline(p.title)).filter(Boolean))];
232
+ const titles = uniqueTitles.slice(0, 8);
233
+ const description = truncate(`${desc ? `${desc}. ` : ''}Library of ${prompts.length} saved prompt${prompts.length === 1 ? '' : 's'} from the "${sanitizeInline(projectName)}" repo` +
234
+ `${titles.length ? ` (${titles.join(', ')}${uniqueTitles.length > titles.length ? ', …' : ''})` : ''}. ` +
235
+ 'Use when the user asks for one of these tasks or refers to a prompt from this repo by name.', SKILL_DESCRIPTION_MAX);
236
+ const index = refs.map(({ p, file }) => {
237
+ const d = sanitizeInline(p.description ?? '');
238
+ return `- **${sanitizeInline(p.title) || file}** → [references/${file}.md](references/${file}.md)${d ? `: ${d}` : ''}`;
239
+ });
240
+ const skillMd = [
241
+ frontmatter(name, description, { source: SOURCE, repo: sanitizeInline(projectName), exported: exportedAt.slice(0, 10) }),
242
+ '',
243
+ `# ${sanitizeInline(projectName) || name}`,
244
+ '',
245
+ 'Pick the prompt that matches the task, read only that reference file, fill its `{{placeholders}}` from the conversation (ask once for missing ones), then follow it.',
246
+ '',
247
+ '## Prompts',
248
+ '',
249
+ ...index,
250
+ '',
251
+ ].join('\n');
252
+ const files = [{ path: `${name}/SKILL.md`, content: skillMd }];
253
+ for (const { p, file } of refs) {
254
+ const header = [`# ${sanitizeInline(p.title) || file}`, ''];
255
+ const d = sanitizeInline(p.description ?? '');
256
+ if (d)
257
+ header.push(`> ${d}`, '');
258
+ files.push({
259
+ path: `${name}/references/${file}.md`,
260
+ content: `${header.join('\n')}${demoteHeadings(p.body.trim(), 1)}\n`,
261
+ });
262
+ }
263
+ return { name, files };
264
+ }
265
+ // ---------------------------------------------------------------------------
266
+ // Zip (STORE, sıkıştırmasız) — bağımlılıksız; web + CLI aynı byte'ları üretir.
267
+ // ---------------------------------------------------------------------------
268
+ function utf8(text) {
269
+ const out = [];
270
+ for (const ch of text) {
271
+ let cp = ch.codePointAt(0) ?? 0;
272
+ if (cp < 0x80)
273
+ out.push(cp);
274
+ else if (cp < 0x800)
275
+ out.push(0xc0 | (cp >> 6), 0x80 | (cp & 0x3f));
276
+ else if (cp < 0x10000) {
277
+ if (cp >= 0xd800 && cp <= 0xdfff)
278
+ cp = 0xfffd; // yalnız surrogate → U+FFFD
279
+ out.push(0xe0 | (cp >> 12), 0x80 | ((cp >> 6) & 0x3f), 0x80 | (cp & 0x3f));
280
+ }
281
+ else {
282
+ out.push(0xf0 | (cp >> 18), 0x80 | ((cp >> 12) & 0x3f), 0x80 | ((cp >> 6) & 0x3f), 0x80 | (cp & 0x3f));
283
+ }
284
+ }
285
+ return Uint8Array.from(out);
286
+ }
287
+ let crcTable = null;
288
+ function crc32(data) {
289
+ if (!crcTable) {
290
+ crcTable = new Uint32Array(256);
291
+ for (let n = 0; n < 256; n++) {
292
+ let c = n;
293
+ for (let k = 0; k < 8; k++)
294
+ c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
295
+ crcTable[n] = c >>> 0;
296
+ }
297
+ }
298
+ let crc = 0xffffffff;
299
+ for (let i = 0; i < data.length; i++)
300
+ crc = crcTable[(crc ^ data[i]) & 0xff] ^ (crc >>> 8);
301
+ return (crc ^ 0xffffffff) >>> 0;
302
+ }
303
+ /**
304
+ * Dosyaları zip'e koyar. Ara klasörler için dizin girdisi de yazılır (bazı
305
+ * yükleyiciler kökteki klasörü girdiden tanır). Adlar UTF-8 (bit 11).
306
+ */
307
+ function createZip(files, date = new Date()) {
308
+ const dosTime = (date.getHours() << 11) | (date.getMinutes() << 5) | Math.floor(date.getSeconds() / 2);
309
+ const dosDate = ((Math.max(1980, date.getFullYear()) - 1980) << 9) | ((date.getMonth() + 1) << 5) | date.getDate();
310
+ const entries = [];
311
+ const dirs = new Set();
312
+ for (const f of files) {
313
+ const segs = f.path.split('/');
314
+ for (let i = 1; i < segs.length; i++) {
315
+ const dir = `${segs.slice(0, i).join('/')}/`;
316
+ if (!dirs.has(dir)) {
317
+ dirs.add(dir);
318
+ entries.push({ name: utf8(dir), data: new Uint8Array(0), dir: true });
319
+ }
320
+ }
321
+ entries.push({ name: utf8(f.path), data: utf8(f.content), dir: false });
322
+ }
323
+ const chunks = [];
324
+ const central = [];
325
+ let offset = 0;
326
+ for (const e of entries) {
327
+ const crc = crc32(e.data);
328
+ const local = new Uint8Array(30 + e.name.length);
329
+ const lv = new DataView(local.buffer);
330
+ lv.setUint32(0, 0x04034b50, true);
331
+ lv.setUint16(4, 20, true);
332
+ lv.setUint16(6, 0x0800, true);
333
+ lv.setUint16(8, 0, true);
334
+ lv.setUint16(10, dosTime, true);
335
+ lv.setUint16(12, dosDate, true);
336
+ lv.setUint32(14, crc, true);
337
+ lv.setUint32(18, e.data.length, true);
338
+ lv.setUint32(22, e.data.length, true);
339
+ lv.setUint16(26, e.name.length, true);
340
+ lv.setUint16(28, 0, true);
341
+ local.set(e.name, 30);
342
+ const cd = new Uint8Array(46 + e.name.length);
343
+ const cv = new DataView(cd.buffer);
344
+ cv.setUint32(0, 0x02014b50, true);
345
+ cv.setUint16(4, 20, true);
346
+ cv.setUint16(6, 20, true);
347
+ cv.setUint16(8, 0x0800, true);
348
+ cv.setUint16(10, 0, true);
349
+ cv.setUint16(12, dosTime, true);
350
+ cv.setUint16(14, dosDate, true);
351
+ cv.setUint32(16, crc, true);
352
+ cv.setUint32(20, e.data.length, true);
353
+ cv.setUint32(24, e.data.length, true);
354
+ cv.setUint16(28, e.name.length, true);
355
+ cv.setUint32(38, e.dir ? 0x10 : 0, true);
356
+ cv.setUint32(42, offset, true);
357
+ cd.set(e.name, 46);
358
+ chunks.push(local, e.data);
359
+ central.push(cd);
360
+ offset += local.length + e.data.length;
361
+ }
362
+ const cdSize = central.reduce((n, c) => n + c.length, 0);
363
+ const end = new Uint8Array(22);
364
+ const ev = new DataView(end.buffer);
365
+ ev.setUint32(0, 0x06054b50, true);
366
+ ev.setUint16(8, entries.length, true);
367
+ ev.setUint16(10, entries.length, true);
368
+ ev.setUint32(12, cdSize, true);
369
+ ev.setUint32(16, offset, true);
370
+ const all = [...chunks, ...central, end];
371
+ const out = new Uint8Array(all.reduce((n, c) => n + c.length, 0));
372
+ let pos = 0;
373
+ for (const c of all) {
374
+ out.set(c, pos);
375
+ pos += c.length;
376
+ }
377
+ return out;
378
+ }
@@ -14,13 +14,20 @@
14
14
  * - map 429 / error bodies to clean, user-facing Error messages
15
15
  */
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
+ exports.USE_SURFACES = void 0;
17
18
  exports.login = login;
18
19
  exports.ensureAuthed = ensureAuthed;
19
20
  exports.listPrompts = listPrompts;
20
21
  exports.importPrompts = importPrompts;
22
+ exports.getImportedHashes = getImportedHashes;
23
+ exports.getAccountHeadroom = getAccountHeadroom;
21
24
  exports.listProjects = listProjects;
22
25
  exports.getPromptById = getPromptById;
26
+ exports.getPromptHistory = getPromptHistory;
27
+ exports.rollbackPrompt = rollbackPrompt;
28
+ exports.buildUseEventBody = buildUseEventBody;
23
29
  exports.recordPromptUse = recordPromptUse;
30
+ exports.getUsageInsights = getUsageInsights;
24
31
  const constants_1 = require("./constants");
25
32
  const config_1 = require("./config");
26
33
  const NOT_LOGGED_IN = 'Not logged in. Run `ple login` first.';
@@ -195,19 +202,47 @@ async function listPrompts(params = {}) {
195
202
  * the caller batches and reports whatever came back rather than assuming
196
203
  * everything landed.
197
204
  */
198
- async function importPrompts(prompts) {
205
+ async function importPrompts(prompts, options = {}) {
199
206
  const res = await apiFetch('/api/prompts/import', {
200
207
  method: 'POST',
201
- body: { prompts },
208
+ body: { prompts, ...options },
202
209
  });
203
210
  return {
204
211
  imported: res.imported ?? 0,
205
212
  failed: res.failed ?? 0,
206
213
  skippedInvalid: res.skippedInvalid ?? 0,
207
214
  truncatedByQuota: res.truncatedByQuota ?? 0,
215
+ skippedDuplicate: res.skippedDuplicate ?? 0,
216
+ projectId: res.projectId,
208
217
  tagsApplied: res.tagsApplied,
209
218
  };
210
219
  }
220
+ /**
221
+ * GET /api/prompts/import — sha256 of everything already brought in with
222
+ * `ple import --scan`. Older servers (no GET handler) → empty set, so the
223
+ * preview just cannot mark "already imported"; the POST still dedupes.
224
+ */
225
+ async function getImportedHashes() {
226
+ try {
227
+ const res = await apiFetch('/api/prompts/import');
228
+ return new Set(res.knownHashes ?? []);
229
+ }
230
+ catch {
231
+ return new Set();
232
+ }
233
+ }
234
+ async function getAccountHeadroom() {
235
+ try {
236
+ const res = await apiFetch('/api/account/limits');
237
+ return {
238
+ promptsRemaining: res.usage?.promptsRemaining ?? null,
239
+ isPro: res.plan?.isPro === true,
240
+ };
241
+ }
242
+ catch {
243
+ return { promptsRemaining: null, isPro: false };
244
+ }
245
+ }
211
246
  /** GET /api/projects — list the user's accessible repos (for --project resolution). */
212
247
  async function listProjects() {
213
248
  const res = await apiFetch('/api/projects', {
@@ -227,14 +262,62 @@ async function getPromptById(id) {
227
262
  throw err;
228
263
  }
229
264
  }
265
+ /** GET /api/prompts/{id} → history for `ple log/diff/rollback`. */
266
+ async function getPromptHistory(id) {
267
+ const res = await apiFetch(`/api/prompts/${id}`);
268
+ if (!res.prompt)
269
+ throw new Error('Prompt not found.');
270
+ return {
271
+ id: res.prompt.id,
272
+ title: res.prompt.title,
273
+ current_version_id: res.prompt.current_version_id ?? null,
274
+ versions: Array.isArray(res.prompt.versions) ? res.prompt.versions : [],
275
+ };
276
+ }
277
+ /**
278
+ * POST /api/prompts/{id}/rollback — restores a version as a NEW version
279
+ * (nothing is deleted; the history keeps growing).
280
+ */
281
+ async function rollbackPrompt(id, versionId) {
282
+ return apiFetch(`/api/prompts/${id}/rollback`, {
283
+ method: 'POST',
284
+ body: { versionId },
285
+ });
286
+ }
287
+ /** Kullanım yüzeyleri — sunucudaki `USE_SURFACES` ile aynı küme (W1-1). */
288
+ exports.USE_SURFACES = [
289
+ 'web', 'cli', 'mcp_tool', 'mcp_prompt', 'mcp_resource', 'extension', 'hook', 'repo', 'api', 'unknown',
290
+ ];
291
+ /**
292
+ * Build the use-event body. `PLE_SURFACE` / `PLE_VIA` let a wrapper (e.g. an
293
+ * agent hook calling `ple get`) attribute the use correctly; unknown values
294
+ * fall back to the CLI defaults rather than failing the command.
295
+ */
296
+ function buildUseEventBody(opts = {}, env = process.env) {
297
+ const envSurface = env.PLE_SURFACE?.trim().toLowerCase();
298
+ const surface = exports.USE_SURFACES.includes(envSurface ?? '')
299
+ ? envSurface
300
+ : 'cli';
301
+ const via = env.PLE_VIA?.trim().toLowerCase() === 'suggestion' ? 'suggestion' : 'direct';
302
+ const body = { surface, client: `ple-cli/${constants_1.CLI_VERSION}`, via };
303
+ if (typeof opts.version === 'number' && Number.isInteger(opts.version) && opts.version > 0) {
304
+ body.version = opts.version;
305
+ }
306
+ return body;
307
+ }
230
308
  /**
231
- * Kullanım kaydı (REV-6) — `ple copy/get/show` sonrası fire-and-forget.
232
- * Most Used + ⌘K sıralaması eskiden yalnız web kopyalarını sayıyordu; ana
233
- * reuse yüzeyi terminal olduğundan metrik köreliyordu. Hata YUTULUR:
234
- * telemetri asıl komutu asla kırmaz.
309
+ * Kullanım kaydı (REV-6 → W1-1) — `ple copy/get/show` sonrası fire-and-forget.
310
+ * Gövde yüzeyi (`surface: 'cli'`) ve istemciyi taşır; sunucu olay defterine
311
+ * yazar (defter yoksa eski sayaca düşer). Hata YUTULUR: telemetri asıl
312
+ * komutu asla kırmaz.
235
313
  */
236
- function recordPromptUse(promptId) {
237
- apiFetch(`/api/prompts/${promptId}/use`, { method: 'POST' }).catch(() => {
314
+ function recordPromptUse(promptId, opts = {}) {
315
+ apiFetch(`/api/prompts/${promptId}/use`, { method: 'POST', body: buildUseEventBody(opts) }).catch(() => {
238
316
  /* sessiz — telemetri */
239
317
  });
240
318
  }
319
+ /** GET /api/insights?range= — usage summary for `ple stats`. */
320
+ async function getUsageInsights(range) {
321
+ const res = await apiFetch('/api/insights', { query: { range } });
322
+ return res.insights ?? null;
323
+ }
@@ -34,7 +34,6 @@ exports.CLI_NAME = 'ple';
34
34
  function readVersion() {
35
35
  try {
36
36
  const pkgPath = '../../package.json';
37
- // eslint-disable-next-line @typescript-eslint/no-var-requires
38
37
  const pkg = require(pkgPath);
39
38
  return pkg.version ?? '0.0.0';
40
39
  }
@@ -0,0 +1,149 @@
1
+ "use strict";
2
+ /**
3
+ * Line-based unified diff for `ple diff` (W1-4). No dependency (the CLI is
4
+ * commander + chalk only): Myers' O((N+M)·D) shortest-edit-script, then
5
+ * hunks with N lines of context — the same shape `git diff` prints, so it
6
+ * pipes into `delta`, `less -R` or a patch reviewer unchanged.
7
+ */
8
+ Object.defineProperty(exports, "__esModule", { value: true });
9
+ exports.splitLines = splitLines;
10
+ exports.diffLines = diffLines;
11
+ exports.unifiedDiff = unifiedDiff;
12
+ /** Split into lines; a trailing newline does not create an empty last line. */
13
+ function splitLines(text) {
14
+ const normalized = text.replace(/\r\n/g, '\n');
15
+ if (normalized === '')
16
+ return [];
17
+ const lines = normalized.split('\n');
18
+ if (lines[lines.length - 1] === '')
19
+ lines.pop();
20
+ return lines;
21
+ }
22
+ /** Myers diff → ordered edit script. */
23
+ function diffLines(a, b) {
24
+ const n = a.length;
25
+ const m = b.length;
26
+ const max = n + m;
27
+ const offset = max;
28
+ const v = new Int32Array(2 * max + 2);
29
+ const trace = [];
30
+ let found = false;
31
+ for (let d = 0; d <= max && !found; d++) {
32
+ trace.push(v.slice());
33
+ for (let k = -d; k <= d; k += 2) {
34
+ let x;
35
+ if (k === -d || (k !== d && v[offset + k - 1] < v[offset + k + 1])) {
36
+ x = v[offset + k + 1]; // down (insertion)
37
+ }
38
+ else {
39
+ x = v[offset + k - 1] + 1; // right (deletion)
40
+ }
41
+ let y = x - k;
42
+ while (x < n && y < m && a[x] === b[y]) {
43
+ x++;
44
+ y++;
45
+ }
46
+ v[offset + k] = x;
47
+ if (x >= n && y >= m) {
48
+ found = true;
49
+ break;
50
+ }
51
+ }
52
+ }
53
+ trace.push(v.slice());
54
+ // Backtrack from (n, m) through the saved frontiers.
55
+ const ops = [];
56
+ let x = n;
57
+ let y = m;
58
+ for (let d = trace.length - 2; d >= 0 && (x > 0 || y > 0); d--) {
59
+ const vd = trace[d];
60
+ const k = x - y;
61
+ let prevK;
62
+ if (k === -d || (k !== d && vd[offset + k - 1] < vd[offset + k + 1])) {
63
+ prevK = k + 1;
64
+ }
65
+ else {
66
+ prevK = k - 1;
67
+ }
68
+ const prevX = vd[offset + prevK];
69
+ const prevY = prevX - prevK;
70
+ while (x > prevX && y > prevY) {
71
+ ops.push({ type: 'equal', line: a[x - 1] });
72
+ x--;
73
+ y--;
74
+ }
75
+ if (d === 0)
76
+ break;
77
+ if (x === prevX) {
78
+ ops.push({ type: 'add', line: b[y - 1] });
79
+ }
80
+ else {
81
+ ops.push({ type: 'del', line: a[x - 1] });
82
+ }
83
+ x = prevX;
84
+ y = prevY;
85
+ }
86
+ while (x > 0 && y > 0) {
87
+ ops.push({ type: 'equal', line: a[x - 1] });
88
+ x--;
89
+ y--;
90
+ }
91
+ return ops.reverse();
92
+ }
93
+ /**
94
+ * Render a unified diff. Returns [] when the texts are identical so the
95
+ * caller can print its own "no changes" message.
96
+ */
97
+ function unifiedDiff(from, to, opts) {
98
+ const a = splitLines(from);
99
+ const b = splitLines(to);
100
+ const ops = diffLines(a, b);
101
+ if (ops.every((o) => o.type === 'equal'))
102
+ return [];
103
+ const ctx = opts.context ?? 3;
104
+ const id = (s) => s;
105
+ const col = opts.colors ?? { header: id, hunk: id, add: id, del: id };
106
+ // Indices of changed ops; group into hunks whose context windows touch.
107
+ const changed = ops.map((o, i) => (o.type === 'equal' ? -1 : i)).filter((i) => i >= 0);
108
+ const groups = [];
109
+ for (const i of changed) {
110
+ const start = Math.max(0, i - ctx);
111
+ const end = Math.min(ops.length - 1, i + ctx);
112
+ const last = groups[groups.length - 1];
113
+ if (last && start <= last[1] + 1)
114
+ last[1] = end;
115
+ else
116
+ groups.push([start, end]);
117
+ }
118
+ // Line numbers before each op.
119
+ const aLineAt = [];
120
+ const bLineAt = [];
121
+ let ai = 1;
122
+ let bi = 1;
123
+ for (const o of ops) {
124
+ aLineAt.push(ai);
125
+ bLineAt.push(bi);
126
+ if (o.type !== 'add')
127
+ ai++;
128
+ if (o.type !== 'del')
129
+ bi++;
130
+ }
131
+ const out = [col.header(`--- ${opts.fromLabel}`), col.header(`+++ ${opts.toLabel}`)];
132
+ for (const [start, end] of groups) {
133
+ const slice = ops.slice(start, end + 1);
134
+ const aCount = slice.filter((o) => o.type !== 'add').length;
135
+ const bCount = slice.filter((o) => o.type !== 'del').length;
136
+ const aStart = aCount === 0 ? aLineAt[start] - 1 : aLineAt[start];
137
+ const bStart = bCount === 0 ? bLineAt[start] - 1 : bLineAt[start];
138
+ out.push(col.hunk(`@@ -${aStart},${aCount} +${bStart},${bCount} @@`));
139
+ for (const o of slice) {
140
+ if (o.type === 'equal')
141
+ out.push(` ${o.line}`);
142
+ else if (o.type === 'del')
143
+ out.push(col.del(`-${o.line}`));
144
+ else
145
+ out.push(col.add(`+${o.line}`));
146
+ }
147
+ }
148
+ return out;
149
+ }