@adminide-stack/yantra-mobile 12.0.163 → 12.0.164

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 (158) hide show
  1. package/lib/components/CustomDrawer.js +8 -1
  2. package/lib/components/CustomDrawer.js.map +1 -1
  3. package/lib/components/NavigationHeader/HeaderSheet.js +23 -8
  4. package/lib/components/NavigationHeader/HeaderSheet.js.map +1 -1
  5. package/lib/components/NavigationHeader/HeaderSkillsButton.js +6 -3
  6. package/lib/components/NavigationHeader/HeaderSkillsButton.js.map +1 -1
  7. package/lib/components/NavigationHeader/HeaderSystemButtons.js +7 -0
  8. package/lib/components/NavigationHeader/HeaderSystemButtons.js.map +1 -0
  9. package/lib/components/NavigationHeader/HeaderTasksButton.js +144 -93
  10. package/lib/components/NavigationHeader/HeaderTasksButton.js.map +1 -1
  11. package/lib/components/NavigationHeader/NavigationHeader.js +2 -2
  12. package/lib/components/NavigationHeader/NavigationHeader.js.map +1 -1
  13. package/lib/features/agent-chat/NativeAgentChat.js +3 -3
  14. package/lib/features/agent-chat/NativeAgentChat.js.map +1 -1
  15. package/lib/features/audio-input/AudioRecorderPanel.js +1 -1
  16. package/lib/features/audio-input/NativeDictationBar.js +1 -1
  17. package/lib/features/canvas/CanvasExperience.js +1 -1
  18. package/lib/features/channels/ConnectAppsSheet.js +1 -1
  19. package/lib/features/channels/HomeImessage.js +1 -1
  20. package/lib/features/channels/useChannelsApi.js +1 -1
  21. package/lib/features/chat/OneTimeCodePrompt.js +1 -1
  22. package/lib/features/chat/QueuedFollowUps.js +4 -3
  23. package/lib/features/chat/QueuedFollowUps.js.map +1 -1
  24. package/lib/features/chat/TemporaryChatView.js +238 -0
  25. package/lib/features/chat/TemporaryChatView.js.map +1 -0
  26. package/lib/features/chat/connectorConnect.js +1 -1
  27. package/lib/features/chat/temporaryChatStore.js +59 -7
  28. package/lib/features/chat/temporaryChatStore.js.map +1 -1
  29. package/lib/features/chat/withTemporaryChat.js +24 -0
  30. package/lib/features/chat/withTemporaryChat.js.map +1 -0
  31. package/lib/features/dictate/recorderStatus.js +22 -0
  32. package/lib/features/dictate/recorderStatus.js.map +1 -0
  33. package/lib/features/dictate/useDictationRecorder.js +4 -4
  34. package/lib/features/dictate/useDictationRecorder.js.map +1 -1
  35. package/lib/features/home/sky/HomeSky.js +1 -1
  36. package/lib/features/skills/SkillTemplatePicker.js +107 -143
  37. package/lib/features/skills/SkillTemplatePicker.js.map +1 -1
  38. package/lib/features/webbuilder/WebBuilderExperience.js +402 -33
  39. package/lib/features/webbuilder/WebBuilderExperience.js.map +1 -1
  40. package/lib/features/webbuilder/components/CloudSheet.js +35 -15
  41. package/lib/features/webbuilder/components/CloudSheet.js.map +1 -1
  42. package/lib/features/webbuilder/components/Credits.js +149 -0
  43. package/lib/features/webbuilder/components/Credits.js.map +1 -0
  44. package/lib/features/webbuilder/components/PreviewFrame.js +15 -4
  45. package/lib/features/webbuilder/components/PreviewFrame.js.map +1 -1
  46. package/lib/features/webbuilder/components/PreviewScreen.js +5 -2
  47. package/lib/features/webbuilder/components/PreviewScreen.js.map +1 -1
  48. package/lib/features/webbuilder/components/ProjectChat.js +58 -8
  49. package/lib/features/webbuilder/components/ProjectChat.js.map +1 -1
  50. package/lib/features/webbuilder/components/ProjectSheets.js +29 -6
  51. package/lib/features/webbuilder/components/ProjectSheets.js.map +1 -1
  52. package/lib/features/webbuilder/components/ProjectsScreen.js +16 -7
  53. package/lib/features/webbuilder/components/ProjectsScreen.js.map +1 -1
  54. package/lib/features/webbuilder/components/PublishSheet.js +133 -2
  55. package/lib/features/webbuilder/components/PublishSheet.js.map +1 -1
  56. package/lib/features/webbuilder/components/RetentionBanner.js +130 -0
  57. package/lib/features/webbuilder/components/RetentionBanner.js.map +1 -0
  58. package/lib/features/webbuilder/components/ShareSheet.js +265 -0
  59. package/lib/features/webbuilder/components/ShareSheet.js.map +1 -0
  60. package/lib/features/webbuilder/components/SiteStatusSheet.js +533 -0
  61. package/lib/features/webbuilder/components/SiteStatusSheet.js.map +1 -0
  62. package/lib/features/webbuilder/components/StudioHome.js +8 -1
  63. package/lib/features/webbuilder/components/StudioHome.js.map +1 -1
  64. package/lib/features/webbuilder/components/TemplateSuggestions.js +98 -0
  65. package/lib/features/webbuilder/components/TemplateSuggestions.js.map +1 -0
  66. package/lib/features/webbuilder/connectorTemplates.js +3 -3
  67. package/lib/features/webbuilder/connectorTemplates.js.map +1 -1
  68. package/lib/features/webbuilder/creditsLinks.js +5 -0
  69. package/lib/features/webbuilder/creditsLinks.js.map +1 -0
  70. package/lib/features/webbuilder/previewAccess.js +207 -0
  71. package/lib/features/webbuilder/previewAccess.js.map +1 -0
  72. package/lib/features/webbuilder/previewProbe.js +49 -1
  73. package/lib/features/webbuilder/previewProbe.js.map +1 -1
  74. package/lib/features/webbuilder/readiness.js +14 -0
  75. package/lib/features/webbuilder/readiness.js.map +1 -0
  76. package/lib/features/webbuilder/shareLink.js +26 -0
  77. package/lib/features/webbuilder/shareLink.js.map +1 -0
  78. package/lib/features/webbuilder/templateCover.js +11 -0
  79. package/lib/features/webbuilder/templateCover.js.map +1 -0
  80. package/lib/features/webbuilder/templateSuggestions.js +112 -0
  81. package/lib/features/webbuilder/templateSuggestions.js.map +1 -0
  82. package/lib/features/webbuilder/useGithubAutoSync.js +83 -0
  83. package/lib/features/webbuilder/useGithubAutoSync.js.map +1 -0
  84. package/lib/features/webbuilder/usePreviewAccess.js +61 -0
  85. package/lib/features/webbuilder/usePreviewAccess.js.map +1 -0
  86. package/lib/features/webbuilder/useWebBuilderCredits.js +99 -0
  87. package/lib/features/webbuilder/useWebBuilderCredits.js.map +1 -0
  88. package/lib/features/webbuilder/web/credits/credits.js +203 -0
  89. package/lib/features/webbuilder/web/credits/credits.js.map +1 -0
  90. package/lib/features/webbuilder/web/credits/creditsReader.js +65 -0
  91. package/lib/features/webbuilder/web/credits/creditsReader.js.map +1 -0
  92. package/lib/features/webbuilder/web/data/cloud.js +3 -3
  93. package/lib/features/webbuilder/web/data/cloud.js.map +1 -1
  94. package/lib/features/webbuilder/web/data/database.js +4 -1
  95. package/lib/features/webbuilder/web/data/database.js.map +1 -1
  96. package/lib/features/webbuilder/web/github/autoSync.js +231 -0
  97. package/lib/features/webbuilder/web/github/autoSync.js.map +1 -0
  98. package/lib/features/webbuilder/web/github/autoSyncEngine.js +367 -0
  99. package/lib/features/webbuilder/web/github/autoSyncEngine.js.map +1 -0
  100. package/lib/features/webbuilder/web/github/githubSync.js +54 -0
  101. package/lib/features/webbuilder/web/github/githubSync.js.map +1 -0
  102. package/lib/features/webbuilder/web/history/versions.js +83 -0
  103. package/lib/features/webbuilder/web/history/versions.js.map +1 -0
  104. package/lib/features/webbuilder/web/project/retention.js +217 -0
  105. package/lib/features/webbuilder/web/project/retention.js.map +1 -0
  106. package/lib/features/webbuilder/web/publish/actionErrors.js +81 -0
  107. package/lib/features/webbuilder/web/publish/actionErrors.js.map +1 -0
  108. package/lib/features/webbuilder/web/publish/publishSteps.js +86 -0
  109. package/lib/features/webbuilder/web/publish/publishSteps.js.map +1 -0
  110. package/lib/features/webbuilder/web/publish/siteAddress.js +79 -0
  111. package/lib/features/webbuilder/web/publish/siteAddress.js.map +1 -0
  112. package/lib/features/webbuilder/web/publish/siteHealth.js +497 -0
  113. package/lib/features/webbuilder/web/publish/siteHealth.js.map +1 -0
  114. package/lib/features/webbuilder/web/publish/siteInsights.js +145 -0
  115. package/lib/features/webbuilder/web/publish/siteInsights.js.map +1 -0
  116. package/lib/features/webbuilder/web/sharing/roles.js +108 -2
  117. package/lib/features/webbuilder/web/sharing/roles.js.map +1 -1
  118. package/lib/features/webbuilder/web/sharing/share.js +52 -0
  119. package/lib/features/webbuilder/web/sharing/share.js.map +1 -0
  120. package/lib/features/webbuilder/web/sharing/sharingApi.js +199 -0
  121. package/lib/features/webbuilder/web/sharing/sharingApi.js.map +1 -0
  122. package/lib/features/webbuilder/web/webServices.js +13 -2
  123. package/lib/features/webbuilder/web/webServices.js.map +1 -1
  124. package/lib/features/webbuilder/webbuilderPrompts.js +4 -1
  125. package/lib/features/webbuilder/webbuilderPrompts.js.map +1 -1
  126. package/lib/features/webbuilder/workflow.js +2 -2
  127. package/lib/features/webbuilder/workflow.js.map +1 -1
  128. package/lib/hooks/useSurfaceJobs.js +113 -28
  129. package/lib/hooks/useSurfaceJobs.js.map +1 -1
  130. package/lib/index.js +1 -1
  131. package/lib/index.js.map +1 -1
  132. package/lib/screens/Chat/index.js +3 -2
  133. package/lib/screens/Chat/index.js.map +1 -1
  134. package/lib/screens/Home/HomeScreen.js +1 -1
  135. package/lib/screens/Home/components/BuildTemplatesSection.js +1 -1
  136. package/lib/screens/Home/components/ChooseTemplateModal.js +1 -1
  137. package/lib/screens/Home/components/HomeHero.js +1 -1
  138. package/lib/screens/Home/components/HomeSuggestions.js +1 -1
  139. package/lib/screens/Home/components/TemplateBrowserModal.js +1 -1
  140. package/lib/screens/Home/index.js +1 -1
  141. package/lib/screens/Home/index.js.map +1 -1
  142. package/lib/screens/WebBuilderNative/index.js +1 -1
  143. package/lib/screens/WebBuilderNative/index.js.map +1 -1
  144. package/lib/screens/WebBuilderNative/sandboxProxyApi.js +33 -3
  145. package/lib/screens/WebBuilderNative/sandboxProxyApi.js.map +1 -1
  146. package/lib/screens/WebBuilderNative/useWebBuilderHost.js +33 -13
  147. package/lib/screens/WebBuilderNative/useWebBuilderHost.js.map +1 -1
  148. package/lib/screens/WebBuilderNative/useWebBuilderJobs.js +11 -4
  149. package/lib/screens/WebBuilderNative/useWebBuilderJobs.js.map +1 -1
  150. package/lib/screens/WebBuilderNative/webbuilderTransport.js +1 -1
  151. package/lib/screens/WebBuilderNative/webbuilderTransport.js.map +1 -1
  152. package/lib/services/brainQuickReply.js +47 -14
  153. package/lib/services/brainQuickReply.js.map +1 -1
  154. package/package.json +4 -4
  155. package/lib/components/NavigationHeader/HeaderMoreMenu.js +0 -78
  156. package/lib/components/NavigationHeader/HeaderMoreMenu.js.map +0 -1
  157. package/lib/components/NavigationHeader/HeaderSettingsMenu.js +0 -132
  158. package/lib/components/NavigationHeader/HeaderSettingsMenu.js.map +0 -1
