@goodz-core/sdk 0.3.3 → 0.3.4

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/README.md CHANGED
@@ -462,12 +462,41 @@ try {
462
462
 
463
463
  | Code | HTTP | Meaning | Action |
464
464
  |------|------|---------|--------|
465
- | `BAD_REQUEST` | 400 | Invalid input or insufficient balance | Check input values |
465
+ | `BAD_REQUEST` | 400 | Invalid input | Check input values |
466
+ | `INSUFFICIENT_BALANCE` | 400 | Not enough Z-coin | Redirect to `e.depositUrl` |
466
467
  | `UNAUTHORIZED` | 401 | Missing or invalid token | Refresh token or re-login |
467
468
  | `FORBIDDEN` | 403 | No permission | Show permission denied |
468
469
  | `NOT_FOUND` | 404 | Resource doesn't exist | Show 404 or fallback |
469
470
  | `CONFLICT` | 409 | Version conflict | Retry the operation |
470
471
 
472
+ ### Handling Insufficient Balance (Auto-Redirect to Deposit)
473
+
474
+ When a payment fails due to insufficient Z-coin, the error includes a deposit URL for seamless top-up:
475
+
476
+ ```ts
477
+ import { GoodZApiError } from "@goodz-core/sdk";
478
+
479
+ try {
480
+ await goodz.zcoin.mintAndCharge({ /* gacha pull */ });
481
+ } catch (err) {
482
+ if (err instanceof GoodZApiError && err.isInsufficientBalance()) {
483
+ // Option 1: Redirect to Core's deposit page (simplest)
484
+ window.open(err.depositUrl, '_blank');
485
+
486
+ // Option 2: Build a custom deposit URL with return_url
487
+ const depositUrl = await goodz.zcoin.getDepositUrl({
488
+ amount: 100, // pre-select 100 Z-coin package
489
+ returnUrl: window.location.href,
490
+ appId: 'od_myapp',
491
+ });
492
+ window.open(depositUrl.url, '_blank');
493
+ }
494
+ }
495
+ ```
496
+
497
+ The `isInsufficientBalance()` helper and `depositUrl` getter work for all payment methods:
498
+ `commercialTransfer`, `mintAndCharge`, and `chargeUser`.
499
+
471
500
  ## UI Components (React)
472
501
 
473
502
  The SDK includes a React component for displaying GoodZ collectibles with full material effects and tilt interaction — the same experience used on GoodZ.Core itself.
@@ -1,4 +1,4 @@
1
- import { $ as TransportConfig } from '../transport-CzoXrUZs.js';
1
+ import { $ as TransportConfig } from '../transport-BSpGsxyt.js';
2
2
 
3
3
  /**
4
4
  * @goodz-core/sdk — Alive API Type Definitions
@@ -1,4 +1,4 @@
1
- export { createAliveNamespace } from '../chunk-JAVMQXJM.js';
2
- import '../chunk-4SU7SU7K.js';
1
+ export { createAliveNamespace } from '../chunk-KP7DP5LP.js';
2
+ import '../chunk-ORUFMYZB.js';
3
3
  //# sourceMappingURL=index.js.map
4
4
  //# sourceMappingURL=index.js.map
@@ -1,7 +1,7 @@
1
- import { createCommerceNamespace } from './chunk-V73MMKHI.js';
2
- import { createExchangeNamespace } from './chunk-OUKZ2PRD.js';
3
- import { createAliveNamespace } from './chunk-JAVMQXJM.js';
4
- import { createMcpTransportConfig, callMutation, callQuery } from './chunk-4SU7SU7K.js';
1
+ import { createCommerceNamespace } from './chunk-SWD7BJQ7.js';
2
+ import { createExchangeNamespace } from './chunk-GH33FPMY.js';
3
+ import { createAliveNamespace } from './chunk-KP7DP5LP.js';
4
+ import { createMcpTransportConfig, callMutation, callQuery } from './chunk-ORUFMYZB.js';
5
5
 
6
6
  // src/core/index.ts
7
7
  var DEFAULT_CORE_URL = "https://goodzcore.manus.space";
@@ -99,5 +99,5 @@ function createGoodZClient(config = {}) {
99
99
  var createUserClient = createGoodZClient;
100
100
 
101
101
  export { createGoodZClient, createUserClient };
102
- //# sourceMappingURL=chunk-EQUAL5M6.js.map
103
- //# sourceMappingURL=chunk-EQUAL5M6.js.map
102
+ //# sourceMappingURL=chunk-DSWHCVKV.js.map
103
+ //# sourceMappingURL=chunk-DSWHCVKV.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/core/index.ts"],"names":[],"mappings":";;;;;;AA0HA,IAAM,gBAAA,GAAmB,+BAAA;AACzB,IAAM,oBAAA,GAAuB,mCAAA;AAC7B,IAAM,oBAAA,GAAuB,mCAAA;AAC7B,I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AoD,2BAA2B;AAAA,KACvG;AAAA;AAAA,IAGA,IAAA,EAAM;AAAA,MACJ,EAAA,EAAI,EAAyB,SAAS,CAAA;AAAA,MACtC,eAAA,EAAiB,EAAqD,sBAAsB;AAAA,KAC9F;AAAA;AAAA,IAGA,EAAA,EAAI;AAAA,MACF,YAAA,EAAc,EAA0B,eAAe,CAAA;AAAA,MACvD,SAAA,EAAW,EAAuB,YAAY,CAAA;AAAA,MAC9C,qBAAA,EAAuB,EAAqC,wBAAwB,CAAA;AAAA,MACpF,OAAA,EAAS,EAAqB,UAAU,CAAA;AAAA,MACxC,iBAAA,EAAmB,EAAgC,mBAAmB;AAAA,KACxE;AAAA;AAAA,IAGA,QAAA,EAAU,wBAAwB,iBAAiB,CAAA;AAAA;AAAA,IAGnD,QAAA,EAAU,wBAAwB,iBAAiB,CAAA;AAAA;AAAA,IAGnD,KAAA,EAAO,qBAAqB,cAAc,CAAA;AAAA;AAAA,IAG1C,UAAU,CAAU,IAAA,EAAc,UAAgB,SAAA,CAAkB,aAAA,EAAe,MAAM,KAAK,CAAA;AAAA,IAC9F,aAAa,CAAU,IAAA,EAAc,UAAgB,YAAA,CAAqB,aAAA,EAAe,MAAM,KAAK;AAAA,GACtG;AACF;AAMO,IAAM,gBAAA,GAAmB","file":"chunk-DSWHCVKV.js","sourcesContent":["/**\n * @goodz-core/sdk/core — Unified GoodZ API Client\n *\n * One client, all services. Stripe-style namespace architecture:\n * goodz.zcoin.* → Core settlement & Z-coin\n * goodz.inventory.* → Core instance management\n * goodz.collectible.* → Core card queries\n * goodz.user.* → Core user profiles\n * goodz.auth.* → Core auth\n * goodz.ip.* → Core IP (franchise/series/card)\n * goodz.commerce.* → Commerce/Shops (MCP)\n * goodz.exchange.* → Exchange marketplace (MCP)\n * goodz.alive.* → Alive companions (MCP)\n *\n * Core uses tRPC HTTP wire protocol; sub-sites use MCP JSON-RPC 2.0.\n * The client handles routing transparently.\n *\n * @example\n * ```ts\n * import { createGoodZClient } from \"@goodz-core/sdk\";\n *\n * const goodz = createGoodZClient({\n * accessToken: \"your-jwt-token\",\n * });\n *\n * // Core APIs\n * const balance = await goodz.zcoin.getMyBalance();\n * const result = await goodz.zcoin.commercialTransfer({ ... });\n *\n * // Commerce APIs\n * const shop = await goodz.commerce.createShop({ name: \"My Shop\" });\n * const order = await goodz.commerce.executePurchase({ campaignId: 1, quantity: 1 });\n *\n * // Exchange APIs\n * const listing = await goodz.exchange.createListing({ ... });\n * const data = await goodz.exchange.getMarketData({ coreGoodzId: 42 });\n *\n * // Alive APIs\n * const chat = await goodz.alive.sendMessage({ instanceId: 1, userId: 1, message: \"Hello!\" });\n * const memories = await goodz.alive.recallMemories({ instanceId: 1, userId: 1, query: \"birthday\" });\n * ```\n *\n * @module\n */\n\nimport { callQuery, callMutation, GoodZApiError } from \"../transport\";\nimport type { TransportConfig } from \"../transport\";\nimport { createMcpTransportConfig } from \"../mcp-transport\";\nimport { createCommerceNamespace } from \"../commerce/index\";\nimport type { CommerceNamespace } from \"../commerce/index\";\nimport { createExchangeNamespace } from \"../exchange/index\";\nimport type { ExchangeNamespace } from \"../exchange/index\";\nimport { createAliveNamespace } from \"../alive/index\";\nimport type { AliveNamespace } from \"../alive/index\";\nimport type {\n // zcoin\n ZcoinGetMyBalanceOutput,\n ZcoinGetMyHistoryInput,\n ZcoinCommercialTransferInput,\n ZcoinCommercialTransferOutput,\n ZcoinMintAndChargeInput,\n ZcoinMintAndChargeOutput,\n ZcoinChargeUserInput,\n ZcoinChargeUserOutput,\n ZcoinCreateDirectPurchaseOrderInput,\n ZcoinCreateDirectPurchaseOrderOutput,\n ZcoinGetDepositPackagesInput,\n ZcoinDepositPackage,\n ZcoinCreateDepositOrderInput,\n ZcoinCreateDepositOrderOutput,\n ZcoinGetDepositStatusInput,\n ZcoinGetDepositStatusOutput,\n ZcoinGetDepositUrlInput,\n ZcoinGetDepositUrlOutput,\n // inventory\n InventoryGetUserInventoryInput,\n InventoryItem,\n InventoryConfirmOwnershipInput,\n InventoryConfirmOwnershipOutput,\n InventoryMintInput,\n InventoryMintOutput,\n InventoryTransferInput,\n InventoryTransferOutput,\n InventoryTransferByCardInput,\n InventoryTransferByCardOutput,\n InventoryGrantMintAuthInput,\n InventoryTransferHistoryInput,\n // collectible\n CollectibleGetInstanceByIdInput,\n CollectibleGetPublicInstanceInput,\n CollectibleGetPublicInstancesBatchInput,\n CollectibleGetCardProfileInput,\n CollectibleGetShellImageUrlInput,\n // user\n UserGetPublicProfileInput,\n UserPublicProfile,\n UserGetPublicProfileByIdInput,\n // auth\n AuthGetOAuthAppInfoInput,\n AuthOAuthAppInfo,\n AuthUser,\n // ip\n FranchiseGetInput,\n SeriesGetInput,\n SeriesListByFranchiseInput,\n CardGetInput,\n CardListBySeriesInput,\n} from \"../types\";\n\n// ─── Re-export types and error class ─────────────────────────\n\nexport { GoodZApiError } from \"../transport\";\nexport type * from \"../types\";\nexport type * from \"../types-commerce\";\nexport type * from \"../types-exchange\";\nexport type * from \"../types-alive\";\nexport type { CommerceNamespace } from \"../commerce/index\";\nexport type { ExchangeNamespace } from \"../exchange/index\";\nexport type { AliveNamespace } from \"../alive/index\";\n\n// ─── Default sub-site URLs ──────────────────────────────────\n\nconst DEFAULT_CORE_URL = \"https://goodzcore.manus.space\";\nconst DEFAULT_COMMERCE_URL = \"https://goodzcommerce.manus.space\";\nconst DEFAULT_EXCHANGE_URL = \"https://goodzexchange.manus.space\";\nconst DEFAULT_ALIVE_URL = \"https://goodzalive.manus.space\";\n\n// ─── Client config ───────────────────────────────────────────\n\nexport interface GoodZClientConfig {\n /**\n * GoodZ.Core base URL.\n * @default \"https://goodzcore.manus.space\"\n */\n coreUrl?: string;\n\n /**\n * GoodZ.Commerce (Shops) base URL.\n * @default \"https://goodzcommerce.manus.space\"\n */\n commerceUrl?: string;\n\n /**\n * GoodZ.Exchange base URL.\n * @default \"https://goodzexchange.manus.space\"\n */\n exchangeUrl?: string;\n\n /**\n * GoodZ.Alive base URL.\n * @default \"https://goodzalive.manus.space\"\n */\n aliveUrl?: string;\n\n /**\n * Static access token (JWT) for authentication.\n * For server-to-server calls, obtain this via OAuth client_credentials flow.\n * For user-context calls, pass the user's access token.\n */\n accessToken?: string;\n\n /**\n * Dynamic token provider — called before every request.\n * Use this when tokens may rotate (e.g., auto-refresh).\n * Takes precedence over `accessToken` if both are set.\n */\n getAccessToken?: () => string | Promise<string>;\n\n /**\n * Custom headers to include in every request.\n * Useful for passing app identifiers or tracing headers.\n */\n headers?: Record<string, string>;\n}\n\n// ─── Core namespace interfaces (tRPC) ───────────────────────\n\nexport interface ZcoinNamespace {\n /** Get the authenticated user's Z-coin balance. */\n getMyBalance(): Promise<ZcoinGetMyBalanceOutput>;\n\n /** Get the authenticated user's Z-coin transaction history. */\n getMyHistory(input?: ZcoinGetMyHistoryInput): Promise<any[]>;\n\n /** Get available Z-coin deposit packages with pricing. */\n getDepositPackages(input?: ZcoinGetDepositPackagesInput): Promise<ZcoinDepositPackage[]>;\n\n /** Create a Stripe checkout session for Z-coin deposit. */\n createDepositOrder(input: ZcoinCreateDepositOrderInput): Promise<ZcoinCreateDepositOrderOutput>;\n\n /** Check the status of a deposit checkout session. */\n getDepositStatus(input: ZcoinGetDepositStatusInput): Promise<ZcoinGetDepositStatusOutput>;\n\n /**\n * Generate a deposit deep link URL for Z-coin top-up.\n * Returns a URL that redirects users to Core's deposit page.\n * After completing the deposit, the user is redirected back to returnUrl.\n *\n * No authentication required — anyone can generate a deposit URL.\n *\n * @example\n * ```ts\n * const { url } = await goodz.zcoin.getDepositUrl({\n * amount: 100,\n * returnUrl: \"https://myapp.com/shop\",\n * appId: \"od_myapp\",\n * });\n * window.open(url, \"_blank\");\n * ```\n */\n getDepositUrl(input?: ZcoinGetDepositUrlInput): Promise<ZcoinGetDepositUrlOutput>;\n\n /**\n * Atomic commercial transfer: Z-coin payment + ownership transfer in one transaction.\n * This is the primary API for Commerce and Exchange purchase flows.\n *\n * Idempotent via referenceId — duplicate calls return the same result.\n *\n * @throws {GoodZApiError} INSUFFICIENT_BALANCE — use `e.isInsufficientBalance()` to detect,\n * `e.depositUrl` to get the top-up redirect URL\n * @throws {GoodZApiError} CONFLICT — version conflict (retry)\n * @throws {GoodZApiError} FORBIDDEN — seller doesn't own instance\n */\n commercialTransfer(input: ZcoinCommercialTransferInput): Promise<ZcoinCommercialTransferOutput>;\n\n /**\n * Mint a new card instance and charge the buyer in one atomic transaction.\n * Used by Commerce for gacha and direct-from-creator purchases.\n *\n * Requires mint authorization (granted via inventory.grantMintAuth).\n * Idempotent via referenceId.\n *\n * @throws {GoodZApiError} FORBIDDEN — no mint authorization\n * @throws {GoodZApiError} INSUFFICIENT_BALANCE — use `e.isInsufficientBalance()` to detect,\n * `e.depositUrl` to get the top-up redirect URL\n */\n mintAndCharge(input: ZcoinMintAndChargeInput): Promise<ZcoinMintAndChargeOutput>;\n\n /**\n * Charge a user's Z-coin balance for an in-app purchase.\n * Used by apps that sell non-GoodZ digital goods/services.\n *\n * Idempotent via appOrderId.\n *\n * @throws {GoodZApiError} INSUFFICIENT_BALANCE — use `e.isInsufficientBalance()` to detect,\n * `e.depositUrl` to get the top-up redirect URL\n * @throws {GoodZApiError} CONFLICT — version conflict\n */\n chargeUser(input: ZcoinChargeUserInput): Promise<ZcoinChargeUserOutput>;\n\n /**\n * Create a direct purchase checkout session (fiat → Z-coin → transfer).\n * Transparent intermediation: user sees fiat price, Core handles conversion.\n */\n createDirectPurchaseOrder(input: ZcoinCreateDirectPurchaseOrderInput): Promise<ZcoinCreateDirectPurchaseOrderOutput>;\n}\n\nexport interface InventoryNamespace {\n /** Get a user's inventory (owned card instances). */\n getUserInventory(input: InventoryGetUserInventoryInput): Promise<InventoryItem[]>;\n\n /** Check if a user owns at least one instance of a specific card. */\n confirmOwnership(input: InventoryConfirmOwnershipInput): Promise<InventoryConfirmOwnershipOutput>;\n\n /**\n * Mint new card instances. Requires franchise ownership or admin role.\n * For Commerce/Exchange, use zcoin.mintAndCharge instead (includes payment).\n */\n mint(input: InventoryMintInput): Promise<InventoryMintOutput>;\n\n /**\n * Transfer a specific card instance to another user.\n * For commercial transfers, use zcoin.commercialTransfer instead.\n *\n * @deprecated for reason=\"purchase\"|\"trade\" — use commercialTransfer\n */\n transfer(input: InventoryTransferInput): Promise<InventoryTransferOutput>;\n\n /**\n * Transfer card instances by cardId (transfers oldest instances).\n * For commercial transfers, use zcoin.commercialTransfer instead.\n *\n * @deprecated for reason=\"purchase\"|\"trade\" — use commercialTransfer\n */\n transferByCard(input: InventoryTransferByCardInput): Promise<InventoryTransferByCardOutput>;\n\n /**\n * Grant mint authorization to another user/app for a specific card.\n * Required before Commerce can call zcoin.mintAndCharge for that card.\n */\n grantMintAuth(input: InventoryGrantMintAuthInput): Promise<any>;\n\n /** Get transfer/ownership history for an instance, card, or user. */\n transferHistory(input: InventoryTransferHistoryInput): Promise<any[]>;\n}\n\nexport interface CollectibleNamespace {\n /** Get a card instance by its numeric ID. Returns full instance data with card chain. */\n getInstanceById(input: CollectibleGetInstanceByIdInput): Promise<any>;\n\n /** Get a card instance by its instance code (public-facing identifier). */\n getPublicInstance(input: CollectibleGetPublicInstanceInput): Promise<any>;\n\n /** Batch-fetch multiple card instances by their IDs (max 100). */\n getPublicInstancesBatch(input: CollectibleGetPublicInstancesBatchInput): Promise<any[]>;\n\n /** Get the card profile (metadata, rarity, series info). */\n getCardProfile(input: CollectibleGetCardProfileInput): Promise<any>;\n\n /** Get the shell (packaging) image URL for a card. */\n getShellImageUrl(input: CollectibleGetShellImageUrlInput): Promise<any>;\n}\n\nexport interface UserNamespace {\n /** Get a user's public profile by openId. */\n getPublicProfile(input: UserGetPublicProfileInput): Promise<UserPublicProfile>;\n\n /** Get a user's public profile by internal userId. */\n getPublicProfileById(input: UserGetPublicProfileByIdInput): Promise<UserPublicProfile>;\n}\n\nexport interface AuthNamespace {\n /** Get the authenticated user's profile. Returns null if not authenticated. */\n me(): Promise<AuthUser | null>;\n\n /** Get public info about an OAuth app by its client ID. */\n getOAuthAppInfo(input: AuthGetOAuthAppInfoInput): Promise<AuthOAuthAppInfo | null>;\n}\n\nexport interface IpNamespace {\n /** Get a franchise by ID or slug. */\n getFranchise(input: FranchiseGetInput): Promise<any>;\n\n /** Get a series by ID or slug. */\n getSeries(input: SeriesGetInput): Promise<any>;\n\n /** List all series in a franchise. */\n listSeriesByFranchise(input: SeriesListByFranchiseInput): Promise<any[]>;\n\n /** Get a card by ID. */\n getCard(input: CardGetInput): Promise<any>;\n\n /** List all cards in a series. */\n listCardsBySeries(input: CardListBySeriesInput): Promise<any[]>;\n}\n\n// ─── GoodZClient type ────────────────────────────────────────\n\nexport interface GoodZClient {\n // ── Core namespaces (tRPC) ──\n readonly zcoin: ZcoinNamespace;\n readonly inventory: InventoryNamespace;\n readonly collectible: CollectibleNamespace;\n readonly user: UserNamespace;\n readonly auth: AuthNamespace;\n readonly ip: IpNamespace;\n\n // ── Sub-site namespaces (MCP) ──\n readonly commerce: CommerceNamespace;\n readonly exchange: ExchangeNamespace;\n readonly alive: AliveNamespace;\n\n /**\n * Make a raw tRPC query call to Core. Use this for routes not yet covered\n * by the typed namespaces.\n */\n rawQuery<T = any>(path: string, input?: any): Promise<T>;\n\n /**\n * Make a raw tRPC mutation call to Core. Use this for routes not yet covered\n * by the typed namespaces.\n */\n rawMutation<T = any>(path: string, input?: any): Promise<T>;\n}\n\n// ─── Client factory ──────────────────────────────────────────\n\n/**\n * Create a unified GoodZ API client — one client for all services.\n *\n * @example Server-to-server with static token\n * ```ts\n * const goodz = createGoodZClient({\n * accessToken: process.env.CORE_ACCESS_TOKEN,\n * });\n *\n * // Core\n * const balance = await goodz.zcoin.getMyBalance();\n *\n * // Commerce\n * const shop = await goodz.commerce.createShop({ name: \"My Shop\" });\n *\n * // Exchange\n * const listings = await goodz.exchange.browseMarketplace();\n *\n * // Alive\n * const chat = await goodz.alive.sendMessage({ instanceId: 1, userId: 1, message: \"Hi!\" });\n * ```\n *\n * @example With dynamic token provider (auto-refresh)\n * ```ts\n * const goodz = createGoodZClient({\n * getAccessToken: async () => {\n * const token = await refreshTokenIfNeeded();\n * return token;\n * },\n * });\n * ```\n *\n * @example Custom sub-site URLs (e.g., staging environment)\n * ```ts\n * const goodz = createGoodZClient({\n * accessToken: \"...\",\n * coreUrl: \"https://staging-core.goodz.dev\",\n * commerceUrl: \"https://staging-commerce.goodz.dev\",\n * exchangeUrl: \"https://staging-exchange.goodz.dev\",\n * aliveUrl: \"https://staging-alive.goodz.dev\",\n * });\n * ```\n */\nexport function createGoodZClient(config: GoodZClientConfig = {}): GoodZClient {\n const {\n coreUrl = DEFAULT_CORE_URL,\n commerceUrl = DEFAULT_COMMERCE_URL,\n exchangeUrl = DEFAULT_EXCHANGE_URL,\n aliveUrl = DEFAULT_ALIVE_URL,\n accessToken,\n getAccessToken,\n headers: customHeaders,\n } = config;\n\n // Shared header builder — used by both tRPC and MCP transports\n const buildHeaders = async (): Promise<Record<string, string>> => {\n const h: Record<string, string> = { ...customHeaders };\n const token = getAccessToken ? await getAccessToken() : accessToken;\n if (token) {\n h[\"Authorization\"] = `Bearer ${token}`;\n }\n return h;\n };\n\n // ── Core transport (tRPC) ──\n const coreTransport: TransportConfig = {\n baseUrl: coreUrl.replace(/\\/$/, \"\"),\n getHeaders: buildHeaders,\n };\n\n // ── Sub-site transports (MCP) ──\n const commerceTransport = createMcpTransportConfig(commerceUrl, buildHeaders);\n const exchangeTransport = createMcpTransportConfig(exchangeUrl, buildHeaders);\n const aliveTransport = createMcpTransportConfig(aliveUrl, buildHeaders);\n\n // Helper shortcuts for Core tRPC\n const q = <I, O>(path: string) => (input?: I) => callQuery<I, O>(coreTransport, path, input);\n const m = <I, O>(path: string) => (input?: I) => callMutation<I, O>(coreTransport, path, input);\n\n return {\n // ── zcoin ──────────────────────────────────────────────\n zcoin: {\n getMyBalance: q<void, ZcoinGetMyBalanceOutput>(\"zcoin.getMyBalance\"),\n getMyHistory: q<ZcoinGetMyHistoryInput, any[]>(\"zcoin.getMyHistory\"),\n getDepositPackages: q<ZcoinGetDepositPackagesInput, ZcoinDepositPackage[]>(\"zcoin.getDepositPackages\"),\n createDepositOrder: m<ZcoinCreateDepositOrderInput, ZcoinCreateDepositOrderOutput>(\"zcoin.createDepositOrder\"),\n getDepositStatus: q<ZcoinGetDepositStatusInput, ZcoinGetDepositStatusOutput>(\"zcoin.getDepositStatus\"),\n getDepositUrl: q<ZcoinGetDepositUrlInput, ZcoinGetDepositUrlOutput>(\"zcoin.getDepositUrl\"),\n commercialTransfer: m<ZcoinCommercialTransferInput, ZcoinCommercialTransferOutput>(\"zcoin.commercialTransfer\"),\n mintAndCharge: m<ZcoinMintAndChargeInput, ZcoinMintAndChargeOutput>(\"zcoin.mintAndCharge\"),\n chargeUser: m<ZcoinChargeUserInput, ZcoinChargeUserOutput>(\"zcoin.chargeUser\"),\n createDirectPurchaseOrder: m<ZcoinCreateDirectPurchaseOrderInput, ZcoinCreateDirectPurchaseOrderOutput>(\"zcoin.createDirectPurchaseOrder\"),\n },\n\n // ── inventory ──────────────────────────────────────────\n inventory: {\n getUserInventory: q<InventoryGetUserInventoryInput, InventoryItem[]>(\"inventory.getUserInventory\"),\n confirmOwnership: q<InventoryConfirmOwnershipInput, InventoryConfirmOwnershipOutput>(\"inventory.confirmOwnership\"),\n mint: m<InventoryMintInput, InventoryMintOutput>(\"inventory.mint\"),\n transfer: m<InventoryTransferInput, InventoryTransferOutput>(\"inventory.transfer\"),\n transferByCard: m<InventoryTransferByCardInput, InventoryTransferByCardOutput>(\"inventory.transferByCard\"),\n grantMintAuth: m<InventoryGrantMintAuthInput, any>(\"inventory.grantMintAuth\"),\n transferHistory: q<InventoryTransferHistoryInput, any[]>(\"inventory.transferHistory\"),\n },\n\n // ── collectible ────────────────────────────────────────\n collectible: {\n getInstanceById: q<CollectibleGetInstanceByIdInput, any>(\"collectible.getInstanceById\"),\n getPublicInstance: q<CollectibleGetPublicInstanceInput, any>(\"collectible.getPublicInstance\"),\n getPublicInstancesBatch: q<CollectibleGetPublicInstancesBatchInput, any[]>(\"collectible.getPublicInstancesBatch\"),\n getCardProfile: q<CollectibleGetCardProfileInput, any>(\"collectible.getCardProfile\"),\n getShellImageUrl: q<CollectibleGetShellImageUrlInput, any>(\"collectible.getShellImageUrl\"),\n },\n\n // ── user ───────────────────────────────────────────────\n user: {\n getPublicProfile: q<UserGetPublicProfileInput, UserPublicProfile>(\"user.getPublicProfile\"),\n getPublicProfileById: q<UserGetPublicProfileByIdInput, UserPublicProfile>(\"user.getPublicProfileById\"),\n },\n\n // ── auth ───────────────────────────────────────────────\n auth: {\n me: q<void, AuthUser | null>(\"auth.me\"),\n getOAuthAppInfo: q<AuthGetOAuthAppInfoInput, AuthOAuthAppInfo | null>(\"auth.getOAuthAppInfo\"),\n },\n\n // ── ip (franchise/series/card) ─────────────────────────\n ip: {\n getFranchise: q<FranchiseGetInput, any>(\"franchise.get\"),\n getSeries: q<SeriesGetInput, any>(\"series.get\"),\n listSeriesByFranchise: q<SeriesListByFranchiseInput, any[]>(\"series.listByFranchise\"),\n getCard: q<CardGetInput, any>(\"card.get\"),\n listCardsBySeries: q<CardListBySeriesInput, any[]>(\"card.listBySeries\"),\n },\n\n // ── commerce (MCP) ─────────────────────────────────────\n commerce: createCommerceNamespace(commerceTransport),\n\n // ── exchange (MCP) ─────────────────────────────────────\n exchange: createExchangeNamespace(exchangeTransport),\n\n // ── alive (MCP) ────────────────────────────────────────\n alive: createAliveNamespace(aliveTransport),\n\n // ── raw escape hatches (Core tRPC only) ────────────────\n rawQuery: <T = any>(path: string, input?: any) => callQuery<any, T>(coreTransport, path, input),\n rawMutation: <T = any>(path: string, input?: any) => callMutation<any, T>(coreTransport, path, input),\n };\n}\n\n/**\n * Alias for createGoodZClient — creates a client acting on behalf of a user.\n * Semantically identical, but makes the intent clearer in server-to-server code.\n */\nexport const createUserClient = createGoodZClient;\n"]}
@@ -1,4 +1,4 @@
1
- import { callMcpTool } from './chunk-4SU7SU7K.js';
1
+ import { callMcpTool } from './chunk-ORUFMYZB.js';
2
2
 
