farseer-cli 1.8.2 → 1.8.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +18 -4
- package/dist/commands/app.js +42 -80
- package/dist/commands/app.js.map +2 -2
- package/dist/commands/pull.js +44 -9
- package/dist/commands/pull.js.map +2 -2
- package/dist/mcp/prompts/workflows.js +1 -1
- package/dist/mcp/prompts/workflows.js.map +2 -2
- package/dist/mcp/tools/appTools.js +33 -61
- package/dist/mcp/tools/appTools.js.map +2 -2
- package/dist/services/appSyncService.js +35 -31
- package/dist/services/appSyncService.js.map +2 -2
- package/dist/services/farseerApi.js +95 -16
- package/dist/services/farseerApi.js.map +3 -3
- package/dist/services/farseerFactory.js.map +1 -1
- package/dist/services/farseerService.js +11 -14
- package/dist/services/farseerService.js.map +2 -2
- package/package.json +1 -1
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../src/mcp/tools/appTools.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * App Management Tools\n *\n * Tools for managing Farseer apps (Remote Jobs).\n */\n\nimport { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';\nimport { z } from 'zod';\nimport { getFarseerClientWithFallback } from '../../services/farseerFactory';\nimport { AppArgument } from '../../services/farseerApi';\nimport {\n resolveOrgAndTenant,\n successResponse,\n errorResponse,\n authRequiredResponse,\n tenantRequiredResponse,\n} from '../utils/helpers';\nimport { formatClientError } from '../../utils/errorFormatter';\n\n// Define schemas outside of tool registration to avoid deep type instantiation\nconst listAppsSchema = {\n organisation: z\n .string()\n .optional()\n .describe('Farseer organisation (subdomain). If omitted, uses checked-out org or saved mapping.'),\n tenant: z.string().optional().describe('Tenant ID. Uses checked-out tenant if omitted.'),\n details: z.boolean().optional().describe('Include full details for each app'),\n};\n\nconst getAppSchema = {\n organisation: z\n .string()\n .optional()\n .describe('Farseer organisation (subdomain). If omitted, uses checked-out org or saved mapping.'),\n tenant: z.string().optional().describe('Tenant ID. Uses checked-out tenant if omitted.'),\n appName: z.string().describe('Name of the app (can include spaces)'),\n};\n\nconst createAppSchema = {\n organisation: z\n .string()\n .optional()\n .describe('Farseer organisation (subdomain). If omitted, uses checked-out org or saved mapping.'),\n tenant: z.string().optional().describe('Tenant ID. Uses checked-out tenant if omitted.'),\n appName: z.string().describe('Name for the new app'),\n};\n\nexport const argumentSchema = z\n .object({\n name: z.string(),\n dataType: z.enum(['string', 'boolean']).optional().describe('Data type. Defaults to \"string\" if omitted.'),\n fixed: z\n .boolean()\n .optional()\n .describe('Lock the value at run time so users cannot override it (admin sets, user reads only).'),\n options: z\n .array(z.string())\n .optional()\n .describe('Closed allowed-value set. Only meaningful for string dataType.'),\n defaultValue: z.string().optional(),\n secret: z.boolean().optional().describe('Mask the value in inputs and logs.'),\n })\n // Cross-axis checks mirror the backend's `validateExpectedArguments` so an\n // LLM caller gets pre-request feedback. Backend stays authoritative \u2014 these\n // catch the same shapes earlier, they don't replace the validator.\n .refine(\n (a) => a.dataType !== 'boolean' || a.defaultValue === undefined || ['true', 'false'].includes(a.defaultValue),\n {\n message: 'Boolean argument defaultValue must be \"true\" or \"false\"',\n path: ['defaultValue'],\n },\n )\n .refine((a) => !a.options || a.defaultValue === undefined || a.options.includes(a.defaultValue), {\n message: 'defaultValue must be one of the options',\n path: ['defaultValue'],\n });\n\nconst configureAppSchema = {\n organisation: z\n .string()\n .optional()\n .describe('Farseer organisation (subdomain). If omitted, uses checked-out org or saved mapping.'),\n tenant: z.string().optional().describe('Tenant ID. Uses checked-out tenant if omitted.'),\n appName: z.string().describe('Name of the app to configure'),\n entrypoint: z.string().optional().describe('Main script filename (e.g., \"index.ts\")'),\n scripts: z.array(z.string()).optional().describe('List of script filenames to include'),\n description: z.string().optional().describe('App description'),\n arguments: z.array(argumentSchema).optional().describe('App arguments with default values'),\n newName: z.string().optional().describe('Rename the app'),\n};\n\nconst deleteAppSchema = {\n organisation: z\n .string()\n .optional()\n .describe('Farseer organisation (subdomain). If omitted, uses checked-out org or saved mapping.'),\n tenant: z.string().optional().describe('Tenant ID. Uses checked-out tenant if omitted.'),\n appName: z.string().describe('Name of the app to delete'),\n};\n\nexport function registerAppTools(server: McpServer): void {\n // Cast to avoid TS2589 deep type instantiation with MCP SDK + Zod generics\n const s: any = server;\n\n // farseer_list_apps - List all apps\n s.tool(\n 'farseer_list_apps',\n `List all apps (Remote Jobs) configured on a Farseer tenant.\n\nApps are executable script configurations that include:\n- Entry point script\n- List of included scripts\n- Expected arguments with default values\n\nUse details=true to include full information for each app.\n\nIf no tenant is specified, uses the currently checked-out tenant.`,\n listAppsSchema,\n async (params: { organisation?: string; tenant?: string; details?: boolean }) => {\n const resolved = resolveOrgAndTenant(params);\n if (!resolved) {\n return tenantRequiredResponse();\n }\n const { organisation, tenant } = resolved;\n\n const clientResult = await getFarseerClientWithFallback(organisation, tenant);\n if (!clientResult) {\n return authRequiredResponse(tenant);\n }\n\n try {\n const appList = await clientResult.client.listApps();\n\n if (!params.details) {\n return successResponse({\n tenant,\n totalApps: appList.length,\n apps: appList.map((a) => ({\n name: a.name,\n id: a.id,\n reference: a.reference,\n })),\n });\n }\n\n // Get full details for each app\n const appsWithDetails = [];\n for (const item of appList) {\n const app = await clientResult.client.getApp(item.reference);\n if (app) {\n const appScripts = app.scriptFiles ?? [];\n const mainScript = appScripts.find((s) => s.id === app.mainScriptFileId);\n appsWithDetails.push({\n name: app.name,\n id: app.id,\n description: app.description || '',\n entrypoint: mainScript?.name || null,\n scripts: appScripts.map((s) => s.name),\n arguments: app.expectedArguments.map((a) => ({\n name: a.name,\n dataType: a.dataType,\n ...(a.fixed !== undefined ? { fixed: a.fixed } : {}),\n ...(a.options !== undefined ? { options: a.options } : {}),\n ...(a.defaultValue !== undefined ? { defaultValue: a.defaultValue } : {}),\n ...(a.secret !== undefined ? { secret: a.secret } : {}),\n })),\n });\n }\n }\n\n return successResponse({\n tenant,\n totalApps: appsWithDetails.length,\n apps: appsWithDetails,\n });\n } catch (error) {\n return errorResponse(`List apps failed: ${await formatClientError(error)}`, 'NETWORK_ERROR');\n }\n },\n );\n\n // farseer_get_app - Get app details\n s.tool(\n 'farseer_get_app',\n `Get detailed information about a specific Farseer app.\n\nReturns:\n- App name and description\n- Entry point script (main script that runs)\n- List of all included scripts\n- Expected arguments with their default values\n\nIf no tenant is specified, uses the currently checked-out tenant.`,\n getAppSchema,\n async (params: { organisation?: string; tenant?: string; appName: string }) => {\n const resolved = resolveOrgAndTenant(params);\n if (!resolved) {\n return tenantRequiredResponse();\n }\n const { organisation, tenant } = resolved;\n\n const clientResult = await getFarseerClientWithFallback(organisation, tenant);\n if (!clientResult) {\n return authRequiredResponse(tenant);\n }\n\n try {\n const app = await clientResult.client.getAppByName(params.appName);\n\n if (!app) {\n return errorResponse(`App \"${params.appName}\" not found`, 'NOT_FOUND');\n }\n\n const getAppScripts = app.scriptFiles ?? [];\n const mainScript = getAppScripts.find((s) => s.id === app.mainScriptFileId);\n\n return successResponse({\n tenant,\n app: {\n id: app.id,\n name: app.name,\n description: app.description || '',\n entrypoint: mainScript?.name || null,\n scripts: getAppScripts.map((s) => ({\n id: s.id,\n name: s.name,\n isEntrypoint: s.id === app.mainScriptFileId,\n })),\n arguments: app.expectedArguments.map((a) => ({\n name: a.name,\n dataType: a.dataType,\n ...(a.fixed !== undefined ? { fixed: a.fixed } : {}),\n ...(a.options !== undefined ? { options: a.options } : {}),\n ...(a.defaultValue !== undefined ? { defaultValue: a.defaultValue } : {}),\n ...(a.secret !== undefined ? { secret: a.secret } : {}),\n })),\n status: app.status,\n lastHeartbeat: app.lastHeartbeat,\n },\n });\n } catch (error) {\n return errorResponse(`Get app failed: ${await formatClientError(error)}`, 'NETWORK_ERROR');\n }\n },\n );\n\n // farseer_create_app - Create new app\n s.tool(\n 'farseer_create_app',\n `Create a new Farseer app.\n\nA Farseer App is a named configuration that points to a TypeScript script and defines its arguments.\nThe script uses farseer-client to interact with the Farseer API (import data, export reports, etc.).\n\nWorkflow to create a new app:\n1. Write the script at farseer-apps/<tenant>/files/Scripts/<name>.ts\n2. Push the script to remote with farseer_push (scripts must exist on remote first)\n3. Create the app with this tool (farseer_create_app)\n4. Configure it with farseer_configure_app (set entrypoint, scripts, arguments)\n5. Run it with farseer_run_app (CLI injects auth credentials automatically)\n\nScripts should use \\`new FarseerClient()\\` with no arguments - credentials are injected via environment variables by the CLI at runtime.\n\nIf no tenant is specified, uses the currently checked-out tenant.`,\n createAppSchema,\n async (params: { organisation?: string; tenant?: string; appName: string }) => {\n const resolved = resolveOrgAndTenant(params);\n if (!resolved) {\n return tenantRequiredResponse();\n }\n const { organisation, tenant } = resolved;\n\n const clientResult = await getFarseerClientWithFallback(organisation, tenant);\n if (!clientResult) {\n return authRequiredResponse(tenant);\n }\n\n try {\n // Check if app already exists\n const existing = await clientResult.client.getAppByName(params.appName);\n if (existing) {\n return errorResponse(`App \"${params.appName}\" already exists`, 'VALIDATION_ERROR');\n }\n\n const app = await clientResult.client.createApp(params.appName);\n\n return successResponse({\n tenant,\n app: {\n id: app.id,\n name: app.name,\n },\n message: `App \"${params.appName}\" created. Use farseer_configure_app to set entrypoint, scripts, and arguments.`,\n });\n } catch (error) {\n return errorResponse(`Create app failed: ${await formatClientError(error)}`, 'NETWORK_ERROR');\n }\n },\n );\n\n // farseer_configure_app - Configure app settings\n s.tool(\n 'farseer_configure_app',\n `Configure an existing Farseer app.\n\nYou can set:\n- entrypoint: Main script to execute (e.g., \"index.ts\")\n- scripts: List of scripts to include in the app\n- description: App description\n- arguments: List of expected arguments. Each has a name, optional dataType\n ('string' | 'boolean' \u2014 defaults to 'string'), optional fixed (locks the\n value at run time), optional options (closed allowed-value set, string\n dataType only), optional defaultValue, and optional secret.\n- newName: Rename the app\n\nImportant:\n- Scripts must exist on the remote (push them first)\n- If you set scripts but not entrypoint, the first script becomes entrypoint\n- Arguments are passed to the script as a JSON-encoded FARSEER_ARGS env var\n- Boolean dataType requires defaultValue \u2208 { \"true\", \"false\" }; defaultValue\n must be one of options when options is set\n\nIf no tenant is specified, uses the currently checked-out tenant.`,\n configureAppSchema,\n async (params: {\n organisation?: string;\n tenant?: string;\n appName: string;\n entrypoint?: string;\n scripts?: string[];\n description?: string;\n arguments?: Array<{\n name: string;\n dataType?: 'string' | 'boolean';\n fixed?: boolean;\n options?: string[];\n defaultValue?: string;\n secret?: boolean;\n }>;\n newName?: string;\n }) => {\n const resolved = resolveOrgAndTenant(params);\n if (!resolved) {\n return tenantRequiredResponse();\n }\n const { organisation, tenant } = resolved;\n\n const clientResult = await getFarseerClientWithFallback(organisation, tenant);\n if (!clientResult) {\n return authRequiredResponse(tenant);\n }\n\n try {\n const app = await clientResult.client.getAppByName(params.appName);\n if (!app) {\n return errorResponse(`App \"${params.appName}\" not found`, 'NOT_FOUND');\n }\n\n // Get available scripts for ID lookup\n // Build maps for both path-based and filename-based lookup\n const availableScripts = await clientResult.client.getScriptFiles();\n const scriptIdByPath = new Map<string, string>();\n const scriptIdByName = new Map<string, string>();\n for (const s of availableScripts) {\n scriptIdByPath.set(s.name.toLowerCase(), s.id);\n const filename = s.name.split('/').pop()?.toLowerCase() || s.name.toLowerCase();\n if (!scriptIdByName.has(filename)) {\n scriptIdByName.set(filename, s.id);\n }\n }\n // Resolve by path first, then by filename\n const resolveScriptId = (name: string): string | undefined => {\n const lower = name.toLowerCase();\n return scriptIdByPath.get(lower) || scriptIdByName.get(lower);\n };\n\n // Build update payload\n const update: {\n name?: string;\n description?: string;\n expectedArguments?: AppArgument[];\n mainScriptFileId?: string | null;\n scriptFileIds?: string[];\n } = {};\n\n if (params.newName) {\n update.name = params.newName;\n }\n\n if (params.description !== undefined) {\n update.description = params.description;\n }\n\n if (params.arguments) {\n // PUT semantics on the backend: this `expectedArguments`\n // array replaces the existing one wholesale. So if the\n // caller supplies a name but omits axes (dataType, fixed,\n // options, secret), we look up the existing arg by name\n // and carry those fields over. Without this merge, a\n // configure_app call that only re-sets defaultValue would\n // silently clear the secret flag or demote a dropdown\n // back to a plain string variable.\n //\n // Lookup is case-insensitive for convenience (caller\n // shouldn't have to remember exact casing to update an\n // existing arg), but on the write we keep the backend's\n // stored casing: validateExpectedArguments on the server\n // is case-sensitive (seen.has(arg.name)), so writing\n // back caller-supplied case would silently rename the\n // arg (e.g. jobName \u2192 JOBNAME) and break the next push.\n const existingByName = new Map(app.expectedArguments.map((e) => [e.name.toLowerCase(), e]));\n update.expectedArguments = params.arguments.map((a) => {\n const existing = existingByName.get(a.name.toLowerCase());\n const arg: AppArgument = {\n name: existing?.name ?? a.name,\n dataType: a.dataType ?? existing?.dataType ?? 'string',\n };\n const fixed = a.fixed ?? existing?.fixed;\n if (fixed !== undefined) arg.fixed = fixed;\n const options = a.options ?? existing?.options;\n if (options !== undefined) arg.options = options;\n const defaultValue = a.defaultValue ?? existing?.defaultValue;\n if (defaultValue !== undefined) arg.defaultValue = defaultValue;\n const secret = a.secret ?? existing?.secret;\n if (secret !== undefined) arg.secret = secret;\n return arg;\n });\n }\n\n if (params.scripts && params.scripts.length > 0) {\n const scriptIds: string[] = [];\n const notFound: string[] = [];\n\n for (const scriptName of params.scripts) {\n const id = resolveScriptId(scriptName);\n if (id) {\n scriptIds.push(id);\n } else {\n notFound.push(scriptName);\n }\n }\n\n if (notFound.length > 0) {\n return errorResponse(\n `Scripts not found on remote: ${notFound.join(', ')}. Push them first.`,\n 'VALIDATION_ERROR',\n );\n }\n\n update.scriptFileIds = scriptIds;\n\n // Set entrypoint to first script if not explicitly specified\n if (!params.entrypoint && scriptIds.length > 0) {\n update.mainScriptFileId = scriptIds[0];\n }\n }\n\n if (params.entrypoint) {\n const entrypointId = resolveScriptId(params.entrypoint);\n if (!entrypointId) {\n return errorResponse(\n `Entrypoint script \"${params.entrypoint}\" not found on remote. Push it first.`,\n 'VALIDATION_ERROR',\n );\n }\n update.mainScriptFileId = entrypointId;\n }\n\n // Apply update - name is required by the backend API\n if (!update.name) {\n update.name = app.name;\n }\n const reference = app.id.toString();\n await clientResult.client.updateApp(reference, update);\n\n return successResponse({\n tenant,\n appName: params.newName || params.appName,\n updated: Object.keys(update),\n message: `App \"${params.appName}\" configured successfully`,\n });\n } catch (error) {\n return errorResponse(`Configure app failed: ${await formatClientError(error)}`, 'NETWORK_ERROR');\n }\n },\n );\n\n // farseer_delete_app - Delete app\n s.tool(\n 'farseer_delete_app',\n `Delete an app from a Farseer tenant.\n\nWARNING: This is irreversible - the app will be permanently removed from the remote instance.\n\nThis does NOT delete the script files, only the app configuration.\n\nIf no tenant is specified, uses the currently checked-out tenant.`,\n deleteAppSchema,\n async (params: { organisation?: string; tenant?: string; appName: string }) => {\n const resolved = resolveOrgAndTenant(params);\n if (!resolved) {\n return tenantRequiredResponse();\n }\n const { organisation, tenant } = resolved;\n\n const clientResult = await getFarseerClientWithFallback(organisation, tenant);\n if (!clientResult) {\n return authRequiredResponse(tenant);\n }\n\n try {\n // Find the app in the folder listing to get the folder item_node ID\n // (getAppByName returns remoteJob ID which differs from folder item ID)\n const allApps = await clientResult.client.listApps();\n const appItem = allApps.find((a) => a.name.toLowerCase() === params.appName.toLowerCase());\n if (!appItem) {\n return errorResponse(`App \"${params.appName}\" not found`, 'NOT_FOUND');\n }\n\n // Delete via folders API using the folder item_node ID\n await clientResult.client.deleteApp(appItem.id.toString());\n\n return successResponse({\n tenant,\n deletedApp: params.appName,\n message: `App \"${params.appName}\" has been deleted`,\n });\n } catch (error) {\n return errorResponse(`Delete app failed: ${await formatClientError(error)}`, 'NETWORK_ERROR');\n }\n },\n );\n}\n"],
|
|
5
|
-
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAOA,iBAAkB;AAClB,4BAA6C;
|
|
4
|
+
"sourcesContent": ["/**\n * App Management Tools\n *\n * Tools for managing Farseer apps (Remote Jobs).\n */\n\nimport { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';\nimport { z } from 'zod';\nimport { getFarseerClientWithFallback } from '../../services/farseerFactory';\nimport { AppArgument, AppUpdateChanges, applySourceFolderChange } from '../../services/farseerApi';\nimport {\n resolveOrgAndTenant,\n successResponse,\n errorResponse,\n authRequiredResponse,\n tenantRequiredResponse,\n} from '../utils/helpers';\nimport { formatClientError } from '../../utils/errorFormatter';\n\n// Define schemas outside of tool registration to avoid deep type instantiation\nconst listAppsSchema = {\n organisation: z\n .string()\n .optional()\n .describe('Farseer organisation (subdomain). If omitted, uses checked-out org or saved mapping.'),\n tenant: z.string().optional().describe('Tenant ID. Uses checked-out tenant if omitted.'),\n details: z.boolean().optional().describe('Include full details for each app'),\n};\n\nconst getAppSchema = {\n organisation: z\n .string()\n .optional()\n .describe('Farseer organisation (subdomain). If omitted, uses checked-out org or saved mapping.'),\n tenant: z.string().optional().describe('Tenant ID. Uses checked-out tenant if omitted.'),\n appName: z.string().describe('Name of the app (can include spaces)'),\n};\n\nconst createAppSchema = {\n organisation: z\n .string()\n .optional()\n .describe('Farseer organisation (subdomain). If omitted, uses checked-out org or saved mapping.'),\n tenant: z.string().optional().describe('Tenant ID. Uses checked-out tenant if omitted.'),\n appName: z.string().describe('Name for the new app'),\n};\n\nexport const argumentSchema = z\n .object({\n name: z.string(),\n dataType: z.enum(['string', 'boolean']).optional().describe('Data type. Defaults to \"string\" if omitted.'),\n fixed: z\n .boolean()\n .optional()\n .describe('Lock the value at run time so users cannot override it (admin sets, user reads only).'),\n options: z\n .array(z.string())\n .optional()\n .describe('Closed allowed-value set. Only meaningful for string dataType.'),\n defaultValue: z.string().optional(),\n secret: z.boolean().optional().describe('Mask the value in inputs and logs.'),\n })\n // Cross-axis checks mirror the backend's `validateExpectedArguments` so an\n // LLM caller gets pre-request feedback. Backend stays authoritative \u2014 these\n // catch the same shapes earlier, they don't replace the validator.\n .refine(\n (a) => a.dataType !== 'boolean' || a.defaultValue === undefined || ['true', 'false'].includes(a.defaultValue),\n {\n message: 'Boolean argument defaultValue must be \"true\" or \"false\"',\n path: ['defaultValue'],\n },\n )\n .refine((a) => !a.options || a.defaultValue === undefined || a.options.includes(a.defaultValue), {\n message: 'defaultValue must be one of the options',\n path: ['defaultValue'],\n });\n\nconst configureAppSchema = {\n organisation: z\n .string()\n .optional()\n .describe('Farseer organisation (subdomain). If omitted, uses checked-out org or saved mapping.'),\n tenant: z.string().optional().describe('Tenant ID. Uses checked-out tenant if omitted.'),\n appName: z.string().describe('Name of the app to configure'),\n entrypoint: z\n .string()\n .optional()\n .describe('Main script filename \u2014 must be a file in the app\\'s source folder (e.g., \"index.ts\")'),\n sourceFolder: z\n .string()\n .optional()\n .describe('Source folder the app\\'s scripts come from (path under Files/, e.g. \"Scripts/MyApp\")'),\n description: z.string().optional().describe('App description'),\n arguments: z.array(argumentSchema).optional().describe('App arguments with default values'),\n newName: z.string().optional().describe('Rename the app'),\n};\n\nconst deleteAppSchema = {\n organisation: z\n .string()\n .optional()\n .describe('Farseer organisation (subdomain). If omitted, uses checked-out org or saved mapping.'),\n tenant: z.string().optional().describe('Tenant ID. Uses checked-out tenant if omitted.'),\n appName: z.string().describe('Name of the app to delete'),\n};\n\nexport function registerAppTools(server: McpServer): void {\n // Cast to avoid TS2589 deep type instantiation with MCP SDK + Zod generics\n const s: any = server;\n\n // farseer_list_apps - List all apps\n s.tool(\n 'farseer_list_apps',\n `List all apps (Remote Jobs) configured on a Farseer tenant.\n\nApps are executable script configurations that include:\n- Entry point script\n- List of included scripts\n- Expected arguments with default values\n\nUse details=true to include full information for each app.\n\nIf no tenant is specified, uses the currently checked-out tenant.`,\n listAppsSchema,\n async (params: { organisation?: string; tenant?: string; details?: boolean }) => {\n const resolved = resolveOrgAndTenant(params);\n if (!resolved) {\n return tenantRequiredResponse();\n }\n const { organisation, tenant } = resolved;\n\n const clientResult = await getFarseerClientWithFallback(organisation, tenant);\n if (!clientResult) {\n return authRequiredResponse(tenant);\n }\n\n try {\n const appList = await clientResult.client.listApps();\n\n if (!params.details) {\n return successResponse({\n tenant,\n totalApps: appList.length,\n apps: appList.map((a) => ({\n name: a.name,\n id: a.id,\n reference: a.reference,\n })),\n });\n }\n\n // Get full details for each app\n const appsWithDetails = [];\n for (const item of appList) {\n const app = await clientResult.client.getApp(item.reference);\n if (app) {\n const appScripts = app.scriptFiles ?? [];\n const mainScript = appScripts.find((s) => s.id === app.mainScriptFileId);\n appsWithDetails.push({\n name: app.name,\n id: app.id,\n description: app.description || '',\n entrypoint: mainScript?.name || null,\n scripts: appScripts.map((s) => s.name),\n arguments: app.expectedArguments.map((a) => ({\n name: a.name,\n dataType: a.dataType,\n ...(a.fixed !== undefined ? { fixed: a.fixed } : {}),\n ...(a.options !== undefined ? { options: a.options } : {}),\n ...(a.defaultValue !== undefined ? { defaultValue: a.defaultValue } : {}),\n ...(a.secret !== undefined ? { secret: a.secret } : {}),\n })),\n });\n }\n }\n\n return successResponse({\n tenant,\n totalApps: appsWithDetails.length,\n apps: appsWithDetails,\n });\n } catch (error) {\n return errorResponse(`List apps failed: ${await formatClientError(error)}`, 'NETWORK_ERROR');\n }\n },\n );\n\n // farseer_get_app - Get app details\n s.tool(\n 'farseer_get_app',\n `Get detailed information about a specific Farseer app.\n\nReturns:\n- App name and description\n- Entry point script (main script that runs)\n- List of all included scripts\n- Expected arguments with their default values\n\nIf no tenant is specified, uses the currently checked-out tenant.`,\n getAppSchema,\n async (params: { organisation?: string; tenant?: string; appName: string }) => {\n const resolved = resolveOrgAndTenant(params);\n if (!resolved) {\n return tenantRequiredResponse();\n }\n const { organisation, tenant } = resolved;\n\n const clientResult = await getFarseerClientWithFallback(organisation, tenant);\n if (!clientResult) {\n return authRequiredResponse(tenant);\n }\n\n try {\n const app = await clientResult.client.getAppByName(params.appName);\n\n if (!app) {\n return errorResponse(`App \"${params.appName}\" not found`, 'NOT_FOUND');\n }\n\n const getAppScripts = app.scriptFiles ?? [];\n const mainScript = getAppScripts.find((s) => s.id === app.mainScriptFileId);\n\n return successResponse({\n tenant,\n app: {\n id: app.id,\n name: app.name,\n description: app.description || '',\n entrypoint: mainScript?.name || null,\n scripts: getAppScripts.map((s) => ({\n id: s.id,\n name: s.name,\n isEntrypoint: s.id === app.mainScriptFileId,\n })),\n arguments: app.expectedArguments.map((a) => ({\n name: a.name,\n dataType: a.dataType,\n ...(a.fixed !== undefined ? { fixed: a.fixed } : {}),\n ...(a.options !== undefined ? { options: a.options } : {}),\n ...(a.defaultValue !== undefined ? { defaultValue: a.defaultValue } : {}),\n ...(a.secret !== undefined ? { secret: a.secret } : {}),\n })),\n status: app.status,\n lastHeartbeat: app.lastHeartbeat,\n },\n });\n } catch (error) {\n return errorResponse(`Get app failed: ${await formatClientError(error)}`, 'NETWORK_ERROR');\n }\n },\n );\n\n // farseer_create_app - Create new app\n s.tool(\n 'farseer_create_app',\n `Create a new Farseer app.\n\nA Farseer App is a named configuration that points to a TypeScript script and defines its arguments.\nThe script uses farseer-client to interact with the Farseer API (import data, export reports, etc.).\n\nWorkflow to create a new app:\n1. Write the script at farseer-apps/<tenant>/files/Scripts/<name>.ts\n2. Push the script to remote with farseer_push (scripts must exist on remote first)\n3. Create the app with this tool (farseer_create_app)\n4. Configure it with farseer_configure_app (set entrypoint, scripts, arguments)\n5. Run it with farseer_run_app (CLI injects auth credentials automatically)\n\nScripts should use \\`new FarseerClient()\\` with no arguments - credentials are injected via environment variables by the CLI at runtime.\n\nIf no tenant is specified, uses the currently checked-out tenant.`,\n createAppSchema,\n async (params: { organisation?: string; tenant?: string; appName: string }) => {\n const resolved = resolveOrgAndTenant(params);\n if (!resolved) {\n return tenantRequiredResponse();\n }\n const { organisation, tenant } = resolved;\n\n const clientResult = await getFarseerClientWithFallback(organisation, tenant);\n if (!clientResult) {\n return authRequiredResponse(tenant);\n }\n\n try {\n // Check if app already exists\n const existing = await clientResult.client.getAppByName(params.appName);\n if (existing) {\n return errorResponse(`App \"${params.appName}\" already exists`, 'VALIDATION_ERROR');\n }\n\n const app = await clientResult.client.createApp(params.appName);\n\n return successResponse({\n tenant,\n app: {\n id: app.id,\n name: app.name,\n },\n message: `App \"${params.appName}\" created. Use farseer_configure_app to set entrypoint, scripts, and arguments.`,\n });\n } catch (error) {\n return errorResponse(`Create app failed: ${await formatClientError(error)}`, 'NETWORK_ERROR');\n }\n },\n );\n\n // farseer_configure_app - Configure app settings\n s.tool(\n 'farseer_configure_app',\n `Configure an existing Farseer app.\n\nYou can set:\n- sourceFolder: Folder under Files/ the app's scripts come from (e.g. \"Scripts/MyApp\")\n- entrypoint: Main script to execute \u2014 must be a file in the source folder (e.g., \"index.ts\")\n- description: App description\n- arguments: List of expected arguments. Each has a name, optional dataType\n ('string' | 'boolean' \u2014 defaults to 'string'), optional fixed (locks the\n value at run time), optional options (closed allowed-value set, string\n dataType only), optional defaultValue, and optional secret.\n- newName: Rename the app\n\nImportant:\n- The app's scripts are derived from its source folder; the entrypoint must be\n one of those files. To use a script from another folder, set sourceFolder first.\n- Changing sourceFolder to a folder that doesn't contain the current entrypoint\n requires passing entrypoint in the same call.\n- Settings you don't pass are preserved (this only changes what you specify).\n- Arguments are passed to the script as a JSON-encoded FARSEER_ARGS env var\n- Boolean dataType requires defaultValue \u2208 { \"true\", \"false\" }; defaultValue\n must be one of options when options is set\n\nIf no tenant is specified, uses the currently checked-out tenant.`,\n configureAppSchema,\n async (params: {\n organisation?: string;\n tenant?: string;\n appName: string;\n entrypoint?: string;\n sourceFolder?: string;\n description?: string;\n arguments?: Array<{\n name: string;\n dataType?: 'string' | 'boolean';\n fixed?: boolean;\n options?: string[];\n defaultValue?: string;\n secret?: boolean;\n }>;\n newName?: string;\n }) => {\n const resolved = resolveOrgAndTenant(params);\n if (!resolved) {\n return tenantRequiredResponse();\n }\n const { organisation, tenant } = resolved;\n\n const clientResult = await getFarseerClientWithFallback(organisation, tenant);\n if (!clientResult) {\n return authRequiredResponse(tenant);\n }\n\n try {\n const app = await clientResult.client.getAppByName(params.appName);\n if (!app) {\n return errorResponse(`App \"${params.appName}\" not found`, 'NOT_FOUND');\n }\n\n // The set of changes. updateApp merges these onto the app's\n // current state, so anything left out here is preserved.\n const changes: AppUpdateChanges = {};\n\n if (params.newName) {\n changes.name = params.newName;\n }\n\n if (params.description !== undefined) {\n changes.description = params.description;\n }\n\n if (params.arguments) {\n // PUT semantics on the backend: this `expectedArguments`\n // array replaces the existing one wholesale. So if the\n // caller supplies a name but omits axes (dataType, fixed,\n // options, secret), we look up the existing arg by name\n // and carry those fields over. Without this merge, a\n // configure_app call that only re-sets defaultValue would\n // silently clear the secret flag or demote a dropdown\n // back to a plain string variable.\n //\n // Lookup is case-insensitive for convenience (caller\n // shouldn't have to remember exact casing to update an\n // existing arg), but on the write we keep the backend's\n // stored casing: validateExpectedArguments on the server\n // is case-sensitive (seen.has(arg.name)), so writing\n // back caller-supplied case would silently rename the\n // arg (e.g. jobName \u2192 JOBNAME) and break the next push.\n const existingByName = new Map(app.expectedArguments.map((e) => [e.name.toLowerCase(), e]));\n changes.expectedArguments = params.arguments.map((a) => {\n const existing = existingByName.get(a.name.toLowerCase());\n const arg: AppArgument = {\n name: existing?.name ?? a.name,\n dataType: a.dataType ?? existing?.dataType ?? 'string',\n };\n const fixed = a.fixed ?? existing?.fixed;\n if (fixed !== undefined) arg.fixed = fixed;\n const options = a.options ?? existing?.options;\n if (options !== undefined) arg.options = options;\n const defaultValue = a.defaultValue ?? existing?.defaultValue;\n if (defaultValue !== undefined) arg.defaultValue = defaultValue;\n const secret = a.secret ?? existing?.secret;\n if (secret !== undefined) arg.secret = secret;\n return arg;\n });\n }\n\n // Source folder + entrypoint. An app's scripts derive from its\n // source folder, and the entrypoint must be one of those files.\n // The decision lives in applySourceFolderChange (shared with the\n // CLI `app configure` command); the 'mcp' caller gets a plain,\n // param-worded error string.\n const sourceFolderError = await applySourceFolderChange(\n clientResult.client,\n app,\n changes,\n { sourceFolder: params.sourceFolder, entrypoint: params.entrypoint },\n 'mcp',\n );\n if (sourceFolderError) {\n return errorResponse(sourceFolderError, 'VALIDATION_ERROR');\n }\n\n const reference = app.id.toString();\n await clientResult.client.updateApp(reference, changes, app);\n\n return successResponse({\n tenant,\n appName: params.newName || params.appName,\n updated: Object.keys(changes),\n message: `App \"${params.appName}\" configured successfully`,\n });\n } catch (error) {\n return errorResponse(`Configure app failed: ${await formatClientError(error)}`, 'NETWORK_ERROR');\n }\n },\n );\n\n // farseer_delete_app - Delete app\n s.tool(\n 'farseer_delete_app',\n `Delete an app from a Farseer tenant.\n\nWARNING: This is irreversible - the app will be permanently removed from the remote instance.\n\nThis does NOT delete the script files, only the app configuration.\n\nIf no tenant is specified, uses the currently checked-out tenant.`,\n deleteAppSchema,\n async (params: { organisation?: string; tenant?: string; appName: string }) => {\n const resolved = resolveOrgAndTenant(params);\n if (!resolved) {\n return tenantRequiredResponse();\n }\n const { organisation, tenant } = resolved;\n\n const clientResult = await getFarseerClientWithFallback(organisation, tenant);\n if (!clientResult) {\n return authRequiredResponse(tenant);\n }\n\n try {\n // Find the app in the folder listing to get the folder item_node ID\n // (getAppByName returns remoteJob ID which differs from folder item ID)\n const allApps = await clientResult.client.listApps();\n const appItem = allApps.find((a) => a.name.toLowerCase() === params.appName.toLowerCase());\n if (!appItem) {\n return errorResponse(`App \"${params.appName}\" not found`, 'NOT_FOUND');\n }\n\n await clientResult.client.deleteApp(appItem.id);\n\n // The folder API 200s even when nothing was deleted; confirm.\n const remaining = await clientResult.client.listApps();\n if (remaining.some((a) => a.id === appItem.id)) {\n return errorResponse(\n `Delete reported success but \"${params.appName}\" is still present`,\n 'NETWORK_ERROR',\n );\n }\n\n return successResponse({\n tenant,\n deletedApp: params.appName,\n message: `App \"${params.appName}\" has been deleted`,\n });\n } catch (error) {\n return errorResponse(`Delete app failed: ${await formatClientError(error)}`, 'NETWORK_ERROR');\n }\n },\n );\n}\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAOA,iBAAkB;AAClB,4BAA6C;AAC7C,wBAAuE;AACvE,qBAMO;AACP,4BAAkC;AAGlC,MAAM,iBAAiB;AAAA,EACnB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,mBAAO,qCAAqB,MAAM;AAAA,MACtC;AAEA,UAAI;AAGA,cAAM,UAAU,MAAM,aAAa,OAAO,SAAS;AACnD,cAAM,UAAU,QAAQ,KAAK,CAAC,MAAM,EAAE,KAAK,YAAY,MAAM,OAAO,QAAQ,YAAY,CAAC;AACzF,YAAI,CAAC,SAAS;AACV,qBAAO,8BAAc,QAAQ,OAAO,OAAO,eAAe,WAAW;AAAA,QACzE;AAEA,cAAM,aAAa,OAAO,UAAU,QAAQ,EAAE;AAG9C,cAAM,YAAY,MAAM,aAAa,OAAO,SAAS;AACrD,YAAI,UAAU,KAAK,CAAC,MAAM,EAAE,OAAO,QAAQ,EAAE,GAAG;AAC5C,qBAAO;AAAA,YACH,gCAAgC,OAAO,OAAO;AAAA,YAC9C;AAAA,UACJ;AAAA,QACJ;AAEA,mBAAO,gCAAgB;AAAA,UACnB;AAAA,UACA,YAAY,OAAO;AAAA,UACnB,SAAS,QAAQ,OAAO,OAAO;AAAA,QACnC,CAAC;AAAA,MACL,SAAS,OAAO;AACZ,mBAAO,8BAAc,sBAAsB,UAAM,yCAAkB,KAAK,CAAC,IAAI,eAAe;AAAA,MAChG;AAAA,IACJ;AAAA,EACJ;AACJ;",
|
|
6
6
|
"names": ["s"]
|
|
7
7
|
}
|
|
@@ -133,6 +133,28 @@ class AppSyncService {
|
|
|
133
133
|
getAppFilename(name) {
|
|
134
134
|
return sanitizeDiacritics(name).replace(/[<>:"/\\|?*]/g, "").trim() + ".json";
|
|
135
135
|
}
|
|
136
|
+
/**
|
|
137
|
+
* Names of locally-tracked apps the next `pull` would delete because
|
|
138
|
+
* remote no longer has them. Uses only `listApps` (no per-app fetch),
|
|
139
|
+
* so pull can preview deletions for the destructive-action prompt
|
|
140
|
+
* without paying for getStatus's full per-app round-trip.
|
|
141
|
+
*
|
|
142
|
+
* Mirrors the deletion gate in `pull()` (`local._remote && !remoteApps.has(key)`):
|
|
143
|
+
* apps the user never pulled (`_remote` undefined) are kept untouched
|
|
144
|
+
* by pull, so they don't belong in this list.
|
|
145
|
+
*/
|
|
146
|
+
async getRemoteDeletions() {
|
|
147
|
+
const localApps = this.loadLocalApps();
|
|
148
|
+
const remoteAppList = await this.api.listApps();
|
|
149
|
+
const remoteNames = new Set(remoteAppList.map((a) => a.name.toLowerCase()));
|
|
150
|
+
const deleted = [];
|
|
151
|
+
for (const [key, local] of localApps) {
|
|
152
|
+
if (local._remote && !remoteNames.has(key)) {
|
|
153
|
+
deleted.push(local.name);
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
return deleted;
|
|
157
|
+
}
|
|
136
158
|
/**
|
|
137
159
|
* Load all local app configs
|
|
138
160
|
*/
|
|
@@ -183,7 +205,6 @@ class AppSyncService {
|
|
|
183
205
|
name: remote.name,
|
|
184
206
|
description: remote.description || "",
|
|
185
207
|
entrypoint: mainScript?.name || null,
|
|
186
|
-
scripts: scriptFiles.map((s) => s.name),
|
|
187
208
|
arguments: remote.expectedArguments.map((a) => {
|
|
188
209
|
const arg = {
|
|
189
210
|
name: a.name,
|
|
@@ -210,9 +231,6 @@ class AppSyncService {
|
|
|
210
231
|
const remoteScriptFiles = remote.scriptFiles ?? [];
|
|
211
232
|
const remoteEntrypoint = remoteScriptFiles.find((s) => s.id === remote.mainScriptFileId)?.name || null;
|
|
212
233
|
if (local.entrypoint !== remoteEntrypoint) return false;
|
|
213
|
-
const localScripts = [...local.scripts].sort();
|
|
214
|
-
const remoteScripts = [...remoteScriptFiles.map((s) => s.name)].sort();
|
|
215
|
-
if (JSON.stringify(localScripts) !== JSON.stringify(remoteScripts)) return false;
|
|
216
234
|
if (local.arguments.length !== remote.expectedArguments.length) return false;
|
|
217
235
|
for (let i = 0; i < local.arguments.length; i++) {
|
|
218
236
|
const l = local.arguments[i];
|
|
@@ -335,7 +353,7 @@ class AppSyncService {
|
|
|
335
353
|
const update = this.buildUpdatePayload(local, findScriptId);
|
|
336
354
|
update.name = local.name;
|
|
337
355
|
update.description = local.description;
|
|
338
|
-
await this.api.updateApp(created.id.toString(), update);
|
|
356
|
+
await this.api.updateApp(created.id.toString(), update, created);
|
|
339
357
|
local._remote = {
|
|
340
358
|
id: created.id,
|
|
341
359
|
reference: created.id.toString()
|
|
@@ -350,7 +368,7 @@ class AppSyncService {
|
|
|
350
368
|
const update = this.buildUpdatePayload(local, findScriptId);
|
|
351
369
|
update.name = local.name;
|
|
352
370
|
update.description = local.description;
|
|
353
|
-
await this.api.updateApp(remote.reference, update);
|
|
371
|
+
await this.api.updateApp(remote.reference, update, remote.app);
|
|
354
372
|
result.updated.push(local.name);
|
|
355
373
|
} catch (error) {
|
|
356
374
|
import_logger.logger.error(`Failed to update app ${local.name}: ${await (0, import_errorFormatter.formatClientError)(error)}`);
|
|
@@ -366,31 +384,17 @@ class AppSyncService {
|
|
|
366
384
|
*/
|
|
367
385
|
buildUpdatePayload(local, findScriptId) {
|
|
368
386
|
const update = {};
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
});
|
|
381
|
-
}
|
|
382
|
-
if (local.scripts.length > 0) {
|
|
383
|
-
const scriptIds = [];
|
|
384
|
-
for (const scriptRef of local.scripts) {
|
|
385
|
-
const id = findScriptId(scriptRef);
|
|
386
|
-
if (id) {
|
|
387
|
-
scriptIds.push(id);
|
|
388
|
-
}
|
|
389
|
-
}
|
|
390
|
-
if (scriptIds.length > 0) {
|
|
391
|
-
update.scriptFileIds = scriptIds;
|
|
392
|
-
}
|
|
393
|
-
}
|
|
387
|
+
update.expectedArguments = local.arguments.map((a) => {
|
|
388
|
+
const arg = {
|
|
389
|
+
name: a.name,
|
|
390
|
+
dataType: a.dataType ?? "string"
|
|
391
|
+
};
|
|
392
|
+
if (a.fixed !== void 0) arg.fixed = a.fixed;
|
|
393
|
+
if (a.options !== void 0) arg.options = a.options;
|
|
394
|
+
if (a.defaultValue !== void 0) arg.defaultValue = a.defaultValue;
|
|
395
|
+
if (a.secret !== void 0) arg.secret = a.secret;
|
|
396
|
+
return arg;
|
|
397
|
+
});
|
|
394
398
|
if (local.entrypoint) {
|
|
395
399
|
const entrypointId = findScriptId(local.entrypoint);
|
|
396
400
|
if (entrypointId) {
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/services/appSyncService.ts"],
|
|
4
|
-
"sourcesContent": ["import * as fs from 'fs';\nimport * as path from 'path';\nimport { RemoteApp, AppArgument, AppArgumentDataType } from './farseerApi';\nimport { IFarseerClient } from './farseerFactory';\nimport { getTenantAppsDir, ensureDirectoryExists, fetchWithConcurrency } from '../utils/helpers';\nimport { logger } from '../utils/logger';\nimport { formatClientError } from '../utils/errorFormatter';\n\n// Local app config format (stored in apps/*.json) \u2014 mirrors AppArgument so\n// pull/push round-trips don't drop any axis.\nexport interface LocalAppConfig {\n name: string;\n description: string;\n entrypoint: string | null; // Script filename (e.g., \"index.ts\")\n scripts: string[]; // List of script filenames\n arguments: {\n name: string;\n // `dataType` defaults to 'string' on legacy configs that pre-date typed\n // parameters. Without round-tripping the full axes (`dataType`,\n // `fixed`, `options`), a pull \u2192 push cycle silently demoted a boolean /\n // dropdown / locked arg back to a plain string variable.\n dataType?: AppArgumentDataType;\n fixed?: boolean;\n options?: string[];\n defaultValue?: string;\n secret?: boolean;\n }[];\n _remote?: {\n id: number;\n reference: string;\n };\n}\n\nexport interface AppSyncResult {\n created: string[];\n updated: string[];\n deleted: string[];\n unchanged: string[];\n}\n\nexport interface AppSyncStatus {\n newLocal: string[]; // Local apps not on remote\n newRemote: string[]; // Remote apps not locally\n modified: string[]; // Apps that differ\n synced: string[]; // Apps in sync\n}\n\n/**\n * Sanitize Croatian diacritics and other special characters to ASCII equivalents\n */\nfunction sanitizeDiacritics(text: string): string {\n const diacriticMap: Record<string, string> = {\n // Croatian\n \u010D: 'c',\n \u010C: 'C',\n \u0107: 'c',\n \u0106: 'C',\n \u0161: 's',\n \u0160: 'S',\n \u017E: 'z',\n \u017D: 'Z',\n \u0111: 'd',\n \u0110: 'D',\n // German/Other common\n \u00E4: 'a',\n \u00C4: 'A',\n \u00F6: 'o',\n \u00D6: 'O',\n \u00FC: 'u',\n \u00DC: 'U',\n \u00DF: 'ss',\n // Polish\n \u0105: 'a',\n \u0104: 'A',\n \u0119: 'e',\n \u0118: 'E',\n \u0142: 'l',\n \u0141: 'L',\n \u0144: 'n',\n \u0143: 'N',\n \u00F3: 'o',\n \u00D3: 'O',\n \u015B: 's',\n \u015A: 'S',\n \u017A: 'z',\n \u0179: 'Z',\n \u017C: 'z',\n \u017B: 'Z',\n // French/Spanish\n \u00E0: 'a',\n \u00E1: 'a',\n \u00E2: 'a',\n \u00E8: 'e',\n \u00E9: 'e',\n \u00EA: 'e',\n \u00EB: 'e',\n \u00EC: 'i',\n \u00ED: 'i',\n \u00EE: 'i',\n \u00EF: 'i',\n \u00F2: 'o',\n \u00F4: 'o',\n \u00F9: 'u',\n \u00FA: 'u',\n \u00FB: 'u',\n \u00F1: 'n',\n \u00D1: 'N',\n \u00E7: 'c',\n \u00C7: 'C',\n };\n\n return text\n .split('')\n .map((char) => diacriticMap[char] || char)\n .join('');\n}\n\n/**\n * Migrate legacy `type: 'variable' | 'constant' | 'boolean' | 'dropdown'` on\n * pre-PR pulls to the orthogonal-axes shape used by `localToUpdate` and\n * `areAppsEqual`. Idempotent \u2014 leaves new-shape entries untouched.\n *\n * Without this, a push immediately after upgrade silently demoted locked\n * args (`type: 'constant'` \u2192 no `fixed`) because the new code ignores the\n * legacy `type` key when building the wire payload. `areAppsEqual` flagged\n * the diff but didn't block, so the silent demote slipped through.\n */\nfunction migrateLegacyArguments(config: { arguments?: unknown[] } & Record<string, unknown>): Record<string, unknown> {\n if (!Array.isArray(config.arguments)) return config as Record<string, unknown>;\n config.arguments = config.arguments.map((raw) => {\n if (raw === null || typeof raw !== 'object') return raw;\n const a = raw as Record<string, unknown>;\n if (a.dataType !== undefined || a.type === undefined) return a;\n const legacyType = a.type;\n const rest: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(a)) {\n if (k !== 'type') rest[k] = v;\n }\n switch (legacyType) {\n case 'constant':\n return { ...rest, dataType: 'string', fixed: true };\n case 'boolean':\n return { ...rest, dataType: 'boolean' };\n case 'dropdown':\n case 'variable':\n default:\n return { ...rest, dataType: 'string' };\n }\n });\n return config as Record<string, unknown>;\n}\n\n/**\n * Service for syncing app configurations between local JSON files and remote Farseer instance\n */\nexport class AppSyncService {\n private api: IFarseerClient;\n private appsDir: string;\n\n constructor(tenant: string, api: IFarseerClient) {\n this.api = api;\n this.appsDir = getTenantAppsDir(tenant);\n }\n\n /**\n * Get filename for an app (keep original name, just sanitize for filesystem)\n */\n private getAppFilename(name: string): string {\n return (\n sanitizeDiacritics(name)\n .replace(/[<>:\"/\\\\|?*]/g, '') // Remove invalid filename characters\n .trim() + '.json'\n );\n }\n\n /**\n * Load all local app configs\n */\n loadLocalApps(): Map<string, LocalAppConfig> {\n const apps = new Map<string, LocalAppConfig>();\n\n if (!fs.existsSync(this.appsDir)) {\n return apps;\n }\n\n const files = fs.readdirSync(this.appsDir).filter((f) => f.endsWith('.json'));\n\n for (const file of files) {\n try {\n const content = fs.readFileSync(path.join(this.appsDir, file), 'utf-8');\n const config = migrateLegacyArguments(JSON.parse(content)) as LocalAppConfig;\n apps.set(config.name.toLowerCase(), config);\n } catch {\n // Skip invalid files\n }\n }\n\n return apps;\n }\n\n /**\n * Save a local app config\n */\n saveLocalApp(config: LocalAppConfig): void {\n ensureDirectoryExists(this.appsDir);\n const filename = this.getAppFilename(config.name);\n const filePath = path.join(this.appsDir, filename);\n fs.writeFileSync(filePath, JSON.stringify(config, null, 2), 'utf-8');\n }\n\n /**\n * Delete a local app config\n */\n deleteLocalApp(name: string): boolean {\n const filename = this.getAppFilename(name);\n const filePath = path.join(this.appsDir, filename);\n\n if (fs.existsSync(filePath)) {\n fs.unlinkSync(filePath);\n return true;\n }\n return false;\n }\n\n /**\n * Convert remote app to local config format\n */\n private remoteToLocal(remote: RemoteApp, reference: string): LocalAppConfig {\n const scriptFiles = remote.scriptFiles ?? [];\n const mainScript = scriptFiles.find((s) => s.id === remote.mainScriptFileId);\n\n // \"No default\" canonical shape locally is `defaultValue: ''` (empty\n // string), NOT an omitted key. The OpenAPI schema makes the field\n // optional, so the backend can emit either; if we passed `undefined`\n // through verbatim, a user who added `defaultValue: ''` locally\n // would see `areAppsEqual` say \"match\" (both normalise to '') but\n // the next pull would strip the key again \u2014 the on-disk JSON would\n // oscillate forever and never reach a steady state. type is treated\n // the same way ('variable' is the implicit default), secret only\n // appears when explicitly true on the backend (boolean is a clear\n // tri-state: true/false/unset, and \"unset\" reads as false anyway).\n return {\n name: remote.name,\n description: remote.description || '',\n entrypoint: mainScript?.name || null,\n scripts: scriptFiles.map((s) => s.name),\n arguments: remote.expectedArguments.map((a) => {\n // Pin a steady-state shape so two pulls back-to-back don't\n // oscillate. `defaultValue` is normalized to '' when omitted \u2014\n // a user-edited `defaultValue: ''` locally must compare equal\n // to a remote that omits the field. `dataType` defaults to\n // 'string' (the implicit pre-fix shape). All other axes\n // (`fixed`, `options`, `secret`) are only emitted when the\n // remote populated them, to keep the JSON minimal.\n const arg: LocalAppConfig['arguments'][number] = {\n name: a.name,\n defaultValue: a.defaultValue ?? '',\n dataType: a.dataType ?? 'string',\n };\n if (a.fixed !== undefined) arg.fixed = a.fixed;\n if (a.options !== undefined) arg.options = a.options;\n if (a.secret !== undefined) arg.secret = a.secret;\n return arg;\n }),\n _remote: {\n id: remote.id,\n reference: reference,\n },\n };\n }\n\n /**\n * Check if local and remote app configs are equivalent\n */\n private areAppsEqual(local: LocalAppConfig, remote: RemoteApp): boolean {\n // Compare name\n if (local.name !== remote.name) return false;\n\n // Compare description\n if ((local.description || '') !== (remote.description || '')) return false;\n\n // Compare entrypoint\n const remoteScriptFiles = remote.scriptFiles ?? [];\n const remoteEntrypoint = remoteScriptFiles.find((s) => s.id === remote.mainScriptFileId)?.name || null;\n if (local.entrypoint !== remoteEntrypoint) return false;\n\n // Compare scripts\n const localScripts = [...local.scripts].sort();\n const remoteScripts = [...remoteScriptFiles.map((s) => s.name)].sort();\n if (JSON.stringify(localScripts) !== JSON.stringify(remoteScripts)) return false;\n\n // Compare arguments. Order matters here: backend renders args in the\n // saved order in the UI, so we treat reordering as a real change.\n // Missing `dataType` defaults to 'string' (the implicit pre-fix value);\n // missing scalar defaults are normalized so '' vs undefined doesn't\n // show up as a spurious diff. All four axes (dataType, fixed, options,\n // defaultValue, secret) are compared so a pull\u2192push round-trip\n // detects changes on any of them.\n if (local.arguments.length !== remote.expectedArguments.length) return false;\n for (let i = 0; i < local.arguments.length; i++) {\n const l = local.arguments[i];\n const r = remote.expectedArguments[i];\n if (l.name !== r.name) return false;\n if ((l.dataType ?? 'string') !== (r.dataType ?? 'string')) return false;\n if (Boolean(l.fixed) !== Boolean(r.fixed)) return false;\n if (JSON.stringify(l.options ?? []) !== JSON.stringify(r.options ?? [])) return false;\n if ((l.defaultValue ?? '') !== (r.defaultValue ?? '')) return false;\n if (Boolean(l.secret) !== Boolean(r.secret)) return false;\n }\n\n return true;\n }\n\n /**\n * Pull apps from remote and save locally\n */\n async pull(): Promise<AppSyncResult> {\n const result: AppSyncResult = {\n created: [],\n updated: [],\n deleted: [],\n unchanged: [],\n };\n\n // Load local apps\n const localApps = this.loadLocalApps();\n\n // Fetch remote apps\n const remoteAppList = await this.api.listApps();\n const remoteApps = new Map<string, { app: RemoteApp; reference: string }>();\n\n // Fetch app details in parallel with concurrency limit\n logger.dim(`Fetching ${remoteAppList.length} apps in parallel...`);\n const appDetails = await fetchWithConcurrency(\n remoteAppList,\n async (item, index) => {\n const app = await this.api.getApp(item.reference);\n // Show progress every 10 apps\n if ((index + 1) % 10 === 0 || index === remoteAppList.length - 1) {\n const stream = process.env.FARSEER_MCP === '1' ? process.stderr : process.stdout;\n stream.write(`\\r Progress: ${index + 1}/${remoteAppList.length} apps`);\n }\n return { app, reference: item.reference };\n },\n 15,\n );\n // Clear progress line\n if (remoteAppList.length > 0) {\n const stream = process.env.FARSEER_MCP === '1' ? process.stderr : process.stdout;\n stream.write('\\r' + ' '.repeat(50) + '\\r');\n }\n\n for (const { app, reference } of appDetails) {\n if (app) {\n remoteApps.set(app.name.toLowerCase(), { app, reference });\n }\n }\n\n // Process remote apps\n for (const [key, { app, reference }] of remoteApps) {\n const localConfig = this.remoteToLocal(app, reference);\n const existingLocal = localApps.get(key);\n\n if (!existingLocal) {\n // New app from remote\n this.saveLocalApp(localConfig);\n result.created.push(app.name);\n } else if (!this.areAppsEqual(existingLocal, app)) {\n // App changed on remote - update local\n this.saveLocalApp(localConfig);\n result.updated.push(app.name);\n } else {\n result.unchanged.push(app.name);\n }\n }\n\n // Check for apps deleted on remote\n for (const [key, local] of localApps) {\n if (!remoteApps.has(key) && local._remote) {\n // App was synced before but now deleted on remote\n this.deleteLocalApp(local.name);\n result.deleted.push(local.name);\n }\n }\n\n return result;\n }\n\n /**\n * Push local apps to remote\n */\n async push(): Promise<AppSyncResult> {\n const result: AppSyncResult = {\n created: [],\n updated: [],\n deleted: [],\n unchanged: [],\n };\n\n // Load local apps\n const localApps = this.loadLocalApps();\n\n // Fetch remote apps\n const remoteAppList = await this.api.listApps();\n const remoteApps = new Map<string, { app: RemoteApp; reference: string }>();\n\n // Fetch app details in parallel with concurrency limit\n const appDetails = await fetchWithConcurrency(\n remoteAppList,\n async (item) => {\n const app = await this.api.getApp(item.reference);\n return { app, reference: item.reference };\n },\n 15,\n );\n\n for (const { app, reference } of appDetails) {\n if (app) {\n remoteApps.set(app.name.toLowerCase(), { app, reference });\n }\n }\n\n // Get available scripts for ID lookup\n // Build maps for both path-based and filename-based lookup (backward compatibility)\n const availableScripts = await this.api.getScriptFiles();\n const scriptIdByPath = new Map<string, string>();\n const scriptIdByName = new Map<string, string>();\n\n for (const s of availableScripts) {\n // s.name now contains full path (e.g., \"Scripts/test.ts\")\n const pathKey = s.name.toLowerCase();\n const filenameKey = s.name.split('/').pop()?.toLowerCase() || pathKey;\n\n scriptIdByPath.set(pathKey, s.id);\n // For filename lookup, only set if not already set (first match wins for ambiguous names)\n if (!scriptIdByName.has(filenameKey)) {\n scriptIdByName.set(filenameKey, s.id);\n }\n }\n\n // Helper to find script ID by path or filename\n const findScriptId = (scriptRef: string): string | undefined => {\n const key = scriptRef.toLowerCase();\n // Try exact path match first\n const byPath = scriptIdByPath.get(key);\n if (byPath) return byPath;\n // Try with Scripts/ prefix\n const withPrefix = scriptIdByPath.get(`scripts/${key}`);\n if (withPrefix) return withPrefix;\n // Fall back to filename match\n return scriptIdByName.get(key.split('/').pop() || key);\n };\n\n // Process local apps\n for (const [key, local] of localApps) {\n const remote = remoteApps.get(key);\n\n if (!remote) {\n // New local app - create on remote\n try {\n const created = await this.api.createApp(local.name);\n\n // Update with config (API requires name and description)\n const update = this.buildUpdatePayload(local, findScriptId);\n update.name = local.name;\n update.description = local.description;\n await this.api.updateApp(created.id.toString(), update);\n\n // Update local with remote ID\n local._remote = {\n id: created.id,\n reference: created.id.toString(),\n };\n this.saveLocalApp(local);\n\n result.created.push(local.name);\n } catch (error) {\n logger.error(`Failed to create app ${local.name}: ${await formatClientError(error)}`);\n }\n } else if (!this.areAppsEqual(local, remote.app)) {\n // App differs - update remote\n try {\n const update = this.buildUpdatePayload(local, findScriptId);\n update.name = local.name;\n update.description = local.description;\n\n await this.api.updateApp(remote.reference, update);\n result.updated.push(local.name);\n } catch (error) {\n logger.error(`Failed to update app ${local.name}: ${await formatClientError(error)}`);\n }\n } else {\n result.unchanged.push(local.name);\n }\n }\n\n // Note: We don't auto-delete remote apps when deleted locally\n // User must use \"farseer app delete\" explicitly\n\n return result;\n }\n\n /**\n * Build update payload for API\n */\n private buildUpdatePayload(\n local: LocalAppConfig,\n findScriptId: (scriptRef: string) => string | undefined,\n ): {\n name?: string;\n description?: string;\n expectedArguments?: AppArgument[];\n mainScriptFileId?: string | null;\n scriptFileIds?: string[];\n } {\n const update: {\n name?: string;\n description?: string;\n expectedArguments?: AppArgument[];\n mainScriptFileId?: string | null;\n scriptFileIds?: string[];\n } = {};\n\n // Arguments \u2014 preserve all axes. `dataType` defaults to 'string' for\n // older app json files that pre-date typed parameters. Conditional\n // expansion keeps the wire payload clean (no explicit `undefined`\n // values) so the backend's adapter doesn't have to second-guess.\n if (local.arguments.length > 0) {\n update.expectedArguments = local.arguments.map((a) => {\n const arg: AppArgument = {\n name: a.name,\n dataType: a.dataType ?? 'string',\n };\n if (a.fixed !== undefined) arg.fixed = a.fixed;\n if (a.options !== undefined) arg.options = a.options;\n if (a.defaultValue !== undefined) arg.defaultValue = a.defaultValue;\n if (a.secret !== undefined) arg.secret = a.secret;\n return arg;\n });\n }\n\n // Scripts - lookup by path or filename\n if (local.scripts.length > 0) {\n const scriptIds: string[] = [];\n for (const scriptRef of local.scripts) {\n const id = findScriptId(scriptRef);\n if (id) {\n scriptIds.push(id);\n }\n }\n if (scriptIds.length > 0) {\n update.scriptFileIds = scriptIds;\n }\n }\n\n // Entrypoint - lookup by path or filename\n if (local.entrypoint) {\n const entrypointId = findScriptId(local.entrypoint);\n if (entrypointId) {\n update.mainScriptFileId = entrypointId;\n }\n }\n\n return update;\n }\n\n /**\n * Get sync status without making changes\n */\n async getStatus(): Promise<AppSyncStatus> {\n const status: AppSyncStatus = {\n newLocal: [],\n newRemote: [],\n modified: [],\n synced: [],\n };\n\n // Load local apps\n const localApps = this.loadLocalApps();\n\n // Fetch remote apps\n const remoteAppList = await this.api.listApps();\n const remoteApps = new Map<string, { app: RemoteApp; reference: string }>();\n\n // Fetch app details in parallel with concurrency limit\n const appDetails = await fetchWithConcurrency(\n remoteAppList,\n async (item) => {\n const app = await this.api.getApp(item.reference);\n return { app, reference: item.reference };\n },\n 15,\n );\n\n for (const { app, reference } of appDetails) {\n if (app) {\n remoteApps.set(app.name.toLowerCase(), { app, reference });\n }\n }\n\n // Check local apps\n for (const [key, local] of localApps) {\n const remote = remoteApps.get(key);\n\n if (!remote) {\n status.newLocal.push(local.name);\n } else if (!this.areAppsEqual(local, remote.app)) {\n status.modified.push(local.name);\n } else {\n status.synced.push(local.name);\n }\n }\n\n // Check for new remote apps\n for (const [key, { app }] of remoteApps) {\n if (!localApps.has(key)) {\n status.newRemote.push(app.name);\n }\n }\n\n return status;\n }\n}\n"],
|
|
5
|
-
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,SAAoB;AACpB,WAAsB;AAGtB,qBAA8E;AAC9E,oBAAuB;AACvB,4BAAkC;
|
|
4
|
+
"sourcesContent": ["import * as fs from 'fs';\nimport * as path from 'path';\nimport { RemoteApp, AppArgument, AppArgumentDataType } from './farseerApi';\nimport { IFarseerClient } from './farseerFactory';\nimport { getTenantAppsDir, ensureDirectoryExists, fetchWithConcurrency } from '../utils/helpers';\nimport { logger } from '../utils/logger';\nimport { formatClientError } from '../utils/errorFormatter';\n\n// Local app config format (stored in apps/*.json) \u2014 mirrors AppArgument so\n// pull/push round-trips don't drop any axis.\nexport interface LocalAppConfig {\n name: string;\n description: string;\n entrypoint: string | null; // Script filename (e.g., \"index.ts\")\n arguments: {\n name: string;\n // `dataType` defaults to 'string' on legacy configs that pre-date typed\n // parameters. Without round-tripping the full axes (`dataType`,\n // `fixed`, `options`), a pull \u2192 push cycle silently demoted a boolean /\n // dropdown / locked arg back to a plain string variable.\n dataType?: AppArgumentDataType;\n fixed?: boolean;\n options?: string[];\n defaultValue?: string;\n secret?: boolean;\n }[];\n _remote?: {\n id: number;\n reference: string;\n };\n}\n\nexport interface AppSyncResult {\n created: string[];\n updated: string[];\n deleted: string[];\n unchanged: string[];\n}\n\nexport interface AppSyncStatus {\n newLocal: string[]; // Local apps not on remote\n newRemote: string[]; // Remote apps not locally\n modified: string[]; // Apps that differ\n synced: string[]; // Apps in sync\n}\n\n/**\n * Sanitize Croatian diacritics and other special characters to ASCII equivalents\n */\nfunction sanitizeDiacritics(text: string): string {\n const diacriticMap: Record<string, string> = {\n // Croatian\n \u010D: 'c',\n \u010C: 'C',\n \u0107: 'c',\n \u0106: 'C',\n \u0161: 's',\n \u0160: 'S',\n \u017E: 'z',\n \u017D: 'Z',\n \u0111: 'd',\n \u0110: 'D',\n // German/Other common\n \u00E4: 'a',\n \u00C4: 'A',\n \u00F6: 'o',\n \u00D6: 'O',\n \u00FC: 'u',\n \u00DC: 'U',\n \u00DF: 'ss',\n // Polish\n \u0105: 'a',\n \u0104: 'A',\n \u0119: 'e',\n \u0118: 'E',\n \u0142: 'l',\n \u0141: 'L',\n \u0144: 'n',\n \u0143: 'N',\n \u00F3: 'o',\n \u00D3: 'O',\n \u015B: 's',\n \u015A: 'S',\n \u017A: 'z',\n \u0179: 'Z',\n \u017C: 'z',\n \u017B: 'Z',\n // French/Spanish\n \u00E0: 'a',\n \u00E1: 'a',\n \u00E2: 'a',\n \u00E8: 'e',\n \u00E9: 'e',\n \u00EA: 'e',\n \u00EB: 'e',\n \u00EC: 'i',\n \u00ED: 'i',\n \u00EE: 'i',\n \u00EF: 'i',\n \u00F2: 'o',\n \u00F4: 'o',\n \u00F9: 'u',\n \u00FA: 'u',\n \u00FB: 'u',\n \u00F1: 'n',\n \u00D1: 'N',\n \u00E7: 'c',\n \u00C7: 'C',\n };\n\n return text\n .split('')\n .map((char) => diacriticMap[char] || char)\n .join('');\n}\n\n/**\n * Migrate legacy `type: 'variable' | 'constant' | 'boolean' | 'dropdown'` on\n * pre-PR pulls to the orthogonal-axes shape used by `localToUpdate` and\n * `areAppsEqual`. Idempotent \u2014 leaves new-shape entries untouched.\n *\n * Without this, a push immediately after upgrade silently demoted locked\n * args (`type: 'constant'` \u2192 no `fixed`) because the new code ignores the\n * legacy `type` key when building the wire payload. `areAppsEqual` flagged\n * the diff but didn't block, so the silent demote slipped through.\n */\nfunction migrateLegacyArguments(config: { arguments?: unknown[] } & Record<string, unknown>): Record<string, unknown> {\n if (!Array.isArray(config.arguments)) return config as Record<string, unknown>;\n config.arguments = config.arguments.map((raw) => {\n if (raw === null || typeof raw !== 'object') return raw;\n const a = raw as Record<string, unknown>;\n if (a.dataType !== undefined || a.type === undefined) return a;\n const legacyType = a.type;\n const rest: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(a)) {\n if (k !== 'type') rest[k] = v;\n }\n switch (legacyType) {\n case 'constant':\n return { ...rest, dataType: 'string', fixed: true };\n case 'boolean':\n return { ...rest, dataType: 'boolean' };\n case 'dropdown':\n case 'variable':\n default:\n return { ...rest, dataType: 'string' };\n }\n });\n return config as Record<string, unknown>;\n}\n\n/**\n * Service for syncing app configurations between local JSON files and remote Farseer instance\n */\nexport class AppSyncService {\n private api: IFarseerClient;\n private appsDir: string;\n\n constructor(tenant: string, api: IFarseerClient) {\n this.api = api;\n this.appsDir = getTenantAppsDir(tenant);\n }\n\n /**\n * Get filename for an app (keep original name, just sanitize for filesystem)\n */\n private getAppFilename(name: string): string {\n return (\n sanitizeDiacritics(name)\n .replace(/[<>:\"/\\\\|?*]/g, '') // Remove invalid filename characters\n .trim() + '.json'\n );\n }\n\n /**\n * Names of locally-tracked apps the next `pull` would delete because\n * remote no longer has them. Uses only `listApps` (no per-app fetch),\n * so pull can preview deletions for the destructive-action prompt\n * without paying for getStatus's full per-app round-trip.\n *\n * Mirrors the deletion gate in `pull()` (`local._remote && !remoteApps.has(key)`):\n * apps the user never pulled (`_remote` undefined) are kept untouched\n * by pull, so they don't belong in this list.\n */\n async getRemoteDeletions(): Promise<string[]> {\n const localApps = this.loadLocalApps();\n const remoteAppList = await this.api.listApps();\n const remoteNames = new Set(remoteAppList.map((a) => a.name.toLowerCase()));\n const deleted: string[] = [];\n for (const [key, local] of localApps) {\n if (local._remote && !remoteNames.has(key)) {\n deleted.push(local.name);\n }\n }\n return deleted;\n }\n\n /**\n * Load all local app configs\n */\n loadLocalApps(): Map<string, LocalAppConfig> {\n const apps = new Map<string, LocalAppConfig>();\n\n if (!fs.existsSync(this.appsDir)) {\n return apps;\n }\n\n const files = fs.readdirSync(this.appsDir).filter((f) => f.endsWith('.json'));\n\n for (const file of files) {\n try {\n const content = fs.readFileSync(path.join(this.appsDir, file), 'utf-8');\n const config = migrateLegacyArguments(JSON.parse(content)) as LocalAppConfig;\n apps.set(config.name.toLowerCase(), config);\n } catch {\n // Skip invalid files\n }\n }\n\n return apps;\n }\n\n /**\n * Save a local app config\n */\n saveLocalApp(config: LocalAppConfig): void {\n ensureDirectoryExists(this.appsDir);\n const filename = this.getAppFilename(config.name);\n const filePath = path.join(this.appsDir, filename);\n fs.writeFileSync(filePath, JSON.stringify(config, null, 2), 'utf-8');\n }\n\n /**\n * Delete a local app config\n */\n deleteLocalApp(name: string): boolean {\n const filename = this.getAppFilename(name);\n const filePath = path.join(this.appsDir, filename);\n\n if (fs.existsSync(filePath)) {\n fs.unlinkSync(filePath);\n return true;\n }\n return false;\n }\n\n /**\n * Convert remote app to local config format\n */\n private remoteToLocal(remote: RemoteApp, reference: string): LocalAppConfig {\n const scriptFiles = remote.scriptFiles ?? [];\n const mainScript = scriptFiles.find((s) => s.id === remote.mainScriptFileId);\n\n // \"No default\" canonical shape locally is `defaultValue: ''` (empty\n // string), NOT an omitted key. The OpenAPI schema makes the field\n // optional, so the backend can emit either; if we passed `undefined`\n // through verbatim, a user who added `defaultValue: ''` locally\n // would see `areAppsEqual` say \"match\" (both normalise to '') but\n // the next pull would strip the key again \u2014 the on-disk JSON would\n // oscillate forever and never reach a steady state. type is treated\n // the same way ('variable' is the implicit default), secret only\n // appears when explicitly true on the backend (boolean is a clear\n // tri-state: true/false/unset, and \"unset\" reads as false anyway).\n return {\n name: remote.name,\n description: remote.description || '',\n entrypoint: mainScript?.name || null,\n arguments: remote.expectedArguments.map((a) => {\n // Pin a steady-state shape so two pulls back-to-back don't\n // oscillate. `defaultValue` is normalized to '' when omitted \u2014\n // a user-edited `defaultValue: ''` locally must compare equal\n // to a remote that omits the field. `dataType` defaults to\n // 'string' (the implicit pre-fix shape). All other axes\n // (`fixed`, `options`, `secret`) are only emitted when the\n // remote populated them, to keep the JSON minimal.\n const arg: LocalAppConfig['arguments'][number] = {\n name: a.name,\n defaultValue: a.defaultValue ?? '',\n dataType: a.dataType ?? 'string',\n };\n if (a.fixed !== undefined) arg.fixed = a.fixed;\n if (a.options !== undefined) arg.options = a.options;\n if (a.secret !== undefined) arg.secret = a.secret;\n return arg;\n }),\n _remote: {\n id: remote.id,\n reference: reference,\n },\n };\n }\n\n /**\n * Check if local and remote app configs are equivalent\n */\n private areAppsEqual(local: LocalAppConfig, remote: RemoteApp): boolean {\n // Compare name\n if (local.name !== remote.name) return false;\n\n // Compare description\n if ((local.description || '') !== (remote.description || '')) return false;\n\n // Compare entrypoint\n const remoteScriptFiles = remote.scriptFiles ?? [];\n const remoteEntrypoint = remoteScriptFiles.find((s) => s.id === remote.mainScriptFileId)?.name || null;\n if (local.entrypoint !== remoteEntrypoint) return false;\n\n // Compare arguments. Order matters here: backend renders args in the\n // saved order in the UI, so we treat reordering as a real change.\n // Missing `dataType` defaults to 'string' (the implicit pre-fix value);\n // missing scalar defaults are normalized so '' vs undefined doesn't\n // show up as a spurious diff. All four axes (dataType, fixed, options,\n // defaultValue, secret) are compared so a pull\u2192push round-trip\n // detects changes on any of them.\n if (local.arguments.length !== remote.expectedArguments.length) return false;\n for (let i = 0; i < local.arguments.length; i++) {\n const l = local.arguments[i];\n const r = remote.expectedArguments[i];\n if (l.name !== r.name) return false;\n if ((l.dataType ?? 'string') !== (r.dataType ?? 'string')) return false;\n if (Boolean(l.fixed) !== Boolean(r.fixed)) return false;\n if (JSON.stringify(l.options ?? []) !== JSON.stringify(r.options ?? [])) return false;\n if ((l.defaultValue ?? '') !== (r.defaultValue ?? '')) return false;\n if (Boolean(l.secret) !== Boolean(r.secret)) return false;\n }\n\n return true;\n }\n\n /**\n * Pull apps from remote and save locally\n */\n async pull(): Promise<AppSyncResult> {\n const result: AppSyncResult = {\n created: [],\n updated: [],\n deleted: [],\n unchanged: [],\n };\n\n // Load local apps\n const localApps = this.loadLocalApps();\n\n // Fetch remote apps\n const remoteAppList = await this.api.listApps();\n const remoteApps = new Map<string, { app: RemoteApp; reference: string }>();\n\n // Fetch app details in parallel with concurrency limit\n logger.dim(`Fetching ${remoteAppList.length} apps in parallel...`);\n const appDetails = await fetchWithConcurrency(\n remoteAppList,\n async (item, index) => {\n const app = await this.api.getApp(item.reference);\n // Show progress every 10 apps\n if ((index + 1) % 10 === 0 || index === remoteAppList.length - 1) {\n const stream = process.env.FARSEER_MCP === '1' ? process.stderr : process.stdout;\n stream.write(`\\r Progress: ${index + 1}/${remoteAppList.length} apps`);\n }\n return { app, reference: item.reference };\n },\n 15,\n );\n // Clear progress line\n if (remoteAppList.length > 0) {\n const stream = process.env.FARSEER_MCP === '1' ? process.stderr : process.stdout;\n stream.write('\\r' + ' '.repeat(50) + '\\r');\n }\n\n for (const { app, reference } of appDetails) {\n if (app) {\n remoteApps.set(app.name.toLowerCase(), { app, reference });\n }\n }\n\n // Process remote apps\n for (const [key, { app, reference }] of remoteApps) {\n const localConfig = this.remoteToLocal(app, reference);\n const existingLocal = localApps.get(key);\n\n if (!existingLocal) {\n // New app from remote\n this.saveLocalApp(localConfig);\n result.created.push(app.name);\n } else if (!this.areAppsEqual(existingLocal, app)) {\n // App changed on remote - update local\n this.saveLocalApp(localConfig);\n result.updated.push(app.name);\n } else {\n result.unchanged.push(app.name);\n }\n }\n\n // Check for apps deleted on remote\n for (const [key, local] of localApps) {\n if (!remoteApps.has(key) && local._remote) {\n // App was synced before but now deleted on remote\n this.deleteLocalApp(local.name);\n result.deleted.push(local.name);\n }\n }\n\n return result;\n }\n\n /**\n * Push local apps to remote\n */\n async push(): Promise<AppSyncResult> {\n const result: AppSyncResult = {\n created: [],\n updated: [],\n deleted: [],\n unchanged: [],\n };\n\n // Load local apps\n const localApps = this.loadLocalApps();\n\n // Fetch remote apps\n const remoteAppList = await this.api.listApps();\n const remoteApps = new Map<string, { app: RemoteApp; reference: string }>();\n\n // Fetch app details in parallel with concurrency limit\n const appDetails = await fetchWithConcurrency(\n remoteAppList,\n async (item) => {\n const app = await this.api.getApp(item.reference);\n return { app, reference: item.reference };\n },\n 15,\n );\n\n for (const { app, reference } of appDetails) {\n if (app) {\n remoteApps.set(app.name.toLowerCase(), { app, reference });\n }\n }\n\n // Get available scripts for ID lookup\n // Build maps for both path-based and filename-based lookup (backward compatibility)\n const availableScripts = await this.api.getScriptFiles();\n const scriptIdByPath = new Map<string, string>();\n const scriptIdByName = new Map<string, string>();\n\n for (const s of availableScripts) {\n // s.name now contains full path (e.g., \"Scripts/test.ts\")\n const pathKey = s.name.toLowerCase();\n const filenameKey = s.name.split('/').pop()?.toLowerCase() || pathKey;\n\n scriptIdByPath.set(pathKey, s.id);\n // For filename lookup, only set if not already set (first match wins for ambiguous names)\n if (!scriptIdByName.has(filenameKey)) {\n scriptIdByName.set(filenameKey, s.id);\n }\n }\n\n // Helper to find script ID by path or filename\n const findScriptId = (scriptRef: string): string | undefined => {\n const key = scriptRef.toLowerCase();\n // Try exact path match first\n const byPath = scriptIdByPath.get(key);\n if (byPath) return byPath;\n // Try with Scripts/ prefix\n const withPrefix = scriptIdByPath.get(`scripts/${key}`);\n if (withPrefix) return withPrefix;\n // Fall back to filename match\n return scriptIdByName.get(key.split('/').pop() || key);\n };\n\n // Process local apps\n for (const [key, local] of localApps) {\n const remote = remoteApps.get(key);\n\n if (!remote) {\n // New local app - create on remote\n try {\n const created = await this.api.createApp(local.name);\n\n // Update with config (API requires name and description)\n const update = this.buildUpdatePayload(local, findScriptId);\n update.name = local.name;\n update.description = local.description;\n await this.api.updateApp(created.id.toString(), update, created);\n\n // Update local with remote ID\n local._remote = {\n id: created.id,\n reference: created.id.toString(),\n };\n this.saveLocalApp(local);\n\n result.created.push(local.name);\n } catch (error) {\n logger.error(`Failed to create app ${local.name}: ${await formatClientError(error)}`);\n }\n } else if (!this.areAppsEqual(local, remote.app)) {\n // App differs - update remote\n try {\n const update = this.buildUpdatePayload(local, findScriptId);\n update.name = local.name;\n update.description = local.description;\n\n await this.api.updateApp(remote.reference, update, remote.app);\n result.updated.push(local.name);\n } catch (error) {\n logger.error(`Failed to update app ${local.name}: ${await formatClientError(error)}`);\n }\n } else {\n result.unchanged.push(local.name);\n }\n }\n\n // Note: We don't auto-delete remote apps when deleted locally\n // User must use \"farseer app delete\" explicitly\n\n return result;\n }\n\n /**\n * Build update payload for API\n */\n private buildUpdatePayload(\n local: LocalAppConfig,\n findScriptId: (scriptRef: string) => string | undefined,\n ): {\n name?: string;\n description?: string;\n expectedArguments?: AppArgument[];\n mainScriptFileId?: string | null;\n } {\n const update: {\n name?: string;\n description?: string;\n expectedArguments?: AppArgument[];\n mainScriptFileId?: string | null;\n } = {};\n\n // Arguments \u2014 preserve all axes. `dataType` defaults to 'string' for\n // older app json files that pre-date typed parameters. Always sent\n // (even when empty): the local config is authoritative for the sync\n // path, so an app whose args were cleared locally must push that\n // emptiness through, otherwise `mergeAppUpdate` would keep the remote\n // args and `status` would report the app modified forever.\n update.expectedArguments = local.arguments.map((a) => {\n const arg: AppArgument = {\n name: a.name,\n dataType: a.dataType ?? 'string',\n };\n if (a.fixed !== undefined) arg.fixed = a.fixed;\n if (a.options !== undefined) arg.options = a.options;\n if (a.defaultValue !== undefined) arg.defaultValue = a.defaultValue;\n if (a.secret !== undefined) arg.secret = a.secret;\n return arg;\n });\n\n // Entrypoint - lookup by path or filename\n if (local.entrypoint) {\n const entrypointId = findScriptId(local.entrypoint);\n if (entrypointId) {\n update.mainScriptFileId = entrypointId;\n }\n }\n\n return update;\n }\n\n /**\n * Get sync status without making changes\n */\n async getStatus(): Promise<AppSyncStatus> {\n const status: AppSyncStatus = {\n newLocal: [],\n newRemote: [],\n modified: [],\n synced: [],\n };\n\n // Load local apps\n const localApps = this.loadLocalApps();\n\n // Fetch remote apps\n const remoteAppList = await this.api.listApps();\n const remoteApps = new Map<string, { app: RemoteApp; reference: string }>();\n\n // Fetch app details in parallel with concurrency limit\n const appDetails = await fetchWithConcurrency(\n remoteAppList,\n async (item) => {\n const app = await this.api.getApp(item.reference);\n return { app, reference: item.reference };\n },\n 15,\n );\n\n for (const { app, reference } of appDetails) {\n if (app) {\n remoteApps.set(app.name.toLowerCase(), { app, reference });\n }\n }\n\n // Check local apps\n for (const [key, local] of localApps) {\n const remote = remoteApps.get(key);\n\n if (!remote) {\n status.newLocal.push(local.name);\n } else if (!this.areAppsEqual(local, remote.app)) {\n status.modified.push(local.name);\n } else {\n status.synced.push(local.name);\n }\n }\n\n // Check for new remote apps\n for (const [key, { app }] of remoteApps) {\n if (!localApps.has(key)) {\n status.newRemote.push(app.name);\n }\n }\n\n return status;\n }\n}\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,SAAoB;AACpB,WAAsB;AAGtB,qBAA8E;AAC9E,oBAAuB;AACvB,4BAAkC;AA2ClC,SAAS,mBAAmB,MAAsB;AAC9C,QAAM,eAAuC;AAAA;AAAA,IAEzC,QAAG;AAAA,IACH,QAAG;AAAA,IACH,QAAG;AAAA,IACH,QAAG;AAAA,IACH,QAAG;AAAA,IACH,QAAG;AAAA,IACH,QAAG;AAAA,IACH,QAAG;AAAA,IACH,QAAG;AAAA,IACH,QAAG;AAAA;AAAA,IAEH,QAAG;AAAA,IACH,QAAG;AAAA,IACH,QAAG;AAAA,IACH,QAAG;AAAA,IACH,QAAG;AAAA,IACH,QAAG;AAAA,IACH,QAAG;AAAA;AAAA,IAEH,QAAG;AAAA,IACH,QAAG;AAAA,IACH,QAAG;AAAA,IACH,QAAG;AAAA,IACH,QAAG;AAAA,IACH,QAAG;AAAA,IACH,QAAG;AAAA,IACH,QAAG;AAAA,IACH,QAAG;AAAA,IACH,QAAG;AAAA,IACH,QAAG;AAAA,IACH,QAAG;AAAA,IACH,QAAG;AAAA,IACH,QAAG;AAAA,IACH,QAAG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C,UAAI,CAAC,QAAQ;AACT,eAAO,SAAS,KAAK,MAAM,IAAI;AAAA,MACnC,WAAW,CAAC,KAAK,aAAa,OAAO,OAAO,GAAG,GAAG;AAC9C,eAAO,SAAS,KAAK,MAAM,IAAI;AAAA,MACnC,OAAO;AACH,eAAO,OAAO,KAAK,MAAM,IAAI;AAAA,MACjC;AAAA,IACJ;AAGA,eAAW,CAAC,KAAK,EAAE,IAAI,CAAC,KAAK,YAAY;AACrC,UAAI,CAAC,UAAU,IAAI,GAAG,GAAG;AACrB,eAAO,UAAU,KAAK,IAAI,IAAI;AAAA,MAClC;AAAA,IACJ;AAEA,WAAO;AAAA,EACX;AACJ;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -29,15 +29,94 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
|
|
|
29
29
|
var farseerApi_exports = {};
|
|
30
30
|
__export(farseerApi_exports, {
|
|
31
31
|
FarseerApi: () => FarseerApi,
|
|
32
|
-
|
|
32
|
+
applySourceFolderChange: () => applySourceFolderChange,
|
|
33
|
+
findScriptInFolder: () => findScriptInFolder,
|
|
34
|
+
loadDimensionTableViaEntitiesApi: () => loadDimensionTableViaEntitiesApi,
|
|
35
|
+
mergeAppUpdate: () => mergeAppUpdate
|
|
33
36
|
});
|
|
34
37
|
module.exports = __toCommonJS(farseerApi_exports);
|
|
35
38
|
var import_axios = __toESM(require("axios"));
|
|
39
|
+
var import_chalk = __toESM(require("chalk"));
|
|
36
40
|
var farseer = __toESM(require("farseer-client"));
|
|
37
41
|
var import_configService = require("./configService");
|
|
38
42
|
var import_farseerService = require("./farseerService");
|
|
39
43
|
var import_errorFormatter = require("../utils/errorFormatter");
|
|
40
44
|
var import_logger = require("../utils/logger");
|
|
45
|
+
function mergeAppUpdate(current, changes) {
|
|
46
|
+
return {
|
|
47
|
+
name: changes.name ?? current.name,
|
|
48
|
+
description: changes.description ?? current.description ?? "",
|
|
49
|
+
expectedArguments: changes.expectedArguments ?? current.expectedArguments ?? [],
|
|
50
|
+
mainScriptFileId: changes.mainScriptFileId ?? current.mainScriptFileId ?? null,
|
|
51
|
+
sourceFolderId: changes.sourceFolderId ?? current.sourceFolderId ?? null,
|
|
52
|
+
schedule: changes.schedule ?? current.schedule ?? null,
|
|
53
|
+
runnerName: changes.runnerName ?? current.runnerName ?? null,
|
|
54
|
+
runnerImage: changes.runnerImage ?? current.runnerImage ?? null,
|
|
55
|
+
predefinedActions: changes.predefinedActions ?? current.predefinedActions ?? []
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
function findScriptInFolder(folderScripts, name) {
|
|
59
|
+
return folderScripts.find((s) => s.name === name);
|
|
60
|
+
}
|
|
61
|
+
async function applySourceFolderChange(client, app, changes, options, caller) {
|
|
62
|
+
const cli = caller === "cli";
|
|
63
|
+
const hint = (text) => cli ? import_chalk.default.dim(text) : text;
|
|
64
|
+
let folderScripts = app.scriptFiles ?? [];
|
|
65
|
+
let sourceFolderId;
|
|
66
|
+
if (options.sourceFolder) {
|
|
67
|
+
let resolved;
|
|
68
|
+
try {
|
|
69
|
+
resolved = await client.resolveSourceFolder(options.sourceFolder);
|
|
70
|
+
} catch {
|
|
71
|
+
return [
|
|
72
|
+
`Source folder not found under Files/: ${options.sourceFolder}`,
|
|
73
|
+
hint('Use a path relative to Files/, e.g. "Scripts/MyApp".')
|
|
74
|
+
].join("\n");
|
|
75
|
+
}
|
|
76
|
+
sourceFolderId = resolved.id;
|
|
77
|
+
folderScripts = resolved.scripts;
|
|
78
|
+
if (!options.entrypoint && app.mainScriptFileId) {
|
|
79
|
+
const stillThere = folderScripts.some((s) => s.id === app.mainScriptFileId);
|
|
80
|
+
if (!stillThere) {
|
|
81
|
+
const files = folderScripts.map((s) => s.name).join(", ") || "(none)";
|
|
82
|
+
return [
|
|
83
|
+
"The app's current entrypoint is not in the new source folder.",
|
|
84
|
+
hint(
|
|
85
|
+
cli ? "Pass --entrypoint <script> (a file in the new folder) in the same command." : 'Pass "entrypoint" (a file in the new folder) in the same call.'
|
|
86
|
+
),
|
|
87
|
+
hint(`Files in this folder: ${files}`)
|
|
88
|
+
].join("\n");
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
let mainScriptFileId;
|
|
93
|
+
if (options.entrypoint) {
|
|
94
|
+
const match = findScriptInFolder(folderScripts, options.entrypoint);
|
|
95
|
+
if (!match) {
|
|
96
|
+
const files = folderScripts.map((s) => s.name).join(", ") || "(none)";
|
|
97
|
+
const lines = [
|
|
98
|
+
`Entrypoint not found in the source folder: ${options.entrypoint}`,
|
|
99
|
+
hint(`Files in this folder: ${files}`)
|
|
100
|
+
];
|
|
101
|
+
if (!options.sourceFolder) {
|
|
102
|
+
lines.push(
|
|
103
|
+
hint(
|
|
104
|
+
cli ? "To use a file from another folder, set it first with --source-folder <path>." : "To use a file from another folder, pass sourceFolder first."
|
|
105
|
+
)
|
|
106
|
+
);
|
|
107
|
+
}
|
|
108
|
+
return lines.join("\n");
|
|
109
|
+
}
|
|
110
|
+
mainScriptFileId = match.id;
|
|
111
|
+
}
|
|
112
|
+
if (sourceFolderId !== void 0) {
|
|
113
|
+
changes.sourceFolderId = sourceFolderId;
|
|
114
|
+
}
|
|
115
|
+
if (mainScriptFileId !== void 0) {
|
|
116
|
+
changes.mainScriptFileId = mainScriptFileId;
|
|
117
|
+
}
|
|
118
|
+
return null;
|
|
119
|
+
}
|
|
41
120
|
class FarseerApi {
|
|
42
121
|
constructor(accessToken, tenant, tenantId) {
|
|
43
122
|
this.isRefreshing = false;
|
|
@@ -377,6 +456,12 @@ You may need to use --tenant-id to specify a different tenant ID.`
|
|
|
377
456
|
return [];
|
|
378
457
|
}
|
|
379
458
|
}
|
|
459
|
+
async resolveSourceFolder(relativePath) {
|
|
460
|
+
const segments = relativePath.split("/").map((s) => s.trim()).filter(Boolean);
|
|
461
|
+
const folder = await this.getItemByPath(["Files", ...segments]);
|
|
462
|
+
const scripts = await this.resolveAppScripts(folder.id);
|
|
463
|
+
return { id: folder.id, scripts };
|
|
464
|
+
}
|
|
380
465
|
/**
|
|
381
466
|
* Get app by name
|
|
382
467
|
*/
|
|
@@ -405,28 +490,19 @@ You may need to use --tenant-id to specify a different tenant ID.`
|
|
|
405
490
|
/**
|
|
406
491
|
* Update an app
|
|
407
492
|
*/
|
|
408
|
-
async updateApp(referenceId, update) {
|
|
409
|
-
await this.client.put(`/remoteJobs/${referenceId}`,
|
|
410
|
-
...update,
|
|
411
|
-
schedule: null,
|
|
412
|
-
runnerName: null,
|
|
413
|
-
predefinedActions: []
|
|
414
|
-
});
|
|
493
|
+
async updateApp(referenceId, update, currentApp) {
|
|
494
|
+
await this.client.put(`/remoteJobs/${referenceId}`, mergeAppUpdate(currentApp, update));
|
|
415
495
|
const app = await this.getApp(referenceId);
|
|
416
496
|
if (!app) {
|
|
417
|
-
throw new Error(
|
|
497
|
+
throw new Error(`Failed to fetch updated app ${referenceId}`);
|
|
418
498
|
}
|
|
419
499
|
return app;
|
|
420
500
|
}
|
|
421
501
|
/**
|
|
422
502
|
* Delete an app
|
|
423
503
|
*/
|
|
424
|
-
async deleteApp(
|
|
425
|
-
|
|
426
|
-
if (isNaN(numericId)) {
|
|
427
|
-
throw new Error(`Invalid app reference ID: ${referenceId}`);
|
|
428
|
-
}
|
|
429
|
-
await this.client.post("/folders/deleteItems", [{ id: numericId }]);
|
|
504
|
+
async deleteApp(itemNodeId) {
|
|
505
|
+
await this.client.post("/folders/deleteItems", [{ id: itemNodeId }]);
|
|
430
506
|
}
|
|
431
507
|
/**
|
|
432
508
|
* Run an app with arguments
|
|
@@ -584,6 +660,9 @@ async function loadDimensionTableViaEntitiesApi(nativeClient, name) {
|
|
|
584
660
|
// Annotate the CommonJS export names for ESM import in node:
|
|
585
661
|
0 && (module.exports = {
|
|
586
662
|
FarseerApi,
|
|
587
|
-
|
|
663
|
+
applySourceFolderChange,
|
|
664
|
+
findScriptInFolder,
|
|
665
|
+
loadDimensionTableViaEntitiesApi,
|
|
666
|
+
mergeAppUpdate
|
|
588
667
|
});
|
|
589
668
|
//# sourceMappingURL=farseerApi.js.map
|