@booki-aui/core 0.3.2 → 0.4.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 (118) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/dist/activity.js +6 -2
  3. package/dist/aging.js +6 -2
  4. package/dist/approval.js +6 -2
  5. package/dist/attachments.js +6 -2
  6. package/dist/audit.js +6 -2
  7. package/dist/{chunk-U2M6WCUI.js → chunk-2DAEO7ZI.js} +2 -2
  8. package/dist/{chunk-62QTK3RO.js → chunk-2JWD25RD.js} +3 -3
  9. package/dist/chunk-54VPA5IO.js +15 -0
  10. package/dist/chunk-54VPA5IO.js.map +1 -0
  11. package/dist/{chunk-5YV57WVB.js → chunk-5LFO4F23.js} +2 -2
  12. package/dist/{chunk-BIFYH2Y6.js → chunk-5XMQENFN.js} +2 -2
  13. package/dist/{chunk-6SFOABFT.js → chunk-65YBZVDN.js} +2 -2
  14. package/dist/chunk-6QCJ2ZBB.js +55 -0
  15. package/dist/chunk-6QCJ2ZBB.js.map +1 -0
  16. package/dist/{chunk-CBOKL727.js → chunk-DONOCNQS.js} +4 -4
  17. package/dist/chunk-DONOCNQS.js.map +1 -0
  18. package/dist/chunk-EIM3HADW.js +31 -0
  19. package/dist/chunk-EIM3HADW.js.map +1 -0
  20. package/dist/{chunk-OKVUS75Z.js → chunk-F2DHORUA.js} +62 -25
  21. package/dist/chunk-F2DHORUA.js.map +1 -0
  22. package/dist/chunk-GCSGHKXS.js +20 -0
  23. package/dist/chunk-GCSGHKXS.js.map +1 -0
  24. package/dist/{chunk-XDAXPC27.js → chunk-I7QGX3UY.js} +2 -2
  25. package/dist/{chunk-VCBYT2E7.js → chunk-IRG7U7OI.js} +2 -2
  26. package/dist/{chunk-HCMLRRN4.js → chunk-J6PB5LMQ.js} +3 -3
  27. package/dist/{chunk-ZVBXNHFR.js → chunk-K3LOJGUG.js} +4 -4
  28. package/dist/{chunk-V5DTXL3H.js → chunk-MA536GKU.js} +2 -2
  29. package/dist/{chunk-D7CU3G3K.js → chunk-MVRBXSBJ.js} +2 -2
  30. package/dist/{chunk-KDCB6RKO.js → chunk-NP2S3BCP.js} +3 -3
  31. package/dist/{chunk-BUMQBGO3.js → chunk-NZ3APVAI.js} +43 -24
  32. package/dist/chunk-NZ3APVAI.js.map +1 -0
  33. package/dist/{chunk-MN3MBEQ7.js → chunk-OCOEKN4O.js} +2 -2
  34. package/dist/{chunk-KAFDCP6S.js → chunk-PRRF4UV4.js} +2 -2
  35. package/dist/{chunk-6IVK3UQA.js → chunk-T4T3U4OS.js} +2 -2
  36. package/dist/{chunk-B45JAHB5.js → chunk-TA5KB4W4.js} +3 -3
  37. package/dist/{chunk-SRVXIZKH.js → chunk-TVYI5YJI.js} +3 -3
  38. package/dist/{chunk-VOA56E4X.js → chunk-U6CQNW5O.js} +2 -2
  39. package/dist/{chunk-EOY5C5DL.js → chunk-V2FS3TLG.js} +2 -2
  40. package/dist/{chunk-KMXOHG6A.js → chunk-VCGG3SFN.js} +2 -2
  41. package/dist/{chunk-4FRT7XRX.js → chunk-VLV6CMVP.js} +2 -2
  42. package/dist/{chunk-MEZZFV6D.js → chunk-W72GPG4R.js} +12 -3
  43. package/dist/chunk-W72GPG4R.js.map +1 -0
  44. package/dist/{chunk-TTD6VZNY.js → chunk-YJY536ZO.js} +2 -2
  45. package/dist/{chunk-XKUL5BDJ.js → chunk-YMNDDLSY.js} +2 -2
  46. package/dist/{chunk-EGUAYFGH.js → chunk-YVF4UCRM.js} +25 -44
  47. package/dist/chunk-YVF4UCRM.js.map +1 -0
  48. package/dist/{chunk-JMOLS4U5.js → chunk-YZ3UV5S3.js} +2 -2
  49. package/dist/{chunk-KXYJZ6HG.js → chunk-ZACNAMJC.js} +2 -2
  50. package/dist/client-request.js +6 -2
  51. package/dist/close.js +6 -2
  52. package/dist/document-signoff.d.ts +1 -1
  53. package/dist/document-signoff.js +6 -2
  54. package/dist/expense.js +6 -2
  55. package/dist/findings.js +6 -2
  56. package/dist/fixed-assets.js +7 -3
  57. package/dist/funnel.js +6 -2
  58. package/dist/fx.js +7 -3
  59. package/dist/index.d.ts +1 -1
  60. package/dist/index.js +57 -53
  61. package/dist/invoice.js +6 -2
  62. package/dist/ledger.js +7 -3
  63. package/dist/locale/index.js +3 -2
  64. package/dist/messages.d.ts +2 -2
  65. package/dist/messages.js +6 -2
  66. package/dist/money.d.ts +3 -2
  67. package/dist/money.js +3 -2
  68. package/dist/msg-DvA8vxX9.d.ts +694 -0
  69. package/dist/msg-amount.d.ts +22 -0
  70. package/dist/msg-amount.js +14 -0
  71. package/dist/msg-amount.js.map +1 -0
  72. package/dist/msg.d.ts +1 -679
  73. package/dist/msg.js +8 -3
  74. package/dist/payment-batch.js +6 -2
  75. package/dist/period-lock.js +7 -3
  76. package/dist/period.js +6 -2
  77. package/dist/permissions.js +6 -2
  78. package/dist/pipeline.js +6 -2
  79. package/dist/reconciliation.js +6 -2
  80. package/dist/recurring.js +6 -2
  81. package/dist/server.d.ts +1 -1
  82. package/dist/server.js +20 -16
  83. package/dist/server.js.map +1 -1
  84. package/dist/supplier-invoice.js +6 -2
  85. package/dist/table.js +6 -2
  86. package/dist/vat-return.js +7 -3
  87. package/dist/voucher.js +10 -6
  88. package/package.json +6 -2
  89. package/dist/chunk-BUMQBGO3.js.map +0 -1
  90. package/dist/chunk-CBOKL727.js.map +0 -1
  91. package/dist/chunk-EGUAYFGH.js.map +0 -1
  92. package/dist/chunk-MEZZFV6D.js.map +0 -1
  93. package/dist/chunk-OKVUS75Z.js.map +0 -1
  94. /package/dist/{chunk-U2M6WCUI.js.map → chunk-2DAEO7ZI.js.map} +0 -0
  95. /package/dist/{chunk-62QTK3RO.js.map → chunk-2JWD25RD.js.map} +0 -0
  96. /package/dist/{chunk-5YV57WVB.js.map → chunk-5LFO4F23.js.map} +0 -0
  97. /package/dist/{chunk-BIFYH2Y6.js.map → chunk-5XMQENFN.js.map} +0 -0
  98. /package/dist/{chunk-6SFOABFT.js.map → chunk-65YBZVDN.js.map} +0 -0
  99. /package/dist/{chunk-XDAXPC27.js.map → chunk-I7QGX3UY.js.map} +0 -0
  100. /package/dist/{chunk-VCBYT2E7.js.map → chunk-IRG7U7OI.js.map} +0 -0
  101. /package/dist/{chunk-HCMLRRN4.js.map → chunk-J6PB5LMQ.js.map} +0 -0
  102. /package/dist/{chunk-ZVBXNHFR.js.map → chunk-K3LOJGUG.js.map} +0 -0
  103. /package/dist/{chunk-V5DTXL3H.js.map → chunk-MA536GKU.js.map} +0 -0
  104. /package/dist/{chunk-D7CU3G3K.js.map → chunk-MVRBXSBJ.js.map} +0 -0
  105. /package/dist/{chunk-KDCB6RKO.js.map → chunk-NP2S3BCP.js.map} +0 -0
  106. /package/dist/{chunk-MN3MBEQ7.js.map → chunk-OCOEKN4O.js.map} +0 -0
  107. /package/dist/{chunk-KAFDCP6S.js.map → chunk-PRRF4UV4.js.map} +0 -0
  108. /package/dist/{chunk-6IVK3UQA.js.map → chunk-T4T3U4OS.js.map} +0 -0
  109. /package/dist/{chunk-B45JAHB5.js.map → chunk-TA5KB4W4.js.map} +0 -0
  110. /package/dist/{chunk-SRVXIZKH.js.map → chunk-TVYI5YJI.js.map} +0 -0
  111. /package/dist/{chunk-VOA56E4X.js.map → chunk-U6CQNW5O.js.map} +0 -0
  112. /package/dist/{chunk-EOY5C5DL.js.map → chunk-V2FS3TLG.js.map} +0 -0
  113. /package/dist/{chunk-KMXOHG6A.js.map → chunk-VCGG3SFN.js.map} +0 -0
  114. /package/dist/{chunk-4FRT7XRX.js.map → chunk-VLV6CMVP.js.map} +0 -0
  115. /package/dist/{chunk-TTD6VZNY.js.map → chunk-YJY536ZO.js.map} +0 -0
  116. /package/dist/{chunk-XKUL5BDJ.js.map → chunk-YMNDDLSY.js.map} +0 -0
  117. /package/dist/{chunk-JMOLS4U5.js.map → chunk-YZ3UV5S3.js.map} +0 -0
  118. /package/dist/{chunk-KXYJZ6HG.js.map → chunk-ZACNAMJC.js.map} +0 -0
package/dist/msg.js CHANGED
@@ -1,10 +1,15 @@
1
1
  import {
2
2
  BookiError,
3
- PLACEHOLDER,
4
3
  isBookiError,
5
- msg,
4
+ msg
5
+ } from "./chunk-YVF4UCRM.js";
6
+ import "./chunk-54VPA5IO.js";
7
+ import "./chunk-GCSGHKXS.js";
8
+ import "./chunk-EIM3HADW.js";
9
+ import {
10
+ PLACEHOLDER,
6
11
  render
7
- } from "./chunk-EGUAYFGH.js";
12
+ } from "./chunk-6QCJ2ZBB.js";
8
13
  export {
9
14
  BookiError,
10
15
  PLACEHOLDER,
@@ -8,8 +8,12 @@ import {
8
8
  duplicatePayments,
9
9
  releaseBatch,
10
10
  setBatchItems
11
- } from "./chunk-D7CU3G3K.js";
12
- import "./chunk-EGUAYFGH.js";
11
+ } from "./chunk-MVRBXSBJ.js";
12
+ import "./chunk-YVF4UCRM.js";
13
+ import "./chunk-54VPA5IO.js";
14
+ import "./chunk-GCSGHKXS.js";
15
+ import "./chunk-EIM3HADW.js";
16
+ import "./chunk-6QCJ2ZBB.js";
13
17
  export {
14
18
  approveBatch,
15
19
  assertReleasable,
@@ -2,10 +2,14 @@ import {
2
2
  assertPostingAllowed,
3
3
  periodStatusOn,
4
4
  setPeriodStatus
5
- } from "./chunk-HCMLRRN4.js";
5
+ } from "./chunk-J6PB5LMQ.js";
6
6
  import "./chunk-ICBA5A2V.js";
