diff --git a/docs/content_mappers/add-span-mappings-alias.svg b/docs/content_mappers/add-span-mappings-alias.svg new file mode 100644 index 0000000000000..845136f4b61db --- /dev/null +++ b/docs/content_mappers/add-span-mappings-alias.svg @@ -0,0 +1,75 @@ + \ No newline at end of file diff --git a/docs/content_mappers/add-span-mappings.svg b/docs/content_mappers/add-span-mappings.svg new file mode 100644 index 0000000000000..65b596d94ccaa --- /dev/null +++ b/docs/content_mappers/add-span-mappings.svg @@ -0,0 +1,75 @@ + \ No newline at end of file diff --git a/docs/content_mappers/class-active-def.png b/docs/content_mappers/class-active-def.png new file mode 100644 index 0000000000000..f86a2afba938a Binary files /dev/null and b/docs/content_mappers/class-active-def.png differ diff --git a/docs/content_mappers/impl_content_mappers.md b/docs/content_mappers/impl_content_mappers.md new file mode 100644 index 0000000000000..86adf1be03f80 --- /dev/null +++ b/docs/content_mappers/impl_content_mappers.md @@ -0,0 +1,761 @@ +# Implementing content mappers + +A content mapper is a child process spawned by the TypeScript compiler that receives and responds to JSON-RPC messages over STDIO. +It can be implemented in any language, but must be provided as a Node.js package with a `package.json` specifying how to launch it: + +`package.json`: +```jsonc +{ + "name": "vue-content-mapper", + "version": "1.0.0", + "typescript": { + "contentMapper": { + "exec": ["node", "dist/server.js"], + "compilerOptions": ["module", "jsx", "jsxImportSource"], + "dynamicConfig": true, + } + } +} +``` +The `package.json` of the content mapper package must specify a `typescript` top-level field with a nested `contentMapper` field describing how to spawn the content mapper process and what compiler options its transform requires. +We'll call that configuration the content mapper's **manifest**. + +A mapper that reads additional project-specific configuration from external sources beyond the specified compiler options must additionally declare `dynamicConfig: true`. +For more details, see [`openProject` requests](#openproject). + +In addition to the options above, a content mapper manifest can optionally specify a mapping of output extensions: + +```jsonc +{ + "name": "ember-content-mapper", + "typescript": { + "contentMapper": { + "exec": ["node", "server.js"], + "outputExtensions": { + ".gts": ".js" + } + } + } +} +``` + +This is useful when the original content mapped files will be emitted to a different format, rather than being left as-is. +In the example above, the `.gts` files are Ember components that Ember will emit to `.js` files. +With this information, TypeScript emits declaration files with the correct file extensions (i.e. `Component.gts` -> `Component.d.ts` instead of `Component.d.gts.ts`) and also permits `.gts` import paths to resolve to `.js` files at runtime via `--rewriteRelativeImportExtensions`. +For more details, see [the implementation PR](https://github.com/microsoft/TypeScript/pull/64581). + +## Protocol + +A content mapper communicates with TypeScript using JSON-RPC over STDIO. +A JSON schema of the content mapper protocol types can be found in the TypeScript npm package, under `/schemas/contentmapper.schema.json`. +TypeScript will spawn content mappers and send requests as needed. +A content mapper must not send requests or notifications to TypeScript; only responses. +The basic requests that a content mapper must handle are `initialize`, `openProject`, `transform`, and `closeProject`. + +### `initialize` + +TypeScript will spawn the content mapper process using the command specified in the `"exec"` option of the content mapper's `package.json`. +It will then send an `initialize` request containing a list of position encodings that TypeScript supports, and optionally a locale that the mapper should use for its diagnostics. + +```ts +/** Parameters for the initialize request. */ +export interface InitializeParams { + /** BCP 47 locale for mapper-authored diagnostic messages, when configured. */ + locale?: string; + /** Coordinate spaces accepted by the host. */ + positionEncodings: PositionEncoding[]; +} + +/** Coordinate space for mappings and diagnostics: UTF-8 byte offsets or UTF-16 code unit offsets. */ +export type PositionEncoding = "utf-8" | "utf-16"; +``` + +The content mapper must respond with one of the supported position encodings that it will use throughout, and also a diagnostic source string that will be used to identify diagnostics emitted by the content mapper. +The diagnostic source must not be `typescript`, `tsc`, or any other extension supported by TypeScript (`ts`, `tsx`, `json`, `js`, etc), so that the content mapper diagnostics are not confused with regular TypeScript diagnostics. + +```ts +/** Response to the initialize request. */ +export interface InitializeResult { + positionEncoding: PositionEncoding; + /** + * Prefix for mapper-authored diagnostic codes. It must not be whitespace-only or, ignoring case, typescript, tsc, + * or a native source extension without its leading dot. + */ + diagnosticSource: string; +} +``` + +After initialization, the content mapper must be ready to receive the other kinds of requests. + +Note that the protocol will only change in backward-compatible ways after its official release. +New features may be added via LSP-like capabilities negotiation in `initialize`. + +### `openProject` + +The first time TypeScript needs to transform a file in a project, it will send an `openProject` request containing a project handle that uniquely identifies the project, the project's relevant compiler options (as specified in the content mapper's manifest), the content mapper options specified in the project's `tsconfig.json`, and optionally a path to a tsconfig for that project, if any exists. + +```ts +/** Parameters for the openProject request. */ +export interface OpenProjectParams { + /** Absolute project configuration file name, or an empty string when there is none. */ + configFileName: string; + /** Opaque, process-local project handle assigned by the host. */ + projectHandle: string; + /** Mapper entry's options from the project's contentMappers configuration. */ + options?: unknown; + /** Project's effective compiler options, serialized by the host. */ + compilerOptions: unknown; +} +``` + +The content mapper must respond to this request. +Its response should contain diagnostics for the project's content mapper options, if any exist. +Additionally, if the content mapper specified `dynamicConfig: true` in its manifest, the response must contain a `configIdentity`: a stable fingerprint of all *dynamically discovered configuration* that can affect transforms for the project. +If `dynamicConfig: true`, the content mapper's response may also contain a list of `watchedFiles`, which are additional files that, if modified, may change the project's `configIdentity` and affect the content mapper's transform. +In that case, whenever a file in the list of `watchedFiles` changes, TypeScript will send a request to close the project (see [`closeProject`](#closeproject)). +TypeScript may then call `openProject` for the same project again when needed. +If changes to the watched files affect the content mapper's transform behavior, that mapper must return a different `configIdentity` for this new `openProject` request. + +```ts +/** + * Response to an openProject request. Only mappers declaring dynamicConfig may return a non-empty configIdentity or + * watchedFiles. + */ +export interface OpenProjectResult { + /** + * Stable fingerprint of all dynamic configuration affecting transforms. It must be non-empty for dynamicConfig + * mappers; otherwise it must be empty or omitted. + */ + configIdentity?: string; + /** Absolute file names whose changes may alter configIdentity or transform output. */ + watchedFiles?: string[]; + /** Diagnostics reporting invalid mapper options. */ + optionDiagnostics?: OptionDiagnosticResult[]; +} +``` + +As an example, if a project uses the Vue content mapper, its content mapper options can specify a Vue target version. +One way to configure the Vue target is to specify `target: "auto"`: + +`project/tsconfig.json`: +```jsonc +{ + "compilerOptions": { + ... + }, + "contentMappers": [ + { + "package": "@vue/content-mapper", + "extensions": [".vue"], + "options": { + "target": "auto" // Vue content mapper's target + } + } + ] +} +``` + +Under this target option, the Vue content mapper reads the nearest `node_modules/vue/package.json` to determine the Vue version: + +`project/node_modules/vue/package.json`: +```jsonc +{ + "name": "vue", + "version": "3.5.46", // version that the content mapper will use + "description": "The progressive JavaScript framework for building modern web UI.", + ... +} +``` + +If the nearest `node_modules/vue/package.json`'s version changes from `3.5.46` to `3.6.0`, it affects the virtual content produced by the content mapper for a Vue file. +Therefore the Vue content mapper's manifest needs to specify `dynamicConfig: true`, its `openProject` response needs to encode the Vue version `3.5.46` in the `configIdentity`, and the response can specify `project/node_modules/vue/package.json` as a watched file. + +Note that compiler options will only be sent by TypeScript as part of the `openProject` request. +The content mapper should store the compiler options for each opened project and associate them with the project's handle so that it can use them during a [`transform`](#transform) request. + +Also note that a single content mapper process must be able to handle multiple projects, because TypeScript tries to reuse a content mapper process for any project that matches that content mapper. + +### `transform` + +When a content-mapped file is [included in a TypeScript program](intro_content_mappers.md#including-content-mapped-files), TypeScript will need to transform that file into a file it can understand. +For instance, if there's a TS file in a program that imports a content-mapped file: + +`index.ts`: +```ts +import { createApp } from 'vue' +import UserList from './UserList.vue' + +createApp(UserList).mount('#app') +``` + +Then TypeScript needs to transform `UserList.vue` into e.g. a TS or JS file. +To do that, it sends a `transform` request to the content mapper. +That request will have the absolute filename of the *original file* (e.g. `/home/blah/project/file1.vue`), the content of that file, and the handle of the project that file belongs to. + +```ts +/** Parameters for the transform request. */ +export interface TransformParams { + /** Absolute name of the content-mapped source file. */ + fileName: string; + /** Original source text. */ + content: string; + /** Handle for the project configuration opened for this transform. */ + projectHandle: string; +} +``` + +The content mapper should then respond with information about the content-mapped *virtual file*: its transformed content, its extension (e.g. `.ts`, `.tsx`, etc.), *span mappings* between spans in the virtual file and the original file, and diagnostic directives for the virtual file (e.g. `@ts-expect-error`). + +```ts +/** Canonical output for one input file, with optional mapper diagnostics and supplemental compiler inputs. */ +export interface TransformResult extends MappedOutput { + /** Mapper-authored errors in original-source coordinates. */ + diagnostics?: Diagnostic[]; + /** Additional unnamed compiler inputs associated with this source file. */ + supplemental?: SupplementalOutput[]; +} + +/** Virtual source text and its mapping to the original input. */ +export interface MappedOutput { + /** Virtual source text. */ + text: string; + /** Extension determining the virtual source file's syntax. */ + extension: ".js" | ".jsx" | ".mjs" | ".cjs" | ".ts" | ".tsx" | ".mts" | ".cts" | ".json"; + /** + * Span map tuples in the selected position encoding. Absent, null, or empty mappings describe fully synthesized + * output. + */ + mappings?: SpanMapSegment[] | null; + diagnosticDirectives?: DiagnosticDirectives; +} +``` + +#### Span mappings + +A *span* is a pair of a position and a length within a given file's source text. +The position and length use the `positionEncoding` specified in a session's `initialize` request. +*Span mappings* correlate spans in the original file and virtual file: + + + +TypeScript needs these mappings to emit diagnostics and to power other language server features. +In the CLI, these mappings are used to show TypeScript-generated diagnostics in the original, non-TypeScript content; in the example above, the following diagnostic is shown: + +``` +add.lisp:7:13 - error TS2345: Argument of type 'string' is not assignable to parameter of type 'number'. + +1 (+ 1 2 "oops") + ~~~~~~ +``` + +For more details, see [More on span mappings](#more-on-span-mappings-and-language-features). + +#### Diagnostic directives + +A content mapper can have its own diagnostic directives, whose scoping rules can be different from TypeScript's `// @ts-ignore` or `// @ts-expect-error`. +For instance, Vue supports the `@vue-expect-error` directive: + +`File.vue`: +```vue + +
+``` + +`File.ts`: +```ts +__VLS_asFunctionalElement1( + __VLS_intrinsics.div, + __VLS_intrinsics.div, +)({ + id: (__VLS_ctx.firstError), + title: (__VLS_ctx.secondError), +}); +``` + +The expect-error directive in Vue applies to errors on every line of the `Hello
+ + +``` + +`ClassBinding.ts` (virtual file): +```ts +///Hello
`, is mapped to three virtual spans: +`active` property in `...{ class: ({ |active|: active }) }`, `active` reference in `...{ class: ({ active: |active| }) }`, and `active` key text in `/** @type {__VLS_StyleScopedClasses['|active|']} */;`. +The `features` masks of all three span mappings include the "definition" feature, so if we run "Go To Definition" on `active` in `Hello
`, we will get three occurrences, each corresponding to running "Go To Definition" on a span in the virtual file and mapping the result back to the original file: + + + +Only the first two span mappings include the "hover" feature, such that if we hover over `active`, we only see hover content corresponding to these two mappings, one for a property, another for a variable reference. +The third span mapping is ignored: + +``` +(property) active: boolean +const active: boolean +``` + +More precisely, the TypeScript language server currently supports the following features for content-mapped files: + +- **Diagnostics** - always mapped to original content where possible; diagnostics in synthesized regions are collected and reported at the top of the file. Declared-but-not-used diagnostics are automatically suppressed in synthesized regions. Diagnostics are intentionally not represented by a span-map feature flag. Framework-specific semantic diagnostic suppression is instead expressed explicitly through [`diagnosticDirectives`](#diagnostic-directives). +- **Position-based features** - hover, signature help, completions, definitions, type definitions, implementations, source definitions, references, document highlights, rename, call hierarchy, code actions, formatting, linked editing, and auto-insert map incoming positions or ranges through spans participating in their corresponding `SpanMapFeature` flag. +- **Document-wide features** - inlay hints, semantic tokens, folding ranges, selection ranges, document symbols, and CodeLens map visible results back only through spans participating in their corresponding flag. +- **Text edits** - feature participation does not make a mapping edit-safe. Rename, code action, completion, and formatting edits may be written back only through exact, length-preserving `SpanMapKind.Verbatim` mappings. + +```ts +/** + * Language-service feature bitmask. Diagnostics and exact edit mapping do not use feature filtering. Named flags may be + * combined. + */ +export enum SpanMapFeature { + Hover = 1, + SignatureHelp = 2, + Completion = 4, + Definition = 8, + TypeDefinition = 16, + Implementation = 32, + References = 64, + DocumentHighlights = 128, + Rename = 256, + CallHierarchy = 512, + CodeActions = 1024, + Formatting = 2048, + InlayHints = 4096, + SemanticTokens = 8192, + FoldingRanges = 16384, + SelectionRanges = 32768, + LinkedEditing = 65536, + AutoInsert = 131072, + DocumentSymbols = 262144, + CodeLens = 524288, + None = 0, + All = 1048575, +} +``` + +Language service requests and visible results can be disabled independently for any span by clearing the corresponding bits, or disabled for all features with `SpanMapFeature.None`. If `features` is omitted from the span mapping tuple, it defaults to `SpanMapFeature.All`, enabling every supported language service feature for that span. + +> [!NOTE] +> Unlike with Volar, feature participation must be statically determined by the content mapper during transformation. +This level of LSP feature mapping is not intended to replace fully custom language servers. TypeScript’s goal in providing language service support for content-mapped files is to support a good editing experience inside ` + + + + + + +``` + +Content mappers allow TypeScript to understand these specialized file types by mapping their content to equivalent TypeScript code. +For the example above, a Vue content mapper could map that `.vue` file into the following TypeScript file: + +`UserList.ts`: +```ts +import { ref } from 'vue' +const count = ref