@vaadin/hilla-frontend 24.7.14 → 24.7.15
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/Authentication.js.map +1 -1
- package/Connect.js.map +1 -1
- package/CookieManager.js.map +1 -1
- package/CsrfUtils.js.map +1 -1
- package/EndpointErrors.js.map +1 -1
- package/FluxConnection.js.map +1 -1
- package/FluxMessages.js.map +1 -1
- package/index.js +1 -1
- package/index.js.map +1 -1
- package/package.json +2 -2
package/Authentication.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"mappings":"AACA,OAAO,uCAAwC;AAC/C,SACE,mBACA,yCACA,4CACA,0CACsB;AAExB,MAAM,kBAAkB;AAExB,SAAS,mCAAmCA,MAAsC;CAChF,MAAM,MAAM,IAAI,YAAY,gBAAgB,MAAM,YAAY;AAC9D,QAAO,kBAAkB,IAAI;AAC9B;AAED,SAAS,0BAA0B;AACjC,OAAM,KACJ,SAAS,KAAK,iBAAiB,oFAA8E,CAC9G,CAAC,QAAQ,CAAC,OAAO,GAAG,QAAQ,CAAC;AAC/B;AAED,SAAS,yBAAyBC,gBAAwC;AACxE,0BAAyB;CACzB,MAAMC,iBAAkC,SAAS,cAAc,OAAO;AACtE,gBAAe,OAAO;AACtB,gBAAe,UAAU,eAAe;AACxC,UAAS,KAAK,YAAY,eAAe;CACzC,MAAMC,YAA6B,SAAS,cAAc,OAAO;AACjE,WAAU,OAAO;AACjB,WAAU,UAAU,eAAe;AACnC,UAAS,KAAK,YAAY,UAAU;AACrC;AAED,MAAM,qCAAqC,CAACH,SAAqC;CAC/E,MAAM,QAAQ,6EAA6E,KAAK,KAAK;AACrG,QAAO,QAAQ,MAAM,KAAK;AAC3B;AAED,eAAe,gCAAgCI,UAAiD;CAC9F,MAAM,eAAe,MAAM,SAAS,MAAM;CAC1C,MAAM,QAAQ,mCAAmC,aAAa;CAC9D,MAAM,sBAAsB,mCAAmC,aAAa;AAC5E,0BAAyB,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C,MAAM,WAAW,MAAM,KAAK,QAAQ;AACpC,MAAI,SAAS,WAAW,KAAK;GAC3B,MAAM,cAAc,MAAM,KAAK,0BAA0B;AACzD,OAAI,YAAY,OAAO;AACrB,kBAAc,QAAQ,QAAQ,IAAI,oBAAoB,YAAY,MAAM;AACxE,WAAO,KAAK,cAAc;GAC3B;EACF;AACD,SAAO;CACR;AACF","names":["body: string","springCsrfInfo: Record<string, string>","headerNameMeta: HTMLMetaElement","tokenMeta: HTMLMetaElement","response: Response","logoutUrl: URL | string","headers: Record<string, string>","url: URL | string","parameters: Record<string, string>","doc: Document","options?: LogoutOptions","url: string","to: string","username: string","password: string","options?: LoginOptions","springCsrfTokenInfo: Record<string, string>","e: unknown","response: Response | undefined","onInvalidSessionCallback: OnInvalidSessionCallback","context: MiddlewareContext","next: MiddlewareNext"],"sources":["/opt/agent/work/1af72d8adc613024/hilla/packages/ts/frontend/src/Authentication.ts"],"sourcesContent":["import type { MiddlewareClass, MiddlewareContext, MiddlewareNext } from './Connect.js';\nimport CookieManager from './CookieManager.js';\nimport {\n getSpringCsrfInfo,\n getSpringCsrfTokenHeadersForAuthRequest,\n getSpringCsrfTokenParametersForAuthRequest,\n VAADIN_CSRF_HEADER,\n} from './CsrfUtils.js';\n\nconst JWT_COOKIE_NAME = 'jwt.headerAndPayload';\n\nfunction getSpringCsrfTokenFromResponseBody(body: string): Record<string, string> {\n const doc = new DOMParser().parseFromString(body, 'text/html');\n return getSpringCsrfInfo(doc);\n}\n\nfunction clearSpringCsrfMetaTags() {\n Array.from(\n document.head.querySelectorAll('meta[name=\"_csrf\"], meta[name=\"_csrf_header\"], meta[name=\"_csrf_parameter\"]'),\n ).forEach((el) => el.remove());\n}\n\nfunction updateSpringCsrfMetaTags(springCsrfInfo: Record<string, string>) {\n clearSpringCsrfMetaTags();\n const headerNameMeta: HTMLMetaElement = document.createElement('meta');\n headerNameMeta.name = '_csrf_header';\n headerNameMeta.content = springCsrfInfo._csrf_header;\n document.head.appendChild(headerNameMeta);\n const tokenMeta: HTMLMetaElement = document.createElement('meta');\n tokenMeta.name = '_csrf';\n tokenMeta.content = springCsrfInfo._csrf;\n document.head.appendChild(tokenMeta);\n}\n\nconst getVaadinCsrfTokenFromResponseBody = (body: string): string | undefined => {\n const match = /window\\.Vaadin = \\{TypeScript: \\{\"csrfToken\":\"([0-9a-zA-Z\\\\-]{36})\"\\}\\};/iu.exec(body);\n return match ? match[1] : undefined;\n};\n\nasync function updateCsrfTokensBasedOnResponse(response: Response): Promise<string | undefined> {\n const responseText = await response.text();\n const token = getVaadinCsrfTokenFromResponseBody(responseText);\n const springCsrfTokenInfo = getSpringCsrfTokenFromResponseBody(responseText);\n updateSpringCsrfMetaTags(springCsrfTokenInfo);\n\n return token;\n}\n\nasync function doFetchLogout(logoutUrl: URL | string, headers: Record<string, string>) {\n const response = await fetch(logoutUrl, { headers, method: 'POST' });\n if (!response.ok) {\n throw new Error(`failed to logout with response ${response.status}`);\n }\n\n await updateCsrfTokensBasedOnResponse(response);\n\n return response;\n}\n\nasync function doFormLogout(url: URL | string, parameters: Record<string, string>): Promise<void> {\n const logoutUrl = typeof url === 'string' ? url : url.toString();\n\n // Create form to send POST request\n const form = document.createElement('form');\n form.setAttribute('method', 'POST');\n form.setAttribute('action', logoutUrl);\n form.style.display = 'none';\n\n // Add data to form as hidden input fields\n for (const [name, value] of Object.entries(parameters)) {\n const input = document.createElement('input');\n input.setAttribute('type', 'hidden');\n input.setAttribute('name', name);\n input.setAttribute('value', value);\n\n form.appendChild(input);\n }\n\n // Append form to page and submit it to perform logout and redirect\n document.body.appendChild(form);\n\n // No code should run after a form submission, as it will navigate away.\n // The promise will reject after a long timeout to avoid executing code after\n // (old user code has a `reload` call that could happen before the form submission).\n return new Promise((_, reject) => {\n setTimeout(() => {\n reject(new Error('Form submission did not navigate away after 10 seconds.'));\n }, 10000);\n form.submit();\n });\n}\n\nasync function doLogout(doc: Document, options?: LogoutOptions): Promise<Response> {\n // performing fetch logout only makes sense if at least one of the 'navigate'\n // or 'onSuccess' is defined, otherwise we can just do a form logout:\n const shouldSubmitFormLogout = !options?.navigate && !options?.onSuccess;\n // this assumes the default Spring Security logout configuration (handler URL)\n const logoutUrl = options?.logoutUrl ?? 'logout';\n if (shouldSubmitFormLogout) {\n const parameters = getSpringCsrfTokenParametersForAuthRequest(doc);\n await doFormLogout(logoutUrl, parameters);\n // This should never be reached, as form submission will navigate away\n return new Response(null, {\n status: 500,\n statusText: 'Form submission did not navigate away.',\n } as ResponseInit);\n }\n const headers = getSpringCsrfTokenHeadersForAuthRequest(doc);\n return await doFetchLogout(logoutUrl, headers);\n}\n\nexport interface LoginResult {\n error: boolean;\n token?: string;\n errorTitle?: string;\n errorMessage?: string;\n redirectUrl?: string;\n defaultUrl?: string;\n}\n\nexport type SuccessCallback = () => Promise<void> | void;\n\nexport type NavigateFunction = (path: string) => void;\n\nexport interface LoginOptions {\n /**\n * The URL for login request, defaults to `/login`.\n */\n loginProcessingUrl?: URL | string;\n\n /**\n * The success callback.\n */\n onSuccess?: SuccessCallback;\n\n /**\n * The navigation callback, called after successful login. The default\n * reloads the page.\n */\n navigate?: NavigateFunction;\n}\n\nexport interface LogoutOptions {\n /**\n * The URL for logout request, defaults to `/logout`.\n */\n logoutUrl?: URL | string;\n\n /**\n * The success callback.\n */\n onSuccess?: SuccessCallback;\n\n /**\n * The navigation callback, called after successful logout. The default\n * reloads the page.\n */\n navigate?: NavigateFunction;\n}\n\nfunction normalizePath(url: string): string {\n // URL with context path\n const effectiveBaseURL = new URL('.', document.baseURI);\n const effectiveBaseURI = effectiveBaseURL.toString();\n\n let normalized = url;\n\n // Strip context path prefix\n if (normalized.startsWith(effectiveBaseURL.pathname)) {\n return `/${normalized.slice(effectiveBaseURL.pathname.length)}`;\n }\n\n // Strip base URI\n normalized = normalized.startsWith(effectiveBaseURI) ? `/${normalized.slice(effectiveBaseURI.length)}` : normalized;\n\n return normalized;\n}\n\n/**\n * Navigates to the provided path using page reload.\n *\n * @param to - navigation target path\n */\nfunction navigateWithPageReload(to: string) {\n // Consider absolute path to be within application context\n const url = to.startsWith('/') ? new URL(`.${to}`, document.baseURI) : to;\n window.location.replace(url);\n}\n\n/**\n * A helper method for Spring Security based form login.\n * @param username - username\n * @param password - password\n * @param options - defines additional options, e.g, the loginProcessingUrl etc.\n */\nexport async function login(username: string, password: string, options?: LoginOptions): Promise<LoginResult> {\n try {\n const data = new FormData();\n data.append('username', username);\n data.append('password', password);\n\n const loginProcessingUrl = options?.loginProcessingUrl ?? 'login';\n const headers = getSpringCsrfTokenHeadersForAuthRequest(document);\n headers.source = 'typescript';\n const response = await fetch(loginProcessingUrl, {\n body: data,\n headers,\n method: 'POST',\n });\n\n // This code assumes that a VaadinSavedRequestAwareAuthenticationSuccessHandler is used on the server side,\n // setting these header values based on the \"source=typescript\" header set above\n\n const result = response.headers.get('Result');\n const savedUrl = response.headers.get('Saved-url') ?? undefined;\n const defaultUrl = response.headers.get('Default-url') ?? undefined;\n const loginSuccessful = response.ok && result === 'success';\n\n if (loginSuccessful) {\n const vaadinCsrfToken = response.headers.get('Vaadin-CSRF') ?? undefined;\n\n const springCsrfHeader = response.headers.get('Spring-CSRF-header') ?? undefined;\n const springCsrfToken = response.headers.get('Spring-CSRF-token') ?? undefined;\n if (springCsrfHeader && springCsrfToken) {\n const springCsrfTokenInfo: Record<string, string> = {};\n springCsrfTokenInfo._csrf = springCsrfToken;\n // eslint-disable-next-line camelcase\n springCsrfTokenInfo._csrf_header = springCsrfHeader;\n updateSpringCsrfMetaTags(springCsrfTokenInfo);\n }\n\n if (options?.onSuccess) {\n await options.onSuccess();\n }\n\n const url = savedUrl ?? defaultUrl ?? document.baseURI;\n const toPath = normalizePath(url);\n const navigate = options?.navigate ?? navigateWithPageReload;\n navigate(toPath);\n\n return {\n defaultUrl,\n error: false,\n redirectUrl: savedUrl,\n token: vaadinCsrfToken,\n };\n }\n return {\n error: true,\n errorMessage: 'Check that you have entered the correct username and password and try again.',\n errorTitle: 'Incorrect username or password.',\n };\n } catch (e: unknown) {\n if (e instanceof Error) {\n return {\n error: true,\n errorMessage: e.message,\n errorTitle: e.name,\n };\n }\n\n throw e;\n }\n}\n\n/**\n * A helper method for Spring Security based form logout\n * @param options - defines additional options, e.g, the logoutUrl.\n */\nexport async function logout(options?: LogoutOptions): Promise<void> {\n let response: Response | undefined;\n try {\n response = await doLogout(document, options);\n } catch {\n try {\n const noCacheResponse = await fetch('?nocache');\n const responseText = await noCacheResponse.text();\n const doc = new DOMParser().parseFromString(responseText, 'text/html');\n response = await doLogout(doc, options);\n } catch (error) {\n // clear the token if the call fails\n clearSpringCsrfMetaTags();\n throw error;\n }\n } finally {\n CookieManager.remove(JWT_COOKIE_NAME);\n if (response && response.ok && response.redirected) {\n if (options?.onSuccess) {\n await options.onSuccess();\n }\n const toPath = normalizePath(response.url);\n const navigate = options?.navigate ?? navigateWithPageReload;\n navigate(toPath);\n }\n }\n}\n\n/**\n * It defines what to do when it detects a session is invalid. E.g.,\n * show a login view.\n * It takes an <code>EndpointCallContinue</code> parameter, which can be\n * used to continue the endpoint call.\n */\nexport type OnInvalidSessionCallback = () => Promise<LoginResult>;\n\n/**\n * A helper class for handling invalid sessions during an endpoint call.\n * E.g., you can use this to show user a login page when the session has\n * expired.\n */\nexport class InvalidSessionMiddleware implements MiddlewareClass {\n private readonly onInvalidSessionCallback: OnInvalidSessionCallback;\n\n constructor(onInvalidSessionCallback: OnInvalidSessionCallback) {\n this.onInvalidSessionCallback = onInvalidSessionCallback;\n }\n\n async invoke(context: MiddlewareContext, next: MiddlewareNext): Promise<Response> {\n const clonedContext = { ...context };\n clonedContext.request = context.request.clone();\n const response = await next(context);\n if (response.status === 401) {\n const loginResult = await this.onInvalidSessionCallback();\n if (loginResult.token) {\n clonedContext.request.headers.set(VAADIN_CSRF_HEADER, loginResult.token);\n return next(clonedContext) as Promise<Response>;\n }\n }\n return response;\n }\n}\n"],"version":3}
|
|
1
|
+
{"mappings":"AACA,OAAO,uCAAwC;AA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,YAAY,EAAE;GACf;EACF;AAED,QAAM;CACP;AACF;;;;;AAMD,OAAO,eAAe,OAAOP,SAAwC;CACnE,IAAIQ;AACJ,KAAI;AACF,aAAW,MAAM,SAAS,UAAU,QAAQ;CAC7C,QAAO;AACN,MAAI;GACF,MAAM,kBAAkB,MAAM,MAAM,WAAW;GAC/C,MAAM,eAAe,MAAM,gBAAgB,MAAM;GACjD,MAAM,MAAM,IAAI,YAAY,gBAAgB,cAAc,YAAY;AACtE,cAAW,MAAM,SAAS,KAAK,QAAQ;EACxC,SAAQ,OAAO;AAEd,4BAAyB;AACzB,SAAM;EACP;CACF,UAAS;AACR,gBAAc,OAAO,gBAAgB;AACrC,MAAI,YAAY,SAAS,MAAM,SAAS,YAAY;AAClD,OAAI,SAAS,WAAW;AACtB,UAAM,QAAQ,WAAW;GAC1B;GACD,MAAM,SAAS,cAAc,SAAS,IAAI;GAC1C,MAAM,WAAW,SAAS,YAAY;AACtC,YAAS,OAAO;EACjB;CACF;AACF;;;;;;AAeD,OAAO,MAAM,yBAAoD;CAC/D,AAAiB;CAEjB,YAAYC,0BAAoD;AAC9D,OAAK,2BAA2B;CACjC;CAED,MAAM,OAAOC,SAA4BC,MAAyC;EAChF,MAAM,gBAAgB,EAAE,GAAG,QAAS;AACpC,gBAAc,UAAU,QAAQ,QAAQ,OAAO;EAC/C,MAAM,WAAW,MAAM,KAAK,QAAQ;AACpC,MAAI,SAAS,WAAW,KAAK;GAC3B,MAAM,cAAc,MAAM,KAAK,0BAA0B;AACzD,OAAI,YAAY,OAAO;AACrB,kBAAc,QAAQ,QAAQ,IAAI,oBAAoB,YAAY,MAAM;AACxE,WAAO,KAAK,cAAc;GAC3B;EACF;AACD,SAAO;CACR;AACF","names":["body: string","springCsrfInfo: Record<string, string>","headerNameMeta: HTMLMetaElement","tokenMeta: HTMLMetaElement","response: Response","logoutUrl: URL | string","headers: Record<string, string>","url: URL | string","parameters: Record<string, string>","doc: Document","options?: LogoutOptions","url: string","to: string","username: string","password: string","options?: LoginOptions","springCsrfTokenInfo: Record<string, string>","e: unknown","response: Response | undefined","onInvalidSessionCallback: OnInvalidSessionCallback","context: MiddlewareContext","next: MiddlewareNext"],"sources":["/opt/agent/work/649c11185a3798db/packages/ts/frontend/src/Authentication.ts"],"sourcesContent":["import type { MiddlewareClass, MiddlewareContext, MiddlewareNext } from './Connect.js';\nimport CookieManager from './CookieManager.js';\nimport {\n getSpringCsrfInfo,\n getSpringCsrfTokenHeadersForAuthRequest,\n getSpringCsrfTokenParametersForAuthRequest,\n VAADIN_CSRF_HEADER,\n} from './CsrfUtils.js';\n\nconst JWT_COOKIE_NAME = 'jwt.headerAndPayload';\n\nfunction getSpringCsrfTokenFromResponseBody(body: string): Record<string, string> {\n const doc = new DOMParser().parseFromString(body, 'text/html');\n return getSpringCsrfInfo(doc);\n}\n\nfunction clearSpringCsrfMetaTags() {\n Array.from(\n document.head.querySelectorAll('meta[name=\"_csrf\"], meta[name=\"_csrf_header\"], meta[name=\"_csrf_parameter\"]'),\n ).forEach((el) => el.remove());\n}\n\nfunction updateSpringCsrfMetaTags(springCsrfInfo: Record<string, string>) {\n clearSpringCsrfMetaTags();\n const headerNameMeta: HTMLMetaElement = document.createElement('meta');\n headerNameMeta.name = '_csrf_header';\n headerNameMeta.content = springCsrfInfo._csrf_header;\n document.head.appendChild(headerNameMeta);\n const tokenMeta: HTMLMetaElement = document.createElement('meta');\n tokenMeta.name = '_csrf';\n tokenMeta.content = springCsrfInfo._csrf;\n document.head.appendChild(tokenMeta);\n}\n\nconst getVaadinCsrfTokenFromResponseBody = (body: string): string | undefined => {\n const match = /window\\.Vaadin = \\{TypeScript: \\{\"csrfToken\":\"([0-9a-zA-Z\\\\-]{36})\"\\}\\};/iu.exec(body);\n return match ? match[1] : undefined;\n};\n\nasync function updateCsrfTokensBasedOnResponse(response: Response): Promise<string | undefined> {\n const responseText = await response.text();\n const token = getVaadinCsrfTokenFromResponseBody(responseText);\n const springCsrfTokenInfo = getSpringCsrfTokenFromResponseBody(responseText);\n updateSpringCsrfMetaTags(springCsrfTokenInfo);\n\n return token;\n}\n\nasync function doFetchLogout(logoutUrl: URL | string, headers: Record<string, string>) {\n const response = await fetch(logoutUrl, { headers, method: 'POST' });\n if (!response.ok) {\n throw new Error(`failed to logout with response ${response.status}`);\n }\n\n await updateCsrfTokensBasedOnResponse(response);\n\n return response;\n}\n\nasync function doFormLogout(url: URL | string, parameters: Record<string, string>): Promise<void> {\n const logoutUrl = typeof url === 'string' ? url : url.toString();\n\n // Create form to send POST request\n const form = document.createElement('form');\n form.setAttribute('method', 'POST');\n form.setAttribute('action', logoutUrl);\n form.style.display = 'none';\n\n // Add data to form as hidden input fields\n for (const [name, value] of Object.entries(parameters)) {\n const input = document.createElement('input');\n input.setAttribute('type', 'hidden');\n input.setAttribute('name', name);\n input.setAttribute('value', value);\n\n form.appendChild(input);\n }\n\n // Append form to page and submit it to perform logout and redirect\n document.body.appendChild(form);\n\n // No code should run after a form submission, as it will navigate away.\n // The promise will reject after a long timeout to avoid executing code after\n // (old user code has a `reload` call that could happen before the form submission).\n return new Promise((_, reject) => {\n setTimeout(() => {\n reject(new Error('Form submission did not navigate away after 10 seconds.'));\n }, 10000);\n form.submit();\n });\n}\n\nasync function doLogout(doc: Document, options?: LogoutOptions): Promise<Response> {\n // performing fetch logout only makes sense if at least one of the 'navigate'\n // or 'onSuccess' is defined, otherwise we can just do a form logout:\n const shouldSubmitFormLogout = !options?.navigate && !options?.onSuccess;\n // this assumes the default Spring Security logout configuration (handler URL)\n const logoutUrl = options?.logoutUrl ?? 'logout';\n if (shouldSubmitFormLogout) {\n const parameters = getSpringCsrfTokenParametersForAuthRequest(doc);\n await doFormLogout(logoutUrl, parameters);\n // This should never be reached, as form submission will navigate away\n return new Response(null, {\n status: 500,\n statusText: 'Form submission did not navigate away.',\n });\n }\n const headers = getSpringCsrfTokenHeadersForAuthRequest(doc);\n return await doFetchLogout(logoutUrl, headers);\n}\n\nexport interface LoginResult {\n error: boolean;\n token?: string;\n errorTitle?: string;\n errorMessage?: string;\n redirectUrl?: string;\n defaultUrl?: string;\n}\n\nexport type SuccessCallback = () => Promise<void> | void;\n\nexport type NavigateFunction = (path: string) => void;\n\nexport interface LoginOptions {\n /**\n * The URL for login request, defaults to `/login`.\n */\n loginProcessingUrl?: URL | string;\n\n /**\n * The success callback.\n */\n onSuccess?: SuccessCallback;\n\n /**\n * The navigation callback, called after successful login. The default\n * reloads the page.\n */\n navigate?: NavigateFunction;\n}\n\nexport interface LogoutOptions {\n /**\n * The URL for logout request, defaults to `/logout`.\n */\n logoutUrl?: URL | string;\n\n /**\n * The success callback.\n */\n onSuccess?: SuccessCallback;\n\n /**\n * The navigation callback, called after successful logout. The default\n * reloads the page.\n */\n navigate?: NavigateFunction;\n}\n\nfunction normalizePath(url: string): string {\n // URL with context path\n const effectiveBaseURL = new URL('.', document.baseURI);\n const effectiveBaseURI = effectiveBaseURL.toString();\n\n let normalized = url;\n\n // Strip context path prefix\n if (normalized.startsWith(effectiveBaseURL.pathname)) {\n return `/${normalized.slice(effectiveBaseURL.pathname.length)}`;\n }\n\n // Strip base URI\n normalized = normalized.startsWith(effectiveBaseURI) ? `/${normalized.slice(effectiveBaseURI.length)}` : normalized;\n\n return normalized;\n}\n\n/**\n * Navigates to the provided path using page reload.\n *\n * @param to - navigation target path\n */\nfunction navigateWithPageReload(to: string) {\n // Consider absolute path to be within application context\n const url = to.startsWith('/') ? new URL(`.${to}`, document.baseURI) : to;\n window.location.replace(url);\n}\n\n/**\n * A helper method for Spring Security based form login.\n * @param username - username\n * @param password - password\n * @param options - defines additional options, e.g, the loginProcessingUrl etc.\n */\nexport async function login(username: string, password: string, options?: LoginOptions): Promise<LoginResult> {\n try {\n const data = new FormData();\n data.append('username', username);\n data.append('password', password);\n\n const loginProcessingUrl = options?.loginProcessingUrl ?? 'login';\n const headers = getSpringCsrfTokenHeadersForAuthRequest(document);\n headers.source = 'typescript';\n const response = await fetch(loginProcessingUrl, {\n body: data,\n headers,\n method: 'POST',\n });\n\n // This code assumes that a VaadinSavedRequestAwareAuthenticationSuccessHandler is used on the server side,\n // setting these header values based on the \"source=typescript\" header set above\n\n const result = response.headers.get('Result');\n const savedUrl = response.headers.get('Saved-url') ?? undefined;\n const defaultUrl = response.headers.get('Default-url') ?? undefined;\n const loginSuccessful = response.ok && result === 'success';\n\n if (loginSuccessful) {\n const vaadinCsrfToken = response.headers.get('Vaadin-CSRF') ?? undefined;\n\n const springCsrfHeader = response.headers.get('Spring-CSRF-header') ?? undefined;\n const springCsrfToken = response.headers.get('Spring-CSRF-token') ?? undefined;\n if (springCsrfHeader && springCsrfToken) {\n const springCsrfTokenInfo: Record<string, string> = {};\n springCsrfTokenInfo._csrf = springCsrfToken;\n // eslint-disable-next-line camelcase\n springCsrfTokenInfo._csrf_header = springCsrfHeader;\n updateSpringCsrfMetaTags(springCsrfTokenInfo);\n }\n\n if (options?.onSuccess) {\n await options.onSuccess();\n }\n\n const url = savedUrl ?? defaultUrl ?? document.baseURI;\n const toPath = normalizePath(url);\n const navigate = options?.navigate ?? navigateWithPageReload;\n navigate(toPath);\n\n return {\n defaultUrl,\n error: false,\n redirectUrl: savedUrl,\n token: vaadinCsrfToken,\n };\n }\n return {\n error: true,\n errorMessage: 'Check that you have entered the correct username and password and try again.',\n errorTitle: 'Incorrect username or password.',\n };\n } catch (e: unknown) {\n if (e instanceof Error) {\n return {\n error: true,\n errorMessage: e.message,\n errorTitle: e.name,\n };\n }\n\n throw e;\n }\n}\n\n/**\n * A helper method for Spring Security based form logout\n * @param options - defines additional options, e.g, the logoutUrl.\n */\nexport async function logout(options?: LogoutOptions): Promise<void> {\n let response: Response | undefined;\n try {\n response = await doLogout(document, options);\n } catch {\n try {\n const noCacheResponse = await fetch('?nocache');\n const responseText = await noCacheResponse.text();\n const doc = new DOMParser().parseFromString(responseText, 'text/html');\n response = await doLogout(doc, options);\n } catch (error) {\n // clear the token if the call fails\n clearSpringCsrfMetaTags();\n throw error;\n }\n } finally {\n CookieManager.remove(JWT_COOKIE_NAME);\n if (response && response.ok && response.redirected) {\n if (options?.onSuccess) {\n await options.onSuccess();\n }\n const toPath = normalizePath(response.url);\n const navigate = options?.navigate ?? navigateWithPageReload;\n navigate(toPath);\n }\n }\n}\n\n/**\n * It defines what to do when it detects a session is invalid. E.g.,\n * show a login view.\n * It takes an <code>EndpointCallContinue</code> parameter, which can be\n * used to continue the endpoint call.\n */\nexport type OnInvalidSessionCallback = () => Promise<LoginResult>;\n\n/**\n * A helper class for handling invalid sessions during an endpoint call.\n * E.g., you can use this to show user a login page when the session has\n * expired.\n */\nexport class InvalidSessionMiddleware implements MiddlewareClass {\n private readonly onInvalidSessionCallback: OnInvalidSessionCallback;\n\n constructor(onInvalidSessionCallback: OnInvalidSessionCallback) {\n this.onInvalidSessionCallback = onInvalidSessionCallback;\n }\n\n async invoke(context: MiddlewareContext, next: MiddlewareNext): Promise<Response> {\n const clonedContext = { ...context };\n clonedContext.request = context.request.clone();\n const response = await next(context);\n if (response.status === 401) {\n const loginResult = await this.onInvalidSessionCallback();\n if (loginResult.token) {\n clonedContext.request.headers.set(VAADIN_CSRF_HEADER, loginResult.token);\n return next(clonedContext);\n }\n }\n return response;\n }\n}\n"],"version":3}
|
package/Connect.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"mappings":"AACA,SAAS,qBAAqB,gDAAiD;AAC/E,SAAS,6DAA8D;AACvE,SACE,eACA,uBACA,yBACA,wBACA,sDAE2B;AAC7B,SAEE,2CAE2B;AAG7B,MAAM,OAAO;AAEb,KAAK,WAAW,CAAE;AAClB,KAAK,OAAO,kBAAkB,CAAE;AAChC,KAAK,OAAO,cAAc,KAAK,EAC7B,IAAI,WACL,EAAC;AAEF,OAAO,MAAM,iBAAiB;;;;;AAgD9B,MAAM,qBAAqB,OAAOA,aAAsC;AACtE,MAAK,SAAS,IAAI;EAChB,MAAM,YAAY,MAAM,SAAS,MAAM;EACvC,IAAIC;AACJ,MAAI;AACF,eAAY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aD,UAAUP,UAAkBC,QAAgBS,QAAiC;AAC3E,SAAO,KAAK,eAAe,UAAU,UAAU,QAAQ,SAAS,OAAO,OAAO,OAAO,GAAG,CAAE,EAAC;CAC5F;AACF","names":["response: Response","errorJson: ConnectExceptionData | null","obj: Record<string, unknown>","prop: unknown","path: string","options: ConnectClientOptions","#fluxConnection","endpoint: string","method: string","params?: Record<string, unknown>","init?: EndpointRequestInit","headers: Record<string, string>","initialContext: MiddlewareContext","context: MiddlewareContext","next: MiddlewareNext","value: any","error: unknown","params?: any"],"sources":["/opt/agent/work/1af72d8adc613024/hilla/packages/ts/frontend/src/Connect.ts"],"sourcesContent":["import type { ReactiveControllerHost } from '@lit/reactive-element';\nimport { ConnectionIndicator, ConnectionState } from '@vaadin/common-frontend';\nimport { getCsrfTokenHeadersForEndpointRequest } from './CsrfUtils.js';\nimport {\n EndpointError,\n EndpointResponseError,\n EndpointValidationError,\n ForbiddenResponseError,\n UnauthorizedResponseError,\n type ValidationErrorData,\n} from './EndpointErrors.js';\nimport {\n type ActionOnLostSubscription,\n FluxConnection,\n type FluxSubscriptionStateChangeEvent,\n} from './FluxConnection.js';\nimport type { VaadinGlobal } from './types.js';\n\nconst $wnd = globalThis as VaadinGlobal;\n\n$wnd.Vaadin ??= {};\n$wnd.Vaadin.registrations ??= [];\n$wnd.Vaadin.registrations.push({\n is: 'endpoint',\n});\n\nexport const BODY_PART_NAME = 'hilla_body_part';\n\nexport type MaybePromise<T> = Promise<T> | T;\n\n/**\n * Represents the connection to and endpoint returning a subscription rather than a value.\n */\nexport interface Subscription<T> {\n /** Cancels the subscription. No values are made available after calling this. */\n cancel(): void;\n\n /*\n * Binds to the given context (element) so that when the context is deactivated (element detached), the subscription is closed.\n */\n context(context: ReactiveControllerHost): Subscription<T>;\n\n /** Called when the subscription has completed. No values are made available after calling this. */\n onComplete(callback: () => void): Subscription<T>;\n\n /** Called when an exception occured in the subscription. */\n onError(callback: (message: string) => void): Subscription<T>;\n\n /** Called when a new value is available. */\n onNext(callback: (value: T) => void): Subscription<T>;\n\n /** Called when the subscription state changes. */\n onConnectionStateChange(callback: (event: FluxSubscriptionStateChangeEvent) => void): Subscription<T>;\n\n /**\n * Called when the connection is restored, but there's no longer a valid subscription. If the callback returns\n * `ActionOnLostSubscription.RESUBSCRIBE`, the subscription will be re-established by connecting to the same\n * server method again. If the callback returns `ActionOnLostSubscription.REMOVE`, the subscription will be\n * forgotten. This is also the default behavior if the callback is not set or if it returns `undefined`.\n */\n onSubscriptionLost(callback: () => ActionOnLostSubscription | void): Subscription<T>;\n}\n\ninterface ConnectExceptionData {\n detail?: any;\n message: string;\n type: string;\n validationErrorData?: ValidationErrorData[];\n}\n\n/**\n * Throws a TypeError if the response is not 200 OK.\n * @param response - The response to assert.\n */\nconst assertResponseIsOk = async (response: Response): Promise<void> => {\n if (!response.ok) {\n const errorText = await response.text();\n let errorJson: ConnectExceptionData | null;\n try {\n errorJson = JSON.parse(errorText);\n } catch {\n // not a json\n errorJson = null;\n }\n\n const message =\n errorJson?.message ??\n (errorText.length > 0\n ? errorText\n : `expected \"200 OK\" response, but got ${response.status} ${response.statusText}`);\n const type = errorJson?.type;\n\n if (errorJson?.validationErrorData) {\n throw new EndpointValidationError(message, errorJson.validationErrorData, type);\n }\n\n if (type) {\n throw new EndpointError(message, type, errorJson?.detail);\n }\n\n switch (response.status) {\n case 401:\n throw new UnauthorizedResponseError(message, response);\n case 403:\n throw new ForbiddenResponseError(message, response);\n default:\n throw new EndpointResponseError(message, response);\n }\n }\n};\n\n/**\n * The `ConnectClient` constructor options.\n */\nexport interface ConnectClientOptions {\n /**\n * The `middlewares` property value.\n */\n middlewares?: Middleware[];\n /**\n * The `prefix` property value.\n */\n prefix?: string;\n /**\n * The Atmosphere options for the FluxConnection.\n */\n atmosphereOptions?: Partial<Atmosphere.Request>;\n}\n\nexport interface EndpointCallMetaInfo {\n /**\n * The endpoint name.\n */\n endpoint: string;\n\n /**\n * The method name to call on in the endpoint class.\n */\n method: string;\n\n /**\n * Optional object with method call arguments.\n */\n params?: Record<string, unknown>;\n}\n\n/**\n * An object with the call arguments and the related Request instance.\n * See also {@link ConnectClient.call | the call() method in ConnectClient}.\n */\nexport interface MiddlewareContext extends EndpointCallMetaInfo {\n /**\n * The Fetch API Request object reflecting the other properties.\n */\n request: Request;\n}\n\n/**\n * An async middleware callback that invokes the next middleware in the chain\n * or makes the actual request.\n * @param context - The information about the call and request\n */\nexport type MiddlewareNext = (context: MiddlewareContext) => MaybePromise<Response>;\n\n/**\n * An interface that allows defining a middleware as a class.\n */\nexport interface MiddlewareClass {\n /**\n * @param context - The information about the call and request\n * @param next - Invokes the next in the call chain\n */\n invoke(context: MiddlewareContext, next: MiddlewareNext): MaybePromise<Response>;\n}\n\n/**\n * An async callback function that can intercept the request and response\n * of a call.\n */\nexport type MiddlewareFunction = (context: MiddlewareContext, next: MiddlewareNext) => MaybePromise<Response>;\n\n/**\n * An async callback that can intercept the request and response\n * of a call, could be either a function or a class.\n */\nexport type Middleware = MiddlewareClass | MiddlewareFunction;\n\nfunction isFlowLoaded(): boolean {\n return $wnd.Vaadin?.Flow?.clients?.TypeScript !== undefined;\n}\n\n/**\n * Extracts file objects from the object that is used to build the request body.\n *\n * @param obj - The object to extract files from.\n * @returns A tuple with the object without files and a map of files.\n */\nfunction extractFiles(obj: Record<string, unknown>): [Record<string, unknown>, Map<string, File>] {\n const fileMap = new Map<string, File>();\n\n function recursiveExtract(prop: unknown, path: string): unknown {\n if (prop !== null && typeof prop === 'object') {\n if (prop instanceof File) {\n fileMap.set(path, prop);\n return null;\n }\n if (Array.isArray(prop)) {\n return prop.map((item, index) => recursiveExtract(item, `${path}/${index}`));\n }\n return Object.entries(prop).reduce<Record<string, unknown>>((acc, [key, value]) => {\n const newPath = `${path}/${key}`;\n if (value instanceof File) {\n fileMap.set(newPath, value);\n } else {\n acc[key] = recursiveExtract(value, newPath);\n }\n return acc;\n }, {});\n }\n return prop;\n }\n\n return [recursiveExtract(obj, '') as Record<string, unknown>, fileMap];\n}\n\n/**\n * A list of parameters supported by {@link ConnectClient.call | the call() method in ConnectClient}.\n */\nexport interface EndpointRequestInit {\n /**\n * An AbortSignal to set request's signal.\n */\n signal?: AbortSignal | null;\n /**\n * If set to true, the connection state will not be updated during the request.\n */\n mute?: boolean;\n}\n\n/**\n * A low-level network calling utility. It stores\n * a prefix and facilitates remote calls to endpoint class methods\n * on the Hilla backend.\n *\n * Example usage:\n *\n * ```js\n * const client = new ConnectClient();\n * const responseData = await client.call('MyEndpoint', 'myMethod');\n * ```\n *\n * ### Prefix\n *\n * The client supports an `prefix` constructor option:\n * ```js\n * const client = new ConnectClient({prefix: '/my-connect-prefix'});\n * ```\n *\n * The default prefix is '/connect'.\n *\n */\nexport class ConnectClient {\n /**\n * The array of middlewares that are invoked during a call.\n */\n middlewares: Middleware[] = [];\n /**\n * The Hilla endpoint prefix\n */\n prefix = '/connect';\n /**\n * The Atmosphere options for the FluxConnection.\n */\n atmosphereOptions: Partial<Atmosphere.Request> = {};\n\n #fluxConnection?: FluxConnection;\n\n /**\n * @param options - Constructor options.\n */\n constructor(options: ConnectClientOptions = {}) {\n if (options.prefix) {\n this.prefix = options.prefix;\n }\n\n if (options.middlewares) {\n this.middlewares = options.middlewares;\n }\n\n if (options.atmosphereOptions) {\n this.atmosphereOptions = options.atmosphereOptions;\n }\n\n // add connection indicator to DOM\n ConnectionIndicator.create();\n\n // Listen to browser online/offline events and update the loading indicator accordingly.\n // Note: if Flow.ts is loaded, it instead handles the state transitions.\n addEventListener('online', () => {\n if (!isFlowLoaded() && $wnd.Vaadin?.connectionState) {\n $wnd.Vaadin.connectionState.state = ConnectionState.CONNECTED;\n }\n });\n addEventListener('offline', () => {\n if (!isFlowLoaded() && $wnd.Vaadin?.connectionState) {\n $wnd.Vaadin.connectionState.state = ConnectionState.CONNECTION_LOST;\n }\n });\n }\n\n /**\n * Gets a representation of the underlying persistent network connection used for subscribing to Flux type endpoint\n * methods.\n */\n get fluxConnection(): FluxConnection {\n if (!this.#fluxConnection) {\n this.#fluxConnection = new FluxConnection(this.prefix, this.atmosphereOptions);\n }\n return this.#fluxConnection;\n }\n\n /**\n * Calls the given endpoint method defined using the endpoint and method\n * parameters with the parameters given as params.\n * Asynchronously returns the parsed JSON response data.\n *\n * @param endpoint - Endpoint name.\n * @param method - Method name to call in the endpoint class.\n * @param params - Optional parameters to pass to the method.\n * @param init - Optional parameters for the request\n * @returns Decoded JSON response data.\n */\n async call(\n endpoint: string,\n method: string,\n params?: Record<string, unknown>,\n init?: EndpointRequestInit,\n ): Promise<any> {\n if (arguments.length < 2) {\n throw new TypeError(`2 arguments required, but got only ${arguments.length}`);\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n const csrfHeaders = globalThis.document ? getCsrfTokenHeadersForEndpointRequest(globalThis.document) : {};\n const headers: Record<string, string> = {\n Accept: 'application/json',\n ...csrfHeaders,\n };\n\n const [paramsWithoutFiles, files] = extractFiles(params ?? {});\n let body;\n\n if (files.size > 0) {\n // in this case params is not undefined, otherwise there would be no files\n body = new FormData();\n body.append(\n BODY_PART_NAME,\n JSON.stringify(paramsWithoutFiles, (_, value) => (value === undefined ? null : value)),\n );\n\n for (const [path, file] of files) {\n body.append(path, file);\n }\n } else {\n headers['Content-Type'] = 'application/json';\n if (params) {\n body = JSON.stringify(params, (_, value) => (value === undefined ? null : value));\n }\n }\n\n const request = new Request(`${this.prefix}/${endpoint}/${method}`, {\n body, // automatically sets Content-Type header\n headers,\n method: 'POST',\n });\n\n // The middleware `context`, includes the call arguments and the request\n // constructed from them\n const initialContext: MiddlewareContext = {\n endpoint,\n method,\n params,\n request,\n };\n\n // The internal middleware to assert and parse the response. The internal\n // response handling should come last after the other middlewares are done\n // with processing the response. That is why this middleware is first\n // in the final middlewares array.\n async function responseHandlerMiddleware(context: MiddlewareContext, next: MiddlewareNext): Promise<Response> {\n const response = await next(context);\n await assertResponseIsOk(response);\n const text = await response.text();\n return JSON.parse(text, (_, value: any) => (value === null ? undefined : value));\n }\n\n // The actual fetch call itself is expressed as a middleware\n // chain item for our convenience. Always having an ending of the chain\n // this way makes the folding down below more concise.\n async function fetchNext(context: MiddlewareContext) {\n // if the request is not \"muted\", notify the connection state about changes\n const connectionState = init?.mute ? undefined : $wnd.Vaadin?.connectionState;\n connectionState?.loadingStarted();\n try {\n const response = await fetch(context.request, { signal: init?.signal });\n connectionState?.loadingFinished();\n return response;\n } catch (error: unknown) {\n // don't bother about connections aborted by purpose\n if (error instanceof Error && error.name === 'AbortError') {\n connectionState?.loadingFinished();\n } else {\n connectionState?.loadingFailed();\n }\n throw error;\n }\n }\n\n // Assemble the final middlewares array from internal\n // and external middlewares\n const middlewares = [responseHandlerMiddleware as Middleware, ...this.middlewares];\n\n // Fold the final middlewares array into a single function\n const chain = middlewares.reduceRight(\n (next: MiddlewareNext, middleware) =>\n // Compose and return the new chain step, that takes the context and\n // invokes the current middleware with the context and the further chain\n // as the next argument\n async (context) => {\n if (typeof middleware === 'function') {\n return middleware(context, next);\n }\n return middleware.invoke(context, next);\n },\n // Initialize reduceRight the accumulator with `fetchNext`\n fetchNext,\n );\n\n // Invoke all the folded async middlewares and return\n return chain(initialContext);\n }\n\n /**\n * Subscribes to the given method defined using the endpoint and method\n * parameters with the parameters given as params. The method must return a\n * compatible type such as a Flux.\n * Returns a subscription that is used to fetch values as they become available.\n *\n * @param endpoint - Endpoint name.\n * @param method - Method name to call in the endpoint class.\n * @param params - Optional parameters to pass to the method.\n * @returns A subscription used to handles values as they become available.\n */\n subscribe(endpoint: string, method: string, params?: any): Subscription<any> {\n return this.fluxConnection.subscribe(endpoint, method, params ? Object.values(params) : []);\n }\n}\n"],"version":3}
|
|
1
|
+
{"mappings":"AACA,SAAS,qBAAqB,gDAAiD;AAC/E,SAAS,6DAA8D;AACvE,SACE,eACA,uBACA,yBACA,wBACA,sDAE2B;AAC7B,SAEE,2CAE2B;AAG7B,MAAM,OAAO;AAEb,KAAK,WAAW,CAAE;AAClB,KAAK,OAA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AK,WAAY;EAGlF,MAAM,QAAQ,YAAY;GACxB,CAACF,MAAsB,eAIrB,OAAO,YAAY;AACjB,eAAW,eAAe,YAAY;AACpC,YAAO,WAAW,SAAS,KAAK;IACjC;AACD,WAAO,WAAW,OAAO,SAAS,KAAK;GACxC;;GAEH;CACD;AAGD,SAAO,MAAM,eAAe;CAC7B;;;;;;;;;;;;CAaD,UAAUP,UAAkBC,QAAgBS,QAAiC;AAC3E,SAAO,KAAK,eAAe,UAAU,UAAU,QAAQ,SAAS,OAAO,OAAO,OAAO,GAAG,CAAE,EAAC;CAC5F;AACF","names":["response: Response","errorJson: ConnectExceptionData | null","obj: Record<string, unknown>","prop: unknown","path: string","options: ConnectClientOptions","#fluxConnection","endpoint: string","method: string","params?: Record<string, unknown>","init?: EndpointRequestInit","headers: Record<string, string>","initialContext: MiddlewareContext","context: MiddlewareContext","next: MiddlewareNext","value: any","error: unknown","params?: any"],"sources":["/opt/agent/work/649c11185a3798db/packages/ts/frontend/src/Connect.ts"],"sourcesContent":["import type { ReactiveControllerHost } from '@lit/reactive-element';\nimport { ConnectionIndicator, ConnectionState } from '@vaadin/common-frontend';\nimport { getCsrfTokenHeadersForEndpointRequest } from './CsrfUtils.js';\nimport {\n EndpointError,\n EndpointResponseError,\n EndpointValidationError,\n ForbiddenResponseError,\n UnauthorizedResponseError,\n type ValidationErrorData,\n} from './EndpointErrors.js';\nimport {\n type ActionOnLostSubscription,\n FluxConnection,\n type FluxSubscriptionStateChangeEvent,\n} from './FluxConnection.js';\nimport type { VaadinGlobal } from './types.js';\n\nconst $wnd = globalThis as VaadinGlobal;\n\n$wnd.Vaadin ??= {};\n$wnd.Vaadin.registrations ??= [];\n$wnd.Vaadin.registrations.push({\n is: 'endpoint',\n});\n\nexport const BODY_PART_NAME = 'hilla_body_part';\n\nexport type MaybePromise<T> = Promise<T> | T;\n\n/**\n * Represents the connection to and endpoint returning a subscription rather than a value.\n */\nexport interface Subscription<T> {\n /** Cancels the subscription. No values are made available after calling this. */\n cancel(): void;\n\n /*\n * Binds to the given context (element) so that when the context is deactivated (element detached), the subscription is closed.\n */\n context(context: ReactiveControllerHost): Subscription<T>;\n\n /** Called when the subscription has completed. No values are made available after calling this. */\n onComplete(callback: () => void): Subscription<T>;\n\n /** Called when an exception occured in the subscription. */\n onError(callback: (message: string) => void): Subscription<T>;\n\n /** Called when a new value is available. */\n onNext(callback: (value: T) => void): Subscription<T>;\n\n /** Called when the subscription state changes. */\n onConnectionStateChange(callback: (event: FluxSubscriptionStateChangeEvent) => void): Subscription<T>;\n\n /**\n * Called when the connection is restored, but there's no longer a valid subscription. If the callback returns\n * `ActionOnLostSubscription.RESUBSCRIBE`, the subscription will be re-established by connecting to the same\n * server method again. If the callback returns `ActionOnLostSubscription.REMOVE`, the subscription will be\n * forgotten. This is also the default behavior if the callback is not set or if it returns `undefined`.\n */\n onSubscriptionLost(callback: () => ActionOnLostSubscription | void): Subscription<T>;\n}\n\ninterface ConnectExceptionData {\n detail?: any;\n message: string;\n type: string;\n validationErrorData?: ValidationErrorData[];\n}\n\n/**\n * Throws a TypeError if the response is not 200 OK.\n * @param response - The response to assert.\n */\nconst assertResponseIsOk = async (response: Response): Promise<void> => {\n if (!response.ok) {\n const errorText = await response.text();\n let errorJson: ConnectExceptionData | null;\n try {\n errorJson = JSON.parse(errorText);\n } catch {\n // not a json\n errorJson = null;\n }\n\n const message =\n errorJson?.message ??\n (errorText.length > 0\n ? errorText\n : `expected \"200 OK\" response, but got ${response.status} ${response.statusText}`);\n const type = errorJson?.type;\n\n if (errorJson?.validationErrorData) {\n throw new EndpointValidationError(message, errorJson.validationErrorData, type);\n }\n\n if (type) {\n throw new EndpointError(message, type, errorJson?.detail);\n }\n\n switch (response.status) {\n case 401:\n throw new UnauthorizedResponseError(message, response);\n case 403:\n throw new ForbiddenResponseError(message, response);\n default:\n throw new EndpointResponseError(message, response);\n }\n }\n};\n\n/**\n * The `ConnectClient` constructor options.\n */\nexport interface ConnectClientOptions {\n /**\n * The `middlewares` property value.\n */\n middlewares?: Middleware[];\n /**\n * The `prefix` property value.\n */\n prefix?: string;\n /**\n * The Atmosphere options for the FluxConnection.\n */\n atmosphereOptions?: Partial<Atmosphere.Request>;\n}\n\nexport interface EndpointCallMetaInfo {\n /**\n * The endpoint name.\n */\n endpoint: string;\n\n /**\n * The method name to call on in the endpoint class.\n */\n method: string;\n\n /**\n * Optional object with method call arguments.\n */\n params?: Record<string, unknown>;\n}\n\n/**\n * An object with the call arguments and the related Request instance.\n * See also {@link ConnectClient.call | the call() method in ConnectClient}.\n */\nexport interface MiddlewareContext extends EndpointCallMetaInfo {\n /**\n * The Fetch API Request object reflecting the other properties.\n */\n request: Request;\n}\n\n/**\n * An async middleware callback that invokes the next middleware in the chain\n * or makes the actual request.\n * @param context - The information about the call and request\n */\nexport type MiddlewareNext = (context: MiddlewareContext) => MaybePromise<Response>;\n\n/**\n * An interface that allows defining a middleware as a class.\n */\nexport interface MiddlewareClass {\n /**\n * @param context - The information about the call and request\n * @param next - Invokes the next in the call chain\n */\n invoke(context: MiddlewareContext, next: MiddlewareNext): MaybePromise<Response>;\n}\n\n/**\n * An async callback function that can intercept the request and response\n * of a call.\n */\nexport type MiddlewareFunction = (context: MiddlewareContext, next: MiddlewareNext) => MaybePromise<Response>;\n\n/**\n * An async callback that can intercept the request and response\n * of a call, could be either a function or a class.\n */\nexport type Middleware = MiddlewareClass | MiddlewareFunction;\n\nfunction isFlowLoaded(): boolean {\n return $wnd.Vaadin?.Flow?.clients?.TypeScript !== undefined;\n}\n\n/**\n * Extracts file objects from the object that is used to build the request body.\n *\n * @param obj - The object to extract files from.\n * @returns A tuple with the object without files and a map of files.\n */\nfunction extractFiles(obj: Record<string, unknown>): [Record<string, unknown>, Map<string, File>] {\n const fileMap = new Map<string, File>();\n\n function recursiveExtract(prop: unknown, path: string): unknown {\n if (prop !== null && typeof prop === 'object') {\n if (prop instanceof File) {\n fileMap.set(path, prop);\n return null;\n }\n if (Array.isArray(prop)) {\n return prop.map((item, index) => recursiveExtract(item, `${path}/${index}`));\n }\n return Object.entries(prop).reduce<Record<string, unknown>>((acc, [key, value]) => {\n const newPath = `${path}/${key}`;\n if (value instanceof File) {\n fileMap.set(newPath, value);\n } else {\n acc[key] = recursiveExtract(value, newPath);\n }\n return acc;\n }, {});\n }\n return prop;\n }\n\n return [recursiveExtract(obj, '') as Record<string, unknown>, fileMap];\n}\n\n/**\n * A list of parameters supported by {@link ConnectClient.call | the call() method in ConnectClient}.\n */\nexport interface EndpointRequestInit {\n /**\n * An AbortSignal to set request's signal.\n */\n signal?: AbortSignal | null;\n /**\n * If set to true, the connection state will not be updated during the request.\n */\n mute?: boolean;\n}\n\n/**\n * A low-level network calling utility. It stores\n * a prefix and facilitates remote calls to endpoint class methods\n * on the Hilla backend.\n *\n * Example usage:\n *\n * ```js\n * const client = new ConnectClient();\n * const responseData = await client.call('MyEndpoint', 'myMethod');\n * ```\n *\n * ### Prefix\n *\n * The client supports an `prefix` constructor option:\n * ```js\n * const client = new ConnectClient({prefix: '/my-connect-prefix'});\n * ```\n *\n * The default prefix is '/connect'.\n *\n */\nexport class ConnectClient {\n /**\n * The array of middlewares that are invoked during a call.\n */\n middlewares: Middleware[] = [];\n /**\n * The Hilla endpoint prefix\n */\n prefix = '/connect';\n /**\n * The Atmosphere options for the FluxConnection.\n */\n atmosphereOptions: Partial<Atmosphere.Request> = {};\n\n #fluxConnection?: FluxConnection;\n\n /**\n * @param options - Constructor options.\n */\n constructor(options: ConnectClientOptions = {}) {\n if (options.prefix) {\n this.prefix = options.prefix;\n }\n\n if (options.middlewares) {\n this.middlewares = options.middlewares;\n }\n\n if (options.atmosphereOptions) {\n this.atmosphereOptions = options.atmosphereOptions;\n }\n\n // add connection indicator to DOM\n ConnectionIndicator.create();\n\n // Listen to browser online/offline events and update the loading indicator accordingly.\n // Note: if Flow.ts is loaded, it instead handles the state transitions.\n addEventListener('online', () => {\n if (!isFlowLoaded() && $wnd.Vaadin?.connectionState) {\n $wnd.Vaadin.connectionState.state = ConnectionState.CONNECTED;\n }\n });\n addEventListener('offline', () => {\n if (!isFlowLoaded() && $wnd.Vaadin?.connectionState) {\n $wnd.Vaadin.connectionState.state = ConnectionState.CONNECTION_LOST;\n }\n });\n }\n\n /**\n * Gets a representation of the underlying persistent network connection used for subscribing to Flux type endpoint\n * methods.\n */\n get fluxConnection(): FluxConnection {\n if (!this.#fluxConnection) {\n this.#fluxConnection = new FluxConnection(this.prefix, this.atmosphereOptions);\n }\n return this.#fluxConnection;\n }\n\n /**\n * Calls the given endpoint method defined using the endpoint and method\n * parameters with the parameters given as params.\n * Asynchronously returns the parsed JSON response data.\n *\n * @param endpoint - Endpoint name.\n * @param method - Method name to call in the endpoint class.\n * @param params - Optional parameters to pass to the method.\n * @param init - Optional parameters for the request\n * @returns Decoded JSON response data.\n */\n async call(\n endpoint: string,\n method: string,\n params?: Record<string, unknown>,\n init?: EndpointRequestInit,\n ): Promise<any> {\n if (arguments.length < 2) {\n throw new TypeError(`2 arguments required, but got only ${arguments.length}`);\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n const csrfHeaders = globalThis.document ? getCsrfTokenHeadersForEndpointRequest(globalThis.document) : {};\n const headers: Record<string, string> = {\n Accept: 'application/json',\n ...csrfHeaders,\n };\n\n const [paramsWithoutFiles, files] = extractFiles(params ?? {});\n let body;\n\n if (files.size > 0) {\n // in this case params is not undefined, otherwise there would be no files\n body = new FormData();\n body.append(\n BODY_PART_NAME,\n JSON.stringify(paramsWithoutFiles, (_, value) => (value === undefined ? null : value)),\n );\n\n for (const [path, file] of files) {\n body.append(path, file);\n }\n } else {\n headers['Content-Type'] = 'application/json';\n if (params) {\n body = JSON.stringify(params, (_, value) => (value === undefined ? null : value));\n }\n }\n\n const request = new Request(`${this.prefix}/${endpoint}/${method}`, {\n body, // automatically sets Content-Type header\n headers,\n method: 'POST',\n });\n\n // The middleware `context`, includes the call arguments and the request\n // constructed from them\n const initialContext: MiddlewareContext = {\n endpoint,\n method,\n params,\n request,\n };\n\n // The internal middleware to assert and parse the response. The internal\n // response handling should come last after the other middlewares are done\n // with processing the response. That is why this middleware is first\n // in the final middlewares array.\n async function responseHandlerMiddleware(context: MiddlewareContext, next: MiddlewareNext): Promise<Response> {\n const response = await next(context);\n await assertResponseIsOk(response);\n const text = await response.text();\n return JSON.parse(text, (_, value: any) => (value === null ? undefined : value));\n }\n\n // The actual fetch call itself is expressed as a middleware\n // chain item for our convenience. Always having an ending of the chain\n // this way makes the folding down below more concise.\n async function fetchNext(context: MiddlewareContext) {\n // if the request is not \"muted\", notify the connection state about changes\n const connectionState = init?.mute ? undefined : $wnd.Vaadin?.connectionState;\n connectionState?.loadingStarted();\n try {\n const response = await fetch(context.request, { signal: init?.signal });\n connectionState?.loadingFinished();\n return response;\n } catch (error: unknown) {\n // don't bother about connections aborted by purpose\n if (error instanceof Error && error.name === 'AbortError') {\n connectionState?.loadingFinished();\n } else {\n connectionState?.loadingFailed();\n }\n throw error;\n }\n }\n\n // Assemble the final middlewares array from internal\n // and external middlewares\n const middlewares = [responseHandlerMiddleware as Middleware, ...this.middlewares];\n\n // Fold the final middlewares array into a single function\n const chain = middlewares.reduceRight(\n (next: MiddlewareNext, middleware) =>\n // Compose and return the new chain step, that takes the context and\n // invokes the current middleware with the context and the further chain\n // as the next argument\n async (context) => {\n if (typeof middleware === 'function') {\n return middleware(context, next);\n }\n return middleware.invoke(context, next);\n },\n // Initialize reduceRight the accumulator with `fetchNext`\n fetchNext,\n );\n\n // Invoke all the folded async middlewares and return\n return chain(initialContext);\n }\n\n /**\n * Subscribes to the given method defined using the endpoint and method\n * parameters with the parameters given as params. The method must return a\n * compatible type such as a Flux.\n * Returns a subscription that is used to fetch values as they become available.\n *\n * @param endpoint - Endpoint name.\n * @param method - Method name to call in the endpoint class.\n * @param params - Optional parameters to pass to the method.\n * @returns A subscription used to handles values as they become available.\n */\n subscribe(endpoint: string, method: string, params?: any): Subscription<any> {\n return this.fluxConnection.subscribe(endpoint, method, params ? Object.values(params) : []);\n }\n}\n"],"version":3}
|
package/CookieManager.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"mappings":"AAAA,OAAO,wBAAyB;AAEhC,OAAO,SAAS,cAAc,EAAE,UAAe,EAAU;AACvD,QAAO,SAAS,SAAS,KAAK,SAAS,SAAS,IAAI,GAAG,SAAS,MAAM,IAAI,EAAE,GAAG;AAChF;AAED,MAAMA,gBAAgC,QAAQ,eAAe,EAE3D,MAAM,cAAc,IAAI,IAAI,WAAW,UAAU,WAAW,KAAK,CAClE,EAAC;AAEF,eAAe","names":["CookieManager: typeof Cookies"],"sources":["/opt/agent/work/
|
|
1
|
+
{"mappings":"AAAA,OAAO,wBAAyB;AAEhC,OAAO,SAAS,cAAc,EAAE,UAAe,EAAU;AACvD,QAAO,SAAS,SAAS,KAAK,SAAS,SAAS,IAAI,GAAG,SAAS,MAAM,IAAI,EAAE,GAAG;AAChF;AAED,MAAMA,gBAAgC,QAAQ,eAAe,EAE3D,MAAM,cAAc,IAAI,IAAI,WAAW,UAAU,WAAW,KAAK,CAClE,EAAC;AAEF,eAAe","names":["CookieManager: typeof Cookies"],"sources":["/opt/agent/work/649c11185a3798db/packages/ts/frontend/src/CookieManager.ts"],"sourcesContent":["import Cookies from 'js-cookie';\n\nexport function calculatePath({ pathname }: URL): string {\n return pathname.length > 1 && pathname.endsWith('/') ? pathname.slice(0, -1) : pathname;\n}\n\nconst CookieManager: typeof Cookies = Cookies.withAttributes({\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n path: calculatePath(new URL(globalThis.document?.baseURI ?? '/')),\n});\n\nexport default CookieManager;\n"],"version":3}
|
package/CsrfUtils.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"mappings":"AAAA,OAAO,uCAAwC;;AAG/C,OAAO,MAAM,qBAAqB;;AAElC,OAAO,MAAM,0BAA0B;;AAEvC,OAAO,MAAM,0BAA0B;AAEvC,SAAS,0BAA0BA,KAAeC,S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OAAO,SAAS,2CAA2CF,KAAuC;CAChG,MAAM,WAAW,kBAAkB,IAAI;CACvC,MAAMG,aAAqC,CAAE;AAC7C,KAAI,SAAS,SAAS,SAAS,iBAAiB;AAC9C,aAAW,SAAS,mBAAmB,SAAS;CACjD;AACD,QAAO;AACR","names":["doc: Document","metaTag: string","headers: Record<string, string>","parameters: Record<string, string>"],"sources":["/opt/agent/work/649c11185a3798db/packages/ts/frontend/src/CsrfUtils.ts"],"sourcesContent":["import CookieManager from './CookieManager.js';\n\n/** @internal */\nexport const VAADIN_CSRF_HEADER = 'X-CSRF-Token';\n/** @internal */\nexport const VAADIN_CSRF_COOKIE_NAME = 'csrfToken';\n/** @internal */\nexport const SPRING_CSRF_COOKIE_NAME = 'XSRF-TOKEN';\n\nfunction extractContentFromMetaTag(doc: Document, metaTag: string): string | undefined {\n const element = doc.head.querySelector<HTMLMetaElement>(`meta[name=\"${metaTag}\"]`);\n if (element) {\n const value = element.content;\n if (value && value.toLowerCase() !== 'undefined') {\n return value;\n }\n }\n return undefined;\n}\n\nexport function getSpringCsrfInfo(doc: Document): Record<string, string> {\n let csrf = CookieManager.get(SPRING_CSRF_COOKIE_NAME);\n if (!csrf || csrf.length === 0) {\n csrf = extractContentFromMetaTag(doc, '_csrf');\n }\n const csrfHeader = extractContentFromMetaTag(doc, '_csrf_header');\n\n const headers: Record<string, string> = {};\n if (csrf && csrfHeader) {\n headers._csrf = csrf;\n // eslint-disable-next-line camelcase\n headers._csrf_header = csrfHeader;\n\n const csrfParameter = extractContentFromMetaTag(doc, '_csrf_parameter');\n if (csrfParameter) {\n // eslint-disable-next-line camelcase\n headers._csrf_parameter = csrfParameter;\n }\n }\n return headers;\n}\n\n/** @internal */\nexport function getSpringCsrfTokenHeadersForAuthRequest(doc: Document): Record<string, string> {\n const csrfInfo = getSpringCsrfInfo(doc);\n const headers: Record<string, string> = {};\n if (csrfInfo._csrf && csrfInfo._csrf_header) {\n headers[csrfInfo._csrf_header] = csrfInfo._csrf;\n }\n return headers;\n}\n\n/** @internal */\nexport function getCsrfTokenHeadersForEndpointRequest(doc: Document): Record<string, string> {\n const headers: Record<string, string> = {};\n\n const csrfInfo = getSpringCsrfInfo(doc);\n if (csrfInfo._csrf && csrfInfo._csrf_header) {\n headers[csrfInfo._csrf_header] = csrfInfo._csrf;\n } else {\n headers[VAADIN_CSRF_HEADER] = CookieManager.get(VAADIN_CSRF_COOKIE_NAME) ?? '';\n }\n\n return headers;\n}\n\n/** @internal */\nexport function getSpringCsrfTokenParametersForAuthRequest(doc: Document): Record<string, string> {\n const csrfInfo = getSpringCsrfInfo(doc);\n const parameters: Record<string, string> = {};\n if (csrfInfo._csrf && csrfInfo._csrf_parameter) {\n parameters[csrfInfo._csrf_parameter] = csrfInfo._csrf;\n }\n return parameters;\n}\n"],"version":3}
|
package/EndpointErrors.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"mappings":";;;;AAIA,OAAO,MAAM,sBAAsB,MAAM;;;;;CAKvC;;;;CAIA;;;;;;CAOA,YAAYA,SAAiBC,MAAeC,QAAkB;AAC5D,QAAM,QAAQ;AACd,OAAK,OAAO;AACZ,OAAK,SAAS;CACf;AACF;;;;;;AAOD,OAAO,MAAM,gCAAgC,cAAc;;;;CAIzD;;;;CAIA;;;;;;CAOA,YAAYF,SAAiBG,qBAA4CF,MAAe;AACtF,QAAM,SAAS,MAAM,oBAAoB;AACzC,OAAK,yBAAyB;AAC9B,OAAK,SAAS;AACd,OAAK,sBAAsB;CAC5B;AACF;;;;AAKD,OAAO,MAAM,8BAA8B,cAAc;;;;CAIvD;;;;;CAMA,YAAYD,SAAiBI,UAAoB;AAC/C,QAAM,SAAS,yBAAyB,SAAS;AACjD,OAAK,WAAW;CACjB;;;;CAKD,IAAI,SAAiB;AACnB,SAAO,KAAK,SAAS;CACtB;AACF;AAED,OAAO,MAAM,kCAAkC,sBAAsB;CACnE,YAAYJ,SAAiBI,UAAoB;AAC/C,QAAM,SAAS,SAAS;AACxB,OAAK,OAAO;CACb;AACF;AAED,OAAO,MAAM,+BAA+B,sBAAsB;CAChE,YAAYJ,SAAiBI,UAAoB;AAC/C,QAAM,SAAS,SAAS;AACxB,OAAK,OAAO;CACb;AACF;;;;AAKD,OAAO,MAAM,oBAAoB;;;;CAI/B;;;;CAKA;;;;CAKA;;;;;;CAOA,YAAYJ,SAAiBK,eAAwBC,kBAA2B;AAC9E,OAAK,UAAU;AACf,OAAK,gBAAgB;AACrB,OAAK,mBAAmB;CACzB;AACF","names":["message: string","type?: string","detail?: unknown","validationErrorData: ValidationErrorData[]","response: Response","parameterName?: string","validatorMessage?: string"],"sources":["/opt/agent/work/
|
|
1
|
+
{"mappings":";;;;AAIA,OAAO,MAAM,sBAAsB,MAAM;;;;;CAKvC;;;;CAIA;;;;;;CAOA,YAAYA,SAAiBC,MAAeC,QAAkB;AAC5D,QAAM,QAAQ;AACd,OAAK,OAAO;AACZ,OAAK,SAAS;CACf;AACF;;;;;;AAOD,OAAO,MAAM,gCAAgC,cAAc;;;;CAIzD;;;;CAIA;;;;;;CAOA,YAAYF,SAAiBG,qBAA4CF,MAAe;AACtF,QAAM,SAAS,MAAM,oBAAoB;AACzC,OAAK,yBAAyB;AAC9B,OAAK,SAAS;AACd,OAAK,sBAAsB;CAC5B;AACF;;;;AAKD,OAAO,MAAM,8BAA8B,cAAc;;;;CAIvD;;;;;CAMA,YAAYD,SAAiBI,UAAoB;AAC/C,QAAM,SAAS,yBAAyB,SAAS;AACjD,OAAK,WAAW;CACjB;;;;CAKD,IAAI,SAAiB;AACnB,SAAO,KAAK,SAAS;CACtB;AACF;AAED,OAAO,MAAM,kCAAkC,sBAAsB;CACnE,YAAYJ,SAAiBI,UAAoB;AAC/C,QAAM,SAAS,SAAS;AACxB,OAAK,OAAO;CACb;AACF;AAED,OAAO,MAAM,+BAA+B,sBAAsB;CAChE,YAAYJ,SAAiBI,UAAoB;AAC/C,QAAM,SAAS,SAAS;AACxB,OAAK,OAAO;CACb;AACF;;;;AAKD,OAAO,MAAM,oBAAoB;;;;CAI/B;;;;CAKA;;;;CAKA;;;;;;CAOA,YAAYJ,SAAiBK,eAAwBC,kBAA2B;AAC9E,OAAK,UAAU;AACf,OAAK,gBAAgB;AACrB,OAAK,mBAAmB;CACzB;AACF","names":["message: string","type?: string","detail?: unknown","validationErrorData: ValidationErrorData[]","response: Response","parameterName?: string","validatorMessage?: string"],"sources":["/opt/agent/work/649c11185a3798db/packages/ts/frontend/src/EndpointErrors.ts"],"sourcesContent":["/**\n * An exception that gets thrown when the Vaadin backend responds\n * with not ok status.\n */\nexport class EndpointError extends Error {\n /**\n * The optional detail object, containing additional information sent\n * from the backend\n */\n detail?: unknown;\n /**\n * The optional name of the exception that was thrown on a backend\n */\n type?: string;\n\n /**\n * @param message - the `message` property value\n * @param type - the `type` property value\n * @param detail - the `detail` property value\n */\n constructor(message: string, type?: string, detail?: unknown) {\n super(message);\n this.type = type;\n this.detail = detail;\n }\n}\n\n/**\n * An exception that gets thrown if Vaadin endpoint responds\n * with non-ok status and provides additional info\n * on the validation errors occurred.\n */\nexport class EndpointValidationError extends EndpointError {\n /**\n * An array of the validation errors.\n */\n validationErrorData: ValidationErrorData[];\n /**\n * An original validation error message.\n */\n validationErrorMessage: string;\n\n /**\n * @param message - the `message` property value\n * @param validationErrorData - the `validationErrorData` property value\n * @param type - the `type` property value\n */\n constructor(message: string, validationErrorData: ValidationErrorData[], type?: string) {\n super(message, type, validationErrorData);\n this.validationErrorMessage = message;\n this.detail = null;\n this.validationErrorData = validationErrorData;\n }\n}\n\n/**\n * An exception that gets thrown for unexpected HTTP response.\n */\nexport class EndpointResponseError extends EndpointError {\n /**\n * The optional response object, containing the HTTP response error\n */\n response: Response;\n\n /**\n * @param message - the `message` property value\n * @param response - the `response` property value\n */\n constructor(message: string, response: Response) {\n super(message, 'EndpointResponseError', response);\n this.response = response;\n }\n\n /**\n * Convenience property to get the HTTP code status directly\n */\n get status(): number {\n return this.response.status;\n }\n}\n\nexport class UnauthorizedResponseError extends EndpointResponseError {\n constructor(message: string, response: Response) {\n super(message, response);\n this.type = 'UnauthorizedResponseError';\n }\n}\n\nexport class ForbiddenResponseError extends EndpointResponseError {\n constructor(message: string, response: Response) {\n super(message, response);\n this.type = 'ForbiddenResponseError';\n }\n}\n\n/**\n * An object, containing all data for the particular validation error.\n */\nexport class ValidationErrorData {\n /**\n * The validation error message.\n */\n message: string;\n\n /**\n * The parameter name that caused the validation error.\n */\n parameterName?: string;\n\n /**\n * Validator original message\n */\n validatorMessage?: string;\n\n /**\n * @param message - The `message` property value\n * @param parameterName - The `parameterName` property value\n * @param validatorMessage - The `validatorMessage` property value\n */\n constructor(message: string, parameterName?: string, validatorMessage?: string) {\n this.message = message;\n this.parameterName = parameterName;\n this.validatorMessage = validatorMessage;\n }\n}\n"],"version":3}
|
package/FluxConnection.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"mappings":"AACA,OAAO,+BAAgC;AAEvC,SAAS,6DAA8D;AACvE,SACE,0CAIyB;AAE3B,OAAO,IAAK,wBAAL;AACL;AACA;AACA;;AACD;;;;AAiBD,OAAO,IAAK,8DAAL;;;;AAIL;;;;AAIA;;AACD;;;;AAKD,OAAO,IAAK,wDAAL;;;;AAIL;;;;AAIA;;;;AAIA;;AACD;;;;AAiBD,OAAO,MAAM,uBAAuB,YAAY;CAC9C,QAAe,MAAM;CACrB,YAAY;CACZ,AAASA,iBAAiB,IAAI;CAC9B,UAAU;CACV,AAASC,uBAAuB,IAAI;CACpC,AAASC,oBAAoB,IAAI;CACjC,AAASC,mBAAmB,IAAI;CAChC,AAASC,0BAA0B,IAAI;CACvC,AAASC,yBAAyB,IAAI;CACtC,mBAAoC,CAAE;CACtC;CAEA,YAAYC,eAAuBC,mBAAiD;AAClF,SAAO;AACP,OAAKC,kBAAkB,cAAc,QAAQ,aAAa,GAAG,EAAE,qBAAqB,CAAE,EAAC;CACxF;CAED,0BAA0B;AACxB,MAAI,KAAK,WAAW;AAClB,QAAK,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,eAAe,OAAO,GAAG;CAC/B;CAED,MAAMmC,SAAwB;AAC5B,MAAI,KAAK,UAAU,MAAM,UAAU;AACjC,QAAKC,iBAAiB,KAAK,QAAQ;EACpC,OAAM;AACL,QAAKP,SAAS,OAAO,KAAK,UAAU,QAAQ,CAAC;EAC9C;CACF;CAED,uBAAuB;AACrB,OAAKO,iBAAiB,QAAQ,CAAC,QAAQ,KAAKzB,MAAM,IAAI,CAAC;AACvD,OAAKyB,mBAAmB,CAAE;CAC3B;AACF","names":["#endpointInfos","#onCompleteCallbacks","#onErrorCallbacks","#onNextCallbacks","#onStateChangeCallbacks","#statusOfSubscriptions","connectPrefix: string","atmosphereOptions?: Partial<Atmosphere.Request>","#connectWebsocket","toBeRemoved: string[]","#setSubscriptionConnState","#send","#removeSubscription","endpointName: string","methodName: string","parameters?: unknown[]","id: string","#nextId","msg: ServerConnectMessage","hillaSubscription: Subscription<any>","closeMessage: ServerCloseMessage","context: ReactiveControllerHost","callback: () => void","callback: (message: string) => void","callback: (value: any) => void","callback: () => ActionOnLostSubscription | void","callback: (event: FluxSubscriptionStateChangeEvent) => void","prefix: string","atmosphereOptions: Partial<Atmosphere.Request>","#socket","#handleMessage","#resubscribeIfWasClosed","#sendPendingMessages","state: FluxSubscriptionState","message: unknown","message: ServerMessage","#pendingMessages"],"sources":["/opt/agent/work/1af72d8adc613024/hilla/packages/ts/frontend/src/FluxConnection.ts"],"sourcesContent":["import type { ReactiveControllerHost } from '@lit/reactive-element';\nimport atmosphere from 'atmosphere.js';\nimport type { Subscription } from './Connect.js';\nimport { getCsrfTokenHeadersForEndpointRequest } from './CsrfUtils.js';\nimport {\n isClientMessage,\n type ServerCloseMessage,\n type ServerConnectMessage,\n type ServerMessage,\n} from './FluxMessages.js';\n\nexport enum State {\n ACTIVE = 'active',\n INACTIVE = 'inactive',\n RECONNECTING = 'reconnecting',\n}\n\ntype ActiveEvent = CustomEvent<{ active: boolean }>;\ninterface EventMap {\n 'state-changed': ActiveEvent;\n}\n\ntype ListenerType<T extends keyof EventMap> =\n | ((this: FluxConnection, ev: EventMap[T]) => any)\n | {\n handleEvent(ev: EventMap[T]): void;\n }\n | null;\n\n/**\n * Possible options for dealing with lost subscriptions after a websocket is reopened.\n */\nexport enum ActionOnLostSubscription {\n /**\n * The subscription should be resubscribed using the same server method and parameters.\n */\n RESUBSCRIBE = 'resubscribe',\n /**\n * The subscription should be removed.\n */\n REMOVE = 'remove',\n}\n\n/**\n * Possible states of a flux subscription.\n */\nexport enum FluxSubscriptionState {\n /**\n * The subscription is not connected and is trying to connect.\n */\n CONNECTING = 'connecting',\n /**\n * The subscription is connected and receiving updates.\n */\n CONNECTED = 'connected',\n /**\n * The subscription is closed and is not trying to reconnect.\n */\n CLOSED = 'closed',\n}\n\n/**\n * Event wrapper for flux subscription connection state change callback\n */\nexport type FluxSubscriptionStateChangeEvent = CustomEvent<{ state: FluxSubscriptionState }>;\n\ntype EndpointInfo = {\n endpointName: string;\n methodName: string;\n params: unknown[] | undefined;\n reconnect?(): ActionOnLostSubscription | void;\n};\n\n/**\n * A representation of the underlying persistent network connection used for subscribing to Flux type endpoint methods.\n */\nexport class FluxConnection extends EventTarget {\n state: State = State.INACTIVE;\n wasClosed = false;\n readonly #endpointInfos = new Map<string, EndpointInfo>();\n #nextId = 0;\n readonly #onCompleteCallbacks = new Map<string, () => void>();\n readonly #onErrorCallbacks = new Map<string, (message: string) => void>();\n readonly #onNextCallbacks = new Map<string, (value: any) => void>();\n readonly #onStateChangeCallbacks = new Map<string, (event: FluxSubscriptionStateChangeEvent) => void>();\n readonly #statusOfSubscriptions = new Map<string, FluxSubscriptionState>();\n #pendingMessages: ServerMessage[] = [];\n #socket?: Atmosphere.Request;\n\n constructor(connectPrefix: string, atmosphereOptions?: Partial<Atmosphere.Request>) {\n super();\n this.#connectWebsocket(connectPrefix.replace(/connect$/u, ''), atmosphereOptions ?? {});\n }\n\n #resubscribeIfWasClosed() {\n if (this.wasClosed) {\n this.wasClosed = false;\n const toBeRemoved: string[] = [];\n this.#endpointInfos.forEach((endpointInfo, id) => {\n if (endpointInfo.reconnect?.() === ActionOnLostSubscription.RESUBSCRIBE) {\n this.#setSubscriptionConnState(id, FluxSubscriptionState.CONNECTING);\n this.#send({\n '@type': 'subscribe',\n endpointName: endpointInfo.endpointName,\n id,\n methodName: endpointInfo.methodName,\n params: endpointInfo.params,\n });\n } else {\n toBeRemoved.push(id);\n }\n });\n toBeRemoved.forEach((id) => this.#removeSubscription(id));\n }\n }\n\n /**\n * Subscribes to the flux returned by the given endpoint name + method name using the given parameters.\n *\n * @param endpointName - the endpoint to connect to\n * @param methodName - the method in the endpoint to connect to\n * @param parameters - the parameters to use\n * @returns a subscription\n */\n subscribe(endpointName: string, methodName: string, parameters?: unknown[]): Subscription<any> {\n const id: string = this.#nextId.toString();\n this.#nextId += 1;\n const params = parameters ?? [];\n\n const msg: ServerConnectMessage = { '@type': 'subscribe', endpointName, id, methodName, params };\n this.#send(msg);\n this.#endpointInfos.set(id, { endpointName, methodName, params });\n this.#setSubscriptionConnState(id, FluxSubscriptionState.CONNECTING);\n const hillaSubscription: Subscription<any> = {\n cancel: () => {\n if (!this.#endpointInfos.has(id)) {\n // Subscription already closed or canceled\n return;\n }\n\n const closeMessage: ServerCloseMessage = { '@type': 'unsubscribe', id };\n this.#send(closeMessage);\n this.#removeSubscription(id);\n },\n context(context: ReactiveControllerHost): Subscription<any> {\n context.addController({\n hostDisconnected() {\n hillaSubscription.cancel();\n },\n });\n return hillaSubscription;\n },\n onComplete: (callback: () => void): Subscription<any> => {\n this.#onCompleteCallbacks.set(id, callback);\n return hillaSubscription;\n },\n onError: (callback: (message: string) => void): Subscription<any> => {\n this.#onErrorCallbacks.set(id, callback);\n return hillaSubscription;\n },\n onNext: (callback: (value: any) => void): Subscription<any> => {\n this.#onNextCallbacks.set(id, callback);\n return hillaSubscription;\n },\n onSubscriptionLost: (callback: () => ActionOnLostSubscription | void): Subscription<any> => {\n if (this.#endpointInfos.has(id)) {\n this.#endpointInfos.get(id)!.reconnect = callback;\n } else {\n console.warn(`\"onReconnect\" value not set for subscription \"${id}\" because it was already canceled`);\n }\n return hillaSubscription;\n },\n onConnectionStateChange: (callback: (event: FluxSubscriptionStateChangeEvent) => void): Subscription<any> => {\n this.#onStateChangeCallbacks.set(id, callback);\n callback(\n new CustomEvent('subscription-state-change', { detail: { state: this.#statusOfSubscriptions.get(id)! } }),\n );\n return hillaSubscription;\n },\n };\n return hillaSubscription;\n }\n\n #connectWebsocket(prefix: string, atmosphereOptions: Partial<Atmosphere.Request>) {\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n const extraHeaders = globalThis.document ? getCsrfTokenHeadersForEndpointRequest(globalThis.document) : {};\n const pushUrl = 'HILLA/push';\n const url = prefix.length === 0 ? pushUrl : (prefix.endsWith('/') ? prefix : `${prefix}/`) + pushUrl;\n this.#socket = atmosphere.subscribe?.({\n contentType: 'application/json; charset=UTF-8',\n enableProtocol: true,\n transport: 'websocket',\n fallbackTransport: 'websocket',\n headers: extraHeaders,\n maxReconnectOnClose: 10000000,\n reconnectInterval: 5000,\n timeout: -1,\n trackMessageLength: true,\n url,\n onClose: () => {\n this.wasClosed = true;\n if (this.state !== State.INACTIVE) {\n this.state = State.INACTIVE;\n this.dispatchEvent(new CustomEvent('state-changed', { detail: { active: false } }));\n }\n },\n onError: (response) => {\n // eslint-disable-next-line no-console\n console.error('error in push communication', response);\n },\n onMessage: (response) => {\n if (response.responseBody) {\n this.#handleMessage(JSON.parse(response.responseBody));\n }\n },\n onMessagePublished: (response) => {\n if (response?.responseBody) {\n this.#handleMessage(JSON.parse(response.responseBody));\n }\n },\n onOpen: () => {\n if (this.state !== State.ACTIVE) {\n this.#resubscribeIfWasClosed();\n this.state = State.ACTIVE;\n this.dispatchEvent(new CustomEvent('state-changed', { detail: { active: true } }));\n this.#sendPendingMessages();\n }\n },\n onReopen: () => {\n if (this.state !== State.ACTIVE) {\n this.#resubscribeIfWasClosed();\n this.state = State.ACTIVE;\n this.dispatchEvent(new CustomEvent('state-changed', { detail: { active: true } }));\n this.#sendPendingMessages();\n }\n },\n onReconnect: () => {\n if (this.state !== State.RECONNECTING) {\n this.state = State.RECONNECTING;\n this.#endpointInfos.forEach((_, id) => {\n this.#setSubscriptionConnState(id, FluxSubscriptionState.CONNECTING);\n });\n }\n },\n onFailureToReconnect: () => {\n if (this.state !== State.INACTIVE) {\n this.state = State.INACTIVE;\n this.dispatchEvent(new CustomEvent('state-changed', { detail: { active: false } }));\n this.#endpointInfos.forEach((_, id) => this.#setSubscriptionConnState(id, FluxSubscriptionState.CLOSED));\n }\n },\n ...atmosphereOptions,\n } satisfies Atmosphere.Request);\n }\n\n #setSubscriptionConnState(id: string, state: FluxSubscriptionState) {\n const currentState = this.#statusOfSubscriptions.get(id);\n if (!currentState) {\n this.#statusOfSubscriptions.set(id, state);\n this.#onStateChangeCallbacks.get(id)?.(\n new CustomEvent('subscription-state-change', { detail: { state: this.#statusOfSubscriptions.get(id)! } }),\n );\n } else if (currentState !== state) {\n this.#statusOfSubscriptions.set(id, state);\n this.#onStateChangeCallbacks.get(id)?.(\n new CustomEvent('subscription-state-change', { detail: { state: this.#statusOfSubscriptions.get(id)! } }),\n );\n }\n }\n\n #handleMessage(message: unknown) {\n if (isClientMessage(message)) {\n const { id } = message;\n const endpointInfo = this.#endpointInfos.get(id);\n\n if (message['@type'] === 'update') {\n const callback = this.#onNextCallbacks.get(id);\n if (callback) {\n callback(message.item);\n }\n this.#setSubscriptionConnState(id, FluxSubscriptionState.CONNECTED);\n } else if (message['@type'] === 'complete') {\n this.#onCompleteCallbacks.get(id)?.();\n this.#removeSubscription(id);\n } else {\n const callback = this.#onErrorCallbacks.get(id);\n if (callback) {\n callback(message.message);\n }\n this.#removeSubscription(id);\n if (!callback) {\n throw new Error(\n endpointInfo\n ? `Error in ${endpointInfo.endpointName}.${endpointInfo.methodName}(${JSON.stringify(endpointInfo.params)}): ${message.message}`\n : `Error in unknown subscription: ${message.message}`,\n );\n }\n }\n } else {\n throw new Error(`Unknown message from server: ${String(message)}`);\n }\n }\n\n #removeSubscription(id: string) {\n this.#setSubscriptionConnState(id, FluxSubscriptionState.CLOSED);\n this.#statusOfSubscriptions.delete(id);\n this.#onStateChangeCallbacks.delete(id);\n this.#onNextCallbacks.delete(id);\n this.#onCompleteCallbacks.delete(id);\n this.#onErrorCallbacks.delete(id);\n this.#endpointInfos.delete(id);\n }\n\n #send(message: ServerMessage) {\n if (this.state === State.INACTIVE) {\n this.#pendingMessages.push(message);\n } else {\n this.#socket?.push?.(JSON.stringify(message));\n }\n }\n\n #sendPendingMessages() {\n this.#pendingMessages.forEach((msg) => this.#send(msg));\n this.#pendingMessages = [];\n }\n}\n\nexport interface FluxConnection {\n addEventListener<T extends keyof EventMap>(type: T, listener: ListenerType<T>): void;\n removeEventListener<T extends keyof EventMap>(type: T, listener: ListenerType<T>): void;\n}\n"],"version":3}
|
|
1
|
+
{"mappings":"AACA,OAAO,+BAAgC;AAEvC,SAAS,6DAA8D;AACvE,SACE,0CAIyB;AAE3B,OAAO,IAAK,wBAAL;AACL;AACA;AACA;;AACD;;;;AAiBD,OAAO,IAAK,8DAAL;;;;AAIL;;;;AAIA;;AACD;;;;AAKD,OAAO,IAAK,wDAAL;;;;AAIL;;;;AAIA;;;;AAIA;;AACD;;;;AAiBD,OAAO,MAAM,uBAAuB,YAAY;CAC9C,QAAe,MAAM;CACrB,YAAY;CACZ,AAASA,iBAAiB,IAAI;CAC9B,UAAU;CACV,AAASC,uBAAuB,IAAI;CACpC,AAASC,oBAAoB,IAAI;CACjC,AAASC,mBAAmB,IAAI;CAChC,AAASC,0BAA0B,IAAI;CACvC,AAASC,yBAAyB,IAAI;CACtC,mBAAoC,CAAE;CACtC;CAEA,YAAYC,eAAuBC,mBAAiD;AAClF,SAAO;AACP,OAAKC,kBAAkB,cAAc,QAAQ,aAAa,GAAG,EAAE,qBAAqB,CAAE,EAAC;CACxF;CAED,0BAA0B;AACxB,MAAI,KAAK,W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AAG;AACjC,OAAKF,eAAe,OAAO,GAAG;CAC/B;CAED,MAAMmC,SAAwB;AAC5B,MAAI,KAAK,UAAU,MAAM,UAAU;AACjC,QAAKC,iBAAiB,KAAK,QAAQ;EACpC,OAAM;AACL,QAAKP,SAAS,OAAO,KAAK,UAAU,QAAQ,CAAC;EAC9C;CACF;CAED,uBAAuB;AACrB,OAAKO,iBAAiB,QAAQ,CAAC,QAAQ,KAAKzB,MAAM,IAAI,CAAC;AACvD,OAAKyB,mBAAmB,CAAE;CAC3B;AACF","names":["#endpointInfos","#onCompleteCallbacks","#onErrorCallbacks","#onNextCallbacks","#onStateChangeCallbacks","#statusOfSubscriptions","connectPrefix: string","atmosphereOptions?: Partial<Atmosphere.Request>","#connectWebsocket","toBeRemoved: string[]","#setSubscriptionConnState","#send","#removeSubscription","endpointName: string","methodName: string","parameters?: unknown[]","id: string","#nextId","msg: ServerConnectMessage","hillaSubscription: Subscription<any>","closeMessage: ServerCloseMessage","context: ReactiveControllerHost","callback: () => void","callback: (message: string) => void","callback: (value: any) => void","callback: () => ActionOnLostSubscription | void","callback: (event: FluxSubscriptionStateChangeEvent) => void","prefix: string","atmosphereOptions: Partial<Atmosphere.Request>","#socket","#handleMessage","#resubscribeIfWasClosed","#sendPendingMessages","state: FluxSubscriptionState","message: unknown","message: ServerMessage","#pendingMessages"],"sources":["/opt/agent/work/649c11185a3798db/packages/ts/frontend/src/FluxConnection.ts"],"sourcesContent":["import type { ReactiveControllerHost } from '@lit/reactive-element';\nimport atmosphere from 'atmosphere.js';\nimport type { Subscription } from './Connect.js';\nimport { getCsrfTokenHeadersForEndpointRequest } from './CsrfUtils.js';\nimport {\n isClientMessage,\n type ServerCloseMessage,\n type ServerConnectMessage,\n type ServerMessage,\n} from './FluxMessages.js';\n\nexport enum State {\n ACTIVE = 'active',\n INACTIVE = 'inactive',\n RECONNECTING = 'reconnecting',\n}\n\ntype ActiveEvent = CustomEvent<{ active: boolean }>;\ninterface EventMap {\n 'state-changed': ActiveEvent;\n}\n\ntype ListenerType<T extends keyof EventMap> =\n | ((this: FluxConnection, ev: EventMap[T]) => any)\n | {\n handleEvent(ev: EventMap[T]): void;\n }\n | null;\n\n/**\n * Possible options for dealing with lost subscriptions after a websocket is reopened.\n */\nexport enum ActionOnLostSubscription {\n /**\n * The subscription should be resubscribed using the same server method and parameters.\n */\n RESUBSCRIBE = 'resubscribe',\n /**\n * The subscription should be removed.\n */\n REMOVE = 'remove',\n}\n\n/**\n * Possible states of a flux subscription.\n */\nexport enum FluxSubscriptionState {\n /**\n * The subscription is not connected and is trying to connect.\n */\n CONNECTING = 'connecting',\n /**\n * The subscription is connected and receiving updates.\n */\n CONNECTED = 'connected',\n /**\n * The subscription is closed and is not trying to reconnect.\n */\n CLOSED = 'closed',\n}\n\n/**\n * Event wrapper for flux subscription connection state change callback\n */\nexport type FluxSubscriptionStateChangeEvent = CustomEvent<{ state: FluxSubscriptionState }>;\n\ntype EndpointInfo = {\n endpointName: string;\n methodName: string;\n params: unknown[] | undefined;\n reconnect?(): ActionOnLostSubscription | void;\n};\n\n/**\n * A representation of the underlying persistent network connection used for subscribing to Flux type endpoint methods.\n */\nexport class FluxConnection extends EventTarget {\n state: State = State.INACTIVE;\n wasClosed = false;\n readonly #endpointInfos = new Map<string, EndpointInfo>();\n #nextId = 0;\n readonly #onCompleteCallbacks = new Map<string, () => void>();\n readonly #onErrorCallbacks = new Map<string, (message: string) => void>();\n readonly #onNextCallbacks = new Map<string, (value: any) => void>();\n readonly #onStateChangeCallbacks = new Map<string, (event: FluxSubscriptionStateChangeEvent) => void>();\n readonly #statusOfSubscriptions = new Map<string, FluxSubscriptionState>();\n #pendingMessages: ServerMessage[] = [];\n #socket?: Atmosphere.Request;\n\n constructor(connectPrefix: string, atmosphereOptions?: Partial<Atmosphere.Request>) {\n super();\n this.#connectWebsocket(connectPrefix.replace(/connect$/u, ''), atmosphereOptions ?? {});\n }\n\n #resubscribeIfWasClosed() {\n if (this.wasClosed) {\n this.wasClosed = false;\n const toBeRemoved: string[] = [];\n this.#endpointInfos.forEach((endpointInfo, id) => {\n if (endpointInfo.reconnect?.() === ActionOnLostSubscription.RESUBSCRIBE) {\n this.#setSubscriptionConnState(id, FluxSubscriptionState.CONNECTING);\n this.#send({\n '@type': 'subscribe',\n endpointName: endpointInfo.endpointName,\n id,\n methodName: endpointInfo.methodName,\n params: endpointInfo.params,\n });\n } else {\n toBeRemoved.push(id);\n }\n });\n toBeRemoved.forEach((id) => this.#removeSubscription(id));\n }\n }\n\n /**\n * Subscribes to the flux returned by the given endpoint name + method name using the given parameters.\n *\n * @param endpointName - the endpoint to connect to\n * @param methodName - the method in the endpoint to connect to\n * @param parameters - the parameters to use\n * @returns a subscription\n */\n subscribe(endpointName: string, methodName: string, parameters?: unknown[]): Subscription<any> {\n const id: string = this.#nextId.toString();\n this.#nextId += 1;\n const params = parameters ?? [];\n\n const msg: ServerConnectMessage = { '@type': 'subscribe', endpointName, id, methodName, params };\n this.#send(msg);\n this.#endpointInfos.set(id, { endpointName, methodName, params });\n this.#setSubscriptionConnState(id, FluxSubscriptionState.CONNECTING);\n const hillaSubscription: Subscription<any> = {\n cancel: () => {\n if (!this.#endpointInfos.has(id)) {\n // Subscription already closed or canceled\n return;\n }\n\n const closeMessage: ServerCloseMessage = { '@type': 'unsubscribe', id };\n this.#send(closeMessage);\n this.#removeSubscription(id);\n },\n context(context: ReactiveControllerHost): Subscription<any> {\n context.addController({\n hostDisconnected() {\n hillaSubscription.cancel();\n },\n });\n return hillaSubscription;\n },\n onComplete: (callback: () => void): Subscription<any> => {\n this.#onCompleteCallbacks.set(id, callback);\n return hillaSubscription;\n },\n onError: (callback: (message: string) => void): Subscription<any> => {\n this.#onErrorCallbacks.set(id, callback);\n return hillaSubscription;\n },\n onNext: (callback: (value: any) => void): Subscription<any> => {\n this.#onNextCallbacks.set(id, callback);\n return hillaSubscription;\n },\n onSubscriptionLost: (callback: () => ActionOnLostSubscription | void): Subscription<any> => {\n if (this.#endpointInfos.has(id)) {\n this.#endpointInfos.get(id)!.reconnect = callback;\n } else {\n console.warn(`\"onReconnect\" value not set for subscription \"${id}\" because it was already canceled`);\n }\n return hillaSubscription;\n },\n onConnectionStateChange: (callback: (event: FluxSubscriptionStateChangeEvent) => void): Subscription<any> => {\n this.#onStateChangeCallbacks.set(id, callback);\n callback(\n new CustomEvent('subscription-state-change', { detail: { state: this.#statusOfSubscriptions.get(id)! } }),\n );\n return hillaSubscription;\n },\n };\n return hillaSubscription;\n }\n\n #connectWebsocket(prefix: string, atmosphereOptions: Partial<Atmosphere.Request>) {\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n const extraHeaders = globalThis.document ? getCsrfTokenHeadersForEndpointRequest(globalThis.document) : {};\n const pushUrl = 'HILLA/push';\n const url = prefix.length === 0 ? pushUrl : (prefix.endsWith('/') ? prefix : `${prefix}/`) + pushUrl;\n this.#socket = atmosphere.subscribe?.({\n contentType: 'application/json; charset=UTF-8',\n enableProtocol: true,\n transport: 'websocket',\n fallbackTransport: 'websocket',\n headers: extraHeaders,\n maxReconnectOnClose: 10000000,\n reconnectInterval: 5000,\n timeout: -1,\n trackMessageLength: true,\n url,\n onClose: () => {\n this.wasClosed = true;\n if (this.state !== State.INACTIVE) {\n this.state = State.INACTIVE;\n this.dispatchEvent(new CustomEvent('state-changed', { detail: { active: false } }));\n }\n },\n onError: (response) => {\n // eslint-disable-next-line no-console\n console.error('error in push communication', response);\n },\n onMessage: (response) => {\n if (response.responseBody) {\n this.#handleMessage(JSON.parse(response.responseBody));\n }\n },\n onMessagePublished: (response) => {\n if (response?.responseBody) {\n this.#handleMessage(JSON.parse(response.responseBody));\n }\n },\n onOpen: () => {\n if (this.state !== State.ACTIVE) {\n this.#resubscribeIfWasClosed();\n this.state = State.ACTIVE;\n this.dispatchEvent(new CustomEvent('state-changed', { detail: { active: true } }));\n this.#sendPendingMessages();\n }\n },\n onReopen: () => {\n if (this.state !== State.ACTIVE) {\n this.#resubscribeIfWasClosed();\n this.state = State.ACTIVE;\n this.dispatchEvent(new CustomEvent('state-changed', { detail: { active: true } }));\n this.#sendPendingMessages();\n }\n },\n onReconnect: () => {\n if (this.state !== State.RECONNECTING) {\n this.state = State.RECONNECTING;\n this.#endpointInfos.forEach((_, id) => {\n this.#setSubscriptionConnState(id, FluxSubscriptionState.CONNECTING);\n });\n }\n },\n onFailureToReconnect: () => {\n if (this.state !== State.INACTIVE) {\n this.state = State.INACTIVE;\n this.dispatchEvent(new CustomEvent('state-changed', { detail: { active: false } }));\n this.#endpointInfos.forEach((_, id) => this.#setSubscriptionConnState(id, FluxSubscriptionState.CLOSED));\n }\n },\n ...atmosphereOptions,\n } satisfies Atmosphere.Request);\n }\n\n #setSubscriptionConnState(id: string, state: FluxSubscriptionState) {\n const currentState = this.#statusOfSubscriptions.get(id);\n if (!currentState) {\n this.#statusOfSubscriptions.set(id, state);\n this.#onStateChangeCallbacks.get(id)?.(\n new CustomEvent('subscription-state-change', { detail: { state: this.#statusOfSubscriptions.get(id)! } }),\n );\n } else if (currentState !== state) {\n this.#statusOfSubscriptions.set(id, state);\n this.#onStateChangeCallbacks.get(id)?.(\n new CustomEvent('subscription-state-change', { detail: { state: this.#statusOfSubscriptions.get(id)! } }),\n );\n }\n }\n\n #handleMessage(message: unknown) {\n if (isClientMessage(message)) {\n const { id } = message;\n const endpointInfo = this.#endpointInfos.get(id);\n\n if (message['@type'] === 'update') {\n const callback = this.#onNextCallbacks.get(id);\n if (callback) {\n callback(message.item);\n }\n this.#setSubscriptionConnState(id, FluxSubscriptionState.CONNECTED);\n } else if (message['@type'] === 'complete') {\n this.#onCompleteCallbacks.get(id)?.();\n this.#removeSubscription(id);\n } else {\n const callback = this.#onErrorCallbacks.get(id);\n if (callback) {\n callback(message.message);\n }\n this.#removeSubscription(id);\n if (!callback) {\n throw new Error(\n endpointInfo\n ? `Error in ${endpointInfo.endpointName}.${endpointInfo.methodName}(${JSON.stringify(endpointInfo.params)}): ${message.message}`\n : `Error in unknown subscription: ${message.message}`,\n );\n }\n }\n } else {\n throw new Error(`Unknown message from server: ${String(message)}`);\n }\n }\n\n #removeSubscription(id: string) {\n this.#setSubscriptionConnState(id, FluxSubscriptionState.CLOSED);\n this.#statusOfSubscriptions.delete(id);\n this.#onStateChangeCallbacks.delete(id);\n this.#onNextCallbacks.delete(id);\n this.#onCompleteCallbacks.delete(id);\n this.#onErrorCallbacks.delete(id);\n this.#endpointInfos.delete(id);\n }\n\n #send(message: ServerMessage) {\n if (this.state === State.INACTIVE) {\n this.#pendingMessages.push(message);\n } else {\n this.#socket?.push?.(JSON.stringify(message));\n }\n }\n\n #sendPendingMessages() {\n this.#pendingMessages.forEach((msg) => this.#send(msg));\n this.#pendingMessages = [];\n }\n}\n\nexport interface FluxConnection {\n addEventListener<T extends keyof EventMap>(type: T, listener: ListenerType<T>): void;\n removeEventListener<T extends keyof EventMap>(type: T, listener: ListenerType<T>): void;\n}\n"],"version":3}
|
package/FluxMessages.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"mappings":"AAmBA,OAAO,SAAS,gBAAgBA,OAAwC;AACtE,QAAO,SAAS,eAAe,UAAU,YAAY,WAAW;AACjE","names":["value: unknown"],"sources":["/opt/agent/work/
|
|
1
|
+
{"mappings":"AAmBA,OAAO,SAAS,gBAAgBA,OAAwC;AACtE,QAAO,SAAS,eAAe,UAAU,YAAY,WAAW;AACjE","names":["value: unknown"],"sources":["/opt/agent/work/649c11185a3798db/packages/ts/frontend/src/FluxMessages.ts"],"sourcesContent":["export interface AbstractMessage {\n '@type': string;\n id: string;\n}\n\nexport interface ClientErrorMessage extends AbstractMessage {\n '@type': 'error';\n message: string;\n}\nexport interface ClientCompleteMessage extends AbstractMessage {\n '@type': 'complete';\n}\nexport interface ClientUpdateMessage extends AbstractMessage {\n '@type': 'update';\n item: any;\n}\n\nexport type ClientMessage = ClientCompleteMessage | ClientErrorMessage | ClientUpdateMessage;\n\nexport function isClientMessage(value: unknown): value is ClientMessage {\n return value != null && typeof value === 'object' && '@type' in value;\n}\n\nexport interface ServerConnectMessage extends AbstractMessage {\n id: string;\n '@type': 'subscribe';\n endpointName: string;\n methodName: string;\n params?: any;\n}\nexport interface ServerCloseMessage extends AbstractMessage {\n id: string;\n '@type': 'unsubscribe';\n}\n\nexport type ServerMessage = ServerCloseMessage | ServerConnectMessage;\n"],"version":3}
|
package/index.js
CHANGED
|
@@ -6,7 +6,7 @@ export { ActionOnLostSubscription, FluxConnection, State } from "./FluxConnectio
|
|
|
6
6
|
vaadinObj.registrations ??= [];
|
|
7
7
|
vaadinObj.registrations.push({
|
|
8
8
|
is: feature ? `@vaadin/hilla-frontend/${feature}` : "@vaadin/hilla-frontend",
|
|
9
|
-
version: "24.7.
|
|
9
|
+
version: "24.7.15"
|
|
10
10
|
});
|
|
11
11
|
})();
|
|
12
12
|
//# sourceMappingURL=./index.js.map
|
package/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"mappings":"AAAA;AACA;AACA;AACA,SAAS,0BAA0B,gBAAgB;AAInD,CAAC,CAAC,SAAS,YAAa,OAAO,WAAW,CAAE,MAAM;AAChD,WAAU,kBAAkB,CAAE;AAC9B,WAAU,cAAc,KAAK;EAC3B,IAAI,WAAW,yBAAyB,QAAQ,IAAI;EACpD,SAAS;CACV,EAAC;AACH,IAAG","names":[],"sources":["/opt/agent/work/
|
|
1
|
+
{"mappings":"AAAA;AACA;AACA;AACA,SAAS,0BAA0B,gBAAgB;AAInD,CAAC,CAAC,SAAS,YAAa,OAAO,WAAW,CAAE,MAAM;AAChD,WAAU,kBAAkB,CAAE;AAC9B,WAAU,cAAc,KAAK;EAC3B,IAAI,WAAW,yBAAyB,QAAQ,IAAI;EACpD,SAAS;CACV,EAAC;AACH,IAAG","names":[],"sources":["/opt/agent/work/649c11185a3798db/packages/ts/frontend/src/index.ts"],"sourcesContent":["export * from './Authentication.js';\nexport * from './Connect.js';\nexport * from './EndpointErrors.js';\nexport { ActionOnLostSubscription, FluxConnection, State } from './FluxConnection.js';\n\n// @ts-expect-error: esbuild injection\n// eslint-disable-next-line @typescript-eslint/no-unsafe-call\n((feature, vaadinObj = (window.Vaadin ??= {})) => {\n vaadinObj.registrations ??= [];\n vaadinObj.registrations.push({\n is: feature ? `@vaadin/hilla-frontend/${feature}` : '@vaadin/hilla-frontend',\n version: '24.7.15',\n });\n})();\n"],"version":3}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@vaadin/hilla-frontend",
|
|
3
|
-
"version": "24.7.
|
|
3
|
+
"version": "24.7.15",
|
|
4
4
|
"description": "Hilla core frontend utils",
|
|
5
5
|
"main": "index.js",
|
|
6
6
|
"module": "index.js",
|
|
@@ -64,7 +64,7 @@
|
|
|
64
64
|
"dependencies": {
|
|
65
65
|
"@vaadin/common-frontend": "0.0.19",
|
|
66
66
|
"atmosphere.js": "3.1.3",
|
|
67
|
-
"js-cookie": "3.0.
|
|
67
|
+
"js-cookie": "3.0.8"
|
|
68
68
|
},
|
|
69
69
|
"peerDependencies": {
|
|
70
70
|
"lit": "^3.0.0"
|