farseer-cli 1.16.0 → 1.18.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.
Files changed (61) hide show
  1. package/README.md +329 -1
  2. package/dist/commands/code.js +104 -0
  3. package/dist/commands/code.js.map +7 -0
  4. package/dist/commands/formula.js +16 -7
  5. package/dist/commands/formula.js.map +2 -2
  6. package/dist/commands/tool.js +120 -0
  7. package/dist/commands/tool.js.map +7 -0
  8. package/dist/index.js +21 -2
  9. package/dist/index.js.map +2 -2
  10. package/dist/mcp/tools/modelTools.js +65 -23
  11. package/dist/mcp/tools/modelTools.js.map +3 -3
  12. package/dist/mcp/tools/runTools.js +6 -2
  13. package/dist/mcp/tools/runTools.js.map +2 -2
  14. package/dist/mcp/utils/launchPin.js +1 -1
  15. package/dist/mcp/utils/launchPin.js.map +2 -2
  16. package/dist/pipeline/service.js +1 -1
  17. package/dist/pipeline/service.js.map +2 -2
  18. package/dist/services/codefirst/api.js +269 -0
  19. package/dist/services/codefirst/api.js.map +7 -0
  20. package/dist/services/codefirst/binaryDisk.js +67 -0
  21. package/dist/services/codefirst/binaryDisk.js.map +7 -0
  22. package/dist/services/codefirst/byteHashes.js +129 -0
  23. package/dist/services/codefirst/byteHashes.js.map +7 -0
  24. package/dist/services/codefirst/documents.js +563 -0
  25. package/dist/services/codefirst/documents.js.map +7 -0
  26. package/dist/services/codefirst/layoutBinaryProjection.js +974 -0
  27. package/dist/services/codefirst/layoutBinaryProjection.js.map +7 -0
  28. package/dist/services/codefirst/layoutCompose.js +593 -0
  29. package/dist/services/codefirst/layoutCompose.js.map +7 -0
  30. package/dist/services/codefirst/layoutCore.js +260 -0
  31. package/dist/services/codefirst/layoutCore.js.map +7 -0
  32. package/dist/services/codefirst/layoutPaths.js +492 -0
  33. package/dist/services/codefirst/layoutPaths.js.map +7 -0
  34. package/dist/services/codefirst/layoutProjection.js +995 -0
  35. package/dist/services/codefirst/layoutProjection.js.map +7 -0
  36. package/dist/services/codefirst/layoutReadback.js +2552 -0
  37. package/dist/services/codefirst/layoutReadback.js.map +7 -0
  38. package/dist/services/codefirst/layoutReadbackPlacement.js +1517 -0
  39. package/dist/services/codefirst/layoutReadbackPlacement.js.map +7 -0
  40. package/dist/services/codefirst/layoutReceipt.js +1592 -0
  41. package/dist/services/codefirst/layoutReceipt.js.map +7 -0
  42. package/dist/services/codefirst/layoutScan.js +882 -0
  43. package/dist/services/codefirst/layoutScan.js.map +7 -0
  44. package/dist/services/codefirst/output.js +179 -0
  45. package/dist/services/codefirst/output.js.map +7 -0
  46. package/dist/services/codefirst/types.js +17 -0
  47. package/dist/services/codefirst/types.js.map +7 -0
  48. package/dist/services/codefirst/workflow.js +581 -0
  49. package/dist/services/codefirst/workflow.js.map +7 -0
  50. package/dist/services/codefirst/workspace.js +310 -0
  51. package/dist/services/codefirst/workspace.js.map +7 -0
  52. package/dist/services/codefirst/workspaceLock.js +148 -0
  53. package/dist/services/codefirst/workspaceLock.js.map +7 -0
  54. package/dist/services/codefirst/workspaceRoot.js +147 -0
  55. package/dist/services/codefirst/workspaceRoot.js.map +7 -0
  56. package/dist/utils/formulaFilters.js +48 -0
  57. package/dist/utils/formulaFilters.js.map +7 -0
  58. package/dist/utils/logger.js +9 -3
  59. package/dist/utils/logger.js.map +2 -2
  60. package/docs/cli-guide.md +13 -0
  61. package/package.json +3 -2
