ledgercrossing 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +135 -3
- package/dist/index.cjs +524 -0
- package/dist/index.d.cts +248 -0
- package/dist/index.d.ts +248 -0
- package/dist/index.js +502 -0
- package/package.json +65 -6
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 EFFIQUEST, LLC
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,135 @@
|
|
|
1
|
-
#
|
|
2
|
-
|
|
3
|
-
|
|
1
|
+
# ledgercrossing
|
|
2
|
+
|
|
3
|
+
TypeScript/JavaScript client for the **QuickBooks Desktop API** through
|
|
4
|
+
[LedgerCrossing](https://ledgercrossing.com/quickbooks-desktop-api). It sends qbXML to QuickBooks Desktop over plain
|
|
5
|
+
HTTP and returns QuickBooks' answer in the same call. There's no Web Connector, no SOAP service to host, and no polling.
|
|
6
|
+
No runtime dependencies; types included; ESM and CommonJS.
|
|
7
|
+
|
|
8
|
+
```bash
|
|
9
|
+
npm install ledgercrossing
|
|
10
|
+
```
|
|
11
|
+
|
|
12
|
+
```ts
|
|
13
|
+
import { LedgerCrossing } from "ledgercrossing";
|
|
14
|
+
|
|
15
|
+
const lc = new LedgerCrossing(); // http://localhost:8284 on the QuickBooks computer; no key needed there
|
|
16
|
+
|
|
17
|
+
const reply = await lc.qbxml(`<?xml version="1.0"?><?qbxml version="13.0"?>
|
|
18
|
+
<QBXML><QBXMLMsgsRq onError="stopOnError">
|
|
19
|
+
<CustomerQueryRq><MaxReturned>10</MaxReturned></CustomerQueryRq>
|
|
20
|
+
</QBXMLMsgsRq></QBXML>`);
|
|
21
|
+
|
|
22
|
+
console.log(String(reply)); // QuickBooks' own qbXML, with statusCode="0" on success
|
|
23
|
+
|
|
24
|
+
for (const customer of reply.records()) { // the CustomerRet elements
|
|
25
|
+
console.log(customer.findText("FullName"), customer.findText("Balance"));
|
|
26
|
+
}
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
## What you need
|
|
30
|
+
|
|
31
|
+
- **QuickBooks Desktop** Pro, Premier or Enterprise for Windows, 2019 or later.
|
|
32
|
+
- **[LedgerCrossing](https://ledgercrossing.com)** on the computer where QuickBooks Desktop runs. It's a one-time purchase per computer, with unlimited company files. This package is the client; LedgerCrossing is the connection to QuickBooks.
|
|
33
|
+
- **Node.js 18 or later** (it uses the built-in `fetch`), on any operating system. Only the QuickBooks computer needs Windows.
|
|
34
|
+
|
|
35
|
+
Works with anything that can make a web request. If you rely on an off-the-shelf app that syncs through the Web
|
|
36
|
+
Connector, that vendor controls the connection, and LedgerCrossing doesn't slip in underneath it.
|
|
37
|
+
|
|
38
|
+
## Connecting from where your code runs
|
|
39
|
+
|
|
40
|
+
| Your code runs | URL | Key |
|
|
41
|
+
|---|---|---|
|
|
42
|
+
| On the QuickBooks computer | `http://localhost:8284` (the default) | Not needed |
|
|
43
|
+
| On another computer in the office | `http://<machine-name>:8284`, after turning on **Settings > Allowed Connections > Local network** | The API key from **Settings > Allowed Connections** |
|
|
44
|
+
| Anywhere else, through [LedgerCrossing Remote](https://ledgercrossing.com/remote) | Your Remote address | The API key, with **Allow the API key** turned on under **Settings > Allowed Connections > Internet** |
|
|
45
|
+
| Anywhere else, through [your own Cloudflare Tunnel](https://ledgercrossing.com/docs/quickbooks-remote-access-cloudflare-tunnel) | Your tunnel's address | The API key, with **Local network** turned on: LedgerCrossing treats a tunnel on its own computer like the office network |
|
|
46
|
+
|
|
47
|
+
```ts
|
|
48
|
+
const lc = new LedgerCrossing({ url: process.env.LC_URL, apiKey: process.env.LC_KEY });
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
Over Remote, Internet access starts read-only: writes are refused until you turn off **Read-only** under
|
|
52
|
+
**Settings > Allowed Connections > Internet**.
|
|
53
|
+
|
|
54
|
+
Signing in as a person over Remote (the sign-in that claude.ai uses) isn't supported by this package yet; use the
|
|
55
|
+
API key.
|
|
56
|
+
|
|
57
|
+
This package is for servers, scripts and desktop apps. LedgerCrossing refuses requests from a web page on another
|
|
58
|
+
website, so don't call it from a browser.
|
|
59
|
+
|
|
60
|
+
## Which company file
|
|
61
|
+
|
|
62
|
+
It follows the **QuickBooks File** page in LedgerCrossing. If it's set to **The caller names the file in each
|
|
63
|
+
request**, pass `companyFile`:
|
|
64
|
+
|
|
65
|
+
```ts
|
|
66
|
+
await lc.qbxml(xml, { companyFile: "C:\\Users\\Public\\Documents\\Intuit\\QuickBooks\\Company Files\\MyCompany.qbw" });
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
## Helpers
|
|
70
|
+
|
|
71
|
+
Three shortcuts for common reads. Each one is bounded, so it never trips the unbounded-query rule, and each returns
|
|
72
|
+
the same `Reply` as `qbxml()`:
|
|
73
|
+
|
|
74
|
+
```ts
|
|
75
|
+
await lc.customers({ maxReturned: 100 });
|
|
76
|
+
await lc.invoices({ fromDate: "2026-10-01", toDate: "2026-10-31", maxReturned: 50, includeLineItems: true });
|
|
77
|
+
await lc.profitAndLoss({ fromDate: "2026-01-01", toDate: "2026-06-30", basis: "Accrual" }); // basis is optional
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
Dates are `"YYYY-MM-DD"` or a `Date` (its local calendar date). Every helper also takes `companyFile`.
|
|
81
|
+
|
|
82
|
+
`await lc.health()` checks that LedgerCrossing is reachable; it needs no key.
|
|
83
|
+
|
|
84
|
+
## The reply
|
|
85
|
+
|
|
86
|
+
`qbxml()` resolves to a `Reply`:
|
|
87
|
+
|
|
88
|
+
- `String(reply)` or `reply.raw`: QuickBooks' XML, exactly as it came.
|
|
89
|
+
- `reply.responses`: one entry per response element, with `name` (e.g. `CustomerQueryRs`), `statusCode`,
|
|
90
|
+
`statusSeverity`, `statusMessage`, `ok` and `element`.
|
|
91
|
+
- `reply.records()`: every returned record (`CustomerRet`, `InvoiceRet`, `ReportRet`, ...) as `XmlElement`s, with
|
|
92
|
+
`name`, `attributes`, `children`, `text`, `find(name)`, `findAll(name)`, `findText(name)` and `get(attribute)`.
|
|
93
|
+
- `reply.ok`: false if any response has severity `Error`.
|
|
94
|
+
- `reply.raiseForStatus()`: throws `QuickBooksStatusError` if any response is an error, and returns the reply otherwise.
|
|
95
|
+
|
|
96
|
+
A QuickBooks error inside a reply isn't thrown on its own: with `onError="continueOnError"` a mix of results is normal.
|
|
97
|
+
Status code 1 ("did not find a matching object") is an Info status, not an error.
|
|
98
|
+
|
|
99
|
+
## Errors
|
|
100
|
+
|
|
101
|
+
LedgerCrossing refusing or failing a request throws a subclass of `LedgerCrossingError`, with `status`, `message`,
|
|
102
|
+
`code` (when sent), `retryAfter` (when sent) and `body`:
|
|
103
|
+
|
|
104
|
+
| Status | Error | Meaning |
|
|
105
|
+
|---|---|---|
|
|
106
|
+
| `400` | `BadRequestError` | Malformed request, an unbounded query (below), an event-subscription request, or a company file the current mode doesn't accept |
|
|
107
|
+
| `401` | `AuthenticationError` | Missing or wrong API key |
|
|
108
|
+
| `403` | `ReadOnlyError` | The request would change the books, and Internet connections, or this signed-in person, are read-only |
|
|
109
|
+
| `403` | `PermissionDeniedError` | The company file is outside the person's list, or the request was refused at the door (`refusedAtDoor`: Local network is off, or the caller isn't on a private address or the allowlist) |
|
|
110
|
+
| `409` | `ConflictError` | Conflicts with QuickBooks' current state, for example the file is in use, or QuickBooks didn't open it in time (`code` `QB_OPEN_TIMEOUT`) |
|
|
111
|
+
| `429` | `RateLimitError` | Queue full or waited too long (`queueDepth`), or too many wrong keys from one address; wait `retryAfter` seconds |
|
|
112
|
+
| `500` | `ServerError` | A genuine fault; `code` names it, e.g. an HRESULT |
|
|
113
|
+
| `503` | `UnavailableError` | QuickBooks isn't responding (`QB_NOT_RESPONDING`) or LedgerCrossing is shutting down (`SHUTTING_DOWN`); wait `retryAfter` seconds |
|
|
114
|
+
| none | `NetworkError`, `RequestTimeoutError` | LedgerCrossing couldn't be reached, or didn't answer within `timeoutMs` (300000 by default) |
|
|
115
|
+
|
|
116
|
+
Branch on the error class or on `code`; the wording of `message` is for people and may change. After a
|
|
117
|
+
`RequestTimeoutError` the request may still run in QuickBooks, so check before sending an add again.
|
|
118
|
+
|
|
119
|
+
**Unbounded queries are refused.** A list or transaction query needs `<MaxReturned>`, an iterator, or a specific
|
|
120
|
+
record (`<ListID>` / `<FullName>`). Otherwise LedgerCrossing answers `400` before the request reaches QuickBooks.
|
|
121
|
+
|
|
122
|
+
## Using it with AI assistants
|
|
123
|
+
|
|
124
|
+
LedgerCrossing also includes an MCP server, so Claude, ChatGPT, Meta Muse, Grok Bot, Claude Desktop, Claude Code,
|
|
125
|
+
Cursor, VS Code, Codex and Gemini CLI can work with the same company file. See the
|
|
126
|
+
[QuickBooks Desktop MCP server quickstart](https://ledgercrossing.com/docs/mcp).
|
|
127
|
+
|
|
128
|
+
## Links
|
|
129
|
+
|
|
130
|
+
- [QuickBooks Desktop API reference](https://ledgercrossing.com/quickbooks-desktop-api): endpoint, bodies and status codes
|
|
131
|
+
- [Source](https://github.com/LedgerCrossing/ledgercrossing-clients) and [examples](https://github.com/LedgerCrossing/quickbooks-desktop-mcp) on GitHub
|
|
132
|
+
- [Security and IT review](https://ledgercrossing.com/security)
|
|
133
|
+
|
|
134
|
+
MIT license. QuickBooks is a registered trademark of Intuit Inc. LedgerCrossing is not affiliated with or endorsed by
|
|
135
|
+
Intuit.
|
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,524 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// src/errors.ts
|
|
4
|
+
var LedgerCrossingError = class extends Error {
|
|
5
|
+
status;
|
|
6
|
+
code;
|
|
7
|
+
retryAfter;
|
|
8
|
+
body;
|
|
9
|
+
headers;
|
|
10
|
+
constructor(message, details = {}) {
|
|
11
|
+
super(message, details.cause === void 0 ? void 0 : { cause: details.cause });
|
|
12
|
+
this.name = new.target.name;
|
|
13
|
+
this.status = details.status;
|
|
14
|
+
this.code = details.code;
|
|
15
|
+
this.retryAfter = details.retryAfter;
|
|
16
|
+
this.body = details.body;
|
|
17
|
+
this.headers = details.headers ?? {};
|
|
18
|
+
}
|
|
19
|
+
};
|
|
20
|
+
var NetworkError = class extends LedgerCrossingError {
|
|
21
|
+
};
|
|
22
|
+
var RequestTimeoutError = class extends NetworkError {
|
|
23
|
+
};
|
|
24
|
+
var BadRequestError = class extends LedgerCrossingError {
|
|
25
|
+
};
|
|
26
|
+
var AuthenticationError = class extends LedgerCrossingError {
|
|
27
|
+
};
|
|
28
|
+
var PermissionDeniedError = class extends LedgerCrossingError {
|
|
29
|
+
refusedAtDoor;
|
|
30
|
+
constructor(message, details = {}) {
|
|
31
|
+
super(message, details);
|
|
32
|
+
this.refusedAtDoor = details.refusedAtDoor ?? false;
|
|
33
|
+
}
|
|
34
|
+
};
|
|
35
|
+
var ReadOnlyError = class extends PermissionDeniedError {
|
|
36
|
+
};
|
|
37
|
+
var NotFoundError = class extends LedgerCrossingError {
|
|
38
|
+
};
|
|
39
|
+
var ConflictError = class extends LedgerCrossingError {
|
|
40
|
+
};
|
|
41
|
+
var RateLimitError = class extends LedgerCrossingError {
|
|
42
|
+
queueDepth;
|
|
43
|
+
constructor(message, details = {}) {
|
|
44
|
+
super(message, details);
|
|
45
|
+
this.queueDepth = details.queueDepth;
|
|
46
|
+
}
|
|
47
|
+
};
|
|
48
|
+
var ServerError = class extends LedgerCrossingError {
|
|
49
|
+
};
|
|
50
|
+
var UnavailableError = class extends ServerError {
|
|
51
|
+
};
|
|
52
|
+
var QuickBooksStatusError = class extends LedgerCrossingError {
|
|
53
|
+
responses;
|
|
54
|
+
constructor(message, details = {}) {
|
|
55
|
+
super(message, details);
|
|
56
|
+
this.responses = details.responses ?? [];
|
|
57
|
+
}
|
|
58
|
+
};
|
|
59
|
+
|
|
60
|
+
// src/xml.ts
|
|
61
|
+
var XmlParseError = class extends Error {
|
|
62
|
+
constructor(message, position) {
|
|
63
|
+
super(`${message} (at character ${position})`);
|
|
64
|
+
this.position = position;
|
|
65
|
+
this.name = "XmlParseError";
|
|
66
|
+
}
|
|
67
|
+
position;
|
|
68
|
+
};
|
|
69
|
+
var XmlElement = class {
|
|
70
|
+
constructor(name, attributes = {}) {
|
|
71
|
+
this.name = name;
|
|
72
|
+
this.attributes = attributes;
|
|
73
|
+
}
|
|
74
|
+
name;
|
|
75
|
+
attributes;
|
|
76
|
+
/** Direct text content, entities decoded; "" for an element that only holds other elements. */
|
|
77
|
+
text = "";
|
|
78
|
+
children = [];
|
|
79
|
+
/** The first direct child with this name. */
|
|
80
|
+
find(name) {
|
|
81
|
+
return this.children.find((c) => c.name === name);
|
|
82
|
+
}
|
|
83
|
+
/** Every direct child with this name. */
|
|
84
|
+
findAll(name) {
|
|
85
|
+
return this.children.filter((c) => c.name === name);
|
|
86
|
+
}
|
|
87
|
+
/** The text of the first direct child with this name, or undefined when there is none. */
|
|
88
|
+
findText(name) {
|
|
89
|
+
return this.find(name)?.text;
|
|
90
|
+
}
|
|
91
|
+
/** An attribute's value, or undefined. */
|
|
92
|
+
get(attribute) {
|
|
93
|
+
return Object.prototype.hasOwnProperty.call(this.attributes, attribute) ? this.attributes[attribute] : void 0;
|
|
94
|
+
}
|
|
95
|
+
};
|
|
96
|
+
var NAMED = { lt: "<", gt: ">", amp: "&", quot: '"', apos: "'" };
|
|
97
|
+
function decode(text, offset) {
|
|
98
|
+
if (!text.includes("&")) return text;
|
|
99
|
+
return text.replace(/&([^;&\s]*);?/g, (match, entity, index) => {
|
|
100
|
+
if (!match.endsWith(";")) throw new XmlParseError("Unterminated entity", offset + index);
|
|
101
|
+
if (entity in NAMED) return NAMED[entity];
|
|
102
|
+
const numeric = /^#(?:x([0-9a-fA-F]+)|([0-9]+))$/.exec(entity);
|
|
103
|
+
if (numeric) {
|
|
104
|
+
const code = numeric[1] !== void 0 ? parseInt(numeric[1], 16) : parseInt(numeric[2], 10);
|
|
105
|
+
if (code > 1114111 || code >= 55296 && code <= 57343 || code === 0) {
|
|
106
|
+
throw new XmlParseError(`Invalid character reference &${entity};`, offset + index);
|
|
107
|
+
}
|
|
108
|
+
return String.fromCodePoint(code);
|
|
109
|
+
}
|
|
110
|
+
throw new XmlParseError(`Unknown entity &${entity};`, offset + index);
|
|
111
|
+
});
|
|
112
|
+
}
|
|
113
|
+
var NAME = /^[^\s/>=<"'!?]+/;
|
|
114
|
+
var ATTRIBUTE = /^\s+([^\s/>=<"']+)\s*=\s*(?:"([^"<]*)"|'([^'<]*)')/;
|
|
115
|
+
function parseXml(xml) {
|
|
116
|
+
let i = xml.charCodeAt(0) === 65279 ? 1 : 0;
|
|
117
|
+
const n = xml.length;
|
|
118
|
+
const stack = [];
|
|
119
|
+
let root;
|
|
120
|
+
const skipMarkup = () => {
|
|
121
|
+
if (xml.startsWith("<?", i)) {
|
|
122
|
+
const end = xml.indexOf("?>", i + 2);
|
|
123
|
+
if (end < 0) throw new XmlParseError("Unterminated processing instruction", i);
|
|
124
|
+
i = end + 2;
|
|
125
|
+
return true;
|
|
126
|
+
}
|
|
127
|
+
if (xml.startsWith("<!--", i)) {
|
|
128
|
+
const end = xml.indexOf("-->", i + 4);
|
|
129
|
+
if (end < 0) throw new XmlParseError("Unterminated comment", i);
|
|
130
|
+
i = end + 3;
|
|
131
|
+
return true;
|
|
132
|
+
}
|
|
133
|
+
if (xml.startsWith("<!DOCTYPE", i) || xml.startsWith("<!doctype", i)) {
|
|
134
|
+
throw new XmlParseError("A DOCTYPE is not accepted", i);
|
|
135
|
+
}
|
|
136
|
+
return false;
|
|
137
|
+
};
|
|
138
|
+
while (i < n) {
|
|
139
|
+
if (stack.length === 0) {
|
|
140
|
+
while (i < n && /\s/.test(xml[i])) i++;
|
|
141
|
+
if (i >= n) break;
|
|
142
|
+
if (skipMarkup()) continue;
|
|
143
|
+
if (root) throw new XmlParseError("Content after the root element", i);
|
|
144
|
+
if (xml[i] !== "<") throw new XmlParseError("Text outside the root element", i);
|
|
145
|
+
} else if (xml[i] !== "<") {
|
|
146
|
+
const end = xml.indexOf("<", i);
|
|
147
|
+
if (end < 0) throw new XmlParseError(`Unclosed element <${stack[stack.length - 1].element.name}>`, i);
|
|
148
|
+
stack[stack.length - 1].text.push(decode(xml.slice(i, end), i));
|
|
149
|
+
i = end;
|
|
150
|
+
continue;
|
|
151
|
+
} else if (skipMarkup()) {
|
|
152
|
+
continue;
|
|
153
|
+
} else if (xml.startsWith("<![CDATA[", i)) {
|
|
154
|
+
const end = xml.indexOf("]]>", i + 9);
|
|
155
|
+
if (end < 0) throw new XmlParseError("Unterminated CDATA section", i);
|
|
156
|
+
stack[stack.length - 1].text.push(xml.slice(i + 9, end));
|
|
157
|
+
i = end + 3;
|
|
158
|
+
continue;
|
|
159
|
+
} else if (xml.startsWith("</", i)) {
|
|
160
|
+
const close = /^<\/([^\s>]+)\s*>/.exec(xml.slice(i, i + 512));
|
|
161
|
+
const open = stack.pop();
|
|
162
|
+
if (!close || close[1] !== open.element.name) {
|
|
163
|
+
throw new XmlParseError(`Expected </${open.element.name}>`, i);
|
|
164
|
+
}
|
|
165
|
+
finish(open);
|
|
166
|
+
i += close[0].length;
|
|
167
|
+
if (stack.length === 0) root = open.element;
|
|
168
|
+
continue;
|
|
169
|
+
}
|
|
170
|
+
const nameMatch = NAME.exec(xml.slice(i + 1, i + 257));
|
|
171
|
+
if (!nameMatch) throw new XmlParseError("Expected an element name", i + 1);
|
|
172
|
+
const name = nameMatch[0];
|
|
173
|
+
i += 1 + name.length;
|
|
174
|
+
const attributes = /* @__PURE__ */ Object.create(null);
|
|
175
|
+
for (; ; ) {
|
|
176
|
+
const rest = xml.slice(i, i + 65536);
|
|
177
|
+
const attribute = ATTRIBUTE.exec(rest);
|
|
178
|
+
if (attribute) {
|
|
179
|
+
const key = attribute[1];
|
|
180
|
+
if (key in attributes) throw new XmlParseError(`Duplicate attribute ${key}`, i);
|
|
181
|
+
attributes[key] = decode(attribute[2] ?? attribute[3] ?? "", i);
|
|
182
|
+
i += attribute[0].length;
|
|
183
|
+
continue;
|
|
184
|
+
}
|
|
185
|
+
const end = /^\s*(\/?)>/.exec(rest);
|
|
186
|
+
if (!end) throw new XmlParseError(`Malformed tag <${name}>`, i);
|
|
187
|
+
i += end[0].length;
|
|
188
|
+
const element = new XmlElement(name, attributes);
|
|
189
|
+
const parent = stack[stack.length - 1];
|
|
190
|
+
if (parent) parent.element.children.push(element);
|
|
191
|
+
else if (root) throw new XmlParseError("Content after the root element", i);
|
|
192
|
+
if (end[1] === "/") {
|
|
193
|
+
if (!parent) root = element;
|
|
194
|
+
} else {
|
|
195
|
+
stack.push({ element, text: [] });
|
|
196
|
+
}
|
|
197
|
+
break;
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
if (stack.length > 0) {
|
|
201
|
+
throw new XmlParseError(`Unclosed element <${stack[stack.length - 1].element.name}>`, n);
|
|
202
|
+
}
|
|
203
|
+
if (!root) throw new XmlParseError("No root element", n);
|
|
204
|
+
return root;
|
|
205
|
+
}
|
|
206
|
+
function finish(open) {
|
|
207
|
+
const text = open.text.join("");
|
|
208
|
+
open.element.text = open.element.children.length > 0 && text.trim() === "" ? "" : text;
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
// src/reply.ts
|
|
212
|
+
var Reply = class {
|
|
213
|
+
raw;
|
|
214
|
+
/** The parsed document, or null when the XML was not readable. */
|
|
215
|
+
root;
|
|
216
|
+
responses;
|
|
217
|
+
constructor(raw) {
|
|
218
|
+
this.raw = raw;
|
|
219
|
+
let root = null;
|
|
220
|
+
try {
|
|
221
|
+
root = parseXml(raw);
|
|
222
|
+
} catch {
|
|
223
|
+
root = null;
|
|
224
|
+
}
|
|
225
|
+
this.root = root;
|
|
226
|
+
this.responses = root ? readResponses(root) : [];
|
|
227
|
+
}
|
|
228
|
+
/** True when the XML was readable and no response is an error. */
|
|
229
|
+
get ok() {
|
|
230
|
+
return this.root !== null && this.responses.every((r) => r.ok);
|
|
231
|
+
}
|
|
232
|
+
/** Every returned record across all responses, in order. */
|
|
233
|
+
records() {
|
|
234
|
+
return this.responses.flatMap((r) => r.records());
|
|
235
|
+
}
|
|
236
|
+
/** Throw QuickBooksStatusError if any response is an error; else return this reply. */
|
|
237
|
+
raiseForStatus() {
|
|
238
|
+
if (this.root === null) {
|
|
239
|
+
throw new QuickBooksStatusError("The reply is not readable qbXML.", { status: 200 });
|
|
240
|
+
}
|
|
241
|
+
const failed = this.responses.filter((r) => !r.ok);
|
|
242
|
+
if (failed.length > 0) {
|
|
243
|
+
const first = failed[0];
|
|
244
|
+
throw new QuickBooksStatusError(`${first.name}: ${first.statusMessage}`, {
|
|
245
|
+
status: 200,
|
|
246
|
+
code: String(first.statusCode),
|
|
247
|
+
responses: failed
|
|
248
|
+
});
|
|
249
|
+
}
|
|
250
|
+
return this;
|
|
251
|
+
}
|
|
252
|
+
toString() {
|
|
253
|
+
return this.raw;
|
|
254
|
+
}
|
|
255
|
+
};
|
|
256
|
+
function readResponses(root) {
|
|
257
|
+
const out = [];
|
|
258
|
+
for (const msgs of root.children) {
|
|
259
|
+
if (!msgs.name.endsWith("MsgsRs")) continue;
|
|
260
|
+
for (const element of msgs.children) {
|
|
261
|
+
const code = element.get("statusCode");
|
|
262
|
+
if (code === void 0) continue;
|
|
263
|
+
const parsed = /^-?\d+$/.test(code.trim()) ? Number(code) : -1;
|
|
264
|
+
const severity = element.get("statusSeverity") ?? "";
|
|
265
|
+
out.push({
|
|
266
|
+
name: element.name,
|
|
267
|
+
statusCode: parsed,
|
|
268
|
+
statusSeverity: severity,
|
|
269
|
+
statusMessage: element.get("statusMessage") ?? "",
|
|
270
|
+
requestId: element.get("requestID"),
|
|
271
|
+
element,
|
|
272
|
+
ok: severity.toLowerCase() !== "error",
|
|
273
|
+
records: () => element.children.filter((c) => c.name.endsWith("Ret"))
|
|
274
|
+
});
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
return out;
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
// src/version.ts
|
|
281
|
+
var VERSION = "0.1.0";
|
|
282
|
+
|
|
283
|
+
// src/client.ts
|
|
284
|
+
var DEFAULT_URL = "http://localhost:8284";
|
|
285
|
+
var QBXML_VERSION = "13.0";
|
|
286
|
+
var LedgerCrossing = class {
|
|
287
|
+
url;
|
|
288
|
+
timeoutMs;
|
|
289
|
+
#apiKey;
|
|
290
|
+
#fetch;
|
|
291
|
+
constructor(options = {}) {
|
|
292
|
+
const url = (options.url ?? DEFAULT_URL).trim() || DEFAULT_URL;
|
|
293
|
+
if (!/^https?:\/\//i.test(url)) {
|
|
294
|
+
throw new TypeError(`url must start with http:// or https://, got ${JSON.stringify(url)}`);
|
|
295
|
+
}
|
|
296
|
+
this.url = url.replace(/\/+$/, "");
|
|
297
|
+
this.#apiKey = options.apiKey || void 0;
|
|
298
|
+
const timeoutMs = options.timeoutMs ?? 3e5;
|
|
299
|
+
if (!(timeoutMs > 0) || !Number.isFinite(timeoutMs)) throw new RangeError("timeoutMs must be a positive number");
|
|
300
|
+
this.timeoutMs = timeoutMs;
|
|
301
|
+
const f = options.fetch ?? globalThis.fetch;
|
|
302
|
+
if (typeof f !== "function") throw new TypeError("No fetch available: use Node.js 18 or later, or pass options.fetch");
|
|
303
|
+
this.#fetch = f;
|
|
304
|
+
}
|
|
305
|
+
/**
|
|
306
|
+
* Send a qbXML request to QuickBooks and return its answer.
|
|
307
|
+
* A QuickBooks error inside the reply (statusSeverity="Error") is not thrown;
|
|
308
|
+
* call `reply.raiseForStatus()` for that. Throws a LedgerCrossingError subclass
|
|
309
|
+
* for each refusal or failure.
|
|
310
|
+
*/
|
|
311
|
+
async qbxml(xml, options = {}) {
|
|
312
|
+
if (typeof xml !== "string" || xml.trim() === "") throw new TypeError("xml must be a non-empty qbXML string");
|
|
313
|
+
const body = { qbxml: xml };
|
|
314
|
+
if (options.companyFile) body.company_file = options.companyFile;
|
|
315
|
+
if (options.openMode !== void 0) {
|
|
316
|
+
if (![0, 1, 2].includes(options.openMode)) throw new RangeError("openMode must be 0, 1 or 2");
|
|
317
|
+
body.open_mode = options.openMode;
|
|
318
|
+
}
|
|
319
|
+
const answer = await this.#request("POST", "/api/v1/qbxml", body, options.signal);
|
|
320
|
+
if (answer.success !== true || typeof answer.response !== "string") {
|
|
321
|
+
throw new LedgerCrossingError("LedgerCrossing's answer had no qbXML response.", { status: 200, body: answer });
|
|
322
|
+
}
|
|
323
|
+
return new Reply(answer.response);
|
|
324
|
+
}
|
|
325
|
+
/**
|
|
326
|
+
* GET /health: whether LedgerCrossing is up. Needs no key. On the QuickBooks
|
|
327
|
+
* computer the answer includes the version and QuickBooks' state; from
|
|
328
|
+
* elsewhere it is only `{ success: true, status: "ok" }`.
|
|
329
|
+
*/
|
|
330
|
+
async health(options = {}) {
|
|
331
|
+
return await this.#request("GET", "/health", void 0, options.signal);
|
|
332
|
+
}
|
|
333
|
+
/** Up to `maxReturned` (default 100) active customers (CustomerQuery). */
|
|
334
|
+
customers(options = {}) {
|
|
335
|
+
const max = count(options.maxReturned ?? 100);
|
|
336
|
+
return this.qbxml(envelope(`<CustomerQueryRq><MaxReturned>${max}</MaxReturned></CustomerQueryRq>`), {
|
|
337
|
+
companyFile: options.companyFile
|
|
338
|
+
});
|
|
339
|
+
}
|
|
340
|
+
/** Up to `maxReturned` (default 100) invoices, optionally by transaction date (InvoiceQuery). */
|
|
341
|
+
invoices(options = {}) {
|
|
342
|
+
const parts = [`<MaxReturned>${count(options.maxReturned ?? 100)}</MaxReturned>`];
|
|
343
|
+
if (options.fromDate !== void 0 || options.toDate !== void 0) {
|
|
344
|
+
let dates = "";
|
|
345
|
+
if (options.fromDate !== void 0) dates += `<FromTxnDate>${date(options.fromDate)}</FromTxnDate>`;
|
|
346
|
+
if (options.toDate !== void 0) dates += `<ToTxnDate>${date(options.toDate)}</ToTxnDate>`;
|
|
347
|
+
parts.push(`<TxnDateRangeFilter>${dates}</TxnDateRangeFilter>`);
|
|
348
|
+
}
|
|
349
|
+
if (options.includeLineItems) parts.push("<IncludeLineItems>true</IncludeLineItems>");
|
|
350
|
+
return this.qbxml(envelope(`<InvoiceQueryRq>${parts.join("")}</InvoiceQueryRq>`), {
|
|
351
|
+
companyFile: options.companyFile
|
|
352
|
+
});
|
|
353
|
+
}
|
|
354
|
+
/** The standard Profit & Loss report for a period (GeneralSummaryReportQuery). */
|
|
355
|
+
profitAndLoss(options) {
|
|
356
|
+
if (!options) throw new TypeError("profitAndLoss needs { fromDate, toDate }");
|
|
357
|
+
let body = `<GeneralSummaryReportQueryRq><GeneralSummaryReportType>ProfitAndLossStandard</GeneralSummaryReportType><ReportPeriod><FromReportDate>${date(options.fromDate)}</FromReportDate><ToReportDate>${date(options.toDate)}</ToReportDate></ReportPeriod>`;
|
|
358
|
+
if (options.basis !== void 0) {
|
|
359
|
+
if (options.basis !== "Accrual" && options.basis !== "Cash") throw new RangeError('basis must be "Accrual" or "Cash"');
|
|
360
|
+
body += `<ReportBasis>${options.basis}</ReportBasis>`;
|
|
361
|
+
}
|
|
362
|
+
body += "</GeneralSummaryReportQueryRq>";
|
|
363
|
+
return this.qbxml(envelope(body), { companyFile: options.companyFile });
|
|
364
|
+
}
|
|
365
|
+
async #request(method, path, body, signal) {
|
|
366
|
+
const headers = {
|
|
367
|
+
Accept: "application/json",
|
|
368
|
+
"User-Agent": `ledgercrossing-node/${VERSION}`
|
|
369
|
+
};
|
|
370
|
+
if (body !== void 0) headers["Content-Type"] = "application/json; charset=utf-8";
|
|
371
|
+
if (this.#apiKey) headers["X-Api-Key"] = this.#apiKey;
|
|
372
|
+
const controller = new AbortController();
|
|
373
|
+
let timedOut = false;
|
|
374
|
+
const timer = setTimeout(() => {
|
|
375
|
+
timedOut = true;
|
|
376
|
+
controller.abort();
|
|
377
|
+
}, this.timeoutMs);
|
|
378
|
+
const onAbort = () => controller.abort(signal?.reason);
|
|
379
|
+
if (signal) {
|
|
380
|
+
if (signal.aborted) onAbort();
|
|
381
|
+
else signal.addEventListener("abort", onAbort, { once: true });
|
|
382
|
+
}
|
|
383
|
+
let status;
|
|
384
|
+
let answerHeaders;
|
|
385
|
+
let text;
|
|
386
|
+
try {
|
|
387
|
+
const response = await this.#fetch(this.url + path, {
|
|
388
|
+
method,
|
|
389
|
+
headers,
|
|
390
|
+
body: body === void 0 ? void 0 : JSON.stringify(body),
|
|
391
|
+
signal: controller.signal,
|
|
392
|
+
redirect: "manual"
|
|
393
|
+
});
|
|
394
|
+
status = response.status;
|
|
395
|
+
answerHeaders = {};
|
|
396
|
+
response.headers.forEach((value, name) => {
|
|
397
|
+
answerHeaders[name.toLowerCase()] = value;
|
|
398
|
+
});
|
|
399
|
+
text = await response.text();
|
|
400
|
+
} catch (error) {
|
|
401
|
+
if (timedOut) {
|
|
402
|
+
throw new RequestTimeoutError(
|
|
403
|
+
`No answer from LedgerCrossing within ${this.timeoutMs / 1e3} s. The request may still run in QuickBooks; check before sending an add again.`,
|
|
404
|
+
{ cause: error }
|
|
405
|
+
);
|
|
406
|
+
}
|
|
407
|
+
if (signal?.aborted) throw error;
|
|
408
|
+
throw new NetworkError(`Could not reach LedgerCrossing at ${this.url}: ${describe(error)}`, { cause: error });
|
|
409
|
+
} finally {
|
|
410
|
+
clearTimeout(timer);
|
|
411
|
+
signal?.removeEventListener("abort", onAbort);
|
|
412
|
+
}
|
|
413
|
+
const parsed = parseJson(text);
|
|
414
|
+
if (status >= 200 && status < 300) {
|
|
415
|
+
if (parsed === void 0) {
|
|
416
|
+
throw new LedgerCrossingError(
|
|
417
|
+
`The answer from ${this.url}${path} is not LedgerCrossing's JSON. Check the URL.`,
|
|
418
|
+
{ status, headers: answerHeaders }
|
|
419
|
+
);
|
|
420
|
+
}
|
|
421
|
+
return parsed;
|
|
422
|
+
}
|
|
423
|
+
throw errorFor(status, parsed, answerHeaders, text);
|
|
424
|
+
}
|
|
425
|
+
};
|
|
426
|
+
function errorFor(status, body, headers, text = "") {
|
|
427
|
+
const message = body && body.error != null ? String(body.error) : "";
|
|
428
|
+
const code = body && body.code != null ? String(body.code) : void 0;
|
|
429
|
+
const details = { status, code, retryAfter: toInt(headers["retry-after"]), body, headers };
|
|
430
|
+
switch (status) {
|
|
431
|
+
case 400:
|
|
432
|
+
return new BadRequestError(message || "Bad request.", details);
|
|
433
|
+
case 401:
|
|
434
|
+
return new AuthenticationError(message || "Invalid or missing API key.", details);
|
|
435
|
+
case 403:
|
|
436
|
+
if (body === void 0) {
|
|
437
|
+
return new PermissionDeniedError(
|
|
438
|
+
"Refused at the door: from the office network, turn on Local network in LedgerCrossing (Settings > Allowed Connections) and check the address is private or on the allowlist; a request from a web page on another website is always refused.",
|
|
439
|
+
{ ...details, refusedAtDoor: true }
|
|
440
|
+
);
|
|
441
|
+
}
|
|
442
|
+
if (message.toLowerCase().includes("read-only")) return new ReadOnlyError(message, details);
|
|
443
|
+
return new PermissionDeniedError(message || "Forbidden.", details);
|
|
444
|
+
case 404:
|
|
445
|
+
return new NotFoundError(message || "Not found: check the URL.", details);
|
|
446
|
+
case 409:
|
|
447
|
+
return new ConflictError(message || "Conflict with QuickBooks' current state.", details);
|
|
448
|
+
case 429:
|
|
449
|
+
return new RateLimitError(message || "Too many requests.", { ...details, queueDepth: toInt(body?.queue_depth) });
|
|
450
|
+
case 503:
|
|
451
|
+
return new UnavailableError(message || "Unavailable.", details);
|
|
452
|
+
}
|
|
453
|
+
if (status >= 500) return new ServerError(message || `Server error ${status}.`, details);
|
|
454
|
+
if (status >= 300 && status < 400) {
|
|
455
|
+
return new LedgerCrossingError(
|
|
456
|
+
`Redirected (${status}) to ${headers["location"] ?? "another address"}; not followed. Use that URL directly if it is yours.`,
|
|
457
|
+
details
|
|
458
|
+
);
|
|
459
|
+
}
|
|
460
|
+
const snippet = text.trim().slice(0, 200);
|
|
461
|
+
return new LedgerCrossingError(message || `Unexpected HTTP ${status}${snippet ? `: ${snippet}` : "."}`, details);
|
|
462
|
+
}
|
|
463
|
+
function envelope(body) {
|
|
464
|
+
return `<?xml version="1.0" encoding="utf-8"?><?qbxml version="${QBXML_VERSION}"?><QBXML><QBXMLMsgsRq onError="stopOnError">${body}</QBXMLMsgsRq></QBXML>`;
|
|
465
|
+
}
|
|
466
|
+
function count(value) {
|
|
467
|
+
if (!Number.isInteger(value) || value < 1) throw new RangeError("maxReturned must be a positive integer");
|
|
468
|
+
return value;
|
|
469
|
+
}
|
|
470
|
+
function date(value) {
|
|
471
|
+
if (value instanceof Date) {
|
|
472
|
+
if (Number.isNaN(value.getTime())) throw new RangeError("Invalid Date");
|
|
473
|
+
const pad = (n) => String(n).padStart(2, "0");
|
|
474
|
+
return `${value.getFullYear()}-${pad(value.getMonth() + 1)}-${pad(value.getDate())}`;
|
|
475
|
+
}
|
|
476
|
+
if (typeof value === "string" && /^\d{4}-\d{2}-\d{2}$/.test(value)) {
|
|
477
|
+
const [y, m, d] = value.split("-").map(Number);
|
|
478
|
+
const check = new Date(Date.UTC(y, m - 1, d));
|
|
479
|
+
if (check.getUTCFullYear() === y && check.getUTCMonth() === m - 1 && check.getUTCDate() === d) return value;
|
|
480
|
+
}
|
|
481
|
+
throw new RangeError(`dates must be a Date or "YYYY-MM-DD", got ${JSON.stringify(value)}`);
|
|
482
|
+
}
|
|
483
|
+
function parseJson(text) {
|
|
484
|
+
if (text.trim() === "") return void 0;
|
|
485
|
+
try {
|
|
486
|
+
const value = JSON.parse(text);
|
|
487
|
+
return value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
|
|
488
|
+
} catch {
|
|
489
|
+
return void 0;
|
|
490
|
+
}
|
|
491
|
+
}
|
|
492
|
+
function toInt(value) {
|
|
493
|
+
if (value === void 0 || value === null) return void 0;
|
|
494
|
+
const n = Number(String(value).trim());
|
|
495
|
+
return Number.isInteger(n) ? n : void 0;
|
|
496
|
+
}
|
|
497
|
+
function describe(error) {
|
|
498
|
+
const cause = error?.cause;
|
|
499
|
+
if (cause?.code) return cause.code;
|
|
500
|
+
if (cause?.message) return cause.message;
|
|
501
|
+
return error instanceof Error ? error.message : String(error);
|
|
502
|
+
}
|
|
503
|
+
|
|
504
|
+
exports.AuthenticationError = AuthenticationError;
|
|
505
|
+
exports.BadRequestError = BadRequestError;
|
|
506
|
+
exports.ConflictError = ConflictError;
|
|
507
|
+
exports.DEFAULT_URL = DEFAULT_URL;
|
|
508
|
+
exports.LedgerCrossing = LedgerCrossing;
|
|
509
|
+
exports.LedgerCrossingError = LedgerCrossingError;
|
|
510
|
+
exports.NetworkError = NetworkError;
|
|
511
|
+
exports.NotFoundError = NotFoundError;
|
|
512
|
+
exports.PermissionDeniedError = PermissionDeniedError;
|
|
513
|
+
exports.QBXML_VERSION = QBXML_VERSION;
|
|
514
|
+
exports.QuickBooksStatusError = QuickBooksStatusError;
|
|
515
|
+
exports.RateLimitError = RateLimitError;
|
|
516
|
+
exports.ReadOnlyError = ReadOnlyError;
|
|
517
|
+
exports.Reply = Reply;
|
|
518
|
+
exports.RequestTimeoutError = RequestTimeoutError;
|
|
519
|
+
exports.ServerError = ServerError;
|
|
520
|
+
exports.UnavailableError = UnavailableError;
|
|
521
|
+
exports.VERSION = VERSION;
|
|
522
|
+
exports.XmlElement = XmlElement;
|
|
523
|
+
exports.XmlParseError = XmlParseError;
|
|
524
|
+
exports.parseXml = parseXml;
|