@adminide-stack/yantra-mobile 12.0.194-alpha.0 → 12.0.194-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (132) hide show
  1. package/lib/bridge/handlers/NavigationBridgeHandler.js +6 -9
  2. package/lib/bridge/handlers/NavigationBridgeHandler.js.map +1 -1
  3. package/lib/components/BrandBar/BrandBarBackground.js +27 -0
  4. package/lib/components/BrandBar/BrandBarBackground.js.map +1 -0
  5. package/lib/components/BrandBar/MenuToggle.js +73 -0
  6. package/lib/components/BrandBar/MenuToggle.js.map +1 -0
  7. package/lib/components/CustomDrawer.js +6 -6
  8. package/lib/components/CustomDrawer.js.map +1 -1
  9. package/lib/components/GatewayConnector/GatewayConnector.js +3 -2
  10. package/lib/components/GatewayConnector/GatewayConnector.js.map +1 -1
  11. package/lib/components/GatewayToolbarButtonMobile.js +12 -2
  12. package/lib/components/GatewayToolbarButtonMobile.js.map +1 -1
  13. package/lib/components/NavigationHeader/HeaderChip.js +76 -0
  14. package/lib/components/NavigationHeader/HeaderChip.js.map +1 -0
  15. package/lib/components/NavigationHeader/HeaderSkillsButton.js +4 -3
  16. package/lib/components/NavigationHeader/HeaderSkillsButton.js.map +1 -1
  17. package/lib/components/NavigationHeader/HeaderTasksButton.js +4 -3
  18. package/lib/components/NavigationHeader/HeaderTasksButton.js.map +1 -1
  19. package/lib/components/NavigationHeader/NavigationHeader.js +96 -41
  20. package/lib/components/NavigationHeader/NavigationHeader.js.map +1 -1
  21. package/lib/components/YantraTopBar/YantraTopBar.js +98 -0
  22. package/lib/components/YantraTopBar/YantraTopBar.js.map +1 -0
  23. package/lib/compute.js +18 -25
  24. package/lib/compute.js.map +1 -1
  25. package/lib/features/apps/AppsCatalog.js +7 -4
  26. package/lib/features/apps/AppsCatalog.js.map +1 -1
  27. package/lib/features/apps/MarketplaceGallery.js +6 -3
  28. package/lib/features/apps/MarketplaceGallery.js.map +1 -1
  29. package/lib/features/apps/nativeSurfaceTwin.js +1 -1
  30. package/lib/features/apps/nativeSurfaceTwin.js.map +1 -1
  31. package/lib/features/apps/useMarketplaceApps.js +6 -2
  32. package/lib/features/apps/useMarketplaceApps.js.map +1 -1
  33. package/lib/features/attachments/useImageAttachments.js +44 -1
  34. package/lib/features/attachments/useImageAttachments.js.map +1 -1
  35. package/lib/features/credits/FreeCreditsPhoneStepHost.js +67 -0
  36. package/lib/features/credits/FreeCreditsPhoneStepHost.js.map +1 -0
  37. package/lib/features/credits/freeCredits.js +52 -13
  38. package/lib/features/credits/freeCredits.js.map +1 -1
  39. package/lib/features/credits/freeCreditsPhoneStep.js +55 -0
  40. package/lib/features/credits/freeCreditsPhoneStep.js.map +1 -0
  41. package/lib/features/credits/useFreeCredits.js +29 -3
  42. package/lib/features/credits/useFreeCredits.js.map +1 -1
  43. package/lib/features/links/openInApp.js +3 -6
  44. package/lib/features/links/openInApp.js.map +1 -1
  45. package/lib/features/webbuilder/WebBuilderExperience.js +88 -28
  46. package/lib/features/webbuilder/WebBuilderExperience.js.map +1 -1
  47. package/lib/features/webbuilder/appPreview.js +70 -0
  48. package/lib/features/webbuilder/appPreview.js.map +1 -0
  49. package/lib/features/webbuilder/buildFragments.js +33 -12
  50. package/lib/features/webbuilder/buildFragments.js.map +1 -1
  51. package/lib/features/webbuilder/components/AppPhoneSheet.js +127 -0
  52. package/lib/features/webbuilder/components/AppPhoneSheet.js.map +1 -0
  53. package/lib/features/webbuilder/components/BottomTabs.js +32 -21
  54. package/lib/features/webbuilder/components/BottomTabs.js.map +1 -1
  55. package/lib/features/webbuilder/components/Composer.js +144 -47
  56. package/lib/features/webbuilder/components/Composer.js.map +1 -1
  57. package/lib/features/webbuilder/components/PreviewFrame.js +1 -1
  58. package/lib/features/webbuilder/components/PreviewFrame.js.map +1 -1
  59. package/lib/features/webbuilder/components/PreviewScreen.js +9 -4
  60. package/lib/features/webbuilder/components/PreviewScreen.js.map +1 -1
  61. package/lib/features/webbuilder/components/ProjectSheets.js +76 -22
  62. package/lib/features/webbuilder/components/ProjectSheets.js.map +1 -1
  63. package/lib/features/webbuilder/components/ProjectsScreen.js +30 -12
  64. package/lib/features/webbuilder/components/ProjectsScreen.js.map +1 -1
  65. package/lib/features/webbuilder/components/PublishSheet.js +2 -2
  66. package/lib/features/webbuilder/components/PublishSheet.js.map +1 -1
  67. package/lib/features/webbuilder/components/SiteUploadSheet.js +17 -2
  68. package/lib/features/webbuilder/components/SiteUploadSheet.js.map +1 -1
  69. package/lib/features/webbuilder/components/SocialExportPicker.js +253 -0
  70. package/lib/features/webbuilder/components/SocialExportPicker.js.map +1 -0
  71. package/lib/features/webbuilder/components/StudioHome.js +300 -185
  72. package/lib/features/webbuilder/components/StudioHome.js.map +1 -1
  73. package/lib/features/webbuilder/components/TemplateCard.js +13 -5
  74. package/lib/features/webbuilder/components/TemplateCard.js.map +1 -1
  75. package/lib/features/webbuilder/connectorTemplates.js +3 -2
  76. package/lib/features/webbuilder/connectorTemplates.js.map +1 -1
  77. package/lib/features/webbuilder/liveSiteDelete.js +58 -0
  78. package/lib/features/webbuilder/liveSiteDelete.js.map +1 -0
  79. package/lib/features/webbuilder/publishTools.js +3 -1
  80. package/lib/features/webbuilder/publishTools.js.map +1 -1
  81. package/lib/features/webbuilder/socialExportFile.js +84 -0
  82. package/lib/features/webbuilder/socialExportFile.js.map +1 -0
  83. package/lib/features/webbuilder/stepLabels.js +7 -7
  84. package/lib/features/webbuilder/stepLabels.js.map +1 -1
  85. package/lib/features/webbuilder/thumbSources.js +17 -3
  86. package/lib/features/webbuilder/thumbSources.js.map +1 -1
  87. package/lib/features/webbuilder/useVoiceTyping.js +169 -0
  88. package/lib/features/webbuilder/useVoiceTyping.js.map +1 -0
  89. package/lib/features/webbuilder/web/chat/connectRequest.js +17 -0
  90. package/lib/features/webbuilder/web/chat/connectRequest.js.map +1 -0
  91. package/lib/features/webbuilder/web/notify/turnDone.js +20 -0
  92. package/lib/features/webbuilder/web/notify/turnDone.js.map +1 -0
  93. package/lib/features/webbuilder/web/project/coverRequest.js +22 -0
  94. package/lib/features/webbuilder/web/project/coverRequest.js.map +1 -0
  95. package/lib/features/webbuilder/web/project/deleteFlow.js +57 -0
  96. package/lib/features/webbuilder/web/project/deleteFlow.js.map +1 -0
  97. package/lib/features/webbuilder/web/publish/siteAddress.js +5 -1
  98. package/lib/features/webbuilder/web/publish/siteAddress.js.map +1 -1
  99. package/lib/features/webbuilder/web/upload/sitePhotos.js +2 -2
  100. package/lib/features/webbuilder/web/upload/sitePhotos.js.map +1 -1
  101. package/lib/features/webbuilder/web/upload/socialExport.js +191 -0
  102. package/lib/features/webbuilder/web/upload/socialExport.js.map +1 -0
  103. package/lib/features/webbuilder/web/upload/zipRandomAccess.js +64 -0
  104. package/lib/features/webbuilder/web/upload/zipRandomAccess.js.map +1 -0
  105. package/lib/features/webbuilder/web/webServices.js +27 -3
  106. package/lib/features/webbuilder/web/webServices.js.map +1 -1
  107. package/lib/hooks/useHeaderProfile.js +25 -0
  108. package/lib/hooks/useHeaderProfile.js.map +1 -0
  109. package/lib/index.js +1 -1
  110. package/lib/index.js.map +1 -1
  111. package/lib/routes.json +21 -29
  112. package/lib/screens/Account/AccountSheets.js +140 -74
  113. package/lib/screens/Account/AccountSheets.js.map +1 -1
  114. package/lib/screens/Account/index.js +3 -3
  115. package/lib/screens/Account/index.js.map +1 -1
  116. package/lib/screens/Apps/index.js +1 -1
  117. package/lib/screens/Apps/index.js.map +1 -1
  118. package/lib/screens/ChatHistory/index.js +1 -1
  119. package/lib/screens/ChatHistory/index.js.map +1 -1
  120. package/lib/screens/ExpensesNative/index.js +3 -3
  121. package/lib/screens/ExpensesNative/index.js.map +1 -1
  122. package/lib/screens/Home/HomeScreen.js +11 -0
  123. package/lib/screens/Home/HomeScreen.js.map +1 -1
  124. package/lib/screens/Home/components/ChatHistoryLanding.js +3 -2
  125. package/lib/screens/Home/components/ChatHistoryLanding.js.map +1 -1
  126. package/lib/screens/WebBuilderNative/index.js +3 -2
  127. package/lib/screens/WebBuilderNative/index.js.map +1 -1
  128. package/lib/screens/WebBuilderNative/useWebBuilderHost.js +2 -2
  129. package/lib/screens/WebBuilderNative/useWebBuilderHost.js.map +1 -1
  130. package/lib/utils/drawerRoutes.js +13 -0
  131. package/lib/utils/drawerRoutes.js.map +1 -0
  132. package/package.json +2 -2
