@shotik/mcp 0.1.0 → 0.1.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.
@@ -0,0 +1,314 @@
1
+ // GENERATED by brain/storecheck/build.mjs from categories/classify-core.mjs and storecheck/storecheck.mjs. Do not edit.
2
+ // Store check for browsers: import { storeCheck } from "./storecheck.browser.js" (serve packs/ next to it, or pass loadPack/loadTaxonomy).
3
+
4
+ // ---- classify-core.mjs ----
5
+ // Category classifier core (APPC-10): pure ESM with no Node imports, so it runs in a browser. classify.mjs wraps it for Node
6
+ // (loads taxonomy.json from disk); browsers and other hosts call useTaxonomy(tax) once, or pass the compiled taxonomy.
7
+ // Pure and synchronous: no network, no file reads after the taxonomy is loaded once. Interface agreed with APPC-8
8
+ // (handoffs/brain/APPC-8-interfaces.md, APPC-10-to-APPC-8.md).
9
+ // Profile: { app: { name, subtitle, appstore_category, description, iaps: [{ name, price }], paywall? }, facts?: [{ text }], chapters?: [] }.
10
+ let TAX = null;
11
+ export function useTaxonomy(tax) { TAX = compile(tax); return TAX; }
12
+ export function currentTaxonomy() {
13
+ if (!TAX) throw new Error("classify: no taxonomy loaded; call useTaxonomy(taxonomy) first");
14
+ return TAX;
15
+ }
16
+
17
+ // The first part of a description says what the app is; the rest is feature lists and legal text. 1,500 characters keeps
18
+ // accuracy and holds classify() under 5 ms at p95 (eval/RESULTS.md).
19
+ const DESC_CHARS = 1500;
20
+ const FIELD_WEIGHT = { name: 4, subtitle: 3, chapters: 1.5, iaps: 1, description: 1 };
21
+ export const norm = (s) => " " + String(s || "").toLowerCase().replace(/&/g, " and ").replace(/[’']/g, "").replace(/[^\p{L}\p{N}+]+/gu, " ").replace(/\s+/g, " ").trim() + " ";
22
+ const slugify = (s) => String(s || "").toLowerCase().replace(/&/g, "and").replace(/[^a-z]+/g, "-").replace(/^-|-$/g, "");
23
+ const esc = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
24
+ // A keyword matches at a word start and may take a plural or -ing ending: "language" matches "languages", "ai" does not match "aid".
25
+ const ENDINGS = ["", "s", "es", "ing", "er", "ers", "ed"];
26
+ const kw = (k) => { k = k.trim(); return k.includes(" ") ? { k, re: new RegExp(" " + esc(k) + "(s|es|ing|ers?|ed)? ") } : { k, forms: ENDINGS.map((e) => k + e) }; };
27
+ // A field is its normalised text plus its set of words: one-word keywords are set lookups, phrases a regex over the text.
28
+ const field = (s) => { const text = norm(s); return { text, words: new Set(text.split(" ")) }; };
29
+ const has = (f, k) => k.forms ? k.forms.some((w) => f.words.has(w)) : k.re.test(f.text);
30
+
31
+ export function compile(tax) {
32
+ const cats = tax.categories.map((c) => ({
33
+ id: c.id, label: c.label, appstore: (c.appstore || []).map(slugify),
34
+ keywords: [...new Set((c.keywords || []).map(norm))].filter((k) => k.trim()).map(kw),
35
+ negative: [...new Set((c.negative_keywords || []).map(norm))].filter((k) => k.trim()).map(kw),
36
+ subtypes: (c.subtypes || []).map((s) => typeof s === "string" ? { id: s } : s)
37
+ .map((s) => ({ id: s.id, signals: [...new Set((s.signals || []).concat(s.keywords || []).concat(s.id.split(".")[1].split("-")).map(norm))].filter((k) => k.trim().length > 2).map(kw) })),
38
+ }));
39
+ return { raw: tax, cats };
40
+ }
41
+
42
+ function fields(profile) {
43
+ const app = profile.app || profile;
44
+ const chapters = [...(profile.chapters || app.chapters || []), ...(profile.facts || []).map((f) => f.text)];
45
+ return {
46
+ name: field(app.name), subtitle: field(app.subtitle),
47
+ description: field(String(app.description || "").slice(0, DESC_CHARS)),
48
+ chapters: field(chapters.join(" . ")),
49
+ iaps: field((app.iaps || []).map((i) => i.name).join(" . ")),
50
+ fullDescription: norm(app.description),
51
+ };
52
+ }
53
+
54
+ function scoreCats(f, appstore, tax) {
55
+ const store = slugify(appstore);
56
+ return tax.cats.map((c) => {
57
+ let score = 0; const basis = [];
58
+ for (const [field, w] of Object.entries(FIELD_WEIGHT)) {
59
+ const text = f[field];
60
+ if (!text.text.trim()) continue;
61
+ let hits = 0;
62
+ for (const k of c.keywords) if (has(text, k)) { hits++; if (basis.length < 6) basis.push({ field, value: k.k }); }
63
+ for (const k of c.negative) if (has(text, k)) hits -= 1;
64
+ score += w * Math.sign(hits) * Math.sqrt(Math.abs(hits));
65
+ }
66
+ const si = c.appstore.indexOf(store);
67
+ if (si >= 0) { score += si === 0 ? 1.5 : 0.75; basis.unshift({ field: "appstore_category", value: appstore }); }
68
+ return { id: c.id, score, basis, cat: c };
69
+ }).sort((a, b) => b.score - a.score);
70
+ }
71
+
72
+ // The best subtype by weighted signal hits, with the runner-up's score: a lone description hit or a near tie is a weak guess.
73
+ function subtypeOf(cat, f) {
74
+ let best = null, bestScore = 0, second = 0;
75
+ for (const s of cat.subtypes) {
76
+ let sc = 0;
77
+ for (const [field, w] of Object.entries(FIELD_WEIGHT)) for (const k of s.signals) if (has(f[field], k)) sc += w;
78
+ if (sc > bestScore) { second = bestScore; best = s.id; bestScore = sc; } else if (sc > second) second = sc;
79
+ }
80
+ return { id: best, score: bestScore, second };
81
+ }
82
+
83
+ const PER = [[/week|7 day/, 52 / 12], [/year|annual|12 month/, 1 / 12], [/6 month|half/, 1 / 6], [/3 month|quarter/, 1 / 3], [/month/, 1]];
84
+ export function monthly(iap) {
85
+ const p = parseFloat(String(iap.price || "").replace(/[^0-9.]/g, ""));
86
+ if (!p) return null;
87
+ const n = String(iap.name || "").toLowerCase();
88
+ if (/lifetime|forever|one[- ]time/.test(n)) return null;
89
+ for (const [re, k] of PER) if (re.test(n)) return p * k;
90
+ return null;
91
+ }
92
+
93
+ function businessModel(profile, f) {
94
+ const app = profile.app || profile;
95
+ const iaps = app.iaps || [];
96
+ const all = f.fullDescription + f.iaps.text + f.chapters.text;
97
+ const sub = /subscri|auto renew|renews|per month|per year|weekly|annual|yearly|monthly|membership/.test(all) || iaps.some((i) => monthly(i) != null);
98
+ const lifetime = /lifetime/.test(all);
99
+ const credits = /\b(credits|coins|gems|tokens|diamonds|boosts|super likes)\b/.test(f.iaps.text) || /\b(buy|purchase) (credits|coins|gems)\b/.test(f.description.text);
100
+ const ads = /\bads\b|advert|ad free|remove ads/.test(all);
101
+ const kind = sub ? (lifetime ? "subscription+lifetime" : "subscription") : credits ? "consumable" : iaps.length ? "one-time" : ads ? "ads" : null;
102
+ const pw = profile.paywall || app.paywall || null;
103
+ if (pw) {
104
+ const p = String(pw);
105
+ return { paywall: p.startsWith("hard") ? "hard" : p.startsWith("soft") ? "soft" : p.startsWith("none") ? "none" : null, trial: /trial/.test(p) ? !/no trial/.test(p) : null, kind };
106
+ }
107
+ const trial = /free trial|day trial|trial period|try (it )?(for )?free|days? free|free for \d/.test(all) ? true : null;
108
+ return { paywall: !sub && !credits ? (iaps.length ? "freemium" : "none") : null, trial, kind };
109
+ }
110
+
111
+ function pricePoint(profile) {
112
+ const m = ((profile.app || profile).iaps || []).map(monthly).filter((x) => x != null);
113
+ if (!m.length) return null;
114
+ const v = Math.max(...m);
115
+ return v < 5 ? "low" : v <= 15 ? "mid" : "high";
116
+ }
117
+
118
+ export function classify(profile, tax = currentTaxonomy()) {
119
+ const app = profile.app || profile;
120
+ const f = fields(profile);
121
+ const scored = scoreCats(f, app.appstore_category, tax);
122
+ const [top, second] = scored;
123
+ const margin = top.score - (second?.score || 0);
124
+ const confidence = top.score <= 1 ? "low" : margin >= 3 && top.score >= 4 ? "high" : margin >= 1.2 ? "medium" : "low";
125
+ const st = subtypeOf(top.cat, f), subtype = st.id;
126
+ const subtype_confidence = !subtype || confidence === "low" ? "low" : st.score >= 4 && st.score >= 2 * st.second ? "high" : st.score >= 2 && st.score > st.second ? "medium" : "low";
127
+ return {
128
+ category: subtype || top.id, group: top.id, subtype,
129
+ model: businessModel(profile, f), price_point: pricePoint(profile), confidence, subtype_confidence,
130
+ basis: top.basis,
131
+ alternates: scored.slice(1, 3).filter((s) => s.score > 0).map((s) => ({ category: s.id, score: +s.score.toFixed(2) })),
132
+ score: +top.score.toFixed(2),
133
+ };
134
+ }
135
+
136
+ // Groups an evidence row belongs to: its own tag's group, or for an untagged/"all" row with an App Store slug, every group that
137
+ // App Store category feeds (a parent-level row there). [] = cross-category.
138
+ export function rowGroups(row, tax = currentTaxonomy()) {
139
+ const tag = String(row.category || "").trim();
140
+ if (tag && tag !== "all" && tag !== "other") { const g = tag.split(".")[0]; if (tax.cats.some((c) => c.id === g)) return [g]; }
141
+ const sc = String(row.store_category || "").split(",").map(slugify).filter(Boolean);
142
+ return sc.length ? tax.cats.filter((c) => c.appstore.some((a) => sc.includes(a))).map((c) => c.id) : [];
143
+ }
144
+
145
+ // ---- storecheck.mjs ----
146
+ // Store check (APPC-10): what Apple's public data and the brain can honestly say about one App Store app.
147
+ // Pure ESM with no Node imports: the site (in the browser), the app and @shotik/mcp run the same code. Types: storecheck.d.ts.
148
+ //
149
+ // import { storeCheck } from "./storecheck.mjs";
150
+ // const r = await storeCheck("https://apps.apple.com/us/app/walkito/id6813076846", { lang: "ru" });
151
+ //
152
+ // Steps: parse the link or id; Apple's lookup API (iTunes Search API) for the listing; the customer-review RSS; the screenshots
153
+ // from the lookup; classify() from classify-core.mjs over name, description and genre; then the category's pack (packs/<group>.json,
154
+ // loaded lazily) for norms, key points and top apps. In-app purchase prices are not in any public, browser-readable Apple API,
155
+ // so the result never states them; nothing here reads the founder's build, keys or analytics.
156
+
157
+ export const VERSION = "1";
158
+ const LOOKUP = "https://itunes.apple.com/lookup";
159
+ const SEARCH = "https://itunes.apple.com/search";
160
+ const RSS = (cc, id) => `https://itunes.apple.com/${cc}/rss/customerreviews/page=1/id=${id}/sortby=mostrecent/json`;
161
+ const DAY = 86400000;
162
+
163
+ // Data: packs/taxonomy.json and packs/<group>.json next to this file, imported as JSON modules (Node 22+, current browsers).
164
+ // Hosts that serve them elsewhere pass loadPack/loadTaxonomy.
165
+ const here = (f) => new URL("./packs/" + f, import.meta.url).href;
166
+ const importJSON = async (url) => (await import(/* @vite-ignore */ url, { with: { type: "json" } })).default;
167
+ const defaults = { loadTaxonomy: () => importJSON(here("taxonomy.json")), loadPack: (group) => importJSON(here(group + ".json")) };
168
+
169
+ // "https://apps.apple.com/us/app/walkito/id6813076846", "id6813076846", "6813076846" -> { id, country }; anything else -> { term }.
170
+ export function parseInput(input, country = "us") {
171
+ const s = String(input || "").trim();
172
+ const url = s.match(/apps\.apple\.com\/([a-z]{2})\/(?:[^\s?#]*\/)?id(\d{6,12})/i);
173
+ if (url) return { id: url[2], country: url[1].toLowerCase() };
174
+ const id = s.match(/^(?:id)?(\d{6,12})$/i);
175
+ if (id) return { id: id[1], country };
176
+ return s ? { term: s, country } : { error: "empty" };
177
+ }
178
+
179
+ // fetch first; if the browser blocks it (CORS) and the endpoint speaks JSONP (lookup and search do), use a script tag.
180
+ async function getJSON(url, { fetch: f = globalThis.fetch, jsonp = true, timeoutMs = 8000 } = {}) {
181
+ try {
182
+ const ctl = typeof AbortController !== "undefined" ? new AbortController() : null;
183
+ const t = ctl && setTimeout(() => ctl.abort(), timeoutMs);
184
+ const res = await f(url, ctl ? { signal: ctl.signal } : undefined);
185
+ if (t) clearTimeout(t);
186
+ if (!res.ok) return { error: "http " + res.status };
187
+ return { data: await res.json(), via: "fetch" };
188
+ } catch (e) {
189
+ if (!jsonp || typeof document === "undefined" || !/itunes\.apple\.com\/(lookup|search)/.test(url)) return { error: String(e?.message || e) };
190
+ return new Promise((resolve) => {
191
+ const cb = "__shotikStoreCheck" + Math.random().toString(36).slice(2);
192
+ const el = document.createElement("script");
193
+ const done = (out) => { delete globalThis[cb]; el.remove(); clearTimeout(timer); resolve(out); };
194
+ const timer = setTimeout(() => done({ error: "jsonp timeout" }), timeoutMs);
195
+ globalThis[cb] = (data) => done({ data, via: "jsonp" });
196
+ el.onerror = () => done({ error: "jsonp failed" });
197
+ el.src = url + (url.includes("?") ? "&" : "?") + "callback=" + cb;
198
+ document.head.appendChild(el);
199
+ });
200
+ }
201
+ }
202
+
203
+ const TRIAL = /free trial|(\d+|one|three|seven|fourteen)[- ]day (free )?trial|trial period|try (it )?(for )?free|start (your )?(free )?trial|days? free\b/i;
204
+ const SUBS = /subscription|auto[- ]?renew|renews automatically|membership|premium|pro version/i;
205
+ const TERMS = /terms of (use|service)|privacy policy|eula/i;
206
+ const MONEY_REVIEW = /price|pric(e|ey)|expensive|cheap|charg|subscri|cancel|refund|paywall|trial|pay(ing|wall)?\b|money|\$\d|cost/i;
207
+ const t2 = (en, ru) => ({ en, ru });
208
+ const plural = (n, one, few, many) => { const m = Math.abs(n) % 100; if (m >= 11 && m <= 14) return many; const d = m % 10; return d === 1 ? one : d >= 2 && d <= 4 ? few : many; };
209
+
210
+ function listingOf(x) {
211
+ return {
212
+ id: String(x.trackId), name: x.trackName, developer: x.sellerName || x.artistName, url: x.trackViewUrl?.split("?")[0] || null,
213
+ icon: x.artworkUrl512 || x.artworkUrl100 || null, genre: x.primaryGenreName || null, genres: x.genres || [],
214
+ version: x.version || null, updated: x.currentVersionReleaseDate || null, released: x.releaseDate || null,
215
+ rating: x.averageUserRating != null ? +x.averageUserRating.toFixed(2) : null, ratings: x.userRatingCount ?? null,
216
+ rating_current_version: x.averageUserRatingForCurrentVersion != null ? +x.averageUserRatingForCurrentVersion.toFixed(2) : null,
217
+ price: x.price ?? null, formatted_price: x.formattedPrice || null, currency: x.currency || null,
218
+ content_rating: x.contentAdvisoryRating || null, languages: x.languageCodesISO2A || [], min_os: x.minimumOsVersion || null,
219
+ size_bytes: x.fileSizeBytes ? Number(x.fileSizeBytes) : null,
220
+ screenshots: { iphone: x.screenshotUrls || [], ipad: x.ipadScreenshotUrls || [] },
221
+ description: x.description || "", release_notes: x.releaseNotes || "",
222
+ };
223
+ }
224
+
225
+ async function reviewsOf(id, country, opts) {
226
+ const url = RSS(country, id);
227
+ const r = await getJSON(url, { ...opts, jsonp: false });
228
+ if (r.error) return { available: false, why: r.error, url };
229
+ const entries = [].concat(r.data?.feed?.entry || []).filter((e) => e?.["im:rating"]);
230
+ const items = entries.map((e) => ({ rating: +e["im:rating"].label, title: e.title?.label || "", text: e.content?.label || "", author: e.author?.name?.label || null, version: e["im:version"]?.label || null, updated: e.updated?.label || null }));
231
+ const money = items.filter((i) => MONEY_REVIEW.test(i.title + " " + i.text));
232
+ const short = (s) => s.length > 220 ? s.slice(0, 217).replace(/\s+\S*$/, "") + "…" : s;
233
+ return { available: true, url, recent: items.length, avg_recent: items.length ? +(items.reduce((a, i) => a + i.rating, 0) / items.length).toFixed(2) : null,
234
+ money_mentions: money.length, quotes: money.sort((a, b) => a.rating - b.rating).slice(0, 2).map((i) => ({ ...i, text: short(i.text) })) };
235
+ }
236
+
237
+ // Signals compare what the listing shows with what the category's recorded apps do. Each says which side it rests on.
238
+ function signalsOf(L, pack, now) {
239
+ const out = [], text = L.description + "\n" + L.release_notes;
240
+ const trial = TRIAL.test(text);
241
+ const n = pack?.norms?.trial_share;
242
+ if (n) out.push({ id: "trial-wording", lever: "trial-terms", listing: { mentions_trial: trial },
243
+ text: t2(`${n.value} of recorded ${pack.label} paywalls offer a free trial (n=${n.n}). Your description ${trial ? "mentions" : "does not mention"} a trial.`,
244
+ `${n.value.replace(".", ",")} записанных пейволов в категории «${pack.label}» предлагают бесплатный триал (n=${n.n}). В вашем описании триал ${trial ? "упомянут" : "не упомянут"}.`),
245
+ refs: [n.ref] });
246
+ const subs = SUBS.test(text), terms = TERMS.test(text);
247
+ out.push({ id: "subscription-terms", lever: "price-framing", listing: { mentions_subscription: subs, links_terms: terms },
248
+ text: t2(`Description ${subs ? "mentions" : "does not mention"} a subscription and ${terms ? "names" : "does not name"} terms or a privacy policy.`,
249
+ `В описании подписка ${subs ? "упомянута" : "не упомянута"}, условия или политика конфиденциальности ${terms ? "указаны" : "не указаны"}.`), refs: [] });
250
+ if (L.updated) {
251
+ const d = Math.max(0, Math.round((now - Date.parse(L.updated)) / DAY));
252
+ out.push({ id: "last-update", lever: "retention-hooks", listing: { days_since_update: d, version: L.version },
253
+ text: t2(`Last update ${d} day${d === 1 ? "" : "s"} ago (version ${L.version}).`, `Последнее обновление ${d} ${plural(d, "день", "дня", "дней")} назад (версия ${L.version}).`), refs: [] });
254
+ }
255
+ const shots = L.screenshots.iphone.length;
256
+ out.push({ id: "screenshots", lever: "value-moment", listing: { iphone: shots, ipad: L.screenshots.ipad.length },
257
+ text: t2(`${shots} iPhone screenshot${shots === 1 ? "" : "s"} on the listing.`, `На странице ${shots} ${plural(shots, "скриншот", "скриншота", "скриншотов")} для iPhone.`), refs: [] });
258
+ if (L.ratings != null) out.push({ id: "rating", lever: "social-proof", listing: { rating: L.rating, ratings: L.ratings },
259
+ text: t2(`Rated ${L.rating} from ${L.ratings} ratings.`, `Рейтинг ${String(L.rating).replace(".", ",")} по ${L.ratings} ${plural(L.ratings, "оценке", "оценкам", "оценкам")}.`), refs: [] });
260
+ return out;
261
+ }
262
+
263
+ const LOCKED = [
264
+ { id: "persona-walk", text: t2("Walk your onboarding as 40 people: needs your build, on your Mac.", "Пройти ваш онбординг глазами 40 людей: нужна ваша сборка, на вашем Mac.") },
265
+ { id: "leak-pricing", text: t2("Price each leak in $/month: needs your analytics, on your Mac.", "Оценить каждую утечку в $ в месяц: нужна ваша аналитика, на вашем Mac.") },
266
+ { id: "branch-fix", text: t2("Fix it in a branch: needs your code, on your Mac.", "Исправить в ветке: нужен ваш код, на вашем Mac.") },
267
+ ];
268
+
269
+ export async function storeCheck(input, opts = {}) {
270
+ const t0 = Date.now(), now = opts.now ? +new Date(opts.now) : Date.now();
271
+ const lang = opts.lang === "ru" ? "ru" : "en";
272
+ const q = parseInput(input, opts.country || "us");
273
+ const base = { version: VERSION, input: String(input ?? ""), lang, checked_at: new Date(now).toISOString() };
274
+ if (q.error) return { ...base, ok: false, error: "empty-input" };
275
+ let raw = opts.lookup || null, via = opts.lookup ? "given" : null;
276
+ if (!raw) {
277
+ const url = q.id ? `${LOOKUP}?id=${q.id}&country=${q.country}&entity=software` : `${SEARCH}?term=${encodeURIComponent(q.term)}&country=${q.country}&entity=software&limit=1`;
278
+ const r = await getJSON(url, opts);
279
+ if (r.error) return { ...base, ok: false, error: "lookup-failed", detail: r.error };
280
+ raw = r.data; via = r.via;
281
+ }
282
+ const x = (raw.results || []).find((r) => r.wrapperType === "software" || r.kind === "software") || (raw.results || [])[0];
283
+ if (!x) return { ...base, ok: false, error: "not-found", country: q.country };
284
+ const L = listingOf(x), country = q.country;
285
+
286
+ const tax = opts.taxonomy || await (opts.loadTaxonomy || defaults.loadTaxonomy)();
287
+ const compiled = useTaxonomy(tax);
288
+ const c = classify({ app: { name: L.name, subtitle: "", appstore_category: L.genre, description: L.description, iaps: [] } }, compiled);
289
+ const [pack, reviews] = await Promise.all([
290
+ (opts.loadPack || defaults.loadPack)(c.group).catch(() => null),
291
+ opts.reviews === false ? { available: false, why: "skipped" } : reviewsOf(L.id, country, opts),
292
+ ]);
293
+ // A subtype is shown only when the classifier is sure of it (high: 174 of 188 right on the eval set; medium: 30 of 50).
294
+ // Otherwise the result names the group alone and uses group-wide apps, so no weak guess reaches a page.
295
+ const subtype = c.subtype_confidence === "high" ? c.subtype : null;
296
+ const sub = subtype && pack?.subtypes?.[subtype];
297
+ const top = subtype ? (pack?.top_apps || []).filter((a) => a.subtype === subtype) : [];
298
+ return {
299
+ ...base, ok: true, ms: Date.now() - t0, source: { lookup: via, country },
300
+ app: { ...L, description: L.description.slice(0, 600), release_notes: L.release_notes.slice(0, 400) },
301
+ category: { group: c.group, group_label: pack?.label || c.group, subtype, subtype_label: sub || null, confidence: c.confidence, subtype_confidence: c.subtype_confidence,
302
+ basis: c.basis, alternates: c.alternates, model: c.model },
303
+ iap: { known: false, why: t2("In-app purchase prices are not in Apple's public lookup; they stay unknown here.", "Цены встроенных покупок нет в публичных данных Apple, здесь они неизвестны.") },
304
+ signals: signalsOf(L, pack, now),
305
+ category_norms: pack ? { norms: pack.norms, key_points: pack.key_points, good_enough: pack.good_enough, top_apps: (top.length ? top : pack.top_apps).slice(0, 5) } : null,
306
+ reviews,
307
+ locked: LOCKED,
308
+ sources: pack?.sources || {},
309
+ hash: "#check=" + L.id + (country !== "us" ? "-" + country : ""),
310
+ };
311
+ }
312
+
313
+ // The text of a bilingual field in the result's language: pick(r.signals[0].text, r.lang).
314
+ export const pick = (t, lang = "en") => (t && typeof t === "object" ? t[lang] ?? t.en : t);
@@ -305,8 +305,9 @@ plain difference. It logs `[shotik-sample] configure_ms=…` and a `Shotik.confi
305
305
  or `.denied` also holds uploads.
306
306
  - **Screens are named after classes such as `UIHostingController<…>`.** SwiftUI screens need `.shotikScreen("Name")`
307
307
  or a navigation title.
308
- - **Messages sit at "Sending".** While offline they show "Queued" and the header counts them. They go out when the
309
- server is reachable, and after 3 failed attempts they show "Not sent · Retry".
308
+ - **Messages sit at "Sending".** While offline, or while the server is unreachable or answers 5xx/429, they show
309
+ "Will send when you're back online" (clock) and the header counts them; they go out on their own once the server is
310
+ reachable. Only a 4xx answer shows "Not sent · Retry".
310
311
  - **App Store privacy questions.** The privacy manifest ships in ShotikCore. Xcode merges it into the app's privacy
311
312
  report (Product → Archive → Generate Privacy Report).
312
313
 
@@ -311,8 +311,9 @@ ShotikAnalytics.optOut() // .denied: очистить очередь и нич
311
311
  Отправку держит и согласие `.pending` или `.denied`.
312
312
  - **Экраны называются по классам вроде `UIHostingController<…>`.** Экранам SwiftUI нужен `.shotikScreen("Имя")` или
313
313
  заголовок навигации.
314
- - **Сообщения висят в «Отправляется».** Без сети они помечены «В очереди», а в шапке виден их счётчик. Они уйдут,
315
- когда сервер станет доступен, а после 3 неудачных попыток покажут «Не отправлено · Повторить».
314
+ - **Сообщения висят в «Отправляется».** Без сети, а также пока сервер недоступен или отвечает 5xx/429, под ними
315
+ «Отправим, когда появится связь» (часы), а шапка показывает их число; уйдут сами, когда сервер станет доступен.
316
+ «Не отправлено · Повторить» появляется только при ответе 4xx.
316
317
  - **Вопросы о приватности в App Store.** Манифест приватности лежит в ShotikCore. Xcode добавляет его в отчёт о
317
318
  приватности приложения (Product → Archive → Generate Privacy Report).
318
319
 
@@ -14,7 +14,8 @@
14
14
  "Edit only the files a step names or detects. Never change signing, bundle ids, deployment targets or other build settings beyond what a step says.",
15
15
  "Replace {{VARS}} before writing. Keep edits minimal and idempotent: skip a step whose `done` check already passes.",
16
16
  "The SDK has zero dependencies; never add other packages for it. Never add NSAllowsArbitraryLoads.",
17
- "Generated projects (XcodeGen project.yml, Tuist Project.swift) are edited at the source, never in the generated .xcodeproj."
17
+ "Generated projects (XcodeGen project.yml, Tuist Project.swift) are edited at the source, never in the generated .xcodeproj.",
18
+ "In Shotik, run add-swift-package and plist-* edits through the ios_project tool (it edits project.pbxproj and plists the way Xcode does, idempotently). Without that tool, or when it returns an error, make the edit by hand as the step's how describes."
18
19
  ],
19
20
  "variables": {
20
21
  "APP_KEY": {
@@ -136,7 +137,19 @@
136
137
  "from": "0.1.0",
137
138
  "products": "{{PRODUCTS}}",
138
139
  "target": "{{detect.appTarget}}",
139
- "how": "XCRemoteSwiftPackageReference (repositoryURL = https://github.com/rahimwws/shotik-app, requirement { kind = upToNextMajorVersion; minimumVersion = 0.1.0; }) in the project's packageReferences, one XCSwiftPackageProductDependency per product (package = that reference) in the target's packageProductDependencies, and a PBXBuildFile with productRef in its Frameworks build phase. Same as Xcode's File → Add Package Dependencies… with the URL pasted in the search field."
140
+ "how": "XCRemoteSwiftPackageReference (repositoryURL = https://github.com/rahimwws/shotik-app, requirement { kind = upToNextMajorVersion; minimumVersion = 0.1.0; }) in the project's packageReferences, one XCSwiftPackageProductDependency per product (package = that reference) in the target's packageProductDependencies, and a PBXBuildFile with productRef in its Frameworks build phase. Same as Xcode's File → Add Package Dependencies… with the URL pasted in the search field.",
141
+ "tool": {
142
+ "name": "ios_project",
143
+ "args": {
144
+ "action": "add_swift_package",
145
+ "project": "<the .xcodeproj of detect.appTarget>",
146
+ "url": "https://github.com/rahimwws/shotik-app",
147
+ "minimumVersion": "0.1.0",
148
+ "products": "{{PRODUCTS}} split on commas",
149
+ "target": "{{detect.appTarget}}",
150
+ "replaceLocal": "when detect.legacy: [the Vendor/ShotikSDK path relative to the project]"
151
+ }
152
+ }
140
153
  },
141
154
  {
142
155
  "op": "yaml-set",
@@ -252,7 +265,19 @@
252
265
  "<lowercased app name, letters only>"
253
266
  ]
254
267
  }
255
- ]
268
+ ],
269
+ "tool": {
270
+ "name": "ios_project",
271
+ "args": {
272
+ "action": "plist",
273
+ "file": "the app target's Info.plist (or project.yml info.properties)",
274
+ "path": [
275
+ "CFBundleURLTypes"
276
+ ],
277
+ "value": "each entry of value",
278
+ "mode": "append"
279
+ }
280
+ }
256
281
  },
257
282
  {
258
283
  "op": "insert-before",
@@ -426,7 +451,20 @@
426
451
  "NSAppTransportSecurity",
427
452
  "NSAllowsLocalNetworking"
428
453
  ],
429
- "value": true
454
+ "value": true,
455
+ "tool": {
456
+ "name": "ios_project",
457
+ "args": {
458
+ "action": "plist",
459
+ "file": "the app target's Info.plist",
460
+ "path": [
461
+ "NSAppTransportSecurity",
462
+ "NSAllowsLocalNetworking"
463
+ ],
464
+ "value": true,
465
+ "mode": "set"
466
+ }
467
+ }
430
468
  }
431
469
  ],
432
470
  "note": "Only for LAN or .local addresses; production uses HTTPS. Never add NSAllowsArbitraryLoads."
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@shotik/mcp",
3
- "version": "0.1.0",
3
+ "version": "0.1.1",
4
4
  "description": "MCP server with Shotik's SDK install recipes, guides and protocol, so coding agents add Shotik Support and Analytics to an app themselves.",
5
5
  "keywords": [
6
6
  "mcp",
package/server.mjs CHANGED
@@ -1,12 +1,13 @@
1
1
  #!/usr/bin/env node
2
2
  // @shotik/mcp: Shotik's SDK install recipes, guides and wire protocol over MCP (stdio), so any coding agent can add
3
- // Shotik Support and Analytics to an app by itself.
3
+ // Shotik Support and Analytics to an app by itself, plus the store check (brain/storecheck, CONVERSION.md app item 6).
4
4
  // npx -y @shotik/mcp
5
5
  // claude mcp add shotik -- npx -y @shotik/mcp
6
- // Newline-delimited JSON-RPC 2.0 on stdin/stdout; nothing else is written to stdout. No dependencies, no network.
6
+ // Newline-delimited JSON-RPC 2.0 on stdin/stdout; nothing else is written to stdout. No dependencies. The only network
7
+ // calls are store_check's reads of Apple's public lookup and review RSS.
7
8
  import { existsSync, readFileSync, readdirSync } from 'node:fs'
8
9
  import { dirname, join, resolve } from 'node:path'
9
- import { fileURLToPath } from 'node:url'
10
+ import { fileURLToPath, pathToFileURL } from 'node:url'
10
11
  import readline from 'node:readline'
11
12
 
12
13
  const here = dirname(fileURLToPath(import.meta.url))
@@ -55,6 +56,19 @@ function detect(path) {
55
56
  return { path: root, matches: found.map((f) => ({ ...f, install: sdkOf(f.sdk).install, recipe: 'get_recipe { "sdk": "' + f.sdk + '" }' })), hint: found.length ? undefined : 'No React Native, Flutter or iOS project at this path. Pass the app folder as path.' }
56
57
  }
57
58
 
59
+ // The shared store check, vendored as one file plus its category packs (bundled into data/storecheck at pack time).
60
+ const checkDir = existsSync(join(here, 'data')) ? join(data, 'storecheck') : resolve(here, '..', SOURCES.storecheck)
61
+ const pack = async (name) => JSON.parse(readFileSync(join(checkDir, 'packs', name.replace(/[^a-z0-9-]/g, '') + '.json'), 'utf8'))
62
+ let checker
63
+ async function storeCheck(a) {
64
+ checker ??= import(pathToFileURL(join(checkDir, 'storecheck.browser.js')).href)
65
+ const lang = a.lang === 'ru' ? 'ru' : 'en'
66
+ const r = await (await checker).storeCheck(String(a.app ?? ''), { lang, country: a.country, loadTaxonomy: () => pack('taxonomy'), loadPack: pack })
67
+ if (!r.ok) throw new Error({ 'empty-input': 'Pass an App Store link, an id or the app name.', 'not-found': 'No App Store app matches "' + a.app + '".', 'lookup-failed': "Couldn't reach Apple's App Store lookup" + (r.detail ? ': ' + r.detail : '') + '. Try again.' }[r.error] ?? r.error)
68
+ const link = 'shotik://continue?' + new URLSearchParams({ store: r.app.id, lang, ref: 'mcp' })
69
+ return JSON.stringify(r, null, 2) + '\n\n' + (lang === 'ru' ? 'Посмотрите это на своих экранах в Shotik: ' : 'See it on your screens in Shotik: ') + link
70
+ }
71
+
58
72
  const sdkArg = { type: 'string', enum: ids, description: 'Which SDK: ' + SDKS.map((s) => s.id + ' (' + s.title + ')').join(', ') }
59
73
  const langArg = { type: 'string', enum: ['en', 'ru'], description: 'Language of the guide and README (default en)' }
60
74
  const TOOLS = [
@@ -73,6 +87,9 @@ const TOOLS = [
73
87
  } },
74
88
  { name: 'get_protocol', description: 'The Shotik SDK wire protocol (PROTOCOL.md): endpoints, payloads, storage keys and behaviour every SDK follows. Read it to build or debug an SDK, not to install one.', inputSchema: { type: 'object', properties: {} },
75
89
  run: () => read(SOURCES.protocol) },
90
+ { name: 'store_check', description: "Check an app's App Store listing against its category: listing facts, category and subtype, what the top apps in that subtype do on onboarding and paywall, trial and subscription wording, days since the last update, screenshots, rating and recent reviews. Reads Apple's public lookup and review RSS; in-app purchase prices are never known, so never state them. Show the user the signals and key points in their language, then end with the last line of the result (\"See it on your screens in Shotik\" and its shotik://continue link) exactly as given.",
91
+ inputSchema: { type: 'object', properties: { app: { type: 'string', description: 'App Store link, id123, a bare id, or the app name' }, lang: { type: 'string', enum: ['en', 'ru'], description: 'Language of the answer and of the Shotik link (default en)' }, country: { type: 'string', description: 'Two-letter storefront for an id or a name (default us; a link keeps its own)' } }, required: ['app'] },
92
+ run: storeCheck },
76
93
  ]
77
94
 
78
95
  const RESOURCES = [
@@ -85,11 +102,13 @@ const RESOURCES = [
85
102
  ].filter(Boolean)),
86
103
  ].filter((r) => has(r.file))
87
104
 
88
- const INSTRUCTIONS = 'Shotik adds in-app support chat and product analytics to mobile apps. To integrate: call detect_project on the app folder, then get_recipe for the SDK it names and follow the steps in order (each step has a done check, so re-running is safe). Ask the user for APP_KEY (Shotik → Support → SDK, spk_…, safe to ship) and SERVER_URL. Install from the registry (' + SDKS.map((s) => s.install).join('; ') + '), never by copying SDK folders.'
105
+ const INSTRUCTIONS = 'Shotik adds in-app support chat and product analytics to mobile apps. To integrate: call detect_project on the app folder, then get_recipe for the SDK it names and follow the steps in order (each step has a done check, so re-running is safe). Ask the user for APP_KEY (Shotik → Support → SDK, spk_…, safe to ship) and SERVER_URL. Install from the registry (' + SDKS.map((s) => s.install).join('; ') + '), never by copying SDK folders. To review an App Store listing against its category, call store_check.'
89
106
 
90
107
  const send = (m) => process.stdout.write(JSON.stringify(m) + '\n')
91
108
  const text = (v) => ({ content: [{ type: 'text', text: typeof v === 'string' ? v : JSON.stringify(v, null, 2) }] })
92
109
 
110
+ const inflight = new Set()
111
+
93
112
  function handle(msg) {
94
113
  const { id, method, params = {} } = msg
95
114
  if (id === undefined || id === null) return
@@ -103,7 +122,9 @@ function handle(msg) {
103
122
  case 'tools/call': {
104
123
  const t = TOOLS.find((x) => x.name === params.name)
105
124
  if (!t) return fail(-32602, 'Unknown tool: ' + params.name)
106
- try { return ok(text(t.run(params.arguments || {}))) } catch (e) { return ok({ ...text(e.message), isError: true }) }
125
+ const p = Promise.resolve().then(() => t.run(params.arguments || {})).then((v) => ok(text(v)), (e) => ok({ ...text(e.message), isError: true }))
126
+ inflight.add(p)
127
+ return void p.finally(() => inflight.delete(p))
107
128
  }
108
129
  case 'resources/list': return ok({ resources: RESOURCES.map(({ file, ...r }) => r) })
109
130
  case 'resources/read': {
@@ -120,4 +141,4 @@ readline.createInterface({ input: process.stdin }).on('line', (line) => {
120
141
  let msg
121
142
  try { msg = JSON.parse(line) } catch { return send({ jsonrpc: '2.0', id: null, error: { code: -32700, message: 'Parse error' } }) }
122
143
  handle(msg)
123
- }).on('close', () => process.exit(0))
144
+ }).on('close', () => Promise.allSettled(inflight).then(() => process.exit(0)))
package/sources.json CHANGED
@@ -1,5 +1,6 @@
1
1
  {
2
2
  "protocol": "PROTOCOL.md",
3
+ "storecheck": "../brain/storecheck",
3
4
  "sdks": [
4
5
  {
5
6
  "id": "react-native",