@uipath/packager-tool-datafabric 1.206.0-preview.306 → 1.207.0-preview.307

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
@@ -1,618 +1,35 @@
1
- // ../../common/src/telemetry/telemetry-dimensions.ts
2
- var BaseDimensions = {
3
- ApplicationName: "ApplicationName",
4
- ProductVersion: "ProductVersion",
5
- InstallationId: "InstallationId",
6
- CloudUserId: "CloudUserId",
7
- CloudTenantId: "CloudTenantId",
8
- CloudOrganizationId: "CloudOrganizationId",
9
- IsInternalUser: "IsInternalUser",
10
- Environment: "Environment",
11
- BaseUrl: "BaseUrl",
12
- Region: "Region",
13
- Agent: "Agent",
14
- AgentVersion: "AgentVersion",
15
- AgentModel: "AgentModel",
16
- ToolName: "ToolName",
17
- ToolVersion: "ToolVersion",
18
- ExecutionContext: "ExecutionContext",
19
- CiProvider: "CiProvider",
20
- SessionIdSource: "SessionIdSource",
21
- SessionId: "SessionId"
22
- };
23
- var CommandDimensions = {
24
- IsCommand: "IsCommand",
25
- IsReexec: "IsReexec",
26
- CommandName: "CommandName",
27
- ExitCode: "ExitCode",
28
- TerminalOutcome: "TerminalOutcome",
29
- ErrorClass: "ErrorClass",
30
- TerminalSignal: "TerminalSignal",
31
- ErrorMessage: "ErrorMessage",
32
- SkillName: "SkillName",
33
- ProductArea: "ProductArea",
34
- Mode: "Mode"
35
- };
36
- var ProjectDimensions = {
37
- ProjectKey: "ProjectKey",
38
- ProjectType: "ProjectType",
39
- ProjectIdentityStatus: "ProjectIdentityStatus",
40
- SolutionKey: "SolutionKey",
41
- SolutionProjectKey: "SolutionProjectKey",
42
- SolutionIdentityStatus: "SolutionIdentityStatus",
43
- PreviousSolutionKey: "PreviousSolutionKey"
44
- };
45
- var GUID_KEY_DIMENSIONS = new Set([
46
- ProjectDimensions.ProjectKey,
47
- ProjectDimensions.SolutionKey,
48
- ProjectDimensions.SolutionProjectKey,
49
- ProjectDimensions.PreviousSolutionKey
50
- ]);
51
- var ShipDimensions = {
52
- ShipKind: "ShipKind",
53
- Target: "Target",
54
- ProjectType: "ProjectType",
55
- ProjectTypes: "ProjectTypes",
56
- ArtifactCorrelationKey: "ArtifactCorrelationKey",
57
- PackageName: "PackageName",
58
- PackageVersion: "PackageVersion",
59
- PackageVersionKey: "PackageVersionKey",
60
- DeploymentKey: "DeploymentKey",
61
- SolutionId: "SolutionId",
62
- FolderKey: "FolderKey",
63
- FeedId: "FeedId"
64
- };
65
- var ErrorDimensions = {
66
- Result: "Result",
67
- ErrorCode: "ErrorCode",
68
- Retry: "Retry",
69
- ErrorMessage: "ErrorMessage",
70
- HttpStatus: "HttpStatus",
71
- UpstreamErrorCode: "UpstreamErrorCode"
72
- };
73
- var AuthDimensions = {
74
- AuthenticationMethod: "AuthenticationMethod",
75
- Success: "Success",
76
- Reason: "Reason"
77
- };
78
- var SkillsDimensions = {
79
- SchemaVersion: "SchemaVersion",
80
- AgentType: "AgentType",
81
- SkillsVersion: "SkillsVersion",
82
- UipSubcommand: "UipSubcommand",
83
- FileExtension: "FileExtension",
84
- SubagentModel: "SubagentModel",
85
- SubagentType: "SubagentType",
86
- PermissionMode: "PermissionMode",
87
- EffortLevel: "EffortLevel",
88
- SessionSource: "SessionSource",
89
- Outcome: "Outcome",
90
- DurationMs: "DurationMs",
91
- Source: "Source"
92
- };
93
- var PackagerDimensions = {
94
- ProjectId: "ProjectId",
95
- ProjectType: "ProjectType",
96
- SolutionId: "SolutionId"
97
- };
98
- var ScopeDimensions = {
99
- FolderId: "FolderId"
100
- };
101
- var ID_DIMENSIONS = new Set([
102
- BaseDimensions.CloudUserId,
103
- BaseDimensions.CloudTenantId,
104
- BaseDimensions.CloudOrganizationId,
105
- BaseDimensions.InstallationId,
106
- ShipDimensions.ArtifactCorrelationKey,
107
- ShipDimensions.PackageVersionKey,
108
- ShipDimensions.DeploymentKey,
109
- ShipDimensions.SolutionId,
110
- ShipDimensions.FolderKey,
111
- ShipDimensions.FeedId,
112
- PackagerDimensions.ProjectId
113
- ]);
114
- var RESERVED_DIMENSION_NAMES = new Set([
115
- ...Object.values(BaseDimensions),
116
- ...Object.values(CommandDimensions),
117
- ...Object.values(ShipDimensions),
118
- ...Object.values(ProjectDimensions),
119
- ...Object.values(ErrorDimensions),
120
- ...Object.values(AuthDimensions),
121
- ...Object.values(SkillsDimensions),
122
- ...Object.values(PackagerDimensions),
123
- ...Object.values(ScopeDimensions)
124
- ]);
125
- var CURATED_DIMENSIONS = new Set([
126
- BaseDimensions.ApplicationName,
127
- BaseDimensions.ProductVersion,
128
- BaseDimensions.InstallationId,
129
- BaseDimensions.CloudUserId,
130
- BaseDimensions.CloudTenantId,
131
- BaseDimensions.CloudOrganizationId,
132
- BaseDimensions.IsInternalUser,
133
- BaseDimensions.Environment,
134
- BaseDimensions.BaseUrl,
135
- BaseDimensions.Region,
136
- BaseDimensions.Agent,
137
- BaseDimensions.AgentVersion,
138
- BaseDimensions.ToolVersion,
139
- BaseDimensions.ExecutionContext,
140
- BaseDimensions.CiProvider,
141
- BaseDimensions.SessionIdSource,
142
- BaseDimensions.SessionId,
143
- ...Object.values(CommandDimensions),
144
- ...Object.values(ShipDimensions),
145
- ...Object.values(ProjectDimensions)
146
- ]);
147
-
148
- // ../../common/src/telemetry/pseudonymize.ts
149
- var SHA256_K = new Uint32Array([
150
- 1116352408,
151
- 1899447441,
152
- 3049323471,
153
- 3921009573,
154
- 961987163,
155
- 1508970993,
156
- 2453635748,
157
- 2870763221,
158
- 3624381080,
159
- 310598401,
160
- 607225278,
161
- 1426881987,
162
- 1925078388,
163
- 2162078206,
164
- 2614888103,
165
- 3248222580,
166
- 3835390401,
167
- 4022224774,
168
- 264347078,
169
- 604807628,
170
- 770255983,
171
- 1249150122,
172
- 1555081692,
173
- 1996064986,
174
- 2554220882,
175
- 2821834349,
176
- 2952996808,
177
- 3210313671,
178
- 3336571891,
179
- 3584528711,
180
- 113926993,
181
- 338241895,
182
- 666307205,
183
- 773529912,
184
- 1294757372,
185
- 1396182291,
186
- 1695183700,
187
- 1986661051,
188
- 2177026350,
189
- 2456956037,
190
- 2730485921,
191
- 2820302411,
192
- 3259730800,
193
- 3345764771,
194
- 3516065817,
195
- 3600352804,
196
- 4094571909,
197
- 275423344,
198
- 430227734,
199
- 506948616,
200
- 659060556,
201
- 883997877,
202
- 958139571,
203
- 1322822218,
204
- 1537002063,
205
- 1747873779,
206
- 1955562222,
207
- 2024104815,
208
- 2227730452,
209
- 2361852424,
210
- 2428436474,
211
- 2756734187,
212
- 3204031479,
213
- 3329325298
214
- ]);
215
- var SHA256_INITIAL_STATE = new Uint32Array([
216
- 1779033703,
217
- 3144134277,
218
- 1013904242,
219
- 2773480762,
220
- 1359893119,
221
- 2600822924,
222
- 528734635,
223
- 1541459225
224
- ]);
225
-
226
- // ../../common/src/singleton.ts
227
- var PREFIX = "@uipath/common/";
228
- var _g = globalThis;
229
- function singleton(ctorOrName) {
230
- const name = typeof ctorOrName === "string" ? ctorOrName : ctorOrName.name;
231
- const key = Symbol.for(PREFIX + name);
232
- return {
233
- get(fallback) {
234
- return _g[key] ?? fallback;
235
- },
236
- set(value) {
237
- _g[key] = value;
238
- },
239
- clear() {
240
- delete _g[key];
241
- },
242
- getOrInit(factory, guard) {
243
- const existing = _g[key];
244
- if (existing != null && typeof existing === "object") {
245
- if (!guard || guard(existing)) {
246
- return existing;
247
- }
248
- }
249
- const instance = factory();
250
- _g[key] = instance;
251
- return instance;
252
- }
253
- };
254
- }
255
-
256
- // ../../common/src/telemetry/supplied-values.ts
257
- var suppliedValuesSlot = singleton("TelemetrySuppliedArgumentValues");
258
-
259
- // ../../common/src/telemetry/pii-redactor.ts
260
- var SENSITIVE_NAME_TOKENS = new Set([
261
- "token",
262
- "tokens",
263
- "secret",
264
- "secrets",
265
- "password",
266
- "passwords",
267
- "pwd",
268
- "credential",
269
- "credentials",
270
- "auth",
271
- "authentication",
272
- "authorization",
273
- "authority",
274
- "cert",
275
- "certificate",
276
- "certificates"
277
- ]);
278
- var SENSITIVE_KEY_PREFIXES = new Set([
279
- "api",
280
- "access",
281
- "client",
282
- "private",
283
- "public",
284
- "signing",
285
- "encryption",
286
- "session",
287
- "master",
288
- "shared",
289
- "root",
290
- "ssh",
291
- "rsa",
292
- "aes",
293
- "hmac",
294
- "oauth"
295
- ]);
296
- var SOURCE_FILE_EXTENSIONS = new Set([
297
- "ts",
298
- "tsx",
299
- "js",
300
- "jsx",
301
- "mjs",
302
- "cjs",
303
- "cts",
304
- "mts",
305
- "py",
306
- "cs",
307
- "java",
308
- "go",
309
- "rs",
310
- "rb",
311
- "php",
312
- "sh",
313
- "ps1",
314
- "json",
315
- "jsonc",
316
- "yaml",
317
- "yml",
318
- "xml",
319
- "xaml",
320
- "md",
321
- "txt",
322
- "log",
323
- "css",
324
- "html",
325
- "htm",
326
- "csproj",
327
- "nuspec",
328
- "sql"
329
- ]);
330
- var QUOTED_LITERAL_MAX_SPAN = 200;
331
- var QUOTED_LITERAL_PATTERN = new RegExp([
332
- `(?<![A-Za-z0-9])'(?:[^\\
333
- ]|\\.){2,${QUOTED_LITERAL_MAX_SPAN}}?'(?![A-Za-z0-9])`,
334
- `(?<![A-Za-z0-9])"(?:[^\\
335
- ]|\\.){2,${QUOTED_LITERAL_MAX_SPAN}}?"(?![A-Za-z0-9])`
336
- ].join("|"), "g");
337
- var MESSAGE_NAMES = new Set([
338
- "message",
339
- "errormessage",
340
- "errmessage",
341
- "error_message",
342
- "msg",
343
- "detail",
344
- "details",
345
- "reason",
346
- "instructions",
347
- "warning"
348
- ]);
349
- function nameTokens(name) {
350
- return name.replace(/([a-z0-9])([A-Z])/g, "$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g, "$1 $2").split(/[\s._-]+/).map((t) => t.toLowerCase()).filter(Boolean);
351
- }
352
- function isSensitiveName(name) {
353
- const tokens = nameTokens(name);
354
- for (let i = 0;i < tokens.length; i++) {
355
- const token = tokens[i];
356
- if (SENSITIVE_NAME_TOKENS.has(token)) {
357
- return true;
358
- }
359
- if (token === "key" || token === "keys") {
360
- const prev = tokens[i - 1];
361
- if (prev && SENSITIVE_KEY_PREFIXES.has(prev)) {
362
- return true;
363
- }
364
- }
365
- }
366
- return false;
367
- }
368
-
369
- // ../../common/src/catch-error.ts
370
- var MAX_SERIALIZED_LENGTH = 500;
371
- var TRUNCATION_SUFFIX = "…(truncated)";
372
- var REDACTED = "[REDACTED]";
373
- function cap(text) {
374
- return text.length > MAX_SERIALIZED_LENGTH ? `${text.slice(0, MAX_SERIALIZED_LENGTH)}${TRUNCATION_SUFFIX}` : text;
375
- }
376
- function omitSensitive(key, value) {
377
- return key.length > 0 && isSensitiveName(key) ? REDACTED : value;
378
- }
379
- function describeThrownValue(value) {
380
- if (typeof value !== "object" || value === null) {
381
- return String(value);
382
- }
383
- let message;
384
- try {
385
- message = value.message;
386
- } catch {
387
- message = undefined;
388
- }
389
- if (typeof message === "string" && message.length > 0) {
390
- return cap(message);
391
- }
392
- try {
393
- const json = JSON.stringify(value, omitSensitive);
394
- if (json !== undefined) {
395
- return cap(json);
396
- }
397
- } catch {}
398
- return String(value);
399
- }
400
- function toError(error) {
401
- return error instanceof Error ? error : new Error(describeThrownValue(error), { cause: error });
402
- }
403
- function isPromiseLike(value) {
404
- return value !== null && typeof value === "object" && typeof value.then === "function";
405
- }
406
- function catchError(fnOrPromise) {
407
- if (isPromiseLike(fnOrPromise)) {
408
- return settlePromiseLike(fnOrPromise);
409
- }
410
- try {
411
- const result = fnOrPromise();
412
- if (isPromiseLike(result)) {
413
- return settlePromiseLike(result);
414
- }
415
- return [undefined, result];
416
- } catch (error) {
417
- return [toError(error), undefined];
418
- }
419
- }
420
- function settlePromiseLike(thenable) {
421
- return Promise.resolve(thenable).then((data) => [undefined, data]).catch((error) => [toError(error), undefined]);
422
- }
423
-
424
- // src/pack/entity-project-tool.ts
425
- import {
426
- ProjectTool,
427
- ToolResult
428
- } from "@uipath/solutionpackager-tool-core";
429
-
430
- // src/missing-path.ts
431
- function isMissingPathError(error) {
432
- if (!(error instanceof Error) || !("code" in error))
433
- return false;
434
- const { code } = error;
435
- return code === "ENOENT" || code === "ENOTDIR" || code === "PathNotFound";
436
- }
437
- function isFilesystemError(error) {
438
- const code = error?.code;
439
- return typeof code === "string" && /^E[A-Z]+$/.test(code);
440
- }
441
- function isUnreadablePathError(error) {
442
- return isFilesystemError(error) && !isMissingPathError(error);
443
- }
444
-
445
- // src/pack/constants.ts
446
- var ENTITY_EXTENSION_CONST = ".entity";
447
- var ENTITY_VALIDATION_FAILED = "ENTITY_VALIDATION_FAILED";
448
- var PACK_DIAGNOSTIC_CODES = {
449
- misplacedMainFile: "MISPLACED_MAIN_FILE",
450
- noParentSolution: "NO_PARENT_SOLUTION",
451
- solutionRootUnreadable: "SOLUTION_ROOT_UNREADABLE"
452
- };
453
-
454
- // src/schema/solution-entity-names.ts
455
- function withoutOneOccurrence(names, name) {
456
- const siblings = [...names];
457
- const self = siblings.indexOf(name);
458
- if (self >= 0) {
459
- siblings.splice(self, 1);
460
- }
461
- return siblings;
462
- }
463
- function isMissingPath(error) {
464
- return error instanceof Error && "code" in error && (error.code === "ENOENT" || error.code === "PathNotFound");
465
- }
466
- async function collectSolutionEntityNames(solutionDir, fs) {
467
- const names = [];
468
- let topLevel = [];
469
- try {
470
- topLevel = await fs.readdir(solutionDir);
471
- } catch (error) {
472
- if (!isMissingPath(error)) {
473
- throw error;
474
- }
475
- return names;
476
- }
477
- for (const entry of topLevel) {
478
- if (entry === "resources" || entry.startsWith(".")) {
479
- continue;
480
- }
481
- const dir = fs.path.join(solutionDir, entry);
482
- try {
483
- const stat = await fs.stat(dir);
484
- if (!stat?.isDirectory()) {
485
- continue;
486
- }
487
- for (const file of await fs.readdir(dir)) {
488
- if (file.endsWith(ENTITY_EXTENSION_CONST)) {
489
- names.push(fs.path.basename(file, ENTITY_EXTENSION_CONST));
490
- }
491
- }
492
- } catch (error) {
493
- if (!isMissingPath(error)) {
494
- throw error;
495
- }
496
- }
497
- }
498
- return names;
499
- }
500
-
501
- // ../../common/src/entity-field-rules.ts
502
- var MAX_SAFE_NUMERIC_BOUND = 9007199254740991;
503
- var LENGTH_LIMIT_RANGES = {
504
- STRING: [1, 4000],
505
- MULTILINE_TEXT: [1, 1e4],
506
- MULTILINE_MAX: [1, 131072]
507
- };
508
- var MAX_MULTILINE_MAX_FIELDS = 10;
509
- function isNumber(v) {
510
- return typeof v === "number" && Number.isFinite(v);
511
- }
512
- function findInvalidFieldConstraints(fields) {
513
- for (const f of fields) {
514
- if (typeof f !== "object" || f === null)
515
- continue;
516
- const rec = f;
517
- const type = rec.type;
518
- if (typeof type !== "string")
519
- continue;
520
- const fieldName = typeof rec.name === "string" ? rec.name : "<field>";
521
- if (rec.lengthLimit !== undefined) {
522
- if (!isNumber(rec.lengthLimit) || !Number.isInteger(rec.lengthLimit)) {
523
- return {
524
- message: `Field '${fieldName}' 'lengthLimit' must be an integer`,
525
- instructions: "Pass a positive integer within the type's range (STRING 1-4000, MULTILINE_TEXT 1-10000, MULTILINE_MAX 1-131072 UTF-16 bytes)."
526
- };
527
- }
528
- const range = LENGTH_LIMIT_RANGES[type];
529
- if (range === undefined) {
530
- return {
531
- message: `Field '${fieldName}' of type '${type}' does not accept 'lengthLimit'`,
532
- instructions: "'lengthLimit' applies only to STRING, MULTILINE_TEXT, and MULTILINE_MAX. Remove it or change the field type."
533
- };
534
- }
535
- const [min, max] = range;
536
- if (rec.lengthLimit < min || rec.lengthLimit > max) {
537
- return {
538
- message: `Field '${fieldName}' 'lengthLimit' ${rec.lengthLimit} is outside the allowed range for type '${type}'`,
539
- instructions: `'lengthLimit' on '${type}' must be between ${min} and ${max}. MULTILINE_MAX 'lengthLimit' is a UTF-16 byte budget (≈2 per char).`
540
- };
541
- }
542
- }
543
- if (rec.maxValue !== undefined || rec.minValue !== undefined) {
544
- if (type !== "DECIMAL" && type !== "AUTO_NUMBER") {
545
- const which = rec.maxValue !== undefined ? "maxValue" : "minValue";
546
- return {
547
- message: `Field '${fieldName}' of type '${type}' does not accept '${which}'`,
548
- instructions: "'minValue' and 'maxValue' apply only to DECIMAL and AUTO_NUMBER. Remove them or change the field type."
549
- };
550
- }
551
- if (rec.maxValue !== undefined && !isNumber(rec.maxValue)) {
552
- return {
553
- message: `Field '${fieldName}' 'maxValue' must be a number`,
554
- instructions: "Pass a numeric value."
555
- };
556
- }
557
- if (rec.minValue !== undefined && !isNumber(rec.minValue)) {
558
- return {
559
- message: `Field '${fieldName}' 'minValue' must be a number`,
560
- instructions: "Pass a numeric value."
561
- };
562
- }
563
- const maxValue = rec.maxValue;
564
- if (maxValue !== undefined && (maxValue > MAX_SAFE_NUMERIC_BOUND || maxValue < -MAX_SAFE_NUMERIC_BOUND)) {
565
- return {
566
- message: `Field '${fieldName}' 'maxValue' ${rec.maxValue} is outside the supported numeric range`,
567
- instructions: `Use a value between ${-MAX_SAFE_NUMERIC_BOUND} and ${MAX_SAFE_NUMERIC_BOUND}.`
568
- };
569
- }
570
- const minValue = rec.minValue;
571
- if (minValue !== undefined && (minValue > MAX_SAFE_NUMERIC_BOUND || minValue < -MAX_SAFE_NUMERIC_BOUND)) {
572
- return {
573
- message: `Field '${fieldName}' 'minValue' ${rec.minValue} is outside the supported numeric range`,
574
- instructions: `Use a value between ${-MAX_SAFE_NUMERIC_BOUND} and ${MAX_SAFE_NUMERIC_BOUND}.`
575
- };
576
- }
577
- if (rec.maxValue !== undefined && rec.minValue !== undefined && rec.minValue > rec.maxValue) {
578
- return {
579
- message: `Field '${fieldName}' 'minValue' (${rec.minValue}) must not exceed 'maxValue' (${rec.maxValue})`,
580
- instructions: "Adjust the bounds so 'minValue <= maxValue', or drop one of the two."
581
- };
582
- }
583
- }
584
- if (rec.decimalPrecision !== undefined) {
585
- if (type !== "DECIMAL" && type !== "AUTO_NUMBER") {
586
- return {
587
- message: `Field '${fieldName}' of type '${type}' does not accept 'decimalPrecision'`,
588
- instructions: "'decimalPrecision' applies only to DECIMAL and AUTO_NUMBER. Remove it or change the field type."
589
- };
590
- }
591
- if (!isNumber(rec.decimalPrecision) || !Number.isInteger(rec.decimalPrecision) || rec.decimalPrecision < 0 || rec.decimalPrecision > 10) {
592
- return {
593
- message: `Field '${fieldName}' 'decimalPrecision' ${rec.decimalPrecision} is invalid`,
594
- instructions: "'decimalPrecision' must be an integer between 0 and 10 (0 for whole numbers, 2 for money)."
595
- };
596
- }
597
- }
598
- }
599
- return null;
600
- }
601
-
602
- // ../../common/src/entity-name-rules.ts
603
- var RESERVED_SQL_KEYWORDS_LOWER = new Set(["group", "order"]);
604
- var ENTITY_NAME_PATTERN = /^[a-zA-Z][a-zA-Z0-9_]{2,99}$/;
605
- var FIELD_NAME_PATTERN = /^[a-zA-Z][a-zA-Z0-9]{2,99}$/;
606
- var RESERVED_FIELD_NAMES_LOWER = new Set([
607
- "id",
608
- "createdby",
609
- "createtime",
610
- "updatedby",
611
- "updatetime",
612
- "recordowner",
613
- "version"
614
- ]);
615
- var RESERVED_KEYWORDS_LOWER = new Set([
1
+ // ../../../node_modules/@uipath/entity-modeler/dist/chunk-7VKIHCI7.js
2
+ var SqlTypeName = {
3
+ UNIQUEIDENTIFIER: "UNIQUEIDENTIFIER",
4
+ NVARCHAR: "NVARCHAR",
5
+ INT: "INT",
6
+ DATETIME2: "DATETIME2",
7
+ DATETIMEOFFSET: "DATETIMEOFFSET",
8
+ FLOAT: "FLOAT",
9
+ REAL: "REAL",
10
+ BIGINT: "BIGINT",
11
+ DATE: "DATE",
12
+ BIT: "BIT",
13
+ DECIMAL: "DECIMAL",
14
+ MULTILINE: "MULTILINE",
15
+ MULTILINE_MAX: "MULTILINE_MAX",
16
+ UNKNOWN: "UNKNOWN"
17
+ };
18
+ var FieldDisplayType = {
19
+ Basic: "Basic",
20
+ Relationship: "Relationship",
21
+ File: "File",
22
+ ChoiceSetSingle: "ChoiceSetSingle",
23
+ ChoiceSetMultiple: "ChoiceSetMultiple",
24
+ AutoNumber: "AutoNumber",
25
+ MultiLineText: "MultiLineText"
26
+ };
27
+ var DEFAULT_REFERENCE_TYPE = "ManyToOne";
28
+ var CSHARP_RESERVED_WORDS = [
29
+ "__arglist",
30
+ "__makeref",
31
+ "__reftype",
32
+ "__refvalue",
616
33
  "abstract",
617
34
  "as",
618
35
  "base",
@@ -660,6 +77,7 @@ var RESERVED_KEYWORDS_LOWER = new Set([
660
77
  "out",
661
78
  "override",
662
79
  "params",
80
+ "partial",
663
81
  "private",
664
82
  "protected",
665
83
  "public",
@@ -689,25 +107,42 @@ var RESERVED_KEYWORDS_LOWER = new Set([
689
107
  "virtual",
690
108
  "void",
691
109
  "volatile",
110
+ "where",
692
111
  "while",
112
+ "yield"
113
+ ];
114
+ var VB_RESERVED_WORDS = [
693
115
  "addhandler",
694
116
  "addressof",
695
117
  "alias",
696
118
  "and",
697
119
  "andalso",
120
+ "ansi",
121
+ "as",
122
+ "assembly",
123
+ "auto",
698
124
  "boolean",
699
125
  "byref",
126
+ "byte",
700
127
  "byval",
701
128
  "call",
129
+ "case",
130
+ "catch",
702
131
  "cbool",
703
132
  "cbyte",
704
133
  "cchar",
705
134
  "cdate",
706
135
  "cdbl",
707
136
  "cdec",
137
+ "char",
708
138
  "cint",
139
+ "class",
140
+ "class_finalize",
141
+ "class_initialize",
709
142
  "clng",
710
143
  "cobj",
144
+ "const",
145
+ "continue",
711
146
  "csbyte",
712
147
  "cshort",
713
148
  "csng",
@@ -717,33 +152,48 @@ var RESERVED_KEYWORDS_LOWER = new Set([
717
152
  "culng",
718
153
  "cushort",
719
154
  "date",
155
+ "decimal",
720
156
  "declare",
157
+ "default",
158
+ "delegate",
721
159
  "dim",
722
160
  "directcast",
161
+ "do",
162
+ "double",
723
163
  "each",
164
+ "else",
724
165
  "elseif",
725
166
  "end",
726
167
  "endif",
168
+ "enum",
727
169
  "erase",
728
170
  "error",
171
+ "event",
729
172
  "exit",
173
+ "false",
174
+ "finally",
175
+ "for",
730
176
  "friend",
731
177
  "function",
732
178
  "get",
733
179
  "gettype",
734
- "getxmlnamespace",
735
180
  "global",
736
181
  "gosub",
737
182
  "goto",
738
183
  "handles",
184
+ "if",
739
185
  "implements",
740
186
  "imports",
187
+ "in",
741
188
  "inherits",
742
189
  "integer",
190
+ "interface",
191
+ "is",
743
192
  "isnot",
744
193
  "let",
745
194
  "lib",
746
195
  "like",
196
+ "long",
747
197
  "loop",
748
198
  "me",
749
199
  "mod",
@@ -752,14 +202,18 @@ var RESERVED_KEYWORDS_LOWER = new Set([
752
202
  "mustoverride",
753
203
  "mybase",
754
204
  "myclass",
205
+ "namespace",
755
206
  "narrowing",
207
+ "new",
756
208
  "next",
757
209
  "not",
758
210
  "nothing",
759
211
  "notinheritable",
760
212
  "notoverridable",
213
+ "object",
761
214
  "of",
762
215
  "on",
216
+ "operator",
763
217
  "option",
764
218
  "optional",
765
219
  "or",
@@ -769,100 +223,562 @@ var RESERVED_KEYWORDS_LOWER = new Set([
769
223
  "overrides",
770
224
  "paramarray",
771
225
  "partial",
226
+ "preserve",
227
+ "private",
772
228
  "property",
229
+ "protected",
230
+ "public",
773
231
  "raiseevent",
232
+ "readonly",
774
233
  "redim",
775
234
  "rem",
776
235
  "removehandler",
777
236
  "resume",
237
+ "return",
238
+ "sbyte",
778
239
  "select",
779
240
  "set",
780
241
  "shadows",
781
242
  "shared",
243
+ "short",
782
244
  "single",
245
+ "static",
783
246
  "step",
784
247
  "stop",
248
+ "string",
785
249
  "structure",
786
250
  "sub",
787
251
  "synclock",
788
252
  "then",
253
+ "throw",
789
254
  "to",
255
+ "true",
256
+ "try",
790
257
  "trycast",
258
+ "typeof",
791
259
  "uinteger",
260
+ "ulong",
261
+ "unicode",
262
+ "until",
792
263
  "ushort",
264
+ "using",
793
265
  "variant",
794
266
  "wend",
795
267
  "when",
268
+ "while",
796
269
  "widening",
797
270
  "with",
798
271
  "withevents",
799
272
  "writeonly",
800
273
  "xor"
274
+ ];
275
+ var CSHARP_RESERVED = new Set(CSHARP_RESERVED_WORDS);
276
+ var VB_RESERVED = new Set(VB_RESERVED_WORDS);
277
+ var GA_TYPE_PAIRS = [
278
+ [FieldDisplayType.Basic, SqlTypeName.NVARCHAR],
279
+ [FieldDisplayType.Basic, SqlTypeName.DECIMAL],
280
+ [FieldDisplayType.Basic, SqlTypeName.FLOAT],
281
+ [FieldDisplayType.Basic, SqlTypeName.BIT],
282
+ [FieldDisplayType.Basic, SqlTypeName.DATE],
283
+ [FieldDisplayType.Basic, SqlTypeName.DATETIMEOFFSET],
284
+ [FieldDisplayType.Basic, SqlTypeName.UNIQUEIDENTIFIER],
285
+ [FieldDisplayType.AutoNumber, SqlTypeName.DECIMAL],
286
+ [FieldDisplayType.Basic, SqlTypeName.MULTILINE],
287
+ [FieldDisplayType.Basic, SqlTypeName.MULTILINE_MAX],
288
+ [FieldDisplayType.File, SqlTypeName.UNIQUEIDENTIFIER]
289
+ ];
290
+ var ALLOWED_TYPE_PAIRS = new Set(GA_TYPE_PAIRS.map(([display, sql]) => `${display}:${sql}`));
291
+ // ../../common/src/entity-field-rules.ts
292
+ var MAX_SAFE_NUMERIC_BOUND = 9007199254740991;
293
+ var LENGTH_LIMIT_RANGES = {
294
+ STRING: [1, 4000],
295
+ MULTILINE_TEXT: [1, 1e4],
296
+ MULTILINE_MAX: [1, 131072]
297
+ };
298
+ var MAX_MULTILINE_MAX_FIELDS = 10;
299
+ function isNumber(v) {
300
+ return typeof v === "number" && Number.isFinite(v);
301
+ }
302
+ function findInvalidFieldConstraints(fields) {
303
+ for (const f of fields) {
304
+ if (typeof f !== "object" || f === null)
305
+ continue;
306
+ const rec = f;
307
+ const type = rec.type;
308
+ if (typeof type !== "string")
309
+ continue;
310
+ const fieldName = typeof rec.name === "string" ? rec.name : "<field>";
311
+ if (rec.lengthLimit !== undefined) {
312
+ if (!isNumber(rec.lengthLimit) || !Number.isInteger(rec.lengthLimit)) {
313
+ return {
314
+ message: `Field '${fieldName}' 'lengthLimit' must be an integer`,
315
+ instructions: "Pass a positive integer within the type's range (STRING 1-4000, MULTILINE_TEXT 1-10000, MULTILINE_MAX 1-131072 UTF-16 bytes)."
316
+ };
317
+ }
318
+ const range = LENGTH_LIMIT_RANGES[type];
319
+ if (range === undefined) {
320
+ return {
321
+ message: `Field '${fieldName}' of type '${type}' does not accept 'lengthLimit'`,
322
+ instructions: "'lengthLimit' applies only to STRING, MULTILINE_TEXT, and MULTILINE_MAX. Remove it or change the field type."
323
+ };
324
+ }
325
+ const [min, max] = range;
326
+ if (rec.lengthLimit < min || rec.lengthLimit > max) {
327
+ return {
328
+ message: `Field '${fieldName}' 'lengthLimit' ${rec.lengthLimit} is outside the allowed range for type '${type}'`,
329
+ instructions: `'lengthLimit' on '${type}' must be between ${min} and ${max}. MULTILINE_MAX 'lengthLimit' is a UTF-16 byte budget (≈2 per char).`
330
+ };
331
+ }
332
+ }
333
+ if (rec.maxValue !== undefined || rec.minValue !== undefined) {
334
+ if (type !== "DECIMAL" && type !== "AUTO_NUMBER") {
335
+ const which = rec.maxValue !== undefined ? "maxValue" : "minValue";
336
+ return {
337
+ message: `Field '${fieldName}' of type '${type}' does not accept '${which}'`,
338
+ instructions: "'minValue' and 'maxValue' apply only to DECIMAL and AUTO_NUMBER. Remove them or change the field type."
339
+ };
340
+ }
341
+ if (rec.maxValue !== undefined && !isNumber(rec.maxValue)) {
342
+ return {
343
+ message: `Field '${fieldName}' 'maxValue' must be a number`,
344
+ instructions: "Pass a numeric value."
345
+ };
346
+ }
347
+ if (rec.minValue !== undefined && !isNumber(rec.minValue)) {
348
+ return {
349
+ message: `Field '${fieldName}' 'minValue' must be a number`,
350
+ instructions: "Pass a numeric value."
351
+ };
352
+ }
353
+ const maxValue = rec.maxValue;
354
+ if (maxValue !== undefined && (maxValue > MAX_SAFE_NUMERIC_BOUND || maxValue < -MAX_SAFE_NUMERIC_BOUND)) {
355
+ return {
356
+ message: `Field '${fieldName}' 'maxValue' ${rec.maxValue} is outside the supported numeric range`,
357
+ instructions: `Use a value between ${-MAX_SAFE_NUMERIC_BOUND} and ${MAX_SAFE_NUMERIC_BOUND}.`
358
+ };
359
+ }
360
+ const minValue = rec.minValue;
361
+ if (minValue !== undefined && (minValue > MAX_SAFE_NUMERIC_BOUND || minValue < -MAX_SAFE_NUMERIC_BOUND)) {
362
+ return {
363
+ message: `Field '${fieldName}' 'minValue' ${rec.minValue} is outside the supported numeric range`,
364
+ instructions: `Use a value between ${-MAX_SAFE_NUMERIC_BOUND} and ${MAX_SAFE_NUMERIC_BOUND}.`
365
+ };
366
+ }
367
+ if (rec.maxValue !== undefined && rec.minValue !== undefined && rec.minValue > rec.maxValue) {
368
+ return {
369
+ message: `Field '${fieldName}' 'minValue' (${rec.minValue}) must not exceed 'maxValue' (${rec.maxValue})`,
370
+ instructions: "Adjust the bounds so 'minValue <= maxValue', or drop one of the two."
371
+ };
372
+ }
373
+ }
374
+ if (rec.decimalPrecision !== undefined) {
375
+ if (type !== "DECIMAL" && type !== "AUTO_NUMBER") {
376
+ return {
377
+ message: `Field '${fieldName}' of type '${type}' does not accept 'decimalPrecision'`,
378
+ instructions: "'decimalPrecision' applies only to DECIMAL and AUTO_NUMBER. Remove it or change the field type."
379
+ };
380
+ }
381
+ if (!isNumber(rec.decimalPrecision) || !Number.isInteger(rec.decimalPrecision) || rec.decimalPrecision < 0 || rec.decimalPrecision > 10) {
382
+ return {
383
+ message: `Field '${fieldName}' 'decimalPrecision' ${rec.decimalPrecision} is invalid`,
384
+ instructions: "'decimalPrecision' must be an integer between 0 and 10 (0 for whole numbers, 2 for money)."
385
+ };
386
+ }
387
+ }
388
+ }
389
+ return null;
390
+ }
391
+
392
+ // src/reference-keys.ts
393
+ var LOCAL_REFERENCE_KEYS = {
394
+ referenceEntityName: ["RELATIONSHIP"],
395
+ referenceFieldName: ["RELATIONSHIP"],
396
+ choiceSetName: ["CHOICE_SET_SINGLE", "CHOICE_SET_MULTIPLE"]
397
+ };
398
+ var LOCAL_REFERENCE_KEY_NAMES = Object.keys(LOCAL_REFERENCE_KEYS);
399
+
400
+ // src/sort-names.ts
401
+ function byName(a, b) {
402
+ return a.localeCompare(b, "en");
403
+ }
404
+ function sameName(a, b) {
405
+ return a.toLowerCase() === b.toLowerCase();
406
+ }
407
+
408
+ // src/schema/folder-sentinel.ts
409
+ var UNASSIGNED_FOLDER_ID = "99999999-9999-9999-9999-999999999999";
410
+
411
+ // src/schema/author-field.ts
412
+ var REFERENCE_TYPE_PAIRS = new Set([
413
+ `${FieldDisplayType.Relationship}:${SqlTypeName.UNIQUEIDENTIFIER}`,
414
+ `${FieldDisplayType.ChoiceSetSingle}:${SqlTypeName.INT}`,
415
+ `${FieldDisplayType.ChoiceSetMultiple}:${SqlTypeName.NVARCHAR}`
801
416
  ]);
802
- function findReservedNameError(name, kind) {
803
- if (kind === "field" && RESERVED_FIELD_NAMES_LOWER.has(name.toLowerCase())) {
804
- return {
805
- message: `Field name '${name}' is reserved`,
806
- instructions: "The following field names are reserved by the platform (case-insensitive): Id, CreatedBy, CreateTime, UpdatedBy, UpdateTime, RecordOwner, Version. Pick a different name."
807
- };
417
+ var REFERENCE_TYPE_MAP = {
418
+ RELATIONSHIP: [FieldDisplayType.Relationship, SqlTypeName.UNIQUEIDENTIFIER],
419
+ CHOICE_SET_SINGLE: [FieldDisplayType.ChoiceSetSingle, SqlTypeName.INT],
420
+ CHOICE_SET_MULTIPLE: [
421
+ FieldDisplayType.ChoiceSetMultiple,
422
+ SqlTypeName.NVARCHAR
423
+ ]
424
+ };
425
+ var TYPE_MAP = {
426
+ STRING: [FieldDisplayType.Basic, SqlTypeName.NVARCHAR],
427
+ DECIMAL: [FieldDisplayType.Basic, SqlTypeName.DECIMAL],
428
+ BOOLEAN: [FieldDisplayType.Basic, SqlTypeName.BIT],
429
+ DATE: [FieldDisplayType.Basic, SqlTypeName.DATE],
430
+ DATETIME_WITH_TZ: [FieldDisplayType.Basic, SqlTypeName.DATETIMEOFFSET],
431
+ MULTILINE_TEXT: [FieldDisplayType.Basic, SqlTypeName.MULTILINE],
432
+ MULTILINE_MAX: [FieldDisplayType.Basic, SqlTypeName.MULTILINE_MAX],
433
+ AUTO_NUMBER: [FieldDisplayType.AutoNumber, SqlTypeName.DECIMAL],
434
+ FILE: [FieldDisplayType.File, SqlTypeName.UNIQUEIDENTIFIER]
435
+ };
436
+ var AUTHORABLE_FIELD_TYPES = Object.freeze([...Object.keys(TYPE_MAP), ...Object.keys(REFERENCE_TYPE_MAP)].sort(byName));
437
+ function authoredTypeOf(field) {
438
+ const pair = `${String(field.FieldDisplayType)}:${String(field.SqlType?.Name)}`;
439
+ for (const map of [TYPE_MAP, REFERENCE_TYPE_MAP]) {
440
+ for (const [type, [display, sql]] of Object.entries(map)) {
441
+ if (`${display}:${sql}` === pair)
442
+ return type;
443
+ }
808
444
  }
809
- if (RESERVED_KEYWORDS_LOWER.has(name.toLowerCase())) {
810
- return {
811
- message: `${kind === "entity" ? "Entity" : kind === "field" ? "Field" : "Choice set"} name '${name}' is a reserved C# or VB keyword`,
812
- instructions: "Reserved keywords are rejected with RESERVED_LANGUAGE_KEYWORDS. Pick a domain-specific rename, for example 'Case' -> 'WorkItem', 'Class' -> 'Category', 'New' -> 'IsNew'."
813
- };
445
+ if (pair === `${FieldDisplayType.MultiLineText}:${SqlTypeName.MULTILINE}`)
446
+ return "MULTILINE_TEXT";
447
+ if (pair === `${FieldDisplayType.MultiLineText}:${SqlTypeName.MULTILINE_MAX}`)
448
+ return "MULTILINE_MAX";
449
+ return;
450
+ }
451
+ function sourceColumnTypeOf(field) {
452
+ return authoredTypeOf({
453
+ ...field,
454
+ FieldDisplayType: field.FieldDisplayType ?? FieldDisplayType.Basic
455
+ });
456
+ }
457
+ function basicSqlTypeNameOf(type) {
458
+ const pair = TYPE_MAP[type];
459
+ return pair?.[0] === FieldDisplayType.Basic ? pair[1] : undefined;
460
+ }
461
+ var UNSUPPORTED_SOURCE_COLUMN_INSTRUCTIONS = "A federated column is a plain STRING, DECIMAL, BOOLEAN, DATE, DATETIME_WITH_TZ, MULTILINE_TEXT or MULTILINE_MAX column; a relationship, choice-set, file or auto-number column of a source cannot be mapped. Leave it out of the source's 'fields' and out of its joins.";
462
+ var REFERENCE_FIELD_TYPES = Object.freeze(Object.keys(REFERENCE_TYPE_MAP).sort(byName));
463
+ var UNAUTHORABLE_TYPES = {
464
+ INTEGER: "use DECIMAL with decimalPrecision: 0",
465
+ BIG_INTEGER: "use DECIMAL with decimalPrecision: 0",
466
+ FLOAT: "use DECIMAL with a decimalPrecision",
467
+ DOUBLE: "use DECIMAL with a decimalPrecision",
468
+ UUID: "use STRING",
469
+ DATETIME: "use DATETIME_WITH_TZ"
470
+ };
471
+
472
+ class AuthoredFieldError extends Error {
473
+ instructions;
474
+ constructor(message, instructions) {
475
+ super(message);
476
+ this.instructions = instructions;
477
+ this.name = "AuthoredFieldError";
814
478
  }
815
- if (kind === "entity" && RESERVED_SQL_KEYWORDS_LOWER.has(name.toLowerCase())) {
816
- return {
817
- message: `Entity name '${name}' is a reserved SQL keyword`,
818
- instructions: "The platform rejects 'Order' and 'Group' as entity names. Pick a domain-specific name such as 'PurchaseOrder' or 'TeamGroup'."
819
- };
479
+ }
480
+ function buildSqlType(name, spec) {
481
+ const sqlType = { Name: name };
482
+ if (spec.lengthLimit != null)
483
+ sqlType.LengthLimit = spec.lengthLimit;
484
+ if (spec.decimalPrecision != null)
485
+ sqlType.DecimalPrecision = spec.decimalPrecision;
486
+ if (spec.maxValue != null)
487
+ sqlType.MaxValue = spec.maxValue;
488
+ if (spec.minValue != null)
489
+ sqlType.MinValue = spec.minValue;
490
+ return sqlType;
491
+ }
492
+ var DEFAULT_VALUE_SHAPES = {
493
+ BOOLEAN: '"true" or "false"',
494
+ DECIMAL: 'a number in quotes, e.g. "0"',
495
+ AUTO_NUMBER: 'a number in quotes, e.g. "0"'
496
+ };
497
+ function assertDefaultValue(spec, checkContent) {
498
+ const value = spec.defaultValue;
499
+ if (value === undefined || value === null) {
500
+ return;
501
+ }
502
+ if (!checkContent) {
503
+ return;
504
+ }
505
+ if (typeof value !== "string") {
506
+ const shape = DEFAULT_VALUE_SHAPES[spec.type] ?? "a string";
507
+ throw new AuthoredFieldError(`Field '${spec.name}': 'defaultValue' must be a string or null`, `Received ${JSON.stringify(value)}. Entity documents store every default as text, whatever the field type — for ${spec.type} pass ${shape}, or null to clear it.`);
508
+ }
509
+ if (spec.type === "BOOLEAN" && value.toLowerCase() !== "true" && value.toLowerCase() !== "false") {
510
+ throw new AuthoredFieldError(`Field '${spec.name}': 'defaultValue' ${JSON.stringify(value)} is not a boolean`, 'A BOOLEAN default is the text "true" or "false".');
511
+ }
512
+ if ((spec.type === "DECIMAL" || spec.type === "AUTO_NUMBER") && (value.trim() === "" || !Number.isFinite(Number(value)))) {
513
+ throw new AuthoredFieldError(`Field '${spec.name}': 'defaultValue' ${JSON.stringify(value)} is not a number`, `A ${spec.type} default is a number written as text, e.g. "0".`);
820
514
  }
821
- return null;
822
515
  }
823
- function validateNameFormat(name, kind) {
824
- const pattern = kind === "field" ? FIELD_NAME_PATTERN : ENTITY_NAME_PATTERN;
825
- if (pattern.test(name)) {
826
- return null;
516
+ function authorField(spec, options = {}) {
517
+ assertReferenceKeysMatchType(spec);
518
+ if (REFERENCE_TYPE_MAP[spec.type] !== undefined) {
519
+ return authorReferenceField(spec);
520
+ }
521
+ const pair = TYPE_MAP[spec.type];
522
+ if (pair === undefined) {
523
+ const redirect = UNAUTHORABLE_TYPES[spec.type];
524
+ throw new AuthoredFieldError(`Field '${spec.name}' has unsupported type '${spec.type}'`, redirect === undefined ? `Supported types: ${AUTHORABLE_FIELD_TYPES.join(", ")}.` : `${redirect}. Supported types: ${AUTHORABLE_FIELD_TYPES.join(", ")}.`);
525
+ }
526
+ const [fieldDisplayType, sqlTypeName] = pair;
527
+ const pairKey = `${fieldDisplayType}:${sqlTypeName}`;
528
+ if (!ALLOWED_TYPE_PAIRS.has(pairKey)) {
529
+ throw new AuthoredFieldError(`Internal: type '${spec.type}' maps to ${pairKey}, which is not an allowed pair`, "This is a defect in author-field.ts — the type map has drifted from GA_TYPE_PAIRS.");
827
530
  }
531
+ assertScalars(spec);
532
+ assertDefaultValue(spec, options.defaultValueFromCaller !== false);
533
+ assertConstraints(spec);
828
534
  return {
829
- message: `Invalid ${kind} name '${name}'`,
830
- instructions: kind === "field" ? "Field names must start with a letter, contain only letters and digits (no underscores), and be 3-100 characters long." : "Names must start with a letter, contain only letters, digits, and underscores, and be 3-100 characters long."
535
+ Name: spec.name,
536
+ DisplayName: spec.displayName ?? spec.name,
537
+ SqlType: buildSqlType(sqlTypeName, spec),
538
+ IsRequired: spec.isRequired ?? false,
539
+ IsUnique: spec.isUnique ?? false,
540
+ IsPrimaryKey: false,
541
+ IsForeignKey: false,
542
+ IsExternalField: false,
543
+ IsHiddenField: false,
544
+ FieldCategoryId: 0,
545
+ ReferenceType: DEFAULT_REFERENCE_TYPE,
546
+ Transformation: null,
547
+ IsEncrypted: false,
548
+ Description: spec.description ?? "",
549
+ IsSystemField: false,
550
+ FieldDisplayType: fieldDisplayType,
551
+ DefaultValue: spec.defaultValue ?? null,
552
+ IsAttachment: false,
553
+ IsRbacEnabled: false,
554
+ IsModelReserved: false,
555
+ ReferenceChoiceSet: null,
556
+ ReferenceEntity: null,
557
+ ReferenceField: null,
558
+ ReferenceName: null
831
559
  };
832
560
  }
833
-
834
- // ../../../node_modules/@uipath/entity-modeler/dist/chunk-7VKIHCI7.js
835
- var SqlTypeName = {
836
- UNIQUEIDENTIFIER: "UNIQUEIDENTIFIER",
837
- NVARCHAR: "NVARCHAR",
838
- INT: "INT",
839
- DATETIME2: "DATETIME2",
840
- DATETIMEOFFSET: "DATETIMEOFFSET",
841
- FLOAT: "FLOAT",
842
- REAL: "REAL",
843
- BIGINT: "BIGINT",
844
- DATE: "DATE",
845
- BIT: "BIT",
846
- DECIMAL: "DECIMAL",
847
- MULTILINE: "MULTILINE",
848
- MULTILINE_MAX: "MULTILINE_MAX",
849
- UNKNOWN: "UNKNOWN"
850
- };
851
- var FieldDisplayType = {
852
- Basic: "Basic",
853
- Relationship: "Relationship",
854
- File: "File",
855
- ChoiceSetSingle: "ChoiceSetSingle",
856
- ChoiceSetMultiple: "ChoiceSetMultiple",
857
- AutoNumber: "AutoNumber",
858
- MultiLineText: "MultiLineText"
561
+ function assertScalars(spec) {
562
+ for (const [key, value] of [
563
+ ["isRequired", spec.isRequired],
564
+ ["isUnique", spec.isUnique]
565
+ ]) {
566
+ if (value !== undefined && typeof value !== "boolean") {
567
+ throw new AuthoredFieldError(`Field '${spec.name}': '${key}' must be true or false`, `Received ${JSON.stringify(value)}. Use a JSON boolean, not a string.`);
568
+ }
569
+ }
570
+ for (const [key, value] of [
571
+ ["displayName", spec.displayName],
572
+ ["description", spec.description]
573
+ ]) {
574
+ if (value !== undefined && typeof value !== "string") {
575
+ throw new AuthoredFieldError(`Field '${spec.name}': '${key}' must be a string`, `Received ${JSON.stringify(value)}.`);
576
+ }
577
+ }
578
+ }
579
+ function assertConstraints(spec) {
580
+ const constraintError = findInvalidFieldConstraints([
581
+ {
582
+ name: spec.name,
583
+ type: spec.type,
584
+ ...spec.lengthLimit != null && {
585
+ lengthLimit: spec.lengthLimit
586
+ },
587
+ ...spec.decimalPrecision != null && {
588
+ decimalPrecision: spec.decimalPrecision
589
+ },
590
+ ...spec.maxValue != null && { maxValue: spec.maxValue },
591
+ ...spec.minValue != null && { minValue: spec.minValue }
592
+ }
593
+ ]);
594
+ if (constraintError) {
595
+ throw new AuthoredFieldError(constraintError.message, constraintError.instructions);
596
+ }
597
+ }
598
+ var REFERENCE_KEYS_BY_TYPE = Object.entries(LOCAL_REFERENCE_KEYS);
599
+ function assertReferenceKeysMatchType(spec) {
600
+ for (const [key, types] of REFERENCE_KEYS_BY_TYPE) {
601
+ if (spec[key] !== undefined && !types.includes(spec.type)) {
602
+ throw new AuthoredFieldError(`Field '${spec.name}': '${key}' applies only to ${types.join(" and ")} fields`, `The field's type is '${spec.type}'. Remove '${key}', or change the type.`);
603
+ }
604
+ }
605
+ }
606
+ function requiredName(spec, key, what) {
607
+ const value = spec[key];
608
+ if (typeof value !== "string" || value.trim() === "") {
609
+ throw new AuthoredFieldError(`Field '${spec.name}' (type '${spec.type}') requires '${key}'`, `Set '${key}' to the name of the ${what} in this solution${key === "choiceSetName" ? " (create one with 'uip df choice-sets create <Name> --local')" : ""}.`);
610
+ }
611
+ return value;
612
+ }
613
+ function referenceTargetShape(target) {
614
+ const isEntity = target.kind === "entity";
615
+ return {
616
+ Name: target.name,
617
+ DisplayName: target.displayName,
618
+ EntityTypeId: isEntity ? 0 : 1,
619
+ EntityType: isEntity ? "Entity" : "ChoiceSet",
620
+ TemplateName: null,
621
+ Description: null,
622
+ FolderId: typeof target.folderId === "string" && target.folderId !== "" ? target.folderId : UNASSIGNED_FOLDER_ID,
623
+ Fields: null,
624
+ ExternalFields: null,
625
+ SourceJoinCriterias: null,
626
+ RecordCount: null,
627
+ StorageSizeInMB: null,
628
+ UsedStorageSizeInMB: null,
629
+ AttachmentSizeInByte: null,
630
+ IsRbacEnabled: false,
631
+ IsInsightsEnabled: false,
632
+ ConcurrencyMode: null,
633
+ InvalidIdentifiers: [],
634
+ IsModelReserved: false,
635
+ CategoryId: null,
636
+ Folder: null,
637
+ SubType: null,
638
+ Id: target.id,
639
+ UpdateTime: null
640
+ };
641
+ }
642
+ function referenceFieldShape(target) {
643
+ const id = typeof target.Id === "string" && target.Id !== "" ? target.Id : null;
644
+ const idKey = id === null ? {} : { Id: id };
645
+ const sqlType = target.SqlType ?? { Name: SqlTypeName.UNIQUEIDENTIFIER };
646
+ return {
647
+ ...idKey,
648
+ Definition: {
649
+ ...idKey,
650
+ Name: target.Name,
651
+ IsPrimaryKey: false,
652
+ IsForeignKey: false,
653
+ IsExternalField: false,
654
+ IsHiddenField: false,
655
+ FieldCategoryId: 0,
656
+ IsUnique: false,
657
+ ReferenceName: null,
658
+ ReferenceEntity: null,
659
+ ReferenceChoiceSet: null,
660
+ ReferenceField: null,
661
+ ReferenceType: DEFAULT_REFERENCE_TYPE,
662
+ SqlType: fullSqlType(sqlType.Name, sqlType),
663
+ Transformation: null,
664
+ IsRequired: false,
665
+ IsEncrypted: false,
666
+ DisplayName: target.DisplayName ?? target.Name,
667
+ Description: null,
668
+ IsSystemField: false,
669
+ DefaultValue: null,
670
+ IsAttachment: false,
671
+ IsRbacEnabled: false,
672
+ IsModelReserved: false
673
+ }
674
+ };
675
+ }
676
+ function fullSqlType(name, from = {}) {
677
+ return {
678
+ Name: name,
679
+ LengthLimit: from.LengthLimit ?? null,
680
+ MaxValue: from.MaxValue ?? null,
681
+ MinValue: from.MinValue ?? null,
682
+ DecimalPrecision: from.DecimalPrecision ?? null
683
+ };
684
+ }
685
+ var REFERENCE_SQL_TYPES = {
686
+ RELATIONSHIP: fullSqlType(SqlTypeName.UNIQUEIDENTIFIER, {
687
+ LengthLimit: 300
688
+ }),
689
+ CHOICE_SET_SINGLE: fullSqlType(SqlTypeName.INT, {
690
+ MaxValue: 1000000000000,
691
+ MinValue: -1000000000000
692
+ }),
693
+ CHOICE_SET_MULTIPLE: fullSqlType(SqlTypeName.NVARCHAR, {
694
+ LengthLimit: 4000
695
+ })
859
696
  };
860
- var DEFAULT_REFERENCE_TYPE = "ManyToOne";
861
- var CSHARP_RESERVED_WORDS = [
862
- "__arglist",
863
- "__makeref",
864
- "__reftype",
865
- "__refvalue",
697
+ function authorReferenceField(spec) {
698
+ const pair = REFERENCE_TYPE_MAP[spec.type];
699
+ if (pair === undefined) {
700
+ throw new AuthoredFieldError(`Internal: '${spec.type}' is not a reference type`, "This is a defect in author-field.ts.");
701
+ }
702
+ const [fieldDisplayType, sqlTypeName] = pair;
703
+ const pairKey = `${fieldDisplayType}:${sqlTypeName}`;
704
+ if (!ALLOWED_TYPE_PAIRS.has(pairKey) && !REFERENCE_TYPE_PAIRS.has(pairKey)) {
705
+ throw new AuthoredFieldError(`Internal: type '${spec.type}' maps to ${pairKey}, which is not an allowed pair`, "This is a defect in author-field.ts — the reference type map has drifted from REFERENCE_TYPE_PAIRS.");
706
+ }
707
+ assertScalars(spec);
708
+ assertConstraints(spec);
709
+ if (spec.defaultValue != null) {
710
+ throw new AuthoredFieldError(`Field '${spec.name}' (type '${spec.type}') cannot have a 'defaultValue'`, "Reference fields hold the id of a record or a choice; remove 'defaultValue'.");
711
+ }
712
+ const sqlType = { ...REFERENCE_SQL_TYPES[spec.type] };
713
+ const isRelationship = spec.type === "RELATIONSHIP";
714
+ let referenceEntity = null;
715
+ let referenceField = null;
716
+ let referenceChoiceSet = null;
717
+ if (isRelationship) {
718
+ const target = requiredName(spec, "referenceEntityName", "entity");
719
+ const fieldName = spec.referenceFieldName ?? "Id";
720
+ if (typeof fieldName !== "string" || fieldName.trim() === "") {
721
+ throw new AuthoredFieldError(`Field '${spec.name}': 'referenceFieldName' must be a non-empty string`, `Received ${JSON.stringify(spec.referenceFieldName)}. Name a field of '${target}', or omit it for 'Id'.`);
722
+ }
723
+ referenceEntity = referenceTargetShape({
724
+ name: target,
725
+ displayName: target,
726
+ kind: "entity",
727
+ id: null
728
+ });
729
+ referenceField = referenceFieldShape({ Name: fieldName });
730
+ } else {
731
+ referenceChoiceSet = referenceTargetShape({
732
+ name: requiredName(spec, "choiceSetName", "choice set"),
733
+ displayName: null,
734
+ kind: "choiceSet",
735
+ id: null
736
+ });
737
+ }
738
+ const field = {
739
+ Name: spec.name,
740
+ IsPrimaryKey: false,
741
+ IsForeignKey: isRelationship,
742
+ IsExternalField: false,
743
+ IsHiddenField: false,
744
+ FieldCategoryId: 0,
745
+ IsUnique: spec.isUnique ?? false,
746
+ ReferenceName: isRelationship ? `fk_${spec.name}_${globalThis.crypto.randomUUID()}` : null,
747
+ ReferenceEntity: referenceEntity,
748
+ ReferenceChoiceSet: referenceChoiceSet,
749
+ ReferenceField: referenceField,
750
+ ReferenceType: DEFAULT_REFERENCE_TYPE,
751
+ SqlType: sqlType,
752
+ Transformation: null,
753
+ IsRequired: spec.isRequired ?? false,
754
+ IsEncrypted: false,
755
+ DisplayName: spec.displayName ?? spec.name,
756
+ Description: spec.description ?? "",
757
+ IsSystemField: false,
758
+ FieldDisplayType: fieldDisplayType,
759
+ ...!isRelationship && { ChoiceSetId: null },
760
+ DefaultValue: null,
761
+ IsAttachment: false,
762
+ IsRbacEnabled: false,
763
+ IsModelReserved: false
764
+ };
765
+ return field;
766
+ }
767
+
768
+ // ../../common/src/entity-name-rules.ts
769
+ var RESERVED_SQL_KEYWORDS_LOWER = new Set(["group", "order"]);
770
+ var ENTITY_NAME_PATTERN = /^[a-zA-Z][a-zA-Z0-9_]{2,99}$/;
771
+ var FIELD_NAME_PATTERN2 = /^[a-zA-Z][a-zA-Z0-9]{2,99}$/;
772
+ var RESERVED_FIELD_NAMES_LOWER = new Set([
773
+ "id",
774
+ "createdby",
775
+ "createtime",
776
+ "updatedby",
777
+ "updatetime",
778
+ "recordowner",
779
+ "version"
780
+ ]);
781
+ var RESERVED_KEYWORDS_LOWER = new Set([
866
782
  "abstract",
867
783
  "as",
868
784
  "base",
@@ -910,7 +826,6 @@ var CSHARP_RESERVED_WORDS = [
910
826
  "out",
911
827
  "override",
912
828
  "params",
913
- "partial",
914
829
  "private",
915
830
  "protected",
916
831
  "public",
@@ -940,42 +855,25 @@ var CSHARP_RESERVED_WORDS = [
940
855
  "virtual",
941
856
  "void",
942
857
  "volatile",
943
- "where",
944
858
  "while",
945
- "yield"
946
- ];
947
- var VB_RESERVED_WORDS = [
948
859
  "addhandler",
949
860
  "addressof",
950
861
  "alias",
951
862
  "and",
952
863
  "andalso",
953
- "ansi",
954
- "as",
955
- "assembly",
956
- "auto",
957
864
  "boolean",
958
865
  "byref",
959
- "byte",
960
866
  "byval",
961
867
  "call",
962
- "case",
963
- "catch",
964
868
  "cbool",
965
869
  "cbyte",
966
870
  "cchar",
967
871
  "cdate",
968
872
  "cdbl",
969
873
  "cdec",
970
- "char",
971
874
  "cint",
972
- "class",
973
- "class_finalize",
974
- "class_initialize",
975
875
  "clng",
976
876
  "cobj",
977
- "const",
978
- "continue",
979
877
  "csbyte",
980
878
  "cshort",
981
879
  "csng",
@@ -985,48 +883,33 @@ var VB_RESERVED_WORDS = [
985
883
  "culng",
986
884
  "cushort",
987
885
  "date",
988
- "decimal",
989
886
  "declare",
990
- "default",
991
- "delegate",
992
887
  "dim",
993
888
  "directcast",
994
- "do",
995
- "double",
996
889
  "each",
997
- "else",
998
890
  "elseif",
999
891
  "end",
1000
892
  "endif",
1001
- "enum",
1002
893
  "erase",
1003
894
  "error",
1004
- "event",
1005
895
  "exit",
1006
- "false",
1007
- "finally",
1008
- "for",
1009
896
  "friend",
1010
897
  "function",
1011
898
  "get",
1012
899
  "gettype",
900
+ "getxmlnamespace",
1013
901
  "global",
1014
902
  "gosub",
1015
903
  "goto",
1016
904
  "handles",
1017
- "if",
1018
905
  "implements",
1019
906
  "imports",
1020
- "in",
1021
907
  "inherits",
1022
908
  "integer",
1023
- "interface",
1024
- "is",
1025
909
  "isnot",
1026
910
  "let",
1027
911
  "lib",
1028
912
  "like",
1029
- "long",
1030
913
  "loop",
1031
914
  "me",
1032
915
  "mod",
@@ -1035,18 +918,14 @@ var VB_RESERVED_WORDS = [
1035
918
  "mustoverride",
1036
919
  "mybase",
1037
920
  "myclass",
1038
- "namespace",
1039
921
  "narrowing",
1040
- "new",
1041
922
  "next",
1042
923
  "not",
1043
924
  "nothing",
1044
925
  "notinheritable",
1045
926
  "notoverridable",
1046
- "object",
1047
927
  "of",
1048
928
  "on",
1049
- "operator",
1050
929
  "option",
1051
930
  "optional",
1052
931
  "or",
@@ -1056,544 +935,1137 @@ var VB_RESERVED_WORDS = [
1056
935
  "overrides",
1057
936
  "paramarray",
1058
937
  "partial",
1059
- "preserve",
1060
- "private",
1061
938
  "property",
1062
- "protected",
1063
- "public",
1064
939
  "raiseevent",
1065
- "readonly",
1066
940
  "redim",
1067
941
  "rem",
1068
942
  "removehandler",
1069
943
  "resume",
1070
- "return",
1071
- "sbyte",
1072
944
  "select",
1073
945
  "set",
1074
946
  "shadows",
1075
947
  "shared",
1076
- "short",
1077
948
  "single",
1078
- "static",
1079
949
  "step",
1080
950
  "stop",
1081
- "string",
1082
951
  "structure",
1083
952
  "sub",
1084
953
  "synclock",
1085
954
  "then",
1086
- "throw",
1087
955
  "to",
1088
- "true",
1089
- "try",
1090
956
  "trycast",
1091
- "typeof",
1092
957
  "uinteger",
1093
- "ulong",
1094
- "unicode",
1095
- "until",
1096
958
  "ushort",
1097
- "using",
1098
959
  "variant",
1099
960
  "wend",
1100
961
  "when",
1101
- "while",
1102
962
  "widening",
1103
963
  "with",
1104
964
  "withevents",
1105
965
  "writeonly",
1106
966
  "xor"
1107
- ];
1108
- var CSHARP_RESERVED = new Set(CSHARP_RESERVED_WORDS);
1109
- var VB_RESERVED = new Set(VB_RESERVED_WORDS);
1110
- var GA_TYPE_PAIRS = [
1111
- [FieldDisplayType.Basic, SqlTypeName.NVARCHAR],
1112
- [FieldDisplayType.Basic, SqlTypeName.DECIMAL],
1113
- [FieldDisplayType.Basic, SqlTypeName.FLOAT],
1114
- [FieldDisplayType.Basic, SqlTypeName.BIT],
1115
- [FieldDisplayType.Basic, SqlTypeName.DATE],
1116
- [FieldDisplayType.Basic, SqlTypeName.DATETIMEOFFSET],
1117
- [FieldDisplayType.Basic, SqlTypeName.UNIQUEIDENTIFIER],
1118
- [FieldDisplayType.AutoNumber, SqlTypeName.DECIMAL],
1119
- [FieldDisplayType.Basic, SqlTypeName.MULTILINE],
1120
- [FieldDisplayType.Basic, SqlTypeName.MULTILINE_MAX],
1121
- [FieldDisplayType.File, SqlTypeName.UNIQUEIDENTIFIER]
1122
- ];
1123
- var ALLOWED_TYPE_PAIRS = new Set(GA_TYPE_PAIRS.map(([display, sql]) => `${display}:${sql}`));
1124
- // src/sort-names.ts
1125
- function byName(a, b) {
1126
- return a.localeCompare(b, "en");
967
+ ]);
968
+ function findReservedNameError(name, kind) {
969
+ if (kind === "field" && RESERVED_FIELD_NAMES_LOWER.has(name.toLowerCase())) {
970
+ return {
971
+ message: `Field name '${name}' is reserved`,
972
+ instructions: "The following field names are reserved by the platform (case-insensitive): Id, CreatedBy, CreateTime, UpdatedBy, UpdateTime, RecordOwner, Version. Pick a different name."
973
+ };
974
+ }
975
+ if (RESERVED_KEYWORDS_LOWER.has(name.toLowerCase())) {
976
+ return {
977
+ message: `${kind === "entity" ? "Entity" : kind === "field" ? "Field" : "Choice set"} name '${name}' is a reserved C# or VB keyword`,
978
+ instructions: "Reserved keywords are rejected with RESERVED_LANGUAGE_KEYWORDS. Pick a domain-specific rename, for example 'Case' -> 'WorkItem', 'Class' -> 'Category', 'New' -> 'IsNew'."
979
+ };
980
+ }
981
+ if (kind === "entity" && RESERVED_SQL_KEYWORDS_LOWER.has(name.toLowerCase())) {
982
+ return {
983
+ message: `Entity name '${name}' is a reserved SQL keyword`,
984
+ instructions: "The platform rejects 'Order' and 'Group' as entity names. Pick a domain-specific name such as 'PurchaseOrder' or 'TeamGroup'."
985
+ };
986
+ }
987
+ return null;
988
+ }
989
+ function validateNameFormat(name, kind) {
990
+ const pattern = kind === "field" ? FIELD_NAME_PATTERN2 : ENTITY_NAME_PATTERN;
991
+ if (pattern.test(name)) {
992
+ return null;
993
+ }
994
+ return {
995
+ message: `Invalid ${kind} name '${name}'`,
996
+ instructions: kind === "field" ? "Field names must start with a letter, contain only letters and digits (no underscores), and be 3-100 characters long." : "Names must start with a letter, contain only letters, digits, and underscores, and be 3-100 characters long."
997
+ };
1127
998
  }
1128
999
 
1129
- // src/schema/author-field.ts
1130
- var TYPE_MAP = {
1131
- STRING: [FieldDisplayType.Basic, SqlTypeName.NVARCHAR],
1132
- DECIMAL: [FieldDisplayType.Basic, SqlTypeName.DECIMAL],
1133
- BOOLEAN: [FieldDisplayType.Basic, SqlTypeName.BIT],
1134
- DATE: [FieldDisplayType.Basic, SqlTypeName.DATE],
1135
- DATETIME_WITH_TZ: [FieldDisplayType.Basic, SqlTypeName.DATETIMEOFFSET],
1136
- MULTILINE_TEXT: [FieldDisplayType.Basic, SqlTypeName.MULTILINE],
1137
- MULTILINE_MAX: [FieldDisplayType.Basic, SqlTypeName.MULTILINE_MAX],
1138
- AUTO_NUMBER: [FieldDisplayType.AutoNumber, SqlTypeName.DECIMAL],
1139
- FILE: [FieldDisplayType.File, SqlTypeName.UNIQUEIDENTIFIER]
1000
+ // src/schema/create-entity-skeleton.ts
1001
+ function isLocallyAuthored(entity) {
1002
+ return entity.FolderId === UNASSIGNED_FOLDER_ID;
1003
+ }
1004
+ var SYSTEM_FIELD_DEFAULTS = {
1005
+ IsPrimaryKey: false,
1006
+ IsForeignKey: false,
1007
+ IsExternalField: false,
1008
+ IsHiddenField: true,
1009
+ FieldCategoryId: 0,
1010
+ IsUnique: false,
1011
+ ReferenceType: "ManyToOne",
1012
+ Transformation: null,
1013
+ IsRequired: false,
1014
+ IsEncrypted: false,
1015
+ Description: "",
1016
+ IsSystemField: true,
1017
+ FieldDisplayType: FieldDisplayType.Basic,
1018
+ IsAttachment: false,
1019
+ IsRbacEnabled: false,
1020
+ IsModelReserved: false
1140
1021
  };
1141
- var AUTHORABLE_FIELD_TYPES = Object.freeze(Object.keys(TYPE_MAP).sort(byName));
1142
- var UNAUTHORABLE_TYPES = {
1143
- CHOICE_SET_SINGLE: "choice-set fields are not authorable locally — add the field in Data Fabric",
1144
- CHOICE_SET_MULTIPLE: "choice-set fields are not authorable locally — add the field in Data Fabric",
1145
- RELATIONSHIP: "relationship fields are not authorable locally — add the field in Data Fabric",
1146
- INTEGER: "use DECIMAL with decimalPrecision: 0",
1147
- BIG_INTEGER: "use DECIMAL with decimalPrecision: 0",
1148
- FLOAT: "use DECIMAL with a decimalPrecision",
1149
- DOUBLE: "use DECIMAL with a decimalPrecision",
1150
- UUID: "use STRING",
1151
- DATETIME: "use DATETIME_WITH_TZ"
1022
+ var SYSTEM_FIELD_TEMPLATES = [
1023
+ {
1024
+ ...SYSTEM_FIELD_DEFAULTS,
1025
+ Name: "Id",
1026
+ DisplayName: "Id",
1027
+ IsPrimaryKey: true,
1028
+ SqlType: { Name: SqlTypeName.UNIQUEIDENTIFIER }
1029
+ },
1030
+ {
1031
+ ...SYSTEM_FIELD_DEFAULTS,
1032
+ Name: "CreateTime",
1033
+ DisplayName: "CreateTime",
1034
+ SqlType: { Name: SqlTypeName.DATETIMEOFFSET }
1035
+ },
1036
+ {
1037
+ ...SYSTEM_FIELD_DEFAULTS,
1038
+ Name: "CreatedBy",
1039
+ DisplayName: "CreatedBy",
1040
+ FieldDisplayType: FieldDisplayType.Relationship,
1041
+ SqlType: { Name: SqlTypeName.UNIQUEIDENTIFIER }
1042
+ },
1043
+ {
1044
+ ...SYSTEM_FIELD_DEFAULTS,
1045
+ Name: "UpdateTime",
1046
+ DisplayName: "UpdateTime",
1047
+ SqlType: { Name: SqlTypeName.DATETIMEOFFSET }
1048
+ },
1049
+ {
1050
+ ...SYSTEM_FIELD_DEFAULTS,
1051
+ Name: "UpdatedBy",
1052
+ DisplayName: "UpdatedBy",
1053
+ FieldDisplayType: FieldDisplayType.Relationship,
1054
+ SqlType: { Name: SqlTypeName.UNIQUEIDENTIFIER }
1055
+ }
1056
+ ];
1057
+ function createEntitySkeleton(name) {
1058
+ return {
1059
+ Id: globalThis.crypto.randomUUID(),
1060
+ Name: name,
1061
+ DisplayName: name,
1062
+ EntityTypeId: 0,
1063
+ EntityType: "Entity",
1064
+ Description: "",
1065
+ FolderId: UNASSIGNED_FOLDER_ID,
1066
+ Fields: SYSTEM_FIELD_TEMPLATES.map((template) => ({
1067
+ ...template,
1068
+ SqlType: { ...template.SqlType }
1069
+ })),
1070
+ Data: null,
1071
+ ExternalFields: null,
1072
+ SourceJoinCriterias: null,
1073
+ RecordCount: 0,
1074
+ StorageSizeInMB: null,
1075
+ UsedStorageSizeInMB: null,
1076
+ AttachmentSizeInByte: null,
1077
+ IsRbacEnabled: false,
1078
+ InvalidIdentifiers: [],
1079
+ IsModelReserved: false,
1080
+ CategoryId: null
1081
+ };
1082
+ }
1083
+
1084
+ // src/schema/validate-entity.ts
1085
+ var DIAGNOSTIC_CODES = {
1086
+ entityNameInvalid: "ENTITY_NAME_INVALID",
1087
+ entityNameNotUnique: "ENTITY_NAME_NOT_UNIQUE",
1088
+ fieldNameInvalid: "FIELD_NAME_INVALID",
1089
+ duplicateFieldName: "DUPLICATE_FIELD_NAME",
1090
+ fieldTypeNotAllowed: "FIELD_TYPE_NOT_ALLOWED",
1091
+ nameReserved: "NAME_RESERVED",
1092
+ systemFieldMissing: "SYSTEM_FIELD_MISSING",
1093
+ systemFieldModified: "SYSTEM_FIELD_MODIFIED",
1094
+ fieldsMalformed: "FIELDS_MALFORMED",
1095
+ tooManyMultilineMax: "TOO_MANY_MULTILINE_MAX",
1096
+ propertyTypeInvalid: "PROPERTY_TYPE_INVALID",
1097
+ referenceMissing: "REFERENCE_MISSING"
1152
1098
  };
1153
-
1154
- class AuthoredFieldError extends Error {
1155
- instructions;
1156
- constructor(message, instructions) {
1157
- super(message);
1158
- this.instructions = instructions;
1159
- this.name = "AuthoredFieldError";
1099
+ function validateEntity(entity, ctx) {
1100
+ const diagnostics = [];
1101
+ if (typeof entity?.Name !== "string") {
1102
+ return [
1103
+ {
1104
+ code: DIAGNOSTIC_CODES.entityNameInvalid,
1105
+ message: "The entity document has no 'Name'. The resource is malformed.",
1106
+ severity: "error"
1107
+ }
1108
+ ];
1109
+ }
1110
+ const entityNameFormat = validateNameFormat(entity.Name, "entity");
1111
+ if (entityNameFormat) {
1112
+ diagnostics.push({
1113
+ code: DIAGNOSTIC_CODES.entityNameInvalid,
1114
+ message: `${entityNameFormat.message}. ${entityNameFormat.instructions}`,
1115
+ severity: "error"
1116
+ });
1117
+ }
1118
+ const reservedEntityName = findReservedNameError(entity.Name, "entity");
1119
+ if (reservedEntityName) {
1120
+ diagnostics.push({
1121
+ code: DIAGNOSTIC_CODES.nameReserved,
1122
+ message: `${reservedEntityName.message}. ${reservedEntityName.instructions}`,
1123
+ severity: "error"
1124
+ });
1125
+ }
1126
+ const entityNameLower = entity.Name.toLowerCase();
1127
+ if (ctx.siblingNames.some((sibling) => sibling.toLowerCase() === entityNameLower)) {
1128
+ diagnostics.push({
1129
+ code: DIAGNOSTIC_CODES.entityNameNotUnique,
1130
+ message: `An entity named '${entity.Name}' already exists in this solution. Entity names are solution-wide unique.`,
1131
+ severity: "error"
1132
+ });
1133
+ }
1134
+ diagnostics.push(...typeProblems(entity, ENTITY_SCALARS).map((problem) => propertyTypeDiagnostic(`Entity '${entity.Name}'`, problem)));
1135
+ if (!Array.isArray(entity.Fields)) {
1136
+ diagnostics.push({
1137
+ code: DIAGNOSTIC_CODES.fieldsMalformed,
1138
+ message: "The entity document has no usable 'Fields' array. The resource is malformed.",
1139
+ severity: "error"
1140
+ });
1141
+ return diagnostics;
1142
+ }
1143
+ const seenFieldNames = new Map;
1144
+ for (const field of entity.Fields) {
1145
+ if (typeof field?.Name !== "string") {
1146
+ diagnostics.push({
1147
+ code: DIAGNOSTIC_CODES.fieldNameInvalid,
1148
+ message: "A field has no 'Name'. Every field needs one, system or custom.",
1149
+ severity: "error"
1150
+ });
1151
+ continue;
1152
+ }
1153
+ const isSystem = isSystemField(field);
1154
+ if (!SYSTEM_FIELD_NAMES.has(field.Name)) {
1155
+ diagnostics.push(...fieldTypeDiagnostics(field));
1156
+ }
1157
+ const fieldNameFormat = isSystem ? null : validateNameFormat(field.Name, "field");
1158
+ if (fieldNameFormat) {
1159
+ diagnostics.push({
1160
+ code: DIAGNOSTIC_CODES.fieldNameInvalid,
1161
+ message: `${fieldNameFormat.message}. ${fieldNameFormat.instructions}`,
1162
+ severity: "error",
1163
+ fieldName: field.Name
1164
+ });
1165
+ }
1166
+ if (!isSystem) {
1167
+ const reservedFieldName = findReservedNameError(field.Name, "field");
1168
+ if (reservedFieldName) {
1169
+ diagnostics.push({
1170
+ code: DIAGNOSTIC_CODES.nameReserved,
1171
+ message: `${reservedFieldName.message}. ${reservedFieldName.instructions}`,
1172
+ severity: "error",
1173
+ fieldName: field.Name
1174
+ });
1175
+ }
1176
+ }
1177
+ const fieldNameLower = field.Name.toLowerCase();
1178
+ if (!isSystem && typeof entity.Name === "string" && fieldNameLower === entity.Name.toLowerCase()) {
1179
+ diagnostics.push({
1180
+ code: DIAGNOSTIC_CODES.fieldNameInvalid,
1181
+ message: `Field name '${field.Name}' cannot match entity name '${entity.Name}' (names are compared case-insensitively).`,
1182
+ severity: "error",
1183
+ fieldName: field.Name
1184
+ });
1185
+ }
1186
+ const firstWithName = seenFieldNames.get(fieldNameLower);
1187
+ if (firstWithName !== undefined) {
1188
+ diagnostics.push({
1189
+ code: DIAGNOSTIC_CODES.duplicateFieldName,
1190
+ message: `Duplicate field name '${field.Name}' (names are case-insensitive; first defined as '${firstWithName}').`,
1191
+ severity: "error",
1192
+ fieldName: field.Name
1193
+ });
1194
+ } else {
1195
+ seenFieldNames.set(fieldNameLower, field.Name);
1196
+ }
1197
+ const pairKey = `${field.FieldDisplayType}:${field.SqlType?.Name}`;
1198
+ if (!isSystem && !ALLOWED_TYPE_PAIRS.has(pairKey) && !REFERENCE_TYPE_PAIRS.has(pairKey)) {
1199
+ diagnostics.push({
1200
+ code: DIAGNOSTIC_CODES.fieldTypeNotAllowed,
1201
+ message: `Field '${field.Name}' uses an unsupported type combination ` + `(${field.FieldDisplayType} / ${field.SqlType?.Name}).`,
1202
+ severity: "error",
1203
+ fieldName: field.Name
1204
+ });
1205
+ }
1206
+ if (!isSystem && REFERENCE_TYPE_PAIRS.has(pairKey)) {
1207
+ const missing = missingReference(field);
1208
+ if (missing !== undefined) {
1209
+ diagnostics.push({
1210
+ code: DIAGNOSTIC_CODES.referenceMissing,
1211
+ message: `Field '${field.Name}' (${field.FieldDisplayType}) has no ${missing}. The resource was edited by hand or is malformed; re-add the field with 'uip df entities update --local'.`,
1212
+ severity: "error",
1213
+ fieldName: field.Name
1214
+ });
1215
+ }
1216
+ }
1217
+ }
1218
+ const usableFields = entity.Fields.filter((field) => typeof field === "object" && field !== null);
1219
+ const multilineMax = usableFields.filter((field) => field.SqlType?.Name === SqlTypeName.MULTILINE_MAX);
1220
+ if (multilineMax.length > MAX_MULTILINE_MAX_FIELDS) {
1221
+ diagnostics.push({
1222
+ code: DIAGNOSTIC_CODES.tooManyMultilineMax,
1223
+ message: `Entity '${entity.Name}' defines ${multilineMax.length} MULTILINE_MAX fields; ` + `the maximum is ${MAX_MULTILINE_MAX_FIELDS}. Remove some, or use MULTILINE_TEXT where the content fits.`,
1224
+ severity: "error"
1225
+ });
1160
1226
  }
1227
+ diagnostics.push(...validateSystemFields(entity, usableFields));
1228
+ return diagnostics;
1161
1229
  }
1162
- function buildSqlType(name, spec) {
1163
- const sqlType = { Name: name };
1164
- if (spec.lengthLimit != null)
1165
- sqlType.LengthLimit = spec.lengthLimit;
1166
- if (spec.decimalPrecision != null)
1167
- sqlType.DecimalPrecision = spec.decimalPrecision;
1168
- if (spec.maxValue != null)
1169
- sqlType.MaxValue = spec.maxValue;
1170
- if (spec.minValue != null)
1171
- sqlType.MinValue = spec.minValue;
1172
- return sqlType;
1230
+ function missingReference(field) {
1231
+ const nameOf = (value) => value?.Name;
1232
+ const named = (value) => typeof value === "string" && value.trim() !== "";
1233
+ if (field.FieldDisplayType === FieldDisplayType.Relationship) {
1234
+ if (!named(nameOf(field.ReferenceEntity))) {
1235
+ return "'ReferenceEntity.Name'";
1236
+ }
1237
+ const definition = field.ReferenceField?.Definition;
1238
+ if (!named(nameOf(definition))) {
1239
+ return "'ReferenceField.Definition.Name'";
1240
+ }
1241
+ return;
1242
+ }
1243
+ return named(nameOf(field.ReferenceChoiceSet)) ? undefined : "'ReferenceChoiceSet.Name'";
1173
1244
  }
1174
- var DEFAULT_VALUE_SHAPES = {
1175
- BOOLEAN: '"true" or "false"',
1176
- DECIMAL: 'a number in quotes, e.g. "0"',
1177
- AUTO_NUMBER: 'a number in quotes, e.g. "0"'
1245
+ var SERVER_ASSIGNED_FIELD_PROPS = new Set([
1246
+ "Id",
1247
+ "CreateTime",
1248
+ "CreatedBy",
1249
+ "UpdateTime",
1250
+ "UpdatedBy"
1251
+ ]);
1252
+ function isUnmodifiedSystemField(template, actual) {
1253
+ const equal = (left, right) => JSON.stringify(left ?? null) === JSON.stringify(right ?? null);
1254
+ for (const key of Object.keys(template)) {
1255
+ if (!equal(template[key], actual[key])) {
1256
+ return false;
1257
+ }
1258
+ }
1259
+ return Object.keys(actual).every((key) => (key in template) || SERVER_ASSIGNED_FIELD_PROPS.has(key));
1260
+ }
1261
+ function validateSystemFields(entity, usableFields) {
1262
+ const diagnostics = [];
1263
+ for (const template of SYSTEM_FIELD_TEMPLATES) {
1264
+ const actual = usableFields.find((field) => field.Name === template.Name);
1265
+ if (!actual) {
1266
+ diagnostics.push({
1267
+ code: DIAGNOSTIC_CODES.systemFieldMissing,
1268
+ message: `System field '${template.Name}' is missing. System fields cannot be removed.`,
1269
+ severity: "error",
1270
+ fieldName: template.Name
1271
+ });
1272
+ continue;
1273
+ }
1274
+ if (!isUnmodifiedSystemField(template, actual)) {
1275
+ diagnostics.push({
1276
+ code: DIAGNOSTIC_CODES.systemFieldModified,
1277
+ message: `System field '${template.Name}' was modified. System fields are read-only.`,
1278
+ severity: "error",
1279
+ fieldName: template.Name
1280
+ });
1281
+ }
1282
+ }
1283
+ return diagnostics;
1284
+ }
1285
+ function isSystemField(field) {
1286
+ const { IsSystemField: flag, Name: name } = field ?? {};
1287
+ return flag === true || typeof name === "string" && SYSTEM_FIELD_NAMES.has(name);
1288
+ }
1289
+ var SYSTEM_FIELD_NAMES = new Set(SYSTEM_FIELD_TEMPLATES.map((template) => template.Name));
1290
+ var ENTITY_SCALARS = [
1291
+ { key: "DisplayName", kind: "string" },
1292
+ { key: "Description", kind: "string" },
1293
+ { key: "EntityTypeId", kind: "integer" },
1294
+ { key: "RecordCount", kind: "integer" },
1295
+ { key: "IsRbacEnabled", kind: "boolean" },
1296
+ { key: "IsModelReserved", kind: "boolean" }
1297
+ ];
1298
+ var FIELD_SCALARS = [
1299
+ { key: "DisplayName", kind: "string" },
1300
+ { key: "Description", kind: "string" },
1301
+ { key: "ReferenceType", kind: "string" },
1302
+ { key: "FieldCategoryId", kind: "integer" },
1303
+ { key: "IsRequired", kind: "boolean" },
1304
+ { key: "IsUnique", kind: "boolean" },
1305
+ { key: "IsPrimaryKey", kind: "boolean" },
1306
+ { key: "IsForeignKey", kind: "boolean" },
1307
+ { key: "IsSystemField", kind: "boolean" },
1308
+ { key: "IsExternalField", kind: "boolean" },
1309
+ { key: "IsHiddenField", kind: "boolean" },
1310
+ { key: "IsEncrypted", kind: "boolean" },
1311
+ { key: "IsAttachment", kind: "boolean" },
1312
+ { key: "IsRbacEnabled", kind: "boolean" },
1313
+ { key: "IsModelReserved", kind: "boolean" }
1314
+ ];
1315
+ var SQL_TYPE_SCALARS = [
1316
+ { key: "LengthLimit", kind: "integer", nullable: true },
1317
+ { key: "DecimalPrecision", kind: "integer", nullable: true },
1318
+ { key: "MaxValue", kind: "number", nullable: true },
1319
+ { key: "MinValue", kind: "number", nullable: true }
1320
+ ];
1321
+ function typeProblems(record, rules, prefix = "") {
1322
+ const values = record;
1323
+ return rules.filter(({ key, kind, nullable }) => {
1324
+ const value = values[key];
1325
+ if (value === undefined)
1326
+ return false;
1327
+ if (value === null)
1328
+ return !nullable;
1329
+ if (kind === "integer")
1330
+ return !Number.isInteger(value);
1331
+ return kind === "number" ? !(typeof value === "number" && Number.isFinite(value)) : typeof value !== kind;
1332
+ }).map(({ key, kind, nullable }) => `'${prefix}${key}' must be ${kind === "integer" ? "an" : "a"} ${kind}${nullable ? " or null" : ""}`);
1333
+ }
1334
+ function propertyTypeDiagnostic(subject, problem, fieldName) {
1335
+ return {
1336
+ code: DIAGNOSTIC_CODES.propertyTypeInvalid,
1337
+ message: `${subject}: ${problem}. The resource was edited by hand or is malformed.`,
1338
+ severity: "error",
1339
+ ...fieldName !== undefined && { fieldName }
1340
+ };
1341
+ }
1342
+ function fieldTypeDiagnostics(field) {
1343
+ const problems = typeProblems(field, FIELD_SCALARS);
1344
+ if (typeof field.SqlType === "object" && field.SqlType !== null) {
1345
+ problems.push(...typeProblems(field.SqlType, SQL_TYPE_SCALARS, "SqlType."));
1346
+ }
1347
+ const defaultValue = field.DefaultValue;
1348
+ const isYesNo = field.SqlType?.Name === SqlTypeName.BIT;
1349
+ if (defaultValue != null && typeof defaultValue !== "string" && !(isYesNo && typeof defaultValue === "boolean")) {
1350
+ problems.push(isYesNo ? "'DefaultValue' must be a boolean, a string or null" : "'DefaultValue' must be a string or null");
1351
+ }
1352
+ return problems.map((problem) => propertyTypeDiagnostic(`Field '${field.Name}'`, problem, field.Name));
1353
+ }
1354
+
1355
+ // src/inline/entity-references.ts
1356
+ var REFERENCE_CODES = {
1357
+ referenceTargetNotFound: "REFERENCE_TARGET_NOT_FOUND",
1358
+ choiceSetNotFound: "CHOICE_SET_NOT_FOUND",
1359
+ staleReference: "STALE_REFERENCE",
1360
+ relationshipCycle: "RELATIONSHIP_CYCLE",
1361
+ choiceSetNameTaken: "CHOICE_SET_NAME_TAKEN"
1178
1362
  };
1179
- function assertDefaultValue(spec, checkContent) {
1180
- const value = spec.defaultValue;
1181
- if (value === undefined || value === null) {
1363
+ function findCycle(nodes, adding) {
1364
+ if (sameName(adding.from, adding.to))
1182
1365
  return;
1183
- }
1184
- if (!checkContent) {
1366
+ const spelling = (name) => nodes.find((node) => sameName(node.name, name))?.name ?? name;
1367
+ const targetsOf = (name) => {
1368
+ const own = nodes.find((node) => sameName(node.name, name))?.relationshipTargets ?? [];
1369
+ const extra = sameName(name, adding.from) ? [adding.to] : [];
1370
+ return [...own, ...extra].filter((target) => !sameName(target, name));
1371
+ };
1372
+ const visited = new Set;
1373
+ const walk = (name, path) => {
1374
+ if (sameName(name, adding.from))
1375
+ return path;
1376
+ const key = name.toLowerCase();
1377
+ if (visited.has(key))
1378
+ return;
1379
+ visited.add(key);
1380
+ for (const next of targetsOf(name)) {
1381
+ const found = walk(next, [...path, spelling(next)]);
1382
+ if (found !== undefined)
1383
+ return found;
1384
+ }
1185
1385
  return;
1186
- }
1187
- if (typeof value !== "string") {
1188
- const shape = DEFAULT_VALUE_SHAPES[spec.type] ?? "a string";
1189
- throw new AuthoredFieldError(`Field '${spec.name}': 'defaultValue' must be a string or null`, `Received ${JSON.stringify(value)}. Entity documents store every default as text, whatever the field type — for ${spec.type} pass ${shape}, or null to clear it.`);
1190
- }
1191
- if (spec.type === "BOOLEAN" && value.toLowerCase() !== "true" && value.toLowerCase() !== "false") {
1192
- throw new AuthoredFieldError(`Field '${spec.name}': 'defaultValue' ${JSON.stringify(value)} is not a boolean`, 'A BOOLEAN default is the text "true" or "false".');
1193
- }
1194
- if ((spec.type === "DECIMAL" || spec.type === "AUTO_NUMBER") && (value.trim() === "" || !Number.isFinite(Number(value)))) {
1195
- throw new AuthoredFieldError(`Field '${spec.name}': 'defaultValue' ${JSON.stringify(value)} is not a number`, `A ${spec.type} default is a number written as text, e.g. "0".`);
1196
- }
1386
+ };
1387
+ return walk(adding.to, [spelling(adding.from), spelling(adding.to)]);
1197
1388
  }
1198
- function authorField(spec, options = {}) {
1199
- const pair = TYPE_MAP[spec.type];
1200
- if (pair === undefined) {
1201
- const redirect = UNAUTHORABLE_TYPES[spec.type];
1202
- throw new AuthoredFieldError(`Field '${spec.name}' has unsupported type '${spec.type}'`, redirect === undefined ? `Supported types: ${AUTHORABLE_FIELD_TYPES.join(", ")}.` : `${redirect}. Supported types: ${AUTHORABLE_FIELD_TYPES.join(", ")}.`);
1203
- }
1204
- const [fieldDisplayType, sqlTypeName] = pair;
1205
- const pairKey = `${fieldDisplayType}:${sqlTypeName}`;
1206
- if (!ALLOWED_TYPE_PAIRS.has(pairKey)) {
1207
- throw new AuthoredFieldError(`Internal: type '${spec.type}' maps to ${pairKey}, which is not an allowed pair`, "This is a defect in author-field.ts — the type map has drifted from GA_TYPE_PAIRS.");
1208
- }
1209
- for (const [key, value] of [
1210
- ["isRequired", spec.isRequired],
1211
- ["isUnique", spec.isUnique]
1212
- ]) {
1213
- if (value !== undefined && typeof value !== "boolean") {
1214
- throw new AuthoredFieldError(`Field '${spec.name}': '${key}' must be true or false`, `Received ${JSON.stringify(value)}. Use a JSON boolean, not a string.`);
1389
+ function isCustomField(field) {
1390
+ return typeof field === "object" && field !== null && !isSystemField(field);
1391
+ }
1392
+ function targetName(value) {
1393
+ const name = value?.Name;
1394
+ return typeof name === "string" && name !== "" ? name : undefined;
1395
+ }
1396
+ function relationshipFields(entity) {
1397
+ return (Array.isArray(entity.Fields) ? entity.Fields : []).filter(isCustomField).filter((field) => field.FieldDisplayType === FieldDisplayType.Relationship).map((field) => ({
1398
+ field: field.Name,
1399
+ target: targetName(field.ReferenceEntity)
1400
+ })).filter((each) => each.target !== undefined);
1401
+ }
1402
+ function relationshipTargets(entity) {
1403
+ return relationshipFields(entity).map((each) => each.target);
1404
+ }
1405
+ function choiceSetTargets(entity) {
1406
+ return (Array.isArray(entity.Fields) ? entity.Fields : []).filter(isCustomField).filter((field) => field.FieldDisplayType === FieldDisplayType.ChoiceSetSingle || field.FieldDisplayType === FieldDisplayType.ChoiceSetMultiple).map((field) => targetName(field.ReferenceChoiceSet)).filter((name) => name !== undefined);
1407
+ }
1408
+ function referenceDependencies(resourceJson) {
1409
+ const found = [];
1410
+ const add = (kind, name) => {
1411
+ if (!found.some((entry) => entry.kind === kind && sameName(entry.name, name))) {
1412
+ found.push({ kind, name });
1215
1413
  }
1414
+ };
1415
+ for (const name of choiceSetTargets(resourceJson))
1416
+ add("choiceSet", name);
1417
+ for (const name of relationshipTargets(resourceJson)) {
1418
+ if (!sameName(name, resourceJson.Name))
1419
+ add("entity", name);
1216
1420
  }
1217
- for (const [key, value] of [
1218
- ["displayName", spec.displayName],
1219
- ["description", spec.description]
1220
- ]) {
1221
- if (value !== undefined && typeof value !== "string") {
1222
- throw new AuthoredFieldError(`Field '${spec.name}': '${key}' must be a string`, `Received ${JSON.stringify(value)}.`);
1421
+ return found.sort((a, b) => byName(DEPENDENCY_KINDS[a.kind], DEPENDENCY_KINDS[b.kind]) || byName(a.name, b.name));
1422
+ }
1423
+ var DEPENDENCY_KINDS = {
1424
+ entity: "Entity",
1425
+ choiceset: "ChoiceSet",
1426
+ choiceSet: "ChoiceSet"
1427
+ };
1428
+ function withReferenceDependencies(existing, refs) {
1429
+ const owned = (kind) => typeof kind === "string" && ["entity", "choiceset"].includes(kind.toLowerCase());
1430
+ const kept = (Array.isArray(existing) ? existing : []).filter((entry) => !owned(entry?.kind));
1431
+ return [
1432
+ ...kept,
1433
+ ...refs.map((ref) => ({
1434
+ kind: DEPENDENCY_KINDS[ref.kind] ?? ref.kind,
1435
+ name: ref.name
1436
+ }))
1437
+ ];
1438
+ }
1439
+ function bindReferences(entity, targets) {
1440
+ const problems = [];
1441
+ const findEntity = (name) => sameName(name, entity.Name) ? { key: entity.Id, entity } : targets.entities.find((each) => sameName(each.entity.Name, name));
1442
+ const fields = (Array.isArray(entity.Fields) ? entity.Fields : []).map((field) => {
1443
+ if (!isCustomField(field))
1444
+ return field;
1445
+ if (field.FieldDisplayType === FieldDisplayType.Relationship) {
1446
+ const name = targetName(field.ReferenceEntity);
1447
+ if (name === undefined)
1448
+ return field;
1449
+ const target = findEntity(name);
1450
+ if (target === undefined) {
1451
+ problems.push({
1452
+ kind: "entityNotFound",
1453
+ field: field.Name,
1454
+ target: name
1455
+ });
1456
+ return field;
1457
+ }
1458
+ const wantedField = targetName(field.ReferenceField?.Definition) ?? "Id";
1459
+ const targetFields = Array.isArray(target.entity.Fields) ? target.entity.Fields : [];
1460
+ const targetField = targetFields.find((each) => typeof each?.Name === "string" && sameName(each.Name, wantedField));
1461
+ if (targetField === undefined) {
1462
+ problems.push({
1463
+ kind: "fieldNotFound",
1464
+ field: field.Name,
1465
+ target: target.entity.Name,
1466
+ targetField: wantedField,
1467
+ fields: targetFields.map((each) => each?.Name).filter((each) => typeof each === "string")
1468
+ });
1469
+ return field;
1470
+ }
1471
+ return {
1472
+ ...field,
1473
+ ReferenceEntity: referenceTargetShape({
1474
+ name: target.entity.Name,
1475
+ displayName: target.entity.DisplayName ?? null,
1476
+ kind: "entity",
1477
+ id: target.key,
1478
+ folderId: target.entity.FolderId
1479
+ }),
1480
+ ReferenceField: referenceFieldShape(targetField)
1481
+ };
1223
1482
  }
1224
- }
1225
- assertDefaultValue(spec, options.defaultValueFromCaller !== false);
1226
- const constraintError = findInvalidFieldConstraints([
1227
- {
1228
- name: spec.name,
1229
- type: spec.type,
1230
- ...spec.lengthLimit != null && {
1231
- lengthLimit: spec.lengthLimit
1232
- },
1233
- ...spec.decimalPrecision != null && {
1234
- decimalPrecision: spec.decimalPrecision
1235
- },
1236
- ...spec.maxValue != null && { maxValue: spec.maxValue },
1237
- ...spec.minValue != null && { minValue: spec.minValue }
1483
+ if (field.FieldDisplayType === FieldDisplayType.ChoiceSetSingle || field.FieldDisplayType === FieldDisplayType.ChoiceSetMultiple) {
1484
+ const name = targetName(field.ReferenceChoiceSet);
1485
+ if (name === undefined)
1486
+ return field;
1487
+ const target = targets.choiceSets.find((each) => sameName(each.name, name));
1488
+ if (target === undefined) {
1489
+ problems.push({
1490
+ kind: "choiceSetNotFound",
1491
+ field: field.Name,
1492
+ target: name
1493
+ });
1494
+ return field;
1495
+ }
1496
+ return {
1497
+ ...field,
1498
+ ReferenceChoiceSet: referenceTargetShape({
1499
+ name: target.name,
1500
+ displayName: null,
1501
+ kind: "choiceSet",
1502
+ id: target.key,
1503
+ folderId: target.folderId
1504
+ }),
1505
+ ChoiceSetId: target.key
1506
+ };
1238
1507
  }
1239
- ]);
1240
- if (constraintError) {
1241
- throw new AuthoredFieldError(constraintError.message, constraintError.instructions);
1508
+ return field;
1509
+ });
1510
+ return { entity: { ...entity, Fields: fields }, problems };
1511
+ }
1512
+ function staleReferenceFields(stored, bound) {
1513
+ const idOf = (value) => value?.Id;
1514
+ const idsOf = (field) => [
1515
+ idOf(field.ReferenceEntity),
1516
+ idOf(field.ReferenceField),
1517
+ idOf(field.ReferenceChoiceSet),
1518
+ field.ChoiceSetId
1519
+ ];
1520
+ const boundFields = Array.isArray(bound.Fields) ? bound.Fields : [];
1521
+ return (Array.isArray(stored.Fields) ? stored.Fields : []).filter(isCustomField).filter((field) => {
1522
+ const after = boundFields.find((each) => isCustomField(each) && sameName(each.Name, field.Name));
1523
+ if (after === undefined)
1524
+ return false;
1525
+ const before = idsOf(field);
1526
+ return idsOf(after).some((id, at) => id !== before[at]);
1527
+ }).map((field) => field.Name);
1528
+ }
1529
+ function referenceIssues(entity, targets) {
1530
+ const { entity: bound, problems } = bindReferences(entity, targets);
1531
+ const issues = problems.map(referenceIssueOf);
1532
+ return problems.length > 0 ? issues : staleReferenceIssues(entity, bound);
1533
+ }
1534
+ function referenceIssueOf(problem) {
1535
+ if (problem.kind === "choiceSetNotFound") {
1536
+ return {
1537
+ code: REFERENCE_CODES.choiceSetNotFound,
1538
+ fieldName: problem.field,
1539
+ message: `Field '${problem.field}' references choice set '${problem.target}', which is not in this solution.`
1540
+ };
1541
+ }
1542
+ return {
1543
+ code: REFERENCE_CODES.referenceTargetNotFound,
1544
+ fieldName: problem.field,
1545
+ message: problem.kind === "fieldNotFound" ? `Field '${problem.field}' references '${problem.target}.${problem.targetField}', which does not exist.` : `Field '${problem.field}' references entity '${problem.target}', which is not in this solution.`
1546
+ };
1547
+ }
1548
+ function staleReferenceIssues(stored, bound) {
1549
+ return staleReferenceFields(stored, bound).map((field) => ({
1550
+ code: REFERENCE_CODES.staleReference,
1551
+ fieldName: field,
1552
+ message: `Field '${field}' of '${stored.Name}' still carries the ids of a target that has since been replaced. Rebind it by writing the entity again: 'uip df entities update ${stored.Name} --local --body '{}''.`
1553
+ }));
1554
+ }
1555
+ function findRelationshipCycle(entity, others) {
1556
+ const nodes = others.map((each) => ({
1557
+ name: each.entity.Name,
1558
+ relationshipTargets: relationshipTargets(each.entity)
1559
+ }));
1560
+ const self = { name: entity.Name, relationshipTargets: [] };
1561
+ nodes.push(self);
1562
+ for (const { field, target } of relationshipFields(entity)) {
1563
+ const path = findCycle(nodes, { from: entity.Name, to: target });
1564
+ if (path !== undefined)
1565
+ return { field, path };
1566
+ self.relationshipTargets.push(target);
1567
+ }
1568
+ return;
1569
+ }
1570
+ function entityGraphIssues(entity, others, choiceSets) {
1571
+ const issues = [];
1572
+ const holder = choiceSets.find((each) => sameName(each.name, entity.Name));
1573
+ if (holder !== undefined) {
1574
+ issues.push({
1575
+ code: REFERENCE_CODES.choiceSetNameTaken,
1576
+ fieldName: "",
1577
+ message: `Entity '${entity.Name}' has the name of choice set '${holder.name}'. Entities and choice sets share one namespace in Data Fabric, regardless of case: rename one of them.`
1578
+ });
1242
1579
  }
1580
+ const cycle = findRelationshipCycle(entity, others);
1581
+ if (cycle !== undefined) {
1582
+ issues.push({
1583
+ code: REFERENCE_CODES.relationshipCycle,
1584
+ fieldName: cycle.field,
1585
+ message: `Relationship '${entity.Name}.${cycle.field}' closes a cycle: ${cycle.path.join(" → ")}. Solutions deploys entities in dependency order, and a cycle fails the deploy: remove the relationship on one side.`
1586
+ });
1587
+ }
1588
+ return issues;
1589
+ }
1590
+ // ../../common/src/telemetry/telemetry-dimensions.ts
1591
+ var BaseDimensions = {
1592
+ ApplicationName: "ApplicationName",
1593
+ ProductVersion: "ProductVersion",
1594
+ InstallationId: "InstallationId",
1595
+ CloudUserId: "CloudUserId",
1596
+ CloudTenantId: "CloudTenantId",
1597
+ CloudOrganizationId: "CloudOrganizationId",
1598
+ IsInternalUser: "IsInternalUser",
1599
+ Environment: "Environment",
1600
+ BaseUrl: "BaseUrl",
1601
+ Region: "Region",
1602
+ Agent: "Agent",
1603
+ AgentVersion: "AgentVersion",
1604
+ AgentModel: "AgentModel",
1605
+ ToolName: "ToolName",
1606
+ ToolVersion: "ToolVersion",
1607
+ ExecutionContext: "ExecutionContext",
1608
+ CiProvider: "CiProvider",
1609
+ SessionIdSource: "SessionIdSource",
1610
+ SessionId: "SessionId"
1611
+ };
1612
+ var CommandDimensions = {
1613
+ IsCommand: "IsCommand",
1614
+ IsReexec: "IsReexec",
1615
+ CommandName: "CommandName",
1616
+ ExitCode: "ExitCode",
1617
+ TerminalOutcome: "TerminalOutcome",
1618
+ ErrorClass: "ErrorClass",
1619
+ TerminalSignal: "TerminalSignal",
1620
+ ErrorMessage: "ErrorMessage",
1621
+ SkillName: "SkillName",
1622
+ ProductArea: "ProductArea",
1623
+ Mode: "Mode"
1624
+ };
1625
+ var ProjectDimensions = {
1626
+ ProjectKey: "ProjectKey",
1627
+ ProjectType: "ProjectType",
1628
+ ProjectIdentityStatus: "ProjectIdentityStatus",
1629
+ SolutionKey: "SolutionKey",
1630
+ SolutionProjectKey: "SolutionProjectKey",
1631
+ SolutionIdentityStatus: "SolutionIdentityStatus",
1632
+ PreviousSolutionKey: "PreviousSolutionKey",
1633
+ PreviousProjectKey: "PreviousProjectKey"
1634
+ };
1635
+ var GUID_KEY_DIMENSIONS = new Set([
1636
+ ProjectDimensions.ProjectKey,
1637
+ ProjectDimensions.SolutionKey,
1638
+ ProjectDimensions.SolutionProjectKey,
1639
+ ProjectDimensions.PreviousSolutionKey,
1640
+ ProjectDimensions.PreviousProjectKey
1641
+ ]);
1642
+ var ShipDimensions = {
1643
+ ShipKind: "ShipKind",
1644
+ Target: "Target",
1645
+ ProjectType: "ProjectType",
1646
+ ProjectTypes: "ProjectTypes",
1647
+ ArtifactCorrelationKey: "ArtifactCorrelationKey",
1648
+ PackageName: "PackageName",
1649
+ PackageVersion: "PackageVersion",
1650
+ PackageVersionKey: "PackageVersionKey",
1651
+ DeploymentKey: "DeploymentKey",
1652
+ SolutionId: "SolutionId",
1653
+ FolderKey: "FolderKey",
1654
+ FeedId: "FeedId"
1655
+ };
1656
+ var ErrorDimensions = {
1657
+ Result: "Result",
1658
+ ErrorCode: "ErrorCode",
1659
+ Retry: "Retry",
1660
+ ErrorMessage: "ErrorMessage",
1661
+ HttpStatus: "HttpStatus",
1662
+ UpstreamErrorCode: "UpstreamErrorCode"
1663
+ };
1664
+ var AuthDimensions = {
1665
+ AuthenticationMethod: "AuthenticationMethod",
1666
+ Success: "Success",
1667
+ Reason: "Reason"
1668
+ };
1669
+ var SkillsDimensions = {
1670
+ SchemaVersion: "SchemaVersion",
1671
+ AgentType: "AgentType",
1672
+ SkillsVersion: "SkillsVersion",
1673
+ UipSubcommand: "UipSubcommand",
1674
+ FileExtension: "FileExtension",
1675
+ SubagentModel: "SubagentModel",
1676
+ SubagentType: "SubagentType",
1677
+ PermissionMode: "PermissionMode",
1678
+ EffortLevel: "EffortLevel",
1679
+ SessionSource: "SessionSource",
1680
+ Outcome: "Outcome",
1681
+ DurationMs: "DurationMs",
1682
+ Source: "Source"
1683
+ };
1684
+ var PackagerDimensions = {
1685
+ ProjectId: "ProjectId",
1686
+ ProjectType: "ProjectType",
1687
+ SolutionId: "SolutionId"
1688
+ };
1689
+ var ScopeDimensions = {
1690
+ FolderId: "FolderId"
1691
+ };
1692
+ var ID_DIMENSIONS = new Set([
1693
+ BaseDimensions.CloudUserId,
1694
+ BaseDimensions.CloudTenantId,
1695
+ BaseDimensions.CloudOrganizationId,
1696
+ BaseDimensions.InstallationId,
1697
+ ShipDimensions.ArtifactCorrelationKey,
1698
+ ShipDimensions.PackageVersionKey,
1699
+ ShipDimensions.DeploymentKey,
1700
+ ShipDimensions.SolutionId,
1701
+ ShipDimensions.FolderKey,
1702
+ ShipDimensions.FeedId,
1703
+ PackagerDimensions.ProjectId
1704
+ ]);
1705
+ var RESERVED_DIMENSION_NAMES = new Set([
1706
+ ...Object.values(BaseDimensions),
1707
+ ...Object.values(CommandDimensions),
1708
+ ...Object.values(ShipDimensions),
1709
+ ...Object.values(ProjectDimensions),
1710
+ ...Object.values(ErrorDimensions),
1711
+ ...Object.values(AuthDimensions),
1712
+ ...Object.values(SkillsDimensions),
1713
+ ...Object.values(PackagerDimensions),
1714
+ ...Object.values(ScopeDimensions)
1715
+ ]);
1716
+ var CURATED_DIMENSIONS = new Set([
1717
+ BaseDimensions.ApplicationName,
1718
+ BaseDimensions.ProductVersion,
1719
+ BaseDimensions.InstallationId,
1720
+ BaseDimensions.CloudUserId,
1721
+ BaseDimensions.CloudTenantId,
1722
+ BaseDimensions.CloudOrganizationId,
1723
+ BaseDimensions.IsInternalUser,
1724
+ BaseDimensions.Environment,
1725
+ BaseDimensions.BaseUrl,
1726
+ BaseDimensions.Region,
1727
+ BaseDimensions.Agent,
1728
+ BaseDimensions.AgentVersion,
1729
+ BaseDimensions.ToolVersion,
1730
+ BaseDimensions.ExecutionContext,
1731
+ BaseDimensions.CiProvider,
1732
+ BaseDimensions.SessionIdSource,
1733
+ BaseDimensions.SessionId,
1734
+ ...Object.values(CommandDimensions),
1735
+ ...Object.values(ShipDimensions),
1736
+ ...Object.values(ProjectDimensions)
1737
+ ]);
1738
+
1739
+ // ../../common/src/sha256.ts
1740
+ var SHA256_K = new Uint32Array([
1741
+ 1116352408,
1742
+ 1899447441,
1743
+ 3049323471,
1744
+ 3921009573,
1745
+ 961987163,
1746
+ 1508970993,
1747
+ 2453635748,
1748
+ 2870763221,
1749
+ 3624381080,
1750
+ 310598401,
1751
+ 607225278,
1752
+ 1426881987,
1753
+ 1925078388,
1754
+ 2162078206,
1755
+ 2614888103,
1756
+ 3248222580,
1757
+ 3835390401,
1758
+ 4022224774,
1759
+ 264347078,
1760
+ 604807628,
1761
+ 770255983,
1762
+ 1249150122,
1763
+ 1555081692,
1764
+ 1996064986,
1765
+ 2554220882,
1766
+ 2821834349,
1767
+ 2952996808,
1768
+ 3210313671,
1769
+ 3336571891,
1770
+ 3584528711,
1771
+ 113926993,
1772
+ 338241895,
1773
+ 666307205,
1774
+ 773529912,
1775
+ 1294757372,
1776
+ 1396182291,
1777
+ 1695183700,
1778
+ 1986661051,
1779
+ 2177026350,
1780
+ 2456956037,
1781
+ 2730485921,
1782
+ 2820302411,
1783
+ 3259730800,
1784
+ 3345764771,
1785
+ 3516065817,
1786
+ 3600352804,
1787
+ 4094571909,
1788
+ 275423344,
1789
+ 430227734,
1790
+ 506948616,
1791
+ 659060556,
1792
+ 883997877,
1793
+ 958139571,
1794
+ 1322822218,
1795
+ 1537002063,
1796
+ 1747873779,
1797
+ 1955562222,
1798
+ 2024104815,
1799
+ 2227730452,
1800
+ 2361852424,
1801
+ 2428436474,
1802
+ 2756734187,
1803
+ 3204031479,
1804
+ 3329325298
1805
+ ]);
1806
+ var SHA256_INITIAL_STATE = new Uint32Array([
1807
+ 1779033703,
1808
+ 3144134277,
1809
+ 1013904242,
1810
+ 2773480762,
1811
+ 1359893119,
1812
+ 2600822924,
1813
+ 528734635,
1814
+ 1541459225
1815
+ ]);
1816
+
1817
+ // ../../common/src/singleton.ts
1818
+ var PREFIX = "@uipath/common/";
1819
+ var _g = globalThis;
1820
+ function singleton(ctorOrName) {
1821
+ const name = typeof ctorOrName === "string" ? ctorOrName : ctorOrName.name;
1822
+ const key = Symbol.for(PREFIX + name);
1243
1823
  return {
1244
- Name: spec.name,
1245
- DisplayName: spec.displayName ?? spec.name,
1246
- SqlType: buildSqlType(sqlTypeName, spec),
1247
- IsRequired: spec.isRequired ?? false,
1248
- IsUnique: spec.isUnique ?? false,
1249
- IsPrimaryKey: false,
1250
- IsForeignKey: false,
1251
- IsExternalField: false,
1252
- IsHiddenField: false,
1253
- FieldCategoryId: 0,
1254
- ReferenceType: DEFAULT_REFERENCE_TYPE,
1255
- Transformation: null,
1256
- IsEncrypted: false,
1257
- Description: spec.description ?? "",
1258
- IsSystemField: false,
1259
- FieldDisplayType: fieldDisplayType,
1260
- DefaultValue: spec.defaultValue ?? null,
1261
- IsAttachment: false,
1262
- IsRbacEnabled: false,
1263
- IsModelReserved: false,
1264
- ReferenceChoiceSet: null,
1265
- ReferenceEntity: null,
1266
- ReferenceField: null,
1267
- ReferenceName: null
1824
+ get(fallback) {
1825
+ return _g[key] ?? fallback;
1826
+ },
1827
+ set(value) {
1828
+ _g[key] = value;
1829
+ },
1830
+ clear() {
1831
+ delete _g[key];
1832
+ },
1833
+ getOrInit(factory, guard) {
1834
+ const existing = _g[key];
1835
+ if (existing != null && typeof existing === "object") {
1836
+ if (!guard || guard(existing)) {
1837
+ return existing;
1838
+ }
1839
+ }
1840
+ const instance = factory();
1841
+ _g[key] = instance;
1842
+ return instance;
1843
+ }
1268
1844
  };
1269
1845
  }
1270
1846
 
1271
- // src/schema/create-entity-skeleton.ts
1272
- var UNASSIGNED_FOLDER_ID = "99999999-9999-9999-9999-999999999999";
1273
- function isLocallyAuthored(entity) {
1274
- return entity.FolderId === UNASSIGNED_FOLDER_ID;
1275
- }
1276
- var SYSTEM_FIELD_DEFAULTS = {
1277
- IsPrimaryKey: false,
1278
- IsForeignKey: false,
1279
- IsExternalField: false,
1280
- IsHiddenField: true,
1281
- FieldCategoryId: 0,
1282
- IsUnique: false,
1283
- ReferenceType: "ManyToOne",
1284
- Transformation: null,
1285
- IsRequired: false,
1286
- IsEncrypted: false,
1287
- Description: "",
1288
- IsSystemField: true,
1289
- FieldDisplayType: FieldDisplayType.Basic,
1290
- IsAttachment: false,
1291
- IsRbacEnabled: false,
1292
- IsModelReserved: false
1293
- };
1294
- var SYSTEM_FIELD_TEMPLATES = [
1295
- {
1296
- ...SYSTEM_FIELD_DEFAULTS,
1297
- Name: "Id",
1298
- DisplayName: "Id",
1299
- IsPrimaryKey: true,
1300
- SqlType: { Name: SqlTypeName.UNIQUEIDENTIFIER }
1301
- },
1302
- {
1303
- ...SYSTEM_FIELD_DEFAULTS,
1304
- Name: "CreateTime",
1305
- DisplayName: "CreateTime",
1306
- SqlType: { Name: SqlTypeName.DATETIMEOFFSET }
1307
- },
1308
- {
1309
- ...SYSTEM_FIELD_DEFAULTS,
1310
- Name: "CreatedBy",
1311
- DisplayName: "CreatedBy",
1312
- FieldDisplayType: FieldDisplayType.Relationship,
1313
- SqlType: { Name: SqlTypeName.UNIQUEIDENTIFIER }
1314
- },
1315
- {
1316
- ...SYSTEM_FIELD_DEFAULTS,
1317
- Name: "UpdateTime",
1318
- DisplayName: "UpdateTime",
1319
- SqlType: { Name: SqlTypeName.DATETIMEOFFSET }
1320
- },
1321
- {
1322
- ...SYSTEM_FIELD_DEFAULTS,
1323
- Name: "UpdatedBy",
1324
- DisplayName: "UpdatedBy",
1325
- FieldDisplayType: FieldDisplayType.Relationship,
1326
- SqlType: { Name: SqlTypeName.UNIQUEIDENTIFIER }
1327
- }
1328
- ];
1329
- function createEntitySkeleton(name) {
1330
- return {
1331
- Id: globalThis.crypto.randomUUID(),
1332
- Name: name,
1333
- DisplayName: name,
1334
- EntityTypeId: 0,
1335
- EntityType: "Entity",
1336
- Description: "",
1337
- FolderId: UNASSIGNED_FOLDER_ID,
1338
- Fields: SYSTEM_FIELD_TEMPLATES.map((template) => ({
1339
- ...template,
1340
- SqlType: { ...template.SqlType }
1341
- })),
1342
- Data: null,
1343
- ExternalFields: null,
1344
- SourceJoinCriterias: null,
1345
- RecordCount: 0,
1346
- StorageSizeInMB: null,
1347
- UsedStorageSizeInMB: null,
1348
- AttachmentSizeInByte: null,
1349
- IsRbacEnabled: false,
1350
- InvalidIdentifiers: [],
1351
- IsModelReserved: false,
1352
- CategoryId: null
1353
- };
1847
+ // ../../common/src/telemetry/supplied-values.ts
1848
+ var suppliedValuesSlot = singleton("TelemetrySuppliedArgumentValues");
1849
+
1850
+ // ../../common/src/telemetry/pii-redactor.ts
1851
+ var SENSITIVE_NAME_TOKENS = new Set([
1852
+ "token",
1853
+ "tokens",
1854
+ "secret",
1855
+ "secrets",
1856
+ "password",
1857
+ "passwords",
1858
+ "pwd",
1859
+ "credential",
1860
+ "credentials",
1861
+ "auth",
1862
+ "authentication",
1863
+ "authorization",
1864
+ "authority",
1865
+ "cert",
1866
+ "certificate",
1867
+ "certificates"
1868
+ ]);
1869
+ var SENSITIVE_KEY_PREFIXES = new Set([
1870
+ "api",
1871
+ "access",
1872
+ "client",
1873
+ "private",
1874
+ "public",
1875
+ "signing",
1876
+ "encryption",
1877
+ "session",
1878
+ "master",
1879
+ "shared",
1880
+ "root",
1881
+ "ssh",
1882
+ "rsa",
1883
+ "aes",
1884
+ "hmac",
1885
+ "oauth"
1886
+ ]);
1887
+ var SOURCE_FILE_EXTENSIONS = new Set([
1888
+ "ts",
1889
+ "tsx",
1890
+ "js",
1891
+ "jsx",
1892
+ "mjs",
1893
+ "cjs",
1894
+ "cts",
1895
+ "mts",
1896
+ "py",
1897
+ "cs",
1898
+ "java",
1899
+ "go",
1900
+ "rs",
1901
+ "rb",
1902
+ "php",
1903
+ "sh",
1904
+ "ps1",
1905
+ "json",
1906
+ "jsonc",
1907
+ "yaml",
1908
+ "yml",
1909
+ "xml",
1910
+ "xaml",
1911
+ "md",
1912
+ "txt",
1913
+ "log",
1914
+ "css",
1915
+ "html",
1916
+ "htm",
1917
+ "csproj",
1918
+ "nuspec",
1919
+ "sql"
1920
+ ]);
1921
+ var QUOTED_LITERAL_MAX_SPAN = 200;
1922
+ var QUOTED_LITERAL_PATTERN = new RegExp([
1923
+ `(?<![A-Za-z0-9])'(?:[^\\
1924
+ ]|\\.){2,${QUOTED_LITERAL_MAX_SPAN}}?'(?![A-Za-z0-9])`,
1925
+ `(?<![A-Za-z0-9])"(?:[^\\
1926
+ ]|\\.){2,${QUOTED_LITERAL_MAX_SPAN}}?"(?![A-Za-z0-9])`
1927
+ ].join("|"), "g");
1928
+ var MESSAGE_NAMES = new Set([
1929
+ "message",
1930
+ "errormessage",
1931
+ "errmessage",
1932
+ "error_message",
1933
+ "msg",
1934
+ "detail",
1935
+ "details",
1936
+ "reason",
1937
+ "instructions",
1938
+ "warning"
1939
+ ]);
1940
+ function nameTokens(name) {
1941
+ return name.replace(/([a-z0-9])([A-Z])/g, "$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g, "$1 $2").split(/[\s._-]+/).map((t) => t.toLowerCase()).filter(Boolean);
1354
1942
  }
1355
-
1356
- // src/schema/validate-entity.ts
1357
- var DIAGNOSTIC_CODES = {
1358
- entityNameInvalid: "ENTITY_NAME_INVALID",
1359
- entityNameNotUnique: "ENTITY_NAME_NOT_UNIQUE",
1360
- fieldNameInvalid: "FIELD_NAME_INVALID",
1361
- duplicateFieldName: "DUPLICATE_FIELD_NAME",
1362
- fieldTypeNotAllowed: "FIELD_TYPE_NOT_ALLOWED",
1363
- nameReserved: "NAME_RESERVED",
1364
- systemFieldMissing: "SYSTEM_FIELD_MISSING",
1365
- systemFieldModified: "SYSTEM_FIELD_MODIFIED",
1366
- fieldsMalformed: "FIELDS_MALFORMED",
1367
- tooManyMultilineMax: "TOO_MANY_MULTILINE_MAX",
1368
- propertyTypeInvalid: "PROPERTY_TYPE_INVALID"
1369
- };
1370
- function validateEntity(entity, ctx) {
1371
- const diagnostics = [];
1372
- if (typeof entity?.Name !== "string") {
1373
- return [
1374
- {
1375
- code: DIAGNOSTIC_CODES.entityNameInvalid,
1376
- message: "The entity document has no 'Name'. The resource is malformed.",
1377
- severity: "error"
1943
+ function isSensitiveName(name) {
1944
+ const tokens = nameTokens(name);
1945
+ for (let i = 0;i < tokens.length; i++) {
1946
+ const token = tokens[i];
1947
+ if (SENSITIVE_NAME_TOKENS.has(token)) {
1948
+ return true;
1949
+ }
1950
+ if (token === "key" || token === "keys") {
1951
+ const prev = tokens[i - 1];
1952
+ if (prev && SENSITIVE_KEY_PREFIXES.has(prev)) {
1953
+ return true;
1378
1954
  }
1379
- ];
1380
- }
1381
- const entityNameFormat = validateNameFormat(entity.Name, "entity");
1382
- if (entityNameFormat) {
1383
- diagnostics.push({
1384
- code: DIAGNOSTIC_CODES.entityNameInvalid,
1385
- message: `${entityNameFormat.message}. ${entityNameFormat.instructions}`,
1386
- severity: "error"
1387
- });
1955
+ }
1388
1956
  }
1389
- const reservedEntityName = findReservedNameError(entity.Name, "entity");
1390
- if (reservedEntityName) {
1391
- diagnostics.push({
1392
- code: DIAGNOSTIC_CODES.nameReserved,
1393
- message: `${reservedEntityName.message}. ${reservedEntityName.instructions}`,
1394
- severity: "error"
1395
- });
1957
+ return false;
1958
+ }
1959
+
1960
+ // ../../common/src/catch-error.ts
1961
+ var MAX_SERIALIZED_LENGTH = 500;
1962
+ var TRUNCATION_SUFFIX = "…(truncated)";
1963
+ var REDACTED = "[REDACTED]";
1964
+ function cap(text) {
1965
+ return text.length > MAX_SERIALIZED_LENGTH ? `${text.slice(0, MAX_SERIALIZED_LENGTH)}${TRUNCATION_SUFFIX}` : text;
1966
+ }
1967
+ function omitSensitive(key, value) {
1968
+ return key.length > 0 && isSensitiveName(key) ? REDACTED : value;
1969
+ }
1970
+ function describeThrownValue(value) {
1971
+ if (typeof value !== "object" || value === null) {
1972
+ return String(value);
1396
1973
  }
1397
- const entityNameLower = entity.Name.toLowerCase();
1398
- if (ctx.siblingNames.some((sibling) => sibling.toLowerCase() === entityNameLower)) {
1399
- diagnostics.push({
1400
- code: DIAGNOSTIC_CODES.entityNameNotUnique,
1401
- message: `An entity named '${entity.Name}' already exists in this solution. Entity names are solution-wide unique.`,
1402
- severity: "error"
1403
- });
1974
+ let message;
1975
+ try {
1976
+ message = value.message;
1977
+ } catch {
1978
+ message = undefined;
1404
1979
  }
1405
- diagnostics.push(...typeProblems(entity, ENTITY_SCALARS).map((problem) => propertyTypeDiagnostic(`Entity '${entity.Name}'`, problem)));
1406
- if (!Array.isArray(entity.Fields)) {
1407
- diagnostics.push({
1408
- code: DIAGNOSTIC_CODES.fieldsMalformed,
1409
- message: "The entity document has no usable 'Fields' array. The resource is malformed.",
1410
- severity: "error"
1411
- });
1412
- return diagnostics;
1980
+ if (typeof message === "string" && message.length > 0) {
1981
+ return cap(message);
1413
1982
  }
1414
- const seenFieldNames = new Map;
1415
- for (const field of entity.Fields) {
1416
- if (typeof field?.Name !== "string") {
1417
- diagnostics.push({
1418
- code: DIAGNOSTIC_CODES.fieldNameInvalid,
1419
- message: "A field has no 'Name'. Every field needs one, system or custom.",
1420
- severity: "error"
1421
- });
1422
- continue;
1423
- }
1424
- const isSystem = isSystemField(field);
1425
- if (!SYSTEM_FIELD_NAMES.has(field.Name)) {
1426
- diagnostics.push(...fieldTypeDiagnostics(field));
1427
- }
1428
- const fieldNameFormat = isSystem ? null : validateNameFormat(field.Name, "field");
1429
- if (fieldNameFormat) {
1430
- diagnostics.push({
1431
- code: DIAGNOSTIC_CODES.fieldNameInvalid,
1432
- message: `${fieldNameFormat.message}. ${fieldNameFormat.instructions}`,
1433
- severity: "error",
1434
- fieldName: field.Name
1435
- });
1436
- }
1437
- if (!isSystem) {
1438
- const reservedFieldName = findReservedNameError(field.Name, "field");
1439
- if (reservedFieldName) {
1440
- diagnostics.push({
1441
- code: DIAGNOSTIC_CODES.nameReserved,
1442
- message: `${reservedFieldName.message}. ${reservedFieldName.instructions}`,
1443
- severity: "error",
1444
- fieldName: field.Name
1445
- });
1446
- }
1447
- }
1448
- const fieldNameLower = field.Name.toLowerCase();
1449
- if (!isSystem && typeof entity.Name === "string" && fieldNameLower === entity.Name.toLowerCase()) {
1450
- diagnostics.push({
1451
- code: DIAGNOSTIC_CODES.fieldNameInvalid,
1452
- message: `Field name '${field.Name}' cannot match entity name '${entity.Name}' (names are compared case-insensitively).`,
1453
- severity: "error",
1454
- fieldName: field.Name
1455
- });
1456
- }
1457
- const firstWithName = seenFieldNames.get(fieldNameLower);
1458
- if (firstWithName !== undefined) {
1459
- diagnostics.push({
1460
- code: DIAGNOSTIC_CODES.duplicateFieldName,
1461
- message: `Duplicate field name '${field.Name}' (names are case-insensitive; first defined as '${firstWithName}').`,
1462
- severity: "error",
1463
- fieldName: field.Name
1464
- });
1465
- } else {
1466
- seenFieldNames.set(fieldNameLower, field.Name);
1467
- }
1468
- if (!isSystem && !ALLOWED_TYPE_PAIRS.has(`${field.FieldDisplayType}:${field.SqlType?.Name}`)) {
1469
- diagnostics.push({
1470
- code: DIAGNOSTIC_CODES.fieldTypeNotAllowed,
1471
- message: `Field '${field.Name}' uses an unsupported type combination ` + `(${field.FieldDisplayType} / ${field.SqlType?.Name}).`,
1472
- severity: "error",
1473
- fieldName: field.Name
1474
- });
1983
+ try {
1984
+ const json = JSON.stringify(value, omitSensitive);
1985
+ if (json !== undefined) {
1986
+ return cap(json);
1475
1987
  }
1476
- }
1477
- const usableFields = entity.Fields.filter((field) => typeof field === "object" && field !== null);
1478
- const multilineMax = usableFields.filter((field) => field.SqlType?.Name === SqlTypeName.MULTILINE_MAX);
1479
- if (multilineMax.length > MAX_MULTILINE_MAX_FIELDS) {
1480
- diagnostics.push({
1481
- code: DIAGNOSTIC_CODES.tooManyMultilineMax,
1482
- message: `Entity '${entity.Name}' defines ${multilineMax.length} MULTILINE_MAX fields; ` + `the maximum is ${MAX_MULTILINE_MAX_FIELDS}. Remove some, or use MULTILINE_TEXT where the content fits.`,
1483
- severity: "error"
1484
- });
1485
- }
1486
- diagnostics.push(...validateSystemFields(entity, usableFields));
1487
- return diagnostics;
1988
+ } catch {}
1989
+ return String(value);
1488
1990
  }
1489
- var SERVER_ASSIGNED_FIELD_PROPS = new Set([
1490
- "Id",
1491
- "CreateTime",
1492
- "CreatedBy",
1493
- "UpdateTime",
1494
- "UpdatedBy"
1495
- ]);
1496
- function isUnmodifiedSystemField(template, actual) {
1497
- const equal = (left, right) => JSON.stringify(left ?? null) === JSON.stringify(right ?? null);
1498
- for (const key of Object.keys(template)) {
1499
- if (!equal(template[key], actual[key])) {
1500
- return false;
1991
+ function toError(error) {
1992
+ return error instanceof Error ? error : new Error(describeThrownValue(error), { cause: error });
1993
+ }
1994
+ function isPromiseLike(value) {
1995
+ return value !== null && typeof value === "object" && typeof value.then === "function";
1996
+ }
1997
+ function catchError(fnOrPromise) {
1998
+ if (isPromiseLike(fnOrPromise)) {
1999
+ return settlePromiseLike(fnOrPromise);
2000
+ }
2001
+ try {
2002
+ const result = fnOrPromise();
2003
+ if (isPromiseLike(result)) {
2004
+ return settlePromiseLike(result);
1501
2005
  }
2006
+ return [undefined, result];
2007
+ } catch (error) {
2008
+ return [toError(error), undefined];
1502
2009
  }
1503
- return Object.keys(actual).every((key) => (key in template) || SERVER_ASSIGNED_FIELD_PROPS.has(key));
1504
2010
  }
1505
- function validateSystemFields(entity, usableFields) {
1506
- const diagnostics = [];
1507
- for (const template of SYSTEM_FIELD_TEMPLATES) {
1508
- const actual = usableFields.find((field) => field.Name === template.Name);
1509
- if (!actual) {
1510
- diagnostics.push({
1511
- code: DIAGNOSTIC_CODES.systemFieldMissing,
1512
- message: `System field '${template.Name}' is missing. System fields cannot be removed.`,
1513
- severity: "error",
1514
- fieldName: template.Name
1515
- });
1516
- continue;
1517
- }
1518
- if (!isUnmodifiedSystemField(template, actual)) {
1519
- diagnostics.push({
1520
- code: DIAGNOSTIC_CODES.systemFieldModified,
1521
- message: `System field '${template.Name}' was modified. System fields are read-only.`,
1522
- severity: "error",
1523
- fieldName: template.Name
1524
- });
1525
- }
2011
+ function settlePromiseLike(thenable) {
2012
+ return Promise.resolve(thenable).then((data) => [undefined, data]).catch((error) => [toError(error), undefined]);
2013
+ }
2014
+
2015
+ // src/pack/entity-project-tool.ts
2016
+ import {
2017
+ ProjectTool,
2018
+ ToolResult
2019
+ } from "@uipath/solutionpackager-tool-core";
2020
+
2021
+ // src/canonical-path.ts
2022
+ async function canonicalPathAsync(target, fs) {
2023
+ const realpath = fs.realpath?.bind(fs);
2024
+ const absolute = fs.path.resolve(target);
2025
+ if (realpath === undefined)
2026
+ return absolute;
2027
+ const tail = [];
2028
+ let current = absolute;
2029
+ while (!await fs.exists(current)) {
2030
+ const parent = fs.path.dirname(current);
2031
+ if (parent === current)
2032
+ return absolute;
2033
+ tail.unshift(fs.path.basename(current));
2034
+ current = parent;
1526
2035
  }
1527
- return diagnostics;
2036
+ return fs.path.join(await realpath(current), ...tail);
1528
2037
  }
1529
- function isSystemField(field) {
1530
- const { IsSystemField: flag, Name: name } = field ?? {};
1531
- return flag === true || typeof name === "string" && SYSTEM_FIELD_NAMES.has(name);
2038
+ async function resolvesInsideAsync(target, root, fs) {
2039
+ const canonicalRoot = await canonicalPathAsync(root, fs);
2040
+ const resolved = await canonicalPathAsync(target, fs);
2041
+ const relative = fs.path.relative(canonicalRoot, resolved);
2042
+ const inside = relative !== "" && relative.split(/[\\/]/)[0] !== ".." && !fs.path.isAbsolute(relative);
2043
+ return { inside, resolved, root: canonicalRoot };
1532
2044
  }
1533
- var SYSTEM_FIELD_NAMES = new Set(SYSTEM_FIELD_TEMPLATES.map((template) => template.Name));
1534
- var ENTITY_SCALARS = [
1535
- { key: "DisplayName", kind: "string" },
1536
- { key: "Description", kind: "string" },
1537
- { key: "EntityTypeId", kind: "integer" },
1538
- { key: "RecordCount", kind: "integer" },
1539
- { key: "IsRbacEnabled", kind: "boolean" },
1540
- { key: "IsModelReserved", kind: "boolean" }
1541
- ];
1542
- var FIELD_SCALARS = [
1543
- { key: "DisplayName", kind: "string" },
1544
- { key: "Description", kind: "string" },
1545
- { key: "ReferenceType", kind: "string" },
1546
- { key: "FieldCategoryId", kind: "integer" },
1547
- { key: "IsRequired", kind: "boolean" },
1548
- { key: "IsUnique", kind: "boolean" },
1549
- { key: "IsPrimaryKey", kind: "boolean" },
1550
- { key: "IsForeignKey", kind: "boolean" },
1551
- { key: "IsSystemField", kind: "boolean" },
1552
- { key: "IsExternalField", kind: "boolean" },
1553
- { key: "IsHiddenField", kind: "boolean" },
1554
- { key: "IsEncrypted", kind: "boolean" },
1555
- { key: "IsAttachment", kind: "boolean" },
1556
- { key: "IsRbacEnabled", kind: "boolean" },
1557
- { key: "IsModelReserved", kind: "boolean" }
1558
- ];
1559
- var SQL_TYPE_SCALARS = [
1560
- { key: "LengthLimit", kind: "integer", nullable: true },
1561
- { key: "DecimalPrecision", kind: "integer", nullable: true },
1562
- { key: "MaxValue", kind: "number", nullable: true },
1563
- { key: "MinValue", kind: "number", nullable: true }
1564
- ];
1565
- function typeProblems(record, rules, prefix = "") {
1566
- const values = record;
1567
- return rules.filter(({ key, kind, nullable }) => {
1568
- const value = values[key];
1569
- if (value === undefined)
1570
- return false;
1571
- if (value === null)
1572
- return !nullable;
1573
- if (kind === "integer")
1574
- return !Number.isInteger(value);
1575
- return kind === "number" ? !(typeof value === "number" && Number.isFinite(value)) : typeof value !== kind;
1576
- }).map(({ key, kind, nullable }) => `'${prefix}${key}' must be ${kind === "integer" ? "an" : "a"} ${kind}${nullable ? " or null" : ""}`);
2045
+ async function isSymlinkEntryAsync(target, fs) {
2046
+ const isSymbolicLink = fs.isSymbolicLink?.bind(fs);
2047
+ return isSymbolicLink === undefined ? false : isSymbolicLink(fs.path.resolve(target));
1577
2048
  }
1578
- function propertyTypeDiagnostic(subject, problem, fieldName) {
1579
- return {
1580
- code: DIAGNOSTIC_CODES.propertyTypeInvalid,
1581
- message: `${subject}: ${problem}. The resource was edited by hand or is malformed.`,
1582
- severity: "error",
1583
- ...fieldName !== undefined && { fieldName }
1584
- };
2049
+
2050
+ // src/decode-text.ts
2051
+ function decodeText(raw) {
2052
+ const text = typeof raw === "string" ? raw : new TextDecoder().decode(raw ?? new Uint8Array);
2053
+ return text.startsWith("\uFEFF") ? text.slice(1) : text;
1585
2054
  }
1586
- function fieldTypeDiagnostics(field) {
1587
- const problems = typeProblems(field, FIELD_SCALARS);
1588
- if (typeof field.SqlType === "object" && field.SqlType !== null) {
1589
- problems.push(...typeProblems(field.SqlType, SQL_TYPE_SCALARS, "SqlType."));
1590
- }
1591
- const defaultValue = field.DefaultValue;
1592
- const isYesNo = field.SqlType?.Name === SqlTypeName.BIT;
1593
- if (defaultValue != null && typeof defaultValue !== "string" && !(isYesNo && typeof defaultValue === "boolean")) {
1594
- problems.push(isYesNo ? "'DefaultValue' must be a boolean, a string or null" : "'DefaultValue' must be a string or null");
1595
- }
1596
- return problems.map((problem) => propertyTypeDiagnostic(`Field '${field.Name}'`, problem, field.Name));
2055
+
2056
+ // src/missing-path.ts
2057
+ function isMissingPathError(error) {
2058
+ if (!(error instanceof Error) || !("code" in error))
2059
+ return false;
2060
+ const { code } = error;
2061
+ return code === "ENOENT" || code === "ENOTDIR" || code === "PathNotFound";
2062
+ }
2063
+ function isFilesystemError(error) {
2064
+ const code = error?.code;
2065
+ return typeof code === "string" && /^E[A-Z]+$/.test(code);
2066
+ }
2067
+ function isUnreadablePathError(error) {
2068
+ return isFilesystemError(error) && !isMissingPathError(error);
1597
2069
  }
1598
2070
 
1599
2071
  // src/resource/unified-resource-file.ts
@@ -1606,6 +2078,16 @@ var ENTITY_RESOURCE_DIR = `${ENTITY_RESOURCE_KIND}/${ENTITY_RESOURCE_TYPE}`;
1606
2078
  function entityResourcePath(entityName) {
1607
2079
  return `resources/${SOLUTION_FOLDER}/${ENTITY_RESOURCE_DIR}/${entityName}.json`;
1608
2080
  }
2081
+ var FEDERATED_ENTITY_RESOURCE_TYPE = "federated";
2082
+ var FEDERATED_ENTITY_RESOURCE_DIR = `${ENTITY_RESOURCE_KIND}/${FEDERATED_ENTITY_RESOURCE_TYPE}`;
2083
+ function federatedEntityResourcePath(entityName) {
2084
+ return `resources/${SOLUTION_FOLDER}/${FEDERATED_ENTITY_RESOURCE_DIR}/${entityName}.json`;
2085
+ }
2086
+ var CONNECTION_RESOURCE_KIND = "connection";
2087
+ var CHOICE_SET_RESOURCE_KIND = "choiceSet";
2088
+ function choiceSetResourcePath(choiceSetName) {
2089
+ return `resources/${SOLUTION_FOLDER}/${CHOICE_SET_RESOURCE_KIND}/${choiceSetName}.json`;
2090
+ }
1609
2091
 
1610
2092
  // src/resource/resource-io.ts
1611
2093
  function serialize(value) {
@@ -1686,6 +2168,15 @@ function updateResourceSchema(file, entity) {
1686
2168
  };
1687
2169
  }
1688
2170
 
2171
+ // src/pack/constants.ts
2172
+ var ENTITY_EXTENSION_CONST = ".entity";
2173
+ var ENTITY_VALIDATION_FAILED = "ENTITY_VALIDATION_FAILED";
2174
+ var PACK_DIAGNOSTIC_CODES = {
2175
+ misplacedMainFile: "MISPLACED_MAIN_FILE",
2176
+ noParentSolution: "NO_PARENT_SOLUTION",
2177
+ solutionRootUnreadable: "SOLUTION_ROOT_UNREADABLE"
2178
+ };
2179
+
1689
2180
  // src/pack/verify-pair.ts
1690
2181
  async function verifyPair(stubFile, solutionDir, fs) {
1691
2182
  const parsedStub = await readStub(stubFile, fs);
@@ -1782,6 +2273,154 @@ async function findSolutionRoot(startDir, fs) {
1782
2273
  }
1783
2274
  }
1784
2275
 
2276
+ // src/schema/solution-entity-names.ts
2277
+ function withoutOneOccurrence(names, name) {
2278
+ const siblings = [...names];
2279
+ const self = siblings.indexOf(name);
2280
+ if (self >= 0) {
2281
+ siblings.splice(self, 1);
2282
+ }
2283
+ return siblings;
2284
+ }
2285
+ function isMissingPath(error) {
2286
+ return error instanceof Error && "code" in error && (error.code === "ENOENT" || error.code === "PathNotFound");
2287
+ }
2288
+ async function collectSolutionEntityNames(solutionDir, fs) {
2289
+ const names = [];
2290
+ let topLevel = [];
2291
+ try {
2292
+ topLevel = await fs.readdir(solutionDir);
2293
+ } catch (error) {
2294
+ if (!isMissingPath(error)) {
2295
+ throw error;
2296
+ }
2297
+ return names;
2298
+ }
2299
+ for (const entry of topLevel) {
2300
+ if (entry === "resources" || entry.startsWith(".")) {
2301
+ continue;
2302
+ }
2303
+ const dir = fs.path.join(solutionDir, entry);
2304
+ try {
2305
+ const stat = await fs.stat(dir);
2306
+ if (!stat?.isDirectory()) {
2307
+ continue;
2308
+ }
2309
+ for (const file of await fs.readdir(dir)) {
2310
+ if (file.endsWith(ENTITY_EXTENSION_CONST)) {
2311
+ names.push(fs.path.basename(file, ENTITY_EXTENSION_CONST));
2312
+ }
2313
+ }
2314
+ } catch (error) {
2315
+ if (!isMissingPath(error)) {
2316
+ throw error;
2317
+ }
2318
+ }
2319
+ }
2320
+ return names;
2321
+ }
2322
+
2323
+ // src/inline/solution-references.ts
2324
+ async function jsonFilesAsync(dir, solutionDir, fs) {
2325
+ const [readError, names] = await catchError(fs.readdir(dir));
2326
+ if (readError) {
2327
+ if (isMissingPathError(readError))
2328
+ return [];
2329
+ throw readError;
2330
+ }
2331
+ const files = [];
2332
+ for (const name of names.sort(byName)) {
2333
+ if (!name.toLowerCase().endsWith(".json"))
2334
+ continue;
2335
+ const file = fs.path.join(dir, name);
2336
+ if (await isSymlinkEntryAsync(file, fs))
2337
+ continue;
2338
+ if (!(await resolvesInsideAsync(file, solutionDir, fs)).inside) {
2339
+ continue;
2340
+ }
2341
+ files.push(file);
2342
+ }
2343
+ return files;
2344
+ }
2345
+ async function parseAsync(file, fs) {
2346
+ const raw = await fs.readFile(file);
2347
+ const text = decodeText(raw);
2348
+ const [error, parsed] = catchError(() => JSON.parse(text));
2349
+ if (error) {
2350
+ if (error instanceof SyntaxError) {
2351
+ return { problem: `it is not valid JSON (${error.message}).` };
2352
+ }
2353
+ throw error;
2354
+ }
2355
+ return typeof parsed === "object" && parsed !== null ? { parsed } : { problem: "it is not a JSON object." };
2356
+ }
2357
+ async function parsedAsync(file, fs) {
2358
+ const result = await parseAsync(file, fs);
2359
+ return "parsed" in result ? result.parsed : undefined;
2360
+ }
2361
+ function keyOf(resource, id) {
2362
+ const key = resource?.key;
2363
+ if (typeof key === "string" && key !== "")
2364
+ return key;
2365
+ return typeof id === "string" ? id : "";
2366
+ }
2367
+ async function readSolutionNativeEntitiesAsync(solutionDir, fs) {
2368
+ return (await readEntityResourcesAsync(solutionDir, ENTITY_RESOURCE_DIR, fs)).entities;
2369
+ }
2370
+ async function readEntityResourcesAsync(solutionDir, entityDir, fs) {
2371
+ const dir = fs.path.join(solutionDir, "resources", SOLUTION_FOLDER, ...entityDir.split("/"));
2372
+ const found = [];
2373
+ const unreadable = [];
2374
+ for (const file of await jsonFilesAsync(dir, solutionDir, fs)) {
2375
+ const result = await parseAsync(file, fs);
2376
+ if ("problem" in result) {
2377
+ unreadable.push({ file, reason: result.problem });
2378
+ continue;
2379
+ }
2380
+ const { parsed } = result;
2381
+ const [unwrapError, entity] = catchError(() => unwrapResource(parsed));
2382
+ if (unwrapError) {
2383
+ unreadable.push({ file, reason: unwrapError.message });
2384
+ continue;
2385
+ }
2386
+ if (typeof entity?.Name !== "string") {
2387
+ unreadable.push({ file, reason: "its entity has no Name." });
2388
+ continue;
2389
+ }
2390
+ const dependencies = parsed.resource?.dependencies;
2391
+ found.push({
2392
+ key: keyOf(parsed.resource, entity.Id),
2393
+ entity,
2394
+ dependencies: Array.isArray(dependencies) ? dependencies : [],
2395
+ file
2396
+ });
2397
+ }
2398
+ return { entities: found, unreadable };
2399
+ }
2400
+ async function readSolutionChoiceSetsAsync(solutionDir, fs) {
2401
+ const dir = fs.path.join(solutionDir, "resources", SOLUTION_FOLDER, CHOICE_SET_RESOURCE_KIND);
2402
+ const found = [];
2403
+ for (const file of await jsonFilesAsync(dir, solutionDir, fs)) {
2404
+ const parsed = await parsedAsync(file, fs);
2405
+ const resource = parsed?.resource;
2406
+ if (typeof resource?.kind !== "string" || resource.kind.toLowerCase() !== CHOICE_SET_RESOURCE_KIND.toLowerCase()) {
2407
+ continue;
2408
+ }
2409
+ if (typeof resource.name !== "string")
2410
+ continue;
2411
+ const [parseError, document] = catchError(() => JSON.parse(String(resource.spec?.resourceJson)));
2412
+ if (parseError || typeof document !== "object" || document === null) {
2413
+ continue;
2414
+ }
2415
+ found.push({
2416
+ key: keyOf(resource, document?.Id),
2417
+ name: resource.name,
2418
+ ...typeof document?.FolderId === "string" && document.FolderId !== "" && { folderId: document.FolderId }
2419
+ });
2420
+ }
2421
+ return found;
2422
+ }
2423
+
1785
2424
  // src/pack/entity-project-tool.ts
1786
2425
  class EntityProjectTool extends ProjectTool {
1787
2426
  async validateAsync(options, _cancellationToken) {
@@ -1842,6 +2481,8 @@ class EntityProjectTool extends ProjectTool {
1842
2481
  const fs = this.fileSystem;
1843
2482
  const diagnostics = [];
1844
2483
  const allEntityNames = await collectSolutionEntityNames(solutionDir, fs);
2484
+ const natives = await readSolutionNativeEntitiesAsync(solutionDir, fs);
2485
+ const choiceSets = await readSolutionChoiceSetsAsync(solutionDir, fs);
1845
2486
  for (const stubName of stubs) {
1846
2487
  const stubFile = fs.path.join(projectPath, stubName);
1847
2488
  const pair = await verifyPair(stubFile, solutionDir, fs);
@@ -1853,9 +2494,10 @@ class EntityProjectTool extends ProjectTool {
1853
2494
  });
1854
2495
  continue;
1855
2496
  }
1856
- for (const diagnostic of validateEntity(pair.entity, {
2497
+ const schema = validateEntity(pair.entity, {
1857
2498
  siblingNames: withoutOneOccurrence(allEntityNames, pair.entityName)
1858
- })) {
2499
+ });
2500
+ for (const diagnostic of schema) {
1859
2501
  diagnostics.push({
1860
2502
  file: pair.resourceFile,
1861
2503
  code: diagnostic.code,
@@ -1863,6 +2505,26 @@ class EntityProjectTool extends ProjectTool {
1863
2505
  fieldName: diagnostic.fieldName
1864
2506
  });
1865
2507
  }
2508
+ if (schema.length > 0 || !isLocallyAuthored(pair.entity))
2509
+ continue;
2510
+ const name = pair.entity.Name.toLowerCase();
2511
+ const others = natives.filter((each) => each.entity.Name.toLowerCase() !== name);
2512
+ for (const issue of [
2513
+ ...referenceIssues(pair.entity, {
2514
+ entities: others,
2515
+ choiceSets
2516
+ }),
2517
+ ...entityGraphIssues(pair.entity, others, choiceSets)
2518
+ ]) {
2519
+ diagnostics.push({
2520
+ file: pair.resourceFile,
2521
+ code: issue.code,
2522
+ message: issue.message,
2523
+ ...issue.fieldName !== "" && {
2524
+ fieldName: issue.fieldName
2525
+ }
2526
+ });
2527
+ }
1866
2528
  }
1867
2529
  return diagnostics;
1868
2530
  }
@@ -1883,6 +2545,292 @@ class EntityToolFactory {
1883
2545
  return new EntityProjectTool(fileSystem, logger);
1884
2546
  }
1885
2547
  }
2548
+ // src/resource/choice-set-resource.ts
2549
+ class ChoiceSetResourceError extends Error {
2550
+ failure;
2551
+ constructor(failure, message) {
2552
+ super(message);
2553
+ this.failure = failure;
2554
+ this.name = "ChoiceSetResourceError";
2555
+ }
2556
+ }
2557
+ function createChoiceSetResource(name, init) {
2558
+ const id = globalThis.crypto.randomUUID();
2559
+ const displayName = init.displayName ?? name;
2560
+ const description = init.description ?? "";
2561
+ return {
2562
+ docVersion: ENTITY_RESOURCE_DOC_VERSION,
2563
+ resource: {
2564
+ name,
2565
+ kind: CHOICE_SET_RESOURCE_KIND,
2566
+ apiVersion: ENTITY_RESOURCE_API_VERSION,
2567
+ isOverridable: false,
2568
+ dependencies: [],
2569
+ runtimeDependencies: [],
2570
+ folders: [{ fullyQualifiedName: SOLUTION_FOLDER }],
2571
+ spec: {
2572
+ resourceJson: JSON.stringify({
2573
+ Id: id,
2574
+ Name: name,
2575
+ DisplayName: displayName,
2576
+ Description: description,
2577
+ FolderId: UNASSIGNED_FOLDER_ID,
2578
+ IsModelReserved: false,
2579
+ Data: []
2580
+ }),
2581
+ name,
2582
+ description,
2583
+ displayName
2584
+ },
2585
+ locks: [],
2586
+ key: id,
2587
+ files: []
2588
+ }
2589
+ };
2590
+ }
2591
+ function parseChoiceSet(file) {
2592
+ const resourceJson = file?.resource?.spec?.resourceJson;
2593
+ if (typeof resourceJson !== "string") {
2594
+ throw new ChoiceSetResourceError("ResourceJsonUnparsable", "Resource file has no 'spec.resourceJson' string.");
2595
+ }
2596
+ const [parseError, parsed] = catchError(() => JSON.parse(resourceJson));
2597
+ if (parseError) {
2598
+ throw new ChoiceSetResourceError("ResourceJsonUnparsable", "'spec.resourceJson' is not valid JSON.");
2599
+ }
2600
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed) || !Array.isArray(parsed.Data)) {
2601
+ throw new ChoiceSetResourceError("ChoiceSetUnparsable", "'spec.resourceJson' is not a choice set: it has no 'Data' array.");
2602
+ }
2603
+ return parsed;
2604
+ }
2605
+ function readChoiceSetValues(file) {
2606
+ const data = parseChoiceSet(file).Data;
2607
+ return data.map((entry) => {
2608
+ const value = entry;
2609
+ if (typeof value?.Name !== "string" || typeof value.DisplayName !== "string" || value.NumberId !== undefined && typeof value.NumberId !== "number") {
2610
+ throw new ChoiceSetResourceError("ChoiceSetUnparsable", "A choice set value needs a string Name, a string DisplayName and, when it has one, a numeric NumberId.");
2611
+ }
2612
+ return {
2613
+ name: value.Name,
2614
+ displayName: value.DisplayName,
2615
+ ...typeof value.NumberId === "number" && {
2616
+ numberId: value.NumberId
2617
+ }
2618
+ };
2619
+ });
2620
+ }
2621
+ function withChoiceSetValues(file, values) {
2622
+ const choiceSet = parseChoiceSet(file);
2623
+ const next = {
2624
+ ...choiceSet,
2625
+ Data: values.map((value) => ({
2626
+ DisplayName: value.displayName,
2627
+ Name: value.name,
2628
+ ...value.numberId !== undefined && { NumberId: value.numberId }
2629
+ }))
2630
+ };
2631
+ return {
2632
+ ...file,
2633
+ resource: {
2634
+ ...file.resource,
2635
+ spec: {
2636
+ ...file.resource.spec,
2637
+ resourceJson: JSON.stringify(next)
2638
+ }
2639
+ }
2640
+ };
2641
+ }
2642
+ // src/resource/federated-entity-resource.ts
2643
+ class FederatedEntityResourceError extends Error {
2644
+ instructions;
2645
+ code;
2646
+ constructor(message, instructions, code) {
2647
+ super(message);
2648
+ this.instructions = instructions;
2649
+ this.code = code;
2650
+ this.name = "FederatedEntityResourceError";
2651
+ }
2652
+ }
2653
+ var rec = (value) => typeof value === "object" && value !== null ? value : {};
2654
+ var str = (value) => typeof value === "string" ? value : undefined;
2655
+ var present = (key, value) => value === undefined || value === null ? {} : { [key]: value };
2656
+ var BOOLEAN_OVERRIDES = [
2657
+ ["sortable", "sortable"],
2658
+ ["isRequiredForRead", "requiredForRead"]
2659
+ ];
2660
+ function assertBooleanOverrides(fieldName, mapping) {
2661
+ for (const [key, bodyKey] of BOOLEAN_OVERRIDES) {
2662
+ if (typeof mapping[key] !== "boolean") {
2663
+ throw new FederatedEntityResourceError(`Field '${fieldName}' has '${bodyKey}' ${JSON.stringify(mapping[key]) ?? "missing"}, which is not true or false`, `Set '${bodyKey}' to true or false in the source's 'fields' entry, or leave it out to take the default.`, "INVALID_FEDERATED_SOURCE");
2664
+ }
2665
+ }
2666
+ }
2667
+ var DEFAULT_TEXT_LENGTH = 200;
2668
+ function sqlTypeOf(field) {
2669
+ const type = str(field.type) ?? "";
2670
+ const name = basicSqlTypeNameOf(type);
2671
+ if (name === undefined) {
2672
+ throw new FederatedEntityResourceError(`Field '${String(field.name)}' has type '${type}', which a federated column cannot carry`, UNSUPPORTED_SOURCE_COLUMN_INSTRUCTIONS, "UNSUPPORTED_SOURCE_COLUMN");
2673
+ }
2674
+ return {
2675
+ Name: name,
2676
+ LengthLimit: type === "STRING" ? DEFAULT_TEXT_LENGTH : null,
2677
+ MaxValue: null,
2678
+ MinValue: null,
2679
+ DecimalPrecision: typeof field.decimalPrecision === "number" ? field.decimalPrecision : null
2680
+ };
2681
+ }
2682
+ function createFederatedEntityResource(name, expanded, solution) {
2683
+ const document = createEntitySkeleton(name);
2684
+ if (typeof expanded.displayName === "string") {
2685
+ document.DisplayName = expanded.displayName;
2686
+ }
2687
+ if (typeof expanded.description === "string") {
2688
+ document.Description = expanded.description;
2689
+ }
2690
+ const sources = Array.isArray(expanded.externalFields) ? expanded.externalFields.map(rec) : [];
2691
+ const joins = Array.isArray(expanded.sourceJoinConditionDetails) ? expanded.sourceJoinConditionDetails.map(rec) : [];
2692
+ const primary = joins[0];
2693
+ const dependencies = [];
2694
+ const depend = (kind, dependency) => {
2695
+ if (!dependencies.some((each) => each.kind === kind && sameName(each.name, dependency))) {
2696
+ dependencies.push({ kind, name: dependency });
2697
+ }
2698
+ };
2699
+ const written = [];
2700
+ const fields = [];
2701
+ const externalFields = sources.map((source, index) => {
2702
+ const native = rec(source.nativeConnectionDetail);
2703
+ const external = rec(source.externalConnectionDetail);
2704
+ const object = rec(source.externalObjectDetail);
2705
+ const isNative = str(native.entityId) !== undefined;
2706
+ const connId = isNative ? native.entityId : external.connectionId;
2707
+ if (connId === undefined) {
2708
+ throw new FederatedEntityResourceError(`Source ${index + 1} names neither a native entity nor a connection`, "Each source reads a native entity of the solution ('entityName') or a connection resource of it ('connectionName' and 'object').", "INVALID_FEDERATED_SOURCE");
2709
+ }
2710
+ const target = (isNative ? solution.nativeEntities : solution.connections).find((each) => sameName(each.key, connId));
2711
+ if (target === undefined) {
2712
+ throw new FederatedEntityResourceError(`Source ${index + 1} reads ${isNative ? "entity" : "connection"} '${connId}', which is not a resource of this solution`, isNative ? "A native source must be a native entity in the solution. Create it with 'uip df entities create <Name> --local', or add it with 'uip solution resources add --source remote --kind Entity --name <Name>'." : "A connector source reads a connection resource of the solution. Add it with 'uip solution resources add --source remote --kind Connection --name <Name>'.", isNative ? "REFERENCE_TARGET_NOT_FOUND" : "CONNECTION_NOT_FOUND");
2713
+ }
2714
+ depend(isNative ? "Entity" : "Connection", target.name);
2715
+ const objectName = str(object.externalObjectName) ?? target.name;
2716
+ if (written.some((each) => sameName(each.objectName, objectName) && sameName(each.connId, connId))) {
2717
+ throw new FederatedEntityResourceError(`Source ${index + 1} reads '${objectName}' again`, "List each source object once in 'externalFields', with all of its fields; a self-join on one source is not supported.", "INVALID_FEDERATED_SOURCE");
2718
+ }
2719
+ const objectId = globalThis.crypto.randomUUID();
2720
+ written.push({ objectId, objectName, connId });
2721
+ const nativeDetail = isNative ? {
2722
+ EntityId: target.key,
2723
+ ...present("FolderKey", native.folderKey)
2724
+ } : undefined;
2725
+ const fieldNames = [];
2726
+ for (const entry of Array.isArray(source.fields) ? source.fields.map(rec) : []) {
2727
+ const field = rec(entry.field);
2728
+ const mapping = rec(entry.externalFieldMappingDetail);
2729
+ const fieldName = String(field.name);
2730
+ assertBooleanOverrides(fieldName, mapping);
2731
+ const fieldId = globalThis.crypto.randomUUID();
2732
+ fieldNames.push(fieldName);
2733
+ fields.push({
2734
+ Id: fieldId,
2735
+ Name: fieldName,
2736
+ IsPrimaryKey: false,
2737
+ IsForeignKey: false,
2738
+ IsExternalField: true,
2739
+ IsHiddenField: false,
2740
+ ExternalFieldMappingDetail: {
2741
+ Id: globalThis.crypto.randomUUID(),
2742
+ ExternalFieldName: mapping.externalFieldName,
2743
+ ExternalFieldDisplayName: mapping.externalFieldName,
2744
+ ExternalObjectId: objectId,
2745
+ ExternalFieldType: mapping.externalFieldType,
2746
+ InternalFieldId: fieldId,
2747
+ DirectionType: mapping.directionType,
2748
+ Searchability: mapping.searchability,
2749
+ IsRequiredForRead: mapping.isRequiredForRead,
2750
+ ...nativeDetail && {
2751
+ NativeConnectionDetail: nativeDetail
2752
+ },
2753
+ Sortable: mapping.sortable
2754
+ },
2755
+ FieldCategoryId: 0,
2756
+ IsUnique: false,
2757
+ ReferenceName: null,
2758
+ ReferenceEntity: null,
2759
+ ReferenceChoiceSet: null,
2760
+ ReferenceField: null,
2761
+ ReferenceType: "ManyToOne",
2762
+ SqlType: sqlTypeOf(field),
2763
+ Transformation: null,
2764
+ IsRequired: false,
2765
+ IsEncrypted: false,
2766
+ DisplayName: fieldName,
2767
+ Description: "",
2768
+ IsSystemField: false,
2769
+ DefaultValue: null,
2770
+ IsAttachment: false,
2771
+ IsRbacEnabled: false,
2772
+ IsModelReserved: false
2773
+ });
2774
+ }
2775
+ const isPrimary = primary === undefined ? index === 0 : sameName(String(primary.sourceObjectName), objectName) && sameName(String(primary.sourceObjectConnectionId), connId);
2776
+ return {
2777
+ FieldNames: fieldNames,
2778
+ ExternalObjectDetail: {
2779
+ Id: objectId,
2780
+ ExternalObjectName: objectName,
2781
+ ExternalObjectDisplayName: str(object.externalObjectDisplayName) ?? objectName,
2782
+ PrimaryKey: object.primaryKey,
2783
+ ...!isNative && { ExternalConnectionId: target.key },
2784
+ EntityId: document.Id,
2785
+ IsPrimarySource: isPrimary,
2786
+ Method: str(object.method) ?? null
2787
+ },
2788
+ ExternalConnectionDetail: isNative ? {} : {
2789
+ Id: target.key,
2790
+ ConnectionId: target.key,
2791
+ ...present("ElementInstanceId", external.elementInstanceId),
2792
+ ...present("FolderKey", external.folderKey),
2793
+ ...present("ConnectorKey", external.connectorKey),
2794
+ ...present("ConnectorName", external.connectorName),
2795
+ ...present("ConnectionName", external.connectionName)
2796
+ },
2797
+ NativeConnectionDetail: nativeDetail ?? {}
2798
+ };
2799
+ });
2800
+ const objectIdOf = (objectName, connId) => {
2801
+ const found = written.find((each) => sameName(each.objectName, String(objectName)) && sameName(each.connId, String(connId)));
2802
+ if (found === undefined) {
2803
+ throw new FederatedEntityResourceError(`A join names source '${String(objectName)}', which is not one of the entity's sources`, "Each side of a join names a source in 'externalFields' by its object and connection.", "INVALID_JOIN");
2804
+ }
2805
+ return found.objectId;
2806
+ };
2807
+ const sourceJoinCriterias = joins.map((join) => {
2808
+ const sourceObjectId = objectIdOf(join.sourceObjectName, join.sourceObjectConnectionId);
2809
+ const relatedSourceObjectId = objectIdOf(join.relatedSourceObjectName, join.relatedSourceObjectConnectionId);
2810
+ if (sourceObjectId === relatedSourceObjectId) {
2811
+ throw new FederatedEntityResourceError(`A join relates source '${String(join.sourceObjectName)}' to itself`, "Each join relates the primary source to another source in 'externalFields', so that every source is joined.", "INVALID_JOIN");
2812
+ }
2813
+ return {
2814
+ Id: globalThis.crypto.randomUUID(),
2815
+ EntityId: document.Id,
2816
+ SourceObjectId: sourceObjectId,
2817
+ JoinFieldName: join.sourceJoinField,
2818
+ JoinType: join.joinType,
2819
+ RelatedSourceObjectId: relatedSourceObjectId,
2820
+ RelatedSourceFieldName: join.relatedSourceJoinField
2821
+ };
2822
+ });
2823
+ const entity = {
2824
+ ...document,
2825
+ Fields: [...document.Fields, ...fields],
2826
+ ExternalFields: externalFields,
2827
+ SourceJoinCriterias: sourceJoinCriterias
2828
+ };
2829
+ const file = wrapEntityJson(entity);
2830
+ file.resource.type = FEDERATED_ENTITY_RESOURCE_TYPE;
2831
+ file.resource.dependencies = dependencies.sort((a, b) => byName(a.kind, b.kind) || byName(a.name, b.name));
2832
+ return file;
2833
+ }
1886
2834
  // src/resource/local-entities.ts
1887
2835
  async function readSolutionInlineEntities(fs, flowFilePath) {
1888
2836
  const found = new Map;
@@ -1924,6 +2872,9 @@ async function readSolutionInlineEntities(fs, flowFilePath) {
1924
2872
  export {
1925
2873
  AUTHORABLE_FIELD_TYPES,
1926
2874
  AuthoredFieldError,
2875
+ CHOICE_SET_RESOURCE_KIND,
2876
+ CONNECTION_RESOURCE_KIND,
2877
+ ChoiceSetResourceError,
1927
2878
  DIAGNOSTIC_CODES,
1928
2879
  ENTITY_RESOURCE_API_VERSION,
1929
2880
  ENTITY_RESOURCE_DIR,
@@ -1934,22 +2885,40 @@ export {
1934
2885
  EntityProjectTool,
1935
2886
  EntityResourceError,
1936
2887
  EntityToolFactory,
2888
+ FEDERATED_ENTITY_RESOURCE_DIR,
2889
+ FEDERATED_ENTITY_RESOURCE_TYPE,
2890
+ FederatedEntityResourceError,
2891
+ REFERENCE_FIELD_TYPES,
2892
+ REFERENCE_TYPE_PAIRS,
1937
2893
  SOLUTION_FOLDER,
1938
2894
  SYSTEM_FIELD_TEMPLATES,
1939
2895
  UNASSIGNED_FOLDER_ID,
1940
2896
  authorField,
2897
+ authoredTypeOf,
2898
+ basicSqlTypeNameOf,
2899
+ bindReferences,
2900
+ choiceSetResourcePath,
2901
+ createChoiceSetResource,
1941
2902
  createEntitySkeleton,
2903
+ createFederatedEntityResource,
1942
2904
  entityResourcePath,
2905
+ federatedEntityResourcePath,
2906
+ findCycle,
1943
2907
  findSolutionRoot,
1944
2908
  isLocallyAuthored,
2909
+ readChoiceSetValues,
1945
2910
  readSolutionInlineEntities,
2911
+ referenceDependencies,
1946
2912
  serialize,
1947
2913
  serializeEntityJson,
2914
+ sourceColumnTypeOf,
1948
2915
  unwrapResource,
1949
2916
  updateResourceSchema,
1950
2917
  validateEntity,
1951
2918
  verifyPair,
2919
+ withChoiceSetValues,
2920
+ withReferenceDependencies,
1952
2921
  wrapEntityJson
1953
2922
  };
1954
2923
 
1955
- //# debugId=C7C9E32BAC72C2C864756E2164756E21
2924
+ //# debugId=DE0C4F52B6A250D964756E2164756E21