1/**
2 * Copyright © 2022 650 Industries.
3 *
4 * This source code is licensed under the MIT license found in the
5 * LICENSE file in the root directory of this source tree.
6 */
7import assert from 'assert';
8import chalk from 'chalk';
9import fs from 'fs';
10import path from 'path';
11import prettyBytes from 'pretty-bytes';
12import { inspect } from 'util';
13
14import { getVirtualFaviconAssetsAsync } from './favicon';
15import { Log } from '../log';
16import { DevServerManager } from '../start/server/DevServerManager';
17import { MetroBundlerDevServer } from '../start/server/metro/MetroBundlerDevServer';
18import { logMetroErrorAsync } from '../start/server/metro/metroErrorInterface';
19import { learnMore } from '../utils/link';
20
21const debug = require('debug')('expo:export:generateStaticRoutes') as typeof console.log;
22
23type Options = { outputDir: string; minify: boolean };
24
25/** @private */
26export async function unstable_exportStaticAsync(projectRoot: string, options: Options) {
27  Log.warn(
28    `Experimental static rendering is enabled. ` +
29      learnMore('https://docs.expo.dev/router/reference/static-rendering/')
30  );
31
32  // TODO: Prevent starting the watcher.
33  const devServerManager = new DevServerManager(projectRoot, {
34    minify: options.minify,
35    mode: 'production',
36    location: {},
37  });
38  await devServerManager.startAsync([
39    {
40      type: 'metro',
41      options: {
42        location: {},
43        isExporting: true,
44      },
45    },
46  ]);
47
48  try {
49    await exportFromServerAsync(projectRoot, devServerManager, options);
50  } finally {
51    await devServerManager.stopAsync();
52  }
53}
54
55/** Match `(page)` -> `page` */
56function matchGroupName(name: string): string | undefined {
57  return name.match(/^\(([^/]+?)\)$/)?.[1];
58}
59
60export async function getFilesToExportFromServerAsync(
61  projectRoot: string,
62  {
63    manifest,
64    renderAsync,
65  }: {
66    manifest: any;
67    renderAsync: (pathname: string) => Promise<string>;
68  }
69): Promise<Map<string, string>> {
70  // name : contents
71  const files = new Map<string, string>();
72
73  await Promise.all(
74    getHtmlFiles({ manifest }).map(async (outputPath) => {
75      const pathname = outputPath.replace(/(?:index)?\.html$/, '');
76      try {
77        files.set(outputPath, '');
78        const data = await renderAsync(pathname);
79        files.set(outputPath, data);
80      } catch (e: any) {
81        await logMetroErrorAsync({ error: e, projectRoot });
82        throw new Error('Failed to statically export route: ' + pathname);
83      }
84    })
85  );
86
87  return files;
88}
89
90/** Perform all fs commits */
91export async function exportFromServerAsync(
92  projectRoot: string,
93  devServerManager: DevServerManager,
94  { outputDir, minify }: Options
95): Promise<void> {
96  const injectFaviconTag = await getVirtualFaviconAssetsAsync(projectRoot, outputDir);
97
98  const devServer = devServerManager.getDefaultDevServer();
99  assert(devServer instanceof MetroBundlerDevServer);
100
101  const [resources, { manifest, renderAsync }] = await Promise.all([
102    devServer.getStaticResourcesAsync({ mode: 'production', minify }),
103    devServer.getStaticRenderFunctionAsync({
104      mode: 'production',
105      minify,
106    }),
107  ]);
108
109  debug('Routes:\n', inspect(manifest, { colors: true, depth: null }));
110
111  const files = await getFilesToExportFromServerAsync(projectRoot, {
112    manifest,
113    async renderAsync(pathname: string) {
114      const template = await renderAsync(pathname);
115      let html = await devServer.composeResourcesWithHtml({
116        mode: 'production',
117        resources,
118        template,
119      });
120
121      if (injectFaviconTag) {
122        html = injectFaviconTag(html);
123      }
124
125      return html;
126    },
127  });
128
129  resources.forEach((resource) => {
130    files.set(resource.filename, resource.source);
131  });
132
133  fs.mkdirSync(path.join(outputDir), { recursive: true });
134
135  Log.log('');
136  Log.log(chalk.bold`Exporting ${files.size} files:`);
137  await Promise.all(
138    [...files.entries()]
139      .sort(([a], [b]) => a.localeCompare(b))
140      .map(async ([file, contents]) => {
141        const length = Buffer.byteLength(contents, 'utf8');
142        Log.log(file, chalk.gray`(${prettyBytes(length)})`);
143        const outputPath = path.join(outputDir, file);
144        await fs.promises.mkdir(path.dirname(outputPath), { recursive: true });
145        await fs.promises.writeFile(outputPath, contents);
146      })
147  );
148  Log.log('');
149}
150
151export function getHtmlFiles({ manifest }: { manifest: any }): string[] {
152  const htmlFiles = new Set<string>();
153
154  function traverseScreens(screens: string | { screens: any; path: string }, basePath = '') {
155    for (const value of Object.values(screens)) {
156      if (typeof value === 'string') {
157        let filePath = basePath + value;
158        if (value === '') {
159          filePath =
160            basePath === ''
161              ? 'index'
162              : basePath.endsWith('/')
163              ? basePath + 'index'
164              : basePath.slice(0, -1);
165        }
166        // TODO: Dedupe requests for alias routes.
167        addOptionalGroups(filePath);
168      } else if (typeof value === 'object' && value?.screens) {
169        const newPath = basePath + value.path + '/';
170        traverseScreens(value.screens, newPath);
171      }
172    }
173  }
174
175  function addOptionalGroups(path: string) {
176    const variations = getPathVariations(path);
177    for (const variation of variations) {
178      htmlFiles.add(variation);
179    }
180  }
181
182  traverseScreens(manifest.screens);
183
184  return Array.from(htmlFiles).map((value) => {
185    const parts = value.split('/');
186    // Replace `:foo` with `[foo]` and `*foo` with `[...foo]`
187    const partsWithGroups = parts.map((part) => {
188      if (part.startsWith(':')) {
189        return `[${part.slice(1)}]`;
190      } else if (part.startsWith('*')) {
191        return `[...${part.slice(1)}]`;
192      }
193      return part;
194    });
195    return partsWithGroups.join('/') + '.html';
196  });
197}
198
199// Given a route like `(foo)/bar/(baz)`, return all possible variations of the route.
200// e.g. `(foo)/bar/(baz)`, `(foo)/bar/baz`, `foo/bar/(baz)`, `foo/bar/baz`,
201export function getPathVariations(routePath: string): string[] {
202  const variations = new Set<string>([routePath]);
203  const segments = routePath.split('/');
204
205  function generateVariations(segments: string[], index: number): void {
206    if (index >= segments.length) {
207      return;
208    }
209
210    const newSegments = [...segments];
211    while (
212      index < newSegments.length &&
213      matchGroupName(newSegments[index]) &&
214      newSegments.length > 1
215    ) {
216      newSegments.splice(index, 1);
217      variations.add(newSegments.join('/'));
218      generateVariations(newSegments, index + 1);
219    }
220
221    generateVariations(segments, index + 1);
222  }
223
224  generateVariations(segments, 0);
225
226  return Array.from(variations);
227}
228