1*6d6b81f9SEvan Baconimport { parsePlatformHeader } from './resolvePlatform';
2*6d6b81f9SEvan Baconimport { ServerNext, ServerRequest, ServerResponse } from './server.types';
3*6d6b81f9SEvan Bacon
4*6d6b81f9SEvan Bacon/**
5*6d6b81f9SEvan Bacon * Create a web-only middleware which redirects to the index middleware without losing the path component.
6*6d6b81f9SEvan Bacon * This is useful for things like React Navigation which need to render the index.html and then direct the user in-memory.
7*6d6b81f9SEvan Bacon */
8*6d6b81f9SEvan Baconexport class HistoryFallbackMiddleware {
9*6d6b81f9SEvan Bacon  constructor(
10*6d6b81f9SEvan Bacon    private indexMiddleware: (
11*6d6b81f9SEvan Bacon      req: ServerRequest,
12*6d6b81f9SEvan Bacon      res: ServerResponse,
13*6d6b81f9SEvan Bacon      next: ServerNext
14*6d6b81f9SEvan Bacon    ) => Promise<void>
15*6d6b81f9SEvan Bacon  ) {}
16*6d6b81f9SEvan Bacon  getHandler() {
17*6d6b81f9SEvan Bacon    return (req: ServerRequest, res: ServerResponse, next: any) => {
18*6d6b81f9SEvan Bacon      const platform = parsePlatformHeader(req);
19*6d6b81f9SEvan Bacon
20*6d6b81f9SEvan Bacon      if (!platform || platform === 'web') {
21*6d6b81f9SEvan Bacon        // Redirect unknown to the manifest handler while preserving the path.
22*6d6b81f9SEvan Bacon        // This implements the HTML5 history fallback API.
23*6d6b81f9SEvan Bacon        return this.indexMiddleware(req, res, next);
24*6d6b81f9SEvan Bacon      }
25*6d6b81f9SEvan Bacon
26*6d6b81f9SEvan Bacon      return next();
27*6d6b81f9SEvan Bacon    };
28*6d6b81f9SEvan Bacon  }
29*6d6b81f9SEvan Bacon}
30