@apimatic/cli 2.0.0-beta.4 → 2.0.0-beta.5

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 (137) hide show
  1. package/README.md +15 -64
  2. package/apimatic.schema.json +2 -2
  3. package/lib/actions/action-result.d.ts +4 -2
  4. package/lib/actions/action-result.js +8 -3
  5. package/lib/actions/action-result.js.map +1 -1
  6. package/lib/actions/api/transform.d.ts +7 -6
  7. package/lib/actions/api/transform.js +12 -13
  8. package/lib/actions/api/transform.js.map +1 -1
  9. package/lib/actions/api/validate.d.ts +4 -5
  10. package/lib/actions/api/validate.js +30 -32
  11. package/lib/actions/api/validate.js.map +1 -1
  12. package/lib/actions/portal/generate.js +3 -3
  13. package/lib/actions/portal/generate.js.map +1 -1
  14. package/lib/actions/quickstart.d.ts +1 -9
  15. package/lib/actions/quickstart.js +122 -102
  16. package/lib/actions/quickstart.js.map +1 -1
  17. package/lib/commands/api/transform.d.ts +1 -1
  18. package/lib/commands/api/transform.js +2 -2
  19. package/lib/commands/api/transform.js.map +1 -1
  20. package/lib/commands/api/validate.d.ts +3 -3
  21. package/lib/commands/api/validate.js +28 -17
  22. package/lib/commands/api/validate.js.map +1 -1
  23. package/lib/commands/plugin/generate.d.ts +1 -1
  24. package/lib/commands/portal/generate.d.ts +2 -2
  25. package/lib/commands/portal/generate.js +1 -1
  26. package/lib/commands/portal/generate.js.map +1 -1
  27. package/lib/commands/portal/serve.d.ts +2 -2
  28. package/lib/commands/portal/serve.js +1 -1
  29. package/lib/commands/sdk/generate.d.ts +1 -1
  30. package/lib/infrastructure/file-service.d.ts +3 -0
  31. package/lib/infrastructure/file-service.js +24 -0
  32. package/lib/infrastructure/file-service.js.map +1 -1
  33. package/lib/infrastructure/portal-dev-server-service.js +2 -1
  34. package/lib/infrastructure/portal-dev-server-service.js.map +1 -1
  35. package/lib/infrastructure/portal-project-service.d.ts +1 -0
  36. package/lib/infrastructure/portal-project-service.js +7 -3
  37. package/lib/infrastructure/portal-project-service.js.map +1 -1
  38. package/lib/infrastructure/services/file-download-service.d.ts +4 -4
  39. package/lib/infrastructure/services/file-download-service.js +14 -14
  40. package/lib/infrastructure/services/file-download-service.js.map +1 -1
  41. package/lib/prompts/api/transform.d.ts +0 -2
  42. package/lib/prompts/api/transform.js +0 -3
  43. package/lib/prompts/api/transform.js.map +1 -1
  44. package/lib/prompts/api/validate.d.ts +2 -2
  45. package/lib/prompts/api/validate.js +35 -3
  46. package/lib/prompts/api/validate.js.map +1 -1
  47. package/lib/prompts/format.d.ts +1 -1
  48. package/lib/prompts/format.js.map +1 -1
  49. package/lib/prompts/portal/generate.d.ts +2 -1
  50. package/lib/prompts/portal/generate.js +22 -6
  51. package/lib/prompts/portal/generate.js.map +1 -1
  52. package/lib/prompts/portal/prepare-project.js +5 -0
  53. package/lib/prompts/portal/prepare-project.js.map +1 -1
  54. package/lib/prompts/portal/serve.js +4 -3
  55. package/lib/prompts/portal/serve.js.map +1 -1
  56. package/lib/prompts/portal/source.d.ts +2 -5
  57. package/lib/prompts/portal/source.js +7 -17
  58. package/lib/prompts/portal/source.js.map +1 -1
  59. package/lib/prompts/quickstart.d.ts +14 -13
  60. package/lib/prompts/quickstart.js +43 -27
  61. package/lib/prompts/quickstart.js.map +1 -1
  62. package/lib/types/apimatic-config/document.d.ts +2 -0
  63. package/lib/types/apimatic-config/document.js +4 -0
  64. package/lib/types/apimatic-config/document.js.map +1 -1
  65. package/lib/types/file/resource-input.d.ts +7 -5
  66. package/lib/types/file/resource-input.js +16 -15
  67. package/lib/types/file/resource-input.js.map +1 -1
  68. package/lib/types/flags-provider.d.ts +6 -1
  69. package/lib/types/flags-provider.js +22 -12
  70. package/lib/types/flags-provider.js.map +1 -1
  71. package/lib/types/plugin-config-context.d.ts +3 -0
  72. package/lib/types/plugin-config-context.js +33 -12
  73. package/lib/types/plugin-config-context.js.map +1 -1
  74. package/lib/types/portal/config/site-address.d.ts +16 -0
  75. package/lib/types/portal/config/site-address.js +67 -0
  76. package/lib/types/portal/config/site-address.js.map +1 -0
  77. package/lib/types/portal/config/site-config.d.ts +3 -5
  78. package/lib/types/portal/config/site-config.js +10 -33
  79. package/lib/types/portal/config/site-config.js.map +1 -1
  80. package/lib/types/portal/config/static-asset.d.ts +2 -2
  81. package/lib/types/portal/config/static-asset.js +2 -2
  82. package/lib/types/portal/config/static-asset.js.map +1 -1
  83. package/lib/types/portal/content-tree.d.ts +11 -4
  84. package/lib/types/portal/content-tree.js +19 -4
  85. package/lib/types/portal/content-tree.js.map +1 -1
  86. package/lib/types/portal/page.js +16 -1
  87. package/lib/types/portal/page.js.map +1 -1
  88. package/lib/types/portal/portal-config.d.ts +6 -3
  89. package/lib/types/portal/portal-config.js +8 -4
  90. package/lib/types/portal/portal-config.js.map +1 -1
  91. package/lib/types/portal/portal-languages.d.ts +2 -0
  92. package/lib/types/portal/portal-languages.js +5 -1
  93. package/lib/types/portal/portal-languages.js.map +1 -1
  94. package/lib/types/portal/portal-source.d.ts +9 -3
  95. package/lib/types/portal-source-context.d.ts +7 -8
  96. package/lib/types/portal-source-context.js +51 -26
  97. package/lib/types/portal-source-context.js.map +1 -1
  98. package/lib/types/project-context.d.ts +18 -0
  99. package/lib/types/project-context.js +18 -1
  100. package/lib/types/project-context.js.map +1 -1
  101. package/lib/types/resource-context.d.ts +25 -10
  102. package/lib/types/resource-context.js +40 -23
  103. package/lib/types/resource-context.js.map +1 -1
  104. package/oclif.manifest.json +88 -70
  105. package/package.json +1 -1
  106. package/portal-template/dependency-directories.ts +31 -40
  107. package/portal-template/downloads.ts +6 -3
  108. package/portal-template/portal-config.ts +2 -0
  109. package/portal-template/prerender-pages.ts +8 -2
  110. package/portal-template/src/components/api-markdown.tsx +32 -0
  111. package/portal-template/src/components/api-page.tsx +8 -1
  112. package/portal-template/src/components/authorization-failure.tsx +63 -0
  113. package/portal-template/src/components/markdown-copy-button.tsx +2 -2
  114. package/portal-template/src/components/plugin-install.tsx +6 -5
  115. package/portal-template/src/components/sdk-actions.tsx +3 -2
  116. package/portal-template/src/components/sdk-cards.tsx +2 -1
  117. package/portal-template/src/components/search.tsx +9 -2
  118. package/portal-template/src/lib/base-path.ts +14 -0
  119. package/portal-template/src/lib/code-titles.ts +8 -0
  120. package/portal-template/src/lib/copy-markdown.ts +4 -2
  121. package/portal-template/src/lib/install-command.ts +5 -5
  122. package/portal-template/src/lib/layout.shared.tsx +5 -3
  123. package/portal-template/src/lib/llms.server.ts +29 -5
  124. package/portal-template/src/lib/oauth-callback.ts +63 -0
  125. package/portal-template/src/lib/portal-types.ts +3 -3
  126. package/portal-template/src/lib/rehype-code-titles.ts +3 -5
  127. package/portal-template/src/lib/remark-image-references.ts +35 -0
  128. package/portal-template/src/lib/search-content.ts +28 -0
  129. package/portal-template/src/lib/search-options.ts +7 -0
  130. package/portal-template/src/lib/source.server.ts +2 -0
  131. package/portal-template/src/router.tsx +3 -1
  132. package/portal-template/src/routes/$.tsx +3 -2
  133. package/portal-template/src/routes/__root.tsx +8 -1
  134. package/portal-template/src/routes/api/search[.]json.ts +23 -2
  135. package/portal-template/src/routes/oauth.callback.tsx +54 -0
  136. package/portal-template/static-functions-base.ts +41 -0
  137. package/portal-template/vite.config.ts +14 -7
