@uipath/function-tool 1.202.0 → 1.203.0-preview.160

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.
@@ -1,40 +1,46 @@
1
+ import"./packager-tool-1de529jm.js";
2
+
1
3
  // ../../node_modules/@uipath/coded-functions-js-cli/dist/cliRunner.js
2
4
  import { createRequire } from "node:module";
3
5
  import { fileURLToPath as fileURLToPath3 } from "node:url";
4
- import { dirname as dirname5, join as join21 } from "node:path";
5
- import { readFileSync as readFileSync15 } from "node:fs";
6
+ import { dirname as dirname6, join as join22 } from "node:path";
7
+ import { readFileSync as readFileSync17 } from "node:fs";
6
8
  import { execSync } from "node:child_process";
7
9
  import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
8
10
  import { join } from "node:path";
9
11
  import { homedir } from "node:os";
10
- import { spawnSync as spawnSync2 } from "node:child_process";
11
- import { existsSync as existsSync2, writeFileSync as writeFileSync3 } from "node:fs";
12
- import { join as join3, resolve } from "node:path";
12
+ import { existsSync as existsSync3, writeFileSync as writeFileSync4 } from "node:fs";
13
+ import { join as join4, resolve } from "node:path";
13
14
  import { mkdirSync as mkdirSync2, writeFileSync as writeFileSync2 } from "node:fs";
14
15
  import { join as join2 } from "node:path";
15
16
  import { spawnSync } from "node:child_process";
16
- import { existsSync as existsSync6, readFileSync as readFileSync5, writeFileSync as writeFileSync7 } from "node:fs";
17
- import { basename, join as join8, resolve as resolve3 } from "node:path";
17
+ import { copyFileSync, existsSync as existsSync2, readFileSync as readFileSync2, writeFileSync as writeFileSync3 } from "node:fs";
18
+ import { basename, extname, isAbsolute, join as join3 } from "node:path";
19
+ import { existsSync as existsSync7, readFileSync as readFileSync6, writeFileSync as writeFileSync8 } from "node:fs";
20
+ import { basename as basename3, join as join9, resolve as resolve3 } from "node:path";
18
21
  import { spawn } from "node:child_process";
19
- import { writeFileSync as writeFileSync4, mkdirSync as mkdirSync3 } from "node:fs";
20
- import { extname, join as join4 } from "node:path";
21
- import { existsSync as existsSync3, readFileSync as readFileSync2 } from "node:fs";
22
- import { join as join5 } from "node:path";
22
+ import { writeFileSync as writeFileSync5, mkdirSync as mkdirSync3 } from "node:fs";
23
+ import { extname as extname2, join as join5 } from "node:path";
24
+ import { existsSync as existsSync4, readFileSync as readFileSync3 } from "node:fs";
25
+ import { join as join6 } from "node:path";
23
26
  import ts2 from "typescript";
24
27
  import { dirname, resolve as resolve2 } from "node:path";
25
28
  import ts from "typescript";
26
- import { copyFileSync, existsSync as existsSync4, lstatSync, mkdirSync as mkdirSync4, readFileSync as readFileSync3, readdirSync, symlinkSync, writeFileSync as writeFileSync5, cpSync } from "node:fs";
29
+ import { basename as basename2, dirname as dirname2 } from "node:path";
30
+ import ts3 from "typescript";
31
+ import { existsSync as existsSync5, lstatSync, mkdirSync as mkdirSync4, readFileSync as readFileSync4, readdirSync, symlinkSync, writeFileSync as writeFileSync6, cpSync } from "node:fs";
32
+ import { spawnSync as spawnSync2 } from "node:child_process";
27
33
  import { createRequire as createRequire2 } from "node:module";
28
- import { join as join6 } from "node:path";
29
- import { spawnSync as spawnSync3 } from "node:child_process";
34
+ import { join as join7 } from "node:path";
35
+ import { pathToFileURL } from "node:url";
30
36
  import { execSync as execSync2 } from "node:child_process";
31
- import { existsSync as existsSync5, readFileSync as readFileSync4, readdirSync as readdirSync2, writeFileSync as writeFileSync6 } from "node:fs";
32
- import { extname as extname2, join as join7 } from "node:path";
33
- import { mkdirSync as mkdirSync5, readFileSync as readFileSync8, readdirSync as readdirSync3, rmSync, statSync, writeFileSync as writeFileSync9 } from "node:fs";
34
- import { join as join12, resolve as resolve5 } from "node:path";
37
+ import { existsSync as existsSync6, readFileSync as readFileSync5, readdirSync as readdirSync2, writeFileSync as writeFileSync7 } from "node:fs";
38
+ import { extname as extname3, join as join8 } from "node:path";
39
+ import { mkdirSync as mkdirSync5, readFileSync as readFileSync9, readdirSync as readdirSync3, rmSync, statSync, writeFileSync as writeFileSync10 } from "node:fs";
40
+ import { join as join13, resolve as resolve5 } from "node:path";
35
41
  import { randomUUID } from "node:crypto";
36
42
  import { createRequire as createRequire3 } from "module";
37
- import { existsSync as existsSync7 } from "node:fs";
43
+ import { existsSync as existsSync8 } from "node:fs";
38
44
  import * as fs6 from "node:fs/promises";
39
45
  import * as os2 from "node:os";
40
46
  import * as path2 from "node:path";
@@ -67,35 +73,33 @@ import { execFile as execFile4, execFileSync } from "node:child_process";
67
73
  import { promisify as promisify5 } from "node:util";
68
74
  import { execFile as execFile5 } from "node:child_process";
69
75
  import process7 from "node:process";
70
- import { existsSync as existsSync9, readFileSync as readFileSync7 } from "node:fs";
71
- import { join as join11 } from "node:path";
72
- import ts3 from "typescript";
76
+ import { existsSync as existsSync10, readFileSync as readFileSync8 } from "node:fs";
77
+ import { join as join12 } from "node:path";
73
78
  import { createRequire as createRequire4 } from "node:module";
74
79
  import { register } from "node:module";
75
- import { existsSync as existsSync8, readFileSync as readFileSync6, writeFileSync as writeFileSync8 } from "node:fs";
76
- import { join as join10 } from "node:path";
77
- import { pathToFileURL } from "node:url";
78
- import { existsSync as existsSync10, readdirSync as readdirSync4, readFileSync as readFileSync9, statSync as statSync2 } from "node:fs";
80
+ import { existsSync as existsSync9, readFileSync as readFileSync7, writeFileSync as writeFileSync9 } from "node:fs";
81
+ import { join as join11 } from "node:path";
82
+ import { pathToFileURL as pathToFileURL2 } from "node:url";
83
+ import { existsSync as existsSync11, readdirSync as readdirSync4, readFileSync as readFileSync10, statSync as statSync2 } from "node:fs";
79
84
  import { emitKeypressEvents } from "node:readline";
80
- import { join as join13, resolve as resolve6 } from "node:path";
81
- import { existsSync as existsSync13, readFileSync as readFileSync12, writeFileSync as writeFileSync11 } from "node:fs";
82
- import { join as join16, resolve as resolve7 } from "node:path";
85
+ import { join as join14, resolve as resolve6 } from "node:path";
86
+ import { existsSync as existsSync14, readFileSync as readFileSync13, writeFileSync as writeFileSync12 } from "node:fs";
87
+ import { join as join17, resolve as resolve7 } from "node:path";
83
88
  import { createHash } from "node:crypto";
84
- import { existsSync as existsSync12, readFileSync as readFileSync11, readdirSync as readdirSync5, statSync as statSync3 } from "node:fs";
85
- import { join as join15, relative as relative2 } from "node:path";
86
- import { existsSync as existsSync11, mkdirSync as mkdirSync6, readFileSync as readFileSync10, writeFileSync as writeFileSync10 } from "node:fs";
87
- import { dirname as dirname3, join as join14 } from "node:path";
88
- import { existsSync as existsSync15, mkdirSync as mkdirSync8, renameSync, writeFileSync as writeFileSync13 } from "node:fs";
89
- import { join as join18, resolve as resolve9 } from "node:path";
89
+ import { existsSync as existsSync13, readFileSync as readFileSync12, readdirSync as readdirSync5, statSync as statSync3 } from "node:fs";
90
+ import { join as join16, relative as relative2 } from "node:path";
91
+ import { existsSync as existsSync12, mkdirSync as mkdirSync6, readFileSync as readFileSync11, writeFileSync as writeFileSync11 } from "node:fs";
92
+ import { dirname as dirname4, join as join15 } from "node:path";
93
+ import { existsSync as existsSync16, mkdirSync as mkdirSync8, readFileSync as readFileSync15, renameSync, rmSync as rmSync2, writeFileSync as writeFileSync14 } from "node:fs";
94
+ import { join as join19, resolve as resolve9 } from "node:path";
90
95
  import { spawn as spawn2 } from "node:child_process";
91
- import { existsSync as existsSync14, mkdirSync as mkdirSync7, readFileSync as readFileSync13, writeFileSync as writeFileSync12 } from "node:fs";
92
- import { isAbsolute as isAbsolute2, join as join17, relative as relative3, resolve as resolve8 } from "node:path";
93
- import { mkdirSync as mkdirSync9, writeFileSync as writeFileSync14 } from "node:fs";
94
- import { join as join19, resolve as resolve10 } from "node:path";
95
- import { spawnSync as spawnSync4 } from "node:child_process";
96
+ import { existsSync as existsSync15, mkdirSync as mkdirSync7, readFileSync as readFileSync14, writeFileSync as writeFileSync13 } from "node:fs";
97
+ import { isAbsolute as isAbsolute3, join as join18, relative as relative3, resolve as resolve8 } from "node:path";
98
+ import { mkdirSync as mkdirSync9, writeFileSync as writeFileSync15 } from "node:fs";
99
+ import { join as join20, resolve as resolve10 } from "node:path";
96
100
  import { resolve as resolve11 } from "node:path";
97
- import { existsSync as existsSync16, mkdirSync as mkdirSync10, readFileSync as readFileSync14, readdirSync as readdirSync6, writeFileSync as writeFileSync15 } from "node:fs";
98
- import { dirname as dirname4, join as join20, resolve as resolve12 } from "node:path";
101
+ import { existsSync as existsSync17, mkdirSync as mkdirSync10, readFileSync as readFileSync16, readdirSync as readdirSync6, writeFileSync as writeFileSync16 } from "node:fs";
102
+ import { dirname as dirname5, join as join21, resolve as resolve12 } from "node:path";
99
103
  import { fileURLToPath as fileURLToPath2 } from "node:url";
100
104
  import { spawn as spawn3 } from "node:child_process";
101
105
  import { randomUUID as randomUUID2 } from "node:crypto";
@@ -1971,7 +1975,8 @@ var {
1971
1975
  Option,
1972
1976
  Help
1973
1977
  } = import__.default;
