@stainless-api/docs 0.1.0-beta.99 → 1.0.0-beta.140

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 (136) hide show
  1. package/CHANGELOG.md +390 -0
  2. package/ambient.d.ts +6 -0
  3. package/eslint-suppressions.json +22 -6
  4. package/{eslint.config.js → eslint.config.ts} +1 -7
  5. package/package.json +57 -40
  6. package/plugin/buildAlgoliaIndex.ts +6 -12
  7. package/plugin/components/SDKSelect.astro +0 -6
  8. package/plugin/components/SnippetCode.tsx +6 -37
  9. package/plugin/components/search/SearchAlgolia.astro +1 -1
  10. package/plugin/components/search/SearchIsland.tsx +19 -13
  11. package/plugin/generateAPIReferenceLink.ts +0 -40
  12. package/plugin/globalJs/ai-dropdown-options.ts +22 -9
  13. package/plugin/globalJs/code-snippets.ts +5 -5
  14. package/plugin/globalJs/copy.ts +20 -91
  15. package/plugin/globalJs/navigation.ts +13 -13
  16. package/plugin/globalJs/summary-selection-tweak.ts +29 -0
  17. package/plugin/index.ts +107 -163
  18. package/plugin/loadPluginConfig.ts +49 -151
  19. package/plugin/markdown/highlighter.ts +100 -0
  20. package/plugin/markdown/index.ts +39 -0
  21. package/plugin/middlewareBuilder/stainlessMiddleware.d.ts +2 -0
  22. package/plugin/react/Routing.tsx +10 -244
  23. package/plugin/referencePlaceholderUtils.ts +1 -1
  24. package/plugin/replaceSidebarPlaceholderMiddleware.ts +1 -1
  25. package/plugin/routes/Docs.astro +3 -1
  26. package/plugin/routes/Overview.astro +14 -7
  27. package/plugin/routes/llms.ts +186 -0
  28. package/plugin/routes/markdown.ts +62 -13
  29. package/plugin/sidebar-utils/sidebar-builder.ts +38 -12
  30. package/plugin/specs/defaultSpecLoader.ts +192 -0
  31. package/plugin/specs/fetchSpecSSR.ts +1 -1
  32. package/plugin/specs/utils.ts +86 -0
  33. package/shared/conditionalIntegration.ts +28 -0
  34. package/shared/getProsePages.ts +6 -7
  35. package/shared/virtualModule.ts +1 -26
  36. package/stl-docs/aiChatExamples.ts +31 -0
  37. package/stl-docs/chat/docs-chat-handler.ts +17 -0
  38. package/stl-docs/chat/hook.ts +225 -0
  39. package/stl-docs/chat/schemas.ts +27 -0
  40. package/stl-docs/chat/ui/AiChat.module.css +591 -0
  41. package/stl-docs/chat/ui/AiChat.tsx +175 -0
  42. package/stl-docs/chat/ui/Trigger.tsx +154 -0
  43. package/stl-docs/chat/ui/components/ChatControls.tsx +51 -0
  44. package/stl-docs/chat/ui/components/ChatEmpty.tsx +42 -0
  45. package/stl-docs/chat/ui/components/ChatLog.tsx +93 -0
  46. package/stl-docs/chat/ui/components/ChatMessage.tsx +47 -0
  47. package/stl-docs/chat/ui/components/CodeBlock.tsx +33 -0
  48. package/stl-docs/chat/ui/components/MessageFeedback.tsx +106 -0
  49. package/stl-docs/chat/ui/components/Table.tsx +15 -0
  50. package/stl-docs/chat/ui/components/ToolCall.tsx +34 -0
  51. package/stl-docs/chat/ui/components/hljs-github.css +81 -0
  52. package/stl-docs/chat/ui/scroll-manager.ts +86 -0
  53. package/stl-docs/chat/ui/types.ts +45 -0
  54. package/stl-docs/components/AiChatIsland.tsx +10 -12
  55. package/stl-docs/components/ContentPanel.astro +9 -0
  56. package/stl-docs/components/Footer.astro +89 -0
  57. package/stl-docs/components/Header.astro +0 -5
  58. package/stl-docs/components/PageFrame.astro +23 -8
  59. package/stl-docs/components/PageSidebar.astro +11 -0
  60. package/stl-docs/components/StainlessLogo.svg +4 -0
  61. package/stl-docs/components/TwoColumnContent.astro +2 -0
  62. package/stl-docs/components/headers/DefaultHeader.astro +6 -8
  63. package/stl-docs/components/headers/StackedHeader.astro +5 -53
  64. package/stl-docs/components/mintlify-compat/Accordion.astro +2 -2
  65. package/stl-docs/components/mintlify-compat/AccordionGroup.astro +0 -4
  66. package/stl-docs/components/mintlify-compat/Columns.astro +2 -2
  67. package/stl-docs/components/mintlify-compat/Frame.astro +2 -2
  68. package/stl-docs/components/mintlify-compat/Tab.astro +2 -2
  69. package/stl-docs/components/mintlify-compat/callouts/Callout.astro +2 -2
  70. package/stl-docs/components/mintlify-compat/callouts/Check.astro +0 -4
  71. package/stl-docs/components/mintlify-compat/callouts/Danger.astro +0 -4
  72. package/stl-docs/components/mintlify-compat/callouts/Info.astro +0 -4
  73. package/stl-docs/components/mintlify-compat/callouts/Note.astro +0 -4
  74. package/stl-docs/components/mintlify-compat/callouts/Tip.astro +0 -4
  75. package/stl-docs/components/mintlify-compat/callouts/Warning.astro +0 -4
  76. package/stl-docs/components/nav-tabs/NavDropdown.astro +12 -7
  77. package/stl-docs/components/nav-tabs/NavTabs.astro +5 -3
  78. package/stl-docs/components/nav-tabs/buildNavLinks.ts +2 -0
  79. package/stl-docs/components/pagination/Pagination.astro +4 -2
  80. package/stl-docs/components/pagination/PaginationLinkEmphasized.astro +2 -2
  81. package/stl-docs/components/pagination/PaginationLinkQuiet.astro +2 -2
  82. package/stl-docs/components/pagination/util.ts +3 -3
  83. package/stl-docs/components/sidebars/BaseSidebar.astro +72 -1
  84. package/stl-docs/disableCalloutSyntax.ts +1 -1
  85. package/stl-docs/fonts.ts +5 -5
  86. package/stl-docs/index.ts +76 -53
  87. package/stl-docs/loadStlDocsConfig.ts +38 -8
  88. package/stl-docs/og-image/components/OpenGraphFunctionSignature.tsx +64 -0
  89. package/stl-docs/og-image/components/OpenGraphImage.tsx +126 -0
  90. package/stl-docs/og-image/config.ts +56 -0
  91. package/stl-docs/og-image/image-gen/generate-api-reference-og-image.tsx +188 -0
  92. package/stl-docs/og-image/image-gen/generate-og-image.tsx +119 -0
  93. package/stl-docs/og-image/image-gen/get-logo-url.ts +47 -0
  94. package/stl-docs/og-image/index.ts +135 -0
  95. package/stl-docs/og-image/routes/add-og-image.ts +45 -0
  96. package/stl-docs/og-image/routes/get-api-reference-og-image.ts +36 -0
  97. package/stl-docs/og-image/routes/get-og-image.ts +28 -0
  98. package/stl-docs/og-image/theme.ts +43 -0
  99. package/stl-docs/og-image/utils.ts +14 -0
  100. package/stl-docs/proseDocSync.test.ts +74 -0
  101. package/stl-docs/proseDocSync.ts +344 -0
  102. package/stl-docs/proseMarkdown/proseMarkdownIntegration.ts +4 -12
  103. package/stl-docs/schema-extension.ts +12 -0
  104. package/stl-docs/tabsMiddleware.ts +1 -1
  105. package/styles/overrides.css +2 -14
  106. package/styles/page.css +210 -71
  107. package/styles/sidebar.css +30 -17
  108. package/styles/sl-variables.css +3 -8
  109. package/styles/stldocs-variables.css +2 -2
  110. package/styles/toc.css +8 -0
  111. package/tsconfig.json +1 -1
  112. package/virtual-module.d.ts +35 -11
  113. package/playground-virtual-modules.d.ts +0 -96
  114. package/plugin/globalJs/create-playground.shim.ts +0 -3
  115. package/plugin/globalJs/playground-data.shim.ts +0 -1
  116. package/plugin/globalJs/playground-data.ts +0 -14
  117. package/plugin/specs/FileCache.ts +0 -99
  118. package/plugin/specs/generateSpec.ts +0 -112
  119. package/plugin/specs/index.ts +0 -132
  120. package/plugin/specs/inputResolver.ts +0 -146
  121. package/plugin/specs/worker.ts +0 -199
  122. package/plugin/vendor/preview.worker.docs.js +0 -26108
  123. package/plugin/vendor/templates/cli.md +0 -1
  124. package/plugin/vendor/templates/go.md +0 -316
  125. package/plugin/vendor/templates/java.md +0 -89
  126. package/plugin/vendor/templates/kotlin.md +0 -89
  127. package/plugin/vendor/templates/node.md +0 -235
  128. package/plugin/vendor/templates/python.md +0 -251
  129. package/plugin/vendor/templates/ruby.md +0 -147
  130. package/plugin/vendor/templates/terraform.md +0 -60
  131. package/plugin/vendor/templates/typescript.md +0 -319
  132. package/scripts/vendor_deps.ts +0 -50
  133. package/stl-docs/components/ClientRouterHead.astro +0 -41
  134. package/stl-docs/components/content-panel/ContentPanel.astro +0 -42
  135. package/stl-docs/components/headers/SplashMobileMenuToggle.astro +0 -65
  136. package/stl-docs/proseSearchIndexing.ts +0 -606