@@ -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';\nimport { isGenericTitle as isGenericArtifactTitle } from '../../buildFragments';\nimport { withoutRestorePointLine } from '../../webbuilderPrompts';\nimport { parseToolActivity } from '../../../chat/toolActivity';\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. */\n/**\n * For the agent only: this turn came from the photo page (also when only words were sent, web 0.20.1), and what the\n * files are, so none is mistaken for a design to copy. `publish=yes` only when the person ticked it for a live site.\n */\nexport function siteMediaNote({ photos, videos }: MediaCounts, opts: { publish?: boolean } = {}): string {\n return `[Site media] photos=${photos} videos=${videos}${opts.publish ? ' publish=yes' : ''}`;\n}\n\n/** Hosts the platform gives sites (not a name the owner chose). */\nconst PLATFORM_HOST = /\\.(yarntra\\.com|yantra\\.app|pages\\.dev|workers\\.dev|cdebase\\.dev)$/i;\n\n/** A first chat message used as the project's title (\"hi, can you build me a website for my bakery in kurnool\"). */\nconst REQUEST_LEAD =\n /^(?:(?:hi|hello|hey)\\b[\\s,.!]*)?(?:(?:can|could|would|will) you\\s+(?:please\\s+)?|please\\s+|i\\s+(?:want|need|would like)\\s+(?:you\\s+to\\s+)?)?(?:(?:build|make|create|design|set up|start)\\s+)?(?:(?:me|us)\\s+)?(?:(?:an|a|my|the)\\s+)?(?:new\\s+)?(?:(?:simple|modern|nice|small)\\s+)?(?:(?:website|web site|site|landing page|web app|app|page)\\s+)?(?:(?:for|about|called|named)\\s+)?(?:(?:my|our|an|a|the)\\s+)?/i;\n\n/** A published project's name as words: \"rama-bakery-iail9r\" -> \"Rama Bakery\" (the random suffix dropped). */\nexport function projectDisplayName(projectName: string | null | undefined): string | null {\n const words = String(projectName ?? '')\n .toLowerCase()\n .split(/[-_\\s]+/)\n .filter(Boolean);\n const last = words[words.length - 1] ?? '';\n if (words.length > 1 && /^[a-z0-9]{5,8}$/.test(last) && /\\d/.test(last)) words.pop();\n const name = words\n .filter((w) => !/^\\d+$/.test(w))\n .map((w) => w[0].toUpperCase() + w.slice(1))\n .join(' ');\n return name.length >= 3 ? name : null;\n}\n\nconst hostOf = (url: string | null | undefined) =>\n String(url ?? '')\n .replace(/^https?:\\/\\//i, '')\n .split(/[/?#]/)[0]\n .toLowerCase();\n\n/** The project name a live address on the platform was published under (`<name>.yarntra.com`), or null. */\nfunction platformProjectName(liveUrl: string | null | undefined): string | null {\n const m = /^([a-z0-9-]+)\\.(?:yarntra\\.com|pages\\.dev)$/.exec(hostOf(liveUrl));\n return m ? m[1] : null;\n}\n\n/**\n * A name people recognise for the site (web 0.20.1 `siteName`): its own domain, its published name, a real project\n * name, or the subject of the request it began with - never the chat prompt itself.\n */\nexport function siteName(site: { title?: string | null; liveUrl?: string | null }, fallback: string): string {\n const host = hostOf(site.liveUrl);\n if (host && !PLATFORM_HOST.test(host)) return host.replace(/^www\\./, '');\n const published = projectDisplayName(platformProjectName(site.liveUrl));\n if (published) return published;\n const title = String(site.title ?? '')\n .replace(/\\s+/g, ' ')\n .trim();\n if (title && !isGenericArtifactTitle(title)) {\n const looksLikeRequest = /\\?|^(hi|hello|hey)\\b|\\b(can|could|would) you\\b|\\b(build|make|create|design)\\b/i.test(\n title,\n );\n if (!looksLikeRequest && title.length <= 48) return title;\n const subject = title\n .replace(REQUEST_LEAD, '')\n .replace(/[?.!]+$/, '')\n .trim();\n if (subject.length >= 3 && subject !== title) {\n const short = subject.length > 40 ? `${subject.slice(0, 40).replace(/\\s+\\S*$/, '')}…` : subject;\n return short[0].toUpperCase() + short.slice(1);\n }\n }\n return host || fallback;\n}\n\n/** The live site a one-tap publish updates: its platform name and own domain. Null when it is not live. */\nexport function republishTarget(site: {\n liveUrl?: string | null;\n}): { projectName: string; customDomain?: string } | null {\n const host = hostOf(site.liveUrl);\n if (!host) return null;\n const projectName = platformProjectName(site.liveUrl);\n if (projectName) return { projectName };\n return 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 // Web 0.20.5: no restore point line, and no sandbox preview address (the sheet is not where it is opened).\n // Without the agent's tool-call rows (web 0.20.1 `finalAnswerText`).\n const text = withoutRestorePointLine(parseToolActivity(stripAskUser(String(reply ?? '')), false).text)\n .text.replace(/\\n\\s*\\**\\s*Next steps?\\s*\\**\\s*:[\\s\\S]*$/i, '')\n .replace(/\\s*\\(\\s*(?:live\\s+)?preview:?\\s+https?:\\/\\/\\S+?\\)/gi, '')\n .replace(/^[ \\t]*(?:live\\s+)?preview:?\\s+https?:\\/\\/\\S+[ \\t]*$/gim, '')\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;\n// Combining marks and variation selectors are the point: they are what gets removed (the gateway's own table).\nconst INVISIBLE_RE =\n // eslint-disable-next-line no-misleading-character-class\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 // A constructor on purpose: a literal with `\\\\p{…}` would fail to parse on an engine without it.\n // eslint-disable-next-line prefer-regex-literals\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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAcA,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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,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
+ {"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 { stripConnectorConnect } from '../chat/connectRequest';\nimport { stripAskUser } from '../../../chat/askUser';\nimport { isGenericTitle as isGenericArtifactTitle } from '../../buildFragments';\nimport { withoutRestorePointLine } from '../../webbuilderPrompts';\nimport { parseToolActivity } from '../../../chat/toolActivity';\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. */\n/**\n * For the agent only: this turn came from the photo page (also when only words were sent, web 0.20.1), and what the\n * files are, so none is mistaken for a design to copy. `publish=yes` only when the person ticked it for a live site.\n */\nexport function siteMediaNote({ photos, videos }: MediaCounts, opts: { publish?: boolean } = {}): string {\n return `[Site media] photos=${photos} videos=${videos}${opts.publish ? ' publish=yes' : ''}`;\n}\n\n/** Hosts the platform gives sites (not a name the owner chose). */\nconst PLATFORM_HOST = /\\.(yarntra\\.com|yantra\\.app|pages\\.dev|workers\\.dev|cdebase\\.dev)$/i;\n\n/** A first chat message used as the project's title (\"hi, can you build me a website for my bakery in kurnool\"). */\nconst REQUEST_LEAD =\n /^(?:(?:hi|hello|hey)\\b[\\s,.!]*)?(?:(?:can|could|would|will) you\\s+(?:please\\s+)?|please\\s+|i\\s+(?:want|need|would like)\\s+(?:you\\s+to\\s+)?)?(?:(?:build|make|create|design|set up|start)\\s+)?(?:(?:me|us)\\s+)?(?:(?:an|a|my|the)\\s+)?(?:new\\s+)?(?:(?:simple|modern|nice|small)\\s+)?(?:(?:website|web site|site|landing page|web app|app|page)\\s+)?(?:(?:for|about|called|named)\\s+)?(?:(?:my|our|an|a|the)\\s+)?/i;\n\n/** A published project's name as words: \"rama-bakery-iail9r\" -> \"Rama Bakery\" (the random suffix dropped). */\nexport function projectDisplayName(projectName: string | null | undefined): string | null {\n const words = String(projectName ?? '')\n .toLowerCase()\n .split(/[-_\\s]+/)\n .filter(Boolean);\n const last = words[words.length - 1] ?? '';\n if (words.length > 1 && /^[a-z0-9]{5,8}$/.test(last) && /\\d/.test(last)) words.pop();\n const name = words\n .filter((w) => !/^\\d+$/.test(w))\n .map((w) => w[0].toUpperCase() + w.slice(1))\n .join(' ');\n return name.length >= 3 ? name : null;\n}\n\nconst hostOf = (url: string | null | undefined) =>\n String(url ?? '')\n .replace(/^https?:\\/\\//i, '')\n .split(/[/?#]/)[0]\n .toLowerCase();\n\n/** The project name a live address on the platform was published under (`<name>.yarntra.com`), or null. */\nfunction platformProjectName(liveUrl: string | null | undefined): string | null {\n const m = /^([a-z0-9-]+)\\.(?:yarntra\\.com|pages\\.dev)$/.exec(hostOf(liveUrl));\n return m ? m[1] : null;\n}\n\n/**\n * A name people recognise for the site (web 0.20.1 `siteName`): its own domain, its published name, a real project\n * name, or the subject of the request it began with - never the chat prompt itself.\n */\nexport function siteName(site: { title?: string | null; liveUrl?: string | null }, fallback: string): string {\n const host = hostOf(site.liveUrl);\n if (host && !PLATFORM_HOST.test(host)) return host.replace(/^www\\./, '');\n const published = projectDisplayName(platformProjectName(site.liveUrl));\n if (published) return published;\n const title = String(site.title ?? '')\n .replace(/\\s+/g, ' ')\n .trim();\n if (title && !isGenericArtifactTitle(title)) {\n const looksLikeRequest = /\\?|^(hi|hello|hey)\\b|\\b(can|could|would) you\\b|\\b(build|make|create|design)\\b/i.test(\n title,\n );\n if (!looksLikeRequest && title.length <= 48) return title;\n const subject = title\n .replace(REQUEST_LEAD, '')\n .replace(/[?.!]+$/, '')\n .trim();\n if (subject.length >= 3 && subject !== title) {\n const short = subject.length > 40 ? `${subject.slice(0, 40).replace(/\\s+\\S*$/, '')}…` : subject;\n return short[0].toUpperCase() + short.slice(1);\n }\n }\n return host || fallback;\n}\n\n/** The live site a one-tap publish updates: its platform name and own domain. Null when it is not live. */\nexport function republishTarget(site: {\n liveUrl?: string | null;\n}): { projectName: string; customDomain?: string } | null {\n const host = hostOf(site.liveUrl);\n if (!host) return null;\n const projectName = platformProjectName(site.liveUrl);\n if (projectName) return { projectName };\n return 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 // Web 0.20.5: no restore point line, and no sandbox preview address (the sheet is not where it is opened).\n // Without the agent's tool-call rows (web 0.20.1 `finalAnswerText`).\n // A connect request is the Connect card under the words, never words itself (web 0.20.14).\n const text = withoutRestorePointLine(\n parseToolActivity(stripAskUser(stripConnectorConnect(String(reply ?? ''))), false).text,\n )\n .text.replace(/\\n\\s*\\**\\s*Next steps?\\s*\\**\\s*:[\\s\\S]*$/i, '')\n .replace(/\\s*\\(\\s*(?:live\\s+)?preview:?\\s+https?:\\/\\/\\S+?\\)/gi, '')\n .replace(/^[ \\t]*(?:live\\s+)?preview:?\\s+https?:\\/\\/\\S+[ \\t]*$/gim, '')\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;\n// Combining marks and variation selectors are the point: they are what gets removed (the gateway's own table).\nconst INVISIBLE_RE =\n // eslint-disable-next-line no-misleading-character-class\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 // A constructor on purpose: a literal with `\\\\p{…}` would fail to parse on an engine without it.\n // eslint-disable-next-line prefer-regex-literals\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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAeA,MAAM,YAAe,GAAA,QAAA;AACrB,MAAM,WAAc,GAAA,OAAA;AAEpB,MAAM,WAAA,GAAc,CAAC,IAAA,EAAM,OAAO,CAAA;AAClC,SAAS,Q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,SAAS,MAAQ,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"}
@@ -0,0 +1,191 @@
1
+ import {utf8}from'../../../canvas/elements/zipRead.js';import {readZipDirectory,readZipEntry}from'./zipRandomAccess.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
+ const EXPORT_MAX_BYTES = 400 * 1024 * 1024;
21
+ const EXPORT_MAX_ITEMS = 200;
22
+ const PHOTO = /\.(jpe?g|png|webp|gif)$/i;
23
+ const VIDEO = /\.(mp4|mov|m4v|webm)$/i;
24
+ const PRIVATE = /(?:^|\/)(messages|inbox|message_requests|archived_threads|filtered_threads|e2ee_cutover|direct|security_and_login_information|logged_information|ads_information|apps_and_websites)(?:\/|$)/i;
25
+ const POSTED = /(?:^|\/)(posts|photos_and_videos|media|albums|your_photos|your_videos|reels|stories|profile_photos|cover_photos)(?:\/|$)/i;
26
+ const TOO_BIG_MESSAGE = `That file is over ${EXPORT_MAX_BYTES / (1024 * 1024)} MB. Download "Photos and videos" only, at medium quality, or pick one part of the download at a time.`;
27
+ function strictUtf8(bytes) {
28
+ for (let i = 0; i < bytes.length; ) {
29
+ const b = bytes[i];
30
+ let extra = 0;
31
+ if (b < 128) extra = 0;
32
+ else if (b >= 194 && b < 224) extra = 1;
33
+ else if (b >= 224 && b < 240) extra = 2;
34
+ else if (b >= 240 && b < 245) extra = 3;
35
+ else return null;
36
+ for (let k = 1; k <= extra; k++) if (i + k >= bytes.length || (bytes[i + k] & 192) !== 128) return null;
37
+ i += extra + 1;
38
+ }
39
+ return utf8(bytes);
40
+ }
41
+ function fixMojibake(s) {
42
+ var _a;
43
+ if (!/[Â-ô][\u0080-¿]/.test(s)) return s;
44
+ const chars = Array.from(s);
45
+ if (chars.some((c) => c.charCodeAt(0) > 255)) return s;
46
+ return (_a = strictUtf8(Uint8Array.from(chars.map((c) => c.charCodeAt(0))))) != null ? _a : s;
47
+ }
48
+ function exportSource(names) {
49
+ if (names.some((n) => /(^|\/)(your_instagram_activity|instagram)/i.test(n) || /(^|\/)media\/(posts|reels)\/\d{6}\//i.test(n))) return "instagram";
50
+ if (names.some((n) => /(^|\/)(your_facebook_activity|your_activity_across_facebook|photos_and_videos|this_profile's_activity_across_facebook)/i.test(n))) return "facebook";
51
+ if (names.some((n) => /(^|\/)posts\/(media|your_posts)/i.test(n))) return "facebook";
52
+ return null;
53
+ }
54
+ function folderDate(path) {
55
+ const m = path.match(/(?:^|\/)(20\d{2})(0[1-9]|1[0-2])(?:\/|$)/);
56
+ return m ? Math.floor(Date.UTC(Number(m[1]), Number(m[2]) - 1, 1) / 1e3) : null;
57
+ }
58
+ function textOf(o) {
59
+ for (const k of ["description", "post", "title"]) {
60
+ const v = o[k];
61
+ if (typeof v === "string" && v.trim()) return fixMojibake(v).trim();
62
+ }
63
+ return "";
64
+ }
65
+ function timeOf(o) {
66
+ for (const k of ["creation_timestamp", "timestamp", "taken_at"]) if (typeof o[k] === "number") return o[k];
67
+ return null;
68
+ }
69
+ function captionsFromJson(json) {
70
+ const out = /* @__PURE__ */ new Map();
71
+ const walk = (v, ctx, depth) => {
72
+ var _a;
73
+ if (depth > 12 || v === null || typeof v !== "object") return;
74
+ if (Array.isArray(v)) {
75
+ for (const x of v) walk(x, ctx, depth + 1);
76
+ return;
77
+ }
78
+ const o = v;
79
+ let here = {
80
+ caption: textOf(o) || ctx.caption,
81
+ takenAt: (_a = timeOf(o)) != null ? _a : ctx.takenAt
82
+ };
83
+ if (Array.isArray(o.data)) {
84
+ for (const d of o.data) {
85
+ const post = d && typeof d === "object" ? d.post : void 0;
86
+ if (typeof post === "string") here = __spreadProps(__spreadValues({}, here), {
87
+ caption: fixMojibake(post).trim() || here.caption
88
+ });
89
+ }
90
+ }
91
+ if (typeof o.uri === "string" && (PHOTO.test(o.uri) || VIDEO.test(o.uri)) && !out.has(o.uri)) out.set(o.uri, here);
92
+ for (const [k, x] of Object.entries(o)) if (k !== "uri") walk(x, here, depth + 1);
93
+ };
94
+ walk(json, {
95
+ caption: "",
96
+ takenAt: null
97
+ }, 0);
98
+ return out;
99
+ }
100
+ function mediaKind(path) {
101
+ if (PHOTO.test(path)) return "photo";
102
+ if (VIDEO.test(path)) return "video";
103
+ return null;
104
+ }
105
+ function listExportMedia(entries, captions) {
106
+ var _a, _b, _c;
107
+ const media = [];
108
+ for (const e of entries) {
109
+ const path = e.name;
110
+ if (path.endsWith("/") || /(?:^|\/)__MACOSX\//.test(path)) continue;
111
+ const kind = mediaKind(path);
112
+ if (!kind || PRIVATE.test(path) || !POSTED.test(path)) continue;
113
+ if (kind === "photo" && (e.size || 0) < 8 * 1024) continue;
114
+ const known = (_b = captions.get(path)) != null ? _b : (_a = [...captions.entries()].find(([uri]) => path.endsWith(`/${uri}`))) == null ? void 0 : _a[1];
115
+ media.push({
116
+ path,
117
+ name: path.split("/").pop() || "photo.jpg",
118
+ size: e.size || 0,
119
+ kind,
120
+ takenAt: (_c = known == null ? void 0 : known.takenAt) != null ? _c : folderDate(path),
121
+ caption: ((known == null ? void 0 : known.caption) || "").slice(0, 500)
122
+ });
123
+ }
124
+ media.sort((a, b) => {
125
+ var _a2, _b2;
126
+ return ((_a2 = b.takenAt) != null ? _a2 : 0) - ((_b2 = a.takenAt) != null ? _b2 : 0) || a.path.localeCompare(b.path);
127
+ });
128
+ return media;
129
+ }
130
+ const JSON_NAME = /(?:^|\/)(posts|content|photos_and_videos|albums|media)[^.]*?\.json$|(?:^|\/)(your_posts|posts|reels|stories|album)[^/]*\.json$/i;
131
+ async function readSocialExport(reader) {
132
+ if (reader.size > EXPORT_MAX_BYTES) return {
133
+ ok: false,
134
+ message: TOO_BIG_MESSAGE
135
+ };
136
+ const entries = await readZipDirectory(reader);
137
+ if (!entries) return {
138
+ ok: false,
139
+ message: "That isn't a zip we can read. Pick the .zip Facebook or Instagram emailed you."
140
+ };
141
+ const source = exportSource(entries.map((e) => e.name));
142
+ if (!source) return {
143
+ ok: false,
144
+ message: "This zip isn't a Facebook or Instagram download. Use Settings \u2192 Download your information there."
145
+ };
146
+ const captions = /* @__PURE__ */ new Map();
147
+ for (const e of entries) {
148
+ if (!JSON_NAME.test(e.name) || PRIVATE.test(e.name) || e.size > 20 * 1024 * 1024) continue;
149
+ const data = await readZipEntry(reader, e);
150
+ if (!data) continue;
151
+ try {
152
+ for (const [k, v] of captionsFromJson(JSON.parse(utf8(data)))) if (!captions.has(k)) captions.set(k, v);
153
+ } catch (e2) {
154
+ }
155
+ }
156
+ const all = listExportMedia(entries, captions);
157
+ if (!all.length) {
158
+ return {
159
+ ok: false,
160
+ message: 'No posted photos or videos in this download. In "Download your information", include "Photos and videos" (Facebook) or "Media" (Instagram).'
161
+ };
162
+ }
163
+ return {
164
+ ok: true,
165
+ source,
166
+ media: all.slice(0, EXPORT_MAX_ITEMS),
167
+ total: all.length,
168
+ entries
169
+ };
170
+ }
171
+ const TYPES = {
172
+ jpg: "image/jpeg",
173
+ jpeg: "image/jpeg",
174
+ png: "image/png",
175
+ webp: "image/webp",
176
+ gif: "image/gif",
177
+ mp4: "video/mp4",
178
+ mov: "video/quicktime",
179
+ m4v: "video/mp4",
180
+ webm: "video/webm"
181
+ };
182
+ function exportMediaType(name) {
183
+ return TYPES[(name.split(".").pop() || "").toLowerCase()] || "application/octet-stream";
184
+ }
185
+ async function exportMediaBytes(reader, entries, item) {
186
+ const entry = entries.find((e) => e.name === item.path);
187
+ return entry ? readZipEntry(reader, entry) : null;
188
+ }
189
+ function pickLimitText(room) {
190
+ return `Pick up to ${room} ${room === 1 ? "photo" : "photos"}.`;
191
+ }export{EXPORT_MAX_BYTES,EXPORT_MAX_ITEMS,TOO_BIG_MESSAGE,captionsFromJson,exportMediaBytes,exportMediaType,exportSource,fixMojibake,listExportMedia,pickLimitText,readSocialExport};//# sourceMappingURL=socialExport.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"socialExport.js","sources":["../../../../../src/features/webbuilder/web/upload/socialExport.ts"],"sourcesContent":["/**\n * Photos from a Facebook or Instagram \"Download your information\" zip, for the upload sheet (web 0.20.14\n * `upload/socialExport`).\n *\n * Works for anyone, with no Facebook login and no Meta app: the owner downloads their own data and picks it here.\n * Only posted media is offered (posts, albums, Page photos, Instagram posts and reels); messages are never read.\n * Captions and dates come from the export's JSON files when they mention the file. The zip is read in pieces\n * (`zipRandomAccess`), never whole. Pure.\n */\nimport { utf8 } from '../../../canvas/elements/zipRead';\nimport { readZipDirectory, readZipEntry, type ZipEntry, type ZipReader } from './zipRandomAccess';\n\n/** Exports are split into parts by Facebook; one part is read at a time. */\nexport const EXPORT_MAX_BYTES = 400 * 1024 * 1024;\n/** Most-recent first; more than this is too many to pick from on a phone. */\nexport const EXPORT_MAX_ITEMS = 200;\n\nconst PHOTO = /\\.(jpe?g|png|webp|gif)$/i;\nconst VIDEO = /\\.(mp4|mov|m4v|webm)$/i;\n/** Private conversations and account files: never offered. */\nconst PRIVATE =\n /(?:^|\\/)(messages|inbox|message_requests|archived_threads|filtered_threads|e2ee_cutover|direct|security_and_login_information|logged_information|ads_information|apps_and_websites)(?:\\/|$)/i;\n/** Where posted media lives in the two exports (old and new layouts). */\nconst POSTED =\n /(?:^|\\/)(posts|photos_and_videos|media|albums|your_photos|your_videos|reels|stories|profile_photos|cover_photos)(?:\\/|$)/i;\n\nexport type ExportSource = 'facebook' | 'instagram';\n\nexport interface ExportMedia {\n /** The path inside the zip. */\n path: string;\n /** A file name for the upload. */\n name: string;\n size: number;\n kind: 'photo' | 'video';\n /** Unix seconds, when the export says when it was posted. */\n takenAt: number | null;\n caption: string;\n}\n\nexport type SocialExport =\n | { ok: true; source: ExportSource; media: ExportMedia[]; total: number; entries: ZipEntry[] }\n | { ok: false; message: string };\n\nexport const TOO_BIG_MESSAGE = `That file is over ${EXPORT_MAX_BYTES / (1024 * 1024)} MB. Download \"Photos and videos\" only, at medium quality, or pick one part of the download at a time.`;\n\n/** Strict UTF-8: null when the bytes are not valid UTF-8 (the web's `TextDecoder('utf-8', { fatal: true })`). */\nfunction strictUtf8(bytes: Uint8Array): string | null {\n for (let i = 0; i < bytes.length; ) {\n const b = bytes[i];\n let extra = 0;\n if (b < 0x80) extra = 0;\n else if (b >= 0xc2 && b < 0xe0) extra = 1;\n else if (b >= 0xe0 && b < 0xf0) extra = 2;\n else if (b >= 0xf0 && b < 0xf5) extra = 3;\n else return null;\n for (let k = 1; k <= extra; k++) if (i + k >= bytes.length || (bytes[i + k] & 0xc0) !== 0x80) return null;\n i += extra + 1;\n }\n return utf8(bytes);\n}\n\n/** Facebook writes UTF-8 text as Latin-1 escapes (\"Café\"); this reads it back as written. */\nexport function fixMojibake(s: string): string {\n if (!/[Â-ô][\\u0080-¿]/.test(s)) return s;\n const chars = Array.from(s);\n if (chars.some((c) => c.charCodeAt(0) > 0xff)) return s;\n return strictUtf8(Uint8Array.from(chars.map((c) => c.charCodeAt(0)))) ?? s;\n}\n\nexport function exportSource(names: readonly string[]): ExportSource | null {\n if (\n names.some(\n (n) =>\n /(^|\\/)(your_instagram_activity|instagram)/i.test(n) || /(^|\\/)media\\/(posts|reels)\\/\\d{6}\\//i.test(n),\n )\n )\n return 'instagram';\n if (\n names.some((n) =>\n /(^|\\/)(your_facebook_activity|your_activity_across_facebook|photos_and_videos|this_profile's_activity_across_facebook)/i.test(\n n,\n ),\n )\n )\n return 'facebook';\n if (names.some((n) => /(^|\\/)posts\\/(media|your_posts)/i.test(n))) return 'facebook';\n return null;\n}\n\n/** Folder dates like media/posts/202411/ -> unix seconds of that month. */\nfunction folderDate(path: string): number | null {\n const m = path.match(/(?:^|\\/)(20\\d{2})(0[1-9]|1[0-2])(?:\\/|$)/);\n return m ? Math.floor(Date.UTC(Number(m[1]), Number(m[2]) - 1, 1) / 1000) : null;\n}\n\ntype Caption = { caption: string; takenAt: number | null };\n\nfunction textOf(o: Record<string, unknown>): string {\n for (const k of ['description', 'post', 'title']) {\n const v = o[k];\n if (typeof v === 'string' && v.trim()) return fixMojibake(v).trim();\n }\n return '';\n}\n\nfunction timeOf(o: Record<string, unknown>): number | null {\n for (const k of ['creation_timestamp', 'timestamp', 'taken_at'])\n if (typeof o[k] === 'number') return o[k] as number;\n return null;\n}\n\n/** The uri -> {caption, takenAt} pairs in any export JSON: the nearest title/description/post and timestamp. */\nexport function captionsFromJson(json: unknown): Map<string, Caption> {\n const out = new Map<string, Caption>();\n const walk = (v: unknown, ctx: Caption, depth: number) => {\n if (depth > 12 || v === null || typeof v !== 'object') return;\n if (Array.isArray(v)) {\n for (const x of v) walk(x, ctx, depth + 1);\n return;\n }\n const o = v as Record<string, unknown>;\n // Post-level text: \"post\" in data[] belongs to the whole post; read data[] first so attachments inherit it.\n let here: Caption = { caption: textOf(o) || ctx.caption, takenAt: timeOf(o) ?? ctx.takenAt };\n if (Array.isArray(o.data)) {\n for (const d of o.data) {\n const post = d && typeof d === 'object' ? (d as Record<string, unknown>).post : undefined;\n if (typeof post === 'string') here = { ...here, caption: fixMojibake(post).trim() || here.caption };\n }\n }\n if (typeof o.uri === 'string' && (PHOTO.test(o.uri) || VIDEO.test(o.uri)) && !out.has(o.uri))\n out.set(o.uri, here);\n for (const [k, x] of Object.entries(o)) if (k !== 'uri') walk(x, here, depth + 1);\n };\n walk(json, { caption: '', takenAt: null }, 0);\n return out;\n}\n\nfunction mediaKind(path: string): 'photo' | 'video' | null {\n if (PHOTO.test(path)) return 'photo';\n if (VIDEO.test(path)) return 'video';\n return null;\n}\n\n/** The media the export holds, newest first (pure: entry names and the captions found). */\nexport function listExportMedia(\n entries: ReadonlyArray<Pick<ZipEntry, 'name' | 'size'>>,\n captions: Map<string, Caption>,\n): ExportMedia[] {\n const media: ExportMedia[] = [];\n for (const e of entries) {\n const path = e.name;\n if (path.endsWith('/') || /(?:^|\\/)__MACOSX\\//.test(path)) continue;\n const kind = mediaKind(path);\n if (!kind || PRIVATE.test(path) || !POSTED.test(path)) continue;\n // Icons and stickers are tiny; a posted photo is not.\n if (kind === 'photo' && (e.size || 0) < 8 * 1024) continue;\n // JSON uris are relative to the export root; the zip may wrap everything in one folder.\n const known = captions.get(path) ?? [...captions.entries()].find(([uri]) => path.endsWith(`/${uri}`))?.[1];\n media.push({\n path,\n name: path.split('/').pop() || 'photo.jpg',\n size: e.size || 0,\n kind,\n takenAt: known?.takenAt ?? folderDate(path),\n caption: (known?.caption || '').slice(0, 500),\n });\n }\n media.sort((a, b) => (b.takenAt ?? 0) - (a.takenAt ?? 0) || a.path.localeCompare(b.path));\n return media;\n}\n\nconst JSON_NAME =\n /(?:^|\\/)(posts|content|photos_and_videos|albums|media)[^.]*?\\.json$|(?:^|\\/)(your_posts|posts|reels|stories|album)[^/]*\\.json$/i;\n\n/** Reads the zip: which network it came from and every posted photo and video in it. */\nexport async function readSocialExport(reader: ZipReader): Promise<SocialExport> {\n if (reader.size > EXPORT_MAX_BYTES) return { ok: false, message: TOO_BIG_MESSAGE };\n const entries = await readZipDirectory(reader);\n if (!entries)\n return { ok: false, message: \"That isn't a zip we can read. Pick the .zip Facebook or Instagram emailed you.\" };\n const source = exportSource(entries.map((e) => e.name));\n if (!source)\n return {\n ok: false,\n message: \"This zip isn't a Facebook or Instagram download. Use Settings → Download your information there.\",\n };\n const captions = new Map<string, Caption>();\n for (const e of entries) {\n if (!JSON_NAME.test(e.name) || PRIVATE.test(e.name) || e.size > 20 * 1024 * 1024) continue;\n const data = await readZipEntry(reader, e);\n if (!data) continue;\n try {\n for (const [k, v] of captionsFromJson(JSON.parse(utf8(data)))) if (!captions.has(k)) captions.set(k, v);\n } catch {\n /* not JSON we understand: dates fall back to folder names */\n }\n }\n const all = listExportMedia(entries, captions);\n if (!all.length) {\n return {\n ok: false,\n message:\n 'No posted photos or videos in this download. In \"Download your information\", include \"Photos and videos\" (Facebook) or \"Media\" (Instagram).',\n };\n }\n return { ok: true, source, media: all.slice(0, EXPORT_MAX_ITEMS), total: all.length, entries };\n}\n\nconst TYPES: Record<string, string> = {\n jpg: 'image/jpeg',\n jpeg: 'image/jpeg',\n png: 'image/png',\n webp: 'image/webp',\n gif: 'image/gif',\n mp4: 'video/mp4',\n mov: 'video/quicktime',\n m4v: 'video/mp4',\n webm: 'video/webm',\n};\n\nexport function exportMediaType(name: string): string {\n return TYPES[(name.split('.').pop() || '').toLowerCase()] || 'application/octet-stream';\n}\n\n/** One picked item's bytes, ready to go the way a photo picked from the phone goes. */\nexport async function exportMediaBytes(\n reader: ZipReader,\n entries: readonly ZipEntry[],\n item: ExportMedia,\n): Promise<Uint8Array | null> {\n const entry = entries.find((e) => e.name === item.path);\n return entry ? readZipEntry(reader, entry) : null;\n}\n\n/** \"Pick up to 9 photos\" (the phone sends photos only: the upload sheet has no video picker). */\nexport function pickLimitText(room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;AACR,CAAA;AACO,SAAS,gBAAgB,IAAsB,EAAA;AACpD,EAAO,OAAA,KAAA,CAAA,CAAO,IAAK,CAAA,KAAA,CAAM,GAAG,CAAA,CAAE,KAAS,IAAA,EAAA,EAAI,WAAY,EAAC,CAAK,IAAA,0BAAA;AAC/D;AAGsB,eAAA,gBAAA,CAAiB,MAAmB,EAAA,OAAA,EAA8B,IAA+C,EAAA;AACrI,EAAA,MAAM,QAAQ,OAAQ,CAAA,IAAA,CAAK,OAAK,CAAE,CAAA,IAAA,KAAS,KAAK,IAAI,CAAA;AACpD,EAAA,OAAO,KAAQ,GAAA,YAAA,CAAa,MAAQ,EAAA,KAAK,CAAI,GAAA,IAAA;AAC/C;AAGO,SAAS,cAAc,IAAsB,EAAA;AAClD,EAAA,OAAO,cAAc,IAAI,CAAA,CAAA,EAAI,IAAS,KAAA,CAAA,GAAI,UAAU,QAAQ,CAAA,CAAA,CAAA;AAC9D"}
@@ -0,0 +1,64 @@
1
+ import {utf8,inflateRaw}from'../../../canvas/elements/zipRead.js';const EOCD_SIG = 101010256;
2
+ const CENTRAL_SIG = 33639248;
3
+ const LOCAL_SIG = 67324752;
4
+ const TAIL = 65535 + 22;
5
+ const MAX_ENTRY_BYTES = 64 * 1024 * 1024;
6
+ const u16 = (b, at) => b[at] | b[at + 1] << 8;
7
+ const u32 = (b, at) => (b[at] | b[at + 1] << 8 | b[at + 2] << 16 | b[at + 3] << 24) >>> 0;
8
+ function latin1(bytes) {
9
+ let out = "";
10
+ for (let i = 0; i < bytes.length; i++) out += String.fromCharCode(bytes[i]);
11
+ return out;
12
+ }
13
+ async function readZipDirectory(reader) {
14
+ if (reader.size < 22) return null;
15
+ const tailStart = Math.max(0, reader.size - TAIL);
16
+ const tail = await reader.read(tailStart, reader.size - tailStart);
17
+ let eocd = -1;
18
+ for (let i = tail.length - 22; i >= 0; i--) {
19
+ if (u32(tail, i) === EOCD_SIG) {
20
+ eocd = i;
21
+ break;
22
+ }
23
+ }
24
+ if (eocd < 0) return null;
25
+ const count = u16(tail, eocd + 10);
26
+ const dirSize = u32(tail, eocd + 12);
27
+ const dirOffset = u32(tail, eocd + 16);
28
+ if (dirOffset === 4294967295 || dirOffset + dirSize > reader.size) return null;
29
+ const dir = await reader.read(dirOffset, dirSize);
30
+ const entries = [];
31
+ let at = 0;
32
+ for (let n = 0; n < count; n++) {
33
+ if (at + 46 > dir.length || u32(dir, at) !== CENTRAL_SIG) break;
34
+ const flags = u16(dir, at + 8);
35
+ const nameLen = u16(dir, at + 28);
36
+ const extraLen = u16(dir, at + 30);
37
+ const commentLen = u16(dir, at + 32);
38
+ const raw = dir.subarray(at + 46, at + 46 + nameLen);
39
+ entries.push({
40
+ name: flags & 2048 ? utf8(raw) : latin1(raw),
41
+ method: u16(dir, at + 10),
42
+ compressedSize: u32(dir, at + 20),
43
+ size: u32(dir, at + 24),
44
+ localOffset: u32(dir, at + 42)
45
+ });
46
+ at += 46 + nameLen + extraLen + commentLen;
47
+ }
48
+ return entries;
49
+ }
50
+ async function readZipEntry(reader, entry) {
51
+ if (entry.size > MAX_ENTRY_BYTES || entry.compressedSize > MAX_ENTRY_BYTES) return null;
52
+ if (entry.method !== 0 && entry.method !== 8) return null;
53
+ const head = await reader.read(entry.localOffset, 30);
54
+ if (head.length < 30 || u32(head, 0) !== LOCAL_SIG || u16(head, 6) & 1) return null;
55
+ const start = entry.localOffset + 30 + u16(head, 26) + u16(head, 28);
56
+ const data = await reader.read(start, entry.compressedSize);
57
+ if (data.length < entry.compressedSize) return null;
58
+ if (entry.method === 0) return data;
59
+ try {
60
+ return inflateRaw(data);
61
+ } catch (e) {
62
+ return null;
63
+ }
64
+ }export{MAX_ENTRY_BYTES,readZipDirectory,readZipEntry};//# sourceMappingURL=zipRandomAccess.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"zipRandomAccess.js","sources":["../../../../../src/features/webbuilder/web/upload/zipRandomAccess.ts"],"sourcesContent":["/**\n * A zip read in pieces: the central directory, then only the entries asked for (web `chat/zipEntries`). A\n * Facebook download can be hundreds of megabytes, which a phone cannot hold as one JavaScript string, so every\n * read goes through `reader` (a byte range of the file). Stored and raw-DEFLATE entries; no zip64, no encryption.\n * Inflate is the app's own (`canvas/elements/zipRead`): Hermes has no DecompressionStream. Pure.\n */\nimport { inflateRaw, utf8 } from '../../../canvas/elements/zipRead';\n\nexport interface ZipReader {\n /** The file's size in bytes. */\n size: number;\n /** `length` bytes from `offset` (fewer only at the end of the file). */\n read: (offset: number, length: number) => Promise<Uint8Array>;\n}\n\nexport interface ZipEntry {\n name: string;\n method: number;\n compressedSize: number;\n size: number;\n localOffset: number;\n}\n\nconst EOCD_SIG = 0x06054b50;\nconst CENTRAL_SIG = 0x02014b50;\nconst LOCAL_SIG = 0x04034b50;\n/** The end record sits in the last 64 KB plus its own 22 bytes. */\nconst TAIL = 0xffff + 22;\n/** An entry bigger than this is never inflated in memory (a zip bomb, or a video too big to send). */\nexport const MAX_ENTRY_BYTES = 64 * 1024 * 1024;\n\nconst u16 = (b: Uint8Array, at: number) => b[at] | (b[at + 1] << 8);\nconst u32 = (b: Uint8Array, at: number) => (b[at] | (b[at + 1] << 8) | (b[at + 2] << 16) | (b[at + 3] << 24)) >>> 0;\n\n/** Latin-1 (CP437 for the ASCII range): names without the UTF-8 flag. */\nfunction latin1(bytes: Uint8Array): string {\n let out = '';\n for (let i = 0; i < bytes.length; i++) out += String.fromCharCode(bytes[i]);\n return out;\n}\n\n/** The entries, or null when this isn't a zip this reader can open. */\nexport async function readZipDirectory(reader: ZipReader): Promise<ZipEntry[] | null> {\n if (reader.size < 22) return null;\n const tailStart = Math.max(0, reader.size - TAIL);\n const tail = await reader.read(tailStart, reader.size - tailStart);\n let eocd = -1;\n for (let i = tail.length - 22; i >= 0; i--) {\n if (u32(tail, i) === EOCD_SIG) {\n eocd = i;\n break;\n }\n }\n if (eocd < 0) return null;\n const count = u16(tail, eocd + 10);\n const dirSize = u32(tail, eocd + 12);\n const dirOffset = u32(tail, eocd + 16);\n // zip64 marks these 0xffff / 0xffffffff: not read here (an export part is under 4 GB and 65k files).\n if (dirOffset === 0xffffffff || dirOffset + dirSize > reader.size) return null;\n const dir = await reader.read(dirOffset, dirSize);\n const entries: ZipEntry[] = [];\n let at = 0;\n for (let n = 0; n < count; n++) {\n if (at + 46 > dir.length || u32(dir, at) !== CENTRAL_SIG) break;\n const flags = u16(dir, at + 8);\n const nameLen = u16(dir, at + 28);\n const extraLen = u16(dir, at + 30);\n const commentLen = u16(dir, at + 32);\n const raw = dir.subarray(at + 46, at + 46 + nameLen);\n entries.push({\n name: flags & 0x0800 ? utf8(raw) : latin1(raw),\n method: u16(dir, at + 10),\n compressedSize: u32(dir, at + 20),\n size: u32(dir, at + 24),\n localOffset: u32(dir, at + 42),\n });\n at += 46 + nameLen + extraLen + commentLen;\n }\n return entries;\n}\n\n/** One entry's bytes; null when it is missing, encrypted, too big or uses another compression method. */\nexport async function readZipEntry(reader: ZipReader, entry: ZipEntry): Promise<Uint8Array | null> {\n if (entry.size > MAX_ENTRY_BYTES || entry.compressedSize > MAX_ENTRY_BYTES) return null;\n if (entry.method !== 0 && entry.method !== 8) return null;\n const head = await reader.read(entry.localOffset, 30);\n if (head.length < 30 || u32(head, 0) !== LOCAL_SIG || u16(head, 6) & 0x0001) return null;\n const start = entry.localOffset + 30 + u16(head, 26) + u16(head, 28);\n const data = await reader.read(start, entry.compressedSize);\n if (data.length < entry.compressedSize) return null;\n if (entry.method === 0) return data;\n try {\n return inflateRaw(data);\n } catch {\n return null;\n }\n}\n\n/** A reader over bytes already in memory (tests, small files). */\nexport function bytesReader(bytes: Uint8Array): ZipReader {\n return {\n size: bytes.length,\n read: async (offset, length) => bytes.subarray(offset, Math.min(bytes.length, offset + length)),\n };\n}\n"],"names":[],"mappings":"kEAoBA,MAAM,QAAW,GAAA,SAAA;AACjB,MAAM,WAAc,GAAA,QAAA;AACpB,MAAM,SAAY,GAAA,QAAA;AAElB,MAAM,OAAO,KAAS,GAAA,EAAA;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AA,CAAA,EAAU,OAAA,IAAA;AAC/B,EAAI,IAAA;AACF,IAAA,OAAO,WAAW,IAAI,CAAA;AAAA,GAChB,CAAA,OAAA,CAAA,EAAA;AACN,IAAO,OAAA,IAAA;AAAA;AAEX"}
@@ -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 {createGithubConnectService}from'./github/githubConnectApi.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 {createCoverRequester}from'./project/coverRequest.js';import {CLOUDFLARE_PROJECT_QUERY,siteFromLookup}from'./project/deleteFlow.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;
@@ -273,7 +273,9 @@ function createWebServices(opts) {
273
273
  disable: (project) => disableSiteMail(gql, project.channelId)
274
274
  }
275
275
  };
276
- const sharing = createSharingService((document, variables) => /^\s*mutation\b/.test(document) ? transport.mutate(document, variables) : transport.query(document, variables));
276
+ const runDocument = (document, variables) => /^\s*mutation\b/.test(document) ? transport.mutate(document, variables) : transport.query(document, variables);
277
+ const sharing = createSharingService(runDocument);
278
+ const requestCover = createCoverRequester(runDocument);
277
279
  const serverSettings = async (channelId) => {
278
280
  var _a, _b, _c;
279
281
  const r = await transport.query(PROJECT_SETTINGS_QUERY, {
@@ -293,6 +295,26 @@ function createWebServices(opts) {
293
295
  },
294
296
  currentUserId: () => sharing.currentUserId().catch(() => null)
295
297
  });
298
+ const findPublishedSite = async (channelId, known) => {
299
+ var _a, _b;
300
+ let name = null;
301
+ let failed = false;
302
+ try {
303
+ const r = await Promise.race([transport.query(CLOUDFLARE_PROJECT_QUERY, {
304
+ channelId
305
+ }), new Promise((_, reject) => {
306
+ setTimeout(() => reject(new Error("timeout")), 1e4);
307
+ })]);
308
+ name = ((_a = r.data) == null ? void 0 : _a.aiCodeGetCloudflareProject) || null;
309
+ failed = !name && Boolean((_b = r.errors) == null ? void 0 : _b.length);
310
+ } catch (e) {
311
+ failed = true;
312
+ }
313
+ return siteFromLookup({
314
+ name,
315
+ failed
316
+ }, known);
317
+ };
296
318
  return {
297
319
  data,
298
320
  secrets,
@@ -300,6 +322,8 @@ function createWebServices(opts) {
300
322
  integrations,
301
323
  sharing,
302
324
  githubConnect,
303
- serverSettings
325
+ serverSettings,
326
+ requestCover,
327
+ findPublishedSite
304
328
  };
305
329
  }export{SITE_AGENT_URL,createWebServices};//# sourceMappingURL=webServices.js.map