@prisma/orm-toolchain 8.0.0-rc.13-dev.8 → 8.0.0-rc.13-dev.9

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.
@@ -10,10 +10,10 @@ import { normalize as normalize$1 } from "node:path";
10
10
  import { format } from "@prisma/orm-framework/psl-parser/format";
11
11
  import { assembleAttributeSpecs, blockSpecFactoryOf, buildSymbolTable, findBlockDescriptor, isPrismaNextSchema, renameLegacyDirective } from "@prisma/orm-framework/psl-parser";
12
12
  import { CompletionItemKind, CompletionItemTag, ConnectionError, ConnectionErrors, DiagnosticSeverity, DidChangeWatchedFilesNotification, DocumentDiagnosticReportKind, FoldingRangeKind, InsertTextFormat, LSPErrorCodes, MarkupKind, ProposedFeatures, RegistrationRequest, ResponseError, SemanticTokenModifiers, SemanticTokenTypes, TextDocumentSyncKind, createConnection } from "vscode-languageserver";
13
+ import { TextDocument } from "vscode-languageserver-textdocument";
13
14
  import { ArrayLiteralAst, AttributeArgAst, AttributeArgListAst, BooleanLiteralExprAst, CompositeTypeDeclarationAst, FieldAttributeAst, FieldDeclarationAst, FunctionCallAst, GenericBlockDeclarationAst, IdentifierAst, KeyValuePairAst, ModelAttributeAst, ModelDeclarationAst, NamespaceDeclarationAst, NumberLiteralExprAst, ObjectLiteralExprAst, PslSources, StringLiteralExprAst, SyntaxNode, TaggedLiteralExprAst, TypesBlockAst, any, filterChildren, findChildToken, isTrivia, nonTriviaSibling, parse, skipTriviaToken } from "@prisma/orm-framework/psl-parser/syntax";
14
- import { isAuthoringPslBlockDescriptor, isAuthoringTypeConstructorDescriptor } from "@prisma/orm-framework/components/authoring";
15
15
  import { hasPslInterpreter } from "@prisma/orm-framework/psl-parser/interpret";
16
- import { TextDocument } from "vscode-languageserver-textdocument";
16
+ import { isAuthoringPslBlockDescriptor, isAuthoringTypeConstructorDescriptor } from "@prisma/orm-framework/components/authoring";
17
17
  import { ProposedFeatures as ProposedFeatures$1, StreamMessageReader, StreamMessageWriter, createConnection as createConnection$1, createProtocolConnection } from "vscode-languageserver/node";
18
18
  import { Console } from "node:console";
19
19
  import { Readable, Writable } from "node:stream";
@@ -33,22 +33,330 @@ function mapParseDiagnostics(diagnostics) {
33
33
  severity: ParseDiagnosticSeverity.Error
34
34
  }));
35
35
  }
