@uipath/packager-tool-datafabric 1.204.0 → 1.205.0-preview.258

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/inline.js ADDED
@@ -0,0 +1,3665 @@
1
+ import { createRequire } from "node:module";
2
+ var __create = Object.create;
3
+ var __getProtoOf = Object.getPrototypeOf;
4
+ var __defProp = Object.defineProperty;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ function __accessProp(key) {
8
+ return this[key];
9
+ }
10
+ var __toESMCache_node;
11
+ var __toESMCache_esm;
12
+ var __toESM = (mod, isNodeMode, target) => {
13
+ var canCache = mod != null && typeof mod === "object";
14
+ if (canCache) {
15
+ var cache = isNodeMode ? __toESMCache_node ??= new WeakMap : __toESMCache_esm ??= new WeakMap;
16
+ var cached = cache.get(mod);
17
+ if (cached)
18
+ return cached;
19
+ }
20
+ target = mod != null ? __create(__getProtoOf(mod)) : {};
21
+ const to = isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target;
22
+ if (mod && typeof mod === "object" || typeof mod === "function") {
23
+ for (let key of __getOwnPropNames(mod))
24
+ if (!__hasOwnProp.call(to, key))
25
+ __defProp(to, key, {
26
+ get: __accessProp.bind(mod, key),
27
+ enumerable: true
28
+ });
29
+ }
30
+ if (canCache)
31
+ cache.set(mod, to);
32
+ return to;
33
+ };
34
+ var __commonJS = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports);
35
+ var __returnValue = (v) => v;
36
+ function __exportSetter(name, newValue) {
37
+ this[name] = __returnValue.bind(null, newValue);
38
+ }
39
+ var __export = (target, all) => {
40
+ for (var name in all)
41
+ __defProp(target, name, {
42
+ get: all[name],
43
+ enumerable: true,
44
+ configurable: true,
45
+ set: __exportSetter.bind(all, name)
46
+ });
47
+ };
48
+ var __esm = (fn, res) => () => (fn && (res = fn(fn = 0)), res);
49
+ var __require = /* @__PURE__ */ createRequire(import.meta.url);
50
+
51
+ // ../../../node_modules/is-inside-container/node_modules/is-docker/index.js
52
+ import fs from "node:fs";
53
+ function hasDockerEnv() {
54
+ try {
55
+ fs.statSync("/.dockerenv");
56
+ return true;
57
+ } catch {
58
+ return false;
59
+ }
60
+ }
61
+ function hasDockerCGroup() {
62
+ try {
63
+ return fs.readFileSync("/proc/self/cgroup", "utf8").includes("docker");
64
+ } catch {
65
+ return false;
66
+ }
67
+ }
68
+ function isDocker() {
69
+ if (isDockerCached === undefined) {
70
+ isDockerCached = hasDockerEnv() || hasDockerCGroup();
71
+ }
72
+ return isDockerCached;
73
+ }
74
+ var isDockerCached;
75
+ var init_is_docker = () => {};
76
+
77
+ // ../../../node_modules/is-inside-container/index.js
78
+ import fs2 from "node:fs";
79
+ function isInsideContainer() {
80
+ if (cachedResult === undefined) {
81
+ cachedResult = hasContainerEnv() || isDocker();
82
+ }
83
+ return cachedResult;
84
+ }
85
+ var cachedResult, hasContainerEnv = () => {
86
+ try {
87
+ fs2.statSync("/run/.containerenv");
88
+ return true;
89
+ } catch {
90
+ return false;
91
+ }
92
+ };
93
+ var init_is_inside_container = __esm(() => {
94
+ init_is_docker();
95
+ });
96
+
97
+ // ../../../node_modules/wsl-utils/node_modules/is-wsl/index.js
98
+ import process2 from "node:process";
99
+ import os from "node:os";
100
+ import fs3 from "node:fs";
101
+ var isWsl = () => {
102
+ if (process2.platform !== "linux") {
103
+ return false;
104
+ }
105
+ if (os.release().toLowerCase().includes("microsoft")) {
106
+ if (isInsideContainer()) {
107
+ return false;
108
+ }
109
+ return true;
110
+ }
111
+ try {
112
+ if (fs3.readFileSync("/proc/version", "utf8").toLowerCase().includes("microsoft")) {
113
+ return !isInsideContainer();
114
+ }
115
+ } catch {}
116
+ if (fs3.existsSync("/proc/sys/fs/binfmt_misc/WSLInterop") || fs3.existsSync("/run/WSL")) {
117
+ return !isInsideContainer();
118
+ }
119
+ return false;
120
+ }, is_wsl_default;
121
+ var init_is_wsl = __esm(() => {
122
+ init_is_inside_container();
123
+ is_wsl_default = process2.env.__IS_WSL_TEST__ ? isWsl : isWsl();
124
+ });
125
+
126
+ // ../../../node_modules/powershell-utils/index.js
127
+ import process3 from "node:process";
128
+ import { Buffer } from "node:buffer";
129
+ import { promisify } from "node:util";
130
+ import childProcess from "node:child_process";
131
+ var execFile, powerShellPath = () => `${process3.env.SYSTEMROOT || process3.env.windir || String.raw`C:\Windows`}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`, executePowerShell = async (command, options = {}) => {
132
+ const {
133
+ powerShellPath: psPath,
134
+ ...execFileOptions
135
+ } = options;
136
+ const encodedCommand = executePowerShell.encodeCommand(command);
137
+ return execFile(psPath ?? powerShellPath(), [
138
+ ...executePowerShell.argumentsPrefix,
139
+ encodedCommand
140
+ ], {
141
+ encoding: "utf8",
142
+ ...execFileOptions
143
+ });
144
+ };
145
+ var init_powershell_utils = __esm(() => {
146
+ execFile = promisify(childProcess.execFile);
147
+ executePowerShell.argumentsPrefix = [
148
+ "-NoProfile",
149
+ "-NonInteractive",
150
+ "-ExecutionPolicy",
151
+ "Bypass",
152
+ "-EncodedCommand"
153
+ ];
154
+ executePowerShell.encodeCommand = (command) => Buffer.from(command, "utf16le").toString("base64");
155
+ executePowerShell.escapeArgument = (value) => `'${String(value).replaceAll("'", "''")}'`;
156
+ });
157
+
158
+ // ../../../node_modules/wsl-utils/utilities.js
159
+ function parseMountPointFromConfig(content) {
160
+ for (const line of content.split(`
161
+ `)) {
162
+ if (/^\s*#/.test(line)) {
163
+ continue;
164
+ }
165
+ const match = /^\s*root\s*=\s*(?<mountPoint>"[^"]*"|'[^']*'|[^#]*)/.exec(line);
166
+ if (!match) {
167
+ continue;
168
+ }
169
+ return match.groups.mountPoint.trim().replaceAll(/^["']|["']$/g, "");
170
+ }
171
+ }
172
+
173
+ // ../../../node_modules/wsl-utils/index.js
174
+ import { promisify as promisify2 } from "node:util";
175
+ import childProcess2 from "node:child_process";
176
+ import fs4, { constants as fsConstants } from "node:fs/promises";
177
+ var execFile2, wslDrivesMountPoint, powerShellPathFromWsl = async () => {
178
+ const mountPoint = await wslDrivesMountPoint();
179
+ return `${mountPoint}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`;
180
+ }, powerShellPath2, canAccessPowerShellPromise, canAccessPowerShell = async () => {
181
+ canAccessPowerShellPromise ??= (async () => {
182
+ try {
183
+ const psPath = await powerShellPath2();
184
+ await fs4.access(psPath, fsConstants.X_OK);
185
+ return true;
186
+ } catch {
187
+ return false;
188
+ }
189
+ })();
190
+ return canAccessPowerShellPromise;
191
+ }, wslDefaultBrowser = async () => {
192
+ const psPath = await powerShellPath2();
193
+ const command = String.raw`(Get-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http\UserChoice").ProgId`;
194
+ const { stdout } = await executePowerShell(command, { powerShellPath: psPath });
195
+ return stdout.trim();
196
+ }, convertWslPathToWindows = async (path) => {
197
+ if (/^[a-z]+:\/\//i.test(path)) {
198
+ return path;
199
+ }
200
+ try {
201
+ const { stdout } = await execFile2("wslpath", ["-aw", path], { encoding: "utf8" });
202
+ return stdout.trim();
203
+ } catch {
204
+ return path;
205
+ }
206
+ };
207
+ var init_wsl_utils = __esm(() => {
208
+ init_is_wsl();
209
+ init_powershell_utils();
210
+ init_is_wsl();
211
+ execFile2 = promisify2(childProcess2.execFile);
212
+ wslDrivesMountPoint = (() => {
213
+ const defaultMountPoint = "/mnt/";
214
+ let mountPoint;
215
+ return async function() {
216
+ if (mountPoint) {
217
+ return mountPoint;
218
+ }
219
+ const configFilePath = "/etc/wsl.conf";
220
+ let isConfigFileExists = false;
221
+ try {
222
+ await fs4.access(configFilePath, fsConstants.F_OK);
223
+ isConfigFileExists = true;
224
+ } catch {}
225
+ if (!isConfigFileExists) {
226
+ return defaultMountPoint;
227
+ }
228
+ const configContent = await fs4.readFile(configFilePath, { encoding: "utf8" });
229
+ const parsedMountPoint = parseMountPointFromConfig(configContent);
230
+ if (parsedMountPoint === undefined) {
231
+ return defaultMountPoint;
232
+ }
233
+ mountPoint = parsedMountPoint;
234
+ mountPoint = mountPoint.endsWith("/") ? mountPoint : `${mountPoint}/`;
235
+ return mountPoint;
236
+ };
237
+ })();
238
+ powerShellPath2 = is_wsl_default ? powerShellPathFromWsl : powerShellPath;
239
+ });
240
+
241
+ // ../../../node_modules/open/node_modules/define-lazy-prop/index.js
242
+ function defineLazyProperty(object, propertyName, valueGetter) {
243
+ const define = (value) => Object.defineProperty(object, propertyName, { value, enumerable: true, writable: true });
244
+ Object.defineProperty(object, propertyName, {
245
+ configurable: true,
246
+ enumerable: true,
247
+ get() {
248
+ const result = valueGetter();
249
+ define(result);
250
+ return result;
251
+ },
252
+ set(value) {
253
+ define(value);
254
+ }
255
+ });
256
+ return object;
257
+ }
258
+
259
+ // ../../../node_modules/default-browser-id/index.js
260
+ import { promisify as promisify3 } from "node:util";
261
+ import process4 from "node:process";
262
+ import { execFile as execFile3 } from "node:child_process";
263
+ async function defaultBrowserId() {
264
+ if (process4.platform !== "darwin") {
265
+ throw new Error("macOS only");
266
+ }
267
+ const { stdout } = await execFileAsync("defaults", ["read", "com.apple.LaunchServices/com.apple.launchservices.secure", "LSHandlers"]);
268
+ const match = /LSHandlerRoleAll = "(?!-)(?<id>[^"]+?)";\s+?LSHandlerURLScheme = (?:http|https);/.exec(stdout);
269
+ const browserId = match?.groups.id ?? "com.apple.Safari";
270
+ if (browserId === "com.apple.safari") {
271
+ return "com.apple.Safari";
272
+ }
273
+ return browserId;
274
+ }
275
+ var execFileAsync;
276
+ var init_default_browser_id = __esm(() => {
277
+ execFileAsync = promisify3(execFile3);
278
+ });
279
+
280
+ // ../../../node_modules/run-applescript/index.js
281
+ import process5 from "node:process";
282
+ import { promisify as promisify4 } from "node:util";
283
+ import { execFile as execFile4, execFileSync } from "node:child_process";
284
+ async function runAppleScript(script, { humanReadableOutput = true, signal } = {}) {
285
+ if (process5.platform !== "darwin") {
286
+ throw new Error("macOS only");
287
+ }
288
+ const outputArguments = humanReadableOutput ? [] : ["-ss"];
289
+ const execOptions = {};
290
+ if (signal) {
291
+ execOptions.signal = signal;
292
+ }
293
+ const { stdout } = await execFileAsync2("osascript", ["-e", script, outputArguments], execOptions);
294
+ return stdout.trim();
295
+ }
296
+ var execFileAsync2;
297
+ var init_run_applescript = __esm(() => {
298
+ execFileAsync2 = promisify4(execFile4);
299
+ });
300
+
301
+ // ../../../node_modules/bundle-name/index.js
302
+ async function bundleName(bundleId) {
303
+ return runAppleScript(`tell application "Finder" to set app_path to application file id "${bundleId}" as string
304
+ tell application "System Events" to get value of property list item "CFBundleName" of property list file (app_path & ":Contents:Info.plist")`);
305
+ }
306
+ var init_bundle_name = __esm(() => {
307
+ init_run_applescript();
308
+ });
309
+
310
+ // ../../../node_modules/default-browser/windows.js
311
+ import { promisify as promisify5 } from "node:util";
312
+ import { execFile as execFile5 } from "node:child_process";
313
+ async function defaultBrowser(_execFileAsync = execFileAsync3) {
314
+ const { stdout } = await _execFileAsync("reg", [
315
+ "QUERY",
316
+ " HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\http\\UserChoice",
317
+ "/v",
318
+ "ProgId"
319
+ ]);
320
+ const match = /ProgId\s*REG_SZ\s*(?<id>\S+)/.exec(stdout);
321
+ if (!match) {
322
+ throw new UnknownBrowserError(`Cannot find Windows browser in stdout: ${JSON.stringify(stdout)}`);
323
+ }
324
+ const { id } = match.groups;
325
+ const dotIndex = id.lastIndexOf(".");
326
+ const hyphenIndex = id.lastIndexOf("-");
327
+ const baseIdByDot = dotIndex === -1 ? undefined : id.slice(0, dotIndex);
328
+ const baseIdByHyphen = hyphenIndex === -1 ? undefined : id.slice(0, hyphenIndex);
329
+ return windowsBrowserProgIds[id] ?? windowsBrowserProgIds[baseIdByDot] ?? windowsBrowserProgIds[baseIdByHyphen] ?? { name: id, id };
330
+ }
331
+ var execFileAsync3, windowsBrowserProgIds, _windowsBrowserProgIdMap, UnknownBrowserError;
332
+ var init_windows = __esm(() => {
333
+ execFileAsync3 = promisify5(execFile5);
334
+ windowsBrowserProgIds = {
335
+ MSEdgeHTM: { name: "Edge", id: "com.microsoft.edge" },
336
+ MSEdgeBHTML: { name: "Edge Beta", id: "com.microsoft.edge.beta" },
337
+ MSEdgeDHTML: { name: "Edge Dev", id: "com.microsoft.edge.dev" },
338
+ AppXq0fevzme2pys62n3e0fbqa7peapykr8v: { name: "Edge", id: "com.microsoft.edge.old" },
339
+ ChromeHTML: { name: "Chrome", id: "com.google.chrome" },
340
+ ChromeBHTML: { name: "Chrome Beta", id: "com.google.chrome.beta" },
341
+ ChromeDHTML: { name: "Chrome Dev", id: "com.google.chrome.dev" },
342
+ ChromiumHTM: { name: "Chromium", id: "org.chromium.Chromium" },
343
+ BraveHTML: { name: "Brave", id: "com.brave.Browser" },
344
+ BraveBHTML: { name: "Brave Beta", id: "com.brave.Browser.beta" },
345
+ BraveDHTML: { name: "Brave Dev", id: "com.brave.Browser.dev" },
346
+ BraveSSHTM: { name: "Brave Nightly", id: "com.brave.Browser.nightly" },
347
+ FirefoxURL: { name: "Firefox", id: "org.mozilla.firefox" },
348
+ OperaStable: { name: "Opera", id: "com.operasoftware.Opera" },
349
+ VivaldiHTM: { name: "Vivaldi", id: "com.vivaldi.Vivaldi" },
350
+ "IE.HTTP": { name: "Internet Explorer", id: "com.microsoft.ie" }
351
+ };
352
+ _windowsBrowserProgIdMap = new Map(Object.entries(windowsBrowserProgIds));
353
+ UnknownBrowserError = class UnknownBrowserError extends Error {
354
+ };
355
+ });
356
+
357
+ // ../../../node_modules/default-browser/index.js
358
+ import { promisify as promisify6 } from "node:util";
359
+ import process6 from "node:process";
360
+ import { execFile as execFile6 } from "node:child_process";
361
+ async function defaultBrowser2() {
362
+ if (process6.platform === "darwin") {
363
+ const id = await defaultBrowserId();
364
+ const name = await bundleName(id);
365
+ return { name, id };
366
+ }
367
+ if (process6.platform === "linux") {
368
+ const { stdout } = await execFileAsync4("xdg-mime", ["query", "default", "x-scheme-handler/http"]);
369
+ const id = stdout.trim();
370
+ const name = titleize(id.replace(/.desktop$/, "").replace("-", " "));
371
+ return { name, id };
372
+ }
373
+ if (process6.platform === "win32") {
374
+ return defaultBrowser();
375
+ }
376
+ throw new Error("Only macOS, Linux, and Windows are supported");
377
+ }
378
+ var execFileAsync4, titleize = (string) => string.toLowerCase().replaceAll(/(?:^|\s|-)\S/g, (x) => x.toUpperCase());
379
+ var init_default_browser = __esm(() => {
380
+ init_default_browser_id();
381
+ init_bundle_name();
382
+ init_windows();
383
+ init_windows();
384
+ execFileAsync4 = promisify6(execFile6);
385
+ });
386
+
387
+ // ../../../node_modules/is-in-ssh/index.js
388
+ import process7 from "node:process";
389
+ var isInSsh, is_in_ssh_default;
390
+ var init_is_in_ssh = __esm(() => {
391
+ isInSsh = Boolean(process7.env.SSH_CONNECTION || process7.env.SSH_CLIENT || process7.env.SSH_TTY);
392
+ is_in_ssh_default = isInSsh;
393
+ });
394
+
395
+ // ../../../node_modules/open/index.js
396
+ var exports_open = {};
397
+ __export(exports_open, {
398
+ apps: () => apps,
399
+ default: () => open_default,
400
+ openApp: () => openApp
401
+ });
402
+ import process8 from "node:process";
403
+ import path from "node:path";
404
+ import { fileURLToPath } from "node:url";
405
+ import childProcess3 from "node:child_process";
406
+ import fs5, { constants as fsConstants2 } from "node:fs/promises";
407
+ function detectArchBinary(binary) {
408
+ if (typeof binary === "string" || Array.isArray(binary)) {
409
+ return binary;
410
+ }
411
+ const { [arch]: archBinary } = binary;
412
+ if (!archBinary) {
413
+ throw new Error(`${arch} is not supported`);
414
+ }
415
+ return archBinary;
416
+ }
417
+ function detectPlatformBinary({ [platform]: platformBinary }, { wsl } = {}) {
418
+ if (wsl && is_wsl_default) {
419
+ return detectArchBinary(wsl);
420
+ }
421
+ if (!platformBinary) {
422
+ throw new Error(`${platform} is not supported`);
423
+ }
424
+ return detectArchBinary(platformBinary);
425
+ }
426
+ var fallbackAttemptSymbol, __dirname2, localXdgOpenPath, platform, arch, tryEachApp = async (apps, opener) => {
427
+ if (apps.length === 0) {
428
+ return;
429
+ }
430
+ const errors = [];
431
+ for (const app of apps) {
432
+ try {
433
+ return await opener(app);
434
+ } catch (error) {
435
+ errors.push(error);
436
+ }
437
+ }
438
+ throw new AggregateError(errors, "Failed to open in all supported apps");
439
+ }, baseOpen = async (options) => {
440
+ options = {
441
+ wait: false,
442
+ background: false,
443
+ newInstance: false,
444
+ allowNonzeroExitCode: false,
445
+ ...options
446
+ };
447
+ const isFallbackAttempt = options[fallbackAttemptSymbol] === true;
448
+ delete options[fallbackAttemptSymbol];
449
+ if (Array.isArray(options.app)) {
450
+ return tryEachApp(options.app, (singleApp) => baseOpen({
451
+ ...options,
452
+ app: singleApp,
453
+ [fallbackAttemptSymbol]: true
454
+ }));
455
+ }
456
+ let { name: app, arguments: appArguments = [] } = options.app ?? {};
457
+ appArguments = [...appArguments];
458
+ if (Array.isArray(app)) {
459
+ return tryEachApp(app, (appName) => baseOpen({
460
+ ...options,
461
+ app: {
462
+ name: appName,
463
+ arguments: appArguments
464
+ },
465
+ [fallbackAttemptSymbol]: true
466
+ }));
467
+ }
468
+ if (app === "browser" || app === "browserPrivate") {
469
+ const ids = {
470
+ "com.google.chrome": "chrome",
471
+ "google-chrome.desktop": "chrome",
472
+ "com.brave.browser": "brave",
473
+ "org.mozilla.firefox": "firefox",
474
+ "firefox.desktop": "firefox",
475
+ "com.microsoft.msedge": "edge",
476
+ "com.microsoft.edge": "edge",
477
+ "com.microsoft.edgemac": "edge",
478
+ "microsoft-edge.desktop": "edge",
479
+ "com.apple.safari": "safari"
480
+ };
481
+ const flags = {
482
+ chrome: "--incognito",
483
+ brave: "--incognito",
484
+ firefox: "--private-window",
485
+ edge: "--inPrivate"
486
+ };
487
+ let browser;
488
+ if (is_wsl_default) {
489
+ const progId = await wslDefaultBrowser();
490
+ const browserInfo = _windowsBrowserProgIdMap.get(progId);
491
+ browser = browserInfo ?? {};
492
+ } else {
493
+ browser = await defaultBrowser2();
494
+ }
495
+ if (browser.id in ids) {
496
+ const browserName = ids[browser.id.toLowerCase()];
497
+ if (app === "browserPrivate") {
498
+ if (browserName === "safari") {
499
+ throw new Error("Safari doesn't support opening in private mode via command line");
500
+ }
501
+ appArguments.push(flags[browserName]);
502
+ }
503
+ return baseOpen({
504
+ ...options,
505
+ app: {
506
+ name: apps[browserName],
507
+ arguments: appArguments
508
+ }
509
+ });
510
+ }
511
+ throw new Error(`${browser.name} is not supported as a default browser`);
512
+ }
513
+ let command;
514
+ const cliArguments = [];
515
+ const childProcessOptions = {};
516
+ let shouldUseWindowsInWsl = false;
517
+ if (is_wsl_default && !isInsideContainer() && !is_in_ssh_default && !app) {
518
+ shouldUseWindowsInWsl = await canAccessPowerShell();
519
+ }
520
+ if (platform === "darwin") {
521
+ command = "open";
522
+ if (options.wait) {
523
+ cliArguments.push("--wait-apps");
524
+ }
525
+ if (options.background) {
526
+ cliArguments.push("--background");
527
+ }
528
+ if (options.newInstance) {
529
+ cliArguments.push("--new");
530
+ }
531
+ if (app) {
532
+ cliArguments.push("-a", app);
533
+ }
534
+ } else if (platform === "win32" || shouldUseWindowsInWsl) {
535
+ command = await powerShellPath2();
536
+ cliArguments.push(...executePowerShell.argumentsPrefix);
537
+ if (!is_wsl_default) {
538
+ childProcessOptions.windowsVerbatimArguments = true;
539
+ }
540
+ if (is_wsl_default && options.target) {
541
+ options.target = await convertWslPathToWindows(options.target);
542
+ }
543
+ const encodedArguments = ["$ProgressPreference = 'SilentlyContinue';", "Start"];
544
+ if (options.wait) {
545
+ encodedArguments.push("-Wait");
546
+ }
547
+ if (app) {
548
+ encodedArguments.push(executePowerShell.escapeArgument(app));
549
+ if (options.target) {
550
+ appArguments.push(options.target);
551
+ }
552
+ } else if (options.target) {
553
+ encodedArguments.push(executePowerShell.escapeArgument(options.target));
554
+ }
555
+ if (appArguments.length > 0) {
556
+ appArguments = appArguments.map((argument) => executePowerShell.escapeArgument(argument));
557
+ encodedArguments.push("-ArgumentList", appArguments.join(","));
558
+ }
559
+ options.target = executePowerShell.encodeCommand(encodedArguments.join(" "));
560
+ if (!options.wait) {
561
+ childProcessOptions.stdio = "ignore";
562
+ }
563
+ } else {
564
+ if (app) {
565
+ command = app;
566
+ } else {
567
+ const isBundled = !__dirname2 || __dirname2 === "/";
568
+ let exeLocalXdgOpen = false;
569
+ try {
570
+ await fs5.access(localXdgOpenPath, fsConstants2.X_OK);
571
+ exeLocalXdgOpen = true;
572
+ } catch {}
573
+ const useSystemXdgOpen = process8.versions.electron ?? (platform === "android" || isBundled || !exeLocalXdgOpen);
574
+ command = useSystemXdgOpen ? "xdg-open" : localXdgOpenPath;
575
+ }
576
+ if (appArguments.length > 0) {
577
+ cliArguments.push(...appArguments);
578
+ }
579
+ if (!options.wait) {
580
+ childProcessOptions.stdio = "ignore";
581
+ childProcessOptions.detached = true;
582
+ }
583
+ }
584
+ if (platform === "darwin" && appArguments.length > 0) {
585
+ cliArguments.push("--args", ...appArguments);
586
+ }
587
+ if (options.target) {
588
+ cliArguments.push(options.target);
589
+ }
590
+ const subprocess = childProcess3.spawn(command, cliArguments, childProcessOptions);
591
+ if (options.wait) {
592
+ return new Promise((resolve, reject) => {
593
+ subprocess.once("error", reject);
594
+ subprocess.once("close", (exitCode) => {
595
+ if (!options.allowNonzeroExitCode && exitCode !== 0) {
596
+ reject(new Error(`Exited with code ${exitCode}`));
597
+ return;
598
+ }
599
+ resolve(subprocess);
600
+ });
601
+ });
602
+ }
603
+ if (isFallbackAttempt) {
604
+ return new Promise((resolve, reject) => {
605
+ subprocess.once("error", reject);
606
+ subprocess.once("spawn", () => {
607
+ subprocess.once("close", (exitCode) => {
608
+ subprocess.off("error", reject);
609
+ if (exitCode !== 0) {
610
+ reject(new Error(`Exited with code ${exitCode}`));
611
+ return;
612
+ }
613
+ subprocess.unref();
614
+ resolve(subprocess);
615
+ });
616
+ });
617
+ });
618
+ }
619
+ subprocess.unref();
620
+ return new Promise((resolve, reject) => {
621
+ subprocess.once("error", reject);
622
+ subprocess.once("spawn", () => {
623
+ subprocess.off("error", reject);
624
+ resolve(subprocess);
625
+ });
626
+ });
627
+ }, open = (target, options) => {
628
+ if (typeof target !== "string") {
629
+ throw new TypeError("Expected a `target`");
630
+ }
631
+ return baseOpen({
632
+ ...options,
633
+ target
634
+ });
635
+ }, openApp = (name, options) => {
636
+ if (typeof name !== "string" && !Array.isArray(name)) {
637
+ throw new TypeError("Expected a valid `name`");
638
+ }
639
+ const { arguments: appArguments = [] } = options ?? {};
640
+ if (appArguments !== undefined && appArguments !== null && !Array.isArray(appArguments)) {
641
+ throw new TypeError("Expected `appArguments` as Array type");
642
+ }
643
+ return baseOpen({
644
+ ...options,
645
+ app: {
646
+ name,
647
+ arguments: appArguments
648
+ }
649
+ });
650
+ }, apps, open_default;
651
+ var init_open = __esm(() => {
652
+ init_wsl_utils();
653
+ init_powershell_utils();
654
+ init_default_browser();
655
+ init_is_inside_container();
656
+ init_is_in_ssh();
657
+ fallbackAttemptSymbol = Symbol("fallbackAttempt");
658
+ __dirname2 = import.meta.url ? path.dirname(fileURLToPath(import.meta.url)) : "";
659
+ localXdgOpenPath = path.join(__dirname2, "xdg-open");
660
+ ({ platform, arch } = process8);
661
+ apps = {
662
+ browser: "browser",
663
+ browserPrivate: "browserPrivate"
664
+ };
665
+ defineLazyProperty(apps, "chrome", () => detectPlatformBinary({
666
+ darwin: "google chrome",
667
+ win32: "chrome",
668
+ linux: ["google-chrome", "google-chrome-stable", "chromium", "chromium-browser"]
669
+ }, {
670
+ wsl: {
671
+ ia32: "/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe",
672
+ x64: ["/mnt/c/Program Files/Google/Chrome/Application/chrome.exe", "/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe"]
673
+ }
674
+ }));
675
+ defineLazyProperty(apps, "brave", () => detectPlatformBinary({
676
+ darwin: "brave browser",
677
+ win32: "brave",
678
+ linux: ["brave-browser", "brave"]
679
+ }, {
680
+ wsl: {
681
+ ia32: "/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe",
682
+ x64: ["/mnt/c/Program Files/BraveSoftware/Brave-Browser/Application/brave.exe", "/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe"]
683
+ }
684
+ }));
685
+ defineLazyProperty(apps, "firefox", () => detectPlatformBinary({
686
+ darwin: "firefox",
687
+ win32: String.raw`C:\Program Files\Mozilla Firefox\firefox.exe`,
688
+ linux: "firefox"
689
+ }, {
690
+ wsl: "/mnt/c/Program Files/Mozilla Firefox/firefox.exe"
691
+ }));
692
+ defineLazyProperty(apps, "edge", () => detectPlatformBinary({
693
+ darwin: "microsoft edge",
694
+ win32: "msedge",
695
+ linux: ["microsoft-edge", "microsoft-edge-dev"]
696
+ }, {
697
+ wsl: "/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe"
698
+ }));
699
+ defineLazyProperty(apps, "safari", () => detectPlatformBinary({
700
+ darwin: "Safari"
701
+ }));
702
+ open_default = open;
703
+ });
704
+
705
+ // ../../common/src/entity-name-rules.ts
706
+ var RESERVED_SQL_KEYWORDS_LOWER = new Set(["group", "order"]);
707
+ var ENTITY_NAME_PATTERN = /^[a-zA-Z][a-zA-Z0-9_]{2,99}$/;
708
+ var FIELD_NAME_PATTERN = /^[a-zA-Z][a-zA-Z0-9]{2,99}$/;
709
+ var RESERVED_FIELD_NAMES_LOWER = new Set([
710
+ "id",
711
+ "createdby",
712
+ "createtime",
713
+ "updatedby",
714
+ "updatetime",
715
+ "recordowner",
716
+ "version"
717
+ ]);
718
+ var RESERVED_KEYWORDS_LOWER = new Set([
719
+ "abstract",
720
+ "as",
721
+ "base",
722
+ "bool",
723
+ "break",
724
+ "byte",
725
+ "case",
726
+ "catch",
727
+ "char",
728
+ "checked",
729
+ "class",
730
+ "const",
731
+ "continue",
732
+ "decimal",
733
+ "default",
734
+ "delegate",
735
+ "do",
736
+ "double",
737
+ "else",
738
+ "enum",
739
+ "event",
740
+ "explicit",
741
+ "extern",
742
+ "false",
743
+ "finally",
744
+ "fixed",
745
+ "float",
746
+ "for",
747
+ "foreach",
748
+ "goto",
749
+ "if",
750
+ "implicit",
751
+ "in",
752
+ "int",
753
+ "interface",
754
+ "internal",
755
+ "is",
756
+ "lock",
757
+ "long",
758
+ "namespace",
759
+ "new",
760
+ "null",
761
+ "object",
762
+ "operator",
763
+ "out",
764
+ "override",
765
+ "params",
766
+ "private",
767
+ "protected",
768
+ "public",
769
+ "readonly",
770
+ "ref",
771
+ "return",
772
+ "sbyte",
773
+ "sealed",
774
+ "short",
775
+ "sizeof",
776
+ "stackalloc",
777
+ "static",
778
+ "string",
779
+ "struct",
780
+ "switch",
781
+ "this",
782
+ "throw",
783
+ "true",
784
+ "try",
785
+ "typeof",
786
+ "uint",
787
+ "ulong",
788
+ "unchecked",
789
+ "unsafe",
790
+ "ushort",
791
+ "using",
792
+ "virtual",
793
+ "void",
794
+ "volatile",
795
+ "while",
796
+ "addhandler",
797
+ "addressof",
798
+ "alias",
799
+ "and",
800
+ "andalso",
801
+ "boolean",
802
+ "byref",
803
+ "byval",
804
+ "call",
805
+ "cbool",
806
+ "cbyte",
807
+ "cchar",
808
+ "cdate",
809
+ "cdbl",
810
+ "cdec",
811
+ "cint",
812
+ "clng",
813
+ "cobj",
814
+ "csbyte",
815
+ "cshort",
816
+ "csng",
817
+ "cstr",
818
+ "ctype",
819
+ "cuint",
820
+ "culng",
821
+ "cushort",
822
+ "date",
823
+ "declare",
824
+ "dim",
825
+ "directcast",
826
+ "each",
827
+ "elseif",
828
+ "end",
829
+ "endif",
830
+ "erase",
831
+ "error",
832
+ "exit",
833
+ "friend",
834
+ "function",
835
+ "get",
836
+ "gettype",
837
+ "getxmlnamespace",
838
+ "global",
839
+ "gosub",
840
+ "goto",
841
+ "handles",
842
+ "implements",
843
+ "imports",
844
+ "inherits",
845
+ "integer",
846
+ "isnot",
847
+ "let",
848
+ "lib",
849
+ "like",
850
+ "loop",
851
+ "me",
852
+ "mod",
853
+ "module",
854
+ "mustinherit",
855
+ "mustoverride",
856
+ "mybase",
857
+ "myclass",
858
+ "narrowing",
859
+ "next",
860
+ "not",
861
+ "nothing",
862
+ "notinheritable",
863
+ "notoverridable",
864
+ "of",
865
+ "on",
866
+ "option",
867
+ "optional",
868
+ "or",
869
+ "orelse",
870
+ "overloads",
871
+ "overridable",
872
+ "overrides",
873
+ "paramarray",
874
+ "partial",
875
+ "property",
876
+ "raiseevent",
877
+ "redim",
878
+ "rem",
879
+ "removehandler",
880
+ "resume",
881
+ "select",
882
+ "set",
883
+ "shadows",
884
+ "shared",
885
+ "single",
886
+ "step",
887
+ "stop",
888
+ "structure",
889
+ "sub",
890
+ "synclock",
891
+ "then",
892
+ "to",
893
+ "trycast",
894
+ "uinteger",
895
+ "ushort",
896
+ "variant",
897
+ "wend",
898
+ "when",
899
+ "widening",
900
+ "with",
901
+ "withevents",
902
+ "writeonly",
903
+ "xor"
904
+ ]);
905
+ function findReservedNameError(name, kind) {
906
+ if (kind === "field" && RESERVED_FIELD_NAMES_LOWER.has(name.toLowerCase())) {
907
+ return {
908
+ message: `Field name '${name}' is reserved`,
909
+ instructions: "The following field names are reserved by the platform (case-insensitive): Id, CreatedBy, CreateTime, UpdatedBy, UpdateTime, RecordOwner, Version. Pick a different name."
910
+ };
911
+ }
912
+ if (RESERVED_KEYWORDS_LOWER.has(name.toLowerCase())) {
913
+ return {
914
+ message: `${kind === "entity" ? "Entity" : kind === "field" ? "Field" : "Choice set"} name '${name}' is a reserved C# or VB keyword`,
915
+ instructions: "Reserved keywords are rejected with RESERVED_LANGUAGE_KEYWORDS. Pick a domain-specific rename, for example 'Case' -> 'WorkItem', 'Class' -> 'Category', 'New' -> 'IsNew'."
916
+ };
917
+ }
918
+ if (kind === "entity" && RESERVED_SQL_KEYWORDS_LOWER.has(name.toLowerCase())) {
919
+ return {
920
+ message: `Entity name '${name}' is a reserved SQL keyword`,
921
+ instructions: "The platform rejects 'Order' and 'Group' as entity names. Pick a domain-specific name such as 'PurchaseOrder' or 'TeamGroup'."
922
+ };
923
+ }
924
+ return null;
925
+ }
926
+ function validateNameFormat(name, kind) {
927
+ const pattern = kind === "field" ? FIELD_NAME_PATTERN : ENTITY_NAME_PATTERN;
928
+ if (pattern.test(name)) {
929
+ return null;
930
+ }
931
+ return {
932
+ message: `Invalid ${kind} name '${name}'`,
933
+ 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."
934
+ };
935
+ }
936
+
937
+ // ../../filesystem/src/node.ts
938
+ import { randomUUID } from "node:crypto";
939
+ import { existsSync } from "node:fs";
940
+ import * as fs6 from "node:fs/promises";
941
+ import * as os2 from "node:os";
942
+ import * as path2 from "node:path";
943
+ var LOCK_HEARTBEAT_MS = 5000;
944
+ var LOCK_STALE_MS = 15000;
945
+ var LOCK_MAX_WAIT_MS = 20000;
946
+ var LOCK_MAX_HOLD_MS = 60000;
947
+ var LOCK_RETRY_MIN_MS = 100;
948
+ var LOCK_RETRY_JITTER_MS = 200;
949
+
950
+ class NodeFileSystem {
951
+ path = {
952
+ join: path2.join,
953
+ resolve: path2.resolve,
954
+ relative: path2.relative,
955
+ dirname: path2.dirname,
956
+ isAbsolute: path2.isAbsolute,
957
+ basename: path2.basename
958
+ };
959
+ env = {
960
+ cwd: process.cwd,
961
+ homedir: os2.homedir,
962
+ tmpdir: os2.tmpdir,
963
+ getenv: (key) => process.env[key]
964
+ };
965
+ utils = {
966
+ open: async (url) => {
967
+ const { default: open2 } = await Promise.resolve().then(() => (init_open(), exports_open));
968
+ await open2(url);
969
+ }
970
+ };
971
+ async readFile(path3, options) {
972
+ try {
973
+ if (options) {
974
+ return await fs6.readFile(path3, "utf-8");
975
+ }
976
+ return await fs6.readFile(path3);
977
+ } catch (error) {
978
+ if (this.isEnoent(error))
979
+ return null;
980
+ throw error;
981
+ }
982
+ }
983
+ async writeFile(filePath, data) {
984
+ const dir = path2.dirname(filePath);
985
+ if (dir) {
986
+ await fs6.mkdir(dir, { recursive: true });
987
+ }
988
+ await fs6.writeFile(filePath, data);
989
+ }
990
+ async appendFile(filePath, data) {
991
+ const dir = path2.dirname(filePath);
992
+ if (dir) {
993
+ await fs6.mkdir(dir, { recursive: true });
994
+ }
995
+ await fs6.appendFile(filePath, data);
996
+ }
997
+ async readdir(dirPath) {
998
+ try {
999
+ return await fs6.readdir(dirPath);
1000
+ } catch (error) {
1001
+ if (this.isEnoent(error))
1002
+ return [];
1003
+ throw error;
1004
+ }
1005
+ }
1006
+ async stat(filePath) {
1007
+ try {
1008
+ const stats = await fs6.stat(filePath);
1009
+ return {
1010
+ isFile: () => stats.isFile(),
1011
+ isDirectory: () => stats.isDirectory(),
1012
+ size: stats.size,
1013
+ mtimeMs: stats.mtimeMs
1014
+ };
1015
+ } catch (error) {
1016
+ if (this.isEnoent(error))
1017
+ return null;
1018
+ throw error;
1019
+ }
1020
+ }
1021
+ async exists(filePath) {
1022
+ return existsSync(filePath);
1023
+ }
1024
+ async mkdir(dirPath) {
1025
+ await fs6.mkdir(dirPath, { recursive: true });
1026
+ }
1027
+ async acquireLock(lockPath) {
1028
+ const canonicalPath = await this.canonicalizeLockTarget(lockPath);
1029
+ const lockFile = `${canonicalPath}.lock`;
1030
+ const ownerId = randomUUID();
1031
+ const start = Date.now();
1032
+ while (true) {
1033
+ try {
1034
+ await fs6.writeFile(lockFile, ownerId, { flag: "wx" });
1035
+ return this.createLockRelease(lockFile, ownerId);
1036
+ } catch (error) {
1037
+ if (!this.hasErrnoCode(error, "EEXIST")) {
1038
+ throw error;
1039
+ }
1040
+ const stats = await fs6.stat(lockFile).catch(() => null);
1041
+ if (stats && Date.now() - stats.mtimeMs > LOCK_STALE_MS) {
1042
+ const reclaimed = await fs6.rm(lockFile, { force: true }).then(() => true).catch(() => false);
1043
+ if (reclaimed)
1044
+ continue;
1045
+ }
1046
+ if (Date.now() - start > LOCK_MAX_WAIT_MS) {
1047
+ throw new Error(`ELOCKED: timed out waiting for lock on ${canonicalPath}`);
1048
+ }
1049
+ await new Promise((resolve2) => setTimeout(resolve2, LOCK_RETRY_MIN_MS + Math.random() * LOCK_RETRY_JITTER_MS));
1050
+ }
1051
+ }
1052
+ }
1053
+ async canonicalizeLockTarget(lockPath) {
1054
+ const absolute = path2.resolve(lockPath);
1055
+ const fullReal = await fs6.realpath(absolute).catch(() => null);
1056
+ if (fullReal)
1057
+ return fullReal;
1058
+ const parent = path2.dirname(absolute);
1059
+ const base = path2.basename(absolute);
1060
+ const canonicalParent = await fs6.realpath(parent).catch(() => parent);
1061
+ return path2.join(canonicalParent, base);
1062
+ }
1063
+ createLockRelease(lockFile, ownerId) {
1064
+ const heartbeatStart = Date.now();
1065
+ let heartbeatTimer;
1066
+ let stopped = false;
1067
+ const stopHeartbeat = () => {
1068
+ stopped = true;
1069
+ if (heartbeatTimer)
1070
+ clearTimeout(heartbeatTimer);
1071
+ };
1072
+ const scheduleNextHeartbeat = () => {
1073
+ if (stopped)
1074
+ return;
1075
+ if (Date.now() - heartbeatStart >= LOCK_MAX_HOLD_MS) {
1076
+ stopped = true;
1077
+ return;
1078
+ }
1079
+ heartbeatTimer = setTimeout(() => {
1080
+ runHeartbeat();
1081
+ }, LOCK_HEARTBEAT_MS);
1082
+ heartbeatTimer.unref?.();
1083
+ };
1084
+ const runHeartbeat = async () => {
1085
+ if (stopped)
1086
+ return;
1087
+ const current = await fs6.readFile(lockFile, "utf-8").catch(() => null);
1088
+ if (stopped)
1089
+ return;
1090
+ if (current !== ownerId) {
1091
+ stopped = true;
1092
+ return;
1093
+ }
1094
+ const now = Date.now() / 1000;
1095
+ await fs6.utimes(lockFile, now, now).catch(() => {});
1096
+ scheduleNextHeartbeat();
1097
+ };
1098
+ scheduleNextHeartbeat();
1099
+ let released = false;
1100
+ return async () => {
1101
+ if (released)
1102
+ return;
1103
+ released = true;
1104
+ stopHeartbeat();
1105
+ const current = await fs6.readFile(lockFile, "utf-8").catch(() => null);
1106
+ if (current === ownerId) {
1107
+ await fs6.rm(lockFile, { force: true });
1108
+ }
1109
+ };
1110
+ }
1111
+ async rm(filePath) {
1112
+ await fs6.rm(filePath, { recursive: true, force: true });
1113
+ }
1114
+ async rename(oldPath, newPath) {
1115
+ await fs6.rename(oldPath, newPath);
1116
+ }
1117
+ async isSymbolicLink(filePath) {
1118
+ try {
1119
+ return (await fs6.lstat(filePath)).isSymbolicLink();
1120
+ } catch (error) {
1121
+ if (this.isEnoent(error) || this.hasErrnoCode(error, "ENOTDIR")) {
1122
+ return false;
1123
+ }
1124
+ throw error;
1125
+ }
1126
+ }
1127
+ async realpath(filePath) {
1128
+ try {
1129
+ return await fs6.realpath(filePath);
1130
+ } catch (error) {
1131
+ if (this.isEnoent(error))
1132
+ return filePath;
1133
+ throw error;
1134
+ }
1135
+ }
1136
+ async getTempDir() {
1137
+ return await fs6.mkdtemp(path2.join(os2.tmpdir(), "uipath-fs-"));
1138
+ }
1139
+ async copyDirectory(sourcePath, destPath) {
1140
+ const sourceStats = await this.stat(sourcePath);
1141
+ if (!sourceStats) {
1142
+ throw new Error(`Source directory does not exist: ${sourcePath}`);
1143
+ }
1144
+ if (!sourceStats.isDirectory()) {
1145
+ throw new Error(`Source path is not a directory: ${sourcePath}`);
1146
+ }
1147
+ await this.mkdir(destPath);
1148
+ const entries = await this.readdir(sourcePath);
1149
+ for (const entry of entries) {
1150
+ const srcEntry = path2.join(sourcePath, entry);
1151
+ const destEntry = path2.join(destPath, entry);
1152
+ const entryStats = await this.stat(srcEntry);
1153
+ if (!entryStats)
1154
+ continue;
1155
+ if (entryStats.isDirectory()) {
1156
+ await this.copyDirectory(srcEntry, destEntry);
1157
+ } else if (entryStats.isFile()) {
1158
+ const content = await this.readFile(srcEntry);
1159
+ if (content !== null) {
1160
+ await this.writeFile(destEntry, content);
1161
+ }
1162
+ }
1163
+ }
1164
+ }
1165
+ isEnoent(error) {
1166
+ return this.hasErrnoCode(error, "ENOENT");
1167
+ }
1168
+ hasErrnoCode(error, code) {
1169
+ return typeof error === "object" && error !== null && "code" in error && error.code === code;
1170
+ }
1171
+ }
1172
+
1173
+ // ../../filesystem/src/index.ts
1174
+ var fsInstance = new NodeFileSystem;
1175
+ var getFileSystem = () => fsInstance;
1176
+
1177
+ // src/canonical-path.ts
1178
+ async function canonicalPathAsync(target, fs7) {
1179
+ const realpath2 = fs7.realpath?.bind(fs7);
1180
+ const absolute = fs7.path.resolve(target);
1181
+ if (realpath2 === undefined)
1182
+ return absolute;
1183
+ const tail = [];
1184
+ let current = absolute;
1185
+ while (!await fs7.exists(current)) {
1186
+ const parent = fs7.path.dirname(current);
1187
+ if (parent === current)
1188
+ return absolute;
1189
+ tail.unshift(fs7.path.basename(current));
1190
+ current = parent;
1191
+ }
1192
+ return fs7.path.join(await realpath2(current), ...tail);
1193
+ }
1194
+ async function resolvesInsideAsync(target, root, fs7) {
1195
+ const canonicalRoot = await canonicalPathAsync(root, fs7);
1196
+ const resolved = await canonicalPathAsync(target, fs7);
1197
+ const relative2 = fs7.path.relative(canonicalRoot, resolved);
1198
+ const inside = relative2 !== "" && relative2.split(/[\\/]/)[0] !== ".." && !fs7.path.isAbsolute(relative2);
1199
+ return { inside, resolved, root: canonicalRoot };
1200
+ }
1201
+ async function isSymlinkEntryAsync(target, fs7) {
1202
+ const isSymbolicLink = fs7.isSymbolicLink?.bind(fs7);
1203
+ return isSymbolicLink === undefined ? false : isSymbolicLink(fs7.path.resolve(target));
1204
+ }
1205
+
1206
+ // src/missing-path.ts
1207
+ function isMissingPathError(error) {
1208
+ if (!(error instanceof Error) || !("code" in error))
1209
+ return false;
1210
+ const { code } = error;
1211
+ return code === "ENOENT" || code === "ENOTDIR" || code === "PathNotFound";
1212
+ }
1213
+ function isFilesystemError(error) {
1214
+ const code = error?.code;
1215
+ return typeof code === "string" && /^E[A-Z]+$/.test(code);
1216
+ }
1217
+ function isUnreadablePathError(error) {
1218
+ return isFilesystemError(error) && !isMissingPathError(error);
1219
+ }
1220
+
1221
+ // src/pack/constants.ts
1222
+ var ENTITY_EXTENSION_CONST = ".entity";
1223
+
1224
+ // ../../common/src/telemetry/pseudonymize.ts
1225
+ var PSEUDONYM_DOMAIN = "uipath-cli/telemetry/pseudonym/v1:";
1226
+ var PSEUDONYM_HEX_LENGTH = 32;
1227
+ var SHA256_K = new Uint32Array([
1228
+ 1116352408,
1229
+ 1899447441,
1230
+ 3049323471,
1231
+ 3921009573,
1232
+ 961987163,
1233
+ 1508970993,
1234
+ 2453635748,
1235
+ 2870763221,
1236
+ 3624381080,
1237
+ 310598401,
1238
+ 607225278,
1239
+ 1426881987,
1240
+ 1925078388,
1241
+ 2162078206,
1242
+ 2614888103,
1243
+ 3248222580,
1244
+ 3835390401,
1245
+ 4022224774,
1246
+ 264347078,
1247
+ 604807628,
1248
+ 770255983,
1249
+ 1249150122,
1250
+ 1555081692,
1251
+ 1996064986,
1252
+ 2554220882,
1253
+ 2821834349,
1254
+ 2952996808,
1255
+ 3210313671,
1256
+ 3336571891,
1257
+ 3584528711,
1258
+ 113926993,
1259
+ 338241895,
1260
+ 666307205,
1261
+ 773529912,
1262
+ 1294757372,
1263
+ 1396182291,
1264
+ 1695183700,
1265
+ 1986661051,
1266
+ 2177026350,
1267
+ 2456956037,
1268
+ 2730485921,
1269
+ 2820302411,
1270
+ 3259730800,
1271
+ 3345764771,
1272
+ 3516065817,
1273
+ 3600352804,
1274
+ 4094571909,
1275
+ 275423344,
1276
+ 430227734,
1277
+ 506948616,
1278
+ 659060556,
1279
+ 883997877,
1280
+ 958139571,
1281
+ 1322822218,
1282
+ 1537002063,
1283
+ 1747873779,
1284
+ 1955562222,
1285
+ 2024104815,
1286
+ 2227730452,
1287
+ 2361852424,
1288
+ 2428436474,
1289
+ 2756734187,
1290
+ 3204031479,
1291
+ 3329325298
1292
+ ]);
1293
+ var SHA256_INITIAL_STATE = new Uint32Array([
1294
+ 1779033703,
1295
+ 3144134277,
1296
+ 1013904242,
1297
+ 2773480762,
1298
+ 1359893119,
1299
+ 2600822924,
1300
+ 528734635,
1301
+ 1541459225
1302
+ ]);
1303
+ function rotr(value, bits) {
1304
+ return (value >>> bits | value << 32 - bits) >>> 0;
1305
+ }
1306
+ function sha256Hex(input) {
1307
+ const bytes = new TextEncoder().encode(input);
1308
+ const paddedLength = bytes.length + 9 + 63 >> 6 << 6;
1309
+ const buffer = new Uint8Array(paddedLength);
1310
+ buffer.set(bytes);
1311
+ buffer[bytes.length] = 128;
1312
+ const view = new DataView(buffer.buffer);
1313
+ const bitLength = bytes.length * 8;
1314
+ view.setUint32(paddedLength - 8, Math.floor(bitLength / 4294967296));
1315
+ view.setUint32(paddedLength - 4, bitLength >>> 0);
1316
+ const state = SHA256_INITIAL_STATE.slice();
1317
+ const schedule = new Uint32Array(64);
1318
+ for (let offset = 0;offset < paddedLength; offset += 64) {
1319
+ for (let i = 0;i < 16; i++) {
1320
+ schedule[i] = view.getUint32(offset + i * 4);
1321
+ }
1322
+ for (let i = 16;i < 64; i++) {
1323
+ const x = schedule[i - 15];
1324
+ const y = schedule[i - 2];
1325
+ const s0 = (rotr(x, 7) ^ rotr(x, 18) ^ x >>> 3) >>> 0;
1326
+ const s1 = (rotr(y, 17) ^ rotr(y, 19) ^ y >>> 10) >>> 0;
1327
+ schedule[i] = schedule[i - 16] + s0 + schedule[i - 7] + s1 >>> 0;
1328
+ }
1329
+ let a = state[0];
1330
+ let b = state[1];
1331
+ let c = state[2];
1332
+ let d = state[3];
1333
+ let e = state[4];
1334
+ let f = state[5];
1335
+ let g = state[6];
1336
+ let h = state[7];
1337
+ for (let i = 0;i < 64; i++) {
1338
+ const s1 = (rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25)) >>> 0;
1339
+ const ch = (e & f ^ ~e & g) >>> 0;
1340
+ const temp1 = h + s1 + ch + SHA256_K[i] + schedule[i] >>> 0;
1341
+ const s0 = (rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22)) >>> 0;
1342
+ const maj = (a & b ^ a & c ^ b & c) >>> 0;
1343
+ const temp2 = s0 + maj >>> 0;
1344
+ h = g;
1345
+ g = f;
1346
+ f = e;
1347
+ e = d + temp1 >>> 0;
1348
+ d = c;
1349
+ c = b;
1350
+ b = a;
1351
+ a = temp1 + temp2 >>> 0;
1352
+ }
1353
+ state[0] = state[0] + a >>> 0;
1354
+ state[1] = state[1] + b >>> 0;
1355
+ state[2] = state[2] + c >>> 0;
1356
+ state[3] = state[3] + d >>> 0;
1357
+ state[4] = state[4] + e >>> 0;
1358
+ state[5] = state[5] + f >>> 0;
1359
+ state[6] = state[6] + g >>> 0;
1360
+ state[7] = state[7] + h >>> 0;
1361
+ }
1362
+ let hex = "";
1363
+ for (const word of state) {
1364
+ hex += word.toString(16).padStart(8, "0");
1365
+ }
1366
+ return hex;
1367
+ }
1368
+ function resolveSha256Hex() {
1369
+ try {
1370
+ const nodeCrypto = __require("node:crypto");
1371
+ const createHash = nodeCrypto?.createHash;
1372
+ if (typeof createHash !== "function") {
1373
+ return sha256Hex;
1374
+ }
1375
+ const native = (input) => createHash("sha256").update(input, "utf8").digest("hex");
1376
+ return native("abc") === sha256Hex("abc") ? native : sha256Hex;
1377
+ } catch {
1378
+ return sha256Hex;
1379
+ }
1380
+ }
1381
+ var cachedSha256Hex;
1382
+ function digest(input) {
1383
+ cachedSha256Hex ??= resolveSha256Hex();
1384
+ return cachedSha256Hex(input);
1385
+ }
1386
+ function pseudonymize(input) {
1387
+ return digest(`${PSEUDONYM_DOMAIN}${input}`).slice(0, PSEUDONYM_HEX_LENGTH);
1388
+ }
1389
+
1390
+ // ../../common/src/singleton.ts
1391
+ var PREFIX = "@uipath/common/";
1392
+ var _g = globalThis;
1393
+ function singleton(ctorOrName) {
1394
+ const name = typeof ctorOrName === "string" ? ctorOrName : ctorOrName.name;
1395
+ const key = Symbol.for(PREFIX + name);
1396
+ return {
1397
+ get(fallback) {
1398
+ return _g[key] ?? fallback;
1399
+ },
1400
+ set(value) {
1401
+ _g[key] = value;
1402
+ },
1403
+ clear() {
1404
+ delete _g[key];
1405
+ },
1406
+ getOrInit(factory, guard) {
1407
+ const existing = _g[key];
1408
+ if (existing != null && typeof existing === "object") {
1409
+ if (!guard || guard(existing)) {
1410
+ return existing;
1411
+ }
1412
+ }
1413
+ const instance = factory();
1414
+ _g[key] = instance;
1415
+ return instance;
1416
+ }
1417
+ };
1418
+ }
1419
+
1420
+ // ../../common/src/telemetry/supplied-values.ts
1421
+ var suppliedValuesSlot = singleton("TelemetrySuppliedArgumentValues");
1422
+ function activeEntries() {
1423
+ const existing = suppliedValuesSlot.get();
1424
+ return Array.isArray(existing) ? existing : [];
1425
+ }
1426
+ var MIN_SCRUBBABLE_LENGTH = 4;
1427
+ function recordSuppliedArgumentValues(values) {
1428
+ const flat = [];
1429
+ const push = (value) => {
1430
+ if (Array.isArray(value)) {
1431
+ for (const item of value) {
1432
+ push(item);
1433
+ }
1434
+ return;
1435
+ }
1436
+ if (typeof value === "string" && value.length >= MIN_SCRUBBABLE_LENGTH) {
1437
+ flat.push(value);
1438
+ }
1439
+ };
1440
+ push(values);
1441
+ const entry = { values: flat };
1442
+ suppliedValuesSlot.set([...activeEntries(), entry]);
1443
+ return entry;
1444
+ }
1445
+ function releaseSuppliedArgumentValues(entry) {
1446
+ suppliedValuesSlot.set(activeEntries().filter((held) => held !== entry));
1447
+ }
1448
+ function getSuppliedArgumentValues() {
1449
+ const all = new Set;
1450
+ for (const entry of activeEntries()) {
1451
+ for (const value of entry.values) {
1452
+ all.add(value);
1453
+ }
1454
+ }
1455
+ return [...all].sort((a, b) => b.length - a.length);
1456
+ }
1457
+
1458
+ // ../../common/src/telemetry/pii-redactor.ts
1459
+ var REDACTED = "[REDACTED]";
1460
+ var MAX_VALUE_LENGTH = 280;
1461
+ var MAX_STACK_LENGTH = 4096;
1462
+ var MAX_SCAN_LENGTH = MAX_STACK_LENGTH;
1463
+ function truncate(value, maxLength) {
1464
+ return value.length > maxLength ? `${value.slice(0, maxLength)}…` : value;
1465
+ }
1466
+ var SENSITIVE_NAME_TOKENS = new Set([
1467
+ "token",
1468
+ "tokens",
1469
+ "secret",
1470
+ "secrets",
1471
+ "password",
1472
+ "passwords",
1473
+ "pwd",
1474
+ "credential",
1475
+ "credentials",
1476
+ "auth",
1477
+ "authentication",
1478
+ "authorization",
1479
+ "authority",
1480
+ "cert",
1481
+ "certificate",
1482
+ "certificates"
1483
+ ]);
1484
+ var SENSITIVE_KEY_PREFIXES = new Set([
1485
+ "api",
1486
+ "access",
1487
+ "client",
1488
+ "private",
1489
+ "public",
1490
+ "signing",
1491
+ "encryption",
1492
+ "session",
1493
+ "master",
1494
+ "shared",
1495
+ "root",
1496
+ "ssh",
1497
+ "rsa",
1498
+ "aes",
1499
+ "hmac",
1500
+ "oauth"
1501
+ ]);
1502
+ var UUID_PATTERN = /\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\b/gi;
1503
+ var EMAIL_PATTERN = /\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b/g;
1504
+ var JWT_PATTERN = /\beyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/g;
1505
+ var LONG_TOKEN_PATTERN = /\b[A-Za-z0-9_-]{40,}\b/g;
1506
+ var PADDED_BASE64_PATTERN = /(?<![A-Za-z0-9+/])[A-Za-z0-9+/]{16,}={1,2}(?![A-Za-z0-9+/=])/g;
1507
+ var BASE64_WITH_PLUS_PATTERN = /[A-Za-z0-9+/]{40,}/g;
1508
+ var USER_HOME_PATTERN = /(?<![A-Za-z0-9._-])([/\\])(Users|home|Profiles)([/\\])([^/\\]+)/gi;
1509
+ var UNC_PATH_PATTERN = /(^|[\s"'<>|=,;([{])(\\\\[^\s"'<>|]+)/g;
1510
+ var HOST_PORT_PATTERN = /(?<![/@.\w-])(?!\d+\.\d+\.\d+\.\d+:)[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?(?:\.[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?)+:\d{1,5}\b/g;
1511
+ var SOURCE_FILE_EXTENSIONS = new Set([
1512
+ "ts",
1513
+ "tsx",
1514
+ "js",
1515
+ "jsx",
1516
+ "mjs",
1517
+ "cjs",
1518
+ "cts",
1519
+ "mts",
1520
+ "py",
1521
+ "cs",
1522
+ "java",
1523
+ "go",
1524
+ "rs",
1525
+ "rb",
1526
+ "php",
1527
+ "sh",
1528
+ "ps1",
1529
+ "json",
1530
+ "jsonc",
1531
+ "yaml",
1532
+ "yml",
1533
+ "xml",
1534
+ "xaml",
1535
+ "md",
1536
+ "txt",
1537
+ "log",
1538
+ "css",
1539
+ "html",
1540
+ "htm",
1541
+ "csproj",
1542
+ "nuspec",
1543
+ "sql"
1544
+ ]);
1545
+ var URL_PATTERN = /\bhttps?:\/\/[^\s,;]+/gi;
1546
+ var QUOTED_LITERAL_MAX_SPAN = 200;
1547
+ var QUOTED_LITERAL_PATTERN = new RegExp([
1548
+ `(?<![A-Za-z0-9])'(?:[^\\
1549
+ ]|\\.){2,${QUOTED_LITERAL_MAX_SPAN}}?'(?![A-Za-z0-9])`,
1550
+ `(?<![A-Za-z0-9])"(?:[^\\
1551
+ ]|\\.){2,${QUOTED_LITERAL_MAX_SPAN}}?"(?![A-Za-z0-9])`
1552
+ ].join("|"), "g");
1553
+ var JSON_BODY_PATTERN = /[{[][^{}[\]:,]*[:,][^{}[\]]*[\]}]/g;
1554
+ var COLLAPSED_BODY = "{…}";
1555
+ var COLLAPSED_BODY_MARKER = "\x01body\x01";
1556
+ var MAX_BODY_NESTING = 8;
1557
+ function collapseJsonBodies(text) {
1558
+ let out = text;
1559
+ for (let pass = 0;pass < MAX_BODY_NESTING; pass++) {
1560
+ const next = out.replace(JSON_BODY_PATTERN, COLLAPSED_BODY_MARKER);
1561
+ if (next === out) {
1562
+ break;
1563
+ }
1564
+ out = next;
1565
+ }
1566
+ return out.split(COLLAPSED_BODY_MARKER).join(COLLAPSED_BODY);
1567
+ }
1568
+ var TRAILING_PROSE_PUNCT = `.,;:!?)]}>'"`;
1569
+ function peelTrailingPunctuation(match) {
1570
+ let end = match.length;
1571
+ while (end > 0 && TRAILING_PROSE_PUNCT.includes(match[end - 1])) {
1572
+ end -= 1;
1573
+ }
1574
+ return [match.slice(0, end), match.slice(end)];
1575
+ }
1576
+ function redactUrl(raw) {
1577
+ try {
1578
+ const url = new URL(raw);
1579
+ return `${url.protocol}//${url.host}`;
1580
+ } catch {
1581
+ return `url#${pseudonymize(raw)}`;
1582
+ }
1583
+ }
1584
+ function redactValueDetectors(value, maxLength = MAX_VALUE_LENGTH) {
1585
+ let out = truncate(value, MAX_SCAN_LENGTH);
1586
+ out = out.replace(JWT_PATTERN, () => REDACTED);
1587
+ out = out.replace(URL_PATTERN, (match) => {
1588
+ const [core, trailing] = peelTrailingPunctuation(match);
1589
+ return `${redactUrl(core)}${trailing}`;
1590
+ });
1591
+ out = out.replace(USER_HOME_PATTERN, (_match, sep1, folder, sep2) => `${sep1}${folder}${sep2}<user>`);
1592
+ out = out.replace(UNC_PATH_PATTERN, (_match, before, path3) => {
1593
+ const [core, trailing] = peelTrailingPunctuation(path3);
1594
+ return `${before}unc#${pseudonymize(core)}${trailing}`;
1595
+ });
1596
+ out = out.replace(EMAIL_PATTERN, (match) => `email#${pseudonymize(match)}`);
1597
+ out = out.replace(UUID_PATTERN, (match) => `uuid#${pseudonymize(match)}`);
1598
+ out = out.replace(HOST_PORT_PATTERN, (match) => {
1599
+ const split = match.lastIndexOf(":");
1600
+ const host = match.slice(0, split);
1601
+ const extension = host.slice(host.lastIndexOf(".") + 1).toLowerCase();
1602
+ if (SOURCE_FILE_EXTENSIONS.has(extension)) {
1603
+ return match;
1604
+ }
1605
+ return `host#${pseudonymize(host)}:${match.slice(split + 1)}`;
1606
+ });
1607
+ out = out.replace(PADDED_BASE64_PATTERN, () => REDACTED);
1608
+ out = out.replace(BASE64_WITH_PLUS_PATTERN, (match) => match.includes("+") ? REDACTED : match);
1609
+ out = out.replace(LONG_TOKEN_PATTERN, () => REDACTED);
1610
+ return truncate(out, maxLength);
1611
+ }
1612
+ function redactSpanName(name) {
1613
+ return redactValueDetectors(truncate(name, MAX_SCAN_LENGTH).replace(QUOTED_LITERAL_PATTERN, (match) => `${match[0]}<redacted>${match[0]}`));
1614
+ }
1615
+ var HTTP_DEPENDENCY_NAME = /^([A-Z]+) (\/.*)$/s;
1616
+ function redactHttpDependencyName(name) {
1617
+ const parts = HTTP_DEPENDENCY_NAME.exec(name);
1618
+ if (!parts) {
1619
+ return redactMessage(name);
1620
+ }
1621
+ return `${parts[1]} ${redactMessage(parts[2])}`;
1622
+ }
1623
+ function redactMessage(value) {
1624
+ let out = collapseJsonBodies(truncate(value, MAX_SCAN_LENGTH)).replace(QUOTED_LITERAL_PATTERN, (match) => `${match[0]}<redacted>${match[0]}`);
1625
+ for (const supplied of getSuppliedArgumentValues()) {
1626
+ out = out.split(supplied).join(REDACTED);
1627
+ }
1628
+ return redactValueDetectors(out);
1629
+ }
1630
+ var MESSAGE_NAMES = new Set([
1631
+ "message",
1632
+ "errormessage",
1633
+ "errmessage",
1634
+ "error_message",
1635
+ "msg",
1636
+ "detail",
1637
+ "details",
1638
+ "reason",
1639
+ "instructions",
1640
+ "warning"
1641
+ ]);
1642
+ function isFreeFormValue(name, value) {
1643
+ return MESSAGE_NAMES.has(name.toLowerCase()) || /['"{[]/.test(value);
1644
+ }
1645
+ function redactError(error) {
1646
+ const safe = new Error(redactMessage(error.message ?? ""));
1647
+ safe.name = error.name;
1648
+ safe.stack = typeof error.stack === "string" ? redactStack(error.stack) : undefined;
1649
+ return safe;
1650
+ }
1651
+ function redactStack(stack) {
1652
+ const bounded = truncate(stack, MAX_STACK_LENGTH);
1653
+ const firstBreak = bounded.indexOf(`
1654
+ `);
1655
+ if (firstBreak === -1) {
1656
+ return redactMessage(bounded);
1657
+ }
1658
+ return `${redactMessage(bounded.slice(0, firstBreak))}
1659
+ ${redactValueDetectors(bounded.slice(firstBreak + 1), MAX_STACK_LENGTH)}`;
1660
+ }
1661
+ function nameTokens(name) {
1662
+ 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);
1663
+ }
1664
+ function isSensitiveName(name) {
1665
+ const tokens = nameTokens(name);
1666
+ for (let i = 0;i < tokens.length; i++) {
1667
+ const token = tokens[i];
1668
+ if (SENSITIVE_NAME_TOKENS.has(token)) {
1669
+ return true;
1670
+ }
1671
+ if (token === "key" || token === "keys") {
1672
+ const prev = tokens[i - 1];
1673
+ if (prev && SENSITIVE_KEY_PREFIXES.has(prev)) {
1674
+ return true;
1675
+ }
1676
+ }
1677
+ }
1678
+ return false;
1679
+ }
1680
+ function redactProperty(name, value) {
1681
+ if (value === undefined || value === null) {
1682
+ return;
1683
+ }
1684
+ if (isSensitiveName(name)) {
1685
+ return REDACTED;
1686
+ }
1687
+ if (typeof value === "boolean" || typeof value === "number") {
1688
+ return value;
1689
+ }
1690
+ if (typeof value !== "string") {
1691
+ return "[OBJECT]";
1692
+ }
1693
+ return isFreeFormValue(name, value) ? redactMessage(value) : redactValueDetectors(value);
1694
+ }
1695
+ function redactProperties(properties) {
1696
+ const out = {};
1697
+ for (const [name, value] of Object.entries(properties)) {
1698
+ const redacted = redactProperty(name, value);
1699
+ if (redacted !== undefined) {
1700
+ out[name] = redacted;
1701
+ }
1702
+ }
1703
+ return out;
1704
+ }
1705
+
1706
+ // ../../common/src/catch-error.ts
1707
+ var MAX_SERIALIZED_LENGTH = 500;
1708
+ var TRUNCATION_SUFFIX = "…(truncated)";
1709
+ var REDACTED2 = "[REDACTED]";
1710
+ function cap(text) {
1711
+ return text.length > MAX_SERIALIZED_LENGTH ? `${text.slice(0, MAX_SERIALIZED_LENGTH)}${TRUNCATION_SUFFIX}` : text;
1712
+ }
1713
+ function omitSensitive(key, value) {
1714
+ return key.length > 0 && isSensitiveName(key) ? REDACTED2 : value;
1715
+ }
1716
+ function describeThrownValue(value) {
1717
+ if (typeof value !== "object" || value === null) {
1718
+ return String(value);
1719
+ }
1720
+ let message;
1721
+ try {
1722
+ message = value.message;
1723
+ } catch {
1724
+ message = undefined;
1725
+ }
1726
+ if (typeof message === "string" && message.length > 0) {
1727
+ return cap(message);
1728
+ }
1729
+ try {
1730
+ const json = JSON.stringify(value, omitSensitive);
1731
+ if (json !== undefined) {
1732
+ return cap(json);
1733
+ }
1734
+ } catch {}
1735
+ return String(value);
1736
+ }
1737
+ function toError(error) {
1738
+ return error instanceof Error ? error : new Error(describeThrownValue(error), { cause: error });
1739
+ }
1740
+ function isPromiseLike(value) {
1741
+ return value !== null && typeof value === "object" && typeof value.then === "function";
1742
+ }
1743
+ function catchError(fnOrPromise) {
1744
+ if (isPromiseLike(fnOrPromise)) {
1745
+ return settlePromiseLike(fnOrPromise);
1746
+ }
1747
+ try {
1748
+ const result = fnOrPromise();
1749
+ if (isPromiseLike(result)) {
1750
+ return settlePromiseLike(result);
1751
+ }
1752
+ return [undefined, result];
1753
+ } catch (error) {
1754
+ return [toError(error), undefined];
1755
+ }
1756
+ }
1757
+ function settlePromiseLike(thenable) {
1758
+ return Promise.resolve(thenable).then((data) => [undefined, data]).catch((error) => [toError(error), undefined]);
1759
+ }
1760
+
1761
+ // src/resource/unified-resource-file.ts
1762
+ var ENTITY_RESOURCE_KIND = "entity";
1763
+ var ENTITY_RESOURCE_TYPE = "native";
1764
+ var ENTITY_RESOURCE_API_VERSION = "dataservice.uipath.com/v2";
1765
+ var ENTITY_RESOURCE_DOC_VERSION = "1.0.0";
1766
+ var SOLUTION_FOLDER = "solution_folder";
1767
+ var ENTITY_RESOURCE_DIR = `${ENTITY_RESOURCE_KIND}/${ENTITY_RESOURCE_TYPE}`;
1768
+ function entityResourcePath(entityName) {
1769
+ return `resources/${SOLUTION_FOLDER}/${ENTITY_RESOURCE_DIR}/${entityName}.json`;
1770
+ }
1771
+
1772
+ // src/resource/resource-io.ts
1773
+ function serialize(value) {
1774
+ return `${JSON.stringify(value, null, 2)}
1775
+ `;
1776
+ }
1777
+ function serializeEntityJson(entity) {
1778
+ return JSON.stringify(entity);
1779
+ }
1780
+
1781
+ class EntityResourceError extends Error {
1782
+ failure;
1783
+ constructor(failure, message) {
1784
+ super(message);
1785
+ this.failure = failure;
1786
+ this.name = "EntityResourceError";
1787
+ }
1788
+ }
1789
+ function wrapEntityJson(entity) {
1790
+ return {
1791
+ docVersion: ENTITY_RESOURCE_DOC_VERSION,
1792
+ resource: {
1793
+ name: entity.Name,
1794
+ kind: ENTITY_RESOURCE_KIND,
1795
+ type: ENTITY_RESOURCE_TYPE,
1796
+ apiVersion: ENTITY_RESOURCE_API_VERSION,
1797
+ isOverridable: true,
1798
+ dependencies: [],
1799
+ runtimeDependencies: [],
1800
+ folders: [{ fullyQualifiedName: SOLUTION_FOLDER }],
1801
+ spec: {
1802
+ resourceJson: serializeEntityJson(entity),
1803
+ name: entity.Name,
1804
+ displayName: entity.DisplayName,
1805
+ description: entity.Description
1806
+ },
1807
+ locks: [],
1808
+ key: entity.Id,
1809
+ files: []
1810
+ }
1811
+ };
1812
+ }
1813
+ function unwrapResource(file) {
1814
+ if (typeof file !== "object" || file === null || Array.isArray(file)) {
1815
+ throw new EntityResourceError("NotAnObject", "Resource file is not a JSON object.");
1816
+ }
1817
+ const resource = file.resource;
1818
+ if (typeof resource !== "object" || resource === null) {
1819
+ throw new EntityResourceError("MissingResource", "Resource file has no 'resource' object.");
1820
+ }
1821
+ if (resource.kind !== ENTITY_RESOURCE_KIND) {
1822
+ throw new EntityResourceError("NotAnEntityResource", `Resource kind is '${String(resource.kind)}', expected '${ENTITY_RESOURCE_KIND}'.`);
1823
+ }
1824
+ const spec = resource.spec;
1825
+ if (typeof spec !== "object" || spec === null || typeof spec.resourceJson !== "string") {
1826
+ throw new EntityResourceError("MissingSpec", "Resource file has no 'spec.resourceJson' string.");
1827
+ }
1828
+ try {
1829
+ return JSON.parse(spec.resourceJson);
1830
+ } catch {
1831
+ throw new EntityResourceError("ResourceJsonUnparsable", "'spec.resourceJson' is not valid JSON.");
1832
+ }
1833
+ }
1834
+ function updateResourceSchema(file, entity) {
1835
+ return {
1836
+ ...file,
1837
+ resource: {
1838
+ ...file.resource,
1839
+ name: entity.Name,
1840
+ spec: {
1841
+ ...file.resource.spec,
1842
+ resourceJson: serializeEntityJson(entity),
1843
+ name: entity.Name,
1844
+ displayName: entity.DisplayName,
1845
+ description: entity.Description
1846
+ }
1847
+ }
1848
+ };
1849
+ }
1850
+
1851
+ // src/pack/verify-pair.ts
1852
+ async function verifyPair(stubFile, solutionDir, fs7) {
1853
+ const parsedStub = await readStub(stubFile, fs7);
1854
+ if ("failure" in parsedStub) {
1855
+ return { ok: false, failure: parsedStub.failure };
1856
+ }
1857
+ const stub = parsedStub.stub;
1858
+ const baseName = fs7.path.basename(stubFile, ENTITY_EXTENSION_CONST);
1859
+ if (baseName !== stub.name) {
1860
+ return fail("StubFileNameMismatch", `Stub file '${baseName}${ENTITY_EXTENSION_CONST}' names entity '${stub.name}' — the filename and the entity name must match.`);
1861
+ }
1862
+ const solutionRoot = fs7.path.resolve(solutionDir);
1863
+ const resourceFile = fs7.path.resolve(solutionRoot, ...stub.resourcePath.split("/"));
1864
+ const boundary = resourceFile.charAt(solutionRoot.length);
1865
+ if (!resourceFile.startsWith(solutionRoot) || boundary !== "/" && boundary !== "\\") {
1866
+ return fail("ResourcePathEscapes", `'${stub.name}': resourcePath '${stub.resourcePath}' points outside the solution.`);
1867
+ }
1868
+ const parsedResource = await readResource(resourceFile, stub.name, stub.resourcePath, fs7);
1869
+ if ("failure" in parsedResource) {
1870
+ return { ok: false, failure: parsedResource.failure };
1871
+ }
1872
+ const resourceRaw = parsedResource.raw;
1873
+ let entity;
1874
+ try {
1875
+ entity = unwrapResource(resourceRaw);
1876
+ } catch (error) {
1877
+ const detail = error instanceof EntityResourceError ? ` (${error.failure})` : "";
1878
+ return fail("ResourceInvalid", `'${stub.name}': resource '${stub.resourcePath}' is not a valid entity resource${detail}.`);
1879
+ }
1880
+ if (entity.Name !== stub.name) {
1881
+ return fail("NameCoupling", `Stub '${stub.name}' points at a resource defining entity '${entity.Name}' — the names must match.`);
1882
+ }
1883
+ return { ok: true, entityName: stub.name, resourceFile, entity };
1884
+ }
1885
+ function fail(code, message) {
1886
+ return { ok: false, failure: { code, message } };
1887
+ }
1888
+ async function readStub(stubFile, fs7) {
1889
+ let parsed;
1890
+ try {
1891
+ const raw = await fs7.readFile(stubFile);
1892
+ if (raw === null) {
1893
+ return failure("StubUnparsable", `'${stubFile}' could not be read.`);
1894
+ }
1895
+ parsed = JSON.parse(decode(raw));
1896
+ } catch {
1897
+ return failure("StubUnparsable", `'${stubFile}' is not valid JSON.`);
1898
+ }
1899
+ if (typeof parsed !== "object" || parsed === null || typeof parsed.name !== "string" || typeof parsed.resourcePath !== "string") {
1900
+ return failure("StubUnparsable", `'${stubFile}' must be an object with string 'name' and 'resourcePath'.`);
1901
+ }
1902
+ return { stub: { name: parsed.name, resourcePath: parsed.resourcePath } };
1903
+ }
1904
+ async function readResource(resourceFile, entityName, resourcePath, fs7) {
1905
+ const missing = failure("ResourceMissing", `'${entityName}': definition resource '${resourcePath}' is missing. Restore it (check trash/backup) or delete the entity.`);
1906
+ try {
1907
+ const raw = await fs7.readFile(resourceFile);
1908
+ if (raw === null) {
1909
+ return missing;
1910
+ }
1911
+ return { raw: JSON.parse(decode(raw)) };
1912
+ } catch (error) {
1913
+ if (error instanceof SyntaxError) {
1914
+ return failure("ResourceInvalid", `'${entityName}': resource '${resourcePath}' is not valid JSON.`);
1915
+ }
1916
+ return missing;
1917
+ }
1918
+ }
1919
+ function decode(raw) {
1920
+ return typeof raw === "string" ? raw : new TextDecoder().decode(raw);
1921
+ }
1922
+ function failure(code, message) {
1923
+ return { failure: { code, message } };
1924
+ }
1925
+ async function findSolutionRoot(startDir, fs7) {
1926
+ let dir = fs7.path.resolve(startDir);
1927
+ let unreadable;
1928
+ for (;; ) {
1929
+ const [error, entries] = await catchError(fs7.readdir(dir));
1930
+ if (error && isUnreadablePathError(error)) {
1931
+ unreadable ??= error;
1932
+ }
1933
+ if (entries?.some((name) => name.endsWith(".uipx"))) {
1934
+ if (unreadable) {
1935
+ throw Object.assign(new Error(`Could not locate the solution from '${startDir}': ${unreadable.message}. A directory between here and the nearest .uipx cannot be read, and it may be the solution itself — fix read access and retry.`, { cause: unreadable }), { code: unreadable.code });
1936
+ }
1937
+ return dir;
1938
+ }
1939
+ const parent = fs7.path.dirname(dir);
1940
+ if (parent === dir) {
1941
+ return;
1942
+ }
1943
+ dir = parent;
1944
+ }
1945
+ }
1946
+
1947
+ // ../../common/src/entity-field-rules.ts
1948
+ var MAX_SAFE_NUMERIC_BOUND = 9007199254740991;
1949
+ var LENGTH_LIMIT_RANGES = {
1950
+ STRING: [1, 4000],
1951
+ MULTILINE_TEXT: [1, 1e4],
1952
+ MULTILINE_MAX: [1, 131072]
1953
+ };
1954
+ var MAX_MULTILINE_MAX_FIELDS = 10;
1955
+ function isNumber(v) {
1956
+ return typeof v === "number" && Number.isFinite(v);
1957
+ }
1958
+ function findInvalidFieldConstraints(fields) {
1959
+ for (const f of fields) {
1960
+ if (typeof f !== "object" || f === null)
1961
+ continue;
1962
+ const rec = f;
1963
+ const type = rec.type;
1964
+ if (typeof type !== "string")
1965
+ continue;
1966
+ const fieldName = typeof rec.name === "string" ? rec.name : "<field>";
1967
+ if (rec.lengthLimit !== undefined) {
1968
+ if (!isNumber(rec.lengthLimit) || !Number.isInteger(rec.lengthLimit)) {
1969
+ return {
1970
+ message: `Field '${fieldName}' 'lengthLimit' must be an integer`,
1971
+ instructions: "Pass a positive integer within the type's range (STRING 1-4000, MULTILINE_TEXT 1-10000, MULTILINE_MAX 1-131072 UTF-16 bytes)."
1972
+ };
1973
+ }
1974
+ const range = LENGTH_LIMIT_RANGES[type];
1975
+ if (range === undefined) {
1976
+ return {
1977
+ message: `Field '${fieldName}' of type '${type}' does not accept 'lengthLimit'`,
1978
+ instructions: "'lengthLimit' applies only to STRING, MULTILINE_TEXT, and MULTILINE_MAX. Remove it or change the field type."
1979
+ };
1980
+ }
1981
+ const [min, max] = range;
1982
+ if (rec.lengthLimit < min || rec.lengthLimit > max) {
1983
+ return {
1984
+ message: `Field '${fieldName}' 'lengthLimit' ${rec.lengthLimit} is outside the allowed range for type '${type}'`,
1985
+ instructions: `'lengthLimit' on '${type}' must be between ${min} and ${max}. MULTILINE_MAX 'lengthLimit' is a UTF-16 byte budget (≈2 per char).`
1986
+ };
1987
+ }
1988
+ }
1989
+ if (rec.maxValue !== undefined || rec.minValue !== undefined) {
1990
+ if (type !== "DECIMAL" && type !== "AUTO_NUMBER") {
1991
+ const which = rec.maxValue !== undefined ? "maxValue" : "minValue";
1992
+ return {
1993
+ message: `Field '${fieldName}' of type '${type}' does not accept '${which}'`,
1994
+ instructions: "'minValue' and 'maxValue' apply only to DECIMAL and AUTO_NUMBER. Remove them or change the field type."
1995
+ };
1996
+ }
1997
+ if (rec.maxValue !== undefined && !isNumber(rec.maxValue)) {
1998
+ return {
1999
+ message: `Field '${fieldName}' 'maxValue' must be a number`,
2000
+ instructions: "Pass a numeric value."
2001
+ };
2002
+ }
2003
+ if (rec.minValue !== undefined && !isNumber(rec.minValue)) {
2004
+ return {
2005
+ message: `Field '${fieldName}' 'minValue' must be a number`,
2006
+ instructions: "Pass a numeric value."
2007
+ };
2008
+ }
2009
+ const maxValue = rec.maxValue;
2010
+ if (maxValue !== undefined && (maxValue > MAX_SAFE_NUMERIC_BOUND || maxValue < -MAX_SAFE_NUMERIC_BOUND)) {
2011
+ return {
2012
+ message: `Field '${fieldName}' 'maxValue' ${rec.maxValue} is outside the supported numeric range`,
2013
+ instructions: `Use a value between ${-MAX_SAFE_NUMERIC_BOUND} and ${MAX_SAFE_NUMERIC_BOUND}.`
2014
+ };
2015
+ }
2016
+ const minValue = rec.minValue;
2017
+ if (minValue !== undefined && (minValue > MAX_SAFE_NUMERIC_BOUND || minValue < -MAX_SAFE_NUMERIC_BOUND)) {
2018
+ return {
2019
+ message: `Field '${fieldName}' 'minValue' ${rec.minValue} is outside the supported numeric range`,
2020
+ instructions: `Use a value between ${-MAX_SAFE_NUMERIC_BOUND} and ${MAX_SAFE_NUMERIC_BOUND}.`
2021
+ };
2022
+ }
2023
+ if (rec.maxValue !== undefined && rec.minValue !== undefined && rec.minValue > rec.maxValue) {
2024
+ return {
2025
+ message: `Field '${fieldName}' 'minValue' (${rec.minValue}) must not exceed 'maxValue' (${rec.maxValue})`,
2026
+ instructions: "Adjust the bounds so 'minValue <= maxValue', or drop one of the two."
2027
+ };
2028
+ }
2029
+ }
2030
+ if (rec.decimalPrecision !== undefined) {
2031
+ if (type !== "DECIMAL" && type !== "AUTO_NUMBER") {
2032
+ return {
2033
+ message: `Field '${fieldName}' of type '${type}' does not accept 'decimalPrecision'`,
2034
+ instructions: "'decimalPrecision' applies only to DECIMAL and AUTO_NUMBER. Remove it or change the field type."
2035
+ };
2036
+ }
2037
+ if (!isNumber(rec.decimalPrecision) || !Number.isInteger(rec.decimalPrecision) || rec.decimalPrecision < 0 || rec.decimalPrecision > 10) {
2038
+ return {
2039
+ message: `Field '${fieldName}' 'decimalPrecision' ${rec.decimalPrecision} is invalid`,
2040
+ instructions: "'decimalPrecision' must be an integer between 0 and 10 (0 for whole numbers, 2 for money)."
2041
+ };
2042
+ }
2043
+ }
2044
+ }
2045
+ return null;
2046
+ }
2047
+
2048
+ // ../../../node_modules/@uipath/entity-modeler/dist/chunk-7VKIHCI7.js
2049
+ var SqlTypeName = {
2050
+ UNIQUEIDENTIFIER: "UNIQUEIDENTIFIER",
2051
+ NVARCHAR: "NVARCHAR",
2052
+ INT: "INT",
2053
+ DATETIME2: "DATETIME2",
2054
+ DATETIMEOFFSET: "DATETIMEOFFSET",
2055
+ FLOAT: "FLOAT",
2056
+ REAL: "REAL",
2057
+ BIGINT: "BIGINT",
2058
+ DATE: "DATE",
2059
+ BIT: "BIT",
2060
+ DECIMAL: "DECIMAL",
2061
+ MULTILINE: "MULTILINE",
2062
+ MULTILINE_MAX: "MULTILINE_MAX",
2063
+ UNKNOWN: "UNKNOWN"
2064
+ };
2065
+ var FieldDisplayType = {
2066
+ Basic: "Basic",
2067
+ Relationship: "Relationship",
2068
+ File: "File",
2069
+ ChoiceSetSingle: "ChoiceSetSingle",
2070
+ ChoiceSetMultiple: "ChoiceSetMultiple",
2071
+ AutoNumber: "AutoNumber",
2072
+ MultiLineText: "MultiLineText"
2073
+ };
2074
+ var DEFAULT_REFERENCE_TYPE = "ManyToOne";
2075
+ var CSHARP_RESERVED_WORDS = [
2076
+ "__arglist",
2077
+ "__makeref",
2078
+ "__reftype",
2079
+ "__refvalue",
2080
+ "abstract",
2081
+ "as",
2082
+ "base",
2083
+ "bool",
2084
+ "break",
2085
+ "byte",
2086
+ "case",
2087
+ "catch",
2088
+ "char",
2089
+ "checked",
2090
+ "class",
2091
+ "const",
2092
+ "continue",
2093
+ "decimal",
2094
+ "default",
2095
+ "delegate",
2096
+ "do",
2097
+ "double",
2098
+ "else",
2099
+ "enum",
2100
+ "event",
2101
+ "explicit",
2102
+ "extern",
2103
+ "false",
2104
+ "finally",
2105
+ "fixed",
2106
+ "float",
2107
+ "for",
2108
+ "foreach",
2109
+ "goto",
2110
+ "if",
2111
+ "implicit",
2112
+ "in",
2113
+ "int",
2114
+ "interface",
2115
+ "internal",
2116
+ "is",
2117
+ "lock",
2118
+ "long",
2119
+ "namespace",
2120
+ "new",
2121
+ "null",
2122
+ "object",
2123
+ "operator",
2124
+ "out",
2125
+ "override",
2126
+ "params",
2127
+ "partial",
2128
+ "private",
2129
+ "protected",
2130
+ "public",
2131
+ "readonly",
2132
+ "ref",
2133
+ "return",
2134
+ "sbyte",
2135
+ "sealed",
2136
+ "short",
2137
+ "sizeof",
2138
+ "stackalloc",
2139
+ "static",
2140
+ "string",
2141
+ "struct",
2142
+ "switch",
2143
+ "this",
2144
+ "throw",
2145
+ "true",
2146
+ "try",
2147
+ "typeof",
2148
+ "uint",
2149
+ "ulong",
2150
+ "unchecked",
2151
+ "unsafe",
2152
+ "ushort",
2153
+ "using",
2154
+ "virtual",
2155
+ "void",
2156
+ "volatile",
2157
+ "where",
2158
+ "while",
2159
+ "yield"
2160
+ ];
2161
+ var VB_RESERVED_WORDS = [
2162
+ "addhandler",
2163
+ "addressof",
2164
+ "alias",
2165
+ "and",
2166
+ "andalso",
2167
+ "ansi",
2168
+ "as",
2169
+ "assembly",
2170
+ "auto",
2171
+ "boolean",
2172
+ "byref",
2173
+ "byte",
2174
+ "byval",
2175
+ "call",
2176
+ "case",
2177
+ "catch",
2178
+ "cbool",
2179
+ "cbyte",
2180
+ "cchar",
2181
+ "cdate",
2182
+ "cdbl",
2183
+ "cdec",
2184
+ "char",
2185
+ "cint",
2186
+ "class",
2187
+ "class_finalize",
2188
+ "class_initialize",
2189
+ "clng",
2190
+ "cobj",
2191
+ "const",
2192
+ "continue",
2193
+ "csbyte",
2194
+ "cshort",
2195
+ "csng",
2196
+ "cstr",
2197
+ "ctype",
2198
+ "cuint",
2199
+ "culng",
2200
+ "cushort",
2201
+ "date",
2202
+ "decimal",
2203
+ "declare",
2204
+ "default",
2205
+ "delegate",
2206
+ "dim",
2207
+ "directcast",
2208
+ "do",
2209
+ "double",
2210
+ "each",
2211
+ "else",
2212
+ "elseif",
2213
+ "end",
2214
+ "endif",
2215
+ "enum",
2216
+ "erase",
2217
+ "error",
2218
+ "event",
2219
+ "exit",
2220
+ "false",
2221
+ "finally",
2222
+ "for",
2223
+ "friend",
2224
+ "function",
2225
+ "get",
2226
+ "gettype",
2227
+ "global",
2228
+ "gosub",
2229
+ "goto",
2230
+ "handles",
2231
+ "if",
2232
+ "implements",
2233
+ "imports",
2234
+ "in",
2235
+ "inherits",
2236
+ "integer",
2237
+ "interface",
2238
+ "is",
2239
+ "isnot",
2240
+ "let",
2241
+ "lib",
2242
+ "like",
2243
+ "long",
2244
+ "loop",
2245
+ "me",
2246
+ "mod",
2247
+ "module",
2248
+ "mustinherit",
2249
+ "mustoverride",
2250
+ "mybase",
2251
+ "myclass",
2252
+ "namespace",
2253
+ "narrowing",
2254
+ "new",
2255
+ "next",
2256
+ "not",
2257
+ "nothing",
2258
+ "notinheritable",
2259
+ "notoverridable",
2260
+ "object",
2261
+ "of",
2262
+ "on",
2263
+ "operator",
2264
+ "option",
2265
+ "optional",
2266
+ "or",
2267
+ "orelse",
2268
+ "overloads",
2269
+ "overridable",
2270
+ "overrides",
2271
+ "paramarray",
2272
+ "partial",
2273
+ "preserve",
2274
+ "private",
2275
+ "property",
2276
+ "protected",
2277
+ "public",
2278
+ "raiseevent",
2279
+ "readonly",
2280
+ "redim",
2281
+ "rem",
2282
+ "removehandler",
2283
+ "resume",
2284
+ "return",
2285
+ "sbyte",
2286
+ "select",
2287
+ "set",
2288
+ "shadows",
2289
+ "shared",
2290
+ "short",
2291
+ "single",
2292
+ "static",
2293
+ "step",
2294
+ "stop",
2295
+ "string",
2296
+ "structure",
2297
+ "sub",
2298
+ "synclock",
2299
+ "then",
2300
+ "throw",
2301
+ "to",
2302
+ "true",
2303
+ "try",
2304
+ "trycast",
2305
+ "typeof",
2306
+ "uinteger",
2307
+ "ulong",
2308
+ "unicode",
2309
+ "until",
2310
+ "ushort",
2311
+ "using",
2312
+ "variant",
2313
+ "wend",
2314
+ "when",
2315
+ "while",
2316
+ "widening",
2317
+ "with",
2318
+ "withevents",
2319
+ "writeonly",
2320
+ "xor"
2321
+ ];
2322
+ var CSHARP_RESERVED = new Set(CSHARP_RESERVED_WORDS);
2323
+ var VB_RESERVED = new Set(VB_RESERVED_WORDS);
2324
+ var GA_TYPE_PAIRS = [
2325
+ [FieldDisplayType.Basic, SqlTypeName.NVARCHAR],
2326
+ [FieldDisplayType.Basic, SqlTypeName.DECIMAL],
2327
+ [FieldDisplayType.Basic, SqlTypeName.FLOAT],
2328
+ [FieldDisplayType.Basic, SqlTypeName.BIT],
2329
+ [FieldDisplayType.Basic, SqlTypeName.DATE],
2330
+ [FieldDisplayType.Basic, SqlTypeName.DATETIMEOFFSET],
2331
+ [FieldDisplayType.Basic, SqlTypeName.UNIQUEIDENTIFIER],
2332
+ [FieldDisplayType.AutoNumber, SqlTypeName.DECIMAL],
2333
+ [FieldDisplayType.Basic, SqlTypeName.MULTILINE],
2334
+ [FieldDisplayType.Basic, SqlTypeName.MULTILINE_MAX],
2335
+ [FieldDisplayType.File, SqlTypeName.UNIQUEIDENTIFIER]
2336
+ ];
2337
+ var ALLOWED_TYPE_PAIRS = new Set(GA_TYPE_PAIRS.map(([display, sql]) => `${display}:${sql}`));
2338
+ // src/sort-names.ts
2339
+ function byName(a, b) {
2340
+ return a.localeCompare(b, "en");
2341
+ }
2342
+
2343
+ // src/schema/author-field.ts
2344
+ var TYPE_MAP = {
2345
+ STRING: [FieldDisplayType.Basic, SqlTypeName.NVARCHAR],
2346
+ DECIMAL: [FieldDisplayType.Basic, SqlTypeName.DECIMAL],
2347
+ BOOLEAN: [FieldDisplayType.Basic, SqlTypeName.BIT],
2348
+ DATE: [FieldDisplayType.Basic, SqlTypeName.DATE],
2349
+ DATETIME_WITH_TZ: [FieldDisplayType.Basic, SqlTypeName.DATETIMEOFFSET],
2350
+ MULTILINE_TEXT: [FieldDisplayType.Basic, SqlTypeName.MULTILINE],
2351
+ MULTILINE_MAX: [FieldDisplayType.Basic, SqlTypeName.MULTILINE_MAX],
2352
+ AUTO_NUMBER: [FieldDisplayType.AutoNumber, SqlTypeName.DECIMAL],
2353
+ FILE: [FieldDisplayType.File, SqlTypeName.UNIQUEIDENTIFIER]
2354
+ };
2355
+ var AUTHORABLE_FIELD_TYPES = Object.freeze(Object.keys(TYPE_MAP).sort(byName));
2356
+ var UNAUTHORABLE_TYPES = {
2357
+ CHOICE_SET_SINGLE: "choice-set fields are not authorable locally — add the field in Data Fabric",
2358
+ CHOICE_SET_MULTIPLE: "choice-set fields are not authorable locally — add the field in Data Fabric",
2359
+ RELATIONSHIP: "relationship fields are not authorable locally — add the field in Data Fabric",
2360
+ INTEGER: "use DECIMAL with decimalPrecision: 0",
2361
+ BIG_INTEGER: "use DECIMAL with decimalPrecision: 0",
2362
+ FLOAT: "use DECIMAL with a decimalPrecision",
2363
+ DOUBLE: "use DECIMAL with a decimalPrecision",
2364
+ UUID: "use STRING",
2365
+ DATETIME: "use DATETIME_WITH_TZ"
2366
+ };
2367
+
2368
+ class AuthoredFieldError extends Error {
2369
+ instructions;
2370
+ constructor(message, instructions) {
2371
+ super(message);
2372
+ this.instructions = instructions;
2373
+ this.name = "AuthoredFieldError";
2374
+ }
2375
+ }
2376
+ function buildSqlType(name, spec) {
2377
+ const sqlType = { Name: name };
2378
+ if (spec.lengthLimit != null)
2379
+ sqlType.LengthLimit = spec.lengthLimit;
2380
+ if (spec.decimalPrecision != null)
2381
+ sqlType.DecimalPrecision = spec.decimalPrecision;
2382
+ if (spec.maxValue != null)
2383
+ sqlType.MaxValue = spec.maxValue;
2384
+ if (spec.minValue != null)
2385
+ sqlType.MinValue = spec.minValue;
2386
+ return sqlType;
2387
+ }
2388
+ var DEFAULT_VALUE_SHAPES = {
2389
+ BOOLEAN: '"true" or "false"',
2390
+ DECIMAL: 'a number in quotes, e.g. "0"',
2391
+ AUTO_NUMBER: 'a number in quotes, e.g. "0"'
2392
+ };
2393
+ function assertDefaultValue(spec, checkContent) {
2394
+ const value = spec.defaultValue;
2395
+ if (value === undefined || value === null) {
2396
+ return;
2397
+ }
2398
+ if (!checkContent) {
2399
+ return;
2400
+ }
2401
+ if (typeof value !== "string") {
2402
+ const shape = DEFAULT_VALUE_SHAPES[spec.type] ?? "a string";
2403
+ 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.`);
2404
+ }
2405
+ if (spec.type === "BOOLEAN" && value.toLowerCase() !== "true" && value.toLowerCase() !== "false") {
2406
+ throw new AuthoredFieldError(`Field '${spec.name}': 'defaultValue' ${JSON.stringify(value)} is not a boolean`, 'A BOOLEAN default is the text "true" or "false".');
2407
+ }
2408
+ if ((spec.type === "DECIMAL" || spec.type === "AUTO_NUMBER") && (value.trim() === "" || !Number.isFinite(Number(value)))) {
2409
+ 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".`);
2410
+ }
2411
+ }
2412
+ function authorField(spec, options = {}) {
2413
+ const pair = TYPE_MAP[spec.type];
2414
+ if (pair === undefined) {
2415
+ const redirect = UNAUTHORABLE_TYPES[spec.type];
2416
+ 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(", ")}.`);
2417
+ }
2418
+ const [fieldDisplayType, sqlTypeName] = pair;
2419
+ const pairKey = `${fieldDisplayType}:${sqlTypeName}`;
2420
+ if (!ALLOWED_TYPE_PAIRS.has(pairKey)) {
2421
+ 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.");
2422
+ }
2423
+ for (const [key, value] of [
2424
+ ["isRequired", spec.isRequired],
2425
+ ["isUnique", spec.isUnique]
2426
+ ]) {
2427
+ if (value !== undefined && typeof value !== "boolean") {
2428
+ throw new AuthoredFieldError(`Field '${spec.name}': '${key}' must be true or false`, `Received ${JSON.stringify(value)}. Use a JSON boolean, not a string.`);
2429
+ }
2430
+ }
2431
+ for (const [key, value] of [
2432
+ ["displayName", spec.displayName],
2433
+ ["description", spec.description]
2434
+ ]) {
2435
+ if (value !== undefined && typeof value !== "string") {
2436
+ throw new AuthoredFieldError(`Field '${spec.name}': '${key}' must be a string`, `Received ${JSON.stringify(value)}.`);
2437
+ }
2438
+ }
2439
+ assertDefaultValue(spec, options.defaultValueFromCaller !== false);
2440
+ const constraintError = findInvalidFieldConstraints([
2441
+ {
2442
+ name: spec.name,
2443
+ type: spec.type,
2444
+ ...spec.lengthLimit != null && {
2445
+ lengthLimit: spec.lengthLimit
2446
+ },
2447
+ ...spec.decimalPrecision != null && {
2448
+ decimalPrecision: spec.decimalPrecision
2449
+ },
2450
+ ...spec.maxValue != null && { maxValue: spec.maxValue },
2451
+ ...spec.minValue != null && { minValue: spec.minValue }
2452
+ }
2453
+ ]);
2454
+ if (constraintError) {
2455
+ throw new AuthoredFieldError(constraintError.message, constraintError.instructions);
2456
+ }
2457
+ return {
2458
+ Name: spec.name,
2459
+ DisplayName: spec.displayName ?? spec.name,
2460
+ SqlType: buildSqlType(sqlTypeName, spec),
2461
+ IsRequired: spec.isRequired ?? false,
2462
+ IsUnique: spec.isUnique ?? false,
2463
+ IsPrimaryKey: false,
2464
+ IsForeignKey: false,
2465
+ IsExternalField: false,
2466
+ IsHiddenField: false,
2467
+ FieldCategoryId: 0,
2468
+ ReferenceType: DEFAULT_REFERENCE_TYPE,
2469
+ Transformation: null,
2470
+ IsEncrypted: false,
2471
+ Description: spec.description ?? "",
2472
+ IsSystemField: false,
2473
+ FieldDisplayType: fieldDisplayType,
2474
+ DefaultValue: spec.defaultValue ?? null,
2475
+ IsAttachment: false,
2476
+ IsRbacEnabled: false,
2477
+ IsModelReserved: false,
2478
+ ReferenceChoiceSet: null,
2479
+ ReferenceEntity: null,
2480
+ ReferenceField: null,
2481
+ ReferenceName: null
2482
+ };
2483
+ }
2484
+
2485
+ // src/schema/create-entity-skeleton.ts
2486
+ var UNASSIGNED_FOLDER_ID = "99999999-9999-9999-9999-999999999999";
2487
+ function isLocallyAuthored(entity) {
2488
+ return entity.FolderId === UNASSIGNED_FOLDER_ID;
2489
+ }
2490
+ var SYSTEM_FIELD_DEFAULTS = {
2491
+ IsPrimaryKey: false,
2492
+ IsForeignKey: false,
2493
+ IsExternalField: false,
2494
+ IsHiddenField: true,
2495
+ FieldCategoryId: 0,
2496
+ IsUnique: false,
2497
+ ReferenceType: "ManyToOne",
2498
+ Transformation: null,
2499
+ IsRequired: false,
2500
+ IsEncrypted: false,
2501
+ Description: "",
2502
+ IsSystemField: true,
2503
+ FieldDisplayType: FieldDisplayType.Basic,
2504
+ IsAttachment: false,
2505
+ IsRbacEnabled: false,
2506
+ IsModelReserved: false
2507
+ };
2508
+ var SYSTEM_FIELD_TEMPLATES = [
2509
+ {
2510
+ ...SYSTEM_FIELD_DEFAULTS,
2511
+ Name: "Id",
2512
+ DisplayName: "Id",
2513
+ IsPrimaryKey: true,
2514
+ SqlType: { Name: SqlTypeName.UNIQUEIDENTIFIER }
2515
+ },
2516
+ {
2517
+ ...SYSTEM_FIELD_DEFAULTS,
2518
+ Name: "CreateTime",
2519
+ DisplayName: "CreateTime",
2520
+ SqlType: { Name: SqlTypeName.DATETIMEOFFSET }
2521
+ },
2522
+ {
2523
+ ...SYSTEM_FIELD_DEFAULTS,
2524
+ Name: "CreatedBy",
2525
+ DisplayName: "CreatedBy",
2526
+ FieldDisplayType: FieldDisplayType.Relationship,
2527
+ SqlType: { Name: SqlTypeName.UNIQUEIDENTIFIER }
2528
+ },
2529
+ {
2530
+ ...SYSTEM_FIELD_DEFAULTS,
2531
+ Name: "UpdateTime",
2532
+ DisplayName: "UpdateTime",
2533
+ SqlType: { Name: SqlTypeName.DATETIMEOFFSET }
2534
+ },
2535
+ {
2536
+ ...SYSTEM_FIELD_DEFAULTS,
2537
+ Name: "UpdatedBy",
2538
+ DisplayName: "UpdatedBy",
2539
+ FieldDisplayType: FieldDisplayType.Relationship,
2540
+ SqlType: { Name: SqlTypeName.UNIQUEIDENTIFIER }
2541
+ }
2542
+ ];
2543
+ function createEntitySkeleton(name) {
2544
+ return {
2545
+ Id: globalThis.crypto.randomUUID(),
2546
+ Name: name,
2547
+ DisplayName: name,
2548
+ EntityTypeId: 0,
2549
+ EntityType: "Entity",
2550
+ Description: "",
2551
+ FolderId: UNASSIGNED_FOLDER_ID,
2552
+ Fields: SYSTEM_FIELD_TEMPLATES.map((template) => ({
2553
+ ...template,
2554
+ SqlType: { ...template.SqlType }
2555
+ })),
2556
+ Data: null,
2557
+ ExternalFields: null,
2558
+ SourceJoinCriterias: null,
2559
+ RecordCount: 0,
2560
+ StorageSizeInMB: null,
2561
+ UsedStorageSizeInMB: null,
2562
+ AttachmentSizeInByte: null,
2563
+ IsRbacEnabled: false,
2564
+ InvalidIdentifiers: [],
2565
+ IsModelReserved: false,
2566
+ CategoryId: null
2567
+ };
2568
+ }
2569
+ function requireAuthoredName(authored, entityName) {
2570
+ if (authored !== undefined && authored.Name !== entityName) {
2571
+ throw new AuthoredFieldError(`Authored entity '${authored.Name}' cannot be written as '${entityName}'`, "Author the document with the name it is created under.");
2572
+ }
2573
+ }
2574
+
2575
+ // src/schema/solution-entity-names.ts
2576
+ function withoutOneOccurrence(names, name) {
2577
+ const siblings = [...names];
2578
+ const self = siblings.indexOf(name);
2579
+ if (self >= 0) {
2580
+ siblings.splice(self, 1);
2581
+ }
2582
+ return siblings;
2583
+ }
2584
+ function isMissingPath(error) {
2585
+ return error instanceof Error && "code" in error && (error.code === "ENOENT" || error.code === "PathNotFound");
2586
+ }
2587
+ async function collectSolutionEntityNames(solutionDir, fs7) {
2588
+ const names = [];
2589
+ let topLevel = [];
2590
+ try {
2591
+ topLevel = await fs7.readdir(solutionDir);
2592
+ } catch (error) {
2593
+ if (!isMissingPath(error)) {
2594
+ throw error;
2595
+ }
2596
+ return names;
2597
+ }
2598
+ for (const entry of topLevel) {
2599
+ if (entry === "resources" || entry.startsWith(".")) {
2600
+ continue;
2601
+ }
2602
+ const dir = fs7.path.join(solutionDir, entry);
2603
+ try {
2604
+ const stat2 = await fs7.stat(dir);
2605
+ if (!stat2?.isDirectory()) {
2606
+ continue;
2607
+ }
2608
+ for (const file of await fs7.readdir(dir)) {
2609
+ if (file.endsWith(ENTITY_EXTENSION_CONST)) {
2610
+ names.push(fs7.path.basename(file, ENTITY_EXTENSION_CONST));
2611
+ }
2612
+ }
2613
+ } catch (error) {
2614
+ if (!isMissingPath(error)) {
2615
+ throw error;
2616
+ }
2617
+ }
2618
+ }
2619
+ return names;
2620
+ }
2621
+ async function siblingNamesFor(solutionDir, entityName, fs7) {
2622
+ return withoutOneOccurrence(await collectSolutionEntityNames(solutionDir, fs7), entityName);
2623
+ }
2624
+ async function findProjectsOwningEntity(solutionDir, entityName, fs7) {
2625
+ const owners = [];
2626
+ const wanted = `${entityName}${ENTITY_EXTENSION_CONST}`.toLowerCase();
2627
+ let topLevel = [];
2628
+ try {
2629
+ topLevel = await fs7.readdir(solutionDir);
2630
+ } catch (error) {
2631
+ if (isMissingPathError(error))
2632
+ return owners;
2633
+ throw error;
2634
+ }
2635
+ for (const entry of topLevel) {
2636
+ if (entry === "resources" || entry.startsWith(".")) {
2637
+ continue;
2638
+ }
2639
+ const dir = fs7.path.join(solutionDir, entry);
2640
+ try {
2641
+ const stat2 = await fs7.stat(dir);
2642
+ if (!stat2?.isDirectory()) {
2643
+ continue;
2644
+ }
2645
+ for (const file of await fs7.readdir(dir)) {
2646
+ if (file.toLowerCase() === wanted) {
2647
+ owners.push({
2648
+ projectName: entry,
2649
+ entityName: fs7.path.basename(file, ENTITY_EXTENSION_CONST)
2650
+ });
2651
+ break;
2652
+ }
2653
+ }
2654
+ } catch (error) {
2655
+ if (!isMissingPathError(error))
2656
+ throw error;
2657
+ }
2658
+ }
2659
+ return owners;
2660
+ }
2661
+
2662
+ // src/schema/validate-entity.ts
2663
+ var DIAGNOSTIC_CODES = {
2664
+ entityNameInvalid: "ENTITY_NAME_INVALID",
2665
+ entityNameNotUnique: "ENTITY_NAME_NOT_UNIQUE",
2666
+ fieldNameInvalid: "FIELD_NAME_INVALID",
2667
+ duplicateFieldName: "DUPLICATE_FIELD_NAME",
2668
+ fieldTypeNotAllowed: "FIELD_TYPE_NOT_ALLOWED",
2669
+ nameReserved: "NAME_RESERVED",
2670
+ systemFieldMissing: "SYSTEM_FIELD_MISSING",
2671
+ systemFieldModified: "SYSTEM_FIELD_MODIFIED",
2672
+ fieldsMalformed: "FIELDS_MALFORMED",
2673
+ tooManyMultilineMax: "TOO_MANY_MULTILINE_MAX",
2674
+ propertyTypeInvalid: "PROPERTY_TYPE_INVALID"
2675
+ };
2676
+ function validateEntity(entity, ctx) {
2677
+ const diagnostics = [];
2678
+ if (typeof entity?.Name !== "string") {
2679
+ return [
2680
+ {
2681
+ code: DIAGNOSTIC_CODES.entityNameInvalid,
2682
+ message: "The entity document has no 'Name'. The resource is malformed.",
2683
+ severity: "error"
2684
+ }
2685
+ ];
2686
+ }
2687
+ const entityNameFormat = validateNameFormat(entity.Name, "entity");
2688
+ if (entityNameFormat) {
2689
+ diagnostics.push({
2690
+ code: DIAGNOSTIC_CODES.entityNameInvalid,
2691
+ message: `${entityNameFormat.message}. ${entityNameFormat.instructions}`,
2692
+ severity: "error"
2693
+ });
2694
+ }
2695
+ const reservedEntityName = findReservedNameError(entity.Name, "entity");
2696
+ if (reservedEntityName) {
2697
+ diagnostics.push({
2698
+ code: DIAGNOSTIC_CODES.nameReserved,
2699
+ message: `${reservedEntityName.message}. ${reservedEntityName.instructions}`,
2700
+ severity: "error"
2701
+ });
2702
+ }
2703
+ const entityNameLower = entity.Name.toLowerCase();
2704
+ if (ctx.siblingNames.some((sibling) => sibling.toLowerCase() === entityNameLower)) {
2705
+ diagnostics.push({
2706
+ code: DIAGNOSTIC_CODES.entityNameNotUnique,
2707
+ message: `An entity named '${entity.Name}' already exists in this solution. Entity names are solution-wide unique.`,
2708
+ severity: "error"
2709
+ });
2710
+ }
2711
+ diagnostics.push(...typeProblems(entity, ENTITY_SCALARS).map((problem) => propertyTypeDiagnostic(`Entity '${entity.Name}'`, problem)));
2712
+ if (!Array.isArray(entity.Fields)) {
2713
+ diagnostics.push({
2714
+ code: DIAGNOSTIC_CODES.fieldsMalformed,
2715
+ message: "The entity document has no usable 'Fields' array. The resource is malformed.",
2716
+ severity: "error"
2717
+ });
2718
+ return diagnostics;
2719
+ }
2720
+ const seenFieldNames = new Map;
2721
+ for (const field of entity.Fields) {
2722
+ if (typeof field?.Name !== "string") {
2723
+ diagnostics.push({
2724
+ code: DIAGNOSTIC_CODES.fieldNameInvalid,
2725
+ message: "A field has no 'Name'. Every field needs one, system or custom.",
2726
+ severity: "error"
2727
+ });
2728
+ continue;
2729
+ }
2730
+ const isSystem = isSystemField(field);
2731
+ if (!SYSTEM_FIELD_NAMES.has(field.Name)) {
2732
+ diagnostics.push(...fieldTypeDiagnostics(field));
2733
+ }
2734
+ const fieldNameFormat = isSystem ? null : validateNameFormat(field.Name, "field");
2735
+ if (fieldNameFormat) {
2736
+ diagnostics.push({
2737
+ code: DIAGNOSTIC_CODES.fieldNameInvalid,
2738
+ message: `${fieldNameFormat.message}. ${fieldNameFormat.instructions}`,
2739
+ severity: "error",
2740
+ fieldName: field.Name
2741
+ });
2742
+ }
2743
+ if (!isSystem) {
2744
+ const reservedFieldName = findReservedNameError(field.Name, "field");
2745
+ if (reservedFieldName) {
2746
+ diagnostics.push({
2747
+ code: DIAGNOSTIC_CODES.nameReserved,
2748
+ message: `${reservedFieldName.message}. ${reservedFieldName.instructions}`,
2749
+ severity: "error",
2750
+ fieldName: field.Name
2751
+ });
2752
+ }
2753
+ }
2754
+ const fieldNameLower = field.Name.toLowerCase();
2755
+ if (!isSystem && typeof entity.Name === "string" && fieldNameLower === entity.Name.toLowerCase()) {
2756
+ diagnostics.push({
2757
+ code: DIAGNOSTIC_CODES.fieldNameInvalid,
2758
+ message: `Field name '${field.Name}' cannot match entity name '${entity.Name}' (names are compared case-insensitively).`,
2759
+ severity: "error",
2760
+ fieldName: field.Name
2761
+ });
2762
+ }
2763
+ const firstWithName = seenFieldNames.get(fieldNameLower);
2764
+ if (firstWithName !== undefined) {
2765
+ diagnostics.push({
2766
+ code: DIAGNOSTIC_CODES.duplicateFieldName,
2767
+ message: `Duplicate field name '${field.Name}' (names are case-insensitive; first defined as '${firstWithName}').`,
2768
+ severity: "error",
2769
+ fieldName: field.Name
2770
+ });
2771
+ } else {
2772
+ seenFieldNames.set(fieldNameLower, field.Name);
2773
+ }
2774
+ if (!isSystem && !ALLOWED_TYPE_PAIRS.has(`${field.FieldDisplayType}:${field.SqlType?.Name}`)) {
2775
+ diagnostics.push({
2776
+ code: DIAGNOSTIC_CODES.fieldTypeNotAllowed,
2777
+ message: `Field '${field.Name}' uses an unsupported type combination ` + `(${field.FieldDisplayType} / ${field.SqlType?.Name}).`,
2778
+ severity: "error",
2779
+ fieldName: field.Name
2780
+ });
2781
+ }
2782
+ }
2783
+ const usableFields = entity.Fields.filter((field) => typeof field === "object" && field !== null);
2784
+ const multilineMax = usableFields.filter((field) => field.SqlType?.Name === SqlTypeName.MULTILINE_MAX);
2785
+ if (multilineMax.length > MAX_MULTILINE_MAX_FIELDS) {
2786
+ diagnostics.push({
2787
+ code: DIAGNOSTIC_CODES.tooManyMultilineMax,
2788
+ 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.`,
2789
+ severity: "error"
2790
+ });
2791
+ }
2792
+ diagnostics.push(...validateSystemFields(entity, usableFields));
2793
+ return diagnostics;
2794
+ }
2795
+ var SERVER_ASSIGNED_FIELD_PROPS = new Set([
2796
+ "Id",
2797
+ "CreateTime",
2798
+ "CreatedBy",
2799
+ "UpdateTime",
2800
+ "UpdatedBy"
2801
+ ]);
2802
+ function isUnmodifiedSystemField(template, actual) {
2803
+ const equal = (left, right) => JSON.stringify(left ?? null) === JSON.stringify(right ?? null);
2804
+ for (const key of Object.keys(template)) {
2805
+ if (!equal(template[key], actual[key])) {
2806
+ return false;
2807
+ }
2808
+ }
2809
+ return Object.keys(actual).every((key) => (key in template) || SERVER_ASSIGNED_FIELD_PROPS.has(key));
2810
+ }
2811
+ function validateSystemFields(entity, usableFields) {
2812
+ const diagnostics = [];
2813
+ for (const template of SYSTEM_FIELD_TEMPLATES) {
2814
+ const actual = usableFields.find((field) => field.Name === template.Name);
2815
+ if (!actual) {
2816
+ diagnostics.push({
2817
+ code: DIAGNOSTIC_CODES.systemFieldMissing,
2818
+ message: `System field '${template.Name}' is missing. System fields cannot be removed.`,
2819
+ severity: "error",
2820
+ fieldName: template.Name
2821
+ });
2822
+ continue;
2823
+ }
2824
+ if (!isUnmodifiedSystemField(template, actual)) {
2825
+ diagnostics.push({
2826
+ code: DIAGNOSTIC_CODES.systemFieldModified,
2827
+ message: `System field '${template.Name}' was modified. System fields are read-only.`,
2828
+ severity: "error",
2829
+ fieldName: template.Name
2830
+ });
2831
+ }
2832
+ }
2833
+ return diagnostics;
2834
+ }
2835
+ function isSystemField(field) {
2836
+ const { IsSystemField: flag, Name: name } = field ?? {};
2837
+ return flag === true || typeof name === "string" && SYSTEM_FIELD_NAMES.has(name);
2838
+ }
2839
+ var SYSTEM_FIELD_NAMES = new Set(SYSTEM_FIELD_TEMPLATES.map((template) => template.Name));
2840
+ var ENTITY_SCALARS = [
2841
+ { key: "DisplayName", kind: "string" },
2842
+ { key: "Description", kind: "string" },
2843
+ { key: "EntityTypeId", kind: "integer" },
2844
+ { key: "RecordCount", kind: "integer" },
2845
+ { key: "IsRbacEnabled", kind: "boolean" },
2846
+ { key: "IsModelReserved", kind: "boolean" }
2847
+ ];
2848
+ var FIELD_SCALARS = [
2849
+ { key: "DisplayName", kind: "string" },
2850
+ { key: "Description", kind: "string" },
2851
+ { key: "ReferenceType", kind: "string" },
2852
+ { key: "FieldCategoryId", kind: "integer" },
2853
+ { key: "IsRequired", kind: "boolean" },
2854
+ { key: "IsUnique", kind: "boolean" },
2855
+ { key: "IsPrimaryKey", kind: "boolean" },
2856
+ { key: "IsForeignKey", kind: "boolean" },
2857
+ { key: "IsSystemField", kind: "boolean" },
2858
+ { key: "IsExternalField", kind: "boolean" },
2859
+ { key: "IsHiddenField", kind: "boolean" },
2860
+ { key: "IsEncrypted", kind: "boolean" },
2861
+ { key: "IsAttachment", kind: "boolean" },
2862
+ { key: "IsRbacEnabled", kind: "boolean" },
2863
+ { key: "IsModelReserved", kind: "boolean" }
2864
+ ];
2865
+ var SQL_TYPE_SCALARS = [
2866
+ { key: "LengthLimit", kind: "integer", nullable: true },
2867
+ { key: "DecimalPrecision", kind: "integer", nullable: true },
2868
+ { key: "MaxValue", kind: "number", nullable: true },
2869
+ { key: "MinValue", kind: "number", nullable: true }
2870
+ ];
2871
+ function typeProblems(record, rules, prefix = "") {
2872
+ const values = record;
2873
+ return rules.filter(({ key, kind, nullable }) => {
2874
+ const value = values[key];
2875
+ if (value === undefined)
2876
+ return false;
2877
+ if (value === null)
2878
+ return !nullable;
2879
+ if (kind === "integer")
2880
+ return !Number.isInteger(value);
2881
+ return kind === "number" ? !(typeof value === "number" && Number.isFinite(value)) : typeof value !== kind;
2882
+ }).map(({ key, kind, nullable }) => `'${prefix}${key}' must be ${kind === "integer" ? "an" : "a"} ${kind}${nullable ? " or null" : ""}`);
2883
+ }
2884
+ function propertyTypeDiagnostic(subject, problem, fieldName) {
2885
+ return {
2886
+ code: DIAGNOSTIC_CODES.propertyTypeInvalid,
2887
+ message: `${subject}: ${problem}. The resource was edited by hand or is malformed.`,
2888
+ severity: "error",
2889
+ ...fieldName !== undefined && { fieldName }
2890
+ };
2891
+ }
2892
+ function fieldTypeDiagnostics(field) {
2893
+ const problems = typeProblems(field, FIELD_SCALARS);
2894
+ if (typeof field.SqlType === "object" && field.SqlType !== null) {
2895
+ problems.push(...typeProblems(field.SqlType, SQL_TYPE_SCALARS, "SqlType."));
2896
+ }
2897
+ const defaultValue = field.DefaultValue;
2898
+ const isYesNo = field.SqlType?.Name === SqlTypeName.BIT;
2899
+ if (defaultValue != null && typeof defaultValue !== "string" && !(isYesNo && typeof defaultValue === "boolean")) {
2900
+ problems.push(isYesNo ? "'DefaultValue' must be a boolean, a string or null" : "'DefaultValue' must be a string or null");
2901
+ }
2902
+ return problems.map((problem) => propertyTypeDiagnostic(`Field '${field.Name}'`, problem, field.Name));
2903
+ }
2904
+
2905
+ // src/inline/inline-entity-service.ts
2906
+ var INLINE_ENTITY_ERROR_CODES = {
2907
+ projectNotFound: "PROJECT_NOT_FOUND",
2908
+ noParentSolution: "NO_PARENT_SOLUTION",
2909
+ entityNotFound: "ENTITY_NOT_FOUND",
2910
+ notLocallyAuthored: "NOT_LOCALLY_AUTHORED"
2911
+ };
2912
+
2913
+ class InlineEntityError extends Error {
2914
+ instructions;
2915
+ code;
2916
+ constructor(message, instructions, code) {
2917
+ super(message);
2918
+ this.instructions = instructions;
2919
+ this.code = code;
2920
+ this.name = "InlineEntityError";
2921
+ }
2922
+ }
2923
+ function fsOf() {
2924
+ return getFileSystem();
2925
+ }
2926
+ var VALID_PROJECT_NAME = /^[a-zA-Z0-9_-]+$/;
2927
+ var PRESERVED_FIELD_PROPS = [
2928
+ "Id",
2929
+ "IsEncrypted",
2930
+ "IsRbacEnabled",
2931
+ "IsHiddenField",
2932
+ "IsAttachment",
2933
+ "Transformation",
2934
+ "FieldCategoryId",
2935
+ "ReferenceEntity",
2936
+ "ReferenceField",
2937
+ "ReferenceType",
2938
+ "ReferenceChoiceSet",
2939
+ "ReferenceName",
2940
+ "CreateTime",
2941
+ "CreatedBy",
2942
+ "UpdateTime",
2943
+ "UpdatedBy"
2944
+ ];
2945
+ async function assertInsideSolutionAsync(target, solutionDir, fs7) {
2946
+ const { inside, resolved, root } = await resolvesInsideAsync(target, solutionDir, fs7);
2947
+ if (!inside) {
2948
+ throw new InlineEntityError(`'${target}' resolves outside the solution`, `It leads to '${resolved}' once symlinks are followed. Projects and entity definitions must live inside the solution at '${root}'; replace the link with the directory or file itself.`);
2949
+ }
2950
+ if (await isSymlinkEntryAsync(target, fs7)) {
2951
+ throw new InlineEntityError(`'${target}' is a symbolic link`, "Entity stubs and definition resources must be real files, not links — a link is followed by every read and write, wherever it points. Replace it with the file itself.");
2952
+ }
2953
+ }
2954
+ async function containmentProblemAsync(target, solutionDir, fs7) {
2955
+ try {
2956
+ await assertInsideSolutionAsync(target, solutionDir, fs7);
2957
+ return;
2958
+ } catch (error) {
2959
+ if (error instanceof InlineEntityError)
2960
+ return error.message;
2961
+ throw error;
2962
+ }
2963
+ }
2964
+ async function checkedPairAsync(stubFile, solutionDir, fs7) {
2965
+ const stubProblem = await containmentProblemAsync(stubFile, solutionDir, fs7);
2966
+ if (stubProblem !== undefined)
2967
+ return { ok: false, problem: stubProblem };
2968
+ const pointed = await lexicalResourcePathAsync(stubFile, solutionDir, fs7);
2969
+ if (pointed !== undefined) {
2970
+ const resourceProblem = await containmentProblemAsync(pointed, solutionDir, fs7);
2971
+ if (resourceProblem !== undefined) {
2972
+ return { ok: false, problem: resourceProblem };
2973
+ }
2974
+ }
2975
+ const pair = await verifyPair(stubFile, solutionDir, fs7);
2976
+ return pair.ok ? { ok: true, pair } : { ok: false, problem: pair.failure.message };
2977
+ }
2978
+ async function lexicalResourcePathAsync(stubFile, solutionDir, fs7) {
2979
+ let pointer;
2980
+ try {
2981
+ const raw = await fs7.readFile(stubFile);
2982
+ pointer = JSON.parse(typeof raw === "string" ? raw : new TextDecoder().decode(raw ?? new Uint8Array)).resourcePath;
2983
+ } catch {
2984
+ return;
2985
+ }
2986
+ return typeof pointer === "string" ? fs7.path.resolve(solutionDir, ...pointer.split("/")) : undefined;
2987
+ }
2988
+ function assertEntityTextInput(input) {
2989
+ for (const key of ["displayName", "description"]) {
2990
+ const value = input[key];
2991
+ if (value !== undefined && typeof value !== "string") {
2992
+ throw new InlineEntityError(`'${key}' must be a string`, `Received ${JSON.stringify(value)}. Pass text, or "" for none.`);
2993
+ }
2994
+ }
2995
+ }
2996
+ async function solutionRootAsync(options = {}) {
2997
+ const fs7 = fsOf();
2998
+ const from = options.cwd ?? process.cwd();
2999
+ const root = await findSolutionRoot(from, fs7);
3000
+ if (root === undefined) {
3001
+ throw new InlineEntityError("Not inside a solution", `Looked upward from '${from}' for a .uipx. Run this from the solution directory, or create one with 'uip solution init'.`, INLINE_ENTITY_ERROR_CODES.noParentSolution);
3002
+ }
3003
+ return root;
3004
+ }
3005
+ async function resolveProjectAsync(projectName, options = {}) {
3006
+ const fs7 = fsOf();
3007
+ if (!VALID_PROJECT_NAME.test(projectName)) {
3008
+ throw new InlineEntityError(`Invalid project name '${projectName}'`, "Project names contain only letters, numbers, underscores (_) and hyphens (-) — they are a single directory name, never a path.");
3009
+ }
3010
+ const root = await solutionRootAsync(options);
3011
+ const projectDir = fs7.path.resolve(root, projectName);
3012
+ if (await isSymlinkEntryAsync(projectDir, fs7)) {
3013
+ throw new InlineEntityError(`Entity project '${projectName}' is a symbolic link`, "A project is addressed by its own directory in the solution — a link would have stubs written wherever it points. Replace the link with the directory itself.");
3014
+ }
3015
+ let stat2 = null;
3016
+ try {
3017
+ stat2 = await fs7.stat(projectDir);
3018
+ } catch (error) {
3019
+ if (!isMissingPathError(error)) {
3020
+ throw error;
3021
+ }
3022
+ stat2 = null;
3023
+ }
3024
+ if (stat2 === null || !stat2.isDirectory()) {
3025
+ throw new InlineEntityError(`Entity project '${projectName}' not found`, `Looked for '${projectDir}'. Run the command from the solution directory, or create the project with 'uip df entities create <Name> --local --project-name ${projectName}'.`, INLINE_ENTITY_ERROR_CODES.projectNotFound);
3026
+ }
3027
+ await assertInsideSolutionAsync(projectDir, root, fs7);
3028
+ return { projectDir, solutionDir: root };
3029
+ }
3030
+ async function registeredProjectTypesAsync(solutionDir, fs7) {
3031
+ const registered = new Map;
3032
+ for (const file of await fs7.readdir(solutionDir)) {
3033
+ if (!file.endsWith(".uipx"))
3034
+ continue;
3035
+ const raw = await fs7.readFile(fs7.path.join(solutionDir, file), "utf-8");
3036
+ let projects;
3037
+ try {
3038
+ projects = JSON.parse(typeof raw === "string" ? raw : new TextDecoder().decode(raw ?? new Uint8Array)).Projects;
3039
+ } catch {
3040
+ throw new InlineEntityError(`Solution manifest '${file}' is not valid JSON`, `Fix '${fs7.path.join(solutionDir, file)}' — 'uip solution pack' cannot read it either.`);
3041
+ }
3042
+ for (const project of Array.isArray(projects) ? projects : []) {
3043
+ const { Type, ProjectRelativePath } = project ?? {};
3044
+ if (typeof Type === "string" && typeof ProjectRelativePath === "string") {
3045
+ const segments = ProjectRelativePath.split(/[\\/]/);
3046
+ const key = segments.length === 2 ? segments[0]?.toLowerCase() : undefined;
3047
+ if (key && registered.get(key)?.toLowerCase() !== "entity") {
3048
+ registered.set(key, Type);
3049
+ }
3050
+ }
3051
+ }
3052
+ }
3053
+ return registered;
3054
+ }
3055
+ async function requireEntityProjectAsync(projectDir, projectName, solutionDir, fs7) {
3056
+ const projectFile = fs7.path.join(projectDir, "project.uiproj");
3057
+ let raw = null;
3058
+ try {
3059
+ raw = await fs7.readFile(projectFile, "utf-8");
3060
+ } catch (error) {
3061
+ if (!isMissingPathError(error)) {
3062
+ throw error;
3063
+ }
3064
+ raw = null;
3065
+ }
3066
+ if (raw === null) {
3067
+ throw new InlineEntityError(`Directory '${projectName}' is not an Entity project`, `No 'project.uiproj' in '${projectDir}'. An entity can only be authored into a project of type Entity — create one with 'uip df entities create <Name> --local --project-name <NewProject>'.`);
3068
+ }
3069
+ let projectType;
3070
+ try {
3071
+ projectType = JSON.parse(typeof raw === "string" ? raw : new TextDecoder().decode(raw)).ProjectType;
3072
+ } catch {
3073
+ throw new InlineEntityError(`Project file for '${projectName}' is not valid JSON`, `Fix '${projectFile}' — it must be a JSON object naming a 'ProjectType'.`);
3074
+ }
3075
+ if (typeof projectType !== "string" || projectType.toLowerCase() !== "entity") {
3076
+ throw new InlineEntityError(`Project '${projectName}' is not an Entity project`, `'${projectFile}' declares ProjectType '${String(projectType)}'. Pack only ships entities from a project of type Entity, so an entity written here would never deploy. Use an Entity project, or create one with 'uip df entities create <Name> --local --project-name <NewProject>'.`);
3077
+ }
3078
+ await requireRegisteredAsync(projectName, solutionDir, fs7);
3079
+ }
3080
+ async function requireRegisteredAsync(projectName, solutionDir, fs7) {
3081
+ const type = (await registeredProjectTypesAsync(solutionDir, fs7)).get(projectName.toLowerCase());
3082
+ if (type !== undefined && type.toLowerCase() !== "entity") {
3083
+ throw new InlineEntityError(`Project '${projectName}' is registered as '${type}', not as an Entity project`, `The solution's .uipx lists '${projectName}' as a ${type} project, so pack never reads entities from it. Author entities in an Entity project — create one with 'uip df entities create <Name> --local --project-name <NewProject>'.`);
3084
+ }
3085
+ if (type === undefined) {
3086
+ throw new InlineEntityError(`Entity project '${projectName}' is not registered in the solution`, `'${projectName}' is not in the solution's .uipx as an Entity project, so 'uip solution pack' never visits it and nothing written there would deploy. Register it with 'uip solution projects add ${projectName}'.`);
3087
+ }
3088
+ }
3089
+ function entityStubPath(projectDir, entityName, fs7) {
3090
+ const nameError = validateNameFormat(entityName, "entity");
3091
+ if (nameError) {
3092
+ throw new InlineEntityError(nameError.message, nameError.instructions);
3093
+ }
3094
+ const stubFile = fs7.path.join(projectDir, `${entityName}${ENTITY_EXTENSION_CONST}`);
3095
+ if (fs7.path.dirname(fs7.path.resolve(stubFile)) !== fs7.path.resolve(projectDir)) {
3096
+ throw new InlineEntityError(`Entity name '${entityName}' does not resolve inside project directory`, "Entity names are plain identifiers, never paths.");
3097
+ }
3098
+ return stubFile;
3099
+ }
3100
+ async function resolveOwningProjectAsync(entityName, options = {}) {
3101
+ const fs7 = fsOf();
3102
+ const from = options.cwd ?? process.cwd();
3103
+ const solutionDir = await findSolutionRoot(from, fs7);
3104
+ if (solutionDir === undefined) {
3105
+ throw new InlineEntityError("Not inside a solution", `Looked upward from '${from}' for a .uipx. Run this from the solution directory, or name the project with --project-name.`, INLINE_ENTITY_ERROR_CODES.noParentSolution);
3106
+ }
3107
+ const owners = await findProjectsOwningEntity(solutionDir, entityName, fs7);
3108
+ const owner = owners[0];
3109
+ if (owners.length === 1 && owner !== undefined) {
3110
+ return {
3111
+ projectName: owner.projectName,
3112
+ entityName: owner.entityName,
3113
+ solutionDir
3114
+ };
3115
+ }
3116
+ if (owners.length === 0) {
3117
+ const known = await collectSolutionEntityNames(solutionDir, fs7);
3118
+ throw new InlineEntityError(`No entity named '${entityName}' in this solution`, known.length === 0 ? "The solution has no authored entities yet. Create one with 'uip df entities create <Name> --local'." : `Entities here: ${[...new Set(known)].sort(byName).join(", ")}.`, INLINE_ENTITY_ERROR_CODES.entityNotFound);
3119
+ }
3120
+ throw new InlineEntityError(`More than one project owns an entity named '${entityName}'`, `Found in: ${owners.map((each) => each.projectName).join(", ")}. Name the one you mean with --project-name.`);
3121
+ }
3122
+ async function stubNamesAsync(projectDir, fs7) {
3123
+ let entries = [];
3124
+ try {
3125
+ entries = await fs7.readdir(projectDir);
3126
+ } catch (error) {
3127
+ if (!isMissingPathError(error)) {
3128
+ throw error;
3129
+ }
3130
+ return [];
3131
+ }
3132
+ return entries.filter((name) => name.endsWith(ENTITY_EXTENSION_CONST)).sort(byName);
3133
+ }
3134
+ async function inlineEntityListAsync(projectName, options = {}) {
3135
+ const fs7 = fsOf();
3136
+ const { projectDir, solutionDir } = await resolveProjectAsync(projectName, options);
3137
+ await requireRegisteredAsync(projectName, solutionDir, fs7);
3138
+ const summaries = [];
3139
+ for (const stubName of await stubNamesAsync(projectDir, fs7)) {
3140
+ const stubFile = fs7.path.join(projectDir, stubName);
3141
+ const checked = await checkedPairAsync(stubFile, solutionDir, fs7);
3142
+ if (!checked.ok) {
3143
+ summaries.push({
3144
+ name: fs7.path.basename(stubName, ENTITY_EXTENSION_CONST),
3145
+ stubFile,
3146
+ problem: checked.problem
3147
+ });
3148
+ continue;
3149
+ }
3150
+ const { pair } = checked;
3151
+ summaries.push({
3152
+ name: pair.entityName,
3153
+ stubFile,
3154
+ resourceFile: pair.resourceFile,
3155
+ locallyAuthored: isLocallyAuthored(pair.entity)
3156
+ });
3157
+ }
3158
+ return summaries;
3159
+ }
3160
+ async function inlineEntityListAllAsync(options = {}) {
3161
+ const fs7 = fsOf();
3162
+ const from = options.cwd ?? process.cwd();
3163
+ const solutionDir = await findSolutionRoot(from, fs7);
3164
+ if (solutionDir === undefined) {
3165
+ throw new InlineEntityError("Not inside a solution", `Looked upward from '${from}' for a .uipx. Run this from the solution directory.`, INLINE_ENTITY_ERROR_CODES.noParentSolution);
3166
+ }
3167
+ const rows = [];
3168
+ for (const entry of (await fs7.readdir(solutionDir)).sort(byName)) {
3169
+ if (entry === "resources" || entry.startsWith(".")) {
3170
+ continue;
3171
+ }
3172
+ const dir = fs7.path.join(solutionDir, entry);
3173
+ const [statError, stat2] = await catchInline(() => fs7.stat(dir));
3174
+ if (statError !== undefined && !isMissingPathError(statError)) {
3175
+ rows.push({
3176
+ projectName: entry,
3177
+ name: entry,
3178
+ stubFile: dir,
3179
+ solutionDir,
3180
+ projectProblem: `Directory '${entry}' could not be read: ${messageOf(statError)}`
3181
+ });
3182
+ continue;
3183
+ }
3184
+ if (!stat2?.isDirectory()) {
3185
+ continue;
3186
+ }
3187
+ const [readError, entries] = await catchInline(() => fs7.readdir(dir));
3188
+ if (readError !== undefined) {
3189
+ if (isMissingPathError(readError)) {
3190
+ continue;
3191
+ }
3192
+ rows.push({
3193
+ projectName: entry,
3194
+ name: entry,
3195
+ stubFile: dir,
3196
+ solutionDir,
3197
+ projectProblem: `Directory '${entry}' could not be read: ${messageOf(readError)}`
3198
+ });
3199
+ continue;
3200
+ }
3201
+ if (!(entries ?? []).some((file) => file.endsWith(ENTITY_EXTENSION_CONST))) {
3202
+ continue;
3203
+ }
3204
+ const [listError, listed] = await catchInline(() => inlineEntityListAsync(entry, { cwd: solutionDir }));
3205
+ if (listError !== undefined) {
3206
+ rows.push({
3207
+ projectName: entry,
3208
+ name: entry,
3209
+ stubFile: dir,
3210
+ solutionDir,
3211
+ projectProblem: listError instanceof InlineEntityError && listError.instructions ? `${listError.message}. ${listError.instructions}` : messageOf(listError)
3212
+ });
3213
+ continue;
3214
+ }
3215
+ for (const summary of listed ?? []) {
3216
+ rows.push({ ...summary, projectName: entry, solutionDir });
3217
+ }
3218
+ }
3219
+ return rows;
3220
+ }
3221
+ function messageOf(error) {
3222
+ return error instanceof Error ? error.message : String(error);
3223
+ }
3224
+ async function catchInline(run) {
3225
+ try {
3226
+ return [undefined, await run()];
3227
+ } catch (error) {
3228
+ return [error, undefined];
3229
+ }
3230
+ }
3231
+ async function resolveEntityAsync(projectName, entityName, options) {
3232
+ const fs7 = fsOf();
3233
+ const { projectDir, solutionDir } = await resolveProjectAsync(projectName, options);
3234
+ const stubFile = entityStubPath(projectDir, entityName, fs7);
3235
+ const checked = await checkedPairAsync(stubFile, solutionDir, fs7);
3236
+ if (!checked.ok) {
3237
+ const known = (await stubNamesAsync(projectDir, fs7)).map((name) => fs7.path.basename(name, ENTITY_EXTENSION_CONST));
3238
+ throw new InlineEntityError(`Entity '${entityName}' is not usable in project '${projectName}': ${checked.problem}`, known.length === 0 ? `Project '${projectName}' has no entities. Add one with 'uip df entities create ${entityName} --local --project-name ${projectName}'.` : `Entities in this project: ${known.join(", ")}.`);
3239
+ }
3240
+ const { pair } = checked;
3241
+ await assertInsideSolutionAsync(pair.resourceFile, solutionDir, fs7);
3242
+ const rawResource = await fs7.readFile(pair.resourceFile, "utf-8");
3243
+ if (rawResource === null) {
3244
+ throw new InlineEntityError(`Entity definition for '${pair.entityName}' could not be read`, `Expected it at '${pair.resourceFile}'.`);
3245
+ }
3246
+ const resource = JSON.parse(rawResource);
3247
+ return {
3248
+ projectDir,
3249
+ solutionDir,
3250
+ entityName: pair.entityName,
3251
+ stubFile,
3252
+ resourceFile: pair.resourceFile,
3253
+ entity: pair.entity,
3254
+ resource
3255
+ };
3256
+ }
3257
+ async function inlineEntityGetAsync(projectName, entityName, options = {}) {
3258
+ return (await resolveEntityAsync(projectName, entityName, options)).entity;
3259
+ }
3260
+ async function inlineEntityValidateAsync(projectName, options = {}) {
3261
+ const fs7 = fsOf();
3262
+ const { projectDir, solutionDir } = await resolveProjectAsync(projectName, options);
3263
+ await requireRegisteredAsync(projectName, solutionDir, fs7);
3264
+ const stubFiles = options.entityName === undefined ? (await stubNamesAsync(projectDir, fs7)).map((stubName) => fs7.path.join(projectDir, stubName)) : [entityStubPath(projectDir, options.entityName, fs7)];
3265
+ const results = [];
3266
+ for (const stubFile of stubFiles) {
3267
+ const name = fs7.path.basename(stubFile, ENTITY_EXTENSION_CONST);
3268
+ const checked = await checkedPairAsync(stubFile, solutionDir, fs7);
3269
+ if (!checked.ok) {
3270
+ results.push({
3271
+ entityName: name,
3272
+ diagnostics: [],
3273
+ pairProblem: checked.problem
3274
+ });
3275
+ continue;
3276
+ }
3277
+ const { pair } = checked;
3278
+ results.push({
3279
+ entityName: pair.entityName,
3280
+ resourceFile: pair.resourceFile,
3281
+ diagnostics: validateEntity(pair.entity, {
3282
+ siblingNames: await siblingNamesFor(solutionDir, pair.entityName, fs7)
3283
+ })
3284
+ });
3285
+ }
3286
+ return results;
3287
+ }
3288
+ function requireLocallyAuthored(resolved) {
3289
+ if (isLocallyAuthored(resolved.entity)) {
3290
+ return;
3291
+ }
3292
+ throw new InlineEntityError(`Entity '${resolved.entityName}' is a platform entity this solution references, not an inline one`, `It resolves to Data Fabric folder '${resolved.entity.FolderId}'. Change its schema with 'uip df entities update <id>' or in Data Fabric; the inline commands only author entities created locally.`, INLINE_ENTITY_ERROR_CODES.notLocallyAuthored);
3293
+ }
3294
+ async function inlineEntityUpdateAsync(projectName, entityName, update, options = {}) {
3295
+ assertEntityTextInput(update);
3296
+ const fs7 = fsOf();
3297
+ const resolved = await resolveEntityAsync(projectName, entityName, options);
3298
+ requireLocallyAuthored(resolved);
3299
+ await requireEntityProjectAsync(resolved.projectDir, projectName, resolved.solutionDir, fs7);
3300
+ const next = {
3301
+ ...resolved.entity,
3302
+ Fields: [...resolved.entity.Fields]
3303
+ };
3304
+ if (update.displayName !== undefined)
3305
+ next.DisplayName = update.displayName;
3306
+ if (update.description !== undefined)
3307
+ next.Description = update.description;
3308
+ const indexOfField = (name) => fieldIndexOf(next, name);
3309
+ for (const remove of update.removeFields ?? []) {
3310
+ const at = indexOfField(remove.name);
3311
+ if (at < 0) {
3312
+ throw new InlineEntityError(`Field '${remove.name}' is not on entity '${resolved.entityName}'`, `Fields: ${next.Fields.map((field) => field.Name).join(", ")}.`);
3313
+ }
3314
+ if (isSystemField(next.Fields[at])) {
3315
+ throw new InlineEntityError(`Field '${remove.name}' is a system field and cannot be removed`, "Data Fabric owns Id, CreateTime, CreatedBy, UpdateTime and UpdatedBy on every entity.");
3316
+ }
3317
+ next.Fields.splice(at, 1);
3318
+ }
3319
+ for (const change of update.updateFields ?? []) {
3320
+ const at = indexOfField(change.name);
3321
+ if (at < 0) {
3322
+ throw new InlineEntityError(`Field '${change.name}' is not on entity '${resolved.entityName}'`, `Fields: ${next.Fields.map((field) => field.Name).join(", ")}.`);
3323
+ }
3324
+ const current = next.Fields[at];
3325
+ if (current === undefined || isSystemField(current)) {
3326
+ throw new InlineEntityError(`Field '${change.name}' is a system field and cannot be changed`, "Data Fabric owns Id, CreateTime, CreatedBy, UpdateTime and UpdatedBy on every entity.");
3327
+ }
3328
+ const merged = (key, fallback) => (key in change) ? change[key] : fallback;
3329
+ const currentType = sdkTypeOf(current);
3330
+ const retyped = change.type !== undefined && change.type !== currentType;
3331
+ const inherited = (key, fallback) => retyped ? merged(key, undefined) : merged(key, fallback);
3332
+ next.Fields[at] = authorField({
3333
+ name: current.Name,
3334
+ type: merged("type", currentType),
3335
+ displayName: merged("displayName", current.DisplayName),
3336
+ description: merged("description", current.Description),
3337
+ isRequired: merged("isRequired", current.IsRequired),
3338
+ isUnique: merged("isUnique", current.IsUnique),
3339
+ lengthLimit: inherited("lengthLimit", current.SqlType?.LengthLimit),
3340
+ decimalPrecision: inherited("decimalPrecision", current.SqlType?.DecimalPrecision),
3341
+ maxValue: inherited("maxValue", current.SqlType?.MaxValue),
3342
+ minValue: inherited("minValue", current.SqlType?.MinValue),
3343
+ defaultValue: merged("defaultValue", retyped && typeof current.DefaultValue === "boolean" ? String(current.DefaultValue) : current.DefaultValue)
3344
+ }, {
3345
+ defaultValueFromCaller: retyped || "defaultValue" in change
3346
+ });
3347
+ const rebuilt = next.Fields[at];
3348
+ const previous = current;
3349
+ for (const key of Object.keys(previous)) {
3350
+ if (!(key in rebuilt)) {
3351
+ rebuilt[key] = previous[key];
3352
+ }
3353
+ }
3354
+ for (const preserved of PRESERVED_FIELD_PROPS) {
3355
+ if (previous[preserved] !== undefined) {
3356
+ rebuilt[preserved] = previous[preserved];
3357
+ }
3358
+ }
3359
+ }
3360
+ addAuthoredFields(next, update.addFields ?? [], resolved.entityName, "Field names are case-insensitive. Use updateFields to change the existing one.");
3361
+ const diagnostics = validateEntity(next, {
3362
+ siblingNames: await siblingNamesFor(resolved.solutionDir, resolved.entityName, fs7)
3363
+ });
3364
+ if (diagnostics.length > 0) {
3365
+ throw new InlineEntityError(`The edit would leave entity '${resolved.entityName}' invalid, so nothing was written`, diagnostics.map((diagnostic) => `${diagnostic.code}: ${diagnostic.message}`).join(`
3366
+ `));
3367
+ }
3368
+ await fs7.writeFile(resolved.resourceFile, serialize(updateResourceSchema(resolved.resource, next)));
3369
+ return { entity: next, resourceFile: resolved.resourceFile };
3370
+ }
3371
+ function fieldIndexOf(entity, name) {
3372
+ return entity.Fields.findIndex((field) => typeof field?.Name === "string" && field.Name.toLowerCase() === name.toLowerCase());
3373
+ }
3374
+ function addAuthoredFields(next, fields, entityName, duplicateAdvice) {
3375
+ for (const add of fields) {
3376
+ const existing = next.Fields[fieldIndexOf(next, add.name)];
3377
+ if (isSystemField(existing)) {
3378
+ throw new InlineEntityError(`'${existing.Name}' is a system field on entity '${entityName}'`, "Data Fabric adds Id, CreateTime, CreatedBy, UpdateTime and UpdatedBy to every entity. Choose another name.");
3379
+ }
3380
+ if (existing !== undefined) {
3381
+ throw new InlineEntityError(`Entity '${entityName}' already has a field named '${add.name}'`, duplicateAdvice);
3382
+ }
3383
+ next.Fields.push(authorField(add));
3384
+ }
3385
+ }
3386
+ function authorNewEntity(entityName, definition) {
3387
+ assertEntityTextInput(definition);
3388
+ const next = createEntitySkeleton(entityName);
3389
+ if (definition.displayName !== undefined) {
3390
+ next.DisplayName = definition.displayName;
3391
+ }
3392
+ if (definition.description !== undefined) {
3393
+ next.Description = definition.description;
3394
+ }
3395
+ addAuthoredFields(next, definition.addFields ?? [], entityName, "Field names are case-insensitive. Give each field a distinct name.");
3396
+ const diagnostics = validateEntity(next, { siblingNames: [] });
3397
+ if (diagnostics.length > 0) {
3398
+ throw new InlineEntityError(`Cannot create entity '${entityName}'`, diagnostics.map((diagnostic) => `${diagnostic.code}: ${diagnostic.message}`).join(`
3399
+ `));
3400
+ }
3401
+ return next;
3402
+ }
3403
+ function sdkTypeOf(field) {
3404
+ const pair = `${field.FieldDisplayType}:${field.SqlType.Name}`;
3405
+ const known = {
3406
+ "Basic:NVARCHAR": "STRING",
3407
+ "Basic:DECIMAL": "DECIMAL",
3408
+ "Basic:BIT": "BOOLEAN",
3409
+ "Basic:DATE": "DATE",
3410
+ "Basic:DATETIMEOFFSET": "DATETIME_WITH_TZ",
3411
+ "Basic:MULTILINE": "MULTILINE_TEXT",
3412
+ "Basic:MULTILINE_MAX": "MULTILINE_MAX",
3413
+ "MultiLineText:MULTILINE": "MULTILINE_TEXT",
3414
+ "MultiLineText:MULTILINE_MAX": "MULTILINE_MAX",
3415
+ "AutoNumber:DECIMAL": "AUTO_NUMBER",
3416
+ "File:UNIQUEIDENTIFIER": "FILE"
3417
+ };
3418
+ const type = known[pair];
3419
+ if (type === undefined) {
3420
+ throw new InlineEntityError(`Field type ${pair} cannot be edited by the inline commands`, "Only fields authored from the supported type list can be changed here. Edit this one in Data Fabric.");
3421
+ }
3422
+ return type;
3423
+ }
3424
+ async function inlineEntityAddAsync(projectName, entityName, options = {}, authored) {
3425
+ requireAuthoredName(authored, entityName);
3426
+ const fs7 = fsOf();
3427
+ const { projectDir, solutionDir } = await resolveProjectAsync(projectName, options);
3428
+ await requireEntityProjectAsync(projectDir, projectName, solutionDir, fs7);
3429
+ const stubFile = entityStubPath(projectDir, entityName, fs7);
3430
+ let exists = false;
3431
+ try {
3432
+ exists = await fs7.stat(stubFile) !== null;
3433
+ } catch (error) {
3434
+ if (!isMissingPathError(error)) {
3435
+ throw error;
3436
+ }
3437
+ exists = false;
3438
+ }
3439
+ if (exists) {
3440
+ throw new InlineEntityError(`Entity '${entityName}' already exists in project '${projectName}'`, `Edit it with 'uip df entities update ${entityName} --local'.`);
3441
+ }
3442
+ const document = authored ?? createEntitySkeleton(entityName);
3443
+ const diagnostics = validateEntity(document, {
3444
+ siblingNames: await collectSolutionEntityNames(solutionDir, fs7)
3445
+ });
3446
+ if (diagnostics.length > 0) {
3447
+ throw new InlineEntityError(`Cannot create entity '${entityName}'`, diagnostics.map((diagnostic) => `${diagnostic.code}: ${diagnostic.message}`).join(`
3448
+ `));
3449
+ }
3450
+ const relativeResourcePath = entityResourcePath(entityName);
3451
+ const resourceFile = fs7.path.join(solutionDir, ...relativeResourcePath.split("/"));
3452
+ let resourceExists = false;
3453
+ try {
3454
+ resourceExists = await fs7.stat(resourceFile) !== null;
3455
+ } catch (error) {
3456
+ if (!isMissingPathError(error)) {
3457
+ throw error;
3458
+ }
3459
+ resourceExists = false;
3460
+ }
3461
+ if (resourceExists) {
3462
+ throw new InlineEntityError(`An entity definition for '${entityName}' already exists in this solution`, `'${relativeResourcePath}' is already present. Entity names are solution-wide unique — pick a different name, or edit the existing entity with 'uip df entities update ${entityName} --local'. If no .entity stub points at it (an interrupted create or delete leaves one behind), clear it with 'uip df entities delete ${entityName} --local --project-name ${projectName} --force --yes'.`);
3463
+ }
3464
+ await assertInsideSolutionAsync(resourceFile, solutionDir, fs7);
3465
+ await assertInsideSolutionAsync(stubFile, solutionDir, fs7);
3466
+ await fs7.mkdir(fs7.path.dirname(resourceFile));
3467
+ await fs7.writeFile(resourceFile, serialize(wrapEntityJson(document)));
3468
+ await fs7.writeFile(stubFile, serialize({ name: entityName, resourcePath: relativeResourcePath }));
3469
+ return { entityFile: stubFile, resourceFile };
3470
+ }
3471
+ async function inlineEntityDeleteAsync(projectName, entityName, options = {}) {
3472
+ const fs7 = fsOf();
3473
+ const { projectDir, solutionDir } = await resolveProjectAsync(projectName, options);
3474
+ const stubFile = entityStubPath(projectDir, entityName, fs7);
3475
+ const checked = await checkedPairAsync(stubFile, solutionDir, fs7);
3476
+ if (checked.ok) {
3477
+ const { pair } = checked;
3478
+ requireLocallyAuthored({
3479
+ entityName: pair.entityName,
3480
+ entity: pair.entity
3481
+ });
3482
+ await assertInsideSolutionAsync(pair.resourceFile, solutionDir, fs7);
3483
+ const shared = await derivedResourceOwnershipProblem(pair.resourceFile, projectName, pair.entityName, solutionDir, fs7);
3484
+ if (shared !== undefined) {
3485
+ throw new InlineEntityError(`Refusing to delete entity '${pair.entityName}' from project '${projectName}'`, shared);
3486
+ }
3487
+ await fs7.rm(stubFile);
3488
+ await fs7.rm(pair.resourceFile);
3489
+ return { stubFile, resourceFile: pair.resourceFile };
3490
+ }
3491
+ if (!options.force) {
3492
+ const stubMissing = !await pathOrLinkExistsAsync(stubFile, fs7);
3493
+ const known = (await stubNamesAsync(projectDir, fs7)).map((name) => fs7.path.basename(name, ENTITY_EXTENSION_CONST));
3494
+ throw new InlineEntityError(`Entity '${entityName}' is not usable in project '${projectName}': ${checked.problem}`, stubMissing ? known.length === 0 ? `Project '${projectName}' has no entities.` : `Entities in this project: ${known.join(", ")}.` : `Add --force to delete it anyway: that removes the stub and the definition resource for '${entityName}' without needing either to parse. It still refuses when it cannot prove the files are this project's to remove.`);
3495
+ }
3496
+ const derived = fs7.path.join(solutionDir, ...entityResourcePath(entityName).split("/"));
3497
+ const stubIsLink = await isSymlinkEntryAsync(stubFile, fs7);
3498
+ const stubExists = stubIsLink || await pathExistsAsync(stubFile, fs7);
3499
+ const pointed = stubExists && !stubIsLink ? await stubResourcePathAsync(stubFile, entityName, solutionDir, fs7) : undefined;
3500
+ const candidates = [];
3501
+ if (pointed !== undefined && await pathOrLinkExistsAsync(pointed, fs7)) {
3502
+ candidates.push(pointed);
3503
+ }
3504
+ if (await pathOrLinkExistsAsync(derived, fs7)) {
3505
+ candidates.push(derived);
3506
+ }
3507
+ for (const candidate of candidates) {
3508
+ await assertResourceRemovableAsync(candidate, projectName, entityName, solutionDir, fs7);
3509
+ }
3510
+ if (!stubExists && candidates.length === 0) {
3511
+ throw new InlineEntityError(`Nothing to delete for entity '${entityName}' in project '${projectName}'`, `Neither '${stubFile}' nor a definition resource for '${entityName}' is on disk.`);
3512
+ }
3513
+ const removed = { forced: true };
3514
+ if (stubExists) {
3515
+ await fs7.rm(stubFile);
3516
+ removed.stubFile = stubFile;
3517
+ }
3518
+ const removedPaths = [];
3519
+ for (const candidate of candidates) {
3520
+ if (await pathOrLinkExistsAsync(candidate, fs7)) {
3521
+ await fs7.rm(candidate);
3522
+ removedPaths.push(candidate);
3523
+ }
3524
+ }
3525
+ removed.resourceFile = removedPaths[0];
3526
+ return removed;
3527
+ }
3528
+ async function assertResourceRemovableAsync(resource, projectName, entityName, solutionDir, fs7) {
3529
+ if (await isSymlinkEntryAsync(resource, fs7)) {
3530
+ await assertInsideSolutionAsync(fs7.path.dirname(resource), solutionDir, fs7);
3531
+ const blocked2 = await derivedResourceOwnershipProblem(resource, projectName, entityName, solutionDir, fs7, { ownersOnly: true });
3532
+ if (blocked2 !== undefined) {
3533
+ throw new InlineEntityError(`Refusing to delete the definition resource for '${entityName}'`, blocked2);
3534
+ }
3535
+ return;
3536
+ }
3537
+ await assertInsideSolutionAsync(resource, solutionDir, fs7);
3538
+ const stat2 = await fs7.stat(resource);
3539
+ if (stat2 !== null && !stat2.isFile()) {
3540
+ throw new InlineEntityError(`Refusing to delete '${resource}'`, "It is a directory, not an entity definition file. Remove it by hand if it is not needed.");
3541
+ }
3542
+ const blocked = await derivedResourceOwnershipProblem(resource, projectName, entityName, solutionDir, fs7);
3543
+ if (blocked !== undefined) {
3544
+ throw new InlineEntityError(`Refusing to delete the definition resource for '${entityName}'`, blocked);
3545
+ }
3546
+ }
3547
+ async function inlineEntityDeleteOrphanAsync(entityName, options = {}) {
3548
+ const fs7 = fsOf();
3549
+ const nameError = validateNameFormat(entityName, "entity");
3550
+ if (nameError) {
3551
+ throw new InlineEntityError(nameError.message, nameError.instructions);
3552
+ }
3553
+ const solutionDir = await solutionRootAsync(options);
3554
+ const resource = fs7.path.join(solutionDir, ...entityResourcePath(entityName).split("/"));
3555
+ if (!await pathOrLinkExistsAsync(resource, fs7)) {
3556
+ throw new InlineEntityError(`Entity '${entityName}' not found`, `No project declares it and no definition resource for it is at '${resource}'.`, INLINE_ENTITY_ERROR_CODES.entityNotFound);
3557
+ }
3558
+ await assertResourceRemovableAsync(resource, "", entityName, solutionDir, fs7);
3559
+ await fs7.rm(resource);
3560
+ return { resourceFile: resource, forced: true };
3561
+ }
3562
+ async function pathOrLinkExistsAsync(path3, fs7) {
3563
+ return await isSymlinkEntryAsync(path3, fs7) || await pathExistsAsync(path3, fs7);
3564
+ }
3565
+ async function pathExistsAsync(path3, fs7) {
3566
+ try {
3567
+ return await fs7.stat(path3) !== null;
3568
+ } catch (error) {
3569
+ if (isMissingPathError(error)) {
3570
+ return false;
3571
+ }
3572
+ throw error;
3573
+ }
3574
+ }
3575
+ async function stubResourcePathAsync(stubFile, entityName, solutionDir, fs7) {
3576
+ let pointer;
3577
+ try {
3578
+ const raw = await fs7.readFile(stubFile, "utf-8");
3579
+ if (raw === null)
3580
+ return;
3581
+ pointer = JSON.parse(raw).resourcePath;
3582
+ } catch (error) {
3583
+ if (isUnreadablePathError(error))
3584
+ throw error;
3585
+ return;
3586
+ }
3587
+ if (typeof pointer !== "string")
3588
+ return;
3589
+ const solutionRoot = fs7.path.resolve(solutionDir);
3590
+ const resolved = fs7.path.resolve(solutionRoot, ...pointer.split("/"));
3591
+ const boundary = resolved.charAt(solutionRoot.length);
3592
+ if (!resolved.startsWith(solutionRoot) || boundary !== "/" && boundary !== "\\") {
3593
+ return;
3594
+ }
3595
+ const canonicalTree = await canonicalPathAsync(entityTreeDir(solutionRoot, fs7), fs7);
3596
+ const canonical = await canonicalPathAsync(resolved, fs7);
3597
+ const parent = fs7.path.dirname(canonical);
3598
+ const sameDir = parent.toLowerCase() === canonicalTree.toLowerCase();
3599
+ const expected = `${entityName}.json`.toLowerCase();
3600
+ if (!sameDir || fs7.path.basename(canonical).toLowerCase() !== expected) {
3601
+ return;
3602
+ }
3603
+ let stat2 = null;
3604
+ try {
3605
+ stat2 = await fs7.stat(canonical);
3606
+ } catch (error) {
3607
+ if (!isMissingPathError(error))
3608
+ throw error;
3609
+ }
3610
+ if (stat2 !== null && !stat2.isFile()) {
3611
+ return;
3612
+ }
3613
+ return canonical;
3614
+ }
3615
+ function entityTreeDir(solutionRoot, fs7) {
3616
+ return fs7.path.resolve(solutionRoot, "resources", SOLUTION_FOLDER, ...ENTITY_RESOURCE_DIR.split("/"));
3617
+ }
3618
+ async function derivedResourceOwnershipProblem(derived, projectName, entityName, solutionDir, fs7, options = {}) {
3619
+ let owners;
3620
+ try {
3621
+ owners = await findProjectsOwningEntity(solutionDir, entityName, fs7);
3622
+ } catch (error) {
3623
+ return `Could not check whether another project still declares an entity named '${entityName}' (${error instanceof Error ? error.message : String(error)}), and the definition resource is shared by name across the solution. Fix access to the solution's project directories and retry.`;
3624
+ }
3625
+ const others = owners.filter((owner) => owner.projectName.toLowerCase() !== projectName.toLowerCase());
3626
+ if (others.length > 0) {
3627
+ return `'${others.map((owner) => owner.projectName).join("', '")}' still declare an entity named '${entityName}', and the definition resource is shared by name across the solution. Delete it from there instead, or remove those stubs first.`;
3628
+ }
3629
+ if (options.ownersOnly)
3630
+ return;
3631
+ let entity;
3632
+ try {
3633
+ const raw = await fs7.readFile(derived, "utf-8");
3634
+ if (typeof raw !== "string")
3635
+ return;
3636
+ entity = unwrapResource(JSON.parse(raw));
3637
+ } catch (error) {
3638
+ if (isUnreadablePathError(error)) {
3639
+ return `Could not read the definition resource '${derived}' (${messageOf(error)}), so whether it is safe to delete cannot be checked. Fix access to the file and retry.`;
3640
+ }
3641
+ return;
3642
+ }
3643
+ if (!isLocallyAuthored(entity)) {
3644
+ return `It describes a platform entity this solution references, not one authored here — it resolves to Data Fabric folder '${entity.FolderId}'. Remove the reference with 'uip solution resources remove' instead; deleting the file drops the reference without recording it.`;
3645
+ }
3646
+ return;
3647
+ }
3648
+ export {
3649
+ INLINE_ENTITY_ERROR_CODES,
3650
+ InlineEntityError,
3651
+ authorNewEntity,
3652
+ inlineEntityAddAsync,
3653
+ inlineEntityDeleteAsync,
3654
+ inlineEntityDeleteOrphanAsync,
3655
+ inlineEntityGetAsync,
3656
+ inlineEntityListAllAsync,
3657
+ inlineEntityListAsync,
3658
+ inlineEntityUpdateAsync,
3659
+ inlineEntityValidateAsync,
3660
+ resolveOwningProjectAsync,
3661
+ resolveProjectAsync,
3662
+ solutionRootAsync
3663
+ };
3664
+
3665
+ //# debugId=AA4817EB17331A5D64756E2164756E21