@nodaro/sdk 2.47.0 → 2.51.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 (88) hide show
  1. package/dist/{chunk-KBHDUHKM.js → chunk-2SQ7V6EX.js} +2 -2
  2. package/dist/chunk-2SQ7V6EX.js.map +1 -0
  3. package/dist/{chunk-FIMBPKIH.cjs → chunk-4BAHF762.cjs} +43 -2
  4. package/dist/chunk-4BAHF762.cjs.map +1 -0
  5. package/dist/chunk-6FZN3QQO.cjs +146 -0
  6. package/dist/chunk-6FZN3QQO.cjs.map +1 -0
  7. package/dist/{chunk-5MOJSYHI.js → chunk-7QK2NXJA.js} +43 -2
  8. package/dist/chunk-7QK2NXJA.js.map +1 -0
  9. package/dist/{chunk-JTAW54UM.js → chunk-AEUPH7EE.js} +2 -2
  10. package/dist/{chunk-34PU2DAT.cjs.map → chunk-AEUPH7EE.js.map} +1 -1
  11. package/dist/{chunk-DIF7A5OH.cjs → chunk-E5MJK3W5.cjs} +2 -2
  12. package/dist/chunk-E5MJK3W5.cjs.map +1 -0
  13. package/dist/{chunk-I7AHLDXV.js → chunk-EC6MC46Y.js} +10 -10
  14. package/dist/{chunk-I7AHLDXV.js.map → chunk-EC6MC46Y.js.map} +1 -1
  15. package/dist/{chunk-NP6KDFIJ.cjs → chunk-HPSENMVN.cjs} +18 -18
  16. package/dist/{chunk-NP6KDFIJ.cjs.map → chunk-HPSENMVN.cjs.map} +1 -1
  17. package/dist/{chunk-XKDVEQVD.cjs → chunk-LTZKNAXM.cjs} +2 -2
  18. package/dist/chunk-LTZKNAXM.cjs.map +1 -0
  19. package/dist/{chunk-OWG3XAHQ.js → chunk-OCRUDBPG.js} +10 -6
  20. package/dist/chunk-OCRUDBPG.js.map +1 -0
  21. package/dist/{chunk-MYTMNPCP.cjs → chunk-OMX7JBGY.cjs} +3 -3
  22. package/dist/{chunk-MYTMNPCP.cjs.map → chunk-OMX7JBGY.cjs.map} +1 -1
  23. package/dist/{chunk-7LTVS75S.cjs → chunk-P6AM42UB.cjs} +2 -2
  24. package/dist/chunk-P6AM42UB.cjs.map +1 -0
  25. package/dist/{chunk-34PU2DAT.cjs → chunk-Q45PC4YD.cjs} +2 -2
  26. package/dist/chunk-Q45PC4YD.cjs.map +1 -0
  27. package/dist/{chunk-PQHZUWSL.js → chunk-THLTFB6I.js} +2 -2
  28. package/dist/chunk-THLTFB6I.js.map +1 -0
  29. package/dist/{chunk-GDDV5U32.cjs → chunk-TY2S25W5.cjs} +10 -6
  30. package/dist/chunk-TY2S25W5.cjs.map +1 -0
  31. package/dist/chunk-WYYDWJFF.js +144 -0
  32. package/dist/chunk-WYYDWJFF.js.map +1 -0
  33. package/dist/{chunk-FCYN4N3M.js → chunk-XISHBW5I.js} +3 -3
  34. package/dist/{chunk-FCYN4N3M.js.map → chunk-XISHBW5I.js.map} +1 -1
  35. package/dist/{chunk-XILR6TFO.js → chunk-YXVMQEJX.js} +2 -2
  36. package/dist/chunk-YXVMQEJX.js.map +1 -0
  37. package/dist/entries/billing.cjs +2 -2
  38. package/dist/entries/billing.d.cts +202 -3
  39. package/dist/entries/billing.d.ts +202 -3
  40. package/dist/entries/billing.js +1 -1
  41. package/dist/entries/cast-swap.cjs +2 -2
  42. package/dist/entries/cast-swap.d.cts +34 -31
  43. package/dist/entries/cast-swap.d.ts +34 -31
  44. package/dist/entries/cast-swap.js +1 -1
  45. package/dist/entries/client.cjs +14 -14
  46. package/dist/entries/client.js +9 -9
  47. package/dist/entries/core.cjs +5 -5
  48. package/dist/entries/core.js +1 -1
  49. package/dist/entries/credits.cjs +2 -2
  50. package/dist/entries/credits.d.cts +179 -1
  51. package/dist/entries/credits.d.ts +179 -1
  52. package/dist/entries/credits.js +1 -1
  53. package/dist/entries/jobs.cjs +2 -2
  54. package/dist/entries/jobs.d.cts +18 -7
  55. package/dist/entries/jobs.d.ts +18 -7
  56. package/dist/entries/jobs.js +1 -1
  57. package/dist/entries/node-presets.cjs +2 -2
  58. package/dist/entries/node-presets.d.cts +6 -0
  59. package/dist/entries/node-presets.d.ts +6 -0
  60. package/dist/entries/node-presets.js +1 -1
  61. package/dist/entries/trash.cjs +2 -2
  62. package/dist/entries/trash.d.cts +4 -1
  63. package/dist/entries/trash.d.ts +4 -1
  64. package/dist/entries/trash.js +1 -1
  65. package/dist/entries/trends.cjs +2 -2
  66. package/dist/entries/trends.d.cts +22 -13
  67. package/dist/entries/trends.d.ts +22 -13
  68. package/dist/entries/trends.js +1 -1
  69. package/dist/index.cjs +22 -22
  70. package/dist/index.d.cts +2 -2
  71. package/dist/index.d.ts +2 -2
  72. package/dist/index.js +9 -9
  73. package/package.json +3 -3
  74. package/dist/chunk-5MOJSYHI.js.map +0 -1
  75. package/dist/chunk-7LTVS75S.cjs.map +0 -1
  76. package/dist/chunk-DIF7A5OH.cjs.map +0 -1
  77. package/dist/chunk-FIMBPKIH.cjs.map +0 -1
  78. package/dist/chunk-GDDV5U32.cjs.map +0 -1
  79. package/dist/chunk-J4WFSKY6.js +0 -50
  80. package/dist/chunk-J4WFSKY6.js.map +0 -1
  81. package/dist/chunk-JTAW54UM.js.map +0 -1
  82. package/dist/chunk-KBHDUHKM.js.map +0 -1
  83. package/dist/chunk-NGKODS3J.cjs +0 -52
  84. package/dist/chunk-NGKODS3J.cjs.map +0 -1
  85. package/dist/chunk-OWG3XAHQ.js.map +0 -1
  86. package/dist/chunk-PQHZUWSL.js.map +0 -1
  87. package/dist/chunk-XILR6TFO.js.map +0 -1
  88. package/dist/chunk-XKDVEQVD.cjs.map +0 -1
@@ -17,5 +17,5 @@ var TrashResource = class {
17
17
  };
18
18
 
19
19
  export { TrashResource };
20
- //# sourceMappingURL=chunk-KBHDUHKM.js.map
21
- //# sourceMappingURL=chunk-KBHDUHKM.js.map
20
+ //# sourceMappingURL=chunk-2SQ7V6EX.js.map
21
+ //# sourceMappingURL=chunk-2SQ7V6EX.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/resources/trash.ts"],"names":[],"mappings":";AA4DO,IAAM,gBAAN,MAAoB;AAAA,EACzB,YAAoB,MAAA,EAA0B;AAA1B,IAAA,IAAA,CAAA,MAAA,GAAA,MAAA;AAAA,EAA2B;AAAA,EAA3B,MAAA;AAAA;AAAA,EAGpB,IAAA,CAAK,MAAA,GAA0B,EAAC,EAAuB;AACrD,IAAA,MAAM,QAAgC,EAAC;AACvC,IAAA,IAAI,MAAA,CAAO,SAAA,EAAW,KAAA,CAAM,SAAA,GAAY,MAAA,CAAO,SAAA;AAC/C,IAAA,IAAI,MAAA,CAAO,IAAA,EAAM,KAAA,CAAM,IAAA,GAAO,MAAA,CAAO,IAAA;AACrC,IAAA,IAAI,MAAA,CAAO,IAAA,KAAS,MAAA,EAAW,KAAA,CAAM,OAAO,OAAO,MAAA,CAAO,IAAA,KAAS,QAAA,GAAW,MAAA,CAAO,IAAA,GAAO,MAAA,CAAO,IAAA,CAAK,KAAK,GAAG,CAAA;AAChH,IAAA,IAAI,OAAO,KAAA,KAAU,MAAA,QAAiB,KAAA,GAAQ,MAAA,CAAO,OAAO,KAAK,CAAA;AACjE,IAAA,IAAI,MAAA,CAAO,MAAA,EAAQ,KAAA,CAAM,MAAA,GAAS,MAAA,CAAO,MAAA;AACzC,IAAA,OAAO,KAAK,MAAA,CAAO,OAAA,CAAQ,OAAO,WAAA,EAAa,EAAE,OAAO,CAAA;AAAA,EAC1D;AACF","file":"chunk-2SQ7V6EX.js","sourcesContent":["import type { NodaroClientCore } from \"../core.js\"\nimport type { Job } from \"./jobs.js\"\n\n/** The session a removed item was removed from — restore it there with\n * `client.sessions.restoreItem(session.id, job.id)`. */\nexport interface TrashSession {\n id: string\n /** `null` = untitled; a UI may fall back to the first prompt. */\n title: string | null\n /** The session's project, or `null` when it has none. */\n projectId: string | null\n}\n\n/**\n * One entry of the Trash: an item removed from a session, or a deleted job.\n * Narrow on `kind`.\n *\n * - `removed`: kept until restored (`client.sessions.restoreItem(session.id, job.id)`)\n * or deleted for good (`client.sessions.removeItem(session.id, job.id, { forever: true })`).\n * - `deleted`: kept until `purgeAt` (30 days after `deletedAt`), then deleted for\n * good (a copy saved to the Library stays); restore with `client.jobs.restore(job.id)`, or delete\n * now with `client.jobs.delete(job.id, { forever: true })`.\n *\n * A removed item whose job was also deleted is listed once, as the deleted job.\n */\nexport type TrashEntry =\n | { kind: \"removed\"; removedAt: string; session: TrashSession; job: Job }\n | { kind: \"deleted\"; deletedAt: string; purgeAt: string; job: Job }\n\nexport interface ListTrashParams {\n /**\n * A project's id: its sessions' removed items, and deleted jobs a session of\n * it held. `\"none\"`: the sessions with no project, and General.\n */\n projectId?: string | \"none\"\n /**\n * A creation tool (e.g. `\"create-image\"`): what a session of that tool holds\n * or held. A job no session ever held has no tool and is left out — filter by\n * `type` alone to include it.\n */\n tool?: string\n /**\n * The job's `input_data.type` (`\"generate-image\"`, …), like `client.jobs.list`.\n * One value or several (up to 20). Every filter combines with AND.\n */\n type?: string | readonly string[]\n /** Page size, 1–100 (server default 50). */\n limit?: number\n /** The previous page's `next`. */\n cursor?: string\n}\n\nexport interface TrashPage {\n /** A page may hold fewer than `limit` entries and still carry a `next`; page on `next`. */\n data: TrashEntry[]\n /** Pass back as `cursor` for the next page; `null` on the last one. */\n next: string | null\n}\n\n/** Your Trash (`GET /v1/trash`): one entry beside General in a creation tool's sessions list. */\nexport class TrashResource {\n constructor(private client: NodaroClientCore) {}\n\n /** One newest-first page of the Trash, on your side of the workspace line. */\n list(params: ListTrashParams = {}): Promise<TrashPage> {\n const query: Record<string, string> = {}\n if (params.projectId) query.projectId = params.projectId\n if (params.tool) query.tool = params.tool\n if (params.type !== undefined) query.type = typeof params.type === \"string\" ? params.type : params.type.join(\",\")\n if (params.limit !== undefined) query.limit = String(params.limit)\n if (params.cursor) query.cursor = params.cursor\n return this.client.request(\"GET\", \"/v1/trash\", { query })\n }\n}\n"]}
@@ -31,6 +31,47 @@ var CreditsResource = class {
31
31
  query: { limit: options.limit, cursor: options.cursor }
32
32
  });
33
33
  }
