Spec for how the plugin turns a tsserver request inside a tagged template into a CSS language service call and back. Authoritative for the invariants below; change this file first when changing them.
- tsserver
require()s the package root (src/index.ts), which returns a factory producingTsServerStyledPlugin(src/tsserver/tsserver-plugin.ts). create()checks the host TypeScript version, then wraps the host language service withdecorateWithTemplateLanguageServicefromtypescript-template-language-service-decorator.- The decorator finds tagged templates whose tag matches a configured tag name (matching rules:
docs/tsserver-host.md, "Tag matching"), replaces each${...}viagetTemplateSubstitutions(src/template/template-substitutions.ts), and callsStyledTemplateLanguageService(src/template-language-service.ts) with aTemplateContextand template-relative positions. - Each feature (
src/features/*) asks the virtual document provider for an SCSS document, callsvscode-css-languageservice, and translates results back to template-relative offsets. The decorator shifts those to file offsets.
- Output length equals input length, always. Every template offset is also a virtual-text offset (plus the wrapper length).
- Every fill writes its characters over every character of its placeholder, line terminators included, in order (
$a:0plus spaces for a mixin broken across lines when a;follows and the statement rule holds): at runtime the interpolated value holds none of the source's line breaks, and a kept one would split a name, an at-rule prelude, a string, aurl(...)token, or a//comment. A placeholder shorter than a branch's fill gets the next fill in that branch's chain (below), ending at the plain fill: the replacement character over every character. Position mapping never depends on the substituted text's line breaks (the line map in the "Virtual document" section reads the raw text; Emmet, which reads lines from text, gets the line view in the "Completions" section). - Solid fill: a placeholder that starts inside a comment (
/* */or//), a string, or an unquotedurl(...)argument run fills withx, and no branch below applies to it; content there is opaque to the CSS service, and another branch's fill (block position's whitespace, the hex fill's000insideurl(#...)) would change the token. A run that starts with a backslash does not count: an escape, whose backslash may take the placeholder's first character into the escape's identifier at code. An unquotedurl(...)argument whose function name starts with an escape (\75 rl() also starts with a backslash and is excluded with the escapes, since the run list does not tell the two apart; a placeholder there gets its branch's fill. Whether a placeholder starts inside a run depends only on the text before it. A//comment holding a multi-line interpolation continues through it: the solid fill leaves no line terminator inside the placeholder, so the CSS service reads the comment as one unbroken, multi-line comment, matching runtime, where the interpolated value holds no line break either. - Cost is linear in template length for any number or arrangement of placeholders (many on one line included), and builds no per-character tables over the whole text: the document is rebuilt after every edit, so a whole-text pass is paid per keystroke. Forward scans are lazy and shared across placeholders (each kind of scan remembers the range it last covered, so a later query inside that range reuses the answer; the selector list scan below and the search for a comment's closing
*/do the same). The scans that must know what is code (the selector-shape search, the selector list scan, and the running statement boundaries that set where each placeholder's statement starts) read the text's characters directly and step over its non-code runs (comments, strings, escapes, and unquoted url() arguments) whole, each scan keeping its own place in one list of those runs, since each placeholder lies past the previous one. One forward walk with the boundary scanner finds the list, stopping only where the scanner can act (a quote,/, a backslash,), or aubeforeror a backslash), so a text with few such characters, the common case, costs about one search more than plain code. The selector list scan reads a line's last code character back over that line's trailing whitespace and comments only. The running line facts (whether the line holds non-whitespace before a placeholder, and its latest line break or statement boundary, where a line break or non-whitespace character inside a comment or string still counts) jump from one line break or statement boundary to the next and read each stretch between for non-whitespace with one search. The statement rule's look-back past comments jumps between the characters that can open a comment or string instead of visiting every character; the at-rule condition test looks back over at most one gap and one word, and reads each statement's leading whitespace and comments once. The JavaScript escape replacement below is one pass over the masked text, or one search when the text holds no backslash. The masked text and its non-code runs are built once, and the solid fill is decided by one walk of the placeholders against those runs. A template with no placeholders is returned unchanged.pnpm test:scalingguards the linear bound; a before-and-after benchmark guards the constant factor. - Placeholder spans: every scan walks them in ascending order, clamped into the template, with overlapping spans merged into their union (spans that only touch stay separate, as adjacent placeholders do) and empty spans dropped (they substitute nothing). The decorator supplies spans in that shape already; a span list from
./api'sgetSubstitutionsin any other order, overlapping, empty, or out of range is normalized once, with one copy and one sort. The output depends only on span positions, so the same spans in any order give the same output. - Each branch of
getSubstitutiontargets one placeholder shape (property value, whole declaration, property name, selector, at-rule condition, hex color); comments insrc/template/template-substitutions.tsshow each shape. - Masked text: the template text with every placeholder as x's over its whole length (so a line fact never starts a new line inside a placeholder) and JavaScript escapes replaced as the virtual document replaces them (the "Virtual document" section), so a JavaScript-escaped quote,
;, or brace reads as the character styled-components receives. Every rule below reads the masked text; the output keeps the raw text between placeholders. - Name characters, for the rules below: ASCII letters, digits,
-,_, and every UTF-16 code unit from U+0080 up except U+2028 and U+2029, which are line terminators, in the masked text (where adjacent placeholders form one name). This isvscode-css-languageservice6.3.10's_identChar, so a non-ASCII space such as U+00A0 is a name character, as the CSS scanner reads it. The same set serves every name reader in the "Virtual document" section: the boundary scanner, the@layername, and theurlfunction name in the JavaScript escape replacement. - Block position (a placeholder standing in for whole declarations, such as a mixin or a
cssfragment) is filled with whitespace, or, when a;follows it, with the dummy declaration$a:0(thena:0, then whitespace, for a shorter placeholder) if the statement rule's look-back below holds and with x's otherwise (nothing before it to anchor a declaration to). A placeholder is in block position when either rule holds:- Statement rule: the last significant character before it in the masked text, across lines and past comments (a string counts as one significant character at its opening quote, an escape at its backslash, an unquoted
url(...)argument at its(), is;,{,}, or the template start, or is the end of a preceding placeholder that the statement rule itself placed in block position (so${a} ${b}on one line is two mixins, and so iscolor: red; /* note */ ${a}); and the next non-whitespace character after it is none of{,:,,,&,.,#,[,>,+,~,*,%(a rule body, a property name, a selector list, a selector continuation, or a percentage such as the keyframe selector${step}% {). A placeholder inside a comment or string never passes this rule.- Matches styled-components v7's slot classification (
isStandaloneSlotinpackages/styled-components/src/parser/source.ts, an undocumented internal), except,and%: v7 excludes neither, and the plugin adds,so a placeholder that starts a selector list stays x-filled, the safe direction, and%so a placeholder before%stays a number. - Not modeled: v7's missing-semicolon recovery (
shouldRecoverFragmentSlot), which promotes a slot to block position when its value is acssfragment containing;,{, or}(color: red ${fragment};). The plugin sees only the${...}syntax, never the fragment's value, so such a slot stays a value.
- Matches styled-components v7's slot classification (
- Line rule: only whitespace precedes it on its own line, and the next non-whitespace character after it is none of
{,:,,,%. A placeholder placed only by this rule never passes block position on to the next placeholder, sopadding:\n ${a} ${b};andborder:\n ${a}\n ${b};keep${b}a value.
- Statement rule: the last significant character before it in the masked text, across lines and past comments (a string counts as one significant character at its opening quote, an escape at its backslash, an unquoted
- Property name: the next non-whitespace character after the placeholder, or after the name characters joined directly to its end, is
:, without the selector shape below. Such a placeholder is never in block position. Filled with$aplus x's (x's for a one-character placeholder), except:- Inside a custom property name (the statement starts with
--): x's. - Joined to name characters directly before or after it (
padding-${side}:,${side}-top:,border-${side}-color:): the Sass interpolation#{x}plus spaces, which the parser reads as part of one property name and the linter never reports as an unknown property. A placeholder shorter than 4 characters gets x's.
- Inside a custom property name (the statement starts with
- Selector: that
:is followed, on its own line, by a{or&at code with no;or}at code before it (a;or}ends the declaration first, sopadding-${s}: 0; &:hover {and${p}: 0; &:hover {keep a property name), or by a line break at code after which the next non-whitespace character is{(${Child}:not(:last-child)with{on the next line). At code means outside comments, strings, escapes, and unquotedurl(...)arguments, read with the boundary scanner (the "Virtual document" section): a;,{,},&, or line break inside one decides nothing (${Link}:hover /* a; b */ {and${Link}:not([x="a;b"]) {are selectors,${p}: "a{b";a property name), and a//comment ends at its line break, which counts. A line whose last code character is,(comments skipped) continues a selector list: the search goes on over the next line, and over each further line ending in,, for a{or&(${C}:hover,then${C}:focus {), stopping at a;or}(a declaration value continued after,, such as${prop}: a,thenb;) or a blank line. Filled with&plus spaces (nothing for an empty placeholder), except when joined to name characters or right after.,#,&, or:(&.${className}:hover {), where it is part of a name: x's. - At-rule condition: in an
@media,@supports, or@containerprelude that starts the statement (at the start of the placeholder's own line, or, for a prelude split over lines, right after the last;,{, or}at code before it, in both cases after any whitespace, block comments, and//comments; an unterminated block comment hides the at-keyword), a placeholder separated by whitespace and comments, line breaks included, from a precedingand,or, ornot, right after@supports, right after the container name (@container card ${query}), or right after@mediaand followed by a separateor(which follows only a condition, never a media type:@media ${a} or ${b}) stands for a condition. Filled with(x, spaces, and)in@mediaand@container, and withx(, spaces, and)in@supports, which the parser reads as a function-shaped supports condition (the plain fill for a placeholder shorter than 3 characters). Otherwise, right after@mediaor@container, the x-filled placeholder already reads as a media type or a container name. - Hex color: right after
#. Filled with000plus spaces (the plain fill for a placeholder shorter than 3 characters). - Every other placeholder is a value: x's, or
0s right before%.
- Contents: wrapper line, substituted template text with JavaScript escapes replaced (below), then
\n}. Wrapper is one of:@keyframes custom {\nwhen the tag name iskeyframes.:root{all:\n(the value wrapper) when the tag name iscssand the substituted text is value-shaped, such ascss`1px solid red`orcss`${fadeIn} 1s linear`: it validates the text as the value ofall(a known property, so the wrapper line reports nothing of its own;vscode-css-languageservicedoes not check a value against its property's grammar). Value-shaped means all of: no;,{, or}outside strings, comments, and unquotedurl(...)arguments; no:outside strings, comments, and parentheses; some non-whitespace text; the trimmed text is not a single identifier, escapes included (css`dis`is a property name being typed, which needs property completions); and the first non-whitespace character does not start a selector or at-rule (&,>,+,~,*,[,@, or a.not followed by a digit). The test jumps between the characters that can change its answer (the boundary scanner's own,;,{,},:, and parentheses) and stops at the first structural one.- A
cssfragment that misses value shape only because its trimmed text is a single identifier (css`red`,css`none`,css`${x}px`,css`colr`) reads as a value as much as a property name, so it keeps:root{\nfor completions, and validation reports only the diagnostics both readings report: the template is validated a second time under the value wrapper, and a diagnostic is kept only when the value reading has one with the same code, message, and range (both wrappers are one line, so a range past the wrapper names the same template span in either). The wrapper's own ambiguity (colon expected,semi-colon expected) is therefore silent. The validation cache stores the kept list. :root{\notherwise.
- Reading: everything besides the raw text that shapes a template's document and its diagnostics: the wrapper, whether the template's top level is a nested position for the
@layerrewrite (below), and whether acsstemplate is a single identifier (the double validation above). All three are pure functions of the tag kind and the raw template text; nothing else enters (no configuration, no provider state), because the substituted text and its escape replacement are themselves pure functions of the raw text (the placeholder spans are the${...}positions in it). Tag kind:keyframes,css, a global-style tag (createGlobalStyle,globalCss,injectGlobal), or any other tag. So the same raw text under two tag kinds can read differently (@layer x { color: red; }instyled.divand increateGlobalStyle;colrincssand instyled.div).getReadingKeynames the tag kind as a string; the validation cache key andcanReuseVirtualDocument(both in the "Caching" section) use it with the raw text and never compute the reading. The reading is computed only when a document is built or an offset translation needs the wrapper, and kept perTemplateContextand for the last (tag kind, raw text) pair, so a fresh context for unchanged text reuses it. - Line map comes from a line-start table computed once from
context.rawText(the original, unsubstituted template source), never from the substituted text and never fromTemplateContext.toPosition/toOffset: template line L, character C is virtual line L + 1, character C. Virtual line 0 is the wrapper. The table uses TypeScript's own line-terminator rules (\r\n, a lone\n, a lone\r, U+2028, U+2029;docs/tsserver-host.md). Built once perTemplateContextas aTemplateLineMap(createTemplateLineMap,src/virtual-document/template-line-map.ts, which keeps it per context, so the document and the session provider share one table) and threaded through every position a feature translates, not recomputed per diagnostic, hover, folding, or code-fix result: translating a large result set stays linear in the result count.VirtualDocumentSessionProvider.getDocumentandgetParsedDocumentreturn it with the document. The same module maps a virtual range back to template offsets (fromVirtualDocSpan,fromVirtualDocSpanStrict) under the rules below; features take their offsets from these and never callTemplateContext.toOffset. - One boundary scanner (
nonCodeEnd,src/virtual-document/css-code-scanner.ts, with the character predicates every reader shares) decides what is comment, string, escape, or code for these scans, so they never disagree: separator normalization and the@layerrewrite below, the value-shape test above, the stray closing brace search in diagnostics, the statement rule's look-back, the statement boundaries that start an at-rule condition's statement and the custom-property test's text, the selector-shape search in substitution, the nearest non-whitespace character and the joined name after a placeholder, the{that opens a rule body on the next line, and the at-keyword look-back, caret placement, and at-rule prelude test in completions. Those three substitution scans (the nearest non-whitespace character and the joined name after a placeholder, and the{that opens a rule body on the next line) skip whole comment runs, never strings or unquotedurl(...)arguments, which are significant content: a comment between a placeholder and the character that decides its role never hides that character (${Child} /* note */ { color: red; }is a selector,${p} /* note */: red;a property name, and a comment alone on the line before a rule body still opens it). The line rule, and the hex-color and custom-property--tests of the text before a placeholder, still do not skip comments or strings; the at-rule condition's at-keyword test skips only the whitespace and comments that open its statement. The scanner's rules followvscode-css-languageservice6.3.10's own SCSS scanner and the parser that drives it (Scanner.comment,SCSSScanner.comment,Scanner._escape,Parser._parseURILiteral), reading U+2028 and U+2029 outside strings as the\nthe virtual document turns them into:- A block comment runs from
/*to the next*/, or to the end of the text when unterminated. - A
//line comment (SCSS) ends at the next\n,\r,\f, U+2028, or U+2029. - A
'or"string runs through its matching quote, or ends before an unescaped\n,\r, or\f. A backslash escapes one character, or a line break (a\r\npair counts as one), or up to six hex digits plus one optional space, tab, or line break after them. A quote inside a comment opens no string. - Outside strings and comments, a backslash escapes the same way (up to six hex digits plus one optional space, tab, or line break, or else one character) except before a line break, where it escapes nothing, and at the end of the template text, where it also escapes nothing because the virtual document follows the text with a line break. An escaped character is identifier text: an escaped quote opens no string, an escaped
/opens no comment, an escaped brace,;, or@is not structural, and the escape joins the identifier it starts or continues (\41 urlis one identifier). - An unquoted
url(...)argument opens where an identifier whose name, with escapes decoded and compared case-insensitively, isurlorurl-prefixis followed directly by(, as the CSS parser reads one:\75 rl(opens one,image-url(and#url(do not. The parser reads the argument as trivia (whitespace and block comments), one token, then trivia again, with//comments off (SCSSScanner.commenttests!this.inURLfor//only). So inside it:- A
/*opens a block comment only where a token can start: right after the(, right after a string or another comment, or after whitespace that no escape took (url(/* x */a.png),url(a.png /* x */)). Next to url characters,/and*are url content (url(a/*x*/b.png)is one url). //opens no comment.- An escape steps over its own characters, so an escaped
)does not close the argument; an unescaped)does. - Every structural reader skips the argument the way it skips a string: a
;,{, or}in it (url(a;b.png),url(a/*;*/b.png)) ends no statement, opens or closes no block, and makes acssfragment no less value-shaped. The look-back reads the argument as one significant character at its(, so a placeholder or caret inside it follows the(. - Not modeled: the url token ends at whitespace that follows url characters (
url(a b)), where the parser reports an error; the argument stays open here until the).
- A
\fends a string or//comment here but starts no new line for position mapping (the line map above).- A look-back query at the end of a string or comment with no closing delimiter (a string cut off by a line break or the end of the text, an unclosed block comment, a line comment the text ends inside) is inside it: a caret there still types into it. A query at the end of a closed one is after it.
- A block comment runs from
- JavaScript escapes: the template text is the raw source between the backticks, while styled-components (v6 and v7) receives the cooked strings, each escape already resolved to its character (
interleaveinpackages/styled-components/src/utils/interleave.tsreads theTemplateStringsArrayelements, never.raw). Each run of adjacent escape sequences becomes a same-length stand-in for its cooked text (replaceJavaScriptEscapes,src/virtual-document/javascript-escapes.ts) before every other scan in this section reads the text (the value-shape test, separator normalization, the@layerrewrite, and the stray closing brace search in diagnostics). Substitution replaces them in its masked text before any decision (the "Substitution invariants" section). After substitution,getTemplateCssText(same file) computes the replaced text once perTemplateContext, the one source for the virtual document, the value-shape test, and the stray closing brace search; completions read the virtual document, so they see the same text:- The cooked text is written right-aligned in the run's span, with spaces before it (
\"x\"reads as"x ",\\as\). A cooked control character (below U+0020, and U+007F) or U+2028 or U+2029 is written as a space, so\n,\t, and a line continuation (a backslash before a line break, cooked to nothing) become spaces, except for padding inside an unquotedurl(...)argument (below). - When the cooked run ends with a backslash that escapes what follows (an odd count), the padding goes inside that CSS escape instead of before it: as leading zeros before the hex digits that follow (
"\\f101"reads as"\0f101"), while the zeros and digits together stay within six. The CSS escape reads on over hex digits from later runs too: when a later run's cooked text continues those digits, that run joins the stand-in and the zeros go after the backslash for the whole escape ("\\4\x31"reads as"\000041"); outside an unquotedurl(...)argument, when the joined zeros and digits would pass six, each run keeps its own stand-in (x\\fa\x34;reads asx\0fa\034;). Otherwise as the escaped character's own hex code, padded to fill the room (u\\rl(reads asu\72l(), when the code fits and the character after it is none of a hex digit, whitespace, a backslash, or the end of the text. - Otherwise, inside an unquoted
url(...)argument, where a space would end the url token, every run's padding is_, after its cooked text and before a trailing escaping backslash unless placed as below, and none of the name rules below apply:url(a\\(b)reads asurl(a_\(b),url(a/\x41y.png)asurl(a/A___y.png), and a line continuation (url(foo\then a line break, thenbar.png)) asurl(foo__bar.png). The stand-in holds no line break there, which position mapping allows (the line map below counts the raw one). Placement inside the argument:- The
_goes before a)in the cooked text that closes the argument, and before CSS whitespace that ends the url token, so it never lands outside the argument or forms a second token:url(a.png\x20)reads asurl(a.png___ ). A)a cooked backslash escapes, and whitespace a CSS escape takes (after a backslash, or one after a hex escape's digits), is url content:url(\x5c\x31\n\\f)reads asurl(\1 ________\f). - A run that cooks to whitespace alone at the argument's start is leading trivia, padded with spaces (
url(\x204a)reads asurl( 4a)); right after a hex escape a previous run left open, the whitespace comes first, so the escape takes it, and the_follows. - A cooked quote as the argument's first content makes the argument a quoted string: the run is padded as outside a url (
url(\x22\x22)reads asurl( "")).
- The
- The argument is found by reading back from the run over url characters to the
(of aurlorurl-prefixfunction, with whitespace allowed only right after that(; a quote, a paren, or other whitespace means no url, unless a CSS escape takes it (a cooked backslash right before it, or one whitespace after a hex escape of at most six digits:url(a\\"b\x41)andurl(a\\41 b\x41)stay one url). A url function name must be written literally: the name is the run of name characters before the(in the raw text (the name characters defined above), so a name character beforeurl, a non-ASCII letter included, makes a different function name (äurl(,image-url(), and so does a#,@, or backslash before it; a name spelled with an escape inside it or joined to an escape run before it (u\x72l(,\x75rl(,u\\rl(,\x20url() opens no url here, and the runs in its argument are padded as outside one. Inside the argument, a run whose cooked text leaves a CSS hex escape open takes that escape whole (the hex digits after it, raw or from later runs, which then join its stand-in), and its padding goes as leading zeros after the backslash while the escape stays within six digits, or else as_before the backslash, never between the digits and the whitespace the escape takes:url(a\\4\x31 b)reads asurl(a\000041 b), andurl(a\\\x34\x31 b)asurl(a_______\41 b). Each run's look-back stops where the previous run ended and takes that run's answer, unless its cooked text holds a character no CSS escape takes that ends the url token (CSS whitespace, a quote, or a paren) or that the stand-in writes as a space; a character that only JavaScript counts as whitespace (U+00A0, U+3000, U+FEFF) is url content. So the text is read once. - Inside a name, spaces between the name and the run would split it, so when the stand-in starts with a name character or a CSS escape, or is exactly
(right after a name (url() takes no whitespace before its(:url\x28a)reads asurl(a)), the run continues the name before it: name characters read back from the run (to where the previous stand-in ended), plus one leading#,.,@,:, or!. When the character before that name is whitespace,;,{,},(,,, or the template start, the padding moves in front of the whole name and the name reaches the CSS service spelled as it is cooked:co\x6Crreads ascolr(one unknown property,colr),ba\x63kgroundasbackground,r\x65dasred,.md\\:flexas.md\:flex. A later run in the same name adds its padding to the same spaces (\x63ol\x6Frreads ascolor). - Otherwise, where whitespace in front of the name would split a larger token (
&.bt\x6E,a:ho\x76er,color:r\x65d), the last cooked character becomes a CSS hex escape filling the padding, followed directly by the text after the run when that character is none of a hex digit, whitespace, a backslash, or the end of the text (&.bt\06e{), and ended by one space otherwise (&.bor\64 er, since the CSS scanner absorbs one space after a hex escape). The CSS service reads the escaped name as one identifier; a property name spelled with a CSS escape is checked as written, which is why the move in front comes first. - The padding stays spaces before the cooked text, splitting the name, when neither applies: the name is a hash or starts with a digit, where an escaped digit would start an identifier (
color:#f\x66f,margin:1\x30px); the code does not fit six hex digits (a character outside the Basic Multilingual Plane after&.a); the cooked text ends with a CSS escape. A stand-in that starts with any other character (colr\x3a red) keeps its spaces between the name and the run, so an edit to the name alone does not touch the run. - A cooked line break inside a
//comment is a space here, so the comment runs to the real end of its line and hides the rest of that line from validation. - An invalid escape (
\1,\x4,\u{110000}, cooked toundefinedat runtime) stays as written.
- The cooked text is written right-aligned in the run's span, with spaces before it (
- U+2028 and U+2029 become
\noutside quoted CSS strings (the CSS scanner does not treat them as whitespace) and stay verbatim inside strings. Replacement is one character for one character. - Nested block
@layerworkaround: vscode-css-languageservice's SCSS parser parses a block@layerinside a style rule without its nested flag, so a declaration directly in the layer body (@layer utilities { color: red; }) reports a false{ expected(microsoft/vscode-css-languageservice#530). The virtual text rewrites each block@layerprelude that sits in a nested position (the@layerkeyword in any letter case, as the parser matches keywords, plus an optional single layer name of name characters, dotted names and the anonymous form included, up to its{) to spaces with one&just before the{, so the parser reads a nested& { ... }rule with the same body. Nested position is any brace depth inside the template, plus the template's own top level, except when the tag is a global-style tag (createGlobalStyle,globalCss,injectGlobal), whose top level is the stylesheet's top level; which of the two the template's top level is belongs to its reading (above). A comment in the prelude separates tokens as whitespace does and is blanked with the rest of the prelude (@layer /* note */ base {). Statement-form@layer a, b;, a list prelude (@layer a, b {), a prelude holding an unterminated comment, and a prelude holding any other character (a string) stay untouched. The same string, comment, andurl(...)aware scan as the separator normalization does both jobs in one linear pass that jumps between the characters either job can act on (the boundary scanner's own,@, braces, and the separators) and copies each stretch between them unchanged, skipped when the text has neither separator nor@layer. Output length equals input length. Remove this rewrite once the plugin depends on a vscode-css-languageservice release containing the upstream fix. - Mapping back to the template:
- diagnostics, hover, folding: a position on the closing
\n}clamps to the template end, so end-of-template syntax errors (unclosed block, truncated declaration) are reported; a position inside the opening wrapper is dropped. - a hover without its own range: the one character at the caret, or an empty span when the caret sits at the template end, so the span never covers the closing backtick.
- code-fix text edits: any position outside the template body is rejected, because the wrapper does not exist in the source file.
- Escape runs: the span of raw text each run of JavaScript escapes and its stand-in cover (the escaped character after it included when the stand-in took it, the hex digits and later runs a joined CSS hex escape takes, and the name characters before and between the runs when the padding moved in front of the name), computed in the same pass as the replaced text (
getTemplateEscapeRuns) and carried on theTemplateLineMap, which computes them on first read and only when the raw text holds a backslash (no placeholder fill holds one, so without one in the raw text there are no runs). That first read calls back into theTemplateContexttheTemplateLineMapwas built from (getTemplateEscapeRunsreadscontext.text), even when a reused line map (the "Caching" section) answers a later, different context's request: safe only becauseVirtualDocumentSessionProvider.ensureDocumentbuilds aTemplateLineMapsolely alongsidecreateVirtualDocumentfor that same context, andcreateVirtualDocumentalready reads that context's substituted text (getTemplateCssText, which sharesgetTemplateEscapeRuns's own per-context cache injavascript-escapes.ts), so the escape-runs read always hits that cache instead of substituting again. A caller that could obtain aTemplateLineMapwithoutcreateVirtualDocumenthaving already run for its own building context would read a stale context's.textthere. A diagnostic, hover, folding, or completion replacement span whose start or end falls strictly inside a run widens to cover the whole run (\x63olris underlined whole, not3olr). A code fix is dropped when any of its edits overlaps a run, or, when empty, sits strictly inside one: the edit is written for the stand-in, so applied to the escape as written it corrupts it (renaming\x63olrtocolorwould write\x6color). An edit that only touches a run's edge is kept.
- diagnostics, hover, folding: a position on the closing
- A completion list merges, in order: CSS items, SCSS items filtered to pseudo-class functions, nested at-rules (below), then Emmet abbreviations.
- Caret placement, decided on the virtual text (wrapper included) with the boundary scanner (the "Virtual document" section):
- Inside a comment or string, the end of one with no closing delimiter included: no completions at all. The CSS language service offers nothing useful there: none inside a value string, and only selector names inside an attribute-selector string.
- No declaration can start: the last structural code character before the caret (
;,{,}, or:) is:(a value, a selector with a pseudo-class such as&:hover m10 {, or a media feature such as@media (min-width: m10)), or the statement that character ends, past whitespace and comments, starts with@(an at-rule prelude such as@media m10 {). The value wrapper of a value-shapedcssfragment counts, so its whole text is a value. Emmet items that expand to a whole declaration (their label holds a:, such asfloat: left;forfl) are dropped, because accepting one inserts a declaration where none fits. Value expansions (#121212for#12,!important) stay. - Anywhere else, including an empty template and a line typed above a nested rule (
m10before&:hover {, where a declaration can start): every source above. - Cost: the structural search runs only when an Emmet item expands to a declaration, and costs at most two passes over the text before the caret (one in the common case, where the nearest structural character is code), plus the whitespace and comments that open the caret's statement.
- Emmet line view:
@vscode/emmet-helper2.11.0 reads the caret's line from the document text between\ncharacters (getCurrentLine) and indexes it by the caret's character, while positions follow the template's own lines (the line map in the "Virtual document" section). A template line can end without a\nin the virtual text: under a fill, under an escape stand-in (a line continuation), at a lone\r, or at a U+2028 or U+2029 kept inside a string. So Emmet gets a fresh document built over the template text with\nwritten at the end of every template line: the same length as the substituted text, and a document whose own lines are exactly the template's lines, so its line-based reads (getText,getLineRange,lineCount) and its position mapping (offsetAt,positionAt) all agree with each other; the view is the document itself when every template line already ends in\n. Every other consumer reads positions through the document's own mapping. - Nested at-rules:
vscode-css-languageserviceoffers no at-rules inside a style rule (CSS mode returns none; SCSS mode returns only Sass directives, which the SCSS filter drops). When the caret ends or sits inside an at-keyword (@and the name characters around the caret, the set in the "Substitution invariants" section, as the CSS scanner reads one:@,@me,@mé) that is code (not inside a comment or string) and whose preceding significant character in the template, past comments, is;,{,}, or the template start, the list adds the at-rules valid nested in a style rule (@media,@supports,@container,@layer,@scope,@starting-style) and the ones styled-components hoists to the top level (@keyframes,@property,@font-face,@font-palette-values,@page,@counter-style), skipping a label the list already has.- Inclusion rule for hoisted at-rules: one the styled-components v7 emitter writes at the stylesheet's top level, outside the component's selector, through either of its two branches in
packages/styled-components/src/parser/emit-web.ts(an undocumented internal): a name inDECL_BODY_AT_RULES, whose bodyemitAtRulewrites as bare declarations, or a keyframes name, which the parser reads into its own keyframes node (isKeyframesName,packages/styled-components/src/parser/atRuleNames.ts) andemitKeyframeswrites as keyframe blocks of declarations; whose body v7 keeps as the author wrote it; and that the CSS language service completes at the top level. Applied to each candidate:@font-face,@page,@property,@counter-style,@font-palette-values: the declaration branch; bodies of declarations, kept; completed. Included.@keyframes: the keyframes branch; keyframe blocks, kept; completed. Included.@color-profile,@viewport: the declaration branch, but the CSS language service does not complete them. Left out.@font-feature-values: the declaration branch, but its body holds feature-value blocks (@styleset,@swash), whichemitAtRuledrops because it writes only declarations. Left out.- Vendor-prefixed keyframes (
@-webkit-keyframes,@-moz-keyframes,@-o-keyframes): the keyframes branch, and they pass the rule, but they are left out: legacy prefixed syntax is not worth supporting (AGENTS.md, "User experience"), and the unprefixed@keyframesis offered.
- Name, kind, and documentation come from the CSS language service's own top-level at-rule completions (the catalog); a name absent from the catalog is not offered.
- The replacement span covers the whole at-keyword at the caret.
- Inclusion rule for hoisted at-rules: one the styled-components v7 emitter writes at the stylesheet's top level, outside the component's selector, through either of its two branches in
- Every entry is translated the same way: name, kind, kind modifiers, sort text, replacement span; never insert text, a snippet flag, or filter text.
- Entry details for a name the list at that position does not hold (and the recovery fallback, the "Exception recovery" section): the name as the only display part, kind unknown, no kind modifiers, documentation, or tags.
- Validation: the SCSS service's
doValidationover the virtual document, intersected with the value reading for a single-identifiercssfragment (the "Virtual document" section), then extended by the keyframe property check below, memoized byRawValidationCache(the "Caching" section). Withvalidate: false: no diagnostics and no code fixes. - Keyframe property check: the language service lints an unknown property only inside a style rule, so a declaration in a keyframe selector (
from,to,50%, or a list of them) is never checked. AfterdoValidation, the plugin walks the already parsed stylesheet forKeyframeSelectornodes and checks eachDeclarationin them:- A selector counts when its enclosing keyframes at-rule has the keyword
@keyframesin any letter case; a vendor-prefixed keyframes at-rule (@-webkit-keyframes) is excluded. - The check mirrors the language service's unknown-property rule: a name is known when it is in the default CSS data or in
lint.validProperties; a name with one leading-(not--) followslint.unknownVendorSpecificPropertiesinstead; custom properties are skipped; a leading*or_is dropped before the lookup; a name that holds an interpolation is skipped. Codes, messages, levels, and defaults (unknownPropertieswarning,unknownVendorSpecificPropertiesignore) match the main validation. - The diagnostic range is the property node on the document
doCodeActionsreads, so the "Rename to ..." code action finds the declaration. - The walk runs only when the document text holds
@keyframesin any letter case and at least one of the two rules would report; any other template pays for one text search. - Everything else stays with the main validation: a bare declaration in a
keyframestag, declarations in an@mediarule there, declarations in a vendor-prefixed keyframes at-rule, and every other lint rule. - The check runs only with the built-in virtual-document provider and only with the default styles language service. A custom
StylesLanguageServiceFactorymay add CSS data the default list does not know, so its keyframe declarations stay unchecked instead of falsely reported.
- A selector counts when its enclosing keyframes at-rule has the keyword
- Shown list (
DiagnosticsFeature.getShownDiagnostics), the one list diagnostics and code fixes both read: each raw diagnostic mapped to template offsets under the diagnostics rule in "Mapping back to the template" (the "Virtual document" section: clamped at the closing wrapper, dropped inside the opening one, widened to whole escape runs), then the stray closing brace rule below. - Empty rules: with the built-in virtual-document provider, an
emptyRuleslint diagnostic is dropped when the rule body contains a template interpolation. The interpolation may produce declarations at runtime, so the plugin cannot prove that rule empty. The diagnostic stays for a genuinely empty body, including when an interpolation appears only in the selector. Rule-body braces are found in the template's CSS text after JavaScript escapes are cooked, so a JavaScript escape can contribute a structural brace. The boundary scanner ignores braces in comments, strings, CSS escapes, and unquotedurl(...)arguments; an unclosed body extends to the template end while the user is editing. A custom provider owns its document's structure, so its diagnostics are not filtered against the template text. - Translation: the diagnostic's own
codewhen numeric,CSS_DIAGNOSTIC_CODE(9999) otherwise; severity Error or none as Error, Warning as Warning, Information and Hint as Message;sourceis the plugin identity. - Stray closing brace:
css-ruleorselectorexpected("at-rule or selector expected") at the template end reports the wrapper's own closing brace, which the template's content closed early.- Causes: a stray
}, or an unattached;. An empty template reports nothing. - Always kept: never dropped because another diagnostic exists in the template (an unrelated lint warning, or one from the brace's own cascade).
- Re-anchored to the stray
}: the first}in the template's CSS text (getTemplateCssText) with no matching opener, read after JavaScript escapes are cooked, so a JavaScript escape can contribute a structural brace. The boundary scanner ignores a}in a string, comment, CSS escape, or unquotedurl(...)argument; no placeholder fill holds a brace. The span is that one character. - No stray
}(an unattached;): stays at the template end, zero length. - The same code anywhere else in the template is a real diagnostic and stays where reported. Other end-of-template diagnostics (
} expected,property value expected) carry other codes and stay.
- Causes: a stray
- Supported codes:
CSS_DIAGNOSTIC_CODEonly, a constant that builds no language service. A request whose error codes omit it gets no fixes. - A request asks about the shown diagnostics (the "Diagnostics" section) whose template span holds its caret (an empty request; start inclusive, end exclusive) or shares at least one character with its selection. None asked about: no fixes and no CSS service call. So a diagnostic the single-identifier intersection drops gets no fix, and a request after a diagnostics request is answered from the validation cache.
- The asked-about raw diagnostics go to the SCSS service's
doCodeActionswith the request's range mapped into the virtual document. Only_css.applyCodeActioncommands whose third argument is an array of text edits become fixes; each edit maps under the code-fix rule in "Mapping back to the template", and a command with any unmappable edit is dropped whole.
- Every
StyledTemplateLanguageServiceentry point runs inside onerecoverwrapper, so a throw never reaches tsserver: the decorator forwards each result straight into the response for the whole file, TypeScript's own diagnostics included. - On a throw: one line
<method> threw and was recovered: <stack>through the plugin logger (the tsserver log; a service constructed with a language service factory instead of a logger writes none), then the fallback:- completions: an empty completion list, a fresh object per call.
- completion entry details: the unknown-entry details (the "Completions" section).
- quick info: none.
- diagnostics, code fixes, outlining spans: an empty list.
getSupportedCodeFixesreturns its constant and cannot throw.- A recovered throw leaves the service answering later requests.
- One cached virtual document and parsed stylesheet per service, reused only when
canReuseVirtualDocumentholds: same file name, same raw (unsubstituted) template text, same tag kind (the "Virtual document" section, "Reading"). Raw text, not substituted text: two placeholders of equal length can substitute identically while having different line maps. Same tag kind, because the same raw text under another tag kind can read differently; the reading is a pure function of the two, so the check computes neither the reading nor the substituted text. - A request answered from a cache (a validation hit, a reused document or completion result) never reads
TemplateContext.text, which the decorator substitutes lazily, once per context, and every request brings a fresh context: an empty-template test or a template-end bound readsrawText.length(substitution keeps the length).test/unit/template-language-service.test.ts("substitution on unchanged templates") counts substitutions to guard it. - A reused document's
positionAt/offsetAtnever call back into theTemplateContextthat built it, only the line-start table above:TemplateContext.toPosition/toOffsetare memoized by the decorator against the template's position in the file at the moment that context was constructed (StandardTemplateContext,typescript-template-language-service-decorator), so a request that edits the file outside the template moves the template without invalidating a reusable cache entry, and a document that kept consulting the old context would map to the wrong span for the rest of that session. - Completions cache the last result per position with the same reuse rule, both the raw CSS items and the translated tsserver entries, and clear on configuration change.
- The nested at-rule catalog (the "Completions" section) is requested once per service on first use and kept for its lifetime: it does not depend on configuration.
- A third-party
VirtualDocumentProviderwithoutcanReuseVirtualDocumentgets no reuse. - Diagnostics additionally memoize raw (untranslated)
vscode.Diagnostic[]validation results across every template in a file, not just the one-entry virtual-document cache above.RawValidationCache(src/features/diagnostics.ts) is a least-recently-used map keyed by the tag kind (getReadingKey, the "Virtual document" section, "Reading") plus the template's own raw text. A file with many templates otherwise re-parses and re-validates every template on every request, because the one-entry cache above is evicted by the next template before the same template comes around again. - The validation cache is bounded by both an entry count (
MAX_VALIDATION_CACHE_ENTRIES) and an estimated total byte size (MAX_VALIDATION_CACHE_BYTES), whichever binds first. An entry's estimated size is its key length plus, per diagnostic, its message length (both counted as UTF-16 code units times 2 bytes) plus a fixed per-diagnostic overhead constant (VALIDATION_CACHE_DIAGNOSTIC_OVERHEAD_BYTES). An entry estimated larger than the byte budget alone is never cached.pnpm test:scalingguards the byte budget with a long edit session through a realistic multi-kilobyte, many-diagnostic template. - The validation cache stores only raw vscode diagnostics, never translated
ts.Diagnostics (which holdfile: SourceFileand must not outlive the request). Reuse is trusted only for the built-inStyledVirtualDocumentProvider(checked byinstanceof, not by a third-party object merely defining a same-namedcanReuseVirtualDocument, which this cache never calls), because only that provider's virtual text and validation are verified as a pure function of the tag kind and the raw text. A hit builds no document and computes no reading. It needs a line map only when it holds a diagnostic to map (an empty hit maps nothing): the session's line map when the session's cached document is reusable for that template, and a fresh line map otherwise. The cache clears on configuration change because lint settings change validation results. - The validation key length-prefixes the tag kind key before the raw text (
buildValidationCacheKey,src/features/diagnostics.ts), so two different (tag kind key, raw text) pairs cannot concatenate to the same characters. - A stored key is copied so it references none of the open file's text (
flattenCacheKey), only when the cache stores it (set).context.rawTextis a slice of the whole open file's text, and V8 represents a slice of a long string as a view into its parent rather than a copy; the copy is a near-free defense against depending on that unspecified behavior (node --expose-gc test/performance/validation-cache-key-flattening-probe.mjsverifies it). A lookup (peek) compares the caller's unflattened key against stored keys by content, then re-inserts under the matching entry's already-flattened key on a hit. - Flattening uses pure UTF-16 concatenation and slicing, not a Node-only
Buffer: this file is reachable from./api, which a bundler could ship to a browser, and a UTF-8 round trip would rewrite an unpaired surrogate to U+FFFD, colliding two templates that differ only in one.
- Source:
compilerOptions.plugins[]entry at startup, thenconfigurePluginrequests. Each project has an internalProjectConfigurationManager, while the package-root factory shares one internal dynamic configuration store across project plugin instances in the same tsserverProjectService(src/tsserver/editor-configuration.ts). The store recordsnone, the last valid legacy replacement, or the last valid editor overlay, so a project created later in the same session inherits the same dynamic state as existing projects. AWeakMapisolates separate embedded hosts in one process. The managers build on the publicPluginConfigurationManager(src/configuration/plugin-configuration.ts), which normalizes JSON-shaped input, the shape tsconfig andconfigurePlugindeliver, and never throws on it, including when its logger throws. Parsing, logging, and applying configuration to each manager are contained so no exception escapes into tsserver; the calls toProject.getCompilerOptions()andProject.refreshDiagnostics()are unguarded because they are tsserver host calls that cannot throw (docs/tsserver-host.md). - Normalization per field:
tags: a list of strings, or one string as a one-item list. Anything else is rejected.validate: a boolean, or the string"true"or"false". Anything else is rejected.lint,emmet: an object; anything else is rejected. Insidelint, a level setting (every key ofStyledPluginLintConfigurationexceptvalidProperties) takes"ignore","warning", or"error", plus the aliases"off"(as"ignore") and"warn"(as"warning"), each in any letter case ("Error"as"error"); another value is rejected and the key dropped, so a key with a plugin default (defaultConfiguration.lint, such asemptyRules) keeps that default, and any other key gets the CSS language service's own default for that rule. The log message names the plugin default where one applies.validPropertiestakes a list, keeping its string entries and rejecting the rest, or one string as a one-item list. Unknownlintkeys and everyemmetkey pass through unchanged.- A rejected value falls back to its default and logs one message to the tsserver log naming the setting, the accepted form, and the value received. An accepted alias or letter-case variant logs nothing, and neither does an absent field or a
nullorundefinedtop-level configuration. A field set tonullis rejected. - A top-level key that is not one of the fields above is ignored and logs one message naming it and those fields, plus a "Did you mean" suggestion: the setting nearest by edit distance with letter case ignored, when that distance is at most 40% of the key's length (at least 1), so
tagsuggeststagsandvalidationsuggestsvalidate. The keys tsserver adds to the configuration it passes (nameandglobal, docs/tsserver-host.md) log nothing.
- A normal
configurePluginupdate keeps the 1.0.1 behavior: it becomes the complete effective runtime configuration, fields absent from the update return to defaults, and any editor overlay is deactivated. The shared store broadcasts the normalized legacy snapshot to every live manager, including managers belonging to older decorators retained after a project reload. - A plain object with its own
editorConfigurationkey is instead an editor overlay envelope. ItseditorConfiguration.extraTagsfield must be an array. String entries are trimmed, empty strings and non-string entries are dropped, and the rest are stably deduplicated. A non-empty input array from which every entry is dropped is invalid and preserves the current dynamic state; only the literal empty array clears the overlay. A valid normalized list replaces the previous overlay and is appended after each project's base tags with stable deduplication. It cannot changevalidate,lint, oremmet. An invalid envelope preserves the last valid dynamic state for the current tsserver session and never falls back to normal replacement behavior. A host that persists configuration must keep and replay its last valid payload, since a new process cannot recover an invalid payload's predecessor from old process memory. - Legacy runtime replacement and editor overlay are mutually exclusive dynamic states. A valid editor envelope, including
extraTags: [], deactivates the legacy replacement, restores each project's original base, and appends the overlay. This last-kind-wins rule makes the effective state reproducible when a host restarts tsserver and replays its last valid plugin configuration. TsServerStyledPlugin.createreads the project's base from the matchingcompilerOptions.plugins[]entry: the entry that isPluginCreateInfo.configitself, otherwise the entry whosenameequalsPluginCreateInfo.config.name, which can be an npm alias of this package. This preserves the base when tsserver puts a dynamic override inPluginCreateInfo.configafter a pre-projectconfigurePluginrequest. WhenPluginCreateInfo.configis the project's own entry (the same object, or a structurally equal one), it is only the base: aneditorConfigurationkey in it is an unknown setting, not an envelope, and it never becomes shared legacy state. A separately constructedPluginCreateInfo.configwith the same effective plugin settings as that project entry is still the project base; tsserver's injectednameandglobalfields do not make it a legacy replacement. Only different effective settings become shared legacy state. Each created language service has a separate base manager. The shared store keeps live managers in aSetand wraps each project'sclose()once to remove all its managers, including those retained after reloads, before calling the original close method.- Effective configuration changes notify the language service through the existing
onUpdatedConfigpath. After all live managers receive the configuration, including older decorators retained after a reload, the shared store callsrefreshDiagnostics()on one live project. This sends one event for all open files in thatProjectService. A failure while applying configuration to one manager is logged and does not stop the others from updating. Repeating the same normalized overlay, sending an initial overlay that leaves the project configuration unchanged, an invalid envelope, or an equivalent legacy snapshot does not notify, clear caches, or refresh diagnostics. - Editor configuration parsing and tag merging are linear in the number of base and additional tags and run only when configuration changes.
- Defaults (tags, lint levels) live in
PluginConfigurationManager.defaultConfiguration; user-facing documentation indocs/usage.md.
- Package root: the tsserver plugin factory only, at
lib/index.js(1.0.1's exactmainpath), a CommonJS bundle. tsdown builds it aslib/index.cjs(cjsDefaultturnsexport default createPluginintomodule.exports = createPlugin) and abuild:donehook renames it tolib/index.jsand writes a nestedlib/package.json({"type": "commonjs"}) so Node and every supported TypeScript version's classic plugin resolution treat it as CommonJS despite the package root's own"type": "module". The rename matters because tsserver always loads plugins by readingmainand resolving it with classic Node10require(), never through theexportsmap: a.cjs-suffixed main fails to resolve on TypeScript 4.4 and older (docs/tsserver-host.md), the same class of gap already recorded there for a.mjsmain. The singleexports["."]condition (typesplusdefault, noimport/requiresplit) serves this same file to both arequire()caller and animportcaller: Node's ESM loader synthesizes the default export frommodule.exportsfor the latter. Types arelib/index.d.cts(and a copy atlib/index.d.ts, see below), tsdown-generated fromsrc/index.tsusingexport =, which every supported TypeScript version (5.0 through current) parses; a.ctsconsumer reads it asimport plugin = require(...), an ESM consumer reads it as a default import. - Deep subpaths 1.0.1 resolved without any
exportsmap keep resolving through explicit entries:./lib/index,./lib/index.js(both redirect to the root'slib/index.jsruntime andlib/index.d.ctstypes),./lib/api,./lib/api.js(both resolve to the physicallib/api.jsruntime andlib/api.d.tstypes described below), and./package.json. tsserver's own plugin loader only ever readsmainfor., never these subpaths or theexportsmap at all, so they exist purely for a consumer's ownrequire()/import(). Unlike./api, these two subpaths carry one{ types, default }mapping with noimport/requiresplit, because 1.0.1 shippedlib/api.jsas a plain CommonJS file: arequire()and animport x fromof it both got the whole CommonJS exports object back, a shape a real ES module cannot reproduce (it never synthesizes a default export, so a consumer default-importing one gets TS1192).lib/api.jsandlib/api.d.tsare real files, not onlyexportsentries, so a resolver that ignoresexportsentirely (webpack 4, Jest before 28, theresolvepackage's default configuration) still finds them by walkingnode_modulesfor a file at the literal requested path; each is a thin CommonJS re-export of the./apibuild below (module.exports = require('./esm/api.cjs');export * from './esm/api.cjs'), written by thebuild:donehook intsdown.config.ts, so this deep subpath and./api's require condition share onemodule.exportsobject instead of shipping the compiled bundle twice.test/package-api/runtime.tsloads this file by its absolute path in the extracted tarball, bypassingexportsthe same way, to prove it is a real file rather than only anexportsredirect target. @styled/typescript-styled-plugin/api(import and require):StyledTemplateLanguageService,PluginConfigurationManager(and itsConfigurationManageralias, matching 1.0.1's class name),getTemplateSettings, and the configuration and provider types listed insrc/api.ts. Removing or narrowing anything here is breaking and ships in amajorchangeset. Runtime is a real dual build:importgetslib/esm/api.mjs,requiregetslib/esm/api.cjs, a genuine CommonJS bundle (not a stub) generated from the samesrc/api.tsby the same tsdown config's CommonJS format, sorequire('@styled/typescript-styled-plugin/api')works on every Node version this package supports, not only ones withrequire(esm)support;./lib/apiand./lib/api.js(above) always resolve to this same CommonJS bundle, regardless of import or require syntax. Types mirror the runtime split:importgetslib/esm/api.d.mts(tsdown's normal ESM dts pass),requiregetslib/esm/api.d.ctsfrom the CommonJS format, which never imports from the ESM-onlyapi.mjs(the cross-module-system import is what TS1479 flags on TypeScript 5.0 through 5.7) and cannot drift from the source the way a hand-kept copy could. Neither./apibundle loadstypescript-template-language-service-decoratorat runtime:getTemplateSettingslives insrc/template-settings.ts, apart from the tsserver entry that calls the decorator, and the decorator'sTemplateSettingstype reaches the declarations only.moduleResolution: node10ignoresexportsentirely, so a node10 consumer's deep import instead needs either a real file at the literal requested path or atypesVersionsredirect.apiusestypesVersions(package.json) to redirect tolib/esm/api.d.cts;lib/apiandlib/api.jsneed no redirect, since node10's file-based lookup finds the physicallib/api.d.tsnext tolib/api.js(above).lib/indexandlib/index.jscannot use the same mechanism, becausetypesVersionsalso reaches the plugin loader itself for a subpath that equalsmain(docs/tsserver-host.md):lib/index.d.tsis instead a real, physically-copied file (mirroring 1.0.1's ownlib/index.d.tsfilename) that node10's default file-based lookup finds without any redirect.- Emitted declarations are contract:
test/package-apitype-checks the root entry (both a.ctsimport = require(...)consumer and an ESM default-import consumer),./api(both conditions), a consumer written exactly to 1.0.1's published shape (consumer-1.0.1-shape.cts: an unguardedonConfigurationChangedcall, aStyledPluginConfigurationwith arbitrarylint/emmetkeys, and aVirtualDocumentProviderimplementation omitting the optional context parameter), and amoduleResolution: node10consumer of the deep subpaths (consumer-node10.cts), and loads the packed tarball's root,./api, and the deep subpaths from bothrequire()andimport(), including a default import of./lib/api.js(test/package-api/runtime.ts). The type gates run against the minimum and maximum supported TypeScript plus two versions in between, plus the node10 consumer on the current version, all throughpnpm test:package-api:consumers(scripts/test-package-api-types.ts), which runs eachtsconfig.consumers.<gate>.json(the sharedtsconfig.consumers.jsonbase excepted) with the TypeScript itstypescript/*pathsentry names: that override maps the specifier to that exact version's own install (test/e2e/node_modules/<alias>/*, an alias declared intest/e2e/package.json), so the ambienttypescript/lib/tsserverlibrarytypes match the compiler running the check instead of whichevertypescriptversion the root resolves. Adding a TypeScript version means adding one tsconfig. The node10 gate additionally needs a realnode_modules/@styled/typescript-styled-pluginself-link at the repository root, which the same runner creates when missing and re-points when it resolves anywhere else, because node10 resolution has no self-reference feature to fall back on the way node16/nodenext/bundler do. AmoduleResolution: bundlergate (tsconfig.consumers.bundler.json) default-imports./lib/api.js(consumer-lib-api-default.mts, also checked under the default node16-family config above) to prove the CommonJS shape holds under bundler resolution too. StyledPluginConfigurationis the fully-resolved shape 1.0.1 published under this name (tags,validate,lint,emmetall required), withlintandemmettyped exactly as 1.0.1 declared them, the open{ [key: string]: any }shape, not the closedStyledPluginLintConfiguration/StyledPluginEmmetConfigurationinterfaces; those richer, closed shapes live onStyledPluginConfigurationInput, the partial shape for building a configuration from individual overrides, and on the standalone interfaces themselves.- The package root factory's declared return type has
createandonConfigurationChangedboth required, withonConfigurationChanged's parameter typedany, matching 1.0.1's ownStyledPluginclass exactly rather than the host'sts.server.PluginModule(both members optional there): a non-exportedStyledPlugininterface local tosrc/index.tsstates this contract, andTsServerStyledPlugin(src/tsserver/tsserver-plugin.ts) already implements both members as required.