3
3
  // src/exchange/index.ts
4
4
  function createExchangeNamespace(transport) {
@@ -33,5 +33,5 @@ function createExchangeNamespace(transport) {
33
33
  }
34
34
 
35
35
  export { createExchangeNamespace };
36
- //# sourceMappingURL=chunk-OUKZ2PRD.js.map
37
- //# sourceMappingURL=chunk-OUKZ2PRD.js.map
36
+ //# sourceMappingURL=chunk-GH33FPMY.js.map
37
+ //# sourceMappingURL=chunk-GH33FPMY.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/exchange/index.ts"],"names":[],"mappings":";;;AAqGO,SAAS,wBAAwB,SAAA,EAA+C;AACrF,EAAA,MAAM,IAAA,GAAO,CAAmC,IAAA,KAC9C,CAAC,UAAc,WAAA,CAAkB,SAAA,EAAW,MAAM,KAAU,CAAA;AAE9D,EAAA,OAAO;AAAA;AAAA,IAEL,iBAAA,EAAmB,KAAwD,oBAAoB,CAAA;AAAA,IAC/F,gBAAA,EAAkB,KAAqD,oBAAoB,CAAA;AAAA;AAAA,IAG3F,aAAA,EAAe,KAA8D,gBAAgB,CAAA;AAAA,IAC7F,aAAA,EAAe,KAAsC,gBAAgB,CAAA;AAAA;AAAA,IAGrE,UAAA,EAAY,KAAwD,aAAa,CAAA;AAAA,IACjF,QAAA,EAAU,KAAoD,WAAW,CAAA;AAAA,IACzE,OAAA,EAAS,KAA0C,UAAU,CAAA;AAAA;AAAA,IAG7D,SAAA,EAAW,KAA0C,YAAY,CAAA;AAAA,IACjE,UAAA,EAAY,KAAwD,aAAa,CAAA;AAAA,IACjF,SAAA,EAAW,KAAkC,YAAY,CAAA;AAAA;AAAA,IAGzD,YAAA,EAAc,KAAuD,eAAe,CAAA;AAAA,IACpF,cAAA,EAAgB,KAAgE,kBAAkB,CAAA;AAAA;AAAA,IAGlG,YAAA,EAAc,KAAqD,eAAe,CAAA;AAAA,IAClF,cAAA,EAAgB,KAAyD,kBAAkB,CAAA;AAAA,IAC3F,mBAAA,EAAqB,KAA4C,uBAAuB,CAAA;AAAA;AAAA,IAGxF,aAAA,EAAe,KAAqD,iBAAiB,CAAA;AAAA;AAAA,IAGrF,SAAS,CAAU,QAAA,EAAkB,SACnC,WAAA,CAAoC,SAAA,EAAW,UAAU,IAAI;AAAA,GACjE;AACF","file":"chunk-OUKZ2PRD.js","sourcesContent":["/**\n * @goodz-core/sdk — Exchange Namespace\n *\n * Provides typed access to GoodZ.Exchange MCP tools:\n * marketplace listings, auctions, WTB, P2P trades,\n * watchlist, and market data.\n *\n * All prices are in Z-coin (1 Z-coin = $0.10 USD).\n *\n * @module\n */\n\nimport { callMcpTool } from \"../mcp-transport\";\nimport type { TransportConfig } from \"../mcp-transport\";\nimport type {\n ExchangeBrowseMarketplaceInput,\n ExchangeListing,\n ExchangeGetListingDetailInput,\n ExchangeCreateListingInput,\n ExchangeCreateListingOutput,\n ExchangeCancelListingInput,\n ExchangeBuyListingInput,\n ExchangeBuyListingOutput,\n ExchangePlaceBidInput,\n ExchangePlaceBidOutput,\n ExchangeGetBidsInput,\n ExchangeBid,\n ExchangeCreateWtbInput,\n ExchangeWtb,\n ExchangeFulfillWtbInput,\n ExchangeFulfillWtbOutput,\n ExchangeCancelWtbInput,\n ExchangeProposeTradeInput,\n ExchangeTradeProposal,\n ExchangeRespondToTradeInput,\n ExchangeRespondToTradeOutput,\n ExchangeAddToWatchlistInput,\n ExchangeWatchlistItem,\n ExchangeRemoveFromWatchlistInput,\n ExchangeGetMarketDataInput,\n ExchangeMarketData,\n} from \"../types-exchange\";\n\n// Re-export all Exchange types\nexport type * from \"../types-exchange\";\n\n// ─── Namespace interface ────────────────────────────────────\n\nexport interface ExchangeNamespace {\n // Marketplace\n /** Browse active marketplace listings. */\n browseMarketplace(input?: ExchangeBrowseMarketplaceInput): Promise<ExchangeListing[]>;\n /** Get detailed info about a specific listing. */\n getListingDetail(input: ExchangeGetListingDetailInput): Promise<ExchangeListing>;\n\n // Listing Management\n /** Create a new listing (fixed_price or auction). Core locks the instance atomically. */\n createListing(input: ExchangeCreateListingInput): Promise<ExchangeCreateListingOutput>;\n /** Cancel an active listing. Core unlocks the instance. */\n cancelListing(input: ExchangeCancelListingInput): Promise<any>;\n\n // Purchase & Bidding\n /** Buy a fixed-price listing. Z-coin debit + ownership transfer via Core settlement. */\n buyListing(input: ExchangeBuyListingInput): Promise<ExchangeBuyListingOutput>;\n /** Place a bid on an auction. If bid meets buy-now price, immediate purchase is executed. */\n placeBid(input: ExchangePlaceBidInput): Promise<ExchangePlaceBidOutput>;\n /** Get all bids for an auction listing (highest first). */\n getBids(input: ExchangeGetBidsInput): Promise<ExchangeBid[]>;\n\n // Want-to-Buy\n /** Create a WTB request — announce what you're looking for. */\n createWtb(input: ExchangeCreateWtbInput): Promise<ExchangeWtb>;\n /** Fulfill a WTB request by offering your item. Settlement via Core. */\n fulfillWtb(input: ExchangeFulfillWtbInput): Promise<ExchangeFulfillWtbOutput>;\n /** Cancel your own WTB request. */\n cancelWtb(input: ExchangeCancelWtbInput): Promise<any>;\n\n // P2P Trade\n /** Propose a trade/swap with another user. Optional Z-coin compensation. */\n proposeTrade(input: ExchangeProposeTradeInput): Promise<ExchangeTradeProposal>;\n /** Accept or reject a trade proposal. If accepted, all items transfer via Core. */\n respondToTrade(input: ExchangeRespondToTradeInput): Promise<ExchangeRespondToTradeOutput>;\n\n // Watchlist\n /** Get your watchlist. */\n getWatchlist(): Promise<ExchangeWatchlistItem[]>;\n /** Add a GoodZ or listing to your watchlist. */\n addToWatchlist(input: ExchangeAddToWatchlistInput): Promise<ExchangeWatchlistItem>;\n /** Remove an item from your watchlist. */\n removeFromWatchlist(input: ExchangeRemoveFromWatchlistInput): Promise<any>;\n\n // Market Data\n /** Get market data: price history, floor price, volume, trends. */\n getMarketData(input: ExchangeGetMarketDataInput): Promise<ExchangeMarketData>;\n\n /** Call a raw MCP tool by name. Escape hatch for tools not yet in the typed API. */\n rawTool<T = any>(toolName: string, args?: Record<string, any>): Promise<T>;\n}\n\n// ─── Factory ────────────────────────────────────────────────\n\nexport function createExchangeNamespace(transport: TransportConfig): ExchangeNamespace {\n const tool = <I extends Record<string, any>, O>(name: string) =>\n (input?: I) => callMcpTool<I, O>(transport, name, input as I);\n\n return {\n // Marketplace\n browseMarketplace: tool<ExchangeBrowseMarketplaceInput, ExchangeListing[]>(\"browse_marketplace\"),\n getListingDetail: tool<ExchangeGetListingDetailInput, ExchangeListing>(\"get_listing_detail\"),\n\n // Listing Management\n createListing: tool<ExchangeCreateListingInput, ExchangeCreateListingOutput>(\"create_listing\"),\n cancelListing: tool<ExchangeCancelListingInput, any>(\"cancel_listing\"),\n\n // Purchase & Bidding\n buyListing: tool<ExchangeBuyListingInput, ExchangeBuyListingOutput>(\"buy_listing\"),\n placeBid: tool<ExchangePlaceBidInput, ExchangePlaceBidOutput>(\"place_bid\"),\n getBids: tool<ExchangeGetBidsInput, ExchangeBid[]>(\"get_bids\"),\n\n // WTB\n createWtb: tool<ExchangeCreateWtbInput, ExchangeWtb>(\"create_wtb\"),\n fulfillWtb: tool<ExchangeFulfillWtbInput, ExchangeFulfillWtbOutput>(\"fulfill_wtb\"),\n cancelWtb: tool<ExchangeCancelWtbInput, any>(\"cancel_wtb\"),\n\n // P2P Trade\n proposeTrade: tool<ExchangeProposeTradeInput, ExchangeTradeProposal>(\"propose_trade\"),\n respondToTrade: tool<ExchangeRespondToTradeInput, ExchangeRespondToTradeOutput>(\"respond_to_trade\"),\n\n // Watchlist\n getWatchlist: tool<Record<string, never>, ExchangeWatchlistItem[]>(\"get_watchlist\"),\n addToWatchlist: tool<ExchangeAddToWatchlistInput, ExchangeWatchlistItem>(\"add_to_watchlist\"),\n removeFromWatchlist: tool<ExchangeRemoveFromWatchlistInput, any>(\"remove_from_watchlist\"),\n\n // Market Data\n getMarketData: tool<ExchangeGetMarketDataInput, ExchangeMarketData>(\"get_market_data\"),\n\n // Raw escape hatch\n rawTool: <T = any>(toolName: string, args?: Record<string, any>) =>\n callMcpTool<Record<string, any>, T>(transport, toolName, args),\n };\n}\n"]}
1
+ {"version":3,"sources":["../src/exchange/index.ts"],"names":[],"mappings":";;;AAqGO,SAAS,wBAAwB,SAAA,EAA+C;AACrF,EAAA,MAAM,IAAA,GAAO,CAAmC,IAAA,KAC9C,CAAC,UAAc,WAAA,CAAkB,SAAA,EAAW,MAAM,KAAU,CAAA;AAE9D,EAAA,OAAO;AAAA;AAAA,IAEL,iBAAA,EAAmB,KAAwD,oBAAoB,CAAA;AAAA,IAC/F,gBAAA,EAAkB,KAAqD,oBAAoB,CAAA;AAAA;AAAA,IAG3F,aAAA,EAAe,KAA8D,gBAAgB,CAAA;AAAA,IAC7F,aAAA,EAAe,KAAsC,gBAAgB,CAAA;AAAA;AAAA,IAGrE,UAAA,EAAY,KAAwD,aAAa,CAAA;AAAA,IACjF,QAAA,EAAU,KAAoD,WAAW,CAAA;AAAA,IACzE,OAAA,EAAS,KAA0C,UAAU,CAAA;AAAA;AAAA,IAG7D,SAAA,EAAW,KAA0C,YAAY,CAAA;AAAA,IACjE,UAAA,EAAY,KAAwD,aAAa,CAAA;AAAA,IACjF,SAAA,EAAW,KAAkC,YAAY,CAAA;AAAA;AAAA,IAGzD,YAAA,EAAc,KAAuD,eAAe,CAAA;AAAA,IACpF,cAAA,EAAgB,KAAgE,kBAAkB,CAAA;AAAA;AAAA,IAGlG,YAAA,EAAc,KAAqD,eAAe,CAAA;AAAA,IAClF,cAAA,EAAgB,KAAyD,kBAAkB,CAAA;AAAA,IAC3F,mBAAA,EAAqB,KAA4C,uBAAuB,CAAA;AAAA;AAAA,IAGxF,aAAA,EAAe,KAAqD,iBAAiB,CAAA;AAAA;AAAA,IAGrF,SAAS,CAAU,QAAA,EAAkB,SACnC,WAAA,CAAoC,SAAA,EAAW,UAAU,IAAI;AAAA,GACjE;AACF","file":"chunk-GH33FPMY.js","sourcesContent":["/**\n * @goodz-core/sdk — Exchange Namespace\n *\n * Provides typed access to GoodZ.Exchange MCP tools:\n * marketplace listings, auctions, WTB, P2P trades,\n * watchlist, and market data.\n *\n * All prices are in Z-coin (1 Z-coin = $0.10 USD).\n *\n * @module\n */\n\nimport { callMcpTool } from \"../mcp-transport\";\nimport type { TransportConfig } from \"../mcp-transport\";\nimport type {\n ExchangeBrowseMarketplaceInput,\n ExchangeListing,\n ExchangeGetListingDetailInput,\n ExchangeCreateListingInput,\n ExchangeCreateListingOutput,\n ExchangeCancelListingInput,\n ExchangeBuyListingInput,\n ExchangeBuyListingOutput,\n ExchangePlaceBidInput,\n ExchangePlaceBidOutput,\n ExchangeGetBidsInput,\n ExchangeBid,\n ExchangeCreateWtbInput,\n ExchangeWtb,\n ExchangeFulfillWtbInput,\n ExchangeFulfillWtbOutput,\n ExchangeCancelWtbInput,\n ExchangeProposeTradeInput,\n ExchangeTradeProposal,\n ExchangeRespondToTradeInput,\n ExchangeRespondToTradeOutput,\n ExchangeAddToWatchlistInput,\n ExchangeWatchlistItem,\n ExchangeRemoveFromWatchlistInput,\n ExchangeGetMarketDataInput,\n ExchangeMarketData,\n} from \"../types-exchange\";\n\n// Re-export all Exchange types\nexport type * from \"../types-exchange\";\n\n// ─── Namespace interface ────────────────────────────────────\n\nexport interface ExchangeNamespace {\n // Marketplace\n /** Browse active marketplace listings. */\n browseMarketplace(input?: ExchangeBrowseMarketplaceInput): Promise<ExchangeListing[]>;\n /** Get detailed info about a specific listing. */\n getListingDetail(input: ExchangeGetListingDetailInput): Promise<ExchangeListing>;\n\n // Listing Management\n /** Create a new listing (fixed_price or auction). Core locks the instance atomically. */\n createListing(input: ExchangeCreateListingInput): Promise<ExchangeCreateListingOutput>;\n /** Cancel an active listing. Core unlocks the instance. */\n cancelListing(input: ExchangeCancelListingInput): Promise<any>;\n\n // Purchase & Bidding\n /** Buy a fixed-price listing. Z-coin debit + ownership transfer via Core settlement. */\n buyListing(input: ExchangeBuyListingInput): Promise<ExchangeBuyListingOutput>;\n /** Place a bid on an auction. If bid meets buy-now price, immediate purchase is executed. */\n placeBid(input: ExchangePlaceBidInput): Promise<ExchangePlaceBidOutput>;\n /** Get all bids for an auction listing (highest first). */\n getBids(input: ExchangeGetBidsInput): Promise<ExchangeBid[]>;\n\n // Want-to-Buy\n /** Create a WTB request — announce what you're looking for. */\n createWtb(input: ExchangeCreateWtbInput): Promise<ExchangeWtb>;\n /** Fulfill a WTB request by offering your item. Settlement via Core. */\n fulfillWtb(input: ExchangeFulfillWtbInput): Promise<ExchangeFulfillWtbOutput>;\n /** Cancel your own WTB request. */\n cancelWtb(input: ExchangeCancelWtbInput): Promise<any>;\n\n // P2P Trade\n /** Propose a trade/swap with another user. Optional Z-coin compensation. */\n proposeTrade(input: ExchangeProposeTradeInput): Promise<ExchangeTradeProposal>;\n /** Accept or reject a trade proposal. If accepted, all items transfer via Core. */\n respondToTrade(input: ExchangeRespondToTradeInput): Promise<ExchangeRespondToTradeOutput>;\n\n // Watchlist\n /** Get your watchlist. */\n getWatchlist(): Promise<ExchangeWatchlistItem[]>;\n /** Add a GoodZ or listing to your watchlist. */\n addToWatchlist(input: ExchangeAddToWatchlistInput): Promise<ExchangeWatchlistItem>;\n /** Remove an item from your watchlist. */\n removeFromWatchlist(input: ExchangeRemoveFromWatchlistInput): Promise<any>;\n\n // Market Data\n /** Get market data: price history, floor price, volume, trends. */\n getMarketData(input: ExchangeGetMarketDataInput): Promise<ExchangeMarketData>;\n\n /** Call a raw MCP tool by name. Escape hatch for tools not yet in the typed API. */\n rawTool<T = any>(toolName: string, args?: Record<string, any>): Promise<T>;\n}\n\n// ─── Factory ────────────────────────────────────────────────\n\nexport function createExchangeNamespace(transport: TransportConfig): ExchangeNamespace {\n const tool = <I extends Record<string, any>, O>(name: string) =>\n (input?: I) => callMcpTool<I, O>(transport, name, input as I);\n\n return {\n // Marketplace\n browseMarketplace: tool<ExchangeBrowseMarketplaceInput, ExchangeListing[]>(\"browse_marketplace\"),\n getListingDetail: tool<ExchangeGetListingDetailInput, ExchangeListing>(\"get_listing_detail\"),\n\n // Listing Management\n createListing: tool<ExchangeCreateListingInput, ExchangeCreateListingOutput>(\"create_listing\"),\n cancelListing: tool<ExchangeCancelListingInput, any>(\"cancel_listing\"),\n\n // Purchase & Bidding\n buyListing: tool<ExchangeBuyListingInput, ExchangeBuyListingOutput>(\"buy_listing\"),\n placeBid: tool<ExchangePlaceBidInput, ExchangePlaceBidOutput>(\"place_bid\"),\n getBids: tool<ExchangeGetBidsInput, ExchangeBid[]>(\"get_bids\"),\n\n // WTB\n createWtb: tool<ExchangeCreateWtbInput, ExchangeWtb>(\"create_wtb\"),\n fulfillWtb: tool<ExchangeFulfillWtbInput, ExchangeFulfillWtbOutput>(\"fulfill_wtb\"),\n cancelWtb: tool<ExchangeCancelWtbInput, any>(\"cancel_wtb\"),\n\n // P2P Trade\n proposeTrade: tool<ExchangeProposeTradeInput, ExchangeTradeProposal>(\"propose_trade\"),\n respondToTrade: tool<ExchangeRespondToTradeInput, ExchangeRespondToTradeOutput>(\"respond_to_trade\"),\n\n // Watchlist\n getWatchlist: tool<Record<string, never>, ExchangeWatchlistItem[]>(\"get_watchlist\"),\n addToWatchlist: tool<ExchangeAddToWatchlistInput, ExchangeWatchlistItem>(\"add_to_watchlist\"),\n removeFromWatchlist: tool<ExchangeRemoveFromWatchlistInput, any>(\"remove_from_watchlist\"),\n\n // Market Data\n getMarketData: tool<ExchangeGetMarketDataInput, ExchangeMarketData>(\"get_market_data\"),\n\n // Raw escape hatch\n rawTool: <T = any>(toolName: string, args?: Record<string, any>) =>\n callMcpTool<Record<string, any>, T>(transport, toolName, args),\n };\n}\n"]}
@@ -1,4 +1,4 @@
1
- import { callMcpTool } from './chunk-4SU7SU7K.js';
1
+ import { callMcpTool } from './chunk-ORUFMYZB.js';
2
2
 
3
3
  // src/alive/index.ts
4
4
  function createAliveNamespace(transport) {
@@ -23,5 +23,5 @@ function createAliveNamespace(transport) {
23
23
  }
24
24
 
25
25
  export { createAliveNamespace };
26
- //# sourceMappingURL=chunk-JAVMQXJM.js.map
27
- //# sourceMappingURL=chunk-JAVMQXJM.js.map
26
+ //# sourceMappingURL=chunk-KP7DP5LP.js.map
27
+ //# sourceMappingURL=chunk-KP7DP5LP.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/alive/index.ts"],"names":[],"mappings":";;;AAqEO,SAAS,qBAAqB,SAAA,EAA4C;AAC/E,EAAA,MAAM,IAAA,GAAO,CAAmC,IAAA,KAC9C,CAAC,UAAc,WAAA,CAAkB,SAAA,EAAW,MAAM,KAAU,CAAA;AAE9D,EAAA,OAAO;AAAA;AAAA,IAEL,WAAA,EAAa,KAAyC,cAAc,CAAA;AAAA,IACpE,cAAA,EAAgB,KAA8C,iBAAiB,CAAA;AAAA,IAC/E,YAAA,EAAc,KAAkC,eAAe,CAAA;AAAA;AAAA,IAG/D,WAAA,EAAa,KAA2C,cAAc,CAAA;AAAA,IACtE,cAAA,EAAgB,KAA8C,iBAAiB,CAAA;AAAA;AAAA,IAG/E,YAAA,EAAc,KAA2C,eAAe,CAAA;AAAA;AAAA,IAGxE,cAAA,EAAgB,KAAsD,iBAAiB,CAAA;AAAA;AAAA,IAGvF,WAAA,EAAa,KAA+C,cAAc,CAAA;AAAA;AAAA,IAG1E,SAAS,CAAU,QAAA,EAAkB,SACnC,WAAA,CAAoC,SAAA,EAAW,UAAU,IAAI;AAAA,GACjE;AACF","file":"chunk-JAVMQXJM.js","sourcesContent":["/**\n * @goodz-core/sdk — Alive Namespace\n *\n * Provides typed access to GoodZ.Alive MCP tools:\n * memory management, intimacy/affection, context building,\n * intent classification, and chat sessions.\n *\n * GoodZ.Alive gives each GoodZ card a \"soul\" — an AI-powered\n * companion that remembers, grows, and responds uniquely.\n *\n * @module\n */\n\nimport { callMcpTool } from \"../mcp-transport\";\nimport type { TransportConfig } from \"../mcp-transport\";\nimport type {\n AliveStoreMemoryInput,\n AliveMemory,\n AliveRecallMemoriesInput,\n AliveForgetMemoryInput,\n AliveGetIntimacyInput,\n AliveIntimacy,\n AliveUpdateIntimacyInput,\n AliveBuildContextInput,\n AliveContext,\n AliveClassifyIntentInput,\n AliveClassifiedIntent,\n AliveSendMessageInput,\n AliveChatResponse,\n} from \"../types-alive\";\n\n// Re-export all Alive types\nexport type * from \"../types-alive\";\n\n// ─── Namespace interface ────────────────────────────────────\n\nexport interface AliveNamespace {\n // Memory\n /** Store a new memory for a character-user pair. */\n storeMemory(input: AliveStoreMemoryInput): Promise<AliveMemory>;\n /** Recall relevant memories using semantic search. */\n recallMemories(input: AliveRecallMemoriesInput): Promise<AliveMemory[]>;\n /** Delete a specific memory. */\n forgetMemory(input: AliveForgetMemoryInput): Promise<any>;\n\n // Intimacy\n /** Get the intimacy/affection state between a character and user. */\n getIntimacy(input: AliveGetIntimacyInput): Promise<AliveIntimacy>;\n /** Update intimacy level (e.g., after a positive/negative interaction). */\n updateIntimacy(input: AliveUpdateIntimacyInput): Promise<AliveIntimacy>;\n\n // Context\n /** Build a full context object for AI generation (profile + memories + history + system prompt). */\n buildContext(input: AliveBuildContextInput): Promise<AliveContext>;\n\n // Intent\n /** Classify a user's message into an intent category. */\n classifyIntent(input: AliveClassifyIntentInput): Promise<AliveClassifiedIntent>;\n\n // Chat\n /** Send a message and get a character response (includes memory, intimacy, and intent processing). */\n sendMessage(input: AliveSendMessageInput): Promise<AliveChatResponse>;\n\n /** Call a raw MCP tool by name. Escape hatch for tools not yet in the typed API. */\n rawTool<T = any>(toolName: string, args?: Record<string, any>): Promise<T>;\n}\n\n// ─── Factory ────────────────────────────────────────────────\n\nexport function createAliveNamespace(transport: TransportConfig): AliveNamespace {\n const tool = <I extends Record<string, any>, O>(name: string) =>\n (input?: I) => callMcpTool<I, O>(transport, name, input as I);\n\n return {\n // Memory\n storeMemory: tool<AliveStoreMemoryInput, AliveMemory>(\"store_memory\"),\n recallMemories: tool<AliveRecallMemoriesInput, AliveMemory[]>(\"recall_memories\"),\n forgetMemory: tool<AliveForgetMemoryInput, any>(\"forget_memory\"),\n\n // Intimacy\n getIntimacy: tool<AliveGetIntimacyInput, AliveIntimacy>(\"get_intimacy\"),\n updateIntimacy: tool<AliveUpdateIntimacyInput, AliveIntimacy>(\"update_intimacy\"),\n\n // Context\n buildContext: tool<AliveBuildContextInput, AliveContext>(\"build_context\"),\n\n // Intent\n classifyIntent: tool<AliveClassifyIntentInput, AliveClassifiedIntent>(\"classify_intent\"),\n\n // Chat\n sendMessage: tool<AliveSendMessageInput, AliveChatResponse>(\"send_message\"),\n\n // Raw escape hatch\n rawTool: <T = any>(toolName: string, args?: Record<string, any>) =>\n callMcpTool<Record<string, any>, T>(transport, toolName, args),\n };\n}\n"]}
1
+ {"version":3,"sources":["../src/alive/index.ts"],"names":[],"mappings":";;;AAqEO,SAAS,qBAAqB,SAAA,EAA4C;AAC/E,EAAA,MAAM,IAAA,GAAO,CAAmC,IAAA,KAC9C,CAAC,UAAc,WAAA,CAAkB,SAAA,EAAW,MAAM,KAAU,CAAA;AAE9D,EAAA,OAAO;AAAA;AAAA,IAEL,WAAA,EAAa,KAAyC,cAAc,CAAA;AAAA,IACpE,cAAA,EAAgB,KAA8C,iBAAiB,CAAA;AAAA,IAC/E,YAAA,EAAc,KAAkC,eAAe,CAAA;AAAA;AAAA,IAG/D,WAAA,EAAa,KAA2C,cAAc,CAAA;AAAA,IACtE,cAAA,EAAgB,KAA8C,iBAAiB,CAAA;AAAA;AAAA,IAG/E,YAAA,EAAc,KAA2C,eAAe,CAAA;AAAA;AAAA,IAGxE,cAAA,EAAgB,KAAsD,iBAAiB,CAAA;AAAA;AAAA,IAGvF,WAAA,EAAa,KAA+C,cAAc,CAAA;AAAA;AAAA,IAG1E,SAAS,CAAU,QAAA,EAAkB,SACnC,WAAA,CAAoC,SAAA,EAAW,UAAU,IAAI;AAAA,GACjE;AACF","file":"chunk-KP7DP5LP.js","sourcesContent":["/**\n * @goodz-core/sdk — Alive Namespace\n *\n * Provides typed access to GoodZ.Alive MCP tools:\n * memory management, intimacy/affection, context building,\n * intent classification, and chat sessions.\n *\n * GoodZ.Alive gives each GoodZ card a \"soul\" — an AI-powered\n * companion that remembers, grows, and responds uniquely.\n *\n * @module\n */\n\nimport { callMcpTool } from \"../mcp-transport\";\nimport type { TransportConfig } from \"../mcp-transport\";\nimport type {\n AliveStoreMemoryInput,\n AliveMemory,\n AliveRecallMemoriesInput,\n AliveForgetMemoryInput,\n AliveGetIntimacyInput,\n AliveIntimacy,\n AliveUpdateIntimacyInput,\n AliveBuildContextInput,\n AliveContext,\n AliveClassifyIntentInput,\n AliveClassifiedIntent,\n AliveSendMessageInput,\n AliveChatResponse,\n} from \"../types-alive\";\n\n// Re-export all Alive types\nexport type * from \"../types-alive\";\n\n// ─── Namespace interface ────────────────────────────────────\n\nexport interface AliveNamespace {\n // Memory\n /** Store a new memory for a character-user pair. */\n storeMemory(input: AliveStoreMemoryInput): Promise<AliveMemory>;\n /** Recall relevant memories using semantic search. */\n recallMemories(input: AliveRecallMemoriesInput): Promise<AliveMemory[]>;\n /** Delete a specific memory. */\n forgetMemory(input: AliveForgetMemoryInput): Promise<any>;\n\n // Intimacy\n /** Get the intimacy/affection state between a character and user. */\n getIntimacy(input: AliveGetIntimacyInput): Promise<AliveIntimacy>;\n /** Update intimacy level (e.g., after a positive/negative interaction). */\n updateIntimacy(input: AliveUpdateIntimacyInput): Promise<AliveIntimacy>;\n\n // Context\n /** Build a full context object for AI generation (profile + memories + history + system prompt). */\n buildContext(input: AliveBuildContextInput): Promise<AliveContext>;\n\n // Intent\n /** Classify a user's message into an intent category. */\n classifyIntent(input: AliveClassifyIntentInput): Promise<AliveClassifiedIntent>;\n\n // Chat\n /** Send a message and get a character response (includes memory, intimacy, and intent processing). */\n sendMessage(input: AliveSendMessageInput): Promise<AliveChatResponse>;\n\n /** Call a raw MCP tool by name. Escape hatch for tools not yet in the typed API. */\n rawTool<T = any>(toolName: string, args?: Record<string, any>): Promise<T>;\n}\n\n// ─── Factory ────────────────────────────────────────────────\n\nexport function createAliveNamespace(transport: TransportConfig): AliveNamespace {\n const tool = <I extends Record<string, any>, O>(name: string) =>\n (input?: I) => callMcpTool<I, O>(transport, name, input as I);\n\n return {\n // Memory\n storeMemory: tool<AliveStoreMemoryInput, AliveMemory>(\"store_memory\"),\n recallMemories: tool<AliveRecallMemoriesInput, AliveMemory[]>(\"recall_memories\"),\n forgetMemory: tool<AliveForgetMemoryInput, any>(\"forget_memory\"),\n\n // Intimacy\n getIntimacy: tool<AliveGetIntimacyInput, AliveIntimacy>(\"get_intimacy\"),\n updateIntimacy: tool<AliveUpdateIntimacyInput, AliveIntimacy>(\"update_intimacy\"),\n\n // Context\n buildContext: tool<AliveBuildContextInput, AliveContext>(\"build_context\"),\n\n // Intent\n classifyIntent: tool<AliveClassifyIntentInput, AliveClassifiedIntent>(\"classify_intent\"),\n\n // Chat\n sendMessage: tool<AliveSendMessageInput, AliveChatResponse>(\"send_message\"),\n\n // Raw escape hatch\n rawTool: <T = any>(toolName: string, args?: Record<string, any>) =>\n callMcpTool<Record<string, any>, T>(transport, toolName, args),\n };\n}\n"]}
@@ -29,6 +29,33 @@ var GoodZApiError = class extends Error {
29
29
  }
30
30
  return parts.join("\n");
31
31
  }
32
+ /**
33
+ * Check if this error is an insufficient Z-coin balance error.
34
+ * When true, `depositUrl` provides the URL to redirect users for top-up.
35
+ *
36
+ * @example
37
+ * ```ts
38
+ * try {
39
+ * await goodz.zcoin.commercialTransfer({ ... });
40
+ * } catch (e) {
41
+ * if (e instanceof GoodZApiError && e.isInsufficientBalance()) {
42
+ * window.open(e.depositUrl!, '_blank');
43
+ * }
44
+ * }
45
+ * ```
46
+ */
47
+ isInsufficientBalance() {
48
+ return this.code === "INSUFFICIENT_BALANCE" || this.message?.toLowerCase().includes("insufficient") && this.message?.toLowerCase().includes("balance");
49
+ }
50
+ /**
51
+ * Deposit URL for Z-coin top-up (available when isInsufficientBalance() is true).
52
+ * Returned by Core when a payment fails due to insufficient balance.
53
+ * Append `&amount={needed}&return_url={your_page}` for seamless round-trip.
54
+ */
55
+ get depositUrl() {
56
+ const d = this.data;
57
+ return d?.deposit_url ?? d?.deposit_url_with_return ?? void 0;
58
+ }
32
59
  };