7
- import "./chunk-JMOLS4U5.js";
8
- import "./chunk-EGUAYFGH.js";
7
+ import "./chunk-YZ3UV5S3.js";
8
+ import "./chunk-YVF4UCRM.js";
9
+ import "./chunk-54VPA5IO.js";
10
+ import "./chunk-GCSGHKXS.js";
11
+ import "./chunk-EIM3HADW.js";
12
+ import "./chunk-6QCJ2ZBB.js";
9
13
  export {
10
14
  assertPostingAllowed,
11
15
  periodStatusOn,
package/dist/period.js CHANGED
@@ -7,8 +7,12 @@ import {
7
7
  periodItemsForYear,
8
8
  vatTermPeriod,
9
9
  yearPeriod
10
- } from "./chunk-JMOLS4U5.js";
11
- import "./chunk-EGUAYFGH.js";
10
+ } from "./chunk-YZ3UV5S3.js";
11
+ import "./chunk-YVF4UCRM.js";
12
+ import "./chunk-54VPA5IO.js";
13
+ import "./chunk-GCSGHKXS.js";
14
+ import "./chunk-EIM3HADW.js";
15
+ import "./chunk-6QCJ2ZBB.js";
12
16
  export {
13
17
  formatPeriod,
14
18
  isValidPeriodCode,
@@ -6,8 +6,12 @@ import {
6
6
  assertCan,
7
7
  can,
8
8
  rolesIn
9
- } from "./chunk-4FRT7XRX.js";
10
- import "./chunk-EGUAYFGH.js";
9
+ } from "./chunk-VLV6CMVP.js";
10
+ import "./chunk-YVF4UCRM.js";
11
+ import "./chunk-54VPA5IO.js";
12
+ import "./chunk-GCSGHKXS.js";
13
+ import "./chunk-EIM3HADW.js";
14
+ import "./chunk-6QCJ2ZBB.js";
11
15
  export {
12
16
  DutyRefusal,
13
17
  PERMISSIONS,
package/dist/pipeline.js CHANGED
@@ -18,8 +18,12 @@ import {
18
18
  setExpectedClose,
19
19
  timeInStage,
20
20
  valueCounts
21
- } from "./chunk-VOA56E4X.js";
22
- import "./chunk-EGUAYFGH.js";
21
+ } from "./chunk-U6CQNW5O.js";
22
+ import "./chunk-YVF4UCRM.js";
23
+ import "./chunk-54VPA5IO.js";
24
+ import "./chunk-GCSGHKXS.js";
25
+ import "./chunk-EIM3HADW.js";
26
+ import "./chunk-6QCJ2ZBB.js";
23
27
  export {
24
28
  DEAL_VALUE_FIELDS,
25
29
  DEAL_VALUE_STATUSES,
@@ -4,8 +4,12 @@ import {
4
4
  summarize,
5
5
  unmatched,
6
6
  validateMatch
7
- } from "./chunk-6IVK3UQA.js";
8
- import "./chunk-EGUAYFGH.js";
7
+ } from "./chunk-T4T3U4OS.js";
8
+ import "./chunk-YVF4UCRM.js";
9
+ import "./chunk-54VPA5IO.js";
10
+ import "./chunk-GCSGHKXS.js";
11
+ import "./chunk-EIM3HADW.js";
12
+ import "./chunk-6QCJ2ZBB.js";
9
13
  export {
10
14
  assertReconciled,
11
15
  suggestMatches,
package/dist/recurring.js CHANGED
@@ -11,8 +11,12 @@ import {
11
11
  recurringBridge,
12
12
  recurringCurrencies,
13
13
  recurringIssues
14
- } from "./chunk-VCBYT2E7.js";
15
- import "./chunk-EGUAYFGH.js";
14
+ } from "./chunk-IRG7U7OI.js";
15
+ import "./chunk-YVF4UCRM.js";
16
+ import "./chunk-54VPA5IO.js";
17
+ import "./chunk-GCSGHKXS.js";
18
+ import "./chunk-EIM3HADW.js";
19
+ import "./chunk-6QCJ2ZBB.js";
16
20
  export {
17
21
  RECURRING_INTERVALS,
18
22
  RECURRING_MOVEMENTS,
package/dist/server.d.ts CHANGED
@@ -3,7 +3,7 @@ import { CloseTask, CloseSummary } from './close.js';
3
3
  import { SignableDocument, SignoffLevel, SignoffRules } from './document-signoff.js';
4
4
  import { Finding } from './findings.js';
5
5
  import { Invoice } from './invoice.js';
6
- import { MessageLanguage } from './msg.js';
6
+ import { a as MessageLanguage } from './msg-DvA8vxX9.js';
7
7
  import { PaymentBatch } from './payment-batch.js';
8
8
  import { Deal, PipelineStage, DealOutcome } from './pipeline.js';
9
9
  import { Actor, Role, Permission, Deed, DutyRule } from './permissions.js';
package/dist/server.js CHANGED
@@ -1,54 +1,58 @@
1
1
  import {
2
2
  assertVatReturnReady
3
- } from "./chunk-KDCB6RKO.js";
3
+ } from "./chunk-NP2S3BCP.js";
4
4
  import {
5
5
  assertPostable
6
- } from "./chunk-ZVBXNHFR.js";
6
+ } from "./chunk-K3LOJGUG.js";
7
7
  import {
8
8
  releaseBatch
9
- } from "./chunk-D7CU3G3K.js";
10
- import "./chunk-HCMLRRN4.js";
9
+ } from "./chunk-MVRBXSBJ.js";
10
+ import "./chunk-J6PB5LMQ.js";
11
11
  import {
12
12
  DutyRefusal,
13
13
  STANDARD_DUTY_RULES,
14
14
  STANDARD_ROLES,
15
15
  assertCan,
16
16
  can
17
- } from "./chunk-4FRT7XRX.js";
17
+ } from "./chunk-VLV6CMVP.js";
18
18
  import {
19
19
  closeDeal
20
- } from "./chunk-VOA56E4X.js";
20
+ } from "./chunk-U6CQNW5O.js";
21
21
  import {
22
22
  finalizeInvoice
23
- } from "./chunk-OKVUS75Z.js";
23
+ } from "./chunk-F2DHORUA.js";
24
24
  import {
25
25
  isIsoDate
26
26
  } from "./chunk-ICBA5A2V.js";
27
27
  import {
28
28
  localize,
29
29
  msgIn
30
- } from "./chunk-MEZZFV6D.js";
30
+ } from "./chunk-W72GPG4R.js";
31
31
  import {
32
32
  signDocument
33
- } from "./chunk-EOY5C5DL.js";
33
+ } from "./chunk-V2FS3TLG.js";
34
34
  import {
35
35
  confirmFinding
36
- } from "./chunk-KAFDCP6S.js";
37
- import "./chunk-JMOLS4U5.js";
38
- import "./chunk-62QTK3RO.js";
39
- import "./chunk-BUMQBGO3.js";
36
+ } from "./chunk-PRRF4UV4.js";
37
+ import "./chunk-YZ3UV5S3.js";
38
+ import "./chunk-2JWD25RD.js";
39
+ import "./chunk-NZ3APVAI.js";
40
40
  import {
41
41
  assertApproved,
42
42
  decide
43
- } from "./chunk-MN3MBEQ7.js";
43
+ } from "./chunk-OCOEKN4O.js";
44
44
  import {
45
45
  assertReadyToClose
46
- } from "./chunk-5YV57WVB.js";
46
+ } from "./chunk-5LFO4F23.js";
47
47
  import {
48
48
  BookiError,
49
49
  isBookiError,
50
50
  msg
51
- } from "./chunk-EGUAYFGH.js";
51
+ } from "./chunk-YVF4UCRM.js";
52
+ import "./chunk-54VPA5IO.js";
53
+ import "./chunk-GCSGHKXS.js";
54
+ import "./chunk-EIM3HADW.js";
55
+ import "./chunk-6QCJ2ZBB.js";
52
56
  import "./chunk-ZJXNLPER.js";
53
57
 
