sunpeak 0.16.27 → 0.16.28

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (87) hide show
  1. package/bin/commands/build.mjs +0 -1
  2. package/dist/chatgpt/globals.css +10 -9
  3. package/dist/chatgpt/index.cjs +55 -24
  4. package/dist/chatgpt/index.cjs.map +1 -1
  5. package/dist/chatgpt/index.js +31 -25
  6. package/dist/chatgpt/index.js.map +1 -1
  7. package/dist/chunk-9hOWP6kD.cjs +64 -0
  8. package/dist/chunk-D6g4UhsZ.js +35 -0
  9. package/dist/claude/index.cjs +4 -4
  10. package/dist/claude/index.js +3 -5
  11. package/dist/discovery-BxKCIgG5.cjs +332 -0
  12. package/dist/discovery-BxKCIgG5.cjs.map +1 -0
  13. package/dist/discovery-Du4LHrih.js +261 -0
  14. package/dist/discovery-Du4LHrih.js.map +1 -0
  15. package/dist/host/chatgpt/index.cjs +171 -65
  16. package/dist/host/chatgpt/index.cjs.map +1 -1
  17. package/dist/host/chatgpt/index.js +170 -70
  18. package/dist/host/chatgpt/index.js.map +1 -1
  19. package/dist/host/index.cjs +47 -19
  20. package/dist/host/index.cjs.map +1 -1
  21. package/dist/host/index.js +47 -24
  22. package/dist/host/index.js.map +1 -1
  23. package/dist/index.cjs +3103 -3725
  24. package/dist/index.cjs.map +1 -1
  25. package/dist/index.js +3026 -3746
  26. package/dist/index.js.map +1 -1
  27. package/dist/lib/discovery-cli.cjs +117 -131
  28. package/dist/lib/discovery-cli.cjs.map +1 -1
  29. package/dist/lib/discovery-cli.js +107 -111
  30. package/dist/lib/discovery-cli.js.map +1 -1
  31. package/dist/mcp/index.cjs +9818 -10283
  32. package/dist/mcp/index.cjs.map +1 -1
  33. package/dist/mcp/index.js +9799 -10282
  34. package/dist/mcp/index.js.map +1 -1
  35. package/dist/protocol-DJmRaBzO.js +11080 -0
  36. package/dist/{protocol-DkDHRwOW.cjs.map → protocol-DJmRaBzO.js.map} +1 -1
  37. package/dist/protocol-jbxhzcnS.cjs +11493 -0
  38. package/dist/protocol-jbxhzcnS.cjs.map +1 -0
  39. package/dist/simulator/index.cjs +79 -36
  40. package/dist/simulator/index.cjs.map +1 -1
  41. package/dist/simulator/index.js +43 -37
  42. package/dist/simulator/index.js.map +1 -1
  43. package/dist/simulator-BYIH-xqQ.cjs +3701 -0
  44. package/dist/{simulator-Gc6n_fT4.cjs.map → simulator-BYIH-xqQ.cjs.map} +1 -1
  45. package/dist/simulator-CmgNnWBO.js +3575 -0
  46. package/dist/simulator-CmgNnWBO.js.map +1 -0
  47. package/dist/simulator-url-BDGD4vZD.cjs +69 -0
  48. package/dist/simulator-url-BDGD4vZD.cjs.map +1 -0
  49. package/dist/simulator-url-Bkxj43yT.js +64 -0
  50. package/dist/simulator-url-Bkxj43yT.js.map +1 -0
  51. package/dist/style.css +10 -9
  52. package/dist/use-app-D2h-aiyr.cjs +940 -0
  53. package/dist/use-app-D2h-aiyr.cjs.map +1 -0
  54. package/dist/use-app-X7JbGskk.js +598 -0
  55. package/dist/use-app-X7JbGskk.js.map +1 -0
  56. package/package.json +8 -8
  57. package/template/node_modules/.bin/vite +2 -2
  58. package/template/node_modules/.bin/vitest +2 -2
  59. package/template/package.json +5 -5
  60. package/dist/claude/index.cjs.map +0 -1
  61. package/dist/claude/index.js.map +0 -1
  62. package/dist/discovery-BVqD-JsT.js +0 -224
  63. package/dist/discovery-BVqD-JsT.js.map +0 -1
  64. package/dist/discovery-D1gpaVz4.cjs +0 -223
  65. package/dist/discovery-D1gpaVz4.cjs.map +0 -1
  66. package/dist/index-BEWVLFfB.cjs +0 -28
  67. package/dist/index-BEWVLFfB.cjs.map +0 -1
  68. package/dist/index-C6XYFOmh.js +0 -29
  69. package/dist/index-C6XYFOmh.js.map +0 -1
  70. package/dist/index-D0FsXP3Y.cjs +0 -40
  71. package/dist/index-D0FsXP3Y.cjs.map +0 -1
  72. package/dist/index-Rg7SWjvl.js +0 -41
  73. package/dist/index-Rg7SWjvl.js.map +0 -1
  74. package/dist/protocol-DkDHRwOW.cjs +0 -12221
  75. package/dist/protocol-uge7qFev.js +0 -12223
  76. package/dist/protocol-uge7qFev.js.map +0 -1
  77. package/dist/simulator-B-CrMHVs.js +0 -3534
  78. package/dist/simulator-B-CrMHVs.js.map +0 -1
  79. package/dist/simulator-Gc6n_fT4.cjs +0 -3549
  80. package/dist/simulator-url-DcSYRl-P.cjs +0 -53
  81. package/dist/simulator-url-DcSYRl-P.cjs.map +0 -1
  82. package/dist/simulator-url-j_XV3EoP.js +0 -54
  83. package/dist/simulator-url-j_XV3EoP.js.map +0 -1
  84. package/dist/use-app-C9gpzIQO.js +0 -349
  85. package/dist/use-app-C9gpzIQO.js.map +0 -1
  86. package/dist/use-app-D09O2swh.cjs +0 -348
  87. package/dist/use-app-D09O2swh.cjs.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"discovery-Du4LHrih.js","names":[],"sources":["../src/lib/discovery.ts"],"sourcesContent":["/**\n * Discovery utilities for auto-discovering resources and simulations\n *\n * These helpers process the results of import.meta.glob() calls to extract\n * keys, build component maps, and connect simulations to resources.\n *\n * The glob calls themselves must remain in the template (Vite compile-time),\n * but all the processing logic lives here for easy updates across templates.\n *\n * Node.js utilities (findResourceDirs, findToolFiles, etc.) can be used\n * by CLI commands for build-time and runtime discovery.\n */\n\nimport type { Simulation } from '../types/simulation.js';\n\n/**\n * Convert a kebab-case string to PascalCase\n * @example toPascalCase('review') // 'Review'\n * @example toPascalCase('album-art') // 'AlbumArt'\n */\nexport function toPascalCase(str: string): string {\n return str\n .split('-')\n .map((part) => part.charAt(0).toUpperCase() + part.slice(1))\n .join('');\n}\n\n/**\n * Extract the resource key from a resource file path.\n * Matches {name}.tsx (e.g., './albums/albums.tsx' → 'albums')\n */\nexport function extractResourceKey(path: string): string | undefined {\n const match = path.match(/([^/]+)\\.tsx$/);\n return match ? match[1] : undefined;\n}\n\n/**\n * Extract the simulation key from a simulation file path.\n * Matches any *.json file (e.g., './show-albums.json' → 'show-albums')\n */\nexport function extractSimulationKey(path: string): string | undefined {\n const match = path.match(/([^/]+)\\.json$/);\n return match ? match[1] : undefined;\n}\n\n/**\n * Find the best matching resource key for a simulation key.\n * Matches the longest resource name that is a prefix of the simulation key.\n * @example findResourceKey('review-diff', ['review', 'carousel']) // 'review'\n * @example findResourceKey('albums', ['albums', 'review']) // 'albums'\n */\nexport function findResourceKey(simulationKey: string, resourceKeys: string[]): string | undefined {\n // Sort by length descending to find longest match first\n const sorted = [...resourceKeys].sort((a, b) => b.length - a.length);\n for (const resourceKey of sorted) {\n if (simulationKey === resourceKey || simulationKey.startsWith(resourceKey + '-')) {\n return resourceKey;\n }\n }\n return undefined;\n}\n\n/**\n * Get the expected component export name for a resource\n * @example getComponentName('review') // 'ReviewResource'\n * @example getComponentName('album-art') // 'AlbumArtResource'\n */\nexport function getComponentName(resourceKey: string): string {\n return `${toPascalCase(resourceKey)}Resource`;\n}\n\n// --- Glob processing helpers ---\n\ntype GlobModules = Record<string, unknown>;\n\n/**\n * Process resource component modules from import.meta.glob() result.\n * Extracts components and exports them with PascalCase names.\n *\n * @example\n * const modules = import.meta.glob('./*\\/*.tsx', { eager: true });\n * export default createResourceExports(modules);\n */\nexport function createResourceExports(modules: GlobModules): Record<string, React.ComponentType> {\n const resources: Record<string, React.ComponentType> = {};\n\n for (const [path, module] of Object.entries(modules)) {\n const key = extractResourceKey(path);\n if (!key) continue;\n\n const exportName = getComponentName(key);\n const mod = module as Record<string, unknown>;\n\n // Try default export first, then named export matching the expected name\n const component = mod.default ?? mod[exportName];\n\n // Accept functions (regular components) or objects (forwardRef/memo components)\n if (component && (typeof component === 'function' || typeof component === 'object')) {\n resources[exportName] = component as React.ComponentType;\n }\n }\n\n return resources;\n}\n\n/**\n * Build a resource metadata map from import.meta.glob() result.\n * Used for connecting simulations to their resource definitions.\n *\n * @example\n * const modules = import.meta.glob('../src/resources/*\\/*.tsx', { eager: true });\n * const resourcesMap = buildResourceMap(modules);\n */\nexport function buildResourceMap<T>(modules: GlobModules): Map<string, T> {\n const map = new Map<string, T>();\n\n for (const [path, module] of Object.entries(modules)) {\n const key = extractResourceKey(path);\n if (key) {\n map.set(key, (module as { resource: T }).resource);\n }\n }\n\n return map;\n}\n\n/**\n * Options for building simulations from discovered modules\n */\nexport interface BuildSimulationsOptions<TResource, TSimulation> {\n /** Glob result of simulation JSON files */\n simulationModules: GlobModules;\n /** Map of resource key -> resource metadata */\n resourcesMap: Map<string, TResource>;\n /** Map of component name -> React component */\n resourceComponents: Record<string, React.ComponentType>;\n /** Create the final simulation object */\n createSimulation: (\n simulationKey: string,\n simulationData: unknown,\n resource: TResource,\n resourceComponent: React.ComponentType\n ) => TSimulation;\n /** Optional warning handler for missing resources */\n onMissingResource?: (simulationKey: string, expectedPrefix: string) => void;\n}\n\n/**\n * Build simulations by connecting simulation data with resources and components.\n * This is the main orchestration function for dev server bootstrap.\n */\nexport function buildSimulations<TResource, TSimulation>(\n options: BuildSimulationsOptions<TResource, TSimulation>\n): Record<string, TSimulation> {\n const {\n simulationModules,\n resourcesMap,\n resourceComponents,\n createSimulation,\n onMissingResource = (key, prefix) =>\n console.warn(\n `No matching resource found for simulation \"${key}\". ` +\n `Expected a resource file like src/resources/${prefix}/${prefix}.tsx`\n ),\n } = options;\n\n const resourceKeys = Array.from(resourcesMap.keys());\n const simulations: Record<string, TSimulation> = {};\n\n for (const [path, module] of Object.entries(simulationModules)) {\n const simulationKey = extractSimulationKey(path);\n if (!simulationKey) continue;\n\n const simulationData = (module as { default: unknown }).default;\n\n // Find matching resource\n const resourceKey = findResourceKey(simulationKey, resourceKeys);\n if (!resourceKey) {\n onMissingResource(simulationKey, simulationKey.split('-')[0]);\n continue;\n }\n\n const resource = resourcesMap.get(resourceKey)!;\n\n // Get component\n const componentName = getComponentName(resourceKey);\n const resourceComponent = resourceComponents[componentName];\n\n if (!resourceComponent) {\n console.warn(\n `Resource component \"${componentName}\" not found for resource \"${resourceKey}\". ` +\n `Make sure src/resources/${resourceKey}/${resourceKey}.tsx exists with a default export.`\n );\n continue;\n }\n\n simulations[simulationKey] = createSimulation(\n simulationKey,\n simulationData,\n resource,\n resourceComponent\n );\n }\n\n return simulations;\n}\n\n// --- Dev server helpers ---\n\n/**\n * Resource metadata from resource .tsx files\n */\nexport interface ResourceMetadata {\n name: string;\n [key: string]: unknown;\n}\n\n/**\n * Options for building dev simulations\n */\nexport interface BuildDevSimulationsOptions {\n /** Glob result of simulation JSON files */\n simulationModules: GlobModules;\n /** Resource components map from src/resources/index.ts */\n resourceComponents: Record<string, React.ComponentType>;\n /** Glob result of tool files: import.meta.glob('src/tools/*.ts', { eager: true }) */\n toolModules: GlobModules;\n /** Glob result of resource .tsx files from src/resources/ */\n resourceModules: GlobModules;\n}\n\n/**\n * Tool metadata extracted from a tool module's `tool` export\n */\ninterface ToolModuleInfo {\n tool: Record<string, unknown>;\n /** Resource name string from tool.resource (undefined for tools without UI) */\n resourceName?: string;\n}\n\n/**\n * Build simulations for the dev server from glob results.\n * Simulation JSON has `\"tool\": \"tool-name\"` string referencing a tool file.\n * Tool files have `resource: 'name'` linking to a resource discovered from resourceModules.\n */\nexport function buildDevSimulations(\n options: BuildDevSimulationsOptions\n): Record<string, Simulation> {\n const { simulationModules, resourceComponents, toolModules, resourceModules } = options;\n\n // Build resource metadata map from resource modules (keyed by resource name)\n const resourceMetaByName = new Map<string, ResourceMetadata>();\n const resourceKeyByName = new Map<string, string>();\n for (const [path, module] of Object.entries(resourceModules)) {\n const key = extractResourceKey(path);\n if (!key) continue;\n const mod = module as { resource?: ResourceMetadata };\n if (mod.resource) {\n // Use explicit name if provided, otherwise derive from directory key\n const name = mod.resource.name ?? key;\n resourceMetaByName.set(name, { ...mod.resource, name });\n resourceKeyByName.set(name, key);\n }\n }\n\n // Build tool map from tool modules\n const toolsMap = new Map<string, ToolModuleInfo>();\n if (toolModules) {\n for (const [path, module] of Object.entries(toolModules)) {\n const nameMatch = path.match(/([^/]+)\\.ts$/);\n if (!nameMatch) continue;\n const mod = module as { tool?: Record<string, unknown> };\n if (mod.tool) {\n const resourceName = mod.tool.resource as string | undefined;\n toolsMap.set(nameMatch[1], { tool: mod.tool, resourceName });\n }\n }\n }\n\n const simulations: Record<string, Simulation> = {};\n\n for (const [path, module] of Object.entries(simulationModules)) {\n const simKey = extractSimulationKey(path);\n if (!simKey) continue;\n\n const simulationData = (module as { default: Record<string, unknown> }).default;\n\n const toolName =\n typeof simulationData.tool === 'string' ? (simulationData.tool as string) : simKey;\n const toolInfo = toolsMap.get(toolName);\n if (!toolInfo) {\n console.warn(\n `Tool \"${toolName}\" not found for simulation \"${simKey}\". ` +\n `Make sure src/tools/${toolName}.ts exists.`\n );\n continue;\n }\n\n // Look up resource metadata by name (if tool has a UI)\n const resourceMeta = toolInfo.resourceName\n ? resourceMetaByName.get(toolInfo.resourceName)\n : undefined;\n const resourceKey = toolInfo.resourceName\n ? resourceKeyByName.get(toolInfo.resourceName)\n : undefined;\n\n if (toolInfo.resourceName && (!resourceMeta || !resourceKey)) {\n console.warn(\n `Resource \"${toolInfo.resourceName}\" not found for tool \"${toolName}\". ` +\n `Make sure a resource with name \"${toolInfo.resourceName}\" exists in src/resources/.`\n );\n continue;\n }\n\n // Build resource block only for UI tools\n let resourceBlock: Pick<Simulation, 'resource' | 'resourceUrl'> = {};\n if (resourceKey && resourceMeta) {\n const componentName = getComponentName(resourceKey);\n const resourceComponent = resourceComponents[componentName];\n\n if (!resourceComponent) {\n console.warn(`Resource component \"${componentName}\" not found for tool \"${toolName}\".`);\n continue;\n }\n\n resourceBlock = {\n resource: {\n uri: `ui://${resourceKey}`,\n name: resourceKey,\n ...(resourceMeta.title != null ? { title: resourceMeta.title as string } : {}),\n ...(resourceMeta.description != null\n ? { description: resourceMeta.description as string }\n : {}),\n ...(resourceMeta.mimeType != null ? { mimeType: resourceMeta.mimeType as string } : {}),\n ...(resourceMeta._meta != null\n ? { _meta: resourceMeta._meta as Record<string, unknown> }\n : {}),\n },\n resourceUrl: `/.sunpeak/resource-loader.html?component=${componentName}`,\n };\n }\n\n simulations[simKey] = {\n name: simKey,\n userMessage: simulationData.userMessage as string | undefined,\n tool: {\n name: toolName,\n description: (toolInfo.tool.description as string) ?? '',\n inputSchema: { type: 'object' as const },\n ...(toolInfo.tool.title != null ? { title: toolInfo.tool.title as string } : {}),\n ...(toolInfo.tool.annotations != null\n ? { annotations: toolInfo.tool.annotations as Record<string, unknown> }\n : {}),\n ...(toolInfo.tool._meta != null\n ? { _meta: toolInfo.tool._meta as Record<string, unknown> }\n : {}),\n },\n ...resourceBlock,\n toolInput: simulationData.toolInput as Record<string, unknown> | undefined,\n toolResult: simulationData.toolResult as Simulation['toolResult'],\n serverTools: simulationData.serverTools as Simulation['serverTools'],\n };\n }\n\n return simulations;\n}\n\n// --- Node.js utilities for CLI commands ---\n// These utilities use standard Node.js APIs and can be imported by build/push/mcp commands.\n\n/**\n * Information about a discovered resource directory\n */\nexport interface ResourceDirInfo {\n /** Resource key (directory name), e.g., 'albums', 'carousel' */\n key: string;\n /** Full path to the resource directory */\n dir: string;\n /** Full path to the main resource file (tsx or json depending on context) */\n resourcePath: string;\n}\n\n/**\n * File system operations interface for dependency injection in tests\n */\nexport interface FsOps {\n readdirSync: (\n path: string,\n options: { withFileTypes: true }\n ) => Array<{ name: string; isDirectory: () => boolean }>;\n existsSync: (path: string) => boolean;\n}\n\n/**\n * Find all resource directories in a base directory.\n * Each valid resource directory contains a file matching the expected pattern.\n *\n * @param baseDir - Base directory to scan (e.g., 'src/resources' or 'dist')\n * @param filePattern - Function to generate expected filename from resource key\n * @param fs - File system operations (for testing)\n *\n * @example\n * // Find source resources (tsx files)\n * const resources = findResourceDirs('src/resources', key => `${key}.tsx`);\n *\n * @example\n * // Find built resources (js files)\n * const resources = findResourceDirs('dist', key => `${key}.js`);\n */\nexport function findResourceDirs(\n baseDir: string,\n filePattern: (key: string) => string,\n fs: FsOps\n): ResourceDirInfo[] {\n if (!fs.existsSync(baseDir)) {\n return [];\n }\n\n const entries = fs.readdirSync(baseDir, { withFileTypes: true });\n\n return entries\n .filter((entry) => entry.isDirectory())\n .map((entry) => {\n const key = entry.name;\n const dir = `${baseDir}/${key}`;\n const resourcePath = `${dir}/${filePattern(key)}`;\n\n if (!fs.existsSync(resourcePath)) {\n return null;\n }\n\n return { key, dir, resourcePath };\n })\n .filter((info): info is ResourceDirInfo => info !== null);\n}\n\n// --- Tool files + flat simulations discovery ---\n\n/**\n * Information about a discovered tool file\n */\nexport interface ToolFileInfo {\n /** Tool name derived from filename (e.g., 'show-albums') */\n name: string;\n /** Full path to the tool file */\n path: string;\n}\n\n/**\n * Find all tool files in a tools directory.\n * Matches *.ts files directly in the directory (not recursive).\n *\n * @example\n * findToolFiles('src/tools', fs)\n * // [{ name: 'show-albums', path: 'src/tools/show-albums.ts' }]\n */\nexport function findToolFiles(\n toolsDir: string,\n fs: Pick<FsOps, 'readdirSync' | 'existsSync'>\n): ToolFileInfo[] {\n if (!fs.existsSync(toolsDir)) {\n return [];\n }\n\n const entries = fs.readdirSync(toolsDir, { withFileTypes: true });\n\n return entries\n .filter(\n (entry) =>\n !entry.isDirectory() && entry.name.endsWith('.ts') && !entry.name.endsWith('.test.ts')\n )\n .map((entry) => ({\n name: entry.name.replace(/\\.ts$/, ''),\n path: `${toolsDir}/${entry.name}`,\n }));\n}\n\n/**\n * Information about a discovered simulation file (flat convention)\n */\nexport interface SimulationFileInfo {\n /** Filename without extension (e.g., 'show-albums') */\n name: string;\n /** Full path to the simulation file */\n path: string;\n}\n\n/**\n * Find all simulation JSON files in a flat simulations directory.\n * Matches any *.json file directly in the directory.\n *\n * @example\n * findSimulationFilesFlat('tests/simulations', fs)\n * // [{ name: 'show-albums', path: 'tests/simulations/show-albums.json' }]\n */\nexport function findSimulationFilesFlat(\n simulationsDir: string,\n fs: Pick<FsOps, 'readdirSync' | 'existsSync'>\n): SimulationFileInfo[] {\n if (!fs.existsSync(simulationsDir)) {\n return [];\n }\n\n const entries = fs.readdirSync(simulationsDir, { withFileTypes: true });\n\n return entries\n .filter((entry) => !entry.isDirectory() && entry.name.endsWith('.json'))\n .map((entry) => ({\n name: entry.name.replace(/\\.json$/, ''),\n path: `${simulationsDir}/${entry.name}`,\n }));\n}\n"],"mappings":";;;;;;AAoBA,SAAgB,aAAa,KAAqB;AAChD,QAAO,IACJ,MAAM,IAAI,CACV,KAAK,SAAS,KAAK,OAAO,EAAE,CAAC,aAAa,GAAG,KAAK,MAAM,EAAE,CAAC,CAC3D,KAAK,GAAG;;;;;;AAOb,SAAgB,mBAAmB,MAAkC;CACnE,MAAM,QAAQ,KAAK,MAAM,gBAAgB;AACzC,QAAO,QAAQ,MAAM,KAAK,KAAA;;;;;;AAO5B,SAAgB,qBAAqB,MAAkC;CACrE,MAAM,QAAQ,KAAK,MAAM,iBAAiB;AAC1C,QAAO,QAAQ,MAAM,KAAK,KAAA;;;;;;;;AAS5B,SAAgB,gBAAgB,eAAuB,cAA4C;CAEjG,MAAM,SAAS,CAAC,GAAG,aAAa,CAAC,MAAM,GAAG,MAAM,EAAE,SAAS,EAAE,OAAO;AACpE,MAAK,MAAM,eAAe,OACxB,KAAI,kBAAkB,eAAe,cAAc,WAAW,cAAc,IAAI,CAC9E,QAAO;;;;;;;AAWb,SAAgB,iBAAiB,aAA6B;AAC5D,QAAO,GAAG,aAAa,YAAY,CAAC;;;;;;;;;;AAetC,SAAgB,sBAAsB,SAA2D;CAC/F,MAAM,YAAiD,EAAE;AAEzD,MAAK,MAAM,CAAC,MAAM,WAAW,OAAO,QAAQ,QAAQ,EAAE;EACpD,MAAM,MAAM,mBAAmB,KAAK;AACpC,MAAI,CAAC,IAAK;EAEV,MAAM,aAAa,iBAAiB,IAAI;EACxC,MAAM,MAAM;EAGZ,MAAM,YAAY,IAAI,WAAW,IAAI;AAGrC,MAAI,cAAc,OAAO,cAAc,cAAc,OAAO,cAAc,UACxE,WAAU,cAAc;;AAI5B,QAAO;;;;;;;;;;AAWT,SAAgB,iBAAoB,SAA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GAAG,IAAI,GAAG,YAAY,IAAI;AAE/C,MAAI,CAAC,GAAG,WAAW,aAAa,CAC9B,QAAO;AAGT,SAAO;GAAE;GAAK;GAAK;GAAc;GACjC,CACD,QAAQ,SAAkC,SAAS,KAAK;;;;;;;;;;AAuB7D,SAAgB,cACd,UACA,IACgB;AAChB,KAAI,CAAC,GAAG,WAAW,SAAS,CAC1B,QAAO,EAAE;AAKX,QAFgB,GAAG,YAAY,UAAU,EAAE,eAAe,MAAM,CAAC,CAG9D,QACE,UACC,CAAC,MAAM,aAAa,IAAI,MAAM,KAAK,SAAS,MAAM,IAAI,CAAC,MAAM,KAAK,SAAS,WAAW,CACzF,CACA,KAAK,WAAW;EACf,MAAM,MAAM,KAAK,QAAQ,SAAS,GAAG;EACrC,MAAM,GAAG,SAAS,GAAG,MAAM;EAC5B,EAAE;;;;;;;;;;AAqBP,SAAgB,wBACd,gBACA,IACsB;AACtB,KAAI,CAAC,GAAG,WAAW,eAAe,CAChC,QAAO,EAAE;AAKX,QAFgB,GAAG,YAAY,gBAAgB,EAAE,eAAe,MAAM,CAAC,CAGpE,QAAQ,UAAU,CAAC,MAAM,aAAa,IAAI,MAAM,KAAK,SAAS,QAAQ,CAAC,CACvE,KAAK,WAAW;EACf,MAAM,MAAM,KAAK,QAAQ,WAAW,GAAG;EACvC,MAAM,GAAG,eAAe,GAAG,MAAM;EAClC,EAAE"}
