|
1 | 1 | import MagicString from 'magic-string';
|
2 |
| -import * as svelteCompiler from 'svelte/compiler'; |
3 | 2 | import { PreprocessorGroup } from 'svelte/types/compiler/preprocess';
|
4 | 3 |
|
5 | 4 | import { ComponentTrackingInitOptions, SentryPreprocessorGroup, TrackComponentOptions } from './types';
|
@@ -124,8 +123,16 @@ function getBaseName(filename: string): string {
|
124 | 123 | }
|
125 | 124 |
|
126 | 125 | function hasScriptTag(content: string): boolean {
|
127 |
| - const ast = svelteCompiler.parse(content); |
128 |
| - // ast.instance holds whatever is defined in <script> |
129 |
| - // if there is no script tag, it's undefined. |
130 |
| - return ast.instance !== undefined; |
| 126 | + // This regex is taken from the Svelte compiler code. |
| 127 | + // They use this regex to find matching script tags that are passed to the `script` preprocessor hook: |
| 128 | + // https://github.com/sveltejs/svelte/blob/bb83eddfc623437528f24e9fe210885b446e72fa/src/compiler/preprocess/index.ts#L144 |
| 129 | + // However, we remove the first part of the regex to not match HTML comments |
| 130 | + const scriptTagRegex = /<script(\s[^]*?)?(?:>([^]*?)<\/script>|\/>)/gi; |
| 131 | + |
| 132 | + // Regex testing is not a super safe way of checking for the presence of a <script> tag in the Svelte |
| 133 | + // component file but I think we can use it as a start. |
| 134 | + // A case that is not covered by regex-testing HTML is e.g. nested <script> tags but I cannot |
| 135 | + // think of why one would do this in Svelte components. For instance, the Svelte compiler errors |
| 136 | + // when there's more than one top-level script tag. |
| 137 | + return scriptTagRegex.test(content); |
131 | 138 | }
|
0 commit comments