@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,1329 @@
1
+ /* tslint:disable:function-constructor no-any */
2
+ import { SessionCookieResolver } from '@teleporthq/teleport-shared'
3
+ import { generateLazyPgClientCode } from '@teleporthq/teleport-plugin-next-workflows'
4
+ import { buildForumMarkdownSource } from '../src/forum/markdown-source'
5
+ import {
6
+ buildForumLlmsPageSource,
7
+ buildForumSitemapPageSource,
8
+ FORUM_SEO_RUNTIME,
9
+ } from '../src/forum/seo'
10
+ import { buildForumPageDataSource } from '../src/forum/page-data-source'
11
+ import { ForumConfig, resolveForumConfig } from '../src/forum/settings'
12
+
13
+ /**
14
+ * The data module, loaded as the generated site would require it, over a fake
15
+ * `pg` whose Client answers each statement from the fixture below and keeps
16
+ * every statement it was asked. The fixture is one private community with a
17
+ * topic, a three-level thread under it and a pending reply; a test changes the
18
+ * community, the topic and who the viewer is there through `load`'s options.
19
+ */
20
+
21
+ interface Statement {
22
+ sql: string
23
+ params: unknown[]
24
+ }
25
+
26
+ const COMMUNITY = {
27
+ id: 'c0000000-0000-4000-8000-000000000001',
28
+ slug: 'private-club',
29
+ name: 'Private club',
30
+ description: 'Members only.',
31
+ rules: '[{"title":"Be kind","text":"Always."}]',
32
+ kind: 'questions',
33
+ visibility: 'private',
34
+ posting: 'members',
35
+ status: 'active',
36
+ created_by: 'owner',
37
+ member_count: 2,
38
+ topic_count: 1,
39
+ created_at: new Date('2026-10-01T10:00:00Z'),
40
+ }
41
+
42
+ const TOPIC = {
43
+ id: 't0000000-0000-4000-8000-000000000001',
44
+ community_id: COMMUNITY.id,
45
+ community_slug: 'private-club',
46
+ community_visibility: 'private',
47
+ author_id: 'author',
48
+ author_handle: 'jane',
49
+ author_name: 'Jane Doe',
50
+ author_avatar: null as string | null,
51
+ title: 'How do I start?',
52
+ slug: 'how-do-i-start-abc123',
53
+ body: 'Hello **world**',
54
+ body_text: 'Hello world',
55
+ tags: '["help"]',
56
+ attachments: '[]',
57
+ status: 'published',
58
+ is_pinned: false,
59
+ is_locked: false,
60
+ accepted_reply_id: 'r0000000-0000-4000-8000-000000000002',
61
+ score: 3,
62
+ upvotes: 3,
63
+ downvotes: 0,
64
+ reply_count: 4,
65
+ view_count: 10,
66
+ last_activity_at: new Date('2026-10-02T10:00:00Z'),
67
+ created_at: new Date('2026-10-01T12:00:00Z'),
68
+ updated_at: new Date('2026-10-01T12:00:00Z'),
69
+ author_reputation: 42,
70
+ author_badges: '["first-topic"]',
71
+ }
72
+
73
+ const reply = (
74
+ n: number,
75
+ parent: number | null,
76
+ depth: number,
77
+ extra: Record<string, unknown> = {}
78
+ ) => ({
79
+ id: `r0000000-0000-4000-8000-00000000000${n}`,
80
+ topic_id: TOPIC.id,
81
+ community_id: COMMUNITY.id,
82
+ parent_id: parent === null ? null : `r0000000-0000-4000-8000-00000000000${parent}`,
83
+ depth,
84
+ path: `0000000000000${n}.r${n}`,
85
+ author_id: `user-${n}`,
86
+ author_handle: `user${n}`,
87
+ author_name: `User ${n}`,
88
+ author_avatar: null as string | null,
89
+ body: `Reply ${n}`,
90
+ body_text: `Reply ${n}`,
91
+ attachments: '[]',
92
+ status: 'published',
93
+ score: n,
94
+ upvotes: n,
95
+ downvotes: 0,
96
+ is_accepted: false,
97
+ created_at: new Date(`2026-10-0${n}T12:00:00Z`),
98
+ ...extra,
99
+ })
100
+
101
+ const HEADS = [
102
+ reply(1, null, 0),
103
+ reply(2, null, 0, { is_accepted: true }),
104
+ reply(5, null, 0, { status: 'removed' }),
105
+ ]
106
+ const CHILDREN = [reply(3, 1, 1), reply(4, 3, 2)]
107
+
108
+ // Who runs the community, as the database orders them: the owner first.
109
+ const MODERATORS: Array<Record<string, string | null>> = [
110
+ { user_id: 'owner', role: 'owner', handle: 'olga', display_name: 'Olga Owner', avatar_url: null },
111
+ { user_id: 'mod', role: 'moderator', handle: 'max', display_name: null, avatar_url: '/max.png' },
112
+ { user_id: 'new', role: 'moderator', handle: null, display_name: null, avatar_url: null },
113
+ ]
114
+
115
+ interface Loaded {
116
+ module: any
117
+ statements: Statement[]
118
+ }
119
+
120
+ interface Fixture {
121
+ /** The viewer is an active member of the community. */
122
+ member?: boolean
123
+ /** The viewer's membership as stored, when it is not a plain active member's. */
124
+ membership?: { role: string; status: string }
125
+ /** The viewer's forum profile says `moderator` (a site moderator). */
126
+ moderator?: boolean
127
+ /** The viewer's forum profile role, when it is neither `member` nor `moderator`. */
128
+ profileRole?: string
129
+ community?: Record<string, unknown>
130
+ topic?: Record<string, unknown>
131
+ /** How many topics the community holds for the viewer (one unless said). */
132
+ topicCount?: number
133
+ /** The community page's "per page" setting, as the editor exports it. */
134
+ topicsPerPage?: unknown
135
+ /** How the forum is organised, as the record says it (communities unless said). */
136
+ structure?: string
137
+ /** More of the plugin's settings, as the editor stores them. */
138
+ settings?: Record<string, unknown>
139
+ /** What the database answers for a flat list of replies (every reply of the fixture unless said). */
140
+ flatReplies?: Array<Record<string, unknown>>
141
+ }
142
+
143
+ /** A reply that is in no page of the tree: what the accepted answer is read by id for. */
144
+ const OFF_PAGE = reply(6, null, 0, { is_accepted: true, author_id: 'user-1' })
145
+
146
+ /** A moment `minutes` ago, as the database stores a row's `created_at`. */
147
+ const minutesAgo = (minutes: number): Date => new Date(Date.now() - minutes * 60000)
148
+
149
+ /** The plugin's configuration for a fixture, as the generator resolves it from the project. */
150
+ const configOf = (options: Fixture = {}): ForumConfig =>
151
+ resolveForumConfig({
152
+ plugins: {
153
+ forum: {
154
+ settings: {
155
+ reactions: true,
156
+ ...(options.structure !== undefined ? { structure: options.structure } : {}),
157
+ ...options.settings,
158
+ },
159
+ ...(options.topicsPerPage !== undefined
160
+ ? { data: { communityTopicsPerPage: options.topicsPerPage } }
161
+ : {}),
162
+ },
163
+ },
164
+ dataSources: {},
165
+ root: { stateDefinitions: { route: { values: [] } } },
166
+ } as any)!
167
+
168
+ const load = (options: Fixture = {}): Loaded => {
169
+ const statements: Statement[] = []
170
+ const community = { ...COMMUNITY, ...options.community }
171
+ const topic = { ...TOPIC, ...options.topic }
172
+ const membership =
173
+ options.membership ?? (options.member ? { role: 'member', status: 'active' } : null)
174
+ const answer = (sql: string, params: unknown[]): unknown[] => {
175
+ if (/FROM teleport_forum_topics t .*WHERE t\.slug = \$1/.test(sql)) {
176
+ return params[0] === TOPIC.slug ? [topic] : []
177
+ }
178
+ if (/FROM teleport_forum_topics t .*WHERE t\.id = \$1/.test(sql)) {
179
+ return params[0] === TOPIC.id ? [topic] : []
180
+ }
181
+ if (/FROM teleport_forum_communities c WHERE c\.(id|slug) = \$1/.test(sql)) {
182
+ return params[0] === community.id || params[0] === community.slug ? [community] : []
183
+ }
184
+ // The live index: every community and topic a visitor may read, by the columns it selects.
185
+ if (/FROM teleport_forum_communities c WHERE c\.status = 'active'/.test(sql)) {
186
+ const { slug, name, description, updated_at } = community as Record<string, unknown>
187
+ return [{ slug, name, description, updated_at }]
188
+ }
189
+ if (/FROM teleport_forum_topics t WHERE t\.status = 'published'/.test(sql)) {
190
+ const { slug, title, body_text, updated_at } = topic
191
+ return [{ slug, title, body_text, updated_at }]
192
+ }
193
+ if (/FROM teleport_forum_profiles p WHERE p\.user_id = \$1/.test(sql)) {
194
+ return [
195
+ {
196
+ user_id: params[0],
197
+ handle: 'me',
198
+ display_name: 'Me',
199
+ role: options.profileRole ?? (options.moderator ? 'moderator' : 'member'),
200
+ reputation: 1,
201
+ badges: '[]',
202
+ },
203
+ ]
204
+ }
205
+ if (
206
+ /FROM teleport_forum_memberships m WHERE m\.community_id = \$1 AND m\.user_id = \$2/.test(sql)
207
+ ) {
208
+ return membership ? [membership] : []
209
+ }
210
+ if (/FROM teleport_forum_memberships m LEFT JOIN teleport_forum_profiles p/.test(sql)) {
211
+ return MODERATORS
212
+ }
213
+ if (/FROM teleport_forum_memberships m WHERE .*m\.status = 'pending'/.test(sql)) {
214
+ return [{ total: 3 }]
215
+ }
216
+ if (/FROM teleport_forum_reports x WHERE /.test(sql)) {
217
+ return [{ total: '2' }]
218
+ }
219
+ if (/SELECT r\.id, r\.depth, r\.path FROM teleport_forum_replies r/.test(sql)) {
220
+ return CHILDREN.filter((child) => child.id === params[1])
221
+ }
222
+ if (/FROM teleport_forum_replies r .*r\.parent_id (IS NULL|= \$2)/.test(sql)) {
223
+ return HEADS
224
+ }
225
+ if (/FROM teleport_forum_replies r .*r\.path LIKE ANY/.test(sql)) {
226
+ return CHILDREN
227
+ }
228
+ // Flat replies: every reply of the topic, in the order the database was asked for.
229
+ if (/FROM teleport_forum_replies r .*WHERE r\.topic_id = \$1 AND \(r\.status/.test(sql)) {
230
+ return options.flatReplies ?? [...HEADS, ...CHILDREN]
231
+ }
232
+ if (/FROM teleport_forum_replies r .*WHERE r\.topic_id = \$1 AND r\.id = \$2 AND /.test(sql)) {
233
+ return params[1] === OFF_PAGE.id ? [OFF_PAGE] : []
234
+ }
235
+ if (/FROM teleport_forum_topics t .*t\.community_id = \$1/.test(sql)) {
236
+ return /COUNT\(\*\)/.test(sql) ? [{ total: options.topicCount ?? 1 }] : [topic]
237
+ }
238
+ if (/FROM teleport_forum_notifications n WHERE n\.user_id = \$1 ORDER BY/.test(sql)) {
239
+ return [
240
+ {
241
+ id: 'n1',
242
+ kind: 'reply',
243
+ title: 'Jane replied',
244
+ body: 'Hi',
245
+ url: '/forum/t/x',
246
+ read_at: null,
247
+ created_at: new Date('2026-10-03T12:00:00Z'),
248
+ },
249
+ ]
250
+ }
251
+ if (/COUNT\(\*\)/.test(sql)) {
252
+ return [{ total: 0 }]
253
+ }
254
+ return []
255
+ }
256
+ class Client {
257
+ async connect(): Promise<void> {
258
+ return undefined
259
+ }
260
+ async query(sql: string, params: unknown[]) {
261
+ statements.push({ sql, params })
262
+ return { rows: answer(sql, params) }
263
+ }
264
+ async end(): Promise<void> {
265
+ return undefined
266
+ }
267
+ }
268
+ const markdown = { exports: {} as any }
269
+ new Function('module', 'exports', buildForumMarkdownSource())(markdown, markdown.exports)
270
+ const source = buildForumPageDataSource(configOf(options), { withSessionRevocation: false })
271
+ const module = { exports: {} as any }
272
+ const fakeRequire = (name: string) => {
273
+ if (name === 'pg') {
274
+ return { Client }
275
+ }
276
+ if (name === './forum-markdown') {
277
+ return markdown.exports
278
+ }
279
+ throw new Error(`Cannot find module '${name}'`)
280
+ }
281
+ new Function('require', 'module', 'exports', 'process', source)(
282
+ fakeRequire,
283
+ module,
284
+ module.exports,
285
+ { env: {} }
286
+ )
287
+ return { module: module.exports, statements }
288
+ }
289
+
290
+ const sqlOf = (loaded: Loaded) => loaded.statements.map((statement) => statement.sql).join('\n')
291
+
292
+ /**
293
+ * What an index page (`/sitemap-forum.xml`, `/llms-forum.txt`) sends for a
294
+ * request to `site.example`, its `listPublicIndex` being the module's own.
295
+ */
296
+ const sendIndexPage = async (
297
+ source: string,
298
+ loaded: Loaded,
299
+ context: Record<string, unknown> = {}
300
+ ): Promise<string> => {
301
+ const body = source
302
+ .replace(/^import \{ listPublicIndex \} from .*$/m, '')
303
+ .replace('export async function getServerSideProps', 'async function getServerSideProps')
304
+ .replace(/export default function \w+\(\) \{\s*return null\s*\}/, '')
305
+ expect(body).not.toMatch(/^(import|export) /m)
306
+ const getServerSideProps = new Function('listPublicIndex', `${body}\nreturn getServerSideProps`)(
307
+ loaded.module.listPublicIndex
308
+ )
309
+ let sent = ''
310
+ const res = {
311
+ statusCode: 0,
312
+ setHeader: (): void => undefined,
313
+ end: (text: string): void => {
314
+ sent = text
315
+ },
316
+ }
317
+ await getServerSideProps({ req: { headers: { host: 'site.example' } }, res, ...context })
318
+ expect(res.statusCode).toBe(200)
319
+ return sent
320
+ }
321
+
322
+ describe('the forum data module', () => {
323
+ it('stays within its line budget, the shared driver and session blocks aside', () => {
324
+ const config = resolveForumConfig({
325
+ plugins: { forum: { settings: {} } },
326
+ dataSources: {},
327
+ root: {},
328
+ } as any)!
329
+ const own = buildForumPageDataSource(config, { withSessionRevocation: false })
330
+ .replace(generateLazyPgClientCode(), '')
331
+ .replace(
332
+ SessionCookieResolver.generateCommonJsSessionTokenResolverCode('..', {
333
+ withRevocation: false,
334
+ }),
335
+ ''
336
+ )
337
+ .replace(FORUM_SEO_RUNTIME, '')
338
+ // The plan's budget is 450; the module runs over it (reported): the shapes the
339
+ // pages bind (forum-shapes.ts in the editor) added the accepted answer and the URLs,
340
+ // round 2 the gate of the Manage and New topic pages, round 7 the pictures a post
341
+ // still shows (the pictures route asks before it removes one), round 8 flat replies,
342
+ // who may edit a post and the page of a community waiting for approval, round 12 who
343
+ // may delete a community and the pictures a community still shows.
344
+ expect(own.split('\n').length).toBeLessThanOrEqual(645)
345
+ })
346
+
347
+ it('refuses a private community’s topic to a visitor who is not a member', async () => {
348
+ const anonymous = load()
349
+ expect(await anonymous.module.loadTopicPage({ slug: TOPIC.slug, session: null })).toBeNull()
350
+ expect(sqlOf(anonymous)).not.toContain('FROM teleport_forum_replies')
351
+
352
+ const outsider = load({ member: false })
353
+ expect(
354
+ await outsider.module.loadTopicPage({ slug: TOPIC.slug, session: { id: 'someone' } })
355
+ ).toBeNull()
356
+ expect(sqlOf(outsider)).toContain(
357
+ 'FROM teleport_forum_memberships m WHERE m.community_id = $1 AND m.user_id = $2'
358
+ )
359
+
360
+ const missing = load({ member: true })
361
+ expect(
362
+ await missing.module.loadTopicPage({ slug: 'nope', session: { id: 'someone' } })
363
+ ).toBeNull()
364
+ })
365
+
366
+ it('serves a member the topic with its viewer block, the tree and the counts', async () => {
367
+ const loaded = load({ member: true })
368
+ const page = await loaded.module.loadTopicPage({
369
+ slug: TOPIC.slug,
370
+ session: { id: 'user-1', role: 'member' },
371
+ sort: 'best',
372
+ url: 'https://site.example/forum/t/how-do-i-start-abc123',
373
+ })
374
+ expect(page).not.toBeNull()
375
+ expect(page.viewer).toMatchObject({
376
+ signed_in: true,
377
+ my_membership: 'active',
378
+ my_role: 'member',
379
+ can_read: true,
380
+ can_moderate: false,
381
+ can_post: true,
382
+ is_author: false,
383
+ is_subscribed: false,
384
+ // A member who is not the author may not accept an answer; the vote on the topic is a number.
385
+ can_accept: false,
386
+ my_vote: 0,
387
+ })
388
+ // The row is JSON-plain, rendered and masked where it must be.
389
+ expect(page.topic.body_html).toBe('<p>Hello <strong>world</strong></p>')
390
+ expect(page.topic.created_at).toBe('2026-10-01T12:00:00.000Z')
391
+ expect(page.topic.tag_list).toEqual(['help'])
392
+ // The shapes the pages bind (forum-shapes.ts in the editor).
393
+ expect(page.topic.tags).toEqual([{ name: 'help' }])
394
+ expect(page.topic.attachments).toEqual([])
395
+ expect(page.topic.author_reputation).toBe(42)
396
+ // A topic written before the column existed is named by its community's row.
397
+ expect(page.topic.community_name).toBe('Private club')
398
+ expect(page.topic.community_url).toBe('/forum/c/private-club')
399
+ expect(page.topic.is_mine).toBe(false)
400
+ expect(page.topic.excerpt).toBe('Hello world')
401
+ expect(page.topic.accepted_reply).toMatchObject({
402
+ id: TOPIC.accepted_reply_id,
403
+ is_accepted: true,
404
+ })
405
+ expect(page.topic.author).toMatchObject({
406
+ handle: 'jane',
407
+ reputation: 42,
408
+ badges: ['first-topic'],
409
+ initials: 'JD',
410
+ })
411
+ expect(page.topic).not.toHaveProperty('author_badges')
412
+ expect(page.score).toBe(3)
413
+ expect(page.community.rule_list).toEqual([{ title: 'Be kind', text: 'Always.' }])
414
+ expect(page.community.rules_text).toBe('Be kind: Always.')
415
+ // The accepted answer first, then by score; the removed one keeps its place, masked.
416
+ expect(page.replies.map((r: any) => r.id.slice(-1))).toEqual(['2', '5', '1'])
417
+ expect(page.replies[1].body_html).toBe('<p><em>[removed]</em></p>')
418
+ expect(page.replies[1].body).toBe('')
419
+ const first = page.replies[2]
420
+ expect(first.children.map((r: any) => r.id.slice(-1))).toEqual(['3'])
421
+ expect(first.children[0].children.map((r: any) => r.id.slice(-1))).toEqual(['4'])
422
+ expect(first.children[0].children[0].is_author).toBe(false)
423
+ expect(page.replies[2].is_author).toBe(true)
424
+ expect(page.replies[2].is_mine).toBe(true)
425
+ expect(page.replies[2].thread_url).toBe(
426
+ `/forum/t/how-do-i-start-abc123?reply=${page.replies[2].id}`
427
+ )
428
+ expect(page.replies[2].attachments).toEqual([])
429
+ expect(page.hasMoreReplies).toBe(false)
430
+ expect(page.nextReplyOffset).toBe(3)
431
+ expect(page.seo.noindex).toBe(true)
432
+ expect(page.seo.jsonLd).toBeNull()
433
+
434
+ const sql = sqlOf(loaded)
435
+ // Only published and removed rows for a member; pending ones only their own.
436
+ expect(sql).toContain(
437
+ "(r.status IN ('published', 'removed') OR (r.status = 'pending' AND r.author_id = $"
438
+ )
439
+ expect(sql).not.toContain("'pending'))\n")
440
+ // Three levels are drawn from the root (depths 0, 1 and 2 under a topic); the fourth is read
441
+ // only so a reply of the third can say its thread goes on.
442
+ expect(sql).toContain('r.path LIKE ANY($2::text[]) AND r.depth <= $3')
443
+ const children = loaded.statements.find((statement) =>
444
+ statement.sql.includes('r.path LIKE ANY')
445
+ )!
446
+ expect(children.params[2]).toBe(3)
447
+ expect(children.params[1]).toEqual(HEADS.map((head) => `${head.path}%`))
448
+ // Nothing is interpolated: every value travels as a parameter.
449
+ for (const statement of loaded.statements) {
450
+ expect(statement.sql).not.toContain(TOPIC.slug)
451
+ expect(statement.sql).not.toContain('user-1')
452
+ }
453
+ // Reactions were counted (the setting is on), the viewer's vote asked by id.
454
+ expect(sql).toContain('FROM teleport_forum_reactions x WHERE x.target_id = ANY($1::uuid[])')
455
+ expect(sql).toContain(
456
+ 'FROM teleport_forum_votes v WHERE v.user_id = $1 AND v.target_id = ANY($2::uuid[])'
457
+ )
458
+ // Follow / Following is the topic's own subscription.
459
+ const follows = loaded.statements.find((statement) =>
460
+ statement.sql.includes('FROM teleport_forum_subscriptions')
461
+ )!
462
+ expect(follows.sql).toContain("s.user_id = $1 AND s.target_kind = 'topic' AND s.target_id = $2")
463
+ expect(follows.params).toEqual(['user-1', TOPIC.id])
464
+ })
465
+
466
+ it('continues a thread from one reply: three levels under it, and one more as the signal', async () => {
467
+ const loaded = load({ member: true })
468
+ // The reply the visitor continues from sits two levels deep.
469
+ const root = CHILDREN[1]
470
+ const page = await loaded.module.loadTopicPage({
471
+ slug: TOPIC.slug,
472
+ session: { id: 'user-1' },
473
+ rootReplyId: root.id,
474
+ })
475
+ expect(page.replyTo).toBe(root.id)
476
+ const heads = loaded.statements.find((statement) => statement.sql.includes('r.parent_id = $2'))!
477
+ expect(heads.params.slice(0, 2)).toEqual([TOPIC.id, root.id])
478
+ const children = loaded.statements.find((statement) =>
479
+ statement.sql.includes('r.path LIKE ANY')
480
+ )!
481
+ // Its children are the first level (depth 3); drawn to depth 5, read to depth 6.
482
+ expect(root.depth).toBe(2)
483
+ expect(children.params[2]).toBe(6)
484
+
485
+ // A reply that is not this topic's opens nothing.
486
+ const none = await load({ member: true }).module.loadTopicPage({
487
+ slug: TOPIC.slug,
488
+ session: { id: 'user-1' },
489
+ rootReplyId: 'not-a-reply',
490
+ })
491
+ expect(none.replies).toEqual([])
492
+ })
493
+
494
+ it('names a topic’s community by the topic’s own column when it has one', async () => {
495
+ const loaded = load({ member: true, topic: { community_name: 'The club' } })
496
+ const session = { id: 'user-1' }
497
+ const page = await loaded.module.loadTopicPage({ slug: TOPIC.slug, session })
498
+ expect(page.topic.community_name).toBe('The club')
499
+ const list = await loaded.module.loadCommunityPage({ slug: COMMUNITY.slug, session })
500
+ expect(list.topics[0].community_name).toBe('The club')
501
+ expect(sqlOf(loaded)).toContain('t.community_slug, t.community_name, t.community_visibility')
502
+ })
503
+
504
+ it('lets a site moderator read everything, pending rows included', async () => {
505
+ const loaded = load({ member: false, moderator: true })
506
+ const page = await loaded.module.loadTopicPage({ slug: TOPIC.slug, session: { id: 'mod' } })
507
+ expect(page.viewer.can_moderate).toBe(true)
508
+ expect(page.viewer.can_read).toBe(true)
509
+ expect(sqlOf(loaded)).toContain("(r.status IN ('published', 'removed', 'pending'))")
510
+ })
511
+
512
+ it('shows a non-member only the About side of a private community, members its topics', async () => {
513
+ const outsider = load()
514
+ const closed = await outsider.module.loadCommunityPage({ slug: COMMUNITY.slug, session: null })
515
+ expect(closed.viewer.can_read).toBe(false)
516
+ expect(closed.viewer.can_post).toBe(false)
517
+ // Joining is following: a community has no subscription of its own.
518
+ expect(closed.viewer).not.toHaveProperty('is_subscribed')
519
+ expect(closed.topics).toEqual([])
520
+ expect(closed.community.name).toBe('Private club')
521
+ // The About card's lists are served with the shell.
522
+ expect(closed.rules).toEqual([{ title: 'Be kind', text: 'Always.' }])
523
+ expect(closed.moderators).toEqual([
524
+ { user_id: 'owner', handle: 'olga', name: 'Olga Owner', avatar: null, role: 'owner' },
525
+ { user_id: 'mod', handle: 'max', name: 'max', avatar: '/max.png', role: 'moderator' },
526
+ { user_id: 'new', handle: '', name: 'Member', avatar: null, role: 'moderator' },
527
+ ])
528
+ expect(sqlOf(outsider)).not.toContain('FROM teleport_forum_topics')
529
+ // The owner first; the role read is the membership's (a profile has a role too).
530
+ expect(sqlOf(outsider)).toContain(
531
+ "SELECT m.user_id, m.role, p.handle, p.display_name, p.avatar_url FROM teleport_forum_memberships m LEFT JOIN teleport_forum_profiles 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"
532
+ )
533
+
534
+ const member = load({ member: true, topicsPerPage: 10, topicCount: 25 })
535
+ const open = await member.module.loadCommunityPage({
536
+ slug: COMMUNITY.slug,
537
+ session: { id: 'user-1' },
538
+ sort: 'top',
539
+ page: 2,
540
+ })
541
+ expect(open.viewer.can_read).toBe(true)
542
+ expect(open.topics).toHaveLength(1)
543
+ expect(open.topics[0].body_html).toBe('')
544
+ expect(open.topics[0].excerpt).toBe('Hello world')
545
+ expect(open.topics[0].community_name).toBe('Private club')
546
+ expect(open.topics[0].community_url).toBe('/forum/c/private-club')
547
+ expect(open.sortBy).toBe('top')
548
+ // The second of three pages: the pager's links open the first and the third.
549
+ expect(open.paging).toEqual({ page: 2, pages: 3, previous: 1, next: 3 })
550
+ expect(open.pendingJoinCount).toBe(0)
551
+ expect(open.openReportCount).toBe(0)
552
+ const sql = sqlOf(member)
553
+ expect(sql).toContain(
554
+ "t.community_id = $1 AND (t.status = 'published' OR (t.status = 'pending' AND t.author_id = $2))"
555
+ )
556
+ expect(sql).toContain(
557
+ 'ORDER BY t.is_pinned DESC, t.score DESC, t.created_at DESC LIMIT $3 OFFSET $4'
558
+ )
559
+ const list = member.statements.find((statement) => statement.sql.includes('OFFSET $4'))!
560
+ expect(list.params).toEqual([COMMUNITY.id, 'user-1', 10, 10])
561
+ // A moderator's counts were not asked for a member.
562
+ expect(sql).not.toContain("m.status = 'pending'")
563
+ // Joining is following: no subscription is read for a community.
564
+ expect(open.viewer).not.toHaveProperty('is_subscribed')
565
+ expect(sql).not.toContain('FROM teleport_forum_subscriptions')
566
+ })
567
+
568
+ it('pages a community’s topics by the page’s own setting, never by the address', async () => {
569
+ const pagingOf = async (fixture: Fixture, args: Record<string, unknown> = {}) => {
570
+ const loaded = load({ community: { visibility: 'public' }, ...fixture })
571
+ const page = await loaded.module.loadCommunityPage({
572
+ slug: COMMUNITY.slug,
573
+ session: null,
574
+ ...args,
575
+ })
576
+ const list = loaded.statements.find((statement) => statement.sql.includes('OFFSET'))!
577
+ return { paging: page.paging, sortBy: page.sortBy, limit: list.params.slice(-2) }
578
+ }
579
+
580
+ // One page: no pager, the default order, twenty topics a page when the editor set nothing.
581
+ expect(await pagingOf({})).toEqual({
582
+ paging: { page: 1, pages: 1, previous: 0, next: 0 },
583
+ sortBy: 'latest',
584
+ limit: [20, 0],
585
+ })
586
+ // The first of several has only a next one; an order the forum does not have is the default.
587
+ expect(await pagingOf({ topicCount: 45 }, { sort: 'created_at-desc' })).toEqual({
588
+ paging: { page: 1, pages: 3, previous: 0, next: 2 },
589
+ sortBy: 'latest',
590
+ limit: [20, 0],
591
+ })
592
+ // A page past the last one (an old link) is the last one; what the address asks per page is ignored.
593
+ expect(await pagingOf({ topicCount: 45 }, { page: 9, perPage: 1 })).toEqual({
594
+ paging: { page: 3, pages: 3, previous: 2, next: 0 },
595
+ sortBy: 'latest',
596
+ limit: [20, 40],
597
+ })
598
+ // The setting is kept within what one page may hold.
599
+ expect((await pagingOf({ topicsPerPage: 500 })).limit).toEqual([50, 0])
600
+ expect((await pagingOf({ topicsPerPage: 0 })).limit).toEqual([1, 0])
601
+ expect((await pagingOf({ topicsPerPage: 'many' })).limit).toEqual([20, 0])
602
+ })
603
+
604
+ it('counts what waits for a moderator as numbers', async () => {
605
+ const loaded = load({ membership: { role: 'owner', status: 'active' } })
606
+ const page = await loaded.module.loadCommunityPage({
607
+ slug: COMMUNITY.slug,
608
+ session: { id: 'owner' },
609
+ })
610
+ expect(page.viewer).toMatchObject({ can_moderate: true, my_role: 'owner', can_post: true })
611
+ expect(page.pendingJoinCount).toBe(3)
612
+ expect(page.openReportCount).toBe(2)
613
+ })
614
+
615
+ it('lets anyone signed in post where the community is public, its members elsewhere, and only who moderates where moderators post', async () => {
616
+ const canPost = async (fixture: Fixture, session: unknown = { id: 'user-1' }) => {
617
+ const page = await load({
618
+ community: { visibility: 'public' },
619
+ ...fixture,
620
+ }).module.loadCommunityPage({ slug: COMMUNITY.slug, session })
621
+ return page.viewer.can_post
622
+ }
623
+ const restricted = { visibility: 'restricted' }
624
+ const moderatorsOnly = { visibility: 'public', posting: 'moderators' }
625
+ const announcements = { visibility: 'public', kind: 'announcements' }
626
+
627
+ // Public: anyone signed in, joined or not; never a visitor or a ban.
628
+ expect(await canPost({ member: true })).toBe(true)
629
+ expect(await canPost({})).toBe(true)
630
+ expect(await canPost({ member: true }, null)).toBe(false)
631
+ expect(await canPost({ membership: { role: 'member', status: 'banned' } })).toBe(false)
632
+ expect(await canPost({ member: true, profileRole: 'banned' })).toBe(false)
633
+ expect(await canPost({}, { id: 'boss', role: 'admin' })).toBe(true)
634
+
635
+ // Restricted: its active members only; a request still pending does not count.
636
+ expect(await canPost({ community: restricted, member: true })).toBe(true)
637
+ expect(await canPost({ community: restricted })).toBe(false)
638
+ expect(
639
+ await canPost({ community: restricted, membership: { role: 'member', status: 'pending' } })
640
+ ).toBe(false)
641
+ expect(await canPost({ community: restricted, moderator: true })).toBe(false)
642
+
643
+ // Where only moderators post — the setting, or an announcements community.
644
+ for (const community of [moderatorsOnly, announcements]) {
645
+ expect(await canPost({ community, member: true })).toBe(false)
646
+ expect(
647
+ await canPost({ community, membership: { role: 'moderator', status: 'active' } })
648
+ ).toBe(true)
649
+ expect(await canPost({ community, membership: { role: 'owner', status: 'active' } })).toBe(
650
+ true
651
+ )
652
+ expect(await canPost({ community, moderator: true })).toBe(true)
653
+ expect(await canPost({ community }, { id: 'boss', role: 'admin' })).toBe(true)
654
+ }
655
+ })
656
+
657
+ it('lets a visitor reply as the reply statement does: members of an announcements community too', async () => {
658
+ const canReply = async (fixture: Fixture, session: unknown = { id: 'user-1' }) => {
659
+ const page = await load({
660
+ community: { visibility: 'public' },
661
+ ...fixture,
662
+ }).module.loadTopicPage({ slug: TOPIC.slug, session })
663
+ return page.viewer.can_reply
664
+ }
665
+ expect(await canReply({})).toBe(true)
666
+ expect(await canReply({}, null)).toBe(false)
667
+ expect(await canReply({ member: true, profileRole: 'banned' })).toBe(false)
668
+ expect(await canReply({ community: { visibility: 'restricted' } })).toBe(false)
669
+ expect(await canReply({ community: { visibility: 'restricted' }, member: true })).toBe(true)
670
+ // Announcements keep new topics to moderators; their replies are open to members.
671
+ expect(await canReply({ community: { visibility: 'public', kind: 'announcements' } })).toBe(
672
+ true
673
+ )
674
+ expect(await canReply({ community: { visibility: 'public', posting: 'moderators' } })).toBe(
675
+ false
676
+ )
677
+ expect(
678
+ await canReply({
679
+ community: { visibility: 'public', posting: 'moderators' },
680
+ moderator: true,
681
+ })
682
+ ).toBe(true)
683
+ })
684
+
685
+ describe('the gate of the Manage and New topic pages', () => {
686
+ const SESSION = { id: 'user-1' }
687
+ const VIEWERS: Record<string, { fixture: Fixture; session: unknown }> = {
688
+ 'signed out': { fixture: {}, session: null },
689
+ stranger: { fixture: {}, session: SESSION },
690
+ member: { fixture: { member: true }, session: SESSION },
691
+ moderator: {
692
+ fixture: { membership: { role: 'moderator', status: 'active' } },
693
+ session: SESSION,
694
+ },
695
+ }
696
+ const gate = async (who: string, visibility: string, need: string) => {
697
+ const { fixture, session } = VIEWERS[who]
698
+ const loaded = load({ ...fixture, community: { visibility } })
699
+ const answer = await loaded.module.loadCommunityGate({ slug: COMMUNITY.slug, session, need })
700
+ return { answer, loaded }
701
+ }
702
+
703
+ it.each(['public', 'private'])(
704
+ 'opens Manage of a %s community to who moderates it only',
705
+ async (visibility) => {
706
+ for (const who of ['signed out', 'stranger', 'member']) {
707
+ expect((await gate(who, visibility, 'moderate')).answer).toBeNull()
708
+ }
709
+ const { answer, loaded } = await gate('moderator', visibility, 'moderate')
710
+ expect(answer.viewer).toMatchObject({
711
+ signed_in: true,
712
+ can_moderate: true,
713
+ community_id: COMMUNITY.id,
714
+ community_slug: 'private-club',
715
+ community_name: 'Private club',
716
+ })
717
+ // The record the page binds is the shaped community.
718
+ expect(answer.community).toMatchObject({
719
+ id: COMMUNITY.id,
720
+ visibility,
721
+ rules_text: 'Be kind: Always.',
722
+ created_at: '2026-10-01T10:00:00.000Z',
723
+ })
724
+ // Read whatever its visibility: the membership decides, not the visitor's row policy.
725
+ expect(sqlOf(loaded)).not.toContain("visibility <> 'private'")
726
+ }
727
+ )
728
+
729
+ it('opens New topic of a public community to every signed-in viewer, saying who may post', async () => {
730
+ expect((await gate('signed out', 'public', 'post')).answer).toBeNull()
731
+ // A public community takes posts from anyone signed in; joining is not required.
732
+ const stranger = (await gate('stranger', 'public', 'post')).answer
733
+ expect(stranger.viewer).toMatchObject({
734
+ signed_in: true,
735
+ my_membership: null,
736
+ can_post: true,
737
+ })
738
+ expect(stranger.community.slug).toBe('private-club')
739
+ const member = (await gate('member', 'public', 'post')).answer
740
+ expect(member.viewer).toMatchObject({
741
+ signed_in: true,
742
+ my_membership: 'active',
743
+ can_post: true,
744
+ })
745
+ expect((await gate('moderator', 'public', 'post')).answer.viewer.can_post).toBe(true)
746
+ })
747
+
748
+ it('opens New topic of a private community to its members and moderators only', async () => {
749
+ expect((await gate('signed out', 'private', 'post')).answer).toBeNull()
750
+ expect((await gate('stranger', 'private', 'post')).answer).toBeNull()
751
+ const member = (await gate('member', 'private', 'post')).answer
752
+ expect(member.viewer).toMatchObject({ my_membership: 'active', can_post: true })
753
+ expect((await gate('moderator', 'private', 'post')).answer.viewer.can_post).toBe(true)
754
+ })
755
+
756
+ it('admits a site moderator and an admin, and refuses what it cannot name', async () => {
757
+ const site = load({ moderator: true })
758
+ expect(
759
+ (
760
+ await site.module.loadCommunityGate({
761
+ slug: COMMUNITY.slug,
762
+ session: SESSION,
763
+ need: 'moderate',
764
+ })
765
+ ).viewer.can_moderate
766
+ ).toBe(true)
767
+ const admin = await load().module.loadCommunityGate({
768
+ slug: COMMUNITY.slug,
769
+ session: { id: 'boss', role: 'admin' },
770
+ need: 'moderate',
771
+ })
772
+ expect(admin.viewer.can_moderate).toBe(true)
773
+
774
+ // A signed-out visitor is refused before the database is asked anything.
775
+ const anonymous = await gate('signed out', 'public', 'post')
776
+ expect(anonymous.loaded.statements).toEqual([])
777
+ const moderator = load({ membership: { role: 'owner', status: 'active' } })
778
+ const ask = (args: Record<string, unknown>) =>
779
+ moderator.module.loadCommunityGate({ slug: COMMUNITY.slug, session: SESSION, ...args })
780
+ expect(await ask({ need: 'anything' })).toBeNull()
781
+ expect(await ask({})).toBeNull()
782
+ expect(await ask({ need: 'moderate', slug: 'nope' })).toBeNull()
783
+ // An archived community: still managed, no longer written in by its members.
784
+ const archived = { status: 'archived', visibility: 'public' }
785
+ const closed = load({ member: true, community: archived })
786
+ expect(
787
+ await closed.module.loadCommunityGate({
788
+ slug: COMMUNITY.slug,
789
+ session: SESSION,
790
+ need: 'post',
791
+ })
792
+ ).toBeNull()
793
+ const kept = load({ membership: { role: 'owner', status: 'active' }, community: archived })
794
+ const managed = await kept.module.loadCommunityGate({
795
+ slug: COMMUNITY.slug,
796
+ session: SESSION,
797
+ need: 'moderate',
798
+ })
799
+ expect(managed.viewer).toMatchObject({ can_moderate: true, can_post: false })
800
+ })
801
+
802
+ it('lets the owner, a site moderator and an admin delete the community, never a community moderator', async () => {
803
+ const canDelete = async (fixture: Fixture, session: unknown = SESSION) =>
804
+ (
805
+ await load(fixture).module.loadCommunityGate({
806
+ slug: COMMUNITY.slug,
807
+ session,
808
+ need: 'moderate',
809
+ })
810
+ ).viewer.can_delete
811
+ expect(await canDelete({ membership: { role: 'owner', status: 'active' } })).toBe(true)
812
+ expect(await canDelete({ moderator: true })).toBe(true)
813
+ expect(
814
+ await canDelete(
815
+ { membership: { role: 'moderator', status: 'active' } },
816
+ { id: 'boss', role: 'admin' }
817
+ )
818
+ ).toBe(true)
819
+ expect(await canDelete({}, { id: 'boss', role: 'admin' })).toBe(true)
820
+ expect(await canDelete({ membership: { role: 'moderator', status: 'active' } })).toBe(false)
821
+ // The community a forum keeps its topics in has no Manage page at all.
822
+ expect(
823
+ await load({
824
+ membership: { role: 'owner', status: 'active' },
825
+ community: { slug: 'main' },
826
+ }).module.loadCommunityGate({ slug: COMMUNITY.slug, session: SESSION, need: 'moderate' })
827
+ ).toBeNull()
828
+ })
829
+ })
830
+
831
+ it('answers the replies route through the same rules, from an offset', async () => {
832
+ const loaded = load({ member: true })
833
+ const page = await loaded.module.loadReplies({
834
+ topicId: TOPIC.id,
835
+ session: { id: 'user-1' },
836
+ sort: 'new',
837
+ after: 50,
838
+ })
839
+ expect(page.replies.map((r: any) => r.id.slice(-1))).toEqual(['5', '2', '1'])
840
+ // The page's count follows a reply posted: the topic's published replies as stored now.
841
+ expect(page.replyCount).toBe(TOPIC.reply_count)
842
+ const heads = loaded.statements.find((statement) =>
843
+ statement.sql.includes('r.parent_id IS NULL')
844
+ )!
845
+ expect(heads.sql).toContain('ORDER BY r.created_at DESC LIMIT $3 OFFSET $4')
846
+ expect(heads.params).toEqual([TOPIC.id, 'user-1', 51, 50])
847
+ expect(await load().module.loadReplies({ topicId: TOPIC.id, session: null })).toBeNull()
848
+ })
849
+
850
+ describe('flat replies', () => {
851
+ const FLAT: Fixture = { member: true, settings: { replyNesting: 'flat' } }
852
+ const SESSION = { id: 'user-1' }
853
+ const idsOf = (replies: any[]) => replies.map((r: any) => r.id.slice(-1))
854
+
855
+ it('reads every reply of the topic as one level, in the order asked', async () => {
856
+ const loaded = load(FLAT)
857
+ const page = await loaded.module.loadTopicPage({
858
+ slug: TOPIC.slug,
859
+ session: SESSION,
860
+ sort: 'old',
861
+ })
862
+ // The database's order, nothing nested: a reply to a reply is a row of the list, not lost.
863
+ expect(idsOf(page.replies)).toEqual(['1', '2', '5', '3', '4'])
864
+ expect(page.replies.every((r: any) => Array.isArray(r.children) && !r.children.length)).toBe(
865
+ true
866
+ )
867
+ expect(page.replies[4].parent_id).toBe(CHILDREN[0].id)
868
+ // The removed one keeps its place, masked; the accepted answer is the list's own row.
869
+ expect(page.replies[2].body_html).toBe('<p><em>[removed]</em></p>')
870
+ expect(page.topic.accepted_reply).toMatchObject({ id: TOPIC.accepted_reply_id })
871
+ expect(page.hasMoreReplies).toBe(false)
872
+ expect(page.nextReplyOffset).toBe(5)
873
+ const heads = loaded.statements.find((statement) => statement.sql.includes('OFFSET $4'))!
874
+ expect(heads.sql).toContain(
875
+ "WHERE r.topic_id = $1 AND (r.status IN ('published', 'removed') OR (r.status = 'pending' AND r.author_id = $2)) ORDER BY r.created_at ASC LIMIT $3 OFFSET $4"
876
+ )
877
+ expect(heads.params).toEqual([TOPIC.id, 'user-1', 51, 0])
878
+ expect(sqlOf(loaded)).not.toContain('r.parent_id IS NULL')
879
+ expect(sqlOf(loaded)).not.toContain('r.path LIKE ANY')
880
+ })
881
+
882
+ it('answers the same list to "Continue this thread" and pages it on the replies route', async () => {
883
+ const continued = load(FLAT)
884
+ const page = await continued.module.loadTopicPage({
885
+ slug: TOPIC.slug,
886
+ session: SESSION,
887
+ rootReplyId: CHILDREN[0].id,
888
+ })
889
+ expect(idsOf(page.replies)).toEqual(['1', '2', '5', '3', '4'])
890
+ expect(sqlOf(continued)).not.toContain('SELECT r.id, r.depth, r.path')
891
+ expect(sqlOf(continued)).not.toContain('r.parent_id = $2')
892
+
893
+ // One more row than a page holds says there is more.
894
+ const many = Array.from({ length: 51 }, (_, i) => reply(1, null, 0, { id: `r-${i}` }))
895
+ const route = load({ ...FLAT, flatReplies: many })
896
+ const more = await route.module.loadReplies({
897
+ topicId: TOPIC.id,
898
+ session: SESSION,
899
+ sort: 'new',
900
+ after: 50,
901
+ rootReplyId: CHILDREN[0].id,
902
+ })
903
+ expect(more.replies).toHaveLength(50)
904
+ expect(more.hasMore).toBe(true)
905
+ expect(more.nextOffset).toBe(100)
906
+ const heads = route.statements.find((statement) => statement.sql.includes('OFFSET $4'))!
907
+ expect(heads.sql).toContain('ORDER BY r.created_at DESC LIMIT $3 OFFSET $4')
908
+ expect(heads.params).toEqual([TOPIC.id, 'user-1', 51, 50])
909
+ })
910
+ })
911
+
912
+ describe('who may edit a post', () => {
913
+ const AUTHOR = { id: 'author' }
914
+ const SESSION = { id: 'user-1' }
915
+ const RECENT: Fixture = { topic: { created_at: minutesAgo(5) } }
916
+ const topicViewer = async (fixture: Fixture, session: unknown) =>
917
+ (
918
+ await load({ community: { visibility: 'public' }, ...fixture }).module.loadTopicPage({
919
+ slug: TOPIC.slug,
920
+ session,
921
+ })
922
+ ).viewer
923
+ // Every reply's can_edit, by the reply's number, through the whole tree.
924
+ const canEditOf = (replies: any[]): Record<string, boolean> => {
925
+ const out: Record<string, boolean> = {}
926
+ const walk = (nodes: any[]) =>
927
+ nodes.forEach((node) => {
928
+ out[node.id.slice(-1)] = node.can_edit
929
+ walk(node.children)
930
+ })
931
+ walk(replies)
932
+ return out
933
+ }
934
+
935
+ it('lets the topic’s author edit it within the edit window, and who moderates it always', async () => {
936
+ expect((await topicViewer(RECENT, AUTHOR)).can_edit).toBe(true)
937
+ // Thirty minutes unless set; 0 is no window at all.
938
+ expect((await topicViewer({ topic: { created_at: minutesAgo(31) } }, AUTHOR)).can_edit).toBe(
939
+ false
940
+ )
941
+ expect(
942
+ (
943
+ await topicViewer(
944
+ { settings: { editWindowMinutes: 120 }, topic: { created_at: minutesAgo(90) } },
945
+ AUTHOR
946
+ )
947
+ ).can_edit
948
+ ).toBe(true)
949
+ expect((await topicViewer({ settings: { editWindowMinutes: 0 } }, AUTHOR)).can_edit).toBe(
950
+ true
951
+ )
952
+ // Anyone else, a visitor: never.
953
+ expect((await topicViewer(RECENT, SESSION)).can_edit).toBe(false)
954
+ expect((await topicViewer(RECENT, null)).can_edit).toBe(false)
955
+ // Who moderates it, however old: the community's moderator, a site moderator, an admin.
956
+ const communityModerator = { membership: { role: 'moderator', status: 'active' } }
957
+ expect((await topicViewer(communityModerator, SESSION)).can_edit).toBe(true)
958
+ expect((await topicViewer({ moderator: true }, SESSION)).can_edit).toBe(true)
959
+ expect((await topicViewer({}, { id: 'boss', role: 'admin' })).can_edit).toBe(true)
960
+ // Never someone banned, never a removed post.
961
+ expect((await topicViewer({ ...RECENT, profileRole: 'banned' }, AUTHOR)).can_edit).toBe(false)
962
+ const removed = { moderator: true, topic: { status: 'removed' } }
963
+ expect((await topicViewer(removed, SESSION)).can_edit).toBe(false)
964
+ })
965
+
966
+ it('says it on every reply: the tree, the accepted answer and the replies route', async () => {
967
+ const always: Fixture = { member: true, settings: { editWindowMinutes: 0 } }
968
+ const ask = (fixture: Fixture, session: unknown = SESSION) =>
969
+ load(fixture).module.loadTopicPage({ slug: TOPIC.slug, session })
970
+ // user-1 wrote reply 1 only; reply 5 is removed.
971
+ const own = { '1': true, '2': false, '3': false, '4': false, '5': false }
972
+ expect(canEditOf((await ask(always)).replies)).toEqual(own)
973
+ // The fixture's replies were written weeks ago: past the window, its author no longer.
974
+ expect(canEditOf((await ask({ member: true })).replies)['1']).toBe(false)
975
+ // Who moderates: every reply but the removed one.
976
+ expect(canEditOf((await ask({ moderator: true })).replies)).toEqual({
977
+ '1': true,
978
+ '2': true,
979
+ '3': true,
980
+ '4': true,
981
+ '5': false,
982
+ })
983
+ // A visitor of a public community's topic: none.
984
+ const visitor = await ask({ ...always, community: { visibility: 'public' } }, null)
985
+ expect(Object.values(canEditOf(visitor.replies)).some(Boolean)).toBe(false)
986
+ // The accepted answer read by id, off the page, carries it too.
987
+ const offPage = await ask({ ...always, topic: { accepted_reply_id: OFF_PAGE.id } })
988
+ expect(offPage.topic.accepted_reply).toMatchObject({ id: OFF_PAGE.id, can_edit: true })
989
+ const more = await load(always).module.loadReplies({ topicId: TOPIC.id, session: SESSION })
990
+ expect(canEditOf(more.replies)).toEqual(own)
991
+ })
992
+ })
993
+
994
+ describe('a community that is not active', () => {
995
+ // The fixture's community was created by `owner`, who holds no membership unless said.
996
+ const CREATOR = { id: 'owner' }
997
+ const SESSION = { id: 'user-1' }
998
+ const communityPage = (status: string, session: unknown, fixture: Fixture = {}) =>
999
+ load({ community: { status, visibility: 'public' }, ...fixture }).module.loadCommunityPage({
1000
+ slug: COMMUNITY.slug,
1001
+ session,
1002
+ })
1003
+
1004
+ it('shows one waiting for approval to its creator and who moderates it, to nobody else', async () => {
1005
+ expect(await communityPage('pending', null)).toBeNull()
1006
+ expect(await communityPage('pending', SESSION)).toBeNull()
1007
+ expect(await communityPage('pending', SESSION, { member: true })).toBeNull()
1008
+ const mine = await communityPage('pending', CREATOR)
1009
+ expect(mine.community.status).toBe('pending')
1010
+ expect(mine.viewer).toMatchObject({ is_creator: true, can_moderate: false, can_post: false })
1011
+ expect(mine.seo.noindex).toBe(true)
1012
+ const moderated = await communityPage('pending', SESSION, { moderator: true })
1013
+ expect(moderated.viewer).toMatchObject({
1014
+ is_creator: false,
1015
+ can_moderate: true,
1016
+ can_post: false,
1017
+ })
1018
+ expect(moderated.seo.noindex).toBe(true)
1019
+ })
1020
+
1021
+ it('shows an archived one to who moderates it only, its creator too only as one', async () => {
1022
+ expect(await communityPage('archived', CREATOR)).toBeNull()
1023
+ expect(await communityPage('archived', SESSION)).toBeNull()
1024
+ const owner = { membership: { role: 'owner', status: 'active' } }
1025
+ const kept = await communityPage('archived', CREATOR, owner)
1026
+ expect(kept.viewer).toMatchObject({ is_creator: true, can_moderate: true, can_post: false })
1027
+ expect(kept.seo.noindex).toBe(true)
1028
+ })
1029
+
1030
+ it('says who created an active one', async () => {
1031
+ expect((await communityPage('active', CREATOR)).viewer.is_creator).toBe(true)
1032
+ expect((await communityPage('active', SESSION)).viewer.is_creator).toBe(false)
1033
+ expect((await communityPage('active', null)).viewer.is_creator).toBe(false)
1034
+ })
1035
+ })
1036
+
1037
+ it('has no "Top" order of a community’s topics without votes', async () => {
1038
+ const orderOf = async (settings: Record<string, unknown>, sort: string) => {
1039
+ const loaded = load({ community: { visibility: 'public' }, settings })
1040
+ const page = await loaded.module.loadCommunityPage({
1041
+ slug: COMMUNITY.slug,
1042
+ session: null,
1043
+ sort,
1044
+ })
1045
+ const list = loaded.statements.find((statement) => statement.sql.includes('OFFSET'))!
1046
+ return { sortBy: page.sortBy, sql: list.sql }
1047
+ }
1048
+ const off = await orderOf({ votes: 'off' }, 'top')
1049
+ expect(off.sortBy).toBe('latest')
1050
+ expect(off.sql).toContain('ORDER BY t.is_pinned DESC, t.last_activity_at DESC NULLS LAST')
1051
+ // The other orders stay; with votes, upvotes only too, "Top" is the score's.
1052
+ expect((await orderOf({ votes: 'off' }, 'new')).sortBy).toBe('new')
1053
+ expect((await orderOf({ votes: 'up' }, 'top')).sortBy).toBe('top')
1054
+ })
1055
+
1056
+ it('reads and marks notifications for the session’s user only', async () => {
1057
+ const loaded = load()
1058
+ expect(await loaded.module.loadNotifications(null, {})).toEqual({ items: [], unreadCount: 0 })
1059
+ const mine = await loaded.module.loadNotifications({ sub: 'user-9' }, { limit: 5 })
1060
+ // `text` beside `title`: the profile tab binds one, the overlay the other.
1061
+ expect(mine.items[0]).toMatchObject({
1062
+ title: 'Jane replied',
1063
+ text: 'Jane replied',
1064
+ created_at: '2026-10-03T12:00:00.000Z',
1065
+ })
1066
+ await loaded.module.markNotificationsRead({ id: 'user-9' }, ['n1'])
1067
+ const sql = sqlOf(loaded)
1068
+ expect(sql).toContain(
1069
+ 'FROM teleport_forum_notifications n WHERE n.user_id = $1 ORDER BY n.created_at DESC LIMIT $2'
1070
+ )
1071
+ expect(sql).toContain(
1072
+ 'SET read_at = NOW() WHERE user_id = $1 AND read_at IS NULL AND id = ANY($2::uuid[])'
1073
+ )
1074
+ expect(loaded.statements.every((statement) => statement.params[0] === 'user-9')).toBe(true)
1075
+ })
1076
+
1077
+ it('names the pictures a topic or a reply still shows, by the file id in their address', async () => {
1078
+ const loaded = load()
1079
+ expect(await loaded.module.filesStillShown(['f-1', 'f-2'])).toEqual([])
1080
+ const statement = loaded.statements[loaded.statements.length - 1]
1081
+ expect(statement.params).toEqual([['f-1', 'f-2']])
1082
+ expect(statement.sql).toContain('FROM unnest($1::text[]) AS f(id)')
1083
+ expect(statement.sql).toContain(
1084
+ "FROM teleport_forum_topics t WHERE t.attachments::text LIKE '%/' || f.id || '/%'"
1085
+ )
1086
+ expect(statement.sql).toContain(
1087
+ "FROM teleport_forum_replies r WHERE r.attachments::text LIKE '%/' || f.id || '/%'"
1088
+ )
1089
+ // A community's icon or banner is a picture the forum still shows too.
1090
+ expect(statement.sql).toContain(
1091
+ "FROM teleport_forum_communities c WHERE COALESCE(c.icon_url, '') LIKE '%/' || f.id || '/%' OR COALESCE(c.banner_url, '') LIKE '%/' || f.id || '/%'"
1092
+ )
1093
+ })
1094
+
1095
+ it('lists only public, published rows for the live index', async () => {
1096
+ const loaded = load()
1097
+ await loaded.module.listPublicIndex()
1098
+ const sql = sqlOf(loaded)
1099
+ expect(sql).toContain("c.status = 'active' AND c.visibility <> 'private'")
1100
+ // A topic of an archived community, or of one still waiting for approval, is not listed.
1101
+ expect(sql).toContain(
1102
+ "t.status = 'published' AND t.community_visibility <> 'private' AND EXISTS (SELECT 1 FROM teleport_forum_communities c WHERE c.id = t.community_id AND c.status = 'active')"
1103
+ )
1104
+ })
1105
+
1106
+ describe('a forum without communities', () => {
1107
+ // The one community its topics are kept in, as the editor writes it at activation.
1108
+ const MAIN = {
1109
+ slug: 'main',
1110
+ name: 'General',
1111
+ description: 'Everything that has no community of its own.',
1112
+ kind: 'discussion',
1113
+ visibility: 'public',
1114
+ }
1115
+ const IN_MAIN = {
1116
+ community_slug: 'main',
1117
+ community_name: 'General',
1118
+ community_visibility: 'public',
1119
+ }
1120
+ const SESSION = { id: 'user-1' }
1121
+ const TOPIC_URL = `https://site.example/forum/t/${TOPIC.slug}`
1122
+ const topicsOnly = (fixture: Fixture = {}) =>
1123
+ load({ structure: 'topics', community: MAIN, topic: IN_MAIN, ...fixture })
1124
+ // The same rows in a forum that has communities.
1125
+ const withCommunities = (fixture: Fixture = {}) =>
1126
+ load({ community: MAIN, topic: IN_MAIN, ...fixture })
1127
+ const namesTheCommunity = (answer: unknown): boolean =>
1128
+ /General|"main"|\/forum\/c|no community of its own/.test(JSON.stringify(answer))
1129
+
1130
+ it('names and links no community on a topic, and still decides the rights on it', async () => {
1131
+ const loaded = topicsOnly()
1132
+ const page = await loaded.module.loadTopicPage({
1133
+ slug: TOPIC.slug,
1134
+ session: SESSION,
1135
+ url: TOPIC_URL,
1136
+ })
1137
+ expect(page.topic.community_name).toBe('')
1138
+ expect(page.topic.community_url).toBe('')
1139
+ expect(page.topic.community_slug).toBe('')
1140
+ expect(page.community).toBeNull()
1141
+ // A public topic is indexed, and its JSON-LD names the topic and its author alone.
1142
+ expect(page.seo.noindex).toBe(false)
1143
+ expect(page.seo.jsonLd).toMatchObject({
1144
+ '@type': 'DiscussionForumPosting',
1145
+ url: TOPIC_URL,
1146
+ headline: 'How do I start?',
1147
+ })
1148
+ expect(namesTheCommunity(page)).toBe(false)
1149
+ // The rest of the topic is what any forum answers.
1150
+ expect(page.topic.title).toBe('How do I start?')
1151
+ expect(page.topic.body_html).toBe('<p>Hello <strong>world</strong></p>')
1152
+ expect(page.replies.map((r: any) => r.id.slice(-1))).toEqual(['2', '5', '1'])
1153
+ // The community row is still read: anyone signed in posts, nobody is a member.
1154
+ expect(sqlOf(loaded)).toContain('FROM teleport_forum_communities c WHERE c.id = $1')
1155
+ expect(page.viewer).toMatchObject({
1156
+ signed_in: true,
1157
+ my_membership: null,
1158
+ my_role: null,
1159
+ can_read: true,
1160
+ can_post: true,
1161
+ can_moderate: false,
1162
+ })
1163
+ const moderator = await topicsOnly({ moderator: true }).module.loadTopicPage({
1164
+ slug: TOPIC.slug,
1165
+ session: SESSION,
1166
+ })
1167
+ expect(moderator.viewer.can_moderate).toBe(true)
1168
+ const banned = await topicsOnly({ profileRole: 'banned' }).module.loadTopicPage({
1169
+ slug: TOPIC.slug,
1170
+ session: SESSION,
1171
+ })
1172
+ expect(banned.viewer).toMatchObject({ can_read: true, can_post: false })
1173
+ // An archived main community closes its topics to everyone but who moderates.
1174
+ const archived = { ...MAIN, status: 'archived' }
1175
+ expect(
1176
+ await topicsOnly({ community: archived }).module.loadTopicPage({
1177
+ slug: TOPIC.slug,
1178
+ session: SESSION,
1179
+ })
1180
+ ).toBeNull()
1181
+
1182
+ // The same rows in a forum with communities name it, link it and answer it.
1183
+ const named = await withCommunities().module.loadTopicPage({
1184
+ slug: TOPIC.slug,
1185
+ session: SESSION,
1186
+ url: TOPIC_URL,
1187
+ })
1188
+ expect(named.topic.community_name).toBe('General')
1189
+ expect(named.topic.community_url).toBe('/forum/c/main')
1190
+ expect(named.topic.community_slug).toBe('main')
1191
+ expect(named.community).toMatchObject({ slug: 'main', name: 'General' })
1192
+ expect(named.viewer).toEqual(page.viewer)
1193
+ })
1194
+
1195
+ it('opens the composer by the main community’s slug, answering the rights alone', async () => {
1196
+ const ask = (loaded: Loaded, session: unknown) =>
1197
+ loaded.module.loadCommunityGate({ slug: 'main', session, need: 'post' })
1198
+
1199
+ const anonymous = topicsOnly()
1200
+ expect(await ask(anonymous, null)).toBeNull()
1201
+ expect(anonymous.statements).toEqual([])
1202
+
1203
+ const answer = await ask(topicsOnly(), SESSION)
1204
+ expect(answer.community).toBeNull()
1205
+ expect(answer.viewer).toMatchObject({ signed_in: true, can_read: true, can_post: true })
1206
+ expect(Object.keys(answer.viewer).filter((key) => key.startsWith('community'))).toEqual([])
1207
+ expect(namesTheCommunity(answer)).toBe(false)
1208
+ // Someone banned from posting still gets the page, which tells them so.
1209
+ expect((await ask(topicsOnly({ profileRole: 'banned' }), SESSION)).viewer.can_post).toBe(
1210
+ false
1211
+ )
1212
+ // No main community (a database that lost the row): there is nothing to write in.
1213
+ expect(
1214
+ await topicsOnly().module.loadCommunityGate({
1215
+ slug: 'nope',
1216
+ session: SESSION,
1217
+ need: 'post',
1218
+ })
1219
+ ).toBeNull()
1220
+
1221
+ // A forum with communities answers the community with the rights, as its pages bind it.
1222
+ const named = await ask(withCommunities(), SESSION)
1223
+ expect(named.community).toMatchObject({ slug: 'main', name: 'General' })
1224
+ expect(named.viewer).toMatchObject({ community_slug: 'main', community_name: 'General' })
1225
+ })
1226
+
1227
+ it('has no community page and no community in the public index', async () => {
1228
+ const loaded = topicsOnly()
1229
+ expect(await loaded.module.loadCommunityPage({ slug: 'main', session: SESSION })).toBeNull()
1230
+ expect(loaded.statements).toEqual([])
1231
+
1232
+ const index = await loaded.module.listPublicIndex()
1233
+ expect(index.communities).toEqual([])
1234
+ expect(index.topics).toEqual([
1235
+ {
1236
+ slug: TOPIC.slug,
1237
+ title: 'How do I start?',
1238
+ updated_at: '2026-10-01T12:00:00.000Z',
1239
+ excerpt: 'Hello world',
1240
+ },
1241
+ ])
1242
+ // No community is listed: only the main one's status is asked, for its topics.
1243
+ expect(sqlOf(loaded)).not.toContain('SELECT c.slug')
1244
+ expect(sqlOf(loaded)).toContain(
1245
+ "t.status = 'published' AND t.community_visibility <> 'private' AND EXISTS (SELECT 1 FROM teleport_forum_communities c WHERE c.id = t.community_id AND c.status = 'active')"
1246
+ )
1247
+
1248
+ expect((await withCommunities().module.listPublicIndex()).communities).toHaveLength(1)
1249
+ })
1250
+
1251
+ it('lists the topics alone in the sitemap and the llms file', async () => {
1252
+ const config = configOf({ structure: 'topics' })
1253
+ const sitemap = await sendIndexPage(buildForumSitemapPageSource(config), topicsOnly())
1254
+ expect(sitemap.match(/<loc>[^<]*<\/loc>/g)).toEqual([`<loc>${TOPIC_URL}</loc>`])
1255
+ const llms = await sendIndexPage(buildForumLlmsPageSource(config), topicsOnly())
1256
+ expect(llms).toBe(`# Forum\n\n## Topics\n\n- [How do I start?](${TOPIC_URL}): Hello world\n`)
1257
+
1258
+ // With communities both name each community first, as before.
1259
+ const named = configOf()
1260
+ const namedSitemap = await sendIndexPage(
1261
+ buildForumSitemapPageSource(named),
1262
+ withCommunities()
1263
+ )
1264
+ expect(namedSitemap.match(/<loc>[^<]*<\/loc>/g)).toEqual([
1265
+ '<loc>https://site.example/forum/c/main</loc>',
1266
+ `<loc>${TOPIC_URL}</loc>`,
1267
+ ])
1268
+ const namedLlms = await sendIndexPage(buildForumLlmsPageSource(named), withCommunities())
1269
+ expect(namedLlms).toBe(
1270
+ '# Forum\n\n## Communities\n\n' +
1271
+ '- [General](https://site.example/forum/c/main): Everything that has no community of its own.\n' +
1272
+ `\n## Topics\n\n- [How do I start?](${TOPIC_URL}): Hello world\n`
1273
+ )
1274
+ })
1275
+
1276
+ /**
1277
+ * A site in several languages serves every forum page under each language's
1278
+ * prefix too: the sitemap lists each address with the others as alternates
1279
+ * and the default one as `x-default`, as the editor's static sitemap does.
1280
+ */
1281
+ it('lists each page in every language of a site in several languages', async () => {
1282
+ const named = configOf()
1283
+ const languages = { locales: ['en', 'es'], defaultLocale: 'en', locale: 'en' }
1284
+ const sitemap = await sendIndexPage(
1285
+ buildForumSitemapPageSource(named, { multilingual: true }),
1286
+ withCommunities(),
1287
+ languages
1288
+ )
1289
+ const community = 'https://site.example/forum/c/main'
1290
+ const spanishCommunity = 'https://site.example/es/forum/c/main'
1291
+ const spanishTopic = `https://site.example/es/forum/t/${TOPIC.slug}`
1292
+
1293
+ expect(sitemap).toContain(
1294
+ '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xhtml="http://www.w3.org/1999/xhtml">'
1295
+ )
1296
+ expect(sitemap.match(/<loc>[^<]*<\/loc>/g)).toEqual([
1297
+ `<loc>${community}</loc>`,
1298
+ `<loc>${spanishCommunity}</loc>`,
1299
+ `<loc>${TOPIC_URL}</loc>`,
1300
+ `<loc>${spanishTopic}</loc>`,
1301
+ ])
1302
+ const topicEntries = sitemap.split('<url>').filter((entry) => entry.includes('/forum/t/'))
1303
+ expect(topicEntries).toHaveLength(2)
1304
+ topicEntries.forEach((entry) => {
1305
+ expect(entry.match(/<xhtml:link [^>]*\/>/g)).toEqual([
1306
+ `<xhtml:link rel="alternate" hreflang="en" href="${TOPIC_URL}" />`,
1307
+ `<xhtml:link rel="alternate" hreflang="es" href="${spanishTopic}" />`,
1308
+ `<xhtml:link rel="alternate" hreflang="x-default" href="${TOPIC_URL}" />`,
1309
+ ])
1310
+ expect(entry).toContain('<lastmod>2026-10-01T12:00:00.000Z</lastmod>')
1311
+ })
1312
+
1313
+ // A site in one language reads exactly as the single-language sitemap.
1314
+ const alone = await sendIndexPage(
1315
+ buildForumSitemapPageSource(named, { multilingual: true }),
1316
+ withCommunities(),
1317
+ { locales: ['en'], defaultLocale: 'en', locale: 'en' }
1318
+ )
1319
+ expect(alone.replace(' xmlns:xhtml="http://www.w3.org/1999/xhtml"', '')).toBe(
1320
+ await sendIndexPage(buildForumSitemapPageSource(named), withCommunities())
1321
+ )
1322
+ // Without languages the page is generated as it always was.
1323
+ expect(buildForumSitemapPageSource(named, { multilingual: false })).toBe(
1324
+ buildForumSitemapPageSource(named)
1325
+ )
1326
+ expect(buildForumSitemapPageSource(named)).not.toContain('xhtml')
1327
+ })
1328
+ })
1329
+ })