@@ -1,81 +1,187 @@
1
- "use strict";
2
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
- const React = require("react");
4
- const useApp = require("../../use-app-D09O2swh.cjs");
2
+ require("../../chunk-9hOWP6kD.cjs");
3
+ require("../../protocol-jbxhzcnS.cjs");
4
+ const require_use_app = require("../../use-app-D2h-aiyr.cjs");
5
+ let react = require("react");
6
+ //#region src/host/chatgpt/openai-types.ts
7
+ /**
8
+ * Get the `window.openai` runtime if available.
9
+ * Returns `undefined` outside of ChatGPT or in SSR.
10
+ */
5
11
  function getOpenAIRuntime() {
6
- if (typeof window !== "undefined" && "openai" in window) {
7
- return window.openai;
8
- }
9
- return void 0;
12
+ if (typeof window !== "undefined" && "openai" in window) return window.openai;
10
13
  }
14
+ //#endregion
15
+ //#region src/host/chatgpt/use-create-file.ts
16
+ /**
17
+ * Upload a file from the app UI into the ChatGPT conversation.
18
+ *
19
+ * Wraps `window.openai.uploadFile` which is only available inside ChatGPT.
20
+ * Supported formats: `image/png`, `image/jpeg`, `image/webp`.
21
+ *
22
+ * Import from `sunpeak/host/chatgpt`:
23
+ *
24
+ * @example
25
+ * ```tsx
26
+ * import { useUploadFile } from 'sunpeak/host/chatgpt';
27
+ *
28
+ * function ImageUploader() {
29
+ * const uploadFile = useUploadFile();
30
+ *
31
+ * const handleChange = async (e: React.ChangeEvent<HTMLInputElement>) => {
32
+ * const file = e.currentTarget.files?.[0];
33
+ * if (!file) return;
34
+ * const { fileId } = await uploadFile(file);
35
+ * console.log('Uploaded:', fileId);
36
+ * };
37
+ *
38
+ * return <input type="file" accept="image/*" onChange={handleChange} />;
39
+ * }
40
+ * ```
41
+ */
11
42
  function useUploadFile() {
12
- const app = useApp.useApp();
13
- return React.useCallback(
14
- async (file) => {
15
- if (!app) {
16
- throw new Error("[useUploadFile] App not connected");
17
- }
18
- const runtime = getOpenAIRuntime();
19
- if (!runtime?.uploadFile) {
20
- throw new Error("[useUploadFile] window.openai.uploadFile not available");
21
- }
22
- return runtime.uploadFile(file);
23
- },
24
- [app]
25
- );
43
+ const app = require_use_app.useApp();
44
+ return (0, react.useCallback)(async (file) => {
45
+ if (!app) throw new Error("[useUploadFile] App not connected");
46
+ const runtime = getOpenAIRuntime();
47
+ if (!runtime?.uploadFile) throw new Error("[useUploadFile] window.openai.uploadFile not available");
48
+ return runtime.uploadFile(file);
49
+ }, [app]);
26
50
  }
