farseer-cli 1.10.3 → 1.11.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +5 -0
- package/dist/commands/app.js +41 -42
- package/dist/commands/app.js.map +2 -2
- package/dist/commands/apps.js +3 -3
- package/dist/commands/apps.js.map +2 -2
- package/dist/commands/cells.js +3 -3
- package/dist/commands/cells.js.map +2 -2
- package/dist/commands/config.js +23 -15
- package/dist/commands/config.js.map +2 -2
- package/dist/commands/dashboards.js +3 -3
- package/dist/commands/dashboards.js.map +2 -2
- package/dist/commands/dimensions.js +3 -3
- package/dist/commands/dimensions.js.map +2 -2
- package/dist/commands/files.js +5 -4
- package/dist/commands/files.js.map +2 -2
- package/dist/commands/formula.js +3 -3
- package/dist/commands/formula.js.map +2 -2
- package/dist/commands/list.js +5 -4
- package/dist/commands/list.js.map +2 -2
- package/dist/commands/login.js +6 -5
- package/dist/commands/login.js.map +2 -2
- package/dist/commands/model.js +5 -4
- package/dist/commands/model.js.map +2 -2
- package/dist/commands/push.js +5 -7
- package/dist/commands/push.js.map +2 -2
- package/dist/commands/run.js +13 -15
- package/dist/commands/run.js.map +2 -2
- package/dist/commands/sheets.js +3 -3
- package/dist/commands/sheets.js.map +2 -2
- package/dist/commands/variables.js +5 -4
- package/dist/commands/variables.js.map +2 -2
- package/dist/mcp/index.js +1 -1
- package/dist/mcp/index.js.map +2 -2
- package/dist/mcp/tools/appTools.js +38 -23
- package/dist/mcp/tools/appTools.js.map +2 -2
- package/dist/mcp/tools/dataTools.js +5 -2
- package/dist/mcp/tools/dataTools.js.map +2 -2
- package/dist/mcp/tools/modelTools.js +45 -48
- package/dist/mcp/tools/modelTools.js.map +2 -2
- package/dist/mcp/tools/runTools.js +12 -7
- package/dist/mcp/tools/runTools.js.map +2 -2
- package/dist/mcp/utils/helpers.js +41 -0
- package/dist/mcp/utils/helpers.js.map +2 -2
- package/dist/mcp/utils/session.js +2 -2
- package/dist/mcp/utils/session.js.map +2 -2
- package/dist/services/appSyncService.js.map +1 -1
- package/dist/services/apps.js +149 -0
- package/dist/services/apps.js.map +7 -0
- package/dist/services/authErrors.js +77 -0
- package/dist/services/authErrors.js.map +7 -0
- package/dist/services/configService.js +7 -4
- package/dist/services/configService.js.map +2 -2
- package/dist/services/credentials.js +87 -0
- package/dist/services/credentials.js.map +7 -0
- package/dist/services/farseerService.js +247 -123
- package/dist/services/farseerService.js.map +2 -2
- package/dist/services/httpError.js +35 -0
- package/dist/services/httpError.js.map +7 -0
- package/dist/services/modelExport.js +63 -0
- package/dist/services/modelExport.js.map +7 -0
- package/dist/services/organisation.js +88 -0
- package/dist/services/organisation.js.map +7 -0
- package/dist/services/preflight.js +10 -13
- package/dist/services/preflight.js.map +2 -2
- package/dist/services/syncService.js +2 -2
- package/dist/services/syncService.js.map +2 -2
- package/dist/utils/appResolver.js +63 -0
- package/dist/utils/appResolver.js.map +7 -0
- package/dist/utils/constants.js +2 -5
- package/dist/utils/constants.js.map +2 -2
- package/dist/utils/fileLogger.js +24 -1
- package/dist/utils/fileLogger.js.map +2 -2
- package/dist/utils/folderMatch.js +49 -0
- package/dist/utils/folderMatch.js.map +7 -0
- package/dist/utils/helpers.js +98 -1
- package/dist/utils/helpers.js.map +3 -3
- package/dist/utils/syncScope.js +44 -0
- package/dist/utils/syncScope.js.map +7 -0
- package/docs/api-reference.md +13 -1
- package/package.json +1 -1
- package/dist/services/farseerApi.js +0 -716
- package/dist/services/farseerApi.js.map +0 -7
- package/dist/services/farseerFactory.js +0 -276
- package/dist/services/farseerFactory.js.map +0 -7
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../src/services/apps.ts"],
|
|
4
|
+
"sourcesContent": ["/**\n * Apps (Remote Jobs): their shape, and the rules over it.\n *\n * What belongs here is decided by dependency direction, not by I/O: nothing in\n * this module constructs a client or reads a credential. applySourceFolderChange\n * does make a call, but through an injected one-method resolver, so it stays\n * testable without one.\n */\n\nimport chalk from 'chalk';\nimport * as farseer from 'farseer-client';\n\nexport type AppArgumentDataType = 'string' | 'boolean';\n\nexport interface AppArgument {\n name: string;\n dataType: AppArgumentDataType;\n fixed?: boolean;\n options?: string[];\n defaultValue?: string;\n secret?: boolean;\n}\n\nexport interface AppScriptFile {\n id: string;\n name: string;\n}\n\n// A resolved source folder: its node id (to set on the app) plus the script\n// files it contains (to validate an entrypoint lives inside it).\nexport interface SourceFolderResolution {\n id: number;\n scripts: AppScriptFile[];\n}\n\nexport interface RemoteApp {\n id: number;\n name: string;\n description: string;\n expectedArguments: AppArgument[];\n status: string;\n lastHeartbeat: string;\n mainScriptFileId: string | null;\n scriptFiles?: AppScriptFile[];\n sourceFolderId?: number;\n schedule?: string | null;\n runnerName?: string | null;\n runnerImage?: string | null;\n predefinedActions: unknown[];\n}\n\n// The fields a Remote Job update writes. The backend PUT replaces the whole\n// row, so any field omitted here is reset to its default (args/predefined \u2192\n// empty, the rest \u2192 null). `mergeAppUpdate` exists so a caller that only wants\n// to touch one field doesn't silently wipe the others.\nexport interface UpdateAppPayload {\n name: string;\n description: string;\n expectedArguments: AppArgument[];\n mainScriptFileId: string | null;\n sourceFolderId: number | null;\n schedule: string | null;\n runnerName: string | null;\n runnerImage: string | null;\n predefinedActions: unknown[];\n}\n\n// `scriptFileIds` is accepted from callers for backwards compatibility but is\n// never sent \u2014 the backend ignores it (scripts derive from the source folder).\nexport type AppUpdateChanges = Partial<UpdateAppPayload> & { scriptFileIds?: string[] };\n\n/**\n * Overlay a caller's changes onto an app's current state to build a full,\n * non-destructive update payload. Every field the caller leaves out keeps its\n * current value \u2014 so changing one setting never clears the others.\n */\nexport function mergeAppUpdate(current: RemoteApp, changes: AppUpdateChanges): UpdateAppPayload {\n return {\n name: changes.name ?? current.name,\n description: changes.description ?? current.description ?? '',\n expectedArguments: changes.expectedArguments ?? current.expectedArguments ?? [],\n mainScriptFileId: changes.mainScriptFileId ?? current.mainScriptFileId ?? null,\n sourceFolderId: changes.sourceFolderId ?? current.sourceFolderId ?? null,\n schedule: changes.schedule ?? current.schedule ?? null,\n runnerName: changes.runnerName ?? current.runnerName ?? null,\n runnerImage: changes.runnerImage ?? current.runnerImage ?? null,\n predefinedActions: changes.predefinedActions ?? current.predefinedActions ?? [],\n };\n}\n\n/**\n * Find a script in a source folder's file list by its exact name. Farseer file\n * names are case-sensitive \u2014 two files differing only in case can coexist in a\n * folder \u2014 so matching is exact, never case-folded, to avoid resolving an\n * entrypoint to the wrong file. Resolution is folder-scoped, never tenant-wide,\n * so a same-named file in another folder can't be picked by accident. Returns\n * undefined when the name isn't in the folder.\n */\nexport function findScriptInFolder(folderScripts: AppScriptFile[], name: string): AppScriptFile | undefined {\n return folderScripts.find((s) => s.name === name);\n}\n\n// The one client capability applySourceFolderChange needs. Kept minimal (not the\n// whole client) so it is trivial to unit-test with a fake resolver.\nexport interface SourceFolderResolver {\n resolveSourceFolder(relativePath: string): Promise<SourceFolderResolution | null>;\n}\n\n// Selects only how an error is presented \u2014 dimming, and `--flag` (CLI) vs param\n// (MCP) wording. It is a pure UX knob: the decision, the ids written to `changes`,\n// and the success/failure outcome are identical for both values. Never branch\n// functionality on it.\nexport type ConfigureCaller = 'cli' | 'mcp';\n\n/**\n * Resolve the source-folder / entrypoint settings for an `app configure` and\n * write the resulting ids into `changes`, applying the rule that an app's\n * scripts derive from its source folder and the entrypoint must be a file in\n * that folder. `sourceFolder` (a path under Files/) switches the folder;\n * otherwise the entrypoint is validated against the app's current folder. Moving\n * the folder must not orphan the entrypoint: if the current entrypoint isn't in\n * the new folder and the caller didn't supply one, the request is rejected \u2014 the\n * entrypoint is never silently cleared or relocated.\n *\n * Returns an error message for the caller to surface (and `changes` is left\n * untouched), or null once the ids have been written. The decision lives here so\n * the CLI and MCP paths can't drift.\n */\nexport async function applySourceFolderChange(\n client: SourceFolderResolver,\n app: Pick<RemoteApp, 'scriptFiles' | 'mainScriptFileId'>,\n changes: AppUpdateChanges,\n options: { sourceFolder?: string; entrypoint?: string },\n caller: ConfigureCaller,\n): Promise<string | null> {\n const cli = caller === 'cli';\n // Secondary guidance lines are dimmed in the terminal; plain for the MCP tool.\n const hint = (text: string) => (cli ? chalk.dim(text) : text);\n\n let folderScripts = app.scriptFiles ?? [];\n let sourceFolderId: number | undefined;\n\n if (options.sourceFolder) {\n // A failed request is deliberately not caught: \"no such folder\" is an\n // answer, and a 500 or a dropped connection is not one. Both callers\n // surface the throw with the status intact.\n const resolved = await client.resolveSourceFolder(options.sourceFolder);\n if (!resolved) {\n return [\n `Source folder not found under Files/: ${options.sourceFolder}`,\n hint('Use a path relative to Files/, e.g. \"Scripts/MyApp\".'),\n ].join('\\n');\n }\n sourceFolderId = resolved.id;\n folderScripts = resolved.scripts;\n\n // Moving the folder must not leave the entrypoint pointing outside it.\n if (!options.entrypoint && app.mainScriptFileId) {\n const stillThere = folderScripts.some((s) => s.id === app.mainScriptFileId);\n if (!stillThere) {\n const files = folderScripts.map((s) => s.name).join(', ') || '(none)';\n return [\n \"The app's current entrypoint is not in the new source folder.\",\n hint(\n cli\n ? 'Pass --entrypoint <script> (a file in the new folder) in the same command.'\n : 'Pass \"entrypoint\" (a file in the new folder) in the same call.',\n ),\n hint(`Files in this folder: ${files}`),\n ].join('\\n');\n }\n }\n }\n\n let mainScriptFileId: string | undefined;\n if (options.entrypoint) {\n const match = findScriptInFolder(folderScripts, options.entrypoint);\n if (!match) {\n const files = folderScripts.map((s) => s.name).join(', ') || '(none)';\n const lines = [\n `Entrypoint not found in the source folder: ${options.entrypoint}`,\n hint(`Files in this folder: ${files}`),\n ];\n if (!options.sourceFolder) {\n lines.push(\n hint(\n cli\n ? 'To use a file from another folder, set it first with --source-folder <path>.'\n : 'To use a file from another folder, pass sourceFolder first.',\n ),\n );\n }\n return lines.join('\\n');\n }\n mainScriptFileId = match.id;\n }\n\n // Apply only after every check passes, so a rejected request never partially\n // mutates `changes`.\n if (sourceFolderId !== undefined) {\n changes.sourceFolderId = sourceFolderId;\n }\n if (mainScriptFileId !== undefined) {\n changes.mainScriptFileId = mainScriptFileId;\n }\n return null;\n}\n\n// `reference` (the Remote Job id) is deliberately the only id here \u2014 apps also\n// have a folder-item id, in an overlapping number space, and carrying both is\n// what let `app delete` destroy unrelated objects.\nexport interface AppListItem {\n name: string;\n type: string;\n reference: string;\n}\n\nexport const REMOTE_JOB_ITEM_TYPE = farseer.FolderItemType.RemoteJob;\n\n// A `folders.resolveItems` result: `id` is the folder-item id, `reference` the\n// id in the item's own domain (for REMOTE_JOB, the Remote Job id).\nexport interface ResolvedFolderItem {\n id: number;\n name: string;\n type: string;\n reference: string;\n}\n\nexport function remoteJobReverseReferences(remoteJobIds: readonly string[]): farseer.ReverseReference[] {\n return remoteJobIds.map((reference) => ({ reference, type: REMOTE_JOB_ITEM_TYPE }));\n}\n\n// A deliberate refusal from the delete guard, as distinct from a transport\n// failure. Callers surface it as a validation error, not a retryable one:\n// nothing was deleted and retrying cannot change that.\nexport class AppDeleteRefusedError extends Error {}\n\n/**\n * Pick the folder-item id to delete for an app, from the `resolveItems` response.\n *\n * Remote Job ids and folder-item ids overlap \u2014 the low folder ids are the roots\n * (13 = Files, 15 = Apps) \u2014 so posting a Remote Job id to `deleteItems` deletes\n * whichever unrelated node owns that number. `resolveItems` is type-scoped\n * server-side; these checks make sure a server change can't widen that.\n */\nexport function resolveAppItemNodeId(remoteJobId: string, items: readonly ResolvedFolderItem[]): number {\n const matches = items.filter((item) => item.reference === remoteJobId);\n\n if (matches.length === 0) {\n throw new AppDeleteRefusedError(`No app found for Remote Job id ${remoteJobId} \u2014 nothing was deleted.`);\n }\n if (matches.length > 1) {\n throw new AppDeleteRefusedError(\n `Remote Job id ${remoteJobId} resolved to ${matches.length} folder items \u2014 refusing to delete.`,\n );\n }\n\n const item = matches[0];\n if (item.type !== REMOTE_JOB_ITEM_TYPE) {\n throw new AppDeleteRefusedError(\n `Refusing to delete: Remote Job id ${remoteJobId} resolved to a ${item.type} ` +\n `(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AU,MAAM,OAAO,CAACC,UAASA,MAAK,cAAc,WAAW;AAErE,MAAI,QAAQ,WAAW,GAAG;AACtB,UAAM,IAAI,sBAAsB,kCAAkC,WAAW,8BAAyB;AAAA,EAC1G;AACA,MAAI,QAAQ,SAAS,GAAG;AACpB,UAAM,IAAI;AAAA,MACN,iBAAiB,WAAW,gBAAgB,QAAQ,MAAM;AAAA,IAC9D;AAAA,EACJ;AAEA,QAAM,OAAO,QAAQ,CAAC;AACtB,MAAI,KAAK,SAAS,sBAAsB;AACpC,UAAM,IAAI;AAAA,MACN,qCAAqC,WAAW,kBAAkB,KAAK,IAAI,MAClE,KAAK,IAAI;AAAA,IACtB;AAAA,EACJ;AAEA,SAAO,KAAK;AAChB;",
|
|
6
|
+
"names": ["chalk", "item"]
|
|
7
|
+
}
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
var authErrors_exports = {};
|
|
20
|
+
__export(authErrors_exports, {
|
|
21
|
+
isAuthError: () => isAuthError,
|
|
22
|
+
isTenantNotFoundError: () => isTenantNotFoundError,
|
|
23
|
+
mentionsUnknownTenant: () => mentionsUnknownTenant,
|
|
24
|
+
showLoginPrompt: () => showLoginPrompt
|
|
25
|
+
});
|
|
26
|
+
module.exports = __toCommonJS(authErrors_exports);
|
|
27
|
+
var import_logger = require("../utils/logger");
|
|
28
|
+
function isTenantNotFoundError(error) {
|
|
29
|
+
return error instanceof Error && mentionsUnknownTenant(error.message);
|
|
30
|
+
}
|
|
31
|
+
function mentionsUnknownTenant(text) {
|
|
32
|
+
if (!text) {
|
|
33
|
+
return false;
|
|
34
|
+
}
|
|
35
|
+
const msg = text.toLowerCase();
|
|
36
|
+
return msg.includes("does not exist") && msg.includes("tenant");
|
|
37
|
+
}
|
|
38
|
+
function isAuthError(error) {
|
|
39
|
+
if (isTenantNotFoundError(error)) {
|
|
40
|
+
return false;
|
|
41
|
+
}
|
|
42
|
+
const status = statusOf(error) ?? statusOf(error?.cause);
|
|
43
|
+
if (status !== void 0) {
|
|
44
|
+
if (status === 401) {
|
|
45
|
+
return true;
|
|
46
|
+
}
|
|
47
|
+
return status === 403 && error instanceof Error;
|
|
48
|
+
}
|
|
49
|
+
if (error instanceof Error) {
|
|
50
|
+
return mentionsAuthStatus(error.message);
|
|
51
|
+
}
|
|
52
|
+
return false;
|
|
53
|
+
}
|
|
54
|
+
function mentionsAuthStatus(message) {
|
|
55
|
+
const msg = message.toLowerCase();
|
|
56
|
+
return /(?:code|status|http)\s*:?\s*(?:401|403)\b/.test(msg) || msg.includes("unauthorized") || msg.includes("forbidden");
|
|
57
|
+
}
|
|
58
|
+
function statusOf(value) {
|
|
59
|
+
const status = value?.status;
|
|
60
|
+
return typeof status === "number" ? status : void 0;
|
|
61
|
+
}
|
|
62
|
+
function showLoginPrompt(tenant) {
|
|
63
|
+
import_logger.logger.error("Authentication required.");
|
|
64
|
+
if (tenant) {
|
|
65
|
+
import_logger.logger.dim(`No valid credentials found for tenant "${tenant}".`);
|
|
66
|
+
}
|
|
67
|
+
import_logger.logger.info('Run "farseer login" to authenticate via browser.');
|
|
68
|
+
import_logger.logger.dim('Or use "farseer config set <tenant> --api-key <key>" for API key auth.');
|
|
69
|
+
}
|
|
70
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
71
|
+
0 && (module.exports = {
|
|
72
|
+
isAuthError,
|
|
73
|
+
isTenantNotFoundError,
|
|
74
|
+
mentionsUnknownTenant,
|
|
75
|
+
showLoginPrompt
|
|
76
|
+
});
|
|
77
|
+
//# sourceMappingURL=authErrors.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../src/services/authErrors.ts"],
|
|
4
|
+
"sourcesContent": ["/**\n * Telling an authentication failure from everything else.\n *\n * The 403 is the hard one: the backend answers it both for a credential it will\n * not accept and for a tenant the organisation does not have. The second is not\n * a credentials problem \u2014 every tenant-scoped request carries X-TENANT-ID, and\n * an organisation without that tenant refuses on that alone \u2014 so \"log in again\"\n * would send the user to fix the one thing that works. Only the body tells them\n * apart, which is why this is a shared decision and not a status check at each\n * call site.\n */\n\nimport { logger } from '../utils/logger';\n\n/** The wrong-organisation 403: `{\"code\":\"Forbidden\",\"message\":\"Tenant with id <t> does not exist\"}`. */\nexport function isTenantNotFoundError(error: unknown): boolean {\n return error instanceof Error && mentionsUnknownTenant(error.message);\n}\n\n/**\n * Apart from isTenantNotFoundError because that sentence reaches us two ways:\n * inside an Error the SDK threw, and as the `message` of a 403 body the\n * organisation probe reads straight off the response.\n */\nexport function mentionsUnknownTenant(text: string | undefined): boolean {\n if (!text) {\n return false;\n }\n const msg = text.toLowerCase();\n return msg.includes('does not exist') && msg.includes('tenant');\n}\n\nexport function isAuthError(error: unknown): boolean {\n if (isTenantNotFoundError(error)) {\n return false;\n }\n // Status first; the message is only a fallback, and messages now carry\n // folder paths and Remote Job ids \u2014 \"Failed to load app 1403\" is not a 403.\n const status = statusOf(error) ?? statusOf((error as { cause?: unknown } | null)?.cause);\n if (status !== undefined) {\n if (status === 401) {\n return true;\n }\n // The exclusion above reads a message and a raw Response carries none,\n // so for a bare 403 it never ran \u2014 claiming an auth failure here would\n // guess against the case this module exists to catch.\n return status === 403 && error instanceof Error;\n }\n if (error instanceof Error) {\n return mentionsAuthStatus(error.message);\n }\n return false;\n}\n\n/**\n * Only reached when nothing carried a status. The number must be presented as\n * one to count: a bare `includes('403')` read a folder named `403-reports` as\n * an auth failure.\n */\nfunction mentionsAuthStatus(message: string): boolean {\n const msg = message.toLowerCase();\n return (\n /(?:code|status|http)\\s*:?\\s*(?:401|403)\\b/.test(msg) ||\n msg.includes('unauthorized') ||\n msg.includes('forbidden')\n );\n}\n\n/** The HTTP status of an HttpError or a raw fetch Response, when there is one. */\nfunction statusOf(value: unknown): number | undefined {\n const status = (value as { status?: unknown } | null | undefined)?.status;\n return typeof status === 'number' ? status : undefined;\n}\n\nexport function showLoginPrompt(tenant?: string): void {\n logger.error('Authentication required.');\n if (tenant) {\n logger.dim(`No valid credentials found for tenant \"${tenant}\".`);\n }\n logger.info('Run \"farseer login\" to authenticate via browser.');\n logger.dim('Or use \"farseer config set <tenant> --api-key <key>\" for API key auth.');\n}\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAYA,oBAAuB;AAGhB,SAAS,sBAAsB,OAAyB;AAC3D,SAAO,iBAAiB,SAAS,sBAAsB,MAAM,OAAO;AACxE;AAOO,SAAS,sBAAsB,MAAmC;AACrE,MAAI,CAAC,MAAM;AACP,WAAO;AAAA,EACX;AACA,QAAM,MAAM,KAAK,YAAY;AAC7B,SAAO,IAAI,SAAS,gBAAgB,KAAK,IAAI,SAAS,QAAQ;AAClE;AAEO,SAAS,YAAY,OAAyB;AACjD,MAAI,sBAAsB,KAAK,GAAG;AAC9B,WAAO;AAAA,EACX;AAGA,QAAM,SAAS,SAAS,KAAK,KAAK,SAAU,OAAsC,KAAK;AACvF,MAAI,WAAW,QAAW;AACtB,QAAI,WAAW,KAAK;AAChB,aAAO;AAAA,IACX;AAIA,WAAO,WAAW,OAAO,iBAAiB;AAAA,EAC9C;AACA,MAAI,iBAAiB,OAAO;AACxB,WAAO,mBAAmB,MAAM,OAAO;AAAA,EAC3C;AACA,SAAO;AACX;AAOA,SAAS,mBAAmB,SAA0B;AAClD,QAAM,MAAM,QAAQ,YAAY;AAChC,SACI,4CAA4C,KAAK,GAAG,KACpD,IAAI,SAAS,cAAc,KAC3B,IAAI,SAAS,WAAW;AAEhC;AAGA,SAAS,SAAS,OAAoC;AAClD,QAAM,SAAU,OAAmD;AACnE,SAAO,OAAO,WAAW,WAAW,SAAS;AACjD;AAEO,SAAS,gBAAgB,QAAuB;AACnD,uBAAO,MAAM,0BAA0B;AACvC,MAAI,QAAQ;AACR,yBAAO,IAAI,0CAA0C,MAAM,IAAI;AAAA,EACnE;AACA,uBAAO,KAAK,kDAAkD;AAC9D,uBAAO,IAAI,wEAAwE;AACvF;",
|
|
6
|
+
"names": []
|
|
7
|
+
}
|
|
@@ -52,7 +52,7 @@ const CONFIG_DIR = path.join(os.homedir(), ".farseer");
|
|
|
52
52
|
const CONFIG_FILE = path.join(CONFIG_DIR, "config.json");
|
|
53
53
|
function ensureConfigDir() {
|
|
54
54
|
if (!fs.existsSync(CONFIG_DIR)) {
|
|
55
|
-
fs.mkdirSync(CONFIG_DIR, { recursive: true });
|
|
55
|
+
fs.mkdirSync(CONFIG_DIR, { recursive: true, mode: 448 });
|
|
56
56
|
}
|
|
57
57
|
}
|
|
58
58
|
function getDefaultConfig() {
|
|
@@ -75,7 +75,11 @@ function loadConfig() {
|
|
|
75
75
|
}
|
|
76
76
|
function saveConfig(config) {
|
|
77
77
|
ensureConfigDir();
|
|
78
|
-
fs.writeFileSync(CONFIG_FILE, JSON.stringify(config, null, 2), "utf-8");
|
|
78
|
+
fs.writeFileSync(CONFIG_FILE, JSON.stringify(config, null, 2), { encoding: "utf-8", mode: 384 });
|
|
79
|
+
try {
|
|
80
|
+
fs.chmodSync(CONFIG_FILE, 384);
|
|
81
|
+
} catch {
|
|
82
|
+
}
|
|
79
83
|
}
|
|
80
84
|
function getCredential(tenant) {
|
|
81
85
|
const config = loadConfig();
|
|
@@ -113,8 +117,7 @@ function clearUserAuth() {
|
|
|
113
117
|
config.userAuth = void 0;
|
|
114
118
|
saveConfig(config);
|
|
115
119
|
}
|
|
116
|
-
function isUserAuthValid() {
|
|
117
|
-
const auth = getUserAuth();
|
|
120
|
+
function isUserAuthValid(auth = getUserAuth()) {
|
|
118
121
|
if (!auth) return false;
|
|
119
122
|
const expiresAt = new Date(auth.expiresAt);
|
|
120
123
|
const bufferMs = 10 * 1e3;
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/services/configService.ts"],
|
|
4
|
-
"sourcesContent": ["import * as fs from 'fs';\nimport * as path from 'path';\nimport * as os from 'os';\n\nexport interface ApiKeyCredential {\n type: 'apiKey';\n tenantId: string;\n apiKey: string;\n basePath: string;\n}\n\nexport interface UserAuth {\n accessToken: string;\n refreshToken: string;\n expiresAt: string;\n tenant?: string; // Tenant used for login (Keycloak client ID)\n realm?: string; // Keycloak realm (default: master)\n}\n\n// Resolved { org, tenant } pair. No longer persisted as a machine-global\n// default (that made it impossible to work on two tenants in two shells and\n// silently retargeted bare commands). It survives only as the shape the MCP\n// per-process pin and the CLI's env-based resolution both pass around.\nexport interface CurrentCheckout {\n organisation: string; // For URL: https://<organisation>.farseer.io\n tenant: string; // For X-TENANT-ID header\n}\n\nexport interface SyncIncludes {\n extensions?: string[];\n folders?: string[];\n}\n\nexport interface FarseerConfig {\n credentials: Record<string, ApiKeyCredential>;\n userAuth?: UserAuth;\n tenantOrgMapping?: Record<string, string>; // Tenant -> Organisation mapping\n syncIncludes?: Record<string, SyncIncludes>; // Per-tenant sync includes\n}\n\nconst CONFIG_DIR = path.join(os.homedir(), '.farseer');\nconst CONFIG_FILE = path.join(CONFIG_DIR, 'config.json');\n\nfunction ensureConfigDir(): void {\n if (!fs.existsSync(CONFIG_DIR)) {\n fs.mkdirSync(CONFIG_DIR, { recursive: true });\n }\n}\n\nfunction getDefaultConfig(): FarseerConfig {\n return {\n credentials: {},\n userAuth: undefined,\n };\n}\n\nexport function loadConfig(): FarseerConfig {\n ensureConfigDir();\n\n if (!fs.existsSync(CONFIG_FILE)) {\n return getDefaultConfig();\n }\n\n try {\n const content = fs.readFileSync(CONFIG_FILE, 'utf-8');\n return JSON.parse(content) as FarseerConfig;\n } catch {\n return getDefaultConfig();\n }\n}\n\nexport function saveConfig(config: FarseerConfig): void {\n ensureConfigDir();\n fs.writeFileSync(CONFIG_FILE, JSON.stringify(config, null, 2), 'utf-8');\n}\n\nexport function getCredential(tenant: string): ApiKeyCredential | undefined {\n const config = loadConfig();\n return config.credentials[tenant];\n}\n\nexport function setCredential(tenant: string, credential: ApiKeyCredential): void {\n const config = loadConfig();\n config.credentials[tenant] = credential;\n saveConfig(config);\n}\n\nexport function removeCredential(tenant: string): boolean {\n const config = loadConfig();\n if (config.credentials[tenant]) {\n delete config.credentials[tenant];\n saveConfig(config);\n return true;\n }\n return false;\n}\n\nexport function listCredentials(): Record<string, ApiKeyCredential> {\n const config = loadConfig();\n return config.credentials;\n}\n\nexport function getUserAuth(): UserAuth | undefined {\n const config = loadConfig();\n return config.userAuth;\n}\n\nexport function setUserAuth(auth: UserAuth): void {\n const config = loadConfig();\n config.userAuth = auth;\n saveConfig(config);\n}\n\nexport function clearUserAuth(): void {\n const config = loadConfig();\n config.userAuth = undefined;\n saveConfig(config);\n}\n\nexport function isUserAuthValid(
|
|
5
|
-
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,SAAoB;AACpB,WAAsB;AACtB,SAAoB;AAsCpB,MAAM,aAAa,KAAK,KAAK,GAAG,QAAQ,GAAG,UAAU;AACrD,MAAM,cAAc,KAAK,KAAK,YAAY,aAAa;AAEvD,SAAS,kBAAwB;AAC7B,MAAI,CAAC,GAAG,WAAW,UAAU,GAAG;AAC5B,OAAG,UAAU,YAAY,EAAE,WAAW,
|
|
4
|
+
"sourcesContent": ["import * as fs from 'fs';\nimport * as path from 'path';\nimport * as os from 'os';\n\nexport interface ApiKeyCredential {\n type: 'apiKey';\n tenantId: string;\n apiKey: string;\n basePath: string;\n}\n\nexport interface UserAuth {\n accessToken: string;\n refreshToken: string;\n expiresAt: string;\n tenant?: string; // Tenant used for login (Keycloak client ID)\n realm?: string; // Keycloak realm (default: master)\n}\n\n// Resolved { org, tenant } pair. No longer persisted as a machine-global\n// default (that made it impossible to work on two tenants in two shells and\n// silently retargeted bare commands). It survives only as the shape the MCP\n// per-process pin and the CLI's env-based resolution both pass around.\nexport interface CurrentCheckout {\n organisation: string; // For URL: https://<organisation>.farseer.io\n tenant: string; // For X-TENANT-ID header\n}\n\nexport interface SyncIncludes {\n extensions?: string[];\n folders?: string[];\n}\n\nexport interface FarseerConfig {\n credentials: Record<string, ApiKeyCredential>;\n userAuth?: UserAuth;\n tenantOrgMapping?: Record<string, string>; // Tenant -> Organisation mapping\n syncIncludes?: Record<string, SyncIncludes>; // Per-tenant sync includes\n}\n\nconst CONFIG_DIR = path.join(os.homedir(), '.farseer');\nconst CONFIG_FILE = path.join(CONFIG_DIR, 'config.json');\n\nfunction ensureConfigDir(): void {\n if (!fs.existsSync(CONFIG_DIR)) {\n fs.mkdirSync(CONFIG_DIR, { recursive: true, mode: 0o700 });\n }\n}\n\nfunction getDefaultConfig(): FarseerConfig {\n return {\n credentials: {},\n userAuth: undefined,\n };\n}\n\nexport function loadConfig(): FarseerConfig {\n ensureConfigDir();\n\n if (!fs.existsSync(CONFIG_FILE)) {\n return getDefaultConfig();\n }\n\n try {\n const content = fs.readFileSync(CONFIG_FILE, 'utf-8');\n return JSON.parse(content) as FarseerConfig;\n } catch {\n return getDefaultConfig();\n }\n}\n\n/**\n * This file holds every stored API key plus the Keycloak refresh and access\n * tokens, so it is owner-only. `mode` on writeFileSync applies to a file being\n * created, not an existing one, and the token refresh rewrites this file from\n * every request \u2014 so an existing 0644 file is corrected explicitly rather than\n * staying world-readable for the life of the install.\n */\nexport function saveConfig(config: FarseerConfig): void {\n ensureConfigDir();\n fs.writeFileSync(CONFIG_FILE, JSON.stringify(config, null, 2), { encoding: 'utf-8', mode: 0o600 });\n try {\n fs.chmodSync(CONFIG_FILE, 0o600);\n } catch {\n // A filesystem that will not take a mode (a Windows volume, a mounted\n // share) is not a reason to fail the write the caller asked for.\n }\n}\n\nexport function getCredential(tenant: string): ApiKeyCredential | undefined {\n const config = loadConfig();\n return config.credentials[tenant];\n}\n\nexport function setCredential(tenant: string, credential: ApiKeyCredential): void {\n const config = loadConfig();\n config.credentials[tenant] = credential;\n saveConfig(config);\n}\n\nexport function removeCredential(tenant: string): boolean {\n const config = loadConfig();\n if (config.credentials[tenant]) {\n delete config.credentials[tenant];\n saveConfig(config);\n return true;\n }\n return false;\n}\n\nexport function listCredentials(): Record<string, ApiKeyCredential> {\n const config = loadConfig();\n return config.credentials;\n}\n\nexport function getUserAuth(): UserAuth | undefined {\n const config = loadConfig();\n return config.userAuth;\n}\n\nexport function setUserAuth(auth: UserAuth): void {\n const config = loadConfig();\n config.userAuth = auth;\n saveConfig(config);\n}\n\nexport function clearUserAuth(): void {\n const config = loadConfig();\n config.userAuth = undefined;\n saveConfig(config);\n}\n\n/**\n * Pass `auth` when you already have it. The middleware asks this on every\n * request and re-reading the config file to answer it means a second\n * existsSync + readFileSync + JSON.parse per call.\n */\nexport function isUserAuthValid(auth: UserAuth | undefined = getUserAuth()): boolean {\n if (!auth) return false;\n\n const expiresAt = new Date(auth.expiresAt);\n // Add 10 second buffer to proactively refresh before actual expiry\n // Note: Keycloak tokens typically last 60 seconds, so buffer must be small\n const bufferMs = 10 * 1000;\n return expiresAt.getTime() > Date.now() + bufferMs;\n}\n\nexport function generateBasePath(organisation: string): string {\n return `https://${organisation}.farseer.io/api/v3`;\n}\n\n// There is deliberately no persisted \"current tenant\" any more. A command's\n// target comes from an explicit argument or the FARSEER_TENANT env var (see\n// getEnvCheckout in utils/helpers.ts), and the CLI errors if neither is set\n// rather than falling back to a machine-global default. The tenant->org\n// mapping below is kept: it lets `export FARSEER_TENANT=<tenant>` resolve the\n// org on its own, so only new org != tenant tenants need FARSEER_ORG too.\n\n// Tenant-Organisation mapping\nexport function saveTenantOrgMapping(tenant: string, organisation: string): void {\n const config = loadConfig();\n if (!config.tenantOrgMapping) {\n config.tenantOrgMapping = {};\n }\n config.tenantOrgMapping[tenant] = organisation;\n saveConfig(config);\n}\n\nexport function getTenantOrg(tenant: string): string | undefined {\n const config = loadConfig();\n return config.tenantOrgMapping?.[tenant];\n}\n\n// Sync includes management\nexport function getSyncIncludes(tenant: string): SyncIncludes | null {\n const config = loadConfig();\n return config.syncIncludes?.[tenant] ?? null;\n}\n\nexport function setSyncIncludes(tenant: string, includes: SyncIncludes): void {\n const config = loadConfig();\n if (!config.syncIncludes) {\n config.syncIncludes = {};\n }\n // Clean up empty arrays\n if (includes.extensions?.length === 0) delete includes.extensions;\n if (includes.folders?.length === 0) delete includes.folders;\n // Remove entry entirely if empty\n if (!includes.extensions && !includes.folders) {\n delete config.syncIncludes[tenant];\n } else {\n config.syncIncludes[tenant] = includes;\n }\n // Remove syncIncludes key if no tenants left\n if (Object.keys(config.syncIncludes).length === 0) {\n delete config.syncIncludes;\n }\n saveConfig(config);\n}\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,SAAoB;AACpB,WAAsB;AAC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O;AACH,WAAO,aAAa,MAAM,IAAI;AAAA,EAClC;AAEA,MAAI,OAAO,KAAK,OAAO,YAAY,EAAE,WAAW,GAAG;AAC/C,WAAO,OAAO;AAAA,EAClB;AACA,aAAW,MAAM;AACrB;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
var credentials_exports = {};
|
|
20
|
+
__export(credentials_exports, {
|
|
21
|
+
buildClient: () => buildClient,
|
|
22
|
+
getFreshAccessToken: () => import_farseerService2.getFreshAccessToken,
|
|
23
|
+
refreshAuth: () => refreshAuth,
|
|
24
|
+
resolveAuth: () => resolveAuth,
|
|
25
|
+
resolveAuthByProbe: () => resolveAuthByProbe
|
|
26
|
+
});
|
|
27
|
+
module.exports = __toCommonJS(credentials_exports);
|
|
28
|
+
var import_farseerService = require("./farseerService");
|
|
29
|
+
var import_configService = require("./configService");
|
|
30
|
+
var import_logger = require("../utils/logger");
|
|
31
|
+
var import_farseerService2 = require("./farseerService");
|
|
32
|
+
function jwtAuth(accessToken, organisation, tenant) {
|
|
33
|
+
return { kind: "jwt", accessToken, basePath: (0, import_configService.generateBasePath)(organisation), tenant };
|
|
34
|
+
}
|
|
35
|
+
function buildClient(auth) {
|
|
36
|
+
return new import_farseerService.FarseerService(auth);
|
|
37
|
+
}
|
|
38
|
+
async function resolveAuth(organisation, tenant) {
|
|
39
|
+
const accessToken = await (0, import_farseerService.getFreshAccessToken)();
|
|
40
|
+
if (accessToken) {
|
|
41
|
+
return jwtAuth(accessToken, organisation, tenant);
|
|
42
|
+
}
|
|
43
|
+
const credential = (0, import_configService.getCredential)(tenant);
|
|
44
|
+
return credential ? { kind: "apiKey", credential } : null;
|
|
45
|
+
}
|
|
46
|
+
async function resolveAuthByProbe(organisation, tenant) {
|
|
47
|
+
const accessToken = await (0, import_farseerService.getFreshAccessToken)();
|
|
48
|
+
if (accessToken) {
|
|
49
|
+
const auth = jwtAuth(accessToken, organisation, tenant);
|
|
50
|
+
if (await connects(auth)) {
|
|
51
|
+
return auth;
|
|
52
|
+
}
|
|
53
|
+
import_logger.logger.dim("JWT auth failed for this tenant, trying API key...");
|
|
54
|
+
}
|
|
55
|
+
const credential = (0, import_configService.getCredential)(tenant);
|
|
56
|
+
if (credential) {
|
|
57
|
+
const auth = { kind: "apiKey", credential };
|
|
58
|
+
if (await connects(auth)) {
|
|
59
|
+
return auth;
|
|
60
|
+
}
|
|
61
|
+
import_logger.logger.dim("API key auth failed.");
|
|
62
|
+
}
|
|
63
|
+
return null;
|
|
64
|
+
}
|
|
65
|
+
async function refreshAuth(auth) {
|
|
66
|
+
if (auth.kind === "apiKey") {
|
|
67
|
+
return auth;
|
|
68
|
+
}
|
|
69
|
+
const accessToken = await (0, import_farseerService.getFreshAccessToken)();
|
|
70
|
+
return accessToken ? { ...auth, accessToken } : null;
|
|
71
|
+
}
|
|
72
|
+
async function connects(auth) {
|
|
73
|
+
const connection = await buildClient(auth).checkConnection();
|
|
74
|
+
if (!connection.ok && connection.reason !== "rejected") {
|
|
75
|
+
import_logger.logger.dim(`The credential could not be checked: ${connection.message}`);
|
|
76
|
+
}
|
|
77
|
+
return connection.ok;
|
|
78
|
+
}
|
|
79
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
80
|
+
0 && (module.exports = {
|
|
81
|
+
buildClient,
|
|
82
|
+
getFreshAccessToken,
|
|
83
|
+
refreshAuth,
|
|
84
|
+
resolveAuth,
|
|
85
|
+
resolveAuthByProbe
|
|
86
|
+
});
|
|
87
|
+
//# sourceMappingURL=credentials.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../src/services/credentials.ts"],
|
|
4
|
+
"sourcesContent": ["/**\n * Deciding which credential a command runs on.\n *\n * A browser login is preferred when there is a usable one, a stored API key\n * otherwise. The decision is made once, as a ResolvedAuth, and the client is\n * built from that \u2014 nothing downstream re-derives it.\n */\n\nimport { FarseerService, getFreshAccessToken, type ResolvedAuth } from './farseerService';\nimport { getCredential, generateBasePath } from './configService';\nimport { logger } from '../utils/logger';\n\n// Defined next to the refresh it calls, re-exported where callers look for it.\nexport { getFreshAccessToken } from './farseerService';\n\n/**\n * Always the organisation that was typed. A stored key's basePath belongs to\n * that key; letting it stand in here made the host depend on whether a key\n * happened to be named after the organisation.\n */\nfunction jwtAuth(accessToken: string, organisation: string, tenant: string): ResolvedAuth {\n return { kind: 'jwt', accessToken, basePath: generateBasePath(organisation), tenant };\n}\n\nexport function buildClient(auth: ResolvedAuth): FarseerService {\n return new FarseerService(auth);\n}\n\n/** Pick by what's available. Nothing is sent, so it can't tell whether the credential works. */\nexport async function resolveAuth(organisation: string, tenant: string): Promise<ResolvedAuth | null> {\n const accessToken = await getFreshAccessToken();\n if (accessToken) {\n return jwtAuth(accessToken, organisation, tenant);\n }\n\n const credential = getCredential(tenant);\n return credential ? { kind: 'apiKey', credential } : null;\n}\n\n/**\n * Pick one that actually connects. The probe is the point: a key is the only\n * thing that still works once the organisation route is dead.\n */\nexport async function resolveAuthByProbe(organisation: string, tenant: string): Promise<ResolvedAuth | null> {\n const accessToken = await getFreshAccessToken();\n if (accessToken) {\n const auth = jwtAuth(accessToken, organisation, tenant);\n if (await connects(auth)) {\n return auth;\n }\n logger.dim('JWT auth failed for this tenant, trying API key...');\n }\n\n const credential = getCredential(tenant);\n if (credential) {\n const auth: ResolvedAuth = { kind: 'apiKey', credential };\n if (await connects(auth)) {\n return auth;\n }\n logger.dim('API key auth failed.');\n }\n\n return null;\n}\n\n/**\n * The same decision with a fresh browser token. A CLI command lives for one\n * request; an MCP server runs for hours, so the token is the part it re-takes.\n */\nexport async function refreshAuth(auth: ResolvedAuth): Promise<ResolvedAuth | null> {\n if (auth.kind === 'apiKey') {\n return auth;\n }\n const accessToken = await getFreshAccessToken();\n return accessToken ? { ...auth, accessToken } : null;\n}\n\nasync function connects(auth: ResolvedAuth): Promise<boolean> {\n const connection = await buildClient(auth).checkConnection();\n if (!connection.ok && connection.reason !== 'rejected') {\n // Nothing rejected the credential. Say so here: the caller's only\n // remaining move is \"no credential worked\", which blames the wrong thing.\n logger.dim(`The credential could not be checked: ${connection.message}`);\n }\n return connection.ok;\n}\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAQA,4BAAuE;AACvE,2BAAgD;AAChD,oBAAuB;AAGvB,IAAAA,yBAAoC;AAOpC,SAAS,QAAQ,aAAqB,cAAsB,QAA8B;AACtF,SAAO,EAAE,MAAM,OAAO,aAAa,cAAU,uCAAiB,YAAY,GAAG,OAAO;AACxF;AAEO,SAAS,YAAY,MAAoC;AAC5D,SAAO,IAAI,qCAAe,IAAI;AAClC;AAGA,eAAsB,YAAY,cAAsB,QAA8C;AAClG,QAAM,cAAc,UAAM,2CAAoB;AAC9C,MAAI,aAAa;AACb,WAAO,QAAQ,aAAa,cAAc,MA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