54
58
  // src/agent-token.ts
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/agent-token.ts","../src/server.ts"],"sourcesContent":["/**\n * A short-lived credential of the agent's own, so the server can tell the\n * agent from the person it works for. Your sign-in issues it for a signed-in\n * person; the page sends it with the agent's writes; the server verifies it\n * and adds the agent's roles. Signed with HMAC-SHA-256 through WebCrypto, so\n * it runs in Node, edge runtimes, Deno and Bun.\n *\n * It is not a session: keep the person's own sign-in for their writes.\n */\n\nexport type AgentGrant = {\n /** The agent's id, as `actorLabel` writes it after `agent:`. */\n agentId: string;\n /** The person whose session the agent works in. */\n onBehalfOf: string;\n /** The client it came through (your page, an MCP client). */\n clientId?: string;\n /**\n * What the token is for: an engagement, a company, one API. `verifyAgentToken`\n * with `{ audience }` refuses a token issued for anything else.\n */\n audience?: string;\n /** Seconds it is valid. Default 900 (15 minutes), at most 86 400. */\n ttlSeconds?: number;\n};\n\n/** What a valid token says: add `roles` from your own records to make a `ServerActor`. */\nexport type AgentClaims = {\n id: string;\n kind: \"agent\";\n onBehalfOf: string;\n clientId?: string;\n audience?: string;\n /** This token's own id, for the audit trail (`actorRecord`). */\n grantId: string;\n /** When it stops being valid, in milliseconds since 1970. */\n expiresAt: number;\n};\n\nimport { BookiError } from \"./msg.js\";\n\nconst PREFIX = \"bk1\";\nconst encoder = new TextEncoder();\n\nconst base64url = (bytes: Uint8Array) =>\n btoa(String.fromCharCode(...bytes))\n .replace(/\\+/g, \"-\")\n .replace(/\\//g, \"_\")\n .replace(/=+$/, \"\");\nconst fromBase64url = (text: string) => {\n const plain = atob(text.replace(/-/g, \"+\").replace(/_/g, \"/\"));\n return Uint8Array.from(plain, (char) => char.charCodeAt(0));\n};\n\nasync function keyFor(secret: string): Promise<CryptoKey> {\n if (typeof secret !== \"string\" || secret.length < 32) {\n throw new BookiError(\"agent-token.secret-short\");\n }\n return crypto.subtle.importKey(\"raw\", encoder.encode(secret), { name: \"HMAC\", hash: \"SHA-256\" }, false, [\n \"sign\",\n \"verify\",\n ]);\n}\n\n/** Issues a token for an agent working for `onBehalfOf`. Call it only for a person your sign-in established. */\nexport async function issueAgentToken(grant: AgentGrant, secret: string, now = Date.now()): Promise<string> {\n const ttl = grant.ttlSeconds ?? 900;\n if (!Number.isSafeInteger(ttl) || ttl < 1 || ttl > 86_400) {\n throw new BookiError(\"agent-token.ttl\", { value: String(ttl) });\n }\n if (!grant.agentId || !grant.onBehalfOf) throw new BookiError(\"agent-token.grant\");\n const claims: AgentClaims = {\n id: grant.agentId,\n kind: \"agent\",\n onBehalfOf: grant.onBehalfOf,\n ...(grant.clientId ? { clientId: grant.clientId } : {}),\n ...(grant.audience ? { audience: grant.audience } : {}),\n grantId: base64url(crypto.getRandomValues(new Uint8Array(12))),\n expiresAt: now + ttl * 1000,\n };\n const payload = base64url(encoder.encode(JSON.stringify(claims)));\n const signature = await crypto.subtle.sign(\"HMAC\", await keyFor(secret), encoder.encode(`${PREFIX}.${payload}`));\n return `${PREFIX}.${payload}.${base64url(new Uint8Array(signature))}`;\n}\n\n/**\n * The claims of a valid, unexpired token signed with `secret`, or null. Null\n * for every failure alike: a caller learns nothing about why.\n */\nexport async function verifyAgentToken(\n token: unknown,\n secret: string,\n now: number | { now?: number; audience?: string } = Date.now(),\n): Promise<AgentClaims | null> {\n const at = typeof now === \"number\" ? now : (now.now ?? Date.now());\n const audience = typeof now === \"number\" ? undefined : now.audience;\n const key = await keyFor(secret);\n if (typeof token !== \"string\" || token.length > 4096) return null;\n const [prefix, payload, signature, ...rest] = token.split(\".\");\n if (prefix !== PREFIX || !payload || !signature || rest.length) return null;\n try {\n const ok = await crypto.subtle.verify(\n \"HMAC\",\n key,\n fromBase64url(signature),\n encoder.encode(`${PREFIX}.${payload}`),\n );\n if (!ok) return null;\n const claims = JSON.parse(new TextDecoder().decode(fromBase64url(payload))) as AgentClaims;\n if (claims.kind !== \"agent\" || typeof claims.id !== \"string\" || typeof claims.onBehalfOf !== \"string\") return null;\n if (!Number.isFinite(claims.expiresAt) || claims.expiresAt <= at) return null;\n // Given an audience, only a token issued for exactly that one passes.\n if (audience !== undefined && claims.audience !== audience) return null;\n return claims;\n } catch {\n return null;\n }\n}\n","/**\n * The same rules the screen enforces, for your API.\n *\n * The controls refuse what a role may not do and what the books do not allow,\n * but a browser is not a security boundary: anything can call your API. Run\n * every write through one of these guards on the server, with the actor your\n * own sign-in established (never one the request says it is). Each guard\n * answers with a verdict you can send straight back: the HTTP status, a stable\n * code and the same sentence the control showed, in English or Norwegian.\n *\n * Order of checks, for every action:\n * 1. Signed in? 401\n * 2. A person's decision, and the actor an agent? 403\n * 3. Role allows it, in this entity? 403\n * And, for an agent acting for someone, theirs? 403 (with `personOf`)\n * 4. Separation of duties against what they did? 403\n * 5. A reason given, where one is required? 422\n * 6. The books allow it (balance, period, approvals, readiness)? 409 or 422\n *\n * Where the books are a matter of professional judgment (an audit file, say),\n * use `advise` instead of `guard`: steps 1 to 5 still refuse, and step 6 comes\n * back as warnings for the person to weigh.\n *\n * Framework-free: plain data in, plain data out. Works in Node, edge runtimes,\n * Deno and Bun.\n */\nexport { type AgentClaims, type AgentGrant, issueAgentToken, verifyAgentToken } from \"./agent-token.js\";\nimport { assertApproved, decide, type ApprovalDecision, type ApprovalLevel, type ApprovalRequest } from \"./approval.js\";\nimport { assertReadyToClose, type CloseSummary, type CloseTask } from \"./close.js\";\nimport { signDocument, type SignableDocument, type SignoffLevel, type SignoffRules } from \"./document-signoff.js\";\nimport { confirmFinding, type Finding } from \"./findings.js\";\nimport { finalizeInvoice, type Invoice } from \"./invoice.js\";\nimport { isIsoDate } from \"./iso-date.js\";\nimport { localize, msgIn, type MessageLanguage } from \"./messages.js\";\nimport { BookiError, isBookiError, msg } from \"./msg.js\";\nimport { releaseBatch, type PaymentBatch } from \"./payment-batch.js\";\nimport { closeDeal, type Deal, type DealOutcome, type PipelineStage } from \"./pipeline.js\";\nimport {\n STANDARD_DUTY_RULES,\n STANDARD_ROLES,\n DutyRefusal,\n assertCan,\n can,\n type Actor,\n type Deed,\n type DutyRule,\n type Permission,\n type Role,\n} from \"./permissions.js\";\nimport { assertVatReturnReady, type VatReturnComputation } from \"./vat-return.js\";\nimport { assertPostable, type VoucherBalance, type VoucherLine, type VoucherRules } from \"./voucher.js\";\n\n/**\n * Who is calling, as your sign-in established it. An agent gets its own\n * credential and comes here as `kind: \"agent\"`; `onBehalfOf` is the person\n * whose session started it. It is recorded, the duty rules count it, and with\n * `personOf` in the context the person's own roles limit what the agent may do.\n */\nexport type ServerActor = Actor & {\n kind: \"person\" | \"agent\";\n onBehalfOf?: string;\n /** For an agent: the client it came through (an MCP client, your workflow), for the audit trail. */\n clientId?: string;\n /** For an agent: the grant or token the person gave it, for the audit trail. */\n grantId?: string;\n};\n\nexport type GuardContext = {\n actor?: ServerActor;\n /** Your roles. Default: `STANDARD_ROLES`. */\n roles?: Role[];\n /** The company the request is for. An actor limited to other entities is refused. */\n entity?: string;\n /** The engagement, case or project: the actor's roles there (`scopes`) count too. */\n scope?: string;\n /** Why, in the actor's words. Kept with the decision. */\n reason?: string;\n /** Refuse unless `reason` has at least this many characters (withdrawing a sign-off, say). */\n minReason?: number;\n /** Your own permissions that only a person may use, added to `PERSON_ONLY`. */\n personOnly?: Permission[];\n /**\n * The person an agent acts for (`actor.onBehalfOf`), with their roles as they\n * are now. Give it, and an agent may only do what that person may do: an id\n * it does not know is refused, and so is a permission or entity the person\n * lacks. Without it `onBehalfOf` is recorded and counts for the duty rules,\n * but the person's roles are not checked.\n */\n personOf?: (id: string) => Actor | undefined;\n /**\n * Permissions an agent has by the company's own rule rather than the person's\n * (approving invoices under a limit, say): `personOf` is not asked for these.\n */\n agentOwn?: Permission[];\n /** What has already been done to this item, and by whom, for the duty rules. */\n deeds?: Deed[];\n /** Default: `STANDARD_DUTY_RULES`. Pass `[]` to switch them off. */\n dutyRules?: DutyRule[];\n /** Language of the refusal sentence. Default: English. */\n locale?: MessageLanguage;\n};\n\nexport type Refusal = {\n ok: false;\n status: 401 | 403 | 409 | 422;\n /** Stable, for your client and your logs. */\n code: string;\n /** One sentence a person or an agent can act on. */\n message: string;\n /** Every problem, where the rule found several. */\n issues?: string[];\n};\n\nexport type Verdict<T> = { ok: true; value: T; actor: string } | Refusal;\n\n/** What `advise` answers: allowed, with what the books say against it, if anything. */\nexport type Advice<T> = { ok: true; value: T | undefined; actor: string; warnings: string[] } | Refusal;\n\n/**\n * Decisions that stay with people, whatever an agent's role says: approving,\n * signing off, finalizing, releasing, closing and submitting.\n */\nexport const PERSON_ONLY: readonly Permission[] = [\n \"audit.review\",\n \"audit.conclude\",\n \"audit.eqcr\",\n \"audit.freeze\",\n \"approval.decide\",\n \"supplier-invoice.approve\",\n \"expense.approve\",\n \"payment.approve\",\n \"payment.release\",\n \"reconciliation.approve\",\n \"period.close\",\n \"period.adjust-closed\",\n \"close.sign-off\",\n \"invoice.finalize\",\n \"vat.submit\",\n \"asset.dispose\",\n \"audit.sign-off\",\n \"finding.confirm\",\n \"finding.withdraw\",\n \"request.send\",\n \"request.decide\",\n \"deal.close\",\n];\n\n/** How an actor appears in the audit trail: `agent:bookkeeper` or the person's id. */\nexport const actorLabel = (actor: ServerActor) => (actor.kind === \"agent\" ? `agent:${actor.id}` : actor.id);\n\n/**\n * The deed to record for what an actor just did, for later duty checks: it\n * names the agent's label and whose session it ran in, so the person cannot\n * review what their own agent prepared.\n */\nexport function actorDeed(actor: ServerActor, permission: Permission): Deed {\n return { actorId: actorLabel(actor), permission, ...(actor.onBehalfOf ? { onBehalfOf: actor.onBehalfOf } : {}) };\n}\n\n/** Everything the audit trail should keep about who acted: the label, the kind, and for an agent whose session, client and grant. */\nexport function actorRecord(actor: ServerActor): {\n actor: string;\n kind: ServerActor[\"kind\"];\n onBehalfOf?: string;\n clientId?: string;\n grantId?: string;\n} {\n return {\n actor: actorLabel(actor),\n kind: actor.kind,\n ...(actor.onBehalfOf ? { onBehalfOf: actor.onBehalfOf } : {}),\n ...(actor.clientId ? { clientId: actor.clientId } : {}),\n ...(actor.grantId ? { grantId: actor.grantId } : {}),\n };\n}\n\nfunction statusOf(code: string): Refusal[\"status\"] {\n if (code === \"permissions.signed-out\") return 401;\n if (code === \"server.reason-required\") return 422;\n if (code.startsWith(\"permissions.\") || code.startsWith(\"server.\")) return 403;\n if (\n /^(period\\.|approval\\.(waiting|rejected)|batch\\.already|invoice\\.(not-editable|number-used)|close\\.)/.test(code)\n ) {\n return 409;\n }\n return 422;\n}\n\nfunction refuse(error: unknown, locale: MessageLanguage | undefined): Refusal {\n if (isBookiError(error)) {\n const issues = Array.isArray(error.params.issues) ? (error.params.issues as unknown[]).map(String) : undefined;\n return {\n ok: false,\n status: statusOf(error.code),\n code: error.code,\n message: locale && locale !== \"en\" ? msgIn(locale, error.code, error.params) : error.message,\n ...(issues\n ? { issues: locale && locale !== \"en\" ? issues.map((issue) => localize(issue, locale)) : issues }\n : {}),\n };\n }\n if (error instanceof DutyRefusal) {\n return {\n ok: false,\n status: 403,\n code: \"permissions.duty\",\n message: locale && locale !== \"en\" ? localize(error.message, locale) : error.message,\n };\n }\n // Your own rule's refusal: its sentence goes back as it is.\n if (error instanceof RuleRefusal) return { ok: false, status: 422, code: \"server.rule\", message: error.message };\n // Anything else (a database error, a bug) is not a refusal, and its message\n // can hold hosts and user names: rethrow it for your error handling.\n throw error;\n}\n\n/**\n * Throw it from a rule of your own to refuse with a sentence of yours: the\n * guard answers 422 `server.rule` with it. Any other error a rule throws is\n * rethrown, so a database error never reaches the caller as a message.\n */\nexport class RuleRefusal extends Error {\n override name = \"RuleRefusal\";\n}\n\n/**\n * The general guard: may this actor do `permission`, and does `rule` pass?\n * The specific guards below are this with the right rule filled in; use it\n * directly for your own actions.\n */\nexport function guard<T>(context: GuardContext, permission: Permission, rule: () => T): Verdict<T> {\n try {\n admit(context, permission);\n return { ok: true, value: rule(), actor: actorLabel(context.actor!) };\n } catch (error) {\n return refuse(error, context.locale);\n }\n}\n\n/**\n * Like `guard`, for actions where the books are a matter of judgment: who may\n * act is still enforced (signed in, a person's decision, role, duties, reason),\n * but what `rule` finds against it comes back as `warnings` instead of a\n * refusal, and `value` is undefined when the rule threw. The person decides.\n */\nexport function advise<T>(context: GuardContext, permission: Permission, rule: () => T): Advice<T> {\n try {\n admit(context, permission);\n } catch (error) {\n return refuse(error, context.locale);\n }\n const actor = actorLabel(context.actor!);\n try {\n return { ok: true, value: rule(), actor, warnings: [] };\n } catch (error) {\n const found = refuse(error, context.locale);\n // Only the books' own objections become warnings; anything about who may act still refuses.\n if (found.status === 409 || found.status === 422) {\n return { ok: true, value: undefined, actor, warnings: found.issues?.length ? found.issues : [found.message] };\n }\n return found;\n }\n}\n\n/** Steps 1 to 5: who may act, and why. Throws a BookiError when not. */\nfunction admit(context: GuardContext, permission: Permission): void {\n const {\n actor,\n roles = STANDARD_ROLES,\n entity,\n scope,\n deeds,\n dutyRules = STANDARD_DUTY_RULES,\n reason,\n minReason,\n } = context;\n // Fail closed: an actor whose kind is neither a person nor an agent is refused outright.\n if (actor && actor.kind !== \"person\" && actor.kind !== \"agent\") {\n throw new BookiError(\"server.unknown-kind\", { kind: String((actor as { kind?: unknown }).kind) });\n }\n const personOnly = PERSON_ONLY.includes(permission) || (context.personOnly ?? []).includes(permission);\n if (actor?.kind === \"agent\" && personOnly) {\n // Who to ask: a role the refused agent holds is no answer for the reader.\n const able = roles\n .filter((role) => role.permissions.includes(permission) && !actor.roles.includes(role.id))\n .map((role) => role.name);\n throw new BookiError(\"server.person-only\", {\n permission: String(permission),\n roles: able.join(\", \") || msg(\"permissions.none-defined\"),\n });\n }\n assertCan(actor, roles, permission, { entity, scope, deeds, dutyRules });\n // An agent never does more than the person it acts for could have done.\n if (actor?.kind === \"agent\" && actor.onBehalfOf !== undefined && context.personOf) {\n if (!(context.agentOwn ?? []).includes(permission)) {\n const person = context.personOf(actor.onBehalfOf);\n if (!person || person.id !== actor.onBehalfOf) {\n throw new BookiError(\"server.delegation-unknown\", {\n agent: String(actor.id),\n person: String(actor.onBehalfOf),\n });\n }\n if (entity && person.entities && !person.entities.includes(entity)) {\n throw new BookiError(\"server.delegation-entity\", {\n agent: String(actor.id),\n person: String(person.id),\n entity: String(entity),\n });\n }\n if (!can(person, roles, permission, { scope })) {\n // The roles a person could hold: an agent's own roles are not an answer for them.\n const all = roles.filter((role) => role.permissions.includes(permission));\n const forPeople = all.filter((role) => !actor.roles.includes(role.id));\n const able = (forPeople.length ? forPeople : all).map((role) => role.name);\n throw new BookiError(\"server.delegation\", {\n agent: String(actor.id),\n person: String(person.id),\n permission: String(permission),\n roles: able.join(\", \") || msg(\"permissions.none-defined\"),\n });\n }\n }\n }\n if (minReason && String(reason ?? \"\").trim().length < minReason) {\n throw new BookiError(\"server.reason-required\", { min: minReason });\n }\n}\n\n/**\n * Post a voucher: balanced, closed lists, open period. Only a person with\n * `period.adjust-closed` may post into a soft-closed period; an agent never.\n */\nexport function guardPostVoucher(\n context: GuardContext,\n input: { lines: VoucherLine[]; date: string; rules?: VoucherRules },\n): Verdict<VoucherBalance> {\n const roles = context.roles ?? STANDARD_ROLES;\n const mayAdjustClosed =\n context.actor?.kind === \"person\" && can(context.actor, roles, \"period.adjust-closed\", { entity: context.entity });\n return guard(context, \"voucher.post\", () => {\n // A date that does not exist (\"2026-02-30\") would roll into the next month and past a closed period.\n if (!isIsoDate(input.date))\n throw new BookiError(\"period.posting-date-format\", { value: JSON.stringify(input.date) });\n return assertPostable(input.lines, input.rules ?? {}, { date: input.date, mayAdjustClosed });\n });\n}\n\n/** Record an approval decision. A person's, at the level the chain is waiting for. */\nexport function guardDecideApproval(\n context: GuardContext,\n input: {\n chain: ApprovalLevel[];\n request: ApprovalRequest;\n decision: ApprovalDecision[\"decision\"];\n at: string;\n note?: string;\n },\n): Verdict<ApprovalRequest> {\n return guard(context, \"approval.decide\", () =>\n decide(input.chain, input.request, {\n approverId: context.actor!.id,\n decision: input.decision,\n at: input.at,\n ...(input.note ? { note: input.note } : {}),\n }),\n );\n}\n\n/** Act on something that needs approval first (pay it, post it): only once the chain is through. */\nexport function guardApproved(\n context: GuardContext,\n permission: Permission,\n input: { chain: ApprovalLevel[]; request: ApprovalRequest },\n): Verdict<ApprovalRequest> {\n return guard(context, permission, () => {\n assertApproved(input.chain, input.request);\n return input.request;\n });\n}\n\n/**\n * Release a payment batch to the bank: enough current approvals, no\n * duplicates, and the person releasing did not approve it themselves.\n */\nexport function guardReleasePayments(\n context: GuardContext,\n input: { batch: PaymentBatch; requiredApprovals?: number },\n): Verdict<PaymentBatch> {\n const deeds: Deed[] = [\n ...(context.deeds ?? []),\n ...input.batch.approvals.map((approval) => ({\n actorId: approval.approverId,\n permission: \"payment.approve\" as Permission,\n })),\n ];\n return guard({ ...context, deeds }, \"payment.release\", () => releaseBatch(input.batch, input.requiredApprovals));\n}\n\n/** Close a period: every task done and every sign-off in. */\nexport function guardClosePeriod(context: GuardContext, input: { tasks: CloseTask[] }): Verdict<CloseSummary> {\n return guard(context, \"period.close\", () => assertReadyToClose(input.tasks));\n}\n\n/** Mark a deal won or lost: a person's, recorded under their id. Lost needs a reason. */\nexport function guardCloseDeal(\n context: GuardContext,\n input: { deal: Deal; stages: PipelineStage[]; outcome: DealOutcome; at: string; reason?: string },\n): Verdict<Deal> {\n return guard(context, \"deal.close\", () =>\n closeDeal(input.deal, input.stages, input.outcome, context.actor!.id, input.at, input.reason),\n );\n}\n\n/** Confirm an audit finding: a person's, recorded under their id. Warnings (`findingIssues`) do not refuse it. */\nexport function guardConfirmFinding(context: GuardContext, input: { finding: Finding; at: string }): Verdict<Finding> {\n return guard(context, \"finding.confirm\", () => confirmFinding(input.finding, context.actor!.id, input.at));\n}\n\nconst SIGNOFF_PERMISSION = {\n performed: \"audit.prepare\",\n reviewed: \"audit.review\",\n approved: \"audit.sign-off\",\n} as const satisfies Record<SignoffLevel, Permission>;\n\n/**\n * Sign a level of a document: a person's, recorded under their id. `blockOpenPoints` refuses it while points are open\n * (default: they go with the signature). An agent is refused at every level.\n */\nexport function guardSignDocument(\n context: GuardContext,\n input: { document: SignableDocument; level: SignoffLevel; at: string } & SignoffRules,\n): Verdict<SignableDocument> {\n // An unknown level has no permission of its own: check the sign-off permission, and let signDocument name the level.\n const known = Object.prototype.hasOwnProperty.call(SIGNOFF_PERMISSION, input.level);\n const permission: Permission = known ? SIGNOFF_PERMISSION[input.level] : \"audit.sign-off\";\n const actor = context.actor;\n const name = actor?.name;\n return guard({ ...context, personOnly: [...(context.personOnly ?? []), permission] }, permission, () =>\n signDocument(input.document, input.level, { id: actor!.id, ...(name ? { name } : {}) }, input.at, {\n blockOpenPoints: input.blockOpenPoints,\n }),\n );\n}\n\n/** Finalize a sales invoice under a number: no issues, number unused. */\nexport function guardFinalizeInvoice(\n context: GuardContext,\n input: { invoice: Invoice; number: string; others?: Invoice[] },\n): Verdict<Invoice> {\n return guard(context, \"invoice.finalize\", () => finalizeInvoice(input.invoice, input.number, input.others));\n}\n\n/** Submit a VAT return: computed from a valid schema, with no open issues. */\nexport function guardSubmitVatReturn(\n context: GuardContext,\n input: { computation: VatReturnComputation },\n): Verdict<VatReturnComputation> {\n return guard(context, \"vat.submit\", () => {\n assertVatReturnReady(input.computation);\n return input.computation;\n });\n}\n\n/**\n * A verdict as an HTTP answer, for any framework:\n * `const { status, body } = toHttp(verdict); return Response.json(body, { status })`.\n */\nexport function toHttp<T>(verdict: Verdict<T>): { status: number; body: HttpBody<T> } {\n if (verdict.ok) return { status: 200, body: { ok: true, actor: verdict.actor, value: verdict.value } };\n const { status, ...body } = verdict;\n return { status, body };\n}\n\n/** What `toHttp` answers with: the value on success, `{ ok: false, code, message, issues? }` on a refusal. */\nexport type HttpBody<T> = { ok: true; actor: string; value: T } | Omit<Refusal, \"status\">;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyCA,IAAM,SAAS;AACf,IAAM,UAAU,IAAI,YAAY;AAEhC,IAAM,YAAY,CAAC,UACjB,KAAK,OAAO,aAAa,GAAG,KAAK,CAAC,EAC/B,QAAQ,OAAO,GAAG,EAClB,QAAQ,OAAO,GAAG,EAClB,QAAQ,OAAO,EAAE;AACtB,IAAM,gBAAgB,CAAC,SAAiB;AACtC,QAAM,QAAQ,KAAK,KAAK,QAAQ,MAAM,GAAG,EAAE,QAAQ,MAAM,GAAG,CAAC;A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kBACd,SACA,OAC2B;AAE3B,QAAM,QAAQ,OAAO,UAAU,eAAe,KAAK,oBAAoB,MAAM,KAAK;AAClF,QAAM,aAAyB,QAAQ,mBAAmB,MAAM,KAAK,IAAI;AACzE,QAAM,QAAQ,QAAQ;AACtB,QAAM,OAAO,OAAO;AACpB,SAAO;AAAA,IAAM,EAAE,GAAG,SAAS,YAAY,CAAC,GAAI,QAAQ,cAAc,CAAC,GAAI,UAAU,EAAE;AAAA,IAAG;AAAA,IAAY,MAChG,aAAa,MAAM,UAAU,MAAM,OAAO,EAAE,IAAI,MAAO,IAAI,GAAI,OAAO,EAAE,KAAK,IAAI,CAAC,EAAG,GAAG,MAAM,IAAI;AAAA,MAChG,iBAAiB,MAAM;AAAA,IACzB,CAAC;AAAA,EACH;AACF;AAGO,SAAS,qBACd,SACA,OACkB;AAClB,SAAO,MAAM,SAAS,oBAAoB,MAAM,gBAAgB,MAAM,SAAS,MAAM,QAAQ,MAAM,MAAM,CAAC;AAC5G;AAGO,SAAS,qBACd,SACA,OAC+B;AAC/B,SAAO,MAAM,SAAS,cAAc,MAAM;AACxC,yBAAqB,MAAM,WAAW;AACtC,WAAO,MAAM;AAAA,EACf,CAAC;AACH;AAMO,SAAS,OAAU,SAA4D;AACpF,MAAI,QAAQ,GAAI,QAAO,EAAE,QAAQ,KAAK,MAAM,EAAE,IAAI,MAAM,OAAO,QAAQ,OAAO,OAAO,QAAQ,MAAM,EAAE;AACrG,QAAM,EAAE,QAAQ,GAAG,KAAK,IAAI;AAC5B,SAAO,EAAE,QAAQ,KAAK;AACxB;","names":[]}
1
+ {"version":3,"sources":["../src/agent-token.ts","../src/server.ts"],"sourcesContent":["/**\n * A short-lived credential of the agent's own, so the server can tell the\n * agent from the person it works for. Your sign-in issues it for a signed-in\n * person; the page sends it with the agent's writes; the server verifies it\n * and adds the agent's roles. Signed with HMAC-SHA-256 through WebCrypto, so\n * it runs in Node, edge runtimes, Deno and Bun.\n *\n * It is not a session: keep the person's own sign-in for their writes.\n */\n\nexport type AgentGrant = {\n /** The agent's id, as `actorLabel` writes it after `agent:`. */\n agentId: string;\n /** The person whose session the agent works in. */\n onBehalfOf: string;\n /** The client it came through (your page, an MCP client). */\n clientId?: string;\n /**\n * What the token is for: an engagement, a company, one API. `verifyAgentToken`\n * with `{ audience }` refuses a token issued for anything else.\n */\n audience?: string;\n /** Seconds it is valid. Default 900 (15 minutes), at most 86 400. */\n ttlSeconds?: number;\n};\n\n/** What a valid token says: add `roles` from your own records to make a `ServerActor`. */\nexport type AgentClaims = {\n id: string;\n kind: \"agent\";\n onBehalfOf: string;\n clientId?: string;\n audience?: string;\n /** This token's own id, for the audit trail (`actorRecord`). */\n grantId: string;\n /** When it stops being valid, in milliseconds since 1970. */\n expiresAt: number;\n};\n\nimport { BookiError } from \"./msg.js\";\n\nconst PREFIX = \"bk1\";\nconst encoder = new TextEncoder();\n\nconst base64url = (bytes: Uint8Array) =>\n btoa(String.fromCharCode(...bytes))\n .replace(/\\+/g, \"-\")\n .replace(/\\//g, \"_\")\n .replace(/=+$/, \"\");\nconst fromBase64url = (text: string) => {\n const plain = atob(text.replace(/-/g, \"+\").replace(/_/g, \"/\"));\n return Uint8Array.from(plain, (char) => char.charCodeAt(0));\n};\n\nasync function keyFor(secret: string): Promise<CryptoKey> {\n if (typeof secret !== \"string\" || secret.length < 32) {\n throw new BookiError(\"agent-token.secret-short\");\n }\n return crypto.subtle.importKey(\"raw\", encoder.encode(secret), { name: \"HMAC\", hash: \"SHA-256\" }, false, [\n \"sign\",\n \"verify\",\n ]);\n}\n\n/** Issues a token for an agent working for `onBehalfOf`. Call it only for a person your sign-in established. */\nexport async function issueAgentToken(grant: AgentGrant, secret: string, now = Date.now()): Promise<string> {\n const ttl = grant.ttlSeconds ?? 900;\n if (!Number.isSafeInteger(ttl) || ttl < 1 || ttl > 86_400) {\n throw new BookiError(\"agent-token.ttl\", { value: String(ttl) });\n }\n if (!grant.agentId || !grant.onBehalfOf) throw new BookiError(\"agent-token.grant\");\n const claims: AgentClaims = {\n id: grant.agentId,\n kind: \"agent\",\n onBehalfOf: grant.onBehalfOf,\n ...(grant.clientId ? { clientId: grant.clientId } : {}),\n ...(grant.audience ? { audience: grant.audience } : {}),\n grantId: base64url(crypto.getRandomValues(new Uint8Array(12))),\n expiresAt: now + ttl * 1000,\n };\n const payload = base64url(encoder.encode(JSON.stringify(claims)));\n const signature = await crypto.subtle.sign(\"HMAC\", await keyFor(secret), encoder.encode(`${PREFIX}.${payload}`));\n return `${PREFIX}.${payload}.${base64url(new Uint8Array(signature))}`;\n}\n\n/**\n * The claims of a valid, unexpired token signed with `secret`, or null. Null\n * for every failure alike: a caller learns nothing about why.\n */\nexport async function verifyAgentToken(\n token: unknown,\n secret: string,\n now: number | { now?: number; audience?: string } = Date.now(),\n): Promise<AgentClaims | null> {\n const at = typeof now === \"number\" ? now : (now.now ?? Date.now());\n const audience = typeof now === \"number\" ? undefined : now.audience;\n const key = await keyFor(secret);\n if (typeof token !== \"string\" || token.length > 4096) return null;\n const [prefix, payload, signature, ...rest] = token.split(\".\");\n if (prefix !== PREFIX || !payload || !signature || rest.length) return null;\n try {\n const ok = await crypto.subtle.verify(\n \"HMAC\",\n key,\n fromBase64url(signature),\n encoder.encode(`${PREFIX}.${payload}`),\n );\n if (!ok) return null;\n const claims = JSON.parse(new TextDecoder().decode(fromBase64url(payload))) as AgentClaims;\n if (claims.kind !== \"agent\" || typeof claims.id !== \"string\" || typeof claims.onBehalfOf !== \"string\") return null;\n if (!Number.isFinite(claims.expiresAt) || claims.expiresAt <= at) return null;\n // Given an audience, only a token issued for exactly that one passes.\n if (audience !== undefined && claims.audience !== audience) return null;\n return claims;\n } catch {\n return null;\n }\n}\n","/**\n * The same rules the screen enforces, for your API.\n *\n * The controls refuse what a role may not do and what the books do not allow,\n * but a browser is not a security boundary: anything can call your API. Run\n * every write through one of these guards on the server, with the actor your\n * own sign-in established (never one the request says it is). Each guard\n * answers with a verdict you can send straight back: the HTTP status, a stable\n * code and the same sentence the control showed, in English or Norwegian.\n *\n * Order of checks, for every action:\n * 1. Signed in? 401\n * 2. A person's decision, and the actor an agent? 403\n * 3. Role allows it, in this entity? 403\n * And, for an agent acting for someone, theirs? 403 (with `personOf`)\n * 4. Separation of duties against what they did? 403\n * 5. A reason given, where one is required? 422\n * 6. The books allow it (balance, period, approvals, readiness)? 409 or 422\n *\n * Where the books are a matter of professional judgment (an audit file, say),\n * use `advise` instead of `guard`: steps 1 to 5 still refuse, and step 6 comes\n * back as warnings for the person to weigh.\n *\n * Framework-free: plain data in, plain data out. Works in Node, edge runtimes,\n * Deno and Bun.\n */\nexport { type AgentClaims, type AgentGrant, issueAgentToken, verifyAgentToken } from \"./agent-token.js\";\nimport { assertApproved, decide, type ApprovalDecision, type ApprovalLevel, type ApprovalRequest } from \"./approval.js\";\nimport { assertReadyToClose, type CloseSummary, type CloseTask } from \"./close.js\";\nimport { signDocument, type SignableDocument, type SignoffLevel, type SignoffRules } from \"./document-signoff.js\";\nimport { confirmFinding, type Finding } from \"./findings.js\";\nimport { finalizeInvoice, type Invoice } from \"./invoice.js\";\nimport { isIsoDate } from \"./iso-date.js\";\nimport { localize, msgIn, type MessageLanguage } from \"./messages.js\";\nimport { BookiError, isBookiError, msg } from \"./msg.js\";\nimport { releaseBatch, type PaymentBatch } from \"./payment-batch.js\";\nimport { closeDeal, type Deal, type DealOutcome, type PipelineStage } from \"./pipeline.js\";\nimport {\n STANDARD_DUTY_RULES,\n STANDARD_ROLES,\n DutyRefusal,\n assertCan,\n can,\n type Actor,\n type Deed,\n type DutyRule,\n type Permission,\n type Role,\n} from \"./permissions.js\";\nimport { assertVatReturnReady, type VatReturnComputation } from \"./vat-return.js\";\nimport { assertPostable, type VoucherBalance, type VoucherLine, type VoucherRules } from \"./voucher.js\";\n\n/**\n * Who is calling, as your sign-in established it. An agent gets its own\n * credential and comes here as `kind: \"agent\"`; `onBehalfOf` is the person\n * whose session started it. It is recorded, the duty rules count it, and with\n * `personOf` in the context the person's own roles limit what the agent may do.\n */\nexport type ServerActor = Actor & {\n kind: \"person\" | \"agent\";\n onBehalfOf?: string;\n /** For an agent: the client it came through (an MCP client, your workflow), for the audit trail. */\n clientId?: string;\n /** For an agent: the grant or token the person gave it, for the audit trail. */\n grantId?: string;\n};\n\nexport type GuardContext = {\n actor?: ServerActor;\n /** Your roles. Default: `STANDARD_ROLES`. */\n roles?: Role[];\n /** The company the request is for. An actor limited to other entities is refused. */\n entity?: string;\n /** The engagement, case or project: the actor's roles there (`scopes`) count too. */\n scope?: string;\n /** Why, in the actor's words. Kept with the decision. */\n reason?: string;\n /** Refuse unless `reason` has at least this many characters (withdrawing a sign-off, say). */\n minReason?: number;\n /** Your own permissions that only a person may use, added to `PERSON_ONLY`. */\n personOnly?: Permission[];\n /**\n * The person an agent acts for (`actor.onBehalfOf`), with their roles as they\n * are now. Give it, and an agent may only do what that person may do: an id\n * it does not know is refused, and so is a permission or entity the person\n * lacks. Without it `onBehalfOf` is recorded and counts for the duty rules,\n * but the person's roles are not checked.\n */\n personOf?: (id: string) => Actor | undefined;\n /**\n * Permissions an agent has by the company's own rule rather than the person's\n * (approving invoices under a limit, say): `personOf` is not asked for these.\n */\n agentOwn?: Permission[];\n /** What has already been done to this item, and by whom, for the duty rules. */\n deeds?: Deed[];\n /** Default: `STANDARD_DUTY_RULES`. Pass `[]` to switch them off. */\n dutyRules?: DutyRule[];\n /** Language of the refusal sentence. Default: English. */\n locale?: MessageLanguage;\n};\n\nexport type Refusal = {\n ok: false;\n status: 401 | 403 | 409 | 422;\n /** Stable, for your client and your logs. */\n code: string;\n /** One sentence a person or an agent can act on. */\n message: string;\n /** Every problem, where the rule found several. */\n issues?: string[];\n};\n\nexport type Verdict<T> = { ok: true; value: T; actor: string } | Refusal;\n\n/** What `advise` answers: allowed, with what the books say against it, if anything. */\nexport type Advice<T> = { ok: true; value: T | undefined; actor: string; warnings: string[] } | Refusal;\n\n/**\n * Decisions that stay with people, whatever an agent's role says: approving,\n * signing off, finalizing, releasing, closing and submitting.\n */\nexport const PERSON_ONLY: readonly Permission[] = [\n \"audit.review\",\n \"audit.conclude\",\n \"audit.eqcr\",\n \"audit.freeze\",\n \"approval.decide\",\n \"supplier-invoice.approve\",\n \"expense.approve\",\n \"payment.approve\",\n \"payment.release\",\n \"reconciliation.approve\",\n \"period.close\",\n \"period.adjust-closed\",\n \"close.sign-off\",\n \"invoice.finalize\",\n \"vat.submit\",\n \"asset.dispose\",\n \"audit.sign-off\",\n \"finding.confirm\",\n \"finding.withdraw\",\n \"request.send\",\n \"request.decide\",\n \"deal.close\",\n];\n\n/** How an actor appears in the audit trail: `agent:bookkeeper` or the person's id. */\nexport const actorLabel = (actor: ServerActor) => (actor.kind === \"agent\" ? `agent:${actor.id}` : actor.id);\n\n/**\n * The deed to record for what an actor just did, for later duty checks: it\n * names the agent's label and whose session it ran in, so the person cannot\n * review what their own agent prepared.\n */\nexport function actorDeed(actor: ServerActor, permission: Permission): Deed {\n return { actorId: actorLabel(actor), permission, ...(actor.onBehalfOf ? { onBehalfOf: actor.onBehalfOf } : {}) };\n}\n\n/** Everything the audit trail should keep about who acted: the label, the kind, and for an agent whose session, client and grant. */\nexport function actorRecord(actor: ServerActor): {\n actor: string;\n kind: ServerActor[\"kind\"];\n onBehalfOf?: string;\n clientId?: string;\n grantId?: string;\n} {\n return {\n actor: actorLabel(actor),\n kind: actor.kind,\n ...(actor.onBehalfOf ? { onBehalfOf: actor.onBehalfOf } : {}),\n ...(actor.clientId ? { clientId: actor.clientId } : {}),\n ...(actor.grantId ? { grantId: actor.grantId } : {}),\n };\n}\n\nfunction statusOf(code: string): Refusal[\"status\"] {\n if (code === \"permissions.signed-out\") return 401;\n if (code === \"server.reason-required\") return 422;\n if (code.startsWith(\"permissions.\") || code.startsWith(\"server.\")) return 403;\n if (\n /^(period\\.|approval\\.(waiting|rejected)|batch\\.already|invoice\\.(not-editable|number-used)|close\\.)/.test(code)\n ) {\n return 409;\n }\n return 422;\n}\n\nfunction refuse(error: unknown, locale: MessageLanguage | undefined): Refusal {\n if (isBookiError(error)) {\n const issues = Array.isArray(error.params.issues) ? (error.params.issues as unknown[]).map(String) : undefined;\n return {\n ok: false,\n status: statusOf(error.code),\n code: error.code,\n message: locale && locale !== \"en\" ? msgIn(locale, error.code, error.params) : error.message,\n ...(issues\n ? { issues: locale && locale !== \"en\" ? issues.map((issue) => localize(issue, locale)) : issues }\n : {}),\n };\n }\n if (error instanceof DutyRefusal) {\n return {\n ok: false,\n status: 403,\n code: \"permissions.duty\",\n message: locale && locale !== \"en\" ? localize(error.message, locale) : error.message,\n };\n }\n // Your own rule's refusal: its sentence goes back as it is.\n if (error instanceof RuleRefusal) return { ok: false, status: 422, code: \"server.rule\", message: error.message };\n // Anything else (a database error, a bug) is not a refusal, and its message\n // can hold hosts and user names: rethrow it for your error handling.\n throw error;\n}\n\n/**\n * Throw it from a rule of your own to refuse with a sentence of yours: the\n * guard answers 422 `server.rule` with it. Any other error a rule throws is\n * rethrown, so a database error never reaches the caller as a message.\n */\nexport class RuleRefusal extends Error {\n override name = \"RuleRefusal\";\n}\n\n/**\n * The general guard: may this actor do `permission`, and does `rule` pass?\n * The specific guards below are this with the right rule filled in; use it\n * directly for your own actions.\n */\nexport function guard<T>(context: GuardContext, permission: Permission, rule: () => T): Verdict<T> {\n try {\n admit(context, permission);\n return { ok: true, value: rule(), actor: actorLabel(context.actor!) };\n } catch (error) {\n return refuse(error, context.locale);\n }\n}\n\n/**\n * Like `guard`, for actions where the books are a matter of judgment: who may\n * act is still enforced (signed in, a person's decision, role, duties, reason),\n * but what `rule` finds against it comes back as `warnings` instead of a\n * refusal, and `value` is undefined when the rule threw. The person decides.\n */\nexport function advise<T>(context: GuardContext, permission: Permission, rule: () => T): Advice<T> {\n try {\n admit(context, permission);\n } catch (error) {\n return refuse(error, context.locale);\n }\n const actor = actorLabel(context.actor!);\n try {\n return { ok: true, value: rule(), actor, warnings: [] };\n } catch (error) {\n const found = refuse(error, context.locale);\n // Only the books' own objections become warnings; anything about who may act still refuses.\n if (found.status === 409 || found.status === 422) {\n return { ok: true, value: undefined, actor, warnings: found.issues?.length ? found.issues : [found.message] };\n }\n return found;\n }\n}\n\n/** Steps 1 to 5: who may act, and why. Throws a BookiError when not. */\nfunction admit(context: GuardContext, permission: Permission): void {\n const {\n actor,\n roles = STANDARD_ROLES,\n entity,\n scope,\n deeds,\n dutyRules = STANDARD_DUTY_RULES,\n reason,\n minReason,\n } = context;\n // Fail closed: an actor whose kind is neither a person nor an agent is refused outright.\n if (actor && actor.kind !== \"person\" && actor.kind !== \"agent\") {\n throw new BookiError(\"server.unknown-kind\", { kind: String((actor as { kind?: unknown }).kind) });\n }\n const personOnly = PERSON_ONLY.includes(permission) || (context.personOnly ?? []).includes(permission);\n if (actor?.kind === \"agent\" && personOnly) {\n // Who to ask: a role the refused agent holds is no answer for the reader.\n const able = roles\n .filter((role) => role.permissions.includes(permission) && !actor.roles.includes(role.id))\n .map((role) => role.name);\n throw new BookiError(\"server.person-only\", {\n permission: String(permission),\n roles: able.join(\", \") || msg(\"permissions.none-defined\"),\n });\n }\n assertCan(actor, roles, permission, { entity, scope, deeds, dutyRules });\n // An agent never does more than the person it acts for could have done.\n if (actor?.kind === \"agent\" && actor.onBehalfOf !== undefined && context.personOf) {\n if (!(context.agentOwn ?? []).includes(permission)) {\n const person = context.personOf(actor.onBehalfOf);\n if (!person || person.id !== actor.onBehalfOf) {\n throw new BookiError(\"server.delegation-unknown\", {\n agent: String(actor.id),\n person: String(actor.onBehalfOf),\n });\n }\n if (entity && person.entities && !person.entities.includes(entity)) {\n throw new BookiError(\"server.delegation-entity\", {\n agent: String(actor.id),\n person: String(person.id),\n entity: String(entity),\n });\n }\n if (!can(person, roles, permission, { scope })) {\n // The roles a person could hold: an agent's own roles are not an answer for them.\n const all = roles.filter((role) => role.permissions.includes(permission));\n const forPeople = all.filter((role) => !actor.roles.includes(role.id));\n const able = (forPeople.length ? forPeople : all).map((role) => role.name);\n throw new BookiError(\"server.delegation\", {\n agent: String(actor.id),\n person: String(person.id),\n permission: String(permission),\n roles: able.join(\", \") || msg(\"permissions.none-defined\"),\n });\n }\n }\n }\n if (minReason && String(reason ?? \"\").trim().length < minReason) {\n throw new BookiError(\"server.reason-required\", { min: minReason });\n }\n}\n\n/**\n * Post a voucher: balanced, closed lists, open period. Only a person with\n * `period.adjust-closed` may post into a soft-closed period; an agent never.\n */\nexport function guardPostVoucher(\n context: GuardContext,\n input: { lines: VoucherLine[]; date: string; rules?: VoucherRules },\n): Verdict<VoucherBalance> {\n const roles = context.roles ?? STANDARD_ROLES;\n const mayAdjustClosed =\n context.actor?.kind === \"person\" && can(context.actor, roles, \"period.adjust-closed\", { entity: context.entity });\n return guard(context, \"voucher.post\", () => {\n // A date that does not exist (\"2026-02-30\") would roll into the next month and past a closed period.\n if (!isIsoDate(input.date))\n throw new BookiError(\"period.posting-date-format\", { value: JSON.stringify(input.date) });\n return assertPostable(input.lines, input.rules ?? {}, { date: input.date, mayAdjustClosed });\n });\n}\n\n/** Record an approval decision. A person's, at the level the chain is waiting for. */\nexport function guardDecideApproval(\n context: GuardContext,\n input: {\n chain: ApprovalLevel[];\n request: ApprovalRequest;\n decision: ApprovalDecision[\"decision\"];\n at: string;\n note?: string;\n },\n): Verdict<ApprovalRequest> {\n return guard(context, \"approval.decide\", () =>\n decide(input.chain, input.request, {\n approverId: context.actor!.id,\n decision: input.decision,\n at: input.at,\n ...(input.note ? { note: input.note } : {}),\n }),\n );\n}\n\n/** Act on something that needs approval first (pay it, post it): only once the chain is through. */\nexport function guardApproved(\n context: GuardContext,\n permission: Permission,\n input: { chain: ApprovalLevel[]; request: ApprovalRequest },\n): Verdict<ApprovalRequest> {\n return guard(context, permission, () => {\n assertApproved(input.chain, input.request);\n return input.request;\n });\n}\n\n/**\n * Release a payment batch to the bank: enough current approvals, no\n * duplicates, and the person releasing did not approve it themselves.\n */\nexport function guardReleasePayments(\n context: GuardContext,\n input: { batch: PaymentBatch; requiredApprovals?: number },\n): Verdict<PaymentBatch> {\n const deeds: Deed[] = [\n ...(context.deeds ?? []),\n ...input.batch.approvals.map((approval) => ({\n actorId: approval.approverId,\n permission: \"payment.approve\" as Permission,\n })),\n ];\n return guard({ ...context, deeds }, \"payment.release\", () => releaseBatch(input.batch, input.requiredApprovals));\n}\n\n/** Close a period: every task done and every sign-off in. */\nexport function guardClosePeriod(context: GuardContext, input: { tasks: CloseTask[] }): Verdict<CloseSummary> {\n return guard(context, \"period.close\", () => assertReadyToClose(input.tasks));\n}\n\n/** Mark a deal won or lost: a person's, recorded under their id. Lost needs a reason. */\nexport function guardCloseDeal(\n context: GuardContext,\n input: { deal: Deal; stages: PipelineStage[]; outcome: DealOutcome; at: string; reason?: string },\n): Verdict<Deal> {\n return guard(context, \"deal.close\", () =>\n closeDeal(input.deal, input.stages, input.outcome, context.actor!.id, input.at, input.reason),\n );\n}\n\n/** Confirm an audit finding: a person's, recorded under their id. Warnings (`findingIssues`) do not refuse it. */\nexport function guardConfirmFinding(context: GuardContext, input: { finding: Finding; at: string }): Verdict<Finding> {\n return guard(context, \"finding.confirm\", () => confirmFinding(input.finding, context.actor!.id, input.at));\n}\n\nconst SIGNOFF_PERMISSION = {\n performed: \"audit.prepare\",\n reviewed: \"audit.review\",\n approved: \"audit.sign-off\",\n} as const satisfies Record<SignoffLevel, Permission>;\n\n/**\n * Sign a level of a document: a person's, recorded under their id. `blockOpenPoints` refuses it while points are open\n * (default: they go with the signature). An agent is refused at every level.\n */\nexport function guardSignDocument(\n context: GuardContext,\n input: { document: SignableDocument; level: SignoffLevel; at: string } & SignoffRules,\n): Verdict<SignableDocument> {\n // An unknown level has no permission of its own: check the sign-off permission, and let signDocument name the level.\n const known = Object.prototype.hasOwnProperty.call(SIGNOFF_PERMISSION, input.level);\n const permission: Permission = known ? SIGNOFF_PERMISSION[input.level] : \"audit.sign-off\";\n const actor = context.actor;\n const name = actor?.name;\n return guard({ ...context, personOnly: [...(context.personOnly ?? []), permission] }, permission, () =>\n signDocument(input.document, input.level, { id: actor!.id, ...(name ? { name } : {}) }, input.at, {\n blockOpenPoints: input.blockOpenPoints,\n }),\n );\n}\n\n/** Finalize a sales invoice under a number: no issues, number unused. */\nexport function guardFinalizeInvoice(\n context: GuardContext,\n input: { invoice: Invoice; number: string; others?: Invoice[] },\n): Verdict<Invoice> {\n return guard(context, \"invoice.finalize\", () => finalizeInvoice(input.invoice, input.number, input.others));\n}\n\n/** Submit a VAT return: computed from a valid schema, with no open issues. */\nexport function guardSubmitVatReturn(\n context: GuardContext,\n input: { computation: VatReturnComputation },\n): Verdict<VatReturnComputation> {\n return guard(context, \"vat.submit\", () => {\n assertVatReturnReady(input.computation);\n return input.computation;\n });\n}\n\n/**\n * A verdict as an HTTP answer, for any framework:\n * `const { status, body } = toHttp(verdict); return Response.json(body, { status })`.\n */\nexport function toHttp<T>(verdict: Verdict<T>): { status: number; body: HttpBody<T> } {\n if (verdict.ok) return { status: 200, body: { ok: true, actor: verdict.actor, value: verdict.value } };\n const { status, ...body } = verdict;\n return { status, body };\n}\n\n/** What `toHttp` answers with: the value on success, `{ ok: false, code, message, issues? }` on a refusal. */\nexport type HttpBody<T> = { ok: true; actor: string; value: T } | Omit<Refusal, \"status\">;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyCA,IAAM,SAAS;AACf,IAAM,UAAU,IAAI,YAAY;AAEhC,IAAM,YAAY,CAAC,UACjB,KAAK,OAAO,aAAa,GAAG,KAAK,CAAC,EAC/B,QAAQ,OAAO,GAAG,EAClB,QAAQ,OAAO,GAAG,EAClB,QAAQ,OAAO,EAAE;AACtB,IAAM,gBAAgB,CAAC,SAAiB;AACtC,QAAM,QAAQ,KAAK,KAAK,QAAQ,MAAM,GAAG,EAAE,QAAQ,MAAM,GAAG,CAAC;AAC7D,SAAO,WAAW,KAAK,OAAO,CAAC,SAAS,KAAK,WAAW,CAAC,CAAC;AAC5D;AAEA,eAAe,OAA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QAAM,aAAyB,QAAQ,mBAAmB,MAAM,KAAK,IAAI;AACzE,QAAM,QAAQ,QAAQ;AACtB,QAAM,OAAO,OAAO;AACpB,SAAO;AAAA,IAAM,EAAE,GAAG,SAAS,YAAY,CAAC,GAAI,QAAQ,cAAc,CAAC,GAAI,UAAU,EAAE;AAAA,IAAG;AAAA,IAAY,MAChG,aAAa,MAAM,UAAU,MAAM,OAAO,EAAE,IAAI,MAAO,IAAI,GAAI,OAAO,EAAE,KAAK,IAAI,CAAC,EAAG,GAAG,MAAM,IAAI;AAAA,MAChG,iBAAiB,MAAM;AAAA,IACzB,CAAC;AAAA,EACH;AACF;AAGO,SAAS,qBACd,SACA,OACkB;AAClB,SAAO,MAAM,SAAS,oBAAoB,MAAM,gBAAgB,MAAM,SAAS,MAAM,QAAQ,MAAM,MAAM,CAAC;AAC5G;AAGO,SAAS,qBACd,SACA,OAC+B;AAC/B,SAAO,MAAM,SAAS,cAAc,MAAM;AACxC,yBAAqB,MAAM,WAAW;AACtC,WAAO,MAAM;AAAA,EACf,CAAC;AACH;AAMO,SAAS,OAAU,SAA4D;AACpF,MAAI,QAAQ,GAAI,QAAO,EAAE,QAAQ,KAAK,MAAM,EAAE,IAAI,MAAM,OAAO,QAAQ,OAAO,OAAO,QAAQ,MAAM,EAAE;AACrG,QAAM,EAAE,QAAQ,GAAG,KAAK,IAAI;AAC5B,SAAO,EAAE,QAAQ,KAAK;AACxB;","names":[]}
@@ -13,8 +13,12 @@ import {
13
13
  redactSupplierInvoice,
14
14
  rejectSupplierInvoice,
15
15
  supplierInvoiceIssues
16
- } from "./chunk-U2M6WCUI.js";
17
- import "./chunk-EGUAYFGH.js";
16
+ } from "./chunk-2DAEO7ZI.js";
17
+ import "./chunk-YVF4UCRM.js";
18
+ import "./chunk-54VPA5IO.js";
19
+ import "./chunk-GCSGHKXS.js";
20
+ import "./chunk-EIM3HADW.js";
21
+ import "./chunk-6QCJ2ZBB.js";
18
22
  export {
19
23
  DEFAULT_CONFIDENCE_THRESHOLD,
20
24
  SUPPLIER_INVOICE_FIELDS,
package/dist/table.js CHANGED
@@ -6,8 +6,12 @@ import {
6
6
  normalizeQuery,
7
7
  tableView,
8
8
  toCsv
9
- } from "./chunk-V5DTXL3H.js";
10
- import "./chunk-EGUAYFGH.js";
9
+ } from "./chunk-MA536GKU.js";
10
+ import "./chunk-YVF4UCRM.js";
11
+ import "./chunk-54VPA5IO.js";
12
+ import "./chunk-GCSGHKXS.js";
13
+ import "./chunk-EIM3HADW.js";
14
+ import "./chunk-6QCJ2ZBB.js";
11
15
  export {
12
16
  MAX_PAGE_SIZE,
13
17
  assertPage,
@@ -9,10 +9,14 @@ import {
9
9
  vatBoxVouchers,
10
10
  vatReturnIssues,
11
11
  vatSchemaIssues
12
- } from "./chunk-KDCB6RKO.js";
12
+ } from "./chunk-NP2S3BCP.js";
13
13
  import "./chunk-ICBA5A2V.js";
