@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,82 @@
1
+ /* tslint:disable:function-constructor no-any */
2
+ import { SessionCookieResolver } from '@teleporthq/teleport-shared'
3
+ import { buildForumRepliesRouteSource, FORUM_ROUTE_ROOT } from '../src/forum/replies-route'
4
+
5
+ /**
6
+ * The replies route ("Load more", the reply sort, the list read again after a
7
+ * reply), run as the generated site runs it over a fake data module. A list
8
+ * read with any credential must never be cached: the reply a member just
9
+ * posted would otherwise come back missing from a browser or CDN copy.
10
+ */
11
+
12
+ const TOPIC_ID = 'aaaaaaaa-0000-4000-8000-000000000001'
13
+
14
+ function loadRoute() {
15
+ const forum = {
16
+ loadReplies: async () => ({
17
+ replies: [{ id: 'r-1' }],
18
+ hasMore: false,
19
+ nextOffset: 1,
20
+ replyCount: 7,
21
+ }),
22
+ }
23
+ const security = { rateLimitRequest: async () => true }
24
+ const resolver = SessionCookieResolver.generateCommonJsSessionTokenResolverCode(
25
+ FORUM_ROUTE_ROOT,
26
+ { withRevocation: false }
27
+ )
28
+ const source = buildForumRepliesRouteSource({ withSessionRevocation: false })
29
+ expect(source).toContain(resolver)
30
+ const body = source
31
+ .replace(resolver, 'async function __tqSessionToken(req) { return req.session; }')
32
+ .replace('export default async function handler', 'module.exports = async function handler')
33
+ const module = { exports: {} as any }
34
+ const fakeRequire = (name: string) => (name.includes('security') ? security : forum)
35
+ new Function('require', 'module', 'exports', body)(fakeRequire, module, module.exports)
36
+ return module.exports as (req: any, res: any) => Promise<void>
37
+ }
38
+
39
+ async function ask(headers: Record<string, string>, session: object | null = null) {
40
+ const answer = { status: 0, json: null as any, headers: {} as Record<string, string> }
41
+ const res = {
42
+ setHeader: (name: string, value: string) => {
43
+ answer.headers[name] = value
44
+ },
45
+ status(code: number) {
46
+ answer.status = code
47
+ return this
48
+ },
49
+ json(value: unknown) {
50
+ answer.json = value
51
+ return this
52
+ },
53
+ }
54
+ await loadRoute()(
55
+ { method: 'GET', query: { topic: TOPIC_ID, sort: 'best' }, headers, session },
56
+ res
57
+ )
58
+ return answer
59
+ }
60
+
61
+ describe('forum replies route', () => {
62
+ it('answers the topic’s count of published replies beside the list', async () => {
63
+ const answer = await ask({})
64
+ expect(answer.status).toBe(200)
65
+ expect(answer.json).toMatchObject({ success: true, replyCount: 7, hasMore: false })
66
+ })
67
+
68
+ it('lets a shared cache keep only a request that carries no credentials', async () => {
69
+ expect((await ask({})).headers['Cache-Control']).toContain('public')
70
+ })
71
+
72
+ it('never lets a request with a session, a cookie or an authorization be cached', async () => {
73
+ for (const [headers, session] of [
74
+ [{}, { id: 'user-1' }],
75
+ // A cookie whose session could not be read (expired, revoked, a slow check).
76
+ [{ cookie: 'next-auth.session-token=stale' }, null],
77
+ [{ authorization: 'Bearer x' }, null],
78
+ ] as Array<[Record<string, string>, object | null]>) {
79
+ expect((await ask(headers, session)).headers['Cache-Control']).toBe('private, no-store')
80
+ }
81
+ })
82
+ })
@@ -0,0 +1,124 @@
1
+ /* tslint:disable:no-any */
2
+ import { parse } from '@babel/parser'
3
+ import { GeneratedFolder } from '@teleporthq/teleport-types'
4
+ import uidlSample from '../../../examples/test-samples/project-sample.json'
5
+ import profileFixture from './__fixtures__/profile-page-uidl.json'
6
+ import { createNextProjectGenerator } from '../src'
7
+ import NextTemplate from '../src/project-template'
8
+
9
+ /**
10
+ * A forum without communities, through the whole generator: its New topic
11
+ * page is a static page behind a sign-in (`/forum/new`), which the generator
12
+ * writes at `pages/forum/new.js` — where the Forum plugin finds it and serves
13
+ * it per request, through the gate of the main community.
14
+ */
15
+
16
+ const template = JSON.parse(JSON.stringify(NextTemplate)) as GeneratedFolder
17
+ const fixture = profileFixture as any
18
+
19
+ const buildTopicsOnlyUidl = (): Record<string, unknown> => {
20
+ const uidl = JSON.parse(JSON.stringify(uidlSample)) as any
21
+ uidl.dataSources = { [fixture.dataSource.id]: fixture.dataSource }
22
+ uidl.authentication = {
23
+ ...fixture.authentication,
24
+ pageProtection: { composer: { route: '/forum/new', requiresAuth: true, allowedRoles: [] } },
25
+ }
26
+ uidl.plugins = {
27
+ forum: {
28
+ settings: { structure: 'topics' },
29
+ pages: { home: '/forum', topic: '/forum/t', 'new-topic': '/forum/new' },
30
+ },
31
+ }
32
+ uidl.root.stateDefinitions.route.values.push({
33
+ value: 'forum-new',
34
+ seo: { title: 'New topic' },
35
+ pageOptions: {
36
+ navLink: '/forum/new',
37
+ componentName: 'NewTopic',
38
+ stateDefinitions: {
39
+ viewer: { type: 'object', defaultValue: { signed_in: false, can_post: false } },
40
+ },
41
+ },
42
+ })
43
+ uidl.root.node.content.children.push({
44
+ type: 'conditional',
45
+ content: {
46
+ node: {
47
+ type: 'element',
48
+ content: {
49
+ elementType: 'container',
50
+ name: 'composer',
51
+ attrs: { 'data-tq-forum-page': { type: 'static', content: 'new-topic' } },
52
+ children: [{ type: 'static', content: 'New topic' }],
53
+ },
54
+ },
55
+ value: 'forum-new',
56
+ reference: { type: 'dynamic', content: { referenceType: 'state', id: 'route' } },
57
+ },
58
+ })
59
+ return uidl
60
+ }
61
+
62
+ /** Every generated file by its path (`pages/forum/new.js`). */
63
+ const filesOf = (folder: GeneratedFolder, prefix = ''): Record<string, string> =>
64
+ folder.subFolders.reduce(
65
+ (files, sub) => ({ ...files, ...filesOf(sub, `${prefix}${sub.name}/`) }),
66
+ Object.fromEntries(
67
+ folder.files.map((file) => [`${prefix}${file.name}.${file.fileType}`, String(file.content)])
68
+ )
69
+ )
70
+
71
+ describe('a forum without communities, generated', () => {
72
+ let files: Record<string, string>
73
+
74
+ beforeAll(async () => {
75
+ files = filesOf(
76
+ await createNextProjectGenerator().generateProject(buildTopicsOnlyUidl(), template)
77
+ )
78
+ }, 120000)
79
+
80
+ it('writes the static composer at pages/forum/new.js and serves it through the main community’s gate', () => {
81
+ const composer = files['pages/forum/new.js']
82
+ expect(composer).toBeDefined()
83
+ expect(() => parse(composer, { sourceType: 'module', plugins: ['jsx'] })).not.toThrow()
84
+ expect(composer).toContain('import __tqForumData from "../../utils/forum-page-data"')
85
+ expect(composer.match(/export async function getServerSideProps/g)).toHaveLength(1)
86
+ expect(composer).not.toContain('getStaticProps')
87
+
88
+ const body = composer.slice(composer.indexOf('export async function getServerSideProps'))
89
+ // The sign-in guard the page was generated with stays in front of the gate.
90
+ expect(body.indexOf('__tqPageAccess.guardPageAccess(context')).toBeGreaterThan(0)
91
+ expect(body.indexOf('__tqPageAccess.guardPageAccess(context')).toBeLessThan(
92
+ body.indexOf('loadCommunityGate')
93
+ )
94
+ expect(body).toContain('const slug = "main"')
95
+ expect(body).toMatch(/loadCommunityGate\(\{\s*slug,\s*session,\s*need: 'post'\s*\}\)/)
96
+ expect(body).toContain("res.setHeader('Cache-Control', 'private, no-store')")
97
+ expect(body).not.toContain('s-maxage')
98
+ expect(body).toContain('viewer: data.viewer')
99
+ expect(body).toMatch(/__tqForum: \{\s*seo: \{\s*noindex: true\s*\}\s*\}/)
100
+ expect(composer).toContain('useState(props.viewer !== undefined ? props.viewer : {')
101
+ expect(composer).toContain('<meta name="robots" content="noindex" />')
102
+ expect(composer).toContain('export default remountOnPageArrival(NewTopic)')
103
+ expect(files['utils/page-arrival.js']).toBeDefined()
104
+ expect(files['utils/auth/page-access.js']).toBeDefined()
105
+ })
106
+
107
+ it('emits the forum’s module and routes, and nothing of a community', () => {
108
+ const data = files['utils/forum-page-data.js']
109
+ expect(data).toContain('"structure":"topics"')
110
+ expect(files['pages/api/plugins/forum/replies.js']).toBeDefined()
111
+ expect(files['pages/api/plugins/forum/notifications.js']).toBeDefined()
112
+ for (const name of ['pages/sitemap-forum.xml.js', 'pages/llms-forum.txt.js']) {
113
+ expect(files[name]).toBeDefined()
114
+ expect(files[name]).not.toMatch(/communit/i)
115
+ }
116
+ const forumPages = Object.keys(files).filter((name) => name.startsWith('pages/forum/'))
117
+ expect(forumPages).toEqual(['pages/forum/new.js'])
118
+ // No file links a community's page.
119
+ const linking = Object.keys(files).filter((name) =>
120
+ /\/forum\/(c|manage|communities)\b/.test(files[name])
121
+ )
122
+ expect(linking).toEqual([])
123
+ })
124
+ })
@@ -0,0 +1,187 @@
1
+ import { NextProjectPlugini18nConfig } from '../src/internationalization/project'
2
+ import {
3
+ buildI18nRuntimeSource,
4
+ dayjsLocaleOf,
5
+ DAYJS_VERSION,
6
+ } from '../src/internationalization/app-i18n-runtime'
7
+ import { APP_SOURCE, baseUidl, buildStructure, fileContent } from './_helpers/pwa-fixtures'
8
+
9
+ /**
10
+ * A site with internationalization hands the page's language to everything
11
+ * below `_app`: dates (`DateTimePrimitive` formats with dayjs's global
12
+ * language) and workflow scripts (`window.__TQ_I18N__`), which run outside
13
+ * React and cannot reach the page's `translate`.
14
+ */
15
+
16
+ const i18n = (languages: Record<string, string> = { en: 'English', es: 'Spanish' }) => ({
17
+ main: { name: 'English', locale: 'en' },
18
+ languages,
19
+ translations: Object.keys(languages).reduce(
20
+ (all, code) => ({ ...all, [code]: {} }),
21
+ {} as Record<string, Record<string, never>>
22
+ ),
23
+ })
24
+
25
+ const run = async (extra: Record<string, unknown>) =>
26
+ new NextProjectPlugini18nConfig().runAfter(
27
+ buildStructure(baseUidl(extra), { withNextConfig: false })
28
+ )
29
+
30
+ const appOf = (structure: Awaited<ReturnType<typeof run>>) =>
31
+ fileContent(structure, '_app', '_app') as string
32
+
33
+ interface Page {
34
+ locale?: string
35
+ defaultLocale?: string
36
+ messages?: Record<string, string>
37
+ }
38
+
39
+ /**
40
+ * The emitted module run as one render after another in a single process, as
41
+ * the server renders every language: returns dayjs's language after each.
42
+ */
43
+ const renderPages = (source: string, pages: Page[], options: { browser: boolean }) => {
44
+ let dayjsLocale = 'en'
45
+ const dayjs = {
46
+ locale: (name: string) => {
47
+ dayjsLocale = name
48
+ return name
49
+ },
50
+ }
51
+ const imported: string[] = []
52
+ let router: Page = {}
53
+ const body = source
54
+ .replace(/^import \{ useRouter \} from 'next\/router'$/m, '')
55
+ .replace(/^import dayjs from 'dayjs'$/m, '')
56
+ .replace(/^import '(dayjs\/locale\/[^']+)'$/gm, (_line, name) => {
57
+ imported.push(name)
58
+ return ''
59
+ })
60
+ .replace('export function useTqI18n', 'function useTqI18n')
61
+ expect(body).not.toMatch(/^(import|export) /m)
62
+ const scope: { __TQ_I18N__?: unknown } = {}
63
+ const useTqI18n = new Function('useRouter', 'dayjs', 'window', `${body}\nreturn useTqI18n`)(
64
+ () => router,
65
+ dayjs,
66
+ options.browser ? scope : undefined
67
+ )
68
+ const seen = pages.map((page) => {
69
+ router = { locale: page.locale, defaultLocale: page.defaultLocale }
70
+ useTqI18n({ messages: page.messages })
71
+ return { dayjs: dayjsLocale, global: scope.__TQ_I18N__ }
72
+ })
73
+ return { seen, imported }
74
+ }
75
+
76
+ describe('the page language in _app', () => {
77
+ it('calls the hook first thing in _app, imports it, and pins the dayjs _app imports', async () => {
78
+ const structure = await run({ internationalization: i18n() })
79
+ const app = appOf(structure)
80
+
81
+ expect(app).toMatch(
82
+ /export default function MyApp\(\{ Component, pageProps \}\) \{\n {2}useTqI18n\(pageProps\)\n {2}return \(/
83
+ )
84
+ expect(app.indexOf("import { useTqI18n } from '../utils/tq-i18n'\n")).toBe(0)
85
+ expect(structure.files.get('tq-i18n-runtime')?.path).toEqual(['utils'])
86
+ expect(fileContent(structure, 'tq-i18n-runtime', 'tq-i18n')).toContain(
87
+ "import 'dayjs/locale/es'"
88
+ )
89
+ expect(structure.dependencies.dayjs).toBe(DAYJS_VERSION)
90
+ })
91
+
92
+ it('changes nothing for a project without internationalization', async () => {
93
+ const structure = await run({})
94
+
95
+ expect(appOf(structure)).toBe(APP_SOURCE)
96
+ expect(structure.files.has('tq-i18n-runtime')).toBe(false)
97
+ expect(structure.dependencies.dayjs).toBeUndefined()
98
+ })
99
+
100
+ it('adds the call once when the plugin runs again', async () => {
101
+ const structure = await run({ internationalization: i18n() })
102
+ await new NextProjectPlugini18nConfig().runAfter(structure)
103
+
104
+ expect(appOf(structure).match(/useTqI18n\(pageProps\)/g)).toHaveLength(1)
105
+ expect(appOf(structure).match(/import \{ useTqI18n \}/g)).toHaveLength(1)
106
+ })
107
+
108
+ it('keeps a dayjs version the project already pins', async () => {
109
+ const structure = buildStructure(baseUidl({ internationalization: i18n() }), {
110
+ withNextConfig: false,
111
+ })
112
+ structure.dependencies.dayjs = '1.11.10'
113
+ await new NextProjectPlugini18nConfig().runAfter(structure)
114
+
115
+ expect(structure.dependencies.dayjs).toBe('1.11.10')
116
+ })
117
+ })
118
+
119
+ describe('the date language', () => {
120
+ it.each([
121
+ ['es', 'es'],
122
+ ['pt-BR', 'pt-br'],
123
+ ['de-LI', 'de'],
124
+ ['no', 'nb'],
125
+ ['tl', 'tl-ph'],
126
+ ['en', 'en'],
127
+ ['zz', null],
128
+ ])('of %s is dayjs’s %s', (code, expected) => {
129
+ expect(dayjsLocaleOf(code)).toBe(expected)
130
+ })
131
+
132
+ it('imports the file of each language dayjs knows, English being built in', () => {
133
+ const source = buildI18nRuntimeSource(['en', 'es', 'pt-BR', 'zz'], 'en')
134
+
135
+ expect(source.match(/^import 'dayjs\/locale\/[^']+'$/gm)).toEqual([
136
+ "import 'dayjs/locale/es'",
137
+ "import 'dayjs/locale/pt-br'",
138
+ ])
139
+ expect(source).toContain('var DATE_LOCALES = {"en":"en","es":"es","pt-BR":"pt-br"}')
140
+ })
141
+
142
+ /**
143
+ * One server process renders every language. A render must never keep the
144
+ * language the one before it set — not even for a language dayjs has no
145
+ * file for, which reads in English.
146
+ */
147
+ it('sets every render’s own language, never the previous page’s', () => {
148
+ const source = buildI18nRuntimeSource(['en', 'es', 'zz'], 'en')
149
+ const { seen, imported } = renderPages(
150
+ source,
151
+ [
152
+ { locale: 'es', defaultLocale: 'en' },
153
+ { locale: 'en', defaultLocale: 'en' },
154
+ { locale: 'es', defaultLocale: 'en' },
155
+ { locale: 'zz', defaultLocale: 'en' },
156
+ {},
157
+ ],
158
+ { browser: false }
159
+ )
160
+
161
+ expect(imported).toEqual(['dayjs/locale/es'])
162
+ expect(seen.map((render) => render.dayjs)).toEqual(['es', 'en', 'es', 'en', 'en'])
163
+ // The server never writes a window global.
164
+ expect(seen.map((render) => render.global)).toEqual([
165
+ undefined,
166
+ undefined,
167
+ undefined,
168
+ undefined,
169
+ undefined,
170
+ ])
171
+ })
172
+
173
+ it('hands scripts the page’s language and words in the browser', () => {
174
+ const messages = { 'forum-word_title-needed': 'Ponle un título a tu tema.' }
175
+ const { seen } = renderPages(
176
+ buildI18nRuntimeSource(['en', 'es'], 'en'),
177
+ [
178
+ { locale: 'es', defaultLocale: 'en', messages },
179
+ { locale: 'en', defaultLocale: 'en' },
180
+ ],
181
+ { browser: true }
182
+ )
183
+
184
+ expect(seen[0].global).toEqual({ locale: 'es', defaultLocale: 'en', messages })
185
+ expect(seen[1].global).toEqual({ locale: 'en', defaultLocale: 'en', messages: undefined })
186
+ })
187
+ })
@@ -1,4 +1,6 @@
1
+ import * as crypto from 'crypto'
1
2
  import { InMemoryFileRecord, ProjectPluginStructure } from '@teleporthq/teleport-types'
3
+ import { PageRevalidate } from '@teleporthq/teleport-shared'
2
4
  import { NextPageRevalidatePlugin } from '../src/page-revalidate/project-plugin'
3
5
 
4
6
  const buildStructure = (options: {
@@ -6,10 +8,15 @@ const buildStructure = (options: {
6
8
  workflowNodes?: any[]
7
9
  // tslint:disable-next-line:no-any
8
10
  customNodeNodes?: any[]
11
+ // tslint:disable-next-line:no-any
12
+ internationalization?: any
9
13
  }): ProjectPluginStructure =>
10
14
  ({
11
15
  uidl: {
12
16
  name: 'Store',
17
+ ...(options.internationalization
18
+ ? { internationalization: options.internationalization }
19
+ : {}),
13
20
  globals: { settings: {}, meta: [], assets: [], env: {} },
14
21
  root: { name: 'App', node: { type: 'element', content: { elementType: 'container' } } },
15
22
  components: {},
@@ -121,4 +128,108 @@ describe('NextPageRevalidatePlugin', () => {
121
128
  expect(route).toContain('const MAX_PATHS = 20')
122
129
  expect(route).toContain('.slice(0, MAX_PATHS)')
123
130
  })
131
+
132
+ describe('on a site in several languages', () => {
133
+ const SECRET = 'a-real-secret'
134
+ const spanish = {
135
+ main: { name: 'English', locale: 'en' },
136
+ languages: { en: 'English', es: 'Spanish', fr: 'French' },
137
+ translations: { en: {}, es: {}, fr: {} },
138
+ }
139
+
140
+ /** The paths the route rebuilds for one request asking for `paths`. */
141
+ const rebuilds = async (route: string, paths: string[]) => {
142
+ const commonJs = route
143
+ .replace(/^import crypto from 'crypto'$/m, "const crypto = require('crypto')")
144
+ .replace('export default async function handler', 'module.exports = async function handler')
145
+ const module = { exports: null as any }
146
+ // tslint:disable-next-line:function-constructor
147
+ new Function('module', 'require', 'process', commonJs)(module, () => crypto, {
148
+ env: { TQ_CACHE_SECRET: SECRET },
149
+ })
150
+ const rebuilt: string[] = []
151
+ let sent: any = null
152
+ const res = {
153
+ status: () => res,
154
+ json: (body: unknown) => {
155
+ sent = body
156
+ return res
157
+ },
158
+ revalidate: async (path: string) => {
159
+ rebuilt.push(path)
160
+ if (path.endsWith('/gone')) {
161
+ throw new Error('never generated')
162
+ }
163
+ },
164
+ }
165
+ await module.exports(
166
+ { method: 'POST', headers: { 'x-tq-cache-secret': SECRET }, body: { paths } },
167
+ res
168
+ )
169
+ return { rebuilt, sent }
170
+ }
171
+
172
+ /**
173
+ * Next keeps a copy of a static page per language, and
174
+ * `res.revalidate('/forum')` rebuilds the default language's alone: the
175
+ * visitor on `/es/forum` kept the old copy until its own window ran out.
176
+ */
177
+ it('rebuilds every language’s copy of each path, the default one first', async () => {
178
+ const route = routeOf(
179
+ await run(
180
+ buildStructure({
181
+ workflowNodes: [{ type: 'page-revalidate' }],
182
+ internationalization: spanish,
183
+ })
184
+ )
185
+ )
186
+
187
+ const { rebuilt, sent } = await rebuilds(route, ['/forum', '/', 'forum/t/gone'])
188
+ expect(rebuilt).toEqual([
189
+ '/forum',
190
+ '/es/forum',
191
+ '/fr/forum',
192
+ '/',
193
+ '/es',
194
+ '/fr',
195
+ '/forum/t/gone',
196
+ '/es/forum/t/gone',
197
+ '/fr/forum/t/gone',
198
+ ])
199
+ expect(sent.failed).toEqual(['/forum/t/gone', '/es/forum/t/gone', '/fr/forum/t/gone'])
200
+ })
201
+
202
+ it('rebuilds a path that already names a language as it is, once', async () => {
203
+ const route = routeOf(
204
+ await run(
205
+ buildStructure({
206
+ workflowNodes: [{ type: 'page-revalidate' }],
207
+ internationalization: spanish,
208
+ })
209
+ )
210
+ )
211
+
212
+ const { rebuilt } = await rebuilds(route, ['/es/forum', '/en/forum', '/forum', '/es'])
213
+ expect(rebuilt).toEqual(['/es/forum', '/en/forum', '/forum', '/fr/forum', '/es'])
214
+ })
215
+
216
+ it('leaves the route of a site in one language as it always was', async () => {
217
+ const plain = routeOf(
218
+ await run(buildStructure({ workflowNodes: [{ type: 'page-revalidate' }] }))
219
+ )
220
+ const oneLanguage = routeOf(
221
+ await run(
222
+ buildStructure({
223
+ workflowNodes: [{ type: 'page-revalidate' }],
224
+ internationalization: { ...spanish, languages: { en: 'English' } },
225
+ })
226
+ )
227
+ )
228
+
229
+ expect(plain).toBe(PageRevalidate.generatePageRevalidateRoute())
230
+ expect(oneLanguage).toBe(plain)
231
+ expect(plain).not.toContain('LOCALES')
232
+ expect((await rebuilds(plain, ['/forum'])).rebuilt).toEqual(['/forum'])
233
+ })
234
+ })
124
235
  })
@@ -0,0 +1,25 @@
1
+ import { generateRichTextEditorComponentCode } from '../src/rich-text-editor/component-generator'
2
+
3
+ /*
4
+ A page gives the editor a box (`min-height: 220px` on the New topic page of
5
+ the forum, 200px on an admin form) and the editor stayed one line tall inside
6
+ it: Quill sizes its writing area to its content. The editor's own global
7
+ styles stretch the writing area over the box it was given.
8
+ */
9
+ describe('rich text editor — the writing area fills its box', () => {
10
+ it.each([
11
+ ['without embeds', {}],
12
+ ['with embeds', { withEmbeds: true }],
13
+ ])('ships the frame styles in the global style tag (%s)', (_label, options) => {
14
+ const source = generateRichTextEditorComponentCode(options)
15
+ const styles = /const RICH_TEXT_CONTENT_STYLES = ("(?:[^"\\]|\\.)*")/.exec(source)
16
+ expect(styles).not.toBeNull()
17
+ const css = JSON.parse((styles as RegExpExecArray)[1]) as string
18
+
19
+ // The box's own minimum travels to Quill's root, whose two parts then share it.
20
+ expect(css).toContain('.quill { display: flex; flex-direction: column; min-height: inherit; }')
21
+ expect(css).toContain('.quill > .ql-container { display: flex; flex: 1 1 auto;')
22
+ expect(css).toContain('.quill > .ql-container > .ql-editor { flex: 1 1 auto; }')
23
+ expect(source).toContain('<style jsx global>{RICH_TEXT_CONTENT_STYLES}</style>')
24
+ })
25
+ })
@@ -0,0 +1,26 @@
1
+ /** ⛔ PAIRED with `FORUM_FILES_ROUTE` in teleport-gui `features/forum/constants/forum-markers.ts`. */
2
+ export declare const FORUM_FILES_ROUTE = "/api/plugins/forum/files";
3
+ /**
4
+ * The runtime-storage folder the forum's composers upload pictures into.
5
+ * ⛔ PAIRED with `FORUM_UPLOAD_FOLDER` in teleport-gui
6
+ * `features/forum/constants/forum-markers.ts`.
7
+ */
8
+ export declare const FORUM_UPLOAD_FOLDER = "forum";
9
+ /**
10
+ * `pages/api/plugins/forum/files.js`: takes the pictures of deleted posts out
11
+ * of runtime storage. A delete's statement answers the file ids its posts
12
+ * showed and the page posts them here (`POST { files: [id] }`, same-origin
13
+ * JSON, a session required, 30 calls per 10 minutes per visitor).
14
+ *
15
+ * The ids are only a hint: a post's pictures are addresses its author wrote,
16
+ * so any public file of the project could be named. A file is removed only
17
+ * when BOTH hold — the storage worker lists it in the forum's upload folder
18
+ * (only the composers upload there), and no topic or reply still shows it
19
+ * (`filesStillShown`). Anything else is left alone, and the answer is the
20
+ * same either way (`{ success, deleted }`): the post is already gone, so a
21
+ * storage failure is logged, never shown.
22
+ */
23
+ export declare const buildForumFilesRouteSource: (options?: {
24
+ withSessionRevocation?: boolean;
25
+ }) => string;
26
+ //# sourceMappingURL=files-route.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"files-route.d.ts","sourceRoot":"","sources":["../../../src/forum/files-route.ts"],"names":[],"mappings":"AAOA,qGAAqG;AACrG,eAAO,MAAM,iBAAiB,6BAA6B,CAAA;AAE3D;;;;GAIG;AACH,eAAO,MAAM,mBAAmB,UAAU,CAAA;AAS1C;;;;;;;;;;;;;GAaG;AACH,eAAO,MAAM,0BAA0B,aAC5B;IAAE,qBAAqB,CAAC,EAAE,OAAO,CAAA;CAAE,KAC3C,MA4FF,CAAA"}
@@ -0,0 +1,42 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.buildForumFilesRouteSource = exports.FORUM_UPLOAD_FOLDER = exports.FORUM_FILES_ROUTE = void 0;
4
+ var teleport_shared_1 = require("@teleporthq/teleport-shared");
5
+ var teleport_plugin_next_workflows_1 = require("@teleporthq/teleport-plugin-next-workflows");
6
+ var source_literals_1 = require("../pwa/source-literals");
7
+ var page_data_source_1 = require("./page-data-source");
8
+ var notifications_route_1 = require("./notifications-route");
9
+ var replies_route_1 = require("./replies-route");
10
+ /** ⛔ PAIRED with `FORUM_FILES_ROUTE` in teleport-gui `features/forum/constants/forum-markers.ts`. */
11
+ exports.FORUM_FILES_ROUTE = '/api/plugins/forum/files';
12
+ /**
13
+ * The runtime-storage folder the forum's composers upload pictures into.
14
+ * ⛔ PAIRED with `FORUM_UPLOAD_FOLDER` in teleport-gui
15
+ * `features/forum/constants/forum-markers.ts`.
16
+ */
17
+ exports.FORUM_UPLOAD_FOLDER = 'forum';
18
+ /** The most file ids one call names (a topic and its replies, at four pictures each, rarely reach it). */
19
+ var MAX_FILES = 40;
20
+ var DATA_MODULE_IMPORT = "".concat(replies_route_1.FORUM_ROUTE_ROOT, "/").concat(page_data_source_1.FORUM_PAGE_DATA_MODULE_PATH.join('/'), "/").concat(page_data_source_1.FORUM_PAGE_DATA_MODULE_NAME);
21
+ /**
22
+ * `pages/api/plugins/forum/files.js`: takes the pictures of deleted posts out
23
+ * of runtime storage. A delete's statement answers the file ids its posts
24
+ * showed and the page posts them here (`POST { files: [id] }`, same-origin
25
+ * JSON, a session required, 30 calls per 10 minutes per visitor).
26
+ *
27
+ * The ids are only a hint: a post's pictures are addresses its author wrote,
28
+ * so any public file of the project could be named. A file is removed only
29
+ * when BOTH hold — the storage worker lists it in the forum's upload folder
30
+ * (only the composers upload there), and no topic or reply still shows it
31
+ * (`filesStillShown`). Anything else is left alone, and the answer is the
32
+ * same either way (`{ success, deleted }`): the post is already gone, so a
33
+ * storage failure is logged, never shown.
34
+ */
35
+ var buildForumFilesRouteSource = function (options) {
36
+ if (options === void 0) { options = {}; }
37
+ return "var forum = require(".concat((0, source_literals_1.toJsLiteral)(DATA_MODULE_IMPORT), ");\nvar security = require(").concat((0, source_literals_1.toJsLiteral)((0, teleport_plugin_next_workflows_1.securityRuntimeSpecifier)(replies_route_1.FORUM_ROUTE_ROOT)), ");\n\n").concat(teleport_shared_1.SessionCookieResolver.generateCommonJsSessionTokenResolverCode(replies_route_1.FORUM_ROUTE_ROOT, {
38
+ withRevocation: options.withSessionRevocation !== false,
39
+ }), "\n\nvar UUID = new RegExp(").concat((0, source_literals_1.toJsLiteral)(replies_route_1.UUID_PATTERN), ", 'i');\nvar RATE_LIMIT = { scope: 'forum-files', limit: 30, windowSeconds: 600 };\nvar FOLDER = ").concat((0, source_literals_1.toJsLiteral)(exports.FORUM_UPLOAD_FOLDER), ";\nvar MAX_FILES = ").concat(MAX_FILES, ";\nvar STORAGE_URL = process.env.RUNTIME_STORAGE_URL;\nvar STORAGE_KEY = process.env.RUNTIME_STORAGE_API_KEY;\nvar STORAGE_PROJECT = process.env.RUNTIME_STORAGE_PROJECT_ID;\n\n").concat(notifications_route_1.FORUM_SAME_ORIGIN_SOURCE, "\n\nfunction storage(path, method) {\n return fetch(STORAGE_URL + '/project/' + encodeURIComponent(STORAGE_PROJECT) + path, {\n method: method,\n headers: { Authorization: 'Bearer ' + STORAGE_KEY },\n });\n}\n\n// The named files the forum's composers uploaded: the ones storage lists in the forum's folder.\nasync function forumFilesAmong(ids) {\n var response = await storage(\n '/files?folder=' + encodeURIComponent(FOLDER) + '&limit=' + ids.length + '&ids=' + ids.map(encodeURIComponent).join(','),\n 'GET'\n );\n if (!response.ok) {\n throw new Error('storage answered ' + response.status);\n }\n var data = await response.json();\n var listed = Array.isArray(data && data.files) ? data.files : [];\n return listed\n .map(function (file) { return String((file && file.id) || ''); })\n .filter(function (id) { return ids.indexOf(id) !== -1; });\n}\n\nexport default async function handler(req, res) {\n res.setHeader('Cache-Control', 'private, no-store');\n if (req.method !== 'POST') {\n res.setHeader('Allow', 'POST');\n return res.status(405).json({ success: false, error: 'Method not allowed' });\n }\n if (!(await security.rateLimitRequest(req, res, RATE_LIMIT))) {\n return;\n }\n if (!isSameOrigin(req)) {\n return res.status(403).json({ success: false, error: 'Forbidden' });\n }\n var session = null;\n try {\n session = await __tqSessionToken(req);\n } catch (error) {\n session = null;\n }\n if (!session || !(session.id || session.sub)) {\n return res.status(401).json({ success: false, error: 'Sign in first.' });\n }\n var body = req.body && typeof req.body === 'object' ? req.body : {};\n var ids = [];\n (Array.isArray(body.files) ? body.files : []).forEach(function (value) {\n var id = String(value == null ? '' : value).trim().toLowerCase();\n if (UUID.test(id) && ids.indexOf(id) === -1 && ids.length < MAX_FILES) {\n ids.push(id);\n }\n });\n if (ids.length === 0 || !STORAGE_URL || !STORAGE_KEY || !STORAGE_PROJECT) {\n return res.status(200).json({ success: true, deleted: 0 });\n }\n var deleted = 0;\n try {\n var forumIds = await forumFilesAmong(ids);\n var shown = forumIds.length > 0 ? await forum.filesStillShown(forumIds) : [];\n var unused = forumIds.filter(function (id) { return shown.indexOf(id) === -1; });\n for (var i = 0; i < unused.length; i++) {\n try {\n var answer = await storage('/files/' + encodeURIComponent(unused[i]), 'DELETE');\n if (answer.ok || answer.status === 404) {\n deleted += 1;\n }\n } catch (error) {\n console.error('[forum] a picture could not be removed:', error && error.message);\n }\n }\n } catch (error) {\n console.error('[forum] pictures could not be checked:', error && error.message);\n }\n return res.status(200).json({ success: true, deleted: deleted });\n}\n");
40
+ };
41
+ exports.buildForumFilesRouteSource = buildForumFilesRouteSource;
42
+ //# sourceMappingURL=files-route.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"files-route.js","sourceRoot":"","sources":["../../../src/forum/files-route.ts"],"names":[],"mappings":";;;AAAA,+DAAmE;AACnE,6FAAqF;AACrF,0DAAoD;AACpD,uDAA6F;AAC7F,6DAAgE;AAChE,iDAAgE;AAEhE,qGAAqG;AACxF,QAAA,iBAAiB,GAAG,0BAA0B,CAAA;AAE3D;;;;GAIG;AACU,QAAA,mBAAmB,GAAG,OAAO,CAAA;AAE1C,0GAA0G;AAC1G,IAAM,SAAS,GAAG,EAAE,CAAA;AAEpB,IAAM,kBAAkB,GAAG,UAAG,gCAAgB,cAAI,8CAA2B,CAAC,IAAI,CAChF,GAAG,CACJ,cAAI,8CAA2B,CAAE,CAAA;AAElC;;;;;;;;;;;;;GAaG;AACI,IAAM,0BAA0B,GAAG,UACxC,OAAiD;IAAjD,wBAAA,EAAA,YAAiD;IACtC,OAAA,8BAAuB,IAAA,6BAAW,EAAC,kBAAkB,CAAC,wCAC1C,IAAA,6BAAW,EAAC,IAAA,yDAAwB,EAAC,gCAAgB,CAAC,CAAC,mBAE9E,uCAAqB,CAAC,wCAAwC,CAAC,gCAAgB,EAAE;QACjF,cAAc,EAAE,OAAO,CAAC,qBAAqB,KAAK,KAAK;KACxD,CAAC,uCAEsB,IAAA,6BAAW,EAAC,4BAAY,CAAC,8GAElC,IAAA,6BAAW,EAAC,2BAAmB,CAAC,gCAC7B,SAAS,6LAKzB,8CAAwB,u1FA6EzB;AA5FY,CA4FZ,CAAA;AA9FY,QAAA,0BAA0B,8BA8FtC"}
@@ -0,0 +1,17 @@
1
+ export declare const FORUM_MARKDOWN_MODULE_PATH: string[];
2
+ export declare const FORUM_MARKDOWN_MODULE_NAME = "forum-markdown";
3
+ /**
4
+ * `utils/forum-markdown.js`: the allow-list renderer every piece of member
5
+ * content goes through (plan 7.5). The whole text is HTML-escaped FIRST, then
6
+ * the Markdown subset is recognised on the escaped text, so no character a
7
+ * member typed ever reaches the page as markup: raw HTML renders as the text
8
+ * it is. Links are http(s) only and open in a new tab with
9
+ * `rel="nofollow ugc noopener"`; images only from `https://` or the project's
10
+ * own upload base; `@handle` is emphasised text in v1 (no profile link: the
11
+ * handle alone does not name the user id). Pure, CommonJS, no dependency —
12
+ * the data module and the composer preview require the same file.
13
+ */
14
+ export declare const buildForumMarkdownSource: (options?: {
15
+ storageBase?: string | null;
16
+ }) => string;
17
+ //# sourceMappingURL=markdown-source.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"markdown-source.d.ts","sourceRoot":"","sources":["../../../src/forum/markdown-source.ts"],"names":[],"mappings":"AAEA,eAAO,MAAM,0BAA0B,UAAY,CAAA;AACnD,eAAO,MAAM,0BAA0B,mBAAmB,CAAA;AAE1D;;;;;;;;;;GAUG;AACH,eAAO,MAAM,wBAAwB,aAAa;IAAE,WAAW,CAAC,EAAE,MAAM,GAAG,IAAI,CAAA;CAAE,KAAQ,MAgKxF,CAAA"}