33
60
  async function callQuery(config, path, input) {
34
61
  const url = `${config.baseUrl}/api/trpc/${path}`;
@@ -223,5 +250,5 @@ function createMcpTransportConfig(baseUrl, getHeaders) {
223
250
  }
224
251
 
225
252
  export { GoodZApiError, callMcpTool, callMutation, callQuery, createMcpTransportConfig };
226
- //# sourceMappingURL=chunk-4SU7SU7K.js.map
227
- //# sourceMappingURL=chunk-4SU7SU7K.js.map
253
+ //# sourceMappingURL=chunk-ORUFMYZB.js.map
254
+ //# sourceMappingURL=chunk-ORUFMYZB.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/transport.ts","../src/mcp-transport.ts"],"names":[],"mappings":";;;AAmBO,IAAM,aAAA,GAAN,cAA4B,KAAA,CAAM;AAAA,EACvB,IAAA;AAAA,EACA,UAAA;AAAA,EACA,IAAA;AAAA,EACA,SAAA;AAAA,EACA,IAAA;AAAA,EAEhB,YAAY,IAAA,EAOT;AACD,IAAA,KAAA,CAAM,KAAK,OAAO,CAAA;AAClB,IAAA,IAAA,CAAK,IAAA,GAAO,eAAA;AACZ,IAAA,IAAA,CAAK,OAAO,IAAA,CAAK,IAAA;AACjB,IAAA,IAAA,CAAK,aAAa,IAAA,CAAK,UAAA;AACvB,IAAA,IAAA,CAAK,OAAO,IAAA,CAAK,IAAA;AACjB,IAAA,IAAA,CAAK,YAAY,IAAA,CAAK,SAAA;AACtB,IAAA,IAAA,CAAK,OAAO,IAAA,CAAK,IAAA;AAAA,EACnB;AAAA;AAAA,EAGA,gBAAA,GAA2B;AACzB,IAAA,MAAM,KAAA,GAAQ;AAAA,MACZ,CAAA,gBAAA,EAAmB,KAAK,IAAI,CAAA,IAAA,EAAO,KAAK,IAAI,CAAA,EAAA,EAAK,KAAK,OAAO,CAAA;AAAA,KAC/D;AACA,IAAA,IAAI,IAAA,CAAK,WAAW,MAAA,EAAQ;AAC1B,MAAA,KAAA,CAAM,KAAK,eAAe,CAAA;AAC1B,MAAA,KAAA,MAA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A,CAAK,CAAC,CAAA,KAAW,CAAA,CAAE,SAAS,MAAM,CAAA;AAC5D,IAAA,IAAI,WAAW,IAAA,EAAM;AAEnB,MAAA,IAAI,OAAO,OAAA,EAAS;AAClB,QAAA,MAAM,IAAI,aAAA,CAAc;AAAA,UACtB,SAAS,SAAA,CAAU,IAAA;AAAA,UACnB,IAAA,EAAM,gBAAA;AAAA,UACN,UAAA;AAAA,UACA,IAAA,EAAM;AAAA,SACP,CAAA;AAAA,MACH;AAGA,MAAA,IAAI;AACF,QAAA,OAAO,IAAA,CAAK,KAAA,CAAM,SAAA,CAAU,IAAI,CAAA;AAAA,MAClC,CAAA,CAAA,MAAQ;AAEN,QAAA,OAAO,SAAA,CAAU,IAAA;AAAA,MACnB;AAAA,IACF;AAAA,EACF;AAGA,EAAA,OAAO,MAAA;AACT;AAOO,SAAS,wBAAA,CACd,SACA,UAAA,EACiB;AACjB,EAAA,OAAO;AAAA,IACL,OAAA,EAAS,OAAA,CAAQ,OAAA,CAAQ,KAAA,EAAO,EAAE,CAAA;AAAA,IAClC;AAAA,GACF;AACF","file":"chunk-ORUFMYZB.js","sourcesContent":["/**\n * @goodz-core/sdk — HTTP Transport Layer\n *\n * Speaks the tRPC v11 HTTP wire protocol directly using fetch.\n * Handles superjson serialization, batching, and error parsing.\n *\n * Wire format reference:\n * - Queries: GET /api/trpc/{procedure}?input={superjson-encoded}\n * - Mutations: POST /api/trpc/{procedure} body: {superjson-encoded}\n * - Batch: GET /api/trpc/{p1},{p2}?input={0: ..., 1: ...}\n *\n * @internal\n */\n\nimport superjson from \"superjson\";\nimport type { GoodZApiFieldError } from \"./types\";\n\n// ─── Error class ─────────────────────────────────────────────\n\nexport class GoodZApiError extends Error {\n public readonly code: string;\n public readonly httpStatus: number;\n public readonly path: string;\n public readonly zodErrors?: GoodZApiFieldError[];\n public readonly data?: unknown;\n\n constructor(opts: {\n message: string;\n code: string;\n httpStatus: number;\n path: string;\n zodErrors?: GoodZApiFieldError[];\n data?: unknown;\n }) {\n super(opts.message);\n this.name = \"GoodZApiError\";\n this.code = opts.code;\n this.httpStatus = opts.httpStatus;\n this.path = opts.path;\n this.zodErrors = opts.zodErrors;\n this.data = opts.data;\n }\n\n /** Human-readable summary including field errors if present. */\n toDetailedString(): string {\n const parts = [\n `[GoodZApiError] ${this.code} on ${this.path}: ${this.message}`,\n ];\n if (this.zodErrors?.length) {\n parts.push(\"Field errors:\");\n for (const e of this.zodErrors) {\n parts.push(` - ${e.path.join(\".\")}: ${e.message} (${e.code})`);\n }\n }\n return parts.join(\"\\n\");\n }\n\n /**\n * Check if this error is an insufficient Z-coin balance error.\n * When true, `depositUrl` provides the URL to redirect users for top-up.\n *\n * @example\n * ```ts\n * try {\n * await goodz.zcoin.commercialTransfer({ ... });\n * } catch (e) {\n * if (e instanceof GoodZApiError && e.isInsufficientBalance()) {\n * window.open(e.depositUrl!, '_blank');\n * }\n * }\n * ```\n */\n isInsufficientBalance(): boolean {\n return this.code === \"INSUFFICIENT_BALANCE\" ||\n (this.message?.toLowerCase().includes(\"insufficient\") &&\n this.message?.toLowerCase().includes(\"balance\"));\n }\n\n /**\n * Deposit URL for Z-coin top-up (available when isInsufficientBalance() is true).\n * Returned by Core when a payment fails due to insufficient balance.\n * Append `&amount={needed}&return_url={your_page}` for seamless round-trip.\n */\n get depositUrl(): string | undefined {\n const d = this.data as Record<string, unknown> | undefined;\n return (d?.deposit_url as string) ?? (d?.deposit_url_with_return as string) ?? undefined;\n }\n}\n\n// ─── Transport config ────────────────────────────────────────\n\nexport interface TransportConfig {\n baseUrl: string;\n getHeaders: () => Record<string, string> | Promise<Record<string, string>>;\n}\n\n// ─── Core transport functions ────────────────────────────────\n\n/**\n * Call a tRPC query (GET request).\n * Uses POST with method override for compatibility with Commerce/Exchange\n * server-to-server patterns (some proxies strip GET bodies).\n */\nexport async function callQuery<TInput, TOutput>(\n config: TransportConfig,\n path: string,\n input?: TInput,\n): Promise<TOutput> {\n const url = `${config.baseUrl}/api/trpc/${path}`;\n const headers = await config.getHeaders();\n\n // Use GET with query params for queries (standard tRPC)\n const serialized = input !== undefined ? superjson.serialize(input) : undefined;\n const queryUrl = serialized\n ? `${url}?input=${encodeURIComponent(JSON.stringify(serialized))}`\n : url;\n\n const res = await fetch(queryUrl, {\n method: \"GET\",\n headers: {\n ...headers,\n \"Content-Type\": \"application/json\",\n },\n });\n\n return parseResponse<TOutput>(res, path);\n}\n\n/**\n * Call a tRPC mutation (POST request).\n */\nexport async function callMutation<TInput, TOutput>(\n config: TransportConfig,\n path: string,\n input?: TInput,\n): Promise<TOutput> {\n const url = `${config.baseUrl}/api/trpc/${path}`;\n const headers = await config.getHeaders();\n\n const serialized = input !== undefined ? superjson.serialize(input) : undefined;\n\n const res = await fetch(url, {\n method: \"POST\",\n headers: {\n ...headers,\n \"Content-Type\": \"application/json\",\n },\n body: serialized ? JSON.stringify(serialized) : undefined,\n });\n\n return parseResponse<TOutput>(res, path);\n}\n\n// ─── Response parser ─────────────────────────────────────────\n\nasync function parseResponse<T>(res: Response, path: string): Promise<T> {\n const text = await res.text();\n let body: any;\n\n try {\n body = JSON.parse(text);\n } catch {\n throw new GoodZApiError({\n message: `Invalid JSON response: ${text.slice(0, 200)}`,\n code: \"PARSE_ERROR\",\n httpStatus: res.status,\n path,\n });\n }\n\n // tRPC wraps responses in { result: { data: ... } }\n // Batch responses are arrays: [{ result: { data: ... } }]\n const envelope = Array.isArray(body) ? body[0] : body;\n\n // Check for tRPC error envelope\n if (envelope?.error) {\n const err = envelope.error;\n const errJson = err?.json ?? err;\n const errData = errJson?.data ?? {};\n\n throw new GoodZApiError({\n message: errJson?.message ?? \"Unknown API error\",\n code: errData?.code ?? errJson?.code ?? \"UNKNOWN\",\n httpStatus: errData?.httpStatus ?? res.status,\n path: errData?.path ?? path,\n zodErrors: errData?.zodError?.issues,\n data: errData,\n });\n }\n\n // Success path: extract and deserialize the data\n const resultData = envelope?.result?.data;\n if (resultData === undefined) {\n // Some queries return null/undefined legitimately\n if (res.ok) return undefined as T;\n\n throw new GoodZApiError({\n message: `Unexpected response shape from ${path}`,\n code: \"UNEXPECTED_RESPONSE\",\n httpStatus: res.status,\n path,\n });\n }\n\n // superjson wraps data in { json: ..., meta?: ... }\n // Check if it's a superjson envelope\n if (resultData && typeof resultData === \"object\" && \"json\" in resultData) {\n return superjson.deserialize(resultData) as T;\n }\n\n // Plain JSON (shouldn't happen with superjson transformer, but be safe)\n return resultData as T;\n}\n","/**\n * @goodz-core/sdk — MCP Transport Layer\n *\n * Speaks the MCP (Model Context Protocol) JSON-RPC 2.0 wire format\n * used by Commerce, Exchange, and Alive sub-sites.\n *\n * Wire format:\n * POST /api/mcp\n * Content-Type: application/json\n * Authorization: Bearer <token>\n *\n * { \"jsonrpc\": \"2.0\", \"method\": \"tools/call\", \"params\": { \"name\": \"<tool>\", \"arguments\": { ... } }, \"id\": 1 }\n *\n * Response:\n * { \"jsonrpc\": \"2.0\", \"result\": { \"content\": [{ \"type\": \"text\", \"text\": \"<json>\" }] }, \"id\": 1 }\n *\n * @internal\n */\n\nimport { GoodZApiError } from \"./transport\";\nimport type { TransportConfig } from \"./transport\";\n\n// Re-export for convenience\nexport type { TransportConfig };\n\n// ─── MCP request counter ────────────────────────────────────\n\nlet _mcpRequestId = 0;\nfunction nextId(): number {\n return ++_mcpRequestId;\n}\n\n// ─── Session management ─────────────────────────────────────\n\nconst _sessionIds = new Map<string, string>();\n\n// ─── Core MCP call function ─────────────────────────────────\n\n/**\n * Call an MCP tool on a sub-site.\n *\n * Handles:\n * - JSON-RPC 2.0 envelope construction\n * - Session ID management (mcp-session-id header)\n * - Response parsing (extracts JSON from text content)\n * - Error mapping to GoodZApiError\n */\nexport async function callMcpTool<TInput extends Record<string, any>, TOutput>(\n config: TransportConfig,\n toolName: string,\n args?: TInput,\n): Promise<TOutput> {\n const url = `${config.baseUrl}/api/mcp`;\n const headers = await config.getHeaders();\n\n // Add session ID if we have one for this endpoint\n const sessionId = _sessionIds.get(config.baseUrl);\n if (sessionId) {\n headers[\"mcp-session-id\"] = sessionId;\n }\n\n const body = {\n jsonrpc: \"2.0\" as const,\n method: \"tools/call\",\n params: {\n name: toolName,\n arguments: args ?? {},\n },\n id: nextId(),\n };\n\n const res = await fetch(url, {\n method: \"POST\",\n headers: {\n ...headers,\n \"Content-Type\": \"application/json\",\n Accept: \"application/json, text/event-stream\",\n },\n body: JSON.stringify(body),\n });\n\n // Store session ID from response\n const newSessionId = res.headers.get(\"mcp-session-id\");\n if (newSessionId) {\n _sessionIds.set(config.baseUrl, newSessionId);\n }\n\n // Handle SSE responses (some MCP servers use streaming)\n const contentType = res.headers.get(\"content-type\") || \"\";\n if (contentType.includes(\"text/event-stream\")) {\n return parseSseResponse<TOutput>(res, toolName);\n }\n\n // Standard JSON response\n const text = await res.text();\n return parseJsonRpcResponse<TOutput>(text, res.status, toolName);\n}\n\n// ─── Response parsers ───────────────────────────────────────\n\nfunction parseJsonRpcResponse<T>(\n text: string,\n httpStatus: number,\n toolName: string,\n): T {\n let body: any;\n try {\n body = JSON.parse(text);\n } catch {\n throw new GoodZApiError({\n message: `Invalid JSON response from MCP tool ${toolName}: ${text.slice(0, 200)}`,\n code: \"PARSE_ERROR\",\n httpStatus,\n path: toolName,\n });\n }\n\n // JSON-RPC error\n if (body.error) {\n throw new GoodZApiError({\n message: body.error.message || \"MCP tool error\",\n code: body.error.code?.toString() || \"MCP_ERROR\",\n httpStatus,\n path: toolName,\n data: body.error.data,\n });\n }\n\n // Extract result from MCP content array\n return extractMcpResult<T>(body.result, toolName, httpStatus);\n}\n\nasync function parseSseResponse<T>(\n res: Response,\n toolName: string,\n): Promise<T> {\n const text = await res.text();\n const lines = text.split(\"\\n\");\n\n // Find the last \"data:\" line that contains a JSON-RPC response\n let lastData: string | null = null;\n for (const line of lines) {\n if (line.startsWith(\"data:\")) {\n lastData = line.slice(5).trim();\n }\n }\n\n if (!lastData) {\n throw new GoodZApiError({\n message: `Empty SSE response from MCP tool ${toolName}`,\n code: \"EMPTY_RESPONSE\",\n httpStatus: res.status,\n path: toolName,\n });\n }\n\n return parseJsonRpcResponse<T>(lastData, res.status, toolName);\n}\n\nfunction extractMcpResult<T>(\n result: any,\n toolName: string,\n httpStatus: number,\n): T {\n if (!result) {\n throw new GoodZApiError({\n message: `No result from MCP tool ${toolName}`,\n code: \"EMPTY_RESULT\",\n httpStatus,\n path: toolName,\n });\n }\n\n // MCP tools return { content: [{ type: \"text\", text: \"...\" }] }\n const content = result.content;\n if (Array.isArray(content)) {\n // Find the first text content block\n const textBlock = content.find((c: any) => c.type === \"text\");\n if (textBlock?.text) {\n // Check if the tool returned an error in the text\n if (result.isError) {\n throw new GoodZApiError({\n message: textBlock.text,\n code: \"MCP_TOOL_ERROR\",\n httpStatus,\n path: toolName,\n });\n }\n\n // Try to parse as JSON\n try {\n return JSON.parse(textBlock.text) as T;\n } catch {\n // If not JSON, return the text as-is (some tools return plain text)\n return textBlock.text as T;\n }\n }\n }\n\n // Fallback: return the result directly\n return result as T;\n}\n\n// ─── MCP transport config builder ───────────────────────────\n\n/**\n * Create a TransportConfig for an MCP sub-site endpoint.\n */\nexport function createMcpTransportConfig(\n baseUrl: string,\n getHeaders: () => Record<string, string> | Promise<Record<string, string>>,\n): TransportConfig {\n return {\n baseUrl: baseUrl.replace(/\\/$/, \"\"),\n getHeaders,\n };\n}\n"]}
@@ -1,4 +1,4 @@
1
- import { callMcpTool } from './chunk-4SU7SU7K.js';
1
+ import { callMcpTool } from './chunk-ORUFMYZB.js';
2
2
 
3
3
  // src/commerce/index.ts
4
4
  function createCommerceNamespace(transport) {
@@ -52,5 +52,5 @@ function createCommerceNamespace(transport) {
52
52
  }
53
53
 
54
54
  export { createCommerceNamespace };
55
- //# sourceMappingURL=chunk-V73MMKHI.js.map
56
- //# sourceMappingURL=chunk-V73MMKHI.js.map
55
+ //# sourceMappingURL=chunk-SWD7BJQ7.js.map
56
+ //# sourceMappingURL=chunk-SWD7BJQ7.js.map
@@ -1 +1 @@
1
- {"version":3,"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CAAA;AAAA,IACnF,mBAAA,EAAqB,KAA8C,wBAAwB,CAAA;AAAA;AAAA,IAG3F,cAAA,EAAgB,KAAuC,uBAAuB,CAAA;AAAA;AAAA,IAG9E,eAAA,EAAiB,KAAoD,kBAAkB,CAAA;AAAA,IACvF,YAAA,EAAc,KAA+C,eAAe,CAAA;AAAA,IAC5E,WAAA,EAAa,KAAoC,cAAc,CAAA;AAAA,IAC/D,aAAA,EAAe,KAAsC,gBAAgB,CAAA;AAAA;AAAA,IAGrE,WAAA,EAAa,KAAoC,cAAc,CAAA;AAAA,IAC/D,SAAA,EAAW,KAAkC,YAAY,CAAA;AAAA,IACzD,UAAA,EAAY,KAAqC,cAAc,CAAA;AAAA,IAC/D,UAAA,EAAY,KAA+C,cAAc,CAAA;AAAA;AAAA,IAGzE,SAAS,CAAU,QAAA,EAAkB,SACnC,WAAA,CAAoC,SAAA,EAAW,UAAU,IAAI;AAAA,GACjE;AACF","file":"chunk-V73MMKHI.js","sourcesContent":["/**\n * @goodz-core/sdk — Commerce / Shops Namespace\n *\n * Provides typed access to GoodZ.Commerce MCP tools:\n * shop management, batches, gacha pools, campaigns,\n * wholesale, purchases, settlement, and webhooks.\n *\n * @module\n */\n\nimport { callMcpTool } from \"../mcp-transport\";\nimport type { TransportConfig } from \"../mcp-transport\";\nimport type {\n CommerceCreateShopInput,\n CommerceShop,\n CommerceGetShopDashboardInput,\n CommerceShopDashboard,\n CommerceCreateBatchInput,\n CommerceBatch,\n CommerceCreateGachaPoolInput,\n CommerceGachaPool,\n CommerceLaunchCampaignInput,\n CommerceCampaign,\n CommerceActivateCampaignInput,\n CommercePauseCampaignInput,\n CommerceEndCampaignInput,\n CommerceUpdateCampaignInput,\n CommerceGetCampaignInfoInput,\n CommerceGetCampaignItemsInput,\n CommerceCampaignItem,\n CommerceExecutePurchaseInput,\n CommerceDrawResult,\n CommerceGetMyOrdersInput,\n CommerceOrder,\n CommercePublishToWholesaleInput,\n CommerceBrowseWholesaleInput,\n CommerceWholesaleListing,\n CommerceProcureBatchInput,\n CommerceManageInventoryInput,\n CommerceRegisterInstancesInput,\n CommerceMintToInventoryInput,\n CommerceGetSettlementReportInput,\n CommerceSearchMarketplaceInput,\n CommerceGetShopsByBlueprintInput,\n CommerceRedeemPhysicalInput,\n CommerceRegisterWebhookInput,\n CommerceWebhook,\n CommerceTestWebhookInput,\n CommerceDeleteWebhookInput,\n CommerceRegisterAppInput,\n CommerceUpdateAppInput,\n CommerceListMyAppsInput,\n CommerceGetAuthUrlInput,\n} from \"../types-commerce\";\n\n// Re-export all Commerce types\nexport type * from \"../types-commerce\";\n\n// ─── Namespace interface ────────────────────────────────────\n\nexport interface CommerceNamespace {\n // Shop Management\n /** Create a new shop. */\n createShop(input: CommerceCreateShopInput): Promise<CommerceShop>;\n /** Get shop dashboard with stats, revenue, and recent orders. */\n getShopDashboard(input?: CommerceGetShopDashboardInput): Promise<CommerceShopDashboard>;\n\n // Product Assembly\n /** Create a batch (product assembly with tiers). Supports blind_box, ichiban_kuji, direct_sale. */\n createBatch(input: CommerceCreateBatchInput): Promise<CommerceBatch>;\n /** Create a gacha pool with weighted probabilities and optional pity mechanics. */\n createGachaPool(input: CommerceCreateGachaPoolInput): Promise<CommerceGachaPool>;\n\n // Campaign Lifecycle\n /** Launch a sales campaign in draft status. Connect a Batch or Gacha pool to the storefront. */\n launchCampaign(input: CommerceLaunchCampaignInput): Promise<CommerceCampaign>;\n /** Activate a draft/paused campaign — makes it live and purchasable. */\n activateCampaign(input: CommerceActivateCampaignInput): Promise<CommerceCampaign>;\n /** Pause an active campaign. Existing orders unaffected. */\n pauseCampaign(input: CommercePauseCampaignInput): Promise<CommerceCampaign>;\n /** Permanently end a campaign (terminal state). */\n endCampaign(input: CommerceEndCampaignInput): Promise<CommerceCampaign>;\n /** Update campaign configuration (editable fields depend on status). */\n updateCampaign(input: CommerceUpdateCampaignInput): Promise<CommerceCampaign>;\n /** Get detailed campaign info including batch/gacha config and tiers. */\n getCampaignInfo(input: CommerceGetCampaignInfoInput): Promise<any>;\n /** Get unified campaign items list (works for both batch and gacha campaigns). */\n getCampaignItems(input: CommerceGetCampaignItemsInput): Promise<CommerceCampaignItem[]>;\n\n // Purchase / Draw\n /** Execute a purchase or draw. Handles payment, draw mechanics, settlement, and ownership transfer. */\n executePurchase(input: CommerceExecutePurchaseInput): Promise<CommerceDrawResult>;\n /** Get the authenticated user's order history. */\n getMyOrders(input?: CommerceGetMyOrdersInput): Promise<CommerceOrder[]>;\n\n // Wholesale\n /** Publish a batch to the wholesale market for other shopkeepers to procure. */\n publishToWholesale(input: CommercePublishToWholesaleInput): Promise<any>;\n /** Browse available wholesale listings. */\n browseWholesale(input?: CommerceBrowseWholesaleInput): Promise<CommerceWholesaleListing[]>;\n /** Procure goods from the wholesale market. */\n procureBatch(input: CommerceProcureBatchInput): Promise<any>;\n\n // Inventory\n /** View and manage shop inventory (list or sync from Core). */\n manageInventory(input?: CommerceManageInventoryInput): Promise<any>;\n /** Register existing Core instances into shop inventory. */\n registerInstances(input: CommerceRegisterInstancesInput): Promise<any>;\n /** Mint new instances directly into shop inventory. */\n mintToInventory(input: CommerceMintToInventoryInput): Promise<any>;\n\n // Settlement\n /** Get settlement report with revenue breakdown. */\n getSettlementReport(input?: CommerceGetSettlementReportInput): Promise<any>;\n\n // Discovery\n /** Search the marketplace for campaigns. */\n searchMarketplace(input?: CommerceSearchMarketplaceInput): Promise<any[]>;\n /** Find shops selling a specific GoodZ card. */\n getShopsByBlueprint(input: CommerceGetShopsByBlueprintInput): Promise<any[]>;\n\n // Physical Redemption\n /** Request physical redemption for a purchased item. */\n redeemPhysical(input: CommerceRedeemPhysicalInput): Promise<any>;\n\n // Webhooks\n /** Register a webhook URL to receive shop event notifications. */\n registerWebhook(input: CommerceRegisterWebhookInput): Promise<CommerceWebhook>;\n /** List all registered webhook endpoints. */\n listWebhooks(): Promise<CommerceWebhook[]>;\n /** Send a test ping to a webhook endpoint. */\n testWebhook(input: CommerceTestWebhookInput): Promise<any>;\n /** Delete a webhook endpoint. */\n deleteWebhook(input: CommerceDeleteWebhookInput): Promise<any>;\n\n // OAuth App Management\n /** Register a new OAuth application with Commerce scopes. */\n registerApp(input: CommerceRegisterAppInput): Promise<any>;\n /** Update an existing OAuth application. */\n updateApp(input: CommerceUpdateAppInput): Promise<any>;\n /** List all OAuth applications owned by the user. */\n listMyApps(input?: CommerceListMyAppsInput): Promise<any[]>;\n /** Generate an OAuth authorization URL. */\n getAuthUrl(input?: CommerceGetAuthUrlInput): Promise<{ url: string }>;\n\n /** Call a raw MCP tool by name. Escape hatch for tools not yet in the typed API. */\n rawTool<T = any>(toolName: string, args?: Record<string, any>): Promise<T>;\n}\n\n// ─── Factory ────────────────────────────────────────────────\n\nexport function createCommerceNamespace(transport: TransportConfig): CommerceNamespace {\n const tool = <I extends Record<string, any>, O>(name: string) =>\n (input?: I) => callMcpTool<I, O>(transport, name, input as I);\n\n return {\n // Shop\n createShop: tool<CommerceCreateShopInput, CommerceShop>(\"create_shop\"),\n getShopDashboard: tool<CommerceGetShopDashboardInput, CommerceShopDashboard>(\"get_shop_dashboard\"),\n\n // Product Assembly\n createBatch: tool<CommerceCreateBatchInput, CommerceBatch>(\"assemble_batch\"),\n createGachaPool: tool<CommerceCreateGachaPoolInput, CommerceGachaPool>(\"create_gacha_pool\"),\n\n // Campaign Lifecycle\n launchCampaign: tool<CommerceLaunchCampaignInput, CommerceCampaign>(\"launch_sales_campaign\"),\n activateCampaign: tool<CommerceActivateCampaignInput, CommerceCampaign>(\"activate_campaign\"),\n pauseCampaign: tool<CommercePauseCampaignInput, CommerceCampaign>(\"pause_campaign\"),\n endCampaign: tool<CommerceEndCampaignInput, CommerceCampaign>(\"end_campaign\"),\n updateCampaign: tool<CommerceUpdateCampaignInput, CommerceCampaign>(\"update_campaign\"),\n getCampaignInfo: tool<CommerceGetCampaignInfoInput, any>(\"get_campaign_info\"),\n getCampaignItems: tool<CommerceGetCampaignItemsInput, CommerceCampaignItem[]>(\"get_campaign_items\"),\n\n // Purchase\n executePurchase: tool<CommerceExecutePurchaseInput, CommerceDrawResult>(\"execute_purchase\"),\n getMyOrders: tool<CommerceGetMyOrdersInput, CommerceOrder[]>(\"get_my_orders\"),\n\n // Wholesale\n publishToWholesale: tool<CommercePublishToWholesaleInput, any>(\"publish_to_wholesale\"),\n browseWholesale: tool<CommerceBrowseWholesaleInput, CommerceWholesaleListing[]>(\"browse_wholesale_market\"),\n procureBatch: tool<CommerceProcureBatchInput, any>(\"procure_batch\"),\n\n // Inventory\n manageInventory: tool<CommerceManageInventoryInput, any>(\"manage_inventory\"),\n registerInstances: tool<CommerceRegisterInstancesInput, any>(\"register_instances\"),\n mintToInventory: tool<CommerceMintToInventoryInput, any>(\"mint_to_inventory\"),\n\n // Settlement\n getSettlementReport: tool<CommerceGetSettlementReportInput, any>(\"get_settlement_report\"),\n\n // Discovery\n searchMarketplace: tool<CommerceSearchMarketplaceInput, any[]>(\"search_marketplace\"),\n getShopsByBlueprint: tool<CommerceGetShopsByBlueprintInput, any[]>(\"get_shops_by_blueprint\"),\n\n // Physical Redemption\n redeemPhysical: tool<CommerceRedeemPhysicalInput, any>(\"redeem_physical_goodz\"),\n\n // Webhooks\n registerWebhook: tool<CommerceRegisterWebhookInput, CommerceWebhook>(\"register_webhook\"),\n listWebhooks: tool<Record<string, never>, CommerceWebhook[]>(\"list_webhooks\"),\n testWebhook: tool<CommerceTestWebhookInput, any>(\"test_webhook\"),\n deleteWebhook: tool<CommerceDeleteWebhookInput, any>(\"delete_webhook\"),\n\n // OAuth App\n registerApp: tool<CommerceRegisterAppInput, any>(\"register_app\"),\n updateApp: tool<CommerceUpdateAppInput, any>(\"update_app\"),\n listMyApps: tool<CommerceListMyAppsInput, any[]>(\"list_my_apps\"),\n getAuthUrl: tool<CommerceGetAuthUrlInput, { url: string }>(\"get_auth_url\"),\n\n // Raw escape hatch\n rawTool: <T = any>(toolName: string, args?: Record<string, any>) =>\n callMcpTool<Record<string, any>, T>(transport, toolName, args),\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AA,EAAmB,KAA4C,oBAAoB,CAAA;AAAA,IACnF,mBAAA,EAAqB,KAA8C,wBAAwB,CAAA;AAAA;AAAA,IAG3F,cAAA,EAAgB,KAAuC,uBAAuB,CAAA;AAAA;AAAA,IAG9E,eAAA,EAAiB,KAAoD,kBAAkB,CAAA;AAAA,IACvF,YAAA,EAAc,KAA+C,eAAe,CAAA;AAAA,IAC5E,WAAA,EAAa,KAAoC,cAAc,CAAA;AAAA,IAC/D,aAAA,EAAe,KAAsC,gBAAgB,CAAA;AAAA;AAAA,IAGrE,WAAA,EAAa,KAAoC,cAAc,CAAA;AAAA,IAC/D,SAAA,EAAW,KAAkC,YAAY,CAAA;AAAA,IACzD,UAAA,EAAY,KAAqC,cAAc,CAAA;AAAA,IAC/D,UAAA,EAAY,KAA+C,cAAc,CAAA;AAAA;AAAA,IAGzE,SAAS,CAAU,QAAA,EAAkB,SACnC,WAAA,CAAoC,SAAA,EAAW,UAAU,IAAI;AAAA,GACjE;AACF","file":"chunk-SWD7BJQ7.js","sourcesContent":["/**\n * @goodz-core/sdk — Commerce / Shops Namespace\n *\n * Provides typed access to GoodZ.Commerce MCP tools:\n * shop management, batches, gacha pools, campaigns,\n * wholesale, purchases, settlement, and webhooks.\n *\n * @module\n */\n\nimport { callMcpTool } from \"../mcp-transport\";\nimport type { TransportConfig } from \"../mcp-transport\";\nimport type {\n CommerceCreateShopInput,\n CommerceShop,\n CommerceGetShopDashboardInput,\n CommerceShopDashboard,\n CommerceCreateBatchInput,\n CommerceBatch,\n CommerceCreateGachaPoolInput,\n CommerceGachaPool,\n CommerceLaunchCampaignInput,\n CommerceCampaign,\n CommerceActivateCampaignInput,\n CommercePauseCampaignInput,\n CommerceEndCampaignInput,\n CommerceUpdateCampaignInput,\n CommerceGetCampaignInfoInput,\n CommerceGetCampaignItemsInput,\n CommerceCampaignItem,\n CommerceExecutePurchaseInput,\n CommerceDrawResult,\n CommerceGetMyOrdersInput,\n CommerceOrder,\n CommercePublishToWholesaleInput,\n CommerceBrowseWholesaleInput,\n CommerceWholesaleListing,\n CommerceProcureBatchInput,\n CommerceManageInventoryInput,\n CommerceRegisterInstancesInput,\n CommerceMintToInventoryInput,\n CommerceGetSettlementReportInput,\n CommerceSearchMarketplaceInput,\n CommerceGetShopsByBlueprintInput,\n CommerceRedeemPhysicalInput,\n CommerceRegisterWebhookInput,\n CommerceWebhook,\n CommerceTestWebhookInput,\n CommerceDeleteWebhookInput,\n CommerceRegisterAppInput,\n CommerceUpdateAppInput,\n CommerceListMyAppsInput,\n CommerceGetAuthUrlInput,\n} from \"../types-commerce\";\n\n// Re-export all Commerce types\nexport type * from \"../types-commerce\";\n\n// ─── Namespace interface ────────────────────────────────────\n\nexport interface CommerceNamespace {\n // Shop Management\n /** Create a new shop. */\n createShop(input: CommerceCreateShopInput): Promise<CommerceShop>;\n /** Get shop dashboard with stats, revenue, and recent orders. */\n getShopDashboard(input?: CommerceGetShopDashboardInput): Promise<CommerceShopDashboard>;\n\n // Product Assembly\n /** Create a batch (product assembly with tiers). Supports blind_box, ichiban_kuji, direct_sale. */\n createBatch(input: CommerceCreateBatchInput): Promise<CommerceBatch>;\n /** Create a gacha pool with weighted probabilities and optional pity mechanics. */\n createGachaPool(input: CommerceCreateGachaPoolInput): Promise<CommerceGachaPool>;\n\n // Campaign Lifecycle\n /** Launch a sales campaign in draft status. Connect a Batch or Gacha pool to the storefront. */\n launchCampaign(input: CommerceLaunchCampaignInput): Promise<CommerceCampaign>;\n /** Activate a draft/paused campaign — makes it live and purchasable. */\n activateCampaign(input: CommerceActivateCampaignInput): Promise<CommerceCampaign>;\n /** Pause an active campaign. Existing orders unaffected. */\n pauseCampaign(input: CommercePauseCampaignInput): Promise<CommerceCampaign>;\n /** Permanently end a campaign (terminal state). */\n endCampaign(input: CommerceEndCampaignInput): Promise<CommerceCampaign>;\n /** Update campaign configuration (editable fields depend on status). */\n updateCampaign(input: CommerceUpdateCampaignInput): Promise<CommerceCampaign>;\n /** Get detailed campaign info including batch/gacha config and tiers. */\n getCampaignInfo(input: CommerceGetCampaignInfoInput): Promise<any>;\n /** Get unified campaign items list (works for both batch and gacha campaigns). */\n getCampaignItems(input: CommerceGetCampaignItemsInput): Promise<CommerceCampaignItem[]>;\n\n // Purchase / Draw\n /** Execute a purchase or draw. Handles payment, draw mechanics, settlement, and ownership transfer. */\n executePurchase(input: CommerceExecutePurchaseInput): Promise<CommerceDrawResult>;\n /** Get the authenticated user's order history. */\n getMyOrders(input?: CommerceGetMyOrdersInput): Promise<CommerceOrder[]>;\n\n // Wholesale\n /** Publish a batch to the wholesale market for other shopkeepers to procure. */\n publishToWholesale(input: CommercePublishToWholesaleInput): Promise<any>;\n /** Browse available wholesale listings. */\n browseWholesale(input?: CommerceBrowseWholesaleInput): Promise<CommerceWholesaleListing[]>;\n /** Procure goods from the wholesale market. */\n procureBatch(input: CommerceProcureBatchInput): Promise<any>;\n\n // Inventory\n /** View and manage shop inventory (list or sync from Core). */\n manageInventory(input?: CommerceManageInventoryInput): Promise<any>;\n /** Register existing Core instances into shop inventory. */\n registerInstances(input: CommerceRegisterInstancesInput): Promise<any>;\n /** Mint new instances directly into shop inventory. */\n mintToInventory(input: CommerceMintToInventoryInput): Promise<any>;\n\n // Settlement\n /** Get settlement report with revenue breakdown. */\n getSettlementReport(input?: CommerceGetSettlementReportInput): Promise<any>;\n\n // Discovery\n /** Search the marketplace for campaigns. */\n searchMarketplace(input?: CommerceSearchMarketplaceInput): Promise<any[]>;\n /** Find shops selling a specific GoodZ card. */\n getShopsByBlueprint(input: CommerceGetShopsByBlueprintInput): Promise<any[]>;\n\n // Physical Redemption\n /** Request physical redemption for a purchased item. */\n redeemPhysical(input: CommerceRedeemPhysicalInput): Promise<any>;\n\n // Webhooks\n /** Register a webhook URL to receive shop event notifications. */\n registerWebhook(input: CommerceRegisterWebhookInput): Promise<CommerceWebhook>;\n /** List all registered webhook endpoints. */\n listWebhooks(): Promise<CommerceWebhook[]>;\n /** Send a test ping to a webhook endpoint. */\n testWebhook(input: CommerceTestWebhookInput): Promise<any>;\n /** Delete a webhook endpoint. */\n deleteWebhook(input: CommerceDeleteWebhookInput): Promise<any>;\n\n // OAuth App Management\n /** Register a new OAuth application with Commerce scopes. */\n registerApp(input: CommerceRegisterAppInput): Promise<any>;\n /** Update an existing OAuth application. */\n updateApp(input: CommerceUpdateAppInput): Promise<any>;\n /** List all OAuth applications owned by the user. */\n listMyApps(input?: CommerceListMyAppsInput): Promise<any[]>;\n /** Generate an OAuth authorization URL. */\n getAuthUrl(input?: CommerceGetAuthUrlInput): Promise<{ url: string }>;\n\n /** Call a raw MCP tool by name. Escape hatch for tools not yet in the typed API. */\n rawTool<T = any>(toolName: string, args?: Record<string, any>): Promise<T>;\n}\n\n// ─── Factory ────────────────────────────────────────────────\n\nexport function createCommerceNamespace(transport: TransportConfig): CommerceNamespace {\n const tool = <I extends Record<string, any>, O>(name: string) =>\n (input?: I) => callMcpTool<I, O>(transport, name, input as I);\n\n return {\n // Shop\n createShop: tool<CommerceCreateShopInput, CommerceShop>(\"create_shop\"),\n getShopDashboard: tool<CommerceGetShopDashboardInput, CommerceShopDashboard>(\"get_shop_dashboard\"),\n\n // Product Assembly\n createBatch: tool<CommerceCreateBatchInput, CommerceBatch>(\"assemble_batch\"),\n createGachaPool: tool<CommerceCreateGachaPoolInput, CommerceGachaPool>(\"create_gacha_pool\"),\n\n // Campaign Lifecycle\n launchCampaign: tool<CommerceLaunchCampaignInput, CommerceCampaign>(\"launch_sales_campaign\"),\n activateCampaign: tool<CommerceActivateCampaignInput, CommerceCampaign>(\"activate_campaign\"),\n pauseCampaign: tool<CommercePauseCampaignInput, CommerceCampaign>(\"pause_campaign\"),\n endCampaign: tool<CommerceEndCampaignInput, CommerceCampaign>(\"end_campaign\"),\n updateCampaign: tool<CommerceUpdateCampaignInput, CommerceCampaign>(\"update_campaign\"),\n getCampaignInfo: tool<CommerceGetCampaignInfoInput, any>(\"get_campaign_info\"),\n getCampaignItems: tool<CommerceGetCampaignItemsInput, CommerceCampaignItem[]>(\"get_campaign_items\"),\n\n // Purchase\n executePurchase: tool<CommerceExecutePurchaseInput, CommerceDrawResult>(\"execute_purchase\"),\n getMyOrders: tool<CommerceGetMyOrdersInput, CommerceOrder[]>(\"get_my_orders\"),\n\n // Wholesale\n publishToWholesale: tool<CommercePublishToWholesaleInput, any>(\"publish_to_wholesale\"),\n browseWholesale: tool<CommerceBrowseWholesaleInput, CommerceWholesaleListing[]>(\"browse_wholesale_market\"),\n procureBatch: tool<CommerceProcureBatchInput, any>(\"procure_batch\"),\n\n // Inventory\n manageInventory: tool<CommerceManageInventoryInput, any>(\"manage_inventory\"),\n registerInstances: tool<CommerceRegisterInstancesInput, any>(\"register_instances\"),\n mintToInventory: tool<CommerceMintToInventoryInput, any>(\"mint_to_inventory\"),\n\n // Settlement\n getSettlementReport: tool<CommerceGetSettlementReportInput, any>(\"get_settlement_report\"),\n\n // Discovery\n searchMarketplace: tool<CommerceSearchMarketplaceInput, any[]>(\"search_marketplace\"),\n getShopsByBlueprint: tool<CommerceGetShopsByBlueprintInput, any[]>(\"get_shops_by_blueprint\"),\n\n // Physical Redemption\n redeemPhysical: tool<CommerceRedeemPhysicalInput, any>(\"redeem_physical_goodz\"),\n\n // Webhooks\n registerWebhook: tool<CommerceRegisterWebhookInput, CommerceWebhook>(\"register_webhook\"),\n listWebhooks: tool<Record<string, never>, CommerceWebhook[]>(\"list_webhooks\"),\n testWebhook: tool<CommerceTestWebhookInput, any>(\"test_webhook\"),\n deleteWebhook: tool<CommerceDeleteWebhookInput, any>(\"delete_webhook\"),\n\n // OAuth App\n registerApp: tool<CommerceRegisterAppInput, any>(\"register_app\"),\n updateApp: tool<CommerceUpdateAppInput, any>(\"update_app\"),\n listMyApps: tool<CommerceListMyAppsInput, any[]>(\"list_my_apps\"),\n getAuthUrl: tool<CommerceGetAuthUrlInput, { url: string }>(\"get_auth_url\"),\n\n // Raw escape hatch\n rawTool: <T = any>(toolName: string, args?: Record<string, any>) =>\n callMcpTool<Record<string, any>, T>(transport, toolName, args),\n };\n}\n"]}
@@ -1,4 +1,4 @@
1
- import { $ as TransportConfig } from '../transport-CzoXrUZs.js';
1
+ import { $ as TransportConfig } from '../transport-BSpGsxyt.js';
2
2
 
3
3
  /**
4
4
  * @goodz-core/sdk — Commerce / Shops API Type Definitions
@@ -1,4 +1,4 @@
1
- export { createCommerceNamespace } from '../chunk-V73MMKHI.js';
2
- import '../chunk-4SU7SU7K.js';
1
+ export { createCommerceNamespace } from '../chunk-SWD7BJQ7.js';
2
+ import '../chunk-ORUFMYZB.js';
3
3
  //# sourceMappingURL=index.js.map
4
4
  //# sourceMappingURL=index.js.map
@@ -4,8 +4,8 @@ import { ExchangeNamespace } from '../exchange/index.js';
4
4
  export { CompensationDirection, ExchangeAddToWatchlistInput, ExchangeBid, ExchangeBrowseMarketplaceInput, ExchangeBuyListingInput, ExchangeBuyListingOutput, ExchangeCancelListingInput, ExchangeCancelWtbInput, ExchangeCreateListingInput, ExchangeCreateListingOutput, ExchangeCreateWtbInput, ExchangeFulfillWtbInput, ExchangeFulfillWtbOutput, ExchangeGetBidsInput, ExchangeGetListingDetailInput, ExchangeGetMarketDataInput, ExchangeListing, ExchangeMarketData, ExchangePlaceBidInput, ExchangePlaceBidOutput, ExchangePricePoint, ExchangeProposeTradeInput, ExchangeRemoveFromWatchlistInput, ExchangeRespondToTradeInput, ExchangeRespondToTradeOutput, ExchangeTradeItem, ExchangeTradeProposal, ExchangeWatchlistItem, ExchangeWtb, ListingCondition, ListingType } from '../exchange/index.js';
5
5
  import { AliveNamespace } from '../alive/index.js';
6
6
  export { AliveBuildContextInput, AliveChatResponse, AliveClassifiedIntent, AliveClassifyIntentInput, AliveContext, AliveForgetMemoryInput, AliveGetIntimacyInput, AliveIntimacy, AliveMemory, AliveRecallMemoriesInput, AliveSendMessageInput, AliveStoreMemoryInput, AliveUpdateIntimacyInput, IntentCategory, MemoryType, MoodState } from '../alive/index.js';
7
- import { b as AuthUser, A as AuthGetOAuthAppInfoInput, a as AuthOAuthAppInfo, e as CollectibleGetInstanceByIdInput, f as CollectibleGetPublicInstanceInput, g as CollectibleGetPublicInstancesBatchInput, d as CollectibleGetCardProfileInput, h as CollectibleGetShellImageUrlInput, V as ZcoinGetMyBalanceOutput, W as ZcoinGetMyHistoryInput, M as ZcoinGetDepositPackagesInput, L as ZcoinDepositPackage, E as ZcoinCreateDepositOrderInput, H as ZcoinCreateDepositOrderOutput, N as ZcoinGetDepositStatusInput, O as ZcoinGetDepositStatusOutput, Q as ZcoinGetDepositUrlInput, R as ZcoinGetDepositUrlOutput, B as ZcoinCommercialTransferInput, D as ZcoinCommercialTransferOutput, X as ZcoinMintAndChargeInput, Y as ZcoinMintAndChargeOutput, Z as ZcoinChargeUserInput, z as ZcoinChargeUserOutput, J as ZcoinCreateDirectPurchaseOrderInput, K as ZcoinCreateDirectPurchaseOrderOutput, l as InventoryGetUserInventoryInput, n as InventoryItem, I as InventoryConfirmOwnershipInput, k as InventoryConfirmOwnershipOutput, o as InventoryMintInput, p as InventoryMintOutput, t as InventoryTransferInput, u as InventoryTransferOutput, q as InventoryTransferByCardInput, r as InventoryTransferByCardOutput, m as InventoryGrantMintAuthInput, s as InventoryTransferHistoryInput, x as UserGetPublicProfileInput, y as UserPublicProfile, U as UserGetPublicProfileByIdInput, F as FranchiseGetInput, v as SeriesGetInput, w as SeriesListByFranchiseInput, C as CardGetInput, c as CardListBySeriesInput } from '../transport-CzoXrUZs.js';
8
- export { G as GoodZApiError, i as GoodZApiFieldError, j as GoodZErrorV2, P as PurchaseChannel, S as SaleType, T as TransferReason, _ as ZcoinTxType } from '../transport-CzoXrUZs.js';
7
+ import { b as AuthUser, A as AuthGetOAuthAppInfoInput, a as AuthOAuthAppInfo, e as CollectibleGetInstanceByIdInput, f as CollectibleGetPublicInstanceInput, g as CollectibleGetPublicInstancesBatchInput, d as CollectibleGetCardProfileInput, h as CollectibleGetShellImageUrlInput, V as ZcoinGetMyBalanceOutput, W as ZcoinGetMyHistoryInput, M as ZcoinGetDepositPackagesInput, L as ZcoinDepositPackage, E as ZcoinCreateDepositOrderInput, H as ZcoinCreateDepositOrderOutput, N as ZcoinGetDepositStatusInput, O as ZcoinGetDepositStatusOutput, Q as ZcoinGetDepositUrlInput, R as ZcoinGetDepositUrlOutput, B as ZcoinCommercialTransferInput, D as ZcoinCommercialTransferOutput, X as ZcoinMintAndChargeInput, Y as ZcoinMintAndChargeOutput, Z as ZcoinChargeUserInput, z as ZcoinChargeUserOutput, J as ZcoinCreateDirectPurchaseOrderInput, K as ZcoinCreateDirectPurchaseOrderOutput, l as InventoryGetUserInventoryInput, n as InventoryItem, I as InventoryConfirmOwnershipInput, k as InventoryConfirmOwnershipOutput, o as InventoryMintInput, p as InventoryMintOutput, t as InventoryTransferInput, u as InventoryTransferOutput, q as InventoryTransferByCardInput, r as InventoryTransferByCardOutput, m as InventoryGrantMintAuthInput, s as InventoryTransferHistoryInput, x as UserGetPublicProfileInput, y as UserPublicProfile, U as UserGetPublicProfileByIdInput, F as FranchiseGetInput, v as SeriesGetInput, w as SeriesListByFranchiseInput, C as CardGetInput, c as CardListBySeriesInput } from '../transport-BSpGsxyt.js';
8
+ export { G as GoodZApiError, i as GoodZApiFieldError, j as GoodZErrorV2, P as PurchaseChannel, S as SaleType, T as TransferReason, _ as ZcoinTxType } from '../transport-BSpGsxyt.js';
9
9
 
10
10
  /**
11
11
  * @goodz-core/sdk/core — Unified GoodZ API Client
@@ -126,7 +126,8 @@ interface ZcoinNamespace {
126
126
  *
127
127
  * Idempotent via referenceId — duplicate calls return the same result.
128
128
  *
129
- * @throws {GoodZApiError} BAD_REQUESTinsufficient balance
129
+ * @throws {GoodZApiError} INSUFFICIENT_BALANCEuse `e.isInsufficientBalance()` to detect,
130
+ * `e.depositUrl` to get the top-up redirect URL
130
131
  * @throws {GoodZApiError} CONFLICT — version conflict (retry)
131
132
  * @throws {GoodZApiError} FORBIDDEN — seller doesn't own instance
132
133
  */
@@ -139,7 +140,8 @@ interface ZcoinNamespace {
139
140
  * Idempotent via referenceId.
140
141
  *
141
142
  * @throws {GoodZApiError} FORBIDDEN — no mint authorization
142
- * @throws {GoodZApiError} BAD_REQUESTinsufficient balance
143
+ * @throws {GoodZApiError} INSUFFICIENT_BALANCEuse `e.isInsufficientBalance()` to detect,
144
+ * `e.depositUrl` to get the top-up redirect URL
143
145
  */
144
146
  mintAndCharge(input: ZcoinMintAndChargeInput): Promise<ZcoinMintAndChargeOutput>;
145
147
  /**
@@ -148,7 +150,8 @@ interface ZcoinNamespace {
148
150
  *
149
151
  * Idempotent via appOrderId.
150
152
  *
151
- * @throws {GoodZApiError} BAD_REQUESTinsufficient balance
153
+ * @throws {GoodZApiError} INSUFFICIENT_BALANCEuse `e.isInsufficientBalance()` to detect,
154
+ * `e.depositUrl` to get the top-up redirect URL
152
155
  * @throws {GoodZApiError} CONFLICT — version conflict
153
156
  */
154
157
  chargeUser(input: ZcoinChargeUserInput): Promise<ZcoinChargeUserOutput>;
@@ -1,7 +1,7 @@
1
- export { createGoodZClient, createUserClient } from '../chunk-EQUAL5M6.js';
2
- import '../chunk-V73MMKHI.js';
3
- import '../chunk-OUKZ2PRD.js';
4
- import '../chunk-JAVMQXJM.js';
5
- export { GoodZApiError } from '../chunk-4SU7SU7K.js';
1
+ export { createGoodZClient, createUserClient } from '../chunk-DSWHCVKV.js';
2
+ import '../chunk-SWD7BJQ7.js';
3
+ import '../chunk-GH33FPMY.js';
4
+ import '../chunk-KP7DP5LP.js';
5
+ export { GoodZApiError } from '../chunk-ORUFMYZB.js';
6
6
  //# sourceMappingURL=index.js.map
7
7
  //# sourceMappingURL=index.js.map
@@ -1,4 +1,4 @@
1
- import { $ as TransportConfig } from '../transport-CzoXrUZs.js';
1
+ import { $ as TransportConfig } from '../transport-BSpGsxyt.js';
2
2
 
3
3
  /**
4
4
  * @goodz-core/sdk — Exchange API Type Definitions
@@ -1,4 +1,4 @@
1
- export { createExchangeNamespace } from '../chunk-OUKZ2PRD.js';
2
- import '../chunk-4SU7SU7K.js';
1
+ export { createExchangeNamespace } from '../chunk-GH33FPMY.js';
2
+ import '../chunk-ORUFMYZB.js';
3
3
  //# sourceMappingURL=index.js.map
4
4
  //# sourceMappingURL=index.js.map
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  export { AuthNamespace, CollectibleNamespace, GoodZClient, GoodZClientConfig, InventoryNamespace, IpNamespace, UserNamespace, ZcoinNamespace, createGoodZClient, createUserClient } from './core/index.js';
2
- export { A as AuthGetOAuthAppInfoInput, a as AuthOAuthAppInfo, b as AuthUser, C as CardGetInput, c as CardListBySeriesInput, d as CollectibleGetCardProfileInput, e as CollectibleGetInstanceByIdInput, f as CollectibleGetPublicInstanceInput, g as CollectibleGetPublicInstancesBatchInput, h as CollectibleGetShellImageUrlInput, F as FranchiseGetInput, G as GoodZApiError, i as GoodZApiFieldError, j as GoodZErrorV2, I as InventoryConfirmOwnershipInput, k as InventoryConfirmOwnershipOutput, l as InventoryGetUserInventoryInput, m as InventoryGrantMintAuthInput, n as InventoryItem, o as InventoryMintInput, p as InventoryMintOutput, q as InventoryTransferByCardInput, r as InventoryTransferByCardOutput, s as InventoryTransferHistoryInput, t as InventoryTransferInput, u as InventoryTransferOutput, P as PurchaseChannel, S as SaleType, v as SeriesGetInput, w as SeriesListByFranchiseInput, T as TransferReason, U as UserGetPublicProfileByIdInput, x as UserGetPublicProfileInput, y as UserPublicProfile, Z as ZcoinChargeUserInput, z as ZcoinChargeUserOutput, B as ZcoinCommercialTransferInput, D as ZcoinCommercialTransferOutput, E as ZcoinCreateDepositOrderInput, H as ZcoinCreateDepositOrderOutput, J as ZcoinCreateDirectPurchaseOrderInput, K as ZcoinCreateDirectPurchaseOrderOutput, L as ZcoinDepositPackage, M as ZcoinGetDepositPackagesInput, N as ZcoinGetDepositStatusInput, O as ZcoinGetDepositStatusOutput, Q as ZcoinGetDepositUrlInput, R as ZcoinGetDepositUrlOutput, V as ZcoinGetMyBalanceOutput, W as ZcoinGetMyHistoryInput, X as ZcoinMintAndChargeInput, Y as ZcoinMintAndChargeOutput, _ as ZcoinTxType } from './transport-CzoXrUZs.js';
2
+ export { A as AuthGetOAuthAppInfoInput, a as AuthOAuthAppInfo, b as AuthUser, C as CardGetInput, c as CardListBySeriesInput, d as CollectibleGetCardProfileInput, e as CollectibleGetInstanceByIdInput, f as CollectibleGetPublicInstanceInput, g as CollectibleGetPublicInstancesBatchInput, h as CollectibleGetShellImageUrlInput, F as FranchiseGetInput, G as GoodZApiError, i as GoodZApiFieldError, j as GoodZErrorV2, I as InventoryConfirmOwnershipInput, k as InventoryConfirmOwnershipOutput, l as InventoryGetUserInventoryInput, m as InventoryGrantMintAuthInput, n as InventoryItem, o as InventoryMintInput, p as InventoryMintOutput, q as InventoryTransferByCardInput, r as InventoryTransferByCardOutput, s as InventoryTransferHistoryInput, t as InventoryTransferInput, u as InventoryTransferOutput, P as PurchaseChannel, S as SaleType, v as SeriesGetInput, w as SeriesListByFranchiseInput, T as TransferReason, U as UserGetPublicProfileByIdInput, x as UserGetPublicProfileInput, y as UserPublicProfile, Z as ZcoinChargeUserInput, z as ZcoinChargeUserOutput, B as ZcoinCommercialTransferInput, D as ZcoinCommercialTransferOutput, E as ZcoinCreateDepositOrderInput, H as ZcoinCreateDepositOrderOutput, J as ZcoinCreateDirectPurchaseOrderInput, K as ZcoinCreateDirectPurchaseOrderOutput, L as ZcoinDepositPackage, M as ZcoinGetDepositPackagesInput, N as ZcoinGetDepositStatusInput, O as ZcoinGetDepositStatusOutput, Q as ZcoinGetDepositUrlInput, R as ZcoinGetDepositUrlOutput, V as ZcoinGetMyBalanceOutput, W as ZcoinGetMyHistoryInput, X as ZcoinMintAndChargeInput, Y as ZcoinMintAndChargeOutput, _ as ZcoinTxType } from './transport-BSpGsxyt.js';
3
3
  export { AuthorizationMode, CampaignStatus, CommerceActivateCampaignInput, CommerceBatch, CommerceBatchTier, CommerceBrowseWholesaleInput, CommerceCampaign, CommerceCampaignItem, CommerceCreateBatchInput, CommerceCreateGachaPoolInput, CommerceCreateShopInput, CommerceDeleteWebhookInput, CommerceDrawResult, CommerceEndCampaignInput, CommerceExecutePurchaseInput, CommerceGachaItem, CommerceGachaPool, CommerceGetAuthUrlInput, CommerceGetCampaignInfoInput, CommerceGetCampaignItemsInput, CommerceGetMyOrdersInput, CommerceGetSettlementReportInput, CommerceGetShopDashboardInput, CommerceGetShopsByBlueprintInput, CommerceLaunchCampaignInput, CommerceListMyAppsInput, CommerceManageInventoryInput, CommerceMintToInventoryInput, CommerceNamespace, CommerceOrder, CommercePauseCampaignInput, CommercePityConfig, CommerceProcureBatchInput, CommercePublishToWholesaleInput, CommerceRedeemPhysicalInput, CommerceRegisterAppInput, CommerceRegisterInstancesInput, CommerceRegisterWebhookInput, CommerceSearchMarketplaceInput, CommerceShop, CommerceShopDashboard, CommerceTestWebhookInput, CommerceUpdateAppInput, CommerceUpdateCampaignInput, CommerceWebhook, CommerceWholesaleListing, IntegrationMode, SaleMode } from './commerce/index.js';
4
4
  export { CompensationDirection, ExchangeAddToWatchlistInput, ExchangeBid, ExchangeBrowseMarketplaceInput, ExchangeBuyListingInput, ExchangeBuyListingOutput, ExchangeCancelListingInput, ExchangeCancelWtbInput, ExchangeCreateListingInput, ExchangeCreateListingOutput, ExchangeCreateWtbInput, ExchangeFulfillWtbInput, ExchangeFulfillWtbOutput, ExchangeGetBidsInput, ExchangeGetListingDetailInput, ExchangeGetMarketDataInput, ExchangeListing, ExchangeMarketData, ExchangeNamespace, ExchangePlaceBidInput, ExchangePlaceBidOutput, ExchangePricePoint, ExchangeProposeTradeInput, ExchangeRemoveFromWatchlistInput, ExchangeRespondToTradeInput, ExchangeRespondToTradeOutput, ExchangeTradeItem, ExchangeTradeProposal, ExchangeWatchlistItem, ExchangeWtb, ListingCondition, ListingType } from './exchange/index.js';
5
5
  export { AliveBuildContextInput, AliveChatResponse, AliveClassifiedIntent, AliveClassifyIntentInput, AliveContext, AliveForgetMemoryInput, AliveGetIntimacyInput, AliveIntimacy, AliveMemory, AliveNamespace, AliveRecallMemoriesInput, AliveSendMessageInput, AliveStoreMemoryInput, AliveUpdateIntimacyInput, IntentCategory, MemoryType, MoodState } from './alive/index.js';
@@ -46,6 +46,6 @@ import 'react';
46
46
  * @module
47
47
  */
48
48
 
49
- declare const SDK_VERSION = "0.3.3";
49
+ declare const SDK_VERSION = "0.3.4";
50
50
 
51
51
  export { SDK_VERSION };
package/dist/index.js CHANGED
@@ -1,14 +1,14 @@
1
- export { createGoodZClient, createUserClient } from './chunk-EQUAL5M6.js';
1
+ export { createGoodZClient, createUserClient } from './chunk-DSWHCVKV.js';
2
2
  export { TokenManager, buildAuthorizationUrl, exchangeCode } from './chunk-EUKUN4JF.js';
3
3
  export { ZCOIN_PRECISION, formatZcoin, formatZcoinWithSymbol, toDisplay, toHundredths } from './chunk-2ZETOE2X.js';
4
4
  export { FORM_FACTORS, GoodZCardFocus, getAspectRatioCSS, getFormFactorSpec } from './chunk-K6IFJWLB.js';
5
- import './chunk-V73MMKHI.js';
6
- import './chunk-OUKZ2PRD.js';
7
- import './chunk-JAVMQXJM.js';
8
- export { GoodZApiError } from './chunk-4SU7SU7K.js';
5
+ import './chunk-SWD7BJQ7.js';
6
+ import './chunk-GH33FPMY.js';
7
+ import './chunk-KP7DP5LP.js';
8
+ export { GoodZApiError } from './chunk-ORUFMYZB.js';
9
9
 
10
10
  // src/index.ts
11
- var SDK_VERSION = "0.3.3";
11
+ var SDK_VERSION = "0.3.4";
12
12
 
13
13
  export { SDK_VERSION };
14
14
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts"],"names":[],"mappings":";;;;;;;;;;AAqGO,IAAM,WAAA,GAAc","file":"index.js","sourcesContent":["/**\n * @goodz-core/sdk — Official SDK for the GoodZ Ecosystem\n *\n * One package, all services. Stripe-style unified client.\n *\n * ```ts\n * import { createGoodZClient } from \"@goodz-core/sdk\";\n *\n * const goodz = createGoodZClient({ accessToken: \"...\" });\n *\n * // Core\n * await goodz.zcoin.getMyBalance();\n * await goodz.inventory.mint({ ... });\n *\n * // Commerce\n * await goodz.commerce.createShop({ name: \"My Shop\" });\n * await goodz.commerce.executePurchase({ campaignId: 1, quantity: 1 });\n *\n * // Exchange\n * await goodz.exchange.createListing({ ... });\n * await goodz.exchange.getMarketData({ coreGoodzId: 42 });\n *\n * // Alive\n * await goodz.alive.sendMessage({ instanceId: 1, userId: 1, message: \"Hello!\" });\n * ```\n *\n * For tree-shaking, prefer importing from specific subpaths:\n *\n * ```ts\n * import { createGoodZClient } from \"@goodz-core/sdk/core\";\n * import { TokenManager } from \"@goodz-core/sdk/auth\";\n * import { GoodZCardFocus } from \"@goodz-core/sdk/ui\";\n * ```\n *\n * @module\n */\n\n// Core client (includes all namespace types)\nexport {\n createGoodZClient,\n createUserClient,\n GoodZApiError,\n type GoodZClient,\n type GoodZClientConfig,\n // Core namespaces\n type ZcoinNamespace,\n type InventoryNamespace,\n type CollectibleNamespace,\n type UserNamespace,\n type AuthNamespace,\n type IpNamespace,\n // Sub-site namespaces\n type CommerceNamespace,\n type ExchangeNamespace,\n type AliveNamespace,\n} from \"./core/index\";\n\n// All API types — Core\nexport type * from \"./types\";\n\n// All API types — Commerce\nexport type * from \"./types-commerce\";\n\n// All API types — Exchange\nexport type * from \"./types-exchange\";\n\n// All API types — Alive\nexport type * from \"./types-alive\";\n\n// Auth helpers\nexport {\n TokenManager,\n buildAuthorizationUrl,\n exchangeCode,\n type TokenManagerConfig,\n type TokenPair,\n type OAuthUrlConfig,\n} from \"./auth/index\";\n\n// Z-coin utilities\nexport {\n ZCOIN_PRECISION,\n toHundredths,\n toDisplay,\n formatZcoin,\n formatZcoinWithSymbol,\n} from \"./zcoin-utils\";\n\n// UI components (React 18+)\n// Note: Import from \"@goodz-core/sdk/ui\" for tree-shaking\nexport {\n GoodZCardFocus,\n type GoodZCardFocusProps,\n type FormFactorKey,\n type FormFactorSpec,\n FORM_FACTORS,\n getFormFactorSpec,\n getAspectRatioCSS,\n} from \"./ui/index\";\n\n// SDK version\nexport const SDK_VERSION = \"0.3.3\";\n"]}
1
+ {"version":3,"sources":["../src/index.ts"],"names":[],"mappings":";;;;;;;;;;AAqGO,IAAM,WAAA,GAAc","file":"index.js","sourcesContent":["/**\n * @goodz-core/sdk — Official SDK for the GoodZ Ecosystem\n *\n * One package, all services. Stripe-style unified client.\n *\n * ```ts\n * import { createGoodZClient } from \"@goodz-core/sdk\";\n *\n * const goodz = createGoodZClient({ accessToken: \"...\" });\n *\n * // Core\n * await goodz.zcoin.getMyBalance();\n * await goodz.inventory.mint({ ... });\n *\n * // Commerce\n * await goodz.commerce.createShop({ name: \"My Shop\" });\n * await goodz.commerce.executePurchase({ campaignId: 1, quantity: 1 });\n *\n * // Exchange\n * await goodz.exchange.createListing({ ... });\n * await goodz.exchange.getMarketData({ coreGoodzId: 42 });\n *\n * // Alive\n * await goodz.alive.sendMessage({ instanceId: 1, userId: 1, message: \"Hello!\" });\n * ```\n *\n * For tree-shaking, prefer importing from specific subpaths:\n *\n * ```ts\n * import { createGoodZClient } from \"@goodz-core/sdk/core\";\n * import { TokenManager } from \"@goodz-core/sdk/auth\";\n * import { GoodZCardFocus } from \"@goodz-core/sdk/ui\";\n * ```\n *\n * @module\n */\n\n// Core client (includes all namespace types)\nexport {\n createGoodZClient,\n createUserClient,\n GoodZApiError,\n type GoodZClient,\n type GoodZClientConfig,\n // Core namespaces\n type ZcoinNamespace,\n type InventoryNamespace,\n type CollectibleNamespace,\n type UserNamespace,\n type AuthNamespace,\n type IpNamespace,\n // Sub-site namespaces\n type CommerceNamespace,\n type ExchangeNamespace,\n type AliveNamespace,\n} from \"./core/index\";\n\n// All API types — Core\nexport type * from \"./types\";\n\n// All API types — Commerce\nexport type * from \"./types-commerce\";\n\n// All API types — Exchange\nexport type * from \"./types-exchange\";\n\n// All API types — Alive\nexport type * from \"./types-alive\";\n\n// Auth helpers\nexport {\n TokenManager,\n buildAuthorizationUrl,\n exchangeCode,\n type TokenManagerConfig,\n type TokenPair,\n type OAuthUrlConfig,\n} from \"./auth/index\";\n\n// Z-coin utilities\nexport {\n ZCOIN_PRECISION,\n toHundredths,\n toDisplay,\n formatZcoin,\n formatZcoinWithSymbol,\n} from \"./zcoin-utils\";\n\n// UI components (React 18+)\n// Note: Import from \"@goodz-core/sdk/ui\" for tree-shaking\nexport {\n GoodZCardFocus,\n type GoodZCardFocusProps,\n type FormFactorKey,\n type FormFactorSpec,\n FORM_FACTORS,\n getFormFactorSpec,\n getAspectRatioCSS,\n} from \"./ui/index\";\n\n// SDK version\nexport const SDK_VERSION = \"0.3.4\";\n"]}
@@ -423,6 +423,28 @@ declare class GoodZApiError extends Error {
423
423
  });
424
424
  /** Human-readable summary including field errors if present. */
425
425
  toDetailedString(): string;
426
+ /**
427
+ * Check if this error is an insufficient Z-coin balance error.
428
+ * When true, `depositUrl` provides the URL to redirect users for top-up.
429
+ *
430
+ * @example
431
+ * ```ts
432
+ * try {
433
+ * await goodz.zcoin.commercialTransfer({ ... });
434
+ * } catch (e) {
435
+ * if (e instanceof GoodZApiError && e.isInsufficientBalance()) {
436
+ * window.open(e.depositUrl!, '_blank');
437
+ * }
438
+ * }
439
+ * ```
440
+ */
441
+ isInsufficientBalance(): boolean;
442
+ /**
443
+ * Deposit URL for Z-coin top-up (available when isInsufficientBalance() is true).
444
+ * Returned by Core when a payment fails due to insufficient balance.
445
+ * Append `&amount={needed}&return_url={your_page}` for seamless round-trip.
446
+ */
447
+ get depositUrl(): string | undefined;
426
448
  }
427
449
  interface TransportConfig {
428
450
  baseUrl: string;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@goodz-core/sdk",
3
- "version": "0.3.3",
3
+ "version": "0.3.4",
4
4
  "description": "Official SDK for the GoodZ Ecosystem — unified API client for Core, Commerce, Exchange, and Alive. Includes OAuth helpers, Z-coin utilities, and React UI components.",
5
5
  "type": "module",
6
6
  "main": "./dist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A,EACA,UAAA,EACG;AACH,EAAA,IAAI,CAAC,MAAA,EAAQ;AACX,IAAA,MAAM,IAAI,aAAA,CAAc;AAAA,MACtB,OAAA,EAAS,2BAA2B,QAAQ,CAAA,CAAA;AAAA,MAC5C,IAAA,EAAM,cAAA;AAAA,MACN,UAAA;AAAA,MACA,IAAA,EAAM;AAAA,KACP,CAAA;AAAA,EACH;AAGA,EAAA,MAAM,UAAU,MAAA,CAAO,OAAA;AACvB,EAAA,IAAI,KAAA,CAAM,OAAA,CAAQ,OAAO,CAAA,EAAG;AAE1B,IAAA,MAAM,YAAY,OAAA,CAAQ,IAAA,CAAK,CAAC,CAAA,KAAW,CAAA,CAAE,SAAS,MAAM,CAAA;AAC5D,IAAA,IAAI,WAAW,IAAA,EAAM;AAEnB,MAAA,IAAI,OAAO,OAAA,EAAS;AAClB,QAAA,MAAM,IAAI,aAAA,CAAc;AAAA,UACtB,SAAS,SAAA,CAAU,IAAA;AAAA,UACnB,IAAA,EAAM,gBAAA;AAAA,UACN,UAAA;AAAA,UACA,IAAA,EAAM;AAAA,SACP,CAAA;AAAA,MACH;AAGA,MAAA,IAAI;AACF,QAAA,OAAO,IAAA,CAAK,KAAA,CAAM,SAAA,CAAU,IAAI,CAAA;AAAA,MAClC,CAAA,CAAA,MAAQ;AAEN,QAAA,OAAO,SAAA,CAAU,IAAA;AAAA,MACnB;AAAA,IACF;AAAA,EACF;AAGA,EAAA,OAAO,MAAA;AACT;AAOO,SAAS,wBAAA,CACd,SACA,UAAA,EACiB;AACjB,EAAA,OAAO;AAAA,IACL,OAAA,EAAS,OAAA,CAAQ,OAAA,CAAQ,KAAA,EAAO,EAAE,CAAA;AAAA,IAClC;AAAA,GACF;AACF","file":"chunk-4SU7SU7K.js","sourcesContent":["/**\n * @goodz-core/sdk — HTTP Transport Layer\n *\n * Speaks the tRPC v11 HTTP wire protocol directly using fetch.\n * Handles superjson serialization, batching, and error parsing.\n *\n * Wire format reference:\n * - Queries: GET /api/trpc/{procedure}?input={superjson-encoded}\n * - Mutations: POST /api/trpc/{procedure} body: {superjson-encoded}\n * - Batch: GET /api/trpc/{p1},{p2}?input={0: ..., 1: ...}\n *\n * @internal\n */\n\nimport superjson from \"superjson\";\nimport type { GoodZApiFieldError } from \"./types\";\n\n// ─── Error class ─────────────────────────────────────────────\n\nexport class GoodZApiError extends Error {\n public readonly code: string;\n public readonly httpStatus: number;\n public readonly path: string;\n public readonly zodErrors?: GoodZApiFieldError[];\n public readonly data?: unknown;\n\n constructor(opts: {\n message: string;\n code: string;\n httpStatus: number;\n path: string;\n zodErrors?: GoodZApiFieldError[];\n data?: unknown;\n }) {\n super(opts.message);\n this.name = \"GoodZApiError\";\n this.code = opts.code;\n this.httpStatus = opts.httpStatus;\n this.path = opts.path;\n this.zodErrors = opts.zodErrors;\n this.data = opts.data;\n }\n\n /** Human-readable summary including field errors if present. */\n toDetailedString(): string {\n const parts = [\n `[GoodZApiError] ${this.code} on ${this.path}: ${this.message}`,\n ];\n if (this.zodErrors?.length) {\n parts.push(\"Field errors:\");\n for (const e of this.zodErrors) {\n parts.push(` - ${e.path.join(\".\")}: ${e.message} (${e.code})`);\n }\n }\n return parts.join(\"\\n\");\n }\n}\n\n// ─── Transport config ────────────────────────────────────────\n\nexport interface TransportConfig {\n baseUrl: string;\n getHeaders: () => Record<string, string> | Promise<Record<string, string>>;\n}\n\n// ─── Core transport functions ────────────────────────────────\n\n/**\n * Call a tRPC query (GET request).\n * Uses POST with method override for compatibility with Commerce/Exchange\n * server-to-server patterns (some proxies strip GET bodies).\n */\nexport async function callQuery<TInput, TOutput>(\n config: TransportConfig,\n path: string,\n input?: TInput,\n): Promise<TOutput> {\n const url = `${config.baseUrl}/api/trpc/${path}`;\n const headers = await config.getHeaders();\n\n // Use GET with query params for queries (standard tRPC)\n const serialized = input !== undefined ? superjson.serialize(input) : undefined;\n const queryUrl = serialized\n ? `${url}?input=${encodeURIComponent(JSON.stringify(serialized))}`\n : url;\n\n const res = await fetch(queryUrl, {\n method: \"GET\",\n headers: {\n ...headers,\n \"Content-Type\": \"application/json\",\n },\n });\n\n return parseResponse<TOutput>(res, path);\n}\n\n/**\n * Call a tRPC mutation (POST request).\n */\nexport async function callMutation<TInput, TOutput>(\n config: TransportConfig,\n path: string,\n input?: TInput,\n): Promise<TOutput> {\n const url = `${config.baseUrl}/api/trpc/${path}`;\n const headers = await config.getHeaders();\n\n const serialized = input !== undefined ? superjson.serialize(input) : undefined;\n\n const res = await fetch(url, {\n method: \"POST\",\n headers: {\n ...headers,\n \"Content-Type\": \"application/json\",\n },\n body: serialized ? JSON.stringify(serialized) : undefined,\n });\n\n return parseResponse<TOutput>(res, path);\n}\n\n// ─── Response parser ─────────────────────────────────────────\n\nasync function parseResponse<T>(res: Response, path: string): Promise<T> {\n const text = await res.text();\n let body: any;\n\n try {\n body = JSON.parse(text);\n } catch {\n throw new GoodZApiError({\n message: `Invalid JSON response: ${text.slice(0, 200)}`,\n code: \"PARSE_ERROR\",\n httpStatus: res.status,\n path,\n });\n }\n\n // tRPC wraps responses in { result: { data: ... } }\n // Batch responses are arrays: [{ result: { data: ... } }]\n const envelope = Array.isArray(body) ? body[0] : body;\n\n // Check for tRPC error envelope\n if (envelope?.error) {\n const err = envelope.error;\n const errJson = err?.json ?? err;\n const errData = errJson?.data ?? {};\n\n throw new GoodZApiError({\n message: errJson?.message ?? \"Unknown API error\",\n code: errData?.code ?? errJson?.code ?? \"UNKNOWN\",\n httpStatus: errData?.httpStatus ?? res.status,\n path: errData?.path ?? path,\n zodErrors: errData?.zodError?.issues,\n data: errData,\n });\n }\n\n // Success path: extract and deserialize the data\n const resultData = envelope?.result?.data;\n if (resultData === undefined) {\n // Some queries return null/undefined legitimately\n if (res.ok) return undefined as T;\n\n throw new GoodZApiError({\n message: `Unexpected response shape from ${path}`,\n code: \"UNEXPECTED_RESPONSE\",\n httpStatus: res.status,\n path,\n });\n }\n\n // superjson wraps data in { json: ..., meta?: ... }\n // Check if it's a superjson envelope\n if (resultData && typeof resultData === \"object\" && \"json\" in resultData) {\n return superjson.deserialize(resultData) as T;\n }\n\n // Plain JSON (shouldn't happen with superjson transformer, but be safe)\n return resultData as T;\n}\n","/**\n * @goodz-core/sdk — MCP Transport Layer\n *\n * Speaks the MCP (Model Context Protocol) JSON-RPC 2.0 wire format\n * used by Commerce, Exchange, and Alive sub-sites.\n *\n * Wire format:\n * POST /api/mcp\n * Content-Type: application/json\n * Authorization: Bearer <token>\n *\n * { \"jsonrpc\": \"2.0\", \"method\": \"tools/call\", \"params\": { \"name\": \"<tool>\", \"arguments\": { ... } }, \"id\": 1 }\n *\n * Response:\n * { \"jsonrpc\": \"2.0\", \"result\": { \"content\": [{ \"type\": \"text\", \"text\": \"<json>\" }] }, \"id\": 1 }\n *\n * @internal\n */\n\nimport { GoodZApiError } from \"./transport\";\nimport type { TransportConfig } from \"./transport\";\n\n// Re-export for convenience\nexport type { TransportConfig };\n\n// ─── MCP request counter ────────────────────────────────────\n\nlet _mcpRequestId = 0;\nfunction nextId(): number {\n return ++_mcpRequestId;\n}\n\n// ─── Session management ─────────────────────────────────────\n\nconst _sessionIds = new Map<string, string>();\n\n// ─── Core MCP call function ─────────────────────────────────\n\n/**\n * Call an MCP tool on a sub-site.\n *\n * Handles:\n * - JSON-RPC 2.0 envelope construction\n * - Session ID management (mcp-session-id header)\n * - Response parsing (extracts JSON from text content)\n * - Error mapping to GoodZApiError\n */\nexport async function callMcpTool<TInput extends Record<string, any>, TOutput>(\n config: TransportConfig,\n toolName: string,\n args?: TInput,\n): Promise<TOutput> {\n const url = `${config.baseUrl}/api/mcp`;\n const headers = await config.getHeaders();\n\n // Add session ID if we have one for this endpoint\n const sessionId = _sessionIds.get(config.baseUrl);\n if (sessionId) {\n headers[\"mcp-session-id\"] = sessionId;\n }\n\n const body = {\n jsonrpc: \"2.0\" as const,\n method: \"tools/call\",\n params: {\n name: toolName,\n arguments: args ?? {},\n },\n id: nextId(),\n };\n\n const res = await fetch(url, {\n method: \"POST\",\n headers: {\n ...headers,\n \"Content-Type\": \"application/json\",\n Accept: \"application/json, text/event-stream\",\n },\n body: JSON.stringify(body),\n });\n\n // Store session ID from response\n const newSessionId = res.headers.get(\"mcp-session-id\");\n if (newSessionId) {\n _sessionIds.set(config.baseUrl, newSessionId);\n }\n\n // Handle SSE responses (some MCP servers use streaming)\n const contentType = res.headers.get(\"content-type\") || \"\";\n if (contentType.includes(\"text/event-stream\")) {\n return parseSseResponse<TOutput>(res, toolName);\n }\n\n // Standard JSON response\n const text = await res.text();\n return parseJsonRpcResponse<TOutput>(text, res.status, toolName);\n}\n\n// ─── Response parsers ───────────────────────────────────────\n\nfunction parseJsonRpcResponse<T>(\n text: string,\n httpStatus: number,\n toolName: string,\n): T {\n let body: any;\n try {\n body = JSON.parse(text);\n } catch {\n throw new GoodZApiError({\n message: `Invalid JSON response from MCP tool ${toolName}: ${text.slice(0, 200)}`,\n code: \"PARSE_ERROR\",\n httpStatus,\n path: toolName,\n });\n }\n\n // JSON-RPC error\n if (body.error) {\n throw new GoodZApiError({\n message: body.error.message || \"MCP tool error\",\n code: body.error.code?.toString() || \"MCP_ERROR\",\n httpStatus,\n path: toolName,\n data: body.error.data,\n });\n }\n\n // Extract result from MCP content array\n return extractMcpResult<T>(body.result, toolName, httpStatus);\n}\n\nasync function parseSseResponse<T>(\n res: Response,\n toolName: string,\n): Promise<T> {\n const text = await res.text();\n const lines = text.split(\"\\n\");\n\n // Find the last \"data:\" line that contains a JSON-RPC response\n let lastData: string | null = null;\n for (const line of lines) {\n if (line.startsWith(\"data:\")) {\n lastData = line.slice(5).trim();\n }\n }\n\n if (!lastData) {\n throw new GoodZApiError({\n message: `Empty SSE response from MCP tool ${toolName}`,\n code: \"EMPTY_RESPONSE\",\n httpStatus: res.status,\n path: toolName,\n });\n }\n\n return parseJsonRpcResponse<T>(lastData, res.status, toolName);\n}\n\nfunction extractMcpResult<T>(\n result: any,\n toolName: string,\n httpStatus: number,\n): T {\n if (!result) {\n throw new GoodZApiError({\n message: `No result from MCP tool ${toolName}`,\n code: \"EMPTY_RESULT\",\n httpStatus,\n path: toolName,\n });\n }\n\n // MCP tools return { content: [{ type: \"text\", text: \"...\" }] }\n const content = result.content;\n if (Array.isArray(content)) {\n // Find the first text content block\n const textBlock = content.find((c: any) => c.type === \"text\");\n if (textBlock?.text) {\n // Check if the tool returned an error in the text\n if (result.isError) {\n throw new GoodZApiError({\n message: textBlock.text,\n code: \"MCP_TOOL_ERROR\",\n httpStatus,\n path: toolName,\n });\n }\n\n // Try to parse as JSON\n try {\n return JSON.parse(textBlock.text) as T;\n } catch {\n // If not JSON, return the text as-is (some tools return plain text)\n return textBlock.text as T;\n }\n }\n }\n\n // Fallback: return the result directly\n return result as T;\n}\n\n// ─── MCP transport config builder ───────────────────────────\n\n/**\n * Create a TransportConfig for an MCP sub-site endpoint.\n */\nexport function createMcpTransportConfig(\n baseUrl: string,\n getHeaders: () => Record<string, string> | Promise<Record<string, string>>,\n): TransportConfig {\n return {\n baseUrl: baseUrl.replace(/\\/$/, \"\"),\n getHeaders,\n };\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/core/index.ts"],"names":[],"mappings":";;;;;;AA0HA,IAAM,gBAAA,GAAmB,+BAAA;AACzB,IAAM,oBAAA,GAAuB,mCAAA;AAC7B,IAAM,oBAAA,GAAuB,mCAAA;AAC7B,IAAM,iBAAA,GAAoB,gCAAA;AAoSnB,SAAS,iBAAA,CAAkB,MAAA,GAA4B,EAAC,EAAgB;AAC7E,EAAA,MAAM;AAAA,IACJ,OAAA,GAAU,gBAAA;AAAA,IACV,WAAA,GAAc,oBAAA;AAAA,IACd,WAAA,GAAc,oBAAA;AAAA,IACd,QAAA,GAAW,iBAAA;AAAA,IACX,WAAA;AAAA,IACA,cAAA;AAAA,IACA,OAAA,EAAS;AAAA,GACX,GAAI,MAAA;AAGJ,EAAA,MAAM,eAAe,YAA6C;AAChE,IAAA,MAAM,CAAA,GAA4B,EAAE,GAAG,aAAA,EAAc;AACr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,mBAAmB;AAAA,KACxE;AAAA;AAAA,IAGA,QAAA,EAAU,wBAAwB,iBAAiB,CAAA;AAAA;AAAA,IAGnD,QAAA,EAAU,wBAAwB,iBAAiB,CAAA;AAAA;AAAA,IAGnD,KAAA,EAAO,qBAAqB,cAAc,CAAA;AAAA;AAAA,IAG1C,UAAU,CAAU,IAAA,EAAc,UAAgB,SAAA,CAAkB,aAAA,EAAe,MAAM,KAAK,CAAA;AAAA,IAC9F,aAAa,CAAU,IAAA,EAAc,UAAgB,YAAA,CAAqB,aAAA,EAAe,MAAM,KAAK;AAAA,GACtG;AACF;AAMO,IAAM,gBAAA,GAAmB","file":"chunk-EQUAL5M6.js","sourcesContent":["/**\n * @goodz-core/sdk/core — Unified GoodZ API Client\n *\n * One client, all services. Stripe-style namespace architecture:\n * goodz.zcoin.* → Core settlement & Z-coin\n * goodz.inventory.* → Core instance management\n * goodz.collectible.* → Core card queries\n * goodz.user.* → Core user profiles\n * goodz.auth.* → Core auth\n * goodz.ip.* → Core IP (franchise/series/card)\n * goodz.commerce.* → Commerce/Shops (MCP)\n * goodz.exchange.* → Exchange marketplace (MCP)\n * goodz.alive.* → Alive companions (MCP)\n *\n * Core uses tRPC HTTP wire protocol; sub-sites use MCP JSON-RPC 2.0.\n * The client handles routing transparently.\n *\n * @example\n * ```ts\n * import { createGoodZClient } from \"@goodz-core/sdk\";\n *\n * const goodz = createGoodZClient({\n * accessToken: \"your-jwt-token\",\n * });\n *\n * // Core APIs\n * const balance = await goodz.zcoin.getMyBalance();\n * const result = await goodz.zcoin.commercialTransfer({ ... });\n *\n * // Commerce APIs\n * const shop = await goodz.commerce.createShop({ name: \"My Shop\" });\n * const order = await goodz.commerce.executePurchase({ campaignId: 1, quantity: 1 });\n *\n * // Exchange APIs\n * const listing = await goodz.exchange.createListing({ ... });\n * const data = await goodz.exchange.getMarketData({ coreGoodzId: 42 });\n *\n * // Alive APIs\n * const chat = await goodz.alive.sendMessage({ instanceId: 1, userId: 1, message: \"Hello!\" });\n * const memories = await goodz.alive.recallMemories({ instanceId: 1, userId: 1, query: \"birthday\" });\n * ```\n *\n * @module\n */\n\nimport { callQuery, callMutation, GoodZApiError } from \"../transport\";\nimport type { TransportConfig } from \"../transport\";\nimport { createMcpTransportConfig } from \"../mcp-transport\";\nimport { createCommerceNamespace } from \"../commerce/index\";\nimport type { CommerceNamespace } from \"../commerce/index\";\nimport { createExchangeNamespace } from \"../exchange/index\";\nimport type { ExchangeNamespace } from \"../exchange/index\";\nimport { createAliveNamespace } from \"../alive/index\";\nimport type { AliveNamespace } from \"../alive/index\";\nimport type {\n // zcoin\n ZcoinGetMyBalanceOutput,\n ZcoinGetMyHistoryInput,\n ZcoinCommercialTransferInput,\n ZcoinCommercialTransferOutput,\n ZcoinMintAndChargeInput,\n ZcoinMintAndChargeOutput,\n ZcoinChargeUserInput,\n ZcoinChargeUserOutput,\n ZcoinCreateDirectPurchaseOrderInput,\n ZcoinCreateDirectPurchaseOrderOutput,\n ZcoinGetDepositPackagesInput,\n ZcoinDepositPackage,\n ZcoinCreateDepositOrderInput,\n ZcoinCreateDepositOrderOutput,\n ZcoinGetDepositStatusInput,\n ZcoinGetDepositStatusOutput,\n ZcoinGetDepositUrlInput,\n ZcoinGetDepositUrlOutput,\n // inventory\n InventoryGetUserInventoryInput,\n InventoryItem,\n InventoryConfirmOwnershipInput,\n InventoryConfirmOwnershipOutput,\n InventoryMintInput,\n InventoryMintOutput,\n InventoryTransferInput,\n InventoryTransferOutput,\n InventoryTransferByCardInput,\n InventoryTransferByCardOutput,\n InventoryGrantMintAuthInput,\n InventoryTransferHistoryInput,\n // collectible\n CollectibleGetInstanceByIdInput,\n CollectibleGetPublicInstanceInput,\n CollectibleGetPublicInstancesBatchInput,\n CollectibleGetCardProfileInput,\n CollectibleGetShellImageUrlInput,\n // user\n UserGetPublicProfileInput,\n UserPublicProfile,\n UserGetPublicProfileByIdInput,\n // auth\n AuthGetOAuthAppInfoInput,\n AuthOAuthAppInfo,\n AuthUser,\n // ip\n FranchiseGetInput,\n SeriesGetInput,\n SeriesListByFranchiseInput,\n CardGetInput,\n CardListBySeriesInput,\n} from \"../types\";\n\n// ─── Re-export types and error class ─────────────────────────\n\nexport { GoodZApiError } from \"../transport\";\nexport type * from \"../types\";\nexport type * from \"../types-commerce\";\nexport type * from \"../types-exchange\";\nexport type * from \"../types-alive\";\nexport type { CommerceNamespace } from \"../commerce/index\";\nexport type { ExchangeNamespace } from \"../exchange/index\";\nexport type { AliveNamespace } from \"../alive/index\";\n\n// ─── Default sub-site URLs ──────────────────────────────────\n\nconst DEFAULT_CORE_URL = \"https://goodzcore.manus.space\";\nconst DEFAULT_COMMERCE_URL = \"https://goodzcommerce.manus.space\";\nconst DEFAULT_EXCHANGE_URL = \"https://goodzexchange.manus.space\";\nconst DEFAULT_ALIVE_URL = \"https://goodzalive.manus.space\";\n\n// ─── Client config ───────────────────────────────────────────\n\nexport interface GoodZClientConfig {\n /**\n * GoodZ.Core base URL.\n * @default \"https://goodzcore.manus.space\"\n */\n coreUrl?: string;\n\n /**\n * GoodZ.Commerce (Shops) base URL.\n * @default \"https://goodzcommerce.manus.space\"\n */\n commerceUrl?: string;\n\n /**\n * GoodZ.Exchange base URL.\n * @default \"https://goodzexchange.manus.space\"\n */\n exchangeUrl?: string;\n\n /**\n * GoodZ.Alive base URL.\n * @default \"https://goodzalive.manus.space\"\n */\n aliveUrl?: string;\n\n /**\n * Static access token (JWT) for authentication.\n * For server-to-server calls, obtain this via OAuth client_credentials flow.\n * For user-context calls, pass the user's access token.\n */\n accessToken?: string;\n\n /**\n * Dynamic token provider — called before every request.\n * Use this when tokens may rotate (e.g., auto-refresh).\n * Takes precedence over `accessToken` if both are set.\n */\n getAccessToken?: () => string | Promise<string>;\n\n /**\n * Custom headers to include in every request.\n * Useful for passing app identifiers or tracing headers.\n */\n headers?: Record<string, string>;\n}\n\n// ─── Core namespace interfaces (tRPC) ───────────────────────\n\nexport interface ZcoinNamespace {\n /** Get the authenticated user's Z-coin balance. */\n getMyBalance(): Promise<ZcoinGetMyBalanceOutput>;\n\n /** Get the authenticated user's Z-coin transaction history. */\n getMyHistory(input?: ZcoinGetMyHistoryInput): Promise<any[]>;\n\n /** Get available Z-coin deposit packages with pricing. */\n getDepositPackages(input?: ZcoinGetDepositPackagesInput): Promise<ZcoinDepositPackage[]>;\n\n /** Create a Stripe checkout session for Z-coin deposit. */\n createDepositOrder(input: ZcoinCreateDepositOrderInput): Promise<ZcoinCreateDepositOrderOutput>;\n\n /** Check the status of a deposit checkout session. */\n getDepositStatus(input: ZcoinGetDepositStatusInput): Promise<ZcoinGetDepositStatusOutput>;\n\n /**\n * Generate a deposit deep link URL for Z-coin top-up.\n * Returns a URL that redirects users to Core's deposit page.\n * After completing the deposit, the user is redirected back to returnUrl.\n *\n * No authentication required — anyone can generate a deposit URL.\n *\n * @example\n * ```ts\n * const { url } = await goodz.zcoin.getDepositUrl({\n * amount: 100,\n * returnUrl: \"https://myapp.com/shop\",\n * appId: \"od_myapp\",\n * });\n * window.open(url, \"_blank\");\n * ```\n */\n getDepositUrl(input?: ZcoinGetDepositUrlInput): Promise<ZcoinGetDepositUrlOutput>;\n\n /**\n * Atomic commercial transfer: Z-coin payment + ownership transfer in one transaction.\n * This is the primary API for Commerce and Exchange purchase flows.\n *\n * Idempotent via referenceId — duplicate calls return the same result.\n *\n * @throws {GoodZApiError} BAD_REQUEST — insufficient balance\n * @throws {GoodZApiError} CONFLICT — version conflict (retry)\n * @throws {GoodZApiError} FORBIDDEN — seller doesn't own instance\n */\n commercialTransfer(input: ZcoinCommercialTransferInput): Promise<ZcoinCommercialTransferOutput>;\n\n /**\n * Mint a new card instance and charge the buyer in one atomic transaction.\n * Used by Commerce for gacha and direct-from-creator purchases.\n *\n * Requires mint authorization (granted via inventory.grantMintAuth).\n * Idempotent via referenceId.\n *\n * @throws {GoodZApiError} FORBIDDEN — no mint authorization\n * @throws {GoodZApiError} BAD_REQUEST — insufficient balance\n */\n mintAndCharge(input: ZcoinMintAndChargeInput): Promise<ZcoinMintAndChargeOutput>;\n\n /**\n * Charge a user's Z-coin balance for an in-app purchase.\n * Used by apps that sell non-GoodZ digital goods/services.\n *\n * Idempotent via appOrderId.\n *\n * @throws {GoodZApiError} BAD_REQUEST — insufficient balance\n * @throws {GoodZApiError} CONFLICT — version conflict\n */\n chargeUser(input: ZcoinChargeUserInput): Promise<ZcoinChargeUserOutput>;\n\n /**\n * Create a direct purchase checkout session (fiat → Z-coin → transfer).\n * Transparent intermediation: user sees fiat price, Core handles conversion.\n */\n createDirectPurchaseOrder(input: ZcoinCreateDirectPurchaseOrderInput): Promise<ZcoinCreateDirectPurchaseOrderOutput>;\n}\n\nexport interface InventoryNamespace {\n /** Get a user's inventory (owned card instances). */\n getUserInventory(input: InventoryGetUserInventoryInput): Promise<InventoryItem[]>;\n\n /** Check if a user owns at least one instance of a specific card. */\n confirmOwnership(input: InventoryConfirmOwnershipInput): Promise<InventoryConfirmOwnershipOutput>;\n\n /**\n * Mint new card instances. Requires franchise ownership or admin role.\n * For Commerce/Exchange, use zcoin.mintAndCharge instead (includes payment).\n */\n mint(input: InventoryMintInput): Promise<InventoryMintOutput>;\n\n /**\n * Transfer a specific card instance to another user.\n * For commercial transfers, use zcoin.commercialTransfer instead.\n *\n * @deprecated for reason=\"purchase\"|\"trade\" — use commercialTransfer\n */\n transfer(input: InventoryTransferInput): Promise<InventoryTransferOutput>;\n\n /**\n * Transfer card instances by cardId (transfers oldest instances).\n * For commercial transfers, use zcoin.commercialTransfer instead.\n *\n * @deprecated for reason=\"purchase\"|\"trade\" — use commercialTransfer\n */\n transferByCard(input: InventoryTransferByCardInput): Promise<InventoryTransferByCardOutput>;\n\n /**\n * Grant mint authorization to another user/app for a specific card.\n * Required before Commerce can call zcoin.mintAndCharge for that card.\n */\n grantMintAuth(input: InventoryGrantMintAuthInput): Promise<any>;\n\n /** Get transfer/ownership history for an instance, card, or user. */\n transferHistory(input: InventoryTransferHistoryInput): Promise<any[]>;\n}\n\nexport interface CollectibleNamespace {\n /** Get a card instance by its numeric ID. Returns full instance data with card chain. */\n getInstanceById(input: CollectibleGetInstanceByIdInput): Promise<any>;\n\n /** Get a card instance by its instance code (public-facing identifier). */\n getPublicInstance(input: CollectibleGetPublicInstanceInput): Promise<any>;\n\n /** Batch-fetch multiple card instances by their IDs (max 100). */\n getPublicInstancesBatch(input: CollectibleGetPublicInstancesBatchInput): Promise<any[]>;\n\n /** Get the card profile (metadata, rarity, series info). */\n getCardProfile(input: CollectibleGetCardProfileInput): Promise<any>;\n\n /** Get the shell (packaging) image URL for a card. */\n getShellImageUrl(input: CollectibleGetShellImageUrlInput): Promise<any>;\n}\n\nexport interface UserNamespace {\n /** Get a user's public profile by openId. */\n getPublicProfile(input: UserGetPublicProfileInput): Promise<UserPublicProfile>;\n\n /** Get a user's public profile by internal userId. */\n getPublicProfileById(input: UserGetPublicProfileByIdInput): Promise<UserPublicProfile>;\n}\n\nexport interface AuthNamespace {\n /** Get the authenticated user's profile. Returns null if not authenticated. */\n me(): Promise<AuthUser | null>;\n\n /** Get public info about an OAuth app by its client ID. */\n getOAuthAppInfo(input: AuthGetOAuthAppInfoInput): Promise<AuthOAuthAppInfo | null>;\n}\n\nexport interface IpNamespace {\n /** Get a franchise by ID or slug. */\n getFranchise(input: FranchiseGetInput): Promise<any>;\n\n /** Get a series by ID or slug. */\n getSeries(input: SeriesGetInput): Promise<any>;\n\n /** List all series in a franchise. */\n listSeriesByFranchise(input: SeriesListByFranchiseInput): Promise<any[]>;\n\n /** Get a card by ID. */\n getCard(input: CardGetInput): Promise<any>;\n\n /** List all cards in a series. */\n listCardsBySeries(input: CardListBySeriesInput): Promise<any[]>;\n}\n\n// ─── GoodZClient type ────────────────────────────────────────\n\nexport interface GoodZClient {\n // ── Core namespaces (tRPC) ──\n readonly zcoin: ZcoinNamespace;\n readonly inventory: InventoryNamespace;\n readonly collectible: CollectibleNamespace;\n readonly user: UserNamespace;\n readonly auth: AuthNamespace;\n readonly ip: IpNamespace;\n\n // ── Sub-site namespaces (MCP) ──\n readonly commerce: CommerceNamespace;\n readonly exchange: ExchangeNamespace;\n readonly alive: AliveNamespace;\n\n /**\n * Make a raw tRPC query call to Core. Use this for routes not yet covered\n * by the typed namespaces.\n */\n rawQuery<T = any>(path: string, input?: any): Promise<T>;\n\n /**\n * Make a raw tRPC mutation call to Core. Use this for routes not yet covered\n * by the typed namespaces.\n */\n rawMutation<T = any>(path: string, input?: any): Promise<T>;\n}\n\n// ─── Client factory ──────────────────────────────────────────\n\n/**\n * Create a unified GoodZ API client — one client for all services.\n *\n * @example Server-to-server with static token\n * ```ts\n * const goodz = createGoodZClient({\n * accessToken: process.env.CORE_ACCESS_TOKEN,\n * });\n *\n * // Core\n * const balance = await goodz.zcoin.getMyBalance();\n *\n * // Commerce\n * const shop = await goodz.commerce.createShop({ name: \"My Shop\" });\n *\n * // Exchange\n * const listings = await goodz.exchange.browseMarketplace();\n *\n * // Alive\n * const chat = await goodz.alive.sendMessage({ instanceId: 1, userId: 1, message: \"Hi!\" });\n * ```\n *\n * @example With dynamic token provider (auto-refresh)\n * ```ts\n * const goodz = createGoodZClient({\n * getAccessToken: async () => {\n * const token = await refreshTokenIfNeeded();\n * return token;\n * },\n * });\n * ```\n *\n * @example Custom sub-site URLs (e.g., staging environment)\n * ```ts\n * const goodz = createGoodZClient({\n * accessToken: \"...\",\n * coreUrl: \"https://staging-core.goodz.dev\",\n * commerceUrl: \"https://staging-commerce.goodz.dev\",\n * exchangeUrl: \"https://staging-exchange.goodz.dev\",\n * aliveUrl: \"https://staging-alive.goodz.dev\",\n * });\n * ```\n */\nexport function createGoodZClient(config: GoodZClientConfig = {}): GoodZClient {\n const {\n coreUrl = DEFAULT_CORE_URL,\n commerceUrl = DEFAULT_COMMERCE_URL,\n exchangeUrl = DEFAULT_EXCHANGE_URL,\n aliveUrl = DEFAULT_ALIVE_URL,\n accessToken,\n getAccessToken,\n headers: customHeaders,\n } = config;\n\n // Shared header builder — used by both tRPC and MCP transports\n const buildHeaders = async (): Promise<Record<string, string>> => {\n const h: Record<string, string> = { ...customHeaders };\n const token = getAccessToken ? await getAccessToken() : accessToken;\n if (token) {\n h[\"Authorization\"] = `Bearer ${token}`;\n }\n return h;\n };\n\n // ── Core transport (tRPC) ──\n const coreTransport: TransportConfig = {\n baseUrl: coreUrl.replace(/\\/$/, \"\"),\n getHeaders: buildHeaders,\n };\n\n // ── Sub-site transports (MCP) ──\n const commerceTransport = createMcpTransportConfig(commerceUrl, buildHeaders);\n const exchangeTransport = createMcpTransportConfig(exchangeUrl, buildHeaders);\n const aliveTransport = createMcpTransportConfig(aliveUrl, buildHeaders);\n\n // Helper shortcuts for Core tRPC\n const q = <I, O>(path: string) => (input?: I) => callQuery<I, O>(coreTransport, path, input);\n const m = <I, O>(path: string) => (input?: I) => callMutation<I, O>(coreTransport, path, input);\n\n return {\n // ── zcoin ──────────────────────────────────────────────\n zcoin: {\n getMyBalance: q<void, ZcoinGetMyBalanceOutput>(\"zcoin.getMyBalance\"),\n getMyHistory: q<ZcoinGetMyHistoryInput, any[]>(\"zcoin.getMyHistory\"),\n getDepositPackages: q<ZcoinGetDepositPackagesInput, ZcoinDepositPackage[]>(\"zcoin.getDepositPackages\"),\n createDepositOrder: m<ZcoinCreateDepositOrderInput, ZcoinCreateDepositOrderOutput>(\"zcoin.createDepositOrder\"),\n getDepositStatus: q<ZcoinGetDepositStatusInput, ZcoinGetDepositStatusOutput>(\"zcoin.getDepositStatus\"),\n getDepositUrl: q<ZcoinGetDepositUrlInput, ZcoinGetDepositUrlOutput>(\"zcoin.getDepositUrl\"),\n commercialTransfer: m<ZcoinCommercialTransferInput, ZcoinCommercialTransferOutput>(\"zcoin.commercialTransfer\"),\n mintAndCharge: m<ZcoinMintAndChargeInput, ZcoinMintAndChargeOutput>(\"zcoin.mintAndCharge\"),\n chargeUser: m<ZcoinChargeUserInput, ZcoinChargeUserOutput>(\"zcoin.chargeUser\"),\n createDirectPurchaseOrder: m<ZcoinCreateDirectPurchaseOrderInput, ZcoinCreateDirectPurchaseOrderOutput>(\"zcoin.createDirectPurchaseOrder\"),\n },\n\n // ── inventory ──────────────────────────────────────────\n inventory: {\n getUserInventory: q<InventoryGetUserInventoryInput, InventoryItem[]>(\"inventory.getUserInventory\"),\n confirmOwnership: q<InventoryConfirmOwnershipInput, InventoryConfirmOwnershipOutput>(\"inventory.confirmOwnership\"),\n mint: m<InventoryMintInput, InventoryMintOutput>(\"inventory.mint\"),\n transfer: m<InventoryTransferInput, InventoryTransferOutput>(\"inventory.transfer\"),\n transferByCard: m<InventoryTransferByCardInput, InventoryTransferByCardOutput>(\"inventory.transferByCard\"),\n grantMintAuth: m<InventoryGrantMintAuthInput, any>(\"inventory.grantMintAuth\"),\n transferHistory: q<InventoryTransferHistoryInput, any[]>(\"inventory.transferHistory\"),\n },\n\n // ── collectible ────────────────────────────────────────\n collectible: {\n getInstanceById: q<CollectibleGetInstanceByIdInput, any>(\"collectible.getInstanceById\"),\n getPublicInstance: q<CollectibleGetPublicInstanceInput, any>(\"collectible.getPublicInstance\"),\n getPublicInstancesBatch: q<CollectibleGetPublicInstancesBatchInput, any[]>(\"collectible.getPublicInstancesBatch\"),\n getCardProfile: q<CollectibleGetCardProfileInput, any>(\"collectible.getCardProfile\"),\n getShellImageUrl: q<CollectibleGetShellImageUrlInput, any>(\"collectible.getShellImageUrl\"),\n },\n\n // ── user ───────────────────────────────────────────────\n user: {\n getPublicProfile: q<UserGetPublicProfileInput, UserPublicProfile>(\"user.getPublicProfile\"),\n getPublicProfileById: q<UserGetPublicProfileByIdInput, UserPublicProfile>(\"user.getPublicProfileById\"),\n },\n\n // ── auth ───────────────────────────────────────────────\n auth: {\n me: q<void, AuthUser | null>(\"auth.me\"),\n getOAuthAppInfo: q<AuthGetOAuthAppInfoInput, AuthOAuthAppInfo | null>(\"auth.getOAuthAppInfo\"),\n },\n\n // ── ip (franchise/series/card) ─────────────────────────\n ip: {\n getFranchise: q<FranchiseGetInput, any>(\"franchise.get\"),\n getSeries: q<SeriesGetInput, any>(\"series.get\"),\n listSeriesByFranchise: q<SeriesListByFranchiseInput, any[]>(\"series.listByFranchise\"),\n getCard: q<CardGetInput, any>(\"card.get\"),\n listCardsBySeries: q<CardListBySeriesInput, any[]>(\"card.listBySeries\"),\n },\n\n // ── commerce (MCP) ─────────────────────────────────────\n commerce: createCommerceNamespace(commerceTransport),\n\n // ── exchange (MCP) ─────────────────────────────────────\n exchange: createExchangeNamespace(exchangeTransport),\n\n // ── alive (MCP) ────────────────────────────────────────\n alive: createAliveNamespace(aliveTransport),\n\n // ── raw escape hatches (Core tRPC only) ────────────────\n rawQuery: <T = any>(path: string, input?: any) => callQuery<any, T>(coreTransport, path, input),\n rawMutation: <T = any>(path: string, input?: any) => callMutation<any, T>(coreTransport, path, input),\n };\n}\n\n/**\n * Alias for createGoodZClient — creates a client acting on behalf of a user.\n * Semantically identical, but makes the intent clearer in server-to-server code.\n */\nexport const createUserClient = createGoodZClient;\n"]}