@tangle-network/agent-app 0.60.60 → 0.60.62

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.
@@ -17,6 +17,44 @@ import { betterAuth } from "better-auth";
17
17
  import { drizzleAdapter } from "better-auth/adapters/drizzle";
18
18
  var DEFAULT_STATE_COOKIE = "tangle_sso_state";
19
19
  var DEFAULT_SESSION_COOKIE_CACHE_SECONDS = 5 * 60;
20
+ var SESSION_MEMO_MAX_MS = 3e4;
21
+ var SESSION_MEMO_LIMIT = 500;
22
+ var requestSessions = /* @__PURE__ */ new WeakMap();
23
+ var isolateSessions = /* @__PURE__ */ new Map();
24
+ function memoizedSession(scope, ttlMs, request, read) {
25
+ const known = requestSessions.get(request);
26
+ if (known) return known;
27
+ const cookie = request.headers.get("cookie") ?? "";
28
+ const authorization = request.headers.get("authorization") ?? "";
29
+ if (!cookie && !authorization) return read(request);
30
+ const key = `${scope}\0${authorization}\0${cookie}`;
31
+ const now = Date.now();
32
+ const hit = isolateSessions.get(key);
33
+ if (hit && hit.until > now) {
34
+ requestSessions.set(request, hit.session);
35
+ return hit.session;
36
+ }
37
+ const session = read(request).then((value) => {
38
+ const expiresAt = value ? new Date(value.session.expiresAt).getTime() : 0;
39
+ if (!value || !(expiresAt > Date.now())) isolateSessions.delete(key);
40
+ else {
41
+ const entry = isolateSessions.get(key);
42
+ if (entry) entry.until = Math.min(entry.until, expiresAt);
43
+ }
44
+ return value;
45
+ }, (error) => {
46
+ isolateSessions.delete(key);
47
+ throw error;
48
+ });
49
+ isolateSessions.delete(key);
50
+ isolateSessions.set(key, { until: now + ttlMs, session });
51
+ if (isolateSessions.size > SESSION_MEMO_LIMIT) isolateSessions.delete(isolateSessions.keys().next().value);
52
+ requestSessions.set(request, session);
53
+ return session;
54
+ }
55
+ function forgetSessions(scope) {
56
+ for (const key of isolateSessions.keys()) if (key.startsWith(`${scope}\0`)) isolateSessions.delete(key);
57
+ }
20
58
  function slugify(name) {
21
59
  return name.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
22
60
  }
@@ -155,10 +193,21 @@ function createAppAuth(config) {
155
193
  advanced: { cookiePrefix, ...config.advanced }
156
194
  };
157
195
  const auth = betterAuth(options);
