@zenstackhq/language 3.0.0-beta.3 → 3.0.0-beta.30

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -7,16 +7,19 @@ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require
7
7
  throw Error('Dynamic require of "' + x + '" is not supported');
8
8
  });
9
9
 
10
- // src/index.ts
11
- import { isAstNode, URI as URI3 } from "langium";
12
- import { NodeFileSystem } from "langium/node";
13
- import fs3 from "fs";
14
- import path3 from "path";
15
- import { fileURLToPath as fileURLToPath2 } from "url";
10
+ // src/document.ts
11
+ import { isAstNode, TextDocument, URI as URI4 } from "langium";
12
+ import fs4 from "fs";
13
+ import path4 from "path";
14
+ import { fileURLToPath as fileURLToPath4 } from "url";
16
15
 
17
16
  // src/generated/ast.ts
18
17
  import * as langium from "langium";
19
18
  var AbstractDeclaration = "AbstractDeclaration";
19
+ function isAbstractDeclaration(item) {
20
+ return reflection.isInstance(item, AbstractDeclaration);
21
+ }
22
+ __name(isAbstractDeclaration, "isAbstractDeclaration");
20
23
  var ConfigExpr = "ConfigExpr";
21
24
  var Expression = "Expression";
22
25
  function isExpression(item) {
@@ -43,6 +46,10 @@ function isAttribute(item) {
43
46
  }
44
47
  __name(isAttribute, "isAttribute");
45
48
  var AttributeArg = "AttributeArg";
49
+ function isAttributeArg(item) {
50
+ return reflection.isInstance(item, AttributeArg);
51
+ }
52
+ __name(isAttributeArg, "isAttributeArg");
46
53
  var AttributeParam = "AttributeParam";
47
54
  var AttributeParamType = "AttributeParamType";
48
55
  var BinaryExpr = "BinaryExpr";
@@ -61,6 +68,10 @@ function isConfigArrayExpr(item) {
61
68
  }
62
69
  __name(isConfigArrayExpr, "isConfigArrayExpr");
63
70
  var ConfigField = "ConfigField";
71
+ function isConfigField(item) {
72
+ return reflection.isInstance(item, ConfigField);
73
+ }
74
+ __name(isConfigField, "isConfigField");
64
75
  var ConfigInvocationArg = "ConfigInvocationArg";
65
76
  var ConfigInvocationExpr = "ConfigInvocationExpr";
66
77
  var DataField = "DataField";
@@ -105,10 +116,22 @@ function isEnumField(item) {
105
116
  __name(isEnumField, "isEnumField");
106
117
  var FieldInitializer = "FieldInitializer";
107
118
  var FunctionDecl = "FunctionDecl";
119
+ function isFunctionDecl(item) {
120
+ return reflection.isInstance(item, FunctionDecl);
121
+ }
122
+ __name(isFunctionDecl, "isFunctionDecl");
108
123
  var FunctionParam = "FunctionParam";
109
124
  var FunctionParamType = "FunctionParamType";
110
125
  var GeneratorDecl = "GeneratorDecl";
126
+ function isGeneratorDecl(item) {
127
+ return reflection.isInstance(item, GeneratorDecl);
128
+ }
129
+ __name(isGeneratorDecl, "isGeneratorDecl");
111
130
  var InternalAttribute = "InternalAttribute";
131
+ function isInternalAttribute(item) {
132
+ return reflection.isInstance(item, InternalAttribute);
133
+ }
134
+ __name(isInternalAttribute, "isInternalAttribute");
112
135
  var InvocationExpr = "InvocationExpr";
113
136
  function isInvocationExpr(item) {
114
137
  return reflection.isInstance(item, InvocationExpr);
@@ -125,6 +148,10 @@ function isModel(item) {
125
148
  }
126
149
  __name(isModel, "isModel");
127
150
  var ModelImport = "ModelImport";
151
+ function isModelImport(item) {
152
+ return reflection.isInstance(item, ModelImport);
153
+ }
154
+ __name(isModelImport, "isModelImport");
128
155
  var NullExpr = "NullExpr";
129
156
  function isNullExpr(item) {
130
157
  return reflection.isInstance(item, NullExpr);
@@ -146,6 +173,10 @@ function isPlugin(item) {
146
173
  }
147
174
  __name(isPlugin, "isPlugin");
148
175
  var PluginField = "PluginField";
176
+ function isPluginField(item) {
177
+ return reflection.isInstance(item, PluginField);
178
+ }
179
+ __name(isPluginField, "isPluginField");
149
180
  var Procedure = "Procedure";
150
181
  var ProcedureParam = "ProcedureParam";
151
182
  var ReferenceArg = "ReferenceArg";
@@ -1012,6 +1043,26 @@ var ZModelAstReflection = class extends langium.AbstractAstReflection {
1012
1043
  };
1013
1044
  var reflection = new ZModelAstReflection();
1014
1045
 
1046
+ // src/ast.ts
1047
+ var BinaryExprOperatorPriority = {
1048
+ //LogicalExpr
1049
+ "||": 1,
1050
+ "&&": 1,
1051
+ //EqualityExpr
1052
+ "==": 2,
1053
+ "!=": 2,
1054
+ //ComparisonExpr
1055
+ ">": 3,
1056
+ "<": 3,
1057
+ ">=": 3,
1058
+ "<=": 3,
1059
+ in: 4,
1060
+ //CollectionPredicateExpr
1061
+ "^": 5,
1062
+ "?": 5,
1063
+ "!": 5
1064
+ };
1065
+
1015
1066
  // src/constants.ts
1016
1067
  var SUPPORTED_PROVIDERS = [
1017
1068
  "sqlite",
@@ -1042,8 +1093,11 @@ var ExpressionContext = /* @__PURE__ */ function(ExpressionContext2) {
1042
1093
  }({});
1043
1094
 
1044
1095
  // src/module.ts
1045
- import { inject } from "langium";
1096
+ import { DocumentState as DocumentState2, inject, URI as URI3 } from "langium";
1046
1097
  import { createDefaultModule, createDefaultSharedModule } from "langium/lsp";
1098
+ import { NodeFileSystem } from "langium/node";
1099
+ import path3 from "path";
1100
+ import { fileURLToPath as fileURLToPath3 } from "url";
1047
1101
 
1048
1102
  // src/generated/grammar.ts
1049
1103
  import { loadGrammarFromJson } from "langium";
@@ -5104,15 +5158,12 @@ var ZModelGeneratedModule = {
5104
5158
  parser: {}
5105
5159
  };
5106
5160
 
5107
- // src/validators/attribute-application-validator.ts
5108
- import { AstUtils as AstUtils2 } from "langium";
5109
- import pluralize from "pluralize";
5110
-
5111
5161
  // src/utils.ts
5112
- import { invariant } from "@zenstackhq/common-helpers";
5113
5162
  import { AstUtils, URI } from "langium";
5114
5163
  import fs from "fs";
5164
+ import { createRequire } from "module";
5115
5165
  import path from "path";
5166
+ import { fileURLToPath, pathToFileURL } from "url";
5116
5167
  function hasAttribute(decl, name) {
5117
5168
  return !!getAttribute(decl, name);
5118
5169
  }
@@ -5192,10 +5243,6 @@ function isRelationshipField(field) {
5192
5243
  return isDataModel(field.type.reference?.ref);
5193
5244
  }
5194
5245
  __name(isRelationshipField, "isRelationshipField");
5195
- function isFutureExpr(node) {
5196
- return isInvocationExpr(node) && node.function.ref?.name === "future" && isFromStdlib(node.function.ref);
5197
- }
5198
- __name(isFutureExpr, "isFutureExpr");
5199
5246
  function isDelegateModel(node) {
5200
5247
  return isDataModel(node) && hasAttribute(node, "@@delegate");
5201
5248
  }
@@ -5213,8 +5260,14 @@ function getRecursiveBases(decl, includeDelegate = true, seen = /* @__PURE__ */
5213
5260
  return result;
5214
5261
  }
5215
5262
  seen.add(decl);
5216
- decl.mixins.forEach((mixin) => {
5217
- const baseDecl = mixin.ref;
5263
+ const bases = [
5264
+ ...decl.mixins,
5265
+ ...isDataModel(decl) && decl.baseModel ? [
5266
+ decl.baseModel
5267
+ ] : []
5268
+ ];
5269
+ bases.forEach((base) => {
5270
+ const baseDecl = decl.$container.declarations.find((d) => (isTypeDef(d) || isDataModel(d)) && d.name === base.$refText);
5218
5271
  if (baseDecl) {
5219
5272
  if (!includeDelegate && isDelegateModel(baseDecl)) {
5220
5273
  return;
@@ -5337,6 +5390,10 @@ function getArray(expr) {
5337
5390
  return isArrayExpr(expr) || isConfigArrayExpr(expr) ? expr.items : void 0;
5338
5391
  }
5339
5392
  __name(getArray, "getArray");
5393
+ function getAttributeArg(attr, name) {
5394
+ return attr.args.find((arg) => arg.$resolvedParam?.name === name)?.value;
5395
+ }
5396
+ __name(getAttributeArg, "getAttributeArg");
5340
5397
  function getFunctionExpressionContext(funcDecl) {
5341
5398
  const funcAllowedContext = [];
5342
5399
  const funcAttr = funcDecl.attributes.find((attr) => attr.decl.$refText === "@@@expressionContext");
@@ -5354,7 +5411,7 @@ function getFunctionExpressionContext(funcDecl) {
5354
5411
  }
5355
5412
  __name(getFunctionExpressionContext, "getFunctionExpressionContext");
5356
5413
  function isCheckInvocation(node) {
5357
- return isInvocationExpr(node) && node.function.ref?.name === "check" && isFromStdlib(node.function.ref);
5414
+ return isInvocationExpr(node) && node.function.ref?.name === "check";
5358
5415
  }
5359
5416
  __name(isCheckInvocation, "isCheckInvocation");
5360
5417
  function resolveTransitiveImports(documents, model) {
@@ -5424,17 +5481,17 @@ function getAllDeclarationsIncludingImports(documents, model) {
5424
5481
  }
5425
5482
  __name(getAllDeclarationsIncludingImports, "getAllDeclarationsIncludingImports");
5426
5483
  function getAuthDecl(decls) {
5427
- let authModel = decls.find((m) => hasAttribute(m, "@@auth"));
5484
+ let authModel = decls.find((d) => hasAttribute(d, "@@auth"));
5428
5485
  if (!authModel) {
5429
- authModel = decls.find((m) => m.name === "User");
5486
+ authModel = decls.find((d) => d.name === "User");
5430
5487
  }
5431
5488
  return authModel;
5432
5489
  }
5433
5490
  __name(getAuthDecl, "getAuthDecl");
5434
- function isFutureInvocation(node) {
5435
- return isInvocationExpr(node) && node.function.ref?.name === "future" && isFromStdlib(node.function.ref);
5491
+ function isBeforeInvocation(node) {
5492
+ return isInvocationExpr(node) && node.function.ref?.name === "before";
5436
5493
  }
5437
- __name(isFutureInvocation, "isFutureInvocation");
5494
+ __name(isBeforeInvocation, "isBeforeInvocation");
5438
5495
  function isCollectionPredicate(node) {
5439
5496
  return isBinaryExpr(node) && [
5440
5497
  "?",
@@ -5489,12 +5546,14 @@ function getAllFields(decl, includeIgnored = false, seen = /* @__PURE__ */ new S
5489
5546
  seen.add(decl);
5490
5547
  const fields = [];
5491
5548
  for (const mixin of decl.mixins) {
5492
- invariant(mixin.ref, `Mixin ${mixin.$refText} is not resolved`);
5493
- fields.push(...getAllFields(mixin.ref, includeIgnored, seen));
5549
+ if (mixin.ref) {
5550
+ fields.push(...getAllFields(mixin.ref, includeIgnored, seen));
5551
+ }
5494
5552
  }
5495
5553
  if (isDataModel(decl) && decl.baseModel) {
5496
- invariant(decl.baseModel.ref, `Base model ${decl.baseModel.$refText} is not resolved`);
5497
- fields.push(...getAllFields(decl.baseModel.ref, includeIgnored, seen));
5554
+ if (decl.baseModel.ref) {
5555
+ fields.push(...getAllFields(decl.baseModel.ref, includeIgnored, seen));
5556
+ }
5498
5557
  }
5499
5558
  fields.push(...decl.fields.filter((f) => includeIgnored || !hasAttribute(f, "@ignore")));
5500
5559
  return fields;
@@ -5507,17 +5566,29 @@ function getAllAttributes(decl, seen = /* @__PURE__ */ new Set()) {
5507
5566
  seen.add(decl);
5508
5567
  const attributes = [];
5509
5568
  for (const mixin of decl.mixins) {
5510
- invariant(mixin.ref, `Mixin ${mixin.$refText} is not resolved`);
5511
- attributes.push(...getAllAttributes(mixin.ref, seen));
5569
+ if (mixin.ref) {
5570
+ attributes.push(...getAllAttributes(mixin.ref, seen));
5571
+ }
5512
5572
  }
5513
5573
  if (isDataModel(decl) && decl.baseModel) {
5514
- invariant(decl.baseModel.ref, `Base model ${decl.baseModel.$refText} is not resolved`);
5515
- attributes.push(...getAllAttributes(decl.baseModel.ref, seen));
5574
+ if (decl.baseModel.ref) {
5575
+ const attrs = getAllAttributes(decl.baseModel.ref, seen).filter((attr) => !isNonInheritableAttribute(attr));
5576
+ attributes.push(...attrs);
5577
+ }
5516
5578
  }
5517
5579
  attributes.push(...decl.attributes);
5518
5580
  return attributes;
5519
5581
  }
5520
5582
  __name(getAllAttributes, "getAllAttributes");
5583
+ function isNonInheritableAttribute(attr) {
5584
+ const attrName = attr.decl.ref?.name ?? attr.decl.$refText;
5585
+ return [
5586
+ "@@map",
5587
+ "@@unique",
5588
+ "@@index"
5589
+ ].includes(attrName);
5590
+ }
5591
+ __name(isNonInheritableAttribute, "isNonInheritableAttribute");
5521
5592
  function getDocument(node) {
5522
5593
  const rootNode = findRootNode(node);
5523
5594
  const result = rootNode.$document;
@@ -5527,6 +5598,71 @@ function getDocument(node) {
5527
5598
  return result;
5528
5599
  }
5529
5600
  __name(getDocument, "getDocument");
5601
+ function getPluginDocuments(model, schemaPath) {
5602
+ const result = [];
5603
+ for (const decl of model.declarations.filter(isPlugin)) {
5604
+ const providerField = decl.fields.find((f) => f.name === "provider");
5605
+ if (!providerField) {
5606
+ continue;
5607
+ }
5608
+ const provider = getLiteral(providerField.value);
5609
+ if (!provider) {
5610
+ continue;
5611
+ }
5612
+ let pluginModelFile;
5613
+ let providerPath = path.resolve(path.dirname(schemaPath), provider);
5614
+ if (fs.existsSync(providerPath)) {
5615
+ if (fs.statSync(providerPath).isDirectory()) {
5616
+ providerPath = path.join(providerPath, "index.js");
5617
+ }
5618
+ pluginModelFile = path.resolve(path.dirname(providerPath), PLUGIN_MODULE_NAME);
5619
+ if (!fs.existsSync(pluginModelFile)) {
5620
+ pluginModelFile = findUp([
5621
+ PLUGIN_MODULE_NAME
5622
+ ], path.dirname(providerPath));
5623
+ }
5624
+ }
5625
+ if (!pluginModelFile) {
5626
+ if (typeof import.meta.resolve === "function") {
5627
+ try {
5628
+ const resolvedUrl = import.meta.resolve(`${provider}/${PLUGIN_MODULE_NAME}`);
5629
+ pluginModelFile = fileURLToPath(resolvedUrl);
5630
+ } catch {
5631
+ }
5632
+ }
5633
+ }
5634
+ if (!pluginModelFile) {
5635
+ try {
5636
+ const require2 = createRequire(pathToFileURL(schemaPath));
5637
+ pluginModelFile = require2.resolve(`${provider}/${PLUGIN_MODULE_NAME}`);
5638
+ } catch {
5639
+ }
5640
+ }
5641
+ if (pluginModelFile && fs.existsSync(pluginModelFile)) {
5642
+ result.push(pluginModelFile);
5643
+ }
5644
+ }
5645
+ return result;
5646
+ }
5647
+ __name(getPluginDocuments, "getPluginDocuments");
5648
+ function findUp(names, cwd = process.cwd(), multiple = false, result = []) {
5649
+ if (!names.some((name) => !!name)) {
5650
+ return void 0;
5651
+ }
5652
+ const target = names.find((name) => fs.existsSync(path.join(cwd, name)));
5653
+ if (multiple === false && target) {
5654
+ return path.join(cwd, target);
5655
+ }
5656
+ if (target) {
5657
+ result.push(path.join(cwd, target));
5658
+ }
5659
+ const up = path.resolve(cwd, "..");
5660
+ if (up === cwd) {
5661
+ return multiple && result.length > 0 ? result : void 0;
5662
+ }
5663
+ return findUp(names, up, multiple, result);
5664
+ }
5665
+ __name(findUp, "findUp");
5530
5666
  function findRootNode(node) {
5531
5667
  while (node.$container) {
5532
5668
  node = node.$container;
@@ -5536,6 +5672,9 @@ function findRootNode(node) {
5536
5672
  __name(findRootNode, "findRootNode");
5537
5673
 
5538
5674
  // src/validators/attribute-application-validator.ts
5675
+ import { invariant } from "@zenstackhq/common-helpers";
5676
+ import { AstUtils as AstUtils2 } from "langium";
5677
+ import pluralize from "pluralize";
5539
5678
  function _ts_decorate(decorators, target, key, desc) {
5540
5679
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
5541
5680
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
@@ -5649,6 +5788,7 @@ var AttributeApplicationValidator = class {
5649
5788
  });
5650
5789
  }
5651
5790
  }
5791
+ // TODO: design a way to let plugin register validation
5652
5792
  _checkModelLevelPolicy(attr, accept) {
5653
5793
  const kind = getStringLiteral(attr.args[0]?.value);
5654
5794
  if (!kind) {
@@ -5661,11 +5801,61 @@ var AttributeApplicationValidator = class {
5661
5801
  "create",
5662
5802
  "read",
5663
5803
  "update",
5804
+ "post-update",
5664
5805
  "delete",
5665
5806
  "all"
5666
5807
  ], attr, accept);
5667
- this.rejectEncryptedFields(attr, accept);
5808
+ if ((kind === "create" || kind === "all") && attr.args[1]?.value) {
5809
+ this.rejectNonOwnedRelationInExpression(attr.args[1].value, accept);
5810
+ }
5811
+ if (kind !== "post-update" && attr.args[1]?.value) {
5812
+ const beforeCall = AstUtils2.streamAst(attr.args[1]?.value).find(isBeforeInvocation);
5813
+ if (beforeCall) {
5814
+ accept("error", `"before()" is only allowed in "post-update" policy rules`, {
5815
+ node: beforeCall
5816
+ });
5817
+ }
5818
+ }
5819
+ }
5820
+ rejectNonOwnedRelationInExpression(expr, accept) {
5821
+ const contextModel = AstUtils2.getContainerOfType(expr, isDataModel);
5822
+ if (!contextModel) {
5823
+ return;
5824
+ }
5825
+ if (AstUtils2.streamAst(expr).some((node) => {
5826
+ if (!isDataFieldReference(node)) {
5827
+ return false;
5828
+ }
5829
+ if (node.target.ref?.$container !== contextModel) {
5830
+ return false;
5831
+ }
5832
+ const field = node.target.ref;
5833
+ if (!isRelationshipField(field)) {
5834
+ return false;
5835
+ }
5836
+ if (isAuthOrAuthMemberAccess(node)) {
5837
+ return false;
5838
+ }
5839
+ const startNode = isCollectionPredicate(node.$container) && node.$container.left === node ? node.$container : node;
5840
+ const collectionPredicate = AstUtils2.getContainerOfType(startNode.$container, isCollectionPredicate);
5841
+ if (collectionPredicate && isAuthOrAuthMemberAccess(collectionPredicate.left)) {
5842
+ return false;
5843
+ }
5844
+ const relationAttr = field.attributes.find((attr) => attr.decl.ref?.name === "@relation");
5845
+ if (!relationAttr) {
5846
+ return true;
5847
+ }
5848
+ if (!relationAttr.args.some((arg) => arg.name === "fields")) {
5849
+ return true;
5850
+ }
5851
+ return false;
5852
+ })) {
5853
+ accept("error", `non-owned relation fields are not allowed in "create" rules`, {
5854
+ node: expr
5855
+ });
5856
+ }
5668
5857
  }
5858
+ // TODO: design a way to let plugin register validation
5669
5859
  _checkFieldLevelPolicy(attr, accept) {
5670
5860
  const kind = getStringLiteral(attr.args[0]?.value);
5671
5861
  if (!kind) {
@@ -5680,8 +5870,8 @@ var AttributeApplicationValidator = class {
5680
5870
  "all"
5681
5871
  ], attr, accept);
5682
5872
  const expr = attr.args[1]?.value;
5683
- if (expr && AstUtils2.streamAst(expr).some((node) => isFutureExpr(node))) {
5684
- accept("error", `"future()" is not allowed in field-level policy rules`, {
5873
+ if (expr && AstUtils2.streamAst(expr).some((node) => isBeforeInvocation(node))) {
5874
+ accept("error", `"before()" is not allowed in field-level policy rules`, {
5685
5875
  node: expr
5686
5876
  });
5687
5877
  }
@@ -5693,7 +5883,6 @@ var AttributeApplicationValidator = class {
5693
5883
  });
5694
5884
  }
5695
5885
  }
5696
- this.rejectEncryptedFields(attr, accept);
5697
5886
  }
5698
5887
  _checkValidate(attr, accept) {
5699
5888
  const condition = attr.args[0]?.value;
@@ -5703,8 +5892,9 @@ var AttributeApplicationValidator = class {
5703
5892
  });
5704
5893
  }
5705
5894
  }
5706
- _checkUnique(attr, accept) {
5707
- const fields = attr.args[0]?.value;
5895
+ _checkConstraint(attr, accept) {
5896
+ const fields = getAttributeArg(attr, "fields");
5897
+ const attrName = attr.decl.ref?.name;
5708
5898
  if (!fields) {
5709
5899
  accept("error", `expects an array of field references`, {
5710
5900
  node: attr.args[0]
@@ -5713,7 +5903,7 @@ var AttributeApplicationValidator = class {
5713
5903
  }
5714
5904
  if (isArrayExpr(fields)) {
5715
5905
  if (fields.items.length === 0) {
5716
- accept("error", `\`@@unique\` expects at least one field reference`, {
5906
+ accept("error", `\`${attrName}\` expects at least one field reference`, {
5717
5907
  node: fields
5718
5908
  });
5719
5909
  return;
@@ -5732,7 +5922,7 @@ var AttributeApplicationValidator = class {
5732
5922
  return;
5733
5923
  }
5734
5924
  if (item.target.ref.$container !== attr.$container && isDelegateModel(item.target.ref.$container)) {
5735
- accept("error", `Cannot use fields inherited from a polymorphic base model in \`@@unique\``, {
5925
+ accept("error", `Cannot use fields inherited from a polymorphic base model in \`${attrName}\``, {
5736
5926
  node: item
5737
5927
  });
5738
5928
  }
@@ -5743,14 +5933,23 @@ var AttributeApplicationValidator = class {
5743
5933
  });
5744
5934
  }
5745
5935
  }
5746
- rejectEncryptedFields(attr, accept) {
5747
- AstUtils2.streamAllContents(attr).forEach((node) => {
5748
- if (isDataFieldReference(node) && hasAttribute(node.target.ref, "@encrypted")) {
5749
- accept("error", `Encrypted fields cannot be used in policy rules`, {
5750
- node
5936
+ _checkSchema(attr, accept) {
5937
+ const schemaName = getStringLiteral(attr.args[0]?.value);
5938
+ invariant(schemaName, `@@schema expects a string literal`);
5939
+ const zmodel = AstUtils2.getContainerOfType(attr, isModel);
5940
+ const datasource = zmodel.declarations.find(isDataSource);
5941
+ if (datasource) {
5942
+ let found = false;
5943
+ const schemas = datasource.fields.find((f) => f.name === "schemas");
5944
+ if (schemas && isConfigArrayExpr(schemas.value)) {
5945
+ found = schemas.value.items.some((item) => isLiteralExpr(item) && item.value === schemaName);
5946
+ }
5947
+ if (!found) {
5948
+ accept("error", `Schema "${schemaName}" is not defined in the datasource`, {
5949
+ node: attr
5751
5950
  });
5752
5951
  }
5753
- });
5952
+ }
5754
5953
  }
5755
5954
  validatePolicyKinds(kind, candidates, attr, accept) {
5756
5955
  const items = kind.split(",").map((x) => x.trim());
@@ -5794,15 +5993,25 @@ _ts_decorate([
5794
5993
  _ts_metadata("design:returntype", void 0)
5795
5994
  ], AttributeApplicationValidator.prototype, "_checkValidate", null);
5796
5995
  _ts_decorate([
5797
- check("@@unique"),
5798
5996
  check("@@id"),
5997
+ check("@@index"),
5998
+ check("@@unique"),
5799
5999
  _ts_metadata("design:type", Function),
5800
6000
  _ts_metadata("design:paramtypes", [
5801
6001
  typeof AttributeApplication === "undefined" ? Object : AttributeApplication,
5802
6002
  typeof ValidationAcceptor === "undefined" ? Object : ValidationAcceptor
5803
6003
  ]),
5804
6004
  _ts_metadata("design:returntype", void 0)
5805
- ], AttributeApplicationValidator.prototype, "_checkUnique", null);
6005
+ ], AttributeApplicationValidator.prototype, "_checkConstraint", null);
6006
+ _ts_decorate([
6007
+ check("@@schema"),
6008
+ _ts_metadata("design:type", Function),
6009
+ _ts_metadata("design:paramtypes", [
6010
+ typeof AttributeApplication === "undefined" ? Object : AttributeApplication,
6011
+ typeof ValidationAcceptor === "undefined" ? Object : ValidationAcceptor
6012
+ ]),
6013
+ _ts_metadata("design:returntype", void 0)
6014
+ ], AttributeApplicationValidator.prototype, "_checkSchema", null);
5806
6015
  function assignableToAttributeParam(arg, param, attr) {
5807
6016
  const argResolvedType = arg.$resolvedType;
5808
6017
  if (!argResolvedType) {
@@ -5812,6 +6021,10 @@ function assignableToAttributeParam(arg, param, attr) {
5812
6021
  let dstIsArray = param.type.array;
5813
6022
  if (dstType === "ContextType") {
5814
6023
  if (isDataField(attr.$container)) {
6024
+ const dstIsTypedJson = hasAttribute(attr.$container, "@json");
6025
+ if (dstIsTypedJson && attr.decl.ref?.name === "@default") {
6026
+ return argResolvedType.decl === "String";
6027
+ }
5815
6028
  dstIsArray = attr.$container.type.array;
5816
6029
  }
5817
6030
  }
@@ -5903,6 +6116,9 @@ function isValidAttributeTarget(attrDecl, targetDecl) {
5903
6116
  case "TypeDefField":
5904
6117
  allowed = allowed || isTypeDef(targetDecl.type.reference?.ref);
5905
6118
  break;
6119
+ case "ListField":
6120
+ allowed = allowed || !isDataModel(targetDecl.type.reference?.ref) && targetDecl.type.array;
6121
+ break;
5906
6122
  default:
5907
6123
  break;
5908
6124
  }
@@ -6170,7 +6386,7 @@ var DataModelValidator = class {
6170
6386
  if (!thisRelation.valid) {
6171
6387
  return;
6172
6388
  }
6173
- if (this.isFieldInheritedFromDelegateModel(field)) {
6389
+ if (this.isFieldInheritedFromDelegateModel(field, contextModel)) {
6174
6390
  return;
6175
6391
  }
6176
6392
  if (this.isSelfRelation(field)) {
@@ -6293,8 +6509,8 @@ var DataModelValidator = class {
6293
6509
  }
6294
6510
  }
6295
6511
  // checks if the given field is inherited directly or indirectly from a delegate model
6296
- isFieldInheritedFromDelegateModel(field) {
6297
- return isDelegateModel(field.$container);
6512
+ isFieldInheritedFromDelegateModel(field, contextModel) {
6513
+ return field.$container !== contextModel && isDelegateModel(field.$container);
6298
6514
  }
6299
6515
  validateInherits(model, accept) {
6300
6516
  if (!model.baseModel) {
@@ -6353,7 +6569,6 @@ var DataSourceValidator = class {
6353
6569
  validateDuplicatedDeclarations(ds, ds.fields, accept);
6354
6570
  this.validateProvider(ds, accept);
6355
6571
  this.validateUrl(ds, accept);
6356
- this.validateRelationMode(ds, accept);
6357
6572
  }
6358
6573
  validateProvider(ds, accept) {
6359
6574
  const provider = ds.fields.find((f) => f.name === "provider");
@@ -6363,16 +6578,52 @@ var DataSourceValidator = class {
6363
6578
  });
6364
6579
  return;
6365
6580
  }
6366
- const value = getStringLiteral(provider.value);
6367
- if (!value) {
6581
+ const providerValue = getStringLiteral(provider.value);
6582
+ if (!providerValue) {
6368
6583
  accept("error", '"provider" must be set to a string literal', {
6369
6584
  node: provider.value
6370
6585
  });
6371
- } else if (!SUPPORTED_PROVIDERS.includes(value)) {
6372
- accept("error", `Provider "${value}" is not supported. Choose from ${SUPPORTED_PROVIDERS.map((p) => '"' + p + '"').join(" | ")}.`, {
6586
+ } else if (!SUPPORTED_PROVIDERS.includes(providerValue)) {
6587
+ accept("error", `Provider "${providerValue}" is not supported. Choose from ${SUPPORTED_PROVIDERS.map((p) => '"' + p + '"').join(" | ")}.`, {
6373
6588
  node: provider.value
6374
6589
  });
6375
6590
  }
6591
+ const defaultSchemaField = ds.fields.find((f) => f.name === "defaultSchema");
6592
+ let defaultSchemaValue;
6593
+ if (defaultSchemaField) {
6594
+ if (providerValue !== "postgresql") {
6595
+ accept("error", '"defaultSchema" is only supported for "postgresql" provider', {
6596
+ node: defaultSchemaField
6597
+ });
6598
+ }
6599
+ defaultSchemaValue = getStringLiteral(defaultSchemaField.value);
6600
+ if (!defaultSchemaValue) {
6601
+ accept("error", '"defaultSchema" must be a string literal', {
6602
+ node: defaultSchemaField.value
6603
+ });
6604
+ }
6605
+ }
6606
+ const schemasField = ds.fields.find((f) => f.name === "schemas");
6607
+ if (schemasField) {
6608
+ if (providerValue !== "postgresql") {
6609
+ accept("error", '"schemas" is only supported for "postgresql" provider', {
6610
+ node: schemasField
6611
+ });
6612
+ }
6613
+ const schemasValue = schemasField.value;
6614
+ if (!isConfigArrayExpr(schemasValue) || !schemasValue.items.every((e) => isLiteralExpr(e) && typeof getStringLiteral(e) === "string")) {
6615
+ accept("error", '"schemas" must be an array of string literals', {
6616
+ node: schemasField
6617
+ });
6618
+ } else if (
6619
+ // validate `defaultSchema` is included in `schemas`
6620
+ defaultSchemaValue && !schemasValue.items.some((e) => getStringLiteral(e) === defaultSchemaValue)
6621
+ ) {
6622
+ accept("error", `"${defaultSchemaValue}" must be included in the "schemas" array`, {
6623
+ node: schemasField
6624
+ });
6625
+ }
6626
+ }
6376
6627
  }
6377
6628
  validateUrl(ds, accept) {
6378
6629
  const urlField = ds.fields.find((f) => f.name === "url");
@@ -6386,20 +6637,6 @@ var DataSourceValidator = class {
6386
6637
  });
6387
6638
  }
6388
6639
  }
6389
- validateRelationMode(ds, accept) {
6390
- const field = ds.fields.find((f) => f.name === "relationMode");
6391
- if (field) {
6392
- const val = getStringLiteral(field.value);
6393
- if (!val || ![
6394
- "foreignKeys",
6395
- "prisma"
6396
- ].includes(val)) {
6397
- accept("error", '"relationMode" must be set to "foreignKeys" or "prisma"', {
6398
- node: field.value
6399
- });
6400
- }
6401
- }
6402
- }
6403
6640
  };
6404
6641
 
6405
6642
  // src/validators/enum-validator.ts
@@ -6452,11 +6689,21 @@ var ExpressionValidator = class {
6452
6689
  }
6453
6690
  }
6454
6691
  switch (expr.$type) {
6692
+ case "MemberAccessExpr":
6693
+ this.validateMemberAccessExpr(expr, accept);
6694
+ break;
6455
6695
  case "BinaryExpr":
6456
6696
  this.validateBinaryExpr(expr, accept);
6457
6697
  break;
6458
6698
  }
6459
6699
  }
6700
+ validateMemberAccessExpr(expr, accept) {
6701
+ if (isBeforeInvocation(expr.operand) && isDataModel(expr.$resolvedType?.decl)) {
6702
+ accept("error", "relation fields cannot be accessed from `before()`", {
6703
+ node: expr
6704
+ });
6705
+ }
6706
+ }
6460
6707
  validateBinaryExpr(expr, accept) {
6461
6708
  switch (expr.operator) {
6462
6709
  case "in": {
@@ -6509,23 +6756,25 @@ var ExpressionValidator = class {
6509
6756
  "Any"
6510
6757
  ];
6511
6758
  }
6512
- if (typeof expr.left.$resolvedType?.decl !== "string" || !supportedShapes.includes(expr.left.$resolvedType.decl)) {
6759
+ const leftResolvedDecl = expr.left.$resolvedType?.decl;
6760
+ const rightResolvedDecl = expr.right.$resolvedType?.decl;
6761
+ if (leftResolvedDecl && (typeof leftResolvedDecl !== "string" || !supportedShapes.includes(leftResolvedDecl))) {
6513
6762
  accept("error", `invalid operand type for "${expr.operator}" operator`, {
6514
6763
  node: expr.left
6515
6764
  });
6516
6765
  return;
6517
6766
  }
6518
- if (typeof expr.right.$resolvedType?.decl !== "string" || !supportedShapes.includes(expr.right.$resolvedType.decl)) {
6767
+ if (rightResolvedDecl && (typeof rightResolvedDecl !== "string" || !supportedShapes.includes(rightResolvedDecl))) {
6519
6768
  accept("error", `invalid operand type for "${expr.operator}" operator`, {
6520
6769
  node: expr.right
6521
6770
  });
6522
6771
  return;
6523
6772
  }
6524
- if (expr.left.$resolvedType.decl === "DateTime" && expr.right.$resolvedType.decl !== "DateTime") {
6773
+ if (leftResolvedDecl === "DateTime" && rightResolvedDecl && rightResolvedDecl !== "DateTime") {
6525
6774
  accept("error", "incompatible operand types", {
6526
6775
  node: expr
6527
6776
  });
6528
- } else if (expr.right.$resolvedType.decl === "DateTime" && expr.left.$resolvedType.decl !== "DateTime") {
6777
+ } else if (rightResolvedDecl === "DateTime" && leftResolvedDecl && leftResolvedDecl !== "DateTime") {
6529
6778
  accept("error", "incompatible operand types", {
6530
6779
  node: expr
6531
6780
  });
@@ -6565,11 +6814,11 @@ var ExpressionValidator = class {
6565
6814
  });
6566
6815
  }
6567
6816
  if (isDataFieldReference(expr.left) && (isThisExpr(expr.right) || isDataFieldReference(expr.right))) {
6568
- accept("error", "comparison between model-typed fields are not supported", {
6817
+ accept("error", "comparison between models is not supported", {
6569
6818
  node: expr
6570
6819
  });
6571
6820
  } else if (isDataFieldReference(expr.right) && (isThisExpr(expr.left) || isDataFieldReference(expr.left))) {
6572
- accept("error", "comparison between model-typed fields are not supported", {
6821
+ accept("error", "comparison between models is not supported", {
6573
6822
  node: expr
6574
6823
  });
6575
6824
  }
@@ -6659,41 +6908,39 @@ var FunctionInvocationValidator = class {
6659
6908
  if (!this.validateArgs(funcDecl, expr.args, accept)) {
6660
6909
  return;
6661
6910
  }
6662
- if (isFromStdlib(funcDecl)) {
6663
- let curr = expr.$container;
6664
- let containerAttribute;
6665
- while (curr) {
6666
- if (isDataModelAttribute(curr) || isDataFieldAttribute(curr)) {
6667
- containerAttribute = curr;
6668
- break;
6669
- }
6670
- curr = curr.$container;
6911
+ let curr = expr.$container;
6912
+ let containerAttribute;
6913
+ while (curr) {
6914
+ if (isDataModelAttribute(curr) || isDataFieldAttribute(curr)) {
6915
+ containerAttribute = curr;
6916
+ break;
6671
6917
  }
6672
- const exprContext = match(containerAttribute?.decl.$refText).with("@default", () => ExpressionContext.DefaultValue).with(P.union("@@allow", "@@deny", "@allow", "@deny"), () => ExpressionContext.AccessPolicy).with("@@validate", () => ExpressionContext.ValidationRule).with("@@index", () => ExpressionContext.Index).otherwise(() => void 0);
6673
- const funcAllowedContext = getFunctionExpressionContext(funcDecl);
6674
- if (exprContext && !funcAllowedContext.includes(exprContext)) {
6675
- accept("error", `function "${funcDecl.name}" is not allowed in the current context: ${exprContext}`, {
6676
- node: expr
6918
+ curr = curr.$container;
6919
+ }
6920
+ const exprContext = this.getExpressionContext(containerAttribute);
6921
+ const funcAllowedContext = getFunctionExpressionContext(funcDecl);
6922
+ if (exprContext && !funcAllowedContext.includes(exprContext)) {
6923
+ accept("error", `function "${funcDecl.name}" is not allowed in the current context: ${exprContext}`, {
6924
+ node: expr
6925
+ });
6926
+ return;
6927
+ }
6928
+ const allCasing = [
6929
+ "original",
6930
+ "upper",
6931
+ "lower",
6932
+ "capitalize",
6933
+ "uncapitalize"
6934
+ ];
6935
+ if ([
6936
+ "currentModel",
6937
+ "currentOperation"
6938
+ ].includes(funcDecl.name)) {
6939
+ const arg = getLiteral(expr.args[0]?.value);
6940
+ if (arg && !allCasing.includes(arg)) {
6941
+ accept("error", `argument must be one of: ${allCasing.map((c) => '"' + c + '"').join(", ")}`, {
6942
+ node: expr.args[0]
6677
6943
  });
6678
- return;
6679
- }
6680
- const allCasing = [
6681
- "original",
6682
- "upper",
6683
- "lower",
6684
- "capitalize",
6685
- "uncapitalize"
6686
- ];
6687
- if ([
6688
- "currentModel",
6689
- "currentOperation"
6690
- ].includes(funcDecl.name)) {
6691
- const arg = getLiteral(expr.args[0]?.value);
6692
- if (arg && !allCasing.includes(arg)) {
6693
- accept("error", `argument must be one of: ${allCasing.map((c) => '"' + c + '"').join(", ")}`, {
6694
- node: expr.args[0]
6695
- });
6696
- }
6697
6944
  }
6698
6945
  }
6699
6946
  const checker = invocationCheckers.get(expr.function.$refText);
@@ -6701,6 +6948,18 @@ var FunctionInvocationValidator = class {
6701
6948
  checker.value.call(this, expr, accept);
6702
6949
  }
6703
6950
  }
6951
+ getExpressionContext(containerAttribute) {
6952
+ if (!containerAttribute) {
6953
+ return void 0;
6954
+ }
6955
+ if (this.isValidationAttribute(containerAttribute)) {
6956
+ return ExpressionContext.ValidationRule;
6957
+ }
6958
+ return match(containerAttribute?.decl.$refText).with("@default", () => ExpressionContext.DefaultValue).with(P.union("@@allow", "@@deny", "@allow", "@deny"), () => ExpressionContext.AccessPolicy).with("@@index", () => ExpressionContext.Index).otherwise(() => void 0);
6959
+ }
6960
+ isValidationAttribute(attr) {
6961
+ return !!attr.decl.ref?.attributes.some((attr2) => attr2.decl.$refText === "@@@validation");
6962
+ }
6704
6963
  validateArgs(funcDecl, args, accept) {
6705
6964
  let success = true;
6706
6965
  for (let i = 0; i < funcDecl.params.length; i++) {
@@ -6761,6 +7020,51 @@ var FunctionInvocationValidator = class {
6761
7020
  }
6762
7021
  return true;
6763
7022
  }
7023
+ _checkAuth(expr, accept) {
7024
+ if (!expr.$resolvedType) {
7025
+ accept("error", 'cannot resolve `auth()` - make sure you have a model or type with `@auth` attribute or named "User"', {
7026
+ node: expr
7027
+ });
7028
+ }
7029
+ }
7030
+ _checkLength(expr, accept) {
7031
+ const msg = "argument must be a string or list field";
7032
+ const fieldArg = expr.args[0].value;
7033
+ if (!isDataFieldReference(fieldArg)) {
7034
+ accept("error", msg, {
7035
+ node: expr.args[0]
7036
+ });
7037
+ return;
7038
+ }
7039
+ if (isDataModel(fieldArg.$resolvedType?.decl)) {
7040
+ accept("error", msg, {
7041
+ node: expr.args[0]
7042
+ });
7043
+ return;
7044
+ }
7045
+ if (!fieldArg.$resolvedType?.array && fieldArg.$resolvedType?.decl !== "String") {
7046
+ accept("error", msg, {
7047
+ node: expr.args[0]
7048
+ });
7049
+ }
7050
+ }
7051
+ _checkRegex(expr, accept) {
7052
+ const regex = expr.args[1]?.value;
7053
+ if (!isStringLiteral(regex)) {
7054
+ accept("error", "second argument must be a string literal", {
7055
+ node: expr.args[1]
7056
+ });
7057
+ return;
7058
+ }
7059
+ try {
7060
+ new RegExp(regex.value);
7061
+ } catch (e) {
7062
+ accept("error", "invalid regular expression: " + e.message, {
7063
+ node: expr.args[1]
7064
+ });
7065
+ }
7066
+ }
7067
+ // TODO: move this to policy plugin
6764
7068
  _checkCheck(expr, accept) {
6765
7069
  let valid = true;
6766
7070
  const fieldArg = expr.args[0].value;
@@ -6832,6 +7136,33 @@ var FunctionInvocationValidator = class {
6832
7136
  }
6833
7137
  }
6834
7138
  };
7139
+ _ts_decorate2([
7140
+ func("auth"),
7141
+ _ts_metadata2("design:type", Function),
7142
+ _ts_metadata2("design:paramtypes", [
7143
+ typeof InvocationExpr === "undefined" ? Object : InvocationExpr,
7144
+ typeof ValidationAcceptor === "undefined" ? Object : ValidationAcceptor
7145
+ ]),
7146
+ _ts_metadata2("design:returntype", void 0)
7147
+ ], FunctionInvocationValidator.prototype, "_checkAuth", null);
7148
+ _ts_decorate2([
7149
+ func("length"),
7150
+ _ts_metadata2("design:type", Function),
7151
+ _ts_metadata2("design:paramtypes", [
7152
+ typeof InvocationExpr === "undefined" ? Object : InvocationExpr,
7153
+ typeof ValidationAcceptor === "undefined" ? Object : ValidationAcceptor
7154
+ ]),
7155
+ _ts_metadata2("design:returntype", void 0)
7156
+ ], FunctionInvocationValidator.prototype, "_checkLength", null);
7157
+ _ts_decorate2([
7158
+ func("regex"),
7159
+ _ts_metadata2("design:type", Function),
7160
+ _ts_metadata2("design:paramtypes", [
7161
+ typeof InvocationExpr === "undefined" ? Object : InvocationExpr,
7162
+ typeof ValidationAcceptor === "undefined" ? Object : ValidationAcceptor
7163
+ ]),
7164
+ _ts_metadata2("design:returntype", void 0)
7165
+ ], FunctionInvocationValidator.prototype, "_checkRegex", null);
6835
7166
  _ts_decorate2([
6836
7167
  func("check"),
6837
7168
  _ts_metadata2("design:type", Function),
@@ -6922,6 +7253,7 @@ function registerValidationChecks(services) {
6922
7253
  const checks = {
6923
7254
  Model: validator.checkModel,
6924
7255
  DataSource: validator.checkDataSource,
7256
+ GeneratorDecl: validator.checkGenerator,
6925
7257
  DataModel: validator.checkDataModel,
6926
7258
  TypeDef: validator.checkTypeDef,
6927
7259
  Enum: validator.checkEnum,
@@ -6941,50 +7273,1044 @@ var ZModelValidator = class {
6941
7273
  constructor(services) {
6942
7274
  this.services = services;
6943
7275
  }
6944
- shouldCheck(node) {
6945
- let doc;
6946
- let currNode = node;
6947
- while (currNode) {
6948
- if (currNode.$document) {
6949
- doc = currNode.$document;
6950
- break;
6951
- }
6952
- currNode = currNode.$container;
6953
- }
6954
- return doc?.parseResult.lexerErrors.length === 0 && doc?.parseResult.parserErrors.length === 0;
6955
- }
6956
7276
  checkModel(node, accept) {
6957
- this.shouldCheck(node) && new SchemaValidator(this.services.shared.workspace.LangiumDocuments).validate(node, accept);
7277
+ new SchemaValidator(this.services.shared.workspace.LangiumDocuments).validate(node, accept);
6958
7278
  }
6959
7279
  checkDataSource(node, accept) {
6960
- this.shouldCheck(node) && new DataSourceValidator().validate(node, accept);
7280
+ new DataSourceValidator().validate(node, accept);
7281
+ }
7282
+ checkGenerator(node, accept) {
7283
+ accept("warning", '"generator" is not used by ZenStack and should be removed.', {
7284
+ node
7285
+ });
6961
7286
  }
6962
7287
  checkDataModel(node, accept) {
6963
- this.shouldCheck(node) && new DataModelValidator().validate(node, accept);
7288
+ new DataModelValidator().validate(node, accept);
6964
7289
  }
6965
7290
  checkTypeDef(node, accept) {
6966
- this.shouldCheck(node) && new TypeDefValidator().validate(node, accept);
7291
+ new TypeDefValidator().validate(node, accept);
6967
7292
  }
6968
7293
  checkEnum(node, accept) {
6969
- this.shouldCheck(node) && new EnumValidator().validate(node, accept);
7294
+ new EnumValidator().validate(node, accept);
6970
7295
  }
6971
7296
  checkAttribute(node, accept) {
6972
- this.shouldCheck(node) && new AttributeValidator().validate(node, accept);
7297
+ new AttributeValidator().validate(node, accept);
6973
7298
  }
6974
7299
  checkExpression(node, accept) {
6975
- this.shouldCheck(node) && new ExpressionValidator().validate(node, accept);
7300
+ new ExpressionValidator().validate(node, accept);
6976
7301
  }
6977
7302
  checkFunctionInvocation(node, accept) {
6978
- this.shouldCheck(node) && new FunctionInvocationValidator().validate(node, accept);
7303
+ new FunctionInvocationValidator().validate(node, accept);
6979
7304
  }
6980
7305
  checkFunctionDecl(node, accept) {
6981
- this.shouldCheck(node) && new FunctionDeclValidator().validate(node, accept);
7306
+ new FunctionDeclValidator().validate(node, accept);
6982
7307
  }
6983
7308
  };
6984
7309
 
6985
- // src/zmodel-linker.ts
6986
- import { AstUtils as AstUtils6, Cancellation, DefaultLinker, DocumentState, interruptAndCheck, isReference } from "langium";
7310
+ // src/zmodel-comment-provider.ts
7311
+ import { DefaultCommentProvider } from "langium";
6987
7312
  import { match as match2 } from "ts-pattern";
7313
+ var ZModelCommentProvider = class extends DefaultCommentProvider {
7314
+ static {
7315
+ __name(this, "ZModelCommentProvider");
7316
+ }
7317
+ getComment(node) {
7318
+ let comment = super.getComment(node);
7319
+ if (!comment) {
7320
+ comment = match2(node).when(isDataModel, (d) => `/**
7321
+ * Model *${d.name}*
7322
+ */`).when(isTypeDef, (d) => `/**
7323
+ * Type *${d.name}*
7324
+ */`).when(isEnum, (e) => `/**
7325
+ * Enum *${e.name}*
7326
+ */`).when(isEnumField, (f) => `/**
7327
+ * Value of enum *${f.$container?.name}*
7328
+ */`).when(isDataField, (f) => `/**
7329
+ * Field of *${f.$container?.name}*
7330
+ */`).when(isFunctionDecl, (f) => `/**
7331
+ * Function *${f.name}*
7332
+ */`).otherwise(() => "");
7333
+ }
7334
+ return comment;
7335
+ }
7336
+ };
7337
+
7338
+ // src/zmodel-completion-provider.ts
7339
+ import { DefaultCompletionProvider } from "langium/lsp";
7340
+ import fs2 from "fs";
7341
+ import { P as P2, match as match3 } from "ts-pattern";
7342
+ import { CompletionItemKind } from "vscode-languageserver";
7343
+
7344
+ // src/zmodel-code-generator.ts
7345
+ function _ts_decorate3(decorators, target, key, desc) {
7346
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
7347
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
7348
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
7349
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
7350
+ }
7351
+ __name(_ts_decorate3, "_ts_decorate");
7352
+ function _ts_metadata3(k, v) {
7353
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
7354
+ }
7355
+ __name(_ts_metadata3, "_ts_metadata");
7356
+ var generationHandlers = /* @__PURE__ */ new Map();
7357
+ function gen(name) {
7358
+ return function(_target, _propertyKey, descriptor) {
7359
+ if (!generationHandlers.get(name)) {
7360
+ generationHandlers.set(name, descriptor);
7361
+ }
7362
+ return descriptor;
7363
+ };
7364
+ }
7365
+ __name(gen, "gen");
7366
+ var ZModelCodeGenerator = class {
7367
+ static {
7368
+ __name(this, "ZModelCodeGenerator");
7369
+ }
7370
+ options;
7371
+ constructor(options) {
7372
+ this.options = {
7373
+ binaryExprNumberOfSpaces: options?.binaryExprNumberOfSpaces ?? 1,
7374
+ unaryExprNumberOfSpaces: options?.unaryExprNumberOfSpaces ?? 0,
7375
+ indent: options?.indent ?? 4,
7376
+ quote: options?.quote ?? "single"
7377
+ };
7378
+ }
7379
+ /**
7380
+ * Generates ZModel source code from AST.
7381
+ */
7382
+ generate(ast) {
7383
+ const handler = generationHandlers.get(ast.$type);
7384
+ if (!handler) {
7385
+ throw new Error(`No generation handler found for ${ast.$type}`);
7386
+ }
7387
+ return handler.value.call(this, ast);
7388
+ }
7389
+ _generateModel(ast) {
7390
+ return ast.declarations.map((d) => this.generate(d)).join("\n\n");
7391
+ }
7392
+ _generateDataSource(ast) {
7393
+ return `datasource ${ast.name} {
7394
+ ${ast.fields.map((x) => this.indent + this.generate(x)).join("\n")}
7395
+ }`;
7396
+ }
7397
+ _generateEnum(ast) {
7398
+ return `enum ${ast.name} {
7399
+ ${ast.fields.map((x) => this.indent + this.generate(x)).join("\n")}
7400
+ }`;
7401
+ }
7402
+ _generateEnumField(ast) {
7403
+ return `${ast.name}${ast.attributes.length > 0 ? " " + ast.attributes.map((x) => this.generate(x)).join(" ") : ""}`;
7404
+ }
7405
+ _generateGenerator(ast) {
7406
+ return `generator ${ast.name} {
7407
+ ${ast.fields.map((x) => this.indent + this.generate(x)).join("\n")}
7408
+ }`;
7409
+ }
7410
+ _generateConfigField(ast) {
7411
+ return `${ast.name} = ${this.generate(ast.value)}`;
7412
+ }
7413
+ _generateConfigArrayExpr(ast) {
7414
+ return `[${ast.items.map((x) => this.generate(x)).join(", ")}]`;
7415
+ }
7416
+ _generateConfigInvocationExpr(ast) {
7417
+ if (ast.args.length === 0) {
7418
+ return ast.name;
7419
+ } else {
7420
+ return `${ast.name}(${ast.args.map((x) => (x.name ? x.name + ": " : "") + this.generate(x.value)).join(", ")})`;
7421
+ }
7422
+ }
7423
+ _generatePlugin(ast) {
7424
+ return `plugin ${ast.name} {
7425
+ ${ast.fields.map((x) => this.indent + this.generate(x)).join("\n")}
7426
+ }`;
7427
+ }
7428
+ _generatePluginField(ast) {
7429
+ return `${ast.name} = ${this.generate(ast.value)}`;
7430
+ }
7431
+ _generateDataModel(ast) {
7432
+ return `${ast.isView ? "view" : "model"} ${ast.name}${ast.mixins.length > 0 ? " mixes " + ast.mixins.map((x) => x.$refText).join(", ") : ""} {
7433
+ ${ast.fields.map((x) => this.indent + this.generate(x)).join("\n")}${ast.attributes.length > 0 ? "\n\n" + ast.attributes.map((x) => this.indent + this.generate(x)).join("\n") : ""}
7434
+ }`;
7435
+ }
7436
+ _generateDataField(ast) {
7437
+ return `${ast.name} ${this.fieldType(ast.type)}${ast.attributes.length > 0 ? " " + ast.attributes.map((x) => this.generate(x)).join(" ") : ""}`;
7438
+ }
7439
+ fieldType(type) {
7440
+ const baseType = type.type ? type.type : type.$type == "DataFieldType" && type.unsupported ? "Unsupported(" + this.generate(type.unsupported.value) + ")" : type.reference?.$refText;
7441
+ return `${baseType}${type.array ? "[]" : ""}${type.optional ? "?" : ""}`;
7442
+ }
7443
+ _generateDataModelAttribute(ast) {
7444
+ return this.attribute(ast);
7445
+ }
7446
+ _generateDataFieldAttribute(ast) {
7447
+ return this.attribute(ast);
7448
+ }
7449
+ attribute(ast) {
7450
+ const args = ast.args.length ? `(${ast.args.map((x) => this.generate(x)).join(", ")})` : "";
7451
+ return `${ast.decl.$refText}${args}`;
7452
+ }
7453
+ _generateAttributeArg(ast) {
7454
+ if (ast.name) {
7455
+ return `${ast.name}: ${this.generate(ast.value)}`;
7456
+ } else {
7457
+ return this.generate(ast.value);
7458
+ }
7459
+ }
7460
+ _generateObjectExpr(ast) {
7461
+ return `{ ${ast.fields.map((field) => this.objectField(field)).join(", ")} }`;
7462
+ }
7463
+ objectField(field) {
7464
+ return `${field.name}: ${this.generate(field.value)}`;
7465
+ }
7466
+ _generateArrayExpr(ast) {
7467
+ return `[${ast.items.map((item) => this.generate(item)).join(", ")}]`;
7468
+ }
7469
+ _generateLiteralExpr(ast) {
7470
+ return this.options.quote === "single" ? `'${ast.value}'` : `"${ast.value}"`;
7471
+ }
7472
+ _generateNumberLiteral(ast) {
7473
+ return ast.value.toString();
7474
+ }
7475
+ _generateBooleanLiteral(ast) {
7476
+ return ast.value.toString();
7477
+ }
7478
+ _generateUnaryExpr(ast) {
7479
+ return `${ast.operator}${this.unaryExprSpace}${this.generate(ast.operand)}`;
7480
+ }
7481
+ _generateBinaryExpr(ast) {
7482
+ const operator = ast.operator;
7483
+ const isCollectionPredicate2 = this.isCollectionPredicateOperator(operator);
7484
+ const rightExpr = this.generate(ast.right);
7485
+ const { left: isLeftParenthesis, right: isRightParenthesis } = this.isParenthesesNeededForBinaryExpr(ast);
7486
+ return `${isLeftParenthesis ? "(" : ""}${this.generate(ast.left)}${isLeftParenthesis ? ")" : ""}${isCollectionPredicate2 ? "" : this.binaryExprSpace}${operator}${isCollectionPredicate2 ? "" : this.binaryExprSpace}${isRightParenthesis ? "(" : ""}${isCollectionPredicate2 ? `[${rightExpr}]` : rightExpr}${isRightParenthesis ? ")" : ""}`;
7487
+ }
7488
+ _generateReferenceExpr(ast) {
7489
+ const args = ast.args.length ? `(${ast.args.map((x) => this.generate(x)).join(", ")})` : "";
7490
+ return `${ast.target.$refText}${args}`;
7491
+ }
7492
+ _generateReferenceArg(ast) {
7493
+ return `${ast.name}:${this.generate(ast.value)}`;
7494
+ }
7495
+ _generateMemberExpr(ast) {
7496
+ return `${this.generate(ast.operand)}.${ast.member.$refText}`;
7497
+ }
7498
+ _generateInvocationExpr(ast) {
7499
+ return `${ast.function.$refText}(${ast.args.map((x) => this.argument(x)).join(", ")})`;
7500
+ }
7501
+ _generateNullExpr() {
7502
+ return "null";
7503
+ }
7504
+ _generateThisExpr() {
7505
+ return "this";
7506
+ }
7507
+ _generateAttribute(ast) {
7508
+ return `attribute ${ast.name}(${ast.params.map((x) => this.generate(x)).join(", ")})`;
7509
+ }
7510
+ _generateAttributeParam(ast) {
7511
+ return `${ast.default ? "_ " : ""}${ast.name}: ${this.generate(ast.type)}`;
7512
+ }
7513
+ _generateAttributeParamType(ast) {
7514
+ return `${ast.type ?? ast.reference?.$refText}${ast.array ? "[]" : ""}${ast.optional ? "?" : ""}`;
7515
+ }
7516
+ _generateFunctionDecl(ast) {
7517
+ return `function ${ast.name}(${ast.params.map((x) => this.generate(x)).join(", ")}) ${ast.returnType ? ": " + this.generate(ast.returnType) : ""} {}`;
7518
+ }
7519
+ _generateFunctionParam(ast) {
7520
+ return `${ast.name}: ${this.generate(ast.type)}`;
7521
+ }
7522
+ _generateFunctionParamType(ast) {
7523
+ return `${ast.type ?? ast.reference?.$refText}${ast.array ? "[]" : ""}`;
7524
+ }
7525
+ _generateTypeDef(ast) {
7526
+ return `type ${ast.name} {
7527
+ ${ast.fields.map((x) => this.indent + this.generate(x)).join("\n")}${ast.attributes.length > 0 ? "\n\n" + ast.attributes.map((x) => this.indent + this.generate(x)).join("\n") : ""}
7528
+ }`;
7529
+ }
7530
+ argument(ast) {
7531
+ return this.generate(ast.value);
7532
+ }
7533
+ get binaryExprSpace() {
7534
+ return " ".repeat(this.options.binaryExprNumberOfSpaces);
7535
+ }
7536
+ get unaryExprSpace() {
7537
+ return " ".repeat(this.options.unaryExprNumberOfSpaces);
7538
+ }
7539
+ get indent() {
7540
+ return " ".repeat(this.options.indent);
7541
+ }
7542
+ isParenthesesNeededForBinaryExpr(ast) {
7543
+ const result = {
7544
+ left: false,
7545
+ right: false
7546
+ };
7547
+ const operator = ast.operator;
7548
+ const isCollectionPredicate2 = this.isCollectionPredicateOperator(operator);
7549
+ const currentPriority = BinaryExprOperatorPriority[operator];
7550
+ if (ast.left.$type === BinaryExpr && BinaryExprOperatorPriority[ast.left["operator"]] < currentPriority) {
7551
+ result.left = true;
7552
+ }
7553
+ if (!isCollectionPredicate2 && ast.right.$type === BinaryExpr && BinaryExprOperatorPriority[ast.right["operator"]] <= currentPriority) {
7554
+ result.right = true;
7555
+ }
7556
+ return result;
7557
+ }
7558
+ isCollectionPredicateOperator(op) {
7559
+ return [
7560
+ "?",
7561
+ "!",
7562
+ "^"
7563
+ ].includes(op);
7564
+ }
7565
+ };
7566
+ _ts_decorate3([
7567
+ gen(Model),
7568
+ _ts_metadata3("design:type", Function),
7569
+ _ts_metadata3("design:paramtypes", [
7570
+ typeof Model === "undefined" ? Object : Model
7571
+ ]),
7572
+ _ts_metadata3("design:returntype", void 0)
7573
+ ], ZModelCodeGenerator.prototype, "_generateModel", null);
7574
+ _ts_decorate3([
7575
+ gen(DataSource),
7576
+ _ts_metadata3("design:type", Function),
7577
+ _ts_metadata3("design:paramtypes", [
7578
+ typeof DataSource === "undefined" ? Object : DataSource
7579
+ ]),
7580
+ _ts_metadata3("design:returntype", void 0)
7581
+ ], ZModelCodeGenerator.prototype, "_generateDataSource", null);
7582
+ _ts_decorate3([
7583
+ gen(Enum),
7584
+ _ts_metadata3("design:type", Function),
7585
+ _ts_metadata3("design:paramtypes", [
7586
+ typeof Enum === "undefined" ? Object : Enum
7587
+ ]),
7588
+ _ts_metadata3("design:returntype", void 0)
7589
+ ], ZModelCodeGenerator.prototype, "_generateEnum", null);
7590
+ _ts_decorate3([
7591
+ gen(EnumField),
7592
+ _ts_metadata3("design:type", Function),
7593
+ _ts_metadata3("design:paramtypes", [
7594
+ typeof EnumField === "undefined" ? Object : EnumField
7595
+ ]),
7596
+ _ts_metadata3("design:returntype", void 0)
7597
+ ], ZModelCodeGenerator.prototype, "_generateEnumField", null);
7598
+ _ts_decorate3([
7599
+ gen(GeneratorDecl),
7600
+ _ts_metadata3("design:type", Function),
7601
+ _ts_metadata3("design:paramtypes", [
7602
+ typeof GeneratorDecl === "undefined" ? Object : GeneratorDecl
7603
+ ]),
7604
+ _ts_metadata3("design:returntype", void 0)
7605
+ ], ZModelCodeGenerator.prototype, "_generateGenerator", null);
7606
+ _ts_decorate3([
7607
+ gen(ConfigField),
7608
+ _ts_metadata3("design:type", Function),
7609
+ _ts_metadata3("design:paramtypes", [
7610
+ typeof ConfigField === "undefined" ? Object : ConfigField
7611
+ ]),
7612
+ _ts_metadata3("design:returntype", void 0)
7613
+ ], ZModelCodeGenerator.prototype, "_generateConfigField", null);
7614
+ _ts_decorate3([
7615
+ gen(ConfigArrayExpr),
7616
+ _ts_metadata3("design:type", Function),
7617
+ _ts_metadata3("design:paramtypes", [
7618
+ typeof ConfigArrayExpr === "undefined" ? Object : ConfigArrayExpr
7619
+ ]),
7620
+ _ts_metadata3("design:returntype", void 0)
7621
+ ], ZModelCodeGenerator.prototype, "_generateConfigArrayExpr", null);
7622
+ _ts_decorate3([
7623
+ gen(ConfigInvocationExpr),
7624
+ _ts_metadata3("design:type", Function),
7625
+ _ts_metadata3("design:paramtypes", [
7626
+ typeof ConfigInvocationExpr === "undefined" ? Object : ConfigInvocationExpr
7627
+ ]),
7628
+ _ts_metadata3("design:returntype", void 0)
7629
+ ], ZModelCodeGenerator.prototype, "_generateConfigInvocationExpr", null);
7630
+ _ts_decorate3([
7631
+ gen(Plugin),
7632
+ _ts_metadata3("design:type", Function),
7633
+ _ts_metadata3("design:paramtypes", [
7634
+ typeof Plugin === "undefined" ? Object : Plugin
7635
+ ]),
7636
+ _ts_metadata3("design:returntype", void 0)
7637
+ ], ZModelCodeGenerator.prototype, "_generatePlugin", null);
7638
+ _ts_decorate3([
7639
+ gen(PluginField),
7640
+ _ts_metadata3("design:type", Function),
7641
+ _ts_metadata3("design:paramtypes", [
7642
+ typeof PluginField === "undefined" ? Object : PluginField
7643
+ ]),
7644
+ _ts_metadata3("design:returntype", void 0)
7645
+ ], ZModelCodeGenerator.prototype, "_generatePluginField", null);
7646
+ _ts_decorate3([
7647
+ gen(DataModel),
7648
+ _ts_metadata3("design:type", Function),
7649
+ _ts_metadata3("design:paramtypes", [
7650
+ typeof DataModel === "undefined" ? Object : DataModel
7651
+ ]),
7652
+ _ts_metadata3("design:returntype", void 0)
7653
+ ], ZModelCodeGenerator.prototype, "_generateDataModel", null);
7654
+ _ts_decorate3([
7655
+ gen(DataField),
7656
+ _ts_metadata3("design:type", Function),
7657
+ _ts_metadata3("design:paramtypes", [
7658
+ typeof DataField === "undefined" ? Object : DataField
7659
+ ]),
7660
+ _ts_metadata3("design:returntype", void 0)
7661
+ ], ZModelCodeGenerator.prototype, "_generateDataField", null);
7662
+ _ts_decorate3([
7663
+ gen(DataModelAttribute),
7664
+ _ts_metadata3("design:type", Function),
7665
+ _ts_metadata3("design:paramtypes", [
7666
+ typeof DataModelAttribute === "undefined" ? Object : DataModelAttribute
7667
+ ]),
7668
+ _ts_metadata3("design:returntype", void 0)
7669
+ ], ZModelCodeGenerator.prototype, "_generateDataModelAttribute", null);
7670
+ _ts_decorate3([
7671
+ gen(DataFieldAttribute),
7672
+ _ts_metadata3("design:type", Function),
7673
+ _ts_metadata3("design:paramtypes", [
7674
+ typeof DataFieldAttribute === "undefined" ? Object : DataFieldAttribute
7675
+ ]),
7676
+ _ts_metadata3("design:returntype", void 0)
7677
+ ], ZModelCodeGenerator.prototype, "_generateDataFieldAttribute", null);
7678
+ _ts_decorate3([
7679
+ gen(AttributeArg),
7680
+ _ts_metadata3("design:type", Function),
7681
+ _ts_metadata3("design:paramtypes", [
7682
+ typeof AttributeArg === "undefined" ? Object : AttributeArg
7683
+ ]),
7684
+ _ts_metadata3("design:returntype", void 0)
7685
+ ], ZModelCodeGenerator.prototype, "_generateAttributeArg", null);
7686
+ _ts_decorate3([
7687
+ gen(ObjectExpr),
7688
+ _ts_metadata3("design:type", Function),
7689
+ _ts_metadata3("design:paramtypes", [
7690
+ typeof ObjectExpr === "undefined" ? Object : ObjectExpr
7691
+ ]),
7692
+ _ts_metadata3("design:returntype", void 0)
7693
+ ], ZModelCodeGenerator.prototype, "_generateObjectExpr", null);
7694
+ _ts_decorate3([
7695
+ gen(ArrayExpr),
7696
+ _ts_metadata3("design:type", Function),
7697
+ _ts_metadata3("design:paramtypes", [
7698
+ typeof ArrayExpr === "undefined" ? Object : ArrayExpr
7699
+ ]),
7700
+ _ts_metadata3("design:returntype", void 0)
7701
+ ], ZModelCodeGenerator.prototype, "_generateArrayExpr", null);
7702
+ _ts_decorate3([
7703
+ gen(StringLiteral),
7704
+ _ts_metadata3("design:type", Function),
7705
+ _ts_metadata3("design:paramtypes", [
7706
+ typeof LiteralExpr === "undefined" ? Object : LiteralExpr
7707
+ ]),
7708
+ _ts_metadata3("design:returntype", void 0)
7709
+ ], ZModelCodeGenerator.prototype, "_generateLiteralExpr", null);
7710
+ _ts_decorate3([
7711
+ gen(NumberLiteral),
7712
+ _ts_metadata3("design:type", Function),
7713
+ _ts_metadata3("design:paramtypes", [
7714
+ typeof NumberLiteral === "undefined" ? Object : NumberLiteral
7715
+ ]),
7716
+ _ts_metadata3("design:returntype", void 0)
7717
+ ], ZModelCodeGenerator.prototype, "_generateNumberLiteral", null);
7718
+ _ts_decorate3([
7719
+ gen(BooleanLiteral),
7720
+ _ts_metadata3("design:type", Function),
7721
+ _ts_metadata3("design:paramtypes", [
7722
+ typeof BooleanLiteral === "undefined" ? Object : BooleanLiteral
7723
+ ]),
7724
+ _ts_metadata3("design:returntype", void 0)
7725
+ ], ZModelCodeGenerator.prototype, "_generateBooleanLiteral", null);
7726
+ _ts_decorate3([
7727
+ gen(UnaryExpr),
7728
+ _ts_metadata3("design:type", Function),
7729
+ _ts_metadata3("design:paramtypes", [
7730
+ typeof UnaryExpr === "undefined" ? Object : UnaryExpr
7731
+ ]),
7732
+ _ts_metadata3("design:returntype", void 0)
7733
+ ], ZModelCodeGenerator.prototype, "_generateUnaryExpr", null);
7734
+ _ts_decorate3([
7735
+ gen(BinaryExpr),
7736
+ _ts_metadata3("design:type", Function),
7737
+ _ts_metadata3("design:paramtypes", [
7738
+ typeof BinaryExpr === "undefined" ? Object : BinaryExpr
7739
+ ]),
7740
+ _ts_metadata3("design:returntype", void 0)
7741
+ ], ZModelCodeGenerator.prototype, "_generateBinaryExpr", null);
7742
+ _ts_decorate3([
7743
+ gen(ReferenceExpr),
7744
+ _ts_metadata3("design:type", Function),
7745
+ _ts_metadata3("design:paramtypes", [
7746
+ typeof ReferenceExpr === "undefined" ? Object : ReferenceExpr
7747
+ ]),
7748
+ _ts_metadata3("design:returntype", void 0)
7749
+ ], ZModelCodeGenerator.prototype, "_generateReferenceExpr", null);
7750
+ _ts_decorate3([
7751
+ gen(ReferenceArg),
7752
+ _ts_metadata3("design:type", Function),
7753
+ _ts_metadata3("design:paramtypes", [
7754
+ typeof ReferenceArg === "undefined" ? Object : ReferenceArg
7755
+ ]),
7756
+ _ts_metadata3("design:returntype", void 0)
7757
+ ], ZModelCodeGenerator.prototype, "_generateReferenceArg", null);
7758
+ _ts_decorate3([
7759
+ gen(MemberAccessExpr),
7760
+ _ts_metadata3("design:type", Function),
7761
+ _ts_metadata3("design:paramtypes", [
7762
+ typeof MemberAccessExpr === "undefined" ? Object : MemberAccessExpr
7763
+ ]),
7764
+ _ts_metadata3("design:returntype", void 0)
7765
+ ], ZModelCodeGenerator.prototype, "_generateMemberExpr", null);
7766
+ _ts_decorate3([
7767
+ gen(InvocationExpr),
7768
+ _ts_metadata3("design:type", Function),
7769
+ _ts_metadata3("design:paramtypes", [
7770
+ typeof InvocationExpr === "undefined" ? Object : InvocationExpr
7771
+ ]),
7772
+ _ts_metadata3("design:returntype", void 0)
7773
+ ], ZModelCodeGenerator.prototype, "_generateInvocationExpr", null);
7774
+ _ts_decorate3([
7775
+ gen(NullExpr),
7776
+ _ts_metadata3("design:type", Function),
7777
+ _ts_metadata3("design:paramtypes", []),
7778
+ _ts_metadata3("design:returntype", void 0)
7779
+ ], ZModelCodeGenerator.prototype, "_generateNullExpr", null);
7780
+ _ts_decorate3([
7781
+ gen(ThisExpr),
7782
+ _ts_metadata3("design:type", Function),
7783
+ _ts_metadata3("design:paramtypes", []),
7784
+ _ts_metadata3("design:returntype", void 0)
7785
+ ], ZModelCodeGenerator.prototype, "_generateThisExpr", null);
7786
+ _ts_decorate3([
7787
+ gen(Attribute),
7788
+ _ts_metadata3("design:type", Function),
7789
+ _ts_metadata3("design:paramtypes", [
7790
+ typeof Attribute === "undefined" ? Object : Attribute
7791
+ ]),
7792
+ _ts_metadata3("design:returntype", void 0)
7793
+ ], ZModelCodeGenerator.prototype, "_generateAttribute", null);
7794
+ _ts_decorate3([
7795
+ gen(AttributeParam),
7796
+ _ts_metadata3("design:type", Function),
7797
+ _ts_metadata3("design:paramtypes", [
7798
+ typeof AttributeParam === "undefined" ? Object : AttributeParam
7799
+ ]),
7800
+ _ts_metadata3("design:returntype", void 0)
7801
+ ], ZModelCodeGenerator.prototype, "_generateAttributeParam", null);
7802
+ _ts_decorate3([
7803
+ gen(AttributeParamType),
7804
+ _ts_metadata3("design:type", Function),
7805
+ _ts_metadata3("design:paramtypes", [
7806
+ typeof AttributeParamType === "undefined" ? Object : AttributeParamType
7807
+ ]),
7808
+ _ts_metadata3("design:returntype", void 0)
7809
+ ], ZModelCodeGenerator.prototype, "_generateAttributeParamType", null);
7810
+ _ts_decorate3([
7811
+ gen(FunctionDecl),
7812
+ _ts_metadata3("design:type", Function),
7813
+ _ts_metadata3("design:paramtypes", [
7814
+ typeof FunctionDecl === "undefined" ? Object : FunctionDecl
7815
+ ]),
7816
+ _ts_metadata3("design:returntype", void 0)
7817
+ ], ZModelCodeGenerator.prototype, "_generateFunctionDecl", null);
7818
+ _ts_decorate3([
7819
+ gen(FunctionParam),
7820
+ _ts_metadata3("design:type", Function),
7821
+ _ts_metadata3("design:paramtypes", [
7822
+ typeof FunctionParam === "undefined" ? Object : FunctionParam
7823
+ ]),
7824
+ _ts_metadata3("design:returntype", void 0)
7825
+ ], ZModelCodeGenerator.prototype, "_generateFunctionParam", null);
7826
+ _ts_decorate3([
7827
+ gen(FunctionParamType),
7828
+ _ts_metadata3("design:type", Function),
7829
+ _ts_metadata3("design:paramtypes", [
7830
+ typeof FunctionParamType === "undefined" ? Object : FunctionParamType
7831
+ ]),
7832
+ _ts_metadata3("design:returntype", void 0)
7833
+ ], ZModelCodeGenerator.prototype, "_generateFunctionParamType", null);
7834
+ _ts_decorate3([
7835
+ gen(TypeDef),
7836
+ _ts_metadata3("design:type", Function),
7837
+ _ts_metadata3("design:paramtypes", [
7838
+ typeof TypeDef === "undefined" ? Object : TypeDef
7839
+ ]),
7840
+ _ts_metadata3("design:returntype", void 0)
7841
+ ], ZModelCodeGenerator.prototype, "_generateTypeDef", null);
7842
+
7843
+ // src/zmodel-completion-provider.ts
7844
+ var ZModelCompletionProvider = class extends DefaultCompletionProvider {
7845
+ static {
7846
+ __name(this, "ZModelCompletionProvider");
7847
+ }
7848
+ services;
7849
+ constructor(services) {
7850
+ super(services), this.services = services;
7851
+ }
7852
+ completionOptions = {
7853
+ triggerCharacters: [
7854
+ "@",
7855
+ "(",
7856
+ ",",
7857
+ "."
7858
+ ]
7859
+ };
7860
+ async getCompletion(document, params) {
7861
+ try {
7862
+ return await super.getCompletion(document, params);
7863
+ } catch (e) {
7864
+ console.error("Completion error:", e.message);
7865
+ return void 0;
7866
+ }
7867
+ }
7868
+ completionFor(context, next, acceptor) {
7869
+ if (isDataModelAttribute(context.node) || isDataFieldAttribute(context.node)) {
7870
+ const completions = this.getCompletionFromHint(context.node);
7871
+ if (completions) {
7872
+ completions.forEach((c) => acceptor(context, c));
7873
+ return;
7874
+ }
7875
+ }
7876
+ return super.completionFor(context, next, acceptor);
7877
+ }
7878
+ getCompletionFromHint(contextNode) {
7879
+ const unfilledParams = this.getUnfilledAttributeParams(contextNode);
7880
+ const nextParam = unfilledParams[0];
7881
+ if (!nextParam) {
7882
+ return void 0;
7883
+ }
7884
+ const hintAttr = getAttribute(nextParam, "@@@completionHint");
7885
+ if (hintAttr) {
7886
+ const hint = hintAttr.args[0];
7887
+ if (hint?.value) {
7888
+ if (isArrayExpr(hint.value)) {
7889
+ return hint.value.items.map((item) => {
7890
+ return {
7891
+ label: `${item.value}`,
7892
+ kind: CompletionItemKind.Value,
7893
+ detail: "Parameter",
7894
+ sortText: "0"
7895
+ };
7896
+ });
7897
+ }
7898
+ }
7899
+ }
7900
+ return void 0;
7901
+ }
7902
+ // TODO: this doesn't work when the file contains parse errors
7903
+ getUnfilledAttributeParams(contextNode) {
7904
+ try {
7905
+ const params = contextNode.decl.ref?.params;
7906
+ if (params) {
7907
+ const args = contextNode.args;
7908
+ let unfilledParams = [
7909
+ ...params
7910
+ ];
7911
+ args.forEach((arg) => {
7912
+ if (arg.name) {
7913
+ unfilledParams = unfilledParams.filter((p) => p.name !== arg.name);
7914
+ } else {
7915
+ unfilledParams.shift();
7916
+ }
7917
+ });
7918
+ return unfilledParams;
7919
+ }
7920
+ } catch {
7921
+ }
7922
+ return [];
7923
+ }
7924
+ completionForCrossReference(context, crossRef, acceptor) {
7925
+ if (crossRef.property === "member" && !isMemberAccessExpr(context.node)) {
7926
+ return;
7927
+ }
7928
+ const customAcceptor = /* @__PURE__ */ __name((context2, item) => {
7929
+ if (item.insertText?.startsWith("@@@") || item.label?.startsWith("@@@")) {
7930
+ return;
7931
+ }
7932
+ if ("nodeDescription" in item) {
7933
+ const node = this.getAstNode(item.nodeDescription);
7934
+ if (!node) {
7935
+ return;
7936
+ }
7937
+ if ((isEnum(node) || isEnumField(node)) && isFromStdlib(node)) {
7938
+ return;
7939
+ }
7940
+ if ((isDataModelAttribute(context2.node) || isDataFieldAttribute(context2.node)) && !this.filterAttributeApplicationCompletion(context2.node, node)) {
7941
+ return;
7942
+ }
7943
+ }
7944
+ acceptor(context2, item);
7945
+ }, "customAcceptor");
7946
+ return super.completionForCrossReference(context, crossRef, customAcceptor);
7947
+ }
7948
+ completionForKeyword(context, keyword, acceptor) {
7949
+ const customAcceptor = /* @__PURE__ */ __name((context2, item) => {
7950
+ if (!this.filterKeywordForContext(context2, keyword.value)) {
7951
+ return;
7952
+ }
7953
+ acceptor(context2, item);
7954
+ }, "customAcceptor");
7955
+ return super.completionForKeyword(context, keyword, customAcceptor);
7956
+ }
7957
+ filterKeywordForContext(context, keyword) {
7958
+ if (isInvocationExpr(context.node)) {
7959
+ return [
7960
+ "true",
7961
+ "false",
7962
+ "null",
7963
+ "this"
7964
+ ].includes(keyword);
7965
+ } else if (isDataModelAttribute(context.node) || isDataFieldAttribute(context.node)) {
7966
+ const exprContext = this.getAttributeContextType(context.node);
7967
+ if (exprContext === "DefaultValue") {
7968
+ return [
7969
+ "true",
7970
+ "false",
7971
+ "null"
7972
+ ].includes(keyword);
7973
+ } else {
7974
+ return [
7975
+ "true",
7976
+ "false",
7977
+ "null",
7978
+ "this"
7979
+ ].includes(keyword);
7980
+ }
7981
+ } else {
7982
+ return true;
7983
+ }
7984
+ }
7985
+ filterAttributeApplicationCompletion(contextNode, node) {
7986
+ const attrContextType = this.getAttributeContextType(contextNode);
7987
+ if (isFunctionDecl(node) && attrContextType) {
7988
+ const funcExprContextAttr = getAttribute(node, "@@@expressionContext");
7989
+ if (funcExprContextAttr && funcExprContextAttr.args[0]) {
7990
+ const arg = funcExprContextAttr.args[0];
7991
+ if (isArrayExpr(arg.value)) {
7992
+ return arg.value.items.some((item) => isEnumFieldReference(item) && item.target.$refText === attrContextType);
7993
+ }
7994
+ }
7995
+ return false;
7996
+ }
7997
+ if (isDataField(node)) {
7998
+ return attrContextType !== "DefaultValue";
7999
+ }
8000
+ return true;
8001
+ }
8002
+ getAttributeContextType(node) {
8003
+ return match3(node.decl.$refText).with("@default", () => "DefaultValue").with(P2.union("@@allow", "@allow", "@@deny", "@deny"), () => "AccessPolicy").with("@@validate", () => "ValidationRule").otherwise(() => void 0);
8004
+ }
8005
+ createReferenceCompletionItem(nodeDescription) {
8006
+ const node = this.getAstNode(nodeDescription);
8007
+ const documentation = this.getNodeDocumentation(node);
8008
+ return match3(node).when(isDataModel, () => ({
8009
+ nodeDescription,
8010
+ kind: CompletionItemKind.Class,
8011
+ detail: "Model",
8012
+ sortText: "1",
8013
+ documentation
8014
+ })).when(isTypeDef, () => ({
8015
+ nodeDescription,
8016
+ kind: CompletionItemKind.Class,
8017
+ detail: "Type",
8018
+ sortText: "1",
8019
+ documentation
8020
+ })).when(isDataField, () => ({
8021
+ nodeDescription,
8022
+ kind: CompletionItemKind.Field,
8023
+ detail: "Field",
8024
+ sortText: "0",
8025
+ documentation
8026
+ })).when(isEnum, () => ({
8027
+ nodeDescription,
8028
+ kind: CompletionItemKind.Class,
8029
+ detail: "Enum",
8030
+ sortText: "1",
8031
+ documentation
8032
+ })).when(isEnumField, (d) => {
8033
+ const container = d.$container;
8034
+ return {
8035
+ nodeDescription,
8036
+ kind: CompletionItemKind.Enum,
8037
+ detail: `Value of enum "${container.name}"`,
8038
+ sortText: "1",
8039
+ documentation
8040
+ };
8041
+ }).when(isFunctionDecl, () => ({
8042
+ nodeDescription,
8043
+ insertText: this.getFunctionInsertText(nodeDescription),
8044
+ kind: CompletionItemKind.Function,
8045
+ detail: "Function",
8046
+ sortText: "1",
8047
+ documentation
8048
+ })).when(isAttribute, () => ({
8049
+ nodeDescription,
8050
+ insertText: this.getAttributeInsertText(nodeDescription),
8051
+ kind: CompletionItemKind.Property,
8052
+ detail: "Attribute",
8053
+ sortText: "1",
8054
+ documentation
8055
+ })).otherwise(() => ({
8056
+ nodeDescription,
8057
+ kind: CompletionItemKind.Reference,
8058
+ detail: nodeDescription.type,
8059
+ sortText: "2",
8060
+ documentation
8061
+ }));
8062
+ }
8063
+ getFunctionInsertText(nodeDescription) {
8064
+ const node = this.getAstNode(nodeDescription);
8065
+ if (isFunctionDecl(node)) {
8066
+ if (node.params.some((p) => !p.optional)) {
8067
+ return nodeDescription.name;
8068
+ }
8069
+ }
8070
+ return `${nodeDescription.name}()`;
8071
+ }
8072
+ getAttributeInsertText(nodeDescription) {
8073
+ const node = this.getAstNode(nodeDescription);
8074
+ if (isAttribute(node)) {
8075
+ if (node.name === "@relation") {
8076
+ return `${nodeDescription.name}(fields: [], references: [])`;
8077
+ }
8078
+ }
8079
+ return nodeDescription.name;
8080
+ }
8081
+ getAstNode(nodeDescription) {
8082
+ let node = nodeDescription.node;
8083
+ if (!node) {
8084
+ const doc = this.getOrCreateDocumentSync(nodeDescription);
8085
+ if (!doc) {
8086
+ return void 0;
8087
+ }
8088
+ node = this.services.workspace.AstNodeLocator.getAstNode(doc.parseResult.value, nodeDescription.path);
8089
+ if (!node) {
8090
+ return void 0;
8091
+ }
8092
+ }
8093
+ return node;
8094
+ }
8095
+ getOrCreateDocumentSync(nodeDescription) {
8096
+ let doc = this.services.shared.workspace.LangiumDocuments.getDocument(nodeDescription.documentUri);
8097
+ if (!doc) {
8098
+ try {
8099
+ const content = fs2.readFileSync(nodeDescription.documentUri.fsPath, "utf-8");
8100
+ doc = this.services.shared.workspace.LangiumDocuments.createDocument(nodeDescription.documentUri, content);
8101
+ } catch {
8102
+ console.warn("Failed to read or create document:", nodeDescription.documentUri);
8103
+ return void 0;
8104
+ }
8105
+ }
8106
+ return doc;
8107
+ }
8108
+ getNodeDocumentation(node) {
8109
+ if (!node) {
8110
+ return void 0;
8111
+ }
8112
+ const md = this.commentsToMarkdown(node);
8113
+ return {
8114
+ kind: "markdown",
8115
+ value: md
8116
+ };
8117
+ }
8118
+ commentsToMarkdown(node) {
8119
+ const md = this.services.documentation.DocumentationProvider.getDocumentation(node) ?? "";
8120
+ const zModelGenerator = new ZModelCodeGenerator();
8121
+ const docs = [];
8122
+ try {
8123
+ match3(node).when(isAttribute, (attr) => {
8124
+ docs.push("```prisma", zModelGenerator.generate(attr), "```");
8125
+ }).when(isFunctionDecl, (func2) => {
8126
+ docs.push("```ts", zModelGenerator.generate(func2), "```");
8127
+ }).when(isDataModel, (model) => {
8128
+ docs.push("```prisma", `model ${model.name} { ... }`, "```");
8129
+ }).when(isEnum, (enumDecl) => {
8130
+ docs.push("```prisma", zModelGenerator.generate(enumDecl), "```");
8131
+ }).when(isDataField, (field) => {
8132
+ docs.push(`${field.name}: ${field.type.type ?? field.type.reference?.$refText}`);
8133
+ }).otherwise((ast) => {
8134
+ const name = ast.name;
8135
+ if (name) {
8136
+ docs.push(name);
8137
+ }
8138
+ });
8139
+ } catch {
8140
+ }
8141
+ if (md) {
8142
+ docs.push("___", md);
8143
+ }
8144
+ return docs.join("\n");
8145
+ }
8146
+ };
8147
+
8148
+ // src/zmodel-definition.ts
8149
+ import { DefaultDefinitionProvider } from "langium/lsp";
8150
+ import { LocationLink, Range } from "vscode-languageserver";
8151
+ var ZModelDefinitionProvider = class extends DefaultDefinitionProvider {
8152
+ static {
8153
+ __name(this, "ZModelDefinitionProvider");
8154
+ }
8155
+ documents;
8156
+ constructor(services) {
8157
+ super(services);
8158
+ this.documents = services.shared.workspace.LangiumDocuments;
8159
+ }
8160
+ collectLocationLinks(sourceCstNode, _params) {
8161
+ if (isModelImport(sourceCstNode.astNode)) {
8162
+ const importedModel = resolveImport(this.documents, sourceCstNode.astNode);
8163
+ if (importedModel?.$document) {
8164
+ const targetObject = importedModel;
8165
+ const selectionRange = this.nameProvider.getNameNode(targetObject)?.range ?? Range.create(0, 0, 0, 0);
8166
+ const previewRange = targetObject.$cstNode?.range ?? Range.create(0, 0, 0, 0);
8167
+ return [
8168
+ LocationLink.create(importedModel.$document.uri.toString(), previewRange, selectionRange, sourceCstNode.range)
8169
+ ];
8170
+ }
8171
+ return void 0;
8172
+ }
8173
+ return super.collectLocationLinks(sourceCstNode, _params);
8174
+ }
8175
+ };
8176
+
8177
+ // src/zmodel-document-builder.ts
8178
+ import { DefaultDocumentBuilder } from "langium";
8179
+ var ZModelDocumentBuilder = class extends DefaultDocumentBuilder {
8180
+ static {
8181
+ __name(this, "ZModelDocumentBuilder");
8182
+ }
8183
+ constructor(services) {
8184
+ super(services);
8185
+ let validationOptions = this.updateBuildOptions.validation;
8186
+ const stopFlags = {
8187
+ stopAfterLinkingErrors: true,
8188
+ stopAfterLexingErrors: true,
8189
+ stopAfterParsingErrors: true
8190
+ };
8191
+ if (validationOptions === true) {
8192
+ validationOptions = stopFlags;
8193
+ } else if (typeof validationOptions === "object") {
8194
+ validationOptions = {
8195
+ ...validationOptions,
8196
+ ...stopFlags
8197
+ };
8198
+ }
8199
+ this.updateBuildOptions = {
8200
+ ...this.updateBuildOptions,
8201
+ validation: validationOptions
8202
+ };
8203
+ }
8204
+ };
8205
+
8206
+ // src/zmodel-documentation-provider.ts
8207
+ import { JSDocDocumentationProvider } from "langium";
8208
+ var ZModelDocumentationProvider = class extends JSDocDocumentationProvider {
8209
+ static {
8210
+ __name(this, "ZModelDocumentationProvider");
8211
+ }
8212
+ getDocumentation(node) {
8213
+ if ("comments" in node && Array.isArray(node.comments) && node.comments.length > 0) {
8214
+ return node.comments.map((c) => c.replace(/^[/]*\s*/, "")).join("\n");
8215
+ }
8216
+ return super.getDocumentation(node);
8217
+ }
8218
+ };
8219
+
8220
+ // src/zmodel-formatter.ts
8221
+ import { AbstractFormatter, Formatting } from "langium/lsp";
8222
+ var ZModelFormatter = class extends AbstractFormatter {
8223
+ static {
8224
+ __name(this, "ZModelFormatter");
8225
+ }
8226
+ formatOptions;
8227
+ configurationProvider;
8228
+ constructor(services) {
8229
+ super();
8230
+ this.configurationProvider = services.shared.workspace.ConfigurationProvider;
8231
+ }
8232
+ format(node) {
8233
+ const formatter = this.getNodeFormatter(node);
8234
+ if (isDataField(node)) {
8235
+ if (isDataModel(node.$container) || isTypeDef(node.$container)) {
8236
+ const dataModel = node.$container;
8237
+ const compareFn = /* @__PURE__ */ __name((a, b) => b - a, "compareFn");
8238
+ const maxNameLength = dataModel.fields.map((x) => x.name.length).sort(compareFn)[0] ?? 0;
8239
+ const maxTypeLength = dataModel.fields.map(this.getFieldTypeLength).sort(compareFn)[0] ?? 0;
8240
+ formatter.property("type").prepend(Formatting.spaces(maxNameLength - node.name.length + 1));
8241
+ if (node.attributes.length > 0) {
8242
+ formatter.node(node.attributes[0]).prepend(Formatting.spaces(maxTypeLength - this.getFieldTypeLength(node) + 1));
8243
+ formatter.nodes(...node.attributes.slice(1)).prepend(Formatting.oneSpace());
8244
+ }
8245
+ } else {
8246
+ formatter.property("type").prepend(Formatting.oneSpace());
8247
+ if (node.attributes.length > 0) {
8248
+ formatter.properties("attributes").prepend(Formatting.oneSpace());
8249
+ }
8250
+ }
8251
+ } else if (isDataFieldAttribute(node)) {
8252
+ formatter.keyword("(").surround(Formatting.noSpace());
8253
+ formatter.keyword(")").prepend(Formatting.noSpace());
8254
+ formatter.keyword(",").append(Formatting.oneSpace());
8255
+ if (node.args.length > 1) {
8256
+ formatter.nodes(...node.args.slice(1)).prepend(Formatting.oneSpace());
8257
+ }
8258
+ } else if (isAttributeArg(node)) {
8259
+ formatter.keyword(":").prepend(Formatting.noSpace());
8260
+ formatter.keyword(":").append(Formatting.oneSpace());
8261
+ } else if (isAbstractDeclaration(node)) {
8262
+ const bracesOpen = formatter.keyword("{");
8263
+ const bracesClose = formatter.keyword("}");
8264
+ formatter.interior(bracesOpen, bracesClose).prepend(Formatting.indent({
8265
+ allowMore: true
8266
+ }));
8267
+ bracesOpen.prepend(Formatting.oneSpace());
8268
+ bracesClose.prepend(Formatting.newLine());
8269
+ } else if (isModel(node)) {
8270
+ const model = node;
8271
+ const nodes = formatter.nodes(...model.declarations);
8272
+ nodes.prepend(Formatting.noIndent());
8273
+ }
8274
+ }
8275
+ formatDocument(document, params) {
8276
+ this.formatOptions = params.options;
8277
+ this.configurationProvider.getConfiguration(ZModelLanguageMetaData.languageId, "format").then((config) => {
8278
+ if (config) {
8279
+ }
8280
+ });
8281
+ return super.formatDocument(document, params);
8282
+ }
8283
+ getFormatOptions() {
8284
+ return this.formatOptions;
8285
+ }
8286
+ getIndent() {
8287
+ return 1;
8288
+ }
8289
+ getFieldTypeLength(field) {
8290
+ let length;
8291
+ if (field.type.type) {
8292
+ length = field.type.type.length;
8293
+ } else if (field.type.reference) {
8294
+ length = field.type.reference.$refText.length;
8295
+ } else if (isDataField(field) && field.type.unsupported) {
8296
+ const name = `Unsupported("${field.type.unsupported.value.value}")`;
8297
+ length = name.length;
8298
+ } else {
8299
+ length = 1;
8300
+ }
8301
+ if (field.type.optional) {
8302
+ length += 1;
8303
+ }
8304
+ if (field.type.array) {
8305
+ length += 2;
8306
+ }
8307
+ return length;
8308
+ }
8309
+ };
8310
+
8311
+ // src/zmodel-linker.ts
8312
+ import { AstUtils as AstUtils6, Cancellation, DefaultLinker, DocumentState, interruptAndCheck } from "langium";
8313
+ import { match as match4 } from "ts-pattern";
6988
8314
  var ZModelLinker = class extends DefaultLinker {
6989
8315
  static {
6990
8316
  __name(this, "ZModelLinker");
@@ -7005,21 +8331,19 @@ var ZModelLinker = class extends DefaultLinker {
7005
8331
  }
7006
8332
  document.state = DocumentState.Linked;
7007
8333
  }
7008
- linkReference(container, property, document, extraScopes) {
7009
- if (this.resolveFromScopeProviders(container, property, document, extraScopes)) {
8334
+ linkReference(refInfo, document, extraScopes) {
8335
+ const defaultRef = refInfo.reference;
8336
+ if (defaultRef._ref) {
8337
+ return;
8338
+ }
8339
+ if (this.resolveFromScopeProviders(refInfo.reference, document, extraScopes)) {
7010
8340
  return;
7011
8341
  }
7012
- const reference = container[property];
7013
- this.doLink({
7014
- reference,
7015
- container,
7016
- property
7017
- }, document);
8342
+ this.doLink(refInfo, document);
7018
8343
  }
7019
8344
  //#endregion
7020
8345
  //#region Expression type resolving
7021
- resolveFromScopeProviders(node, property, document, providers) {
7022
- const reference = node[property];
8346
+ resolveFromScopeProviders(reference, document, providers) {
7023
8347
  for (const provider of providers) {
7024
8348
  const target = provider(reference.$refText);
7025
8349
  if (target) {
@@ -7148,7 +8472,11 @@ var ZModelLinker = class extends DefaultLinker {
7148
8472
  }
7149
8473
  }
7150
8474
  resolveInvocation(node, document, extraScopes) {
7151
- this.linkReference(node, "function", document, extraScopes);
8475
+ this.linkReference({
8476
+ reference: node.function,
8477
+ container: node,
8478
+ property: "function"
8479
+ }, document, extraScopes);
7152
8480
  node.args.forEach((arg) => this.resolve(arg, document, extraScopes));
7153
8481
  if (node.function.ref) {
7154
8482
  const funcDecl = node.function.ref;
@@ -7161,7 +8489,7 @@ var ZModelLinker = class extends DefaultLinker {
7161
8489
  nullable: true
7162
8490
  };
7163
8491
  }
7164
- } else if (isFutureExpr(node)) {
8492
+ } else if (isBeforeInvocation(node)) {
7165
8493
  node.$resolvedType = {
7166
8494
  decl: getContainingDataModel(node)
7167
8495
  };
@@ -7171,7 +8499,7 @@ var ZModelLinker = class extends DefaultLinker {
7171
8499
  }
7172
8500
  }
7173
8501
  resolveLiteral(node) {
7174
- const type = match2(node).when(isStringLiteral, () => "String").when(isBooleanLiteral, () => "Boolean").when(isNumberLiteral, () => "Int").exhaustive();
8502
+ const type = match4(node).when(isStringLiteral, () => "String").when(isBooleanLiteral, () => "Boolean").when(isNumberLiteral, () => "Int").exhaustive();
7175
8503
  if (type) {
7176
8504
  this.resolveToBuiltinTypeOrDecl(node, type);
7177
8505
  }
@@ -7225,7 +8553,7 @@ var ZModelLinker = class extends DefaultLinker {
7225
8553
  if (isArrayExpr(node.value)) {
7226
8554
  node.value.items.forEach((item) => {
7227
8555
  if (isReferenceExpr(item)) {
7228
- const resolved2 = this.resolveFromScopeProviders(item, "target", document, [
8556
+ const resolved2 = this.resolveFromScopeProviders(item.target, document, [
7229
8557
  scopeProvider
7230
8558
  ]);
7231
8559
  if (resolved2) {
@@ -7239,7 +8567,7 @@ var ZModelLinker = class extends DefaultLinker {
7239
8567
  this.resolveToBuiltinTypeOrDecl(node.value, node.value.items[0].$resolvedType.decl, true);
7240
8568
  }
7241
8569
  } else if (isReferenceExpr(node.value)) {
7242
- const resolved2 = this.resolveFromScopeProviders(node.value, "target", document, [
8570
+ const resolved2 = this.resolveFromScopeProviders(node.value.target, document, [
7243
8571
  scopeProvider
7244
8572
  ]);
7245
8573
  if (resolved2) {
@@ -7291,13 +8619,9 @@ var ZModelLinker = class extends DefaultLinker {
7291
8619
  this.resolveDefault(node, document, scopes);
7292
8620
  }
7293
8621
  resolveDefault(node, document, extraScopes) {
7294
- for (const [property, value] of Object.entries(node)) {
7295
- if (!property.startsWith("$")) {
7296
- if (isReference(value)) {
7297
- this.linkReference(node, property, document, extraScopes);
7298
- }
7299
- }
7300
- }
8622
+ AstUtils6.streamReferences(node).forEach((ref) => {
8623
+ this.linkReference(ref, document, extraScopes);
8624
+ });
7301
8625
  for (const child of AstUtils6.streamContents(node)) {
7302
8626
  this.resolve(child, document, extraScopes);
7303
8627
  }
@@ -7343,7 +8667,7 @@ var ZModelLinker = class extends DefaultLinker {
7343
8667
 
7344
8668
  // src/zmodel-scope.ts
7345
8669
  import { AstUtils as AstUtils7, DefaultScopeComputation, DefaultScopeProvider, EMPTY_SCOPE, StreamScope, UriUtils, interruptAndCheck as interruptAndCheck2 } from "langium";
7346
- import { match as match3 } from "ts-pattern";
8670
+ import { match as match5 } from "ts-pattern";
7347
8671
  var ZModelScopeComputation = class extends DefaultScopeComputation {
7348
8672
  static {
7349
8673
  __name(this, "ZModelScopeComputation");
@@ -7367,7 +8691,7 @@ var ZModelScopeComputation = class extends DefaultScopeComputation {
7367
8691
  }
7368
8692
  processNode(node, document, scopes) {
7369
8693
  super.processNode(node, document, scopes);
7370
- if (isDataModel(node)) {
8694
+ if (isDataModel(node) || isTypeDef(node)) {
7371
8695
  const bases = getRecursiveBases(node);
7372
8696
  for (const base of bases) {
7373
8697
  for (const field of base.fields) {
@@ -7416,11 +8740,8 @@ var ZModelScopeProvider = class extends DefaultScopeProvider {
7416
8740
  const referenceType = this.reflection.getReferenceType(context);
7417
8741
  const globalScope = this.getGlobalScope(referenceType, context);
7418
8742
  const node = context.container;
7419
- const allowTypeDefScope = (
7420
- // isAuthOrAuthMemberAccess(node.operand) ||
7421
- !!AstUtils7.getContainerOfType(node, isTypeDef)
7422
- );
7423
- return match3(node.operand).when(isReferenceExpr, (operand) => {
8743
+ const allowTypeDefScope = isAuthOrAuthMemberAccess(node.operand) || !!AstUtils7.getContainerOfType(node, isTypeDef);
8744
+ return match5(node.operand).when(isReferenceExpr, (operand) => {
7424
8745
  const ref = operand.target.ref;
7425
8746
  if (isDataField(ref)) {
7426
8747
  return this.createScopeForContainer(ref.type.reference?.ref, globalScope, allowTypeDefScope);
@@ -7438,7 +8759,7 @@ var ZModelScopeProvider = class extends DefaultScopeProvider {
7438
8759
  if (isAuthInvocation(operand)) {
7439
8760
  return this.createScopeForAuth(node, globalScope);
7440
8761
  }
7441
- if (isFutureInvocation(operand)) {
8762
+ if (isBeforeInvocation(operand)) {
7442
8763
  return this.createScopeForContainingModel(node, globalScope);
7443
8764
  }
7444
8765
  return EMPTY_SCOPE;
@@ -7448,8 +8769,8 @@ var ZModelScopeProvider = class extends DefaultScopeProvider {
7448
8769
  const referenceType = this.reflection.getReferenceType(context);
7449
8770
  const globalScope = this.getGlobalScope(referenceType, context);
7450
8771
  const collection = collectionPredicate.left;
7451
- const allowTypeDefScope = false;
7452
- return match3(collection).when(isReferenceExpr, (expr) => {
8772
+ const allowTypeDefScope = isAuthOrAuthMemberAccess(collection);
8773
+ return match5(collection).when(isReferenceExpr, (expr) => {
7453
8774
  const ref = expr.target.ref;
7454
8775
  if (isDataField(ref)) {
7455
8776
  return this.createScopeForContainer(ref.type.reference?.ref, globalScope, allowTypeDefScope);
@@ -7511,11 +8832,95 @@ function getCollectionPredicateContext(node) {
7511
8832
  }
7512
8833
  __name(getCollectionPredicateContext, "getCollectionPredicateContext");
7513
8834
 
8835
+ // src/zmodel-semantic.ts
8836
+ import { AbstractSemanticTokenProvider } from "langium/lsp";
8837
+ import { SemanticTokenTypes } from "vscode-languageserver";
8838
+ var ZModelSemanticTokenProvider = class extends AbstractSemanticTokenProvider {
8839
+ static {
8840
+ __name(this, "ZModelSemanticTokenProvider");
8841
+ }
8842
+ highlightElement(node, acceptor) {
8843
+ if (isDataModel(node)) {
8844
+ acceptor({
8845
+ node,
8846
+ property: "name",
8847
+ type: SemanticTokenTypes.type
8848
+ });
8849
+ acceptor({
8850
+ node,
8851
+ property: "mixins",
8852
+ type: SemanticTokenTypes.type
8853
+ });
8854
+ acceptor({
8855
+ node,
8856
+ property: "baseModel",
8857
+ type: SemanticTokenTypes.type
8858
+ });
8859
+ } else if (isDataSource(node) || isGeneratorDecl(node) || isPlugin(node) || isEnum(node) || isTypeDef(node)) {
8860
+ acceptor({
8861
+ node,
8862
+ property: "name",
8863
+ type: SemanticTokenTypes.type
8864
+ });
8865
+ } else if (isDataField(node) || isConfigField(node) || isAttributeArg(node) || isPluginField(node) || isEnumField(node)) {
8866
+ acceptor({
8867
+ node,
8868
+ property: "name",
8869
+ type: SemanticTokenTypes.variable
8870
+ });
8871
+ } else if (isDataFieldType(node)) {
8872
+ if (node.type) {
8873
+ acceptor({
8874
+ node,
8875
+ property: "type",
8876
+ type: SemanticTokenTypes.type
8877
+ });
8878
+ } else {
8879
+ acceptor({
8880
+ node,
8881
+ property: "reference",
8882
+ type: SemanticTokenTypes.macro
8883
+ });
8884
+ }
8885
+ } else if (isDataModelAttribute(node) || isDataFieldAttribute(node) || isInternalAttribute(node)) {
8886
+ acceptor({
8887
+ node,
8888
+ property: "decl",
8889
+ type: SemanticTokenTypes.function
8890
+ });
8891
+ } else if (isInvocationExpr(node)) {
8892
+ acceptor({
8893
+ node,
8894
+ property: "function",
8895
+ type: SemanticTokenTypes.function
8896
+ });
8897
+ } else if (isFunctionDecl(node) || isAttribute(node)) {
8898
+ acceptor({
8899
+ node,
8900
+ property: "name",
8901
+ type: SemanticTokenTypes.function
8902
+ });
8903
+ } else if (isReferenceExpr(node)) {
8904
+ acceptor({
8905
+ node,
8906
+ property: "target",
8907
+ type: SemanticTokenTypes.variable
8908
+ });
8909
+ } else if (isMemberAccessExpr(node)) {
8910
+ acceptor({
8911
+ node,
8912
+ property: "member",
8913
+ type: SemanticTokenTypes.property
8914
+ });
8915
+ }
8916
+ }
8917
+ };
8918
+
7514
8919
  // src/zmodel-workspace-manager.ts
7515
- import { DefaultWorkspaceManager, URI as URI2, UriUtils as UriUtils2 } from "langium";
7516
- import fs2 from "fs";
8920
+ import { DefaultWorkspaceManager, URI as URI2 } from "langium";
8921
+ import fs3 from "fs";
7517
8922
  import path2 from "path";
7518
- import { fileURLToPath } from "url";
8923
+ import { fileURLToPath as fileURLToPath2 } from "url";
7519
8924
  var ZModelWorkspaceManager = class extends DefaultWorkspaceManager {
7520
8925
  static {
7521
8926
  __name(this, "ZModelWorkspaceManager");
@@ -7539,7 +8944,7 @@ var ZModelWorkspaceManager = class extends DefaultWorkspaceManager {
7539
8944
  });
7540
8945
  const languagePackageDir = path2.dirname(languagePackagePath);
7541
8946
  const candidateStdlibPath = path2.join(languagePackageDir, "res", STD_LIB_MODULE_NAME);
7542
- if (fs2.existsSync(candidateStdlibPath)) {
8947
+ if (fs3.existsSync(candidateStdlibPath)) {
7543
8948
  installedStdlibPath = candidateStdlibPath;
7544
8949
  console.log(`Found installed zenstack package stdlib at: ${installedStdlibPath}`);
7545
8950
  break;
@@ -7551,73 +8956,12 @@ var ZModelWorkspaceManager = class extends DefaultWorkspaceManager {
7551
8956
  if (installedStdlibPath) {
7552
8957
  stdLibPath = installedStdlibPath;
7553
8958
  } else {
7554
- const _dirname = typeof __dirname !== "undefined" ? __dirname : path2.dirname(fileURLToPath(import.meta.url));
8959
+ const _dirname = typeof __dirname !== "undefined" ? __dirname : path2.dirname(fileURLToPath2(import.meta.url));
7555
8960
  stdLibPath = path2.join(_dirname, "../res", STD_LIB_MODULE_NAME);
7556
8961
  console.log(`Using bundled stdlib in extension:`, stdLibPath);
7557
8962
  }
7558
8963
  const stdlib = await this.documentFactory.fromUri(URI2.file(stdLibPath));
7559
8964
  collector(stdlib);
7560
- const documents = this.langiumDocuments.all;
7561
- const pluginModels = /* @__PURE__ */ new Set();
7562
- documents.forEach((doc) => {
7563
- const parsed = doc.parseResult.value;
7564
- parsed.declarations.forEach((decl) => {
7565
- if (isPlugin(decl)) {
7566
- const providerField = decl.fields.find((f) => f.name === "provider");
7567
- if (providerField) {
7568
- const provider = getLiteral(providerField.value);
7569
- if (provider) {
7570
- pluginModels.add(provider);
7571
- }
7572
- }
7573
- }
7574
- });
7575
- });
7576
- if (pluginModels.size > 0) {
7577
- console.log(`Used plugin modules: ${Array.from(pluginModels)}`);
7578
- const pendingPluginModules = new Set(pluginModels);
7579
- await Promise.all(folders.map((wf) => [
7580
- wf,
7581
- this.getRootFolder(wf)
7582
- ]).map(async (entry) => this.loadPluginModels(...entry, pendingPluginModules, collector)));
7583
- }
7584
- }
7585
- async loadPluginModels(workspaceFolder, folderPath, pendingPluginModels, collector) {
7586
- const content = (await this.fileSystemProvider.readDirectory(folderPath)).sort((a, b) => {
7587
- if (a.isDirectory && b.isDirectory) {
7588
- const aName = UriUtils2.basename(a.uri);
7589
- if (aName === "node_modules") {
7590
- return -1;
7591
- } else {
7592
- return 1;
7593
- }
7594
- } else {
7595
- return 0;
7596
- }
7597
- });
7598
- for (const entry of content) {
7599
- if (entry.isDirectory) {
7600
- const name = UriUtils2.basename(entry.uri);
7601
- if (name === "node_modules") {
7602
- for (const plugin of Array.from(pendingPluginModels)) {
7603
- const path4 = UriUtils2.joinPath(entry.uri, plugin, PLUGIN_MODULE_NAME);
7604
- try {
7605
- await this.fileSystemProvider.readFile(path4);
7606
- const document = await this.langiumDocuments.getOrCreateDocument(path4);
7607
- collector(document);
7608
- console.log(`Adding plugin document from ${path4.path}`);
7609
- pendingPluginModels.delete(plugin);
7610
- if (pendingPluginModels.size === 0) {
7611
- return;
7612
- }
7613
- } catch {
7614
- }
7615
- }
7616
- } else {
7617
- await this.loadPluginModels(workspaceFolder, entry.uri, pendingPluginModels, collector);
7618
- }
7619
- }
7620
- }
7621
8965
  }
7622
8966
  };
7623
8967
 
@@ -7630,14 +8974,25 @@ var ZModelLanguageModule = {
7630
8974
  },
7631
8975
  validation: {
7632
8976
  ZModelValidator: /* @__PURE__ */ __name((services) => new ZModelValidator(services), "ZModelValidator")
8977
+ },
8978
+ lsp: {
8979
+ Formatter: /* @__PURE__ */ __name((services) => new ZModelFormatter(services), "Formatter"),
8980
+ DefinitionProvider: /* @__PURE__ */ __name((services) => new ZModelDefinitionProvider(services), "DefinitionProvider"),
8981
+ CompletionProvider: /* @__PURE__ */ __name((services) => new ZModelCompletionProvider(services), "CompletionProvider"),
8982
+ SemanticTokenProvider: /* @__PURE__ */ __name((services) => new ZModelSemanticTokenProvider(services), "SemanticTokenProvider")
8983
+ },
8984
+ documentation: {
8985
+ CommentProvider: /* @__PURE__ */ __name((services) => new ZModelCommentProvider(services), "CommentProvider"),
8986
+ DocumentationProvider: /* @__PURE__ */ __name((services) => new ZModelDocumentationProvider(services), "DocumentationProvider")
7633
8987
  }
7634
8988
  };
7635
8989
  var ZModelSharedModule = {
7636
8990
  workspace: {
8991
+ DocumentBuilder: /* @__PURE__ */ __name((services) => new ZModelDocumentBuilder(services), "DocumentBuilder"),
7637
8992
  WorkspaceManager: /* @__PURE__ */ __name((services) => new ZModelWorkspaceManager(services), "WorkspaceManager")
7638
8993
  }
7639
8994
  };
7640
- function createZModelLanguageServices(context) {
8995
+ function createZModelLanguageServices(context, logToConsole = false) {
7641
8996
  const shared = inject(createDefaultSharedModule(context), ZModelGeneratedSharedModule, ZModelSharedModule);
7642
8997
  const ZModelLanguage = inject(createDefaultModule({
7643
8998
  shared
@@ -7647,30 +9002,47 @@ function createZModelLanguageServices(context) {
7647
9002
  if (!context.connection) {
7648
9003
  shared.workspace.ConfigurationProvider.initialized({});
7649
9004
  }
9005
+ shared.workspace.DocumentBuilder.onBuildPhase(DocumentState2.Parsed, async (documents) => {
9006
+ for (const doc of documents) {
9007
+ if (doc.parseResult.lexerErrors.length > 0 || doc.parseResult.parserErrors.length > 0) {
9008
+ continue;
9009
+ }
9010
+ if (doc.uri.scheme !== "file") {
9011
+ continue;
9012
+ }
9013
+ const schemaPath = fileURLToPath3(doc.uri.toString());
9014
+ const pluginSchemas = getPluginDocuments(doc.parseResult.value, schemaPath);
9015
+ for (const plugin of pluginSchemas) {
9016
+ const pluginDocUri = URI3.file(path3.resolve(plugin));
9017
+ let pluginDoc = shared.workspace.LangiumDocuments.getDocument(pluginDocUri);
9018
+ if (!pluginDoc) {
9019
+ pluginDoc = await shared.workspace.LangiumDocuments.getOrCreateDocument(pluginDocUri);
9020
+ if (pluginDoc) {
9021
+ shared.workspace.IndexManager.updateContent(pluginDoc);
9022
+ if (logToConsole) {
9023
+ console.log(`Loaded plugin model: ${plugin}`);
9024
+ }
9025
+ }
9026
+ }
9027
+ }
9028
+ }
9029
+ });
7650
9030
  return {
7651
9031
  shared,
7652
9032
  ZModelLanguage
7653
9033
  };
7654
9034
  }
7655
9035
  __name(createZModelLanguageServices, "createZModelLanguageServices");
7656
-
7657
- // src/index.ts
7658
- function createZModelServices() {
7659
- return createZModelLanguageServices(NodeFileSystem);
9036
+ function createZModelServices(logToConsole = false) {
9037
+ return createZModelLanguageServices(NodeFileSystem, logToConsole);
7660
9038
  }
7661
9039
  __name(createZModelServices, "createZModelServices");
7662
- var DocumentLoadError = class extends Error {
7663
- static {
7664
- __name(this, "DocumentLoadError");
7665
- }
7666
- constructor(message) {
7667
- super(message);
7668
- }
7669
- };
7670
- async function loadDocument(fileName, pluginModelFiles = []) {
7671
- const { ZModelLanguage: services } = createZModelServices();
9040
+
9041
+ // src/document.ts
9042
+ async function loadDocument(fileName, additionalModelFiles = []) {
9043
+ const { ZModelLanguage: services } = createZModelServices(false);
7672
9044
  const extensions = services.LanguageMetaData.fileExtensions;
7673
- if (!extensions.includes(path3.extname(fileName))) {
9045
+ if (!extensions.includes(path4.extname(fileName))) {
7674
9046
  return {
7675
9047
  success: false,
7676
9048
  errors: [
@@ -7679,7 +9051,7 @@ async function loadDocument(fileName, pluginModelFiles = []) {
7679
9051
  warnings: []
7680
9052
  };
7681
9053
  }
7682
- if (!fs3.existsSync(fileName)) {
9054
+ if (!fs4.existsSync(fileName)) {
7683
9055
  return {
7684
9056
  success: false,
7685
9057
  errors: [
@@ -7688,23 +9060,27 @@ async function loadDocument(fileName, pluginModelFiles = []) {
7688
9060
  warnings: []
7689
9061
  };
7690
9062
  }
7691
- const _dirname = typeof __dirname !== "undefined" ? __dirname : path3.dirname(fileURLToPath2(import.meta.url));
7692
- const stdLib = await services.shared.workspace.LangiumDocuments.getOrCreateDocument(URI3.file(path3.resolve(path3.join(_dirname, "../res", STD_LIB_MODULE_NAME))));
7693
- const pluginDocs = await Promise.all(pluginModelFiles.map((file) => services.shared.workspace.LangiumDocuments.getOrCreateDocument(URI3.file(path3.resolve(file)))));
9063
+ const _dirname = typeof __dirname !== "undefined" ? __dirname : path4.dirname(fileURLToPath4(import.meta.url));
9064
+ const stdLib = await services.shared.workspace.LangiumDocuments.getOrCreateDocument(URI4.file(path4.resolve(path4.join(_dirname, "../res", STD_LIB_MODULE_NAME))));
7694
9065
  const langiumDocuments = services.shared.workspace.LangiumDocuments;
7695
- const document = await langiumDocuments.getOrCreateDocument(URI3.file(path3.resolve(fileName)));
9066
+ const document = await langiumDocuments.getOrCreateDocument(URI4.file(path4.resolve(fileName)));
7696
9067
  const importedURIs = await loadImports(document, langiumDocuments);
7697
9068
  const importedDocuments = [];
7698
9069
  for (const uri of importedURIs) {
7699
9070
  importedDocuments.push(await langiumDocuments.getOrCreateDocument(uri));
7700
9071
  }
9072
+ const additionalDocs = await Promise.all(additionalModelFiles.map((file) => services.shared.workspace.LangiumDocuments.getOrCreateDocument(URI4.file(path4.resolve(file)))));
7701
9073
  await services.shared.workspace.DocumentBuilder.build([
7702
9074
  stdLib,
7703
- ...pluginDocs,
9075
+ ...additionalDocs,
7704
9076
  document,
7705
9077
  ...importedDocuments
7706
9078
  ], {
7707
- validation: true
9079
+ validation: {
9080
+ stopAfterLexingErrors: true,
9081
+ stopAfterParsingErrors: true,
9082
+ stopAfterLinkingErrors: true
9083
+ }
7708
9084
  });
7709
9085
  const diagnostics = langiumDocuments.all.flatMap((doc) => (doc.diagnostics ?? []).map((diag) => ({
7710
9086
  doc,
@@ -7714,7 +9090,7 @@ async function loadDocument(fileName, pluginModelFiles = []) {
7714
9090
  const warnings = [];
7715
9091
  if (diagnostics.length > 0) {
7716
9092
  for (const { doc, diag } of diagnostics) {
7717
- const message = `${path3.relative(process.cwd(), doc.uri.fsPath)}:${diag.range.start.line + 1}:${diag.range.start.character + 1} - ${diag.message}`;
9093
+ const message = `${path4.relative(process.cwd(), doc.uri.fsPath)}:${diag.range.start.line + 1}:${diag.range.start.character + 1} - ${diag.message}`;
7718
9094
  if (diag.severity === 1) {
7719
9095
  errors.push(message);
7720
9096
  } else {
@@ -7763,7 +9139,7 @@ async function loadImports(document, documents, uris = /* @__PURE__ */ new Set()
7763
9139
  }
7764
9140
  }
7765
9141
  }
7766
- return Array.from(uris).filter((x) => uriString != x).map((e) => URI3.parse(e));
9142
+ return Array.from(uris).filter((x) => uriString != x).map((e) => URI4.parse(e));
7767
9143
  }
7768
9144
  __name(loadImports, "loadImports");
7769
9145
  function mergeImportsDeclarations(documents, model) {
@@ -7812,13 +9188,33 @@ function validationAfterImportMerge(model) {
7812
9188
  return errors;
7813
9189
  }
7814
9190
  __name(validationAfterImportMerge, "validationAfterImportMerge");
9191
+ async function formatDocument(content) {
9192
+ const services = createZModelServices().ZModelLanguage;
9193
+ const langiumDocuments = services.shared.workspace.LangiumDocuments;
9194
+ const document = langiumDocuments.createDocument(URI4.parse("memory://schema.zmodel"), content);
9195
+ const formatter = services.lsp.Formatter;
9196
+ const identifier = {
9197
+ uri: document.uri.toString()
9198
+ };
9199
+ const options = formatter.getFormatOptions() ?? {
9200
+ insertSpaces: true,
9201
+ tabSize: 4
9202
+ };
9203
+ const edits = await formatter.formatDocument(document, {
9204
+ options,
9205
+ textDocument: identifier
9206
+ });
9207
+ return TextDocument.applyEdits(document.textDocument, edits);
9208
+ }
9209
+ __name(formatDocument, "formatDocument");
7815
9210
  export {
7816
- DocumentLoadError,
9211
+ ZModelCodeGenerator,
7817
9212
  ZModelLanguageMetaData,
7818
9213
  ZModelLanguageModule,
7819
9214
  ZModelSharedModule,
7820
9215
  createZModelLanguageServices,
7821
9216
  createZModelServices,
9217
+ formatDocument,
7822
9218
  loadDocument
7823
9219
  };
7824
9220
  //# sourceMappingURL=index.js.map