@appeeky/spec 0.7.0 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/setup.js CHANGED
@@ -2,8 +2,8 @@ import { existsSync, readdirSync, readFileSync } from "node:fs";
2
2
  import { join } from "node:path";
3
3
  import { installedTargets } from "./agents.js";
4
4
  import { SPEC_DIR, SPEC_FILE } from "./files.js";
5
- import { normalize, words } from "./text.js";
6
- import { STORE_CLIS, onPath } from "./transport.js";
5
+ import { words } from "./text.js";
6
+ import { createTransport, hasLocalKeys, npxPackage, onPath, STORE_CLIS } from "./transport.js";
7
7
  /** App Store apps matching a name, from Apple's public search. */
8
8
  export async function findApps(term, country = "us", fetcher = fetch) {
9
9
  const url = `https://itunes.apple.com/search?media=software&entity=software&limit=6&country=${encodeURIComponent(country)}&term=${encodeURIComponent(term)}`;
@@ -45,7 +45,8 @@ export function targetCandidates(project, limit = 14, storeName) {
45
45
  const play = project.listings["google-play"][locale] ?? Object.values(project.listings["google-play"])[0];
46
46
  const name = asc?.name ?? play?.title ?? storeName ?? project.spec.app.name;
47
47
  const subtitle = asc?.subtitle ?? play?.shortDescription ?? "";
48
- const brand = normalize(project.spec.app.name).trim();
48
+ // The brand is the name's first part ("Saiko AI" in "Saiko AI: Dance Video Maker"), not the whole name.
49
+ const brand = words(project.spec.app.name.split(/[:\-–—|]/)[0]).join(" ");
49
50
  const out = [];
50
51
  const add = (phrase) => {
51
52
  const ws = words(phrase);
@@ -206,9 +207,6 @@ jobs:
206
207
  const ok = (area, detail) => ({ area, status: "ok", detail });
207
208
  const warn = (area, detail, fix) => ({ area, status: "warn", detail, fix });
208
209
  const fail = (area, detail, fix) => ({ area, status: "fail", detail, fix });
209
- const hasLocalKeys = (store, env) => store === "app-store"
210
- ? Boolean(env.ASC_KEY_ID && (env.ASC_PRIVATE_KEY || env.ASC_PRIVATE_KEY_PATH))
211
- : Boolean(env.GPS_CREDENTIALS || env.GOOGLE_PLAY_CREDENTIALS || env.GOOGLE_APPLICATION_CREDENTIALS);
212
210
  /** Where each store CLI keeps its saved accounts (`appstore accounts add`, `gps accounts add`). */
213
211
  export function savedAccountsFile(store, env = process.env) {
214
212
  const base = env.XDG_CONFIG_HOME ?? join(env.HOME ?? env.USERPROFILE ?? "", ".config");
@@ -225,6 +223,54 @@ export function savedAccounts(store, env = process.env) {
225
223
  return [];
226
224
  }
227
225
  }
226
+ const HOSTED_DETAIL = "hosted through your Appeeky connection (APPEEKY_API_KEY)";
227
+ /** One read per store, the cheapest the adapters make, to prove the connection works and not only that a key is set. */
228
+ const PROBES = {
229
+ "app-store": (project) => {
230
+ const cfg = project.spec.stores.appStore;
231
+ return cfg ? ["appstore_list_versions", { appId: cfg.appId, platform: cfg.platform ?? "IOS" }] : null;
232
+ },
233
+ "google-play": (project) => {
234
+ const cfg = project.spec.stores.googlePlay;
235
+ return cfg ? ["gps_list_listings", { packageName: cfg.packageName }] : null;
236
+ },
237
+ };
238
+ /**
239
+ * `diagnose` only sees which keys are set. This asks each store reached through the hosted
240
+ * gateway for one read, so a key that is valid but has no store connected (or the wrong
241
+ * account's key) shows up as a failure instead of "Ready". Local CLIs are not called: that
242
+ * can take a minute through npx; `pull` shows their errors.
243
+ */
244
+ export async function probeConnections(project, checks, env = process.env, fetcher, timeoutMs = 15_000) {
245
+ const out = [...checks];
246
+ for (const store of ["app-store", "google-play"]) {
247
+ const label = store === "app-store" ? "App Store" : "Google Play";
248
+ const i = out.findIndex((c) => c.area === label && c.status === "ok" && c.detail === HOSTED_DETAIL);
249
+ const probe = PROBES[store](project);
250
+ if (i < 0 || !probe)
251
+ continue;
252
+ const cfg = store === "app-store" ? project.spec.stores.appStore : project.spec.stores.googlePlay;
253
+ let timer;
254
+ try {
255
+ const transport = createTransport(store, { via: cfg?.via ?? "auto", env, fetcher });
256
+ if (transport.kind !== "hosted")
257
+ continue;
258
+ const timeout = new Promise((_, reject) => {
259
+ timer = setTimeout(() => reject(new Error(`no answer in ${timeoutMs / 1000}s`)), timeoutMs);
260
+ });
261
+ await Promise.race([transport.call(probe[0], probe[1]), timeout]);
262
+ out[i] = ok(label, `${HOSTED_DETAIL}, connected`);
263
+ }
264
+ catch (e) {
265
+ out[i] = fail(label, `APPEEKY_API_KEY is set, but the hosted gateway refused: ${e.message}`, `Connect ${label} in Appeeky for the account this key belongs to (appeeky.com/dashboard), or use your own store key with \`via: local\`.`);
266
+ }
267
+ finally {
268
+ if (timer)
269
+ clearTimeout(timer);
270
+ }
271
+ }
272
+ return out;
273
+ }
228
274
  /** What is set up for this repo, and what is missing. Works without a spec (it says so). */
229
275
  export function diagnose(root, project, env = process.env, nodeVersion = process.versions.node) {
230
276
  const out = [];
@@ -247,13 +293,14 @@ export function diagnose(root, project, env = process.env, nodeVersion = process
247
293
  // The CLI runs from PATH or through npx; either way it reads keys from the environment or its saved accounts.
248
294
  const accounts = savedAccounts(store, env);
249
295
  const keys = hasLocalKeys(store, env) ? "keys in the environment" : accounts.length ? `saved account${accounts.length > 1 ? "s" : ""} ${accounts.join(", ")}` : "";
250
- const runner = local ? `${cli.bin} CLI` : `npx ${cli.npmPackage}`;
296
+ const runner = local ? `${cli.bin} CLI` : `npx ${npxPackage(store)}`;
251
297
  if (via === "hosted")
252
- out.push(key ? ok(label, "hosted through your Appeeky connection (APPEEKY_API_KEY)") : fail(label, "via: hosted, but APPEEKY_API_KEY is not set", "Set APPEEKY_API_KEY (appeeky.com/dashboard/settings)."));
253
- else if (keys && (via === "local" || local || !key))
298
+ out.push(key ? ok(label, HOSTED_DETAIL) : fail(label, "via: hosted, but APPEEKY_API_KEY is not set", "Set APPEEKY_API_KEY (appeeky.com/dashboard/settings)."));
299
+ // Same order as createTransport: an installed CLI or keys in the environment win over the hosted gateway.
300
+ else if (keys && (via === "local" || local || hasLocalKeys(store, env) || !key))
254
301
  out.push(ok(label, `your own key: ${runner}, ${keys}`));
255
302
  else if (via !== "local" && key)
256
- out.push(ok(label, "hosted through your Appeeky connection (APPEEKY_API_KEY)"));
303
+ out.push(ok(label, HOSTED_DETAIL));
257
304
  else if (local)
258
305
  out.push(fail(label, `${cli.bin} CLI is installed but has no saved account and no keys in the environment`, cli.setupHint));
259
306
  else
package/dist/social.d.ts CHANGED
@@ -38,7 +38,8 @@ export interface NativePost {
38
38
  account: string;
39
39
  platform: string;
40
40
  url?: string;
41
- text: string;
41
+ /** Missing when the post or comment has no text (emoji-only, an image, no caption): empty strings are not stored. */
42
+ text?: string;
42
43
  mediaType?: string;
43
44
  publishedAt?: string;
44
45
  metrics?: Partial<Record<SocialMetric | "engagementRate", number>>;
@@ -50,7 +51,8 @@ export interface SocialComment {
50
51
  postUrl?: string;
51
52
  postId?: string;
52
53
  platformPostId?: string;
53
- text: string;
54
+ /** Missing when the post or comment has no text (emoji-only, an image, no caption): empty strings are not stored. */
55
+ text?: string;
54
56
  author?: string;
55
57
  own?: boolean;
56
58
  reply?: boolean;
@@ -87,7 +89,8 @@ export interface SocialData {
87
89
  export interface SocialPost {
88
90
  id: string;
89
91
  status: string;
90
- text: string;
92
+ /** Missing when the post or comment has no text (emoji-only, an image, no caption): empty strings are not stored. */
93
+ text?: string;
91
94
  createdAt: string;
92
95
  scheduledFor?: string;
93
96
  platforms: SocialPlatformResult[];
@@ -180,8 +183,11 @@ export declare function toInsights(r: InsightsRow, account: SocialAccount): Acco
180
183
  * Connected accounts and the latest posts made through Appeeky, with analytics for the ones that
181
184
  * went out; then, per account, the posts made in the platform's app, recent comments and followers.
182
185
  */
186
+ /** Whether an account is one of `only` (ids, handles, names or platform:handle, as in `social.accounts`). */
187
+ export declare function accountMatches(a: SocialAccount, only: string[]): boolean;
183
188
  export declare function fetchSocial(api: AppeekyApi, options?: {
184
189
  limit?: number;
190
+ only?: string[];
185
191
  }): Promise<SocialData>;
186
192
  export declare function summaryMarkdown(accounts: SocialAccount[], posts: SocialPost[], now?: Date, more?: Pick<SocialData, "nativePosts" | "comments" | "insights">): string;
187
193
  export declare function saveSocial(root: string, data: SocialData, now?: Date): Promise<void>;
@@ -388,8 +394,8 @@ export declare const draftSchema: z.ZodObject<{
388
394
  sentAt: z.ZodOptional<z.ZodString>;
389
395
  }, "strict", z.ZodTypeAny, {
390
396
  status: "draft" | "sent";
391
- text: string;
392
397
  accounts: string[];
398
+ text: string;
393
399
  tiktok?: {
394
400
  title?: string | undefined;
395
401
  comments?: boolean | undefined;
@@ -419,8 +425,8 @@ export declare const draftSchema: z.ZodObject<{
419
425
  why?: string | undefined;
420
426
  postId?: string | undefined;
421
427
  }, {
422
- text: string;
423
428
  accounts: string[];
429
+ text: string;
424
430
  status?: "draft" | "sent" | undefined;
425
431
  tiktok?: {
426
432
  title?: string | undefined;
package/dist/social.js CHANGED
@@ -122,9 +122,26 @@ async function perAccount(accounts, what, warnings, fetchOne, map, skip = []) {
122
122
  * Connected accounts and the latest posts made through Appeeky, with analytics for the ones that
123
123
  * went out; then, per account, the posts made in the platform's app, recent comments and followers.
124
124
  */
125
+ /** Whether an account is one of `only` (ids, handles, names or platform:handle, as in `social.accounts`). */
126
+ export function accountMatches(a, only) {
127
+ const handles = accountHandles(a);
128
+ return only.some((ref) => {
129
+ const r = ref.trim().toLowerCase();
130
+ if (r === a.id.toLowerCase())
131
+ return true;
132
+ const m = /^([a-z]+):(.+)$/.exec(r);
133
+ if (m)
134
+ return platformKey(m[1]) === platformKey(a.platform) && handles.includes(m[2]);
135
+ return handles.includes(r);
136
+ });
137
+ }
125
138
  export async function fetchSocial(api, options = {}) {
126
- const accounts = ((await api.get("/connect/social/accounts")) ?? []).map(toAccount);
127
- const rows = (await api.get("/social/posts", { limit: String(options.limit ?? 100) })) ?? [];
139
+ const all = ((await api.get("/connect/social/accounts")) ?? []).map(toAccount);
140
+ const accounts = options.only?.length ? all.filter((a) => accountMatches(a, options.only)) : all;
141
+ const allRows = (await api.get("/social/posts", { limit: String(options.limit ?? 100) })) ?? [];
142
+ // Posts made through Appeeky name platforms, not accounts: with social.accounts, keep those on this app's platforms.
143
+ const platforms = new Set(accounts.map((a) => platformKey(a.platform)));
144
+ const rows = options.only?.length ? allRows.filter((r) => (r.social_media_platform_posts ?? []).some((p) => platforms.has(platformKey(p.platform)))) : allRows;
128
145
  const posts = [];
129
146
  for (const row of rows) {
130
147
  const published = (row.social_media_platform_posts ?? []).some((p) => p.published_at);
@@ -143,8 +160,11 @@ const total = (p, k) => p.metrics?.[k] ?? 0;
143
160
  /** The reach of a post on one platform: views when the platform reports them, else impressions or reach. */
144
161
  const seen = (p) => total(p, "views") || total(p, "impressions") || total(p, "reach");
145
162
  const score = (p) => seen(p) + total(p, "likes") * 10;
163
+ /** Text without a caption (an emoji-only or image comment, a video posted without one) arrives without `text`. */
146
164
  const oneLine = (text, max) => {
147
- const t = text.replace(/\s+/g, " ").trim();
165
+ const t = (text ?? "").replace(/\s+/g, " ").trim();
166
+ if (!t)
167
+ return "(no text)";
148
168
  return `${t.slice(0, max)}${t.length > max ? "…" : ""}`;
149
169
  };
150
170
  const signed = (n) => (n > 0 ? `+${n}` : String(n));
@@ -18,6 +18,11 @@ export declare class TransportError extends Error {
18
18
  interface StoreCli {
19
19
  bin: string;
20
20
  npmPackage: string;
21
+ /**
22
+ * The CLI version `npx` runs when it is not installed. Pinned so a scheduled run with the
23
+ * user's store keys never picks up whatever was published last; bump it deliberately.
24
+ */
25
+ npmVersion: string;
21
26
  /** argv before the op name, e.g. `ops call` vs `call`. */
22
27
  callArgs: string[];
23
28
  /** Flag that picks a named account or profile. */
@@ -27,6 +32,20 @@ interface StoreCli {
27
32
  setupHint: string;
28
33
  }
29
34
  export declare const STORE_CLIS: Record<StoreId, StoreCli>;
35
+ /** `@appeeky/…-cli@<version>`: what `npx -p` installs. */
36
+ export declare const npxPackage: (store: StoreId) => string;
37
+ /**
38
+ * Store keys in the environment that the store CLI reads (the user's own key, no saved account
39
+ * needed). A path counts only when the file exists, so a variable left over in an env file, or
40
+ * a key folder that is not mounted, does not take the store away from the hosted gateway.
41
+ */
42
+ export declare const hasLocalKeys: (store: StoreId, env?: NodeJS.ProcessEnv) => boolean;
43
+ /**
44
+ * The gateways and the Appeeky API answer "No appeeky-web account found for the API key owner"
45
+ * when the key is valid but belongs to no Appeeky account with stores connected (an internal or
46
+ * service key, or a key made before the account existed). Say what to do instead.
47
+ */
48
+ export declare function explainAppeekyError(message: string, status?: number): string;
30
49
  export declare function onPath(bin: string, env?: NodeJS.ProcessEnv): boolean;
31
50
  export type Runner = (command: string, args: string[], env?: Record<string, string>) => Promise<{
32
51
  code: number;
@@ -91,9 +110,10 @@ export interface TransportOptions {
91
110
  fetcher?: Fetcher;
92
111
  }
93
112
  /**
94
- * `auto` prefers the local CLI when it is installed (your key, nothing leaves
95
- * your machine), then the hosted gateway when an Appeeky API key is set, and
96
- * finally the CLI through npx.
113
+ * `auto` prefers your own key: the local CLI when it is installed, or through npx when
114
+ * the store keys are in the environment (ASC_KEY_ID…, GPS_CREDENTIALS, GOOGLE_APPLICATION_CREDENTIALS),
115
+ * as in a container. Then the hosted gateway when an Appeeky API key is set, and finally
116
+ * the CLI through npx with its saved accounts.
97
117
  */
98
118
  export declare function createTransport(store: StoreId, options: TransportOptions): OpsTransport;
99
119
  export {};
package/dist/transport.js CHANGED
@@ -13,6 +13,7 @@ export const STORE_CLIS = {
13
13
  "app-store": {
14
14
  bin: "appstore",
15
15
  npmPackage: "@appeeky/app-store-connect-cli",
16
+ npmVersion: "0.2.0",
16
17
  callArgs: ["ops", "call"],
17
18
  accountFlag: "--account",
18
19
  hostedUrl: "https://asc-api.appeeky.com",
@@ -22,6 +23,7 @@ export const STORE_CLIS = {
22
23
  "google-play": {
23
24
  bin: "gps",
24
25
  npmPackage: "@appeeky/google-play-store-cli",
26
+ npmVersion: "0.1.2",
25
27
  callArgs: ["call"],
26
28
  accountFlag: "--account",
27
29
  hostedUrl: "https://gps-api.appeeky.com",
@@ -29,6 +31,31 @@ export const STORE_CLIS = {
29
31
  setupHint: "Save your Google Play service account once with the Google Play CLI: `npx -p @appeeky/google-play-store-cli gps accounts add my-co --credentials service-account.json --default` (github.com/appeeky/google-play-console-cli). Or set APPEEKY_API_KEY to use your connection in Appeeky.",
30
32
  },
31
33
  };
34
+ /** `@appeeky/…-cli@<version>`: what `npx -p` installs. */
35
+ export const npxPackage = (store) => `${STORE_CLIS[store].npmPackage}@${STORE_CLIS[store].npmVersion}`;
36
+ /** A key given inline (JSON or PEM), or a path to a file that is there: a path to nothing is not a key. */
37
+ const keyThere = (value, inline) => Boolean(value && (inline.test(value.trim()) || existsSync(value)));
38
+ /**
39
+ * Store keys in the environment that the store CLI reads (the user's own key, no saved account
40
+ * needed). A path counts only when the file exists, so a variable left over in an env file, or
41
+ * a key folder that is not mounted, does not take the store away from the hosted gateway.
42
+ */
43
+ export const hasLocalKeys = (store, env = process.env) => store === "app-store"
44
+ ? Boolean(env.ASC_KEY_ID && (env.ASC_PRIVATE_KEY || keyThere(env.ASC_PRIVATE_KEY_PATH, /^-----BEGIN/)))
45
+ : [env.GPS_CREDENTIALS, env.GOOGLE_PLAY_CREDENTIALS, env.GOOGLE_APPLICATION_CREDENTIALS].some((v) => keyThere(v, /^\{/));
46
+ /**
47
+ * The gateways and the Appeeky API answer "No appeeky-web account found for the API key owner"
48
+ * when the key is valid but belongs to no Appeeky account with stores connected (an internal or
49
+ * service key, or a key made before the account existed). Say what to do instead.
50
+ */
51
+ export function explainAppeekyError(message, status) {
52
+ const said = message.replace(/[.\s]+$/, "");
53
+ if (/no appeeky-web account/i.test(message))
54
+ return `${said}. This APPEEKY_API_KEY is valid but belongs to no Appeeky account with the stores connected: create the key at appeeky.com/dashboard/settings while signed in to the account where this app's App Store Connect and Google Play are connected (and its social accounts), or use your own store keys with \`via: local\`.`;
55
+ if (status === 401)
56
+ return `${said}. Check APPEEKY_API_KEY: it is missing, revoked or mistyped (appeeky.com/dashboard/settings).`;
57
+ return message;
58
+ }
32
59
  export function onPath(bin, env = process.env) {
33
60
  const exts = process.platform === "win32" ? (env.PATHEXT ?? ".EXE;.CMD").split(";") : [""];
34
61
  for (const dir of (env.PATH ?? "").split(delimiter)) {
@@ -63,7 +90,7 @@ export class LocalCliTransport {
63
90
  this.store = store;
64
91
  this.options = options;
65
92
  const cli = STORE_CLIS[store];
66
- this.label = options.label ?? (options.useNpx ? `npx ${cli.npmPackage}` : `local ${cli.bin} CLI`);
93
+ this.label = options.label ?? (options.useNpx ? `npx ${npxPackage(store)}` : `local ${cli.bin} CLI`);
67
94
  }
68
95
  async call(op, args, options = {}) {
69
96
  const cli = STORE_CLIS[this.store];
@@ -76,7 +103,7 @@ export class LocalCliTransport {
76
103
  const [command, full] = this.options.command
77
104
  ? [this.options.command.file, [...this.options.command.args, ...argv]]
78
105
  : this.options.useNpx
79
- ? ["npx", ["-y", "-p", cli.npmPackage, cli.bin, ...argv]]
106
+ ? ["npx", ["-y", "-p", npxPackage(this.store), cli.bin, ...argv]]
80
107
  : [cli.bin, argv];
81
108
  const run = this.options.runner ?? defaultRunner;
82
109
  let result;
@@ -88,7 +115,9 @@ export class LocalCliTransport {
88
115
  }
89
116
  if (result.code !== 0) {
90
117
  const detail = (result.stderr || result.stdout).trim().split("\n").slice(-3).join(" ");
91
- throw new TransportError(`${cli.bin} ${op} failed: ${detail || `exit ${result.code}`}`, op);
118
+ // No key at all: say both ways in (save your own key, or use the stores connected in Appeeky).
119
+ const noKey = /no .*(api key|credentials)|accounts add|service account/i.test(detail);
120
+ throw new TransportError(`${cli.bin} ${op} failed: ${detail || `exit ${result.code}`}${noKey ? ` ${cli.setupHint}` : ""}`, op);
92
121
  }
93
122
  const text = result.stdout.trim();
94
123
  if (!text)
@@ -135,15 +164,16 @@ export class HostedTransport {
135
164
  const body = (await res.json().catch(() => null));
136
165
  if (!res.ok) {
137
166
  const message = body?.error?.message ?? `HTTP ${res.status}`;
138
- throw new TransportError(`${op} failed on ${new URL(base).host}: ${message}`, op);
167
+ throw new TransportError(explainAppeekyError(`${op} failed on ${new URL(base).host}: ${message}`, res.status), op);
139
168
  }
140
169
  return body?.data;
141
170
  }
142
171
  }
143
172
  /**
144
- * `auto` prefers the local CLI when it is installed (your key, nothing leaves
145
- * your machine), then the hosted gateway when an Appeeky API key is set, and
146
- * finally the CLI through npx.
173
+ * `auto` prefers your own key: the local CLI when it is installed, or through npx when
174
+ * the store keys are in the environment (ASC_KEY_ID…, GPS_CREDENTIALS, GOOGLE_APPLICATION_CREDENTIALS),
175
+ * as in a container. Then the hosted gateway when an Appeeky API key is set, and finally
176
+ * the CLI through npx with its saved accounts.
147
177
  */
148
178
  export function createTransport(store, options) {
149
179
  const env = options.env ?? process.env;
@@ -162,6 +192,8 @@ export function createTransport(store, options) {
162
192
  case "auto":
163
193
  if (onPath(cli.bin, env))
164
194
  return local(false);
195
+ if (hasLocalKeys(store, env))
196
+ return local(true);
165
197
  if (apiKey)
166
198
  return hosted(apiKey);
167
199
  return local(true);
@@ -1,29 +1,29 @@
1
- function f(t){return!!t&&typeof t=="object"&&!Array.isArray(t)}function w(t){return Array.isArray(t)?t:[]}function h(t){return typeof t=="string"&&t.length>0?t:void 0}function k(t){return typeof t=="number"&&Number.isFinite(t)?t:0}function W(t){try{let n=new URL(t);n.hash="",n.searchParams.delete("utm_source");let e=n.toString();return e.endsWith("/")&&(e=e.slice(0,-1)),e.toLowerCase()}catch{return t.trim().toLowerCase()}}var A=class{list=[];index=new Map;add(n,e){if(!n)return null;let r=W(n),o=this.index.get(r);if(o!==void 0){let i=this.list[o];return!i.title&&e&&(i.title=e),o+1}return this.list.push(e?{url:n,title:e}:{url:n}),this.index.set(r,this.list.length-1),this.list.length}get citations(){return this.list}};function S(t){return Array.from(new Set(t)).sort((e,r)=>e-r).map(e=>` [${e}]`).join("")}function E(t){let n=f(t)?t:{},e=new A,r=[],o=0;for(let a of w(n.output))if(f(a)){if(a.type==="web_search_call"){o+=1;continue}if(a.type==="message")for(let p of w(a.content)){if(!f(p)||p.type!=="output_text")continue;let u=typeof p.text=="string"?p.text:"",l=[];for(let c of w(p.annotations)){if(!f(c)||c.type!=="url_citation")continue;let m=h(c.url),g=e.add(m,h(c.title));if(g===null||!m)continue;let d=G(u,c,m);d!==null&&l.push({at:d,n:g})}r.push(F(u,l))}}let i=r.join(`
1
+ var W=20,G=300;function M(e){let n=[],t=new Set;for(let o of e){if(typeof o!="string")continue;let s=o.trim().replace(/\s+/g," ").slice(0,G);if(!s)continue;let i=s.toLowerCase();if(!t.has(i)&&(t.add(i),n.push(s),n.length>=W))break}return n}function h(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function w(e){return Array.isArray(e)?e:[]}function y(e){return typeof e=="string"&&e.length>0?e:void 0}function _(e){return typeof e=="number"&&Number.isFinite(e)?e:0}function F(e){try{let n=new URL(e);n.hash="",n.searchParams.delete("utm_source");let t=n.toString();return t.endsWith("/")&&(t=t.slice(0,-1)),t.toLowerCase()}catch{return e.trim().toLowerCase()}}var C=class{list=[];index=new Map;add(n,t){if(!n)return null;let o=F(n),s=this.index.get(o);if(s!==void 0){let i=this.list[s];return!i.title&&t&&(i.title=t),s+1}return this.list.push(t?{url:n,title:t}:{url:n}),this.index.set(o,this.list.length-1),this.list.length}get citations(){return this.list}};function v(e){return Array.from(new Set(e)).sort((t,o)=>t-o).map(t=>` [${t}]`).join("")}function O(e){let n=h(e)?e:{},t=new C,o=[],s=[],i=0;for(let m of w(n.output))if(h(m)){if(m.type==="web_search_call"){i+=1;let l=h(m.action)?m.action:{};s.push(l.query,...w(l.queries));continue}if(m.type==="message")for(let l of w(m.content)){if(!h(l)||l.type!=="output_text")continue;let u=typeof l.text=="string"?l.text:"",a=[];for(let p of w(l.annotations)){if(!h(p)||p.type!=="url_citation")continue;let g=y(p.url),d=t.add(g,y(p.title));if(d===null||!g)continue;let f=J(u,p,g);f!==null&&a.push({at:f,n:d})}o.push(B(u,a))}}let r=o.join(`
2
2
 
3
- `).trim();!i&&typeof n.output_text=="string"&&(i=n.output_text.trim());let s=f(n.usage)?n.usage:{};return{text:i,citations:e.citations,inputTokens:k(s.input_tokens),outputTokens:k(s.output_tokens),searchCalls:o}}function G(t,n,e){let r=typeof n.start_index=="number"?n.start_index:null,o=typeof n.end_index=="number"?n.end_index:null,i="";try{i=new URL(e).hostname.replace(/^www\./,"")}catch{}if(r!==null&&o!==null&&o<=t.length&&r<o){let p=t.slice(r,o);if(p.includes(e)||i&&p.includes(i))return o}let s=t.indexOf(e);if(s===-1)return null;let a=s+e.length;for(;a<t.length&&t[a]===")";)a+=1;return a}function F(t,n){if(n.length===0)return t;let e=new Map;for(let{at:o,n:i}of n)e.set(o,[...e.get(o)??[],i]);let r=t;for(let o of Array.from(e.keys()).sort((i,s)=>s-i))r=r.slice(0,o)+S(e.get(o))+r.slice(o);return r}function T(t){let n=f(t)?t:{},e=new A,r=w(n.content).filter(f),o="",i=0;for(let u of r){if(u.type==="server_tool_use"&&u.name==="web_search"&&(i+=1),u.type!=="text")continue;let l=typeof u.text=="string"?u.text:"",c=[];for(let m of w(u.citations)){if(!f(m)||m.type!==void 0&&m.type!=="web_search_result_location")continue;let g=e.add(h(m.url),h(m.title));g!==null&&c.push(g)}o+=c.length>0?J(l,S(c)):l}for(let u of r)if(u.type==="web_search_tool_result")for(let l of w(u.content))f(l)&&(l.type!==void 0&&l.type!=="web_search_result"||e.add(h(l.url),h(l.title)));let s=f(n.usage)?n.usage:{},a=f(s.server_tool_use)?s.server_tool_use:{},p=k(a.web_search_requests);return{text:o.trim(),citations:e.citations,inputTokens:k(s.input_tokens),outputTokens:k(s.output_tokens),searchCalls:p>0?p:i}}function J(t,n){let e=/\s*$/.exec(t),r=e?e.index:t.length;return t.slice(0,r)+n+t.slice(r)}function O(t){let n=new A,e=f(t.groundingMetadata)?t.groundingMetadata:{},r=[];for(let s of w(e.groundingChunks)){let a=f(s)&&f(s.web)?s.web:f(s)&&f(s.retrievedContext)?s.retrievedContext:null;r.push(a?n.add(h(a.uri),h(a.title)):null)}for(let s of t.sources??[])n.add(h(s?.url),h(s?.title));let o=t.text;for(let s of w(e.groundingSupports)){if(!f(s))continue;let a=f(s.segment)?s.segment:{},p=h(a.text)??h(s.segment_text);if(!p)continue;let u=w(s.groundingChunkIndices).map(m=>typeof m=="number"?r[m]:null).filter(m=>typeof m=="number");if(u.length===0)continue;let l=o.indexOf(p);if(l===-1)continue;let c=l+p.length;o=o.slice(0,c)+S(u)+o.slice(c)}let i=w(e.webSearchQueries).length;return{text:o,citations:n.citations,searchCalls:i>0||n.citations.length>0?1:0}}var R=["chatgpt","claude","gemini","perplexity"],$={chatgpt:{model:"chatgpt",env:["OPENAI_API_KEY"],modelId:"gpt-4.1",estimateUsd:.035},claude:{model:"claude",env:["ANTHROPIC_API_KEY"],modelId:"claude-haiku-5-5",estimateUsd:.015},gemini:{model:"gemini",env:["GEMINI_API_KEY","GOOGLE_API_KEY","GOOGLE_GENERATIVE_AI_API_KEY"],modelId:"gemini-2.5-flash",estimateUsd:.04},perplexity:{model:"perplexity",env:["PERPLEXITY_API_KEY"],modelId:"sonar",estimateUsd:.008}},B=[{model:"chatgpt",modelId:"gpt-4.1-mini",estimateUsd:.001},{model:"gemini",modelId:"gemini-2.5-flash",estimateUsd:.001},{model:"claude",modelId:"claude-haiku-5-5",estimateUsd:.002}];function j(t,n){for(let e of $[t].env)if(n[e]?.trim())return n[e].trim()}function nt(t,n=R){return n.filter(e=>j(e,t))}function D(t){for(let n of B){let e=j(n.model,t);if(e)return{...n,key:e}}return null}function st(t,n,e){let r=D(e),o=n.reduce((i,s)=>i+$[s].estimateUsd+(r?.estimateUsd??0),0);return Math.round(t*o*100)/100}var Y=t=>new Promise(n=>setTimeout(n,t));async function b(t,n,e,r,o=12e4){let i="";for(let s=0;s<4;s++){let a=await t(n,{method:"POST",headers:{"content-type":"application/json",...e},body:JSON.stringify(r),signal:AbortSignal.timeout(o)}),p=await a.text();if(a.ok)return JSON.parse(p);if(i=`${a.status} ${q(p)}`,a.status!==429&&a.status<500)break;let u=Number(a.headers.get("retry-after"));await Y(Number.isFinite(u)&&u>0?Math.min(u*1e3,3e4):2e3*2**s)}throw new Error(i)}function q(t){try{let n=JSON.parse(t),e=Array.isArray(n)?n[0]?.error:n.error;return(typeof e=="string"?e:e?.message)??t.slice(0,200)}catch{return t.slice(0,200)}}var H={"gpt-4.1":{in:2,out:8},"gpt-4.1-mini":{in:.4,out:1.6},"claude-haiku-5-5":{in:.1,out:.5},"gemini-2.5-flash":{in:.3,out:2.5},sonar:{in:1,out:1}},C={chatgpt:.025,claude:.01,gemini:.035,perplexity:.005},x=(t,n,e)=>{let r=H[t];return r?(n*r.in+e*r.out)/1e6:0};function K(t,n){return`You are a helpful assistant recommending mobile apps.
4
- The user is in ${t.toUpperCase()} and writes in ${n.toUpperCase()}.
3
+ `).trim();!r&&typeof n.output_text=="string"&&(r=n.output_text.trim());let c=h(n.usage)?n.usage:{};return{text:r,citations:t.citations,inputTokens:_(c.input_tokens),outputTokens:_(c.output_tokens),searchCalls:i,searchQueries:M(s)}}function J(e,n,t){let o=typeof n.start_index=="number"?n.start_index:null,s=typeof n.end_index=="number"?n.end_index:null,i="";try{i=new URL(t).hostname.replace(/^www\./,"")}catch{}if(o!==null&&s!==null&&s<=e.length&&o<s){let m=e.slice(o,s);if(m.includes(t)||i&&m.includes(i))return s}let r=e.indexOf(t);if(r===-1)return null;let c=r+t.length;for(;c<e.length&&e[c]===")";)c+=1;return c}function B(e,n){if(n.length===0)return e;let t=new Map;for(let{at:s,n:i}of n)t.set(s,[...t.get(s)??[],i]);let o=e;for(let s of Array.from(t.keys()).sort((i,r)=>r-i))o=o.slice(0,s)+v(t.get(s))+o.slice(s);return o}function T(e){let n=h(e)?e:{},t=new C,o=w(n.content).filter(h),s="",i=0,r=[];for(let u of o){if(u.type==="server_tool_use"&&u.name==="web_search"&&(i+=1,h(u.input)&&r.push(u.input.query)),u.type!=="text")continue;let a=typeof u.text=="string"?u.text:"",p=[];for(let g of w(u.citations)){if(!h(g)||g.type!==void 0&&g.type!=="web_search_result_location")continue;let d=t.add(y(g.url),y(g.title));d!==null&&p.push(d)}s+=p.length>0?Q(a,v(p)):a}for(let u of o)if(u.type==="web_search_tool_result")for(let a of w(u.content))h(a)&&(a.type!==void 0&&a.type!=="web_search_result"||t.add(y(a.url),y(a.title)));let c=h(n.usage)?n.usage:{},m=h(c.server_tool_use)?c.server_tool_use:{},l=_(m.web_search_requests);return{text:s.trim(),citations:t.citations,inputTokens:_(c.input_tokens),outputTokens:_(c.output_tokens),searchCalls:l>0?l:i,searchQueries:M(r)}}function Q(e,n){let t=/\s*$/.exec(e),o=t?t.index:e.length;return e.slice(0,o)+n+e.slice(o)}function N(e){let n=new C,t=h(e.groundingMetadata)?e.groundingMetadata:{},o=[];for(let r of w(t.groundingChunks)){let c=h(r)&&h(r.web)?r.web:h(r)&&h(r.retrievedContext)?r.retrievedContext:null;o.push(c?n.add(y(c.uri),y(c.title)):null)}for(let r of e.sources??[])n.add(y(r?.url),y(r?.title));let s=e.text;for(let r of w(t.groundingSupports)){if(!h(r))continue;let c=h(r.segment)?r.segment:{},m=y(c.text)??y(r.segment_text);if(!m)continue;let l=w(r.groundingChunkIndices).map(p=>typeof p=="number"?o[p]:null).filter(p=>typeof p=="number");if(l.length===0)continue;let u=s.indexOf(m);if(u===-1)continue;let a=u+m.length;s=s.slice(0,a)+v(l)+s.slice(a)}let i=M(w(t.webSearchQueries));return{text:s,citations:n.citations,searchCalls:i.length>0||n.citations.length>0?1:0,searchQueries:i}}var j=["chatgpt","claude","gemini","perplexity"],R={chatgpt:{model:"chatgpt",env:["OPENAI_API_KEY"],modelId:"gpt-4.1",estimateUsd:.035},claude:{model:"claude",env:["ANTHROPIC_API_KEY"],modelId:"claude-haiku-5-5",estimateUsd:.015},gemini:{model:"gemini",env:["GEMINI_API_KEY","GOOGLE_API_KEY","GOOGLE_GENERATIVE_AI_API_KEY"],modelId:"gemini-2.5-flash",estimateUsd:.04},perplexity:{model:"perplexity",env:["PERPLEXITY_API_KEY"],modelId:"sonar",estimateUsd:.008}},Y=[{model:"chatgpt",modelId:"gpt-4.1-mini",estimateUsd:.001},{model:"gemini",modelId:"gemini-2.5-flash",estimateUsd:.001},{model:"claude",modelId:"claude-haiku-5-5",estimateUsd:.002}];function L(e,n){for(let t of R[e].env)if(n[t]?.trim())return n[t].trim()}function re(e,n=j){return n.filter(t=>L(t,e))}function D(e){for(let n of Y){let t=L(n.model,e);if(t)return{...n,key:t}}return null}function ie(e,n,t){let o=D(t),s=n.reduce((i,r)=>i+R[r].estimateUsd+(o?.estimateUsd??0),0);return Math.round(e*s*100)/100}var H=e=>new Promise(n=>setTimeout(n,e));async function b(e,n,t,o,s=12e4){let i="";for(let r=0;r<4;r++){let c=await e(n,{method:"POST",headers:{"content-type":"application/json",...t},body:JSON.stringify(o),signal:AbortSignal.timeout(s)}),m=await c.text();if(c.ok)return JSON.parse(m);if(i=`${c.status} ${K(m)}`,c.status!==429&&c.status<500)break;let l=Number(c.headers.get("retry-after"));await H(Number.isFinite(l)&&l>0?Math.min(l*1e3,3e4):2e3*2**r)}throw new Error(i)}function K(e){try{let n=JSON.parse(e),t=Array.isArray(n)?n[0]?.error:n.error;return(typeof t=="string"?t:t?.message)??e.slice(0,200)}catch{return e.slice(0,200)}}var V={"gpt-4.1":{in:2,out:8},"gpt-4.1-mini":{in:.4,out:1.6},"claude-haiku-5-5":{in:.1,out:.5},"gemini-2.5-flash":{in:.3,out:2.5},sonar:{in:1,out:1}},S={chatgpt:.025,claude:.01,gemini:.035,perplexity:.005},x=(e,n,t)=>{let o=V[e];return o?(n*o.in+t*o.out)/1e6:0};function z(e,n){return`You are a helpful assistant recommending mobile apps.
4
+ The user is in ${e.toUpperCase()} and writes in ${n.toUpperCase()}.
5
5
  When the user asks for an app, return a short ranked list (1\u20135) of real,
6
6
  currently-available apps. For each app: state its name first, then a
7
7
  one-sentence reason. Prefer iOS App Store apps. Be specific \u2014 name the
8
8
  exact app, not a category. If you genuinely cannot recommend any app,
9
- say so plainly.`}function z(t){let n=t.toLowerCase();return["i can't recommend","i cannot recommend","i'm unable to recommend","i am unable to recommend"].some(e=>n.includes(e))||n.startsWith("i'm sorry")||n.startsWith("sorry, i")}var L=t=>/claude-[a-z]+-5/.test(t)?{max_tokens:16e3}:{max_tokens:1500,temperature:.4};async function ot(t,n,e,r=fetch){let o=$[t].modelId,i=K(e.country,e.language);try{let s="",a=[],p=0;if(t==="chatgpt"){let u=await b(r,"https://api.openai.com/v1/responses",{authorization:`Bearer ${n}`},{model:o,instructions:i,input:e.prompt,temperature:.4,tools:[{type:"web_search_preview",search_context_size:"low"}]}),l=E(u);({text:s,citations:a}=l),p=x(o,l.inputTokens,l.outputTokens)+C.chatgpt*Math.max(1,l.searchCalls)}else if(t==="claude"){let u=await b(r,"https://api.anthropic.com/v1/messages",{"x-api-key":n,"anthropic-version":"2023-06-01"},{model:o,...L(o),system:i,messages:[{role:"user",content:e.prompt}],tools:[{type:"web_search_20250305",name:"web_search",max_uses:3}]}),l=T(u);({text:s,citations:a}=l),p=x(o,l.inputTokens,l.outputTokens)+C.claude*Math.max(1,l.searchCalls)}else if(t==="gemini"){let u=await b(r,`https://generativelanguage.googleapis.com/v1beta/models/${o}:generateContent`,{"x-goog-api-key":n},{systemInstruction:{parts:[{text:i}]},contents:[{role:"user",parts:[{text:e.prompt}]}],tools:[{google_search:{}}],generationConfig:{temperature:.4}}),l=u?.candidates?.[0],c=(l?.content?.parts??[]).map(d=>d.text??"").join(""),m=O({text:c,groundingMetadata:l?.groundingMetadata});({text:s,citations:a}=m);let g=u?.usageMetadata??{};p=x(o,g.promptTokenCount??0,(g.candidatesTokenCount??0)+(g.thoughtsTokenCount??0))+(m.searchCalls>0?C.gemini:0)}else{let u=await b(r,"https://api.perplexity.ai/chat/completions",{authorization:`Bearer ${n}`},{model:o,temperature:.4,messages:[{role:"system",content:i},{role:"user",content:e.prompt}]});s=u?.choices?.[0]?.message?.content??"",a=(Array.isArray(u?.search_results)&&u.search_results.length?u.search_results:Array.isArray(u?.citations)?u.citations:[]).map(c=>typeof c=="string"?{url:c}:c&&typeof c.url=="string"?{url:c.url,title:c.title}:null).filter(c=>c!==null),p=x(o,u?.usage?.prompt_tokens??0,u?.usage?.completion_tokens??0)+C.perplexity}return{model:t,modelId:o,status:z(s)?"refusal":"ok",text:s,citations:a,costUsd:p}}catch(s){return{model:t,modelId:o,status:"error",text:"",citations:[],costUsd:0,error:s.message}}}function v(t){let n=t.indexOf("{"),e=t.lastIndexOf("}");if(n===-1||e<=n)throw new Error("no JSON in the answer");return JSON.parse(t.slice(n,e+1))}async function P(t,n,e,r=fetch){if(t.model==="chatgpt"){let s=await b(r,"https://api.openai.com/v1/chat/completions",{authorization:`Bearer ${t.key}`},{model:t.modelId,temperature:e,response_format:{type:"json_object"},messages:[{role:"user",content:n}]});return{json:v(s?.choices?.[0]?.message?.content??""),costUsd:x(t.modelId,s?.usage?.prompt_tokens??0,s?.usage?.completion_tokens??0)}}if(t.model==="gemini"){let s=await b(r,`https://generativelanguage.googleapis.com/v1beta/models/${t.modelId}:generateContent`,{"x-goog-api-key":t.key},{contents:[{role:"user",parts:[{text:n}]}],generationConfig:{temperature:e,responseMimeType:"application/json"}}),a=(s?.candidates?.[0]?.content?.parts??[]).map(u=>u.text??"").join(""),p=s?.usageMetadata??{};return{json:v(a),costUsd:x(t.modelId,p.promptTokenCount??0,(p.candidatesTokenCount??0)+(p.thoughtsTokenCount??0))}}let o=await b(r,"https://api.anthropic.com/v1/messages",{"x-api-key":t.key,"anthropic-version":"2023-06-01"},{model:t.modelId,...L(t.modelId),messages:[{role:"user",content:`${n}
9
+ say so plainly.`}function X(e){let n=e.toLowerCase();return["i can't recommend","i cannot recommend","i'm unable to recommend","i am unable to recommend"].some(t=>n.includes(t))||n.startsWith("i'm sorry")||n.startsWith("sorry, i")}var q=e=>/claude-[a-z]+-5/.test(e)?{max_tokens:16e3}:{max_tokens:1500,temperature:.4};async function ae(e,n,t,o=fetch){let s=R[e].modelId,i=z(t.country,t.language);try{let r="",c=[],m=[],l=0;if(e==="chatgpt"){let u=await b(o,"https://api.openai.com/v1/responses",{authorization:`Bearer ${n}`},{model:s,instructions:i,input:t.prompt,temperature:.4,tools:[{type:"web_search_preview",search_context_size:"low"}]}),a=O(u);({text:r,citations:c}=a),m=a.searchQueries??[],l=x(s,a.inputTokens,a.outputTokens)+S.chatgpt*Math.max(1,a.searchCalls)}else if(e==="claude"){let u=await b(o,"https://api.anthropic.com/v1/messages",{"x-api-key":n,"anthropic-version":"2023-06-01"},{model:s,...q(s),system:i,messages:[{role:"user",content:t.prompt}],tools:[{type:"web_search_20250305",name:"web_search",max_uses:3}]}),a=T(u);({text:r,citations:c}=a),m=a.searchQueries??[],l=x(s,a.inputTokens,a.outputTokens)+S.claude*Math.max(1,a.searchCalls)}else if(e==="gemini"){let u=await b(o,`https://generativelanguage.googleapis.com/v1beta/models/${s}:generateContent`,{"x-goog-api-key":n},{systemInstruction:{parts:[{text:i}]},contents:[{role:"user",parts:[{text:t.prompt}]}],tools:[{google_search:{}}],generationConfig:{temperature:.4}}),a=u?.candidates?.[0],p=(a?.content?.parts??[]).map(f=>f.text??"").join(""),g=N({text:p,groundingMetadata:a?.groundingMetadata});({text:r,citations:c}=g),m=g.searchQueries??[];let d=u?.usageMetadata??{};l=x(s,d.promptTokenCount??0,(d.candidatesTokenCount??0)+(d.thoughtsTokenCount??0))+(g.searchCalls>0?S.gemini:0)}else{let u=await b(o,"https://api.perplexity.ai/chat/completions",{authorization:`Bearer ${n}`},{model:s,temperature:.4,messages:[{role:"system",content:i},{role:"user",content:t.prompt}]});r=u?.choices?.[0]?.message?.content??"",c=(Array.isArray(u?.search_results)&&u.search_results.length?u.search_results:Array.isArray(u?.citations)?u.citations:[]).map(p=>typeof p=="string"?{url:p}:p&&typeof p.url=="string"?{url:p.url,title:p.title}:null).filter(p=>p!==null),l=x(s,u?.usage?.prompt_tokens??0,u?.usage?.completion_tokens??0)+S.perplexity}return{model:e,modelId:s,status:X(r)?"refusal":"ok",text:r,citations:c,searches:m,costUsd:l}}catch(r){return{model:e,modelId:s,status:"error",text:"",citations:[],searches:[],costUsd:0,error:r.message}}}function E(e){let n=e.indexOf("{"),t=e.lastIndexOf("}");if(n===-1||t<=n)throw new Error("no JSON in the answer");return JSON.parse(e.slice(n,t+1))}async function P(e,n,t,o=fetch){if(e.model==="chatgpt"){let r=await b(o,"https://api.openai.com/v1/chat/completions",{authorization:`Bearer ${e.key}`},{model:e.modelId,temperature:t,response_format:{type:"json_object"},messages:[{role:"user",content:n}]});return{json:E(r?.choices?.[0]?.message?.content??""),costUsd:x(e.modelId,r?.usage?.prompt_tokens??0,r?.usage?.completion_tokens??0)}}if(e.model==="gemini"){let r=await b(o,`https://generativelanguage.googleapis.com/v1beta/models/${e.modelId}:generateContent`,{"x-goog-api-key":e.key},{contents:[{role:"user",parts:[{text:n}]}],generationConfig:{temperature:t,responseMimeType:"application/json"}}),c=(r?.candidates?.[0]?.content?.parts??[]).map(l=>l.text??"").join(""),m=r?.usageMetadata??{};return{json:E(c),costUsd:x(e.modelId,m.promptTokenCount??0,(m.candidatesTokenCount??0)+(m.thoughtsTokenCount??0))}}let s=await b(o,"https://api.anthropic.com/v1/messages",{"x-api-key":e.key,"anthropic-version":"2023-06-01"},{model:e.modelId,...q(e.modelId),messages:[{role:"user",content:`${n}
10
10
 
11
- Answer with the JSON object only.`}]}),i=(o?.content??[]).filter(s=>s.type==="text").map(s=>s.text).join("");return{json:v(i),costUsd:x(t.modelId,o?.usage?.input_tokens??0,o?.usage?.output_tokens??0)}}function V(t){let n=t.competitors.length?`
12
- Known competitor apps: ${t.competitors.slice(0,10).join(", ")}`:"",e=t.citations.length?`
11
+ Answer with the JSON object only.`}]}),i=(s?.content??[]).filter(r=>r.type==="text").map(r=>r.text).join("");return{json:E(i),costUsd:x(e.modelId,s?.usage?.input_tokens??0,s?.usage?.output_tokens??0)}}function Z(e){let n=e.competitors.length?`
12
+ Known competitor apps: ${e.competitors.slice(0,10).join(", ")}`:"",t=e.citations.length?`
13
13
 
14
14
  Citations available (0-indexed):
15
- ${t.citations.slice(0,10).map((r,o)=>` [${o}] ${r.title??r.url}`).join(`
15
+ ${e.citations.slice(0,10).map((o,s)=>` [${s}] ${o.title??o.url}`).join(`
16
16
  `)}`:"";return`You parse a recommendation answer from an AI assistant and extract
17
17
  which mobile apps were mentioned, and in which position.
18
18
 
19
19
  Original user prompt:
20
- """${t.prompt}"""
20
+ """${e.prompt}"""
21
21
 
22
22
  The user owns this app (recognise it even with minor spelling variants):
23
- "${t.owner}"${n}
23
+ "${e.owner}"${n}
24
24
 
25
25
  Assistant's answer:
26
- """${t.answer.slice(0,8e3)}"""${e}
26
+ """${e.answer.slice(0,8e3)}"""${t}
27
27
 
28
28
  Return JSON: {"refusal": boolean, "apps": [{"appName": string, "position": number|null, "citationIndex": number|null}]}
29
29
 
@@ -40,21 +40,21 @@ Rules:
40
40
  generic phrases like "an app for X" \u2014 only specific named apps.
41
41
  - Strip explanatory parentheses from appName (return "Calm" not
42
42
  "Calm (popular meditation app)").
43
- - App names should be the brand the assistant used.`}async function rt(t,n,e=fetch){let{json:r,costUsd:o}=await P(t,V(n),0,e),s=(Array.isArray(r?.apps)?r.apps:[]).map(a=>a).filter(a=>typeof a.appName=="string"&&a.appName.trim()).map(a=>({name:a.appName.trim(),position:typeof a.position=="number"&&a.position>=1?Math.round(a.position):null,citation:typeof a.citationIndex=="number"&&a.citationIndex>=0?Math.round(a.citationIndex):null}));return{refusal:!!r?.refusal,mentions:s,costUsd:o}}var _=t=>t.toLowerCase().replace(/[^\p{L}\p{N}]/gu,"");function N(t,n){let e=_(t);return e?n.some(r=>[r,r.split(/\s[:\-–—|]\s|:\s/)[0]??r].map(_).filter(i=>i.length>=3).some(i=>e===i||i.length>=4&&(e.includes(i)||i.includes(e)&&e.length>=i.length*.7))):!1}var X=25,I=t=>Math.round(t*10)/10;function it(t,n,e){return n.map(r=>{let o=t.filter(c=>c.intent===r&&(c.status==="ok"||c.status==="refusal")),i={};for(let c of R){let m=o.filter(y=>y.model===c);if(!m.length)continue;let g=m.map(y=>y.mentions.find(M=>N(M.name,e))).filter(y=>!!y),d=g.map(y=>y.position).filter(y=>y!==null);i[c]={pct:I(g.length/m.length*100),position:d.length?I(d.reduce((y,M)=>y+M,0)/d.length):null,prompts:m.length}}let s=Object.values(i),a=s.length?I(s.reduce((c,m)=>c+m.pct,0)/s.length):void 0,p=new Map;for(let c of o)for(let m of c.mentions){if(N(m.name,e))continue;let g=_(m.name),d=p.get(g)??{name:m.name,count:0,models:new Set};d.count++,d.models.add(c.model),p.set(g,d)}let u=[...p.values()].sort((c,m)=>m.count-c.count||c.name.localeCompare(m.name)).slice(0,5).map(c=>({name:c.name,pct:o.length?Math.min(100,I(c.count/o.length*100)):0,models:[...c.models]})),l=a===void 0?"no_data":a>=X?"winning":a>0?"weak":"missing";return{label:r,status:l,you:a,byModel:i,namedInstead:u}})}function at(t,n){let e=n.map(o=>o.toLowerCase().replace(/^www\./,"")),r=new Map;for(let o of t)for(let i of o.citations){let s;try{s=new URL(i.url).hostname.toLowerCase().replace(/^www\./,"")}catch{continue}s.endsWith("vertexaisearch.cloud.google.com")&&i.title&&/^[\w.-]+\.[a-z]{2,}$/i.test(i.title)&&(s=i.title.toLowerCase().replace(/^www\./,""));let a=r.get(s)??{domain:s,count:0,url:i.url};a.count++,e.some(p=>s===p||s.endsWith(`.${p}`))&&(a.yours=!0),r.set(s,a)}return[...r.values()].sort((o,i)=>i.count-o.count||o.domain.localeCompare(i.domain))}function Q(t,n,e){return`You map a mobile app to the *user intents* it serves \u2014 the goals
43
+ - App names should be the brand the assistant used.`}async function ce(e,n,t=fetch){let{json:o,costUsd:s}=await P(e,Z(n),0,t),r=(Array.isArray(o?.apps)?o.apps:[]).map(c=>c).filter(c=>typeof c.appName=="string"&&c.appName.trim()).map(c=>({name:c.appName.trim(),position:typeof c.position=="number"&&c.position>=1?Math.round(c.position):null,citation:typeof c.citationIndex=="number"&&c.citationIndex>=0?Math.round(c.citationIndex):null}));return{refusal:!!o?.refusal,mentions:r,costUsd:s}}var A=e=>e.toLowerCase().replace(/[^\p{L}\p{N}]/gu,"");function $(e,n){let t=A(e);return t?n.some(o=>[o,o.split(/\s[:\-–—|]\s|:\s/)[0]??o].map(A).filter(i=>i.length>=3).some(i=>t===i||i.length>=4&&(t.includes(i)||i.includes(t)&&t.length>=i.length*.7))):!1}var ee=25,k=e=>Math.round(e*10)/10;function ue(e,n,t){return n.map(o=>{let s=e.filter(a=>a.intent===o&&(a.status==="ok"||a.status==="refusal")),i={};for(let a of j){let p=s.filter(f=>f.model===a);if(!p.length)continue;let g=p.map(f=>f.mentions.find(I=>$(I.name,t))).filter(f=>!!f),d=g.map(f=>f.position).filter(f=>f!==null);i[a]={pct:k(g.length/p.length*100),position:d.length?k(d.reduce((f,I)=>f+I,0)/d.length):null,prompts:p.length}}let r=Object.values(i),c=r.length?k(r.reduce((a,p)=>a+p.pct,0)/r.length):void 0,m=new Map;for(let a of s)for(let p of a.mentions){if($(p.name,t))continue;let g=A(p.name),d=m.get(g)??{name:p.name,count:0,models:new Set};d.count++,d.models.add(a.model),m.set(g,d)}let l=[...m.values()].sort((a,p)=>p.count-a.count||a.name.localeCompare(p.name)).slice(0,5).map(a=>({name:a.name,pct:s.length?Math.min(100,k(a.count/s.length*100)):0,models:[...a.models]})),u=c===void 0?"no_data":c>=ee?"winning":c>0?"weak":"missing";return{label:o,status:u,you:c,byModel:i,namedInstead:l}})}function le(e,n){let t=e.filter(l=>l.status==="ok"||l.status==="refusal"),o=new Map,s=0;for(let l of t){let u=new Set;for(let a of l.mentions){let p=$(a.name,n),g=p?"\0you":A(a.name);if(!g||u.has(g))continue;u.add(g);let d=o.get(g)??{name:p?n[0]:a.name,you:p,hits:0,firsts:0,positions:[]};d.hits++,s++,a.position===1&&d.firsts++,a.position!==null&&d.positions.push(a.position),o.set(g,d)}}let i=(l,u)=>u?k(l/u*100):0,r=l=>({name:l.name,...l.you?{you:!0}:{},visibility:i(l.hits,t.length),shareOfVoice:i(l.hits,s),winRate:i(l.firsts,t.length),position:l.positions.length?k(l.positions.reduce((u,a)=>u+a,0)/l.positions.length):null}),c=[...o.values()].sort((l,u)=>u.hits-l.hits||l.name.localeCompare(u.name)).map(r),m=c.find(l=>l.you)??{name:n[0]??"",you:!0,visibility:0,shareOfVoice:0,winRate:0,position:null};return{answers:t.length,you:m,apps:c}}function pe(e){let n=new Map;for(let t of e)for(let o of t.searches??[]){let s=o.toLowerCase().replace(/\s+/g," ").trim();if(!s)continue;let i=n.get(s)??{query:o.trim(),count:0,models:new Set};i.count++,i.models.add(t.model),n.set(s,i)}return[...n.values()].sort((t,o)=>o.count-t.count||t.query.localeCompare(o.query)).map(t=>({query:t.query,count:t.count,models:[...t.models]}))}function me(e,n){let t=n.map(s=>s.toLowerCase().replace(/^www\./,"")),o=new Map;for(let s of e)for(let i of s.citations){let r;try{r=new URL(i.url).hostname.toLowerCase().replace(/^www\./,"")}catch{continue}r.endsWith("vertexaisearch.cloud.google.com")&&i.title&&/^[\w.-]+\.[a-z]{2,}$/i.test(i.title)&&(r=i.title.toLowerCase().replace(/^www\./,""));let c=o.get(r)??{domain:r,count:0,url:i.url};c.count++,t.some(m=>r===m||r.endsWith(`.${m}`))&&(c.yours=!0),o.set(r,c)}return[...o.values()].sort((s,i)=>i.count-s.count||s.domain.localeCompare(i.domain))}function te(e,n,t){return`You map a mobile app to the *user intents* it serves \u2014 the goals
44
44
  real users would ask an AI assistant (like ChatGPT, Gemini, or
45
45
  Perplexity) about. Each intent is a short user-meaningful goal,
46
46
  NOT an app feature.
47
47
 
48
- App: ${t.title}${t.subtitle?`
49
- Subtitle: ${t.subtitle}`:""}${t.description?`
50
- Description (first 700 chars): ${t.description.slice(0,700)}`:""}${t.keywords?.length?`
51
- Target keywords: ${t.keywords.slice(0,20).join(", ")}`:""}
48
+ App: ${e.title}${e.subtitle?`
49
+ Subtitle: ${e.subtitle}`:""}${e.description?`
50
+ Description (first 700 chars): ${e.description.slice(0,700)}`:""}${e.keywords?.length?`
51
+ Target keywords: ${e.keywords.slice(0,20).join(", ")}`:""}
52
52
 
53
- Country: ${t.country.toUpperCase()}
54
- Language: ${t.language.toUpperCase()}${e.length?`
53
+ Country: ${e.country.toUpperCase()}
54
+ Language: ${e.language.toUpperCase()}${t.length?`
55
55
 
56
56
  ALREADY DEFINED (do NOT propose duplicates or near-duplicates):
57
- - ${e.slice(0,30).join(`
57
+ - ${t.slice(0,30).join(`
58
58
  - `)}`:""}
59
59
 
60
60
  Return JSON: {"intents": [{"label": string, "description": string}]}
@@ -69,7 +69,7 @@ Rules:
69
69
  problem-driven goals, and at least one comparison/alternative angle when applicable.
70
70
  - Write labels in the storefront's language.
71
71
  - Description (1 sentence, max 200 chars): what kind of user has this
72
- intent and what they want the assistant to recommend.`}function Z(t,n,e){return`You write realistic prompts that everyday users would type into an
72
+ intent and what they want the assistant to recommend.`}function ne(e,n,t){return`You write realistic prompts that everyday users would type into an
73
73
  AI assistant (ChatGPT, Gemini, Perplexity) when looking for a mobile app.
74
74
 
75
75
  Intent to cover:
@@ -77,20 +77,20 @@ Intent to cover:
77
77
  ${n.description}`:""}
78
78
 
79
79
  App context (the app whose visibility we're measuring):
80
- Title: ${t.title}${t.subtitle?`
81
- Subtitle: ${t.subtitle}`:""}${t.competitors?.length?`
82
- Known competitor apps (use in comparison prompts where natural): ${t.competitors.slice(0,6).join(", ")}`:""}
80
+ Title: ${e.title}${e.subtitle?`
81
+ Subtitle: ${e.subtitle}`:""}${e.competitors?.length?`
82
+ Known competitor apps (use in comparison prompts where natural): ${e.competitors.slice(0,6).join(", ")}`:""}
83
83
 
84
- Country: ${t.country.toUpperCase()}
85
- Language: ${t.language.toUpperCase()}
84
+ Country: ${e.country.toUpperCase()}
85
+ Language: ${e.language.toUpperCase()}
86
86
 
87
87
  Return JSON: {"prompts": [string]}
88
88
 
89
89
  Rules:
90
- - Produce ${e} prompts that cover the intent from different angles:
90
+ - Produce ${t} prompts that cover the intent from different angles:
91
91
  a pure category query, a problem-first one ("I struggle with\u2026"),
92
92
  a scenario ("an app for my morning routine"), and where natural an
93
93
  "alternative to X" comparison. Never name the app being measured.
94
94
  - Write the way a casual user types, in the storefront's language:
95
95
  conversational, lower-case is fine. Length 8\u201335 words.
96
- - Do NOT mention that you're an AI or test prompts. No emojis.`}var U=t=>t.toLowerCase().replace(/[^\p{L}\p{N}\s]/gu," ").split(/\s+/).filter(Boolean).sort().join(" ");async function ct(t,n,e={},r=fetch){let o=e.maxIntents??6,i=await P(t,Q(n,o,e.exclude??[]),.7,r),s=i.costUsd,a=new Set((e.exclude??[]).map(U)),p=[];for(let l of Array.isArray(i.json?.intents)?i.json.intents:[]){if(typeof l?.label!="string"||l.label.trim().length<4)continue;let c=U(l.label);if(!a.has(c)&&(a.add(c),p.push({label:l.label.trim(),description:typeof l.description=="string"?l.description.trim():void 0}),p.length>=o))break}let u=[];for(let l of p){let c=await P(t,Z(n,l,e.promptsPerIntent??4),.8,r);s+=c.costUsd;let m=_(n.title.split(/[:\-–—|]/)[0]??n.title),g=[...new Set((Array.isArray(c.json?.prompts)?c.json.prompts:[]).filter(d=>typeof d=="string"&&d.trim().length>=15).map(d=>d.trim()))].filter(d=>m.length<4||!_(d).includes(m)).slice(0,e.promptsPerIntent??4);g.length&&u.push({...l,prompts:g})}return{intents:u,costUsd:s}}export{R as MODELS,$ as PROVIDERS,X as WINNING_PCT,ot as ask,nt as availableModels,at as citedDomains,rt as extract,ct as generateIntents,D as helperFor,P as helperJson,N as isOwner,j as keyFor,st as quoteScan,it as score};
96
+ - Do NOT mention that you're an AI or test prompts. No emojis.`}var U=e=>e.toLowerCase().replace(/[^\p{L}\p{N}\s]/gu," ").split(/\s+/).filter(Boolean).sort().join(" ");async function de(e,n,t={},o=fetch){let s=t.maxIntents??6,i=await P(e,te(n,s,t.exclude??[]),.7,o),r=i.costUsd,c=new Set((t.exclude??[]).map(U)),m=[];for(let u of Array.isArray(i.json?.intents)?i.json.intents:[]){if(typeof u?.label!="string"||u.label.trim().length<4)continue;let a=U(u.label);if(!c.has(a)&&(c.add(a),m.push({label:u.label.trim(),description:typeof u.description=="string"?u.description.trim():void 0}),m.length>=s))break}let l=[];for(let u of m){let a=await P(e,ne(n,u,t.promptsPerIntent??4),.8,o);r+=a.costUsd;let p=A(n.title.split(/[:\-–—|]/)[0]??n.title),g=[...new Set((Array.isArray(a.json?.prompts)?a.json.prompts:[]).filter(d=>typeof d=="string"&&d.trim().length>=15).map(d=>d.trim()))].filter(d=>p.length<4||!A(d).includes(p)).slice(0,t.promptsPerIntent??4);g.length&&l.push({...u,prompts:g})}return{intents:l,costUsd:r}}export{j as MODELS,R as PROVIDERS,ee as WINNING_PCT,ae as ask,re as availableModels,me as citedDomains,ce as extract,de as generateIntents,D as helperFor,P as helperJson,$ as isOwner,L as keyFor,le as overall,ie as quoteScan,ue as score,pe as searchQueries};
@@ -19,6 +19,7 @@ interface Answer {
19
19
  status: "ok" | "refusal" | "error";
20
20
  text: string;
21
21
  citations: Citation[];
22
+ searches?: string[];
22
23
  costUsd: number;
23
24
  error?: string;
24
25
  }
@@ -40,6 +41,15 @@ interface ScoredAnswer {
40
41
  status: Answer["status"];
41
42
  mentions: Mention[];
42
43
  citations: Citation[];
44
+ searches?: string[];
45
+ }
46
+ interface AppShare {
47
+ name: string;
48
+ you?: true;
49
+ visibility: number;
50
+ shareOfVoice: number;
51
+ winRate: number;
52
+ position: number | null;
43
53
  }
44
54
  interface IntentScore {
45
55
  label: string;
@@ -94,6 +104,16 @@ export interface VisibilityCore {
94
104
  }>;
95
105
  isOwner(name: string, titles: string[]): boolean;
96
106
  score(answers: ScoredAnswer[], intents: string[], owner: string[]): IntentScore[];
107
+ overall(answers: ScoredAnswer[], owner: string[]): {
108
+ answers: number;
109
+ you: AppShare;
110
+ apps: AppShare[];
111
+ };
112
+ searchQueries(answers: ScoredAnswer[]): Array<{
113
+ query: string;
114
+ count: number;
115
+ models: Model[];
116
+ }>;
97
117
  citedDomains(answers: ScoredAnswer[], ownDomains: string[]): Array<{
98
118
  domain: string;
99
119
  count: number;