14
- import "./chunk-JMOLS4U5.js";
15
- import "./chunk-EGUAYFGH.js";
14
+ import "./chunk-YZ3UV5S3.js";
15
+ import "./chunk-YVF4UCRM.js";
16
+ import "./chunk-54VPA5IO.js";
17
+ import "./chunk-GCSGHKXS.js";
18
+ import "./chunk-EIM3HADW.js";
19
+ import "./chunk-6QCJ2ZBB.js";
16
20
  export {
17
21
  DRAFT_VAT_FILING,
18
22
  GENERIC_VAT_SCHEMA_EXAMPLE,
package/dist/voucher.js CHANGED
@@ -22,13 +22,17 @@ import {
22
22
  validateVoucherLine,
23
23
  vatPostings,
24
24
  voucherIssues
25
- } from "./chunk-ZVBXNHFR.js";
26
- import "./chunk-HCMLRRN4.js";
25
+ } from "./chunk-K3LOJGUG.js";
26
+ import "./chunk-J6PB5LMQ.js";
27
27
  import "./chunk-ICBA5A2V.js";
28
- import "./chunk-JMOLS4U5.js";
29
- import "./chunk-62QTK3RO.js";
30
- import "./chunk-BUMQBGO3.js";
31
- import "./chunk-EGUAYFGH.js";
28
+ import "./chunk-YZ3UV5S3.js";
29
+ import "./chunk-2JWD25RD.js";
30
+ import "./chunk-NZ3APVAI.js";
31
+ import "./chunk-YVF4UCRM.js";
32
+ import "./chunk-54VPA5IO.js";
33
+ import "./chunk-GCSGHKXS.js";
34
+ import "./chunk-EIM3HADW.js";
35
+ import "./chunk-6QCJ2ZBB.js";
32
36
  import "./chunk-ZJXNLPER.js";
