@wix/cli-app 1.1.53 → 1.1.55

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 (95) hide show
  1. package/README.md +45 -0
  2. package/build/{CreateVersionCommand-2W37YQW4.js → CreateVersionCommand-XTZT5DED.js} +2 -2
  3. package/build/{DevCommand-JDHE7RQB.js → DevCommand-Q5XLAGMG.js} +2 -2
  4. package/build/DevCommand-Q5XLAGMG.js.map +1 -0
  5. package/build/GenerateCommand-HNFICZJA.js +128 -0
  6. package/build/{GenerateCommand-3PPXF4B6.js.map → GenerateCommand-HNFICZJA.js.map} +1 -1
  7. package/build/LogsCommand-XJHE75L2.js +4 -0
  8. package/build/LogsCommand-XJHE75L2.js.map +1 -0
  9. package/build/PreviewCommand-JKPFMGWV.js +4 -0
  10. package/build/ServeCommand-CPZOI7DC.js +4 -0
  11. package/build/ServeCommand-CPZOI7DC.js.map +1 -0
  12. package/build/build-3RXHADZD.js +4 -0
  13. package/build/build-3RXHADZD.js.map +1 -0
  14. package/build/{chunk-FVG3T57Z.js → chunk-2FB5F5QF.js} +2 -2
  15. package/build/{chunk-TSAKYUDG.js → chunk-4BHNJVL2.js} +2 -2
  16. package/build/{chunk-PSQ4AQFG.js → chunk-6HSUK2A2.js} +2 -2
  17. package/build/{chunk-QXIKCJLU.js → chunk-7VOKCPZP.js} +3 -3
  18. package/build/{chunk-QXIKCJLU.js.map → chunk-7VOKCPZP.js.map} +1 -1
  19. package/build/{chunk-WXOIL7LC.js → chunk-B4SDDVMV.js} +2 -2
  20. package/build/{chunk-DLQYJEV6.js → chunk-C4SXZWXS.js} +2 -2
  21. package/build/{chunk-4CCKO52Z.js → chunk-FKBCPMYK.js} +3 -3
  22. package/build/chunk-FKBCPMYK.js.map +1 -0
  23. package/build/chunk-FMIXY6J5.js +115 -0
  24. package/build/chunk-FMIXY6J5.js.map +1 -0
  25. package/build/{chunk-YIGHU6O6.js → chunk-GWU77DPO.js} +2 -2
  26. package/build/chunk-GWU77DPO.js.map +1 -0
  27. package/build/{chunk-SZ5JWJ4Q.js → chunk-HDXLQ34N.js} +2 -2
  28. package/build/{chunk-2W2YJZP5.js → chunk-JXE3LQ2S.js} +15 -15
  29. package/build/chunk-JXE3LQ2S.js.map +1 -0
  30. package/build/chunk-K2A77MMN.js +4 -0
  31. package/build/chunk-K2A77MMN.js.map +1 -0
  32. package/build/{chunk-C3O7WWDR.js → chunk-KG7BHEJG.js} +2 -2
  33. package/build/chunk-LJEYXY4V.js +4 -0
  34. package/build/chunk-LJEYXY4V.js.map +1 -0
  35. package/build/{chunk-B5P4JHUW.js → chunk-N5D4TFKX.js} +132 -130
  36. package/build/chunk-N5D4TFKX.js.map +1 -0
  37. package/build/{chunk-AXAJ7DJ4.js → chunk-QOUZ6J7N.js} +2 -2
  38. package/build/{chunk-HILXNAWZ.js → chunk-X4BLMM2K.js} +2 -2
  39. package/build/chunk-X4BLMM2K.js.map +1 -0
  40. package/build/cloudflare-runtime/entry.js +300 -48
  41. package/build/cloudflare-runtime/getRegisteredExtensions.js +299 -47
  42. package/build/index.js +2 -2
  43. package/build/platform-sdk/chunk-GZP4Z76C.js +2 -0
  44. package/build/platform-sdk/chunk-GZP4Z76C.js.map +1 -0
  45. package/build/platform-sdk/chunk-KGLNBMRO.js +2 -0
  46. package/build/platform-sdk/chunk-KGLNBMRO.js.map +1 -0
  47. package/build/platform-sdk/dashboard.js +1 -1
  48. package/build/platform-sdk/editor.js +2 -2
  49. package/build/platform-sdk/editor.js.map +1 -1
  50. package/build/platform-sdk/site.js +1 -1
  51. package/build/platform-sdk/site.js.map +1 -1
  52. package/build/preview-TM7JAWFS.js +4 -0
  53. package/build/preview-TM7JAWFS.js.map +1 -0
  54. package/build/render-command-QEQ3L7OX.js +4 -0
  55. package/build/render-command-QEQ3L7OX.js.map +1 -0
  56. package/package.json +7 -6
  57. package/templates/dashboard-plugin/files/plugin.tsx.ejs +8 -18
  58. package/build/DevCommand-JDHE7RQB.js.map +0 -1
  59. package/build/GenerateCommand-3PPXF4B6.js +0 -128
  60. package/build/LogsCommand-LQKTBY6D.js +0 -4
  61. package/build/LogsCommand-LQKTBY6D.js.map +0 -1
  62. package/build/PreviewCommand-H3HVD7DH.js +0 -4
  63. package/build/ServeCommand-RHONEHTF.js +0 -4
  64. package/build/ServeCommand-RHONEHTF.js.map +0 -1
  65. package/build/build-QN6TGE3Q.js +0 -4
  66. package/build/build-QN6TGE3Q.js.map +0 -1
  67. package/build/chunk-2W2YJZP5.js.map +0 -1
  68. package/build/chunk-4CCKO52Z.js.map +0 -1
  69. package/build/chunk-B5P4JHUW.js.map +0 -1
  70. package/build/chunk-F6MVNSX2.js +0 -4
  71. package/build/chunk-F6MVNSX2.js.map +0 -1
  72. package/build/chunk-HILXNAWZ.js.map +0 -1
  73. package/build/chunk-LDGXTJLC.js +0 -4
  74. package/build/chunk-LDGXTJLC.js.map +0 -1
  75. package/build/chunk-YIGHU6O6.js.map +0 -1
  76. package/build/chunk-YMRYABCG.js +0 -115
  77. package/build/chunk-YMRYABCG.js.map +0 -1
  78. package/build/platform-sdk/chunk-32RIHE6N.js +0 -2
  79. package/build/platform-sdk/chunk-32RIHE6N.js.map +0 -1
  80. package/build/platform-sdk/chunk-DGX4CFXG.js +0 -2
  81. package/build/platform-sdk/chunk-DGX4CFXG.js.map +0 -1
  82. package/build/preview-457BTAHF.js +0 -4
  83. package/build/preview-457BTAHF.js.map +0 -1
  84. package/build/render-command-W6CY3R4Q.js +0 -4
  85. package/build/render-command-W6CY3R4Q.js.map +0 -1
  86. /package/build/{CreateVersionCommand-2W37YQW4.js.map → CreateVersionCommand-XTZT5DED.js.map} +0 -0
  87. /package/build/{PreviewCommand-H3HVD7DH.js.map → PreviewCommand-JKPFMGWV.js.map} +0 -0
  88. /package/build/{chunk-FVG3T57Z.js.map → chunk-2FB5F5QF.js.map} +0 -0
  89. /package/build/{chunk-TSAKYUDG.js.map → chunk-4BHNJVL2.js.map} +0 -0
  90. /package/build/{chunk-PSQ4AQFG.js.map → chunk-6HSUK2A2.js.map} +0 -0
  91. /package/build/{chunk-WXOIL7LC.js.map → chunk-B4SDDVMV.js.map} +0 -0
  92. /package/build/{chunk-DLQYJEV6.js.map → chunk-C4SXZWXS.js.map} +0 -0
  93. /package/build/{chunk-SZ5JWJ4Q.js.map → chunk-HDXLQ34N.js.map} +0 -0
  94. /package/build/{chunk-C3O7WWDR.js.map → chunk-KG7BHEJG.js.map} +0 -0
  95. /package/build/{chunk-AXAJ7DJ4.js.map → chunk-QOUZ6J7N.js.map} +0 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../node_modules/@wix/sdk-types/build/browser/index.mjs","../../../node_modules/serialize-error/index.js","../../../node_modules/@wix/sdk/build/wixClient.js","../../../node_modules/@wix/sdk/build/ambassador-modules.js","../../../node_modules/@wix/sdk/build/common.js","../../../node_modules/@wix/sdk/build/fetch-error.js","../../../node_modules/@wix/sdk/build/helpers.js","../../../node_modules/@wix/sdk/build/host-modules.js","../../../node_modules/@wix/sdk/build/bi/biHeaderGenerator.js","../../../node_modules/@wix/sdk-runtime/build/context.js","../../../node_modules/@wix/sdk-runtime/build/context-v2.js","../../../node_modules/@wix/sdk/build/rest-modules.js","../../../node_modules/@wix/sdk/build/event-handlers-modules.js","../../../node_modules/@wix/sdk/build/nanoevents.js","../../../node_modules/@wix/sdk/build/service-plugin-modules.js","../../../node_modules/@wix/sdk/build/web-method-modules.js","../../../node_modules/@wix/sdk/build/get-token-info.js"],"sourcesContent":["// src/event-handlers-modules.ts\nfunction EventDefinition(type, isDomainEvent = false, transformations = (x) => x) {\n return () => ({\n __type: \"event-definition\",\n type,\n isDomainEvent,\n transformations\n });\n}\n\n// src/service-plugins.ts\nfunction ServicePluginDefinition(componentType, methods) {\n return {\n __type: \"service-plugin-definition\",\n componentType,\n methods\n };\n}\nvar SERVICE_PLUGIN_ERROR_TYPE = \"wix_spi_error\";\nexport {\n EventDefinition,\n SERVICE_PLUGIN_ERROR_TYPE,\n ServicePluginDefinition\n};\n","'use strict';\n\nclass NonError extends Error {\n\tconstructor(message) {\n\t\tsuper(NonError._prepareSuperMessage(message));\n\t\tObject.defineProperty(this, 'name', {\n\t\t\tvalue: 'NonError',\n\t\t\tconfigurable: true,\n\t\t\twritable: true\n\t\t});\n\n\t\tif (Error.captureStackTrace) {\n\t\t\tError.captureStackTrace(this, NonError);\n\t\t}\n\t}\n\n\tstatic _prepareSuperMessage(message) {\n\t\ttry {\n\t\t\treturn JSON.stringify(message);\n\t\t} catch {\n\t\t\treturn String(message);\n\t\t}\n\t}\n}\n\nconst commonProperties = [\n\t{property: 'name', enumerable: false},\n\t{property: 'message', enumerable: false},\n\t{property: 'stack', enumerable: false},\n\t{property: 'code', enumerable: true}\n];\n\nconst isCalled = Symbol('.toJSON called');\n\nconst toJSON = from => {\n\tfrom[isCalled] = true;\n\tconst json = from.toJSON();\n\tdelete from[isCalled];\n\treturn json;\n};\n\nconst destroyCircular = ({\n\tfrom,\n\tseen,\n\tto_,\n\tforceEnumerable,\n\tmaxDepth,\n\tdepth\n}) => {\n\tconst to = to_ || (Array.isArray(from) ? [] : {});\n\n\tseen.push(from);\n\n\tif (depth >= maxDepth) {\n\t\treturn to;\n\t}\n\n\tif (typeof from.toJSON === 'function' && from[isCalled] !== true) {\n\t\treturn toJSON(from);\n\t}\n\n\tfor (const [key, value] of Object.entries(from)) {\n\t\tif (typeof Buffer === 'function' && Buffer.isBuffer(value)) {\n\t\t\tto[key] = '[object Buffer]';\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (typeof value === 'function') {\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (!value || typeof value !== 'object') {\n\t\t\tto[key] = value;\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (!seen.includes(from[key])) {\n\t\t\tdepth++;\n\n\t\t\tto[key] = destroyCircular({\n\t\t\t\tfrom: from[key],\n\t\t\t\tseen: seen.slice(),\n\t\t\t\tforceEnumerable,\n\t\t\t\tmaxDepth,\n\t\t\t\tdepth\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\n\t\tto[key] = '[Circular]';\n\t}\n\n\tfor (const {property, enumerable} of commonProperties) {\n\t\tif (typeof from[property] === 'string') {\n\t\t\tObject.defineProperty(to, property, {\n\t\t\t\tvalue: from[property],\n\t\t\t\tenumerable: forceEnumerable ? true : enumerable,\n\t\t\t\tconfigurable: true,\n\t\t\t\twritable: true\n\t\t\t});\n\t\t}\n\t}\n\n\treturn to;\n};\n\nconst serializeError = (value, options = {}) => {\n\tconst {maxDepth = Number.POSITIVE_INFINITY} = options;\n\n\tif (typeof value === 'object' && value !== null) {\n\t\treturn destroyCircular({\n\t\t\tfrom: value,\n\t\t\tseen: [],\n\t\t\tforceEnumerable: true,\n\t\t\tmaxDepth,\n\t\t\tdepth: 0\n\t\t});\n\t}\n\n\t// People sometimes throw things besides Error objects…\n\tif (typeof value === 'function') {\n\t\t// `JSON.stringify()` discards functions. We do too, unless a function is thrown directly.\n\t\treturn `[Function: ${(value.name || 'anonymous')}]`;\n\t}\n\n\treturn value;\n};\n\nconst deserializeError = (value, options = {}) => {\n\tconst {maxDepth = Number.POSITIVE_INFINITY} = options;\n\n\tif (value instanceof Error) {\n\t\treturn value;\n\t}\n\n\tif (typeof value === 'object' && value !== null && !Array.isArray(value)) {\n\t\tconst newError = new Error(); // eslint-disable-line unicorn/error-message\n\t\tdestroyCircular({\n\t\t\tfrom: value,\n\t\t\tseen: [],\n\t\t\tto_: newError,\n\t\t\tmaxDepth,\n\t\t\tdepth: 0\n\t\t});\n\t\treturn newError;\n\t}\n\n\treturn new NonError(value);\n};\n\nmodule.exports = {\n\tserializeError,\n\tdeserializeError\n};\n","import { wixContext } from '@wix/sdk-context';\nimport { SERVICE_PLUGIN_ERROR_TYPE, } from '@wix/sdk-types';\nimport { isAmbassadorModule, toHTTPModule } from './ambassador-modules.js';\nimport { DEFAULT_API_URL, PUBLIC_METADATA_KEY } from './common.js';\nimport { FetchErrorResponse } from './fetch-error.js';\nimport { getDefaultContentHeader, isObject } from './helpers.js';\nimport { buildHostModule, isHostModule } from './host-modules.js';\nimport { buildRESTDescriptor } from './rest-modules.js';\nimport { eventHandlersModules, isEventHandlerModule, } from './event-handlers-modules.js';\nimport { isServicePluginModule, servicePluginsModules, } from './service-plugin-modules.js';\nimport { runWithoutContext } from '@wix/sdk-runtime/context';\nimport { isWebMethodModules, webMethodModules, } from './web-method-modules.js';\nexport function createClient(config) {\n const _headers = config.headers || { Authorization: '' };\n const authStrategy = config.auth ||\n {\n getAuthHeaders: (_) => Promise.resolve({ headers: {} }),\n };\n const boundGetAuthHeaders = authStrategy.getAuthHeaders.bind(undefined, config.host);\n authStrategy.getAuthHeaders = boundGetAuthHeaders;\n const fetchWithAuth = async (urlOrRequest, requestInit) => {\n if (typeof urlOrRequest === 'string' || urlOrRequest instanceof URL) {\n return fetch(urlOrRequest, {\n ...requestInit,\n headers: {\n ...requestInit?.headers,\n ...(await boundGetAuthHeaders()).headers,\n },\n });\n }\n else {\n for (const [k, v] of Object.entries((await boundGetAuthHeaders()).headers)) {\n urlOrRequest.headers.set(k, v);\n }\n return fetch(urlOrRequest, requestInit);\n }\n };\n const { client: servicePluginsClient, initModule: initServicePluginModule } = servicePluginsModules(authStrategy);\n const { client: eventHandlersClient, initModule: initEventHandlerModule } = eventHandlersModules(authStrategy);\n const { client: webMethodClient, initModule } = webMethodModules();\n const boundFetch = async (url, options) => {\n const authHeaders = await boundGetAuthHeaders();\n const defaultContentTypeHeader = getDefaultContentHeader(options);\n return fetch(url, {\n ...options,\n headers: {\n ...defaultContentTypeHeader,\n ..._headers,\n ...authHeaders?.headers,\n ...options?.headers,\n ...config.host?.essentials?.passThroughHeaders,\n },\n });\n };\n // This is typed as `any` because when trying to properly type it as defined\n // on the WixClient, typescript starts failing with `Type instantiation is\n // excessively deep and possibly infinite.`\n const use = (modules, metadata) => {\n if (isEventHandlerModule(modules)) {\n return initEventHandlerModule(modules);\n }\n else if (isServicePluginModule(modules)) {\n return initServicePluginModule(modules);\n }\n else if (isHostModule(modules) && config.host) {\n return buildHostModule(modules, config.host);\n }\n else if (isWebMethodModules(modules)) {\n return initModule(modules);\n }\n else if (typeof modules === 'function') {\n // The generated namespaces all have the error classes on them and\n // a class is also a function, so we need to explicitly ignore these\n // error classes using a static field that exists on them.\n if ('__type' in modules && modules.__type === SERVICE_PLUGIN_ERROR_TYPE) {\n return modules;\n }\n const apiBaseUrl = config.host?.apiBaseUrl ?? DEFAULT_API_URL;\n return buildRESTDescriptor(runWithoutContext(() => isAmbassadorModule(modules))\n ? toHTTPModule(modules)\n : modules, metadata ?? {}, boundFetch, (relativeUrl, fetchOptions) => {\n const finalUrl = new URL(relativeUrl, `https://${apiBaseUrl}`);\n finalUrl.host = apiBaseUrl;\n finalUrl.protocol = 'https';\n return boundFetch(finalUrl.toString(), fetchOptions);\n }, authStrategy.getActiveToken, { HTTPHost: apiBaseUrl }, config.host?.name);\n }\n else if (isObject(modules)) {\n return Object.fromEntries(Object.entries(modules).map(([key, value]) => {\n return [key, use(value, modules[PUBLIC_METADATA_KEY])];\n }));\n }\n else {\n return modules;\n }\n };\n const setHeaders = (headers) => {\n for (const k in headers) {\n _headers[k] = headers[k];\n }\n };\n const wrappedModules = config.modules\n ? use(config.modules)\n : {};\n return {\n ...wrappedModules,\n auth: authStrategy,\n setHeaders,\n use,\n enableContext(contextType, opts = { elevated: false }) {\n if (contextType === 'global') {\n if (globalThis.__wix_context__ != null) {\n if (opts.elevated) {\n globalThis.__wix_context__.elevatedClient = this;\n }\n else {\n globalThis.__wix_context__.client = this;\n }\n }\n else {\n if (opts.elevated) {\n globalThis.__wix_context__ = { elevatedClient: this };\n }\n else {\n globalThis.__wix_context__ = { client: this };\n }\n }\n }\n else {\n if (opts.elevated) {\n wixContext.elevatedClient = this;\n }\n else {\n wixContext.client = this;\n }\n }\n },\n /**\n * @param relativeUrl The URL to fetch relative to the API base URL\n * @param options The fetch options\n * @returns The fetch Response object\n * @deprecated Use `fetchWithAuth` instead\n */\n fetch: (relativeUrl, options) => {\n const apiBaseUrl = config.host?.apiBaseUrl ?? DEFAULT_API_URL;\n const finalUrl = new URL(relativeUrl, `https://${apiBaseUrl}`);\n finalUrl.host = apiBaseUrl;\n finalUrl.protocol = 'https';\n return boundFetch(finalUrl.toString(), options);\n },\n fetchWithAuth,\n async graphql(query, variables, opts = {\n apiVersion: 'alpha',\n }) {\n const apiBaseUrl = config?.host?.apiBaseUrl ?? DEFAULT_API_URL;\n const res = await boundFetch(`https://${apiBaseUrl}/graphql/${opts.apiVersion}`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({ query, variables }),\n });\n if (res.status !== 200) {\n throw new FetchErrorResponse(`GraphQL request failed with status ${res.status}`, res);\n }\n const { data, errors } = await res.json();\n return { data: data ?? {}, errors };\n },\n webhooks: eventHandlersClient,\n webMethods: webMethodClient,\n servicePlugins: servicePluginsClient,\n };\n}\n","const parseMethod = (method) => {\n switch (method) {\n case 'get':\n case 'GET':\n return 'GET';\n case 'post':\n case 'POST':\n return 'POST';\n case 'put':\n case 'PUT':\n return 'PUT';\n case 'delete':\n case 'DELETE':\n return 'DELETE';\n case 'patch':\n case 'PATCH':\n return 'PATCH';\n case 'head':\n case 'HEAD':\n return 'HEAD';\n case 'options':\n case 'OPTIONS':\n return 'OPTIONS';\n default:\n throw new Error(`Unknown method: ${method}`);\n }\n};\nexport const toHTTPModule = (factory) => (httpClient) => async (payload) => {\n let requestOptions;\n const HTTPFactory = (context) => {\n requestOptions = factory(payload)(context);\n if (requestOptions.url === undefined) {\n throw new Error('Url was not successfully created for this request, please reach out to support channels for assistance.');\n }\n const { method, url, params } = requestOptions;\n return {\n ...requestOptions,\n method: parseMethod(method),\n url,\n data: requestOptions.data,\n params,\n };\n };\n try {\n const response = await httpClient.request(HTTPFactory);\n if (requestOptions === undefined) {\n throw new Error('Request options were not created for this request, please reach out to support channels for assistance.');\n }\n const transformations = Array.isArray(requestOptions.transformResponse)\n ? requestOptions.transformResponse\n : [requestOptions.transformResponse];\n /**\n * Based on Axios implementation:\n * https://github.com/axios/axios/blob/3f53eb6960f05a1f88409c4b731a40de595cb825/lib/core/transformData.js#L22\n */\n let data = response.data;\n transformations.forEach((transform) => {\n if (transform) {\n data = transform(response.data, response.headers);\n }\n });\n return data;\n }\n catch (e) {\n if (typeof e === 'object' &&\n e !== null &&\n 'response' in e &&\n typeof e.response === 'object' &&\n e.response !== null &&\n 'data' in e.response) {\n throw e.response.data;\n }\n throw e;\n }\n};\n/*\n * Because of issues with tree-shaking, we cant really put static parameter on module.\n * We still have check for __isAmbassador for backward compatibility\n */\nexport const isAmbassadorModule = (module) => {\n if (module.__isAmbassador) {\n return true;\n }\n const fn = module();\n return Boolean(fn.__isAmbassador);\n};\n","export const PUBLIC_METADATA_KEY = '__metadata';\nexport const DEFAULT_API_URL = 'www.wixapis.com';\nexport const FORCE_WRITE_API_URLS = ['/ecom/v1/carts/current'];\n","export class FetchErrorResponse extends Error {\n message;\n response;\n constructor(message, response) {\n super(message);\n this.message = message;\n this.response = response;\n }\n async details() {\n const dataError = await this.response.json();\n return errorBuilder(this.response.status, dataError?.message, dataError?.details, {\n requestId: this.response.headers.get('X-Wix-Request-Id'),\n details: dataError,\n });\n }\n}\nconst errorBuilder = (code, description, details, data) => {\n return {\n details: {\n ...(!details?.validationError && {\n applicationError: {\n description,\n code,\n data,\n },\n }),\n ...details,\n },\n message: description,\n };\n};\n","// we follow a simplified version of the axios convention\n// https://github.com/axios/axios/blob/649d739288c8e2c55829ac60e2345a0f3439c730/lib/defaults/index.js#L65\nexport const getDefaultContentHeader = (options) => {\n if (options?.method &&\n ['post', 'put', 'patch'].includes(options.method.toLocaleLowerCase()) &&\n options.body) {\n return { 'Content-Type': 'application/json' };\n }\n return {};\n};\nexport const isObject = (val) => val && typeof val === 'object' && !Array.isArray(val);\nexport function parsePublicKeyIfEncoded(publicKey) {\n if (publicKey.includes('\\n') || publicKey.includes('\\r')) {\n // publicKey is multi-line string, can be used as is\n return publicKey.trim();\n }\n else {\n // publicKey is base64 encoded\n return typeof atob !== 'undefined'\n ? atob(publicKey)\n : Buffer.from(publicKey, 'base64').toString('utf-8');\n }\n}\n","export const isHostModule = (val) => val.__type === 'host';\nexport function buildHostModule(val, host) {\n return val.create(host);\n}\n","export const WixBIHeaderName = 'x-wix-bi-gateway';\nexport function biHeaderGenerator(apiMetadata, publicMetadata, environment) {\n return {\n [WixBIHeaderName]: objectToKeyValue({\n environment: `js-sdk${environment ? `-${environment}` : ``}`,\n 'package-name': apiMetadata.packageName ?? publicMetadata?.PACKAGE_NAME,\n 'method-fqn': apiMetadata.methodFqn,\n entity: apiMetadata.entityFqdn,\n }),\n };\n}\nfunction objectToKeyValue(input) {\n return Object.entries(input)\n .filter(([_, value]) => Boolean(value))\n .map(([key, value]) => `${key}=${value}`)\n .join(',');\n}\n","import { wixContext } from '@wix/sdk-context';\nexport function resolveContext() {\n const oldContext = typeof $wixContext !== 'undefined' && $wixContext.initWixModules\n ? $wixContext.initWixModules\n : typeof globalThis.__wix_context__ !== 'undefined' &&\n globalThis.__wix_context__.initWixModules\n ? globalThis.__wix_context__.initWixModules\n : undefined;\n if (oldContext) {\n return {\n // @ts-expect-error\n initWixModules(modules, elevated) {\n return runWithoutContext(() => oldContext(modules, elevated));\n },\n fetchWithAuth() {\n throw new Error('fetchWithAuth is not available in this context');\n },\n graphql() {\n throw new Error('graphql is not available in this context');\n },\n };\n }\n const contextualClient = typeof $wixContext !== 'undefined'\n ? $wixContext.client\n : typeof wixContext.client !== 'undefined'\n ? wixContext.client\n : typeof globalThis.__wix_context__ !== 'undefined'\n ? globalThis.__wix_context__.client\n : undefined;\n const elevatedClient = typeof $wixContext !== 'undefined'\n ? $wixContext.elevatedClient\n : typeof wixContext.elevatedClient !== 'undefined'\n ? wixContext.elevatedClient\n : typeof globalThis.__wix_context__ !== 'undefined'\n ? globalThis.__wix_context__.elevatedClient\n : undefined;\n if (!contextualClient && !elevatedClient) {\n return;\n }\n return {\n initWixModules(wixModules, elevated) {\n if (elevated) {\n if (!elevatedClient) {\n throw new Error('An elevated client is required to use elevated modules. Make sure to initialize the Wix context with an elevated client before using elevated SDK modules');\n }\n return runWithoutContext(() => elevatedClient.use(wixModules));\n }\n if (!contextualClient) {\n throw new Error('Wix context is not available. Make sure to initialize the Wix context before using SDK modules');\n }\n return runWithoutContext(() => contextualClient.use(wixModules));\n },\n fetchWithAuth: (urlOrRequest, requestInit) => {\n if (!contextualClient) {\n throw new Error('Wix context is not available. Make sure to initialize the Wix context before using SDK modules');\n }\n return contextualClient.fetchWithAuth(urlOrRequest, requestInit);\n },\n async graphql(query, variables, opts) {\n if (!contextualClient) {\n throw new Error('Wix context is not available. Make sure to initialize the Wix context before using SDK modules');\n }\n return contextualClient.graphql(query, variables, opts);\n },\n };\n}\nexport function contextualizeHostModule(hostModule, prop) {\n return (...args) => {\n const context = resolveContext();\n if (!context) {\n throw new Error('Wix context is not available. Make sure to initialize the Wix context before using SDK modules');\n }\n return context.initWixModules(hostModule)[prop].apply(undefined, args);\n };\n}\nexport function contextualizeRESTModule(restModule, expectedArgsLength) {\n return ((...args) => {\n const context = resolveContext();\n if (!context) {\n throw new Error('Wix context is not available. Make sure to initialize the Wix context before using SDK modules');\n }\n return context\n .initWixModules(restModule, args[expectedArgsLength]?.suppressAuth ? true : false)\n .apply(undefined, args);\n });\n}\nexport function contextualizeEventDefinitionModule(eventDefinition) {\n return ((...args) => {\n const context = resolveContext();\n if (!context) {\n throw new Error('Wix context is not available. Make sure to initialize the Wix context before using SDK modules');\n }\n return context.initWixModules(eventDefinition).apply(undefined, args);\n });\n}\nexport function contextualizeSerivcePluginModule(servicePlugin) {\n return ((...args) => {\n const context = resolveContext();\n if (!context) {\n throw new Error('Wix context is not available. Make sure to initialize the Wix context before using SDK modules');\n }\n return context.initWixModules(servicePlugin).apply(undefined, args);\n });\n}\nexport * from './context-v2.js';\nexport function runWithoutContext(fn) {\n const globalContext = globalThis.__wix_context__;\n const moduleContext = {\n client: wixContext.client,\n elevatedClient: wixContext.elevatedClient,\n };\n let closureContext;\n globalThis.__wix_context__ = undefined;\n wixContext.client = undefined;\n wixContext.elevatedClient = undefined;\n if (typeof $wixContext !== 'undefined') {\n closureContext = {\n client: $wixContext?.client,\n elevatedClient: $wixContext?.elevatedClient,\n };\n delete $wixContext.client;\n delete $wixContext.elevatedClient;\n }\n try {\n return fn();\n }\n finally {\n globalThis.__wix_context__ = globalContext;\n wixContext.client = moduleContext.client;\n wixContext.elevatedClient = moduleContext.elevatedClient;\n if (typeof $wixContext !== 'undefined') {\n $wixContext.client = closureContext.client;\n $wixContext.elevatedClient = closureContext.elevatedClient;\n }\n }\n}\n","import { EventDefinition, ServicePluginDefinition, } from '@wix/sdk-types';\nimport { resolveContext } from './context.js';\nexport { EventDefinition, ServicePluginDefinition, };\nexport function contextualizeHostModuleV2(hostModule, props) {\n return {\n ...hostModule,\n ...Object.fromEntries(props.map((prop) => [\n prop,\n (...args) => {\n const context = resolveContext();\n if (!context) {\n throw new Error('Wix context is not available. Make sure to initialize the Wix context before using SDK modules');\n }\n return context\n .initWixModules(hostModule)[prop].apply(undefined, args);\n },\n ])),\n };\n}\nexport function contextualizeRESTModuleV2(restModule, elevated) {\n return ((...args) => {\n const context = resolveContext();\n if (!context) {\n // @ts-expect-error - if there is no context, we want to behave like the original module\n return restModule.apply(undefined, args);\n }\n return (context\n .initWixModules(restModule, elevated)\n // @ts-expect-error - we know the args here are meant to be passed to the initalized module\n .apply(undefined, args));\n });\n}\nexport function contextualizeEventDefinitionModuleV2(eventDefinition) {\n const contextualMethod = ((...args) => {\n const context = resolveContext();\n if (!context) {\n // this line should throw, but this would be a breaking change for older SDK versions\n // this is because in wixClient there's code that calls any function it detects and checks\n // if it's an ambassador module (see isAmbassadorModule)\n return () => { };\n }\n return context.initWixModules(eventDefinition).apply(undefined, args);\n });\n contextualMethod.__type = eventDefinition.__type;\n contextualMethod.type = eventDefinition.type;\n contextualMethod.isDomainEvent = eventDefinition.isDomainEvent;\n contextualMethod.transformations = eventDefinition.transformations;\n return contextualMethod;\n}\nexport function contextualizeSerivcePluginModuleV2(servicePlugin) {\n const contextualMethod = ((...args) => {\n const context = resolveContext();\n if (!context) {\n // this line should throw, but this would be a breaking change for older SDK versions\n // this is because in wixClient there's code that calls any function it detects and checks\n // if it's an ambassador module (see isAmbassadorModule)\n return () => { };\n }\n return context.initWixModules(servicePlugin).apply(undefined, args);\n });\n contextualMethod.__type = servicePlugin.__type;\n contextualMethod.componentType = servicePlugin.componentType;\n contextualMethod.methods = servicePlugin.methods;\n return contextualMethod;\n}\n","import { biHeaderGenerator } from './bi/biHeaderGenerator.js';\nimport { DEFAULT_API_URL } from './common.js';\nimport { runWithoutContext } from '@wix/sdk-runtime/context';\nexport function buildRESTDescriptor(origFunc, publicMetadata, boundFetch, wixAPIFetch, getActiveToken, options, hostName) {\n return runWithoutContext(() => origFunc({\n request: async (factory) => {\n const requestOptions = factory({\n host: options?.HTTPHost || DEFAULT_API_URL,\n });\n let request = requestOptions;\n if (request.method === 'GET' &&\n request.fallback?.length &&\n request.params.toString().length > 4000) {\n request = requestOptions.fallback[0];\n }\n const domain = options?.HTTPHost ?? DEFAULT_API_URL;\n let url = `https://${domain}${request.url}`;\n if (request.params && request.params.toString()) {\n url += `?${request.params.toString()}`;\n }\n try {\n const biHeader = biHeaderGenerator(requestOptions, publicMetadata, hostName);\n const res = await boundFetch(url, {\n method: request.method,\n ...(request.data && {\n body: JSON.stringify(request.data),\n }),\n headers: {\n ...biHeader,\n },\n });\n if (res.status !== 200) {\n let dataError = null;\n try {\n dataError = await res.json();\n }\n catch (e) {\n //\n }\n throw errorBuilder(res.status, dataError?.message, dataError?.details, {\n requestId: res.headers.get('X-Wix-Request-Id'),\n details: dataError,\n });\n }\n const data = await res.json();\n return {\n data,\n headers: res.headers,\n status: res.status,\n statusText: res.statusText,\n };\n }\n catch (e) {\n if (e.message?.includes('fetch is not defined')) {\n console.error('Node.js v18+ is required');\n }\n throw e;\n }\n },\n fetchWithAuth: boundFetch,\n wixAPIFetch,\n getActiveToken,\n }));\n}\nconst errorBuilder = (code, description, details, data) => {\n return {\n response: {\n data: {\n details: {\n ...(!details?.validationError && {\n applicationError: {\n description,\n code,\n data,\n },\n }),\n ...details,\n },\n message: description,\n },\n status: code,\n },\n };\n};\n","import { EventDefinition, } from '@wix/sdk-types';\nimport { createNanoEvents } from './nanoevents.js';\nexport const isEventHandlerModule = (val) => val.__type === 'event-definition';\nexport function buildEventDefinition(eventDefinition, registerHandler) {\n return (handler) => {\n registerHandler(eventDefinition, handler);\n };\n}\nfunction runHandler(eventDefinition, handler, payload, baseEventMetadata) {\n let envelope;\n if (eventDefinition.isDomainEvent) {\n const domainEventPayload = payload;\n const { deletedEvent, actionEvent, createdEvent, updatedEvent, ...domainEventMetadata } = domainEventPayload;\n const metadata = {\n ...baseEventMetadata,\n ...domainEventMetadata,\n };\n if (deletedEvent) {\n if (deletedEvent?.deletedEntity) {\n envelope = {\n entity: deletedEvent?.deletedEntity,\n metadata,\n };\n }\n else {\n envelope = { metadata };\n }\n }\n else if (actionEvent) {\n envelope = {\n data: actionEvent.body,\n metadata,\n };\n }\n else {\n envelope = {\n entity: createdEvent?.entity ?? updatedEvent?.currentEntity,\n metadata,\n };\n }\n }\n else {\n envelope = {\n data: payload,\n metadata: baseEventMetadata,\n };\n }\n const transformFromRESTFn = eventDefinition.transformations ?? ((x) => x);\n return handler(transformFromRESTFn(envelope));\n}\nexport function eventHandlersModules(authStrategy) {\n const eventHandlers = new Map();\n const webhooksEmitter = createNanoEvents();\n const client = {\n ...webhooksEmitter,\n getRegisteredEvents: () => eventHandlers,\n async process(jwt, opts = {\n expectedEvents: [],\n }) {\n const { eventType, identity, instanceId, payload } = await this.parseJWT(jwt);\n const allExpectedEvents = [\n ...opts.expectedEvents,\n ...Array.from(eventHandlers.keys()).map((type) => ({ type })),\n ];\n if (allExpectedEvents.length > 0 &&\n !allExpectedEvents.some(({ type }) => type === eventType)) {\n throw new Error(`Unexpected event type: ${eventType}. Expected one of: ${allExpectedEvents\n .map((x) => x.type)\n .join(', ')}`);\n }\n const handlers = eventHandlers.get(eventType) ?? [];\n await Promise.all(handlers.map(({ eventDefinition, handler }) => runHandler(eventDefinition, handler, payload, {\n instanceId,\n identity,\n })));\n return {\n instanceId,\n eventType,\n payload,\n identity,\n };\n },\n async processRequest(request, opts) {\n const body = await request.text();\n return this.process(body, opts);\n },\n async parseJWT(jwt) {\n if (!authStrategy.decodeJWT) {\n throw new Error('decodeJWT is not supported by the authentication strategy');\n }\n const { decoded, valid } = await authStrategy.decodeJWT(jwt);\n if (!valid) {\n throw new Error('JWT is not valid');\n }\n if (typeof decoded.data !== 'string') {\n throw new Error(`Unexpected type of JWT data: expected string, got ${typeof decoded.data}`);\n }\n const parsedDecoded = JSON.parse(decoded.data);\n const eventType = parsedDecoded.eventType;\n const instanceId = parsedDecoded.instanceId;\n const identity = parsedDecoded.identity\n ? JSON.parse(parsedDecoded.identity)\n : undefined;\n const payload = JSON.parse(parsedDecoded.data);\n return {\n instanceId,\n eventType,\n payload,\n identity,\n };\n },\n async parseRequest(request) {\n const jwt = await request.text();\n return this.parseJWT(jwt);\n },\n async executeHandlers(event) {\n const allExpectedEvents = Array.from(eventHandlers.keys()).map((type) => ({ type }));\n if (allExpectedEvents.length > 0 &&\n !allExpectedEvents.some(({ type }) => type === event.eventType)) {\n throw new Error(`Unexpected event type: ${event.eventType}. Expected one of: ${allExpectedEvents\n .map((x) => x.type)\n .join(', ')}`);\n }\n const handlers = eventHandlers.get(event.eventType) ?? [];\n await Promise.all(handlers.map(({ eventDefinition, handler }) => runHandler(eventDefinition, handler, event.payload, {\n instanceId: event.instanceId,\n identity: event.identity,\n })));\n },\n apps: {\n AppInstalled: EventDefinition('AppInstalled')(),\n AppRemoved: EventDefinition('AppRemoved')(),\n },\n };\n return {\n initModule(eventDefinition) {\n return (handler) => {\n const handlers = eventHandlers.get(eventDefinition.type) ?? [];\n handlers.push({ eventDefinition, handler });\n eventHandlers.set(eventDefinition.type, handlers);\n webhooksEmitter.emit('registered', eventDefinition);\n };\n },\n client,\n };\n}\n","// Inlined from https://github.com/ai/nanoevents/blob/main/index.js\n/**\n * Create event emitter.\n *\n * ```js\n * import { createNanoEvents } from 'nanoevents'\n *\n * class Ticker {\n * constructor() {\n * this.emitter = createNanoEvents()\n * }\n * on(...args) {\n * return this.emitter.on(...args)\n * }\n * tick() {\n * this.emitter.emit('tick')\n * }\n * }\n * ```\n * @returns Event emitter.\n */\nexport function createNanoEvents() {\n return {\n emit(event, ...args) {\n for (let i = 0, callbacks = this.events[event] || [], length = callbacks.length; i < length; i++) {\n callbacks[i](...args);\n }\n },\n events: {},\n on(event, cb) {\n (this.events[event] ||= []).push(cb);\n return () => {\n this.events[event] = this.events[event]?.filter((i) => cb !== i);\n };\n },\n };\n}\n","import { createNanoEvents } from './nanoevents.js';\nexport const isServicePluginModule = (val) => val.__type === 'service-plugin-definition';\nexport function servicePluginsModules(authStrategy) {\n const servicePluginsImplementations = new Map();\n const servicePluginsEmitter = createNanoEvents();\n const client = {\n ...servicePluginsEmitter,\n getRegisteredServicePlugins: () => servicePluginsImplementations,\n async parseJWT(jwt) {\n if (!authStrategy.decodeJWT) {\n throw new Error('decodeJWT is not supported by the authentication strategy');\n }\n const { decoded, valid } = await authStrategy.decodeJWT(jwt, true);\n if (!valid) {\n throw new Error('JWT is not valid');\n }\n if (typeof decoded.data !== 'object' ||\n decoded.data === null ||\n !('metadata' in decoded.data) ||\n typeof decoded.data.metadata !== 'object' ||\n decoded.data.metadata === null ||\n !('appExtensionType' in decoded.data.metadata) ||\n typeof decoded.data.metadata.appExtensionType !== 'string') {\n throw new Error('Unexpected JWT data: expected object with metadata.appExtensionType string');\n }\n return decoded.data;\n },\n async process(request) {\n const servicePluginRequest = await this.parseJWT(request.body);\n return this.executeHandler(servicePluginRequest, request.url);\n },\n async parseRequest(request) {\n const body = await request.text();\n return this.parseJWT(body);\n },\n async processRequest(request) {\n const url = request.url;\n const body = await request.text();\n try {\n const implMethodResult = await this.process({ url, body });\n return Response.json(implMethodResult);\n }\n catch (err) {\n if (err.errorType === 'SPI' && err.applicationCode && err.httpCode) {\n return Response.json({ applicationError: { code: err.applicationCode, data: err.data } }, { status: err.httpCode });\n }\n throw err;\n }\n },\n async executeHandler(servicePluginRequest, url) {\n const componentType = servicePluginRequest.metadata.appExtensionType.toLowerCase();\n const implementations = servicePluginsImplementations.get(componentType) ?? [];\n if (implementations.length === 0) {\n throw new Error(`No service plugin implementations found for component type ${componentType}`);\n }\n else if (implementations.length > 1) {\n throw new Error(`Multiple service plugin implementations found for component type ${componentType}. This is currently not supported`);\n }\n const { implementation: impl, servicePluginDefinition } = implementations[0];\n const method = servicePluginDefinition.methods.find((m) => url.endsWith(m.primaryHttpMappingPath));\n if (!method) {\n throw new Error('Unexpect request: request url did not match any method: ' + url);\n }\n const implMethod = impl[method.name];\n if (!implMethod) {\n throw new Error(`Got request for service plugin method ${method.name} but no implementation was provided. Available methods: ${Object.keys(impl).join(', ')}`);\n }\n return method.transformations.toREST(await implMethod(method.transformations.fromREST(servicePluginRequest)));\n },\n };\n return {\n initModule(servicePluginDefinition) {\n return (implementation) => {\n const implementations = servicePluginsImplementations.get(servicePluginDefinition.componentType.toLowerCase()) ?? [];\n implementations.push({ servicePluginDefinition, implementation });\n servicePluginsImplementations.set(servicePluginDefinition.componentType.toLowerCase(), implementations);\n servicePluginsEmitter.emit('registered', servicePluginDefinition);\n };\n },\n client,\n };\n}\n","import { serializeError } from 'serialize-error';\nimport { getTokenInfo } from './get-token-info.js';\nexport const isWebMethodModules = (val) => val.__type === 'web-method-module';\nvar Permissions;\n(function (Permissions) {\n Permissions[\"Anyone\"] = \"anyone\";\n Permissions[\"Admin\"] = \"admin\";\n Permissions[\"SiteMember\"] = \"site-member\";\n})(Permissions || (Permissions = {}));\nasync function checkPermission(request, permission) {\n const accessToken = request.headers.get('Authorization');\n if (!accessToken) {\n throw new Error('Request is missing authentication data');\n }\n const { subjectType } = await getTokenInfo(accessToken);\n switch (permission) {\n case Permissions.Anyone: {\n if (subjectType !== 'VISITOR' &&\n subjectType !== 'MEMBER' &&\n subjectType !== 'USER') {\n throw new Error('Insufficient permissions');\n }\n break;\n }\n case Permissions.SiteMember: {\n if (subjectType !== 'MEMBER' && subjectType !== 'USER') {\n throw new Error('Insufficient permissions');\n }\n break;\n }\n case Permissions.Admin: {\n if (subjectType !== 'USER') {\n throw new Error('Insufficient permissions');\n }\n break;\n }\n }\n}\nconst urlRegex = /\\/_webMethods\\/(.+\\..+)\\/(.+\\..+)/;\n// /_webMethods/backend/my-module.web.js/multiply.ajax\nfunction extractUrlParts(url) {\n const parts = url.match(urlRegex);\n if (parts) {\n return [parts[1], parts[2].replace('.ajax', '')];\n }\n}\nfunction isRequestBodyValid(body) {\n return !!body && typeof body === 'object' && Array.isArray(body);\n}\nconst productionErrorMessage = 'Error: Unable to handle the request. Contact the site administrator or view site monitoring logs for more information.';\nexport function webMethodModules() {\n const webMethods = {};\n const client = {\n async processRequest(request, devMode = false) {\n const urlParts = extractUrlParts(request.url);\n if (!urlParts) {\n return new Response('invalid request', { status: 400 });\n }\n const [file, method] = urlParts;\n const body = (await request.json());\n if (!isRequestBodyValid(body)) {\n return new Response('invalid request', { status: 400 });\n }\n const loadWebMethodFile = webMethods[`/${file}`];\n try {\n if (!loadWebMethodFile) {\n throw new Error(`Error loading web module ${file}: Cannot find module '${file}'`);\n }\n const webMethodFile = await loadWebMethodFile();\n const webMethod = webMethodFile[method];\n if (!webMethod) {\n throw new Error(`Error loading function from web module ${file}: function '${method}' not found`);\n }\n await checkPermission(request, webMethod.permission);\n return Response.json({\n result: await webMethod.handler(...body),\n });\n }\n catch (error) {\n const serializedError = serializeError(error, { maxDepth: 1 });\n return Response.json({\n result: devMode || !(error instanceof Error)\n ? serializedError\n : {\n ...serializedError,\n message: productionErrorMessage,\n stack: productionErrorMessage,\n },\n exception: true,\n });\n }\n },\n };\n return {\n initModule(webMethodModule) {\n Object.assign(webMethods, webMethodModule);\n },\n client,\n };\n}\n","export async function getTokenInfo(token) {\n const tokenInfoRes = await fetch('https://www.wixapis.com/oauth2/token-info', {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({\n token,\n }),\n });\n if (tokenInfoRes.status !== 200) {\n throw new Error(`Failed to get token info. Unexpected status code from Wix OAuth API: ${tokenInfoRes.status}`);\n }\n return (await tokenInfoRes.json());\n}\n"],"mappings":"wEAAA,IAAAA,GAAA,GAAAC,GAAAD,GAAA,qBAAAE,EAAA,8BAAAC,EAAA,4BAAAC,KACA,SAASF,EAAgBG,EAAMC,EAAgB,GAAOC,EAAmBC,GAAMA,EAAG,CAChF,MAAO,KAAO,CACZ,OAAQ,mBACR,KAAAH,EACA,cAAAC,EACA,gBAAAC,CACF,EACF,CAGA,SAASH,GAAwBK,EAAeC,EAAS,CACvD,MAAO,CACL,OAAQ,4BACR,cAAAD,EACA,QAAAC,CACF,CACF,CAjBA,IAkBIP,EAlBJQ,EAAAC,GAAA,kBAkBIT,EAA4B,kBClBhC,IAAAU,EAAAC,GAAA,CAAAC,GAAAC,IAAA,cAEA,IAAMC,EAAN,MAAMC,UAAiB,KAAM,CAC5B,YAAYC,EAAS,CACpB,MAAMD,EAAS,qBAAqBC,CAAO,CAAC,EAC5C,OAAO,eAAe,KAAM,OAAQ,CACnC,MAAO,WACP,aAAc,GACd,SAAU,EACX,CAAC,EAEG,MAAM,mBACT,MAAM,kBAAkB,KAAMD,CAAQ,CAExC,CAEA,OAAO,qBAAqBC,EAAS,CACpC,GAAI,CACH,OAAO,KAAK,UAAUA,CAAO,CAC9B,MAAQ,CACP,OAAO,OAAOA,CAAO,CACtB,CACD,CACD,EAEMC,GAAmB,CACxB,CAAC,SAAU,OAAQ,WAAY,EAAK,EACpC,CAAC,SAAU,UAAW,WAAY,EAAK,EACvC,CAAC,SAAU,QAAS,WAAY,EAAK,EACrC,CAAC,SAAU,O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AK,UAAU,CAAE,MAAAE,EAAO,UAAAC,CAAU,CAAC,CAC7C,CAAC,EACD,GAAIC,EAAI,SAAW,IACf,MAAM,IAAIC,EAAmB,sCAAsCD,EAAI,MAAM,GAAIA,CAAG,EAExF,GAAM,CAAE,KAAAE,EAAM,OAAAC,EAAO,EAAI,MAAMH,EAAI,KAAK,EACxC,MAAO,CAAE,KAAME,GAAQ,CAAC,EAAG,OAAAC,EAAO,CACtC,EACA,SAAU5C,EACV,WAAYG,EACZ,eAAgBN,CACpB,CACJ","names":["browser_exports","__export","EventDefinition","SERVICE_PLUGIN_ERROR_TYPE","ServicePluginDefinition","type","isDomainEvent","transformations","x","componentType","methods","init_browser","__esmMin","require_serialize_error","__commonJSMin","exports","module","NonError","_NonError","message","commonProperties","isCalled","toJSON","from","json","destroyCircular","seen","to_","forceEnumerable","maxDepth","depth","to","key","value","property","enumerable","serializeError","options","deserializeError","newError","init_browser","wixContext","parseMethod","method","toHTTPModule","factory","httpClient","payload","requestOptions","HTTPFactory","context","url","params","response","transformations","data","transform","e","isAmbassadorModule","module","PUBLIC_METADATA_KEY","DEFAULT_API_URL","FetchErrorResponse","message","response","__publicField","dataError","errorBuilder","code","description","details","data","getDefaultContentHeader","options","isObject","val","isHostModule","val","buildHostModule","host","WixBIHeaderName","biHeaderGenerator","apiMetadata","publicMetadata","environment","objectToKeyValue","input","_","value","key","wixContext","contextualizeHostModuleV2","hostModule","props","prop","args","context","resolveContext","resolveContext","oldContext","modules","elevated","runWithoutContext","contextualClient","wixContext","elevatedClient","wixModules","urlOrRequest","requestInit","query","variables","opts","runWithoutContext","fn","globalContext","moduleContext","wixContext","closureContext","buildRESTDescriptor","origFunc","publicMetadata","boundFetch","wixAPIFetch","getActiveToken","options","hostName","runWithoutContext","factory","requestOptions","DEFAULT_API_URL","request","url","biHeader","biHeaderGenerator","res","dataError","errorBuilder","e","code","description","details","data","init_browser","createNanoEvents","event","args","i","callbacks","length","cb","isEventHandlerModule","val","runHandler","eventDefinition","handler","payload","baseEventMetadata","envelope","domainEventPayload","deletedEvent","actionEvent","createdEvent","updatedEvent","domainEventMetadata","metadata","transformFromRESTFn","x","eventHandlersModules","authStrategy","eventHandlers","webhooksEmitter","createNanoEvents","client","jwt","opts","eventType","identity","instanceId","allExpectedEvents","type","handlers","request","body","decoded","valid","parsedDecoded","event","EventDefinition","isServicePluginModule","val","servicePluginsModules","authStrategy","servicePluginsImplementations","servicePluginsEmitter","createNanoEvents","client","jwt","decoded","valid","request","servicePluginRequest","body","url","implMethodResult","err","componentType","implementations","impl","servicePluginDefinition","method","m","implMethod","implementation","import_serialize_error","getTokenInfo","token","tokenInfoRes","isWebMethodModules","val","Permissions","checkPermission","request","permission","accessToken","subjectType","getTokenInfo","urlRegex","extractUrlParts","url","parts","isRequestBodyValid","body","productionErrorMessage","webMethodModules","webMethods","webMethodModule","devMode","urlParts","file","method","loadWebMethodFile","webMethod","error","serializedError","createClient","config","_headers","authStrategy","_","boundGetAuthHeaders","fetchWithAuth","urlOrRequest","requestInit","k","v","servicePluginsClient","initServicePluginModule","servicePluginsModules","eventHandlersClient","initEventHandlerModule","eventHandlersModules","webMethodClient","initModule","webMethodModules","boundFetch","url","options","authHeaders","defaultContentTypeHeader","getDefaultContentHeader","use","modules","metadata","isEventHandlerModule","isServicePluginModule","isHostModule","buildHostModule","isWebMethodModules","SERVICE_PLUGIN_ERROR_TYPE","apiBaseUrl","DEFAULT_API_URL","buildRESTDescriptor","runWithoutContext","isAmbassadorModule","toHTTPModule","relativeUrl","fetchOptions","finalUrl","isObject","key","value","PUBLIC_METADATA_KEY","setHeaders","headers","contextType","opts","wixContext","query","variables","res","FetchErrorResponse","data","errors"]}
