@@ -19,6 +19,7 @@ import {
1919 getDataOrNull ,
2020 throwIfDataError ,
2121} from '@v2/lib/data' ;
22+ import assertNever from 'assert-never' ;
2223import { notFound } from 'next/navigation' ;
2324import { assert } from 'ts-essentials' ;
2425import { GITBOOK_URL } from './env' ;
@@ -242,19 +243,45 @@ export async function fetchSiteContextByIds(
242243 ? parseSiteSectionsAndGroups ( siteStructure , ids . siteSection )
243244 : null ;
244245
245- const siteSpace = (
246- siteStructure . type === 'siteSpaces' && siteStructure . structure
247- ? siteStructure . structure
248- : sections ?. current . siteSpaces
249- ) ?. find ( ( siteSpace ) => siteSpace . id === ids . siteSpace ) ;
250- if ( ! siteSpace ) {
251- throw new Error ( 'Site space not found' ) ;
252- }
246+ // Parse the current siteSpace and siteSpaces based on the site structure type.
247+ const { siteSpaces, siteSpace } : { siteSpaces : SiteSpace [ ] ; siteSpace : SiteSpace } = ( ( ) => {
248+ if ( siteStructure . type === 'siteSpaces' ) {
249+ const siteSpaces = siteStructure . structure ;
250+ const siteSpace = siteSpaces . find ( ( siteSpace ) => siteSpace . id === ids . siteSpace ) ;
251+
252+ if ( ! siteSpace ) {
253+ throw new Error (
254+ `Site space "${ ids . siteSpace } " not found in structure type="siteSpaces"`
255+ ) ;
256+ }
257+
258+ return { siteSpaces, siteSpace } ;
259+ }
260+
261+ if ( siteStructure . type === 'sections' ) {
262+ assert (
263+ sections ,
264+ `cannot find site space "${ ids . siteSpace } " because parsed sections are missing siteStructure.type="sections" siteSection="${ ids . siteSection } "`
265+ ) ;
253266
254- const siteSpaces =
255- siteStructure . type === 'siteSpaces'
256- ? siteStructure . structure
257- : ( sections ?. current . siteSpaces ?? [ ] ) ;
267+ const currentSection = sections . current ;
268+ const siteSpaces = currentSection . siteSpaces ;
269+ const siteSpace = currentSection . siteSpaces . find (
270+ ( siteSpace ) => siteSpace . id === ids . siteSpace
271+ ) ;
272+
273+ if ( ! siteSpace ) {
274+ throw new Error (
275+ `Site space "${ ids . siteSpace } " not found in structure type="sections" currentSection="${ currentSection . id } "`
276+ ) ;
277+ }
278+
279+ return { siteSpaces, siteSpace } ;
280+ }
281+
282+ // @ts -expect-error
283+ assertNever ( siteStructure , `cannot handle site structure of type ${ siteStructure . type } ` ) ;
284+ } ) ( ) ;
258285
259286 const customization = ( ( ) => {
260287 if ( ids . siteSpace ) {
0 commit comments