promptlike 0.9.0 → 0.10.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.
Files changed (41) hide show
  1. package/CHANGELOG.md +112 -0
  2. package/README.md +241 -27
  3. package/dist/commands/config.js +13 -0
  4. package/dist/commands/copy.js +10 -3
  5. package/dist/commands/get.js +11 -2
  6. package/dist/commands/import.js +30 -128
  7. package/dist/commands/importCheck.js +304 -0
  8. package/dist/commands/importGithub.js +171 -0
  9. package/dist/commands/list.js +83 -17
  10. package/dist/commands/local.js +31 -9
  11. package/dist/commands/login.js +6 -5
  12. package/dist/commands/save.js +1 -1
  13. package/dist/commands/search.js +73 -7
  14. package/dist/commands/show.js +11 -3
  15. package/dist/commands/suggest.js +100 -10
  16. package/dist/commands/sync.js +57 -13
  17. package/dist/index.js +7 -0
  18. package/dist/lib/errors.js +4 -0
  19. package/dist/lib/format.js +28 -0
  20. package/dist/lib/frontmatter.js +86 -4
  21. package/dist/lib/github.js +208 -0
  22. package/dist/lib/githubCache.js +118 -0
  23. package/dist/lib/githubHttp.js +197 -0
  24. package/dist/lib/githubImport.js +238 -0
  25. package/dist/lib/githubSelect.js +148 -0
  26. package/dist/lib/githubSnapshot.js +67 -0
  27. package/dist/lib/githubSpec.js +78 -0
  28. package/dist/lib/importOrigins.js +36 -0
  29. package/dist/lib/importShared.js +179 -0
  30. package/dist/lib/licenses.js +243 -0
  31. package/dist/lib/localStore.js +80 -2
  32. package/dist/lib/loopApi.js +63 -11
  33. package/dist/lib/promptResolver.js +22 -9
  34. package/dist/lib/promptSource.js +123 -0
  35. package/dist/lib/rank.js +30 -13
  36. package/dist/lib/settings.js +24 -3
  37. package/dist/lib/tagFilter.js +40 -0
  38. package/dist/lib/updateCheck.js +296 -0
  39. package/dist/lib/upstreamCheck.js +71 -0
  40. package/dist/program.js +26 -7
  41. package/package.json +1 -1
