diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..ac16a50 --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +# Editors +.vscode/ +.idea/ diff --git a/README.md b/README.md index aca2c28..4650c1b 100644 --- a/README.md +++ b/README.md @@ -21,7 +21,9 @@ plugins: [ resolve:"@weknow/gatsby-remark-twitch", options: { width: 800, - height: 400 + height: 400, + // Required! + domain: 'example.com' // Also accepts "https://example.com/route } } ] @@ -45,7 +47,7 @@ https://www.twitch.tv/videos/347319713 #### Twitch clip -https://www.twitch.tv/xisuma/clip/MagnificentOilyUdonTTours +https://clips.twitch.tv/MagnificentOilyUdonTTours #### Twitch channel diff --git a/index.js b/index.js index ffeb989..0f02f72 100644 --- a/index.js +++ b/index.js @@ -2,19 +2,41 @@ const visit = require('unist-util-visit'); -module.exports = async ({ markdownAST }, options = { width: 600, height: 300 }) => { +module.exports = async ({ markdownAST }, options = { width: 600, height: 300, domain: '' }) => { + if (!options.domain) { + console.error('You must configure a domain for Gatsby Remark Twitch'); + return; + } + let parent = options.domain; + // Try & Catch to allow for hosts themselves to be passed + // `new URL('domain.com')` will fail/throw, but is a valid host + try { + const url = new URL(options.domain); + // URLs like 'localhost:3000' might not give host. + // Throw in order to catch in wrapper handler + if (!url.host) throw new Error(); + } catch (_) { + const url = new URL('https://' + options.domain); + parent = url.host || parent; + } + + // Twitch embedd throws error with strings like 'localhost:3000', but + // those persist with `new URL().host` + if (parent.startsWith('localhost')) { + parent = 'localhost'; + } + visit(markdownAST, 'text', async (node) => { const { value } = node; - const twitchVideo = value.match(/https:\/\/(www\.)?twitch\.tv\/(videos\/[A-Za-z0-9-_?=]*)/gi); - const twitchClip = value.match(/https:\/\/(www\.)?twitch\.tv\/([A-Za-z0-9-_?=]*\/clip\/[A-Za-z0-9-_?=]*)/gi); + const twitchVideo = value.match(/https:\/\/(www\.)?twitch\.tv\/videos\/([A-Za-z0-9-_?=]*)/gi); + const twitchClip = value.match(/https:\/\/(www\.)?clips\.twitch\.tv\/([A-Za-z0-9-_?=]*)/gi); const twitchChannel = value.match(/https:\/\/(www\.)?twitch\.tv\/([A-Za-z0-9-_?=]*)$/gi); if (twitchVideo) { const videoId = (value.split('/')).pop(); - console.log(`\n Embeding video: ${twitchVideo} ${videoId} \n`); node.type = 'html'; node.value = `