package/README.md CHANGED
@@ -29,6 +29,7 @@ Command-line tool for managing Farseer Apps and scripts. Includes AI assistant i
29
29
  9. [File Structure](#file-structure)
30
30
  10. [Configuration](#configuration)
31
31
  11. [Troubleshooting](#troubleshooting)
32
+ 12. [Farseer as code (experimental)](#farseer-as-code-experimental)
32
33
 
33
34
  ---
34
35
 
@@ -727,7 +728,7 @@ Once configured, AI assistants have access to:
727
728
  - `farseer_list_variables` - List variables
728
729
  - `farseer_get_table` - Get table details
729
730
  - `farseer_get_variable` - Get variable details
730
- - `farseer_evaluate_formula` - Evaluate a formula expression with dimension filters. Variable names with spaces or special characters (e.g., "P&L") are auto-quoted.
731
+ - `farseer_evaluate_formula` - Evaluate one formula, or several in one request with `formulas`. Dimension filters apply to a single variable name, placed inside `SUM`; an expression carries its own. Variable names with spaces or `&` (e.g., "P&L") are auto-quoted; a name with other symbols, such as `-` or parentheses, has to be passed in double quotes.
731
732
  - `farseer_list_dimension_members` - List members of a dimension table (auto-CSV for 500+)
732
733
  - `farseer_manage_dimension_members` - Create or delete dimension members
733
734
  - `farseer_create_variable` - Create a new variable with dimensions and formula. Accepts rollupType in any case (e.g., "Sum", "average", "CLOSING STATE").
@@ -1071,6 +1072,333 @@ The tag version must match `package.json` or the pipeline will fail.
1071
1072
 
1072
1073
  ---
1073
1074
 
1075
+ ## Farseer as code (experimental)
1076
+
1077
+ Experimental: the commands, the workspace layout and the state file can still change.
1078
+ `farseer code` manages the whole model as files: folders, variables, dimension-table
1079
+ schemas, member sets, sheets, dashboards, shares, user groups, direct CLASS grants,
1080
+ labels, settings, dataset definitions, files, export configurations and remote jobs.
1081
+ Commit the readable JSON and the raw bytes beside it. Every `code` command needs a
1082
+ superuser credential, because the workspace holds the whole tenant.
1083
+
1084
+ It is a separate feature with its own workspace. The files/apps sync described above
1085
+ (`pull`, `push`, `status`, `diff`) keeps its own `farseer-apps/<tenant>/` directory and
1086
+ is not touched by any `code` command. Both can write the same uploaded script, so do not
1087
+ edit one script in both places.
1088
+
1089
+ `farseer code checkout [org] [tenant]` creates the workspace in the current directory. It takes its
1090
+ arguments in the same shape, and resolves them by the same rules, as `pull`, `push` and every other
1091
+ command: two arguments are the organisation and the tenant, one argument is the tenant, and with no
1092
+ argument it uses `FARSEER_TENANT`. The workspace directory is named after the tenant that resolves.
1093
+
1094
+ ```sh
1095
+ farseer code checkout my-org my-tenant
1096
+ cd my-tenant
1097
+ ```
1098
+
1099
+ The workspace is a tree. Four roots are managed and nothing else is read or written:
1100
+
1101
+ ```
1102
+ <tenant>/
1103
+ tree/ item containment: folders and the items inside them
1104
+ access/ shares, user groups, CLASS grants, labels
1105
+ definitions/ settings, datasets, export configurations
1106
+ detached/ resources whose normal placement cannot be represented
1107
+ .fscode/ state.json: baseline, physical routes, the plans still to apply (newest three),
1108
+ cached hashes of the raw files
1109
+ .gitignore written by checkout; it ignores .fscode/, OS and tool files, temporaries
1110
+ ```
1111
+
1112
+ One `farseer code` command runs in a workspace at a time: each holds `.fscode/lock` while it runs,
1113
+ and a second one refuses and names the holder; delete the lock only when no such command runs.
1114
+
1115
+ `.fscode/state.json` is per-machine tool state, not authored work: keep it local. A workspace
1116
+ belongs to the checkout that made it: a git clone of a committed workspace has no state and
1117
+ cannot plan; people share through the server (`code pull`), not through git, for now. It also
1118
+ records the tenant, the organisation and the server the checkout used, so every other `code`
1119
+ command takes no tenant argument. Each one finds its workspace the way `git`
1120
+ finds `.git`: it walks up from the current directory to the nearest `.fscode/state.json`.
1121
+ Run them anywhere inside the checkout; outside one they refuse with
1122
+ `Not inside a Farseer code workspace; run farseer code checkout <tenant> first`.
1123
+
1124
+ A workspace belongs to the server it was checked out from. Plan numbers and baselines belong to
1125
+ one server, so `code apply p5` against another server would apply that server's plan 5. Every
1126
+ command therefore refuses when its credential or `FARSEER_API_URL` resolves to another server,
1127
+ and names both. A workspace checked out before the CLI recorded its server is refused: delete it
1128
+ and run `farseer code checkout` again.
1129
+
1130
+ ### The item tree
1131
+
1132
+ `tree/` mirrors backend containment. Every managed folder is a directory with a
1133
+ `_folder.json` marker holding its `id`, exact numeric `order` and `allowedTypes`. The
1134
+ marker is what opts a directory into managed recursion, so a generated `node_modules/`
1135
+ or `.venv/` tree needs no ignore language: an unmarked directory is one opaque local
1136
+ subtree. Losing a marker while managed descendants remain is an error.
1137
+
1138
+ Each ordinary item is one `Name.json` file with `kind` and `id` inside it. The decoded
1139
+ filename supplies the item's name, so a rename is a file rename and a move is a file
1140
+ move. Item-node sibling names are unique across kinds, so no kind suffix is needed. A
1141
+ folder's own name comes from its directory and is never written into `_folder.json`.
1142
+
1143
+ Unsafe bytes in a name are escaped as `~HH` (`~7E` is a literal `~`). When a name
1144
+ cannot be represented by any filename — a collision after case folding, an
1145
+ unrepresentable spelling, a path over the platform budget — the file carries an
1146
+ explicit lossless `name` field that overrides the filename. Traversal, overlapping
1147
+ roles and symlinks anywhere in a managed path are refused.
1148
+
1149
+ A name that a filesystem can store in two Unicode forms, such as `Prihod čisti` or
1150
+ `Müller`, also carries a `name` field, but only to keep its exact spelling. Rename such a
1151
+ file and the new filename is the name; the `name` field wins only while it spells the
1152
+ same name as the filename. A `name` field that spells another name is reported with a
1153
+ `name-override-ignored` warning naming the file and both spellings: edit the filename to
1154
+ rename the resource.
1155
+
1156
+ Operating-system and tool files are ignored by exact name: `.DS_Store`, `Thumbs.db`,
1157
+ `desktop.ini`, `__pycache__`, `.git`, and AppleDouble files that start with `._`. They are
1158
+ never local files of yours, so they do not hold a folder in place, and the workspace
1159
+ `.gitignore` lists them, together with the `<name>.tmp-<uuid>` temporaries a killed command
1160
+ can leave. A resource whose name is spelled like one of them is written with an escaped
1161
+ first character, so no resource can hide behind the ignore.
1162
+
1163
+ A dimension table and its member set share one physical file, `tree/<path>/<Table>.json`,
1164
+ whose `members` list is required (`[]` requests an empty set). They stay two canonical
1165
+ resources with separate hashes, operations and baselines; deleting the file requests
1166
+ both deletions, and one half can fail while the other applies. Inside the combined file
1167
+ the member set carries no `table` reference: the container supplies it. A member's `data`
1168
+ holds custom columns only; `name`, `formula`, `order`, `active` and `description` are
1169
+ top-level member fields, and naming one of them inside `data` is an error.
1170
+
1171
+ ### Shares
1172
+
1173
+ Each share is its own canonical resource. All the shares of one owner live in one flat
1174
+ group at `access/shares/<kind>-<id>.json`, which contains `owner: {kind, id}` and a
1175
+ `shares` array. The owner's own document carries a small navigation pointer,
1176
+ `shares: {"file": "access/shares/<kind>-<id>.json"}`; for an uploaded file that pointer
1177
+ sits inside its `.meta` sidecar. The pointer is local navigation, not canonical
1178
+ identity, so editing a route does not dirty the owner's value.
1179
+
1180
+ Omit a new share's `id` and give it a local `key` if another authored artifact must
1181
+ refer to it. Removing an entry requests that share's deletion; removing the group or
1182
+ its pointer requests deletion of every share it represented. Deleting an owner instead
1183
+ uses the backend's ownership cascade, which removes every share owned at execution
1184
+ time. Item creation inherits parent grants and grants its creator EDIT, so a new item
1185
+ reads back with system-created shares the author never wrote; the CLI materializes them
1186
+ into the owner's group. Tracked shares omit `type`, and lifecycle state and public
1187
+ secrets are never authored.
1188
+
1189
+ ### Groups, grants and labels
1190
+
1191
+ `access/groups/<name>.json`, `access/labels/<name>.json`, and CLASS grants at
1192
+ `access/grants/users/<keycloak-id>.json` or `access/grants/service/<service-name>.json`. Users
1193
+ are references, not authored resources: use a keycloak id or `{ "service": "name" }`. A
1194
+ grant document contains `kind`, `user` and `permissions` and has no authored id; delete
1195
+ the document to remove all CLASS grants for that user. FEATURE and SUPER_USER grants
1196
+ remain system-owned. Groups and grants require superuser; labels and shares use their
1197
+ ordinary class permissions and item access checks.
1198
+
1199
+ ### Definitions
1200
+
1201
+ `definitions/settings.json` is the singleton `settings/1`; reset its fields instead of
1202
+ deleting it. Datasets live at `definitions/datasets/<name>.json` with integer ids, not
1203
+ HTTP UUIDs; format is immutable and deletes with current or completed versions are
1204
+ protected. Export configurations are `definitions/exports/<Name>.json` with their
1205
+ optional template bytes beside them as `definitions/exports/<Name>.xlsx`.
1206
+
1207
+ ### Uploaded files and attachments
1208
+
1209
+ Raw uploaded files live directly in their item directory. Each one carries its metadata
1210
+ in a sidecar beside the bytes: for `report.bin` the sidecar is `report.bin.meta`.
1211
+
1212
+ ```json
1213
+ {
1214
+ "kind": "file",
1215
+ "id": "4",
1216
+ "order": 2,
1217
+ "type": "text/x-python",
1218
+ "category": "files",
1219
+ "shares": { "file": "access/shares/file-4.json" }
1220
+ }
1221
+ ```
1222
+
1223
+ The bytes are the truth: the adapter derives name and placement from the path, hashes the
1224
+ bytes and sends the file document, so authors never maintain a content hash or size. A
1225
+ new upload needs the bytes plus one complete id-less sidecar. Rename or move the bytes and
1226
+ their sidecar together; a whole-folder move carries the raw files, their sidecars and the
1227
+ marker together. Identity is never inferred from content, name or timing. Bytes that
1228
+ disappear while their sidecar remains request the file's deletion; removing the sidecar
1229
+ while the bytes remain is an error. Copying an id-bearing sidecar is a duplicate-id error.
1230
+ Files without a sidecar are local-only, and a sidecar claims its sibling even when that
1231
+ sibling is `.json`. `.meta` is reserved: an uploaded file whose own name ends in `.meta`
1232
+ is written with an escaped spelling and an explicit `name` field. Changed uploads are
1233
+ limited to 64 MiB; unchanged larger files remain usable. Only READY ITEM_NODE files are
1234
+ modeled.
1235
+
1236
+ Job icons and export templates are nullable fields of their owners, with no resource id
1237
+ and no sidecar. Keep the bytes beside the owner JSON and point at them:
1238
+ `"icon": {"file": "tree/Apps/Nightly.icon"}`, `"template": {"file": "definitions/exports/Default KPI.xlsx"}`.
1239
+ Explicit `null` clears the field; deleting tracked bytes clears it too. Omitting the
1240
+ field preserves the association while the tracked bytes remain. A pointer to missing
1241
+ bytes is an error. Bytes left behind after an explicit `null` are unreferenced local
1242
+ files and are not deleted for you, and a later omission cannot restore them.
1243
+
1244
+ ### Detached resources
1245
+
1246
+ `detached/` is for a resource whose valid placement cannot be represented normally, or
1247
+ whose ancestry is provably damaged: `detached/<kind>/<id>.json` with an explicit
1248
+ semantic name and location, and `detached/files/<id>/` with one raw file: its bytes and
1249
+ the `.meta` sidecar beside them. A healthy detached resource stays editable; moving it into a managed folder
1250
+ keeps its id and drops its location override. A damaged resource keeps its exact
1251
+ baseline-bound proof and can only be repaired, never re-owned.
1252
+
1253
+ ### Checkout, pull, plan, apply
1254
+
1255
+ ```sh
1256
+ farseer code checkout my-org my-tenant
1257
+ cd my-tenant
1258
+ # Edit a document, for example a variable's description.
1259
+ farseer code plan
1260
+ farseer code apply p123 # use the plan ID printed above
1261
+ farseer code plan # no changes after a successful apply
1262
+ ```
1263
+
1264
+ `checkout` refuses a directory that already holds something, a tenant named
1265
+ `farseer-apps`, and any directory inside the legacy sync tree or inside another code
1266
+ workspace. A checkout that was interrupted leaves the directory holding `.fscode/` and
1267
+ `.gitignore`; run `farseer code pull` inside it to finish it, as the refusal says. `code pull` writes the head into the workspace and fast-forwards per resource. An unchanged
1268
+ clean resource is not rewritten and not reported. A locally edited resource keeps its
1269
+ text: `kept local` when the head did not move, `conflict` (exit status 1) when it did. A
1270
+ resource you deleted locally is never recreated; the deletion stands until you plan it.
1271
+ `code pull` and `code checkout` do not print the head's own diagnostics (data problems the
1272
+ tenant already has); `--verbose` prints them. `code pull --force` discards every local difference after confirmation, including
1273
+ re-creating a file you deleted. It always asks; no flag skips the question, by decision, so
1274
+ without a terminal the confirmation cannot be answered and the command exits 130.
1275
+
1276
+ When someone else renamed or moved a resource, `code pull` follows it on disk instead of
1277
+ leaving a second copy behind. Nothing is renamed and nothing is moved: the CLI writes the
1278
+ resource at its new path and then deletes the file it left, so a swap is two writes and a
1279
+ renamed folder is the set of writes into its new directory plus the deletion of the old
1280
+ files. A rename that changes only letter case works on a case-insensitive filesystem too:
1281
+ the old entry goes immediately before the write, because both spellings name one file.
1282
+ A folder whose own path changed moves whole or not at all. Its old directory has to end
1283
+ up empty, so anything the pull does not write elsewhere or delete keeps the whole folder
1284
+ where you have it: a resource with local edits or a conflict, a file of your own inside the
1285
+ directory, or a subtree the workspace cannot manage. `code pull` then reports
1286
+ `kept in place: <directory>; resolve <paths> and pull again` (exit status 1) and names only
1287
+ the paths that really hold it. Resolve those and pull again, and the whole folder moves. A
1288
+ folder whose path did not change is written where it is, whatever its own fields did. A
1289
+ folder whose directory changes only in letter case follows the same rule: when it moves whole,
1290
+ a filesystem that ignores case gets its directory renamed to the new spelling, and one that
1291
+ respects case gets the new directory written and the old one removed. A directory you renamed
1292
+ in case yourself is kept as it is when the apply's receipt adopts the folder; the next
1293
+ `code pull` then renews the proofs of the files inside it without changing them.
1294
+
1295
+ The writes of a pull or an apply come in an order that never leaves a resource on no path: a renamed
1296
+ resource is written at its new path before another one takes its old path, and two resources that
1297
+ swap paths pass through a temporary name. Ctrl-C waits until the writes and the state are saved,
1298
+ then ends the command; during the downloads before the writes it removes what was staged, the
1299
+ partial download included. Each file is compared with what the command read before the writes start
1300
+ and again just before it is replaced: a file you save while a large pull is downloading is kept and
1301
+ reported `unmaterialized`, with the rest of its resource and any rename that depends on it, so pull
1302
+ again. Downloads go to a temporary file beside their destination, never to the system temporary
1303
+ directory, and a rewritten file keeps its mode, so a committed executable bit survives.
1304
+
1305
+ A saved plan draft the CLI cannot read is quarantined in `unreadableReceipts` instead of
1306
+ making the workspace unreadable. Every command then warns and carries on, and the guard
1307
+ still holds: an `applying` draft stops `code plan` and `code apply`, and each names
1308
+ `code pull --force`, which drops the quarantined drafts and is the only way out.
1309
+
1310
+ `code plan` composes the workspace into documents, uploads the bytes its evidence does not
1311
+ already know, and posts them with the workspace baseline. It prints the revision the plan
1312
+ was computed against and warns when the workspace is behind the head. A workspace whose
1313
+ model files are all gone (a deleted `tree/`, or a `git clean -fd`, which keeps the ignored
1314
+ `.fscode/`) is refused instead of planning to delete everything; restore the files with
1315
+ `farseer code pull --force`. Reformatting JSON is not an
1316
+ edit: the plan compares canonical values, so key order and whitespace produce an empty
1317
+ plan. Deleting a tracked document expresses a planned server deletion; read the plan
1318
+ before applying it. `code plan` exits 1 whenever the server's plan is not applicable (a
1319
+ conflict, a blocked operation or an error diagnostic) and 0 otherwise, including for an
1320
+ empty plan. A field missing from a file keeps the server's value. To clear it, write the field's
1321
+ default value, which the `field-omitted` warning of `code plan` names (for example
1322
+ `"formula": null`). A changed field prints with the values as the files show them, and a member,
1323
+ column, line or tile by its id: `members/412/name "HR" -> "Croatia"`. `code plan --json` prints
1324
+ the plan response as JSON on stdout and every other line on stderr, for scripts and agents.
1325
+ A workspace keeps the newest three plans that were never applied; a fourth plan drops the oldest
1326
+ and names it: `Dropped the saved plan p1: only the newest 3 unapplied plans stay applicable.`
1327
+
1328
+ The plan prints every error, every warning the plan itself causes, and every warning on a
1329
+ resource it changes. A warning the server marks `preexisting` (a data problem the tenant already
1330
+ had, such as a dangling reference in a sheet nobody edited) on a resource the plan leaves alone
1331
+ is counted instead: `N pre-existing tenant warnings hidden (farseer code plan --verbose shows
1332
+ them)`. `code plan --verbose` prints them all.
1333
+
1334
+ `code apply` runs the saved plan and reconciles its receipt. Before it posts anything, it
1335
+ reads the plan from the server and refuses one that is not the plan this workspace
1336
+ created. It patches every assigned id
1337
+ into the file that created the resource, rewrites an applied file from the server's
1338
+ read-back when that file has not changed since the plan, and advances the baseline of
1339
+ applied resources. A create that did not apply but exists on the server gets its id in the
1340
+ file and the server's version as its baseline, so the next `code plan` shows it as an
1341
+ ordinary update. Failed and blocked files keep the desired text apart from patched ids, and
1342
+ a failed update keeps its old baseline. Partial and failed attempts exit nonzero. A pending attempt (HTTP 202)
1343
+ finishes by resuming the same `code apply p123`; the CLI does that while it waits and then
1344
+ prints a resume command. Merely reading an attempt does not finish it — v1 has no
1345
+ background finalizer. `--wait-seconds 300` widens the default 120-second window. When the
1346
+ apply's response never arrives, or its receipt could not be written, the next `code pull`
1347
+ reads that receipt and writes it before it pulls anything else; `code plan` refuses until
1348
+ then. When the server answers that the plan has no attempt at all, the apply never arrived:
1349
+ `code pull` lifts the guard and prints `Plan p123 was never applied; it stays applicable with
1350
+ farseer code apply p123`. That holds only when the apply request got an answer or never left
1351
+ the machine. After a timeout or a lost connection the request may still be running on the
1352
+ server, so the guard stays and `code apply` and `code pull` both ask you to run the same
1353
+ `farseer code apply p123` again, which resumes that apply. Do not delete the local state
1354
+ during recovery.
1355
+
1356
+ After each write the CLI rescans the workspace and composes it again. A resource
1357
+ advances its baseline and routes only when the recomposed document is the authoritative
1358
+ one; anything else keeps its previous facts and is named in a `unverified-readback`
1359
+ warning.
1360
+
1361
+ `ambiguous-patch: <file> (<kind>/<id>; …)` means the apply created that resource, but its
1362
+ assigned id could not be placed safely: the file is gone, or it changed after the plan so that
1363
+ the place of the id is no longer certain. The baseline does not advance for that create.
1364
+ Recover with one of:
1365
+
1366
+ 1. Put the printed id into that file or share entry by hand, then run `code pull`. The pull adopts
1367
+ the resource once the file holds the server's version of it. Another edit to the same resource
1368
+ makes the pull report a `conflict`, so make that edit after the pull. A plan before the pull is
1369
+ refused with `unknown-id`.
1370
+ 2. Delete the share entry, or the file when it holds nothing else you keep, then run `code pull`.
1371
+ It writes the created resource from the server. A file that is already gone needs only the pull.
1372
+
1373
+ Without either, the next plan asks for the create again, and the server refuses a named resource
1374
+ with `name-taken`.
1375
+
1376
+ Unadmitted plans expire after 7 days by default (the server operator can change the
1377
+ window). `code apply` reports `Plan p123 expired on <server date>; run farseer code plan again.`
1378
+ and exits nonzero. An expired read writes nothing, and expiry racing the apply POST
1379
+ clears only the temporary apply guard. Already-admitted attempts never expire.
1380
+
1381
+ Server baseline hashes describe bound canonical values and are intentionally different
1382
+ from anything you can compute from the text. Do not hand-edit the baseline.
1383
+
1384
+ Every workspace that predates `.fscode/state.json` is retired, including the prototype's
1385
+ flat `model/` workspace and the code tree the legacy `pull` used to write under
1386
+ `farseer-apps/<tenant>/`. Their state files are refused, not upgraded: delete the old
1387
+ directory and run `farseer code checkout <tenant>`.
1388
+
1389
+ For local development only, set `FARSEER_API_URL=http://localhost:3000/api/v3`
1390
+ before login and all subsequent commands. The `[org]` argument is only the name the
1391
+ credential was stored under at `login`; with the override it does not form a URL, so
1392
+ use the same name for both (for example `local`): `farseer login --api-key local`, then
1393
+ `farseer code checkout local farseer-dev`. It overrides the API base URL of each
1394
+ request only: a saved credential keeps its organization URL, so the same credential
1395
+ reaches that organization again once the variable is unset. Use only credentials
1396
+ intended for that server; API credentials are sent to the configured URL.
1397
+
1398
+ For operator/storage/authorization caveats, see the backend module's
1399
+ [working guide](../backend/app/openapi/v3/services/codefirst/CLAUDE.md).
1400
+ Blob GC is a manual superuser HTTP operation, not a CLI command or scheduled task.
1401
+
1074
1402
  ## License
1075
1403
 
1076
1404
  ISC
@@ -0,0 +1,104 @@
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 code_exports = {};
30
+ __export(code_exports, {
31
+ registerCodeCommand: () => registerCodeCommand
32
+ });
33
+ module.exports = __toCommonJS(code_exports);
34
+ var import_commander = require("commander");
35
+ var import_inquirer = __toESM(require("inquirer"));
36
+ var import_preflight = require("../services/preflight");
37
+ var import_workflow = require("../services/codefirst/workflow");
38
+ var import_workspaceRoot = require("../services/codefirst/workspaceRoot");
39
+ var import_errorFormatter = require("../utils/errorFormatter");
40
+ var import_logger = require("../utils/logger");
41
+ function registerCodeCommand(program) {
42
+ const code = program.command("code").description("Experimental: Farseer as code, the model as files");
43
+ code.configureHelp({ visibleCommands: (command) => new import_commander.Help().visibleCommands(command) });
44
+ code.command("checkout [org] [tenant]").description("Experimental: create ./<tenant>/ and check the model out into it").option("--wait-seconds <seconds>", "Maximum wait for an applying revision", import_workflow.waitSeconds, 120).option("--verbose", "Also print the head's pre-existing tenant warnings").action(async (org, tenant, options) => {
45
+ await run(async () => {
46
+ const target = await (0, import_preflight.preflight)(org, tenant);
47
+ await (0, import_workflow.checkoutModel)(target, tenant ?? org, process.cwd(), options.waitSeconds, console.log, {
48
+ verbose: !!options.verbose
49
+ });
50
+ });
51
+ });
52
+ code.command("pull").description("Experimental: fast-forward this code workspace to the current model head").option("--force", "Reset tracked resources to the head; new local files stay (asks for confirmation)").option("--wait-seconds <seconds>", "Maximum wait for an applying revision", import_workflow.waitSeconds, 120).option("--verbose", "Also print the head's pre-existing tenant warnings").action(async (options) => {
53
+ await run(async () => {
54
+ const workspace = await currentWorkspace();
55
+ if (options.force && !await confirmForce(workspace.target.tenant)) {
56
+ import_logger.logger.info("Pull cancelled.");
57
+ return;
58
+ }
59
+ await (0, import_workflow.pullModel)(workspace, !!options.force, options.waitSeconds, console.log, {
60
+ verbose: !!options.verbose
61
+ });
62
+ });
63
+ });
64
+ code.command("plan").description("Experimental: compose this code workspace and save a plan for its changes").option("--json", "Print the plan response as JSON on stdout, and every other line on stderr").option("--wait-seconds <seconds>", "Maximum wait for an applying revision", import_workflow.waitSeconds, 120).option("--verbose", "Also print the pre-existing tenant warnings on resources the plan leaves alone").action(async (options) => {
65
+ if (options.json) (0, import_logger.reserveStdout)();
66
+ await run(
67
+ async () => (0, import_workflow.planModel)(await currentWorkspace(), options.waitSeconds, console.log, {
68
+ json: !!options.json,
69
+ verbose: !!options.verbose
70
+ })
71
+ );
72
+ });
73
+ code.command("apply <planId>").description("Experimental: apply or resume a plan saved in this code workspace").option("--wait-seconds <seconds>", "Maximum wait for a pending receipt", import_workflow.waitSeconds, 120).action(async (planId, options) => {
74
+ await run(async () => (0, import_workflow.applyModel)(await currentWorkspace(), planId, options.waitSeconds));
75
+ });
76
+ }
77
+ async function currentWorkspace() {
78
+ const workspace = (0, import_workspaceRoot.resolveCodeWorkspace)(process.cwd());
79
+ return { ...workspace, target: await (0, import_preflight.preflight)(workspace.state.organisation, workspace.state.tenant) };
80
+ }
81
+ async function confirmForce(tenant) {
82
+ const answer = await import_inquirer.default.prompt([
83
+ {
84
+ type: "confirm",
85
+ name: "proceed",
86
+ message: `Discard local model changes and reset ${tenant} to the remote head?`,
87
+ default: false
88
+ }
89
+ ]);
90
+ return !!answer.proceed;
91
+ }
92
+ async function run(action) {
93
+ try {
94
+ await action();
95
+ } catch (error) {
96
+ import_logger.logger.error(await (0, import_errorFormatter.formatClientError)(error));
97
+ process.exitCode = 1;
98
+ }
99
+ }
100
+ // Annotate the CommonJS export names for ESM import in node:
101
+ 0 && (module.exports = {
102
+ registerCodeCommand
103
+ });
104
+ //# sourceMappingURL=code.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../src/commands/code.ts"],
4
+ "sourcesContent": ["import { Command, Help } from 'commander';\nimport inquirer from 'inquirer';\nimport { preflight } from '../services/preflight';\nimport {\n applyModel,\n checkoutModel,\n planModel,\n pullModel,\n waitSeconds,\n type WorkspaceCommand,\n} from '../services/codefirst/workflow';\nimport { resolveCodeWorkspace } from '../services/codefirst/workspaceRoot';\nimport { formatClientError } from '../utils/errorFormatter';\nimport { logger, reserveStdout } from '../utils/logger';\n\n/**\n * `farseer code` \u2014 the experimental Farseer-as-code workspace, separate from the legacy files/apps\n * sync. The group and every subcommand say \"Experimental\" in their descriptions.\n *\n * Only `checkout` names a tenant. Every other command walks up from the current directory to the\n * workspace it runs in and reads the target from its `.fscode/state.json`, so one checkout can never\n * be driven against another tenant by an argument or an environment variable.\n */\nexport function registerCodeCommand(program: Command): void {\n const code = program.command('code').description('Experimental: Farseer as code, the model as files');\n // The root command hides its own command list; this group has no custom help, so it shows one.\n code.configureHelp({ visibleCommands: (command) => new Help().visibleCommands(command) });\n\n // Same argument shape as every legacy command, so `preflight` resolves the pair on its own: two\n // arguments are `<org> <tenant>`, one is the tenant, none falls back to `FARSEER_TENANT`. The\n // typed tenant, when there is one, is only a cross-check on what `preflight` resolved.\n code.command('checkout [org] [tenant]')\n .description('Experimental: create ./<tenant>/ and check the model out into it')\n .option('--wait-seconds <seconds>', 'Maximum wait for an applying revision', waitSeconds, 120)\n .option('--verbose', \"Also print the head's pre-existing tenant warnings\")\n .action(async (org, tenant, options) => {\n await run(async () => {\n const target = await preflight(org, tenant);\n await checkoutModel(target, tenant ?? org, process.cwd(), options.waitSeconds, console.log, {\n verbose: !!options.verbose,\n });\n });\n });\n\n code.command('pull')\n .description('Experimental: fast-forward this code workspace to the current model head')\n .option('--force', 'Reset tracked resources to the head; new local files stay (asks for confirmation)')\n .option('--wait-seconds <seconds>', 'Maximum wait for an applying revision', waitSeconds, 120)\n .option('--verbose', \"Also print the head's pre-existing tenant warnings\")\n .action(async (options) => {\n await run(async () => {\n const workspace = await currentWorkspace();\n if (options.force && !(await confirmForce(workspace.target.tenant))) {\n logger.info('Pull cancelled.');\n return;\n }\n await pullModel(workspace, !!options.force, options.waitSeconds, console.log, {\n verbose: !!options.verbose,\n });\n });\n });\n\n code.command('plan')\n .description('Experimental: compose this code workspace and save a plan for its changes')\n .option('--json', 'Print the plan response as JSON on stdout, and every other line on stderr')\n .option('--wait-seconds <seconds>', 'Maximum wait for an applying revision', waitSeconds, 120)\n .option('--verbose', 'Also print the pre-existing tenant warnings on resources the plan leaves alone')\n .action(async (options) => {\n if (options.json) reserveStdout();\n await run(async () =>\n planModel(await currentWorkspace(), options.waitSeconds, console.log, {\n json: !!options.json,\n verbose: !!options.verbose,\n }),\n );\n });\n\n code.command('apply <planId>')\n .description('Experimental: apply or resume a plan saved in this code workspace')\n .option('--wait-seconds <seconds>', 'Maximum wait for a pending receipt', waitSeconds, 120)\n .action(async (planId, options) => {\n await run(async () => applyModel(await currentWorkspace(), planId, options.waitSeconds));\n });\n}\n\n/** The workspace this directory belongs to, authenticated against the target its state names. */\nasync function currentWorkspace(): Promise<WorkspaceCommand> {\n const workspace = resolveCodeWorkspace(process.cwd());\n return { ...workspace, target: await preflight(workspace.state.organisation, workspace.state.tenant) };\n}\n\n/** `--force` discards authored work, so it always asks; there is no flag that skips the question. */\nasync function confirmForce(tenant: string): Promise<boolean> {\n const answer = await inquirer.prompt([\n {\n type: 'confirm',\n name: 'proceed',\n message: `Discard local model changes and reset ${tenant} to the remote head?`,\n default: false,\n },\n ]);\n return !!answer.proceed;\n}\n\nasync function run(action: () => Promise<void>): Promise<void> {\n try {\n await action();\n } catch (error) {\n logger.error(await formatClientError(error));\n process.exitCode = 1;\n }\n}\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,uBAA8B;AAC9B,sBAAqB;AACrB,uBAA0B;AAC1B,sBAOO;AACP,2BAAqC;AACrC,4BAAkC;AAClC,oBAAsC;AAU/B,SAAS,oBAAoB,SAAwB;AACxD,QAAM,OAAO,QAAQ,QAAQ,MAAM,EAAE,YAAY,mDAAmD;AAEpG,OAAK,cAAc,EAAE,iBAAiB,CAAC,YAAY,IAAI,sBAAK,EAAE,gBAAgB,OAAO,EAAE,CAAC;AAKxF,OAAK,QAAQ,yBAAyB,EACjC,YAAY,kEAAkE,EAC9E,OAAO,4BAA4B,yCAAyC,6BAAa,GAAG,EAC5F,OAAO,aAAa,oDAAoD,EACxE,OAAO,OAAO,KAAK,QAAQ,YAAY;AACpC,UAAM,IAAI,YAAY;AAClB,YAAM,SAAS,UAAM,4BAAU,KAAK,MAAM;AAC1C,gBAAM,+BAAc,QAAQ,UAAU,KAAK,QAAQ,IAAI,GAAG,QAAQ,aAAa,QAAQ,KAAK;AAAA,QACxF,SAAS,CAAC,CAAC,QAAQ;AAAA,MACvB,CAAC;AAAA,IACL,CAAC;AAAA,EACL,CAAC;AAEL,OAAK,QAAQ,MAAM,EACd,YAAY,0EAA0E,EACtF,OAAO,WAAW,mFAAmF,EACrG,OAAO,4BAA4B,y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;AAC1D,QAAM,SAAS,MAAM,gBAAAA,QAAS,OAAO;AAAA,IACjC;AAAA,MACI,MAAM;AAAA,MACN,MAAM;AAAA,MACN,SAAS,yCAAyC,MAAM;AAAA,MACxD,SAAS;AAAA,IACb;AAAA,EACJ,CAAC;AACD,SAAO,CAAC,CAAC,OAAO;AACpB;AAEA,eAAe,IAAI,QAA4C;AAC3D,MAAI;AACA,UAAM,OAAO;AAAA,EACjB,SAAS,OAAO;AACZ,yBAAO,MAAM,UAAM,yCAAkB,KAAK,CAAC;AAC3C,YAAQ,WAAW;AAAA,EACvB;AACJ;",
6
+ "names": ["inquirer"]
7
+ }
@@ -35,11 +35,13 @@ var import_chalk = __toESM(require("chalk"));
35
35
  var import_logger = require("../utils/logger");
36
36
  var import_authErrors = require("../services/authErrors");
37
37
  var import_preflight = require("../services/preflight");
38
+ var import_formulaFilters = require("../utils/formulaFilters");
39
+ var import_errorFormatter = require("../utils/errorFormatter");
38
40
  function registerFormulaCommand(program) {
39
41
  const formulaCmd = program.command("formula").description("Evaluate formulas");
40
42
  formulaCmd.command("eval <expression> [org] [tenant]").description("Evaluate a formula expression").option(
41
43
  "--filter <table=member>",
42
- "Dimension filter (repeatable)",
44
+ "Dimension filter (repeatable); applies to a single variable name, an expression carries its own",
43
45
  (val, acc) => {
44
46
  acc.push(val);
45
47
  return acc;
@@ -56,9 +58,16 @@ function registerFormulaCommand(program) {
56
58
  }
57
59
  return [f.substring(0, eqIndex), f.substring(eqIndex + 1)];
58
60
  });
61
+ let formula;
62
+ try {
63
+ formula = (0, import_formulaFilters.filtersInFormula)(expression, filters);
64
+ } catch (error) {
65
+ import_logger.logger.error(error.message);
66
+ process.exit(1);
67
+ }
59
68
  const evaluateRequest = {
60
- filters,
61
- cellQueries: [{ type: "VARIABLE", formula: expression }]
69
+ filters: [],
70
+ cellQueries: [{ type: "VARIABLE", formula }]
62
71
  };
63
72
  const results = await nativeClient.evaluator.evaluate(evaluateRequest);
64
73
  if (options.json) {
@@ -86,15 +95,15 @@ function registerFormulaCommand(program) {
86
95
  import_logger.logger.dim(" No results.");
87
96
  }
88
97
  } catch (error) {
89
- handleFormulaError(error, tenant);
98
+ await handleFormulaError(error, tenant);
90
99
  }
91
100
  });
92
101
  }
