### Convert Technical Documentation to Slack Format Source: https://github.com/nicoespeon/md-to-slack/blob/main/_autodocs/examples.md Converts technical documentation, including installation instructions, API usage examples, method descriptions, and error handling code blocks, into a Slack-compatible format. This example demonstrates the handling of inline code and bash/javascript code blocks. ```javascript import { markdownToSlack } from "md-to-slack"; const markdown = ` API Integration Guide **Installation:** \`\`\`bash npm install @company/api-client \`\`\` **Basic Usage:** Import the client: \`\`\`javascript import { APIClient } from "@company/api-client"; const client = new APIClient({ apiKey: "..." }); \`\`\` **Methods:** - `client.get(endpoint)` - Fetch resource - `client.post(endpoint, data)` - Create resource - `client.put(endpoint, data)` - Update resource - `client.delete(endpoint)` - Delete resource **Error Handling:** \`\`\`javascript try { const result = await client.get("/users"); } catch (error) { console.error(error.message); } \`\`\` For more details, see [documentation](https://docs.example.com). `; const result = markdownToSlack(markdown); ``` -------------------------------- ### Clone and Install Dependencies Source: https://github.com/nicoespeon/md-to-slack/blob/main/README.md Clone the repository and install project dependencies using pnpm. ```shell git clone https://github.com/nicoespeon/md-to-slack cd md-to-slack pnpm install ``` -------------------------------- ### Install md-to-slack Package Source: https://github.com/nicoespeon/md-to-slack/blob/main/README.md Install the md-to-slack package using npm. This is the first step before using the markdownToSlack function. ```shell npm i md-to-slack ``` -------------------------------- ### Quick Example: Markdown to Slack Conversion Source: https://github.com/nicoespeon/md-to-slack/blob/main/_autodocs/README.md Demonstrates how to import and use the markdownToSlack function to convert a sample Markdown string into Slack's mrkdwn format. The example shows a basic conversion of bold text and a link. ```javascript import { markdownToSlack } from "md-to-slack"; const markdown = "Hello **world**! Visit [example.com](https://example.com)"; const slack = markdownToSlack(markdown); // Result: "Hello *world*! Visit " ``` -------------------------------- ### Named Import Example Source: https://github.com/nicoespeon/md-to-slack/blob/main/_autodocs/index.md Demonstrates the correct way to import the markdownToSlack function using a named import. Avoid using a default import. ```javascript import { markdownToSlack } from "md-to-slack"; // ✓ correct import md2slack from "md-to-slack"; // ✗ fails ``` -------------------------------- ### Convert Project Status Update to Slack Format Source: https://github.com/nicoespeon/md-to-slack/blob/main/_autodocs/examples.md Transforms a project status update, including task lists, next steps, risks, and contact information, into a Slack-friendly format. This example highlights the conversion of markdown checkboxes and blockquotes. ```javascript import { markdownToSlack } from "md-to-slack"; const markdown = ` Project Status - June 2026 **Progress:** - [x] Design phase complete - [x] Backend implementation done - [ ] Frontend development in progress - [ ] Testing & QA - [ ] Launch **Next Steps:** 1. Complete UI implementation by EOW 2. Begin integration testing 3. Prepare launch documentation **Risks:** > Database migration might take longer than expected. > Contingency plan in place. Contact: [jane.doe@example.com](mailto:jane.doe@example.com) `; const result = markdownToSlack(markdown); ``` -------------------------------- ### Custom Starting Numbered List Conversion Source: https://github.com/nicoespeon/md-to-slack/blob/main/_autodocs/examples.md Converts Markdown ordered lists with custom starting numbers to Slack's numbered list format. Requires importing the 'md-to-slack' library. ```javascript import { markdownToSlack } from "md-to-slack"; const markdown = ` 5. Item five 6. Item six 7. Item seven `; const result = markdownToSlack(markdown); // Output: // 5. Item five // 6. Item six // 7. Item seven ``` -------------------------------- ### Complex Example Conversion Source: https://github.com/nicoespeon/md-to-slack/blob/main/_autodocs/api-reference.md Demonstrates the conversion of a complex Markdown string containing headings, bold, italics, strikethrough, links, blockquotes, and code blocks into Slack's mrkdwn format. Headings are removed, and other elements are converted. Ensure the 'md-to-slack' package is imported. ```javascript import { markdownToSlack } from "md-to-slack"; const markdown = ` # Release Notes ## Version 2.0 New **features**: - Support for _italics_ - Better ~~code~~ formatting - [View docs](https://example.com/docs) > Important: Breaking changes included ``` const v2 = new API(); ``` `; const slack = markdownToSlack(markdown); // Headings removed, rest converted to mrkdwn ``` -------------------------------- ### Marked Library Dependency Source: https://github.com/nicoespeon/md-to-slack/blob/main/_autodocs/configuration.md This JSON snippet shows the dependency on the 'marked' library and its version requirement. Ensure you have version 17.0.1 or a compatible version installed. ```json { "dependencies": { "marked": "^17.0.1" } } ``` -------------------------------- ### Build Project Files Source: https://github.com/nicoespeon/md-to-slack/blob/main/README.md Build source files from src/ into dist/ using tsup. ```shell pnpm build ``` -------------------------------- ### md-to-slack Project Structure Source: https://github.com/nicoespeon/md-to-slack/blob/main/_autodocs/index.md Illustrates the directory layout of the md-to-slack project, including source files, compiled output, and configuration files. ```tree md-to-slack/ ├── src/ │ ├── index.ts # Main library: markdownToSlack() function │ └── markdownToSlack.test.ts # Test suite with 40+ test cases ├── dist/ # Compiled output (esm, cjs, iife) ├── package.json # Dependencies, build scripts, metadata ├── tsconfig.json # TypeScript configuration └── README.md # User-facing documentation ``` -------------------------------- ### Convert Multi-line Blockquote to Slack Source: https://github.com/nicoespeon/md-to-slack/blob/main/_autodocs/examples.md Converts a multi-line Markdown blockquote into a Slack blockquote. Each line starting with '>' is preserved. ```javascript import { markdownToSlack } from "md-to-slack"; const markdown = ` > This is the first line > This is the second line > This is the third line `; const result = markdownToSlack(markdown); // Output: // > This is the first line // > This is the second line // > This is the third line ``` -------------------------------- ### Build Project Files in Watch Mode Source: https://github.com/nicoespeon/md-to-slack/blob/main/README.md Continuously build source files as they change using tsup in watch mode. ```shell pnpm build --watch ``` -------------------------------- ### Run Tests with Vitest Source: https://github.com/nicoespeon/md-to-slack/blob/main/README.md Execute the project's test suite using Vitest. Tests run in watch mode by default. ```shell pnpm test ``` -------------------------------- ### Importing markdownToSlack Source: https://github.com/nicoespeon/md-to-slack/blob/main/_autodocs/index.md Demonstrates how to import the markdownToSlack function from the 'md-to-slack' package. ```javascript import { markdownToSlack } from "md-to-slack"; ``` -------------------------------- ### Format Code with Prettier Source: https://github.com/nicoespeon/md-to-slack/blob/main/README.md Manually reformat all project files using Prettier. ```shell pnpm format --write ``` -------------------------------- ### Convert Release Notes to Slack Format Source: https://github.com/nicoespeon/md-to-slack/blob/main/_autodocs/examples.md Converts detailed release notes, including markdown formatting, lists, links, and code blocks, into a Slack-compatible string. Headings are automatically stripped. ```javascript import { markdownToSlack } from "md-to-slack"; const markdown = ` ## Version 2.0 Released We're excited to announce **Version 2.0** with new features: - Support for _markdown formatting_ - Better ~~code~~ rendering with language detection - [View full changelog](https://github.com/example/releases/v2.0) ### Breaking Changes If upgrading from v1.x, note these changes: 1. Old API removed (use new API) 2. Configuration format changed 3. Default behavior updated > Migration guide available at [docs site](https://docs.example.com/migrate) \`\`\`javascript // Old way (no longer works) const old = legacyInit(); // New way const fresh = modernInit(); \`\`\` For questions, [open an issue](https://github.com/example/issues). `; const result = markdownToSlack(markdown); // Headings stripped, everything else formatted for Slack ``` -------------------------------- ### Production Dependencies Source: https://github.com/nicoespeon/md-to-slack/blob/main/_autodocs/index.md The library depends on 'marked' for Markdown parsing. No other runtime dependencies are required. ```json { "marked": "^17.0.1" } ``` -------------------------------- ### Basic Formatting: Strikethrough Source: https://github.com/nicoespeon/md-to-slack/blob/main/_autodocs/api-reference.md Converts Markdown strikethrough syntax to Slack's mrkdwn format. Ensure the 'md-to-slack' package is imported. ```javascript import { markdownToSlack } from "md-to-slack"; // Strikethrough const result2 = markdownToSlack("This is ~~wrong~~ correct."); // Result: "This is ~wrong~ correct." ``` -------------------------------- ### Mixed Formatting Conversion to Slack Source: https://github.com/nicoespeon/md-to-slack/blob/main/_autodocs/examples.md Demonstrates the conversion of Markdown with combined bold and italic, and nested strike-through formatting into Slack's equivalent syntax. ```javascript import { markdownToSlack } from "md-to-slack"; markdownToSlack("***bold and italic***"); // Output: "*_bold and italic_*" markdownToSlack("**bold with ~~strike~~ inside**"); // Output: "*bold with ~strike~ inside*" ``` -------------------------------- ### Typical Markdown to Slack Conversion Source: https://github.com/nicoespeon/md-to-slack/blob/main/_autodocs/index.md Demonstrates the common pattern of converting Markdown text, including headings, bold, italics, links, blockquotes, and code blocks, into a format suitable for Slack messages. The library automatically handles the conversion and escaping. ```javascript import { markdownToSlack } from "md-to-slack"; // User writes Markdown const userMarkdown = ` # Release v2.0 New **features**: - Support for _italics_ - Better [documentation](https://example.com) > This is a breaking change \`\`\`js const result = await getData(); \`\`\` `; // Convert to Slack const slackMessage = markdownToSlack(userMarkdown); // Headings are removed, everything else converted // Send to Slack API await slack.chat.postMessage({ channel: "#announcements", text: slackMessage, mrkdwn: true }); ``` -------------------------------- ### Handle Headings in Markdown Source: https://github.com/nicoespeon/md-to-slack/blob/main/_autodocs/examples.md Demonstrates that headings are stripped by default and suggests using bold text for emphasis as a workaround for Slack's mrkdwn limitations. ```javascript // ❌ Expect headings to appear const markdown = "# Title\n## Subtitle\nContent"; markdownToSlack(markdown); // Output: "Title\nSubtitle\nContent" (headings are stripped) // ✓ Use bold for emphasis instead const markdown = "**Title**\n**Subtitle**\nContent"; markdownToSlack(markdown); // Output: "*Title*\n*Subtitle*\nContent" ``` -------------------------------- ### Configure Marked.js Parsing Options Source: https://github.com/nicoespeon/md-to-slack/blob/main/_autodocs/configuration.md These options are passed to `marked.parse()` internally. `async: false` ensures synchronous execution, while `gfm: true` enables GitHub Flavored Markdown support. ```typescript marked.parse(markdown, { async: false, // Disable async rendering for synchronous execution gfm: true // Enable GitHub Flavored Markdown support }) ``` -------------------------------- ### Lint Source Files Source: https://github.com/nicoespeon/md-to-slack/blob/main/README.md Run ESLint to check for code quality issues in JavaScript and TypeScript files. ```shell pnpm run lint ``` -------------------------------- ### Handling Empty Input in Markdown to Slack Conversion Source: https://github.com/nicoespeon/md-to-slack/blob/main/_autodocs/examples.md Illustrates that empty strings, strings with only whitespace, or strings with only newlines are converted to empty strings. ```javascript import { markdownToSlack } from "md-to-slack"; markdownToSlack(""); // Output: "" markdownToSlack(" "); // Output: "" markdownToSlack("\n\n"); // Output: "" ``` -------------------------------- ### Handle Tables in Markdown Source: https://github.com/nicoespeon/md-to-slack/blob/main/_autodocs/examples.md Shows that tables are not supported in mrkdwn and provides an alternative by converting table data into a formatted list. ```javascript // ❌ Tables not supported in mrkdwn const markdown = "\ | Name | Value |\n|------|-------|\n| A | 1 |\n"; markdownToSlack(markdown); // Output: "" (table ignored) // ✓ Convert to list format const markdown = "\ **Name | Value**\n- A: 1\n- B: 2\n"; markdownToSlack(markdown); // Output as formatted list ``` -------------------------------- ### Import markdownToSlack (IIFE/Browser) Source: https://github.com/nicoespeon/md-to-slack/blob/main/_autodocs/api-reference.md For use in a browser environment via an IIFE (Immediately Invoked Function Expression), the markdownToSlack function is available globally on the window object. ```typescript // IIFE (browser) // Global: window.markdownToSlack ``` -------------------------------- ### Handle Images in Markdown Source: https://github.com/nicoespeon/md-to-slack/blob/main/_autodocs/examples.md Illustrates that images are removed by default and recommends using the Slack Block Kit API for rendering images. ```javascript // ❌ Images are removed by design markdownToSlack("![alt text](image.jpg)"); // Output: "" (image removed) // ✓ For images, use Slack Block Kit API instead // See: https://api.slack.com/block-kit/ ``` -------------------------------- ### markdownToSlack() Source: https://github.com/nicoespeon/md-to-slack/blob/main/_autodocs/api-reference.md The main function that converts Markdown syntax to Slack-compatible mrkdwn format. It takes a Markdown string as input and returns the converted mrkdwn string. ```APIDOC ## markdownToSlack() ### Description Converts Markdown input into Slack's proprietary `mrkdwn` syntax. The function parses the input using the `marked` library with GFM support enabled and applies a custom renderer that translates Markdown elements into their Slack equivalents. ### Method `markdownToSlack(markdown: string): string` ### Parameters #### Path Parameters - **markdown** (string) - Required - Markdown text to convert. Supports both standard Markdown and GitHub Flavored Markdown (GFM) syntax. ### Return Type **string** — The converted Slack-compatible mrkdwn text with trailing whitespace trimmed. ### Supported Conversions #### Text Formatting - **Bold**: `**text**` or `__text__` → `*text*` - **Italic**: `*text*` or `_text_` → `_text_` - **Strikethrough**: `~~text~~`, `text`, `text`, `text` → `~text~` - **Inline Code**: `` `text` `` → `` `text` `` - **Code Blocks**: ` ```language code ``` ` → ` ```language code ``` ` #### Links - Autolinks: `` → `` - Links with text: `[text](http://example.com)` → `` - Email links: `` → `` - Reference links: `[text][1]` followed by `[1]: url` → `` #### Block Elements - **Blockquotes**: `> text` → `> text` - **Lists**: Unordered (`-`, `*`, `+`) and ordered (`1.`, `2.`) lists with nesting support - **Checkboxes**: `- [x]` → `☒`, `- [ ]` → `☐` - **Horizontal Rules**: `---`, `***`, `___` → preserved as-is - **Line Breaks**: `
` and `
` → ` ` #### Not Supported - **Headings**: All heading levels (`#`, `##`, etc.) are stripped - **Images**: Image syntax `![alt](url)` is removed (use Slack Block Kit for rich media) - **Tables**: GitHub Flavored Markdown tables are not rendered #### Character Escaping Special HTML characters are automatically escaped for safe rendering in Slack: - `&` → `&` - `<` → `<` - `>` → `>` ### Security Note The function does not sanitize HTML or remove potentially malicious content. If your Markdown input originates from external sources, sanitize it before calling `markdownToSlack()` to prevent XSS attacks when the output is rendered in Slack. ``` -------------------------------- ### strong(token) Source: https://github.com/nicoespeon/md-to-slack/blob/main/_autodocs/renderer-reference.md Renders markdown bold text (`**text**`) into Slack's bold syntax (`*text*`). It recursively parses nested inline tokens and supports formatting within bold text. ```APIDOC ## strong(token) ### Description Renders markdown bold text (`**text**`) into Slack's bold syntax (`*text*`). It recursively parses nested inline tokens and supports formatting within bold text. ### Input Token ```typescript { type: "strong", tokens: Token[], // Nested inline tokens raw: string } ``` ### Implementation ```typescript strong(token) { const text = this.parser.parseInline(token.tokens); return `*${text}*`; } ``` ### Behavior - Recursively parses nested inline tokens - Wraps result with `*` on both sides (Slack bold syntax) - Supports nested formatting inside bold ### Examples ``` Input: **bold** Output: *bold* Input: **bold with _italic_** Output: *bold with _italic_* ``` ``` -------------------------------- ### Render Tables Source: https://github.com/nicoespeon/md-to-slack/blob/main/_autodocs/renderer-reference.md These functions return empty strings as tables are not natively supported in Slack's mrkdwn and are handled by marked but not rendered. ```typescript table() { return ""; } tablerow() { return ""; } tablecell() { return ""; } ``` -------------------------------- ### Configure Marked.js Renderer Source: https://github.com/nicoespeon/md-to-slack/blob/main/_autodocs/configuration.md The renderer is configured globally once when the module loads using `marked.use()`. This object contains handler functions to map Markdown tokens to Slack mrkdwn equivalents. ```typescript marked.use({ renderer }); ``` -------------------------------- ### Basic Formatting: Bold and Italic Source: https://github.com/nicoespeon/md-to-slack/blob/main/_autodocs/api-reference.md Converts Markdown bold and italic syntax to Slack's mrkdwn format. Ensure the 'md-to-slack' package is imported. ```javascript import { markdownToSlack } from "md-to-slack"; // Bold and italic const result1 = markdownToSlack("Hello **bold** and *italic* world!"); // Result: "Hello *bold* and _italic_ world!" ``` -------------------------------- ### Convert Inline Code to Slack Source: https://github.com/nicoespeon/md-to-slack/blob/main/_autodocs/examples.md Use this snippet to convert simple inline Markdown code to its Slack equivalent. Ensure the 'md-to-slack' library is imported. ```javascript import { markdownToSlack } from "md-to-slack"; markdownToSlack( "Use the `const` keyword to declare variables" ); // Output: "Use the `const` keyword to declare variables" ``` -------------------------------- ### Task List Conversion (GitHub Flavored Markdown) Source: https://github.com/nicoespeon/md-to-slack/blob/main/_autodocs/examples.md Converts GitHub Flavored Markdown task lists (checkboxes) into their corresponding Slack representations (checked or unchecked). Ensure the 'md-to-slack' library is imported. ```javascript import { markdownToSlack } from "md-to-slack"; const markdown = ` - [x] Completed task - [x] Another done task - [ ] Pending task - [ ] Waiting for review `; const result = markdownToSlack(markdown); // Output: // ☒ Completed task // ☒ Another done task // ☐ Pending task // ☐ Waiting for review ``` -------------------------------- ### Import markdownToSlack (ESM) Source: https://github.com/nicoespeon/md-to-slack/blob/main/_autodocs/api-reference.md Import the markdownToSlack function using ES Module syntax. This is the standard for modern JavaScript environments. ```typescript // ESM import { markdownToSlack } from "md-to-slack"; ``` -------------------------------- ### Basic Formatting Conversion Source: https://github.com/nicoespeon/md-to-slack/blob/main/_autodocs/examples.md Converts bold, italic, and strikethrough text from Markdown to Slack format. Ensure the 'md-to-slack' library is imported. ```javascript import { markdownToSlack } from "md-to-slack"; // Bold text markdownToSlack("This is **bold** text"); // Output: "This is *bold* text" // Italic text markdownToSlack("This is *italic* text"); // Output: "This is _italic_ text" // Strikethrough markdownToSlack("This is ~~wrong~~ correct"); // Output: "This is ~wrong~ correct" ``` -------------------------------- ### Render Markdown Lists Source: https://github.com/nicoespeon/md-to-slack/blob/main/_autodocs/renderer-reference.md Handles the rendering of both ordered and unordered lists, including task lists and nested lists. It preserves indentation and formats items with appropriate markers. ```typescript list(token) { const parseItemContent = (itemTokens) => { const hasBlockContent = itemTokens.some( (t) => t.type === "list" || t.type === "code" || t.type === "blockquote" ); if (hasBlockContent) { return this.parser.parse(itemTokens); } return itemTokens .map((t) => { if (t.type === "text" && "tokens" in t && t.tokens) { return this.parser.parseInline(t.tokens); } else if (t.type === "space") { return t.raw; } return this.parser.parse([t]); }) .join(""); }; const items = token.ordered ? token.items.map( (item, i) => `${Number(token.start) + i}. ${parseItemContent(item.tokens)}` ) : token.items.map((item) => { const marker = item.task ? (item.checked ? "☒" : "☐") : "-"; return `${marker} ${parseItemContent(item.tokens)}`; }); const firstItem = token.items[0].raw; const indentation = firstItem.match(/^(\s+)/)?.[0]; if (!indentation) { return items.join("\n"); } const newLine = token.ordered ? `\n${indentation} ` : `\n${indentation}`; return newLine + items.join(newLine); } ``` -------------------------------- ### Import markdownToSlack (CommonJS) Source: https://github.com/nicoespeon/md-to-slack/blob/main/_autodocs/api-reference.md Import the markdownToSlack function using CommonJS syntax. This is typically used in Node.js environments prior to ESM becoming standard. ```typescript // CommonJS const { markdownToSlack } = require("md-to-slack"); ``` -------------------------------- ### Renderer Methods for Markdown to Slack Conversion Source: https://github.com/nicoespeon/md-to-slack/blob/main/_autodocs/types.md Defines the structure for custom renderer methods that convert Markdown tokens into Slack-compatible mrkdwn. Each method receives a token and returns a string representation. ```typescript const renderer = { // Block-level methods space(token): string code(token): string blockquote(token): string html(token): string heading(token): string hr(token): string list(token): string listitem(token): string checkbox(token): string paragraph(token): string table(token): string tablerow(token): string tablecell(token): string // Inline-level methods strong(token): string em(token): string codespan(token): string br(token): string del(token): string link(token): string image(token): string text(token): string } satisfies MarkedExtension["renderer"] ``` -------------------------------- ### Nested Lists with Formatting Conversion to Slack Source: https://github.com/nicoespeon/md-to-slack/blob/main/_autodocs/examples.md Shows how nested Markdown lists containing bold text, links, italic text, and code snippets are converted to Slack's list format. ```javascript import { markdownToSlack } from "md-to-slack"; const markdown = ` - **Bold** item with [link](https://example.com) - _Italic_ nested item - Another nested with code `; const result = markdownToSlack(markdown); // Output: // - *Bold* item with // - _Italic_ nested item // - Another nested with `code` ``` -------------------------------- ### Sanitize User Input Before Markdown to Slack Conversion Source: https://github.com/nicoespeon/md-to-slack/blob/main/_autodocs/configuration.md Demonstrates how to sanitize user-provided Markdown using 'sanitize-html' before passing it to 'markdownToSlack' to prevent XSS attacks. Ensure to define allowed HTML tags for sanitization. ```javascript import { markdownToSlack } from "md-to-slack"; import sanitizeHtml from "sanitize-html"; const userInput = "**bold**"; const clean = sanitizeHtml(userInput, { allowedTags: ["b", "i", "em", "strong", "a", "code", "pre", "del", "s", "br"] }); const result = markdownToSlack(clean); ``` -------------------------------- ### heading Renderer Implementation Source: https://github.com/nicoespeon/md-to-slack/blob/main/_autodocs/renderer-reference.md The 'heading' renderer strips Markdown heading markers and adds two newlines for spacing, rendering the heading as plain text in Slack. ```typescript heading(token) { return `${token.text}\n\n`; } ``` -------------------------------- ### Links with No Text or URL as Text in Markdown to Slack Source: https://github.com/nicoespeon/md-to-slack/blob/main/_autodocs/examples.md Covers cases where Markdown links have no visible text or where the link text is identical to the URL, converting them to simple Slack links. ```javascript import { markdownToSlack } from "md-to-slack"; // Empty link text markdownToSlack("[](https://example.com)"); // Output: "" // Link text equals URL markdownToSlack("[https://example.com](https://example.com)"); // Output: "" ``` -------------------------------- ### Render Image Token Source: https://github.com/nicoespeon/md-to-slack/blob/main/_autodocs/renderer-reference.md Handles 'image' tokens by returning an empty string. Slack's mrkdwn does not support images directly; Block Kit API should be used instead. ```typescript image() { return ""; } ``` -------------------------------- ### Links: Link with Text Source: https://github.com/nicoespeon/md-to-slack/blob/main/_autodocs/api-reference.md Converts Markdown links with text to Slack's mrkdwn format. Ensure the 'md-to-slack' package is imported. ```javascript import { markdownToSlack } from "md-to-slack"; // Link with text const result = markdownToSlack("[Click here](https://example.com)"); // Result: "" ``` -------------------------------- ### Render Link Token Source: https://github.com/nicoespeon/md-to-slack/blob/main/_autodocs/renderer-reference.md Formats 'link' tokens into Slack's mrkdwn link syntax. It handles URL encoding and formats links as autolinks or with explicit text. ```typescript link(token) { const text = this.parser.parseInline(token.tokens); const url = cleanUrl(token.href); return url === text || url === `mailto:${text}` || !text ? `<${url}>` : `<${url}|${text}>`; } ``` -------------------------------- ### Measure md-to-slack Performance Source: https://github.com/nicoespeon/md-to-slack/blob/main/_autodocs/examples.md Measure the synchronous conversion time for a given Markdown string. This helps in understanding the performance characteristics for different document sizes. ```javascript import { markdownToSlack } from "md-to-slack"; import { performance } from "perf_hooks"; const markdown = "# Large Document\n".repeat(100) + "Content here"; const start = performance.now(); const result = markdownToSlack(markdown); const duration = performance.now() - start; console.log(`Conversion took ${duration.toFixed(2)}ms`); // Typical output: ~1-5ms for moderate documents ``` -------------------------------- ### Type Check Project Files Source: https://github.com/nicoespeon/md-to-slack/blob/main/README.md Perform type checking on all files in the src/ directory using the TypeScript compiler. ```shell pnpm tsc ``` -------------------------------- ### Lists: Ordered List Source: https://github.com/nicoespeon/md-to-slack/blob/main/_autodocs/api-reference.md Converts Markdown ordered lists to Slack's mrkdwn format. Ensure the 'md-to-slack' package is imported. ```javascript import { markdownToSlack } from "md-to-slack"; // Ordered list const ordered = markdownToSlack(`1. First 2. Second 3. Third`); // Result: // 1. First // 2. Second // 3. Third ``` -------------------------------- ### Ordered List Conversion Source: https://github.com/nicoespeon/md-to-slack/blob/main/_autodocs/examples.md Converts Markdown ordered lists to Slack's numbered list format. Ensure the 'md-to-slack' library is imported. ```javascript import { markdownToSlack } from "md-to-slack"; const markdown = ` 1. First item 2. Second item 3. Third item `; const result = markdownToSlack(markdown); // Output: // 1. First item // 2. Second item // 3. Third item ``` -------------------------------- ### Email Link Conversion Source: https://github.com/nicoespeon/md-to-slack/blob/main/_autodocs/index.md Converts email addresses in angle brackets (``) to Slack's mailto link format (``). ```markdown ``` -------------------------------- ### codespan(token) Source: https://github.com/nicoespeon/md-to-slack/blob/main/_autodocs/renderer-reference.md Renders markdown inline code (`code`) by returning the raw text without any modification. This preserves backticks and literal content, and does not process internal formatting. ```APIDOC ## codespan(token) ### Description Renders markdown inline code (`code`) by returning the raw text without any modification. This preserves backticks and literal content, and does not process internal formatting. ### Input Token ```typescript { type: "codespan", text: string, raw: string } ``` ### Implementation ```typescript codespan(token) { return token.raw; } ``` ### Behavior - Returns the raw inline code unchanged - Backticks and content are preserved exactly - No escaping or transformation applied - Formatting inside code is not processed (remains literal) ### Examples ``` Input: `code` Output: `code` Input: `const x = "value"` Output: `const x = "value"` Input: `code with **bold** literal` Output: `code with **bold** literal` ``` ``` -------------------------------- ### URL Encoding for Links in Markdown to Slack Source: https://github.com/nicoespeon/md-to-slack/blob/main/_autodocs/examples.md Shows how URLs with spaces or international characters are encoded for Slack links, and ensures already-encoded URLs are not double-encoded. ```javascript import { markdownToSlack } from "md-to-slack"; // Spaces in URL (encoded) markdownToSlack("[Click](https://example.com/path%20with%20spaces)"); // Output: "" // International characters markdownToSlack("[Café](https://example.com/café)"); // Output: "" // Already-encoded URLs (not double-encoded) markdownToSlack("[Link](https://example.com/search?q=hello%20world)"); // Output: "" ``` -------------------------------- ### link(token) Source: https://github.com/nicoespeon/md-to-slack/blob/main/_autodocs/renderer-reference.md Renders markdown links (`[text](url)`) into Slack's link format (``). It handles URL encoding, special cases like mailto links, and autolinks when the URL and text are identical or the text is empty. The link title is ignored. ```APIDOC ## link(token) ### Description Renders markdown links (`[text](url)`) into Slack's link format (``). It handles URL encoding, special cases like mailto links, and autolinks when the URL and text are identical or the text is empty. The link title is ignored. ### Input Token ```typescript { type: "link", href: string, // URL title: string | null, // Optional link title tokens: Token[], // Link text content raw: string } ``` ### Implementation ```typescript link(token) { const text = this.parser.parseInline(token.tokens); const url = cleanUrl(token.href); return url === text || url === `mailto:${text}` || !text ? `<${url}>` : `<${url}|${text}>`; } ``` ### Helper: cleanUrl(href) ```typescript function cleanUrl(href: string) { try { return encodeURI(href).replace(/%25/g, "%25"); } catch { return href; } } ``` ### Behavior 1. **URL Processing:** - Applies `encodeURI()` for safe URL encoding - Replaces `%25` (double-encoded %) with single `%` - Falls back to original href if encoding fails 2. **Link Formatting:** - If URL equals link text OR URL equals `mailto:{text}` OR text is empty: - Format as `` (autolink) - Otherwise: - Format as `` (link with text) 3. **Title Attribute:** - Title is ignored (not rendered in Slack) ### Examples ``` Input: [example](https://example.com) Output: Input: Output: Input: [https://example.com](https://example.com) Output: Input: Output: Input: [Click here](https://example.com "Title ignored") Output: ``` ``` -------------------------------- ### br(token) Source: https://github.com/nicoespeon/md-to-slack/blob/main/_autodocs/renderer-reference.md Handles markdown line breaks (e.g., two spaces followed by a newline) by returning an empty string, as Slack does not render them directly. HTML `
` tags are handled by the `html()` renderer. ```APIDOC ## br(token) ### Description Handles markdown line breaks (e.g., two spaces followed by a newline) by returning an empty string, as Slack does not render them directly. HTML `
` tags are handled by the `html()` renderer. ### Input Token ```typescript { type: "br", raw: string // "\n" or markdown line break } ``` ### Implementation ```typescript br() { return ""; } ``` ### Behavior - Returns empty string - Markdown-style line breaks (two spaces + newline) are handled by returning empty - HTML `
` tags are handled by the `html()` renderer - The raw newline is usually already in the parsed output ``` -------------------------------- ### Unordered List Conversion Source: https://github.com/nicoespeon/md-to-slack/blob/main/_autodocs/examples.md Converts Markdown unordered lists to Slack's list format. The 'md-to-slack' library must be imported. ```javascript import { markdownToSlack } from "md-to-slack"; const markdown = ` - Item 1 - Item 2 - Item 3 `; const result = markdownToSlack(markdown); // Output: // - Item 1 // - Item 2 // - Item 3 ``` -------------------------------- ### Bold Text Conversion Source: https://github.com/nicoespeon/md-to-slack/blob/main/_autodocs/index.md Converts standard Markdown bold syntax (`**text**` or `__text__`) to Slack's bold format (`*text*`). ```markdown **hello** ``` -------------------------------- ### Link Conversion Source: https://github.com/nicoespeon/md-to-slack/blob/main/_autodocs/examples.md Handles conversion of different types of Markdown links, including text links, autolinks, email links, and reference-style links, to Slack's URL format. Requires importing the 'md-to-slack' library. ```javascript import { markdownToSlack } from "md-to-slack"; // Link with text markdownToSlack("[Click here](https://example.com)"); // Output: "" // Autolink markdownToSlack(""); // Output: "" // Email link markdownToSlack(""); // Output: "" // Link with reference const markdown = ` Learn more at [my site][1] [1]: https://example.com `; markdownToSlack(markdown); // Output: "Learn more at " ``` -------------------------------- ### code Renderer Implementation Source: https://github.com/nicoespeon/md-to-slack/blob/main/_autodocs/renderer-reference.md The 'code' renderer wraps the code content in triple backticks, creating a Slack code block. It includes the language identifier if provided and preserves the exact formatting of the code. ```typescript code(token) { return `\ \ ```${token.lang ?? ""} ${token.text} \ \ ```\ \ `; } ``` -------------------------------- ### Auto-fix Linting Issues Source: https://github.com/nicoespeon/md-to-slack/blob/main/README.md Run ESLint with the --fix flag to automatically resolve some lint rule violations. ```shell pnpm run lint --fix ``` -------------------------------- ### image(token) Source: https://github.com/nicoespeon/md-to-slack/blob/main/_autodocs/renderer-reference.md Handles markdown images (`![alt](url)`) by returning an empty string, as images are not supported in Slack's mrkdwn. Users should utilize the Slack Block Kit API for image display. Nested images within links are stripped, retaining only the link. ```APIDOC ## image(token) ### Description Handles markdown images (`![alt](url)`) by returning an empty string, as images are not supported in Slack's mrkdwn. Users should utilize the Slack Block Kit API for image display. Nested images within links are stripped, retaining only the link. ### Input Token ```typescript { type: "image", href: string, // Image URL title: string | null, // Optional image title text: string // Alt text } ``` ### Implementation ```typescript image() { return ""; } ``` ### Behavior - Returns empty string - Images are not supported by Slack mrkdwn - For images, users should use Slack Block Kit API **Note:** If an image is inside a link (e.g., `[![alt](img.url)](link.url)`), only the link part is retained, and the image is stripped. ``` -------------------------------- ### Type Check Project Files in Watch Mode Source: https://github.com/nicoespeon/md-to-slack/blob/main/README.md Keep the TypeScript type checker running in watch mode, updating as files are saved. ```shell pnpm tsc --watch ``` -------------------------------- ### Nested List Conversion Source: https://github.com/nicoespeon/md-to-slack/blob/main/_autodocs/examples.md Handles conversion of nested Markdown lists (both ordered and unordered) into Slack's hierarchical list structure. The 'md-to-slack' library must be imported. ```javascript import { markdownToSlack } from "md-to-slack"; const markdown = ` 1. First item 2. Second item 1. Nested 2.1 2. Nested 2.2 3. Third item - Nested bullet - Another bullet `; const result = markdownToSlack(markdown); // Output: // 1. First item // 2. Second item // 1. Nested 2.1 // 2. Nested 2.2 // 3. Third item // - Nested bullet // - Another bullet ``` -------------------------------- ### Render Paragraph Source: https://github.com/nicoespeon/md-to-slack/blob/main/_autodocs/renderer-reference.md Parses and renders inline tokens within a paragraph, applying text formatting like bold, italic, and links without adding any wrapper elements. ```typescript paragraph(token) { return this.parser.parseInline(token.tokens); } ``` -------------------------------- ### Convert Markdown to Slack Text Source: https://github.com/nicoespeon/md-to-slack/blob/main/README.md Import and use the markdownToSlack function to convert a Markdown string into Slack-compatible mrkdwn text. Ensure the function is imported correctly. ```javascript import { markdownToSlack } from "md-to-slack"; const slackText = markdownToSlack("Hello **world**!"); ``` -------------------------------- ### em(token) Source: https://github.com/nicoespeon/md-to-slack/blob/main/_autodocs/renderer-reference.md Renders markdown italic text (`*text*`) into Slack's italic syntax (`_text_`). It handles nested formatting within italic text and recursively parses inline tokens. ```APIDOC ## em(token) ### Description Renders markdown italic text (`*text*`) into Slack's italic syntax (`_text_`). It handles nested formatting within italic text and recursively parses inline tokens. ### Input Token ```typescript { type: "em", tokens: Token[], // Nested inline tokens raw: string } ``` ### Implementation ```typescript em(token) { const text = this.parser.parseInline(token.tokens); return `_${text}_`; } ``` ### Behavior - Recursively parses nested inline tokens - Wraps result with `_` on both sides (Slack italic syntax) - Supports nested formatting inside italic ### Examples ``` Input: *italic* Output: _italic_ Input: *italic with **bold*** Output: _italic with *bold*_ ``` ``` -------------------------------- ### Render Codespan Token Source: https://github.com/nicoespeon/md-to-slack/blob/main/_autodocs/renderer-reference.md Handles 'codespan' tokens by returning the raw text. No escaping or transformation is applied, preserving backticks and literal content. ```typescript codespan(token) { return token.raw; } ``` -------------------------------- ### Links: Autolink Source: https://github.com/nicoespeon/md-to-slack/blob/main/_autodocs/api-reference.md Converts Markdown autolinks to Slack's mrkdwn format. Ensure the 'md-to-slack' package is imported. ```javascript import { markdownToSlack } from "md-to-slack"; // Autolink const result2 = markdownToSlack(""); // Result: "" ``` -------------------------------- ### Checkboxes (GFM) Source: https://github.com/nicoespeon/md-to-slack/blob/main/_autodocs/api-reference.md Converts GitHub Flavored Markdown (GFM) checkboxes to Slack's mrkdwn format. Ensure the 'md-to-slack' package is imported. ```javascript import { markdownToSlack } from "md-to-slack"; const tasks = markdownToSlack(`- [x] Completed task - [ ] Pending task`); // Result: // ☒ Completed task // ☐ Pending task ``` -------------------------------- ### Link Conversion Source: https://github.com/nicoespeon/md-to-slack/blob/main/_autodocs/index.md Converts Markdown links (`[text](url)`) to Slack's URL format (``). Also handles bare URLs and reference-style links. ```markdown [text](url) ``` ```markdown ``` ```markdown [text][ref] ``` -------------------------------- ### Strikethrough Text Conversion Source: https://github.com/nicoespeon/md-to-slack/blob/main/_autodocs/index.md Converts Markdown strikethrough syntax (`~~text~~`) to Slack's strikethrough format (`~text~`). Also handles HTML `` tags. ```markdown ~~old~~ ``` ```html wrong ``` -------------------------------- ### blockquote Renderer Implementation Source: https://github.com/nicoespeon/md-to-slack/blob/main/_autodocs/renderer-reference.md The 'blockquote' renderer parses nested tokens recursively and prefixes each line with '> ' to create a Slack blockquote. It trims whitespace and joins lines with newlines. ```typescript blockquote(token) { return token.tokens .map((t) => ("> " + this.parser.parse([t])).trim()) .join("\n"); } ``` -------------------------------- ### Unordered List Item Conversion Source: https://github.com/nicoespeon/md-to-slack/blob/main/_autodocs/index.md Converts Markdown unordered list items (e.g., `- item`) to Slack's unordered list format. ```markdown - item ``` -------------------------------- ### markdownToSlack Function Source: https://github.com/nicoespeon/md-to-slack/blob/main/_autodocs/MANIFEST.md The main function of the md-to-slack library converts Markdown strings to Slack-compatible formatted strings. It supports various Markdown elements and provides options for customization. ```APIDOC ## markdownToSlack(markdown: string): string ### Description Converts a Markdown string into a Slack-formatted string. This function handles various Markdown syntax elements and character escaping to ensure compatibility with Slack. ### Method Function Call ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **markdown** (string) - Required - The Markdown string to convert. ### Return Type - **string** - The Slack-formatted string. ### Examples This section refers to the `examples.md` file for detailed usage examples, including basic conversions, lists, code blocks, blockquotes, complex scenarios, and integration patterns. ``` -------------------------------- ### Send Markdown Announcements via Slack SDK Source: https://github.com/nicoespeon/md-to-slack/blob/main/_autodocs/examples.md Use this snippet to send formatted Markdown announcements to Slack channels using the Bolt for JavaScript SDK. Ensure your SLACK_BOT_TOKEN environment variable is set. ```javascript import { App } from "@slack/bolt"; import { markdownToSlack } from "md-to-slack"; const app = new App({ token: process.env.SLACK_BOT_TOKEN }); app.command("/announcement", async ({ ack, say }) => { ack(); const markdown = ` **Important Update** We're deploying new features today: - Performance improvements - Bug fixes - New dashboard [View release notes](https://example.com/notes) `; const slackText = markdownToSlack(markdown); await say({ text: slackText, mrkdwn: true }); }); app.start(); ``` -------------------------------- ### space Renderer Implementation Source: https://github.com/nicoespeon/md-to-slack/blob/main/_autodocs/renderer-reference.md The 'space' renderer function returns the raw whitespace token exactly as-is. This preserves empty lines and spacing between blocks without any transformation. ```typescript space(token) { return token.raw; } ``` -------------------------------- ### Lists: Unordered List Source: https://github.com/nicoespeon/md-to-slack/blob/main/_autodocs/api-reference.md Converts Markdown unordered lists, including nested items, to Slack's mrkdwn format. Ensure the 'md-to-slack' package is imported. ```javascript import { markdownToSlack } from "md-to-slack"; // Unordered list const list = markdownToSlack(`- Item 1 - Item 2 - Nested item`); // Result: // - Item 1 // - Item 2 // - Nested item ``` -------------------------------- ### del(token) Source: https://github.com/nicoespeon/md-to-slack/blob/main/_autodocs/renderer-reference.md Renders markdown strikethrough text (`~~text~~`) into Slack's strikethrough syntax (`~text~`). It supports nested formatting within strikethrough text and recursively parses inline tokens. ```APIDOC ## del(token) ### Description Renders markdown strikethrough text (`~~text~~`) into Slack's strikethrough syntax (`~text~`). It supports nested formatting within strikethrough text and recursively parses inline tokens. ### Input Token ```typescript { type: "del", tokens: Token[], // Nested inline tokens raw: string } ``` ### Implementation ```typescript del(token) { const text = this.parser.parseInline(token.tokens); return `~${text}~`; } ``` ### Behavior - Recursively parses nested inline tokens - Wraps result with `~` on both sides (Slack strikethrough syntax) - Supports nested formatting inside strikethrough ### Examples ``` Input: ~~strikethrough~~ Output: ~strikethrough~ Input: ~~wrong **bold** text~~ Output: ~wrong *bold* text~ ``` ``` -------------------------------- ### Ordered List Item Conversion Source: https://github.com/nicoespeon/md-to-slack/blob/main/_autodocs/index.md Converts Markdown ordered list items (e.g., `1. item`) to Slack's ordered list format. ```markdown 1. item ``` -------------------------------- ### Code Blocks Source: https://github.com/nicoespeon/md-to-slack/blob/main/_autodocs/api-reference.md Converts Markdown code blocks, including language specification, to Slack's mrkdwn format. Ensure the 'md-to-slack' package is imported. ```javascript import { markdownToSlack } from "md-to-slack"; const code = markdownToSlack(` ```javascript const greeting = "Hello, Slack!"; console.log(greeting); ``` `); // Result: // ```javascript // const greeting = "Hello, Slack!"; // console.log(greeting); // ``` ``` -------------------------------- ### Markdown Parsing Options Source: https://github.com/nicoespeon/md-to-slack/blob/main/_autodocs/types.md Specifies the configuration options for the markdownToSlack function, including enabling synchronous parsing and GitHub Flavored Markdown. ```typescript { async: false, // Synchronous parsing (no async processing) gfm: true // Enable GitHub Flavored Markdown syntax } ``` -------------------------------- ### Task List Item Conversion Source: https://github.com/nicoespeon/md-to-slack/blob/main/_autodocs/index.md Converts Markdown task list items (`- [ ] task` and `- [x] task`) to Slack's checkbox format (`☐ task` and `☒ task`). ```markdown - [ ] task ``` ```markdown - [x] task ``` -------------------------------- ### Convert Blockquote with Formatting to Slack Source: https://github.com/nicoespeon/md-to-slack/blob/main/_autodocs/examples.md Converts a Markdown blockquote containing formatting like bold, italics, and links to its Slack equivalent. The library attempts to translate Markdown formatting to Slack's supported markup. ```javascript import { markdownToSlack } from "md-to-slack"; const markdown = ` > **Important**: Remember to [read the docs](https://example.com) > Don't forget the *details*! `; const result = markdownToSlack(markdown); // Output: // > *Important*: Remember to // > Don't forget the _details_! ```