@teleporthq/teleport-project-generator-next 0.45.21 → 0.45.22

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 (151) hide show
  1. package/__tests__/code-copy-runtime.test.ts +31 -24
  2. package/__tests__/forum-files-route.test.ts +147 -0
  3. package/__tests__/forum-markdown.test.ts +136 -0
  4. package/__tests__/forum-page-data.test.ts +1329 -0
  5. package/__tests__/forum-project-plugin.test.ts +789 -0
  6. package/__tests__/forum-replies-route.test.ts +82 -0
  7. package/__tests__/forum-topics-only-end2end.test.ts +124 -0
  8. package/__tests__/i18n-app-runtime.test.ts +187 -0
  9. package/__tests__/page-revalidate-plugin.test.ts +111 -0
  10. package/__tests__/rich-text-editor-frame.test.ts +25 -0
  11. package/dist/cjs/forum/files-route.d.ts +26 -0
  12. package/dist/cjs/forum/files-route.d.ts.map +1 -0
  13. package/dist/cjs/forum/files-route.js +42 -0
  14. package/dist/cjs/forum/files-route.js.map +1 -0
  15. package/dist/cjs/forum/markdown-source.d.ts +17 -0
  16. package/dist/cjs/forum/markdown-source.d.ts.map +1 -0
  17. package/dist/cjs/forum/markdown-source.js +23 -0
  18. package/dist/cjs/forum/markdown-source.js.map +1 -0
  19. package/dist/cjs/forum/notifications-route.d.ts +17 -0
  20. package/dist/cjs/forum/notifications-route.d.ts.map +1 -0
  21. package/dist/cjs/forum/notifications-route.js +30 -0
  22. package/dist/cjs/forum/notifications-route.js.map +1 -0
  23. package/dist/cjs/forum/page-data-source.d.ts +58 -0
  24. package/dist/cjs/forum/page-data-source.d.ts.map +1 -0
  25. package/dist/cjs/forum/page-data-source.js +168 -0
  26. package/dist/cjs/forum/page-data-source.js.map +1 -0
  27. package/dist/cjs/forum/page-rewrite.d.ts +50 -0
  28. package/dist/cjs/forum/page-rewrite.d.ts.map +1 -0
  29. package/dist/cjs/forum/page-rewrite.js +473 -0
  30. package/dist/cjs/forum/page-rewrite.js.map +1 -0
  31. package/dist/cjs/forum/project-plugin.d.ts +34 -0
  32. package/dist/cjs/forum/project-plugin.d.ts.map +1 -0
  33. package/dist/cjs/forum/project-plugin.js +272 -0
  34. package/dist/cjs/forum/project-plugin.js.map +1 -0
  35. package/dist/cjs/forum/replies-route.d.ts +21 -0
  36. package/dist/cjs/forum/replies-route.d.ts.map +1 -0
  37. package/dist/cjs/forum/replies-route.js +33 -0
  38. package/dist/cjs/forum/replies-route.js.map +1 -0
  39. package/dist/cjs/forum/seo.d.ts +29 -0
  40. package/dist/cjs/forum/seo.d.ts.map +1 -0
  41. package/dist/cjs/forum/seo.js +61 -0
  42. package/dist/cjs/forum/seo.js.map +1 -0
  43. package/dist/cjs/forum/settings.d.ts +97 -0
  44. package/dist/cjs/forum/settings.d.ts.map +1 -0
  45. package/dist/cjs/forum/settings.js +162 -0
  46. package/dist/cjs/forum/settings.js.map +1 -0
  47. package/dist/cjs/index.d.ts +1 -0
  48. package/dist/cjs/index.d.ts.map +1 -1
  49. package/dist/cjs/index.js +87 -80
  50. package/dist/cjs/index.js.map +1 -1
  51. package/dist/cjs/instant-search/sections.d.ts.map +1 -1
  52. package/dist/cjs/instant-search/sections.js +18 -0
  53. package/dist/cjs/instant-search/sections.js.map +1 -1
  54. package/dist/cjs/instant-search/settings.d.ts +1 -1
  55. package/dist/cjs/instant-search/settings.d.ts.map +1 -1
  56. package/dist/cjs/instant-search/settings.js +2 -0
  57. package/dist/cjs/instant-search/settings.js.map +1 -1
  58. package/dist/cjs/internationalization/app-i18n-runtime.d.ts +39 -0
  59. package/dist/cjs/internationalization/app-i18n-runtime.d.ts.map +1 -0
  60. package/dist/cjs/internationalization/app-i18n-runtime.js +126 -0
  61. package/dist/cjs/internationalization/app-i18n-runtime.js.map +1 -0
  62. package/dist/cjs/internationalization/project.d.ts.map +1 -1
  63. package/dist/cjs/internationalization/project.js +6 -0
  64. package/dist/cjs/internationalization/project.js.map +1 -1
  65. package/dist/cjs/page-revalidate/project-plugin.d.ts.map +1 -1
  66. package/dist/cjs/page-revalidate/project-plugin.js +5 -1
  67. package/dist/cjs/page-revalidate/project-plugin.js.map +1 -1
  68. package/dist/cjs/rich-text-editor/content-support-source.d.ts +2 -1
  69. package/dist/cjs/rich-text-editor/content-support-source.d.ts.map +1 -1
  70. package/dist/cjs/rich-text-editor/content-support-source.js +9 -2
  71. package/dist/cjs/rich-text-editor/content-support-source.js.map +1 -1
  72. package/dist/cjs/tsconfig.tsbuildinfo +1 -1
  73. package/dist/esm/forum/files-route.d.ts +26 -0
  74. package/dist/esm/forum/files-route.d.ts.map +1 -0
  75. package/dist/esm/forum/files-route.js +38 -0
  76. package/dist/esm/forum/files-route.js.map +1 -0
  77. package/dist/esm/forum/markdown-source.d.ts +17 -0
  78. package/dist/esm/forum/markdown-source.d.ts.map +1 -0
  79. package/dist/esm/forum/markdown-source.js +19 -0
  80. package/dist/esm/forum/markdown-source.js.map +1 -0
  81. package/dist/esm/forum/notifications-route.d.ts +17 -0
  82. package/dist/esm/forum/notifications-route.d.ts.map +1 -0
  83. package/dist/esm/forum/notifications-route.js +26 -0
  84. package/dist/esm/forum/notifications-route.js.map +1 -0
  85. package/dist/esm/forum/page-data-source.d.ts +58 -0
  86. package/dist/esm/forum/page-data-source.d.ts.map +1 -0
  87. package/dist/esm/forum/page-data-source.js +164 -0
  88. package/dist/esm/forum/page-data-source.js.map +1 -0
  89. package/dist/esm/forum/page-rewrite.d.ts +50 -0
  90. package/dist/esm/forum/page-rewrite.d.ts.map +1 -0
  91. package/dist/esm/forum/page-rewrite.js +446 -0
  92. package/dist/esm/forum/page-rewrite.js.map +1 -0
  93. package/dist/esm/forum/project-plugin.d.ts +34 -0
  94. package/dist/esm/forum/project-plugin.d.ts.map +1 -0
  95. package/dist/esm/forum/project-plugin.js +269 -0
  96. package/dist/esm/forum/project-plugin.js.map +1 -0
  97. package/dist/esm/forum/replies-route.d.ts +21 -0
  98. package/dist/esm/forum/replies-route.d.ts.map +1 -0
  99. package/dist/esm/forum/replies-route.js +29 -0
  100. package/dist/esm/forum/replies-route.js.map +1 -0
  101. package/dist/esm/forum/seo.d.ts +29 -0
  102. package/dist/esm/forum/seo.d.ts.map +1 -0
  103. package/dist/esm/forum/seo.js +56 -0
  104. package/dist/esm/forum/seo.js.map +1 -0
  105. package/dist/esm/forum/settings.d.ts +97 -0
  106. package/dist/esm/forum/settings.d.ts.map +1 -0
  107. package/dist/esm/forum/settings.js +158 -0
  108. package/dist/esm/forum/settings.js.map +1 -0
  109. package/dist/esm/index.d.ts +1 -0
  110. package/dist/esm/index.d.ts.map +1 -1
  111. package/dist/esm/index.js +6 -0
  112. package/dist/esm/index.js.map +1 -1
  113. package/dist/esm/instant-search/sections.d.ts.map +1 -1
  114. package/dist/esm/instant-search/sections.js +18 -0
  115. package/dist/esm/instant-search/sections.js.map +1 -1
  116. package/dist/esm/instant-search/settings.d.ts +1 -1
  117. package/dist/esm/instant-search/settings.d.ts.map +1 -1
  118. package/dist/esm/instant-search/settings.js +2 -0
  119. package/dist/esm/instant-search/settings.js.map +1 -1
  120. package/dist/esm/internationalization/app-i18n-runtime.d.ts +39 -0
  121. package/dist/esm/internationalization/app-i18n-runtime.d.ts.map +1 -0
  122. package/dist/esm/internationalization/app-i18n-runtime.js +120 -0
  123. package/dist/esm/internationalization/app-i18n-runtime.js.map +1 -0
  124. package/dist/esm/internationalization/project.d.ts.map +1 -1
  125. package/dist/esm/internationalization/project.js +6 -0
  126. package/dist/esm/internationalization/project.js.map +1 -1
  127. package/dist/esm/page-revalidate/project-plugin.d.ts.map +1 -1
  128. package/dist/esm/page-revalidate/project-plugin.js +5 -1
  129. package/dist/esm/page-revalidate/project-plugin.js.map +1 -1
  130. package/dist/esm/rich-text-editor/content-support-source.d.ts +2 -1
  131. package/dist/esm/rich-text-editor/content-support-source.d.ts.map +1 -1
  132. package/dist/esm/rich-text-editor/content-support-source.js +9 -2
  133. package/dist/esm/rich-text-editor/content-support-source.js.map +1 -1
  134. package/dist/esm/tsconfig.tsbuildinfo +1 -1
  135. package/package.json +19 -19
  136. package/src/forum/files-route.ts +133 -0
  137. package/src/forum/markdown-source.ts +177 -0
  138. package/src/forum/notifications-route.ts +87 -0
  139. package/src/forum/page-data-source.ts +810 -0
  140. package/src/forum/page-rewrite.ts +567 -0
  141. package/src/forum/project-plugin.ts +328 -0
  142. package/src/forum/replies-route.ts +91 -0
  143. package/src/forum/seo.ts +245 -0
  144. package/src/forum/settings.ts +261 -0
  145. package/src/index.ts +6 -0
  146. package/src/instant-search/sections.ts +20 -0
  147. package/src/instant-search/settings.ts +2 -0
  148. package/src/internationalization/app-i18n-runtime.ts +165 -0
  149. package/src/internationalization/project.ts +7 -0
  150. package/src/page-revalidate/project-plugin.ts +5 -1
  151. package/src/rich-text-editor/content-support-source.ts +14 -2