34
+ /**
35
+ * `GET /v1/credits/usage-summary` → the period's credit usage summed the
36
+ * way a billing screen draws it: totals, the spend by model and by
37
+ * category, a series over time (`bucket`: day, week or month, no holes),
38
+ * and the spend by session and by workflow. The last 30 days unless
39
+ * `from` / `to` say otherwise; a period of at most a year (400 beyond).
40
+ * Cloud-only route: a self-hosted instance answers 404.
41
+ */
42
+ async usageSummary(options = {}) {
43
+ const res = await this.client.request("GET", "/v1/credits/usage-summary", {
44
+ query: { from: options.from, to: options.to, bucket: options.bucket }
45
+ });
46
+ return res.data;
47
+ }
48
+ /**
49
+ * `GET /v1/credits/history` → one page of every movement of the balance,
50
+ * newest first — runs, purchases, grants, refunds, adjustments, expiries —
51
+ * each with the balance after it; a job's reserve row carries its model,
52
+ * its `charge` (the settled charge, the hold while the run is open, `0`
53
+ * once refunded — read that for spend, not `amount`) and its job. Filter by
54
+ * `kind`, `model`, `from` / `to` and `q`; pass the page's `nextCursor` (an
55
+ * opaque string) as `cursor` for the next page (`null` at the end).
56
+ * Cloud-only route: a self-hosted instance answers 404.
57
+ */
58
+ history(options = {}) {
59
+ const { limit, cursor, ...filters } = options;
60
+ return this.client.request("GET", "/v1/credits/history", {
61
+ query: { limit, cursor, ...filters }
62
+ });
63
+ }
64
+ /**
65
+ * `GET /v1/credits/history?format=csv` → the whole filtered history as a
66
+ * CSV file (the same fields as {@link history}, one line per movement,
67
+ * newest first), at most 5,000 rows — the last line says when it was cut.
68
+ * Hand the text to the person as `credit-history.csv`.
69
+ */
70
+ exportHistory(filters = {}) {
71
+ return this.client.requestText("GET", "/v1/credits/history", {
72
+ query: { ...filters, format: "csv" }
73
+ });
74
+ }
34
75
  /**
35
76
  * `POST /v1/credits/model-costs` → per-identifier credit cost, for editor
36
77
  * cost previews. Capped at the first {@link MODEL_COSTS_LIMIT} identifiers
@@ -104,5 +145,5 @@ var CreditsResource = class {
104
145
  };
105
146
 
106
147
  exports.CreditsResource = CreditsResource;
107
- //# sourceMappingURL=chunk-FIMBPKIH.cjs.map
108
- //# sourceMappingURL=chunk-FIMBPKIH.cjs.map
148
+ //# sourceMappingURL=chunk-4BAHF762.cjs.map
149
+ //# sourceMappingURL=chunk-4BAHF762.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/resources/credits.ts"],"names":[],"mappings":";;;AAwXA,IAAM,iBAAA,GAAoB,EAAA;AAEnB,IAAM,kBAAN,MAAsB;AAAA,EAC3B,YAAoB,MAAA,EAA0B;AAA1B,IAAA,IAAA,CAAA,MAAA,GAAA,MAAA;AAAA,EAA2B;AAAA,EAA3B,MAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOpB,MAAM,OAAA,GAAgC;AACpC,IAAA,MAAM,GAAA,GAAM,MAAM,IAAA,CAAK,MAAA,CAAO,OAAA;AAAA,MAC5B,KAAA;AAAA,MACA;AAAA,KACF;AACA,IAAA,OAAO,GAAA,CAAI,IAAA;AAAA,EACb;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EASA,YAAA,CAAa,OAAA,GAAqC,EAAC,EAAoC;AACrF,IAAA,OAAO,IAAA,CAAK,MAAA,CAAO,OAAA,CAAgC,KAAA,EAAO,0BAAA,EAA4B;AAAA,MACpF,OAAO,EAAE,KAAA,EAAO,QAAQ,KAAA,EAAO,MAAA,EAAQ,QAAQ,MAAA;AAAO,KACvD,CAAA;AAAA,EACH;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAUA,MAAM,YAAA,CAAa,OAAA,GAA+B,EAAC,EAA0B;AAC3E,IAAA,MAAM,MAAM,MAAM,IAAA,CAAK,MAAA,CAAO,OAAA,CAAgC,OAAO,2BAAA,EAA6B;AAAA,MAChG,KAAA,EAAO,EAAE,IAAA,EAAM,OAAA,CAAQ,IAAA,EAAM,IAAI,OAAA,CAAQ,EAAA,EAAI,MAAA,EAAQ,OAAA,CAAQ,MAAA;AAAO,KACrE,CAAA;AACD,IAAA,OA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A;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAiBA,iBAAA,CAAkB,KAAA,GAAgC,EAAC,EAAqC;AACtF,IAAA,OAAO,IAAA,CAAK,MAAA,CAAO,OAAA,CAAiC,MAAA,EAAQ,iCAAA,EAAmC;AAAA,MAC7F,IAAA,EAAM;AAAA,KACP,CAAA;AAAA,EACH;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAYA,oBAAA,GAAwD;AACtD,IAAA,OAAO,IAAA,CAAK,MAAA,CAAO,OAAA,CAAgC,MAAA,EAAQ,gCAAgC,CAAA;AAAA,EAC7F;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAUF","file":"chunk-4BAHF762.cjs","sourcesContent":["import type { NodaroClientCore } from \"../core.js\"\n\n/**\n * Authenticated user's credit balance — the shape of `GET /v1/user/credits`'s\n * `data` field. Mirrors the canonical `UserBalance` from the backend billing\n * module (`backend/src/ee/billing/credits.ts`), the source of truth: keep this\n * in sync if that interface changes.\n */\nexport interface UserBalance {\n total: number\n subscription: number\n topup: number\n dailySpent: number\n dailyLimit: number | null\n monthlyAllocation: number\n /** Stored billing tier. Display should prefer `effectiveTier`. */\n tier: string\n /** Derived entitlement tier: \"payg\" when stored-free with purchased credits. */\n effectiveTier: string\n features: Record<string, unknown>\n periodEnd: string | null\n /** Credits earned for app usage (free tier only — earned by running flows). */\n appCreditsAllowance: number\n /** Present when a deployment uses an external shared wallet. Raw credits;\n * null means unavailable. Do not substitute the personal `total` balance. */\n externalWallet?: { available: number | null }\n /**\n * Where the account's free signup grant stands. `\"withheld\"` means the\n * account works but the grant did not land — show the activation path.\n * Absent where the deployment has no signup grant.\n */\n freeGrantState?: FreeGrantState\n /**\n * Present only with `freeGrantState: \"withheld\"`, when the claim showed no\n * browser signals at all: the app may say \"free credits need a regular\n * browser — reload\", because a reload in one judges the account again.\n */\n freeGrantNotice?: \"browser_unmeasured\"\n /**\n * The welcome-credits opt-in. PRESENT only while the deployment has the\n * offer switched on — absent means \"no popup, no banner, no block\".\n */\n welcomeOffer?: WelcomeOfferState\n}\n\n/** Where an account's free signup grant stands. */\nexport type FreeGrantState = \"unclaimed\" | \"granted\" | \"withheld\" | \"revoked\"\n\n/** `UserBalance.welcomeOffer` — what an app needs to show the welcome offer. */\nexport interface WelcomeOfferState {\n /** The one-time popup was already shown (see `markWelcomeOfferSeen`). */\n popupSeen: boolean\n /**\n * The account already has its credits (granted elsewhere) but still owes\n * the email consent: the web apps block creation until it is given — the\n * claim records it.\n */\n consentPending: boolean\n /** The credits a claim grants. Name this figure in the offer; never hard-code it. */\n credits: number\n}\n\n/** What `claimWelcomeOffer` sends: the browser signals plus the app answering. */\nexport interface WelcomeOfferClaimInput extends SignupKeys {\n /**\n * The answering app's slug (lowercase letters, digits and `-`, up to 40\n * characters), recorded with the consent. A value outside that grammar is\n * stored as absent, never refused.\n */\n sourceApp?: string\n /**\n * The interface language the user answered in — the id of a language Nodaro\n * ships, such as `\"en\"`, `\"ja\"` or `\"pt-BR\"`. Matched exactly and\n * case-sensitively: `\"en-US\"` or `\"pt-br\"` is stored as absent, never refused.\n * Recorded with the consent as the language of the LATEST consent: a later\n * \"yes\" in another language replaces it.\n */\n locale?: string\n}\n\n/** The answer of `POST /v1/credits/welcome-offer/claim`. */\nexport interface WelcomeOfferClaimResult {\n /** The email consent is recorded. */\n consent: \"granted\"\n /** Where the free grant stands after the claim — `\"withheld\"` when the abuse gate refused it. */\n grant: FreeGrantState\n /** The grant's figure. A grant tops the subscription credits UP TO it (it is not added on top), so a claim that lands it leaves the subscription credits at no less than this. */\n credits: number\n}\n\n/** The answer of `POST /v1/credits/welcome-offer/seen`. */\nexport interface WelcomeOfferSeenResult {\n ok: true\n}\n\n/**\n * Result of `POST /v1/credits/model-costs` — a batch cost lookup for editor\n * cost previews. `data` maps each priced identifier → its credit cost.\n *\n * Per-model fault isolation (the route runs the lookups under\n * `Promise.allSettled`): identifiers with no pricing row are reported in\n * `missing` (undisplayable until an operator seeds a price) and lookup\n * failures in `errors`, instead of failing the whole batch. Callers typically\n * render `'—'` for any identifier that lands in `missing`. The hard-fail\n * policy still triggers at reservation time when the user actually runs the\n * node — this preview lookup is intentionally lenient.\n */\nexport interface ModelCostsResult {\n data: Record<string, number>\n missing: string[]\n errors: string[]\n /**\n * Why each identifier in `errors` has no price — today only\n * `llm_model_unpriced`: a metered LLM price key whose model has no rate on\n * the lane it would be served on (it cannot be run). Omitted when `errors`\n * is empty.\n */\n errorCodes?: Record<string, ModelCostError>\n /**\n * The identifiers in `data` whose figure is an ESTIMATE, not a fixed price:\n * metered LLM price keys (`llmPriceKey` from `@nodaro/shared/llm-models`,\n * `<feature>:<model>[:direct]`), charged on what the call actually uses.\n * Show these as `≈N`. Omitted when there are none, so a batch of fixed ids\n * answers exactly as it always has. A metered key that lands in `missing`\n * instead means the server is not pricing LLM calls per model — show no\n * price for it.\n */\n estimates?: string[]\n}\n\n/** {@link ModelCostsResult.errorCodes} — why an identifier has no price. */\nexport interface ModelCostError {\n /** Today only `llm_model_unpriced`; open to codes a newer server may add. */\n code: \"llm_model_unpriced\" | (string & {})\n /** A sentence to show the user. */\n message: string\n}\n\n/**\n * Result of `GET /v1/credits/model-cost?model=<id>` (`data`): the credits one\n * identifier is charged. `estimate: true` marks a metered LLM price key's\n * figure as an estimate (show it as `≈N`); such an answer is never cached.\n */\nexport interface ModelCostResult {\n model: string\n creditCost: number\n estimate?: true\n}\n\n/**\n * The two browser signals a claim reports — SHA-256 hex digests computed by\n * `@nodaro/sdk/signup-signals` (`collectSignupKeys`). Either may be absent:\n * a browser that cannot be measured still claims, and the server treats the\n * absence as what it is. Any other value is stored as absent server-side.\n */\nexport interface SignupKeys {\n browserKey?: string\n deviceKey?: string\n}\n\n/** The answer of `POST /v1/credits/claim-signup-grant`. */\nexport interface SignupGrantClaimResult {\n /** Where the account's free grant stands after this call. */\n state: FreeGrantState\n /** True only when THIS call moved the credits — a repeat is `false` with the same state. */\n granted: boolean\n}\n\n/**\n * One row of `GET /v1/credits/transactions` — a run's reservation and how it\n * settled.\n *\n * Which amount to read: a run first HOLDS credits and is then settled — charged\n * all or part of the hold, the rest returned. `credits_charged` is what the run\n * cost (`null` while the hold is still open, `0` once refunded); sum it for\n * spend. `credits_reserved` is the hold, which never changes. `credits_used`\n * is the same hold under its original name, kept for existing integrations.\n */\nexport interface CreditTransaction {\n id: string\n /** ISO-8601. Also the paging cursor: pass the last row's value as `cursor`. */\n created_at: string\n /** Settled charge; `null` while `status` is `\"reserved\"`, `0` when refunded. */\n credits_charged: number | null\n /** The hold taken when the run was accepted. */\n credits_reserved: number | null\n /** The hold, under its original name. Prefer `credits_charged`. */\n credits_used: number | null\n /** The model or operation the credits were for. */\n action: string | null\n provider: string | null\n /** Reservation lifecycle: `\"reserved\"`, `\"committed\"` or `\"refunded\"`. */\n status: string | null\n /** The caller's own billing details for the run (model, which pool paid, …). */\n metadata: Record<string, unknown>\n /** `\"workspace\"` when a class or team budget paid, not your balance. */\n payer: \"user\" | \"workspace\"\n workspaceId: string | null\n}\n\n/** A page of {@link CreditTransaction}s, newest first. */\nexport interface CreditTransactionsPage {\n data: CreditTransaction[]\n /** Pass as `cursor` for the next page; `null` when there are no more rows. */\n nextCursor: string | null\n}\n\nexport interface CreditTransactionsOptions {\n /** Rows per page, 1–50 (server default 20). */\n limit?: number\n /** The `nextCursor` of the previous page. */\n cursor?: string\n}\n\n/** How `credits.usageSummary()` groups the series over time. */\nexport type UsageSummaryBucket = \"day\" | \"week\" | \"month\"\n\nexport interface UsageSummaryOptions {\n /** An ISO-8601 timestamp, or a date alone (`\"2026-10-01\"`: that whole UTC day), inclusive; default the last 30 days up to now. A period of at most a year. */\n from?: string\n to?: string\n /** Default `\"day\"`. Buckets are UTC. */\n bucket?: UsageSummaryBucket\n}\n\nexport interface UsageSummaryTotals {\n /** Credits spent on runs in the period: each run's charge (a running hold counts; a refunded run does not). */\n used: number\n /** Credits bought: packs, loads, subscription grants. */\n purchased: number\n /** Credits granted free, net: sign-up and admin adjustments, a grant taken back subtracted. */\n granted: number\n /** Credits given back for a refunded run or by Stripe (a hold released when a run settled below it is not a refund). */\n refunded: number\n /** Runs that were charged or are still running. */\n runs: number\n /** `used / runs`, one decimal; 0 with no runs. */\n avgPerRun: number\n}\n\nexport interface UsageByModel {\n model: string\n provider: string | null\n credits: number\n runs: number\n /** Of `totals.used`, 0–1. */\n share: number\n}\n\nexport interface UsageByCategory {\n /** `\"image\"`, `\"video\"`, `\"audio\"` or `\"other\"`. */\n category: string\n credits: number\n runs: number\n}\n\nexport interface UsageOverTime {\n /** The bucket's first day in UTC (`\"2026-10-26\"`; a week by its Monday; a month as `\"2026-10\"`). The first bucket of a period may be a partial week or month. */\n bucket: string\n used: number\n purchased: number\n runs: number\n}\n\n/** The spend of one session or one workflow. */\nexport interface UsageByGroup {\n id: string\n /** The session's title or the workflow's name; `null` when it has none or is gone. */\n name: string | null\n /** The tool the session belongs to; `null` on a workflow. */\n tool: string | null\n credits: number\n runs: number\n /** The models used, by spend. */\n models: string[]\n /** ISO-8601: the latest run. */\n lastAt: string\n}\n\n/** The answer of `credits.usageSummary()`. */\nexport interface UsageSummary {\n period: { from: string; to: string; bucket: UsageSummaryBucket }\n totals: UsageSummaryTotals\n /** The model with the most spend; `null` with no runs. */\n mostUsed: UsageByModel | null\n /** By spend. */\n byModel: UsageByModel[]\n byCategory: UsageByCategory[]\n /** Every bucket of the period, empty ones included, oldest first. */\n overTime: UsageOverTime[]\n bySession: UsageByGroup[]\n byWorkflow: UsageByGroup[]\n /** A read hit the server's row cap: the figures under-report; narrow the period. */\n truncated: boolean\n /** A side read failed on the server (the jobs, or a session's or workflow's name): a grouping is missing or unnamed; the totals are whole. */\n partial: boolean\n}\n\n/** What a movement of the balance was; `app` is credits earned from, or paid for, a published app. */\nexport type CreditHistoryKind = \"usage\" | \"purchase\" | \"grant\" | \"refund\" | \"app\" | \"adjustment\" | \"expiry\"\n\n/** The job behind a usage row of {@link CreditHistoryEntry}. */\nexport interface CreditHistoryJob {\n id: string\n /** The node type that ran (`generate-image`, `image-to-video`, …); `null` when the job is gone. */\n type: string | null\n status: string | null\n startedAt: string | null\n completedAt: string | null\n /** From start to completion; `null` until it completes. */\n durationMs: number | null\n workflowId: string | null\n sessionId: string | null\n}\n\n/** One movement of the balance (`credits.history()`). */\nexport interface CreditHistoryEntry {\n id: string\n /** ISO-8601. Also the paging cursor. */\n at: string\n kind: CreditHistoryKind\n /** The ledger's own word: `usage`, `one_time_purchase`, `subscription_renewal`, `signup_grant`, `refund`, `admin_adjustment`, `expiry`, … */\n source: string\n /** The movement, signed: a run's hold negative, a purchase positive. */\n amount: number\n /** The balance right after this movement. */\n balanceAfter: number\n /** Which pool moved; `\"mixed\"` when both did. */\n pool: \"subscription\" | \"topup\" | \"mixed\"\n description: string | null\n /** The model that ran, on a row with a job; `null` otherwise. */\n model: string | null\n provider: string | null\n /**\n * The job's charge, on its reserve row only (the hold taken when the run\n * was accepted): the settled charge, the hold while the run is open, `0`\n * once refunded. `null` on every other row — a refund, a metered overrun\n * line, a purchase — so summing it over a list counts each job once. Read\n * this for spend, not `amount`.\n */\n charge: number | null\n /** The run's credit status (`\"reserved\"`, `\"committed\"` or `\"refunded\"`), beside `charge`; `null` elsewhere. */\n status: string | null\n /** On a row with a job; `type` and the rest `null` when the job is gone or not the person's. */\n job: CreditHistoryJob | null\n /** Stripe's hosted receipt, on a purchase that has one. */\n receiptUrl: string | null\n}\n\n/** A page of {@link CreditHistoryEntry}, newest first. */\nexport interface CreditHistoryPage {\n data: CreditHistoryEntry[]\n /** Pass as `cursor` for the next page; `null` when there are no more rows. */\n nextCursor: string | null\n}\n\n/** What narrows the history. */\nexport interface CreditHistoryFilters {\n kind?: CreditHistoryKind\n /** A model identifier: only runs of that model. */\n model?: string\n /** ISO-8601 bounds on `at`, inclusive. */\n from?: string\n to?: string\n /** Words looked for in the description, case-insensitively. */\n q?: string\n}\n\nexport interface CreditHistoryOptions extends CreditHistoryFilters {\n /** Rows per page, 1–100 (server default 50). */\n limit?: number\n /** The `nextCursor` of the previous page, as given (opaque; another string is refused with 400). */\n cursor?: string\n}\n\n/** Max identifiers per `model-costs` batch — the route caps the request at 50. */\nconst MODEL_COSTS_LIMIT = 50\n\nexport class CreditsResource {\n constructor(private client: NodaroClientCore) {}\n\n /**\n * `GET /v1/user/credits` → the authenticated user's credit balance and tier\n * info. Throws `UnauthorizedError` (401) when signed out, and the SDK's\n * other typed errors on the usual statuses.\n */\n async balance(): Promise<UserBalance> {\n const res = await this.client.request<{ data: UserBalance }>(\n \"GET\",\n \"/v1/user/credits\",\n )\n return res.data\n }\n\n /**\n * `GET /v1/credits/transactions` → one page of the caller's credit\n * transactions, newest first, with `nextCursor` for the next page (`null`\n * at the end). Read `credits_charged` for what each run cost — it can be\n * below the hold (`credits_reserved`) and is `null` while the hold is open.\n * Cloud-only route: a self-hosted instance answers 404.\n */\n transactions(options: CreditTransactionsOptions = {}): Promise<CreditTransactionsPage> {\n return this.client.request<CreditTransactionsPage>(\"GET\", \"/v1/credits/transactions\", {\n query: { limit: options.limit, cursor: options.cursor },\n })\n }\n\n /**\n * `GET /v1/credits/usage-summary` → the period's credit usage summed the\n * way a billing screen draws it: totals, the spend by model and by\n * category, a series over time (`bucket`: day, week or month, no holes),\n * and the spend by session and by workflow. The last 30 days unless\n * `from` / `to` say otherwise; a period of at most a year (400 beyond).\n * Cloud-only route: a self-hosted instance answers 404.\n */\n async usageSummary(options: UsageSummaryOptions = {}): Promise<UsageSummary> {\n const res = await this.client.request<{ data: UsageSummary }>(\"GET\", \"/v1/credits/usage-summary\", {\n query: { from: options.from, to: options.to, bucket: options.bucket },\n })\n return res.data\n }\n\n /**\n * `GET /v1/credits/history` → one page of every movement of the balance,\n * newest first — runs, purchases, grants, refunds, adjustments, expiries —\n * each with the balance after it; a job's reserve row carries its model,\n * its `charge` (the settled charge, the hold while the run is open, `0`\n * once refunded — read that for spend, not `amount`) and its job. Filter by\n * `kind`, `model`, `from` / `to` and `q`; pass the page's `nextCursor` (an\n * opaque string) as `cursor` for the next page (`null` at the end).\n * Cloud-only route: a self-hosted instance answers 404.\n */\n history(options: CreditHistoryOptions = {}): Promise<CreditHistoryPage> {\n const { limit, cursor, ...filters } = options\n return this.client.request<CreditHistoryPage>(\"GET\", \"/v1/credits/history\", {\n query: { limit, cursor, ...filters },\n })\n }\n\n /**\n * `GET /v1/credits/history?format=csv` → the whole filtered history as a\n * CSV file (the same fields as {@link history}, one line per movement,\n * newest first), at most 5,000 rows — the last line says when it was cut.\n * Hand the text to the person as `credit-history.csv`.\n */\n exportHistory(filters: CreditHistoryFilters = {}): Promise<string> {\n return this.client.requestText(\"GET\", \"/v1/credits/history\", {\n query: { ...filters, format: \"csv\" },\n })\n }\n\n /**\n * `POST /v1/credits/model-costs` → per-identifier credit cost, for editor\n * cost previews. Capped at the first {@link MODEL_COSTS_LIMIT} identifiers\n * (the route's request limit). Preserves the `{ data, missing, errors }`\n * fault-isolation shape verbatim, plus `estimates` / `errorCodes` when a\n * metered LLM price key was asked (see {@link ModelCostsResult}).\n */\n modelCosts(ids: string[]): Promise<ModelCostsResult> {\n return this.client.request<ModelCostsResult>(\"POST\", \"/v1/credits/model-costs\", {\n body: { models: ids.slice(0, MODEL_COSTS_LIMIT) },\n })\n }\n\n /**\n * `POST /v1/credits/claim-signup-grant` → claims the account's free signup\n * grant, once, with the browser signals of the page making the claim.\n *\n * Call it once per page load as soon as the session is known, and never\n * wait on it for rendering: it is idempotent (a decided account answers\n * with its state and `granted: false`), it costs the user nothing when it\n * fails (the next load asks again), and the signals are what make the\n * claim worth sending — collect them with `collectSignupKeys()` from\n * `@nodaro/sdk/signup-signals` and pass whatever came back, `{}` included.\n * Cloud-only route: a self-hosted instance answers 404.\n */\n claimSignupGrant(keys: SignupKeys = {}): Promise<SignupGrantClaimResult> {\n return this.client.request<SignupGrantClaimResult>(\"POST\", \"/v1/credits/claim-signup-grant\", {\n body: keys,\n })\n }\n\n /**\n * `POST /v1/credits/welcome-offer/claim` → the user's \"yes\" to the welcome\n * offer, as ONE server action: the marketing-email consent is recorded,\n * then the free signup grant is claimed with that consent. The abuse gate\n * still decides — consent is necessary, not sufficient — so read `grant`:\n * `\"granted\"` (the grant has landed: this call topped the subscription credits up to `credits` — not added on top — or it had landed before), `\"withheld\"` (refused), `\"revoked\"` (taken back earlier; nothing moves), `\"unclaimed\"` (nothing moved — treat as a failure and let the user retry).\n * Pass the browser signals from `collectSignupKeys()` and your app's slug.\n *\n * **Browser session only.** Usable from a first-party web app signed in\n * with a Supabase session (the consent is a person's choice in a browser);\n * an API key or OAuth app token is refused with 403. 409\n * `welcome_offer_disabled` while the deployment has the offer off — show\n * it only when `balance().welcomeOffer` is present. Cloud-only route: a\n * self-hosted instance answers 404.\n */\n claimWelcomeOffer(input: WelcomeOfferClaimInput = {}): Promise<WelcomeOfferClaimResult> {\n return this.client.request<WelcomeOfferClaimResult>(\"POST\", \"/v1/credits/welcome-offer/claim\", {\n body: input,\n })\n }\n\n /**\n * `POST /v1/credits/welcome-offer/seen` → records that the one-time welcome\n * popup was shown, so `balance().welcomeOffer.popupSeen` turns true on every\n * app. Idempotent (the first stamp wins); a failed call only means the popup\n * may show once more, so callers usually ignore errors.\n *\n * **Browser session only**, like {@link claimWelcomeOffer}: 403 for an API\n * key or OAuth app token, 409 `welcome_offer_disabled` while the offer is\n * off, 404 on a self-hosted instance.\n */\n markWelcomeOfferSeen(): Promise<WelcomeOfferSeenResult> {\n return this.client.request<WelcomeOfferSeenResult>(\"POST\", \"/v1/credits/welcome-offer/seen\")\n }\n\n // NOTE: no `estimate(...)` helper. The backend exposes\n // `POST /v1/credits/estimate-workflow` (body `{ nodes }` → `{ data: {\n // totalCredits, nodeCount, estimate?: true } }` — `estimate` when a metered\n // LLM node's estimate is in the total), but no consumer has a settled shape for it\n // yet (studio pre-checks `balance >= Σ modelCosts` client-side rather than\n // calling an estimate endpoint). Adding it now would be inventing an API\n // surface ahead of a real caller, so it's deliberately omitted — add it when\n // a consumer needs it, shaped to that need.\n}\n"]}
@@ -0,0 +1,146 @@
1
+ 'use strict';
2
+
3
+ // src/resources/billing.ts
4
+ var BillingResource = class {
5
+ constructor(client) {
6
+ this.client = client;
7
+ }
8
+ client;
9
+ /**
10
+ * `GET /v1/billing/plans` → the plans and credit packs on sale, with their
11
+ * prices. Public: works with no credential, the same for every caller.
12
+ * Nodaro Cloud only — a self-hosted instance answers 404. Throws on `403
13
+ * self_serve_disabled` (this deployment does not sell to its users) and on
14
+ * `503` (`stripe_not_configured`, or prices briefly unavailable).
15
+ */
16
+ plans() {
17
+ return this.client.request("GET", "/v1/billing/plans");
18
+ }
19
+ /**
20
+ * `GET /v1/billing/subscription` → the account's latest subscription
21
+ * (`null` when it never subscribed) and the tier its entitlements follow.
22
+ * Match `effectiveTier` to a {@link BillingPlan} `id` to mark the current
23
+ * plan (no match: pay-as-you-go, or a tier not on sale). Needs a signed-in
24
+ * session, a personal API token without a workflow limit, or an app's OAuth
25
+ * token. Nodaro Cloud only — a self-hosted instance answers 404.
26
+ */
27
+ subscription() {
28
+ return this.client.request("GET", "/v1/billing/subscription");
29
+ }
30
+ /**
31
+ * `GET /v1/billing/surface` → how this deployment bills: whether it meters
32
+ * at all (`providerId !== "none"`) and in which unit costs display. Public,
33
+ * every edition.
34
+ */
35
+ async surface() {
36
+ const res = await this.client.request("GET", "/v1/billing/surface");
37
+ return res.data;
38
+ }
39
+ /**
40
+ * `GET /v1/billing/account` → the caller's plan and balance as the
41
+ * deployment's billing provider reports them, in its display unit. `null`
42
+ * when the provider could not answer — not a zero balance. Every edition.
43
+ */
44
+ async account() {
45
+ const res = await this.client.request("GET", "/v1/billing/account");
46
+ return res.data;
47
+ }
48
+ // ── Signed-in session only (ForbiddenError on an API key or an app token) ──
49
+ /**
50
+ * `GET /v1/billing/transactions` → the account's credit purchases, newest
51
+ * first: subscription payments and credit packs, each with its Stripe
52
+ * receipt link when one was captured. **Signed-in session only.**
53
+ */
54
+ async purchases() {
55
+ const res = await this.client.request("GET", "/v1/billing/transactions");
56
+ return res.data;
57
+ }
58
+ /**
59
+ * `GET /v1/billing/invoices` → every payment as a document, newest first:
60
+ * a Stripe invoice (with its PDF) for each subscription payment, a hosted
61
+ * receipt for each credit pack or load. **Signed-in session only.**
62
+ */
63
+ async invoices() {
64
+ const res = await this.client.request("GET", "/v1/billing/invoices");
65
+ return res.data;
66
+ }
67
+ /**
68
+ * `GET /v1/billing/payment-method` → the card and the billing details on
69
+ * file with Stripe; both `null` for an account that has not bought yet
70
+ * (never an error). **Signed-in session only.**
71
+ */
72
+ async paymentMethod() {
73
+ const res = await this.client.request("GET", "/v1/billing/payment-method");
74
+ return res.data;
75
+ }
76
+ /**
77
+ * `GET /v1/billing/auto-recharge` → the automatic top-up setting: when the
78
+ * balance falls under `thresholdCredits`, `amountUsd` is loaded from the
79
+ * saved card. **Signed-in session only.**
80
+ */
81
+ async autoRecharge() {
82
+ const res = await this.client.request("GET", "/v1/billing/auto-recharge");
83
+ return res.data;
84
+ }
85
+ /**
86
+ * `PUT /v1/billing/auto-recharge` → changes the automatic top-up. Enabling
87
+ * needs both `thresholdCredits` (100–100,000) and `amountUsd` (a whole
88
+ * amount in the load range); the server answers `400` otherwise. A change
89
+ * clears the failure count. **Signed-in session only.**
90
+ */
91
+ async setAutoRecharge(input) {
92
+ const res = await this.client.request("PUT", "/v1/billing/auto-recharge", { body: input });
93
+ return res.data;
94
+ }
95
+ /**
96
+ * `POST /v1/billing/create-checkout-session` → a Stripe Checkout page for a
97
+ * plan or a credit pack (`priceId` from {@link BillingPlansResult}): send
98
+ * the person to `url`. Pass `returnPath` (a path on your own origin, such
99
+ * as `"/billing"`) to have Stripe bring them back to your app with
100
+ * `checkout=success` or `checkout=cancelled` in the query; without it the
101
+ * Nodaro app's own pages are used. `ForbiddenError` with the code
102
+ * `self_serve_disabled` on a deployment that does not sell to its users.
103
+ * **Signed-in session only.**
104
+ */
105
+ async checkout(input) {
106
+ const res = await this.client.request("POST", "/v1/billing/create-checkout-session", { body: input });
107
+ return res.data;
108
+ }
109
+ /**
110
+ * `POST /v1/billing/create-load-session` → a Stripe Checkout page that loads
111
+ * a whole amount (`amountUsd`, within {@link BillingPlansResult.topUpRange})
112
+ * as credits at the packs' rate; `credits` is what it will grant. The card
113
+ * is saved for auto top-up. `returnPath` as in {@link checkout}.
114
+ * **Signed-in session only.**
115
+ */
116
+ async loadCredits(input) {
117
+ const res = await this.client.request("POST", "/v1/billing/create-load-session", { body: input });
118
+ return res.data;
119
+ }
120
+ /**
121
+ * `POST /v1/billing/manage-subscription` → a Stripe Customer Portal page
122
+ * (the card, the billing address, the invoices, cancelling): send the person
123
+ * to `url`; `returnPath` is where the portal's Back goes (default the app's
124
+ * `/billing`). `NotFoundError` before a first purchase — Stripe does not
125
+ * know the account yet. **Signed-in session only.**
126
+ */
127
+ async portal(input = {}) {
128
+ const res = await this.client.request("POST", "/v1/billing/manage-subscription", { body: input });
129
+ return res.data;
130
+ }
131
+ /**
132
+ * `POST /v1/billing/change-plan` → moves the active subscription to another
133
+ * plan's price (`newPriceId`, a subscription price from the plans list),
134
+ * prorated by Stripe; the new tier applies at once. `NotFoundError` with no
135
+ * active subscription; `400` on a pack's price or the current one.
136
+ * **Signed-in session only.**
137
+ */
138
+ async changePlan(input) {
139
+ const res = await this.client.request("POST", "/v1/billing/change-plan", { body: input });
140
+ return res.data;
141
+ }
142
+ };
143
+
144
+ exports.BillingResource = BillingResource;
145
+ //# sourceMappingURL=chunk-6FZN3QQO.cjs.map
146
+ //# sourceMappingURL=chunk-6FZN3QQO.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/resources/billing.ts"],"names":[],"mappings":";;;AA+KO,IAAM,kBAAN,MAAsB;AAAA,EAC3B,YAAoB,MAAA,EAA0B;AAA1B,IAAA,IAAA,CAAA,MAAA,GAAA,MAAA;AAAA,EAA2B;AAAA,EAA3B,MAAA;AAAA;AAAA;AAA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Q,iCAAA,EAAmC,EAAE,IAAA,EAAM,KAAA,EAAO,CAAA;AAChI,IAAA,OAAO,GAAA,CAAI,IAAA;AAAA,EACb;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EASA,MAAM,WAAW,KAAA,EAAiE;AAChF,IAAA,MAAM,GAAA,GAAM,MAAM,IAAA,CAAK,MAAA,CAAO,OAAA,CAA2C,QAAQ,yBAAA,EAA2B,EAAE,IAAA,EAAM,KAAA,EAAO,CAAA;AAC3H,IAAA,OAAO,GAAA,CAAI,IAAA;AAAA,EACb;AACF","file":"chunk-6FZN3QQO.cjs","sourcesContent":["import type { NodaroClientCore } from \"../core.js\"\n\n/**\n * Plans and prices, the subscription, and the billing surface — the shapes of\n * the `/v1/billing/*` routes an app may call. Mirrors the backend routes\n * (`backend/src/ee/routes/billing.ts`, `backend/src/routes/billing-surface.ts`),\n * the source of truth: keep these in sync if they change.\n *\n * Buying, the plan, the payment settings, the receipts and the invoices answer\n * a SIGNED-IN SESSION only (`supabaseAuth`, the credential a first-party web\n * app holds): those routes refuse an API key and an app's OAuth token with\n * `403 forbidden` (`ForbiddenError`). Their methods are marked so below.\n */\n\n/** A sum of money in its currency's major unit (`12` = 12.00), with its ISO-4217 code (`\"USD\"`). */\nexport interface BillingMoney {\n amount: number\n currency: string\n}\n\n/** The credits a price grants, and how often. */\nexport interface BillingPriceCredits {\n amount: number\n per: \"month\" | \"year\"\n}\n\n/** A monthly price, and what it grants. */\nexport interface BillingMonthlyPrice extends BillingMoney {\n /** `null` when the price does not state it. */\n credits: BillingPriceCredits | null\n}\n\n/** A yearly price, what it comes to per month, and what it grants. */\nexport interface BillingYearlyPrice extends BillingMoney {\n /** The yearly amount spread over the months it pays for; `null` when that cannot be said. */\n perMonth: number | null\n /** What the price grants — the plan's credits every month, as a monthly price; `null` when the price does not state it. */\n credits: BillingPriceCredits | null\n}\n\nexport interface BillingPlanPrices {\n /** `null` = Stripe cannot sell this price right now: show it as unavailable, never as free. */\n monthly: BillingMonthlyPrice | null\n yearly: BillingYearlyPrice | null\n}\n\n/** One plan on sale. */\nexport interface BillingPlan {\n /** `\"free\"`, `\"basic\"`, `\"standard\"`, … — the stable id. */\n id: string\n name: string\n /** `null` for the free plan: there is nothing to pay. */\n prices: BillingPlanPrices | null\n /** The free plan's one-time grant at sign-up; `null` on a paid plan, whose credits come with each price. */\n signupCredits: number | null\n /** How many nodes of one workflow run at once. */\n parallelism: number\n /** Storage for your media, in bytes. */\n storageBytes: number\n}\n\n/** A credit pack: this many credits for this price. */\nexport interface BillingTopUp {\n id: string\n credits: number\n /** `null` when the pack's price cannot be stated right now: show it as unavailable. */\n price: BillingMoney | null\n}\n\n/** The answer of `GET /v1/billing/plans`. */\nexport interface BillingPlansResult {\n /** The free plan first, then each paid plan from the smallest. */\n data: BillingPlan[]\n /** The credit packs, from the smallest. */\n topUps: BillingTopUp[]\n /** Any whole amount in this range can be loaded as credits, at the same rate as the packs. */\n topUpRange: { min: number; max: number; currency: string }\n}\n\n/** The account's latest subscription record. */\nexport interface BillingSubscription {\n id: string\n stripe_subscription_id: string | null\n /** The plan id: `\"basic\"`, `\"standard\"`, … */\n tier: string\n /** `\"active\"`, `\"trialing\"`, `\"past_due\"`, `\"paused\"`, `\"canceled\"`, `\"incomplete\"` or `\"expired\"`. */\n status: string\n stripe_price_id: string | null\n /** ISO-8601. */\n current_period_start: string | null\n /** ISO-8601: when the current period ends (and renews, unless cancelled). */\n current_period_end: string | null\n /** True when the subscription ends at `current_period_end` instead of renewing. */\n cancel_at_period_end: boolean\n /** ISO-8601: when a scheduled cancellation takes effect. */\n cancel_at: string | null\n /** ISO-8601: when it was cancelled. */\n canceled_at: string | null\n}\n\n/** The answer of `GET /v1/billing/subscription`. */\nexport interface BillingSubscriptionResult {\n /** `null` when the account never subscribed. */\n data: BillingSubscription | null\n /**\n * The tier the account's entitlements follow: usually a plan id from\n * `plans()` (`\"free\"` included); `\"payg\"` — no subscription, but credits\n * bought (every model, no watermark); or a tier that is not on sale, such\n * as `\"enterprise\"`.\n */\n effectiveTier: string\n}\n\n/** How this deployment bills, the same for every caller (`GET /v1/billing/surface`). */\nexport interface BillingSurface {\n /** The billing-surface contract version (an integer). */\n contract: number\n /** The registered billing provider; `\"none\"` = this deployment meters nothing. */\n providerId: string\n /** The unit costs display in by default (`\"credits\"`, `\"usd\"`, or a deployment's own label). */\n displayUnit: string\n canReport: boolean\n canQuote: boolean\n canAccount: boolean\n /** Whether a cost view belongs on this deployment. */\n mountCostTab: boolean\n /** One billing account pays for every user here. */\n deploymentPayer: boolean\n}\n\n/** One row of {@link BillingAccountSummary.byCategory}. */\nexport interface BillingUsageCategory {\n category: string\n count: number\n /** Spend in the display unit; `null` = unavailable, never 0. */\n amount: number | null\n spent: BillingMoney | null\n}\n\n/**\n * The caller's account as the deployment's billing provider sees it\n * (`GET /v1/billing/account`). Money and amounts are `null` when the provider\n * could not say: show that distinctly, never as 0. A field the provider leaves\n * out is a concept it does not have.\n */\nexport interface BillingAccountSummary {\n /** A plain string; `\"unknown\"` is a real answer. */\n plan: string\n balance: number | null\n dailyAllowance: number | null\n unit: string\n /** `\"external_wallet\"` when the balance comes from a wallet outside Nodaro. */\n balanceSource?: \"external_wallet\"\n /** ISO-8601 start of the current usage period. */\n periodStart?: string | null\n /** Generations this period. */\n generations?: number | null\n /** Money spent this period. */\n spent?: BillingMoney | null\n /** Pay-as-you-go state. */\n payg?: {\n enabled: boolean\n reserve: number | null\n rate: { creditsPerUnit: number; currency: string } | null\n monthlyCap: BillingMoney | null\n } | null\n /** The daily cap and when it resets; prefer it over `dailyAllowance` when present. `limit: 0` means blocked. */\n daily?: { limit: number; used: number; remaining: number; resetsAt: string } | null\n /** Money value of the pay-as-you-go reserve. */\n reserveValue?: BillingMoney | null\n byCategory?: BillingUsageCategory[] | null\n /** The total the balance is drawn from, where the provider grants each user an allocation. */\n allocated?: number | null\n}\n\nexport class BillingResource {\n constructor(private client: NodaroClientCore) {}\n\n /**\n * `GET /v1/billing/plans` → the plans and credit packs on sale, with their\n * prices. Public: works with no credential, the same for every caller.\n * Nodaro Cloud only — a self-hosted instance answers 404. Throws on `403\n * self_serve_disabled` (this deployment does not sell to its users) and on\n * `503` (`stripe_not_configured`, or prices briefly unavailable).\n */\n plans(): Promise<BillingPlansResult> {\n return this.client.request<BillingPlansResult>(\"GET\", \"/v1/billing/plans\")\n }\n\n /**\n * `GET /v1/billing/subscription` → the account's latest subscription\n * (`null` when it never subscribed) and the tier its entitlements follow.\n * Match `effectiveTier` to a {@link BillingPlan} `id` to mark the current\n * plan (no match: pay-as-you-go, or a tier not on sale). Needs a signed-in\n * session, a personal API token without a workflow limit, or an app's OAuth\n * token. Nodaro Cloud only — a self-hosted instance answers 404.\n */\n subscription(): Promise<BillingSubscriptionResult> {\n return this.client.request<BillingSubscriptionResult>(\"GET\", \"/v1/billing/subscription\")\n }\n\n /**\n * `GET /v1/billing/surface` → how this deployment bills: whether it meters\n * at all (`providerId !== \"none\"`) and in which unit costs display. Public,\n * every edition.\n */\n async surface(): Promise<BillingSurface> {\n const res = await this.client.request<{ data: BillingSurface }>(\"GET\", \"/v1/billing/surface\")\n return res.data\n }\n\n /**\n * `GET /v1/billing/account` → the caller's plan and balance as the\n * deployment's billing provider reports them, in its display unit. `null`\n * when the provider could not answer — not a zero balance. Every edition.\n */\n async account(): Promise<BillingAccountSummary | null> {\n const res = await this.client.request<{ data: BillingAccountSummary | null }>(\"GET\", \"/v1/billing/account\")\n return res.data\n }\n\n // ── Signed-in session only (ForbiddenError on an API key or an app token) ──\n\n /**\n * `GET /v1/billing/transactions` → the account's credit purchases, newest\n * first: subscription payments and credit packs, each with its Stripe\n * receipt link when one was captured. **Signed-in session only.**\n */\n async purchases(): Promise<BillingPurchase[]> {\n const res = await this.client.request<{ data: BillingPurchase[] }>(\"GET\", \"/v1/billing/transactions\")\n return res.data\n }\n\n /**\n * `GET /v1/billing/invoices` → every payment as a document, newest first:\n * a Stripe invoice (with its PDF) for each subscription payment, a hosted\n * receipt for each credit pack or load. **Signed-in session only.**\n */\n async invoices(): Promise<BillingDocument[]> {\n const res = await this.client.request<{ data: BillingDocument[] }>(\"GET\", \"/v1/billing/invoices\")\n return res.data\n }\n\n /**\n * `GET /v1/billing/payment-method` → the card and the billing details on\n * file with Stripe; both `null` for an account that has not bought yet\n * (never an error). **Signed-in session only.**\n */\n async paymentMethod(): Promise<BillingPaymentMethod> {\n const res = await this.client.request<{ data: BillingPaymentMethod }>(\"GET\", \"/v1/billing/payment-method\")\n return res.data\n }\n\n /**\n * `GET /v1/billing/auto-recharge` → the automatic top-up setting: when the\n * balance falls under `thresholdCredits`, `amountUsd` is loaded from the\n * saved card. **Signed-in session only.**\n */\n async autoRecharge(): Promise<BillingAutoRecharge> {\n const res = await this.client.request<{ data: BillingAutoRecharge }>(\"GET\", \"/v1/billing/auto-recharge\")\n return res.data\n }\n\n /**\n * `PUT /v1/billing/auto-recharge` → changes the automatic top-up. Enabling\n * needs both `thresholdCredits` (100–100,000) and `amountUsd` (a whole\n * amount in the load range); the server answers `400` otherwise. A change\n * clears the failure count. **Signed-in session only.**\n */\n async setAutoRecharge(input: BillingAutoRechargeInput): Promise<BillingAutoRechargeSaved> {\n const res = await this.client.request<{ data: BillingAutoRechargeSaved }>(\"PUT\", \"/v1/billing/auto-recharge\", { body: input })\n return res.data\n }\n\n /**\n * `POST /v1/billing/create-checkout-session` → a Stripe Checkout page for a\n * plan or a credit pack (`priceId` from {@link BillingPlansResult}): send\n * the person to `url`. Pass `returnPath` (a path on your own origin, such\n * as `\"/billing\"`) to have Stripe bring them back to your app with\n * `checkout=success` or `checkout=cancelled` in the query; without it the\n * Nodaro app's own pages are used. `ForbiddenError` with the code\n * `self_serve_disabled` on a deployment that does not sell to its users.\n * **Signed-in session only.**\n */\n async checkout(input: BillingCheckoutInput): Promise<BillingCheckoutSession> {\n const res = await this.client.request<{ data: BillingCheckoutSession }>(\"POST\", \"/v1/billing/create-checkout-session\", { body: input })\n return res.data\n }\n\n /**\n * `POST /v1/billing/create-load-session` → a Stripe Checkout page that loads\n * a whole amount (`amountUsd`, within {@link BillingPlansResult.topUpRange})\n * as credits at the packs' rate; `credits` is what it will grant. The card\n * is saved for auto top-up. `returnPath` as in {@link checkout}.\n * **Signed-in session only.**\n */\n async loadCredits(input: BillingLoadInput): Promise<BillingLoadSession> {\n const res = await this.client.request<{ data: BillingLoadSession }>(\"POST\", \"/v1/billing/create-load-session\", { body: input })\n return res.data\n }\n\n /**\n * `POST /v1/billing/manage-subscription` → a Stripe Customer Portal page\n * (the card, the billing address, the invoices, cancelling): send the person\n * to `url`; `returnPath` is where the portal's Back goes (default the app's\n * `/billing`). `NotFoundError` before a first purchase — Stripe does not\n * know the account yet. **Signed-in session only.**\n */\n async portal(input: BillingPortalInput = {}): Promise<BillingPortalSession> {\n const res = await this.client.request<{ data: BillingPortalSession }>(\"POST\", \"/v1/billing/manage-subscription\", { body: input })\n return res.data\n }\n\n /**\n * `POST /v1/billing/change-plan` → moves the active subscription to another\n * plan's price (`newPriceId`, a subscription price from the plans list),\n * prorated by Stripe; the new tier applies at once. `NotFoundError` with no\n * active subscription; `400` on a pack's price or the current one.\n * **Signed-in session only.**\n */\n async changePlan(input: BillingChangePlanInput): Promise<BillingChangePlanResult> {\n const res = await this.client.request<{ data: BillingChangePlanResult }>(\"POST\", \"/v1/billing/change-plan\", { body: input })\n return res.data\n }\n}\n\n// ── Types of the signed-in-session methods ──\n\n/** One credit purchase (`billing.purchases()`), as the `transactions` row names it. */\nexport interface BillingPurchase {\n id: string\n /** The Stripe payment or subscription id. */\n stripe_transaction_id: string | null\n /** `\"subscription\"` (a plan payment), `\"topup\"` (a credit pack or a load) or `\"refund\"` (money given back: `credits_granted` negative). */\n type: string\n /** What was paid, in US dollars (on a refund, the sum given back). */\n amount_usd: number\n /** Negative on a refund. */\n credits_granted: number\n /** The plan paid for, on a subscription payment. */\n tier: string | null\n /** ISO-8601. */\n created_at: string\n /** Stripe's hosted receipt; `null` when none was captured. */\n receipt_url: string | null\n}\n\n/** A payment document: a Stripe invoice (a subscription payment) or a receipt (a credit purchase). */\nexport interface BillingDocument {\n id: string\n kind: \"invoice\" | \"receipt\"\n /** The invoice number Stripe printed; `null` on a receipt. */\n number: string | null\n /** ISO-8601. */\n at: string\n amount: BillingMoney\n /** The credits the payment granted; `null` on an invoice (the plan's credits come with the period). Negative on a refund. */\n credits: number | null\n /** `\"paid\"`, `\"open\"`, `\"void\"`, `\"uncollectible\"`, or `\"refunded\"` (a receipt for money given back: `amount` and `credits` negative). */\n status: string\n description: string | null\n /** The PDF, on an invoice; `null` on a receipt. */\n pdfUrl: string | null\n /** The hosted page: Stripe's invoice page, or the receipt. */\n url: string | null\n}\n\n/** The card on file, as Stripe shows it. */\nexport interface BillingCard {\n /** `\"visa\"`, `\"mastercard\"`, … */\n brand: string\n last4: string\n expMonth: number\n expYear: number\n}\n\n/** The name, email and country on file. */\nexport interface BillingDetails {\n name: string | null\n email: string | null\n /** ISO-3166 alpha-2. */\n country: string | null\n}\n\n/** The answer of `billing.paymentMethod()`: both `null` before a first purchase. */\nexport interface BillingPaymentMethod {\n card: BillingCard | null\n billingDetails: BillingDetails | null\n}\n\n/** The automatic top-up setting (`billing.autoRecharge()`). */\nexport interface BillingAutoRecharge {\n enabled: boolean\n /** Load when the balance falls under this many credits; `null` when never set. */\n thresholdCredits: number | null\n /** The whole dollar amount loaded each time; `null` when never set. */\n amountUsd: number | null\n /** Failed attempts in a row; the server stops trying after a few, until the setting is saved again. */\n failureCount: number\n /** ISO-8601; `null` before the first attempt. */\n lastAttemptAt: string | null\n /** Whether a card is saved to charge; without one, enabling cannot work. */\n hasSavedCard: boolean\n}\n\n/** What `billing.setAutoRecharge()` sends; `thresholdCredits` and `amountUsd` are both required to enable. */\nexport interface BillingAutoRechargeInput {\n enabled: boolean\n thresholdCredits?: number\n amountUsd?: number\n}\n\n/** What `billing.setAutoRecharge()` answers: the fields as sent (`null` for one left out, even when a stored value remains); read {@link BillingResource.autoRecharge} for the whole setting. */\nexport interface BillingAutoRechargeSaved {\n enabled: boolean\n thresholdCredits: number | null\n amountUsd: number | null\n}\n\n/** What `billing.checkout()` sends. */\nexport interface BillingCheckoutInput {\n /** A plan's monthly or yearly price id, or a credit pack's (`BillingTopUp.id`). */\n priceId: string\n /** Inferred from the price when omitted. */\n mode?: \"subscription\" | \"payment\"\n /** A path on the calling origin Stripe brings the person back to (`\"/billing\"`, a query allowed): one leading `/`, no host, no `#`. Wins over `embedded`. */\n returnPath?: string\n /** Set by an embedded first-party surface: return to the app's public checkout-complete page. */\n embedded?: boolean\n}\n\n/** A Stripe Checkout page to send the person to. */\nexport interface BillingCheckoutSession {\n url: string | null\n}\n\n/** What `billing.loadCredits()` sends. */\nexport interface BillingLoadInput {\n /** A whole dollar amount within `topUpRange`. */\n amountUsd: number\n /** As in {@link BillingCheckoutInput.returnPath}; wins over `embedded`. */\n returnPath?: string\n embedded?: boolean\n}\n\n/** A Stripe Checkout page for a load, and the credits it grants. */\nexport interface BillingLoadSession {\n url: string | null\n credits: number\n}\n\n/** What `billing.portal()` sends. */\nexport interface BillingPortalInput {\n /** Where the portal's Back goes: a path on the calling origin; default the app's `/billing`. */\n returnPath?: string\n}\n\n/** A Stripe Customer Portal page to send the person to. */\nexport interface BillingPortalSession {\n url: string\n}\n\n/** What `billing.changePlan()` sends. */\nexport interface BillingChangePlanInput {\n /** A subscription price id from the plans list. */\n newPriceId: string\n}\n\n/** What `billing.changePlan()` answers. */\nexport interface BillingChangePlanResult {\n subscriptionId: string\n /** The plan now in force: `\"basic\"`, `\"standard\"`, … */\n tier: string\n}\n"]}
@@ -29,6 +29,47 @@ var CreditsResource = class {
29
29
  query: { limit: options.limit, cursor: options.cursor }
30
30
  });
