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

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 (41) hide show
  1. package/__tests__/_helpers/data-exposure-fixture.ts +114 -44
  2. package/__tests__/component-bound-state.test.ts +817 -0
  3. package/__tests__/nav-active-links-locale.test.ts +279 -0
  4. package/__tests__/page-transition-end2end.test.ts +3 -3
  5. package/__tests__/page-transition-language-switch.test.ts +273 -0
  6. package/__tests__/security-runtime-require-paths.test.ts +29 -1
  7. package/dist/cjs/index.d.ts.map +1 -1
  8. package/dist/cjs/index.js +2 -0
  9. package/dist/cjs/index.js.map +1 -1
  10. package/dist/cjs/nav-active-link/nav-active-link-component.d.ts +1 -1
  11. package/dist/cjs/nav-active-link/nav-active-link-component.d.ts.map +1 -1
  12. package/dist/cjs/nav-active-link/nav-active-link-component.js +12 -4
  13. package/dist/cjs/nav-active-link/nav-active-link-component.js.map +1 -1
  14. package/dist/cjs/page-transition/page-transition-component.d.ts.map +1 -1
  15. package/dist/cjs/page-transition/page-transition-component.js +1 -1
  16. package/dist/cjs/page-transition/page-transition-component.js.map +1 -1
  17. package/dist/cjs/state-data-source-plugin.d.ts +27 -0
  18. package/dist/cjs/state-data-source-plugin.d.ts.map +1 -1
  19. package/dist/cjs/state-data-source-plugin.js +278 -4
  20. package/dist/cjs/state-data-source-plugin.js.map +1 -1
  21. package/dist/cjs/tsconfig.tsbuildinfo +1 -1
  22. package/dist/esm/index.d.ts.map +1 -1
  23. package/dist/esm/index.js +3 -1
  24. package/dist/esm/index.js.map +1 -1
  25. package/dist/esm/nav-active-link/nav-active-link-component.d.ts +1 -1
  26. package/dist/esm/nav-active-link/nav-active-link-component.d.ts.map +1 -1
  27. package/dist/esm/nav-active-link/nav-active-link-component.js +12 -4
  28. package/dist/esm/nav-active-link/nav-active-link-component.js.map +1 -1
  29. package/dist/esm/page-transition/page-transition-component.d.ts.map +1 -1
  30. package/dist/esm/page-transition/page-transition-component.js +1 -1
  31. package/dist/esm/page-transition/page-transition-component.js.map +1 -1
  32. package/dist/esm/state-data-source-plugin.d.ts +27 -0
  33. package/dist/esm/state-data-source-plugin.d.ts.map +1 -1
  34. package/dist/esm/state-data-source-plugin.js +278 -5
  35. package/dist/esm/state-data-source-plugin.js.map +1 -1
  36. package/dist/esm/tsconfig.tsbuildinfo +1 -1
  37. package/package.json +21 -21
  38. package/src/index.ts +6 -1
  39. package/src/nav-active-link/nav-active-link-component.ts +68 -5
  40. package/src/page-transition/page-transition-component.ts +19 -5
  41. package/src/state-data-source-plugin.ts +433 -9