@@ -0,0 +1,810 @@
1
+ import { SessionCookieResolver } from '@teleporthq/teleport-shared'
2
+ import { generateLazyPgClientCode } from '@teleporthq/teleport-plugin-next-workflows'
3
+ import { toJsLiteral } from '../pwa/source-literals'
4
+ import { FORUM_SEO_RUNTIME } from './seo'
5
+ import { ForumConfig, FORUM_TABLES } from './settings'
6
+ import { FORUM_MARKDOWN_MODULE_NAME } from './markdown-source'
7
+
8
+ export const FORUM_PAGE_DATA_MODULE_PATH = ['utils']
9
+ export const FORUM_PAGE_DATA_MODULE_NAME = 'forum-page-data'
10
+
11
+ /** How many replies one read of the tree or of `/api/plugins/forum/replies` takes. */
12
+ export const FORUM_REPLIES_PAGE = 50
13
+ const TOPIC_COLUMNS = [
14
+ 'id',
15
+ 'community_id',
16
+ 'community_slug',
17
+ 'community_name',
18
+ 'community_visibility',
19
+ 'author_id',
20
+ 'author_handle',
21
+ 'author_name',
22
+ 'author_avatar',
23
+ 'title',
24
+ 'slug',
25
+ 'body',
26
+ 'body_text',
27
+ 'tags',
28
+ 'attachments',
29
+ 'status',
30
+ 'is_pinned',
31
+ 'is_locked',
32
+ 'accepted_reply_id',
33
+ 'score',
34
+ 'upvotes',
35
+ 'downvotes',
36
+ 'reply_count',
37
+ 'view_count',
38
+ 'last_activity_at',
39
+ 'edited_at',
40
+ 'removed_reason',
41
+ 'created_at',
42
+ 'updated_at',
43
+ ]
44
+ const REPLY_COLUMNS = [
45
+ 'id',
46
+ 'topic_id',
47
+ 'community_id',
48
+ 'parent_id',
49
+ 'depth',
50
+ 'path',
51
+ 'author_id',
52
+ 'author_handle',
53
+ 'author_name',
54
+ 'author_avatar',
55
+ 'body',
56
+ 'body_text',
57
+ 'attachments',
58
+ 'status',
59
+ 'score',
60
+ 'upvotes',
61
+ 'downvotes',
62
+ 'is_accepted',
63
+ 'quote_of',
64
+ 'edited_at',
65
+ 'removed_reason',
66
+ 'created_at',
67
+ 'updated_at',
68
+ ]
69
+ const COMMUNITY_COLUMNS = [
70
+ 'id',
71
+ 'slug',
72
+ 'name',
73
+ 'description',
74
+ 'rules',
75
+ 'icon_url',
76
+ 'banner_url',
77
+ 'kind',
78
+ 'visibility',
79
+ 'posting',
80
+ 'status',
81
+ 'created_by',
82
+ 'member_count',
83
+ 'topic_count',
84
+ 'last_activity_at',
85
+ 'is_featured',
86
+ 'sort_order',
87
+ 'created_at',
88
+ 'updated_at',
89
+ ]
90
+ /** The public columns of a member's forum profile: never an e-mail, never a note. */
91
+ const PROFILE_COLUMNS = [
92
+ 'user_id',
93
+ 'handle',
94
+ 'display_name',
95
+ 'avatar_url',
96
+ 'reputation',
97
+ 'badges',
98
+ 'role',
99
+ ]
100
+
101
+ const columns = (alias: string, names: string[]): string =>
102
+ names.map((name) => `${alias}.${name}`).join(', ')
103
+
104
+ /**
105
+ * `utils/forum-page-data.js` (plan D14b): what the topic, community, Manage
106
+ * and New topic pages render per request, and what the replies and
107
+ * notifications routes answer. Parameterised SQL only, over the forum tables,
108
+ * through the project's own database connection (the one the data API opens:
109
+ * `TELEPORT_DB_*`).
110
+ *
111
+ * Rules, applied here and nowhere else:
112
+ * - a topic or reply is served when `published`, or to a viewer who moderates
113
+ * it or wrote it (their own pending post);
114
+ * - a private community is read by its active members and moderators only:
115
+ * to anyone else its topics answer `null` (the page answers `notFound`) and
116
+ * its own page only the About side (`viewer.can_read` false, no topics);
117
+ * - a community that is not `active` is answered to who moderates it, and one
118
+ * still `pending` (waiting for approval) to its creator too
119
+ * (`viewer.is_creator`); its topics are in no public list;
120
+ * - Manage is served to who moderates the community, New topic to a signed-in
121
+ * viewer who can read it (`loadCommunityGate`): `null` for anyone else;
122
+ * - the reply tree is at most three levels from its root, in `path` order,
123
+ * the accepted answer first under `best`; a removed reply keeps its place
124
+ * with its body masked so the thread under it still reads. With flat
125
+ * replies (`SETTINGS.replyNesting` is `flat`) it is one level: every reply
126
+ * of the topic in the chosen order, an old reply to a reply among them;
127
+ * - without votes (`SETTINGS.votes` is `off`) there is no score, so no `top`
128
+ * order of a community's topics;
129
+ * - the viewer block says what the pages gate on: `signed_in`, `my_vote` (by
130
+ * target id), `my_membership`, `my_role`, `can_moderate`, `can_read`,
131
+ * `can_post` (anyone signed in where the community is public, an active
132
+ * member elsewhere; where only moderators post, one who moderates),
133
+ * `can_reply` (the reply statement's rule: as `can_post`, but only a
134
+ * `moderators` posting rule keeps members out — an announcements community
135
+ * takes its members' replies), and on
136
+ * a topic `is_subscribed`, `is_author`, `can_accept`, `can_edit` (every
137
+ * reply carries its own `can_edit`): as the edit statement decides it,
138
+ * never banned nor a removed post, and who moderates it or its author within
139
+ * `SETTINGS.editWindowMinutes` of writing it (0: always);
140
+ * - the shapes the pages bind are listed in the editor's
141
+ * `features/forum/constants/forum-shapes.ts`: `tags` as `[{ name }]`,
142
+ * `attachments` as `[{ url }]`, `body_html`, `community_name`,
143
+ * `community_url`, `accepted_reply`, `is_mine`, `thread_url`, `rules_text`;
144
+ * - author profiles carry public columns only;
145
+ * - a forum without communities (`SETTINGS.structure` is `topics`) keeps every
146
+ * topic in one community of its own. It is read for the rights like any
147
+ * other and never answered: no topic names it or links to it, the composer's
148
+ * gate answers the viewer alone, and it has no page and no place in the
149
+ * public index.
150
+ *
151
+ * Every row goes out JSON-plain (dates as ISO strings): Next.js props.
152
+ */
153
+ export const buildForumPageDataSource = (
154
+ config: ForumConfig,
155
+ options: { withSessionRevocation?: boolean } = {}
156
+ ): string => {
157
+ const { settings } = config
158
+ // Where the details pages are served (`forum-markers.ts` there: `/forum/t`, `/forum/c`);
159
+ // a forum without communities has no community page to link to.
160
+ const urls = {
161
+ topic: config.routes.topic?.staticBase || '/forum/t',
162
+ community:
163
+ settings.structure === 'communities' ? config.routes.community?.staticBase || '/forum/c' : '',
164
+ }
165
+ return `'use strict';
166
+ // Forum page data — generated by TeleportHQ. Server-side only.
167
+ ${generateLazyPgClientCode()}
168
+ var markdown = require('./${FORUM_MARKDOWN_MODULE_NAME}');
169
+
170
+ ${SessionCookieResolver.generateCommonJsSessionTokenResolverCode('..', {
171
+ withRevocation: options.withSessionRevocation !== false,
172
+ })}
173
+ // The session cookie's token for a page or route, or null: who is asking.
174
+ async function readSession(req) {
175
+ try {
176
+ return (await __tqSessionToken(req)) || null;
177
+ } catch (error) {
178
+ return null;
179
+ }
180
+ }
181
+
182
+ var SETTINGS = ${toJsLiteral(settings)};
183
+ // A forum without communities keeps its topics in one community of its own: read for the rights, never answered.
184
+ var HAS_COMMUNITIES = SETTINGS.structure !== 'topics';
185
+ // Flat replies: one list of every reply, an old reply to a reply among them rather than lost.
186
+ var FLAT_REPLIES = SETTINGS.replyNesting === 'flat';
187
+ var T =${toJsLiteral(FORUM_TABLES)};
188
+ var REPLIES_PAGE = ${FORUM_REPLIES_PAGE};
189
+ var TOPICS_PER_PAGE = ${config.communityTopicsPerPage};
190
+ var MAX_DEPTH = 3;
191
+ var EXCERPT_LENGTH = 240;
192
+ var NOTIFICATIONS_PAGE = 30;
193
+ var URLS = ${toJsLiteral(urls)};
194
+ var STAFF_ROLES = ['admin'];
195
+ var TOPIC_SQL = ${toJsLiteral(columns('t', TOPIC_COLUMNS))};
196
+ var REPLY_SQL = ${toJsLiteral(columns('r', REPLY_COLUMNS))};
197
+ var COMMUNITY_SQL = ${toJsLiteral(columns('c', COMMUNITY_COLUMNS))};
198
+ var PROFILE_SQL = ${toJsLiteral(columns('p', PROFILE_COLUMNS))};
199
+ var REPLY_SORTS = {
200
+ best: 'r.is_accepted DESC, r.score DESC, r.created_at ASC',
201
+ new: 'r.created_at DESC',
202
+ old: 'r.created_at ASC',
203
+ };
204
+ var TOPIC_SORTS = {
205
+ latest: 't.last_activity_at DESC NULLS LAST, t.created_at DESC',
206
+ top: 't.score DESC, t.created_at DESC',
207
+ new: 't.created_at DESC',
208
+ unanswered: 't.reply_count ASC, t.created_at DESC',
209
+ };
210
+
211
+ ${FORUM_SEO_RUNTIME}
212
+ // --- helpers ------------------------------------------------------------------
213
+ function text(value) { return value === undefined || value === null ? '' : String(value); }
214
+ function num(value) { var n = Number(value); return isFinite(n) ? n : 0; }
215
+ function list(value) {
216
+ if (Array.isArray(value)) return value;
217
+ try { var parsed = JSON.parse(text(value) || '[]'); return Array.isArray(parsed) ? parsed : []; } catch (e) { return []; }
218
+ }
219
+ // A row as JSON-plain values: a Date becomes its ISO string, undefined null.
220
+ function plain(row) {
221
+ var out = {};
222
+ Object.keys(row || {}).forEach(function (key) {
223
+ var value = row[key];
224
+ out[key] = value instanceof Date ? value.toISOString() : value === undefined ? null : value;
225
+ });
226
+ return out;
227
+ }
228
+ function stringList(value) { return list(value).filter(function (item) { return typeof item === 'string' && item !== ''; }); }
229
+ // The rules column as the manage form's textarea shows it: one rule per line, "title: text".
230
+ function rulesText(rules) {
231
+ return list(rules).map(function (rule) {
232
+ if (!rule || typeof rule !== 'object') return '';
233
+ var title = text(rule.title).trim();
234
+ var body = text(rule.text).trim();
235
+ return title && body ? title + ': ' + body : title || body;
236
+ }).filter(Boolean).join('\\n');
237
+ }
238
+ function threadUrlOf(topicSlug, replyId) {
239
+ return URLS.topic + '/' + encodeURIComponent(text(topicSlug)) + '?reply=' + encodeURIComponent(text(replyId));
240
+ }
241
+ function communityUrlOf(communitySlug) {
242
+ return URLS.community + '/' + encodeURIComponent(text(communitySlug));
243
+ }
244
+ // A topic's community as the pages bind it: its name (the topic's own column, the community's for a topic
245
+ // written before the column existed) and where its page is. A forum without communities answers neither, nor its slug.
246
+ function nameCommunity(post, community) {
247
+ post.community_name = HAS_COMMUNITIES ? text(post.community_name) || text(community.name) : '';
248
+ post.community_url = HAS_COMMUNITIES ? communityUrlOf(community.slug) : '';
249
+ if (!HAS_COMMUNITIES) post.community_slug = '';
250
+ }
251
+ function excerptOf(bodyText) {
252
+ var words = text(bodyText).replace(/\\s+/g, ' ').trim();
253
+ return words.length > EXCERPT_LENGTH ? words.slice(0, EXCERPT_LENGTH).replace(/\\s+\\S*$/, '') + '…' : words;
254
+ }
255
+ function sessionOf(session) {
256
+ var token = session && typeof session === 'object' ? session : null;
257
+ var id = token ? text(token.id || token.sub) : '';
258
+ var role = token ? (typeof token.role === 'string' ? token.role : Array.isArray(token.roles) ? token.roles[0] : null) : null;
259
+ return { id: id, role: role || null };
260
+ }
261
+ function sortKey(value, sorts, fallback) {
262
+ var key = text(value);
263
+ return Object.prototype.hasOwnProperty.call(sorts, key) ? key : fallback;
264
+ }
265
+
266
+ // One connection per call: opened, used for every read of the call, closed.
267
+ async function withClient(work) {
268
+ var client = getClient();
269
+ await client.connect();
270
+ try {
271
+ return await work(function query(sql, params) {
272
+ return client.query(sql, params || []).then(function (result) { return result.rows || []; });
273
+ });
274
+ } finally {
275
+ try { await client.end(); } catch (e) {}
276
+ }
277
+ }
278
+
279
+ // --- the viewer ------------------------------------------------------------------
280
+ async function viewerOf(q, user, community) {
281
+ var viewer = {
282
+ signed_in: !!user.id,
283
+ user_id: user.id || null,
284
+ my_membership: null,
285
+ my_role: null,
286
+ can_moderate: false,
287
+ can_delete: false,
288
+ can_read: true,
289
+ can_post: false,
290
+ can_reply: false,
291
+ is_author: false,
292
+ can_accept: false,
293
+ can_edit: false,
294
+ my_vote: 0,
295
+ profile_role: null,
296
+ is_banned: false,
297
+ };
298
+ if (user.id) {
299
+ var profiles = await q('SELECT ' + PROFILE_SQL + ' FROM ' + T.profiles + ' p WHERE p.user_id = $1 LIMIT 1', [user.id]);
300
+ var profile = profiles[0] || null;
301
+ viewer.profile_role = profile ? text(profile.role) || 'member' : null;
302
+ viewer.is_banned = !!profile && profile.role === 'banned';
303
+ var staff = STAFF_ROLES.indexOf(text(user.role)) !== -1 || viewer.profile_role === 'moderator';
304
+ viewer.can_moderate = staff;
305
+ if (community) {
306
+ var memberships = await q(
307
+ 'SELECT m.role, m.status FROM ' + T.memberships + ' m WHERE m.community_id = $1 AND m.user_id = $2 LIMIT 1',
308
+ [community.id, user.id]
309
+ );
310
+ var membership = memberships[0] || null;
311
+ viewer.my_membership = membership ? text(membership.status) : null;
312
+ viewer.my_role = membership ? text(membership.role) : null;
313
+ var active = !!membership && membership.status === 'active';
314
+ viewer.can_moderate = staff || (active && (membership.role === 'moderator' || membership.role === 'owner'));
315
+ // Who deletes the whole community, as its statement decides: the owner, a site moderator or an admin.
316
+ viewer.can_delete = HAS_COMMUNITIES && (staff || (active && membership.role === 'owner'));
317
+ }
318
+ }
319
+ if (community) {
320
+ var member = viewer.my_membership === 'active';
321
+ viewer.can_read = community.visibility !== 'private' || member || viewer.can_moderate;
322
+ // Posting, as the statements decide it: anyone signed in where the community
323
+ // is public (unless banned from it), its active members elsewhere; where only
324
+ // moderators post (the community's setting, or an announcements community),
325
+ // the ones who moderate it.
326
+ var moderatorsOnly = community.posting === 'moderators' || community.kind === 'announcements';
327
+ var admitted = member || (viewer.signed_in && community.visibility === 'public' && viewer.my_membership !== 'banned');
328
+ viewer.can_post = admitted && !viewer.is_banned && community.status === 'active' && (!moderatorsOnly || viewer.can_moderate);
329
+ viewer.can_reply = admitted && !viewer.is_banned && community.status === 'active' && (community.posting !== 'moderators' || viewer.can_moderate);
330
+ }
331
+ return viewer;
332
+ }
333
+
334
+ // Whether the viewer may edit this topic or reply, as the edit statement decides it: never banned, never a
335
+ // removed post; who moderates it, or its author within SETTINGS.editWindowMinutes of writing it (0: always).
336
+ function canEdit(viewer, row) {
337
+ if (!viewer.signed_in || viewer.is_banned || row.status === 'removed') return false;
338
+ if (viewer.can_moderate) return true;
339
+ if (text(row.author_id) !== viewer.user_id) return false;
340
+ return SETTINGS.editWindowMinutes === 0 || new Date(row.created_at).getTime() > Date.now() - SETTINGS.editWindowMinutes * 60000;
341
+ }
342
+
343
+ async function votesOf(q, user, targetIds) {
344
+ var votes = {};
345
+ if (!user.id || !targetIds.length) return votes;
346
+ var rows = await q('SELECT v.target_id, v.value FROM ' + T.votes + ' v WHERE v.user_id = $1 AND v.target_id = ANY($2::uuid[])', [user.id, targetIds]);
347
+ rows.forEach(function (row) { votes[text(row.target_id)] = num(row.value); });
348
+ return votes;
349
+ }
350
+
351
+ // Following is a topic's: joining a community is how it is followed.
352
+ async function followsTopic(q, user, topicId) {
353
+ if (!user.id) return false;
354
+ var rows = await q('SELECT 1 FROM ' + T.subscriptions + " s WHERE s.user_id = $1 AND s.target_kind = 'topic' AND s.target_id = $2 LIMIT 1", [user.id, topicId]);
355
+ return rows.length > 0;
356
+ }
357
+
358
+ // { [targetId]: { [emoji]: { count, mine } } } for every target asked.
359
+ async function reactionsOf(q, user, targetIds) {
360
+ var byTarget = {};
361
+ targetIds.forEach(function (id) { byTarget[id] = {}; });
362
+ if (!SETTINGS.reactions || !targetIds.length) return byTarget;
363
+ var rows = await q(
364
+ 'SELECT x.target_id, x.emoji, COUNT(*)::int AS count, BOOL_OR(x.user_id = $2) AS mine FROM ' + T.reactions +
365
+ ' x WHERE x.target_id = ANY($1::uuid[]) GROUP BY x.target_id, x.emoji',
366
+ [targetIds, user.id || '']
367
+ );
368
+ rows.forEach(function (row) {
369
+ var id = text(row.target_id);
370
+ if (!id || !row.emoji) return;
371
+ if (!byTarget[id]) byTarget[id] = {};
372
+ byTarget[id][text(row.emoji)] = { count: num(row.count), mine: !!row.mine && !!user.id };
373
+ });
374
+ return byTarget;
375
+ }
376
+
377
+ function authorOf(row) {
378
+ return {
379
+ id: text(row.author_id),
380
+ handle: text(row.author_handle),
381
+ name: text(row.author_name),
382
+ avatar: row.author_avatar || null,
383
+ reputation: SETTINGS.reputation ? num(row.author_reputation) : 0,
384
+ badges: SETTINGS.badges ? list(row.author_badges) : [],
385
+ initials: text(row.author_name).split(/\\s+/).map(function (w) { return w.charAt(0); }).join('').slice(0, 2).toUpperCase(),
386
+ };
387
+ }
388
+
389
+ // The public shape of a topic or reply: Markdown rendered, JSON columns parsed,
390
+ // a removed one masked so the thread keeps its place.
391
+ function shapePost(row, votes, reactions) {
392
+ var out = plain(row);
393
+ delete out.author_badges;
394
+ // The page's author line binds author_reputation as a number of its own.
395
+ out.author_reputation = SETTINGS.reputation ? num(row.author_reputation) : 0;
396
+ var removed = row.status === 'removed';
397
+ out.body = removed ? '' : text(row.body);
398
+ out.body_text = removed ? '[removed]' : text(row.body_text);
399
+ out.body_html = removed ? '<p><em>[removed]</em></p>' : markdown.renderForumMarkdown(row.body);
400
+ out.excerpt = excerptOf(out.body_text);
401
+ // The pages bind tags as [{ name }] and attachments as [{ url }] (forum-shapes.ts there);
402
+ // the plain lists stay beside them.
403
+ out.tag_list = stringList(row.tags);
404
+ out.tags = out.tag_list.map(function (name) { return { name: name }; });
405
+ out.attachment_list = removed ? [] : stringList(row.attachments);
406
+ out.attachments = out.attachment_list.map(function (url) { return { url: url }; });
407
+ out.author = authorOf(row);
408
+ out.my_vote = votes[text(row.id)] || 0;
409
+ out.is_mine = false;
410
+ out.reactions = reactions[text(row.id)] || {};
411
+ // The same derived fields the feed transform gives a card (forum-feed.ts).
412
+ out.is_solved = !!row.accepted_reply_id;
413
+ out.is_answered = num(row.reply_count) > 0;
414
+ out.author_initials = out.author.initials;
415
+ return out;
416
+ }
417
+
418
+ function shapeCommunity(row) {
419
+ var out = plain(row);
420
+ out.rule_list = list(row.rules).filter(function (rule) { return rule && typeof rule === 'object'; });
421
+ out.rules_text = rulesText(row.rules);
422
+ out.excerpt = excerptOf(row.description);
423
+ out.is_private = row.visibility === 'private';
424
+ out.initials = text(row.name).split(/\s+/).filter(Boolean).map(function (w) { return w.charAt(0); }).join('').slice(0, 2).toUpperCase();
425
+ return out;
426
+ }
427
+
428
+ // --- replies -----------------------------------------------------------------------
429
+ function postVisibility(alias, viewer, user, params) {
430
+ // Published and removed rows for everyone (a removed one is masked); pending
431
+ // ones for a moderator, and to their own author.
432
+ if (viewer.can_moderate) return "(" + alias + ".status IN ('published', 'removed', 'pending'))";
433
+ if (user.id) {
434
+ params.push(user.id);
435
+ return "(" + alias + ".status IN ('published', 'removed') OR (" + alias + ".status = 'pending' AND " + alias + ".author_id = $" + params.length + '))';
436
+ }
437
+ return "(" + alias + ".status IN ('published', 'removed'))";
438
+ }
439
+
440
+ // A community's list: published topics, plus the pending ones a moderator
441
+ // reviews and a member's own; removed topics are gone from every list.
442
+ function topicVisibility(viewer, user, params) {
443
+ if (viewer.can_moderate) return "(t.status IN ('published', 'pending'))";
444
+ if (user.id) {
445
+ params.push(user.id);
446
+ return "(t.status = 'published' OR (t.status = 'pending' AND t.author_id = $" + params.length + '))';
447
+ }
448
+ return "(t.status = 'published')";
449
+ }
450
+
451
+ function nest(rows, rootDepth, sort) {
452
+ var byId = {};
453
+ var roots = [];
454
+ rows.forEach(function (row) { row.children = []; byId[row.id] = row; });
455
+ rows.forEach(function (row) {
456
+ var parent = row.depth > rootDepth && row.parent_id ? byId[text(row.parent_id)] : null;
457
+ if (parent) parent.children.push(row); else roots.push(row);
458
+ });
459
+ var compare = sort === 'new'
460
+ ? function (a, b) { return text(b.created_at).localeCompare(text(a.created_at)); }
461
+ : sort === 'old'
462
+ ? function (a, b) { return text(a.created_at).localeCompare(text(b.created_at)); }
463
+ : function (a, b) { return (b.is_accepted ? 1 : 0) - (a.is_accepted ? 1 : 0) || num(b.score) - num(a.score) || text(a.created_at).localeCompare(text(b.created_at)); };
464
+ var sortTree = function (nodes) { nodes.sort(compare); nodes.forEach(function (node) { sortTree(node.children); }); };
465
+ sortTree(roots);
466
+ return roots;
467
+ }
468
+
469
+ // The tree under a topic (or under one reply, "Continue this thread"): the
470
+ // first REPLIES_PAGE roots after the offset and what is under them. MAX_DEPTH
471
+ // levels are drawn, the roots being the first; one level more is read, only so
472
+ // a reply of the last drawn level can say its thread goes on. Flat replies are
473
+ // one level: the first REPLIES_PAGE of every reply, whatever it answers (a
474
+ // "Continue this thread" link reads the same list).
475
+ async function replyTree(q, user, viewer, topic, rootReplyId, sort, offset) {
476
+ var rootDepth = -1;
477
+ var params = [topic.id];
478
+ var where = 'r.topic_id = $1';
479
+ if (rootReplyId && !FLAT_REPLIES) {
480
+ var roots = await q('SELECT r.id, r.depth, r.path FROM ' + T.replies + ' r WHERE r.topic_id = $1 AND r.id = $2 LIMIT 1', [topic.id, rootReplyId]);
481
+ if (!roots.length) return { replies: [], hasMore: false, nextOffset: 0 };
482
+ rootDepth = num(roots[0].depth);
483
+ params.push(roots[0].id);
484
+ where += ' AND r.parent_id = $2';
485
+ } else if (!FLAT_REPLIES) {
486
+ where += ' AND r.parent_id IS NULL';
487
+ }
488
+ where += ' AND ' + postVisibility('r', viewer, user, params);
489
+ params.push(REPLIES_PAGE + 1, Math.max(0, num(offset)));
490
+ var heads = await q(
491
+ 'SELECT ' + REPLY_SQL + ', p.reputation AS author_reputation, p.badges AS author_badges FROM ' + T.replies + ' r LEFT JOIN ' + T.profiles +
492
+ ' p ON p.user_id = r.author_id WHERE ' + where + ' ORDER BY ' + REPLY_SORTS[sort] + ' LIMIT $' + (params.length - 1) + ' OFFSET $' + params.length,
493
+ params
494
+ );
495
+ var hasMore = heads.length > REPLIES_PAGE;
496
+ heads = heads.slice(0, REPLIES_PAGE);
497
+ var rows = heads;
498
+ if (heads.length && !FLAT_REPLIES) {
499
+ var patterns = heads.map(function (head) { return text(head.path) + '%'; });
500
+ var childParams = [topic.id, patterns, rootDepth + MAX_DEPTH + 1, heads.map(function (head) { return head.id; })];
501
+ var children = await q(
502
+ 'SELECT ' + REPLY_SQL + ', p.reputation AS author_reputation, p.badges AS author_badges FROM ' + T.replies + ' r LEFT JOIN ' + T.profiles +
503
+ ' p ON p.user_id = r.author_id WHERE r.topic_id = $1 AND r.path LIKE ANY($2::text[]) AND r.depth <= $3 AND NOT (r.id = ANY($4::uuid[])) AND ' +
504
+ postVisibility('r', viewer, user, childParams) + ' ORDER BY r.path',
505
+ childParams
506
+ );
507
+ rows = heads.concat(children);
508
+ }
509
+ var ids = rows.map(function (row) { return row.id; });
510
+ var votes = await votesOf(q, user, ids);
511
+ var reactions = await reactionsOf(q, user, ids);
512
+ var shaped = rows.map(function (row) { return shapeReply(row, user, viewer, topic, votes, reactions); });
513
+ // A flat list is in the database's order already, and nests nothing.
514
+ return { replies: FLAT_REPLIES ? shaped : nest(shaped, rootDepth, sort), hasMore: hasMore, nextOffset: num(offset) + heads.length };
515
+ }
516
+
517
+ // One reply as the Reply component binds it: the viewer's own, whether they may edit it, and where its thread continues.
518
+ function shapeReply(row, user, viewer, topic, votes, reactions) {
519
+ var post = shapePost(row, votes, reactions);
520
+ post.is_author = !!user.id && text(row.author_id) === user.id;
521
+ post.is_mine = post.is_author;
522
+ post.can_edit = canEdit(viewer, row);
523
+ post.thread_url = threadUrlOf(topic.slug, row.id);
524
+ if (!Array.isArray(post.children)) post.children = [];
525
+ return post;
526
+ }
527
+
528
+ // The accepted answer as a reply row (the "Accepted answer" block), from the
529
+ // tree when it is on this page, else read by id; null when there is none.
530
+ async function acceptedReplyOf(q, user, viewer, topic, replies) {
531
+ var acceptedId = text(topic.accepted_reply_id);
532
+ if (!acceptedId) return null;
533
+ var inTree = flatten(replies).filter(function (reply) { return text(reply.id) === acceptedId; })[0];
534
+ if (inTree) return inTree;
535
+ var params = [topic.id, acceptedId];
536
+ var rows = await q(
537
+ 'SELECT ' + REPLY_SQL + ', p.reputation AS author_reputation, p.badges AS author_badges FROM ' + T.replies + ' r LEFT JOIN ' + T.profiles +
538
+ ' p ON p.user_id = r.author_id WHERE r.topic_id = $1 AND r.id = $2 AND ' + postVisibility('r', viewer, user, params) + ' LIMIT 1',
539
+ params
540
+ );
541
+ if (!rows.length) return null;
542
+ var votes = await votesOf(q, user, [rows[0].id]);
543
+ var reactions = await reactionsOf(q, user, [rows[0].id]);
544
+ var reply = shapeReply(rows[0], user, viewer, topic, votes, reactions);
545
+ reply.children = [];
546
+ return reply;
547
+ }
548
+
549
+ async function readableTopic(q, user, slugOrId, byId) {
550
+ var topics = await q(
551
+ 'SELECT ' + TOPIC_SQL + ', p.reputation AS author_reputation, p.badges AS author_badges FROM ' + T.topics + ' t LEFT JOIN ' + T.profiles +
552
+ ' p ON p.user_id = t.author_id WHERE t.' + (byId ? 'id' : 'slug') + ' = $1 LIMIT 1',
553
+ [slugOrId]
554
+ );
555
+ var topic = topics[0];
556
+ if (!topic) return null;
557
+ var communities = await q('SELECT ' + COMMUNITY_SQL + ' FROM ' + T.communities + ' c WHERE c.id = $1 LIMIT 1', [topic.community_id]);
558
+ var community = communities[0];
559
+ if (!community) return null;
560
+ var viewer = await viewerOf(q, user, community);
561
+ viewer.is_author = !!user.id && text(topic.author_id) === user.id;
562
+ viewer.can_accept = (viewer.is_author || viewer.can_moderate) && SETTINGS.acceptedAnswers !== 'off' &&
563
+ (SETTINGS.acceptedAnswers === 'all' || community.kind === 'questions');
564
+ viewer.can_edit = canEdit(viewer, topic);
565
+ if (!viewer.can_read) return null;
566
+ if (topic.status !== 'published' && !(viewer.can_moderate || viewer.is_author)) return null;
567
+ if (community.status !== 'active' && !viewer.can_moderate) return null;
568
+ return { topic: topic, community: community, viewer: viewer };
569
+ }
570
+
571
+ // --- the pages ---------------------------------------------------------------------
572
+ // { topic, community, viewer, replies, reactions, score, myVote, hasMoreReplies,
573
+ // replySort, replyTo, nextReplyOffset, seo } — or null: the page answers notFound.
574
+ async function loadTopicPage(args) {
575
+ var user = sessionOf(args.session);
576
+ var sort = sortKey(args.sort, REPLY_SORTS, 'best');
577
+ return withClient(async function (q) {
578
+ var found = await readableTopic(q, user, text(args.slug), false);
579
+ if (!found) return null;
580
+ var topic = found.topic;
581
+ var viewer = found.viewer;
582
+ var tree = await replyTree(q, user, viewer, topic, text(args.rootReplyId) || null, sort, 0);
583
+ var votes = await votesOf(q, user, [topic.id]);
584
+ var reactions = await reactionsOf(q, user, [topic.id]);
585
+ // The viewer's vote on the topic itself: a number (the replies carry their own).
586
+ viewer.my_vote = votes[text(topic.id)] || 0;
587
+ viewer.is_subscribed = await followsTopic(q, user, topic.id);
588
+ var post = shapePost(topic, votes, reactions);
589
+ post.is_author = viewer.is_author;
590
+ post.is_mine = viewer.is_author;
591
+ nameCommunity(post, found.community);
592
+ post.accepted_reply = await acceptedReplyOf(q, user, viewer, topic, tree.replies);
593
+ var community = shapeCommunity(found.community);
594
+ var url = text(args.url);
595
+ return {
596
+ topic: post,
597
+ community: HAS_COMMUNITIES ? community : null,
598
+ viewer: viewer,
599
+ replies: tree.replies,
600
+ reactions: post.reactions,
601
+ score: num(topic.score),
602
+ myVote: post.my_vote,
603
+ hasMoreReplies: tree.hasMore,
604
+ nextReplyOffset: tree.nextOffset,
605
+ replySort: sort,
606
+ replyTo: text(args.rootReplyId) || '',
607
+ seo: {
608
+ noindex: topicNoIndex(topic, found.community),
609
+ jsonLd: url && !topicNoIndex(topic, found.community) ? topicJsonLd(post, community, flatten(tree.replies), url) : null,
610
+ },
611
+ };
612
+ });
613
+ }
614
+
615
+ function flatten(nodes) {
616
+ var out = [];
617
+ (nodes || []).forEach(function (node) { out.push(node); out = out.concat(flatten(node.children)); });
618
+ return out;
619
+ }
620
+
621
+ // { community, viewer, topics, sortBy, paging, rules, moderators, pendingJoinCount,
622
+ // openReportCount, seo } — or null. topics is one page of the list, in the order
623
+ // sortBy names; paging says where it stands: { page, pages, previous, next }, the
624
+ // last two the page numbers the pager's links open, 0 where there is none.
625
+ // A private community's non-member gets the About side only: can_read false, no topics.
626
+ async function loadCommunityPage(args) {
627
+ if (!HAS_COMMUNITIES) return null; // a forum without communities has no such page
628
+ var user = sessionOf(args.session);
629
+ var sort = sortKey(args.sort, TOPIC_SORTS, 'latest');
630
+ // Without votes there is no score to order by.
631
+ if (sort === 'top' && SETTINGS.votes === 'off') sort = 'latest';
632
+ var page = Math.max(1, num(args.page) || 1);
633
+ return withClient(async function (q) {
634
+ var communities = await q('SELECT ' + COMMUNITY_SQL + ' FROM ' + T.communities + ' c WHERE c.slug = $1 LIMIT 1', [text(args.slug)]);
635
+ var row = communities[0];
636
+ if (!row) return null;
637
+ var viewer = await viewerOf(q, user, row);
638
+ // A community waiting for approval is its creator's to see (the page tells them so) and its
639
+ // moderators'; an archived one its moderators' only.
640
+ viewer.is_creator = !!user.id && text(row.created_by) === user.id;
641
+ if (row.status !== 'active' && !viewer.can_moderate && !(row.status === 'pending' && viewer.is_creator)) return null;
642
+ var community = shapeCommunity(row);
643
+ // Who runs it, the owner first. The role is the membership's, never the profile's.
644
+ var moderators = await q(
645
+ 'SELECT m.user_id, m.role, p.handle, p.display_name, p.avatar_url FROM ' + T.memberships + ' m LEFT JOIN ' + T.profiles +
646
+ " p ON p.user_id = m.user_id WHERE m.community_id = $1 AND m.status = 'active' AND m.role IN ('owner', 'moderator') AND COALESCE(p.role, '') <> 'banned' ORDER BY (m.role = 'owner') DESC, m.joined_at LIMIT 20",
647
+ [row.id]
648
+ );
649
+ var result = {
650
+ community: community,
651
+ viewer: viewer,
652
+ topics: [],
653
+ sortBy: sort,
654
+ paging: { page: 1, pages: 1, previous: 0, next: 0 },
655
+ rules: community.rule_list.map(function (rule) { return { title: text(rule.title), text: text(rule.text) }; }),
656
+ moderators: moderators.map(function (m) {
657
+ return { user_id: text(m.user_id), handle: text(m.handle), name: text(m.display_name) || text(m.handle) || 'Member', avatar: m.avatar_url || null, role: text(m.role) };
658
+ }),
659
+ pendingJoinCount: 0,
660
+ openReportCount: 0,
661
+ seo: { noindex: row.status !== 'active' || row.visibility === 'private' },
662
+ };
663
+ if (!viewer.can_read) return result;
664
+ var params = [row.id];
665
+ var where = 't.community_id = $1 AND ' + topicVisibility(viewer, user, params);
666
+ var counted = await q('SELECT COUNT(*)::int AS total FROM ' + T.topics + ' t WHERE ' + where, params);
667
+ var pages = Math.max(1, Math.ceil(num(counted[0] && counted[0].total) / TOPICS_PER_PAGE));
668
+ // A page past the last one (an old link, topics removed since) is the last one.
669
+ page = Math.min(page, pages);
670
+ result.paging = { page: page, pages: pages, previous: page > 1 ? page - 1 : 0, next: page < pages ? page + 1 : 0 };
671
+ params.push(TOPICS_PER_PAGE, (page - 1) * TOPICS_PER_PAGE);
672
+ var topics = await q(
673
+ 'SELECT ' + TOPIC_SQL + ', p.reputation AS author_reputation, p.badges AS author_badges FROM ' + T.topics + ' t LEFT JOIN ' + T.profiles +
674
+ ' p ON p.user_id = t.author_id WHERE ' + where + ' ORDER BY t.is_pinned DESC, ' + TOPIC_SORTS[sort] + ' LIMIT $' + (params.length - 1) + ' OFFSET $' + params.length,
675
+ params
676
+ );
677
+ var votes = await votesOf(q, user, topics.map(function (t) { return t.id; }));
678
+ result.topics = topics.map(function (t) {
679
+ var post = shapePost(t, votes, {});
680
+ post.body = '';
681
+ post.body_html = '';
682
+ post.is_mine = !!user.id && text(t.author_id) === user.id;
683
+ nameCommunity(post, row);
684
+ return post;
685
+ });
686
+ if (viewer.can_moderate) {
687
+ var joins = await q('SELECT COUNT(*)::int AS total FROM ' + T.memberships + " m WHERE m.community_id = $1 AND m.status = 'pending'", [row.id]);
688
+ var reports = await q('SELECT COUNT(*)::int AS total FROM ' + T.reports + " x WHERE x.community_id = $1 AND x.status = 'open'", [row.id]);
689
+ result.pendingJoinCount = num(joins[0] && joins[0].total);
690
+ result.openReportCount = num(reports[0] && reports[0].total);
691
+ }
692
+ return result;
693
+ });
694
+ }
695
+
696
+ // A community's Manage (need 'moderate') and New topic (need 'post') pages:
697
+ // { community, viewer } — or null (notFound). The row is read whatever its
698
+ // visibility; the viewer decides: Manage for who moderates it, New topic for a
699
+ // signed-in viewer who can read it (one who may not post yet is told to join there).
700
+ async function loadCommunityGate(args) {
701
+ var user = sessionOf(args.session);
702
+ if (!user.id) return null;
703
+ return withClient(async function (q) {
704
+ var communities = await q('SELECT ' + COMMUNITY_SQL + ' FROM ' + T.communities + ' c WHERE c.slug = $1 LIMIT 1', [text(args.slug)]);
705
+ var row = communities[0];
706
+ if (!row) return null;
707
+ var viewer = await viewerOf(q, user, row);
708
+ var admitted = args.need === 'moderate' ? viewer.can_moderate : args.need === 'post' && (viewer.can_post || viewer.can_read);
709
+ if (!admitted || (row.status !== 'active' && !viewer.can_moderate)) return null;
710
+ if (!HAS_COMMUNITIES) return { community: null, viewer: viewer }; // its composer is answered the rights alone
711
+ // What the Manage page's own load answers beside the rights (forum-shapes.ts there).
712
+ viewer.community_id = text(row.id);
713
+ viewer.community_slug = text(row.slug);
714
+ viewer.community_name = text(row.name);
715
+ return { community: shapeCommunity(row), viewer: viewer };
716
+ });
717
+ }
718
+
719
+ // { replies, hasMore, nextOffset, replyCount } for the replies route — or null
720
+ // when the topic cannot be read by this viewer. replyCount is the topic's
721
+ // published replies as stored now: the page's count follows a reply posted.
722
+ async function loadReplies(args) {
723
+ var user = sessionOf(args.session);
724
+ var sort = sortKey(args.sort, REPLY_SORTS, 'best');
725
+ return withClient(async function (q) {
726
+ var found = await readableTopic(q, user, text(args.topicId), true);
727
+ if (!found) return null;
728
+ var tree = await replyTree(q, user, found.viewer, found.topic, text(args.rootReplyId) || null, sort, num(args.after));
729
+ tree.replyCount = num(found.topic.reply_count);
730
+ return tree;
731
+ });
732
+ }
733
+
734
+ // --- notifications ---------------------------------------------------------------------
735
+ async function loadNotifications(session, args) {
736
+ var user = sessionOf(session);
737
+ if (!user.id) return { items: [], unreadCount: 0 };
738
+ var limit = Math.min(100, Math.max(1, num(args && args.limit) || NOTIFICATIONS_PAGE));
739
+ return withClient(async function (q) {
740
+ var rows = await q(
741
+ 'SELECT n.id, n.kind, n.title, n.body, n.url, n.actor_handle, n.read_at, n.created_at FROM ' + T.notifications +
742
+ ' n WHERE n.user_id = $1 ORDER BY n.created_at DESC LIMIT $2',
743
+ [user.id, limit]
744
+ );
745
+ var unread = await q('SELECT COUNT(*)::int AS total FROM ' + T.notifications + ' n WHERE n.user_id = $1 AND n.read_at IS NULL', [user.id]);
746
+ // text is what the profile tab's row binds; the overlay binds title and body.
747
+ return {
748
+ items: rows.map(function (row) { var out = plain(row); out.text = text(row.title); return out; }),
749
+ unreadCount: num(unread[0] && unread[0].total),
750
+ };
751
+ });
752
+ }
753
+
754
+ async function markNotificationsRead(session, ids) {
755
+ var user = sessionOf(session);
756
+ if (!user.id) return 0;
757
+ var only = Array.isArray(ids) ? ids.map(text).filter(Boolean).slice(0, 200) : null;
758
+ return withClient(async function (q) {
759
+ var rows = await q(
760
+ 'UPDATE ' + T.notifications + ' SET read_at = NOW() WHERE user_id = $1 AND read_at IS NULL' + (only ? ' AND id = ANY($2::uuid[])' : '') + ' RETURNING id',
761
+ only ? [user.id, only] : [user.id]
762
+ );
763
+ return rows.length;
764
+ });
765
+ }
766
+
767
+ // Of these storage file ids, the ones a topic, a reply or a community's icon or banner
768
+ // still shows: they hold the file's address, \`<bucket>/<project>/<file id>/<name>\`.
769
+ async function filesStillShown(fileIds) {
770
+ return withClient(async function (q) {
771
+ var rows = await q(
772
+ 'SELECT f.id FROM unnest($1::text[]) AS f(id) WHERE EXISTS (SELECT 1 FROM ' + T.topics + " t WHERE t.attachments::text LIKE '%/' || f.id || '/%') OR EXISTS (SELECT 1 FROM " + T.replies + " r WHERE r.attachments::text LIKE '%/' || f.id || '/%') OR EXISTS (SELECT 1 FROM " + T.communities + " c WHERE COALESCE(c.icon_url, '') LIKE '%/' || f.id || '/%' OR COALESCE(c.banner_url, '') LIKE '%/' || f.id || '/%')",
773
+ [fileIds]
774
+ );
775
+ return rows.map(function (row) { return text(row.id); });
776
+ });
777
+ }
778
+
779
+ // --- the live index ------------------------------------------------------------------------
780
+ async function listPublicIndex() {
781
+ return withClient(async function (q) {
782
+ var communities = HAS_COMMUNITIES ? await q(
783
+ 'SELECT c.slug, c.name, c.description, c.updated_at FROM ' + T.communities + " c WHERE c.status = 'active' AND c.visibility <> 'private' ORDER BY c.sort_order, c.created_at LIMIT 5000"
784
+ ) : [];
785
+ var topics = await q(
786
+ // A topic of an archived community, or of one still waiting for approval, is not public.
787
+ 'SELECT t.slug, t.title, t.body_text, t.updated_at FROM ' + T.topics + " t WHERE t.status = 'published' AND t.community_visibility <> 'private' AND EXISTS (SELECT 1 FROM " +
788
+ T.communities + " c WHERE c.id = t.community_id AND c.status = 'active') ORDER BY t.created_at DESC LIMIT 50000"
789
+ );
790
+ return {
791
+ communities: communities.map(plain),
792
+ topics: topics.map(function (t) { var out = plain(t); out.excerpt = excerptOf(t.body_text); delete out.body_text; return out; }),
793
+ };
794
+ });
795
+ }
796
+
797
+ module.exports = {
798
+ readSession: readSession,
799
+ loadTopicPage: loadTopicPage,
800
+ loadCommunityPage: loadCommunityPage,
801
+ loadCommunityGate: loadCommunityGate,
802
+ loadReplies: loadReplies,
803
+ loadNotifications: loadNotifications,
804
+ markNotificationsRead: markNotificationsRead,
805
+ filesStillShown: filesStillShown,
806
+ listPublicIndex: listPublicIndex,
807
+ settings: SETTINGS,
808
+ };
809
+ `
810
+ }