@nodaro/sdk 2.31.0 → 2.33.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{chunk-XQAIEPAZ.js → chunk-4CXB7RA6.js} +2 -2
- package/dist/chunk-4CXB7RA6.js.map +1 -0
- package/dist/{chunk-REUFPWM7.cjs → chunk-56NJIP7P.cjs} +3 -3
- package/dist/{chunk-REUFPWM7.cjs.map → chunk-56NJIP7P.cjs.map} +1 -1
- package/dist/{chunk-I4A5VJRL.js → chunk-5A7J24LN.js} +68 -20
- package/dist/chunk-5A7J24LN.js.map +1 -0
- package/dist/{chunk-QITJGSFA.js → chunk-6ECW23GA.js} +6 -2
- package/dist/chunk-6ECW23GA.js.map +1 -0
- package/dist/{chunk-RAZN6C5R.cjs → chunk-6T54F65Q.cjs} +2 -2
- package/dist/{chunk-PHKYIWE4.cjs.map → chunk-6T54F65Q.cjs.map} +1 -1
- package/dist/{chunk-PHKYIWE4.cjs → chunk-7CK6I4CT.cjs} +2 -2
- package/dist/{chunk-RAZN6C5R.cjs.map → chunk-7CK6I4CT.cjs.map} +1 -1
- package/dist/{chunk-BFMKPELU.cjs → chunk-B7RG6AUQ.cjs} +6 -2
- package/dist/chunk-B7RG6AUQ.cjs.map +1 -0
- package/dist/{chunk-7ISSKQ6S.cjs → chunk-GB724HW2.cjs} +2 -2
- package/dist/chunk-GB724HW2.cjs.map +1 -0
- package/dist/{chunk-UI2NXUML.cjs → chunk-GKQSA24K.cjs} +10 -10
- package/dist/{chunk-UI2NXUML.cjs.map → chunk-GKQSA24K.cjs.map} +1 -1
- package/dist/{chunk-5WAI7VGO.js → chunk-JSCC2N7N.js} +6 -6
- package/dist/{chunk-5WAI7VGO.js.map → chunk-JSCC2N7N.js.map} +1 -1
- package/dist/{chunk-WUIEZ6Z4.cjs → chunk-RHJRLXKY.cjs} +68 -20
- package/dist/chunk-RHJRLXKY.cjs.map +1 -0
- package/dist/chunk-UKB64254.js +3 -0
- package/dist/{chunk-W7YI5UT3.js.map → chunk-UKB64254.js.map} +1 -1
- package/dist/{chunk-LHP2CWHD.js → chunk-Y5CYFNNW.js} +3 -3
- package/dist/{chunk-LHP2CWHD.js.map → chunk-Y5CYFNNW.js.map} +1 -1
- package/dist/chunk-ZYPH2FPT.js +3 -0
- package/dist/{chunk-ZH4F2P2G.js.map → chunk-ZYPH2FPT.js.map} +1 -1
- package/dist/entries/characters.d.cts +1 -1
- package/dist/entries/characters.d.ts +1 -1
- package/dist/entries/client.cjs +10 -10
- package/dist/entries/client.d.cts +1 -1
- package/dist/entries/client.d.ts +1 -1
- package/dist/entries/client.js +5 -5
- package/dist/entries/core.cjs +5 -5
- package/dist/entries/core.js +1 -1
- package/dist/entries/creatures.d.cts +1 -1
- package/dist/entries/creatures.d.ts +1 -1
- package/dist/entries/credits.cjs +2 -2
- package/dist/entries/credits.d.cts +8 -0
- package/dist/entries/credits.d.ts +8 -0
- package/dist/entries/credits.js +1 -1
- package/dist/entries/edit.cjs +8 -8
- package/dist/entries/edit.d.cts +134 -24
- package/dist/entries/edit.d.ts +134 -24
- package/dist/entries/edit.js +2 -2
- package/dist/entries/locations.d.cts +1 -1
- package/dist/entries/locations.d.ts +1 -1
- package/dist/entries/nodes.cjs +5 -5
- package/dist/entries/nodes.d.cts +2 -2
- package/dist/entries/nodes.d.ts +2 -2
- package/dist/entries/nodes.js +2 -2
- package/dist/entries/objects.d.cts +1 -1
- package/dist/entries/objects.d.ts +1 -1
- package/dist/entries/scene3d.d.cts +2 -2
- package/dist/entries/scene3d.d.ts +2 -2
- package/dist/index.cjs +23 -23
- package/dist/index.d.cts +3 -3
- package/dist/index.d.ts +3 -3
- package/dist/index.js +7 -7
- package/dist/{nodes-C2zu3uqn.d.ts → nodes-C-wrO6Sg.d.ts} +106 -6
- package/dist/{nodes-BPvrAoUs.d.cts → nodes-J8ByUN8z.d.cts} +106 -6
- package/package.json +2 -2
- package/dist/chunk-7ISSKQ6S.cjs.map +0 -1
- package/dist/chunk-BFMKPELU.cjs.map +0 -1
- package/dist/chunk-I4A5VJRL.js.map +0 -1
- package/dist/chunk-QITJGSFA.js.map +0 -1
- package/dist/chunk-W7YI5UT3.js +0 -3
- package/dist/chunk-WUIEZ6Z4.cjs.map +0 -1
- package/dist/chunk-XQAIEPAZ.js.map +0 -1
- package/dist/chunk-ZH4F2P2G.js +0 -3
|
@@ -100,5 +100,5 @@ var CreditsResource = class {
|
|
|
100
100
|
};
|
|
101
101
|
|
|
102
102
|
export { CreditsResource };
|
|
103
|
-
//# sourceMappingURL=chunk-
|
|
104
|
-
//# sourceMappingURL=chunk-
|
|
103
|
+
//# sourceMappingURL=chunk-4CXB7RA6.js.map
|
|
104
|
+
//# sourceMappingURL=chunk-4CXB7RA6.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/resources/credits.ts"],"names":[],"mappings":";AAmLA,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,EAQA,WAAW,GAAA,EAA0C;AACnD,IAAA,OAAO,IAAA,CAAK,MAAA,CAAO,OAAA,CAA0B,MAAA,EAAQ,yBAAA,EAA2B;AAAA,MAC9E,MAAM,EAAE,MAAA,EAAQ,IAAI,KAAA,CAAM,CAAA,EAAG,iBAAiB,CAAA;AAAE,KACjD,CAAA;AAAA,EACH;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAcA,gBAAA,CAAiB,IAAA,GAAmB,EAAC,EAAoC;AACvE,IAAA,OAAO,IAAA,CAAK,MAAA,CAAO,OAAA,CAAgC,MAAA,EAAQ,gCAAA,EAAkC;AAAA,MAC3F,IAAA,EAAM;AAAA,KACP,CAAA;AAAA,EACH;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;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;AASF","file":"chunk-4CXB7RA6.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\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/** 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 * `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 (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 } }`), 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"]}
|
|
@@ -36,7 +36,7 @@ async function readBinaryResponse(response, maxBytes) {
|
|
|
36
36
|
}
|
|
37
37
|
return bytes.buffer;
|
|
38
38
|
}
|
|
39
|
-
var SDK_VERSION = "2.
|
|
39
|
+
var SDK_VERSION = "2.33.0" ;
|
|
40
40
|
var CLIENT_HEADER = "X-Nodaro-Client";
|
|
41
41
|
var isBrowser = () => typeof window !== "undefined" && typeof window.document !== "undefined";
|
|
42
42
|
var NodaroClientCore = class {
|
|
@@ -229,5 +229,5 @@ exports.CallbackAuth = CallbackAuth;
|
|
|
229
229
|
exports.NodaroClientCore = NodaroClientCore;
|
|
230
230
|
exports.StaticTokenAuth = StaticTokenAuth;
|
|
231
231
|
exports.supabaseAuth = supabaseAuth;
|
|
232
|
-
//# sourceMappingURL=chunk-
|
|
233
|
-
//# sourceMappingURL=chunk-
|
|
232
|
+
//# sourceMappingURL=chunk-56NJIP7P.cjs.map
|
|
233
|
+
//# sourceMappingURL=chunk-56NJIP7P.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/binary-response.ts","../src/core.ts","../src/auth.ts"],"names":["WORKSPACE_HEADER","throwFromResponse"],"mappings":";;;;;;AACA,eAAsB,kBAAA,CAAmB,UAAoB,QAAA,EAAwC;AACnG,EAAA,MAAM,UAAA,GAAa,QAAA,CAAS,OAAA,CAAQ,GAAA,CAAI,gBAAgB,CAAA;AACxD,EAAA,IAAI,UAAA,KAAe,IAAA,KAAS,CAAC,OAAA,CAAQ,IAAA,CAAK,UAAU,CAAA,IAAK,MAAA,CAAO,UAAU,CAAA,GAAI,QAAA,CAAA,EAAW;AACvF,IAAA,MAAM,QAAA,CAAS,MAAM,MAAA,EAAO;AAC5B,IAAA,MAAM,IAAI,MAAM,iDAAiD,CAAA;AAAA,EACnE;AACA,EAAA,IAAI,CAAC,QAAA,CAAS,IAAA,EAAM,OAAO,IAAI,YAAY,CAAC,CAAA;AAC5C,EAAA,MAAM,MAAA,GAAS,QAAA,CAAS,IAAA,CAAK,SAAA,EAAU;AACvC,EAAA,MAAM,SAAuB,EAAC;AAC9B,EAAA,IAAI,MAAA,GAAS,CAAA;AACb,EAAA,IAAI;AACF,IAAA,OAAO,IAAA,EAAM;AACX,MAAA,MAAM,IAAA,GAAO,MAAM,MAAA,CAAO,IAAA,EAAK;AAC/B,MAAA,IAAI,KAAK,IAAA,EAAM;AACf,MAAA,MAAA,IAAU,KAAK,KAAA,CAAM,UAAA;AACrB,MAAA,IAAI,SAAS,QAAA,EAAU;AACrB,QAAA,MAAM,OAAO,MAAA,EAAO;AACpB,QAAA,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AACf,IAAA,OAAO,IAAA,CAAK,KAAA;AAAA,EACd;AACF;AAEO,IAAM,eAAN,MAAmC;AAAA,EACxC,YAAoB,EAAA,EAAkD;AAAlD,IAAA,IAAA,CAAA,EAAA,GAAA,EAAA;AAAA,EAAmD;AAAA,EAAnD,EAAA;AAAA,EACpB,MAAM,QAAA,GAAW;AACf,IAAA,OAAO,KAAK,EAAA,EAAG;AAAA,EACjB;AACF;AASO,SAAS,aAAa,QAAA,EAAoC;AAC/D,EAAA,OAAO;AAAA,IACL,MAAM,QAAA,GAAW;AACf,MAAA,MAAM,EAAE,IAAA,EAAK,GAAI,MAAM,QAAA,CAAS,KAAK,UAAA,EAAW;AAChD,MAAA,OAAO,IAAA,CAAK,SAAS,YAAA,IAAgB,IAAA;AAAA,IACvC;AAAA,GACF;AACF","file":"chunk-REUFPWM7.cjs","sourcesContent":["/** Bound decoded response bytes even when Content-Length is absent or compressed. */\nexport async function readBinaryResponse(response: Response, maxBytes: number): Promise<ArrayBuffer> {\n const advertised = response.headers.get(\"content-length\")\n if (advertised !== null && (!/^\\d+$/.test(advertised) || Number(advertised) > maxBytes)) {\n await response.body?.cancel()\n throw new Error(\"Binary response exceeds its declared size limit\")\n }\n if (!response.body) return new ArrayBuffer(0)\n const reader = response.body.getReader()\n const chunks: Uint8Array[] = []\n let length = 0\n try {\n while (true) {\n const next = await reader.read()\n if (next.done) break\n length += next.value.byteLength\n if (length > maxBytes) {\n await reader.cancel()\n throw new Error(\"Binary response exceeds its declared size limit\")\n }\n chunks.push(next.value)\n }\n } finally { reader.releaseLock() }\n const bytes = new Uint8Array(length)\n let offset = 0\n for (const chunk of chunks) { bytes.set(chunk, offset); offset += chunk.byteLength }\n return bytes.buffer\n}\n","/**\n * The client core: configuration, auth, the request transport and the\n * account-identity calls — everything a resource needs, and none of the\n * resources themselves.\n *\n * {@link NodaroClient} (`createClient`) extends it with every resource. An app\n * that uses only a few resources can extend it with just those, so it loads\n * (and its tests depend on) only the resource modules it actually uses:\n *\n * class AppClient extends NodaroClientCore {\n * readonly jobs = new JobsResource(this)\n * readonly nodes = new NodesResource(this) // needs `jobs` on the same client\n * }\n *\n * A resource that calls another one through the client says so in its\n * constructor type (`NodesResource` takes a core that also has `jobs`), so a\n * client missing it fails to compile rather than at run time.\n */\nimport { readBinaryResponse } from \"./binary-response.js\"\nimport { throwFromResponse } from \"./errors.js\"\nimport type { Auth } from \"./auth.js\"\nimport type { DeveloperAppKind, DeveloperAppScope } from \"./resources/developer-apps.js\"\nimport { WORKSPACE_HEADER, type MeOrganizations } from \"@nodaro/shared/organizations\"\n\n/** Replaced at build time by tsup `define` from package.json. The fallback\n * keeps `tsx`/vitest runs of the source working, where no define applies. */\ndeclare const __SDK_VERSION__: string | undefined\nconst SDK_VERSION = typeof __SDK_VERSION__ === \"string\" ? __SDK_VERSION__ : \"0.0.0-dev\"\n\n/**\n * Identifies the calling package to the backend, which records it as the job's\n * provenance (`jobs.source` / `source_detail`) so an operator can tell a CLI\n * run from an SDK integration from a browser session.\n *\n * Only `sdk/…` and `cli/…` are honoured server-side; anything else is ignored\n * rather than trusted, since this is an unauthenticated header.\n */\nexport const CLIENT_HEADER = \"X-Nodaro-Client\"\n\n/**\n * In a browser the header is redundant AND a liability, so it is not sent.\n *\n * Redundant: the browser already sends `Origin`, which names the actual product\n * (`studio.nodaro.ai`) rather than merely the library it used — and the backend\n * deliberately prefers Origin over this header, so a browser-sent value is\n * discarded on arrival.\n *\n * A liability: `X-Nodaro-Client` is not a CORS-safelisted request header, so a\n * browser sending it requires an exact match in the server's\n * `Access-Control-Allow-Headers`. Any deployment whose backend predates that\n * allowlist entry would fail the PREFLIGHT — breaking every API call from the\n * app, not just its provenance. Self-hosted and lagging deployments make that a\n * real risk, and nothing in a browser app would reveal the cause.\n *\n * An EXPLICIT `clientLabel` is always sent regardless: a caller that names\n * itself has opted in deliberately, and that intent outranks this default.\n */\nconst isBrowser = (): boolean => typeof window !== \"undefined\" && typeof window.document !== \"undefined\"\n\nexport interface ClientOptions {\n /** Backend base URL, e.g. \"https://nodaro.example.com\" or empty string for same-origin. */\n baseUrl: string\n /** Auth provider. Use StaticTokenAuth, supabaseAuth, or CallbackAuth. */\n auth: Auth\n /** Optional fetch override (for tests or custom transports). */\n fetch?: typeof fetch\n /** Default request timeout in ms. Default 60s. */\n timeoutMs?: number\n /**\n * Overrides the `X-Nodaro-Client` label. Defaults to `sdk/<version>`.\n *\n * Exists for `@nodaro/cli`, which is a wrapper AROUND this SDK: without an\n * override every CLI invocation would be recorded as an SDK call and the two\n * surfaces could never be told apart.\n */\n clientLabel?: string\n /**\n * The workspace every request acts in — sent as `X-Nodaro-Workspace`.\n *\n * It selects which workspace a LIST reads from and where a CREATE lands.\n * It never authorizes: reading, updating, deleting or running an\n * identified object is decided by that object's own workspace, so a\n * forgotten header cannot hide work and a forged one cannot reach anyone\n * else's. Omit it to work in the caller's personal space.\n *\n * Prefer {@link NodaroClient.withWorkspace} for anything short-lived — one\n * client per workspace, no shared mutable selection to get wrong.\n */\n workspaceId?: string\n}\n\ninterface RequestOptions {\n body?: unknown\n query?: Record<string, string | number | boolean | undefined>\n headers?: Record<string, string>\n signal?: AbortSignal\n}\n\n/**\n * The authenticated user's canonical identity (`GET /v1/me`). A token-\n * introspection primitive: any valid bearer token (first-party Supabase JWT or\n * a developer-app OAuth token) resolves to its owner's identity. Mirrors the\n * `profiles` identity columns server-side — the route is the source of truth.\n */\nexport interface UserIdentity {\n /** Nodaro user id (= the Supabase auth user id). */\n readonly id: string\n readonly email: string\n /** Human-readable display name (from `profiles.full_name`); `null` if unset. */\n readonly displayName: string | null\n /** Avatar URL; `null` if unset. */\n readonly avatarUrl: string | null\n /** Subscription tier (e.g. \"free\", \"pro\"). */\n readonly tier: string\n /**\n * Whether the user holds an admin role. DESCRIPTIVE only — use it to decide\n * whether to render admin surfaces without capability-probing an admin\n * endpoint; every admin API stays enforced server-side regardless.\n */\n readonly isAdmin: boolean\n}\n\n/**\n * An app the user let into their account through OAuth (`GET\n * /v1/me/connected-apps`): a developer app, an AI assistant's MCP connector, or\n * a self-hosted install. One entry per grant still in force.\n */\nexport interface ConnectedApp {\n /** The grant's id — what {@link NodaroClient.revokeConnectedApp} takes. */\n readonly authorizationId: string\n /** The app's name; `null` if it has none. A `dynamic_mcp` client chose its own. */\n readonly name: string | null\n /**\n * How the app came to exist: `user` (a developer app someone registered),\n * `first_party_mcp`, `dynamic_mcp` (an MCP client that registered itself) or\n * `community_instance` (a self-hosted install).\n */\n readonly kind: DeveloperAppKind | (string & {})\n readonly homepageUrl: string | null\n /** The scopes this grant holds. */\n readonly scopes: readonly DeveloperAppScope[]\n /** When the user granted access (ISO 8601). */\n readonly connectedAt: string\n /** The latest use of any token issued under the grant; `null` if never used. */\n readonly lastUsedAt: string | null\n}\n\nexport class NodaroClientCore {\n readonly baseUrl: string\n readonly auth: Auth\n readonly timeoutMs: number\n /** Value sent as `X-Nodaro-Client`; recorded by the backend as job provenance. */\n readonly clientLabel: string\n /** Whether to actually send it — see the note on {@link CLIENT_HEADER}. */\n private readonly sendClientHeader: boolean\n private readonly fetchOverride: typeof fetch | undefined\n\n /**\n * Resolved lazily so consumers can swap `globalThis.fetch` after the\n * client has been constructed (e.g. test mocks). Always rebound to the\n * global object — native fetch throws \"Illegal invocation\" when its\n * `this` is anything else.\n */\n get fetch(): typeof fetch {\n return this.fetchOverride ?? globalThis.fetch.bind(globalThis)\n }\n\n /** The workspace this client acts in; undefined = the personal space. */\n readonly workspaceId: string | undefined\n\n constructor(opts: ClientOptions) {\n this.baseUrl = opts.baseUrl.replace(/\\/$/, \"\") // strip trailing slash\n this.auth = opts.auth\n this.fetchOverride = opts.fetch\n this.timeoutMs = opts.timeoutMs ?? 60_000\n this.clientLabel = opts.clientLabel ?? `sdk/${SDK_VERSION}`\n this.workspaceId = opts.workspaceId\n // Explicit label = deliberate opt-in, always sent. The default is suppressed\n // in browsers — see the note on CLIENT_HEADER.\n this.sendClientHeader = opts.clientLabel !== undefined || !isBrowser()\n }\n\n /**\n * The transport: build the request, send it, throw the typed error on a\n * non-2xx via {@link throwFromResponse}, then read the body via `read` — all\n * inside the abort timer, so `timeoutMs` bounds the body download too (a\n * stalled CSV stream aborts, it does not hang forever). Both the JSON path\n * ({@link request}) and the text path ({@link requestText}) go through here.\n */\n private async send<T>(\n method: string,\n path: string,\n options: RequestOptions,\n read: (res: Response) => Promise<T>,\n ): Promise<T> {\n const url = this.buildUrl(path, options.query)\n\n const token = await this.auth.getToken()\n // A `FormData` body is a multipart upload: let the runtime set\n // `Content-Type: multipart/form-data; boundary=…` itself (a manual JSON\n // content-type corrupts the boundary), and send the body as-is rather than\n // JSON-stringifying it. Every other body stays JSON, exactly as before.\n const isFormData =\n typeof FormData !== \"undefined\" && options.body instanceof FormData\n const headers: Record<string, string> = {\n ...(isFormData ? {} : { \"Content-Type\": \"application/json\" }),\n ...(this.sendClientHeader ? { [CLIENT_HEADER]: this.clientLabel } : {}),\n // Before per-request headers: a resource that needs to reach outside\n // this client's workspace says so explicitly and wins.\n ...(this.workspaceId ? { [WORKSPACE_HEADER]: this.workspaceId } : {}),\n ...(options.headers ?? {}),\n }\n if (token) headers[\"Authorization\"] = `Bearer ${token}`\n\n const ac = new AbortController()\n const timeoutId = setTimeout(() => ac.abort(), this.timeoutMs)\n const abort = () => ac.abort(options.signal?.reason)\n options.signal?.addEventListener(\"abort\", abort, { once: true })\n if (options.signal?.aborted) abort()\n\n try {\n ac.signal.throwIfAborted()\n const res = await this.fetch(url, {\n method,\n headers,\n body:\n options.body === undefined\n ? undefined\n : isFormData\n ? (options.body as FormData)\n : JSON.stringify(options.body),\n signal: ac.signal,\n })\n\n if (!res.ok) {\n let errBody: Record<string, unknown> = {}\n try {\n errBody = await res.json() as Record<string, unknown>\n } catch {\n // Empty/non-JSON body — fall through with empty errBody\n }\n throwFromResponse(res.status, errBody)\n }\n\n return await read(res)\n } finally {\n clearTimeout(timeoutId)\n options.signal?.removeEventListener(\"abort\", abort)\n }\n }\n\n /** Authenticated, bounded binary reads through the normal timeout/error transport. */\n async requestBytes(method: string, path: string, options: RequestOptions & { maxBytes: number }): Promise<ArrayBuffer> {\n if (!Number.isSafeInteger(options.maxBytes) || options.maxBytes < 1) throw new Error(\"maxBytes must be a positive integer\")\n return this.send(method, path, options, (response) => readBinaryResponse(response, options.maxBytes))\n }\n\n async request<T>(method: string, path: string, options: RequestOptions = {}): Promise<T> {\n return this.send(method, path, options, async (res) =>\n // 204 No Content\n res.status === 204 ? (undefined as T) : ((await res.json()) as T),\n )\n }\n\n /**\n * Like {@link request}, for endpoints that answer text (CSV exports). Errors\n * are still the JSON envelope and throw the same typed errors, and the read is\n * bounded by the same timeout as the request.\n */\n async requestText(method: string, path: string, options: RequestOptions = {}): Promise<string> {\n return this.send(method, path, options, (res) => res.text())\n }\n\n /**\n * `GET /v1/me` → the authenticated user's identity (see {@link UserIdentity}).\n * Unwraps the `{ data }` envelope. Throws `UnauthorizedError` (401) when the\n * token is missing/invalid, and the SDK's other typed errors as usual.\n *\n * On an instance with organizations it also carries what the caller belongs\n * to. THREE states, and collapsing them is wrong in a way users feel: the\n * organization fields ABSENT means this instance has no organizations at\n * all; present and empty means the account belongs to none; and\n * `organizationsUnavailable` means the lookup failed — keep whatever\n * selection you already had rather than concluding the person was removed\n * from everything.\n */\n async me(): Promise<UserIdentity & MeOrganizations> {\n const res = await this.request<{ data: UserIdentity & MeOrganizations }>(\"GET\", \"/v1/me\")\n return res.data\n }\n\n /**\n * `GET /v1/me/connected-apps` → every app with access to the signed-in\n * user's account (see {@link ConnectedApp}), newest grant first.\n *\n * **A signed-in browser session only.** The route answers a Supabase\n * session token (`supabaseAuth(…)`, `createSharedSupabaseClient`, or a\n * `StaticTokenAuth` holding one) and refuses every other credential with\n * `UnauthorizedError` (\"Sign in required\"): an app token or an API key must\n * not list the grants it lives under. Build your \"Connected apps\" settings\n * screen on this; a server-side integration cannot call it.\n */\n async connectedApps(): Promise<ConnectedApp[]> {\n const res = await this.request<{ apps: ConnectedApp[] }>(\"GET\", \"/v1/me/connected-apps\")\n return res.apps\n }\n\n /**\n * `POST /v1/me/connected-apps/:authorizationId/revoke` — ends an app's\n * access: the grant and every token issued under it, at once (the app's next\n * call is a 401). Resolves when done.\n *\n * A signed-in browser session only, like {@link connectedApps}. Throws\n * `NotFoundError` when the grant is not the user's or is already revoked.\n */\n async revokeConnectedApp(authorizationId: string): Promise<void> {\n await this.request(\"POST\", `/v1/me/connected-apps/${encodeURIComponent(authorizationId)}/revoke`)\n }\n\n private buildUrl(path: string, query?: Record<string, string | number | boolean | undefined>): string {\n const base = this.baseUrl || (typeof window !== \"undefined\" ? window.location.origin : \"http://placeholder\")\n const url = new URL(path, base)\n // If baseUrl was empty, strip the placeholder origin\n const fullUrl = this.baseUrl ? url.toString() : url.pathname + url.search\n if (query) {\n const u = new URL(this.baseUrl ? fullUrl : fullUrl, base)\n for (const [k, v] of Object.entries(query)) {\n if (v !== undefined) u.searchParams.set(k, String(v))\n }\n return this.baseUrl ? u.toString() : u.pathname + u.search\n }\n return fullUrl\n }\n}\n","/**\n * Auth provides the token used for `Authorization: Bearer <token>` on each request.\n * Implementations:\n * - StaticTokenAuth — fixed string (server-side, OAuth access token, API token)\n * - CallbackAuth — caller-supplied async function (BYO logic)\n * - supabaseAuth — pulls JWT from a Supabase client live (browser frontends)\n */\nexport interface Auth {\n /** Returns the current Bearer token, or null if not authenticated. */\n getToken(): Promise<string | null>\n}\n\nexport class StaticTokenAuth implements Auth {\n constructor(private token: string) {}\n async getToken() {\n return this.token\n }\n}\n\nexport class CallbackAuth implements Auth {\n constructor(private fn: () => string | null | Promise<string | null>) {}\n async getToken() {\n return this.fn()\n }\n}\n\ninterface SupabaseLikeClient {\n auth: {\n getSession(): Promise<{ data: { session: { access_token: string } | null } }>\n }\n}\n\n/** Pulls a JWT from a Supabase v2 client. Caller supplies their own supabase. */\nexport function supabaseAuth(supabase: SupabaseLikeClient): Auth {\n return {\n async getToken() {\n const { data } = await supabase.auth.getSession()\n return data.session?.access_token ?? null\n },\n }\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/binary-response.ts","../src/core.ts","../src/auth.ts"],"names":["WORKSPACE_HEADER","throwFromResponse"],"mappings":";;;;;;AACA,eAAsB,kBAAA,CAAmB,UAAoB,QAAA,EAAwC;AACnG,EAAA,MAAM,UAAA,GAAa,QAAA,CAAS,OAAA,CAAQ,GAAA,CAAI,gBAAgB,CAAA;AACxD,EAAA,IAAI,UAAA,KAAe,IAAA,KAAS,CAAC,OAAA,CAAQ,IAAA,CAAK,UAAU,CAAA,IAAK,MAAA,CAAO,UAAU,CAAA,GAAI,QAAA,CAAA,EAAW;AACvF,IAAA,MAAM,QAAA,CAAS,MAAM,MAAA,EAAO;AAC5B,IAAA,MAAM,IAAI,MAAM,iDAAiD,CAAA;AAAA,EACnE;AACA,EAAA,IAAI,CAAC,QAAA,CAAS,IAAA,EAAM,OAAO,IAAI,YAAY,CAAC,CAAA;AAC5C,EAAA,MAAM,MAAA,GAAS,QAAA,CAAS,IAAA,CAAK,SAAA,EAAU;AACvC,EAAA,MAAM,SAAuB,EAAC;AAC9B,EAAA,IAAI,MAAA,GAAS,CAAA;AACb,EAAA,IAAI;AACF,IAAA,OAAO,IAAA,EAAM;AACX,MAAA,MAAM,IAAA,GAAO,MAAM,MAAA,CAAO,IAAA,EAAK;AAC/B,MAAA,IAAI,KAAK,IAAA,EAAM;AACf,MAAA,MAAA,IAAU,KAAK,KAAA,CAAM,UAAA;AACrB,MAAA,IAAI,SAAS,QAAA,EAAU;AACrB,QAAA,MAAM,OAAO,MAAA,EAAO;AACpB,QAAA,MAAM,IAAI,MAAM,iDAAiD,CAAA;AAAA,MACnE;AACA,MAAA,MAAA,CAAO,IAAA,CAAK,KAAK,KAAK,CAAA;AAAA,IACxB;AAAA,EACF,CAAA,SAAE;AAAU,IAAA,MAAA,CAAO,WAAA,EAAY;AAAA,EAAE;AACjC,EAAA,MAAM,KAAA,GAAQ,IAAI,UAAA,CAAW,MAAM,CA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AAA,EAAG;AAAA,EACjB;AACF;AASO,SAAS,aAAa,QAAA,EAAoC;AAC/D,EAAA,OAAO;AAAA,IACL,MAAM,QAAA,GAAW;AACf,MAAA,MAAM,EAAE,IAAA,EAAK,GAAI,MAAM,QAAA,CAAS,KAAK,UAAA,EAAW;AAChD,MAAA,OAAO,IAAA,CAAK,SAAS,YAAA,IAAgB,IAAA;AAAA,IACvC;AAAA,GACF;AACF","file":"chunk-56NJIP7P.cjs","sourcesContent":["/** Bound decoded response bytes even when Content-Length is absent or compressed. */\nexport async function readBinaryResponse(response: Response, maxBytes: number): Promise<ArrayBuffer> {\n const advertised = response.headers.get(\"content-length\")\n if (advertised !== null && (!/^\\d+$/.test(advertised) || Number(advertised) > maxBytes)) {\n await response.body?.cancel()\n throw new Error(\"Binary response exceeds its declared size limit\")\n }\n if (!response.body) return new ArrayBuffer(0)\n const reader = response.body.getReader()\n const chunks: Uint8Array[] = []\n let length = 0\n try {\n while (true) {\n const next = await reader.read()\n if (next.done) break\n length += next.value.byteLength\n if (length > maxBytes) {\n await reader.cancel()\n throw new Error(\"Binary response exceeds its declared size limit\")\n }\n chunks.push(next.value)\n }\n } finally { reader.releaseLock() }\n const bytes = new Uint8Array(length)\n let offset = 0\n for (const chunk of chunks) { bytes.set(chunk, offset); offset += chunk.byteLength }\n return bytes.buffer\n}\n","/**\n * The client core: configuration, auth, the request transport and the\n * account-identity calls — everything a resource needs, and none of the\n * resources themselves.\n *\n * {@link NodaroClient} (`createClient`) extends it with every resource. An app\n * that uses only a few resources can extend it with just those, so it loads\n * (and its tests depend on) only the resource modules it actually uses:\n *\n * class AppClient extends NodaroClientCore {\n * readonly jobs = new JobsResource(this)\n * readonly nodes = new NodesResource(this) // needs `jobs` on the same client\n * }\n *\n * A resource that calls another one through the client says so in its\n * constructor type (`NodesResource` takes a core that also has `jobs`), so a\n * client missing it fails to compile rather than at run time.\n */\nimport { readBinaryResponse } from \"./binary-response.js\"\nimport { throwFromResponse } from \"./errors.js\"\nimport type { Auth } from \"./auth.js\"\nimport type { DeveloperAppKind, DeveloperAppScope } from \"./resources/developer-apps.js\"\nimport { WORKSPACE_HEADER, type MeOrganizations } from \"@nodaro/shared/organizations\"\n\n/** Replaced at build time by tsup `define` from package.json. The fallback\n * keeps `tsx`/vitest runs of the source working, where no define applies. */\ndeclare const __SDK_VERSION__: string | undefined\nconst SDK_VERSION = typeof __SDK_VERSION__ === \"string\" ? __SDK_VERSION__ : \"0.0.0-dev\"\n\n/**\n * Identifies the calling package to the backend, which records it as the job's\n * provenance (`jobs.source` / `source_detail`) so an operator can tell a CLI\n * run from an SDK integration from a browser session.\n *\n * Only `sdk/…` and `cli/…` are honoured server-side; anything else is ignored\n * rather than trusted, since this is an unauthenticated header.\n */\nexport const CLIENT_HEADER = \"X-Nodaro-Client\"\n\n/**\n * In a browser the header is redundant AND a liability, so it is not sent.\n *\n * Redundant: the browser already sends `Origin`, which names the actual product\n * (`studio.nodaro.ai`) rather than merely the library it used — and the backend\n * deliberately prefers Origin over this header, so a browser-sent value is\n * discarded on arrival.\n *\n * A liability: `X-Nodaro-Client` is not a CORS-safelisted request header, so a\n * browser sending it requires an exact match in the server's\n * `Access-Control-Allow-Headers`. Any deployment whose backend predates that\n * allowlist entry would fail the PREFLIGHT — breaking every API call from the\n * app, not just its provenance. Self-hosted and lagging deployments make that a\n * real risk, and nothing in a browser app would reveal the cause.\n *\n * An EXPLICIT `clientLabel` is always sent regardless: a caller that names\n * itself has opted in deliberately, and that intent outranks this default.\n */\nconst isBrowser = (): boolean => typeof window !== \"undefined\" && typeof window.document !== \"undefined\"\n\nexport interface ClientOptions {\n /** Backend base URL, e.g. \"https://nodaro.example.com\" or empty string for same-origin. */\n baseUrl: string\n /** Auth provider. Use StaticTokenAuth, supabaseAuth, or CallbackAuth. */\n auth: Auth\n /** Optional fetch override (for tests or custom transports). */\n fetch?: typeof fetch\n /** Default request timeout in ms. Default 60s. */\n timeoutMs?: number\n /**\n * Overrides the `X-Nodaro-Client` label. Defaults to `sdk/<version>`.\n *\n * Exists for `@nodaro/cli`, which is a wrapper AROUND this SDK: without an\n * override every CLI invocation would be recorded as an SDK call and the two\n * surfaces could never be told apart.\n */\n clientLabel?: string\n /**\n * The workspace every request acts in — sent as `X-Nodaro-Workspace`.\n *\n * It selects which workspace a LIST reads from and where a CREATE lands.\n * It never authorizes: reading, updating, deleting or running an\n * identified object is decided by that object's own workspace, so a\n * forgotten header cannot hide work and a forged one cannot reach anyone\n * else's. Omit it to work in the caller's personal space.\n *\n * Prefer {@link NodaroClient.withWorkspace} for anything short-lived — one\n * client per workspace, no shared mutable selection to get wrong.\n */\n workspaceId?: string\n}\n\ninterface RequestOptions {\n body?: unknown\n query?: Record<string, string | number | boolean | undefined>\n headers?: Record<string, string>\n signal?: AbortSignal\n}\n\n/**\n * The authenticated user's canonical identity (`GET /v1/me`). A token-\n * introspection primitive: any valid bearer token (first-party Supabase JWT or\n * a developer-app OAuth token) resolves to its owner's identity. Mirrors the\n * `profiles` identity columns server-side — the route is the source of truth.\n */\nexport interface UserIdentity {\n /** Nodaro user id (= the Supabase auth user id). */\n readonly id: string\n readonly email: string\n /** Human-readable display name (from `profiles.full_name`); `null` if unset. */\n readonly displayName: string | null\n /** Avatar URL; `null` if unset. */\n readonly avatarUrl: string | null\n /** Subscription tier (e.g. \"free\", \"pro\"). */\n readonly tier: string\n /**\n * Whether the user holds an admin role. DESCRIPTIVE only — use it to decide\n * whether to render admin surfaces without capability-probing an admin\n * endpoint; every admin API stays enforced server-side regardless.\n */\n readonly isAdmin: boolean\n}\n\n/**\n * An app the user let into their account through OAuth (`GET\n * /v1/me/connected-apps`): a developer app, an AI assistant's MCP connector, or\n * a self-hosted install. One entry per grant still in force.\n */\nexport interface ConnectedApp {\n /** The grant's id — what {@link NodaroClient.revokeConnectedApp} takes. */\n readonly authorizationId: string\n /** The app's name; `null` if it has none. A `dynamic_mcp` client chose its own. */\n readonly name: string | null\n /**\n * How the app came to exist: `user` (a developer app someone registered),\n * `first_party_mcp`, `dynamic_mcp` (an MCP client that registered itself) or\n * `community_instance` (a self-hosted install).\n */\n readonly kind: DeveloperAppKind | (string & {})\n readonly homepageUrl: string | null\n /** The scopes this grant holds. */\n readonly scopes: readonly DeveloperAppScope[]\n /** When the user granted access (ISO 8601). */\n readonly connectedAt: string\n /** The latest use of any token issued under the grant; `null` if never used. */\n readonly lastUsedAt: string | null\n}\n\nexport class NodaroClientCore {\n readonly baseUrl: string\n readonly auth: Auth\n readonly timeoutMs: number\n /** Value sent as `X-Nodaro-Client`; recorded by the backend as job provenance. */\n readonly clientLabel: string\n /** Whether to actually send it — see the note on {@link CLIENT_HEADER}. */\n private readonly sendClientHeader: boolean\n private readonly fetchOverride: typeof fetch | undefined\n\n /**\n * Resolved lazily so consumers can swap `globalThis.fetch` after the\n * client has been constructed (e.g. test mocks). Always rebound to the\n * global object — native fetch throws \"Illegal invocation\" when its\n * `this` is anything else.\n */\n get fetch(): typeof fetch {\n return this.fetchOverride ?? globalThis.fetch.bind(globalThis)\n }\n\n /** The workspace this client acts in; undefined = the personal space. */\n readonly workspaceId: string | undefined\n\n constructor(opts: ClientOptions) {\n this.baseUrl = opts.baseUrl.replace(/\\/$/, \"\") // strip trailing slash\n this.auth = opts.auth\n this.fetchOverride = opts.fetch\n this.timeoutMs = opts.timeoutMs ?? 60_000\n this.clientLabel = opts.clientLabel ?? `sdk/${SDK_VERSION}`\n this.workspaceId = opts.workspaceId\n // Explicit label = deliberate opt-in, always sent. The default is suppressed\n // in browsers — see the note on CLIENT_HEADER.\n this.sendClientHeader = opts.clientLabel !== undefined || !isBrowser()\n }\n\n /**\n * The transport: build the request, send it, throw the typed error on a\n * non-2xx via {@link throwFromResponse}, then read the body via `read` — all\n * inside the abort timer, so `timeoutMs` bounds the body download too (a\n * stalled CSV stream aborts, it does not hang forever). Both the JSON path\n * ({@link request}) and the text path ({@link requestText}) go through here.\n */\n private async send<T>(\n method: string,\n path: string,\n options: RequestOptions,\n read: (res: Response) => Promise<T>,\n ): Promise<T> {\n const url = this.buildUrl(path, options.query)\n\n const token = await this.auth.getToken()\n // A `FormData` body is a multipart upload: let the runtime set\n // `Content-Type: multipart/form-data; boundary=…` itself (a manual JSON\n // content-type corrupts the boundary), and send the body as-is rather than\n // JSON-stringifying it. Every other body stays JSON, exactly as before.\n const isFormData =\n typeof FormData !== \"undefined\" && options.body instanceof FormData\n const headers: Record<string, string> = {\n ...(isFormData ? {} : { \"Content-Type\": \"application/json\" }),\n ...(this.sendClientHeader ? { [CLIENT_HEADER]: this.clientLabel } : {}),\n // Before per-request headers: a resource that needs to reach outside\n // this client's workspace says so explicitly and wins.\n ...(this.workspaceId ? { [WORKSPACE_HEADER]: this.workspaceId } : {}),\n ...(options.headers ?? {}),\n }\n if (token) headers[\"Authorization\"] = `Bearer ${token}`\n\n const ac = new AbortController()\n const timeoutId = setTimeout(() => ac.abort(), this.timeoutMs)\n const abort = () => ac.abort(options.signal?.reason)\n options.signal?.addEventListener(\"abort\", abort, { once: true })\n if (options.signal?.aborted) abort()\n\n try {\n ac.signal.throwIfAborted()\n const res = await this.fetch(url, {\n method,\n headers,\n body:\n options.body === undefined\n ? undefined\n : isFormData\n ? (options.body as FormData)\n : JSON.stringify(options.body),\n signal: ac.signal,\n })\n\n if (!res.ok) {\n let errBody: Record<string, unknown> = {}\n try {\n errBody = await res.json() as Record<string, unknown>\n } catch {\n // Empty/non-JSON body — fall through with empty errBody\n }\n throwFromResponse(res.status, errBody)\n }\n\n return await read(res)\n } finally {\n clearTimeout(timeoutId)\n options.signal?.removeEventListener(\"abort\", abort)\n }\n }\n\n /** Authenticated, bounded binary reads through the normal timeout/error transport. */\n async requestBytes(method: string, path: string, options: RequestOptions & { maxBytes: number }): Promise<ArrayBuffer> {\n if (!Number.isSafeInteger(options.maxBytes) || options.maxBytes < 1) throw new Error(\"maxBytes must be a positive integer\")\n return this.send(method, path, options, (response) => readBinaryResponse(response, options.maxBytes))\n }\n\n async request<T>(method: string, path: string, options: RequestOptions = {}): Promise<T> {\n return this.send(method, path, options, async (res) =>\n // 204 No Content\n res.status === 204 ? (undefined as T) : ((await res.json()) as T),\n )\n }\n\n /**\n * Like {@link request}, for endpoints that answer text (CSV exports). Errors\n * are still the JSON envelope and throw the same typed errors, and the read is\n * bounded by the same timeout as the request.\n */\n async requestText(method: string, path: string, options: RequestOptions = {}): Promise<string> {\n return this.send(method, path, options, (res) => res.text())\n }\n\n /**\n * `GET /v1/me` → the authenticated user's identity (see {@link UserIdentity}).\n * Unwraps the `{ data }` envelope. Throws `UnauthorizedError` (401) when the\n * token is missing/invalid, and the SDK's other typed errors as usual.\n *\n * On an instance with organizations it also carries what the caller belongs\n * to. THREE states, and collapsing them is wrong in a way users feel: the\n * organization fields ABSENT means this instance has no organizations at\n * all; present and empty means the account belongs to none; and\n * `organizationsUnavailable` means the lookup failed — keep whatever\n * selection you already had rather than concluding the person was removed\n * from everything.\n */\n async me(): Promise<UserIdentity & MeOrganizations> {\n const res = await this.request<{ data: UserIdentity & MeOrganizations }>(\"GET\", \"/v1/me\")\n return res.data\n }\n\n /**\n * `GET /v1/me/connected-apps` → every app with access to the signed-in\n * user's account (see {@link ConnectedApp}), newest grant first.\n *\n * **A signed-in browser session only.** The route answers a Supabase\n * session token (`supabaseAuth(…)`, `createSharedSupabaseClient`, or a\n * `StaticTokenAuth` holding one) and refuses every other credential with\n * `UnauthorizedError` (\"Sign in required\"): an app token or an API key must\n * not list the grants it lives under. Build your \"Connected apps\" settings\n * screen on this; a server-side integration cannot call it.\n */\n async connectedApps(): Promise<ConnectedApp[]> {\n const res = await this.request<{ apps: ConnectedApp[] }>(\"GET\", \"/v1/me/connected-apps\")\n return res.apps\n }\n\n /**\n * `POST /v1/me/connected-apps/:authorizationId/revoke` — ends an app's\n * access: the grant and every token issued under it, at once (the app's next\n * call is a 401). Resolves when done.\n *\n * A signed-in browser session only, like {@link connectedApps}. Throws\n * `NotFoundError` when the grant is not the user's or is already revoked.\n */\n async revokeConnectedApp(authorizationId: string): Promise<void> {\n await this.request(\"POST\", `/v1/me/connected-apps/${encodeURIComponent(authorizationId)}/revoke`)\n }\n\n private buildUrl(path: string, query?: Record<string, string | number | boolean | undefined>): string {\n const base = this.baseUrl || (typeof window !== \"undefined\" ? window.location.origin : \"http://placeholder\")\n const url = new URL(path, base)\n // If baseUrl was empty, strip the placeholder origin\n const fullUrl = this.baseUrl ? url.toString() : url.pathname + url.search\n if (query) {\n const u = new URL(this.baseUrl ? fullUrl : fullUrl, base)\n for (const [k, v] of Object.entries(query)) {\n if (v !== undefined) u.searchParams.set(k, String(v))\n }\n return this.baseUrl ? u.toString() : u.pathname + u.search\n }\n return fullUrl\n }\n}\n","/**\n * Auth provides the token used for `Authorization: Bearer <token>` on each request.\n * Implementations:\n * - StaticTokenAuth — fixed string (server-side, OAuth access token, API token)\n * - CallbackAuth — caller-supplied async function (BYO logic)\n * - supabaseAuth — pulls JWT from a Supabase client live (browser frontends)\n */\nexport interface Auth {\n /** Returns the current Bearer token, or null if not authenticated. */\n getToken(): Promise<string | null>\n}\n\nexport class StaticTokenAuth implements Auth {\n constructor(private token: string) {}\n async getToken() {\n return this.token\n }\n}\n\nexport class CallbackAuth implements Auth {\n constructor(private fn: () => string | null | Promise<string | null>) {}\n async getToken() {\n return this.fn()\n }\n}\n\ninterface SupabaseLikeClient {\n auth: {\n getSession(): Promise<{ data: { session: { access_token: string } | null } }>\n }\n}\n\n/** Pulls a JWT from a Supabase v2 client. Caller supplies their own supabase. */\nexport function supabaseAuth(supabase: SupabaseLikeClient): Auth {\n return {\n async getToken() {\n const { data } = await supabase.auth.getSession()\n return data.session?.access_token ?? null\n },\n }\n}\n"]}
|
|
@@ -7,21 +7,44 @@ export { USE_CASE_NODE_TYPES } from '@nodaro/shared/nodes';
|
|
|
7
7
|
var TRAILER_FORMATS = ["9:16", "1:1", "4:5", "16:9"];
|
|
8
8
|
var CLIP_PACK_MIN_TARGET_SEC = 5;
|
|
9
9
|
var CLIP_PACK_MAX_TARGET_SEC = 180;
|
|
10
|
+
function withRecordings(input) {
|
|
11
|
+
const { mediaUrl, mediaUrls, masterAudioUrl, cameras, ...rest } = input;
|
|
12
|
+
if (mediaUrl !== void 0 && mediaUrls !== void 0) throw new TypeError("pass mediaUrl or mediaUrls, not both");
|
|
13
|
+
const recordings = mediaUrls ?? (mediaUrl !== void 0 ? [mediaUrl] : void 0);
|
|
14
|
+
if (!recordings) throw new TypeError("pass mediaUrl or mediaUrls");
|
|
15
|
+
return {
|
|
16
|
+
mediaUrls: [...recordings],
|
|
17
|
+
...masterAudioUrl !== void 0 ? { masterAudioUrl } : {},
|
|
18
|
+
...cameras !== void 0 ? { cameras } : {},
|
|
19
|
+
...Object.fromEntries(Object.entries(rest).filter(([, v]) => v !== void 0))
|
|
20
|
+
};
|
|
21
|
+
}
|
|
22
|
+
function withUseCaseBody(build, send) {
|
|
23
|
+
let body;
|
|
24
|
+
try {
|
|
25
|
+
body = build();
|
|
26
|
+
} catch (err) {
|
|
27
|
+
return Promise.reject(err);
|
|
28
|
+
}
|
|
29
|
+
return send(body);
|
|
30
|
+
}
|
|
10
31
|
function tightenBody(input) {
|
|
11
|
-
|
|
12
|
-
return { mediaUrls: [mediaUrl], ...Object.fromEntries(Object.entries(rest).filter(([, v]) => v !== void 0)) };
|
|
32
|
+
return withRecordings(input);
|
|
13
33
|
}
|
|
14
34
|
function chaptersBody(input) {
|
|
15
|
-
return {
|
|
16
|
-
|
|
35
|
+
return withRecordings({
|
|
36
|
+
mediaUrl: input.mediaUrl,
|
|
17
37
|
...input.planTier !== void 0 ? { planTier: input.planTier } : {},
|
|
18
38
|
...input.instructions !== void 0 ? { instructions: input.instructions } : {},
|
|
19
39
|
...input.styleGuide !== void 0 ? { styleGuide: input.styleGuide } : {}
|
|
20
|
-
};
|
|
40
|
+
});
|
|
21
41
|
}
|
|
22
42
|
function trailerBody(input) {
|
|
23
|
-
return {
|
|
24
|
-
|
|
43
|
+
return withRecordings({
|
|
44
|
+
mediaUrl: input.mediaUrl,
|
|
45
|
+
mediaUrls: input.mediaUrls,
|
|
46
|
+
masterAudioUrl: input.masterAudioUrl,
|
|
47
|
+
cameras: input.cameras,
|
|
25
48
|
...input.introCardUrl !== void 0 ? { introCardUrl: input.introCardUrl } : {},
|
|
26
49
|
// An empty list is sent as is: the route refuses it (at least one format).
|
|
27
50
|
...input.formats !== void 0 ? { formats: input.formats } : {},
|
|
@@ -29,11 +52,13 @@ function trailerBody(input) {
|
|
|
29
52
|
...input.planTier !== void 0 ? { planTier: input.planTier } : {},
|
|
30
53
|
...input.instructions !== void 0 ? { instructions: input.instructions } : {},
|
|
31
54
|
...input.styleGuide !== void 0 ? { styleGuide: input.styleGuide } : {}
|
|
32
|
-
};
|
|
55
|
+
});
|
|
33
56
|
}
|
|
34
57
|
function clipPackBody(input) {
|
|
35
|
-
|
|
36
|
-
|
|
58
|
+
return withRecordings(input);
|
|
59
|
+
}
|
|
60
|
+
function speakerLayoutBody(input) {
|
|
61
|
+
return withRecordings(input);
|
|
37
62
|
}
|
|
38
63
|
var continuePathOf = (type) => `/v1/${type}/continue`;
|
|
39
64
|
function idempotencyHeaders(options) {
|
|
@@ -127,7 +152,7 @@ var EditResource = class {
|
|
|
127
152
|
* {@link estimateTightenEpisode}.
|
|
128
153
|
*/
|
|
129
154
|
tightenEpisode(input, options) {
|
|
130
|
-
return this.client.request("POST", "/v1/tighten-episode", { body
|
|
155
|
+
return withUseCaseBody(() => tightenBody(input), (body) => this.client.request("POST", "/v1/tighten-episode", { body, ...idempotencyHeaders(options) }));
|
|
131
156
|
}
|
|
132
157
|
/**
|
|
133
158
|
* What a Tighten Episode run is estimated at (`POST /v1/tighten-episode/estimate`):
|
|
@@ -136,7 +161,7 @@ var EditResource = class {
|
|
|
136
161
|
* full length, while the charge follows the minutes actually rendered.
|
|
137
162
|
*/
|
|
138
163
|
estimateTightenEpisode(input) {
|
|
139
|
-
return this.client.request("POST", "/v1/tighten-episode/estimate", { body
|
|
164
|
+
return withUseCaseBody(() => tightenBody(input), (body) => this.client.request("POST", "/v1/tighten-episode/estimate", { body }));
|
|
140
165
|
}
|
|
141
166
|
/**
|
|
142
167
|
* Chapters (`POST /v1/episode-chapters`): transcribe a recording and list its
|
|
@@ -149,7 +174,7 @@ var EditResource = class {
|
|
|
149
174
|
* listed per-run fee; quote it first with {@link estimateEpisodeChapters}.
|
|
150
175
|
*/
|
|
151
176
|
episodeChapters(input, options) {
|
|
152
|
-
return this.client.request("POST", "/v1/episode-chapters", { body
|
|
177
|
+
return withUseCaseBody(() => chaptersBody(input), (body) => this.client.request("POST", "/v1/episode-chapters", { body, ...idempotencyHeaders(options) }));
|
|
153
178
|
}
|
|
154
179
|
/**
|
|
155
180
|
* What a Chapters run is estimated at (`POST /v1/episode-chapters/estimate`):
|
|
@@ -158,7 +183,7 @@ var EditResource = class {
|
|
|
158
183
|
* 180-minute ceiling.
|
|
159
184
|
*/
|
|
160
185
|
estimateEpisodeChapters(input) {
|
|
161
|
-
return this.client.request("POST", "/v1/episode-chapters/estimate", { body
|
|
186
|
+
return withUseCaseBody(() => chaptersBody(input), (body) => this.client.request("POST", "/v1/episode-chapters/estimate", { body }));
|
|
162
187
|
}
|
|
163
188
|
/**
|
|
164
189
|
* Trailer (`POST /v1/episode-trailer`): cut a 20–40 s trailer of a recording
|
|
@@ -171,7 +196,7 @@ var EditResource = class {
|
|
|
171
196
|
* the listed per-run fee; quote it first with {@link estimateEpisodeTrailer}.
|
|
172
197
|
*/
|
|
173
198
|
episodeTrailer(input, options) {
|
|
174
|
-
return this.client.request("POST", "/v1/episode-trailer", { body
|
|
199
|
+
return withUseCaseBody(() => trailerBody(input), (body) => this.client.request("POST", "/v1/episode-trailer", { body, ...idempotencyHeaders(options) }));
|
|
175
200
|
}
|
|
176
201
|
/**
|
|
177
202
|
* What a Trailer run is estimated at (`POST /v1/episode-trailer/estimate`):
|
|
@@ -181,7 +206,7 @@ var EditResource = class {
|
|
|
181
206
|
* review's edits), plus the intro card.
|
|
182
207
|
*/
|
|
183
208
|
estimateEpisodeTrailer(input) {
|
|
184
|
-
return this.client.request("POST", "/v1/episode-trailer/estimate", { body
|
|
209
|
+
return withUseCaseBody(() => trailerBody(input), (body) => this.client.request("POST", "/v1/episode-trailer/estimate", { body }));
|
|
185
210
|
}
|
|
186
211
|
/**
|
|
187
212
|
* Clip Pack (`POST /v1/clip-pack`): cut a recording into a pack of short
|
|
@@ -202,7 +227,7 @@ var EditResource = class {
|
|
|
202
227
|
* quote it first with {@link estimateClipPack}.
|
|
203
228
|
*/
|
|
204
229
|
clipPack(input, options) {
|
|
205
|
-
return this.client.request("POST", "/v1/clip-pack", { body
|
|
230
|
+
return withUseCaseBody(() => clipPackBody(input), (body) => this.client.request("POST", "/v1/clip-pack", { body, ...idempotencyHeaders(options) }));
|
|
206
231
|
}
|
|
207
232
|
/**
|
|
208
233
|
* What a Clip Pack run is estimated at (`POST /v1/clip-pack/estimate`): its
|
|
@@ -211,7 +236,30 @@ var EditResource = class {
|
|
|
211
236
|
* a clip longer than asked); the charge follows each clip's real length.
|
|
212
237
|
*/
|
|
213
238
|
estimateClipPack(input) {
|
|
214
|
-
return this.client.request("POST", "/v1/clip-pack/estimate", { body
|
|
239
|
+
return withUseCaseBody(() => clipPackBody(input), (body) => this.client.request("POST", "/v1/clip-pack/estimate", { body }));
|
|
240
|
+
}
|
|
241
|
+
/**
|
|
242
|
+
* Speaker Layout (`POST /v1/speaker-layout`): frame a whole recording by
|
|
243
|
+
* speaker in one call — the same length, nothing cut. One recording: each
|
|
244
|
+
* speaker framed in turn; several recordings of one conversation: lined up,
|
|
245
|
+
* each speaker shown on their own camera. The finished job's
|
|
246
|
+
* `output_data.videoUrl` is the framed video, `output_data.json` the edit
|
|
247
|
+
* Speaker View drew. With `reviewBeforeRender` the run stops at a preview;
|
|
248
|
+
* {@link continueUseCase} (`mode: "render-final"`, no `editedEdl`) renders
|
|
249
|
+
* it at full quality. Priced as its steps at their own rates plus the listed
|
|
250
|
+
* per-run fee; quote it first with {@link estimateSpeakerLayout}.
|
|
251
|
+
*/
|
|
252
|
+
speakerLayout(input, options) {
|
|
253
|
+
return withUseCaseBody(() => speakerLayoutBody(input), (body) => this.client.request("POST", "/v1/speaker-layout", { body, ...idempotencyHeaders(options) }));
|
|
254
|
+
}
|
|
255
|
+
/**
|
|
256
|
+
* What a Speaker Layout run is estimated at (`POST /v1/speaker-layout/estimate`):
|
|
257
|
+
* its steps at their own rates plus its per-run fee. Nothing is created or
|
|
258
|
+
* charged. A recording whose length cannot be read is estimated at the
|
|
259
|
+
* 180-minute ceiling.
|
|
260
|
+
*/
|
|
261
|
+
estimateSpeakerLayout(input) {
|
|
262
|
+
return withUseCaseBody(() => speakerLayoutBody(input), (body) => this.client.request("POST", "/v1/speaker-layout/estimate", { body }));
|
|
215
263
|
}
|
|
216
264
|
/**
|
|
217
265
|
* Continue a use-case run as a new job (`POST /v1/<type>/continue`, the
|
|
@@ -348,5 +396,5 @@ var EditResource = class {
|
|
|
348
396
|
};
|
|
349
397
|
|
|
350
398
|
export { CLIP_PACK_MAX_TARGET_SEC, CLIP_PACK_MIN_TARGET_SEC, EditResource, TRAILER_FORMATS };
|
|
351
|
-
//# sourceMappingURL=chunk-
|
|
352
|
-
//# sourceMappingURL=chunk-
|
|
399
|
+
//# sourceMappingURL=chunk-5A7J24LN.js.map
|
|
400
|
+
//# sourceMappingURL=chunk-5A7J24LN.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/resources/edit-use-case-inputs.ts","../src/resources/edit.ts"],"names":[],"mappings":";;;;;;AA+GO,IAAM,eAAA,GAAkB,CAAC,MAAA,EAAQ,KAAA,EAAO,OAAO,MAAM;AA4BrD,IAAM,wBAAA,GAA2B;AACjC,IAAM,wBAAA,GAA2B;AAyGxC,SAAS,eAAiD,KAAA,EAAmC;AAC3F,EAAA,MAAM,EAAE,QAAA,EAAU,SAAA,EAAW,gBAAgB,OAAA,EAAS,GAAG,MAAK,GAAI,KAAA;AAClE,EAAA,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,GAAY,EAAE,YAAA,EAAc,KAAA,CAAM,YAAA,EAAa,GAAI,EAAC;AAAA,QAC/E,GAAI,MAAM,SAAA,KAAc,MAAA,GAAY,EAAE,SAAA,EAAW,KAAA,CAAM,SAAA,EAAU,GAAI,EAAC;AAAA,QACtE,GAAI,MAAM,MAAA,KAAW,MAAA,GAAY,EAAE,MAAA,EAAQ,KAAA,CAAM,MAAA,EAAO,GAAI,EAAC;AAAA,QAC7D,GAAI,MAAM,SAAA,KAAc,MAAA,GAAY,EAAE,SAAA,EAAW,KAAA,CAAM,SAAA,EAAU,GAAI,EAAC;AAAA,QACtE,GAAI,MAAM,SAAA,KAAc,MAAA,GAAY,EAAE,SAAA,EAAW,KAAA,CAAM,SAAA,EAAU,GAAI,EAAC;AAAA,QACtE,GAAI,MAAM,WAAA,KAAgB,MAAA,GAAY,EAAE,WAAA,EAAa,KAAA,CAAM,WAAA,EAAY,GAAI,EAAC;AAAA,QAC5E,GAAI,MAAM,UAAA,KAAe,MAAA,GAAY,EAAE,UAAA,EAAY,KAAA,CAAM,UAAA,EAAW,GAAI;AAAC;AAC3E,KACD,CAAA;AAAA,EACH;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EASA,eAAA,CAAgB,KAAU,UAAA,EAAoC;AAC5D,IAAA,OAAO,yBAAA,CAA0B,KAAK,UAAU,CAAA;AAAA,EAClD;AACF","file":"chunk-5A7J24LN.js","sourcesContent":["/**\n * The inputs of the podcast use-case runs on the `edit` resource (Tighten\n * Episode, Chapters, Trailer, Clip Pack, Speaker Layout) and the request body each one sends.\n * Split from `edit.ts`, which holds the methods, the type list and the\n * continue routes; every name here is re-exported from there.\n */\nimport type { EditPlanTier, EdlTargetAspect, SpeakerEmphasisStyle, SpeakerSwitchId } from \"@nodaro/shared/edl\"\nimport type { CaptionStyle } from \"@nodaro/shared/captions\"\n\n/**\n * The recordings of a use-case run: one (`mediaUrl`), or the recordings of one\n * conversation (`mediaUrls`, in order — the cameras; one may be sound only),\n * an optional Master audio and the Cameras settings. Pass `mediaUrl` or\n * `mediaUrls`, not both.\n *\n * Several recordings or a Master audio need Speaker Map, which tells who is on\n * which camera: where it is not available to you (not yet on nodaro.ai) the\n * request is refused `403 node_not_available` — send one recording.\n */\nexport interface UseCaseRecordingsInput {\n /** The recording — a video or audio URL, up to 3 hours. */\n mediaUrl?: string\n /**\n * Instead of `mediaUrl`: the recordings of one conversation, in order — up\n * to six in all with the Master audio; without one, two or more cameras keep\n * a place for the sound, so up to five. With two or more the run lines them\n * up, works out who is on which camera and cuts to whoever is talking.\n */\n mediaUrls?: string[]\n /** The mixer or recorder track: the episode's sound and the clock the recordings are lined up to. */\n masterAudioUrl?: string\n /** With several recordings or a Master audio: the Cameras settings (ignored with one recording and no Master audio). */\n cameras?: {\n /** Which recording (1-based) is the wide shot, shown when a speaker has no camera of their own; `null` for none. */\n wide?: number | null\n /** The recordings already share one clock: skip lining them up. */\n synced?: boolean\n /** Who is on which camera: speaker number (`\"1\"` = the first voice heard) → recording number, 0 = the wide shot. Overrides the automatic map. */\n speakerCameras?: Record<string, number>\n }\n}\n\n/**\n * Input for {@link EditResource.tightenEpisode} and\n * {@link EditResource.estimateTightenEpisode}: the recording (or the\n * recordings of one conversation, see {@link UseCaseRecordingsInput}) in, the\n * tightened episode out. Only the recording is required; every other field\n * left out takes the node's default.\n */\nexport interface TightenEpisodeInput extends UseCaseRecordingsInput {\n /** Optional music bed, ducked under the voice and ending with the episode. */\n musicUrl?: string\n /** `\"video\"` or `\"audio\"`; an audio recording always makes an audio episode. */\n output?: \"video\" | \"audio\"\n /**\n * Frame a video episode with Speaker View: an output aspect and a layout,\n * over automatic boxes on the speakers on screen. A layout the aspect does\n * not draw is snapped to one it does. `null` or absent: no framing.\n */\n framing?: {\n aspect: EdlTargetAspect\n layout: \"auto\" | \"single\" | \"side-by-side\" | \"stacked\" | \"grid\" | \"pip\"\n } | null\n /**\n * With a framing, how it follows the speakers: `\"static\"` (the default)\n * splits the frame evenly by speaker; `\"tracking\"` follows faces with\n * Speaker Frames (charged per started block of 1,000 sampled frames; a\n * camera shared by several speakers keeps the even split until faces are\n * named; refused 403 where Speaker Frames is not available to the caller);\n * `\"auto\"` follows faces while Speaker Frames is available to the caller,\n * else the even split. Ignored without a framing.\n */\n framingSource?: \"auto\" | \"static\" | \"tracking\"\n /** Captions on a video episode (on by default). */\n captions?: boolean\n /** The captions' look. */\n captionStyle?: CaptionStyle\n /**\n * Stop at a quick preview for a person to review; render the full-quality\n * episode afterwards with {@link EditResource.continueUseCase}\n * (`mode: \"render-final\"`).\n */\n reviewBeforeRender?: boolean\n /** The planner's tier. */\n planTier?: EditPlanTier\n /** Editing instructions for the planner (up to 4 000 characters). */\n instructions?: string\n /** A style guide for the planner (up to 4 000 characters). */\n styleGuide?: string\n /** How far the music dips under the voice, 0–100 (default 75). */\n musicDuckAmount?: number\n}\n\n/**\n * Input for {@link EditResource.episodeChapters} and\n * {@link EditResource.estimateEpisodeChapters}: one recording in, its chapters\n * out. Only `mediaUrl` is required; every other field left out takes the\n * node's default.\n */\nexport interface EpisodeChaptersInput {\n /** The recording — a video or audio URL, up to 3 hours. */\n mediaUrl: string\n /** The planner's tier (default `\"economy\"`). */\n planTier?: EditPlanTier\n /** Instructions for the chapters, e.g. \"5 to 8 chapters\" (up to 4 000 characters). */\n instructions?: string\n /** A style guide for the chapter titles (up to 4 000 characters). */\n styleGuide?: string\n}\n\n/** The formats a Trailer is delivered in, in delivery order (16:9 is a 1920×1080 landscape). */\nexport const TRAILER_FORMATS = [\"9:16\", \"1:1\", \"4:5\", \"16:9\"] as const\n/** One Trailer format (see {@link TRAILER_FORMATS}). */\nexport type TrailerFormat = (typeof TRAILER_FORMATS)[number]\n\n/**\n * Input for {@link EditResource.episodeTrailer} and\n * {@link EditResource.estimateEpisodeTrailer}: one video recording (or the\n * recordings of one conversation, see {@link UseCaseRecordingsInput}) in, a\n * 20–40 s trailer out in each chosen format. Only the recording is required.\n */\nexport interface EpisodeTrailerInput extends UseCaseRecordingsInput {\n /** The recording — a video URL, up to 3 hours (a run with no picture is refused). Or `mediaUrls`. */\n mediaUrl?: string\n /** An optional intro card: a short video (15 s at most) played before the trailer. */\n introCardUrl?: string\n /** The formats to deliver, padded, never cropped (default `[\"9:16\", \"1:1\", \"4:5\"]`; an empty list is refused). */\n formats?: TrailerFormat[]\n /** Stop at a preview of the trailer; render every format with {@link EditResource.continueUseCase} (`mode: \"render-final\"`). */\n reviewBeforeRender?: boolean\n /** The planner's tier (default `\"standard\"`). */\n planTier?: EditPlanTier\n /** Instructions for the trailer (up to 4 000 characters). */\n instructions?: string\n /** A style guide for the planner (up to 4 000 characters). */\n styleGuide?: string\n}\n\n/** The shortest and longest clip a Clip Pack asks the plan for, in seconds. */\nexport const CLIP_PACK_MIN_TARGET_SEC = 5\nexport const CLIP_PACK_MAX_TARGET_SEC = 180\n\n/**\n * A Clip Pack emphasis: `\"none\"`, or one or more of `\"scale\"`, `\"border\"` and\n * `\"dim\"` joined with `\"+\"` (each once — the route refuses a repeat).\n */\nexport type ClipPackEmphasis = SpeakerEmphasisStyle | `${Exclude<SpeakerEmphasisStyle, \"none\">}+${string}`\n\n/**\n * Input for {@link EditResource.clipPack} and\n * {@link EditResource.estimateClipPack}: the recording (or the recordings of\n * one conversation, see {@link UseCaseRecordingsInput} — each clip then cuts\n * to whoever is talking) in, a pack of short clips out. An audio recording\n * makes audio clips (no framing, no captions). Only the recording is\n * required; every other field left out takes the node's default.\n */\nexport interface ClipPackInput extends UseCaseRecordingsInput {\n /** How many clips to find, 1–50 (default 8). The plan may find fewer. */\n count?: number\n /** Each clip's target length in seconds, {@link CLIP_PACK_MIN_TARGET_SEC}–{@link CLIP_PACK_MAX_TARGET_SEC} (default 60). */\n targetDurationSec?: number\n /**\n * Frame each video clip with Speaker View on automatic boxes over the\n * episode's speakers: the shape, and optionally the layout (default\n * `\"stacked\"`; one the shape does not draw is snapped), the switch at each\n * speaker change (default `\"pan\"`) and the emphasis (default `\"scale\"`;\n * `\"none\"`, or `\"scale\"`, `\"border\"` and `\"dim\"` joined with `\"+\"`). Left\n * out: 9:16, stacked, pan, scale. `null`: no framing (the recording's shape).\n */\n framing?: {\n aspect: EdlTargetAspect\n layout?: \"auto\" | \"single\" | \"side-by-side\" | \"stacked\" | \"grid\" | \"pip\"\n switchType?: SpeakerSwitchId\n emphasisStyle?: ClipPackEmphasis\n } | null\n /**\n * With a framing, how it follows the speakers: `\"static\"` splits the frame\n * evenly by speaker (what a request that leaves this out gets); `\"tracking\"`\n * runs Speaker Frames once over the whole pack to follow faces (charged per\n * started block of 1,000 sampled frames; refused 403 where Speaker Frames is\n * not available to the caller); `\"auto\"` follows faces while Speaker Frames\n * is available to the caller, else the even split. Ignored without a framing.\n */\n framingSource?: \"auto\" | \"static\" | \"tracking\"\n /** Caption each video clip (on by default). */\n captions?: boolean\n /** The captions' look (default `\"karaoke\"`). */\n captionStyle?: CaptionStyle\n /**\n * Stop at quick previews of the clips for a person to review; render the\n * kept clips at full quality with {@link EditResource.continueUseCase}\n * (`mode: \"render-final\"`, an `editedEdl` that keeps or drops clips).\n */\n reviewBeforeRender?: boolean\n /** The planner's tier (default `\"standard\"`). */\n planTier?: EditPlanTier\n /** Instructions for picking the clips (up to 4 000 characters). */\n instructions?: string\n /** A style guide for the planner (up to 4 000 characters). */\n styleGuide?: string\n}\n\n/**\n * Input for {@link EditResource.speakerLayout} and\n * {@link EditResource.estimateSpeakerLayout}: one video recording (or the\n * recordings of one conversation, see {@link UseCaseRecordingsInput}) in, the\n * whole recording framed by speaker out — the same length, nothing cut. Only\n * the recording is required; every other field left out takes the node's\n * default.\n */\nexport interface SpeakerLayoutInput extends UseCaseRecordingsInput {\n /** The recording — a video URL, up to 3 hours (an audio-only recording is refused). Or `mediaUrls`. */\n mediaUrl?: string\n /** The video's shape (default `\"9:16\"`). With one recording, a video already as narrow as the shape (or narrower) is refused `400 media_shape`. */\n targetAspect?: EdlTargetAspect\n /** How the speakers are laid out (default `\"stacked\"`; one the shape does not draw is snapped to one it does). */\n layout?: \"auto\" | \"single\" | \"side-by-side\" | \"stacked\" | \"grid\" | \"pip\"\n /** The switch at each speaker change (default `\"cut\"`). */\n switchType?: SpeakerSwitchId\n /** How the speaker talking is emphasised (default `\"scale\"`): `\"none\"`, or `\"scale\"`, `\"border\"` and `\"dim\"` joined with `\"+\"`. */\n emphasisStyle?: ClipPackEmphasis\n /**\n * How the speakers are followed: `\"auto\"` (the default) follows faces with\n * Speaker Frames while it is available to the caller, else splits the frame\n * evenly; `\"static\"` splits the frame evenly by speaker; `\"tracking\"`\n * follows faces (charged per started block of 1,000 sampled frames;\n * refused 403 where Speaker Frames is not available to the caller). Faces\n * aren't named after a speaker yet, so a camera shared by several speakers\n * keeps the even split.\n */\n framingSource?: \"auto\" | \"static\" | \"tracking\"\n /**\n * Stop at a quick preview for a person to review; render it at full\n * quality with {@link EditResource.continueUseCase}\n * (`mode: \"render-final\"`, no `editedEdl`: the layout has no cut to change).\n */\n reviewBeforeRender?: boolean\n}\n\n/**\n * The body's recordings (`mediaUrls`, then `masterAudioUrl` and `cameras` when\n * given), and the rest of the input as it came: the one mapper every use-case\n * body goes through. Throws before any request when the input names both\n * `mediaUrl` and `mediaUrls`, or neither.\n */\nfunction withRecordings<T extends UseCaseRecordingsInput>(input: T): Record<string, unknown> {\n const { mediaUrl, mediaUrls, masterAudioUrl, cameras, ...rest } = input\n if (mediaUrl !== undefined && mediaUrls !== undefined) throw new TypeError(\"pass mediaUrl or mediaUrls, not both\")\n const recordings = mediaUrls ?? (mediaUrl !== undefined ? [mediaUrl] : undefined)\n if (!recordings) throw new TypeError(\"pass mediaUrl or mediaUrls\")\n return {\n mediaUrls: [...recordings],\n ...(masterAudioUrl !== undefined ? { masterAudioUrl } : {}),\n ...(cameras !== undefined ? { cameras } : {}),\n ...Object.fromEntries(Object.entries(rest).filter(([, v]) => v !== undefined)),\n }\n}\n\n/**\n * Sends `send` the body `build` makes, or rejects (never throws) with the\n * error of an input the body cannot take — before any request, as every input\n * check of the `edit` resource rejects.\n */\nexport function withUseCaseBody<T>(build: () => Record<string, unknown>, send: (body: Record<string, unknown>) => Promise<T>): Promise<T> {\n let body: Record<string, unknown>\n try {\n body = build()\n } catch (err) {\n return Promise.reject(err)\n }\n return send(body)\n}\n\nexport function tightenBody(input: TightenEpisodeInput): Record<string, unknown> {\n return withRecordings(input)\n}\n\nexport function chaptersBody(input: EpisodeChaptersInput): Record<string, unknown> {\n return withRecordings({\n mediaUrl: input.mediaUrl,\n ...(input.planTier !== undefined ? { planTier: input.planTier } : {}),\n ...(input.instructions !== undefined ? { instructions: input.instructions } : {}),\n ...(input.styleGuide !== undefined ? { styleGuide: input.styleGuide } : {}),\n })\n}\n\nexport function trailerBody(input: EpisodeTrailerInput): Record<string, unknown> {\n return withRecordings({\n mediaUrl: input.mediaUrl,\n mediaUrls: input.mediaUrls,\n masterAudioUrl: input.masterAudioUrl,\n cameras: input.cameras,\n ...(input.introCardUrl !== undefined ? { introCardUrl: input.introCardUrl } : {}),\n // An empty list is sent as is: the route refuses it (at least one format).\n ...(input.formats !== undefined ? { formats: input.formats } : {}),\n ...(input.reviewBeforeRender !== undefined ? { reviewBeforeRender: input.reviewBeforeRender } : {}),\n ...(input.planTier !== undefined ? { planTier: input.planTier } : {}),\n ...(input.instructions !== undefined ? { instructions: input.instructions } : {}),\n ...(input.styleGuide !== undefined ? { styleGuide: input.styleGuide } : {}),\n })\n}\n\n/** Clip Pack's body: what the caller set, `framing: null` included (no framing). */\nexport function clipPackBody(input: ClipPackInput): Record<string, unknown> {\n return withRecordings(input)\n}\n\n/** Speaker Layout's body: the recordings, then what the caller set. */\nexport function speakerLayoutBody(input: SpeakerLayoutInput): Record<string, unknown> {\n return withRecordings(input)\n}\n","import type { NodaroClientCore } from \"../core.js\"\nimport { ForbiddenError, NodaroError } from \"../errors.js\"\nimport {\n remapTranscriptThroughEdl,\n unwrapEditPlanOutput,\n resolveEditPlanSources,\n describeAudioSyncOffsetIssue,\n transcriptSpeakerLabels,\n cameraSwitchSpeakerMap, speakerMapResultOf, type SpeakerMapResult,\n type Edl,\n type Transcript,\n type EditPlanMode,\n type EditPlanTier,\n type EdlClipSet,\n type ChapterSet,\n type EdlTargetAspect\n} from \"@nodaro/shared/edl\"\nimport { USE_CASE_NODE_TYPES, isUseCaseNodeType, type UseCaseNodeType } from \"@nodaro/shared/nodes\"\nimport type { SpeakerMapInput } from \"./speaker-map-inputs.js\"\nimport {\n chaptersBody,\n clipPackBody,\n speakerLayoutBody,\n tightenBody,\n trailerBody,\n withUseCaseBody,\n type ClipPackInput,\n type EpisodeChaptersInput,\n type EpisodeTrailerInput,\n type SpeakerLayoutInput,\n type TightenEpisodeInput,\n} from \"./edit-use-case-inputs.js\"\n\nexport { CLIP_PACK_MAX_TARGET_SEC, CLIP_PACK_MIN_TARGET_SEC, TRAILER_FORMATS } from \"./edit-use-case-inputs.js\"\nexport type { ClipPackEmphasis, ClipPackInput, EpisodeChaptersInput, EpisodeTrailerInput, SpeakerLayoutInput, TightenEpisodeInput, TrailerFormat, UseCaseRecordingsInput } from \"./edit-use-case-inputs.js\"\n\n// Re-export the canonical EDL / transcript vocabulary from `@nodaro/shared`\n// (single source of truth — the shapes live at `packages/shared/src/edl.ts`).\n// `@nodaro/shared` is already a hard dep of this package, so there is no\n// bundle-size cost to importing from it, and an integration builds requests and\n// reads results with one dependency. `EdlClipSet` / `ChapterSet` are the raw\n// `output_data` shapes of the `clips` / `chapters` modes, and\n// `unwrapEditPlanOutput` is the sanctioned way to normalize any edit-plan job's\n// `output_data` (it also strips the relay's `viaNodaroCloud` marker).\nexport type { Edl, Transcript, EditPlanMode, EditPlanTier, EdlClipSet, ChapterSet }\nexport { unwrapEditPlanOutput }\n\n/**\n * A silence-detect job's `output_data.json` — the value to pass as\n * {@link EditPlanInput.silence}. It is NOT what {@link EditResource.silenceDetect}\n * returns (that is `{ jobId }`); fetch the finished job and read its\n * `output_data.json`. The planner reads the `ranges` array — an input without\n * one is silently ignored, so pass this whole object.\n */\nexport interface SilenceRanges {\n /** Wire version of the payload. */\n version?: number\n /** Silence spans on the source clock, in ms. */\n ranges: ReadonlyArray<{ startMs: number; endMs: number }>\n /** Total source duration, in ms. */\n durationMs?: number\n}\n\n/** Every editorial route answers with the queued job to poll. */\nexport interface EditJobResult {\n /** The queued job id — follow it via `client.jobs.getStatus(jobId)`. */\n jobId: string\n}\n\nexport interface SilenceDetectInput {\n /**\n * An audio OR video source. A single ffmpeg `silencedetect` pass runs over the\n * source's audio proxy either way — no provider key required.\n */\n audioUrl: string\n /** dBFS threshold, always ≤ 0. Default -35 (a good podcast default). */\n thresholdDb?: number\n /** Minimum silence length to report, in ms. Default 700. */\n minSilenceMs?: number\n /** Padding kept around speech, in ms — shrinks each reported range inward. Default 120. */\n padMs?: number\n /**\n * Optionally associate this run with a workflow execution (display only — it\n * ties the standalone job back to a workflow for the execution history).\n */\n workflowId?: string\n}\n\n/** One recording for {@link EditResource.audioSync}. */\nexport interface AudioSyncSource {\n /**\n * Your id for this recording (1–200 chars, unique within the request) —\n * echoed back as its offset's `sourceId`. Use the id your EDL gives the same\n * recording (`EdlSource.id`) and the result folds straight into it.\n */\n id: string\n /** An audio OR video URL — the audio track is read either way. */\n url: string\n}\n\nexport interface AudioSyncInput {\n /** The 2–6 recordings of one conversation to line up (camera files and/or a master mic). */\n sources: AudioSyncSource[]\n /**\n * The id of the source every offset is measured against (its own offset is\n * 0). Must be one of `sources`' ids; default: the first source.\n */\n reference?: string\n /** Optionally associate this run with a workflow execution (display only). */\n workflowId?: string\n}\n\n/** One recording's measured clock offset in an {@link AudioSyncResult}. */\nexport interface AudioSyncOffset {\n /** The recording's `id` from the request. */\n sourceId: string\n /**\n * Where this recording sits on the reference's clock, in integer ms:\n * `referenceMs = sourceMs + offsetMs` (the EDL's D19 sign — the value\n * `EdlSource.offsetMs` takes when the reference is the master).\n */\n offsetMs: number\n /** 0–1. Below 0.5 a `notes` line asks for a check by ear. */\n confidence: number\n /**\n * Measured clock drift against the reference, in ms gained per hour; `null`\n * when the shared stretch was too short to measure it. Drift is reported,\n * never corrected — the offset is taken at the middle of the overlap.\n */\n driftMsPerHour: number | null\n}\n\n/**\n * An audio-sync job's `output_data.json`. It is NOT what\n * {@link EditResource.audioSync} returns (that is `{ jobId }`); fetch the\n * finished job and read its `output_data.json`.\n */\nexport interface AudioSyncResult {\n /** Wire version of the payload. */\n version: number\n /** The source every offset is measured against (its own offset is 0). */\n reference: string\n offsets: AudioSyncOffset[]\n /** Human-readable warnings: low confidence, measured drift, no shared sound. */\n notes: string[]\n}\n\nexport interface ApplyEdlInput {\n /** The edit decision list to render. Media resolves from each `edl.sources[i].url`. */\n edl: Edl\n /**\n * Optional media-URL overrides for `edl.sources[i].url`, POSITIONAL in this\n * array's order. Each URL is SSRF-guarded server-side like any media the\n * platform fetches.\n */\n sources?: string[]\n /**\n * Optional transcript to remap through the cut. The rendered job returns the\n * remapped transcript on its `json` output. A word-level multi-hour transcript\n * is several MB — if you only need the re-timed transcript (not a render), use\n * {@link EditResource.remapTranscript} locally instead of sending it here.\n */\n transcript?: Transcript\n /** Render a full video (default) or an audio-only cut. */\n output?: \"video\" | \"audio\"\n /** Fast proxy draft or the final render. Default \"final\". */\n quality?: \"proxy\" | \"final\"\n /**\n * Default crossfade (ms) on boundaries with no explicit transition; 0 = hard\n * cuts. Per-boundary clamped to the ffmpeg-xfade limit server-side. Default 0.\n */\n crossfadeMs?: number\n /**\n * The plan clip this render cuts — `edlSpanKey(clip)` from `@nodaro/shared`\n * (`\"<first inMs>-<last outMs>\"`). The job's result carries it back as\n * `output_data.clipKey`, so renders of a clip set can be matched to their\n * clips. Omit for a render of no plan clip.\n */\n clipKey?: string\n /**\n * The plan value this render cuts — `renderReadBasis(value)` from\n * `@nodaro/shared` (16 lowercase hex digits), where `value` is the Edit\n * Plan's Tighten EDL with any review applied, or the clip this render cuts.\n * The job's result carries it back as `output_data.planBasis`, so a take can\n * be told apart from one cut from an earlier plan. Send it only when the EDL\n * you send IS that value (not one an intermediate step re-cut from an older\n * plan); omit it otherwise. The result's `output_data.renderBasis` (the\n * render's own settings and sources) is stamped by the server.\n */\n planBasis?: string\n /** Optionally associate this run with a workflow execution (display only). */\n workflowId?: string\n}\n\n/**\n * One media source for an edit-plan run. Mirrors the shape the workflow engine\n * sends: a stable `id` (adopted verbatim as the plan's `EdlSource` id), the\n * media `url`, and the `kind`, plus optional per-source annotations the planner\n * honors.\n */\nexport interface EditPlanSource {\n /** Stable id for this source — becomes the `EdlSource` id in the returned plan. */\n id: string\n /** The source's media URL (SSRF-guarded server-side). */\n url: string\n /** This source's medium. */\n kind: \"video\" | \"audio\"\n /** Role annotation. `\"master-audio\"` marks the clock the plan is reserved on. */\n role?: \"master-audio\" | \"camera\" | \"wide\" | \"screen\"\n /** Speaker labels present in this source. */\n speakers?: string[]\n /**\n * This source's origin on the master clock (masterMs = sourceMs + offsetMs).\n * Set by hand, it wins over a measured offset from `offsets`.\n */\n offsetMs?: number\n}\n\nexport interface EditPlanInput {\n /**\n * Planning mode. The finished job's `output_data` carries the plan — read it\n * with {@link unwrapEditPlanOutput}, which also strips the relay's\n * `viaNodaroCloud` marker:\n * - `\"tighten\"` → an `Edl`.\n * - `\"clips\"` → an {@link EdlClipSet} (`{ version, clips: Edl[] }`);\n * `unwrapEditPlanOutput` returns the bare `Edl[]`.\n * - `\"chapters\"` → a {@link ChapterSet} (`{ version, chapters: [...] }`).\n * - `\"trailer\"` → an `Edl` (one short teaser cut from the strongest moments).\n */\n mode: EditPlanMode\n /** Reasoning tier — affects plan quality AND the credit bucket. */\n planTier: EditPlanTier\n /** The timed transcript driving the plan. */\n transcript: Transcript\n /**\n * Optional detected silence ranges. Pass the silence-detect JOB'S RESULT —\n * `getStatus(jobId).data.output_data.json` (a {@link SilenceRanges} object),\n * NOT the `{ jobId }` that {@link EditResource.silenceDetect} returns. The\n * planner reads the `ranges` array; an input without one is silently ignored.\n */\n silence?: SilenceRanges\n /** The recording's media sources (1–6). */\n sources: EditPlanSource[]\n /**\n * Multicam: an {@link AudioSyncResult} (the audio-sync job's\n * `output_data.json`) measured over these same source ids. Each source's\n * measured offset is written onto its `offsetMs` BEFORE the request, on the\n * master's clock (the `master-audio` source, else the first) — a source's\n * own `offsetMs` wins. `editPlan` rejects with a {@link NodaroError}\n * (`code: \"edit_plan_sources\"`), before any request or charge, when a\n * source was not measured or matched weakly (confidence < 0.5 — set its\n * `offsetMs` by hand), or the master was not measured.\n */\n offsets?: AudioSyncResult | string\n /**\n * The id of the source the transcript was made from, when you know it. The\n * plan follows the master's clock, so a transcript made from a source that\n * is off it is rejected the same way.\n */\n transcriptSourceId?: string\n /** Free-text editing steer. */\n instructions?: string\n /** Style-guide text applied to the plan. */\n styleGuide?: string\n /** `\"clips\"` mode only: how many clips to cut. */\n count?: number\n /** `\"clips\"` mode only: target duration per clip, in seconds. */\n targetDurationSec?: number\n /** Target aspect for cut clips (`\"clips\"`) or the teaser (`\"trailer\"`). */\n targetAspect?: \"16:9\" | \"9:16\" | \"1:1\" | \"4:5\"\n /** Target platform hint (e.g. a social platform name). */\n platform?: string\n /** Optionally associate this run with a workflow execution (display only). */\n workflowId?: string\n}\n\n/** Input for {@link EditResource.cameraSwitch} (podcast B5). */\nexport interface CameraSwitchInput {\n /** One EDL — an `editPlan` result (`unwrapEditPlanOutput`), not a clip set. */\n edl: Edl\n /** The word transcript WITH speaker labels (transcribe with speaker detection). */\n transcript: Transcript\n /** Speaker label → the EDL source id of that speaker's camera. A speaker\n * left out shows the source whose `speakers` list names them, else the\n * `wide` camera, else any camera that filmed them. */\n speakerMap?: Record<string, string>\n /** A {@link EditResource.speakerMap} job's `output_data.json`: a label in `speakerMap`\n * wins, then this result, then the n-th speaker heard gets the n-th camera. */\n speakerMapResult?: SpeakerMapResult | string\n /** Speaker label → display name (on the segments and the returned transcript). */\n speakerNames?: Record<string, string>\n /** The shortest shot in ms (default 2 500): a shorter turn holds the shot. */\n minShotMs?: number\n /** Cut this long before the new speaker starts, ms (default 200). */\n leadMs?: number\n /** With a `wide` source: break to it after this long on one camera, ms (default 20 000). */\n maxShotMs?: number\n /** With a `wide` source: every N-th cut goes to the wide (default 0 = off). */\n wideEvery?: number\n /** Overlapping speech → a layout hint (default false; Apply EDL renders cut-only edits). */\n layoutHints?: boolean\n /** Optionally associate this run with a workflow execution (display only). */\n workflowId?: string\n}\n\n/**\n * The podcast use-case node types, each one a route (`POST /v1/<type>`, and\n * `POST /v1/<type>/continue` to continue one of its runs).\n */\nexport { USE_CASE_NODE_TYPES, type UseCaseNodeType }\n\n/** The route that continues a run of `type`. */\nconst continuePathOf = (type: UseCaseNodeType): `/v1/${UseCaseNodeType}/continue` => `/v1/${type}/continue`\n\n/** What a use-case run (`tightenEpisode`, `episodeChapters`, `episodeTrailer`, `clipPack`, `speakerLayout`) and `continueUseCase` answer: the run's job to poll. */\nexport interface UseCaseJobResult extends EditJobResult {\n /** The run's execution (absent on a deduplicated retry). */\n executionId?: string\n /** `true` when an `Idempotency-Key` retry found the run already started: `jobId` is that run. */\n deduped?: boolean\n}\n\n/** What `tightenEpisode` answers (a {@link UseCaseJobResult}). */\nexport type TightenEpisodeJobResult = UseCaseJobResult\n\n/**\n * What a use-case run is estimated at (`data`). Every credit amount is 0\n * on an edition without credits; `durationSec` is `null` when the recording's\n * length could not be read.\n */\nexport interface UseCaseEstimate {\n /** The whole run: its steps plus the fee. */\n totalCredits: number\n /** The steps at their own rates. */\n stepsCredits: number\n /** The per-run fee. */\n feeCredits: number\n /** The recording's length, in seconds. */\n durationSec: number | null\n}\n\n/** What a Tighten Episode run is estimated at (a {@link UseCaseEstimate}). */\nexport type TightenEpisodeEstimate = UseCaseEstimate\n\n/** Input for {@link EditResource.continueUseCase}. */\nexport interface UseCaseContinueInput {\n /** The run to continue: the job `tightenEpisode`, `episodeChapters`, `episodeTrailer`, `clipPack` or `speakerLayout` (or an earlier continuation) answered. */\n jobId: string\n /**\n * `\"from-failed\"` re-runs what did not finish of a failed run;\n * `\"render-final\"` renders the full-quality result after a review-on preview\n * (a Chapters run has no preview: it is refused `render_final_not_preview`;\n * a Clip Pack edit that drops every clip is refused `use_case_nothing_kept`).\n */\n mode: \"from-failed\" | \"render-final\"\n /** Render final only: the reviewer's edit of the plan (an EDL). A Speaker Layout run has no plan: an edit is refused `400 use_case_no_plan`. */\n editedEdl?: unknown\n /**\n * The run's node type: its continuation goes to `POST /v1/<nodeType>/continue`.\n * Optional: when absent the job is read first (`GET /v1/jobs/:id`, which\n * needs the `jobs:read` scope on an app token) for the type the run records.\n * Required when that read cannot answer: a key without `jobs:read`, or a job\n * that records no use-case type (the call rejects with `use_case_type_unknown`).\n */\n nodeType?: UseCaseNodeType\n}\n\n/** Per-call options for the use-case requests (Tighten Episode, Chapters, Trailer, Clip Pack, Speaker Layout, and their continuations). */\nexport interface UseCaseRequestOptions {\n /**\n * Sent as the `Idempotency-Key` header. Reuse the same value when retrying\n * the same request and the server answers the run it already started\n * (`deduped: true`) instead of starting a second one.\n */\n idempotencyKey?: string\n}\n\nfunction idempotencyHeaders(options?: UseCaseRequestOptions): { headers?: Record<string, string> } {\n return options?.idempotencyKey ? { headers: { \"Idempotency-Key\": options.idempotencyKey } } : {}\n}\n\n/**\n * Editorial primitives for podcast / long-form video editing, single-camera\n * and multicam: measure the cameras' offsets ({@link audioSync}), plan the cut\n * ({@link editPlan}), put each cut on the speaker's camera\n * ({@link cameraSwitch}), render a Preview to review (`applyEdl` with\n * `quality: \"proxy\"`), then the final (`quality: \"final\"`).\n *\n * - {@link silenceDetect}, {@link audioSync} and {@link applyEdl} are core nodes\n * available on every edition.\n * - {@link editPlan} and {@link cameraSwitch} run on nodaro.ai; a self-hosted\n * install relays them once it is connected (a 503\n * `code: \"nodaro_connection_required\"` otherwise).\n * - {@link tightenEpisode} runs the whole chain (transcribe, plan, render, and\n * optionally captions, music and framing) in one call. It is core, but a\n * self-hosted install needs a nodaro.ai connection for the steps that run\n * there (a 503 `code: \"nodaro_connection_required\"` otherwise).\n * {@link continueUseCase} continues one of its runs.\n * - {@link episodeChapters} lists a recording's chapters (transcribe, then the\n * plan in chapters mode) in one call; nothing renders. Like\n * {@link tightenEpisode}, a self-hosted install needs a nodaro.ai connection.\n * - {@link episodeTrailer} cuts a 20–40 s trailer of a recording and delivers\n * it in each chosen format in one call; the same connection applies.\n * - {@link clipPack} cuts a recording into a pack of short clips (framed and\n * captioned by default) in one call; the same connection applies.\n * - {@link speakerLayout} frames a whole recording by speaker (the same\n * length, nothing cut) in one call; the same connection applies.\n * - {@link remapTranscript} is a PURE local transform (no request) — the same\n * remap `applyEdl` performs on its `transcript`, exposed for callers that hold\n * an EDL and a transcript and only want the re-timed transcript.\n *\n * Every request method except the estimates ({@link estimateTightenEpisode},\n * {@link estimateEpisodeChapters}, {@link estimateEpisodeTrailer},\n * {@link estimateClipPack}, {@link estimateSpeakerLayout}: a quote, `{ data }`) returns\n * {@link EditJobResult} (the use-case runs a {@link UseCaseJobResult}); poll the\n * `jobId` with `client.jobs.getStatus(jobId)`.\n */\nexport class EditResource {\n constructor(private client: NodaroClientCore) {}\n\n /**\n * Detect silence ranges in an audio/video source (`POST /v1/silence-detect`).\n * Keyless — one ffmpeg pass over the source's audio proxy.\n */\n silenceDetect(input: SilenceDetectInput): Promise<EditJobResult> {\n return this.client.request(\"POST\", \"/v1/silence-detect\", {\n body: {\n audioUrl: input.audioUrl,\n ...(input.thresholdDb !== undefined ? { thresholdDb: input.thresholdDb } : {}),\n ...(input.minSilenceMs !== undefined ? { minSilenceMs: input.minSilenceMs } : {}),\n ...(input.padMs !== undefined ? { padMs: input.padMs } : {}),\n ...(input.workflowId !== undefined ? { workflowId: input.workflowId } : {}),\n },\n })\n }\n\n /**\n * Measure how far apart the clocks of 2–6 recordings of one conversation are\n * (`POST /v1/audio-sync`), by cross-correlating their audio — keyless, one\n * ffmpeg decode per source. The finished job's `output_data.json` is an\n * {@link AudioSyncResult}. A malformed request (fewer than 2 or more than 6\n * sources, a repeated id, a `reference` that is not one of the ids) throws a\n * typed `NodaroError` (400, `code: \"validation_error\"`) before any credits\n * are reserved.\n */\n audioSync(input: AudioSyncInput): Promise<EditJobResult> {\n return this.client.request(\"POST\", \"/v1/audio-sync\", {\n body: {\n sources: input.sources.map((s) => ({ id: s.id, url: s.url })),\n ...(input.reference !== undefined ? { reference: input.reference } : {}),\n ...(input.workflowId !== undefined ? { workflowId: input.workflowId } : {}),\n },\n })\n }\n\n /**\n * Which camera each speaker is on, from the cameras' own microphones (`POST\n * /v1/speaker-map`), keyless. `output_data.json` is a `SpeakerMapResult`: pass\n * it to {@link cameraSwitch} as `speakerMapResult`. A malformed request throws\n * a `NodaroError` (400 `validation_error`; 422 `no_speakers` for a transcript\n * with no speaker labels) before any credits are reserved.\n */\n speakerMap(input: SpeakerMapInput): Promise<EditJobResult> {\n return this.client.request(\"POST\", \"/v1/speaker-map\", {\n body: {\n sources: input.sources.map((s) => ({ id: s.id, url: s.url, ...(s.kind ? { kind: s.kind } : {}) })),\n transcript: input.transcript,\n ...(input.offsets !== undefined ? { offsets: input.offsets } : {}),\n ...(input.masterSourceId !== undefined ? { masterSourceId: input.masterSourceId } : {}),\n ...(input.wideSourceId !== undefined ? { wideSourceId: input.wideSourceId } : {}),\n ...(input.marginDb !== undefined ? { marginDb: input.marginDb } : {}),\n ...(input.workflowId !== undefined ? { workflowId: input.workflowId } : {}),\n },\n })\n }\n\n /**\n * Render an edit decision list into a video or audio cut (`POST /v1/apply-edl`).\n * The EDL is validated at ingress — an unresolvable source or a picture-less\n * segment on a video edit throws a typed `NodaroError` (400, `code:\n * \"invalid_edl\"`) before any credits are reserved.\n */\n applyEdl(input: ApplyEdlInput): Promise<EditJobResult> {\n return this.client.request(\"POST\", \"/v1/apply-edl\", {\n body: {\n edl: input.edl,\n ...(input.sources !== undefined ? { sources: input.sources } : {}),\n ...(input.transcript !== undefined ? { transcript: input.transcript } : {}),\n ...(input.output !== undefined ? { output: input.output } : {}),\n ...(input.quality !== undefined ? { quality: input.quality } : {}),\n ...(input.crossfadeMs !== undefined ? { crossfadeMs: input.crossfadeMs } : {}),\n ...(input.clipKey !== undefined ? { clipKey: input.clipKey } : {}),\n ...(input.planBasis !== undefined ? { planBasis: input.planBasis } : {}),\n ...(input.workflowId !== undefined ? { workflowId: input.workflowId } : {}),\n },\n })\n }\n\n /**\n * Tighten Episode (`POST /v1/tighten-episode`): tighten a podcast recording\n * in one call — transcribe, cut the silences and filler, render, with\n * optional captions, music and framing. Answers the run's job to poll; its\n * `output_data` holds the episode. The run is priced as its steps at their own\n * rates plus the listed per-run fee. Quote it first with\n * {@link estimateTightenEpisode}.\n */\n tightenEpisode(input: TightenEpisodeInput, options?: UseCaseRequestOptions): Promise<TightenEpisodeJobResult> {\n return withUseCaseBody(() => tightenBody(input), (body) => this.client.request(\"POST\", \"/v1/tighten-episode\", { body, ...idempotencyHeaders(options) }))\n }\n\n /**\n * What a Tighten Episode run is estimated at (`POST /v1/tighten-episode/estimate`):\n * its steps at their own rates plus its per-run fee. Nothing is created or\n * charged. The estimate leans high: the render is priced at the recording's\n * full length, while the charge follows the minutes actually rendered.\n */\n estimateTightenEpisode(input: TightenEpisodeInput): Promise<{ data: TightenEpisodeEstimate }> {\n return withUseCaseBody(() => tightenBody(input), (body) => this.client.request(\"POST\", \"/v1/tighten-episode/estimate\", { body }))\n }\n\n /**\n * Chapters (`POST /v1/episode-chapters`): transcribe a recording and list its\n * chapters in one call. Answers the run's job to poll; the finished job's\n * `output_data.text` is the list as show notes (one `0:00 Title` line per\n * chapter; once a chapter starts at 1:00:00 or later, every line is\n * `H:MM:SS`), `output_data.json` the list itself (`{ startMs, title }[]`, the\n * same rows; the first starts at 0). A run that finds no chapters fails,\n * and its fee is refunded. Priced as its steps at their own rates plus the\n * listed per-run fee; quote it first with {@link estimateEpisodeChapters}.\n */\n episodeChapters(input: EpisodeChaptersInput, options?: UseCaseRequestOptions): Promise<UseCaseJobResult> {\n return withUseCaseBody(() => chaptersBody(input), (body) => this.client.request(\"POST\", \"/v1/episode-chapters\", { body, ...idempotencyHeaders(options) }))\n }\n\n /**\n * What a Chapters run is estimated at (`POST /v1/episode-chapters/estimate`):\n * its steps at their own rates plus its per-run fee. Nothing is created or\n * charged. A recording whose length cannot be read is estimated at the\n * 180-minute ceiling.\n */\n estimateEpisodeChapters(input: EpisodeChaptersInput): Promise<{ data: UseCaseEstimate }> {\n return withUseCaseBody(() => chaptersBody(input), (body) => this.client.request(\"POST\", \"/v1/episode-chapters/estimate\", { body }))\n }\n\n /**\n * Trailer (`POST /v1/episode-trailer`): cut a 20–40 s trailer of a recording\n * and deliver it in each chosen format (padded, never cropped), optionally\n * after an intro card, in one call. The finished job's `output_data.formats`\n * is `{ format, url }[]` in format order, the first also `output_data.videoUrl`;\n * a format that failed is named in `output_data.failedFormats` (the run keeps\n * the others). With `reviewBeforeRender` the run stops at a preview\n * (`videoUrl`, no formats yet). Priced as its steps at their own rates plus\n * the listed per-run fee; quote it first with {@link estimateEpisodeTrailer}.\n */\n episodeTrailer(input: EpisodeTrailerInput, options?: UseCaseRequestOptions): Promise<UseCaseJobResult> {\n return withUseCaseBody(() => trailerBody(input), (body) => this.client.request(\"POST\", \"/v1/episode-trailer\", { body, ...idempotencyHeaders(options) }))\n }\n\n /**\n * What a Trailer run is estimated at (`POST /v1/episode-trailer/estimate`):\n * its steps at their own rates plus its per-run fee. Nothing is created or\n * charged. The trailer is quoted at 40 seconds, the longest trailer the\n * plan cuts; a Render final is quoted on the trailer the run cut (with the\n * review's edits), plus the intro card.\n */\n estimateEpisodeTrailer(input: EpisodeTrailerInput): Promise<{ data: UseCaseEstimate }> {\n return withUseCaseBody(() => trailerBody(input), (body) => this.client.request(\"POST\", \"/v1/episode-trailer/estimate\", { body }))\n }\n\n /**\n * Clip Pack (`POST /v1/clip-pack`): cut a recording into a pack of short\n * clips in one call — the plan finds the best moments (`count`, default 8,\n * of about `targetDurationSec`, default 60), each is rendered (framed 9:16\n * with the speakers stacked by default; `framing: null` keeps the\n * recording's shape) and captioned. An audio recording makes audio clips.\n * The finished job's `output_data.clips` is `{ url, title?, hook?, clipKey,\n * thumbnailUrl?, captionsFailed? }[]` in plan order, the first also\n * `output_data.videoUrl` (`audioUrl` for audio clips). Every clip is tried:\n * one that cannot be rendered is skipped, not charged and counted on\n * `failedClips` (the pack keeps the others and its fee); a clip whose\n * captions failed comes uncaptioned (`captionsFailed`, counted on\n * `failedCaptions`). When no clip renders the run fails and its fee is\n * refunded. With `reviewBeforeRender` the run stops at previews; Render\n * final ({@link continueUseCase}) renders only the clips the edit keeps.\n * Priced as its steps at their own rates plus the listed per-run fee;\n * quote it first with {@link estimateClipPack}.\n */\n clipPack(input: ClipPackInput, options?: UseCaseRequestOptions): Promise<UseCaseJobResult> {\n return withUseCaseBody(() => clipPackBody(input), (body) => this.client.request(\"POST\", \"/v1/clip-pack\", { body, ...idempotencyHeaders(options) }))\n }\n\n /**\n * What a Clip Pack run is estimated at (`POST /v1/clip-pack/estimate`): its\n * steps at their own rates plus its per-run fee. Nothing is created or\n * charged. Each clip is quoted at twice the target length (the plan may cut\n * a clip longer than asked); the charge follows each clip's real length.\n */\n estimateClipPack(input: ClipPackInput): Promise<{ data: UseCaseEstimate }> {\n return withUseCaseBody(() => clipPackBody(input), (body) => this.client.request(\"POST\", \"/v1/clip-pack/estimate\", { body }))\n }\n\n /**\n * Speaker Layout (`POST /v1/speaker-layout`): frame a whole recording by\n * speaker in one call — the same length, nothing cut. One recording: each\n * speaker framed in turn; several recordings of one conversation: lined up,\n * each speaker shown on their own camera. The finished job's\n * `output_data.videoUrl` is the framed video, `output_data.json` the edit\n * Speaker View drew. With `reviewBeforeRender` the run stops at a preview;\n * {@link continueUseCase} (`mode: \"render-final\"`, no `editedEdl`) renders\n * it at full quality. Priced as its steps at their own rates plus the listed\n * per-run fee; quote it first with {@link estimateSpeakerLayout}.\n */\n speakerLayout(input: SpeakerLayoutInput, options?: UseCaseRequestOptions): Promise<UseCaseJobResult> {\n return withUseCaseBody(() => speakerLayoutBody(input), (body) => this.client.request(\"POST\", \"/v1/speaker-layout\", { body, ...idempotencyHeaders(options) }))\n }\n\n /**\n * What a Speaker Layout run is estimated at (`POST /v1/speaker-layout/estimate`):\n * its steps at their own rates plus its per-run fee. Nothing is created or\n * charged. A recording whose length cannot be read is estimated at the\n * 180-minute ceiling.\n */\n estimateSpeakerLayout(input: SpeakerLayoutInput): Promise<{ data: UseCaseEstimate }> {\n return withUseCaseBody(() => speakerLayoutBody(input), (body) => this.client.request(\"POST\", \"/v1/speaker-layout/estimate\", { body }))\n }\n\n /**\n * Continue a use-case run as a new job (`POST /v1/<type>/continue`, the\n * run's own type: `input.nodeType`, else the type the job records, read with\n * `GET /v1/jobs/:id`; when that read cannot tell, this rejects with a\n * `NodaroError` coded `use_case_type_unknown` — pass `nodeType` then):\n * `\"from-failed\"` keeps the steps that finished and runs the rest (the fee\n * is held again; the failed run's was refunded);\n * `\"render-final\"` renders the full-quality result after a review-on preview,\n * with the preview's settings and no fee. A refusal that names another job\n * (`already_running`, `continuation_superseded`,\n * `render_final_already_rendered`) throws a `ContinuationRefusedError`\n * carrying that `jobId`.\n */\n async continueUseCase(input: UseCaseContinueInput, options?: UseCaseRequestOptions): Promise<UseCaseJobResult> {\n if (input.nodeType !== undefined && !isUseCaseNodeType(input.nodeType)) {\n throw new NodaroError(\n `continueUseCase: nodeType \"${String(input.nodeType)}\" is not a use-case node type (${USE_CASE_NODE_TYPES.join(\", \")})`,\n \"invalid_node_type\",\n 400,\n )\n }\n const type = input.nodeType ?? (await this.runTypeOf(input.jobId))\n return this.client.request(\"POST\", continuePathOf(type), {\n body: { jobId: input.jobId, mode: input.mode, ...(input.editedEdl !== undefined ? { editedEdl: input.editedEdl } : {}) },\n ...idempotencyHeaders(options),\n })\n }\n\n /**\n * The use-case type a run records (`input_data.type`, else its `job_type`).\n * When the key lacks the `jobs:read` scope (403 naming that scope) or the job\n * names no use-case type, the type cannot be read: this rejects with a\n * `NodaroError` (`use_case_type_unknown`, 400) asking for `nodeType`, and\n * nothing is posted (decided 2026-10-18: no route is guessed for the run).\n * Any other failure of the read, any other 403 included, is thrown as is.\n */\n private async runTypeOf(jobId: string): Promise<UseCaseNodeType> {\n const unknown = () =>\n new NodaroError(\"continueUseCase: the run's node type cannot be read — pass nodeType\", \"use_case_type_unknown\", 400)\n let row: { job_type?: unknown; input_data?: unknown } | undefined\n try {\n row = (await this.client.request<{ data?: { job_type?: unknown; input_data?: unknown } }>(\"GET\", `/v1/jobs/${encodeURIComponent(jobId)}`)).data\n } catch (err) {\n if (err instanceof ForbiddenError && err.missingScope === \"jobs:read\") throw unknown()\n throw err\n }\n const input = row?.input_data\n const recorded = input && typeof input === \"object\" && !Array.isArray(input) ? (input as { type?: unknown }).type : undefined\n const type = typeof recorded === \"string\" && recorded.length > 0 ? recorded : row?.job_type\n if (!isUseCaseNodeType(type)) throw unknown()\n return type\n }\n\n /**\n * Plan a transcript-driven cut (`POST /v1/edit-plan`). Reads a timed\n * transcript (plus optional silence ranges) and the media sources, and plans\n * the edit. The finished job's `output_data` holds the plan: an `Edl`\n * (`\"tighten\"` or `\"trailer\"`), an {@link EdlClipSet} (`\"clips\"`), or a\n * {@link ChapterSet} (`\"chapters\"`) — normalize it with {@link unwrapEditPlanOutput}.\n *\n * On a self-hosted install the request relays to nodaro.ai and needs the\n * install connected (a 503 `code: \"nodaro_connection_required\"` otherwise);\n * on nodaro.ai it runs directly.\n */\n editPlan(input: EditPlanInput): Promise<EditJobResult> {\n // The same pre-dispatch check the canvas and MCP run (B4): the server never\n // sees `offsets` — they are written onto the sources here.\n const planned = resolveEditPlanSources(input.sources, {\n offsets: input.offsets,\n transcriptSourceId: input.transcriptSourceId,\n })\n if (!planned.ok) {\n const message = planned.issues.map((issue) => describeAudioSyncOffsetIssue(issue)).join(\"; \")\n return Promise.reject(new NodaroError(`editPlan: ${message}`, \"edit_plan_sources\", 400))\n }\n const transcript = planned.transcriptSourceId\n ? { ...input.transcript, sourceId: planned.transcriptSourceId }\n : input.transcript\n return this.client.request(\"POST\", \"/v1/edit-plan\", {\n body: {\n mode: input.mode,\n planTier: input.planTier,\n transcript,\n sources: planned.sources,\n ...(input.silence !== undefined ? { silence: input.silence } : {}),\n ...(input.instructions !== undefined ? { instructions: input.instructions } : {}),\n ...(input.styleGuide !== undefined ? { styleGuide: input.styleGuide } : {}),\n ...(input.count !== undefined ? { count: input.count } : {}),\n ...(input.targetDurationSec !== undefined ? { targetDurationSec: input.targetDurationSec } : {}),\n ...(input.targetAspect !== undefined ? { targetAspect: input.targetAspect } : {}),\n ...(input.platform !== undefined ? { platform: input.platform } : {}),\n ...(input.workflowId !== undefined ? { workflowId: input.workflowId } : {}),\n },\n })\n }\n\n /**\n * Camera Switch (podcast B5): choose which camera shows each cut of `edl`\n * by who is speaking — the sound never changes. Cloud edition; a flat\n * price. The finished job's `output_data.json` is the switched EDL (feed it\n * to {@link applyEdl}) and `output_data.transcript` the transcript with\n * `speakerNames` applied. A transcript with no speaker labels rejects with\n * a {@link NodaroError} (`code: \"no_speakers\"`) before any request or charge.\n */\n cameraSwitch(input: CameraSwitchInput): Promise<EditJobResult> {\n if (transcriptSpeakerLabels(input.transcript).length === 0) {\n return Promise.reject(new NodaroError(\n \"cameraSwitch: the transcript has no speaker labels — transcribe with speaker detection on\",\n \"no_speakers\",\n 422,\n ))\n }\n const result = input.speakerMapResult\n if (result !== undefined && !speakerMapResultOf(result)) return Promise.reject(new NodaroError(\"cameraSwitch: speakerMapResult is not a Speaker Map result — pass that job's output_data.json\", \"not_a_speaker_map\", 400))\n const speakerMap = result !== undefined ? cameraSwitchSpeakerMap({ speakerMap: input.speakerMap }, input.edl, input.transcript, { speakerMap: result }) : input.speakerMap\n return this.client.request(\"POST\", \"/v1/camera-switch\", {\n body: {\n edl: input.edl,\n transcript: input.transcript,\n ...(speakerMap !== undefined ? { speakerMap } : {}),\n ...(input.speakerNames !== undefined ? { speakerNames: input.speakerNames } : {}),\n ...(input.minShotMs !== undefined ? { minShotMs: input.minShotMs } : {}),\n ...(input.leadMs !== undefined ? { leadMs: input.leadMs } : {}),\n ...(input.maxShotMs !== undefined ? { maxShotMs: input.maxShotMs } : {}),\n ...(input.wideEvery !== undefined ? { wideEvery: input.wideEvery } : {}),\n ...(input.layoutHints !== undefined ? { layoutHints: input.layoutHints } : {}),\n ...(input.workflowId !== undefined ? { workflowId: input.workflowId } : {}),\n },\n })\n }\n\n /**\n * Remap a transcript through an EDL — a PURE client-side transform (NO\n * request). Returns a new transcript whose word (and segment) timings are on\n * the EDL's rendered output clock, dropping words that fall in cut regions and\n * clipping straddlers. Runs `@nodaro/shared`'s canonical\n * `remapTranscriptThroughEdl`, the same remap `applyEdl` performs server-side.\n */\n remapTranscript(edl: Edl, transcript: Transcript): Transcript {\n return remapTranscriptThroughEdl(edl, transcript)\n }\n}\n"]}
|
|
@@ -81,6 +81,10 @@ var NodesResource = class {
|
|
|
81
81
|
throw err;
|
|
82
82
|
});
|
|
83
83
|
}
|
|
84
|
+
async quote(type, params = {}) {
|
|
85
|
+
const res = await this.client.request("POST", "/v1/quote", { body: { type, params } });
|
|
86
|
+
return res.data;
|
|
87
|
+
}
|
|
84
88
|
async runAndWait(type, params = {}, opts = {}) {
|
|
85
89
|
if (opts.signal?.aborted) throw new JobAbortedError();
|
|
86
90
|
if (isImageBatchRequest(type, params)) throw batchRefusal(`${type} with count above 1 or models makes several jobs`);
|
|
@@ -206,5 +210,5 @@ var NodesResource = class {
|
|
|
206
210
|
};
|
|
207
211
|
|
|
208
212
|
export { NodesResource };
|
|
209
|
-
//# sourceMappingURL=chunk-
|
|
210
|
-
//# sourceMappingURL=chunk-
|
|
213
|
+
//# sourceMappingURL=chunk-6ECW23GA.js.map
|
|
214
|
+
//# sourceMappingURL=chunk-6ECW23GA.js.map
|