1974
- var CACHE_FILE = join(homedir(), ".uipcli", "functions-cache.json");
1978
+ var CACHE_DIR = join(homedir(), ".uipath");
1979
+ var CACHE_FILE = join(CACHE_DIR, "functions-runtime-cache.json");
1975
1980
  function registerSetupCommand(program2) {
1976
1981
  program2.command("setup", { hidden: true }).description("Verify and cache Node.js (and optionally Deno) for JS Functions development.").option("--runtime <runtime>", "Runtime to set up: node, deno, or both", "node").action((opts) => {
1977
1982
  const runtimes = opts.runtime === "both" ? ["node", "deno"] : [opts.runtime];
@@ -2013,13 +2018,6 @@ function setupNode(cache) {
2013
2018
  }).trim();
2014
2019
  cache.node = { path: path3, version };
2015
2020
  console.log(`Node.js ${version} ✓`);
2016
- try {
2017
- execSync("npx --yes tsx --version", { encoding: "utf-8", stdio: "pipe" });
2018
- console.log("tsx ✓");
2019
- } catch {
2020
- console.log("tsx not found — installing globally...");
2021
- execSync("npm install -g tsx", { stdio: "inherit" });
2022
- }
2023
2021
  } catch {
2024
2022
  console.error("Node.js not found. Install from https://nodejs.org (v20+).");
2025
2023
  process.exit(1);
@@ -2050,103 +2048,25 @@ function readCache() {
2050
2048
  return {};
2051
2049
  }
2052
2050
  function writeCache(cache) {
2053
- mkdirSync(join(homedir(), ".uipcli"), { recursive: true });
2051
+ mkdirSync(CACHE_DIR, { recursive: true });
2054
2052
  writeFileSync(CACHE_FILE, JSON.stringify(cache, null, 2), "utf-8");
2055
2053
  }
2056
- var SERVER_RUNNER_DIR = ".uipath/server-runner";
2057
- var DESIGN_TIME_ENV = "DESIGN_TIME";
2058
- var SDK_VERSION = "^0.6.0";
2059
- var RUNTIME_VERSION = "^0.8.0";
2060
- var HONO_NODE_VERSION = "^1.0.0";
2061
- var TSX_VERSION = "^4.0.0";
2062
- var COREIPC_VERSION = "2.5.1-20260324-07";
2063
- var SIGNALR_VERSION = "8.0.7";
2064
- var TRACE_MAPPING_VERSION = "0.3.25";
2065
- var NPM_RC = `@uipath:registry=https://npm.pkg.github.com
2066
- //npm.pkg.github.com/:_authToken=\${GITHUB_TOKEN}`;
2067
- function scaffoldProject(opts) {
2068
- const { projectDir, name, lang, functions } = opts;
2069
- mkdirSync2(projectDir, { recursive: true });
2070
- mkdirSync2(join2(projectDir, "functions"), { recursive: true });
2071
- writeFileSync2(join2(projectDir, "uipath.json"), JSON.stringify({
2072
- $schema: "https://cloud.uipath.com/draft/2024-12/uipath",
2073
- packOptions: {
2074
- fileExtensionsIncluded: [],
2075
- filesIncluded: [],
2076
- filesExcluded: [],
2077
- directoriesExcluded: [],
2078
- includeLockFile: true
2079
- },
2080
- functions
2081
- }, null, 2) + `
2082
- `, "utf-8");
2083
- writeFileSync2(join2(projectDir, "package.json"), JSON.stringify({
2084
- name,
2085
- version: "1.0.0",
2086
- type: "module",
2087
- devDependencies: {
2088
- "@uipath/coded-functions-js-sdk": SDK_VERSION,
2089
- ...lang === "ts" ? { typescript: "^5.7.0" } : {}
2090
- }
2091
- }, null, 2) + `
2092
- `, "utf-8");
2093
- if (lang === "ts") {
2094
- writeFileSync2(join2(projectDir, "tsconfig.json"), JSON.stringify({
2095
- compilerOptions: {
2096
- target: "ESNext",
2097
- module: "ESNext",
2098
- moduleResolution: "bundler",
2099
- strict: true,
2100
- allowImportingTsExtensions: true,
2101
- noEmit: true
2102
- },
2103
- include: ["**/*.ts"],
2104
- exclude: ["node_modules", "dist"]
2105
- }, null, 2) + `
2106
- `, "utf-8");
2107
- }
2108
- writeFileSync2(join2(projectDir, ".env.example"), [
2109
- "UIPATH_URL=",
2110
- "UIPATH_ORGANIZATION_NAME=",
2111
- "UIPATH_TENANT_NAME=",
2112
- "UIPATH_ACCESS_TOKEN=",
2113
- "",
2114
- "# push: Studio Web project ID (create the project in Studio Web to get this)",
2115
- "UIPATH_PROJECT_ID="
2116
- ].join(`
2117
- `) + `
2118
- `, "utf-8");
2119
- writeFileSync2(join2(projectDir, ".gitignore"), `node_modules/
2120
- dist/
2121
- .env
2122
- *.nupkg
2123
- .uipath/
2124
- `, "utf-8");
2125
- }
2126
- var bunAvailableCache;
2127
- function hasBun() {
2128
- if (bunAvailableCache !== undefined)
2129
- return bunAvailableCache;
2130
- const result = spawnSync("bun", ["--version"], {
2131
- stdio: "ignore",
2132
- shell: process.platform === "win32"
2133
- });
2134
- bunAvailableCache = result.status === 0;
2135
- return bunAvailableCache;
2136
- }
2137
- function getInstallCommand(onlyProd, extraArgs = []) {
2138
- if (hasBun()) {
2139
- if (onlyProd) {
2140
- return { cmd: "bun", args: ["install", "--production", ...extraArgs] };
2141
- }
2142
- return { cmd: "bun", args: ["install", ...extraArgs] };
2143
- }
2144
- if (onlyProd) {
2145
- return { cmd: "npm", args: ["install", "--omit=dev", ...extraArgs] };
2146
- }
2147
- return { cmd: "npm", args: ["install", ...extraArgs] };
2148
- }
2149
- var HELLO_TS = `import { defineFunction, defineSchema } from "@uipath/coded-functions-js-sdk";
2054
+ var SDK_VERSION = "0.6.2";
2055
+ var SDK_RANGE = `^${SDK_VERSION}`;
2056
+ var SDK_PACKAGE_NAME = "@uipath/coded-functions-js-sdk";
2057
+ var TYPESCRIPT_RANGE = "^5.7.0";
2058
+ var SAMPLE_FUNCTION = {
2059
+ name: "hello",
2060
+ description: "Returns a greeting message.",
2061
+ method: "POST",
2062
+ path: "/hello",
2063
+ entryExport: "default"
2064
+ };
2065
+ var httpSemantics = ` method: "${SAMPLE_FUNCTION.method}",
2066
+ path: "${SAMPLE_FUNCTION.path}",
2067
+ `;
2068
+ var semanticsFor = (variant) => variant === "http" ? httpSemantics : "";
2069
+ var buildHelloTs = (variant) => `import { defineFunction, defineSchema, type FunctionContext } from "@uipath/coded-functions-js-sdk";
2150
2070
 
2151
2071
  interface HelloInput {
2152
2072
  /**
@@ -2160,27 +2080,28 @@ interface HelloOutput {
2160
2080
  message: string;
2161
2081
  }
2162
2082
 
2083
+ function main(input: HelloInput, ctx: FunctionContext): HelloOutput {
2084
+ const output: HelloOutput = {
2085
+ message: \`Hello, \${input.name}!\`,
2086
+ };
2087
+ return output;
2088
+ }
2089
+
2163
2090
  export default defineFunction({
2164
- name: "hello",
2165
- description: "Returns a greeting message.",
2166
- method: "POST",
2167
- path: "/hello",
2168
- input: defineSchema<HelloInput>(),
2091
+ name: "${SAMPLE_FUNCTION.name}",
2092
+ description: "${SAMPLE_FUNCTION.description}",
2093
+ ${semanticsFor(variant)} input: defineSchema<HelloInput>(),
2169
2094
  output: defineSchema<HelloOutput>(),
2170
- handler: async (input, ctx) => ({
2171
- message: \`Hello, \${input.name}!\`,
2172
- }),
2095
+ handler: main,
2173
2096
  });
2174
2097
  `;
2175
- var HELLO_JS = `// @ts-check
2098
+ var buildHelloJs = (variant) => `// @ts-check
2176
2099
  import { defineFunction } from "@uipath/coded-functions-js-sdk";
2177
2100
 
2178
2101
  export default defineFunction({
2179
- name: "hello",
2180
- description: "Returns a greeting message.",
2181
- method: "POST",
2182
- path: "/hello",
2183
- input: {
2102
+ name: "${SAMPLE_FUNCTION.name}",
2103
+ description: "${SAMPLE_FUNCTION.description}",
2104
+ ${semanticsFor(variant)} input: {
2184
2105
  type: "object",
2185
2106
  properties: {
2186
2107
  name: { type: "string", default: "World" },
@@ -2200,93 +2121,634 @@ export default defineFunction({
2200
2121
  }),
2201
2122
  });
2202
2123
  `;
2203
- function registerNewCommand(program2) {
2204
- program2.command("new [name]").description("Scaffold a new JS/TS Functions project. Includes a hello world function by default; pass --empty to skip it.").option("--name <name>", "Project name / directory (alias for positional arg)").option("-l, --language <lang>", "Language: ts (default) or js", "ts").option("--empty", "Skip the hello world function — create an empty project").action((nameArg, opts) => {
2205
- const projectName = opts.name ?? nameArg ?? "my-functions";
2206
- const lang = opts.language === "js" ? "js" : "ts";
2207
- const projectDir = resolve(projectName);
2208
- if (existsSync2(projectDir)) {
2209
- console.error(`Directory already exists: ${projectDir}`);
2210
- process.exit(1);
2211
- }
2212
- ensureSetup();
2213
- const withSample = !opts.empty;
2214
- scaffoldProject({
2215
- projectDir,
2216
- name: projectName,
2217
- type: "module",
2218
- lang,
2219
- functions: withSample ? { hello: `functions/hello.${lang}:default` } : {}
2220
- });
2221
- if (withSample) {
2222
- writeFileSync3(join3(projectDir, "functions", `hello.${lang}`), lang === "ts" ? HELLO_TS : HELLO_JS, "utf-8");
2223
- }
2224
- if (process.env["GITHUB_TOKEN"]) {
2225
- writeFileSync3(join3(projectDir, ".npmrc"), NPM_RC, "utf-8");
2226
- }
2227
- console.log(`
2228
- Created ${projectName}/`);
2229
- console.log("Installing dependencies...");
2230
- const { cmd, args } = getInstallCommand(false);
2231
- const installResult = spawnSync2(cmd, args, {
2232
- cwd: projectDir,
2233
- stdio: "inherit",
2234
- shell: process.platform === "win32"
2235
- });
2236
- if (installResult.status !== 0) {
2237
- console.error(`${cmd} install failed in ${projectDir}.`);
2238
- process.exit(1);
2124
+ var HELLO_TS = buildHelloTs("http");
2125
+ var HELLO_TS_JOB = buildHelloTs("job");
2126
+ var HELLO_JS = buildHelloJs("http");
2127
+ var HELLO_JS_JOB = buildHelloJs("job");
2128
+ var sanitizeNpmPackageName = (projectName) => projectName.toLowerCase().replace(/\s+/g, "-").replace(/[^a-z0-9-._]/g, "").replace(/^[-._]+/, "") || "function-project";
2129
+ var sampleDevDependencies = (language) => ({
2130
+ [SDK_PACKAGE_NAME]: SDK_RANGE,
2131
+ ...language === "ts" ? { typescript: TYPESCRIPT_RANGE } : {}
2132
+ });
2133
+ var getSamplePackageJson = (projectName, language) => JSON.stringify({
2134
+ name: sanitizeNpmPackageName(projectName),
2135
+ version: "1.0.0",
2136
+ type: "module",
2137
+ devDependencies: sampleDevDependencies(language)
2138
+ }, null, 2) + `
2139
+ `;
2140
+ var SAMPLE_TSCONFIG = JSON.stringify({
2141
+ compilerOptions: {
2142
+ target: "ESNext",
2143
+ module: "ESNext",
2144
+ moduleResolution: "bundler",
2145
+ strict: true,
2146
+ allowImportingTsExtensions: true,
2147
+ noEmit: true
2148
+ },
2149
+ include: ["**/*.ts"],
2150
+ exclude: ["node_modules", "dist"]
2151
+ }, null, 2) + `
2152
+ `;
2153
+ var SAMPLE_LOCK_PACKAGES = {
2154
+ "node_modules/@babel/runtime": {
2155
+ version: "7.29.7",
2156
+ resolved: "https://registry.npmjs.org/@babel/runtime/-/runtime-7.29.7.tgz",
2157
+ integrity: "sha512-Nq8OhGWiZIZGV6hLHoyAKLLcJihP/xFeBMGJoUrxTX2psI8dCifzLhZISFb+VWS3wFMRDmCGw5R+dOySCqPLhw==",
2158
+ dev: true,
2159
+ license: "MIT",
2160
+ engines: { node: ">=6.9.0" }
2161
+ },
2162
+ "node_modules/@standard-schema/spec": {
2163
+ version: "1.1.0",
2164
+ resolved: "https://registry.npmjs.org/@standard-schema/spec/-/spec-1.1.0.tgz",
2165
+ integrity: "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==",
2166
+ dev: true,
2167
+ license: "MIT"
2168
+ },
2169
+ [`node_modules/${SDK_PACKAGE_NAME}`]: {
2170
+ version: SDK_VERSION,
2171
+ dev: true,
2172
+ dependencies: {
2173
+ "@standard-schema/spec": "^1.1.0",
2174
+ "json-schema-to-ts": "^3.1.1"
2239
2175
  }
2240
- console.log(`
2241
- Ready. Next steps:`);
2242
- console.log(` cd ${projectName}`);
2243
- if (withSample) {
2244
- console.log(` uip functions serve`);
2245
- } else {
2246
- console.log(` # Add your function entry points to ${projectName}/functions/`);
2247
- console.log(` uip functions serve`);
2176
+ },
2177
+ "node_modules/json-schema-to-ts": {
2178
+ version: "3.1.1",
2179
+ resolved: "https://registry.npmjs.org/json-schema-to-ts/-/json-schema-to-ts-3.1.1.tgz",
2180
+ integrity: "sha512-+DWg8jCJG2TEnpy7kOm/7/AxaYoaRbjVB4LFZLySZlWn8exGs3A4OLJR966cVvU26N7X9TWxl+Jsw7dzAqKT6g==",
2181
+ dev: true,
2182
+ license: "MIT",
2183
+ dependencies: {
2184
+ "@babel/runtime": "^7.18.3",
2185
+ "ts-algebra": "^2.0.0"
2186
+ },
2187
+ engines: { node: ">=16" }
2188
+ },
2189
+ "node_modules/ts-algebra": {
2190
+ version: "2.0.0",
2191
+ resolved: "https://registry.npmjs.org/ts-algebra/-/ts-algebra-2.0.0.tgz",
2192
+ integrity: "sha512-FPAhNPFMrkwz76P7cdjdmiShwMynZYN6SgOujD1urY4oNm80Ou9oMdmbR45LotcKOXoy7wSmHkRFE6Mxbrhefw==",
2193
+ dev: true,
2194
+ license: "MIT"
2195
+ },
2196
+ "node_modules/typescript": {
2197
+ version: "5.9.3",
2198
+ resolved: "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz",
2199
+ integrity: "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==",
2200
+ dev: true,
2201
+ license: "Apache-2.0",
2202
+ bin: { tsc: "bin/tsc", tsserver: "bin/tsserver" },
2203
+ engines: { node: ">=14.17" }
2204
+ }
2205
+ };
2206
+ function scaffoldProject(opts) {
2207
+ const { projectDir, name, lang, functions } = opts;
2208
+ mkdirSync2(projectDir, { recursive: true });
2209
+ mkdirSync2(join2(projectDir, "functions"), { recursive: true });
2210
+ writeFileSync2(join2(projectDir, "uipath.json"), JSON.stringify({
2211
+ $schema: "https://cloud.uipath.com/draft/2024-12/uipath",
2212
+ packOptions: {
2213
+ fileExtensionsIncluded: [],
2214
+ filesIncluded: [],
2215
+ filesExcluded: [],
2216
+ directoriesExcluded: []
2217
+ },
2218
+ functions
2219
+ }, null, 2) + `
2220
+ `, "utf-8");
2221
+ writeFileSync2(join2(projectDir, "package.json"), getSamplePackageJson(name, lang), "utf-8");
2222
+ if (lang === "ts") {
2223
+ writeFileSync2(join2(projectDir, "tsconfig.json"), SAMPLE_TSCONFIG, "utf-8");
2224
+ }
2225
+ writeFileSync2(join2(projectDir, ".env.example"), [
2226
+ "UIPATH_URL=",
2227
+ "UIPATH_ORGANIZATION_NAME=",
2228
+ "UIPATH_TENANT_NAME=",
2229
+ "UIPATH_ACCESS_TOKEN=",
2230
+ "",
2231
+ "# push: Studio Web project ID (create the project in Studio Web to get this)",
2232
+ "UIPATH_PROJECT_ID="
2233
+ ].join(`
2234
+ `) + `
2235
+ `, "utf-8");
2236
+ writeFileSync2(join2(projectDir, ".gitignore"), `node_modules/
2237
+ dist/
2238
+ .env
2239
+ *.nupkg
2240
+ .uipath/
2241
+ `, "utf-8");
2242
+ }
2243
+ var npm = { name: "npm", lockFile: "package-lock.json", installHint: "npm install" };
2244
+ var bun = { name: "bun", lockFile: "bun.lock", installHint: "bun install" };
2245
+ var SUPPORTED_MANAGERS = [npm, bun];
2246
+ var RECOGNIZED_UNSUPPORTED_LOCK_FILES = ["yarn.lock", "pnpm-lock.yaml", "bun.lockb"];
2247
+ function detectPackageManager(present) {
2248
+ const supported = SUPPORTED_MANAGERS.filter((manager) => present.has(manager.lockFile));
2249
+ if (supported.length > 1)
2250
+ return { kind: "ambiguous", managers: supported };
2251
+ if (supported.length === 1)
2252
+ return { kind: "found", manager: supported[0] };
2253
+ const unsupported = RECOGNIZED_UNSUPPORTED_LOCK_FILES.filter((name) => present.has(name));
2254
+ return unsupported.length > 0 ? { kind: "unsupported", fileNames: unsupported } : { kind: "none" };
2255
+ }
2256
+ var CANDIDATE_LOCK_FILES = [
2257
+ ...SUPPORTED_MANAGERS.map((manager) => manager.lockFile),
2258
+ ...RECOGNIZED_UNSUPPORTED_LOCK_FILES
2259
+ ];
2260
+ async function probeLockFiles(reader) {
2261
+ const present = new Set;
2262
+ for (const fileName of CANDIDATE_LOCK_FILES) {
2263
+ if (await reader.fileExists(fileName))
2264
+ present.add(fileName);
2265
+ }
2266
+ return present;
2267
+ }
2268
+ function supportedLockFilesLabel() {
2269
+ return SUPPORTED_MANAGERS.map((manager) => `${manager.lockFile} (${manager.name})`).join(" or ");
2270
+ }
2271
+ function describeDependencyProblem(detection) {
2272
+ const defaultHint = SUPPORTED_MANAGERS[0].installHint;
2273
+ switch (detection.kind) {
2274
+ case "none":
2275
+ return {
2276
+ problem: `No dependency lock file found; expected ${supportedLockFilesLabel()}.`,
2277
+ remedyCommand: defaultHint
2278
+ };
2279
+ case "unsupported": {
2280
+ const names = detection.fileNames.join(" and ");
2281
+ return {
2282
+ problem: `Found ${names}, which cannot be installed from; expected ${supportedLockFilesLabel()}. ` + `Create a supported lock file, then delete ${names}.`,
2283
+ remedyCommand: defaultHint
2284
+ };
2248
2285
  }
2286
+ case "ambiguous":
2287
+ return {
2288
+ problem: `Found ${detection.managers.map((manager) => manager.lockFile).join(" and ")}. Keep exactly one: ` + `with two lock files the installer that runs on the pod picks one and the other's resolution ` + `is silently ignored.`,
2289
+ remedyCommand: null
2290
+ };
2291
+ }
2292
+ }
2293
+ var REGISTRY_CONFIG_FILE = ".npmrc";
2294
+ function isRegistryConfigFile(fileName) {
2295
+ return fileName === REGISTRY_CONFIG_FILE;
2296
+ }
2297
+ var CREDENTIAL_KEYS = ["_authtoken", "_auth", "_password"];
2298
+ function isComment(line) {
2299
+ return line === "" || line.startsWith("#") || line.startsWith(";");
2300
+ }
2301
+ function settingKey(line) {
2302
+ const trimmed = line.trim();
2303
+ if (isComment(trimmed))
2304
+ return null;
2305
+ return (trimmed.split("=")[0] ?? "").trim().toLowerCase();
2306
+ }
2307
+ function sanitizeRegistryConfig(content, stripScopes) {
2308
+ const stripped = stripScopes.map((scope) => `${scope.replace(/:$/, "")}:`.toLowerCase());
2309
+ const kept = content.split(/\r?\n/).filter((line) => {
2310
+ const key = settingKey(line);
2311
+ if (key === null)
2312
+ return true;
2313
+ if (stripped.some((scope) => key.startsWith(scope)))
2314
+ return false;
2315
+ return !CREDENTIAL_KEYS.some((credential) => key.endsWith(credential));
2249
2316
  });
2317
+ return kept.some((line) => !isComment(line.trim())) ? kept.join(`
2318
+ `) : null;
2250
2319
  }
2251
- function generateAggregator(functionsMap, cwd, variant, derivedByPath = {}) {
2252
- const lang = detectLanguage(functionsMap);
2253
- const ext = lang === "javascript" ? "js" : "ts";
2254
- const fileToFunctions = new Map;
2255
- for (const [name, entry] of Object.entries(functionsMap)) {
2256
- const file = entry.split(":")[0];
2257
- const existing = fileToFunctions.get(file);
2258
- if (existing) {
2259
- existing.push(name);
2260
- } else {
2261
- fileToFunctions.set(file, [name]);
2320
+ function ifsProjectFileReader(fs7, projectPath) {
2321
+ return {
2322
+ async fileExists(fileName) {
2323
+ try {
2324
+ return await fs7.exists(fs7.path.join(projectPath, fileName));
2325
+ } catch {
2326
+ return false;
2327
+ }
2328
+ },
2329
+ async readFile(fileName) {
2330
+ const content = await fs7.readFile(fs7.path.join(projectPath, fileName), "utf-8");
2331
+ if (content === null)
2332
+ throw new Error(`${fileName} not found in ${projectPath}.`);
2333
+ return content;
2262
2334
  }
2335
+ };
2336
+ }
2337
+ var EXCLUDED_NAMES = new Set([
2338
+ "node_modules",
2339
+ ".git",
2340
+ ".env",
2341
+ ".deno",
2342
+ "dist",
2343
+ ".uipath"
2344
+ ]);
2345
+ var EXCLUDED_EXTENSIONS = [".nupkg"];
2346
+ var SCOPES_NOT_PACKAGED = ["@uipath"];
2347
+ async function buildFunctionsPackage(fs7, options) {
2348
+ const { projectPath, outputPath, projectStorageId } = options;
2349
+ const contentPath = fs7.path.join(outputPath, "content");
2350
+ await fs7.mkdir(outputPath);
2351
+ await fs7.mkdir(contentPath);
2352
+ const uipathJsonRaw = await fs7.readFile(fs7.path.join(projectPath, "uipath.json"), "utf-8");
2353
+ if (!uipathJsonRaw) {
2354
+ throw new Error("uipath.json not found. Run 'uipath-functions init' first.");
2263
2355
  }
2264
- for (const [file, names] of fileToFunctions) {
2265
- if (names.length > 1) {
2266
- throw new Error(`Multiple function definitions in the same file are not allowed.
2267
- ` + `File "${file}" is used by: ${names.join(", ")}.
2268
- ` + `Each function must be defined in its own file.`);
2269
- }
2356
+ const uipathJson = JSON.parse(uipathJsonRaw);
2357
+ const entryPointsRaw = await fs7.readFile(fs7.path.join(projectPath, "entry-points.json"), "utf-8");
2358
+ if (!entryPointsRaw) {
2359
+ throw new Error("entry-points.json not found. Run 'uipath-functions pack' to generate it.");
2270
2360
  }
2271
- const files = [...fileToFunctions.keys()];
2272
- let outputFile;
2273
- let importPrefix;
2274
- if (variant === "serve") {
2275
- const dbgDir = join4(cwd, SERVER_RUNNER_DIR);
2276
- mkdirSync3(dbgDir, { recursive: true });
2277
- outputFile = join4(dbgDir, `function-main.${ext}`);
2278
- importPrefix = "../../";
2279
- } else {
2280
- outputFile = join4(cwd, `function-main.${ext}`);
2281
- importPrefix = "./";
2361
+ const entryPoints = JSON.parse(entryPointsRaw);
2362
+ const bindingsRaw = await fs7.readFile(fs7.path.join(projectPath, "bindings_v2.json"), "utf-8");
2363
+ if (!bindingsRaw) {
2364
+ throw new Error("bindings_v2.json not found. Run 'uipath-functions pack' to generate it.");
2282
2365
  }
2283
- const imports = files.map((file, i) => `import f${i} from "${importPrefix}${file}";`).join(`
2284
- `);
2285
- const relevantDerived = {};
2286
- for (const file of files) {
2287
- const d = derivedByPath[file];
2288
- if (!d)
2289
- continue;
2366
+ const bindings = JSON.parse(bindingsRaw);
2367
+ const packageJsonRaw = await fs7.readFile(fs7.path.join(projectPath, "package.json"), "utf-8");
2368
+ const packageDependencies = packageJsonRaw ? JSON.parse(packageJsonRaw).dependencies ?? {} : {};
2369
+ const targetRuntime = detectRuntime(uipathJson.functions);
2370
+ const detection = detectPackageManager(await probeLockFiles(ifsProjectFileReader(fs7, projectPath)));
2371
+ if (detection.kind !== "found") {
2372
+ const { problem, remedyCommand } = describeDependencyProblem(detection);
2373
+ throw new Error(remedyCommand !== null ? `${problem} Run '${remedyCommand}' in the project, then pack again.` : `${problem} Then pack again.`);
2374
+ }
2375
+ const lockFile = detection.manager.lockFile;
2376
+ if (uipathJson.packOptions?.includeLockFile === false) {
2377
+ console.warn(`uipath.json packOptions.includeLockFile is ignored: ${lockFile} is always packaged.`);
2378
+ }
2379
+ await copyProjectFiles(fs7, projectPath, contentPath, lockFile, uipathJson.packOptions);
2380
+ const operateJson = {
2381
+ $schema: "https://cloud.uipath.com/draft/2024-12/operate",
2382
+ projectId: projectStorageId,
2383
+ contentType: "function",
2384
+ targetFramework: "Portable",
2385
+ targetRuntime,
2386
+ runtimeOptions: {
2387
+ requiresUserInteraction: false,
2388
+ isAttended: false
2389
+ },
2390
+ deploymentOptions: {
2391
+ generateSlug: true
2392
+ },
2393
+ dependencies: packageDependencies
2394
+ };
2395
+ await fs7.writeFile(fs7.path.join(contentPath, "operate.json"), JSON.stringify(operateJson, null, 2));
2396
+ await fs7.writeFile(fs7.path.join(contentPath, "entry-points.json"), JSON.stringify(entryPoints, null, 2));
2397
+ await fs7.writeFile(fs7.path.join(contentPath, "bindings_v2.json"), JSON.stringify(bindings, null, 2));
2398
+ const packageDescriptor = {
2399
+ $schema: "https://cloud.uipath.com/draft/2024-12/package-descriptor",
2400
+ files: {
2401
+ "operate.json": "content/operate.json",
2402
+ "entry-points.json": "content/entry-points.json",
2403
+ "bindings.json": "content/bindings_v2.json"
2404
+ }
2405
+ };
2406
+ for (const ep of entryPoints.entryPoints) {
2407
+ const fnEntry = uipathJson.functions?.[ep.filePath];
2408
+ const filePath = fnEntry ? fnEntry.split(":")[0] ?? ep.filePath : ep.filePath;
2409
+ packageDescriptor.files[ep.filePath] = `${filePath}`;
2410
+ }
2411
+ await fs7.writeFile(fs7.path.join(contentPath, "package-descriptor.json"), JSON.stringify(packageDescriptor, null, 2));
2412
+ }
2413
+ function detectRuntime(functions) {
2414
+ if (!functions)
2415
+ return "javascript";
2416
+ const first = Object.values(functions)[0];
2417
+ if (!first)
2418
+ return "javascript";
2419
+ const filePath = first.split(":")[0] ?? "";
2420
+ const ext = filePath.slice(filePath.lastIndexOf("."));
2421
+ if (ext === ".py")
2422
+ return "python";
2423
+ return "javascript";
2424
+ }
2425
+ async function copyProjectFiles(fs7, sourcePath, destPath, lockFile, packOptions) {
2426
+ const extraExcludedDirs = new Set(packOptions?.directoriesExcluded ?? []);
2427
+ const extraExcludedFiles = new Set(packOptions?.filesExcluded ?? []);
2428
+ const otherLockFiles = new Set(CANDIDATE_LOCK_FILES.filter((name) => name !== lockFile));
2429
+ async function walk(src, dest) {
2430
+ await fs7.mkdir(dest);
2431
+ const entries = await fs7.readdir(src);
2432
+ for (const name of entries) {
2433
+ if (EXCLUDED_NAMES.has(name))
2434
+ continue;
2435
+ if (extraExcludedDirs.has(name))
2436
+ continue;
2437
+ if (extraExcludedFiles.has(name))
2438
+ continue;
2439
+ if (EXCLUDED_EXTENSIONS.some((ext) => name.endsWith(ext)))
2440
+ continue;
2441
+ if (otherLockFiles.has(name))
2442
+ continue;
2443
+ const srcEntry = fs7.path.join(src, name);
2444
+ const destEntry = fs7.path.join(dest, name);
2445
+ const stat2 = await fs7.stat(srcEntry);
2446
+ if (stat2?.isDirectory()) {
2447
+ await walk(srcEntry, destEntry);
2448
+ } else if (isRegistryConfigFile(name)) {
2449
+ const raw = await fs7.readFile(srcEntry, "utf-8") ?? "";
2450
+ const sanitized = sanitizeRegistryConfig(raw, SCOPES_NOT_PACKAGED);
2451
+ if (sanitized !== null)
2452
+ await fs7.writeFile(destEntry, sanitized);
2453
+ } else if (stat2?.isFile()) {
2454
+ const content = await fs7.readFile(srcEntry);
2455
+ if (content)
2456
+ await fs7.writeFile(destEntry, content);
2457
+ }
2458
+ }
2459
+ }
2460
+ await walk(sourcePath, destPath);
2461
+ }
2462
+ var COMMANDS = {
2463
+ npm: {
2464
+ bin: "npm",
2465
+ args: ({ production, preferOffline }) => [
2466
+ "install",
2467
+ ...production === true ? ["--omit=dev"] : [],
2468
+ ...preferOffline === true ? ["--prefer-offline"] : []
2469
+ ],
2470
+ verifyArgs: ["ci", "--dry-run", "--no-audit", "--no-fund"],
2471
+ saysLockDiffers: (output) => output.includes("EUSAGE")
2472
+ },
2473
+ bun: {
2474
+ bin: "bun",
2475
+ args: ({ production, preferOffline }) => [
2476
+ "install",
2477
+ ...production === true ? ["--production"] : [],
2478
+ ...preferOffline === true ? ["--prefer-offline"] : []
2479
+ ],
2480
+ verifyArgs: ["install", "--frozen-lockfile", "--dry-run"],
2481
+ saysLockDiffers: (output) => output.includes("lockfile had changes")
2482
+ }
2483
+ };
2484
+ var FALLBACK_ORDER = ["npm", "bun"];
2485
+ var PACKAGE_MANAGER_NAMES = Object.keys(COMMANDS);
2486
+ var RUNNER_REGISTRY_CONFIG = `@uipath:registry=https://npm.pkg.github.com
2487
+ //npm.pkg.github.com/:_authToken=\${GITHUB_TOKEN}`;
2488
+ function writeRunnerRegistryConfig(dir) {
2489
+ if (process.env["GITHUB_TOKEN"] === undefined || process.env["GITHUB_TOKEN"] === "")
2490
+ return;
2491
+ writeFileSync3(join3(dir, REGISTRY_CONFIG_FILE), RUNNER_REGISTRY_CONFIG, "utf-8");
2492
+ }
2493
+ function shareRegistryConfig(fromDir, toDir) {
2494
+ if (fromDir === toDir)
2495
+ return;
2496
+ const source = join3(fromDir, REGISTRY_CONFIG_FILE);
2497
+ if (existsSync2(source))
2498
+ copyFileSync(source, join3(toDir, REGISTRY_CONFIG_FILE));
2499
+ }
2500
+ var onPathCache = new Map;
2501
+ function isOnPath(name) {
2502
+ const cached = onPathCache.get(name);
2503
+ if (cached !== undefined)
2504
+ return cached;
2505
+ const result = spawnSync(COMMANDS[name].bin, ["--version"], {
2506
+ stdio: "ignore",
2507
+ shell: process.platform === "win32"
2508
+ });
2509
+ const available = result.status === 0;
2510
+ onPathCache.set(name, available);
2511
+ return available;
2512
+ }
2513
+ function detectAvailableManagers() {
2514
+ return FALLBACK_ORDER.filter((name) => isOnPath(name));
2515
+ }
2516
+ function declaredManager(cwd) {
2517
+ let declared;
2518
+ try {
2519
+ declared = JSON.parse(readFileSync2(join3(cwd, "package.json"), "utf-8")).packageManager;
2520
+ } catch {
2521
+ return null;
2522
+ }
2523
+ if (typeof declared !== "string")
2524
+ return null;
2525
+ const name = declared.split("@")[0];
2526
+ return Object.keys(COMMANDS).find((known) => known === name) ?? null;
2527
+ }
2528
+ function presentLockFiles(cwd) {
2529
+ return new Set(CANDIDATE_LOCK_FILES.filter((fileName) => existsSync2(join3(cwd, fileName))));
2530
+ }
2531
+ function lockedManager(cwd) {
2532
+ const detection = detectPackageManager(presentLockFiles(cwd));
2533
+ return detection.kind === "found" ? detection.manager.name : null;
2534
+ }
2535
+ function firstComplaint(output) {
2536
+ const lines = output.split(`
2537
+ `).map((line) => line.replace(/^npm (error|warn)/, "").trim()).filter((line) => line !== "");
2538
+ const end = lines.findIndex((line) => line.startsWith("Usage:") || line.startsWith("Options:"));
2539
+ return (end === -1 ? lines : lines.slice(0, end)).slice(0, 3).join(" ");
2540
+ }
2541
+ function detectProjectManager(cwd) {
2542
+ return lockedManager(cwd) ?? declaredManager(cwd);
2543
+ }
2544
+ function resolvePackageManager(cwd, required) {
2545
+ const { name, bin, shell } = required === undefined ? chosenInvocation(cwd) : requiredInvocation(required);
2546
+ const { args, verifyArgs, saysLockDiffers } = COMMANDS[name];
2547
+ return {
2548
+ name,
2549
+ verifyLock(dir) {
2550
+ const result = spawnSync(bin, [...verifyArgs], {
2551
+ cwd: dir,
2552
+ encoding: "utf-8",
2553
+ shell
2554
+ });
2555
+ const output = `${result.stdout ?? ""}
2556
+ ${result.stderr ?? ""}`;
2557
+ const detail = firstComplaint(output);
2558
+ if (result.status === 0)
2559
+ return { verdict: "current", detail };
2560
+ return { verdict: saysLockDiffers(output) ? "differs" : "unknown", detail };
2561
+ },
2562
+ runInstall(dir, options = {}) {
2563
+ shareRegistryConfig(cwd, dir);
2564
+ const argv = args(options);
2565
+ console.log(`Running: ${bin} ${argv.join(" ")}`);
2566
+ const result = spawnSync(bin, argv, {
2567
+ cwd: dir,
2568
+ stdio: "inherit",
2569
+ shell
2570
+ });
2571
+ if (result.status !== 0) {
2572
+ throw new Error(`'${bin} ${argv.join(" ")}' failed in ${dir}.`);
2573
+ }
2574
+ }
2575
+ };
2576
+ }
2577
+ function chooseManager(cwd) {
2578
+ const available = detectAvailableManagers();
2579
+ const desired = detectProjectManager(cwd);
2580
+ if (desired !== null && !available.includes(desired)) {
2581
+ const found = available.length > 0 ? ` (found ${available.join(", ")})` : "";
2582
+ throw new Error(`This project must be installed with ${desired}, which is not on PATH${found}.`);
2583
+ }
2584
+ const name = desired ?? available[0];
2585
+ if (name === undefined) {
2586
+ throw new Error(`No supported package manager is on PATH (looked for ${FALLBACK_ORDER.join(", ")}).`);
2587
+ }
2588
+ return name;
2589
+ }
2590
+ function chosenInvocation(cwd) {
2591
+ const name = chooseManager(cwd);
2592
+ return { name, bin: COMMANDS[name].bin, shell: process.platform === "win32" };
2593
+ }
2594
+ function requiredInvocation(required) {
2595
+ if (isManagerName(required)) {
2596
+ if (!isOnPath(required)) {
2597
+ throw new Error(`Cannot install with ${required}: it is not on PATH.`);
2598
+ }
2599
+ return { name: required, bin: COMMANDS[required].bin, shell: process.platform === "win32" };
2600
+ }
2601
+ const name = basename(required, extname(required)).toLowerCase();
2602
+ if (!isManagerName(name)) {
2603
+ throw new Error(`Cannot tell which package manager '${required}' is. Pass ${PACKAGE_MANAGER_NAMES.join(" or ")}, ` + "or the path to a binary named after one.");
2604
+ }
2605
+ if (!isAbsolute(required)) {
2606
+ throw new Error(`Cannot install with '${required}': a package manager path must be absolute.`);
2607
+ }
2608
+ if (!existsSync2(required)) {
2609
+ throw new Error(`Cannot install with '${required}': there is no such file.`);
2610
+ }
2611
+ return { name, bin: required, shell: needsShell(required) };
2612
+ }
2613
+ function isManagerName(value) {
2614
+ return PACKAGE_MANAGER_NAMES.includes(value);
2615
+ }
2616
+ function needsShell(managerPath) {
2617
+ return process.platform === "win32" && extname(managerPath).toLowerCase() !== ".exe";
2618
+ }
2619
+ function checkDependenciesInstalled(cwd) {
2620
+ if (existsSync2(join3(cwd, "node_modules")))
2621
+ return { ready: true, problem: null, remedyCommand: null };
2622
+ return {
2623
+ ready: false,
2624
+ problem: "node_modules not found.",
2625
+ remedyCommand: describeInstallCommand(cwd)
2626
+ };
2627
+ }
2628
+ function checkLockCurrent(cwd) {
2629
+ const detection = detectPackageManager(presentLockFiles(cwd));
2630
+ if (detection.kind !== "found") {
2631
+ const { problem, remedyCommand } = describeDependencyProblem(detection);
2632
+ return { ready: false, problem, remedyCommand };
2633
+ }
2634
+ const { lockFile, installHint } = detection.manager;
2635
+ const { verdict, detail } = resolvePackageManager(cwd).verifyLock(cwd);
2636
+ if (verdict === "current")
2637
+ return { ready: true, problem: null, remedyCommand: null };
2638
+ if (verdict === "unknown") {
2639
+ return {
2640
+ ready: false,
2641
+ problem: `Could not check whether ${lockFile} is up to date${detail === "" ? "." : `: ${detail}`}`,
2642
+ remedyCommand: null
2643
+ };
2644
+ }
2645
+ return {
2646
+ ready: false,
2647
+ problem: detail === "" ? `${lockFile} is out of date.` : `${lockFile} is out of date: ${detail}`,
2648
+ remedyCommand: installHint
2649
+ };
2650
+ }
2651
+ function describeInstallCommand(cwd) {
2652
+ const name = detectProjectManager(cwd) ?? FALLBACK_ORDER[0];
2653
+ const { bin, args } = COMMANDS[name];
2654
+ return `${bin} ${args({}).join(" ")}`;
2655
+ }
2656
+ function affectsDependencyInstall(fileName) {
2657
+ return CANDIDATE_LOCK_FILES.includes(fileName);
2658
+ }
2659
+ function describePackagedInstallProblem(installInputs) {
2660
+ const detection = detectPackageManager(new Set(installInputs));
2661
+ if (detection.kind === "found")
2662
+ return null;
2663
+ return `cannot be installed: ${describeDependencyProblem(detection).problem}`;
2664
+ }
2665
+ function registerNewCommand(program2) {
2666
+ program2.command("new [name]").description("Scaffold a new JS/TS Functions project. Includes a hello world function by default; pass --empty to skip it.").option("--name <name>", "Project name / directory (alias for positional arg)").option("-l, --language <lang>", "Language: ts (default) or js", "ts").option("--empty", "Skip the hello world function — create an empty project").action((nameArg, opts) => {
2667
+ const projectName = opts.name ?? nameArg ?? "my-functions";
2668
+ const lang = opts.language === "js" ? "js" : "ts";
2669
+ const projectDir = resolve(projectName);
2670
+ if (existsSync3(projectDir)) {
2671
+ console.error(`Directory already exists: ${projectDir}`);
2672
+ process.exit(1);
2673
+ }
2674
+ ensureSetup();
2675
+ const withSample = !opts.empty;
2676
+ const sampleFile = `functions/${SAMPLE_FUNCTION.name}.${lang}`;
2677
+ scaffoldProject({
2678
+ projectDir,
2679
+ name: projectName,
2680
+ lang,
2681
+ functions: withSample ? { [SAMPLE_FUNCTION.name]: `${sampleFile}:${SAMPLE_FUNCTION.entryExport}` } : {}
2682
+ });
2683
+ if (withSample) {
2684
+ writeFileSync4(join4(projectDir, sampleFile), lang === "ts" ? HELLO_TS : HELLO_JS, "utf-8");
2685
+ }
2686
+ console.log(`
2687
+ Created ${projectName}/`);
2688
+ console.log("Installing dependencies...");
2689
+ try {
2690
+ resolvePackageManager(projectDir).runInstall(projectDir);
2691
+ } catch (err) {
2692
+ console.error(err instanceof Error ? err.message : String(err));
2693
+ process.exit(1);
2694
+ }
2695
+ console.log(`
2696
+ Ready. Next steps:`);
2697
+ console.log(` cd ${projectName}`);
2698
+ if (withSample) {
2699
+ console.log(` uip functions serve`);
2700
+ } else {
2701
+ console.log(` # Add your function entry points to ${projectName}/functions/`);
2702
+ console.log(` uip functions serve`);
2703
+ }
2704
+ });
2705
+ }
2706
+ var SERVER_RUNNER_DIR = ".uipath/server-runner";
2707
+ var DESIGN_TIME_ENV = "DESIGN_TIME";
2708
+ var RUNTIME_VERSION = "^0.9.0";
2709
+ var TSX_VERSION = "^4.0.0";
2710
+ var COREIPC_VERSION = "2.5.3";
2711
+ var SIGNALR_VERSION = "8.0.7";
2712
+ var TRACE_MAPPING_VERSION = "0.3.25";
2713
+ function generateAggregator(functionsMap, cwd, variant, derivedByPath = {}) {
2714
+ const lang = detectLanguage(functionsMap);
2715
+ const ext = lang === "javascript" ? "js" : "ts";
2716
+ const fileToFunctions = new Map;
2717
+ for (const [name, entry] of Object.entries(functionsMap)) {
2718
+ const file = entry.split(":")[0];
2719
+ const existing = fileToFunctions.get(file);
2720
+ if (existing) {
2721
+ existing.push(name);
2722
+ } else {
2723
+ fileToFunctions.set(file, [name]);
2724
+ }
2725
+ }
2726
+ for (const [file, names] of fileToFunctions) {
2727
+ if (names.length > 1) {
2728
+ throw new Error(`Multiple function definitions in the same file are not allowed.
2729
+ ` + `File "${file}" is used by: ${names.join(", ")}.
2730
+ ` + `Each function must be defined in its own file.`);
2731
+ }
2732
+ }
2733
+ const files = [...fileToFunctions.keys()];
2734
+ let outputFile;
2735
+ let importPrefix;
2736
+ if (variant === "serve") {
2737
+ const dbgDir = join5(cwd, SERVER_RUNNER_DIR);
2738
+ mkdirSync3(dbgDir, { recursive: true });
2739
+ outputFile = join5(dbgDir, `function-main.${ext}`);
2740
+ importPrefix = "../../";
2741
+ } else {
2742
+ outputFile = join5(cwd, `function-main.${ext}`);
2743
+ importPrefix = "./";
2744
+ }
2745
+ const imports = files.map((file, i) => `import f${i} from "${importPrefix}${file}";`).join(`
2746
+ `);
2747
+ const relevantDerived = {};
2748
+ for (const file of files) {
2749
+ const d = derivedByPath[file];
2750
+ if (!d)
2751
+ continue;
2290
2752
  const entry = {};
2291
2753
  if (d.input !== undefined)
2292
2754
  entry.input = d.input;
@@ -2319,12 +2781,12 @@ function generateAggregator(functionsMap, cwd, variant, derivedByPath = {}) {
2319
2781
 
2320
2782
  ` + `${loweringBlock}` + `export default createApp([${entries}]);
2321
2783
  `;
2322
- writeFileSync4(outputFile, content, "utf-8");
2784
+ writeFileSync5(outputFile, content, "utf-8");
2323
2785
  return outputFile;
2324
2786
  }
2325
2787
  function detectLanguage(functionsMap) {
2326
2788
  const first = Object.values(functionsMap)[0]?.split(":")[0] ?? "";
2327
- return extname(first) === ".js" ? "javascript" : "typescript";
2789
+ return extname2(first) === ".js" ? "javascript" : "typescript";
2328
2790
  }
2329
2791
  var SegmentTier = {
2330
2792
  Literal: 0,
@@ -2589,10 +3051,13 @@ var DIAGNOSTIC_CODES = {
2589
3051
  UNSUPPORTED_VALIDATOR: "unsupported-validator",
2590
3052
  UNSUPPORTED_TYPE: "unsupported-type",
2591
3053
  NON_STATIC_LITERAL: "non-static-literal",
3054
+ UNREADABLE_PROPERTY: "unreadable-property",
2592
3055
  MISSING_TYPE_ARGUMENT: "missing-type-argument",
2593
3056
  AMBIGUOUS_ROUTE: "ambiguous-route",
2594
3057
  MULTIPLE_FUNCTIONS_PER_FILE: "multiple-functions-per-file",
2595
- DEPRECATED_MARKER: "deprecated-marker"
3058
+ DEPRECATED_MARKER: "deprecated-marker",
3059
+ NO_FUNCTION_DEFINITION: "no-function-definition",
3060
+ UNRESOLVED_SOURCE_FILE: "unresolved-source-file"
2596
3061
  };
2597
3062
  function extractFunctionContracts(sourceFile, checker) {
2598
3063
  const bindings = sdkImportBindings(sourceFile);
@@ -2610,6 +3075,21 @@ function extractFunctionContracts(sourceFile, checker) {
2610
3075
  if (diagnostic)
2611
3076
  diagnostics.push({ ...diagnostic, functionName: fn.name, field });
2612
3077
  }
3078
+ const unreadable = isNestedInFunction(node) ? { fields: [], anyField: false } : unreadableProperties(arg);
3079
+ if (unreadable.anyField) {
3080
+ diagnostics.push({
3081
+ ...diag(DIAGNOSTIC_CODES.UNREADABLE_PROPERTY, "the definition spreads another object or uses a computed key, so which " + "contract fields it carries is not statically known", "warning"),
3082
+ functionName: fn.name
3083
+ });
3084
+ } else {
3085
+ for (const field of unreadable.fields) {
3086
+ diagnostics.push({
3087
+ ...diag(DIAGNOSTIC_CODES.UNREADABLE_PROPERTY, METADATA_FIELDS.has(field) ? `${field} cannot be read statically: a shorthand property, a method, an ` + `accessor and a reference to a variable all read as absent. Write it at ` + `the defineFunction call as a string literal.` : `${field} is declared as a shorthand property, a method or an accessor, ` + `which reads as absent. Write it as \`${field}: <value>\`.`, "warning"),
3088
+ functionName: fn.name,
3089
+ ...field === "input" || field === "output" ? { field } : {}
3090
+ });
3091
+ }
3092
+ }
2613
3093
  functions.push(fn);
2614
3094
  }
2615
3095
  }
@@ -2623,13 +3103,28 @@ function extractFromFiles(files, checker, limits) {
2623
3103
  const diagnostics = [];
2624
3104
  const maxPerFile = limits?.maxDefineFunctionsPerFile;
2625
3105
  for (const { functionPath, sourceFile } of files) {
2626
- if (!sourceFile)
3106
+ if (!sourceFile) {
3107
+ diagnostics.push({
3108
+ code: DIAGNOSTIC_CODES.UNRESOLVED_SOURCE_FILE,
3109
+ severity: "error",
3110
+ message: `could not be loaded — the file is missing, unreadable, or excluded from the ` + `TypeScript program.`,
3111
+ file: functionPath
3112
+ });
2627
3113
  continue;
3114
+ }
2628
3115
  const result = extractFunctionContracts(sourceFile, checker);
2629
3116
  for (const fn of result.functions)
2630
3117
  functions.push({ ...fn, functionPath });
2631
3118
  for (const d of result.diagnostics)
2632
3119
  diagnostics.push({ ...d, file: functionPath });
3120
+ if (limits?.requireFunctionPerFile && result.functions.length === 0 && !hasDefaultExport(sourceFile, checker)) {
3121
+ diagnostics.push({
3122
+ code: DIAGNOSTIC_CODES.NO_FUNCTION_DEFINITION,
3123
+ severity: "error",
3124
+ message: `no default export — an entry point must default-export its function definition.`,
3125
+ file: functionPath
3126
+ });
3127
+ }
2633
3128
  if (maxPerFile !== undefined && result.functions.length > maxPerFile) {
2634
3129
  diagnostics.push({
2635
3130
  code: DIAGNOSTIC_CODES.MULTIPLE_FUNCTIONS_PER_FILE,
@@ -2651,6 +3146,12 @@ function extractFromFiles(files, checker, limits) {
2651
3146
  return { functions, diagnostics };
2652
3147
  }
2653
3148
  var SDK_MODULE = "@uipath/coded-functions-js-sdk";
3149
+ function hasDefaultExport(sourceFile, checker) {
3150
+ const moduleSymbol = checker.getSymbolAtLocation(sourceFile);
3151
+ if (!moduleSymbol)
3152
+ return false;
3153
+ return checker.getExportsOfModule(moduleSymbol).some((s) => s.escapedName === "default");
3154
+ }
2654
3155
  var MARKER_EXPORTS = ["defineSchema", "type"];
2655
3156
  function sdkImportBindings(sourceFile) {
2656
3157
  const map = new Map;
@@ -2679,7 +3180,7 @@ function resolveField(obj, field, checker, bindings) {
2679
3180
  const prop = findProp(obj, field);
2680
3181
  if (!prop)
2681
3182
  return {};
2682
- const value = prop.initializer;
3183
+ const value = unwrap(prop.initializer);
2683
3184
  const callee = ts.isCallExpression(value) && ts.isIdentifier(value.expression) ? value.expression.text : undefined;
2684
3185
  if (ts.isCallExpression(value) && callee !== undefined && MARKER_EXPORTS.some((name) => matchesSdkExport(callee, name, bindings))) {
2685
3186
  const typeArg = value.typeArguments?.[0];
@@ -2710,15 +3211,50 @@ function resolveField(obj, field, checker, bindings) {
2710
3211
  };
2711
3212
  }
2712
3213
  function propertyName(name) {
2713
- if (ts.isIdentifier(name) || ts.isStringLiteral(name))
3214
+ if (ts.isIdentifier(name) || ts.isStringLiteral(name) || ts.isNumericLiteral(name)) {
2714
3215
  return name.text;
3216
+ }
2715
3217
  return;
2716
3218
  }
3219
+ var CONTRACT_FIELDS = new Set(["name", "method", "path", "description", "input", "output"]);
3220
+ var METADATA_FIELDS = new Set(["name", "method", "path", "description"]);
3221
+ function isNestedInFunction(node) {
3222
+ for (let current = node.parent;current && !ts.isSourceFile(current); current = current.parent) {
3223
+ if (ts.isFunctionLike(current) || ts.isClassStaticBlockDeclaration(current))
3224
+ return true;
3225
+ }
3226
+ return false;
3227
+ }
3228
+ function unreadableProperties(obj) {
3229
+ const fields = new Set;
3230
+ for (const property of obj.properties) {
3231
+ if (ts.isPropertyAssignment(property)) {
3232
+ const name2 = propertyName(property.name);
3233
+ if (name2 === undefined)
3234
+ return { fields: [], anyField: true };
3235
+ if (METADATA_FIELDS.has(name2) && !isReadableMetadataValue(property.initializer)) {
3236
+ fields.add(name2);
3237
+ }
3238
+ continue;
3239
+ }
3240
+ if (ts.isSpreadAssignment(property))
3241
+ return { fields: [], anyField: true };
3242
+ const name = property.name && propertyName(property.name);
3243
+ if (name === undefined)
3244
+ return { fields: [], anyField: true };
3245
+ if (CONTRACT_FIELDS.has(name))
3246
+ fields.add(name);
3247
+ }
3248
+ return { fields: [...fields], anyField: false };
3249
+ }
3250
+ function isReadableMetadataValue(value) {
3251
+ return ts.isStringLiteralLike(unwrap(value));
3252
+ }
2717
3253
  function findProp(obj, field) {
2718
3254
  return obj.properties.find((p) => ts.isPropertyAssignment(p) && propertyName(p.name) === field);
2719
3255
  }
2720
- function diag(code, message) {
2721
- return { code, severity: "error", message };
3256
+ function diag(code, message, severity = "error") {
3257
+ return { code, severity, message };
2722
3258
  }
2723
3259
  function readMetadata(obj) {
2724
3260
  const meta = {};
@@ -2739,26 +3275,41 @@ function readMetadata(obj) {
2739
3275
  meta.tags = tags;
2740
3276
  return meta;
2741
3277
  }
3278
+ function unwrap(value) {
3279
+ let current = value;
3280
+ while (ts.isAsExpression(current) || ts.isParenthesizedExpression(current) || ts.isSatisfiesExpression(current)) {
3281
+ current = current.expression;
3282
+ }
3283
+ return current;
3284
+ }
2742
3285
  function stringProp(obj, field) {
2743
3286
  const prop = findProp(obj, field);
2744
- return prop && ts.isStringLiteralLike(prop.initializer) ? prop.initializer.text : undefined;
3287
+ if (!prop)
3288
+ return;
3289
+ const value = unwrap(prop.initializer);
3290
+ return ts.isStringLiteralLike(value) ? value.text : undefined;
2745
3291
  }
2746
3292
  function stringArrayProp(obj, field) {
2747
3293
  const prop = findProp(obj, field);
2748
- if (!prop || !ts.isArrayLiteralExpression(prop.initializer))
3294
+ if (!prop)
3295
+ return;
3296
+ const array = unwrap(prop.initializer);
3297
+ if (!ts.isArrayLiteralExpression(array))
2749
3298
  return;
2750
3299
  const values = [];
2751
- for (const el of prop.initializer.elements) {
2752
- if (!ts.isStringLiteralLike(el))
3300
+ for (const el of array.elements) {
3301
+ const value = unwrap(el);
3302
+ if (!ts.isStringLiteralLike(value))
2753
3303
  return;
2754
- values.push(el.text);
3304
+ values.push(value.text);
2755
3305
  }
2756
3306
  return values;
2757
3307
  }
2758
3308
  function literalToSchema(node) {
2759
3309
  return foldLiteral(node);
2760
3310
  }
2761
- function foldLiteral(node) {
3311
+ function foldLiteral(expression) {
3312
+ const node = unwrap(expression);
2762
3313
  if (ts.isStringLiteralLike(node))
2763
3314
  return node.text;
2764
3315
  if (ts.isNumericLiteral(node))
@@ -2822,7 +3373,11 @@ function readCompilerOptions(cwd) {
2822
3373
  }
2823
3374
  function extractProject(functionsMap, cwd) {
2824
3375
  const files = [...new Set(Object.values(functionsMap).map((v) => v.split(":")[0]))];
2825
- return extractDisk({ cwd, files });
3376
+ return extractDisk({
3377
+ cwd,
3378
+ files,
3379
+ limits: { requireFunctionPerFile: true }
3380
+ });
2826
3381
  }
2827
3382
  function toDerivedContracts(functions) {
2828
3383
  const derived = {};
@@ -2833,9 +3388,6 @@ function toDerivedContracts(functions) {
2833
3388
  }
2834
3389
  return derived;
2835
3390
  }
2836
- function deriveMarkerContracts(functionsMap, cwd) {
2837
- return toDerivedContracts(extractProject(functionsMap, cwd).functions);
2838
- }
2839
3391
  function deriveRunContract(relFile, cwd) {
2840
3392
  const { functions } = extractDisk({ cwd, files: [relFile] });
2841
3393
  const fn = functions.find((f) => f.input !== undefined || f.output !== undefined);
@@ -2849,7 +3401,7 @@ function deriveRunContract(relFile, cwd) {
2849
3401
  return derived;
2850
3402
  }
2851
3403
  function readBakedContract(relFile, cwd) {
2852
- const doc = readJsonIfExists(join5(cwd, "entry-points.json"));
3404
+ const doc = readJsonIfExists(join6(cwd, "entry-points.json"));
2853
3405
  const entryPoints = doc?.entryPoints;
2854
3406
  if (!Array.isArray(entryPoints))
2855
3407
  return null;
@@ -2869,93 +3421,534 @@ function stripContentPrefix(p) {
2869
3421
  return s.startsWith("content/") ? s.slice("content/".length) : s;
2870
3422
  }
2871
3423
  function readJsonIfExists(path3) {
2872
- if (!existsSync3(path3))
3424
+ if (!existsSync4(path3))
2873
3425
  return null;
2874
3426
  try {
2875
- return JSON.parse(readFileSync2(path3, "utf-8"));
3427
+ return JSON.parse(readFileSync3(path3, "utf-8"));
2876
3428
  } catch {
2877
3429
  return null;
2878
3430
  }
2879
3431
  }
2880
- function setupRunDependencies(cwd, serverRunnerTemplatePath = "") {
2881
- const serverRunnerDir = join6(cwd, SERVER_RUNNER_DIR);
2882
- mkdirSync4(serverRunnerDir, { recursive: true });
2883
- if (serverRunnerTemplatePath !== "" && existsSync4(serverRunnerTemplatePath)) {
2884
- console.log("Copying server-runner ...");
2885
- for (const entry of readdirSync(serverRunnerTemplatePath)) {
2886
- cpSync(join6(serverRunnerTemplatePath, entry), join6(serverRunnerDir, entry), { recursive: true });
3432
+ var SDK_VERSION2 = "0.6.2";
3433
+ var SDK_RANGE2 = `^${SDK_VERSION2}`;
3434
+ var SDK_PACKAGE_NAME2 = "@uipath/coded-functions-js-sdk";
3435
+ var SAMPLE_FUNCTION2 = {
3436
+ name: "hello",
3437
+ description: "Returns a greeting message.",
3438
+ method: "POST",
3439
+ path: "/hello",
3440
+ entryExport: "default"
3441
+ };
3442
+ var httpSemantics2 = ` method: "${SAMPLE_FUNCTION2.method}",
3443
+ path: "${SAMPLE_FUNCTION2.path}",
3444
+ `;
3445
+ var semanticsFor2 = (variant) => variant === "http" ? httpSemantics2 : "";
3446
+ var buildHelloTs2 = (variant) => `import { defineFunction, defineSchema, type FunctionContext } from "@uipath/coded-functions-js-sdk";
3447
+
3448
+ interface HelloInput {
3449
+ /**
3450
+ * Name to greet — filled in by the runtime when omitted.
3451
+ * @default "World"
3452
+ */
3453
+ name?: string;
3454
+ }
3455
+
3456
+ interface HelloOutput {
3457
+ message: string;
3458
+ }
3459
+
3460
+ function main(input: HelloInput, ctx: FunctionContext): HelloOutput {
3461
+ const output: HelloOutput = {
3462
+ message: \`Hello, \${input.name}!\`,
3463
+ };
3464
+ return output;
3465
+ }
3466
+
3467
+ export default defineFunction({
3468
+ name: "${SAMPLE_FUNCTION2.name}",
3469
+ description: "${SAMPLE_FUNCTION2.description}",
3470
+ ${semanticsFor2(variant)} input: defineSchema<HelloInput>(),
3471
+ output: defineSchema<HelloOutput>(),
3472
+ handler: main,
3473
+ });
3474
+ `;
3475
+ var buildHelloJs2 = (variant) => `// @ts-check
3476
+ import { defineFunction } from "@uipath/coded-functions-js-sdk";
3477
+
3478
+ export default defineFunction({
3479
+ name: "${SAMPLE_FUNCTION2.name}",
3480
+ description: "${SAMPLE_FUNCTION2.description}",
3481
+ ${semanticsFor2(variant)} input: {
3482
+ type: "object",
3483
+ properties: {
3484
+ name: { type: "string", default: "World" },
3485
+ },
3486
+ additionalProperties: false,
3487
+ },
3488
+ output: {
3489
+ type: "object",
3490
+ properties: {
3491
+ message: { type: "string" },
3492
+ },
3493
+ required: ["message"],
3494
+ additionalProperties: false,
3495
+ },
3496
+ handler: async (input, ctx) => ({
3497
+ message: \`Hello, \${input.name}!\`,
3498
+ }),
3499
+ });
3500
+ `;
3501
+ var HELLO_TS2 = buildHelloTs2("http");
3502
+ var HELLO_TS_JOB2 = buildHelloTs2("job");
3503
+ var HELLO_JS2 = buildHelloJs2("http");
3504
+ var HELLO_JS_JOB2 = buildHelloJs2("job");
3505
+ var SAMPLE_TSCONFIG2 = JSON.stringify({
3506
+ compilerOptions: {
3507
+ target: "ESNext",
3508
+ module: "ESNext",
3509
+ moduleResolution: "bundler",
3510
+ strict: true,
3511
+ allowImportingTsExtensions: true,
3512
+ noEmit: true
3513
+ },
3514
+ include: ["**/*.ts"],
3515
+ exclude: ["node_modules", "dist"]
3516
+ }, null, 2) + `
3517
+ `;
3518
+ var SAMPLE_LOCK_PACKAGES2 = {
3519
+ "node_modules/@babel/runtime": {
3520
+ version: "7.29.7",
3521
+ resolved: "https://registry.npmjs.org/@babel/runtime/-/runtime-7.29.7.tgz",
3522
+ integrity: "sha512-Nq8OhGWiZIZGV6hLHoyAKLLcJihP/xFeBMGJoUrxTX2psI8dCifzLhZISFb+VWS3wFMRDmCGw5R+dOySCqPLhw==",
3523
+ dev: true,
3524
+ license: "MIT",
3525
+ engines: { node: ">=6.9.0" }
3526
+ },
3527
+ "node_modules/@standard-schema/spec": {
3528
+ version: "1.1.0",
3529
+ resolved: "https://registry.npmjs.org/@standard-schema/spec/-/spec-1.1.0.tgz",
3530
+ integrity: "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==",
3531
+ dev: true,
3532
+ license: "MIT"
3533
+ },
3534
+ [`node_modules/${SDK_PACKAGE_NAME2}`]: {
3535
+ version: SDK_VERSION2,
3536
+ dev: true,
3537
+ dependencies: {
3538
+ "@standard-schema/spec": "^1.1.0",
3539
+ "json-schema-to-ts": "^3.1.1"
2887
3540
  }
2888
- console.log("server-runner copied in " + serverRunnerDir + ".");
2889
- } else {
2890
- let runtimeVersion = "no-version";
2891
- let honoVersion = "no-version";
2892
- let tsxVersion = "no-version";
2893
- const pkgJson = JSON.parse(readFileSync3(join6(cwd, "package.json"), "utf-8"));
2894
- try {
2895
- const allDeps = { ...pkgJson.dependencies ?? {}, ...pkgJson.devDependencies ?? {} };
2896
- runtimeVersion = allDeps["@uipath/coded-functions-js-runtime"] ?? RUNTIME_VERSION;
2897
- honoVersion = allDeps["@hono/node-server"] ?? HONO_NODE_VERSION;
2898
- tsxVersion = allDeps["tsx"] ?? TSX_VERSION;
2899
- } catch {}
2900
- pkgJson.dependencies = {
2901
- "@uipath/coded-functions-js-runtime": runtimeVersion,
2902
- "@uipath/coreipc": COREIPC_VERSION,
2903
- "@hono/node-server": HONO_NODE_VERSION,
2904
- tsx: tsxVersion,
2905
- "@microsoft/signalr": SIGNALR_VERSION,
2906
- "@jridgewell/trace-mapping": TRACE_MAPPING_VERSION
3541
+ },
3542
+ "node_modules/json-schema-to-ts": {
3543
+ version: "3.1.1",
3544
+ resolved: "https://registry.npmjs.org/json-schema-to-ts/-/json-schema-to-ts-3.1.1.tgz",
3545
+ integrity: "sha512-+DWg8jCJG2TEnpy7kOm/7/AxaYoaRbjVB4LFZLySZlWn8exGs3A4OLJR966cVvU26N7X9TWxl+Jsw7dzAqKT6g==",
3546
+ dev: true,
3547
+ license: "MIT",
3548
+ dependencies: {
3549
+ "@babel/runtime": "^7.18.3",
3550
+ "ts-algebra": "^2.0.0"
3551
+ },
3552
+ engines: { node: ">=16" }
3553
+ },
3554
+ "node_modules/ts-algebra": {
3555
+ version: "2.0.0",
3556
+ resolved: "https://registry.npmjs.org/ts-algebra/-/ts-algebra-2.0.0.tgz",
3557
+ integrity: "sha512-FPAhNPFMrkwz76P7cdjdmiShwMynZYN6SgOujD1urY4oNm80Ou9oMdmbR45LotcKOXoy7wSmHkRFE6Mxbrhefw==",
3558
+ dev: true,
3559
+ license: "MIT"
3560
+ },
3561
+ "node_modules/typescript": {
3562
+ version: "5.9.3",
3563
+ resolved: "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz",
3564
+ integrity: "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==",
3565
+ dev: true,
3566
+ license: "Apache-2.0",
3567
+ bin: { tsc: "bin/tsc", tsserver: "bin/tsserver" },
3568
+ engines: { node: ">=14.17" }
3569
+ }
3570
+ };
3571
+ var CONSUMER_COMPILER_OPTIONS2 = {
3572
+ target: ts3.ScriptTarget.ES2020,
3573
+ module: ts3.ModuleKind.ESNext,
3574
+ moduleResolution: ts3.ModuleResolutionKind.Bundler,
3575
+ allowImportingTsExtensions: true,
3576
+ allowJs: true,
3577
+ strict: true,
3578
+ skipLibCheck: true,
3579
+ noEmit: true
3580
+ };
3581
+ var DIAGNOSTIC_CODES2 = {
3582
+ UNSUPPORTED_VALIDATOR: "unsupported-validator",
3583
+ UNSUPPORTED_TYPE: "unsupported-type",
3584
+ NON_STATIC_LITERAL: "non-static-literal",
3585
+ UNREADABLE_PROPERTY: "unreadable-property",
3586
+ MISSING_TYPE_ARGUMENT: "missing-type-argument",
3587
+ AMBIGUOUS_ROUTE: "ambiguous-route",
3588
+ MULTIPLE_FUNCTIONS_PER_FILE: "multiple-functions-per-file",
3589
+ DEPRECATED_MARKER: "deprecated-marker",
3590
+ NO_FUNCTION_DEFINITION: "no-function-definition",
3591
+ UNRESOLVED_SOURCE_FILE: "unresolved-source-file"
3592
+ };
3593
+ var CONTRACT_FIELDS2 = new Set(["name", "method", "path", "description", "input", "output"]);
3594
+ var METADATA_FIELDS2 = new Set(["name", "method", "path", "description"]);
3595
+ var JOB_ATTACHMENT_REF = "#/definitions/job-attachment";
3596
+ var JOB_ATTACHMENT_DEFINITION_KEY = "job-attachment";
3597
+ var JOB_ATTACHMENT_DEFINITION = {
3598
+ type: "object",
3599
+ required: ["ID"],
3600
+ "x-uipath-resource-kind": "JobAttachment",
3601
+ properties: {
3602
+ ID: { type: "string", description: "Orchestrator attachment key" },
3603
+ FullName: { type: "string", description: "File name" },
3604
+ MimeType: {
3605
+ type: "string",
3606
+ description: 'The MIME type of the content, such as "application/json" or "image/png"'
3607
+ },
3608
+ Metadata: {
3609
+ type: "object",
3610
+ description: "Dictionary<string, string> of metadata",
3611
+ additionalProperties: { type: "string" }
3612
+ }
3613
+ }
3614
+ };
3615
+ var ANNOTATION_KEYS = ["title", "description", "default"];
3616
+ var STRUCTURAL_KEYS = new Set(["type", "properties", "required", "additionalProperties"]);
3617
+ var STRING_PROPERTIES = ["ID", "FullName", "MimeType"];
3618
+ function stripAnnotations(node) {
3619
+ const out = { ...node };
3620
+ for (const key of ANNOTATION_KEYS)
3621
+ delete out[key];
3622
+ return out;
3623
+ }
3624
+ function isPlainString(node) {
3625
+ if (!node)
3626
+ return false;
3627
+ const shape = stripAnnotations(node);
3628
+ return Object.keys(shape).length === 1 && shape.type === "string";
3629
+ }
3630
+ function isOpenObject(node) {
3631
+ if (!node)
3632
+ return false;
3633
+ const shape = stripAnnotations(node);
3634
+ if (shape.type !== "object")
3635
+ return false;
3636
+ return Object.keys(shape).every((key) => key === "type" || key === "additionalProperties");
3637
+ }
3638
+ function matchesJobAttachment(node) {
3639
+ if (node.type !== "object")
3640
+ return false;
3641
+ if (node.additionalProperties !== false && node.additionalProperties !== undefined)
3642
+ return false;
3643
+ for (const key of Object.keys(node)) {
3644
+ if (!STRUCTURAL_KEYS.has(key) && !ANNOTATION_KEYS.includes(key))
3645
+ return false;
3646
+ }
3647
+ const props = node.properties;
3648
+ if (!props)
3649
+ return false;
3650
+ if (Object.keys(props).length !== ("Metadata" in props ? 4 : 3))
3651
+ return false;
3652
+ if (!STRING_PROPERTIES.every((p) => isPlainString(props[p])))
3653
+ return false;
3654
+ if ("Metadata" in props && !isOpenObject(props.Metadata))
3655
+ return false;
3656
+ const required = node.required ?? [];
3657
+ return required.includes("ID") && required.every((p) => STRING_PROPERTIES.includes(p));
3658
+ }
3659
+ function rewrite(node) {
3660
+ if (matchesJobAttachment(node)) {
3661
+ const ref = {};
3662
+ for (const key of ANNOTATION_KEYS) {
3663
+ if (key in node)
3664
+ ref[key] = node[key];
3665
+ }
3666
+ ref.$ref = JOB_ATTACHMENT_REF;
3667
+ return { node: ref, found: true };
3668
+ }
3669
+ let found = false;
3670
+ const out = { ...node };
3671
+ if (node.properties) {
3672
+ const properties = {};
3673
+ for (const [key, value] of Object.entries(node.properties)) {
3674
+ const result = rewrite(value);
3675
+ properties[key] = result.node;
3676
+ found = found || result.found;
3677
+ }
3678
+ out.properties = properties;
3679
+ }
3680
+ if (node.items) {
3681
+ const result = rewrite(node.items);
3682
+ out.items = result.node;
3683
+ found = found || result.found;
3684
+ }
3685
+ if (typeof node.additionalProperties === "object") {
3686
+ const result = rewrite(node.additionalProperties);
3687
+ out.additionalProperties = result.node;
3688
+ found = found || result.found;
3689
+ }
3690
+ for (const key of ["anyOf", "oneOf", "allOf"]) {
3691
+ const members = node[key];
3692
+ if (members) {
3693
+ const results = members.map(rewrite);
3694
+ out[key] = results.map((r) => r.node);
3695
+ found = found || results.some((r) => r.found);
3696
+ }
3697
+ }
3698
+ return { node: out, found };
3699
+ }
3700
+ function transformAttachments(schema) {
3701
+ const { node, found } = rewrite(schema);
3702
+ if (found)
3703
+ node.definitions = { [JOB_ATTACHMENT_DEFINITION_KEY]: JOB_ATTACHMENT_DEFINITION };
3704
+ return node;
3705
+ }
3706
+ function newId() {
3707
+ return globalThis.crypto.randomUUID();
3708
+ }
3709
+ function buildEntryPointsDoc(functions, existing, filePathPrefix = "content/") {
3710
+ const functionIds = new Map;
3711
+ const transactionRoots = new Set;
3712
+ const preserved = [];
3713
+ for (const ep of existing?.entryPoints ?? []) {
3714
+ if (ep.type === "function") {
3715
+ functionIds.set(ep.filePath, ep.uniqueId);
3716
+ if (ep.isTransactionRoot === true) {
3717
+ transactionRoots.add(ep.filePath);
3718
+ }
3719
+ } else {
3720
+ preserved.push(ep);
3721
+ }
3722
+ }
3723
+ const functionEntries = functions.map((fn) => {
3724
+ const filePath = filePathPrefix + (fn.functionPath ?? "");
3725
+ return {
3726
+ filePath,
3727
+ uniqueId: functionIds.get(filePath) ?? newId(),
3728
+ type: "function",
3729
+ input: transformAttachments(fn.input ?? { type: "object" }),
3730
+ output: transformAttachments(fn.output ?? { type: "object" }),
3731
+ ...transactionRoots.has(filePath) ? { isTransactionRoot: true } : {}
2907
3732
  };
2908
- writeFileSync5(join6(serverRunnerDir, "package.json"), JSON.stringify(pkgJson, null, 2), "utf-8");
2909
- const npmrc = join6(cwd, ".npmrc");
2910
- if (existsSync4(npmrc)) {
2911
- copyFileSync(npmrc, join6(serverRunnerDir, ".npmrc"));
2912
- }
2913
- console.log("Installing runtime dependencies ...");
2914
- const install = getInstallCommand(false, ["--prefer-offline"]);
2915
- const result = spawnSync3(install.cmd, install.args, {
2916
- cwd: serverRunnerDir,
2917
- stdio: "inherit",
2918
- shell: process.platform === "win32"
2919
- });
2920
- if (result.status !== 0) {
2921
- throw new Error("Failed to install .uipath/server-runner/ dependencies.");
3733
+ });
3734
+ return {
3735
+ $schema: "https://cloud.uipath.com/draft/2024-12/entry-point",
3736
+ $id: "entry-points.json",
3737
+ entryPoints: [...preserved, ...functionEntries]
3738
+ };
3739
+ }
3740
+ function buildBindingsDoc(functions, entryPointIdByPath, existingBindings, filePathPrefix = "content/") {
3741
+ const httpExisting = new Map;
3742
+ const preserved = [];
3743
+ for (const r of existingBindings?.resources ?? []) {
3744
+ if (r.resource === "HttpTrigger") {
3745
+ const meta = r.metadata;
3746
+ if (meta?.Method && meta?.Slug) {
3747
+ httpExisting.set(`${meta.Method}:${meta.Slug}`, { key: r.key, id: r.id });
3748
+ }
2922
3749
  } else {
2923
- console.log("Runtime dependencies installed.");
3750
+ preserved.push(r);
2924
3751
  }
2925
3752
  }
2926
- if (!existsSync4(join6(cwd, "node_modules"))) {
2927
- console.log("Preparing node_modules in package working folder.");
2928
- let packagesToCopy = ["@uipath/coded-functions-js-sdk"];
2929
- for (let i = 0;i < packagesToCopy.length; i++) {
2930
- const packageName = packagesToCopy[i];
2931
- mkdirSync4(join6(cwd, "node_modules", packageName), { recursive: true });
2932
- for (const entry of readdirSync(join6(serverRunnerDir, "node_modules", packageName))) {
2933
- cpSync(join6(serverRunnerDir, "node_modules", packageName, entry), join6(cwd, "node_modules", packageName, entry), { recursive: true });
3753
+ const httpTriggers = functions.filter((fn) => fn.method && fn.path).map((fn) => {
3754
+ const existing = httpExisting.get(`${fn.method}:${fn.path}`);
3755
+ const bindingKey = existing?.key ?? newId();
3756
+ const bindingId = existing?.id ?? newId();
3757
+ const entryPointUniqueId = entryPointIdByPath.get(filePathPrefix + (fn.functionPath ?? ""));
3758
+ if (!entryPointUniqueId) {
3759
+ throw new Error(`Internal error: binding for "${fn.method} ${fn.path}" references entry point "${filePathPrefix}${fn.functionPath}", which is missing from entry-points.json.`);
3760
+ }
3761
+ return {
3762
+ resource: "HttpTrigger",
3763
+ key: bindingKey,
3764
+ id: bindingId,
3765
+ value: {
3766
+ EntryPointUniqueId: {
3767
+ DefaultValue: entryPointUniqueId,
3768
+ IsExpression: false
3769
+ }
3770
+ },
3771
+ metadata: {
3772
+ BindingsVersion: "2.1",
3773
+ Name: fn.name ?? "",
3774
+ Method: fn.method,
3775
+ Slug: fn.path,
3776
+ CallingMode: "LongPolling",
3777
+ Description: fn.description ?? ""
2934
3778
  }
3779
+ };
3780
+ });
3781
+ return {
3782
+ $schema: "https://cloud.uipath.com/draft/2024-12/bindings",
3783
+ version: "2.0",
3784
+ resources: [...preserved, ...httpTriggers]
3785
+ };
3786
+ }
3787
+ var BLOCKING_CODES = new Set([
3788
+ DIAGNOSTIC_CODES2.NO_FUNCTION_DEFINITION,
3789
+ DIAGNOSTIC_CODES2.UNRESOLVED_SOURCE_FILE
3790
+ ]);
3791
+ var SILENT_CODES = new Set([DIAGNOSTIC_CODES2.UNSUPPORTED_VALIDATOR]);
3792
+ function isSilentSchemaSignal(d) {
3793
+ return d.code === DIAGNOSTIC_CODES2.UNREADABLE_PROPERTY && d.field !== undefined;
3794
+ }
3795
+ var REMEDIATION = {
3796
+ [DIAGNOSTIC_CODES2.NO_FUNCTION_DEFINITION]: (d) => `Every file in functions/ is served as a function. If this file is a helper, move it out ` + `of functions/ or rename it to ${underscored(d.file)} so discovery skips it.`,
3797
+ [DIAGNOSTIC_CODES2.UNRESOLVED_SOURCE_FILE]: () => `Check the path exists and that tsconfig.json does not exclude it.`
3798
+ };
3799
+ function reportDiagnostics(diagnostics) {
3800
+ const blocking = diagnostics.filter((d) => BLOCKING_CODES.has(d.code));
3801
+ const rest = diagnostics.filter((d) => !BLOCKING_CODES.has(d.code) && !SILENT_CODES.has(d.code) && !isSilentSchemaSignal(d));
3802
+ for (const d of blocking)
3803
+ console.error(` Error: ${format(d)}`);
3804
+ for (const d of rest)
3805
+ console.warn(` Warning: ${format(d)}`);
3806
+ return blocking.length;
3807
+ }
3808
+ function reportDiagnosticsOrExit(diagnostics) {
3809
+ const blocking = reportDiagnostics(diagnostics);
3810
+ if (blocking === 0)
3811
+ return;
3812
+ console.error(`
3813
+ ${blocking} error(s) in the project's function files — nothing was written. ` + `Fix them and re-run.`);
3814
+ process.exit(1);
3815
+ }
3816
+ function format(d) {
3817
+ const where = [d.functionName, d.field].filter(Boolean).join(".");
3818
+ const location = [d.file, where ? `(${where})` : ""].filter(Boolean).join(" ");
3819
+ const hint = REMEDIATION[d.code]?.(d);
3820
+ return [location ? `${location}: ` : "", d.message, hint ? ` ${hint}` : ""].join("");
3821
+ }
3822
+ function underscored(file) {
3823
+ if (!file)
3824
+ return "_<name>.ts";
3825
+ const dir = dirname2(file);
3826
+ const renamed = `_${basename2(file)}`;
3827
+ return dir === "." ? renamed : `${dir}/${renamed}`;
3828
+ }
3829
+ function installServerRunner(cwd, serverRunnerTemplatePath = "", packageManager) {
3830
+ const serverRunnerDir = join7(cwd, SERVER_RUNNER_DIR);
3831
+ mkdirSync4(serverRunnerDir, { recursive: true });
3832
+ if (serverRunnerTemplatePath !== "" && existsSync5(serverRunnerTemplatePath)) {
3833
+ console.log("Copying server-runner ...");
3834
+ for (const entry of readdirSync(serverRunnerTemplatePath)) {
3835
+ cpSync(join7(serverRunnerTemplatePath, entry), join7(serverRunnerDir, entry), { recursive: true });
2935
3836
  }
2936
- console.log("Installing dependencies in package working folder.");
2937
- const install = getInstallCommand(true, ["--prefer-offline"]);
2938
- const result = spawnSync3(install.cmd, install.args, {
2939
- cwd,
2940
- stdio: "inherit",
2941
- shell: process.platform === "win32"
2942
- });
2943
- if (result.status !== 0) {
2944
- throw new Error("Failed to install package working folder dependencies.");
2945
- } else {
2946
- console.log("Package working folder dependencies installed.");
3837
+ console.log("server-runner copied in " + serverRunnerDir + ".");
3838
+ return;
3839
+ }
3840
+ const pkgJson = JSON.parse(readFileSync4(join7(cwd, "package.json"), "utf-8"));
3841
+ pkgJson.dependencies = buildRunnerDependencies(cwd);
3842
+ writeFileSync6(join7(serverRunnerDir, "package.json"), JSON.stringify(pkgJson, null, 2), "utf-8");
3843
+ console.log("Installing runtime dependencies ...");
3844
+ resolvePackageManager(cwd, packageManager).runInstall(serverRunnerDir, { preferOffline: true });
3845
+ console.log("Runtime dependencies installed.");
3846
+ }
3847
+ function declaresProductionDependency(cwd, packageName) {
3848
+ let parsed;
3849
+ try {
3850
+ parsed = JSON.parse(readFileSync4(join7(cwd, "package.json"), "utf-8"));
3851
+ } catch {
3852
+ return false;
3853
+ }
3854
+ if (typeof parsed !== "object" || parsed === null || !("dependencies" in parsed)) {
3855
+ return false;
3856
+ }
3857
+ const { dependencies } = parsed;
3858
+ if (typeof dependencies !== "object" || dependencies === null) {
3859
+ return false;
3860
+ }
3861
+ return Object.hasOwn(dependencies, packageName);
3862
+ }
3863
+ function installProjectProductionDependencies(cwd, manager = resolvePackageManager(cwd)) {
3864
+ const serverRunnerDir = join7(cwd, SERVER_RUNNER_DIR);
3865
+ console.log("Installing dependencies in package working folder.");
3866
+ manager.runInstall(cwd, { production: true, preferOffline: true });
3867
+ console.log("Preparing node_modules in package working folder.");
3868
+ const packagesToCopy = ["@uipath/coded-functions-js-sdk"];
3869
+ for (const packageName of packagesToCopy) {
3870
+ if (declaresProductionDependency(cwd, packageName)) {
3871
+ continue;
2947
3872
  }
3873
+ mkdirSync4(join7(cwd, "node_modules", packageName), { recursive: true });
3874
+ for (const entry of readdirSync(join7(serverRunnerDir, "node_modules", packageName))) {
3875
+ cpSync(join7(serverRunnerDir, "node_modules", packageName, entry), join7(cwd, "node_modules", packageName, entry), { recursive: true });
3876
+ }
3877
+ }
3878
+ console.log("Package working folder dependencies installed.");
3879
+ }
3880
+ function provisionPackage(cwd, serverRunnerTemplatePath = "", packageManager) {
3881
+ installServerRunner(cwd, serverRunnerTemplatePath, packageManager);
3882
+ if (!existsSync5(join7(cwd, "node_modules"))) {
3883
+ installProjectProductionDependencies(cwd, resolvePackageManager(cwd, packageManager));
2948
3884
  }
2949
3885
  }
3886
+ function buildRunnerDependencies(cwd) {
3887
+ let runtimeVersion = RUNTIME_VERSION;
3888
+ let tsxVersion = TSX_VERSION;
3889
+ try {
3890
+ const pkgJson = JSON.parse(readFileSync4(join7(cwd, "package.json"), "utf-8"));
3891
+ const allDeps = { ...pkgJson.dependencies ?? {}, ...pkgJson.devDependencies ?? {} };
3892
+ runtimeVersion = allDeps["@uipath/coded-functions-js-runtime"] ?? RUNTIME_VERSION;
3893
+ tsxVersion = allDeps["tsx"] ?? TSX_VERSION;
3894
+ } catch {}
3895
+ return {
3896
+ "@uipath/coded-functions-js-runtime": runtimeVersion,
3897
+ "@uipath/coreipc": COREIPC_VERSION,
3898
+ tsx: tsxVersion,
3899
+ "@microsoft/signalr": SIGNALR_VERSION,
3900
+ "@jridgewell/trace-mapping": TRACE_MAPPING_VERSION
3901
+ };
3902
+ }
2950
3903
  function resolveTsx(cwd) {
2951
- const dbgPkg = join6(cwd, SERVER_RUNNER_DIR, "package.json");
3904
+ const dbgPkg = join7(cwd, SERVER_RUNNER_DIR, "package.json");
2952
3905
  try {
2953
3906
  const tsxPath = createRequire2(dbgPkg).resolve("tsx/cli");
2954
3907
  return ["node", [tsxPath]];
2955
3908
  } catch {
2956
- return ["npx", ["--yes", "tsx"]];
3909
+ throw new Error(`tsx not found in ${SERVER_RUNNER_DIR}. Run 'uipath-functions install-server' and retry.`);
3910
+ }
3911
+ }
3912
+ function resolveTsxLoader(cwd) {
3913
+ const dbgPkg = join7(cwd, SERVER_RUNNER_DIR, "package.json");
3914
+ try {
3915
+ return ["--import", pathToFileURL(createRequire2(dbgPkg).resolve("tsx")).href];
3916
+ } catch {
3917
+ return;
3918
+ }
3919
+ }
3920
+ function resolveDeno() {
3921
+ return process.env.DENO_BINARY ?? (process.platform === "win32" ? "deno.exe" : "deno");
3922
+ }
3923
+ var denoOnPath;
3924
+ function denoAvailable() {
3925
+ denoOnPath ??= spawnSync2(resolveDeno(), ["--version"], {
3926
+ stdio: "ignore",
3927
+ shell: process.platform === "win32"
3928
+ }).status === 0;
3929
+ return denoOnPath;
3930
+ }
3931
+
3932
+ class ProjectNotInstalledError extends Error {
3933
+ constructor(problem, remedyCommand, cwd) {
3934
+ super(remedyCommand !== null ? `${problem}
3935
+ Run '${remedyCommand}' in ${cwd}, then retry.` : `${problem}
3936
+ Then retry in ${cwd}.`);
3937
+ this.name = "ProjectNotInstalledError";
2957
3938
  }
2958
3939
  }
3940
+ function assert(check, cwd) {
3941
+ if (!check.ready) {
3942
+ throw new ProjectNotInstalledError(check.problem ?? "Project is not installed.", check.remedyCommand, cwd);
3943
+ }
3944
+ }
3945
+ function assertDependenciesInstalled(cwd) {
3946
+ assert(checkDependenciesInstalled(cwd), cwd);
3947
+ }
3948
+ function assertReadyToPackage(cwd) {
3949
+ assert(checkDependenciesInstalled(cwd), cwd);
3950
+ assert(checkLockCurrent(cwd), cwd);
3951
+ }
2959
3952
  function freePort(port) {
2960
3953
  try {
2961
3954
  let pid = null;
@@ -3058,17 +4051,17 @@ var SIGNAL_READY_DENO = `async function signalReady() {
3058
4051
  var FUNCTIONS_DIR = "functions";
3059
4052
  var SUPPORTED_EXTS = new Set([".ts", ".js"]);
3060
4053
  function syncFunctionsMap(cwd) {
3061
- const uipathJsonPath = join7(cwd, "uipath.json");
3062
- const functionsDir = join7(cwd, FUNCTIONS_DIR);
3063
- if (!existsSync5(uipathJsonPath) || !existsSync5(functionsDir))
4054
+ const uipathJsonPath = join8(cwd, "uipath.json");
4055
+ const functionsDir = join8(cwd, FUNCTIONS_DIR);
4056
+ if (!existsSync6(uipathJsonPath) || !existsSync6(functionsDir))
3064
4057
  return false;
3065
4058
  const discovered = discoverFunctions(functionsDir);
3066
- const uipathJson = JSON.parse(readFileSync4(uipathJsonPath, "utf-8"));
4059
+ const uipathJson = JSON.parse(readFileSync5(uipathJsonPath, "utf-8"));
3067
4060
  const existing = uipathJson.functions ?? {};
3068
4061
  if (mapsEqual(existing, discovered))
3069
4062
  return false;
3070
4063
  uipathJson.functions = Object.fromEntries(Object.keys(discovered).sort().map((k) => [k, discovered[k]]));
3071
- writeFileSync6(uipathJsonPath, JSON.stringify(uipathJson, null, 2) + `
4064
+ writeFileSync7(uipathJsonPath, JSON.stringify(uipathJson, null, 2) + `
3072
4065
  `, "utf-8");
3073
4066
  return true;
3074
4067
  }
@@ -3077,7 +4070,7 @@ function discoverFunctions(functionsDir) {
3077
4070
  for (const entry of readdirSync2(functionsDir, { withFileTypes: true })) {
3078
4071
  if (!isFunctionFile(entry))
3079
4072
  continue;
3080
- const ext = extname2(entry.name);
4073
+ const ext = extname3(entry.name);
3081
4074
  const key = entry.name.slice(0, -ext.length);
3082
4075
  discovered[key] = `${FUNCTIONS_DIR}/${entry.name}:default`;
3083
4076
  }
@@ -3087,7 +4080,7 @@ function isFunctionFile(entry) {
3087
4080
  if (!entry.isFile() || entry.name.startsWith("_") || entry.name.endsWith(".d.ts")) {
3088
4081
  return false;
3089
4082
  }
3090
- return SUPPORTED_EXTS.has(extname2(entry.name));
4083
+ return SUPPORTED_EXTS.has(extname3(entry.name));
3091
4084
  }
3092
4085
  function mapsEqual(a, b) {
3093
4086
  const ak = Object.keys(a);
@@ -3098,29 +4091,40 @@ function registerServeCommand(program2) {
3098
4091
  program2.command("serve").description("Start local function server with hot reload.").option("--runtime <runtime>", "Runtime: node (default) or deno", "node").option("--port <port>", "Port to listen on", String(DEFAULT_PORT)).option("--production", "Run under production context and skip .uipath/server-runner install if already exists; also skip freePort check.").action(async (opts) => {
3099
4092
  const cwd = resolve3(".");
3100
4093
  const port = parseInt(opts.port, 10) || DEFAULT_PORT;
3101
- const uipathJsonPath = join8(cwd, "uipath.json");
3102
- if (!existsSync6(uipathJsonPath)) {
4094
+ const uipathJsonPath = join9(cwd, "uipath.json");
4095
+ if (!existsSync7(uipathJsonPath)) {
3103
4096
  console.error("No uipath.json found. Run 'uipath-functions init' first.");
3104
4097
  process.exit(1);
3105
4098
  }
3106
4099
  if (syncFunctionsMap(cwd)) {
3107
4100
  console.log("Updated functions map in uipath.json.");
3108
4101
  }
3109
- const uipathJson = JSON.parse(readFileSync5(uipathJsonPath, "utf-8"));
4102
+ const uipathJson = JSON.parse(readFileSync6(uipathJsonPath, "utf-8"));
3110
4103
  if (!uipathJson.functions || Object.keys(uipathJson.functions).length === 0) {
3111
4104
  console.error("No functions defined in uipath.json. Add at least one function.");
3112
4105
  process.exit(1);
3113
4106
  }
3114
- const skipInstall = opts.production === true && existsSync6(join8(cwd, SERVER_RUNNER_DIR));
4107
+ if (opts.production !== true) {
4108
+ try {
4109
+ assertDependenciesInstalled(cwd);
4110
+ } catch (err) {
4111
+ console.error(err instanceof Error ? err.message : String(err));
4112
+ process.exit(1);
4113
+ }
4114
+ }
4115
+ const extraction = extractProject(uipathJson.functions, cwd);
4116
+ if (opts.production !== true)
4117
+ reportDiagnosticsOrExit(extraction.diagnostics);
4118
+ const skipInstall = opts.production === true && existsSync7(join9(cwd, SERVER_RUNNER_DIR));
3115
4119
  if (!skipInstall) {
3116
4120
  try {
3117
- setupRunDependencies(cwd);
4121
+ installServerRunner(cwd);
3118
4122
  } catch (err) {
3119
4123
  console.error(err instanceof Error ? err.message : String(err));
3120
4124
  process.exit(1);
3121
4125
  }
3122
4126
  }
3123
- const derived = deriveMarkerContracts(uipathJson.functions, cwd);
4127
+ const derived = toDerivedContracts(extraction.functions);
3124
4128
  const aggregatorPath = generateAggregator(uipathJson.functions, cwd, "serve", derived);
3125
4129
  if (opts.production !== true) {
3126
4130
  freePort(port);
@@ -3129,42 +4133,67 @@ function registerServeCommand(program2) {
3129
4133
  if (opts.production !== true) {
3130
4134
  process.env[DESIGN_TIME_ENV] = "1";
3131
4135
  }
4136
+ const production = opts.production === true;
3132
4137
  if (opts.runtime === "deno") {
3133
- serveDeno(cwd, port, aggregatorPath);
4138
+ serveDeno(cwd, port, aggregatorPath, production);
3134
4139
  } else {
3135
- serveNode(cwd, port, aggregatorPath);
4140
+ serveNode(cwd, port, aggregatorPath, production);
3136
4141
  }
3137
4142
  });
3138
4143
  }
3139
- function serveNode(cwd, port, aggregatorPath) {
3140
- const nodeEntryPath = join8(cwd, SERVER_RUNNER_DIR, "serve-node.ts");
3141
- const aggregatorFile = basename(aggregatorPath);
3142
- writeFileSync7(nodeEntryPath, `import { serve } from "@hono/node-server";
4144
+ function tsxServeArgs(entryPath, opts) {
4145
+ return [
4146
+ ...opts.production ? [] : ["watch"],
4147
+ ...opts.envFile ? [`--env-file=${opts.envFile}`] : [],
4148
+ entryPath
4149
+ ];
4150
+ }
4151
+ function denoServeArgs(entryPath, opts) {
4152
+ return [
4153
+ "run",
4154
+ "--allow-env",
4155
+ "--allow-net",
4156
+ "--allow-read",
4157
+ "--allow-write",
4158
+ ...opts.production ? [] : ["--watch"],
4159
+ ...opts.envFile ? [`--env-file=${opts.envFile}`] : [],
4160
+ entryPath
4161
+ ];
4162
+ }
4163
+ function serveNode(cwd, port, aggregatorPath, production) {
4164
+ const nodeEntryPath = join9(cwd, SERVER_RUNNER_DIR, "serve-node.ts");
4165
+ const aggregatorFile = basename3(aggregatorPath);
4166
+ writeFileSync8(nodeEntryPath, `import { serveNode } from "@uipath/coded-functions-js-runtime/node";
3143
4167
  ` + `import app from "./${aggregatorFile}";
3144
4168
  ` + `const port = Number(process.env.HTTP_SERVER_LISTEN_PORT ?? ${port});
3145
4169
  ` + `console.log("http://localhost:" + port);
3146
4170
  ` + `${SIGNAL_READY_NODE}
3147
- ` + `serve(
3148
- {
3149
- fetch: app.fetch,
3150
- port,
3151
- },
3152
- (info) => {
3153
- console.log(\`JS function node server listening on http://127.0.0.1:\${info.port}\`);
3154
- signalReady();
3155
- });
4171
+ ` + `serveNode(app, port, (port) => {
4172
+ console.log(\`JS function node server listening on http://127.0.0.1:\${port}\`);
4173
+ signalReady();
4174
+ });
3156
4175
  `, "utf-8");
3157
- const envFile = join8(cwd, ".env");
3158
- const envFileArgs = existsSync6(envFile) ? [`--env-file=${envFile}`] : [];
3159
- const [bin, tsxPrefix] = resolveTsx(cwd);
3160
- const proc = spawn(bin, [...tsxPrefix, "watch", ...envFileArgs, nodeEntryPath], {
4176
+ const envFile = join9(cwd, ".env");
4177
+ let bin;
4178
+ let tsxPrefix;
4179
+ try {
4180
+ [bin, tsxPrefix] = resolveTsx(cwd);
4181
+ } catch (err) {
4182
+ console.error(err instanceof Error ? err.message : String(err));
4183
+ process.exit(1);
4184
+ }
4185
+ const tsxArgs = tsxServeArgs(nodeEntryPath, {
4186
+ production,
4187
+ envFile: existsSync7(envFile) ? envFile : undefined
4188
+ });
4189
+ const proc = spawn(bin, [...tsxPrefix, ...tsxArgs], {
3161
4190
  cwd,
3162
4191
  env: { ...process.env, HTTP_SERVER_LISTEN_PORT: String(port) },
3163
4192
  stdio: "inherit"
3164
4193
  });
3165
4194
  proc.on("error", (err) => {
3166
4195
  if (err.code === "ENOENT")
3167
- console.error("npx/tsx not found. Run 'uipath-functions setup'.");
4196
+ console.error("node not found. Run 'uipath-functions setup'.");
3168
4197
  else
3169
4198
  console.error(err);
3170
4199
  process.exit(1);
@@ -3172,9 +4201,9 @@ function serveNode(cwd, port, aggregatorPath) {
3172
4201
  proc.on("exit", (code) => process.exit(code ?? 0));
3173
4202
  }
3174
4203
  function writeDenoServeEntry(cwd, port, aggregatorPath) {
3175
- const denoEntryPath = join8(cwd, SERVER_RUNNER_DIR, "serve-deno.ts");
3176
- const aggregatorFile = basename(aggregatorPath);
3177
- writeFileSync7(denoEntryPath, `import app from "./${aggregatorFile}";
4204
+ const denoEntryPath = join9(cwd, SERVER_RUNNER_DIR, "serve-deno.ts");
4205
+ const aggregatorFile = basename3(aggregatorPath);
4206
+ writeFileSync8(denoEntryPath, `import app from "./${aggregatorFile}";
3178
4207
  ` + `const port = Number(Deno.env.get("HTTP_SERVER_LISTEN_PORT") ?? ${port});
3179
4208
  ` + `console.log("http://localhost:" + port);
3180
4209
  ` + `${SIGNAL_READY_DENO}
@@ -3189,19 +4218,13 @@ function writeDenoServeEntry(cwd, port, aggregatorPath) {
3189
4218
  `, "utf-8");
3190
4219
  return denoEntryPath;
3191
4220
  }
3192
- function serveDeno(cwd, port, aggregatorPath) {
4221
+ function serveDeno(cwd, port, aggregatorPath, production) {
3193
4222
  const denoEntryPath = writeDenoServeEntry(cwd, port, aggregatorPath);
3194
- const denoArgs = [
3195
- "run",
3196
- "--allow-env",
3197
- "--allow-net",
3198
- "--allow-read",
3199
- "--allow-write",
3200
- "--watch",
3201
- ...existsSync6(join8(cwd, ".env")) ? ["--env-file=.env"] : [],
3202
- denoEntryPath
3203
- ];
3204
- const deno = process.env.DENO_BINARY ?? (process.platform === "win32" ? "deno.exe" : "deno");
4223
+ const denoArgs = denoServeArgs(denoEntryPath, {
4224
+ production,
4225
+ envFile: existsSync7(join9(cwd, ".env")) ? ".env" : undefined
4226
+ });
4227
+ const deno = resolveDeno();
3205
4228
  const proc = spawn(deno, denoArgs, {
3206
4229
  cwd,
3207
4230
  env: { ...process.env, HTTP_SERVER_LISTEN_PORT: String(port) },
@@ -3312,7 +4335,25 @@ for (i = 0;i < 32; ++i)
3312
4335
  fdt[i] = 5;
3313
4336
  var i;
3314
4337
  var flm = /* @__PURE__ */ hMap(flt, 9, 0);
4338
+ var flrm = /* @__PURE__ */ hMap(flt, 9, 1);
3315
4339
  var fdm = /* @__PURE__ */ hMap(fdt, 5, 0);
4340
+ var fdrm = /* @__PURE__ */ hMap(fdt, 5, 1);
4341
+ var max = function(a) {
4342
+ var m = a[0];
4343
+ for (var i2 = 1;i2 < a.length; ++i2) {
4344
+ if (a[i2] > m)
4345
+ m = a[i2];
4346
+ }
4347
+ return m;
4348
+ };
4349
+ var bits = function(d, p, m) {
4350
+ var o = p / 8 | 0;
4351
+ return (d[o] | d[o + 1] << 8) >> (p & 7) & m;
4352
+ };
4353
+ var bits16 = function(d, p) {
4354
+ var o = p / 8 | 0;
4355
+ return (d[o] | d[o + 1] << 8 | d[o + 2] << 16) >> (p & 7);
4356
+ };
3316
4357
  var shft = function(p) {
3317
4358
  return (p + 7) / 8 | 0;
3318
4359
  };
@@ -3348,6 +4389,147 @@ var err = function(ind, msg, nt) {
3348
4389
  throw e;
3349
4390
  return e;
3350
4391
  };
4392
+ var inflt = function(dat, st, buf, dict) {
4393
+ var sl = dat.length, dl = dict ? dict.length : 0;
4394
+ if (!sl || st.f && !st.l)
4395
+ return buf || new u8(0);
4396
+ var noBuf = !buf;
4397
+ var resize = noBuf || st.i != 2;
4398
+ var noSt = st.i;
4399
+ if (noBuf)
4400
+ buf = new u8(sl * 3);
4401
+ var cbuf = function(l2) {
4402
+ var bl = buf.length;
4403
+ if (l2 > bl) {
4404
+ var nbuf = new u8(Math.max(bl * 2, l2));
4405
+ nbuf.set(buf);
4406
+ buf = nbuf;
4407
+ }
4408
+ };
4409
+ var final = st.f || 0, pos = st.p || 0, bt = st.b || 0, lm = st.l, dm = st.d, lbt = st.m, dbt = st.n;
4410
+ var tbts = sl * 8;
4411
+ do {
4412
+ if (!lm) {
4413
+ final = bits(dat, pos, 1);
4414
+ var type = bits(dat, pos + 1, 3);
4415
+ pos += 3;
4416
+ if (!type) {
4417
+ var s = shft(pos) + 4, l = dat[s - 4] | dat[s - 3] << 8, t = s + l;
4418
+ if (t > sl) {
4419
+ if (noSt)
4420
+ err(0);
4421
+ break;
4422
+ }
4423
+ if (resize)
4424
+ cbuf(bt + l);
4425
+ buf.set(dat.subarray(s, t), bt);
4426
+ st.b = bt += l, st.p = pos = t * 8, st.f = final;
4427
+ continue;
4428
+ } else if (type == 1)
4429
+ lm = flrm, dm = fdrm, lbt = 9, dbt = 5;
4430
+ else if (type == 2) {
4431
+ var hLit = bits(dat, pos, 31) + 257, hcLen = bits(dat, pos + 10, 15) + 4;
4432
+ var tl = hLit + bits(dat, pos + 5, 31) + 1;
4433
+ pos += 14;
4434
+ var ldt = new u8(tl);
4435
+ var clt = new u8(19);
4436
+ for (var i2 = 0;i2 < hcLen; ++i2) {
4437
+ clt[clim[i2]] = bits(dat, pos + i2 * 3, 7);
4438
+ }
4439
+ pos += hcLen * 3;
4440
+ var clb = max(clt), clbmsk = (1 << clb) - 1;
4441
+ var clm = hMap(clt, clb, 1);
4442
+ for (var i2 = 0;i2 < tl; ) {
4443
+ var r = clm[bits(dat, pos, clbmsk)];
4444
+ pos += r & 15;
4445
+ var s = r >> 4;
4446
+ if (s < 16) {
4447
+ ldt[i2++] = s;
4448
+ } else {
4449
+ var c = 0, n = 0;
4450
+ if (s == 16)
4451
+ n = 3 + bits(dat, pos, 3), pos += 2, c = ldt[i2 - 1];
4452
+ else if (s == 17)
4453
+ n = 3 + bits(dat, pos, 7), pos += 3;
4454
+ else if (s == 18)
4455
+ n = 11 + bits(dat, pos, 127), pos += 7;
4456
+ while (n--)
4457
+ ldt[i2++] = c;
4458
+ }
4459
+ }
4460
+ var lt = ldt.subarray(0, hLit), dt = ldt.subarray(hLit);
4461
+ lbt = max(lt);
4462
+ dbt = max(dt);
4463
+ lm = hMap(lt, lbt, 1);
4464
+ dm = hMap(dt, dbt, 1);
4465
+ } else
4466
+ err(1);
4467
+ if (pos > tbts) {
4468
+ if (noSt)
4469
+ err(0);
4470
+ break;
4471
+ }
4472
+ }
4473
+ if (resize)
4474
+ cbuf(bt + 131072);
4475
+ var lms = (1 << lbt) - 1, dms = (1 << dbt) - 1;
4476
+ var lpos = pos;
4477
+ for (;; lpos = pos) {
4478
+ var c = lm[bits16(dat, pos) & lms], sym = c >> 4;
4479
+ pos += c & 15;
4480
+ if (pos > tbts) {
4481
+ if (noSt)
4482
+ err(0);
4483
+ break;
4484
+ }
4485
+ if (!c)
4486
+ err(2);
4487
+ if (sym < 256)
4488
+ buf[bt++] = sym;
4489
+ else if (sym == 256) {
4490
+ lpos = pos, lm = null;
4491
+ break;
4492
+ } else {
4493
+ var add = sym - 254;
4494
+ if (sym > 264) {
4495
+ var i2 = sym - 257, b = fleb[i2];
4496
+ add = bits(dat, pos, (1 << b) - 1) + fl[i2];
4497
+ pos += b;
4498
+ }
4499
+ var d = dm[bits16(dat, pos) & dms], dsym = d >> 4;
4500
+ if (!d)
4501
+ err(3);
4502
+ pos += d & 15;
4503
+ var dt = fd[dsym];
4504
+ if (dsym > 3) {
4505
+ var b = fdeb[dsym];
4506
+ dt += bits16(dat, pos) & (1 << b) - 1, pos += b;
4507
+ }
4508
+ if (pos > tbts) {
4509
+ if (noSt)
4510
+ err(0);
4511
+ break;
4512
+ }
4513
+ if (resize)
4514
+ cbuf(bt + 131072);
4515
+ var end = bt + add;
4516
+ if (bt < dt) {
4517
+ var shift = dl - dt, dend = Math.min(dt, end);
4518
+ if (shift + bt < 0)
4519
+ err(3);
4520
+ for (;bt < dend; ++bt)
4521
+ buf[bt] = dict[shift + bt];
4522
+ }
4523
+ for (;bt < end; ++bt)
4524
+ buf[bt] = buf[bt - dt];
4525
+ }
4526
+ }
4527
+ st.l = lm, st.p = lpos, st.b = bt, st.f = final;
4528
+ if (lm)
4529
+ final = 1, st.m = lbt, st.d = dm, st.n = dbt;
4530
+ } while (!final);
4531
+ return bt != buf.length && noBuf ? slc(buf, 0, bt) : buf.subarray(0, bt);
4532
+ };
3351
4533
  var wbits = function(d, p, v) {
3352
4534
  v <<= p & 7;
3353
4535
  var o = p / 8 | 0;
@@ -3695,6 +4877,15 @@ var mrg = function(a, b) {
3695
4877
  o[k] = b[k];
3696
4878
  return o;
3697
4879
  };
4880
+ var b2 = function(d, b) {
4881
+ return d[b] | d[b + 1] << 8;
4882
+ };
4883
+ var b4 = function(d, b) {
4884
+ return (d[b] | d[b + 1] << 8 | d[b + 2] << 16 | d[b + 3] << 24) >>> 0;
4885
+ };
4886
+ var b8 = function(d, b) {
4887
+ return b4(d, b) + b4(d, b + 4) * 4294967296;
4888
+ };
3698
4889
  var wbytes = function(d, b, v) {
3699
4890
  for (;v; ++b)
3700
4891
  d[b] = v, v >>>= 8;
@@ -3702,6 +4893,9 @@ var wbytes = function(d, b, v) {
3702
4893
  function deflateSync(data, opts) {
3703
4894
  return dopt(data, opts || {}, 0, 0);
3704
4895
  }
4896
+ function inflateSync(data, opts) {
4897
+ return inflt(data, { i: 2 }, opts && opts.out, opts && opts.dictionary);
4898
+ }
3705
4899
  var fltn = function(d, p, t, o) {
3706
4900
  for (var k in d) {
3707
4901
  var val = d[k], n = p + k, op = o;
@@ -3722,6 +4916,22 @@ try {
3722
4916
  td.decode(et, { stream: true });
3723
4917
  tds = 1;
3724
4918
  } catch (e) {}
4919
+ var dutf8 = function(d) {
4920
+ for (var r = "", i2 = 0;; ) {
4921
+ var c = d[i2++];
4922
+ var eb = (c > 127) + (c > 223) + (c > 239);
4923
+ if (i2 + eb > d.length)
4924
+ return { s: r, r: slc(d, i2 - 1) };
4925
+ if (!eb)
4926
+ r += String.fromCharCode(c);
4927
+ else if (eb == 3) {
4928
+ c = ((c & 15) << 18 | (d[i2++] & 63) << 12 | (d[i2++] & 63) << 6 | d[i2++] & 63) - 65536, r += String.fromCharCode(55296 | c >> 10, 56320 | c & 1023);
4929
+ } else if (eb & 1)
4930
+ r += String.fromCharCode((c & 31) << 6 | d[i2++] & 63);
4931
+ else
4932
+ r += String.fromCharCode((c & 15) << 12 | (d[i2++] & 63) << 6 | d[i2++] & 63);
4933
+ }
4934
+ };
3725
4935
  function strToU8(str, latin1) {
3726
4936
  if (latin1) {
3727
4937
  var ar_1 = new u8(str.length);
@@ -3755,6 +4965,48 @@ function strToU8(str, latin1) {
3755
4965
  }
3756
4966
  return slc(ar, 0, ai);
3757
4967
  }
4968
+ function strFromU8(dat, latin1) {
4969
+ if (latin1) {
4970
+ var r = "";
4971
+ for (var i2 = 0;i2 < dat.length; i2 += 16384)
4972
+ r += String.fromCharCode.apply(null, dat.subarray(i2, i2 + 16384));
4973
+ return r;
4974
+ } else if (td) {
4975
+ return td.decode(dat);
4976
+ } else {
4977
+ var _a2 = dutf8(dat), s = _a2.s, r = _a2.r;
4978
+ if (r.length)
4979
+ err(8);
4980
+ return s;
4981
+ }
4982
+ }
4983
+ var slzh = function(d, b) {
4984
+ return b + 30 + b2(d, b + 26) + b2(d, b + 28);
4985
+ };
4986
+ var zh = function(d, b, z) {
4987
+ var fnl = b2(d, b + 28), efl = b2(d, b + 30), fn = strFromU8(d.subarray(b + 46, b + 46 + fnl), !(b2(d, b + 8) & 2048)), es = b + 46 + fnl;
4988
+ var _a2 = z64hs(d, es, efl, z, b4(d, b + 20), b4(d, b + 24), b4(d, b + 42)), sc = _a2[0], su = _a2[1], off = _a2[2];
4989
+ return [b2(d, b + 10), sc, su, fn, es + efl + b2(d, b + 32), off];
4990
+ };
4991
+ var z64hs = function(d, b, l, z, sc, su, off) {
4992
+ var nsc = sc == 4294967295, nsu = su == 4294967295, noff = off == 4294967295, e = b + l;
4993
+ var nf = nsc + nsu + noff;
4994
+ if (z && nf) {
4995
+ for (;b + 4 < e; b += 4 + b2(d, b + 2)) {
4996
+ if (b2(d, b) == 1) {
4997
+ return [
4998
+ nsc ? b8(d, b + 4 + 8 * nsu) : sc,
4999
+ nsu ? b8(d, b + 4) : su,
5000
+ noff ? b8(d, b + 4 + 8 * (nsu + nsc)) : off,
5001
+ 1
5002
+ ];
5003
+ }
5004
+ }
5005
+ if (z < 2)
5006
+ err(13);
5007
+ }
5008
+ return [sc, su, off, 0];
5009
+ };
3758
5010
  var exfl = function(ex) {
3759
5011
  var le = 0;
3760
5012
  if (ex) {
@@ -3856,6 +5108,46 @@ function zipSync(data, opts) {
3856
5108
  wzf(out, o, files.length, cdl, oe);
3857
5109
  return out;
3858
5110
  }
5111
+ function unzipSync(data, opts) {
5112
+ var files = {};
5113
+ var e = data.length - 22;
5114
+ for (;b4(data, e) != 101010256; --e) {
5115
+ if (!e || data.length - e > 65558)
5116
+ err(13);
5117
+ }
5118
+ var c = b2(data, e + 8);
5119
+ if (!c)
5120
+ return {};
5121
+ var o = b4(data, e + 16);
5122
+ var z = b4(data, e - 20) == 117853008;
5123
+ if (z) {
5124
+ var ze = b4(data, e - 12);
5125
+ z = b4(data, ze) == 101075792;
5126
+ if (z) {
5127
+ c = b4(data, ze + 32);
5128
+ o = b4(data, ze + 48);
5129
+ }
5130
+ }
5131
+ var fltr = opts && opts.filter;
5132
+ for (var i2 = 0;i2 < c; ++i2) {
5133
+ var _a2 = zh(data, o, z), c_2 = _a2[0], sc = _a2[1], su = _a2[2], fn = _a2[3], no = _a2[4], off = _a2[5], b = slzh(data, off);
5134
+ o = no;
5135
+ if (!fltr || fltr({
5136
+ name: fn,
5137
+ size: sc,
5138
+ originalSize: su,
5139
+ compression: c_2
5140
+ })) {
5141
+ if (!c_2)
5142
+ files[fn] = slc(data, b, b + sc);
5143
+ else if (c_2 == 8)
5144
+ files[fn] = inflateSync(data.subarray(b, b + sc), { out: new u8(su) });
5145
+ else
5146
+ err(14, "unknown compression type " + c_2);
5147
+ }
5148
+ }
5149
+ return files;
5150
+ }
3859
5151
  var isDockerCached;
3860
5152
  function hasDockerEnv() {
3861
5153
  try {
@@ -4428,323 +5720,90 @@ class NodeFileSystem {
4428
5720
  return await fs6.readFile(path3);
4429
5721
  } catch (error) {
4430
5722
  if (this.isEnoent(error))
4431
- return null;
4432
- throw error;
4433
- }
4434
- }
4435
- async writeFile(filePath, data) {
4436
- const dir = path2.dirname(filePath);
4437
- if (dir) {
4438
- await fs6.mkdir(dir, { recursive: true });
4439
- }
4440
- await fs6.writeFile(filePath, data);
4441
- }
4442
- async readdir(dirPath) {
4443
- try {
4444
- return await fs6.readdir(dirPath);
4445
- } catch (error) {
4446
- if (this.isEnoent(error))
4447
- return [];
4448
- throw error;
4449
- }
4450
- }
4451
- async stat(filePath) {
4452
- try {
4453
- const stats = await fs6.stat(filePath);
4454
- return {
4455
- isFile: () => stats.isFile(),
4456
- isDirectory: () => stats.isDirectory(),
4457
- size: stats.size,
4458
- mtimeMs: stats.mtimeMs
4459
- };
4460
- } catch (error) {
4461
- if (this.isEnoent(error))
4462
- return null;
4463
- throw error;
4464
- }
4465
- }
4466
- async exists(filePath) {
4467
- return existsSync7(filePath);
4468
- }
4469
- async mkdir(dirPath) {
4470
- await fs6.mkdir(dirPath, { recursive: true });
4471
- }
4472
- async rm(filePath) {
4473
- await fs6.rm(filePath, { recursive: true, force: true });
4474
- }
4475
- async rename(oldPath, newPath) {
4476
- await fs6.rename(oldPath, newPath);
4477
- }
4478
- async getTempDir() {
4479
- return await fs6.mkdtemp(path2.join(os2.tmpdir(), "uipath-fs-"));
4480
- }
4481
- async copyDirectory(sourcePath, destPath) {
4482
- const sourceStats = await this.stat(sourcePath);
4483
- if (!sourceStats) {
4484
- throw new Error(`Source directory does not exist: ${sourcePath}`);
4485
- }
4486
- if (!sourceStats.isDirectory()) {
4487
- throw new Error(`Source path is not a directory: ${sourcePath}`);
4488
- }
4489
- await this.mkdir(destPath);
4490
- const entries = await this.readdir(sourcePath);
4491
- for (const entry of entries) {
4492
- const srcEntry = path2.join(sourcePath, entry);
4493
- const destEntry = path2.join(destPath, entry);
4494
- const entryStats = await this.stat(srcEntry);
4495
- if (!entryStats)
4496
- continue;
4497
- if (entryStats.isDirectory()) {
4498
- await this.copyDirectory(srcEntry, destEntry);
4499
- } else if (entryStats.isFile()) {
4500
- const content = await this.readFile(srcEntry);
4501
- if (content !== null) {
4502
- await this.writeFile(destEntry, content);
4503
- }
4504
- }
4505
- }
4506
- }
4507
- isEnoent(error) {
4508
- return typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT";
4509
- }
4510
- }
4511
- var fsInstance = new NodeFileSystem;
4512
- var getFileSystem = () => {
4513
- return fsInstance;
4514
- };
4515
- var EXCLUDED_NAMES = new Set([
4516
- "node_modules",
4517
- ".git",
4518
- ".env",
4519
- ".deno",
4520
- "dist",
4521
- ".uipath"
4522
- ]);
4523
- var EXCLUDED_EXTENSIONS = [".nupkg"];
4524
- var NPMRC = ".npmrc";
4525
- var UIPATH_SCOPE = "@uipath:";
4526
- var CREDENTIAL_KEYS = ["_authtoken", "_auth", "_password"];
4527
- function isComment(line) {
4528
- return line === "" || line.startsWith("#") || line.startsWith(";");
4529
- }
4530
- function isOurs(line) {
4531
- const trimmed = line.trim();
4532
- if (isComment(trimmed))
4533
- return false;
4534
- const key = (trimmed.split("=")[0] ?? "").trim().toLowerCase();
4535
- return key.startsWith(UIPATH_SCOPE) || CREDENTIAL_KEYS.some((c) => key.endsWith(c));
4536
- }
4537
- function sanitizeNpmrc(content) {
4538
- const kept = content.split(/\r?\n/).filter((line) => !isOurs(line));
4539
- return kept.some((line) => !isComment(line.trim())) ? kept.join(`
4540
- `) : null;
4541
- }
4542
- var LOCK_FILES = new Set(["bun.lock", "package-lock.json", "deno.lock", "yarn.lock"]);
4543
- async function buildFunctionsPackage(fs7, options) {
4544
- const { projectPath, outputPath, projectStorageId } = options;
4545
- const contentPath = fs7.path.join(outputPath, "content");
4546
- await fs7.mkdir(outputPath);
4547
- await fs7.mkdir(contentPath);
4548
- const uipathJsonRaw = await fs7.readFile(fs7.path.join(projectPath, "uipath.json"), "utf-8");
4549
- if (!uipathJsonRaw) {
4550
- throw new Error("uipath.json not found. Run 'uipath-functions init' first.");
4551
- }
4552
- const uipathJson = JSON.parse(uipathJsonRaw);
4553
- const entryPointsRaw = await fs7.readFile(fs7.path.join(projectPath, "entry-points.json"), "utf-8");
4554
- if (!entryPointsRaw) {
4555
- throw new Error("entry-points.json not found. Run 'uipath-functions pack' to generate it.");
4556
- }
4557
- const entryPoints = JSON.parse(entryPointsRaw);
4558
- const bindingsRaw = await fs7.readFile(fs7.path.join(projectPath, "bindings_v2.json"), "utf-8");
4559
- if (!bindingsRaw) {
4560
- throw new Error("bindings_v2.json not found. Run 'uipath-functions pack' to generate it.");
4561
- }
4562
- const bindings = JSON.parse(bindingsRaw);
4563
- const packageJsonRaw = await fs7.readFile(fs7.path.join(projectPath, "package.json"), "utf-8");
4564
- const packageDependencies = packageJsonRaw ? JSON.parse(packageJsonRaw).dependencies ?? {} : {};
4565
- const targetRuntime = detectRuntime(uipathJson.functions);
4566
- const includeLockFile = options.excludeLockFile ? false : uipathJson.packOptions?.includeLockFile ?? true;
4567
- await copyProjectFiles(fs7, projectPath, contentPath, includeLockFile, uipathJson.packOptions);
4568
- const operateJson = {
4569
- $schema: "https://cloud.uipath.com/draft/2024-12/operate",
4570
- projectId: projectStorageId,
4571
- contentType: "function",
4572
- targetFramework: "Portable",
4573
- targetRuntime,
4574
- runtimeOptions: {
4575
- requiresUserInteraction: false,
4576
- isAttended: false
4577
- },
4578
- deploymentOptions: {
4579
- generateSlug: true
4580
- },
4581
- dependencies: packageDependencies
4582
- };
4583
- await fs7.writeFile(fs7.path.join(contentPath, "operate.json"), JSON.stringify(operateJson, null, 2));
4584
- await fs7.writeFile(fs7.path.join(contentPath, "entry-points.json"), JSON.stringify(entryPoints, null, 2));
4585
- await fs7.writeFile(fs7.path.join(contentPath, "bindings_v2.json"), JSON.stringify(bindings, null, 2));
4586
- const packageDescriptor = {
4587
- $schema: "https://cloud.uipath.com/draft/2024-12/package-descriptor",
4588
- files: {
4589
- "operate.json": "content/operate.json",
4590
- "entry-points.json": "content/entry-points.json",
4591
- "bindings.json": "content/bindings_v2.json"
4592
- }
4593
- };
4594
- for (const ep of entryPoints.entryPoints) {
4595
- const fnEntry = uipathJson.functions?.[ep.filePath];
4596
- const filePath = fnEntry ? fnEntry.split(":")[0] ?? ep.filePath : ep.filePath;
4597
- packageDescriptor.files[ep.filePath] = `${filePath}`;
4598
- }
4599
- await fs7.writeFile(fs7.path.join(contentPath, "package-descriptor.json"), JSON.stringify(packageDescriptor, null, 2));
4600
- }
4601
- function detectRuntime(functions) {
4602
- if (!functions)
4603
- return "javascript";
4604
- const first = Object.values(functions)[0];
4605
- if (!first)
4606
- return "javascript";
4607
- const filePath = first.split(":")[0] ?? "";
4608
- const ext = filePath.slice(filePath.lastIndexOf("."));
4609
- if (ext === ".py")
4610
- return "python";
4611
- return "javascript";
4612
- }
4613
- async function copyProjectFiles(fs7, sourcePath, destPath, includeLockFile, packOptions) {
4614
- const extraExcludedDirs = new Set(packOptions?.directoriesExcluded ?? []);
4615
- const extraExcludedFiles = new Set(packOptions?.filesExcluded ?? []);
4616
- async function walk(src, dest) {
4617
- await fs7.mkdir(dest);
4618
- const entries = await fs7.readdir(src);
4619
- for (const name of entries) {
4620
- if (EXCLUDED_NAMES.has(name))
4621
- continue;
4622
- if (extraExcludedDirs.has(name))
4623
- continue;
4624
- if (extraExcludedFiles.has(name))
4625
- continue;
4626
- if (EXCLUDED_EXTENSIONS.some((ext) => name.endsWith(ext)))
4627
- continue;
4628
- if (!includeLockFile && LOCK_FILES.has(name))
4629
- continue;
4630
- const srcEntry = fs7.path.join(src, name);
4631
- const destEntry = fs7.path.join(dest, name);
4632
- const stat2 = await fs7.stat(srcEntry);
4633
- if (stat2?.isDirectory()) {
4634
- await walk(srcEntry, destEntry);
4635
- } else if (name === NPMRC) {
4636
- const sanitized = sanitizeNpmrc(await fs7.readFile(srcEntry, "utf-8") ?? "");
4637
- if (sanitized !== null)
4638
- await fs7.writeFile(destEntry, sanitized);
4639
- } else if (stat2?.isFile()) {
4640
- const content = await fs7.readFile(srcEntry);
4641
- if (content)
4642
- await fs7.writeFile(destEntry, content);
4643
- }
5723
+ return null;
5724
+ throw error;
4644
5725
  }
4645
5726
  }
4646
- await walk(sourcePath, destPath);
4647
- }
4648
- var CONSUMER_COMPILER_OPTIONS2 = {
4649
- target: ts3.ScriptTarget.ES2020,
4650
- module: ts3.ModuleKind.ESNext,
4651
- moduleResolution: ts3.ModuleResolutionKind.Bundler,
4652
- allowImportingTsExtensions: true,
4653
- allowJs: true,
4654
- strict: true,
4655
- skipLibCheck: true,
4656
- noEmit: true
4657
- };
4658
- var DIAGNOSTIC_CODES2 = {
4659
- UNSUPPORTED_VALIDATOR: "unsupported-validator",
4660
- UNSUPPORTED_TYPE: "unsupported-type",
4661
- NON_STATIC_LITERAL: "non-static-literal",
4662
- MISSING_TYPE_ARGUMENT: "missing-type-argument",
4663
- AMBIGUOUS_ROUTE: "ambiguous-route",
4664
- MULTIPLE_FUNCTIONS_PER_FILE: "multiple-functions-per-file",
4665
- DEPRECATED_MARKER: "deprecated-marker"
4666
- };
4667
- function newId() {
4668
- return globalThis.crypto.randomUUID();
4669
- }
4670
- function buildEntryPointsDoc(functions, existing, filePathPrefix = "content/") {
4671
- const functionIds = new Map;
4672
- const transactionRoots = new Set;
4673
- const preserved = [];
4674
- for (const ep of existing?.entryPoints ?? []) {
4675
- if (ep.type === "function") {
4676
- functionIds.set(ep.filePath, ep.uniqueId);
4677
- if (ep.isTransactionRoot === true) {
4678
- transactionRoots.add(ep.filePath);
4679
- }
4680
- } else {
4681
- preserved.push(ep);
5727
+ async writeFile(filePath, data) {
5728
+ const dir = path2.dirname(filePath);
5729
+ if (dir) {
5730
+ await fs6.mkdir(dir, { recursive: true });
4682
5731
  }
5732
+ await fs6.writeFile(filePath, data);
4683
5733
  }
4684
- const functionEntries = functions.map((fn) => {
4685
- const filePath = filePathPrefix + (fn.functionPath ?? "");
4686
- return {
4687
- filePath,
4688
- uniqueId: functionIds.get(filePath) ?? newId(),
4689
- type: "function",
4690
- input: fn.input ?? { type: "object" },
4691
- output: fn.output ?? { type: "object" },
4692
- ...transactionRoots.has(filePath) ? { isTransactionRoot: true } : {}
4693
- };
4694
- });
4695
- return {
4696
- $schema: "https://cloud.uipath.com/draft/2024-12/entry-point",
4697
- $id: "entry-points.json",
4698
- entryPoints: [...preserved, ...functionEntries]
4699
- };
4700
- }
4701
- function buildBindingsDoc(functions, entryPointIdByPath, existingBindings, filePathPrefix = "content/") {
4702
- const httpExisting = new Map;
4703
- const preserved = [];
4704
- for (const r of existingBindings?.resources ?? []) {
4705
- if (r.resource === "HttpTrigger") {
4706
- const meta = r.metadata;
4707
- if (meta?.Method && meta?.Slug) {
4708
- httpExisting.set(`${meta.Method}:${meta.Slug}`, { key: r.key, id: r.id });
4709
- }
4710
- } else {
4711
- preserved.push(r);
5734
+ async readdir(dirPath) {
5735
+ try {
5736
+ return await fs6.readdir(dirPath);
5737
+ } catch (error) {
5738
+ if (this.isEnoent(error))
5739
+ return [];
5740
+ throw error;
4712
5741
  }
4713
5742
  }
4714
- const httpTriggers = functions.filter((fn) => fn.method && fn.path).map((fn) => {
4715
- const existing = httpExisting.get(`${fn.method}:${fn.path}`);
4716
- const bindingKey = existing?.key ?? newId();
4717
- const bindingId = existing?.id ?? newId();
4718
- const entryPointUniqueId = entryPointIdByPath.get(filePathPrefix + (fn.functionPath ?? ""));
4719
- if (!entryPointUniqueId) {
4720
- throw new Error(`Internal error: binding for "${fn.method} ${fn.path}" references entry point "${filePathPrefix}${fn.functionPath}", which is missing from entry-points.json.`);
5743
+ async stat(filePath) {
5744
+ try {
5745
+ const stats = await fs6.stat(filePath);
5746
+ return {
5747
+ isFile: () => stats.isFile(),
5748
+ isDirectory: () => stats.isDirectory(),
5749
+ size: stats.size,
5750
+ mtimeMs: stats.mtimeMs
5751
+ };
5752
+ } catch (error) {
5753
+ if (this.isEnoent(error))
5754
+ return null;
5755
+ throw error;
4721
5756
  }
4722
- return {
4723
- resource: "HttpTrigger",
4724
- key: bindingKey,
4725
- id: bindingId,
4726
- value: {
4727
- EntryPointUniqueId: {
4728
- DefaultValue: entryPointUniqueId,
4729
- IsExpression: false
5757
+ }
5758
+ async exists(filePath) {
5759
+ return existsSync8(filePath);
5760
+ }
5761
+ async mkdir(dirPath) {
5762
+ await fs6.mkdir(dirPath, { recursive: true });
5763
+ }
5764
+ async rm(filePath) {
5765
+ await fs6.rm(filePath, { recursive: true, force: true });
5766
+ }
5767
+ async rename(oldPath, newPath) {
5768
+ await fs6.rename(oldPath, newPath);
5769
+ }
5770
+ async getTempDir() {
5771
+ return await fs6.mkdtemp(path2.join(os2.tmpdir(), "uipath-fs-"));
5772
+ }
5773
+ async copyDirectory(sourcePath, destPath) {
5774
+ const sourceStats = await this.stat(sourcePath);
5775
+ if (!sourceStats) {
5776
+ throw new Error(`Source directory does not exist: ${sourcePath}`);
5777
+ }
5778
+ if (!sourceStats.isDirectory()) {
5779
+ throw new Error(`Source path is not a directory: ${sourcePath}`);
5780
+ }
5781
+ await this.mkdir(destPath);
5782
+ const entries = await this.readdir(sourcePath);
5783
+ for (const entry of entries) {
5784
+ const srcEntry = path2.join(sourcePath, entry);
5785
+ const destEntry = path2.join(destPath, entry);
5786
+ const entryStats = await this.stat(srcEntry);
5787
+ if (!entryStats)
5788
+ continue;
5789
+ if (entryStats.isDirectory()) {
5790
+ await this.copyDirectory(srcEntry, destEntry);
5791
+ } else if (entryStats.isFile()) {
5792
+ const content = await this.readFile(srcEntry);
5793
+ if (content !== null) {
5794
+ await this.writeFile(destEntry, content);
4730
5795
  }
4731
- },
4732
- metadata: {
4733
- BindingsVersion: "2.1",
4734
- Name: fn.name ?? "",
4735
- Method: fn.method,
4736
- Slug: fn.path,
4737
- CallingMode: "LongPolling",
4738
- Description: fn.description ?? ""
4739
5796
  }
4740
- };
4741
- });
4742
- return {
4743
- $schema: "https://cloud.uipath.com/draft/2024-12/bindings",
4744
- version: "2.0",
4745
- resources: [...preserved, ...httpTriggers]
4746
- };
5797
+ }
5798
+ }
5799
+ isEnoent(error) {
5800
+ return typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT";
5801
+ }
4747
5802
  }
5803
+ var fsInstance = new NodeFileSystem;
5804
+ var getFileSystem = () => {
5805
+ return fsInstance;
5806
+ };
4748
5807
  function toExtractedFunctions(endpoints) {
4749
5808
  return endpoints.map((e) => ({
4750
5809
  functionPath: e.functionPath,
@@ -4760,20 +5819,20 @@ var tsxRegistered = false;
4760
5819
  async function extractAndWriteEntryPointsAndBindings(aggregatorPath, projectPath) {
4761
5820
  if (!tsxRegistered) {
4762
5821
  try {
4763
- const dbgPkg = join10(projectPath, SERVER_RUNNER_DIR, "package.json");
5822
+ const dbgPkg = join11(projectPath, SERVER_RUNNER_DIR, "package.json");
4764
5823
  const tsxEsm = createRequire4(dbgPkg).resolve("tsx/esm");
4765
- register(pathToFileURL(tsxEsm).href, pathToFileURL(join10(projectPath, SERVER_RUNNER_DIR) + "/").href);
5824
+ register(pathToFileURL2(tsxEsm).href, pathToFileURL2(join11(projectPath, SERVER_RUNNER_DIR) + "/").href);
4766
5825
  tsxRegistered = true;
4767
5826
  } catch {}
4768
5827
  }
4769
5828
  let app;
4770
5829
  try {
4771
- const mod = await import(pathToFileURL(aggregatorPath).href);
5830
+ const mod = await import(pathToFileURL2(aggregatorPath).href);
4772
5831
  app = mod.default;
4773
5832
  } catch (err2) {
4774
5833
  const msg = err2 instanceof Error ? err2.message : String(err2);
4775
5834
  if (msg.includes("Cannot find") || msg.includes("ERR_MODULE_NOT_FOUND")) {
4776
- throw new Error("Failed to load function modules. Run 'npm install' first, then retry.");
5835
+ throw new Error(`Failed to load function modules. Run '${describeInstallCommand(projectPath)}' first, then retry.`);
4777
5836
  }
4778
5837
  throw new Error(`Manifest extraction failed.
4779
5838
  ${msg}`);
@@ -4789,40 +5848,47 @@ ${msg}`);
4789
5848
  return manifest;
4790
5849
  }
4791
5850
  function writeEntryPointsAndBindings(functions, projectPath) {
4792
- const epPath = join10(projectPath, "entry-points.json");
5851
+ const epPath = join11(projectPath, "entry-points.json");
4793
5852
  let existingEntryPointsDoc = null;
4794
- if (existsSync8(epPath)) {
5853
+ if (existsSync9(epPath)) {
4795
5854
  try {
4796
- existingEntryPointsDoc = JSON.parse(readFileSync6(epPath, "utf-8"));
5855
+ existingEntryPointsDoc = JSON.parse(readFileSync7(epPath, "utf-8"));
4797
5856
  } catch {}
4798
5857
  }
4799
5858
  const entryPointsDoc = buildEntryPointsDoc(functions, existingEntryPointsDoc);
4800
- writeFileSync8(join10(projectPath, "entry-points.json"), JSON.stringify(entryPointsDoc, null, 2));
5859
+ writeFileSync9(join11(projectPath, "entry-points.json"), JSON.stringify(entryPointsDoc, null, 2));
4801
5860
  const entryPointIdByPath = new Map;
4802
5861
  for (const ep of entryPointsDoc.entryPoints) {
4803
5862
  if (ep.type === "function" && !entryPointIdByPath.has(ep.filePath)) {
4804
5863
  entryPointIdByPath.set(ep.filePath, ep.uniqueId);
4805
5864
  }
4806
5865
  }
4807
- const bindingsPath = join10(projectPath, "bindings_v2.json");
5866
+ const bindingsPath = join11(projectPath, "bindings_v2.json");
4808
5867
  let existingBindingsDoc = null;
4809
- if (existsSync8(bindingsPath)) {
5868
+ if (existsSync9(bindingsPath)) {
4810
5869
  try {
4811
- existingBindingsDoc = JSON.parse(readFileSync6(bindingsPath, "utf-8"));
5870
+ existingBindingsDoc = JSON.parse(readFileSync7(bindingsPath, "utf-8"));
4812
5871
  } catch {}
4813
5872
  }
4814
5873
  const bindingsDoc = buildBindingsDoc(functions, entryPointIdByPath, existingBindingsDoc);
4815
- writeFileSync8(join10(projectPath, "bindings_v2.json"), JSON.stringify(bindingsDoc, null, 2));
5874
+ writeFileSync9(join11(projectPath, "bindings_v2.json"), JSON.stringify(bindingsDoc, null, 2));
4816
5875
  }
4817
- async function writeManifest(extraction, aggregatorPath, projectPath) {
4818
- const needsExecution = extraction.diagnostics.some((d) => d.code === DIAGNOSTIC_CODES2.UNSUPPORTED_VALIDATOR);
4819
- for (const d of extraction.diagnostics) {
4820
- if (d.code === DIAGNOSTIC_CODES2.UNSUPPORTED_VALIDATOR)
4821
- continue;
4822
- const where = [d.functionName, d.field].filter(Boolean).join(".");
4823
- console.warn(` Warning${where ? ` (${where})` : ""}: ${d.message}`);
5876
+ function manifestNeedsExecution(extraction, functionsMap) {
5877
+ const forcesExecution = new Set([
5878
+ DIAGNOSTIC_CODES2.UNSUPPORTED_VALIDATOR,
5879
+ DIAGNOSTIC_CODES2.UNREADABLE_PROPERTY,
5880
+ DIAGNOSTIC_CODES2.NON_STATIC_LITERAL
5881
+ ]);
5882
+ if (extraction.diagnostics.some((d) => forcesExecution.has(d.code))) {
5883
+ return true;
4824
5884
  }
4825
- if (needsExecution) {
5885
+ if (!functionsMap)
5886
+ return false;
5887
+ const covered = new Set(extraction.functions.map((f) => f.functionPath));
5888
+ return Object.values(functionsMap).some((v) => !covered.has(v.split(":")[0]));
5889
+ }
5890
+ async function writeManifest(extraction, aggregatorPath, projectPath, functionsMap) {
5891
+ if (manifestNeedsExecution(extraction, functionsMap)) {
4826
5892
  const manifest = await extractAndWriteEntryPointsAndBindings(aggregatorPath, projectPath);
4827
5893
  return { count: manifest.endpoints.length, static: false };
4828
5894
  }
@@ -4834,34 +5900,34 @@ async function writeManifest(extraction, aggregatorPath, projectPath) {
4834
5900
  return { count: functions.length, static: true };
4835
5901
  }
4836
5902
  async function generateManifests(projectPath) {
4837
- const uipathJsonPath = join11(projectPath, "uipath.json");
4838
- if (!existsSync9(uipathJsonPath)) {
5903
+ const uipathJsonPath = join12(projectPath, "uipath.json");
5904
+ if (!existsSync10(uipathJsonPath)) {
4839
5905
  throw new Error("No uipath.json found. Run 'uipath-functions init' first.");
4840
5906
  }
4841
5907
  if (syncFunctionsMap(projectPath)) {
4842
5908
  console.log("Updated functions map in uipath.json.");
4843
5909
  }
4844
- const uipathJson = JSON.parse(readFileSync7(uipathJsonPath, "utf-8"));
5910
+ const uipathJson = JSON.parse(readFileSync8(uipathJsonPath, "utf-8"));
4845
5911
  if (!uipathJson.functions || Object.keys(uipathJson.functions).length === 0) {
4846
5912
  throw new Error("No functions defined in uipath.json.");
4847
5913
  }
4848
- let bootstrapped = false;
4849
- if (!existsSync9(join11(projectPath, "node_modules"))) {
4850
- setupRunDependencies(projectPath);
4851
- bootstrapped = true;
4852
- }
5914
+ assertReadyToPackage(projectPath);
4853
5915
  const previousDesignTime = process.env[DESIGN_TIME_ENV];
4854
5916
  process.env[DESIGN_TIME_ENV] = "1";
4855
5917
  try {
4856
- console.log("Generating aggregator...");
4857
5918
  const extraction = extractProject(uipathJson.functions, projectPath);
5919
+ const blocking = reportDiagnostics(extraction.diagnostics);
5920
+ if (blocking > 0) {
5921
+ throw new Error(`${blocking} error(s) in the project's function files — nothing was written. ` + `Fix them and re-run.`);
5922
+ }
5923
+ console.log("Generating aggregator...");
4858
5924
  const aggregatorPath = generateAggregator(uipathJson.functions, projectPath, "serve", toDerivedContracts(extraction.functions));
4859
- const needsExecution = extraction.diagnostics.some((d) => d.code === DIAGNOSTIC_CODES2.UNSUPPORTED_VALIDATOR);
4860
- if (needsExecution && !bootstrapped) {
4861
- setupRunDependencies(projectPath);
5925
+ const needsExecution = manifestNeedsExecution(extraction, uipathJson.functions);
5926
+ if (needsExecution) {
5927
+ installServerRunner(projectPath);
4862
5928
  }
4863
5929
  console.log("Extracting function manifest...");
4864
- return await writeManifest(extraction, aggregatorPath, projectPath);
5930
+ return await writeManifest(extraction, aggregatorPath, projectPath, uipathJson.functions);
4865
5931
  } finally {
4866
5932
  if (previousDesignTime === undefined) {
4867
5933
  delete process.env[DESIGN_TIME_ENV];
@@ -4871,8 +5937,11 @@ async function generateManifests(projectPath) {
4871
5937
  }
4872
5938
  }
4873
5939
  function registerPackCommand(program2) {
4874
- program2.command("pack").description("Pack the project into a .nupkg for deployment.").option("--nolock", "Exclude lock file from package").action(async (opts) => {
5940
+ program2.command("pack").description("Pack the project into a .nupkg for deployment.").option("--nolock", "Deprecated and ignored: the project's lock file is always packaged").action(async (opts) => {
4875
5941
  const cwd = resolve5(".");
5942
+ if (opts.nolock) {
5943
+ console.warn("--nolock is ignored: the project's lock file is always packaged, the pod installs from it.");
5944
+ }
4876
5945
  try {
4877
5946
  const result = await generateManifests(cwd);
4878
5947
  console.log(` ${result.count} function(s) — ${result.static ? "extracted statically" : "executed to extract"}.`);
@@ -4880,24 +5949,23 @@ function registerPackCommand(program2) {
4880
5949
  console.error(err2 instanceof Error ? err2.message : String(err2));
4881
5950
  process.exit(1);
4882
5951
  }
4883
- const uipathJsonPath = join12(cwd, "uipath.json");
4884
- const uipathJson = JSON.parse(readFileSync8(uipathJsonPath, "utf-8"));
4885
- const packageJson = JSON.parse(readFileSync8(join12(cwd, "package.json"), "utf-8"));
5952
+ const uipathJsonPath = join13(cwd, "uipath.json");
5953
+ const uipathJson = JSON.parse(readFileSync9(uipathJsonPath, "utf-8"));
5954
+ const packageJson = JSON.parse(readFileSync9(join13(cwd, "package.json"), "utf-8"));
4886
5955
  const packageId = (packageJson.name ?? "functions").replace(/[^a-zA-Z0-9._-]/g, "") || "functions";
4887
5956
  const version = packageJson.version ?? "1.0.0";
4888
5957
  if (!uipathJson.projectId) {
4889
5958
  uipathJson.projectId = randomUUID();
4890
- writeFileSync9(uipathJsonPath, JSON.stringify(uipathJson, null, 2), "utf-8");
5959
+ writeFileSync10(uipathJsonPath, JSON.stringify(uipathJson, null, 2), "utf-8");
4891
5960
  }
4892
5961
  console.log("Assembling package...");
4893
- const outputDir = join12(cwd, ".uipath", "package-build");
5962
+ const outputDir = join13(cwd, ".uipath", "package-build");
4894
5963
  mkdirSync5(outputDir, { recursive: true });
4895
5964
  const fs7 = getFileSystem();
4896
5965
  await buildFunctionsPackage(fs7, {
4897
5966
  projectPath: cwd,
4898
5967
  outputPath: outputDir,
4899
5968
  projectStorageId: uipathJson.projectId,
4900
- excludeLockFile: opts.nolock,
4901
5969
  package: {
4902
5970
  id: packageId,
4903
5971
  version,
@@ -4917,12 +5985,12 @@ function zipToNupkg(buildDir, cwd, packageId, version) {
4917
5985
  const files = {};
4918
5986
  function walk(dir, prefix) {
4919
5987
  for (const name of readdirSync3(dir)) {
4920
- const abs = join12(dir, name);
5988
+ const abs = join13(dir, name);
4921
5989
  const rel = prefix ? `${prefix}/${name}` : name;
4922
5990
  if (statSync(abs).isDirectory()) {
4923
5991
  walk(abs, rel);
4924
5992
  } else {
4925
- files[rel] = new Uint8Array(readFileSync8(abs));
5993
+ files[rel] = new Uint8Array(readFileSync9(abs));
4926
5994
  }
4927
5995
  }
4928
5996
  }
@@ -4932,15 +6000,31 @@ function zipToNupkg(buildDir, cwd, packageId, version) {
4932
6000
  files["[Content_Types].xml"] = enc.encode(`<?xml version="1.0" encoding="utf-8"?><Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Default Extension="nuspec" ContentType="application/octet"/><Default Extension="ts" ContentType="application/octet"/><Default Extension="js" ContentType="application/octet"/><Default Extension="json" ContentType="application/octet"/></Types>`);
4933
6001
  files["_rels/.rels"] = enc.encode(`<?xml version="1.0" encoding="utf-8"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Type="http://schemas.microsoft.com/packaging/2010/07/manifest" Target="/${packageId}.nuspec" Id="Rd1"/></Relationships>`);
4934
6002
  const zipped = zipSync(files);
4935
- mkdirSync5(join12(cwd, ".uipath"), { recursive: true });
4936
- const nupkgPath = join12(cwd, ".uipath", `${packageId}.${version}.nupkg`);
4937
- writeFileSync9(nupkgPath, zipped);
6003
+ mkdirSync5(join13(cwd, ".uipath"), { recursive: true });
6004
+ const nupkgPath = join13(cwd, ".uipath", `${packageId}.${version}.nupkg`);
6005
+ writeFileSync10(nupkgPath, zipped);
4938
6006
  return nupkgPath;
4939
6007
  }
4940
6008
  var GUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
4941
6009
  function isGuid(value) {
4942
6010
  return GUID_RE.test(value);
4943
6011
  }
6012
+ var CONTENT_PREFIX = "content/";
6013
+ function describeNupkgProblem(nupkg) {
6014
+ const packedName = (entryName) => entryName.startsWith(CONTENT_PREFIX) ? entryName.slice(CONTENT_PREFIX.length) : null;
6015
+ let entries;
6016
+ try {
6017
+ entries = unzipSync(nupkg, {
6018
+ filter: (file) => {
6019
+ const name = packedName(file.name);
6020
+ return name !== null && affectsDependencyInstall(name);
6021
+ }
6022
+ });
6023
+ } catch {
6024
+ return "is not a valid .nupkg archive.";
6025
+ }
6026
+ return describePackagedInstallProblem(Object.keys(entries).flatMap((name) => packedName(name) ?? []));
6027
+ }
4944
6028
  async function fetchProcessFeeds(baseUrl, org, tenant, token) {
4945
6029
  const url = `${baseUrl}/${org}/${tenant}/orchestrator_/api/PackageFeeds/GetFeeds`;
4946
6030
  const res = await fetch(url, { headers: { Authorization: `Bearer ${token}` } });
@@ -5016,8 +6100,8 @@ Publish cancelled.
5016
6100
  function registerPublishCommand(program2) {
5017
6101
  program2.command("publish").description("Upload the packed .nupkg to an Orchestrator feed. Fetches available feeds and prompts for selection; press ESC to cancel.").option("--url <url>", "UiPath platform base URL (or UIPATH_URL env)").option("--org <org>", "Organization name (or UIPATH_ORGANIZATION_NAME env)").option("--tenant <tenant>", "Tenant name (or UIPATH_TENANT_NAME env)").option("--token <token>", "Access token (or UIPATH_ACCESS_TOKEN env)").option("--feed-id <id>", "Feed ID — skips the interactive picker (for CI use)").action(async (opts) => {
5018
6102
  const cwd = resolve6(".");
5019
- const nupkgDir = join13(cwd, ".uipath");
5020
- if (!existsSync10(nupkgDir)) {
6103
+ const nupkgDir = join14(cwd, ".uipath");
6104
+ if (!existsSync11(nupkgDir)) {
5021
6105
  console.error("No .uipath/ directory found. Run 'uipath-functions pack' first.");
5022
6106
  process.exit(1);
5023
6107
  }
@@ -5026,8 +6110,13 @@ function registerPublishCommand(program2) {
5026
6110
  console.error("No .nupkg found in .uipath/. Run 'uipath-functions pack' first.");
5027
6111
  process.exit(1);
5028
6112
  }
5029
- const nupkgFile = nupkgs.map((f) => ({ name: f, mtime: statSync2(join13(nupkgDir, f)).mtimeMs })).sort((a, b) => b.mtime - a.mtime)[0].name;
5030
- const nupkgPath = join13(nupkgDir, nupkgFile);
6113
+ const nupkgFile = nupkgs.map((f) => ({ name: f, mtime: statSync2(join14(nupkgDir, f)).mtimeMs })).sort((a, b) => b.mtime - a.mtime)[0].name;
6114
+ const nupkgPath = join14(nupkgDir, nupkgFile);
6115
+ const nupkgProblem = describeNupkgProblem(readFileSync10(nupkgPath));
6116
+ if (nupkgProblem) {
6117
+ console.error(`${nupkgFile}: ${nupkgProblem} Run 'uipath-functions pack' again, then publish.`);
6118
+ process.exit(1);
6119
+ }
5031
6120
  const baseUrl = (opts.url ?? process.env["UIPATH_URL"])?.replace(/\/$/, "");
5032
6121
  const org = opts.org ?? process.env["UIPATH_ORGANIZATION_NAME"];
5033
6122
  const tenant = opts.tenant ?? process.env["UIPATH_TENANT_NAME"];
@@ -5073,7 +6162,7 @@ function registerPublishCommand(program2) {
5073
6162
  console.log(`
5074
6163
  Publishing ${nupkgFile} → ${feedLabel}...`);
5075
6164
  const form = new FormData;
5076
- const blob = new Blob([readFileSync9(nupkgPath)], {
6165
+ const blob = new Blob([readFileSync10(nupkgPath)], {
5077
6166
  type: "application/octet-stream"
5078
6167
  });
5079
6168
  form.append("file", blob, nupkgFile);
@@ -5120,11 +6209,11 @@ function resolveStudioMetadata(opts) {
5120
6209
  };
5121
6210
  }
5122
6211
  function readLocalStudioMetadata(projectDir) {
5123
- const path3 = join14(projectDir, STUDIO_METADATA_PATH);
5124
- if (!existsSync11(path3))
6212
+ const path3 = join15(projectDir, STUDIO_METADATA_PATH);
6213
+ if (!existsSync12(path3))
5125
6214
  return null;
5126
6215
  try {
5127
- const parsed = JSON.parse(readFileSync10(path3, "utf-8"));
6216
+ const parsed = JSON.parse(readFileSync11(path3, "utf-8"));
5128
6217
  if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
5129
6218
  return null;
5130
6219
  }
@@ -5134,9 +6223,9 @@ function readLocalStudioMetadata(projectDir) {
5134
6223
  }
5135
6224
  }
5136
6225
  function writeStudioMetadata(projectDir, metadata) {
5137
- const path3 = join14(projectDir, STUDIO_METADATA_PATH);
5138
- mkdirSync6(dirname3(path3), { recursive: true });
5139
- writeFileSync10(path3, JSON.stringify(metadata, null, 2) + `
6226
+ const path3 = join15(projectDir, STUDIO_METADATA_PATH);
6227
+ mkdirSync6(dirname4(path3), { recursive: true });
6228
+ writeFileSync11(path3, JSON.stringify(metadata, null, 2) + `
5140
6229
  `, "utf-8");
5141
6230
  return path3;
5142
6231
  }
@@ -5161,7 +6250,7 @@ function claim(claims, name) {
5161
6250
  }
5162
6251
  function authorFromPackageJson(projectDir) {
5163
6252
  try {
5164
- const pkg = JSON.parse(readFileSync10(join14(projectDir, "package.json"), "utf-8"));
6253
+ const pkg = JSON.parse(readFileSync11(join15(projectDir, "package.json"), "utf-8"));
5165
6254
  if (typeof pkg.author === "string")
5166
6255
  return pkg.author.trim();
5167
6256
  return (pkg.author?.email ?? pkg.author?.name ?? "").trim();
@@ -5189,7 +6278,7 @@ var IGNORE_FILES = new Set([
5189
6278
  ".gitignore",
5190
6279
  ".uipathignore",
5191
6280
  ".gitkeep",
5192
- ".npmrc"
6281
+ REGISTRY_CONFIG_FILE
5193
6282
  ]);
5194
6283
  var TEXT_EXTS = new Set([
5195
6284
  ".ts",
@@ -5229,7 +6318,7 @@ function collectLocalFiles(projectDir) {
5229
6318
  continue;
5230
6319
  if (name.startsWith(".") && IGNORE_FILES.has(name))
5231
6320
  continue;
5232
- const abs = join15(dir, name);
6321
+ const abs = join16(dir, name);
5233
6322
  const stat2 = statSync3(abs);
5234
6323
  if (stat2.isDirectory()) {
5235
6324
  walk(abs);
@@ -5320,7 +6409,7 @@ async function performStructuralMigration(cfg, lockKey, plan) {
5320
6409
  const form = new FormData;
5321
6410
  form.append("DeletedResources", JSON.stringify(plan.filesToDelete.map((f) => f.id)));
5322
6411
  plan.filesToUpload.forEach((f, i2) => {
5323
- const content = readFileSync11(f.absolutePath);
6412
+ const content = readFileSync12(f.absolutePath);
5324
6413
  const fileName = f.remotePath.split("/").at(-1);
5325
6414
  form.append(`AddedResources[${i2}].Content`, new Blob([content]), fileName);
5326
6415
  const parentPath = f.remotePath.includes("/") ? f.remotePath.slice(0, f.remotePath.lastIndexOf("/")) : "";
@@ -5328,7 +6417,7 @@ async function performStructuralMigration(cfg, lockKey, plan) {
5328
6417
  form.append(`AddedResources[${i2}].ParentPath`, parentPath);
5329
6418
  });
5330
6419
  plan.filesToUpdate.forEach(({ local, remoteId }, i2) => {
5331
- const content = readFileSync11(local.absolutePath);
6420
+ const content = readFileSync12(local.absolutePath);
5332
6421
  const fileName = local.remotePath.split("/").at(-1);
5333
6422
  form.append(`ModifiedResources[${i2}].Content`, new Blob([content]), fileName);
5334
6423
  form.append(`ModifiedResources[${i2}].Id`, remoteId);
@@ -5380,7 +6469,7 @@ async function computePlan(cfg, localFiles, structure) {
5380
6469
  plan.filesToUpload.push(lf);
5381
6470
  return;
5382
6471
  }
5383
- const localContent = readFileSync11(lf.absolutePath);
6472
+ const localContent = readFileSync12(lf.absolutePath);
5384
6473
  const localHash = computeHash(localContent, lf.absolutePath);
5385
6474
  const remoteContent = await downloadFile(cfg, remote.id);
5386
6475
  const remoteHash = computeHash(remoteContent, lf.absolutePath);
@@ -5449,9 +6538,9 @@ async function pushToStudio(cfg, projectDir, localFiles, onProgress) {
5449
6538
  }
5450
6539
  }
5451
6540
  function readPushCredentials(opts) {
5452
- const envPath = join15(process.cwd(), ".env");
5453
- if (existsSync12(envPath)) {
5454
- for (const line of readFileSync11(envPath, "utf-8").split(`
6541
+ const envPath = join16(process.cwd(), ".env");
6542
+ if (existsSync13(envPath)) {
6543
+ for (const line of readFileSync12(envPath, "utf-8").split(`
5455
6544
  `)) {
5456
6545
  if (line.trimStart().startsWith("#"))
5457
6546
  continue;
@@ -5477,21 +6566,23 @@ function readPushCredentials(opts) {
5477
6566
  function registerPushCommand(program2) {
5478
6567
  program2.command("push").description("Sync the project to Studio Web (generate entry-points, diff, upload changed files).").option("--url <url>", "UiPath base URL (or UIPATH_URL in env)").option("--org <org>", "Organization name (or UIPATH_ORGANIZATION_NAME in env)").option("--tenant <tenant>", "Tenant name (or UIPATH_TENANT_NAME in env)").option("--token <token>", "Access token (or UIPATH_ACCESS_TOKEN in env)").option("--project-id <id>", "Studio Web project ID — mandatory (or UIPATH_PROJECT_ID in env)").action(async (opts) => {
5479
6568
  const cwd = resolve7(".");
5480
- const uipathJsonPath = join16(cwd, "uipath.json");
5481
- if (!existsSync13(uipathJsonPath)) {
6569
+ const uipathJsonPath = join17(cwd, "uipath.json");
6570
+ if (!existsSync14(uipathJsonPath)) {
5482
6571
  console.error("No uipath.json found. Run 'uipath-functions init' first.");
5483
6572
  process.exit(1);
5484
6573
  }
5485
6574
  if (syncFunctionsMap(cwd)) {
5486
6575
  console.log("Updated functions map in uipath.json.");
5487
6576
  }
5488
- const uipathJson = JSON.parse(readFileSync12(uipathJsonPath, "utf-8"));
6577
+ const uipathJson = JSON.parse(readFileSync13(uipathJsonPath, "utf-8"));
5489
6578
  if (!uipathJson.functions || Object.keys(uipathJson.functions).length === 0) {
5490
6579
  console.error("No functions defined in uipath.json.");
5491
6580
  process.exit(1);
5492
6581
  }
5493
- if (!existsSync13(join16(cwd, "node_modules"))) {
5494
- console.error("node_modules not found. Run 'npm install' first.");
6582
+ try {
6583
+ assertReadyToPackage(cwd);
6584
+ } catch (err2) {
6585
+ console.error(err2 instanceof Error ? err2.message : String(err2));
5495
6586
  process.exit(1);
5496
6587
  }
5497
6588
  const creds = readPushCredentials(opts);
@@ -5502,14 +6593,18 @@ Create the project in Studio Web first to get UIPATH_PROJECT_ID.`);
5502
6593
  }
5503
6594
  if (!uipathJson.projectId) {
5504
6595
  uipathJson.projectId = creds.projectId;
5505
- writeFileSync11(uipathJsonPath, JSON.stringify(uipathJson, null, 2) + `
6596
+ writeFileSync12(uipathJsonPath, JSON.stringify(uipathJson, null, 2) + `
5506
6597
  `, "utf-8");
5507
6598
  }
5508
6599
  console.log("Generating entry-points.json...");
5509
6600
  const extraction = extractProject(uipathJson.functions, cwd);
6601
+ reportDiagnosticsOrExit(extraction.diagnostics);
5510
6602
  const aggregatorPath = generateAggregator(uipathJson.functions, cwd, "serve", toDerivedContracts(extraction.functions));
6603
+ if (manifestNeedsExecution(extraction, uipathJson.functions)) {
6604
+ installServerRunner(cwd);
6605
+ }
5511
6606
  try {
5512
- const result = await writeManifest(extraction, aggregatorPath, cwd);
6607
+ const result = await writeManifest(extraction, aggregatorPath, cwd, uipathJson.functions);
5513
6608
  console.log(` ${result.count} function(s) exported — ${result.static ? "extracted statically" : "executed to extract"}.`);
5514
6609
  } catch (err2) {
5515
6610
  console.error(err2 instanceof Error ? err2.message : String(err2));
@@ -5544,7 +6639,7 @@ function resolveTargetFile(cwd, opts) {
5544
6639
  return null;
5545
6640
  const match = entry.match(/^(.*?):([A-Za-z_$][\w$]*)$/);
5546
6641
  const filePart = match ? match[1] : entry;
5547
- const abs = isAbsolute2(filePart) ? filePart : resolve8(cwd, filePart);
6642
+ const abs = isAbsolute3(filePart) ? filePart : resolve8(cwd, filePart);
5548
6643
  return relative3(cwd, abs);
5549
6644
  }
5550
6645
  function writeDerivedContract(cwd, opts) {
@@ -5555,9 +6650,9 @@ function writeDerivedContract(cwd, opts) {
5555
6650
  const derived = opts.production ? readBakedContract(relFile, cwd) : deriveRunContract(relFile, cwd);
5556
6651
  if (!derived)
5557
6652
  return "";
5558
- const outPath = join17(cwd, DERIVED_CONTRACT_FILE);
5559
- mkdirSync7(join17(cwd, ".uipath/run"), { recursive: true });
5560
- writeFileSync12(outPath, JSON.stringify(derived), "utf-8");
6653
+ const outPath = join18(cwd, DERIVED_CONTRACT_FILE);
6654
+ mkdirSync7(join18(cwd, ".uipath/run"), { recursive: true });
6655
+ writeFileSync13(outPath, JSON.stringify(derived), "utf-8");
5561
6656
  return outPath;
5562
6657
  } catch (err2) {
5563
6658
  console.error("contract preparation skipped: " + (err2 instanceof Error ? err2.message : String(err2)));
@@ -5565,7 +6660,7 @@ function writeDerivedContract(cwd, opts) {
5565
6660
  }
5566
6661
  }
5567
6662
  function readFunctionsMap(cwd) {
5568
- const parsed = readJsonIfExists2(join17(cwd, "uipath.json"));
6663
+ const parsed = readJsonIfExists2(join18(cwd, "uipath.json"));
5569
6664
  const functions = isRecord(parsed) ? parsed.functions : undefined;
5570
6665
  if (!isRecord(functions))
5571
6666
  return {};
@@ -5580,32 +6675,58 @@ function isRecord(value) {
5580
6675
  return typeof value === "object" && value !== null;
5581
6676
  }
5582
6677
  function readJsonIfExists2(path3) {
5583
- if (!existsSync14(path3))
6678
+ if (!existsSync15(path3))
5584
6679
  return null;
5585
6680
  try {
5586
- return JSON.parse(readFileSync13(path3, "utf-8"));
6681
+ return JSON.parse(readFileSync14(path3, "utf-8"));
5587
6682
  } catch {
5588
6683
  return null;
5589
6684
  }
5590
6685
  }
5591
- var RUN_FUNCTION_CALL = `runFunction({ entrypoint: entrypoint || undefined, function: fn || undefined, input: input || undefined, inputFile: inputFile || undefined, context: context || undefined, contextFile: contextFile || undefined, derivedFile: derivedFile || undefined })`;
5592
- var DENO_ENTRY_CONTENT = `import { runFunction } from "@uipath/coded-functions-js-runtime";
6686
+ var RUN_FUNCTION_CALL = `runtime.runFunction({ entrypoint: entrypoint || undefined, function: fn || undefined, input: input || undefined, inputFile: inputFile || undefined, context: context || undefined, contextFile: contextFile || undefined, derivedFile: derivedFile || undefined, ...traced })`;
6687
+ var TRACED_OPTIONS = `let traced = {};
6688
+ if (env.UIPATH_TRACE_STORE === "1") {
6689
+ if (!runtime.traceStoreOptionsFromEnv) {
6690
+ console.error("trace store: the installed @uipath/coded-functions-js-runtime predates --trace-store (needs >= 0.9.1); spans will not be posted.");
6691
+ } else {
6692
+ traced = runtime.traceStoreOptionsFromEnv(env, (detail) => console.error(\`trace store: ingest failed: \${detail}\`)) ?? {};
6693
+ if (!traced.onSpans) { console.error("trace store: incomplete UIPATH_* trace scope/token; spans will not be posted."); }
6694
+ }
6695
+ }`;
6696
+ var DENO_ENTRY_CONTENT = `import * as runtime from "@uipath/coded-functions-js-runtime";
5593
6697
  const [entrypoint, fn, input, inputFile, context, contextFile, derivedFile] = Deno.args;
6698
+ const env = Deno.env.toObject();
6699
+ ${TRACED_OPTIONS}
5594
6700
  const exitCode = await ${RUN_FUNCTION_CALL};
5595
6701
  Deno.exit(exitCode);
5596
6702
  `;
5597
- var NODE_ENTRY_CONTENT = `import { runFunction } from "@uipath/coded-functions-js-runtime";
6703
+ var NODE_ENTRY_CONTENT = `import * as runtime from "@uipath/coded-functions-js-runtime";
5598
6704
  const [entrypoint, fn, input, inputFile, context, contextFile, derivedFile] = process.argv.slice(2);
6705
+ const env = process.env;
6706
+ ${TRACED_OPTIONS}
5599
6707
  ${RUN_FUNCTION_CALL}
5600
6708
  .then((code) => process.exit(code));
5601
6709
  `;
6710
+ var DEFAULT_INSPECTOR_ENDPOINT = "127.0.0.1:9229";
5602
6711
  function registerRunCommand(program2) {
5603
- program2.command("run").description("Execute a single coded function once (one-shot job) and report the result.").option("--runtime <runtime>", "Runtime: node (default) or deno", "node").option("--entrypoint <path>", "Path to the function file").option("--function <name>", "Function name resolved via uipath.json").option("--input <json>", "JSON input payload", "{}").option("--input-file <path>", "Path to a JSON input file (takes priority over --input)").option("--context <json>", "JSON runtime-context payload (used when --context-file is absent)").option("--context-file <path>", "Path to the runtime-context JSON file (takes priority over --context)").option("--production", "Run under production context; skip the .uipath/server-runner install when it already exists.").action((opts) => {
6712
+ program2.command("run").description("Execute a single coded function once (one-shot job) and report the result.").option("--runtime <runtime>", "Runtime: node (default) or deno", "node").option("--entrypoint <path>", "Path to the function file").option("--function <name>", "Function name resolved via uipath.json").option("--input <json>", "JSON input payload", "{}").option("--input-file <path>", "Path to a JSON input file (takes priority over --input)").option("--context <json>", "JSON runtime-context payload (used when --context-file is absent)").option("--context-file <path>", "Path to the runtime-context JSON file (takes priority over --context)").option("--production", "Run under production context; skip the .uipath/server-runner install when it already exists.").option("--inspect [endpoint]", `Open the V8 inspector on host:port while the function runs (default ${DEFAULT_INSPECTOR_ENDPOINT})`).option("--inspect-wait [endpoint]", `Open the V8 inspector on host:port and wait for a debugger to attach before executing (default ${DEFAULT_INSPECTOR_ENDPOINT})`).option("--trace-store", "Post the run's trace spans to the platform trace store (scope from UIPATH_* env vars + UIPATH_ACCESS_TOKEN)").action(async (opts) => {
5604
6713
  const cwd = resolve9(".");
5605
- const skipInstall = opts.production === true && existsSync15(join18(cwd, SERVER_RUNNER_DIR));
6714
+ if (opts.inspect && opts.inspectWait) {
6715
+ console.error("Provide only one of --inspect or --inspect-wait.");
6716
+ process.exit(1);
6717
+ }
6718
+ if (opts.production !== true) {
6719
+ try {
6720
+ assertDependenciesInstalled(cwd);
6721
+ } catch (err2) {
6722
+ console.error(err2 instanceof Error ? err2.message : String(err2));
6723
+ process.exit(1);
6724
+ }
6725
+ }
6726
+ const skipInstall = opts.production === true && existsSync16(join19(cwd, SERVER_RUNNER_DIR));
5606
6727
  if (!skipInstall) {
5607
6728
  try {
5608
- setupRunDependencies(cwd);
6729
+ installServerRunner(cwd);
5609
6730
  } catch (err2) {
5610
6731
  console.error(err2 instanceof Error ? err2.message : String(err2));
5611
6732
  process.exit(1);
@@ -5620,58 +6741,135 @@ function registerRunCommand(program2) {
5620
6741
  }
5621
6742
  });
5622
6743
  }
5623
- function denoPermissionFlags(cwd, production) {
6744
+ function inspectorFlags(opts) {
6745
+ const endpoint = (value) => value === true ? DEFAULT_INSPECTOR_ENDPOINT : value;
6746
+ if (opts.inspectWait) {
6747
+ return [`--inspect-wait=${endpoint(opts.inspectWait)}`];
6748
+ }
6749
+ if (opts.inspect) {
6750
+ return [`--inspect=${endpoint(opts.inspect)}`];
6751
+ }
6752
+ return [];
6753
+ }
6754
+ function runEnv(opts, base = process.env) {
6755
+ const env = { ...base };
6756
+ delete env.UIPATH_TRACE_STORE;
6757
+ return opts.traceStore ? { ...env, UIPATH_TRACE_STORE: "1" } : env;
6758
+ }
6759
+ function denoPermissionFlags(cwd, production, env = process.env) {
5624
6760
  if (!production) {
5625
6761
  return ["--allow-env", "--allow-net", "--allow-read", "--allow-write", "--allow-sys", "--allow-run"];
5626
6762
  }
5627
- const jobDir = process.env.JOB_WORKING_DIRECTORY ?? cwd;
6763
+ const jobDir = env.JOB_WORKING_DIRECTORY ?? cwd;
6764
+ const endpoint = env.UIPATH_JOB_API_ENDPOINT_PATH;
6765
+ const writeTargets = endpoint ? [jobDir, endpoint] : [jobDir];
5628
6766
  return [
5629
6767
  "--allow-env",
5630
6768
  "--allow-net",
5631
6769
  "--allow-read",
5632
- `--allow-write=${jobDir}`,
6770
+ `--allow-write=${writeTargets.join(",")}`,
5633
6771
  "--allow-sys=hostname,cpus,osRelease,systemMemoryInfo"
5634
6772
  ];
5635
6773
  }
6774
+ function readIfPresent(path3) {
6775
+ try {
6776
+ return readFileSync15(path3, "utf-8");
6777
+ } catch {
6778
+ return;
6779
+ }
6780
+ }
6781
+ function removeQuietly(path3) {
6782
+ try {
6783
+ rmSync2(path3, { force: true });
6784
+ return true;
6785
+ } catch {
6786
+ return false;
6787
+ }
6788
+ }
5636
6789
  function writeRunEntry(cwd, fileName, content) {
5637
- const serverRunnerDir = join18(cwd, SERVER_RUNNER_DIR);
6790
+ const serverRunnerDir = join19(cwd, SERVER_RUNNER_DIR);
5638
6791
  mkdirSync8(serverRunnerDir, { recursive: true });
5639
- const entryPath = join18(serverRunnerDir, fileName);
5640
- if (!existsSync15(entryPath)) {
5641
- const tmp = `${entryPath}.${process.pid}.tmp`;
5642
- writeFileSync13(tmp, content, "utf-8");
6792
+ const entryPath = join19(serverRunnerDir, fileName);
6793
+ if (readIfPresent(entryPath) === content) {
6794
+ return entryPath;
6795
+ }
6796
+ const tmp = `${entryPath}.${process.pid}.tmp`;
6797
+ try {
6798
+ writeFileSync14(tmp, content, "utf-8");
5643
6799
  renameSync(tmp, entryPath);
6800
+ } catch (err2) {
6801
+ removeQuietly(tmp);
6802
+ if (!existsSync16(entryPath)) {
6803
+ throw err2;
6804
+ }
6805
+ if (readIfPresent(entryPath) !== content) {
6806
+ console.error(`Warning: could not refresh ${entryPath} (${err2 instanceof Error ? err2.message : String(err2)}); running the existing entry.`);
6807
+ }
5644
6808
  }
5645
6809
  return entryPath;
5646
6810
  }
5647
6811
  function runArgs(opts) {
5648
6812
  return [opts.entrypoint ?? "", opts.function ?? "", opts.input ?? "{}", opts.inputFile ?? "", opts.context ?? "", opts.contextFile ?? "", opts.derivedFile ?? ""];
5649
6813
  }
5650
- function onChildExit(proc, missingMessage) {
6814
+ var SIGNAL_EXIT_GRACE_MS = 2000;
6815
+ function onChildExit(proc, missingMessage, forwardSignals) {
6816
+ let forwarded;
6817
+ if (forwardSignals && process.platform !== "win32") {
6818
+ for (const signal of ["SIGTERM", "SIGINT", "SIGHUP"]) {
6819
+ process.once(signal, () => {
6820
+ forwarded = signal;
6821
+ proc.kill(signal);
6822
+ setTimeout(() => process.kill(process.pid, signal), SIGNAL_EXIT_GRACE_MS).unref();
6823
+ });
6824
+ }
6825
+ }
5651
6826
  proc.on("error", (err2) => {
5652
6827
  console.error(err2.code === "ENOENT" ? missingMessage : err2);
5653
6828
  process.exit(1);
5654
6829
  });
5655
- proc.on("exit", (code) => process.exit(code ?? 0));
6830
+ proc.on("exit", (code, signal) => {
6831
+ if (forwarded) {
6832
+ process.kill(process.pid, forwarded);
6833
+ return;
6834
+ }
6835
+ process.exit(code ?? (signal ? 1 : 0));
6836
+ });
5656
6837
  }
5657
6838
  function runDeno(cwd, opts) {
5658
6839
  const entryPath = writeRunEntry(cwd, "run-deno.ts", DENO_ENTRY_CONTENT);
5659
- const deno = process.env.DENO_BINARY ?? (process.platform === "win32" ? "deno.exe" : "deno");
6840
+ const deno = resolveDeno();
5660
6841
  const denoArgs = [
5661
6842
  "run",
5662
6843
  ...denoPermissionFlags(cwd, opts.production),
5663
6844
  "--no-check",
6845
+ ...inspectorFlags(opts),
5664
6846
  entryPath,
5665
6847
  ...runArgs(opts)
5666
6848
  ];
5667
- const proc = spawn2(deno, denoArgs, { cwd, env: process.env, stdio: "inherit" });
5668
- onChildExit(proc, "Deno not found. Ensure DENO_BINARY is set or deno is on PATH.");
6849
+ const proc = spawn2(deno, denoArgs, { cwd, env: runEnv(opts), stdio: "inherit" });
6850
+ onChildExit(proc, "Deno not found. Ensure DENO_BINARY is set or deno is on PATH.", inspectorFlags(opts).length > 0);
6851
+ }
6852
+ function nodeCommand(cwd, inspector) {
6853
+ const loader = inspector.length > 0 ? resolveTsxLoader(cwd) : undefined;
6854
+ if (loader) {
6855
+ return ["node", [...inspector, ...loader]];
6856
+ }
6857
+ const [bin, tsxPrefix] = resolveTsx(cwd);
6858
+ return [bin, [...tsxPrefix, ...inspector]];
5669
6859
  }
5670
6860
  function runNode(cwd, opts) {
5671
6861
  const entryPath = writeRunEntry(cwd, "run-node.ts", NODE_ENTRY_CONTENT);
5672
- const [bin, tsxPrefix] = resolveTsx(cwd);
5673
- const proc = spawn2(bin, [...tsxPrefix, entryPath, ...runArgs(opts)], { cwd, env: process.env, stdio: "inherit" });
5674
- onChildExit(proc, "tsx not found. Run 'uipath-functions setup'.");
6862
+ const inspector = inspectorFlags(opts);
6863
+ let bin;
6864
+ let prefix;
6865
+ try {
6866
+ [bin, prefix] = nodeCommand(cwd, inspector);
6867
+ } catch (err2) {
6868
+ console.error(err2 instanceof Error ? err2.message : String(err2));
6869
+ process.exit(1);
6870
+ }
6871
+ const proc = spawn2(bin, [...prefix, entryPath, ...runArgs(opts)], { cwd, env: runEnv(opts), stdio: "inherit" });
6872
+ onChildExit(proc, "node not found. Run 'uipath-functions setup'.", inspector.length > 0);
5675
6873
  }
5676
6874
  function registerInvokeCommand(program2) {
5677
6875
  program2.command("invoke <path>").description("Invoke a function against the local serve endpoint over HTTP (dev convenience). Pass the function's HTTP path, e.g. /hello.").option("--port <port>", "Port the local server is running on", "7070").option("--input <json>", "JSON input payload", "{}").action(async (path3, opts) => {
@@ -5707,8 +6905,15 @@ ${err2.message}`);
5707
6905
  });
5708
6906
  }
5709
6907
  function registerPrepareRuntimeCommand(program2) {
5710
- program2.command("runtime-install").description("Create a runner folder with a package.json and install runtime dependencies.").requiredOption("--path <folder>", "Target folder to create and install into").action((opts) => {
6908
+ program2.command("runtime-install").description("Create a runner folder with a package.json and install runtime dependencies.").requiredOption("--path <folder>", "Target folder to create and install into").addOption(new Option("--package-manager <name-or-path>", "Install with this package manager instead of the folder's own").hideHelp()).action((opts) => {
5711
6909
  const runnerDir = resolve10(opts.path);
6910
+ let manager;
6911
+ try {
6912
+ manager = resolvePackageManager(runnerDir, opts.packageManager);
6913
+ } catch (err2) {
6914
+ console.error(err2 instanceof Error ? err2.message : String(err2));
6915
+ process.exit(1);
6916
+ }
5712
6917
  mkdirSync9(runnerDir, { recursive: true });
5713
6918
  const pkg = {
5714
6919
  name: "runner",
@@ -5717,37 +6922,30 @@ function registerPrepareRuntimeCommand(program2) {
5717
6922
  dependencies: {
5718
6923
  "@uipath/coded-functions-js-runtime": RUNTIME_VERSION,
5719
6924
  "@uipath/coreipc": COREIPC_VERSION,
5720
- "@hono/node-server": HONO_NODE_VERSION,
5721
6925
  tsx: TSX_VERSION,
5722
6926
  "@microsoft/signalr": SIGNALR_VERSION,
5723
6927
  "@jridgewell/trace-mapping": TRACE_MAPPING_VERSION
5724
6928
  }
5725
6929
  };
5726
- const pkgPath = join19(runnerDir, "package.json");
5727
- writeFileSync14(pkgPath, JSON.stringify(pkg, null, 2), "utf-8");
6930
+ const pkgPath = join20(runnerDir, "package.json");
6931
+ writeFileSync15(pkgPath, JSON.stringify(pkg, null, 2), "utf-8");
5728
6932
  console.log(`Wrote ${pkgPath}`);
5729
- if (process.env["GITHUB_TOKEN"]) {
5730
- writeFileSync14(join19(runnerDir, ".npmrc"), NPM_RC, "utf-8");
5731
- }
6933
+ writeRunnerRegistryConfig(runnerDir);
5732
6934
  console.log("Installing dependencies...");
5733
- const { cmd, args } = getInstallCommand(true);
5734
- const result = spawnSync4(cmd, args, {
5735
- cwd: runnerDir,
5736
- stdio: "inherit",
5737
- shell: process.platform === "win32"
5738
- });
5739
- if (result.status !== 0) {
5740
- console.error(`${cmd} install failed in ${runnerDir}.`);
6935
+ try {
6936
+ manager.runInstall(runnerDir, { production: true });
6937
+ } catch (err2) {
6938
+ console.error(err2 instanceof Error ? err2.message : String(err2));
5741
6939
  process.exit(1);
5742
6940
  }
5743
6941
  console.log(`Runner ready at ${runnerDir}`);
5744
6942
  });
5745
6943
  }
5746
6944
  function registerInstallServerCommand(program2) {
5747
- program2.command("install-server").description("Prepare runtime dependencies for running the function server.").option("--template <path>", "Path to the server-runner template folder").action((opts) => {
6945
+ program2.command("install-server").description("Provision a packed project: install the server-runner and, when node_modules is missing, its production dependencies.").option("--template <path>", "Path to the server-runner template folder").addOption(new Option("--package-manager <name-or-path>", "Install with this package manager instead of the project's own").hideHelp()).action((opts) => {
5748
6946
  const cwd = resolve11(".");
5749
6947
  try {
5750
- setupRunDependencies(cwd, opts.template);
6948
+ provisionPackage(cwd, opts.template, opts.packageManager);
5751
6949
  } catch (err2) {
5752
6950
  console.error(err2 instanceof Error ? err2.message : String(err2));
5753
6951
  process.exit(1);
@@ -5760,27 +6958,27 @@ var DEFAULT_INSPECT = "127.0.0.1:9231";
5760
6958
  var BRIDGE_FILE = "debug-bridge.ts";
5761
6959
  var WORKER_FILE = "debug-job-worker.ts";
5762
6960
  function resolveDebugAssetsDir(moduleUrl) {
5763
- const moduleDir = dirname4(fileURLToPath2(moduleUrl));
6961
+ const moduleDir = dirname5(fileURLToPath2(moduleUrl));
5764
6962
  const candidates = [
5765
- join20(moduleDir, "deno-runtime", "debug"),
5766
- join20(moduleDir, "..", "deno-runtime", "debug"),
5767
- join20(moduleDir, "..", "..", "deno-runtime", "debug")
6963
+ join21(moduleDir, "deno-runtime", "debug"),
6964
+ join21(moduleDir, "..", "deno-runtime", "debug"),
6965
+ join21(moduleDir, "..", "..", "deno-runtime", "debug")
5768
6966
  ];
5769
6967
  for (const candidate of candidates) {
5770
- if (existsSync16(join20(candidate, BRIDGE_FILE))) {
6968
+ if (existsSync17(join21(candidate, BRIDGE_FILE))) {
5771
6969
  return candidate;
5772
6970
  }
5773
6971
  }
5774
6972
  throw new Error(`debug assets not found (looked in: ${candidates.join(", ")})`);
5775
6973
  }
5776
6974
  function stageDebugAssets(cwd) {
5777
- const stagedDir = join20(cwd, SERVER_RUNNER_DIR, "debug");
6975
+ const stagedDir = join21(cwd, SERVER_RUNNER_DIR, "debug");
5778
6976
  mkdirSync10(stagedDir, { recursive: true });
5779
6977
  const assetsDir = resolveDebugAssetsDir(import.meta.url);
5780
6978
  for (const entry of readdirSync6(assetsDir)) {
5781
- writeFileSync15(join20(stagedDir, entry), readFileSync14(join20(assetsDir, entry), "utf-8"), "utf-8");
6979
+ writeFileSync16(join21(stagedDir, entry), readFileSync16(join21(assetsDir, entry), "utf-8"), "utf-8");
5782
6980
  }
5783
- return { bridge: join20(stagedDir, BRIDGE_FILE), worker: join20(stagedDir, WORKER_FILE) };
6981
+ return { bridge: join21(stagedDir, BRIDGE_FILE), worker: join21(stagedDir, WORKER_FILE) };
5784
6982
  }
5785
6983
  function buildBridgeSpawn(bridgePath, workerEntry, opts) {
5786
6984
  const modeEnv = opts.runAsJob ? {
@@ -5823,7 +7021,7 @@ function buildBridgeSpawn(bridgePath, workerEntry, opts) {
5823
7021
  };
5824
7022
  }
5825
7023
  function registerDebugCommand(program2) {
5826
- program2.command("debug").description("Debug a coded function: bridges StudioWeb's SignalR DebugHub to the Deno V8 inspector for line breakpoints.").option("--session <id>", "Debug session id / jobKey (must match the FE debug hub group)").option("--hub <url>", "SignalR DebugHub relay URL", DEFAULT_HUB).option("--run-as-job", "Debug a one-shot coded function job without an HTTP server").option("--entrypoint <path>", "Path to the function file (run-as-job mode)").option("--function <name>", "Which function from uipath.json to debug (default: the first)").option("--port <port>", "Port the debug server listens on", String(DEFAULT_PORT2)).option("--input <json>", "JSON input passed to the function's main method", "{}").option("--input-file <path>", "Path to a JSON input file (takes priority over --input)").option("--context <json>", "JSON runtime-context payload (used when --context-file is absent)").option("--context-file <path>", "Path to the runtime-context JSON file (takes priority over --context)").option("--production", "Use the preinstalled server-runner dependencies when available").option("--inspect <endpoint>", "V8 inspector endpoint for the spawned runner", DEFAULT_INSPECT).option("--token <jwt>", "Bearer token for a remote SignalR hub. Falls back to env HUB_ACCESS_TOKEN when omitted; leave both unset for an unauthenticated local hub.", "").action(async (opts) => {
7024
+ program2.command("debug").description("Debug a coded function: bridges StudioWeb's SignalR DebugHub to the Deno V8 inspector for line breakpoints. Without Deno, --run-as-job falls back to a plain Node run of the same job.").option("--session <id>", "Debug session id / jobKey (must match the FE debug hub group)").option("--hub <url>", "SignalR DebugHub relay URL", DEFAULT_HUB).option("--run-as-job", "Debug a one-shot coded function job without an HTTP server").option("--entrypoint <path>", "Path to the function file (run-as-job mode)").option("--function <name>", "Which function from uipath.json to debug (default: the first)").option("--port <port>", "Port the debug server listens on", String(DEFAULT_PORT2)).option("--input <json>", "JSON input passed to the function's main method", "{}").option("--input-file <path>", "Path to a JSON input file (takes priority over --input)").option("--context <json>", "JSON runtime-context payload (used when --context-file is absent)").option("--context-file <path>", "Path to the runtime-context JSON file (takes priority over --context)").option("--production", "Use the preinstalled server-runner dependencies when available").option("--inspect <endpoint>", "V8 inspector endpoint for the spawned runner", DEFAULT_INSPECT).option("--token <jwt>", "Bearer token for a remote SignalR hub. Falls back to env HUB_ACCESS_TOKEN when omitted; leave both unset for an unauthenticated local hub.", "").action(async (opts) => {
5827
7025
  const cwd = resolve12(".");
5828
7026
  const runAsJob = opts.runAsJob === true;
5829
7027
  if (opts.entrypoint && !runAsJob) {
@@ -5838,17 +7036,17 @@ function registerDebugCommand(program2) {
5838
7036
  console.error("Provide only one of --entrypoint or --function.");
5839
7037
  process.exit(1);
5840
7038
  }
5841
- const uipathJsonPath = join20(cwd, "uipath.json");
5842
- if (!existsSync16(uipathJsonPath) && (!runAsJob || !opts.entrypoint)) {
7039
+ const uipathJsonPath = join21(cwd, "uipath.json");
7040
+ if (!existsSync17(uipathJsonPath) && (!runAsJob || !opts.entrypoint)) {
5843
7041
  console.error("No uipath.json found. Run 'uipath-functions init' first.");
5844
7042
  process.exit(1);
5845
7043
  }
5846
- if (!opts.entrypoint && existsSync16(uipathJsonPath) && syncFunctionsMap(cwd)) {
7044
+ if (!opts.entrypoint && existsSync17(uipathJsonPath) && syncFunctionsMap(cwd)) {
5847
7045
  console.log("Updated functions map in uipath.json.");
5848
7046
  }
5849
7047
  const functions = {};
5850
- if (existsSync16(uipathJsonPath)) {
5851
- const uipathJson = JSON.parse(readFileSync14(uipathJsonPath, "utf-8"));
7048
+ if (existsSync17(uipathJsonPath)) {
7049
+ const uipathJson = JSON.parse(readFileSync16(uipathJsonPath, "utf-8"));
5852
7050
  if (typeof uipathJson === "object" && uipathJson !== null && "functions" in uipathJson && typeof uipathJson.functions === "object" && uipathJson.functions !== null) {
5853
7051
  for (const [name, entry] of Object.entries(uipathJson.functions)) {
5854
7052
  if (typeof entry === "string") {
@@ -5885,15 +7083,40 @@ function registerDebugCommand(program2) {
5885
7083
  }
5886
7084
  const fnName = opts.entrypoint ? "" : opts.function ?? names[0] ?? "";
5887
7085
  const port = runAsJob ? undefined : parseInt(opts.port, 10) || DEFAULT_PORT2;
5888
- const skipInstall = opts.production === true && existsSync16(join20(cwd, SERVER_RUNNER_DIR));
7086
+ if (opts.production !== true) {
7087
+ try {
7088
+ assertDependenciesInstalled(cwd);
7089
+ } catch (err2) {
7090
+ console.error(err2 instanceof Error ? err2.message : String(err2));
7091
+ process.exit(1);
7092
+ }
7093
+ }
7094
+ const skipInstall = opts.production === true && existsSync17(join21(cwd, SERVER_RUNNER_DIR));
5889
7095
  if (!skipInstall) {
5890
7096
  try {
5891
- setupRunDependencies(cwd);
7097
+ installServerRunner(cwd);
5892
7098
  } catch (err2) {
5893
7099
  console.error(err2 instanceof Error ? err2.message : String(err2));
5894
7100
  process.exit(1);
5895
7101
  }
5896
7102
  }
7103
+ if (!denoAvailable()) {
7104
+ if (!runAsJob) {
7105
+ console.error("Deno not found, and the HTTP debug bridge needs it. Install it with 'uipath-functions setup --runtime deno', or debug a single invocation with --run-as-job.");
7106
+ process.exit(1);
7107
+ }
7108
+ console.error("Deno not found: running the job under Node instead, without breakpoints or the debug hub bridge. Install Deno with 'uipath-functions setup --runtime deno' for a full debug session.");
7109
+ const selector = { entrypoint: opts.entrypoint, function: fnName || undefined, production: opts.production };
7110
+ runNode(cwd, {
7111
+ ...selector,
7112
+ input: inputJson,
7113
+ inputFile: opts.inputFile,
7114
+ context: opts.context,
7115
+ contextFile: opts.contextFile,
7116
+ derivedFile: writeDerivedContract(cwd, selector)
7117
+ });
7118
+ return;
7119
+ }
5897
7120
  const staged = stageDebugAssets(cwd);
5898
7121
  let workerEntry;
5899
7122
  let derivedFile = "";
@@ -5901,7 +7124,9 @@ function registerDebugCommand(program2) {
5901
7124
  derivedFile = writeDerivedContract(cwd, { entrypoint: opts.entrypoint, function: opts.function, production: opts.production });
5902
7125
  workerEntry = staged.worker;
5903
7126
  } else {
5904
- const derived = deriveMarkerContracts(functions, cwd);
7127
+ const extraction = extractProject(functions, cwd);
7128
+ reportDiagnosticsOrExit(extraction.diagnostics);
7129
+ const derived = toDerivedContracts(extraction.functions);
5905
7130
  const aggregatorPath = generateAggregator(functions, cwd, "serve", derived);
5906
7131
  workerEntry = writeDenoServeEntry(cwd, port, aggregatorPath);
5907
7132
  freePort(port);
@@ -5920,13 +7145,13 @@ function registerDebugCommand(program2) {
5920
7145
  context: opts.context ?? "",
5921
7146
  contextFile: opts.contextFile ?? "",
5922
7147
  token: opts.token && opts.token.length > 0 ? opts.token : process.env.HUB_ACCESS_TOKEN ?? "",
5923
- envFile: existsSync16(join20(cwd, ".env")) ? ".env" : "",
7148
+ envFile: existsSync17(join21(cwd, ".env")) ? ".env" : "",
5924
7149
  derivedFile
5925
7150
  };
5926
7151
  const { args, env } = buildBridgeSpawn(staged.bridge, workerEntry, resolved);
5927
7152
  const target = resolved.entrypoint || resolved.functionName;
5928
7153
  console.log(runAsJob ? `Debug bridge: session=${resolved.session} hub=${resolved.hub} job=${target} inspector=${resolved.inspect}` : `Debug bridge: session=${resolved.session} hub=${resolved.hub} function=${fnName} port=${port} inspector=${resolved.inspect}`);
5929
- const deno = process.env.DENO_BINARY ?? (process.platform === "win32" ? "deno.exe" : "deno");
7154
+ const deno = resolveDeno();
5930
7155
  const proc = spawn3(deno, args, {
5931
7156
  cwd,
5932
7157
  env: { ...process.env, ...env },
@@ -5943,8 +7168,8 @@ function registerDebugCommand(program2) {
5943
7168
  proc.on("exit", (code) => process.exit(code ?? 0));
5944
7169
  });
5945
7170
  }
5946
- var __dirname3 = dirname5(fileURLToPath3(import.meta.url));
5947
- var pkg = JSON.parse(readFileSync15(join21(__dirname3, "..", "package.json"), "utf-8"));
7171
+ var __dirname3 = dirname6(fileURLToPath3(import.meta.url));
7172
+ var pkg = JSON.parse(readFileSync17(join22(__dirname3, "..", "package.json"), "utf-8"));
5948
7173
  function buildProgram() {
5949
7174
  const program2 = new Command;
5950
7175
  program2.name("uipath-functions").description("Build, serve, and publish UiPath JS/TS Functions").version(pkg.version);
@@ -5965,6 +7190,9 @@ async function cliRunner(args) {
5965
7190
  const program2 = buildProgram();
5966
7191
  await program2.parseAsync(["node", "uipath-functions", ...args]);
5967
7192
  }
5968
- export { generateManifests, cliRunner };
7193
+ export {
7194
+ cliRunner,
7195
+ generateManifests
7196
+ };
5969
7197
 
5970
- //# debugId=DF52938DC2551B7B64756E2164756E21
7198
+ //# debugId=94EBF991AB3525F364756E2164756E21