51
+ //#endregion
52
+ //#region src/host/chatgpt/use-file-download.ts
53
+ /**
54
+ * Get a temporary download URL for a file by its ID.
55
+ *
56
+ * @deprecated Use {@link useDownloadFile} from `sunpeak` instead — it works
57
+ * across all hosts via the MCP Apps SDK `app.downloadFile()` method.
58
+ *
59
+ * Wraps `window.openai.getFileDownloadUrl` which is only available inside
60
+ * ChatGPT. Use this to retrieve URLs for files uploaded via {@link useUploadFile}
61
+ * or file IDs received in tool parameters.
62
+ *
63
+ * Import from `sunpeak/host/chatgpt`:
64
+ *
65
+ * @example
66
+ * ```tsx
67
+ * import { useGetFileDownloadUrl } from 'sunpeak/host/chatgpt';
68
+ *
69
+ * function FilePreview({ fileId }: { fileId: string }) {
70
+ * const getFileDownloadUrl = useGetFileDownloadUrl();
71
+ * const [src, setSrc] = useState<string>();
72
+ *
73
+ * useEffect(() => {
74
+ * getFileDownloadUrl({ fileId }).then(({ downloadUrl }) => setSrc(downloadUrl));
75
+ * }, [fileId, getFileDownloadUrl]);
76
+ *
77
+ * return src ? <img src={src} /> : <p>Loading...</p>;
78
+ * }
79
+ * ```
80
+ */
27
81
  function useGetFileDownloadUrl() {
28
- const app = useApp.useApp();
29
- return React.useCallback(
30
- async (params) => {
31
- if (!app) {
32
- throw new Error("[useGetFileDownloadUrl] App not connected");
33
- }
34
- const runtime = getOpenAIRuntime();
35
- if (!runtime?.getFileDownloadUrl) {
36
- throw new Error("[useGetFileDownloadUrl] window.openai.getFileDownloadUrl not available");
37
- }
38
- return runtime.getFileDownloadUrl(params);
39
- },
40
- [app]
41
- );
82
+ const app = require_use_app.useApp();
83
+ return (0, react.useCallback)(async (params) => {
84
+ if (!app) throw new Error("[useGetFileDownloadUrl] App not connected");
85
+ const runtime = getOpenAIRuntime();
86
+ if (!runtime?.getFileDownloadUrl) throw new Error("[useGetFileDownloadUrl] window.openai.getFileDownloadUrl not available");
87
+ return runtime.getFileDownloadUrl(params);
88
+ }, [app]);
42
89
  }
