farseer-cli 1.18.0 → 1.19.0
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 +2 -2
- package/dist/commands/app.js.map +0 -1
- package/dist/commands/apps.js.map +0 -1
- package/dist/commands/cells.js.map +0 -1
- package/dist/commands/code.js.map +0 -1
- package/dist/commands/config.js.map +0 -1
- package/dist/commands/dashboards.js.map +0 -1
- package/dist/commands/diff.js.map +0 -1
- package/dist/commands/dimensions.js.map +0 -1
- package/dist/commands/files.js.map +0 -1
- package/dist/commands/formula.js.map +0 -1
- package/dist/commands/install.js.map +0 -1
- package/dist/commands/list.js.map +0 -1
- package/dist/commands/login.js +3 -3
- package/dist/commands/login.js.map +1 -2
- package/dist/commands/logout.js.map +0 -1
- package/dist/commands/mcp-server.js.map +0 -1
- package/dist/commands/model.js.map +0 -1
- package/dist/commands/pipeline.js.map +0 -1
- package/dist/commands/pull.js +1 -1
- package/dist/commands/pull.js.map +1 -2
- package/dist/commands/push.js +2 -2
- package/dist/commands/push.js.map +1 -2
- package/dist/commands/refresh.js.map +0 -1
- package/dist/commands/run.js.map +0 -1
- package/dist/commands/sheets.js.map +0 -1
- package/dist/commands/status.js.map +0 -1
- package/dist/commands/tool.js.map +0 -1
- package/dist/commands/variables.js.map +0 -1
- package/dist/commands/whoami.js.map +0 -1
- package/dist/index.js +24 -10
- package/dist/index.js.map +1 -2
- package/dist/mcp/index.js.map +0 -1
- package/dist/mcp/prompts/workflows.js.map +0 -1
- package/dist/mcp/resources/documentation.js.map +0 -1
- package/dist/mcp/server.js.map +0 -1
- package/dist/mcp/skills.js.map +0 -1
- package/dist/mcp/tools/appTools.js.map +0 -1
- package/dist/mcp/tools/authTools.js +1 -1
- package/dist/mcp/tools/authTools.js.map +1 -2
- package/dist/mcp/tools/cellTools.js.map +0 -1
- package/dist/mcp/tools/dashboardTools.js.map +0 -1
- package/dist/mcp/tools/dataTools.js.map +0 -1
- package/dist/mcp/tools/folderTools.js.map +0 -1
- package/dist/mcp/tools/modelTools.js.map +0 -1
- package/dist/mcp/tools/pipelineContract.js.map +0 -1
- package/dist/mcp/tools/pipelineTools.js.map +0 -1
- package/dist/mcp/tools/runTools.js.map +0 -1
- package/dist/mcp/tools/sheetTools.js.map +0 -1
- package/dist/mcp/tools/syncTools.js +2 -2
- package/dist/mcp/tools/syncTools.js.map +1 -2
- package/dist/mcp/utils/helpers.js.map +0 -1
- package/dist/mcp/utils/launchPin.js.map +0 -1
- package/dist/mcp/utils/registerTool.js.map +0 -1
- package/dist/mcp/utils/session.js.map +0 -1
- package/dist/mcp/utils/tenantPin.js.map +0 -1
- package/dist/pipeline/compatibility.js.map +0 -1
- package/dist/pipeline/connect.js.map +0 -1
- package/dist/pipeline/create.js.map +0 -1
- package/dist/pipeline/errors.js.map +0 -1
- package/dist/pipeline/generated-reference.json +22 -10
- package/dist/pipeline/guide.js.map +0 -1
- package/dist/pipeline/init.js.map +0 -1
- package/dist/pipeline/operations.js.map +0 -1
- package/dist/pipeline/query.js.map +0 -1
- package/dist/pipeline/queryDownloads.js.map +0 -1
- package/dist/pipeline/queryWorker.js.map +0 -1
- package/dist/pipeline/readiness.js.map +0 -1
- package/dist/pipeline/reference.js.map +0 -1
- package/dist/pipeline/requests.js.map +0 -1
- package/dist/pipeline/runArguments.js.map +0 -1
- package/dist/pipeline/runtime.js.map +0 -1
- package/dist/pipeline/service.js.map +0 -1
- package/dist/services/agentApprovalFetch.js +7 -3
- package/dist/services/agentApprovalFetch.js.map +1 -2
- package/dist/services/appSyncService.js.map +0 -1
- package/dist/services/apps.js.map +0 -1
- package/dist/services/authErrors.js.map +0 -1
- package/dist/services/codefirst/api.js +38 -5
- package/dist/services/codefirst/api.js.map +1 -2
- package/dist/services/codefirst/binaryDisk.js.map +0 -1
- package/dist/services/codefirst/byteHashes.js +5 -0
- package/dist/services/codefirst/byteHashes.js.map +1 -2
- package/dist/services/codefirst/documents.js +41 -15
- package/dist/services/codefirst/documents.js.map +1 -2
- package/dist/services/codefirst/layoutBinaryProjection.js +24 -13
- package/dist/services/codefirst/layoutBinaryProjection.js.map +1 -2
- package/dist/services/codefirst/layoutCompose.js +44 -38
- package/dist/services/codefirst/layoutCompose.js.map +1 -2
- package/dist/services/codefirst/layoutCore.js +14 -1
- package/dist/services/codefirst/layoutCore.js.map +1 -2
- package/dist/services/codefirst/layoutPaths.js +80 -4
- package/dist/services/codefirst/layoutPaths.js.map +1 -2
- package/dist/services/codefirst/layoutProjection.js +73 -39
- package/dist/services/codefirst/layoutProjection.js.map +1 -2
- package/dist/services/codefirst/layoutReadback.js +357 -130
- package/dist/services/codefirst/layoutReadback.js.map +2 -3
- package/dist/services/codefirst/layoutReadbackPlacement.js +94 -57
- package/dist/services/codefirst/layoutReadbackPlacement.js.map +2 -3
- package/dist/services/codefirst/layoutReceipt.js +283 -243
- package/dist/services/codefirst/layoutReceipt.js.map +2 -3
- package/dist/services/codefirst/layoutScan.js +208 -110
- package/dist/services/codefirst/layoutScan.js.map +1 -2
- package/dist/services/codefirst/output.js +76 -10
- package/dist/services/codefirst/output.js.map +1 -2
- package/dist/services/codefirst/types.js.map +0 -1
- package/dist/services/codefirst/workflow.js +65 -29
- package/dist/services/codefirst/workflow.js.map +2 -3
- package/dist/services/codefirst/workspace.js.map +0 -1
- package/dist/services/codefirst/workspaceLock.js.map +0 -1
- package/dist/services/codefirst/workspaceRoot.js +2 -1
- package/dist/services/codefirst/workspaceRoot.js.map +1 -2
- package/dist/services/configService.js.map +0 -1
- package/dist/services/credentials.js.map +0 -1
- package/dist/services/farseerService.js +3 -1
- package/dist/services/farseerService.js.map +1 -2
- package/dist/services/httpError.js.map +0 -1
- package/dist/services/modelExport.js.map +0 -1
- package/dist/services/organisation.js.map +0 -1
- package/dist/services/preflight.js.map +0 -1
- package/dist/services/realms.js.map +0 -1
- package/dist/services/syncService.js +3 -3
- package/dist/services/syncService.js.map +1 -2
- package/dist/skills/pipeline.js.map +0 -1
- package/dist/utils/agentSandbox.js.map +0 -1
- package/dist/utils/cliOptions.js.map +0 -1
- package/dist/utils/constants.js.map +0 -1
- package/dist/utils/entityResolver.js.map +0 -1
- package/dist/utils/errorFormatter.js +59 -11
- package/dist/utils/errorFormatter.js.map +1 -2
- package/dist/utils/fileLogger.js.map +0 -1
- package/dist/utils/fileValidation.js.map +0 -1
- package/dist/utils/folderMatch.js.map +0 -1
- package/dist/utils/formulaFilters.js.map +0 -1
- package/dist/utils/helpers.js.map +0 -1
- package/dist/utils/logger.js.map +0 -1
- package/dist/utils/nameResolver.js.map +0 -1
- package/dist/utils/packageManager.js.map +0 -1
- package/dist/utils/syncReporting.js.map +0 -1
- package/dist/utils/syncScope.js.map +0 -1
- package/dist/utils/updateCheck.js.map +0 -1
- package/dist/utils/variableValues.js.map +0 -1
- package/dist/utils/workspace.js.map +0 -1
- package/docs/cli-guide.md +1 -1
- package/docs/import-workflows.md +14 -14
- package/docs/new-app-template.md +1 -1
- package/docs/pipeline-client-guide.md +1 -1
- package/docs/pipeline-reference.md +292 -3
- package/package.json +2 -2
- package/skills/farseer-analysis/SKILL.md +132 -0
- package/skills/farseer-dashboards/SKILL.md +40 -0
- package/skills/farseer-formulas/SKILL.md +165 -0
- package/skills/farseer-model/SKILL.md +119 -0
- package/skills/pipeline-authoring/SKILL.md +6 -4
- package/skills/pipeline-authoring/practices.md +6 -5
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/utils/fileLogger.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * File Logger\n *\n * Writes debug logs to ~/.farseer/logs/ for diagnostics.\n * On error, prints the log path so users can share the file for support.\n *\n * Log rotation: keeps last 10 log files, deletes oldest on startup.\n * Format: one JSON line per entry (JSONL) for easy parsing.\n *\n * Usage:\n * import { fileLogger } from './utils/fileLogger';\n * fileLogger.init(); // Call once at startup\n * fileLogger.log('http', { method: 'GET', url: '...' });\n * fileLogger.error('push', error);\n * fileLogger.getLogPath(); // Returns current log file path\n */\n\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport * as os from 'os';\nimport { CLI_VERSION } from './constants';\n\nconst LOG_DIR = path.join(os.homedir(), '.farseer', 'logs');\nconst MAX_LOG_FILES = 10;\n\nlet logFilePath: string | null = null;\nlet logStream: fs.WriteStream | null = null;\n\n/**\n * Create a timestamped log file path.\n */\nfunction createLogPath(): string {\n const ts = new Date().toISOString().replace(/[:.]/g, '-');\n return path.join(LOG_DIR, `farseer-${ts}.log`);\n}\n\n/**\n * Remove old log files, keeping only the newest MAX_LOG_FILES.\n */\nfunction rotateLogFiles(): void {\n try {\n const files = fs\n .readdirSync(LOG_DIR)\n .filter((f) => f.startsWith('farseer-') && f.endsWith('.log'))\n .sort()\n .reverse();\n\n for (const file of files.slice(MAX_LOG_FILES)) {\n try {\n fs.unlinkSync(path.join(LOG_DIR, file));\n } catch {\n // Ignore deletion errors\n }\n }\n } catch {\n // Log dir might not exist yet\n }\n}\n\n/**\n * Write a structured log entry.\n */\nfunction writeEntry(level: string, category: string, data?: unknown): void {\n if (!logStream) return;\n try {\n const entry = {\n ts: new Date().toISOString(),\n level,\n cat: category,\n ...(data !== undefined ? { data } : {}),\n };\n logStream.write(JSON.stringify(entry) + '\\n');\n } catch {\n // Never throw from logger\n }\n}\n\n/**\n * Write a log entry synchronously (bypasses stream buffering).\n * Used in crash handlers where process.exit follows immediately.\n */\nfunction writeSyncEntry(level: string, category: string, data?: unknown): void {\n if (!logFilePath) return;\n try {\n const entry = {\n ts: new Date().toISOString(),\n level,\n cat: category,\n ...(data !== undefined ? { data } : {}),\n };\n fs.appendFileSync(logFilePath, JSON.stringify(entry) + '\\n');\n } catch {\n // Never throw from logger\n }\n}\n\n/**\n * Extract error details for logging.\n *\n * Handles:\n * - Error instances (including axios errors with .response)\n * - fetch Response objects thrown by farseer-client's generated runtime\n * - plain objects / primitives\n *\n * The cause chain is included when present so nested errors remain inspectable.\n */\nfunction serializeError(error: unknown): Record<string, unknown> {\n if (error instanceof Error) {\n const result: Record<string, unknown> = {\n name: error.name,\n message: error.message,\n stack: error.stack,\n };\n // Axios errors\n if ('response' in error) {\n const e = error as any;\n result.status = e.response?.status;\n result.statusText = e.response?.statusText;\n result.responseData = e.response?.data;\n result.url = e.config?.url;\n result.method = e.config?.method;\n }\n const cause = (error as Error & { cause?: unknown }).cause;\n if (cause !== undefined && cause !== error) {\n result.cause = serializeError(cause);\n }\n return result;\n }\n\n // fetch Response thrown by farseer-client \u2014 preserve status/url so the log\n // is useful even though we can't synchronously read the body here.\n if (\n error &&\n typeof error === 'object' &&\n typeof (error as { status?: unknown }).status === 'number' &&\n typeof (error as { text?: unknown }).text === 'function'\n ) {\n const resp = error as { status: number; statusText?: string; url?: string };\n return {\n kind: 'HttpResponse',\n status: resp.status,\n statusText: resp.statusText,\n url: resp.url,\n };\n }\n\n if (typeof error === 'object' && error !== null) {\n try {\n return JSON.parse(JSON.stringify(error));\n } catch {\n return { raw: String(error) };\n }\n }\n return { raw: String(error) };\n}\n\nlet initialized = false;\nlet crashHandlersInstalled = false;\nlet exitOnUnhandledRejection = true;\n\nexport const fileLogger = {\n /**\n * Initialize the file logger. Idempotent \u2014 safe to call multiple times.\n * Creates the log directory and file, writes session header.\n */\n init(): void {\n if (initialized) return;\n initialized = true;\n try {\n fs.mkdirSync(LOG_DIR, { recursive: true });\n rotateLogFiles();\n logFilePath = createLogPath();\n logStream = fs.createWriteStream(logFilePath, { flags: 'a' });\n\n // Write session header\n writeEntry('info', 'session', {\n version: CLI_VERSION,\n node: process.version,\n platform: os.platform(),\n arch: os.arch(),\n argv: process.argv.slice(2),\n cwd: process.cwd(),\n pid: process.pid,\n });\n } catch {\n // If we can't create logs, continue without file logging\n logFilePath = null;\n logStream = null;\n }\n },\n\n /**\n * Log an informational entry.\n */\n log(category: string, data?: unknown): void {\n writeEntry('info', category, data);\n },\n\n /**\n * Log a warning.\n */\n warn(category: string, data?: unknown): void {\n writeEntry('warn', category, data);\n },\n\n /**\n * Log an error with full details.\n * Uses async stream write (same as other entries) for correct ordering.\n * Only crash handlers use writeSyncEntry where process.exit follows immediately.\n */\n error(category: string, error: unknown, context?: Record<string, unknown>): void {\n writeEntry('error', category, {\n ...serializeError(error),\n ...(context || {}),\n });\n },\n\n /**\n * Log an HTTP request/response (for debug).\n */\n http(method: string, url: string, status?: number, durationMs?: number, error?: unknown): void {\n const data: Record<string, unknown> = { method, url };\n if (status !== undefined) data.status = status;\n if (durationMs !== undefined) data.durationMs = durationMs;\n if (error) data.error = serializeError(error);\n writeEntry(error ? 'error' : 'info', 'http', data);\n },\n\n /**\n * Log an MCP tool call.\n */\n toolCall(toolName: string, params: unknown, success: boolean, durationMs?: number, error?: unknown): void {\n const data: Record<string, unknown> = { tool: toolName, params, success };\n if (durationMs !== undefined) data.durationMs = durationMs;\n if (error) data.error = serializeError(error);\n writeEntry(success ? 'info' : 'error', 'mcp-tool', data);\n },\n\n /**\n * Get the current log file path (to tell user where to find it).\n */\n getLogPath(): string | null {\n return logFilePath;\n },\n\n /**\n * Close the log stream. Call on process exit.\n */\n close(): void {\n if (logStream) {\n logStream.end();\n logStream = null;\n }\n },\n\n /**\n * Install crash handlers that write to the log before exit. Idempotent.\n *\n * `exitOnRejection` is the difference between the two surfaces. A command is\n * one process for one operation: a rejection it did not catch means the\n * operation did not happen, and a shell that reads the exit code has to be\n * told that. A server is one process for many operations, each of which\n * already answers its own caller, so ending it would take out a session over\n * something that has been reported.\n *\n * The listeners are registered once, but the policy is taken from the latest\n * call and read when a rejection arrives: the CLI entry point installs these\n * before it knows which command it is running, and the MCP server, which\n * must not exit, installs them again once it does.\n */\n installCrashHandlers({ exitOnRejection = true }: { exitOnRejection?: boolean } = {}): void {\n exitOnUnhandledRejection = exitOnRejection;\n if (crashHandlersInstalled) return;\n crashHandlersInstalled = true;\n process.on('uncaughtException', (err) => {\n // Use sync write \u2014 stream may not flush before process.exit\n writeSyncEntry('fatal', 'crash', {\n source: 'uncaughtException',\n ...serializeError(err),\n });\n if (logFilePath) {\n console.error(`\\nCrash log written to: ${logFilePath}`);\n }\n process.exit(1);\n });\n\n process.on('unhandledRejection', (reason) => {\n // Pass reason directly \u2014 serializeError handles Error, objects, and primitives.\n // Wrapping in new Error(String(reason)) would lose structured fields on plain objects.\n writeSyncEntry('fatal', 'crash', {\n source: 'unhandledRejection',\n ...serializeError(reason),\n });\n if (!exitOnUnhandledRejection) {\n return;\n }\n // Node has ended the process on these since v15, and registering this\n // handler is what stops it. Without the exit, a command whose await\n // escaped its try block prints nothing and reports success.\n console.error(`\\nCommand failed: ${reason instanceof Error ? reason.message : String(reason)}`);\n if (logFilePath) {\n console.error(`Crash log written to: ${logFilePath}`);\n }\n process.exit(1);\n });\n },\n};\n"],
|
|
5
4
|
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAiBA,SAAoB;AACpB,WAAsB;AACtB,SAAoB;AACpB,uBAA4B;AAE5B,MAAM,UAAU,KAAK,KAAK,GAAG,QAAQ,GAAG,YAAY,MAAM;AAC1D,MAAM,gBAAgB;AAEtB,IAAI,cAA6B;AACjC,IAAI,YAAmC;AAKvC,SAAS,gBAAwB;AAC7B,QAAM,MAAK,oBAAI,KAAK,GAAE,YAAY,EAAE,QAAQ,SAAS,GAAG;AACxD,SAAO,KAAK,KAAK,SAAS,WAAW,EAAE,MAAM;AACjD;AAKA,SAAS,iBAAuB;AAC5B,MAAI;AACA,UAAM,QAAQ,GACT,YAAY,OAAO,EACnB,OAAO,CAAC,MAAM,EAAE,WAAW,UAAU,KAAK,EAAE,SAAS,MAAM,CAAC,EAC5D,KAAK,EACL,QAAQ;AAEb,eAAW,QAAQ,MAAM,MAAM,aAAa,GAAG;AAC3C,UAAI;AACA,WAAG,WAAW,KAAK,KAAK,SAAS,IAAI,CAAC;AAAA,MAC1C,QAAQ;AAAA,MAER;AAAA,IACJ;AAAA,EACJ,QAAQ;AAAA,EAER;AACJ;AAKA,SAA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Q,KAAK,CAAC;AAAA,IAClB,CAAC;AAED,YAAQ,GAAG,sBAAsB,CAAC,WAAW;AAGzC,qBAAe,SAAS,SAAS;AAAA,QAC7B,QAAQ;AAAA,QACR,GAAG,eAAe,MAAM;AAAA,MAC5B,CAAC;AACD,UAAI,CAAC,0BAA0B;AAC3B;AAAA,MACJ;AAIA,cAAQ,MAAM;AAAA,kBAAqB,kBAAkB,QAAQ,OAAO,UAAU,OAAO,MAAM,CAAC,EAAE;AAC9F,UAAI,aAAa;AACb,gBAAQ,MAAM,yBAAyB,WAAW,EAAE;AAAA,MACxD;AACA,cAAQ,KAAK,CAAC;AAAA,IAClB,CAAC;AAAA,EACL;AACJ;",
|
|
6
5
|
"names": []
|
|
7
6
|
}
|
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/utils/fileValidation.ts"],
|
|
4
|
-
"sourcesContent": ["import * as path from 'path';\n\n/**\n * Pre-flight validation that mirrors the backend's Farseer Files rules so the\n * CLI can refuse a doomed upload locally \u2014 with an actionable message \u2014\n * instead of letting the user see a cryptic `HTTP 400 {\"code\":\"BadRequest\"}`\n * coming back from the API after the request is already in flight.\n *\n * Source of truth on the backend:\n * - Extension whitelist:\n * `backend/app/openapi/v3/services/farseerFileService.ts`\n * (FILE_EXTENSION_WHITELIST static + validateFileExtension())\n * - Name length: `backend/app/openapi/util/itemNodeNameUtil.ts`\n * (MAX_NAME_SIZE = 256, trim, non-empty)\n *\n * Keep this list in lockstep with the backend. If the backend adds an\n * extension, add it here so users stop seeing \"File type not allowed\" for\n * something that is actually allowed.\n */\n\nexport const BACKEND_EXTENSION_WHITELIST: ReadonlySet<string> = new Set([\n // Office / spreadsheets\n 'xls',\n 'xlsx',\n 'csv',\n 'pdf',\n 'docx',\n // Code (frontend / scripts)\n 'js',\n 'jsx',\n 'ts',\n 'tsx',\n // Code (Python)\n 'py',\n // Markup / config / data\n 'xml',\n 'json',\n 'yaml',\n 'yml',\n 'html',\n 'css',\n 'scss',\n 'md',\n 'txt',\n // Images\n 'jpg',\n 'jpeg',\n 'png',\n 'gif',\n 'svg',\n 'webp',\n // Archives / columnar data\n 'zip',\n 'parquet',\n]);\n\nexport const MAX_FILE_NAME_LENGTH = 256;\n\nexport interface ValidationFailure {\n filePath: string;\n reason: 'extension_not_allowed' | 'name_empty' | 'name_too_long' | 'empty_content' | 'unresolved_conflict_markers';\n detail: string;\n hint?: string;\n}\n\n/**\n * Detect git-style conflict markers left over from an unresolved\n * `merge_markers` pull. Pushing a file with these markers would upload\n * broken syntax to the backend (the file wouldn't compile / parse). The\n * patterns intentionally match the exact strings the CLI writes\n * (syncService.ts: MERGE_MARKER_*) so we don't false-positive on user\n * code that happens to contain `<<<<<<<` in some other context.\n *\n * We refuse on EITHER unique sentinel \u2014 the earlier \"require both\n * LOCAL and REMOTE\" gate let a partially-resolved file slip through\n * (user deleted only one half of the block). The `=======` separator\n * is intentionally NOT included: bare `=======` lines are common in\n * RST headings and ASCII tables, so flagging them would false-positive\n * on legitimate text content.\n */\nconst CONFLICT_MARKER_LOCAL = /^<<<<<<< LOCAL \\(your version\\)$/m;\nconst CONFLICT_MARKER_REMOTE = /^>>>>>>> REMOTE$/m;\n\n/**\n * Best-effort check for \"is this file content text we can safely splice\n * git-style merge markers into?\". Used to gate the `merge_markers`\n * conflict resolution: writing markers into a .png / .xlsx / .zip\n * corrupts the binary, and the .toString('utf-8') round-trip used by\n * the merge logic flips bytes silently.\n *\n * Two-step check:\n * 1. File extension allowlist \u2014 fast path, deterministic.\n * 2. Null-byte heuristic on the content \u2014 covers misnamed files\n * and unknown extensions.\n *\n * False negatives (binary that passes both checks) just write garbage\n * markers; push pre-flight then refuses to upload because the marker\n * pattern is mangled. False positives (text that trips null-byte) just\n * mean the user gets the keep_both fallback \u2014 annoying but safe.\n */\n// Symmetrical with BACKEND_EXTENSION_WHITELIST: only formats the user\n// can actually push end up here. .mjs / .cjs are technically text but\n// they're not on the backend whitelist (and not in DEFAULT_SCRIPT_EXTENSIONS),\n// so offering merge_markers for them would lead the user through a manual\n// resolve only to hit pre-flight rejection on push. Drop them to match\n// the pre-flight's reality.\nconst KNOWN_TEXT_EXTENSIONS: ReadonlySet<string> = new Set([\n '.ts',\n '.tsx',\n '.js',\n '.jsx',\n '.json',\n '.md',\n '.txt',\n '.html',\n '.css',\n '.scss',\n '.yaml',\n '.yml',\n '.xml',\n '.py',\n '.csv',\n]);\n\nexport function isLikelyTextFile(filePath: string, content?: Buffer): boolean {\n const ext = path.extname(filePath).toLowerCase();\n if (KNOWN_TEXT_EXTENSIONS.has(ext)) return true;\n if (!content) return false;\n // Sample first 8KB for a NUL byte. Binary formats (PDF, PNG, ZIP,\n // XLSX, \u2026) have one almost immediately; text files practically never.\n const slice = content.subarray(0, 8 * 1024);\n return !slice.includes(0);\n}\n\nexport function hasUnresolvedConflictMarkers(content: string | Buffer): boolean {\n const text = Buffer.isBuffer(content) ? content.toString('utf-8') : content;\n // OR (not AND) across the unique sentinels: a half-resolved file where\n // the user kept only the LOCAL or REMOTE marker still uploads broken\n // text. The `=======` separator is omitted on purpose \u2014 RST headings\n // and ASCII tables use bare `=======` lines and would false-positive.\n return CONFLICT_MARKER_LOCAL.test(text) || CONFLICT_MARKER_REMOTE.test(text);\n}\n\n/**\n * Same algorithm the backend uses (`tail(name.split('.'))`): split on `.`\n * and take the last segment, lowercased. This means:\n * - `foo.ts` \u2192 `ts`\n * - `Foo.TS` \u2192 `ts` (case-insensitive \u2014 backend folds case before lookup)\n * - `.gitignore` \u2192 `gitignore` (rejected, not in whitelist)\n * - `Makefile` \u2192 `makefile` (rejected \u2014 no `.`, returns the basename lowercased)\n * - `archive.tar.gz` \u2192 `gz` (rejected)\n */\nexport function getBackendExtension(fileName: string): string {\n const base = path.basename(fileName);\n const parts = base.split('.');\n return parts[parts.length - 1].toLowerCase();\n}\n\nexport function isExtensionAllowed(fileName: string): boolean {\n return BACKEND_EXTENSION_WHITELIST.has(getBackendExtension(fileName));\n}\n\nexport interface ValidatedFile {\n filePath: string;\n size: number;\n /**\n * Optional file content. When provided, the validator additionally\n * checks for unresolved git-style conflict markers (left behind by a\n * `merge_markers` pull resolution that the user hasn't cleaned up).\n * Push pre-flight passes content; tests/abstract callers can omit it.\n */\n content?: Buffer;\n}\n\n/**\n * Validate a single file the CLI is about to upload. Returns null when the\n * file would pass the backend's create/update validation, otherwise a\n * `ValidationFailure` describing the rule that would reject it.\n *\n * `size` is required so we can also flag empty files: the backend's\n * multipart parser tends to surface a content-less request as the cryptic\n * `{\"code\":\"BadRequest\"}` body that field reports point to.\n */\nexport function validateFileForUpload(file: ValidatedFile): ValidationFailure | null {\n const baseName = path.basename(file.filePath);\n const trimmed = baseName.trim();\n\n if (trimmed.length === 0) {\n return {\n filePath: file.filePath,\n reason: 'name_empty',\n detail: 'Filename is empty after trimming whitespace',\n hint: 'Rename the file to a non-empty name before pushing.',\n };\n }\n\n if (trimmed.length > MAX_FILE_NAME_LENGTH) {\n return {\n filePath: file.filePath,\n reason: 'name_too_long',\n detail: `Filename is ${trimmed.length} characters; backend rejects names longer than ${MAX_FILE_NAME_LENGTH}`,\n hint: 'Shorten the filename and try again.',\n };\n }\n\n if (!isExtensionAllowed(baseName)) {\n const ext = getBackendExtension(baseName);\n return {\n filePath: file.filePath,\n reason: 'extension_not_allowed',\n detail: `Extension \".${ext}\" is not in the backend whitelist`,\n hint: `Allowed: ${[...BACKEND_EXTENSION_WHITELIST]\n .map((e) => '.' + e)\n .sort()\n .join(', ')}`,\n };\n }\n\n if (file.size === 0) {\n return {\n filePath: file.filePath,\n reason: 'empty_content',\n detail: 'File is empty (0 bytes)',\n hint: 'Empty files often come back as opaque \"BadRequest\" from the upload endpoint. Add at least one byte before pushing.',\n };\n }\n\n if (file.content && hasUnresolvedConflictMarkers(file.content)) {\n return {\n filePath: file.filePath,\n reason: 'unresolved_conflict_markers',\n detail: 'File contains unresolved git-style conflict markers (<<<<<<< LOCAL / ======= / >>>>>>> REMOTE)',\n hint: \"Open the file, pick which version to keep, remove the marker lines, then 'farseer push' again.\",\n };\n }\n\n return null;\n}\n\n/**\n * Validate a batch and split into pushable + rejected. The push command uses\n * this to render a single grouped message (\"4 file(s) skipped: \u2026\") and exit\n * cleanly without sending any request that we know will fail.\n */\nexport function partitionForUpload(files: ValidatedFile[]): {\n valid: ValidatedFile[];\n rejected: ValidationFailure[];\n} {\n const valid: ValidatedFile[] = [];\n const rejected: ValidationFailure[] = [];\n for (const file of files) {\n const failure = validateFileForUpload(file);\n if (failure) rejected.push(failure);\n else valid.push(file);\n }\n return { valid, rejected };\n}\n"],
|
|
5
4
|
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,WAAsB;AAoBf,MAAM,8BAAmD,oBAAI,IAAI;AAAA;AAAA,EAEpE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA;AAAA,EAEA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA;AAAA,EAEA;AAAA;AAAA,EAEA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA;AAAA,EAEA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA;AAAA,EAEA;AAAA,EACA;AACJ,CAAC;AAEM,MAAM,uBAAuB;AAwBpC,MAAM,wBAAwB;AAC9B,MAAM,yBAAyB;AAyB/B,MAAM,wBAA6C,oBAAI,IAAI;AAAA,EACvD;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACJ,CAAC;AAEM,SAAS,iBAAiB,UAAkB,SAA2B;AAC1E,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AAY,CAAC,GAAG,2BAA2B,EAC5C,IAAI,CAAC,MAAM,MAAM,CAAC,EAClB,KAAK,EACL,KAAK,IAAI,CAAC;AAAA,IACnB;AAAA,EACJ;AAEA,MAAI,KAAK,SAAS,GAAG;AACjB,WAAO;AAAA,MACH,UAAU,KAAK;AAAA,MACf,QAAQ;AAAA,MACR,QAAQ;AAAA,MACR,MAAM;AAAA,IACV;AAAA,EACJ;AAEA,MAAI,KAAK,WAAW,6BAA6B,KAAK,OAAO,GAAG;AAC5D,WAAO;AAAA,MACH,UAAU,KAAK;AAAA,MACf,QAAQ;AAAA,MACR,QAAQ;AAAA,MACR,MAAM;AAAA,IACV;AAAA,EACJ;AAEA,SAAO;AACX;AAOO,SAAS,mBAAmB,OAGjC;AACE,QAAM,QAAyB,CAAC;AAChC,QAAM,WAAgC,CAAC;AACvC,aAAW,QAAQ,OAAO;AACtB,UAAM,UAAU,sBAAsB,IAAI;AAC1C,QAAI,QAAS,UAAS,KAAK,OAAO;AAAA,QAC7B,OAAM,KAAK,IAAI;AAAA,EACxB;AACA,SAAO,EAAE,OAAO,SAAS;AAC7B;",
|
|
6
5
|
"names": []
|
|
7
6
|
}
|
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/utils/folderMatch.ts"],
|
|
4
|
-
"sourcesContent": ["/** Two sibling folders answer to the same name, and neither is an exact match. */\nexport class AmbiguousFolderError extends Error {}\n\n/**\n * Pick the folder a path segment names, out of one parent's listing.\n *\n * Exact first, because the backend allows `Sales` and `sales` to sit side by\n * side and only the typed name says which was meant. A case-insensitive match\n * is still accepted when it is the only candidate \u2014 that is the ordinary case,\n * where nothing is ambiguous and refusing would only be pedantic. Two\n * candidates and no exact match is refused rather than resolved by listing\n * order, which would silently write into whichever the backend returned first.\n */\nexport function matchFolderSegment<T extends { id: number; name: string }>(folders: T[], segment: string): T | null {\n const exact = folders.find((folder) => folder.name === segment);\n if (exact) {\n return exact;\n }\n\n const insensitive = folders.filter((folder) => folder.name.toLowerCase() === segment.toLowerCase());\n if (insensitive.length === 1) {\n return insensitive[0];\n }\n if (insensitive.length > 1) {\n const names = insensitive.map((folder) => `\"${folder.name}\"`).join(', ');\n throw new AmbiguousFolderError(\n `Folder name \"${segment}\" matches ${insensitive.length} folders that differ only in case: ${names}. ` +\n 'Use the exact name.',\n );\n }\n\n return null;\n}\n"],
|
|
5
4
|
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AACO,MAAM,6BAA6B,MAAM;AAAC;AAY1C,SAAS,mBAA2D,SAAc,SAA2B;AAChH,QAAM,QAAQ,QAAQ,KAAK,CAAC,WAAW,OAAO,SAAS,OAAO;AAC9D,MAAI,OAAO;AACP,WAAO;AAAA,EACX;AAEA,QAAM,cAAc,QAAQ,OAAO,CAAC,WAAW,OAAO,KAAK,YAAY,MAAM,QAAQ,YAAY,CAAC;AAClG,MAAI,YAAY,WAAW,GAAG;AAC1B,WAAO,YAAY,CAAC;AAAA,EACxB;AACA,MAAI,YAAY,SAAS,GAAG;AACxB,UAAM,QAAQ,YAAY,IAAI,CAAC,WAAW,IAAI,OAAO,IAAI,GAAG,EAAE,KAAK,IAAI;AACvE,UAAM,IAAI;AAAA,MACN,gBAAgB,OAAO,aAAa,YAAY,MAAM,sCAAsC,KAAK;AAAA,IAErG;AAAA,EACJ;AAEA,SAAO;AACX;",
|
|
6
5
|
"names": []
|
|
7
6
|
}
|
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/utils/formulaFilters.ts"],
|
|
4
|
-
"sourcesContent": ["const EXPRESSION_SYMBOLS = /[+\\-*/()<>=!,\"]/;\nconst GID = /^\\$\\d+$/;\n\n/** The formula parser needs a name with spaces, & or brackets double-quoted; an expression or a gid is left as written. */\nfunction quoteName(formula: string): string {\n return !EXPRESSION_SYMBOLS.test(formula) && /[\\s&[\\]]/.test(formula) ? `\"${formula}\"` : formula;\n}\n\n/**\n * The formula with [table, member] filters inside SUM, where Farseer applies them: the evaluate API's own `filters`\n * are named filters and ignore these pairs. An expression has no safe place for them, so it is refused.\n */\nexport function filtersInFormula(formula: string, filters: string[][]): string {\n if (filters.length === 0) return quoteName(formula);\n if (filters.some((pair) => pair.length !== 2)) {\n throw new Error('Each filter is a table and a member, as in [\"Years\", \"Y2025\"]');\n }\n const trimmed = formula.trim();\n const quoted = /^\"[^\"]+\"$/.test(trimmed);\n if (!quoted && EXPRESSION_SYMBOLS.test(trimmed)) {\n throw new Error(\n `\"${trimmed}\": a variable name with symbols such as - ( ) goes in double quotes. ` +\n 'An expression takes its filters inside the formula, as in SUM(\"Revenue\", \"Years\">\"Y2025\")',\n );\n }\n const variable = quoted || GID.test(trimmed) ? trimmed : `\"${trimmed}\"`;\n return `SUM(${[variable, ...filters.map(([table, member]) => `\"${table}\">\"${member}\"`)].join(', ')})`;\n}\n"],
|
|
5
4
|
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,MAAM,qBAAqB;AAC3B,MAAM,MAAM;AAGZ,SAAS,UAAU,SAAyB;AACxC,SAAO,CAAC,mBAAmB,KAAK,OAAO,KAAK,WAAW,KAAK,OAAO,IAAI,IAAI,OAAO,MAAM;AAC5F;AAMO,SAAS,iBAAiB,SAAiB,SAA6B;AAC3E,MAAI,QAAQ,WAAW,EAAG,QAAO,UAAU,OAAO;AAClD,MAAI,QAAQ,KAAK,CAAC,SAAS,KAAK,WAAW,CAAC,GAAG;AAC3C,UAAM,IAAI,MAAM,+DAA+D;AAAA,EACnF;AACA,QAAM,UAAU,QAAQ,KAAK;AAC7B,QAAM,SAAS,YAAY,KAAK,OAAO;AACvC,MAAI,CAAC,UAAU,mBAAmB,KAAK,OAAO,GAAG;AAC7C,UAAM,IAAI;AAAA,MACN,IAAI,OAAO;AAAA,IAEf;AAAA,EACJ;AACA,QAAM,WAAW,UAAU,IAAI,KAAK,OAAO,IAAI,UAAU,IAAI,OAAO;AACpE,SAAO,OAAO,CAAC,UAAU,GAAG,QAAQ,IAAI,CAAC,CAAC,OAAO,MAAM,MAAM,IAAI,KAAK,MAAM,MAAM,GAAG,CAAC,EAAE,KAAK,IAAI,CAAC;AACtG;",
|
|
6
5
|
"names": []
|
|
7
6
|
}
|
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/utils/helpers.ts"],
|
|
4
|
-
"sourcesContent": ["import * as crypto from 'crypto';\nimport * as path from 'path';\nimport * as fs from 'fs';\nimport { getCredential, getTenantOrg } from '../services/configService';\nimport { logger } from './logger';\nimport { formatClientError } from './errorFormatter';\nimport type { AppListItem, RemoteApp } from '../services/apps';\nimport type { ConnectionFailure, FarseerService } from '../services/farseerService';\nimport { selectByNameOrId, formatAmbiguous } from './nameResolver';\n\nexport function calculateHash(content: string | Buffer): string {\n return crypto.createHash('md5').update(content).digest('hex');\n}\n\n/**\n * Where tenant folders live: `<FARSEER_APPS_DIR>/farseer-apps/<tenant>`, or the working\n * directory when the variable is unset. A host that starts `farseer mcp-server` from a\n * different directory than the project it manages (Mindseer starts it from the project\n * root and keeps each instance's files under `instances/<slug>/`) points it here.\n */\nexport function getAppsDir(): string {\n const base = process.env.FARSEER_APPS_DIR?.trim();\n return path.join(base ? path.resolve(process.cwd(), base) : process.cwd(), 'farseer-apps');\n}\n\nexport function getTenantDir(tenant: string): string {\n return path.join(getAppsDir(), tenant);\n}\n\nexport function getTenantFilesDir(tenant: string): string {\n return path.join(getTenantDir(tenant), 'files');\n}\n\n/**\n * Human-readable path string for log output. Renders the directory the\n * CLI actually scans, so users who copy-paste the displayed path land\n * on the right files.\n *\n * Earlier `status` hard-coded the literal `apps/<tenant>/files/` which\n * had drifted from the real `farseer-apps/<tenant>/files/` layout \u2014\n * users who followed the displayed path edited files the CLI never\n * looked at. Deriving from the same helper as the operation prevents\n * the strings from drifting again.\n *\n * Edge cases handled:\n * \u2022 If a `path.relative(cwd, absDir)` would point UP (`../`) or to\n * the cwd itself, we fall back to the absolute path \u2014 the user is\n * running the CLI from outside / at the synced directory, and\n * showing `\"../\"` or an empty relative string is more confusing\n * than the absolute form.\n * \u2022 macOS resolves `/tmp` \u2192 `/private/tmp` via `fs.realpathSync`,\n * which makes `path.relative` from cwd `/tmp/x` to absDir\n * `/private/tmp/x/...` emit `../../../...`. We resolve both sides\n * through `realpathSync` before comparing so the symlink doesn't\n * leak into the displayed path.\n */\nexport function displayLocalPath(absDir: string): string {\n // Resolve symlinks on both sides so /tmp vs /private/tmp on macOS\n // doesn't blow up the relative path with `../../../`.\n const resolvedCwd = safeRealpath(process.cwd());\n const resolvedDir = safeRealpath(absDir);\n const rel = path.relative(resolvedCwd, resolvedDir);\n // `..` prefix means absDir is OUTSIDE cwd. Falling back to the\n // absolute form is clearer than a deep `../` chain \u2014 and it stays\n // copy-pasteable. An empty string means cwd === absDir, which would\n // otherwise render as just `/`; show `./` instead so the trailing\n // slash convention stays consistent.\n if (rel === '') return './';\n if (rel.startsWith('..')) return resolvedDir + '/';\n return rel + '/';\n}\n\n/**\n * `fs.realpathSync` with a graceful fallback: returns the input\n * unchanged when the path doesn't exist or can't be resolved. Used by\n * `displayLocalPath` so we can render a still-to-be-created tenant\n * folder without throwing.\n */\nfunction safeRealpath(p: string): string {\n try {\n return fs.realpathSync(p);\n } catch {\n return p;\n }\n}\n\n// Legacy - for backwards compatibility with run command\nexport function getTenantSrcDir(tenant: string): string {\n return path.join(getTenantFilesDir(tenant), 'Scripts');\n}\n\nexport function getSyncFilePath(tenant: string): string {\n return path.join(getTenantDir(tenant), '.farseer-sync.json');\n}\n\nexport function getAuditLogPath(tenant: string): string {\n return path.join(getTenantDir(tenant), '.farseer-audit.log');\n}\n\nexport function getTenantAppsDir(tenant: string): string {\n return path.join(getTenantDir(tenant), 'apps');\n}\n\nexport function ensureDirectoryExists(dirPath: string): void {\n if (!fs.existsSync(dirPath)) {\n fs.mkdirSync(dirPath, { recursive: true });\n }\n}\n\n/**\n * Returns `fullPath` relative to `basePath`, always with POSIX separators.\n *\n * On Windows `path.relative` returns backslash-separated paths. Those flow\n * through `getAllFilesInDir` / `getAllFiles` and become KEYS in the sync\n * state, `localFileHashes`, `localPresenceSet`, etc. Remote keys come back\n * from the API as POSIX (`/`-separated), so without this normalisation the\n * key comparison fails and every file looks like a local-delete + remote-add\n * pair. Normalising once here means every caller \u2014 sync state, status\n * comparator, blocklist matcher \u2014 sees the same shape regardless of OS.\n */\nexport function getRelativePath(fullPath: string, basePath: string): string {\n return path.relative(basePath, fullPath).split(path.sep).join('/');\n}\n\n/**\n * Resolve `filePath` against `baseDir` and verify the resolved path stays\n * inside it. Anything that escapes (`..`, absolute paths, symlink-style\n * tricks once resolved) throws \u2014 callers that build paths from REMOTE\n * data must use this so a backend bug or compromised tenant returning\n * `../../etc/passwd` can't write or unlink outside the tenant's files\n * folder.\n *\n * Use everywhere we touch the filesystem with a path that came from\n * remote: pull's writes/unlinks, the merge_markers `.remote` sibling\n * write, push/wipe candidate iteration, etc.\n */\nexport function safeResolveWithinBase(baseDir: string, filePath: string): string {\n const resolvedBase = path.resolve(baseDir);\n const resolved = path.resolve(resolvedBase, filePath);\n // path.resolve normalises `..`; check the result is inside the base\n // directory (allow exact match for the base itself, but require a\n // separator suffix for descendants to avoid `/foo/bar` vs `/foo/barbaz`).\n if (resolved !== resolvedBase && !resolved.startsWith(resolvedBase + path.sep)) {\n throw new Error(\n `Path escapes base directory: '${filePath}' resolves to '${resolved}' (base: '${resolvedBase}')`,\n );\n }\n return resolved;\n}\n\n/**\n * Resolves a list of relative paths against `baseDir` and partitions\n * them into resolved-to-real-file vs. missing. Used by `push --only`\n * to validate the user's whitelist before any network call.\n *\n * \"Missing\" covers all the ways a path can fail to point at a real\n * file under the base:\n * - filename typo / wrong case / double slash\n * - file was deleted locally after the user typed the command\n * - traversal attempt (`../foo`) \u2014 safeResolveWithinBase throws, we\n * catch and treat it as missing rather than crashing the whole\n * pre-flight on the first offender. Without the catch, the user\n * would see one error and never get the consolidated \"here's\n * everything that didn't resolve\" output.\n *\n * Order is preserved in `missing` so the error message lists paths\n * in the same order the user wrote them.\n */\nexport function validateOnlyFilePaths(baseDir: string, paths: string[]): { missing: string[] } {\n const missing: string[] = [];\n for (const p of paths) {\n try {\n const fullPath = safeResolveWithinBase(baseDir, p);\n if (!fs.existsSync(fullPath) || !fs.statSync(fullPath).isFile()) {\n missing.push(p);\n }\n } catch {\n missing.push(p);\n }\n }\n return { missing };\n}\n\n/**\n * OS-generated metadata files / folders that should NEVER be synced.\n *\n * These accumulate locally without the user creating them and would otherwise\n * leak into the remote workspace (and trip backend filename validation).\n * Match against the basename of any path segment, including nested copies\n * (e.g. `Scripts/.DS_Store`, `__MACOSX/Apps/foo.ts`).\n *\n * Lives in helpers (not syncService) so the file-listing helper itself can\n * apply the filter \u2014 keeping it in syncService meant every call site had to\n * remember to `.filter((f) => !isOsMetadataFile(f))` and a single forgotten\n * one would silently leak `.DS_Store` (which is exactly how PR #1878 started).\n */\nconst OS_METADATA_BASENAMES = new Set([\n '.DS_Store', // macOS Finder\n '.AppleDouble', // macOS Time Machine / netatalk\n '.LSOverride', // macOS Launch Services\n '.Spotlight-V100', // macOS Spotlight\n '.Trashes', // macOS\n '.fseventsd', // macOS\n '.DocumentRevisions-V100', // macOS\n '.TemporaryItems', // macOS\n '.VolumeIcon.icns', // macOS\n '.com.apple.timemachine.donotpresent',\n 'Thumbs.db', // Windows Explorer\n 'Thumbs.db:encryptable',\n 'ehthumbs.db', // Windows Explorer\n 'ehthumbs_vista.db',\n 'desktop.ini', // Windows\n '$RECYCLE.BIN', // Windows\n '__MACOSX', // macOS zip artefact\n]);\n\n/**\n * Returns true when any segment of the path is an OS metadata file/folder\n * we always want to hide from sync \u2014 irrespective of `--all` or includes\n * config. Used as the bottom-line filter in `getAllFilesInDir` and applied\n * defensively to remote listings so old clients can't get metadata files\n * stuck on a tenant.\n */\nexport function isOsMetadataFile(filePath: string): boolean {\n const segments = filePath.split('/');\n for (const seg of segments) {\n if (OS_METADATA_BASENAMES.has(seg)) return true;\n // The `._<name>` prefix is reserved for macOS AppleDouble resource\n // forks (created by tar/zip/AFP when copying across HFS+ boundaries)\n // and is therefore aggressive: any user-named file starting with\n // `._` is silently dropped from sync. We accept this \u2014 collisions\n // are rare in practice and the alternative (uploading bookkeeping\n // junk) is the worse failure mode.\n if (seg.startsWith('._')) return true;\n }\n return false;\n}\n\n/**\n * Returns true when the path contains any segment starting with `.` that is\n * NOT covered by `isOsMetadataFile`. Things like `.env`, `.git/`, `.vscode/`\n * fall here. The CLI's `shouldIncludeFile` requires explicit opt-in for\n * these (via `--include-ext` / `--include-folder` / persistent sync-includes\n * config) \u2014 they are never picked up by `--all` alone, so a stray credential\n * file in `farseer-apps/<tenant>/files/` doesn't get pushed by accident.\n */\nexport function isHiddenFile(filePath: string): boolean {\n if (isOsMetadataFile(filePath)) return false; // those have their own rule\n const segments = filePath.split('/');\n return segments.some((seg) => seg.length > 0 && seg.startsWith('.'));\n}\n\nexport function getAllFiles(dirPath: string, basePath?: string): string[] {\n if (!fs.existsSync(dirPath)) {\n return [];\n }\n\n const base = basePath || dirPath;\n const files: string[] = [];\n\n const items = fs.readdirSync(dirPath, { withFileTypes: true });\n\n for (const item of items) {\n const fullPath = path.join(dirPath, item.name);\n\n if (item.isDirectory()) {\n files.push(...getAllFiles(fullPath, base));\n } else if (item.isFile() && isScriptFile(item.name)) {\n files.push(getRelativePath(fullPath, base));\n }\n }\n\n return files;\n}\n\n/**\n * Get all files in a directory recursively, with OS metadata stripped.\n *\n * The OS-metadata filter is the default behavior \u2014 every call site needs it,\n * and forgetting to add a `.filter((f) => !isOsMetadataFile(f))` at a new\n * call site is exactly how `.DS_Store` started leaking into pushes. Pass\n * `{ includeOsMetadata: true }` only when you have a specific reason to see\n * those files (e.g. a debug listing, audit dump). Hidden files are NOT\n * filtered here \u2014 that gate lives in `shouldIncludeFile` because the user\n * can opt in to specific dotfile patterns via the includes config.\n *\n * Pass `shouldSkipDir(relPath)` to short-circuit the walk into directories\n * the caller knows it will discard anyway. This is how callers actually\n * bound memory \u2014 without it a tenant containing `.git/` or `node_modules/`\n * still materialises every filename before any filter runs.\n */\nexport function getAllFilesInDir(\n dirPath: string,\n basePathOrOptions?: string | { includeOsMetadata?: boolean; shouldSkipDir?: (relPath: string) => boolean },\n optionsArg?: { includeOsMetadata?: boolean; shouldSkipDir?: (relPath: string) => boolean },\n): string[] {\n // Backwards-compat with the old (dirPath, basePath?) signature.\n const basePath = typeof basePathOrOptions === 'string' ? basePathOrOptions : undefined;\n const options = typeof basePathOrOptions === 'object' ? basePathOrOptions : (optionsArg ?? {});\n\n if (!fs.existsSync(dirPath)) return [];\n\n const base = basePath || dirPath;\n const files: string[] = [];\n const items = fs.readdirSync(dirPath, { withFileTypes: true });\n\n for (const item of items) {\n const fullPath = path.join(dirPath, item.name);\n\n if (item.isDirectory()) {\n const relPath = getRelativePath(fullPath, base);\n // Skip whole OS-metadata directories at recursion time \u2014 saves a\n // pointless walk into `__MACOSX/` etc. when we'd just discard\n // every entry afterwards.\n if (!options.includeOsMetadata && isOsMetadataFile(relPath)) {\n continue;\n }\n // Caller-supplied skip: lets sync callers prune hidden/`node_modules`\n // subtrees before we materialise their contents.\n if (options.shouldSkipDir && options.shouldSkipDir(relPath)) {\n continue;\n }\n files.push(...getAllFilesInDir(fullPath, base, options));\n } else if (item.isFile()) {\n const relPath = getRelativePath(fullPath, base);\n if (!options.includeOsMetadata && isOsMetadataFile(relPath)) continue;\n files.push(relPath);\n }\n }\n\n return files;\n}\n\nexport function isScriptFile(filename: string): boolean {\n const ext = path.extname(filename).toLowerCase();\n return ['.ts', '.js', '.mjs', '.cjs'].includes(ext);\n}\n\nexport function isTextFile(filename: string): boolean {\n const ext = path.extname(filename).toLowerCase().slice(1); // remove leading dot\n return ['ts', 'js', 'mjs', 'cjs', 'json', 'txt', 'md', 'csv', 'xml', 'html', 'css', 'yaml', 'yml'].includes(ext);\n}\n\nexport function formatFileSize(bytes: number): string {\n if (bytes < 1024) return `${bytes} B`;\n if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;\n return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;\n}\n\nexport function formatDate(date: Date | string): string {\n const d = typeof date === 'string' ? new Date(date) : date;\n return d.toLocaleString();\n}\n\nexport function getCredentialsHint(tenant: string): string {\n return `Use: farseer login\n Or: farseer config set ${tenant} --api-key <key> --org <organisation>`;\n}\n\n/**\n * The headline for a failed credential probe. Shared by `config test` and\n * `login` so the same failure cannot be described two ways, and separate from\n * ConnectionCheck itself so the MCP surface can word it differently.\n */\nexport function connectionFailureMessage(reason: ConnectionFailure, host: string, tenant: string): string {\n switch (reason) {\n case 'rejected':\n return 'Connection failed: the server rejected this API key.';\n case 'tenant-unknown':\n return `Connection failed: ${host} has no tenant \"${tenant}\". The key is fine \u2014 check the organisation.`;\n case 'server-error':\n return `Connection failed: ${host} answered with an error.`;\n case 'unreachable':\n return `Connection failed: could not reach ${host}.`;\n }\n}\n\n/**\n * Resolve tenant from argument or the FARSEER_TENANT env.\n * If tenant is provided, use it. Otherwise, use the env tenant.\n * Returns null if no tenant is available.\n */\nexport interface ResolvedCheckout {\n organisation: string;\n tenant: string;\n}\n\n/**\n * Per-shell target from the environment. There is no persisted global default\n * any more \u2014 a command takes its tenant from an explicit argument or from\n * FARSEER_TENANT in the calling shell, and errors if neither is set. Two shells\n * can therefore hold different tenants at once, and a bare command never\n * silently retargets to a stale machine-global checkout.\n *\n * Org resolves the same way the MCP launch path does (mcp/utils/launchPin.ts):\n * FARSEER_ORG > saved tenant->org mapping > the tenant name. So once a confirmed\n * `farseer pull <org> <tenant>` has recorded the mapping, `export FARSEER_TENANT=x`\n * alone is enough; only new org != tenant tenants also need FARSEER_ORG.\n */\nexport function getEnvCheckout(): ResolvedCheckout | null {\n const tenant = process.env.FARSEER_TENANT;\n if (!tenant) return null;\n const organisation = process.env.FARSEER_ORG || getTenantOrg(tenant) || tenant;\n if (organisation === tenant) {\n logger.dim(`Using tenant from FARSEER_TENANT: ${tenant}`);\n } else {\n logger.dim(`Using tenant from FARSEER_TENANT: ${tenant} (org: ${organisation})`);\n }\n return { organisation, tenant };\n}\n\n/**\n * Resolve organisation and tenant from argument or the FARSEER_TENANT env.\n * When only tenant is provided, assumes organisation = tenant.\n */\nexport function resolveOrgAndTenant(tenantArg?: string): ResolvedCheckout | null {\n if (tenantArg) {\n // When tenant is specified as arg, assume org = tenant\n // (org != tenant tenants are resolved via the mapping in the\n // richer resolveTenantWithOrgMapping path).\n return { organisation: tenantArg, tenant: tenantArg };\n }\n\n return getEnvCheckout();\n}\n\nexport function resolveTenant(tenantArg?: string): string | null {\n const resolved = resolveOrgAndTenant(tenantArg);\n return resolved?.tenant || null;\n}\n\n/**\n * Resolve tenant or exit with error if not available.\n */\nexport function resolveTenantOrExit(tenantArg?: string): string {\n const tenant = resolveTenant(tenantArg);\n if (!tenant) {\n logger.error('No tenant specified.');\n logger.dim('Pass it: farseer <command> <tenant>');\n logger.dim('Or set it (per shell): export FARSEER_TENANT=<tenant>');\n process.exit(1);\n }\n return tenant;\n}\n\n/**\n * Resolve organisation and tenant with support for org-tenant mapping.\n *\n * Usage patterns:\n * - <org> <tenant>: Explicit org and tenant\n * - <tenant>: Look up org from FARSEER_ORG or the saved mapping\n * - (no args): Fall back to FARSEER_TENANT/FARSEER_ORG from the shell\n *\n * Read-only by design: resolving a pair must not persist it. A typo'd org\n * (`farseer pull wrong-org my-tenant`) would otherwise be remembered as\n * my-tenant's org before anything confirmed it, and every later one-arg command\n * would inherit the wrong host \u2014 silently, since `*.farseer.io` is a wildcard.\n * The mapping is written by the preflight instead, and only for a pair the\n * organisation itself confirmed.\n *\n * @param arg1 - Organisation (if 2 args) or tenant (if 1 arg)\n * @param arg2 - Tenant (if 2 args)\n * @returns ResolvedCheckout or exits with error\n */\nexport function resolveTenantWithOrgMapping(arg1?: string, arg2?: string): ResolvedCheckout {\n // Case 1: Two arguments - <org> <tenant>\n if (arg1 && arg2) {\n const org = arg1;\n const tenant = arg2;\n\n if (org === tenant) {\n logger.dim(`Using tenant: ${tenant}`);\n } else {\n logger.dim(`Using tenant: ${tenant} (org: ${org})`);\n }\n\n return { organisation: org, tenant };\n }\n\n // Case 2: One argument - <tenant>\n if (arg1) {\n const tenant = arg1;\n\n // FARSEER_ORG pairs with FARSEER_TENANT (it's the org for the shell's\n // env tenant), so only honour it when this explicit tenant IS that env\n // tenant \u2014 otherwise a shell-level FARSEER_ORG would leak onto an\n // unrelated tenant and build the wrong host. Else use the saved mapping.\n const envOrg = tenant === process.env.FARSEER_TENANT ? process.env.FARSEER_ORG : undefined;\n const org = envOrg || getTenantOrg(tenant);\n if (org) {\n if (org === tenant) {\n logger.dim(`Using tenant: ${tenant}`);\n } else {\n logger.dim(`Using tenant: ${tenant} (org: ${org})`);\n }\n return { organisation: org, tenant };\n }\n\n // An API-key tenant needs no remembered org: the stored credential\n // carries its own base URL and the organisation is ignored on that path.\n // Only confirmed pairs get recorded now, so these tenants often have no\n // mapping at all \u2014 don't demand an org we would never use.\n if (getCredential(tenant)) {\n logger.dim(`Using tenant: ${tenant}`);\n return { organisation: tenant, tenant };\n }\n\n // Org for this tenant is unknown - fail loud rather than guess a host.\n logger.error(`Organisation unknown for tenant \"${tenant}\".`);\n logger.dim('Pass both: farseer <command> <organisation> <tenant>');\n logger.dim(`Or set them per shell: export FARSEER_TENANT=${tenant} FARSEER_ORG=<organisation>`);\n process.exit(1);\n }\n\n // Case 3: No arguments - fall back to FARSEER_TENANT from the shell.\n const envCheckout = getEnvCheckout();\n if (envCheckout) {\n return envCheckout;\n }\n\n // Nothing to go on - fail loud instead of guessing a tenant.\n logger.error('No tenant specified.');\n logger.dim('Pass it: farseer <command> <tenant>');\n logger.dim('Or set it (per shell): export FARSEER_TENANT=<tenant> (FARSEER_ORG=<org> if org differs)');\n process.exit(1);\n}\n\n/**\n * Resolve organisation and tenant or exit with error.\n */\nexport function resolveOrgAndTenantOrExit(tenantArg?: string): ResolvedCheckout {\n const resolved = resolveOrgAndTenant(tenantArg);\n if (!resolved) {\n logger.error('No tenant specified.');\n logger.dim('Pass it: farseer <command> <tenant>');\n logger.dim('Or set it (per shell): export FARSEER_TENANT=<tenant>');\n process.exit(1);\n }\n return resolved;\n}\n\n/**\n * Check if a string is a known tenant (has credentials configured).\n */\nexport function isKnownTenant(name: string): boolean {\n return !!getCredential(name);\n}\n\nexport interface ParsedAppArgs {\n organisation: string;\n tenant: string;\n appName: string;\n}\n\n/**\n * Parse variadic arguments to extract tenant and app name.\n * If first arg is a known tenant, use it as tenant and rest as app name.\n * Otherwise, use checked-out tenant and all args as app name.\n *\n * @param args Array of arguments (from variadic command)\n * @returns { organisation: string, tenant: string, appName: string }\n */\nexport function parseAppArgs(\n args: string[],\n options: { allowEmptyName?: boolean; command?: string } = {},\n): ParsedAppArgs {\n if (args.length === 0) {\n if (options.allowEmptyName) {\n // `--id` path: no app name was typed, so the tenant can only come\n // from FARSEER_TENANT in the shell.\n const envCheckout = getEnvCheckout();\n if (envCheckout) {\n return { organisation: envCheckout.organisation, tenant: envCheckout.tenant, appName: '' };\n }\n logger.error('No tenant specified.');\n logger.dim('Either specify a tenant: farseer app show <tenant> --id <id>');\n logger.dim('Or set FARSEER_TENANT in your shell.');\n process.exit(1);\n }\n logger.error('App name is required.');\n process.exit(1);\n }\n\n // `--id` path with a single positional. It reads as a tenant \u2014 but the\n // collision message that sends people here had them type an app *name*, so\n // reading it as a tenant is how adding `--id` to a failed command silently\n // moves it to a different tenant.\n if (options.allowEmptyName && args.length === 1) {\n const only = args[0];\n const envCheckout = getEnvCheckout();\n const namesATenant = isKnownTenant(only) || !!getTenantOrg(only);\n\n if (envCheckout && namesATenant && only !== envCheckout.tenant) {\n // Both readings are real and they target different tenants, which is\n // the one case worth stopping for: on `app delete` the wrong guess\n // destroys something in a tenant the user never named.\n const command = options.command ?? 'app show';\n logger.error(`\"${only}\" is both a configured tenant and the name you are selecting by id.`);\n logger.dim('With --id the name is not used, so drop it and let the tenant say itself:');\n logger.dim(` farseer ${command} --id <id> (tenant ${envCheckout.tenant})`);\n logger.dim(` FARSEER_TENANT=${only} farseer ${command} --id <id> (tenant ${only})`);\n process.exit(1);\n }\n\n // An env tenant means the command already had a target before `--id` was\n // added, and adding it must not move that target.\n if (envCheckout) {\n return { organisation: envCheckout.organisation, tenant: envCheckout.tenant, appName: only };\n }\n\n return { organisation: getTenantOrg(only) || only, tenant: only, appName: '' };\n }\n\n // First arg looks like a tenant when either:\n // (a) we have API-key credentials saved for it, or\n // (b) we have a saved tenantOrgMapping entry for it (from a previous\n // `farseer pull <org> <tenant>`).\n // In both cases we prefer the saved organisation over args[0] so\n // run/apps/etc. build the right URL when org != tenant.\n if (args.length >= 2) {\n const first = args[0];\n const knownViaCredential = isKnownTenant(first);\n const savedOrg = getTenantOrg(first);\n if (knownViaCredential || savedOrg) {\n return {\n organisation: savedOrg || first,\n tenant: first,\n appName: args.slice(1).join(' '),\n };\n }\n }\n\n // Fall back to FARSEER_TENANT from the shell; all args are the app name.\n const envCheckout = getEnvCheckout();\n if (envCheckout) {\n return {\n organisation: envCheckout.organisation,\n tenant: envCheckout.tenant,\n appName: args.join(' '),\n };\n }\n\n // No env tenant and first arg isn't a known tenant\n // Assume first arg is tenant (will fail later if invalid)\n if (args.length >= 2) {\n return {\n organisation: args[0],\n tenant: args[0],\n appName: args.slice(1).join(' '),\n };\n }\n\n // Only one arg and no env tenant - could be tenant or app name\n logger.error('No tenant specified.');\n logger.dim('Pass it: farseer app show <tenant> <app-name>');\n logger.dim('Or set it (per shell): export FARSEER_TENANT=<tenant>');\n process.exit(1);\n}\n\n/**\n * Run a lookup that reports absence as null and everything else by throwing,\n * and end the command on the everything else. Commander does not await an\n * action, so without a boundary here the rejection escapes to the process\n * handler, which is the wrong place to explain that one read failed.\n */\nexport async function orExit<T>(work: Promise<T>, message: string): Promise<T> {\n try {\n return await work;\n } catch (error) {\n logger.error(message);\n logger.dim(await formatClientError(error));\n return process.exit(1);\n }\n}\n\n/**\n * Resolve an app to its folder list item, or exit with a clear message. An\n * explicit `--id` wins; a name that matches more than one app aborts, listing\n * the candidates, rather than picking the first.\n *\n * Callers take `.reference` to fetch details and `.id` to delete \u2014 the two ids\n * are different and their number spaces overlap.\n */\nexport async function resolveAppItemOrExit(\n api: FarseerService,\n selector: { appName?: string; id?: string; tenant?: string },\n): Promise<AppListItem> {\n const apps = await orExit(api.listApps(), 'Failed to list apps.');\n const selection = selectByNameOrId(apps, { name: selector.appName, id: selector.id }, (a) => a.reference);\n\n if (selection.kind === 'found') {\n return selection.entity;\n }\n\n if (selection.kind === 'ambiguous') {\n logger.error(formatAmbiguous('apps', selector.appName ?? '', selection.matches, (a) => a.reference));\n logger.dim('Re-run with --id <id> in place of the name to pick one.');\n process.exit(1);\n }\n\n if (selection.kind === 'conflict') {\n const { entity: app, name } = selection;\n logger.error(\n `App ${app.reference} is \"${app.name}\", not \"${name}\". The id and the name point at different apps, so nothing was done.`,\n );\n logger.dim(\n `To act on app ${app.reference}${selector.tenant ? ` in tenant \"${selector.tenant}\"` : ''}, drop the name.`,\n );\n if (!/\\s/.test(name)) {\n logger.dim(\n `If \"${name}\" is a tenant, select it and re-run with only the id: export FARSEER_TENANT=${name}`,\n );\n }\n process.exit(1);\n }\n\n logger.error(selector.id ? `App not found: id ${selector.id}` : `App not found: ${selector.appName}`);\n logger.dim('List apps with: farseer app list <tenant>');\n process.exit(1);\n}\n\n/**\n * Resolve an app for a CLI command to its full details, or exit with a clear\n * message. Wraps `resolveAppItemOrExit` + `getApp` so the commands that need\n * the whole `RemoteApp` (show, run) don't repeat the fetch.\n */\nexport async function resolveAppOrExit(\n api: FarseerService,\n selector: { appName?: string; id?: string; tenant?: string },\n): Promise<RemoteApp> {\n const item = await resolveAppItemOrExit(api, selector);\n const app = await orExit(api.getApp(item.reference), `Failed to load app details: ${item.name}`);\n if (!app) {\n logger.error(`Failed to load app details: ${item.name}`);\n process.exit(1);\n }\n return app;\n}\n\n// Credential injection/stripping for local development\n// Matches: const farseerClient = new farseer.FarseerClient();\n// and: const fClient = new farseer.FarseerClient();\n\ninterface CredentialConfig {\n basePath: string;\n tenantId: string;\n apiKey: string;\n}\n\n// Pattern to match empty FarseerClient() constructor (no /g flag to avoid lastIndex issues)\nconst EMPTY_CLIENT_PATTERNS = [\n /const farseerClient = new farseer\\.FarseerClient\\(\\s*\\);/,\n /const fClient = new farseer\\.FarseerClient\\(\\s*\\);/,\n];\n\n// Pattern to match FarseerClient with injected credentials (multiline, no /g flag)\nconst INJECTED_CLIENT_PATTERN =\n /const (farseerClient|fClient) = new farseer\\.FarseerClient\\(\\{[\\s\\S]*?basePath:[\\s\\S]*?headers:[\\s\\S]*?'X-TENANT-ID':[\\s\\S]*?'X-API-KEY':[\\s\\S]*?\\}\\);/;\n\nexport function injectCredentials(code: string, credential: CredentialConfig): string {\n const clientConfig = `{\n basePath: '${credential.basePath}',\n headers: {\n 'X-TENANT-ID': '${credential.tenantId}',\n 'X-API-KEY': '${credential.apiKey}',\n }\n }`;\n\n let modified = code;\n\n // Pattern 1: const farseerClient = new farseer.FarseerClient();\n modified = modified.replace(\n /const farseerClient = new farseer\\.FarseerClient\\(\\s*\\);/g,\n `const farseerClient = new farseer.FarseerClient(${clientConfig});`,\n );\n\n // Pattern 2: const fClient = new farseer.FarseerClient();\n modified = modified.replace(\n /const fClient = new farseer\\.FarseerClient\\(\\s*\\);/g,\n `const fClient = new farseer.FarseerClient(${clientConfig});`,\n );\n\n return modified;\n}\n\nexport function stripCredentials(code: string): string {\n // Replace injected credentials back to empty constructor\n let modified = code;\n\n // Match farseerClient with credentials\n modified = modified.replace(\n /const farseerClient = new farseer\\.FarseerClient\\(\\{[\\s\\S]*?basePath:[\\s\\S]*?headers:[\\s\\S]*?'X-TENANT-ID':[\\s\\S]*?'X-API-KEY':[\\s\\S]*?\\}\\);/g,\n 'const farseerClient = new farseer.FarseerClient();',\n );\n\n // Match fClient with credentials\n modified = modified.replace(\n /const fClient = new farseer\\.FarseerClient\\(\\{[\\s\\S]*?basePath:[\\s\\S]*?headers:[\\s\\S]*?'X-TENANT-ID':[\\s\\S]*?'X-API-KEY':[\\s\\S]*?\\}\\);/g,\n 'const fClient = new farseer.FarseerClient();',\n );\n\n return modified;\n}\n\nexport function hasInjectedCredentials(code: string): boolean {\n return INJECTED_CLIENT_PATTERN.test(code);\n}\n\nexport function hasEmptyFarseerClient(code: string): boolean {\n return EMPTY_CLIENT_PATTERNS.some((pattern) => pattern.test(code));\n}\n\n// Process all script files in a directory\nexport function injectCredentialsInDir(srcDir: string, credential: CredentialConfig): number {\n let count = 0;\n const files = getAllFiles(srcDir);\n\n for (const file of files) {\n const filePath = path.join(srcDir, file);\n const content = fs.readFileSync(filePath, 'utf-8');\n const modified = injectCredentials(content, credential);\n\n if (modified !== content) {\n fs.writeFileSync(filePath, modified);\n count++;\n }\n }\n\n return count;\n}\n\nexport function stripCredentialsInDir(srcDir: string): number {\n let count = 0;\n const files = getAllFiles(srcDir);\n\n for (const file of files) {\n const filePath = path.join(srcDir, file);\n const content = fs.readFileSync(filePath, 'utf-8');\n const modified = stripCredentials(content);\n\n if (modified !== content) {\n fs.writeFileSync(filePath, modified);\n count++;\n }\n }\n\n return count;\n}\n\n// Audit log helpers\nexport interface AuditLogEntry {\n operation: 'pulled' | 'pushed' | 'deleted';\n filePath: string;\n uploadTime?: string;\n uploaderEmail?: string;\n uploaderName?: string;\n}\n\n/**\n * Execute async operations with limited concurrency.\n * Processes items in chunks to avoid overwhelming the API.\n *\n * @param items Array of items to process\n * @param fetcher Async function to call for each item\n * @param concurrency Maximum number of concurrent requests (default: 15)\n * @returns Array of results in the same order as input items\n */\nexport async function fetchWithConcurrency<T, R>(\n items: T[],\n fetcher: (item: T, index: number) => Promise<R>,\n concurrency: number = 15,\n): Promise<R[]> {\n const results: R[] = [];\n\n for (let i = 0; i < items.length; i += concurrency) {\n const chunk = items.slice(i, i + concurrency);\n const chunkResults = await Promise.all(chunk.map((item, chunkIndex) => fetcher(item, i + chunkIndex)));\n results.push(...chunkResults);\n }\n\n return results;\n}\n\nexport function appendToAuditLog(tenant: string, entries: AuditLogEntry[]): void {\n if (entries.length === 0) {\n return;\n }\n\n const logPath = getAuditLogPath(tenant);\n const timestamp = new Date().toISOString();\n\n let logContent = '';\n for (const entry of entries) {\n const uploaderInfo = entry.uploaderName\n ? `${entry.uploaderName} (${entry.uploaderEmail})`\n : entry.uploaderEmail || 'Unknown';\n\n const uploadedAt = entry.uploadTime ? new Date(entry.uploadTime).toLocaleString() : 'Unknown';\n\n logContent += `${timestamp} | ${entry.operation} | ${entry.filePath} | Modified by: ${uploaderInfo} | Uploaded: ${uploadedAt}\\n`;\n }\n\n fs.appendFileSync(logPath, logContent, 'utf-8');\n}\n"],
|
|
5
4
|
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,aAAwB;AACxB,WAAsB;AACtB,SAAoB;AACpB,2BAA4C;AAC5C,oBAAuB;AACvB,4BAAkC;AAGlC,0BAAkD;AAE3C,SAAS,cAAc,SAAkC;AAC5D,SAAO,OAAO,WAAW,KAAK,EAAE,OAAO,OAAO,EAAE,OAAO,KAAK;AAChE;AAQO,SAAS,aAAqB;AACjC,QAAM,OAAO,QAAQ,IAAI,kBAAkB,KAAK;AAChD,SAAO,KAAK,KAAK,OAAO,KAAK,QAAQ,QAAQ,IAAI,GAAG,IAAI,IAAI,QAAQ,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,eACrB,GAAG,MAAM,YAAY,KAAK,MAAM,aAAa,MAC7C,MAAM,iBAAiB;AAE7B,UAAM,aAAa,MAAM,aAAa,IAAI,KAAK,MAAM,UAAU,EAAE,eAAe,IAAI;AAEpF,kBAAc,GAAG,SAAS,MAAM,MAAM,SAAS,MAAM,MAAM,QAAQ,mBAAmB,YAAY,gBAAgB,UAAU;AAAA;AAAA,EAChI;AAEA,KAAG,eAAe,SAAS,YAAY,OAAO;AAClD;",
|
|
6
5
|
"names": ["envCheckout"]
|
|
7
6
|
}
|
package/dist/utils/logger.js.map
CHANGED
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/utils/logger.ts"],
|
|
4
|
-
"sourcesContent": ["import chalk from 'chalk';\n\nlet stdoutReserved = false;\n\n/** Sends every log line to stderr, for a command whose stdout carries machine-readable output. */\nexport function reserveStdout(): void {\n stdoutReserved = true;\n}\n\nfunction log(...args: unknown[]) {\n if (stdoutReserved || process.env.FARSEER_MCP === '1') {\n console.error(...args);\n } else {\n console.log(...args);\n }\n}\n\nexport const logger = {\n info: (message: string) => {\n log(chalk.blue('\u2139'), message);\n },\n\n success: (message: string) => {\n log(chalk.green('\u2713'), message);\n },\n\n warning: (message: string) => {\n log(chalk.yellow('\u26A0'), message);\n },\n\n error: (message: string) => {\n log(chalk.red('\u2717'), message);\n },\n\n log: (message: string) => {\n log(message);\n },\n\n dim: (message: string) => {\n log(chalk.dim(message));\n },\n\n header: (message: string) => {\n log();\n log(chalk.bold.underline(message));\n log();\n },\n\n list: (items: string[], indent: number = 2) => {\n const prefix = ' '.repeat(indent);\n items.forEach((item) => {\n log(`${prefix}${item}`);\n });\n },\n\n table: (rows: { label: string; value: string }[]) => {\n const maxLabelLength = Math.max(...rows.map((r) => r.label.length));\n rows.forEach((row) => {\n const paddedLabel = row.label.padEnd(maxLabelLength);\n log(` ${chalk.dim(paddedLabel)} ${row.value}`);\n });\n },\n};\n"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,KAAK,IAAI,GAAG,KAAK,IAAI,CAAC,MAAM,EAAE,MAAM,MAAM,CAAC;AAClE,SAAK,QAAQ,CAAC,QAAQ;AAClB,YAAM,cAAc,IAAI,MAAM,OAAO,cAAc;AACnD,UAAI,KAAK,aAAAA,QAAM,IAAI,WAAW,CAAC,KAAK,IAAI,KAAK,EAAE;AAAA,IACnD,CAAC;AAAA,EACL;AACJ;",
|
|
6
5
|
"names": ["chalk"]
|
|
7
6
|
}
|
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/utils/nameResolver.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * Resolving a user-typed name to one thing.\n *\n * The backend enforces name uniqueness per folder, not per tenant, so any\n * lookup that searches a whole tenant can find more than one match. Picking the\n * first is the bug this exists to prevent: it acts on an arbitrary one of them\n * and leaves the others unreachable by name.\n *\n * Pure. Each surface renders the outcome its own way \u2014 the CLI exits, the MCP\n * tools return an error response.\n */\n\nexport type Selection<T> =\n | { kind: 'found'; entity: T }\n | { kind: 'notFound' }\n | { kind: 'ambiguous'; matches: T[] }\n // Only when both a name and an id were given; see selectByNameOrId.\n | { kind: 'conflict'; entity: T; name: string };\n\n/** Every entity whose name matches, case-insensitively. */\nexport function matchByName<T extends { name: string }>(items: readonly T[], name: string): T[] {\n const needle = name.trim().toLowerCase();\n return items.filter((item) => item.name.toLowerCase() === needle);\n}\n\n/**\n * An id (unique) decides over a name (may collide). `idOf` reads whichever id\n * the caller disambiguates by, which is not always the one used to address the\n * entity afterwards \u2014 an app is selected by its Remote Job id but deleted by\n * its folder-item id.\n *\n * A name given alongside the id is a claim about which entity that is, and one\n * that does not hold is a conflict rather than something the id overrides: on\n * the CLI it is a tenant name read as an app name, and dropping it acts on the\n * id in the wrong tenant.\n */\nexport function selectByNameOrId<T extends { name: string }>(\n items: readonly T[],\n selector: { name?: string; id?: string },\n idOf: (item: T) => string,\n): Selection<T> {\n const id = selector.id?.trim();\n if (id) {\n const entity = items.find((item) => idOf(item) === id);\n if (!entity) {\n return { kind: 'notFound' };\n }\n const name = selector.name?.trim();\n if (name && matchByName([entity], name).length === 0) {\n return { kind: 'conflict', entity, name };\n }\n return { kind: 'found', entity };\n }\n\n const matches = matchByName(items, selector.name ?? '');\n if (matches.length === 1) {\n return { kind: 'found', entity: matches[0] };\n }\n if (matches.length === 0) {\n return { kind: 'notFound' };\n }\n return { kind: 'ambiguous', matches };\n}\n\n/**\n * Lists each candidate's id. Deliberately free of `--id` wording so it reads\n * correctly from the MCP tools too; the CLI appends its own hint.\n */\nexport function formatAmbiguous<T extends { name: string }>(\n plural: string,\n name: string,\n matches: readonly T[],\n idOf: (item: T) => string,\n): string {\n const lines = matches.map((item) => ` id ${idOf(item)} ${item.name}`);\n return `Multiple ${plural} named \"${name}\" (${matches.length}). Specify one by id:\\n${lines.join('\\n')}`;\n}\n"],
|
|
5
4
|
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAoBO,SAAS,YAAwC,OAAqB,MAAmB;AAC5F,QAAM,SAAS,KAAK,KAAK,EAAE,YAAY;AACvC,SAAO,MAAM,OAAO,CAAC,SAAS,KAAK,KAAK,YAAY,MAAM,MAAM;AACpE;AAaO,SAAS,iBACZ,OACA,UACA,MACY;AACZ,QAAM,KAAK,SAAS,IAAI,KAAK;AAC7B,MAAI,IAAI;AACJ,UAAM,SAAS,MAAM,KAAK,CAAC,SAAS,KAAK,IAAI,MAAM,EAAE;AACrD,QAAI,CAAC,QAAQ;AACT,aAAO,EAAE,MAAM,WAAW;AAAA,IAC9B;AACA,UAAM,OAAO,SAAS,MAAM,KAAK;AACjC,QAAI,QAAQ,YAAY,CAAC,MAAM,GAAG,IAAI,EAAE,WAAW,GAAG;AAClD,aAAO,EAAE,MAAM,YAAY,QAAQ,KAAK;AAAA,IAC5C;AACA,WAAO,EAAE,MAAM,SAAS,OAAO;AAAA,EACnC;AAEA,QAAM,UAAU,YAAY,OAAO,SAAS,QAAQ,EAAE;AACtD,MAAI,QAAQ,WAAW,GAAG;AACtB,WAAO,EAAE,MAAM,SAAS,QAAQ,QAAQ,CAAC,EAAE;AAAA,EAC/C;AACA,MAAI,QAAQ,WAAW,GAAG;AACtB,WAAO,EAAE,MAAM,WAAW;AAAA,EAC9B;AACA,SAAO,EAAE,MAAM,aAAa,QAAQ;AACxC;AAMO,SAAS,gBACZ,QACA,MACA,SACA,MACM;AACN,QAAM,QAAQ,QAAQ,IAAI,CAAC,SAAS,QAAQ,KAAK,IAAI,CAAC,OAAO,KAAK,IAAI,EAAE;AACxE,SAAO,YAAY,MAAM,WAAW,IAAI,MAAM,QAAQ,MAAM;AAAA,EAA0B,MAAM,KAAK,IAAI,CAAC;AAC1G;",
|
|
6
5
|
"names": []
|
|
7
6
|
}
|
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/utils/packageManager.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * Package Manager Utilities\n *\n * Shared logic for managing tenant package.json files and farseer-client dependency.\n * Used by the CLI install and pull commands and the MCP farseer_install tool.\n */\n\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport { FARSEER_CLIENT_DEPENDENCY, FARSEER_CLIENT_VERSION } from './constants';\nimport { isNewerVersion } from './updateCheck';\n\n// Tarballs in this bucket are not an install source, so a dependency pointing\n// into it is always replaced, whoever wrote it.\nconst BUCKET_URL_PREFIX = 'https://storage.googleapis.com/farseer-remote-jobs-results/';\n\nconst CLI_MANAGED_NPM_VERSION = /^npm:@farseerdev\\/farseer-client@(\\d+\\.\\d+\\.\\d+)$/;\n\n// The CLI only overwrites a farseer-client dependency it wrote itself (a bucket\n// tarball or an exact npm version) and only moves it forward, so a user who\n// pinned a newer version, a fork, a local path or a version range keeps it.\nfunction isOutdatedCliManagedClient(dependency: unknown): boolean {\n if (typeof dependency !== 'string') return false;\n if (dependency.startsWith(`${BUCKET_URL_PREFIX}farseer-client/`)) return true;\n const pinned = CLI_MANAGED_NPM_VERSION.exec(dependency)?.[1];\n return pinned !== undefined && isNewerVersion(FARSEER_CLIENT_VERSION, pinned);\n}\n\n/**\n * Move an outdated CLI-managed farseer-client dependency to FARSEER_CLIENT_DEPENDENCY\n * and drop farseer-client-axios when it comes from the bucket. Returns the changes.\n */\nfunction updateClientDependencies(dependencies: Record<string, unknown>): string[] {\n const changes: string[] = [];\n\n const client = dependencies['farseer-client'];\n if (isOutdatedCliManagedClient(client)) {\n dependencies['farseer-client'] = FARSEER_CLIENT_DEPENDENCY;\n changes.push('farseer-client (upgraded)');\n }\n\n const axiosClient = dependencies['farseer-client-axios'];\n if (typeof axiosClient === 'string' && axiosClient.startsWith(BUCKET_URL_PREFIX)) {\n delete dependencies['farseer-client-axios'];\n changes.push('farseer-client-axios (removed)');\n }\n\n return changes;\n}\n\n/**\n * Ensure the tenant directory has a package.json with the current farseer-client\n * dependency. Creates package.json if missing; adds farseer-client if missing;\n * upgrades a CLI-managed farseer-client and removes the bucket's\n * farseer-client-axios. Returns the list of dependency changes performed.\n */\nexport function ensurePackageJson(tenantDir: string, tenant: string): string[] {\n const packageJsonPath = path.join(tenantDir, 'package.json');\n const changes: string[] = [];\n\n let pkg: any;\n if (fs.existsSync(packageJsonPath)) {\n pkg = JSON.parse(fs.readFileSync(packageJsonPath, 'utf-8'));\n } else {\n pkg = {\n name: `farseer-apps-${tenant}`,\n version: '1.0.0',\n private: true,\n description: `Farseer scripts for tenant ${tenant}`,\n dependencies: {},\n };\n changes.push('package.json (created)');\n }\n\n pkg.dependencies = pkg.dependencies || {};\n\n if (!pkg.dependencies['farseer-client']) {\n pkg.dependencies['farseer-client'] = FARSEER_CLIENT_DEPENDENCY;\n changes.push('farseer-client');\n }\n changes.push(...updateClientDependencies(pkg.dependencies));\n\n fs.writeFileSync(packageJsonPath, JSON.stringify(pkg, null, 2) + '\\n');\n return changes;\n}\n\n/**\n * Upgrade the farseer-client dependency of an existing tenant package.json and\n * remove the bucket's farseer-client-axios, without adding anything. The file\n * is only rewritten when something changed. Returns the changes.\n */\nexport function updatePackageJson(tenantDir: string): string[] {\n const packageJsonPath = path.join(tenantDir, 'package.json');\n if (!fs.existsSync(packageJsonPath)) return [];\n\n const pkg = JSON.parse(fs.readFileSync(packageJsonPath, 'utf-8'));\n const changes = pkg.dependencies ? updateClientDependencies(pkg.dependencies) : [];\n if (changes.length > 0) {\n fs.writeFileSync(packageJsonPath, JSON.stringify(pkg, null, 2) + '\\n');\n }\n return changes;\n}\n\n/**\n * Parse an npm package specifier into name and version.\n * Handles scoped packages: @scope/name@version \u2192 { name: \"@scope/name\", version: \"version\" }\n */\nexport function parsePackageSpec(spec: string): { name: string; version: string } {\n const isScoped = spec.startsWith('@');\n const lastAt = spec.lastIndexOf('@');\n const hasVersion = lastAt > 0 && (!isScoped || lastAt > spec.indexOf('/'));\n\n return {\n name: hasVersion ? spec.substring(0, lastAt) : spec,\n version: hasVersion ? spec.substring(lastAt + 1) : '*',\n };\n}\n"],
|
|
5
4
|
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAOA,SAAoB;AACpB,WAAsB;AACtB,uBAAkE;AAClE,yBAA+B;AAI/B,MAAM,oBAAoB;AAE1B,MAAM,0BAA0B;AAKhC,SAAS,2BAA2B,YAA8B;AAC9D,MAAI,OAAO,eAAe,SAAU,QAAO;AAC3C,MAAI,WAAW,WAAW,GAAG,iBAAiB,iBAAiB,EAAG,QAAO;AACzE,QAAM,SAAS,wBAAwB,KAAK,UAAU,IAAI,CAAC;AAC3D,SAAO,WAAW,cAAa,mCAAe,yCAAwB,MAAM;AAChF;AAMA,SAAS,yBAAyB,cAAiD;AAC/E,QAAM,UAAoB,CAAC;AAE3B,QAAM,SAAS,aAAa,gBAAgB;AAC5C,MAAI,2BAA2B,MAAM,GAAG;AACpC,iBAAa,gBAAgB,IA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c,iBAAiB,KAAK,UAAU,KAAK,MAAM,CAAC,IAAI,IAAI;AAAA,EACzE;AACA,SAAO;AACX;AAMO,SAAS,iBAAiB,MAAiD;AAC9E,QAAM,WAAW,KAAK,WAAW,GAAG;AACpC,QAAM,SAAS,KAAK,YAAY,GAAG;AACnC,QAAM,aAAa,SAAS,MAAM,CAAC,YAAY,SAAS,KAAK,QAAQ,GAAG;AAExE,SAAO;AAAA,IACH,MAAM,aAAa,KAAK,UAAU,GAAG,MAAM,IAAI;AAAA,IAC/C,SAAS,aAAa,KAAK,UAAU,SAAS,CAAC,IAAI;AAAA,EACvD;AACJ;",
|
|
6
5
|
"names": []
|
|
7
6
|
}
|
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/utils/syncReporting.ts"],
|
|
4
|
-
"sourcesContent": ["import { logger } from './logger';\nimport type { IgnoredLocalEntry } from '../services/syncService';\n\n/**\n * Upper bound on entries we collect into `ignoredLocal`. A user that\n * clones a sibling repo into `farseer-apps/<tenant>/files/` (or worse,\n * `node_modules/`) would otherwise produce a multi-thousand-entry\n * array and a console wall. The warning only shows a 5-item preview\n * per category regardless of length, so capping the collection itself\n * loses no useful signal.\n */\nexport const IGNORED_LOCAL_CAP = 100;\n\n/**\n * Number of example file paths to surface per category in the warning text.\n * Independent of the in-memory cap above \u2014 the cap protects memory, the\n * preview count protects the user's eyes.\n */\nconst PREVIEW_COUNT = 5;\n\n/**\n * Surface files that live under the synced workspace but were dropped\n * from comparison because they don't match the current sync scope.\n *\n * Files are grouped by `reason` so the hint can be category-specific:\n * - `unsupportedExtension`: nudge the user toward `--include-ext`.\n * - `blocklistedFolder`: flag that opting in is unusual (the folder\n * is one users rarely want synced \u2014 node_modules/, dist/, \u2026).\n *\n * Hidden files (`.env`, `.git/`, `.vscode/`) are excluded upstream in\n * `getStatus`. The warning never tells the user to widen scope to\n * include those \u2014 that would be a credential-leak hint.\n *\n * `total` overrides the count reported in the warning header when the\n * caller truncated the list (the cap kicks in for misuse cases like\n * dropping `node_modules/` under the synced folder). Omit it when the\n * list is the full set.\n */\nexport function reportIgnoredLocal(ignoredLocal: IgnoredLocalEntry[], total?: number): void {\n if (ignoredLocal.length === 0 && (!total || total === 0)) return;\n const reportedTotal = total ?? ignoredLocal.length;\n logger.warning(`${reportedTotal} local file(s) outside the sync scope \u2014 NOT being compared or pushed.`);\n\n const byReason = {\n unsupportedExtension: [] as string[],\n blocklistedFolder: [] as string[],\n };\n for (const entry of ignoredLocal) {\n byReason[entry.reason].push(entry.path);\n }\n\n // Unsupported extension \u2014 straightforward \"broaden scope\" hint.\n // Listed first because most ignored files fall here under default\n // scope, and the hint is the safe one (no destructive opt-in).\n if (byReason.unsupportedExtension.length > 0) {\n const list = byReason.unsupportedExtension;\n const preview = list.slice(0, PREVIEW_COUNT).join(', ');\n const more = list.length > PREVIEW_COUNT ? `, +${list.length - PREVIEW_COUNT} more` : '';\n logger.dim(` Unsupported extension (${list.length}):`);\n logger.dim(` ${preview}${more}`);\n logger.dim(\n ' -> Include with --include-ext <ext> (e.g. --include-ext .csv), or `farseer config include --ext <ext>` to persist.',\n );\n }\n\n // Blocklisted folder \u2014 explicit warning that opting in is unusual.\n // The hint NEVER recommends a flag without first telling the user\n // these are typically tooling artifacts, not user content.\n if (byReason.blocklistedFolder.length > 0) {\n const list = byReason.blocklistedFolder;\n const preview = list.slice(0, PREVIEW_COUNT).join(', ');\n const more = list.length > PREVIEW_COUNT ? `, +${list.length - PREVIEW_COUNT} more` : '';\n logger.dim(` Inside blocklisted folder (${list.length}):`);\n logger.dim(` ${preview}${more}`);\n logger.dim(' -> Usually tooling output, not user content.');\n logger.dim(\n ' If you genuinely want one: --include-folder <path> (per-command) or `farseer config include --folder <path>` to persist.',\n );\n }\n\n // Hidden files are excluded from the warning entirely \u2014 see getStatus.\n // The hint deliberately omits any reference to hidden directories.\n}\n"],
|
|
5
4
|
"mappings": ";;;;;;;;;;;;;;;;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,
|
|
3
3
|
"sources": ["../../src/utils/syncScope.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * Which files the CLI treats as a developer's own source, in two scopes.\n */\n\n// Narrow set of \"script\" extensions \u2014 used by `farseer files list` and\n// `farseer list` to default to source-code style files when listing a\n// folder. NOT the default sync scope; see DEFAULT_SYNC_EXTENSIONS below.\nexport const DEFAULT_SCRIPT_EXTENSIONS = ['.ts', '.js'];\n\n// Default sync scope \u2014 the curated set of files a developer AUTHORS in an\n// editor. NARROWER than the backend's accepted extension list\n// (`cli/src/utils/fileValidation.ts:BACKEND_EXTENSION_WHITELIST`, which\n// mirrors `farseer/backend/app/openapi/v3/services/farseerFileService.ts`).\n// The earlier \"default sync = everything backend accepts\" expanded the\n// default scope to 25 entries including binary / data formats (.csv,\n// .parquet, .xlsx, .pdf, images) \u2014 large files no one edits in a code\n// editor that dominated first-pull time and made `status` noisy.\n//\n// Users opt into the rest of the backend whitelist (data / docs /\n// archives) via `--include-ext <ext>` or persistent\n// `farseer config include`. Anything still outside the backend whitelist\n// requires `--all` or `--include-folder`.\n//\n// Subset contract: every entry here must also be in\n// `BACKEND_EXTENSION_WHITELIST`, otherwise push pre-flight will reject\n// in-scope files (extension not allowed) \u2014 defeats the purpose of the\n// default scope. Asserted by `defaultSyncExtensionsParity.test.ts`.\nexport const DEFAULT_SYNC_EXTENSIONS = [\n // Code (frontend / scripts)\n '.ts',\n '.js',\n // Code (Python)\n '.py',\n // Config / data\n '.yml',\n '.yaml',\n '.json',\n // Docs\n '.md',\n];\n"],
|
|
5
4
|
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAOO,MAAM,4BAA4B,CAAC,OAAO,KAAK;AAoB/C,MAAM,0BAA0B;AAAA;AAAA,EAEnC;AAAA,EACA;AAAA;AAAA,EAEA;AAAA;AAAA,EAEA;AAAA,EACA;AAAA,EACA;AAAA;AAAA,EAEA;AACJ;",
|
|
6
5
|
"names": []
|
|
7
6
|
}
|
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/utils/updateCheck.ts"],
|
|
4
|
-
"sourcesContent": ["import * as https from 'https';\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport * as os from 'os';\nimport chalk from 'chalk';\nimport { CLI_VERSION } from './constants';\n\nconst CONFIG_DIR = path.join(os.homedir(), '.farseer');\nconst CACHE_FILE = path.join(CONFIG_DIR, 'update-check.json');\nconst CACHE_TTL_MS = 4 * 60 * 60 * 1000; // 4 hours\nconst FETCH_TIMEOUT_MS = 3000;\nconst REGISTRY_URL = 'https://registry.npmjs.org/farseer-cli/latest';\n\ninterface UpdateCache {\n lastCheck: number;\n latestVersion: string;\n}\n\nexport function isNewerVersion(latest: string, current: string): boolean {\n const latestParts = latest.split('.').map(Number);\n const currentParts = current.split('.').map(Number);\n for (let i = 0; i < 3; i++) {\n const l = latestParts[i] || 0;\n const c = currentParts[i] || 0;\n if (l > c) return true;\n if (l < c) return false;\n }\n return false;\n}\n\nfunction readCache(): UpdateCache | null {\n try {\n const data = JSON.parse(fs.readFileSync(CACHE_FILE, 'utf-8'));\n if (typeof data.lastCheck === 'number' && typeof data.latestVersion === 'string') {\n return data as UpdateCache;\n }\n } catch {\n // Cache missing or corrupt \u2014 ignore\n }\n return null;\n}\n\nfunction writeCache(latestVersion: string): void {\n try {\n if (!fs.existsSync(CONFIG_DIR)) {\n fs.mkdirSync(CONFIG_DIR, { recursive: true });\n }\n const data: UpdateCache = { lastCheck: Date.now(), latestVersion };\n fs.writeFileSync(CACHE_FILE, JSON.stringify(data), 'utf-8');\n } catch {\n // Non-critical \u2014 ignore write errors\n }\n}\n\nfunction fetchLatestVersion(): Promise<string | null> {\n return new Promise((resolve) => {\n const req = https.get(REGISTRY_URL, { timeout: FETCH_TIMEOUT_MS }, (res) => {\n if (res.statusCode !== 200) {\n res.resume(); // drain response\n resolve(null);\n return;\n }\n let body = '';\n res.setEncoding('utf-8');\n res.on('data', (chunk) => (body += chunk));\n res.on('end', () => {\n try {\n const json = JSON.parse(body);\n resolve(typeof json.version === 'string' ? json.version : null);\n } catch {\n resolve(null);\n }\n });\n });\n req.on('error', () => resolve(null));\n req.on('timeout', () => {\n req.destroy();\n resolve(null);\n });\n });\n}\n\nexport async function checkForUpdates(): Promise<string | null> {\n try {\n let latestVersion: string | null = null;\n\n const cache = readCache();\n if (cache && Date.now() - cache.lastCheck < CACHE_TTL_MS) {\n latestVersion = cache.latestVersion;\n } else {\n latestVersion = await fetchLatestVersion();\n if (latestVersion) {\n writeCache(latestVersion);\n }\n }\n\n if (latestVersion && isNewerVersion(latestVersion, CLI_VERSION)) {\n return [\n '',\n chalk.yellow(` Update available: ${CLI_VERSION} \u2192 ${chalk.green(latestVersion)}`),\n chalk.yellow(` Run ${chalk.cyan('npm install -g farseer-cli@latest')} to update`),\n '',\n ].join('\\n');\n }\n\n return null;\n } catch {\n // Graceful failure \u2014 never let update check break the CLI\n return null;\n }\n}\n"],
|
|
5
4
|
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,YAAuB;AACvB,SAAoB;AACpB,WAAsB;AACtB,SAAoB;AACpB,mBAAkB;AAClB,uBAA4B;AAE5B,MAAM,aAAa,KAAK,KAAK,GAAG,QAAQ,GAAG,UAAU;AACrD,MAAM,aAAa,KAAK,KAAK,YAAY,mBAAmB;AAC5D,MAAM,eAAe,IAAI,KAAK,KAAK;AACnC,MAAM,mBAAmB;AACzB,MAAM,eAAe;AAOd,SAAS,eAAe,QAAgB,SAA0B;AACrE,QAAM,cAAc,OAAO,MAAM,GAAG,EAAE,IAAI,MAAM;AAChD,QAAM,eAAe,QAAQ,MAAM,GAAG,EAAE,IAAI,MAAM;AAClD,WAAS,IAAI,GAAG,IAAI,GAAG,KAAK;AACxB,UAAM,IAAI,YAAY,CAAC,KAAK;AAC5B,UAAM,IAAI,aAAa,C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,QAAQ;AACZ,cAAQ,IAAI;AAAA,IAChB,CAAC;AAAA,EACL,CAAC;AACL;AAEA,eAAsB,kBAA0C;AAC5D,MAAI;AACA,QAAI,gBAA+B;AAEnC,UAAM,QAAQ,UAAU;AACxB,QAAI,SAAS,KAAK,IAAI,IAAI,MAAM,YAAY,cAAc;AACtD,sBAAgB,MAAM;AAAA,IAC1B,OAAO;AACH,sBAAgB,MAAM,mBAAmB;AACzC,UAAI,eAAe;AACf,mBAAW,aAAa;AAAA,MAC5B;AAAA,IACJ;AAEA,QAAI,iBAAiB,eAAe,eAAe,4BAAW,GAAG;AAC7D,aAAO;AAAA,QACH;AAAA,QACA,aAAAA,QAAM,OAAO,uBAAuB,4BAAW,WAAM,aAAAA,QAAM,MAAM,aAAa,CAAC,EAAE;AAAA,QACjF,aAAAA,QAAM,OAAO,SAAS,aAAAA,QAAM,KAAK,mCAAmC,CAAC,YAAY;AAAA,QACjF;AAAA,MACJ,EAAE,KAAK,IAAI;AAAA,IACf;AAEA,WAAO;AAAA,EACX,QAAQ;AAEJ,WAAO;AAAA,EACX;AACJ;",
|
|
6
5
|
"names": ["chalk"]
|
|
7
6
|
}
|
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/utils/variableValues.ts"],
|
|
4
|
-
"sourcesContent": ["// Shared by CLI commands and the existing MCP variable tools.\nconst ROLLUP_TYPES: Record<string, string> = {\n sum: 'SUM',\n average: 'AVERAGE',\n avg: 'AVERAGE',\n min: 'MIN',\n max: 'MAX',\n none: 'NONE',\n formula: 'FORMULA',\n closingstate: 'CLOSING STATE',\n 'closing state': 'CLOSING STATE',\n 'closing-state': 'CLOSING STATE',\n last: 'CLOSING STATE',\n beginningstate: 'BEGINNING STATE',\n 'beginning state': 'BEGINNING STATE',\n 'beginning-state': 'BEGINNING STATE',\n first: 'BEGINNING STATE',\n};\n\nexport function normalizeRollupType(value: string): string {\n const normalized = ROLLUP_TYPES[value.trim().toLowerCase()];\n if (!normalized)\n throw new Error(\n `Invalid rollupType \"${value}\". Valid types: ${[...new Set(Object.values(ROLLUP_TYPES))].join(', ')}`,\n );\n return normalized;\n}\n\nexport function normalizeDataType(value: string): string {\n const normalized = value.trim().toUpperCase();\n if (!['INTEGER', 'DECIMAL'].includes(normalized))\n throw new Error(`Invalid data type \"${value}\". Use Decimal or Integer.`);\n return normalized;\n}\n\n/** Entity updates require the complete variable component; omit read-only response fields. */\nexport function writableVariable(current: Record<string, any> = {}): Record<string, any> {\n return {\n notes: current.notes ?? null,\n tableGids: current.tableGids ?? [],\n memberGids: current.memberGids ?? [],\n rollupType: current.rollupType ?? 'SUM',\n dataType: current.dataType ?? 'DECIMAL',\n topDownMapping: current.topDownMapping ?? null,\n measure: current.measure ?? false,\n readonly: current.readonly ?? false,\n calculateOnDemand: current.calculateOnDemand ?? false,\n zConstraint: current.zConstraint ?? false,\n optimizeCalculation: current.optimizeCalculation ?? true,\n };\n}\n"],
|
|
5
4
|
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AACA,MAAM,eAAuC;AAAA,EACzC,KAAK;AAAA,EACL,SAAS;AAAA,EACT,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,MAAM;AAAA,EACN,SAAS;AAAA,EACT,cAAc;AAAA,EACd,iBAAiB;AAAA,EACjB,iBAAiB;AAAA,EACjB,MAAM;AAAA,EACN,gBAAgB;AAAA,EAChB,mBAAmB;AAAA,EACnB,mBAAmB;AAAA,EACnB,OAAO;AACX;AAEO,SAAS,oBAAoB,OAAuB;AACvD,QAAM,aAAa,aAAa,MAAM,KAAK,EAAE,YAAY,CAAC;AAC1D,MAAI,CAAC;AACD,UAAM,IAAI;AAAA,MACN,uBAAuB,KAAK,mBAAmB,CAAC,GAAG,IAAI,IAAI,OAAO,OAAO,YAAY,CAAC,CAAC,EAAE,KAAK,IAAI,CAAC;AAAA,IACvG;AACJ,SAAO;AACX;AAEO,SAAS,kBAAkB,OAAuB;AACrD,QAAM,aAAa,MAAM,KAAK,EAAE,YAAY;AAC5C,MAAI,CAAC,CAAC,WAAW,SAAS,EAAE,SAAS,UAAU;AAC3C,UAAM,IAAI,MAAM,sBAAsB,KAAK,4BAA4B;AAC3E,SAAO;AACX;AAGO,SAAS,iBAAiB,UAA+B,CAAC,GAAwB;AACrF,SAAO;AAAA,IACH,OAAO,QAAQ,SAAS;AAAA,IACxB,WAAW,QAAQ,aAAa,CAAC;AAAA,IACjC,YAAY,QAAQ,cAAc,CAAC;AAAA,IACnC,YAAY,QAAQ,cAAc;AAAA,IAClC,UAAU,QAAQ,YAAY;AAAA,IAC9B,gBAAgB,QAAQ,kBAAkB;AAAA,IAC1C,SAAS,QAAQ,WAAW;AAAA,IAC5B,UAAU,QAAQ,YAAY;AAAA,IAC9B,mBAAmB,QAAQ,qBAAqB;AAAA,IAChD,aAAa,QAAQ,eAAe;AAAA,IACpC,qBAAqB,QAAQ,uBAAuB;AAAA,EACxD;AACJ;",
|
|
6
5
|
"names": []
|
|
7
6
|
}
|
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/utils/workspace.ts"],
|
|
4
|
-
"sourcesContent": ["import * as fs from 'fs';\nimport { logger } from './logger';\n\n// Entries that MUST appear in the tenant .gitignore for sync to work\n// correctly across machines. Order matters only for readability of a\n// freshly-created file; for the merge case (existing .gitignore missing\n// entries) we append missing entries in this order.\nconst REQUIRED_GITIGNORE_ENTRIES: { pattern: string; comment?: string }[] = [\n {\n pattern: '.farseer-sync.json',\n comment:\n '# Per-machine sync baseline \u2014 diff state, not user work.\\n' +\n '# Committing this causes spurious \"remote drifted\" reports on other machines.',\n },\n { pattern: '.farseer-audit.log', comment: '# Local audit / crash logs.' },\n { pattern: 'node_modules/', comment: '# Node tooling.' },\n];\n\n/**\n * Ensure the tenant .gitignore contains every per-machine entry. If the\n * file doesn't exist, write a fresh one with comments. If it exists but\n * is missing entries (common: pre-1.6.2 workspaces, or `npm init` created\n * a partial .gitignore listing only `node_modules/`), append the missing\n * patterns idempotently \u2014 match on exact-line so a re-run is a no-op.\n *\n * Called from the workspace-initializing path (`farseer pull`) so a\n * workspace can never reach a state where `.farseer-sync.json` is\n * unignored. Living in `utils/` rather than `commands/` keeps it\n * reusable, so any future init path picks it up too.\n */\nexport function ensureGitignoreEntries(gitignorePath: string): void {\n if (!fs.existsSync(gitignorePath)) {\n const blocks = REQUIRED_GITIGNORE_ENTRIES.map((e) =>\n e.comment ? `${e.comment}\\n${e.pattern}\\n` : `${e.pattern}\\n`,\n );\n fs.writeFileSync(gitignorePath, blocks.join('\\n'), 'utf-8');\n logger.dim(`Created .gitignore`);\n return;\n }\n\n const existing = fs.readFileSync(gitignorePath, 'utf-8');\n const existingLines = new Set(\n existing\n .split('\\n')\n .map((l) => l.trim())\n .filter((l) => l.length > 0 && !l.startsWith('#')),\n );\n\n const missing = REQUIRED_GITIGNORE_ENTRIES.filter((e) => !existingLines.has(e.pattern));\n if (missing.length === 0) return;\n\n // Preserve the file's native line ending so we don't mix CRLF/LF on Windows workspaces.\n const eol = existing.includes('\\r\\n') ? '\\r\\n' : '\\n';\n const normalize = (s: string): string => (eol === '\\n' ? s : s.replace(/\\n/g, eol));\n const needsLeadingNewline = !existing.endsWith('\\n');\n const appended =\n (needsLeadingNewline ? eol : '') +\n eol +\n '# farseer-cli \u2014 sync state (added by `farseer pull`).' +\n eol +\n missing.map((e) => (e.comment ? `${normalize(e.comment)}${eol}${e.pattern}` : e.pattern)).join(eol) +\n eol;\n fs.appendFileSync(gitignorePath, appended, 'utf-8');\n logger.dim(`Appended ${missing.length} entr${missing.length === 1 ? 'y' : 'ies'} to .gitignore`);\n}\n"],
|
|
5
4
|
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,SAAoB;AACpB,oBAAuB;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,OAAO;AAClD,uBAAO,IAAI,YAAY,QAAQ,MAAM,QAAQ,QAAQ,WAAW,IAAI,MAAM,KAAK,gBAAgB;AACnG;",
|
|
6
5
|
"names": []
|
|
7
6
|
}
|
package/docs/cli-guide.md
CHANGED
|
@@ -121,7 +121,7 @@ deleted (they share the same status engine).
|
|
|
121
121
|
1. Write your script in `farseer-apps/<tenant>/files/Scripts/myScript.ts`
|
|
122
122
|
2. Push: `farseer push`
|
|
123
123
|
3. Create: `farseer app create "My App"`
|
|
124
|
-
4. Configure: `farseer app configure "My App" --
|
|
124
|
+
4. Configure: `farseer app configure "My App" --source-folder Scripts --entrypoint myScript.ts`
|
|
125
125
|
|
|
126
126
|
### Where and When an App Runs
|
|
127
127
|
|
package/docs/import-workflows.md
CHANGED
|
@@ -16,17 +16,17 @@ Creates an import job and returns an `ImportActions` object with methods for add
|
|
|
16
16
|
|
|
17
17
|
```typescript
|
|
18
18
|
const importJob = await client.createImportJob({
|
|
19
|
-
title:
|
|
20
|
-
description: '
|
|
19
|
+
title: `Planned costs ${year} ${version}`,
|
|
20
|
+
description: 'Planned costs by cost center',
|
|
21
21
|
columns: [
|
|
22
|
-
{ type: 'DIMENSION_TABLE', dimensionTableName: '
|
|
22
|
+
{ type: 'DIMENSION_TABLE', dimensionTableName: 'Cost center' },
|
|
23
23
|
{ type: 'DIMENSION_TABLE', dimensionTableName: 'Entities' },
|
|
24
24
|
{ type: 'DIMENSION_TABLE', dimensionTableName: 'Years' },
|
|
25
25
|
{ type: 'DIMENSION_TABLE', dimensionTableName: 'Months' },
|
|
26
26
|
{ type: 'DIMENSION_TABLE', dimensionTableName: 'Versions' },
|
|
27
|
-
{ type: 'VARIABLE', variableName: '
|
|
27
|
+
{ type: 'VARIABLE', variableName: 'Planned costs' },
|
|
28
28
|
],
|
|
29
|
-
labels: ['
|
|
29
|
+
labels: ['planned costs', year, version]
|
|
30
30
|
});
|
|
31
31
|
```
|
|
32
32
|
|
|
@@ -39,10 +39,10 @@ async function getImportMetadata(client: FarseerClient) {
|
|
|
39
39
|
const YearsTable = await client.getDimensionTable('Years');
|
|
40
40
|
const MonthsTable = await client.getDimensionTable('Months');
|
|
41
41
|
const EntitiesTable = await client.getDimensionTable('Entities');
|
|
42
|
-
const
|
|
42
|
+
const CostCenterTable = await client.getDimensionTable('Cost center');
|
|
43
43
|
|
|
44
44
|
// VARIABLES
|
|
45
|
-
const
|
|
45
|
+
const PlannedCostsVar = await client.getVariable('Planned costs');
|
|
46
46
|
|
|
47
47
|
return {
|
|
48
48
|
handleMissingTags: HandleMissingTags.SKIP_ROW,
|
|
@@ -70,24 +70,24 @@ async function getImportMetadata(client: FarseerClient) {
|
|
|
70
70
|
tableTagId: EntitiesTable.id,
|
|
71
71
|
},
|
|
72
72
|
{
|
|
73
|
-
name: '
|
|
73
|
+
name: 'Cost center',
|
|
74
74
|
dataContext: farseer.ColumnMetaDataContext.IDENTIFIER,
|
|
75
|
-
tableTagId:
|
|
75
|
+
tableTagId: CostCenterTable.id,
|
|
76
76
|
},
|
|
77
77
|
{
|
|
78
|
-
name: '
|
|
78
|
+
name: 'Planned costs',
|
|
79
79
|
dataContext: farseer.ColumnMetaDataContext.VALUES,
|
|
80
|
-
applyTagsIds: [
|
|
80
|
+
applyTagsIds: [PlannedCostsVar.id],
|
|
81
81
|
},
|
|
82
82
|
],
|
|
83
83
|
};
|
|
84
84
|
}
|
|
85
85
|
|
|
86
86
|
const importJob = await client.createImportJob({
|
|
87
|
-
title: '
|
|
88
|
-
description: '
|
|
87
|
+
title: 'Planned costs',
|
|
88
|
+
description: 'Planned costs by cost center',
|
|
89
89
|
metadata: await getImportMetadata(client),
|
|
90
|
-
labels: ['auto', '
|
|
90
|
+
labels: ['auto', 'planned costs']
|
|
91
91
|
});
|
|
92
92
|
```
|
|
93
93
|
|
package/docs/new-app-template.md
CHANGED
|
@@ -47,7 +47,7 @@ farseer app create "My App Name"
|
|
|
47
47
|
### Step 4: Configure the App
|
|
48
48
|
|
|
49
49
|
```bash
|
|
50
|
-
farseer app configure "My App Name" --
|
|
50
|
+
farseer app configure "My App Name" --source-folder Scripts --entrypoint myScript.ts
|
|
51
51
|
```
|
|
52
52
|
|
|
53
53
|
Optionally add arguments:
|
|
@@ -44,7 +44,7 @@ The permissions alone are not enough for an analyst who is not a super user: Far
|
|
|
44
44
|
|
|
45
45
|
The CLI authors for exactly one engine version: the one inside the runner image it was released with. When Farseer releases a new runner image it also releases a CLI, and for a while the backend accepts both. `check` reports a newer CLI as available; below the minimum, pipeline commands stop with "update the CLI". IT should expect to update `farseer-cli` on analysts' laptops a few times a year.
|
|
46
46
|
|
|
47
|
-
The CLI never changes which engine a job runs on its own. A job on an older image keeps running on it. To edit it with a newer CLI, someone runs `farseer pipeline upgrade-runtime`, which moves the job to the CLI's image and says what it moved from; until then the CLI refuses to push to it. That includes pipelines Farseer consultants built for you earlier: the assistant asks before upgrading one, and if the newer engine rejects something it will say so and offer to fix it. A job set to follow `latest` is left alone. Moving a pipeline from simple-pipelines 2.x to 3.0 is a breaking change: every extract must be split into an extract, which only fetches the source's file, and a parse step that reads it, so an inherited pipeline's runs fail on the new engine from its upgrade until it is changed. The assistant's pipeline skill describes the new shape and can make that change. If you would rather a consultant did that, ask before an inherited pipeline is upgraded.
|
|
47
|
+
The CLI never changes which engine a job runs on its own. A job on an older image keeps running on it. To edit it with a newer CLI, someone runs `farseer pipeline upgrade-runtime`, which moves the job to the CLI's image and says what it moved from; until then the CLI refuses to push to it. That includes pipelines Farseer consultants built for you earlier: the assistant asks before upgrading one, and if the newer engine rejects something it will say so and offer to fix it. A job set to follow `latest` is left alone. Moving a pipeline from simple-pipelines 2.x to 3.0 is a breaking change: every extract must be split into an extract, which only fetches the source's file, and a parse step that reads it, so an inherited pipeline's runs fail on the new engine from its upgrade until it is changed. The assistant's pipeline skill describes the new shape and can make that change. If you would rather a consultant did that, ask before an inherited pipeline is upgraded. From 3.1.1, an inherited pipeline that names no store also moves its outputs from its `Data` folder to datasets when it is upgraded, so if anything reads that folder, ask before upgrading it.
|
|
48
48
|
|
|
49
49
|
## Moving to production
|
|
50
50
|
|