@stainless-api/docs 0.1.0-beta.137 → 0.1.0-beta.139

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.
@@ -1,109 +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?.install && meta?.version) {
89
- meta.install = meta.install.replace(meta.version, version);
90
- }
91
-
92
- if (meta?.version) meta.version = version;
93
- }
94
- }
95
-
96
- return {
97
- sdkJson,
98
- languages,
99
- };
100
- }
101
-
102
- export const specCache = new FileCache({
103
- generate: generateSpecFromStrings,
104
- globalHashBits: previewWorkerCode, // you can change this as a last resort to invalidate the cache
105
- });
106
-
107
- export type SpecCacheResult = Awaited<ReturnType<typeof specCache.get>>;
108
-
109
- export type SpecWithAuth = Awaited<ReturnType<typeof generateSpecFromStrings>>;
@@ -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 } 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
- /**
15
- * A helper class to manage multiple spec cache results for a single API
16
- * An API may have multiple spec cache results if it has multiple languages
17
- * Note that one spec may contain multiple languages.
18
- * */
19
- export class SpecComposite {
20
- private languages: Set<SDKJSON.SpecLanguage>;
21
- private readonly specs: Partial<Record<SDKJSON.SpecLanguage, SpecCacheResult>>;
22
-
23
- public getLanguages() {
24
- return Array.from(this.languages);
25
- }
26
-
27
- public getByLanguage(language: SDKJSON.SpecLanguage) {
28
- const spec = this.specs[language];
29
- if (!spec) {
30
- throw new Error(`Spec for language ${language} not found`);
31
- }
32
- return spec;
33
- }
34
-
35
- /**
36
- * Returns all specs. It will return each spec once, even if it has multiple languages.
37
- * */
38
- public listUniqueSpecs() {
39
- const seen = new Set<SpecCacheResult>();
40
- const unique: SpecCacheResult[] = [];
41
- for (const spec of Object.values(this.specs)) {
42
- if (!seen.has(spec)) {
43
- seen.add(spec);
44
- unique.push(spec);
45
- }
46
- }
47
- return unique;
48
- }
49
-
50
- public listAllLanguagesAndIncludeSpecs() {
51
- return this.getLanguages().map((language) => ({
52
- language,
53
- spec: this.getByLanguage(language),
54
- }));
55
- }
56
-
57
- constructor(specs: SpecCacheResult[]) {
58
- this.languages = new Set<SDKJSON.SpecLanguage>();
59
- this.specs = {};
60
- for (const spec of specs) {
61
- for (const lang of spec.data.languages) {
62
- if (this.languages.has(lang)) {
63
- throw new Error(`Language appears multiple times in the same API: ${lang}`);
64
- }
65
- if (lang === 'openapi' || lang === 'sql') continue;
66
- this.languages.add(lang);
67
- this.specs[lang] = spec;
68
- }
69
- }
70
- }
71
- }
72
-
73
- /** Runs once in the build process */
74
- export async function startSpecLoader(
75
- pluginConfig: NormalizedStainlessStarlightConfig,
76
- logger: AstroIntegrationLogger,
77
- codegenDir: URL,
78
- ) {
79
- const specsDirectory = path.join(codegenDir.pathname, 'specs');
80
- await mkdir(specsDirectory, { recursive: true });
81
-
82
- logger.debug(`Setting cache directory to ${specsDirectory}`);
83
-
84
- // 🚨 Important! You cannot call loadSpecs() before setting the cache directory.
85
- specCache.setCacheDirectory(specsDirectory);
86
-
87
- async function load() {
88
- const specs = await pluginConfig.api.loadSpecs();
89
-
90
- // not awaited since it's just cleanup
91
- specCache
92
- .cleanupUnusedFiles()
93
- .then((result) => {
94
- if (result.deletedCount > 0) {
95
- logger.info(`Cleaned up ${result.deletedCount} unused spec files`);
96
- } else {
97
- logger.debug(`No unused spec files to clean up`);
98
- }
99
- })
100
- .catch(() => {
101
- logger.warn(`Failed to clean up unused spec files`);
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,148 +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: {
11
- apiKey: LoadedApiKey | null;
12
- }) => GenerateSpecRawInputs | Promise<GenerateSpecRawInputs>;
13
- printError: (error: Error, logger: AstroIntegrationLogger) => void;
14
- };
15
-
16
- function fromFiles({
17
- oasPath,
18
- configPath,
19
- languageOverrides,
20
- stainlessProject,
21
- }: {
22
- oasPath: string;
23
- configPath: string;
24
- languageOverrides: LanguageGenerateQuery | null;
25
- stainlessProject: string;
26
- }): SpecInputResolver {
27
- return {
28
- resolve: async () => {
29
- const oasStr = await readFile(oasPath, 'utf8');
30
- const configStr = await readFile(configPath, 'utf8');
31
- return {
32
- oasStr,
33
- configStr,
34
- versionInfo: null,
35
- languageOverrides,
36
- stainlessProject,
37
- };
38
- },
39
- printError: (error: Error, logger: AstroIntegrationLogger) => {
40
- logger.error(bold('Failed to resolve spec inputs from files:'));
41
- logger.error(error.message);
42
- },
43
- };
44
- }
45
-
46
- async function fetchVersionInfo(project: string, apiKey: string): Promise<Record<DocsLanguage, string>> {
47
- const data = await fetch(`https://api.stainless.com/api/projects/${project}/package-versions`, {
48
- headers: { Authorization: `Bearer ${apiKey}` },
49
- });
50
-
51
- const content = await data.text();
52
- return JSON.parse(content) as Record<DocsLanguage, string>;
53
- }
54
-
55
- function redactApiKey(apiKey: string) {
56
- return apiKey
57
- .split('')
58
- .map((char, index) => (index < 10 ? char : '*'))
59
- .join('');
60
- }
61
-
62
- function fromStainlessApi(inputs: {
63
- stainlessProject: string;
64
- branch: string;
65
- apiKey?: LoadedApiKey;
66
- languageOverrides: LanguageGenerateQuery | null;
67
- }): SpecInputResolver {
68
- let apiKey: string | undefined;
69
- return {
70
- async resolve(context) {
71
- apiKey = context.apiKey?.value ?? inputs.apiKey?.value;
72
-
73
- if (!apiKey) {
74
- throw new Error('No API key provided');
75
- }
76
-
77
- const client = new Stainless({ apiKey });
78
- const configs = await client.projects.configs.retrieve({
79
- project: inputs.stainlessProject,
80
- branch: inputs.branch,
81
- include: 'openapi',
82
- });
83
- const versionInfo = await fetchVersionInfo(inputs.stainlessProject, apiKey);
84
-
85
- const configYML = Object.values(configs)[0] as { content: unknown };
86
- const oasJson = Object.values(configs)[1] as { content: unknown };
87
- const oasStr = oasJson['content'];
88
- const configStr = configYML['content'];
89
-
90
- if (typeof oasStr !== 'string' || typeof configStr !== 'string') {
91
- throw new Error('Received invalid OAS or config from Stainless');
92
- }
93
-
94
- return {
95
- oasStr,
96
- configStr,
97
- versionInfo,
98
- languageOverrides: inputs.languageOverrides,
99
- stainlessProject: inputs.stainlessProject,
100
- };
101
- },
102
- printError: (error: Error, logger: AstroIntegrationLogger) => {
103
- if (error instanceof APIError && error.status >= 400 && error.status < 500) {
104
- logger.error(`Requested project slug: "${inputs.stainlessProject}"`);
105
- if (apiKey) {
106
- logger.error(`API key: "${redactApiKey(apiKey)}"`);
107
- }
108
- logger.error(
109
- `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.`,
110
- );
111
- }
112
- },
113
- };
114
- }
115
-
116
- function fromStrings({
117
- oasStr,
118
- configStr,
119
- languageOverrides,
120
- stainlessProject,
121
- }: {
122
- oasStr: string;
123
- configStr: string;
124
- languageOverrides: LanguageGenerateQuery | null;
125
- stainlessProject: string;
126
- }): SpecInputResolver {
127
- return {
128
- resolve() {
129
- return {
130
- oasStr,
131
- configStr,
132
- versionInfo: null,
133
- languageOverrides,
134
- stainlessProject,
135
- };
136
- },
137
- printError(error: Error, logger: AstroIntegrationLogger) {
138
- logger.error(bold('Failed to resolve spec inputs from strings:'));
139
- logger.error(error.message);
140
- },
141
- };
142
- }
143
-
144
- export const resolveSpec = {
145
- fromFiles,
146
- fromStainlessApi,
147
- fromStrings,
148
- } 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
- }