Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add script to inline and strip Prism #61

Merged
merged 15 commits into from
May 12, 2022
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,5 @@ node_modules/
*.d.ts
*.log
.DS_Store
package-lock.json
yarn.lock
1 change: 0 additions & 1 deletion .npmrc

This file was deleted.

68 changes: 2 additions & 66 deletions lib/core.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,46 +32,11 @@
* @property {Languages} languages
*/

/* eslint-disable no-undef */
// Don’t allow Prism to run on page load in browser or to start messaging from
// workers.
/* c8 ignore next 15 */
/** @type {typeof globalThis} */
const ctx =
typeof globalThis === 'object'
? globalThis
: // @ts-expect-error
typeof self === 'object'
? // @ts-expect-error
self
: // @ts-expect-error
typeof window === 'object'
? // @ts-expect-error
window
: typeof global === 'object'
? global
: {}
/* eslint-enable no-undef */

const restore = capture()

/* c8 ignore next 5 */
ctx.Prism = ctx.Prism || {}
ctx.Prism.manual = true
ctx.Prism.disableWorkerMessageHandler = true

/* eslint-disable import/first */

// Load all stuff in `prism.js` itself, except for `prism-file-highlight.js`.
// The wrapped non-leaky grammars are loaded instead of Prism’s originals.
import {h} from 'hastscript'
import {parseEntities} from 'parse-entities'
// @ts-expect-error: untyped.
import Prism from 'prismjs/components/prism-core.js'

/* eslint-enable import/first */

restore()
import {Prism} from './prism-core.js'

const own = {}.hasOwnProperty

Expand Down Expand Up @@ -137,6 +102,7 @@ function highlight(value, language) {

return {
type: 'root',
// @ts-expect-error: we hacked Prism to accept and return the things we want.
children: Prism.highlight.call(refractor, value, grammar, name)
}
}
Expand Down Expand Up @@ -317,33 +283,3 @@ function attributes(attrs) {

return attrs
}

/**
* @returns {() => void}
*/
function capture() {
/** @type {boolean|undefined} */
let defined = 'Prism' in ctx
/* c8 ignore next */
let current = defined ? ctx.Prism : undefined

return restore

/**
* @returns {void}
*/
function restore() {
/* istanbul ignore else - Clean leaks after Prism. */
if (defined) {
// @ts-expect-error: hush.
ctx.Prism = current
/* c8 ignore next 4 */
} else {
// @ts-expect-error: hush.
delete ctx.Prism
}

defined = undefined
current = undefined
}
}