33
37
  export {
34
38
  applyAccountRules,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@booki-aui/core",
3
- "version": "0.3.2",
3
+ "version": "0.4.0",
4
4
  "description": "Booki core — the accounting rules behind agent-first apps: integer money, locale profiles, validators, ledger and table logic. Framework-agnostic. Norway and US profiles are supported; SE, DK, GB and DE are experimental starters.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -9,7 +9,7 @@
9
9
  "url": "git+https://github.com/Walgermo/booki.git",
10
10
  "directory": "packages/core"
11
11
  },
12
- "homepage": "https://github.com/Walgermo/booki#readme",
12
+ "homepage": "https://booki.dev/docs/installation",
13
13
  "bugs": {
14
14
  "url": "https://github.com/Walgermo/booki/issues"
15
15
  },
@@ -175,6 +175,10 @@
175
175
  "types": "./dist/msg.d.ts",
176
176
  "default": "./dist/msg.js"
177
177
  },
178
+ "./msg/amount": {
179
+ "types": "./dist/msg-amount.d.ts",
180
+ "default": "./dist/msg-amount.js"
181
+ },
178
182
  "./messages": {
179
183
  "types": "./dist/messages.d.ts",
180
184
  "default": "./dist/messages.js"
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/money.ts"],"sourcesContent":["import { BookiError } from \"./msg.js\";\n\n/** Integer minor-unit money. Never use floats as source of truth. */\n\nexport type BookiCurrencyCode = string;\n\nexport type Money = {\n /** Integer minor units (øre, cents, …) */\n minor: number;\n currency: BookiCurrencyCode;\n};\n\n/** ISO 4217 default fraction digits for MVP currencies (+ extensible). */\nconst MINOR_DIGITS: Record<string, number> = {\n NOK: 2,\n USD: 2,\n EUR: 2,\n GBP: 2,\n SEK: 2,\n DKK: 2,\n JPY: 0,\n KWD: 3,\n};\n\nexport function minorDigitsFor(currency: BookiCurrencyCode): number {\n return MINOR_DIGITS[currency.toUpperCase()] ?? 2;\n}\n\nexport function money(minor: number, currency: BookiCurrencyCode): Money {\n if (!Number.isSafeInteger(minor)) {\n throw new BookiError(\"money.not-safe-integer\", { value: String(minor) });\n }\n // -0 is 0: it would print as \"-NOK 0.00\".\n return { minor: minor === 0 ? 0 : minor, currency: currency.toUpperCase() };\n}\n\n/**\n * Plain decimal digits for a finite number, using its shortest round-trip\n * text (so 1.005 reads as \"1.005\", not 1.00499999…). Expands exponents.\n */\nfunction plainDecimal(value: number): { negative: boolean; int: string; frac: string } {\n const text = String(Math.abs(value)).toLowerCase();\n const [mantissa = \"0\", exponentText] = text.split(\"e\");\n const exponent = exponentText === undefined ? 0 : Number(exponentText);\n const [intPart = \"0\", fracPart = \"\"] = mantissa.split(\".\");\n let digits = intPart + fracPart;\n let point = intPart.length + exponent;\n if (point < 0) {\n digits = \"0\".repeat(-point) + digits;\n point = 0;\n }\n if (point > digits.length) {\n digits = digits + \"0\".repeat(point - digits.length);\n }\n return {\n negative: value < 0,\n int: digits.slice(0, point).replace(/^0+(?=\\d)/, \"\") || \"0\",\n frac: digits.slice(point),\n };\n}\n\n/**\n * Integer minor units from exact decimal digits, rounding half away from zero\n * at the currency's fraction digits.\n */\nfunction digitsToMinor(negative: boolean, int: string, frac: string, minorDigits: number): number {\n const kept = (frac + \"0\".repeat(minorDigits)).slice(0, minorDigits);\n const next = frac.charAt(minorDigits);\n let magnitude = Number(`${int}${kept}`);\n if (next !== \"\" && next >= \"5\") magnitude += 1;\n const minor = negative ? -magnitude : magnitude;\n return minor === 0 ? 0 : minor;\n}\n\n/**\n * Major units (a JS number) to Money. Uses the number's decimal text, so\n * `fromMajor(1.005, \"USD\")` is 101 cents. Rounds half away from zero.\n */\nexport function fromMajor(major: number, currency: BookiCurrencyCode): Money {\n if (!Number.isFinite(major)) {\n throw new BookiError(\"money.not-finite\", { value: String(major) });\n }\n const { negative, int, frac } = plainDecimal(major);\n return money(digitsToMinor(negative, int, frac, minorDigitsFor(currency)), currency);\n}\n\n/**\n * Exact decimal text in major units, as a database numeric or decimal.js gives\n * it (\"1234.5\", \"-0.75\"), to minor units. No floating point on the way. Text\n * with more decimals than the currency has is refused unless they are zeros,\n * so a rounding never happens without you choosing it.\n */\nexport function minorFromDecimal(text: string, currency: BookiCurrencyCode): number {\n const value = String(text).trim();\n const match = /^([+-])?(\\d+)(?:\\.(\\d+))?$/.exec(value);\n if (!match) throw new BookiError(\"money.not-decimal\", { value });\n const [, sign, int, frac = \"\"] = match;\n const digits = minorDigitsFor(currency);\n if (/[1-9]/.test(frac.slice(digits))) {\n throw new BookiError(\"money.too-precise\", { value, digits, currency: String(currency) });\n }\n const whole = BigInt(int! + frac.slice(0, digits).padEnd(digits, \"0\"));\n const minor = sign === \"-\" ? -whole : whole;\n if (minor > BigInt(Number.MAX_SAFE_INTEGER) || minor < BigInt(Number.MIN_SAFE_INTEGER)) {\n throw new BookiError(\"money.not-safe-integer\", { value });\n }\n return Number(minor) || 0;\n}\n\n/** Minor units back to exact decimal text in major units: 123450 NOK → \"1234.50\". */\nexport function decimalFromMinor(minor: number, currency: BookiCurrencyCode): string {\n if (!Number.isSafeInteger(minor)) throw new BookiError(\"money.not-safe-integer\", { value: String(minor) });\n const digits = minorDigitsFor(currency);\n const abs = String(Math.abs(minor)).padStart(digits + 1, \"0\");\n const text = digits ? `${abs.slice(0, -digits)}.${abs.slice(-digits)}` : abs;\n return minor < 0 ? `-${text}` : text;\n}\n\n/**\n * Minor units as exact decimal text for Intl.NumberFormat, which formats a\n * numeric string without going through a float: 7100000000000007 øre stays\n * \",07\", not \",06\".\n */\nfunction exact(minor: number, currency: BookiCurrencyCode): number {\n return decimalFromMinor(minor, currency) as unknown as number;\n}\n\nexport function toMajor(value: Money): number {\n const digits = minorDigitsFor(value.currency);\n return value.minor / 10 ** digits;\n}\n\nexport function addMoney(a: Money, b: Money): Money {\n assertSameCurrency(a, b);\n return money(a.minor + b.minor, a.currency);\n}\n\nexport function subMoney(a: Money, b: Money): Money {\n assertSameCurrency(a, b);\n return money(a.minor - b.minor, a.currency);\n}\n\nexport function assertSameCurrency(a: Money, b: Money): void {\n if (a.currency !== b.currency) {\n throw new BookiError(\"money.currency-mismatch\", { a: String(a.currency), b: String(b.currency) });\n }\n}\n\nexport type FormatMoneyOptions = {\n locale?: string;\n withCurrency?: boolean;\n /** Use accounting parentheses for negatives */\n accounting?: boolean;\n /** Show zero as this text instead, as many Nordic ledgers do: `zero: \"–\"`. */\n zero?: string;\n /** Leave out the fraction when it is zero: `12 500 kr`, but still `12 500,50 kr`. For figures, not ledgers. */\n trimZeroFraction?: boolean;\n};\n\nexport function formatMoney(\n value: Money | number,\n options?: FormatMoneyOptions & { currency?: BookiCurrencyCode },\n): string {\n const m = typeof value === \"number\" ? money(value, options?.currency ?? \"NOK\") : value;\n const locale = options?.locale ?? \"en-US\";\n const accounting = options?.accounting ?? false;\n if (m.minor === 0 && options?.zero !== undefined) return options.zero;\n const digits =\n options?.trimZeroFraction && m.minor % 10 ** minorDigitsFor(m.currency) === 0 ? 0 : minorDigitsFor(m.currency);\n\n if (options?.withCurrency === false) {\n const text = new Intl.NumberFormat(locale, {\n minimumFractionDigits: digits,\n maximumFractionDigits: digits,\n }).format(exact(Math.abs(m.minor), m.currency));\n // Keep the sign: a minus, or the accounting parentheses.\n if (m.minor >= 0) return text;\n return accounting ? `(${text})` : `-${text}`;\n }\n\n const formatted = new Intl.NumberFormat(locale, {\n style: \"currency\",\n currency: m.currency,\n currencySign: accounting ? \"accounting\" : \"standard\",\n minimumFractionDigits: digits,\n maximumFractionDigits: digits,\n }).format(exact(m.minor, m.currency));\n\n return formatted;\n}\n\n/** Exact decimal reading of amount text: sign plus integer / fraction digits. */\nexport type ParsedAmount = {\n negative: boolean;\n /** Integer digits, no separators (\"0\" when the text starts with a separator). */\n int: string;\n /** Fraction digits as typed (\"\" when there are none). */\n frac: string;\n};\n\nfunction localeDecimalSeparator(locale: string): string {\n try {\n return new Intl.NumberFormat(locale).formatToParts(1.1).find((part) => part.type === \"decimal\")?.value ?? \".\";\n } catch {\n return \".\";\n }\n}\n\nfunction currencyMarks(locale: string, currency: string): string[] {\n const marks = new Set<string>([currency.toUpperCase()]);\n for (const currencyDisplay of [\"symbol\", \"narrowSymbol\"] as const) {\n for (const loc of [locale, \"en-US\"]) {\n try {\n const symbol = new Intl.NumberFormat(loc, {\n style: \"currency\",\n currency,\n currencyDisplay,\n })\n .formatToParts(1)\n .find((part) => part.type === \"currency\")?.value;\n if (symbol) marks.add(symbol.replace(/\\s/g, \"\").toUpperCase());\n } catch {\n // Unknown currency code: the code itself is still stripped.\n }\n }\n }\n return [...marks].filter(Boolean).sort((a, b) => b.length - a.length);\n}\n\nfunction stripCurrencyEdges(text: string, marks: string[]): string {\n let out = text;\n let changed = true;\n while (changed) {\n changed = false;\n const upper = out.toUpperCase();\n for (const mark of marks) {\n if (upper.startsWith(mark)) {\n out = out.slice(mark.length);\n changed = true;\n break;\n }\n if (upper.endsWith(mark)) {\n out = out.slice(0, out.length - mark.length);\n changed = true;\n break;\n }\n }\n }\n return out;\n}\n\nfunction count(text: string, char: string): number {\n return text.split(char).length - 1;\n}\n\nfunction isGrouped(text: string, group: string): boolean {\n const escaped = group === \".\" ? \"\\\\.\" : group;\n return new RegExp(`^\\\\d{1,3}(${escaped}\\\\d{3})+$`).test(text);\n}\n\n/**\n * Strict, exact parse of typed amount text. Returns null for anything that\n * isn't unambiguously a number:\n *\n * - Whitespace (incl. NBSP / narrow NBSP), the currency code and symbol are\n * ignored; one leading minus (`-` or `−`) or wrapping parentheses mean negative.\n * - Any other character (letters, exponents, a second sign) → null.\n * - Both `.` and `,`: the last one is the decimal separator; the other must\n * form well-formed 3-digit groups.\n * - One kind only: decimal when it's the locale's decimal separator and appears\n * once; otherwise grouping when it forms 3-digit groups; otherwise decimal\n * when it appears once; otherwise null.\n */\nexport function parseAmountText(\n input: string,\n options?: { locale?: string; currency?: BookiCurrencyCode },\n): ParsedAmount | null {\n const locale = options?.locale ?? \"en-US\";\n const currency = options?.currency ?? \"USD\";\n const marks = currencyMarks(locale, currency);\n\n // Spaces only as thousands groups (\"1 234 567\"): \"12 34\" is a typo, not 1234.\n for (const match of String(input).matchAll(/\\d[\\s\\u00a0\\u202f]+(\\d+)/g)) {\n if (match[1]!.length !== 3) return null;\n }\n let text = String(input).replace(/\\s/g, \"\");\n text = stripCurrencyEdges(text, marks);\n let negative = false;\n if (text.startsWith(\"(\") && text.endsWith(\")\")) {\n negative = true;\n text = stripCurrencyEdges(text.slice(1, -1), marks);\n }\n if (text.startsWith(\"-\") || text.startsWith(\"−\")) {\n if (negative) return null;\n negative = true;\n text = stripCurrencyEdges(text.slice(1), marks);\n }\n if (!/^[\\d.,]+$/.test(text) || !/\\d/.test(text)) return null;\n\n const dots = count(text, \".\");\n const commas = count(text, \",\");\n let decimal: string | null = null;\n let group: string | null = null;\n\n if (dots > 0 && commas > 0) {\n decimal = text.lastIndexOf(\".\") > text.lastIndexOf(\",\") ? \".\" : \",\";\n group = decimal === \".\" ? \",\" : \".\";\n if (count(text, decimal) !== 1) return null;\n } else if (dots > 0 || commas > 0) {\n const sep = dots > 0 ? \".\" : \",\";\n const occurrences = dots + commas;\n if (sep === localeDecimalSeparator(locale) && occurrences === 1) {\n decimal = sep;\n } else if (isGrouped(text, sep)) {\n group = sep;\n } else if (occurrences === 1) {\n decimal = sep;\n } else {\n return null;\n }\n }\n\n let intText = text;\n let frac = \"\";\n if (decimal !== null) {\n const at = text.indexOf(decimal);\n intText = text.slice(0, at);\n frac = text.slice(at + 1);\n if (!/^\\d*$/.test(frac)) return null;\n if (intText === \"\" && frac === \"\") return null;\n }\n if (group !== null && intText.includes(group)) {\n if (!isGrouped(intText, group)) return null;\n intText = intText.split(group).join(\"\");\n }\n if (!/^\\d*$/.test(intText)) return null;\n if (intText === \"\" && group !== null) return null;\n\n return {\n negative,\n int: intText.replace(/^0+(?=\\d)/, \"\") || \"0\",\n frac,\n };\n}\n\n/**\n * Parse user-typed amount text into major units (a JS number).\n * Strict: see `parseAmountText`. Prefer `parseToMinor` for money.\n */\nexport function parseMajorInput(\n input: string,\n options?: { locale?: string; currency?: BookiCurrencyCode },\n): number | null {\n const parsed = parseAmountText(input, options);\n if (!parsed) return null;\n const n = Number(`${parsed.int}${parsed.frac ? `.${parsed.frac}` : \"\"}`);\n if (!Number.isFinite(n)) return null;\n return parsed.negative && n !== 0 ? -n : n;\n}\n\n/**\n * Parse typed amount text straight to integer minor units, without float\n * multiplication. Returns null when the text isn't a number, has more\n * fraction digits than the currency (JPY 0, NOK 2, KWD 3), or is outside the\n * safe integer range.\n */\nexport function parseToMinor(input: string, currency: BookiCurrencyCode, options?: { locale?: string }): number | null {\n const parsed = parseAmountText(input, { locale: options?.locale, currency });\n if (!parsed) return null;\n const digits = minorDigitsFor(currency);\n if (parsed.frac.length > digits) return null;\n const minor = digitsToMinor(parsed.negative, parsed.int, parsed.frac, digits);\n return Number.isSafeInteger(minor) ? minor : null;\n}\n\nexport function parseToMoney(input: string, currency: BookiCurrencyCode, options?: { locale?: string }): Money | null {\n const minor = parseToMinor(input, currency, options);\n if (minor === null) return null;\n return money(minor, currency);\n}\n"],"mappings":";;;;;AAaA,IAAM,eAAuC;AAAA,EAC3C,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AACP;AAEO,SAAS,eAAe,UAAqC;AAClE,SAAO,aAAa,SAAS,YAAY,CAAC,KAAK;AACjD;AAEO,SAAS,MAAM,OAAe,UAAoC;AACvE,MAAI,CAAC,OAAO,cAAc,KAAK,GAAG;AAChC,UAAM,IAAI,WAAW,0BAA0B,EAAE,OAAO,OAAO,KAAK,EAAE,CAAC;AAAA,EACzE;AAEA,SAAO,EAAE,OAAO,UAAU,IAAI,IAAI,O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AO;AAC7C,MAAI,CAAC,OAAQ,QAAO;AACpB,QAAM,IAAI,OAAO,GAAG,OAAO,GAAG,GAAG,OAAO,OAAO,IAAI,OAAO,IAAI,KAAK,EAAE,EAAE;AACvE,MAAI,CAAC,OAAO,SAAS,CAAC,EAAG,QAAO;AAChC,SAAO,OAAO,YAAY,MAAM,IAAI,CAAC,IAAI;AAC3C;AAQO,SAAS,aAAa,OAAe,UAA6B,SAA8C;AACrH,QAAM,SAAS,gBAAgB,OAAO,EAAE,QAAQ,SAAS,QAAQ,SAAS,CAAC;AAC3E,MAAI,CAAC,OAAQ,QAAO;AACpB,QAAM,SAAS,eAAe,QAAQ;AACtC,MAAI,OAAO,KAAK,SAAS,OAAQ,QAAO;AACxC,QAAM,QAAQ,cAAc,OAAO,UAAU,OAAO,KAAK,OAAO,MAAM,MAAM;AAC5E,SAAO,OAAO,cAAc,KAAK,IAAI,QAAQ;AAC/C;AAEO,SAAS,aAAa,OAAe,UAA6B,SAA6C;AACpH,QAAM,QAAQ,aAAa,OAAO,UAAU,OAAO;AACnD,MAAI,UAAU,KAAM,QAAO;AAC3B,SAAO,MAAM,OAAO,QAAQ;AAC9B;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/locale/profiles.ts"],"sourcesContent":["import { BookiError } from \"../msg.js\";\nimport type { BookiLocaleProfile } from \"./types.js\";\n\nexport const NO_PROFILE: BookiLocaleProfile = {\n country: \"NO\",\n locale: \"nb-NO\",\n currency: \"NOK\",\n minorDigits: 2,\n tax: {\n label: \"MVA\",\n defaultPercent: 25,\n codes: [\n { code: \"MVA0\", label: \"0% MVA\", percent: 0 },\n { code: \"MVA15\", label: \"15% MVA\", percent: 15 },\n { code: \"MVA25\", label: \"25% MVA\", percent: 25 },\n ],\n },\n bankAccount: {\n kind: \"kontonummer\",\n label: \"Kontonummer\",\n description: \"11 siffer, formatert som XXXX XX XXXXX\",\n },\n paymentReference: {\n kind: \"kid\",\n label: \"KID\",\n description: \"Kundeidentifikasjon, 4–25 siffer\",\n },\n organizationNumber: {\n kind: \"orgnr\",\n label: \"Organisasjonsnummer\",\n description: \"9 siffer, mod11\",\n },\n period: {\n defaultGranularity: \"vat-term\",\n label: \"Periode\",\n },\n sca: {\n kind: \"bankid\",\n brand: \"BankID\",\n title: \"Bekreft med BankID\",\n description: \"Mock SCA-flyt. Ingen ekte BankID-kall i MVP.\",\n openLabel: \"Åpne BankID\",\n pendingLabel: \"Åpner BankID…\",\n doneLabel: \"Identitet bekreftet\",\n },\n accounts: {\n bank: { number: \"1920\", name: \"Bankinnskudd\" },\n receivable: { number: \"1500\", name: \"Kundefordringer\" },\n revenue: { number: \"3000\", name: \"Salgsinntekt\" },\n taxPayable: { number: \"2701\", name: \"Utgående mva\" },\n expense: { number: \"4000\", name: \"Varekostnad\" },\n },\n copy: {\n amount: \"Beløp\",\n amountExTax: \"Beløp eks. mva\",\n withTax: \"Med {percent}% mva\",\n payee: \"Mottaker\",\n bankAccount: \"Kontonummer\",\n paymentReference: \"KID\",\n memo: \"Melding\",\n fee: \"Gebyr\",\n confirmPayment: \"Bekreft betaling\",\n cancel: \"Avbryt\",\n close: \"Lukk\",\n postVoucher: \"Bokfør bilag\",\n balanced: \"I balanse\",\n unbalanced: \"Ikke i balanse\",\n debit: \"Debet\",\n credit: \"Kredit\",\n account: \"Konto\",\n accountName: \"Navn\",\n dimensions: \"Dimensjoner\",\n department: \"Avdeling\",\n project: \"Prosjekt\",\n line: \"Linje\",\n addLine: \"Legg til linje\",\n removeLine: \"Fjern linje\",\n none: \"Ingen\",\n invalidAmount: \"Ugyldig beløp\",\n reconciliation: \"Bankavstemming\",\n bankStatement: \"Kontoutskrift\",\n ledger: \"Åpne poster\",\n date: \"Dato\",\n text: \"Tekst\",\n select: \"Velg\",\n matchSelected: \"Avstem valgte\",\n selectToMatch: \"Velg linjer på begge sider\",\n difference: \"Differanse\",\n suggestions: \"Forslag\",\n noSuggestions: \"Ingen forslag venter\",\n nothingUnmatched: \"Alt er avstemt\",\n reconciled: \"Avstemt\",\n notReconciled: \"Ikke avstemt\",\n outstanding: \"Gjenstår\",\n emptyAudit: \"Ingen revisjonshendelser\",\n customer: \"Kunde\",\n paymentSent: \"Betaling sendt (mock)\",\n scaVerified: \"SCA fullført\",\n selectAccount: \"Velg konto…\",\n approve: \"Attester\",\n reject: \"Avvis\",\n escalate: \"Eskaler\",\n typeToConfirm: \"Skriv APPROVE for å bekrefte\",\n exceptionTitle: \"Krever gjennomgang\",\n proposedByAgent: \"Foreslått av agent\",\n organizationNumber: \"Organisasjonsnummer\",\n invoiceNumber: \"Fakturanr\",\n invoiceNumberHint: \"Nummeret som står på fakturaen\",\n invoiceDate: \"Fakturadato\",\n dueDate: \"Forfall\",\n postingDate: \"Bokføringsdato\",\n period: \"Periode\",\n attestation: \"Attestering\",\n attestationPending: \"Venter\",\n attestationApproved: \"Godkjent\",\n attestationRejected: \"Avvist\",\n attestationEscalated: \"Eskalert\",\n },\n demo: {\n companyName: \"Nordlys AS\",\n lineDescription: \"Konsulentbistand\",\n },\n};\n\nexport const US_PROFILE: BookiLocaleProfile = {\n country: \"US\",\n locale: \"en-US\",\n currency: \"USD\",\n minorDigits: 2,\n tax: {\n label: \"Sales tax\",\n defaultPercent: 8.875,\n codes: [\n { code: \"TAX0\", label: \"0% tax\", percent: 0 },\n { code: \"TAX8875\", label: \"8.875% tax\", percent: 8.875 },\n ],\n },\n bankAccount: {\n kind: \"routing-account\",\n label: \"Bank account\",\n description: \"ABA routing (9 digits) + account number\",\n },\n paymentReference: {\n kind: \"memo\",\n label: \"Payment memo\",\n description: \"Invoice or remittance reference\",\n },\n organizationNumber: {\n kind: \"ein\",\n label: \"EIN\",\n description: \"Employer Identification Number\",\n },\n period: {\n defaultGranularity: \"month\",\n label: \"Period\",\n },\n sca: {\n kind: \"passkey\",\n brand: \"Passkey\",\n title: \"Confirm with passkey\",\n description: \"Mock SCA step. No live WebAuthn in MVP.\",\n openLabel: \"Use passkey\",\n pendingLabel: \"Waiting…\",\n doneLabel: \"Identity verified\",\n },\n accounts: {\n bank: { number: \"1010\", name: \"Operating cash\" },\n receivable: { number: \"1200\", name: \"Accounts receivable\" },\n revenue: { number: \"4000\", name: \"Sales revenue\" },\n taxPayable: { number: \"2150\", name: \"Sales tax payable\" },\n expense: { number: \"5000\", name: \"Cost of goods sold\" },\n },\n copy: {\n amount: \"Amount\",\n amountExTax: \"Amount excl. tax\",\n withTax: \"With {percent}% tax\",\n payee: \"Payee\",\n bankAccount: \"Account\",\n paymentReference: \"Reference\",\n memo: \"Memo\",\n fee: \"Fee\",\n confirmPayment: \"Confirm payment\",\n cancel: \"Cancel\",\n close: \"Close\",\n postVoucher: \"Post voucher\",\n balanced: \"In balance\",\n unbalanced: \"Out of balance\",\n debit: \"Debit\",\n credit: \"Credit\",\n account: \"Account\",\n accountName: \"Name\",\n dimensions: \"Dimensions\",\n department: \"Department\",\n project: \"Project\",\n line: \"Line\",\n addLine: \"Add line\",\n removeLine: \"Remove line\",\n none: \"None\",\n invalidAmount: \"Invalid amount\",\n reconciliation: \"Bank reconciliation\",\n bankStatement: \"Bank statement\",\n ledger: \"Open posts\",\n date: \"Date\",\n text: \"Text\",\n select: \"Select\",\n matchSelected: \"Match selected\",\n selectToMatch: \"Select lines on both sides\",\n difference: \"Difference\",\n suggestions: \"Suggestions\",\n noSuggestions: \"No suggestions waiting\",\n nothingUnmatched: \"Nothing left to match\",\n reconciled: \"Reconciled\",\n notReconciled: \"Not reconciled\",\n outstanding: \"Outstanding\",\n emptyAudit: \"No audit events yet\",\n customer: \"Customer\",\n paymentSent: \"Payment sent (mock)\",\n scaVerified: \"SCA completed\",\n selectAccount: \"Select account…\",\n approve: \"Approve\",\n reject: \"Reject\",\n escalate: \"Escalate\",\n typeToConfirm: \"Type APPROVE to confirm\",\n exceptionTitle: \"Needs review\",\n proposedByAgent: \"Proposed by agent\",\n organizationNumber: \"EIN\",\n invoiceNumber: \"Invoice #\",\n invoiceNumberHint: \"The number printed on the invoice\",\n invoiceDate: \"Invoice date\",\n dueDate: \"Due date\",\n postingDate: \"Posting date\",\n period: \"Period\",\n attestation: \"Attestation\",\n attestationPending: \"Pending\",\n attestationApproved: \"Approved\",\n attestationRejected: \"Rejected\",\n attestationEscalated: \"Escalated\",\n },\n demo: {\n companyName: \"Northwind LLC\",\n lineDescription: \"Consulting services\",\n },\n};\n\ntype ProfilePatch = {\n [K in keyof BookiLocaleProfile]?: BookiLocaleProfile[K] extends object\n ? BookiLocaleProfile[K] extends unknown[]\n ? BookiLocaleProfile[K]\n : Partial<BookiLocaleProfile[K]>\n : BookiLocaleProfile[K];\n};\n\n/**\n * A profile for a country Booki does not ship: start from one that does and\n * override what differs. Sections are merged one level deep; lists (such as\n * `tax.codes`) are replaced whole.\n *\n * ```ts\n * const FI = defineProfile(SE_PROFILE, { country: \"FI\", locale: \"fi-FI\", currency: \"EUR\" });\n * <BookiLocaleProvider profiles={{ FI }} defaultCountry=\"FI\">\n * ```\n */\nexport function defineProfile(base: BookiLocaleProfile, patch: ProfilePatch): BookiLocaleProfile {\n const out = { ...base } as Record<string, unknown>;\n for (const [key, value] of Object.entries(patch)) {\n const current = out[key];\n out[key] =\n value && typeof value === \"object\" && !Array.isArray(value) && current && typeof current === \"object\"\n ? { ...(current as object), ...(value as object) }\n : value;\n }\n return out as BookiLocaleProfile;\n}\n\nconst euCommon = {\n bankAccount: { kind: \"iban\" as const, label: \"IBAN\", description: \"International bank account number\" },\n paymentReference: {\n kind: \"memo\" as const,\n label: \"Payment reference\",\n description: \"Invoice or remittance reference\",\n },\n period: { defaultGranularity: \"month\" as const, label: \"Period\" },\n};\n\n/**\n * Starter profiles for Sweden, Denmark, the United Kingdom and Germany:\n * currency, number format, standard VAT rates, IBAN and the company-number\n * check. The labels are English. Treat the VAT codes and account numbers as\n * a starting point and replace them with your own.\n */\nexport const SE_PROFILE = defineProfile(US_PROFILE, {\n ...euCommon,\n country: \"SE\",\n locale: \"sv-SE\",\n currency: \"SEK\",\n tax: {\n label: \"VAT (moms)\",\n defaultPercent: 25,\n codes: [\n { code: \"SE0\", label: \"0% VAT\", percent: 0 },\n { code: \"SE6\", label: \"6% VAT\", percent: 6 },\n { code: \"SE12\", label: \"12% VAT\", percent: 12 },\n { code: \"SE25\", label: \"25% VAT\", percent: 25 },\n ],\n },\n organizationNumber: {\n kind: \"se-orgnr\",\n label: \"Organisationsnummer\",\n description: \"10 digits, Luhn check\",\n placeholder: \"556036-0793\",\n invalid: \"Invalid organisationsnummer\",\n },\n copy: { organizationNumber: \"Organisationsnummer\" },\n demo: { companyName: \"Norrsken AB\" },\n});\n\nexport const DK_PROFILE = defineProfile(US_PROFILE, {\n ...euCommon,\n country: \"DK\",\n locale: \"da-DK\",\n currency: \"DKK\",\n tax: {\n label: \"VAT (moms)\",\n defaultPercent: 25,\n codes: [\n { code: \"DK0\", label: \"0% VAT\", percent: 0 },\n { code: \"DK25\", label: \"25% VAT\", percent: 25 },\n ],\n },\n organizationNumber: {\n kind: \"dk-cvr\",\n label: \"CVR number\",\n description: \"8 digits, mod 11\",\n placeholder: \"10 15 08 17\",\n invalid: \"Invalid CVR number\",\n },\n copy: { organizationNumber: \"CVR number\" },\n demo: { companyName: \"Nordlys ApS\" },\n});\n\nexport const GB_PROFILE = defineProfile(US_PROFILE, {\n ...euCommon,\n country: \"GB\",\n locale: \"en-GB\",\n currency: \"GBP\",\n tax: {\n label: \"VAT\",\n defaultPercent: 20,\n codes: [\n { code: \"GB0\", label: \"0% VAT\", percent: 0 },\n { code: \"GB5\", label: \"5% VAT\", percent: 5 },\n { code: \"GB20\", label: \"20% VAT\", percent: 20 },\n ],\n },\n organizationNumber: {\n kind: \"generic\",\n label: \"Company number\",\n description: \"Companies House number, 8 characters\",\n placeholder: \"01234567\",\n invalid: \"Enter the company number\",\n },\n copy: { organizationNumber: \"Company number\" },\n demo: { companyName: \"Northlight Ltd\" },\n});\n\nexport const DE_PROFILE = defineProfile(US_PROFILE, {\n ...euCommon,\n country: \"DE\",\n locale: \"de-DE\",\n currency: \"EUR\",\n tax: {\n label: \"VAT (USt)\",\n defaultPercent: 19,\n codes: [\n { code: \"DE0\", label: \"0% VAT\", percent: 0 },\n { code: \"DE7\", label: \"7% VAT\", percent: 7 },\n { code: \"DE19\", label: \"19% VAT\", percent: 19 },\n ],\n },\n organizationNumber: {\n kind: \"generic\",\n label: \"Company register number\",\n description: \"Handelsregister number\",\n placeholder: \"HRB 12345\",\n invalid: \"Enter the register number\",\n },\n copy: { organizationNumber: \"Company register number\" },\n demo: { companyName: \"Nordlicht GmbH\" },\n});\n\nexport const BOOKI_PROFILES: Record<string, BookiLocaleProfile> = {\n NO: NO_PROFILE,\n US: US_PROFILE,\n SE: SE_PROFILE,\n DK: DK_PROFILE,\n GB: GB_PROFILE,\n DE: DE_PROFILE,\n};\n\n/** The profile for a country. Throws for a code with no profile, naming the ones that exist. */\nexport function getBookiProfile(country: string, extra: Record<string, BookiLocaleProfile> = {}): BookiLocaleProfile {\n const profile = extra[country] ?? BOOKI_PROFILES[country];\n if (!profile) {\n throw new BookiError(\"locale.no-profile\", {\n country: String(country),\n countries: Object.keys(BOOKI_PROFILES).join(\", \"),\n });\n }\n return profile;\n}\n"],"mappings":";;;;;AAGO,IAAM,aAAiC;AAAA,EAC5C,SAAS;AAAA,EACT,QAAQ;AAAA,EACR,UAAU;AAAA,EACV,aAAa;AAAA,EACb,KAAK;AAAA,IACH,OAAO;AAAA,IACP,gBAAgB;AAAA,IAChB,OAAO;AAAA,MACL,EAAE,MAAM,QAAQ,OAAO,UAAU,SAAS,EAAE;AAAA,MAC5C,EAAE,MAAM,SAAS,OAAO,WAAW,SAAS,GAAG;AAAA,MAC/C,EAAE,MAAM,SAAS,OAAO,WAAW,SAAS,GAAG;AAAA,IACjD;AAAA,EACF;AAAA,EACA,aAAa;AAAA,IACX,MAAM;AAAA,IACN,OAAO;AAAA,IACP,aAAa;AAAA,EACf;AAAA,EACA,kBAAkB;AAAA,IAChB,MAAM;AAAA,IACN,OAAO;AAAA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