@@ -1,2 +1,2 @@
1
- import{a as V}from"./chunk-DGX4CFXG.js";import{c as D}from"./chunk-32RIHE6N.js";import"./chunk-SBZEOPXX.js";function S(){return S=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)({}).hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},S.apply(null,arguments)}import ke,{useEffect as le,useState as z}from"react";function y(e){"@babel/helpers - typeof";return y=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},y(e)}function q(e,t){if(y(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t||"default");if(y(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function F(e){var t=q(e,"string");return y(t)=="symbol"?t:t+""}function N(e,t,r){return(t=F(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}var v=class extends Error{constructor(t){let{message:r,code:n}=t;super(r),N(this,"code",void 0),this.message=r,this.code=n}};var K=()=>{let e=l=>{let{channel:c}=l;return function(){let f=c.showToast(...arguments);return{remove:()=>Promise.resolve(f).then(h=>h.remove())}}},t=l=>{let{channel:c}=l;return function(){let f=c.observeState(...arguments);return{disconnect:()=>Promise.resolve(f).then(h=>h.disconnect())}}};return{showToast:e,observeState:t,navigate:l=>{let{channel:c}=l;return function(){return c.navigate(...arguments)}},navigateBack:l=>{let{channel:c}=l;return()=>c.navigateBack()},openModal:l=>{let{channel:c}=l;return function(){let f=c.openModal(...arguments);return{modalClosed:Promise.resolve(f).then(g=>g.modalClosed)}}},closeModal:l=>{let{channel:c}=l;return f=>{if(f===void 0)return c.closeModal();let g=JSON.parse(JSON.stringify(f));return c.closeModal(g)}},getAccessToken:l=>{let{channel:c}=l;return()=>c.getAccessToken()},getPageUrl:l=>{let{channel:c}=l;return function(){return c.getPageUrl(...arguments)}},openMediaManager:l=>{let{channel:c}=l;return function(){return c.openMediaManager(...arguments)}},addSitePlugin:l=>{let{channel:c}=l;return(f,g)=>{let h="802c76e4-b381-4bb3-9152-96acabbf3194",j=g?.placement||{},H=c.openModal(h,{...j,pluginId:f,action:"populate"});return Promise.resolve(H).then(b=>b.modalClosed).then(b=>{if(b?.type===void 0)throw new v({message:"Aborted by user",code:3006});if(b?.type==="ERROR")throw new v(b.data.error)})}},onBeforeUnload:l=>{let{channel:c}=l;return function(){return c.onBeforeUnload(...arguments)}},setPageTitle:l=>{let{channel:c}=l;return f=>c.setPageTitle(f)},getLanguage:l=>{let c=null;return async()=>{var f;if(c)return c;let g=null;return c=await new Promise(h=>{g=t(l)((j,H)=>{h(H.language)})}),(f=g)==null||f.disconnect(),c}},requestFeedback:l=>{let{channel:c}=l;return function(){return c.requestFeedback(...arguments)}}}};var G=e=>{let{createHost:t}=e,r=K();return{...V(r),host:t,auth:()=>({getAuthHeaders:async n=>({headers:{Authorization:await r.getAccessToken(n)()}})})}};var J=(e,t)=>{let r=()=>e.updateHeight(t.offsetHeight),n=new ResizeObserver(r);return n.observe(t),()=>n.disconnect()};var X=Symbol("Comlink.proxy"),de=Symbol("Comlink.endpoint"),C=Symbol("Comlink.releaseProxy"),O=Symbol("Comlink.thrown"),Q=e=>typeof e=="object"&&e!==null||typeof e=="function",fe={canHandle:e=>Q(e)&&e[X],serialize(e){let{port1:t,port2:r}=new MessageChannel;return R(e,t),[r,[r]]},deserialize(e){return e.start(),_(e)}},me={canHandle:e=>Q(e)&&O in e,serialize({value:e}){let t;return e instanceof Error?t={isError:!0,value:{message:e.message,name:e.name,stack:e.stack}}:t={isError:!1,value:e},[t,[]]},deserialize(e){throw e.isError?Object.assign(new Error(e.value.message),e.value):e.value}},Y=new Map([["proxy",fe],["throw",me]]);function R(e,t=self){t.addEventListener("message",function r(n){if(!n||!n.data)return;let{id:o,type:a,path:s}=Object.assign({path:[]},n.data),i=(n.data.argumentList||[]).map(w),u;try{let d=s.slice(0,-1).reduce((p,x)=>p[x],e),m=s.reduce((p,x)=>p[x],e);switch(a){case 0:u=m;break;case 1:d[s.slice(-1)[0]]=w(n.data.value),u=!0;break;case 2:u=m.apply(d,i);break;case 3:{let p=new m(...i);u=M(p)}break;case 4:{let{port1:p,port2:x}=new MessageChannel;R(e,x),u=he(p,[p])}break;case 5:u=void 0;break}}catch(d){u={value:d,[O]:0}}Promise.resolve(u).catch(d=>({value:d,[O]:0})).then(d=>{let[m,p]=T(d);t.postMessage(Object.assign(Object.assign({},m),{id:o}),p),a===5&&(t.removeEventListener("message",r),Z(t))})}),t.start&&t.start()}function pe(e){return e.constructor.name==="MessagePort"}function Z(e){pe(e)&&e.close()}function _(e,t){return U(e,[],t)}function k(e){if(e)throw new Error("Proxy has been released and is not useable")}function U(e,t=[],r=function(){}){let n=!1,o=new Proxy(r,{get(a,s){if(k(n),s===C)return()=>P(e,{type:5,path:t.map(i=>i.toString())}).then(()=>{Z(e),n=!0});if(s==="then"){if(t.length===0)return{then:()=>o};let i=P(e,{type:0,path:t.map(u=>u.toString())}).then(w);return i.then.bind(i)}return U(e,[...t,s])},set(a,s,i){k(n);let[u,d]=T(i);return P(e,{type:1,path:[...t,s].map(m=>m.toString()),value:u},d).then(w)},apply(a,s,i){k(n);let u=t[t.length-1];if(u===de)return P(e,{type:4}).then(w);if(u==="bind")return U(e,t.slice(0,-1));let[d,m]=$(i);return P(e,{type:2,path:t.map(p=>p.toString()),argumentList:d},m).then(w)},construct(a,s){k(n);let[i,u]=$(s);return P(e,{type:3,path:t.map(d=>d.toString()),argumentList:i},u).then(w)}});return o}function ge(e){return Array.prototype.concat.apply([],e)}function $(e){let t=e.map(T);return[t.map(r=>r[0]),ge(t.map(r=>r[1]))]}var ee=new WeakMap;function he(e,t){return ee.set(e,t),e}function M(e){return Object.assign(e,{[X]:!0})}function T(e){for(let[t,r]of Y)if(r.canHandle(e)){let[n,o]=r.serialize(e);return[{type:3,name:t,value:n},o]}return[{type:0,value:e},ee.get(e)||[]]}function w(e){switch(e.type){case 3:return Y.get(e.name).deserialize(e.value);case 0:return e.value}}function P(e,t,r){return new Promise(n=>{let o=be();e.addEventListener("message",function a(s){!s.data||!s.data.id||s.data.id!==o||(e.removeEventListener("message",a),n(s.data))}),e.start&&e.start(),e.postMessage(Object.assign({id:o},t),r)})}function be(){return new Array(4).fill(0).map(()=>Math.floor(Math.random()*Number.MAX_SAFE_INTEGER).toString(16)).join("-")}var B="__proxyCallbackId__wixSDK__",L="__proxyPromiseId__wixSDK__",re=e=>we(e,t=>async function(){for(var r=arguments.length,n=new Array(r),o=0;o<r;o++)n[o]=arguments[o];let[a,s]=I(n),i=await t(M(a),s);return ne(i)});var ye=async e=>{let[t,r]=I(await e);return M({proxies:t,clonables:r})},ne=async e=>A(e?.proxies,await e?.clonables),I=e=>{let t=(o,a)=>{if(oe(a)){let s=te();return o.promises[s]=a,{[L]:s}}if(xe(a)){let s=te();return o.callbacks[s]=(i,u)=>{let d=A(i,u),m=a(...d);return ye(m)},{[B]:s}}return Array.isArray(a)?a.map(s=>t(o,s)):E(a)?se(a,s=>t(o,s)):a},r={promises:{},callbacks:{}},n=t(r,e);return[r,n]},A=(e,t)=>{if(Array.isArray(t))return t.map(r=>A(e,r));if(E(t)&&t.hasOwnProperty(L)){let r=t[L];return e.promises[r]}if(E(t)&&t.hasOwnProperty(B)){let r=t[B];return async function(){for(var n=arguments.length,o=new Array(n),a=0;a<n;a++)o[a]=arguments[a];let[s,i]=I(o),u=await e.callbacks[r](M(s),i);return ne(u)}}return E(t)?se(t,r=>A(e,r)):t},we=(e,t)=>new Proxy(e,{get(r,n){return r[n]?t(r[n]):()=>{throw new Error(`Serialization error occurred while accessing ${n} property of ${r}`)}}}),oe=e=>e instanceof Promise,E=e=>e&&typeof e=="object"&&!oe(e),xe=e=>typeof e=="function",se=(e,t)=>{let r=n=>{let[o,a]=n;return[o,t(a)]};return Object.fromEntries(Object.entries(e).map(r))},te=(()=>{let e=0;return()=>++e})();var Pe="wix-sdk-bo-hello-handshake",ae=e=>{let{postMessage:t,origin:r}=e,{port1:n,port2:o}=new MessageChannel;t({code:Pe,version:"1.0.0",port:o},r,[o]);let i=re(_(n));return{channel:i,close:()=>i[C]()}};var ve=["https://manage.wix.com","https://manage.editorx.com"],Me=new Set(ve),ie=e=>Me.has(e);var ce=e=>{let t=new EventTarget,r=typeof window>"u",n=i=>{t.dispatchEvent(new CustomEvent("beforeunload",{cancelable:!0}))||(i.preventDefault(),i.returnValue=!0)},o=e.onBeforeUnload(n),a=()=>{r||window.removeEventListener("beforeunload",n),o.then(i=>{let{remove:u}=i;return u()})};return r||(window.addEventListener("beforeunload",n),window.addEventListener("unload",a)),{onBeforeUnload:i=>(t.addEventListener("beforeunload",i),{remove:()=>{t.removeEventListener("beforeunload",i)}}),clearBeforeUnloadHandler:a}};var ue=function(e){e===void 0&&(e={});let t=new URLSearchParams(typeof window<"u"?window.location.search:"?"),r=e.origin||t.get("origin")||"",n=e.postMessage||window.parent.postMessage.bind(window.parent);if(!ie(r))throw new Error("Wix Dashboard SDK: Unable to establish a connection with the Wix dashboard. Please ensure that you are running your app within the Wix dashboard.");let{channel:o,close:a}=ae({postMessage:n,origin:r}),s=[a];if(e.autoHeightUpdate===void 0||e.autoHeightUpdate){let d=e.autoHeightElement||document.documentElement,m=J(o,d);s.push(()=>m())}let{onBeforeUnload:i,clearBeforeUnloadHandler:u}=ce(o);return s.push(u),{channel:{...o,showToast:o.showToast,navigate:o.navigate,navigateBack:o.navigateBack,updateHeight:o.updateHeight,observeState:o.observeState,closeModal:o.closeModal,openModal:o.openModal,getAccessToken:o.getAccessToken,getPageUrl:o.getPageUrl,setPageTitle:o.setPageTitle,openMediaManager:o.openMediaManager,onBeforeUnload:i,requestFeedback:o.requestFeedback},close:()=>s.forEach(d=>d()),essentials:t.has("essentials")?Se(t.get("essentials")):void 0}};function Se(e){if(e)try{return JSON.parse(decodeURIComponent(e))}catch(t){console.warn('Failed to parse "essentials" query parameter. Make sure to run the code inside a supported Wix App extension.',t);return}}var W=G({createHost:ue});var Ee=e=>t=>{let{host:r,...n}=t,[o,a]=z(!1),{host:s,props:i}=Ae(r);return le(()=>{s&&(D({auth:W.auth(),host:s}).enableContext("module"),a(!0))},[s]),!s||!i||!o?null:ke.createElement(e,S({host:s},i,n))},Ae=e=>{let[t,r]=z(),[n,o]=z();return le(()=>{if(e)return;let a=W.host();r(a);let s=a.channel.observeState,i=s(d=>{o(d)}),u=async()=>{r(void 0),o(void 0),(await i).disconnect(),a.close()};return()=>{u()}},[e]),e?{host:e,props:{}}:{host:t,props:n}};export{Ee as withContextualWixClient};
1
+ import{a as V}from"./chunk-GZP4Z76C.js";import{d as D}from"./chunk-KGLNBMRO.js";import"./chunk-SBZEOPXX.js";function S(){return S=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)({}).hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},S.apply(null,arguments)}import ke,{useEffect as le,useState as z}from"react";function y(e){"@babel/helpers - typeof";return y=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},y(e)}function q(e,t){if(y(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t||"default");if(y(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function F(e){var t=q(e,"string");return y(t)=="symbol"?t:t+""}function N(e,t,r){return(t=F(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}var v=class extends Error{constructor(t){let{message:r,code:n}=t;super(r),N(this,"code",void 0),this.message=r,this.code=n}};var K=()=>{let e=l=>{let{channel:c}=l;return function(){let f=c.showToast(...arguments);return{remove:()=>Promise.resolve(f).then(h=>h.remove())}}},t=l=>{let{channel:c}=l;return function(){let f=c.observeState(...arguments);return{disconnect:()=>Promise.resolve(f).then(h=>h.disconnect())}}};return{showToast:e,observeState:t,navigate:l=>{let{channel:c}=l;return function(){return c.navigate(...arguments)}},navigateBack:l=>{let{channel:c}=l;return()=>c.navigateBack()},openModal:l=>{let{channel:c}=l;return function(){let f=c.openModal(...arguments);return{modalClosed:Promise.resolve(f).then(g=>g.modalClosed)}}},closeModal:l=>{let{channel:c}=l;return f=>{if(f===void 0)return c.closeModal();let g=JSON.parse(JSON.stringify(f));return c.closeModal(g)}},getAccessToken:l=>{let{channel:c}=l;return()=>c.getAccessToken()},getPageUrl:l=>{let{channel:c}=l;return function(){return c.getPageUrl(...arguments)}},openMediaManager:l=>{let{channel:c}=l;return function(){return c.openMediaManager(...arguments)}},addSitePlugin:l=>{let{channel:c}=l;return(f,g)=>{let h="802c76e4-b381-4bb3-9152-96acabbf3194",j=g?.placement||{},H=c.openModal(h,{...j,pluginId:f,action:"populate"});return Promise.resolve(H).then(b=>b.modalClosed).then(b=>{if(b?.type===void 0)throw new v({message:"Aborted by user",code:3006});if(b?.type==="ERROR")throw new v(b.data.error)})}},onBeforeUnload:l=>{let{channel:c}=l;return function(){return c.onBeforeUnload(...arguments)}},setPageTitle:l=>{let{channel:c}=l;return f=>c.setPageTitle(f)},getLanguage:l=>{let c=null;return async()=>{var f;if(c)return c;let g=null;return c=await new Promise(h=>{g=t(l)((j,H)=>{h(H.language)})}),(f=g)==null||f.disconnect(),c}},requestFeedback:l=>{let{channel:c}=l;return function(){return c.requestFeedback(...arguments)}}}};var G=e=>{let{createHost:t}=e,r=K();return{...V(r),host:t,auth:()=>({getAuthHeaders:async n=>({headers:{Authorization:await r.getAccessToken(n)()}})})}};var J=(e,t)=>{let r=()=>e.updateHeight(t.offsetHeight),n=new ResizeObserver(r);return n.observe(t),()=>n.disconnect()};var X=Symbol("Comlink.proxy"),de=Symbol("Comlink.endpoint"),C=Symbol("Comlink.releaseProxy"),O=Symbol("Comlink.thrown"),Q=e=>typeof e=="object"&&e!==null||typeof e=="function",fe={canHandle:e=>Q(e)&&e[X],serialize(e){let{port1:t,port2:r}=new MessageChannel;return R(e,t),[r,[r]]},deserialize(e){return e.start(),_(e)}},me={canHandle:e=>Q(e)&&O in e,serialize({value:e}){let t;return e instanceof Error?t={isError:!0,value:{message:e.message,name:e.name,stack:e.stack}}:t={isError:!1,value:e},[t,[]]},deserialize(e){throw e.isError?Object.assign(new Error(e.value.message),e.value):e.value}},Y=new Map([["proxy",fe],["throw",me]]);function R(e,t=self){t.addEventListener("message",function r(n){if(!n||!n.data)return;let{id:o,type:a,path:s}=Object.assign({path:[]},n.data),i=(n.data.argumentList||[]).map(w),u;try{let d=s.slice(0,-1).reduce((p,x)=>p[x],e),m=s.reduce((p,x)=>p[x],e);switch(a){case 0:u=m;break;case 1:d[s.slice(-1)[0]]=w(n.data.value),u=!0;break;case 2:u=m.apply(d,i);break;case 3:{let p=new m(...i);u=M(p)}break;case 4:{let{port1:p,port2:x}=new MessageChannel;R(e,x),u=he(p,[p])}break;case 5:u=void 0;break}}catch(d){u={value:d,[O]:0}}Promise.resolve(u).catch(d=>({value:d,[O]:0})).then(d=>{let[m,p]=T(d);t.postMessage(Object.assign(Object.assign({},m),{id:o}),p),a===5&&(t.removeEventListener("message",r),Z(t))})}),t.start&&t.start()}function pe(e){return e.constructor.name==="MessagePort"}function Z(e){pe(e)&&e.close()}function _(e,t){return U(e,[],t)}function k(e){if(e)throw new Error("Proxy has been released and is not useable")}function U(e,t=[],r=function(){}){let n=!1,o=new Proxy(r,{get(a,s){if(k(n),s===C)return()=>P(e,{type:5,path:t.map(i=>i.toString())}).then(()=>{Z(e),n=!0});if(s==="then"){if(t.length===0)return{then:()=>o};let i=P(e,{type:0,path:t.map(u=>u.toString())}).then(w);return i.then.bind(i)}return U(e,[...t,s])},set(a,s,i){k(n);let[u,d]=T(i);return P(e,{type:1,path:[...t,s].map(m=>m.toString()),value:u},d).then(w)},apply(a,s,i){k(n);let u=t[t.length-1];if(u===de)return P(e,{type:4}).then(w);if(u==="bind")return U(e,t.slice(0,-1));let[d,m]=$(i);return P(e,{type:2,path:t.map(p=>p.toString()),argumentList:d},m).then(w)},construct(a,s){k(n);let[i,u]=$(s);return P(e,{type:3,path:t.map(d=>d.toString()),argumentList:i},u).then(w)}});return o}function ge(e){return Array.prototype.concat.apply([],e)}function $(e){let t=e.map(T);return[t.map(r=>r[0]),ge(t.map(r=>r[1]))]}var ee=new WeakMap;function he(e,t){return ee.set(e,t),e}function M(e){return Object.assign(e,{[X]:!0})}function T(e){for(let[t,r]of Y)if(r.canHandle(e)){let[n,o]=r.serialize(e);return[{type:3,name:t,value:n},o]}return[{type:0,value:e},ee.get(e)||[]]}function w(e){switch(e.type){case 3:return Y.get(e.name).deserialize(e.value);case 0:return e.value}}function P(e,t,r){return new Promise(n=>{let o=be();e.addEventListener("message",function a(s){!s.data||!s.data.id||s.data.id!==o||(e.removeEventListener("message",a),n(s.data))}),e.start&&e.start(),e.postMessage(Object.assign({id:o},t),r)})}function be(){return new Array(4).fill(0).map(()=>Math.floor(Math.random()*Number.MAX_SAFE_INTEGER).toString(16)).join("-")}var B="__proxyCallbackId__wixSDK__",L="__proxyPromiseId__wixSDK__",re=e=>we(e,t=>async function(){for(var r=arguments.length,n=new Array(r),o=0;o<r;o++)n[o]=arguments[o];let[a,s]=I(n),i=await t(M(a),s);return ne(i)});var ye=async e=>{let[t,r]=I(await e);return M({proxies:t,clonables:r})},ne=async e=>A(e?.proxies,await e?.clonables),I=e=>{let t=(o,a)=>{if(oe(a)){let s=te();return o.promises[s]=a,{[L]:s}}if(xe(a)){let s=te();return o.callbacks[s]=(i,u)=>{let d=A(i,u),m=a(...d);return ye(m)},{[B]:s}}return Array.isArray(a)?a.map(s=>t(o,s)):E(a)?se(a,s=>t(o,s)):a},r={promises:{},callbacks:{}},n=t(r,e);return[r,n]},A=(e,t)=>{if(Array.isArray(t))return t.map(r=>A(e,r));if(E(t)&&t.hasOwnProperty(L)){let r=t[L];return e.promises[r]}if(E(t)&&t.hasOwnProperty(B)){let r=t[B];return async function(){for(var n=arguments.length,o=new Array(n),a=0;a<n;a++)o[a]=arguments[a];let[s,i]=I(o),u=await e.callbacks[r](M(s),i);return ne(u)}}return E(t)?se(t,r=>A(e,r)):t},we=(e,t)=>new Proxy(e,{get(r,n){return r[n]?t(r[n]):()=>{throw new Error(`Serialization error occurred while accessing ${n} property of ${r}`)}}}),oe=e=>e instanceof Promise,E=e=>e&&typeof e=="object"&&!oe(e),xe=e=>typeof e=="function",se=(e,t)=>{let r=n=>{let[o,a]=n;return[o,t(a)]};return Object.fromEntries(Object.entries(e).map(r))},te=(()=>{let e=0;return()=>++e})();var Pe="wix-sdk-bo-hello-handshake",ae=e=>{let{postMessage:t,origin:r}=e,{port1:n,port2:o}=new MessageChannel;t({code:Pe,version:"1.0.0",port:o},r,[o]);let i=re(_(n));return{channel:i,close:()=>i[C]()}};var ve=["https://manage.wix.com","https://manage.editorx.com"],Me=new Set(ve),ie=e=>Me.has(e);var ce=e=>{let t=new EventTarget,r=typeof window>"u",n=i=>{t.dispatchEvent(new CustomEvent("beforeunload",{cancelable:!0}))||(i.preventDefault(),i.returnValue=!0)},o=e.onBeforeUnload(n),a=()=>{r||window.removeEventListener("beforeunload",n),o.then(i=>{let{remove:u}=i;return u()})};return r||(window.addEventListener("beforeunload",n),window.addEventListener("unload",a)),{onBeforeUnload:i=>(t.addEventListener("beforeunload",i),{remove:()=>{t.removeEventListener("beforeunload",i)}}),clearBeforeUnloadHandler:a}};var ue=function(e){e===void 0&&(e={});let t=new URLSearchParams(typeof window<"u"?window.location.search:"?"),r=e.origin||t.get("origin")||"",n=e.postMessage||window.parent.postMessage.bind(window.parent);if(!ie(r))throw new Error("Wix Dashboard SDK: Unable to establish a connection with the Wix dashboard. Please ensure that you are running your app within the Wix dashboard.");let{channel:o,close:a}=ae({postMessage:n,origin:r}),s=[a];if(e.autoHeightUpdate===void 0||e.autoHeightUpdate){let d=e.autoHeightElement||document.documentElement,m=J(o,d);s.push(()=>m())}let{onBeforeUnload:i,clearBeforeUnloadHandler:u}=ce(o);return s.push(u),{channel:{...o,showToast:o.showToast,navigate:o.navigate,navigateBack:o.navigateBack,updateHeight:o.updateHeight,observeState:o.observeState,closeModal:o.closeModal,openModal:o.openModal,getAccessToken:o.getAccessToken,getPageUrl:o.getPageUrl,setPageTitle:o.setPageTitle,openMediaManager:o.openMediaManager,onBeforeUnload:i,requestFeedback:o.requestFeedback},close:()=>s.forEach(d=>d()),essentials:t.has("essentials")?Se(t.get("essentials")):void 0}};function Se(e){if(e)try{return JSON.parse(decodeURIComponent(e))}catch(t){console.warn('Failed to parse "essentials" query parameter. Make sure to run the code inside a supported Wix App extension.',t);return}}var W=G({createHost:ue});var Ee=e=>t=>{let{host:r,...n}=t,[o,a]=z(!1),{host:s,props:i}=Ae(r);return le(()=>{s&&(D({auth:W.auth(),host:s}).enableContext("module"),a(!0))},[s]),!s||!i||!o?null:ke.createElement(e,S({host:s},i,n))},Ae=e=>{let[t,r]=z(),[n,o]=z();return le(()=>{if(e)return;let a=W.host();r(a);let s=a.channel.observeState,i=s(d=>{o(d)}),u=async()=>{r(void 0),o(void 0),(await i).disconnect(),a.close()};return()=>{u()}},[e]),e?{host:e,props:{}}:{host:t,props:n}};export{Ee as withContextualWixClient};
2
2
  //# sourceMappingURL=dashboard.js.map
@@ -1,8 +1,8 @@
1
- import{a as be}from"./chunk-DGX4CFXG.js";import{a as Be,b as Je,c as we}from"./chunk-32RIHE6N.js";import{b as ve,d as Pe,e as Xe,f as a,g as c,h as u,i as I,j as H}from"./chunk-SBZEOPXX.js";var _e=ve(at=>{"use strict";Object.defineProperty(at,"__esModule",{value:!0});at.EventType=void 0;var Te;(function(n){n.removeAppCompleted="removeAppCompleted",n.componentSelectionChanged="componentSelectionChanged",n.appInstalled="appInstalled",n.appUpdateCompleted="appUpdateCompleted"})(Te||(at.EventType=Te={}))});var jt=ve(A=>{"use strict";var Ge=A&&A.__createBinding||(Object.create?function(n,t,e,i){i===void 0&&(i=e);var r=Object.getOwnPropertyDescriptor(t,e);(!r||("get"in r?!t.__esModule:r.writable||r.configurable))&&(r={enumerable:!0,get:function(){return t[e]}}),Object.defineProperty(n,i,r)}:function(n,t,e,i){i===void 0&&(i=e),n[i]=t[e]}),He=A&&A.__setModuleDefault||(Object.create?function(n,t){Object.defineProperty(n,"default",{enumerable:!0,value:t})}:function(n,t){n.default=t}),Ve=A&&A.__importStar||function(){var n=function(t){return n=Object.getOwnPropertyNames||function(e){var i=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(i[i.length]=r);return i},n(t)};return function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var i=n(t),r=0;r<i.length;r++)i[r]!=="default"&&Ge(e,t,i[r]);return He(e,t),e}}();Object.defineProperty(A,"__esModule",{value:!0});A.EventType=A.WixSDKTypes=void 0;var qe=Ve((Je(),Xe(Be)));A.WixSDKTypes=qe;var Qe=_e();Object.defineProperty(A,"EventType",{enumerable:!0,get:function(){return Qe.EventType}})});var y=class n extends Error{constructor(e,i,r){let s=e?` ${e}`:"",o=`[${r}]#${i}`;super(`${o}.${s}`);a(this,"state",{});a(this,"displayName");a(this,"prefix");a(this,"errorMessage");a(this,"parent");a(this,"messages",[]);a(this,"code");this.displayName=o,this.errorMessage=e,this.prefix=r,this.code=i,this.name=o,Object.defineProperty(this,"message",{get:()=>this.getDisplayMessage()}),Error.captureStackTrace&&Error.captureStackTrace(this,n)}get parentError(){let e=this.parent;if(!e)return null;if(this.parent instanceof n)return this.parent;let i=e.name??"[Unknown Error]";return{getBreadcrumbs(){return[i]},getMessage(){return[i,e.message??"unknown error message"].join(`
1
+ import{a as be}from"./chunk-GZP4Z76C.js";import{a as Ze,b as tn,d as Te}from"./chunk-KGLNBMRO.js";import{b as Lt,d as we,e as Qe,f as a,g as c,h as u,i as A,j as X}from"./chunk-SBZEOPXX.js";var Ce=Lt(pt=>{"use strict";Object.defineProperty(pt,"__esModule",{value:!0});pt.EventType=void 0;var _e;(function(n){n.removeAppCompleted="removeAppCompleted",n.componentSelectionChanged="componentSelectionChanged",n.appInstalled="appInstalled",n.appUpdateCompleted="appUpdateCompleted"})(_e||(pt.EventType=_e={}))});var xe=Lt(Re=>{"use strict";Object.defineProperty(Re,"__esModule",{value:!0})});var Ut=Lt(I=>{"use strict";var Oe=I&&I.__createBinding||(Object.create?function(n,t,e,i){i===void 0&&(i=e);var r=Object.getOwnPropertyDescriptor(t,e);(!r||("get"in r?!t.__esModule:r.writable||r.configurable))&&(r={enumerable:!0,get:function(){return t[e]}}),Object.defineProperty(n,i,r)}:function(n,t,e,i){i===void 0&&(i=e),n[i]=t[e]}),en=I&&I.__setModuleDefault||(Object.create?function(n,t){Object.defineProperty(n,"default",{enumerable:!0,value:t})}:function(n,t){n.default=t}),nn=I&&I.__importStar||function(){var n=function(t){return n=Object.getOwnPropertyNames||function(e){var i=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(i[i.length]=r);return i},n(t)};return function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var i=n(t),r=0;r<i.length;r++)i[r]!=="default"&&Oe(e,t,i[r]);return en(e,t),e}}(),rn=I&&I.__exportStar||function(n,t){for(var e in n)e!=="default"&&!Object.prototype.hasOwnProperty.call(t,e)&&Oe(t,n,e)};Object.defineProperty(I,"__esModule",{value:!0});I.EventType=I.WixSDKTypes=void 0;var sn=nn((tn(),Qe(Ze)));I.WixSDKTypes=sn;var on=Ce();Object.defineProperty(I,"EventType",{enumerable:!0,get:function(){return on.EventType}});rn(xe(),I)});var y=class n extends Error{constructor(e,i,r){let s=e?` ${e}`:"",o=`[${r}]#${i}`;super(`${o}.${s}`);a(this,"state",{});a(this,"displayName");a(this,"prefix");a(this,"errorMessage");a(this,"parent");a(this,"messages",[]);a(this,"code");this.displayName=o,this.errorMessage=e,this.prefix=r,this.code=i,this.name=o,Object.defineProperty(this,"message",{get:()=>this.getDisplayMessage()}),Error.captureStackTrace&&Error.captureStackTrace(this,n)}get parentError(){let e=this.parent;if(!e)return null;if(this.parent instanceof n)return this.parent;let i=e.name??"[Unknown Error]";return{getBreadcrumbs(){return[i]},getMessage(){return[i,e.message??"unknown error message"].join(`
2
2
  `)}}}getDisplayMessage(){return[(this.parentError?this.getBreadcrumbs():[]).join(" -> "),this.getMessage()].filter(i=>i.trim().length).join(`
3
3
  `)}getMessage(){let e=Object.entries(this.state).reduce((p,[l,h])=>(h&&p.push(` \u2013 ${l}: ${h}`),p),[]).join(`
4
4
  `),i=this.messages.reduce((p,l)=>(p.push(` - ${l.join(" ")}`),p),[]).join(`
5
5
  `),r=this.parentError,s=r?["",r.getMessage(),""].join(`
6
6
  `):"",o=this.errorMessage?`${this.displayName}: ${this.errorMessage}`:this.displayName;return[s,o,e,i].filter(p=>p.trim().length).join(`
7
- `)}getBreadcrumbs(){let e=this.parentError;return e?[...e.getBreadcrumbs(),this.displayName]:[this.displayName]}withParentError(e){return this.parent=e,this}withMessage(...e){return this.messages.push(e),this}};function g(n){return function t(e,i=""){let r=new n(i,e);return Error.captureStackTrace&&Error.captureStackTrace(r,t),r}}var Dt=class extends y{constructor(e,i){super(e,i,"Editor Platform Internal Error");a(this,"state",{})}withHost(e){return this.state={...this.state,host:e},this}},Wn=g(Dt);var V=Pe(jt(),1);var N=class N{constructor(){a(this,"uid",0);a(this,"callbacks",new Map);a(this,"inTransaction",!1);a(this,"isSilent",!1);a(this,"queue",[])}silent(t=!0){this.isSilent=t}startTransaction(){this.inTransaction=!0}commit(){this.inTransaction=!1;let t=this.queue;this.queue=[],this.isSilent||t.forEach(e=>{this.notify(e)})}notify(t){this.isSilent||(this.inTransaction?this.queue.push(t):this.callbacks.forEach(e=>{e(t)}))}subscribe(t){let e=this.uid++;return this.callbacks.set(e,t),()=>{this.callbacks.delete(e)}}notifyWithStep(t,e){this.notify({...t,meta:{...t.meta,step:e}})}async withEvent(t,e){let i=e();if(i&&i.hasOwnProperty("then"))try{return this.notifyWithStep(t,N.EventSteps.Start),i=await i,this.notifyWithStep(t,N.EventSteps.End),i}catch(r){throw this.notifyWithStep({...t,meta:{...t.meta,error:r}},N.EventSteps.Error),r}else return this.notify(t),i}};a(N,"biEvents",{PLATFORM_WORKER_SPAWN:123,PLATFORM_APP_RUNNER_INIT_APP_API:124,PLATFORM_APP_RUNNER_RUN_APP:125,PLATFORM_APP_RUNNER_REMOVE_APP:126,PLATFORM_WORKER_APP_BUNDLE_LOAD:127,PLATFORM_WORKER_APP_BUNDLE_EXECUTE:128,PLATFORM_IFRAME_INIT:129,PLATFORM_APP_API_INIT:130,PLATFORM_APP_API_GET:131}),a(N,"EventSteps",{Start:"start",End:"end",Error:"error"});var kt=N,U=(n=>(n.WorkerSpawn="WorkerSpawn",n.HostEvent="HostEvent",n.ApplicationsSpecsReceived="ApplicationsSpecsReceived",n.InitApplicationApi="InitApplicationApi",n.RunApplication="RunApplication",n.getApplicationApi="getApplicationApi",n.IframeInit="IframeInit",n))(U||{}),q=(n=>(n.EditorReady="EditorReady",n))(q||{});var d=(n=>(n.ApplicationInit="ApplicationInit",n.ApplicationExecute="ApplicationExecute",n.ApplicationRemoved="ApplicationRemoved",n.ApplicationLoad="ApplicationLoad",n.ApplicationApiInit="ApplicationApiInit",n.CustomEvent="CustomEvent",n.HostEvent="HostEvent",n.EditorReady="EditorReady",n))(d||{}),Lt=class{createApplicationRemovedEvent(t){return{type:"ApplicationRemoved",payload:{appDefinitionId:t},meta:{bi:{evid:E.biEvents.PLATFORM_WORKER_SPAWN,appDefId:t}}}}createApplicationLoadEvent(t,e){return{type:"ApplicationLoad",payload:{appDefinitionId:t.appDefinitionId,url:e},meta:{bi:{evid:E.biEvents.PLATFORM_WORKER_APP_BUNDLE_LOAD,appDefId:t.appDefinitionId,appType:t.appType,bundleUrl:e}}}}createApplicationExecuteEvent(t,e){return{type:"ApplicationExecute",payload:{appDefinitionId:t.appDefinitionId,url:e},meta:{bi:{evid:E.biEvents.PLATFORM_WORKER_APP_BUNDLE_EXECUTE,appDefId:t.appDefinitionId,appType:t.appType,bundleUrl:e}}}}createApplicationApiInitEvent(t,e){return{type:"ApplicationApiInit",payload:{appDefinitionId:t},meta:{bi:{evid:E.biEvents.PLATFORM_APP_API_INIT,appDefId:t,scope:e}}}}},E=class extends kt{constructor(){super(...arguments);a(this,"factories",new Lt)}},ct=class ct{constructor(t){this.events=t}mapToPlatformHostEvent(t){if(typeof t=="string")try{t=JSON.parse(t)}catch{}return{type:U.HostEvent,payload:{type:t.args.eventType,...t.args.eventPayload},meta:{appDefinitionId:t.appDefinitionId??null,intent:t.intent}}}notify(t){let e=this.mapToPlatformHostEvent(t);ct.allowedEvents.includes(e.payload.type)&&this.events.notify(e)}};a(ct,"allowedEvents",[V.EventType.componentSelectionChanged,V.EventType.appInstalled,V.EventType.appUpdateCompleted,V.EventType.removeAppCompleted]);var Ce=ct;var Z=n=>`"editor-platform-transport": ${n}`,pt=n=>Z(`[Internal Error] ${n}`),Ne="\u0192",Oe="\u2202",Me="_get_",Se="_set_",lt="+",xe="-",Jt="\xB7",Gt="\xD7",Ht="\xB0",De=n=>n[0]===Gt?"":n,Re=n=>n===null||typeof n>"u"||typeof n=="symbol"||typeof n=="number"||typeof n=="boolean"||typeof n=="function"||typeof n=="string",Ze=n=>!!n&&typeof n=="object"&&!Array.isArray(n)&&!(n instanceof Date)&&!(n instanceof Set)&&!(n instanceof Map),tn=n=>W(n.split(Jt)),W=n=>n.map(De).filter(Boolean).join(".");function At(n,t){return{marker:n,...t}}var en=At("A",{shouldUse:n=>Array.isArray(n),serialize:(n,t)=>{n.length?n.forEach((e,i)=>{t(`${i}`,e)}):t("",Ht)},deserialize:{create:()=>[],has:(n,t)=>!(typeof n[t]>"u"),append:(n,t,e)=>{n.push(e)}}}),nn=At("M",{shouldUse:n=>n instanceof Map,serialize:(n,t)=>{n.forEach((e,i)=>{t(i,e)})},deserialize:{create:()=>new Map,has:(n,t)=>n.has(t),append:(n,t,e)=>{n.set(t,e)}}}),rn=At("S",{shouldUse:n=>n instanceof Set,serialize:(n,t)=>{let e=0;n.forEach(i=>{t(`${e++}`,i)})},deserialize:{create:()=>new Set,has:(n,t)=>n.has(t),append:(n,t,e)=>{n.add(e)}}}),Ut=At("O",{shouldUse:n=>typeof n=="object",serialize:(n,t)=>{let e=i=>{let s=Reflect.ownKeys(i).filter(p=>p!=="constructor").filter(p=>typeof p!="symbol");s.length?s.filter(p=>p!=="constructor").filter(p=>typeof p!="symbol").forEach(p=>{let l=Reflect.get(n,p);t(p,l)}):t("",Ht);let o=Reflect.getPrototypeOf(i);!o||o?.hasOwnProperty("__proto__")||e(o)};e(n)},deserialize:{create:()=>({}),has:(n,t)=>!!n[t],append:(n,t,e)=>{n[t]=e}}}),je=[en,rn,nn];function sn(n,t){let e=n;for(;e;){let i=Object.getOwnPropertyDescriptor(e,t);if(i)return i;e=Reflect.getPrototypeOf(e)}return null}function on(n,t){let e=new WeakMap,i=s=>{let o=s.slice(1).map(De).filter(Boolean);return o.slice(1).reduce((p,l)=>({context:p.context[p.pointer],pointer:l}),{context:n,pointer:o[0]})},r=(s,o=[])=>{if(e.has(s)&&e.get(s)?.some(h=>o.join(".").startsWith(h))){t(o,{...i(o),value:"[Circular]"});return}if(s&&!Re(s)&&(e.has(s)&&e.set(s,[]),e.set(s,[...e.get(s)??[],o.join(".")])),Re(s)){t(o,{...i(o),value:s});return}let p=je.find(l=>l.shouldUse(s))??Ut;if(p){p.serialize(s,(l,h)=>{r(h,[...o,`${Gt}${p.marker}`,l])});return}};return r(n)}var an=(n,t)=>{if(!Ze(n))throw new Error(Z("only objects are serializable at the root level"));let e={data:[]},i=(s,o)=>{e.data.push([s,o])},r=(s,o)=>{t(tn(s),(...p)=>o.context[o.pointer](...p)),i(s,Ne)};return on(n,(s,{value:o,context:p,pointer:l})=>{let h=s.slice(1).join(Jt),f=sn(p,l);if(f?.get||f?.set){f?.get&&t(W([...s,Me]),()=>p[l]),f?.set&&t(W([...s,Se]),G=>{p[l]=G});let R=[f?.get?lt:xe,f?.set?lt:xe];i(h,`${Oe}${R.join("")}`)}else typeof o=="function"?r(h,{context:p,pointer:l}):i(h,o)}),e},cn=(n,t)=>typeof n!="object"||n===null?n:n.data.reduce((e,[i,r])=>{let s=e,o=i.split(Jt),p=Ut,l=null;for(let h=0;h<o.length;h++){let f=o[h];if(f[0]===Gt){let R=p.deserialize.has(s,l);if(p=[Ut,...je].find(G=>G.marker===f[1]),!p)throw new Error(Z(`unknown marker "${f[1]}"`));R||(s[l]=p.deserialize.create()),s=s[l]}else l=f}if(r?.toString()===Ht)return e;if(r?.toString()===Ne)p.deserialize.append(s,l,t(W(o)));else if(r?.toString()[0]===Oe){let h=r?.toString()[1]===lt,f=r?.toString()[2]===lt,R={};if(h){let G=t(W([...o,Me]));R.get=()=>G()}f&&(R.set=t(W([...o,Se]))),Object.defineProperty(s,l,R)}else p.deserialize.append(s,l,r);return e},{[Symbol("transferred object")]:`${(JSON.stringify(n.data).length/1024).toFixed(2)}Kb`}),Q=(n=>(n.ExposeAPI="ExposeAPI",n.Call="Call",n.Response="Response",n.Cleanup="Cleanup",n))(Q||{}),_=class n{constructor(t,e){a(this,"correlationId",`M-${performance.now()}`);a(this,"parentCorrelationId");this.type=t,this.payload=e}withParentCorrelationId(t){return this.parentCorrelationId=t,this}serialize(t){return JSON.stringify({parentCorrelationId:this.parentCorrelationId,correlationId:this.correlationId,type:this.type,payload:an(this.payload,(e,i)=>{t(this.correlationId,e,i)})})}static fromEvent(t,e){let i=JSON.parse(t);return new n(i.type,cn(i.payload,r=>e(i.correlationId,r))).withParentCorrelationId(i.correlationId)}},Wt=class extends _{constructor(t){super("Cleanup",t)}},Kt=class extends _{constructor(t){super("Response",t)}},ut=class extends _{constructor(t){super("Response",t)}},$t=class extends _{constructor(t){super("Call",t)}},Ft=(n,t)=>`${n}_${t}`,It,yt,K,v,Yt=class{constructor(t){u(this,It,new FinalizationRegistry(t=>{this.postMessage(new Wt(t))}));u(this,yt,{[Q.Cleanup]:t=>{let e=t.payload.functionMarkerKey,i=t.payload.callId;delete c(this,K)[e],i&&delete c(this,v)[i]},[Q.Response]:async t=>{let e=t.payload.callId,i=t.payload.errorMessage;if(i)if(t.payload.errorStack){let s=new Error(i);s.stack=t.payload.errorStack,c(this,v)[e]?.reject(s)}else c(this,v)[e]?.reject(i);else{let r=t.payload.response;c(this,v)[e]?.resolve(r)}delete c(this,v)[e]},[Q.Call]:async t=>{let e=t.payload.functionMarkerKey,i=c(this,K)[e];if(!i){this.postMessage(new ut({callId:t.payload.callId,errorMessage:Z("function is not available")}));return}try{let r=await i.value(...t.payload.props??[]);this.postMessage(new Kt({callId:t.payload.callId,response:r}))}catch(r){this.postMessage(new ut({callId:t.payload.callId,errorMessage:r.message,errorStack:r.stack}))}}});u(this,K,{});u(this,v,{});a(this,"queue",[]);a(this,"isConnected",!1);this.handshake=t}async run(t){return this.handshake.run(t)}registerMessageListener(){if(!this.port)throw new Error(pt("it is not possible to listen on port events because port is not defined"));this.port.onmessage=t=>{this.onMessage(t)}}onMessage(t){let e=_.fromEvent(t.data,(i,r)=>{let s=this.replaceTransferredFunction(i,r);return c(this,It).register(s,{functionMarkerKey:Ft(i,r)}),s});c(this,yt)[e.type]?.(e),this.messageEvents[e.type]?.(e)}postMessage(t){if(!this.port)throw new Error(pt("it is not possible to post message on port because port is not defined"));this.port.postMessage(t.serialize(this.registerTransferredFunction.bind(this)))}registerTransferredFunction(t,e,i){let r=Ft(t,e);c(this,K)[r]={path:e,value:i}}replaceTransferredFunction(t,e){return(...i)=>{let r=`CALL-${crypto.randomUUID()}`;return this.postMessage(new $t({callId:r,functionMarkerKey:Ft(t,e),props:i})),new Promise((s,o)=>{c(this,v)[r]={resolve:s,reject:o}})}}flush(){this.port&&(this.queue.forEach(t=>{this.postMessage(t)}),this.queue=[])}};It=new WeakMap,yt=new WeakMap,K=new WeakMap,v=new WeakMap;var ht=class extends Yt{constructor(e){super(e);a(this,"port");a(this,"messageEvents",{});this.init()}async init(){let e=await this.run();e?(this.port=e,this.registerMessageListener(),this.flush()):console.error(pt("consumer did not receive message port from the host"))}expose(e){if(!e.type)throw new Error(Z('wrong exposed API instance, "type" property is required'));this.queue.push(new _(Q.ExposeAPI,e)),this.flush()}};var zt=class{constructor(t){this.communicationAPI=t}},O,P,Bt,w,ke,Le,Xt,T=class T extends zt{constructor(){super(...arguments);u(this,w);u(this,O);u(this,P,!1);u(this,Bt,null)}run(e){return new Promise(i=>{e?H(this,w,ke).call(this,e,()=>i(void 0)):H(this,w,Le).call(this,i)})}};O=new WeakMap,P=new WeakMap,Bt=new WeakMap,w=new WeakSet,ke=function(e,i){if(c(this,P))return;if(!e)throw new Error(pt("port should exists on host handshake"));let r=`Host-${performance.now()}`;this.communicationAPI.postMessage(JSON.stringify({memberId:r,type:"Greeting"}),[]),H(this,w,Xt).call(this,r,s=>{var o;if(!c(this,P))switch(s.type){case"Greeting":{this.communicationAPI.postMessage(JSON.stringify({memberId:r,type:"Greeting"}),[]);break}case"RequestPort":{I(this,P,!0),this.communicationAPI.postMessage(JSON.stringify({memberId:r,targetMemberId:s.memberId,type:"Port"}),[e]),(o=c(this,O))==null||o.call(this),i();break}}})},Le=function(e){if(c(this,P))return;let i=`Consumer-${performance.now()}`;this.communicationAPI.postMessage(JSON.stringify({memberId:i,type:"Greeting"}),[]),H(this,w,Xt).call(this,i,(r,s)=>{var o;if(!c(this,P))switch(r.type){case"Greeting":{this.communicationAPI.postMessage(JSON.stringify({memberId:i,type:"RequestPort"}),[]);break}case"Port":{if(r.targetMemberId!==i)return;I(this,P,!0),(o=c(this,O))==null||o.call(this),e(s);break}}})},Xt=function(e,i){var r;(r=c(this,O))==null||r.call(this),I(this,O,this.communicationAPI.onMessage(s=>{try{let o=typeof s.data=="string"?JSON.parse(s.data):{};if(!o.memberId||o.memberId===e)return;i(o,s.ports[0])}catch(o){console.error(o)}}))},a(T,"iframe",{host:e=>new T({postMessage:(i,r)=>{let s=e.contentWindow;s&&s.postMessage(i,"*",r)},onMessage:i=>{let r=s=>{s.origin!==new URL(e.src).origin||e.contentWindow!==s.source||i(s)};return globalThis.addEventListener("message",r),()=>globalThis.removeEventListener("message",r)}}),consumer:()=>new T({postMessage:e=>{globalThis.parent.postMessage(e,"*")},onMessage:e=>(globalThis.addEventListener("message",e),()=>{globalThis.removeEventListener("message",e)})})}),a(T,"worker",{host:e=>new T({postMessage:(i,r)=>{e.postMessage(i,r)},onMessage:i=>(e.addEventListener("message",i),()=>e.removeEventListener("message",i))}),consumer:()=>new T({postMessage:e=>{globalThis.postMessage(e)},onMessage:e=>(globalThis.addEventListener("message",e),()=>{globalThis.removeEventListener("message",e)})})});var dt=T,ft=class extends ht{constructor(){super(dt.iframe.consumer())}};var mt=class extends ht{constructor(){super(dt.worker.consumer())}};var Qt=class{constructor(t){this.platformAppEvents=t}notify(t){switch(t.type){case q.EditorReady:this.platformAppEvents.notify({...t,type:d.EditorReady});break;case U.HostEvent:this.platformAppEvents.notify({...t,type:d.HostEvent});break}}subscribe(t){this.platformAppEvents.subscribe(e=>{t(e)})}},Zt=(n=>(n.Frame="PLATFORM_FRAME_API",n.Worker="PLATFORM_WORKER_API",n))(Zt||{}),te=class{constructor(t){this.env=t,this.create()}},M=(n=>(n.IncorrectEnvironment="IncorrectEnvironment",n.ClientAuthError="ClientAuthError",n))(M||{}),ee=class extends y{constructor(e,i){super(e,i,"Editor Platform Application Context Error");a(this,"state",{})}withUrl(e){return this.state={...this.state,url:e},this}withAppDefinitionId(e){return this.state={...this.state,appDefinitionId:e},this}},$=g(ee);async function pn(n,t){if(!n?.type)return n;switch(n.type){case"componentSelectionChanged":let e=n.componentRefs||[],i=await Promise.all(e.map(r=>t.components.getComponent(r)));return{type:n.type,components:i};default:return n}}var ne=class{constructor(t,e,i){a(this,"events");a(this,"subscribe");a(this,"commit");a(this,"startTransaction");a(this,"silent");this.appDefinitionId=t,this.privateAPI=i,this.events=e,this.subscribe=e.subscribe.bind(e),this.commit=e.commit.bind(e),this.startTransaction=e.startTransaction.bind(e),this.silent=e.silent.bind(e)}notify(t){this.events.notify({type:t.type,payload:t.payload,meta:{appDefinitionId:this.appDefinitionId}})}notifyCustomEvent(t,e){this.notify({type:d.CustomEvent,payload:{...e,type:t}})}addEventListener(t,e){return this.events.subscribe(async i=>{let r=i.meta?.appDefinitionId===this.appDefinitionId||i.meta?.appDefinitionId===null,s=()=>pn(i.payload,this.privateAPI);t==="*"?e(await s()):i.type===d.CustomEvent?t===i.payload?.type&&!r&&e(await s()):i.type===d.HostEvent&&t===i.payload?.type&&r&&e(await s())})}},ln=200,un=50,gt=class{constructor(t){a(this,"_resolveContextInjected",()=>{});a(this,"_isInjected",!1);a(this,"key");this.key=`__${t}_CONTEXT_INJECTION_STATUS_KEY`,globalThis[this.key]||(globalThis[this.key]=new Promise(e=>{this._resolveContextInjected=()=>{this._isInjected=!0,e()}}))}isInjected(){return!!this._isInjected}resolveInjected(){this._resolveContextInjected?.()}waitInjected(){return new Promise((t,e)=>{let i=!1,r,s=0,o=()=>{i||(r=setTimeout(()=>{if(s++,s<un){s%10===0&&console.log($(M.IncorrectEnvironment,"contexts are not resolved, still re-trying").withMessage(`try number ${s}`).message),o();return}if(!i){let l=$(M.IncorrectEnvironment,"contexts are not resolved, threw by timeout");e(l)}},ln))};o(),globalThis[this.key].then(()=>{i=!0,clearTimeout(r),t()})})}},Vt="__ENVIRONMENT_CONTEXT_KEY",Et=(n=>(n.Worker="Worker",n.Frame="Frame",n.ComponentPanel="ComponentPanel",n))(Et||{}),Pt=class Pt{constructor(t){this.environmentContext=t}static async inject(t){if(globalThis[Vt])throw $(M.IncorrectEnvironment,"Environment context already exists and should not be overridden");globalThis[Vt]=new Pt(t),this.status.resolveInjected()}static async getInstance(){return await this.status.waitInjected(),globalThis[Vt]}getPrivateAPI(){return this.environmentContext.privateApi}getEvents(){return this.environmentContext.events}getApplicationAPIs(){return this.environmentContext.applicationAPIs??{}}getEnvironment(){return this.environmentContext.environment}};a(Pt,"status",new gt("environment"));var Y=Pt,qt="__APPLICATION_CONTEXT_KEY",wt=class wt{constructor(t,e){a(this,"events");this.applicationContext=t,this.environment=e,this.events=new ne(this.applicationContext.appDefinitionId,this.environment.getEvents(),this.environment.getPrivateAPI())}static async inject(t){if((await Y.getInstance()).getEnvironment()!==Et.Frame)throw $(M.IncorrectEnvironment,"Application context can be injected only in frame environment");if(globalThis[qt])throw $(M.IncorrectEnvironment,"Application context already exists and should not be overridden");globalThis[qt]=new wt(t,await Y.getInstance()),this.status.resolveInjected()}static async getInstance(){return(await Y.getInstance()).getEnvironment()===Et.Frame?(await this.status.waitInjected(),globalThis[qt]):__APPLICATION_CONTEXT_KEY}getAppDefinitionId(){return this.applicationContext.appDefinitionId}getBindings(){return this.applicationContext}getEvents(){return this.events}getPrivateAPI(){return this.environment.getPrivateAPI()}getPrivateApplicationAPI(){let t=this.getAppDefinitionId();if(!t)throw $(M.IncorrectEnvironment,"appDefinitionId is not available");return this.environment.getApplicationAPIs()[t]}};a(wt,"status",new gt("application"));var ie=wt,hn={classic:"https://www.unpkg.com/@wix/design-system/dist/statics/tokens-default.global.css",studio:"https://www.unpkg.com/@wix/design-system/dist/statics/tokens-studio.global.css"},tt,et,bt,nt,vt=class extends te{constructor(){super(Zt.Frame);a(this,"type",Zt.Frame);u(this,tt,new E);u(this,et,new Qt(c(this,tt)));u(this,bt);u(this,nt)}create(){if(typeof globalThis?.document?.head?.prepend=="function"){let i=new URL(globalThis.location.href).searchParams.get("editorType")==="CLASSIC"?"classic":"studio",r=hn[i],s=r&&!!document.querySelectorAll(`link[type="text/css"][href="${r}"]`)?.length;if(r&&!s){let o=document.createElement("link");o.setAttribute("rel","stylesheet"),o.setAttribute("type","text/css"),o.setAttribute("href",r),globalThis.document.head.prepend(o)}}}async initEnvironment(e){let{applicationPrivateAPI:i,privateAPI:r,appDefinitionId:s}=e;I(this,nt,i),I(this,bt,r),await Y.inject({environment:Et.Frame,privateApi:r,events:c(this,tt),applicationAPIs:{[s]:c(this,nt)}}),await ie.inject({appDefinitionId:s,appDefinitionName:""})}notify(e){c(this,et).notify(e)}subscribe(e){c(this,et).subscribe(e)}};tt=new WeakMap,et=new WeakMap,bt=new WeakMap,nt=new WeakMap;var Fe=Pe(jt());var se=class{constructor(t){this.platformAppEvents=t}notify(t){switch(t.type){case q.EditorReady:this.platformAppEvents.notify({...t,type:d.EditorReady});break;case U.HostEvent:this.platformAppEvents.notify({...t,type:d.HostEvent});break}}subscribe(t){this.platformAppEvents.subscribe(e=>{t(e)})}},k=(n=>(n.IncorrectEnvironment="IncorrectEnvironment",n.ClientAuthError="ClientAuthError",n))(k||{}),oe=class extends y{constructor(e,i){super(e,i,"Editor Platform Application Context Error");a(this,"state",{})}withUrl(e){return this.state={...this.state,url:e},this}withAppDefinitionId(e){return this.state={...this.state,appDefinitionId:e},this}},z=g(oe);async function dn(n,t){if(!n?.type)return n;switch(n.type){case"componentSelectionChanged":let e=n.componentRefs||[],i=await Promise.all(e.map(r=>t.components.getComponent(r)));return{type:n.type,components:i};default:return n}}var ae=class{constructor(t,e,i){a(this,"events");a(this,"subscribe");a(this,"commit");a(this,"startTransaction");a(this,"silent");this.appDefinitionId=t,this.privateAPI=i,this.events=e,this.subscribe=e.subscribe.bind(e),this.commit=e.commit.bind(e),this.startTransaction=e.startTransaction.bind(e),this.silent=e.silent.bind(e)}notify(t){this.events.notify({type:t.type,payload:t.payload,meta:{appDefinitionId:this.appDefinitionId}})}notifyCustomEvent(t,e){this.notify({type:d.CustomEvent,payload:{...e,type:t}})}addEventListener(t,e){return this.events.subscribe(async i=>{let r=i.meta?.appDefinitionId===this.appDefinitionId||i.meta?.appDefinitionId===null,s=()=>dn(i.payload,this.privateAPI);t==="*"?e(await s()):i.type===d.CustomEvent?t===i.payload?.type&&!r&&e(await s()):i.type===d.HostEvent&&t===i.payload?.type&&r&&e(await s())})}},fn=200,mn=50,_t=class{constructor(t){a(this,"_resolveContextInjected",()=>{});a(this,"_isInjected",!1);a(this,"key");this.key=`__${t}_CONTEXT_INJECTION_STATUS_KEY`,globalThis[this.key]||(globalThis[this.key]=new Promise(e=>{this._resolveContextInjected=()=>{this._isInjected=!0,e()}}))}isInjected(){return!!this._isInjected}resolveInjected(){this._resolveContextInjected?.()}waitInjected(){return new Promise((t,e)=>{let i=!1,r,s=0,o=()=>{i||(r=setTimeout(()=>{if(s++,s<mn){s%10===0&&console.log(z(k.IncorrectEnvironment,"contexts are not resolved, still re-trying").withMessage(`try number ${s}`).message),o();return}if(!i){let l=z(k.IncorrectEnvironment,"contexts are not resolved, threw by timeout");e(l)}},fn))};o(),globalThis[this.key].then(()=>{i=!0,clearTimeout(r),t()})})}},re="__ENVIRONMENT_CONTEXT_KEY",Ct=(n=>(n.Worker="Worker",n.Frame="Frame",n.ComponentPanel="ComponentPanel",n))(Ct||{}),Rt=class Rt{constructor(t){this.environmentContext=t}static async inject(t){if(globalThis[re])throw z(k.IncorrectEnvironment,"Environment context already exists and should not be overridden");globalThis[re]=new Rt(t),this.status.resolveInjected()}static async getInstance(){return await this.status.waitInjected(),globalThis[re]}getPrivateAPI(){return this.environmentContext.privateApi}getEvents(){return this.environmentContext.events}getApplicationAPIs(){return this.environmentContext.applicationAPIs??{}}getEnvironment(){return this.environmentContext.environment}};a(Rt,"status",new _t("environment"));var L=Rt,Tt="__APPLICATION_CONTEXT_KEY",Nt=class Nt{constructor(t,e){a(this,"events");this.applicationContext=t,this.environment=e,this.events=new ae(this.applicationContext.appDefinitionId,this.environment.getEvents(),this.environment.getPrivateAPI())}static async inject(t){if((await L.getInstance()).getEnvironment()!==Ct.Frame)throw z(k.IncorrectEnvironment,"Application context can be injected only in frame environment");if(globalThis[Tt])throw z(k.IncorrectEnvironment,"Application context already exists and should not be overridden");globalThis[Tt]=new Nt(t,await L.getInstance()),this.status.resolveInjected()}static async getInstance(){return(await L.getInstance()).getEnvironment()===Ct.Frame?(await this.status.waitInjected(),globalThis[Tt]):__APPLICATION_CONTEXT_KEY}getAppDefinitionId(){return this.applicationContext.appDefinitionId}getBindings(){return this.applicationContext}getEvents(){return this.events}getPrivateAPI(){return this.environment.getPrivateAPI()}getPrivateApplicationAPI(){let t=this.getAppDefinitionId();if(!t)throw z(k.IncorrectEnvironment,"appDefinitionId is not available");return this.environment.getApplicationAPIs()[t]}};a(Nt,"status",new _t("application"));var ce=Nt,C=(n=>(n.ApplicationRuntimeError="ApplicationRuntimeError",n.ApplicationCreationError="ApplicationCreationError",n.ApplicationLoadError="ApplicationLoadError",n.ApplicationFetchError="ApplicationFetchError",n.ApplicationExecuteError="ApplicationExecuteError",n.ApplicationWasRemoved="ApplicationWasRemoved",n.UndefinedApiMethod="UndefinedApiMethod",n.ApplicationIsNotMutable="ApplicationIsNotMutable",n.FailedToGetPrivateAPI="FailedToGetPrivateAPI",n.ClientAuthError="ClientAuthError",n))(C||{}),pe=class extends y{constructor(e,i){super(e,i,"Editor Platform Application Error");a(this,"state",{})}withUrl(e){return this.state={...this.state,url:e},this}withAppDefinitionId(e){return this.state={...this.state,appDefinitionId:e},this}withApiMethod(e){return this.state={...this.state,apiMethod:e},this}withApiType(e){return this.state={...this.state,apiType:e},this}},S=g(pe),In="__APPLICATION_REGISTRY_KEY";async function yn(n,t,e){let i=new Function(Tt,In,e),r,s=o=>{if(r)throw S(C.ApplicationExecuteError,"Application registry called more than once").withAppDefinitionId(t.appDefinitionId);if(o.type!==t.type)throw S(C.ApplicationExecuteError,"Application has different type").withMessage("expected type",t.type).withMessage("received type",o.type);r=o};try{let o={...t};i.call(null,new ce(o,await L.getInstance()),s)}catch(o){throw S(C.ApplicationExecuteError,o.message).withAppDefinitionId(t.appDefinitionId).withParentError(o)}return new Promise((o,p)=>{let l=n.subscribe(h=>{let f=setTimeout(()=>{clearTimeout(f),l(),r||p(S(C.ApplicationExecuteError,"Application registry was not called, threw by timeout").withAppDefinitionId(t.appDefinitionId))},5e3);h.type===d.ApplicationInit&&h.meta.appDefinitionId===t.appDefinitionId&&(clearTimeout(f),l(),r||p(S(C.ApplicationExecuteError,"Application registry was not called").withAppDefinitionId(t.appDefinitionId)),o({instance:r}))})})}var D,it,m,le=class{constructor(t,e){u(this,D,{});u(this,it);u(this,m);I(this,it,t),I(this,m,e),c(this,m).subscribe(i=>{switch(i.type){case d.HostEvent:{i.payload.type===Fe.EventType.removeAppCompleted&&c(this,m).withEvent(c(this,m).factories.createApplicationRemovedEvent(i.payload.appDefinitionId),()=>this.removeApplication(i.payload.appDefinitionId));break}}})}async runApplication(t){let e=await this.loadApplication(t),i=await this.executeApplication(t,e);return this.setApplication(t.appDefinitionId,i),i}setApplication(t,e){c(this,D)[t]=e,c(this,m).withEvent(c(this,m).factories.createApplicationApiInitEvent(t,e?.api?.private?"private":"public"),()=>{c(this,it).applicationManager.setApplication(e)})}getApplication(t){return c(this,D)[t]}getAppDefinitionIds(){return Object.keys(c(this,D))}removeApplication(t){delete c(this,D)[t]}async loadApplication(t){let e=t.url;return c(this,m).withEvent(c(this,m).factories.createApplicationLoadEvent(t,e),async()=>{try{return await this.loadApplicationBundle(e)}catch(i){throw S(C.ApplicationLoadError).withUrl(e).withAppDefinitionId(t.appDefinitionId).withParentError(i)}})}async loadApplicationBundle(t){let e=await fetch(t,{method:"GET"});if(!(e.status>=200&&e.status<=299))throw S(C.ApplicationFetchError).withUrl(t);return e.text()}async executeApplication(t,e){return c(this,m).withEvent(c(this,m).factories.createApplicationExecuteEvent(t,t.url),async()=>{let{instance:i}=await yn(c(this,m),t,e);return i})}};D=new WeakMap,it=new WeakMap,m=new WeakMap;var ue=(n=>(n.Frame="PLATFORM_FRAME_API",n.Worker="PLATFORM_WORKER_API",n))(ue||{}),he=class{constructor(t){this.env=t,this.create()}},X,rt,st,j,ot,xt=class extends he{constructor(){super(ue.Worker);a(this,"type",ue.Worker);u(this,X,new E);u(this,rt,new se(c(this,X)));u(this,st,null);u(this,j);u(this,ot,[])}create(){}async initEnvironment(e){let{buildPrivateAPI:i}=e;I(this,j,await i({type:"EDITOR_ADDON"})),await L.inject({environment:Ct.Worker,events:c(this,X),privateApi:c(this,j),applicationAPIs:{}}),I(this,st,new le(c(this,j),c(this,X))),c(this,ot).forEach(r=>r(this))}async notify(e){await this.waitReady(),c(this,rt).notify(e)}subscribe(e){c(this,rt).subscribe(e)}async runApplication(e){await this.waitReady(),await c(this,st).runApplication(e)}waitReady(){return new Promise(e=>{if(c(this,j))return e(this);c(this,ot).push(e)})}};X=new WeakMap,rt=new WeakMap,st=new WeakMap,j=new WeakMap,ot=new WeakMap;var F=(n=>(n.IncorrectEnvironment="IncorrectEnvironment",n.ClientAuthError="ClientAuthError",n))(F||{}),me=class extends y{constructor(e,i){super(e,i,"Editor Platform Application Context Error");a(this,"state",{})}withUrl(e){return this.state={...this.state,url:e},this}withAppDefinitionId(e){return this.state={...this.state,appDefinitionId:e},this}},B=g(me);async function An(n,t){if(!n?.type)return n;switch(n.type){case"componentSelectionChanged":let e=n.componentRefs||[],i=await Promise.all(e.map(r=>t.components.getComponent(r)));return{type:n.type,components:i};default:return n}}var Ie=class{constructor(t,e,i){a(this,"events");a(this,"subscribe");a(this,"commit");a(this,"startTransaction");a(this,"silent");this.appDefinitionId=t,this.privateAPI=i,this.events=e,this.subscribe=e.subscribe.bind(e),this.commit=e.commit.bind(e),this.startTransaction=e.startTransaction.bind(e),this.silent=e.silent.bind(e)}notify(t){this.events.notify({type:t.type,payload:t.payload,meta:{appDefinitionId:this.appDefinitionId}})}notifyCustomEvent(t,e){this.notify({type:d.CustomEvent,payload:{...e,type:t}})}addEventListener(t,e){return this.events.subscribe(async i=>{let r=i.meta?.appDefinitionId===this.appDefinitionId||i.meta?.appDefinitionId===null,s=()=>An(i.payload,this.privateAPI);t==="*"?e(await s()):i.type===d.CustomEvent?t===i.payload?.type&&!r&&e(await s()):i.type===d.HostEvent&&t===i.payload?.type&&r&&e(await s())})}},gn=200,En=50,Ot=class{constructor(t){a(this,"_resolveContextInjected",()=>{});a(this,"_isInjected",!1);a(this,"key");this.key=`__${t}_CONTEXT_INJECTION_STATUS_KEY`,globalThis[this.key]||(globalThis[this.key]=new Promise(e=>{this._resolveContextInjected=()=>{this._isInjected=!0,e()}}))}isInjected(){return!!this._isInjected}resolveInjected(){this._resolveContextInjected?.()}waitInjected(){return new Promise((t,e)=>{let i=!1,r,s=0,o=()=>{i||(r=setTimeout(()=>{if(s++,s<En){s%10===0&&console.log(B(F.IncorrectEnvironment,"contexts are not resolved, still re-trying").withMessage(`try number ${s}`).message),o();return}if(!i){let l=B(F.IncorrectEnvironment,"contexts are not resolved, threw by timeout");e(l)}},gn))};o(),globalThis[this.key].then(()=>{i=!0,clearTimeout(r),t()})})}},de="__ENVIRONMENT_CONTEXT_KEY",ye=(n=>(n.Worker="Worker",n.Frame="Frame",n.ComponentPanel="ComponentPanel",n))(ye||{}),Mt=class Mt{constructor(t){this.environmentContext=t}static async inject(t){if(globalThis[de])throw B(F.IncorrectEnvironment,"Environment context already exists and should not be overridden");globalThis[de]=new Mt(t),this.status.resolveInjected()}static async getInstance(){return await this.status.waitInjected(),globalThis[de]}getPrivateAPI(){return this.environmentContext.privateApi}getEvents(){return this.environmentContext.events}getApplicationAPIs(){return this.environmentContext.applicationAPIs??{}}getEnvironment(){return this.environmentContext.environment}};a(Mt,"status",new Ot("environment"));var x=Mt,fe="__APPLICATION_CONTEXT_KEY",St=class St{constructor(t,e){a(this,"events");this.applicationContext=t,this.environment=e,this.events=new Ie(this.applicationContext.appDefinitionId,this.environment.getEvents(),this.environment.getPrivateAPI())}static async inject(t){if((await x.getInstance()).getEnvironment()!==ye.Frame)throw B(F.IncorrectEnvironment,"Application context can be injected only in frame environment");if(globalThis[fe])throw B(F.IncorrectEnvironment,"Application context already exists and should not be overridden");globalThis[fe]=new St(t,await x.getInstance()),this.status.resolveInjected()}static async getInstance(){return(await x.getInstance()).getEnvironment()===ye.Frame?(await this.status.waitInjected(),globalThis[fe]):__APPLICATION_CONTEXT_KEY}getAppDefinitionId(){return this.applicationContext.appDefinitionId}getBindings(){return this.applicationContext}getEvents(){return this.events}getPrivateAPI(){return this.environment.getPrivateAPI()}getPrivateApplicationAPI(){let t=this.getAppDefinitionId();if(!t)throw B(F.IncorrectEnvironment,"appDefinitionId is not available");return this.environment.getApplicationAPIs()[t]}};a(St,"status",new Ot("application"));var J=St,Ae=class extends y{constructor(e,i){super(e,i,"Auth Strategy Error");a(this,"state",{})}withAppDefinitionId(e){return this.state={...this.state,appDefinitionId:e},this}},Ue=g(Ae);function vn(n,t){let e=Date.now(),i=n?new Date(n).getTime():null;return i&&i-e>t}var Pn=30*60*1e3,wn=()=>{let n;return{getAuthHeaders:async()=>{let t=await J.getInstance(),e=t.getBindings(),i=t.getPrivateAPI();if(!e.appDefinitionId)throw Ue("EmptyAppDefinitionId");return(!n||vn(n.expires,Pn))&&(n=await i.auth.getAccessToken(e.appDefinitionId,await i.info.getMetaSiteId())),n?.token?{headers:{Authorization:n.token}}:(console.error(Ue("EmptyAppAuthInstance").withAppDefinitionId(e.appDefinitionId)),{headers:{Authorization:""}})}}},We="_EP_TRANSPORT_INIT_KEY";globalThis[We]||(typeof importScripts=="function"?new mt().expose(new xt):new ft().expose(new vt),globalThis[We]=!0);var b=class{constructor(t,e){this.namespace=t,this.shape=e}build(){return be(Object.fromEntries(Object.entries(this.shape).map(([t,e])=>[t,i=>i?.environmentContext&&i?.applicationContext?async(...r)=>{let[s,o]=await Promise.all([i.environmentContext,i.applicationContext]);return e({environmentContext:s,applicationContext:o})(...r)}:async(...r)=>{let[s,o]=await Promise.all([x.getInstance(),J.getInstance()]);return e({environmentContext:s,applicationContext:o})(...r)}])))}},bn=new b("application",{getPrivateAPI({applicationContext:n}){return async()=>n.getPrivateApplicationAPI()},getPublicAPI({applicationContext:n}){return async t=>n.getPrivateAPI().applicationManager.getPublicApplicationAPI(t)},getAppInstance({applicationContext:n}){return async()=>{let t=n.getPrivateAPI(),e=n.getBindings();return t.info.getAppInstance(e.appDefinitionId)}}}),pi=bn.build(),Tn=new b("components",{getSelectedComponents({applicationContext:n}){return async()=>{let t=n.getPrivateAPI(),e=await t.components.getSelectedComponents();return Promise.all(e.map(i=>t.components.getComponent(i)))}}}),_n=Tn.build(),Cn=new b("events",{addEventListener({applicationContext:n}){return async(t,e)=>n.getEvents().addEventListener(t,e)}}),li=Cn.build(),xn=new b("info",{getViewMode({applicationContext:n}){return async()=>n.getPrivateAPI().info.getViewMode()},getLanguageCode({applicationContext:n}){return async()=>n.getPrivateAPI().info.getLanguageCode()}}),ui=xn.build(),Ye=(n=>(n.UndefinedCompRef="UndefinedCompRef",n))(Ye||{}),ge=class extends y{constructor(t,e){super(t,e,"Widget Error")}},Rn=g(ge),Ke=async()=>{let t=(await _n.getSelectedComponents())[0]?.compRef;if(!t)throw Rn(Ye.UndefinedCompRef);return t},Nn=new b("widget",{getProp({applicationContext:n}){return async t=>{let e=n.getPrivateAPI(),i=await Ke();return e.customElement.getAttribute(i,t)}},setProp({applicationContext:n}){return async(t,e)=>{let i=n.getPrivateAPI(),r=await Ke();await i.customElement.setAttribute(r,t,e)}}}),hi=Nn.build(),ze="underline";function On(n){let t=n.trim(),e=t.match(/var\((--[\w-]+),\s*(.+)\)/);return e?{variableName:e[1],fallbackValue:e[2]?.trim()??""}:{variableName:void 0,fallbackValue:t}}function Mn(n){let t={family:void 0,size:void 0};if(n?.font){let{variableName:e,fallbackValue:i}=On(n.font);t.cssVariableName=e;let r=i.match(/(?:(["']).*?\1|\S)+/g)||[];for(let s=0;s<r.length;s++){let o=r[s];switch(o){case"bold":t.bold=!0;break;case"italic":t.italic=!0;break;default:o?.endsWith("px")?t.size=parseInt(o,10):s===r.length-1?t.family=o:t.family=(t.family||"")+" "+o}}}return n?.textDecoration&&(t.underline=n.textDecoration===ze),t.family=t.family?.trim().replace(/['"]+/g,""),t}function Sn(n){return`${n.cssVariableName?`var(${n.cssVariableName}, `:""}${n.italic?"italic ":""}${n.bold?"bold ":""}${n.size||16}px ${n.family?.split(",").map(t=>`"${t.replace(/['"]+/g,"")}"`).join(",")||"serif"}${n.cssVariableName?")":""}`}function Dn(n){if(!n)return null;let t=n,e=t.match(/var\((--[\w-]+),\s*(.+)\)/);return e?{cssVariableName:e[1],color:e[2]}:{color:t}}function $e(n){return n?n.cssVariableName?`var(${n.cssVariableName}, ${n.color})`:n.color:""}var jn={transformFontInternalValue:n=>{if(n){let{theme:t,cssVariableName:e,bold:i,italic:r,underline:s,...o}=n;return{...o,style:{bold:i,italic:r,underline:s},editorKey:e||t||""}}else return{editorKey:"font_7",family:"helvetica-w01-roman",size:16,style:{}}}},kn=new b("inputs",{selectColor({applicationContext:n}){return async(t,e)=>{let i=n.getPrivateAPI(),r=Dn(t),s=$e(r);return await i.inputs.openColorPicker({color:r?.cssVariableName||r?.theme||r?.color},({color:o,theme:p,cssVariableTheme:l})=>{r={color:o,theme:p,cssVariableName:l},s=$e(r),e?.onChange?.(s)}),s}},selectFont({applicationContext:n}){return async(t,e)=>{let i=n.getPrivateAPI(),r=Mn(t),s=t;return await i.inputs.openFontPickerV2({...e,panelSectionsDefinition:{...e?.panelSectionsDefinition,htmlTag:"hidden"},componentStyle:jn.transformFontInternalValue(r)},(o,p)=>{s={font:Sn(o),textDecoration:o.underline?ze:void 0},e?.onChange?.(s)}),s}}}),di=kn.build(),Ln=new b("externalPanels",{getData({applicationContext:n}){return async()=>n.getPrivateAPI().externalPanels.getData()},setData({applicationContext:n}){return async t=>n.getPrivateAPI().externalPanels.setData(t)},getStyle({applicationContext:n}){return async()=>n.getPrivateAPI().externalPanels.getStyle()},setStyle({applicationContext:n}){return async t=>n.getPrivateAPI().externalPanels.setStyle(t)},getTheme({applicationContext:n}){return async()=>n.getPrivateAPI().externalPanels.getTheme()},selectMedia({applicationContext:n}){return async()=>n.getPrivateAPI().externalPanels.selectMedia()},selectLink({applicationContext:n}){return async()=>n.getPrivateAPI().externalPanels.selectLink()},selectColor({applicationContext:n}){return async()=>n.getPrivateAPI().externalPanels.selectColor()},translate({applicationContext:n}){return async(t,e)=>n.getPrivateAPI().externalPanels.translate(t,e)}}),fi=Ln.build(),Fn=()=>{let n=new URLSearchParams(window.location.search);return{environment:{},channel:{observeState:async()=>({disconnect(){}})},environmentContext:x.getInstance(),applicationContext:J.getInstance(),essentials:n.has("essentials")?JSON.parse(n.get("essentials")):{}}},Un=()=>({environment:{},channel:{observeState:async()=>({disconnect(){}})},environmentContext:x.getInstance(),applicationContext:J.getInstance()}),Ee={host:()=>typeof importScripts=="function"?Un():Fn(),auth:wn};var gi=()=>{let n=Ee.host(),t=Ee.auth();we({auth:t,host:n}).enableContext("module")};export{gi as enableClient};
7
+ `)}getBreadcrumbs(){let e=this.parentError;return e?[...e.getBreadcrumbs(),this.displayName]:[this.displayName]}withParentError(e){return this.parent=e,this}withMessage(...e){return this.messages.push(e),this}};function g(n){return function t(e,i=""){let r=new n(i,e);return Error.captureStackTrace&&Error.captureStackTrace(r,t),r}}var Ft=class extends y{constructor(e,i){super(e,i,"Editor Platform Internal Error");a(this,"state",{})}withHost(e){return this.state={...this.state,host:e},this}},Vn=g(Ft);var H=we(Ut(),1);var x=class x{constructor(){a(this,"uid",0);a(this,"callbacks",new Map);a(this,"inTransaction",!1);a(this,"isSilent",!1);a(this,"queue",[])}silent(t=!0){this.isSilent=t}startTransaction(){this.inTransaction=!0}commit(){this.inTransaction=!1;let t=this.queue;this.queue=[],this.isSilent||t.forEach(e=>{this.notify(e)})}notify(t){this.isSilent||(this.inTransaction?this.queue.push(t):this.callbacks.forEach(e=>{e(t)}))}subscribe(t){let e=this.uid++;return this.callbacks.set(e,t),()=>{this.callbacks.delete(e)}}notifyWithStep(t,e){this.notify({...t,meta:{...t.meta,step:e}})}async withEvent(t,e){let i=e();if(i&&i.hasOwnProperty("then"))try{return this.notifyWithStep(t,x.EventSteps.Start),i=await i,this.notifyWithStep(t,x.EventSteps.End),i}catch(r){throw this.notifyWithStep({...t,meta:{...t.meta,error:r}},x.EventSteps.Error),r}else return this.notify(t),i}};a(x,"biEvents",{PLATFORM_WORKER_SPAWN:123,PLATFORM_APP_RUNNER_INIT_APP_API:124,PLATFORM_APP_RUNNER_RUN_APP:125,PLATFORM_APP_RUNNER_REMOVE_APP:126,PLATFORM_WORKER_APP_BUNDLE_LOAD:127,PLATFORM_WORKER_APP_BUNDLE_EXECUTE:128,PLATFORM_IFRAME_INIT:129,PLATFORM_APP_API_INIT:130,PLATFORM_APP_API_GET:131}),a(x,"EventSteps",{Start:"start",End:"end",Error:"error"});var Wt=x,L=(n=>(n.WorkerSpawn="WorkerSpawn",n.HostEvent="HostEvent",n.ApplicationsSpecsReceived="ApplicationsSpecsReceived",n.InitApplicationApi="InitApplicationApi",n.RunApplication="RunApplication",n.getApplicationApi="getApplicationApi",n.IframeInit="IframeInit",n))(L||{}),J=(n=>(n.EditorReady="EditorReady",n))(J||{});var d=(n=>(n.ApplicationInit="ApplicationInit",n.ApplicationExecute="ApplicationExecute",n.ApplicationRemoved="ApplicationRemoved",n.ApplicationLoad="ApplicationLoad",n.ApplicationApiInit="ApplicationApiInit",n.CustomEvent="CustomEvent",n.HostEvent="HostEvent",n.EditorReady="EditorReady",n))(d||{}),Kt=class{createApplicationRemovedEvent(t){return{type:"ApplicationRemoved",payload:{appDefinitionId:t},meta:{bi:{evid:E.biEvents.PLATFORM_WORKER_SPAWN,appDefId:t}}}}createApplicationLoadEvent(t,e){return{type:"ApplicationLoad",payload:{appDefinitionId:t.appDefinitionId,url:e},meta:{bi:{evid:E.biEvents.PLATFORM_WORKER_APP_BUNDLE_LOAD,appDefId:t.appDefinitionId,appType:t.appType,bundleUrl:e}}}}createApplicationExecuteEvent(t,e){return{type:"ApplicationExecute",payload:{appDefinitionId:t.appDefinitionId,url:e},meta:{bi:{evid:E.biEvents.PLATFORM_WORKER_APP_BUNDLE_EXECUTE,appDefId:t.appDefinitionId,appType:t.appType,bundleUrl:e}}}}createApplicationApiInitEvent(t,e){return{type:"ApplicationApiInit",payload:{appDefinitionId:t},meta:{bi:{evid:E.biEvents.PLATFORM_APP_API_INIT,appDefId:t,scope:e}}}}},E=class extends Wt{constructor(){super(...arguments);a(this,"factories",new Kt)}},lt=class lt{constructor(t){this.events=t}mapToPlatformHostEvent(t){if(typeof t=="string")try{t=JSON.parse(t)}catch{}return{type:L.HostEvent,payload:{type:t.args.eventType,...t.args.eventPayload},meta:{appDefinitionId:t.appDefinitionId??null,intent:t.intent}}}notify(t){let e=this.mapToPlatformHostEvent(t);lt.allowedEvents.includes(e.payload.type)&&this.events.notify(e)}};a(lt,"allowedEvents",[H.EventType.componentSelectionChanged,H.EventType.appInstalled,H.EventType.appUpdateCompleted,H.EventType.removeAppCompleted]);var Ne=lt;var et=n=>`"editor-platform-transport": ${n}`,Me=n=>et(`[Internal Error] ${n}`),je="\u0192",ke="\u2202",Le="_get_",Fe="_set_",ut="+",Se="-",Ht="\xB7",Jt="\xD7",Gt="\xB0",Ue=n=>n[0]===Jt?"":n,De=n=>n===null||typeof n>"u"||typeof n=="symbol"||typeof n=="number"||typeof n=="boolean"||typeof n=="function"||typeof n=="string",an=n=>!!n&&typeof n=="object"&&!Array.isArray(n)&&!(n instanceof Date)&&!(n instanceof Set)&&!(n instanceof Map),cn=n=>F(n.split(Ht)),F=n=>n.map(Ue).filter(Boolean).join(".");function vt(n,t){return{marker:n,...t}}var pn=vt("A",{shouldUse:n=>Array.isArray(n),serialize:(n,t)=>{n.length?n.forEach((e,i)=>{t(`${i}`,e)}):t("",Gt)},deserialize:{create:()=>[],has:(n,t)=>!(typeof n[t]>"u"),append:(n,t,e)=>{n.push(e)}}}),ln=vt("M",{shouldUse:n=>n instanceof Map,serialize:(n,t)=>{n.forEach((e,i)=>{t(i,e)})},deserialize:{create:()=>new Map,has:(n,t)=>n.has(t),append:(n,t,e)=>{n.set(t,e)}}}),un=vt("S",{shouldUse:n=>n instanceof Set,serialize:(n,t)=>{let e=0;n.forEach(i=>{t(`${e++}`,i)})},deserialize:{create:()=>new Set,has:(n,t)=>n.has(t),append:(n,t,e)=>{n.add(e)}}}),Yt=vt("O",{shouldUse:n=>typeof n=="object",serialize:(n,t)=>{let e=i=>{let s=Reflect.ownKeys(i).filter(p=>p!=="constructor").filter(p=>typeof p!="symbol");s.length?s.filter(p=>p!=="constructor").filter(p=>typeof p!="symbol").forEach(p=>{let l=Reflect.get(n,p);t(p,l)}):t("",Gt);let o=Reflect.getPrototypeOf(i);!o||o?.hasOwnProperty("__proto__")||e(o)};e(n)},deserialize:{create:()=>({}),has:(n,t)=>!!n[t],append:(n,t,e)=>{n[t]=e}}}),We=[pn,un,ln];function hn(n,t){let e=n;for(;e;){let i=Object.getOwnPropertyDescriptor(e,t);if(i)return i;e=Reflect.getPrototypeOf(e)}return null}function dn(n,t){let e=new WeakMap,i=s=>{let o=s.slice(1).map(Ue).filter(Boolean);return o.slice(1).reduce((p,l)=>({context:p.context[p.pointer],pointer:l}),{context:n,pointer:o[0]})},r=(s,o=[])=>{if(e.has(s)&&e.get(s)?.some(h=>o.join(".").startsWith(h))){t(o,{...i(o),value:"[Circular]"});return}if(s&&!De(s)&&(e.has(s)&&e.set(s,[]),e.set(s,[...e.get(s)??[],o.join(".")])),De(s)){t(o,{...i(o),value:s});return}let p=We.find(l=>l.shouldUse(s))??Yt;if(p){p.serialize(s,(l,h)=>{r(h,[...o,`${Jt}${p.marker}`,l])});return}};return r(n)}var fn=(n,t)=>{if(!an(n))throw new Error(et("only objects are serializable at the root level"));let e={data:[]},i=(s,o)=>{e.data.push([s,o])},r=(s,o)=>{t(cn(s),(...p)=>o.context[o.pointer](...p)),i(s,je)};return dn(n,(s,{value:o,context:p,pointer:l})=>{let h=s.slice(1).join(Ht),f=hn(p,l);if(f?.get||f?.set){f?.get&&t(F([...s,Le]),()=>p[l]),f?.set&&t(F([...s,Fe]),V=>{p[l]=V});let R=[f?.get?ut:Se,f?.set?ut:Se];i(h,`${ke}${R.join("")}`)}else typeof o=="function"?r(h,{context:p,pointer:l}):i(h,o)}),e},In=(n,t)=>typeof n!="object"||n===null?n:n.data.reduce((e,[i,r])=>{let s=e,o=i.split(Ht),p=Yt,l=null;for(let h=0;h<o.length;h++){let f=o[h];if(f[0]===Jt){let R=p.deserialize.has(s,l);if(p=[Yt,...We].find(V=>V.marker===f[1]),!p)throw new Error(et(`unknown marker "${f[1]}"`));R||(s[l]=p.deserialize.create()),s=s[l]}else l=f}if(r?.toString()===Gt)return e;if(r?.toString()===je)p.deserialize.append(s,l,t(F(o)));else if(r?.toString()[0]===ke){let h=r?.toString()[1]===ut,f=r?.toString()[2]===ut,R={};if(h){let V=t(F([...o,Le]));R.get=()=>V()}f&&(R.set=t(F([...o,Fe]))),Object.defineProperty(s,l,R)}else p.deserialize.append(s,l,r);return e},{[Symbol("transferred object")]:`${(JSON.stringify(n.data).length/1024).toFixed(2)}Kb`}),Q=(n=>(n.ExposeAPI="ExposeAPI",n.Call="Call",n.Response="Response",n.Cleanup="Cleanup",n))(Q||{}),T=class n{constructor(t,e){a(this,"correlationId",`M-${performance.now()}`);a(this,"parentCorrelationId");this.type=t,this.payload=e}withParentCorrelationId(t){return this.parentCorrelationId=t,this}serialize(t){return JSON.stringify({parentCorrelationId:this.parentCorrelationId,correlationId:this.correlationId,type:this.type,payload:fn(this.payload,(e,i)=>{t(this.correlationId,e,i)})})}static fromEvent(t,e){let i=JSON.parse(t);return new n(i.type,In(i.payload,r=>e(i.correlationId,r))).withParentCorrelationId(i.correlationId)}},zt=class extends T{constructor(t){super("Cleanup",t)}},Bt=class extends T{constructor(t){super("Response",t)}},ht=class extends T{constructor(t){super("Response",t)}},qt=class extends T{constructor(t){super("Call",t)}},$t=(n,t)=>`${n}_${t}`,At,gt,U,v,Vt=class{constructor(t){u(this,At,new FinalizationRegistry(t=>{this.postMessage(new zt(t))}));u(this,gt,{[Q.Cleanup]:t=>{let e=t.payload.functionMarkerKey,i=t.payload.callId;delete c(this,U)[e],i&&delete c(this,v)[i]},[Q.Response]:async t=>{let e=t.payload.callId,i=t.payload.errorMessage;if(i)if(t.payload.errorStack){let s=new Error(i);s.stack=t.payload.errorStack,c(this,v)[e]?.reject(s)}else c(this,v)[e]?.reject(i);else{let r=t.payload.response;c(this,v)[e]?.resolve(r)}delete c(this,v)[e]},[Q.Call]:async t=>{let e=t.payload.functionMarkerKey,i=c(this,U)[e];if(!i){this.postMessage(new ht({callId:t.payload.callId,errorMessage:et("function is not available")}));return}try{let r=await i.value(...t.payload.props??[]);this.postMessage(new Bt({callId:t.payload.callId,response:r}))}catch(r){this.postMessage(new ht({callId:t.payload.callId,errorMessage:r.message,errorStack:r.stack}))}}});u(this,U,{});u(this,v,{});a(this,"queue",[]);this.port=t,this.port.onmessage=e=>{this.onMessage(e)}}onMessage(t){let e=T.fromEvent(t.data,(i,r)=>{let s=this.replaceTransferredFunction(i,r);return c(this,At).register(s,{functionMarkerKey:$t(i,r)}),s});c(this,gt)[e.type]?.(e),this.messageEvents[e.type]?.(e)}postMessage(t){this.port.postMessage(t.serialize(this.registerTransferredFunction.bind(this)))}registerTransferredFunction(t,e,i){let r=$t(t,e);c(this,U)[r]={path:e,value:i}}replaceTransferredFunction(t,e){return(...i)=>{let r=`CALL-${crypto.randomUUID()}`;return this.postMessage(new qt({callId:r,functionMarkerKey:$t(t,e),props:i})),new Promise((s,o)=>{c(this,v)[r]={resolve:s,reject:o}})}}flush(){this.queue.forEach(t=>{this.postMessage(t)}),this.queue=[]}};At=new WeakMap,gt=new WeakMap,U=new WeakMap,v=new WeakMap;var dt=class extends Vt{constructor(){super(...arguments);a(this,"messageEvents",{})}expose(e){if(!e.type)throw new Error(et('wrong exposed API instance, "type" property is required'));this.queue.push(new T(Q.ExposeAPI,e)),this.flush()}};var G=(n=>(n.Ping="EDITOR_PLATFORM_TRANSPORT_EVENT:__Ping",n.RequestPort="EDITOR_PLATFORM_TRANSPORT_EVENT:__RequestPort",n.Pong="EDITOR_PLATFORM_TRANSPORT_EVENT:__Pong",n.Port="EDITOR_PLATFORM_TRANSPORT_EVENT:__Port",n))(G||{}),W,w,Et,Ke,Xt=class{constructor(t,e){u(this,Et);u(this,W,new Set);u(this,w);this.postMessage=t,this.onMessage=e}setActivePort(t){this.dispose(),A(this,w,t),X(this,Et,Ke).call(this)}dispose(){c(this,w)&&(c(this,w).close(),c(this,w).onmessage=null)}onHandshake(t){return c(this,W).add(t),()=>{c(this,W).delete(t)}}};W=new WeakMap,w=new WeakMap,Et=new WeakSet,Ke=function(){let t=c(this,w);if(!t){console.warn(Me("port is required no notify onHandshake listeners"));return}c(this,W).forEach(e=>e(t))};var Z,tt,b,$e,Ye,ze,ft=class extends Xt{constructor(e,i){super(e,i);u(this,b);u(this,Z,!1);u(this,tt,`consumer-${performance.now()}`);X(this,b,$e).call(this);let r={type:G.Ping};e(JSON.stringify(r))}};Z=new WeakMap,tt=new WeakMap,b=new WeakSet,$e=function(){this.onMessage(e=>{try{let i=JSON.parse(e.data);switch(i.type){case G.Pong:{X(this,b,Ye).call(this);break}case G.Port:{X(this,b,ze).call(this,i.targetMemberId,e.ports?.[0]);break}}}catch{}})},Ye=function(){if(c(this,Z))return;A(this,Z,!0);let e={type:G.RequestPort,memberId:c(this,tt)};this.postMessage(JSON.stringify(e))},ze=function(e,i){if(e===c(this,tt)){if(!i)throw new Error(Me("no port at consumer handshake"));this.setActivePort(i)}};var It=class{get onConnect(){return this.handshake.onHandshake.bind(this.handshake)}},mt=class n extends It{constructor(){super(...arguments);a(this,"handshake",new ft(e=>{globalThis.parent.postMessage(e,"*")},e=>{globalThis.addEventListener("message",e)}))}static exposeAPI(e){new n().onConnect(r=>{new dt(r).expose(e)})}};var yt=class n extends It{constructor(){super(...arguments);a(this,"handshake",new ft(e=>{globalThis.postMessage(e)},e=>{globalThis.addEventListener("message",e)}))}static exposeAPI(e){new n().onConnect(r=>{new dt(r).expose(e)})}};var te=class{constructor(t){this.platformAppEvents=t}notify(t){switch(t.type){case J.EditorReady:this.platformAppEvents.notify({...t,type:d.EditorReady});break;case L.HostEvent:this.platformAppEvents.notify({...t,type:d.HostEvent});break}}subscribe(t){this.platformAppEvents.subscribe(e=>{t(e)})}},ee=(n=>(n.Frame="PLATFORM_FRAME_API",n.Worker="PLATFORM_WORKER_API",n))(ee||{}),ne=class{constructor(t){this.env=t,this.create()}},O=(n=>(n.IncorrectEnvironment="IncorrectEnvironment",n.ClientAuthError="ClientAuthError",n))(O||{}),ie=class extends y{constructor(e,i){super(e,i,"Editor Platform Application Context Error");a(this,"state",{})}withUrl(e){return this.state={...this.state,url:e},this}withAppDefinitionId(e){return this.state={...this.state,appDefinitionId:e},this}},K=g(ie);async function mn(n,t){if(!n?.type)return n;switch(n.type){case"componentSelectionChanged":let e=n.componentRefs||[],i=await Promise.all(e.map(r=>t.components.getComponent(r)));return{type:n.type,components:i};default:return n}}var re=class{constructor(t,e,i){a(this,"events");a(this,"subscribe");a(this,"commit");a(this,"startTransaction");a(this,"silent");this.appDefinitionId=t,this.privateAPI=i,this.events=e,this.subscribe=e.subscribe.bind(e),this.commit=e.commit.bind(e),this.startTransaction=e.startTransaction.bind(e),this.silent=e.silent.bind(e)}notify(t){this.events.notify({type:t.type,payload:t.payload,meta:{appDefinitionId:this.appDefinitionId}})}notifyCustomEvent(t,e){this.notify({type:d.CustomEvent,payload:{...e,type:t}})}addEventListener(t,e){return this.events.subscribe(async i=>{let r=i.meta?.appDefinitionId===this.appDefinitionId||i.meta?.appDefinitionId===null,s=()=>mn(i.payload,this.privateAPI);t==="*"?e(await s()):i.type===d.CustomEvent?t===i.payload?.type&&!r&&e(await s()):i.type===d.HostEvent&&t===i.payload?.type&&r&&e(await s())})}},yn=200,An=50,Pt=class{constructor(t){a(this,"_resolveContextInjected",()=>{});a(this,"_isInjected",!1);a(this,"key");this.key=`__${t}_CONTEXT_INJECTION_STATUS_KEY`,globalThis[this.key]||(globalThis[this.key]=new Promise(e=>{this._resolveContextInjected=()=>{this._isInjected=!0,e()}}))}isInjected(){return!!this._isInjected}resolveInjected(){this._resolveContextInjected?.()}waitInjected(){return new Promise((t,e)=>{let i=!1,r,s=0,o=()=>{i||(r=setTimeout(()=>{if(s++,s<An){s%10===0&&console.log(K(O.IncorrectEnvironment,"contexts are not resolved, still re-trying").withMessage(`try number ${s}`).message),o();return}if(!i){let l=K(O.IncorrectEnvironment,"contexts are not resolved, threw by timeout");e(l)}},yn))};o(),globalThis[this.key].then(()=>{i=!0,clearTimeout(r),t()})})}},Qt="__ENVIRONMENT_CONTEXT_KEY",wt=(n=>(n.Worker="Worker",n.Frame="Frame",n.ComponentPanel="ComponentPanel",n))(wt||{}),bt=class bt{constructor(t){this.environmentContext=t}static async inject(t){if(globalThis[Qt])throw K(O.IncorrectEnvironment,"Environment context already exists and should not be overridden");globalThis[Qt]=new bt(t),this.status.resolveInjected()}static async getInstance(){return await this.status.waitInjected(),globalThis[Qt]}getPrivateAPI(){return this.environmentContext.privateApi}getEvents(){return this.environmentContext.events}getApplicationAPIs(){return this.environmentContext.applicationAPIs??{}}getEnvironment(){return this.environmentContext.environment}};a(bt,"status",new Pt("environment"));var $=bt,Zt="__APPLICATION_CONTEXT_KEY",_t=class _t{constructor(t,e){a(this,"events");this.applicationContext=t,this.environment=e,this.events=new re(this.applicationContext.appDefinitionId,this.environment.getEvents(),this.environment.getPrivateAPI())}static async inject(t){if((await $.getInstance()).getEnvironment()!==wt.Frame)throw K(O.IncorrectEnvironment,"Application context can be injected only in frame environment");if(globalThis[Zt])throw K(O.IncorrectEnvironment,"Application context already exists and should not be overridden");globalThis[Zt]=new _t(t,await $.getInstance()),this.status.resolveInjected()}static async getInstance(){return(await $.getInstance()).getEnvironment()===wt.Frame?(await this.status.waitInjected(),globalThis[Zt]):__APPLICATION_CONTEXT_KEY}getAppDefinitionId(){return this.applicationContext.appDefinitionId}getBindings(){return this.applicationContext}getEvents(){return this.events}getPrivateAPI(){return this.environment.getPrivateAPI()}getPrivateApplicationAPI(){let t=this.getAppDefinitionId();if(!t)throw K(O.IncorrectEnvironment,"appDefinitionId is not available");return this.environment.getApplicationAPIs()[t]}};a(_t,"status",new Pt("application"));var se=_t,gn={classic:"https://www.unpkg.com/@wix/design-system/dist/statics/tokens-default.global.css",studio:"https://www.unpkg.com/@wix/design-system/dist/statics/tokens-studio.global.css"},nt,it,Ct,rt,Tt=class extends ne{constructor(){super(ee.Frame);a(this,"type",ee.Frame);u(this,nt,new E);u(this,it,new te(c(this,nt)));u(this,Ct);u(this,rt)}create(){if(typeof globalThis?.document?.head?.prepend=="function"){let i=new URL(globalThis.location.href).searchParams.get("editorType")==="CLASSIC"?"classic":"studio",r=gn[i],s=r&&!!document.querySelectorAll(`link[type="text/css"][href="${r}"]`)?.length;if(r&&!s){let o=document.createElement("link");o.setAttribute("rel","stylesheet"),o.setAttribute("type","text/css"),o.setAttribute("href",r),globalThis.document.head.prepend(o)}}}async initEnvironment(e){let{applicationPrivateAPI:i,privateAPI:r,appDefinitionId:s}=e;A(this,rt,i),A(this,Ct,r),await $.inject({environment:wt.Frame,privateApi:r,events:c(this,nt),applicationAPIs:{[s]:c(this,rt)}}),await se.inject({appDefinitionId:s,appDefinitionName:""})}notify(e){c(this,it).notify(e)}subscribe(e){c(this,it).subscribe(e)}};nt=new WeakMap,it=new WeakMap,Ct=new WeakMap,rt=new WeakMap;var Be=we(Ut());var ae=class{constructor(t){this.platformAppEvents=t}notify(t){switch(t.type){case J.EditorReady:this.platformAppEvents.notify({...t,type:d.EditorReady});break;case L.HostEvent:this.platformAppEvents.notify({...t,type:d.HostEvent});break}}subscribe(t){this.platformAppEvents.subscribe(e=>{t(e)})}},M=(n=>(n.IncorrectEnvironment="IncorrectEnvironment",n.ClientAuthError="ClientAuthError",n))(M||{}),ce=class extends y{constructor(e,i){super(e,i,"Editor Platform Application Context Error");a(this,"state",{})}withUrl(e){return this.state={...this.state,url:e},this}withAppDefinitionId(e){return this.state={...this.state,appDefinitionId:e},this}},Y=g(ce);async function En(n,t){if(!n?.type)return n;switch(n.type){case"componentSelectionChanged":let e=n.componentRefs||[],i=await Promise.all(e.map(r=>t.components.getComponent(r)));return{type:n.type,components:i};default:return n}}var pe=class{constructor(t,e,i){a(this,"events");a(this,"subscribe");a(this,"commit");a(this,"startTransaction");a(this,"silent");this.appDefinitionId=t,this.privateAPI=i,this.events=e,this.subscribe=e.subscribe.bind(e),this.commit=e.commit.bind(e),this.startTransaction=e.startTransaction.bind(e),this.silent=e.silent.bind(e)}notify(t){this.events.notify({type:t.type,payload:t.payload,meta:{appDefinitionId:this.appDefinitionId}})}notifyCustomEvent(t,e){this.notify({type:d.CustomEvent,payload:{...e,type:t}})}addEventListener(t,e){return this.events.subscribe(async i=>{let r=i.meta?.appDefinitionId===this.appDefinitionId||i.meta?.appDefinitionId===null,s=()=>En(i.payload,this.privateAPI);t==="*"?e(await s()):i.type===d.CustomEvent?t===i.payload?.type&&!r&&e(await s()):i.type===d.HostEvent&&t===i.payload?.type&&r&&e(await s())})}},vn=200,Pn=50,xt=class{constructor(t){a(this,"_resolveContextInjected",()=>{});a(this,"_isInjected",!1);a(this,"key");this.key=`__${t}_CONTEXT_INJECTION_STATUS_KEY`,globalThis[this.key]||(globalThis[this.key]=new Promise(e=>{this._resolveContextInjected=()=>{this._isInjected=!0,e()}}))}isInjected(){return!!this._isInjected}resolveInjected(){this._resolveContextInjected?.()}waitInjected(){return new Promise((t,e)=>{let i=!1,r,s=0,o=()=>{i||(r=setTimeout(()=>{if(s++,s<Pn){s%10===0&&console.log(Y(M.IncorrectEnvironment,"contexts are not resolved, still re-trying").withMessage(`try number ${s}`).message),o();return}if(!i){let l=Y(M.IncorrectEnvironment,"contexts are not resolved, threw by timeout");e(l)}},vn))};o(),globalThis[this.key].then(()=>{i=!0,clearTimeout(r),t()})})}},oe="__ENVIRONMENT_CONTEXT_KEY",Ot=(n=>(n.Worker="Worker",n.Frame="Frame",n.ComponentPanel="ComponentPanel",n))(Ot||{}),St=class St{constructor(t){this.environmentContext=t}static async inject(t){if(globalThis[oe])throw Y(M.IncorrectEnvironment,"Environment context already exists and should not be overridden");globalThis[oe]=new St(t),this.status.resolveInjected()}static async getInstance(){return await this.status.waitInjected(),globalThis[oe]}getPrivateAPI(){return this.environmentContext.privateApi}getEvents(){return this.environmentContext.events}getApplicationAPIs(){return this.environmentContext.applicationAPIs??{}}getEnvironment(){return this.environmentContext.environment}};a(St,"status",new xt("environment"));var j=St,Rt="__APPLICATION_CONTEXT_KEY",Dt=class Dt{constructor(t,e){a(this,"events");this.applicationContext=t,this.environment=e,this.events=new pe(this.applicationContext.appDefinitionId,this.environment.getEvents(),this.environment.getPrivateAPI())}static async inject(t){if((await j.getInstance()).getEnvironment()!==Ot.Frame)throw Y(M.IncorrectEnvironment,"Application context can be injected only in frame environment");if(globalThis[Rt])throw Y(M.IncorrectEnvironment,"Application context already exists and should not be overridden");globalThis[Rt]=new Dt(t,await j.getInstance()),this.status.resolveInjected()}static async getInstance(){return(await j.getInstance()).getEnvironment()===Ot.Frame?(await this.status.waitInjected(),globalThis[Rt]):__APPLICATION_CONTEXT_KEY}getAppDefinitionId(){return this.applicationContext.appDefinitionId}getBindings(){return this.applicationContext}getEvents(){return this.events}getPrivateAPI(){return this.environment.getPrivateAPI()}getPrivateApplicationAPI(){let t=this.getAppDefinitionId();if(!t)throw Y(M.IncorrectEnvironment,"appDefinitionId is not available");return this.environment.getApplicationAPIs()[t]}};a(Dt,"status",new xt("application"));var le=Dt,_=(n=>(n.ApplicationRuntimeError="ApplicationRuntimeError",n.ApplicationCreationError="ApplicationCreationError",n.ApplicationLoadError="ApplicationLoadError",n.ApplicationFetchError="ApplicationFetchError",n.ApplicationExecuteError="ApplicationExecuteError",n.ApplicationWasRemoved="ApplicationWasRemoved",n.UndefinedApiMethod="UndefinedApiMethod",n.ApplicationIsNotMutable="ApplicationIsNotMutable",n.FailedToGetPrivateAPI="FailedToGetPrivateAPI",n.ClientAuthError="ClientAuthError",n))(_||{}),ue=class extends y{constructor(e,i){super(e,i,"Editor Platform Application Error");a(this,"state",{})}withUrl(e){return this.state={...this.state,url:e},this}withAppDefinitionId(e){return this.state={...this.state,appDefinitionId:e},this}withApiMethod(e){return this.state={...this.state,apiMethod:e},this}withApiType(e){return this.state={...this.state,apiType:e},this}},N=g(ue),wn="__APPLICATION_REGISTRY_KEY";async function Tn(n,t,e){let i=new Function(Rt,wn,e),r,s=o=>{if(r)throw N(_.ApplicationExecuteError,"Application registry called more than once").withAppDefinitionId(t.appDefinitionId);if(o.type!==t.type)throw N(_.ApplicationExecuteError,"Application has different type").withMessage("expected type",t.type).withMessage("received type",o.type);r=o};try{let o={...t};i.call(null,new le(o,await j.getInstance()),s)}catch(o){throw N(_.ApplicationExecuteError,o.message).withAppDefinitionId(t.appDefinitionId).withParentError(o)}return new Promise((o,p)=>{let l=n.subscribe(h=>{let f=setTimeout(()=>{clearTimeout(f),l(),r||p(N(_.ApplicationExecuteError,"Application registry was not called, threw by timeout").withAppDefinitionId(t.appDefinitionId))},5e3);h.type===d.ApplicationInit&&h.meta.appDefinitionId===t.appDefinitionId&&(clearTimeout(f),l(),r||p(N(_.ApplicationExecuteError,"Application registry was not called").withAppDefinitionId(t.appDefinitionId)),o({instance:r}))})})}var S,st,m,he=class{constructor(t,e){u(this,S,{});u(this,st);u(this,m);A(this,st,t),A(this,m,e),c(this,m).subscribe(i=>{switch(i.type){case d.HostEvent:{i.payload.type===Be.EventType.removeAppCompleted&&c(this,m).withEvent(c(this,m).factories.createApplicationRemovedEvent(i.payload.appDefinitionId),()=>this.removeApplication(i.payload.appDefinitionId));break}}})}async runApplication(t){let e=await this.loadApplication(t),i=await this.executeApplication(t,e);return this.setApplication(t.appDefinitionId,i),i}setApplication(t,e){c(this,S)[t]=e,c(this,m).withEvent(c(this,m).factories.createApplicationApiInitEvent(t,e?.api?.private?"private":"public"),()=>{c(this,st).applicationManager.setApplication(e)})}getApplication(t){return c(this,S)[t]}getAppDefinitionIds(){return Object.keys(c(this,S))}removeApplication(t){delete c(this,S)[t]}async loadApplication(t){let e=t.url;return c(this,m).withEvent(c(this,m).factories.createApplicationLoadEvent(t,e),async()=>{try{return await this.loadApplicationBundle(e)}catch(i){throw N(_.ApplicationLoadError).withUrl(e).withAppDefinitionId(t.appDefinitionId).withParentError(i)}})}async loadApplicationBundle(t){let e=await fetch(t,{method:"GET"});if(!(e.status>=200&&e.status<=299))throw N(_.ApplicationFetchError).withUrl(t);return e.text()}async executeApplication(t,e){return c(this,m).withEvent(c(this,m).factories.createApplicationExecuteEvent(t,t.url),async()=>{let{instance:i}=await Tn(c(this,m),t,e);return i})}};S=new WeakMap,st=new WeakMap,m=new WeakMap;var de=(n=>(n.Frame="PLATFORM_FRAME_API",n.Worker="PLATFORM_WORKER_API",n))(de||{}),fe=class{constructor(t){this.env=t,this.create()}},z,ot,at,D,ct,Nt=class extends fe{constructor(){super(de.Worker);a(this,"type",de.Worker);u(this,z,new E);u(this,ot,new ae(c(this,z)));u(this,at,null);u(this,D);u(this,ct,[])}create(){}async initEnvironment(e){let{buildPrivateAPI:i}=e;A(this,D,await i({type:"EDITOR_ADDON"})),await j.inject({environment:Ot.Worker,events:c(this,z),privateApi:c(this,D),applicationAPIs:{}}),A(this,at,new he(c(this,D),c(this,z))),c(this,ct).forEach(r=>r(this))}async notify(e){await this.waitReady(),c(this,ot).notify(e)}subscribe(e){c(this,ot).subscribe(e)}async runApplication(e){await this.waitReady(),await c(this,at).runApplication(e)}waitReady(){return new Promise(e=>{if(c(this,D))return e(this);c(this,ct).push(e)})}};z=new WeakMap,ot=new WeakMap,at=new WeakMap,D=new WeakMap,ct=new WeakMap;var k=(n=>(n.IncorrectEnvironment="IncorrectEnvironment",n.ClientAuthError="ClientAuthError",n))(k||{}),ye=class extends y{constructor(e,i){super(e,i,"Editor Platform Application Context Error");a(this,"state",{})}withUrl(e){return this.state={...this.state,url:e},this}withAppDefinitionId(e){return this.state={...this.state,appDefinitionId:e},this}},B=g(ye);async function bn(n,t){if(!n?.type)return n;switch(n.type){case"componentSelectionChanged":let e=n.componentRefs||[],i=await Promise.all(e.map(r=>t.components.getComponent(r)));return{type:n.type,components:i};default:return n}}var Ae=class{constructor(t,e,i){a(this,"events");a(this,"subscribe");a(this,"commit");a(this,"startTransaction");a(this,"silent");this.appDefinitionId=t,this.privateAPI=i,this.events=e,this.subscribe=e.subscribe.bind(e),this.commit=e.commit.bind(e),this.startTransaction=e.startTransaction.bind(e),this.silent=e.silent.bind(e)}notify(t){this.events.notify({type:t.type,payload:t.payload,meta:{appDefinitionId:this.appDefinitionId}})}notifyCustomEvent(t,e){this.notify({type:d.CustomEvent,payload:{...e,type:t}})}addEventListener(t,e){return this.events.subscribe(async i=>{let r=i.meta?.appDefinitionId===this.appDefinitionId||i.meta?.appDefinitionId===null,s=()=>bn(i.payload,this.privateAPI);t==="*"?e(await s()):i.type===d.CustomEvent?t===i.payload?.type&&!r&&e(await s()):i.type===d.HostEvent&&t===i.payload?.type&&r&&e(await s())})}},_n=200,Cn=50,Mt=class{constructor(t){a(this,"_resolveContextInjected",()=>{});a(this,"_isInjected",!1);a(this,"key");this.key=`__${t}_CONTEXT_INJECTION_STATUS_KEY`,globalThis[this.key]||(globalThis[this.key]=new Promise(e=>{this._resolveContextInjected=()=>{this._isInjected=!0,e()}}))}isInjected(){return!!this._isInjected}resolveInjected(){this._resolveContextInjected?.()}waitInjected(){return new Promise((t,e)=>{let i=!1,r,s=0,o=()=>{i||(r=setTimeout(()=>{if(s++,s<Cn){s%10===0&&console.log(B(k.IncorrectEnvironment,"contexts are not resolved, still re-trying").withMessage(`try number ${s}`).message),o();return}if(!i){let l=B(k.IncorrectEnvironment,"contexts are not resolved, threw by timeout");e(l)}},_n))};o(),globalThis[this.key].then(()=>{i=!0,clearTimeout(r),t()})})}},Ie="__ENVIRONMENT_CONTEXT_KEY",ge=(n=>(n.Worker="Worker",n.Frame="Frame",n.ComponentPanel="ComponentPanel",n))(ge||{}),jt=class jt{constructor(t){this.environmentContext=t}static async inject(t){if(globalThis[Ie])throw B(k.IncorrectEnvironment,"Environment context already exists and should not be overridden");globalThis[Ie]=new jt(t),this.status.resolveInjected()}static async getInstance(){return await this.status.waitInjected(),globalThis[Ie]}getPrivateAPI(){return this.environmentContext.privateApi}getEvents(){return this.environmentContext.events}getApplicationAPIs(){return this.environmentContext.applicationAPIs??{}}getEnvironment(){return this.environmentContext.environment}};a(jt,"status",new Mt("environment"));var C=jt,me="__APPLICATION_CONTEXT_KEY",kt=class kt{constructor(t,e){a(this,"events");this.applicationContext=t,this.environment=e,this.events=new Ae(this.applicationContext.appDefinitionId,this.environment.getEvents(),this.environment.getPrivateAPI())}static async inject(t){if((await C.getInstance()).getEnvironment()!==ge.Frame)throw B(k.IncorrectEnvironment,"Application context can be injected only in frame environment");if(globalThis[me])throw B(k.IncorrectEnvironment,"Application context already exists and should not be overridden");globalThis[me]=new kt(t,await C.getInstance()),this.status.resolveInjected()}static async getInstance(){return(await C.getInstance()).getEnvironment()===ge.Frame?(await this.status.waitInjected(),globalThis[me]):__APPLICATION_CONTEXT_KEY}getAppDefinitionId(){return this.applicationContext.appDefinitionId}getBindings(){return this.applicationContext}getEvents(){return this.events}getPrivateAPI(){return this.environment.getPrivateAPI()}getPrivateApplicationAPI(){let t=this.getAppDefinitionId();if(!t)throw B(k.IncorrectEnvironment,"appDefinitionId is not available");return this.environment.getApplicationAPIs()[t]}};a(kt,"status",new Mt("application"));var q=kt,Ee=class extends y{constructor(e,i){super(e,i,"Auth Strategy Error");a(this,"state",{})}withAppDefinitionId(e){return this.state={...this.state,appDefinitionId:e},this}},qe=g(Ee);function Rn(n,t){let e=Date.now(),i=n?new Date(n).getTime():null;return i&&i-e>t}var xn=30*60*1e3,On=()=>{let n;return{getAuthHeaders:async()=>{let t=await q.getInstance(),e=t.getBindings(),i=t.getPrivateAPI();if(!e.appDefinitionId)throw qe("EmptyAppDefinitionId");return(!n||Rn(n.expires,xn))&&(n=await i.auth.getAccessToken(e.appDefinitionId,await i.info.getMetaSiteId())),n?.token?{headers:{Authorization:n.token}}:(console.error(qe("EmptyAppAuthInstance").withAppDefinitionId(e.appDefinitionId)),{headers:{Authorization:""}})}}},Ve="_EP_TRANSPORT_INIT_KEY";globalThis[Ve]||(typeof importScripts=="function"?yt.exposeAPI(new Nt):mt.exposeAPI(new Tt),globalThis[Ve]=!0);var P=class{constructor(t,e){this.namespace=t,this.shape=e}build(){return be(Object.fromEntries(Object.entries(this.shape).map(([t,e])=>[t,i=>i?.environmentContext&&i?.applicationContext?async(...r)=>{let[s,o]=await Promise.all([i.environmentContext,i.applicationContext]);return e({environmentContext:s,applicationContext:o})(...r)}:async(...r)=>{let[s,o]=await Promise.all([C.getInstance(),q.getInstance()]);return e({environmentContext:s,applicationContext:o})(...r)}])))}},Nn=new P("application",{getPrivateAPI({applicationContext:n}){return async()=>n.getPrivateApplicationAPI()},getPublicAPI({applicationContext:n}){return async t=>n.getPrivateAPI().applicationManager.getPublicApplicationAPI(t)},getAppInstance({applicationContext:n}){return async()=>{let t=n.getPrivateAPI(),e=n.getBindings();return t.info.getAppInstance(e.appDefinitionId)}}}),yi=Nn.build(),Sn=new P("components",{getSelectedComponents({applicationContext:n}){return async()=>{let t=n.getPrivateAPI(),e=await t.components.getSelectedComponents();return Promise.all(e.map(i=>t.components.getComponent(i)))}}}),Dn=Sn.build(),Mn=new P("events",{addEventListener({applicationContext:n}){return async(t,e)=>n.getEvents().addEventListener(t,e)}}),Ai=Mn.build(),jn=new P("info",{getViewMode({applicationContext:n}){return async()=>n.getPrivateAPI().info.getViewMode()},getLanguageCode({applicationContext:n}){return async()=>n.getPrivateAPI().info.getLanguageCode()}}),gi=jn.build(),Je=(n=>(n.UndefinedCompRef="UndefinedCompRef",n))(Je||{}),ve=class extends y{constructor(t,e){super(t,e,"Widget Error")}},kn=g(ve),Xe=async()=>{let t=(await Dn.getSelectedComponents())[0]?.compRef;if(!t)throw kn(Je.UndefinedCompRef);return t},Ln=new P("widget",{getProp({applicationContext:n}){return async t=>{let e=n.getPrivateAPI(),i=await Xe();return e.customElement.getAttribute(i,t)}},setProp({applicationContext:n}){return async(t,e)=>{let i=n.getPrivateAPI(),r=await Xe();await i.customElement.setAttribute(r,t,e)}}}),Ei=Ln.build(),Ge="underline";function Fn(n){let t=n.trim(),e=t.match(/var\((--[\w-]+),\s*(.+)\)/);return e?{variableName:e[1],fallbackValue:e[2]?.trim()??""}:{variableName:void 0,fallbackValue:t}}function Un(n){let t={family:void 0,size:void 0};if(n?.font){let{variableName:e,fallbackValue:i}=Fn(n.font);t.cssVariableName=e;let r=i.match(/(?:(["']).*?\1|\S)+/g)||[];for(let s=0;s<r.length;s++){let o=r[s];switch(o){case"bold":t.bold=!0;break;case"italic":t.italic=!0;break;default:o?.endsWith("px")?t.size=parseInt(o,10):s===r.length-1?t.family=o:t.family=(t.family||"")+" "+o}}}return n?.textDecoration&&(t.underline=n.textDecoration===Ge),t.family=t.family?.trim().replace(/['"]+/g,""),t}function Wn(n){return`${n.cssVariableName?`var(${n.cssVariableName}, `:""}${n.italic?"italic ":""}${n.bold?"bold ":""}${n.size||16}px ${n.family?.split(",").map(t=>`"${t.replace(/['"]+/g,"")}"`).join(",")||"serif"}${n.cssVariableName?")":""}`}function Kn(n){if(!n)return null;let t=n,e=t.match(/var\((--[\w-]+),\s*(.+)\)/);return e?{cssVariableName:e[1],color:e[2]}:{color:t}}function He(n){return n?n.cssVariableName?`var(${n.cssVariableName}, ${n.color})`:n.color:""}var $n={transformFontInternalValue:n=>{if(n){let{theme:t,cssVariableName:e,bold:i,italic:r,underline:s,...o}=n;return{...o,style:{bold:i,italic:r,underline:s},editorKey:e||t||""}}else return{editorKey:"font_7",family:"helvetica-w01-roman",size:16,style:{}}}},Yn=new P("inputs",{selectColor({applicationContext:n}){return async(t,e)=>{let i=n.getPrivateAPI(),r=Kn(t),s=He(r);return await i.inputs.openColorPicker({color:r?.cssVariableName||r?.theme||r?.color},({color:o,theme:p,cssVariableTheme:l})=>{r={color:o,theme:p,cssVariableName:l},s=He(r),e?.onChange?.(s)}),s}},selectFont({applicationContext:n}){return async(t,e)=>{let i=n.getPrivateAPI(),r=Un(t),s=t;return await i.inputs.openFontPickerV2({...e,panelSectionsDefinition:{htmlTag:"hidden"},componentStyle:$n.transformFontInternalValue(r)},(o,p)=>{s={font:Wn(o),textDecoration:o.underline?Ge:void 0},e?.onChange?.(s)}),s}}}),vi=Yn.build(),zn=new P("externalPanels",{getData({applicationContext:n}){return async()=>n.getPrivateAPI().externalPanels.getData()},setData({applicationContext:n}){return async t=>n.getPrivateAPI().externalPanels.setData(t)},getStyle({applicationContext:n}){return async()=>n.getPrivateAPI().externalPanels.getStyle()},setStyle({applicationContext:n}){return async t=>n.getPrivateAPI().externalPanels.setStyle(t)},getTheme({applicationContext:n}){return async()=>n.getPrivateAPI().externalPanels.getTheme()},selectMedia({applicationContext:n}){return async()=>n.getPrivateAPI().externalPanels.selectMedia()},selectLink({applicationContext:n}){return async(...t)=>n.getPrivateAPI().externalPanels.selectLink(...t)},selectColor({applicationContext:n}){return async(...t)=>n.getPrivateAPI().externalPanels.selectColor(...t)},translate({applicationContext:n}){return async(t,e)=>n.getPrivateAPI().externalPanels.translate(t,e)}}),Pi=zn.build(),Bn=()=>{let n=new URLSearchParams(window.location.search);return{environment:{},channel:{observeState:async()=>({disconnect(){}})},environmentContext:C.getInstance(),applicationContext:q.getInstance(),essentials:n.has("essentials")?JSON.parse(n.get("essentials")):{}}},qn=()=>({environment:{},channel:{observeState:async()=>({disconnect(){}})},environmentContext:C.getInstance(),applicationContext:q.getInstance()}),Pe={host:()=>typeof importScripts=="function"?qn():Bn(),auth:On};var Ci=()=>{let n=Pe.host(),t=Pe.auth();Te({auth:t,host:n}).enableContext("module")};export{Ci as enableClient};
8
8
  //# sourceMappingURL=editor.js.map