@@ -0,0 +1,145 @@
1
+ import {actionFields}from'./actionErrors.js';import {siteAddress,siteHost}from'./siteAddress.js';function rec(v) {
2
+ return v && typeof v === "object" && !Array.isArray(v) ? v : {};
3
+ }
4
+ function siteStatusView(input) {
5
+ const data = actionFields(input);
6
+ if (data.exists === false) {
7
+ return {
8
+ headline: {
9
+ text: "This site isn't published yet.",
10
+ tone: "neutral"
11
+ },
12
+ lines: []
13
+ };
14
+ }
15
+ const lines = [];
16
+ const live = data.live === true;
17
+ const str = (v) => typeof v === "string" ? v : "";
18
+ const productionUrl = siteAddress({
19
+ customDomainUrl: str(data.productionUrl),
20
+ urls: [str(data.productionUrl), str(data.pagesDevUrl)],
21
+ projectName: str(data.projectName)
22
+ });
23
+ const domainDown = data.customDomainReachable === false;
24
+ const shownUrl = domainDown ? str(data.pagesDevUrl) || productionUrl : productionUrl;
25
+ const headline = live ? {
26
+ text: `Your site is up${shownUrl ? ` at ${siteHost(shownUrl)}` : ""}.`,
27
+ tone: "good"
28
+ } : {
29
+ text: "Your site isn't answering right now.",
30
+ tone: "bad"
31
+ };
32
+ if (live && /^https:\/\//i.test(shownUrl)) {
33
+ lines.push({
34
+ text: "Secure connection (HTTPS) works.",
35
+ tone: "good"
36
+ });
37
+ }
38
+ const dep = rec(data.latestDeployment);
39
+ const status = String(dep.status || (data.deployReady === true ? "success" : "")).toLowerCase();
40
+ if (!Object.keys(dep).length) {
41
+ lines.push({
42
+ text: "Nothing has been published to this project yet.",
43
+ tone: "warn"
44
+ });
45
+ } else if (status === "success") {
46
+ lines.push({
47
+ text: "The latest publish finished successfully.",
48
+ tone: "good"
49
+ });
50
+ } else if (status === "failure" || status === "failed" || status === "canceled") {
51
+ lines.push({
52
+ text: "The latest publish did not finish. Try publishing again.",
53
+ tone: "bad"
54
+ });
55
+ } else {
56
+ lines.push({
57
+ text: "A publish is still in progress.",
58
+ tone: "warn"
59
+ });
60
+ }
61
+ const domains = Array.isArray(data.customDomains) ? data.customDomains.map(rec) : [];
62
+ for (const d of domains) {
63
+ const name = typeof d.domain === "string" ? d.domain : "";
64
+ if (!name) continue;
65
+ if (d.live === true && domainDown) {
66
+ lines.push({
67
+ text: `${name} is connected but isn't answering yet. Your site works at ${siteHost(shownUrl)} meanwhile.`,
68
+ tone: "warn"
69
+ });
70
+ } else if (d.live === true) lines.push({
71
+ text: `${name} is connected and secure.`,
72
+ tone: "good"
73
+ });
74
+ else if (d.attached === true) {
75
+ lines.push({
76
+ text: `${name} is still being set up (DNS and SSL). This usually takes a few minutes, sometimes up to a day.`,
77
+ tone: "warn"
78
+ });
79
+ } else {
80
+ lines.push({
81
+ text: `${name} is not connected to this site yet.`,
82
+ tone: "bad"
83
+ });
84
+ }
85
+ }
86
+ return {
87
+ headline,
88
+ lines
89
+ };
90
+ }
91
+ function count(v) {
92
+ const n = typeof v === "string" ? Number(v) : v;
93
+ return typeof n === "number" && Number.isFinite(n) && n > 0 ? Math.round(n) : 0;
94
+ }
95
+ function parseAnalyticsSummary(input) {
96
+ const data = actionFields(input);
97
+ const hasNumbers = "visits" in data || "pageViews" in data || Array.isArray(data.series);
98
+ if (!hasNumbers) return null;
99
+ const series = (Array.isArray(data.series) ? data.series : []).map(rec).filter((p) => typeof p.date === "string" && !Number.isNaN(new Date(p.date).getTime())).map((p) => ({
100
+ date: String(p.date),
101
+ visits: count(p.visits),
102
+ pageViews: count(p.pageViews)
103
+ })).sort((a, b) => new Date(a.date).getTime() - new Date(b.date).getTime()).slice(-31);
104
+ const topPaths = (Array.isArray(data.topPaths) ? data.topPaths : []).map(rec).filter((p) => typeof p.path === "string" && p.path).map((p) => ({
105
+ path: String(p.path).slice(0, 200),
106
+ views: count(p.views)
107
+ })).sort((a, b) => b.views - a.views).slice(0, 5);
108
+ const topCountries = (Array.isArray(data.topCountries) ? data.topCountries : []).map(rec).filter((p) => typeof p.country === "string" && p.country).map((p) => ({
109
+ country: String(p.country).slice(0, 60),
110
+ views: count(p.views)
111
+ })).sort((a, b) => b.views - a.views).slice(0, 5);
112
+ const days = count(data.days) || series.length || 7;
113
+ return {
114
+ enabled: data.enabled !== false,
115
+ days,
116
+ visits: "visits" in data ? count(data.visits) : series.reduce((s, p) => s + p.visits, 0),
117
+ pageViews: "pageViews" in data ? count(data.pageViews) : series.reduce((s, p) => s + p.pageViews, 0),
118
+ topPaths,
119
+ topCountries,
120
+ series
121
+ };
122
+ }
123
+ function formatCount(n) {
124
+ if (n < 1e3) return String(n);
125
+ if (n < 1e6) return `${(n / 1e3).toFixed(n < 1e4 ? 1 : 0).replace(/\.0$/, "")}k`;
126
+ return `${(n / 1e6).toFixed(1).replace(/\.0$/, "")}M`;
127
+ }
128
+ function sparklinePoints(values, width, height, pad = 2) {
129
+ if (!values.length) return "";
130
+ const max = Math.max(...values, 1);
131
+ const innerW = width - pad * 2;
132
+ const innerH = height - pad * 2;
133
+ const step = values.length > 1 ? innerW / (values.length - 1) : 0;
134
+ const round = (n) => Math.round(n * 10) / 10;
135
+ const pts = values.map((v, i) => {
136
+ const x = values.length > 1 ? pad + i * step : width / 2;
137
+ const y = pad + innerH - Math.max(0, v) / max * innerH;
138
+ return `${round(x)},${round(y)}`;
139
+ });
140
+ if (pts.length === 1) {
141
+ const y = pts[0].split(",")[1];
142
+ return `${pad},${y} ${width - pad},${y}`;
143
+ }
144
+ return pts.join(" ");
145
+ }export{formatCount,parseAnalyticsSummary,siteStatusView,sparklinePoints};//# sourceMappingURL=siteInsights.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"siteInsights.js","sources":["../../../../../src/features/webbuilder/web/publish/siteInsights.ts"],"sourcesContent":["/**\n * W22: plain-language site status (WEBBUILDER_SITE_STATUS) and the analytics\n * summary (WEBBUILDER_ANALYTICS mode:'summary', spec §1), plus the inline\n * sparkline geometry. No chart library.\n */\n\nimport { actionFields } from './actionErrors';\nimport { siteAddress, siteHost } from './siteAddress';\n\nexport type Tone = 'good' | 'warn' | 'bad' | 'neutral';\n\nexport interface StatusLine {\n text: string;\n tone: Tone;\n}\n\nexport interface SiteStatusView {\n headline: StatusLine;\n lines: StatusLine[];\n}\n\nfunction rec(v: unknown): Record<string, unknown> {\n return v && typeof v === 'object' && !Array.isArray(v) ? (v as Record<string, unknown>) : {};\n}\n\n/**\n * WEBBUILDER_SITE_STATUS `{ projectName, exists, live, productionUrl,\n * pagesDevUrl, latestDeployment, deployReady, customDomains[], summary }`.\n */\nexport function siteStatusView(input: Record<string, unknown>): SiteStatusView {\n const data = actionFields(input);\n if (data.exists === false) {\n return { headline: { text: \"This site isn't published yet.\", tone: 'neutral' }, lines: [] };\n }\n const lines: StatusLine[] = [];\n const live = data.live === true;\n const str = (v: unknown) => (typeof v === 'string' ? v : '');\n const productionUrl = siteAddress({\n customDomainUrl: str(data.productionUrl),\n urls: [str(data.productionUrl), str(data.pagesDevUrl)],\n projectName: str(data.projectName),\n });\n // The connector loaded the custom address and it failed: name the address that works.\n const domainDown = data.customDomainReachable === false;\n const shownUrl = domainDown ? str(data.pagesDevUrl) || productionUrl : productionUrl;\n const headline: StatusLine = live\n ? { text: `Your site is up${shownUrl ? ` at ${siteHost(shownUrl)}` : ''}.`, tone: 'good' }\n : { text: \"Your site isn't answering right now.\", tone: 'bad' };\n\n if (live && /^https:\\/\\//i.test(shownUrl)) {\n lines.push({ text: 'Secure connection (HTTPS) works.', tone: 'good' });\n }\n\n const dep = rec(data.latestDeployment);\n const status = String(dep.status || (data.deployReady === true ? 'success' : '')).toLowerCase();\n if (!Object.keys(dep).length) {\n lines.push({ text: 'Nothing has been published to this project yet.', tone: 'warn' });\n } else if (status === 'success') {\n lines.push({ text: 'The latest publish finished successfully.', tone: 'good' });\n } else if (status === 'failure' || status === 'failed' || status === 'canceled') {\n lines.push({ text: 'The latest publish did not finish. Try publishing again.', tone: 'bad' });\n } else {\n lines.push({ text: 'A publish is still in progress.', tone: 'warn' });\n }\n\n const domains = Array.isArray(data.customDomains) ? data.customDomains.map(rec) : [];\n for (const d of domains) {\n const name = typeof d.domain === 'string' ? d.domain : '';\n if (!name) continue;\n if (d.live === true && domainDown) {\n lines.push({\n text: `${name} is connected but isn't answering yet. Your site works at ${siteHost(shownUrl)} meanwhile.`,\n tone: 'warn',\n });\n } else if (d.live === true) lines.push({ text: `${name} is connected and secure.`, tone: 'good' });\n else if (d.attached === true) {\n lines.push({\n text: `${name} is still being set up (DNS and SSL). This usually takes a few minutes, sometimes up to a day.`,\n tone: 'warn',\n });\n } else {\n lines.push({ text: `${name} is not connected to this site yet.`, tone: 'bad' });\n }\n }\n return { headline, lines };\n}\n\nexport interface AnalyticsSummary {\n /** false = Web Analytics is off for this site (the numbers are zeros). */\n enabled: boolean;\n days: number;\n visits: number;\n pageViews: number;\n topPaths: Array<{ path: string; views: number }>;\n topCountries: Array<{ country: string; views: number }>;\n series: Array<{ date: string; visits: number; pageViews: number }>;\n}\n\nfunction count(v: unknown): number {\n const n = typeof v === 'string' ? Number(v) : v;\n return typeof n === 'number' && Number.isFinite(n) && n > 0 ? Math.round(n) : 0;\n}\n\n/**\n * WEBBUILDER_ANALYTICS mode:'summary' `{ enabled, days, visits, pageViews,\n * topPaths[{path,views}], topCountries[{country,views}], series[{date,visits,pageViews}] }`.\n */\nexport function parseAnalyticsSummary(input: Record<string, unknown>): AnalyticsSummary | null {\n const data = actionFields(input);\n const hasNumbers = 'visits' in data || 'pageViews' in data || Array.isArray(data.series);\n if (!hasNumbers) return null;\n const series = (Array.isArray(data.series) ? data.series : [])\n .map(rec)\n .filter((p) => typeof p.date === 'string' && !Number.isNaN(new Date(p.date).getTime()))\n .map((p) => ({ date: String(p.date), visits: count(p.visits), pageViews: count(p.pageViews) }))\n .sort((a, b) => new Date(a.date).getTime() - new Date(b.date).getTime())\n .slice(-31);\n const topPaths = (Array.isArray(data.topPaths) ? data.topPaths : [])\n .map(rec)\n .filter((p) => typeof p.path === 'string' && p.path)\n .map((p) => ({ path: String(p.path).slice(0, 200), views: count(p.views) }))\n .sort((a, b) => b.views - a.views)\n .slice(0, 5);\n const topCountries = (Array.isArray(data.topCountries) ? data.topCountries : [])\n .map(rec)\n .filter((p) => typeof p.country === 'string' && p.country)\n .map((p) => ({ country: String(p.country).slice(0, 60), views: count(p.views) }))\n .sort((a, b) => b.views - a.views)\n .slice(0, 5);\n const days = count(data.days) || series.length || 7;\n return {\n enabled: data.enabled !== false,\n days,\n visits: 'visits' in data ? count(data.visits) : series.reduce((s, p) => s + p.visits, 0),\n pageViews: 'pageViews' in data ? count(data.pageViews) : series.reduce((s, p) => s + p.pageViews, 0),\n topPaths,\n topCountries,\n series,\n };\n}\n\n/** 1234 -> \"1.2k\", 2_500_000 -> \"2.5M\". */\nexport function formatCount(n: number): string {\n if (n < 1000) return String(n);\n if (n < 1_000_000) return `${(n / 1000).toFixed(n < 10_000 ? 1 : 0).replace(/\\.0$/, '')}k`;\n return `${(n / 1_000_000).toFixed(1).replace(/\\.0$/, '')}M`;\n}\n\n/** SVG polyline points for a sparkline in a width x height box. */\nexport function sparklinePoints(values: number[], width: number, height: number, pad = 2): string {\n if (!values.length) return '';\n const max = Math.max(...values, 1);\n const innerW = width - pad * 2;\n const innerH = height - pad * 2;\n const step = values.length > 1 ? innerW / (values.length - 1) : 0;\n const round = (n: number) => Math.round(n * 10) / 10;\n const pts = values.map((v, i) => {\n const x = values.length > 1 ? pad + i * step : width / 2;\n const y = pad + innerH - (Math.max(0, v) / max) * innerH;\n return `${round(x)},${round(y)}`;\n });\n // One point: draw a flat line so it's visible.\n if (pts.length === 1) {\n const y = pts[0].split(',')[1];\n return `${pad},${y} ${width - pad},${y}`;\n }\n return pts.join(' ');\n}\n"],"names":[],"mappings":"iGAiBA,SAAS,IAAI,CAAqC,EAAA;AAChD,EAAO,OAAA,CAAA,IAAK,OAAO,CAAA,KAAM,QAAY,IAAA,CAAC,MAAM,OAAQ,CAAA,CAAC,CAAI,GAAA,CAAA,GAA+B,EAAC;AA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AG,CAAM,KAAA;AAC/B,IAAA,MAAM,IAAI,MAAO,CAAA,MAAA,GAAS,IAAI,GAAM,GAAA,CAAA,GAAI,OAAO,KAAQ,GAAA,CAAA;AACvD,IAAM,MAAA,CAAA,GAAI,MAAM,MAAS,GAAA,IAAA,CAAK,IAAI,CAAG,EAAA,CAAC,IAAI,GAAM,GAAA,MAAA;AAChD,IAAA,OAAO,GAAG,KAAM,CAAA,CAAC,CAAC,CAAI,CAAA,EAAA,KAAA,CAAM,CAAC,CAAC,CAAA,CAAA;AAAA,GAC/B,CAAA;AAED,EAAI,IAAA,GAAA,CAAI,WAAW,CAAG,EAAA;AACpB,IAAA,MAAM,IAAI,GAAI,CAAA,CAAC,EAAE,KAAM,CAAA,GAAG,EAAE,CAAC,CAAA;AAC7B,IAAO,OAAA,CAAA,EAAG,GAAG,CAAI,CAAA,EAAA,CAAC,IAAI,KAAQ,GAAA,GAAG,IAAI,CAAC,CAAA,CAAA;AAAA;AAExC,EAAO,OAAA,GAAA,CAAI,KAAK,GAAG,CAAA;AACrB"}
@@ -1,3 +1,109 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
3
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
4
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
5
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
6
+ var __spreadValues = (a, b) => {
7
+ for (var prop in b || (b = {}))
8
+ if (__hasOwnProp.call(b, prop))
9
+ __defNormalProp(a, prop, b[prop]);
10
+ if (__getOwnPropSymbols)
11
+ for (var prop of __getOwnPropSymbols(b)) {
12
+ if (__propIsEnum.call(b, prop))
13
+ __defNormalProp(a, prop, b[prop]);
14
+ }
15
+ return a;
16
+ };
17
+ const PROJECT_ROLES = ["owner", "editor", "viewer"];
18
+ const INVITE_ROLES = ["editor", "viewer"];
19
+ const VIEWER_ACTIONS = /* @__PURE__ */ new Set(["view", "comment"]);
20
+ const OWNER_ONLY = /* @__PURE__ */ new Set(["share", "changeRole", "removeMember", "delete", "databaseStudio", "databaseSql", "databaseComponents", "githubSync", "secrets", "siteAlerts"]);
21
+ function normalizeRole(raw) {
22
+ const r = typeof raw === "string" ? raw.trim().toLowerCase() : "";
23
+ return r === "owner" || r === "editor" || r === "viewer" ? r : null;
24
+ }
1
25
  function roleCan(role, action) {
2
- return true;
3
- }export{roleCan};//# sourceMappingURL=roles.js.map
26
+ if (!role) return true;
27
+ if (role === "owner") return true;
28
+ if (role === "editor") return !OWNER_ONLY.has(action);
29
+ return VIEWER_ACTIONS.has(action);
30
+ }
31
+ function isRec(v) {
32
+ return Boolean(v) && typeof v === "object" && !Array.isArray(v);
33
+ }
34
+ function text(v, max) {
35
+ if (typeof v !== "string") return void 0;
36
+ const t = v.trim();
37
+ return t ? t.slice(0, max) : void 0;
38
+ }
39
+ function parseMembers(raw) {
40
+ var _a;
41
+ let value = raw;
42
+ if (typeof value === "string") {
43
+ try {
44
+ value = JSON.parse(value);
45
+ } catch (e) {
46
+ return [];
47
+ }
48
+ }
49
+ if (isRec(value) && Array.isArray(value.members)) value = value.members;
50
+ if (!Array.isArray(value)) return [];
51
+ const seen = /* @__PURE__ */ new Set();
52
+ const out = [];
53
+ for (const item of value) {
54
+ if (!isRec(item)) continue;
55
+ const userId = text((_a = item.userId) != null ? _a : item.id, 100);
56
+ const role = normalizeRole(item.role);
57
+ if (!userId || !role || seen.has(userId)) continue;
58
+ seen.add(userId);
59
+ const name = text(item.name, 200);
60
+ const email = text(item.email, 320);
61
+ out.push(__spreadValues(__spreadValues({
62
+ userId,
63
+ role
64
+ }, name ? {
65
+ name
66
+ } : {}), email ? {
67
+ email
68
+ } : {}));
69
+ }
70
+ const rank = {
71
+ owner: 0,
72
+ editor: 1,
73
+ viewer: 2
74
+ };
75
+ return out.sort((a, b) => rank[a.role] - rank[b.role] || memberLabel(a).localeCompare(memberLabel(b)));
76
+ }
77
+ function roleOf(members, userId) {
78
+ var _a, _b;
79
+ if (!userId) return null;
80
+ return (_b = (_a = members.find((m) => m.userId === userId)) == null ? void 0 : _a.role) != null ? _b : null;
81
+ }
82
+ function memberLabel(m) {
83
+ return m.name || m.email || `User ${m.userId.slice(-6)}`;
84
+ }
85
+ const ROLE_LABELS = {
86
+ owner: "Owner",
87
+ editor: "Can edit",
88
+ viewer: "Can view"
89
+ };
90
+ const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/;
91
+ function normalizeEmail(raw) {
92
+ const e = raw.trim().toLowerCase();
93
+ return e.length <= 320 && EMAIL_RE.test(e) ? e : null;
94
+ }
95
+ function lastOwnerProblem(members, userId, next) {
96
+ const target = members.find((m) => m.userId === userId);
97
+ if (!target || target.role !== "owner" || next === "owner") return null;
98
+ const owners = members.filter((m) => m.role === "owner").length;
99
+ if (owners > 1) return null;
100
+ return next === "removed" ? "The project's only owner can't be removed. Make someone else an owner first." : "The project's only owner can't be changed. Make someone else an owner first.";
101
+ }
102
+ function sharingErrorText(message) {
103
+ const m = message.trim();
104
+ if (/not (?:a )?member of|not in (?:the|your) org|same org|organization/i.test(m)) {
105
+ return `${m.replace(/\.?$/, ".")} Only people in your organization can be added.`;
106
+ }
107
+ if (/forbidden|not allowed|only owners|permission/i.test(m)) return "Only owners can change who has access.";
108
+ return m || "Something went wrong.";
109
+ }export{INVITE_ROLES,PROJECT_ROLES,ROLE_LABELS,lastOwnerProblem,memberLabel,normalizeEmail,normalizeRole,parseMembers,roleCan,roleOf,sharingErrorText};//# sourceMappingURL=roles.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"roles.js","sources":["../../../../../src/features/webbuilder/web/sharing/roles.ts"],"sourcesContent":["/**\n * W31 sharing and roles (Phase 6 spec §2), surface side. Pure: tested with node:test.\n *\n * `roleCan` mirrors the server's checks in page-creator (stream P6):\n * - viewers can look (preview, code, history, read-only data views) and comment;\n * - editors can do everything except share, change roles, remove members, delete,\n * open the database Studio, run SQL, change database components, and change\n * GitHub sync or secrets settings;\n * - owners can do everything. The channel creator is always an owner.\n * The server enforces all of this; the surface only hides what would be refused.\n * An unknown role (old server, members not loaded) means \"no restriction shown\".\n */\n\nexport type ProjectRole = 'owner' | 'editor' | 'viewer';\n\nexport const PROJECT_ROLES: readonly ProjectRole[] = ['owner', 'editor', 'viewer'];\n/** Roles an owner can give when inviting (owners are made by changing a role). */\nexport const INVITE_ROLES: readonly ProjectRole[] = ['editor', 'viewer'];\n\nexport type RoleAction =\n | 'view'\n | 'comment'\n /** Build and edit turns (the composer, canvas Ask AI, \"Ask AI to fix\", Try to fix). */\n | 'build'\n /** Hand edits on the canvas and in the code editor. */\n | 'editCanvas'\n | 'editCode'\n | 'restoreVersion'\n | 'publish'\n | 'pushGithub'\n /** GitHub sync settings (auto-sync on or off). */\n | 'githubSync'\n /** Secrets settings (add, change, remove). */\n | 'secrets'\n | 'integrations'\n /** The database Studio link (full database access). */\n | 'databaseStudio'\n /** Cloud panel: data (read and edit rows), health, auth users and storage. Editors and owners. */\n | 'database'\n /** Cloud panel: the raw SQL runner (owners). */\n | 'databaseSql'\n /** Cloud panel: turn database components on or off (owners). */\n | 'databaseComponents'\n | 'updateSettings'\n /** Resolve production errors in the Health panel (editors and owners). */\n | 'resolveSiteErrors'\n /** The Health panel's alert settings (owners). */\n | 'siteAlerts'\n | 'share'\n | 'changeRole'\n | 'removeMember'\n | 'delete';\n\nconst VIEWER_ACTIONS: ReadonlySet<RoleAction> = new Set(['view', 'comment']);\nconst OWNER_ONLY: ReadonlySet<RoleAction> = new Set([\n 'share',\n 'changeRole',\n 'removeMember',\n 'delete',\n 'databaseStudio',\n 'databaseSql',\n 'databaseComponents',\n 'githubSync',\n 'secrets',\n 'siteAlerts',\n]);\n\nexport function normalizeRole(raw: unknown): ProjectRole | null {\n const r = typeof raw === 'string' ? raw.trim().toLowerCase() : '';\n return r === 'owner' || r === 'editor' || r === 'viewer' ? r : null;\n}\n\n/** May `role` do `action`? `null` (unknown) allows everything: the server still checks. */\nexport function roleCan(role: ProjectRole | null | undefined, action: RoleAction): boolean {\n if (!role) return true;\n if (role === 'owner') return true;\n if (role === 'editor') return !OWNER_ONLY.has(action);\n return VIEWER_ACTIONS.has(action);\n}\n\nexport interface ProjectMember {\n userId: string;\n name?: string;\n email?: string;\n role: ProjectRole;\n}\n\ntype Rec = Record<string, unknown>;\n\nfunction isRec(v: unknown): v is Rec {\n return Boolean(v) && typeof v === 'object' && !Array.isArray(v);\n}\n\nfunction text(v: unknown, max: number): string | undefined {\n if (typeof v !== 'string') return undefined;\n const t = v.trim();\n return t ? t.slice(0, max) : undefined;\n}\n\n/** `aiCodeProjectMembers` JSON (an array, or `{ members }`, maybe as a string) -> members, owners first. */\nexport function parseMembers(raw: unknown): ProjectMember[] {\n let value = raw;\n if (typeof value === 'string') {\n try {\n value = JSON.parse(value) as unknown;\n } catch {\n return [];\n }\n }\n if (isRec(value) && Array.isArray(value.members)) value = value.members;\n if (!Array.isArray(value)) return [];\n const seen = new Set<string>();\n const out: ProjectMember[] = [];\n for (const item of value) {\n if (!isRec(item)) continue;\n const userId = text(item.userId ?? item.id, 100);\n const role = normalizeRole(item.role);\n if (!userId || !role || seen.has(userId)) continue;\n seen.add(userId);\n const name = text(item.name, 200);\n const email = text(item.email, 320);\n out.push({ userId, role, ...(name ? { name } : {}), ...(email ? { email } : {}) });\n }\n const rank: Record<ProjectRole, number> = { owner: 0, editor: 1, viewer: 2 };\n return out.sort((a, b) => rank[a.role] - rank[b.role] || memberLabel(a).localeCompare(memberLabel(b)));\n}\n\n/** The current user's role among `members`; null when they aren't listed (unknown). */\nexport function roleOf(members: readonly ProjectMember[], userId: string | null | undefined): ProjectRole | null {\n if (!userId) return null;\n return members.find((m) => m.userId === userId)?.role ?? null;\n}\n\nexport function memberLabel(m: Pick<ProjectMember, 'name' | 'email' | 'userId'>): string {\n return m.name || m.email || `User ${m.userId.slice(-6)}`;\n}\n\nexport const ROLE_LABELS: Record<ProjectRole, string> = {\n owner: 'Owner',\n editor: 'Can edit',\n viewer: 'Can view',\n};\n\nconst EMAIL_RE = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]{2,}$/;\n\nexport function normalizeEmail(raw: string): string | null {\n const e = raw.trim().toLowerCase();\n return e.length <= 320 && EMAIL_RE.test(e) ? e : null;\n}\n\n/**\n * Spec §2: the last owner can't be removed or demoted. Returns the reason to\n * show, or null when the change is fine.\n */\nexport function lastOwnerProblem(\n members: readonly ProjectMember[],\n userId: string,\n next: ProjectRole | 'removed',\n): string | null {\n const target = members.find((m) => m.userId === userId);\n if (!target || target.role !== 'owner' || next === 'owner') return null;\n const owners = members.filter((m) => m.role === 'owner').length;\n if (owners > 1) return null;\n return next === 'removed'\n ? \"The project's only owner can't be removed. Make someone else an owner first.\"\n : \"The project's only owner can't be changed. Make someone else an owner first.\";\n}\n\n/** Board badge: shared with you when someone else created the channel. */\nexport function isSharedWithMe(creatorId: string | null | undefined, myUserId: string | null | undefined): boolean {\n if (!creatorId || !myUserId) return false;\n return creatorId !== myUserId;\n}\n\n/** The composer line while the open project is view-only (through `setExternalBusy`). */\nexport const VIEWER_BLOCKED_REASON = 'You have view access to this project. Ask an owner for edit access to change it.';\n\n/** `failure.stage === 'permission'` from the pipeline (spec §2 \"Limits\"). */\nexport const PERMISSION_FAILURE_TITLE = \"You can't change this project\";\n\nexport function permissionFailureText(message?: string | null): string {\n const m = String(message || '').trim();\n return m || 'You have view access to this project, so the AI did not change it. Ask an owner for edit access.';\n}\n\n/** Turn a server error from a sharing mutation into something a person can act on. */\nexport function sharingErrorText(message: string): string {\n const m = message.trim();\n if (/not (?:a )?member of|not in (?:the|your) org|same org|organization/i.test(m)) {\n return `${m.replace(/\\.?$/, '.')} Only people in your organization can be added.`;\n }\n if (/forbidden|not allowed|only owners|permission/i.test(m)) return 'Only owners can change who has access.';\n return m || 'Something went wrong.';\n}\n"],"names":[],"mappings":"AAoCgB,SAAA,OAAA,CAAQ,MAAsC,MAA6B,EAAA;AACzF,EAAkB,OAAA,IAAA;AAIpB"}
1
+ {"version":3,"file":"roles.js","sources":["../../../../../src/features/webbuilder/web/sharing/roles.ts"],"sourcesContent":["/**\n * W31 sharing and roles (Phase 6 spec §2), surface side. Pure: tested with node:test.\n *\n * `roleCan` mirrors the server's checks in page-creator (stream P6):\n * - viewers can look (preview, code, history, read-only data views) and comment;\n * - editors can do everything except share, change roles, remove members, delete,\n * open the database Studio, run SQL, change database components, and change\n * GitHub sync or secrets settings;\n * - owners can do everything. The channel creator is always an owner.\n * The server enforces all of this; the surface only hides what would be refused.\n * An unknown role (old server, members not loaded) means \"no restriction shown\".\n */\n\nexport type ProjectRole = 'owner' | 'editor' | 'viewer';\n\nexport const PROJECT_ROLES: readonly ProjectRole[] = ['owner', 'editor', 'viewer'];\n/** Roles an owner can give when inviting (owners are made by changing a role). */\nexport const INVITE_ROLES: readonly ProjectRole[] = ['editor', 'viewer'];\n\nexport type RoleAction =\n | 'view'\n | 'comment'\n /** Build and edit turns (the composer, canvas Ask AI, \"Ask AI to fix\", Try to fix). */\n | 'build'\n /** Hand edits on the canvas and in the code editor. */\n | 'editCanvas'\n | 'editCode'\n | 'restoreVersion'\n | 'publish'\n | 'pushGithub'\n /** GitHub sync settings (auto-sync on or off). */\n | 'githubSync'\n /** Secrets settings (add, change, remove). */\n | 'secrets'\n | 'integrations'\n /** The database Studio link (full database access). */\n | 'databaseStudio'\n /** Cloud panel: data (read and edit rows), health, auth users and storage. Editors and owners. */\n | 'database'\n /** Cloud panel: the raw SQL runner (owners). */\n | 'databaseSql'\n /** Cloud panel: turn database components on or off (owners). */\n | 'databaseComponents'\n | 'updateSettings'\n /** Resolve production errors in the Health panel (editors and owners). */\n | 'resolveSiteErrors'\n /** The Health panel's alert settings (owners). */\n | 'siteAlerts'\n | 'share'\n | 'changeRole'\n | 'removeMember'\n | 'delete';\n\nconst VIEWER_ACTIONS: ReadonlySet<RoleAction> = new Set(['view', 'comment']);\nconst OWNER_ONLY: ReadonlySet<RoleAction> = new Set([\n 'share',\n 'changeRole',\n 'removeMember',\n 'delete',\n 'databaseStudio',\n 'databaseSql',\n 'databaseComponents',\n 'githubSync',\n 'secrets',\n 'siteAlerts',\n]);\n\nexport function normalizeRole(raw: unknown): ProjectRole | null {\n const r = typeof raw === 'string' ? raw.trim().toLowerCase() : '';\n return r === 'owner' || r === 'editor' || r === 'viewer' ? r : null;\n}\n\n/** May `role` do `action`? `null` (unknown) allows everything: the server still checks. */\nexport function roleCan(role: ProjectRole | null | undefined, action: RoleAction): boolean {\n if (!role) return true;\n if (role === 'owner') return true;\n if (role === 'editor') return !OWNER_ONLY.has(action);\n return VIEWER_ACTIONS.has(action);\n}\n\nexport interface ProjectMember {\n userId: string;\n name?: string;\n email?: string;\n role: ProjectRole;\n}\n\ntype Rec = Record<string, unknown>;\n\nfunction isRec(v: unknown): v is Rec {\n return Boolean(v) && typeof v === 'object' && !Array.isArray(v);\n}\n\nfunction text(v: unknown, max: number): string | undefined {\n if (typeof v !== 'string') return undefined;\n const t = v.trim();\n return t ? t.slice(0, max) : undefined;\n}\n\n/** `aiCodeProjectMembers` JSON (an array, or `{ members }`, maybe as a string) -> members, owners first. */\nexport function parseMembers(raw: unknown): ProjectMember[] {\n let value = raw;\n if (typeof value === 'string') {\n try {\n value = JSON.parse(value) as unknown;\n } catch {\n return [];\n }\n }\n if (isRec(value) && Array.isArray(value.members)) value = value.members;\n if (!Array.isArray(value)) return [];\n const seen = new Set<string>();\n const out: ProjectMember[] = [];\n for (const item of value) {\n if (!isRec(item)) continue;\n const userId = text(item.userId ?? item.id, 100);\n const role = normalizeRole(item.role);\n if (!userId || !role || seen.has(userId)) continue;\n seen.add(userId);\n const name = text(item.name, 200);\n const email = text(item.email, 320);\n out.push({ userId, role, ...(name ? { name } : {}), ...(email ? { email } : {}) });\n }\n const rank: Record<ProjectRole, number> = { owner: 0, editor: 1, viewer: 2 };\n return out.sort((a, b) => rank[a.role] - rank[b.role] || memberLabel(a).localeCompare(memberLabel(b)));\n}\n\n/** The current user's role among `members`; null when they aren't listed (unknown). */\nexport function roleOf(members: readonly ProjectMember[], userId: string | null | undefined): ProjectRole | null {\n if (!userId) return null;\n return members.find((m) => m.userId === userId)?.role ?? null;\n}\n\nexport function memberLabel(m: Pick<ProjectMember, 'name' | 'email' | 'userId'>): string {\n return m.name || m.email || `User ${m.userId.slice(-6)}`;\n}\n\nexport const ROLE_LABELS: Record<ProjectRole, string> = {\n owner: 'Owner',\n editor: 'Can edit',\n viewer: 'Can view',\n};\n\nconst EMAIL_RE = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]{2,}$/;\n\nexport function normalizeEmail(raw: string): string | null {\n const e = raw.trim().toLowerCase();\n return e.length <= 320 && EMAIL_RE.test(e) ? e : null;\n}\n\n/**\n * Spec §2: the last owner can't be removed or demoted. Returns the reason to\n * show, or null when the change is fine.\n */\nexport function lastOwnerProblem(\n members: readonly ProjectMember[],\n userId: string,\n next: ProjectRole | 'removed',\n): string | null {\n const target = members.find((m) => m.userId === userId);\n if (!target || target.role !== 'owner' || next === 'owner') return null;\n const owners = members.filter((m) => m.role === 'owner').length;\n if (owners > 1) return null;\n return next === 'removed'\n ? \"The project's only owner can't be removed. Make someone else an owner first.\"\n : \"The project's only owner can't be changed. Make someone else an owner first.\";\n}\n\n/** Board badge: shared with you when someone else created the channel. */\nexport function isSharedWithMe(creatorId: string | null | undefined, myUserId: string | null | undefined): boolean {\n if (!creatorId || !myUserId) return false;\n return creatorId !== myUserId;\n}\n\n/** The composer line while the open project is view-only (through `setExternalBusy`). */\nexport const VIEWER_BLOCKED_REASON = 'You have view access to this project. Ask an owner for edit access to change it.';\n\n/** `failure.stage === 'permission'` from the pipeline (spec §2 \"Limits\"). */\nexport const PERMISSION_FAILURE_TITLE = \"You can't change this project\";\n\nexport function permissionFailureText(message?: string | null): string {\n const m = String(message || '').trim();\n return m || 'You have view access to this project, so the AI did not change it. Ask an owner for edit access.';\n}\n\n/** Turn a server error from a sharing mutation into something a person can act on. */\nexport function sharingErrorText(message: string): string {\n const m = message.trim();\n if (/not (?:a )?member of|not in (?:the|your) org|same org|organization/i.test(m)) {\n return `${m.replace(/\\.?$/, '.')} Only people in your organization can be added.`;\n }\n if (/forbidden|not allowed|only owners|permission/i.test(m)) return 'Only owners can change who has access.';\n return m || 'Something went wrong.';\n}\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAcO,MAAM,aAAwC,GAAA,CAAC,OAAS,EAAA,QAAA,EAAU,QAAQ;AAEpE,MAAA,YAAA,GAAuC,CAAC,QAAA,EAAU,QAAQ;AAYvE,MAAM,iCAA8C,IAAA,GAAA,CAAI,CAAC,MAAA,EAAQ,SAAS,CAAC,CAAA;AAC3E,MAAM,UAAsC,mBAAA,IAAI,GAAI,CAAA,CAAC,SAAS,YAAc,EAAA,cAAA,EAAgB,QAAU,EAAA,gBAAA,EAAkB,aAAe,EAAA,oBAAA,EAAsB,YAAc,EAAA,SAAA,EAAW,YAAY,CAAC,CAAA;AAC5L,SAAS,cAAc,GAAkC,EAAA;AAC9D,EAAM,MAAA,CAAA,GAAI,OAAO,GAAQ,KAAA,QAAA,GAAW,IAAI,IAAK,EAAA,CAAE,aAAgB,GAAA,EAAA;AAC/D,EAAA,OAAO,MAAM,OAAW,IAAA,CAAA,KAAM,QAAY,IAAA,CAAA,KAAM,WAAW,CAAI,GAAA,IAAA;AACjE;AAGgB,SAAA,OAAA,CAAQ,MAAsC,MAA6B,EAAA;AACzF,EAAI,IAAA,CAAC,MAAa,OAAA,IAAA;AAClB,EAAI,IAAA,IAAA,KAAS,SAAgB,OAAA,IAAA;AAC7B,EAAA,IAAI,SAAS,QAAU,EAAA,OAAO,CAAC,UAAA,CAAW,IAAI,MAAM,CAAA;AACpD,EAAO,OAAA,cAAA,CAAe,IAAI,MAAM,CAAA;AAClC;AAQA,SAAS,MAAM,CAAsB,EAAA;AACnC,EAAO,OAAA,OAAA,CAAQ,CAAC,CAAK,IAAA,OAAO,MAAM,QAAY,IAAA,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AAA;AACd"}
@@ -0,0 +1,52 @@
1
+ const SNAPSHOT_ID_RE = /^(?:[a-z0-9][a-z0-9_-]{0,63}\/)?[A-Za-z0-9][A-Za-z0-9_-]{2,79}(?::[A-Za-z0-9][A-Za-z0-9._-]{0,63})?$/;
2
+ const REMIX_TITLE_MAX = 80;
3
+ function isValidSnapshotId(id) {
4
+ return typeof id === "string" && id.length <= 160 && SNAPSHOT_ID_RE.test(id);
5
+ }
6
+ function cleanRemixTitle(raw) {
7
+ const t = String(raw != null ? raw : "").replace(/[\u0000-\u001f\u007f<>]/g, " ").replace(/\s+/g, " ").trim().slice(0, REMIX_TITLE_MAX).trim();
8
+ return t || "a shared project";
9
+ }
10
+ function snapshotNameForProject(title) {
11
+ const name = String(title || "").replace(/[^A-Za-z0-9._ -]+/g, " ").replace(/\s+/g, " ").trim().slice(0, 60).trim();
12
+ return name || "webbuilder-project";
13
+ }
14
+ function snapshotIdFromResult(data) {
15
+ var _a, _b;
16
+ const id = String((_b = (_a = data == null ? void 0 : data.snapshotId) != null ? _a : data == null ? void 0 : data.snapshotID) != null ? _b : "").trim();
17
+ return isValidSnapshotId(id) ? id : null;
18
+ }
19
+ function remixSnapshotParams(sandboxId, title) {
20
+ return {
21
+ sandbox_id: sandboxId,
22
+ name: snapshotNameForProject(title),
23
+ excludeSecrets: true
24
+ };
25
+ }
26
+ function remixSecretsCheck(data) {
27
+ const files = Array.isArray(data == null ? void 0 : data.secretFiles) ? data.secretFiles.filter((f) => typeof f === "string" && f.trim() !== "") : [];
28
+ if (!files.length) return {
29
+ ok: true,
30
+ note: null
31
+ };
32
+ const names = [...new Set(files.map((f) => f.split("/").filter(Boolean).pop() || f))];
33
+ const shown = names.slice(0, 4).join(", ") + (names.length > 4 ? ` and ${names.length - 4} more` : "");
34
+ if ((data == null ? void 0 : data.secretsExcluded) !== true) {
35
+ return {
36
+ ok: false,
37
+ message: `The template would include secret files (${shown}), so no link was made. Try again later.`
38
+ };
39
+ }
40
+ return {
41
+ ok: true,
42
+ note: `Left out of the template: ${shown}. They stay in your project only.`
43
+ };
44
+ }
45
+ function buildRemixUrl(currentHref, snapshotId, title) {
46
+ if (!isValidSnapshotId(snapshotId)) throw new Error("invalid snapshot id");
47
+ const u = new URL(currentHref);
48
+ const out = new URL(`${u.origin}${u.pathname}`);
49
+ out.searchParams.set("remix", snapshotId);
50
+ out.searchParams.set("title", cleanRemixTitle(title));
51
+ return out.toString();
52
+ }export{REMIX_TITLE_MAX,buildRemixUrl,cleanRemixTitle,isValidSnapshotId,remixSecretsCheck,remixSnapshotParams,snapshotIdFromResult,snapshotNameForProject};//# sourceMappingURL=share.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"share.js","sources":["../../../../../src/features/webbuilder/web/sharing/share.ts"],"sourcesContent":["/**\n * W24: share and remix links (spec §6). A remix link is the surface URL with\n * `?remix=<snapshotId>&title=<title>`; opening it starts a NEW project from\n * that snapshot. Everything from the URL is validated strictly.\n */\n\n/** E2B snapshot / template ids: `abc123`, `abc123:default`, `team/abc123:tag`. */\nconst SNAPSHOT_ID_RE =\n /^(?:[a-z0-9][a-z0-9_-]{0,63}\\/)?[A-Za-z0-9][A-Za-z0-9_-]{2,79}(?::[A-Za-z0-9][A-Za-z0-9._-]{0,63})?$/;\n\nexport const REMIX_TEMPLATE_ID = 'remix-link';\nexport const REMIX_TITLE_MAX = 80;\n\nexport function isValidSnapshotId(id: unknown): id is string {\n return typeof id === 'string' && id.length <= 160 && SNAPSHOT_ID_RE.test(id);\n}\n\n/** Display title from a URL: no control chars or angle brackets, collapsed spaces, capped. */\nexport function cleanRemixTitle(raw: unknown): string {\n const t = String(raw ?? '')\n // eslint-disable-next-line no-control-regex\n .replace(/[\\u0000-\\u001f\\u007f<>]/g, ' ')\n .replace(/\\s+/g, ' ')\n .trim()\n .slice(0, REMIX_TITLE_MAX)\n .trim();\n return t || 'a shared project';\n}\n\n/** WEBBUILDER_SNAPSHOT `name` must match /^[A-Za-z0-9._ -]{1,100}$/. */\nexport function snapshotNameForProject(title: string): string {\n const name = String(title || '')\n .replace(/[^A-Za-z0-9._ -]+/g, ' ')\n .replace(/\\s+/g, ' ')\n .trim()\n .slice(0, 60)\n .trim();\n return name || 'webbuilder-project';\n}\n\n/** snapshotId from a WEBBUILDER_SNAPSHOT result (validated). */\nexport function snapshotIdFromResult(data: Record<string, unknown> | null | undefined): string | null {\n const id = String(data?.snapshotId ?? data?.snapshotID ?? '').trim();\n return isValidSnapshotId(id) ? id : null;\n}\n\n/**\n * WEBBUILDER_SNAPSHOT params for a remix link. `excludeSecrets` leaves `.env*` / `.dev.vars`\n * out of the shared snapshot (they are put back in the user's sandbox right after).\n */\nexport function remixSnapshotParams(sandboxId: string, title: string): Record<string, unknown> {\n return { sandbox_id: sandboxId, name: snapshotNameForProject(title), excludeSecrets: true };\n}\n\nexport type RemixSecretsCheck = { ok: true; note: string | null } | { ok: false; message: string };\n\n/**\n * What the snapshot said about secret files (`data.secretFiles`, `data.secretsExcluded`):\n * left out -> a note naming them; found but still inside -> refuse to share the link.\n * An older connector returns neither field -> nothing to say.\n */\nexport function remixSecretsCheck(data: Record<string, unknown> | null | undefined): RemixSecretsCheck {\n const files = Array.isArray(data?.secretFiles)\n ? data.secretFiles.filter((f): f is string => typeof f === 'string' && f.trim() !== '')\n : [];\n if (!files.length) return { ok: true, note: null };\n const names = [...new Set(files.map((f) => f.split('/').filter(Boolean).pop() || f))];\n const shown = names.slice(0, 4).join(', ') + (names.length > 4 ? ` and ${names.length - 4} more` : '');\n if (data?.secretsExcluded !== true) {\n return {\n ok: false,\n message: `The template would include secret files (${shown}), so no link was made. Try again later.`,\n };\n }\n return { ok: true, note: `Left out of the template: ${shown}. They stay in your project only.` };\n}\n\n/** `<origin><path>?remix=<id>&title=<t>` - drops the current session's query params. */\nexport function buildRemixUrl(currentHref: string, snapshotId: string, title: string): string {\n if (!isValidSnapshotId(snapshotId)) throw new Error('invalid snapshot id');\n const u = new URL(currentHref);\n const out = new URL(`${u.origin}${u.pathname}`);\n out.searchParams.set('remix', snapshotId);\n out.searchParams.set('title', cleanRemixTitle(title));\n return out.toString();\n}\n\nexport type RemixQuery = { ok: true; snapshotId: string; title: string } | { ok: false };\n\n/** `?remix=` from a location search string; null when absent. */\nexport function parseRemixQuery(search: string): RemixQuery | null {\n const q = new URLSearchParams(search);\n if (!q.has('remix')) return null;\n const id = (q.get('remix') || '').trim();\n if (!isValidSnapshotId(id)) return { ok: false };\n return { ok: true, snapshotId: id, title: cleanRemixTitle(q.get('title')) };\n}\n\n/**\n * The prompt that starts a remix. It never contains the link's title: the\n * title comes from a URL anyone can craft, so it only rides along in the\n * template props (for display), never in text the AI reads as instructions.\n */\nexport const REMIX_PROMPT = 'Create a new project from the shared template';\n\nexport interface RemixSendRequest {\n prompt: string;\n template: { id: string; title: string; snapshotId: string; templateName: string; formTemplateId: string };\n}\n\n/** What the confirmed remix sends: the fixed prompt + the snapshot as a template (the existing remix path). */\nexport function remixSendRequest(remix: { snapshotId: string; title: string }): RemixSendRequest | null {\n if (!isValidSnapshotId(remix.snapshotId)) return null;\n return {\n prompt: REMIX_PROMPT,\n template: {\n id: REMIX_TEMPLATE_ID,\n title: cleanRemixTitle(remix.title),\n snapshotId: remix.snapshotId,\n templateName: 'vite-react',\n formTemplateId: REMIX_TEMPLATE_ID,\n },\n };\n}\n\n/** The search string without the one-shot remix params. */\nexport function stripRemixParams(search: string): string {\n const q = new URLSearchParams(search);\n q.delete('remix');\n q.delete('title');\n const s = q.toString();\n return s ? `?${s}` : '';\n}\n"],"names":[],"mappings":"AAOA,MAAM,cAAiB,GAAA,sGAAA;AAEhB,MAAM,eAAkB,GAAA;AACxB,SAAS,kBAAkB,EAA2B,EAAA;AAC3D,EAAO,OAAA,OAAO,OAAO,QAAY,IAAA,EAAA,CAAG,UAAU,GAAO,IAAA,cAAA,CAAe,KAAK,EAAE,CAAA;AAC7E;AAGO,SAAS,gBAAgB,GAAsB,EAAA;AACpD,EAAA,MAAM,IAAI,MAAO,CAA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,QAAQ,CAAE,CAAA,CAAA;AAC9C,EAAI,GAAA,CAAA,YAAA,CAAa,GAAI,CAAA,OAAA,EAAS,UAAU,CAAA;AACxC,EAAA,GAAA,CAAI,YAAa,CAAA,GAAA,CAAI,OAAS,EAAA,eAAA,CAAgB,KAAK,CAAC,CAAA;AACpD,EAAA,OAAO,IAAI,QAAS,EAAA;AACtB"}
@@ -0,0 +1,199 @@
1
+ import {runGql,failed}from'../data/graphql.js';import {unwrapResult}from'./okResult.js';import {roleOf,parseMembers}from'./roles.js';const PROJECT_MEMBERS_QUERY = `query aiCodeProjectMembers($channelId: String!) {
2
+ aiCodeProjectMembers(channelId: $channelId)
3
+ }`;
4
+ const SHARE_PROJECT_MUTATION = `mutation aiCodeShareProject($channelId: String!, $email: String!, $role: String!) {
5
+ aiCodeShareProject(channelId: $channelId, email: $email, role: $role)
6
+ }`;
7
+ const UPDATE_MEMBER_ROLE_MUTATION = `mutation aiCodeUpdateProjectMemberRole($channelId: String!, $userId: String!, $role: String!) {
8
+ aiCodeUpdateProjectMemberRole(channelId: $channelId, userId: $userId, role: $role)
9
+ }`;
10
+ const REMOVE_MEMBER_MUTATION = `mutation aiCodeRemoveProjectMember($channelId: String!, $userId: String!) {
11
+ aiCodeRemoveProjectMember(channelId: $channelId, userId: $userId)
12
+ }`;
13
+ const DELETE_PROJECT_MUTATION = `mutation aiCodeDeleteProject($channelId: String!) {
14
+ aiCodeDeleteProject(channelId: $channelId)
15
+ }`;
16
+ const CURRENT_USER_QUERY = `query WebbuilderCurrentUser {
17
+ getUserAccount { id }
18
+ }`;
19
+ const CHANNEL_CREATORS_QUERY = `query WebbuilderChannelCreators($criteria: AnyObject, $limit: Int, $skip: Int, $sort: Sort) {
20
+ channelsByUser(criteria: $criteria, limit: $limit, skip: $skip, sort: $sort) {
21
+ id
22
+ creator { id }
23
+ }
24
+ }`;
25
+ const SHARING_OUTDATED_MESSAGE = "Sharing needs the latest server";
26
+ function isRec(v) {
27
+ return Boolean(v) && typeof v === "object" && !Array.isArray(v);
28
+ }
29
+ function membersFromMutation(raw) {
30
+ if (Array.isArray(raw) || isRec(raw) && Array.isArray(raw.members) || typeof raw === "string") {
31
+ const list = parseMembers(raw);
32
+ return list.length ? list : null;
33
+ }
34
+ return null;
35
+ }
36
+ const MEMBER_KEYS = ["members"];
37
+ function createSharingService(call, opts) {
38
+ let me = null;
39
+ const memberCache = /* @__PURE__ */ new Map();
40
+ let outdated = false;
41
+ const currentUserId = () => {
42
+ if (!me) {
43
+ me = call(CURRENT_USER_QUERY, {}).then((r) => {
44
+ var _a, _b;
45
+ return typeof ((_b = (_a = r.data) == null ? void 0 : _a.getUserAccount) == null ? void 0 : _b.id) === "string" ? r.data.getUserAccount.id : null;
46
+ }).catch(() => null).then((id) => {
47
+ if (!id) me = null;
48
+ return id;
49
+ });
50
+ }
51
+ return me;
52
+ };
53
+ const members = async (channelId, o) => {
54
+ if (outdated) return {
55
+ ok: false,
56
+ outdated: true,
57
+ message: SHARING_OUTDATED_MESSAGE
58
+ };
59
+ const cached = memberCache.get(channelId);
60
+ if (cached && !(o == null ? void 0 : o.force)) return {
61
+ ok: true,
62
+ value: cached
63
+ };
64
+ const raw = await runGql(() => call(PROJECT_MEMBERS_QUERY, {
65
+ channelId
66
+ }), (d) => d.aiCodeProjectMembers, {
67
+ outdatedMessage: SHARING_OUTDATED_MESSAGE
68
+ });
69
+ const unwrapped = unwrapResult(raw, MEMBER_KEYS);
70
+ if (!unwrapped.ok) {
71
+ if (unwrapped.outdated) outdated = true;
72
+ return failed(unwrapped);
73
+ }
74
+ const r = {
75
+ ok: true,
76
+ value: parseMembers(unwrapped.value)
77
+ };
78
+ memberCache.set(channelId, r.value);
79
+ return r;
80
+ };
81
+ const myRole = async (channelId, o) => {
82
+ const [list, uid] = await Promise.all([members(channelId, o), currentUserId()]);
83
+ return list.ok ? roleOf(list.value, uid) : null;
84
+ };
85
+ const afterChange = async (channelId, r) => {
86
+ if (!r.ok) return failed(r);
87
+ const direct = membersFromMutation(r.value);
88
+ if (direct) {
89
+ memberCache.set(channelId, direct);
90
+ return {
91
+ ok: true,
92
+ value: direct
93
+ };
94
+ }
95
+ return members(channelId, {
96
+ force: true
97
+ });
98
+ };
99
+ const mutate = async (document, variables, field) => unwrapResult(await runGql(() => call(document, variables), (d) => d[field] === void 0 ? void 0 : d[field], {
100
+ outdatedMessage: SHARING_OUTDATED_MESSAGE
101
+ }), MEMBER_KEYS);
102
+ const share = async (channelId, email, role) => {
103
+ const r = await mutate(SHARE_PROJECT_MUTATION, {
104
+ channelId,
105
+ email,
106
+ role
107
+ }, "aiCodeShareProject");
108
+ return afterChange(channelId, r);
109
+ };
110
+ const updateRole = async (channelId, userId, role) => {
111
+ const r = await mutate(UPDATE_MEMBER_ROLE_MUTATION, {
112
+ channelId,
113
+ userId,
114
+ role
115
+ }, "aiCodeUpdateProjectMemberRole");
116
+ return afterChange(channelId, r);
117
+ };
118
+ const removeMember = async (channelId, userId) => {
119
+ const r = await mutate(REMOVE_MEMBER_MUTATION, {
120
+ channelId,
121
+ userId
122
+ }, "aiCodeRemoveProjectMember");
123
+ return afterChange(channelId, r);
124
+ };
125
+ const deleteProject = async (channelId) => {
126
+ const r = await mutate(DELETE_PROJECT_MUTATION, {
127
+ channelId
128
+ }, "aiCodeDeleteProject");
129
+ if (!r.ok) return r.outdated ? {
130
+ ok: false,
131
+ outdated: true,
132
+ message: r.message
133
+ } : {
134
+ ok: false,
135
+ message: r.message
136
+ };
137
+ if (r.value === false) return {
138
+ ok: false,
139
+ message: "The project could not be deleted."
140
+ };
141
+ memberCache.delete(channelId);
142
+ return {
143
+ ok: true
144
+ };
145
+ };
146
+ const creatorOf = async (channelIds) => {
147
+ var _a, _b, _c, _d, _e;
148
+ const r = await call(CHANNEL_CREATORS_QUERY, {
149
+ criteria: {
150
+ type: "AIASSISTANT"
151
+ },
152
+ limit: Math.min(200, Math.max(channelIds.length, (_b = (_a = void 0 ) == null ? void 0 : _a.call(opts)) != null ? _b : 0, 10)),
153
+ skip: 0,
154
+ sort: {
155
+ key: "updatedAt",
156
+ value: "DESC"
157
+ }
158
+ });
159
+ const out = /* @__PURE__ */ new Map();
160
+ for (const row of (_d = (_c = r.data) == null ? void 0 : _c.channelsByUser) != null ? _d : []) {
161
+ if ((row == null ? void 0 : row.id) && ((_e = row.creator) == null ? void 0 : _e.id)) out.set(row.id, row.creator.id);
162
+ }
163
+ return out;
164
+ };
165
+ const createdByMe = async (channelId) => {
166
+ try {
167
+ const [uid, creators] = await Promise.all([currentUserId(), creatorOf([channelId])]);
168
+ const creator = creators.get(channelId);
169
+ return uid && creator ? creator === uid : null;
170
+ } catch (e) {
171
+ return null;
172
+ }
173
+ };
174
+ const sharedWithMe = async (channelIds) => {
175
+ const out = /* @__PURE__ */ new Set();
176
+ if (!channelIds.length) return out;
177
+ try {
178
+ const [uid, creators] = await Promise.all([currentUserId(), creatorOf(channelIds)]);
179
+ if (!uid) return out;
180
+ for (const id of channelIds) {
181
+ const creator = creators.get(id);
182
+ if (creator && creator !== uid) out.add(id);
183
+ }
184
+ } catch (e) {
185
+ }
186
+ return out;
187
+ };
188
+ return {
189
+ currentUserId,
190
+ members,
191
+ myRole,
192
+ share,
193
+ updateRole,
194
+ removeMember,
195
+ deleteProject,
196
+ sharedWithMe,
197
+ createdByMe
198
+ };
199
+ }export{CHANNEL_CREATORS_QUERY,CURRENT_USER_QUERY,DELETE_PROJECT_MUTATION,PROJECT_MEMBERS_QUERY,REMOVE_MEMBER_MUTATION,SHARE_PROJECT_MUTATION,SHARING_OUTDATED_MESSAGE,UPDATE_MEMBER_ROLE_MUTATION,createSharingService};//# sourceMappingURL=sharingApi.js.map