@opsrev/acculynx-cli 1.6.0 → 1.7.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 (2) hide show
  1. package/dist/index.js +9 -720
  2. package/package.json +2 -4
package/dist/index.js CHANGED
@@ -1,6 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
 
3
3
  // src/index.ts
4
+ import { createRequire } from "module";
4
5
  import { Command } from "commander";
5
6
 
6
7
  // src/config.ts
@@ -309,727 +310,11 @@ function registerEstimatesCommands(parentCmd, getClient2) {
309
310
  });
310
311
  }
311
312
 
312
- // src/unofficial/session-store.ts
313
- import {
314
- existsSync,
315
- readFileSync as readFileSync2,
316
- writeFileSync,
317
- mkdirSync,
318
- readdirSync,
319
- unlinkSync
320
- } from "fs";
321
- import { join } from "path";
322
- import { homedir } from "os";
323
-
324
- // src/unofficial/cookie-jar.ts
325
- var CookieJar = class _CookieJar {
326
- cookies = /* @__PURE__ */ new Map();
327
- /** Extract and store cookies from a response's Set-Cookie headers. */
328
- capture(url, response) {
329
- const domain = new URL(url).hostname;
330
- const jar = this.cookies.get(domain) ?? /* @__PURE__ */ new Map();
331
- for (const header of response.headers.getSetCookie()) {
332
- const [pair] = header.split(";");
333
- const eqIdx = pair.indexOf("=");
334
- if (eqIdx === -1) continue;
335
- jar.set(pair.slice(0, eqIdx).trim(), pair.slice(eqIdx + 1).trim());
336
- }
337
- this.cookies.set(domain, jar);
338
- }
339
- /** Get a specific cookie value by name for a given URL. */
340
- getCookie(url, name) {
341
- const domain = new URL(url).hostname;
342
- for (const [d, jar] of this.cookies) {
343
- if (domain === d || domain.endsWith("." + d)) {
344
- if (jar.has(name)) return jar.get(name);
345
- }
346
- }
347
- return void 0;
348
- }
349
- /** Build a Cookie header string for a given URL. */
350
- headerFor(url) {
351
- const domain = new URL(url).hostname;
352
- const parts = [];
353
- for (const [d, jar] of this.cookies) {
354
- if (domain === d || domain.endsWith("." + d)) {
355
- for (const [k, v] of jar) parts.push(`${k}=${v}`);
356
- }
357
- }
358
- return parts.join("; ");
359
- }
360
- /** Serialize for disk caching. */
361
- toJSON() {
362
- const out = {};
363
- for (const [d, jar] of this.cookies) {
364
- out[d] = Object.fromEntries(jar);
365
- }
366
- return out;
367
- }
368
- /** Restore from disk cache. */
369
- static fromJSON(data) {
370
- const jar = new _CookieJar();
371
- for (const [d, pairs] of Object.entries(data)) {
372
- jar.cookies.set(d, new Map(Object.entries(pairs)));
373
- }
374
- return jar;
375
- }
376
- };
377
-
378
- // src/unofficial/session-store.ts
379
- var CONFIG_DIR = join(
380
- process.env.XDG_CONFIG_HOME ?? join(homedir(), ".config"),
381
- "acculynx-cli"
382
- );
383
- var SESSIONS_DIR = join(CONFIG_DIR, "sessions");
384
- function sessionKey(email, companyId) {
385
- const slug = email.replace(/[@.]/g, "-").toLowerCase();
386
- const prefix = companyId.slice(0, 8);
387
- return `${slug}--${prefix}.json`;
388
- }
389
- function loadSession(email, companyId) {
390
- const file = join(SESSIONS_DIR, sessionKey(email, companyId));
391
- if (!existsSync(file)) return null;
392
- try {
393
- const data = JSON.parse(readFileSync2(file, "utf-8"));
394
- return {
395
- jar: CookieJar.fromJSON(data.cookies),
396
- companyId: data.companyId,
397
- email: data.email
398
- };
399
- } catch {
400
- return null;
401
- }
402
- }
403
- function saveSession(session) {
404
- mkdirSync(SESSIONS_DIR, { recursive: true, mode: 448 });
405
- writeFileSync(
406
- join(SESSIONS_DIR, sessionKey(session.email, session.companyId)),
407
- JSON.stringify(
408
- {
409
- email: session.email,
410
- companyId: session.companyId,
411
- cookies: session.jar.toJSON()
412
- },
413
- null,
414
- 2
415
- ),
416
- { mode: 384 }
417
- );
418
- }
419
- function deleteSession(email, companyId) {
420
- const file = join(SESSIONS_DIR, sessionKey(email, companyId));
421
- if (!existsSync(file)) return false;
422
- unlinkSync(file);
423
- return true;
424
- }
425
- function listSessions() {
426
- if (!existsSync(SESSIONS_DIR)) return [];
427
- return readdirSync(SESSIONS_DIR).filter((f) => f.endsWith(".json")).map((f) => {
428
- try {
429
- const data = JSON.parse(
430
- readFileSync2(join(SESSIONS_DIR, f), "utf-8")
431
- );
432
- return { email: data.email, companyId: data.companyId, file: f };
433
- } catch {
434
- return null;
435
- }
436
- }).filter(Boolean);
437
- }
438
-
439
- // src/unofficial/unofficial-client.ts
440
- function createUnofficialClient(session) {
441
- const base = "https://my.acculynx.com";
442
- async function doGet(path) {
443
- const url = `${base}${path}`;
444
- const resp = await fetch(url, {
445
- headers: {
446
- Cookie: session.jar.headerFor(url),
447
- Accept: "application/json"
448
- }
449
- });
450
- if (resp.status === 401 || resp.status === 302) {
451
- throw new Error(
452
- "Session expired \u2014 run `acculynx unofficial login` to re-authenticate"
453
- );
454
- }
455
- if (!resp.ok) {
456
- throw new Error(
457
- `Unofficial API error (${resp.status}): ${await resp.text()}`
458
- );
459
- }
460
- return resp.json();
461
- }
462
- async function doPost(path, body) {
463
- const url = `${base}${path}`;
464
- const headers = {
465
- Cookie: session.jar.headerFor(url),
466
- Accept: "application/json",
467
- "Content-Type": "application/json"
468
- };
469
- const xsrf = session.jar.getCookie(url, "XSRF-TOKEN");
470
- if (xsrf) {
471
- headers["X-XSRF-TOKEN"] = xsrf;
472
- }
473
- const resp = await fetch(url, {
474
- method: "POST",
475
- headers,
476
- body: JSON.stringify(body)
477
- });
478
- if (resp.status === 401 || resp.status === 302) {
479
- throw new Error(
480
- "Session expired \u2014 run `acculynx unofficial login` to re-authenticate"
481
- );
482
- }
483
- if (!resp.ok) {
484
- throw new Error(
485
- `Unofficial API error (${resp.status}): ${await resp.text()}`
486
- );
487
- }
488
- const text = await resp.text();
489
- if (!text) return {};
490
- return JSON.parse(text);
491
- }
492
- async function doGetBuffer(url) {
493
- const fullUrl = url.startsWith("http") ? url : `${base}${url}`;
494
- const resp = await fetch(fullUrl, {
495
- headers: { Cookie: session.jar.headerFor(fullUrl) }
496
- });
497
- if (!resp.ok) {
498
- throw new Error(`Download failed (${resp.status}): ${fullUrl}`);
499
- }
500
- return Buffer.from(await resp.arrayBuffer());
501
- }
502
- return { get: doGet, post: doPost, getBuffer: doGetBuffer };
503
- }
504
-
505
- // src/unofficial/session.ts
506
- async function fetchFollowingCookies(jar, url, init) {
507
- let currentUrl = url;
508
- let response;
509
- for (let i = 0; i < 10; i++) {
510
- response = await fetch(currentUrl, {
511
- ...init,
512
- redirect: "manual",
513
- headers: {
514
- ...Object.fromEntries(
515
- Object.entries(init?.headers ?? {})
516
- ),
517
- Cookie: jar.headerFor(currentUrl)
518
- }
519
- });
520
- jar.capture(currentUrl, response);
521
- const location = response.headers.get("Location");
522
- if (!location || response.status < 300 || response.status >= 400) {
523
- return response;
524
- }
525
- currentUrl = new URL(location, currentUrl).href;
526
- init = { redirect: "manual" };
527
- }
528
- throw new Error("Too many redirects");
529
- }
530
- async function authenticate(email, password) {
531
- const jar = new CookieJar();
532
- const signinResp = await fetchFollowingCookies(
533
- jar,
534
- "https://my.acculynx.com/signin/"
535
- );
536
- const html = await signinResp.text();
537
- const actionMatch = html.match(/<form[^>]*action="([^"]*)"/);
538
- if (!actionMatch) throw new Error("Could not find login form action");
539
- const formAction = actionMatch[1].replace(/&amp;/g, "&");
540
- const thumbprint = html.match(/name="DeviceThumbprint"[^>]*value="([^"]*)"/)?.[1] ?? "";
541
- const deviceName = html.match(/name="DeviceName"[^>]*value="([^"]*)"/)?.[1] ?? "Node.js CLI";
542
- const body = new URLSearchParams({
543
- Email: email,
544
- Password: password,
545
- DeviceThumbprint: thumbprint,
546
- DeviceName: deviceName
547
- });
548
- const loginResp = await fetchFollowingCookies(jar, formAction, {
549
- method: "POST",
550
- headers: { "Content-Type": "application/x-www-form-urlencoded" },
551
- body: body.toString()
552
- });
553
- const locationResp = await fetchFollowingCookies(
554
- jar,
555
- "https://my.acculynx.com/signin/LocationSelector"
556
- );
557
- const locationHtml = await locationResp.text();
558
- return { jar, locationHtml };
559
- }
560
- async function listCompanies(email, password) {
561
- const { locationHtml } = await authenticate(email, password);
562
- const companyPattern = /SwitchCompany\?CompanyID=([0-9a-f-]+)"[^>]*>([^<]+)/gi;
563
- const companies = [];
564
- let match;
565
- while ((match = companyPattern.exec(locationHtml)) !== null) {
566
- companies.push({ id: match[1], name: match[2].trim() });
567
- }
568
- return companies;
569
- }
570
- async function login(email, password, companyId) {
571
- const { jar } = await authenticate(email, password);
572
- await fetchFollowingCookies(
573
- jar,
574
- `https://my.acculynx.com/signin/SwitchCompany?CompanyID=${companyId}`
575
- );
576
- return { jar, companyId, email };
577
- }
578
-
579
- // src/unofficial/commands/login.ts
580
- function getCredentials(opts) {
581
- const email = opts.email ?? process.env.ACCULYNX_EMAIL;
582
- const password = opts.password ?? process.env.ACCULYNX_PASSWORD;
583
- const companyId = opts.companyId ?? process.env.ACCULYNX_COMPANY_ID;
584
- if (!email) {
585
- throw new Error(
586
- "Missing email: pass --email or set ACCULYNX_EMAIL"
587
- );
588
- }
589
- if (!password) {
590
- throw new Error(
591
- "Missing password: pass --password or set ACCULYNX_PASSWORD"
592
- );
593
- }
594
- if (!companyId) {
595
- throw new Error(
596
- "Missing company ID: pass --company-id or set ACCULYNX_COMPANY_ID"
597
- );
598
- }
599
- return { email, password, companyId };
600
- }
601
- function registerLoginCommands(parentCmd) {
602
- parentCmd.command("login").description("Authenticate and cache session cookies").option("--email <email>", "AccuLynx email (env: ACCULYNX_EMAIL)").option(
603
- "--password <password>",
604
- "AccuLynx password (env: ACCULYNX_PASSWORD)"
605
- ).option(
606
- "--company-id <id>",
607
- "Company GUID (env: ACCULYNX_COMPANY_ID)"
608
- ).action(async (opts) => {
609
- const { email, password, companyId } = getCredentials(opts);
610
- const session = await login(email, password, companyId);
611
- saveSession(session);
612
- console.log(
613
- JSON.stringify({
614
- status: "ok",
615
- email,
616
- companyId,
617
- message: "Session cached successfully"
618
- })
619
- );
620
- });
621
- parentCmd.command("companies").description(
622
- "List available companies for your account (discovers company IDs)"
623
- ).option("--email <email>", "AccuLynx email (env: ACCULYNX_EMAIL)").option(
624
- "--password <password>",
625
- "AccuLynx password (env: ACCULYNX_PASSWORD)"
626
- ).action(async (opts) => {
627
- const email = opts.email ?? process.env.ACCULYNX_EMAIL;
628
- const password = opts.password ?? process.env.ACCULYNX_PASSWORD;
629
- if (!email) {
630
- throw new Error(
631
- "Missing email: pass --email or set ACCULYNX_EMAIL"
632
- );
633
- }
634
- if (!password) {
635
- throw new Error(
636
- "Missing password: pass --password or set ACCULYNX_PASSWORD"
637
- );
638
- }
639
- const companies = await listCompanies(email, password);
640
- console.log(JSON.stringify(companies));
641
- });
642
- parentCmd.command("sessions").description("List cached sessions").action(() => {
643
- const sessions = listSessions();
644
- console.log(JSON.stringify(sessions));
645
- });
646
- parentCmd.command("logout").description("Remove a cached session").option("--email <email>", "AccuLynx email (env: ACCULYNX_EMAIL)").option(
647
- "--company-id <id>",
648
- "Company GUID (env: ACCULYNX_COMPANY_ID)"
649
- ).action((opts) => {
650
- const email = opts.email ?? process.env.ACCULYNX_EMAIL;
651
- const companyId = opts.companyId ?? process.env.ACCULYNX_COMPANY_ID;
652
- if (!email || !companyId) {
653
- throw new Error(
654
- "Both --email and --company-id are required (or set env vars)"
655
- );
656
- }
657
- const removed = deleteSession(email, companyId);
658
- console.log(
659
- JSON.stringify({
660
- status: removed ? "removed" : "not_found",
661
- email,
662
- companyId
663
- })
664
- );
665
- });
666
- }
667
-
668
- // src/unofficial/commands/documents.ts
669
- import { writeFileSync as writeFileSync2 } from "fs";
670
- function registerDocumentsCommands(parentCmd, getClient2) {
671
- const docs = parentCmd.command("documents").description("Job document operations");
672
- docs.command("list").argument("<jobId>", "Job ID (GUID)").description("List all document folders and files for a job").action(async (jobId) => {
673
- const folders = await getClient2().get(
674
- `/api/v4/job-documents/${jobId}/job-document-folders`
675
- );
676
- const result = folders.map((folder) => ({
677
- folder: folder.Name,
678
- folderId: folder.Id,
679
- fileCount: folder.FileCount,
680
- files: folder.Files.map((f) => ({
681
- id: f.Id,
682
- name: f.Name,
683
- extension: f.Extension,
684
- size: f.Size,
685
- mimeType: f.MIMEType,
686
- href: f.Href,
687
- createdBy: f.CreatedByDisplayName,
688
- modifiedDate: f.ModifiedDateUTC
689
- }))
690
- }));
691
- console.log(JSON.stringify(result));
692
- });
693
- docs.command("download").argument("<jobId>", "Job ID (GUID)").argument("<fileId>", "File ID (GUID)").option("--output <path>", "Write to file instead of stdout").description("Download a document file").action(async (jobId, fileId, opts) => {
694
- const folders = await getClient2().get(
695
- `/api/v4/job-documents/${jobId}/job-document-folders`
696
- );
697
- let targetFile;
698
- for (const folder of folders) {
699
- targetFile = folder.Files.find((f) => f.Id === fileId);
700
- if (targetFile) break;
701
- }
702
- if (!targetFile) {
703
- throw new Error(
704
- `File ${fileId} not found in job ${jobId} documents`
705
- );
706
- }
707
- const buffer = await getClient2().getBuffer(targetFile.Href);
708
- if (opts.output) {
709
- writeFileSync2(opts.output, buffer);
710
- console.error(
711
- JSON.stringify({
712
- status: "ok",
713
- file: targetFile.Name,
714
- size: buffer.length,
715
- output: opts.output
716
- })
717
- );
718
- } else {
719
- process.stdout.write(buffer);
720
- }
721
- });
722
- }
723
-
724
- // src/unofficial/commands/messages.ts
725
- import TurndownService from "turndown";
726
- function createTurndown() {
727
- const td = new TurndownService({
728
- headingStyle: "atx",
729
- bulletListMarker: "-"
730
- });
731
- td.addRule("removeImages", {
732
- filter: "img",
733
- replacement: () => ""
734
- });
735
- td.addRule("removeStyle", {
736
- filter: ["style", "script"],
737
- replacement: () => ""
738
- });
739
- return td;
740
- }
741
- var looksLikeHtml = /<[a-z][\s\S]*?>/i;
742
- function cleanMessage(html) {
743
- if (!looksLikeHtml.test(html)) return html;
744
- const td = createTurndown();
745
- return td.turndown(html).replace(/\n{3,}/g, "\n\n").trim();
746
- }
747
- function registerMessagesCommands(parentCmd, getClient2) {
748
- const messages = parentCmd.command("messages").description("Job message/comment operations");
749
- messages.command("list").argument("<jobId>", "Job ID (GUID)").option(
750
- "--sort <sort>",
751
- "Sort field and direction (field|asc or field|desc)",
752
- "createdDate|desc"
753
- ).option("--count-only", "Return only the total count of messages").option(
754
- "--type <type>",
755
- "Filter by message type: Comment, Email, or Signatures"
756
- ).description("List all messages and comments for a job").action(async (jobId, opts) => {
757
- const params = new URLSearchParams({ sort: opts.sort });
758
- if (opts.countOnly) {
759
- params.set("countOnly", "true");
760
- }
761
- if (opts.type) {
762
- params.append("filters", `type=${opts.type}`);
763
- }
764
- const data = await getClient2().get(
765
- `/api/jobs/${jobId}/JobMessageFeed?${params.toString()}`
766
- );
767
- if (opts.countOnly) {
768
- console.log(JSON.stringify({ totalRecords: data.TotalRecords }));
769
- return;
770
- }
771
- const result = {
772
- totalRecords: data.TotalRecords,
773
- currentPage: data.CurrentPage,
774
- totalPages: data.TotalPages,
775
- messages: data.results.map((msg) => ({
776
- id: msg.id,
777
- jobId: msg.JobId,
778
- type: msg.Type,
779
- messageType: msg.MessageType,
780
- message: cleanMessage(msg.Message),
781
- subject: msg.Subject,
782
- createdBy: msg.CreatedBy,
783
- createdById: msg.CreatedByID,
784
- createdDate: msg.CreatedDate,
785
- latestMessage: msg.LatestMessage,
786
- parentMessageId: msg.ParentMessageId,
787
- attachmentOnly: msg.AttachmentOnly,
788
- replyEmail: msg.ReplyEmail,
789
- sentDate: msg.SentDate,
790
- recipients: msg.Recipients.map((r) => ({
791
- id: r.id,
792
- companyUserId: r.companyUserId,
793
- sent: r.Sent,
794
- sentDate: r.SentDate,
795
- delivered: r.Delivered,
796
- deliveredDate: r.DeliveredDate,
797
- failed: r.Failed,
798
- failedDate: r.FailedDate,
799
- failedDescription: r.FailedDescription
800
- })),
801
- attachments: msg.Attachments,
802
- childMessageCount: msg.ChildMessages.length,
803
- childMessages: msg.ChildMessages.map((child) => ({
804
- id: child.id,
805
- type: child.Type,
806
- message: cleanMessage(child.Message),
807
- createdBy: child.CreatedBy,
808
- createdDate: child.CreatedDate
809
- }))
810
- }))
811
- };
812
- console.log(JSON.stringify(result));
813
- });
814
- messages.command("post").argument("<jobId>", "Job ID (GUID)").argument("<message>", "Message text to post").option(
815
- "--notify <userIds>",
816
- "Comma-separated user IDs (GUIDs) to notify"
817
- ).description("Post a comment/message to a job, optionally notifying users").action(async (jobId, message, opts) => {
818
- const emailRecipients = opts.notify ? opts.notify.split(",").map((id) => id.trim()) : [];
819
- const data = await getClient2().post(
820
- `/api/jobs/${jobId}/Messages`,
821
- {
822
- JobId: jobId,
823
- Message: message,
824
- RoleId: "1111111",
825
- MessageType: "General Comment",
826
- emailRecipients,
827
- index: -1
828
- }
829
- );
830
- console.log(
831
- JSON.stringify({
832
- id: data.JobMessageId,
833
- jobId: data.JobId,
834
- message: data.Message,
835
- messageType: data.MessageType,
836
- createdDate: data.CreatedDate,
837
- notified: emailRecipients.length
838
- })
839
- );
840
- });
841
- }
842
-
843
- // src/unofficial/commands/milestones.ts
844
- function registerMilestonesCommands(parentCmd, getClient2) {
845
- const milestones = parentCmd.command("milestones").description("Job milestone/status operations");
846
- milestones.command("list").argument("<jobId>", "Job ID (GUID)").description("List all milestones and statuses for a job's workflow").action(async (jobId) => {
847
- const data = await getClient2().get(
848
- `/api/v3/job-workflows/${jobId}`
849
- );
850
- const result = data.Milestones.map((m) => ({
851
- milestoneId: m.MilestoneId,
852
- name: m.Name,
853
- isCurrent: m.IsCurrent,
854
- done: m.Done,
855
- statuses: m.Statuses.map((s) => ({
856
- statusId: s.StatusId,
857
- name: s.Name.trim(),
858
- isCurrent: s.IsCurrent,
859
- done: s.Done
860
- }))
861
- }));
862
- console.log(JSON.stringify(result));
863
- });
864
- milestones.command("set").argument("<jobId>", "Job ID (GUID)").argument("<statusName>", "Destination milestone/status name (case-insensitive)").option("--message <message>", "Optional comment when advancing", "").description("Set a job's milestone/status by name").action(async (jobId, statusName, opts) => {
865
- const data = await getClient2().get(
866
- `/api/v3/job-workflows/${jobId}`
867
- );
868
- const needle = statusName.toLowerCase().trim();
869
- let matchedMilestoneId = null;
870
- let matchedStatus = null;
871
- for (const m of data.Milestones) {
872
- if (m.Name.toLowerCase().trim() === needle) {
873
- matchedMilestoneId = m.MilestoneId;
874
- matchedStatus = m.Statuses[0] ?? null;
875
- break;
876
- }
877
- for (const s of m.Statuses) {
878
- if (s.Name.toLowerCase().trim() === needle) {
879
- matchedMilestoneId = m.MilestoneId;
880
- matchedStatus = s;
881
- break;
882
- }
883
- }
884
- if (matchedStatus) break;
885
- }
886
- if (!matchedMilestoneId || !matchedStatus) {
887
- const available = data.Milestones.flatMap(
888
- (m) => m.Statuses.map((s) => s.Name.trim())
889
- );
890
- console.error(
891
- JSON.stringify({
892
- error: `Status "${statusName}" not found`,
893
- available
894
- })
895
- );
896
- process.exitCode = 1;
897
- return;
898
- }
899
- await getClient2().post(
900
- `/api/v3/job-workflows/${jobId}/set-state`,
901
- {
902
- MilestoneId: matchedMilestoneId,
903
- StatusId: matchedStatus.StatusId,
904
- Message: opts.message
905
- }
906
- );
907
- console.log(
908
- JSON.stringify({
909
- jobId,
910
- milestoneId: matchedMilestoneId,
911
- statusId: matchedStatus.StatusId,
912
- statusName: matchedStatus.Name.trim(),
913
- message: opts.message || null
914
- })
915
- );
916
- });
917
- }
918
-
919
- // src/unofficial/commands/jobs.ts
920
- async function resolveStatusId(client, statusName) {
921
- const workflow = await client.get(
922
- "/api/v3/workflows"
923
- );
924
- const needle = statusName.toLowerCase().trim();
925
- for (const m of workflow.Milestones) {
926
- for (const s of m.Statuses) {
927
- if (s.Name.toLowerCase().trim() === needle) {
928
- return { statusId: s.StatusId, milestoneName: m.Name };
929
- }
930
- }
931
- }
932
- return null;
933
- }
934
- async function getAvailableStatuses(client) {
935
- const workflow = await client.get(
936
- "/api/v3/workflows"
937
- );
938
- return workflow.Milestones.flatMap(
939
- (m) => m.Statuses.map((s) => s.Name.trim())
940
- );
941
- }
942
- function registerUnofficialJobsCommands(parentCmd, getClient2) {
943
- const jobs = parentCmd.command("jobs").description("Unofficial job search with workflow status filtering");
944
- jobs.command("list").description("List jobs, optionally filtered by workflow status or milestone").option("--status <name>", "Filter by workflow status name (case-insensitive)").option("--milestone <name>", "Filter by milestone name (e.g. Prospect, Approved)").option("--query <text>", "Search term").option("--sort <field>", "Sort: milestoneStart|desc, lastTouched|desc, createdDate|desc", "milestoneStart|desc").option("--page <n>", "Page number", "1").action(async (opts) => {
945
- const client = getClient2();
946
- const params = new URLSearchParams();
947
- if (opts.status) {
948
- const resolved = await resolveStatusId(client, opts.status);
949
- if (!resolved) {
950
- const available = await getAvailableStatuses(client);
951
- console.error(
952
- JSON.stringify({
953
- error: `Status "${opts.status}" not found`,
954
- available
955
- })
956
- );
957
- process.exitCode = 1;
958
- return;
959
- }
960
- params.append("filters", `currentStatusId=${resolved.statusId}`);
961
- }
962
- if (opts.milestone) {
963
- params.append("filters", `currentMilestoneList=${opts.milestone}`);
964
- }
965
- params.set("sort", opts.sort);
966
- params.set("page", opts.page);
967
- params.set("type", "2");
968
- params.set("loadAll", "false");
969
- if (opts.query) params.set("query", opts.query);
970
- const data = await client.get(
971
- `/api/joblist?${params.toString()}`
972
- );
973
- const result = {
974
- totalRecords: data.TotalRecords,
975
- currentPage: data.CurrentPage,
976
- totalPages: data.TotalPages,
977
- jobs: data.results.map((j) => ({
978
- id: j.Id,
979
- name: j.Name,
980
- address: j.FullAddress,
981
- cityState: j.CityState,
982
- milestone: j.CurrentMilestone,
983
- status: j.CurrentStatus,
984
- salesPerson: j.SalesPerson,
985
- createdDate: j.CreatedDate,
986
- lastTouched: j.LastTouched,
987
- workTypes: j.WorkTypes,
988
- trades: j.Trades
989
- }))
990
- };
991
- console.log(JSON.stringify(result));
992
- });
993
- }
994
-
995
- // src/unofficial/commands/index.ts
996
- function getSessionFromEnv() {
997
- const email = process.env.ACCULYNX_EMAIL;
998
- const companyId = process.env.ACCULYNX_COMPANY_ID;
999
- if (!email || !companyId) {
1000
- throw new Error(
1001
- "Set ACCULYNX_EMAIL and ACCULYNX_COMPANY_ID (or run `acculynx unofficial login` first)"
1002
- );
1003
- }
1004
- const session = loadSession(email, companyId);
1005
- if (!session) {
1006
- throw new Error(
1007
- `No cached session for ${email} / ${companyId}. Run \`acculynx unofficial login\` first.`
1008
- );
1009
- }
1010
- return session;
1011
- }
1012
- function registerUnofficialCommands(parentCmd) {
1013
- const unofficial = parentCmd.command("unofficial").description(
1014
- "Unofficial web API commands (cookie-based auth, reverse-engineered)"
1015
- );
1016
- registerLoginCommands(unofficial);
1017
- let _client2 = null;
1018
- function getClient2() {
1019
- if (!_client2) {
1020
- _client2 = createUnofficialClient(getSessionFromEnv());
1021
- }
1022
- return _client2;
1023
- }
1024
- registerDocumentsCommands(unofficial, getClient2);
1025
- registerMessagesCommands(unofficial, getClient2);
1026
- registerMilestonesCommands(unofficial, getClient2);
1027
- registerUnofficialJobsCommands(unofficial, getClient2);
1028
- }
1029
-
1030
313
  // src/index.ts