31
31
  }
32
+ /**
33
+ * `GET /v1/credits/usage-summary` → the period's credit usage summed the
34
+ * way a billing screen draws it: totals, the spend by model and by
35
+ * category, a series over time (`bucket`: day, week or month, no holes),
36
+ * and the spend by session and by workflow. The last 30 days unless
37
+ * `from` / `to` say otherwise; a period of at most a year (400 beyond).
38
+ * Cloud-only route: a self-hosted instance answers 404.
39
+ */
40
+ async usageSummary(options = {}) {
41
+ const res = await this.client.request("GET", "/v1/credits/usage-summary", {
42
+ query: { from: options.from, to: options.to, bucket: options.bucket }
43
+ });
44
+ return res.data;
45
+ }
46
+ /**
47
+ * `GET /v1/credits/history` → one page of every movement of the balance,
48
+ * newest first — runs, purchases, grants, refunds, adjustments, expiries —
49
+ * each with the balance after it; a job's reserve row carries its model,
50
+ * its `charge` (the settled charge, the hold while the run is open, `0`
51
+ * once refunded — read that for spend, not `amount`) and its job. Filter by
52
+ * `kind`, `model`, `from` / `to` and `q`; pass the page's `nextCursor` (an
53
+ * opaque string) as `cursor` for the next page (`null` at the end).
54
+ * Cloud-only route: a self-hosted instance answers 404.
55
+ */
56
+ history(options = {}) {
57
+ const { limit, cursor, ...filters } = options;
58
+ return this.client.request("GET", "/v1/credits/history", {
59
+ query: { limit, cursor, ...filters }
60
+ });
61
+ }
62
+ /**
63
+ * `GET /v1/credits/history?format=csv` → the whole filtered history as a
64
+ * CSV file (the same fields as {@link history}, one line per movement,
65
+ * newest first), at most 5,000 rows — the last line says when it was cut.
66
+ * Hand the text to the person as `credit-history.csv`.
67
+ */
68
+ exportHistory(filters = {}) {
69
+ return this.client.requestText("GET", "/v1/credits/history", {
70
+ query: { ...filters, format: "csv" }
71
+ });
72
+ }
32
73
  /**
33
74
  * `POST /v1/credits/model-costs` → per-identifier credit cost, for editor
34
75
  * cost previews. Capped at the first {@link MODEL_COSTS_LIMIT} identifiers
@@ -102,5 +143,5 @@ var CreditsResource = class {
102
143
  };
103
144
 
104
145
  export { CreditsResource };
105
- //# sourceMappingURL=chunk-5MOJSYHI.js.map
106
- //# sourceMappingURL=chunk-5MOJSYHI.js.map
146
+ //# sourceMappingURL=chunk-7QK2NXJA.js.map
147
+ //# sourceMappingURL=chunk-7QK2NXJA.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src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C;AAAA,MAC7F,IAAA,EAAM;AAAA,KACP,CAAA;AAAA,EACH;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAYA,oBAAA,GAAwD;AACtD,IAAA,OAAO,IAAA,CAAK,MAAA,CAAO,OAAA,CAAgC,MAAA,EAAQ,gCAAgC,CAAA;AAAA,EAC7F;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAUF","file":"chunk-7QK2NXJA.js","sourcesContent":["import type { NodaroClientCore } from \"../core.js\"\n\n/**\n * Authenticated user's credit balance — the shape of `GET /v1/user/credits`'s\n * `data` field. Mirrors the canonical `UserBalance` from the backend billing\n * module (`backend/src/ee/billing/credits.ts`), the source of truth: keep this\n * in sync if that interface changes.\n */\nexport interface UserBalance {\n total: number\n subscription: number\n topup: number\n dailySpent: number\n dailyLimit: number | null\n monthlyAllocation: number\n /** Stored billing tier. Display should prefer `effectiveTier`. */\n tier: string\n /** Derived entitlement tier: \"payg\" when stored-free with purchased credits. */\n effectiveTier: string\n features: Record<string, unknown>\n periodEnd: string | null\n /** Credits earned for app usage (free tier only — earned by running flows). */\n appCreditsAllowance: number\n /** Present when a deployment uses an external shared wallet. Raw credits;\n * null means unavailable. Do not substitute the personal `total` balance. */\n externalWallet?: { available: number | null }\n /**\n * Where the account's free signup grant stands. `\"withheld\"` means the\n * account works but the grant did not land — show the activation path.\n * Absent where the deployment has no signup grant.\n */\n freeGrantState?: FreeGrantState\n /**\n * Present only with `freeGrantState: \"withheld\"`, when the claim showed no\n * browser signals at all: the app may say \"free credits need a regular\n * browser — reload\", because a reload in one judges the account again.\n */\n freeGrantNotice?: \"browser_unmeasured\"\n /**\n * The welcome-credits opt-in. PRESENT only while the deployment has the\n * offer switched on — absent means \"no popup, no banner, no block\".\n */\n welcomeOffer?: WelcomeOfferState\n}\n\n/** Where an account's free signup grant stands. */\nexport type FreeGrantState = \"unclaimed\" | \"granted\" | \"withheld\" | \"revoked\"\n\n/** `UserBalance.welcomeOffer` — what an app needs to show the welcome offer. */\nexport interface WelcomeOfferState {\n /** The one-time popup was already shown (see `markWelcomeOfferSeen`). */\n popupSeen: boolean\n /**\n * The account already has its credits (granted elsewhere) but still owes\n * the email consent: the web apps block creation until it is given — the\n * claim records it.\n */\n consentPending: boolean\n /** The credits a claim grants. Name this figure in the offer; never hard-code it. */\n credits: number\n}\n\n/** What `claimWelcomeOffer` sends: the browser signals plus the app answering. */\nexport interface WelcomeOfferClaimInput extends SignupKeys {\n /**\n * The answering app's slug (lowercase letters, digits and `-`, up to 40\n * characters), recorded with the consent. A value outside that grammar is\n * stored as absent, never refused.\n */\n sourceApp?: string\n /**\n * The interface language the user answered in — the id of a language Nodaro\n * ships, such as `\"en\"`, `\"ja\"` or `\"pt-BR\"`. Matched exactly and\n * case-sensitively: `\"en-US\"` or `\"pt-br\"` is stored as absent, never refused.\n * Recorded with the consent as the language of the LATEST consent: a later\n * \"yes\" in another language replaces it.\n */\n locale?: string\n}\n\n/** The answer of `POST /v1/credits/welcome-offer/claim`. */\nexport interface WelcomeOfferClaimResult {\n /** The email consent is recorded. */\n consent: \"granted\"\n /** Where the free grant stands after the claim — `\"withheld\"` when the abuse gate refused it. */\n grant: FreeGrantState\n /** The grant's figure. A grant tops the subscription credits UP TO it (it is not added on top), so a claim that lands it leaves the subscription credits at no less than this. */\n credits: number\n}\n\n/** The answer of `POST /v1/credits/welcome-offer/seen`. */\nexport interface WelcomeOfferSeenResult {\n ok: true\n}\n\n/**\n * Result of `POST /v1/credits/model-costs` — a batch cost lookup for editor\n * cost previews. `data` maps each priced identifier → its credit cost.\n *\n * Per-model fault isolation (the route runs the lookups under\n * `Promise.allSettled`): identifiers with no pricing row are reported in\n * `missing` (undisplayable until an operator seeds a price) and lookup\n * failures in `errors`, instead of failing the whole batch. Callers typically\n * render `'—'` for any identifier that lands in `missing`. The hard-fail\n * policy still triggers at reservation time when the user actually runs the\n * node — this preview lookup is intentionally lenient.\n */\nexport interface ModelCostsResult {\n data: Record<string, number>\n missing: string[]\n errors: string[]\n /**\n * Why each identifier in `errors` has no price — today only\n * `llm_model_unpriced`: a metered LLM price key whose model has no rate on\n * the lane it would be served on (it cannot be run). Omitted when `errors`\n * is empty.\n */\n errorCodes?: Record<string, ModelCostError>\n /**\n * The identifiers in `data` whose figure is an ESTIMATE, not a fixed price:\n * metered LLM price keys (`llmPriceKey` from `@nodaro/shared/llm-models`,\n * `<feature>:<model>[:direct]`), charged on what the call actually uses.\n * Show these as `≈N`. Omitted when there are none, so a batch of fixed ids\n * answers exactly as it always has. A metered key that lands in `missing`\n * instead means the server is not pricing LLM calls per model — show no\n * price for it.\n */\n estimates?: string[]\n}\n\n/** {@link ModelCostsResult.errorCodes} — why an identifier has no price. */\nexport interface ModelCostError {\n /** Today only `llm_model_unpriced`; open to codes a newer server may add. */\n code: \"llm_model_unpriced\" | (string & {})\n /** A sentence to show the user. */\n message: string\n}\n\n/**\n * Result of `GET /v1/credits/model-cost?model=<id>` (`data`): the credits one\n * identifier is charged. `estimate: true` marks a metered LLM price key's\n * figure as an estimate (show it as `≈N`); such an answer is never cached.\n */\nexport interface ModelCostResult {\n model: string\n creditCost: number\n estimate?: true\n}\n\n/**\n * The two browser signals a claim reports — SHA-256 hex digests computed by\n * `@nodaro/sdk/signup-signals` (`collectSignupKeys`). Either may be absent:\n * a browser that cannot be measured still claims, and the server treats the\n * absence as what it is. Any other value is stored as absent server-side.\n */\nexport interface SignupKeys {\n browserKey?: string\n deviceKey?: string\n}\n\n/** The answer of `POST /v1/credits/claim-signup-grant`. */\nexport interface SignupGrantClaimResult {\n /** Where the account's free grant stands after this call. */\n state: FreeGrantState\n /** True only when THIS call moved the credits — a repeat is `false` with the same state. */\n granted: boolean\n}\n\n/**\n * One row of `GET /v1/credits/transactions` — a run's reservation and how it\n * settled.\n *\n * Which amount to read: a run first HOLDS credits and is then settled — charged\n * all or part of the hold, the rest returned. `credits_charged` is what the run\n * cost (`null` while the hold is still open, `0` once refunded); sum it for\n * spend. `credits_reserved` is the hold, which never changes. `credits_used`\n * is the same hold under its original name, kept for existing integrations.\n */\nexport interface CreditTransaction {\n id: string\n /** ISO-8601. Also the paging cursor: pass the last row's value as `cursor`. */\n created_at: string\n /** Settled charge; `null` while `status` is `\"reserved\"`, `0` when refunded. */\n credits_charged: number | null\n /** The hold taken when the run was accepted. */\n credits_reserved: number | null\n /** The hold, under its original name. Prefer `credits_charged`. */\n credits_used: number | null\n /** The model or operation the credits were for. */\n action: string | null\n provider: string | null\n /** Reservation lifecycle: `\"reserved\"`, `\"committed\"` or `\"refunded\"`. */\n status: string | null\n /** The caller's own billing details for the run (model, which pool paid, …). */\n metadata: Record<string, unknown>\n /** `\"workspace\"` when a class or team budget paid, not your balance. */\n payer: \"user\" | \"workspace\"\n workspaceId: string | null\n}\n\n/** A page of {@link CreditTransaction}s, newest first. */\nexport interface CreditTransactionsPage {\n data: CreditTransaction[]\n /** Pass as `cursor` for the next page; `null` when there are no more rows. */\n nextCursor: string | null\n}\n\nexport interface CreditTransactionsOptions {\n /** Rows per page, 1–50 (server default 20). */\n limit?: number\n /** The `nextCursor` of the previous page. */\n cursor?: string\n}\n\n/** How `credits.usageSummary()` groups the series over time. */\nexport type UsageSummaryBucket = \"day\" | \"week\" | \"month\"\n\nexport interface UsageSummaryOptions {\n /** An ISO-8601 timestamp, or a date alone (`\"2026-10-01\"`: that whole UTC day), inclusive; default the last 30 days up to now. A period of at most a year. */\n from?: string\n to?: string\n /** Default `\"day\"`. Buckets are UTC. */\n bucket?: UsageSummaryBucket\n}\n\nexport interface UsageSummaryTotals {\n /** Credits spent on runs in the period: each run's charge (a running hold counts; a refunded run does not). */\n used: number\n /** Credits bought: packs, loads, subscription grants. */\n purchased: number\n /** Credits granted free, net: sign-up and admin adjustments, a grant taken back subtracted. */\n granted: number\n /** Credits given back for a refunded run or by Stripe (a hold released when a run settled below it is not a refund). */\n refunded: number\n /** Runs that were charged or are still running. */\n runs: number\n /** `used / runs`, one decimal; 0 with no runs. */\n avgPerRun: number\n}\n\nexport interface UsageByModel {\n model: string\n provider: string | null\n credits: number\n runs: number\n /** Of `totals.used`, 0–1. */\n share: number\n}\n\nexport interface UsageByCategory {\n /** `\"image\"`, `\"video\"`, `\"audio\"` or `\"other\"`. */\n category: string\n credits: number\n runs: number\n}\n\nexport interface UsageOverTime {\n /** The bucket's first day in UTC (`\"2026-10-26\"`; a week by its Monday; a month as `\"2026-10\"`). The first bucket of a period may be a partial week or month. */\n bucket: string\n used: number\n purchased: number\n runs: number\n}\n\n/** The spend of one session or one workflow. */\nexport interface UsageByGroup {\n id: string\n /** The session's title or the workflow's name; `null` when it has none or is gone. */\n name: string | null\n /** The tool the session belongs to; `null` on a workflow. */\n tool: string | null\n credits: number\n runs: number\n /** The models used, by spend. */\n models: string[]\n /** ISO-8601: the latest run. */\n lastAt: string\n}\n\n/** The answer of `credits.usageSummary()`. */\nexport interface UsageSummary {\n period: { from: string; to: string; bucket: UsageSummaryBucket }\n totals: UsageSummaryTotals\n /** The model with the most spend; `null` with no runs. */\n mostUsed: UsageByModel | null\n /** By spend. */\n byModel: UsageByModel[]\n byCategory: UsageByCategory[]\n /** Every bucket of the period, empty ones included, oldest first. */\n overTime: UsageOverTime[]\n bySession: UsageByGroup[]\n byWorkflow: UsageByGroup[]\n /** A read hit the server's row cap: the figures under-report; narrow the period. */\n truncated: boolean\n /** A side read failed on the server (the jobs, or a session's or workflow's name): a grouping is missing or unnamed; the totals are whole. */\n partial: boolean\n}\n\n/** What a movement of the balance was; `app` is credits earned from, or paid for, a published app. */\nexport type CreditHistoryKind = \"usage\" | \"purchase\" | \"grant\" | \"refund\" | \"app\" | \"adjustment\" | \"expiry\"\n\n/** The job behind a usage row of {@link CreditHistoryEntry}. */\nexport interface CreditHistoryJob {\n id: string\n /** The node type that ran (`generate-image`, `image-to-video`, …); `null` when the job is gone. */\n type: string | null\n status: string | null\n startedAt: string | null\n completedAt: string | null\n /** From start to completion; `null` until it completes. */\n durationMs: number | null\n workflowId: string | null\n sessionId: string | null\n}\n\n/** One movement of the balance (`credits.history()`). */\nexport interface CreditHistoryEntry {\n id: string\n /** ISO-8601. Also the paging cursor. */\n at: string\n kind: CreditHistoryKind\n /** The ledger's own word: `usage`, `one_time_purchase`, `subscription_renewal`, `signup_grant`, `refund`, `admin_adjustment`, `expiry`, … */\n source: string\n /** The movement, signed: a run's hold negative, a purchase positive. */\n amount: number\n /** The balance right after this movement. */\n balanceAfter: number\n /** Which pool moved; `\"mixed\"` when both did. */\n pool: \"subscription\" | \"topup\" | \"mixed\"\n description: string | null\n /** The model that ran, on a row with a job; `null` otherwise. */\n model: string | null\n provider: string | null\n /**\n * The job's charge, on its reserve row only (the hold taken when the run\n * was accepted): the settled charge, the hold while the run is open, `0`\n * once refunded. `null` on every other row — a refund, a metered overrun\n * line, a purchase — so summing it over a list counts each job once. Read\n * this for spend, not `amount`.\n */\n charge: number | null\n /** The run's credit status (`\"reserved\"`, `\"committed\"` or `\"refunded\"`), beside `charge`; `null` elsewhere. */\n status: string | null\n /** On a row with a job; `type` and the rest `null` when the job is gone or not the person's. */\n job: CreditHistoryJob | null\n /** Stripe's hosted receipt, on a purchase that has one. */\n receiptUrl: string | null\n}\n\n/** A page of {@link CreditHistoryEntry}, newest first. */\nexport interface CreditHistoryPage {\n data: CreditHistoryEntry[]\n /** Pass as `cursor` for the next page; `null` when there are no more rows. */\n nextCursor: string | null\n}\n\n/** What narrows the history. */\nexport interface CreditHistoryFilters {\n kind?: CreditHistoryKind\n /** A model identifier: only runs of that model. */\n model?: string\n /** ISO-8601 bounds on `at`, inclusive. */\n from?: string\n to?: string\n /** Words looked for in the description, case-insensitively. */\n q?: string\n}\n\nexport interface CreditHistoryOptions extends CreditHistoryFilters {\n /** Rows per page, 1–100 (server default 50). */\n limit?: number\n /** The `nextCursor` of the previous page, as given (opaque; another string is refused with 400). */\n cursor?: string\n}\n\n/** Max identifiers per `model-costs` batch — the route caps the request at 50. */\nconst MODEL_COSTS_LIMIT = 50\n\nexport class CreditsResource {\n constructor(private client: NodaroClientCore) {}\n\n /**\n * `GET /v1/user/credits` → the authenticated user's credit balance and tier\n * info. Throws `UnauthorizedError` (401) when signed out, and the SDK's\n * other typed errors on the usual statuses.\n */\n async balance(): Promise<UserBalance> {\n const res = await this.client.request<{ data: UserBalance }>(\n \"GET\",\n \"/v1/user/credits\",\n )\n return res.data\n }\n\n /**\n * `GET /v1/credits/transactions` → one page of the caller's credit\n * transactions, newest first, with `nextCursor` for the next page (`null`\n * at the end). Read `credits_charged` for what each run cost — it can be\n * below the hold (`credits_reserved`) and is `null` while the hold is open.\n * Cloud-only route: a self-hosted instance answers 404.\n */\n transactions(options: CreditTransactionsOptions = {}): Promise<CreditTransactionsPage> {\n return this.client.request<CreditTransactionsPage>(\"GET\", \"/v1/credits/transactions\", {\n query: { limit: options.limit, cursor: options.cursor },\n })\n }\n\n /**\n * `GET /v1/credits/usage-summary` → the period's credit usage summed the\n * way a billing screen draws it: totals, the spend by model and by\n * category, a series over time (`bucket`: day, week or month, no holes),\n * and the spend by session and by workflow. The last 30 days unless\n * `from` / `to` say otherwise; a period of at most a year (400 beyond).\n * Cloud-only route: a self-hosted instance answers 404.\n */\n async usageSummary(options: UsageSummaryOptions = {}): Promise<UsageSummary> {\n const res = await this.client.request<{ data: UsageSummary }>(\"GET\", \"/v1/credits/usage-summary\", {\n query: { from: options.from, to: options.to, bucket: options.bucket },\n })\n return res.data\n }\n\n /**\n * `GET /v1/credits/history` → one page of every movement of the balance,\n * newest first — runs, purchases, grants, refunds, adjustments, expiries —\n * each with the balance after it; a job's reserve row carries its model,\n * its `charge` (the settled charge, the hold while the run is open, `0`\n * once refunded — read that for spend, not `amount`) and its job. Filter by\n * `kind`, `model`, `from` / `to` and `q`; pass the page's `nextCursor` (an\n * opaque string) as `cursor` for the next page (`null` at the end).\n * Cloud-only route: a self-hosted instance answers 404.\n */\n history(options: CreditHistoryOptions = {}): Promise<CreditHistoryPage> {\n const { limit, cursor, ...filters } = options\n return this.client.request<CreditHistoryPage>(\"GET\", \"/v1/credits/history\", {\n query: { limit, cursor, ...filters },\n })\n }\n\n /**\n * `GET /v1/credits/history?format=csv` → the whole filtered history as a\n * CSV file (the same fields as {@link history}, one line per movement,\n * newest first), at most 5,000 rows — the last line says when it was cut.\n * Hand the text to the person as `credit-history.csv`.\n */\n exportHistory(filters: CreditHistoryFilters = {}): Promise<string> {\n return this.client.requestText(\"GET\", \"/v1/credits/history\", {\n query: { ...filters, format: \"csv\" },\n })\n }\n\n /**\n * `POST /v1/credits/model-costs` → per-identifier credit cost, for editor\n * cost previews. Capped at the first {@link MODEL_COSTS_LIMIT} identifiers\n * (the route's request limit). Preserves the `{ data, missing, errors }`\n * fault-isolation shape verbatim, plus `estimates` / `errorCodes` when a\n * metered LLM price key was asked (see {@link ModelCostsResult}).\n */\n modelCosts(ids: string[]): Promise<ModelCostsResult> {\n return this.client.request<ModelCostsResult>(\"POST\", \"/v1/credits/model-costs\", {\n body: { models: ids.slice(0, MODEL_COSTS_LIMIT) },\n })\n }\n\n /**\n * `POST /v1/credits/claim-signup-grant` → claims the account's free signup\n * grant, once, with the browser signals of the page making the claim.\n *\n * Call it once per page load as soon as the session is known, and never\n * wait on it for rendering: it is idempotent (a decided account answers\n * with its state and `granted: false`), it costs the user nothing when it\n * fails (the next load asks again), and the signals are what make the\n * claim worth sending — collect them with `collectSignupKeys()` from\n * `@nodaro/sdk/signup-signals` and pass whatever came back, `{}` included.\n * Cloud-only route: a self-hosted instance answers 404.\n */\n claimSignupGrant(keys: SignupKeys = {}): Promise<SignupGrantClaimResult> {\n return this.client.request<SignupGrantClaimResult>(\"POST\", \"/v1/credits/claim-signup-grant\", {\n body: keys,\n })\n }\n\n /**\n * `POST /v1/credits/welcome-offer/claim` → the user's \"yes\" to the welcome\n * offer, as ONE server action: the marketing-email consent is recorded,\n * then the free signup grant is claimed with that consent. The abuse gate\n * still decides — consent is necessary, not sufficient — so read `grant`:\n * `\"granted\"` (the grant has landed: this call topped the subscription credits up to `credits` — not added on top — or it had landed before), `\"withheld\"` (refused), `\"revoked\"` (taken back earlier; nothing moves), `\"unclaimed\"` (nothing moved — treat as a failure and let the user retry).\n * Pass the browser signals from `collectSignupKeys()` and your app's slug.\n *\n * **Browser session only.** Usable from a first-party web app signed in\n * with a Supabase session (the consent is a person's choice in a browser);\n * an API key or OAuth app token is refused with 403. 409\n * `welcome_offer_disabled` while the deployment has the offer off — show\n * it only when `balance().welcomeOffer` is present. Cloud-only route: a\n * self-hosted instance answers 404.\n */\n claimWelcomeOffer(input: WelcomeOfferClaimInput = {}): Promise<WelcomeOfferClaimResult> {\n return this.client.request<WelcomeOfferClaimResult>(\"POST\", \"/v1/credits/welcome-offer/claim\", {\n body: input,\n })\n }\n\n /**\n * `POST /v1/credits/welcome-offer/seen` → records that the one-time welcome\n * popup was shown, so `balance().welcomeOffer.popupSeen` turns true on every\n * app. Idempotent (the first stamp wins); a failed call only means the popup\n * may show once more, so callers usually ignore errors.\n *\n * **Browser session only**, like {@link claimWelcomeOffer}: 403 for an API\n * key or OAuth app token, 409 `welcome_offer_disabled` while the offer is\n * off, 404 on a self-hosted instance.\n */\n markWelcomeOfferSeen(): Promise<WelcomeOfferSeenResult> {\n return this.client.request<WelcomeOfferSeenResult>(\"POST\", \"/v1/credits/welcome-offer/seen\")\n }\n\n // NOTE: no `estimate(...)` helper. The backend exposes\n // `POST /v1/credits/estimate-workflow` (body `{ nodes }` → `{ data: {\n // totalCredits, nodeCount, estimate?: true } }` — `estimate` when a metered\n // LLM node's estimate is in the total), but no consumer has a settled shape for it\n // yet (studio pre-checks `balance >= Σ modelCosts` client-side rather than\n // calling an estimate endpoint). Adding it now would be inventing an API\n // surface ahead of a real caller, so it's deliberately omitted — add it when\n // a consumer needs it, shaped to that need.\n}\n"]}
@@ -112,5 +112,5 @@ var PresetsResource = class {
112
112
  };
