farseer-cli 1.10.3 → 1.11.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 +5 -0
- package/dist/commands/app.js +15 -12
- package/dist/commands/app.js.map +2 -2
- package/dist/commands/apps.js +3 -3
- package/dist/commands/apps.js.map +2 -2
- package/dist/commands/cells.js +3 -3
- package/dist/commands/cells.js.map +2 -2
- package/dist/commands/config.js +23 -15
- package/dist/commands/config.js.map +2 -2
- package/dist/commands/dashboards.js +3 -3
- package/dist/commands/dashboards.js.map +2 -2
- package/dist/commands/dimensions.js +3 -3
- package/dist/commands/dimensions.js.map +2 -2
- package/dist/commands/files.js +5 -4
- package/dist/commands/files.js.map +2 -2
- package/dist/commands/formula.js +3 -3
- package/dist/commands/formula.js.map +2 -2
- package/dist/commands/list.js +5 -4
- package/dist/commands/list.js.map +2 -2
- package/dist/commands/login.js +6 -5
- package/dist/commands/login.js.map +2 -2
- package/dist/commands/model.js +5 -4
- package/dist/commands/model.js.map +2 -2
- package/dist/commands/push.js +5 -7
- package/dist/commands/push.js.map +2 -2
- package/dist/commands/run.js +3 -3
- package/dist/commands/run.js.map +2 -2
- package/dist/commands/sheets.js +3 -3
- package/dist/commands/sheets.js.map +2 -2
- package/dist/commands/variables.js +5 -4
- package/dist/commands/variables.js.map +2 -2
- package/dist/mcp/index.js +1 -1
- package/dist/mcp/index.js.map +2 -2
- package/dist/mcp/tools/appTools.js +3 -3
- package/dist/mcp/tools/appTools.js.map +2 -2
- package/dist/mcp/tools/dataTools.js +5 -2
- package/dist/mcp/tools/dataTools.js.map +2 -2
- package/dist/mcp/tools/modelTools.js +45 -48
- package/dist/mcp/tools/modelTools.js.map +2 -2
- package/dist/mcp/utils/session.js +2 -2
- package/dist/mcp/utils/session.js.map +2 -2
- package/dist/services/appSyncService.js.map +1 -1
- package/dist/services/apps.js +149 -0
- package/dist/services/apps.js.map +7 -0
- package/dist/services/authErrors.js +77 -0
- package/dist/services/authErrors.js.map +7 -0
- package/dist/services/configService.js +7 -4
- package/dist/services/configService.js.map +2 -2
- package/dist/services/credentials.js +87 -0
- package/dist/services/credentials.js.map +7 -0
- package/dist/services/farseerService.js +247 -112
- package/dist/services/farseerService.js.map +2 -2
- package/dist/services/httpError.js +35 -0
- package/dist/services/httpError.js.map +7 -0
- package/dist/services/modelExport.js +63 -0
- package/dist/services/modelExport.js.map +7 -0
- package/dist/services/organisation.js +88 -0
- package/dist/services/organisation.js.map +7 -0
- package/dist/services/preflight.js +10 -13
- package/dist/services/preflight.js.map +2 -2
- package/dist/services/syncService.js +2 -2
- package/dist/services/syncService.js.map +2 -2
- package/dist/utils/constants.js +2 -5
- package/dist/utils/constants.js.map +2 -2
- package/dist/utils/fileLogger.js +24 -1
- package/dist/utils/fileLogger.js.map +2 -2
- package/dist/utils/folderMatch.js +49 -0
- package/dist/utils/folderMatch.js.map +7 -0
- package/dist/utils/helpers.js +26 -0
- package/dist/utils/helpers.js.map +2 -2
- package/dist/utils/syncScope.js +44 -0
- package/dist/utils/syncScope.js.map +7 -0
- package/docs/api-reference.md +13 -1
- package/package.json +1 -1
- package/dist/services/farseerApi.js +0 -716
- package/dist/services/farseerApi.js.map +0 -7
- package/dist/services/farseerFactory.js +0 -276
- package/dist/services/farseerFactory.js.map +0 -7
package/dist/utils/fileLogger.js
CHANGED
|
@@ -122,6 +122,7 @@ function serializeError(error) {
|
|
|
122
122
|
}
|
|
123
123
|
let initialized = false;
|
|
124
124
|
let crashHandlersInstalled = false;
|
|
125
|
+
let exitOnUnhandledRejection = true;
|
|
125
126
|
const fileLogger = {
|
|
126
127
|
/**
|
|
127
128
|
* Initialize the file logger. Idempotent — safe to call multiple times.
|
|
@@ -208,8 +209,21 @@ const fileLogger = {
|
|
|
208
209
|
},
|
|
209
210
|
/**
|
|
210
211
|
* Install crash handlers that write to the log before exit. Idempotent.
|
|
212
|
+
*
|
|
213
|
+
* `exitOnRejection` is the difference between the two surfaces. A command is
|
|
214
|
+
* one process for one operation: a rejection it did not catch means the
|
|
215
|
+
* operation did not happen, and a shell that reads the exit code has to be
|
|
216
|
+
* told that. A server is one process for many operations, each of which
|
|
217
|
+
* already answers its own caller, so ending it would take out a session over
|
|
218
|
+
* something that has been reported.
|
|
219
|
+
*
|
|
220
|
+
* The listeners are registered once, but the policy is taken from the latest
|
|
221
|
+
* call and read when a rejection arrives: the CLI entry point installs these
|
|
222
|
+
* before it knows which command it is running, and the MCP server, which
|
|
223
|
+
* must not exit, installs them again once it does.
|
|
211
224
|
*/
|
|
212
|
-
installCrashHandlers() {
|
|
225
|
+
installCrashHandlers({ exitOnRejection = true } = {}) {
|
|
226
|
+
exitOnUnhandledRejection = exitOnRejection;
|
|
213
227
|
if (crashHandlersInstalled) return;
|
|
214
228
|
crashHandlersInstalled = true;
|
|
215
229
|
process.on("uncaughtException", (err) => {
|
|
@@ -228,6 +242,15 @@ Crash log written to: ${logFilePath}`);
|
|
|
228
242
|
source: "unhandledRejection",
|
|
229
243
|
...serializeError(reason)
|
|
230
244
|
});
|
|
245
|
+
if (!exitOnUnhandledRejection) {
|
|
246
|
+
return;
|
|
247
|
+
}
|
|
248
|
+
console.error(`
|
|
249
|
+
Command failed: ${reason instanceof Error ? reason.message : String(reason)}`);
|
|
250
|
+
if (logFilePath) {
|
|
251
|
+
console.error(`Crash log written to: ${logFilePath}`);
|
|
252
|
+
}
|
|
253
|
+
process.exit(1);
|
|
231
254
|
});
|
|
232
255
|
}
|
|
233
256
|
};
|
|
@@ -1,7 +1,7 @@
|
|
|
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;\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 installCrashHandlers(): void {\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 // Don't exit \u2014 unhandled rejections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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
|
+
"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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C5B,6BAAyB;AACzB,YAAQ,GAAG,qBAAqB,CAAC,QAAQ;AAErC,qBAAe,SAAS,SAAS;AAAA,QAC7B,QAAQ;AAAA,QACR,GAAG,eAAe,GAAG;AAAA,MACzB,CAAC;AACD,UAAI,aAAa;AACb,gBAAQ,MAAM;AAAA,wBAA2B,WAAW,EAAE;AAAA,MAC1D;AACA,cAAQ,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
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
var folderMatch_exports = {};
|
|
20
|
+
__export(folderMatch_exports, {
|
|
21
|
+
AmbiguousFolderError: () => AmbiguousFolderError,
|
|
22
|
+
matchFolderSegment: () => matchFolderSegment
|
|
23
|
+
});
|
|
24
|
+
module.exports = __toCommonJS(folderMatch_exports);
|
|
25
|
+
class AmbiguousFolderError extends Error {
|
|
26
|
+
}
|
|
27
|
+
function matchFolderSegment(folders, segment) {
|
|
28
|
+
const exact = folders.find((folder) => folder.name === segment);
|
|
29
|
+
if (exact) {
|
|
30
|
+
return exact;
|
|
31
|
+
}
|
|
32
|
+
const insensitive = folders.filter((folder) => folder.name.toLowerCase() === segment.toLowerCase());
|
|
33
|
+
if (insensitive.length === 1) {
|
|
34
|
+
return insensitive[0];
|
|
35
|
+
}
|
|
36
|
+
if (insensitive.length > 1) {
|
|
37
|
+
const names = insensitive.map((folder) => `"${folder.name}"`).join(", ");
|
|
38
|
+
throw new AmbiguousFolderError(
|
|
39
|
+
`Folder name "${segment}" matches ${insensitive.length} folders that differ only in case: ${names}. Use the exact name.`
|
|
40
|
+
);
|
|
41
|
+
}
|
|
42
|
+
return null;
|
|
43
|
+
}
|
|
44
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
45
|
+
0 && (module.exports = {
|
|
46
|
+
AmbiguousFolderError,
|
|
47
|
+
matchFolderSegment
|
|
48
|
+
});
|
|
49
|
+
//# sourceMappingURL=folderMatch.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 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
|
+
"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
|
+
"names": []
|
|
7
|
+
}
|
package/dist/utils/helpers.js
CHANGED
|
@@ -30,6 +30,7 @@ var helpers_exports = {};
|
|
|
30
30
|
__export(helpers_exports, {
|
|
31
31
|
appendToAuditLog: () => appendToAuditLog,
|
|
32
32
|
calculateHash: () => calculateHash,
|
|
33
|
+
connectionFailureMessage: () => connectionFailureMessage,
|
|
33
34
|
displayLocalPath: () => displayLocalPath,
|
|
34
35
|
ensureDirectoryExists: () => ensureDirectoryExists,
|
|
35
36
|
fetchWithConcurrency: () => fetchWithConcurrency,
|
|
@@ -56,6 +57,7 @@ __export(helpers_exports, {
|
|
|
56
57
|
isOsMetadataFile: () => isOsMetadataFile,
|
|
57
58
|
isScriptFile: () => isScriptFile,
|
|
58
59
|
isTextFile: () => isTextFile,
|
|
60
|
+
orExit: () => orExit,
|
|
59
61
|
parseAppArgs: () => parseAppArgs,
|
|
60
62
|
resolveOrgAndTenant: () => resolveOrgAndTenant,
|
|
61
63
|
resolveOrgAndTenantOrExit: () => resolveOrgAndTenantOrExit,
|
|
@@ -73,6 +75,16 @@ var path = __toESM(require("path"));
|
|
|
73
75
|
var fs = __toESM(require("fs"));
|
|
74
76
|
var import_configService = require("../services/configService");
|
|
75
77
|
var import_logger = require("./logger");
|
|
78
|
+
var import_errorFormatter = require("./errorFormatter");
|
|
79
|
+
async function orExit(work, message) {
|
|
80
|
+
try {
|
|
81
|
+
return await work;
|
|
82
|
+
} catch (error) {
|
|
83
|
+
import_logger.logger.error(message);
|
|
84
|
+
import_logger.logger.dim(await (0, import_errorFormatter.formatClientError)(error));
|
|
85
|
+
return process.exit(1);
|
|
86
|
+
}
|
|
87
|
+
}
|
|
76
88
|
function calculateHash(content) {
|
|
77
89
|
return crypto.createHash("md5").update(content).digest("hex");
|
|
78
90
|
}
|
|
@@ -254,6 +266,18 @@ function getCredentialsHint(tenant) {
|
|
|
254
266
|
return `Use: farseer login
|
|
255
267
|
Or: farseer config set ${tenant} --api-key <key> --org <organisation>`;
|
|
256
268
|
}
|
|
269
|
+
function connectionFailureMessage(reason, host, tenant) {
|
|
270
|
+
switch (reason) {
|
|
271
|
+
case "rejected":
|
|
272
|
+
return "Connection failed: the server rejected this API key.";
|
|
273
|
+
case "tenant-unknown":
|
|
274
|
+
return `Connection failed: ${host} has no tenant "${tenant}". The key is fine \u2014 check the organisation.`;
|
|
275
|
+
case "server-error":
|
|
276
|
+
return `Connection failed: ${host} answered with an error.`;
|
|
277
|
+
case "unreachable":
|
|
278
|
+
return `Connection failed: could not reach ${host}.`;
|
|
279
|
+
}
|
|
280
|
+
}
|
|
257
281
|
function getEnvCheckout() {
|
|
258
282
|
const tenant = process.env.FARSEER_TENANT;
|
|
259
283
|
if (!tenant) return null;
|
|
@@ -474,6 +498,7 @@ function appendToAuditLog(tenant, entries) {
|
|
|
474
498
|
0 && (module.exports = {
|
|
475
499
|
appendToAuditLog,
|
|
476
500
|
calculateHash,
|
|
501
|
+
connectionFailureMessage,
|
|
477
502
|
displayLocalPath,
|
|
478
503
|
ensureDirectoryExists,
|
|
479
504
|
fetchWithConcurrency,
|
|
@@ -500,6 +525,7 @@ function appendToAuditLog(tenant, entries) {
|
|
|
500
525
|
isOsMetadataFile,
|
|
501
526
|
isScriptFile,
|
|
502
527
|
isTextFile,
|
|
528
|
+
orExit,
|
|
503
529
|
parseAppArgs,
|
|
504
530
|
resolveOrgAndTenant,
|
|
505
531
|
resolveOrgAndTenantOrExit,
|
|
@@ -1,7 +1,7 @@
|
|
|
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';\n\nexport function calculateHash(content: string | Buffer): string {\n return crypto.createHash('md5').update(content).digest('hex');\n}\n\nexport function getAppsDir(): string {\n return path.join(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 * 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(args: string[]): ParsedAppArgs {\n if (args.length === 0) {\n logger.error('App name is required.');\n process.exit(1);\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// 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
|
-
"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,aAAwB;AACxB,WAAsB;AACtB,SAAoB;AACpB,2BAA4C;AAC5C,oBAAuB;
|
|
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 { ConnectionFailure } from '../services/farseerService';\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\nexport function calculateHash(content: string | Buffer): string {\n return crypto.createHash('md5').update(content).digest('hex');\n}\n\nexport function getAppsDir(): string {\n return path.join(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(args: string[]): ParsedAppArgs {\n if (args.length === 0) {\n logger.error('App name is required.');\n process.exit(1);\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// 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
|
+
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;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;AAAA,EACJ;AAEA,SAAO;AACX;AAoBA,eAAsB,qBAClB,OACA,SACA,cAAsB,IACV;AACZ,QAAM,UAAe,CAAC;AAEtB,WAAS,IAAI,GAAG,IAAI,MAAM,QAAQ,KAAK,aAAa;AAChD,UAAM,QAAQ,MAAM,MAAM,GAAG,IAAI,WAAW;AAC5C,UAAM,eAAe,MAAM,QAAQ,IAAI,MAAM,IAAI,CAAC,MAAM,eAAe,QAAQ,MAAM,IAAI,UAAU,CAAC,CAAC;AACrG,YAAQ,KAAK,GAAG,YAAY;AAAA,EAChC;AAEA,SAAO;AACX;AAEO,SAAS,iBAAiB,QAAgB,SAAgC;AAC7E,MAAI,QAAQ,WAAW,GAAG;AACtB;AAAA,EACJ;AAEA,QAAM,UAAU,gBAAgB,MAAM;AACtC,QAAM,aAAY,oBAAI,KAAK,GAAE,YAAY;AAEzC,MAAI,aAAa;AACjB,aAAW,SAAS,SAAS;AACzB,UAAM,eAAe,MAAM,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
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
var syncScope_exports = {};
|
|
20
|
+
__export(syncScope_exports, {
|
|
21
|
+
DEFAULT_SCRIPT_EXTENSIONS: () => DEFAULT_SCRIPT_EXTENSIONS,
|
|
22
|
+
DEFAULT_SYNC_EXTENSIONS: () => DEFAULT_SYNC_EXTENSIONS
|
|
23
|
+
});
|
|
24
|
+
module.exports = __toCommonJS(syncScope_exports);
|
|
25
|
+
const DEFAULT_SCRIPT_EXTENSIONS = [".ts", ".js"];
|
|
26
|
+
const DEFAULT_SYNC_EXTENSIONS = [
|
|
27
|
+
// Code (frontend / scripts)
|
|
28
|
+
".ts",
|
|
29
|
+
".js",
|
|
30
|
+
// Code (Python)
|
|
31
|
+
".py",
|
|
32
|
+
// Config / data
|
|
33
|
+
".yml",
|
|
34
|
+
".yaml",
|
|
35
|
+
".json",
|
|
36
|
+
// Docs
|
|
37
|
+
".md"
|
|
38
|
+
];
|
|
39
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
40
|
+
0 && (module.exports = {
|
|
41
|
+
DEFAULT_SCRIPT_EXTENSIONS,
|
|
42
|
+
DEFAULT_SYNC_EXTENSIONS
|
|
43
|
+
});
|
|
44
|
+
//# sourceMappingURL=syncScope.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 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
|
+
"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
|
+
"names": []
|
|
7
|
+
}
|
package/docs/api-reference.md
CHANGED
|
@@ -115,6 +115,14 @@ if (result === 'timeout') {
|
|
|
115
115
|
|
|
116
116
|
Navigates the folder structure and retrieves an item by path.
|
|
117
117
|
|
|
118
|
+
> **A single-segment path is not a path lookup.** `getItemByPath(['Files'])` ignores
|
|
119
|
+
> the path and runs a tenant-wide name search across folders, dashboards, sheets,
|
|
120
|
+
> dimension tables and variables, capped at 20 results. The name match is exact, so
|
|
121
|
+
> "Files Overview" is harmless — but it throws when a second item is named exactly
|
|
122
|
+
> "Files" anywhere in the tenant, and it silently misses the real folder when 20
|
|
123
|
+
> other items share the name as a prefix. For a top-level folder, list the root with
|
|
124
|
+
> `folders.listItemsBatch([{ id: null }])` and match the name yourself.
|
|
125
|
+
|
|
118
126
|
```typescript
|
|
119
127
|
// Get the "Reports" folder in "Finance"
|
|
120
128
|
const item = await client.getItemByPath(['Finance', 'Reports']);
|
|
@@ -251,7 +259,11 @@ Saves an Arquero table as a CSV file in Farseer.
|
|
|
251
259
|
|
|
252
260
|
```typescript
|
|
253
261
|
const data = aq.table({ A: [1, 2, 3], B: [4, 5, 6] });
|
|
254
|
-
|
|
262
|
+
|
|
263
|
+
// "Finance" is top-level, so list the root and match it — see the note on
|
|
264
|
+
// getItemByPath above for why a single-segment path is not a path lookup.
|
|
265
|
+
const root = await client.folders.listItemsBatch([{ id: null }]);
|
|
266
|
+
const folder = root[0].items.find((i) => i.name === 'Finance');
|
|
255
267
|
|
|
256
268
|
await client.data.saveToCsvFarseerFile(data, 'output.csv', folder.id);
|
|
257
269
|
```
|