@shotik/mcp 0.0.0-stage → 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.
- package/LICENSE +21 -0
- package/README.md +40 -2
- package/README.ru.md +40 -0
- package/data/PROTOCOL.md +386 -0
- package/data/flutter/INTEGRATION.md +197 -0
- package/data/flutter/README.md +112 -0
- package/data/flutter/README.ru.md +165 -0
- package/data/flutter/guide.json +190 -0
- package/data/flutter/recipe.json +364 -0
- package/data/react-native/README.md +194 -0
- package/data/react-native/README.ru.md +192 -0
- package/data/react-native/guide.json +136 -0
- package/data/react-native/recipe.json +263 -0
- package/data/react-native/src/analytics/README.md +32 -0
- package/data/react-native/src/analytics/recipe.json +263 -0
- package/data/storecheck/packs/ai.json +1 -0
- package/data/storecheck/packs/dating.json +1 -0
- package/data/storecheck/packs/education.json +1 -0
- package/data/storecheck/packs/finance.json +1 -0
- package/data/storecheck/packs/fitness.json +1 -0
- package/data/storecheck/packs/health.json +1 -0
- package/data/storecheck/packs/kids.json +1 -0
- package/data/storecheck/packs/language.json +1 -0
- package/data/storecheck/packs/mindfulness.json +1 -0
- package/data/storecheck/packs/music.json +1 -0
- package/data/storecheck/packs/nutrition.json +1 -0
- package/data/storecheck/packs/photo-video.json +1 -0
- package/data/storecheck/packs/productivity.json +1 -0
- package/data/storecheck/packs/spirituality.json +1 -0
- package/data/storecheck/packs/taxonomy.json +1 -0
- package/data/storecheck/packs/utilities.json +1 -0
- package/data/storecheck/storecheck.browser.js +314 -0
- package/data/swift/README.md +327 -0
- package/data/swift/README.ru.md +333 -0
- package/data/swift/guide.json +189 -0
- package/data/swift/recipe.json +506 -0
- package/package.json +42 -4
- package/server.mjs +144 -0
- package/sources.json +86 -0
|
@@ -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);
|
|
@@ -0,0 +1,327 @@
|
|
|
1
|
+
# Shotik SDK for Swift
|
|
2
|
+
|
|
3
|
+
In-app support chat and product analytics for iOS and macOS apps that talk to a Shotik server. Users write from your
|
|
4
|
+
app and the conversation lands in Shotik's Support inbox on your Mac, where you (or the AI) answer. Analytics records
|
|
5
|
+
screens, taps, scroll depth, stalls, crashes and purchases, and draws wireframes for the screens it sees.
|
|
6
|
+
|
|
7
|
+
- Four SwiftPM libraries, so an app links only what it uses: `ShotikCore` (configure, identity, storage, transport),
|
|
8
|
+
`ShotikSupport` (the chat client), `ShotikSupportUI` (the SwiftUI widget) and `ShotikAnalytics`.
|
|
9
|
+
- iOS 15+ and macOS 12+, Swift 6 with strict concurrency, zero dependencies. No fonts, images or third-party code.
|
|
10
|
+
- `configure` returns in well under a millisecond. Storage, network and JSON run on one background queue, so nothing
|
|
11
|
+
touches disk or the network on the main thread.
|
|
12
|
+
- Automatic capture with no swizzling: one passive gesture recognizer per window, scene notifications, a 500 ms main
|
|
13
|
+
queue watchdog and StoreKit 2 transactions.
|
|
14
|
+
- Wire, state and storage compatible with the React Native SDK (`PROTOCOL.md`). Both SDKs read the same keys, so the
|
|
15
|
+
same server accepts both.
|
|
16
|
+
- Privacy manifest included (`PrivacyInfo.xcprivacy`, shipped in ShotikCore). There's no IDFA and no fingerprinting.
|
|
17
|
+
|
|
18
|
+
## 1. Install
|
|
19
|
+
|
|
20
|
+
**Xcode project.** Go to File → Add Package Dependencies…, paste `https://github.com/rahimwws/shotik-app` into the search field, keep
|
|
21
|
+
"Up to Next Major Version" from `0.1.0`, then add the libraries you want to your app target. Most apps want
|
|
22
|
+
`ShotikAnalytics`, `ShotikSupport` and `ShotikSupportUI`.
|
|
23
|
+
|
|
24
|
+
**Swift package.** In your own `Package.swift`:
|
|
25
|
+
|
|
26
|
+
```swift
|
|
27
|
+
dependencies: [.package(url: "https://github.com/rahimwws/shotik-app", from: "0.1.0")],
|
|
28
|
+
targets: [.target(name: "App", dependencies: [
|
|
29
|
+
.product(name: "ShotikSupportUI", package: "shotik-app"),
|
|
30
|
+
.product(name: "ShotikAnalytics", package: "shotik-app"),
|
|
31
|
+
])]
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
The package lives in the Shotik repo: its `Package.swift` sits at the repo root and builds `sdk/swift/Sources`.
|
|
35
|
+
Releases are the repo's bare semver tags (`0.1.0`).
|
|
36
|
+
|
|
37
|
+
| You link | You get |
|
|
38
|
+
|---|---|
|
|
39
|
+
| `ShotikAnalytics` | Analytics only (Core comes with it) |
|
|
40
|
+
| `ShotikSupport` | The chat client without UI, for a chat screen of your own |
|
|
41
|
+
| `ShotikSupportUI` | The widget (it pulls in Support) |
|
|
42
|
+
|
|
43
|
+
## 2. Configure
|
|
44
|
+
|
|
45
|
+
Get the public key (`spk_…`) from Shotik → Support → SDK. It is a public app key, so it is safe to ship in the app.
|
|
46
|
+
Call configure once, as early as possible. It starts every module you linked.
|
|
47
|
+
|
|
48
|
+
```swift
|
|
49
|
+
import ShotikCore
|
|
50
|
+
import ShotikSupportUI
|
|
51
|
+
import SwiftUI
|
|
52
|
+
|
|
53
|
+
@main
|
|
54
|
+
struct MyApp: App {
|
|
55
|
+
init() {
|
|
56
|
+
Shotik.configure(appKey: "spk_…", serverUrl: "https://support.example.com")
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
var body: some Scene {
|
|
60
|
+
WindowGroup {
|
|
61
|
+
RootView().shotikSupportSheet() // presents the widget on ShotikSupport.open() and myapp://support
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
**UIKit apps** call configure in `application(_:didFinishLaunchingWithOptions:)` and install the widget once the
|
|
68
|
+
window exists:
|
|
69
|
+
|
|
70
|
+
```swift
|
|
71
|
+
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options: UIScene.ConnectionOptions) {
|
|
72
|
+
// … your window setup
|
|
73
|
+
ShotikSupportWidget.install() // presents the widget over the top view controller on open()
|
|
74
|
+
}
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
`ShotikConfig` has more options: `Shotik.configure(ShotikConfig(appKey:serverUrl:consent:snapshots:flushMs:sessionTimeoutMs:autoCapture:debug:))`.
|
|
78
|
+
|
|
79
|
+
| Option | Default | |
|
|
80
|
+
|---|---|---|
|
|
81
|
+
| `consent` | the persisted choice, else `.granted` | Analytics consent, see 5.7 |
|
|
82
|
+
| `snapshots` | `0.2` | Share of sessions that record wireframes (0…1) |
|
|
83
|
+
| `flushMs` | `10000` | Analytics upload interval while active |
|
|
84
|
+
| `sessionTimeoutMs` | 30 min | Inactivity that starts a new session |
|
|
85
|
+
| `autoCapture` | `true` | Taps, screens, stalls, crashes, StoreKit. Manual calls work either way |
|
|
86
|
+
| `debug` | `false` | Prints every event to the console |
|
|
87
|
+
|
|
88
|
+
Every call made before `configure` (identify, push token, track) is held and replayed in order once it runs. Analytics
|
|
89
|
+
holds up to 500 calls.
|
|
90
|
+
|
|
91
|
+
## 3. Support
|
|
92
|
+
|
|
93
|
+
### Open it
|
|
94
|
+
|
|
95
|
+
```swift
|
|
96
|
+
import ShotikSupport
|
|
97
|
+
|
|
98
|
+
Button("Help") { ShotikSupport.open() }
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
The widget is a system sheet with a conversation list, a thread, receipts (sending, sent, delivered, seen), a typing
|
|
102
|
+
indicator while the AI drafts or you type in Shotik, quick-reply chips, "Talk to a person", and photos and screenshots
|
|
103
|
+
as attachments. It supports light and dark, Dynamic Type, VoiceOver and RTL. Copy is English or Russian, picked from the
|
|
104
|
+
device locale. The widget's views are built on the first open, so nothing exists before then except the launcher.
|
|
105
|
+
|
|
106
|
+
Add `.shotikSupportLauncher()` to a view for a floating button with the unread badge. For a badge on your own Help row:
|
|
107
|
+
|
|
108
|
+
```swift
|
|
109
|
+
struct HelpBadge: View {
|
|
110
|
+
@StateObject private var badge = ShotikSupportBadge()
|
|
111
|
+
var body: some View { if badge.unread > 0 { Text("\(badge.unread)") } }
|
|
112
|
+
}
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
### Brand it
|
|
116
|
+
|
|
117
|
+
```swift
|
|
118
|
+
RootView().shotikSupportSheet(SupportWidgetOptions(
|
|
119
|
+
title: "Walkito", // header (default "Support" / "Поддержка")
|
|
120
|
+
teamName: "Rahim", // label above your replies (default "Team" / "Команда")
|
|
121
|
+
quickReplies: ["Billing", "Report a bug"], // chips on a new conversation
|
|
122
|
+
theme: SupportTheme(accent: "#FF5A1F", radius: 18, font: "Inter-Regular", fontBold: "Inter-SemiBold"),
|
|
123
|
+
locale: "ru" // default: the device locale; en is the fallback
|
|
124
|
+
))
|
|
125
|
+
```
|
|
126
|
+
|
|
127
|
+
| `SupportTheme` | Default | |
|
|
128
|
+
|---|---|---|
|
|
129
|
+
| `accent` | iOS blue | Your bubbles, the send button, the launcher, links |
|
|
130
|
+
| `onAccent` | `#FFFFFF` | Text and glyphs on the accent |
|
|
131
|
+
| `radius` | `18` | Bubble radius. The sheet, chips and field follow it |
|
|
132
|
+
| `font`, `fontBold` | system | Font names for regular and semibold text |
|
|
133
|
+
| `scheme` | system | Force `.light` or `.dark` |
|
|
134
|
+
| `light`, `dark` | | `ShotikColors` overrides: `bg raised line text sub faint danger ok warn backdrop` |
|
|
135
|
+
|
|
136
|
+
### Deep link
|
|
137
|
+
|
|
138
|
+
Add a URL scheme to your target (Info → URL Types, for example `myapp`). Then `myapp://support` opens the chat over
|
|
139
|
+
the current screen, from push taps too. `.shotikSupportSheet()` handles it through `onOpenURL`. If your app handles
|
|
140
|
+
URLs itself, pass `handleLinks: false` and call `ShotikSupport.handle(url:)` first in your handler (it returns
|
|
141
|
+
`true` when the URL was for Support). UIKit apps call it from `scene(_:openURLContexts:)`.
|
|
142
|
+
|
|
143
|
+
### Identify after sign-in
|
|
144
|
+
|
|
145
|
+
```swift
|
|
146
|
+
ShotikSupport.identify(userId: user.id, name: user.name, email: user.email, attributes: ["plan": "pro"])
|
|
147
|
+
ShotikAnalytics.identify(user.id, traits: ["plan": "pro"])
|
|
148
|
+
// sign-out: a new anonymous id for Support and Analytics
|
|
149
|
+
Shotik.reset()
|
|
150
|
+
```
|
|
151
|
+
|
|
152
|
+
Anonymous users get a persisted id. When they sign in, their chats move to the signed-in user. Every identify sends the
|
|
153
|
+
device context: platform, OS version, model, app version and build, locale and time zone.
|
|
154
|
+
|
|
155
|
+
### Push
|
|
156
|
+
|
|
157
|
+
```swift
|
|
158
|
+
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
|
|
159
|
+
ShotikSupport.setPushToken(deviceToken: deviceToken)
|
|
160
|
+
}
|
|
161
|
+
```
|
|
162
|
+
|
|
163
|
+
SwiftUI apps get this callback through `@UIApplicationDelegateAdaptor`. Another provider's token string works too:
|
|
164
|
+
`ShotikSupport.setPushToken(token, platform: "ios")`, and `nil` clears it. Every founder or AI reply is recorded as a
|
|
165
|
+
push-ready event (`GET /v1/support/events`) with the user's token and a preview.
|
|
166
|
+
|
|
167
|
+
### Your own chat UI
|
|
168
|
+
|
|
169
|
+
Link only `ShotikSupport`. `ShotikSupport.observe { state in … }` delivers `SupportState` on the main queue
|
|
170
|
+
(conversations, messages, unread, typing, status). `send`, `retry`, `handoff`, `markRead` and `receiptOf` do the
|
|
171
|
+
rest. `SupportClient` is the platform-free core and is what the tests drive.
|
|
172
|
+
|
|
173
|
+
## 4. Support API
|
|
174
|
+
|
|
175
|
+
| | |
|
|
176
|
+
|---|---|
|
|
177
|
+
| `Shotik.configure(appKey:serverUrl:)` | Starts every linked module. `ShotikSupport.configure` and `ShotikAnalytics.configure` do the same |
|
|
178
|
+
| `ShotikSupport.identify(userId:name:email:attributes:)`, `Shotik.reset()` | Signed-in user, sign-out |
|
|
179
|
+
| `ShotikSupport.setPushToken(deviceToken:)`, `setPushToken(_:platform:)` | APNs token (as hex) or any token string; `nil` clears it |
|
|
180
|
+
| `ShotikSupport.open(_ conversationId:)`, `close()`, `select(_:)` | Show or hide the widget, pick a conversation |
|
|
181
|
+
| `ShotikSupport.state.status` | `idle · identifying · connecting · live · offline · error` |
|
|
182
|
+
| `ShotikSupport.send(_:conversationId:attachments:)` | Optimistic and queued while offline. Without an id it starts a new conversation |
|
|
183
|
+
| `ShotikSupport.retry(_ localId:)` | Resend a message marked `.failed` |
|
|
184
|
+
| `ShotikSupport.handoff(_:)` | "Talk to a person": the conversation goes to your Needs-human list and the AI stops answering it |
|
|
185
|
+
| `ShotikSupport.observe(_:)` | State on the main queue; the first call delivers the current state |
|
|
186
|
+
| `receiptOf(_:in:conversation:offline:)` | `sending · queued · failed · sent · delivered · seen` for the user's messages |
|
|
187
|
+
| `ShotikImage.attachment(from:)` | A JPEG `LocalAttachment` (max 2048 px) from image data, for your own picker |
|
|
188
|
+
|
|
189
|
+
## 5. Analytics
|
|
190
|
+
|
|
191
|
+
Linking `ShotikAnalytics` and calling `Shotik.configure` is all it takes. Events are batched and uploaded at most
|
|
192
|
+
once every 10 seconds while the app is active, and once more when it goes to the background. Uploads are retried
|
|
193
|
+
with backoff while offline, and the queue survives restarts.
|
|
194
|
+
|
|
195
|
+
### 5.1 What is captured automatically
|
|
196
|
+
|
|
197
|
+
| Signal | How |
|
|
198
|
+
|---|---|
|
|
199
|
+
| Sessions, open, close | Scene and application notifications. A new session starts after 30 minutes away |
|
|
200
|
+
| Screens and time on screen | The top view controller after each transition, named by `.shotikScreen()`, the navigation title, or the class |
|
|
201
|
+
| Taps, dead taps, rage taps | One passive gesture recognizer per window (`cancelsTouchesInView = false`, it never recognizes). On touch end it only queues the point, the time, the current screen and the `.shotikTag` under the finger; the element is resolved right after. **UIKit:** automatic, from the hit-test chain: the control's `accessibilityIdentifier` (sent as `id` and as `#id` on `el`), its label and class. **SwiftUI:** the tap, its position, screen and rage are automatic, but the element is only named where you add `.shotikTag` (see 5.3); without it the tap is `el: "View"` with no label and no id, and it is never called dead. Taps in the Support widget count on a "Support" screen |
|
|
202
|
+
| Scroll depth | Sampled from the scroll view under a drag when the finger lifts |
|
|
203
|
+
| Stalls, slow screens | A background watchdog pings the main queue every 500 ms |
|
|
204
|
+
| Crashes | `NSSetUncaughtExceptionHandler`, chained to the previous handler |
|
|
205
|
+
| Purchases | StoreKit 2 `Transaction.updates` and a scan of `Transaction.all` on foreground |
|
|
206
|
+
| Wireframes | A view hierarchy walk on the sampled sessions, encoded off the main thread |
|
|
207
|
+
|
|
208
|
+
**Limits of swizzle-free capture.** Scroll depth is sampled when a drag ends, so momentum after the finger lifts is not
|
|
209
|
+
counted, and programmatic scrolling is not tracked at all. Screens are checked after touches end and on scene
|
|
210
|
+
activation, so a screen pushed by code without a touch is named on the next touch. Use `.shotikScreen()` or
|
|
211
|
+
`ShotikAnalytics.screen` for exact names. Swift runtime traps (`fatalError`, force unwraps) are not Objective-C
|
|
212
|
+
exceptions, so they stay with your crash reporter.
|
|
213
|
+
|
|
214
|
+
### 5.2 Screen names
|
|
215
|
+
|
|
216
|
+
```swift
|
|
217
|
+
PaywallView().shotikScreen("Paywall") // SwiftUI; wins over automatic names
|
|
218
|
+
ShotikAnalytics.screen("Paywall") // anywhere
|
|
219
|
+
```
|
|
220
|
+
|
|
221
|
+
### 5.3 Element ids in SwiftUI
|
|
222
|
+
|
|
223
|
+
SwiftUI keeps its accessibility tree empty unless VoiceOver, another assistive technology or UI-test automation is
|
|
224
|
+
running, and there is no public API to make it vend the elements. That's why PostHog asks for `.postHogLabel`, and why
|
|
225
|
+
Amplitude and PostHog autocapture element interactions only in UIKit. So SwiftUI tap targets get their id from a tag:
|
|
226
|
+
|
|
227
|
+
```swift
|
|
228
|
+
Button("Continue") { next() }
|
|
229
|
+
.shotikTag("continue", label: "Continue") // el "Tag#continue", id "continue", label "Continue"
|
|
230
|
+
```
|
|
231
|
+
|
|
232
|
+
Tag your CTAs, paywall plans and buttons, onboarding steps and the Help row. The tag adds a passive background marker
|
|
233
|
+
(no hit testing, hidden from VoiceOver), and the frames are read at touch time, so scrolling, sheets and navigation need
|
|
234
|
+
nothing extra. When tags overlap, the one in the front-most layer wins (a sheet over the screen), then the smallest.
|
|
235
|
+
Labels are your own text, so never put personal data in them. `accessibilityIdentifier` alone isn't enough in SwiftUI:
|
|
236
|
+
it only reaches the SDK while an assistive technology is running.
|
|
237
|
+
|
|
238
|
+
### 5.4 Masking
|
|
239
|
+
|
|
240
|
+
Inputs never send their value. Taps on text fields and secure fields carry `input: 1` and no label, and wireframes draw
|
|
241
|
+
them as empty boxes. To hide anything else from tap labels and wireframes:
|
|
242
|
+
|
|
243
|
+
```swift
|
|
244
|
+
BalanceView().shotikMask() // SwiftUI
|
|
245
|
+
cardView.shotikMasked = true // UIKit
|
|
246
|
+
```
|
|
247
|
+
|
|
248
|
+
### 5.5 Custom events
|
|
249
|
+
|
|
250
|
+
```swift
|
|
251
|
+
ShotikAnalytics.track("Plan selected", ["plan": "annual", "step": 3])
|
|
252
|
+
ShotikAnalytics.error(error) // a handled error, with the top stack frames
|
|
253
|
+
```
|
|
254
|
+
|
|
255
|
+
Custom props are free-form. Never put personal data in them (names, emails, free text the user typed).
|
|
256
|
+
|
|
257
|
+
### 5.6 Purchases
|
|
258
|
+
|
|
259
|
+
Purchases made through StoreKit 2 are recorded without any code. To also record the start and the cancel, wrap the
|
|
260
|
+
purchase call:
|
|
261
|
+
|
|
262
|
+
```swift
|
|
263
|
+
let result = try await ShotikAnalytics.purchase(product: product) { try await product.purchase() }
|
|
264
|
+
```
|
|
265
|
+
|
|
266
|
+
For another store or RevenueCat, use `ShotikAnalytics.purchase(product: "pro.annual", status: .done, price: 49.99, currency: "USD")`.
|
|
267
|
+
|
|
268
|
+
### 5.7 Consent
|
|
269
|
+
|
|
270
|
+
```swift
|
|
271
|
+
Shotik.configure(ShotikConfig(appKey: "spk_…", serverUrl: url, consent: .pending)) // hold events on the device
|
|
272
|
+
ShotikAnalytics.optIn() // .granted: upload what was held
|
|
273
|
+
ShotikAnalytics.optOut() // .denied: drop the queue and record nothing
|
|
274
|
+
```
|
|
275
|
+
|
|
276
|
+
The choice is persisted, so later launches can omit `consent`. Support is not affected by analytics consent.
|
|
277
|
+
|
|
278
|
+
## 6. Performance and size
|
|
279
|
+
|
|
280
|
+
| Budget (PROTOCOL.md §8) | Measured |
|
|
281
|
+
|---|---|
|
|
282
|
+
| `configure` on main < 5 ms cold, < 1 ms typical | 0.0006 ms median, 0.0019 ms p95, 0.025 ms first call (20 calls, macOS test run). The sample logs it on device |
|
|
283
|
+
| Tap handler on main < 0.1 ms p95 | Measured in the sample app (Settings → Tap handler p95); not measured on a device yet |
|
|
284
|
+
| Binary: Core + Analytics < 400 KB, everything < 900 KB (arm64, release, stripped) | Stripped file delta over the no-SDK sample: Core + Analytics +354,136 B (345.8 KiB), everything +925,240 B (903.6 KiB). Section bytes without 16 KiB segment padding: 291.4 KiB and 798.9 KiB |
|
|
285
|
+
|
|
286
|
+
Release builds of the SDK use `-Osize`. Core and Support also drop reflection metadata. The sample app in `Sample/`
|
|
287
|
+
has three targets built from the same screens (everything, Core + Analytics, and no SDK), so the size report is a
|
|
288
|
+
plain difference. It logs `[shotik-sample] configure_ms=…` and a `Shotik.configure` signpost on launch.
|
|
289
|
+
|
|
290
|
+
## Troubleshooting
|
|
291
|
+
|
|
292
|
+
- **Status stays `offline`.** The device can't reach `serverUrl`. The simulator reaches the Mac at
|
|
293
|
+
`http://127.0.0.1:<port>`, but a device needs the Mac's LAN address (`http://192.168.x.x:<port>`) or an HTTPS
|
|
294
|
+
deployment. Check with `curl <serverUrl>/health`.
|
|
295
|
+
- **Plain `http://` fails on a device.** App Transport Security blocks it. Use HTTPS, or for development only add
|
|
296
|
+
`NSAppTransportSecurity → NSAllowsLocalNetworking = YES` (LAN and `.local` hosts) or an exception domain for your
|
|
297
|
+
Mac. Don't ship `NSAllowsArbitraryLoads`.
|
|
298
|
+
- **Status is `error` with "unknown app key".** The key doesn't belong to this server. Create it again in Shotik.
|
|
299
|
+
- **`myapp://support` does nothing.** The URL scheme is missing from the target's URL Types, or the root view has no
|
|
300
|
+
`.shotikSupportSheet()` (UIKit: no `ShotikSupportWidget.install()`, or `handle(url:)` is not called).
|
|
301
|
+
- **The widget never opens.** `.shotikSupportSheet()` must sit on a view that is on screen. Put it on the root view
|
|
302
|
+
of the `WindowGroup`, not on a screen inside a navigation stack.
|
|
303
|
+
- **No analytics events.** Check that `ShotikAnalytics` is linked into the app target, not only imported somewhere:
|
|
304
|
+
Core finds modules by class name at configure time. Pass `debug: true` to print every event. Consent `.pending`
|
|
305
|
+
or `.denied` also holds uploads.
|
|
306
|
+
- **Screens are named after classes such as `UIHostingController<…>`.** SwiftUI screens need `.shotikScreen("Name")`
|
|
307
|
+
or a navigation title.
|
|
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".
|
|
311
|
+
- **App Store privacy questions.** The privacy manifest ships in ShotikCore. Xcode merges it into the app's privacy
|
|
312
|
+
report (Product → Archive → Generate Privacy Report).
|
|
313
|
+
|
|
314
|
+
## Tests
|
|
315
|
+
|
|
316
|
+
```sh
|
|
317
|
+
cd sdk/swift && swift test
|
|
318
|
+
```
|
|
319
|
+
|
|
320
|
+
The suite covers every conformance case in PROTOCOL.md §9 with a manual clock, a fake transport and fake sockets. That
|
|
321
|
+
includes the packed wire example byte for byte, the outbox, backoff, the 4003 re-identify, receipts, typing, consent and
|
|
322
|
+
the network budget. The live test runs against a real Shotik server when `SHOTIK_LIVE_URL`, `SHOTIK_LIVE_KEY` and
|
|
323
|
+
`SHOTIK_LIVE_TOKEN` are set:
|
|
324
|
+
|
|
325
|
+
```sh
|
|
326
|
+
SHOTIK_LIVE_URL=http://127.0.0.1:4590 SHOTIK_LIVE_KEY=spk_… SHOTIK_LIVE_TOKEN=… swift test --filter LiveTests
|
|
327
|
+
```
|