158
- const getSession = async (request) => {
196
+ const readSession = async (request) => {
159
197
  const session = await auth.api.getSession({ headers: request.headers });
160
198
  return session ?? null;
161
199
  };
200
+ const memoMs = config.sessionCookieCacheSeconds === false ? 0 : Math.min(SESSION_MEMO_MAX_MS, (config.sessionCookieCacheSeconds ?? DEFAULT_SESSION_COOKIE_CACHE_SECONDS) * 1e3);
201
+ const memoScope = `${config.baseURL}\0${cookiePrefix}`;
202
+ const getSession = (request) => memoMs > 0 ? memoizedSession(memoScope, memoMs, request, readSession) : readSession(request);
203
+ const handler = auth.handler;
204
+ auth.handler = async (request) => {
205
+ try {
206
+ return await handler(request);
207
+ } finally {
208
+ if (request.method !== "GET") forgetSessions(memoScope);
209
+ }
210
+ };
162
211
  const loginPath = config.loginPath ?? "/login";
163
212
  const guard = createAuthGuard({ getSession, loginPath });
164
213
  let sso = null;
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/app-auth/index.ts"],"sourcesContent":["/**\n * better-auth config factory for agent products (#188 Phase 1). Every product\n * hand-rolls the same ~70–150 line setup — drizzle adapter over the standard\n * users/sessions/accounts/verifications tables, email+password with branded\n * reset/verification mail (`./email`), env-gated GitHub/Google social providers, session\n * cookie cache, and a per-app cookie prefix — and tax additionally\n * re-implemented better-auth's cookie signing for its Tangle SSO callback.\n * `createAppAuth` owns that mechanism once and returns the configured\n * better-auth instance plus the request guards products actually use.\n *\n * Domain stays a parameter: the drizzle db + schema, email client, provider\n * credentials, and SSO store/client all come from the product. No product\n * import, no engine re-implementation — the SSO path composes the existing\n * `platform/sso` cookie minter (`createBetterAuthSessionCookieMinter`), which\n * is byte-compatible with better-auth's own `makeSignature` contract.\n *\n * better-auth is an OPTIONAL peer: only this subpath imports it, so it is\n * deliberately NOT re-exported from the root barrel.\n */\n\nimport { betterAuth, type Auth, type BetterAuthOptions, type Session, type User } from 'better-auth'\nimport { drizzleAdapter } from 'better-auth/adapters/drizzle'\nimport { noticeEmail, type EmailAttachment, type EmailMessage, type EmailProduct } from '../email'\nimport { createAuthGuard, type AuthGuard } from '../platform/guards'\nimport {\n createBetterAuthSessionCookieMinter,\n createTangleSsoHandlers,\n type TangleSsoAccountStore,\n type TangleSsoAuthClient,\n type TangleSsoHandlers,\n type TangleIdentitySsoAccountStore,\n type TangleIdentitySsoAuthClient,\n type TangleOidcSsoAccountStore,\n type TangleOidcSsoAuthClient,\n} from '../platform/sso'\n\nconst DEFAULT_STATE_COOKIE = 'tangle_sso_state'\nconst DEFAULT_SESSION_COOKIE_CACHE_SECONDS = 5 * 60\n\n/** Structural slice of a Resend-style client — no `resend` import. */\nexport interface AppAuthEmailClient {\n emails: {\n send(message: {\n from: string\n to: string\n subject: string\n html: string\n text?: string\n /** Inline images the HTML references by `cid:`, such as the Tangle mark. */\n attachments?: EmailAttachment[]\n }): Promise<unknown>\n }\n}\n\n/** Define email configuration for app authentication including client, sender, verification, and warning options */\nexport interface AppAuthEmailConfig {\n /** A Resend-style client, or a lazy getter returning null when the API key\n * is absent (the products' dev default — mail is skipped with a warning,\n * sign-up itself must not crash). */\n resend: AppAuthEmailClient | (() => AppAuthEmailClient | null)\n /** RFC 5322 From; build it with `emailSender` from `./email`, e.g. `Legal Agent · Tangle <noreply@tangle.tools>`. */\n from: string\n /** Send a verification email on sign-up and auto-sign-in after verifying\n * (the tax/gtm behavior). Default false (the legal behavior). */\n verifyOnSignUp?: boolean\n /** Receives the \"email client unavailable\" warning. Default console.warn. */\n warn?: (message: string) => void\n}\n\n/** Env-shaped: pass the env vars straight through; the provider is registered\n * only when BOTH values are non-empty, so unset env disables it. */\nexport interface AppAuthSocialProviderConfig {\n clientId?: string\n clientSecret?: string\n}\n\n/** Define social authentication configuration options for GitHub and Google providers */\nexport interface AppAuthSocialConfig {\n github?: AppAuthSocialProviderConfig\n google?: AppAuthSocialProviderConfig\n}\n\n/** Cross-site Tangle SSO wiring. The factory supplies the better-auth side —\n * `setSessionCookie` via `createBetterAuthSessionCookieMinter(auth)` (signed\n * `__Secure-`/prefixed cookie that `auth.api.getSession` accepts) — so the\n * product no longer touches `better-auth/crypto` itself. */\nexport interface AppAuthSsoConfig {\n protocol?: 'legacy'\n /** Platform wire client (authorizeUrl + exchange). */\n client: TangleSsoAuthClient\n /** Product persistence: user upsert, session row, platform link. */\n store: TangleSsoAccountStore\n /** Absolute callback URL registered with the platform. */\n callbackUrl: string\n /** Default 'tangle_sso_state'. */\n stateCookieName?: string\n /** HMAC secret for the CSRF state cookie. Default: the auth `secret`. */\n stateSecret?: string\n /** Default: `baseURL` is https. Must match better-auth's own\n * secure-cookie decision or the cookie name lookup diverges. */\n secureCookies?: boolean\n sessionTtlSeconds?: number\n stateTtlSeconds?: number\n /** Post-login redirect fallback. Default '/app'. */\n defaultRedirectPath?: string\n /** Default: the top-level `loginPath`. */\n loginPath?: string\n /** Failure log hook (e.g. console.error). Default no-op. */\n log?: (message: string, error?: unknown) => void\n}\n\n/** Registered OIDC client configuration. The caller supplies Runtime PKCE; login does not mint an API key. */\nexport interface AppAuthOidcSsoConfig extends Omit<AppAuthSsoConfig, 'protocol' | 'client' | 'store'> {\n protocol: 'oidc'\n client: TangleOidcSsoAuthClient\n store: TangleOidcSsoAccountStore\n /** Pass the Runtime's `createPkcePair` helper from the OIDC-only caller. */\n createPkcePair: () => Promise<{ verifier: string; challenge: string }>\n}\n\n/** First-party identity login; no Platform API key is issued or stored. */\nexport interface AppAuthIdentitySsoConfig extends Omit<AppAuthSsoConfig, 'protocol' | 'client' | 'store'> {\n protocol: 'identity'\n client: TangleIdentitySsoAuthClient\n store: TangleIdentitySsoAccountStore\n}\n\n/** Define the structure for application authentication data including users, sessions, accounts, and verifications */\nexport interface AppAuthSchema {\n users: unknown\n sessions: unknown\n accounts: unknown\n verifications: unknown\n}\n\n/** Define configuration settings for app authentication including app name, base URL, secrets, and trusted origins */\nexport interface AppAuthConfig {\n /** Product name — used in email subjects and as the cookie-prefix default. */\n appName: string\n /** Absolute origin better-auth serves from (`BETTER_AUTH_URL`). */\n baseURL: string\n /** better-auth HMAC secret. Optional only because better-auth falls back to\n * the BETTER_AUTH_SECRET env var; `sso` needs it explicitly (or\n * `sso.stateSecret`). */\n secret?: string\n trustedOrigins?: string[]\n /**\n * Session-cookie prefix. Default: slugified `appName`. A per-app prefix is\n * load-bearing, not cosmetic: the platform (id.tangle.tools) mints its own\n * better-auth cookie `Domain=.tangle.tools`-wide under the DEFAULT name, and\n * the platform's (older) cookie wins the Cookie-header order — an app on the\n * default prefix reads the platform's token, fails its own signature check,\n * and every fresh login lands back on /login.\n */\n cookiePrefix?: string\n /** Drizzle database instance; wired through better-auth's drizzle adapter\n * together with `schema`. */\n db?: unknown\n /** The product's users/sessions/accounts/verifications tables (mapped to\n * better-auth's user/session/account/verification models). */\n schema?: AppAuthSchema\n /** Drizzle dialect. Default 'sqlite' (D1). */\n provider?: 'sqlite' | 'pg' | 'mysql'\n /** Escape hatch: a pre-built better-auth database adapter (e.g.\n * `memoryAdapter` in tests). Wins over `db`/`schema`. */\n database?: BetterAuthOptions['database']\n /** Email+password sign-in. Default true (all current products enable it). */\n emailAndPassword?: boolean\n /** Reset/verification mail. Omit to disable password reset entirely. */\n email?: AppAuthEmailConfig\n social?: AppAuthSocialConfig\n /** Session cookie-cache TTL in seconds; `false` disables the cache.\n * Default 300. */\n sessionCookieCacheSeconds?: number | false\n /** Tangle cross-site SSO (start/callback handlers). */\n sso?: AppAuthSsoConfig | AppAuthOidcSsoConfig | AppAuthIdentitySsoConfig\n /** Where guards redirect unauthenticated page requests. Default '/login'. */\n loginPath?: string\n /** Merged over the factory's `advanced` block (cookiePrefix stays unless\n * overridden here). */\n advanced?: BetterAuthOptions['advanced']\n}\n\n/** The configured better-auth instance, typed at better-auth's base surface\n * (`handler`, `api`, `$context`, `$Infer`). */\nexport type AppAuthInstance = Auth\n\n/** What `getSession`/guards resolve: better-auth's base session + user rows. */\nexport interface AppAuthSession {\n session: Session\n user: User\n}\n\n/** Define authentication guard with session retrieval and optional SSO handlers for app requests */\nexport interface AppAuth extends AuthGuard<AppAuthSession> {\n auth: AppAuthInstance\n /** `auth.api.getSession` over a `Request` — the seam the guards consume. */\n getSession(request: Request): Promise<AppAuthSession | null>\n /** Tangle SSO start/callback handlers; null unless `sso` was configured. */\n sso: TangleSsoHandlers | null\n}\n\n/** Lowercased, non-alphanumerics collapsed to '-': `'Legal Agent'` → `'legal-agent'`. */\nfunction slugify(name: string): string {\n return name\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, '-')\n .replace(/^-+|-+$/g, '')\n}\n\nfunction emailProduct(config: AppAuthConfig): EmailProduct {\n return { name: config.appName, url: config.baseURL }\n}\n\nfunction resolveEmailClient(email: AppAuthEmailConfig): AppAuthEmailClient | null {\n return typeof email.resend === 'function' ? email.resend() : email.resend\n}\n\ntype DrizzleAuthAdapter = ReturnType<ReturnType<typeof drizzleAdapter>>\n\n/** Better Auth reads adapter identity during startup, before Workers inject D1.\n * Build the Drizzle adapter on its first database operation. */\nfunction deferDrizzleAdapter(\n db: Record<string, unknown>,\n config: Parameters<typeof drizzleAdapter>[1],\n): ReturnType<typeof drizzleAdapter> {\n return (options) => {\n let adapter: DrizzleAuthAdapter | undefined\n const resolve = () => (adapter ??= drizzleAdapter(db, config)(options))\n\n return {\n id: 'drizzle',\n create: (data) => resolve().create(data),\n findOne: (data) => resolve().findOne(data),\n findMany: (data) => resolve().findMany(data),\n count: (data) => resolve().count(data),\n update: (data) => resolve().update(data),\n updateMany: (data) => resolve().updateMany(data),\n delete: (data) => resolve().delete(data),\n deleteMany: (data) => resolve().deleteMany(data),\n consumeOne: (data) => resolve().consumeOne(data),\n incrementOne: (data) => resolve().incrementOne(data),\n transaction: (callback) => resolve().transaction(callback),\n }\n }\n}\n\n/** Resend reports failures in the resolved value, not by rejecting — surface\n * them loud so better-auth's flow (and the caller's logs) see the failure. */\nasync function sendEmail(client: AppAuthEmailClient, from: string, to: string, message: EmailMessage): Promise<void> {\n const { subject, html, text, attachments } = message\n const result = (await client.emails.send({ from, to, subject, html, text, attachments })) as\n | { error?: { message?: string } | null }\n | null\n | undefined\n if (result && typeof result === 'object' && result.error) {\n throw new Error(`[app-auth] email send failed: ${result.error.message ?? 'unknown error'}`)\n }\n}\n\nfunction resolveDatabase(config: AppAuthConfig): NonNullable<BetterAuthOptions['database']> {\n if (config.database) return config.database\n if (config.db && config.schema) {\n return deferDrizzleAdapter(config.db as Record<string, unknown>, {\n provider: config.provider ?? 'sqlite',\n schema: {\n user: config.schema.users,\n session: config.schema.sessions,\n account: config.schema.accounts,\n verification: config.schema.verifications,\n } as Record<string, unknown>,\n })\n }\n throw new Error(\n 'createAppAuth requires a database: pass `db` + `schema` (drizzle) or `database` (a better-auth adapter)',\n )\n}\n\nfunction resolveSocialProviders(social: AppAuthSocialConfig | undefined): BetterAuthOptions['socialProviders'] {\n const providers: NonNullable<BetterAuthOptions['socialProviders']> = {}\n if (social?.github?.clientId && social.github.clientSecret) {\n providers.github = { clientId: social.github.clientId, clientSecret: social.github.clientSecret }\n }\n if (social?.google?.clientId && social.google.clientSecret) {\n providers.google = { clientId: social.google.clientId, clientSecret: social.google.clientSecret }\n }\n return Object.keys(providers).length > 0 ? providers : undefined\n}\n\nfunction emailAndPasswordOptions(config: AppAuthConfig): BetterAuthOptions['emailAndPassword'] {\n const email = config.email\n if (!email) return { enabled: true }\n const warn = email.warn ?? ((message: string) => console.warn(message))\n return {\n enabled: true,\n sendResetPassword: async ({ user, url }) => {\n const client = resolveEmailClient(email)\n if (!client) {\n warn('[app-auth] email client unavailable — password reset email not sent')\n return\n }\n await sendEmail(client, email.from, user.email, noticeEmail(emailProduct(config), {\n subject: 'Reset your password',\n title: 'Reset your password',\n body: `Someone asked to reset the password for ${user.email}. If it was not you, ignore this email.`,\n action: { label: 'Reset password', url },\n showLink: true,\n note: 'This link expires in 1 hour.',\n footer: { reason: 'You received this because a password reset was requested for this address.' },\n }))\n },\n }\n}\n\nfunction emailVerificationOptions(config: AppAuthConfig): BetterAuthOptions['emailVerification'] {\n const email = config.email\n if (!email?.verifyOnSignUp) return undefined\n const warn = email.warn ?? ((message: string) => console.warn(message))\n return {\n sendOnSignUp: true,\n autoSignInAfterVerification: true,\n sendVerificationEmail: async ({ user, url }) => {\n const client = resolveEmailClient(email)\n if (!client) {\n warn('[app-auth] email client unavailable — verification email not sent')\n return\n }\n await sendEmail(client, email.from, user.email, noticeEmail(emailProduct(config), {\n subject: 'Verify your email',\n title: 'Verify your email',\n body: `Confirm ${user.email} to finish signing in to ${config.appName}.`,\n action: { label: 'Verify email', url },\n showLink: true,\n note: 'This link expires in 1 hour.',\n footer: { reason: `You received this because this address was used to sign in to ${config.appName}.` },\n }))\n },\n }\n}\n\n/**\n * Build the product's better-auth instance plus the request-boundary helpers:\n * `getSession` (Request → session|null), the `createAuthGuard` quartet\n * (`requireUser` 302, `requireApiUser` JSON 401, `requireSession`,\n * `getOptionalSession`), and — when `sso` is configured — the Tangle SSO\n * start/callback handlers with the session cookie minted through better-auth's\n * own name/attributes/signing (no `better-auth/crypto` in product code).\n */\nexport function createAppAuth(config: AppAuthConfig): AppAuth {\n if (!config.appName) throw new Error('createAppAuth: appName is required')\n if (!config.baseURL) throw new Error('createAppAuth: baseURL is required')\n\n const cookiePrefix = config.cookiePrefix ?? slugify(config.appName)\n if (!cookiePrefix) throw new Error('createAppAuth: cookiePrefix (or a slugifiable appName) is required')\n\n const socialProviders = resolveSocialProviders(config.social)\n const options: BetterAuthOptions = {\n appName: config.appName,\n baseURL: config.baseURL,\n ...(config.secret ? { secret: config.secret } : {}),\n ...(config.trustedOrigins ? { trustedOrigins: config.trustedOrigins } : {}),\n database: resolveDatabase(config),\n ...(config.emailAndPassword === false ? {} : { emailAndPassword: emailAndPasswordOptions(config) }),\n ...(config.email?.verifyOnSignUp ? { emailVerification: emailVerificationOptions(config) } : {}),\n ...(socialProviders ? { socialProviders } : {}),\n ...(config.sessionCookieCacheSeconds === false\n ? {}\n : {\n session: {\n cookieCache: {\n enabled: true,\n maxAge: config.sessionCookieCacheSeconds ?? DEFAULT_SESSION_COOKIE_CACHE_SECONDS,\n },\n },\n }),\n advanced: { cookiePrefix, ...config.advanced },\n }\n\n const auth: AppAuthInstance = betterAuth(options)\n\n const getSession = async (request: Request): Promise<AppAuthSession | null> => {\n const session = await auth.api.getSession({ headers: request.headers })\n return (session as AppAuthSession | null) ?? null\n }\n\n const loginPath = config.loginPath ?? '/login'\n const guard = createAuthGuard<AppAuthSession>({ getSession, loginPath })\n\n let sso: TangleSsoHandlers | null = null\n if (config.sso) {\n const stateSecret = config.sso.stateSecret ?? config.secret\n if (!stateSecret) {\n throw new Error(\n 'createAppAuth: sso requires `secret` (or sso.stateSecret) — the signed-state CSRF cookie needs an HMAC secret',\n )\n }\n const transport = config.sso.protocol === 'oidc'\n ? { protocol: 'oidc' as const, auth: config.sso.client, store: config.sso.store, createPkcePair: config.sso.createPkcePair }\n : config.sso.protocol === 'identity'\n ? { protocol: 'identity' as const, auth: config.sso.client, store: config.sso.store }\n : { protocol: 'legacy' as const, auth: config.sso.client, store: config.sso.store }\n sso = createTangleSsoHandlers({\n ...transport,\n stateSecret,\n callbackUrl: config.sso.callbackUrl,\n stateCookieName: config.sso.stateCookieName ?? DEFAULT_STATE_COOKIE,\n setSessionCookie: createBetterAuthSessionCookieMinter(auth),\n secureCookies: config.sso.secureCookies ?? config.baseURL.startsWith('https:'),\n ...(config.sso.sessionTtlSeconds !== undefined ? { sessionTtlSeconds: config.sso.sessionTtlSeconds } : {}),\n ...(config.sso.stateTtlSeconds !== undefined ? { stateTtlSeconds: config.sso.stateTtlSeconds } : {}),\n ...(config.sso.defaultRedirectPath ? { defaultRedirectPath: config.sso.defaultRedirectPath } : {}),\n loginPath: config.sso.loginPath ?? loginPath,\n ...(config.sso.log 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ourcesContent":["/**\n * better-auth config factory for agent products (#188 Phase 1). Every product\n * hand-rolls the same ~70–150 line setup — drizzle adapter over the standard\n * users/sessions/accounts/verifications tables, email+password with branded\n * reset/verification mail (`./email`), env-gated GitHub/Google social providers, session\n * cookie cache, and a per-app cookie prefix — and tax additionally\n * re-implemented better-auth's cookie signing for its Tangle SSO callback.\n * `createAppAuth` owns that mechanism once and returns the configured\n * better-auth instance plus the request guards products actually use.\n *\n * Domain stays a parameter: the drizzle db + schema, email client, provider\n * credentials, and SSO store/client all come from the product. No product\n * import, no engine re-implementation — the SSO path composes the existing\n * `platform/sso` cookie minter (`createBetterAuthSessionCookieMinter`), which\n * is byte-compatible with better-auth's own `makeSignature` contract.\n *\n * better-auth is an OPTIONAL peer: only this subpath imports it, so it is\n * deliberately NOT re-exported from the root barrel.\n */\n\nimport { betterAuth, type Auth, type BetterAuthOptions, type Session, type User } from 'better-auth'\nimport { drizzleAdapter } from 'better-auth/adapters/drizzle'\nimport { noticeEmail, type EmailAttachment, type EmailMessage, type EmailProduct } from '../email'\nimport { createAuthGuard, type AuthGuard } from '../platform/guards'\nimport {\n createBetterAuthSessionCookieMinter,\n createTangleSsoHandlers,\n type TangleSsoAccountStore,\n type TangleSsoAuthClient,\n type TangleSsoHandlers,\n type TangleIdentitySsoAccountStore,\n type TangleIdentitySsoAuthClient,\n type TangleOidcSsoAccountStore,\n type TangleOidcSsoAuthClient,\n} from '../platform/sso'\n\nconst DEFAULT_STATE_COOKIE = 'tangle_sso_state'\nconst DEFAULT_SESSION_COOKIE_CACHE_SECONDS = 5 * 60\n\n/**\n * A session read costs two serial database round trips (session, then user),\n * and a request often resolves it more than once. Resolved sessions are reused\n * within a request and, for at most SESSION_MEMO_MAX_MS, across requests in one\n * isolate, keyed by the exact credentials sent. That stays inside the staleness\n * the session cookie cache already accepts, and any non-GET auth call (sign-out,\n * revocation) clears the app's entries in this isolate.\n */\nconst SESSION_MEMO_MAX_MS = 30_000\nconst SESSION_MEMO_LIMIT = 500\nconst requestSessions = new WeakMap<Request, Promise<AppAuthSession | null>>()\nconst isolateSessions = new Map<string, { until: number; session: Promise<AppAuthSession | null> }>()\n\nfunction memoizedSession(scope: string, ttlMs: number, request: Request,\n read: (request: Request) => Promise<AppAuthSession | null>): Promise<AppAuthSession | null> {\n const known = requestSessions.get(request)\n if (known) return known\n const cookie = request.headers.get('cookie') ?? ''\n const authorization = request.headers.get('authorization') ?? ''\n if (!cookie && !authorization) return read(request)\n const key = `${scope}\\u0000${authorization}\\u0000${cookie}`\n const now = Date.now()\n const hit = isolateSessions.get(key)\n if (hit && hit.until > now) {\n requestSessions.set(request, hit.session)\n return hit.session\n }\n const session = read(request).then((value) => {\n // Only a live session is reused; a miss or an expired session is read again next time.\n const expiresAt = value ? new Date(value.session.expiresAt).getTime() : 0\n if (!value || !(expiresAt > Date.now())) isolateSessions.delete(key)\n else {\n const entry = isolateSessions.get(key)\n if (entry) entry.until = Math.min(entry.until, expiresAt)\n }\n return value\n }, (error) => { isolateSessions.delete(key); throw error })\n isolateSessions.delete(key)\n isolateSessions.set(key, { until: now + ttlMs, session })\n if (isolateSessions.size > SESSION_MEMO_LIMIT) isolateSessions.delete(isolateSessions.keys().next().value!)\n requestSessions.set(request, session)\n return session\n}\n\nfunction forgetSessions(scope: string): void {\n for (const key of isolateSessions.keys()) if (key.startsWith(`${scope}\\u0000`)) isolateSessions.delete(key)\n}\n\n/** Structural slice of a Resend-style client — no `resend` import. */\nexport interface AppAuthEmailClient {\n emails: {\n send(message: {\n from: string\n to: string\n subject: string\n html: string\n text?: string\n /** Inline images the HTML references by `cid:`, such as the Tangle mark. */\n attachments?: EmailAttachment[]\n }): Promise<unknown>\n }\n}\n\n/** Define email configuration for app authentication including client, sender, verification, and warning options */\nexport interface AppAuthEmailConfig {\n /** A Resend-style client, or a lazy getter returning null when the API key\n * is absent (the products' dev default — mail is skipped with a warning,\n * sign-up itself must not crash). */\n resend: AppAuthEmailClient | (() => AppAuthEmailClient | null)\n /** RFC 5322 From; build it with `emailSender` from `./email`, e.g. `Legal Agent · Tangle <noreply@tangle.tools>`. */\n from: string\n /** Send a verification email on sign-up and auto-sign-in after verifying\n * (the tax/gtm behavior). Default false (the legal behavior). */\n verifyOnSignUp?: boolean\n /** Receives the \"email client unavailable\" warning. Default console.warn. */\n warn?: (message: string) => void\n}\n\n/** Env-shaped: pass the env vars straight through; the provider is registered\n * only when BOTH values are non-empty, so unset env disables it. */\nexport interface AppAuthSocialProviderConfig {\n clientId?: string\n clientSecret?: string\n}\n\n/** Define social authentication configuration options for GitHub and Google providers */\nexport interface AppAuthSocialConfig {\n github?: AppAuthSocialProviderConfig\n google?: AppAuthSocialProviderConfig\n}\n\n/** Cross-site Tangle SSO wiring. The factory supplies the better-auth side —\n * `setSessionCookie` via `createBetterAuthSessionCookieMinter(auth)` (signed\n * `__Secure-`/prefixed cookie that `auth.api.getSession` accepts) — so the\n * product no longer touches `better-auth/crypto` itself. */\nexport interface AppAuthSsoConfig {\n protocol?: 'legacy'\n /** Platform wire client (authorizeUrl + exchange). */\n client: TangleSsoAuthClient\n /** Product persistence: user upsert, session row, platform link. */\n store: TangleSsoAccountStore\n /** Absolute callback URL registered with the platform. */\n callbackUrl: string\n /** Default 'tangle_sso_state'. */\n stateCookieName?: string\n /** HMAC secret for the CSRF state cookie. Default: the auth `secret`. */\n stateSecret?: string\n /** Default: `baseURL` is https. Must match better-auth's own\n * secure-cookie decision or the cookie name lookup diverges. */\n secureCookies?: boolean\n sessionTtlSeconds?: number\n stateTtlSeconds?: number\n /** Post-login redirect fallback. Default '/app'. */\n defaultRedirectPath?: string\n /** Default: the top-level `loginPath`. */\n loginPath?: string\n /** Failure log hook (e.g. console.error). Default no-op. */\n log?: (message: string, error?: unknown) => void\n}\n\n/** Registered OIDC client configuration. The caller supplies Runtime PKCE; login does not mint an API key. */\nexport interface AppAuthOidcSsoConfig extends Omit<AppAuthSsoConfig, 'protocol' | 'client' | 'store'> {\n protocol: 'oidc'\n client: TangleOidcSsoAuthClient\n store: TangleOidcSsoAccountStore\n /** Pass the Runtime's `createPkcePair` helper from the OIDC-only caller. */\n createPkcePair: () => Promise<{ verifier: string; challenge: string }>\n}\n\n/** First-party identity login; no Platform API key is issued or stored. */\nexport interface AppAuthIdentitySsoConfig extends Omit<AppAuthSsoConfig, 'protocol' | 'client' | 'store'> {\n protocol: 'identity'\n client: TangleIdentitySsoAuthClient\n store: TangleIdentitySsoAccountStore\n}\n\n/** Define the structure for application authentication data including users, sessions, accounts, and verifications */\nexport interface AppAuthSchema {\n users: unknown\n sessions: unknown\n accounts: unknown\n verifications: unknown\n}\n\n/** Define configuration settings for app authentication including app name, base URL, secrets, and trusted origins */\nexport interface AppAuthConfig {\n /** Product name — used in email subjects and as the cookie-prefix default. */\n appName: string\n /** Absolute origin better-auth serves from (`BETTER_AUTH_URL`). */\n baseURL: string\n /** better-auth HMAC secret. Optional only because better-auth falls back to\n * the BETTER_AUTH_SECRET env var; `sso` needs it explicitly (or\n * `sso.stateSecret`). */\n secret?: string\n trustedOrigins?: string[]\n /**\n * Session-cookie prefix. Default: slugified `appName`. A per-app prefix is\n * load-bearing, not cosmetic: the platform (id.tangle.tools) mints its own\n * better-auth cookie `Domain=.tangle.tools`-wide under the DEFAULT name, and\n * the platform's (older) cookie wins the Cookie-header order — an app on the\n * default prefix reads the platform's token, fails its own signature check,\n * and every fresh login lands back on /login.\n */\n cookiePrefix?: string\n /** Drizzle database instance; wired through better-auth's drizzle adapter\n * together with `schema`. */\n db?: unknown\n /** The product's users/sessions/accounts/verifications tables (mapped to\n * better-auth's user/session/account/verification models). */\n schema?: AppAuthSchema\n /** Drizzle dialect. Default 'sqlite' (D1). */\n provider?: 'sqlite' | 'pg' | 'mysql'\n /** Escape hatch: a pre-built better-auth database adapter (e.g.\n * `memoryAdapter` in tests). Wins over `db`/`schema`. */\n database?: BetterAuthOptions['database']\n /** Email+password sign-in. Default true (all current products enable it). */\n emailAndPassword?: boolean\n /** Reset/verification mail. Omit to disable password reset entirely. */\n email?: AppAuthEmailConfig\n social?: AppAuthSocialConfig\n /** Session cookie-cache TTL in seconds; `false` disables the cache.\n * Default 300. */\n sessionCookieCacheSeconds?: number | false\n /** Tangle cross-site SSO (start/callback handlers). */\n sso?: AppAuthSsoConfig | AppAuthOidcSsoConfig | AppAuthIdentitySsoConfig\n /** Where guards redirect unauthenticated page requests. Default '/login'. */\n loginPath?: string\n /** Merged over the factory's `advanced` block (cookiePrefix stays unless\n * overridden here). */\n advanced?: BetterAuthOptions['advanced']\n}\n\n/** The configured better-auth instance, typed at better-auth's base surface\n * (`handler`, `api`, `$context`, `$Infer`). */\nexport type AppAuthInstance = Auth\n\n/** What `getSession`/guards resolve: better-auth's base session + user rows. */\nexport interface AppAuthSession {\n session: Session\n user: User\n}\n\n/** Define authentication guard with session retrieval and optional SSO handlers for app requests */\nexport interface AppAuth extends AuthGuard<AppAuthSession> {\n auth: AppAuthInstance\n /** `auth.api.getSession` over a `Request` — the seam the guards consume. */\n getSession(request: Request): Promise<AppAuthSession | null>\n /** Tangle SSO start/callback handlers; null unless `sso` was configured. */\n sso: TangleSsoHandlers | null\n}\n\n/** Lowercased, non-alphanumerics collapsed to '-': `'Legal Agent'` → `'legal-agent'`. */\nfunction slugify(name: string): string {\n return name\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, '-')\n .replace(/^-+|-+$/g, '')\n}\n\nfunction emailProduct(config: AppAuthConfig): EmailProduct {\n return { name: config.appName, url: config.baseURL }\n}\n\nfunction resolveEmailClient(email: AppAuthEmailConfig): AppAuthEmailClient | null {\n return typeof email.resend === 'function' ? email.resend() : email.resend\n}\n\ntype DrizzleAuthAdapter = ReturnType<ReturnType<typeof drizzleAdapter>>\n\n/** Better Auth reads adapter identity during startup, before Workers inject D1.\n * Build the Drizzle adapter on its first database operation. */\nfunction deferDrizzleAdapter(\n db: Record<string, unknown>,\n config: Parameters<typeof drizzleAdapter>[1],\n): ReturnType<typeof drizzleAdapter> {\n return (options) => {\n let adapter: DrizzleAuthAdapter | undefined\n const resolve = () => (adapter ??= drizzleAdapter(db, config)(options))\n\n return {\n id: 'drizzle',\n create: (data) => resolve().create(data),\n findOne: (data) => resolve().findOne(data),\n findMany: (data) => resolve().findMany(data),\n count: (data) => resolve().count(data),\n update: (data) => resolve().update(data),\n updateMany: (data) => resolve().updateMany(data),\n delete: (data) => resolve().delete(data),\n deleteMany: (data) => resolve().deleteMany(data),\n consumeOne: (data) => resolve().consumeOne(data),\n incrementOne: (data) => resolve().incrementOne(data),\n transaction: (callback) => resolve().transaction(callback),\n }\n }\n}\n\n/** Resend reports failures in the resolved value, not by rejecting — surface\n * them loud so better-auth's flow (and the caller's logs) see the failure. */\nasync function sendEmail(client: AppAuthEmailClient, from: string, to: string, message: EmailMessage): Promise<void> {\n const { subject, html, text, attachments } = message\n const result = (await client.emails.send({ from, to, subject, html, text, attachments })) as\n | { error?: { message?: string } | null }\n | null\n | undefined\n if (result && typeof result === 'object' && result.error) {\n throw new Error(`[app-auth] email send failed: ${result.error.message ?? 'unknown error'}`)\n }\n}\n\nfunction resolveDatabase(config: AppAuthConfig): NonNullable<BetterAuthOptions['database']> {\n if (config.database) return config.database\n if (config.db && config.schema) {\n return deferDrizzleAdapter(config.db as Record<string, unknown>, {\n provider: config.provider ?? 'sqlite',\n schema: {\n user: config.schema.users,\n session: config.schema.sessions,\n account: config.schema.accounts,\n verification: config.schema.verifications,\n } as Record<string, unknown>,\n })\n }\n throw new Error(\n 'createAppAuth requires a database: pass `db` + `schema` (drizzle) or `database` (a better-auth adapter)',\n )\n}\n\nfunction resolveSocialProviders(social: AppAuthSocialConfig | undefined): BetterAuthOptions['socialProviders'] {\n const providers: NonNullable<BetterAuthOptions['socialProviders']> = {}\n if (social?.github?.clientId && social.github.clientSecret) {\n providers.github = { clientId: social.github.clientId, clientSecret: social.github.clientSecret }\n }\n if (social?.google?.clientId && social.google.clientSecret) {\n providers.google = { clientId: social.google.clientId, clientSecret: social.google.clientSecret }\n }\n return Object.keys(providers).length > 0 ? providers : undefined\n}\n\nfunction emailAndPasswordOptions(config: AppAuthConfig): BetterAuthOptions['emailAndPassword'] {\n const email = config.email\n if (!email) return { enabled: true }\n const warn = email.warn ?? ((message: string) => console.warn(message))\n return {\n enabled: true,\n sendResetPassword: async ({ user, url }) => {\n const client = resolveEmailClient(email)\n if (!client) {\n warn('[app-auth] email client unavailable — password reset email not sent')\n return\n }\n await sendEmail(client, email.from, user.email, noticeEmail(emailProduct(config), {\n subject: 'Reset your password',\n title: 'Reset your password',\n body: `Someone asked to reset the password for ${user.email}. If it was not you, ignore this email.`,\n action: { label: 'Reset password', url },\n showLink: true,\n note: 'This link expires in 1 hour.',\n footer: { reason: 'You received this because a password reset was requested for this address.' },\n }))\n },\n }\n}\n\nfunction emailVerificationOptions(config: AppAuthConfig): BetterAuthOptions['emailVerification'] {\n const email = config.email\n if (!email?.verifyOnSignUp) return undefined\n const warn = email.warn ?? ((message: string) => console.warn(message))\n return {\n sendOnSignUp: true,\n autoSignInAfterVerification: true,\n sendVerificationEmail: async ({ user, url }) => {\n const client = resolveEmailClient(email)\n if (!client) {\n warn('[app-auth] email client unavailable — verification email not sent')\n return\n }\n await sendEmail(client, email.from, user.email, noticeEmail(emailProduct(config), {\n subject: 'Verify your email',\n title: 'Verify your email',\n body: `Confirm ${user.email} to finish signing in to ${config.appName}.`,\n action: { label: 'Verify email', url },\n showLink: true,\n note: 'This link expires in 1 hour.',\n footer: { reason: `You received this because this address was used to sign in to ${config.appName}.` },\n }))\n },\n }\n}\n\n/**\n * Build the product's better-auth instance plus the request-boundary helpers:\n * `getSession` (Request → session|null), the `createAuthGuard` quartet\n * (`requireUser` 302, `requireApiUser` JSON 401, `requireSession`,\n * `getOptionalSession`), and — when `sso` is configured — the Tangle SSO\n * start/callback handlers with the session cookie minted through better-auth's\n * own name/attributes/signing (no `better-auth/crypto` in product code).\n */\nexport function createAppAuth(config: AppAuthConfig): AppAuth {\n if (!config.appName) throw new Error('createAppAuth: appName is required')\n if (!config.baseURL) throw new Error('createAppAuth: baseURL is required')\n\n const cookiePrefix = config.cookiePrefix ?? slugify(config.appName)\n if (!cookiePrefix) throw new Error('createAppAuth: cookiePrefix (or a slugifiable appName) is required')\n\n const socialProviders = resolveSocialProviders(config.social)\n const options: BetterAuthOptions = {\n appName: config.appName,\n baseURL: config.baseURL,\n ...(config.secret ? { secret: config.secret } : {}),\n ...(config.trustedOrigins ? { trustedOrigins: config.trustedOrigins } : {}),\n database: resolveDatabase(config),\n ...(config.emailAndPassword === false ? {} : { emailAndPassword: emailAndPasswordOptions(config) }),\n ...(config.email?.verifyOnSignUp ? { emailVerification: emailVerificationOptions(config) } : {}),\n ...(socialProviders ? { socialProviders } : {}),\n ...(config.sessionCookieCacheSeconds === false\n ? {}\n : {\n session: {\n cookieCache: {\n enabled: true,\n maxAge: config.sessionCookieCacheSeconds ?? DEFAULT_SESSION_COOKIE_CACHE_SECONDS,\n },\n },\n }),\n advanced: { cookiePrefix, ...config.advanced },\n }\n\n const auth: AppAuthInstance = betterAuth(options)\n\n const readSession = async (request: Request): Promise<AppAuthSession | null> => {\n const session = await auth.api.getSession({ headers: request.headers })\n return (session as AppAuthSession | null) ?? null\n }\n const memoMs = config.sessionCookieCacheSeconds === false ? 0\n : Math.min(SESSION_MEMO_MAX_MS, (config.sessionCookieCacheSeconds ?? DEFAULT_SESSION_COOKIE_CACHE_SECONDS) * 1000)\n const memoScope = `${config.baseURL}\\u0000${cookiePrefix}`\n const getSession = (request: Request): Promise<AppAuthSession | null> =>\n memoMs > 0 ? memoizedSession(memoScope, memoMs, request, readSession) : readSession(request)\n // Sign-out and session revocation drop this isolate's remembered sessions for the app.\n const handler = auth.handler\n auth.handler = async (request: Request) => {\n // In finally: a sign-out that fails after deleting the session must not leave it remembered.\n try { return await handler(request) }\n finally { if (request.method !== 'GET') forgetSessions(memoScope) }\n }\n\n const loginPath = config.loginPath ?? '/login'\n const guard = createAuthGuard<AppAuthSession>({ getSession, loginPath })\n\n let sso: TangleSsoHandlers | null = null\n if (config.sso) {\n const stateSecret = config.sso.stateSecret ?? config.secret\n if (!stateSecret) {\n throw new Error(\n 'createAppAuth: sso requires `secret` (or sso.stateSecret) — the signed-state CSRF cookie needs an HMAC secret',\n )\n }\n const transport = config.sso.protocol === 'oidc'\n ? { protocol: 'oidc' as const, auth: config.sso.client, store: config.sso.store, createPkcePair: config.sso.createPkcePair }\n : config.sso.protocol === 'identity'\n ? { protocol: 'identity' as const, auth: config.sso.client, store: config.sso.store }\n : { protocol: 'legacy' as const, auth: config.sso.client, store: config.sso.store }\n sso = createTangleSsoHandlers({\n ...transport,\n stateSecret,\n callbackUrl: config.sso.callbackUrl,\n stateCookieName: config.sso.stateCookieName ?? DEFAULT_STATE_COOKIE,\n setSessionCookie: createBetterAuthSessionCookieMinter(auth),\n secureCookies: config.sso.secureCookies ?? config.baseURL.startsWith('https:'),\n ...(config.sso.sessionTtlSeconds !== undefined ? { sessionTtlSeconds: config.sso.sessionTtlSeconds } : {}),\n ...(config.sso.stateTtlSeconds !== undefined ? { stateTtlSeconds: config.sso.stateTtlSeconds } : {}),\n ...(config.sso.defaultRedirectPath ? { defaultRedirectPath: config.sso.defaultRedirectPath } : {}),\n loginPath: config.sso.loginPath ?? loginPath,\n ...(config.sso.log ? { log: config.sso.log } : {}),\n })\n }\n\n return { auth, getSession, ...guard, sso }\n}\n"],"mappings":";;;;;;;;;;;;;;;AAoBA,SAAS,kBAA8E;AACvF,SAAS,sBAAsB;AAe/B,IAAM,uBAAuB;AAC7B,IAAM,uCAAuC,IAAI;AAUjD,IAAM,sBAAsB;AAC5B,IAAM,qBAAqB;AAC3B,IAAM,kBAAkB,oBAAI,QAAiD;AAC7E,IAAM,kBAAkB,oBAAI,IAAwE;AAEpG,SAAS,gBAAgB,OAAe,OAAe,SACrD,MAA4F;AAC5F,QAAM,QAAQ,gBAAgB,IAAI,OAAO;AACzC,MAAI,MAAO,QAAO;AAClB,QAAM,SAAS,QAAQ,QAAQ,IAAI,QAAQ,KA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,IAAI,IAAI,CAAC;AAAA,IAClD,CAAC;AAAA,EACH;AAEA,SAAO,EAAE,MAAM,YAAY,GAAG,OAAO,IAAI;AAC3C;","names":[]}
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  chatToolCallPart
3
- } from "../chunk-6LPQRKH7.js";
3
+ } from "../chunk-4WJREKXX.js";
4
4
  import "../chunk-FAU5FIFD.js";
5
5
  import "../chunk-3HUFJ5LO.js";
6
6
  import "../chunk-FBVLEGEG.js";
@@ -8,7 +8,7 @@ import "../chunk-Y6PRDUFJ.js";
8
8
  import "../chunk-GEYACSFW.js";
9
9
  import {
10
10
  ChatComposer
11
- } from "../chunk-EQ6CGOZK.js";
11
+ } from "../chunk-GNA5I5NM.js";
12
12
  import "../chunk-L7MB2LLM.js";
13
13
  import "../chunk-KHCJKVQN.js";
14
14
  import "../chunk-XEURJVS5.js";
@@ -82,6 +82,88 @@ function parseSizes(sizes) {
82
82
  if (!m) return {};
83
83
  return { width: Number(m[1]), height: Number(m[2]) };
84
84
  }
85
+ function siteNames(html, base) {
86
+ const squash = (value) => value.toLowerCase().replace(/[^a-z0-9]/g, "");
87
+ const names = [];
88
+ try {
89
+ const labels = new URL(base).hostname.replace(/^www\./, "").split(".");
90
+ const label = labels.length > 1 ? labels[labels.length - 2] : labels[0];
91
+ if (label) names.push(squash(label));
92
+ } catch {
93
+ }
94
+ const site = extractName(html);
95
+ if (site) names.push(squash(site.split(/\s+[|–—\-:·]\s+/)[0] ?? site));
96
+ return names.filter((name) => name.length >= 3);
97
+ }
98
+ var LOGO_FORM_WORDS = /* @__PURE__ */ new Set([
99
+ "logo",
100
+ "logos",
101
+ "default",
102
+ "white",
103
+ "black",
104
+ "dark",
105
+ "light",
106
+ "color",
107
+ "colour",
108
+ "main",
109
+ "primary",
110
+ "header",
111
+ "footer",
112
+ "nav",
113
+ "site",
114
+ "brand",
115
+ "mark",
116
+ "wordmark",
117
+ "full",
118
+ "small",
119
+ "large",
120
+ "mobile",
121
+ "desktop",
122
+ "svg",
123
+ "png",
124
+ "icon",
125
+ "the",
126
+ "and",
127
+ "for",
128
+ "of",
129
+ "company",
130
+ "our",
131
+ "new",
132
+ "retina",
133
+ "horizontal",
134
+ "vertical",
135
+ "stacked",
136
+ "inverse",
137
+ "inverted",
138
+ "transparent",
139
+ "image",
140
+ "img"
141
+ ]);
142
+ function otherBrandNamed(text, own) {
143
+ const squash = (value) => value.toLowerCase().replace(/[^a-z0-9]/g, "");
144
+ const named = [
145
+ ...text.matchAll(/\blogo(?:s)?(?:[\s_-]+(?:for|of))?[\s_-]+([A-Za-z][A-Za-z0-9&]+)/gi),
146
+ ...text.matchAll(/([A-Za-z][A-Za-z0-9&]+)[\s_-]+logo\b/gi)
147
+ ].map((match) => squash(match[1] ?? "")).filter((name) => name.length >= 3 && !LOGO_FORM_WORDS.has(name));
148
+ if (named.length === 0) return null;
149
+ const ours = (name) => own.some((site) => site.includes(name) || name.includes(site));
150
+ return named.some(ours) ? null : named[0];
151
+ }
152
+ function inHeaderOrHomeLink(html, index, base) {
153
+ const before = html.slice(0, index);
154
+ const openHeader = before.lastIndexOf("<header");
155
+ if (openHeader >= 0 && before.indexOf("</header>", openHeader) < 0) return true;
156
+ const openLink = Math.max(before.lastIndexOf("<a "), before.lastIndexOf("<a\n"), before.lastIndexOf("<a>"));
157
+ if (openLink < 0 || before.indexOf("</a>", openLink) >= 0) return false;
158
+ const href = attr(/<a\b[^>]*>/i.exec(before.slice(openLink))?.[0] ?? "", "href");
159
+ if (!href) return false;
160
+ try {
161
+ const target = new URL(href, base);
162
+ return target.origin === new URL(base).origin && (target.pathname === "/" || target.pathname === "");
163
+ } catch {
164
+ return false;
165
+ }
166
+ }
85
167
  function extractLogos(html, base) {
86
168
  const out = [];
87
169
  const seen = /* @__PURE__ */ new Set();
@@ -111,7 +193,9 @@ function extractLogos(html, base) {
111
193
  if (url) push({ url, source: "og:image", confidence: 0.55, mimeType: mimeFromUrl(url) });
112
194
  }
113
195
  }
114
- for (const tag of matchTags(html, "img")) {
196
+ const own = siteNames(html, base);
197
+ for (const found of html.matchAll(/<img\b[^>]*>/gi)) {
198
+ const tag = found[0];
115
199
  const src = attr(tag, "src") ?? attr(tag, "data-src");
116
200
  if (!src) continue;
117
201
  const alt = attr(tag, "alt");
@@ -123,10 +207,13 @@ function extractLogos(html, base) {
123
207
  if (!url) continue;
124
208
  const w = attr(tag, "width");
125
209
  const h = attr(tag, "height");
210
+ const filename = decodeURIComponent(new URL(url).pathname.split("/").pop() ?? "");
211
+ const partner = otherBrandNamed(`${alt ?? ""} ${filename}`, own);
212
+ const placed = inHeaderOrHomeLink(html, found.index ?? 0, base);
126
213
  push({
127
214
  url,
128
215
  source: "img-logo",
129
- confidence: 0.85,
216
+ confidence: partner && !placed ? 0.4 : placed ? 0.95 : 0.85,
130
217
  alt,
131
218
  width: w ? Number(w) || void 0 : void 0,
132
219
  height: h ? Number(h) || void 0 : void 0,
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/brand-extraction/extract.ts","../../src/brand-extraction/map.ts"],"sourcesContent":["/**\n * Brand-kit extraction engine.\n *\n * Given a website URL (or raw HTML), parse the page and pull a typed BrandKit:\n * logo candidates, color palette, fonts, and prominent images. Parsing is\n * regex-based on purpose — this runs on Cloudflare Workers and other edge\n * runtimes where DOM libraries (jsdom/cheerio) are unavailable, and the page\n * structures we read (link tags, meta tags, CSS custom properties, font-family\n * declarations) are flat enough that a DOM buys nothing.\n *\n * Degrades gracefully: a missing favicon, no CSS tokens, or an image-only page\n * each narrow the kit rather than failing it. The ONLY hard failures are a bad\n * input (no html and no fetch) and a fetch error — both returned as a typed\n * `{ succeeded: false }` outcome so callers never mistake an empty kit for a\n * real one.\n */\n\nimport type {\n BrandColor,\n BrandExtractionResult,\n BrandFont,\n BrandImage,\n BrandKit,\n BrandLogoCandidate,\n ExtractBrandKitOptions,\n FetchLike,\n} from './types'\n\nconst DEFAULT_TIMEOUT_MS = 15000\nconst DEFAULT_MAX_PER_LIST = 12\n\n// ── URL helpers ──────────────────────────────────────────────────────────────\n\n/** Normalize a user-supplied site URL: add https:// when scheme-less, validate. */\nexport function normalizeSiteUrl(raw: string): string | null {\n const trimmed = raw.trim()\n if (!trimmed) return null\n // A non-http(s) scheme is an explicit reject — don't paper over it by\n // prepending https:// (that would turn \"ftp://x\" into host \"ftp\").\n if (/^[a-z][a-z0-9+.-]*:/i.test(trimmed) && !/^https?:\\/\\//i.test(trimmed)) return null\n const withScheme = /^https?:\\/\\//i.test(trimmed) ? trimmed : `https://${trimmed}`\n try {\n const u = new URL(withScheme)\n if (u.protocol !== 'http:' && u.protocol !== 'https:') return null\n return u.toString()\n } catch {\n return null\n }\n}\n\n/** Resolve a possibly-relative href against the page URL. Returns null for\n * data: URIs and unresolvable values — we want servable http(s) URLs only. */\nfunction absolutize(href: string, base: string): string | null {\n const v = href.trim()\n if (!v || v.startsWith('data:') || v.startsWith('javascript:')) return null\n try {\n const u = new URL(v, base)\n if (u.protocol !== 'http:' && u.protocol !== 'https:') return null\n return u.toString()\n } catch {\n return null\n }\n}\n\n// ── Attribute parsing ────────────────────────────────────────────────────────\n\n/** Pull all `<tag ...>` open-tags from html (case-insensitive). */\nfunction matchTags(html: string, tag: string): string[] {\n const re = new RegExp(`<${tag}\\\\b[^>]*>`, 'gi')\n return html.match(re) ?? []\n}\n\n/** Read an attribute value from a single tag string. Handles quoted and\n * unquoted values. Returns undefined when absent. */\nfunction attr(tag: string, name: string): string | undefined {\n const quoted = new RegExp(`\\\\b${name}\\\\s*=\\\\s*[\"']([^\"']*)[\"']`, 'i').exec(tag)\n if (quoted) return decodeEntities(quoted[1] ?? '')\n const bare = new RegExp(`\\\\b${name}\\\\s*=\\\\s*([^\\\\s\"'>]+)`, 'i').exec(tag)\n return bare ? decodeEntities(bare[1] ?? '') : undefined\n}\n\nfunction decodeEntities(s: string): string {\n return s\n .replace(/&amp;/g, '&')\n .replace(/&lt;/g, '<')\n .replace(/&gt;/g, '>')\n .replace(/&quot;/g, '\"')\n .replace(/&#39;/g, \"'\")\n .replace(/&#x2F;/gi, '/')\n}\n\n// ── Name / description ───────────────────────────────────────────────────────\n\nfunction extractName(html: string): string | undefined {\n for (const tag of matchTags(html, 'meta')) {\n const prop = (attr(tag, 'property') ?? attr(tag, 'name'))?.toLowerCase()\n if (prop === 'og:site_name') {\n const c = attr(tag, 'content')?.trim()\n if (c) return c\n }\n }\n const title = /<title[^>]*>([\\s\\S]*?)<\\/title>/i.exec(html)?.[1]\n if (title) {\n // \"Acme — the best widget\" → \"Acme\". Split on common separators, take head.\n const head = (decodeEntities(title).split(/\\s+[|–—\\-:·]\\s+/)[0] ?? '').trim()\n if (head) return head\n }\n return undefined\n}\n\nfunction extractDescription(html: string): string | undefined {\n for (const tag of matchTags(html, 'meta')) {\n const prop = (attr(tag, 'property') ?? attr(tag, 'name'))?.toLowerCase()\n if (prop === 'description' || prop === 'og:description') {\n const c = attr(tag, 'content')?.trim()\n if (c) return c\n }\n }\n return undefined\n}\n\n// ── Logos ────────────────────────────────────────────────────────────────────\n\nconst MIME_BY_EXT: Record<string, string> = {\n png: 'image/png',\n jpg: 'image/jpeg',\n jpeg: 'image/jpeg',\n gif: 'image/gif',\n webp: 'image/webp',\n svg: 'image/svg+xml',\n ico: 'image/x-icon',\n}\n\nfunction mimeFromUrl(url: string): string | undefined {\n const ext = new URL(url).pathname.split('.').pop()?.toLowerCase()\n return ext ? MIME_BY_EXT[ext] : undefined\n}\n\nfunction parseSizes(sizes: string | undefined): { width?: number; height?: number } {\n if (!sizes) return {}\n const m = /(\\d+)\\s*[x×]\\s*(\\d+)/i.exec(sizes)\n if (!m) return {}\n return { width: Number(m[1]), height: Number(m[2]) }\n}\n\nfunction extractLogos(html: string, base: string): BrandLogoCandidate[] {\n const out: BrandLogoCandidate[] = []\n const seen = new Set<string>()\n const push = (c: BrandLogoCandidate) => {\n if (seen.has(c.url)) return\n seen.add(c.url)\n out.push(c)\n }\n\n // link rel icons / apple-touch-icon\n for (const tag of matchTags(html, 'link')) {\n const rel = attr(tag, 'rel')?.toLowerCase() ?? ''\n const href = attr(tag, 'href')\n if (!href) continue\n const url = absolutize(href, base)\n if (!url) continue\n const { width, height } = parseSizes(attr(tag, 'sizes'))\n if (rel.includes('apple-touch-icon')) {\n push({ url, source: 'apple-touch-icon', confidence: 0.7, width, height, mimeType: mimeFromUrl(url) })\n } else if (rel.split(/\\s+/).includes('icon') || rel.includes('shortcut icon')) {\n push({ url, source: 'favicon', confidence: 0.5, width, height, mimeType: mimeFromUrl(url) })\n }\n }\n\n // og:image (often shows the logo in context — moderate confidence)\n for (const tag of matchTags(html, 'meta')) {\n const prop = (attr(tag, 'property') ?? attr(tag, 'name'))?.toLowerCase()\n if (prop === 'og:image' || prop === 'og:image:url') {\n const href = attr(tag, 'content')\n const url = href ? absolutize(href, base) : null\n if (url) push({ url, source: 'og:image', confidence: 0.55, mimeType: mimeFromUrl(url) })\n }\n }\n\n // <img> whose src/class/alt/id mentions \"logo\" — the strongest in-page signal\n for (const tag of matchTags(html, 'img')) {\n const src = attr(tag, 'src') ?? attr(tag, 'data-src')\n if (!src) continue\n const alt = attr(tag, 'alt')\n const cls = attr(tag, 'class') ?? ''\n const id = attr(tag, 'id') ?? ''\n const looksLikeLogo = /logo|brand|wordmark/i.test(`${src} ${alt ?? ''} ${cls} ${id}`)\n if (!looksLikeLogo) continue\n const url = absolutize(src, base)\n if (!url) continue\n const w = attr(tag, 'width')\n const h = attr(tag, 'height')\n push({\n url,\n source: 'img-logo',\n confidence: 0.85,\n alt,\n width: w ? Number(w) || undefined : undefined,\n height: h ? Number(h) || undefined : undefined,\n mimeType: mimeFromUrl(url),\n })\n }\n\n // No favicon link tag at all? Fall back to the conventional /favicon.ico —\n // it almost always exists. Lowest confidence.\n if (!out.some((l) => l.source === 'favicon' || l.source === 'apple-touch-icon')) {\n const fav = absolutize('/favicon.ico', base)\n if (fav) push({ url: fav, source: 'favicon', confidence: 0.3, mimeType: 'image/x-icon' })\n }\n\n return out.sort((a, b) => b.confidence - a.confidence)\n}\n\n// ── Colors ───────────────────────────────────────────────────────────────────\n\n/** Normalize any CSS color literal to #rrggbb / #rrggbbaa hex, or null. */\nexport function normalizeColor(raw: string): string | null {\n const v = raw.trim().toLowerCase()\n // #rgb / #rgba / #rrggbb / #rrggbbaa\n const hex = /^#([0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/i.exec(v)\n if (hex) {\n const h = hex[1] ?? ''\n // Expand 3/4-digit shorthand by doubling each nibble.\n if (h.length === 3 || h.length === 4) {\n return `#${h.split('').map((c) => c + c).join('')}`\n }\n return `#${h}`\n }\n // rgb()/rgba()\n const rgb = /^rgba?\\(\\s*([\\d.]+)[\\s,]+([\\d.]+)[\\s,]+([\\d.]+)(?:[\\s,/]+([\\d.%]+))?\\s*\\)$/.exec(v)\n if (rgb) {\n const to255 = (n: string | undefined) => Math.max(0, Math.min(255, Math.round(Number(n))))\n const r = to255(rgb[1]).toString(16).padStart(2, '0')\n const g = to255(rgb[2]).toString(16).padStart(2, '0')\n const b = to255(rgb[3]).toString(16).padStart(2, '0')\n let a = ''\n if (rgb[4] !== undefined) {\n const av = rgb[4].endsWith('%') ? Number(rgb[4].slice(0, -1)) / 100 : Number(rgb[4])\n const ai = Math.max(0, Math.min(255, Math.round(av * 255)))\n if (ai < 255) a = ai.toString(16).padStart(2, '0')\n }\n return `#${r}${g}${b}${a}`\n }\n return null\n}\n\nconst COLOR_LITERAL_RE = /#[0-9a-fA-F]{3,8}\\b|rgba?\\([^)]*\\)/g\nconst ROOT_VAR_RE = /(--[a-z0-9-]*(?:color|colour|bg|background|accent|brand|primary|secondary|surface|text|fg|ink)[a-z0-9-]*)\\s*:\\s*([^;}{]+)/gi\n\nfunction extractPalette(html: string): BrandColor[] {\n const byHex = new Map<string, BrandColor>()\n const bump = (hex: string, fromToken: boolean, tokenName?: string) => {\n const existing = byHex.get(hex)\n if (existing) {\n existing.occurrences += 1\n if (fromToken && !existing.fromToken) {\n existing.fromToken = true\n existing.tokenName = tokenName\n }\n } else {\n byHex.set(hex, { hex, occurrences: 1, fromToken, ...(tokenName ? { tokenName } : {}) })\n }\n }\n\n // CSS custom properties — highest-fidelity design tokens.\n for (const m of html.matchAll(ROOT_VAR_RE)) {\n const tokenName = m[1]\n const value = m[2]\n if (!value) continue\n const lit = value.match(COLOR_LITERAL_RE)?.[0]\n if (!lit) continue\n const hex = normalizeColor(lit)\n if (hex) bump(hex, true, tokenName)\n }\n\n // All other color literals across the document (inline styles, <style>).\n for (const m of html.matchAll(COLOR_LITERAL_RE)) {\n const hex = normalizeColor(m[0])\n if (hex) bump(hex, false)\n }\n\n // Rank: token-sourced first, then by popularity. Drop pure white/black noise\n // to the back so a real brand color leads.\n const isNeutral = (h: string) => /^#(0{6}|f{6})(ff)?$/i.test(h)\n return [...byHex.values()].sort((a, b) => {\n if (a.fromToken !== b.fromToken) return a.fromToken ? -1 : 1\n const an = isNeutral(a.hex) ? 1 : 0\n const bn = isNeutral(b.hex) ? 1 : 0\n if (an !== bn) return an - bn\n return b.occurrences - a.occurrences\n })\n}\n\n// ── Fonts ────────────────────────────────────────────────────────────────────\n\nconst GENERIC_FAMILIES = new Set([\n 'serif', 'sans-serif', 'monospace', 'cursive', 'fantasy', 'system-ui',\n 'ui-sans-serif', 'ui-serif', 'ui-monospace', 'ui-rounded', 'inherit', 'initial', 'unset',\n])\n\n/** The last terminated font-family declaration in one rule body. Applied to a\n * body that holds no brace except an optional closing one, so its\n * backtracking stays inside that body. */\nconst BLOCK_FONT_DECL_RE = /^[^{}]*font-family\\s*:\\s*([^;}{]+)[;}]/i\n\n/**\n * Each rule body's font-family stack, with the selector text before the body\n * for role inference.\n *\n * One pass over the braces. A single unanchored `([^{}]*)\\{[^{}]*font-family`\n * pattern restarted its selector scan at every character of a brace-free run,\n * so a long run of page markup before a rule without a font-family made it\n * quadratic: a 366 KB page took 74 s and the brand intake request exceeded its\n * CPU limit. This walk gives the same selectors and stacks: the selector is\n * the text since the previous brace or the end of the previous declaration it\n * found, whichever is later.\n */\nfunction fontDeclarations(html: string): Array<{ selector: string; stack: string }> {\n const declarations: Array<{ selector: string; stack: string }> = []\n const braces = /[{}]/g\n const nextBrace = /[{}]/g\n let previousBrace = -1\n let resumeAt = 0\n for (let brace = braces.exec(html); brace; brace = braces.exec(html)) {\n const at = brace.index\n if (html[at] === '{') {\n nextBrace.lastIndex = at + 1\n const next = nextBrace.exec(html)\n // The body runs to the next brace and keeps a closing one, which can end the declaration.\n const end = next ? next.index + 1 : html.length\n const match = BLOCK_FONT_DECL_RE.exec(html.slice(at + 1, end))\n if (match) {\n declarations.push({ selector: html.slice(Math.max(previousBrace + 1, resumeAt), at), stack: match[1]! })\n resumeAt = at + 1 + match[0].length\n }\n }\n previousBrace = at\n }\n return declarations\n}\n\nfunction parseFontStack(raw: string | undefined): string[] {\n if (!raw) return []\n return raw\n .split(',')\n .map((s) => s.trim().replace(/^[\"']|[\"']$/g, ''))\n .filter(Boolean)\n}\n\nfunction roleFromSelector(selector: string): 'display' | 'body' | 'unknown' {\n const s = selector.toLowerCase()\n if (/\\b(h[1-3]|\\.h[1-3]|heading|title|display|hero)\\b/.test(s)) return 'display'\n if (/\\b(body|p|html|\\.text|\\.content|root|:root|\\*)\\b/.test(s)) return 'body'\n return 'unknown'\n}\n\nfunction extractFonts(html: string): BrandFont[] {\n // Restrict to <style> blocks + the whole doc; inline style=\"\" attributes are\n // included because the regex matches any `{...font-family...}` chunk, but we\n // also scan style attributes explicitly below.\n const byFamily = new Map<string, BrandFont>()\n const consider = (family: string, stack: string[], role: BrandFont['role']) => {\n const key = family.toLowerCase()\n if (!family || GENERIC_FAMILIES.has(key)) return\n const existing = byFamily.get(key)\n if (existing) {\n existing.occurrences += 1\n if (existing.role === 'unknown' && role !== 'unknown') existing.role = role\n } else {\n byFamily.set(key, { family, stack, role, occurrences: 1 })\n }\n }\n\n for (const declaration of fontDeclarations(html)) {\n const stack = parseFontStack(declaration.stack)\n const primary = stack[0]\n if (!primary) continue\n consider(primary, stack, roleFromSelector(declaration.selector))\n }\n\n // Bare `font-family:` declarations inside inline style attributes and tokens.\n const BARE_RE = /font-family\\s*:\\s*([^;\"'}{]+)/gi\n for (const m of html.matchAll(BARE_RE)) {\n const stack = parseFontStack(m[1])\n const primary = stack[0]\n if (!primary) continue\n consider(primary, stack, 'unknown')\n }\n\n // Google Fonts <link href=\"...family=Inter:wght@400...\"> — strong signal.\n for (const tag of matchTags(html, 'link')) {\n const href = attr(tag, 'href') ?? ''\n if (!/fonts\\.googleapis\\.com/i.test(href)) continue\n for (const fam of href.matchAll(/family=([^:&]+)/gi)) {\n const captured = fam[1]\n if (!captured) continue\n const family = decodeURIComponent(captured.replace(/\\+/g, ' ')).trim()\n consider(family, [family], 'display')\n }\n }\n\n return [...byFamily.values()].sort((a, b) => {\n const rank = (r: BrandFont['role']) => (r === 'display' ? 0 : r === 'body' ? 1 : 2)\n const rr = rank(a.role) - rank(b.role)\n if (rr !== 0) return rr\n return b.occurrences - a.occurrences\n })\n}\n\n// ── Images ───────────────────────────────────────────────────────────────────\n\nfunction extractImages(html: string, base: string): BrandImage[] {\n const out: BrandImage[] = []\n const seen = new Set<string>()\n const push = (img: BrandImage) => {\n if (seen.has(img.url)) return\n seen.add(img.url)\n out.push(img)\n }\n\n for (const tag of matchTags(html, 'meta')) {\n const prop = (attr(tag, 'property') ?? attr(tag, 'name'))?.toLowerCase()\n const href = attr(tag, 'content')\n const url = href ? absolutize(href, base) : null\n if (!url) continue\n if (prop === 'og:image' || prop === 'og:image:url') push({ url, source: 'og:image' })\n else if (prop === 'twitter:image' || prop === 'twitter:image:src') push({ url, source: 'twitter:image' })\n }\n\n for (const tag of matchTags(html, 'img')) {\n const src = attr(tag, 'src') ?? attr(tag, 'data-src')\n if (!src) continue\n const url = absolutize(src, base)\n if (!url) continue\n const cls = `${attr(tag, 'class') ?? ''} ${attr(tag, 'id') ?? ''}`\n // Skip obvious logos/icons — those go in the logos list, not images.\n if (/logo|icon|favicon|wordmark/i.test(`${url} ${cls}`)) continue\n const isHero = /hero|banner|cover|feature|splash/i.test(cls)\n const w = attr(tag, 'width')\n const h = attr(tag, 'height')\n push({\n url,\n source: isHero ? 'img-hero' : 'img-content',\n alt: attr(tag, 'alt'),\n width: w ? Number(w) || undefined : undefined,\n height: h ? Number(h) || undefined : undefined,\n })\n }\n\n const rank = (s: BrandImage['source']) =>\n s === 'og:image' ? 0 : s === 'twitter:image' ? 1 : s === 'img-hero' ? 2 : 3\n return out.sort((a, b) => rank(a.source) - rank(b.source))\n}\n\n// ── Public API ───────────────────────────────────────────────────────────────\n\n/** Parse already-fetched HTML into a BrandKit. Pure — no network. Exposed so\n * callers that hold the HTML (or want to combine multiple pages) can reuse the\n * parsing without re-fetching. */\nexport function parseBrandKit(html: string, sourceUrl: string, maxPerList = DEFAULT_MAX_PER_LIST): BrandKit {\n const logos = extractLogos(html, sourceUrl).slice(0, maxPerList)\n const palette = extractPalette(html).slice(0, maxPerList)\n const fonts = extractFonts(html).slice(0, maxPerList)\n const images = extractImages(html, sourceUrl).slice(0, maxPerList)\n const name = extractName(html)\n const description = extractDescription(html)\n\n return {\n sourceUrl,\n ...(name ? { name } : {}),\n ...(description ? { description } : {}),\n logos,\n palette,\n fonts,\n images,\n extractedFrom: [sourceUrl],\n }\n}\n\n/**\n * Fetch a website (or use supplied HTML) and extract its BrandKit.\n *\n * Returns a typed outcome — callers MUST check `succeeded`. A fetch failure or\n * empty input is a real, surfaced error, never an empty kit masquerading as a\n * result. Parsing itself never throws: a malformed page yields a sparse kit\n * with warnings, which is information, not failure.\n */\nexport async function extractBrandKit(\n url: string,\n options: ExtractBrandKitOptions = {},\n): Promise<BrandExtractionResult> {\n const { html: providedHtml, fetchImpl, timeoutMs = DEFAULT_TIMEOUT_MS, maxPerList = DEFAULT_MAX_PER_LIST } = options\n const warnings: string[] = []\n\n const sourceUrl = normalizeSiteUrl(url)\n if (!sourceUrl) {\n return { succeeded: false, error: `Not a valid http(s) URL: ${JSON.stringify(url)}`, stage: 'input' }\n }\n\n let html = providedHtml\n if (html === undefined) {\n const doFetch: FetchLike | undefined =\n fetchImpl ?? (typeof globalThis.fetch === 'function'\n ? (u, init) => globalThis.fetch(u, init as RequestInit)\n : undefined)\n if (!doFetch) {\n return { succeeded: false, error: 'No html provided and no fetch implementation available', stage: 'input' }\n }\n const controller = new AbortController()\n const timer = setTimeout(() => controller.abort(), timeoutMs)\n try {\n const res = await doFetch(sourceUrl, {\n signal: controller.signal,\n headers: { 'user-agent': 'TangleBrandExtractor/1.0 (+https://tangle.tools)' },\n })\n if (!res.ok) {\n return { succeeded: false, error: `Fetch failed: HTTP ${res.status} for ${sourceUrl}`, stage: 'fetch' }\n }\n html = await res.text()\n } catch (err) {\n const reason = err instanceof Error ? err.message : String(err)\n return { succeeded: false, error: `Fetch error for ${sourceUrl}: ${reason}`, stage: 'fetch' }\n } finally {\n clearTimeout(timer)\n }\n }\n\n if (!html.trim()) {\n return { succeeded: false, error: `Empty document for ${sourceUrl}`, stage: 'parse' }\n }\n\n const kit = parseBrandKit(html, sourceUrl, maxPerList)\n\n if (kit.logos.length === 0) warnings.push('No logo candidates found.')\n if (kit.palette.length === 0) warnings.push('No colors extracted — page has no inline CSS or design tokens.')\n if (kit.fonts.length === 0) warnings.push('No custom fonts found — site likely uses system defaults.')\n if (kit.images.length === 0) warnings.push('No prominent images found.')\n\n return { succeeded: true, kit, warnings }\n}\n","/**\n * Pure mapping helpers from an extracted BrandKit onto consumable shapes.\n *\n * Extraction yields ranked candidate lists; products need decided roles\n * (background vs accent, display vs body). These helpers make the obvious,\n * defensible default choice and expose the reasoning so a confirmation UI can\n * show \"we picked X — change it?\". They NEVER invent a value: when a role can't\n * be filled from the kit, it is omitted, and the caller decides the fallback.\n */\n\nimport type { BrandColor, BrandFont, BrandKit } from './types'\n\n/** Relative luminance (0..1) of an #rrggbb(aa) hex — for light/dark sorting. */\nexport function luminance(hex: string): number {\n const h = hex.replace('#', '').slice(0, 6)\n const r = parseInt(h.slice(0, 2), 16) / 255\n const g = parseInt(h.slice(2, 4), 16) / 255\n const b = parseInt(h.slice(4, 6), 16) / 255\n const lin = (c: number) => (c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4)\n return 0.2126 * lin(r) + 0.7152 * lin(g) + 0.0722 * lin(b)\n}\n\nfunction isGreyish(hex: string): boolean {\n const h = hex.replace('#', '').slice(0, 6)\n const r = parseInt(h.slice(0, 2), 16)\n const g = parseInt(h.slice(2, 4), 16)\n const b = parseInt(h.slice(4, 6), 16)\n const max = Math.max(r, g, b)\n const min = Math.min(r, g, b)\n return max - min < 18\n}\n\n/** Define a color palette with background, surface, text, and accent colors for UI elements */\nexport interface DecidedPalette {\n /** Lightest neutral — page background. */\n background?: string\n /** A raised neutral one step from background. */\n surface?: string\n /** Darkest readable color — primary text. */\n textPrimary?: string\n /** Mid-tone neutral — secondary text. */\n textSecondary?: string\n /** Most saturated / popular brand color — accent. */\n accent?: string\n /** Readable text color to sit on the accent (black or white by contrast). */\n accentText?: string\n}\n\n/**\n * Assign palette roles from the ranked colors. Heuristic, not authoritative —\n * a confirmation step should let the user correct it. Roles only appear when\n * the kit actually contained a color that fits.\n */\nexport function decidePalette(palette: BrandColor[]): DecidedPalette {\n if (palette.length === 0) return {}\n const hexes = palette.map((c) => c.hex)\n const greys = hexes.filter(isGreyish).sort((a, b) => luminance(b) - luminance(a))\n const colored = hexes.filter((h) => !isGreyish(h))\n\n // Accent: the top-ranked non-grey (token-first, popularity-first) color.\n const accent = colored[0]\n // Background: lightest grey (or lightest overall when no greys).\n const sortedLight = [...hexes].sort((a, b) => luminance(b) - luminance(a))\n const background = greys[0] ?? sortedLight[0]\n // Surface: next grey under background, else second-lightest.\n const surface = greys[1] ?? sortedLight.find((h) => h !== background)\n // Text primary: darkest color overall.\n const textPrimary = [...hexes].sort((a, b) => luminance(a) - luminance(b))[0]\n // Text secondary: a mid-luminance grey distinct from primary/background.\n const textSecondary = greys.find((h) => h !== background && h !== surface && h !== textPrimary)\n\n const result: DecidedPalette = {}\n if (background) result.background = background\n if (surface) result.surface = surface\n if (textPrimary) result.textPrimary = textPrimary\n if (textSecondary) result.textSecondary = textSecondary\n if (accent) {\n result.accent = accent\n result.accentText = luminance(accent) > 0.45 ? '#000000' : '#ffffff'\n }\n return result\n}\n\n/** Define font selections for display and body text with optional BrandFont properties */\nexport interface DecidedFonts {\n display?: BrandFont\n body?: BrandFont\n}\n\n/** Pick a display and body font from the ranked list. When only one usable\n * font exists it fills both roles — a single-typeface brand is valid. */\nexport function decideFonts(fonts: BrandFont[]): DecidedFonts {\n if (fonts.length === 0) return {}\n const display = fonts.find((f) => f.role === 'display') ?? fonts[0]\n const body = fonts.find((f) => f.role === 'body') ?? fonts.find((f) => f !== display) ?? display\n return { display, body }\n}\n\n/** Everything a confirmation step needs from a kit, with roles decided. */\nexport interface DecidedBrandKit {\n name?: string\n description?: string\n sourceUrl: string\n palette: DecidedPalette\n fonts: DecidedFonts\n /** Best logo URL, when any candidate was found. */\n primaryLogoUrl?: string\n /** All logo URLs, ranked. */\n logoUrls: string[]\n /** Prominent image URLs, ranked. */\n imageUrls: string[]\n extractedFrom: string[]\n}\n\n/** Collapse a raw BrandKit into decided roles — the shape a product persists. */\nexport function decideBrandKit(kit: BrandKit): DecidedBrandKit {\n const palette = decidePalette(kit.palette)\n const fonts = decideFonts(kit.fonts)\n const logoUrls = kit.logos.map((l) => l.url)\n const result: DecidedBrandKit = {\n sourceUrl: kit.sourceUrl,\n palette,\n fonts,\n logoUrls,\n imageUrls: kit.images.map((i) => i.url),\n extractedFrom: kit.extractedFrom,\n }\n if (kit.name) result.name = kit.name\n if (kit.description) result.description = kit.description\n if (logoUrls[0]) result.primaryLogoUrl = logoUrls[0]\n return result\n}\n"],"mappings":";AA4BA,IAAM,qBAAqB;AAC3B,IAAM,uBAAuB;AAKtB,SAAS,iBAAiB,KAA4B;AAC3D,QAAM,UAAU,IAAI,KAAK;AACzB,MAAI,CAAC,QAAS,QAAO;AA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IAAI,OAAO,IAAI,CAAC,MAAM,EAAE,GAAG;AAAA,IACtC,eAAe,IAAI;AAAA,EACrB;AACA,MAAI,IAAI,KAAM,QAAO,OAAO,IAAI;AAChC,MAAI,IAAI,YAAa,QAAO,cAAc,IAAI;AAC9C,MAAI,SAAS,CAAC,EAAG,QAAO,iBAAiB,SAAS,CAAC;AACnD,SAAO;AACT;","names":[]}
1
+ {"version":3,"sources":["../../src/brand-extraction/extract.ts","../../src/brand-extraction/map.ts"],"sourcesContent":["/**\n * Brand-kit extraction engine.\n *\n * Given a website URL (or raw HTML), parse the page and pull a typed BrandKit:\n * logo candidates, color palette, fonts, and prominent images. Parsing is\n * regex-based on purpose — this runs on Cloudflare Workers and other edge\n * runtimes where DOM libraries (jsdom/cheerio) are unavailable, and the page\n * structures we read (link tags, meta tags, CSS custom properties, font-family\n * declarations) are flat enough that a DOM buys nothing.\n *\n * Degrades gracefully: a missing favicon, no CSS tokens, or an image-only page\n * each narrow the kit rather than failing it. The ONLY hard failures are a bad\n * input (no html and no fetch) and a fetch error — both returned as a typed\n * `{ succeeded: false }` outcome so callers never mistake an empty kit for a\n * real one.\n */\n\nimport type {\n BrandColor,\n BrandExtractionResult,\n BrandFont,\n BrandImage,\n BrandKit,\n BrandLogoCandidate,\n ExtractBrandKitOptions,\n FetchLike,\n} from './types'\n\nconst DEFAULT_TIMEOUT_MS = 15000\nconst DEFAULT_MAX_PER_LIST = 12\n\n// ── URL helpers ──────────────────────────────────────────────────────────────\n\n/** Normalize a user-supplied site URL: add https:// when scheme-less, validate. */\nexport function normalizeSiteUrl(raw: string): string | null {\n const trimmed = raw.trim()\n if (!trimmed) return null\n // A non-http(s) scheme is an explicit reject — don't paper over it by\n // prepending https:// (that would turn \"ftp://x\" into host \"ftp\").\n if (/^[a-z][a-z0-9+.-]*:/i.test(trimmed) && !/^https?:\\/\\//i.test(trimmed)) return null\n const withScheme = /^https?:\\/\\//i.test(trimmed) ? trimmed : `https://${trimmed}`\n try {\n const u = new URL(withScheme)\n if (u.protocol !== 'http:' && u.protocol !== 'https:') return null\n return u.toString()\n } catch {\n return null\n }\n}\n\n/** Resolve a possibly-relative href against the page URL. Returns null for\n * data: URIs and unresolvable values — we want servable http(s) URLs only. */\nfunction absolutize(href: string, base: string): string | null {\n const v = href.trim()\n if (!v || v.startsWith('data:') || v.startsWith('javascript:')) return null\n try {\n const u = new URL(v, base)\n if (u.protocol !== 'http:' && u.protocol !== 'https:') return null\n return u.toString()\n } catch {\n return null\n }\n}\n\n// ── Attribute parsing ────────────────────────────────────────────────────────\n\n/** Pull all `<tag ...>` open-tags from html (case-insensitive). */\nfunction matchTags(html: string, tag: string): string[] {\n const re = new RegExp(`<${tag}\\\\b[^>]*>`, 'gi')\n return html.match(re) ?? []\n}\n\n/** Read an attribute value from a single tag string. Handles quoted and\n * unquoted values. Returns undefined when absent. */\nfunction attr(tag: string, name: string): string | undefined {\n const quoted = new RegExp(`\\\\b${name}\\\\s*=\\\\s*[\"']([^\"']*)[\"']`, 'i').exec(tag)\n if (quoted) return decodeEntities(quoted[1] ?? '')\n const bare = new RegExp(`\\\\b${name}\\\\s*=\\\\s*([^\\\\s\"'>]+)`, 'i').exec(tag)\n return bare ? decodeEntities(bare[1] ?? '') : undefined\n}\n\nfunction decodeEntities(s: string): string {\n return s\n .replace(/&amp;/g, '&')\n .replace(/&lt;/g, '<')\n .replace(/&gt;/g, '>')\n .replace(/&quot;/g, '\"')\n .replace(/&#39;/g, \"'\")\n .replace(/&#x2F;/gi, '/')\n}\n\n// ── Name / description ───────────────────────────────────────────────────────\n\nfunction extractName(html: string): string | undefined {\n for (const tag of matchTags(html, 'meta')) {\n const prop = (attr(tag, 'property') ?? attr(tag, 'name'))?.toLowerCase()\n if (prop === 'og:site_name') {\n const c = attr(tag, 'content')?.trim()\n if (c) return c\n }\n }\n const title = /<title[^>]*>([\\s\\S]*?)<\\/title>/i.exec(html)?.[1]\n if (title) {\n // \"Acme — the best widget\" → \"Acme\". Split on common separators, take head.\n const head = (decodeEntities(title).split(/\\s+[|–—\\-:·]\\s+/)[0] ?? '').trim()\n if (head) return head\n }\n return undefined\n}\n\nfunction extractDescription(html: string): string | undefined {\n for (const tag of matchTags(html, 'meta')) {\n const prop = (attr(tag, 'property') ?? attr(tag, 'name'))?.toLowerCase()\n if (prop === 'description' || prop === 'og:description') {\n const c = attr(tag, 'content')?.trim()\n if (c) return c\n }\n }\n return undefined\n}\n\n// ── Logos ────────────────────────────────────────────────────────────────────\n\nconst MIME_BY_EXT: Record<string, string> = {\n png: 'image/png',\n jpg: 'image/jpeg',\n jpeg: 'image/jpeg',\n gif: 'image/gif',\n webp: 'image/webp',\n svg: 'image/svg+xml',\n ico: 'image/x-icon',\n}\n\nfunction mimeFromUrl(url: string): string | undefined {\n const ext = new URL(url).pathname.split('.').pop()?.toLowerCase()\n return ext ? MIME_BY_EXT[ext] : undefined\n}\n\nfunction parseSizes(sizes: string | undefined): { width?: number; height?: number } {\n if (!sizes) return {}\n const m = /(\\d+)\\s*[x×]\\s*(\\d+)/i.exec(sizes)\n if (!m) return {}\n return { width: Number(m[1]), height: Number(m[2]) }\n}\n\n/** The site's own name in comparable form: its host label and its og:site_name, lower-case letters and digits only. */\nfunction siteNames(html: string, base: string): string[] {\n const squash = (value: string) => value.toLowerCase().replace(/[^a-z0-9]/g, '')\n const names: string[] = []\n try {\n const labels = new URL(base).hostname.replace(/^www\\./, '').split('.')\n const label = labels.length > 1 ? labels[labels.length - 2] : labels[0]\n if (label) names.push(squash(label))\n } catch {\n // An unparsable base names nothing.\n }\n const site = extractName(html)\n if (site) names.push(squash(site.split(/\\s+[|–—\\-:·]\\s+/)[0] ?? site))\n return names.filter((name) => name.length >= 3)\n}\n\n/** Words that name a logo's form, not its owner (\"Logo_White\", \"logo-dark\"). */\nconst LOGO_FORM_WORDS = new Set(['logo', 'logos', 'default', 'white', 'black', 'dark', 'light', 'color', 'colour', 'main', 'primary',\n 'header', 'footer', 'nav', 'site', 'brand', 'mark', 'wordmark', 'full', 'small', 'large', 'mobile', 'desktop', 'svg', 'png', 'icon', 'the', 'and', 'for', 'of',\n 'company', 'our', 'new', 'retina', 'horizontal', 'vertical', 'stacked', 'inverse', 'inverted', 'transparent', 'image', 'img'])\n\n/**\n * The brand a logo image names when it is someone else's: \"Logo for IKEA\",\n * \"Logo_IKEA.png\", \"taskprotect_logo.svg\" on taskrabbit.com. A partner,\n * customer or sub-brand logo is not the site's own.\n */\nfunction otherBrandNamed(text: string, own: string[]): string | null {\n const squash = (value: string) => value.toLowerCase().replace(/[^a-z0-9]/g, '')\n const named = [\n ...text.matchAll(/\\blogo(?:s)?(?:[\\s_-]+(?:for|of))?[\\s_-]+([A-Za-z][A-Za-z0-9&]+)/gi),\n ...text.matchAll(/([A-Za-z][A-Za-z0-9&]+)[\\s_-]+logo\\b/gi),\n ].map((match) => squash(match[1] ?? '')).filter((name) => name.length >= 3 && !LOGO_FORM_WORDS.has(name))\n if (named.length === 0) return null\n const ours = (name: string) => own.some((site) => site.includes(name) || name.includes(site))\n return named.some(ours) ? null : named[0]!\n}\n\n/** Whether `index` falls inside the page header, or inside a link to the site's home page. */\nfunction inHeaderOrHomeLink(html: string, index: number, base: string): boolean {\n const before = html.slice(0, index)\n const openHeader = before.lastIndexOf('<header')\n if (openHeader >= 0 && before.indexOf('</header>', openHeader) < 0) return true\n const openLink = Math.max(before.lastIndexOf('<a '), before.lastIndexOf('<a\\n'), before.lastIndexOf('<a>'))\n if (openLink < 0 || before.indexOf('</a>', openLink) >= 0) return false\n const href = attr(/<a\\b[^>]*>/i.exec(before.slice(openLink))?.[0] ?? '', 'href')\n if (!href) return false\n try {\n const target = new URL(href, base)\n return target.origin === new URL(base).origin && (target.pathname === '/' || target.pathname === '')\n } catch {\n return false\n }\n}\n\nfunction extractLogos(html: string, base: string): BrandLogoCandidate[] {\n const out: BrandLogoCandidate[] = []\n const seen = new Set<string>()\n const push = (c: BrandLogoCandidate) => {\n if (seen.has(c.url)) return\n seen.add(c.url)\n out.push(c)\n }\n\n // link rel icons / apple-touch-icon\n for (const tag of matchTags(html, 'link')) {\n const rel = attr(tag, 'rel')?.toLowerCase() ?? ''\n const href = attr(tag, 'href')\n if (!href) continue\n const url = absolutize(href, base)\n if (!url) continue\n const { width, height } = parseSizes(attr(tag, 'sizes'))\n if (rel.includes('apple-touch-icon')) {\n push({ url, source: 'apple-touch-icon', confidence: 0.7, width, height, mimeType: mimeFromUrl(url) })\n } else if (rel.split(/\\s+/).includes('icon') || rel.includes('shortcut icon')) {\n push({ url, source: 'favicon', confidence: 0.5, width, height, mimeType: mimeFromUrl(url) })\n }\n }\n\n // og:image (often shows the logo in context — moderate confidence)\n for (const tag of matchTags(html, 'meta')) {\n const prop = (attr(tag, 'property') ?? attr(tag, 'name'))?.toLowerCase()\n if (prop === 'og:image' || prop === 'og:image:url') {\n const href = attr(tag, 'content')\n const url = href ? absolutize(href, base) : null\n if (url) push({ url, source: 'og:image', confidence: 0.55, mimeType: mimeFromUrl(url) })\n }\n }\n\n // <img> whose src/class/alt/id mentions \"logo\" — the strongest in-page signal.\n // The site's own logo sits in its header or its home link; one that names\n // another brand (a partner, customer or sub-brand) ranks below the icons.\n const own = siteNames(html, base)\n for (const found of html.matchAll(/<img\\b[^>]*>/gi)) {\n const tag = found[0]\n const src = attr(tag, 'src') ?? attr(tag, 'data-src')\n if (!src) continue\n const alt = attr(tag, 'alt')\n const cls = attr(tag, 'class') ?? ''\n const id = attr(tag, 'id') ?? ''\n const looksLikeLogo = /logo|brand|wordmark/i.test(`${src} ${alt ?? ''} ${cls} ${id}`)\n if (!looksLikeLogo) continue\n const url = absolutize(src, base)\n if (!url) continue\n const w = attr(tag, 'width')\n const h = attr(tag, 'height')\n const filename = decodeURIComponent(new URL(url).pathname.split('/').pop() ?? '')\n const partner = otherBrandNamed(`${alt ?? ''} ${filename}`, own)\n const placed = inHeaderOrHomeLink(html, found.index ?? 0, base)\n push({\n url,\n source: 'img-logo',\n confidence: partner && !placed ? 0.4 : placed ? 0.95 : 0.85,\n alt,\n width: w ? Number(w) || undefined : undefined,\n height: h ? Number(h) || undefined : undefined,\n mimeType: mimeFromUrl(url),\n })\n }\n\n // No favicon link tag at all? Fall back to the conventional /favicon.ico —\n // it almost always exists. Lowest confidence.\n if (!out.some((l) => l.source === 'favicon' || l.source === 'apple-touch-icon')) {\n const fav = absolutize('/favicon.ico', base)\n if (fav) push({ url: fav, source: 'favicon', confidence: 0.3, mimeType: 'image/x-icon' })\n }\n\n return out.sort((a, b) => b.confidence - a.confidence)\n}\n\n// ── Colors ───────────────────────────────────────────────────────────────────\n\n/** Normalize any CSS color literal to #rrggbb / #rrggbbaa hex, or null. */\nexport function normalizeColor(raw: string): string | null {\n const v = raw.trim().toLowerCase()\n // #rgb / #rgba / #rrggbb / #rrggbbaa\n const hex = /^#([0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/i.exec(v)\n if (hex) {\n const h = hex[1] ?? ''\n // Expand 3/4-digit shorthand by doubling each nibble.\n if (h.length === 3 || h.length === 4) {\n return `#${h.split('').map((c) => c + c).join('')}`\n }\n return `#${h}`\n }\n // rgb()/rgba()\n const rgb = /^rgba?\\(\\s*([\\d.]+)[\\s,]+([\\d.]+)[\\s,]+([\\d.]+)(?:[\\s,/]+([\\d.%]+))?\\s*\\)$/.exec(v)\n if (rgb) {\n const to255 = (n: string | undefined) => Math.max(0, Math.min(255, Math.round(Number(n))))\n const r = to255(rgb[1]).toString(16).padStart(2, '0')\n const g = to255(rgb[2]).toString(16).padStart(2, '0')\n const b = to255(rgb[3]).toString(16).padStart(2, '0')\n let a = ''\n if (rgb[4] !== undefined) {\n const av = rgb[4].endsWith('%') ? Number(rgb[4].slice(0, -1)) / 100 : Number(rgb[4])\n const ai = Math.max(0, Math.min(255, Math.round(av * 255)))\n if (ai < 255) a = ai.toString(16).padStart(2, '0')\n }\n return `#${r}${g}${b}${a}`\n }\n return null\n}\n\nconst COLOR_LITERAL_RE = /#[0-9a-fA-F]{3,8}\\b|rgba?\\([^)]*\\)/g\nconst ROOT_VAR_RE = /(--[a-z0-9-]*(?:color|colour|bg|background|accent|brand|primary|secondary|surface|text|fg|ink)[a-z0-9-]*)\\s*:\\s*([^;}{]+)/gi\n\nfunction extractPalette(html: string): BrandColor[] {\n const byHex = new Map<string, BrandColor>()\n const bump = (hex: string, fromToken: boolean, tokenName?: string) => {\n const existing = byHex.get(hex)\n if (existing) {\n existing.occurrences += 1\n if (fromToken && !existing.fromToken) {\n existing.fromToken = true\n existing.tokenName = tokenName\n }\n } else {\n byHex.set(hex, { hex, occurrences: 1, fromToken, ...(tokenName ? { tokenName } : {}) })\n }\n }\n\n // CSS custom properties — highest-fidelity design tokens.\n for (const m of html.matchAll(ROOT_VAR_RE)) {\n const tokenName = m[1]\n const value = m[2]\n if (!value) continue\n const lit = value.match(COLOR_LITERAL_RE)?.[0]\n if (!lit) continue\n const hex = normalizeColor(lit)\n if (hex) bump(hex, true, tokenName)\n }\n\n // All other color literals across the document (inline styles, <style>).\n for (const m of html.matchAll(COLOR_LITERAL_RE)) {\n const hex = normalizeColor(m[0])\n if (hex) bump(hex, false)\n }\n\n // Rank: token-sourced first, then by popularity. Drop pure white/black noise\n // to the back so a real brand color leads.\n const isNeutral = (h: string) => /^#(0{6}|f{6})(ff)?$/i.test(h)\n return [...byHex.values()].sort((a, b) => {\n if (a.fromToken !== b.fromToken) return a.fromToken ? -1 : 1\n const an = isNeutral(a.hex) ? 1 : 0\n const bn = isNeutral(b.hex) ? 1 : 0\n if (an !== bn) return an - bn\n return b.occurrences - a.occurrences\n })\n}\n\n// ── Fonts ────────────────────────────────────────────────────────────────────\n\nconst GENERIC_FAMILIES = new Set([\n 'serif', 'sans-serif', 'monospace', 'cursive', 'fantasy', 'system-ui',\n 'ui-sans-serif', 'ui-serif', 'ui-monospace', 'ui-rounded', 'inherit', 'initial', 'unset',\n])\n\n/** The last terminated font-family declaration in one rule body. Applied to a\n * body that holds no brace except an optional closing one, so its\n * backtracking stays inside that body. */\nconst BLOCK_FONT_DECL_RE = /^[^{}]*font-family\\s*:\\s*([^;}{]+)[;}]/i\n\n/**\n * Each rule body's font-family stack, with the selector text before the body\n * for role inference.\n *\n * One pass over the braces. A single unanchored `([^{}]*)\\{[^{}]*font-family`\n * pattern restarted its selector scan at every character of a brace-free run,\n * so a long run of page markup before a rule without a font-family made it\n * quadratic: a 366 KB page took 74 s and the brand intake request exceeded its\n * CPU limit. This walk gives the same selectors and stacks: the selector is\n * the text since the previous brace or the end of the previous declaration it\n * found, whichever is later.\n */\nfunction fontDeclarations(html: string): Array<{ selector: string; stack: string }> {\n const declarations: Array<{ selector: string; stack: string }> = []\n const braces = /[{}]/g\n const nextBrace = /[{}]/g\n let previousBrace = -1\n let resumeAt = 0\n for (let brace = braces.exec(html); brace; brace = braces.exec(html)) {\n const at = brace.index\n if (html[at] === '{') {\n nextBrace.lastIndex = at + 1\n const next = nextBrace.exec(html)\n // The body runs to the next brace and keeps a closing one, which can end the declaration.\n const end = next ? next.index + 1 : html.length\n const match = BLOCK_FONT_DECL_RE.exec(html.slice(at + 1, end))\n if (match) {\n declarations.push({ selector: html.slice(Math.max(previousBrace + 1, resumeAt), at), stack: match[1]! })\n resumeAt = at + 1 + match[0].length\n }\n }\n previousBrace = at\n }\n return declarations\n}\n\nfunction parseFontStack(raw: string | undefined): string[] {\n if (!raw) return []\n return raw\n .split(',')\n .map((s) => s.trim().replace(/^[\"']|[\"']$/g, ''))\n .filter(Boolean)\n}\n\nfunction roleFromSelector(selector: string): 'display' | 'body' | 'unknown' {\n const s = selector.toLowerCase()\n if (/\\b(h[1-3]|\\.h[1-3]|heading|title|display|hero)\\b/.test(s)) return 'display'\n if (/\\b(body|p|html|\\.text|\\.content|root|:root|\\*)\\b/.test(s)) return 'body'\n return 'unknown'\n}\n\nfunction extractFonts(html: string): BrandFont[] {\n // Restrict to <style> blocks + the whole doc; inline style=\"\" attributes are\n // included because the regex matches any `{...font-family...}` chunk, but we\n // also scan style attributes explicitly below.\n const byFamily = new Map<string, BrandFont>()\n const consider = (family: string, stack: string[], role: BrandFont['role']) => {\n const key = family.toLowerCase()\n if (!family || GENERIC_FAMILIES.has(key)) return\n const existing = byFamily.get(key)\n if (existing) {\n existing.occurrences += 1\n if (existing.role === 'unknown' && role !== 'unknown') existing.role = role\n } else {\n byFamily.set(key, { family, stack, role, occurrences: 1 })\n }\n }\n\n for (const declaration of fontDeclarations(html)) {\n const stack = parseFontStack(declaration.stack)\n const primary = stack[0]\n if (!primary) continue\n consider(primary, stack, roleFromSelector(declaration.selector))\n }\n\n // Bare `font-family:` declarations inside inline style attributes and tokens.\n const BARE_RE = /font-family\\s*:\\s*([^;\"'}{]+)/gi\n for (const m of html.matchAll(BARE_RE)) {\n const stack = parseFontStack(m[1])\n const primary = stack[0]\n if (!primary) continue\n consider(primary, stack, 'unknown')\n }\n\n // Google Fonts <link href=\"...family=Inter:wght@400...\"> — strong signal.\n for (const tag of matchTags(html, 'link')) {\n const href = attr(tag, 'href') ?? ''\n if (!/fonts\\.googleapis\\.com/i.test(href)) continue\n for (const fam of href.matchAll(/family=([^:&]+)/gi)) {\n const captured = fam[1]\n if (!captured) continue\n const family = decodeURIComponent(captured.replace(/\\+/g, ' ')).trim()\n consider(family, [family], 'display')\n }\n }\n\n return [...byFamily.values()].sort((a, b) => {\n const rank = (r: BrandFont['role']) => (r === 'display' ? 0 : r === 'body' ? 1 : 2)\n const rr = rank(a.role) - rank(b.role)\n if (rr !== 0) return rr\n return b.occurrences - a.occurrences\n })\n}\n\n// ── Images ───────────────────────────────────────────────────────────────────\n\nfunction extractImages(html: string, base: string): BrandImage[] {\n const out: BrandImage[] = []\n const seen = new Set<string>()\n const push = (img: BrandImage) => {\n if (seen.has(img.url)) return\n seen.add(img.url)\n out.push(img)\n }\n\n for (const tag of matchTags(html, 'meta')) {\n const prop = (attr(tag, 'property') ?? attr(tag, 'name'))?.toLowerCase()\n const href = attr(tag, 'content')\n const url = href ? absolutize(href, base) : null\n if (!url) continue\n if (prop === 'og:image' || prop === 'og:image:url') push({ url, source: 'og:image' })\n else if (prop === 'twitter:image' || prop === 'twitter:image:src') push({ url, source: 'twitter:image' })\n }\n\n for (const tag of matchTags(html, 'img')) {\n const src = attr(tag, 'src') ?? attr(tag, 'data-src')\n if (!src) continue\n const url = absolutize(src, base)\n if (!url) continue\n const cls = `${attr(tag, 'class') ?? ''} ${attr(tag, 'id') ?? ''}`\n // Skip obvious logos/icons — those go in the logos list, not images.\n if (/logo|icon|favicon|wordmark/i.test(`${url} ${cls}`)) continue\n const isHero = /hero|banner|cover|feature|splash/i.test(cls)\n const w = attr(tag, 'width')\n const h = attr(tag, 'height')\n push({\n url,\n source: isHero ? 'img-hero' : 'img-content',\n alt: attr(tag, 'alt'),\n width: w ? Number(w) || undefined : undefined,\n height: h ? Number(h) || undefined : undefined,\n })\n }\n\n const rank = (s: BrandImage['source']) =>\n s === 'og:image' ? 0 : s === 'twitter:image' ? 1 : s === 'img-hero' ? 2 : 3\n return out.sort((a, b) => rank(a.source) - rank(b.source))\n}\n\n// ── Public API ───────────────────────────────────────────────────────────────\n\n/** Parse already-fetched HTML into a BrandKit. Pure — no network. Exposed so\n * callers that hold the HTML (or want to combine multiple pages) can reuse the\n * parsing without re-fetching. */\nexport function parseBrandKit(html: string, sourceUrl: string, maxPerList = DEFAULT_MAX_PER_LIST): BrandKit {\n const logos = extractLogos(html, sourceUrl).slice(0, maxPerList)\n const palette = extractPalette(html).slice(0, maxPerList)\n const fonts = extractFonts(html).slice(0, maxPerList)\n const images = extractImages(html, sourceUrl).slice(0, maxPerList)\n const name = extractName(html)\n const description = extractDescription(html)\n\n return {\n sourceUrl,\n ...(name ? { name } : {}),\n ...(description ? { description } : {}),\n logos,\n palette,\n fonts,\n images,\n extractedFrom: [sourceUrl],\n }\n}\n\n/**\n * Fetch a website (or use supplied HTML) and extract its BrandKit.\n *\n * Returns a typed outcome — callers MUST check `succeeded`. A fetch failure or\n * empty input is a real, surfaced error, never an empty kit masquerading as a\n * result. Parsing itself never throws: a malformed page yields a sparse kit\n * with warnings, which is information, not failure.\n */\nexport async function extractBrandKit(\n url: string,\n options: ExtractBrandKitOptions = {},\n): Promise<BrandExtractionResult> {\n const { html: providedHtml, fetchImpl, timeoutMs = DEFAULT_TIMEOUT_MS, maxPerList = DEFAULT_MAX_PER_LIST } = options\n const warnings: string[] = []\n\n const sourceUrl = normalizeSiteUrl(url)\n if (!sourceUrl) {\n return { succeeded: false, error: `Not a valid http(s) URL: ${JSON.stringify(url)}`, stage: 'input' }\n }\n\n let html = providedHtml\n if (html === undefined) {\n const doFetch: FetchLike | undefined =\n fetchImpl ?? (typeof globalThis.fetch === 'function'\n ? (u, init) => globalThis.fetch(u, init as RequestInit)\n : undefined)\n if (!doFetch) {\n return { succeeded: false, error: 'No html provided and no fetch implementation available', stage: 'input' }\n }\n const controller = new AbortController()\n const timer = setTimeout(() => controller.abort(), timeoutMs)\n try {\n const res = await doFetch(sourceUrl, {\n signal: controller.signal,\n headers: { 'user-agent': 'TangleBrandExtractor/1.0 (+https://tangle.tools)' },\n })\n if (!res.ok) {\n return { succeeded: false, error: `Fetch failed: HTTP ${res.status} for ${sourceUrl}`, stage: 'fetch' }\n }\n html = await res.text()\n } catch (err) {\n const reason = err instanceof Error ? err.message : String(err)\n return { succeeded: false, error: `Fetch error for ${sourceUrl}: ${reason}`, stage: 'fetch' }\n } finally {\n clearTimeout(timer)\n }\n }\n\n if (!html.trim()) {\n return { succeeded: false, error: `Empty document for ${sourceUrl}`, stage: 'parse' }\n }\n\n const kit = parseBrandKit(html, sourceUrl, maxPerList)\n\n if (kit.logos.length === 0) warnings.push('No logo candidates found.')\n if (kit.palette.length === 0) warnings.push('No colors extracted — page has no inline CSS or design tokens.')\n if (kit.fonts.length === 0) warnings.push('No custom fonts found — site likely uses system defaults.')\n if (kit.images.length === 0) warnings.push('No prominent images found.')\n\n return { succeeded: true, kit, warnings }\n}\n","/**\n * Pure mapping helpers from an extracted BrandKit onto consumable shapes.\n *\n * Extraction yields ranked candidate lists; products need decided roles\n * (background vs accent, display vs body). These helpers make the obvious,\n * defensible default choice and expose the reasoning so a confirmation UI can\n * show \"we picked X — change it?\". They NEVER invent a value: when a role can't\n * be filled from the kit, it is omitted, and the caller decides the fallback.\n */\n\nimport type { BrandColor, BrandFont, BrandKit } from './types'\n\n/** Relative luminance (0..1) of an #rrggbb(aa) hex — for light/dark sorting. */\nexport function luminance(hex: string): number {\n const h = hex.replace('#', '').slice(0, 6)\n const r = parseInt(h.slice(0, 2), 16) / 255\n const g = parseInt(h.slice(2, 4), 16) / 255\n const b = parseInt(h.slice(4, 6), 16) / 255\n const lin = (c: number) => (c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4)\n return 0.2126 * lin(r) + 0.7152 * lin(g) + 0.0722 * lin(b)\n}\n\nfunction isGreyish(hex: string): boolean {\n const h = hex.replace('#', '').slice(0, 6)\n const r = parseInt(h.slice(0, 2), 16)\n const g = parseInt(h.slice(2, 4), 16)\n const b = parseInt(h.slice(4, 6), 16)\n const max = Math.max(r, g, b)\n const min = Math.min(r, g, b)\n return max - min < 18\n}\n\n/** Define a color palette with background, surface, text, and accent colors for UI elements */\nexport interface DecidedPalette {\n /** Lightest neutral — page background. */\n background?: string\n /** A raised neutral one step from background. */\n surface?: string\n /** Darkest readable color — primary text. */\n textPrimary?: string\n /** Mid-tone neutral — secondary text. */\n textSecondary?: string\n /** Most saturated / popular brand color — accent. */\n accent?: string\n /** Readable text color to sit on the accent (black or white by contrast). */\n accentText?: string\n}\n\n/**\n * Assign palette roles from the ranked colors. Heuristic, not authoritative —\n * a confirmation step should let the user correct it. Roles only appear when\n * the kit actually contained a color that fits.\n */\nexport function decidePalette(palette: BrandColor[]): DecidedPalette {\n if (palette.length === 0) return {}\n const hexes = palette.map((c) => c.hex)\n const greys = hexes.filter(isGreyish).sort((a, b) => luminance(b) - luminance(a))\n const colored = hexes.filter((h) => !isGreyish(h))\n\n // Accent: the top-ranked non-grey (token-first, popularity-first) color.\n const accent = colored[0]\n // Background: lightest grey (or lightest overall when no greys).\n const sortedLight = [...hexes].sort((a, b) => luminance(b) - luminance(a))\n const background = greys[0] ?? sortedLight[0]\n // Surface: next grey under background, else second-lightest.\n const surface = greys[1] ?? sortedLight.find((h) => h !== background)\n // Text primary: darkest color overall.\n const textPrimary = [...hexes].sort((a, b) => luminance(a) - luminance(b))[0]\n // Text secondary: a mid-luminance grey distinct from primary/background.\n const textSecondary = greys.find((h) => h !== background && h !== surface && h !== textPrimary)\n\n const result: DecidedPalette = {}\n if (background) result.background = background\n if (surface) result.surface = surface\n if (textPrimary) result.textPrimary = textPrimary\n if (textSecondary) result.textSecondary = textSecondary\n if (accent) {\n result.accent = accent\n result.accentText = luminance(accent) > 0.45 ? '#000000' : '#ffffff'\n }\n return result\n}\n\n/** Define font selections for display and body text with optional BrandFont properties */\nexport interface DecidedFonts {\n display?: BrandFont\n body?: BrandFont\n}\n\n/** Pick a display and body font from the ranked list. When only one usable\n * font exists it fills both roles — a single-typeface brand is valid. */\nexport function decideFonts(fonts: BrandFont[]): DecidedFonts {\n if (fonts.length === 0) return {}\n const display = fonts.find((f) => f.role === 'display') ?? fonts[0]\n const body = fonts.find((f) => f.role === 'body') ?? fonts.find((f) => f !== display) ?? display\n return { display, body }\n}\n\n/** Everything a confirmation step needs from a kit, with roles decided. */\nexport interface DecidedBrandKit {\n name?: string\n description?: string\n sourceUrl: string\n palette: DecidedPalette\n fonts: DecidedFonts\n /** Best logo URL, when any candidate was found. */\n primaryLogoUrl?: string\n /** All logo URLs, ranked. */\n logoUrls: string[]\n /** Prominent image URLs, ranked. */\n imageUrls: string[]\n extractedFrom: string[]\n}\n\n/** Collapse a raw BrandKit into decided roles — the shape a product persists. */\nexport function decideBrandKit(kit: BrandKit): DecidedBrandKit {\n const palette = decidePalette(kit.palette)\n const fonts = decideFonts(kit.fonts)\n const logoUrls = kit.logos.map((l) => l.url)\n const result: DecidedBrandKit = {\n sourceUrl: kit.sourceUrl,\n palette,\n fonts,\n logoUrls,\n imageUrls: kit.images.map((i) => i.url),\n extractedFrom: kit.extractedFrom,\n }\n if (kit.name) result.name = kit.name\n if (kit.description) result.description = kit.description\n if (logoUrls[0]) result.primaryLogoUrl = logoUrls[0]\n return result\n}\n"],"mappings":";AA4BA,IAAM,qBAAqB;AAC3B,IAAM,uBAAuB;AAKtB,SAAS,iBAAiB,KAA4B;AAC3D,QAAM,UAAU,IAAI,KAAK;AACzB,MAAI,CAAC,QAAS,QAAO;AAGrB,MAAI,uBAAuB,KAAK,OAAO,KAAK,CAAC,gBAAgB,KAAK,OAAO,EAAG,QAAO;AACnF,QAAM,aAAa,gBAAgB,KAAK,OAAO,IAAI,UAAU,WAAW,OAAO;AAC/E,MAAI;AACF,UAAM,IAAI,IAAI,IAAI,UAAU;AAC5B,QAAI,EAAE,aAAa,WAAW,EAAE,aAAa,SAAU,QAAO;AAC9D,WAAO,EAAE,SAAS;AAAA,EACpB,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAIA,SAAS,WAAW,MAAc,MAA6B;AAC7D,QAAM,IAAI,KAAK,KAAK;AACpB,MAAI,CAAC,KAAK,EAAE,WAAW,OAAO,KAAK,EAAE,WAAW,aAAa,EAAG,QAAO;AACvE,MAAI;AACF,UAAM,IAAI,IAAI,IAAI,GAAG,IAAI;AACzB,QAAI,EAAE,aAAa,WAAW,EAAE,aAAa,SAAU,QAAO;AAC9D,WAAO,EAAE,SAAS;AAAA,EACpB,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAKA,SAAS,UAAU,MAAc,KAAuB;AACtD,QAAM,KAAK,IAAI,OAAO,IAAI,GAAG,aAAa,IAAI;AAC9C,SAAO,KAAK,MAAM,EAAE,KAAK,CAAC;AAC5B;AAIA,SAAS,KAAK,KAAa,MAAkC;AAC3D,QAAM,SAAS,IAAI,OAAO,MAAM,IAAI,6BAA6B,GAAG,EAAE,KAAK,GAAG;AAC9E,MAAI,OAAQ,QAAO,eAAe,OAAO,CAAC,KAAK,E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M,WAAW,EAAG,QAAO,CAAC;AAChC,QAAM,UAAU,MAAM,KAAK,CAAC,MAAM,EAAE,SAAS,SAAS,KAAK,MAAM,CAAC;AAClE,QAAM,OAAO,MAAM,KAAK,CAAC,MAAM,EAAE,SAAS,MAAM,KAAK,MAAM,KAAK,CAAC,MAAM,MAAM,OAAO,KAAK;AACzF,SAAO,EAAE,SAAS,KAAK;AACzB;AAmBO,SAAS,eAAe,KAAgC;AAC7D,QAAM,UAAU,cAAc,IAAI,OAAO;AACzC,QAAM,QAAQ,YAAY,IAAI,KAAK;AACnC,QAAM,WAAW,IAAI,MAAM,IAAI,CAAC,MAAM,EAAE,GAAG;AAC3C,QAAM,SAA0B;AAAA,IAC9B,WAAW,IAAI;AAAA,IACf;AAAA,IACA;AAAA,IACA;AAAA,IACA,WAAW,IAAI,OAAO,IAAI,CAAC,MAAM,EAAE,GAAG;AAAA,IACtC,eAAe,IAAI;AAAA,EACrB;AACA,MAAI,IAAI,KAAM,QAAO,OAAO,IAAI;AAChC,MAAI,IAAI,YAAa,QAAO,cAAc,IAAI;AAC9C,MAAI,SAAS,CAAC,EAAG,QAAO,iBAAiB,SAAS,CAAC;AACnD,SAAO;AACT;","names":[]}
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  ComposerModeControls,
3
3
  EntryComposer
4
- } from "../chunk-EQ6CGOZK.js";
4
+ } from "../chunk-GNA5I5NM.js";
5
5
  import "../chunk-L7MB2LLM.js";
6
6
  import "../chunk-NJDQ2JCP.js";
7
7
  import "../chunk-HG4OONJA.js";
@@ -42,7 +42,7 @@ import {
42
42
  flattenHistory,
43
43
  readSandboxBinaryBytes,
44
44
  statSandboxFileSize
45
- } from "../chunk-WMCROSA4.js";
45
+ } from "../chunk-7DG6GGRN.js";
46
46
  import "../chunk-4LBCTFBP.js";
47
47
  import "../chunk-MCYJON3F.js";
48
48
  import "../chunk-LWSJK546.js";