36
- const documentStartRange = {
37
- start: {
38
- line: 0,
39
- character: 0
40
- },
41
- end: {
42
- line: 0,
43
- character: 1
44
- }
45
- };
46
- function mapInterpreterDiagnostic(diagnostic, sourceFile) {
36
+ const documentStartRange = {
37
+ start: {
38
+ line: 0,
39
+ character: 0
40
+ },
41
+ end: {
42
+ line: 0,
43
+ character: 1
44
+ }
45
+ };
46
+ function mapInterpreterDiagnostic(diagnostic, sourceFile) {
47
+ return {
48
+ range: diagnostic.span === void 0 ? documentStartRange : sourceFile.pslSpanToRange(diagnostic.span),
49
+ message: diagnostic.message,
50
+ code: diagnostic.code,
51
+ severity: diagnostic.severity === "warning" ? ParseDiagnosticSeverity.Warning : ParseDiagnosticSeverity.Error
52
+ };
53
+ }
54
+ function hasPslInputs(config) {
55
+ const source = config.contract?.source;
56
+ return source?.format === "psl" && source.inputs !== void 0;
57
+ }
58
+ async function resolveSchemaInputs(config, readText) {
59
+ const patterns = (hasPslInputs(config) ? config.contract?.source.inputs : void 0)?.map(toExpandablePath);
60
+ const expanded = await expandContractInputs(patterns);
61
+ const windows = isWindowsPlatform();
62
+ const candidates = expanded.map((path) => normalizeFileUri(pathToFileURL(path, { windows }).toString()));
63
+ const identities = new Set(candidates.map(canonicalFileIdentity));
64
+ function isMember(uri) {
65
+ if (!identities.has(canonicalFileIdentity(uri))) return false;
66
+ const text = readText(uri);
67
+ return text !== void 0 && isPrismaNextSchema(text);
68
+ }
69
+ return {
70
+ includes: isMember,
71
+ uris: () => candidates.filter(isMember)
72
+ };
73
+ }
74
+ function toExpandablePath(input) {
75
+ return isFileUri(input) ? fileURLToPath(new URL(input), { windows: isWindowsPlatform() }) : input;
76
+ }
77
+ function isWatcherCacheEligible(config) {
78
+ const patterns = config.contract?.source.inputs;
79
+ return hasPslInputs(config) && patterns !== void 0 && patterns.length > 0 && patterns.every((pattern) => /^[A-Za-z0-9_./: *?-]+$/.test(pattern) && !isFileUri(pattern) && pattern.split("/").every((segment) => !segment.includes("**") || segment === "**"));
80
+ }
81
+ function toWatcherGlobPattern(pattern) {
82
+ return isWindowsPlatform() ? pattern.replaceAll("\\", "/") : pattern;
83
+ }
84
+ function isFileUri(input) {
85
+ try {
86
+ return new URL(input).protocol === "file:";
87
+ } catch {
88
+ return false;
89
+ }
90
+ }
91
+ function canonicalFileIdentity(uri) {
92
+ let url;
93
+ try {
94
+ url = new URL(uri);
95
+ } catch {
96
+ return uri;
97
+ }
98
+ if (url.protocol !== "file:") return uri;
99
+ try {
100
+ const windows = isWindowsPlatform();
101
+ const filePath = normalize$1(fileURLToPath(url, { windows }));
102
+ return windows ? filePath.toLowerCase() : filePath;
103
+ } catch {
104
+ return uri;
105
+ }
106
+ }
107
+ function normalizeFileUri(uri) {
108
+ const identity = canonicalFileIdentity(uri);
109
+ return identity === uri ? uri : pathToFileURL(identity, { windows: isWindowsPlatform() }).toString();
110
+ }
111
+ function isWindowsPlatform() {
112
+ return process.platform === "win32";
113
+ }
114
+ var DocumentSnapshot = class {
115
+ uri;
116
+ text;
117
+ #parsed;
118
+ constructor(uri, text) {
119
+ this.uri = normalizeFileUri(uri);
120
+ this.text = text;
121
+ Object.freeze(this);
122
+ }
123
+ parse() {
124
+ this.#parsed ??= parse(this.text, this.uri);
125
+ return this.#parsed;
126
+ }
127
+ get sourceFile() {
128
+ const { document, sources } = this.parse();
129
+ return sources.sourceFileFor(document.syntax);
130
+ }
131
+ };
132
+ function statSafe(path) {
133
+ try {
134
+ const stats = statSync(path);
135
+ return {
136
+ mtime: stats.mtimeMs,
137
+ size: stats.size
138
+ };
139
+ } catch {
140
+ return;
141
+ }
142
+ }
143
+ function readDiskEntry(path, uri) {
144
+ const stats = statSafe(path);
145
+ if (stats === void 0) return void 0;
146
+ try {
147
+ return {
148
+ origin: "disk",
149
+ snapshot: new DocumentSnapshot(uri, readFileSync(path, "utf8")),
150
+ mtime: stats.mtime,
151
+ size: stats.size
152
+ };
153
+ } catch {
154
+ return;
155
+ }
156
+ }
157
+ var DocumentStore = class {
158
+ entries = /* @__PURE__ */ new Map();
159
+ watchCoverage = /* @__PURE__ */ new Map();
160
+ watchedIdentities = /* @__PURE__ */ new Set();
161
+ setWatchCoverage(owner, uris) {
162
+ const identities = new Set(Array.from(uris, canonicalFileIdentity));
163
+ if (identities.size === 0) this.watchCoverage.delete(owner);
164
+ else this.watchCoverage.set(owner, identities);
165
+ const next = /* @__PURE__ */ new Set();
166
+ for (const coverage of this.watchCoverage.values()) for (const identity of coverage) next.add(identity);
167
+ for (const identity of this.watchedIdentities) if (!next.has(identity)) this.invalidate(identity);
168
+ for (const identity of next) if (!this.watchedIdentities.has(identity)) this.invalidate(identity);
169
+ this.watchedIdentities = next;
170
+ }
171
+ getOpenDocument = (uri) => {
172
+ const entry = this.entries.get(canonicalFileIdentity(uri));
173
+ return entry?.origin === "overlay" ? entry.document : void 0;
174
+ };
175
+ openDocuments() {
176
+ const documents = [];
177
+ for (const entry of this.entries.values()) if (entry.origin === "overlay") documents.push(entry.document);
178
+ return documents;
179
+ }
180
+ text(uri) {
181
+ return this.readSnapshot(uri)?.text;
182
+ }
183
+ readSnapshot = (uri) => {
184
+ const identity = canonicalFileIdentity(uri);
185
+ const entry = this.entries.get(identity);
186
+ if (entry?.origin === "overlay") return entry.snapshot;
187
+ if (entry?.origin === "disk") {
188
+ if (this.watchedIdentities.has(identity)) return entry.snapshot;
189
+ const stats = statSafe(identity);
190
+ if (stats !== void 0 && stats.mtime === entry.mtime && stats.size === entry.size) return entry.snapshot;
191
+ }
192
+ const fresh = readDiskEntry(identity, normalizeFileUri(uri));
193
+ if (fresh === void 0) {
194
+ this.entries.delete(identity);
195
+ return;
196
+ }
197
+ this.entries.set(identity, fresh);
198
+ return fresh.snapshot;
199
+ };
200
+ invalidate(uri) {
201
+ const identity = canonicalFileIdentity(uri);
202
+ if (this.entries.get(identity)?.origin === "disk") this.entries.delete(identity);
203
+ }
204
+ open(item) {
205
+ const uri = normalizeFileUri(item.uri);
206
+ const document = TextDocument.create(uri, item.languageId, item.version, item.text);
207
+ this.entries.set(canonicalFileIdentity(item.uri), {
208
+ origin: "overlay",
209
+ document,
210
+ snapshot: new DocumentSnapshot(uri, item.text)
211
+ });
212
+ return document;
213
+ }
214
+ change(identifier, changes) {
215
+ if (changes.length === 0) return void 0;
216
+ const { uri, version } = identifier;
217
+ if (version === null || version === void 0) throw new InternalError(`Received document change event for ${uri} without valid version identifier`);
218
+ const document = this.getOpenDocument(uri);
219
+ if (document === void 0) return void 0;
220
+ const updated = TextDocument.update(document, changes, version);
221
+ this.entries.set(canonicalFileIdentity(uri), {
222
+ origin: "overlay",
223
+ document: updated,
224
+ snapshot: new DocumentSnapshot(updated.uri, updated.getText())
225
+ });
226
+ return updated;
227
+ }
228
+ close(uri) {
229
+ const document = this.getOpenDocument(uri);
230
+ this.entries.delete(canonicalFileIdentity(uri));
231
+ return document;
232
+ }
233
+ };
234
+ /**
235
+ * Wraps a connection so that an outbound call the client is no longer there to
236
+ * receive does nothing, instead of throwing at whoever made it.
237
+ *
238
+ * `vscode-jsonrpc` marks the connection closed the moment the input stream
239
+ * ends, and every send after that throws synchronously. A throw that escapes a
240
+ * notification handler ends the process: jsonrpc reports it through its logger,
241
+ * which is the connection's own remote console, so the report is another send —
242
+ * it throws again inside a `.catch()`, and the unhandled rejection is fatal.
243
+ *
244
+ * The wrapper carries the check so no individual send site has to: reads walk
245
+ * the connection's features (`console`, `languages`, …) and hand back guarded
246
+ * functions, so a send added later is guarded by construction. Only the
247
+ * connection's departure is swallowed — any other synchronous failure is a bug
248
+ * in the caller and still reaches it.
249
+ */
250
+ function guardedConnection(connection) {
251
+ return guardCalls(connection);
252
+ }
253
+ function guardCalls(target) {
254
+ const guarded = /* @__PURE__ */ new Map();
255
+ return new Proxy(target, { get: (source, property) => {
256
+ const cached = guarded.get(property);
257
+ if (cached !== void 0) return cached;
258
+ const value = Reflect.get(source, property);
259
+ if (typeof value === "function") {
260
+ const call = (...args) => whileConnected(() => Reflect.apply(value, source, args));
261
+ guarded.set(property, call);
262
+ return call;
263
+ }
264
+ if (typeof value === "object" && value !== null) {
265
+ const feature = guardCalls(value);
266
+ guarded.set(property, feature);
267
+ return feature;
268
+ }
269
+ return value;
270
+ } });
271
+ }
272
+ /**
273
+ * Whether an error says the connection is gone.
274
+ *
275
+ * The identity check is the fast path. It misses when the error comes from a
276
+ * second copy of `vscode-jsonrpc` in the dependency tree, whose
277
+ * `ConnectionError` is a different class carrying the same shape, so the code
278
+ * is what decides: `Closed`, `Disposed` and `AlreadyListening` are the whole
279
+ * range, and no other error jsonrpc throws carries a numeric `code` in it.
280
+ */
281
+ function isConnectionGone(error) {
282
+ if (error instanceof ConnectionError) return true;
283
+ if (!(error instanceof Error) || !("code" in error)) return false;
284
+ const { code } = error;
285
+ return code === ConnectionErrors.Closed || code === ConnectionErrors.Disposed || code === ConnectionErrors.AlreadyListening;
286
+ }
287
+ function whileConnected(send) {
288
+ let sent;
289
+ try {
290
+ sent = send();
291
+ } catch (error) {
292
+ if (isConnectionGone(error)) return Promise.resolve(void 0);
293
+ throw error;
294
+ }
295
+ return isThenable(sent) ? sent.then(void 0, () => void 0) : sent;
296
+ }
297
+ function isThenable(value) {
298
+ return typeof value === "object" && value !== null && "then" in value && typeof Reflect.get(value, "then") === "function";
299
+ }
300
+ const CONFIG_FILENAME = "prisma.config.ts";
301
+ const emptyLspControlStack = {
302
+ scalarTypes: [],
303
+ pslBlockDescriptors: {}
304
+ };
305
+ async function resolveConfigInputs(configPath, readText) {
306
+ const loaded = await loadConfig(configPath);
307
+ if (!loaded.ok) throw loaded.failure;
308
+ const projectSections = requireConfigSections(loaded.value, ["contract", "formatter"]);
309
+ if (!projectSections.ok) throw projectSections.failure;
310
+ const config = projectSections.value;
311
+ const inputs = await resolveSchemaInputs(config, readText);
312
+ const schemaInputConfig = config.contract === void 0 ? {} : { contract: config.contract };
313
+ if (!hasPslInputs(config)) return {
314
+ inputs,
315
+ schemaInputConfig,
316
+ controlStack: emptyLspControlStack,
317
+ ...config.formatter === void 0 ? {} : { formatter: config.formatter }
318
+ };
319
+ const controlSections = requireConfigSections(loaded.value, [
320
+ "family",
321
+ "target",
322
+ "adapter",
323
+ "driver",
324
+ "extensions"
325
+ ]);
326
+ if (!controlSections.ok) throw controlSections.failure;
327
+ const stack = createControlStack(config);
328
+ const interpretation = resolveInterpretation(config, stack, inputs);
329
+ return {
330
+ inputs,
331
+ schemaInputConfig,
332
+ controlStack: lspControlStackFromStack(stack),
333
+ ...config.formatter === void 0 ? {} : { formatter: config.formatter },
334
+ ...interpretation === void 0 ? {} : { interpretation }
335
+ };
336
+ }
337
+ function lspControlStackFromStack(stack) {
338
+ return {
339
+ scalarTypes: [...stack.scalarTypes],
340
+ pslBlockDescriptors: stack.authoringContributions.pslBlockDescriptors,
341
+ authoringContributions: stack.authoringContributions,
342
+ ...stack.controlMutationDefaults === void 0 ? {} : { controlMutationDefaults: stack.controlMutationDefaults }
343
+ };
344
+ }
345
+ function resolveInterpretation(config, stack, inputs) {
346
+ const source = config.contract?.source;
347
+ if (source === void 0 || !hasPslInterpreter(source)) return;
47
348
  return {
48
- range: diagnostic.span === void 0 ? documentStartRange : sourceFile.pslSpanToRange(diagnostic.span),
49
- message: diagnostic.message,
50
- code: diagnostic.code,
51
- severity: diagnostic.severity === "warning" ? ParseDiagnosticSeverity.Warning : ParseDiagnosticSeverity.Error
349
+ source,
350
+ context: {
351
+ composedExtensions: stack.extensions.map((p) => p.id),
352
+ composedExtensionContracts: stack.extensionContracts,
353
+ authoringContributions: stack.authoringContributions,
354
+ codecLookup: stack.codecLookup,
355
+ dataTypeLookup: stack.dataTypeLookup,
356
+ controlMutationDefaults: stack.controlMutationDefaults,
357
+ resolvedInputs: [...inputs.uris()],
358
+ capabilities: stack.capabilities
359
+ }
52
360
  };
53
361
  }
54
362
  function locateAttributeSyntax(input) {
@@ -1115,308 +1423,66 @@ function configuredScalarCandidates(source) {
1115
1423
  return {
1116
1424
  ...base,
1117
1425
  category: "configuredScalar",
1118
- detail: typeConstructor?.documentation || "Configured scalar type"
1119
- };
1120
- });
1121
- }
1122
- function topLevelSymbolCandidates(symbolTable, scalarTypes) {
1123
- const { topLevel } = symbolTable;
1124
- const namedTypes = Object.values(topLevel.namedTypes);
1125
- const scalarRefinementNames = namedTypes.filter((symbol) => refinesScalarType(symbol, scalarTypes)).map((symbol) => symbol.name).sort(compareNames);
1126
- const aliasNames = namedTypes.filter((symbol) => !refinesScalarType(symbol, scalarTypes)).map((symbol) => symbol.name).sort(compareNames);
1127
- return [
1128
- ...symbolCandidates(recordNames(topLevel.models), "topLevelModel", "Model", CompletionItemKind.Class),
1129
- ...symbolCandidates(recordNames(topLevel.compositeTypes), "topLevelCompositeType", "Composite type", CompletionItemKind.Struct),
1130
- ...symbolCandidates(scalarRefinementNames, "scalar", "Scalar type", CompletionItemKind.Unit),
1131
- ...symbolCandidates(aliasNames, "typeAlias", "Type alias", CompletionItemKind.Reference)
1132
- ];
1133
- }
1134
- function allNamespaceCandidates(symbolTable) {
1135
- return Object.values(symbolTable.topLevel.namespaces).sort((left, right) => compareNames(left.name, right.name)).map(namespaceQualifierCandidate);
1136
- }
1137
- function namespaceCandidates(namespace) {
1138
- if (namespace === void 0) return [];
1139
- return [...symbolCandidates(recordNames(namespace.models), "namespaceModel", `Model in namespace ${namespace.name}`, CompletionItemKind.Class), ...symbolCandidates(recordNames(namespace.compositeTypes), "namespaceCompositeType", `Composite type in namespace ${namespace.name}`, CompletionItemKind.Struct)];
1140
- }
1141
- function namespaceQualifierCandidate(namespace) {
1142
- return {
1143
- category: "namespace",
1144
- label: namespace.name,
1145
- insertText: namespace.name,
1146
- filterText: namespace.name,
1147
- detail: "Namespace",
1148
- kind: CompletionItemKind.Module
1149
- };
1150
- }
1151
- function symbolCandidates(names, category, detail, kind) {
1152
- return names.map((name) => ({
1153
- category,
1154
- label: name,
1155
- insertText: name,
1156
- filterText: name,
1157
- detail,
1158
- kind
1159
- }));
1160
- }
1161
- function recordNames(record) {
1162
- return Object.values(record).map((symbol) => symbol.name).sort(compareNames);
1163
- }
1164
- function sortedUnique(names) {
1165
- return [...new Set(names)].sort(compareNames);
1166
- }
1167
- function sortText(candidate) {
1168
- return `${categoryOrder[candidate.category]}:${candidate.label}`;
1169
- }
1170
- function genericBlockParameterSortText(index, label) {
1171
- return `${index.toString().padStart(4, "0")}:${label}`;
1172
- }
1173
- function compareNames(left, right) {
1174
- if (left < right) return -1;
1175
- if (left > right) return 1;
1176
- return 0;
1177
- }
1178
- function hasPslInputs(config) {
1179
- const source = config.contract?.source;
1180
- return source?.format === "psl" && source.inputs !== void 0;
1181
- }
1182
- async function resolveSchemaInputs(config, readText) {
1183
- const patterns = (hasPslInputs(config) ? config.contract?.source.inputs : void 0)?.map(toExpandablePath);
1184
- const expanded = await expandContractInputs(patterns);
1185
- const windows = isWindowsPlatform();
1186
- const candidates = expanded.map((path) => normalizeFileUri(pathToFileURL(path, { windows }).toString()));
1187
- const identities = new Set(candidates.map(canonicalFileIdentity));
1188
- function isMember(uri) {
1189
- if (!identities.has(canonicalFileIdentity(uri))) return false;
1190
- const text = readText(uri);
1191
- return text !== void 0 && isPrismaNextSchema(text);
1192
- }
1193
- return {
1194
- includes: isMember,
1195
- uris: () => candidates.filter(isMember)
1196
- };
1197
- }
1198
- function toExpandablePath(input) {
1199
- return isFileUri(input) ? fileURLToPath(new URL(input), { windows: isWindowsPlatform() }) : input;
1200
- }
1201
- function isWatcherCacheEligible(config) {
1202
- const patterns = config.contract?.source.inputs;
1203
- return hasPslInputs(config) && patterns !== void 0 && patterns.length > 0 && patterns.every((pattern) => /^[A-Za-z0-9_./: *?-]+$/.test(pattern) && !isFileUri(pattern) && pattern.split("/").every((segment) => !segment.includes("**") || segment === "**"));
1204
- }
1205
- function toWatcherGlobPattern(pattern) {
1206
- return isWindowsPlatform() ? pattern.replaceAll("\\", "/") : pattern;
1207
- }
1208
- function isFileUri(input) {
1209
- try {
1210
- return new URL(input).protocol === "file:";
1211
- } catch {
1212
- return false;
1213
- }
1214
- }
1215
- function canonicalFileIdentity(uri) {
1216
- let url;
1217
- try {
1218
- url = new URL(uri);
1219
- } catch {
1220
- return uri;
1221
- }
1222
- if (url.protocol !== "file:") return uri;
1223
- try {
1224
- const windows = isWindowsPlatform();
1225
- const filePath = normalize$1(fileURLToPath(url, { windows }));
1226
- return windows ? filePath.toLowerCase() : filePath;
1227
- } catch {
1228
- return uri;
1229
- }
1230
- }
1231
- function normalizeFileUri(uri) {
1232
- const identity = canonicalFileIdentity(uri);
1233
- return identity === uri ? uri : pathToFileURL(identity, { windows: isWindowsPlatform() }).toString();
1234
- }
1235
- function isWindowsPlatform() {
1236
- return process.platform === "win32";
1237
- }
1238
- const CONFIG_FILENAME = "prisma.config.ts";
1239
- const emptyLspControlStack = {
1240
- scalarTypes: [],
1241
- pslBlockDescriptors: {}
1242
- };
1243
- async function resolveConfigInputs(configPath, readText) {
1244
- const loaded = await loadConfig(configPath);
1245
- if (!loaded.ok) throw loaded.failure;
1246
- const projectSections = requireConfigSections(loaded.value, ["contract", "formatter"]);
1247
- if (!projectSections.ok) throw projectSections.failure;
1248
- const config = projectSections.value;
1249
- const inputs = await resolveSchemaInputs(config, readText);
1250
- const schemaInputConfig = config.contract === void 0 ? {} : { contract: config.contract };
1251
- if (!hasPslInputs(config)) return {
1252
- inputs,
1253
- schemaInputConfig,
1254
- controlStack: emptyLspControlStack,
1255
- ...config.formatter === void 0 ? {} : { formatter: config.formatter }
1256
- };
1257
- const controlSections = requireConfigSections(loaded.value, [
1258
- "family",
1259
- "target",
1260
- "adapter",
1261
- "driver",
1262
- "extensions"
1263
- ]);
1264
- if (!controlSections.ok) throw controlSections.failure;
1265
- const stack = createControlStack(config);
1266
- const interpretation = resolveInterpretation(config, stack, inputs);
1267
- return {
1268
- inputs,
1269
- schemaInputConfig,
1270
- controlStack: lspControlStackFromStack(stack),
1271
- ...config.formatter === void 0 ? {} : { formatter: config.formatter },
1272
- ...interpretation === void 0 ? {} : { interpretation }
1273
- };
1274
- }
1275
- function lspControlStackFromStack(stack) {
1276
- return {
1277
- scalarTypes: [...stack.scalarTypes],
1278
- pslBlockDescriptors: stack.authoringContributions.pslBlockDescriptors,
1279
- authoringContributions: stack.authoringContributions,
1280
- ...stack.controlMutationDefaults === void 0 ? {} : { controlMutationDefaults: stack.controlMutationDefaults }
1281
- };
1282
- }
1283
- function resolveInterpretation(config, stack, inputs) {
1284
- const source = config.contract?.source;
1285
- if (source === void 0 || !hasPslInterpreter(source)) return;
1286
- return {
1287
- source,
1288
- context: {
1289
- composedExtensions: stack.extensions.map((p) => p.id),
1290
- composedExtensionContracts: stack.extensionContracts,
1291
- authoringContributions: stack.authoringContributions,
1292
- codecLookup: stack.codecLookup,
1293
- dataTypeLookup: stack.dataTypeLookup,
1294
- controlMutationDefaults: stack.controlMutationDefaults,
1295
- resolvedInputs: [...inputs.uris()],
1296
- capabilities: stack.capabilities
1297
- }
1298
- };
1299
- }
1300
- var DocumentSnapshot = class {
1301
- uri;
1302
- text;
1303
- #parsed;
1304
- constructor(uri, text) {
1305
- this.uri = normalizeFileUri(uri);
1306
- this.text = text;
1307
- Object.freeze(this);
1308
- }
1309
- parse() {
1310
- this.#parsed ??= parse(this.text, this.uri);
1311
- return this.#parsed;
1312
- }
1313
- get sourceFile() {
1314
- const { document, sources } = this.parse();
1315
- return sources.sourceFileFor(document.syntax);
1316
- }
1317
- };
1318
- function statSafe(path) {
1319
- try {
1320
- const stats = statSync(path);
1321
- return {
1322
- mtime: stats.mtimeMs,
1323
- size: stats.size
1324
- };
1325
- } catch {
1326
- return;
1327
- }
1328
- }
1329
- function readDiskEntry(path, uri) {
1330
- const stats = statSafe(path);
1331
- if (stats === void 0) return void 0;
1332
- try {
1333
- return {
1334
- origin: "disk",
1335
- snapshot: new DocumentSnapshot(uri, readFileSync(path, "utf8")),
1336
- mtime: stats.mtime,
1337
- size: stats.size
1426
+ detail: typeConstructor?.documentation || "Configured scalar type"
1338
1427
  };
1339
- } catch {
1340
- return;
1341
- }
1428
+ });
1342
1429
  }