90
+ //#endregion
91
+ //#region src/host/chatgpt/use-open-modal.ts
92
+ /**
93
+ * Open a host-controlled modal in ChatGPT.
94
+ *
95
+ * Wraps `window.openai.requestModal` which is only available inside ChatGPT.
96
+ * Pass a `template` URL to load alternate UI content in the modal, or omit
97
+ * it to reuse the current UI.
98
+ *
99
+ * Import from `sunpeak/host/chatgpt`:
100
+ *
101
+ * @example
102
+ * ```tsx
103
+ * import { useRequestModal } from 'sunpeak/host/chatgpt';
104
+ *
105
+ * function CheckoutButton() {
106
+ * const requestModal = useRequestModal();
107
+ *
108
+ * return (
109
+ * <button onClick={() => requestModal({ template: 'ui://widget/checkout.html' })}>
110
+ * Checkout
111
+ * </button>
112
+ * );
113
+ * }
114
+ * ```
115
+ */
43
116
  function useRequestModal() {
44
- const app = useApp.useApp();
45
- return React.useCallback(
46
- async (params) => {
47
- if (!app) {
48
- console.warn("[useRequestModal] App not connected");
49
- return;
50
- }
51
- const runtime = getOpenAIRuntime();
52
- if (!runtime?.requestModal) {
53
- throw new Error("[useRequestModal] window.openai.requestModal not available");
54
- }
55
- return runtime.requestModal(params);
56
- },
57
- [app]
58
- );
117
+ const app = require_use_app.useApp();
118
+ return (0, react.useCallback)(async (params) => {
119
+ if (!app) {
120
+ console.warn("[useRequestModal] App not connected");
121
+ return;
122
+ }
123
+ const runtime = getOpenAIRuntime();
124
+ if (!runtime?.requestModal) throw new Error("[useRequestModal] window.openai.requestModal not available");
125
+ return runtime.requestModal(params);
126
+ }, [app]);
59
127
  }
128
+ //#endregion
129
+ //#region src/host/chatgpt/use-request-checkout.ts
130
+ /**
131
+ * Trigger the ChatGPT instant checkout flow.
132
+ *
133
+ * Wraps `window.openai.requestCheckout` which is only available inside
134
+ * ChatGPT. Opens the host checkout UI, handles payment display, and
135
+ * resolves with the finalized order. Rejects on error or user cancel.
136
+ *
137
+ * Import from `sunpeak/host/chatgpt`:
138
+ *
139
+ * @example
140
+ * ```tsx
141
+ * import { useRequestCheckout } from 'sunpeak/host/chatgpt';
142
+ *
143
+ * function BuyButton() {
144
+ * const requestCheckout = useRequestCheckout();
145
+ *
146
+ * const handleBuy = async () => {
147
+ * try {
148
+ * const order = await requestCheckout({
149
+ * id: 'session-1',
150
+ * payment_provider: {
151
+ * provider: 'stripe',
152
+ * merchant_id: 'acct_xxx',
153
+ * supported_payment_methods: ['card', 'apple_pay'],
154
+ * },
155
+ * status: 'ready_for_payment',
156
+ * currency: 'USD',
157
+ * totals: [{ type: 'total', display_text: 'Total', amount: 999 }],
158
+ * links: [],
159
+ * payment_mode: 'live',
160
+ * });
161
+ * console.log('Order completed:', order.id);
162
+ * } catch {
163
+ * console.log('Checkout cancelled or failed');
164
+ * }
165
+ * };
166
+ *
167
+ * return <button onClick={handleBuy}>Buy Now</button>;
168
+ * }
169
+ * ```
170
+ */
60
171
  function useRequestCheckout() {
61
- const app = useApp.useApp();
62
- return React.useCallback(
63
- async (session) => {
64
- if (!app) {
65
- throw new Error("[useRequestCheckout] App not connected");
66
- }
67
- const runtime = getOpenAIRuntime();
68
- if (!runtime?.requestCheckout) {
69
- throw new Error("[useRequestCheckout] window.openai.requestCheckout not available");
70
- }
71
- return runtime.requestCheckout(session);
72
- },
73
- [app]
74
- );
172
+ const app = require_use_app.useApp();
173
+ return (0, react.useCallback)(async (session) => {
174
+ if (!app) throw new Error("[useRequestCheckout] App not connected");
175
+ const runtime = getOpenAIRuntime();
176
+ if (!runtime?.requestCheckout) throw new Error("[useRequestCheckout] window.openai.requestCheckout not available");
177
+ return runtime.requestCheckout(session);
178
+ }, [app]);
75
179
  }
