sfmc-language-lsp 4.4.1 → 4.5.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.
Files changed (44) hide show
  1. package/README.md +39 -0
  2. package/dist/cjs/package-version.cjs +1 -1
  3. package/dist/cjs/typescript/index.cjs +16 -0
  4. package/dist/cjs/typescript/index.d.ts +11 -0
  5. package/dist/cjs/typescript/index.d.ts.map +1 -0
  6. package/dist/cjs/typescript/index.js.map +1 -0
  7. package/dist/cjs/typescript/orchestration.cjs +108 -0
  8. package/dist/cjs/typescript/orchestration.d.ts +59 -0
  9. package/dist/cjs/typescript/orchestration.d.ts.map +1 -0
  10. package/dist/cjs/typescript/orchestration.js.map +1 -0
  11. package/dist/cjs/typescript/service.cjs +810 -0
  12. package/dist/cjs/typescript/service.d.ts +52 -0
  13. package/dist/cjs/typescript/service.d.ts.map +1 -0
  14. package/dist/cjs/typescript/service.js.map +1 -0
  15. package/dist/cjs/typescript/source-analysis.cjs +582 -0
  16. package/dist/cjs/typescript/source-analysis.d.ts +110 -0
  17. package/dist/cjs/typescript/source-analysis.d.ts.map +1 -0
  18. package/dist/cjs/typescript/source-analysis.js.map +1 -0
  19. package/dist/esm/package-version.js +1 -1
  20. package/dist/esm/typescript/index.d.ts +11 -0
  21. package/dist/esm/typescript/index.d.ts.map +1 -0
  22. package/dist/esm/typescript/index.js +9 -0
  23. package/dist/esm/typescript/index.js.map +1 -0
  24. package/dist/esm/typescript/orchestration.d.ts +59 -0
  25. package/dist/esm/typescript/orchestration.d.ts.map +1 -0
  26. package/dist/esm/typescript/orchestration.js +103 -0
  27. package/dist/esm/typescript/orchestration.js.map +1 -0
  28. package/dist/esm/typescript/service.d.ts +52 -0
  29. package/dist/esm/typescript/service.d.ts.map +1 -0
  30. package/dist/esm/typescript/service.js +774 -0
  31. package/dist/esm/typescript/service.js.map +1 -0
  32. package/dist/esm/typescript/source-analysis.d.ts +110 -0
  33. package/dist/esm/typescript/source-analysis.d.ts.map +1 -0
  34. package/dist/esm/typescript/source-analysis.js +572 -0
  35. package/dist/esm/typescript/source-analysis.js.map +1 -0
  36. package/dist/types/typescript/index.d.ts +11 -0
  37. package/dist/types/typescript/index.d.ts.map +1 -0
  38. package/dist/types/typescript/orchestration.d.ts +59 -0
  39. package/dist/types/typescript/orchestration.d.ts.map +1 -0
  40. package/dist/types/typescript/service.d.ts +52 -0
  41. package/dist/types/typescript/service.d.ts.map +1 -0
  42. package/dist/types/typescript/source-analysis.d.ts +110 -0
  43. package/dist/types/typescript/source-analysis.d.ts.map +1 -0
  44. package/package.json +14 -1