@@ -0,0 +1,238 @@
1
+ "use strict";
2
+ /**
3
+ * The middle of `ple import github:…`: read the picked files, gate them, and
4
+ * build what is remembered about where each prompt came from.
5
+ *
6
+ * Every file passes the same gates, in this order: sensitive file name and size
7
+ * (./githubSelect.ts — never fetched), secret scan, empty body, license
8
+ * (./licenses.ts). A file that fails one is listed with the reason and never
9
+ * copied anywhere; downloads are kept in the cache only after a file passed all
10
+ * of them.
11
+ *
12
+ * Provenance has three faces, all built here:
13
+ * origin signed in: sent with the prompt (`prompt_origins.meta`), what `--check` reads back
14
+ * upstream signed out: `upstream_*` lines in the local file (see localStore.ts)
15
+ * description the attribution line appended to the prompt's description
16
+ */
17
+ Object.defineProperty(exports, "__esModule", { value: true });
18
+ exports.trackedKey = exports.loadSnapshot = exports.selectPicks = exports.MAX_PICKS = exports.SPEC_HELP = exports.parseGithubSpec = void 0;
19
+ exports.readUpstream = readUpstream;
20
+ exports.prepareCandidate = prepareCandidate;
21
+ exports.attributionLine = attributionLine;
22
+ exports.buildDescription = buildDescription;
23
+ exports.refreshAttribution = refreshAttribution;
24
+ exports.originFromUpstream = originFromUpstream;
25
+ exports.buildOrigin = buildOrigin;
26
+ exports.buildUpstream = buildUpstream;
27
+ exports.mapLimit = mapLimit;
28
+ exports.collectItems = collectItems;
29
+ const frontmatter_1 = require("./frontmatter");
30
+ const github_1 = require("./github");
31
+ const githubSnapshot_1 = require("./githubSnapshot");
32
+ const githubSelect_1 = require("./githubSelect");
33
+ const format_1 = require("./format");
34
+ const promptTemplate_1 = require("./promptTemplate");
35
+ const scanners_1 = require("./scanners");
36
+ const secretGuard_1 = require("./secretGuard");
37
+ // The steps of an import, from the argument to the stored provenance, are reachable from here:
38
+ var githubSpec_1 = require("./githubSpec");
39
+ Object.defineProperty(exports, "parseGithubSpec", { enumerable: true, get: function () { return githubSpec_1.parseGithubSpec; } });
40
+ Object.defineProperty(exports, "SPEC_HELP", { enumerable: true, get: function () { return githubSpec_1.SPEC_HELP; } });
41
+ var githubSelect_2 = require("./githubSelect");
42
+ Object.defineProperty(exports, "MAX_PICKS", { enumerable: true, get: function () { return githubSelect_2.MAX_PICKS; } });
43
+ Object.defineProperty(exports, "selectPicks", { enumerable: true, get: function () { return githubSelect_2.selectPicks; } });
44
+ var githubSnapshot_2 = require("./githubSnapshot");
45
+ Object.defineProperty(exports, "loadSnapshot", { enumerable: true, get: function () { return githubSnapshot_2.loadSnapshot; } });
46
+ const MAX_TITLE = 200;
47
+ const MAX_DESCRIPTION = 1000;
48
+ const MAX_TAGS = 10;
49
+ const MAX_TAG = 50;
50
+ const KNOWN_KEYS = new Set(['name', 'title', 'description', 'tags', 'license']);
51
+ const oneLine = (s) => (0, format_1.safeText)(s).replace(/\s+/g, ' ').trim();
52
+ /** Text of a file the way import reads it: refuse secrets, strip frontmatter, refuse an empty body. */
53
+ function readUpstream(text) {
54
+ const secret = (0, secretGuard_1.findSecret)(text);
55
+ if (secret)
56
+ return { skip: `looks like it contains a ${secret} — not imported` };
57
+ const fm = (0, frontmatter_1.parseFrontmatter)(text);
58
+ const body = fm.body.trim();
59
+ if (!body)
60
+ return { skip: 'empty body' };
61
+ return { body, declaredLicense: fm.fields.license || undefined, fm };
62
+ }
63
+ function prepareCandidate(pick, text) {
64
+ const read = readUpstream(text);
65
+ if ('skip' in read)
66
+ return read;
67
+ const { body, fm } = read;
68
+ const named = pick.fixedTitle ? '' : oneLine(fm.fields.name || fm.fields.title || '');
69
+ const title = (named || oneLine(pick.titleHint)).slice(0, MAX_TITLE) || 'prompt';
70
+ const fmTags = (fm.lists.tags ?? (fm.fields.tags ? fm.fields.tags.split(',') : []))
71
+ .flatMap((t) => t.split(','))
72
+ .map((t) => oneLine(t).slice(0, MAX_TAG))
73
+ .filter(Boolean);
74
+ // The tool and `github` tags always survive the cap of 10.
75
+ const closing = [...new Set([pick.tool, 'github'])];
76
+ const tags = [...new Set(fmTags.filter((t) => !closing.includes(t)))].slice(0, MAX_TAGS - closing.length).concat(closing);
77
+ const extra = {};
78
+ for (const [k, v] of Object.entries(fm.fields)) {
79
+ if (!KNOWN_KEYS.has(k) && v)
80
+ extra[k] = oneLine(v);
81
+ }
82
+ const warnings = [];
83
+ if (body.includes('${{') || body.includes('{%')) {
84
+ warnings.push('uses ${{ }} / Jinja syntax — {{…}} will be read as PromptLikeEngineer variables');
85
+ }
86
+ return {
87
+ candidate: {
88
+ pick,
89
+ title,
90
+ description: oneLine(fm.fields.description ?? ''),
91
+ tags,
92
+ body,
93
+ extra,
94
+ declaredLicense: read.declaredLicense,
95
+ bytes: Buffer.byteLength(text, 'utf8'),
96
+ sha256: (0, scanners_1.hashBody)(body),
97
+ variables: (0, promptTemplate_1.extractVariables)(body),
98
+ warnings,
99
+ },
100
+ };
101
+ }
102
+ // ---------------------------------------------------------------------------
103
+ // Provenance
104
+ // ---------------------------------------------------------------------------
105
+ const SEP = ' — ';
106
+ // Exactly what attributionLine writes: the link, the SPDX id, and an optional copyright notice.
107
+ const ATTRIBUTION = /(?:^| — )Source: github\.com\/\S+ · [A-Za-z0-9.+-]+(?: · (?:[Cc]opyright|©|\([Cc]\))[^\n]*)?$/;
108
+ /** `Source: github.com/o/r/blob/abc1234/path · MIT · Copyright …` */
109
+ function attributionLine(repo, commit, path, verdict) {
110
+ const link = (0, github_1.blobUrl)(repo, commit.slice(0, 7), path).replace(/^https:\/\//, '');
111
+ return `Source: ${link} · ${verdict.spdx}${verdict.copyright ? ` · ${verdict.copyright}` : ''}`;
112
+ }
113
+ /** The original description, trimmed so that description + attribution stay within the 1000-character limit. */
114
+ function buildDescription(original, attribution) {
115
+ if (!original)
116
+ return attribution.slice(0, MAX_DESCRIPTION);
117
+ const room = MAX_DESCRIPTION - SEP.length - attribution.length;
118
+ if (room <= 0)
119
+ return attribution.slice(0, MAX_DESCRIPTION);
120
+ const kept = original.length > room ? `${original.slice(0, Math.max(0, room - 1)).trimEnd()}…` : original;
121
+ return `${kept}${SEP}${attribution}`;
122
+ }
123
+ /** Swap the attribution at the end of an existing description; null when it has none (the person edited it away). */
124
+ function refreshAttribution(description, attribution) {
125
+ if (!ATTRIBUTION.test(description))
126
+ return null;
127
+ return buildDescription(description.replace(ATTRIBUTION, '').trimEnd(), attribution);
128
+ }
129
+ /** Server-side meta limits (src/lib/import-origin.ts): ≤ 20 keys, values ≤ 500, ≤ 4096 bytes — keep a margin. */
130
+ const META_BUDGET_BYTES = 3500;
131
+ const META_KEY = /^[A-Za-z0-9_-]{1,40}$/;
132
+ const RESERVED = new Set(['source', 'repo', 'ref', 'commit', 'blob', 'file', 'license', 'license_url', 'copyright', 'url']);
133
+ const bytesOf = (v) => Buffer.byteLength(JSON.stringify(v), 'utf8');
134
+ /** The keys `--check` needs to find the file again — never dropped. */
135
+ function baseMeta(up) {
136
+ const cut = (v) => v.slice(0, 500);
137
+ return {
138
+ source: 'github',
139
+ repo: up.repo,
140
+ ref: cut(up.ref),
141
+ commit: up.commit,
142
+ blob: up.blob,
143
+ file: cut(up.path),
144
+ license: cut(up.license),
145
+ ...(up.licenseUrl ? { license_url: cut(up.licenseUrl) } : {}),
146
+ ...(up.copyright ? { copyright: cut(up.copyright) } : {}),
147
+ url: cut(up.url),
148
+ };
149
+ }
150
+ /**
151
+ * Provenance as the server stores it (`prompt_origins`): tool, kind, `github:<repo>/<path>`,
152
+ * the sha256 of the text, and `meta`. The keys `--check` reads are never dropped;
153
+ * `extra` (the file's other frontmatter keys) fills whatever room is left.
154
+ */
155
+ function originFromUpstream(up, sha256, extra = {}) {
156
+ let meta = baseMeta(up);
157
+ for (const [k, v] of Object.entries(extra)) {
158
+ if (RESERVED.has(k) || !META_KEY.test(k) || Object.keys(meta).length >= 20)
159
+ continue;
160
+ const next = { ...meta, [k]: v.slice(0, 500) };
161
+ if (bytesOf(next) <= META_BUDGET_BYTES)
162
+ meta = next;
163
+ }
164
+ return { tool: up.tool, kind: up.kind, path: `github:${up.repo}/${up.path}`, sha256, meta };
165
+ }
166
+ function buildOrigin(snap, c, verdict, url) {
167
+ return originFromUpstream(buildUpstream(snap, c, verdict, url), c.sha256, c.extra);
168
+ }
169
+ function buildUpstream(snap, c, verdict, url) {
170
+ return {
171
+ repo: snap.repo,
172
+ ref: snap.ref,
173
+ commit: snap.commit,
174
+ blob: c.pick.blob,
175
+ path: c.pick.path,
176
+ license: verdict.spdx ?? '',
177
+ ...(verdict.licenseUrl ? { licenseUrl: verdict.licenseUrl } : {}),
178
+ ...(verdict.copyright ? { copyright: verdict.copyright } : {}),
179
+ tool: c.pick.tool,
180
+ kind: c.pick.kind,
181
+ url,
182
+ };
183
+ }
184
+ /** Identity of an imported file for "already imported?" — GitHub treats owner and repo case-insensitively. */
185
+ const trackedKey = (repo, ref, file) => `${repo.toLowerCase()}@${ref}:${file}`;
186
+ exports.trackedKey = trackedKey;
187
+ /** Run `fn` over `items`, at most `limit` at a time; results in input order. */
188
+ async function mapLimit(items, limit, fn) {
189
+ const out = new Array(items.length);
190
+ let next = 0;
191
+ const worker = async () => {
192
+ while (next < items.length) {
193
+ const i = next++;
194
+ out[i] = await fn(items[i]);
195
+ }
196
+ };
197
+ await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));
198
+ return out;
199
+ }
200
+ /**
201
+ * Select, read and gate. Files are downloaded without being cached; only the
202
+ * ones that pass every gate are remembered, so nothing that was refused stays
203
+ * on disk. Network errors propagate.
204
+ */
205
+ async function collectItems(snap, spec, concurrency = 4) {
206
+ const { picks, skipped } = (0, githubSelect_1.selectPicks)(snap, spec);
207
+ const items = [];
208
+ const blocked = [];
209
+ const results = await mapLimit(picks, concurrency, async (pick) => {
210
+ const text = await (0, githubSnapshot_1.readFile)(snap, pick.path, false);
211
+ if (text === null)
212
+ return { pick, skip: 'not a text file or larger than 64 KB — skipped' };
213
+ const prepared = prepareCandidate(pick, text);
214
+ if ('skip' in prepared)
215
+ return { pick, skip: prepared.skip };
216
+ const verdict = await (0, githubSnapshot_1.gate)(snap, pick.path, prepared.candidate.declaredLicense);
217
+ return { pick, candidate: prepared.candidate, verdict, text };
218
+ });
219
+ for (const r of results) {
220
+ if (r.skip !== undefined) {
221
+ skipped.push({ path: r.pick.path, reason: r.skip });
222
+ continue;
223
+ }
224
+ const url = (0, github_1.blobUrl)(snap.repo, snap.commit, r.pick.path);
225
+ if (!r.verdict.allowed) {
226
+ blocked.push({ path: r.pick.path, url, found: r.verdict.spdx });
227
+ continue;
228
+ }
229
+ (0, github_1.rememberRaw)(snap.owner, snap.name, snap.commit, r.pick.path, r.text);
230
+ items.push({
231
+ candidate: r.candidate,
232
+ verdict: r.verdict,
233
+ description: buildDescription(r.candidate.description, attributionLine(snap.repo, snap.commit, r.pick.path, r.verdict)),
234
+ url,
235
+ });
236
+ }
237
+ return { items, blocked, skipped };
238
+ }
@@ -0,0 +1,148 @@
1
+ "use strict";
2
+ /**
3
+ * Which files of a repo count as prompts — the same places `ple import --scan`
4
+ * looks on disk, plus the shapes public repos use:
5
+ *
6
+ * SKILL.md (any depth ≤ 8) claude-code · skill
7
+ * *.prompt.md copilot · prompt
8
+ * .claude/commands/**.md claude-code · command
9
+ * .cursor/commands/**.md cursor · command
10
+ * *.mdc cursor · context
11
+ * …/patterns/<name>/system.md other · prompt (Fabric)
12
+ * AGENTS.md, CLAUDE.md agents-md · context (only at the requested path)
13
+ * one .md file named by the path other · prompt
14
+ *
15
+ * A path that is a file selects just that file. Nothing is fetched here: this
16
+ * works on the file list alone.
17
+ */
18
+ Object.defineProperty(exports, "__esModule", { value: true });
19
+ exports.MAX_PICKS = void 0;
20
+ exports.selectPicks = selectPicks;
21
+ const format_1 = require("./format");
22
+ const secretGuard_1 = require("./secretGuard");
23
+ /** More than this under one path → ask for a narrower path instead of fetching them all. */
24
+ exports.MAX_PICKS = 200;
25
+ const MAX_SKILL_DEPTH = 8;
26
+ /**
27
+ * Server meta values are cut at 500 characters and the origin path (`github:<repo>/<path>`)
28
+ * at 512; a longer file path could not be matched again, so such a file is not imported.
29
+ */
30
+ const MAX_FILE_PATH = 450;
31
+ const MAX_ORIGIN_PATH = 512;
32
+ const ODD_PATH = /[\u0000-\u001f\u007f-\u009f\\]/;
33
+ const baseOf = (p) => p.slice(p.lastIndexOf('/') + 1);
34
+ const dirOf = (p) => (p.includes('/') ? p.slice(0, p.lastIndexOf('/')) : '');
35
+ const stripExt = (name, ext) => name.replace(ext, '');
36
+ /** `…/<a>/<b>/rest` → the part after `<a>/<b>`, or null. */
37
+ function afterDirPair(segs, a, b) {
38
+ for (let i = 0; i + 2 < segs.length; i++) {
39
+ if (segs[i] === a && segs[i + 1] === b)
40
+ return segs.slice(i + 2);
41
+ }
42
+ return null;
43
+ }
44
+ function classify(path, ctx) {
45
+ const name = baseOf(path);
46
+ const segs = path.split('/');
47
+ if (name === 'SKILL.md' && ctx.depthBelowRoot <= MAX_SKILL_DEPTH) {
48
+ return { tool: 'claude-code', kind: 'skill', titleHint: baseOf(dirOf(path)) || ctx.repoName };
49
+ }
50
+ if (/\.prompt\.md$/i.test(name)) {
51
+ return { tool: 'copilot', kind: 'prompt', titleHint: stripExt(name, /\.prompt\.md$/i) };
52
+ }
53
+ if (/\.md$/i.test(name)) {
54
+ const claude = afterDirPair(segs, '.claude', 'commands');
55
+ if (claude)
56
+ return { tool: 'claude-code', kind: 'command', titleHint: stripExt(claude.join('/'), /\.md$/i) };
57
+ const cursor = afterDirPair(segs, '.cursor', 'commands');
58
+ if (cursor)
59
+ return { tool: 'cursor', kind: 'command', titleHint: stripExt(cursor.join('/'), /\.md$/i) };
60
+ }
61
+ if (/\.mdc$/i.test(name)) {
62
+ return { tool: 'cursor', kind: 'context', titleHint: stripExt(name, /\.mdc$/i) };
63
+ }
64
+ if (name === 'system.md' && segs.length >= 3 && segs[segs.length - 3] === 'patterns') {
65
+ return { tool: 'other', kind: 'prompt', titleHint: segs[segs.length - 2] };
66
+ }
67
+ if ((name === 'AGENTS.md' || name === 'CLAUDE.md') && (ctx.single || dirOf(path) === ctx.rootDir)) {
68
+ return { tool: 'agents-md', kind: 'context', titleHint: `${name} (${ctx.repoName})`, fixedTitle: true };
69
+ }
70
+ if (ctx.single && /\.md$/i.test(name)) {
71
+ return { tool: 'other', kind: 'prompt', titleHint: stripExt(name, /\.md$/i) };
72
+ }
73
+ return null;
74
+ }
75
+ /**
76
+ * The prompt files under the requested path. Throws when nothing is there, when
77
+ * the path is a file that is not Markdown, or when there are more than
78
+ * {@link MAX_PICKS}. Files that match but must not be fetched (sensitive name,
79
+ * too large, odd path) are returned as `skipped` with the reason.
80
+ */
81
+ function selectPicks(snap, spec) {
82
+ const root = spec.path;
83
+ const single = root !== '' && snap.byPath.has(root);
84
+ const prefix = root === '' ? '' : `${root}/`;
85
+ const where = `github.com/${snap.repo}@${(0, format_1.safeText)(snap.ref)}`;
86
+ const inside = single ? [snap.byPath.get(root)] : snap.entries.filter((e) => e.path.startsWith(prefix));
87
+ if (!single && root !== '' && inside.length === 0) {
88
+ throw new Error(`Nothing at '${(0, format_1.safeText)(root)}' in ${where}.`);
89
+ }
90
+ if (single && !/\.mdc?$/i.test(root)) {
91
+ throw new Error(`'${(0, format_1.safeText)(root)}' is not a Markdown file — only .md and .mdc files can be imported.`);
92
+ }
93
+ // Files per folder, for "(+N files not imported)" next to a skill.
94
+ const perDir = new Map();
95
+ for (const e of snap.entries) {
96
+ if (/^(LICENSE|LICENCE|COPYING|NOTICE)/i.test(baseOf(e.path)))
97
+ continue;
98
+ for (let d = dirOf(e.path);; d = dirOf(d)) {
99
+ perDir.set(d, (perDir.get(d) ?? 0) + 1);
100
+ if (d === '')
101
+ break;
102
+ }
103
+ }
104
+ const maxPath = Math.min(MAX_FILE_PATH, MAX_ORIGIN_PATH - `github:${snap.repo}/`.length);
105
+ const picks = [];
106
+ const skipped = [];
107
+ for (const e of inside) {
108
+ if (e.mode === '120000')
109
+ continue; // a symlink's content is its target path
110
+ const rel = single ? baseOf(e.path) : e.path.slice(prefix.length);
111
+ const cls = classify(e.path, {
112
+ repoName: snap.name,
113
+ rootDir: root,
114
+ single,
115
+ depthBelowRoot: rel.split('/').length - 1,
116
+ });
117
+ if (!cls)
118
+ continue;
119
+ if ((0, secretGuard_1.isDeniedFileName)(e.path)) {
120
+ skipped.push({ path: e.path, reason: 'sensitive file name — never read' });
121
+ }
122
+ else if (ODD_PATH.test(e.path) || e.path.length > maxPath) {
123
+ skipped.push({ path: e.path, reason: 'path too long or with control characters — skipped' });
124
+ }
125
+ else if (e.size !== undefined && e.size > secretGuard_1.MAX_SCAN_FILE_BYTES) {
126
+ skipped.push({ path: e.path, reason: `larger than ${secretGuard_1.MAX_SCAN_FILE_BYTES / 1024} KB — skipped` });
127
+ }
128
+ else {
129
+ picks.push({
130
+ path: e.path,
131
+ blob: e.sha,
132
+ size: e.size,
133
+ tool: cls.tool,
134
+ kind: cls.kind,
135
+ titleHint: cls.titleHint,
136
+ fixedTitle: cls.fixedTitle === true,
137
+ extraFiles: cls.kind === 'skill' ? Math.max(0, (perDir.get(dirOf(e.path)) ?? 0) - 1) : 0,
138
+ });
139
+ }
140
+ }
141
+ if (picks.length > exports.MAX_PICKS) {
142
+ const hint = root ? `github:${snap.repo}/${root}/<folder>` : `github:${snap.repo}/<folder>`;
143
+ throw new Error(`Found ${picks.length} prompt files in ${where} — too many to import at once. Narrow it to a folder, e.g. ${hint}`);
144
+ }
145
+ // Code-unit order: the same on every machine (localeCompare depends on the ICU build).
146
+ picks.sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));
147
+ return { picks, skipped };
148
+ }
@@ -0,0 +1,67 @@
1
+ "use strict";
2
+ /**
3
+ * A public repo at one commit, as `ple import` and `ple import --check` read it:
4
+ * repo info + the commit a ref points to + the list of files, plus the two
5
+ * helpers that read files from it (candidates, license files) and the license
6
+ * gate bound to it. The network and the cache live in ./github.ts.
7
+ */
8
+ Object.defineProperty(exports, "__esModule", { value: true });
9
+ exports.loadSnapshot = loadSnapshot;
10
+ exports.readFile = readFile;
11
+ exports.gate = gate;
12
+ const github_1 = require("./github");
13
+ const licenses_1 = require("./licenses");
14
+ /** repo → ref → commit → tree: three counted API calls at most, none when the cache has them. */
15
+ async function loadSnapshot(owner, name, ref) {
16
+ const info = await (0, github_1.getRepo)(owner, name);
17
+ const use = ref ?? info.defaultBranch;
18
+ const [o, n] = info.fullName.split('/');
19
+ const commit = await (0, github_1.resolveCommit)(o, n, use);
20
+ const tree = await (0, github_1.getTree)(o, n, commit);
21
+ return {
22
+ info,
23
+ repo: info.fullName,
24
+ owner: o,
25
+ name: n,
26
+ ref: use,
27
+ commit,
28
+ entries: tree.entries,
29
+ byPath: new Map(tree.entries.map((e) => [e.path, e])),
30
+ licenseFiles: (0, licenses_1.indexLicenseFiles)(tree.entries.map((e) => e.path)),
31
+ licenseText: new Map(),
32
+ };
33
+ }
34
+ /**
35
+ * A repo file as text, or null when it is too large or not text. Network errors
36
+ * and the like throw. With `cache: false` the download is not kept on disk until
37
+ * the caller says so (see `rememberRaw`) — files that may still be refused stay off it.
38
+ */
39
+ async function readFile(snap, path, cache) {
40
+ try {
41
+ return await (0, github_1.fetchRaw)(snap.owner, snap.name, snap.commit, path, { cache });
42
+ }
43
+ catch (err) {
44
+ if (err instanceof github_1.GithubError && (err.kind === 'too_large' || err.kind === 'binary'))
45
+ return null;
46
+ throw err;
47
+ }
48
+ }
49
+ /** License files are fetched (and cached) once per run, however many prompts sit under them. */
50
+ function readLicenseText(snap, path) {
51
+ let hit = snap.licenseText.get(path);
52
+ if (!hit) {
53
+ hit = readFile(snap, path, true);
54
+ snap.licenseText.set(path, hit);
55
+ }
56
+ return hit;
57
+ }
58
+ /** The license gate for one file at this snapshot (shared by import and `--check`). */
59
+ function gate(snap, path, declared) {
60
+ return (0, licenses_1.checkLicense)({
61
+ repo: snap.repo,
62
+ commit: snap.commit,
63
+ repoLicense: snap.info.licenseSpdx,
64
+ licenseFiles: snap.licenseFiles,
65
+ readText: (p) => readLicenseText(snap, p),
66
+ }, path, declared);
67
+ }
@@ -0,0 +1,78 @@
1
+ "use strict";
2
+ /**
3
+ * `ple import github:owner/repo[/path][@ref]` — what the argument may look like.
4
+ *
5
+ * github:owner/repo github:owner/repo/sub/path …@ref (split at the LAST '@')
6
+ * https://github.com/o/r …/tree/<ref>/<path> …/blob/<ref>/<path>
7
+ *
8
+ * In the URL form the ref is ONE segment (that is how github.com writes it): a
9
+ * branch name containing '/' needs the `github:…@ref` form (or %2F in the URL).
10
+ * Every part is validated before it can reach a URL; anything else is refused
11
+ * with {@link SPEC_HELP}.
12
+ */
13
+ Object.defineProperty(exports, "__esModule", { value: true });
14
+ exports.SPEC_HELP = void 0;
15
+ exports.parseGithubSpec = parseGithubSpec;
16
+ const github_1 = require("./github");
17
+ exports.SPEC_HELP = 'Use github:<owner>/<repo>[/path][@ref], e.g. github:anthropics/skills/skills/pdf';
18
+ const MAX_SPEC_PATH = 512;
19
+ const MAX_REF = 200;
20
+ const BAD_SEGMENT_CHARS = /[\u0000-\u001f\u007f-\u009f\\]/;
21
+ const REF_RE = /^[A-Za-z0-9._/-]+$/;
22
+ const bad = () => {
23
+ throw new Error(exports.SPEC_HELP);
24
+ };
25
+ function validRef(ref) {
26
+ if (!ref || ref.length > MAX_REF || !REF_RE.test(ref) || ref.includes('..') || ref.includes('//') || ref.startsWith('/') || ref.endsWith('/')) {
27
+ return bad();
28
+ }
29
+ return ref;
30
+ }
31
+ function validParts(owner, repoRaw, pathSegments) {
32
+ const repo = repoRaw.replace(/\.git$/, '');
33
+ if (!github_1.OWNER_RE.test(owner) || !github_1.REPO_RE.test(repo) || repo === '.' || repo === '..')
34
+ return bad();
35
+ for (const s of pathSegments) {
36
+ if (s === '' || s === '.' || s === '..' || s.includes('/') || BAD_SEGMENT_CHARS.test(s))
37
+ return bad();
38
+ }
39
+ const path = pathSegments.join('/');
40
+ if (path.length > MAX_SPEC_PATH)
41
+ return bad();
42
+ return { owner, repo, path };
43
+ }
44
+ function parseGithubSpec(input) {
45
+ const raw = input.trim();
46
+ const url = raw.match(/^https:\/\/github\.com\/([^?#]*)/i);
47
+ if (url) {
48
+ let segs;
49
+ try {
50
+ segs = url[1].replace(/\/+$/, '').split('/').map(decodeURIComponent);
51
+ }
52
+ catch {
53
+ return bad();
54
+ }
55
+ if (segs.length < 2)
56
+ return bad();
57
+ const [owner, repo, kind, ref, ...rest] = segs;
58
+ if (segs.length === 2)
59
+ return { ...validParts(owner, repo, []), ref: null };
60
+ if ((kind !== 'tree' && kind !== 'blob') || ref === undefined)
61
+ return bad();
62
+ return { ...validParts(owner, repo, rest), ref: validRef(ref) };
63
+ }
64
+ const short = raw.match(/^github:(.+)$/i);
65
+ if (!short)
66
+ return bad();
67
+ let body = short[1];
68
+ let ref = null;
69
+ const at = body.lastIndexOf('@');
70
+ if (at !== -1) {
71
+ ref = validRef(body.slice(at + 1));
72
+ body = body.slice(0, at);
73
+ }
74
+ const [owner, repo, ...rest] = body.replace(/\/+$/, '').split('/');
75
+ if (repo === undefined)
76
+ return bad();
77
+ return { ...validParts(owner, repo, rest), ref };
78
+ }
@@ -0,0 +1,36 @@
1
+ "use strict";
2
+ /**
3
+ * What the account remembers about where its prompts came from:
4
+ * GET /api/prompts/import?include=origins → the sha256 of everything imported
5
+ * (`knownHashes`) and, from servers that know the parameter, one row per
6
+ * imported prompt with its provenance (`origins`). Older servers ignore the
7
+ * parameter and answer with `knownHashes` only; `origins` is then null.
8
+ *
9
+ * Rides on the loop module's bearer GET (api-client.ts is not touched);
10
+ * callers run `ensureAuthed()` first.
11
+ */
12
+ Object.defineProperty(exports, "__esModule", { value: true });
13
+ exports.fetchImportOrigins = fetchImportOrigins;
14
+ const loopApi_1 = require("./loopApi");
15
+ const isRecord = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
16
+ function toRow(raw) {
17
+ if (!isRecord(raw) || typeof raw.promptId !== 'string' || typeof raw.sha256 !== 'string')
18
+ return null;
19
+ let meta = null;
20
+ if (isRecord(raw.meta)) {
21
+ meta = {};
22
+ for (const [k, v] of Object.entries(raw.meta)) {
23
+ if (typeof v === 'string')
24
+ meta[k] = v;
25
+ }
26
+ }
27
+ return { promptId: raw.promptId, sha256: raw.sha256, path: typeof raw.path === 'string' ? raw.path : null, meta };
28
+ }
29
+ async function fetchImportOrigins() {
30
+ const res = await (0, loopApi_1.bearerGet)('/api/prompts/import?include=origins');
31
+ const hashes = Array.isArray(res.knownHashes) ? res.knownHashes.filter((h) => typeof h === 'string') : [];
32
+ const origins = Array.isArray(res.origins)
33
+ ? res.origins.map(toRow).filter((r) => r !== null)
34
+ : null;
35
+ return { knownHashes: new Set(hashes), origins };
36
+ }