1343
- var DocumentStore = class {
1344
- entries = /* @__PURE__ */ new Map();
1345
- watchCoverage = /* @__PURE__ */ new Map();
1346
- watchedIdentities = /* @__PURE__ */ new Set();
1347
- setWatchCoverage(owner, uris) {
1348
- const identities = new Set(Array.from(uris, canonicalFileIdentity));
1349
- if (identities.size === 0) this.watchCoverage.delete(owner);
1350
- else this.watchCoverage.set(owner, identities);
1351
- const next = /* @__PURE__ */ new Set();
1352
- for (const coverage of this.watchCoverage.values()) for (const identity of coverage) next.add(identity);
1353
- for (const identity of this.watchedIdentities) if (!next.has(identity)) this.invalidate(identity);
1354
- for (const identity of next) if (!this.watchedIdentities.has(identity)) this.invalidate(identity);
1355
- this.watchedIdentities = next;
1356
- }
1357
- getOpenDocument = (uri) => {
1358
- const entry = this.entries.get(canonicalFileIdentity(uri));
1359
- return entry?.origin === "overlay" ? entry.document : void 0;
1360
- };
1361
- openDocuments() {
1362
- const documents = [];
1363
- for (const entry of this.entries.values()) if (entry.origin === "overlay") documents.push(entry.document);
1364
- return documents;
1365
- }
1366
- text(uri) {
1367
- return this.readSnapshot(uri)?.text;
1368
- }
1369
- readSnapshot = (uri) => {
1370
- const identity = canonicalFileIdentity(uri);
1371
- const entry = this.entries.get(identity);
1372
- if (entry?.origin === "overlay") return entry.snapshot;
1373
- if (entry?.origin === "disk") {
1374
- if (this.watchedIdentities.has(identity)) return entry.snapshot;
1375
- const stats = statSafe(identity);
1376
- if (stats !== void 0 && stats.mtime === entry.mtime && stats.size === entry.size) return entry.snapshot;
1377
- }
1378
- const fresh = readDiskEntry(identity, normalizeFileUri(uri));
1379
- if (fresh === void 0) {
1380
- this.entries.delete(identity);
1381
- return;
1382
- }
1383
- this.entries.set(identity, fresh);
1384
- return fresh.snapshot;
1430
+ function topLevelSymbolCandidates(symbolTable, scalarTypes) {
1431
+ const { topLevel } = symbolTable;
1432
+ const namedTypes = Object.values(topLevel.namedTypes);
1433
+ const scalarRefinementNames = namedTypes.filter((symbol) => refinesScalarType(symbol, scalarTypes)).map((symbol) => symbol.name).sort(compareNames);
1434
+ const aliasNames = namedTypes.filter((symbol) => !refinesScalarType(symbol, scalarTypes)).map((symbol) => symbol.name).sort(compareNames);
1435
+ return [
1436
+ ...symbolCandidates(recordNames(topLevel.models), "topLevelModel", "Model", CompletionItemKind.Class),
1437
+ ...symbolCandidates(recordNames(topLevel.compositeTypes), "topLevelCompositeType", "Composite type", CompletionItemKind.Struct),
1438
+ ...symbolCandidates(scalarRefinementNames, "scalar", "Scalar type", CompletionItemKind.Unit),
1439
+ ...symbolCandidates(aliasNames, "typeAlias", "Type alias", CompletionItemKind.Reference)
1440
+ ];
1441
+ }
1442
+ function allNamespaceCandidates(symbolTable) {
1443
+ return Object.values(symbolTable.topLevel.namespaces).sort((left, right) => compareNames(left.name, right.name)).map(namespaceQualifierCandidate);
1444
+ }
1445
+ function namespaceCandidates(namespace) {
1446
+ if (namespace === void 0) return [];
1447
+ return [...symbolCandidates(recordNames(namespace.models), "namespaceModel", `Model in namespace ${namespace.name}`, CompletionItemKind.Class), ...symbolCandidates(recordNames(namespace.compositeTypes), "namespaceCompositeType", `Composite type in namespace ${namespace.name}`, CompletionItemKind.Struct)];
1448
+ }
1449
+ function namespaceQualifierCandidate(namespace) {
1450
+ return {
1451
+ category: "namespace",
1452
+ label: namespace.name,
1453
+ insertText: namespace.name,
1454
+ filterText: namespace.name,
1455
+ detail: "Namespace",
1456
+ kind: CompletionItemKind.Module
1385
1457
  };
1386
- invalidate(uri) {
1387
- const identity = canonicalFileIdentity(uri);
1388
- if (this.entries.get(identity)?.origin === "disk") this.entries.delete(identity);
1389
- }
1390
- open(item) {
1391
- const uri = normalizeFileUri(item.uri);
1392
- const document = TextDocument.create(uri, item.languageId, item.version, item.text);
1393
- this.entries.set(canonicalFileIdentity(item.uri), {
1394
- origin: "overlay",
1395
- document,
1396
- snapshot: new DocumentSnapshot(uri, item.text)
1397
- });
1398
- return document;
1399
- }
1400
- change(identifier, changes) {
1401
- if (changes.length === 0) return void 0;
1402
- const { uri, version } = identifier;
1403
- if (version === null || version === void 0) throw new InternalError(`Received document change event for ${uri} without valid version identifier`);
1404
- const document = this.getOpenDocument(uri);
1405
- if (document === void 0) return void 0;
1406
- const updated = TextDocument.update(document, changes, version);
1407
- this.entries.set(canonicalFileIdentity(uri), {
1408
- origin: "overlay",
1409
- document: updated,
1410
- snapshot: new DocumentSnapshot(updated.uri, updated.getText())
1411
- });
1412
- return updated;
1413
- }
1414
- close(uri) {
1415
- const document = this.getOpenDocument(uri);
1416
- this.entries.delete(canonicalFileIdentity(uri));
1417
- return document;
1418
- }
1419
- };
1458
+ }
1459
+ function symbolCandidates(names, category, detail, kind) {
1460
+ return names.map((name) => ({
1461
+ category,
1462
+ label: name,
1463
+ insertText: name,
1464
+ filterText: name,
1465
+ detail,
1466
+ kind
1467
+ }));
1468
+ }
1469
+ function recordNames(record) {
1470
+ return Object.values(record).map((symbol) => symbol.name).sort(compareNames);
1471
+ }
1472
+ function sortedUnique(names) {
1473
+ return [...new Set(names)].sort(compareNames);
1474
+ }
1475
+ function sortText(candidate) {
1476
+ return `${categoryOrder[candidate.category]}:${candidate.label}`;
1477
+ }
1478
+ function genericBlockParameterSortText(index, label) {
1479
+ return `${index.toString().padStart(4, "0")}:${label}`;
1480
+ }
1481
+ function compareNames(left, right) {
1482
+ if (left < right) return -1;
1483
+ if (left > right) return 1;
1484
+ return 0;
1485
+ }
1420
1486
  /**
1421
1487
  * Computes folding ranges for block declarations in a PSL document.
1422
1488
  *
@@ -1454,72 +1520,6 @@ function addFoldingRange(declaration, sources, ranges) {
1454
1520
  kind: FoldingRangeKind.Region
1455
1521
  });
1456
1522
  }
1457
- /**
1458
- * Wraps a connection so that an outbound call the client is no longer there to
1459
- * receive does nothing, instead of throwing at whoever made it.
1460
- *
1461
- * `vscode-jsonrpc` marks the connection closed the moment the input stream
1462
- * ends, and every send after that throws synchronously. A throw that escapes a
1463
- * notification handler ends the process: jsonrpc reports it through its logger,
1464
- * which is the connection's own remote console, so the report is another send —
1465
- * it throws again inside a `.catch()`, and the unhandled rejection is fatal.
1466
- *
1467
- * The wrapper carries the check so no individual send site has to: reads walk
1468
- * the connection's features (`console`, `languages`, …) and hand back guarded
1469
- * functions, so a send added later is guarded by construction. Only the
1470
- * connection's departure is swallowed — any other synchronous failure is a bug
1471
- * in the caller and still reaches it.
1472
- */
1473
- function guardedConnection(connection) {
1474
- return guardCalls(connection);
1475
- }
1476
- function guardCalls(target) {
1477
- const guarded = /* @__PURE__ */ new Map();
1478
- return new Proxy(target, { get: (source, property) => {
1479
- const cached = guarded.get(property);
1480
- if (cached !== void 0) return cached;
1481
- const value = Reflect.get(source, property);
1482
- if (typeof value === "function") {
1483
- const call = (...args) => whileConnected(() => Reflect.apply(value, source, args));
1484
- guarded.set(property, call);
1485
- return call;
1486
- }
1487
- if (typeof value === "object" && value !== null) {
1488
- const feature = guardCalls(value);
1489
- guarded.set(property, feature);
1490
- return feature;
1491
- }
1492
- return value;
1493
- } });
1494
- }
1495
- /**
1496
- * Whether an error says the connection is gone.
1497
- *
1498
- * The identity check is the fast path. It misses when the error comes from a
1499
- * second copy of `vscode-jsonrpc` in the dependency tree, whose
1500
- * `ConnectionError` is a different class carrying the same shape, so the code
1501
- * is what decides: `Closed`, `Disposed` and `AlreadyListening` are the whole
1502
- * range, and no other error jsonrpc throws carries a numeric `code` in it.
1503
- */
1504
- function isConnectionGone(error) {
1505
- if (error instanceof ConnectionError) return true;
1506
- if (!(error instanceof Error) || !("code" in error)) return false;
1507
- const { code } = error;
1508
- return code === ConnectionErrors.Closed || code === ConnectionErrors.Disposed || code === ConnectionErrors.AlreadyListening;
1509
- }
1510
- function whileConnected(send) {
1511
- let sent;
1512
- try {
1513
- sent = send();
1514
- } catch (error) {
1515
- if (isConnectionGone(error)) return Promise.resolve(void 0);
1516
- throw error;
1517
- }
1518
- return isThenable(sent) ? sent.then(void 0, () => void 0) : sent;
1519
- }
1520
- function isThenable(value) {
1521
- return typeof value === "object" && value !== null && "then" in value && typeof Reflect.get(value, "then") === "function";
1522
- }
1523
1523
  function schemaInputIdentities(inputs) {
1524
1524
  return new Set(Array.from(inputs.uris(), canonicalFileIdentity));
1525
1525
  }
@@ -2185,108 +2185,136 @@ function renderSignature(name, signature, params, labelOffsets) {
2185
2185
  parameters: rendered
2186
2186
  };
2187
2187
  }
