@wix/mcp 1.0.5 → 1.0.6

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 (41) hide show
  1. package/bin.js +1 -1
  2. package/build/bin.d.ts +3 -3
  3. package/build/bin.js +657 -82
  4. package/build/chunk-YRLMZUQM.js +1834 -0
  5. package/build/index.d.ts +30 -6
  6. package/build/index.js +193 -6
  7. package/package.json +7 -4
  8. package/build/api-call/index.d.ts +0 -2
  9. package/build/api-call/index.js +0 -124
  10. package/build/cli-tools/cli.d.ts +0 -4
  11. package/build/cli-tools/cli.js +0 -338
  12. package/build/cli-tools/utils.d.ts +0 -2
  13. package/build/cli-tools/utils.js +0 -25
  14. package/build/docs/docs.d.ts +0 -4
  15. package/build/docs/docs.js +0 -448
  16. package/build/docs/long-content.d.ts +0 -1
  17. package/build/docs/long-content.js +0 -1
  18. package/build/docs/semanticSearch.d.ts +0 -10
  19. package/build/docs/semanticSearch.js +0 -108
  20. package/build/docs/semanticSearch.test.d.ts +0 -1
  21. package/build/docs/semanticSearch.test.js +0 -459
  22. package/build/interactive-command-tools/eventually.d.ts +0 -6
  23. package/build/interactive-command-tools/eventually.js +0 -15
  24. package/build/interactive-command-tools/handleStdout.d.ts +0 -13
  25. package/build/interactive-command-tools/handleStdout.js +0 -75
  26. package/build/interactive-command-tools/interactive-command-utils.d.ts +0 -7
  27. package/build/interactive-command-tools/interactive-command-utils.js +0 -75
  28. package/build/logger.d.ts +0 -10
  29. package/build/logger.js +0 -61
  30. package/build/resources/docs.d.ts +0 -2
  31. package/build/resources/docs.js +0 -45
  32. package/build/sentry.d.ts +0 -1
  33. package/build/sentry.js +0 -10
  34. package/build/support/index.d.ts +0 -2
  35. package/build/support/index.js +0 -32
  36. package/build/tool-utils.d.ts +0 -1
  37. package/build/tool-utils.js +0 -29
  38. package/build/tool-utils.spec.d.ts +0 -1
  39. package/build/tool-utils.spec.js +0 -119
  40. package/build/wix-mcp-server.d.ts +0 -13
  41. package/build/wix-mcp-server.js +0 -51