@@ -1,99 +0,0 @@
1
- import crypto from 'crypto';
2
- import path from 'path';
3
- import { readdir, readFile, rm, writeFile } from 'fs/promises';
4
-
5
- type CacheResultSource = 'memory' | 'disk' | 'generation';
6
-
7
- export type CacheGetResult<T> = {
8
- resultSource: CacheResultSource;
9
- data: T;
10
- filePath: string;
11
- };
12
-
13
- export class FileCache<Inputs extends Record<string, unknown>, Output> {
14
- private memoryCache: Map<string, Output> = new Map();
15
-
16
- private cacheDirectory: string | null = null;
17
-
18
- public setCacheDirectory(cacheDirectory: string) {
19
- this.cacheDirectory = cacheDirectory;
20
- }
21
- public getCacheDirectory() {
22
- if (!this.cacheDirectory) {
23
- console.error(`Tried to retrieve entry from cache, but no cache directory was set.`);
24
- process.exit(1);
25
- }
26
- return this.cacheDirectory;
27
- }
28
-
29
- private hashInputs(inputs: Inputs): string {
30
- return crypto
31
- .createHash('sha256')
32
- .update(JSON.stringify(inputs) + this.config.globalHashBits)
33
- .digest('hex')
34
- .slice(0, 10);
35
- }
36
-
37
- private getFileName(hash: string) {
38
- return `${hash}.json`;
39
- }
40
-
41
- public async cleanupUnusedFiles() {
42
- const allFiles = await readdir(this.getCacheDirectory());
43
- const usedFiles = Array.from(this.memoryCache.keys()).map((key) => this.getFileName(key));
44
- const unusedFiles = allFiles.filter((file) => !usedFiles.includes(file));
45
- await Promise.all(unusedFiles.map((file) => rm(path.join(this.getCacheDirectory(), file))));
46
- return {
47
- deletedCount: unusedFiles.length,
48
- };
49
- }
50
-
51
- public async get(inputs: Inputs): Promise<CacheGetResult<Output>> {
52
- const hash = this.hashInputs(inputs);
53
- const filePath = path.join(this.getCacheDirectory(), this.getFileName(hash));
54
-
55
- const memoryCacheResult = this.memoryCache.get(hash);
56
- if (memoryCacheResult) {
57
- return {
58
- resultSource: 'memory',
59
- data: memoryCacheResult,
60
- filePath,
61
- };
62
- }
63
-
64
- const getFromFileOrGenerate = async () => {
65
- try {
66
- const fileContents = await readFile(filePath, 'utf8');
67
- return {
68
- resultSource: 'disk' as const,
69
- data: JSON.parse(fileContents) as Output,
70
- filePath,
71
- };
72
- } catch {
73
- const data = await this.config.generate(inputs);
74
- await writeFile(filePath, JSON.stringify(data), 'utf8');
75
- return {
76
- resultSource: 'generation' as const,
77
- data,
78
- filePath,
79
- };
80
- }
81
- };
82
-
83
- const result = await getFromFileOrGenerate();
84
- this.memoryCache.set(hash, result.data);
85
- return result;
86
- }
87
-
88
- constructor(
89
- private config: {
90
- /**
91
- * Additional information to include in the hash of the inputs.
92
- * This is useful for cases where the inputs are the same, but the global state is different.
93
- * Eg: The preview worker source can be used here.
94
- */
95
- globalHashBits: string;
96
- generate: (inputs: Inputs) => Promise<Output>;
97
- },
98
- ) {}
99
- }
@@ -1,112 +0,0 @@
1
- import type * as SDKJSON from '@stainless/sdk-json';
2
- import { Languages } from '@stainless-api/docs-ui/routing';
3
- import { createSDKJSON, ParsedConfig, parseInputs, transformOAS } from './worker';
4
- import { LanguageGenerateQuery } from '../loadPluginConfig';
5
- import { FileCache } from './FileCache';
6
- import previewWorkerCode from '../vendor/preview.worker.docs.js?raw';
7
-
8
- function getLanguagesFromStainlessConfig(config: ParsedConfig): SDKJSON.SpecLanguage[] {
9
- // if the Stainless config has a list of docs languages, use that
10
- if (config.docs?.languages) {
11
- return config.docs.languages;
12
- }
13
-
14
- // otherwise, just loop over all targets in the config + use the ones that are not skipped
15
- return Object.entries(config.targets)
16
- .filter(([name, target]) => {
17
- if (!Languages.includes(name)) return false; // not a valid language
18
- if (target.skip) return false; // config says to skip this language
19
- return true;
20
- })
21
- .map(([name]) => name) as SDKJSON.SpecLanguage[];
22
- }
23
-
24
- // These inputs contain everything needed to generate a spec
25
- // Combined with the source of the preview workers, we can make a hash to cache the resulting spec
26
- export type GenerateSpecRawInputs = {
27
- oasStr: string;
28
- configStr: string;
29
- languageOverrides: LanguageGenerateQuery | null;
30
- stainlessProject: string;
31
- versionInfo: Record<SDKJSON.SpecLanguage, string> | null;
32
- };
33
-
34
- function applyLanguageOverrides(
35
- initialLanguages: SDKJSON.SpecLanguage[],
36
- languageOverrides: LanguageGenerateQuery | null,
37
- ) {
38
- if (!languageOverrides) return initialLanguages;
39
- if (languageOverrides.mode === 'exclude') {
40
- return initialLanguages.filter((language) => !languageOverrides.list.includes(language));
41
- }
42
- return languageOverrides.list;
43
- }
44
-
45
- async function generateSpecFromStrings({
46
- oasStr,
47
- configStr,
48
- stainlessProject,
49
- languageOverrides,
50
- versionInfo,
51
- }: GenerateSpecRawInputs) {
52
- const { oas, config } = await parseInputs({
53
- oas: oasStr,
54
- config: configStr,
55
- });
56
-
57
- const transformedOAS = await transformOAS({ oas, config });
58
-
59
- let languagesToGenerate = getLanguagesFromStainlessConfig(config);
60
- // by default, we should generate the HTTP spec (unless it's explicitly excluded)
61
- if (!languagesToGenerate.includes('http')) {
62
- languagesToGenerate.push('http');
63
- }
64
-
65
- languagesToGenerate = applyLanguageOverrides(languagesToGenerate, languageOverrides);
66
-
67
- // SDKJSON has weird behavior where it will create a spec with HTTP, even if it's not in the languages list
68
- const sdkJson = await createSDKJSON({
69
- oas: transformedOAS,
70
- config,
71
- // if language overrides are provided, use them, otherwise use the languages from the Stainless config
72
- languages: languagesToGenerate,
73
- projectName: stainlessProject,
74
- });
75
-
76
- let languages = sdkJson.docs?.languages;
77
-
78
- if (!languages) {
79
- throw new Error(`SDKJSON created without any languages`);
80
- }
81
-
82
- // if language overrides are provided, filter the languages to only include the ones that are in the overrides
83
- languages = languages.filter((language) => languagesToGenerate.includes(language));
84
-
85
- if (versionInfo) {
86
- for (const [lang, version] of Object.entries(versionInfo)) {
87
- const meta = sdkJson.metadata[lang as SDKJSON.SpecLanguage];
88
- if (meta?.version) meta.version = version;
89
- }
90
- }
91
-
92
- const opts = Object.entries(config.client_settings.opts).map(([k, v]) => ({ name: k, ...v }));
93
- return {
94
- sdkJson,
95
- languages,
96
- auth: sdkJson.security_schemes.map((scheme) => ({
97
- ...scheme,
98
- opts: opts.filter((opt) => opt.auth?.security_scheme === scheme.name),
99
- })),
100
- };
101
- }
102
-
103
- export const specCache = new FileCache({
104
- generate: generateSpecFromStrings,
105
- globalHashBits: previewWorkerCode, // you can change this as a last resort to invalidate the cache
106
- });
107
-
108
- export type SpecCacheResult = Awaited<ReturnType<typeof specCache.get>>;
109
-
110
- export type GenerateSpecFn = typeof generateSpecFromStrings;
111
-
112
- export type SpecWithAuth = Awaited<ReturnType<GenerateSpecFn>>;
@@ -1,132 +0,0 @@
1
- import { mkdir } from 'fs/promises';
2
- import path from 'path';
3
-
4
- import type * as VirtualManifestModule from 'virtual:stainless-apis-manifest';
5
-
6
- import { makeAsyncVirtualModPlugin } from '../../shared/virtualModule';
7
-
8
- import { NormalizedStainlessStarlightConfig, ResolvedAPIConfigEntry } from '../loadPluginConfig';
9
-
10
- import { specCache, SpecCacheResult } from './generateSpec';
11
- import { AstroIntegrationLogger } from 'astro';
12
- import type * as SDKJSON from '@stainless/sdk-json';
13
-
14
- export type LoadedAPIConfigEntry = Omit<ResolvedAPIConfigEntry, 'loadSpecs'> & {
15
- specs: SpecCacheResult[];
16
- languages: SDKJSON.SpecLanguage[];
17
- };
18
-
19
- /**
20
- * A helper class to manage multiple spec cache results for a single API
21
- * An API may have multiple spec cache results if it has multiple languages
22
- * Note that one spec may contain multiple languages.
23
- * */
24
- export class SpecComposite {
25
- private languages: Set<SDKJSON.SpecLanguage>;
26
- private readonly specs: Partial<Record<SDKJSON.SpecLanguage, SpecCacheResult>>;
27
-
28
- public getLanguages() {
29
- return Array.from(this.languages);
30
- }
31
-
32
- public getByLanguage(language: SDKJSON.SpecLanguage) {
33
- const spec = this.specs[language];
34
- if (!spec) {
35
- throw new Error(`Spec for language ${language} not found`);
36
- }
37
- return spec;
38
- }
39
-
40
- /**
41
- * Returns all specs. It will return each spec once, even if it has multiple languages.
42
- * */
43
- public listUniqueSpecs() {
44
- const seen = new Set<SpecCacheResult>();
45
- const unique: SpecCacheResult[] = [];
46
- for (const spec of Object.values(this.specs)) {
47
- if (!seen.has(spec)) {
48
- seen.add(spec);
49
- unique.push(spec);
50
- }
51
- }
52
- return unique;
53
- }
54
-
55
- public listAllLanguagesAndIncludeSpecs() {
56
- return this.getLanguages().map((language) => ({
57
- language,
58
- spec: this.getByLanguage(language),
59
- }));
60
- }
61
-
62
- constructor(specs: SpecCacheResult[]) {
63
- this.languages = new Set<SDKJSON.SpecLanguage>();
64
- this.specs = {};
65
- for (const spec of specs) {
66
- for (const lang of spec.data.languages) {
67
- if (this.languages.has(lang)) {
68
- throw new Error(`Language appears multiple times in the same API: ${lang}`);
69
- }
70
- if (lang === 'openapi' || lang === 'sql') continue;
71
- this.languages.add(lang);
72
- this.specs[lang] = spec;
73
- }
74
- }
75
- }
76
- }
77
-
78
- /** Runs once in the build process */
79
- export async function startSpecLoader(
80
- pluginConfig: NormalizedStainlessStarlightConfig,
81
- logger: AstroIntegrationLogger,
82
- codegenDir: URL,
83
- ) {
84
- const specsDirectory = path.join(codegenDir.pathname, 'specs');
85
- await mkdir(specsDirectory, { recursive: true });
86
-
87
- logger.debug(`Setting cache directory to ${specsDirectory}`);
88
-
89
- // 🚨 Important! You cannot call loadSpecs() before setting the cache directory.
90
- specCache.setCacheDirectory(specsDirectory);
91
-
92
- async function load() {
93
- const specs = await pluginConfig.api.loadSpecs();
94
-
95
- // not awaited since it's just cleanup
96
- specCache.cleanupUnusedFiles().then((result) => {
97
- if (result.deletedCount > 0) {
98
- logger.info(`Cleaned up ${result.deletedCount} unused spec files`);
99
- } else {
100
- logger.debug(`No unused spec files to clean up`);
101
- }
102
- });
103
-
104
- return {
105
- specComposite: new SpecComposite(specs),
106
- };
107
- }
108
-
109
- const specPromise = load();
110
-
111
- return {
112
- specPromise,
113
- // this virtual module only resolves when the spec is generated
114
- // this prevents the SSR module from trying to read the spec file before it's generated
115
- vitePlugins: [
116
- makeAsyncVirtualModPlugin<typeof VirtualManifestModule>('virtual:stainless-apis-manifest', async () => {
117
- const api = await specPromise;
118
-
119
- return {
120
- api: {
121
- languages: api.specComposite.listAllLanguagesAndIncludeSpecs().map((langSpec) => ({
122
- language: langSpec.language,
123
- sdkJSONFilePath: langSpec.spec.filePath,
124
- })),
125
- },
126
- };
127
- }),
128
- ],
129
- };
130
- }
131
-
132
- export type SpecLoader = Awaited<ReturnType<typeof startSpecLoader>>;
@@ -1,146 +0,0 @@
1
- import { DocsLanguage } from '@stainless-api/docs-ui/routing';
2
- import { readFile } from 'fs/promises';
3
- import { AstroIntegrationLogger } from 'astro';
4
- import { bold } from '../../shared/terminalUtils';
5
- import type { LanguageGenerateQuery, LoadedApiKey } from '../loadPluginConfig';
6
- import Stainless, { APIError } from '@stainless-api/sdk';
7
- import { GenerateSpecRawInputs } from './generateSpec';
8
-
9
- export type SpecInputResolver = {
10
- resolve: (context: { apiKey: LoadedApiKey | null }) => Promise<GenerateSpecRawInputs>;
11
- printError: (error: Error, logger: AstroIntegrationLogger) => void;
12
- };
13
-
14
- function fromFiles({
15
- oasPath,
16
- configPath,
17
- languageOverrides,
18
- stainlessProject,
19
- }: {
20
- oasPath: string;
21
- configPath: string;
22
- languageOverrides: LanguageGenerateQuery | null;
23
- stainlessProject: string;
24
- }): SpecInputResolver {
25
- return {
26
- resolve: async () => {
27
- const oasStr = await readFile(oasPath, 'utf8');
28
- const configStr = await readFile(configPath, 'utf8');
29
- return {
30
- oasStr,
31
- configStr,
32
- versionInfo: null,
33
- languageOverrides,
34
- stainlessProject,
35
- };
36
- },
37
- printError: (error: Error, logger: AstroIntegrationLogger) => {
38
- logger.error(bold('Failed to resolve spec inputs from files:'));
39
- logger.error(error.message);
40
- },
41
- };
42
- }
43
-
44
- async function fetchVersionInfo(project: string, apiKey: string): Promise<Record<DocsLanguage, string>> {
45
- const data = await fetch(`https://api.stainless.com/api/projects/${project}/package-versions`, {
46
- headers: { Authorization: `Bearer ${apiKey}` },
47
- });
48
-
49
- const content = await data.text();
50
- return JSON.parse(content) as Record<DocsLanguage, string>;
51
- }
52
-
53
- function redactApiKey(apiKey: string) {
54
- return apiKey
55
- .split('')
56
- .map((char, index) => (index < 10 ? char : '*'))
57
- .join('');
58
- }
59
-
60
- function fromStainlessApi(inputs: {
61
- stainlessProject: string;
62
- branch: string;
63
- apiKey?: LoadedApiKey;
64
- languageOverrides: LanguageGenerateQuery | null;
65
- }): SpecInputResolver {
66
- let apiKey: string | undefined;
67
- return {
68
- async resolve(context) {
69
- apiKey = context.apiKey?.value ?? inputs.apiKey?.value;
70
-
71
- if (!apiKey) {
72
- throw new Error('No API key provided');
73
- }
74
-
75
- const client = new Stainless({ apiKey });
76
- const configs = await client.projects.configs.retrieve({
77
- project: inputs.stainlessProject,
78
- branch: inputs.branch,
79
- include: 'openapi',
80
- });
81
- const versionInfo = await fetchVersionInfo(inputs.stainlessProject, apiKey);
82
-
83
- const configYML = Object.values(configs)[0] as { content: unknown };
84
- const oasJson = Object.values(configs)[1] as { content: unknown };
85
- const oasStr = oasJson['content'];
86
- const configStr = configYML['content'];
87
-
88
- if (typeof oasStr !== 'string' || typeof configStr !== 'string') {
89
- throw new Error('Received invalid OAS or config from Stainless');
90
- }
91
-
92
- return {
93
- oasStr,
94
- configStr,
95
- versionInfo,
96
- languageOverrides: inputs.languageOverrides,
97
- stainlessProject: inputs.stainlessProject,
98
- };
99
- },
100
- printError: (error: Error, logger: AstroIntegrationLogger) => {
101
- if (error instanceof APIError && error.status >= 400 && error.status < 500) {
102
- logger.error(`Requested project slug: "${inputs.stainlessProject}"`);
103
- if (apiKey) {
104
- logger.error(`API key: "${redactApiKey(apiKey)}"`);
105
- }
106
- logger.error(
107
- `This error can usually be corrected by re-authenticating with the Stainless. Use the CLI (stl auth login) or verify that the Stainless API key you're using can access the project mentioned above.`,
108
- );
109
- }
110
- },
111
- };
112
- }
113
-
114
- function fromStrings({
115
- oasStr,
116
- configStr,
117
- languageOverrides,
118
- stainlessProject,
119
- }: {
120
- oasStr: string;
121
- configStr: string;
122
- languageOverrides: LanguageGenerateQuery | null;
123
- stainlessProject: string;
124
- }): SpecInputResolver {
125
- return {
126
- async resolve() {
127
- return {
128
- oasStr,
129
- configStr,
130
- versionInfo: null,
131
- languageOverrides,
132
- stainlessProject,
133
- };
134
- },
135
- printError(error: Error, logger: AstroIntegrationLogger) {
136
- logger.error(bold('Failed to resolve spec inputs from strings:'));
137
- logger.error(error.message);
138
- },
139
- };
140
- }
141
-
142
- export const resolveSpec = {
143
- fromFiles,
144
- fromStainlessApi,
145
- fromStrings,
146
- } satisfies Record<string, (...args: never[]) => SpecInputResolver>;
@@ -1,199 +0,0 @@
1
- import Worker from 'web-worker';
2
- import { Languages, type DocsLanguage } from '@stainless-api/docs-ui/routing';
3
- import type * as SDKJSON from '@stainless/sdk-json';
4
- import { fileURLToPath } from 'node:url';
5
- import { dirname, resolve } from 'node:path';
6
- import fs from 'fs/promises';
7
- import pathutils from 'path';
8
-
9
- const __filename = fileURLToPath(import.meta.url);
10
- const __dirname = dirname(__filename);
11
-
12
- const workerPath = resolve(__dirname, '..', 'vendor', 'preview.worker.docs.js');
13
-
14
- type OpenAPIDocument = Record<string, any>;
15
- export type ParsedConfig = {
16
- docs:
17
- | {
18
- title?: string | undefined;
19
- favicon?: string | undefined;
20
- logo_icon?: string | undefined;
21
- search?:
22
- | {
23
- algolia?:
24
- | {
25
- app_id: string;
26
- index_name: string;
27
- search_key: string;
28
- }
29
- | undefined;
30
- }
31
- | undefined;
32
- description?: string | undefined;
33
- languages?:
34
- | ('node' | 'typescript' | 'python' | 'java' | 'kotlin' | 'go' | 'ruby' | 'terraform' | 'http')[]
35
- | undefined;
36
- snippets?:
37
- | {
38
- exclude_languages?: string[] | undefined;
39
- }
40
- | undefined;
41
- show_security?: boolean | undefined;
42
- show_readme?: boolean | undefined;
43
- base_path?: string | undefined;
44
- navigation?:
45
- | {
46
- menubar?:
47
- | {
48
- title: string;
49
- icon?: string;
50
- variant?: string;
51
- href?: string | undefined;
52
- page?: string | undefined;
53
- }[]
54
- | undefined;
55
- sidebar?:
56
- | {
57
- title: string;
58
- icon?: string;
59
- variant?: string;
60
- href?: string | undefined;
61
- page?: string | undefined;
62
- }[]
63
- | undefined;
64
- }
65
- | undefined;
66
- pages?: unknown;
67
- resources?: unknown[] | undefined;
68
- }
69
- | undefined;
70
- targets: Record<string, { skip?: boolean }>;
71
- client_settings: {
72
- opts: {
73
- [x: string]: {
74
- type: 'string' | 'number' | 'boolean' | 'null' | 'integer';
75
- nullable: boolean;
76
- description?: string | undefined;
77
- example?: unknown;
78
- default?: unknown;
79
- read_env?: string | undefined;
80
- auth?:
81
- | {
82
- security_scheme: string;
83
- role?: 'value' | 'password' | 'username' | 'client_id' | 'client_secret' | undefined;
84
- }
85
- | undefined;
86
- };
87
- };
88
- };
89
- };
90
-
91
- function runJob({ type, signal, data }: { type: string; signal?: AbortSignal; data: any }) {
92
- const stainlessWorker = new Worker(workerPath, {
93
- type: 'module',
94
- name: 'Preview server',
95
- });
96
-
97
- return new Promise<any>((resolve, reject) => {
98
- stainlessWorker.addEventListener('error', (e) => {
99
- e.preventDefault();
100
- reject(e);
101
- });
102
-
103
- stainlessWorker.addEventListener('messageerror', (e) => {
104
- reject(e);
105
- });
106
-
107
- stainlessWorker.addEventListener('message', (message) => {
108
- if (message.data.type === `${type}_done`) {
109
- resolve(message.data);
110
- } else if (message.data.type === `${type}_failed`) {
111
- const { name, message: errorMessage } = message.data;
112
- const err = new Error(errorMessage);
113
- err.name = name;
114
- reject(err);
115
- }
116
- });
117
-
118
- if (signal) {
119
- signal.onabort = () => reject({ type: 'abort' });
120
- }
121
-
122
- if (signal?.aborted) {
123
- reject({ type: 'abort' });
124
- }
125
-
126
- stainlessWorker.postMessage({ ...data, type });
127
- }).finally(() => {
128
- stainlessWorker.terminate();
129
- });
130
- }
131
-
132
- export async function parseInputs({ oas, config }: { oas: string; config: string }) {
133
- const result = await runJob({
134
- type: 'parse',
135
- data: {
136
- oas,
137
- config,
138
- },
139
- });
140
-
141
- return result as {
142
- oas: OpenAPIDocument;
143
- config: ParsedConfig;
144
- };
145
- }
146
-
147
- export async function transformOAS({ oas, config }: { oas: OpenAPIDocument; config: ParsedConfig }) {
148
- const result = await runJob({
149
- type: 'transform',
150
- data: {
151
- oas,
152
- config,
153
- },
154
- });
155
-
156
- return result.transformedOAS;
157
- }
158
-
159
- export async function createSDKJSON({
160
- oas,
161
- config,
162
- languages,
163
- projectName,
164
- }: {
165
- oas: OpenAPIDocument;
166
- config: ParsedConfig;
167
- languages: DocsLanguage[];
168
- projectName: string;
169
- }) {
170
- const templatePath = resolve(__dirname, '../vendor/templates');
171
- const readmeLoader = await Promise.all(
172
- Languages.map(async (language) => {
173
- const mdfile = pathutils.join(templatePath, `${language}.md`);
174
-
175
- try {
176
- const content = await fs.readFile(mdfile);
177
- return [language, content.toString()];
178
- } catch {
179
- return [language, null];
180
- }
181
- }),
182
- );
183
-
184
- const readmeTemplates = Object.fromEntries(readmeLoader);
185
-
186
- const result = await runJob({
187
- type: 'preview',
188
- data: {
189
- oas,
190
- config,
191
- languages,
192
- transform: false,
193
- projectName,
194
- readmeTemplates,
195
- },
196
- });
197
-
198
- return result.spec as SDKJSON.Spec;
199
- }