180
+ //#endregion
76
181
  exports.getOpenAIRuntime = getOpenAIRuntime;
77
182
  exports.useGetFileDownloadUrl = useGetFileDownloadUrl;
78
183
  exports.useRequestCheckout = useRequestCheckout;
79
184
  exports.useRequestModal = useRequestModal;
80
185
  exports.useUploadFile = useUploadFile;
81
- //# sourceMappingURL=index.cjs.map
186
+
187
+ //# sourceMappingURL=index.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","sources":["../../../src/host/chatgpt/openai-types.ts","../../../src/host/chatgpt/use-create-file.ts","../../../src/host/chatgpt/use-file-download.ts","../../../src/host/chatgpt/use-open-modal.ts","../../../src/host/chatgpt/use-request-checkout.ts"],"sourcesContent":["/**\n * TypeScript declarations for the `window.openai` ChatGPT runtime.\n *\n * These APIs are available inside ChatGPT-hosted iframes and provide\n * platform-specific capabilities beyond the MCP Apps standard.\n *\n * @see https://developers.openai.com/apps-sdk/mcp-apps-in-chatgpt\n */\n\nexport interface OpenAIUploadFileResult {\n fileId: string;\n}\n\nexport interface OpenAIFileDownloadUrlResult {\n downloadUrl: string;\n}\n\nexport interface OpenAIRequestModalParams {\n /** URL of an alternate UI template to load in the modal. Omit to reuse the current UI. */\n template?: string;\n /** Arbitrary params forwarded to the modal content. */\n params?: Record<string, unknown>;\n}\n\nexport interface OpenAICheckoutPaymentProvider {\n provider: string;\n merchant_id: string;\n supported_payment_methods: string[];\n}\n\nexport interface OpenAICheckoutTotal {\n type: string;\n display_text: string;\n amount: number;\n}\n\nexport interface OpenAICheckoutLink {\n type: 'terms_of_use' | 'privacy_policy' | string;\n url: string;\n}\n\nexport interface OpenAICheckoutSession {\n id: string;\n payment_provider: OpenAICheckoutPaymentProvider;\n status: 'ready_for_payment';\n currency: string;\n totals: OpenAICheckoutTotal[];\n links: OpenAICheckoutLink[];\n payment_mode: 'live' | 'test';\n}\n\nexport interface OpenAICheckoutOrder {\n id: string;\n checkout_session_id: string;\n status: 'completed' | string;\n permalink_url?: string;\n}\n\n/**\n * The `window.openai` runtime object injected by ChatGPT into hosted iframes.\n */\nexport interface OpenAIRuntime {\n // --- File APIs ---\n uploadFile?(file: File): Promise<OpenAIUploadFileResult>;\n getFileDownloadUrl?(params: { fileId: string }): Promise<OpenAIFileDownloadUrlResult>;\n\n // --- Modal API ---\n requestModal?(params: OpenAIRequestModalParams): Promise<void>;\n\n // --- Checkout API ---\n requestCheckout?(session: OpenAICheckoutSession): Promise<OpenAICheckoutOrder>;\n\n // --- Display ---\n requestClose?(): void;\n requestDisplayMode?(params: { mode: 'inline' | 'PiP' | 'fullscreen' }): Promise<void>;\n\n // --- Messaging ---\n sendFollowUpMessage?(params: { prompt: string }): void;\n\n // --- Other ---\n openExternal?(params: { href: string }): void;\n}\n\n/**\n * Get the `window.openai` runtime if available.\n * Returns `undefined` outside of ChatGPT or in SSR.\n */\nexport function getOpenAIRuntime(): OpenAIRuntime | undefined {\n if (typeof window !== 'undefined' && 'openai' in window) {\n return (window as unknown as { openai: OpenAIRuntime }).openai;\n }\n return undefined;\n}\n","import { useCallback } from 'react';\nimport { useApp } from '../../hooks/use-app';\nimport { getOpenAIRuntime, type OpenAIUploadFileResult } from './openai-types';\n\nexport type { OpenAIUploadFileResult as CreateFileResult };\n\n/**\n * Upload a file from the app UI into the ChatGPT conversation.\n *\n * Wraps `window.openai.uploadFile` which is only available inside ChatGPT.\n * Supported formats: `image/png`, `image/jpeg`, `image/webp`.\n *\n * Import from `sunpeak/host/chatgpt`:\n *\n * @example\n * ```tsx\n * import { useUploadFile } from 'sunpeak/host/chatgpt';\n *\n * function ImageUploader() {\n * const uploadFile = useUploadFile();\n *\n * const handleChange = async (e: React.ChangeEvent<HTMLInputElement>) => {\n * const file = e.currentTarget.files?.[0];\n * if (!file) return;\n * const { fileId } = await uploadFile(file);\n * console.log('Uploaded:', fileId);\n * };\n *\n * return <input type=\"file\" accept=\"image/*\" onChange={handleChange} />;\n * }\n * ```\n */\nexport function useUploadFile(): (file: File) => Promise<OpenAIUploadFileResult> {\n const app = useApp();\n return useCallback(\n async (file: File) => {\n if (!app) {\n throw new Error('[useUploadFile] App not connected');\n }\n const runtime = getOpenAIRuntime();\n if (!runtime?.uploadFile) {\n throw new Error('[useUploadFile] window.openai.uploadFile not available');\n }\n return runtime.uploadFile(file);\n },\n [app]\n );\n}\n","import { useCallback } from 'react';\nimport { useApp } from '../../hooks/use-app';\nimport { getOpenAIRuntime, type OpenAIFileDownloadUrlResult } from './openai-types';\n\nexport type { OpenAIFileDownloadUrlResult as FileDownloadUrlResult };\n\n/**\n * Get a temporary download URL for a file by its ID.\n *\n * @deprecated Use {@link useDownloadFile} from `sunpeak` instead — it works\n * across all hosts via the MCP Apps SDK `app.downloadFile()` method.\n *\n * Wraps `window.openai.getFileDownloadUrl` which is only available inside\n * ChatGPT. Use this to retrieve URLs for files uploaded via {@link useUploadFile}\n * or file IDs received in tool parameters.\n *\n * Import from `sunpeak/host/chatgpt`:\n *\n * @example\n * ```tsx\n * import { useGetFileDownloadUrl } from 'sunpeak/host/chatgpt';\n *\n * function FilePreview({ fileId }: { fileId: string }) {\n * const getFileDownloadUrl = useGetFileDownloadUrl();\n * const [src, setSrc] = useState<string>();\n *\n * useEffect(() => {\n * getFileDownloadUrl({ fileId }).then(({ downloadUrl }) => setSrc(downloadUrl));\n * }, [fileId, getFileDownloadUrl]);\n *\n * return src ? <img src={src} /> : <p>Loading...</p>;\n * }\n * ```\n */\nexport function useGetFileDownloadUrl(): (params: {\n fileId: string;\n}) => Promise<OpenAIFileDownloadUrlResult> {\n const app = useApp();\n return useCallback(\n async (params: { fileId: string }) => {\n if (!app) {\n throw new Error('[useGetFileDownloadUrl] App not connected');\n }\n const runtime = getOpenAIRuntime();\n if (!runtime?.getFileDownloadUrl) {\n throw new Error('[useGetFileDownloadUrl] window.openai.getFileDownloadUrl not available');\n }\n return runtime.getFileDownloadUrl(params);\n },\n [app]\n );\n}\n","import { useCallback } from 'react';\nimport { useApp } from '../../hooks/use-app';\nimport { getOpenAIRuntime, type OpenAIRequestModalParams } from './openai-types';\n\nexport type { OpenAIRequestModalParams as OpenModalParams };\n\n/**\n * Open a host-controlled modal in ChatGPT.\n *\n * Wraps `window.openai.requestModal` which is only available inside ChatGPT.\n * Pass a `template` URL to load alternate UI content in the modal, or omit\n * it to reuse the current UI.\n *\n * Import from `sunpeak/host/chatgpt`:\n *\n * @example\n * ```tsx\n * import { useRequestModal } from 'sunpeak/host/chatgpt';\n *\n * function CheckoutButton() {\n * const requestModal = useRequestModal();\n *\n * return (\n * <button onClick={() => requestModal({ template: 'ui://widget/checkout.html' })}>\n * Checkout\n * </button>\n * );\n * }\n * ```\n */\nexport function useRequestModal(): (params: OpenAIRequestModalParams) => Promise<void> {\n const app = useApp();\n return useCallback(\n async (params: OpenAIRequestModalParams) => {\n if (!app) {\n console.warn('[useRequestModal] App not connected');\n return;\n }\n const runtime = getOpenAIRuntime();\n if (!runtime?.requestModal) {\n throw new Error('[useRequestModal] window.openai.requestModal not available');\n }\n return runtime.requestModal(params);\n },\n [app]\n );\n}\n","import { useCallback } from 'react';\nimport { useApp } from '../../hooks/use-app';\nimport {\n getOpenAIRuntime,\n type OpenAICheckoutSession,\n type OpenAICheckoutOrder,\n} from './openai-types';\n\nexport type { OpenAICheckoutSession as CheckoutSession };\nexport type { OpenAICheckoutOrder as CheckoutOrder };\n\n/**\n * Trigger the ChatGPT instant checkout flow.\n *\n * Wraps `window.openai.requestCheckout` which is only available inside\n * ChatGPT. Opens the host checkout UI, handles payment display, and\n * resolves with the finalized order. Rejects on error or user cancel.\n *\n * Import from `sunpeak/host/chatgpt`:\n *\n * @example\n * ```tsx\n * import { useRequestCheckout } from 'sunpeak/host/chatgpt';\n *\n * function BuyButton() {\n * const requestCheckout = useRequestCheckout();\n *\n * const handleBuy = async () => {\n * try {\n * const order = await requestCheckout({\n * id: 'session-1',\n * payment_provider: {\n * provider: 'stripe',\n * merchant_id: 'acct_xxx',\n * supported_payment_methods: ['card', 'apple_pay'],\n * },\n * status: 'ready_for_payment',\n * currency: 'USD',\n * totals: [{ type: 'total', display_text: 'Total', amount: 999 }],\n * links: [],\n * payment_mode: 'live',\n * });\n * console.log('Order completed:', order.id);\n * } catch {\n * console.log('Checkout cancelled or failed');\n * }\n * };\n *\n * return <button onClick={handleBuy}>Buy Now</button>;\n * }\n * ```\n */\nexport function useRequestCheckout(): (\n session: OpenAICheckoutSession\n) => Promise<OpenAICheckoutOrder> {\n const app = useApp();\n return useCallback(\n async (session: OpenAICheckoutSession) => {\n if (!app) {\n throw new Error('[useRequestCheckout] App not connected');\n }\n const runtime = getOpenAIRuntime();\n if (!runtime?.requestCheckout) {\n throw new Error('[useRequestCheckout] window.openai.requestCheckout not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AA,EAAA;AAER;ACMO,SAAS,qBAEkB;AAChC,QAAM,MAAMD,OAAAA,OAAA;AACZ,SAAOC,MAAAA;AAAAA,IACL,OAAO,YAAmC;AACxC,UAAI,CAAC,KAAK;AACR,cAAM,IAAI,MAAM,wCAAwC;AAAA,MAC1D;AACA,YAAM,UAAU,iBAAA;AAChB,UAAI,CAAC,SAAS,iBAAiB;AAC7B,cAAM,IAAI,MAAM,kEAAkE;AAAA,MACpF;AACA,aAAO,QAAQ,gBAAgB,OAAO;AAAA,IACxC;AAAA,IACA,CAAC,GAAG;AAAA,EAAA;AAER;;;;;;"}
1
+ {"version":3,"file":"index.cjs","names":[],"sources":["../../../src/host/chatgpt/openai-types.ts","../../../src/host/chatgpt/use-create-file.ts","../../../src/host/chatgpt/use-file-download.ts","../../../src/host/chatgpt/use-open-modal.ts","../../../src/host/chatgpt/use-request-checkout.ts"],"sourcesContent":["/**\n * TypeScript declarations for the `window.openai` ChatGPT runtime.\n *\n * These APIs are available inside ChatGPT-hosted iframes and provide\n * platform-specific capabilities beyond the MCP Apps standard.\n *\n * @see https://developers.openai.com/apps-sdk/mcp-apps-in-chatgpt\n */\n\nexport interface OpenAIUploadFileResult {\n fileId: string;\n}\n\nexport interface OpenAIFileDownloadUrlResult {\n downloadUrl: string;\n}\n\nexport interface OpenAIRequestModalParams {\n /** URL of an alternate UI template to load in the modal. Omit to reuse the current UI. */\n template?: string;\n /** Arbitrary params forwarded to the modal content. */\n params?: Record<string, unknown>;\n}\n\nexport interface OpenAICheckoutPaymentProvider {\n provider: string;\n merchant_id: string;\n supported_payment_methods: string[];\n}\n\nexport interface OpenAICheckoutTotal {\n type: string;\n display_text: string;\n amount: number;\n}\n\nexport interface OpenAICheckoutLink {\n type: 'terms_of_use' | 'privacy_policy' | string;\n url: string;\n}\n\nexport interface OpenAICheckoutSession {\n id: string;\n payment_provider: OpenAICheckoutPaymentProvider;\n status: 'ready_for_payment';\n currency: string;\n totals: OpenAICheckoutTotal[];\n links: OpenAICheckoutLink[];\n payment_mode: 'live' | 'test';\n}\n\nexport interface OpenAICheckoutOrder {\n id: string;\n checkout_session_id: string;\n status: 'completed' | string;\n permalink_url?: string;\n}\n\n/**\n * The `window.openai` runtime object injected by ChatGPT into hosted iframes.\n */\nexport interface OpenAIRuntime {\n // --- File APIs ---\n uploadFile?(file: File): Promise<OpenAIUploadFileResult>;\n getFileDownloadUrl?(params: { fileId: string }): Promise<OpenAIFileDownloadUrlResult>;\n\n // --- Modal API ---\n requestModal?(params: OpenAIRequestModalParams): Promise<void>;\n\n // --- Checkout API ---\n requestCheckout?(session: OpenAICheckoutSession): Promise<OpenAICheckoutOrder>;\n\n // --- Display ---\n requestClose?(): void;\n requestDisplayMode?(params: { mode: 'inline' | 'PiP' | 'fullscreen' }): Promise<void>;\n\n // --- Messaging ---\n sendFollowUpMessage?(params: { prompt: string }): void;\n\n // --- Other ---\n openExternal?(params: { href: string }): void;\n}\n\n/**\n * Get the `window.openai` runtime if available.\n * Returns `undefined` outside of ChatGPT or in SSR.\n */\nexport function getOpenAIRuntime(): OpenAIRuntime | undefined {\n if (typeof window !== 'undefined' && 'openai' in window) {\n return (window as unknown as { openai: OpenAIRuntime }).openai;\n }\n return undefined;\n}\n","import { useCallback } from 'react';\nimport { useApp } from '../../hooks/use-app';\nimport { getOpenAIRuntime, type OpenAIUploadFileResult } from './openai-types';\n\nexport type { OpenAIUploadFileResult as CreateFileResult };\n\n/**\n * Upload a file from the app UI into the ChatGPT conversation.\n *\n * Wraps `window.openai.uploadFile` which is only available inside ChatGPT.\n * Supported formats: `image/png`, `image/jpeg`, `image/webp`.\n *\n * Import from `sunpeak/host/chatgpt`:\n *\n * @example\n * ```tsx\n * import { useUploadFile } from 'sunpeak/host/chatgpt';\n *\n * function ImageUploader() {\n * const uploadFile = useUploadFile();\n *\n * const handleChange = async (e: React.ChangeEvent<HTMLInputElement>) => {\n * const file = e.currentTarget.files?.[0];\n * if (!file) return;\n * const { fileId } = await uploadFile(file);\n * console.log('Uploaded:', fileId);\n * };\n *\n * return <input type=\"file\" accept=\"image/*\" onChange={handleChange} />;\n * }\n * ```\n */\nexport function useUploadFile(): (file: File) => Promise<OpenAIUploadFileResult> {\n const app = useApp();\n return useCallback(\n async (file: File) => {\n if (!app) {\n throw new Error('[useUploadFile] App not connected');\n }\n const runtime = getOpenAIRuntime();\n if (!runtime?.uploadFile) {\n throw new Error('[useUploadFile] window.openai.uploadFile not available');\n }\n return runtime.uploadFile(file);\n },\n [app]\n );\n}\n","import { useCallback } from 'react';\nimport { useApp } from '../../hooks/use-app';\nimport { getOpenAIRuntime, type OpenAIFileDownloadUrlResult } from './openai-types';\n\nexport type { OpenAIFileDownloadUrlResult as FileDownloadUrlResult };\n\n/**\n * Get a temporary download URL for a file by its ID.\n *\n * @deprecated Use {@link useDownloadFile} from `sunpeak` instead — it works\n * across all hosts via the MCP Apps SDK `app.downloadFile()` method.\n *\n * Wraps `window.openai.getFileDownloadUrl` which is only available inside\n * ChatGPT. Use this to retrieve URLs for files uploaded via {@link useUploadFile}\n * or file IDs received in tool parameters.\n *\n * Import from `sunpeak/host/chatgpt`:\n *\n * @example\n * ```tsx\n * import { useGetFileDownloadUrl } from 'sunpeak/host/chatgpt';\n *\n * function FilePreview({ fileId }: { fileId: string }) {\n * const getFileDownloadUrl = useGetFileDownloadUrl();\n * const [src, setSrc] = useState<string>();\n *\n * useEffect(() => {\n * getFileDownloadUrl({ fileId }).then(({ downloadUrl }) => setSrc(downloadUrl));\n * }, [fileId, getFileDownloadUrl]);\n *\n * return src ? <img src={src} /> : <p>Loading...</p>;\n * }\n * ```\n */\nexport function useGetFileDownloadUrl(): (params: {\n fileId: string;\n}) => Promise<OpenAIFileDownloadUrlResult> {\n const app = useApp();\n return useCallback(\n async (params: { fileId: string }) => {\n if (!app) {\n throw new Error('[useGetFileDownloadUrl] App not connected');\n }\n const runtime = getOpenAIRuntime();\n if (!runtime?.getFileDownloadUrl) {\n throw new Error('[useGetFileDownloadUrl] window.openai.getFileDownloadUrl not available');\n }\n return runtime.getFileDownloadUrl(params);\n },\n [app]\n );\n}\n","import { useCallback } from 'react';\nimport { useApp } from '../../hooks/use-app';\nimport { getOpenAIRuntime, type OpenAIRequestModalParams } from './openai-types';\n\nexport type { OpenAIRequestModalParams as OpenModalParams };\n\n/**\n * Open a host-controlled modal in ChatGPT.\n *\n * Wraps `window.openai.requestModal` which is only available inside ChatGPT.\n * Pass a `template` URL to load alternate UI content in the modal, or omit\n * it to reuse the current UI.\n *\n * Import from `sunpeak/host/chatgpt`:\n *\n * @example\n * ```tsx\n * import { useRequestModal } from 'sunpeak/host/chatgpt';\n *\n * function CheckoutButton() {\n * const requestModal = useRequestModal();\n *\n * return (\n * <button onClick={() => requestModal({ template: 'ui://widget/checkout.html' })}>\n * Checkout\n * </button>\n * );\n * }\n * ```\n */\nexport function useRequestModal(): (params: OpenAIRequestModalParams) => Promise<void> {\n const app = useApp();\n return useCallback(\n async (params: OpenAIRequestModalParams) => {\n if (!app) {\n console.warn('[useRequestModal] App not connected');\n return;\n }\n const runtime = getOpenAIRuntime();\n if (!runtime?.requestModal) {\n throw new Error('[useRequestModal] window.openai.requestModal not available');\n }\n return runtime.requestModal(params);\n },\n [app]\n );\n}\n","import { useCallback } from 'react';\nimport { useApp } from '../../hooks/use-app';\nimport {\n getOpenAIRuntime,\n type OpenAICheckoutSession,\n type OpenAICheckoutOrder,\n} from './openai-types';\n\nexport type { OpenAICheckoutSession as CheckoutSession };\nexport type { OpenAICheckoutOrder as CheckoutOrder };\n\n/**\n * Trigger the ChatGPT instant checkout flow.\n *\n * Wraps `window.openai.requestCheckout` which is only available inside\n * ChatGPT. Opens the host checkout UI, handles payment display, and\n * resolves with the finalized order. Rejects on error or user cancel.\n *\n * Import from `sunpeak/host/chatgpt`:\n *\n * @example\n * ```tsx\n * import { useRequestCheckout } from 'sunpeak/host/chatgpt';\n *\n * function BuyButton() {\n * const requestCheckout = useRequestCheckout();\n *\n * const handleBuy = async () => {\n * try {\n * const order = await requestCheckout({\n * id: 'session-1',\n * payment_provider: {\n * provider: 'stripe',\n * merchant_id: 'acct_xxx',\n * supported_payment_methods: ['card', 'apple_pay'],\n * },\n * status: 'ready_for_payment',\n * currency: 'USD',\n * totals: [{ type: 'total', display_text: 'Total', amount: 999 }],\n * links: [],\n * payment_mode: 'live',\n * });\n * console.log('Order completed:', order.id);\n * } catch {\n * console.log('Checkout cancelled or failed');\n * }\n * };\n *\n * return <button onClick={handleBuy}>Buy Now</button>;\n * }\n * ```\n */\nexport function useRequestCheckout(): (\n session: OpenAICheckoutSession\n) => Promise<OpenAICheckoutOrder> {\n const app = useApp();\n return useCallback(\n async (session: OpenAICheckoutSession) => {\n if (!app) {\n throw new Error('[useRequestCheckout] App not connected');\n }\n const runtime = getOpenAIRuntime();\n if (!runtime?.requestCheckout) {\n throw new Error('[useRequestCheckout] window.openai.requestCheckout not available');\n }\n return runtime.requestCheckout(session);\n },\n [app]\n );\n}\n"],"mappings":";;;;;;;;;;AAuFA,SAAgB,mBAA8C;AAC5D,KAAI,OAAO,WAAW,eAAe,YAAY,OAC/C,QAAQ,OAAgD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACzD5D,SAAgB,gBAAiE;CAC/E,MAAM,MAAM,gBAAA,QAAQ;AACpB,SAAA,GAAA,MAAA,aACE,OAAO,SAAe;AACpB,MAAI,CAAC,IACH,OAAM,IAAI,MAAM,oCAAoC;EAEtD,MAAM,UAAU,kBAAkB;AAClC,MAAI,CAAC,SAAS,WACZ,OAAM,IAAI,MAAM,yDAAyD;AAE3E,SAAO,QAAQ,WAAW,KAAK;IAEjC,CAAC,IAAI,CACN;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACZH,SAAgB,wBAE2B;CACzC,MAAM,MAAM,gBAAA,QAAQ;AACpB,SAAA,GAAA,MAAA,aACE,OAAO,WAA+B;AACpC,MAAI,CAAC,IACH,OAAM,IAAI,MAAM,4CAA4C;EAE9D,MAAM,UAAU,kBAAkB;AAClC,MAAI,CAAC,SAAS,mBACZ,OAAM,IAAI,MAAM,yEAAyE;AAE3F,SAAO,QAAQ,mBAAmB,OAAO;IAE3C,CAAC,IAAI,CACN;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACpBH,SAAgB,kBAAuE;CACrF,MAAM,MAAM,gBAAA,QAAQ;AACpB,SAAA,GAAA,MAAA,aACE,OAAO,WAAqC;AAC1C,MAAI,CAAC,KAAK;AACR,WAAQ,KAAK,sCAAsC;AACnD;;EAEF,MAAM,UAAU,kBAAkB;AAClC,MAAI,CAAC,SAAS,aACZ,OAAM,IAAI,MAAM,6DAA6D;AAE/E,SAAO,QAAQ,aAAa,OAAO;IAErC,CAAC,IAAI,CACN;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACOH,SAAgB,qBAEkB;CAChC,MAAM,MAAM,gBAAA,QAAQ;AACpB,SAAA,GAAA,MAAA,aACE,OAAO,YAAmC;AACxC,MAAI,CAAC,IACH,OAAM,IAAI,MAAM,yCAAyC;EAE3D,MAAM,UAAU,kBAAkB;AAClC,MAAI,CAAC,SAAS,gBACZ,OAAM,IAAI,MAAM,mEAAmE;AAErF,SAAO,QAAQ,gBAAgB,QAAQ;IAEzC,CAAC,IAAI,CACN"}
@@ -1,81 +1,181 @@
1
+ import "../../protocol-DJmRaBzO.js";
2
+ import { t as useApp } from "../../use-app-X7JbGskk.js";
1
3
  import { useCallback } from "react";