@@ -0,0 +1,1834 @@
1
+ // src/logger.ts
2
+ import fs from "fs/promises";
3
+ import path from "path";
4
+ import { homedir } from "os";
5
+ var createNullLogger = () => {
6
+ return {
7
+ log: () => {
8
+ },
9
+ error: () => {
10
+ }
11
+ };
12
+ };
13
+ var createStdErrLogger = () => {
14
+ return {
15
+ log: (data) => {
16
+ console.error(data);
17
+ },
18
+ error: (data) => {
19
+ console.error(data);
20
+ }
21
+ };
22
+ };
23
+ var createMcpServerLogger = (server) => {
24
+ return {
25
+ log: (data) => {
26
+ server.server.sendLoggingMessage({ level: "info", data });
27
+ },
28
+ error: (data) => {
29
+ server.server.sendLoggingMessage({ level: "error", data });
30
+ }
31
+ };
32
+ };
33
+ var createFileLogger = () => {
34
+ const filePath = path.join(homedir(), "wix-mcp-log.txt");
35
+ const date = (/* @__PURE__ */ new Date()).toLocaleString("en-US", { timeZone: "Asia/Jerusalem" }).replace(/,/g, "");
36
+ return {
37
+ log: (...data) => {
38
+ const message = `[info] ${date} - ${data.join(" ")}`;
39
+ fs.appendFile(filePath, `${message}
40
+ `);
41
+ },
42
+ error: (...data) => {
43
+ const message = `[error] ${date} - ${data.join(" ")}`;
44
+ fs.appendFile(filePath, `${message}
45
+ `);
46
+ }
47
+ };
48
+ };
49
+ var logger = createNullLogger();
50
+ var attachMcpServerLogger = (server) => {
51
+ const mcpLogger = createMcpServerLogger(server);
52
+ logger.log = mcpLogger.log;
53
+ logger.error = mcpLogger.error;
54
+ };
55
+ var attachStdErrLogger = () => {
56
+ const stdErrLogger = createStdErrLogger();
57
+ logger.log = stdErrLogger.log;
58
+ logger.error = stdErrLogger.error;
59
+ };
60
+ var attachFileLogger = () => {
61
+ const fileLogger = createFileLogger();
62
+ logger.log = fileLogger.log;
63
+ logger.error = fileLogger.error;
64
+ };
65
+
66
+ // src/docs/docs.ts
67
+ import { z } from "zod";
68
+
69
+ // src/docs/semanticSearch.ts
70
+ var MAX_CONTENT_LENGTH = 1e4;
71
+ var DEFAULT_MAX_RESULTS = 10;
72
+ var runSemanticSearch = async (toolName, toolParams, maxResults = 20, rerank = false) => {
73
+ const startTime = (/* @__PURE__ */ new Date()).getTime();
74
+ const url = new URL(
75
+ `https://www.wixapis.com/mcp-docs-search/v1/search?maxResults=${maxResults}&rerank=${rerank}`
76
+ );
77
+ if (toolName === "SDK") {
78
+ url.searchParams.append("kbName", "SDK_SCHEMAS_KB_ID");
79
+ url.searchParams.append("kbName", "SDK_DOCS_KB_ID");
80
+ } else if (toolName === "REST" || toolName === "BUSINESS_SOLUTIONS") {
81
+ if (toolName === "REST") {
82
+ url.searchParams.append("kbName", "REST_METHODS_KB_ID");
83
+ }
84
+ url.searchParams.append("kbName", "REST_DOCS_KB_ID");
85
+ url.searchParams.append("kbName", "MCP_REST_RECIPES_KB_ID");
86
+ } else if (toolName === "WDS") {
87
+ url.searchParams.append("kbName", "WDS_DOCS_KB_ID");
88
+ } else if (toolName === "BUILD_APPS") {
89
+ url.searchParams.append("kbName", "BUILD_APPS_KB_ID");
90
+ } else if (toolName === "WIX_HEADLESS") {
91
+ url.searchParams.append("kbName", "HEADLESS_KB_ID");
92
+ }
93
+ for (const [key, value] of Object.entries(toolParams)) {
94
+ url.searchParams.append(key, value);
95
+ }
96
+ logger.log("Running RAG search", url.toString());
97
+ const response = await fetch(url.toString(), {
98
+ headers: {
99
+ "Content-Type": "application/json",
100
+ "x-time-budget": "180000",
101
+ "x-wix-time-budget": "180000"
102
+ }
103
+ });
104
+ if (!response.ok) {
105
+ logger.error(`Failed to run rag search: ${response.statusText}`);
106
+ throw new Error(`Failed to run rag search: ${response.statusText}`);
107
+ }
108
+ const data = await response.json();
109
+ const endTime = (/* @__PURE__ */ new Date()).getTime();
110
+ const timeTaskFormatted = (endTime - startTime) / 1e3;
111
+ logger.log(
112
+ "Ran RAG search successfully with params",
113
+ JSON.stringify(toolParams),
114
+ timeTaskFormatted,
115
+ typeof data
116
+ );
117
+ return data?.results;
118
+ };
119
+ var getContentFromChunkedContent = (chunkedContent) => {
120
+ let content = "";
121
+ for (const chunk of chunkedContent) {
122
+ if (content.length + chunk.length > MAX_CONTENT_LENGTH) {
123
+ break;
124
+ }
125
+ content += "\n\n---\n\n" + chunk;
126
+ }
127
+ return content;
128
+ };
129
+ var formatResultsContent = (resultsFromKbs, maxResults, linesInEachResult = void 0) => {
130
+ const allResults = Object.entries(resultsFromKbs).map(([, { results }]) => results).flat();
131
+ if (allResults.length === 0) {
132
+ throw new Error("No result from search");
133
+ }
134
+ const sortedResults = allResults.sort(
135
+ (a, b) => b.scoresInfo.overallMatchScore - a.scoresInfo.overallMatchScore
136
+ );
137
+ const topResults = sortedResults.slice(0, maxResults);
138
+ const concatenatedContent = topResults.map((result) => {
139
+ let newContent = result.entry.content;
140
+ if (linesInEachResult) {
141
+ const totalLines = newContent.split("\n").length;
142
+ const linesToTake = Math.min(linesInEachResult, totalLines);
143
+ newContent = newContent.split("\n").slice(0, linesToTake).join("\n");
144
+ const moreLines = totalLines - linesToTake;
145
+ const moreLinesText = moreLines > 0 ? `
146
+
147
+ ... ${moreLines} more lines ...` : "";
148
+ newContent = `${newContent}${moreLinesText}`;
149
+ }
150
+ return {
151
+ ...result,
152
+ entry: {
153
+ ...result.entry,
154
+ content: newContent
155
+ }
156
+ };
157
+ }).map((result) => {
158
+ const content = result.entry.content;
159
+ const chunkedContent = result.entry.chunkedContent;
160
+ if (content.length > MAX_CONTENT_LENGTH) {
161
+ logger.log(`Content is too long, using chunked content`, {
162
+ contentLength: content.length,
163
+ chunkedContentLength: chunkedContent.length
164
+ });
165
+ return getContentFromChunkedContent(chunkedContent);
166
+ }
167
+ return content;
168
+ }).join("\n\n---\n\n");
169
+ return concatenatedContent;
170
+ };
171
+ var runSemanticSearchAndFormat = async ({
172
+ toolName,
173
+ toolParams,
174
+ maxResults = DEFAULT_MAX_RESULTS,
175
+ rerank,
176
+ linesInEachResult
177
+ }) => {
178
+ const results = await runSemanticSearch(
179
+ toolName,
180
+ toolParams,
181
+ maxResults,
182
+ rerank
183
+ );
184
+ const maxResultsToUse = Math.min(maxResults, DEFAULT_MAX_RESULTS);
185
+ return formatResultsContent(results, maxResultsToUse, linesInEachResult);
186
+ };
187
+
188
+ // src/docs/docs.ts
189
+ import { captureException } from "@sentry/node";
190
+ var VALID_DOCS_TOOLS = [
191
+ "WDS",
192
+ "REST",
193
+ "SDK",
194
+ "BUILD_APPS",
195
+ "WIX_HEADLESS",
196
+ "BUSINESS_SOLUTIONS"
197
+ ];
198
+ var addDocsTools = (server, allowedTools = [
199
+ "WDS",
200
+ "REST",
201
+ "SDK",
202
+ "BUILD_APPS",
203
+ "WIX_HEADLESS",
204
+ "BUSINESS_SOLUTIONS"
205
+ ]) => {
206
+ if (allowedTools.includes("WDS")) {
207
+ server.tool(
208
+ "SearchWixWDSDocumentation",
209
+ [
210
+ "Searches the Wix Design System Documentation for components and patterns.",
211
+ "Use this tool when you need to understand or implement UI components and design patterns in a Wix project.",
212
+ "Search for specific component names, patterns, or UI requirements.",
213
+ "If you can't find what you need, try to rephrase your search term or use bigger maxResults value."
214
+ ].join("\n"),
215
+ {
216
+ searchTerm: z.string().describe(
217
+ "The search term to search for in the Wix Design System Documentation"
218
+ ),
219
+ maxResults: z.number().describe(
220
+ "The maximum number of results to return, default is 5, max is 15"
221
+ ).min(1).max(15).optional().default(10)
222
+ },
223
+ async ({ searchTerm, maxResults }, { panorama }) => {
224
+ try {
225
+ logger.log(`Searching for ${searchTerm} in Wix WDS`);
226
+ const result = await runSemanticSearchAndFormat({
227
+ toolName: "WDS",
228
+ toolParams: {
229
+ searchTerm
230
+ },
231
+ maxResults: Math.max(1, Math.min(maxResults ?? 5, 15))
232
+ });
233
+ return {
234
+ content: [
235
+ {
236
+ type: "text",
237
+ text: result
238
+ }
239
+ ]
240
+ };
241
+ } catch (error) {
242
+ panorama.errorMonitor().reportError(error);
243
+ captureException(error, {
244
+ tags: {
245
+ componentId: "SearchWixWDSDocumentation",
246
+ toolName: "SearchWixWDSDocumentation"
247
+ }
248
+ });
249
+ logger.error(
250
+ `Error searching for ${searchTerm} in Wix WDS: ${error}`
251
+ );
252
+ return {
253
+ isError: true,
254
+ content: [{ type: "text", text: "Error: " + error.message }]
255
+ };
256
+ }
257
+ }
258
+ );
259
+ }
260
+ if (allowedTools.includes("REST")) {
261
+ server.tool(
262
+ "SearchWixRESTDocumentation",
263
+ [
264
+ "Searches the official Wix REST API documentation.",
265
+ "Use this tool whenever you need to to interact with the Wix platform via HTTP requests.",
266
+ "Specify the API endpoint, resource, or action you need information about (e.g., 'get site details endpoint', 'create data collection', 'update product API', 'REST authentication').",
267
+ "If you can't find what you need, try to rephrase your search term or use bigger maxResults value."
268
+ ].join("\n"),
269
+ {
270
+ searchTerm: z.string().describe(
271
+ "The search term to search for in the Wix REST API Documentation"
272
+ ),
273
+ maxResults: z.number().describe(
274
+ "The maximum number of results to return, default is 5, max is 15"
275
+ ).min(1).max(15).optional().default(10)
276
+ },
277
+ async ({ searchTerm, maxResults }, { panorama }) => {
278
+ try {
279
+ logger.log(`Searching for ${searchTerm} in Wix REST API`);
280
+ const result = await runSemanticSearchAndFormat({
281
+ toolName: "REST",
282
+ toolParams: {
283
+ searchTerm
284
+ },
285
+ maxResults: Math.max(1, Math.min(maxResults ?? 5, 15)),
286
+ linesInEachResult: 15
287
+ });
288
+ return {
289
+ content: [
290
+ {
291
+ type: "text",
292
+ text: result
293
+ },
294
+ {
295
+ type: "text",
296
+ text: "Next, you MUST use the ReadFullDocsArticle tool if you want to read the full documentation for a specific article or method."
297
+ }
298
+ ]
299
+ };
300
+ } catch (error) {
301
+ panorama.errorMonitor().reportError(error);
302
+ captureException(error, {
303
+ tags: {
304
+ componentId: "SearchWixRESTDocumentation",
305
+ toolName: "SearchWixRESTDocumentation"
306
+ }
307
+ });
308
+ logger.error(
309
+ `Error searching for ${searchTerm} in Wix REST API: ${error}`
310
+ );
311
+ return {
312
+ isError: true,
313
+ content: [{ type: "text", text: "Error: " + error.message }]
314
+ };
315
+ }
316
+ }
317
+ );
318
+ }
319
+ if (allowedTools.includes("BUSINESS_SOLUTIONS")) {
320
+ server.tool(
321
+ "WixBusinessFlowsDocumentation",
322
+ [
323
+ "This tool provides step-by-step recipes for setting up complex Wix business solutions that involve multiple API calls.",
324
+ "It excels at guiding the creation of features like booking systems with payments.",
325
+ "For example, it can guide the setup of a service in Wix Bookings where customers can pay using Wix Payments, such as creating a bookable yoga class",
326
+ "It searches the Wix Business Solutions documentation for these integrated workflows involving services, bookings, payments, stores, blogs, and more.",
327
+ "This tool returns a list of articles that are potentially relevant to the input search term.",
328
+ "**IMPORTANT NOTES:**",
329
+ "1. Before attempting to implement a multi step API calls on Wix, YOU MUST TRY THIS TOOL FIRST.",
330
+ "2. Out of the returned list of articles that you will receive, you MUST select the most relevant one and use the ReadFullDocsArticle tool to fetch it."
331
+ ].join("\n"),
332
+ {
333
+ searchTerm: z.string().describe(
334
+ 'The search term for the required sample flow (e.g. "setup a new business")'
335
+ ),
336
+ maxResults: z.number().describe(
337
+ "The maximum number of results to return, default is 5, max is 15"
338
+ ).min(1).max(15).optional().default(5)
339
+ },
340
+ async ({ searchTerm, maxResults }, { panorama }) => {
341
+ try {
342
+ logger.log(`Searching for ${searchTerm} in Wix Sample Flows`);
343
+ const result = await runSemanticSearchAndFormat({
344
+ toolName: "BUSINESS_SOLUTIONS",
345
+ toolParams: {
346
+ searchTerm: "**RECIPE**: Business Recipes - full setup flow for::: " + searchTerm
347
+ },
348
+ maxResults: Math.max(1, Math.min(maxResults ?? 5, 15))
349
+ });
350
+ return {
351
+ content: [
352
+ {
353
+ type: "text",
354
+ text: result
355
+ },
356
+ {
357
+ type: "text",
358
+ text: `Out of the included list of articles, you **MUST** select the one that is most relevant to the user's request and use the ReadFullDocsArticle tool to fetch it.`
359
+ }
360
+ ]
361
+ };
362
+ } catch (error) {
363
+ panorama.errorMonitor().reportError(error);
364
+ captureException(error, {
365
+ tags: {
366
+ componentId: "SearchWixSampleFlowsDocumentation",
367
+ toolName: "SearchWixSampleFlowsDocumentation"
368
+ }
369
+ });
370
+ logger.error(
371
+ `Error searching for ${searchTerm} in Wix Sample Flows: ${error}`
372
+ );
373
+ return {
374
+ isError: true,
375
+ content: [{ type: "text", text: "Error: " + error.message }]
376
+ };
377
+ }
378
+ }
379
+ );
380
+ }
381
+ if (allowedTools.includes("SDK")) {
382
+ server.tool(
383
+ "SearchWixSDKDocumentation",
384
+ [
385
+ "Searches the official Wix javascript SDK documentation.",
386
+ "Use this tool whenever you need to write or modify Wix related SDK code.",
387
+ "Specify the SDK module, function, or feature you need information about (e.g., 'how to query all items from a data collection?', 'how to use wix-stores-backend', 'authentication methods in the SDK').",
388
+ "If you can't find what you need, try to rephrase your search term or use bigger maxResults value."
389
+ ].join("\n"),
390
+ {
391
+ searchTerm: z.string().describe(
392
+ "The search term to search for in the Wix SDK Documentation"
393
+ ),
394
+ maxResults: z.number().describe(
395
+ "The maximum number of results to return, default is 5, max is 15"
396
+ ).min(1).max(15).optional().default(5)
397
+ },
398
+ async ({ searchTerm, maxResults }, { panorama }) => {
399
+ try {
400
+ logger.log(`Searching for ${searchTerm} in Wix SDK`);
401
+ panorama.transaction("SearchWixSDKDocumentation").start({ maxResults });
402
+ const result = await runSemanticSearchAndFormat({
403
+ toolName: "SDK",
404
+ toolParams: {
405
+ searchTerm
406
+ },
407
+ maxResults: Math.max(1, Math.min(maxResults ?? 5, 15)),
408
+ linesInEachResult: 15
409
+ });
410
+ panorama.transaction("SearchWixSDKDocumentation").finish({ maxResults });
411
+ return {
412
+ content: [
413
+ {
414
+ type: "text",
415
+ text: result
416
+ },
417
+ {
418
+ type: "text",
419
+ text: "Next, you MUST use ReadFullDocsArticle tool if you want to read full documentation for a specific article or method."
420
+ }
421
+ ]
422
+ };
423
+ } catch (error) {
424
+ panorama.errorMonitor().reportError(error);
425
+ captureException(error, {
426
+ tags: {
427
+ componentId: "SearchWixSDKDocumentation",
428
+ toolName: "SearchWixSDKDocumentation"
429
+ }
430
+ });
431
+ logger.error(
432
+ `Error searching for ${searchTerm} in Wix SDK: ${error}`
433
+ );
434
+ return {
435
+ isError: true,
436
+ content: [{ type: "text", text: "Error: " + error.message }]
437
+ };
438
+ }
439
+ }
440
+ );
441
+ }
442
+ if (allowedTools.includes("BUILD_APPS")) {
443
+ server.tool(
444
+ "SearchBuildAppsDocumentation",
445
+ [
446
+ "Searches the official Build Apps documentation.",
447
+ "Use this tool when you need to understand or implement Wix CLI applications related code.",
448
+ "The search term should be a specific Wix CLI command or specific topic related to Wix CLI applications or its ecosystem (e.g. deployment, creating new extensions etc).",
449
+ "If you can't find what you need, try to rephrase your search term or use bigger maxResults value."
450
+ ].join("\n"),
451
+ {
452
+ searchTerm: z.string().describe(
453
+ "The search term to search for in the Build Apps Documentation"
454
+ ),
455
+ maxResults: z.number().describe(
456
+ "The maximum number of results to return, default is 5, max is 15"
457
+ ).min(1).max(15).optional().default(5)
458
+ },
459
+ async ({ searchTerm, maxResults }, { panorama }) => {
460
+ try {
461
+ logger.log(`Searching for ${searchTerm} in Build Apps`);
462
+ const result = await runSemanticSearchAndFormat({
463
+ toolName: "BUILD_APPS",
464
+ toolParams: {
465
+ searchTerm: `wix cli docs for ${searchTerm}`
466
+ },
467
+ maxResults: Math.max(1, Math.min(maxResults ?? 5, 15))
468
+ });
469
+ return {
470
+ content: [
471
+ {
472
+ type: "text",
473
+ text: result
474
+ }
475
+ ]
476
+ };
477
+ } catch (error) {
478
+ panorama.errorMonitor().reportError(error);
479
+ captureException(error, {
480
+ tags: {
481
+ componentId: "SearchBuildAppsDocumentation",
482
+ toolName: "SearchBuildAppsDocumentation"
483
+ }
484
+ });
485
+ logger.error(
486
+ `Error searching for ${searchTerm} in Build Apps: ${error}`
487
+ );
488
+ return {
489
+ content: [{ type: "text", text: "Error: " + error.message }]
490
+ };
491
+ }
492
+ }
493
+ );
494
+ }
495
+ if (allowedTools.includes("WIX_HEADLESS")) {
496
+ server.tool(
497
+ "SearchWixHeadlessDocumentation",
498
+ [
499
+ "Searches the official Wix Headless Documentation.",
500
+ "Use this tool when you need to understand or implement Headless related code.",
501
+ "The search term should be a specific Wix Headless topic or feature you need information about.",
502
+ "If you can't find what you need, try to rephrase your search term or use bigger maxResults value."
503
+ ].join("\n"),
504
+ {
505
+ searchTerm: z.string().describe(
506
+ "The search term to search for in the Headless Documentation"
507
+ ),
508
+ maxResults: z.number().describe(
509
+ "The maximum number of results to return, default is 5, max is 15"
510
+ ).min(1).max(15).optional().default(5)
511
+ },
512
+ async ({ searchTerm, maxResults }, { panorama }) => {
513
+ try {
514
+ logger.log(`Searching for ${searchTerm} in Headless`);
515
+ const result = await runSemanticSearchAndFormat({
516
+ toolName: "WIX_HEADLESS",
517
+ toolParams: {
518
+ searchTerm
519
+ },
520
+ maxResults: Math.max(1, Math.min(maxResults ?? 5, 15))
521
+ });
522
+ return {
523
+ content: [
524
+ {
525
+ type: "text",
526
+ text: result
527
+ }
528
+ ]
529
+ };
530
+ } catch (error) {
531
+ panorama.errorMonitor().reportError(error);
532
+ captureException(error, {
533
+ tags: {
534
+ componentId: "SearchWixHeadlessDocumentation",
535
+ toolName: "SearchWixHeadlessDocumentation"
536
+ }
537
+ });
538
+ logger.error(
539
+ `Error searching for ${searchTerm} in Wix Headless: ${error}`
540
+ );
541
+ return {
542
+ content: [{ type: "text", text: "Error: " + error.message }]
543
+ };
544
+ }
545
+ }
546
+ );
547
+ }
548
+ server.tool(
549
+ "ReadFullDocsArticle",
550
+ [
551
+ "Fetches the full Wix docs article or method article.",
552
+ "Use this tool when you read a summary of a docs article or method article, you have the docs url and want to read the full article."
553
+ ].join("\n"),
554
+ {
555
+ articleUrl: z.string().describe(
556
+ "The URL of the docs article or method article to fetch. Should be something like https://dev.wix.com/docs/.../.../..."
557
+ )
558
+ },
559
+ async ({ articleUrl }) => {
560
+ try {
561
+ const articleContent = await fetchArticleContent(articleUrl, "article");
562
+ if (!articleContent) {
563
+ throw new Error("Article content is empty");
564
+ }
565
+ return {
566
+ content: [
567
+ {
568
+ type: "text",
569
+ text: articleContent
570
+ },
571
+ {
572
+ type: "text",
573
+ text: [
574
+ "---",
575
+ "Next, if you are dealing with a method - you MUST call ReadFullDocsMethodSchema tool - it will give you the full request schema for the method."
576
+ ].join("\n")
577
+ }
578
+ ]
579
+ };
580
+ } catch (error) {
581
+ logger.error(
582
+ `Error fetching article content or method schema for ${articleUrl}: ${error}`
583
+ );
584
+ return {
585
+ content: [
586
+ {
587
+ type: "text",
588
+ text: "Could not fetch article content, you should try completing the task without it."
589
+ }
590
+ ]
591
+ };
592
+ }
593
+ }
594
+ );
595
+ server.tool(
596
+ "ReadFullDocsMethodSchema",
597
+ [
598
+ "Fetches the full method schema for a given method. Always use it before calling the method.",
599
+ "This will give you the entire request/response schema with all the fields and their descriptions."
600
+ ].join("\n"),
601
+ {
602
+ articleUrl: z.string().describe(
603
+ "The URL of the documentation to fetch. Should be something like https://dev.wix.com/docs/.../.../..."
604
+ )
605
+ },
606
+ async ({ articleUrl }) => {
607
+ try {
608
+ const articleContent = await fetchArticleContent(
609
+ articleUrl,
610
+ "methodSchema"
611
+ );
612
+ if (!articleContent) {
613
+ throw new Error("Method schema is empty");
614
+ }
615
+ return {
616
+ content: [
617
+ {
618
+ type: "text",
619
+ text: articleContent
620
+ }
621
+ ]
622
+ };
623
+ } catch (error) {
624
+ logger.error(
625
+ `Error fetching method schema for ${articleUrl}: ${error}`
626
+ );
627
+ return {
628
+ content: [
629
+ {
630
+ type: "text",
631
+ text: "Could not fetch method schema, you should try completing the task without it."
632
+ }
633
+ ]
634
+ };
635
+ }
636
+ }
637
+ );
638
+ };
639
+ async function fetchArticleContent(articleUrl, mode) {
640
+ const url = new URL(`https://dev.wix.com/digor/api/get-article-content`);
641
+ url.searchParams.set("articleUrl", articleUrl);
642
+ const schema = mode === "methodSchema" ? "true" : "false";
643
+ url.searchParams.set("schema", schema);
644
+ logger.log(`Fetching resource from docs ${url.toString()}`);
645
+ const response = await fetch(url.toString());
646
+ const data = await response.json();
647
+ logger.log(`Fetched resource from docs: ${data.articleContent}`);
648
+ return data.articleContent;
649
+ }
650
+
651
+ // src/tool-utils.ts
652
+ var safeParseJSON = (text) => {
653
+ try {
654
+ return JSON.parse(text);
655
+ } catch {
656
+ return text;
657
+ }
658
+ };
659
+ var handleWixAPIResponse = async (response) => {
660
+ const responseText = await response.text();
661
+ const responseData = safeParseJSON(responseText);
662
+ if (!response.ok) {
663
+ const requestId = response.headers.get("x-wix-request-id");
664
+ const errorDetails = typeof responseData === "object" ? JSON.stringify(responseData) : responseData;
665
+ throw new Error(
666
+ [
667
+ `Failed to call Wix API: ${response.status} ${response.statusText}.`,
668
+ requestId ? `request id: ${requestId}` : "",
669
+ // Wix 404 for API does not exist is huge (generic 404 page) and loaded to the context
670
+ response.status === 404 && errorDetails.includes("<html") ? "Not found" : errorDetails
671
+ ].filter((str) => !!str).join("\n")
672
+ );
673
+ }
674
+ return responseData;
675
+ };
676
+
677
+ // src/wix-mcp-server.ts
678
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
679
+
680
+ // ../../node_modules/@wix/panorama-common-shared/dist/esm/types/enum-types.js
681
+ var AlertType;
682
+ (function(AlertType2) {
683
+ AlertType2["SuccessRate"] = "SuccessRate";
684
+ AlertType2["SuccessRateQuality"] = "SuccessRateQuality";
685
+ AlertType2["Duration"] = "Duration";
686
+ AlertType2["ErrorRate"] = "ErrorRate";
687
+ })(AlertType || (AlertType = {}));
688
+ var AlertStatus;
689
+ (function(AlertStatus2) {
690
+ AlertStatus2["Alerting"] = "alerting";
691
+ AlertStatus2["Ok"] = "ok";
692
+ })(AlertStatus || (AlertStatus = {}));
693
+ var LogLevel;
694
+ (function(LogLevel2) {
695
+ LogLevel2["Info"] = "INFO";
696
+ LogLevel2["Warn"] = "WARN";
697
+ LogLevel2["Error"] = "ERROR";
698
+ LogLevel2["Debug"] = "DEBUG";
699
+ })(LogLevel || (LogLevel = {}));
700
+ var TransactionAction;
701
+ (function(TransactionAction2) {
702
+ TransactionAction2["Start"] = "START";
703
+ TransactionAction2["Finish"] = "FINISH";
704
+ })(TransactionAction || (TransactionAction = {}));
705
+ var InternalTransactions = {
706
+ ComponentLoad: "PANORAMA_COMPONENT_LOAD",
707
+ ComponentPhase: "PANORAMA_COMPONENT_PHASE"
708
+ };
709
+ var Platform;
710
+ (function(Platform2) {
711
+ Platform2["Standalone"] = "standalone";
712
+ Platform2["BusinessManager"] = "business-manager";
713
+ Platform2["Viewer"] = "viewer";
714
+ Platform2["Editor"] = "editor";
715
+ Platform2["EditorSettings"] = "editor:settings";
716
+ Platform2["Mobile"] = "mobile";
717
+ Platform2["Standards"] = "standards";
718
+ })(Platform || (Platform = {}));
719
+ var ErrorSeverity;
720
+ (function(ErrorSeverity2) {
721
+ ErrorSeverity2["Fatal"] = "fatal";
722
+ ErrorSeverity2["Error"] = "error";
723
+ ErrorSeverity2["Warning"] = "warning";
724
+ ErrorSeverity2["Log"] = "log";
725
+ ErrorSeverity2["Info"] = "info";
726
+ ErrorSeverity2["Debug"] = "debug";
727
+ ErrorSeverity2["Critical"] = "critical";
728
+ })(ErrorSeverity || (ErrorSeverity = {}));
729
+
730
+ // ../../node_modules/@wix/panorama-common/dist/esm/global-config/global-config.js
731
+ import { v4 } from "uuid";
732
+
733
+ // ../../node_modules/@wix/panorama-common/dist/esm/duration-tracker/duration-tracker.js
734
+ var DELIMITER = " | ";
735
+ var DurationTrackerImpl = class {
736
+ constructor() {
737
+ this.transactionStartTimes = {};
738
+ this.phaseStartTimes = {};
739
+ }
740
+ createKey(...args) {
741
+ return args.filter((x) => !!x).join(DELIMITER);
742
+ }
743
+ markTransactionStart(fullArtifactId, componentId, transactionName, transactionId) {
744
+ const key = this.createKey(fullArtifactId, componentId, transactionName, transactionId);
745
+ this.transactionStartTimes[key] = Date.now();
746
+ }
747
+ markTransactionFinish(fullArtifactId, componentId, transactionName, transactionId) {
748
+ const key = this.createKey(fullArtifactId, componentId, transactionName, transactionId);
749
+ const finishTime = Date.now();
750
+ const startTime = this.transactionStartTimes[key] || finishTime;
751
+ const duration = Math.round(finishTime - startTime);
752
+ this.transactionStartTimes[key] = 0;
753
+ return duration;
754
+ }
755
+ markPhaseStart(fullArtifactId, componentId, phaseName) {
756
+ const key = this.createKey(fullArtifactId, componentId, phaseName);
757
+ this.phaseStartTimes[key] = Date.now();
758
+ }
759
+ markPhaseFinish(fullArtifactId, componentId, phaseName) {
760
+ const key = this.createKey(fullArtifactId, componentId, phaseName);
761
+ const finishTime = Date.now();
762
+ const startTime = this.phaseStartTimes[key] || finishTime;
763
+ const duration = Math.round(finishTime - startTime);
764
+ this.phaseStartTimes[key] = 0;
765
+ return duration;
766
+ }
767
+ };
768
+ var createDurationTracker = () => new DurationTrackerImpl();
769
+
770
+ // ../../node_modules/@wix/panorama-common/dist/esm/global-config/global-config.js
771
+ var GlobalConfigImpl = class {
772
+ constructor() {
773
+ this.sessionId = "";
774
+ this.reporter = null;
775
+ this.batchQueue = null;
776
+ this.durationTracker = createDurationTracker();
777
+ this.state = /* @__PURE__ */ new Map();
778
+ this.sessionStart = Date.now();
779
+ }
780
+ getSessionId() {
781
+ this.sessionId = this.sessionId || v4();
782
+ return this.sessionId;
783
+ }
784
+ setSessionId(sessionId) {
785
+ this.sessionId = sessionId;
786
+ }
787
+ getSessionTime() {
788
+ return Date.now() - this.sessionStart;
789
+ }
790
+ getReporter() {
791
+ return this.reporter;
792
+ }
793
+ setReporter(reporter) {
794
+ this.reporter = reporter;
795
+ }
796
+ initBatchQueue(batchQueue) {
797
+ this.batchQueue = this.batchQueue ?? batchQueue;
798
+ }
799
+ getBatchQueue() {
800
+ return this.batchQueue;
801
+ }
802
+ getDurationTracker() {
803
+ return this.durationTracker;
804
+ }
805
+ getStateValue(key) {
806
+ return this.state.get(key);
807
+ }
808
+ setStateValue(key, value) {
809
+ this.state.set(key, value);
810
+ }
811
+ clearState() {
812
+ this.state.clear();
813
+ this.durationTracker = createDurationTracker();
814
+ }
815
+ };
816
+ var createGlobalConfig = () => new GlobalConfigImpl();
817
+
818
+ // ../../node_modules/@wix/panorama-client/dist/esm/panorama-client-factory.js
819
+ import _defineProperty6 from "@babel/runtime/helpers/defineProperty";
820
+
821
+ // ../../node_modules/@wix/panorama-common/dist/esm/utils/class-utils.js
822
+ var bindPrototypeMethodsToSelf = (instance, classFn) => {
823
+ const prototype = classFn ? classFn.prototype : Object.getPrototypeOf(instance);
824
+ const props = Object.getOwnPropertyNames(prototype);
825
+ for (const prop of props) {
826
+ if (prop === "constructor" || typeof prototype[prop] !== "function") {
827
+ continue;
828
+ }
829
+ instance[prop] = prototype[prop].bind(instance);
830
+ }
831
+ };
832
+
833
+ // ../../node_modules/@wix/panorama-client/dist/esm/utils/general-utils.js
834
+ var last = (arr) => Array.isArray(arr) ? arr[arr.length - 1] : void 0;
835
+ var union = function() {
836
+ for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
837
+ args[_key] = arguments[_key];
838
+ }
839
+ return [...new Set(args.flat()).values()];
840
+ };
841
+ var defaults = function() {
842
+ for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
843
+ args[_key2] = arguments[_key2];
844
+ }
845
+ return args.reduce((res, obj) => Object.entries(obj ?? {}).reduce((_res, _ref) => {
846
+ let [key, value] = _ref;
847
+ if (typeof _res[key] === "undefined" && typeof value !== "undefined") {
848
+ _res[key] = value;
849
+ }
850
+ return _res;
851
+ }, res), {});
852
+ };
853
+ var deepDefaults = function(dest) {
854
+ for (var _len3 = arguments.length, rest = new Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) {
855
+ rest[_key3 - 1] = arguments[_key3];
856
+ }
857
+ const keys = union(...rest.map((value) => Object.keys(value ?? {})));
858
+ const all = [dest, ...rest];
859
+ return keys.reduce((res, key) => {
860
+ const values = all.map((value) => value == null ? void 0 : value[key]);
861
+ const merged = defaults(...values);
862
+ const hasValues = Object.values(merged).filter((value) => typeof value !== "undefined").length > 0;
863
+ if (hasValues) {
864
+ res = res ?? {};
865
+ res[key] = merged;
866
+ } else {
867
+ var _res2;
868
+ (_res2 = res) == null || delete _res2[key];
869
+ }
870
+ return res;
871
+ }, dest ? {
872
+ ...dest
873
+ } : dest);
874
+ };
875
+
876
+ // ../../node_modules/@wix/panorama-client/dist/esm/panorama-client.js
877
+ import _defineProperty3 from "@babel/runtime/helpers/defineProperty";
878
+
879
+ // ../../node_modules/@wix/panorama-client/dist/esm/panorama-client-component.js
880
+ import _defineProperty from "@babel/runtime/helpers/defineProperty";
881
+
882
+ // ../../node_modules/@wix/panorama-client/dist/esm/panorama-error-monitor.js
883
+ var PanoramaErrorMonitorImpl = class {
884
+ constructor(baseClient, options) {
885
+ this.baseClient = baseClient;
886
+ this.options = options;
887
+ bindPrototypeMethodsToSelf(this);
888
+ }
889
+ reportError(error, data) {
890
+ this.baseClient.reportError(error, data, this.options);
891
+ }
892
+ addBreadcrumb(breadcrumb) {
893
+ this.baseClient.addBreadcrumb(breadcrumb);
894
+ }
895
+ };
896
+
897
+ // ../../node_modules/@wix/panorama-client/dist/esm/panorama-logger.js
898
+ var PanoramaLoggerImpl = class {
899
+ constructor(baseClient) {
900
+ this.baseClient = baseClient;
901
+ bindPrototypeMethodsToSelf(this);
902
+ }
903
+ info(message, data) {
904
+ this.baseClient.log(LogLevel.Info, message, data);
905
+ }
906
+ warn(message, data) {
907
+ this.baseClient.log(LogLevel.Warn, message, data);
908
+ }
909
+ error(message, data) {
910
+ this.baseClient.log(LogLevel.Error, message, data);
911
+ }
912
+ debug(message, data) {
913
+ this.baseClient.log(LogLevel.Debug, message, data);
914
+ }
915
+ };
916
+
917
+ // ../../node_modules/@wix/panorama-common-shared/dist/esm/utils/transaction-utils.js
918
+ var isCustomTransactionName = (name) => !Object.values(InternalTransactions).includes(name);
919
+
920
+ // ../../node_modules/@wix/panorama-client/dist/esm/panorama-transaction.js
921
+ var PanoramaTransactionImpl = class {
922
+ constructor(baseClient, name, options) {
923
+ this.baseClient = baseClient;
924
+ this.name = name;
925
+ this.options = options;
926
+ if (!isCustomTransactionName(name)) {
927
+ throw new Error(`"${name}" is an internal transaction and can't be used`);
928
+ }
929
+ this.baseClient = baseClient;
930
+ bindPrototypeMethodsToSelf(this);
931
+ }
932
+ start(data, options) {
933
+ return this.baseClient.reportTransactionStart(this.name, defaults(options, this.options), data);
934
+ }
935
+ finish(data, options) {
936
+ return this.baseClient.reportTransactionFinish(this.name, defaults(options, this.options), data);
937
+ }
938
+ };
939
+
940
+ // ../../node_modules/@wix/panorama-client/dist/esm/panorama-client-component.js
941
+ var PanoramaClientForComponentImpl = class {
942
+ constructor(_ref) {
943
+ let {
944
+ baseClient
945
+ } = _ref;
946
+ _defineProperty(this, "baseClient", void 0);
947
+ this.baseClient = baseClient;
948
+ bindPrototypeMethodsToSelf(this);
949
+ }
950
+ transaction(name, options) {
951
+ return new PanoramaTransactionImpl(this.baseClient, name, options);
952
+ }
953
+ errorMonitor(options) {
954
+ return new PanoramaErrorMonitorImpl(this.baseClient, options);
955
+ }
956
+ logger() {
957
+ return new PanoramaLoggerImpl(this.baseClient);
958
+ }
959
+ };
960
+
961
+ // ../../node_modules/@wix/panorama-client/dist/esm/plugins/hooks-manager.js
962
+ import _defineProperty2 from "@babel/runtime/helpers/defineProperty";
963
+ var Hook = /* @__PURE__ */ function(Hook2) {
964
+ Hook2[Hook2["afterCreateClientForComponent"] = 0] = "afterCreateClientForComponent";
965
+ Hook2[Hook2["beforeReport"] = 1] = "beforeReport";
966
+ Hook2[Hook2["beforeReportTransactionStart"] = 2] = "beforeReportTransactionStart";
967
+ Hook2[Hook2["afterReportTransactionStart"] = 3] = "afterReportTransactionStart";
968
+ Hook2[Hook2["beforeReportTransactionFinish"] = 4] = "beforeReportTransactionFinish";
969
+ Hook2[Hook2["afterReportTransactionFinish"] = 5] = "afterReportTransactionFinish";
970
+ Hook2[Hook2["beforeReportPhaseStart"] = 6] = "beforeReportPhaseStart";
971
+ Hook2[Hook2["afterReportPhaseStart"] = 7] = "afterReportPhaseStart";
972
+ Hook2[Hook2["beforeReportPhaseFinish"] = 8] = "beforeReportPhaseFinish";
973
+ Hook2[Hook2["afterReportPhaseFinish"] = 9] = "afterReportPhaseFinish";
974
+ Hook2[Hook2["beforeReportError"] = 10] = "beforeReportError";
975
+ Hook2[Hook2["afterReportError"] = 11] = "afterReportError";
976
+ Hook2[Hook2["beforeAddBreadcrumb"] = 12] = "beforeAddBreadcrumb";
977
+ Hook2[Hook2["afterAddBreadcrumb"] = 13] = "afterAddBreadcrumb";
978
+ Hook2[Hook2["beforeReportLog"] = 14] = "beforeReportLog";
979
+ Hook2[Hook2["afterReportLog"] = 15] = "afterReportLog";
980
+ Hook2[Hook2["beforeUnhandledError"] = 16] = "beforeUnhandledError";
981
+ return Hook2;
982
+ }({});
983
+ var HooksManager = class {
984
+ constructor() {
985
+ _defineProperty2(this, "subscribers", {});
986
+ }
987
+ tap(hook, subscriber) {
988
+ this.subscribers[hook] = this.subscribers[hook] || [];
989
+ this.subscribers[hook].push(subscriber);
990
+ }
991
+ invoke(hook) {
992
+ const subscribers = this.subscribers[hook];
993
+ if (!subscribers) {
994
+ return true;
995
+ }
996
+ for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
997
+ args[_key - 1] = arguments[_key];
998
+ }
999
+ for (const subscriber of subscribers) {
1000
+ if (subscriber(...args) === false) {
1001
+ return false;
1002
+ }
1003
+ }
1004
+ return true;
1005
+ }
1006
+ };
1007
+
1008
+ // ../../node_modules/@wix/panorama-client/dist/esm/panorama-phase.js
1009
+ var PanoramaPhaseImpl = class {
1010
+ constructor(name, baseClient) {
1011
+ this.name = name;
1012
+ this.baseClient = baseClient;
1013
+ this.baseClient = baseClient;
1014
+ bindPrototypeMethodsToSelf(this);
1015
+ }
1016
+ start(data) {
1017
+ return this.baseClient.reportPhaseStart(this.name, data);
1018
+ }
1019
+ finish(data) {
1020
+ return this.baseClient.reportPhaseFinish(this.name, data);
1021
+ }
1022
+ };
1023
+
1024
+ // ../../node_modules/@wix/panorama-client/dist/esm/panorama-client.js
1025
+ var PanoramaClientImpl = class {
1026
+ constructor(_ref) {
1027
+ let {
1028
+ hooksManager,
1029
+ baseClient
1030
+ } = _ref;
1031
+ _defineProperty3(this, "baseClient", void 0);
1032
+ _defineProperty3(this, "hooksManager", void 0);
1033
+ this.baseClient = baseClient;
1034
+ this.hooksManager = hooksManager;
1035
+ bindPrototypeMethodsToSelf(this);
1036
+ }
1037
+ onUnhandledError(subscriber) {
1038
+ this.hooksManager.tap(Hook.beforeUnhandledError, subscriber);
1039
+ }
1040
+ reportLoadStart(data, options) {
1041
+ const {
1042
+ ComponentLoad
1043
+ } = InternalTransactions;
1044
+ return this.baseClient.reportTransactionStart(ComponentLoad, options, data);
1045
+ }
1046
+ reportLoadFinish(data, options) {
1047
+ const {
1048
+ ComponentLoad
1049
+ } = InternalTransactions;
1050
+ return this.baseClient.reportTransactionFinish(ComponentLoad, options, data);
1051
+ }
1052
+ phase(name) {
1053
+ return new PanoramaPhaseImpl(name, this.baseClient);
1054
+ }
1055
+ transaction(name, options) {
1056
+ return new PanoramaTransactionImpl(this.baseClient, name, options);
1057
+ }
1058
+ errorMonitor(options) {
1059
+ return new PanoramaErrorMonitorImpl(this.baseClient, options);
1060
+ }
1061
+ logger() {
1062
+ return new PanoramaLoggerImpl(this.baseClient);
1063
+ }
1064
+ createClientForComponent() {
1065
+ const client = new PanoramaClientForComponentImpl({
1066
+ baseClient: this.baseClient
1067
+ });
1068
+ this.hooksManager.invoke(Hook.afterCreateClientForComponent, client);
1069
+ return client;
1070
+ }
1071
+ };
1072
+
1073
+ // ../../node_modules/@wix/panorama-client/dist/esm/panorama-client-base.js
1074
+ import _defineProperty4 from "@babel/runtime/helpers/defineProperty";
1075
+
1076
+ // ../../node_modules/@wix/panorama-client/dist/esm/utils/error-utils.js
1077
+ var extractWixHttpErrorDetailsRec = (error) => {
1078
+ var _httpClientError$resp;
1079
+ if (!(error instanceof Error)) {
1080
+ return {};
1081
+ }
1082
+ const res = extractWixHttpErrorDetailsRec(error.cause);
1083
+ const httpClientError = error;
1084
+ return defaults(res, {
1085
+ isWixHttpError: httpClientError.isWixHttpError,
1086
+ requestId: ((_httpClientError$resp = httpClientError.response) == null || (_httpClientError$resp = _httpClientError$resp.headers) == null ? void 0 : _httpClientError$resp["x-wix-request-id"]) ?? httpClientError.requestId
1087
+ });
1088
+ };
1089
+ var extractWixHttpErrorDetails = (error) => defaults(extractWixHttpErrorDetailsRec(error), {
1090
+ isWixHttpError: false,
1091
+ requestId: ""
1092
+ });
1093
+
1094
+ // ../../node_modules/@wix/panorama-client/dist/esm/constants.js
1095
+ var MAX_STACK_TRACE_SIZE_BYTES = 32 * 1024;
1096
+
1097
+ // ../../node_modules/@wix/panorama-client/dist/esm/lib/payload-sanitizer.js
1098
+ var sanitizePayload = (payload) => {
1099
+ const {
1100
+ errorStack
1101
+ } = payload;
1102
+ if (errorStack && errorStack.length > MAX_STACK_TRACE_SIZE_BYTES) {
1103
+ const truncationMessage = `...[truncated by Panorama client to ${MAX_STACK_TRACE_SIZE_BYTES / 1024}kb]`;
1104
+ const truncatedErrorStack = errorStack.substring(0, MAX_STACK_TRACE_SIZE_BYTES - truncationMessage.length);
1105
+ payload = {
1106
+ ...payload,
1107
+ errorStack: `${truncatedErrorStack}${truncationMessage}`
1108
+ };
1109
+ }
1110
+ return payload;
1111
+ };
1112
+
1113
+ // ../../node_modules/@wix/panorama-client/dist/esm/lib/payload-builder.js
1114
+ var getSessionParams = (globalConfig2) => {
1115
+ const sessionId = globalConfig2.getSessionId();
1116
+ const sessionTime = Math.round(globalConfig2.getSessionTime());
1117
+ return {
1118
+ sessionId,
1119
+ sessionTime
1120
+ };
1121
+ };
1122
+ var buildTransactionPayload = (globalConfig2, baseParams, transactionParams, data) => {
1123
+ const {
1124
+ transactionName,
1125
+ transactionAction
1126
+ } = transactionParams;
1127
+ const {
1128
+ sessionId,
1129
+ sessionTime
1130
+ } = getSessionParams(globalConfig2);
1131
+ const logLevel = LogLevel.Info;
1132
+ const message = `Panorama ${transactionName} ${transactionAction}`;
1133
+ const requestId = "";
1134
+ return sanitizePayload({
1135
+ ...baseParams,
1136
+ ...transactionParams,
1137
+ sessionId,
1138
+ sessionTime,
1139
+ logLevel,
1140
+ requestId,
1141
+ message,
1142
+ data
1143
+ });
1144
+ };
1145
+ var buildPhasePayload = (globalConfig2, baseParams, phaseParams, data) => {
1146
+ const transactionName = InternalTransactions.ComponentPhase;
1147
+ const {
1148
+ phaseName,
1149
+ transactionAction
1150
+ } = phaseParams;
1151
+ const {
1152
+ sessionId,
1153
+ sessionTime
1154
+ } = getSessionParams(globalConfig2);
1155
+ const logLevel = LogLevel.Info;
1156
+ const message = `Panorama ${phaseName} phase ${transactionAction}`;
1157
+ const requestId = "";
1158
+ return sanitizePayload({
1159
+ ...baseParams,
1160
+ ...phaseParams,
1161
+ transactionName,
1162
+ sessionId,
1163
+ sessionTime,
1164
+ logLevel,
1165
+ requestId,
1166
+ message,
1167
+ data
1168
+ });
1169
+ };
1170
+ var buildErrorPayload = (globalConfig2, baseParams, error, data) => {
1171
+ const {
1172
+ sessionId,
1173
+ sessionTime
1174
+ } = getSessionParams(globalConfig2);
1175
+ const {
1176
+ constructor,
1177
+ message,
1178
+ stack = ""
1179
+ } = error;
1180
+ const logLevel = LogLevel.Error;
1181
+ const {
1182
+ requestId
1183
+ } = extractWixHttpErrorDetails(error);
1184
+ return sanitizePayload({
1185
+ ...baseParams,
1186
+ sessionId,
1187
+ sessionTime,
1188
+ logLevel,
1189
+ requestId,
1190
+ data,
1191
+ errorName: (data == null ? void 0 : data.errorName) ?? constructor.name,
1192
+ errorStack: stack,
1193
+ message
1194
+ });
1195
+ };
1196
+ var buildLoggerPayload = (globalConfig2, baseParams, loggerParams) => {
1197
+ const {
1198
+ sessionId,
1199
+ sessionTime
1200
+ } = getSessionParams(globalConfig2);
1201
+ const requestId = "";
1202
+ return sanitizePayload({
1203
+ ...baseParams,
1204
+ ...loggerParams,
1205
+ sessionId,
1206
+ sessionTime,
1207
+ requestId
1208
+ });
1209
+ };
1210
+
1211
+ // ../../node_modules/@wix/panorama-client/dist/esm/panorama-client-base.js
1212
+ var BasePanoramaClient = class {
1213
+ constructor(_ref) {
1214
+ var _this = this;
1215
+ let {
1216
+ baseParams,
1217
+ globalConfig: globalConfig2,
1218
+ reporter,
1219
+ hooksManager,
1220
+ data,
1221
+ isMuted
1222
+ } = _ref;
1223
+ _defineProperty4(this, "durationTracker", void 0);
1224
+ _defineProperty4(this, "baseParams", void 0);
1225
+ _defineProperty4(this, "globalConfig", void 0);
1226
+ _defineProperty4(this, "reporter", void 0);
1227
+ _defineProperty4(this, "hooksManager", void 0);
1228
+ _defineProperty4(this, "data", void 0);
1229
+ _defineProperty4(this, "isMuted", void 0);
1230
+ _defineProperty4(this, "getErrorMonitorDataWithDefaults", function() {
1231
+ for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
1232
+ args[_key] = arguments[_key];
1233
+ }
1234
+ return _this.data.addDataScope(args).getData();
1235
+ });
1236
+ this.baseParams = baseParams;
1237
+ this.globalConfig = globalConfig2;
1238
+ this.reporter = reporter;
1239
+ this.hooksManager = hooksManager;
1240
+ this.data = data;
1241
+ this.isMuted = isMuted;
1242
+ this.durationTracker = typeof globalConfig2.getDurationTracker === "function" ? globalConfig2.getDurationTracker() : createDurationTracker();
1243
+ }
1244
+ report(eventPayload) {
1245
+ if (this.isMuted()) {
1246
+ return;
1247
+ }
1248
+ const reporterOverride = this.globalConfig.getReporter();
1249
+ const beforeReportHookResult = this.hooksManager.invoke(Hook.beforeReport, eventPayload);
1250
+ if (typeof reporterOverride === "function") {
1251
+ reporterOverride(eventPayload);
1252
+ return;
1253
+ }
1254
+ if (!beforeReportHookResult) {
1255
+ return;
1256
+ }
1257
+ this.reporter(eventPayload);
1258
+ }
1259
+ reportTransactionStart(name, options, data) {
1260
+ if (options === void 0) {
1261
+ options = {};
1262
+ }
1263
+ const {
1264
+ id
1265
+ } = options;
1266
+ const dataWithDefault = this.data.addDataScope(data).getData();
1267
+ if (!this.hooksManager.invoke(Hook.beforeReportTransactionStart, name, dataWithDefault)) {
1268
+ return;
1269
+ }
1270
+ const {
1271
+ fullArtifactId,
1272
+ componentId
1273
+ } = this.baseParams;
1274
+ this.durationTracker.markTransactionStart(fullArtifactId, componentId, name, id);
1275
+ const payload = buildTransactionPayload(this.globalConfig, this.baseParams, {
1276
+ transactionName: name,
1277
+ transactionAction: TransactionAction.Start
1278
+ }, dataWithDefault);
1279
+ this.report(payload);
1280
+ this.hooksManager.invoke(Hook.afterReportTransactionStart, name, payload);
1281
+ }
1282
+ reportTransactionFinish(name, options, data) {
1283
+ if (options === void 0) {
1284
+ options = {};
1285
+ }
1286
+ const {
1287
+ id
1288
+ } = options;
1289
+ const dataWithDefault = this.data.addDataScope(data).getData();
1290
+ if (!this.hooksManager.invoke(Hook.beforeReportTransactionFinish, name, dataWithDefault)) {
1291
+ return;
1292
+ }
1293
+ const {
1294
+ fullArtifactId,
1295
+ componentId
1296
+ } = this.baseParams;
1297
+ const duration = this.durationTracker.markTransactionFinish(fullArtifactId, componentId, name, id);
1298
+ const payload = buildTransactionPayload(this.globalConfig, this.baseParams, {
1299
+ transactionName: name,
1300
+ transactionAction: TransactionAction.Finish,
1301
+ transactionDuration: duration
1302
+ }, dataWithDefault);
1303
+ this.report(payload);
1304
+ this.hooksManager.invoke(Hook.afterReportTransactionFinish, name, payload);
1305
+ }
1306
+ reportPhaseStart(name, data) {
1307
+ const dataWithDefault = this.data.addDataScope(data).getData();
1308
+ if (!this.hooksManager.invoke(Hook.beforeReportPhaseStart, name, dataWithDefault)) {
1309
+ return;
1310
+ }
1311
+ const {
1312
+ fullArtifactId,
1313
+ componentId
1314
+ } = this.baseParams;
1315
+ this.durationTracker.markPhaseStart(fullArtifactId, componentId, name);
1316
+ const payload = buildPhasePayload(this.globalConfig, this.baseParams, {
1317
+ phaseName: name,
1318
+ transactionAction: TransactionAction.Start
1319
+ }, dataWithDefault);
1320
+ this.report(payload);
1321
+ this.hooksManager.invoke(Hook.afterReportPhaseStart, name, payload);
1322
+ }
1323
+ reportPhaseFinish(name, data) {
1324
+ const dataWithDefault = this.data.addDataScope(data).getData();
1325
+ if (!this.hooksManager.invoke(Hook.beforeReportPhaseFinish, name, dataWithDefault)) {
1326
+ return;
1327
+ }
1328
+ const {
1329
+ fullArtifactId,
1330
+ componentId
1331
+ } = this.baseParams;
1332
+ const duration = this.durationTracker.markPhaseFinish(fullArtifactId, componentId, name);
1333
+ const payload = buildPhasePayload(this.globalConfig, this.baseParams, {
1334
+ phaseName: name,
1335
+ transactionAction: TransactionAction.Finish,
1336
+ transactionDuration: duration
1337
+ }, dataWithDefault);
1338
+ this.report(payload);
1339
+ this.hooksManager.invoke(Hook.afterReportPhaseFinish, name, payload);
1340
+ }
1341
+ reportError(error, data, options) {
1342
+ if (!(error instanceof Error)) {
1343
+ return;
1344
+ }
1345
+ data = this.data.addDataScope([data, options == null ? void 0 : options.data]).getData();
1346
+ if (!this.hooksManager.invoke(Hook.beforeReportError, error, data, options)) {
1347
+ return;
1348
+ }
1349
+ const payload = buildErrorPayload(this.globalConfig, this.baseParams, error, data);
1350
+ this.report(payload);
1351
+ this.hooksManager.invoke(Hook.afterReportError, error, data, options);
1352
+ }
1353
+ addBreadcrumb(breadcrumb) {
1354
+ if (!this.hooksManager.invoke(Hook.beforeAddBreadcrumb, breadcrumb)) {
1355
+ return;
1356
+ }
1357
+ this.hooksManager.invoke(Hook.afterAddBreadcrumb, breadcrumb);
1358
+ }
1359
+ log(logLevel, message, data) {
1360
+ if (!message) {
1361
+ return;
1362
+ }
1363
+ const dataWithDefault = this.data.addDataScope(data).getData();
1364
+ const loggerParams = {
1365
+ message,
1366
+ data: dataWithDefault,
1367
+ logLevel
1368
+ };
1369
+ if (!this.hooksManager.invoke(Hook.beforeReportLog, logLevel, message, dataWithDefault)) {
1370
+ return;
1371
+ }
1372
+ const payload = buildLoggerPayload(this.globalConfig, this.baseParams, loggerParams);
1373
+ this.report(payload);
1374
+ this.hooksManager.invoke(Hook.afterReportLog, logLevel, message, dataWithDefault);
1375
+ }
1376
+ };
1377
+
1378
+ // ../../node_modules/@wix/panorama-client/dist/esm/lib/scope.js
1379
+ import _defineProperty5 from "@babel/runtime/helpers/defineProperty";
1380
+ var Scope = class _Scope {
1381
+ constructor(data) {
1382
+ _defineProperty5(this, "data", void 0);
1383
+ this.data = data;
1384
+ }
1385
+ getEntriesToDeepDefaults(data) {
1386
+ if (!data) {
1387
+ return void 0;
1388
+ }
1389
+ return Object.fromEntries(Object.entries(data).filter((_ref) => {
1390
+ let [key] = _ref;
1391
+ return _Scope.KEYS_TO_DEEP_DEFAULTS.includes(key);
1392
+ }));
1393
+ }
1394
+ addDataScope(data) {
1395
+ const outerDataArray = Array.isArray(data) ? data : [data];
1396
+ const deepDefaultData = deepDefaults(...outerDataArray.map((_data) => this.getEntriesToDeepDefaults(_data)), this.getEntriesToDeepDefaults(this.data));
1397
+ return new _Scope(defaults(deepDefaultData, ...outerDataArray, this.data));
1398
+ }
1399
+ getData() {
1400
+ return this.data;
1401
+ }
1402
+ };
1403
+ _defineProperty5(Scope, "KEYS_TO_DEEP_DEFAULTS", ["tags", "context"]);
1404
+
1405
+ // ../../node_modules/@wix/panorama-client/dist/esm/panorama-client-factory.js
1406
+ var PanoramaClientFactoryImpl = class {
1407
+ constructor(options) {
1408
+ this.options = options;
1409
+ _defineProperty6(this, "globalConfig", void 0);
1410
+ _defineProperty6(this, "reporter", () => true);
1411
+ _defineProperty6(this, "plugins", []);
1412
+ _defineProperty6(this, "isMuted", false);
1413
+ bindPrototypeMethodsToSelf(this);
1414
+ }
1415
+ withGlobalConfig(globalConfig2) {
1416
+ this.globalConfig = globalConfig2;
1417
+ return this;
1418
+ }
1419
+ withReporter(reporter) {
1420
+ this.reporter = reporter;
1421
+ return this;
1422
+ }
1423
+ setMuted(isMuted) {
1424
+ this.isMuted = isMuted;
1425
+ return this;
1426
+ }
1427
+ use(plugin) {
1428
+ this.plugins.push(plugin);
1429
+ return this;
1430
+ }
1431
+ client(options) {
1432
+ if (options === void 0) {
1433
+ options = {};
1434
+ }
1435
+ const {
1436
+ pluginParams
1437
+ } = options;
1438
+ const globalConfig2 = this.globalConfig ?? createGlobalConfig();
1439
+ const reporter = this.reporter;
1440
+ const hooksManager = new HooksManager();
1441
+ const baseParams = defaults(options.baseParams, this.options.baseParams);
1442
+ const data = new Scope(this.options.data).addDataScope(options.data);
1443
+ const pluginClientParams = pluginParams ?? {};
1444
+ const baseClient = new BasePanoramaClient({
1445
+ baseParams,
1446
+ globalConfig: globalConfig2,
1447
+ isMuted: () => this.isMuted,
1448
+ reporter,
1449
+ hooksManager,
1450
+ data
1451
+ });
1452
+ const client = new PanoramaClientImpl({
1453
+ baseClient,
1454
+ hooksManager
1455
+ });
1456
+ this.plugins.forEach((plugin) => plugin({
1457
+ hooksManager,
1458
+ globalConfig: globalConfig2,
1459
+ reporter,
1460
+ baseClient,
1461
+ baseParams,
1462
+ pluginParams: pluginClientParams
1463
+ }));
1464
+ return client;
1465
+ }
1466
+ };
1467
+ var panoramaClient = function(options) {
1468
+ if (options === void 0) {
1469
+ options = {};
1470
+ }
1471
+ return new PanoramaClientFactoryImpl(options);
1472
+ };
1473
+
1474
+ // ../../node_modules/@wix/panorama-client/dist/esm/types.js
1475
+ var StacktraceScriptType = /* @__PURE__ */ function(StacktraceScriptType2) {
1476
+ StacktraceScriptType2["WIX_SERVICE"] = "WIX_SERVICE";
1477
+ StacktraceScriptType2["WIX_APP"] = "WIX_APP";
1478
+ StacktraceScriptType2["WIX_CHAT"] = "WIX_CHAT_WIDGET";
1479
+ StacktraceScriptType2["BROWSER_EXTENSION"] = "BROWSER_EXTENSION";
1480
+ return StacktraceScriptType2;
1481
+ }({});
1482
+
1483
+ // ../../node_modules/@wix/panorama-client/dist/esm/utils/artifact-utils.js
1484
+ var scriptRegexs = [{
1485
+ scriptType: StacktraceScriptType.WIX_SERVICE,
1486
+ regex: () => /\/services\/([^/]+)\/([^/]+)\//
1487
+ }, {
1488
+ scriptType: StacktraceScriptType.WIX_APP,
1489
+ regex: () => /apps\.wix\.com\/([^/]+)\//
1490
+ }, {
1491
+ scriptType: StacktraceScriptType.WIX_CHAT,
1492
+ regex: () => /unpkg-semver\/(wix-chatbot-widget)\//
1493
+ }, {
1494
+ scriptType: StacktraceScriptType.BROWSER_EXTENSION,
1495
+ regex: () => /^chrome-extension:/
1496
+ }];
1497
+ var fullArtifactIdToArtifactId = (fullArtifactId) => {
1498
+ if (typeof fullArtifactId !== "string") {
1499
+ return "";
1500
+ }
1501
+ return last(fullArtifactId.split(".")) || "";
1502
+ };
1503
+
1504
+ // ../../node_modules/@wix/panorama-client/dist/esm/utils/url-utils.js
1505
+ var getQueryParamValue = (key) => {
1506
+ if (typeof window === "undefined") {
1507
+ return null;
1508
+ }
1509
+ const queryParams = new URLSearchParams(window.location.search);
1510
+ return queryParams.get(key);
1511
+ };
1512
+ var hasQueryParam = (key) => {
1513
+ const queryParamValue = getQueryParamValue(key);
1514
+ return queryParamValue === "true";
1515
+ };
1516
+
1517
+ // ../../node_modules/@wix/panorama-client/dist/esm/utils/cookie-utils.js
1518
+ var getCookieOverrideValue = (artifactId) => {
1519
+ if (typeof document === "undefined") {
1520
+ return null;
1521
+ }
1522
+ const wixStaticsVersionsCookie = document.cookie.split(";").map((c) => c.trim()).find((c) => c.startsWith("wixStaticsVersions="));
1523
+ if (!wixStaticsVersionsCookie) {
1524
+ return null;
1525
+ }
1526
+ const cookieValue = wixStaticsVersionsCookie.split("=")[1].trim();
1527
+ const overrideArtifactEntry = cookieValue.split("|").find((overrideEntry) => overrideEntry.startsWith(`${artifactId}#`));
1528
+ if (!overrideArtifactEntry) {
1529
+ return null;
1530
+ }
1531
+ return overrideArtifactEntry.split("#")[1];
1532
+ };
1533
+
1534
+ // ../../node_modules/@wix/panorama-client/dist/esm/utils/environment-utils.js
1535
+ var RuntimeEnvironment = /* @__PURE__ */ function(RuntimeEnvironment2) {
1536
+ RuntimeEnvironment2["PRODUCTION"] = "production";
1537
+ RuntimeEnvironment2["DEVELOPMENT"] = "development";
1538
+ RuntimeEnvironment2["BOT"] = "bot";
1539
+ RuntimeEnvironment2["INVALID_USER_AGENT"] = "invalid_useragent";
1540
+ RuntimeEnvironment2["SLED"] = "sled";
1541
+ RuntimeEnvironment2["SERVER"] = "server";
1542
+ RuntimeEnvironment2["TEST"] = "test";
1543
+ return RuntimeEnvironment2;
1544
+ }({});
1545
+ var FORCE_PANORAMA_REPORT_QUERY_PARAM = "forcePanoramaReport";
1546
+ var ENABLE_PANORAMA_LOGS_QUERY_PARAM = "enablePanoramaLogs";
1547
+ var hasForcePanoramaReportQueryParam = () => {
1548
+ return hasQueryParam(FORCE_PANORAMA_REPORT_QUERY_PARAM);
1549
+ };
1550
+ var hasEnablePanoramaLogsQueryParam = () => {
1551
+ return hasQueryParam(ENABLE_PANORAMA_LOGS_QUERY_PARAM);
1552
+ };
1553
+ var checkIsLocalMode = (fullArtifactId) => {
1554
+ const artifactId = fullArtifactIdToArtifactId(fullArtifactId);
1555
+ if (!artifactId) {
1556
+ return false;
1557
+ }
1558
+ const queryParamOverrideValue = getQueryParamValue(`${artifactId}-override`);
1559
+ const isLocalQueryParamOverride = queryParamOverrideValue && queryParamOverrideValue.includes("localhost");
1560
+ if (isLocalQueryParamOverride) {
1561
+ return true;
1562
+ }
1563
+ const wixStaticCookieValue = getCookieOverrideValue(artifactId);
1564
+ return !!wixStaticCookieValue && wixStaticCookieValue.includes("localhost");
1565
+ };
1566
+ function calculateEnvironment() {
1567
+ if (typeof WorkerGlobalScope !== "undefined" && self instanceof WorkerGlobalScope) {
1568
+ return RuntimeEnvironment.PRODUCTION;
1569
+ }
1570
+ if (typeof window === "undefined") {
1571
+ try {
1572
+ return process.env.NODE_ENV || RuntimeEnvironment.SERVER;
1573
+ } catch {
1574
+ return RuntimeEnvironment.SERVER;
1575
+ }
1576
+ }
1577
+ const {
1578
+ hostname
1579
+ } = window.location;
1580
+ const {
1581
+ userAgent
1582
+ } = window.navigator;
1583
+ const {
1584
+ cookie
1585
+ } = window.document;
1586
+ const isSled = /(^|;)\s*automation\s*=\s*sled:/.test(cookie);
1587
+ const isLocalhost = /localhost|127\.0\.0\.1|::1|\.local|local\.wix\.com|^$/i.test(hostname);
1588
+ const isBot = /Googlebot|AdsBot-Google-Mobile|bingbot|BingPreview|facebookexternalhit|Baiduspider|YandexBot/i.test(userAgent);
1589
+ const isNotValidUserAgent = /BonEcho|NewsGator|SeaMonkey|iTunes|Epiphany|Konqueror|Sleipnir|IceWeasel/i.test(userAgent);
1590
+ switch (true) {
1591
+ case isSled:
1592
+ return RuntimeEnvironment.SLED;
1593
+ case process.env.NODE_ENV === "test":
1594
+ return RuntimeEnvironment.TEST;
1595
+ case (process.env.NODE_ENV === "development" || isLocalhost):
1596
+ return RuntimeEnvironment.DEVELOPMENT;
1597
+ case isBot:
1598
+ return RuntimeEnvironment.BOT;
1599
+ case isNotValidUserAgent:
1600
+ return RuntimeEnvironment.INVALID_USER_AGENT;
1601
+ default:
1602
+ return RuntimeEnvironment.PRODUCTION;
1603
+ }
1604
+ }
1605
+
1606
+ // ../../node_modules/@wix/panorama-client/dist/esm/utils/console-utils.js
1607
+ var messageFormatter = (artifactId, componentId, message) => {
1608
+ return ["%c%s %c%s %c%s %c%s", "color: #D39874", "Panorama logger:", "color: #CAB6D3", `${artifactId}`, "color: #B3CAD8", `${componentId}`, "color: #A6C6DB", `${message}`];
1609
+ };
1610
+ var logToConsole = (logLevel, artifactId, componentId, message, data) => {
1611
+ const formattedMessage = messageFormatter(artifactId, componentId, message);
1612
+ if (logLevel === LogLevel.Info) {
1613
+ console.info(...formattedMessage);
1614
+ } else if (logLevel === LogLevel.Warn) {
1615
+ console.warn(...formattedMessage);
1616
+ } else if (logLevel === LogLevel.Error) {
1617
+ console.error(...formattedMessage);
1618
+ } else if (logLevel === LogLevel.Debug) {
1619
+ console.debug(...formattedMessage);
1620
+ } else {
1621
+ console.log(...formattedMessage);
1622
+ }
1623
+ if (data && Object.keys(data).length) {
1624
+ console.table(data);
1625
+ }
1626
+ };
1627
+
1628
+ // ../../node_modules/@wix/panorama-client/dist/esm/plugins/environment/environment-plugin.js
1629
+ var EXCLUDED_ENVIRONMENTS = [RuntimeEnvironment.DEVELOPMENT, RuntimeEnvironment.SLED];
1630
+ var environmentPlugin = () => (_ref) => {
1631
+ let {
1632
+ hooksManager,
1633
+ baseParams: {
1634
+ fullArtifactId,
1635
+ componentId
1636
+ }
1637
+ } = _ref;
1638
+ const environment = calculateEnvironment();
1639
+ const isLocalMode = checkIsLocalMode(fullArtifactId);
1640
+ const enablePanoramaLogs = hasEnablePanoramaLogsQueryParam();
1641
+ const shouldSkipReporting = (EXCLUDED_ENVIRONMENTS.includes(environment) || isLocalMode) && !hasForcePanoramaReportQueryParam();
1642
+ const shouldLogToConsole = shouldSkipReporting && enablePanoramaLogs;
1643
+ if (shouldLogToConsole) {
1644
+ logToConsole(LogLevel.Info, fullArtifactId, componentId, `Local mode detected${fullArtifactId ? ` for ${fullArtifactId}` : ""}. Panorama will log reports in the console.`);
1645
+ }
1646
+ hooksManager.tap(Hook.beforeReport, (eventPayload) => {
1647
+ const {
1648
+ data,
1649
+ message,
1650
+ fullArtifactId: messageFullArtifactId,
1651
+ componentId: messageComponentId,
1652
+ logLevel
1653
+ } = eventPayload;
1654
+ if (shouldLogToConsole) {
1655
+ logToConsole(logLevel, messageFullArtifactId, messageComponentId, message || "", data);
1656
+ }
1657
+ if (shouldSkipReporting) {
1658
+ return false;
1659
+ }
1660
+ return;
1661
+ });
1662
+ };
1663
+
1664
+ // ../../node_modules/@wix/panorama-common-shared/dist/esm/constants.js
1665
+ var CLICKHOUSE_REPORT_URL = "https://panorama.wixapps.net/api/v1/log";
1666
+
1667
+ // ../../node_modules/@wix/panorama-client-node/dist/esm/reporter.js
1668
+ import { createHttpClient } from "@wix/http-client";
1669
+ var nodeReporter = function(url, _temp) {
1670
+ let {
1671
+ silent = false
1672
+ } = _temp === void 0 ? {
1673
+ silent: false
1674
+ } : _temp;
1675
+ return (eventPayload) => {
1676
+ const httpClient = createHttpClient();
1677
+ const body = JSON.stringify({
1678
+ logMessage: eventPayload
1679
+ });
1680
+ httpClient.post(url, body).catch((e) => {
1681
+ if (silent) {
1682
+ return;
1683
+ }
1684
+ console.error(e);
1685
+ });
1686
+ return true;
1687
+ };
1688
+ };
1689
+
1690
+ // ../../node_modules/@wix/panorama-client-node/dist/esm/panorama-client-node.js
1691
+ var panoramaClientFactory = (options) => {
1692
+ const {
1693
+ baseParams,
1694
+ reporterOptions,
1695
+ data
1696
+ } = options;
1697
+ const factory = panoramaClient({
1698
+ baseParams,
1699
+ data
1700
+ }).use(environmentPlugin()).withReporter(nodeReporter(CLICKHOUSE_REPORT_URL, reporterOptions));
1701
+ factory.use = void 0;
1702
+ return factory;
1703
+ };
1704
+
1705
+ // src/panorama.ts
1706
+ var packageJson = {
1707
+ version: "1.0.0"
1708
+ };
1709
+ var globalConfig = createGlobalConfig();
1710
+ var panoramaFactory = panoramaClientFactory({
1711
+ reporterOptions: {
1712
+ silent: true
1713
+ },
1714
+ baseParams: {
1715
+ platform: Platform.Standalone,
1716
+ fullArtifactId: "com.wixpress.spartans.wix-mcp",
1717
+ artifactVersion: packageJson.version
1718
+ },
1719
+ data: {
1720
+ packageVersion: packageJson.version,
1721
+ versions: process.versions,
1722
+ platform: process.platform,
1723
+ arch: process.arch
1724
+ }
1725
+ }).withGlobalConfig(globalConfig);
1726
+
1727
+ // src/wix-mcp-server.ts
1728
+ import { captureException as captureException2, setTags } from "@sentry/node";
1729
+ var WixMcpServer = class extends McpServer {
1730
+ tool(...args) {
1731
+ const cbIndex = args.findIndex((arg) => typeof arg === "function");
1732
+ if (cbIndex !== -1) {
1733
+ const originalCb = args[cbIndex];
1734
+ const toolName = args[0];
1735
+ const panoramaComponentId = toolName;
1736
+ const panorama = panoramaFactory.client({
1737
+ baseParams: {
1738
+ componentId: panoramaComponentId
1739
+ }
1740
+ });
1741
+ setTags({
1742
+ panoramaSessionId: globalConfig.getSessionId()
1743
+ });
1744
+ const wrappedCb = async (...cbArgs) => {
1745
+ const argsBeforeExtra = cbArgs.slice(0, cbArgs.length - 1);
1746
+ const extra = cbArgs[cbArgs.length - 1];
1747
+ const wrappedExtra = {
1748
+ ...extra,
1749
+ panorama: panorama.createClientForComponent()
1750
+ };
1751
+ panorama.transaction(toolName).start();
1752
+ try {
1753
+ const cbResult = await originalCb(...argsBeforeExtra, wrappedExtra);
1754
+ panorama.transaction(toolName).finish();
1755
+ return cbResult;
1756
+ } catch (e) {
1757
+ panorama.errorMonitor().reportError(e);
1758
+ captureException2(e, {
1759
+ tags: {
1760
+ componentId: panoramaComponentId,
1761
+ toolName
1762
+ }
1763
+ });
1764
+ return {
1765
+ isError: true,
1766
+ content: [{ type: "text", text: e.message }]
1767
+ };
1768
+ }
1769
+ };
1770
+ args[cbIndex] = wrappedCb;
1771
+ }
1772
+ return super.tool.apply(this, args);
1773
+ }
1774
+ };
1775
+
1776
+ // src/resources/docs.ts
1777
+ var getPortalIndex = async (portalName) => {
1778
+ const response = await fetch(
1779
+ `https://dev.wix.com/digor/api/portal-index?portalName=${portalName}`
1780
+ );
1781
+ const data = await response.json();
1782
+ return data;
1783
+ };
1784
+ var addPortalResources = async (server, portalName) => {
1785
+ const portalIndexResponse = await getPortalIndex(portalName);
1786
+ logger.log(
1787
+ `portalIndexResponse for ${portalName}`,
1788
+ JSON.stringify(portalIndexResponse, null, 2)
1789
+ );
1790
+ for (const entry of portalIndexResponse.portalIndex) {
1791
+ logger.log(`entry ${JSON.stringify(entry, null, 2)}`);
1792
+ const name = entry.url;
1793
+ const uri = entry.url.replace("https://dev.wix.com/docs/", "wix-docs://");
1794
+ logger.log(`adding resource ${name} ${uri}`);
1795
+ server.resource(name, uri, async (uri2) => {
1796
+ logger.log(`fetching resource ${uri2}`);
1797
+ const docsURL = uri2.toString().replace("wix-docs://", "https://dev.wix.com/docs/");
1798
+ const response = await fetch(
1799
+ `https://dev.wix.com/digor/api/get-article-content?articleUrl=${encodeURIComponent(docsURL)}`
1800
+ );
1801
+ const data = await response.json();
1802
+ return {
1803
+ contents: [
1804
+ {
1805
+ uri: uri2.href,
1806
+ text: data.articleContent || "No content found"
1807
+ }
1808
+ ]
1809
+ };
1810
+ });
1811
+ }
1812
+ };
1813
+ var addDocsResources = async (server, portals) => {
1814
+ for (const portal of portals) {
1815
+ try {
1816
+ logger.log(`Processing portal: ${portal}`);
1817
+ await addPortalResources(server, portal);
1818
+ } catch (error) {
1819
+ logger.error(`Error processing portal ${portal}:`, error);
1820
+ }
1821
+ }
1822
+ };
1823
+
1824
+ export {
1825
+ logger,
1826
+ attachMcpServerLogger,
1827
+ attachStdErrLogger,
1828
+ attachFileLogger,
1829
+ VALID_DOCS_TOOLS,
1830
+ addDocsTools,
1831
+ handleWixAPIResponse,
1832
+ WixMcpServer,
1833
+ addDocsResources
1834
+ };