@@ -0,0 +1,810 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.createSsjsTypeScriptService = createSsjsTypeScriptService;
37
+ /**
38
+ * Embedded TypeScript language service for SSJS.
39
+ *
40
+ * The caller supplies the SSJS globals declarations (`sfmc-globals.d.ts` of ssjs-data) as text;
41
+ * they are the sole built-in library (noLib:true), so the compiler only knows the SFMC-supported
42
+ * API surface. Each SSJS document is tracked in a virtual JS file, and the service returns
43
+ * LSP-typed results. Nothing here touches the file system or the process, so the same code runs
44
+ * in a language server and in a browser.
45
+ */
46
+ const ts = __importStar(require("typescript"));
47
+ const vscode_languageserver_types_1 = require("vscode-languageserver-types");
48
+ const source_analysis_js_1 = require("./source-analysis.cjs");
49
+ const GLOBALS_FILENAME = '__sfmc_globals.d.ts';
50
+ // ---------------------------------------------------------------------------
51
+ // Offset / position utilities
52
+ // ---------------------------------------------------------------------------
53
+ /**
54
+ * Convert an LSP position to a zero-based character offset in the text.
55
+ * @param text - the source text
56
+ * @param position - the LSP line/character position
57
+ * @returns the character offset within the text
58
+ */
59
+ function positionToOffset(text, position) {
60
+ const lines = text.split('\n');
61
+ let offset = 0;
62
+ for (let index = 0; index < position.line && index < lines.length; index++) {
63
+ offset += lines[index].length + 1; // +1 for the '\n'
64
+ }
65
+ return offset + position.character;
66
+ }
67
+ /**
68
+ * Convert a zero-based character offset to an LSP position.
69
+ * @param text - the source text
70
+ * @param offset - the character offset within the text
71
+ * @returns the LSP line/character position
72
+ */
73
+ function offsetToPosition(text, offset) {
74
+ const slice = text.slice(0, Math.max(0, offset));
75
+ const lines = slice.split('\n');
76
+ return {
77
+ line: lines.length - 1,
78
+ character: lines.at(-1).length,
79
+ };
80
+ }
81
+ // ---------------------------------------------------------------------------
82
+ // TS kind → LSP CompletionItemKind
83
+ // ---------------------------------------------------------------------------
84
+ const TS_KIND_MAP = {
85
+ [ts.ScriptElementKind.functionElement]: vscode_languageserver_types_1.CompletionItemKind.Function,
86
+ [ts.ScriptElementKind.memberFunctionElement]: vscode_languageserver_types_1.CompletionItemKind.Method,
87
+ [ts.ScriptElementKind.memberGetAccessorElement]: vscode_languageserver_types_1.CompletionItemKind.Property,
88
+ [ts.ScriptElementKind.memberSetAccessorElement]: vscode_languageserver_types_1.CompletionItemKind.Property,
89
+ [ts.ScriptElementKind.memberVariableElement]: vscode_languageserver_types_1.CompletionItemKind.Field,
90
+ [ts.ScriptElementKind.constructorImplementationElement]: vscode_languageserver_types_1.CompletionItemKind.Constructor,
91
+ [ts.ScriptElementKind.classElement]: vscode_languageserver_types_1.CompletionItemKind.Class,
92
+ [ts.ScriptElementKind.interfaceElement]: vscode_languageserver_types_1.CompletionItemKind.Interface,
93
+ [ts.ScriptElementKind.enumElement]: vscode_languageserver_types_1.CompletionItemKind.Enum,
94
+ [ts.ScriptElementKind.enumMemberElement]: vscode_languageserver_types_1.CompletionItemKind.EnumMember,
95
+ [ts.ScriptElementKind.moduleElement]: vscode_languageserver_types_1.CompletionItemKind.Module,
96
+ [ts.ScriptElementKind.alias]: vscode_languageserver_types_1.CompletionItemKind.Reference,
97
+ [ts.ScriptElementKind.letElement]: vscode_languageserver_types_1.CompletionItemKind.Variable,
98
+ [ts.ScriptElementKind.constElement]: vscode_languageserver_types_1.CompletionItemKind.Constant,
99
+ [ts.ScriptElementKind.variableElement]: vscode_languageserver_types_1.CompletionItemKind.Variable,
100
+ [ts.ScriptElementKind.localVariableElement]: vscode_languageserver_types_1.CompletionItemKind.Variable,
101
+ [ts.ScriptElementKind.parameterElement]: vscode_languageserver_types_1.CompletionItemKind.Variable,
102
+ [ts.ScriptElementKind.typeElement]: vscode_languageserver_types_1.CompletionItemKind.TypeParameter,
103
+ [ts.ScriptElementKind.keyword]: vscode_languageserver_types_1.CompletionItemKind.Keyword,
104
+ };
105
+ /**
106
+ * Map a TypeScript script-element kind to an LSP completion item kind.
107
+ * @param kind - the TypeScript `ScriptElementKind` value
108
+ * @returns the corresponding LSP `CompletionItemKind`
109
+ */
110
+ function tsKindToLsp(kind) {
111
+ return TS_KIND_MAP[kind] ?? vscode_languageserver_types_1.CompletionItemKind.Text;
112
+ }
113
+ // ---------------------------------------------------------------------------
114
+ // TS diagnostic category → LSP severity
115
+ // ---------------------------------------------------------------------------
116
+ /**
117
+ * Map a TypeScript diagnostic category to an LSP diagnostic severity.
118
+ * @param category - the TypeScript `DiagnosticCategory` value
119
+ * @returns the corresponding LSP `DiagnosticSeverity`
120
+ */
121
+ function tsCategoryToSeverity(category) {
122
+ switch (category) {
123
+ case ts.DiagnosticCategory.Error: {
124
+ return vscode_languageserver_types_1.DiagnosticSeverity.Error;
125
+ }
126
+ case ts.DiagnosticCategory.Warning: {
127
+ return vscode_languageserver_types_1.DiagnosticSeverity.Warning;
128
+ }
129
+ case ts.DiagnosticCategory.Suggestion: {
130
+ return vscode_languageserver_types_1.DiagnosticSeverity.Hint;
131
+ }
132
+ default: {
133
+ return vscode_languageserver_types_1.DiagnosticSeverity.Information;
134
+ }
135
+ }
136
+ }
137
+ /**
138
+ * Flatten a TypeScript diagnostic message chain into a single newline-joined string.
139
+ * @param message - the TypeScript diagnostic message chain
140
+ * @returns the flattened message text
141
+ */
142
+ function flattenDiagnosticMessageText(message) {
143
+ let text = message.messageText;
144
+ if (message.next) {
145
+ for (const next of message.next) {
146
+ text += '\n' + flattenDiagnosticMessageText(next);
147
+ }
148
+ }
149
+ return text;
150
+ }
151
+ /**
152
+ * Create a TypeScript-based SSJS language service. All state (virtual files, document names,
153
+ * the active document and the TypeScript language service itself) belongs to the returned
154
+ * instance; two instances share nothing.
155
+ * @param options - globals declarations and optional diagnostic documentation links
156
+ * @returns the service instance
157
+ */
158
+ function createSsjsTypeScriptService(options) {
159
+ const { globalsDts, diagnosticUrl } = options;
160
+ // ---------------------------------------------------------------------------
161
+ // Virtual file system
162
+ // ---------------------------------------------------------------------------
163
+ const virtualFiles = new Map([
164
+ [
165
+ GLOBALS_FILENAME,
166
+ { content: globalsDts, version: 1, snapshot: ts.ScriptSnapshot.fromString(globalsDts) },
167
+ ],
168
+ ]);
169
+ // One counter for all virtual files of this instance. A companion file that is deleted and
170
+ // created again must not restart at an earlier version of the same name, or TypeScript
171
+ // keeps what it read for that version.
172
+ const versions = { last: 1 };
173
+ /**
174
+ * Create or update a virtual in-memory file, giving it a new version and snapshot.
175
+ * Unchanged content keeps its version, so TypeScript does not check it again.
176
+ * @param name - the virtual filename
177
+ * @param content - the file content
178
+ */
179
+ function setVirtualFile(name, content) {
180
+ const existing = virtualFiles.get(name);
181
+ if (existing?.content === content)
182
+ return;
183
+ versions.last += 1;
184
+ virtualFiles.set(name, {
185
+ content,
186
+ version: versions.last,
187
+ snapshot: ts.ScriptSnapshot.fromString(content),
188
+ });
189
+ }
190
+ // ---------------------------------------------------------------------------
191
+ // URI → virtual filename mapping
192
+ // Each SSJS document gets a stable synthetic .js filename so the TS service
193
+ // can process it (TS only handles .js/.ts/.d.ts extensions).
194
+ // Each document may also have a companion .globals.d.ts file that holds
195
+ // ambient declarations derived from ESLint-style /* global NAME */ comments.
196
+ // ---------------------------------------------------------------------------
197
+ // Holder so the counter can be bumped without reassigning a top-level variable
198
+ // inside a function (unicorn/no-top-level-assignment-in-function).
199
+ const counters = { document: 0 };
200
+ // The document the language service is currently answering for. Only this
201
+ // document's virtual files (plus the shared globals) are exposed to TypeScript
202
+ // via getScriptFileNames, so top-level `var` declarations in *other* open SSJS
203
+ // documents cannot collide with this one (which otherwise raises ts2403
204
+ // "Subsequent variable declarations must have the same type").
205
+ const activeDocument = { js: undefined };
206
+ const uriToVirtualName = new Map();
207
+ const uriToGlobalsName = new Map();
208
+ const uriToPolyfillsName = new Map();
209
+ /**
210
+ * Get (or lazily assign) the stable synthetic `.js` filename for a document URI.
211
+ * @param uri - the LSP document URI
212
+ * @returns the virtual `.js` filename for that document
213
+ */
214
+ function virtualNameForUri(uri) {
215
+ let name = uriToVirtualName.get(uri);
216
+ if (!name) {
217
+ name = `__doc_${counters.document}.js`;
218
+ counters.document += 1;
219
+ uriToVirtualName.set(uri, name);
220
+ }
221
+ return name;
222
+ }
223
+ /**
224
+ * Mark a document's virtual `.js` file as the one the language service should
225
+ * answer for. Only this document (plus the shared globals) is exposed via
226
+ * `getScriptFileNames`, isolating its top-level declarations from other open
227
+ * SSJS documents (prevents ts2403 cross-file `var` collisions).
228
+ * @param name - the active document's virtual `.js` filename, or undefined
229
+ */
230
+ function setActiveDocument(name) {
231
+ activeDocument.js = name;
232
+ }
233
+ /**
234
+ * Reverse lookup: map a virtual filename produced by `virtualNameForUri` (or its
235
+ * `.polyfills.d.ts` / `.globals.d.ts` companions) back to the originating LSP
236
+ * document URI. Returns undefined for the shared globals file or unknown names.
237
+ * @param fileName - virtual filename from the TS language service
238
+ * @returns the originating document URI, or undefined
239
+ */
240
+ function uriForVirtualName(fileName) {
241
+ // Companion files share the document's counter; normalize to the base .js name.
242
+ const base = fileName
243
+ .replace(/\.polyfills\.d\.ts$/, '.js')
244
+ .replace(/\.globals\.d\.ts$/, '.js');
245
+ for (const [uri, name] of uriToVirtualName) {
246
+ if (name === base)
247
+ return uri;
248
+ }
249
+ return undefined;
250
+ }
251
+ /**
252
+ * Get (or lazily assign) the companion `.globals.d.ts` filename for a document.
253
+ * @param uri - the LSP document URI
254
+ * @returns the virtual globals declaration filename for that document
255
+ */
256
+ function globalsNameForUri(uri) {
257
+ let name = uriToGlobalsName.get(uri);
258
+ if (!name) {
259
+ // Derived from the JS virtual name so the two always share the same counter.
260
+ const documentName = virtualNameForUri(uri);
261
+ name = documentName.replace(/\.js$/, '.globals.d.ts');
262
+ uriToGlobalsName.set(uri, name);
263
+ }
264
+ return name;
265
+ }
266
+ /**
267
+ * Get (or lazily assign) the companion `.polyfills.d.ts` filename for a document.
268
+ * @param uri - the LSP document URI
269
+ * @returns the virtual polyfills declaration filename for that document
270
+ */
271
+ function polyfillsNameForUri(uri) {
272
+ let name = uriToPolyfillsName.get(uri);
273
+ if (!name) {
274
+ // Derived from the JS virtual name so the two always share the same counter.
275
+ const documentName = virtualNameForUri(uri);
276
+ name = documentName.replace(/\.js$/, '.polyfills.d.ts');
277
+ uriToPolyfillsName.set(uri, name);
278
+ }
279
+ return name;
280
+ }
281
+ // ---------------------------------------------------------------------------
282
+ // Language service host
283
+ // ---------------------------------------------------------------------------
284
+ const host = {
285
+ getCompilationSettings() {
286
+ return {
287
+ allowJs: true,
288
+ checkJs: true,
289
+ noLib: true,
290
+ target: ts.ScriptTarget.ES5,
291
+ strict: false,
292
+ noEmit: true,
293
+ noResolve: true,
294
+ skipLibCheck: false,
295
+ };
296
+ },
297
+ getScriptFileNames() {
298
+ // Expose only the shared globals plus the *active* document's own virtual
299
+ // files. Including every open SSJS document in one program makes their
300
+ // top-level `var` declarations collide in the shared global scope
301
+ // (ts2403). Scoping to the active document keeps each file isolated.
302
+ const active = activeDocument.js;
303
+ if (!active) {
304
+ // Spread the Map (not `.keys()`) so neither unicorn/prefer-spread nor
305
+ // unicorn/prefer-iterator-to-array fires, then take each entry's key.
306
+ return [...virtualFiles].map(([fileName]) => fileName);
307
+ }
308
+ const activeFiles = new Set([
309
+ GLOBALS_FILENAME,
310
+ active,
311
+ active.replace(/\.js$/, '.globals.d.ts'),
312
+ active.replace(/\.js$/, '.polyfills.d.ts'),
313
+ ]);
314
+ return [...virtualFiles]
315
+ .map(([fileName]) => fileName)
316
+ .filter((fileName) => activeFiles.has(fileName));
317
+ },
318
+ getScriptVersion(fileName) {
319
+ return String(virtualFiles.get(fileName)?.version ?? 0);
320
+ },
321
+ getScriptSnapshot(fileName) {
322
+ return virtualFiles.get(fileName)?.snapshot;
323
+ },
324
+ getCurrentDirectory() {
325
+ return '/';
326
+ },
327
+ getDefaultLibFileName() {
328
+ return GLOBALS_FILENAME;
329
+ },
330
+ fileExists(fileName) {
331
+ return virtualFiles.has(fileName);
332
+ },
333
+ readFile(fileName) {
334
+ return virtualFiles.get(fileName)?.content;
335
+ },
336
+ readDirectory() {
337
+ return [];
338
+ },
339
+ directoryExists() {
340
+ return false;
341
+ },
342
+ getDirectories() {
343
+ return [];
344
+ },
345
+ };
346
+ const languageService = ts.createLanguageService(host, ts.createDocumentRegistry());
347
+ /**
348
+ * Notify the service that a SSJS document's content has changed.
349
+ * Must be called before any completions / diagnostics / hover for that URI.
350
+ *
351
+ * Also scans the text for ESLint-style global-comment annotations
352
+ * (the `global` and `globals` block-comment forms) and maintains a
353
+ * per-document companion `.globals.d.ts` virtual file containing
354
+ * the corresponding `declare var` statements so the TypeScript checker
355
+ * does not emit "Cannot find name" errors for those identifiers.
356
+ * @param uri - LSP document URI
357
+ * @param text - full document text
358
+ */
359
+ function updateSsjsDocument(uri, text) {
360
+ setVirtualFile(virtualNameForUri(uri), text);
361
+ const declarations = (0, source_analysis_js_1.parseGlobalCommentDeclarations)(text);
362
+ const globalsName = globalsNameForUri(uri);
363
+ if (declarations) {
364
+ setVirtualFile(globalsName, declarations);
365
+ }
366
+ else {
367
+ // No global comments — remove any stale companion file from a previous
368
+ // document version so old names don't linger in the TS service.
369
+ virtualFiles.delete(globalsName);
370
+ }
371
+ const polyfills = (0, source_analysis_js_1.parsePolyfillDeclarations)(text);
372
+ const polyfillsName = polyfillsNameForUri(uri);
373
+ if (polyfills) {
374
+ setVirtualFile(polyfillsName, polyfills);
375
+ }
376
+ else {
377
+ // No prototype polyfills — drop any stale companion file so members
378
+ // from a previous document version don't linger in the TS service.
379
+ virtualFiles.delete(polyfillsName);
380
+ }
381
+ }
382
+ /**
383
+ * Remove a SSJS document from the virtual FS (e.g. on close).
384
+ * Also removes the companion globals declaration file if one exists.
385
+ * @param uri - LSP document URI
386
+ */
387
+ function removeSsjsDocument(uri) {
388
+ const name = uriToVirtualName.get(uri);
389
+ if (name) {
390
+ virtualFiles.delete(name);
391
+ uriToVirtualName.delete(uri);
392
+ if (activeDocument.js === name)
393
+ setActiveDocument(undefined);
394
+ }
395
+ const globalsName = uriToGlobalsName.get(uri);
396
+ if (globalsName) {
397
+ virtualFiles.delete(globalsName);
398
+ uriToGlobalsName.delete(uri);
399
+ }
400
+ const polyfillsName = uriToPolyfillsName.get(uri);
401
+ if (!polyfillsName) {
402
+ return;
403
+ }
404
+ virtualFiles.delete(polyfillsName);
405
+ uriToPolyfillsName.delete(uri);
406
+ }
407
+ /**
408
+ * Return LSP CompletionItems from the embedded TypeScript language service
409
+ * at the given cursor position. Returns an empty array when the service has
410
+ * no results or the document is not known.
411
+ * @param uri - LSP document URI
412
+ * @param position - cursor position in the document
413
+ * @returns LSP completion items, or an empty array if none are available
414
+ */
415
+ function getSsjsCompletions(uri, position) {
416
+ return getSsjsCompletionInfo(uri, position).items;
417
+ }
418
+ /**
419
+ * Same as getSsjsCompletions, but also returns whether the completion was
420
+ * triggered for member access (e.g. `de.` or `Platform.Function.`).
421
+ * Use this in server.ts to decide whether to suppress SFMC global completions
422
+ * that would pollute member-completion lists.
423
+ * @param uri - LSP document URI
424
+ * @param position - cursor position in the document
425
+ * @returns completion items and a flag indicating whether this is a member-access completion
426
+ */
427
+ function getSsjsCompletionInfo(uri, position) {
428
+ const name = uriToVirtualName.get(uri);
429
+ if (!name)
430
+ return { items: [], isMemberCompletion: false };
431
+ setActiveDocument(name);
432
+ const file = virtualFiles.get(name);
433
+ if (!file)
434
+ return { items: [], isMemberCompletion: false };
435
+ const offset = positionToOffset(file.content, position);
436
+ let info;
437
+ try {
438
+ info = languageService.getCompletionsAtPosition(name, offset, {
439
+ includeCompletionsWithInsertText: true,
440
+ includeCompletionsForModuleExports: false,
441
+ });
442
+ }
443
+ catch {
444
+ return { items: [], isMemberCompletion: false };
445
+ }
446
+ if (!info)
447
+ return { items: [], isMemberCompletion: false };
448
+ const items = info.entries.map((entry) => {
449
+ const item = {
450
+ label: entry.name,
451
+ kind: tsKindToLsp(entry.kind),
452
+ sortText: entry.sortText,
453
+ };
454
+ if (entry.kindModifiers?.includes('deprecated')) {
455
+ item.tags = [1 /* CompletionItemTag.Deprecated */];
456
+ }
457
+ return item;
458
+ });
459
+ return { items, isMemberCompletion: info.isMemberCompletion };
460
+ }
461
+ /**
462
+ * Return LSP Diagnostics from the embedded TypeScript language service for the given SSJS document URI.
463
+ * @param uri - LSP document URI
464
+ * @returns LSP diagnostics, or an empty array if none are found
465
+ */
466
+ function getSsjsDiagnostics(uri) {
467
+ const name = uriToVirtualName.get(uri);
468
+ if (!name)
469
+ return [];
470
+ setActiveDocument(name);
471
+ const file = virtualFiles.get(name);
472
+ if (!file)
473
+ return [];
474
+ let tsDiags;
475
+ try {
476
+ tsDiags = [
477
+ ...languageService.getSyntacticDiagnostics(name),
478
+ ...languageService.getSemanticDiagnostics(name),
479
+ ];
480
+ }
481
+ catch {
482
+ return [];
483
+ }
484
+ const jsdocRanges = (0, source_analysis_js_1.jsdocCommentRanges)(file.content);
485
+ const polyfillBodyRanges = (0, source_analysis_js_1.prototypePolyfillBodyRanges)(file.content);
486
+ const results = [];
487
+ for (const d of tsDiags) {
488
+ if (d.start === undefined || d.length === undefined)
489
+ continue;
490
+ // Suppress "cannot find name" diagnostics that fall inside a JSDoc
491
+ // comment. SSJS authors routinely reference SFMC types (e.g. WSProxy) or
492
+ // user `@typedef`s in `@param`/`@property`/`@returns` tags; with
493
+ // `checkJs` enabled TypeScript flags those undeclared names even though
494
+ // they have no effect on the executed code.
495
+ // 8029: "JSDoc '@param' tag has name 'X', but there is no parameter with
496
+ // that name." Shipped polyfills document rest varargs collected via
497
+ // `arguments` with `@param {...*} [items]` (e.g. splice/bind), which have
498
+ // no matching named parameter — valid SSJS documentation, not an error.
499
+ if ([2304, 2552, 2300, 8029].includes(d.code) && (0, source_analysis_js_1.isInsideJsdoc)(d.start, jsdocRanges)) {
500
+ continue;
501
+ }
502
+ // Suppress `this`-context errors inside self-guarded prototype-polyfill
503
+ // bodies. `X = X || function () { … this.length … return this }` loses the
504
+ // declared `this: any[]` contextual type through the `||`, producing
505
+ // ts2339 ("Property 'length' does not exist") and ts2322 ("Type 'this'
506
+ // is not assignable"). The bodies are valid SSJS polyfills.
507
+ if ((d.code === 2339 || d.code === 2322) &&
508
+ (0, source_analysis_js_1.isInsideJsdoc)(d.start, polyfillBodyRanges)) {
509
+ const text = typeof d.messageText === 'string'
510
+ ? d.messageText
511
+ : flattenDiagnosticMessageText(d.messageText);
512
+ if (text.includes('this') || text.includes("'length'"))
513
+ continue;
514
+ }
515
+ const start = offsetToPosition(file.content, d.start);
516
+ const end = offsetToPosition(file.content, d.start + d.length);
517
+ const message = typeof d.messageText === 'string'
518
+ ? d.messageText
519
+ : flattenDiagnosticMessageText(d.messageText);
520
+ const href = diagnosticUrl?.(d.code);
521
+ results.push({
522
+ range: vscode_languageserver_types_1.Range.create(start, end),
523
+ severity: tsCategoryToSeverity(d.category),
524
+ source: 'sfmc-ts',
525
+ message,
526
+ code: d.code,
527
+ ...(href && { codeDescription: { href } }),
528
+ });
529
+ }
530
+ return results;
531
+ }
532
+ /**
533
+ * Return an LSP Hover from the embedded TypeScript language service at the
534
+ * given cursor position. Returns null when there is nothing to show.
535
+ * @param uri - LSP document URI
536
+ * @param position - cursor position in the document
537
+ * @returns LSP Hover with markdown content, or undefined if nothing to show
538
+ */
539
+ function getSsjsHover(uri, position) {
540
+ const name = uriToVirtualName.get(uri);
541
+ if (!name)
542
+ return undefined;
543
+ setActiveDocument(name);
544
+ const file = virtualFiles.get(name);
545
+ if (!file)
546
+ return undefined;
547
+ const offset = positionToOffset(file.content, position);
548
+ let info;
549
+ try {
550
+ info = languageService.getQuickInfoAtPosition(name, offset);
551
+ }
552
+ catch {
553
+ return undefined;
554
+ }
555
+ if (!info)
556
+ return undefined;
557
+ const sig = info.displayParts?.map((p) => p.text).join('') ?? '';
558
+ const documentation = info.documentation?.map((p) => p.text).join('') ?? '';
559
+ const parts = [];
560
+ if (sig)
561
+ parts.push('```typescript\n' + sig + '\n```');
562
+ if (documentation)
563
+ parts.push(documentation);
564
+ // Render JSDoc tags to match native TypeScript hover style.
565
+ const tags = info.tags ?? [];
566
+ const tagLines = [];
567
+ for (const tag of tags) {
568
+ const tagText = tag.text?.map((p) => p.text).join('') ?? '';
569
+ if (tag.name === 'deprecated') {
570
+ tagLines.push(tagText ? `*Deprecated:* ${tagText}` : '*Deprecated*');
571
+ }
572
+ else if (tag.name === 'remarks') {
573
+ if (tagText)
574
+ tagLines.push(tagText);
575
+ }
576
+ else if (tagText && tag.name === 'param') {
577
+ // TS returns tag text as "paramName - description"; match native TS format:
578
+ // @param `name` — description
579
+ const spaceIndex = tagText.indexOf(' ');
580
+ const pName = spaceIndex === -1 ? tagText : tagText.slice(0, spaceIndex);
581
+ const pDesc = spaceIndex === -1 ? '' : tagText.slice(spaceIndex + 1).replace(/^[-–]\s*/, '');
582
+ tagLines.push(pDesc ? `@param \`${pName}\` — ${pDesc}` : `@param \`${pName}\``);
583
+ }
584
+ else if (tagText && (tag.name === 'returns' || tag.name === 'return')) {
585
+ tagLines.push(`@returns ${tagText}`);
586
+ }
587
+ else if (tagText && tag.name === 'example') {
588
+ tagLines.push(`@example\n\`\`\`javascript\n${tagText.trim()}\n\`\`\``);
589
+ }
590
+ else if (tagText) {
591
+ tagLines.push(`*${tag.name}:* ${tagText}`);
592
+ }
593
+ }
594
+ if (tagLines.length > 0)
595
+ parts.push(tagLines.join('\n\n'));
596
+ if (parts.length === 0)
597
+ return undefined;
598
+ const content = { kind: 'markdown', value: parts.join('\n\n') };
599
+ let range;
600
+ if (info.textSpan) {
601
+ const start = offsetToPosition(file.content, info.textSpan.start);
602
+ const end = offsetToPosition(file.content, info.textSpan.start + info.textSpan.length);
603
+ range = vscode_languageserver_types_1.Range.create(start, end);
604
+ }
605
+ return range ? { contents: content, range } : { contents: content };
606
+ }
607
+ /**
608
+ * Return LSP definition Location(s) from the embedded TypeScript language
609
+ * service at the given cursor position. This gives `.ssjs` files the same
610
+ * go-to-definition quality as `.js` (top-level functions, locals, object
611
+ * members, and prototype-polyfilled methods).
612
+ *
613
+ * Definitions that resolve into a synthetic companion file (the per-document
614
+ * `.polyfills.d.ts` interface-merge) are remapped to the real
615
+ * `Ctor.prototype.method = …` assignment in the originating document, so the
616
+ * user navigates to their own polyfill rather than a generated declaration.
617
+ * @param uri - LSP document URI
618
+ * @param position - cursor position in the document
619
+ * @returns an array of LSP Locations (possibly empty)
620
+ */
621
+ function getSsjsDefinition(uri, position) {
622
+ const name = uriToVirtualName.get(uri);
623
+ const file = name ? virtualFiles.get(name) : undefined;
624
+ if (!name || !file)
625
+ return [];
626
+ setActiveDocument(name);
627
+ const offset = positionToOffset(file.content, position);
628
+ let defs;
629
+ try {
630
+ defs = languageService.getDefinitionAtPosition(name, offset);
631
+ }
632
+ catch {
633
+ return [];
634
+ }
635
+ if (!defs || defs.length === 0)
636
+ return [];
637
+ const locations = [];
638
+ for (const definition of defs) {
639
+ const targetUri = uriForVirtualName(definition.fileName);
640
+ // Skip definitions in the shared globals file — those are ambient API
641
+ // declarations with no navigable source for the user.
642
+ if (!targetUri)
643
+ continue;
644
+ const targetFile = virtualFiles.get(virtualNameForUri(targetUri));
645
+ if (!targetFile)
646
+ continue;
647
+ // A hit inside the synthetic polyfills file points at the generated
648
+ // interface member; redirect to the real prototype assignment.
649
+ const isPolyfillFile = definition.fileName.endsWith('.polyfills.d.ts');
650
+ let span = isPolyfillFile
651
+ ? (0, source_analysis_js_1.findPrototypeAssignmentSpan)(targetFile.content, definition.name)
652
+ : { start: definition.textSpan.start, length: definition.textSpan.length };
653
+ if (!span)
654
+ continue;
655
+ // For a `Ctor.prototype.method = function …` polyfill that carries a
656
+ // leading JSDoc block, TypeScript resolves the method's definition into
657
+ // the JSDoc comment (the first textual occurrence of the name inside the
658
+ // `/** … */`) rather than the assignment identifier. Redirect any
659
+ // same-document definition whose span lands inside a comment to the real
660
+ // prototype assignment so go-to-definition lands on the code line.
661
+ if (!isPolyfillFile && (0, source_analysis_js_1.isOffsetInsideComment)(targetFile.content, span.start)) {
662
+ const assignmentSpan = (0, source_analysis_js_1.findPrototypeAssignmentSpan)(targetFile.content, definition.name);
663
+ if (assignmentSpan)
664
+ span = assignmentSpan;
665
+ }
666
+ locations.push({
667
+ uri: targetUri,
668
+ range: vscode_languageserver_types_1.Range.create(offsetToPosition(targetFile.content, span.start), offsetToPosition(targetFile.content, span.start + span.length)),
669
+ });
670
+ }
671
+ return locations;
672
+ }
673
+ /**
674
+ * Return LSP reference Location(s) from the embedded TypeScript language
675
+ * service at the given cursor position — powering Find All References for
676
+ * `.ssjs` files (top-level functions, locals, object members, and
677
+ * prototype-polyfilled methods).
678
+ *
679
+ * References that resolve into the synthetic per-document `.polyfills.d.ts`
680
+ * companion are remapped to the real `Ctor.prototype.method = …` assignment in
681
+ * the originating document, matching the go-to-definition remap, so the user
682
+ * never sees a generated declaration in the results.
683
+ * @param uri - LSP document URI
684
+ * @param position - cursor position in the document
685
+ * @returns an array of LSP Locations (possibly empty)
686
+ */
687
+ function getSsjsReferences(uri, position) {
688
+ const name = uriToVirtualName.get(uri);
689
+ const file = name ? virtualFiles.get(name) : undefined;
690
+ if (!name || !file)
691
+ return [];
692
+ setActiveDocument(name);
693
+ const offset = positionToOffset(file.content, position);
694
+ let references;
695
+ try {
696
+ references = languageService.getReferencesAtPosition(name, offset);
697
+ }
698
+ catch {
699
+ return [];
700
+ }
701
+ if (!references || references.length === 0)
702
+ return [];
703
+ const locations = [];
704
+ const seen = new Set();
705
+ for (const reference of references) {
706
+ const targetUri = uriForVirtualName(reference.fileName);
707
+ // Skip references in the shared globals file — ambient API declarations
708
+ // with no navigable source for the user.
709
+ if (!targetUri)
710
+ continue;
711
+ const targetFile = virtualFiles.get(virtualNameForUri(targetUri));
712
+ if (!targetFile)
713
+ continue;
714
+ // A hit inside the synthetic polyfills file points at the generated
715
+ // interface member; redirect to the real prototype assignment.
716
+ const isPolyfillFile = reference.fileName.endsWith('.polyfills.d.ts');
717
+ const span = isPolyfillFile
718
+ ? (0, source_analysis_js_1.findPrototypeAssignmentSpan)(targetFile.content, (0, source_analysis_js_1.prototypeMethodNameFor)(targetFile.content, reference.textSpan.start))
719
+ : { start: reference.textSpan.start, length: reference.textSpan.length };
720
+ if (!span)
721
+ continue;
722
+ const start = offsetToPosition(targetFile.content, span.start);
723
+ const end = offsetToPosition(targetFile.content, span.start + span.length);
724
+ // De-duplicate (the polyfill remap can collapse several synthetic hits
725
+ // onto the same assignment span).
726
+ const key = `${targetUri}:${start.line}:${start.character}:${end.line}:${end.character}`;
727
+ if (seen.has(key))
728
+ continue;
729
+ seen.add(key);
730
+ locations.push({ uri: targetUri, range: vscode_languageserver_types_1.Range.create(start, end) });
731
+ }
732
+ return locations;
733
+ }
734
+ /**
735
+ * Return an LSP SignatureHelp from the embedded TypeScript language service at
736
+ * the given cursor position. Returns undefined when the cursor is not inside a
737
+ * function call or TypeScript has no type information for it.
738
+ *
739
+ * Uses TypeScript's native display-part machinery to build the label and
740
+ * numeric `[startOffset, endOffset]` parameter spans so VS Code highlights
741
+ * the active parameter correctly.
742
+ * @param uri - LSP document URI
743
+ * @param position - cursor position in the document
744
+ * @returns LSP SignatureHelp, or undefined if the cursor is not inside a function call
745
+ */
746
+ function getSsjsSignatureHelp(uri, position) {
747
+ const name = uriToVirtualName.get(uri);
748
+ const file = name ? virtualFiles.get(name) : undefined;
749
+ if (!name || !file)
750
+ return undefined;
751
+ setActiveDocument(name);
752
+ const offset = positionToOffset(file.content, position);
753
+ let info;
754
+ try {
755
+ info = languageService.getSignatureHelpItems(name, offset, {});
756
+ }
757
+ catch {
758
+ return undefined;
759
+ }
760
+ if (!info || info.items.length === 0)
761
+ return undefined;
762
+ const signatures = info.items.map((item) => {
763
+ const prefixText = item.prefixDisplayParts.map((p) => p.text).join('');
764
+ const suffixText = item.suffixDisplayParts.map((p) => p.text).join('');
765
+ const separatorText = item.separatorDisplayParts.map((p) => p.text).join('');
766
+ // Build label and compute exact [start, end] byte-offsets for each parameter.
767
+ // Note: span is computed independently from docText — changing documentation
768
+ // to MarkupContent does not affect active-parameter highlighting.
769
+ let cursor = prefixText.length;
770
+ const parameters = item.parameters.map((p, index) => {
771
+ if (index > 0)
772
+ cursor += separatorText.length;
773
+ const parameterText = p.displayParts.map((d) => d.text).join('');
774
+ const span = [cursor, cursor + parameterText.length];
775
+ cursor += parameterText.length;
776
+ const rawDocument_ = p.documentation?.map((d) => d.text).join('');
777
+ const documentation = rawDocument_
778
+ ? { kind: 'markdown', value: rawDocument_ }
779
+ : undefined;
780
+ return { label: span, documentation };
781
+ });
782
+ const parameterParts = item.parameters
783
+ .map((p) => p.displayParts.map((d) => d.text).join(''))
784
+ .join(separatorText);
785
+ const label = prefixText + parameterParts + suffixText;
786
+ const rawDocument = item.documentation?.map((d) => d.text).join('');
787
+ const documentation = rawDocument
788
+ ? { kind: 'markdown', value: rawDocument }
789
+ : undefined;
790
+ return { label, documentation, parameters };
791
+ });
792
+ return {
793
+ signatures,
794
+ activeSignature: info.selectedItemIndex,
795
+ activeParameter: info.argumentIndex,
796
+ };
797
+ }
798
+ return {
799
+ updateDocument: updateSsjsDocument,
800
+ removeDocument: removeSsjsDocument,
801
+ getCompletions: getSsjsCompletions,
802
+ getCompletionInfo: getSsjsCompletionInfo,
803
+ getDiagnostics: getSsjsDiagnostics,
804
+ getHover: getSsjsHover,
805
+ getDefinition: getSsjsDefinition,
806
+ getReferences: getSsjsReferences,
807
+ getSignatureHelp: getSsjsSignatureHelp,
808
+ };
809
+ }
810
+ //# sourceMappingURL=service.js.map