@@ -1,22 +1,23 @@
1
1
  import { useSyncExternalStore } from 'react';
2
2
  import { asMarkdown } from 'fumadocs-core/server';
3
3
  import { CommandBlock } from './command-block';
4
+ import { fullAddress } from '@/lib/base-path';
4
5
  import { installCommand } from '@/lib/install-command';
5
6
  import { portal } from '@/lib/portal';
6
7
 
7
- // The origin never changes while the page is open, so there is nothing to subscribe to.
8
+ // The address never changes while the page is open, so there is nothing to subscribe to.
8
9
  const noSubscribe = () => () => {};
9
10
 
10
- /** The prerender cannot know where the portal is hosted, so the browser swaps in its own origin. */
11
+ /** The prerender cannot know where the portal is hosted, so the browser swaps in its own address. */
11
12
  export function PluginInstall({ path }: Readonly<{ path: string }>) {
12
13
  // Ahead of the hook, which only React may call; either branch is taken in every render of one environment.
13
14
  if (asMarkdown()) {
14
15
  return <CommandBlock command={installCommand(path, portal.siteUrl)} />;
15
16
  }
16
- const origin = useSyncExternalStore(
17
+ const site = useSyncExternalStore(
17
18
  noSubscribe,
18
- () => window.location.origin,
19
+ () => fullAddress('/'),
19
20
  () => portal.siteUrl
20
21
  );
21
- return <CommandBlock command={installCommand(path, origin)} />;
22
+ return <CommandBlock command={installCommand(path, site)} />;
22
23
  }
@@ -2,6 +2,7 @@ import type { ReactNode } from 'react';
2
2
  import { asMarkdown } from 'fumadocs-core/server';
3
3
  import { buttonVariants } from 'fumadocs-ui/components/ui/button';
4
4
  import { Code, Download, Package } from 'lucide-react';
5
+ import { withBasePath } from '@/lib/base-path';
5
6
 
6
7
  export interface SdkActionsProps {
7
8
  download: string;
@@ -22,7 +23,7 @@ export function SdkActions({ download, source, packageUrl, registry }: Readonly<
22
23
  // The page's Markdown twin, which the page actions and llms-full.txt hand to an AI assistant.
23
24
  if (asMarkdown()) {
24
25
  const links = [
25
- `[Download SDK](${download})`,
26
+ `[Download SDK](${withBasePath(download)})`,
26
27
  source ? `[View source](${source})` : null,
27
28
  packageUrl ? `[View on ${registry}](${packageUrl})` : null
28
29
  ];
@@ -64,7 +65,7 @@ interface LinkProps {
64
65
  /** A plain link, not a route: the zip is a file the site serves beside its pages. */
65
66
  export function DownloadLink({ href, className, children }: Readonly<LinkProps>) {
66
67
  return (
67
- <a href={href} download className={className}>
68
+ <a href={withBasePath(href)} download className={className}>
68
69
  {children}
69
70
  </a>
70
71
  );
@@ -2,6 +2,7 @@ import type { ReactNode } from 'react';
2
2
  import Link from 'fumadocs-core/link';
3
3
  import { asMarkdown } from 'fumadocs-core/server';
4
4
  import { ArrowDownToLine, ArrowRight, ExternalLink as ExternalLinkIcon } from 'lucide-react';
5
+ import { withBasePath } from '@/lib/base-path';
5
6
  import { CommandBlock } from './command-block';
6
7
  import { LanguageLogo, LogoTile } from './logos';
7
8
  import { DownloadLink, ExternalLink, LINK, QUIET_LINK, SdkActions, type SdkActionsProps } from './sdk-actions';
@@ -40,7 +41,7 @@ function LinkContext({ name }: Readonly<{ name: string }>) {
40
41
  export function SdkCard({ language, name, page, install, ...actions }: Readonly<SdkCardProps>) {
41
42
  if (asMarkdown()) {
42
43
  const command = install ? `\`${install}\` · ` : '';
43
- return [`- [${name}](${page}): ${command}`, <SdkActions key="actions" {...actions} />];
44
+ return [`- [${name}](${withBasePath(page)}): ${command}`, <SdkActions key="actions" {...actions} />];
44
45
  }
45
46
  const { download, source, packageUrl, registry } = actions;
46
47
  return (
@@ -13,6 +13,8 @@ import {
13
13
  import { useDocsSearch } from 'fumadocs-core/search/client';
14
14
  import { staticClient } from 'fumadocs-core/search/client/orama-static';
15
15
  import { useI18n } from 'fumadocs-ui/contexts/i18n';
16
+ import { useMemo } from 'react';
17
+ import { withBasePath } from '@/lib/base-path';
16
18
 
17
19
  export default function DefaultSearchDialog(props: SharedProps) {
18
20
  const { locale } = useI18n();
@@ -20,10 +22,15 @@ export default function DefaultSearchDialog(props: SharedProps) {
20
22
  // Served with an extension so hosts and CDNs give it a JSON content type; without one
21
23
  // it went out as application/octet-stream, which some of them attach or refuse.
22
24
  client: staticClient({
23
- from: '/api/search.json',
25
+ from: withBasePath('/api/search.json'),
24
26
  locale
25
27
  })
26
28
  });
29
+ // Served URLs, since the dialog navigates by href (search-navigation.test.ts), memoised so its highlight stays put.
30
+ const results = useMemo(
31
+ () => (query.data === 'empty' ? null : query.data?.map((item) => ({ ...item, url: withBasePath(item.url) }))),
32
+ [query.data]
33
+ );
27
34
 
28
35
  return (
29
36
  <SearchDialog search={search} onSearchChange={setSearch} isLoading={query.isLoading} {...props}>
@@ -34,7 +41,7 @@ export default function DefaultSearchDialog(props: SharedProps) {
34
41
  <SearchDialogInput />
35
42
  <SearchDialogClose />
36
43
  </SearchDialogHeader>
37
- <SearchDialogList items={query.data !== 'empty' ? query.data : null} />
44
+ <SearchDialogList items={results} />
38
45
  </SearchDialogContent>
39
46
  </SearchDialog>
40
47
  );
@@ -0,0 +1,14 @@
1
+ /// <reference types="vite/client" />
2
+
3
+ // Undefined outside Vite, as under the template's unit tests; Fumadocs guards it the same way.
4
+ const BASE = typeof import.meta.env === 'undefined' ? '/' : import.meta.env.BASE_URL;
5
+
6
+ /** A portal-relative path as the host serves it, under `base`: Vite's own unless one is given. */
7
+ export function withBasePath(path: string, base: string = BASE): string {
8
+ return `${base.replace(/\/$/, '')}${path}`;
9
+ }
10
+
11
+ /** A portal-relative path's full address as the browser sees it; the path itself where there is no window. */
12
+ export function fullAddress(path: string): string {
13
+ return typeof window === 'undefined' ? path : new URL(withBasePath(path), window.location.origin).toString();
14
+ }
@@ -27,3 +27,11 @@ export const CODE_BLOCK_TITLES: Readonly<Record<BundledLanguage, string>> = {
27
27
  sql: 'SQL',
28
28
  tsx: 'TSX'
29
29
  };
30
+
31
+ const LANGUAGE_CLASS = 'language-';
32
+
33
+ /** The language a fence names, from the class `remark-rehype` gives its `code`. */
34
+ export function languageOf(classes: unknown[]): string | undefined {
35
+ const languageClass = classes.find((name) => typeof name === 'string' && name.startsWith(LANGUAGE_CLASS));
36
+ return typeof languageClass === 'string' ? languageClass.slice(LANGUAGE_CLASS.length) : undefined;
37
+ }
@@ -1,5 +1,7 @@
1
- export async function copyMarkdown(rootRelativeUrl: string, base: string): Promise<void> {
2
- const url = `${base.replace(/\/$/, '')}${rootRelativeUrl}`;
1
+ import { withBasePath } from './base-path';
2
+
3
+ export async function copyMarkdown(rootRelativeUrl: string, base?: string): Promise<void> {
4
+ const url = withBasePath(rootRelativeUrl, base);
3
5
  // Handed over unresolved, so Safari still counts the write as part of the click.
4
6
  const markdown = fetchMarkdown(url);
5
7
  await Promise.all([navigator.clipboard.write([new ClipboardItem({ 'text/plain': markdown })]), markdown]);
@@ -1,13 +1,13 @@
1
1
  const ABSOLUTE = /^https?:\/\//i;
2
2
 
3
3
  // Quoted, so a `&` or a space in the address stays one argument in any shell a reader pastes it into.
4
- export function installCommand(path: string, origin: string | null): string {
5
- return `npx context-plugins install "${installAddress(path, origin)}"`;
4
+ export function installCommand(path: string, site: string | null): string {
5
+ return `npx context-plugins install "${installAddress(path, site)}"`;
6
6
  }
7
7
 
8
- function installAddress(path: string, origin: string | null): string {
9
- if (ABSOLUTE.test(path) || origin === null) {
8
+ function installAddress(path: string, site: string | null): string {
9
+ if (ABSOLUTE.test(path) || site === null) {
10
10
  return path;
11
11
  }
12
- return `${origin.replace(/\/+$/, '')}/${path.replace(/^\/+/, '')}`;
12
+ return `${site.replace(/\/+$/, '')}/${path.replace(/^\/+/, '')}`;
13
13
  }
@@ -1,4 +1,5 @@
1
1
  import type { BaseLayoutProps } from 'fumadocs-ui/layouts/shared';
2
+ import { withBasePath } from './base-path';
2
3
  import { portal } from './portal';
3
4
 
4
5
  export function baseOptions(): BaseLayoutProps {
@@ -30,12 +31,13 @@ const LOGO_SIZE = 'h-6 w-auto max-w-none';
30
31
  function Logo() {
31
32
  const { logo } = portal;
32
33
  if (!logo) return null;
33
- if (logo.light === logo.dark) return <img src={logo.light} alt="" className={LOGO_SIZE} />;
34
+ const [light, dark] = [withBasePath(logo.light), withBasePath(logo.dark)];
35
+ if (light === dark) return <img src={light} alt="" className={LOGO_SIZE} />;
34
36
  // Both are in the page and CSS shows one, so the right one is there before any script runs.
35
37
  return (
36
38
  <>
37
- <img src={logo.light} alt="" className={`${LOGO_SIZE} dark:hidden`} />
38
- <img src={logo.dark} alt="" className={`hidden ${LOGO_SIZE} dark:block`} />
39
+ <img src={light} alt="" className={`${LOGO_SIZE} dark:hidden`} />
40
+ <img src={dark} alt="" className={`hidden ${LOGO_SIZE} dark:block`} />
39
41
  </>
40
42
  );
41
43
  }
@@ -1,15 +1,35 @@
1
+ import type * as PageTree from 'fumadocs-core/page-tree';
1
2
  import { llms } from 'fumadocs-core/source';
2
3
  import { stringify } from 'yaml';
3
4
  import { getMDXComponents } from '@/components/mdx';
5
+ import { withBasePath } from './base-path';
4
6
  import { operationLabels } from './openapi-labels';
5
7
  import { slimOpenAPIPageProps } from './openapi-slim';
6
- import { source } from './source.server';
8
+ import { type PortalPage, source } from './source.server';
7
9
  import { portal } from './portal';
8
10
 
9
- type PortalPage = ReturnType<typeof source.getPages>[number];
10
11
  type ReferencePage = Extract<PortalPage, { type: 'openapi' }>;
11
12
 
12
- const index = llms(source);
13
+ // `llms()` links each page by its tree node's URL and has no base of its own; titles are found by `$ref`.
14
+ const index = llms({
15
+ ...source,
16
+ getPageTree: (locale?: string) => {
17
+ const root = source.getPageTree(locale);
18
+ return { ...root, children: root.children.map(servedNode) };
19
+ }
20
+ });
21
+
22
+ function servedNode(node: PageTree.Node): PageTree.Node {
23
+ if (node.type === 'page') return { ...node, url: withBasePath(node.url) };
24
+ if (node.type === 'folder') {
25
+ return {
26
+ ...node,
27
+ index: node.index && { ...node.index, url: withBasePath(node.index.url) },
28
+ children: node.children.map(servedNode)
29
+ };
30
+ }
31
+ return node;
32
+ }
13
33
 
14
34
  export async function renderPage(page: PortalPage): Promise<string> {
15
35
  return await render(page, true);
@@ -34,14 +54,18 @@ export function renderHome(): string {
34
54
  }
35
55
 
36
56
  async function renderContent(page: Exclude<PortalPage, ReferencePage>): Promise<string> {
37
- return `# ${page.data.title} (${page.url})\n\n${await page.data.getText('processed', { components: getMDXComponents() })}`;
57
+ return `# ${page.data.title} (${withBasePath(page.url)})\n\n${await page.data.getText('processed', { components: getMDXComponents() })}`;
38
58
  }
39
59
 
40
60
  /** An operation's page, with the part of its specification that page renders: what an assistant reads best. */
41
61
  function renderReference(page: ReferencePage, withSpecification: boolean): string {
42
62
  const props = slimOpenAPIPageProps(page.data.getOpenAPIPageProps());
43
63
  const endpoints = operationLabels(props, (signature) => `\`${signature}\``);
44
- const sections = [`# ${page.data.title} (${page.url})`, endpoints.join('\n'), page.data.description ?? ''];
64
+ const sections = [
65
+ `# ${page.data.title} (${withBasePath(page.url)})`,
66
+ endpoints.join('\n'),
67
+ page.data.description ?? ''
68
+ ];
45
69
  if (withSpecification) {
46
70
  // Its tags and the document's description are the portal's to show, and would come with every operation.
47
71
  const { info, tags: _tags, ...document } = props.payload.bundled as Record<string, unknown> & {
@@ -0,0 +1,63 @@
1
+ /**
2
+ * The one redirect URI a portal owner registers with their OAuth provider, instead of the
3
+ * address of every endpoint page that can start an authorization. The CLI keeps the user's
4
+ * pages off it, in `src/types/portal/content-tree.ts`.
5
+ */
6
+ export const oauthCallbackPath = '/oauth/callback';
7
+
8
+ /** The cookie the playground writes before it leaves, naming the page that started the flow. */
9
+ const PAGE_COOKIE_NAME = 'fumadocs-openapi-oauth';
10
+ const PAGE_COOKIE = new RegExp(`(?:^|;\\s*)${PAGE_COOKIE_NAME}=([^;]+)`);
11
+
12
+ /** What the callback does with the browser that lands on it. */
13
+ export type OAuthCallback =
14
+ /** Sends it back to the page that started the flow, with the provider's answer still attached. */
15
+ | { kind: 'return'; url: string }
16
+ /** Stays, to show the error the provider ended the authorization with, and a link back to that page. */
17
+ | { kind: 'providerError'; error: string; description: string | null; page: string }
18
+ /** Stays, since the cookie names no page: no authorization was started in this browser. */
19
+ | { kind: 'notStarted' }
20
+ /** Stays, since the cookie names a page on another site, or one that cannot be read. */
21
+ | { kind: 'unknownPage' };
22
+
23
+ /** Every outcome but sending the browser on, which leaves the callback before it renders again. */
24
+ export type OAuthCallbackFailure = Exclude<OAuthCallback, { kind: 'return' }>;
25
+
26
+ /**
27
+ * The provider answers in the query for the authorization code flow and in the fragment for the
28
+ * implicit one, an error included. Only an authorization this browser started is answered with
29
+ * the provider's error: anyone can link here with an `error_description` of their own.
30
+ */
31
+ export function oauthCallback(cookie: string, location: Pick<Location, 'origin' | 'search' | 'hash'>): OAuthCallback {
32
+ const value = PAGE_COOKIE.exec(cookie)?.[1];
33
+ if (value === undefined) return { kind: 'notStarted' };
34
+
35
+ let page: URL;
36
+ try {
37
+ page = new URL(decodeURIComponent(value), location.origin);
38
+ } catch {
39
+ return { kind: 'unknownPage' };
40
+ }
41
+ // Anything else is an open redirect, carrying the authorization code to another site.
42
+ if (page.origin !== location.origin) return { kind: 'unknownPage' };
43
+
44
+ const query = new URLSearchParams(location.search);
45
+ const answer = query.has('error') ? query : new URLSearchParams(location.hash.slice(1));
46
+ const error = answer.get('error');
47
+ if (error !== null) {
48
+ return { kind: 'providerError', error, description: answer.get('error_description'), page: page.href };
49
+ }
50
+
51
+ // Whole, not as a path: a path of `//evil.test/x` would be read as another site's address.
52
+ page.search = location.search;
53
+ page.hash = location.hash;
54
+ return { kind: 'return', url: page.href };
55
+ }
56
+
57
+ /**
58
+ * The playground leaves the cookie for the session, so a later visit would be sent back to the
59
+ * last page that started an authorization. Forgotten once read, it names only the flow just started.
60
+ */
61
+ export function forgetStartingPage(): void {
62
+ document.cookie = `${PAGE_COOKIE_NAME}=; path=/; max-age=0`;
63
+ }
@@ -10,14 +10,14 @@ export interface PortalLink {
10
10
  external: boolean;
11
11
  }
12
12
 
13
- /** Site-relative, one per colour mode; the same URL twice when one image serves both. */
13
+ /** Portal-relative, one per colour mode; the same URL twice when one image serves both. */
14
14
  export interface PortalLogo {
15
15
  light: string;
16
16
  dark: string;
17
17
  }
18
18
 
19
19
  export interface PortalFavicon {
20
- /** Site-relative, and inside the static directory. */
20
+ /** Portal-relative, and inside the static directory. */
21
21
  url: string;
22
22
  type: string | null;
23
23
  }
@@ -25,7 +25,7 @@ export interface PortalFavicon {
25
25
  export interface Portal {
26
26
  name: string;
27
27
  description: string | null;
28
- /** Origin only, with no trailing slash. */
28
+ /** The site address, with no trailing slash. */
29
29
  siteUrl: string | null;
30
30
  logo: PortalLogo | null;
31
31
  favicon: PortalFavicon | null;
@@ -1,5 +1,5 @@
1
1
  import { parseCodeBlockAttributes } from 'fumadocs-core/mdx-plugins/codeblock-utils';
2
- import { CODE_BLOCK_TITLES } from './code-titles';
2
+ import { CODE_BLOCK_TITLES, languageOf } from './code-titles';
3
3
  import { bundledLanguage } from './shiki-bundle';
4
4
 
5
5
  interface HastNode {
@@ -11,8 +11,6 @@ interface HastNode {
11
11
  children?: HastNode[];
12
12
  }
13
13
 
14
- const LANGUAGE_CLASS = 'language-';
15
-
16
14
  /** Where `remarkCodeTab` puts a tabbed block, by its own tabs or an MDX `<Tabs>`: the tab already names it. */
17
15
  const CODE_TABS = new Set(['CodeBlockTab', 'Tab', 'TabsContent']);
18
16
 
@@ -40,8 +38,8 @@ export function rehypeCodeTitles() {
40
38
  return;
41
39
  }
42
40
  const classes = Array.isArray(code.properties?.className) ? code.properties.className : [];
43
- const languageClass = classes.find((name) => typeof name === 'string' && name.startsWith(LANGUAGE_CLASS));
44
- const language = typeof languageClass === 'string' ? bundledLanguage(languageClass.slice(LANGUAGE_CLASS.length)) : null;
41
+ const name = languageOf(classes);
42
+ const language = name === undefined ? null : bundledLanguage(name);
45
43
  const meta = typeof code.properties?.metastring === 'string' ? code.properties.metastring : '';
46
44
  // Read as `rehypeCode` reads it, which shows no title for a bare or unquoted one.
47
45
  const { title } = parseCodeBlockAttributes(meta, ['title']).attributes;
@@ -0,0 +1,35 @@
1
+ /** An mdast node, as far as images and the definitions they refer to go. */
2
+ interface MarkdownNode {
3
+ type: string;
4
+ identifier?: string;
5
+ url?: string;
6
+ title?: string | null;
7
+ alt?: string | null;
8
+ position?: unknown;
9
+ children?: MarkdownNode[];
10
+ }
11
+
12
+ /** Writes `![alt][ref]` as `![alt](url)`, the only form Fumadocs' `remarkImage` imports. page.ts checks the same. */
13
+ export function remarkImageReferences() {
14
+ return (tree: MarkdownNode) => {
15
+ const definitions = new Map<string, MarkdownNode>();
16
+ const define = (node: MarkdownNode) => {
17
+ // The first definition of a label wins, as CommonMark reads them.
18
+ if (node.type === 'definition' && node.identifier !== undefined && !definitions.has(node.identifier)) {
19
+ definitions.set(node.identifier, node);
20
+ }
21
+ node.children?.forEach(define);
22
+ };
23
+ define(tree);
24
+
25
+ const inline = (node: MarkdownNode): MarkdownNode => {
26
+ const definition = node.type === 'imageReference' ? definitions.get(node.identifier ?? '') : undefined;
27
+ if (definition !== undefined) {
28
+ return { type: 'image', url: definition.url, title: definition.title, alt: node.alt, position: node.position };
29
+ }
30
+ if (node.children !== undefined) node.children = node.children.map(inline);
31
+ return node;
32
+ };
33
+ inline(tree);
34
+ };
35
+ }
@@ -0,0 +1,28 @@
1
+ import { remark } from 'remark';
2
+
3
+ /** An mdast node, as far as finding images goes. */
4
+ interface MarkdownNode {
5
+ type: string;
6
+ position?: { start: { offset?: number }; end: { offset?: number } };
7
+ children?: MarkdownNode[];
8
+ }
9
+
10
+ const IMAGES = new Set(['image', 'imageReference']);
11
+
12
+ // Without GFM, as the search dialog renders a result.
13
+ const markdown = remark();
14
+
15
+ /** Markdown without its images, as Fumadocs indexes a page of its own, and otherwise as written. */
16
+ export function withoutImages(text: string): string {
17
+ let kept = '';
18
+ let from = 0;
19
+ for (const { position } of imagesIn(markdown.parse(text))) {
20
+ kept += text.slice(from, position?.start.offset ?? from);
21
+ from = position?.end.offset ?? from;
22
+ }
23
+ return kept + text.slice(from);
24
+ }
25
+
26
+ function imagesIn(node: MarkdownNode): MarkdownNode[] {
27
+ return IMAGES.has(node.type) ? [node] : (node.children ?? []).flatMap(imagesIn);
28
+ }
@@ -0,0 +1,7 @@
1
+ import { parseSearchWith, stringifySearchWith } from '@tanstack/react-router';
2
+
3
+ /** Query values as text: under a base path the router rewrites the address through these, and JSON loses some. */
4
+ export const searchOptions = {
5
+ parseSearch: parseSearchWith((value) => value),
6
+ stringifySearch: stringifySearchWith(JSON.stringify)
7
+ };
@@ -25,3 +25,5 @@ export const source = loader(
25
25
  pageTree: { transformers: [navigationTransformer(), tabsTransformer()], generateFallback: false }
26
26
  }
27
27
  );
28
+
29
+ export type PortalPage = ReturnType<typeof source.getPages>[number];
@@ -1,12 +1,14 @@
1
1
  import { createRouter as createTanStackRouter } from '@tanstack/react-router';
2
2
  import { routeTree } from './routeTree.gen';
3
3
  import { NotFound } from '@/components/not-found';
4
+ import { searchOptions } from '@/lib/search-options';
4
5
 
5
6
  export function getRouter() {
6
7
  return createTanStackRouter({
7
8
  routeTree,
8
9
  defaultPreload: 'intent',
9
10
  scrollRestoration: true,
10
- defaultNotFoundComponent: NotFound
11
+ defaultNotFoundComponent: NotFound,
12
+ ...searchOptions
11
13
  });
12
14
  }
@@ -3,6 +3,7 @@ import { createServerFn } from '@tanstack/react-start';
3
3
  import { docs, generated } from '@/lib/source';
4
4
  import { source } from '@/lib/source.server';
5
5
  import { PortalLayout } from '@/lib/layout';
6
+ import { fullAddress } from '@/lib/base-path';
6
7
  import { getPageMarkdownUrl, slugsFromSplat } from '@/lib/shared';
7
8
  import { portal } from '@/lib/portal';
8
9
  import { absoluteUrl, canonicalLink } from '@/lib/seo';
@@ -129,7 +130,7 @@ function Content({
129
130
  const PageBody = page.body;
130
131
  const pathname = usePathname();
131
132
  // Named, or the popover reads `window.location.href` and sends the reader's query and hash on.
132
- const pageUrl = typeof window === 'undefined' ? pathname : new URL(pathname, window.location.origin).toString();
133
+ const pageUrl = fullAddress(pathname);
133
134
 
134
135
  return (
135
136
  <DocsPage toc={toc} full={page.full}>
@@ -137,7 +138,7 @@ function Content({
137
138
  <DocsDescription>{page.description}</DocsDescription>
138
139
  <div className="flex flex-row gap-2 items-center border-b -mt-4 pb-6">
139
140
  {/* Keyed so a new page starts at "Copy Markdown", not at the last page's result. */}
140
- <MarkdownCopyButton key={markdownUrl} markdownUrl={markdownUrl} base={import.meta.env.BASE_URL} />
141
+ <MarkdownCopyButton key={markdownUrl} markdownUrl={markdownUrl} />
141
142
  {/* Sends the reader to an external AI vendor, so a portal published under someone
142
143
  else's brand can turn it off. */}
143
144
  {portal.pageActions ? <ViewOptionsPopover markdownUrl={markdownUrl} pageUrl={pageUrl} /> : null}
@@ -5,6 +5,7 @@ import { source } from '@/lib/source.server';
5
5
  import appCss from '@/styles/app.css?url';
6
6
  import { RootProvider } from 'fumadocs-ui/provider/tanstack';
7
7
  import SearchDialog from '@/components/search';
8
+ import { withBasePath } from '@/lib/base-path';
8
9
  import { portal } from '@/lib/portal';
9
10
 
10
11
  // The sidebar tree is the same on every page. Loaded here, once, it is written to a single
@@ -15,7 +16,13 @@ const loadPageTree = createServerFn({ method: 'GET' })
15
16
 
16
17
  // Without one the browser tab shows the blank-document icon on every page.
17
18
  const iconLinks = portal.favicon
18
- ? [{ rel: 'icon', href: portal.favicon.url, ...(portal.favicon.type ? { type: portal.favicon.type } : {}) }]
19
+ ? [
20
+ {
21
+ rel: 'icon',
22
+ href: withBasePath(portal.favicon.url),
23
+ ...(portal.favicon.type ? { type: portal.favicon.type } : {})
24
+ }
25
+ ]
19
26
  : [];
20
27
 
21
28
  // A portal fixed to one mode keeps to it whatever the visitor's system prefers, and offers no
@@ -1,9 +1,30 @@
1
1
  import { createFileRoute } from '@tanstack/react-router';
2
- import { source } from '@/lib/source.server';
2
+ import { withoutImages } from '@/lib/search-content';
3
+ import { type PortalPage, source } from '@/lib/source.server';
3
4
  import { createFromSource } from 'fumadocs-core/search/server';
4
5
 
5
- const server = createFromSource(source, { language: 'english' });
6
+ // Fumadocs indexes a reference page's description as written, so results show its images, without the path.
7
+ const server = createFromSource(
8
+ { ...source, getPages: (language?: string) => source.getPages(language).map(searchable) },
9
+ { language: 'english' }
10
+ );
6
11
 
7
12
  export const Route = createFileRoute('/api/search.json')({
8
13
  server: { handlers: { GET: () => server.staticGET() } }
9
14
  });
15
+
16
+ /** A reference page as Fumadocs indexes a page of its own: without images. */
17
+ function searchable(page: PortalPage): PortalPage {
18
+ if (page.type !== 'openapi') return page;
19
+ const { description, structuredData } = page.data;
20
+ const contents = structuredData.contents.map((item) => ({ ...item, content: withoutImages(item.content) }));
21
+ // Both alike, or Fumadocs no longer finds the description among the contents and indexes it a second time.
22
+ return {
23
+ ...page,
24
+ data: {
25
+ ...page.data,
26
+ description: description && withoutImages(description),
27
+ structuredData: { ...structuredData, contents }
28
+ }
29
+ };
30
+ }
@@ -0,0 +1,54 @@
1
+ import { createFileRoute } from '@tanstack/react-router';
2
+ import { HomeLayout } from 'fumadocs-ui/layouts/home';
3
+ import { useEffect, useState } from 'react';
4
+ import { AuthorizationFailure } from '@/components/authorization-failure';
5
+ import { baseOptions } from '@/lib/layout.shared';
6
+ import { forgetStartingPage, oauthCallback, type OAuthCallback, type OAuthCallbackFailure } from '@/lib/oauth-callback';
7
+ import { portal } from '@/lib/portal';
8
+
9
+ // Published portals are static, so this page does in the browser what Fumadocs'
10
+ // `createOAuthHandler()` route does on a server.
11
+ export const Route = createFileRoute('/oauth/callback')({
12
+ head: () => ({ meta: [{ title: `Authorization | ${portal.name}` }, { name: 'robots', content: 'noindex' }] }),
13
+ component: OAuthCallbackPage
14
+ });
15
+
16
+ let completion: OAuthCallback | undefined;
17
+
18
+ /**
19
+ * Reading the cookie and sending the browser on can each happen only once per page load, not
20
+ * once per mount: the StrictMode `portal serve` runs under mounts the page twice, and the second
21
+ * mount would find the cookie gone. The answer is kept, so a later mount in the same load, such
22
+ * as Back after leaving through the header, shows the same outcome. Every arrival from a provider
23
+ * is a new load.
24
+ */
25
+ function completeAuthorization(): OAuthCallback {
26
+ if (completion === undefined) {
27
+ completion = oauthCallback(document.cookie, window.location);
28
+ forgetStartingPage();
29
+ if (completion.kind === 'return') window.location.replace(completion.url);
30
+ }
31
+ return completion;
32
+ }
33
+
34
+ function OAuthCallbackPage() {
35
+ // Null until the effect has read the cookie, which the prerendered page cannot.
36
+ const [failure, setFailure] = useState<OAuthCallbackFailure | null>(null);
37
+
38
+ useEffect(() => {
39
+ const callback = completeAuthorization();
40
+ if (callback.kind !== 'return') setFailure(callback);
41
+ }, []);
42
+
43
+ return (
44
+ <HomeLayout {...baseOptions()}>
45
+ <div className="flex flex-col px-8 justify-center flex-1 text-center items-center gap-4">
46
+ {failure === null ? (
47
+ <p className="text-fd-muted-foreground">Completing authorization…</p>
48
+ ) : (
49
+ <AuthorizationFailure failure={failure} />
50
+ )}
51
+ </div>
52
+ </HomeLayout>
53
+ );
54
+ }
@@ -0,0 +1,41 @@
1
+ import type { Plugin } from 'vite';
2
+ import { withBasePath } from './src/lib/base-path';
3
+
4
+ /** The package whose browser half fetches a prerendered server function's result. */
5
+ const PACKAGE = /[\\/]@tanstack[\\/]start-static-server-functions[\\/]/;
6
+
7
+ /** Where it fetches that result from, opening backtick included so nothing else naming the folder matches. */
8
+ export const CACHE_ADDRESS = '`/__tsr/staticServerFnCache/';
9
+
10
+ /** Puts the browser's fetch of prerendered page data under the base, until TanStack/router#6152 does it itself. */
11
+ export function staticFunctionsBase(): Plugin {
12
+ let base = '/';
13
+ let found = false;
14
+ return {
15
+ name: 'apimatic:static-functions-base',
16
+ apply: 'build',
17
+ enforce: 'pre',
18
+ // The server writes the files under the output directory, which the host already serves at the base.
19
+ applyToEnvironment: (environment) => environment.name === 'client',
20
+ configResolved(config) {
21
+ base = config.base;
22
+ },
23
+ transform: {
24
+ filter: { id: PACKAGE, code: CACHE_ADDRESS },
25
+ handler(code) {
26
+ // Found at the root too, where the replacement is the address itself.
27
+ found = true;
28
+ return code.replaceAll(CACHE_ADDRESS, '`' + withBasePath(CACHE_ADDRESS.slice(1), base));
29
+ }
30
+ },
31
+ // An upgrade that moves the address fails the build, rather than every link in the portal.
32
+ buildEnd(error) {
33
+ if (error === undefined && !found) {
34
+ this.error(
35
+ `No module of @tanstack/start-static-server-functions holds ${CACHE_ADDRESS}, so a portal ` +
36
+ 'served under a path could not load the pages its links lead to. See portal-template/static-functions-base.ts.'
37
+ );
38
+ }
39
+ }
40
+ };
41
+ }