2
- import { u as useApp } from "../../use-app-C9gpzIQO.js";
4
+ //#region src/host/chatgpt/openai-types.ts
5
+ /**
6
+ * Get the `window.openai` runtime if available.
7
+ * Returns `undefined` outside of ChatGPT or in SSR.
8
+ */
3
9
  function getOpenAIRuntime() {
4
- if (typeof window !== "undefined" && "openai" in window) {
5
- return window.openai;
6
- }
7
- return void 0;
10
+ if (typeof window !== "undefined" && "openai" in window) return window.openai;
8
11
  }
12
+ //#endregion
13
+ //#region src/host/chatgpt/use-create-file.ts
14
+ /**
15
+ * Upload a file from the app UI into the ChatGPT conversation.
16
+ *
17
+ * Wraps `window.openai.uploadFile` which is only available inside ChatGPT.
18
+ * Supported formats: `image/png`, `image/jpeg`, `image/webp`.
19
+ *
20
+ * Import from `sunpeak/host/chatgpt`:
21
+ *
22
+ * @example
23
+ * ```tsx
24
+ * import { useUploadFile } from 'sunpeak/host/chatgpt';
25
+ *
26
+ * function ImageUploader() {
27
+ * const uploadFile = useUploadFile();
28
+ *
29
+ * const handleChange = async (e: React.ChangeEvent<HTMLInputElement>) => {
30
+ * const file = e.currentTarget.files?.[0];
31
+ * if (!file) return;
32
+ * const { fileId } = await uploadFile(file);
33
+ * console.log('Uploaded:', fileId);
34
+ * };
35
+ *
36
+ * return <input type="file" accept="image/*" onChange={handleChange} />;
37
+ * }
38
+ * ```
39
+ */
9
40
  function useUploadFile() {
10
- const app = useApp();
11
- return useCallback(
12
- async (file) => {
13
- if (!app) {
14
- throw new Error("[useUploadFile] App not connected");
15
- }
16
- const runtime = getOpenAIRuntime();
17
- if (!runtime?.uploadFile) {
18
- throw new Error("[useUploadFile] window.openai.uploadFile not available");
19
- }
20
- return runtime.uploadFile(file);
21
- },
22
- [app]
23
- );
41
+ const app = useApp();
42
+ return useCallback(async (file) => {
43
+ if (!app) throw new Error("[useUploadFile] App not connected");
44
+ const runtime = getOpenAIRuntime();
45
+ if (!runtime?.uploadFile) throw new Error("[useUploadFile] window.openai.uploadFile not available");
46
+ return runtime.uploadFile(file);
47
+ }, [app]);
24
48
  }