93
- function handleFormulaError(error, tenant) {
94
- const errorMessage = error instanceof Error ? error.message : String(error);
102
+ async function handleFormulaError(error, tenant) {
103
+ const errorMessage = await (0, import_errorFormatter.formatClientError)(error);
95
104
  if ((0, import_authErrors.isAuthError)(error)) {
96
105
  (0, import_authErrors.showLoginPrompt)(tenant);
97
- } else if (errorMessage.includes("404")) {
106
+ } else if (error instanceof Response && error.status === 404) {
98
107
  import_logger.logger.error("Formula evaluation endpoint not found.");
99
108
  } else if (errorMessage.includes("ENOTFOUND") || errorMessage.includes("ECONNREFUSED")) {
100
109
  import_logger.logger.error("Failed to connect to Farseer.");
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/commands/formula.ts"],
4
- "sourcesContent": ["import { Command } from 'commander';\nimport chalk from 'chalk';\nimport { logger } from '../utils/logger';\nimport { showLoginPrompt, isAuthError } from '../services/authErrors';\nimport { preflight } from '../services/preflight';\n\nexport function registerFormulaCommand(program: Command): void {\n const formulaCmd = program.command('formula').description('Evaluate formulas');\n\n // farseer formula eval <expression> [org] [tenant]\n formulaCmd\n .command('eval <expression> [org] [tenant]')\n .description('Evaluate a formula expression')\n .option(\n '--filter <table=member>',\n 'Dimension filter (repeatable)',\n (val: string, acc: string[]) => {\n acc.push(val);\n return acc;\n },\n [] as string[],\n )\n .option('--json', 'Output raw JSON')\n .action(async (expression, first, second, options) => {\n const { native: nativeClient, tenant } = await preflight(first, second);\n\n try {\n const filters: Array<Array<string>> = (options.filter || []).map((f: string) => {\n const eqIndex = f.indexOf('=');\n if (eqIndex === -1) {\n logger.error(`Invalid filter format: \"${f}\". Expected \"Table=Member\".`);\n process.exit(1);\n }\n return [f.substring(0, eqIndex), f.substring(eqIndex + 1)];\n });\n\n const evaluateRequest = {\n filters,\n cellQueries: [{ type: 'VARIABLE' as const, formula: expression }],\n };\n\n const results = await nativeClient.evaluator.evaluate(evaluateRequest);\n\n if (options.json) {\n console.log(JSON.stringify(results, null, 2));\n return;\n }\n\n logger.header(`Formula: ${expression}`);\n if (filters.length > 0) {\n console.log(` Filters: ${filters.map((f) => `${f[0]}=${f[1]}`).join(', ')}`);\n }\n console.log();\n\n if (Array.isArray(results) && results.length > 0) {\n for (const cell of results) {\n const flags = [];\n if (cell.readonly) flags.push('readonly');\n if (cell.calculated) flags.push('calculated');\n if (cell.frozen) flags.push('frozen');\n const flagStr = flags.length > 0 ? chalk.dim(` [${flags.join(', ')}]`) : '';\n\n console.log(` Value: ${chalk.bold(String(cell.value ?? 'null'))}${flagStr}`);\n if (cell.goal !== undefined) {\n console.log(` Goal: ${cell.goal}`);\n }\n }\n } else {\n logger.dim(' No results.');\n }\n } catch (error) {\n handleFormulaError(error, tenant);\n }\n });\n}\n\nfunction handleFormulaError(error: unknown, tenant: string): void {\n const errorMessage = error instanceof Error ? error.message : String(error);\n\n if (isAuthError(error)) {\n showLoginPrompt(tenant);\n } else if (errorMessage.includes('404')) {\n logger.error('Formula evaluation endpoint not found.');\n } else if (errorMessage.includes('ENOTFOUND') || errorMessage.includes('ECONNREFUSED')) {\n logger.error('Failed to connect to Farseer.');\n } else {\n logger.error('Formula evaluation failed.');\n logger.dim(errorMessage);\n }\n process.exit(1);\n}\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AACA,mBAAkB;AAClB,oBAAuB;AACvB,wBAA6C;AAC7C,uBAA0B;AAEnB,SAAS,uBAAuB,SAAwB;AAC3D,QAAM,aAAa,QAAQ,QAAQ,SAAS,EAAE,YAAY,mBAAmB;AAG7E,aACK,QAAQ,kCAAkC,EAC1C,YAAY,+BAA+B,EAC3C;AAAA,IACG;AAAA,IACA;AAAA,IACA,CAAC,KAAa,QAAk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AAQ,OAAM,KAAK,QAAQ;AACpC,gBAAM,UAAU,MAAM,SAAS,IAAI,aAAAA,QAAM,IAAI,KAAK,MAAM,KAAK,IAAI,CAAC,GAAG,IAAI;AAEzE,kBAAQ,IAAI,YAAY,aAAAA,QAAM,KAAK,OAAO,KAAK,SAAS,MAAM,CAAC,CAAC,GAAG,OAAO,EAAE;AAC5E,cAAI,KAAK,SAAS,QAAW;AACzB,oBAAQ,IAAI,YAAY,KAAK,IAAI,EAAE;AAAA,UACvC;AAAA,QACJ;AAAA,MACJ,OAAO;AACH,6BAAO,IAAI,eAAe;AAAA,MAC9B;AAAA,IACJ,SAAS,OAAO;AACZ,yBAAmB,OAAO,MAAM;AAAA,IACpC;AAAA,EACJ,CAAC;AACT;AAEA,SAAS,mBAAmB,OAAgB,QAAsB;AAC9D,QAAM,eAAe,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AAE1E,UAAI,+BAAY,KAAK,GAAG;AACpB,2CAAgB,MAAM;AAAA,EAC1B,WAAW,aAAa,SAAS,KAAK,GAAG;AACrC,yBAAO,MAAM,wCAAwC;AAAA,EACzD,WAAW,aAAa,SAAS,WAAW,KAAK,aAAa,SAAS,cAAc,GAAG;AACpF,yBAAO,MAAM,+BAA+B;AAAA,EAChD,OAAO;AACH,yBAAO,MAAM,4BAA4B;AACzC,yBAAO,IAAI,YAAY;AAAA,EAC3B;AACA,UAAQ,KAAK,CAAC;AAClB;",
4
+ "sourcesContent": ["import { Command } from 'commander';\nimport chalk from 'chalk';\nimport { logger } from '../utils/logger';\nimport { showLoginPrompt, isAuthError } from '../services/authErrors';\nimport { preflight } from '../services/preflight';\nimport { filtersInFormula } from '../utils/formulaFilters';\nimport { formatClientError } from '../utils/errorFormatter';\n\nexport function registerFormulaCommand(program: Command): void {\n const formulaCmd = program.command('formula').description('Evaluate formulas');\n\n // farseer formula eval <expression> [org] [tenant]\n formulaCmd\n .command('eval <expression> [org] [tenant]')\n .description('Evaluate a formula expression')\n .option(\n '--filter <table=member>',\n 'Dimension filter (repeatable); applies to a single variable name, an expression carries its own',\n (val: string, acc: string[]) => {\n acc.push(val);\n return acc;\n },\n [] as string[],\n )\n .option('--json', 'Output raw JSON')\n .action(async (expression, first, second, options) => {\n const { native: nativeClient, tenant } = await preflight(first, second);\n\n try {\n const filters: Array<Array<string>> = (options.filter || []).map((f: string) => {\n const eqIndex = f.indexOf('=');\n if (eqIndex === -1) {\n logger.error(`Invalid filter format: \"${f}\". Expected \"Table=Member\".`);\n process.exit(1);\n }\n return [f.substring(0, eqIndex), f.substring(eqIndex + 1)];\n });\n let formula: string;\n try {\n formula = filtersInFormula(expression, filters);\n } catch (error) {\n logger.error((error as Error).message);\n process.exit(1);\n }\n\n const evaluateRequest = {\n filters: [],\n cellQueries: [{ type: 'VARIABLE' as const, formula }],\n };\n\n const results = await nativeClient.evaluator.evaluate(evaluateRequest);\n\n if (options.json) {\n console.log(JSON.stringify(results, null, 2));\n return;\n }\n\n logger.header(`Formula: ${expression}`);\n if (filters.length > 0) {\n console.log(` Filters: ${filters.map((f) => `${f[0]}=${f[1]}`).join(', ')}`);\n }\n console.log();\n\n if (Array.isArray(results) && results.length > 0) {\n for (const cell of results) {\n const flags = [];\n if (cell.readonly) flags.push('readonly');\n if (cell.calculated) flags.push('calculated');\n if (cell.frozen) flags.push('frozen');\n const flagStr = flags.length > 0 ? chalk.dim(` [${flags.join(', ')}]`) : '';\n\n console.log(` Value: ${chalk.bold(String(cell.value ?? 'null'))}${flagStr}`);\n if (cell.goal !== undefined) {\n console.log(` Goal: ${cell.goal}`);\n }\n }\n } else {\n logger.dim(' No results.');\n }\n } catch (error) {\n await handleFormulaError(error, tenant);\n }\n });\n}\n\nasync function handleFormulaError(error: unknown, tenant: string): Promise<void> {\n const errorMessage = await formatClientError(error);\n\n if (isAuthError(error)) {\n showLoginPrompt(tenant);\n } else if (error instanceof Response && error.status === 404) {\n logger.error('Formula evaluation endpoint not found.');\n } else if (errorMessage.includes('ENOTFOUND') || errorMessage.includes('ECONNREFUSED')) {\n logger.error('Failed to connect to Farseer.');\n } else {\n logger.error('Formula evaluation failed.');\n logger.dim(errorMessage);\n }\n process.exit(1);\n}\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AACA,mBAAkB;AAClB,oBAAuB;AACvB,wBAA6C;AAC7C,uBAA0B;AAC1B,4BAAiC;AACjC,4BAAkC;AAE3B,SAAS,uBAAuB,SAAwB;AAC3D,QAAM,aAAa,QAAQ,QAAQ,SAAS,EAAE,YAAY,mBAAmB;AAG7E,aACK,QAAQ,kCAAkC,EAC1C,YAAY,+BAA+B,EAC3C;AAAA,IACG;AAAA,IACA;AAAA,IACA,CAAC,KAAa,QAAkB;AAC5B,UAAI,KAAK,GAAG;AACZ,aAAO;AAAA,IACX;AAAA,IACA,CAAC;AAAA,EACL,EACC,OAAO,UAAU,iBAAiB,EAClC,OAAO,OAAO,YAAY,OAAO,QAAQ,YAAY;AAClD,UAAM,EAAE,QAAQ,cAAc,OAAO,IAAI,UAAM,4BAAU,OAAO,MAAM;AAEtE,QAAI;AACA,YAAM,WAAiC,QAAQ,UAAU,CAAC,GAAG,IAAI,CAAC,MAAc;AAC5E,cAAM,UAAU,EAAE,QAAQ,GAAG;AAC7B,YAAI,YAAY,IAAI;AAChB,+BAAO,MAAM,2BAA2B,CAAC,6BAA6B;AACtE,kBAAQ,KAAK,CAAC;AAAA,QAClB;AACA,eAAO,CAAC,EAAE,UAAU,GAAG,OAAO,GAAG,EAAE,UAAU,UAAU,CAAC,CAAC;AAAA,MAC7D,CAAC;AACD,UAAI;AACJ,UAAI;AACA,sBAAU,wCAAiB,YAAY,OAAO;AAAA,MAClD,SAAS,OAAO;AACZ,6BAAO,MAAO,MAAgB,OAAO;AACrC,gBAAQ,KAAK,CAAC;AAAA,MAClB;AAEA,YAAM,kBAAkB;AAAA,QACpB,SAAS,CAAC;AAAA,QACV,aAAa,CAAC,EAAE,MAA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