@burdenoff/microfe-botmanor 2026.1120.9 → 2026.1120.11

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 (31) hide show
  1. package/dist/botlit/components/ChannelSetupPanels.d.ts +5 -0
  2. package/dist/botlit/components/ChannelSetupPanels.js +19 -15
  3. package/dist/botlit/components/ChannelSetupPanels.js.map +1 -1
  4. package/dist/botlit/components/ExecutionFeedback.d.ts +5 -0
  5. package/dist/botlit/components/ExecutionFeedback.js +55 -0
  6. package/dist/botlit/components/ExecutionFeedback.js.map +1 -0
  7. package/dist/botlit/components/KnowledgeReviewSchedule.d.ts +7 -0
  8. package/dist/botlit/components/KnowledgeReviewSchedule.js +92 -0
  9. package/dist/botlit/components/KnowledgeReviewSchedule.js.map +1 -0
  10. package/dist/botlit/components/SuggestionsPanel.d.ts +12 -0
  11. package/dist/botlit/components/SuggestionsPanel.js +219 -0
  12. package/dist/botlit/components/SuggestionsPanel.js.map +1 -0
  13. package/dist/botlit/hooks/useAgentTuning.d.ts +87 -0
  14. package/dist/botlit/hooks/useAgentTuning.js +170 -0
  15. package/dist/botlit/hooks/useAgentTuning.js.map +1 -0
  16. package/dist/botlit/hooks/useAiOperations.js +1 -1
  17. package/dist/botlit/hooks/useAiOperations.js.map +1 -1
  18. package/dist/botlit/hooks/useChannelSetup.d.ts +21 -4
  19. package/dist/botlit/hooks/useChannelSetup.js +128 -32
  20. package/dist/botlit/hooks/useChannelSetup.js.map +1 -1
  21. package/dist/botlit/pages/AgentDetailPage.js +75 -70
  22. package/dist/botlit/pages/AgentDetailPage.js.map +1 -1
  23. package/dist/botlit/pages/BotChannelsTab.js +1 -0
  24. package/dist/botlit/pages/BotChannelsTab.js.map +1 -1
  25. package/dist/botlit/pages/ChannelDetailPage.js +381 -380
  26. package/dist/botlit/pages/ChannelDetailPage.js.map +1 -1
  27. package/dist/botlit/pages/ExecutionDetailPage.js +141 -136
  28. package/dist/botlit/pages/ExecutionDetailPage.js.map +1 -1
  29. package/dist/botlit/pages/KnowledgeBaseDetailPage.js +356 -354
  30. package/dist/botlit/pages/KnowledgeBaseDetailPage.js.map +1 -1
  31. package/package.json +1 -1
@@ -4,7 +4,7 @@ import { useWorkspaceScopedGlobalClient as n } from "./internal/globalWorkspaceS
4
4
  import { useCallback as r, useEffect as i, useRef as a, useState as o } from "react";
5
5
  import { gql as s } from "@apollo/client";
6
6
  // src/botlit/hooks/useChannelSetup.ts
7
- var c = {
7
+ var c = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i, l = {
8
8
  SLACK: {
9
9
  platform: "SLACK",
10
10
  authType: "BOT_TOKEN",
@@ -21,7 +21,101 @@ var c = {
21
21
  placeholder: "Signing secret",
22
22
  secret: !0
23
23
  }],
24
- inboundHint: "In your Slack app, open Event Subscriptions, turn events on and paste this as the Request URL. Subscribe the bot to message.channels, message.im and app_mention, then reinstall the app."
24
+ inboundHint: "In your Slack app, open Event Subscriptions, turn events on and paste this as the Request URL. Subscribe the bot to message.channels, message.im and app_mention, then reinstall the app.",
25
+ usesInboundUrl: !0
26
+ },
27
+ TEAMS: {
28
+ platform: "TEAMS",
29
+ authType: "BOT_TOKEN",
30
+ fields: [
31
+ {
32
+ key: "appId",
33
+ label: "Microsoft App ID",
34
+ description: "Azure portal → your Azure Bot → Settings → Configuration → Microsoft App ID (a GUID).",
35
+ placeholder: "00000000-0000-0000-0000-000000000000",
36
+ secret: !1,
37
+ pattern: c,
38
+ patternMessage: "Microsoft App ID must be a GUID"
39
+ },
40
+ {
41
+ key: "appPassword",
42
+ label: "Client Secret",
43
+ description: "Configuration → Manage Password (or Microsoft Entra ID → App registrations → the bot app) → Certificates & secrets → New client secret. Copy the secret Value, not its ID.",
44
+ placeholder: "Client secret value",
45
+ secret: !0
46
+ },
47
+ {
48
+ key: "tenantId",
49
+ label: "App Tenant ID",
50
+ description: "Azure Bot → Configuration → App Tenant ID (Microsoft Entra ID → Overview → Tenant ID). The bot must be Single Tenant.",
51
+ placeholder: "00000000-0000-0000-0000-000000000000",
52
+ secret: !1,
53
+ pattern: c,
54
+ patternMessage: "App Tenant ID must be a GUID"
55
+ }
56
+ ],
57
+ inboundHint: "In the Azure portal open your Azure Bot → Configuration, paste this as the Messaging endpoint and Apply. Under Channels, add Microsoft Teams. Then install the bot in Teams (a Teams app whose bot id is the Microsoft App ID) and message it; in a channel, @mention it.",
58
+ usesInboundUrl: !0
59
+ },
60
+ WHATSAPP: {
61
+ platform: "WHATSAPP",
62
+ authType: "BOT_TOKEN",
63
+ fields: [
64
+ {
65
+ key: "phoneNumberId",
66
+ label: "Phone Number ID",
67
+ description: "Meta app dashboard → WhatsApp → API Setup → Phone number ID (not the phone number itself).",
68
+ placeholder: "123456789012345",
69
+ secret: !1,
70
+ pattern: /^\d{5,20}$/,
71
+ patternMessage: "Phone Number ID must be digits only"
72
+ },
73
+ {
74
+ key: "accessToken",
75
+ label: "Access Token",
76
+ description: "A permanent token: Meta Business Settings → Users → System users → Generate new token for this app with whatsapp_business_messaging and whatsapp_business_management. The API Setup token expires after 24 hours.",
77
+ placeholder: "EAA…",
78
+ secret: !0
79
+ },
80
+ {
81
+ key: "appSecret",
82
+ label: "App Secret",
83
+ description: "Meta app dashboard → App settings → Basic → App secret (Show).",
84
+ placeholder: "App secret",
85
+ secret: !0
86
+ },
87
+ {
88
+ key: "verifyToken",
89
+ label: "Verify Token",
90
+ description: "Any value you choose. Paste the same value as the Verify token when you set up the webhook in Meta.",
91
+ placeholder: "Generate or paste a token",
92
+ secret: !0,
93
+ generatable: !0
94
+ }
95
+ ],
96
+ inboundHint: "In the Meta app dashboard open WhatsApp → Configuration → Webhook → Edit. Paste this as the Callback URL and your Verify Token, then Verify and save. Under Webhook fields, subscribe to messages.",
97
+ usesInboundUrl: !0
98
+ },
99
+ DISCORD: {
100
+ platform: "DISCORD",
101
+ authType: "BOT_TOKEN",
102
+ fields: [{
103
+ key: "botToken",
104
+ label: "Bot Token",
105
+ description: "Discord Developer Portal → your application → Bot → Reset Token. Turn on Message Content Intent on the same page.",
106
+ placeholder: "Bot token",
107
+ secret: !0
108
+ }, {
109
+ key: "guildId",
110
+ label: "Server ID",
111
+ description: "Discord → User Settings → Advanced → Developer Mode on, then right-click your server → Copy Server ID.",
112
+ placeholder: "123456789012345678",
113
+ secret: !1,
114
+ pattern: /^\d{17,20}$/,
115
+ patternMessage: "Server ID must be a 17-20 digit number"
116
+ }],
117
+ inboundHint: "Discord delivers messages to the bot over its Gateway connection, so no URL is needed: leave Interactions Endpoint URL empty. In the Developer Portal → Bot, turn on Message Content Intent. Invite the bot to your server (OAuth2 → URL Generator → scope bot, permissions View Channels, Send Messages and Read Message History), then message or @mention it.",
118
+ usesInboundUrl: !1
25
119
  },
26
120
  WEBHOOK: {
27
121
  platform: "WEBHOOK",
@@ -41,23 +135,24 @@ var c = {
41
135
  secret: !0,
42
136
  generatable: !0
43
137
  }],
44
- inboundHint: "POST each inbound message here as JSON ({\"event\":\"message\",\"id\",\"sender_id\",\"text\",\"conversation_id\"}), signed with the signing secret in the X-Signature header."
138
+ inboundHint: "POST each inbound message here as JSON ({\"event\":\"message\",\"id\",\"sender_id\",\"text\",\"conversation_id\"}), signed with the signing secret in the X-Signature header.",
139
+ usesInboundUrl: !0
45
140
  }
