@adminide-stack/yantra-mobile 12.0.179 → 12.0.181
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/features/computer/computerChat.js +4 -1
- package/lib/features/computer/computerChat.js.map +1 -1
- package/lib/features/webbuilder/WebBuilderExperience.js +205 -31
- package/lib/features/webbuilder/WebBuilderExperience.js.map +1 -1
- package/lib/features/webbuilder/components/GithubConnectSheet.js +159 -0
- package/lib/features/webbuilder/components/GithubConnectSheet.js.map +1 -0
- package/lib/features/webbuilder/components/ProjectSheets.js +3 -1
- package/lib/features/webbuilder/components/ProjectSheets.js.map +1 -1
- package/lib/features/webbuilder/components/ProjectsScreen.js +122 -23
- package/lib/features/webbuilder/components/ProjectsScreen.js.map +1 -1
- package/lib/features/webbuilder/components/ShareSheet.js +144 -4
- package/lib/features/webbuilder/components/ShareSheet.js.map +1 -1
- package/lib/features/webbuilder/components/SiteUploadSheet.js +92 -3
- package/lib/features/webbuilder/components/SiteUploadSheet.js.map +1 -1
- package/lib/features/webbuilder/components/TemplateCard.js +33 -3
- package/lib/features/webbuilder/components/TemplateCard.js.map +1 -1
- package/lib/features/webbuilder/components/TemplatesSheet.js +54 -15
- package/lib/features/webbuilder/components/TemplatesSheet.js.map +1 -1
- package/lib/features/webbuilder/projectsList.js +117 -0
- package/lib/features/webbuilder/projectsList.js.map +1 -0
- package/lib/features/webbuilder/templateCatalog.js +13 -1
- package/lib/features/webbuilder/templateCatalog.js.map +1 -1
- package/lib/features/webbuilder/uploadCard.js +169 -0
- package/lib/features/webbuilder/uploadCard.js.map +1 -0
- package/lib/features/webbuilder/web/github/autoSync.js +1 -1
- package/lib/features/webbuilder/web/github/autoSync.js.map +1 -1
- package/lib/features/webbuilder/web/github/githubConnect.js +179 -0
- package/lib/features/webbuilder/web/github/githubConnect.js.map +1 -0
- package/lib/features/webbuilder/web/github/githubConnectApi.js +102 -0
- package/lib/features/webbuilder/web/github/githubConnectApi.js.map +1 -0
- package/lib/features/webbuilder/web/history/versions.js.map +1 -1
- package/lib/features/webbuilder/web/sharing/roles.js +50 -4
- package/lib/features/webbuilder/web/sharing/roles.js.map +1 -1
- package/lib/features/webbuilder/web/sharing/sharingApi.js +97 -6
- package/lib/features/webbuilder/web/sharing/sharingApi.js.map +1 -1
- package/lib/features/webbuilder/web/state/storageKeys.js +2 -0
- package/lib/features/webbuilder/web/state/storageKeys.js.map +1 -1
- package/lib/features/webbuilder/web/upload/sitePhotos.js +256 -2
- package/lib/features/webbuilder/web/upload/sitePhotos.js.map +1 -1
- package/lib/features/webbuilder/web/webServices.js +13 -1
- package/lib/features/webbuilder/web/webServices.js.map +1 -1
- package/lib/screens/ChatHistory/index.js +2 -2
- package/lib/screens/ChatHistory/index.js.map +1 -1
- package/lib/screens/ComputerNative/useComputerHostChat.js +7 -3
- package/lib/screens/ComputerNative/useComputerHostChat.js.map +1 -1
- package/lib/screens/WebBuilder/nativeWebBuilderRedirect.js +11 -3
- package/lib/screens/WebBuilder/nativeWebBuilderRedirect.js.map +1 -1
- package/lib/screens/WebBuilderNative/index.js +43 -10
- package/lib/screens/WebBuilderNative/index.js.map +1 -1
- package/lib/screens/WebBuilderNative/runningBuilds.js +44 -2
- package/lib/screens/WebBuilderNative/runningBuilds.js.map +1 -1
- package/lib/screens/WebBuilderNative/useConnectorTemplates.js +12 -3
- package/lib/screens/WebBuilderNative/useConnectorTemplates.js.map +1 -1
- package/lib/screens/WebBuilderNative/useWebBuilderHost.js +2 -0
- package/lib/screens/WebBuilderNative/useWebBuilderHost.js.map +1 -1
- package/package.json +2 -2
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"storageKeys.js","sources":["../../../../../src/features/webbuilder/web/state/storageKeys.ts"],"sourcesContent":["/** Every Web Storage key the surface uses; user keys live under `wbu:<uid>:` and go on sign-out or account change. */\n\nexport type KeyValueStore = Pick<Storage, 'getItem' | 'setItem' | 'removeItem'> & {\n readonly length?: number;\n key?(index: number): string | null;\n};\n\nconst USER_PREFIX = 'wbu:';\nexport const CHAT_LANE_STORAGE_PREFIX = 'webbuilder_chat_lane:';\nexport const CHAT_OUTBOX_PREFIX = 'webbuilder_chat_outbox:';\nconst APOLLO_CACHE_PREFIX = 'wb-apollo-cache:';\nexport const CHAT_LANE_NO_CHANNEL = '_';\nexport const CHAT_LANE_ANON = 'anon';\n\nlet owner = '';\n\nfunction segment(v: string | null | undefined, fallback: string): string {\n return (String(v ?? '').trim() || fallback).replace(/:/g, '_').slice(0, 200);\n}\n\n/** The account user keys are scoped to (the token `sub`); '' until a token is known. */\nexport function storageOwner(): string {\n return owner;\n}\n\nexport function setStorageOwner(uid: string | null | undefined): void {\n owner = String(uid ?? '').trim();\n}\n\nfunction userKey(name: string, id?: string | null): string {\n const base = `${USER_PREFIX}${segment(owner, CHAT_LANE_ANON)}:${name}`;\n return id == null ? base : `${base}:${String(id)}`;\n}\n\nexport const REATTACH_WINDOW_MS = 30 * 60_000;\nexport const HANDOFF_TTL_MS = 15 * 60_000;\n\nexport const storageKeys = {\n // Device, localStorage.\n signedOut: () => 'yantra.webbuilder.signedOut.v1',\n storageOwner: () => 'yantra.webbuilder.storageOwner.v1',\n themeMode: () => 'yantra-webbuilder-theme-mode',\n chatPanelWidth: () => 'yantra.webbuilder.chatPanelWidth.v1',\n suggestStyles: () => 'webbuilder.suggestStyles',\n agentModel: () => 'webbuilder.agentModel',\n demoDatabase: () => 'webbuilder.demoDatabaseSlug',\n businessCategory: () => 'webbuilder.businessCategory',\n // Device, sessionStorage (one-shot handoffs and the tab id).\n mobileHandoff: () => 'webbuilder_mobile_handoff',\n remixPending: () => 'webbuilder_remix_pending',\n remixNotice: () => 'webbuilder_remix_notice',\n realtimeSession: () => 'yantra.webbuilder.realtimeSession',\n // User, sessionStorage.\n apolloCache: (graphqlUrl: string, token: string) => `${APOLLO_CACHE_PREFIX}${graphqlUrl}:${token.slice(-16)}`,\n /** The Code view's open folders, per project. */\n codeTreeExpanded: (projectKey: string) => userKey('codeTreeExpanded', projectKey),\n // User, localStorage.\n agentChannel: () => userKey('agentChannel'),\n agentInFlight: () => userKey('agentInFlight'),\n adoptedChannels: () => userKey('adoptedChannels'),\n agentBuilds: () => userKey('agentBuilds'),\n /** Sandboxes a project moved away from -> the project's channel, so an old build link still opens it. */\n sandboxMoves: () => userKey('sandboxMoves'),\n session: () => userKey('session'),\n brandKit: () => userKey('brandKit'),\n lastSiteScore: () => userKey('lastSiteScore'),\n healthNoticeDismissed: (channelId: string) => userKey('healthNoticeDismissed', channelId),\n restoredSandbox: (channelId: string) => userKey('restoredSandbox', channelId),\n githubSyncPending: (channelId: string) => userKey('githubSyncPending', channelId),\n secretsCredentialId: (channelId: string) => userKey('secretsCredentialId', channelId),\n projectKnowledge: (projectKey: string) => userKey('projectKnowledge', projectKey),\n projectTitle: (projectKey: string) => userKey('projectTitle', projectKey),\n projectSettingsMigrated: (projectKey: string) => userKey('projectSettingsMigrated', projectKey),\n projectExtra: (projectKey: string) => userKey('projectExtra', projectKey),\n customDomain: (projectName: string) => userKey('customDomain', projectName),\n unpublished: (projectName: string) => userKey('unpublished', projectName),\n plans: (channelId: string) => userKey('plans', channelId),\n planNotes: (planId: string) => userKey('planNotes', planId),\n /** Plain chat kept per user and channel (the user is the server's id for the lane). */\n chatLane: (userId: string | null | undefined, channelId: string | null | undefined) =>\n `${CHAT_LANE_STORAGE_PREFIX}${segment(userId, CHAT_LANE_ANON)}:${segment(channelId, CHAT_LANE_NO_CHANNEL)}`,\n chatOutbox: (userId: string | null | undefined) => `${CHAT_OUTBOX_PREFIX}${segment(userId, CHAT_LANE_ANON)}`,\n};\n\ntype PerIdKey = {\n [K in keyof typeof storageKeys]: Parameters<(typeof storageKeys)[K]> extends [string] ? K : never;\n}[keyof typeof storageKeys];\n\n/** Unscoped keys from before the registry: read once into the owner's keys, then removed. */\nconst LEGACY_SINGLE: ReadonlyArray<[string, () => string]> = [\n ['yantra.webbuilder.agentChannel.v1', storageKeys.agentChannel],\n ['yantra.webbuilder.agentInFlight.v1', storageKeys.agentInFlight],\n ['yantra.webbuilder.adoptedChannels.v1', storageKeys.adoptedChannels],\n ['yantra.webbuilder.agentBuilds.v1', storageKeys.agentBuilds],\n ['webbuilder_session', storageKeys.session],\n ['yantra.webbuilder.brandKit.v1', storageKeys.brandKit],\n ['yantra.webbuilder.lastSiteScore.v1', storageKeys.lastSiteScore],\n];\n\nconst LEGACY_PER_ID: ReadonlyArray<[string, PerIdKey]> = [\n ['webbuilder.healthNotice.dismissed.', 'healthNoticeDismissed'],\n ['webbuilder-restored-sandbox-', 'restoredSandbox'],\n ['wb:githubSyncPending:', 'githubSyncPending'],\n ['wb:secretsCredentialId:', 'secretsCredentialId'],\n ['wb:projectKnowledge:', 'projectKnowledge'],\n ['wb:projectTitle:', 'projectTitle'],\n ['wb:projectSettingsMigrated:', 'projectSettingsMigrated'],\n ['wb:projectExtra:', 'projectExtra'],\n ['webbuilder-custom-domain-', 'customDomain'],\n ['webbuilder-unpublished-', 'unpublished'],\n ['webbuilder_plans:', 'plans'],\n ['webbuilder_plan_notes:', 'planNotes'],\n];\n\n/** Keys nothing reads or writes any more. */\nconst DEAD_KEYS = ['webbuilder_workflow'];\nconst DEAD_PREFIXES = [\n 'preview-github-repo-',\n 'preview-github-url-',\n 'preview-cloudflare-project-',\n 'preview-cloudflare-domain-',\n];\n\n/** Keys with a lifetime, and where their write time lives in the stored JSON. */\nconst TTL: ReadonlyArray<{ key: () => string; ttlMs: number; stampOf: (v: Record<string, unknown>) => unknown }> = [\n { key: storageKeys.agentInFlight, ttlMs: REATTACH_WINDOW_MS, stampOf: (v) => v.startedAt },\n { key: storageKeys.mobileHandoff, ttlMs: HANDOFF_TTL_MS, stampOf: (v) => v.savedAt },\n { key: storageKeys.remixPending, ttlMs: HANDOFF_TTL_MS, stampOf: (v) => v.savedAt },\n];\n\n/** True when a stored write time is older than `ttlMs`; values without a time never expire. */\nexport function isExpired(savedAt: unknown, ttlMs: number, now: number = Date.now()): boolean {\n return typeof savedAt === 'number' && Number.isFinite(savedAt) && now - savedAt > ttlMs;\n}\n\nfunction allKeys(store: KeyValueStore | null): string[] {\n const out: string[] = [];\n try {\n if (!store || typeof store.key !== 'function' || typeof store.length !== 'number') return out;\n for (let i = 0; i < store.length; i++) {\n const k = store.key(i);\n if (k) out.push(k);\n }\n } catch {\n /* unreadable */\n }\n return out;\n}\n\nfunction get(store: KeyValueStore | null, key: string): string | null {\n try {\n return store?.getItem(key) ?? null;\n } catch {\n return null;\n }\n}\n\nfunction remove(store: KeyValueStore | null, key: string): void {\n try {\n store?.removeItem(key);\n } catch {\n /* storage unavailable */\n }\n}\n\nfunction moveOnce(store: KeyValueStore, from: string, to: string): void {\n const raw = get(store, from);\n if (raw === null) return;\n try {\n if (store.getItem(to) === null) store.setItem(to, raw);\n } catch {\n /* quota: the legacy value is dropped */\n }\n remove(store, from);\n}\n\nfunction isLegacyOrDead(key: string): boolean {\n return (\n LEGACY_SINGLE.some(([k]) => k === key) ||\n DEAD_KEYS.includes(key) ||\n [...LEGACY_PER_ID.map(([p]) => p), ...DEAD_PREFIXES].some((p) => key.startsWith(p))\n );\n}\n\nfunction isUserKey(key: string): boolean {\n return (\n key.startsWith(USER_PREFIX) ||\n key.startsWith(CHAT_LANE_STORAGE_PREFIX) ||\n key.startsWith(CHAT_OUTBOX_PREFIX) ||\n key.startsWith(APOLLO_CACHE_PREFIX)\n );\n}\n\n/** Copy the pre-registry unscoped keys into the current owner's keys and drop the dead ones. */\nexport function migrateLegacyKeys(store: KeyValueStore | null): void {\n if (!store) return;\n for (const [from, to] of LEGACY_SINGLE) moveOnce(store, from, to());\n const keys = allKeys(store);\n for (const [prefix, name] of LEGACY_PER_ID) {\n for (const k of keys) {\n if (k.startsWith(prefix) && k.length > prefix.length)\n moveOnce(store, k, storageKeys[name](k.slice(prefix.length)));\n }\n }\n removeDeadKeys(store);\n}\n\nexport function removeDeadKeys(store: KeyValueStore | null): void {\n for (const k of allKeys(store))\n if (DEAD_KEYS.includes(k) || DEAD_PREFIXES.some((p) => k.startsWith(p))) remove(store, k);\n}\n\n/** Remove every user key (any account), legacy and dead key. Device preferences stay. */\nexport function clearUserStorage(...stores: Array<KeyValueStore | null>): void {\n for (const store of stores) {\n for (const k of allKeys(store)) if (isUserKey(k) || isLegacyOrDead(k)) remove(store, k);\n }\n}\n\n/** Drop keys whose stored write time is past their TTL. */\nexport function pruneExpired(stores: Array<KeyValueStore | null>, now: number = Date.now()): void {\n for (const store of stores) {\n for (const { key, ttlMs, stampOf } of TTL) {\n const raw = get(store, key());\n if (!raw) continue;\n try {\n const v = JSON.parse(raw) as unknown;\n if (v && typeof v === 'object' && isExpired(stampOf(v as Record<string, unknown>), ttlMs, now)) {\n remove(store, key());\n }\n } catch {\n remove(store, key());\n }\n }\n }\n}\n\nexport type OwnerChange = 'same' | 'adopted' | 'changed';\n\n/** A different `sub` than the stored owner wipes every user key; the first owner adopts the legacy keys. */\nexport function adoptStorageOwner(\n sub: string,\n local: KeyValueStore | null,\n session: KeyValueStore | null = null,\n now: number = Date.now(),\n): OwnerChange {\n const uid = String(sub || '').trim();\n setStorageOwner(uid);\n pruneExpired([local, session], now);\n if (!uid) return 'same';\n const prev = get(local, storageKeys.storageOwner());\n let change: OwnerChange = 'same';\n if (prev && prev !== uid) {\n clearUserStorage(local, session);\n change = 'changed';\n } else if (!prev) {\n change = 'adopted';\n }\n if (change !== 'changed') migrateLegacyKeys(local);\n try {\n local?.setItem(storageKeys.storageOwner(), uid);\n } catch {\n /* storage unavailable */\n }\n return change;\n}\n\n/** Sign-out: every user key goes and storage belongs to no one. */\nexport function forgetStorageOwner(local: KeyValueStore | null, session: KeyValueStore | null = null): void {\n clearUserStorage(local, session);\n remove(local, storageKeys.storageOwner());\n setStorageOwner('');\n}\n"],"names":[],"mappings":"AAMA,MAAM,WAAc,GAAA,MAAA;AACb,MAAM,wBAA2B,GAAA;AACjC,MAAM,kBAAqB,GAAA;AAClC,MAAM,mBAAsB,GAAA,kBAA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AAW,CAAA;AAAA,EAC1E,WAAa,EAAA,CAAC,WAAwB,KAAA,OAAA,CAAQ,eAAe,WAAW,CAAA;AAAA,EACxE,KAAO,EAAA,CAAC,SAAsB,KAAA,OAAA,CAAQ,SAAS,SAAS,CAAA;AAAA,EACxD,SAAW,EAAA,CAAC,MAAmB,KAAA,OAAA,CAAQ,aAAa,MAAM,CAAA;AAAA;AAAA,EAE1D,QAAU,EAAA,CAAC,MAAmC,EAAA,SAAA,KAAyC,GAAG,wBAAwB,CAAA,EAAG,OAAQ,CAAA,MAAA,EAAQ,cAAc,CAAC,CAAA,CAAA,EAAI,OAAQ,CAAA,SAAA,EAAW,oBAAoB,CAAC,CAAA,CAAA;AAAA,EAChM,UAAA,EAAY,CAAC,MAAsC,KAAA,CAAA,EAAG,kBAAkB,CAAG,EAAA,OAAA,CAAQ,MAAQ,EAAA,cAAc,CAAC,CAAA;AAC5G"}
|
|
1
|
+
{"version":3,"file":"storageKeys.js","sources":["../../../../../src/features/webbuilder/web/state/storageKeys.ts"],"sourcesContent":["/** Every Web Storage key the surface uses; user keys live under `wbu:<uid>:` and go on sign-out or account change. */\n\nexport type KeyValueStore = Pick<Storage, 'getItem' | 'setItem' | 'removeItem'> & {\n readonly length?: number;\n key?(index: number): string | null;\n};\n\nconst USER_PREFIX = 'wbu:';\nexport const CHAT_LANE_STORAGE_PREFIX = 'webbuilder_chat_lane:';\nexport const CHAT_OUTBOX_PREFIX = 'webbuilder_chat_outbox:';\nconst APOLLO_CACHE_PREFIX = 'wb-apollo-cache:';\nexport const CHAT_LANE_NO_CHANNEL = '_';\nexport const CHAT_LANE_ANON = 'anon';\n\nlet owner = '';\n\nfunction segment(v: string | null | undefined, fallback: string): string {\n return (String(v ?? '').trim() || fallback).replace(/:/g, '_').slice(0, 200);\n}\n\n/** The account user keys are scoped to (the token `sub`); '' until a token is known. */\nexport function storageOwner(): string {\n return owner;\n}\n\nexport function setStorageOwner(uid: string | null | undefined): void {\n owner = String(uid ?? '').trim();\n}\n\nfunction userKey(name: string, id?: string | null): string {\n const base = `${USER_PREFIX}${segment(owner, CHAT_LANE_ANON)}:${name}`;\n return id == null ? base : `${base}:${String(id)}`;\n}\n\nexport const REATTACH_WINDOW_MS = 30 * 60_000;\nexport const HANDOFF_TTL_MS = 15 * 60_000;\n\nexport const storageKeys = {\n // Device, localStorage.\n signedOut: () => 'yantra.webbuilder.signedOut.v1',\n storageOwner: () => 'yantra.webbuilder.storageOwner.v1',\n themeMode: () => 'yantra-webbuilder-theme-mode',\n chatPanelWidth: () => 'yantra.webbuilder.chatPanelWidth.v1',\n suggestStyles: () => 'webbuilder.suggestStyles',\n agentModel: () => 'webbuilder.agentModel',\n demoDatabase: () => 'webbuilder.demoDatabaseSlug',\n businessCategory: () => 'webbuilder.businessCategory',\n // Device, sessionStorage (one-shot handoffs and the tab id).\n mobileHandoff: () => 'webbuilder_mobile_handoff',\n remixPending: () => 'webbuilder_remix_pending',\n remixNotice: () => 'webbuilder_remix_notice',\n realtimeSession: () => 'yantra.webbuilder.realtimeSession',\n // User, sessionStorage.\n apolloCache: (graphqlUrl: string, token: string) => `${APOLLO_CACHE_PREFIX}${graphqlUrl}:${token.slice(-16)}`,\n /** The Code view's open folders, per project. */\n codeTreeExpanded: (projectKey: string) => userKey('codeTreeExpanded', projectKey),\n // User, localStorage.\n agentChannel: () => userKey('agentChannel'),\n agentInFlight: () => userKey('agentInFlight'),\n adoptedChannels: () => userKey('adoptedChannels'),\n agentBuilds: () => userKey('agentBuilds'),\n /** Sandboxes a project moved away from -> the project's channel, so an old build link still opens it. */\n sandboxMoves: () => userKey('sandboxMoves'),\n session: () => userKey('session'),\n brandKit: () => userKey('brandKit'),\n lastSiteScore: () => userKey('lastSiteScore'),\n /** Last good home data (templates, recent builds, credits) per org, shown while the network read runs. */\n homeCache: (name: string, orgId: string) => userKey('homeCache', `${name}:${orgId || '_'}`),\n healthNoticeDismissed: (channelId: string) => userKey('healthNoticeDismissed', channelId),\n restoredSandbox: (channelId: string) => userKey('restoredSandbox', channelId),\n githubSyncPending: (channelId: string) => userKey('githubSyncPending', channelId),\n secretsCredentialId: (channelId: string) => userKey('secretsCredentialId', channelId),\n projectKnowledge: (projectKey: string) => userKey('projectKnowledge', projectKey),\n projectTitle: (projectKey: string) => userKey('projectTitle', projectKey),\n projectSettingsMigrated: (projectKey: string) => userKey('projectSettingsMigrated', projectKey),\n projectExtra: (projectKey: string) => userKey('projectExtra', projectKey),\n customDomain: (projectName: string) => userKey('customDomain', projectName),\n unpublished: (projectName: string) => userKey('unpublished', projectName),\n plans: (channelId: string) => userKey('plans', channelId),\n planNotes: (planId: string) => userKey('planNotes', planId),\n /** Plain chat kept per user and channel (the user is the server's id for the lane). */\n chatLane: (userId: string | null | undefined, channelId: string | null | undefined) =>\n `${CHAT_LANE_STORAGE_PREFIX}${segment(userId, CHAT_LANE_ANON)}:${segment(channelId, CHAT_LANE_NO_CHANNEL)}`,\n chatOutbox: (userId: string | null | undefined) => `${CHAT_OUTBOX_PREFIX}${segment(userId, CHAT_LANE_ANON)}`,\n};\n\ntype PerIdKey = {\n [K in keyof typeof storageKeys]: Parameters<(typeof storageKeys)[K]> extends [string] ? K : never;\n}[keyof typeof storageKeys];\n\n/** Unscoped keys from before the registry: read once into the owner's keys, then removed. */\nconst LEGACY_SINGLE: ReadonlyArray<[string, () => string]> = [\n ['yantra.webbuilder.agentChannel.v1', storageKeys.agentChannel],\n ['yantra.webbuilder.agentInFlight.v1', storageKeys.agentInFlight],\n ['yantra.webbuilder.adoptedChannels.v1', storageKeys.adoptedChannels],\n ['yantra.webbuilder.agentBuilds.v1', storageKeys.agentBuilds],\n ['webbuilder_session', storageKeys.session],\n ['yantra.webbuilder.brandKit.v1', storageKeys.brandKit],\n ['yantra.webbuilder.lastSiteScore.v1', storageKeys.lastSiteScore],\n];\n\nconst LEGACY_PER_ID: ReadonlyArray<[string, PerIdKey]> = [\n ['webbuilder.healthNotice.dismissed.', 'healthNoticeDismissed'],\n ['webbuilder-restored-sandbox-', 'restoredSandbox'],\n ['wb:githubSyncPending:', 'githubSyncPending'],\n ['wb:secretsCredentialId:', 'secretsCredentialId'],\n ['wb:projectKnowledge:', 'projectKnowledge'],\n ['wb:projectTitle:', 'projectTitle'],\n ['wb:projectSettingsMigrated:', 'projectSettingsMigrated'],\n ['wb:projectExtra:', 'projectExtra'],\n ['webbuilder-custom-domain-', 'customDomain'],\n ['webbuilder-unpublished-', 'unpublished'],\n ['webbuilder_plans:', 'plans'],\n ['webbuilder_plan_notes:', 'planNotes'],\n];\n\n/** Keys nothing reads or writes any more. */\nconst DEAD_KEYS = ['webbuilder_workflow'];\nconst DEAD_PREFIXES = [\n 'preview-github-repo-',\n 'preview-github-url-',\n 'preview-cloudflare-project-',\n 'preview-cloudflare-domain-',\n];\n\n/** Keys with a lifetime, and where their write time lives in the stored JSON. */\nconst TTL: ReadonlyArray<{ key: () => string; ttlMs: number; stampOf: (v: Record<string, unknown>) => unknown }> = [\n { key: storageKeys.agentInFlight, ttlMs: REATTACH_WINDOW_MS, stampOf: (v) => v.startedAt },\n { key: storageKeys.mobileHandoff, ttlMs: HANDOFF_TTL_MS, stampOf: (v) => v.savedAt },\n { key: storageKeys.remixPending, ttlMs: HANDOFF_TTL_MS, stampOf: (v) => v.savedAt },\n];\n\n/** True when a stored write time is older than `ttlMs`; values without a time never expire. */\nexport function isExpired(savedAt: unknown, ttlMs: number, now: number = Date.now()): boolean {\n return typeof savedAt === 'number' && Number.isFinite(savedAt) && now - savedAt > ttlMs;\n}\n\nfunction allKeys(store: KeyValueStore | null): string[] {\n const out: string[] = [];\n try {\n if (!store || typeof store.key !== 'function' || typeof store.length !== 'number') return out;\n for (let i = 0; i < store.length; i++) {\n const k = store.key(i);\n if (k) out.push(k);\n }\n } catch {\n /* unreadable */\n }\n return out;\n}\n\nfunction get(store: KeyValueStore | null, key: string): string | null {\n try {\n return store?.getItem(key) ?? null;\n } catch {\n return null;\n }\n}\n\nfunction remove(store: KeyValueStore | null, key: string): void {\n try {\n store?.removeItem(key);\n } catch {\n /* storage unavailable */\n }\n}\n\nfunction moveOnce(store: KeyValueStore, from: string, to: string): void {\n const raw = get(store, from);\n if (raw === null) return;\n try {\n if (store.getItem(to) === null) store.setItem(to, raw);\n } catch {\n /* quota: the legacy value is dropped */\n }\n remove(store, from);\n}\n\nfunction isLegacyOrDead(key: string): boolean {\n return (\n LEGACY_SINGLE.some(([k]) => k === key) ||\n DEAD_KEYS.includes(key) ||\n [...LEGACY_PER_ID.map(([p]) => p), ...DEAD_PREFIXES].some((p) => key.startsWith(p))\n );\n}\n\nfunction isUserKey(key: string): boolean {\n return (\n key.startsWith(USER_PREFIX) ||\n key.startsWith(CHAT_LANE_STORAGE_PREFIX) ||\n key.startsWith(CHAT_OUTBOX_PREFIX) ||\n key.startsWith(APOLLO_CACHE_PREFIX)\n );\n}\n\n/** Copy the pre-registry unscoped keys into the current owner's keys and drop the dead ones. */\nexport function migrateLegacyKeys(store: KeyValueStore | null): void {\n if (!store) return;\n for (const [from, to] of LEGACY_SINGLE) moveOnce(store, from, to());\n const keys = allKeys(store);\n for (const [prefix, name] of LEGACY_PER_ID) {\n for (const k of keys) {\n if (k.startsWith(prefix) && k.length > prefix.length)\n moveOnce(store, k, storageKeys[name](k.slice(prefix.length)));\n }\n }\n removeDeadKeys(store);\n}\n\nexport function removeDeadKeys(store: KeyValueStore | null): void {\n for (const k of allKeys(store))\n if (DEAD_KEYS.includes(k) || DEAD_PREFIXES.some((p) => k.startsWith(p))) remove(store, k);\n}\n\n/** Remove every user key (any account), legacy and dead key. Device preferences stay. */\nexport function clearUserStorage(...stores: Array<KeyValueStore | null>): void {\n for (const store of stores) {\n for (const k of allKeys(store)) if (isUserKey(k) || isLegacyOrDead(k)) remove(store, k);\n }\n}\n\n/** Drop keys whose stored write time is past their TTL. */\nexport function pruneExpired(stores: Array<KeyValueStore | null>, now: number = Date.now()): void {\n for (const store of stores) {\n for (const { key, ttlMs, stampOf } of TTL) {\n const raw = get(store, key());\n if (!raw) continue;\n try {\n const v = JSON.parse(raw) as unknown;\n if (v && typeof v === 'object' && isExpired(stampOf(v as Record<string, unknown>), ttlMs, now)) {\n remove(store, key());\n }\n } catch {\n remove(store, key());\n }\n }\n }\n}\n\nexport type OwnerChange = 'same' | 'adopted' | 'changed';\n\n/** A different `sub` than the stored owner wipes every user key; the first owner adopts the legacy keys. */\nexport function adoptStorageOwner(\n sub: string,\n local: KeyValueStore | null,\n session: KeyValueStore | null = null,\n now: number = Date.now(),\n): OwnerChange {\n const uid = String(sub || '').trim();\n setStorageOwner(uid);\n pruneExpired([local, session], now);\n if (!uid) return 'same';\n const prev = get(local, storageKeys.storageOwner());\n let change: OwnerChange = 'same';\n if (prev && prev !== uid) {\n clearUserStorage(local, session);\n change = 'changed';\n } else if (!prev) {\n change = 'adopted';\n }\n if (change !== 'changed') migrateLegacyKeys(local);\n try {\n local?.setItem(storageKeys.storageOwner(), uid);\n } catch {\n /* storage unavailable */\n }\n return change;\n}\n\n/** Sign-out: every user key goes and storage belongs to no one. */\nexport function forgetStorageOwner(local: KeyValueStore | null, session: KeyValueStore | null = null): void {\n clearUserStorage(local, session);\n remove(local, storageKeys.storageOwner());\n setStorageOwner('');\n}\n"],"names":[],"mappings":"AAMA,MAAM,WAAc,GAAA,MAAA;AACb,MAAM,wBAA2B,GAAA;AACjC,MAAM,kBAAqB,GAAA;AAClC,MAAM,mBAAsB,GAAA,kBAAA;AACrB,MAAM,oBAAuB,GAAA;AAC7B,MAAM,cAAiB,GAAA;AAC9B,IAAI,KAAQ,GAAA,EAAA;AACZ,SAAS,OAAA,CAAQ,GAA8B,QAA0B,EAAA;AACvE,EAAA,OAAA,CAAQ,MAAO,CAAA,CAAA,IAAA,IAAA,GAAA,CAAA,GAAK,EAAE,CAAA,CAAE,IAAK,EAAA,IAAK,QAAU,EAAA,OAAA,CAAQ,IAAM,EAAA,GAAG,CAAE,CAAA,KAAA,CAAM,GAAG,GAAG,CAAA;AAC7E;AASA,SAAS,OAAA,C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AmB,KAAA,OAAA,CAAQ,aAAa,MAAM,CAAA;AAAA;AAAA,EAE1D,QAAU,EAAA,CAAC,MAAmC,EAAA,SAAA,KAAyC,GAAG,wBAAwB,CAAA,EAAG,OAAQ,CAAA,MAAA,EAAQ,cAAc,CAAC,CAAA,CAAA,EAAI,OAAQ,CAAA,SAAA,EAAW,oBAAoB,CAAC,CAAA,CAAA;AAAA,EAChM,UAAA,EAAY,CAAC,MAAsC,KAAA,CAAA,EAAG,kBAAkB,CAAG,EAAA,OAAA,CAAQ,MAAQ,EAAA,cAAc,CAAC,CAAA;AAC5G"}
|
|
@@ -1,5 +1,37 @@
|
|
|
1
|
-
import {stripAskUser}from'../../../chat/askUser.js';
|
|
1
|
+
import {stripAskUser}from'../../../chat/askUser.js';import {isGenericTitle}from'../../buildFragments.js';var __defProp = Object.defineProperty;
|
|
2
|
+
var __defProps = Object.defineProperties;
|
|
3
|
+
var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
|
|
4
|
+
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __propIsEnum = Object.prototype.propertyIsEnumerable;
|
|
7
|
+
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
|
|
8
|
+
var __spreadValues = (a, b) => {
|
|
9
|
+
for (var prop in b || (b = {}))
|
|
10
|
+
if (__hasOwnProp.call(b, prop))
|
|
11
|
+
__defNormalProp(a, prop, b[prop]);
|
|
12
|
+
if (__getOwnPropSymbols)
|
|
13
|
+
for (var prop of __getOwnPropSymbols(b)) {
|
|
14
|
+
if (__propIsEnum.call(b, prop))
|
|
15
|
+
__defNormalProp(a, prop, b[prop]);
|
|
16
|
+
}
|
|
17
|
+
return a;
|
|
18
|
+
};
|
|
19
|
+
var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
|
|
20
|
+
var __objRest = (source, exclude) => {
|
|
21
|
+
var target = {};
|
|
22
|
+
for (var prop in source)
|
|
23
|
+
if (__hasOwnProp.call(source, prop) && exclude.indexOf(prop) < 0)
|
|
24
|
+
target[prop] = source[prop];
|
|
25
|
+
if (source != null && __getOwnPropSymbols)
|
|
26
|
+
for (var prop of __getOwnPropSymbols(source)) {
|
|
27
|
+
if (exclude.indexOf(prop) < 0 && __propIsEnum.call(source, prop))
|
|
28
|
+
target[prop] = source[prop];
|
|
29
|
+
}
|
|
30
|
+
return target;
|
|
31
|
+
};
|
|
32
|
+
const UPLOAD_PARAM = "upload";
|
|
2
33
|
const BUILD_PARAM = "build";
|
|
34
|
+
const CARD_PARAMS = ["ys", "reply"];
|
|
3
35
|
function queryOf(url) {
|
|
4
36
|
const raw = String(url != null ? url : "");
|
|
5
37
|
const q = raw.indexOf("?");
|
|
@@ -99,4 +131,226 @@ function replySummary(reply) {
|
|
|
99
131
|
}
|
|
100
132
|
function replyAsks(reply) {
|
|
101
133
|
return /\[ASK_USER\]/i.test(String(reply != null ? reply : ""));
|
|
102
|
-
}
|
|
134
|
+
}
|
|
135
|
+
function chatNoticeKind(id) {
|
|
136
|
+
if (!id) return null;
|
|
137
|
+
if (id.startsWith("error-")) return "error";
|
|
138
|
+
if (id.startsWith("stopped-")) return "stopped";
|
|
139
|
+
if (id.startsWith("incomplete-")) return "incomplete";
|
|
140
|
+
if (id.startsWith("note-")) return "note";
|
|
141
|
+
return null;
|
|
142
|
+
}
|
|
143
|
+
function cardParams(url) {
|
|
144
|
+
const q = queryOf(url);
|
|
145
|
+
return {
|
|
146
|
+
snapshotId: q.get(CARD_PARAMS[0]) || null,
|
|
147
|
+
reply: q.get(CARD_PARAMS[1])
|
|
148
|
+
};
|
|
149
|
+
}
|
|
150
|
+
const WEBBUILDER_SURFACE = "webbuilder";
|
|
151
|
+
const SITE_UPLOAD_WIDGET = "webbuilder-upload";
|
|
152
|
+
const SITE_REPLY_MAX_BYTES = 2048;
|
|
153
|
+
const MAX_REPLY_SITE = 120;
|
|
154
|
+
const MAX_REPLY_NOTE = 300;
|
|
155
|
+
const MAX_REPLY_SUMMARY = 600;
|
|
156
|
+
const MAX_REPLY_PHOTOS = 10;
|
|
157
|
+
const MAX_REPLY_VIDEOS = 3;
|
|
158
|
+
const BUILD_KEY_RE = /^[A-Za-z0-9][A-Za-z0-9_.:-]{0,159}$/;
|
|
159
|
+
const REQUEST_ID_RE = /^[A-Za-z0-9_-]{8,40}$/;
|
|
160
|
+
const LONGEST_REQUEST_ID = "x".repeat(40);
|
|
161
|
+
function isSiteBuildKey(value) {
|
|
162
|
+
return typeof value === "string" && BUILD_KEY_RE.test(value);
|
|
163
|
+
}
|
|
164
|
+
function cardOpensUpload(snapshot) {
|
|
165
|
+
if (!snapshot) return false;
|
|
166
|
+
const isUpload = (w) => typeof (w == null ? void 0 : w.propsComponent) === "string" && w.propsComponent.toLowerCase() === SITE_UPLOAD_WIDGET;
|
|
167
|
+
return isUpload(snapshot.widget) || Array.isArray(snapshot.widgets) && isUpload(snapshot.widgets[0]);
|
|
168
|
+
}
|
|
169
|
+
function cardBuildKey(attachment) {
|
|
170
|
+
if (!attachment || typeof attachment !== "object") return null;
|
|
171
|
+
const build = attachment.build;
|
|
172
|
+
const key = typeof build === "string" ? build.trim() : "";
|
|
173
|
+
return isSiteBuildKey(key) ? key : null;
|
|
174
|
+
}
|
|
175
|
+
function canAnswerChat(state) {
|
|
176
|
+
if (!state.snapshotId || state.replyParam === "0" || state.canReply !== true) return false;
|
|
177
|
+
return state.surface == null || state.surface === WEBBUILDER_SURFACE;
|
|
178
|
+
}
|
|
179
|
+
function chatToAnswer(state) {
|
|
180
|
+
if (state.snapshotId) return canAnswerChat(state) ? "card" : null;
|
|
181
|
+
return null;
|
|
182
|
+
}
|
|
183
|
+
function mintReplyId() {
|
|
184
|
+
const ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
|
|
185
|
+
const bytes = new Uint8Array(16);
|
|
186
|
+
const random = globalThis.crypto;
|
|
187
|
+
if (random == null ? void 0 : random.getRandomValues) random.getRandomValues(bytes);
|
|
188
|
+
else for (let i = 0; i < bytes.length; i++) bytes[i] = Math.floor(Math.random() * 256);
|
|
189
|
+
let id = "";
|
|
190
|
+
for (const b of bytes) id += ALPHABET[b & 63];
|
|
191
|
+
return id;
|
|
192
|
+
}
|
|
193
|
+
function isReplyId(value) {
|
|
194
|
+
return typeof value === "string" && REQUEST_ID_RE.test(value);
|
|
195
|
+
}
|
|
196
|
+
const LINE_BREAKING_RE = /[\u0000-\u001f\u007f-\u009f\u2028\u2029]+/g;
|
|
197
|
+
const INVISIBLE_RE = /[\u061c\u180e\u200b-\u200f\u202a-\u202e\u2060-\u2069\ufeff\ufe00-\ufe0f\u{e0000}-\u{e007f}\u{e0100}-\u{e01ef}]+/gu;
|
|
198
|
+
const MARKUP_RE = /[[\]<>`]+/g;
|
|
199
|
+
function nfkc(text) {
|
|
200
|
+
try {
|
|
201
|
+
return text.normalize("NFKC");
|
|
202
|
+
} catch (e) {
|
|
203
|
+
return text;
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
function cleanLine(value) {
|
|
207
|
+
if (typeof value !== "string") return "";
|
|
208
|
+
return nfkc(value).replace(LINE_BREAKING_RE, " ").replace(INVISIBLE_RE, "").replace(MARKUP_RE, "").replace(/\s+/g, " ").trim();
|
|
209
|
+
}
|
|
210
|
+
function cleanReplyText(value, max) {
|
|
211
|
+
return Array.from(cleanLine(value)).slice(0, max).join("").trim();
|
|
212
|
+
}
|
|
213
|
+
const LINK_RE = /https?:\/\/[^\s<>"'`]+/gi;
|
|
214
|
+
const HAS_LINK_RE = /https?:\/\//i;
|
|
215
|
+
const LINK_MARK = "";
|
|
216
|
+
const POINTED_AT_LINK_RE = (
|
|
217
|
+
// eslint-disable-next-line no-control-regex
|
|
218
|
+
/(?:\b(?:live\s+)?preview|\bhere|\blink|\bat|\bon|\bsee|\bvia|\bvisit)?[ \t]*:?[ \t]*\u0001/gi
|
|
219
|
+
);
|
|
220
|
+
const TRAILING_LINK_PUNCTUATION_RE = /[.,;:!?)\]]+$/;
|
|
221
|
+
const HAS_WORD_RE = (() => {
|
|
222
|
+
try {
|
|
223
|
+
return new RegExp("[\\p{L}\\p{N}]", "u");
|
|
224
|
+
} catch (e) {
|
|
225
|
+
return /[^\s.,;:!?()[\]{}'"`\-–—…]/;
|
|
226
|
+
}
|
|
227
|
+
})();
|
|
228
|
+
function withoutLinks(text) {
|
|
229
|
+
if (!HAS_LINK_RE.test(text)) return text;
|
|
230
|
+
const kept = text.replace(LINK_RE, (link) => {
|
|
231
|
+
var _a, _b;
|
|
232
|
+
return LINK_MARK + ((_b = (_a = link.match(TRAILING_LINK_PUNCTUATION_RE)) == null ? void 0 : _a[0]) != null ? _b : "");
|
|
233
|
+
}).replace(POINTED_AT_LINK_RE, " ").replace(/\(\s*(?:live\s+)?(?:preview)?\s*\)|\[\s*\]/gi, "").replace(/[ \t]+([.,;:!?)])/g, "$1").replace(/[,;:]+(?=[ \t]*(?:[.,;:!?)]|$))/g, "").replace(/([.!?])(?:[ \t]*[.,;:])+/g, "$1").replace(/[ \t]{2,}/g, " ").trim();
|
|
234
|
+
return HAS_WORD_RE.test(kept) ? kept : "";
|
|
235
|
+
}
|
|
236
|
+
function cleanSummary(value, max) {
|
|
237
|
+
const text = cleanLine(typeof value === "string" ? withoutLinks(value) : value);
|
|
238
|
+
const chars = Array.from(text);
|
|
239
|
+
if (chars.length <= max) return text;
|
|
240
|
+
const head = chars.slice(0, max - 1).join("");
|
|
241
|
+
const sentence = Math.max(head.lastIndexOf(". "), head.lastIndexOf("! "), head.lastIndexOf("? "));
|
|
242
|
+
if (sentence >= head.length / 2) return head.slice(0, sentence + 1);
|
|
243
|
+
const space = head.lastIndexOf(" ");
|
|
244
|
+
return `${(space > 0 ? head.slice(0, space) : head).trimEnd()}\u2026`;
|
|
245
|
+
}
|
|
246
|
+
function noteAsSentences(note) {
|
|
247
|
+
if (typeof note !== "string") return "";
|
|
248
|
+
const lines = note.split(/\r\n|\r|\n|\u2028|\u2029/).map((line) => line.trim()).filter(Boolean);
|
|
249
|
+
return lines.map((line, i) => i < lines.length - 1 && !/[.!?:;,]$/.test(line) ? `${line}.` : line).join(" ");
|
|
250
|
+
}
|
|
251
|
+
const count = (value, max) => typeof value === "number" && Number.isFinite(value) ? Math.min(max, Math.max(0, Math.floor(value))) : 0;
|
|
252
|
+
const byteLength = (text) => {
|
|
253
|
+
var _a;
|
|
254
|
+
let bytes = 0;
|
|
255
|
+
for (const ch of text) {
|
|
256
|
+
const cp = (_a = ch.codePointAt(0)) != null ? _a : 0;
|
|
257
|
+
bytes += cp < 128 ? 1 : cp < 2048 ? 2 : cp < 65536 ? 3 : 4;
|
|
258
|
+
}
|
|
259
|
+
return bytes;
|
|
260
|
+
};
|
|
261
|
+
function replyFits(reply, requestId) {
|
|
262
|
+
return byteLength(`[SURFACE_REPLY:${WEBBUILDER_SURFACE}:${requestId}] ${JSON.stringify(reply)}`) <= SITE_REPLY_MAX_BYTES;
|
|
263
|
+
}
|
|
264
|
+
function siteMediaReply(input, requestId = LONGEST_REQUEST_ID) {
|
|
265
|
+
const build = typeof input.build === "string" ? input.build.trim() : "";
|
|
266
|
+
const status = input.status;
|
|
267
|
+
if (!isSiteBuildKey(build) || !isReplyId(requestId)) return null;
|
|
268
|
+
if (status !== "done" && status !== "working" && status !== "waiting") return null;
|
|
269
|
+
const site = isGenericTitle(input.title) ? "" : cleanReplyText(input.title, MAX_REPLY_SITE);
|
|
270
|
+
const note = cleanReplyText(noteAsSentences(input.note), MAX_REPLY_NOTE);
|
|
271
|
+
const summary = status === "done" ? cleanSummary(input.summary, MAX_REPLY_SUMMARY) : "";
|
|
272
|
+
const reply = __spreadValues(__spreadValues(__spreadProps(__spreadValues({
|
|
273
|
+
kind: "site-media",
|
|
274
|
+
status,
|
|
275
|
+
build
|
|
276
|
+
}, site ? {
|
|
277
|
+
site
|
|
278
|
+
} : {}), {
|
|
279
|
+
photos: count(input.photos, MAX_REPLY_PHOTOS),
|
|
280
|
+
videos: count(input.videos, MAX_REPLY_VIDEOS)
|
|
281
|
+
}), note ? {
|
|
282
|
+
note
|
|
283
|
+
} : {}), summary ? {
|
|
284
|
+
summary
|
|
285
|
+
} : {});
|
|
286
|
+
if (!reply.photos && !reply.videos && !reply.note) return null;
|
|
287
|
+
if (replyFits(reply, requestId)) return reply;
|
|
288
|
+
delete reply.summary;
|
|
289
|
+
if (replyFits(reply, requestId)) return reply;
|
|
290
|
+
if (reply.note) {
|
|
291
|
+
const chars = Array.from(reply.note);
|
|
292
|
+
const withNote = (n) => {
|
|
293
|
+
const kept = chars.slice(0, n).join("").trimEnd();
|
|
294
|
+
const _a = reply, {
|
|
295
|
+
note: _dropped
|
|
296
|
+
} = _a, rest = __objRest(_a, [
|
|
297
|
+
"note"
|
|
298
|
+
]);
|
|
299
|
+
return kept ? __spreadProps(__spreadValues({}, rest), {
|
|
300
|
+
note: kept
|
|
301
|
+
}) : rest;
|
|
302
|
+
};
|
|
303
|
+
let lo = 0;
|
|
304
|
+
let hi = chars.length;
|
|
305
|
+
while (lo < hi) {
|
|
306
|
+
const mid = Math.ceil((lo + hi) / 2);
|
|
307
|
+
if (replyFits(withNote(mid), requestId)) lo = mid;
|
|
308
|
+
else hi = mid - 1;
|
|
309
|
+
}
|
|
310
|
+
const fitted = withNote(lo);
|
|
311
|
+
return replyFits(fitted, requestId) ? fitted : null;
|
|
312
|
+
}
|
|
313
|
+
return null;
|
|
314
|
+
}
|
|
315
|
+
function newReplyBudget(requestId = mintReplyId()) {
|
|
316
|
+
return {
|
|
317
|
+
requestId,
|
|
318
|
+
early: false,
|
|
319
|
+
done: false
|
|
320
|
+
};
|
|
321
|
+
}
|
|
322
|
+
function takeReply(budget, status, mint = mintReplyId) {
|
|
323
|
+
if (budget.done) return null;
|
|
324
|
+
if (status === "done") {
|
|
325
|
+
return {
|
|
326
|
+
requestId: budget.early ? mint() : budget.requestId,
|
|
327
|
+
budget: __spreadProps(__spreadValues({}, budget), {
|
|
328
|
+
done: true
|
|
329
|
+
})
|
|
330
|
+
};
|
|
331
|
+
}
|
|
332
|
+
if (budget.early) return null;
|
|
333
|
+
return {
|
|
334
|
+
requestId: budget.requestId,
|
|
335
|
+
budget: __spreadProps(__spreadValues({}, budget), {
|
|
336
|
+
early: true
|
|
337
|
+
})
|
|
338
|
+
};
|
|
339
|
+
}
|
|
340
|
+
function leavingReply(state) {
|
|
341
|
+
if (state.step === "adding") return "working";
|
|
342
|
+
if (state.step === "finished" && state.question) return "waiting";
|
|
343
|
+
return null;
|
|
344
|
+
}
|
|
345
|
+
function sendFinishedWell(state) {
|
|
346
|
+
if (state.failed || state.question) return false;
|
|
347
|
+
let answer = null;
|
|
348
|
+
for (let i = state.messages.length - 1; i >= 0; i--) {
|
|
349
|
+
const m = state.messages[i];
|
|
350
|
+
if (m.role === "user") break;
|
|
351
|
+
const notice = chatNoticeKind(m.id);
|
|
352
|
+
if (notice === "error" || notice === "stopped" || notice === "incomplete") return false;
|
|
353
|
+
if (!answer && m.role === "assistant" && !notice) answer = m;
|
|
354
|
+
}
|
|
355
|
+
return Boolean(answer && replySummary(answer.content));
|
|
356
|
+
}export{SITE_REPLY_MAX_BYTES,SITE_SUGGESTIONS,SITE_UPLOAD_WIDGET,UPLOAD_LINK_MAX_PAGES,WEBBUILDER_SURFACE,canAnswerChat,canSend,cardBuildKey,cardOpensUpload,cardParams,chatToAnswer,cleanReplyText,isReplyId,isSiteBuildKey,isUploadLink,leavingReply,mintReplyId,newReplyBudget,replyAsks,replySummary,sendFinishedWell,sendLabel,siteForLink,siteMediaMessage,siteMediaNote,siteMediaReply,takeReply,uploadBuildKey,uploadStep,withSuggestion};//# sourceMappingURL=sitePhotos.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sitePhotos.js","sources":["../../../../../src/features/webbuilder/web/upload/sitePhotos.ts"],"sourcesContent":["/**\n * The upload page (web 0.18-0.19.3, `upload/sitePhotos.ts`): a link that opens straight onto \"add to my site\".\n *\n * Someone who asks for more photos, or to sync with Facebook, is sent here: from the chat, or from a text thread\n * on their phone. They pick photos, and can say what they want done: where these go, a change to the site, or to\n * post them to Facebook and Instagram. What they pick goes into the site like any other file. Pure.\n *\n * Native keeps the parts that are not the browser's: the link (`?upload=1&build=`), the words, the steps. Videos\n * need the web's file upload service, which this app does not have, so a phone sends photos here.\n */\nimport { stripAskUser } from '../../../chat/askUser';\n\nconst UPLOAD_PARAM = 'upload';\nconst BUILD_PARAM = 'build';\n\nfunction queryOf(url: string | null | undefined): URLSearchParams {\n const raw = String(url ?? '');\n const q = raw.indexOf('?');\n if (q < 0) return new URLSearchParams('');\n const hash = raw.indexOf('#', q);\n return new URLSearchParams(raw.slice(q + 1, hash < 0 ? undefined : hash));\n}\n\n/** This address is the photo page. */\nexport function isUploadLink(url: string | null | undefined): boolean {\n return queryOf(url).get(UPLOAD_PARAM) === '1';\n}\n\n/** The site the link names, when it names one. */\nexport function uploadBuildKey(url: string | null | undefined): string | null {\n return queryOf(url).get(BUILD_PARAM) || null;\n}\n\nexport interface MediaCounts {\n photos: number;\n videos: number;\n}\n\nfunction countWords({ photos, videos }: MediaCounts): string {\n const parts: string[] = [];\n if (photos) parts.push(`${photos} ${photos === 1 ? 'photo' : 'photos'}`);\n if (videos) parts.push(`${videos} ${videos === 1 ? 'video' : 'videos'}`);\n return parts.join(' and ');\n}\n\n/** What the person is shown as having asked: their own words when they wrote any. */\nexport function siteMediaMessage(title: string, counts: MediaCounts, note: string): string {\n const own = note.trim();\n if (own) return own;\n if (counts.photos + counts.videos === 1) return `Add this ${counts.photos ? 'photo' : 'video'} to ${title}.`;\n return `Add these ${countWords(counts)} to ${title}.`;\n}\n\n/** For the agent only: what these files are, so none is mistaken for a design to copy. Null with no files. */\nexport function siteMediaNote({ photos, videos }: MediaCounts): string | null {\n return photos + videos ? `[Site media] photos=${photos} videos=${videos}` : null;\n}\n\n/** What the send button says. */\nexport function sendLabel(counts: MediaCounts): string {\n return counts.photos + counts.videos ? `Send ${countWords(counts)}` : 'Send';\n}\n\n/** One tap fills in the common asks; anything else is typed. */\nexport const SITE_SUGGESTIONS = [\n 'Post these to Facebook and Instagram',\n 'Put these on the home page',\n 'Suggest how to improve my site',\n] as const;\n\n/** A suggestion joins what is already written, once. */\nexport function withSuggestion(note: string, suggestion: string): string {\n const current = note.trim();\n if (!current) return suggestion;\n return current.includes(suggestion) ? note : `${current}\\n${suggestion}`;\n}\n\n/** Something to send, and nothing still on its way up. */\nexport function canSend(state: { media: number; note: string; busy: boolean }): boolean {\n return !state.busy && (state.media > 0 || state.note.trim().length > 0);\n}\n\nexport type SiteLinkState = 'ready' | 'choose' | 'wait' | 'load-more' | 'missing' | 'none';\n\n/** Board pages a link may page through looking for its site before it gives up (web BUILD_LINK_MAX_PAGES). */\nexport const UPLOAD_LINK_MAX_PAGES = 5;\n\n/**\n * Which site the page is for, and what it does next. A link names its site by its chat (the native board knows\n * sites by chat), and the board is paged through before the site counts as missing. A link to a site this\n * account cannot find never falls back to another one: the files would land on the wrong site.\n */\nexport function siteForLink<T extends { channelId: string }>(\n sites: readonly T[],\n linked: string | null,\n board: { loading: boolean; pagesSettled: number; hasMore: boolean; error: boolean },\n): { site: T | null; choices: T[]; state: SiteLinkState } {\n const choices = sites.filter((s) => s.channelId);\n if (linked) {\n const site = choices.find((s) => s.channelId === linked) ?? null;\n if (site) return { site, choices, state: 'ready' };\n if (board.loading || board.error) return { site: null, choices, state: 'wait' };\n if (board.hasMore && board.pagesSettled < UPLOAD_LINK_MAX_PAGES)\n return { site: null, choices, state: 'load-more' };\n return { site: null, choices, state: 'missing' };\n }\n if (board.loading && !choices.length) return { site: null, choices, state: 'wait' };\n if (choices.length === 1) return { site: choices[0], choices, state: 'ready' };\n return { site: null, choices, state: choices.length ? 'choose' : 'none' };\n}\n\nexport type UploadStep = 'picking' | 'adding' | 'finished';\n\n/**\n * Where the page is. `sent` is set when the turn went out and `sawBusy` once the agent was seen working: right\n * after a send it may not be busy yet, which is not finished.\n */\nexport function uploadStep(state: { sent: boolean; sawBusy: boolean; busy: boolean }): UploadStep {\n if (!state.sent) return 'picking';\n return state.sawBusy && !state.busy ? 'finished' : 'adding';\n}\n\n/** The agent's own words about what it did, as plain text, without its follow-up prompts. */\nexport function replySummary(reply: string | null | undefined): string | null {\n const text = stripAskUser(String(reply ?? ''))\n .replace(/\\n\\s*\\**\\s*Next steps?\\s*\\**\\s*:[\\s\\S]*$/i, '')\n .replace(/\\[([^\\]]+)\\]\\([^)]*\\)/g, '$1')\n .replace(/\\*\\*|__|`/g, '')\n .trim();\n return text || null;\n}\n\n/** The reply asks the person something (an ASK_USER card). */\nexport function replyAsks(reply: string | null | undefined): boolean {\n return /\\[ASK_USER\\]/i.test(String(reply ?? ''));\n}\n"],"names":[],"mappings":"oDAWA,MAAM,YAAe,GAAA,QAAA;AACrB,MAAM,WAAc,GAAA,OAAA;AACpB,SAAS,QAAQ,GAAiD,EAAA;AAChE,EAAM,MAAA,GAAA,GAAM,MAAO,CAAA,GAAA,IAAA,IAAA,GAAA,GAAA,GAAO,EAAE,CAAA;AAC5B,EAAM,MAAA,CAAA,GAAI,GAAI,CAAA,OAAA,CAAQ,GAAG,CAAA;AACzB,EAAA,IAAI,CAAI,GAAA,CAAA,EAAU,OAAA,IAAI,gBAAgB,EAAE,CAAA;AACxC,EAAA,MAAM,IAAO,GAAA,GAAA,CAAI,OAAQ,CAAA,GAAA,EAAK,CAAC,CAAA;AAC/B,EAAO,OAAA,IAAI,eAAgB,CAAA,GAAA,CAAI,KAAM,CAAA,CAAA,GAAI,GAAG,IAAO,GAAA,CAAA,GAAI,MAAY,GAAA,IAAI,CAAC,CAAA;AAC1E;AAGO,SAAS,aAAa,GAAyC,EAAA;AACpE,EAAA,OAAO,OAAQ,CAAA,GAAG,CAAE,CAAA,GAAA,CAAI,YAAY,CAAM,KAAA,GAAA;AAC5C;AAGO,SAAS,eAAe,GAA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itePhotos.ts"],"sourcesContent":["/**\n * The upload page (web 0.18-0.19.3, `upload/sitePhotos.ts`): a link that opens straight onto \"add to my site\".\n *\n * Someone who asks for more photos, or to sync with Facebook, is sent here: from the chat, or from a text thread\n * on their phone. They pick photos, and can say what they want done: where these go, a change to the site, or to\n * post them to Facebook and Instagram. What they pick goes into the site like any other file. Pure.\n *\n * Native keeps the parts that are not the browser's: the link (`?upload=1&build=`), the words, the steps. Videos\n * need the web's file upload service, which this app does not have, so a phone sends photos here.\n */\nimport { stripAskUser } from '../../../chat/askUser';\nimport { isGenericTitle as isGenericArtifactTitle } from '../../buildFragments';\n\nconst UPLOAD_PARAM = 'upload';\nconst BUILD_PARAM = 'build';\n/** A text thread's card: its snapshot id (the kit's `SURFACE_SNAPSHOT_PARAM`), and `reply=0` (see below). */\nconst CARD_PARAMS = ['ys', 'reply'] as const;\n\nfunction queryOf(url: string | null | undefined): URLSearchParams {\n const raw = String(url ?? '');\n const q = raw.indexOf('?');\n if (q < 0) return new URLSearchParams('');\n const hash = raw.indexOf('#', q);\n return new URLSearchParams(raw.slice(q + 1, hash < 0 ? undefined : hash));\n}\n\n/** This address is the photo page. */\nexport function isUploadLink(url: string | null | undefined): boolean {\n return queryOf(url).get(UPLOAD_PARAM) === '1';\n}\n\n/** The site the link names, when it names one. */\nexport function uploadBuildKey(url: string | null | undefined): string | null {\n return queryOf(url).get(BUILD_PARAM) || null;\n}\n\nexport interface MediaCounts {\n photos: number;\n videos: number;\n}\n\nfunction countWords({ photos, videos }: MediaCounts): string {\n const parts: string[] = [];\n if (photos) parts.push(`${photos} ${photos === 1 ? 'photo' : 'photos'}`);\n if (videos) parts.push(`${videos} ${videos === 1 ? 'video' : 'videos'}`);\n return parts.join(' and ');\n}\n\n/** What the person is shown as having asked: their own words when they wrote any. */\nexport function siteMediaMessage(title: string, counts: MediaCounts, note: string): string {\n const own = note.trim();\n if (own) return own;\n if (counts.photos + counts.videos === 1) return `Add this ${counts.photos ? 'photo' : 'video'} to ${title}.`;\n return `Add these ${countWords(counts)} to ${title}.`;\n}\n\n/** For the agent only: what these files are, so none is mistaken for a design to copy. Null with no files. */\nexport function siteMediaNote({ photos, videos }: MediaCounts): string | null {\n return photos + videos ? `[Site media] photos=${photos} videos=${videos}` : null;\n}\n\n/** What the send button says. */\nexport function sendLabel(counts: MediaCounts): string {\n return counts.photos + counts.videos ? `Send ${countWords(counts)}` : 'Send';\n}\n\n/** One tap fills in the common asks; anything else is typed. */\nexport const SITE_SUGGESTIONS = [\n 'Post these to Facebook and Instagram',\n 'Put these on the home page',\n 'Suggest how to improve my site',\n] as const;\n\n/** A suggestion joins what is already written, once. */\nexport function withSuggestion(note: string, suggestion: string): string {\n const current = note.trim();\n if (!current) return suggestion;\n return current.includes(suggestion) ? note : `${current}\\n${suggestion}`;\n}\n\n/** Something to send, and nothing still on its way up. */\nexport function canSend(state: { media: number; note: string; busy: boolean }): boolean {\n return !state.busy && (state.media > 0 || state.note.trim().length > 0);\n}\n\nexport type SiteLinkState = 'ready' | 'choose' | 'wait' | 'load-more' | 'missing' | 'none';\n\n/** Board pages a link may page through looking for its site before it gives up (web BUILD_LINK_MAX_PAGES). */\nexport const UPLOAD_LINK_MAX_PAGES = 5;\n\n/**\n * Which site the page is for, and what it does next. A link names its site by its chat (the native board knows\n * sites by chat), and the board is paged through before the site counts as missing. A link to a site this\n * account cannot find never falls back to another one: the files would land on the wrong site.\n */\nexport function siteForLink<T extends { channelId: string }>(\n sites: readonly T[],\n linked: string | null,\n board: { loading: boolean; pagesSettled: number; hasMore: boolean; error: boolean },\n): { site: T | null; choices: T[]; state: SiteLinkState } {\n const choices = sites.filter((s) => s.channelId);\n if (linked) {\n const site = choices.find((s) => s.channelId === linked) ?? null;\n if (site) return { site, choices, state: 'ready' };\n if (board.loading || board.error) return { site: null, choices, state: 'wait' };\n if (board.hasMore && board.pagesSettled < UPLOAD_LINK_MAX_PAGES)\n return { site: null, choices, state: 'load-more' };\n return { site: null, choices, state: 'missing' };\n }\n if (board.loading && !choices.length) return { site: null, choices, state: 'wait' };\n if (choices.length === 1) return { site: choices[0], choices, state: 'ready' };\n return { site: null, choices, state: choices.length ? 'choose' : 'none' };\n}\n\nexport type UploadStep = 'picking' | 'adding' | 'finished';\n\n/**\n * Where the page is. `sent` is set when the turn went out and `sawBusy` once the agent was seen working: right\n * after a send it may not be busy yet, which is not finished.\n */\nexport function uploadStep(state: { sent: boolean; sawBusy: boolean; busy: boolean }): UploadStep {\n if (!state.sent) return 'picking';\n return state.sawBusy && !state.busy ? 'finished' : 'adding';\n}\n\n/** The agent's own words about what it did, as plain text, without its follow-up prompts. */\nexport function replySummary(reply: string | null | undefined): string | null {\n const text = stripAskUser(String(reply ?? ''))\n .replace(/\\n\\s*\\**\\s*Next steps?\\s*\\**\\s*:[\\s\\S]*$/i, '')\n .replace(/\\[([^\\]]+)\\]\\([^)]*\\)/g, '$1')\n .replace(/\\*\\*|__|`/g, '')\n .trim();\n return text || null;\n}\n\n/** The reply asks the person something (an ASK_USER card). */\nexport function replyAsks(reply: string | null | undefined): boolean {\n return /\\[ASK_USER\\]/i.test(String(reply ?? ''));\n}\n\n/** The web's `chatNoticeKind` (chat/chatRecovery): the chat's own notices, by message id. */\nfunction chatNoticeKind(id: string | undefined): 'error' | 'stopped' | 'incomplete' | 'note' | null {\n if (!id) return null;\n if (id.startsWith('error-')) return 'error';\n if (id.startsWith('stopped-')) return 'stopped';\n if (id.startsWith('incomplete-')) return 'incomplete';\n if (id.startsWith('note-')) return 'note';\n return null;\n}\n\n/** The card's own parameters on a link (`ys`, `reply`): kept when a link is handed on, dropped from a builder link. */\nexport function cardParams(url: string | null | undefined): { snapshotId: string | null; reply: string | null } {\n const q = queryOf(url);\n return { snapshotId: q.get(CARD_PARAMS[0]) || null, reply: q.get(CARD_PARAMS[1]) };\n}\n\n// ─── Answering the chat a card came from ─────────────────────────────────────\n//\n// An agent in a text thread cannot take photos there, so it sends a card that\n// opens this page (`?ys=<snapshot>`). The person's files go to the SITE'S own\n// agent session, which the thread knows nothing about. Without a word back, the\n// thread's agent would ask \"did you send them?\", or worse, ask for them again.\n// So the page answers the card's chat (`gatewaySurfaceReply`, surface\n// `webbuilder`) with what was sent and what came of it:\n//\n// [SURFACE_REPLY:webbuilder:<requestId>] {\"kind\":\"site-media\",\"status\":\"done\",...}\n//\n// `done` when the site's agent finished, with its own words; `working` or\n// `waiting` when the person leaves the page before that, so the thread is not\n// left silent. The gateway rebuilds the payload field by field and writes the\n// thread's words itself; this side sends only what it knows, cleaned and sized\n// the way the gateway would, so nothing is cut or refused there.\n\n/** The surface a reply names (the snapshot's own). */\nexport const WEBBUILDER_SURFACE = 'webbuilder';\n\n/** The chat widget an agent in a text thread writes for this page: `{ build, title }`. */\nexport const SITE_UPLOAD_WIDGET = 'webbuilder-upload';\n\n/** `reply=0` on a card's link: the gateway's word that its chat never takes an answer. */\nconst REPLY_PARAM = 'reply';\n\n/** The most a reply's whole line may weigh, in UTF-8 bytes (the gateway holds its line to the same). */\nexport const SITE_REPLY_MAX_BYTES = 2048;\n\nconst MAX_REPLY_SITE = 120;\nconst MAX_REPLY_NOTE = 300;\nconst MAX_REPLY_SUMMARY = 600;\n/** The counts a reply may carry: a send's own limits, as the gateway checks them. */\nconst MAX_REPLY_PHOTOS = 10;\n/** Web `MAX_SITE_VIDEOS`: a phone sends photos here, but a reply counts the way the gateway does. */\nconst MAX_REPLY_VIDEOS = 3;\n\n/** A site as a card and the gateway name it: its channel, agent conversation or sandbox id. */\nconst BUILD_KEY_RE = /^[A-Za-z0-9][A-Za-z0-9_.:-]{0,159}$/;\nconst REQUEST_ID_RE = /^[A-Za-z0-9_-]{8,40}$/;\n/** The longest request id there is: a reply measured with it fits under any real one. */\nconst LONGEST_REQUEST_ID = 'x'.repeat(40);\n\nexport type SiteReplyStatus = 'done' | 'working' | 'waiting';\n\n/** What the agent in the card's chat reads. */\nexport interface SiteMediaReply {\n kind: 'site-media';\n status: SiteReplyStatus;\n build: string;\n /** The site's name; absent while it has only a placeholder one. */\n site?: string;\n photos: number;\n videos: number;\n /** The person's own words, when they wrote any. */\n note?: string;\n /** The site agent's own words about what it did (`done` only). */\n summary?: string;\n}\n\nexport function isSiteBuildKey(value: unknown): value is string {\n return typeof value === 'string' && BUILD_KEY_RE.test(value);\n}\n\n/**\n * A card opens this page by its snapshot alone. The link of a card carries `upload=1`, but\n * the copy of the reply the Yantra app shows ends with a plain `?ys=<id>` link; the snapshot\n * then decides. Its first result (`widget`), or the newest of `widgets`, is the agent's\n * `webbuilder-upload` widget only when that very reply wrote one (the gateway never carries\n * an older one forward), so this never reopens an upload from earlier in the chat.\n */\nexport function cardOpensUpload(\n snapshot: {\n widget?: { propsComponent?: unknown } | null;\n widgets?: ReadonlyArray<{ propsComponent?: unknown } | null> | null;\n } | null,\n): boolean {\n if (!snapshot) return false;\n const isUpload = (w: { propsComponent?: unknown } | null | undefined) =>\n typeof w?.propsComponent === 'string' && w.propsComponent.toLowerCase() === SITE_UPLOAD_WIDGET;\n return isUpload(snapshot.widget) || (Array.isArray(snapshot.widgets) && isUpload(snapshot.widgets[0]));\n}\n\n/** The site a card's `webbuilder-upload` widget names, or null (absent, or not a site id). */\nexport function cardBuildKey(attachment: unknown): string | null {\n if (!attachment || typeof attachment !== 'object') return null;\n const build = (attachment as { build?: unknown }).build;\n const key = typeof build === 'string' ? build.trim() : '';\n return isSiteBuildKey(key) ? key : null;\n}\n\n/** The site this page is for: the one its link names, else the one its card names. */\nexport function linkedBuildKey(search: string | null | undefined, cardBuild: string | null): string | null {\n return uploadBuildKey(search) ?? cardBuild;\n}\n\n/** The link's `reply` parameter, as the gateway set it. */\nexport function replyParam(url: string | null | undefined): string | null {\n return queryOf(url).get(REPLY_PARAM);\n}\n\n/**\n * The page may answer the chat only when a card opened it (a snapshot id), the\n * gateway did not mark that chat as one that never takes answers (`reply=0`: a\n * group, or a channel with no way back), and the snapshot itself says so\n * (`canReply`, read as the signed-in person). A snapshot of another surface's\n * card can never take a Web Builder answer, so that counts as no.\n */\nexport function canAnswerChat(state: {\n snapshotId: string | null | undefined;\n replyParam: string | null | undefined;\n canReply: boolean | undefined;\n surface?: string | null;\n}): boolean {\n if (!state.snapshotId || state.replyParam === '0' || state.canReply !== true) return false;\n return state.surface == null || state.surface === WEBBUILDER_SURFACE;\n}\n\n/**\n * Which chat hears about a send. A text thread's card (`?ys=`) answers through the gateway, by\n * {@link canAnswerChat}; a page the host opened beside its own chat (yantra.app's \"Add photos\"\n * card, no `?ys=`) answers through the host. A card decides on its own: its chat never takes an\n * answer just because a host could carry one.\n */\nexport function chatToAnswer(state: {\n snapshotId: string | null | undefined;\n replyParam: string | null | undefined;\n canReply: boolean | undefined;\n surface?: string | null;\n host: boolean;\n}): 'card' | 'host' | null {\n if (state.snapshotId) return canAnswerChat(state) ? 'card' : null;\n return state.host ? 'host' : null;\n}\n\n/** A fresh request id: 16 url-safe random characters. The gateway answers each one once. */\nexport function mintReplyId(): string {\n // Hermes may have no `crypto.getRandomValues`/`btoa`: 16 url-safe characters either way.\n const ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_';\n const bytes = new Uint8Array(16);\n const random = (globalThis as { crypto?: { getRandomValues?: (a: Uint8Array) => Uint8Array } }).crypto;\n if (random?.getRandomValues) random.getRandomValues(bytes);\n else for (let i = 0; i < bytes.length; i++) bytes[i] = Math.floor(Math.random() * 256);\n let id = '';\n for (const b of bytes) id += ALPHABET[b & 63];\n return id;\n}\n\nexport function isReplyId(value: unknown): value is string {\n return typeof value === 'string' && REQUEST_ID_RE.test(value);\n}\n\n// The gateway's cleaning, the same table and order (messenger-gateway surface-reply.ts\n// `cleanReplyText`): NFKC first, so a fullwidth bracket is a bracket; then line breaks and\n// controls become a space (one line of the turn), invisible marks go (text a model reads and a\n// person never sees), and brackets, angle brackets and backticks go (they could close the\n// `[SURFACE_REPLY:...]` prefix or put markup in the bubble).\n// eslint-disable-next-line no-control-regex\nconst LINE_BREAKING_RE = /[\\u0000-\\u001f\\u007f-\\u009f\\u2028\\u2029]+/g;\nconst INVISIBLE_RE =\n /[\\u061c\\u180e\\u200b-\\u200f\\u202a-\\u202e\\u2060-\\u2069\\ufeff\\ufe00-\\ufe0f\\u{e0000}-\\u{e007f}\\u{e0100}-\\u{e01ef}]+/gu;\nconst MARKUP_RE = /[[\\]<>`]+/g;\n\nfunction nfkc(text: string): string {\n try {\n return text.normalize('NFKC');\n } catch {\n return text;\n }\n}\n\nfunction cleanLine(value: unknown): string {\n if (typeof value !== 'string') return '';\n return nfkc(value)\n .replace(LINE_BREAKING_RE, ' ')\n .replace(INVISIBLE_RE, '')\n .replace(MARKUP_RE, '')\n .replace(/\\s+/g, ' ')\n .trim();\n}\n\n/** `value` as a reply may carry it, at most `max` characters (code points, as the gateway counts). */\nexport function cleanReplyText(value: unknown, max: number): string {\n return Array.from(cleanLine(value)).slice(0, max).join('').trim();\n}\n\n// A link in the site agent's words: the summary is texted on to the person, and a sandbox or\n// preview address must never reach a text thread (Web Builder #429). The link goes, with what\n// only pointed at it (\"here:\", \"at\", \"Live preview:\", an emptied \"(preview)\"); its sentence stays.\nconst LINK_RE = /https?:\\/\\/[^\\s<>\"'`]+/gi;\nconst HAS_LINK_RE = /https?:\\/\\//i;\n/** Where a link stood, while what pointed at it is found. */\nconst LINK_MARK = '\\u0001';\nconst POINTED_AT_LINK_RE =\n // eslint-disable-next-line no-control-regex\n /(?:\\b(?:live\\s+)?preview|\\bhere|\\blink|\\bat|\\bon|\\bsee|\\bvia|\\bvisit)?[ \\t]*:?[ \\t]*\\u0001/gi;\nconst TRAILING_LINK_PUNCTUATION_RE = /[.,;:!?)\\]]+$/;\n\n/** A letter or digit in any script (Hermes without Unicode property escapes: any non-punctuation). */\nconst HAS_WORD_RE = ((): RegExp => {\n try {\n return new RegExp('[\\\\p{L}\\\\p{N}]', 'u');\n } catch {\n return /[^\\s.,;:!?()[\\]{}'\"`\\-–—…]/;\n }\n})();\n\n/** `text` without any http(s) link; empty when nothing but links (and words about them) was there. */\nfunction withoutLinks(text: string): string {\n if (!HAS_LINK_RE.test(text)) return text;\n const kept = text\n .replace(LINK_RE, (link) => LINK_MARK + (link.match(TRAILING_LINK_PUNCTUATION_RE)?.[0] ?? ''))\n .replace(POINTED_AT_LINK_RE, ' ')\n // An emptied \"(preview)\" or \"()\", and punctuation left on its own: \"hero . The\", \"Check , .\"\n .replace(/\\(\\s*(?:live\\s+)?(?:preview)?\\s*\\)|\\[\\s*\\]/gi, '')\n .replace(/[ \\t]+([.,;:!?)])/g, '$1')\n .replace(/[,;:]+(?=[ \\t]*(?:[.,;:!?)]|$))/g, '')\n .replace(/([.!?])(?:[ \\t]*[.,;:])+/g, '$1')\n .replace(/[ \\t]{2,}/g, ' ')\n .trim();\n return HAS_WORD_RE.test(kept) ? kept : '';\n}\n\n/**\n * The agent's words, without links, cleaned, and when longer than `max` cut where\n * a sentence ends (else between words, marked with an ellipsis), never mid-word:\n * the agent in the thread repeats what it reads.\n */\nfunction cleanSummary(value: unknown, max: number): string {\n const text = cleanLine(typeof value === 'string' ? withoutLinks(value) : value);\n const chars = Array.from(text);\n if (chars.length <= max) return text;\n const head = chars.slice(0, max - 1).join('');\n const sentence = Math.max(head.lastIndexOf('. '), head.lastIndexOf('! '), head.lastIndexOf('? '));\n if (sentence >= head.length / 2) return head.slice(0, sentence + 1);\n const space = head.lastIndexOf(' ');\n return `${(space > 0 ? head.slice(0, space) : head).trimEnd()}…`;\n}\n\n/**\n * The note on one line. A tapped suggestion goes on a line of its own under what\n * was typed; joined with a bare space the two would run together (\"...the home\n * page Post these to Facebook\"), so a line that does not end a sentence gets a stop.\n */\nfunction noteAsSentences(note: unknown): string {\n if (typeof note !== 'string') return '';\n const lines = note\n .split(/\\r\\n|\\r|\\n|\\u2028|\\u2029/)\n .map((line) => line.trim())\n .filter(Boolean);\n return lines.map((line, i) => (i < lines.length - 1 && !/[.!?:;,]$/.test(line) ? `${line}.` : line)).join(' ');\n}\n\nconst count = (value: unknown, max: number) =>\n typeof value === 'number' && Number.isFinite(value) ? Math.min(max, Math.max(0, Math.floor(value))) : 0;\n\n/** UTF-8 bytes, without `TextEncoder` (not on every Hermes). */\nconst byteLength = (text: string) => {\n let bytes = 0;\n for (const ch of text) {\n const cp = ch.codePointAt(0) ?? 0;\n bytes += cp < 0x80 ? 1 : cp < 0x800 ? 2 : cp < 0x10000 ? 3 : 4;\n }\n return bytes;\n};\n\n/** Does the whole line the agent receives for `reply` stay within the 2 KB the gateway allows? */\nfunction replyFits(reply: SiteMediaReply, requestId: string): boolean {\n return (\n byteLength(`[SURFACE_REPLY:${WEBBUILDER_SURFACE}:${requestId}] ${JSON.stringify(reply)}`) <=\n SITE_REPLY_MAX_BYTES\n );\n}\n\n/**\n * The reply for one send. Fields go in a fixed order and only when they say\n * something: a placeholder site name is left out (the thread would read \"Sent 6\n * photos for my site, New site\"), and the agent's summary rides only with `done`,\n * and never with a link in it (it is texted on).\n * Over 2 KB, the summary goes first, then the note is shortened, as the gateway\n * would fit it. Null when the gateway would refuse it anyway: no site id to name,\n * nothing sent or asked, or a line that still does not fit. `requestId` is the\n * one the line will carry.\n */\nexport function siteMediaReply(\n input: {\n status: SiteReplyStatus;\n build: string | null | undefined;\n /** The site's name as the board shows it. */\n title?: string | null;\n photos: number;\n videos: number;\n note?: string | null;\n summary?: string | null;\n },\n requestId: string = LONGEST_REQUEST_ID,\n): SiteMediaReply | null {\n const build = typeof input.build === 'string' ? input.build.trim() : '';\n const status = input.status;\n if (!isSiteBuildKey(build) || !isReplyId(requestId)) return null;\n if (status !== 'done' && status !== 'working' && status !== 'waiting') return null;\n const site = isGenericArtifactTitle(input.title) ? '' : cleanReplyText(input.title, MAX_REPLY_SITE);\n const note = cleanReplyText(noteAsSentences(input.note), MAX_REPLY_NOTE);\n const summary = status === 'done' ? cleanSummary(input.summary, MAX_REPLY_SUMMARY) : '';\n const reply: SiteMediaReply = {\n kind: 'site-media',\n status,\n build,\n ...(site ? { site } : {}),\n photos: count(input.photos, MAX_REPLY_PHOTOS),\n videos: count(input.videos, MAX_REPLY_VIDEOS),\n ...(note ? { note } : {}),\n ...(summary ? { summary } : {}),\n };\n // Nothing sent and nothing asked (a note that was all brackets): the gateway refuses it, so it never goes.\n if (!reply.photos && !reply.videos && !reply.note) return null;\n if (replyFits(reply, requestId)) return reply;\n delete reply.summary;\n if (replyFits(reply, requestId)) return reply;\n if (reply.note) {\n // The longest start of the note that fits, by whole characters.\n const chars = Array.from(reply.note);\n const withNote = (n: number): SiteMediaReply => {\n const kept = chars.slice(0, n).join('').trimEnd();\n const { note: _dropped, ...rest } = reply;\n return kept ? { ...rest, note: kept } : rest;\n };\n let lo = 0;\n let hi = chars.length;\n while (lo < hi) {\n const mid = Math.ceil((lo + hi) / 2);\n if (replyFits(withNote(mid), requestId)) lo = mid;\n else hi = mid - 1;\n }\n const fitted = withNote(lo);\n return replyFits(fitted, requestId) ? fitted : null;\n }\n return null;\n}\n\n/**\n * What one send may still tell the chat: one early word (`working` or `waiting`)\n * and one `done`. A page left and opened again, or a question answered, never\n * starts more turns in the thread than that.\n */\nexport interface ReplyBudget {\n /** The send's request id: the first reply it makes goes out with it. */\n requestId: string;\n early: boolean;\n done: boolean;\n}\n\nexport function newReplyBudget(requestId: string = mintReplyId()): ReplyBudget {\n return { requestId, early: false, done: false };\n}\n\n/**\n * The request id a reply of `status` goes out with, and the budget after it; null\n * when this send has said that already. `done` after an early reply takes a\n * fresh id: the gateway answers an id once, and the early one is spent.\n */\nexport function takeReply(\n budget: ReplyBudget,\n status: SiteReplyStatus,\n mint: () => string = mintReplyId,\n): { requestId: string; budget: ReplyBudget } | null {\n if (budget.done) return null;\n if (status === 'done') {\n return { requestId: budget.early ? mint() : budget.requestId, budget: { ...budget, done: true } };\n }\n if (budget.early) return null;\n return { requestId: budget.requestId, budget: { ...budget, early: true } };\n}\n\n/** What a page being left says: Yantra still working, or a question waiting here; else nothing. */\nexport function leavingReply(state: { step: UploadStep; question: boolean }): 'working' | 'waiting' | null {\n if (state.step === 'adding') return 'working';\n if (state.step === 'finished' && state.question) return 'waiting';\n return null;\n}\n\n/**\n * The send's turn ended with the site agent's own answer, so the work is done:\n * not a question still waiting on the page, not a failure (an error or a stop in\n * the chat, or `failed`: the chat's recovery, which is also how running out of\n * credits mid-turn shows), and the agent said something. `messages` are the\n * ones since the send.\n */\nexport function sendFinishedWell(state: {\n messages: ReadonlyArray<{ id: string; role: string; content: string }>;\n failed: boolean;\n question: boolean;\n}): boolean {\n if (state.failed || state.question) return false;\n let answer: { content: string } | null = null;\n for (let i = state.messages.length - 1; i >= 0; i--) {\n const m = state.messages[i];\n if (m.role === 'user') break;\n const notice = chatNoticeKind(m.id);\n if (notice === 'error' || notice === 'stopped' || notice === 'incomplete') return false;\n if (!answer && m.role === 'assistant' && !notice) answer = m;\n }\n return Boolean(answer && replySummary(answer.content));\n}\n"],"names":["isGenericArtifactTitle"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAYA,MAAM,YAAe,GAAA,QAAA;AACrB,MAAM,WAAc,GAAA,OAAA;AAEpB,MAAM,WAAA,GAAc,CAAC,IAAA,EAAM,OAAO,CAAA;AAClC,SAAS,QAAQ,GAAiD,EAAA;AAChE,EAAM,MAAA,GAAA,GAAM,MAAO,CAAA,GAAA,IAAA,IAAA,GAAA,GAAA,GAAO,EAAE,CAAA;AAC5B,EAAM,MAAA,CAAA,GAAI,GAAI,CAAA,OAAA,CAAQ,GAAG,CAAA;AACzB,EAAA,IAAI,CAAI,GAAA,CAAA,EAAU,OAAA,IAAI,gBAAgB,EAAE,CAAA;AACxC,EAAA,MAAM,IAAO,GAAA,GAAA,CAAI,OAAQ,CAAA,GAAA,EAAK,CAAC,CAAA;AAC/B,EAAO,OAAA,IAAI,eAAgB,CAAA,GAAA,CAAI,KAAM,CAAA,CAAA,GAAI,GAAG,IAAO,GAAA,CAAA,GAAI,MAAY,GAAA,IAAI,CAAC,CAAA;AAC1E;AAGO,SAAS,aAAa,GAA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AAQ,EAAA;AACvB,IAAM,MAAA,MAAA,GAAS,cAAe,CAAA,CAAA,CAAE,EAAE,CAAA;AAClC,IAAA,IAAI,WAAW,OAAW,IAAA,MAAA,KAAW,SAAa,IAAA,MAAA,KAAW,cAAqB,OAAA,KAAA;AAClF,IAAA,IAAI,CAAC,MAAU,IAAA,CAAA,CAAE,SAAS,WAAe,IAAA,CAAC,QAAiB,MAAA,GAAA,CAAA;AAAA;AAE7D,EAAA,OAAO,OAAQ,CAAA,MAAA,IAAU,YAAa,CAAA,MAAA,CAAO,OAAO,CAAC,CAAA;AACvD"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {createDataService}from'./data/dataApi.js';import {createSecretsService}from'./secrets/secretsApi.js';import {SecretsCredentialStore}from'./secrets/secretsStore.js';import {connectorConnectUrl,checkApiKey,API_KEY_CONNECT,INTEGRATION_CREDENTIALS_QUERY,parseCredentials,INTEGRATION_CATALOG_QUERY,withBuiltInEntries,parseCatalog}from'./integrations/catalog.js';import {createAppSecretsAdapter,mintAndStoreAppToken,appTokenStatusFromNames}from'./integrations/appToken.js';import {enableSiteBilling}from'./integrations/siteBilling.js';import {disableSiteMail,siteMailStatus,enableSiteMail}from'./integrations/siteMail.js';import {createSharingService}from'./sharing/sharingApi.js';import {PROJECT_SETTINGS_QUERY,parseServerProjectSettings}from'./project/serverSettings.js';var __defProp = Object.defineProperty;
|
|
1
|
+
import {createDataService}from'./data/dataApi.js';import {createSecretsService}from'./secrets/secretsApi.js';import {SecretsCredentialStore}from'./secrets/secretsStore.js';import {connectorConnectUrl,checkApiKey,API_KEY_CONNECT,INTEGRATION_CREDENTIALS_QUERY,parseCredentials,INTEGRATION_CATALOG_QUERY,withBuiltInEntries,parseCatalog}from'./integrations/catalog.js';import {createAppSecretsAdapter,mintAndStoreAppToken,appTokenStatusFromNames}from'./integrations/appToken.js';import {enableSiteBilling}from'./integrations/siteBilling.js';import {disableSiteMail,siteMailStatus,enableSiteMail}from'./integrations/siteMail.js';import {createSharingService}from'./sharing/sharingApi.js';import {createGithubConnectService}from'./github/githubConnectApi.js';import {PROJECT_SETTINGS_QUERY,parseServerProjectSettings}from'./project/serverSettings.js';var __defProp = Object.defineProperty;
|
|
2
2
|
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
|
|
3
3
|
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
4
4
|
var __propIsEnum = Object.prototype.propertyIsEnumerable;
|
|
@@ -282,12 +282,24 @@ function createWebServices(opts) {
|
|
|
282
282
|
if (((_a = r.errors) == null ? void 0 : _a.length) && ((_b = r.data) == null ? void 0 : _b.aiCodeProjectSettings) === void 0) return null;
|
|
283
283
|
return parseServerProjectSettings((_c = r.data) == null ? void 0 : _c.aiCodeProjectSettings);
|
|
284
284
|
};
|
|
285
|
+
const githubConnect = createGithubConnectService({
|
|
286
|
+
transport,
|
|
287
|
+
scope: () => {
|
|
288
|
+
const s = scope();
|
|
289
|
+
return {
|
|
290
|
+
orgName: s.orgName,
|
|
291
|
+
project: s.projectId
|
|
292
|
+
};
|
|
293
|
+
},
|
|
294
|
+
currentUserId: () => sharing.currentUserId().catch(() => null)
|
|
295
|
+
});
|
|
285
296
|
return {
|
|
286
297
|
data,
|
|
287
298
|
secrets,
|
|
288
299
|
appSecrets,
|
|
289
300
|
integrations,
|
|
290
301
|
sharing,
|
|
302
|
+
githubConnect,
|
|
291
303
|
serverSettings
|
|
292
304
|
};
|
|
293
305
|
}export{SITE_AGENT_URL,createWebServices};//# sourceMappingURL=webServices.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"webServices.js","sources":["../../../../src/features/webbuilder/web/webServices.ts"],"sourcesContent":["/**\n * The web panels' services on the phone: Secrets (`secrets/secretsApi`), Cloud (`data/dataApi`) and\n * Integrations (web `integrations/useIntegrationsService`), built from the web's own modules over the\n * host's GraphQL seam. Each call is the web's request, unchanged. Pure (no React).\n */\nimport { createDataService, type WebBuilderDataService } from './data/dataApi';\nimport type { GraphqlTransport } from './data/graphql';\nimport { createSecretsService, type WebBuilderSecretsService } from './secrets/secretsApi';\nimport { SecretsCredentialStore } from './secrets/secretsStore';\nimport {\n API_KEY_CONNECT,\n INTEGRATION_CATALOG_QUERY,\n INTEGRATION_CREDENTIALS_QUERY,\n checkApiKey,\n connectorConnectUrl,\n parseCatalog,\n parseCredentials,\n withBuiltInEntries,\n type IntegrationCatalogEntry,\n type IntegrationCredential,\n} from './integrations/catalog';\nimport {\n appTokenStatusFromNames,\n createAppSecretsAdapter,\n mintAndStoreAppToken,\n type AppSecretsAdapter,\n type AppTokenStatus,\n} from './integrations/appToken';\nimport { enableSiteBilling } from './integrations/siteBilling';\nimport { disableSiteMail, enableSiteMail, siteMailStatus } from './integrations/siteMail';\nimport { createSharingService, type WebBuilderSharingService } from './sharing/sharingApi';\nimport {\n PROJECT_SETTINGS_QUERY,\n parseServerProjectSettings,\n type ProjectIntegration,\n type ServerProjectSettings,\n} from './project/serverSettings';\n\nexport interface WebScope {\n orgName: string;\n projectId: string;\n environmentTagId: string;\n}\n\n/**\n * The agent a published site calls (`YANTRA_AGENT_URL`) when the host names none. The host passes the\n * agent of its own plane (web 0.10.1: prod must never fall back to the dev agent).\n */\nexport const SITE_AGENT_URL = 'https://cdecli-agent.cdebase.dev';\n\n/** surface-kit `connectApiKeyConnector`'s request: the connector entry plus the key, recorded `active`. */\nconst CREATE_CUSTOM_CONNECTOR = `\n mutation CreateCustomConnectorExtension($input: CreateCustomConnectorExtensionInput!) {\n createCustomConnectorExtension(input: $input) {\n success message credentialId authorizationUrl connectorType\n }\n }`;\n\nfunction credentialSafeName(raw: string): string {\n return (\n raw\n .replace(/[^A-Za-z0-9 _-]+/g, ' ')\n .replace(/\\s+/g, ' ')\n .trim() || 'Credential'\n );\n}\n\nfunction newUuid(): string {\n return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {\n const r = Math.floor(Math.random() * 16);\n return (c === 'x' ? r : (r % 4) + 8).toString(16);\n });\n}\n\n/** surface-kit `buildCustomConnectorInput` for an api_key connector (the fields Stripe sends). */\nfunction apiKeyConnectorInput(\n connectorId: string,\n spec: (typeof API_KEY_CONNECT)[string],\n key: string,\n scope: WebScope,\n): Record<string, unknown> {\n const name = credentialSafeName(`${spec.label} web builder`);\n return {\n name,\n description: `Custom connector for ${connectorId}`,\n extensionUuid: newUuid(),\n orgName: scope.orgName,\n projectId: scope.projectId,\n environmentTag: scope.environmentTagId,\n publisher: scope.orgName,\n connectorType: 'app',\n provider: {\n id: connectorId,\n name,\n title: name,\n description: `${spec.label} credential`,\n baseUrl: spec.baseUrl,\n providerUrl: '',\n logo: '',\n categories: ['other'],\n category: 'other',\n authMethods: ['api_key'],\n authorizationUrl: '',\n tokenUrl: '',\n revocationUrl: '',\n mcpUrl: '',\n scopes: '',\n clientAuthMethod: 'client_secret_post',\n useBasicAuth: false,\n useCustomOAuthEndpoints: false,\n usePKCE: false,\n color: '',\n iconName: 'AiOutlineApi',\n iconFontSize: 'large',\n enabled: true,\n fields: [\n {\n defaultValue: '',\n description: '',\n enumValues: '',\n genericType: 'api_key',\n iconType: '',\n isConfigField: true,\n isSecret: true,\n label: spec.field.label,\n name: spec.field.name,\n placeholder: '',\n placement: 'none',\n placementKey: '',\n readOnly: false,\n required: false,\n scope: 4,\n secretKey: spec.field.secretKey,\n secretType: 'ENVIRONMENT_VAR',\n type: 'string',\n uiWidget: 'password',\n },\n ],\n },\n values: { authMethod: 'api_key', [spec.field.name]: key.trim() },\n };\n}\n\n/** A project as the web services read it. */\nexport interface WebProjectRef {\n channelId: string;\n projectId?: string | null;\n sandboxId?: string | null;\n templateId?: string | null;\n}\n\nexport interface WebIntegrationsService {\n loadCatalog: () => Promise<IntegrationCatalogEntry[]>;\n /** The person's connections in this workspace; null when they can't be read. */\n loadConnections: () => Promise<IntegrationCredential[] | null>;\n connectUrl: (connectorId: string) => string | null;\n /** The project's saved integrations (server settings); null when they can't be read. */\n projectIntegrations: (channelId: string) => Promise<ProjectIntegration[] | null>;\n appTokenStatus: (project: WebProjectRef) => Promise<AppTokenStatus>;\n createAppToken: (project: WebProjectRef) => Promise<{ ok: boolean; message?: string }>;\n enableSiteBilling: (\n project: WebProjectRef,\n stripeCredentialId: string,\n ) => Promise<{ ok: boolean; message?: string }>;\n connectApiKey: (connectorId: string, key: string) => Promise<{ ok: boolean; message?: string }>;\n siteMail: {\n enable: (project: WebProjectRef, domain: string, notifyTo: string) => ReturnType<typeof enableSiteMail>;\n status: (project: WebProjectRef, diagnose?: boolean) => ReturnType<typeof siteMailStatus>;\n disable: (project: WebProjectRef) => ReturnType<typeof disableSiteMail>;\n };\n}\n\nexport interface WebServices {\n data: WebBuilderDataService;\n secrets: WebBuilderSecretsService;\n appSecrets: AppSecretsAdapter;\n integrations: WebIntegrationsService;\n sharing: WebBuilderSharingService;\n /** The project's server settings (integrations, GitHub sync, database…); null when unreadable. */\n serverSettings: (channelId: string) => Promise<ServerProjectSettings | null>;\n}\n\nexport function createWebServices(opts: {\n transport: GraphqlTransport;\n scope: () => WebScope;\n appUrl?: string;\n /** The agent of the app's own plane (the build profile's CDECLI_AGENT_ENDPOINT). */\n agentUrl?: string;\n}): WebServices {\n const { transport, scope } = opts;\n const data = createDataService(transport);\n const secrets = createSecretsService({\n transport,\n data,\n store: new SecretsCredentialStore(null),\n scope: () => {\n const s = scope();\n return { orgName: s.orgName, project: s.projectId };\n },\n });\n const appSecrets = createAppSecretsAdapter(secrets);\n // The web helpers type `errors` as a plain array; the seam's is read-only (same values).\n const gql = <T>(query: string, variables: Record<string, unknown>) =>\n transport.mutate<T>(query, variables) as Promise<{ data?: T; errors?: Array<{ message: string }> }>;\n /** The project's secrets credential is recorded on its settings (web `settingsSync.update`). */\n const keepCredential = async (channelId: string, credentialId?: string | null) => {\n if (!credentialId) return;\n const s = await data.getSettings(channelId);\n if (s.ok && s.value?.secretsCredentialId !== credentialId) {\n await data.updateSettings(channelId, { secretsCredentialId: credentialId });\n }\n };\n let catalog: Promise<IntegrationCatalogEntry[]> | null = null;\n\n const integrations: WebIntegrationsService = {\n loadCatalog: async () => {\n if (!catalog) {\n catalog = transport\n .query<{ integrationConnectors?: unknown }>(INTEGRATION_CATALOG_QUERY, {})\n .then((r) => {\n if (r.errors?.length && !r.data?.integrationConnectors) {\n catalog = null;\n throw new Error(r.errors[0].message || \"Couldn't load the integrations.\");\n }\n return withBuiltInEntries(parseCatalog(r.data?.integrationConnectors));\n });\n }\n return catalog;\n },\n loadConnections: async () => {\n const s = scope();\n if (!s.orgName || !s.projectId) return null;\n const r = await transport.query<{ formBuilderCredentials?: { data?: unknown } }>(\n INTEGRATION_CREDENTIALS_QUERY,\n {\n filter: {\n orgName: s.orgName,\n projectId: s.projectId,\n ...(s.environmentTagId ? { environmentTag: s.environmentTagId } : {}),\n },\n limit: 200,\n },\n );\n if (r.errors?.length && !r.data?.formBuilderCredentials) return null;\n return parseCredentials(r.data?.formBuilderCredentials?.data);\n },\n connectUrl: (connectorId) =>\n opts.appUrl ? connectorConnectUrl(opts.appUrl, connectorId, scope().projectId) : null,\n projectIntegrations: async (channelId) => {\n const r = await transport.query<{ aiCodeProjectSettings?: unknown }>(PROJECT_SETTINGS_QUERY, { channelId });\n if (r.errors?.length && r.data?.aiCodeProjectSettings === undefined) return null;\n return parseServerProjectSettings(r.data?.aiCodeProjectSettings)?.integrations ?? [];\n },\n appTokenStatus: async (project) => {\n if (!project.channelId) return 'unavailable';\n try {\n return appTokenStatusFromNames(\n await appSecrets.listSecretNames({\n channelId: project.channelId,\n projectId: project.projectId ?? undefined,\n }),\n );\n } catch {\n return 'unavailable';\n }\n },\n createAppToken: async (project) => {\n if (!project.channelId) return { ok: false, message: 'Open a project first.' };\n const r = await mintAndStoreAppToken({\n channelId: project.channelId,\n projectId: project.projectId ?? undefined,\n scope: scope(),\n agentUrl: opts.agentUrl || SITE_AGENT_URL,\n secrets: appSecrets,\n gql,\n });\n // The web's result union, read without narrowing (native: no strict null checks).\n const minted = r as { ok: boolean; credentialId?: string; warning?: string; message?: string };\n if (!minted.ok) return { ok: false, message: minted.message };\n await keepCredential(project.channelId, minted.credentialId);\n return minted.warning ? { ok: true, message: minted.warning } : { ok: true };\n },\n enableSiteBilling: async (project, stripeCredentialId) => {\n if (!project.channelId) return { ok: false, message: 'Open a project first.' };\n const r = await enableSiteBilling({\n channelId: project.channelId,\n projectId: project.projectId ?? undefined,\n stripeCredentialId,\n secrets: appSecrets,\n gql,\n });\n const billed = r as { ok: boolean; credentialId?: string; message?: string };\n if (billed.ok) await keepCredential(project.channelId, billed.credentialId);\n return billed.ok ? { ok: true } : { ok: false, message: billed.message };\n },\n connectApiKey: async (connectorId, key) => {\n const spec = API_KEY_CONNECT[connectorId];\n if (!spec || !checkApiKey(connectorId, key).ok) {\n return { ok: false, message: `That doesn't look like a ${spec?.label ?? ''} secret key.` };\n }\n const s = scope();\n if (!s.orgName || !s.projectId || !s.environmentTagId) {\n return {\n ok: false,\n message: \"Can't tell which workspace to save the key in. Sign in again, then retry.\",\n };\n }\n const r = await transport.mutate<{\n createCustomConnectorExtension?: { credentialId?: string; message?: string };\n }>(CREATE_CUSTOM_CONNECTOR, { input: apiKeyConnectorInput(connectorId, spec, key, s) });\n const created = r.data?.createCustomConnectorExtension;\n if (!created?.credentialId) {\n return {\n ok: false,\n message: created?.message || r.errors?.[0]?.message || `${spec.label} couldn't be connected.`,\n };\n }\n return { ok: true };\n },\n siteMail: {\n enable: async (project, domain, notifyTo) => {\n const r = await enableSiteMail({\n channelId: project.channelId,\n projectId: project.projectId ?? undefined,\n domain,\n notifyTo,\n secrets: appSecrets,\n gql,\n });\n const mailed = r as { ok: boolean; credentialId?: string };\n if (mailed.ok) await keepCredential(project.channelId, mailed.credentialId);\n return r;\n },\n status: (project, diagnose) => siteMailStatus(gql, project.channelId, diagnose),\n disable: (project) => disableSiteMail(gql, project.channelId),\n },\n };\n\n // The web's sharing calls take one document runner: a mutation goes out as one, the rest as queries.\n const sharing = createSharingService((document, variables) =>\n /^\\s*mutation\\b/.test(document) ? transport.mutate(document, variables) : transport.query(document, variables),\n );\n\n const serverSettings = async (channelId: string) => {\n const r = await transport.query<{ aiCodeProjectSettings?: unknown }>(PROJECT_SETTINGS_QUERY, { channelId });\n if (r.errors?.length && r.data?.aiCodeProjectSettings === undefined) return null;\n return parseServerProjectSettings(r.data?.aiCodeProjectSettings);\n };\n\n return { data, secrets, appSecrets, integrations, sharing, serverSettings };\n}\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAyBO,MAAM,cAAiB,GAAA;AAG9B,MAAM,uBAA0B,GAAA;AAAA;AAAA;AAAA;AAAA;AAAA,GAAA,CAAA;AAMhC,SAAS,mBAAmB,GAAqB,EAAA;AAC/C,EAAO,OAAA,GAAA,CAAI,OAAQ,CAAA,mBAAA,EAAqB,GAAG,CAAA,CAAE,QAAQ,MAAQ,EAAA,GAAG,CAAE,CAAA,IAAA,EAAU,IAAA,YAAA;AAC9E;AACA,SAAS,OAAkB,GAAA;AACzB,EAAO,OAAA,sCAAA,CAAuC,OAAQ,CAAA,OAAA,EAAS,CAAK,CAAA,KAAA;AAClE,IAAA,MAAM,IAAI,IAAK,CAAA,KAAA,CAAM,IAAK,CAAA,MAAA,KAAW,EAAE,CAAA;AACvC,IAAA,OAAA,CAAQ,MAAM,GAAM,GAAA,CAAA,GAAI,IAAI,CAAI,GAAA,CAAA,EAAG,SAAS,EAAE,CAAA;AAAA,GAC/C,CAAA;AACH;AAGA,SAAS,oBAAqB,CAAA,WAAA,EAAqB,IAAwC,EAAA,GAAA,EAAa,KAA0C,EAAA;AAChJ,EAAA,MAAM,IAAO,GAAA,kBAAA,CAAmB,CAAG,EAAA,IAAA,CAAK,KAAK,CAAc,YAAA,CAAA,CAAA;AAC3D,EAAO,OAAA;AAAA,IACL,IAAA;AAAA,IACA,WAAA,EAAa,wBAAwB,WAAW,CAAA,CAAA;AAAA,IAChD,eAAe,OAAQ,EAAA;AAAA,IACvB,SAAS,KAAM,CAAA,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,SAAsB,KAAA;AA7WtD,IAAA,IAAA,EAAA,EAAA,EAAA,EAAA,EAAA;AA8WI,IAAA,MAAM,CAAI,GAAA,MAAM,SAAU,CAAA,KAAA,CAEvB,sBAAwB,EAAA;AAAA,MACzB;AAAA,KACD,CAAA;AACD,IAAI,IAAA,CAAA,CAAA,EAAA,GAAA,CAAA,CAAE,WAAF,IAAU,GAAA,MAAA,GAAA,EAAA,CAAA,MAAA,KAAA,CAAA,CAAU,OAAE,IAAF,KAAA,IAAA,GAAA,MAAA,GAAA,EAAA,CAAQ,qBAA0B,MAAA,MAAA,EAAkB,OAAA,IAAA;AAC5E,IAAA,OAAO,0BAA2B,CAAA,CAAA,EAAA,GAAA,CAAA,CAAE,IAAF,KAAA,IAAA,GAAA,MAAA,GAAA,EAAA,CAAQ,qBAAqB,CAAA;AAAA,GACjE;AACA,EAAO,OAAA;AAAA,IACL,IAAA;AAAA,IACA,OAAA;AAAA,IACA,UAAA;AAAA,IACA,YAAA;AAAA,IACA,OAAA;AAAA,IACA;AAAA,GACF;AACF"}
|
|
1
|
+
{"version":3,"file":"webServices.js","sources":["../../../../src/features/webbuilder/web/webServices.ts"],"sourcesContent":["/**\n * The web panels' services on the phone: Secrets (`secrets/secretsApi`), Cloud (`data/dataApi`) and\n * Integrations (web `integrations/useIntegrationsService`), built from the web's own modules over the\n * host's GraphQL seam. Each call is the web's request, unchanged. Pure (no React).\n */\nimport { createDataService, type WebBuilderDataService } from './data/dataApi';\nimport type { GraphqlTransport } from './data/graphql';\nimport { createSecretsService, type WebBuilderSecretsService } from './secrets/secretsApi';\nimport { SecretsCredentialStore } from './secrets/secretsStore';\nimport {\n API_KEY_CONNECT,\n INTEGRATION_CATALOG_QUERY,\n INTEGRATION_CREDENTIALS_QUERY,\n checkApiKey,\n connectorConnectUrl,\n parseCatalog,\n parseCredentials,\n withBuiltInEntries,\n type IntegrationCatalogEntry,\n type IntegrationCredential,\n} from './integrations/catalog';\nimport {\n appTokenStatusFromNames,\n createAppSecretsAdapter,\n mintAndStoreAppToken,\n type AppSecretsAdapter,\n type AppTokenStatus,\n} from './integrations/appToken';\nimport { enableSiteBilling } from './integrations/siteBilling';\nimport { disableSiteMail, enableSiteMail, siteMailStatus } from './integrations/siteMail';\nimport { createSharingService, type WebBuilderSharingService } from './sharing/sharingApi';\nimport { createGithubConnectService, type GithubConnectService } from './github/githubConnectApi';\nimport {\n PROJECT_SETTINGS_QUERY,\n parseServerProjectSettings,\n type ProjectIntegration,\n type ServerProjectSettings,\n} from './project/serverSettings';\n\nexport interface WebScope {\n orgName: string;\n projectId: string;\n environmentTagId: string;\n}\n\n/**\n * The agent a published site calls (`YANTRA_AGENT_URL`) when the host names none. The host passes the\n * agent of its own plane (web 0.10.1: prod must never fall back to the dev agent).\n */\nexport const SITE_AGENT_URL = 'https://cdecli-agent.cdebase.dev';\n\n/** surface-kit `connectApiKeyConnector`'s request: the connector entry plus the key, recorded `active`. */\nconst CREATE_CUSTOM_CONNECTOR = `\n mutation CreateCustomConnectorExtension($input: CreateCustomConnectorExtensionInput!) {\n createCustomConnectorExtension(input: $input) {\n success message credentialId authorizationUrl connectorType\n }\n }`;\n\nfunction credentialSafeName(raw: string): string {\n return (\n raw\n .replace(/[^A-Za-z0-9 _-]+/g, ' ')\n .replace(/\\s+/g, ' ')\n .trim() || 'Credential'\n );\n}\n\nfunction newUuid(): string {\n return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {\n const r = Math.floor(Math.random() * 16);\n return (c === 'x' ? r : (r % 4) + 8).toString(16);\n });\n}\n\n/** surface-kit `buildCustomConnectorInput` for an api_key connector (the fields Stripe sends). */\nfunction apiKeyConnectorInput(\n connectorId: string,\n spec: (typeof API_KEY_CONNECT)[string],\n key: string,\n scope: WebScope,\n): Record<string, unknown> {\n const name = credentialSafeName(`${spec.label} web builder`);\n return {\n name,\n description: `Custom connector for ${connectorId}`,\n extensionUuid: newUuid(),\n orgName: scope.orgName,\n projectId: scope.projectId,\n environmentTag: scope.environmentTagId,\n publisher: scope.orgName,\n connectorType: 'app',\n provider: {\n id: connectorId,\n name,\n title: name,\n description: `${spec.label} credential`,\n baseUrl: spec.baseUrl,\n providerUrl: '',\n logo: '',\n categories: ['other'],\n category: 'other',\n authMethods: ['api_key'],\n authorizationUrl: '',\n tokenUrl: '',\n revocationUrl: '',\n mcpUrl: '',\n scopes: '',\n clientAuthMethod: 'client_secret_post',\n useBasicAuth: false,\n useCustomOAuthEndpoints: false,\n usePKCE: false,\n color: '',\n iconName: 'AiOutlineApi',\n iconFontSize: 'large',\n enabled: true,\n fields: [\n {\n defaultValue: '',\n description: '',\n enumValues: '',\n genericType: 'api_key',\n iconType: '',\n isConfigField: true,\n isSecret: true,\n label: spec.field.label,\n name: spec.field.name,\n placeholder: '',\n placement: 'none',\n placementKey: '',\n readOnly: false,\n required: false,\n scope: 4,\n secretKey: spec.field.secretKey,\n secretType: 'ENVIRONMENT_VAR',\n type: 'string',\n uiWidget: 'password',\n },\n ],\n },\n values: { authMethod: 'api_key', [spec.field.name]: key.trim() },\n };\n}\n\n/** A project as the web services read it. */\nexport interface WebProjectRef {\n channelId: string;\n projectId?: string | null;\n sandboxId?: string | null;\n templateId?: string | null;\n}\n\nexport interface WebIntegrationsService {\n loadCatalog: () => Promise<IntegrationCatalogEntry[]>;\n /** The person's connections in this workspace; null when they can't be read. */\n loadConnections: () => Promise<IntegrationCredential[] | null>;\n connectUrl: (connectorId: string) => string | null;\n /** The project's saved integrations (server settings); null when they can't be read. */\n projectIntegrations: (channelId: string) => Promise<ProjectIntegration[] | null>;\n appTokenStatus: (project: WebProjectRef) => Promise<AppTokenStatus>;\n createAppToken: (project: WebProjectRef) => Promise<{ ok: boolean; message?: string }>;\n enableSiteBilling: (\n project: WebProjectRef,\n stripeCredentialId: string,\n ) => Promise<{ ok: boolean; message?: string }>;\n connectApiKey: (connectorId: string, key: string) => Promise<{ ok: boolean; message?: string }>;\n siteMail: {\n enable: (project: WebProjectRef, domain: string, notifyTo: string) => ReturnType<typeof enableSiteMail>;\n status: (project: WebProjectRef, diagnose?: boolean) => ReturnType<typeof siteMailStatus>;\n disable: (project: WebProjectRef) => ReturnType<typeof disableSiteMail>;\n };\n}\n\nexport interface WebServices {\n data: WebBuilderDataService;\n secrets: WebBuilderSecretsService;\n appSecrets: AppSecretsAdapter;\n integrations: WebIntegrationsService;\n sharing: WebBuilderSharingService;\n /** The person's own GitHub connection (web 0.20.0 Connect GitHub): status and paste-a-token. */\n githubConnect: GithubConnectService;\n /** The project's server settings (integrations, GitHub sync, database…); null when unreadable. */\n serverSettings: (channelId: string) => Promise<ServerProjectSettings | null>;\n}\n\nexport function createWebServices(opts: {\n transport: GraphqlTransport;\n scope: () => WebScope;\n appUrl?: string;\n /** The agent of the app's own plane (the build profile's CDECLI_AGENT_ENDPOINT). */\n agentUrl?: string;\n}): WebServices {\n const { transport, scope } = opts;\n const data = createDataService(transport);\n const secrets = createSecretsService({\n transport,\n data,\n store: new SecretsCredentialStore(null),\n scope: () => {\n const s = scope();\n return { orgName: s.orgName, project: s.projectId };\n },\n });\n const appSecrets = createAppSecretsAdapter(secrets);\n // The web helpers type `errors` as a plain array; the seam's is read-only (same values).\n const gql = <T>(query: string, variables: Record<string, unknown>) =>\n transport.mutate<T>(query, variables) as Promise<{ data?: T; errors?: Array<{ message: string }> }>;\n /** The project's secrets credential is recorded on its settings (web `settingsSync.update`). */\n const keepCredential = async (channelId: string, credentialId?: string | null) => {\n if (!credentialId) return;\n const s = await data.getSettings(channelId);\n if (s.ok && s.value?.secretsCredentialId !== credentialId) {\n await data.updateSettings(channelId, { secretsCredentialId: credentialId });\n }\n };\n let catalog: Promise<IntegrationCatalogEntry[]> | null = null;\n\n const integrations: WebIntegrationsService = {\n loadCatalog: async () => {\n if (!catalog) {\n catalog = transport\n .query<{ integrationConnectors?: unknown }>(INTEGRATION_CATALOG_QUERY, {})\n .then((r) => {\n if (r.errors?.length && !r.data?.integrationConnectors) {\n catalog = null;\n throw new Error(r.errors[0].message || \"Couldn't load the integrations.\");\n }\n return withBuiltInEntries(parseCatalog(r.data?.integrationConnectors));\n });\n }\n return catalog;\n },\n loadConnections: async () => {\n const s = scope();\n if (!s.orgName || !s.projectId) return null;\n const r = await transport.query<{ formBuilderCredentials?: { data?: unknown } }>(\n INTEGRATION_CREDENTIALS_QUERY,\n {\n filter: {\n orgName: s.orgName,\n projectId: s.projectId,\n ...(s.environmentTagId ? { environmentTag: s.environmentTagId } : {}),\n },\n limit: 200,\n },\n );\n if (r.errors?.length && !r.data?.formBuilderCredentials) return null;\n return parseCredentials(r.data?.formBuilderCredentials?.data);\n },\n connectUrl: (connectorId) =>\n opts.appUrl ? connectorConnectUrl(opts.appUrl, connectorId, scope().projectId) : null,\n projectIntegrations: async (channelId) => {\n const r = await transport.query<{ aiCodeProjectSettings?: unknown }>(PROJECT_SETTINGS_QUERY, { channelId });\n if (r.errors?.length && r.data?.aiCodeProjectSettings === undefined) return null;\n return parseServerProjectSettings(r.data?.aiCodeProjectSettings)?.integrations ?? [];\n },\n appTokenStatus: async (project) => {\n if (!project.channelId) return 'unavailable';\n try {\n return appTokenStatusFromNames(\n await appSecrets.listSecretNames({\n channelId: project.channelId,\n projectId: project.projectId ?? undefined,\n }),\n );\n } catch {\n return 'unavailable';\n }\n },\n createAppToken: async (project) => {\n if (!project.channelId) return { ok: false, message: 'Open a project first.' };\n const r = await mintAndStoreAppToken({\n channelId: project.channelId,\n projectId: project.projectId ?? undefined,\n scope: scope(),\n agentUrl: opts.agentUrl || SITE_AGENT_URL,\n secrets: appSecrets,\n gql,\n });\n // The web's result union, read without narrowing (native: no strict null checks).\n const minted = r as { ok: boolean; credentialId?: string; warning?: string; message?: string };\n if (!minted.ok) return { ok: false, message: minted.message };\n await keepCredential(project.channelId, minted.credentialId);\n return minted.warning ? { ok: true, message: minted.warning } : { ok: true };\n },\n enableSiteBilling: async (project, stripeCredentialId) => {\n if (!project.channelId) return { ok: false, message: 'Open a project first.' };\n const r = await enableSiteBilling({\n channelId: project.channelId,\n projectId: project.projectId ?? undefined,\n stripeCredentialId,\n secrets: appSecrets,\n gql,\n });\n const billed = r as { ok: boolean; credentialId?: string; message?: string };\n if (billed.ok) await keepCredential(project.channelId, billed.credentialId);\n return billed.ok ? { ok: true } : { ok: false, message: billed.message };\n },\n connectApiKey: async (connectorId, key) => {\n const spec = API_KEY_CONNECT[connectorId];\n if (!spec || !checkApiKey(connectorId, key).ok) {\n return { ok: false, message: `That doesn't look like a ${spec?.label ?? ''} secret key.` };\n }\n const s = scope();\n if (!s.orgName || !s.projectId || !s.environmentTagId) {\n return {\n ok: false,\n message: \"Can't tell which workspace to save the key in. Sign in again, then retry.\",\n };\n }\n const r = await transport.mutate<{\n createCustomConnectorExtension?: { credentialId?: string; message?: string };\n }>(CREATE_CUSTOM_CONNECTOR, { input: apiKeyConnectorInput(connectorId, spec, key, s) });\n const created = r.data?.createCustomConnectorExtension;\n if (!created?.credentialId) {\n return {\n ok: false,\n message: created?.message || r.errors?.[0]?.message || `${spec.label} couldn't be connected.`,\n };\n }\n return { ok: true };\n },\n siteMail: {\n enable: async (project, domain, notifyTo) => {\n const r = await enableSiteMail({\n channelId: project.channelId,\n projectId: project.projectId ?? undefined,\n domain,\n notifyTo,\n secrets: appSecrets,\n gql,\n });\n const mailed = r as { ok: boolean; credentialId?: string };\n if (mailed.ok) await keepCredential(project.channelId, mailed.credentialId);\n return r;\n },\n status: (project, diagnose) => siteMailStatus(gql, project.channelId, diagnose),\n disable: (project) => disableSiteMail(gql, project.channelId),\n },\n };\n\n // The web's sharing calls take one document runner: a mutation goes out as one, the rest as queries.\n const sharing = createSharingService((document, variables) =>\n /^\\s*mutation\\b/.test(document) ? transport.mutate(document, variables) : transport.query(document, variables),\n );\n\n const serverSettings = async (channelId: string) => {\n const r = await transport.query<{ aiCodeProjectSettings?: unknown }>(PROJECT_SETTINGS_QUERY, { channelId });\n if (r.errors?.length && r.data?.aiCodeProjectSettings === undefined) return null;\n return parseServerProjectSettings(r.data?.aiCodeProjectSettings);\n };\n\n const githubConnect = createGithubConnectService({\n transport,\n scope: () => {\n const s = scope();\n return { orgName: s.orgName, project: s.projectId };\n },\n currentUserId: () => sharing.currentUserId().catch(() => null),\n });\n\n return { data, secrets, appSecrets, integrations, sharing, githubConnect, serverSettings };\n}\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;AA0BO,MAAM,cAAiB,GAAA;AAG9B,MAAM,uBAA0B,GAAA;AAAA;AAAA;AAAA;AAAA;AAAA,GAAA,CAAA;AAMhC,SAAS,mBAAmB,GAAqB,EAAA;AAC/C,EAAO,OAAA,GAAA,CAAI,OAAQ,CAAA,mBAAA,EAAqB,GAAG,CAAA,CAAE,QAAQ,MAAQ,EAAA,GAAG,CAAE,CAAA,IAAA,EAAU,IAAA,YAAA;AAC9E;AACA,SAAS,OAAkB,GAAA;AACzB,EAAO,OAAA,sCAAA,CAAuC,OAAQ,CAAA,OAAA,EAAS,CAAK,CAAA,KAAA;AAClE,IAAA,MAAM,IAAI,IAAK,CAAA,KAAA,CAAM,IAAK,CAAA,MAAA,KAAW,EAAE,CAAA;AACvC,IAAA,OAAA,CAAQ,MAAM,GAAM,GAAA,CAAA,GAAI,IAAI,CAAI,GAAA,CAAA,EAAG,SAAS,EAAE,CAAA;AAAA,GAC/C,CAAA;AACH;AAGA,SAAS,oBAAqB,CAAA,WAAA,EAAqB,IAAwC,EAAA,GAAA,EAAa,KAA0C,EAAA;AAChJ,EAAA,MAAM,IAAO,GAAA,kBAAA,CAAmB,CAAG,EAAA,IAAA,CAAK,KAAK,CAAc,YAAA,CAAA,CAAA;AAC3D,EAAO,OAAA;AAAA,IACL,IAAA;AAAA,IACA,WAAA,EAAa,wBAAwB,WAAW,CAAA,CAAA;AAAA,IAChD,eAAe,OAAQ,EAAA;AAAA,IACvB,SAAS,KAAM,CAAA,OAAA;AAAA,IACf,WAAW,KAAM,CAAA,SAAA;AAAA,IACjB,gBAAgB,KAAM,CAAA,gBA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