farseer-cli 1.18.0 → 1.20.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 +33 -10
- package/dist/commands/app.js +42 -3
- package/dist/commands/app.js.map +1 -2
- package/dist/commands/apps.js.map +0 -1
- package/dist/commands/cells.js +120 -85
- package/dist/commands/cells.js.map +1 -2
- package/dist/commands/code.js.map +0 -1
- package/dist/commands/config.js.map +0 -1
- package/dist/commands/dashboards.js +246 -12
- package/dist/commands/dashboards.js.map +1 -2
- package/dist/commands/diff.js.map +0 -1
- package/dist/commands/dimensions.js +52 -27
- package/dist/commands/dimensions.js.map +1 -2
- package/dist/commands/docs.js +82 -0
- package/dist/commands/docs.js.map +6 -0
- package/dist/commands/files.js +49 -0
- package/dist/commands/files.js.map +2 -3
- package/dist/commands/folders.js +76 -0
- package/dist/commands/folders.js.map +6 -0
- package/dist/commands/formula.js +38 -30
- package/dist/commands/formula.js.map +1 -2
- package/dist/commands/install.js +32 -30
- package/dist/commands/install.js.map +2 -3
- package/dist/commands/list.js.map +0 -1
- package/dist/commands/login.js +3 -3
- package/dist/commands/login.js.map +1 -2
- package/dist/commands/logout.js.map +0 -1
- package/dist/commands/mcp-server.js.map +0 -1
- package/dist/commands/model.js +30 -5
- package/dist/commands/model.js.map +2 -3
- package/dist/commands/pipeline.js.map +0 -1
- package/dist/commands/pull.js +1 -1
- package/dist/commands/pull.js.map +1 -2
- package/dist/commands/push.js +6 -4
- package/dist/commands/push.js.map +1 -2
- package/dist/commands/refresh.js.map +0 -1
- package/dist/commands/run.js.map +0 -1
- package/dist/commands/sheets.js +289 -52
- package/dist/commands/sheets.js.map +1 -2
- package/dist/commands/skills.js +157 -0
- package/dist/commands/skills.js.map +6 -0
- package/dist/commands/status.js.map +0 -1
- package/dist/commands/tool.js.map +0 -1
- package/dist/commands/variables.js +246 -82
- package/dist/commands/variables.js.map +1 -2
- package/dist/commands/whoami.js.map +0 -1
- package/dist/index.js +117 -23
- package/dist/index.js.map +1 -2
- package/dist/mcp/index.js.map +0 -1
- package/dist/mcp/prompts/workflows.js.map +0 -1
- package/dist/mcp/resources/documentation.js +19 -12
- package/dist/mcp/resources/documentation.js.map +1 -2
- package/dist/mcp/server.js.map +0 -1
- package/dist/mcp/skills.js.map +0 -1
- package/dist/mcp/tools/appTools.js +1 -7
- package/dist/mcp/tools/appTools.js.map +1 -2
- package/dist/mcp/tools/authTools.js +1 -1
- package/dist/mcp/tools/authTools.js.map +1 -2
- package/dist/mcp/tools/cellTools.js +6 -19
- package/dist/mcp/tools/cellTools.js.map +1 -2
- package/dist/mcp/tools/dashboardTools.js +30 -412
- package/dist/mcp/tools/dashboardTools.js.map +2 -3
- package/dist/mcp/tools/dataTools.js +15 -146
- package/dist/mcp/tools/dataTools.js.map +1 -2
- package/dist/mcp/tools/folderTools.js +12 -78
- package/dist/mcp/tools/folderTools.js.map +1 -2
- package/dist/mcp/tools/modelTools.js +23 -372
- package/dist/mcp/tools/modelTools.js.map +1 -2
- package/dist/mcp/tools/pipelineContract.js +5 -1
- package/dist/mcp/tools/pipelineContract.js.map +1 -2
- package/dist/mcp/tools/pipelineTools.js.map +0 -1
- package/dist/mcp/tools/runTools.js +8 -69
- package/dist/mcp/tools/runTools.js.map +1 -2
- package/dist/mcp/tools/sheetTools.js +14 -264
- package/dist/mcp/tools/sheetTools.js.map +1 -2
- package/dist/mcp/tools/syncTools.js +7 -3
- package/dist/mcp/tools/syncTools.js.map +1 -2
- package/dist/mcp/utils/helpers.js.map +0 -1
- package/dist/mcp/utils/launchPin.js.map +0 -1
- package/dist/mcp/utils/operationResponse.js +41 -0
- package/dist/mcp/utils/operationResponse.js.map +6 -0
- package/dist/mcp/utils/registerTool.js.map +0 -1
- package/dist/mcp/utils/session.js.map +0 -1
- package/dist/mcp/utils/tenantPin.js.map +0 -1
- package/dist/operations/cells.js +444 -0
- package/dist/operations/cells.js.map +6 -0
- package/dist/operations/dashboards.js +357 -0
- package/dist/operations/dashboards.js.map +6 -0
- package/dist/operations/data.js +206 -0
- package/dist/operations/data.js.map +6 -0
- package/dist/operations/errors.js +64 -0
- package/dist/operations/errors.js.map +6 -0
- package/dist/operations/exportModel.js +59 -0
- package/dist/operations/exportModel.js.map +6 -0
- package/dist/operations/folderPath.js +128 -0
- package/dist/operations/folderPath.js.map +6 -0
- package/dist/operations/folders.js +80 -0
- package/dist/operations/folders.js.map +6 -0
- package/dist/operations/install.js +109 -0
- package/dist/operations/install.js.map +6 -0
- package/dist/operations/model.js +271 -0
- package/dist/operations/model.js.map +6 -0
- package/dist/operations/sheets.js +428 -0
- package/dist/operations/sheets.js.map +6 -0
- package/dist/pipeline/compatibility.js.map +0 -1
- package/dist/pipeline/connect.js.map +0 -1
- package/dist/pipeline/create.js.map +0 -1
- package/dist/pipeline/errors.js.map +0 -1
- package/dist/pipeline/failStep.js +43 -0
- package/dist/pipeline/failStep.js.map +6 -0
- package/dist/pipeline/generated-reference.json +25 -13
- package/dist/pipeline/guide.js.map +0 -1
- package/dist/pipeline/init.js.map +0 -1
- package/dist/pipeline/operations.js.map +0 -1
- package/dist/pipeline/query.js.map +0 -1
- package/dist/pipeline/queryDownloads.js.map +0 -1
- package/dist/pipeline/queryWorker.js +3 -1
- package/dist/pipeline/queryWorker.js.map +1 -2
- package/dist/pipeline/readiness.js.map +0 -1
- package/dist/pipeline/reference.js.map +0 -1
- package/dist/pipeline/requests.js +3 -32
- package/dist/pipeline/requests.js.map +1 -2
- package/dist/pipeline/runArguments.js.map +0 -1
- package/dist/pipeline/runtime.js.map +0 -1
- package/dist/pipeline/service.js +46 -2
- package/dist/pipeline/service.js.map +1 -2
- package/dist/services/appSyncService.js +59 -9
- package/dist/services/appSyncService.js.map +1 -2
- package/dist/services/apps.js +10 -0
- package/dist/services/apps.js.map +1 -2
- package/dist/services/authErrors.js.map +0 -1
- package/dist/services/codefirst/api.js +38 -5
- package/dist/services/codefirst/api.js.map +1 -2
- package/dist/services/codefirst/binaryDisk.js.map +0 -1
- package/dist/services/codefirst/byteHashes.js +5 -0
- package/dist/services/codefirst/byteHashes.js.map +1 -2
- package/dist/services/codefirst/documents.js +41 -15
- package/dist/services/codefirst/documents.js.map +1 -2
- package/dist/services/codefirst/layoutBinaryProjection.js +24 -13
- package/dist/services/codefirst/layoutBinaryProjection.js.map +1 -2
- package/dist/services/codefirst/layoutCompose.js +44 -38
- package/dist/services/codefirst/layoutCompose.js.map +1 -2
- package/dist/services/codefirst/layoutCore.js +14 -1
- package/dist/services/codefirst/layoutCore.js.map +1 -2
- package/dist/services/codefirst/layoutPaths.js +80 -4
- package/dist/services/codefirst/layoutPaths.js.map +1 -2
- package/dist/services/codefirst/layoutProjection.js +73 -39
- package/dist/services/codefirst/layoutProjection.js.map +1 -2
- package/dist/services/codefirst/layoutReadback.js +357 -130
- package/dist/services/codefirst/layoutReadback.js.map +2 -3
- package/dist/services/codefirst/layoutReadbackPlacement.js +94 -57
- package/dist/services/codefirst/layoutReadbackPlacement.js.map +2 -3
- package/dist/services/codefirst/layoutReceipt.js +283 -243
- package/dist/services/codefirst/layoutReceipt.js.map +2 -3
- package/dist/services/codefirst/layoutScan.js +208 -110
- package/dist/services/codefirst/layoutScan.js.map +1 -2
- package/dist/services/codefirst/output.js +76 -10
- package/dist/services/codefirst/output.js.map +1 -2
- package/dist/services/codefirst/types.js.map +0 -1
- package/dist/services/codefirst/workflow.js +65 -29
- package/dist/services/codefirst/workflow.js.map +2 -3
- package/dist/services/codefirst/workspace.js.map +0 -1
- package/dist/services/codefirst/workspaceLock.js.map +0 -1
- package/dist/services/codefirst/workspaceRoot.js +2 -1
- package/dist/services/codefirst/workspaceRoot.js.map +1 -2
- package/dist/services/configService.js.map +0 -1
- package/dist/services/credentials.js.map +0 -1
- package/dist/services/farseerService.js +31 -7
- package/dist/services/farseerService.js.map +1 -2
- package/dist/services/httpError.js.map +0 -1
- package/dist/services/modelExport.js.map +0 -1
- package/dist/services/organisation.js.map +0 -1
- package/dist/services/preflight.js.map +0 -1
- package/dist/services/realms.js.map +0 -1
- package/dist/services/syncService.js +3 -3
- package/dist/services/syncService.js.map +1 -2
- package/dist/skills/bundled.js +106 -0
- package/dist/skills/bundled.js.map +6 -0
- package/dist/skills/install.js +257 -0
- package/dist/skills/install.js.map +6 -0
- package/dist/skills/pipeline.js +10 -18
- package/dist/skills/pipeline.js.map +1 -2
- package/dist/utils/agentSandbox.js +1 -1
- package/dist/utils/agentSandbox.js.map +0 -1
- package/dist/utils/cliOptions.js.map +0 -1
- package/dist/utils/constants.js.map +0 -1
- package/dist/utils/entityResolver.js +72 -25
- package/dist/utils/entityResolver.js.map +1 -2
- package/dist/utils/errorFormatter.js +72 -11
- package/dist/utils/errorFormatter.js.map +1 -2
- package/dist/utils/fileLogger.js.map +0 -1
- package/dist/utils/fileValidation.js.map +0 -1
- package/dist/utils/folderMatch.js.map +0 -1
- package/dist/utils/formulaFilters.js +11 -2
- package/dist/utils/formulaFilters.js.map +1 -2
- package/dist/utils/helpers.js.map +0 -1
- package/dist/utils/logger.js.map +0 -1
- package/dist/utils/nameResolver.js.map +0 -1
- package/dist/utils/operationCli.js +102 -0
- package/dist/utils/operationCli.js.map +6 -0
- package/dist/utils/packageManager.js.map +0 -1
- package/dist/utils/syncReporting.js.map +0 -1
- package/dist/utils/syncScope.js.map +0 -1
- package/dist/utils/updateCheck.js.map +0 -1
- package/dist/utils/variableValues.js.map +0 -1
- package/dist/utils/workspace.js.map +0 -1
- package/docs/cli-guide.md +182 -2
- package/docs/import-workflows.md +14 -14
- package/docs/new-app-template.md +1 -1
- package/docs/pipeline-client-guide.md +1 -1
- package/docs/pipeline-reference.md +304 -9
- package/docs/troubleshooting.md +18 -0
- package/package.json +2 -2
- package/skills/farseer-analysis/SKILL.md +132 -0
- package/skills/farseer-app-dev/SKILL.md +131 -0
- package/skills/farseer-app-dev/assignments.md +185 -0
- package/skills/farseer-app-dev/farseer-client-api-guide.md +907 -0
- package/skills/farseer-app-dev/farseer-client-release-notes.md +212 -0
- package/skills/farseer-app-dev/working-patterns.md +876 -0
- package/skills/farseer-authenticate-to-tenant/SKILL.md +60 -0
- package/skills/farseer-authenticate-to-tenant/app-authentication.md +91 -0
- package/skills/farseer-author-import-job/SKILL.md +114 -0
- package/skills/farseer-author-import-job/cell-writes.md +530 -0
- package/skills/farseer-author-import-job/deploying-a-farseer-app.md +383 -0
- package/skills/farseer-author-import-job/import-job-pattern.md +232 -0
- package/skills/farseer-build-model/SKILL.md +122 -0
- package/skills/farseer-build-model/formula-grain-alignment.md +612 -0
- package/skills/farseer-build-model/naming-conventions.md +435 -0
- package/skills/farseer-build-model/sparse-formulas-pattern.md +330 -0
- package/skills/farseer-build-pipeline/SKILL.md +190 -0
- package/skills/farseer-build-pipeline/erp-sales/README.md +108 -0
- package/skills/farseer-build-pipeline/erp-sales/erp-sales-etl/Models/bronze/erp_sales_invoice_lines.yaml +23 -0
- package/skills/farseer-build-pipeline/erp-sales/erp-sales-etl/Models/bronze/erp_sales_invoice_lines_raw.yaml +23 -0
- package/skills/farseer-build-pipeline/erp-sales/erp-sales-etl/Models/bronze/erp_sales_item_product_map.yaml +17 -0
- package/skills/farseer-build-pipeline/erp-sales/erp-sales-etl/Models/bronze/erp_sales_item_product_map_raw.yaml +11 -0
- package/skills/farseer-build-pipeline/erp-sales/erp-sales-etl/Models/gold/erp_sales_cells.yaml +40 -0
- package/skills/farseer-build-pipeline/erp-sales/erp-sales-etl/Models/silver/erp_sales_lines.yaml +35 -0
- package/skills/farseer-build-pipeline/erp-sales/erp-sales-etl/Models/silver/erp_sales_recon.yaml +43 -0
- package/skills/farseer-build-pipeline/erp-sales/erp-sales-etl/Models/silver/erp_sales_unmapped_items.yaml +28 -0
- package/skills/farseer-build-pipeline/erp-sales/erp-sales-etl/main.py +49 -0
- package/skills/farseer-build-pipeline/erp-sales/erp-sales-load/Models/in/erp_sales_cells.yaml +17 -0
- package/skills/farseer-build-pipeline/erp-sales/erp-sales-load/Models/in/erp_sales_cells_raw.yaml +14 -0
- package/skills/farseer-build-pipeline/erp-sales/erp-sales-load/Models/load/erp_sales_to_model.yaml +47 -0
- package/skills/farseer-build-pipeline/erp-sales/erp-sales-load/main.py +44 -0
- package/skills/farseer-build-pipeline/erp-sales/item_to_product.csv +5 -0
- package/skills/farseer-build-pipeline/pipeline-app-failure-report-pattern.md +103 -0
- package/skills/farseer-build-pipeline/pipeline-source-encoding.md +68 -0
- package/skills/farseer-dashboards/SKILL.md +40 -0
- package/skills/farseer-formulas/SKILL.md +165 -0
- package/skills/farseer-help-center/SKILL.md +66 -0
- package/skills/farseer-model/SKILL.md +119 -0
- package/skills/farseer-modify-model/SKILL.md +158 -0
- package/skills/farseer-modify-model/model-validation-pattern.md +251 -0
- package/skills/farseer-optimize-model/SKILL.md +314 -0
- package/skills/farseer-optimize-model/stats-dump.ts +139 -0
- package/skills/farseer-pnl/SKILL.md +220 -0
- package/skills/farseer-review-model/SKILL.md +172 -0
- package/skills/farseer-run-apps/SKILL.md +102 -0
- package/skills/pipeline-authoring/SKILL.md +7 -5
- package/skills/pipeline-authoring/practices.md +21 -8
- package/dist/services/agentApprovalFetch.js +0 -86
- package/dist/services/agentApprovalFetch.js.map +0 -7
|
@@ -20,6 +20,8 @@ var errorFormatter_exports = {};
|
|
|
20
20
|
__export(errorFormatter_exports, {
|
|
21
21
|
extractHttpErrorDetails: () => extractHttpErrorDetails,
|
|
22
22
|
formatClientError: () => formatClientError,
|
|
23
|
+
formatSyncError: () => formatSyncError,
|
|
24
|
+
splitSyncHints: () => splitSyncHints,
|
|
23
25
|
toError: () => toError
|
|
24
26
|
});
|
|
25
27
|
module.exports = __toCommonJS(errorFormatter_exports);
|
|
@@ -39,13 +41,33 @@ async function readResponseBody(response) {
|
|
|
39
41
|
return `<failed to read response body: ${reason}>`;
|
|
40
42
|
}
|
|
41
43
|
}
|
|
44
|
+
function decodeValidationErrors(header) {
|
|
45
|
+
if (typeof header !== "string" || !header) return void 0;
|
|
46
|
+
try {
|
|
47
|
+
const parsed = JSON.parse(Buffer.from(header, "base64").toString("utf-8"));
|
|
48
|
+
if (!Array.isArray(parsed)) return void 0;
|
|
49
|
+
const errors = parsed.filter(
|
|
50
|
+
(e) => typeof e?.path === "string" && typeof e?.message === "string"
|
|
51
|
+
);
|
|
52
|
+
return errors.length > 0 ? errors : void 0;
|
|
53
|
+
} catch {
|
|
54
|
+
return void 0;
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
function describeRefusals(errors) {
|
|
58
|
+
const clean = (text) => text.replace(/[\u0000-\u001f\u007f-\u009f]/g, "").trim();
|
|
59
|
+
return (errors ?? []).map((e) => `
|
|
60
|
+
${clean(e.path) || "(request)"}: ${clean(e.message)}`).join("");
|
|
61
|
+
}
|
|
42
62
|
async function extractHttpErrorDetails(error) {
|
|
43
63
|
if (looksLikeFetchResponse(error)) {
|
|
64
|
+
const validationErrors = decodeValidationErrors(error.headers?.get?.("x-validation-errors"));
|
|
44
65
|
return {
|
|
45
66
|
status: error.status,
|
|
46
67
|
statusText: error.statusText,
|
|
47
68
|
body: await readResponseBody(error),
|
|
48
|
-
url: error.url
|
|
69
|
+
url: error.url,
|
|
70
|
+
...validationErrors && { validationErrors }
|
|
49
71
|
};
|
|
50
72
|
}
|
|
51
73
|
if (looksLikeAxiosError(error)) {
|
|
@@ -54,12 +76,14 @@ async function extractHttpErrorDetails(error) {
|
|
|
54
76
|
if (data !== void 0 && data !== null) {
|
|
55
77
|
body = typeof data === "string" ? data : safeStringify(data);
|
|
56
78
|
}
|
|
79
|
+
const validationErrors = decodeValidationErrors(error.response?.headers?.["x-validation-errors"]);
|
|
57
80
|
return {
|
|
58
81
|
status: error.response?.status,
|
|
59
82
|
statusText: error.response?.statusText,
|
|
60
83
|
body,
|
|
61
84
|
url: error.config?.url,
|
|
62
|
-
method: error.config?.method
|
|
85
|
+
method: error.config?.method,
|
|
86
|
+
...validationErrors && { validationErrors }
|
|
63
87
|
};
|
|
64
88
|
}
|
|
65
89
|
return null;
|
|
@@ -104,8 +128,15 @@ const FOLDER_TYPE_REJECTION_HINT = [
|
|
|
104
128
|
" \u2022 If you created this folder with an older CLI (\u22641.3.1), it has empty allowedTypes;",
|
|
105
129
|
" delete it via UI and let the new CLI recreate it (it now sends `null` for inheritance)."
|
|
106
130
|
].join("\n");
|
|
107
|
-
|
|
108
|
-
|
|
131
|
+
const EMPTY_FOLDER_SUBFOLDER_HINT = [
|
|
132
|
+
"",
|
|
133
|
+
"The new folder's parent has empty allowedTypes (e.g. a folder created by CLI \u22641.3.1), so it refuses subfolders.",
|
|
134
|
+
" \u2022 If an older CLI created it, delete it via UI and let the new CLI recreate it, or use a different folder."
|
|
135
|
+
].join("\n");
|
|
136
|
+
function folderRejectionHint(body) {
|
|
137
|
+
if (/Invalid parent\s*[-–—]\s*item type 'FARSEER_FILE'/i.test(body)) return FOLDER_TYPE_REJECTION_HINT;
|
|
138
|
+
const emptyFolderRefusedSubfolder = /Invalid parent\s*[-–—]\s*item type 'FOLDER'.*\(allowed types:\s*\)/i;
|
|
139
|
+
return emptyFolderRefusedSubfolder.test(body) ? EMPTY_FOLDER_SUBFOLDER_HINT : "";
|
|
109
140
|
}
|
|
110
141
|
async function formatClientError(error) {
|
|
111
142
|
const details = await extractHttpErrorDetails(error);
|
|
@@ -115,15 +146,16 @@ async function formatClientError(error) {
|
|
|
115
146
|
if (details.statusText) parts.push(details.statusText);
|
|
116
147
|
const left = parts.join(" ").trim();
|
|
117
148
|
const body = (details.body || "").trim();
|
|
118
|
-
const
|
|
119
|
-
const
|
|
120
|
-
const
|
|
121
|
-
if (left && body) return `${left}: ${body}${
|
|
122
|
-
if (left) return `${left}${
|
|
123
|
-
if (body) return body
|
|
149
|
+
const refused = describeRefusals(details.validationErrors);
|
|
150
|
+
const hint = details.status === 400 ? folderRejectionHint(body) : "";
|
|
151
|
+
const tail = refused || hint;
|
|
152
|
+
if (left && body) return `${left}: ${body}${tail}`;
|
|
153
|
+
if (left) return `${left}${tail}`;
|
|
154
|
+
if (body) return `${body}${tail}`;
|
|
124
155
|
}
|
|
125
156
|
if (error instanceof Error) {
|
|
126
|
-
|
|
157
|
+
const message = error.message || error.name || "Unknown error";
|
|
158
|
+
return error instanceof TypeError ? `${message}${describeNetworkCause(error.cause)}` : message;
|
|
127
159
|
}
|
|
128
160
|
if (error && typeof error === "object") {
|
|
129
161
|
const asString = safeStringify(error);
|
|
@@ -131,6 +163,33 @@ async function formatClientError(error) {
|
|
|
131
163
|
}
|
|
132
164
|
return String(error);
|
|
133
165
|
}
|
|
166
|
+
function describeNetworkCause(cause) {
|
|
167
|
+
if (!cause || typeof cause !== "object") return "";
|
|
168
|
+
const { code, message } = cause;
|
|
169
|
+
const text = typeof message === "string" ? message.trim() : "";
|
|
170
|
+
const codeText = typeof code === "string" ? code : "";
|
|
171
|
+
const detail = codeText && !text.includes(codeText) ? [codeText, text].filter(Boolean).join(" ") : text;
|
|
172
|
+
return detail ? ` (${detail})` : "";
|
|
173
|
+
}
|
|
174
|
+
async function formatSyncError(error) {
|
|
175
|
+
const message = await formatClientError(error);
|
|
176
|
+
return isOpaqueBadRequestEnding(message) ? `${message}${OPAQUE_BAD_REQUEST_HINT}` : message;
|
|
177
|
+
}
|
|
178
|
+
const SYNC_HINTS = [OPAQUE_BAD_REQUEST_HINT, FOLDER_TYPE_REJECTION_HINT, EMPTY_FOLDER_SUBFOLDER_HINT];
|
|
179
|
+
function splitSyncHints(reasons) {
|
|
180
|
+
const hints = /* @__PURE__ */ new Set();
|
|
181
|
+
const messages = reasons.map((reason) => {
|
|
182
|
+
const hint = SYNC_HINTS.find((candidate) => reason.endsWith(candidate));
|
|
183
|
+
if (!hint) return reason;
|
|
184
|
+
hints.add(hint);
|
|
185
|
+
return reason.slice(0, -hint.length);
|
|
186
|
+
});
|
|
187
|
+
return { messages, hints: [...hints] };
|
|
188
|
+
}
|
|
189
|
+
function isOpaqueBadRequestEnding(message) {
|
|
190
|
+
const start = message.lastIndexOf("{");
|
|
191
|
+
return start >= 0 && isOpaqueBadRequestBody(message.slice(start)) && /BadRequest/.test(message.slice(start));
|
|
192
|
+
}
|
|
134
193
|
async function toError(error, prefix) {
|
|
135
194
|
if (error instanceof Error && !prefix) return error;
|
|
136
195
|
const message = await formatClientError(error);
|
|
@@ -147,6 +206,8 @@ async function toError(error, prefix) {
|
|
|
147
206
|
0 && (module.exports = {
|
|
148
207
|
extractHttpErrorDetails,
|
|
149
208
|
formatClientError,
|
|
209
|
+
formatSyncError,
|
|
210
|
+
splitSyncHints,
|
|
150
211
|
toError
|
|
151
212
|
});
|
|
152
213
|
//# sourceMappingURL=errorFormatter.js.map
|
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/utils/errorFormatter.ts"],
|
|
4
|
-
"
|
|
5
|
-
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAyBA,SAAS,uBAAuB,OAM9B;AACE,SACI,CAAC,CAAC,SACF,OAAO,UAAU,YACjB,YAAY,SACZ,OAAQ,MAA8B,WAAW,YACjD,OAAQ,MAA6B,SAAS;AAEtD;AAEA,SAAS,oBAAoB,OAK3B;AACE,SAAO,CAAC,CAAC,SAAS,OAAO,UAAU,YAAa,MAAqC,iBAAiB;AAC1G;AAEA,eAAe,iBAAiB,UAGZ;AAChB,QAAM,SAAS,SAAS,QAAQ,SAAS,MAAM,IAAI;AACnD,MAAI;AACA,UAAM,OAAO,MAAM,OAAO,OAAO;AACjC,WAAO,QAAQ;AAAA,EACnB,SAAS,KAAK;AAKV,UAAM,SAAS,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;AAC9D,WAAO,kCAAkC,MAAM;AAAA,EACnD;AACJ;AAMA,eAAsB,wBAAwB,OAAkD;AAC5F,MAAI,uBAAuB,KAAK,GAAG;AAC/B,WAAO;AAAA,MACH,QAAQ,MAAM;AAAA,MACd,YAAY,MAAM;AAAA,MAClB,MAAM,MAAM,iBAAiB,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,YAAY,GAAG;AACrC,SAAO,SAAS,KAAK,uBAAuB,QAAQ,MAAM,KAAK,CAAC,KAAK,aAAa,KAAK,QAAQ,MAAM,KAAK,CAAC;AAC/G;AAQA,eAAsB,QAAQ,OAAgB,QAAiC;AAC3E,MAAI,iBAAiB,SAAS,CAAC,OAAQ,QAAO;AAC9C,QAAM,UAAU,MAAM,kBAAkB,KAAK;AAC7C,QAAM,OAAO,SAAS,GAAG,MAAM,KAAK,OAAO,KAAK;AAEhD,MAAI;AACA,WAAO,IAAI,MAAM,MAAM,EAAE,OAAO,MAAe,CAAC;AAAA,EACpD,QAAQ;AACJ,UAAM,UAAU,IAAI,MAAM,IAAI;AAC9B,IAAC,QAAwC,QAAQ;AACjD,WAAO;AAAA,EACX;AACJ;",
|
|
6
5
|
"names": []
|
|
7
6
|
}
|
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/utils/fileLogger.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * File Logger\n *\n * Writes debug logs to ~/.farseer/logs/ for diagnostics.\n * On error, prints the log path so users can share the file for support.\n *\n * Log rotation: keeps last 10 log files, deletes oldest on startup.\n * Format: one JSON line per entry (JSONL) for easy parsing.\n *\n * Usage:\n * import { fileLogger } from './utils/fileLogger';\n * fileLogger.init(); // Call once at startup\n * fileLogger.log('http', { method: 'GET', url: '...' });\n * fileLogger.error('push', error);\n * fileLogger.getLogPath(); // Returns current log file path\n */\n\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport * as os from 'os';\nimport { CLI_VERSION } from './constants';\n\nconst LOG_DIR = path.join(os.homedir(), '.farseer', 'logs');\nconst MAX_LOG_FILES = 10;\n\nlet logFilePath: string | null = null;\nlet logStream: fs.WriteStream | null = null;\n\n/**\n * Create a timestamped log file path.\n */\nfunction createLogPath(): string {\n const ts = new Date().toISOString().replace(/[:.]/g, '-');\n return path.join(LOG_DIR, `farseer-${ts}.log`);\n}\n\n/**\n * Remove old log files, keeping only the newest MAX_LOG_FILES.\n */\nfunction rotateLogFiles(): void {\n try {\n const files = fs\n .readdirSync(LOG_DIR)\n .filter((f) => f.startsWith('farseer-') && f.endsWith('.log'))\n .sort()\n .reverse();\n\n for (const file of files.slice(MAX_LOG_FILES)) {\n try {\n fs.unlinkSync(path.join(LOG_DIR, file));\n } catch {\n // Ignore deletion errors\n }\n }\n } catch {\n // Log dir might not exist yet\n }\n}\n\n/**\n * Write a structured log entry.\n */\nfunction writeEntry(level: string, category: string, data?: unknown): void {\n if (!logStream) return;\n try {\n const entry = {\n ts: new Date().toISOString(),\n level,\n cat: category,\n ...(data !== undefined ? { data } : {}),\n };\n logStream.write(JSON.stringify(entry) + '\\n');\n } catch {\n // Never throw from logger\n }\n}\n\n/**\n * Write a log entry synchronously (bypasses stream buffering).\n * Used in crash handlers where process.exit follows immediately.\n */\nfunction writeSyncEntry(level: string, category: string, data?: unknown): void {\n if (!logFilePath) return;\n try {\n const entry = {\n ts: new Date().toISOString(),\n level,\n cat: category,\n ...(data !== undefined ? { data } : {}),\n };\n fs.appendFileSync(logFilePath, JSON.stringify(entry) + '\\n');\n } catch {\n // Never throw from logger\n }\n}\n\n/**\n * Extract error details for logging.\n *\n * Handles:\n * - Error instances (including axios errors with .response)\n * - fetch Response objects thrown by farseer-client's generated runtime\n * - plain objects / primitives\n *\n * The cause chain is included when present so nested errors remain inspectable.\n */\nfunction serializeError(error: unknown): Record<string, unknown> {\n if (error instanceof Error) {\n const result: Record<string, unknown> = {\n name: error.name,\n message: error.message,\n stack: error.stack,\n };\n // Axios errors\n if ('response' in error) {\n const e = error as any;\n result.status = e.response?.status;\n result.statusText = e.response?.statusText;\n result.responseData = e.response?.data;\n result.url = e.config?.url;\n result.method = e.config?.method;\n }\n const cause = (error as Error & { cause?: unknown }).cause;\n if (cause !== undefined && cause !== error) {\n result.cause = serializeError(cause);\n }\n return result;\n }\n\n // fetch Response thrown by farseer-client \u2014 preserve status/url so the log\n // is useful even though we can't synchronously read the body here.\n if (\n error &&\n typeof error === 'object' &&\n typeof (error as { status?: unknown }).status === 'number' &&\n typeof (error as { text?: unknown }).text === 'function'\n ) {\n const resp = error as { status: number; statusText?: string; url?: string };\n return {\n kind: 'HttpResponse',\n status: resp.status,\n statusText: resp.statusText,\n url: resp.url,\n };\n }\n\n if (typeof error === 'object' && error !== null) {\n try {\n return JSON.parse(JSON.stringify(error));\n } catch {\n return { raw: String(error) };\n }\n }\n return { raw: String(error) };\n}\n\nlet initialized = false;\nlet crashHandlersInstalled = false;\nlet exitOnUnhandledRejection = true;\n\nexport const fileLogger = {\n /**\n * Initialize the file logger. Idempotent \u2014 safe to call multiple times.\n * Creates the log directory and file, writes session header.\n */\n init(): void {\n if (initialized) return;\n initialized = true;\n try {\n fs.mkdirSync(LOG_DIR, { recursive: true });\n rotateLogFiles();\n logFilePath = createLogPath();\n logStream = fs.createWriteStream(logFilePath, { flags: 'a' });\n\n // Write session header\n writeEntry('info', 'session', {\n version: CLI_VERSION,\n node: process.version,\n platform: os.platform(),\n arch: os.arch(),\n argv: process.argv.slice(2),\n cwd: process.cwd(),\n pid: process.pid,\n });\n } catch {\n // If we can't create logs, continue without file logging\n logFilePath = null;\n logStream = null;\n }\n },\n\n /**\n * Log an informational entry.\n */\n log(category: string, data?: unknown): void {\n writeEntry('info', category, data);\n },\n\n /**\n * Log a warning.\n */\n warn(category: string, data?: unknown): void {\n writeEntry('warn', category, data);\n },\n\n /**\n * Log an error with full details.\n * Uses async stream write (same as other entries) for correct ordering.\n * Only crash handlers use writeSyncEntry where process.exit follows immediately.\n */\n error(category: string, error: unknown, context?: Record<string, unknown>): void {\n writeEntry('error', category, {\n ...serializeError(error),\n ...(context || {}),\n });\n },\n\n /**\n * Log an HTTP request/response (for debug).\n */\n http(method: string, url: string, status?: number, durationMs?: number, error?: unknown): void {\n const data: Record<string, unknown> = { method, url };\n if (status !== undefined) data.status = status;\n if (durationMs !== undefined) data.durationMs = durationMs;\n if (error) data.error = serializeError(error);\n writeEntry(error ? 'error' : 'info', 'http', data);\n },\n\n /**\n * Log an MCP tool call.\n */\n toolCall(toolName: string, params: unknown, success: boolean, durationMs?: number, error?: unknown): void {\n const data: Record<string, unknown> = { tool: toolName, params, success };\n if (durationMs !== undefined) data.durationMs = durationMs;\n if (error) data.error = serializeError(error);\n writeEntry(success ? 'info' : 'error', 'mcp-tool', data);\n },\n\n /**\n * Get the current log file path (to tell user where to find it).\n */\n getLogPath(): string | null {\n return logFilePath;\n },\n\n /**\n * Close the log stream. Call on process exit.\n */\n close(): void {\n if (logStream) {\n logStream.end();\n logStream = null;\n }\n },\n\n /**\n * Install crash handlers that write to the log before exit. Idempotent.\n *\n * `exitOnRejection` is the difference between the two surfaces. A command is\n * one process for one operation: a rejection it did not catch means the\n * operation did not happen, and a shell that reads the exit code has to be\n * told that. A server is one process for many operations, each of which\n * already answers its own caller, so ending it would take out a session over\n * something that has been reported.\n *\n * The listeners are registered once, but the policy is taken from the latest\n * call and read when a rejection arrives: the CLI entry point installs these\n * before it knows which command it is running, and the MCP server, which\n * must not exit, installs them again once it does.\n */\n installCrashHandlers({ exitOnRejection = true }: { exitOnRejection?: boolean } = {}): void {\n exitOnUnhandledRejection = exitOnRejection;\n if (crashHandlersInstalled) return;\n crashHandlersInstalled = true;\n process.on('uncaughtException', (err) => {\n // Use sync write \u2014 stream may not flush before process.exit\n writeSyncEntry('fatal', 'crash', {\n source: 'uncaughtException',\n ...serializeError(err),\n });\n if (logFilePath) {\n console.error(`\\nCrash log written to: ${logFilePath}`);\n }\n process.exit(1);\n });\n\n process.on('unhandledRejection', (reason) => {\n // Pass reason directly \u2014 serializeError handles Error, objects, and primitives.\n // Wrapping in new Error(String(reason)) would lose structured fields on plain objects.\n writeSyncEntry('fatal', 'crash', {\n source: 'unhandledRejection',\n ...serializeError(reason),\n });\n if (!exitOnUnhandledRejection) {\n return;\n }\n // Node has ended the process on these since v15, and registering this\n // handler is what stops it. Without the exit, a command whose await\n // escaped its try block prints nothing and reports success.\n console.error(`\\nCommand failed: ${reason instanceof Error ? reason.message : String(reason)}`);\n if (logFilePath) {\n console.error(`Crash log written to: ${logFilePath}`);\n }\n process.exit(1);\n });\n },\n};\n"],
|
|
5
4
|
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAiBA,SAAoB;AACpB,WAAsB;AACtB,SAAoB;AACpB,uBAA4B;AAE5B,MAAM,UAAU,KAAK,KAAK,GAAG,QAAQ,GAAG,YAAY,MAAM;AAC1D,MAAM,gBAAgB;AAEtB,IAAI,cAA6B;AACjC,IAAI,YAAmC;AAKvC,SAAS,gBAAwB;AAC7B,QAAM,MAAK,oBAAI,KAAK,GAAE,YAAY,EAAE,QAAQ,SAAS,GAAG;AACxD,SAAO,KAAK,KAAK,SAAS,WAAW,EAAE,MAAM;AACjD;AAKA,SAAS,iBAAuB;AAC5B,MAAI;AACA,UAAM,QAAQ,GACT,YAAY,OAAO,EACnB,OAAO,CAAC,MAAM,EAAE,WAAW,UAAU,KAAK,EAAE,SAAS,MAAM,CAAC,EAC5D,KAAK,EACL,QAAQ;AAEb,eAAW,QAAQ,MAAM,MAAM,aAAa,GAAG;AAC3C,UAAI;AACA,WAAG,WAAW,KAAK,KAAK,SAAS,IAAI,CAAC;AAAA,MAC1C,QAAQ;AAAA,MAER;AAAA,IACJ;AAAA,EACJ,QAAQ;AAAA,EAER;AACJ;AAKA,SAAS,WAAW,OAAe,UAAkB,MAAsB;AACvE,MAAI,CAAC,UAAW;AAChB,MAAI;AACA,UAAM,QAAQ;AAAA,MACV,KAAI,oBAAI,KAAK,GAAE,YAAY;AAAA,MAC3B;AAAA,MACA,KAAK;AAAA,MACL,GAAI,SAAS,SAAY,EAAE,KAAK,IAAI,CAAC;AAAA,IACzC;AACA,cAAU,MAAM,KAAK,UAAU,KAAK,IAAI,IAAI;AAAA,EAChD,QAAQ;AAAA,EAER;AACJ;AAMA,SAAS,eAAe,OAAe,UA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MAAM,yBAAyB,WAAW,EAAE;AAAA,MACxD;AACA,cAAQ,KAAK,CAAC;AAAA,IAClB,CAAC;AAAA,EACL;AACJ;",
|
|
6
5
|
"names": []
|
|
7
6
|
}
|
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/utils/fileValidation.ts"],
|
|
4
|
-
"sourcesContent": ["import * as path from 'path';\n\n/**\n * Pre-flight validation that mirrors the backend's Farseer Files rules so the\n * CLI can refuse a doomed upload locally \u2014 with an actionable message \u2014\n * instead of letting the user see a cryptic `HTTP 400 {\"code\":\"BadRequest\"}`\n * coming back from the API after the request is already in flight.\n *\n * Source of truth on the backend:\n * - Extension whitelist:\n * `backend/app/openapi/v3/services/farseerFileService.ts`\n * (FILE_EXTENSION_WHITELIST static + validateFileExtension())\n * - Name length: `backend/app/openapi/util/itemNodeNameUtil.ts`\n * (MAX_NAME_SIZE = 256, trim, non-empty)\n *\n * Keep this list in lockstep with the backend. If the backend adds an\n * extension, add it here so users stop seeing \"File type not allowed\" for\n * something that is actually allowed.\n */\n\nexport const BACKEND_EXTENSION_WHITELIST: ReadonlySet<string> = new Set([\n // Office / spreadsheets\n 'xls',\n 'xlsx',\n 'csv',\n 'pdf',\n 'docx',\n // Code (frontend / scripts)\n 'js',\n 'jsx',\n 'ts',\n 'tsx',\n // Code (Python)\n 'py',\n // Markup / config / data\n 'xml',\n 'json',\n 'yaml',\n 'yml',\n 'html',\n 'css',\n 'scss',\n 'md',\n 'txt',\n // Images\n 'jpg',\n 'jpeg',\n 'png',\n 'gif',\n 'svg',\n 'webp',\n // Archives / columnar data\n 'zip',\n 'parquet',\n]);\n\nexport const MAX_FILE_NAME_LENGTH = 256;\n\nexport interface ValidationFailure {\n filePath: string;\n reason: 'extension_not_allowed' | 'name_empty' | 'name_too_long' | 'empty_content' | 'unresolved_conflict_markers';\n detail: string;\n hint?: string;\n}\n\n/**\n * Detect git-style conflict markers left over from an unresolved\n * `merge_markers` pull. Pushing a file with these markers would upload\n * broken syntax to the backend (the file wouldn't compile / parse). The\n * patterns intentionally match the exact strings the CLI writes\n * (syncService.ts: MERGE_MARKER_*) so we don't false-positive on user\n * code that happens to contain `<<<<<<<` in some other context.\n *\n * We refuse on EITHER unique sentinel \u2014 the earlier \"require both\n * LOCAL and REMOTE\" gate let a partially-resolved file slip through\n * (user deleted only one half of the block). The `=======` separator\n * is intentionally NOT included: bare `=======` lines are common in\n * RST headings and ASCII tables, so flagging them would false-positive\n * on legitimate text content.\n */\nconst CONFLICT_MARKER_LOCAL = /^<<<<<<< LOCAL \\(your version\\)$/m;\nconst CONFLICT_MARKER_REMOTE = /^>>>>>>> REMOTE$/m;\n\n/**\n * Best-effort check for \"is this file content text we can safely splice\n * git-style merge markers into?\". Used to gate the `merge_markers`\n * conflict resolution: writing markers into a .png / .xlsx / .zip\n * corrupts the binary, and the .toString('utf-8') round-trip used by\n * the merge logic flips bytes silently.\n *\n * Two-step check:\n * 1. File extension allowlist \u2014 fast path, deterministic.\n * 2. Null-byte heuristic on the content \u2014 covers misnamed files\n * and unknown extensions.\n *\n * False negatives (binary that passes both checks) just write garbage\n * markers; push pre-flight then refuses to upload because the marker\n * pattern is mangled. False positives (text that trips null-byte) just\n * mean the user gets the keep_both fallback \u2014 annoying but safe.\n */\n// Symmetrical with BACKEND_EXTENSION_WHITELIST: only formats the user\n// can actually push end up here. .mjs / .cjs are technically text but\n// they're not on the backend whitelist (and not in DEFAULT_SCRIPT_EXTENSIONS),\n// so offering merge_markers for them would lead the user through a manual\n// resolve only to hit pre-flight rejection on push. Drop them to match\n// the pre-flight's reality.\nconst KNOWN_TEXT_EXTENSIONS: ReadonlySet<string> = new Set([\n '.ts',\n '.tsx',\n '.js',\n '.jsx',\n '.json',\n '.md',\n '.txt',\n '.html',\n '.css',\n '.scss',\n '.yaml',\n '.yml',\n '.xml',\n '.py',\n '.csv',\n]);\n\nexport function isLikelyTextFile(filePath: string, content?: Buffer): boolean {\n const ext = path.extname(filePath).toLowerCase();\n if (KNOWN_TEXT_EXTENSIONS.has(ext)) return true;\n if (!content) return false;\n // Sample first 8KB for a NUL byte. Binary formats (PDF, PNG, ZIP,\n // XLSX, \u2026) have one almost immediately; text files practically never.\n const slice = content.subarray(0, 8 * 1024);\n return !slice.includes(0);\n}\n\nexport function hasUnresolvedConflictMarkers(content: string | Buffer): boolean {\n const text = Buffer.isBuffer(content) ? content.toString('utf-8') : content;\n // OR (not AND) across the unique sentinels: a half-resolved file where\n // the user kept only the LOCAL or REMOTE marker still uploads broken\n // text. The `=======` separator is omitted on purpose \u2014 RST headings\n // and ASCII tables use bare `=======` lines and would false-positive.\n return CONFLICT_MARKER_LOCAL.test(text) || CONFLICT_MARKER_REMOTE.test(text);\n}\n\n/**\n * Same algorithm the backend uses (`tail(name.split('.'))`): split on `.`\n * and take the last segment, lowercased. This means:\n * - `foo.ts` \u2192 `ts`\n * - `Foo.TS` \u2192 `ts` (case-insensitive \u2014 backend folds case before lookup)\n * - `.gitignore` \u2192 `gitignore` (rejected, not in whitelist)\n * - `Makefile` \u2192 `makefile` (rejected \u2014 no `.`, returns the basename lowercased)\n * - `archive.tar.gz` \u2192 `gz` (rejected)\n */\nexport function getBackendExtension(fileName: string): string {\n const base = path.basename(fileName);\n const parts = base.split('.');\n return parts[parts.length - 1].toLowerCase();\n}\n\nexport function isExtensionAllowed(fileName: string): boolean {\n return BACKEND_EXTENSION_WHITELIST.has(getBackendExtension(fileName));\n}\n\nexport interface ValidatedFile {\n filePath: string;\n size: number;\n /**\n * Optional file content. When provided, the validator additionally\n * checks for unresolved git-style conflict markers (left behind by a\n * `merge_markers` pull resolution that the user hasn't cleaned up).\n * Push pre-flight passes content; tests/abstract callers can omit it.\n */\n content?: Buffer;\n}\n\n/**\n * Validate a single file the CLI is about to upload. Returns null when the\n * file would pass the backend's create/update validation, otherwise a\n * `ValidationFailure` describing the rule that would reject it.\n *\n * `size` is required so we can also flag empty files: the backend's\n * multipart parser tends to surface a content-less request as the cryptic\n * `{\"code\":\"BadRequest\"}` body that field reports point to.\n */\nexport function validateFileForUpload(file: ValidatedFile): ValidationFailure | null {\n const baseName = path.basename(file.filePath);\n const trimmed = baseName.trim();\n\n if (trimmed.length === 0) {\n return {\n filePath: file.filePath,\n reason: 'name_empty',\n detail: 'Filename is empty after trimming whitespace',\n hint: 'Rename the file to a non-empty name before pushing.',\n };\n }\n\n if (trimmed.length > MAX_FILE_NAME_LENGTH) {\n return {\n filePath: file.filePath,\n reason: 'name_too_long',\n detail: `Filename is ${trimmed.length} characters; backend rejects names longer than ${MAX_FILE_NAME_LENGTH}`,\n hint: 'Shorten the filename and try again.',\n };\n }\n\n if (!isExtensionAllowed(baseName)) {\n const ext = getBackendExtension(baseName);\n return {\n filePath: file.filePath,\n reason: 'extension_not_allowed',\n detail: `Extension \".${ext}\" is not in the backend whitelist`,\n hint: `Allowed: ${[...BACKEND_EXTENSION_WHITELIST]\n .map((e) => '.' + e)\n .sort()\n .join(', ')}`,\n };\n }\n\n if (file.size === 0) {\n return {\n filePath: file.filePath,\n reason: 'empty_content',\n detail: 'File is empty (0 bytes)',\n hint: 'Empty files often come back as opaque \"BadRequest\" from the upload endpoint. Add at least one byte before pushing.',\n };\n }\n\n if (file.content && hasUnresolvedConflictMarkers(file.content)) {\n return {\n filePath: file.filePath,\n reason: 'unresolved_conflict_markers',\n detail: 'File contains unresolved git-style conflict markers (<<<<<<< LOCAL / ======= / >>>>>>> REMOTE)',\n hint: \"Open the file, pick which version to keep, remove the marker lines, then 'farseer push' again.\",\n };\n }\n\n return null;\n}\n\n/**\n * Validate a batch and split into pushable + rejected. The push command uses\n * this to render a single grouped message (\"4 file(s) skipped: \u2026\") and exit\n * cleanly without sending any request that we know will fail.\n */\nexport function partitionForUpload(files: ValidatedFile[]): {\n valid: ValidatedFile[];\n rejected: ValidationFailure[];\n} {\n const valid: ValidatedFile[] = [];\n const rejected: ValidationFailure[] = [];\n for (const file of files) {\n const failure = validateFileForUpload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A,MACH,UAAU,KAAK;AAAA,MACf,QAAQ;AAAA,MACR,QAAQ;AAAA,MACR,MAAM;AAAA,IACV;AAAA,EACJ;AAEA,SAAO;AACX;AAOO,SAAS,mBAAmB,OAGjC;AACE,QAAM,QAAyB,CAAC;AAChC,QAAM,WAAgC,CAAC;AACvC,aAAW,QAAQ,OAAO;AACtB,UAAM,UAAU,sBAAsB,IAAI;AAC1C,QAAI,QAAS,UAAS,KAAK,OAAO;AAAA,QAC7B,OAAM,KAAK,IAAI;AAAA,EACxB;AACA,SAAO,EAAE,OAAO,SAAS;AAC7B;",
|
|
6
5
|
"names": []
|
|
7
6
|
}
|
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/utils/folderMatch.ts"],
|
|
4
|
-
"sourcesContent": ["/** Two sibling folders answer to the same name, and neither is an exact match. */\nexport class AmbiguousFolderError extends Error {}\n\n/**\n * Pick the folder a path segment names, out of one parent's listing.\n *\n * Exact first, because the backend allows `Sales` and `sales` to sit side by\n * side and only the typed name says which was meant. A case-insensitive match\n * is still accepted when it is the only candidate \u2014 that is the ordinary case,\n * where nothing is ambiguous and refusing would only be pedantic. Two\n * candidates and no exact match is refused rather than resolved by listing\n * order, which would silently write into whichever the backend returned first.\n */\nexport function matchFolderSegment<T extends { id: number; name: string }>(folders: T[], segment: string): T | null {\n const exact = folders.find((folder) => folder.name === segment);\n if (exact) {\n return exact;\n }\n\n const insensitive = folders.filter((folder) => folder.name.toLowerCase() === segment.toLowerCase());\n if (insensitive.length === 1) {\n return insensitive[0];\n }\n if (insensitive.length > 1) {\n const names = insensitive.map((folder) => `\"${folder.name}\"`).join(', ');\n throw new AmbiguousFolderError(\n `Folder name \"${segment}\" matches ${insensitive.length} folders that differ only in case: ${names}. ` +\n 'Use the exact name.',\n );\n }\n\n return null;\n}\n"],
|
|
5
4
|
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AACO,MAAM,6BAA6B,MAAM;AAAC;AAY1C,SAAS,mBAA2D,SAAc,SAA2B;AAChH,QAAM,QAAQ,QAAQ,KAAK,CAAC,WAAW,OAAO,SAAS,OAAO;AAC9D,MAAI,OAAO;AACP,WAAO;AAAA,EACX;AAEA,QAAM,cAAc,QAAQ,OAAO,CAAC,WAAW,OAAO,KAAK,YAAY,MAAM,QAAQ,YAAY,CAAC;AAClG,MAAI,YAAY,WAAW,GAAG;AAC1B,WAAO,YAAY,CAAC;AAAA,EACxB;AACA,MAAI,YAAY,SAAS,GAAG;AACxB,UAAM,QAAQ,YAAY,IAAI,CAAC,WAAW,IAAI,OAAO,IAAI,GAAG,EAAE,KAAK,IAAI;AACvE,UAAM,IAAI;AAAA,MACN,gBAAgB,OAAO,aAAa,YAAY,MAAM,sCAAsC,KAAK;AAAA,IAErG;AAAA,EACJ;AAEA,SAAO;AACX;",
|
|
6
5
|
"names": []
|
|
7
6
|
}
|
|
@@ -18,7 +18,8 @@ var __copyProps = (to, from, except, desc) => {
|
|
|
18
18
|
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
19
|
var formulaFilters_exports = {};
|
|
20
20
|
__export(formulaFilters_exports, {
|
|
21
|
-
filtersInFormula: () => filtersInFormula
|
|
21
|
+
filtersInFormula: () => filtersInFormula,
|
|
22
|
+
parseFilterOptions: () => parseFilterOptions
|
|
22
23
|
});
|
|
23
24
|
module.exports = __toCommonJS(formulaFilters_exports);
|
|
24
25
|
const EXPRESSION_SYMBOLS = /[+\-*/()<>=!,"]/;
|
|
@@ -41,8 +42,16 @@ function filtersInFormula(formula, filters) {
|
|
|
41
42
|
const variable = quoted || GID.test(trimmed) ? trimmed : `"${trimmed}"`;
|
|
42
43
|
return `SUM(${[variable, ...filters.map(([table, member]) => `"${table}">"${member}"`)].join(", ")})`;
|
|
43
44
|
}
|
|
45
|
+
function parseFilterOptions(values) {
|
|
46
|
+
return values.map((value) => {
|
|
47
|
+
const eqIndex = value.indexOf("=");
|
|
48
|
+
if (eqIndex === -1) throw new Error(`Invalid filter format: "${value}". Expected "Table=Member".`);
|
|
49
|
+
return [value.substring(0, eqIndex), value.substring(eqIndex + 1)];
|
|
50
|
+
});
|
|
51
|
+
}
|
|
44
52
|
// Annotate the CommonJS export names for ESM import in node:
|
|
45
53
|
0 && (module.exports = {
|
|
46
|
-
filtersInFormula
|
|
54
|
+
filtersInFormula,
|
|
55
|
+
parseFilterOptions
|
|
47
56
|
});
|
|
48
57
|
//# sourceMappingURL=formulaFilters.js.map
|
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/utils/formulaFilters.ts"],
|
|
4
|
-
"
|
|
5
|
-
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,MAAM,qBAAqB;AAC3B,MAAM,MAAM;AAGZ,SAAS,UAAU,SAAyB;AACxC,SAAO,CAAC,mBAAmB,KAAK,OAAO,KAAK,WAAW,KAAK,OAAO,IAAI,IAAI,OAAO,MAAM;AAC5F;AAMO,SAAS,iBAAiB,SAAiB,SAA6B;AAC3E,MAAI,QAAQ,WAAW,EAAG,QAAO,UAAU,OAAO;AAClD,MAAI,QAAQ,KAAK,CAAC,SAAS,KAAK,WAAW,CAAC,GAAG;AAC3C,UAAM,IAAI,MAAM,+DAA+D;AAAA,EACnF;AACA,QAAM,UAAU,QAAQ,KAAK;AAC7B,QAAM,SAAS,YAAY,KAAK,OAAO;AACvC,MAAI,CAAC,UAAU,mBAAmB,KAAK,OAAO,GAAG;AAC7C,UAAM,IAAI;AAAA,MACN,IAAI,OAAO;AAAA,IAEf;AAAA,EACJ;AACA,QAAM,WAAW,UAAU,IAAI,KAAK,OAAO,IAAI,UAAU,IAAI,OAAO;AACpE,SAAO,OAAO,CAAC,UAAU,GAAG,QAAQ,IAAI,CAAC,CAAC,OAAO,MAAM,MAAM,IAAI,K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|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/utils/helpers.ts"],
|
|
4
|
-
"sourcesContent": ["import * as crypto from 'crypto';\nimport * as path from 'path';\nimport * as fs from 'fs';\nimport { getCredential, getTenantOrg } from '../services/configService';\nimport { logger } from './logger';\nimport { formatClientError } from './errorFormatter';\nimport type { AppListItem, RemoteApp } from '../services/apps';\nimport type { ConnectionFailure, FarseerService } from '../services/farseerService';\nimport { selectByNameOrId, formatAmbiguous } from './nameResolver';\n\nexport function calculateHash(content: string | Buffer): string {\n return crypto.createHash('md5').update(content).digest('hex');\n}\n\n/**\n * Where tenant folders live: `<FARSEER_APPS_DIR>/farseer-apps/<tenant>`, or the working\n * directory when the variable is unset. A host that starts `farseer mcp-server` from a\n * different directory than the project it manages (Mindseer starts it from the project\n * root and keeps each instance's files under `instances/<slug>/`) points it here.\n */\nexport function getAppsDir(): string {\n const base = process.env.FARSEER_APPS_DIR?.trim();\n return path.join(base ? path.resolve(process.cwd(), base) : process.cwd(), 'farseer-apps');\n}\n\nexport function getTenantDir(tenant: string): string {\n return path.join(getAppsDir(), tenant);\n}\n\nexport function getTenantFilesDir(tenant: string): string {\n return path.join(getTenantDir(tenant), 'files');\n}\n\n/**\n * Human-readable path string for log output. Renders the directory the\n * CLI actually scans, so users who copy-paste the displayed path land\n * on the right files.\n *\n * Earlier `status` hard-coded the literal `apps/<tenant>/files/` which\n * had drifted from the real `farseer-apps/<tenant>/files/` layout \u2014\n * users who followed the displayed path edited files the CLI never\n * looked at. Deriving from the same helper as the operation prevents\n * the strings from drifting again.\n *\n * Edge cases handled:\n * \u2022 If a `path.relative(cwd, absDir)` would point UP (`../`) or to\n * the cwd itself, we fall back to the absolute path \u2014 the user is\n * running the CLI from outside / at the synced directory, and\n * showing `\"../\"` or an empty relative string is more confusing\n * than the absolute form.\n * \u2022 macOS resolves `/tmp` \u2192 `/private/tmp` via `fs.realpathSync`,\n * which makes `path.relative` from cwd `/tmp/x` to absDir\n * `/private/tmp/x/...` emit `../../../...`. We resolve both sides\n * through `realpathSync` before comparing so the symlink doesn't\n * leak into the displayed path.\n */\nexport function displayLocalPath(absDir: string): string {\n // Resolve symlinks on both sides so /tmp vs /private/tmp on macOS\n // doesn't blow up the relative path with `../../../`.\n const resolvedCwd = safeRealpath(process.cwd());\n const resolvedDir = safeRealpath(absDir);\n const rel = path.relative(resolvedCwd, resolvedDir);\n // `..` prefix means absDir is OUTSIDE cwd. Falling back to the\n // absolute form is clearer than a deep `../` chain \u2014 and it stays\n // copy-pasteable. An empty string means cwd === absDir, which would\n // otherwise render as just `/`; show `./` instead so the trailing\n // slash convention stays consistent.\n if (rel === '') return './';\n if (rel.startsWith('..')) return resolvedDir + '/';\n return rel + '/';\n}\n\n/**\n * `fs.realpathSync` with a graceful fallback: returns the input\n * unchanged when the path doesn't exist or can't be resolved. Used by\n * `displayLocalPath` so we can render a still-to-be-created tenant\n * folder without throwing.\n */\nfunction safeRealpath(p: string): string {\n try {\n return fs.realpathSync(p);\n } catch {\n return p;\n }\n}\n\n// Legacy - for backwards compatibility with run command\nexport function getTenantSrcDir(tenant: string): string {\n return path.join(getTenantFilesDir(tenant), 'Scripts');\n}\n\nexport function getSyncFilePath(tenant: string): string {\n return path.join(getTenantDir(tenant), '.farseer-sync.json');\n}\n\nexport function getAuditLogPath(tenant: string): string {\n return path.join(getTenantDir(tenant), '.farseer-audit.log');\n}\n\nexport function getTenantAppsDir(tenant: string): string {\n return path.join(getTenantDir(tenant), 'apps');\n}\n\nexport function ensureDirectoryExists(dirPath: string): void {\n if (!fs.existsSync(dirPath)) {\n fs.mkdirSync(dirPath, { recursive: true });\n }\n}\n\n/**\n * Returns `fullPath` relative to `basePath`, always with POSIX separators.\n *\n * On Windows `path.relative` returns backslash-separated paths. Those flow\n * through `getAllFilesInDir` / `getAllFiles` and become KEYS in the sync\n * state, `localFileHashes`, `localPresenceSet`, etc. Remote keys come back\n * from the API as POSIX (`/`-separated), so without this normalisation the\n * key comparison fails and every file looks like a local-delete + remote-add\n * pair. Normalising once here means every caller \u2014 sync state, status\n * comparator, blocklist matcher \u2014 sees the same shape regardless of OS.\n */\nexport function getRelativePath(fullPath: string, basePath: string): string {\n return path.relative(basePath, fullPath).split(path.sep).join('/');\n}\n\n/**\n * Resolve `filePath` against `baseDir` and verify the resolved path stays\n * inside it. Anything that escapes (`..`, absolute paths, symlink-style\n * tricks once resolved) throws \u2014 callers that build paths from REMOTE\n * data must use this so a backend bug or compromised tenant returning\n * `../../etc/passwd` can't write or unlink outside the tenant's files\n * folder.\n *\n * Use everywhere we touch the filesystem with a path that came from\n * remote: pull's writes/unlinks, the merge_markers `.remote` sibling\n * write, push/wipe candidate iteration, etc.\n */\nexport function safeResolveWithinBase(baseDir: string, filePath: string): string {\n const resolvedBase = path.resolve(baseDir);\n const resolved = path.resolve(resolvedBase, filePath);\n // path.resolve normalises `..`; check the result is inside the base\n // directory (allow exact match for the base itself, but require a\n // separator suffix for descendants to avoid `/foo/bar` vs `/foo/barbaz`).\n if (resolved !== resolvedBase && !resolved.startsWith(resolvedBase + path.sep)) {\n throw new Error(\n `Path escapes base directory: '${filePath}' resolves to '${resolved}' (base: '${resolvedBase}')`,\n );\n }\n return resolved;\n}\n\n/**\n * Resolves a list of relative paths against `baseDir` and partitions\n * them into resolved-to-real-file vs. missing. Used by `push --only`\n * to validate the user's whitelist before any network call.\n *\n * \"Missing\" covers all the ways a path can fail to point at a real\n * file under the base:\n * - filename typo / wrong case / double slash\n * - file was deleted locally after the user typed the command\n * - traversal attempt (`../foo`) \u2014 safeResolveWithinBase throws, we\n * catch and treat it as missing rather than crashing the whole\n * pre-flight on the first offender. Without the catch, the user\n * would see one error and never get the consolidated \"here's\n * everything that didn't resolve\" output.\n *\n * Order is preserved in `missing` so the error message lists paths\n * in the same order the user wrote them.\n */\nexport function validateOnlyFilePaths(baseDir: string, paths: string[]): { missing: string[] } {\n const missing: string[] = [];\n for (const p of paths) {\n try {\n const fullPath = safeResolveWithinBase(baseDir, p);\n if (!fs.existsSync(fullPath) || !fs.statSync(fullPath).isFile()) {\n missing.push(p);\n }\n } catch {\n missing.push(p);\n }\n }\n return { missing };\n}\n\n/**\n * OS-generated metadata files / folders that should NEVER be synced.\n *\n * These accumulate locally without the user creating them and would otherwise\n * leak into the remote workspace (and trip backend filename validation).\n * Match against the basename of any path segment, including nested copies\n * (e.g. `Scripts/.DS_Store`, `__MACOSX/Apps/foo.ts`).\n *\n * Lives in helpers (not syncService) so the file-listing helper itself can\n * apply the filter \u2014 keeping it in syncService meant every call site had to\n * remember to `.filter((f) => !isOsMetadataFile(f))` and a single forgotten\n * one would silently leak `.DS_Store` (which is exactly how PR #1878 started).\n */\nconst OS_METADATA_BASENAMES = new Set([\n '.DS_Store', // macOS Finder\n '.AppleDouble', // macOS Time Machine / netatalk\n '.LSOverride', // macOS Launch Services\n '.Spotlight-V100', // macOS Spotlight\n '.Trashes', // macOS\n '.fseventsd', // macOS\n '.DocumentRevisions-V100', // macOS\n '.TemporaryItems', // macOS\n '.VolumeIcon.icns', // macOS\n '.com.apple.timemachine.donotpresent',\n 'Thumbs.db', // Windows Explorer\n 'Thumbs.db:encryptable',\n 'ehthumbs.db', // Windows Explorer\n 'ehthumbs_vista.db',\n 'desktop.ini', // Windows\n '$RECYCLE.BIN', // Windows\n '__MACOSX', // macOS zip artefact\n]);\n\n/**\n * Returns true when any segment of the path is an OS metadata file/folder\n * we always want to hide from sync \u2014 irrespective of `--all` or includes\n * config. Used as the bottom-line filter in `getAllFilesInDir` and applied\n * defensively to remote listings so old clients can't get metadata files\n * stuck on a tenant.\n */\nexport function isOsMetadataFile(filePath: string): boolean {\n const segments = filePath.split('/');\n for (const seg of segments) {\n if (OS_METADATA_BASENAMES.has(seg)) return true;\n // The `._<name>` prefix is reserved for macOS AppleDouble resource\n // forks (created by tar/zip/AFP when copying across HFS+ boundaries)\n // and is therefore aggressive: any user-named file starting with\n // `._` is silently dropped from sync. We accept this \u2014 collisions\n // are rare in practice and the alternative (uploading bookkeeping\n // junk) is the worse failure mode.\n if (seg.startsWith('._')) return true;\n }\n return false;\n}\n\n/**\n * Returns true when the path contains any segment starting with `.` that is\n * NOT covered by `isOsMetadataFile`. Things like `.env`, `.git/`, `.vscode/`\n * fall here. The CLI's `shouldIncludeFile` requires explicit opt-in for\n * these (via `--include-ext` / `--include-folder` / persistent sync-includes\n * config) \u2014 they are never picked up by `--all` alone, so a stray credential\n * file in `farseer-apps/<tenant>/files/` doesn't get pushed by accident.\n */\nexport function isHiddenFile(filePath: string): boolean {\n if (isOsMetadataFile(filePath)) return false; // those have their own rule\n const segments = filePath.split('/');\n return segments.some((seg) => seg.length > 0 && seg.startsWith('.'));\n}\n\nexport function getAllFiles(dirPath: string, basePath?: string): string[] {\n if (!fs.existsSync(dirPath)) {\n return [];\n }\n\n const base = basePath || dirPath;\n const files: string[] = [];\n\n const items = fs.readdirSync(dirPath, { withFileTypes: true });\n\n for (const item of items) {\n const fullPath = path.join(dirPath, item.name);\n\n if (item.isDirectory()) {\n files.push(...getAllFiles(fullPath, base));\n } else if (item.isFile() && isScriptFile(item.name)) {\n files.push(getRelativePath(fullPath, base));\n }\n }\n\n return files;\n}\n\n/**\n * Get all files in a directory recursively, with OS metadata stripped.\n *\n * The OS-metadata filter is the default behavior \u2014 every call site needs it,\n * and forgetting to add a `.filter((f) => !isOsMetadataFile(f))` at a new\n * call site is exactly how `.DS_Store` started leaking into pushes. Pass\n * `{ includeOsMetadata: true }` only when you have a specific reason to see\n * those files (e.g. a debug listing, audit dump). Hidden files are NOT\n * filtered here \u2014 that gate lives in `shouldIncludeFile` because the user\n * can opt in to specific dotfile patterns via the includes config.\n *\n * Pass `shouldSkipDir(relPath)` to short-circuit the walk into directories\n * the caller knows it will discard anyway. This is how callers actually\n * bound memory \u2014 without it a tenant containing `.git/` or `node_modules/`\n * still materialises every filename before any filter runs.\n */\nexport function getAllFilesInDir(\n dirPath: string,\n basePathOrOptions?: string | { includeOsMetadata?: boolean; shouldSkipDir?: (relPath: string) => boolean },\n optionsArg?: { includeOsMetadata?: boolean; shouldSkipDir?: (relPath: string) => boolean },\n): string[] {\n // Backwards-compat with the old (dirPath, basePath?) signature.\n const basePath = typeof basePathOrOptions === 'string' ? basePathOrOptions : undefined;\n const options = typeof basePathOrOptions === 'object' ? basePathOrOptions : (optionsArg ?? {});\n\n if (!fs.existsSync(dirPath)) return [];\n\n const base = basePath || dirPath;\n const files: string[] = [];\n const items = fs.readdirSync(dirPath, { withFileTypes: true });\n\n for (const item of items) {\n const fullPath = path.join(dirPath, item.name);\n\n if (item.isDirectory()) {\n const relPath = getRelativePath(fullPath, base);\n // Skip whole OS-metadata directories at recursion time \u2014 saves a\n // pointless walk into `__MACOSX/` etc. when we'd just discard\n // every entry afterwards.\n if (!options.includeOsMetadata && isOsMetadataFile(relPath)) {\n continue;\n }\n // Caller-supplied skip: lets sync callers prune hidden/`node_modules`\n // subtrees before we materialise their contents.\n if (options.shouldSkipDir && options.shouldSkipDir(relPath)) {\n continue;\n }\n files.push(...getAllFilesInDir(fullPath, base, options));\n } else if (item.isFile()) {\n const relPath = getRelativePath(fullPath, base);\n if (!options.includeOsMetadata && isOsMetadataFile(relPath)) continue;\n files.push(relPath);\n }\n }\n\n return files;\n}\n\nexport function isScriptFile(filename: string): boolean {\n const ext = path.extname(filename).toLowerCase();\n return ['.ts', '.js', '.mjs', '.cjs'].includes(ext);\n}\n\nexport function isTextFile(filename: string): boolean {\n const ext = path.extname(filename).toLowerCase().slice(1); // remove leading dot\n return ['ts', 'js', 'mjs', 'cjs', 'json', 'txt', 'md', 'csv', 'xml', 'html', 'css', 'yaml', 'yml'].includes(ext);\n}\n\nexport function formatFileSize(bytes: number): string {\n if (bytes < 1024) return `${bytes} B`;\n if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;\n return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;\n}\n\nexport function formatDate(date: Date | string): string {\n const d = typeof date === 'string' ? new Date(date) : date;\n return d.toLocaleString();\n}\n\nexport function getCredentialsHint(tenant: string): string {\n return `Use: farseer login\n Or: farseer config set ${tenant} --api-key <key> --org <organisation>`;\n}\n\n/**\n * The headline for a failed credential probe. Shared by `config test` and\n * `login` so the same failure cannot be described two ways, and separate from\n * ConnectionCheck itself so the MCP surface can word it differently.\n */\nexport function connectionFailureMessage(reason: ConnectionFailure, host: string, tenant: string): string {\n switch (reason) {\n case 'rejected':\n return 'Connection failed: the server rejected this API key.';\n case 'tenant-unknown':\n return `Connection failed: ${host} has no tenant \"${tenant}\". The key is fine \u2014 check the organisation.`;\n case 'server-error':\n return `Connection failed: ${host} answered with an error.`;\n case 'unreachable':\n return `Connection failed: could not reach ${host}.`;\n }\n}\n\n/**\n * Resolve tenant from argument or the FARSEER_TENANT env.\n * If tenant is provided, use it. Otherwise, use the env tenant.\n * Returns null if no tenant is available.\n */\nexport interface ResolvedCheckout {\n organisation: string;\n tenant: string;\n}\n\n/**\n * Per-shell target from the environment. There is no persisted global default\n * any more \u2014 a command takes its tenant from an explicit argument or from\n * FARSEER_TENANT in the calling shell, and errors if neither is set. Two shells\n * can therefore hold different tenants at once, and a bare command never\n * silently retargets to a stale machine-global checkout.\n *\n * Org resolves the same way the MCP launch path does (mcp/utils/launchPin.ts):\n * FARSEER_ORG > saved tenant->org mapping > the tenant name. So once a confirmed\n * `farseer pull <org> <tenant>` has recorded the mapping, `export FARSEER_TENANT=x`\n * alone is enough; only new org != tenant tenants also need FARSEER_ORG.\n */\nexport function getEnvCheckout(): ResolvedCheckout | null {\n const tenant = process.env.FARSEER_TENANT;\n if (!tenant) return null;\n const organisation = process.env.FARSEER_ORG || getTenantOrg(tenant) || tenant;\n if (organisation === tenant) {\n logger.dim(`Using tenant from FARSEER_TENANT: ${tenant}`);\n } else {\n logger.dim(`Using tenant from FARSEER_TENANT: ${tenant} (org: ${organisation})`);\n }\n return { organisation, tenant };\n}\n\n/**\n * Resolve organisation and tenant from argument or the FARSEER_TENANT env.\n * When only tenant is provided, assumes organisation = tenant.\n */\nexport function resolveOrgAndTenant(tenantArg?: string): ResolvedCheckout | null {\n if (tenantArg) {\n // When tenant is specified as arg, assume org = tenant\n // (org != tenant tenants are resolved via the mapping in the\n // richer resolveTenantWithOrgMapping path).\n return { organisation: tenantArg, tenant: tenantArg };\n }\n\n return getEnvCheckout();\n}\n\nexport function resolveTenant(tenantArg?: string): string | null {\n const resolved = resolveOrgAndTenant(tenantArg);\n return resolved?.tenant || null;\n}\n\n/**\n * Resolve tenant or exit with error if not available.\n */\nexport function resolveTenantOrExit(tenantArg?: string): string {\n const tenant = resolveTenant(tenantArg);\n if (!tenant) {\n logger.error('No tenant specified.');\n logger.dim('Pass it: farseer <command> <tenant>');\n logger.dim('Or set it (per shell): export FARSEER_TENANT=<tenant>');\n process.exit(1);\n }\n return tenant;\n}\n\n/**\n * Resolve organisation and tenant with support for org-tenant mapping.\n *\n * Usage patterns:\n * - <org> <tenant>: Explicit org and tenant\n * - <tenant>: Look up org from FARSEER_ORG or the saved mapping\n * - (no args): Fall back to FARSEER_TENANT/FARSEER_ORG from the shell\n *\n * Read-only by design: resolving a pair must not persist it. A typo'd org\n * (`farseer pull wrong-org my-tenant`) would otherwise be remembered as\n * my-tenant's org before anything confirmed it, and every later one-arg command\n * would inherit the wrong host \u2014 silently, since `*.farseer.io` is a wildcard.\n * The mapping is written by the preflight instead, and only for a pair the\n * organisation itself confirmed.\n *\n * @param arg1 - Organisation (if 2 args) or tenant (if 1 arg)\n * @param arg2 - Tenant (if 2 args)\n * @returns ResolvedCheckout or exits with error\n */\nexport function resolveTenantWithOrgMapping(arg1?: string, arg2?: string): ResolvedCheckout {\n // Case 1: Two arguments - <org> <tenant>\n if (arg1 && arg2) {\n const org = arg1;\n const tenant = arg2;\n\n if (org === tenant) {\n logger.dim(`Using tenant: ${tenant}`);\n } else {\n logger.dim(`Using tenant: ${tenant} (org: ${org})`);\n }\n\n return { organisation: org, tenant };\n }\n\n // Case 2: One argument - <tenant>\n if (arg1) {\n const tenant = arg1;\n\n // FARSEER_ORG pairs with FARSEER_TENANT (it's the org for the shell's\n // env tenant), so only honour it when this explicit tenant IS that env\n // tenant \u2014 otherwise a shell-level FARSEER_ORG would leak onto an\n // unrelated tenant and build the wrong host. Else use the saved mapping.\n const envOrg = tenant === process.env.FARSEER_TENANT ? process.env.FARSEER_ORG : undefined;\n const org = envOrg || getTenantOrg(tenant);\n if (org) {\n if (org === tenant) {\n logger.dim(`Using tenant: ${tenant}`);\n } else {\n logger.dim(`Using tenant: ${tenant} (org: ${org})`);\n }\n return { organisation: org, tenant };\n }\n\n // An API-key tenant needs no remembered org: the stored credential\n // carries its own base URL and the organisation is ignored on that path.\n // Only confirmed pairs get recorded now, so these tenants often have no\n // mapping at all \u2014 don't demand an org we would never use.\n if (getCredential(tenant)) {\n logger.dim(`Using tenant: ${tenant}`);\n return { organisation: tenant, tenant };\n }\n\n // Org for this tenant is unknown - fail loud rather than guess a host.\n logger.error(`Organisation unknown for tenant \"${tenant}\".`);\n logger.dim('Pass both: farseer <command> <organisation> <tenant>');\n logger.dim(`Or set them per shell: export FARSEER_TENANT=${tenant} FARSEER_ORG=<organisation>`);\n process.exit(1);\n }\n\n // Case 3: No arguments - fall back to FARSEER_TENANT from the shell.\n const envCheckout = getEnvCheckout();\n if (envCheckout) {\n return envCheckout;\n }\n\n // Nothing to go on - fail loud instead of guessing a tenant.\n logger.error('No tenant specified.');\n logger.dim('Pass it: farseer <command> <tenant>');\n logger.dim('Or set it (per shell): export FARSEER_TENANT=<tenant> (FARSEER_ORG=<org> if org differs)');\n process.exit(1);\n}\n\n/**\n * Resolve organisation and tenant or exit with error.\n */\nexport function resolveOrgAndTenantOrExit(tenantArg?: string): ResolvedCheckout {\n const resolved = resolveOrgAndTenant(tenantArg);\n if (!resolved) {\n logger.error('No tenant specified.');\n logger.dim('Pass it: farseer <command> <tenant>');\n logger.dim('Or set it (per shell): export FARSEER_TENANT=<tenant>');\n process.exit(1);\n }\n return resolved;\n}\n\n/**\n * Check if a string is a known tenant (has credentials configured).\n */\nexport function isKnownTenant(name: string): boolean {\n return !!getCredential(name);\n}\n\nexport interface ParsedAppArgs {\n organisation: string;\n tenant: string;\n appName: string;\n}\n\n/**\n * Parse variadic arguments to extract tenant and app name.\n * If first arg is a known tenant, use it as tenant and rest as app name.\n * Otherwise, use checked-out tenant and all args as app name.\n *\n * @param args Array of arguments (from variadic command)\n * @returns { organisation: string, tenant: string, appName: string }\n */\nexport function parseAppArgs(\n args: string[],\n options: { allowEmptyName?: boolean; command?: string } = {},\n): ParsedAppArgs {\n if (args.length === 0) {\n if (options.allowEmptyName) {\n // `--id` path: no app name was typed, so the tenant can only come\n // from FARSEER_TENANT in the shell.\n const envCheckout = getEnvCheckout();\n if (envCheckout) {\n return { organisation: envCheckout.organisation, tenant: envCheckout.tenant, appName: '' };\n }\n logger.error('No tenant specified.');\n logger.dim('Either specify a tenant: farseer app show <tenant> --id <id>');\n logger.dim('Or set FARSEER_TENANT in your shell.');\n process.exit(1);\n }\n logger.error('App name is required.');\n process.exit(1);\n }\n\n // `--id` path with a single positional. It reads as a tenant \u2014 but the\n // collision message that sends people here had them type an app *name*, so\n // reading it as a tenant is how adding `--id` to a failed command silently\n // moves it to a different tenant.\n if (options.allowEmptyName && args.length === 1) {\n const only = args[0];\n const envCheckout = getEnvCheckout();\n const namesATenant = isKnownTenant(only) || !!getTenantOrg(only);\n\n if (envCheckout && namesATenant && only !== envCheckout.tenant) {\n // Both readings are real and they target different tenants, which is\n // the one case worth stopping for: on `app delete` the wrong guess\n // destroys something in a tenant the user never named.\n const command = options.command ?? 'app show';\n logger.error(`\"${only}\" is both a configured tenant and the name you are selecting by id.`);\n logger.dim('With --id the name is not used, so drop it and let the tenant say itself:');\n logger.dim(` farseer ${command} --id <id> (tenant ${envCheckout.tenant})`);\n logger.dim(` FARSEER_TENANT=${only} farseer ${command} --id <id> (tenant ${only})`);\n process.exit(1);\n }\n\n // An env tenant means the command already had a target before `--id` was\n // added, and adding it must not move that target.\n if (envCheckout) {\n return { organisation: envCheckout.organisation, tenant: envCheckout.tenant, appName: only };\n }\n\n return { organisation: getTenantOrg(only) || only, tenant: only, appName: '' };\n }\n\n // First arg looks like a tenant when either:\n // (a) we have API-key credentials saved for it, or\n // (b) we have a saved tenantOrgMapping entry for it (from a previous\n // `farseer pull <org> <tenant>`).\n // In both cases we prefer the saved organisation over args[0] so\n // run/apps/etc. build the right URL when org != tenant.\n if (args.length >= 2) {\n const first = args[0];\n const knownViaCredential = isKnownTenant(first);\n const savedOrg = getTenantOrg(first);\n if (knownViaCredential || savedOrg) {\n return {\n organisation: savedOrg || first,\n tenant: first,\n appName: args.slice(1).join(' '),\n };\n }\n }\n\n // Fall back to FARSEER_TENANT from the shell; all args are the app name.\n const envCheckout = getEnvCheckout();\n if (envCheckout) {\n return {\n organisation: envCheckout.organisation,\n tenant: envCheckout.tenant,\n appName: args.join(' '),\n };\n }\n\n // No env tenant and first arg isn't a known tenant\n // Assume first arg is tenant (will fail later if invalid)\n if (args.length >= 2) {\n return {\n organisation: args[0],\n tenant: args[0],\n appName: args.slice(1).join(' '),\n };\n }\n\n // Only one arg and no env tenant - could be tenant or app name\n logger.error('No tenant specified.');\n logger.dim('Pass it: farseer app show <tenant> <app-name>');\n logger.dim('Or set it (per shell): export FARSEER_TENANT=<tenant>');\n process.exit(1);\n}\n\n/**\n * Run a lookup that reports absence as null and everything else by throwing,\n * and end the command on the everything else. Commander does not await an\n * action, so without a boundary here the rejection escapes to the process\n * handler, which is the wrong place to explain that one read failed.\n */\nexport async function orExit<T>(work: Promise<T>, message: string): Promise<T> {\n try {\n return await work;\n } catch (error) {\n logger.error(message);\n logger.dim(await formatClientError(error));\n return process.exit(1);\n }\n}\n\n/**\n * Resolve an app to its folder list item, or exit with a clear message. An\n * explicit `--id` wins; a name that matches more than one app aborts, listing\n * the candidates, rather than picking the first.\n *\n * Callers take `.reference` to fetch details and `.id` to delete \u2014 the two ids\n * are different and their number spaces overlap.\n */\nexport async function resolveAppItemOrExit(\n api: FarseerService,\n selector: { appName?: string; id?: string; tenant?: string },\n): Promise<AppListItem> {\n const apps = await orExit(api.listApps(), 'Failed to list apps.');\n const selection = selectByNameOrId(apps, { name: selector.appName, id: selector.id }, (a) => a.reference);\n\n if (selection.kind === 'found') {\n return selection.entity;\n }\n\n if (selection.kind === 'ambiguous') {\n logger.error(formatAmbiguous('apps', selector.appName ?? '', selection.matches, (a) => a.reference));\n logger.dim('Re-run with --id <id> in place of the name to pick one.');\n process.exit(1);\n }\n\n if (selection.kind === 'conflict') {\n const { entity: app, name } = selection;\n logger.error(\n `App ${app.reference} is \"${app.name}\", not \"${name}\". The id and the name point at different apps, so nothing was done.`,\n );\n logger.dim(\n `To act on app ${app.reference}${selector.tenant ? ` in tenant \"${selector.tenant}\"` : ''}, drop the name.`,\n );\n if (!/\\s/.test(name)) {\n logger.dim(\n `If \"${name}\" is a tenant, select it and re-run with only the id: export FARSEER_TENANT=${name}`,\n );\n }\n process.exit(1);\n }\n\n logger.error(selector.id ? `App not found: id ${selector.id}` : `App not found: ${selector.appName}`);\n logger.dim('List apps with: farseer app list <tenant>');\n process.exit(1);\n}\n\n/**\n * Resolve an app for a CLI command to its full details, or exit with a clear\n * message. Wraps `resolveAppItemOrExit` + `getApp` so the commands that need\n * the whole `RemoteApp` (show, run) don't repeat the fetch.\n */\nexport async function resolveAppOrExit(\n api: FarseerService,\n selector: { appName?: string; id?: string; tenant?: string },\n): Promise<RemoteApp> {\n const item = await resolveAppItemOrExit(api, selector);\n const app = await orExit(api.getApp(item.reference), `Failed to load app details: ${item.name}`);\n if (!app) {\n logger.error(`Failed to load app details: ${item.name}`);\n process.exit(1);\n }\n return app;\n}\n\n// Credential injection/stripping for local development\n// Matches: const farseerClient = new farseer.FarseerClient();\n// and: const fClient = new farseer.FarseerClient();\n\ninterface CredentialConfig {\n basePath: string;\n tenantId: string;\n apiKey: string;\n}\n\n// Pattern to match empty FarseerClient() constructor (no /g flag to avoid lastIndex issues)\nconst EMPTY_CLIENT_PATTERNS = [\n /const farseerClient = new farseer\\.FarseerClient\\(\\s*\\);/,\n /const fClient = new farseer\\.FarseerClient\\(\\s*\\);/,\n];\n\n// Pattern to match FarseerClient with injected credentials (multiline, no /g flag)\nconst INJECTED_CLIENT_PATTERN =\n /const (farseerClient|fClient) = new farseer\\.FarseerClient\\(\\{[\\s\\S]*?basePath:[\\s\\S]*?headers:[\\s\\S]*?'X-TENANT-ID':[\\s\\S]*?'X-API-KEY':[\\s\\S]*?\\}\\);/;\n\nexport function injectCredentials(code: string, credential: CredentialConfig): string {\n const clientConfig = `{\n basePath: '${credential.basePath}',\n headers: {\n 'X-TENANT-ID': '${credential.tenantId}',\n 'X-API-KEY': '${credential.apiKey}',\n }\n }`;\n\n let modified = code;\n\n // Pattern 1: const farseerClient = new farseer.FarseerClient();\n modified = modified.replace(\n /const farseerClient = new farseer\\.FarseerClient\\(\\s*\\);/g,\n `const farseerClient = new farseer.FarseerClient(${clientConfig});`,\n );\n\n // Pattern 2: const fClient = new farseer.FarseerClient();\n modified = modified.replace(\n /const fClient = new farseer\\.FarseerClient\\(\\s*\\);/g,\n `const fClient = new farseer.FarseerClient(${clientConfig});`,\n );\n\n return modified;\n}\n\nexport function stripCredentials(code: string): string {\n // Replace injected credentials back to empty constructor\n let modified = code;\n\n // Match farseerClient with credentials\n modified = modified.replace(\n /const farseerClient = new farseer\\.FarseerClient\\(\\{[\\s\\S]*?basePath:[\\s\\S]*?headers:[\\s\\S]*?'X-TENANT-ID':[\\s\\S]*?'X-API-KEY':[\\s\\S]*?\\}\\);/g,\n 'const farseerClient = new farseer.FarseerClient();',\n );\n\n // Match fClient with credentials\n modified = modified.replace(\n /const fClient = new farseer\\.FarseerClient\\(\\{[\\s\\S]*?basePath:[\\s\\S]*?headers:[\\s\\S]*?'X-TENANT-ID':[\\s\\S]*?'X-API-KEY':[\\s\\S]*?\\}\\);/g,\n 'const fClient = new farseer.FarseerClient();',\n );\n\n return modified;\n}\n\nexport function hasInjectedCredentials(code: string): boolean {\n return INJECTED_CLIENT_PATTERN.test(code);\n}\n\nexport function hasEmptyFarseerClient(code: string): boolean {\n return EMPTY_CLIENT_PATTERNS.some((pattern) => pattern.test(code));\n}\n\n// Process all script files in a directory\nexport function injectCredentialsInDir(srcDir: string, credential: CredentialConfig): number {\n let count = 0;\n const files = getAllFiles(srcDir);\n\n for (const file of files) {\n const filePath = path.join(srcDir, file);\n const content = fs.readFileSync(filePath, 'utf-8');\n const modified = injectCredentials(content, credential);\n\n if (modified !== content) {\n fs.writeFileSync(filePath, modified);\n count++;\n }\n }\n\n return count;\n}\n\nexport function stripCredentialsInDir(srcDir: string): number {\n let count = 0;\n const files = getAllFiles(srcDir);\n\n for (const file of files) {\n const filePath = path.join(srcDir, file);\n const content = fs.readFileSync(filePath, 'utf-8');\n const modified = stripCredentials(content);\n\n if (modified !== content) {\n fs.writeFileSync(filePath, modified);\n count++;\n }\n }\n\n return count;\n}\n\n// Audit log helpers\nexport interface AuditLogEntry {\n operation: 'pulled' | 'pushed' | 'deleted';\n filePath: string;\n uploadTime?: string;\n uploaderEmail?: string;\n uploaderName?: string;\n}\n\n/**\n * Execute async operations with limited concurrency.\n * Processes items in chunks to avoid overwhelming the API.\n *\n * @param items Array of items to process\n * @param fetcher Async function to call for each item\n * @param concurrency Maximum number of concurrent requests (default: 15)\n * @returns Array of results in the same order as input items\n */\nexport async function fetchWithConcurrency<T, R>(\n items: T[],\n fetcher: (item: T, index: number) => Promise<R>,\n concurrency: number = 15,\n): Promise<R[]> {\n const results: R[] = [];\n\n for (let i = 0; i < items.length; i += concurrency) {\n const chunk = items.slice(i, i + concurrency);\n const chunkResults = await Promise.all(chunk.map((item, chunkIndex) => fetcher(item, i + chunkIndex)));\n results.push(...chunkResults);\n }\n\n return results;\n}\n\nexport function appendToAuditLog(tenant: string, entries: AuditLogEntry[]): void {\n if (entries.length === 0) {\n return;\n }\n\n const logPath = getAuditLogPath(tenant);\n const timestamp = new Date().toISOString();\n\n let logContent = '';\n for (const entry of entries) {\n const uploaderInfo = entry.uploaderName\n ? `${entry.uploaderName} (${entry.uploaderEmail})`\n : entry.uploaderEmail || 'Unknown';\n\n const uploadedAt = entry.uploadTime ? new Date(entry.uploadTime).toLocaleString() : 'Unknown';\n\n logContent += `${timestamp} | ${entry.operation} | ${entry.filePath} | Modified by: ${uploaderInfo} | Uploaded: ${uploadedAt}\\n`;\n }\n\n fs.appendFileSync(logPath, logContent, 'utf-8');\n}\n"],
|
|
5
4
|
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,aAAwB;AACxB,WAAsB;AACtB,SAAoB;AACpB,2BAA4C;AAC5C,oBAAuB;AACvB,4BAAkC;AAGlC,0BAAkD;AAE3C,SAAS,cAAc,SAAkC;AAC5D,SAAO,OAAO,WAAW,KAAK,EAAE,OAAO,OAAO,EAAE,OAAO,KAAK;AAChE;AAQO,SAAS,aAAqB;AACjC,QAAM,OAAO,QAAQ,IAAI,kBAAkB,KAAK;AAChD,SAAO,KAAK,KAAK,OAAO,KAAK,QAAQ,QAAQ,IAAI,GAAG,IAAI,IAAI,QAAQ,IAAI,GAAG,cAAc;AAC7F;AAEO,SAAS,aAAa,QAAwB;AACjD,SAAO,KAAK,KAAK,WAAW,GAAG,MAAM;AACzC;AAEO,SAAS,kBAAkB,QAAwB;AACtD,SAAO,KAAK,KAAK,aAAa,MAAM,GAAG,OAAO;AAClD;AAyBO,SAAS,iBAAiB,QAAwB;AAGrD,QAAM,cAAc,aAAa,QAAQ,IAAI,CAAC;AAC9C,QAAM,cAAc,aA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AY,OAAO;AAClD;",
|
|
6
5
|
"names": ["envCheckout"]
|
|
7
6
|
}
|
package/dist/utils/logger.js.map
CHANGED
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/utils/logger.ts"],
|
|
4
|
-
"sourcesContent": ["import chalk from 'chalk';\n\nlet stdoutReserved = false;\n\n/** Sends every log line to stderr, for a command whose stdout carries machine-readable output. */\nexport function reserveStdout(): void {\n stdoutReserved = true;\n}\n\nfunction log(...args: unknown[]) {\n if (stdoutReserved || process.env.FARSEER_MCP === '1') {\n console.error(...args);\n } else {\n console.log(...args);\n }\n}\n\nexport const logger = {\n info: (message: string) => {\n log(chalk.blue('\u2139'), message);\n },\n\n success: (message: string) => {\n log(chalk.green('\u2713'), message);\n },\n\n warning: (message: string) => {\n log(chalk.yellow('\u26A0'), message);\n },\n\n error: (message: string) => {\n log(chalk.red('\u2717'), message);\n },\n\n log: (message: string) => {\n log(message);\n },\n\n dim: (message: string) => {\n log(chalk.dim(message));\n },\n\n header: (message: string) => {\n log();\n log(chalk.bold.underline(message));\n log();\n },\n\n list: (items: string[], indent: number = 2) => {\n const prefix = ' '.repeat(indent);\n items.forEach((item) => {\n log(`${prefix}${item}`);\n });\n },\n\n table: (rows: { label: string; value: string }[]) => {\n const maxLabelLength = Math.max(...rows.map((r) => r.label.length));\n rows.forEach((row) => {\n const paddedLabel = row.label.padEnd(maxLabelLength);\n log(` ${chalk.dim(paddedLabel)} ${row.value}`);\n });\n },\n};\n"],
|
|
5
4
|
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,mBAAkB;AAElB,IAAI,iBAAiB;AAGd,SAAS,gBAAsB;AAClC,mBAAiB;AACrB;AAEA,SAAS,OAAO,MAAiB;AAC7B,MAAI,kBAAkB,QAAQ,IAAI,gBAAgB,KAAK;AACnD,YAAQ,MAAM,GAAG,IAAI;AA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]
|
|
7
6
|
}
|
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/utils/nameResolver.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * Resolving a user-typed name to one thing.\n *\n * The backend enforces name uniqueness per folder, not per tenant, so any\n * lookup that searches a whole tenant can find more than one match. Picking the\n * first is the bug this exists to prevent: it acts on an arbitrary one of them\n * and leaves the others unreachable by name.\n *\n * Pure. Each surface renders the outcome its own way \u2014 the CLI exits, the MCP\n * tools return an error response.\n */\n\nexport type Selection<T> =\n | { kind: 'found'; entity: T }\n | { kind: 'notFound' }\n | { kind: 'ambiguous'; matches: T[] }\n // Only when both a name and an id were given; see selectByNameOrId.\n | { kind: 'conflict'; entity: T; name: string };\n\n/** Every entity whose name matches, case-insensitively. */\nexport function matchByName<T extends { name: string }>(items: readonly T[], name: string): T[] {\n const needle = name.trim().toLowerCase();\n return items.filter((item) => item.name.toLowerCase() === needle);\n}\n\n/**\n * An id (unique) decides over a name (may collide). `idOf` reads whichever id\n * the caller disambiguates by, which is not always the one used to address the\n * entity afterwards \u2014 an app is selected by its Remote Job id but deleted by\n * its folder-item id.\n *\n * A name given alongside the id is a claim about which entity that is, and one\n * that does not hold is a conflict rather than something the id overrides: on\n * the CLI it is a tenant name read as an app name, and dropping it acts on the\n * id in the wrong tenant.\n */\nexport function selectByNameOrId<T extends { name: string }>(\n items: readonly T[],\n selector: { name?: string; id?: string },\n idOf: (item: T) => string,\n): Selection<T> {\n const id = selector.id?.trim();\n if (id) {\n const entity = items.find((item) => idOf(item) === id);\n if (!entity) {\n return { kind: 'notFound' };\n }\n const name = selector.name?.trim();\n if (name && matchByName([entity], name).length === 0) {\n return { kind: 'conflict', entity, name };\n }\n return { kind: 'found', entity };\n }\n\n const matches = matchByName(items, selector.name ?? '');\n if (matches.length === 1) {\n return { kind: 'found', entity: matches[0] };\n }\n if (matches.length === 0) {\n return { kind: 'notFound' };\n }\n return { kind: 'ambiguous', matches };\n}\n\n/**\n * Lists each candidate's id. Deliberately free of `--id` wording so it reads\n * correctly from the MCP tools too; the CLI appends its own hint.\n */\nexport function formatAmbiguous<T extends { name: string }>(\n plural: string,\n name: string,\n matches: readonly T[],\n idOf: (item: T) => string,\n): string {\n const lines = matches.map((item) => ` id ${idOf(item)} ${item.name}`);\n return `Multiple ${plural} named \"${name}\" (${matches.length}). Specify one by id:\\n${lines.join('\\n')}`;\n}\n"],
|
|
5
4
|
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAoBO,SAAS,YAAwC,OAAqB,MAAmB;AAC5F,QAAM,SAAS,KAAK,KAAK,EAAE,YAAY;AACvC,SAAO,MAAM,OAAO,CAAC,SAAS,KAAK,KAAK,YAAY,MAAM,MAAM;AACpE;AAaO,SAAS,iBACZ,OACA,UACA,MACY;AACZ,QAAM,KAAK,SAAS,IAAI,KAAK;AAC7B,MAAI,IAAI;AACJ,UAAM,SAAS,MAAM,KAAK,CAAC,SAAS,KAAK,IAAI,MAAM,EAAE;AACrD,QAAI,CAAC,QAAQ;AACT,aAAO,EAAE,MAAM,WAAW;AAAA,IAC9B;AACA,UAAM,OAAO,SAAS,MAAM,KAAK;AACjC,QAAI,QAAQ,YAAY,CAAC,MAAM,GAAG,IAAI,EAAE,WAAW,GAAG;AAClD,aAAO,EAAE,MAAM,YAAY,QAAQ,KAAK;AAAA,IAC5C;AACA,WAAO,EAAE,MAAM,SAAS,OAAO;AAAA,EACnC;AAEA,QAAM,UAAU,YAAY,OAAO,SAAS,QAAQ,EAAE;AACtD,MAAI,QAAQ,WAAW,GAAG;AACtB,WAAO,EAAE,MAAM,SAAS,QAAQ,QAAQ,CAAC,EAAE;AAAA,EAC/C;AACA,MAAI,QAAQ,WAAW,GAAG;AACtB,WAAO,EAAE,MAAM,WAAW;AAAA,EAC9B;AACA,SAAO,EAAE,MAAM,aAAa,QAAQ;AACxC;AAMO,SAAS,gBACZ,QACA,MACA,SACA,MACM;AACN,QAAM,QAAQ,QAAQ,IAAI,CAAC,SAAS,QAAQ,KAAK,IAAI,CAAC,OAAO,KAAK,IAAI,EAAE;AACxE,SAAO,YAAY,MAAM,WAAW,IAAI,MAAM,QAAQ,MAAM;AAAA,EAA0B,MAAM,KAAK,IAAI,CAAC;AAC1G;",
|
|
6
5
|
"names": []
|
|
7
6
|
}
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __create = Object.create;
|
|
3
|
+
var __defProp = Object.defineProperty;
|
|
4
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
5
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
7
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
8
|
+
var __export = (target, all) => {
|
|
9
|
+
for (var name in all)
|
|
10
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
11
|
+
};
|
|
12
|
+
var __copyProps = (to, from, except, desc) => {
|
|
13
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
14
|
+
for (let key of __getOwnPropNames(from))
|
|
15
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
16
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
17
|
+
}
|
|
18
|
+
return to;
|
|
19
|
+
};
|
|
20
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
21
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
22
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
23
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
24
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
25
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
26
|
+
mod
|
|
27
|
+
));
|
|
28
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
29
|
+
var operationCli_exports = {};
|
|
30
|
+
__export(operationCli_exports, {
|
|
31
|
+
folderPath: () => folderPath,
|
|
32
|
+
preview: () => preview,
|
|
33
|
+
readJsonInput: () => readJsonInput,
|
|
34
|
+
readJsonObject: () => readJsonObject,
|
|
35
|
+
repeatable: () => repeatable,
|
|
36
|
+
report: () => report,
|
|
37
|
+
wholeNumber: () => wholeNumber,
|
|
38
|
+
wholeNumbers: () => wholeNumbers
|
|
39
|
+
});
|
|
40
|
+
module.exports = __toCommonJS(operationCli_exports);
|
|
41
|
+
var fs = __toESM(require("fs"));
|
|
42
|
+
var import_commander = require("commander");
|
|
43
|
+
var import_errors = require("../operations/errors");
|
|
44
|
+
var import_logger = require("./logger");
|
|
45
|
+
function wholeNumber(value) {
|
|
46
|
+
if (!/^\d+$/.test(value)) throw new import_commander.InvalidArgumentError("Expected a whole number.");
|
|
47
|
+
return Number(value);
|
|
48
|
+
}
|
|
49
|
+
function folderPath(value) {
|
|
50
|
+
const segments = value.split("/").map((segment) => segment.trim()).filter((segment) => segment !== "");
|
|
51
|
+
if (segments.length === 0) throw new import_commander.InvalidArgumentError('Expected a path such as "Dashboards/Reports".');
|
|
52
|
+
return segments;
|
|
53
|
+
}
|
|
54
|
+
function wholeNumbers(value) {
|
|
55
|
+
return value.split(",").map((id) => wholeNumber(id.trim()));
|
|
56
|
+
}
|
|
57
|
+
function repeatable(value, previous = []) {
|
|
58
|
+
return [...previous, value];
|
|
59
|
+
}
|
|
60
|
+
function readJsonInput(file) {
|
|
61
|
+
try {
|
|
62
|
+
return JSON.parse(fs.readFileSync(file, "utf-8"));
|
|
63
|
+
} catch (error) {
|
|
64
|
+
const reason = error instanceof Error ? error.message : String(error);
|
|
65
|
+
throw new import_errors.OperationError(`Cannot read --input ${file}: ${reason}`, "VALIDATION_ERROR");
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
function readJsonObject(file) {
|
|
69
|
+
const parsed = readJsonInput(file);
|
|
70
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
|
|
71
|
+
throw new import_errors.OperationError(`--input ${file} must hold a JSON object`, "VALIDATION_ERROR");
|
|
72
|
+
}
|
|
73
|
+
return parsed;
|
|
74
|
+
}
|
|
75
|
+
function report(tenant, result, json, human) {
|
|
76
|
+
if (json) {
|
|
77
|
+
console.log(JSON.stringify({ tenant, ...result }, null, 2));
|
|
78
|
+
} else {
|
|
79
|
+
human();
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
function preview(tenant, json, warning, what, details = []) {
|
|
83
|
+
import_logger.logger.warning(warning);
|
|
84
|
+
for (const detail of details) import_logger.logger.dim(` ${detail}`);
|
|
85
|
+
import_logger.logger.dim("Nothing was changed. Run it again with -y to go ahead.");
|
|
86
|
+
if (json) {
|
|
87
|
+
console.log(JSON.stringify({ tenant, preview: true, ...what }, null, 2));
|
|
88
|
+
}
|
|
89
|
+
process.exit(0);
|
|
90
|
+
}
|
|
91
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
92
|
+
0 && (module.exports = {
|
|
93
|
+
folderPath,
|
|
94
|
+
preview,
|
|
95
|
+
readJsonInput,
|
|
96
|
+
readJsonObject,
|
|
97
|
+
repeatable,
|
|
98
|
+
report,
|
|
99
|
+
wholeNumber,
|
|
100
|
+
wholeNumbers
|
|
101
|
+
});
|
|
102
|
+
//# sourceMappingURL=operationCli.js.map
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../src/utils/operationCli.ts"],
|
|
4
|
+
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAKA,SAAoB;AACpB,uBAAqC;AACrC,oBAA+B;AAC/B,oBAAuB;AAG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