@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,328 @@
1
+ import {
2
+ FileType,
3
+ GeneratedFile,
4
+ InMemoryFileRecord,
5
+ ProjectPlugin,
6
+ ProjectPluginStructure,
7
+ ProjectUIDL,
8
+ } from '@teleporthq/teleport-types'
9
+ import { PageArrival } from '@teleporthq/teleport-shared'
10
+ import {
11
+ ensureSecurityRuntimeModule,
12
+ getDatabaseDriverDependencies,
13
+ } from '@teleporthq/teleport-plugin-next-workflows'
14
+ import { DetailsRoute } from '../instant-search/sections'
15
+ import { resolveAppLocales } from '../pwa/locales'
16
+ import {
17
+ ForumConfig,
18
+ ForumDetailsPage,
19
+ FORUM_MAIN_COMMUNITY_SLUG,
20
+ resolveForumConfig,
21
+ } from './settings'
22
+ import {
23
+ buildForumMarkdownSource,
24
+ FORUM_MARKDOWN_MODULE_NAME,
25
+ FORUM_MARKDOWN_MODULE_PATH,
26
+ } from './markdown-source'
27
+ import {
28
+ buildForumPageDataSource,
29
+ FORUM_PAGE_DATA_MODULE_NAME,
30
+ FORUM_PAGE_DATA_MODULE_PATH,
31
+ } from './page-data-source'
32
+ import { buildForumRepliesRouteSource, FORUM_REPLIES_ROUTE } from './replies-route'
33
+ import { buildForumFilesRouteSource, FORUM_FILES_ROUTE } from './files-route'
34
+ import {
35
+ buildForumNotificationsRouteSource,
36
+ FORUM_NOTIFICATIONS_ROUTE,
37
+ } from './notifications-route'
38
+ import {
39
+ buildForumLlmsPageSource,
40
+ buildForumSitemapPageSource,
41
+ FORUM_LLMS_PATH,
42
+ FORUM_SITEMAP_PATH,
43
+ } from './seo'
44
+ import { ForumPageRecord, rewriteForumPage } from './page-rewrite'
45
+
46
+ export const FORUM_FILE_KEYS = {
47
+ markdown: 'forum-markdown',
48
+ pageData: 'forum-page-data',
49
+ repliesRoute: 'forum-replies-route',
50
+ filesRoute: 'forum-files-route',
51
+ notificationsRoute: 'forum-notifications-route',
52
+ sitemap: 'forum-sitemap',
53
+ llms: 'forum-llms',
54
+ pageArrival: `resource-${PageArrival.PAGE_ARRIVAL_DIR.join('/')}/${
55
+ PageArrival.PAGE_ARRIVAL_FILE_NAME
56
+ }`,
57
+ }
58
+
59
+ /** `/api/plugins/forum/replies` → `pages/api/plugins/forum` + `replies`. */
60
+ const routeFile = (route: string): { path: string[]; name: string } => {
61
+ const segments = route.split('/').filter(Boolean)
62
+ return { path: ['pages', ...segments.slice(0, -1)], name: segments[segments.length - 1] }
63
+ }
64
+
65
+ const setJsFile = (
66
+ structure: ProjectPluginStructure,
67
+ key: string,
68
+ path: string[],
69
+ name: string,
70
+ content: string
71
+ ): void => {
72
+ structure.files.set(key, { path, files: [{ name, fileType: FileType.JS, content }] })
73
+ }
74
+
75
+ const hasFile = (files: Map<string, InMemoryFileRecord>, path: string[], name: string): boolean => {
76
+ let found = false
77
+ files.forEach((record) => {
78
+ if (!found && record?.path?.join('/') === path.join('/')) {
79
+ found = (record.files || []).some((file: GeneratedFile) => file?.name === name)
80
+ }
81
+ })
82
+ return found
83
+ }
84
+
85
+ /** Where a generated page is written: `<folder>/<name>.js`. */
86
+ interface PageFileAddress {
87
+ folder: string[]
88
+ name: string
89
+ }
90
+
91
+ const segmentsOf = (route: string): string[] => route.split('/').filter(Boolean)
92
+
93
+ /** A details page is written under its column: `/forum/t/[slug]` at `pages/forum/t/[slug].js`. */
94
+ const detailsPageFile = (route: DetailsRoute): PageFileAddress => ({
95
+ folder: ['pages', ...segmentsOf(route.staticBase)],
96
+ name: `[${route.column}]`,
97
+ })
98
+
99
+ /** A static page is written under its last segment: `/forum/new` at `pages/forum/new.js`. */
100
+ const staticPageFile = (route: string): PageFileAddress => {
101
+ const segments = segmentsOf(route)
102
+ const name = segments.pop() ?? 'index'
103
+ return { folder: ['pages', ...segments], name }
104
+ }
105
+
106
+ /** The generated page at `address`, as `files` keeps it. */
107
+ const findPageFile = (
108
+ files: Map<string, InMemoryFileRecord>,
109
+ address: PageFileAddress
110
+ ): { record: InMemoryFileRecord; file: GeneratedFile } | null => {
111
+ const folder = address.folder.join('/')
112
+ const { name } = address
113
+ let found: { record: InMemoryFileRecord; file: GeneratedFile } | null = null
114
+ files.forEach((record) => {
115
+ if (found || record?.path?.join('/') !== folder) {
116
+ return
117
+ }
118
+ const file = (record.files || []).find(
119
+ (candidate: GeneratedFile) =>
120
+ candidate?.name === name &&
121
+ typeof candidate.content === 'string' &&
122
+ candidate.fileType === FileType.JS
123
+ )
124
+ if (file) {
125
+ found = { record, file }
126
+ }
127
+ })
128
+ return found
129
+ }
130
+
131
+ /** What the page reads its row as (`initialPropsData.exposeAs.name`), from the project's routes. */
132
+ const exposeAsOf = (uidl: ProjectUIDL, route: DetailsRoute): string | null => {
133
+ const values = (
134
+ uidl as unknown as { root?: { stateDefinitions?: { route?: { values?: unknown[] } } } }
135
+ ).root?.stateDefinitions?.route?.values
136
+ const navLink = `${route.staticBase}/[${route.column}]`
137
+ for (const value of Array.isArray(values) ? values : []) {
138
+ const pageOptions = (value as { pageOptions?: Record<string, unknown> })?.pageOptions
139
+ if (pageOptions?.navLink !== navLink) {
140
+ continue
141
+ }
142
+ const exposeAs = (pageOptions.initialPropsData as { exposeAs?: { name?: string } } | undefined)
143
+ ?.exposeAs
144
+ return typeof exposeAs?.name === 'string' && exposeAs.name ? exposeAs.name : null
145
+ }
146
+ return null
147
+ }
148
+
149
+ /** A page to render per request: where it is written, and which record it is about. */
150
+ interface ForumPageTarget {
151
+ kind: ForumDetailsPage
152
+ file: PageFileAddress
153
+ record: ForumPageRecord
154
+ exposeAs: string | null
155
+ }
156
+
157
+ const DETAILS_PAGES: ForumDetailsPage[] = ['topic', 'community', 'manage', 'newTopic']
158
+
159
+ /**
160
+ * The pages the project has, of the ones served per request: its details
161
+ * pages, each about the record its address names, and — in a forum without
162
+ * communities — the static New topic page, always about the main community
163
+ * (no route column, no record prop).
164
+ */
165
+ const forumPageTargets = (uidl: ProjectUIDL, config: ForumConfig): ForumPageTarget[] => {
166
+ const targets: ForumPageTarget[] = []
167
+ for (const kind of DETAILS_PAGES) {
168
+ const route = config.routes[kind]
169
+ if (route) {
170
+ targets.push({
171
+ kind,
172
+ file: detailsPageFile(route),
173
+ record: { column: route.column },
174
+ exposeAs: exposeAsOf(uidl, route),
175
+ })
176
+ }
177
+ }
178
+ if (config.composerPath) {
179
+ targets.push({
180
+ kind: 'newTopic',
181
+ file: staticPageFile(config.composerPath),
182
+ record: { slug: FORUM_MAIN_COMMUNITY_SLUG },
183
+ exposeAs: null,
184
+ })
185
+ }
186
+ return targets
187
+ }
188
+
189
+ /**
190
+ * The Forum plugin on the published site (plan §12): the read side only, since
191
+ * every write is an editor-built workflow. Emits the Markdown renderer and the
192
+ * forum data module, the replies and notifications routes, the forum's own
193
+ * sitemap and llms file, and rewrites the four details pages to render per
194
+ * request through the module (`page-rewrite.ts`): the session decides what is
195
+ * shown. To a non-member, a private community's topic answers `notFound` and
196
+ * its own page shows the About side only (`viewer.can_read` false, no
197
+ * topics). Anonymous answers of the topic and community pages are cached 30 s
198
+ * at the edge, signed-in ones never. A community's Manage and New topic pages
199
+ * are served to who moderates it and to a signed-in viewer who can read it,
200
+ * `notFound` to anyone else, and are never cached nor indexed. A forum without
201
+ * communities (`settings.structure`) has the topic page and a static New topic
202
+ * page, served through the same gate for its main community; no community is
203
+ * named, linked or listed there. A project without the plugin comes out
204
+ * exactly as before.
205
+ */
206
+ export class NextForumProjectPlugin implements ProjectPlugin {
207
+ async runBefore(structure: ProjectPluginStructure): Promise<ProjectPluginStructure> {
208
+ return structure
209
+ }
210
+
211
+ async runAfter(structure: ProjectPluginStructure): Promise<ProjectPluginStructure> {
212
+ const { uidl, dependencies } = structure
213
+ const config = resolveForumConfig(uidl)
214
+ if (!config) {
215
+ return structure
216
+ }
217
+ const withSessionRevocation = uidl.authentication?.enabled === true
218
+
219
+ setJsFile(
220
+ structure,
221
+ FORUM_FILE_KEYS.markdown,
222
+ FORUM_MARKDOWN_MODULE_PATH,
223
+ FORUM_MARKDOWN_MODULE_NAME,
224
+ buildForumMarkdownSource()
225
+ )
226
+ setJsFile(
227
+ structure,
228
+ FORUM_FILE_KEYS.pageData,
229
+ FORUM_PAGE_DATA_MODULE_PATH,
230
+ FORUM_PAGE_DATA_MODULE_NAME,
231
+ buildForumPageDataSource(config, { withSessionRevocation })
232
+ )
233
+ const replies = routeFile(FORUM_REPLIES_ROUTE)
234
+ setJsFile(
235
+ structure,
236
+ FORUM_FILE_KEYS.repliesRoute,
237
+ replies.path,
238
+ replies.name,
239
+ buildForumRepliesRouteSource({ withSessionRevocation })
240
+ )
241
+ const files = routeFile(FORUM_FILES_ROUTE)
242
+ setJsFile(
243
+ structure,
244
+ FORUM_FILE_KEYS.filesRoute,
245
+ files.path,
246
+ files.name,
247
+ buildForumFilesRouteSource({ withSessionRevocation })
248
+ )
249
+ if (config.settings.notifications) {
250
+ const notifications = routeFile(FORUM_NOTIFICATIONS_ROUTE)
251
+ setJsFile(
252
+ structure,
253
+ FORUM_FILE_KEYS.notificationsRoute,
254
+ notifications.path,
255
+ notifications.name,
256
+ buildForumNotificationsRouteSource({ withSessionRevocation })
257
+ )
258
+ }
259
+ setJsFile(
260
+ structure,
261
+ FORUM_FILE_KEYS.sitemap,
262
+ ['pages'],
263
+ FORUM_SITEMAP_PATH.slice(1),
264
+ buildForumSitemapPageSource(config, {
265
+ multilingual:
266
+ Boolean(uidl.internationalization) && resolveAppLocales(uidl).locales.length > 1,
267
+ })
268
+ )
269
+ setJsFile(
270
+ structure,
271
+ FORUM_FILE_KEYS.llms,
272
+ ['pages'],
273
+ FORUM_LLMS_PATH.slice(1),
274
+ buildForumLlmsPageSource(config)
275
+ )
276
+
277
+ // The routes count their visitors through the shared security runtime; the
278
+ // module reads the database through the same driver as the data API.
279
+ ensureSecurityRuntimeModule(structure)
280
+ for (const [name, version] of Object.entries(getDatabaseDriverDependencies('teleport'))) {
281
+ if (!dependencies[name]) {
282
+ dependencies[name] = version
283
+ }
284
+ }
285
+
286
+ this.rewritePages(structure, config)
287
+ return structure
288
+ }
289
+
290
+ private rewritePages(structure: ProjectPluginStructure, config: ForumConfig): void {
291
+ const { uidl, files } = structure
292
+ let remounts = false
293
+ for (const target of forumPageTargets(uidl, config)) {
294
+ const page = findPageFile(files, target.file)
295
+ if (!page) {
296
+ continue
297
+ }
298
+ const rootPrefix = page.record.path.map(() => '..').join('/') + '/'
299
+ const result = rewriteForumPage(page.file.content as string, {
300
+ ...target.record,
301
+ kind: target.kind,
302
+ exposeAs: target.exposeAs,
303
+ rootPrefix,
304
+ dataModulePath: [...FORUM_PAGE_DATA_MODULE_PATH, FORUM_PAGE_DATA_MODULE_NAME].join('/'),
305
+ pageArrivalPath: [...PageArrival.PAGE_ARRIVAL_DIR, PageArrival.PAGE_ARRIVAL_FILE_NAME].join(
306
+ '/'
307
+ ),
308
+ })
309
+ if (!result) {
310
+ continue
311
+ }
312
+ page.file.content = result.content
313
+ remounts = remounts || result.remounts
314
+ }
315
+ if (
316
+ remounts &&
317
+ !hasFile(files, PageArrival.PAGE_ARRIVAL_DIR, PageArrival.PAGE_ARRIVAL_FILE_NAME)
318
+ ) {
319
+ setJsFile(
320
+ structure,
321
+ FORUM_FILE_KEYS.pageArrival,
322
+ [...PageArrival.PAGE_ARRIVAL_DIR],
323
+ PageArrival.PAGE_ARRIVAL_FILE_NAME,
324
+ PageArrival.generatePageArrivalRuntime()
325
+ )
326
+ }
327
+ }
328
+ }
@@ -0,0 +1,91 @@
1
+ import { SessionCookieResolver } from '@teleporthq/teleport-shared'
2
+ import { securityRuntimeSpecifier } from '@teleporthq/teleport-plugin-next-workflows'
3
+ import { toJsLiteral } from '../pwa/source-literals'
4
+ import { FORUM_PAGE_DATA_MODULE_NAME, FORUM_PAGE_DATA_MODULE_PATH } from './page-data-source'
5
+
6
+ export const FORUM_REPLIES_ROUTE = '/api/plugins/forum/replies'
7
+
8
+ /** From `pages/api/plugins/forum/<route>.js` to the project root. */
9
+ export const FORUM_ROUTE_ROOT = '../../../..'
10
+ const DATA_MODULE_IMPORT = `${FORUM_ROUTE_ROOT}/${FORUM_PAGE_DATA_MODULE_PATH.join(
11
+ '/'
12
+ )}/${FORUM_PAGE_DATA_MODULE_NAME}`
13
+
14
+ export const UUID_PATTERN = '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$'
15
+
16
+ /**
17
+ * `pages/api/plugins/forum/replies.js`: "Load more" and the reply sort on a
18
+ * topic page (plan D15). `?topic=<id>&root=<reply id>&sort=best|new|old&after=<n>`
19
+ * answers the next page of the tree through the data module, as the viewer
20
+ * the session cookie names: the same visibility rules as the page itself,
21
+ * never `readAsVisitor` (the replies table is bound by no public page). A
22
+ * visitor may ask 120 times per 10 minutes, counted by the shared security
23
+ * runtime. A topic the viewer may not read answers 404, like its page.
24
+ * Only a request that carries no credentials at all (no cookie, no
25
+ * authorization) may be cached: a member's list right after their own reply
26
+ * must never come from a cache, even when their session could not be read.
27
+ * `replyCount` is the topic's count of published replies.
28
+ */
29
+ export const buildForumRepliesRouteSource = (
30
+ options: { withSessionRevocation?: boolean } = {}
31
+ ): string => `var forum = require(${toJsLiteral(DATA_MODULE_IMPORT)});
32
+ var security = require(${toJsLiteral(securityRuntimeSpecifier(FORUM_ROUTE_ROOT))});
33
+
34
+ ${SessionCookieResolver.generateCommonJsSessionTokenResolverCode(FORUM_ROUTE_ROOT, {
35
+ withRevocation: options.withSessionRevocation !== false,
36
+ })}
37
+
38
+ var UUID = new RegExp(${toJsLiteral(UUID_PATTERN)}, 'i');
39
+ var RATE_LIMIT = { scope: 'forum-replies', limit: 120, windowSeconds: 600 };
40
+
41
+ function carriesCredentials(req) {
42
+ var headers = (req && req.headers) || {};
43
+ return !!(headers.cookie || headers.authorization);
44
+ }
45
+
46
+ function one(value) {
47
+ return String(Array.isArray(value) ? value[0] : value == null ? '' : value).trim();
48
+ }
49
+
50
+ async function sessionOf(req) {
51
+ try {
52
+ return await __tqSessionToken(req);
53
+ } catch (error) {
54
+ return null;
55
+ }
56
+ }
57
+
58
+ export default async function handler(req, res) {
59
+ if (req.method !== 'GET') {
60
+ res.setHeader('Allow', 'GET');
61
+ return res.status(405).json({ success: false, error: 'Method not allowed' });
62
+ }
63
+ if (!(await security.rateLimitRequest(req, res, RATE_LIMIT))) {
64
+ return;
65
+ }
66
+ var topicId = one(req.query.topic);
67
+ var rootReplyId = one(req.query.root);
68
+ if (!UUID.test(topicId) || (rootReplyId && !UUID.test(rootReplyId))) {
69
+ return res.status(400).json({ success: false, error: 'This is not a topic.' });
70
+ }
71
+ var session = await sessionOf(req);
72
+ res.setHeader('Cache-Control', session || carriesCredentials(req) ? 'private, no-store' : 'public, s-maxage=30, stale-while-revalidate=300');
73
+ try {
74
+ var result = await forum.loadReplies({
75
+ topicId: topicId,
76
+ rootReplyId: rootReplyId || null,
77
+ sort: one(req.query.sort),
78
+ after: parseInt(one(req.query.after), 10) || 0,
79
+ session: session,
80
+ });
81
+ if (!result) {
82
+ return res.status(404).json({ success: false, error: 'This topic is no longer available.' });
83
+ }
84
+ return res.status(200).json({ success: true, replies: result.replies, hasMore: result.hasMore, nextOffset: result.nextOffset, replyCount: result.replyCount });
85
+ } catch (error) {
86
+ console.error('[forum] replies could not be read:', error && error.message);
87
+ res.setHeader('Cache-Control', 'no-store');
88
+ return res.status(500).json({ success: false, error: 'The replies could not be loaded.' });
89
+ }
90
+ }
91
+ `
@@ -0,0 +1,245 @@
1
+ import { toJsLiteral } from '../pwa/source-literals'
2
+ import { ForumConfig } from './settings'
3
+
4
+ export const FORUM_SITEMAP_PATH = '/sitemap-forum.xml'
5
+ export const FORUM_LLMS_PATH = '/llms-forum.txt'
6
+
7
+ /**
8
+ * The forum's search-engine side, as JavaScript the data module carries:
9
+ *
10
+ * - `topicNoIndex(topic, community)`: a pending or removed topic, one in a
11
+ * private community or one not yet approved in a restricted one is kept out
12
+ * of search engines (plan 8.3);
13
+ * - `topicJsonLd(topic, community, replies, url)`: `DiscussionForumPosting`,
14
+ * and `QAPage` when the community takes questions and an answer is accepted.
15
+ *
16
+ * The page writes the JSON-LD into its head (see `page-rewrite.ts`).
17
+ */
18
+ export const FORUM_SEO_RUNTIME = `// --- search engines --------------------------------------------------------
19
+ function topicNoIndex(topic, community) {
20
+ if (!topic || topic.status !== 'published') return true;
21
+ if (!community || community.status !== 'active') return true;
22
+ return community.visibility === 'private';
23
+ }
24
+
25
+ function personOf(row) {
26
+ return row && row.author_name ? { '@type': 'Person', name: row.author_name } : undefined;
27
+ }
28
+
29
+ function postingOf(row, url) {
30
+ return {
31
+ '@type': 'Comment',
32
+ text: row.body_text || '',
33
+ url: url,
34
+ author: personOf(row),
35
+ datePublished: row.created_at || undefined,
36
+ upvoteCount: typeof row.upvotes === 'number' ? row.upvotes : undefined,
37
+ };
38
+ }
39
+
40
+ function topicJsonLd(topic, community, replies, url) {
41
+ var answers = (replies || []).filter(function (reply) { return reply.is_accepted; });
42
+ var isQuestion = community && community.kind === 'questions' && answers.length > 0;
43
+ var posting = {
44
+ '@type': 'DiscussionForumPosting',
45
+ '@id': url,
46
+ url: url,
47
+ headline: topic.title,
48
+ text: topic.body_text || '',
49
+ author: personOf(topic),
50
+ datePublished: topic.created_at || undefined,
51
+ dateModified: topic.edited_at || topic.updated_at || undefined,
52
+ interactionStatistic: [
53
+ { '@type': 'InteractionCounter', interactionType: 'https://schema.org/CommentAction', userInteractionCount: topic.reply_count || 0 },
54
+ { '@type': 'InteractionCounter', interactionType: 'https://schema.org/LikeAction', userInteractionCount: topic.upvotes || 0 },
55
+ ],
56
+ comment: (replies || []).slice(0, 20).map(function (reply) { return postingOf(reply, url + '#reply-' + reply.id); }),
57
+ };
58
+ if (!isQuestion) {
59
+ posting['@context'] = 'https://schema.org';
60
+ return posting;
61
+ }
62
+ return {
63
+ '@context': 'https://schema.org',
64
+ '@type': 'QAPage',
65
+ mainEntity: {
66
+ '@type': 'Question',
67
+ name: topic.title,
68
+ text: topic.body_text || '',
69
+ author: personOf(topic),
70
+ dateCreated: topic.created_at || undefined,
71
+ answerCount: topic.reply_count || 0,
72
+ upvoteCount: topic.upvotes || 0,
73
+ acceptedAnswer: Object.assign(postingOf(answers[0], url + '#reply-' + answers[0].id), { '@type': 'Answer' }),
74
+ },
75
+ };
76
+ }
77
+ `
78
+
79
+ const SINGLE_LANGUAGE_ENTRIES_SOURCE = ` var base = origin(context.req)
80
+ var lines = ['<?xml version="1.0" encoding="UTF-8"?>', '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">']
81
+ var entry = function (path, at) {
82
+ lines.push(' <url>')
83
+ lines.push(' <loc>' + xmlText(base + path) + '</loc>')
84
+ if (at) lines.push(' <lastmod>' + xmlText(at) + '</lastmod>')
85
+ lines.push(' </url>')
86
+ }
87
+ `
88
+
89
+ /**
90
+ * A site in several languages: each page once per language (the default
91
+ * unprefixed, the others under `/<locale>`), each naming every language's
92
+ * address and the default one as `x-default` — as the editor's static
93
+ * sitemap and the content presets' live one write theirs.
94
+ */
95
+ const MULTILINGUAL_ENTRIES_SOURCE = ` var base = origin(context.req)
96
+ var main = context.defaultLocale || null
97
+ var locales = [main].concat((Array.isArray(context.locales) ? context.locales : []).filter(function (locale) {
98
+ return locale && locale !== main
99
+ }))
100
+ var lines = ['<?xml version="1.0" encoding="UTF-8"?>', '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xhtml="http://www.w3.org/1999/xhtml">']
101
+ var entry = function (path, at) {
102
+ var addresses = locales.map(function (locale) {
103
+ return { lang: locale, url: base + (locale && locale !== main ? '/' + locale : '') + path }
104
+ })
105
+ var alternates = addresses.length > 1 ? addresses.concat([{ lang: 'x-default', url: base + path }]) : []
106
+ addresses.forEach(function (address) {
107
+ lines.push(' <url>')
108
+ lines.push(' <loc>' + xmlText(address.url) + '</loc>')
109
+ if (at) lines.push(' <lastmod>' + xmlText(at) + '</lastmod>')
110
+ alternates.forEach(function (alternate) {
111
+ lines.push(' <xhtml:link rel="alternate" hreflang="' + xmlText(alternate.lang) + '" href="' + xmlText(alternate.url) + '" />')
112
+ })
113
+ lines.push(' </url>')
114
+ })
115
+ }
116
+ `
117
+
118
+ /** Source only a forum with communities gets: one without them names, links and lists none. */
119
+ const withCommunities = (config: ForumConfig, source: string): string =>
120
+ config.settings.structure === 'communities' ? source : ''
121
+
122
+ const communityBaseSource = (config: ForumConfig): string =>
123
+ withCommunities(
124
+ config,
125
+ `var COMMUNITY_BASE = ${toJsLiteral(config.routes.community?.staticBase ?? '/forum/c')}\n`
126
+ )
127
+
128
+ /**
129
+ * `pages/sitemap-forum.xml.js` and `pages/llms-forum.txt.js`: every public
130
+ * topic and every active community that is not private, read on request
131
+ * through the data module (`listPublicIndex`), as the content presets' live
132
+ * sitemap does (`blog/content-site-index.ts`). The forum's entries are kept
133
+ * in files of their own because the editor's `/llms.txt` page lists the
134
+ * presets' posts and is written by the blog plugin alone. A forum without
135
+ * communities lists its topics only.
136
+ */
137
+ export const buildForumSitemapPageSource = (
138
+ config: ForumConfig,
139
+ options: { multilingual?: boolean } = {}
140
+ ): string => {
141
+ const topicBase = config.routes.topic?.staticBase ?? '/forum/t'
142
+ const communityEntries = withCommunities(
143
+ config,
144
+ ` index.communities.forEach(function (row) { entry(COMMUNITY_BASE + '/' + encodeURIComponent(row.slug), row.updated_at) })\n`
145
+ )
146
+ return `import { listPublicIndex } from '../utils/forum-page-data'
147
+
148
+ var TOPIC_BASE = ${toJsLiteral(topicBase)}
149
+ ${communityBaseSource(config)}
150
+ function xmlText(value) {
151
+ return String(value == null ? '' : value)
152
+ .replace(/[^\\x09\\x0a\\x0d\\x20-\\uD7FF\\uE000-\\uFFFD]/g, '')
153
+ .replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;').replace(/'/g, '&apos;')
154
+ }
155
+
156
+ function origin(req) {
157
+ var host = String((req && req.headers && req.headers.host) || '')
158
+ if (!/^[a-z0-9.-]+(:\\d+)?$/i.test(host)) return ''
159
+ var proto = String(req.headers['x-forwarded-proto'] || '').split(',')[0].trim()
160
+ var local = /^(localhost|127\\.0\\.0\\.1)(:\\d+)?$/.test(host)
161
+ return (proto === 'http' || proto === 'https' ? proto : local ? 'http' : 'https') + '://' + host
162
+ }
163
+
164
+ // ${FORUM_SITEMAP_PATH}, read on request. Generated from the Forum plugin.
165
+ export async function getServerSideProps(context) {
166
+ var res = context.res
167
+ var index
168
+ try {
169
+ index = await listPublicIndex()
170
+ } catch (error) {
171
+ console.error('[forum] the sitemap could not be read: ' + (error && error.message ? error.message : String(error)))
172
+ res.statusCode = 503
173
+ res.setHeader('Retry-After', '300')
174
+ res.setHeader('Cache-Control', 'no-store')
175
+ res.end('This file is unavailable right now. Try again in a few minutes.')
176
+ return { props: {} }
177
+ }
178
+ ${
179
+ options.multilingual ? MULTILINGUAL_ENTRIES_SOURCE : SINGLE_LANGUAGE_ENTRIES_SOURCE
180
+ }${communityEntries} index.topics.forEach(function (row) { entry(TOPIC_BASE + '/' + encodeURIComponent(row.slug), row.updated_at) })
181
+ lines.push('</urlset>')
182
+ res.statusCode = 200
183
+ res.setHeader('Content-Type', 'application/xml; charset=utf-8')
184
+ res.setHeader('Cache-Control', 'public, s-maxage=600, stale-while-revalidate=3600')
185
+ res.end(lines.join('\\n'))
186
+ return { props: {} }
187
+ }
188
+
189
+ export default function ForumSitemap() {
190
+ return null
191
+ }
192
+ `
193
+ }
194
+
195
+ export const buildForumLlmsPageSource = (config: ForumConfig): string => {
196
+ const topicBase = config.routes.topic?.staticBase ?? '/forum/t'
197
+ const communityWords = withCommunities(config, 'communities and ')
198
+ const communityHeading = withCommunities(config, `, '', '## Communities', ''`)
199
+ const communityLinks = withCommunities(
200
+ config,
201
+ ` index.communities.forEach(function (row) {
202
+ lines.push('- [' + linkText(row.name) + '](' + base + COMMUNITY_BASE + '/' + encodeURIComponent(row.slug) + ')' + (row.description ? ': ' + linkText(row.description).slice(0, 200) : ''))
203
+ })
204
+ `
205
+ )
206
+ return `import { listPublicIndex } from '../utils/forum-page-data'
207
+
208
+ var TOPIC_BASE = ${toJsLiteral(topicBase)}
209
+ ${communityBaseSource(config)}
210
+ function linkText(value) {
211
+ return String(value == null ? '' : value).replace(/\\s+/g, ' ').replace(/[\\[\\]]/g, '\\\\$&').trim()
212
+ }
213
+
214
+ // ${FORUM_LLMS_PATH}: the forum's ${communityWords}public topics, for language models.
215
+ export async function getServerSideProps(context) {
216
+ var res = context.res
217
+ var index
218
+ try {
219
+ index = await listPublicIndex()
220
+ } catch (error) {
221
+ res.statusCode = 503
222
+ res.setHeader('Retry-After', '300')
223
+ res.setHeader('Cache-Control', 'no-store')
224
+ res.end('This file is unavailable right now. Try again in a few minutes.')
225
+ return { props: {} }
226
+ }
227
+ var host = String((context.req && context.req.headers && context.req.headers.host) || '')
228
+ var base = /^[a-z0-9.-]+(:\\d+)?$/i.test(host) ? 'https://' + host : ''
229
+ var lines = ['# Forum'${communityHeading}]
230
+ ${communityLinks} lines.push('', '## Topics', '')
231
+ index.topics.forEach(function (row) {
232
+ lines.push('- [' + linkText(row.title) + '](' + base + TOPIC_BASE + '/' + encodeURIComponent(row.slug) + ')' + (row.excerpt ? ': ' + linkText(row.excerpt) : ''))
233
+ })
234
+ res.statusCode = 200
235
+ res.setHeader('Content-Type', 'text/plain; charset=utf-8')
236
+ res.setHeader('Cache-Control', 'public, s-maxage=600, stale-while-revalidate=3600')
237
+ res.end(lines.join('\\n') + '\\n')
238
+ return { props: {} }
239
+ }
240
+
241
+ export default function ForumLlms() {
242
+ return null
243
+ }
244
+ `
245
+ }