@@ -0,0 +1,817 @@
1
+ /* tslint:disable:function-constructor no-any */
2
+ import generator from '@babel/generator'
3
+ import * as types from '@babel/types'
4
+ import { GeneratedFolder } from '@teleporthq/teleport-types'
5
+ import { generateSafeFileName } from '@teleporthq/teleport-plugin-next-data-source'
6
+ import {
7
+ ADMIN_TABLE,
8
+ COMPONENT_STATE_FOLDER,
9
+ DATA_SOURCE_ID,
10
+ SUBSCRIPTION_PRODUCT,
11
+ bootComponentStateRoute,
12
+ bootReadRoute,
13
+ buildDataExposureUidl,
14
+ componentStateRoutesOf,
15
+ fileText,
16
+ } from './_helpers/data-exposure-fixture'
17
+ import { createNextProjectGenerator } from '../src'
18
+ import NextTemplate from '../src/project-template'
19
+ import { createComponentStateDataSourcePlugin } from '../src/state-data-source-plugin'
20
+
21
+ // A state bound to a data source belongs to a page or to a COMPONENT. A page's
22
+ // is handed to it by its own server-side fetch. A component's was declared as
23
+ // `useState(props.<state> !== undefined ? props.<state> : <default>)` and then
24
+ // never given a value: no page fetched it and no instance passed it, so a list
25
+ // over it stayed empty on the generated site while the editor showed its rows.
26
+ // The component now reads for itself: a table through the table's read route,
27
+ // a statement of its own through a route that holds the statement.
28
+ //
29
+ // The components are named as a project names them — by a dash-case key the
30
+ // generator turns into a class name (`studio-showcase` → `StudioShowcase`).
31
+
32
+ const PUBLIC_TABLE = 'studio_pieces'
33
+ const STAFF_ONLY_TABLE = 'staff_board'
34
+ const CATALOGUE_TABLE = 'teleport_products'
35
+
36
+ const BEST_SELLERS = `SELECT * FROM ${PUBLIC_TABLE} ORDER BY name LIMIT 3`
37
+ const FEATURED = `SELECT * FROM ${PUBLIC_TABLE} WHERE status = 'featured'`
38
+ const CATALOGUE = `SELECT id, name FROM ${CATALOGUE_TABLE} ORDER BY name`
39
+ const ORDERS = `SELECT id, name FROM ${ADMIN_TABLE}`
40
+ const MINE = `SELECT * FROM ${PUBLIC_TABLE} WHERE user_id = '{{Current User.id}}'`
41
+ const AGENDA = `SELECT * FROM ${STAFF_ONLY_TABLE} ORDER BY name`
42
+
43
+ const routeOf = (table: string): string => generateSafeFileName('teleport', table, DATA_SOURCE_ID)
44
+
45
+ const boundState = (
46
+ type: string,
47
+ defaultValue: unknown,
48
+ refPath: Array<string | number>,
49
+ extra: Record<string, unknown> = {}
50
+ ) => ({
51
+ type,
52
+ defaultValue,
53
+ dataSourceBinding: { dataSourceId: DATA_SOURCE_ID, refPath },
54
+ ...extra,
55
+ })
56
+
57
+ const component = (name: string, stateDefinitions: Record<string, unknown>) => ({
58
+ name,
59
+ stateDefinitions,
60
+ node: {
61
+ type: 'element',
62
+ content: { elementType: 'container', children: [{ type: 'static', content: name }] },
63
+ },
64
+ })
65
+
66
+ const instanceOf = (name: string) => ({
67
+ type: 'element',
68
+ content: { elementType: 'component', semanticType: name, dependency: { type: 'local' } },
69
+ })
70
+
71
+ const statementState = (statement: string, table = PUBLIC_TABLE) =>
72
+ boundState('array', [], [table], { query: statement })
73
+
74
+ const buildUidl = () => {
75
+ const uidl = buildDataExposureUidl() as any
76
+ const tables = uidl.dataSources[DATA_SOURCE_ID].config.selectedTables
77
+ ;[PUBLIC_TABLE, STAFF_ONLY_TABLE].forEach((table) => {
78
+ tables[table] = {
79
+ name: table,
80
+ columns: ['id', 'name', 'status'].map((name) => ({ name, type: 'text' })),
81
+ }
82
+ })
83
+
84
+ const components: Record<string, Record<string, unknown>> = {
85
+ 'studio-showcase': {
86
+ pieces: boundState('array', [], [PUBLIC_TABLE]),
87
+ firstPiece: boundState('object', {}, [PUBLIC_TABLE, 0]),
88
+ bestSellers: statementState(BEST_SELLERS),
89
+ featured: boundState('object', {}, [PUBLIC_TABLE, 0], { query: FEATURED }),
90
+ catalogue: statementState(CATALOGUE, CATALOGUE_TABLE),
91
+ orders: statementState(ORDERS),
92
+ mine: statementState(MINE),
93
+ },
94
+ 'staff-board': {
95
+ notes: boundState('array', [], [STAFF_ONLY_TABLE]),
96
+ agenda: statementState(AGENDA, STAFF_ONLY_TABLE),
97
+ },
98
+ 'team-badge': { rows: statementState(BEST_SELLERS) },
99
+ 'lesson-list': { rows: statementState(BEST_SELLERS) },
100
+ 'mixed-panel': { rows: statementState(BEST_SELLERS) },
101
+ 'order-totals': {
102
+ rows: statementState(ORDERS),
103
+ catalogue: statementState(CATALOGUE, CATALOGUE_TABLE),
104
+ },
105
+ 'spare-part': { rows: statementState(BEST_SELLERS) },
106
+ }
107
+ Object.keys(components).forEach((name) => {
108
+ uidl.components[name] = component(name, components[name])
109
+ })
110
+
111
+ const place = (page: string, name: string) =>
112
+ uidl.root.node.content.children
113
+ .find((child: any) => child.content.value === page)
114
+ .content.node.content.children.push(instanceOf(name))
115
+ // Every visitor may open the about page.
116
+ place('about', 'studio-showcase')
117
+ // The staff role only.
118
+ place('staff', 'staff-board')
119
+ // Any signed-in visitor, and the staff.
120
+ place('account', 'team-badge')
121
+ place('staff', 'team-badge')
122
+ // Subscribers only.
123
+ place('lessons', 'lesson-list')
124
+ // The staff, or a subscriber.
125
+ place('staff', 'mixed-panel')
126
+ place('lessons', 'mixed-panel')
127
+ // The admin panel only.
128
+ place('admin/orders', 'order-totals')
129
+ // `spare-part` is on no page.
130
+
131
+ return uidl
132
+ }
133
+
134
+ const generate = async (): Promise<GeneratedFolder> => {
135
+ const template = JSON.parse(JSON.stringify(NextTemplate)) as GeneratedFolder
136
+ return createNextProjectGenerator().generateProject(buildUidl(), template)
137
+ }
138
+
139
+ /** The route `componentFile`'s component reads `statement` from. */
140
+ const statementRouteOf = (
141
+ project: GeneratedFolder,
142
+ componentFile: string,
143
+ statement: string
144
+ ): string => {
145
+ const found = componentStateRoutesOf(project).filter(
146
+ (name) =>
147
+ name.indexOf(`${componentFile}-`) === 0 &&
148
+ (fileText(project, COMPONENT_STATE_FOLDER, name) || '').includes(
149
+ `var STATEMENT = ${JSON.stringify(statement)}`
150
+ )
151
+ )
152
+ if (found.length !== 1) {
153
+ throw new Error(`${found.length} routes for ${componentFile}: ${statement}`)
154
+ }
155
+ return found[0]
156
+ }
157
+
158
+ /** The effects of `source` that fill a state from a read route, as written. */
159
+ const stateEffectsOf = (source: string): Array<{ body: string; deps: string }> => {
160
+ const effects: Array<{ body: string; deps: string }> = []
161
+ const pattern = /useEffect\(\(\) => \{\n(\s+let __active = true[\s\S]*?)\n\s+\}, \[([^\]]*)\]\)/g
162
+ let match = pattern.exec(source)
163
+ while (match) {
164
+ effects.push({ body: match[1], deps: match[2] })
165
+ match = pattern.exec(source)
166
+ }
167
+ return effects
168
+ }
169
+
170
+ interface EffectRun {
171
+ requests: string[]
172
+ values: Record<string, unknown[]>
173
+ errors: unknown[][]
174
+ cleanup: () => void
175
+ settle: () => Promise<void>
176
+ }
177
+
178
+ /** Runs one generated effect against a read route that answers `reply`. */
179
+ const runEffect = (
180
+ body: string,
181
+ setters: string[],
182
+ reply: unknown,
183
+ router?: { locale?: string }
184
+ ): EffectRun => {
185
+ const requests: string[] = []
186
+ const errors: unknown[][] = []
187
+ const values: Record<string, unknown[]> = {}
188
+ setters.forEach((name) => (values[name] = []))
189
+ const fetchStub = (url: string) => {
190
+ requests.push(String(url))
191
+ return reply instanceof Error
192
+ ? Promise.reject(reply)
193
+ : Promise.resolve({ json: () => Promise.resolve(reply) })
194
+ }
195
+ const cleanup = new Function('fetch', 'console', 'router', ...setters, body)(
196
+ fetchStub,
197
+ { error: (...args: unknown[]) => errors.push(args) },
198
+ router,
199
+ ...setters.map((name) => (value: unknown) => values[name].push(value))
200
+ ) as () => void
201
+ const settle = async () => {
202
+ for (let turn = 0; turn < 6; turn++) {
203
+ await Promise.resolve()
204
+ }
205
+ }
206
+ return { requests, values, errors, cleanup, settle }
207
+ }
208
+
209
+ describe('a component state bound to a table, on the generated site', () => {
210
+ let project: GeneratedFolder
211
+ let showcase: string
212
+ let warnings: string[]
213
+
214
+ beforeAll(async () => {
215
+ const warn = jest.spyOn(console, 'warn').mockImplementation(() => undefined)
216
+ project = await generate()
217
+ warnings = warn.mock.calls.map((call) => String(call[0]))
218
+ warn.mockRestore()
219
+ showcase = fileText(project, ['components'], 'studio-showcase') || ''
220
+ }, 120000)
221
+
222
+ /** The effect of the showcase that reads its table. */
223
+ const tableEffect = () =>
224
+ stateEffectsOf(showcase).filter((effect) => effect.body.includes('__query'))
225
+
226
+ it('is read by the component itself, once, for every state of the same table', () => {
227
+ const effects = tableEffect()
228
+
229
+ expect(effects).toHaveLength(1)
230
+ expect(effects[0].body).toContain('fetch(`/api/' + routeOf(PUBLIC_TABLE) + '?$' + '{__query}`)')
231
+ expect(effects[0].deps).toBe('')
232
+ expect(showcase).toMatch(/import React, \{[^}]*\buseEffect\b[^}]*\} from 'react'/)
233
+ // Still takes a value a parent hands it.
234
+ expect(showcase).toContain('props.pieces !== undefined ? props.pieces : []')
235
+ })
236
+
237
+ it('fills the list and the single row from what the route answers', async () => {
238
+ const rows = [
239
+ { id: 'p1', name: 'Blue necklace' },
240
+ { id: 'p2', name: 'Green necklace' },
241
+ ]
242
+ const run = runEffect(tableEffect()[0].body, ['setPieces', 'setFirstPiece'], {
243
+ success: true,
244
+ data: rows,
245
+ })
246
+ await run.settle()
247
+
248
+ expect(run.requests).toEqual([`/api/${routeOf(PUBLIC_TABLE)}?`])
249
+ expect(run.values.setPieces).toEqual([rows])
250
+ expect(run.values.setFirstPiece).toEqual([rows[0]])
251
+ expect(run.errors).toEqual([])
252
+ })
253
+
254
+ it('keeps the states as they are when the route refuses, fails or answers late', async () => {
255
+ const body = tableEffect()[0].body
256
+ const setters = ['setPieces', 'setFirstPiece']
257
+
258
+ const refused = runEffect(body, setters, { success: false, error: 'Unauthenticated' })
259
+ await refused.settle()
260
+ expect(refused.values).toEqual({ setPieces: [], setFirstPiece: [] })
261
+
262
+ const failed = runEffect(body, setters, new Error('offline'))
263
+ await failed.settle()
264
+ expect(failed.values).toEqual({ setPieces: [], setFirstPiece: [] })
265
+ expect(failed.errors).toHaveLength(1)
266
+ expect(failed.errors[0][0]).toBe('Error fetching component state (pieces, firstPiece):')
267
+
268
+ const unmounted = runEffect(body, setters, { success: true, data: [{ id: 'p1' }] })
269
+ unmounted.cleanup()
270
+ await unmounted.settle()
271
+ expect(unmounted.values).toEqual({ setPieces: [], setFirstPiece: [] })
272
+ })
273
+
274
+ it('never puts anything but a list into a list, or a missing row into an object', async () => {
275
+ const run = runEffect(tableEffect()[0].body, ['setPieces', 'setFirstPiece'], {
276
+ success: true,
277
+ data: { unexpected: true },
278
+ })
279
+ await run.settle()
280
+
281
+ expect(run.values.setPieces).toEqual([[]])
282
+ expect(run.values.setFirstPiece).toEqual([{}])
283
+ })
284
+
285
+ // THE DEFECT: with the component named as a project names it, the table it
286
+ // alone reads was taken for one no page binds, and every visitor was refused.
287
+ it('THE DEFECT: reads through a route every visitor may call when a page every visitor opens shows it', async () => {
288
+ const reply = await bootReadRoute(project, routeOf(PUBLIC_TABLE))({})
289
+
290
+ expect(reply.status).toBe(200)
291
+ expect(reply.body.success).toBe(true)
292
+ expect(reply.body.data).toHaveLength(1)
293
+ expect(reply.body.data[0]).not.toHaveProperty('password')
294
+ })
295
+
296
+ it('reads through a route only the page’s sessions may call when only a protected page shows it', async () => {
297
+ const staffBoard = fileText(project, ['components'], 'staff-board') || ''
298
+ expect(
299
+ stateEffectsOf(staffBoard).filter((effect) => effect.body.includes('__query'))
300
+ ).toHaveLength(1)
301
+
302
+ const route = bootReadRoute(project, routeOf(STAFF_ONLY_TABLE))
303
+ expect((await route({})).status).toBe(401)
304
+ expect((await route({ session: { role: 'user' } })).status).toBe(403)
305
+ expect((await route({ session: { role: 'staff' } })).status).toBe(200)
306
+ })
307
+
308
+ it('leaves the page that shows the component as it was: no fetch of its own for it', () => {
309
+ const about = fileText(project, ['pages'], 'about') || ''
310
+
311
+ expect(about).toContain('<StudioShowcase>')
312
+ expect(about).not.toContain('pieces')
313
+ })
314
+
315
+ it('leaves a statement that names the signed-in visitor to a workflow, and says so', () => {
316
+ expect(showcase).not.toContain('setMine(')
317
+ expect(
318
+ JSON.stringify(
319
+ componentStateRoutesOf(project).map((name) =>
320
+ fileText(project, COMPONENT_STATE_FOLDER, name)
321
+ )
322
+ )
323
+ ).not.toContain('Current User')
324
+ expect(
325
+ warnings.filter((warning) => /Component "studio-showcase": "mine" is filled/.test(warning))
326
+ ).toHaveLength(1)
327
+ })
328
+ })
329
+
330
+ describe('a component state filled by an SQL statement, on the generated site', () => {
331
+ let project: GeneratedFolder
332
+ let showcase: string
333
+
334
+ beforeAll(async () => {
335
+ const warn = jest.spyOn(console, 'warn').mockImplementation(() => undefined)
336
+ project = await generate()
337
+ warn.mockRestore()
338
+ showcase = fileText(project, ['components'], 'studio-showcase') || ''
339
+ }, 120000)
340
+
341
+ const boot = (componentFile: string, statement: string, rows?: any[]) =>
342
+ bootComponentStateRoute(project, statementRouteOf(project, componentFile, statement), rows)
343
+
344
+ /** The effect of `source` that reads `route`. */
345
+ const effectReading = (source: string, route: string) =>
346
+ stateEffectsOf(source).filter((effect) =>
347
+ effect.body.includes(`fetch('/api/component-state/${route}')`)
348
+ )
349
+
350
+ it('is read by the component itself, from a route of its own that the request hands nothing', async () => {
351
+ const route = statementRouteOf(project, 'studio-showcase', BEST_SELLERS)
352
+ const effects = effectReading(showcase, route)
353
+
354
+ expect(effects).toHaveLength(1)
355
+ expect(effects[0].deps).toBe('')
356
+ expect(effects[0].body).not.toContain('__query')
357
+ // The statement is the server's: none of it is in the component.
358
+ expect(showcase).not.toContain('ORDER BY name LIMIT 3')
359
+
360
+ const rows = [{ id: 'p1', name: 'Blue necklace' }]
361
+ const run = runEffect(effects[0].body, ['setBestSellers'], { success: true, data: rows })
362
+ await run.settle()
363
+ expect(run.requests).toEqual([`/api/component-state/${route}`])
364
+ expect(run.values.setBestSellers).toEqual([rows])
365
+ })
366
+
367
+ it('fills a single row from the first row the statement answers', async () => {
368
+ const route = statementRouteOf(project, 'studio-showcase', FEATURED)
369
+ const [effect] = effectReading(showcase, route)
370
+
371
+ const found = runEffect(effect.body, ['setFeatured'], {
372
+ success: true,
373
+ data: [{ id: 'p7', name: 'Gold ring' }],
374
+ })
375
+ await found.settle()
376
+ expect(found.values.setFeatured).toEqual([{ id: 'p7', name: 'Gold ring' }])
377
+
378
+ const none = runEffect(effect.body, ['setFeatured'], { success: true, data: [] })
379
+ await none.settle()
380
+ expect(none.values.setFeatured).toEqual([{}])
381
+
382
+ const refused = runEffect(effect.body, ['setFeatured'], { success: false, error: 'Forbidden' })
383
+ await refused.settle()
384
+ expect(refused.values.setFeatured).toEqual([])
385
+ })
386
+
387
+ it('answers every visitor when a page every visitor may open shows the component', async () => {
388
+ const reply = await boot('studio-showcase', BEST_SELLERS)({})
389
+
390
+ expect(reply.status).toBe(200)
391
+ expect(reply.body.success).toBe(true)
392
+ expect(reply.queries).toEqual([BEST_SELLERS])
393
+ expect(reply.body.data).toHaveLength(1)
394
+ expect(reply.body.data[0]).toMatchObject({ id: 'r1', name: 'Row' })
395
+ expect(reply.body.data[0]).not.toHaveProperty('password')
396
+ })
397
+
398
+ it('runs its own statement whatever the request names', async () => {
399
+ const reply = await boot(
400
+ 'studio-showcase',
401
+ BEST_SELLERS
402
+ )({
403
+ query: {
404
+ rawQuery: `SELECT * FROM ${ADMIN_TABLE}`,
405
+ query: `SELECT * FROM ${ADMIN_TABLE}`,
406
+ tableName: ADMIN_TABLE,
407
+ filters: JSON.stringify([{ field: 'status', operator: 'equals', value: 'x' }]),
408
+ limit: '100000',
409
+ },
410
+ })
411
+
412
+ expect(reply.status).toBe(200)
413
+ expect(reply.queries).toEqual([BEST_SELLERS])
414
+ })
415
+
416
+ it('hands a browser no more rows than a read route does', async () => {
417
+ const many = Array.from({ length: 600 }, (_, index) => ({ id: `r${index}`, name: 'Row' }))
418
+ const reply = await boot('studio-showcase', BEST_SELLERS, many)({})
419
+
420
+ expect(reply.body.data).toHaveLength(500)
421
+ })
422
+
423
+ it('answers only the sessions of the protected page that shows the component', async () => {
424
+ const route = boot('staff-board', AGENDA)
425
+
426
+ const anonymous = await route({})
427
+ expect(anonymous.status).toBe(401)
428
+ expect(anonymous.body).toMatchObject({ success: false, error: 'Unauthenticated' })
429
+ expect(anonymous.queries).toEqual([])
430
+
431
+ const member = await route({ session: { role: 'member' } })
432
+ expect(member.status).toBe(403)
433
+ expect(member.queries).toEqual([])
434
+
435
+ const staff = await route({ session: { role: 'staff' } })
436
+ expect(staff.status).toBe(200)
437
+ expect(staff.queries).toEqual([AGENDA])
438
+ })
439
+
440
+ it('answers whoever one of its pages admits, when several show the component', async () => {
441
+ const route = boot('team-badge', BEST_SELLERS)
442
+
443
+ expect((await route({})).status).toBe(401)
444
+ expect((await route({ session: { role: 'member' } })).status).toBe(200)
445
+ expect((await route({ session: { role: 'staff' } })).status).toBe(200)
446
+ })
447
+
448
+ it('asks a subscriber-only page’s visitors for the subscription the page asks for', async () => {
449
+ const route = boot('lesson-list', BEST_SELLERS)
450
+
451
+ expect((await route({})).status).toBe(401)
452
+ expect((await route({ session: { role: 'member' } })).status).toBe(403)
453
+ const subscriber = await route({ session: { role: 'member' }, entitled: true })
454
+ expect(subscriber.status).toBe(200)
455
+ expect(subscriber.params[0]).toEqual(
456
+ expect.arrayContaining([expect.arrayContaining([SUBSCRIPTION_PRODUCT])])
457
+ )
458
+ })
459
+
460
+ it('admits by either page when one asks for a role and the other for a subscription', async () => {
461
+ const route = boot('mixed-panel', BEST_SELLERS)
462
+
463
+ expect((await route({ session: { role: 'staff' } })).status).toBe(200)
464
+ expect((await route({ session: { role: 'member' }, entitled: true })).status).toBe(200)
465
+ expect((await route({ session: { role: 'member' } })).status).toBe(403)
466
+ expect((await route({})).status).toBe(401)
467
+ })
468
+
469
+ it('answers no browser for a component no page shows', async () => {
470
+ const route = boot('spare-part', BEST_SELLERS)
471
+
472
+ expect((await route({})).status).toBe(401)
473
+ for (const role of ['member', 'staff', 'admin']) {
474
+ const reply = await route({ session: { role } })
475
+ expect([role, reply.status, reply.queries]).toEqual([role, 403, []])
476
+ }
477
+ })
478
+
479
+ it('serves what a page that shows the component would: the rows a visitor is served', async () => {
480
+ const reply = await boot('studio-showcase', CATALOGUE)({})
481
+
482
+ expect(reply.status).toBe(200)
483
+ expect(reply.queries).toHaveLength(1)
484
+ // The catalogue read for a visitor: the statement runs over the rows the
485
+ // storefront publishes, not over the table.
486
+ expect(reply.queries[0]).toMatch(
487
+ new RegExp(
488
+ `^WITH "${CATALOGUE_TABLE}" AS \\(SELECT .* FROM "${CATALOGUE_TABLE}" AS __brp_rows WHERE \\(`
489
+ )
490
+ )
491
+ expect(reply.queries[0].endsWith(CATALOGUE)).toBe(true)
492
+ })
493
+
494
+ it('serves a visitor nothing of a table a visitor may not read', async () => {
495
+ const reply = await boot('studio-showcase', ORDERS)({})
496
+
497
+ expect(reply.status).toBe(500)
498
+ expect(reply.body.success).toBe(false)
499
+ expect(reply.body.error).toBe('Failed to fetch data')
500
+ expect(reply.body).not.toHaveProperty('data')
501
+ expect(reply.queries).toEqual([])
502
+ })
503
+
504
+ it('reads as the store for a component only the admin panel shows — and only for its readers', async () => {
505
+ const orders = boot('order-totals', ORDERS)
506
+
507
+ expect((await orders({})).status).toBe(401)
508
+ expect((await orders({ session: { role: 'staff' } })).status).toBe(403)
509
+ const admin = await orders({ session: { role: 'admin' } })
510
+ expect(admin.status).toBe(200)
511
+ expect(admin.queries).toEqual([ORDERS])
512
+ expect(admin.body.data).toHaveLength(1)
513
+
514
+ // The whole catalogue, drafts included: what the admin page itself reads.
515
+ const catalogue = await boot('order-totals', CATALOGUE)({ session: { role: 'admin' } })
516
+ expect(catalogue.queries).toEqual([CATALOGUE])
517
+ })
518
+
519
+ it('keeps one route per component and statement, each beside the data-source module it runs through', () => {
520
+ const routes = componentStateRoutesOf(project)
521
+
522
+ expect(routes.filter((name) => name.indexOf('studio-showcase-') === 0)).toHaveLength(4)
523
+ expect(routes.filter((name) => name.indexOf('order-totals-') === 0)).toHaveLength(2)
524
+ for (const name of routes) {
525
+ const source = fileText(project, COMPONENT_STATE_FOLDER, name) || ''
526
+ const imported =
527
+ /import dataSourceModule from '\.\.\/\.\.\/\.\.\/utils\/data-sources\/([^']+)'/.exec(source)
528
+ expect([
529
+ name,
530
+ !!imported && fileText(project, ['utils', 'data-sources'], imported[1]) !== null,
531
+ ]).toEqual([name, true])
532
+ }
533
+ })
534
+ })
535
+
536
+ describe('the component state plugin', () => {
537
+ const CSV_ID = 'csv-0001'
538
+ const I18N = {
539
+ main: { name: 'English', locale: 'en' },
540
+ languages: { en: 'English', es: 'Spanish' },
541
+ }
542
+
543
+ const run = async (
544
+ stateDefinitions: Record<string, unknown>,
545
+ options: Record<string, unknown> = {}
546
+ ) => {
547
+ const structure = {
548
+ uidl: {
549
+ name: 'Showcase',
550
+ stateDefinitions,
551
+ node: { type: 'element', content: { elementType: 'container' } },
552
+ },
553
+ chunks: [
554
+ {
555
+ type: 'AST',
556
+ fileType: 'js',
557
+ name: 'jsx-component',
558
+ linkAfter: [] as string[],
559
+ content: types.variableDeclaration('const', [
560
+ types.variableDeclarator(
561
+ types.identifier('Showcase'),
562
+ types.arrowFunctionExpression(
563
+ [types.identifier('props')],
564
+ types.blockStatement([types.returnStatement(types.nullLiteral())])
565
+ )
566
+ ),
567
+ ]),
568
+ },
569
+ ] as any[],
570
+ dependencies: {} as Record<string, any>,
571
+ options: {
572
+ dataSources: {
573
+ [DATA_SOURCE_ID]: { id: DATA_SOURCE_ID, type: 'teleport', config: {} },
574
+ [CSV_ID]: {
575
+ id: CSV_ID,
576
+ type: 'csv-file',
577
+ config: { columns: [{ id: 'col_1', label: 'Name' }], parsedData: [{ col_1: 'Ada' }] },
578
+ },
579
+ },
580
+ // The route is there already, so the test does not depend on its generation.
581
+ extractedResources: {
582
+ [`api/${routeOf(PUBLIC_TABLE)}`]: { fileName: routeOf(PUBLIC_TABLE), content: '// stub' },
583
+ [`api/${generateSafeFileName('csv-file', 'data', CSV_ID)}`]: {
584
+ fileName: generateSafeFileName('csv-file', 'data', CSV_ID),
585
+ content: '// stub',
586
+ },
587
+ } as Record<string, any>,
588
+ ...options,
589
+ },
590
+ }
591
+ await createComponentStateDataSourcePlugin()(structure as any)
592
+ const code = generator(structure.chunks[0].content as types.Node).code
593
+ return { code, flat: code.replace(/\s+/g, ' '), structure }
594
+ }
595
+
596
+ it('asks the route for the rows in the state’s own order and filter', async () => {
597
+ const sortConfig = [{ field: 'name', direction: 'asc' }]
598
+ const filterConfig = [
599
+ { field: 'status', operator: 'equals', value: 'active' },
600
+ { field: 'name', operator: 'equals', value: 'x', isDynamic: true },
601
+ ]
602
+ const { flat } = await run({
603
+ pieces: boundState('array', [], [PUBLIC_TABLE], { sortConfig, filterConfig }),
604
+ })
605
+
606
+ expect(flat).toContain(
607
+ `new URLSearchParams({ sorts: ${JSON.stringify(
608
+ JSON.stringify(sortConfig)
609
+ )}, filters: ${JSON.stringify(JSON.stringify([filterConfig[0]]))} })`
610
+ )
611
+ })
612
+
613
+ it('reads states of one table with different orders separately', async () => {
614
+ const { code } = await run({
615
+ newest: boundState('array', [], [PUBLIC_TABLE], {
616
+ sortConfig: [{ field: 'name', direction: 'desc' }],
617
+ }),
618
+ all: boundState('array', [], [PUBLIC_TABLE]),
619
+ })
620
+
621
+ expect(stateEffectsOf(code.replace(/^/gm, ' '))).toHaveLength(2)
622
+ })
623
+
624
+ it('asks in the visitor’s language in a project with languages, and again when it changes', async () => {
625
+ const localized = await run(
626
+ { pieces: boundState('array', [], [PUBLIC_TABLE]) },
627
+ { internationalization: I18N }
628
+ )
629
+
630
+ expect(localized.flat).toContain('const router = useRouter();')
631
+ expect(localized.flat).toContain(
632
+ 'if (router?.locale) { __query.set("locale", router?.locale); }'
633
+ )
634
+ expect(localized.flat).toContain('}, [router?.locale]);')
635
+ expect(localized.structure.dependencies.useRouter).toMatchObject({ path: 'next/router' })
636
+
637
+ const single = await run({ pieces: boundState('array', [], [PUBLIC_TABLE]) })
638
+ expect(single.flat).not.toContain('router')
639
+ expect(single.flat).toContain('}, []);')
640
+ })
641
+
642
+ it('keys a CSV file’s rows by column label, as the editor showed them', async () => {
643
+ const { code } = await run({
644
+ people: {
645
+ type: 'array',
646
+ defaultValue: [],
647
+ dataSourceBinding: { dataSourceId: CSV_ID, refPath: ['data'] },
648
+ },
649
+ })
650
+ const [effect] = stateEffectsOf(code.replace(/^/gm, ' '))
651
+ const result = runEffect(effect.body, ['setPeople'], {
652
+ success: true,
653
+ data: [{ col_1: 'Ada' }],
654
+ })
655
+ await result.settle()
656
+
657
+ expect(result.values.setPeople).toEqual([[{ Name: 'Ada' }]])
658
+ })
659
+
660
+ it('runs the state’s mapping function over what it read', async () => {
661
+ const { code } = await run({
662
+ names: boundState('array', [], [PUBLIC_TABLE], {
663
+ mappingFunction: 'function mapData(items) { return items.map((item) => item.name) }',
664
+ }),
665
+ })
666
+ const [effect] = stateEffectsOf(code.replace(/^/gm, ' '))
667
+ const result = runEffect(effect.body, ['setNames'], {
668
+ success: true,
669
+ data: [{ name: 'Ada' }, { name: 'Grace' }],
670
+ })
671
+ await result.settle()
672
+
673
+ expect(result.values.setNames).toEqual([['Ada', 'Grace']])
674
+ })
675
+
676
+ describe('for a state filled by an SQL statement', () => {
677
+ const STATEMENT = `SELECT * FROM ${PUBLIC_TABLE} ORDER BY name LIMIT 3`
678
+ const routesIn = (structure: { options: { extractedResources?: Record<string, any> } }) =>
679
+ Object.keys(structure.options.extractedResources || {}).filter(
680
+ (key) => key.indexOf('pages/api/component-state/') === 0
681
+ )
682
+
683
+ it('writes the route beside the table’s module and fetches it with nothing in the request', async () => {
684
+ const { flat, structure } = await run({
685
+ bestSellers: boundState('array', [], [PUBLIC_TABLE], { query: STATEMENT }),
686
+ })
687
+ const [key] = routesIn(structure)
688
+ const route = structure.options.extractedResources[key]
689
+
690
+ expect(routesIn(structure)).toHaveLength(1)
691
+ expect(route.path).toEqual(['pages', 'api', 'component-state'])
692
+ expect(key).toBe(`pages/api/component-state/${route.fileName}`)
693
+ expect(route.fileName.indexOf(`showcase-${PUBLIC_TABLE}-`)).toBe(0)
694
+ expect(route.content).toContain(`var STATEMENT = ${JSON.stringify(STATEMENT)}`)
695
+ expect(route.content).toContain(
696
+ `import dataSourceModule from '../../../utils/data-sources/${routeOf(PUBLIC_TABLE)}'`
697
+ )
698
+ expect(structure.options.extractedResources[`utils/${routeOf(PUBLIC_TABLE)}`]).toMatchObject({
699
+ path: ['utils', 'data-sources'],
700
+ })
701
+ expect(flat).toContain(`fetch("/api/component-state/${route.fileName}")`)
702
+ expect(flat).not.toContain('URLSearchParams')
703
+ expect(flat).not.toContain('SELECT')
704
+ })
705
+
706
+ it('answers no browser when nothing decided who may open the component’s pages', async () => {
707
+ const { structure } = await run({
708
+ bestSellers: boundState('array', [], [PUBLIC_TABLE], { query: STATEMENT }),
709
+ })
710
+ const route = structure.options.extractedResources[routesIn(structure)[0]]
711
+
712
+ expect(route.content).toContain('var COMPONENT_PAGES = []')
713
+ expect(route.content).toContain('var READS_AS_STORE = false')
714
+ })
715
+
716
+ it('takes who may read from the pages that render the component', async () => {
717
+ const { structure } = await run(
718
+ { bestSellers: boundState('array', [], [PUBLIC_TABLE], { query: STATEMENT }) },
719
+ {
720
+ dataExposure: {
721
+ tables: {},
722
+ dataSources: {},
723
+ components: {
724
+ Showcase: {
725
+ public: false,
726
+ pages: [{ allowedRoles: ['staff'] }],
727
+ readsAsStore: false,
728
+ },
729
+ },
730
+ },
731
+ }
732
+ )
733
+ const route = structure.options.extractedResources[routesIn(structure)[0]]
734
+
735
+ expect(route.content).toContain(
736
+ 'var COMPONENT_PAGES = [{"allowedRoles":["staff"],"requiresSubscription":false,"subscriptionProductIds":[]}]'
737
+ )
738
+ })
739
+
740
+ it('reads a table state and a statement state each from its own route', async () => {
741
+ const { code, flat } = await run({
742
+ pieces: boundState('array', [], [PUBLIC_TABLE]),
743
+ bestSellers: boundState('array', [], [PUBLIC_TABLE], { query: STATEMENT }),
744
+ })
745
+
746
+ expect(stateEffectsOf(code.replace(/^/gm, ' '))).toHaveLength(2)
747
+ expect(flat).toContain('setPieces(')
748
+ expect(flat).toContain('setBestSellers(')
749
+ })
750
+
751
+ it('reads two states of one statement once, and two statements separately', async () => {
752
+ const same = await run({
753
+ bestSellers: boundState('array', [], [PUBLIC_TABLE], { query: STATEMENT }),
754
+ best: boundState('object', {}, [PUBLIC_TABLE, 0], { query: STATEMENT }),
755
+ })
756
+ expect(routesIn(same.structure)).toHaveLength(1)
757
+ expect(stateEffectsOf(same.code.replace(/^/gm, ' '))).toHaveLength(1)
758
+
759
+ const different = await run({
760
+ bestSellers: boundState('array', [], [PUBLIC_TABLE], { query: STATEMENT }),
761
+ newest: boundState('array', [], [PUBLIC_TABLE], {
762
+ query: `SELECT * FROM ${PUBLIC_TABLE} ORDER BY id DESC`,
763
+ }),
764
+ })
765
+ expect(routesIn(different.structure)).toHaveLength(2)
766
+ })
767
+
768
+ it('asks once and in no language, in a project with languages too', async () => {
769
+ const { flat, structure } = await run(
770
+ { bestSellers: boundState('array', [], [PUBLIC_TABLE], { query: STATEMENT }) },
771
+ { internationalization: I18N }
772
+ )
773
+
774
+ expect(flat).toContain('}, []);')
775
+ expect(flat).not.toContain('router')
776
+ expect(structure.dependencies.useRouter).toBeUndefined()
777
+ })
778
+
779
+ it('leaves to a workflow what the generated site cannot run for a component, and says which', async () => {
780
+ const warn = jest.spyOn(console, 'warn').mockImplementation(() => undefined)
781
+ const { flat, structure } = await run({
782
+ mine: boundState('array', [], [PUBLIC_TABLE], {
783
+ query: `SELECT * FROM ${PUBLIC_TABLE} WHERE user_id = '{{Current User.id}}'`,
784
+ }),
785
+ dropped: boundState('array', [], [PUBLIC_TABLE], { query: `DROP TABLE ${PUBLIC_TABLE}` }),
786
+ people: {
787
+ type: 'array',
788
+ defaultValue: [],
789
+ dataSourceBinding: { dataSourceId: CSV_ID, refPath: ['data'] },
790
+ query: 'SELECT * FROM data',
791
+ },
792
+ })
793
+ const said = warn.mock.calls.map((call) => String(call[0]))
794
+ warn.mockRestore()
795
+
796
+ expect(flat).toBe('const Showcase = props => { return null; };')
797
+ expect(routesIn(structure)).toEqual([])
798
+ const ours = said.filter((line) => /Component "Showcase":/.test(line))
799
+ expect(ours).toHaveLength(1)
800
+ for (const name of ['"mine"', '"dropped"', '"people"']) {
801
+ expect(ours[0]).toContain(name)
802
+ }
803
+ })
804
+ })
805
+
806
+ it('changes nothing in a component with no bound state, or with no route to read', async () => {
807
+ const plain = await run({ open: { type: 'boolean', defaultValue: false } })
808
+ expect(plain.flat).toBe('const Showcase = props => { return null; };')
809
+ expect(plain.structure.dependencies).toEqual({})
810
+
811
+ const noRoute = await run(
812
+ { pieces: boundState('array', [], [PUBLIC_TABLE]) },
813
+ { extractedResources: undefined }
814
+ )
815
+ expect(noRoute.flat).toBe('const Showcase = props => { return null; };')
816
+ })
817
+ })