49
+ //#endregion
50
+ //#region src/host/chatgpt/use-file-download.ts
51
+ /**
52
+ * Get a temporary download URL for a file by its ID.
53
+ *
54
+ * @deprecated Use {@link useDownloadFile} from `sunpeak` instead — it works
55
+ * across all hosts via the MCP Apps SDK `app.downloadFile()` method.
56
+ *
57
+ * Wraps `window.openai.getFileDownloadUrl` which is only available inside
58
+ * ChatGPT. Use this to retrieve URLs for files uploaded via {@link useUploadFile}
59
+ * or file IDs received in tool parameters.
60
+ *
61
+ * Import from `sunpeak/host/chatgpt`:
62
+ *
63
+ * @example
64
+ * ```tsx
65
+ * import { useGetFileDownloadUrl } from 'sunpeak/host/chatgpt';
66
+ *
67
+ * function FilePreview({ fileId }: { fileId: string }) {
68
+ * const getFileDownloadUrl = useGetFileDownloadUrl();
69
+ * const [src, setSrc] = useState<string>();
70
+ *
71
+ * useEffect(() => {
72
+ * getFileDownloadUrl({ fileId }).then(({ downloadUrl }) => setSrc(downloadUrl));
73
+ * }, [fileId, getFileDownloadUrl]);
74
+ *
75
+ * return src ? <img src={src} /> : <p>Loading...</p>;
76
+ * }
77
+ * ```
78
+ */
25
79
  function useGetFileDownloadUrl() {
26
- const app = useApp();
27
- return useCallback(
28
- async (params) => {
29
- if (!app) {
30
- throw new Error("[useGetFileDownloadUrl] App not connected");
31
- }
32
- const runtime = getOpenAIRuntime();
33
- if (!runtime?.getFileDownloadUrl) {
34
- throw new Error("[useGetFileDownloadUrl] window.openai.getFileDownloadUrl not available");
35
- }
36
- return runtime.getFileDownloadUrl(params);
37
- },
38
- [app]
39
- );
80
+ const app = useApp();
81
+ return useCallback(async (params) => {
82
+ if (!app) throw new Error("[useGetFileDownloadUrl] App not connected");
83
+ const runtime = getOpenAIRuntime();
84
+ if (!runtime?.getFileDownloadUrl) throw new Error("[useGetFileDownloadUrl] window.openai.getFileDownloadUrl not available");
85
+ return runtime.getFileDownloadUrl(params);
86
+ }, [app]);
40
87
  }