2188
- /** The project a new load of this config could fall back to. */
2189
- function lastGoodProject(entry) {
2190
- if (entry === void 0 || entry.status === "failed") return;
2191
- return entry.status === "loaded" ? entry.project : entry.lastGood;
2192
- }
2193
2188
  const CONFIG_LOAD_FAILED_CODE = "PRISMA_CONFIG_LOAD_FAILED";
2194
- const semanticTokenSourceLimit = 1e5;
2195
- function createServer(connection) {
2196
- return createServerOn(guardedConnection(connection));
2197
- }
2198
- function createServerOn(connection) {
2199
- const documents = new DocumentStore();
2200
- const { getOpenDocument } = documents;
2201
- const managedProjects = /* @__PURE__ */ new Map();
2202
- const documentConfigPaths = /* @__PURE__ */ new Map();
2203
- const publishedMembers = /* @__PURE__ */ new Map();
2204
- const reportedRelatedMembers = /* @__PURE__ */ new Map();
2205
- const schemaWatchRegistrations = /* @__PURE__ */ new Map();
2206
- const schemaWatchGenerations = /* @__PURE__ */ new Map();
2207
- const membershipGenerations = /* @__PURE__ */ new Map();
2208
- let membershipGeneration = 0;
2209
- let rootPath = process.cwd();
2210
- let watchedConfigGlob = join(rootPath, "**", CONFIG_FILENAME);
2211
- let clientCapabilities = noClientCapabilities;
2212
- function sendDiagnostics(params) {
2213
- connection.sendDiagnostics({
2214
- ...params,
2215
- uri: normalizeFileUri(params.uri)
2216
- });
2189
+ var Project = class {
2190
+ configPath;
2191
+ #options;
2192
+ #state = { status: "failed" };
2193
+ #membershipSequence = 0;
2194
+ #watcherGeneration = 0;
2195
+ #watcher;
2196
+ #reportedMembers = /* @__PURE__ */ new Set();
2197
+ constructor(configPath, options) {
2198
+ this.configPath = configPath;
2199
+ this.#options = options;
2217
2200
  }
2218
- function logWarn(message) {
2219
- connection.console.warn(message);
2201
+ get artifacts() {
2202
+ return this.#current()?.artifacts;
2220
2203
  }
2221
- function publishProjectMembers(project) {
2222
- if (clientCapabilities.pullDiagnostics) return;
2223
- const nextLedger = /* @__PURE__ */ new Set();
2224
- const projectSymbolDiagnostics = project.artifacts.symbolDiagnostics();
2225
- for (const candidateUri of project.inputs.uris()) {
2226
- const uri = normalizeFileUri(candidateUri);
2227
- sendDiagnostics({
2228
- uri,
2229
- diagnostics: toDiagnostics(project.artifacts.diagnostics(uri, projectSymbolDiagnostics))
2230
- });
2231
- nextLedger.add(uri);
2204
+ async publishForDocument(uri) {
2205
+ const data = await this.#resolveData().catch(() => void 0);
2206
+ if (data === void 0) return;
2207
+ const member = data.inputs.includes(uri);
2208
+ if (!member) this.#options.unmanage(uri);
2209
+ if (member || this.#reportedMembers.has(normalizeFileUri(uri))) this.#publishMembers(data);
2210
+ }
2211
+ async formatDocument(uri, source) {
2212
+ const data = await this.#resolveMember(uri);
2213
+ if (data === void 0) return void 0;
2214
+ try {
2215
+ return renameLegacyDirective(format(source, data.formatter));
2216
+ } catch {
2217
+ return;
2232
2218
  }
2233
- const previousLedger = publishedMembers.get(project.configPath);
2234
- if (previousLedger !== void 0) {
2235
- for (const uri of previousLedger) if (!nextLedger.has(uri)) sendDiagnostics({
2236
- uri,
2237
- diagnostics: []
2219
+ }
2220
+ async semanticTokens(uri, range) {
2221
+ const data = await this.#resolveMember(uri);
2222
+ const document = data?.artifacts.document(uri);
2223
+ if (data === void 0 || document === void 0) return { data: [] };
2224
+ return buildSemanticTokens({
2225
+ document: document.parse().document,
2226
+ sourceFile: document.sourceFile,
2227
+ symbolTable: data.artifacts.symbolTable(),
2228
+ scalarTypes: data.controlStack.scalarTypes
2229
+ }, range);
2230
+ }
2231
+ async completions(uri, position, capabilities) {
2232
+ const data = await this.#resolveMember(uri);
2233
+ const document = data?.artifacts.document(uri);
2234
+ if (data === void 0 || document === void 0) return [];
2235
+ try {
2236
+ return [...providePslCompletionItems({
2237
+ context: classifyPslCompletionContext({
2238
+ document: document.parse().document,
2239
+ sourceFile: document.sourceFile,
2240
+ position
2241
+ }),
2242
+ sourceFile: document.sourceFile,
2243
+ candidates: {
2244
+ ...data.controlStack,
2245
+ symbolTable: data.artifacts.symbolTable()
2246
+ },
2247
+ clientSupportsSnippets: capabilities.completionSnippets,
2248
+ clientSupportsTriggerSuggestCommand: capabilities.completionTriggerSuggestCommand,
2249
+ clientSupportsTriggerParameterHintsCommand: capabilities.completionTriggerParameterHintsCommand
2250
+ })];
2251
+ } catch {
2252
+ return [];
2253
+ }
2254
+ }
2255
+ async signatureHelp(uri, position, labelOffsets) {
2256
+ const data = await this.#resolveMember(uri);
2257
+ const document = data?.artifacts.document(uri);
2258
+ if (data === void 0 || document === void 0) return null;
2259
+ try {
2260
+ return providePslSignatureHelp({
2261
+ clientSupportsLabelOffsets: labelOffsets,
2262
+ document: document.parse().document,
2263
+ sourceFile: document.sourceFile,
2264
+ position,
2265
+ candidates: {
2266
+ ...data.controlStack,
2267
+ symbolTable: data.artifacts.symbolTable()
2268
+ }
2238
2269
  });
2270
+ } catch {
2271
+ return null;
2239
2272
  }
2240
- publishedMembers.set(project.configPath, nextLedger);
2241
2273
  }
2242
- function clearPublishedMembers(configPath) {
2243
- const ledger = publishedMembers.get(configPath);
2244
- if (ledger === void 0) return;
2245
- for (const uri of ledger) sendDiagnostics({
2246
- uri,
2247
- diagnostics: []
2248
- });
2249
- publishedMembers.delete(configPath);
2250
- }
2251
- function clearSchemaWatcher(configPath) {
2252
- const generation = (schemaWatchGenerations.get(configPath) ?? 0) + 1;
2253
- schemaWatchGenerations.set(configPath, generation);
2254
- documents.setWatchCoverage(configPath, []);
2255
- schemaWatchRegistrations.get(configPath)?.disposable.dispose();
2256
- schemaWatchRegistrations.delete(configPath);
2257
- return generation;
2274
+ async foldingRanges(uri) {
2275
+ const data = await this.#resolveMember(uri);
2276
+ const document = data?.artifacts.document(uri);
2277
+ if (data === void 0 || document === void 0) return [];
2278
+ return computeFoldingRanges(document.parse().document, data.artifacts.sources);
2279
+ }
2280
+ #resolveData() {
2281
+ const entry = this.#state;
2282
+ if (entry.status === "failed") return this.#startLoad();
2283
+ return entry.status === "loaded" ? Promise.resolve(entry.data) : entry.load;
2284
+ }
2285
+ async #resolveMember(uri) {
2286
+ const data = await this.#resolveData().catch(() => void 0);
2287
+ if (data === void 0 || data.inputs.includes(uri)) return data;
2288
+ this.#options.unmanage(uri);
2258
2289
  }
2259
- async function registerSchemaWatcher(project) {
2260
- const configPath = project.configPath;
2261
- const generation = clearSchemaWatcher(configPath);
2262
- if (!clientCapabilities.watchedFilesRegistration) return;
2263
- const patterns = project.schemaInputConfig.contract?.source.inputs ?? [];
2264
- if (patterns.length === 0) return;
2265
- try {
2266
- const disposable = await connection.client.register(DidChangeWatchedFilesNotification.type, { watchers: patterns.map((pattern) => ({ globPattern: toWatcherGlobPattern(pattern) })) });
2267
- if (disposable === void 0) return;
2268
- if (schemaWatchGenerations.get(configPath) === generation) {
2269
- schemaWatchRegistrations.set(configPath, {
2270
- disposable,
2271
- schemaInputConfig: project.schemaInputConfig
2272
- });
2273
- const current = currentProjectState(configPath);
2274
- if (current?.schemaInputConfig === project.schemaInputConfig && isWatcherCacheEligible(project.schemaInputConfig)) documents.setWatchCoverage(configPath, current.inputs.uris());
2275
- } else disposable.dispose();
2276
- } catch {}
2290
+ async reload() {
2291
+ const data = await this.#startLoad();
2292
+ this.#publishMembers(data);
2277
2293
  }
2278
- function onProjectLoaded(project) {
2279
- registerSchemaWatcher(project);
2294
+ publishMembers() {
2295
+ const data = this.#current();
2296
+ if (data !== void 0) this.#publishMembers(data);
2280
2297
  }
2281
- function buildDocumentDiagnosticReport(project, requestedUri) {
2298
+ documentChanged(uri) {
2299
+ this.artifacts?.documentChanged(uri);
2300
+ }
2301
+ documentClosed(uri) {
2302
+ this.artifacts?.documentClosed(uri);
2303
+ }
2304
+ async diagnosticReport(requestedUri) {
2305
+ const project = await this.#resolveData().catch(() => void 0);
2282
2306
  const uri = normalizeFileUri(requestedUri);
2307
+ if (project === void 0 || !project.inputs.includes(uri) && !this.#reportedMembers.has(uri)) return {
2308
+ kind: DocumentDiagnosticReportKind.Full,
2309
+ items: []
2310
+ };
2283
2311
  const projectSymbolDiagnostics = project.artifacts.symbolDiagnostics();
2284
2312
  const reportFor = (memberUri) => ({
2285
2313
  kind: DocumentDiagnosticReportKind.Full,
2286
2314
  items: toDiagnostics(project.artifacts.diagnostics(memberUri, projectSymbolDiagnostics))
2287
2315
  });
2288
2316
  const members = new Set(Array.from(project.inputs.uris(), normalizeFileUri));
2289
- const previous = reportedRelatedMembers.get(project.configPath) ?? /* @__PURE__ */ new Set();
2317
+ const previous = this.#reportedMembers;
2290
2318
  const relatedDocuments = {};
2291
2319
  for (const memberUri of /* @__PURE__ */ new Set([...members, ...previous])) {
2292
2320
  if (memberUri === uri) continue;
@@ -2297,91 +2325,158 @@ function createServerOn(connection) {
2297
2325
  }
2298
2326
  const report = reportFor(uri);
2299
2327
  if (previous.has(uri)) members.add(uri);
2300
- reportedRelatedMembers.set(project.configPath, members);
2328
+ this.#reportedMembers = members;
2301
2329
  return {
2302
2330
  ...report,
2303
2331
  ...Object.keys(relatedDocuments).length > 0 ? { relatedDocuments } : {}
2304
2332
  };
2305
2333
  }
2306
- async function resolveProjectForDocument(uri) {
2307
- const project = await projectForNearestConfig(uri);
2308
- if (project === void 0 || project.inputs.includes(uri)) return project;
2309
- documentConfigPaths.delete(canonicalFileIdentity(uri));
2310
- }
2311
- async function projectForNearestConfig(uri) {
2312
- const knownConfigPath = documentConfigPaths.get(canonicalFileIdentity(uri));
2313
- if (knownConfigPath !== void 0) return resolveProjectIfLoadable(knownConfigPath);
2314
- const filePath = filePathFromUri(uri);
2315
- if (filePath === void 0) return;
2316
- let configPath;
2317
- try {
2318
- configPath = await findNearestConfigPathForFile(filePath);
2319
- } catch {
2320
- return;
2321
- }
2322
- if (configPath === void 0) return;
2323
- documentConfigPaths.set(canonicalFileIdentity(uri), configPath);
2324
- return resolveProjectIfLoadable(configPath);
2325
- }
2326
- async function resolveProjectIfLoadable(configPath) {
2327
- try {
2328
- return await resolveProject(configPath);
2329
- } catch {
2330
- return;
2331
- }
2334
+ async refreshMembership(uri, sequence) {
2335
+ const entry = this.#state;
2336
+ if (entry.status === "failed" || this.#membershipSequence > sequence) return false;
2337
+ this.#membershipSequence = sequence;
2338
+ this.documentChanged(uri);
2339
+ const project = entry.status === "loaded" ? entry.data : await entry.load.catch(() => void 0);
2340
+ const isCurrent = () => this.#state.status === "loaded" && this.#state.data === project && this.#membershipSequence === sequence;
2341
+ if (project === void 0 || !isCurrent()) return false;
2342
+ const nextInputs = await resolveSchemaInputs(project.schemaInputConfig, (candidate) => this.#options.documents.text(candidate));
2343
+ if (!isCurrent()) return false;
2344
+ project.artifacts.updateInputs(nextInputs);
2345
+ const updated = {
2346
+ ...project,
2347
+ inputs: nextInputs
2348
+ };
2349
+ this.#state = {
2350
+ status: "loaded",
2351
+ data: updated
2352
+ };
2353
+ if (this.#watcher?.schemaInputConfig === project.schemaInputConfig && isWatcherCacheEligible(project.schemaInputConfig)) this.#options.documents.setWatchCoverage(this.configPath, nextInputs.uris());
2354
+ this.#publishMembers(updated);
2355
+ return true;
2332
2356
  }
2333
- async function resolveProject(configPath) {
2334
- const entry = managedProjects.get(configPath);
2335
- if (entry === void 0 || entry.status === "failed") return startProjectLoad(configPath);
2336
- return entry.status === "loaded" ? entry.project : entry.load;
2337
- }
2338
- function refreshProject(configPath) {
2339
- return startProjectLoad(configPath);
2340
- }
2341
- function startProjectLoad(configPath) {
2342
- membershipGenerations.set(configPath, ++membershipGeneration);
2343
- clearSchemaWatcher(configPath);
2344
- const existing = managedProjects.get(configPath);
2345
- const previousLoad = existing?.status === "loading" ? existing.load : void 0;
2346
- const lastGood = lastGoodProject(existing);
2347
- const load = (previousLoad ?? Promise.resolve(void 0)).catch(() => void 0).then(() => loadProject(configPath)).then((project) => {
2348
- if (isCurrentLoad(configPath, load)) {
2349
- managedProjects.set(configPath, {
2357
+ #current() {
2358
+ if (this.#state.status === "failed") return void 0;
2359
+ return this.#state.status === "loaded" ? this.#state.data : this.#state.lastGood;
2360
+ }
2361
+ #startLoad() {
2362
+ this.#membershipSequence = this.#options.nextSequence();
2363
+ this.#clearWatcher();
2364
+ const existing = this.#state;
2365
+ const previousLoad = existing.status === "loading" ? existing.load : void 0;
2366
+ const lastGood = this.#current();
2367
+ const load = (previousLoad ?? Promise.resolve(void 0)).catch(() => void 0).then(() => this.#load()).then((data) => {
2368
+ if (this.#isCurrentLoad(load)) {
2369
+ this.#state = {
2350
2370
  status: "loaded",
2351
- project
2371
+ data
2372
+ };
2373
+ this.#sendDiagnostics({
2374
+ uri: pathToFileURL(this.configPath).toString(),
2375
+ diagnostics: []
2352
2376
  });
2353
- clearConfigFailure(configPath);
2354
- onProjectLoaded(project);
2377
+ this.#registerWatcher(data);
2355
2378
  }
2356
- return project;
2379
+ return data;
2357
2380
  }, (error) => {
2358
- if (isCurrentLoad(configPath, load)) {
2359
- publishConfigFailure(configPath, error);
2381
+ if (this.#isCurrentLoad(load)) {
2382
+ this.#publishConfigFailure(error);
2360
2383
  if (lastGood !== void 0) {
2361
- managedProjects.set(configPath, {
2384
+ this.#state = {
2362
2385
  status: "loaded",
2363
- project: lastGood
2364
- });
2365
- onProjectLoaded(lastGood);
2386
+ data: lastGood
2387
+ };
2388
+ this.#registerWatcher(lastGood);
2366
2389
  return lastGood;
2367
2390
  }
2368
- managedProjects.set(configPath, { status: "failed" });
2369
- unmanageDocuments(configPath);
2370
- clearSchemaWatcher(configPath);
2371
- clearPublishedMembers(configPath);
2391
+ this.#state = { status: "failed" };
2392
+ this.#options.unmanage();
2393
+ this.#clearWatcher();
2394
+ this.#clearPublishedMembers();
2372
2395
  }
2373
2396
  throw error;
2374
2397
  });
2375
- managedProjects.set(configPath, {
2398
+ this.#state = {
2376
2399
  status: "loading",
2377
2400
  load,
2378
2401
  lastGood
2379
- });
2402
+ };
2380
2403
  return load;
2381
2404
  }
2382
- function publishConfigFailure(configPath, error) {
2383
- sendDiagnostics({
2384
- uri: pathToFileURL(configPath).toString(),
2405
+ #isCurrentLoad(load) {
2406
+ return this.#state.status === "loading" && this.#state.load === load;
2407
+ }
2408
+ async #load() {
2409
+ const resolution = await resolveConfigInputs(this.configPath, (uri) => this.#options.documents.text(uri));
2410
+ const artifacts = new ProjectArtifacts({
2411
+ inputs: resolution.inputs,
2412
+ readSnapshot: this.#options.documents.readSnapshot,
2413
+ onInterpretationError: (uri, error) => {
2414
+ const detail = error instanceof Error ? error.stack ?? error.message : String(error);
2415
+ this.#options.connection.console.error(`PSL interpretation failed for ${uri}: ${detail}`);
2416
+ },
2417
+ ...resolution.interpretation === void 0 ? {} : { interpretation: resolution.interpretation }
2418
+ });
2419
+ return {
2420
+ ...resolution,
2421
+ artifacts
2422
+ };
2423
+ }
2424
+ #clearWatcher() {
2425
+ const generation = ++this.#watcherGeneration;
2426
+ this.#options.documents.setWatchCoverage(this.configPath, []);
2427
+ this.#watcher?.disposable.dispose();
2428
+ this.#watcher = void 0;
2429
+ return generation;
2430
+ }
2431
+ async #registerWatcher(project) {
2432
+ const generation = this.#clearWatcher();
2433
+ if (!this.#options.watchedFilesRegistration) return;
2434
+ const patterns = project.schemaInputConfig.contract?.source.inputs ?? [];
2435
+ if (patterns.length === 0) return;
2436
+ try {
2437
+ const disposable = await this.#options.connection.client.register(DidChangeWatchedFilesNotification.type, { watchers: patterns.map((pattern) => ({ globPattern: toWatcherGlobPattern(pattern) })) });
2438
+ if (disposable === void 0) return;
2439
+ if (this.#watcherGeneration === generation) {
2440
+ this.#watcher = {
2441
+ disposable,
2442
+ schemaInputConfig: project.schemaInputConfig
2443
+ };
2444
+ const current = this.#current();
2445
+ if (current?.schemaInputConfig === project.schemaInputConfig && isWatcherCacheEligible(project.schemaInputConfig)) this.#options.documents.setWatchCoverage(this.configPath, current.inputs.uris());
2446
+ } else disposable.dispose();
2447
+ } catch {
2448
+ return;
2449
+ }
2450
+ }
2451
+ #publishMembers(project) {
2452
+ if (this.#options.pullDiagnostics) return;
2453
+ const nextLedger = /* @__PURE__ */ new Set();
2454
+ const projectSymbolDiagnostics = project.artifacts.symbolDiagnostics();
2455
+ for (const candidateUri of project.inputs.uris()) {
2456
+ const uri = normalizeFileUri(candidateUri);
2457
+ this.#sendDiagnostics({
2458
+ uri,
2459
+ diagnostics: toDiagnostics(project.artifacts.diagnostics(uri, projectSymbolDiagnostics))
2460
+ });
2461
+ nextLedger.add(uri);
2462
+ }
2463
+ for (const uri of this.#reportedMembers) if (!nextLedger.has(uri)) this.#sendDiagnostics({
2464
+ uri,
2465
+ diagnostics: []
2466
+ });
2467
+ this.#reportedMembers = nextLedger;
2468
+ }
2469
+ #clearPublishedMembers() {
2470
+ if (this.#options.pullDiagnostics) return;
2471
+ for (const uri of this.#reportedMembers) this.#sendDiagnostics({
2472
+ uri,
2473
+ diagnostics: []
2474
+ });
2475
+ this.#reportedMembers = /* @__PURE__ */ new Set();
2476
+ }
2477
+ #publishConfigFailure(error) {
2478
+ this.#sendDiagnostics({
2479
+ uri: pathToFileURL(this.configPath).toString(),
2385
2480
  diagnostics: [{
2386
2481
  range: {
2387
2482
  start: {
@@ -2393,76 +2488,178 @@ function createServerOn(connection) {
2393
2488
  character: 1
2394
2489
  }
2395
2490
  },
2396
- message: configFailureMessage(error),
2491
+ message: CliStructuredError.is(error) ? error.why ?? error.message : error instanceof Error ? error.message : String(error),
2397
2492
  code: CONFIG_LOAD_FAILED_CODE,
2398
2493
  severity: DiagnosticSeverity.Error,
2399
2494
  source: "prisma"
2400
2495
  }]
2401
2496
  });
2402
2497
  }
2403
- function configFailureMessage(error) {
2404
- if (CliStructuredError.is(error)) return error.why ?? error.message;
2405
- return error instanceof Error ? error.message : String(error);
2406
- }
2407
- function clearConfigFailure(configPath) {
2408
- sendDiagnostics({
2409
- uri: pathToFileURL(configPath).toString(),
2410
- diagnostics: []
2498
+ #sendDiagnostics(params) {
2499
+ this.#options.connection.sendDiagnostics({
2500
+ ...params,
2501
+ uri: normalizeFileUri(params.uri)
2411
2502
  });
2412
2503
  }
2413
- function isCurrentLoad(configPath, load) {
2414
- const entry = managedProjects.get(configPath);
2415
- return entry?.status === "loading" && entry.load === load;
2504
+ };
2505
+ function toDiagnostics(computed) {
2506
+ return computed.map((diagnostic) => ({
2507
+ range: diagnostic.range,
2508
+ message: diagnostic.message,
2509
+ code: diagnostic.code,
2510
+ severity: toLspSeverity(diagnostic.severity),
2511
+ source: "prisma"
2512
+ }));
2513
+ }
2514
+ function toLspSeverity(severity) {
2515
+ switch (severity) {
2516
+ case ParseDiagnosticSeverity.Warning: return DiagnosticSeverity.Warning;
2517
+ case ParseDiagnosticSeverity.Information: return DiagnosticSeverity.Information;
2518
+ case ParseDiagnosticSeverity.Hint: return DiagnosticSeverity.Hint;
2519
+ default: return DiagnosticSeverity.Error;
2520
+ }
2521
+ }
2522
+ var ProjectRegistry = class {
2523
+ #documents;
2524
+ #connection;
2525
+ #projectsByConfig = /* @__PURE__ */ new Map();
2526
+ #projectsByDocument = /* @__PURE__ */ new Map();
2527
+ #eventSequence = 0;
2528
+ #capabilities = {
2529
+ pullDiagnostics: false,
2530
+ watchedFilesRegistration: false,
2531
+ diagnosticsRefresh: false
2532
+ };
2533
+ constructor(documents, connection) {
2534
+ this.#documents = documents;
2535
+ this.#connection = connection;
2416
2536
  }
2417
- async function loadProject(configPath) {
2418
- const readText = (uri) => documents.text(uri);
2419
- const resolution = await resolveConfigInputs(configPath, readText);
2420
- const artifacts = new ProjectArtifacts({
2421
- inputs: resolution.inputs,
2422
- readSnapshot: documents.readSnapshot,
2423
- onInterpretationError: (uri, error) => {
2424
- const detail = error instanceof Error ? error.stack ?? error.message : String(error);
2425
- connection.console.error(`PSL interpretation failed for ${uri}: ${detail}`);
2426
- },
2427
- ...resolution.interpretation === void 0 ? {} : { interpretation: resolution.interpretation }
2537
+ setClientCapabilities(capabilities) {
2538
+ this.#capabilities = capabilities;
2539
+ }
2540
+ async nearestProject(uri) {
2541
+ const knownProject = this.associatedProject(uri);
2542
+ if (knownProject !== void 0) return knownProject;
2543
+ const filePath = filePathFromUri(uri);
2544
+ if (filePath === void 0) return void 0;
2545
+ let configPath;
2546
+ try {
2547
+ configPath = await findNearestConfigPathForFile(filePath);
2548
+ } catch {
2549
+ return;
2550
+ }
2551
+ if (configPath === void 0) return void 0;
2552
+ const project = this.#projectForConfig(configPath);
2553
+ this.#projectsByDocument.set(canonicalFileIdentity(uri), project);
2554
+ return project;
2555
+ }
2556
+ associatedProject(uri) {
2557
+ return this.#projectsByDocument.get(canonicalFileIdentity(uri));
2558
+ }
2559
+ documentChanged(uri) {
2560
+ this.associatedProject(uri)?.documentChanged(uri);
2561
+ this.#publishForDocument(uri).catch((error) => {
2562
+ this.#connection.console.error(error instanceof Error ? error.message : String(error));
2428
2563
  });
2429
- return {
2430
- configPath,
2431
- inputs: resolution.inputs,
2432
- schemaInputConfig: resolution.schemaInputConfig,
2433
- controlStack: resolution.controlStack,
2434
- artifacts,
2435
- ...resolution.formatter === void 0 ? {} : { formatter: resolution.formatter },
2436
- ...resolution.interpretation === void 0 ? {} : { interpretation: resolution.interpretation }
2437
- };
2438
2564
  }
2439
- function unmanageDocuments(configPath) {
2440
- for (const document of documents.openDocuments()) if (documentConfigPaths.get(canonicalFileIdentity(document.uri)) === configPath) documentConfigPaths.delete(canonicalFileIdentity(document.uri));
2565
+ documentClosed(uri) {
2566
+ const project = this.associatedProject(uri);
2567
+ project?.documentClosed(uri);
2568
+ this.#projectsByDocument.delete(canonicalFileIdentity(uri));
2569
+ if (project?.artifacts === void 0) {
2570
+ if (!this.#capabilities.pullDiagnostics) this.#connection.sendDiagnostics({
2571
+ uri: normalizeFileUri(uri),
2572
+ diagnostics: []
2573
+ });
2574
+ return;
2575
+ }
2576
+ project.publishMembers();
2441
2577
  }
2442
- async function publishForDocument(uri) {
2443
- const project = await resolveProjectForDocument(uri);
2444
- if (project === void 0) return;
2445
- publishProjectMembers(project);
2578
+ watchConfigFiles(rootPath) {
2579
+ if (this.#capabilities.watchedFilesRegistration) this.#connection.sendRequest(RegistrationRequest.type, { registrations: [{
2580
+ id: "prisma-8-config-watcher",
2581
+ method: DidChangeWatchedFilesNotification.type.method,
2582
+ registerOptions: { watchers: [{ globPattern: join(rootPath, "**", CONFIG_FILENAME) }] }
2583
+ }] });
2584
+ else this.#connection.console.warn("Client does not support dynamic file-watcher registration; Prisma 8 config changes will not be picked up without a restart.");
2446
2585
  }
2447
- function publishForDocumentSafely(uri) {
2448
- publishForDocument(uri).catch((error) => {
2449
- connection.console.error(error instanceof Error ? error.message : String(error));
2586
+ async watchedFilesChanged(changes) {
2587
+ const changedConfigPaths = /* @__PURE__ */ new Set();
2588
+ const memberChanges = [];
2589
+ for (const change of changes) {
2590
+ const filePath = filePathFromUri(change.uri);
2591
+ if (filePath?.endsWith("prisma.config.ts")) changedConfigPaths.add(filePath);
2592
+ else memberChanges.push(change.uri);
2593
+ }
2594
+ const configRefreshes = Array.from(changedConfigPaths, async (configPath) => {
2595
+ return this.#projectsByConfig.get(configPath)?.reload().catch(() => void 0);
2450
2596
  });
2597
+ const [, memberResults] = await Promise.all([Promise.all(configRefreshes), Promise.all(memberChanges.map((uri) => this.#handleSchemaMemberChange(uri)))]);
2598
+ if (this.#capabilities.pullDiagnostics && this.#capabilities.diagnosticsRefresh && (changedConfigPaths.size > 0 || memberResults.some(Boolean))) this.#connection.languages.diagnostics.refresh();
2599
+ }
2600
+ #projectForConfig(configPath) {
2601
+ let project = this.#projectsByConfig.get(configPath);
2602
+ if (project === void 0) {
2603
+ project = new Project(configPath, {
2604
+ documents: this.#documents,
2605
+ connection: this.#connection,
2606
+ pullDiagnostics: this.#capabilities.pullDiagnostics,
2607
+ watchedFilesRegistration: this.#capabilities.watchedFilesRegistration,
2608
+ nextSequence: () => ++this.#eventSequence,
2609
+ unmanage: (uri) => {
2610
+ if (uri === void 0) this.#unmanageDocuments(configPath);
2611
+ else this.#projectsByDocument.delete(canonicalFileIdentity(uri));
2612
+ }
2613
+ });
2614
+ this.#projectsByConfig.set(configPath, project);
2615
+ }
2616
+ return project;
2617
+ }
2618
+ #unmanageDocuments(configPath) {
2619
+ for (const document of this.#documents.openDocuments()) if (this.associatedProject(document.uri)?.configPath === configPath) this.#projectsByDocument.delete(canonicalFileIdentity(document.uri));
2620
+ }
2621
+ async #publishForDocument(uri) {
2622
+ await (await this.nearestProject(uri))?.publishForDocument(uri);
2623
+ }
2624
+ async #handleSchemaMemberChange(uri) {
2625
+ const sequence = ++this.#eventSequence;
2626
+ this.#documents.invalidate(uri);
2627
+ const filePath = filePathFromUri(uri);
2628
+ if (filePath === void 0) return false;
2629
+ let configPath;
2630
+ try {
2631
+ configPath = await findNearestConfigPathForFile(filePath);
2632
+ } catch {
2633
+ return false;
2634
+ }
2635
+ if (configPath === void 0) return false;
2636
+ return this.#projectsByConfig.get(configPath)?.refreshMembership(uri, sequence) ?? false;
2637
+ }
2638
+ };
2639
+ function filePathFromUri(uri) {
2640
+ try {
2641
+ return fileURLToPath(uri);
2642
+ } catch {
2643
+ return;
2451
2644
  }
2645
+ }
2646
+ const semanticTokenSourceLimit = 1e5;
2647
+ function createServer(connection) {
2648
+ return createServerOn(guardedConnection(connection));
2649
+ }
2650
+ function createServerOn(connection) {
2651
+ const documents = new DocumentStore();
2652
+ const { getOpenDocument } = documents;
2653
+ const projects = new ProjectRegistry(documents, connection);
2654
+ let rootPath = process.cwd();
2655
+ let clientCapabilities = noClientCapabilities;
2452
2656
  async function formatDocument(uri) {
2453
2657
  const document = getOpenDocument(uri);
2454
2658
  if (document === void 0) return [];
2455
2659
  const source = document.getText();
2456
2660
  if (!isPrismaNextSchema(source)) return [];
2457
- const project = await resolveProjectForDocument(uri);
2458
- if (project === void 0) return [];
2459
- let formatted;
2460
- try {
2461
- formatted = renameLegacyDirective(format(source, project.formatter));
2462
- } catch {
2463
- return [];
2464
- }
2465
- if (formatted === source) return [];
2661
+ const formatted = await (await projects.nearestProject(uri))?.formatDocument(uri, source);
2662
+ if (formatted === void 0 || formatted === source) return [];
2466
2663
  return [{
2467
2664
  range: {
2468
2665
  start: {
@@ -2478,73 +2675,20 @@ function createServerOn(connection) {
2478
2675
  const document = getOpenDocument(uri);
2479
2676
  if (document === void 0) return emptySemanticTokens();
2480
2677
  if (document.getText().length > semanticTokenSourceLimit) return emptySemanticTokens();
2481
- const project = await resolveProjectForDocument(uri);
2482
- if (project === void 0) return emptySemanticTokens();
2483
- const artifacts = project.artifacts.document(uri);
2484
- if (artifacts === void 0) return emptySemanticTokens();
2485
- return buildSemanticTokens({
2486
- document: artifacts.parse().document,
2487
- sourceFile: artifacts.sourceFile,
2488
- symbolTable: project.artifacts.symbolTable(),
2489
- scalarTypes: project.controlStack.scalarTypes
2490
- }, range);
2678
+ return (await projects.nearestProject(uri))?.semanticTokens(uri, range) ?? emptySemanticTokens();
2491
2679
  }
2492
2680
  async function completeDocument(uri, position) {
2493
2681
  if (getOpenDocument(uri) === void 0) return [];
2494
- const project = await resolveProjectForDocument(uri);
2495
- if (project === void 0) return [];
2496
- const artifacts = project.artifacts.document(uri);
2497
- if (artifacts === void 0) return [];
2498
- try {
2499
- return [...providePslCompletionItems({
2500
- context: classifyPslCompletionContext({
2501
- document: artifacts.parse().document,
2502
- sourceFile: artifacts.sourceFile,
2503
- position
2504
- }),
2505
- sourceFile: artifacts.sourceFile,
2506
- candidates: {
2507
- scalarTypes: project.controlStack.scalarTypes,
2508
- pslBlockDescriptors: project.controlStack.pslBlockDescriptors,
2509
- symbolTable: project.artifacts.symbolTable(),
2510
- ...project.controlStack.authoringContributions === void 0 ? {} : { authoringContributions: project.controlStack.authoringContributions },
2511
- ...project.controlStack.controlMutationDefaults === void 0 ? {} : { controlMutationDefaults: project.controlStack.controlMutationDefaults }
2512
- },
2513
- clientSupportsSnippets: clientCapabilities.completionSnippets,
2514
- clientSupportsTriggerSuggestCommand: clientCapabilities.completionTriggerSuggestCommand,
2515
- clientSupportsTriggerParameterHintsCommand: clientCapabilities.completionTriggerParameterHintsCommand
2516
- })];
2517
- } catch {
2518
- return [];
2519
- }
2682
+ return (await projects.nearestProject(uri))?.completions(uri, position, clientCapabilities) ?? [];
2520
2683
  }
2521
2684
  async function signatureHelpForDocument(uri, position) {
2522
2685
  if (getOpenDocument(uri) === void 0) return null;
2523
- const project = await resolveProjectForDocument(uri);
2524
- if (project === void 0) return null;
2525
- const artifacts = project.artifacts.document(uri);
2526
- if (artifacts === void 0) return null;
2527
- try {
2528
- return providePslSignatureHelp({
2529
- clientSupportsLabelOffsets: clientCapabilities.signatureLabelOffsets,
2530
- document: artifacts.parse().document,
2531
- sourceFile: artifacts.sourceFile,
2532
- position,
2533
- candidates: {
2534
- pslBlockDescriptors: project.controlStack.pslBlockDescriptors,
2535
- symbolTable: project.artifacts.symbolTable(),
2536
- ...project.controlStack.authoringContributions === void 0 ? {} : { authoringContributions: project.controlStack.authoringContributions },
2537
- ...project.controlStack.controlMutationDefaults === void 0 ? {} : { controlMutationDefaults: project.controlStack.controlMutationDefaults }
2538
- }
2539
- });
2540
- } catch {
2541
- return null;
2542
- }
2686
+ return (await projects.nearestProject(uri))?.signatureHelp(uri, position, clientCapabilities.signatureLabelOffsets) ?? null;
2543
2687
  }
2544
2688
  connection.onInitialize(async (params) => {
2545
2689
  rootPath = resolveRootPath(params);
2546
- watchedConfigGlob = join(rootPath, "**", CONFIG_FILENAME);
2547
2690
  clientCapabilities = resolveClientCapabilities(params);
2691
+ projects.setClientCapabilities(clientCapabilities);
2548
2692
  return { capabilities: {
2549
2693
  textDocumentSync: {
2550
2694
  openClose: true,
@@ -2573,66 +2717,8 @@ function createServerOn(connection) {
2573
2717
  } } : {}
2574
2718
  } };
2575
2719
  });
2576
- connection.onInitialized(() => {
2577
- if (clientCapabilities.watchedFilesRegistration) connection.sendRequest(RegistrationRequest.type, { registrations: [{
2578
- id: "prisma-8-config-watcher",
2579
- method: DidChangeWatchedFilesNotification.type.method,
2580
- registerOptions: { watchers: [{ globPattern: watchedConfigGlob }] }
2581
- }] });
2582
- else logWarn("Client does not support dynamic file-watcher registration; Prisma 8 config changes will not be picked up without a restart.");
2583
- });
2584
- async function handleSchemaMemberChange(uri) {
2585
- const generation = ++membershipGeneration;
2586
- documents.invalidate(uri);
2587
- const filePath = filePathFromUri(uri);
2588
- if (filePath === void 0) return false;
2589
- let configPath;
2590
- try {
2591
- configPath = await findNearestConfigPathForFile(filePath);
2592
- } catch {
2593
- return false;
2594
- }
2595
- if (configPath === void 0) return false;
2596
- const entry = managedProjects.get(configPath);
2597
- if (entry === void 0 || entry.status === "failed" || (membershipGenerations.get(configPath) ?? 0) > generation) return false;
2598
- membershipGenerations.set(configPath, generation);
2599
- currentProjectState(configPath)?.artifacts.documentChanged(uri);
2600
- const project = entry.status === "loaded" ? entry.project : await entry.load.catch(() => void 0);
2601
- const isCurrent = () => {
2602
- const current = managedProjects.get(configPath);
2603
- return current?.status === "loaded" && current.project === project && membershipGenerations.get(configPath) === generation;
2604
- };
2605
- if (project === void 0 || !isCurrent()) return false;
2606
- const readText = (candidate) => documents.text(candidate);
2607
- const nextInputs = await resolveSchemaInputs(project.schemaInputConfig, readText);
2608
- if (!isCurrent()) return false;
2609
- project.artifacts.updateInputs(nextInputs);
2610
- const updated = {
2611
- ...project,
2612
- inputs: nextInputs
2613
- };
2614
- managedProjects.set(configPath, {
2615
- status: "loaded",
2616
- project: updated
2617
- });
2618
- if (schemaWatchRegistrations.get(configPath)?.schemaInputConfig === project.schemaInputConfig && isWatcherCacheEligible(project.schemaInputConfig)) documents.setWatchCoverage(configPath, nextInputs.uris());
2619
- publishProjectMembers(updated);
2620
- return true;
2621
- }
2622
- connection.onDidChangeWatchedFiles(async (params) => {
2623
- const configChanges = [];
2624
- const memberChanges = [];
2625
- for (const change of params.changes) (filePathFromUri(change.uri)?.endsWith("prisma.config.ts") ? configChanges : memberChanges).push(change.uri);
2626
- const changedConfigPaths = configPathsFromWatchedChanges(configChanges.map(filePathFromUri));
2627
- const configRefreshes = Array.from(changedConfigPaths, async (configPath) => {
2628
- if (managedProjects.has(configPath)) try {
2629
- publishProjectMembers(await refreshProject(configPath));
2630
- } catch {}
2631
- });
2632
- const [, memberResults] = await Promise.all([Promise.all(configRefreshes), Promise.all(memberChanges.map(handleSchemaMemberChange))]);
2633
- const handledMemberChange = memberResults.some(Boolean);
2634
- if (clientCapabilities.pullDiagnostics && clientCapabilities.diagnosticsRefresh && (changedConfigPaths.size > 0 || handledMemberChange)) connection.languages.diagnostics.refresh();
2635
- });
2720
+ connection.onInitialized(() => projects.watchConfigFiles(rootPath));
2721
+ connection.onDidChangeWatchedFiles((params) => projects.watchedFilesChanged(params.changes));
2636
2722
  connection.onDocumentFormatting((params) => formatDocument(params.textDocument.uri));
2637
2723
  connection.onCompletion((params) => completeDocument(params.textDocument.uri, params.position));
2638
2724
  connection.onSignatureHelp((params) => signatureHelpForDocument(params.textDocument.uri, params.position));
@@ -2644,68 +2730,39 @@ function createServerOn(connection) {
2644
2730
  items: []
2645
2731
  };
2646
2732
  const uri = normalizeFileUri(params.textDocument.uri);
2647
- const project = await projectForNearestConfig(uri);
2648
- if (project === void 0 || !project.inputs.includes(uri) && !reportedRelatedMembers.get(project.configPath)?.has(uri)) return {
2733
+ const project = await projects.nearestProject(uri);
2734
+ if (project === void 0) return {
2649
2735
  kind: DocumentDiagnosticReportKind.Full,
2650
2736
  items: []
2651
2737
  };
2652
- return buildDocumentDiagnosticReport(project, uri);
2738
+ return project.diagnosticReport(uri);
2653
2739
  });
2654
2740
  connection.onFoldingRanges(async (params) => {
2655
- const project = await resolveProjectForDocument(params.textDocument.uri);
2656
- if (project === void 0) return [];
2657
- const artifacts = project.artifacts.document(params.textDocument.uri);
2658
- if (artifacts === void 0) return [];
2659
- return computeFoldingRanges(artifacts.parse().document, project.artifacts.sources);
2741
+ return (await projects.nearestProject(params.textDocument.uri))?.foldingRanges(params.textDocument.uri) ?? [];
2660
2742
  });
2661
- function documentChanged(uri) {
2662
- artifactsForDocument(uri)?.documentChanged(uri);
2663
- publishForDocumentSafely(uri);
2664
- }
2665
2743
  connection.onDidOpenTextDocument((event) => {
2666
- documentChanged(documents.open(event.textDocument).uri);
2744
+ const document = documents.open(event.textDocument);
2745
+ projects.documentChanged(document.uri);
2667
2746
  });
2668
2747
  connection.onDidChangeTextDocument((event) => {
2669
2748
  const document = documents.change(event.textDocument, event.contentChanges);
2670
- if (document !== void 0) documentChanged(document.uri);
2749
+ if (document !== void 0) projects.documentChanged(document.uri);
2671
2750
  });
2672
2751
  connection.onDidCloseTextDocument((event) => {
2673
2752
  const document = documents.close(event.textDocument.uri);
2674
2753
  if (document === void 0) return;
2675
- const uri = document.uri;
2676
- const configPath = documentConfigPaths.get(canonicalFileIdentity(uri));
2677
- artifactsForDocument(uri)?.documentClosed(uri);
2678
- documentConfigPaths.delete(canonicalFileIdentity(uri));
2679
- const project = currentProjectState(configPath);
2680
- if (project === void 0) {
2681
- if (!clientCapabilities.pullDiagnostics) sendDiagnostics({
2682
- uri,
2683
- diagnostics: []
2684
- });
2685
- return;
2686
- }
2687
- publishProjectMembers(project);
2754
+ projects.documentClosed(document.uri);
2688
2755
  });
2689
- function currentProjectState(configPath) {
2690
- if (configPath === void 0) return;
2691
- const entry = managedProjects.get(configPath);
2692
- if (entry === void 0 || entry.status === "failed") return;
2693
- return entry.status === "loaded" ? entry.project : entry.lastGood;
2694
- }
2695
2756
  connection.listen();
2696
2757
  function artifactsForDocument(uri) {
2697
- const configPath = documentConfigPaths.get(canonicalFileIdentity(uri));
2698
- if (configPath === void 0) return;
2699
- const entry = managedProjects.get(configPath);
2700
- if (entry?.status === "loaded") return entry.project.artifacts;
2701
- return entry?.status === "loading" ? entry.lastGood?.artifacts : void 0;
2758
+ return projects.associatedProject(uri)?.artifacts;
2702
2759
  }
2703
2760
  return {
2704
2761
  dispose: () => connection.dispose(),
2705
2762
  getDocumentAst: (uri) => artifactsForDocument(uri)?.document(uri),
2706
2763
  getProjectSymbolTable: (uri) => {
2707
2764
  const artifacts = artifactsForDocument(uri);
2708
- if (artifacts?.document(uri) === void 0) return;
2765
+ if (artifacts?.document(uri) === void 0) return void 0;
2709
2766
  return artifacts.symbolTable();
2710
2767
  }
2711
2768
  };
@@ -2713,23 +2770,6 @@ function createServerOn(connection) {
2713
2770
  function emptySemanticTokens() {
2714
2771
  return { data: [] };
2715
2772
  }
2716
- function toDiagnostics(computed) {
2717
- return computed.map((diagnostic) => ({
2718
- range: diagnostic.range,
2719
- message: diagnostic.message,
2720
- code: diagnostic.code,
2721
- severity: toLspSeverity(diagnostic.severity),
2722
- source: "prisma"
2723
- }));
2724
- }
2725
- function toLspSeverity(severity) {
2726
- switch (severity) {
2727
- case ParseDiagnosticSeverity.Warning: return DiagnosticSeverity.Warning;
2728
- case ParseDiagnosticSeverity.Information: return DiagnosticSeverity.Information;
2729
- case ParseDiagnosticSeverity.Hint: return DiagnosticSeverity.Hint;
2730
- default: return DiagnosticSeverity.Error;
2731
- }
2732
- }
2733
2773
  const noClientCapabilities = {
2734
2774
  watchedFilesRegistration: false,
2735
2775
  completionSnippets: false,
@@ -2753,7 +2793,8 @@ function resolveClientCapabilities(params) {
2753
2793
  function supportsCompletionCommand(options, capability) {
2754
2794
  if (typeof options !== "object" || options === null || !("completion" in options)) return false;
2755
2795
  const completion = options.completion;
2756
- return typeof completion === "object" && completion !== null && capability in completion && Reflect.get(completion, capability) === true;
2796
+ if (typeof completion !== "object" || completion === null) return false;
2797
+ return capability === "supportsTriggerSuggestCommand" ? "supportsTriggerSuggestCommand" in completion && completion.supportsTriggerSuggestCommand === true : "supportsTriggerParameterHintsCommand" in completion && completion.supportsTriggerParameterHintsCommand === true;
2757
2798
  }
2758
2799
  function resolveRootPath(params) {
2759
2800
  const workspaceFolder = params.workspaceFolders?.[0];
@@ -2762,18 +2803,6 @@ function resolveRootPath(params) {
2762
2803
  if (params.rootPath) return params.rootPath;
2763
2804
  return process.cwd();
2764
2805
  }
2765
- function filePathFromUri(uri) {
2766
- try {
2767
- return fileURLToPath(uri);
2768
- } catch {
2769
- return;
2770
- }
2771
- }
2772
- function configPathsFromWatchedChanges(paths) {
2773
- const configPaths = /* @__PURE__ */ new Set();
2774
- for (const path of paths) if (path?.endsWith("prisma.config.ts")) configPaths.add(path);
2775
- return configPaths;
2776
- }
2777
2806
  /**
2778
2807
  * `objectMode: false` is what makes this a byte stream rather than a stream of
2779
2808
  * whatever objects the host yielded: it converts each chunk to a `Buffer`.
@@ -3018,4 +3047,4 @@ function startServer(streams) {
3018
3047
  //#endregion
3019
3048
  export { startServer };
3020
3049
 
3021
- //# sourceMappingURL=exports-Dc8WjBJI.mjs.map
3050
+ //# sourceMappingURL=exports-V-9OgHnQ.mjs.map