@mdsvex/language-core 0.0.0 → 0.1.0-next.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +13 -0
- package/LICENSE +21 -0
- package/package.json +26 -7
- package/src/_svelte_shims.ts +1 -0
- package/src/index.ts +4 -0
- package/src/language_plugin.ts +405 -0
- package/src/svelte_plugin.ts +183 -0
- package/test/language_plugin.spec.ts +177 -0
- package/tsconfig.json +11 -0
- package/README.md +0 -3
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
# @mdsvex/language-core
|
|
2
|
+
|
|
3
|
+
## 0.1.0-next.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- [#799](https://github.com/pngwn/MDsveX/pull/799) [`5b54692`](https://github.com/pngwn/MDsveX/commit/5b54692d6c895f02c947ce620a46c7a9beb856e9) Thanks [@pngwn](https://github.com/pngwn)! - Add language tools
|
|
8
|
+
|
|
9
|
+
### Patch Changes
|
|
10
|
+
|
|
11
|
+
- Updated dependencies [[`6ac3826`](https://github.com/pngwn/MDsveX/commit/6ac382615eb410230e8423d5ca4202005588869e), [`e5b7abe`](https://github.com/pngwn/MDsveX/commit/e5b7abe1ebf868b1df1e934fb96e1e363696f3e9), [`5b54692`](https://github.com/pngwn/MDsveX/commit/5b54692d6c895f02c947ce620a46c7a9beb856e9)]:
|
|
12
|
+
- @mdsvex/render@1.0.0-next.0
|
|
13
|
+
- @mdsvex/source-map@0.1.0-next.0
|
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2020 pngwn
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/package.json
CHANGED
|
@@ -1,15 +1,34 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@mdsvex/language-core",
|
|
3
|
-
"version": "0.0.0",
|
|
4
|
-
"description": "Placeholder release so npm trusted publishing can be configured.",
|
|
5
|
-
"license": "MIT",
|
|
6
|
-
"homepage": "https://mdsvex.pngwn.io",
|
|
3
|
+
"version": "0.1.0-next.0",
|
|
7
4
|
"repository": {
|
|
8
5
|
"type": "git",
|
|
9
|
-
"url": "https://github.com/pngwn/MDsveX",
|
|
6
|
+
"url": "git+https://github.com/pngwn/MDsveX.git",
|
|
10
7
|
"directory": "language-tools/language-core"
|
|
11
8
|
},
|
|
12
|
-
"
|
|
13
|
-
|
|
9
|
+
"description": "PFM Volar LanguagePlugin — teaches Volar how to handle .pfm files",
|
|
10
|
+
"type": "module",
|
|
11
|
+
"exports": {
|
|
12
|
+
".": {
|
|
13
|
+
"import": "./src/index.ts",
|
|
14
|
+
"types": "./src/index.ts"
|
|
15
|
+
}
|
|
16
|
+
},
|
|
17
|
+
"dependencies": {
|
|
18
|
+
"@volar/language-core": "^2.4.28",
|
|
19
|
+
"@volar/typescript": "^2.4.28",
|
|
20
|
+
"svelte2tsx": "^0.7.53",
|
|
21
|
+
"@mdsvex/source-map": "0.1.0-next.0",
|
|
22
|
+
"@mdsvex/render": "1.0.0-next.0"
|
|
23
|
+
},
|
|
24
|
+
"devDependencies": {
|
|
25
|
+
"svelte": "^5.0.0",
|
|
26
|
+
"typescript": "^5.0.0"
|
|
27
|
+
},
|
|
28
|
+
"author": "pngwn <hello@pngwn.io>",
|
|
29
|
+
"license": "MIT",
|
|
30
|
+
"scripts": {
|
|
31
|
+
"test": "vitest --disableConsoleIntercept",
|
|
32
|
+
"test:run": "vitest run --silent"
|
|
14
33
|
}
|
|
15
34
|
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export const SVELTE_SHIMS = "// Whenever a ambient declaration changes, its number should be increased\n// This way, we avoid the situation where multiple ambient versions of svelte2tsx\n// are loaded and their declarations conflict each other\n// See https://github.com/sveltejs/language-tools/issues/1059 for an example bug that stems from it\n// If you change anything in this file, think about whether or not it should be backported to svelte-shims.d.ts\n\ntype AConstructorTypeOf<T, U extends any[] = any[]> = new (...args: U) => T;\n\n/** @internal PRIVATE API, DO NOT USE */\ntype SvelteActionReturnType = {\n\tupdate?: (args: any) => void,\n\tdestroy?: () => void\n} | void\n\n/** @internal PRIVATE API, DO NOT USE */\ntype SvelteTransitionConfig = {\n delay?: number,\n duration?: number,\n easing?: (t: number) => number,\n css?: (t: number, u: number) => string,\n tick?: (t: number, u: number) => void\n}\n\n/** @internal PRIVATE API, DO NOT USE */\ntype SvelteTransitionReturnType = SvelteTransitionConfig | (() => SvelteTransitionConfig)\n\n/** @internal PRIVATE API, DO NOT USE */\ntype SvelteAnimationReturnType = {\n delay?: number,\n duration?: number,\n easing?: (t: number) => number,\n css?: (t: number, u: number) => string,\n tick?: (t: number, u: number) => void\n}\n\n/** @internal PRIVATE API, DO NOT USE */\ntype SvelteWithOptionalProps<Props, Keys extends keyof Props> = Omit<Props, Keys> & Partial<Pick<Props, Keys>>;\n/** @internal PRIVATE API, DO NOT USE */\ntype SvelteAllProps = { [index: string]: any }\n/** @internal PRIVATE API, DO NOT USE */\ntype SveltePropsAnyFallback<Props> = {[K in keyof Props]: Props[K] extends never ? never : Props[K] extends undefined ? any : Props[K]}\n/** @internal PRIVATE API, DO NOT USE */\ntype SvelteSlotsAnyFallback<Slots> = {[K in keyof Slots]: {[S in keyof Slots[K]]: Slots[K][S] extends undefined ? any : Slots[K][S]}}\n/** @internal PRIVATE API, DO NOT USE */\ntype SvelteRestProps = { [index: string]: any }\n/** @internal PRIVATE API, DO NOT USE */\ntype SvelteSlots = { [index: string]: any }\n/** @internal PRIVATE API, DO NOT USE */\ntype SvelteStore<T> = { subscribe: (run: (value: T) => any, invalidate?: any) => any }\n\n// Forces TypeScript to look into the type which results in a better representation of it\n// which helps for error messages and is necessary for d.ts file transformation so that\n// no ambient type references are left in the output\n/** @internal PRIVATE API, DO NOT USE */\ntype Expand<T> = T extends infer O ? { [K in keyof O]: O[K] } : never;\n\n/** @internal PRIVATE API, DO NOT USE */\ntype KeysMatching<Obj, V> = {[K in keyof Obj]-?: Obj[K] extends V ? K : never}[keyof Obj]\n/** @internal PRIVATE API, DO NOT USE */\ndeclare type __sveltets_2_CustomEvents<T> = {[K in KeysMatching<T, CustomEvent>]: T[K] extends CustomEvent ? T[K]['detail']: T[K]}\n\ndeclare function __sveltets_2_ensureRightProps<Props>(props: Props): {};\ndeclare function __sveltets_2_instanceOf<T = any>(type: AConstructorTypeOf<T>): T;\ndeclare function __sveltets_2_allPropsType(): SvelteAllProps\ndeclare function __sveltets_2_restPropsType(): SvelteRestProps\ndeclare function __sveltets_2_slotsType<Slots, Key extends keyof Slots>(slots: Slots): Record<Key, boolean>;\n\n// Overload of the following two functions is necessary.\n// An empty array of optionalProps makes OptionalProps type any, which means we lose the prop typing.\n// optionalProps need to be first or its type cannot be infered correctly.\n\ndeclare function __sveltets_2_partial<Props = {}, Events = {}, Slots = {}, Exports = {}, Bindings = string>(\n render: {props: Props, events: Events, slots: Slots, exports?: Exports, bindings?: Bindings }\n): {props: Expand<SveltePropsAnyFallback<Props>>, events: Events, slots: Expand<SvelteSlotsAnyFallback<Slots>>, exports?: Exports, bindings?: Bindings }\ndeclare function __sveltets_2_partial<Props = {}, Events = {}, Slots = {}, Exports = {}, Bindings = string, OptionalProps extends keyof Props = any>(\n optionalProps: OptionalProps[],\n render: {props: Props, events: Events, slots: Slots, exports?: Exports, bindings?: Bindings }\n): {props: Expand<SvelteWithOptionalProps<SveltePropsAnyFallback<Props>, OptionalProps>>, events: Events, slots: Expand<SvelteSlotsAnyFallback<Slots>>, exports?: Exports, bindings?: Bindings }\n\ndeclare function __sveltets_2_partial_with_any<Props = {}, Events = {}, Slots = {}, Exports = {}, Bindings = string>(\n render: {props: Props, events: Events, slots: Slots, exports?: Exports, bindings?: Bindings }\n): {props: Expand<SveltePropsAnyFallback<Props> & SvelteAllProps>, events: Events, slots: Expand<SvelteSlotsAnyFallback<Slots>>, exports?: Exports, bindings?: Bindings }\ndeclare function __sveltets_2_partial_with_any<Props = {}, Events = {}, Slots = {}, Exports = {}, Bindings = string, OptionalProps extends keyof Props = any>(\n optionalProps: OptionalProps[],\n render: {props: Props, events: Events, slots: Slots, exports?: Exports, bindings?: Bindings }\n): {props: Expand<SvelteWithOptionalProps<SveltePropsAnyFallback<Props>, OptionalProps> & SvelteAllProps>, events: Events, slots: Expand<SvelteSlotsAnyFallback<Slots>>, exports?: Exports, bindings?: Bindings }\n\n\ndeclare function __sveltets_2_with_any<Props = {}, Events = {}, Slots = {}, Exports = {}, Bindings = string>(\n render: {props: Props, events: Events, slots: Slots, exports?: Exports, bindings?: Bindings }\n): {props: Expand<Props & SvelteAllProps>, events: Events, slots: Slots, exports?: Exports, bindings?: Bindings }\n\ndeclare function __sveltets_2_with_any_event<Props = {}, Events = {}, Slots = {}, Exports = {}, Bindings = string>(\n render: {props: Props, events: Events, slots: Slots, exports?: Exports, bindings?: Bindings }\n): {props: Props, events: Events & {[evt: string]: CustomEvent<any>;}, slots: Slots, exports?: Exports, bindings?: Bindings }\n\ndeclare function __sveltets_2_store_get<T = any>(store: SvelteStore<T>): T\ndeclare function __sveltets_2_store_get<Store extends SvelteStore<any> | undefined | null>(store: Store): Store extends SvelteStore<infer T> ? T : Store;\ndeclare function __sveltets_2_any(dummy: any): any;\ndeclare function __sveltets_2_invalidate<T>(getValue: () => T): T\n\ndeclare function __sveltets_2_mapWindowEvent<K extends keyof HTMLBodyElementEventMap>(\n event: K\n): HTMLBodyElementEventMap[K];\ndeclare function __sveltets_2_mapBodyEvent<K extends keyof WindowEventMap>(\n event: K\n): WindowEventMap[K];\ndeclare function __sveltets_2_mapElementEvent<K extends keyof HTMLElementEventMap>(\n event: K\n): HTMLElementEventMap[K];\n\ndeclare function __sveltets_2_bubbleEventDef<Events, K extends keyof Events>(\n events: Events, eventKey: K\n): Events[K];\ndeclare function __sveltets_2_bubbleEventDef(\n events: any, eventKey: string\n): any;\n\ndeclare const __sveltets_2_customEvent: CustomEvent<any>;\ndeclare function __sveltets_2_toEventTypings<Typings>(): {[Key in keyof Typings]: CustomEvent<Typings[Key]>};\n\ndeclare function __sveltets_2_unionType<T1, T2>(t1: T1, t2: T2): T1 | T2;\ndeclare function __sveltets_2_unionType<T1, T2, T3>(t1: T1, t2: T2, t3: T3): T1 | T2 | T3;\ndeclare function __sveltets_2_unionType<T1, T2, T3, T4>(t1: T1, t2: T2, t3: T3, t4: T4): T1 | T2 | T3 | T4;\ndeclare function __sveltets_2_unionType(...types: any[]): any;\n\ndeclare function __sveltets_2_createSvelte2TsxComponent<Props extends {}, Events extends {}, Slots extends {}>(\n render: {props: Props, events: Events, slots: Slots }\n): typeof import(\"svelte\").SvelteComponent<Props, Events, Slots>;\n\ndeclare function __sveltets_2_unwrapArr<T>(arr: ArrayLike<T>): T\ndeclare function __sveltets_2_unwrapPromiseLike<T>(promise: PromiseLike<T> | T): T\n\n// v2\ndeclare function __sveltets_2_createCreateSlot<Slots = Record<string, Record<string, any>>>(): <SlotName extends keyof Slots>(slotName: SlotName, attrs: Slots[SlotName]) => Record<string, any>;\ndeclare function __sveltets_2_createComponentAny(props: Record<string, any>): import(\"svelte\").SvelteComponent<any, any, any>;\n\ndeclare function __sveltets_2_any(...dummy: any[]): any;\ndeclare function __sveltets_2_empty(...dummy: any[]): {};\ndeclare function __sveltets_2_union<T1,T2,T3,T4,T5,T6,T7,T8,T9,T10>(t1:T1,t2?:T2,t3?:T3,t4?:T4,t5?:T5,t6?:T6,t7?:T7,t8?:T8,t9?:T9,t10?:T10): T1 & T2 & T3 & T4 & T5 & T6 & T7 & T8 & T9 & T10;\ndeclare function __sveltets_2_nonNullable<T>(type: T): NonNullable<T>;\n\ndeclare function __sveltets_2_cssProp(prop: Record<string, any>): {};\n\n// @ts-ignore Svelte v3/v4 don't have this\ndeclare function __sveltets_2_ensureSnippet(val: ReturnType<import('svelte').Snippet> | undefined | null): any;\n\n/** @internal PRIVATE API, DO NOT USE */\ntype __sveltets_2_SvelteAnimationReturnType = {\n delay?: number,\n duration?: number,\n easing?: (t: number) => number,\n css?: (t: number, u: number) => string,\n tick?: (t: number, u: number) => void\n}\ndeclare var __sveltets_2_AnimationMove: { from: DOMRect, to: DOMRect }\ndeclare function __sveltets_2_ensureAnimation(animationCall: __sveltets_2_SvelteAnimationReturnType): {};\n\n/** @internal PRIVATE API, DO NOT USE */\ntype __sveltets_2_SvelteActionReturnType = {\n\tupdate?: (args: any) => void,\n\tdestroy?: () => void,\n $$_attributes?: Record<string, any>,\n} | void\ndeclare function __sveltets_2_ensureAction<T extends __sveltets_2_SvelteActionReturnType>(actionCall: T): T extends {$$_attributes?: any} ? T['$$_attributes'] : {};\n\n/** @internal PRIVATE API, DO NOT USE */\ntype __sveltets_2_SvelteTransitionConfig = {\n delay?: number,\n duration?: number,\n easing?: (t: number) => number,\n css?: (t: number, u: number) => string,\n tick?: (t: number, u: number) => void\n}\n/** @internal PRIVATE API, DO NOT USE */\ntype __sveltets_2_SvelteTransitionReturnType = __sveltets_2_SvelteTransitionConfig | (() => __sveltets_2_SvelteTransitionConfig)\ndeclare function __sveltets_2_ensureTransition(transitionCall: __sveltets_2_SvelteTransitionReturnType): {};\n\n// Includes undefined and null for all types as all usages also allow these\ndeclare function __sveltets_2_ensureType<T>(type: AConstructorTypeOf<T>, el: T | undefined | null): {};\ndeclare function __sveltets_2_ensureType<T1, T2>(type1: AConstructorTypeOf<T1>, type2: AConstructorTypeOf<T2>, el: T1 | T2 | undefined | null): {};\n\n// The following is necessary because there are two clashing errors that can't be solved at the same time\n// when using Svelte2TsxComponent, more precisely the event typings in\n// __sveltets_2_ensureComponent<T extends new (..) => _SvelteComponent<any,||any||<-this,any>>(type: T): T;\n// If we type it as \"any\", we have an error when using sth like {a: CustomEvent<any>}\n// If we type it as \"{}\", we have an error when using sth like {[evt: string]: CustomEvent<any>}\n// If we type it as \"unknown\", we get all kinds of follow up errors which we want to avoid\n// Therefore introduce two more base classes just for this case.\n/**\n * Ambient type only used for intellisense, DO NOT USE IN YOUR PROJECT\n */\ndeclare type ATypedSvelteComponent = {\n /**\n * @internal This is for type checking capabilities only\n * and does not exist at runtime. Don't use this property.\n */\n $$prop_def: any;\n /**\n * @internal This is for type checking capabilities only\n * and does not exist at runtime. Don't use this property.\n */\n $$events_def: any;\n /**\n * @internal This is for type checking capabilities only\n * and does not exist at runtime. Don't use this property.\n */\n $$slot_def: any;\n\n $on(event: string, handler: any): () => void;\n}\n/**\n * Ambient type only used for intellisense, DO NOT USE IN YOUR PROJECT.\n * \n * If you're looking for the type of a Svelte Component, use `SvelteComponent` and `ComponentType` instead:\n *\n * ```ts\n * import type { ComponentType, SvelteComponent } from \"svelte\";\n * let myComponentConstructor: ComponentType<SvelteComponent> = ..;\n * ```\n */\ndeclare type ConstructorOfATypedSvelteComponent = new (args: {target: any, props?: any}) => ATypedSvelteComponent\n// Usage note: Cannot properly transform generic function components to class components due to TypeScript limitations\ndeclare function __sveltets_2_ensureComponent<\n T extends\n | ConstructorOfATypedSvelteComponent\n | (typeof import('svelte') extends { mount: any }\n ? // @ts-ignore svelte.Component doesn't exist in Svelte 4\n import('svelte').Component<any, any, any>\n : never)\n | null\n | undefined\n>(\n type: T\n): NonNullable<\n T extends ConstructorOfATypedSvelteComponent\n ? T\n : typeof import('svelte') extends { mount: any }\n ? // @ts-ignore svelte.Component doesn't exist in Svelte 4\n T extends import('svelte').Component<\n infer Props extends Record<string, any>,\n infer Exports extends Record<string, any>,\n infer Bindings extends string\n >\n ? new (\n options: import('svelte').ComponentConstructorOptions<Props>\n ) => import('svelte').SvelteComponent<Props, Props['$$events'], Props['$$slots']> &\n Exports & { $$bindings: Bindings }\n : never\n : never\n>;\n\ndeclare function __sveltets_2_ensureArray<T extends ArrayLike<unknown> | Iterable<unknown>>(\n // Svelte 5 allows undefined or null here, Svelte 4 doesn't\n array: T | (typeof import('svelte') extends { mount: any } ? (undefined | null) : never)\n): T extends ArrayLike<infer U> ? U[] : T extends Iterable<infer U> ? Iterable<U> : any[];\n\ntype __sveltets_2_PropsWithChildren<Props, Slots> = Props &\n (Slots extends { default: any }\n // This is unfortunate because it means \"accepts no props\" turns into \"accepts any prop\"\n // but the alternative is non-fixable type errors because of the way TypeScript index\n // signatures work (they will always take precedence and make an impossible-to-satisfy children type).\n ? Props extends Record<string, never>\n ? any\n : { children?: any }\n : {});\ndeclare function __sveltets_2_runes_constructor<Props extends {}>(render: {props: Props }): import(\"svelte\").ComponentConstructorOptions<Props>;\n\ndeclare function __sveltets_2_get_set_binding<T>(get: (() => T) | null | undefined, set: (t: T) => void): T;\n\ndeclare function __sveltets_$$bindings<Bindings extends string[]>(...bindings: Bindings): Bindings[number];\n\ndeclare function __sveltets_2_fn_component<\n Props extends Record<string, any>, Exports extends Record<string, any>, Bindings extends string\n // @ts-ignore Svelte 5 only\n>(klass: {props: Props, exports?: Exports, bindings?: Bindings }): import('svelte').Component<Props, Exports, Bindings>;\n\ninterface __sveltets_2_IsomorphicComponent<Props extends Record<string, any> = any, Events extends Record<string, any> = any, Slots extends Record<string, any> = any, Exports = {}, Bindings = string> {\n new (options: import('svelte').ComponentConstructorOptions<Props>): import('svelte').SvelteComponent<Props, Events, Slots> & { $$bindings?: Bindings } & Exports;\n (internal: unknown, props: Props extends Record<string, never> ? {$$events?: Events, $$slots?: Slots} : Props & {$$events?: Events, $$slots?: Slots}): Exports & { $set?: any, $on?: any };\n z_$$bindings?: Bindings;\n}\n\ndeclare function __sveltets_2_isomorphic_component<\n Props extends Record<string, any>, Events extends Record<string, any>, Slots extends Record<string, any>, Exports extends Record<string, any>, Bindings extends string\n>(klass: {props: Props, events: Events, slots: Slots, exports?: Exports, bindings?: Bindings }): __sveltets_2_IsomorphicComponent<Props, Events, Slots, Exports, Bindings>;\n\ndeclare function __sveltets_2_isomorphic_component_slots<\n Props extends Record<string, any>, Events extends Record<string, any>, Slots extends Record<string, any>, Exports extends Record<string, any>, Bindings extends string\n>(klass: {props: Props, events: Events, slots: Slots, exports?: Exports, bindings?: Bindings }): __sveltets_2_IsomorphicComponent<__sveltets_2_PropsWithChildren<Props, Slots>, Events, Slots, Exports, Bindings>;\n";
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,405 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* PFM Volar LanguagePlugin.
|
|
3
|
+
*
|
|
4
|
+
* Teaches Volar how to handle .pfm files by producing TypeScript
|
|
5
|
+
* VirtualCode through the pipeline:
|
|
6
|
+
*
|
|
7
|
+
* PFM source -> pfmToSvelte -> svelte2tsx -> compose mappings -> VirtualCode
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import type {
|
|
11
|
+
LanguagePlugin,
|
|
12
|
+
VirtualCode,
|
|
13
|
+
IScriptSnapshot,
|
|
14
|
+
CodeMapping,
|
|
15
|
+
CodegenContext,
|
|
16
|
+
} from "@volar/language-core";
|
|
17
|
+
import { forEachEmbeddedCode } from "@volar/language-core";
|
|
18
|
+
import type { TypeScriptExtraServiceScript } from "@volar/typescript";
|
|
19
|
+
|
|
20
|
+
import { pfmToSvelte } from "@mdsvex/source-map/pfm-to-svelte";
|
|
21
|
+
import { v3ToVolarMappings } from "@mdsvex/source-map/v3-to-volar";
|
|
22
|
+
import { composeMappings } from "@mdsvex/source-map/compose-mappings";
|
|
23
|
+
import { svelte2tsx as svelte_2_tsx } from "svelte2tsx";
|
|
24
|
+
import type { CodeInformation } from "@mdsvex/render/mappings";
|
|
25
|
+
|
|
26
|
+
const PFM_EXTENSION = ".pfm";
|
|
27
|
+
const PFM_LANGUAGE_ID = "pfm";
|
|
28
|
+
|
|
29
|
+
import { SVELTE_SHIMS } from "./_svelte_shims";
|
|
30
|
+
|
|
31
|
+
/** Prepend shims content to svelte2tsx output and shift mappings. */
|
|
32
|
+
function inject_shims(
|
|
33
|
+
tsx_code: string,
|
|
34
|
+
raw_mappings: ReturnType<typeof v3ToVolarMappings>,
|
|
35
|
+
): { code: string; mappings: typeof raw_mappings } {
|
|
36
|
+
if (!SVELTE_SHIMS) return { code: tsx_code, mappings: raw_mappings };
|
|
37
|
+
const prefix = SVELTE_SHIMS + "\n";
|
|
38
|
+
const prefixLen = prefix.length;
|
|
39
|
+
return {
|
|
40
|
+
code: prefix + tsx_code,
|
|
41
|
+
mappings: raw_mappings.map((m) => ({
|
|
42
|
+
...m,
|
|
43
|
+
generatedOffsets: m.generatedOffsets.map((o) => o + prefixLen),
|
|
44
|
+
})),
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export interface PfmVirtualCode extends VirtualCode {
|
|
49
|
+
id: string;
|
|
50
|
+
languageId: string;
|
|
51
|
+
snapshot: IScriptSnapshot;
|
|
52
|
+
mappings: CodeMapping[];
|
|
53
|
+
embeddedCodes: VirtualCode[];
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** Create a simple IScriptSnapshot from a string. */
|
|
57
|
+
function create_snapshot(text: string): IScriptSnapshot {
|
|
58
|
+
return {
|
|
59
|
+
getText: (start, end) => text.slice(start, end),
|
|
60
|
+
getLength: () => text.length,
|
|
61
|
+
getChangeRange: () => undefined,
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** Build a minimal VirtualCode with no TS features (used as fallback on error). */
|
|
66
|
+
function create_fallback_virtual_code(source: string): PfmVirtualCode {
|
|
67
|
+
return {
|
|
68
|
+
id: "root",
|
|
69
|
+
languageId: PFM_LANGUAGE_ID,
|
|
70
|
+
snapshot: create_snapshot(source),
|
|
71
|
+
mappings: [{
|
|
72
|
+
sourceOffsets: [0],
|
|
73
|
+
generatedOffsets: [0],
|
|
74
|
+
lengths: [source.length],
|
|
75
|
+
data: { structure: true },
|
|
76
|
+
}],
|
|
77
|
+
embeddedCodes: [],
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* Run the full PFM to TypeScript pipeline and produce VirtualCode.
|
|
83
|
+
* On any error (parse failure, svelte2tsx crash), returns a fallback
|
|
84
|
+
* VirtualCode with no TS features instead of crashing the server.
|
|
85
|
+
*/
|
|
86
|
+
function create_virtual_code_from_source(
|
|
87
|
+
source: string,
|
|
88
|
+
script_id: string,
|
|
89
|
+
): PfmVirtualCode {
|
|
90
|
+
let svelte;
|
|
91
|
+
try {
|
|
92
|
+
// Step 1: PFM to Svelte
|
|
93
|
+
svelte = pfmToSvelte(source);
|
|
94
|
+
} catch {
|
|
95
|
+
return create_fallback_virtual_code(source);
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
let tsx;
|
|
99
|
+
try {
|
|
100
|
+
// Step 2: Svelte to TypeScript via svelte2tsx
|
|
101
|
+
tsx = svelte_2_tsx(svelte.code, {
|
|
102
|
+
filename: script_id.replace(PFM_EXTENSION, ".svelte"),
|
|
103
|
+
isTsFile: false,
|
|
104
|
+
mode: "ts",
|
|
105
|
+
});
|
|
106
|
+
} catch {
|
|
107
|
+
return create_fallback_virtual_code(source);
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
// Step 3: Convert svelte2tsx's v3 source map to Volar format + inject shims
|
|
111
|
+
const v3_map = tsx.map.toJSON ? tsx.map.toJSON() : tsx.map;
|
|
112
|
+
const raw_svelte_to_ts = v3ToVolarMappings(v3_map as any, tsx.code, svelte.code);
|
|
113
|
+
const { code: ts_code, mappings: svelte_to_ts_mappings } = inject_shims(
|
|
114
|
+
tsx.code,
|
|
115
|
+
raw_svelte_to_ts,
|
|
116
|
+
);
|
|
117
|
+
|
|
118
|
+
// Step 4: Filter mappings for composition.
|
|
119
|
+
// - Exclude "node" role (broadest spans cause duplicate hover results)
|
|
120
|
+
// - Exclude zero-length source mappings
|
|
121
|
+
// - Upgrade capabilities to full, let svelte2tsx's B-side gate features
|
|
122
|
+
const ALL_CAPS: CodeInformation = {
|
|
123
|
+
verification: true,
|
|
124
|
+
completion: true,
|
|
125
|
+
semantic: true,
|
|
126
|
+
navigation: true,
|
|
127
|
+
structure: true,
|
|
128
|
+
};
|
|
129
|
+
const filtered_mappings = svelte.mappings
|
|
130
|
+
.filter((m) => (m.data as any).role !== "node" && m.lengths[0] > 0)
|
|
131
|
+
.map((m) => ({ ...m, data: ALL_CAPS }));
|
|
132
|
+
|
|
133
|
+
// Step 5: Compose PFM to Svelte + Svelte to TS = PFM to TS
|
|
134
|
+
// Use B's capabilities but disable format (overlapping ranges crash the formatter).
|
|
135
|
+
const pfm_to_ts = composeMappings(
|
|
136
|
+
filtered_mappings as any,
|
|
137
|
+
svelte_to_ts_mappings,
|
|
138
|
+
(_a: CodeInformation, b: CodeInformation): CodeInformation => ({
|
|
139
|
+
...b,
|
|
140
|
+
format: false,
|
|
141
|
+
}),
|
|
142
|
+
);
|
|
143
|
+
|
|
144
|
+
// Step 5b: Merge single-char non-identity mappings into adjacent
|
|
145
|
+
// neighbors. svelte2tsx splits attribute names at the first character
|
|
146
|
+
// (e.g. "v" to '"' + "alue=" to 'alue"') and maps syntax chars to filler
|
|
147
|
+
// spaces. These 1-char mappings cause two problems via Volar's
|
|
148
|
+
// inclusive-end (<=) translateOffset:
|
|
149
|
+
// 1. Diagnostic highlights bleed through whitespace (char to space anchors)
|
|
150
|
+
// 2. Duplicate hover at attribute-name boundaries (v/alue overlap)
|
|
151
|
+
// Merging them into the next mapping eliminates the boundary overlap
|
|
152
|
+
// while preserving hover on the first character.
|
|
153
|
+
pfm_to_ts.sort(
|
|
154
|
+
(a, b) => a.sourceOffsets[0] - b.sourceOffsets[0],
|
|
155
|
+
);
|
|
156
|
+
for (let i = pfm_to_ts.length - 2; i >= 0; i--) {
|
|
157
|
+
const m = pfm_to_ts[i];
|
|
158
|
+
if (m.lengths[0] !== 1) continue;
|
|
159
|
+
const gen_len = m.generatedLengths ? m.generatedLengths[0] : 1;
|
|
160
|
+
if (gen_len !== 1) continue;
|
|
161
|
+
const src_ch = source.charCodeAt(m.sourceOffsets[0]);
|
|
162
|
+
const gen_ch = ts_code.charCodeAt(m.generatedOffsets[0]);
|
|
163
|
+
if (src_ch === gen_ch) continue; // identity, leave as-is
|
|
164
|
+
|
|
165
|
+
const next = pfm_to_ts[i + 1];
|
|
166
|
+
const next_gen_len = next.generatedLengths ? next.generatedLengths[0] : next.lengths[0];
|
|
167
|
+
|
|
168
|
+
// Merge into next if source-adjacent and generated gap <= 1
|
|
169
|
+
if (m.sourceOffsets[0] + 1 === next.sourceOffsets[0] &&
|
|
170
|
+
next.generatedOffsets[0] - (m.generatedOffsets[0] + 1) <= 1) {
|
|
171
|
+
const new_gen_start = m.generatedOffsets[0];
|
|
172
|
+
const new_gen_end = next.generatedOffsets[0] + next_gen_len;
|
|
173
|
+
next.sourceOffsets[0] = m.sourceOffsets[0];
|
|
174
|
+
next.lengths[0] += 1;
|
|
175
|
+
next.generatedOffsets[0] = new_gen_start;
|
|
176
|
+
const new_gen_len = new_gen_end - new_gen_start;
|
|
177
|
+
next.generatedLengths = new_gen_len !== next.lengths[0] ? [new_gen_len] : undefined;
|
|
178
|
+
pfm_to_ts.splice(i, 1);
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
// Step 6: Shrink non-identity trailing boundaries at adjacency points.
|
|
183
|
+
// Volar's translateOffset uses inclusive end (<=) so adjacent mappings
|
|
184
|
+
// share boundary offsets. When the last source char differs from the
|
|
185
|
+
// last generated char (e.g. "}" becomes ","), the previous mapping wrongly
|
|
186
|
+
// claims the next token's start, causing diagnostic highlights to
|
|
187
|
+
// bleed through inter-attribute whitespace. We only shrink when the
|
|
188
|
+
// next mapping starts at exactly this mapping's generated end, to
|
|
189
|
+
// avoid dropping diagnostics at the final mapping.
|
|
190
|
+
const by_gen_offset = pfm_to_ts.slice().sort(
|
|
191
|
+
(a, b) => a.generatedOffsets[0] - b.generatedOffsets[0],
|
|
192
|
+
);
|
|
193
|
+
for (let i = 0; i < by_gen_offset.length - 1; i++) {
|
|
194
|
+
const m = by_gen_offset[i];
|
|
195
|
+
const next = by_gen_offset[i + 1];
|
|
196
|
+
const src_len = m.lengths[0];
|
|
197
|
+
const gen_len = m.generatedLengths ? m.generatedLengths[0] : src_len;
|
|
198
|
+
if (gen_len <= 1) continue;
|
|
199
|
+
const gen_end = m.generatedOffsets[0] + gen_len;
|
|
200
|
+
if (gen_end !== next.generatedOffsets[0]) continue;
|
|
201
|
+
const last_src = source.charCodeAt(m.sourceOffsets[0] + src_len - 1);
|
|
202
|
+
const last_gen = ts_code.charCodeAt(m.generatedOffsets[0] + gen_len - 1);
|
|
203
|
+
if (last_src !== last_gen) {
|
|
204
|
+
m.generatedLengths = [gen_len - 1];
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
// Step 7: Deduplicate composed mappings that share the same source range.
|
|
209
|
+
// svelte2tsx maps identifiers like `Test` to multiple TS positions
|
|
210
|
+
// (import, type alias, constructor). Keeping only the first (lowest
|
|
211
|
+
// generated offset) prevents Volar from combining all their hover
|
|
212
|
+
// results into one noisy tooltip.
|
|
213
|
+
{
|
|
214
|
+
const seen = new Set<string>();
|
|
215
|
+
let write = 0;
|
|
216
|
+
for (let read = 0; read < pfm_to_ts.length; read++) {
|
|
217
|
+
const m = pfm_to_ts[read];
|
|
218
|
+
const key = m.sourceOffsets[0] + ":" + m.lengths[0];
|
|
219
|
+
if (seen.has(key)) continue;
|
|
220
|
+
seen.add(key);
|
|
221
|
+
pfm_to_ts[write++] = m;
|
|
222
|
+
}
|
|
223
|
+
pfm_to_ts.length = write;
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
// Build the TypeScript embedded VirtualCode
|
|
227
|
+
const ts_virtual_code: VirtualCode = {
|
|
228
|
+
id: "ts",
|
|
229
|
+
languageId: "typescript",
|
|
230
|
+
snapshot: create_snapshot(ts_code),
|
|
231
|
+
mappings: pfm_to_ts as CodeMapping[],
|
|
232
|
+
embeddedCodes: [],
|
|
233
|
+
};
|
|
234
|
+
|
|
235
|
+
// Build CSS embedded VirtualCodes from <style> blocks
|
|
236
|
+
const embedded_codes: VirtualCode[] = [ts_virtual_code];
|
|
237
|
+
const all_caps = {
|
|
238
|
+
verification: true,
|
|
239
|
+
completion: true,
|
|
240
|
+
semantic: true,
|
|
241
|
+
navigation: true,
|
|
242
|
+
structure: true,
|
|
243
|
+
format: true,
|
|
244
|
+
};
|
|
245
|
+
|
|
246
|
+
for (let i = 0; i < svelte.styleBlocks.length; i++) {
|
|
247
|
+
const sb = svelte.styleBlocks[i];
|
|
248
|
+
const css_text = source.slice(sb.sourceStart, sb.sourceEnd);
|
|
249
|
+
embedded_codes.push({
|
|
250
|
+
id: "style_" + i,
|
|
251
|
+
languageId: "css",
|
|
252
|
+
snapshot: create_snapshot(css_text),
|
|
253
|
+
mappings: [{
|
|
254
|
+
sourceOffsets: [sb.sourceStart],
|
|
255
|
+
generatedOffsets: [0],
|
|
256
|
+
lengths: [css_text.length],
|
|
257
|
+
data: all_caps,
|
|
258
|
+
}],
|
|
259
|
+
embeddedCodes: [],
|
|
260
|
+
});
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
// Build markdown VirtualCode: PFM source with excluded regions
|
|
264
|
+
// (frontmatter, script, style, imports) blanked out so the markdown
|
|
265
|
+
// service sees clean markdown without setext-heading false positives.
|
|
266
|
+
let md_source = source;
|
|
267
|
+
for (const region of svelte.excludedRegions) {
|
|
268
|
+
// Replace excluded bytes with spaces, preserving newlines for line alignment
|
|
269
|
+
const chunk = source.slice(region.start, region.end);
|
|
270
|
+
const blanked = chunk.replace(/[^\n]/g, " ");
|
|
271
|
+
md_source = md_source.slice(0, region.start) + blanked + md_source.slice(region.end);
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
embedded_codes.push({
|
|
275
|
+
id: "md",
|
|
276
|
+
languageId: "markdown",
|
|
277
|
+
snapshot: create_snapshot(md_source),
|
|
278
|
+
mappings: [{
|
|
279
|
+
sourceOffsets: [0],
|
|
280
|
+
generatedOffsets: [0],
|
|
281
|
+
lengths: [source.length],
|
|
282
|
+
data: {
|
|
283
|
+
structure: true,
|
|
284
|
+
navigation: true,
|
|
285
|
+
},
|
|
286
|
+
}],
|
|
287
|
+
embeddedCodes: [],
|
|
288
|
+
});
|
|
289
|
+
|
|
290
|
+
return {
|
|
291
|
+
id: "root",
|
|
292
|
+
languageId: PFM_LANGUAGE_ID,
|
|
293
|
+
snapshot: create_snapshot(source),
|
|
294
|
+
mappings: [{
|
|
295
|
+
sourceOffsets: [0],
|
|
296
|
+
generatedOffsets: [0],
|
|
297
|
+
lengths: [source.length],
|
|
298
|
+
data: { structure: true },
|
|
299
|
+
}],
|
|
300
|
+
embeddedCodes: embedded_codes,
|
|
301
|
+
};
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
/** Simple string hash for content-based caching. */
|
|
305
|
+
function hash_string(s: string): number {
|
|
306
|
+
let h = 0;
|
|
307
|
+
for (let i = 0; i < s.length; i++) {
|
|
308
|
+
h = ((h << 5) - h + s.charCodeAt(i)) | 0;
|
|
309
|
+
}
|
|
310
|
+
return h;
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
/**
|
|
314
|
+
* Create a PFM LanguagePlugin for Volar.
|
|
315
|
+
*
|
|
316
|
+
* Usage:
|
|
317
|
+
* const plugin = createPfmLanguagePlugin();
|
|
318
|
+
* // Pass to @volar/language-server or @volar/kit
|
|
319
|
+
*/
|
|
320
|
+
export function create_pfm_language_plugin(): LanguagePlugin<string, PfmVirtualCode> {
|
|
321
|
+
// Per-file cache: skip full pipeline if content hash hasn't changed
|
|
322
|
+
const cache = new Map<string, { hash: number; result: PfmVirtualCode }>();
|
|
323
|
+
|
|
324
|
+
return {
|
|
325
|
+
getLanguageId(scriptId: string): string | undefined {
|
|
326
|
+
if (scriptId.endsWith(PFM_EXTENSION)) {
|
|
327
|
+
return PFM_LANGUAGE_ID;
|
|
328
|
+
}
|
|
329
|
+
return undefined;
|
|
330
|
+
},
|
|
331
|
+
|
|
332
|
+
createVirtualCode(
|
|
333
|
+
scriptId: string,
|
|
334
|
+
languageId: string,
|
|
335
|
+
snapshot: IScriptSnapshot,
|
|
336
|
+
_ctx: CodegenContext<string>,
|
|
337
|
+
): PfmVirtualCode | undefined {
|
|
338
|
+
if (languageId !== PFM_LANGUAGE_ID) return undefined;
|
|
339
|
+
|
|
340
|
+
const source = snapshot.getText(0, snapshot.getLength());
|
|
341
|
+
const hash = hash_string(source);
|
|
342
|
+
const cached = cache.get(scriptId);
|
|
343
|
+
if (cached && cached.hash === hash) {
|
|
344
|
+
return cached.result;
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
const result = create_virtual_code_from_source(source, scriptId);
|
|
348
|
+
cache.set(scriptId, { hash, result });
|
|
349
|
+
return result;
|
|
350
|
+
},
|
|
351
|
+
|
|
352
|
+
updateVirtualCode(
|
|
353
|
+
scriptId: string,
|
|
354
|
+
_virtualCode: PfmVirtualCode,
|
|
355
|
+
newSnapshot: IScriptSnapshot,
|
|
356
|
+
_ctx: CodegenContext<string>,
|
|
357
|
+
): PfmVirtualCode | undefined {
|
|
358
|
+
const source = newSnapshot.getText(0, newSnapshot.getLength());
|
|
359
|
+
const hash = hash_string(source);
|
|
360
|
+
const cached = cache.get(scriptId);
|
|
361
|
+
if (cached && cached.hash === hash) {
|
|
362
|
+
return cached.result;
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
const result = create_virtual_code_from_source(source, scriptId);
|
|
366
|
+
cache.set(scriptId, { hash, result });
|
|
367
|
+
return result;
|
|
368
|
+
},
|
|
369
|
+
|
|
370
|
+
disposeVirtualCode(scriptId: string) {
|
|
371
|
+
cache.delete(scriptId);
|
|
372
|
+
},
|
|
373
|
+
|
|
374
|
+
typescript: {
|
|
375
|
+
extraFileExtensions: [
|
|
376
|
+
{
|
|
377
|
+
extension: "pfm",
|
|
378
|
+
isMixedContent: true,
|
|
379
|
+
scriptKind: 7 as any, // ts.ScriptKind.Deferred
|
|
380
|
+
},
|
|
381
|
+
],
|
|
382
|
+
getServiceScript(root: VirtualCode) {
|
|
383
|
+
// Return the embedded TS code as the service script:
|
|
384
|
+
// this tells TypeScript "when resolving this .pfm file
|
|
385
|
+
// as a module, use this TS code for its exports"
|
|
386
|
+
const ts_code = root.embeddedCodes?.find(
|
|
387
|
+
(c) => c.languageId === "typescript",
|
|
388
|
+
);
|
|
389
|
+
if (ts_code) {
|
|
390
|
+
return {
|
|
391
|
+
code: ts_code,
|
|
392
|
+
extension: ".ts" as any,
|
|
393
|
+
scriptKind: 3 as any, // ts.ScriptKind.TS
|
|
394
|
+
};
|
|
395
|
+
}
|
|
396
|
+
return undefined;
|
|
397
|
+
},
|
|
398
|
+
getExtraServiceScripts(_fileName: string, _root: VirtualCode) {
|
|
399
|
+
// The main TS code is already returned by getServiceScript.
|
|
400
|
+
// No extra scripts needed, returning it again causes duplicates.
|
|
401
|
+
return [];
|
|
402
|
+
},
|
|
403
|
+
},
|
|
404
|
+
};
|
|
405
|
+
}
|
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Minimal Svelte LanguagePlugin.
|
|
3
|
+
*
|
|
4
|
+
* Runs svelte2tsx on .svelte files to produce TypeScript VirtualCode,
|
|
5
|
+
* enabling component prop types to resolve when imported from .pfm files.
|
|
6
|
+
*
|
|
7
|
+
* This is NOT a full Svelte language server, it only provides enough
|
|
8
|
+
* for cross-file type resolution.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import type {
|
|
12
|
+
LanguagePlugin,
|
|
13
|
+
VirtualCode,
|
|
14
|
+
IScriptSnapshot,
|
|
15
|
+
CodeMapping,
|
|
16
|
+
CodegenContext,
|
|
17
|
+
} from "@volar/language-core";
|
|
18
|
+
import { forEachEmbeddedCode } from "@volar/language-core";
|
|
19
|
+
import type { TypeScriptExtraServiceScript } from "@volar/typescript";
|
|
20
|
+
|
|
21
|
+
import { svelte2tsx } from "svelte2tsx";
|
|
22
|
+
import { v3ToVolarMappings } from "@mdsvex/source-map/v3-to-volar";
|
|
23
|
+
|
|
24
|
+
const SVELTE_EXTENSION = ".svelte";
|
|
25
|
+
|
|
26
|
+
import { SVELTE_SHIMS } from "./_svelte_shims";
|
|
27
|
+
|
|
28
|
+
/** Create a simple IScriptSnapshot from a string. */
|
|
29
|
+
function createSnapshot(text: string): IScriptSnapshot {
|
|
30
|
+
return {
|
|
31
|
+
getText: (start, end) => text.slice(start, end),
|
|
32
|
+
getLength: () => text.length,
|
|
33
|
+
getChangeRange: () => undefined,
|
|
34
|
+
};
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function createSvelteVirtualCode(
|
|
38
|
+
source: string,
|
|
39
|
+
scriptId: string,
|
|
40
|
+
): VirtualCode | undefined {
|
|
41
|
+
let tsx;
|
|
42
|
+
try {
|
|
43
|
+
tsx = svelte2tsx(source, {
|
|
44
|
+
filename: scriptId,
|
|
45
|
+
isTsFile: false,
|
|
46
|
+
mode: "ts",
|
|
47
|
+
});
|
|
48
|
+
} catch {
|
|
49
|
+
return undefined;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
const v3Map = tsx.map.toJSON ? tsx.map.toJSON() : tsx.map;
|
|
53
|
+
|
|
54
|
+
// Prepend svelte2tsx shims so TypeScript can resolve helper types
|
|
55
|
+
const prefix = SVELTE_SHIMS ? SVELTE_SHIMS + "\n" : "";
|
|
56
|
+
const tsCode = prefix + tsx.code;
|
|
57
|
+
const prefixLen = prefix.length;
|
|
58
|
+
|
|
59
|
+
// Build mappings from original tsx output, then shift generated offsets
|
|
60
|
+
const rawMappings = v3ToVolarMappings(v3Map as any, tsx.code, source);
|
|
61
|
+
const mappings = rawMappings.map((m) => ({
|
|
62
|
+
...m,
|
|
63
|
+
generatedOffsets: m.generatedOffsets.map((o) => o + prefixLen),
|
|
64
|
+
}));
|
|
65
|
+
|
|
66
|
+
const tsVirtualCode: VirtualCode = {
|
|
67
|
+
id: "ts",
|
|
68
|
+
languageId: "typescript",
|
|
69
|
+
snapshot: createSnapshot(tsCode),
|
|
70
|
+
mappings: mappings as CodeMapping[],
|
|
71
|
+
embeddedCodes: [],
|
|
72
|
+
};
|
|
73
|
+
|
|
74
|
+
return {
|
|
75
|
+
id: "root",
|
|
76
|
+
languageId: "svelte",
|
|
77
|
+
snapshot: createSnapshot(source),
|
|
78
|
+
mappings: [{
|
|
79
|
+
sourceOffsets: [0],
|
|
80
|
+
generatedOffsets: [0],
|
|
81
|
+
lengths: [source.length],
|
|
82
|
+
data: { structure: true },
|
|
83
|
+
}],
|
|
84
|
+
embeddedCodes: [tsVirtualCode],
|
|
85
|
+
};
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* Create a minimal Svelte LanguagePlugin for cross-file type resolution.
|
|
90
|
+
*/
|
|
91
|
+
export function create_svelte_language_plugin(): LanguagePlugin<string> {
|
|
92
|
+
const cache = new Map<string, { hash: number; result: VirtualCode }>();
|
|
93
|
+
|
|
94
|
+
function hashString(s: string): number {
|
|
95
|
+
let h = 0;
|
|
96
|
+
for (let i = 0; i < s.length; i++) {
|
|
97
|
+
h = ((h << 5) - h + s.charCodeAt(i)) | 0;
|
|
98
|
+
}
|
|
99
|
+
return h;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
return {
|
|
103
|
+
getLanguageId(scriptId: string): string | undefined {
|
|
104
|
+
if (scriptId.endsWith(SVELTE_EXTENSION)) {
|
|
105
|
+
return "svelte";
|
|
106
|
+
}
|
|
107
|
+
return undefined;
|
|
108
|
+
},
|
|
109
|
+
|
|
110
|
+
createVirtualCode(
|
|
111
|
+
scriptId: string,
|
|
112
|
+
languageId: string,
|
|
113
|
+
snapshot: IScriptSnapshot,
|
|
114
|
+
): VirtualCode | undefined {
|
|
115
|
+
if (languageId !== "svelte") return undefined;
|
|
116
|
+
|
|
117
|
+
const source = snapshot.getText(0, snapshot.getLength());
|
|
118
|
+
const hash = hashString(source);
|
|
119
|
+
const cached = cache.get(scriptId);
|
|
120
|
+
if (cached && cached.hash === hash) return cached.result;
|
|
121
|
+
|
|
122
|
+
const result = createSvelteVirtualCode(source, scriptId);
|
|
123
|
+
if (result) cache.set(scriptId, { hash, result });
|
|
124
|
+
return result;
|
|
125
|
+
},
|
|
126
|
+
|
|
127
|
+
updateVirtualCode(
|
|
128
|
+
scriptId: string,
|
|
129
|
+
_virtualCode: VirtualCode,
|
|
130
|
+
newSnapshot: IScriptSnapshot,
|
|
131
|
+
): VirtualCode | undefined {
|
|
132
|
+
const source = newSnapshot.getText(0, newSnapshot.getLength());
|
|
133
|
+
const hash = hashString(source);
|
|
134
|
+
const cached = cache.get(scriptId);
|
|
135
|
+
if (cached && cached.hash === hash) return cached.result;
|
|
136
|
+
|
|
137
|
+
const result = createSvelteVirtualCode(source, scriptId);
|
|
138
|
+
if (result) cache.set(scriptId, { hash, result });
|
|
139
|
+
return result;
|
|
140
|
+
},
|
|
141
|
+
|
|
142
|
+
disposeVirtualCode(scriptId: string) {
|
|
143
|
+
cache.delete(scriptId);
|
|
144
|
+
},
|
|
145
|
+
|
|
146
|
+
typescript: {
|
|
147
|
+
extraFileExtensions: [
|
|
148
|
+
{
|
|
149
|
+
extension: "svelte",
|
|
150
|
+
isMixedContent: true,
|
|
151
|
+
scriptKind: 7 as any, // ts.ScriptKind.Deferred
|
|
152
|
+
},
|
|
153
|
+
],
|
|
154
|
+
getServiceScript(root: VirtualCode) {
|
|
155
|
+
const tsCode = root.embeddedCodes?.find(
|
|
156
|
+
(c) => c.languageId === "typescript",
|
|
157
|
+
);
|
|
158
|
+
if (tsCode) {
|
|
159
|
+
return {
|
|
160
|
+
code: tsCode,
|
|
161
|
+
extension: ".ts" as any,
|
|
162
|
+
scriptKind: 3 as any, // ts.ScriptKind.TS
|
|
163
|
+
};
|
|
164
|
+
}
|
|
165
|
+
return undefined;
|
|
166
|
+
},
|
|
167
|
+
getExtraServiceScripts(fileName: string, root: VirtualCode) {
|
|
168
|
+
const scripts: TypeScriptExtraServiceScript[] = [];
|
|
169
|
+
for (const code of forEachEmbeddedCode(root)) {
|
|
170
|
+
if (code.languageId === "typescript") {
|
|
171
|
+
scripts.push({
|
|
172
|
+
fileName: fileName + "." + code.id + ".ts",
|
|
173
|
+
code,
|
|
174
|
+
extension: ".ts",
|
|
175
|
+
scriptKind: 3 as any,
|
|
176
|
+
});
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
return scripts;
|
|
180
|
+
},
|
|
181
|
+
},
|
|
182
|
+
};
|
|
183
|
+
}
|
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
import { describe, it, expect } from "vitest";
|
|
2
|
+
import { create_pfm_language_plugin } from "../src/language_plugin";
|
|
3
|
+
import type { IScriptSnapshot, CodegenContext, VirtualCode, CodeMapping } from "@volar/language-core";
|
|
4
|
+
|
|
5
|
+
function snap(text: string): IScriptSnapshot {
|
|
6
|
+
return {
|
|
7
|
+
getText: (s, e) => text.slice(s, e),
|
|
8
|
+
getLength: () => text.length,
|
|
9
|
+
getChangeRange: () => undefined,
|
|
10
|
+
};
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
const dummyCtx: CodegenContext<string> = {
|
|
14
|
+
getAssociatedScript: () => undefined,
|
|
15
|
+
};
|
|
16
|
+
|
|
17
|
+
describe("create_pfm_language_plugin", () => {
|
|
18
|
+
const plugin = create_pfm_language_plugin();
|
|
19
|
+
|
|
20
|
+
it("getLanguageId returns 'pfm' for .pfm files", () => {
|
|
21
|
+
expect(plugin.getLanguageId("file.pfm")).toBe("pfm");
|
|
22
|
+
expect(plugin.getLanguageId("/path/to/doc.pfm")).toBe("pfm");
|
|
23
|
+
});
|
|
24
|
+
|
|
25
|
+
it("getLanguageId returns undefined for non-.pfm files", () => {
|
|
26
|
+
expect(plugin.getLanguageId("file.md")).toBeUndefined();
|
|
27
|
+
expect(plugin.getLanguageId("file.svelte")).toBeUndefined();
|
|
28
|
+
expect(plugin.getLanguageId("file.ts")).toBeUndefined();
|
|
29
|
+
});
|
|
30
|
+
|
|
31
|
+
it("createVirtualCode returns undefined for non-pfm languageId", () => {
|
|
32
|
+
const result = plugin.createVirtualCode!(
|
|
33
|
+
"test.pfm",
|
|
34
|
+
"markdown",
|
|
35
|
+
snap("# Hello"),
|
|
36
|
+
dummyCtx,
|
|
37
|
+
);
|
|
38
|
+
expect(result).toBeUndefined();
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
it("createVirtualCode produces valid VirtualCode for simple markdown", () => {
|
|
42
|
+
const vc = plugin.createVirtualCode!(
|
|
43
|
+
"test.pfm",
|
|
44
|
+
"pfm",
|
|
45
|
+
snap("# Hello\n\nWorld\n"),
|
|
46
|
+
dummyCtx,
|
|
47
|
+
);
|
|
48
|
+
|
|
49
|
+
expect(vc).toBeDefined();
|
|
50
|
+
expect(vc!.id).toBe("root");
|
|
51
|
+
expect(vc!.languageId).toBe("pfm");
|
|
52
|
+
expect(vc!.mappings.length).toBeGreaterThan(0);
|
|
53
|
+
expect(vc!.embeddedCodes).toBeDefined();
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
it("produces TypeScript embedded VirtualCode", () => {
|
|
57
|
+
const vc = plugin.createVirtualCode!(
|
|
58
|
+
"test.pfm",
|
|
59
|
+
"pfm",
|
|
60
|
+
snap("# Hello\n\nWorld\n"),
|
|
61
|
+
dummyCtx,
|
|
62
|
+
);
|
|
63
|
+
|
|
64
|
+
const tsCode = vc!.embeddedCodes!.find((c) => c.languageId === "typescript");
|
|
65
|
+
expect(tsCode).toBeDefined();
|
|
66
|
+
expect(tsCode!.id).toBe("ts");
|
|
67
|
+
expect(tsCode!.snapshot.getLength()).toBeGreaterThan(0);
|
|
68
|
+
expect(tsCode!.mappings.length).toBeGreaterThanOrEqual(0);
|
|
69
|
+
});
|
|
70
|
+
|
|
71
|
+
it("TS VirtualCode contains svelte2tsx output", () => {
|
|
72
|
+
const vc = plugin.createVirtualCode!(
|
|
73
|
+
"test.pfm",
|
|
74
|
+
"pfm",
|
|
75
|
+
snap("---\ntitle: hello\n---\n\n# {title}\n"),
|
|
76
|
+
dummyCtx,
|
|
77
|
+
);
|
|
78
|
+
|
|
79
|
+
const tsCode = vc!.embeddedCodes!.find((c) => c.languageId === "typescript");
|
|
80
|
+
const tsText = tsCode!.snapshot.getText(0, tsCode!.snapshot.getLength());
|
|
81
|
+
|
|
82
|
+
// svelte2tsx produces a $$render function
|
|
83
|
+
expect(tsText).toContain("$$render");
|
|
84
|
+
// the title variable should appear
|
|
85
|
+
expect(tsText).toContain("title");
|
|
86
|
+
});
|
|
87
|
+
|
|
88
|
+
it("mappings survive into the TS VirtualCode", () => {
|
|
89
|
+
const pfm = "---\ntitle: hello\ncount: 42\n---\n\n# {title}\n\n{count + 1}\n";
|
|
90
|
+
const vc = plugin.createVirtualCode!(
|
|
91
|
+
"test.pfm",
|
|
92
|
+
"pfm",
|
|
93
|
+
snap(pfm),
|
|
94
|
+
dummyCtx,
|
|
95
|
+
);
|
|
96
|
+
|
|
97
|
+
const tsCode = vc!.embeddedCodes!.find((c) => c.languageId === "typescript");
|
|
98
|
+
const tsText = tsCode!.snapshot.getText(0, tsCode!.snapshot.getLength());
|
|
99
|
+
|
|
100
|
+
// should have composed PFM→TS mappings
|
|
101
|
+
expect(tsCode!.mappings.length).toBeGreaterThan(0);
|
|
102
|
+
|
|
103
|
+
// verify at least one mapping points back to PFM source correctly
|
|
104
|
+
let foundTitle = false;
|
|
105
|
+
for (const m of tsCode!.mappings) {
|
|
106
|
+
for (let i = 0; i < m.sourceOffsets.length; i++) {
|
|
107
|
+
const srcText = pfm.slice(
|
|
108
|
+
m.sourceOffsets[i],
|
|
109
|
+
m.sourceOffsets[i] + m.lengths[i],
|
|
110
|
+
);
|
|
111
|
+
if (srcText === "title") foundTitle = true;
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
expect(foundTitle).toBe(true);
|
|
115
|
+
});
|
|
116
|
+
|
|
117
|
+
it("updateVirtualCode produces fresh VirtualCode", () => {
|
|
118
|
+
const vc1 = plugin.createVirtualCode!(
|
|
119
|
+
"test.pfm",
|
|
120
|
+
"pfm",
|
|
121
|
+
snap("---\nfoo: 1\n---\n\n{foo}\n"),
|
|
122
|
+
dummyCtx,
|
|
123
|
+
);
|
|
124
|
+
|
|
125
|
+
const vc2 = plugin.updateVirtualCode!(
|
|
126
|
+
"test.pfm",
|
|
127
|
+
vc1!,
|
|
128
|
+
snap("---\nbar: 2\n---\n\n{bar}\n"),
|
|
129
|
+
dummyCtx,
|
|
130
|
+
);
|
|
131
|
+
|
|
132
|
+
expect(vc2).toBeDefined();
|
|
133
|
+
const tsCode = vc2!.embeddedCodes!.find((c) => c.languageId === "typescript");
|
|
134
|
+
const tsText = tsCode!.snapshot.getText(0, tsCode!.snapshot.getLength());
|
|
135
|
+
// svelte2tsx preserves expressions — "bar" should appear, "foo" should not
|
|
136
|
+
expect(tsText).toContain("bar");
|
|
137
|
+
expect(tsText).not.toContain("foo");
|
|
138
|
+
});
|
|
139
|
+
|
|
140
|
+
it("handles complex PFM with imports and expressions", () => {
|
|
141
|
+
const pfm = `---
|
|
142
|
+
title: Hello World
|
|
143
|
+
count: 42
|
|
144
|
+
---
|
|
145
|
+
import Counter from "./Counter.svelte"
|
|
146
|
+
|
|
147
|
+
# {title}
|
|
148
|
+
|
|
149
|
+
<Counter value={count} />
|
|
150
|
+
|
|
151
|
+
The count is {count + 1}.
|
|
152
|
+
`;
|
|
153
|
+
const vc = plugin.createVirtualCode!(
|
|
154
|
+
"test.pfm",
|
|
155
|
+
"pfm",
|
|
156
|
+
snap(pfm),
|
|
157
|
+
dummyCtx,
|
|
158
|
+
);
|
|
159
|
+
|
|
160
|
+
expect(vc).toBeDefined();
|
|
161
|
+
const tsCode = vc!.embeddedCodes!.find((c) => c.languageId === "typescript");
|
|
162
|
+
const tsText = tsCode!.snapshot.getText(0, tsCode!.snapshot.getLength());
|
|
163
|
+
|
|
164
|
+
expect(tsText).toContain("title");
|
|
165
|
+
expect(tsText).toContain("count");
|
|
166
|
+
expect(tsText).toContain("Counter");
|
|
167
|
+
expect(tsText).toContain("count + 1");
|
|
168
|
+
|
|
169
|
+
// all mappings should have valid offsets
|
|
170
|
+
for (const m of tsCode!.mappings) {
|
|
171
|
+
for (let i = 0; i < m.sourceOffsets.length; i++) {
|
|
172
|
+
expect(m.sourceOffsets[i]).toBeGreaterThanOrEqual(0);
|
|
173
|
+
expect(m.sourceOffsets[i] + m.lengths[i]).toBeLessThanOrEqual(pfm.length);
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
});
|
|
177
|
+
});
|
package/tsconfig.json
ADDED
package/README.md
DELETED