46
- }, l = {
141
+ }, u = {
47
142
  SLACK: "SLACK",
48
143
  TEAMS: "TEAMS",
49
144
  DISCORD: "DISCORD",
50
145
  WHATSAPP: "WHATSAPP",
51
146
  WEBHOOK: "WEBHOOK"
52
147
  };
53
- function u(e) {
54
- return l[e];
148
+ function d(e) {
149
+ return u[e];
55
150
  }
56
- function d() {
151
+ function f() {
57
152
  let e = /* @__PURE__ */ new Uint8Array(32);
58
153
  return crypto.getRandomValues(e), Array.from(e, (e) => e.toString(16).padStart(2, "0")).join("");
59
154
  }
60
- function f(e, t) {
155
+ function p(e, t) {
61
156
  for (let n of e.fields) {
62
157
  let e = t[n.key]?.trim() ?? "";
63
158
  if (!e) return `${n.label} is required`;
@@ -70,13 +165,14 @@ function f(e, t) {
70
165
  }
71
166
  if (t.protocol !== "https:") return `${n.label} must use https`;
72
167
  }
168
+ if (n.pattern && !n.pattern.test(e)) return n.patternMessage ?? `${n.label} is not valid`;
73
169
  }
74
170
  return null;
75
171
  }
76
- function p() {
172
+ function m() {
77
173
  return e().organizationId || null;
78
174
  }
79
- var m = s`
175
+ var h = s`
80
176
  query BotmanorInboundChannel($id: ID!) {
81
177
  getChannel(id: $id) {
82
178
  id
@@ -88,46 +184,46 @@ var m = s`
88
184
  inboundWebhookUrl
89
185
  }
90
186
  }
91
- `, h = s`
187
+ `, g = s`
92
188
  mutation BotmanorCreateSetupChannel($input: CreateChannelInput!) {
93
189
  createChannel(input: $input) {
94
190
  id
95
191
  }
96
192
  }
97
- `, g = s`
193
+ `, _ = s`
98
194
  mutation BotmanorCreateSetupConnection($input: CreateConnectionInput!) {
99
195
  createConnection(input: $input) {
100
196
  id
101
197
  }
102
198
  }
103
- `, _ = s`
199
+ `, v = s`
104
200
  mutation BotmanorDeleteSetupChannel($id: ID!) {
105
201
  deleteChannel(id: $id)
106
202
  }
107
203
  `;
108
- function v(e, n) {
204
+ function y(e, n) {
109
205
  let r = t(e);
110
206
  return r ? Error(r, { cause: e }) : e instanceof Error ? e : Error(n, { cause: e });
111
207
  }
112
- function y(e, t) {
208
+ function b(e, t) {
113
209
  let n = e.error;
114
- if (n != null) throw v(n, t);
210
+ if (n != null) throw y(n, t);
115
211
  }
116
- function b(e) {
117
- let { client: t, context: s } = n(), [c, l] = o(null), [u, d] = o(!1), [f, p] = o(void 0), h = a(0), g = r(async () => {
118
- let n = ++h.current, r = () => n === h.current;
212
+ function x(e) {
213
+ let { client: t, context: s } = n(), [c, l] = o(null), [u, d] = o(!1), [f, p] = o(void 0), m = a(0), g = r(async () => {
214
+ let n = ++m.current, r = () => n === m.current;
119
215
  if (l(null), p(void 0), e) {
120
216
  d(!0);
121
217
  try {
122
218
  let n = await t.query({
123
- query: m,
219
+ query: h,
124
220
  variables: { id: e },
125
221
  fetchPolicy: "network-only",
126
222
  context: s
127
223
  });
128
- y(n, "Failed to load the channel"), r() && l(n.data?.getChannel ?? null);
224
+ b(n, "Failed to load the channel"), r() && l(n.data?.getChannel ?? null);
129
225
  } catch (e) {
130
- r() && p(v(e, "Failed to load the channel"));
226
+ r() && p(y(e, "Failed to load the channel"));
131
227
  } finally {
132
228
  r() && d(!1);
133
229
  }
@@ -146,10 +242,10 @@ function b(e) {
146
242
  refetch: g
147
243
  };
148
244
  }
149
- function x() {
245
+ function S() {
150
246
  let { client: e, context: t } = n(), [i, a] = o(!1), s = r(async (n) => {
151
- y(await e.mutate({
152
- mutation: _,
247
+ b(await e.mutate({
248
+ mutation: v,
153
249
  variables: { id: n },
154
250
  context: t
155
251
  }), "Failed to delete the channel");
@@ -161,7 +257,7 @@ function x() {
161
257
  let a;
162
258
  try {
163
259
  let s = await e.mutate({
164
- mutation: h,
260
+ mutation: g,
165
261
  variables: { input: {
166
262
  name: n,
167
263
  description: r || void 0,
@@ -171,15 +267,15 @@ function x() {
171
267
  } },
172
268
  context: t
173
269
  });
174
- y(s, "Failed to create the channel"), a = s.data?.createChannel?.id;
270
+ b(s, "Failed to create the channel"), a = s.data?.createChannel?.id;
175
271
  } catch (e) {
176
- throw v(e, "Failed to create the channel");
272
+ throw y(e, "Failed to create the channel");
177
273
  }
178
274
  if (!a) throw Error("Failed to create the channel");
179
275
  let l = Object.fromEntries(o.fields.map((e) => [e.key, c[e.key]?.trim() ?? ""]));
180
276
  try {
181
- y(await e.mutate({
182
- mutation: g,
277
+ b(await e.mutate({
278
+ mutation: _,
183
279
  variables: { input: {
184
280
  channelId: a,
185
281
  authType: o.authType,
@@ -188,7 +284,7 @@ function x() {
188
284
  context: t
189
285
  }), "Failed to save the channel credentials");
190
286
  } catch (e) {
191
- throw await s(a).catch(() => void 0), v(e, "Failed to save the channel credentials");
287
+ throw await s(a).catch(() => void 0), y(e, "Failed to save the channel credentials");
192
288
  }
193
289
  return a;
194
290
  } finally {
@@ -203,6 +299,6 @@ function x() {
203
299
  loading: i
204
300
  };
205
301
  }
206
- export { c as PLATFORM_CREDENTIALS, u as connectorPlatform, d as generateSigningSecret, p as useActiveOrganizationId, b as useInboundChannel, x as useProvisionChannel, f as validateCredentials };
302
+ export { l as PLATFORM_CREDENTIALS, d as connectorPlatform, f as generateSigningSecret, m as useActiveOrganizationId, x as useInboundChannel, S as useProvisionChannel, p as validateCredentials };
207
303
 
208
304
  //# sourceMappingURL=useChannelSetup.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"useChannelSetup.js","names":["PLATFORM_CREDENTIALS","CONNECTOR_PLATFORM","connectorPlatform","connectorType","generateSigningSecret","bytes","byte","validateCredentials","field","definition","value","values","parsed","useActiveOrganizationId","useBotlit","GetInboundChannelDocument","CreateSetupChannelDocument","CreateSetupConnectionDocument","DeleteSetupChannelDocument","toError","message","extractGraphqlFailureMessage","cause","fallback","throwIfOperationFailed","operationError","result","useInboundChannel","useWorkspaceScopedGlobalClient","data","setData","useState","loading","setLoading","error","setError","latestRequest","useRef","refetch","useCallback","request","isLatest","channelId","client","context","useEffect","useProvisionChannel","discard","created","description","trimmed","credentials"],"sources":["../../../src/botlit/hooks/useChannelSetup.ts"],"sourcesContent":["/**\n * Channel setup hooks (BOFF-15360)\n * @module botlit/hooks\n *\n * A BotManor channel connector names a channel on global-channel-svc through\n * `credentialsRefId`. That global channel holds the platform credentials (a\n * Slack bot token and signing secret, a webhook's signing secret and reply\n * URL, …) and publishes the public URL the platform must call with inbound\n * events (`Channel.inboundWebhookUrl`, set once an ACTIVE connector binds the\n * channel to this workspace).\n *\n * These hooks let the connector form create that channel with its credentials\n * and the detail page show its inbound URL, all through the shell's global\n * gateway client, scoped to the active workspace's organization (see\n * `internal/globalWorkspaceScope`). The documents are written inline, like `GetChannels` in\n * `useUserPlatformConnection`: `inboundWebhookUrl` / `inboundWorkspaceId` are\n * newer than the checked-in `graphql/global.graphql`, which cannot be\n * re-pulled while gateway introspection is disabled.\n */\n\nimport { useCallback, useEffect, useRef, useState } from 'react';\nimport { gql } from '@apollo/client';\n\nimport { useBotlit } from '../providers/BotlitProvider';\nimport { extractGraphqlFailureMessage } from '../utils/errors';\nimport { useWorkspaceScopedGlobalClient } from './internal/globalWorkspaceScope';\n\n// ============================================================================\n// Platform credential definitions\n// ============================================================================\n\n/** Global-channel platforms a connector type delivers through. */\nexport type ChannelSetupPlatform = 'SLACK' | 'TEAMS' | 'DISCORD' | 'WHATSAPP' | 'WEBHOOK';\n\n/** `ChannelAuthType` values the setup form sends. */\ntype ChannelSetupAuthType = 'BOT_TOKEN' | 'WEBHOOK';\n\nexport interface CredentialFieldDefinition {\n /** Key stored on the channel connection's credentials. */\n key: string;\n label: string;\n description: string;\n placeholder: string;\n /** Rendered as a password input and never shown again after saving. */\n secret: boolean;\n /** Offer a \"Generate\" button producing a random 64-hex-character secret. */\n generatable?: boolean;\n /** Must be an absolute https URL. */\n url?: boolean;\n}\n\nexport interface PlatformCredentialDefinition {\n platform: ChannelSetupPlatform;\n authType: ChannelSetupAuthType;\n fields: CredentialFieldDefinition[];\n /** Where to paste the inbound webhook URL on the platform side. */\n inboundHint: string;\n}\n\n/**\n * Connector types whose credentials the form can collect directly. The keys\n * are the ones global-channel-svc reads: Slack sends with `botToken` and\n * verifies inbound requests with `signingSecret`; a generic webhook verifies\n * with `webhookSecret` (HMAC-SHA256 hex in `X-Signature`) and POSTs replies\n * to `targetUrl`.\n */\nexport const PLATFORM_CREDENTIALS: Readonly<Record<string, PlatformCredentialDefinition>> = {\n SLACK: {\n platform: 'SLACK',\n authType: 'BOT_TOKEN',\n fields: [\n {\n key: 'botToken',\n label: 'Bot User OAuth Token',\n description: 'Slack app → OAuth & Permissions. Starts with xoxb-.',\n placeholder: 'xoxb-…',\n secret: true,\n },\n {\n key: 'signingSecret',\n label: 'Signing Secret',\n description: 'Slack app → Basic Information → App Credentials.',\n placeholder: 'Signing secret',\n secret: true,\n },\n ],\n inboundHint:\n 'In your Slack app, open Event Subscriptions, turn events on and paste this as the Request URL. Subscribe the bot to message.channels, message.im and app_mention, then reinstall the app.',\n },\n WEBHOOK: {\n platform: 'WEBHOOK',\n authType: 'WEBHOOK',\n fields: [\n {\n key: 'targetUrl',\n label: 'Reply URL',\n description: 'The bot POSTs its replies to this https URL.',\n placeholder: 'https://example.com/bot-replies',\n secret: false,\n url: true,\n },\n {\n key: 'webhookSecret',\n label: 'Signing Secret',\n description:\n 'Your sender signs each request body with HMAC-SHA256 using this secret and sends the hex digest in the X-Signature header.',\n placeholder: 'Generate or paste a secret',\n secret: true,\n generatable: true,\n },\n ],\n inboundHint:\n 'POST each inbound message here as JSON ({\"event\":\"message\",\"id\",\"sender_id\",\"text\",\"conversation_id\"}), signed with the signing secret in the X-Signature header.',\n },\n};\n\n/** Connector type → the global-channel platform it uses (none for widget/custom). */\nconst CONNECTOR_PLATFORM: Readonly<Record<string, ChannelSetupPlatform>> = {\n SLACK: 'SLACK',\n TEAMS: 'TEAMS',\n DISCORD: 'DISCORD',\n WHATSAPP: 'WHATSAPP',\n WEBHOOK: 'WEBHOOK',\n};\n\nexport function connectorPlatform(connectorType: string): ChannelSetupPlatform | undefined {\n return CONNECTOR_PLATFORM[connectorType];\n}\n\n/** A random 32-byte secret, hex encoded, from the browser's CSPRNG. */\nexport function generateSigningSecret(): string {\n const bytes = new Uint8Array(32);\n crypto.getRandomValues(bytes);\n return Array.from(bytes, (byte) => byte.toString(16).padStart(2, '0')).join('');\n}\n\n/**\n * Returns the first problem with the entered credentials, or null when they\n * are complete. Every field is required.\n */\nexport function validateCredentials(\n definition: PlatformCredentialDefinition,\n values: Record<string, string>\n): string | null {\n for (const field of definition.fields) {\n const value = values[field.key]?.trim() ?? '';\n if (!value) return `${field.label} is required`;\n if (field.url) {\n let parsed: URL;\n try {\n parsed = new URL(value);\n } catch {\n return `${field.label} must be a valid URL`;\n }\n if (parsed.protocol !== 'https:') return `${field.label} must use https`;\n }\n }\n return null;\n}\n\n// ============================================================================\n// Organization\n// ============================================================================\n\n/**\n * The shell's active organization (the host passes it with the workspace).\n * Global channels belong to an organization, so creating one needs it.\n */\nexport function useActiveOrganizationId(): string | null {\n return useBotlit().organizationId || null;\n}\n\n// ============================================================================\n// Documents\n// ============================================================================\n\nconst GetInboundChannelDocument = gql`\n query BotmanorInboundChannel($id: ID!) {\n getChannel(id: $id) {\n id\n name\n platform\n status\n isConnected\n inboundWorkspaceId\n inboundWebhookUrl\n }\n }\n`;\n\nconst CreateSetupChannelDocument = gql`\n mutation BotmanorCreateSetupChannel($input: CreateChannelInput!) {\n createChannel(input: $input) {\n id\n }\n }\n`;\n\nconst CreateSetupConnectionDocument = gql`\n mutation BotmanorCreateSetupConnection($input: CreateConnectionInput!) {\n createConnection(input: $input) {\n id\n }\n }\n`;\n\nconst DeleteSetupChannelDocument = gql`\n mutation BotmanorDeleteSetupChannel($id: ID!) {\n deleteChannel(id: $id)\n }\n`;\n\nexport interface InboundChannelData {\n id: string;\n name: string;\n platform: string;\n status: string;\n isConnected: boolean;\n inboundWorkspaceId: string | null;\n inboundWebhookUrl: string | null;\n}\n\nfunction toError(cause: unknown, fallback: string): Error {\n const message = extractGraphqlFailureMessage(cause);\n if (message) return new Error(message, { cause });\n return cause instanceof Error ? cause : new Error(fallback, { cause });\n}\n\n/**\n * Apollo v4 resolves (rather than rejects) with `error` set when the server\n * answers with GraphQL errors; surface those as a failure like a rejection.\n */\nfunction throwIfOperationFailed(result: unknown, fallback: string): void {\n const operationError = (result as { error?: unknown }).error;\n if (operationError != null) throw toError(operationError, fallback);\n}\n\n// ============================================================================\n// Hook: useInboundChannel\n// ============================================================================\n\ninterface UseInboundChannelResult {\n data: InboundChannelData | null;\n loading: boolean;\n error: Error | undefined;\n refetch: () => Promise<void>;\n}\n\n/** The global channel a connector names, with its inbound webhook URL. */\nexport function useInboundChannel(channelId: string | null | undefined): UseInboundChannelResult {\n const { client, context } = useWorkspaceScopedGlobalClient();\n const [data, setData] = useState<InboundChannelData | null>(null);\n const [loading, setLoading] = useState(false);\n const [error, setError] = useState<Error | undefined>(undefined);\n /** Only the latest request may set state: a slower answer for a previous channel is dropped. */\n const latestRequest = useRef(0);\n\n const refetch = useCallback(async () => {\n const request = ++latestRequest.current;\n const isLatest = () => request === latestRequest.current;\n setData(null);\n setError(undefined);\n if (!channelId) return;\n setLoading(true);\n try {\n const result = await client.query<{ getChannel: InboundChannelData | null }>({\n query: GetInboundChannelDocument,\n variables: { id: channelId },\n fetchPolicy: 'network-only',\n context,\n });\n throwIfOperationFailed(result, 'Failed to load the channel');\n if (isLatest()) setData(result.data?.getChannel ?? null);\n } catch (cause) {\n if (isLatest()) setError(toError(cause, 'Failed to load the channel'));\n } finally {\n if (isLatest()) setLoading(false);\n }\n }, [channelId, client, context]);\n\n useEffect(() => {\n void refetch();\n }, [refetch]);\n\n return { data, loading, error, refetch };\n}\n\n// ============================================================================\n// Hook: useProvisionChannel\n// ============================================================================\n\nexport interface ProvisionChannelInput {\n name: string;\n description?: string;\n organizationId: string;\n definition: PlatformCredentialDefinition;\n credentials: Record<string, string>;\n}\n\ninterface UseProvisionChannelResult {\n /** Creates the global channel and its connection; resolves to the channel id. */\n provision: (input: ProvisionChannelInput) => Promise<string>;\n /** Deletes a channel `provision` created (rollback when the connector fails). */\n discard: (channelId: string) => Promise<void>;\n loading: boolean;\n}\n\nexport function useProvisionChannel(): UseProvisionChannelResult {\n const { client, context } = useWorkspaceScopedGlobalClient();\n const [loading, setLoading] = useState(false);\n\n const discard = useCallback(\n async (channelId: string) => {\n const result = await client.mutate({\n mutation: DeleteSetupChannelDocument,\n variables: { id: channelId },\n context,\n });\n throwIfOperationFailed(result, 'Failed to delete the channel');\n },\n [client, context]\n );\n\n const provision = useCallback(\n async ({\n name,\n description,\n organizationId,\n definition,\n credentials,\n }: ProvisionChannelInput): Promise<string> => {\n setLoading(true);\n try {\n let channelId: string | undefined;\n try {\n const created = await client.mutate<{ createChannel: { id: string } | null }>({\n mutation: CreateSetupChannelDocument,\n variables: {\n input: {\n name,\n description: description || undefined,\n platform: definition.platform,\n channelType: 'COMMUNICATION',\n organizationId,\n },\n },\n context,\n });\n throwIfOperationFailed(created, 'Failed to create the channel');\n channelId = created.data?.createChannel?.id;\n } catch (cause) {\n throw toError(cause, 'Failed to create the channel');\n }\n if (!channelId) throw new Error('Failed to create the channel');\n\n const trimmed = Object.fromEntries(\n definition.fields.map((field) => [field.key, credentials[field.key]?.trim() ?? ''])\n );\n try {\n const connected = await client.mutate({\n mutation: CreateSetupConnectionDocument,\n variables: {\n input: { channelId, authType: definition.authType, credentials: trimmed },\n },\n context,\n });\n throwIfOperationFailed(connected, 'Failed to save the channel credentials');\n } catch (cause) {\n // A channel without its credentials can never deliver: remove it so\n // a retry starts clean instead of leaving an orphan behind.\n await discard(channelId).catch(() => undefined);\n throw toError(cause, 'Failed to save the channel credentials');\n }\n return channelId;\n } finally {\n setLoading(false);\n }\n },\n [client, context, discard]\n );\n\n return { provision, discard, loading };\n}\n"],"mappings":";;;;;;AAkEA,IAAaA,IAA+E;CAC1F,OAAO;EACL,UAAU;EACV,UAAU;EACV,QAAQ,CACN;GACE,KAAK;GACL,OAAO;GACP,aAAa;GACb,aAAa;GACb,QAAQ;EACV,GACA;GACE,KAAK;GACL,OAAO;GACP,aAAa;GACb,aAAa;GACb,QAAQ;EACV,CACF;EACA,aACE;CACJ;CACA,SAAS;EACP,UAAU;EACV,UAAU;EACV,QAAQ,CACN;GACE,KAAK;GACL,OAAO;GACP,aAAa;GACb,aAAa;GACb,QAAQ;GACR,KAAK;EACP,GACA;GACE,KAAK;GACL,OAAO;GACP,aACE;GACF,aAAa;GACb,QAAQ;GACR,aAAa;EACf,CACF;EACA,aACE;CACJ;AACF,GAGMC,IAAqE;CACzE,OAAO;CACP,OAAO;CACP,SAAS;CACT,UAAU;CACV,SAAS;AACX;AAEA,SAAgBC,EAAkB,GAAyD;CACzF,OAAOD,E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5E,UAAU3B;MACV,WAAW,EACT,OAAO;OACL;OACA,aAAaiC,KAAe,KAAA;OAC5B,UAAUxC,EAAW;OACrB,aAAa;OACb;MACF,EACF;MACA;KACF,CAAC;KAED,AADAe,EAAuBwB,GAAS,8BAA8B,GAC9D,IAAYA,EAAQ,MAAM,eAAe;IAC3C,SAAS1B,GAAO;KACd,MAAMH,EAAQG,GAAO,8BAA8B;IACrD;IACA,IAAI,CAACoB,GAAW,MAAU,MAAM,8BAA8B;IAE9D,IAAMQ,IAAU,OAAO,YACrBzC,EAAW,OAAO,KAAK,MAAU,CAACD,EAAM,KAAK2C,EAAY3C,EAAM,IAAI,EAAE,KAAK,KAAK,EAAE,CAAC,CACpF;IACA,IAAI;KAQF,EAAuB,MAPCmC,EAAO,OAAO;MACpC,UAAU1B;MACV,WAAW,EACT,OAAO;OAAE;OAAW,UAAUR,EAAW;OAAU,aAAayC;MAAQ,EAC1E;MACA;KACF,CAAC,GACiC,wCAAwC;IAC5E,SAAS5B,GAAO;KAId,MADA,MAAMyB,EAAQL,CAAS,CAAC,CAAC,YAAY,KAAA,CAAS,GACxCvB,EAAQG,GAAO,wCAAwC;IAC/D;IACA,OAAOoB;GACT,UAAU;IACR,EAAW,EAAK;GAClB;EACF,GACA;GAACC;GAAQC;GAASG;EAAO,CAGlB;EAAW;EAAS;CAAQ;AACvC"}
1
+ {"version":3,"file":"useChannelSetup.js","names":["GUID","PLATFORM_CREDENTIALS","CONNECTOR_PLATFORM","connectorPlatform","connectorType","generateSigningSecret","bytes","byte","validateCredentials","field","definition","value","values","parsed","useActiveOrganizationId","useBotlit","GetInboundChannelDocument","CreateSetupChannelDocument","CreateSetupConnectionDocument","DeleteSetupChannelDocument","toError","message","extractGraphqlFailureMessage","cause","fallback","throwIfOperationFailed","operationError","result","useInboundChannel","useWorkspaceScopedGlobalClient","data","setData","useState","loading","setLoading","error","setError","latestRequest","useRef","refetch","useCallback","request","isLatest","channelId","client","context","useEffect","useProvisionChannel","discard","created","description","trimmed","credentials"],"sources":["../../../src/botlit/hooks/useChannelSetup.ts"],"sourcesContent":["/**\n * Channel setup hooks (BOFF-15360)\n * @module botlit/hooks\n *\n * A BotManor channel connector names a channel on global-channel-svc through\n * `credentialsRefId`. That global channel holds the platform credentials (a\n * Slack bot token and signing secret, a webhook's signing secret and reply\n * URL, …) and publishes the public URL the platform must call with inbound\n * events (`Channel.inboundWebhookUrl`, set once an ACTIVE connector binds the\n * channel to this workspace).\n *\n * These hooks let the connector form create that channel with its credentials\n * and the detail page show its inbound URL, all through the shell's global\n * gateway client, scoped to the active workspace's organization (see\n * `internal/globalWorkspaceScope`). The documents are written inline, like `GetChannels` in\n * `useUserPlatformConnection`: `inboundWebhookUrl` / `inboundWorkspaceId` are\n * newer than the checked-in `graphql/global.graphql`, which cannot be\n * re-pulled while gateway introspection is disabled.\n */\n\nimport { useCallback, useEffect, useRef, useState } from 'react';\nimport { gql } from '@apollo/client';\n\nimport { useBotlit } from '../providers/BotlitProvider';\nimport { extractGraphqlFailureMessage } from '../utils/errors';\nimport { useWorkspaceScopedGlobalClient } from './internal/globalWorkspaceScope';\n\n// ============================================================================\n// Platform credential definitions\n// ============================================================================\n\n/** Global-channel platforms a connector type delivers through. */\nexport type ChannelSetupPlatform = 'SLACK' | 'TEAMS' | 'DISCORD' | 'WHATSAPP' | 'WEBHOOK';\n\n/** `ChannelAuthType` values the setup form sends. */\ntype ChannelSetupAuthType = 'BOT_TOKEN' | 'WEBHOOK';\n\nexport interface CredentialFieldDefinition {\n /** Key stored on the channel connection's credentials. */\n key: string;\n label: string;\n description: string;\n placeholder: string;\n /** Rendered as a password input and never shown again after saving. */\n secret: boolean;\n /** Offer a \"Generate\" button producing a random 64-hex-character secret. */\n generatable?: boolean;\n /** Must be an absolute https URL. */\n url?: boolean;\n /** The value must match this pattern (whole value), else `patternMessage`. */\n pattern?: RegExp;\n patternMessage?: string;\n}\n\nexport interface PlatformCredentialDefinition {\n platform: ChannelSetupPlatform;\n authType: ChannelSetupAuthType;\n fields: CredentialFieldDefinition[];\n /** Where to paste the inbound webhook URL on the platform side. */\n inboundHint: string;\n /**\n * False when the platform does not call a URL (Discord: messages arrive\n * over the bot's Gateway connection); the card then shows only the hint.\n */\n usesInboundUrl: boolean;\n}\n\n/** A Microsoft Entra GUID. */\nconst GUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\n\n/**\n * Connector types whose credentials the form can collect directly. The keys\n * are the ones global-channel-svc reads:\n * - Slack sends with `botToken` and verifies inbound requests with\n * `signingSecret`.\n * - Microsoft Teams (an Azure Bot): `appId` is the audience inbound Bot\n * Framework tokens must carry; `appId` + `appPassword` + `tenantId` get the\n * token replies are posted with.\n * - WhatsApp (Cloud API): inbound requests are verified with `appSecret`\n * (X-Hub-Signature-256) and the subscription check with `verifyToken`;\n * replies are sent from `phoneNumberId` with `accessToken`.\n * - Discord: the bot (`botToken`) receives messages over its Gateway\n * connection; `guildId` names the server whose messages this channel takes.\n * - A generic webhook verifies with `webhookSecret` (HMAC-SHA256 hex in\n * `X-Signature`) and POSTs replies to `targetUrl`.\n */\nexport const PLATFORM_CREDENTIALS: Readonly<Record<string, PlatformCredentialDefinition>> = {\n SLACK: {\n platform: 'SLACK',\n authType: 'BOT_TOKEN',\n fields: [\n {\n key: 'botToken',\n label: 'Bot User OAuth Token',\n description: 'Slack app → OAuth & Permissions. Starts with xoxb-.',\n placeholder: 'xoxb-…',\n secret: true,\n },\n {\n key: 'signingSecret',\n label: 'Signing Secret',\n description: 'Slack app → Basic Information → App Credentials.',\n placeholder: 'Signing secret',\n secret: true,\n },\n ],\n inboundHint:\n 'In your Slack app, open Event Subscriptions, turn events on and paste this as the Request URL. Subscribe the bot to message.channels, message.im and app_mention, then reinstall the app.',\n usesInboundUrl: true,\n },\n TEAMS: {\n platform: 'TEAMS',\n authType: 'BOT_TOKEN',\n fields: [\n {\n key: 'appId',\n label: 'Microsoft App ID',\n description:\n 'Azure portal → your Azure Bot → Settings → Configuration → Microsoft App ID (a GUID).',\n placeholder: '00000000-0000-0000-0000-000000000000',\n secret: false,\n pattern: GUID,\n patternMessage: 'Microsoft App ID must be a GUID',\n },\n {\n key: 'appPassword',\n label: 'Client Secret',\n description:\n 'Configuration → Manage Password (or Microsoft Entra ID → App registrations → the bot app) → Certificates & secrets → New client secret. Copy the secret Value, not its ID.',\n placeholder: 'Client secret value',\n secret: true,\n },\n {\n key: 'tenantId',\n label: 'App Tenant ID',\n description:\n 'Azure Bot → Configuration → App Tenant ID (Microsoft Entra ID → Overview → Tenant ID). The bot must be Single Tenant.',\n placeholder: '00000000-0000-0000-0000-000000000000',\n secret: false,\n pattern: GUID,\n patternMessage: 'App Tenant ID must be a GUID',\n },\n ],\n inboundHint:\n 'In the Azure portal open your Azure Bot → Configuration, paste this as the Messaging endpoint and Apply. Under Channels, add Microsoft Teams. Then install the bot in Teams (a Teams app whose bot id is the Microsoft App ID) and message it; in a channel, @mention it.',\n usesInboundUrl: true,\n },\n WHATSAPP: {\n platform: 'WHATSAPP',\n authType: 'BOT_TOKEN',\n fields: [\n {\n key: 'phoneNumberId',\n label: 'Phone Number ID',\n description:\n 'Meta app dashboard → WhatsApp → API Setup → Phone number ID (not the phone number itself).',\n placeholder: '123456789012345',\n secret: false,\n pattern: /^\\d{5,20}$/,\n patternMessage: 'Phone Number ID must be digits only',\n },\n {\n key: 'accessToken',\n label: 'Access Token',\n description:\n 'A permanent token: Meta Business Settings → Users → System users → Generate new token for this app with whatsapp_business_messaging and whatsapp_business_management. The API Setup token expires after 24 hours.',\n placeholder: 'EAA…',\n secret: true,\n },\n {\n key: 'appSecret',\n label: 'App Secret',\n description: 'Meta app dashboard → App settings → Basic → App secret (Show).',\n placeholder: 'App secret',\n secret: true,\n },\n {\n key: 'verifyToken',\n label: 'Verify Token',\n description:\n 'Any value you choose. Paste the same value as the Verify token when you set up the webhook in Meta.',\n placeholder: 'Generate or paste a token',\n secret: true,\n generatable: true,\n },\n ],\n inboundHint:\n 'In the Meta app dashboard open WhatsApp → Configuration → Webhook → Edit. Paste this as the Callback URL and your Verify Token, then Verify and save. Under Webhook fields, subscribe to messages.',\n usesInboundUrl: true,\n },\n DISCORD: {\n platform: 'DISCORD',\n authType: 'BOT_TOKEN',\n fields: [\n {\n key: 'botToken',\n label: 'Bot Token',\n description:\n 'Discord Developer Portal → your application → Bot → Reset Token. Turn on Message Content Intent on the same page.',\n placeholder: 'Bot token',\n secret: true,\n },\n {\n key: 'guildId',\n label: 'Server ID',\n description:\n 'Discord → User Settings → Advanced → Developer Mode on, then right-click your server → Copy Server ID.',\n placeholder: '123456789012345678',\n secret: false,\n pattern: /^\\d{17,20}$/,\n patternMessage: 'Server ID must be a 17-20 digit number',\n },\n ],\n inboundHint:\n 'Discord delivers messages to the bot over its Gateway connection, so no URL is needed: leave Interactions Endpoint URL empty. In the Developer Portal → Bot, turn on Message Content Intent. Invite the bot to your server (OAuth2 → URL Generator → scope bot, permissions View Channels, Send Messages and Read Message History), then message or @mention it.',\n usesInboundUrl: false,\n },\n WEBHOOK: {\n platform: 'WEBHOOK',\n authType: 'WEBHOOK',\n fields: [\n {\n key: 'targetUrl',\n label: 'Reply URL',\n description: 'The bot POSTs its replies to this https URL.',\n placeholder: 'https://example.com/bot-replies',\n secret: false,\n url: true,\n },\n {\n key: 'webhookSecret',\n label: 'Signing Secret',\n description:\n 'Your sender signs each request body with HMAC-SHA256 using this secret and sends the hex digest in the X-Signature header.',\n placeholder: 'Generate or paste a secret',\n secret: true,\n generatable: true,\n },\n ],\n inboundHint:\n 'POST each inbound message here as JSON ({\"event\":\"message\",\"id\",\"sender_id\",\"text\",\"conversation_id\"}), signed with the signing secret in the X-Signature header.',\n usesInboundUrl: true,\n },\n};\n\n/** Connector type → the global-channel platform it uses (none for widget/custom). */\nconst CONNECTOR_PLATFORM: Readonly<Record<string, ChannelSetupPlatform>> = {\n SLACK: 'SLACK',\n TEAMS: 'TEAMS',\n DISCORD: 'DISCORD',\n WHATSAPP: 'WHATSAPP',\n WEBHOOK: 'WEBHOOK',\n};\n\nexport function connectorPlatform(connectorType: string): ChannelSetupPlatform | undefined {\n return CONNECTOR_PLATFORM[connectorType];\n}\n\n/** A random 32-byte secret, hex encoded, from the browser's CSPRNG. */\nexport function generateSigningSecret(): string {\n const bytes = new Uint8Array(32);\n crypto.getRandomValues(bytes);\n return Array.from(bytes, (byte) => byte.toString(16).padStart(2, '0')).join('');\n}\n\n/**\n * Returns the first problem with the entered credentials, or null when they\n * are complete. Every field is required.\n */\nexport function validateCredentials(\n definition: PlatformCredentialDefinition,\n values: Record<string, string>\n): string | null {\n for (const field of definition.fields) {\n const value = values[field.key]?.trim() ?? '';\n if (!value) return `${field.label} is required`;\n if (field.url) {\n let parsed: URL;\n try {\n parsed = new URL(value);\n } catch {\n return `${field.label} must be a valid URL`;\n }\n if (parsed.protocol !== 'https:') return `${field.label} must use https`;\n }\n if (field.pattern && !field.pattern.test(value)) {\n return field.patternMessage ?? `${field.label} is not valid`;\n }\n }\n return null;\n}\n\n// ============================================================================\n// Organization\n// ============================================================================\n\n/**\n * The shell's active organization (the host passes it with the workspace).\n * Global channels belong to an organization, so creating one needs it.\n */\nexport function useActiveOrganizationId(): string | null {\n return useBotlit().organizationId || null;\n}\n\n// ============================================================================\n// Documents\n// ============================================================================\n\nconst GetInboundChannelDocument = gql`\n query BotmanorInboundChannel($id: ID!) {\n getChannel(id: $id) {\n id\n name\n platform\n status\n isConnected\n inboundWorkspaceId\n inboundWebhookUrl\n }\n }\n`;\n\nconst CreateSetupChannelDocument = gql`\n mutation BotmanorCreateSetupChannel($input: CreateChannelInput!) {\n createChannel(input: $input) {\n id\n }\n }\n`;\n\nconst CreateSetupConnectionDocument = gql`\n mutation BotmanorCreateSetupConnection($input: CreateConnectionInput!) {\n createConnection(input: $input) {\n id\n }\n }\n`;\n\nconst DeleteSetupChannelDocument = gql`\n mutation BotmanorDeleteSetupChannel($id: ID!) {\n deleteChannel(id: $id)\n }\n`;\n\nexport interface InboundChannelData {\n id: string;\n name: string;\n platform: string;\n status: string;\n isConnected: boolean;\n inboundWorkspaceId: string | null;\n inboundWebhookUrl: string | null;\n}\n\nfunction toError(cause: unknown, fallback: string): Error {\n const message = extractGraphqlFailureMessage(cause);\n if (message) return new Error(message, { cause });\n return cause instanceof Error ? cause : new Error(fallback, { cause });\n}\n\n/**\n * Apollo v4 resolves (rather than rejects) with `error` set when the server\n * answers with GraphQL errors; surface those as a failure like a rejection.\n */\nfunction throwIfOperationFailed(result: unknown, fallback: string): void {\n const operationError = (result as { error?: unknown }).error;\n if (operationError != null) throw toError(operationError, fallback);\n}\n\n// ============================================================================\n// Hook: useInboundChannel\n// ============================================================================\n\ninterface UseInboundChannelResult {\n data: InboundChannelData | null;\n loading: boolean;\n error: Error | undefined;\n refetch: () => Promise<void>;\n}\n\n/** The global channel a connector names, with its inbound webhook URL. */\nexport function useInboundChannel(channelId: string | null | undefined): UseInboundChannelResult {\n const { client, context } = useWorkspaceScopedGlobalClient();\n const [data, setData] = useState<InboundChannelData | null>(null);\n const [loading, setLoading] = useState(false);\n const [error, setError] = useState<Error | undefined>(undefined);\n /** Only the latest request may set state: a slower answer for a previous channel is dropped. */\n const latestRequest = useRef(0);\n\n const refetch = useCallback(async () => {\n const request = ++latestRequest.current;\n const isLatest = () => request === latestRequest.current;\n setData(null);\n setError(undefined);\n if (!channelId) return;\n setLoading(true);\n try {\n const result = await client.query<{ getChannel: InboundChannelData | null }>({\n query: GetInboundChannelDocument,\n variables: { id: channelId },\n fetchPolicy: 'network-only',\n context,\n });\n throwIfOperationFailed(result, 'Failed to load the channel');\n if (isLatest()) setData(result.data?.getChannel ?? null);\n } catch (cause) {\n if (isLatest()) setError(toError(cause, 'Failed to load the channel'));\n } finally {\n if (isLatest()) setLoading(false);\n }\n }, [channelId, client, context]);\n\n useEffect(() => {\n void refetch();\n }, [refetch]);\n\n return { data, loading, error, refetch };\n}\n\n// ============================================================================\n// Hook: useProvisionChannel\n// ============================================================================\n\nexport interface ProvisionChannelInput {\n name: string;\n description?: string;\n organizationId: string;\n definition: PlatformCredentialDefinition;\n credentials: Record<string, string>;\n}\n\ninterface UseProvisionChannelResult {\n /** Creates the global channel and its connection; resolves to the channel id. */\n provision: (input: ProvisionChannelInput) => Promise<string>;\n /** Deletes a channel `provision` created (rollback when the connector fails). */\n discard: (channelId: string) => Promise<void>;\n loading: boolean;\n}\n\nexport function useProvisionChannel(): UseProvisionChannelResult {\n const { client, context } = useWorkspaceScopedGlobalClient();\n const [loading, setLoading] = useState(false);\n\n const discard = useCallback(\n async (channelId: string) => {\n const result = await client.mutate({\n mutation: DeleteSetupChannelDocument,\n variables: { id: channelId },\n context,\n });\n throwIfOperationFailed(result, 'Failed to delete the channel');\n },\n [client, context]\n );\n\n const provision = useCallback(\n async ({\n name,\n description,\n organizationId,\n definition,\n credentials,\n }: ProvisionChannelInput): Promise<string> => {\n setLoading(true);\n try {\n let channelId: string | undefined;\n try {\n const created = await client.mutate<{ createChannel: { id: string } | null }>({\n mutation: CreateSetupChannelDocument,\n variables: {\n input: {\n name,\n description: description || undefined,\n platform: definition.platform,\n channelType: 'COMMUNICATION',\n organizationId,\n },\n },\n context,\n });\n throwIfOperationFailed(created, 'Failed to create the channel');\n channelId = created.data?.createChannel?.id;\n } catch (cause) {\n throw toError(cause, 'Failed to create the channel');\n }\n if (!channelId) throw new Error('Failed to create the channel');\n\n const trimmed = Object.fromEntries(\n definition.fields.map((field) => [field.key, credentials[field.key]?.trim() ?? ''])\n );\n try {\n const connected = await client.mutate({\n mutation: CreateSetupConnectionDocument,\n variables: {\n input: { channelId, authType: definition.authType, credentials: trimmed },\n },\n context,\n });\n throwIfOperationFailed(connected, 'Failed to save the channel credentials');\n } catch (cause) {\n // A channel without its credentials can never deliver: remove it so\n // a retry starts clean instead of leaving an orphan behind.\n await discard(channelId).catch(() => undefined);\n throw toError(cause, 'Failed to save the channel credentials');\n }\n return channelId;\n } finally {\n setLoading(false);\n }\n },\n [client, context, discard]\n );\n\n return { provision, discard, loading };\n}\n"],"mappings":";;;;;;AAoEA,IAAMA,IAAO,mEAkBAC,IAA+E;CAC1F,OAAO;EACL,UAAU;EACV,UAAU;EACV,QAAQ,CACN;GACE,KAAK;GACL,OAAO;GACP,aAAa;GACb,aAAa;GACb,QAAQ;EACV,GACA;GACE,KAAK;GACL,OAAO;GACP,aAAa;GACb,aAAa;GACb,QAAQ;EACV,CACF;EACA,aACE;EACF,gBAAgB;CAClB;CACA,OAAO;EACL,UAAU;EACV,UAAU;EACV,QAAQ;GACN;IACE,KAAK;IACL,OAAO;IACP,aACE;IACF,aAAa;IACb,QAAQ;IACR,SAASD;IACT,gBAAgB;GAClB;GACA;IACE,KAAK;IACL,OAAO;IACP,aACE;IACF,aAAa;IACb,QAAQ;GACV;GACA;IACE,KAAK;IACL,OAAO;IACP,aACE;IACF,aAAa;IACb,QAAQ;IACR,SAASA;IACT,gBAAgB;GAClB;EACF;EACA,aACE;EACF,gBAAgB;CAClB;CACA,UAAU;EACR,UAAU;EACV,UAAU;EACV,QAAQ;GACN;IACE,KAAK;IACL,OAAO;IACP,aACE;IACF,aAAa;IACb,QAAQ;IACR,SAAS;IACT,gBAAgB;GAClB;GACA;IACE,KAAK;IACL,OAAO;IACP,aACE;IACF,aAAa;IACb,QAAQ;GACV;GACA;IACE,KAAK;IACL,OAAO;IACP,aAAa;IACb,aAAa;IACb,QAAQ;GACV;GACA;IACE,KAAK;IACL,OAAO;IACP,aACE;IACF,aAAa;IACb,QAAQ;IACR,aAAa;GACf;EACF;EACA,aACE;EACF,gBAAgB;CAClB;CACA,SAAS;EACP,UAAU;EACV,UAAU;EACV,QAAQ,CACN;GACE,KAAK;GACL,OAAO;GACP,aACE;GACF,aAAa;GACb,QAAQ;EACV,GACA;GACE,KAAK;GACL,OAAO;GACP,aACE;GACF,aAAa;GACb,QAAQ;GACR,SAAS;GACT,gBAAgB;EAClB,CACF;EACA,aACE;EACF,gBAAgB;CAClB;CACA,SAAS;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