314
+ var require2 = createRequire(import.meta.url);
315
+ var { version } = require2("../package.json");
1031
316
  var program = new Command();
1032
- program.name("acculynx").description("AccuLynx CRM CLI for AI agents").version("0.1.0").exitOverride().configureOutput({
317
+ program.name("acculynx").description("AccuLynx CRM CLI for AI agents").version(version).exitOverride().configureOutput({
1033
318
  writeOut: (str) => process.stdout.write(str),
1034
319
  writeErr: (str) => {
1035
320
  const trimmed = str.trim();
@@ -1057,7 +342,11 @@ registerPingCommand(program, getClient);
1057
342
  registerJobsCommands(program, getClient);
1058
343
  registerContactsCommands(program, getClient);
1059
344
  registerEstimatesCommands(program, getClient);
1060
- registerUnofficialCommands(program);
345
+ try {
346
+ const mod = await import("@opsrev/acculynx-cli-unofficial");
347
+ mod.registerUnofficialCommands(program);
348
+ } catch {
349
+ }
1061
350
  program.parseAsync().catch((err) => {
1062
351
  if (err.message === "(outputHelp)" || err.message === "(version)") {
1063
352
  return;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@opsrev/acculynx-cli",
3
- "version": "1.6.0",
3
+ "version": "1.7.0",
4
4
  "description": "CLI for the AccuLynx roofing CRM API",
5
5
  "type": "module",
6
6
  "bin": {
@@ -28,12 +28,10 @@
28
28
  "dist"
29
29
  ],
30
30
  "dependencies": {
31
- "commander": "^14.0.3",
32
- "turndown": "^7.2.2"
31
+ "commander": "^14.0.3"
33
32
  },
34
33
  "devDependencies": {
35
34
  "@types/node": "^25.4.0",
36
- "@types/turndown": "^5.0.6",
37
35
  "tsup": "^8.5.1",
38
36
  "tsx": "^4.21.0",
39
37
  "typescript": "^5.9.3",