113
113
 
114
114
  export { PresetsResource };
115
- //# sourceMappingURL=chunk-JTAW54UM.js.map
116
- //# source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;AAAA,EACb;AAAA;AAAA,EAGA,MAAM,WAAA,CAAY,EAAA,EAAY,KAAA,EAA6D;AACzF,IAAA,MAAM,GAAA,GAAM,MAAM,IAAA,CAAK,MAAA,CAAO,OAAA,CAAmC,SAAS,CAAA,uBAAA,EAA0B,kBAAA,CAAmB,EAAE,CAAC,CAAA,CAAA,EAAI;AAAA,MAC5H,IAAA,EAAM;AAAA,KACP,CAAA;AACD,IAAA,OAAO,GAAA,CAAI,IAAA;AAAA,EACb;AAAA;AAAA,EAGA,MAAM,YAAY,EAAA,EAAwC;AACxD,IAAA,MAAM,GAAA,GAAM,MAAM,IAAA,CAAK,MAAA,CAAO,OAAA,CAAqC,UAAU,CAAA,uBAAA,EAA0B,kBAAA,CAAmB,EAAE,CAAC,CAAA,CAAE,CAAA;AAC/H,IAAA,OAAO,GAAA,CAAI,IAAA;AAAA,EACb;AACF","file":"chunk-34PU2DAT.cjs","sourcesContent":["import type { NodaroClientCore } from \"../core.js\"\nimport type { FactoryPreset } from \"@nodaro/prompts/presets\"\n\n/**\n * A user's saved custom preset (`GET /v1/node-presets`). Mirrors the backend's\n * camelCase row shape. `data` is captured node config — merge it into a node's\n * data when building/running a workflow to \"apply\" the preset.\n */\nexport interface NodePreset {\n id: string\n nodeType: string\n name: string\n description?: string\n data: Record<string, unknown>\n groupId?: string\n tags: string[]\n sortOrder: number\n /**\n * How many connected reference images the preset works from (0 = none),\n * counted from the `{image:N}` tokens in its prompt. Absent from servers that\n * predate it.\n */\n minReferences?: number\n /** `minReferences > 0` — the preset works from a connected photo. */\n needsImage?: boolean\n /** The example picture stored with the preset, or null. */\n previewUrl?: string | null\n createdAt: string\n updatedAt: string\n}\n\n/** A user's preset folder/section (`GET /v1/node-preset-groups`). */\nexport interface NodePresetGroup {\n id: string\n nodeType: string\n name: string\n kind: \"folder\" | \"section\"\n sortOrder: number\n createdAt: string\n updatedAt: string\n}\n\n/**\n * One built-in preset as `GET /v1/node-presets/factory` serves it: the\n * catalog entry plus what a client needs to present it.\n */\nexport interface FactoryPresetEntry extends FactoryPreset {\n /**\n * How many connected reference images the preset works from (0 = none):\n * Reference Sheet, Portrait Transformations, Edits and every template using\n * `{image:N}` need at least one. Absent from servers that predate it.\n */\n minReferences?: number\n /** `minReferences > 0` — the preset works from a connected photo. */\n needsImage?: boolean\n /**\n * An example picture of what the preset makes — an absolute URL on the\n * server you asked — or null while the preset has none.\n */\n previewUrl?: string | null\n}\n\n/**\n * Result of `GET /v1/node-presets/factory` — the built-in (factory) catalog for\n * a node type.\n */\nexport interface FactoryPresetsResult {\n data: FactoryPresetEntry[]\n}\n\n/** `POST /v1/node-presets` body. */\nexport interface CreateNodePresetInput {\n /** The node type the preset configures, e.g. `\"generate-image\"`. */\n nodeType: string\n /** Unique per node type (case-insensitive); a duplicate answers 409 `name_taken`. */\n name: string\n description?: string\n /** Node config (≤ 64 KB). Runtime keys (results, job ids, labels) are stripped. */\n data: Record<string, unknown>\n /** One of your preset groups, or null for none. */\n groupId?: string | null\n tags?: string[]\n sortOrder?: number\n /**\n * An example picture: an image stored on this platform (an upload or a\n * generated result) that already exists. Anything else answers 400.\n */\n previewUrl?: string | null\n}\n\n/** `PATCH /v1/node-presets/:id` body — every field optional; `previewUrl: null` removes the picture. */\nexport type UpdateNodePresetInput = Partial<Omit<CreateNodePresetInput, \"nodeType\">>\n\n/** One entry of `POST /v1/node-presets/import` (the `presets export` envelope's entries fit). */\nexport interface ImportNodePresetInput {\n nodeType: string\n name: string\n description?: string\n data: Record<string, unknown>\n previewUrl?: string | null\n}\n\n/** `POST /v1/node-presets/reorder` body. */\nexport interface ReorderNodePresetsInput {\n groups?: Array<{ id: string; sortOrder: number }>\n /** `groupId` moves the preset into one of your groups (null = out of any group). */\n presets?: Array<{ id: string; groupId?: string | null; sortOrder: number }>\n}\n\n/** A favorite: a factory preset id (`\"generate-image/character-board\"`) or one of your preset ids. */\nexport interface NodePresetFavoriteInput {\n nodeType: string\n presetId: string\n}\n\n/** `POST /v1/node-preset-groups` body. */\nexport interface CreateNodePresetGroupInput {\n nodeType: string\n name: string\n /** A collapsible `\"folder\"` (default) or a flat `\"section\"` header. */\n kind?: \"folder\" | \"section\"\n sortOrder?: number\n}\n\n/** `PATCH /v1/node-preset-groups/:id` body. */\nexport interface UpdateNodePresetGroupInput {\n name?: string\n sortOrder?: number\n}\n\n/**\n * Node presets — reusable, named node configurations: your own presets and\n * folders, your favorites, and the built-in factory catalog.\n *\n * To *use* a preset, take its `data` and merge it into a node's config when you\n * create/update a workflow. `needsImage` / `minReferences` say how many photos\n * it works from; `previewUrl` is an example picture (null when there is none).\n *\n * The factory catalog (`listFactory`) is public: no token needed. Reads of\n * your own library need the `presets:read` scope for an OAuth app token;\n * writes (create, update, delete, import, reorder, favorites, groups) need\n * `assets:write`. Your own API key needs neither — but a key limited to some\n * workflows cannot reach your own presets (it reads the factory catalog as\n * anyone can).\n */\nexport class PresetsResource {\n constructor(private client: NodaroClientCore) {}\n\n /**\n * `GET /v1/node-presets` → your custom presets, newest first. Pass `nodeType`\n * (e.g. `\"generate-image\"`) to filter to one node type.\n */\n async list(nodeType?: string): Promise<NodePreset[]> {\n const qs = nodeType ? `?nodeType=${encodeURIComponent(nodeType)}` : \"\"\n const res = await this.client.request<{ data: NodePreset[] }>(\"GET\", `/v1/node-presets${qs}`)\n return res.data\n }\n\n /**\n * `GET /v1/node-preset-groups` → your preset folders/sections, in display\n * order. Pass `nodeType` to filter to one node type.\n */\n async listGroups(nodeType?: string): Promise<NodePresetGroup[]> {\n const qs = nodeType ? `?nodeType=${encodeURIComponent(nodeType)}` : \"\"\n const res = await this.client.request<{ data: NodePresetGroup[] }>(\"GET\", `/v1/node-preset-groups${qs}`)\n return res.data\n }\n\n /**\n * `GET /v1/node-presets/factory` → the built-in catalog for `nodeType`. These\n * ship with the app (no account needed to exist), so they're a good starting\n * point for \"what configs are available\".\n *\n * Login is optional: the catalog is public, so this works on a client with\n * no credential at all (`auth: { getToken: async () => null }`) — show the\n * names, example pictures (`previewUrl`) and photo counts (`minReferences`,\n * `needsImage`) to a visitor who is not signed in, and ask for a login only\n * when they generate. Your OWN presets (`list()`) still need a token.\n */\n listFactory(nodeType: string): Promise<FactoryPresetsResult> {\n return this.client.request<FactoryPresetsResult>(\n \"GET\",\n `/v1/node-presets/factory?nodeType=${encodeURIComponent(nodeType)}`,\n )\n }\n\n /** `POST /v1/node-presets` → the new preset. */\n async create(input: CreateNodePresetInput): Promise<NodePreset> {\n const res = await this.client.request<{ data: NodePreset }>(\"POST\", \"/v1/node-presets\", { body: input })\n return res.data\n }\n\n /**\n * `PATCH /v1/node-presets/:id` → the updated preset. Pass the `updatedAt` you\n * read as `expectedUpdatedAt` to refuse (409 `conflict`) a change made\n * elsewhere since.\n */\n async update(id: string, patch: UpdateNodePresetInput, opts: { expectedUpdatedAt?: string } = {}): Promise<NodePreset> {\n const body = opts.expectedUpdatedAt ? { ...patch, expectedUpdatedAt: opts.expectedUpdatedAt } : patch\n const res = await this.client.request<{ data: NodePreset }>(\"PATCH\", `/v1/node-presets/${encodeURIComponent(id)}`, { body })\n return res.data\n }\n\n /** `DELETE /v1/node-presets/:id` (404 when it is not yours). `expectedUpdatedAt` as on `update`. */\n async delete(id: string, opts: { expectedUpdatedAt?: string } = {}): Promise<{ success: true }> {\n const res = await this.client.request<{ data: { success: true } }>(\"DELETE\", `/v1/node-presets/${encodeURIComponent(id)}`, {\n query: { expectedUpdatedAt: opts.expectedUpdatedAt },\n })\n return res.data\n }\n\n /**\n * `POST /v1/node-presets/import` — up to 500 presets in one call. A name you\n * already use gets an \"(imported N)\" suffix; a preset whose data is empty\n * after stripping runtime keys is skipped.\n */\n async import(presets: ImportNodePresetInput[]): Promise<{ imported: number }> {\n const res = await this.client.request<{ data: { imported: number } }>(\"POST\", \"/v1/node-presets/import\", { body: { presets } })\n return res.data\n }\n\n /** `POST /v1/node-presets/reorder` — positions (and group membership) for many presets and groups at once. */\n async reorder(input: ReorderNodePresetsInput): Promise<{ ok: true }> {\n const res = await this.client.request<{ data: { ok: true } }>(\"POST\", \"/v1/node-presets/reorder\", { body: input })\n return res.data\n }\n\n /** `GET /v1/node-presets/favorites` → your favorite preset ids for `nodeType`, newest first. */\n async favorites(nodeType: string): Promise<string[]> {\n const res = await this.client.request<{ data: string[] }>(\"GET\", \"/v1/node-presets/favorites\", { query: { nodeType } })\n return res.data\n }\n\n /** `POST /v1/node-presets/favorites` — idempotent. */\n async addFavorite(input: NodePresetFavoriteInput): Promise<{ success: true }> {\n const res = await this.client.request<{ data: { success: true } }>(\"POST\", \"/v1/node-presets/favorites\", { body: input })\n return res.data\n }\n\n /** `DELETE /v1/node-presets/favorites` — idempotent. */\n async removeFavorite(input: NodePresetFavoriteInput): Promise<{ success: true }> {\n const res = await this.client.request<{ data: { success: true } }>(\"DELETE\", \"/v1/node-presets/favorites\", {\n query: { nodeType: input.nodeType, presetId: input.presetId },\n })\n return res.data\n }\n\n /** `POST /v1/node-preset-groups` → the new folder or section. */\n async createGroup(input: CreateNodePresetGroupInput): Promise<NodePresetGroup> {\n const res = await this.client.request<{ data: NodePresetGroup }>(\"POST\", \"/v1/node-preset-groups\", { body: input })\n return res.data\n }\n\n /** `PATCH /v1/node-preset-groups/:id` → the renamed or moved group. */\n async updateGroup(id: string, patch: UpdateNodePresetGroupInput): Promise<NodePresetGroup> {\n const res = await this.client.request<{ data: NodePresetGroup }>(\"PATCH\", `/v1/node-preset-groups/${encodeURIComponent(id)}`, {\n body: patch,\n })\n return res.data\n }\n\n /** `DELETE /v1/node-preset-groups/:id` — its presets move out of the group; none are deleted. */\n async deleteGroup(id: string): Promise<{ success: true }> {\n const res = await this.client.request<{ data: { success: true } }>(\"DELETE\", `/v1/node-preset-groups/${encodeURIComponent(id)}`)\n return res.data\n }\n}\n"]}
1
+ {"version":3,"sources":["../src/resources/node-presets.ts"],"names":[],"mappings":";AAuJO,IAAM,kBAAN,MAAsB;AAAA,EAC3B,YAAoB,MAAA,EAA0B;AAA1B,IAAA,IAAA,CAAA,MAAA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AACD,IAAA,OAAO,GAAA,CAAI,IAAA;AAAA,EACb;AAAA;AAAA,EAGA,MAAM,YAAY,EAAA,EAAwC;AACxD,IAAA,MAAM,GAAA,GAAM,MAAM,IAAA,CAAK,MAAA,CAAO,OAAA,CAAqC,UAAU,CAAA,uBAAA,EAA0B,kBAAA,CAAmB,EAAE,CAAC,CAAA,CAAE,CAAA;AAC/H,IAAA,OAAO,GAAA,CAAI,IAAA;AAAA,EACb;AACF","file":"chunk-AEUPH7EE.js","sourcesContent":["import type { NodaroClientCore } from \"../core.js\"\nimport type { FactoryPreset } from \"@nodaro/prompts/presets\"\n\n/**\n * A user's saved custom preset (`GET /v1/node-presets`). Mirrors the backend's\n * camelCase row shape. `data` is captured node config — merge it into a node's\n * data when building/running a workflow to \"apply\" the preset.\n */\nexport interface NodePreset {\n id: string\n nodeType: string\n name: string\n description?: string\n data: Record<string, unknown>\n groupId?: string\n tags: string[]\n sortOrder: number\n /**\n * How many connected reference images the preset works from (0 = none),\n * counted from the `{image:N}` tokens in its prompt. Absent from servers that\n * predate it.\n */\n minReferences?: number\n /** `minReferences > 0` — the preset works from a connected photo. */\n needsImage?: boolean\n /** The example picture stored with the preset, or null. */\n previewUrl?: string | null\n createdAt: string\n updatedAt: string\n}\n\n/** A user's preset folder/section (`GET /v1/node-preset-groups`). */\nexport interface NodePresetGroup {\n id: string\n nodeType: string\n name: string\n kind: \"folder\" | \"section\"\n sortOrder: number\n createdAt: string\n updatedAt: string\n}\n\n/**\n * One built-in preset as `GET /v1/node-presets/factory` serves it: the\n * catalog entry plus what a client needs to present it.\n */\nexport interface FactoryPresetEntry extends FactoryPreset {\n /**\n * How many connected reference images the preset works from (0 = none):\n * Reference Sheet, Portrait Transformations, Edits and every template using\n * `{image:N}` need at least one. Absent from servers that predate it.\n */\n minReferences?: number\n /** `minReferences > 0` — the preset works from a connected photo. */\n needsImage?: boolean\n /**\n * An example picture of what the preset makes — an absolute URL on the\n * server you asked — or null while the preset has none.\n */\n previewUrl?: string | null\n /**\n * The same picture at its two sizes for an `<img srcset>` — the tile picture\n * at 512w and the full-screen one at up to 1024w. Present only when the\n * preset has both; absent from servers that predate it.\n */\n previewSrcSet?: string\n}\n\n/**\n * Result of `GET /v1/node-presets/factory` — the built-in (factory) catalog for\n * a node type.\n */\nexport interface FactoryPresetsResult {\n data: FactoryPresetEntry[]\n}\n\n/** `POST /v1/node-presets` body. */\nexport interface CreateNodePresetInput {\n /** The node type the preset configures, e.g. `\"generate-image\"`. */\n nodeType: string\n /** Unique per node type (case-insensitive); a duplicate answers 409 `name_taken`. */\n name: string\n description?: string\n /** Node config (≤ 64 KB). Runtime keys (results, job ids, labels) are stripped. */\n data: Record<string, unknown>\n /** One of your preset groups, or null for none. */\n groupId?: string | null\n tags?: string[]\n sortOrder?: number\n /**\n * An example picture: an image stored on this platform (an upload or a\n * generated result) that already exists. Anything else answers 400.\n */\n previewUrl?: string | null\n}\n\n/** `PATCH /v1/node-presets/:id` body — every field optional; `previewUrl: null` removes the picture. */\nexport type UpdateNodePresetInput = Partial<Omit<CreateNodePresetInput, \"nodeType\">>\n\n/** One entry of `POST /v1/node-presets/import` (the `presets export` envelope's entries fit). */\nexport interface ImportNodePresetInput {\n nodeType: string\n name: string\n description?: string\n data: Record<string, unknown>\n previewUrl?: string | null\n}\n\n/** `POST /v1/node-presets/reorder` body. */\nexport interface ReorderNodePresetsInput {\n groups?: Array<{ id: string; sortOrder: number }>\n /** `groupId` moves the preset into one of your groups (null = out of any group). */\n presets?: Array<{ id: string; groupId?: string | null; sortOrder: number }>\n}\n\n/** A favorite: a factory preset id (`\"generate-image/character-board\"`) or one of your preset ids. */\nexport interface NodePresetFavoriteInput {\n nodeType: string\n presetId: string\n}\n\n/** `POST /v1/node-preset-groups` body. */\nexport interface CreateNodePresetGroupInput {\n nodeType: string\n name: string\n /** A collapsible `\"folder\"` (default) or a flat `\"section\"` header. */\n kind?: \"folder\" | \"section\"\n sortOrder?: number\n}\n\n/** `PATCH /v1/node-preset-groups/:id` body. */\nexport interface UpdateNodePresetGroupInput {\n name?: string\n sortOrder?: number\n}\n\n/**\n * Node presets — reusable, named node configurations: your own presets and\n * folders, your favorites, and the built-in factory catalog.\n *\n * To *use* a preset, take its `data` and merge it into a node's config when you\n * create/update a workflow. `needsImage` / `minReferences` say how many photos\n * it works from; `previewUrl` is an example picture (null when there is none).\n *\n * The factory catalog (`listFactory`) is public: no token needed. Reads of\n * your own library need the `presets:read` scope for an OAuth app token;\n * writes (create, update, delete, import, reorder, favorites, groups) need\n * `assets:write`. Your own API key needs neither — but a key limited to some\n * workflows cannot reach your own presets (it reads the factory catalog as\n * anyone can).\n */\nexport class PresetsResource {\n constructor(private client: NodaroClientCore) {}\n\n /**\n * `GET /v1/node-presets` → your custom presets, newest first. Pass `nodeType`\n * (e.g. `\"generate-image\"`) to filter to one node type.\n */\n async list(nodeType?: string): Promise<NodePreset[]> {\n const qs = nodeType ? `?nodeType=${encodeURIComponent(nodeType)}` : \"\"\n const res = await this.client.request<{ data: NodePreset[] }>(\"GET\", `/v1/node-presets${qs}`)\n return res.data\n }\n\n /**\n * `GET /v1/node-preset-groups` → your preset folders/sections, in display\n * order. Pass `nodeType` to filter to one node type.\n */\n async listGroups(nodeType?: string): Promise<NodePresetGroup[]> {\n const qs = nodeType ? `?nodeType=${encodeURIComponent(nodeType)}` : \"\"\n const res = await this.client.request<{ data: NodePresetGroup[] }>(\"GET\", `/v1/node-preset-groups${qs}`)\n return res.data\n }\n\n /**\n * `GET /v1/node-presets/factory` → the built-in catalog for `nodeType`. These\n * ship with the app (no account needed to exist), so they're a good starting\n * point for \"what configs are available\".\n *\n * Login is optional: the catalog is public, so this works on a client with\n * no credential at all (`auth: { getToken: async () => null }`) — show the\n * names, example pictures (`previewUrl`) and photo counts (`minReferences`,\n * `needsImage`) to a visitor who is not signed in, and ask for a login only\n * when they generate. Your OWN presets (`list()`) still need a token.\n */\n listFactory(nodeType: string): Promise<FactoryPresetsResult> {\n return this.client.request<FactoryPresetsResult>(\n \"GET\",\n `/v1/node-presets/factory?nodeType=${encodeURIComponent(nodeType)}`,\n )\n }\n\n /** `POST /v1/node-presets` → the new preset. */\n async create(input: CreateNodePresetInput): Promise<NodePreset> {\n const res = await this.client.request<{ data: NodePreset }>(\"POST\", \"/v1/node-presets\", { body: input })\n return res.data\n }\n\n /**\n * `PATCH /v1/node-presets/:id` → the updated preset. Pass the `updatedAt` you\n * read as `expectedUpdatedAt` to refuse (409 `conflict`) a change made\n * elsewhere since.\n */\n async update(id: string, patch: UpdateNodePresetInput, opts: { expectedUpdatedAt?: string } = {}): Promise<NodePreset> {\n const body = opts.expectedUpdatedAt ? { ...patch, expectedUpdatedAt: opts.expectedUpdatedAt } : patch\n const res = await this.client.request<{ data: NodePreset }>(\"PATCH\", `/v1/node-presets/${encodeURIComponent(id)}`, { body })\n return res.data\n }\n\n /** `DELETE /v1/node-presets/:id` (404 when it is not yours). `expectedUpdatedAt` as on `update`. */\n async delete(id: string, opts: { expectedUpdatedAt?: string } = {}): Promise<{ success: true }> {\n const res = await this.client.request<{ data: { success: true } }>(\"DELETE\", `/v1/node-presets/${encodeURIComponent(id)}`, {\n query: { expectedUpdatedAt: opts.expectedUpdatedAt },\n })\n return res.data\n }\n\n /**\n * `POST /v1/node-presets/import` — up to 500 presets in one call. A name you\n * already use gets an \"(imported N)\" suffix; a preset whose data is empty\n * after stripping runtime keys is skipped.\n */\n async import(presets: ImportNodePresetInput[]): Promise<{ imported: number }> {\n const res = await this.client.request<{ data: { imported: number } }>(\"POST\", \"/v1/node-presets/import\", { body: { presets } })\n return res.data\n }\n\n /** `POST /v1/node-presets/reorder` — positions (and group membership) for many presets and groups at once. */\n async reorder(input: ReorderNodePresetsInput): Promise<{ ok: true }> {\n const res = await this.client.request<{ data: { ok: true } }>(\"POST\", \"/v1/node-presets/reorder\", { body: input })\n return res.data\n }\n\n /** `GET /v1/node-presets/favorites` → your favorite preset ids for `nodeType`, newest first. */\n async favorites(nodeType: string): Promise<string[]> {\n const res = await this.client.request<{ data: string[] }>(\"GET\", \"/v1/node-presets/favorites\", { query: { nodeType } })\n return res.data\n }\n\n /** `POST /v1/node-presets/favorites` — idempotent. */\n async addFavorite(input: NodePresetFavoriteInput): Promise<{ success: true }> {\n const res = await this.client.request<{ data: { success: true } }>(\"POST\", \"/v1/node-presets/favorites\", { body: input })\n return res.data\n }\n\n /** `DELETE /v1/node-presets/favorites` — idempotent. */\n async removeFavorite(input: NodePresetFavoriteInput): Promise<{ success: true }> {\n const res = await this.client.request<{ data: { success: true } }>(\"DELETE\", \"/v1/node-presets/favorites\", {\n query: { nodeType: input.nodeType, presetId: input.presetId },\n })\n return res.data\n }\n\n /** `POST /v1/node-preset-groups` → the new folder or section. */\n async createGroup(input: CreateNodePresetGroupInput): Promise<NodePresetGroup> {\n const res = await this.client.request<{ data: NodePresetGroup }>(\"POST\", \"/v1/node-preset-groups\", { body: input })\n return res.data\n }\n\n /** `PATCH /v1/node-preset-groups/:id` → the renamed or moved group. */\n async updateGroup(id: string, patch: UpdateNodePresetGroupInput): Promise<NodePresetGroup> {\n const res = await this.client.request<{ data: NodePresetGroup }>(\"PATCH\", `/v1/node-preset-groups/${encodeURIComponent(id)}`, {\n body: patch,\n })\n return res.data\n }\n\n /** `DELETE /v1/node-preset-groups/:id` — its presets move out of the group; none are deleted. */\n async deleteGroup(id: string): Promise<{ success: true }> {\n const res = await this.client.request<{ data: { success: true } }>(\"DELETE\", `/v1/node-preset-groups/${encodeURIComponent(id)}`)\n return res.data\n }\n}\n"]}
@@ -100,5 +100,5 @@ var TrendsResource = class {
100
100
  };
101
101
 
102
102
  exports.TrendsResource = TrendsResource;
103
- //# sourceMappingURL=chunk-DIF7A5OH.cjs.map
104
- //# sourceMappingURL=chunk-DIF7A5OH.cjs.map
103
+ //# sourceMappingURL=chunk-E5MJK3W5.cjs.map
104
+ //# sourceMappingURL=chunk-E5MJK3W5.cjs.map