88
+ //#endregion
89
+ //#region src/host/chatgpt/use-open-modal.ts
90
+ /**
91
+ * Open a host-controlled modal in ChatGPT.
92
+ *
93
+ * Wraps `window.openai.requestModal` which is only available inside ChatGPT.
94
+ * Pass a `template` URL to load alternate UI content in the modal, or omit
95
+ * it to reuse the current UI.
96
+ *
97
+ * Import from `sunpeak/host/chatgpt`:
98
+ *
99
+ * @example
100
+ * ```tsx
101
+ * import { useRequestModal } from 'sunpeak/host/chatgpt';
102
+ *
103
+ * function CheckoutButton() {
104
+ * const requestModal = useRequestModal();
105
+ *
106
+ * return (
107
+ * <button onClick={() => requestModal({ template: 'ui://widget/checkout.html' })}>
108
+ * Checkout
109
+ * </button>
110
+ * );
111
+ * }
112
+ * ```
113
+ */
41
114
  function useRequestModal() {
42
- const app = useApp();
43
- return useCallback(
44
- async (params) => {
45
- if (!app) {
46
- console.warn("[useRequestModal] App not connected");
47
- return;
48
- }
49
- const runtime = getOpenAIRuntime();
50
- if (!runtime?.requestModal) {
51
- throw new Error("[useRequestModal] window.openai.requestModal not available");
52
- }
53
- return runtime.requestModal(params);
54
- },
55
- [app]
56
- );
115
+ const app = useApp();
116
+ return useCallback(async (params) => {
117
+ if (!app) {
118
+ console.warn("[useRequestModal] App not connected");
119
+ return;
120
+ }
121
+ const runtime = getOpenAIRuntime();
122
+ if (!runtime?.requestModal) throw new Error("[useRequestModal] window.openai.requestModal not available");
123
+ return runtime.requestModal(params);
124
+ }, [app]);
57
125
  }
126
+ //#endregion
127
+ //#region src/host/chatgpt/use-request-checkout.ts
128
+ /**
129
+ * Trigger the ChatGPT instant checkout flow.
130
+ *
131
+ * Wraps `window.openai.requestCheckout` which is only available inside
132
+ * ChatGPT. Opens the host checkout UI, handles payment display, and
133
+ * resolves with the finalized order. Rejects on error or user cancel.
134
+ *
135
+ * Import from `sunpeak/host/chatgpt`:
136
+ *
137
+ * @example
138
+ * ```tsx
139
+ * import { useRequestCheckout } from 'sunpeak/host/chatgpt';
140
+ *
141
+ * function BuyButton() {
142
+ * const requestCheckout = useRequestCheckout();
143
+ *
144
+ * const handleBuy = async () => {
145
+ * try {
146
+ * const order = await requestCheckout({
147
+ * id: 'session-1',
148
+ * payment_provider: {
149
+ * provider: 'stripe',
150
+ * merchant_id: 'acct_xxx',
151
+ * supported_payment_methods: ['card', 'apple_pay'],
152
+ * },
153
+ * status: 'ready_for_payment',
154
+ * currency: 'USD',
155
+ * totals: [{ type: 'total', display_text: 'Total', amount: 999 }],
156
+ * links: [],
157
+ * payment_mode: 'live',
158
+ * });
159
+ * console.log('Order completed:', order.id);
160
+ * } catch {
161
+ * console.log('Checkout cancelled or failed');
162
+ * }
163
+ * };
164
+ *
165
+ * return <button onClick={handleBuy}>Buy Now</button>;
166
+ * }
167
+ * ```
168
+ */
58
169
  function useRequestCheckout() {
59
- const app = useApp();
60
- return useCallback(
61
- async (session) => {
62
- if (!app) {
63
- throw new Error("[useRequestCheckout] App not connected");
64
- }
65
- const runtime = getOpenAIRuntime();
66
- if (!runtime?.requestCheckout) {
67
- throw new Error("[useRequestCheckout] window.openai.requestCheckout not available");
68
- }
69
- return runtime.requestCheckout(session);
70
- },
71
- [app]
72
- );
170
+ const app = useApp();
171
+ return useCallback(async (session) => {
172
+ if (!app) throw new Error("[useRequestCheckout] App not connected");
173
+ const runtime = getOpenAIRuntime();
174
+ if (!runtime?.requestCheckout) throw new Error("[useRequestCheckout] window.openai.requestCheckout not available");
175
+ return runtime.requestCheckout(session);
176
+ }, [app]);
73
177
  }
74
- export {
75
- getOpenAIRuntime,
76
- useGetFileDownloadUrl,
77
- useRequestCheckout,
78
- useRequestModal,
79
- useUploadFile
80
- };
81
- //# sourceMappingURL=index.js.map
178
+ //#endregion
179
+ export { getOpenAIRuntime, useGetFileDownloadUrl, useRequestCheckout, useRequestModal, useUploadFile };
180
+
181
+ //# sourceMappingURL=index.js.map