### Clone and Install Swagger Editor Source: https://github.com/swagger-api/swagger-editor/blob/main/README.md Clone the repository and install dependencies to set up the project for local development. ```sh $ git clone https://github.com/swagger-api/swagger-editor.git $ cd swagger-editor $ npm i $ npm start ``` -------------------------------- ### Composing Swagger Editor with SwaggerUI Source: https://github.com/swagger-api/swagger-editor/blob/main/README.md Example of initializing SwaggerUI with a comprehensive set of Swagger Editor plugins. This configuration is suitable for creating a feature-rich editor. ```javascript import SwaggerUI from 'swagger-ui'; import 'swagger-ui/dist/swagger-ui.css'; import UtilPlugin from 'swagger-editor/plugins/util'; import VersionsPlugin from 'swaggereditor/plugins/versions'; import ModalsPlugin from 'swagger-editor/plugins/modals'; import DialogsPlugin from 'swagger-editor/plugins/dialogs'; import DropdownMenuPlugin from 'swagger-editor/plugins/dropdown-menu'; import DropzonePlugin from 'swagger-editor/plugins/dropzone'; import VersionsPlugin from 'swagger-editor/plugins/versions'; import EditorTextareaPlugin from 'swagger-editor/plugins/editor-textarea'; import EditorMonacoPlugin from 'swagger-editor/plugins/editor-monaco'; import EditorMonacoYamlPastePlugin from 'swagger-editor/plugins/editor-monaco-yaml-paste'; import EditorMonacoLanguageApiDOMPlugin from 'swagger-editor/plugins/editor-monaco-language-apidom'; import EditorContentReadOnlyPlugin from 'swagger-editor/plugins/editor-content-read-only'; import EditorContentOriginPlugin from 'swagger-editor/plugins/editor-content-origin'; import EditorContentTypePlugin from 'swagger-editor/plugins/editor-content-type'; import EditorContentPersistencePlugin from 'swagger-editor/plugins/editor-content-persistence'; import EditorContentFixturesPlugin from 'swagger-editor/plugins/editor-content-fixtures'; import EditorContentFromFilePlugin from 'swagger-editor/plugins/editor-content-from-file'; import EditorPreviewPlugin from 'swagger-editor/plugins/editor-preview'; import EditorPreviewSwaggerUIPlugin from 'swagger-editor/plugins/editor-preview-swagger-ui'; import EditorPreviewAsyncAPIPlugin from 'swagger-editor/plugins/editor-preview-asyncapi'; import EditorPreviewApiDesignSystemsPlugin from 'swagger-editor/plugins/editor-preview-api-design-systems'; import TopBarPlugin from 'swagger-editor/plugins/top-bar'; import SplashScreenPlugin from 'swagger-editor/plugins/splash-screen'; import LayoutPlugin from 'swagger-editor/plugins/layout'; import EditorSafeRenderPlugin from 'swagger-editor/plugins/editor-safe-render'; SwaggerUI({ url: 'https://petstore.swagger.io/v2/swagger.json', dom_id: '#swagger-editor', plugins: [ UtilPlugin, VersionsPlugin, ModalsPlugin, DialogsPlugin, DropdownMenuPlugin, DropzonePlugin, VersionsPlugin, EditorTextareaPlugin, EditorMonacoPlugin, EditorMonacoYamlPastePlugin, EditorMonacoLanguageApiDOMPlugin, EditorContentReadOnlyPlugin, EditorContentOriginPlugin, EditorContentTypePlugin, EditorContentPersistencePlugin, EditorContentFixturesPlugin, EditorContentFromFilePlugin, EditorPreviewPlugin, EditorPreviewSwaggerUIPlugin, EditorPreviewAsyncAPIPlugin, EditorPreviewApiDesignSystemsPlugin, TopBarPlugin, SplashScreenPlugin, LayoutPlugin, EditorSafeRenderPlugin, ], layout: 'StandaloneLayout', }); ``` -------------------------------- ### Integrate Swagger Editor via UMD Bundle Source: https://github.com/swagger-api/swagger-editor/blob/main/README.md Example HTML demonstrating how to include and initialize Swagger Editor using the UMD bundle, loading a remote OpenAPI specification. ```html SwaggerEditor
``` -------------------------------- ### Install Swagger Editor via npm Source: https://github.com/swagger-api/swagger-editor/blob/main/README.md Install the Swagger Editor npm package using the npm CLI. Ensure Node.js version is compatible and prerequisites are met. ```sh $ npm install swagger-editor@alpha ``` -------------------------------- ### Start Script with Hot-Reloading (v5) Source: https://github.com/swagger-api/swagger-editor/blob/main/docs/migration.md Use `npm start` for development with hot-reloading in SwaggerEditor v5. This replaces the `npm run dev` command from v4. ```bash $ npm start ``` -------------------------------- ### Add E2E Tests with Playwright Source: https://github.com/swagger-api/swagger-editor/blob/main/CLAUDE.md Write end-to-end tests for your plugin features using Playwright. This example demonstrates setting up tests within a describe block, using beforeEach hooks for common setup like visiting a blank page and waiting for the splash screen, and asserting element visibility after an action. ```typescript // test/playwright/e2e/plugin.my-feature.spec.ts import { test, expect } from '@playwright/test'; import { visitBlankPage, waitForSplashScreen } from '../helpers'; test.describe('My Feature', () => { test.beforeEach(async ({ page }) => { await visitBlankPage(page); await waitForSplashScreen(page); }); test('should perform action', async ({ page }) => { await page.locator('[data-testid="my-button"]').click(); await expect(page.locator('text=Expected Result')).toBeVisible(); }); }); ``` -------------------------------- ### Static Build Script (v5) Source: https://github.com/swagger-api/swagger-editor/blob/main/docs/migration.md SwaggerEditor v5 uses `npm run build:app` and `npm run build:app:serve` for static builds, replacing the `npm start` command used in v4. ```bash $ npm run build:app $ npm run build:app:serve ``` -------------------------------- ### Install Dependencies for Alternative Webpack Config Source: https://github.com/swagger-api/swagger-editor/blob/main/README.md Installs CopyWebpackPlugin and other necessary dependencies for the alternative Webpack 5 configuration that utilizes pre-built Web Worker artifacts. ```sh $ npm i copy-webpack-plugin --save-dev $ npm i stream-browserify --save-dev $ npm i https-browserify --save-dev $ npm i stream-http --save-dev $ npm i util --save-dev $ npm i buffer --save-dev $ npm i process --save-dev ``` -------------------------------- ### Static Worker Extension Entry Point Source: https://github.com/swagger-api/swagger-editor/blob/main/docs/customization/plug-points/editor-monaco-language-apidom.md For static extension, define a custom worker entry point file. This example shows how to import necessary functions, extend the `ApiDOMWorker` class, and initialize the worker. ```javascript import { initialize, makeCreate, ApiDOMWorker } from 'swagger-editor/apidom.worker'; class ApiDOMWorkerExtended extends ApiDOMWorker { // implementation of extensions } const create = makeCreate(ApiDOMWorkerExtended); initialize((ctx, createData) => create(ctx, createData)); export { initialize, create, makeCreate, ApiDOMWorkerExtended as ApiDOMWorker }; ``` -------------------------------- ### Webpack Configuration for Static Worker Source: https://github.com/swagger-api/swagger-editor/blob/main/docs/customization/plug-points/editor-monaco-language-apidom.md Configure your bundler, such as webpack, to use the custom worker entry point. This example shows how to define the `entry` configuration for `apidom.worker`. ```javascript entry: { app: './index.js', 'apidom.worker': './my-custom-apidom.worker.js', 'editor.worker': 'swagger-editor/editor.worker', } ``` -------------------------------- ### Install Webpack 5 Dependencies for Swagger Editor Source: https://github.com/swagger-api/swagger-editor/blob/main/README.md Installs the necessary npm packages for Webpack 5 to correctly build Swagger Editor, including stream and buffer polyfills. ```sh $ npm i stream-browserify --save-dev $ npm i https-browserify --save-dev $ npm i stream-http --save-dev $ npm i util --save-dev $ npm i buffer --save-dev $ npm i process --save-dev ``` -------------------------------- ### Loading WASM grammar with Language.load() Source: https://github.com/swagger-api/swagger-editor/blob/main/docs/wasm-bundling.md This example shows how grammar WASM files are imported as ES modules and then loaded using `Language.load()`. This method is used by apidom parser adapters for YAML and JSON, and it requires the WASM to be provided as a URL string or a `Uint8Array`. ```javascript // @swagger-api/apidom-parser-adapter-yaml-1-2/src/lexical-analysis/browser.mjs import treeSitterYaml from '../../wasm/tree-sitter-yaml.wasm'; // ... await Language.load(treeSitterYaml); ``` -------------------------------- ### Integrate SwaggerEditor Preview Plugins with SwaggerUI Standalone Source: https://github.com/swagger-api/swagger-editor/blob/main/README.md Configure SwaggerUI in standalone mode to render API definitions using SwaggerEditor preview plugins. This setup includes the 'StandaloneLayout' and ensures all required plugins are imported. ```javascript import SwaggerUI from 'swagger-ui'; import SwaggerUIStandalonePreset from 'swagger-ui/dist/swagger-ui-standalone-preset'; import 'swagger-ui/dist/swagger-ui.css'; import 'swagger-editor/swagger-editor.css'; import EditorContentOriginPlugin from 'swagger-editor/plugins/editor-content-origin'; import EditorContentTypePlugin from 'swagger-editor/plugins/editor-content-type'; import EditorPreviewAsyncAPIPlugin from 'swagger-editor/plugins/editor-preview-asyncapi'; import EditorPreviewAPIDesignSystemsPlugin from 'swagger-editor/plugins/editor-preview-api-design-systems'; import SwaggerUIAdapterPlugin from 'swagger-editor/plugins/swagger-ui-adapter'; SwaggerUI({ url: 'https://petstore.swagger.io/v2/swagger.json', dom_id: '#swagger-ui', presets: [SwaggerUI.presets.apis, SwaggerUIStandalonePreset], plugins: [ EditorContentOriginPlugin, EditorContentTypePlugin, EditorPreviewAsyncAPIPlugin, EditorPreviewAPIDesignSystemsPlugin, SwaggerUIAdapterPlugin, SwaggerUI.plugins.DownloadUrl, ], layout: 'StandaloneLayout', }); ``` -------------------------------- ### ApiDOM Worker Dynamic Extension Example: Change Log Level Source: https://github.com/swagger-api/swagger-editor/blob/main/docs/customization/plug-points/editor-monaco-language-apidom.md An example of dynamically extending the ApiDOM worker to change the language service log level to ERROR. It extends the base `ApiDOMWorkerClass` and modifies its static `apiDOMContext`. ```javascript export const customApiDOMWorkerFactory = (ApiDOMWorkerClass, toolbelt) => { const { apidomLS } = toolbelt; class ApiDOMWorkerLogLevelErrorClass extends ApiDOMWorkerClass { static apiDOMContext = { ...ApiDOMWorkerClass.apiDOMContext, logLevel: apidomLS.LogLevel.ERROR, }; } return ApiDOMWorkerLogLevelErrorClass; }; ``` -------------------------------- ### E2E Test Template with Playwright Source: https://github.com/swagger-api/swagger-editor/blob/main/CLAUDE.md A standard template for writing end-to-end tests using Playwright in TypeScript. Includes setup for visiting a blank page and waiting for the splash screen. ```typescript import { test, expect } from '@playwright/test'; import { visitBlankPage, waitForSplashScreen } from '../helpers'; test.describe('Feature Name', () => { test.beforeEach(async ({ page }) => { await visitBlankPage(page); await waitForSplashScreen(page); }); test('should do something', async ({ page }) => { await page.locator('[data-testid="some-element"]').click(); await expect(page.locator('text=Expected Text')).toBeVisible(); }); }); ``` -------------------------------- ### SwaggerClient Response APIs Source: https://github.com/swagger-api/swagger-editor/blob/main/docs/swagger-client.md When performing a fetch GET call to `SwaggerClient(url, [options])`, the response includes `response.apis` methods. Remember to attach `.catch()` to any `response.apis.[method]` call. ```javascript response.apis: - clients: - clientOptions: ƒ(parameters) - downloadFile: ƒ(parameters) - generateClient: ƒ(parameters) - getClientOptions: ƒ(parameters) response.apis.servers: - downloadFile: ƒ(parameters) - generateServerForLanguage: ƒ(parameters) - getServerOptions: ƒ(parameters) - serverOptions: ƒ(parameters) ``` -------------------------------- ### Define Editor Content Action Source: https://github.com/swagger-api/swagger-editor/blob/main/CLAUDE.md Defines an action type and a creator function for setting the editor content. Also includes an example of an asynchronous thunk action for loading definition content from a URL. ```javascript export const SET_EDITOR_CONTENT = 'editor_set_content'; export const setEditorContent = (content) => ({ type: SET_EDITOR_CONTENT, payload: content }); // Async thunk export const loadDefinition = (url) => async (system) => { const { editorActions, fn } = system; const requestId = generateRequestId(); editorActions.loadDefinitionRequest({ url, requestId }); try { const content = await fn.fetchUrl(url); editorActions.loadDefinitionSuccess({ content, requestId }); } catch (error) { editorActions.loadDefinitionFailure({ error, requestId }); } }; ``` -------------------------------- ### Importing Swagger Editor Plugins Source: https://github.com/swagger-api/swagger-editor/blob/main/README.md Demonstrates how to import individual Swagger Editor plugins. Ensure the correct path for each plugin is used. ```javascript import EditorContentTypePlugin from 'swagger-editor/plugins/editor-content-type'; import EditorContentReadOnlyPlugin from 'swagger-editor/plugins/editor-content-read-only'; ``` -------------------------------- ### Typical Plugin File Structure Source: https://github.com/swagger-api/swagger-editor/blob/main/CLAUDE.md Illustrates the standard directory and file organization for a Swagger Editor plugin. ```text plugin-name/ ├── index.js ├── actions/index.js ├── reducers.js ├── selectors.js ├── components/ComponentName.jsx ├── components/ComponentName.scss ├── extensions/other-plugin/wrap-components/ComponentWrapper.jsx ├── after-load.js └── fn.js ``` -------------------------------- ### Build and Run Swagger Editor Locally (Unprivileged) Source: https://github.com/swagger-api/swagger-editor/blob/main/README.md Builds the Swagger Editor application and creates an unprivileged Docker image for local deployment. This uses a specific Dockerfile for unprivileged execution. ```bash $ npm run build:app $ docker build . -f Dockerfile.unprivileged -t swaggerapi/swagger-editor:latest-unprivileged $ docker run -d -p 8080:8080 swaggerapi/swagger-editor:latest-unprivileged ``` -------------------------------- ### Build-free SwaggerUI with Multi-Spec Support via unpkg.com Source: https://github.com/swagger-api/swagger-editor/blob/main/README.md Utilize unpkg.com to load SwaggerUI, SwaggerEditor, and their plugins directly in HTML for a build-free, multi-specification rendering environment. This approach is suitable for creating a standalone version without a build process. ```html
``` -------------------------------- ### Accessing System Properties in Plugins Source: https://github.com/swagger-api/swagger-editor/blob/main/CLAUDE.md Demonstrates how to destructure and utilize system properties like components, actions, selectors, and utility functions within a plugin. ```javascript const MyPlugin = (system) => { const { getComponent, editorActions, editorSelectors, fn } = system; const content = editorSelectors.selectEditorContent(); editorActions.setEditorContent('new content'); const MonacoEditor = getComponent('MonacoEditor'); }; ``` -------------------------------- ### Build and Run Swagger Editor Locally (Privileged) Source: https://github.com/swagger-api/swagger-editor/blob/main/README.md Builds the Swagger Editor application and then creates a Docker image for local deployment. This version requires privileged access. ```bash $ npm run build:app $ docker build . -t swaggerapi/swagger-editor:latest $ docker run -d -p 8080:80 swaggerapi/swagger-editor:latest ``` -------------------------------- ### Override ApiDOM Context Configuration Source: https://github.com/swagger-api/swagger-editor/blob/main/docs/customization/plug-points/editor-monaco-language-apidom.md Override the default ApiDOM Context configuration by passing the `apiDOMContext` option to the `EditorMonacoLanguageApiDOM` plugin. This example enables strict word filtering. ```javascript EditorMonacoLanguageApiDOM({ createData: { apiDOMContext: { completionContext: { enableLSPFilter: true, // enables "strict" word filtering (instead of default Monaco fuzzy matching; https://github.com/swagger-api/apidom/pull/2954) }, }, }, }); ``` -------------------------------- ### Importing Swagger Editor Presets Source: https://github.com/swagger-api/swagger-editor/blob/main/README.md Shows how to import available presets for Swagger Editor. Presets are collections of plugins designed to work together. ```javascript import TextareaPreset from 'swagger-editor/presets/textarea'; import MonacoPreset from 'swagger-editor/presets/monaco'; ``` -------------------------------- ### Manually Package Swagger Editor Source: https://github.com/swagger-api/swagger-editor/blob/main/README.md Commands to manually build the ESM and UMD bundles and create a package archive. ```sh $ npm run build:bundle:esm $ npm run build:bundle:umd $ npm pack ``` -------------------------------- ### Component Wrapping Pattern in Plugins Source: https://github.com/swagger-api/swagger-editor/blob/main/CLAUDE.md Shows how to wrap an original component with enhanced functionality, conditionally rendering a different component based on system state. Ensure the wrapper returns a new component, not the original directly. ```javascript // extensions/editor-preview/wrap-components/EditorPreviewWrapper.jsx const EditorPreviewWrapper = (Original, system) => { const EnhancedComponent = (props) => { const isOpenAPI = system.editorSelectors.selectIsContentTypeOpenAPI(); if (isOpenAPI) return ; return ; }; return EnhancedComponent; // must return new component, not Original directly }; export default EditorPreviewWrapper; ``` -------------------------------- ### Wrap Top Bar Component in React Source: https://github.com/swagger-api/swagger-editor/blob/main/CLAUDE.md Enhance the existing TopBar component by wrapping it with custom logic. This example shows how to conditionally display a banner before the original component. Register the wrapper in your plugin's configuration. ```javascript // src/plugins/my-plugin/extensions/top-bar/wrap-components/TopBarWrapper.jsx const TopBarWrapper = (Original, system) => { const Enhanced = (props) => { const showBanner = system.myPluginSelectors.selectShowBanner(); return ( <> {showBanner &&
Important Notice
} ); }; return Enhanced; }; // Register in plugin: wrapComponents: { TopBar: TopBarWrapper } ``` -------------------------------- ### Run Unit Tests with npm Source: https://github.com/swagger-api/swagger-editor/blob/main/README.md Execute unit tests in watch mode, for a single run, or with coverage reporting. ```sh $ npm test # watch mode $ npm run test:run # single run (CI) $ npm run test:coverage # with coverage report ``` -------------------------------- ### Lint Code with npm Source: https://github.com/swagger-api/swagger-editor/blob/main/README.md Run the linting script to check for code style and potential issues. ```sh $ npm run lint ``` -------------------------------- ### WASM Plugin Transform Hook Behavior Source: https://github.com/swagger-api/swagger-editor/blob/main/docs/wasm-bundling.md This simplified example illustrates how WASM plugins like `@rollup/plugin-wasm` use `load` and `transform` hooks. The `transform` hook replaces the module content with a loader function, which can cause issues if the `load` hook returns JavaScript instead of handling the WASM asset directly. ```javascript // @rollup/plugin-wasm — simplified load(id) { if (!/\.wasm$/.test(id)) return null; // reads file, emits asset }, transform(code, id) { if (code && /\.wasm$/.test(id)) { // replaces module content with the loader function code } } ``` -------------------------------- ### Enable ApiDOM Mode for Semantic Syntax Highlighting in Swagger Editor Source: https://github.com/swagger-api/swagger-editor/blob/main/README.md Configure Swagger Editor plugins to enable ApiDOM semantic token highlighting for more sophisticated syntax analysis in the Monaco editor. ```javascript import EditorMonacoLanguageApiDOMPlugin from 'swagger-editor/plugins/editor-monaco-language-apidom'; // Enable ApiDOM semantic token highlighting const plugins = [ EditorMonacoLanguageApiDOMPlugin({ useApiDOMSyntaxHighlighting: true }), // ... other plugins ]; ``` -------------------------------- ### Creating a New Plugin Structure Source: https://github.com/swagger-api/swagger-editor/blob/main/CLAUDE.md Provides a template for creating a new plugin within the Swagger Editor system. It outlines the structure for components, state plugins (initial state, actions, reducers, selectors), and how to export the plugin. ```javascript // src/plugins/my-plugin/index.js const MyPlugin = () => ({ components: { MyComponent: () =>
Hello from MyPlugin
}, statePlugins: { myPlugin: { initialState: Map({ data: null }), actions: { myAction: (payload) => ({ type: 'MY_ACTION', payload }) }, reducers: { MY_ACTION: (state, action) => state.set('data', action.payload) }, selectors: { selectData: createSelector((s) => s.get('myPlugin'), (s) => s.get('data')) }, }, }, }); export default MyPlugin; ``` -------------------------------- ### Configure MonacoEnvironment.getWorker for Workers Source: https://github.com/swagger-api/swagger-editor/blob/main/docs/workers.md Sets up the global MonacoEnvironment to dispatch requests to the appropriate worker based on the label. Ensure this is set after Monaco is loaded. ```javascript import EditorWorkerConstructor from '@codingame/monaco-vscode-api/workers/editor.worker?worker'; import ApidomWorkerConstructor from '../editor-monaco-language-apidom/language/apidom.worker.js?worker'; globalThis.MonacoEnvironment = { baseUrl: document.baseURI || location.href, getWorker(workerId, label) { if (label === 'apidom') return new ApidomWorkerConstructor(); return new EditorWorkerConstructor(); }, ...globalThis.MonacoEnvironment, }; ``` -------------------------------- ### MonacoEnvironment Defaults and Overrides Source: https://github.com/swagger-api/swagger-editor/blob/main/docs/workers.md Sets default MonacoEnvironment values and allows consumer overrides. Ensure this runs before any Monaco initialization. ```javascript globalThis.MonacoEnvironment = { // defaults first baseUrl: ..., getWorker(...) { ... }, // consumer overrides win ...globalThis.MonacoEnvironment, }; ``` -------------------------------- ### ApiDOM Worker Initialization after Vite Transform Source: https://github.com/swagger-api/swagger-editor/blob/main/docs/workers.md Shows how the ApiDOM worker's `initialize` function is imported after Vite's transform middleware has processed the file. This ensures that dependencies like Monaco's editor worker bootstrap are correctly resolved. ```javascript // Source (src/plugins/.../apidom.worker.js) import { initialize } from 'monaco-editor/esm/vs/editor/editor.worker.js'; // After Vite transform import { initialize } from '/node_modules/.vite/deps/monaco-editor_esm_vs_editor_editor__worker__js.js?v=...'; ``` -------------------------------- ### Build UMD Bundle Source: https://github.com/swagger-api/swagger-editor/blob/main/README.md Creates a UMD bundle that exports Swagger Editor as a global object, allowing consumers to use their own React versions. ```sh $ npm run build:bundle:umd ``` -------------------------------- ### Integrate SwaggerEditor Preview Plugins with SwaggerUI Source: https://github.com/swagger-api/swagger-editor/blob/main/README.md Use SwaggerUIAdapter plugin to integrate SwaggerEditor preview plugins for rendering AsyncAPI and API Design Systems definitions within SwaggerUI. Ensure all necessary SwaggerEditor plugins and SwaggerUI are imported. ```javascript import SwaggerUI from 'swagger-ui'; import SwaggerUIStandalonePreset from 'swagger-ui/dist/swagger-ui-standalone-preset'; import 'swagger-editor/swagger-editor.css'; import EditorContentOriginPlugin from 'swagger-editor/plugins/editor-content-origin'; import EditorContentTypePlugin from 'swagger-editor/plugins/editor-content-type'; import EditorPreviewAsyncAPIPlugin from 'swagger-editor/plugins/editor-preview-asyncapi'; import EditorPreviewAPIDesignSystemsPlugin from 'swagger-editor/plugins/editor-preview-api-design-systems'; import SwaggerUIAdapterPlugin from 'swagger-editor/plugins/swagger-ui-adapter'; SwaggerUI({ url: 'https://petstore.swagger.io/v2/swagger.json', dom_id: '#swagger-ui', presets: [SwaggerUI.presets.apis, SwaggerUIStandalonePreset], plugins: [ EditorContentOriginPlugin, EditorContentTypePlugin, EditorPreviewAsyncAPIPlugin, EditorPreviewAPIDesignSystemsPlugin, SwaggerUIAdapterPlugin, SwaggerUI.plugins.DownloadUrl, ], }); ``` -------------------------------- ### Build Swagger Editor Artifacts Source: https://github.com/swagger-api/swagger-editor/blob/main/README.md Build all Swagger Editor artifacts including app, esm, and umd bundles. ```sh $ npm run build ``` -------------------------------- ### Run E2E Tests with Playwright (CI) Source: https://github.com/swagger-api/swagger-editor/blob/main/README.md Execute end-to-end tests using Playwright in headless mode for Continuous Integration environments. ```sh $ npx playwright test # Run all tests headless ``` -------------------------------- ### Build ESM Bundle Source: https://github.com/swagger-api/swagger-editor/blob/main/README.md Creates an ESM bundle suitable for third-party applications with their own build processes. ```sh $ npm run build:bundle:esm ``` -------------------------------- ### File Naming Conventions Source: https://github.com/swagger-api/swagger-editor/blob/main/CLAUDE.md Specifies the naming conventions for various file types within the project to ensure consistency. ```text | Type | Convention | |------|-----------| | React Components | `PascalCase.jsx/tsx` | | Utilities | `kebab-case.js` | | Types | `kebab-case.d.ts` | | Styles (partials) | `_kebab-case.scss` | | Unit Tests | `ComponentName.test.jsx` | | E2E Tests | `feature.spec.ts` | ``` -------------------------------- ### Integrate Swagger UI React Component Source: https://github.com/swagger-api/swagger-editor/blob/main/README.md Demonstrates how to import and use the SwaggerUI component in a React application, including necessary plugins. Ensure the 'url' variable is defined in your scope. ```javascript import React from 'react'; import ReactDOM from 'react-dom'; import SwaggerUI from 'swagger-ui-react'; import 'swagger-ui-react/swagger-ui.css'; import UtilPlugin from 'swagger-editor/plugins/util'; import VersionsPlugin from 'swagger-editor/plugins/versions'; import ModalsPlugin from 'swagger-editor/plugins/modals'; import DialogsPlugin from 'swagger-editor/plugins/dialogs'; import DropdownMenuPlugin from 'swagger-editor/plugins/dropdown-menu'; import DropzonePlugin from 'swagger-editor/plugins/dropzone'; import VersionsPlugin from 'swagger-editor/plugins/versions'; import EditorTextareaPlugin from 'swagger-editor/plugins/editor-textarea'; import EditorMonacoPlugin from 'swagger-editor/plugins/editor-monaco'; import EditorMonacoYamlPastePlugin from 'swagger-editor/plugins/editor-monaco-yaml-paste'; import EditorMonacoLanguageApiDOMPlugin from 'swagger-editor/plugins/editor-monaco-language-apidom'; import EditorContentReadOnlyPlugin from 'swagger-editor/plugins/editor-content-read-only'; import EditorContentOriginPlugin from 'swagger-editor/plugins/editor-content-origin'; import EditorContentTypePlugin from 'swagger-editor/plugins/editor-content-type'; import EditorContentPersistencePlugin from 'swagger-editor/plugins/editor-content-persistence'; import EditorContentFixturesPlugin from 'swagger-editor/plugins/editor-content-fixtures'; import EditorContentFromFilePlugin from 'swagger-editor/plugins/editor-content-from-file'; import EditorPreviewPlugin from 'swagger-editor/plugins/editor-preview'; import EditorPreviewSwaggerUIPlugin from 'swagger-editor/plugins/editor-preview-swagger-ui'; import EditorPreviewAsyncAPIPlugin from 'swagger-editor/plugins/editor-preview-asyncapi'; import EditorPreviewApiDesignSystemsPlugin from 'swagger-editor/plugins/editor-preview-api-design-systems'; import TopBarPlugin from 'swagger-editor/plugins/top-bar'; import SplashScreenPlugin from 'swagger-editor/plugins/splash-screen'; import LayoutPlugin from 'swagger-editor/plugins/layout'; import EditorSafeRenderPlugin from 'swagger-editor/plugins/editor-safe-render'; const SwaggerEditor = () => { return ( ); }; ReactDOM.render(, document.getElementById('swagger-editor')); ``` -------------------------------- ### Configure Monaco Environment Before Rendering Source: https://github.com/swagger-api/swagger-editor/blob/main/CLAUDE.md Set the `MonacoEnvironment` configuration, specifically `baseUrl`, before rendering the SwaggerEditor component. This is crucial for Monaco Editor to locate its necessary files correctly. ```javascript self.MonacoEnvironment = { baseUrl: `${document.baseURI || location.href}dist/` }; ReactDOM.render(, document.getElementById('root')); ``` -------------------------------- ### Enable Simplified Syntax Highlighting Mode in Swagger Editor Source: https://github.com/swagger-api/swagger-editor/blob/main/README.md Configure Swagger Editor plugins to use the default simplified, regex-based syntax highlighting mode for the Monaco editor. ```javascript import EditorMonacoLanguageApiDOMPlugin from 'swagger-editor/plugins/editor-monaco-language-apidom'; // Default behavior - uses simplified syntax highlighting const plugins = [ EditorMonacoLanguageApiDOMPlugin, // ... other plugins ]; ``` -------------------------------- ### Integrate Swagger Editor in React App Source: https://github.com/swagger-api/swagger-editor/blob/main/README.md Demonstrates how to import and use the SwaggerEditor component in a React application. Ensure 'swagger-editor/swagger-editor.css' is imported for styling. ```javascript import React from 'react'; import ReactDOM from 'react-dom'; import SwaggerEditor from 'swagger-editor'; import 'swagger-editor/swagger-editor.css'; const url = "https://raw.githubusercontent.com/asyncapi/spec/v2.2.0/examples/streetlights-kafka.yml"; const MyApp = () => (

SwaggerEditor Integration

); self.MonacoEnvironment = { /** * We're building into the dist/ folder. When application starts on * URL=https://example.com then SwaggerEditor will look for * `apidom.worker.js` on https://example.com/dist/apidom.worker.js and * `editor.worker` on https://example.com/dist/editor.worker.js. */ baseUrl: `${document.baseURI || location.href}dist/` } ReactDOM.render(, document.getElementById('swagger-editor')); ``` -------------------------------- ### Swagger Editor Package Mapping Source: https://github.com/swagger-api/swagger-editor/blob/main/README.md Configuration in package.json that maps build artifacts to different module systems and entry points. ```json "unpkg": "./dist/umd/swagger-editor.js", "module": "./dist/esm/swagger-editor.js", "browser": "./dist/esm/swagger-editor.js", "jsnext:main": "./dist/esm/swagger-editor.js", "exports": { "./package.json": "./package.json", "./swagger-editor.css": "./dist/swagger-editor.css", ".": { "browser": "./dist/esm/swagger-editor.js" }, "./plugins/*": { "browser": "./dist/esm/plugins/*/index.js", "node": "./dist/esm/plugins/*/index.js" }, "./presets/*": { "browser": "./dist/esm/presets/*/index.js" }, "./apidom.worker": { "browser": "./dist/esm/apidom.worker.js" }, "./editor.worker": { "browser": "./dist/esm/editor.worker.js" } } ``` -------------------------------- ### Import Components with File Extensions Source: https://github.com/swagger-api/swagger-editor/blob/main/CLAUDE.md When importing local JavaScript/JSX components, always include the file extension (e.g., `.jsx`). Omitting extensions can lead to linting errors, except for TypeScript files which have specific ESLint overrides. ```javascript import Component from './Component.jsx'; // ✅ import Component from './Component'; // ❌ fails linting ``` -------------------------------- ### Accessing State and Actions in Components Source: https://github.com/swagger-api/swagger-editor/blob/main/CLAUDE.md Demonstrates how to access selectors and actions from the system hook within a React component to display editor content and loading status. ```javascript const MyComponent = () => { const { editorSelectors, editorActions } = useSystem(); const content = editorSelectors.selectEditorContent(); const isLoading = editorSelectors.selectIsLoading(); return
{isLoading ? 'Loading...' : content}
; }; ``` -------------------------------- ### Configure Webpack Plugins for Swagger Editor Source: https://github.com/swagger-api/swagger-editor/blob/main/README.md Integrate Webpack plugins such as ProvidePlugin for global variables and CopyWebpackPlugin for copying essential worker files to the build output. ```javascript plugins: [ new webpack.ProvidePlugin({ Buffer: ['buffer', 'Buffer'], process: ['process'], }), new CopyWebpackPlugin({ patterns: [ { from: 'node_modules/swagger-editor/dist/umd/apidom.worker.js', to: 'static/js', }, { from: 'node_modules/swagger-editor/dist/umd/editor.worker.js', to: 'static/js' } ] }), ], ``` -------------------------------- ### Vite OptimizeDeps Configuration for Workers Source: https://github.com/swagger-api/swagger-editor/blob/main/docs/workers.md Includes worker entry points in Vite's optimizeDeps to prevent cold-start optimization reloads. Used in vite.config.js. ```javascript optimizeDeps: { include: [ '@codingame/monaco-vscode-api/workers/editor.worker', 'monaco-editor/esm/vs/editor/editor.worker.js', ], } ``` -------------------------------- ### Emscripten Module Initialization Check Source: https://github.com/swagger-api/swagger-editor/blob/main/docs/wasm-bundling.md This snippet shows the logic within Emscripten's `getBinaryPromise` function that checks for `wasmBinary` in the `Module` object. If `wasmBinary` is present, it uses the inlined binary directly, bypassing the need for `fetch`. ```javascript function getBinaryPromise(path) { return wasmBinary // ← truthy → fetch is never called ? Promise.resolve().then(() => getBinarySync(path)) : readAsync(path)...; ``` -------------------------------- ### Run E2E Tests with Playwright (Development) Source: https://github.com/swagger-api/swagger-editor/blob/main/README.md Execute end-to-end tests using Playwright in development mode, with options for a visible browser, UI, or debug mode. ```sh $ npx playwright test --headed # Run with browser visible $ npx playwright test --ui # Run with Playwright UI $ npx playwright test --debug # Run in debug mode ``` -------------------------------- ### Increasing Node.js Memory for Large Builds Source: https://github.com/swagger-api/swagger-editor/blob/main/CLAUDE.md Sets the NODE_OPTIONS environment variable to increase the maximum old space size for Node.js, preventing Out-Of-Memory errors during large build processes. ```bash export NODE_OPTIONS="--max_old_space_size=4096" npm run build ``` -------------------------------- ### Configuring Monaco Environment for Web Workers Source: https://github.com/swagger-api/swagger-editor/blob/main/CLAUDE.md Sets the base URL for Monaco editor's web workers before rendering the editor. This ensures workers are accessible at runtime. ```javascript self.MonacoEnvironment = { baseUrl: `${document.baseURI || location.href}dist/`) }; ``` -------------------------------- ### Import ApiDOM Worker in Dev Mode (Vite) Source: https://github.com/swagger-api/swagger-editor/blob/main/docs/workers.md In development mode, Vite's `?worker` import query is used to load the ApiDOM worker. Vite's transform middleware rewrites bare specifiers within the worker file. ```javascript import ApidomWorkerConstructor from '../editor-monaco-language-apidom/language/apidom.worker.js?worker'; ``` -------------------------------- ### Vite Worker Build Configuration for Production Source: https://github.com/swagger-api/swagger-editor/blob/main/docs/workers.md Configures Vite's worker builder for production builds. This specifies the output format and naming convention for worker files, ensuring hashed filenames for cache busting. ```javascript worker: { format: 'es', rollupOptions: { output: { entryFileNames: 'static/js/[name].[hash].js', }, }, } ``` -------------------------------- ### Configure Dynamic ApiDOM Worker Extension Source: https://github.com/swagger-api/swagger-editor/blob/main/docs/customization/plug-points/editor-monaco-language-apidom.md Configure the EditorMonacoLanguageApiDOM plugin with custom worker path and creation data. This allows for dynamic extension of the ApiDOM worker. ```javascript EditorMonacoLanguageApiDOM({ createData: { authToken: 'c32d8b45-92fe-44f6-8b61-42c2107dfe87', customApiDOMWorkerPath: 'https://example.com/index.js', }, }); ``` -------------------------------- ### Verify WASM Inlining in Build Output Source: https://github.com/swagger-api/swagger-editor/blob/main/docs/wasm-bundling.md These shell commands verify that the WASM files have been correctly inlined into the final JavaScript bundles for both ESM and UMD formats. ```bash # Check tree-sitter.wasm is inlined (Module.wasmBinary injection present) grep -c "wasmBinary" dist/esm/apidom.worker.js # → ≥1 grep -c "wasmBinary" dist/umd/apidom.worker.js # → ≥1 # Check grammar WASMs are Uint8Arrays, not loader functions grep -c "tree_sitter_yaml_default\|tree_sitter_json_default" dist/esm/apidom.worker.js # → 0 grep -c "tree_sitter_yaml_default\|tree_sitter_json_default" dist/umd/apidom.worker.js # → 0 # Language.load should receive bytes$N (Uint8Array), not a function grep "Language.load(" dist/esm/apidom.worker.js # → Language.load(bytes$1) ``` -------------------------------- ### Local & Remote Definitions (v5) Source: https://github.com/swagger-api/swagger-editor/blob/main/docs/migration.md In v5, use the `url` prop directly on the `SwaggerEditor` component for local or remote definitions. Previously, this was configured within `dev-helpers/index.html` using `SwaggerEditorBundle`. ```javascript ``` -------------------------------- ### Webpack 5 Configuration for Swagger Editor Source: https://github.com/swagger-api/swagger-editor/blob/main/README.md A Webpack 5 configuration file that bundles the application, Swagger Editor workers, and includes polyfills for Node.js core modules required by Swagger Editor. It also configures file-loader for WASM files. ```javascript const path = require('path'); const webpack = require('webpack'); module.exports = { mode: 'production', entry: { app: './index.js', 'apidom.worker': 'swagger-editor/apidom.worker', 'editor.worker': 'swagger-editor/editor.worker', }, output: { globalObject: 'self', filename: '[name].js', path: path.resolve(__dirname, 'dist') }, resolve: { fallback: { path: false, fs: false, http: require.resolve('stream-http'), // required for asyncapi parser https: require.resolve('https-browserify'), // required for asyncapi parser stream: require.resolve('stream-browserify'), util: require.resolve('util'), url: require.resolve('url'), buffer: require.resolve('buffer'), zlib: false, }, alias: { // This alias make sure we don't pull two different versions of monaco-editor 'monaco-editor': '/node_modules/monaco-editor', // This alias makes sure we're avoiding a runtime error related to this package '@stoplight/ordered-object-literal$': '/node_modules/@stoplight/ordered-object-literal/src/index.mjs', 'react/jsx-runtime.js': 'react/jsx-runtime', }, }, plugins: [ new webpack.ProvidePlugin({ Buffer: ['buffer', 'Buffer'], process: ['process'], }), ], module: { rules: [ { test: /\.css$/, use: ['style-loader', 'css-loader'] }, /** * The default way in which webpack loads wasm files won’t work in a worker, * so we will have to disable webpack’s default handling of wasm files and * then fetch the wasm file by using the file path that we get using file-loader. * * Resource: https://pspdfkit.com/blog/2020/webassembly-in-a-web-worker/ * * Alternatively, WASM file can be bundled directly into JavaScript bundle as data URLs. * This configuration reduces the complexity of WASM file loading * but increases the overal bundle size: * * { * test: /\.wasm$/, * type: 'asset/inline', * } */ { test: /\.wasm$/, loader: 'file-loader', type: 'javascript/auto', // this disables webpacks default handling of wasm }, ] } }; ``` -------------------------------- ### Import Editor Worker in Dev Mode (Vite) Source: https://github.com/swagger-api/swagger-editor/blob/main/docs/workers.md In development mode, Vite's `?worker` import query is used to load the editor worker. Vite rewrites bare module specifiers to absolute dev-server paths. ```javascript import EditorWorkerConstructor from '@codingame/monaco-vscode-api/workers/editor.worker?worker'; ```