astro-integration-pocketbase 3.1.2-next.2 → 3.1.3
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/dist/index.mjs.map +1 -1
- package/dist/middleware.mjs.map +1 -1
- package/dist/toolbar.mjs +1 -1
- package/dist/toolbar.mjs.map +1 -1
- package/package.json +11 -8
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":[],"sources":["../src/core/refresh-collections.ts","../src/types/pocketbase-api-response.type.ts","../src/utils/get-superuser-token.ts","../src/utils/push-to-map-array.ts","../src/utils/map-collections-to-watch.ts","../src/core/refresh-collections-realtime.ts","../src/pocketbase-integration.ts"],"sourcesContent":["import type { BaseIntegrationHooks } from \"astro\";\n\n/**\n * Listen for the refresh event of the toolbar.\n * When the event is triggered in the toolbar, refresh the content loaded by the PocketBase loader.\n */\nexport function handleRefreshCollections({\n toolbar,\n refreshContent,\n logger\n}: Parameters<BaseIntegrationHooks[\"astro:server:setup\"]>[0]): void {\n if (!refreshContent) {\n return;\n }\n\n logger.info(\"Setting up refresh listener for PocketBase integration\");\n\n // Listen for the refresh event of the toolbar\n toolbar.on(\n \"astro-integration-pocketbase:refresh\",\n // oxlint-disable-next-line strict-void-return\n async ({ force }: { force: boolean }) => {\n // Send a loading state to the toolbar\n toolbar.send(\"astro-integration-pocketbase:refresh\", {\n loading: true\n });\n\n // Refresh content loaded by the PocketBase loader\n logger.info(\n `Refreshing ${force ? \"all \" : \"\"}content loaded by PocketBase loader`\n );\n await refreshContent({\n loaders: [\"pocketbase-loader\"],\n context: {\n source: \"astro-integration-pocketbase\",\n force\n }\n });\n\n // Reset the loading state in the toolbar\n toolbar.send(\"astro-integration-pocketbase:refresh\", {\n loading: false\n });\n }\n );\n}\n","import { z } from \"astro/zod\";\n\n/**\n * The schema for a PocketBase error response.\n */\nexport const pocketBaseErrorResponse = z.object({\n /**\n * The error message returned by PocketBase.\n */\n message: z.string()\n});\n\n/**\n * The schema for a PocketBase login response.\n */\nexport const pocketBaseLoginResponse = z.object({\n /**\n * The authentication token returned by PocketBase.\n */\n token: z.string()\n});\n","import type { AstroIntegrationLogger } from \"astro\";\nimport {\n pocketBaseErrorResponse,\n pocketBaseLoginResponse\n} from \"../types/pocketbase-api-response.type\";\n\n/**\n * This function will get a superuser token from the given PocketBase instance.\n *\n * @param url URL of the PocketBase instance\n * @param superuserCredentials Credentials of the superuser\n *\n * @returns A superuser token to access all resources of the PocketBase instance.\n */\nexport async function getSuperuserToken(\n url: string,\n superuserCredentials: {\n email: string;\n password: string;\n },\n logger: AstroIntegrationLogger\n): Promise<string | undefined> {\n // Build the URL for the login endpoint\n const loginUrl = new URL(\n `api/collections/_superusers/auth-with-password`,\n url\n ).href;\n\n // Create a new FormData object to send the login data\n const loginData = new FormData();\n loginData.set(\"identity\", superuserCredentials.email);\n loginData.set(\"password\", superuserCredentials.password);\n\n // Send the login request to get a token\n const loginRequest = await fetch(loginUrl, {\n method: \"POST\",\n body: loginData\n });\n\n // If the login request was not successful, print the error message and return undefined\n if (!loginRequest.ok) {\n if (loginRequest.status === 429) {\n const info =\n \"A rate limit was hit while trying to authenticate with PocketBase. Consider using an `impersonateToken` as credentials to avoid this issue.\";\n logger.info(info);\n\n // Random wait between 3 (default rate limit interval) and 8 seconds\n const retryAfter = Math.random() * 5 + 3;\n // oxlint-disable-next-line promise/avoid-new\n await new Promise((resolve) => {\n setTimeout(resolve, retryAfter * 1000);\n });\n\n return getSuperuserToken(url, superuserCredentials, logger);\n }\n\n const errorResponse = pocketBaseErrorResponse.parse(\n await loginRequest.json()\n );\n const errorMessage = `The given email / password for ${url} was not correct. Astro can't generate type definitions automatically and may not have access to all resources.\\nReason: ${errorResponse.message}`;\n logger.error(errorMessage);\n return undefined;\n }\n\n // Return the token\n const response = pocketBaseLoginResponse.parse(await loginRequest.json());\n return response.token;\n}\n","/**\n * Adds a value to an array in a map. If the key does not exist, it will be created.\n */\nexport function pushToMapArray<TKey, TArray>(\n map: Map<TKey, Array<TArray>>,\n key: TKey,\n value: TArray\n): void {\n const array = map.get(key);\n if (array) {\n array.push(value);\n return;\n }\n\n map.set(key, [value]);\n}\n","import type { PocketBaseIntegrationOptions } from \"../types/pocketbase-integration-options.type\";\nimport { pushToMapArray } from \"./push-to-map-array\";\n\n/**\n * Create a map of remote collections to watch.\n * Each key in the map represents a remote collection to subscribe to.\n * The value is an array of local collections that should be refreshed when an entry in the remote collection changes.\n */\nexport function mapCollectionsToWatch(\n collectionsToWatch: PocketBaseIntegrationOptions[\"collectionsToWatch\"]\n): Map<string, Array<string>> | undefined {\n // Check if collections should be watched\n if (!collectionsToWatch) {\n return undefined;\n }\n\n // Check if collectionsToWatch is an array\n if (Array.isArray(collectionsToWatch)) {\n // Check if the array is empty\n if (collectionsToWatch.length === 0) {\n return undefined;\n }\n\n // Create a map where each collection is watched by itself\n return new Map(\n collectionsToWatch.map((collection) => [collection, [collection]])\n );\n }\n\n // Check if collectionsToWatch is an empty object\n if (Object.keys(collectionsToWatch).length === 0) {\n return undefined;\n }\n\n // Map collections to watch\n const collectionsMap = new Map<string, Array<string>>();\n for (const localCollection in collectionsToWatch) {\n const watch = collectionsToWatch[localCollection];\n if (!watch) {\n continue;\n }\n\n // Check if collection should be watched by itself\n if (watch === true) {\n pushToMapArray(collectionsMap, localCollection, localCollection);\n continue;\n }\n\n // Collection should be watched by multiple collections\n for (const remoteCollection of watch) {\n pushToMapArray(collectionsMap, remoteCollection, localCollection);\n }\n }\n\n return collectionsMap;\n}\n","import type { AstroIntegrationLogger, BaseIntegrationHooks } from \"astro\";\nimport { EventSource } from \"eventsource\";\nimport type { PocketBaseIntegrationOptions } from \"../types/pocketbase-integration-options.type\";\nimport { getSuperuserToken } from \"../utils/get-superuser-token\";\nimport { mapCollectionsToWatch } from \"../utils/map-collections-to-watch\";\n\nexport function refreshCollectionsRealtime(\n options: PocketBaseIntegrationOptions,\n {\n logger,\n refreshContent,\n toolbar\n }: Parameters<BaseIntegrationHooks[\"astro:server:setup\"]>[0]\n): EventSource | undefined {\n // Check if collections should be watched\n const collectionsMap = mapCollectionsToWatch(options.collectionsToWatch);\n if (!collectionsMap) {\n return undefined;\n }\n const remoteCollections = [...collectionsMap.keys()];\n\n // Check if content loader is used\n if (!refreshContent) {\n logger.warn(\n \"No content loader available, skipping subscription to PocketBase realtime API.\"\n );\n return undefined;\n }\n\n // Check if EventSource is available\n // oxlint-disable-next-line no-unnecessary-condition\n if (!EventSource) {\n logger.warn(\n \"EventSource is not available, skipping subscription to PocketBase realtime API.\\n\" +\n \"Please install the 'eventsource' package.\"\n );\n return undefined;\n }\n\n let refreshEnabled = true;\n // Enable or disable real-time updates via the toolbar\n toolbar.on(\"astro-integration-pocketbase:real-time\", (enabled: boolean) => {\n refreshEnabled = enabled;\n });\n\n const eventSourceUrl = new URL(\"api/realtime\", options.url).href;\n const eventSource = new EventSource(eventSourceUrl);\n let wasConnectedOnce = false;\n let isConnected = false;\n\n // Log potential errors\n // oxlint-disable-next-line prefer-await-to-callbacks\n eventSource.addEventListener(\"error\", (error) => {\n isConnected = false;\n\n // Wait for 5 seconds in case of a connection error\n setTimeout(() => {\n if (isConnected) {\n // Connection was automatically re-established, no need to log the error\n return;\n }\n\n logger.error(\n `Error while connecting to PocketBase realtime API: ${error.type}`\n );\n }, 5000);\n });\n\n // Add event listeners for all collections\n for (const collection of remoteCollections) {\n eventSource.addEventListener(\n `${collection}/*`,\n async (event: MessageEvent<string>) => {\n // Do not refresh if the refresh is disabled\n if (!refreshEnabled) {\n return;\n }\n\n // Refresh the content\n logger.info(`Received update for ${collection}. Refreshing content...`);\n await refreshContent({\n loaders: [\"pocketbase-loader\"],\n context: {\n source: \"astro-integration-pocketbase\",\n collection: collectionsMap.get(collection),\n // oxlint-disable-next-line @typescript-eslint/no-unsafe-assignment\n data: JSON.parse(event.data)\n }\n });\n }\n );\n }\n\n // Add event listener for the connection event\n eventSource.addEventListener(\n \"PB_CONNECT\",\n async (event: MessageEvent<void>) => {\n isConnected = await handleConnectEvent(\n event,\n remoteCollections,\n wasConnectedOnce,\n options,\n logger\n );\n if (isConnected) {\n wasConnectedOnce = true;\n }\n }\n );\n\n return eventSource;\n}\n\nasync function handleConnectEvent(\n event: MessageEvent<void>,\n remoteCollections: Array<string>,\n wasConnectedOnce: boolean,\n options: PocketBaseIntegrationOptions,\n logger: AstroIntegrationLogger\n): Promise<boolean> {\n // Extract the clientId\n const clientId = event.lastEventId;\n\n // Get the superuser token if credentials are available\n let superuserToken: string | undefined;\n if (options.superuserCredentials) {\n if (\"impersonateToken\" in options.superuserCredentials) {\n superuserToken = options.superuserCredentials.impersonateToken;\n } else {\n superuserToken = await getSuperuserToken(\n options.url,\n options.superuserCredentials,\n logger\n );\n }\n }\n\n // Subscribe to the PocketBase realtime API\n const subscriptionUrl = new URL(\"api/realtime\", options.url).href;\n const result = await fetch(subscriptionUrl, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: superuserToken || \"\"\n },\n body: JSON.stringify({\n clientId,\n subscriptions: remoteCollections.map((collection) => `${collection}/*`)\n })\n });\n\n // Log the connection status\n if (!result.ok) {\n logger.error(\n `Error while subscribing to PocketBase realtime API: ${result.status}`\n );\n return false;\n }\n\n if (!wasConnectedOnce) {\n logger.info(\n `Subscribed to PocketBase realtime API. Waiting for updates on ${remoteCollections.join(\n \", \"\n )}.`\n );\n }\n\n return true;\n}\n","import { fileURLToPath } from \"node:url\";\nimport type { AstroIntegration } from \"astro\";\nimport type { EventSource } from \"eventsource\";\nimport { handleRefreshCollections, refreshCollectionsRealtime } from \"./core\";\nimport type { ToolbarOptions } from \"./toolbar/types/options\";\nimport type { PocketBaseIntegrationOptions } from \"./types/pocketbase-integration-options.type\";\n\nexport function pocketbaseIntegration(\n options: PocketBaseIntegrationOptions\n): AstroIntegration {\n let eventSource: EventSource | undefined = undefined;\n let initialSetupDone = false;\n\n return {\n name: \"pocketbase-integration\",\n hooks: {\n \"astro:config:setup\": ({\n addDevToolbarApp,\n addMiddleware,\n command\n }): void => {\n // This integration is only available in dev mode\n if (command !== \"dev\") {\n return;\n }\n\n // Setup Toolbar\n addDevToolbarApp({\n name: \"PocketBase\",\n id: `pocketbase-entry`,\n icon: `<svg role=\"img\" viewBox=\"0 0 24 24\" xmlns=\"http://www.w3.org/2000/svg\"><title>PocketBase</title><path fill=\"currentColor\" d=\"M5.684 12a.632.632 0 0 1-.631-.632V4.421c0-.349.282-.632.631-.632h2.37c.46 0 .889.047 1.287.139.407.084.758.23 1.053.44.303.202.541.475.715.82.173.335.26.75.26 1.246 0 .479-.092.894-.273 1.247a2.373 2.373 0 0 1-.715.869 3.11 3.11 0 0 1-1.053.503c-.398.11-.823.164-1.273.164h-.46a.632.632 0 0 0-.632.632v1.52a.632.632 0 0 1-.632.631Zm1.279-4.888c0 .349.283.632.632.632h.343c1.04 0 1.56-.437 1.56-1.31 0-.428-.135-.73-.404-.907-.26-.176-.645-.264-1.156-.264h-.343a.632.632 0 0 0-.632.631Zm6.3 13.098a.632.632 0 0 1-.631-.631v-6.947a.63.63 0 0 1 .631-.632h2.203c.44 0 .845.034 1.216.1.38.06.708.169.984.328.276.16.492.37.647.63.164.26.246.587.246.982 0 .185-.03.37-.09.554a1.537 1.537 0 0 1-.26.516 1.857 1.857 0 0 1-1.076.7.031.031 0 0 0-.023.03c0 .015.01.028.025.03.591.111 1.04.32 1.346.626.311.31.466.743.466 1.297 0 .42-.082.78-.246 1.083a2.153 2.153 0 0 1-.685.755 3.4 3.4 0 0 1-1.036.441 5.477 5.477 0 0 1-1.268.139zm1.271-5.542c0 .349.283.631.632.631h.21c.465 0 .802-.088 1.009-.264.207-.176.31-.424.31-.743 0-.302-.107-.516-.323-.642-.207-.135-.535-.202-.984-.202h-.222a.632.632 0 0 0-.632.632Zm0 3.463c0 .349.283.631.632.631h.39c1.019 0 1.528-.369 1.528-1.108 0-.36-.125-.621-.376-.78-.241-.16-.625-.24-1.152-.24h-.39a.632.632 0 0 0-.632.632zM1.389 0C.629 0 0 .629 0 1.389V15.03a1.4 1.4 0 0 0 1.389 1.39H8.21a.632.632 0 0 0 .63-.632.632.632 0 0 0-.63-.63H1.389c-.078 0-.125-.05-.125-.128V1.39c0-.078.047-.125.125-.125H15.03c.078 0 .127.047.127.125v6.82a.632.632 0 0 0 .631.63.632.632 0 0 0 .633-.63V1.389A1.4 1.4 0 0 0 15.032 0ZM15.79 7.578a.632.632 0 0 0-.632.633.632.632 0 0 0 .631.63h6.822c.078 0 .125.05.125.128V22.61c0 .078-.047.125-.125.125H8.97c-.077 0-.127-.047-.127-.125v-6.82a.632.632 0 0 0-.631-.63.632.632 0 0 0-.633.63v6.822A1.4 1.4 0 0 0 8.968 24h13.643c.76 0 1.389-.629 1.389-1.389V8.97a1.4 1.4 0 0 0-1.389-1.39Z\"/></svg>`,\n entrypoint: fileURLToPath(new URL(\"./toolbar\", import.meta.url))\n });\n\n // Setup middleware\n addMiddleware({\n order: \"post\",\n entrypoint: fileURLToPath(new URL(\"./middleware\", import.meta.url))\n });\n },\n \"astro:server:setup\": (setupOptions): void => {\n if (!initialSetupDone) {\n // Listen for the refresh event of the toolbar\n handleRefreshCollections(setupOptions);\n }\n\n // Subscribe to PocketBase realtime API\n if (eventSource) {\n eventSource.close();\n eventSource = undefined;\n }\n eventSource = refreshCollectionsRealtime(options, setupOptions);\n\n // Send settings to the toolbar on initialization\n setupOptions.toolbar.onAppInitialized(\"pocketbase-entry\", () => {\n setupOptions.toolbar.send(\"astro-integration-pocketbase:settings\", {\n hasContentLoader: !!setupOptions.refreshContent,\n realtime: !!eventSource,\n baseUrl: options.url\n } satisfies ToolbarOptions);\n });\n\n initialSetupDone = true;\n },\n \"astro:server:done\": ({ logger }): void => {\n // Close the EventSource connection when the server is done\n if (eventSource) {\n logger.info(\"Closing EventSource connection\");\n eventSource.close();\n eventSource = undefined;\n }\n }\n }\n };\n}\n"],"mappings":";;;;;;;;AAMA,SAAgB,yBAAyB,E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EAAE,EACJ;CAGF,OAAO;AACT;;;ACjKA,SAAgB,sBACd,SACkB;CAClB,IAAI,cAAuC,KAAA;CAC3C,IAAI,mBAAmB;CAEvB,OAAO;EACL,MAAM;EACN,OAAO;GACL,uBAAuB,EACrB,kBACA,eACA,cACU;IAEV,IAAI,YAAY,OACd;IAIF,iBAAiB;KACf,MAAM;KACN,IAAI;KACJ,MAAM;KACN,YAAY,cAAc,IAAI,IAAI,aAAa,OAAO,KAAK,GAAG,CAAC;IACjE,CAAC;IAGD,cAAc;KACZ,OAAO;KACP,YAAY,cAAc,IAAI,IAAI,gBAAgB,OAAO,KAAK,GAAG,CAAC;IACpE,CAAC;GACH;GACA,uBAAuB,iBAAuB;IAC5C,IAAI,CAAC,kBAEH,yBAAyB,YAAY;IAIvC,IAAI,aAAa;KACf,YAAY,MAAM;KAClB,cAAc,KAAA;IAChB;IACA,cAAc,2BAA2B,SAAS,YAAY;IAG9D,aAAa,QAAQ,iBAAiB,0BAA0B;KAC9D,aAAa,QAAQ,KAAK,yCAAyC;MACjE,kBAAkB,CAAC,CAAC,aAAa;MACjC,UAAU,CAAC,CAAC;MACZ,SAAS,QAAQ;KACnB,CAA0B;IAC5B,CAAC;IAED,mBAAmB;GACrB;GACA,sBAAsB,EAAE,aAAmB;IAEzC,IAAI,aAAa;KACf,OAAO,KAAK,gCAAgC;KAC5C,YAAY,MAAM;KAClB,cAAc,KAAA;IAChB;GACF;EACF;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":[],"sources":["../src/core/refresh-collections.ts","../src/types/pocketbase-api-response.type.ts","../src/utils/get-superuser-token.ts","../src/utils/push-to-map-array.ts","../src/utils/map-collections-to-watch.ts","../src/core/refresh-collections-realtime.ts","../src/pocketbase-integration.ts"],"sourcesContent":["import type { BaseIntegrationHooks } from \"astro\";\n\n/**\n * Listen for the refresh event of the toolbar.\n * When the event is triggered in the toolbar, refresh the content loaded by the PocketBase loader.\n */\nexport function handleRefreshCollections({\n toolbar,\n refreshContent,\n logger\n}: Parameters<BaseIntegrationHooks[\"astro:server:setup\"]>[0]): void {\n if (!refreshContent) {\n return;\n }\n\n logger.info(\"Setting up refresh listener for PocketBase integration\");\n\n // Listen for the refresh event of the toolbar\n toolbar.on(\n \"astro-integration-pocketbase:refresh\",\n // oxlint-disable-next-line strict-void-return\n async ({ force }: { force: boolean }) => {\n // Send a loading state to the toolbar\n toolbar.send(\"astro-integration-pocketbase:refresh\", {\n loading: true\n });\n\n // Refresh content loaded by the PocketBase loader\n logger.info(\n `Refreshing ${force ? \"all \" : \"\"}content loaded by PocketBase loader`\n );\n await refreshContent({\n loaders: [\"pocketbase-loader\"],\n context: {\n source: \"astro-integration-pocketbase\",\n force\n }\n });\n\n // Reset the loading state in the toolbar\n toolbar.send(\"astro-integration-pocketbase:refresh\", {\n loading: false\n });\n }\n );\n}\n","import { z } from \"astro/zod\";\n\n/**\n * The schema for a PocketBase error response.\n */\nexport const pocketBaseErrorResponse = z.object({\n /**\n * The error message returned by PocketBase.\n */\n message: z.string()\n});\n\n/**\n * The schema for a PocketBase login response.\n */\nexport const pocketBaseLoginResponse = z.object({\n /**\n * The authentication token returned by PocketBase.\n */\n token: z.string()\n});\n","import type { AstroIntegrationLogger } from \"astro\";\nimport {\n pocketBaseErrorResponse,\n pocketBaseLoginResponse\n} from \"../types/pocketbase-api-response.type\";\n\n/**\n * This function will get a superuser token from the given PocketBase instance.\n *\n * @param url URL of the PocketBase instance\n * @param superuserCredentials Credentials of the superuser\n *\n * @returns A superuser token to access all resources of the PocketBase instance.\n */\nexport async function getSuperuserToken(\n url: string,\n superuserCredentials: {\n email: string;\n password: string;\n },\n logger: AstroIntegrationLogger\n): Promise<string | undefined> {\n // Build the URL for the login endpoint\n const loginUrl = new URL(\n `api/collections/_superusers/auth-with-password`,\n url\n ).href;\n\n // Create a new FormData object to send the login data\n const loginData = new FormData();\n loginData.set(\"identity\", superuserCredentials.email);\n loginData.set(\"password\", superuserCredentials.password);\n\n // Send the login request to get a token\n const loginRequest = await fetch(loginUrl, {\n method: \"POST\",\n body: loginData\n });\n\n // If the login request was not successful, print the error message and return undefined\n if (!loginRequest.ok) {\n if (loginRequest.status === 429) {\n const info =\n \"A rate limit was hit while trying to authenticate with PocketBase. Consider using an `impersonateToken` as credentials to avoid this issue.\";\n logger.info(info);\n\n // Random wait between 3 (default rate limit interval) and 8 seconds\n const retryAfter = Math.random() * 5 + 3;\n // oxlint-disable-next-line promise/avoid-new\n await new Promise((resolve) => {\n setTimeout(resolve, retryAfter * 1000);\n });\n\n return getSuperuserToken(url, superuserCredentials, logger);\n }\n\n const errorResponse = pocketBaseErrorResponse.parse(\n await loginRequest.json()\n );\n const errorMessage = `The given email / password for ${url} was not correct. Astro can't generate type definitions automatically and may not have access to all resources.\\nReason: ${errorResponse.message}`;\n logger.error(errorMessage);\n return undefined;\n }\n\n // Return the token\n const response = pocketBaseLoginResponse.parse(await loginRequest.json());\n return response.token;\n}\n","/**\n * Adds a value to an array in a map. If the key does not exist, it will be created.\n */\nexport function pushToMapArray<TKey, TArray>(\n map: Map<TKey, Array<TArray>>,\n key: TKey,\n value: TArray\n): void {\n const array = map.get(key);\n if (array) {\n array.push(value);\n return;\n }\n\n map.set(key, [value]);\n}\n","import type { PocketBaseIntegrationOptions } from \"../types/pocketbase-integration-options.type\";\nimport { pushToMapArray } from \"./push-to-map-array\";\n\n/**\n * Create a map of remote collections to watch.\n * Each key in the map represents a remote collection to subscribe to.\n * The value is an array of local collections that should be refreshed when an entry in the remote collection changes.\n */\nexport function mapCollectionsToWatch(\n collectionsToWatch: PocketBaseIntegrationOptions[\"collectionsToWatch\"]\n): Map<string, Array<string>> | undefined {\n // Check if collections should be watched\n if (!collectionsToWatch) {\n return undefined;\n }\n\n // Check if collectionsToWatch is an array\n if (Array.isArray(collectionsToWatch)) {\n // Check if the array is empty\n if (collectionsToWatch.length === 0) {\n return undefined;\n }\n\n // Create a map where each collection is watched by itself\n return new Map(\n collectionsToWatch.map((collection) => [collection, [collection]])\n );\n }\n\n // Check if collectionsToWatch is an empty object\n if (Object.keys(collectionsToWatch).length === 0) {\n return undefined;\n }\n\n // Map collections to watch\n const collectionsMap = new Map<string, Array<string>>();\n for (const localCollection in collectionsToWatch) {\n const watch = collectionsToWatch[localCollection];\n if (!watch) {\n continue;\n }\n\n // Check if collection should be watched by itself\n if (watch === true) {\n pushToMapArray(collectionsMap, localCollection, localCollection);\n continue;\n }\n\n // Collection should be watched by multiple collections\n for (const remoteCollection of watch) {\n pushToMapArray(collectionsMap, remoteCollection, localCollection);\n }\n }\n\n return collectionsMap;\n}\n","import type { AstroIntegrationLogger, BaseIntegrationHooks } from \"astro\";\nimport { EventSource } from \"eventsource\";\nimport type { PocketBaseIntegrationOptions } from \"../types/pocketbase-integration-options.type\";\nimport { getSuperuserToken } from \"../utils/get-superuser-token\";\nimport { mapCollectionsToWatch } from \"../utils/map-collections-to-watch\";\n\nexport function refreshCollectionsRealtime(\n options: PocketBaseIntegrationOptions,\n {\n logger,\n refreshContent,\n toolbar\n }: Parameters<BaseIntegrationHooks[\"astro:server:setup\"]>[0]\n): EventSource | undefined {\n // Check if collections should be watched\n const collectionsMap = mapCollectionsToWatch(options.collectionsToWatch);\n if (!collectionsMap) {\n return undefined;\n }\n const remoteCollections = [...collectionsMap.keys()];\n\n // Check if content loader is used\n if (!refreshContent) {\n logger.warn(\n \"No content loader available, skipping subscription to PocketBase realtime API.\"\n );\n return undefined;\n }\n\n // Check if EventSource is available\n // oxlint-disable-next-line no-unnecessary-condition\n if (!EventSource) {\n logger.warn(\n \"EventSource is not available, skipping subscription to PocketBase realtime API.\\n\" +\n \"Please install the 'eventsource' package.\"\n );\n return undefined;\n }\n\n let refreshEnabled = true;\n // Enable or disable real-time updates via the toolbar\n toolbar.on(\"astro-integration-pocketbase:real-time\", (enabled: boolean) => {\n refreshEnabled = enabled;\n });\n\n const eventSourceUrl = new URL(\"api/realtime\", options.url).href;\n const eventSource = new EventSource(eventSourceUrl);\n let wasConnectedOnce = false;\n let isConnected = false;\n\n // Log potential errors\n // oxlint-disable-next-line prefer-await-to-callbacks\n eventSource.addEventListener(\"error\", (error) => {\n isConnected = false;\n\n // Wait for 5 seconds in case of a connection error\n setTimeout(() => {\n if (isConnected) {\n // Connection was automatically re-established, no need to log the error\n return;\n }\n\n logger.error(\n `Error while connecting to PocketBase realtime API: ${error.type}`\n );\n }, 5000);\n });\n\n // Add event listeners for all collections\n for (const collection of remoteCollections) {\n eventSource.addEventListener(\n `${collection}/*`,\n async (event: MessageEvent<string>) => {\n // Do not refresh if the refresh is disabled\n if (!refreshEnabled) {\n return;\n }\n\n // Refresh the content\n logger.info(`Received update for ${collection}. Refreshing content...`);\n await refreshContent({\n loaders: [\"pocketbase-loader\"],\n context: {\n source: \"astro-integration-pocketbase\",\n collection: collectionsMap.get(collection),\n // oxlint-disable-next-line @typescript-eslint/no-unsafe-assignment\n data: JSON.parse(event.data)\n }\n });\n }\n );\n }\n\n // Add event listener for the connection event\n eventSource.addEventListener(\n \"PB_CONNECT\",\n async (event: MessageEvent<void>) => {\n isConnected = await handleConnectEvent(\n event,\n remoteCollections,\n wasConnectedOnce,\n options,\n logger\n );\n if (isConnected) {\n wasConnectedOnce = true;\n }\n }\n );\n\n return eventSource;\n}\n\nasync function handleConnectEvent(\n event: MessageEvent<void>,\n remoteCollections: Array<string>,\n wasConnectedOnce: boolean,\n options: PocketBaseIntegrationOptions,\n logger: AstroIntegrationLogger\n): Promise<boolean> {\n // Extract the clientId\n const clientId = event.lastEventId;\n\n // Get the superuser token if credentials are available\n let superuserToken: string | undefined;\n if (options.superuserCredentials) {\n if (\"impersonateToken\" in options.superuserCredentials) {\n superuserToken = options.superuserCredentials.impersonateToken;\n } else {\n superuserToken = await getSuperuserToken(\n options.url,\n options.superuserCredentials,\n logger\n );\n }\n }\n\n // Subscribe to the PocketBase realtime API\n const subscriptionUrl = new URL(\"api/realtime\", options.url).href;\n const result = await fetch(subscriptionUrl, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: superuserToken || \"\"\n },\n body: JSON.stringify({\n clientId,\n subscriptions: remoteCollections.map((collection) => `${collection}/*`)\n })\n });\n\n // Log the connection status\n if (!result.ok) {\n logger.error(\n `Error while subscribing to PocketBase realtime API: ${result.status}`\n );\n return false;\n }\n\n if (!wasConnectedOnce) {\n logger.info(\n `Subscribed to PocketBase realtime API. Waiting for updates on ${remoteCollections.join(\n \", \"\n )}.`\n );\n }\n\n return true;\n}\n","import { fileURLToPath } from \"node:url\";\nimport type { AstroIntegration } from \"astro\";\nimport type { EventSource } from \"eventsource\";\nimport { handleRefreshCollections, refreshCollectionsRealtime } from \"./core\";\nimport type { ToolbarOptions } from \"./toolbar/types/options\";\nimport type { PocketBaseIntegrationOptions } from \"./types/pocketbase-integration-options.type\";\n\nexport function pocketbaseIntegration(\n options: PocketBaseIntegrationOptions\n): AstroIntegration {\n let eventSource: EventSource | undefined = undefined;\n let initialSetupDone = false;\n\n return {\n name: \"pocketbase-integration\",\n hooks: {\n \"astro:config:setup\": ({\n addDevToolbarApp,\n addMiddleware,\n command\n }): void => {\n // This integration is only available in dev mode\n if (command !== \"dev\") {\n return;\n }\n\n // Setup Toolbar\n addDevToolbarApp({\n name: \"PocketBase\",\n id: `pocketbase-entry`,\n icon: `<svg role=\"img\" viewBox=\"0 0 24 24\" xmlns=\"http://www.w3.org/2000/svg\"><title>PocketBase</title><path fill=\"currentColor\" d=\"M5.684 12a.632.632 0 0 1-.631-.632V4.421c0-.349.282-.632.631-.632h2.37c.46 0 .889.047 1.287.139.407.084.758.23 1.053.44.303.202.541.475.715.82.173.335.26.75.26 1.246 0 .479-.092.894-.273 1.247a2.373 2.373 0 0 1-.715.869 3.11 3.11 0 0 1-1.053.503c-.398.11-.823.164-1.273.164h-.46a.632.632 0 0 0-.632.632v1.52a.632.632 0 0 1-.632.631Zm1.279-4.888c0 .349.283.632.632.632h.343c1.04 0 1.56-.437 1.56-1.31 0-.428-.135-.73-.404-.907-.26-.176-.645-.264-1.156-.264h-.343a.632.632 0 0 0-.632.631Zm6.3 13.098a.632.632 0 0 1-.631-.631v-6.947a.63.63 0 0 1 .631-.632h2.203c.44 0 .845.034 1.216.1.38.06.708.169.984.328.276.16.492.37.647.63.164.26.246.587.246.982 0 .185-.03.37-.09.554a1.537 1.537 0 0 1-.26.516 1.857 1.857 0 0 1-1.076.7.031.031 0 0 0-.023.03c0 .015.01.028.025.03.591.111 1.04.32 1.346.626.311.31.466.743.466 1.297 0 .42-.082.78-.246 1.083a2.153 2.153 0 0 1-.685.755 3.4 3.4 0 0 1-1.036.441 5.477 5.477 0 0 1-1.268.139zm1.271-5.542c0 .349.283.631.632.631h.21c.465 0 .802-.088 1.009-.264.207-.176.31-.424.31-.743 0-.302-.107-.516-.323-.642-.207-.135-.535-.202-.984-.202h-.222a.632.632 0 0 0-.632.632Zm0 3.463c0 .349.283.631.632.631h.39c1.019 0 1.528-.369 1.528-1.108 0-.36-.125-.621-.376-.78-.241-.16-.625-.24-1.152-.24h-.39a.632.632 0 0 0-.632.632zM1.389 0C.629 0 0 .629 0 1.389V15.03a1.4 1.4 0 0 0 1.389 1.39H8.21a.632.632 0 0 0 .63-.632.632.632 0 0 0-.63-.63H1.389c-.078 0-.125-.05-.125-.128V1.39c0-.078.047-.125.125-.125H15.03c.078 0 .127.047.127.125v6.82a.632.632 0 0 0 .631.63.632.632 0 0 0 .633-.63V1.389A1.4 1.4 0 0 0 15.032 0ZM15.79 7.578a.632.632 0 0 0-.632.633.632.632 0 0 0 .631.63h6.822c.078 0 .125.05.125.128V22.61c0 .078-.047.125-.125.125H8.97c-.077 0-.127-.047-.127-.125v-6.82a.632.632 0 0 0-.631-.63.632.632 0 0 0-.633.63v6.822A1.4 1.4 0 0 0 8.968 24h13.643c.76 0 1.389-.629 1.389-1.389V8.97a1.4 1.4 0 0 0-1.389-1.39Z\"/></svg>`,\n entrypoint: fileURLToPath(new URL(\"./toolbar\", import.meta.url))\n });\n\n // Setup middleware\n addMiddleware({\n order: \"post\",\n entrypoint: fileURLToPath(new URL(\"./middleware\", import.meta.url))\n });\n },\n \"astro:server:setup\": (setupOptions): void => {\n if (!initialSetupDone) {\n // Listen for the refresh event of the toolbar\n handleRefreshCollections(setupOptions);\n }\n\n // Subscribe to PocketBase realtime API\n if (eventSource) {\n eventSource.close();\n eventSource = undefined;\n }\n eventSource = refreshCollectionsRealtime(options, setupOptions);\n\n // Send settings to the toolbar on initialization\n setupOptions.toolbar.onAppInitialized(\"pocketbase-entry\", () => {\n setupOptions.toolbar.send(\"astro-integration-pocketbase:settings\", {\n hasContentLoader: !!setupOptions.refreshContent,\n realtime: !!eventSource,\n baseUrl: options.url\n } satisfies ToolbarOptions);\n });\n\n initialSetupDone = true;\n },\n \"astro:server:done\": ({ logger }): void => {\n // Close the EventSource connection when the server is done\n if (eventSource) {\n logger.info(\"Closing EventSource connection\");\n eventSource.close();\n eventSource = undefined;\n }\n }\n }\n };\n}\n"],"mappings":";;;;;;;;AAMA,SAAgB,yBAAyB,EACvC,SACA,gBACA,UACkE;CAClE,IAAI,CAAC,gBACH;CAGF,OAAO,KAAK,wDAAwD;CAGpE,QAAQ,GACN,wCAEA,OAAO,EAAE,YAAgC;EAEvC,QAAQ,KAAK,wCAAwC,EACnD,SAAS,KACX,CAAC;EAGD,OAAO,KACL,cAAc,QAAQ,SAAS,GAAG,oCACpC;EACA,MAAM,eAAe;GACnB,SAAS,CAAC,mBAAmB;GAC7B,SAAS;IACP,QAAQ;IACR;GACF;EACF,CAAC;EAGD,QAAQ,KAAK,wCAAwC,EACnD,SAAS,MACX,CAAC;CACH,CACF;AACF;;;;;;ACxCA,MAAa,0BAA0B,EAAE,OAAO;;;;AAI9C,SAAS,EAAE,OAAO,EACpB,CAAC;;;;AAKD,MAAa,0BAA0B,EAAE,OAAO;;;;AAI9C,OAAO,EAAE,OAAO,EAClB,CAAC;;;;;;;;;;;ACND,eAAsB,kBACpB,KACA,sBAIA,QAC6B;CAE7B,MAAM,WAAW,IAA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AAY;IAG9D,aAAa,QAAQ,iBAAiB,0BAA0B;KAC9D,aAAa,QAAQ,KAAK,yCAAyC;MACjE,kBAAkB,CAAC,CAAC,aAAa;MACjC,UAAU,CAAC,CAAC;MACZ,SAAS,QAAQ;KACnB,CAA0B;IAC5B,CAAC;IAED,mBAAmB;GACrB;GACA,sBAAsB,EAAE,aAAmB;IAEzC,IAAI,aAAa;KACf,OAAO,KAAK,gCAAgC;KAC5C,YAAY,MAAM;KAClB,cAAc,KAAA;IAChB;GACF;EACF;CACF;AACF"}
|
package/dist/middleware.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"middleware.mjs","names":[],"sources":["../src/middleware/is-pocketbase-entry.ts","../src/middleware/index.ts"],"sourcesContent":["import { z } from \"astro/zod\";\n\n/**\n * Schema for a PocketBase entry created with [astro-loader-pocketbase](https://github.com/pawcoding/astro-loader-pocketbase)\n */\nconst pocketbaseEntrySchema = z.object({\n id: z.string(),\n data: z.object({\n id: z.string(),\n collectionId: z.string(),\n collectionName: z.string()\n }),\n digest: z.string().length(16),\n collection: z.string()\n});\n\n/**\n * Type for a PocketBase entry created with [astro-loader-pocketbase](https://github.com/pawcoding/astro-loader-pocketbase)\n */\nexport type PocketBaseEntry = z.infer<typeof pocketbaseEntrySchema>;\n\n/**\n * Checks if the given data is a PocketBase entry.\n */\nexport function isPocketbaseEntry(data: unknown): data is PocketBaseEntry {\n try {\n // Try to parse the data with the PocketBase entry schema\n pocketbaseEntrySchema.parse(data);\n return true;\n } catch {\n return false;\n }\n}\n","import { defineMiddleware } from \"astro/middleware\";\nimport type { PocketBaseEntry } from \"./is-pocketbase-entry\";\nimport { isPocketbaseEntry } from \"./is-pocketbase-entry\";\n\nexport const onRequest = defineMiddleware(async (context, next) => {\n // Look for entities given as props to the page\n const props = Object.values(context.props);\n const entities = findEntitiesRecursive(props).map((entity) => entity.data);\n\n const response = await next();\n const contentType = response.headers.get(\"content-type\");\n if (!contentType?.includes(\"text/html\")) {\n // Pass through non-HTML responses unchanged\n return response;\n }\n\n const body = await response.text();\n\n // Append the entities to the <head>\n const entitiesJson = JSON.stringify(entities);\n const newBody = body.replace(\n \"</head>\",\n `<script>window.__astro_entities__ = ${entitiesJson}</script></head>`\n );\n\n return new Response(newBody, response);\n});\n\n/**\n * Find PocketBase entities in the given data.\n */\nfunction findEntitiesRecursive(data: unknown): Array<PocketBaseEntry> {\n // Check if the data is an array and search for entities in each element\n if (Array.isArray(data)) {\n return data.flatMap((item) => findEntitiesRecursive(item));\n }\n\n if (typeof data === \"object\" && data !== null) {\n // Check if the data is an object and a PocketBase entry\n if (isPocketbaseEntry(data)) {\n return [data];\n }\n\n // Search for entities in all values\n return findEntitiesRecursive(Object.values(data));\n }\n\n // No entities found\n return [];\n}\n"],"mappings":";;;;;;AAKA,MAAM,wBAAwB,EAAE,OAAO;CACrC,IAAI,EAAE,OAAO;CACb,MAAM,EAAE,OAAO;EACb,IAAI,EAAE,OAAO;EACb,cAAc,EAAE,OAAO;EACvB,gBAAgB,EAAE,OAAO;CAC3B,CAAC;CACD,QAAQ,EAAE,OAAO,
|
|
1
|
+
{"version":3,"file":"middleware.mjs","names":[],"sources":["../src/middleware/is-pocketbase-entry.ts","../src/middleware/index.ts"],"sourcesContent":["import { z } from \"astro/zod\";\n\n/**\n * Schema for a PocketBase entry created with [astro-loader-pocketbase](https://github.com/pawcoding/astro-loader-pocketbase)\n */\nconst pocketbaseEntrySchema = z.object({\n id: z.string(),\n data: z.object({\n id: z.string(),\n collectionId: z.string(),\n collectionName: z.string()\n }),\n digest: z.string().length(16),\n collection: z.string()\n});\n\n/**\n * Type for a PocketBase entry created with [astro-loader-pocketbase](https://github.com/pawcoding/astro-loader-pocketbase)\n */\nexport type PocketBaseEntry = z.infer<typeof pocketbaseEntrySchema>;\n\n/**\n * Checks if the given data is a PocketBase entry.\n */\nexport function isPocketbaseEntry(data: unknown): data is PocketBaseEntry {\n try {\n // Try to parse the data with the PocketBase entry schema\n pocketbaseEntrySchema.parse(data);\n return true;\n } catch {\n return false;\n }\n}\n","import { defineMiddleware } from \"astro/middleware\";\nimport type { PocketBaseEntry } from \"./is-pocketbase-entry\";\nimport { isPocketbaseEntry } from \"./is-pocketbase-entry\";\n\nexport const onRequest = defineMiddleware(async (context, next) => {\n // Look for entities given as props to the page\n const props = Object.values(context.props);\n const entities = findEntitiesRecursive(props).map((entity) => entity.data);\n\n const response = await next();\n const contentType = response.headers.get(\"content-type\");\n if (!contentType?.includes(\"text/html\")) {\n // Pass through non-HTML responses unchanged\n return response;\n }\n\n const body = await response.text();\n\n // Append the entities to the <head>\n const entitiesJson = JSON.stringify(entities);\n const newBody = body.replace(\n \"</head>\",\n `<script>window.__astro_entities__ = ${entitiesJson}</script></head>`\n );\n\n return new Response(newBody, response);\n});\n\n/**\n * Find PocketBase entities in the given data.\n */\nfunction findEntitiesRecursive(data: unknown): Array<PocketBaseEntry> {\n // Check if the data is an array and search for entities in each element\n if (Array.isArray(data)) {\n return data.flatMap((item) => findEntitiesRecursive(item));\n }\n\n if (typeof data === \"object\" && data !== null) {\n // Check if the data is an object and a PocketBase entry\n if (isPocketbaseEntry(data)) {\n return [data];\n }\n\n // Search for entities in all values\n return findEntitiesRecursive(Object.values(data));\n }\n\n // No entities found\n return [];\n}\n"],"mappings":";;;;;;AAKA,MAAM,wBAAwB,EAAE,OAAO;CACrC,IAAI,EAAE,OAAO;CACb,MAAM,EAAE,OAAO;EACb,IAAI,EAAE,OAAO;EACb,cAAc,EAAE,OAAO;EACvB,gBAAgB,EAAE,OAAO;CAC3B,CAAC;CACD,QAAQ,EAAE,OAAO,CAAC,CAAC,OAAO,EAAE;CAC5B,YAAY,EAAE,OAAO;AACvB,CAAC;;;;AAUD,SAAgB,kBAAkB,MAAwC;CACxE,IAAI;EAEF,sBAAsB,MAAM,IAAI;EAChC,OAAO;CACT,QAAQ;EACN,OAAO;CACT;AACF;;;AC5BA,MAAa,YAAY,iBAAiB,OAAO,SAAS,SAAS;CAGjE,MAAM,WAAW,sBADH,OAAO,OAAO,QAAQ,KACO,CAAC,CAAC,CAAC,KAAK,WAAW,OAAO,IAAI;CAEzE,MAAM,WAAW,MAAM,KAAK;CAE5B,IAAI,CADgB,SAAS,QAAQ,IAAI,cAC1B,CAAC,EAAE,SAAS,WAAW,GAEpC,OAAO;CAGT,MAAM,OAAO,MAAM,SAAS,KAAK;CAGjC,MAAM,eAAe,KAAK,UAAU,QAAQ;CAC5C,MAAM,UAAU,KAAK,QACnB,WACA,uCAAuC,aAAa,kBACtD;CAEA,OAAO,IAAI,SAAS,SAAS,QAAQ;AACvC,CAAC;;;;AAKD,SAAS,sBAAsB,MAAuC;CAEpE,IAAI,MAAM,QAAQ,IAAI,GACpB,OAAO,KAAK,SAAS,SAAS,sBAAsB,IAAI,CAAC;CAG3D,IAAI,OAAO,SAAS,YAAY,SAAS,MAAM;EAE7C,IAAI,kBAAkB,IAAI,GACxB,OAAO,CAAC,IAAI;EAId,OAAO,sBAAsB,OAAO,OAAO,IAAI,CAAC;CAClD;CAGA,OAAO,CAAC;AACV"}
|
package/dist/toolbar.mjs
CHANGED
package/dist/toolbar.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"toolbar.mjs","names":["packageJson.version"],"sources":["../src/toolbar/dom/create-entity.ts","../package.json","../src/toolbar/dom/create-header.ts","../src/toolbar/dom/create-placeholder.ts","../src/toolbar/init-toolbar.ts","../src/toolbar/index.ts"],"sourcesContent":["import type { Entity } from \"../types/entity\";\n\n/**\n * Creates cards for the entities.\n */\nexport function createEntities(data: Array<Entity>, baseUrl: string): string {\n const groupedData = Object.groupBy(data, (data) => data.collectionName);\n const collections = Object.keys(groupedData);\n\n return /* HTML */ `\n <style>\n .collectionName {\n text-transform: capitalize;\n }\n\n .entity {\n position: relative;\n\n pre {\n margin: 0;\n overflow: auto;\n }\n\n astro-dev-toolbar-button {\n position: absolute;\n top: 0;\n right: 0;\n }\n }\n </style>\n\n ${collections\n .map(\n (collection) => /* HTML */ `\n <b class=\".collectionName\">${collection}</b>\n ${groupedData[collection]\n ?.map((entity) => createEntity(entity, baseUrl))\n .join(\"\")}\n `\n )\n .join(\"\")}\n `;\n}\n\n/**\n * Creates a card for a single entity\n */\nfunction createEntity(data: Entity, baseUrl: string): string {\n return /* HTML */ `\n <astro-dev-toolbar-card>\n <div class=\"entity\">\n <pre>${JSON.stringify(data, undefined, 2).replaceAll(\"<\", \"<\")}</pre>\n\n ${baseUrl\n ? /* HTML */ `\n <astro-dev-toolbar-button\n size=\"small\"\n button-style=\"purple\"\n title=\"View in PocketBase\"\n onclick=\"window.open('${baseUrl}/_/#/collections?collection=${data.collectionId}&recordId=${data.id}&record=${data.id}', '_blank')\"\n >\n View in PocketBase\n </astro-dev-toolbar-button>\n `\n : \"\"}\n </div>\n </astro-dev-toolbar-card>\n `;\n}\n","","import type { ToolbarServerHelpers } from \"astro\";\nimport type { DevToolbarButton } from \"astro/runtime/client/dev-toolbar/ui-library/button.js\";\nimport type { DevToolbarWindow } from \"astro/runtime/client/dev-toolbar/ui-library/window.js\";\nimport { default as packageJson } from \"../../../package.json\";\nimport type { ToolbarOptions } from \"../types/options\";\n\n/**\n * Creates the header for the PocketBase toolbar.\n */\n// oxlint-disable-next-line max-lines-per-function\nexport function createHeader(\n windowElement: DevToolbarWindow,\n server: ToolbarServerHelpers,\n { hasContentLoader, realtime }: ToolbarOptions\n): void {\n const header = windowElement.querySelector(\"header\");\n if (!header) {\n throw new Error(\"The header element is missing\");\n }\n\n header.innerHTML = /* HTML */ `\n <style>\n header {\n display: grid;\n grid-template-columns: auto auto 1fr;\n gap: 0.5rem;\n }\n\n h1 {\n display: flex;\n align-items: center;\n gap: 8px;\n font-weight: 600;\n color: #fff;\n margin: 0;\n font-size: 22px;\n }\n\n .actions {\n display: flex;\n align-items: start;\n justify-content: flex-end;\n gap: 0.25rem;\n\n .toggle-container {\n display: flex;\n align-items: center;\n\n label {\n font-size: 0.8rem;\n }\n }\n }\n </style>\n\n <h1>PocketBase</h1>\n <astro-dev-toolbar-badge badge-style=\"yellow\">\n ${packageJson.version}\n </astro-dev-toolbar-badge>\n\n <div class=\"actions\">\n ${realtime\n ? /* HTML */ `\n <div class=\"toggle-container\">\n <label\n for=\"real-time\"\n title=\"Enable or disable real-time updates temporarily\"\n >\n Real-time updates\n </label>\n <!-- real-time-toggle -->\n </div>\n `\n : \"\"}\n ${hasContentLoader\n ? /* HTML */ `\n <astro-dev-toolbar-button\n id=\"refresh-content\"\n size=\"small\"\n button-style=\"green\"\n title=\"Right click to force refresh every collection\"\n >\n Refresh content\n </astro-dev-toolbar-button>\n `\n : \"\"}\n </div>\n `;\n\n if (realtime) {\n // Create the toggle for real-time updates\n const realTimeToggle = document.createElement(\"astro-dev-toolbar-toggle\");\n realTimeToggle.input.id = \"real-time-toggle\";\n realTimeToggle.input.title =\n \"Enable or disable real-time updates temporarily\";\n // Set the toggle state based on the local storage, default to true\n realTimeToggle.input.checked = !(\n localStorage.getItem(\"astro-integration-pocketbase:real-time\") === \"false\"\n );\n realTimeToggle.input.addEventListener(\"change\", () => {\n // Store the toggle state in the local storage\n localStorage.setItem(\n \"astro-integration-pocketbase:real-time\",\n realTimeToggle.input.checked.toString()\n );\n\n // Send the toggle state to the server\n server.send(\n \"astro-integration-pocketbase:real-time\",\n realTimeToggle.input.checked\n );\n });\n // Send the initial toggle state to the server\n server.send(\n \"astro-integration-pocketbase:real-time\",\n realTimeToggle.input.checked\n );\n windowElement.querySelector(\".toggle-container\")?.append(realTimeToggle);\n }\n\n if (hasContentLoader) {\n // Add click listeners to the refresh button\n const refresh =\n windowElement.querySelector<DevToolbarButton>(\"#refresh-content\");\n if (!refresh) {\n throw new Error(\"The refresh button is missing\");\n }\n\n refresh.addEventListener(\"click\", () => {\n server.send(\"astro-integration-pocketbase:refresh\", { force: false });\n });\n refresh.addEventListener(\"contextmenu\", (event) => {\n event.preventDefault();\n server.send(\"astro-integration-pocketbase:refresh\", { force: true });\n });\n\n server.on(\n \"astro-integration-pocketbase:refresh\",\n ({ loading }: { loading?: boolean }) => {\n // Show loading state while refreshing content\n if (loading) {\n refresh.textContent = \"Refreshing content...\";\n refresh.buttonStyle = \"gray\";\n refresh.style.pointerEvents = \"none\";\n } else {\n refresh.textContent = \"Refresh content\";\n refresh.buttonStyle = \"green\";\n refresh.style.pointerEvents = \"unset\";\n }\n }\n );\n }\n}\n","/**\n * Creates a placeholder card.\n */\nexport function createPlaceholder(): string {\n return /* HTML */ `\n <style>\n #placeholder div {\n display: flex;\n align-items: center;\n justify-content: center;\n }\n </style>\n\n <astro-dev-toolbar-card id=\"placeholder\">\n <div>\n <span> Here you will see the raw content of an entity </span>\n </div>\n </astro-dev-toolbar-card>\n `;\n}\n","import {\n closeOnOutsideClick,\n createWindowElement,\n synchronizePlacementOnUpdate\n} from \"astro/runtime/client/dev-toolbar/apps/utils/window.js\";\nimport type {\n ToolbarAppEventTarget,\n ToolbarServerHelpers\n} from \"astro/runtime/client/dev-toolbar/helpers.js\";\nimport { createEntities, createHeader, createPlaceholder } from \"./dom\";\nimport type { Entity } from \"./types/entity\";\nimport type { ToolbarOptions } from \"./types/options\";\n\ndeclare global {\n interface Window {\n __astro_entities__?: Array<Entity>;\n }\n}\n\n/**\n * Initializes the PocketBase toolbar.\n */\nexport function initToolbar(\n canvas: ShadowRoot,\n app: ToolbarAppEventTarget,\n server: ToolbarServerHelpers\n): void {\n // Options for the toolbar\n let options: ToolbarOptions = {\n realtime: false,\n hasContentLoader: false,\n baseUrl: \"\"\n };\n\n // Update the options and refresh the toolbar\n server.on(\n \"astro-integration-pocketbase:settings\",\n (updatedOptions: ToolbarOptions) => {\n options = updatedOptions;\n createPocketBaseWindow();\n }\n );\n\n // Create the window (for every page navigation)\n createPocketBaseWindow();\n document.addEventListener(\"astro:after-swap\", createPocketBaseWindow);\n\n // Setup the window\n closeOnOutsideClick(app);\n synchronizePlacementOnUpdate(app, canvas);\n\n function createPocketBaseWindow(): void {\n // Clear any existing content\n canvas.innerHTML = \"\";\n\n const entities = window.__astro_entities__ || [];\n\n // Create the main window element\n const windowElement = createWindowElement(/* HTML */ `\n <style>\n :host astro-dev-toolbar-window {\n max-height: 480px;\n }\n\n main {\n display: flex;\n flex-direction: column;\n gap: 1rem;\n overflow-y: auto;\n }\n </style>\n\n <header></header>\n\n <hr />\n\n <main>\n ${entities.length > 0\n ? createEntities(entities, options.baseUrl)\n : createPlaceholder()}\n </main>\n `);\n\n // Create and insert the header\n createHeader(windowElement, server, options);\n\n // Add the window to the canvas\n canvas.append(windowElement);\n\n // Update the toolbar depending on the current state\n if (entities.length > 0) {\n app.toggleNotification({ state: true, level: \"info\" });\n } else {\n app.toggleNotification({ state: false });\n app.toggleState({ state: false });\n }\n }\n}\n","import { defineToolbarApp } from \"astro/toolbar\";\nimport { initToolbar } from \"./init-toolbar\";\n\nexport default defineToolbarApp({\n init: initToolbar\n});\n"],"mappings":";;;;;;AAKA,SAAgB,eAAe,MAAqB,SAAyB;CAC3E,MAAM,cAAc,OAAO,QAAQ,OAAO,SAAS,KAAK,cAAc;CAGtE,OAAkB;;;;;;;;;;;;;;;;;;;;;;MAFE,OAAO,KAAK,WAwBlB,EACT,KACE,eAA0B;uCACI,WAAW;YACtC,YAAY,aACV,KAAK,WAAW,aAAa,QAAQ,OAAO,CAAC,EAC9C,KAAK,EAAE,EAAE;SAEhB,EACC,KAAK,EAAE,EAAE;;AAEhB;;;;AAKA,SAAS,aAAa,MAAc,SAAyB;CAC3D,OAAkB;;;eAGL,KAAK,UAAU,MAAM,KAAA,GAAW,CAAC,EAAE,WAAW,KAAK,MAAM,EAAE;;UAEhE,UACa;;;;;wCAKiB,QAAQ,8BAA8B,KAAK,aAAa,YAAY,KAAK,GAAG,UAAU,KAAK,GAAG;;;;gBAK1H,GAAG;;;;AAIf;;;;;;;;;AE1DA,SAAgB,aACd,eACA,QACA,EAAE,kBAAkB,YACd;CACN,MAAM,SAAS,cAAc,cAAc,QAAQ;CACnD,IAAI,CAAC,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N,IAAI,UAA0B;EAC5B,UAAU;EACV,kBAAkB;EAClB,SAAS;CACX;CAGA,OAAO,GACL,0CACC,mBAAmC;EAClC,UAAU;EACV,uBAAuB;CACzB,CACF;CAGA,uBAAuB;CACvB,SAAS,iBAAiB,oBAAoB,sBAAsB;CAGpE,oBAAoB,GAAG;CACvB,6BAA6B,KAAK,MAAM;CAExC,SAAS,yBAA+B;EAEtC,OAAO,YAAY;EAEnB,MAAM,WAAW,OAAO,sBAAsB,CAAC;EAG/C,MAAM,gBAAgB,oBAA+B;;;;;;;;;;;;;;;;;;;UAmB/C,SAAS,SAAS,IAChB,eAAe,UAAU,QAAQ,OAAO,IACxC,kBAAkB,EAAE;;KAE3B;EAGD,aAAa,eAAe,QAAQ,OAAO;EAG3C,OAAO,OAAO,aAAa;EAG3B,IAAI,SAAS,SAAS,GACpB,IAAI,mBAAmB;GAAE,OAAO;GAAM,OAAO;EAAO,CAAC;OAChD;GACL,IAAI,mBAAmB,EAAE,OAAO,MAAM,CAAC;GACvC,IAAI,YAAY,EAAE,OAAO,MAAM,CAAC;EAClC;CACF;AACF;;;AC9FA,IAAA,kBAAe,iBAAiB,EAC9B,MAAM,YACR,CAAC"}
|
|
1
|
+
{"version":3,"file":"toolbar.mjs","names":["packageJson.version"],"sources":["../src/toolbar/dom/create-entity.ts","../package.json","../src/toolbar/dom/create-header.ts","../src/toolbar/dom/create-placeholder.ts","../src/toolbar/init-toolbar.ts","../src/toolbar/index.ts"],"sourcesContent":["import type { Entity } from \"../types/entity\";\n\n/**\n * Creates cards for the entities.\n */\nexport function createEntities(data: Array<Entity>, baseUrl: string): string {\n const groupedData = Object.groupBy(data, (data) => data.collectionName);\n const collections = Object.keys(groupedData);\n\n return /* HTML */ `\n <style>\n .collectionName {\n text-transform: capitalize;\n }\n\n .entity {\n position: relative;\n\n pre {\n margin: 0;\n overflow: auto;\n }\n\n astro-dev-toolbar-button {\n position: absolute;\n top: 0;\n right: 0;\n }\n }\n </style>\n\n ${collections\n .map(\n (collection) => /* HTML */ `\n <b class=\".collectionName\">${collection}</b>\n ${groupedData[collection]\n ?.map((entity) => createEntity(entity, baseUrl))\n .join(\"\")}\n `\n )\n .join(\"\")}\n `;\n}\n\n/**\n * Creates a card for a single entity\n */\nfunction createEntity(data: Entity, baseUrl: string): string {\n return /* HTML */ `\n <astro-dev-toolbar-card>\n <div class=\"entity\">\n <pre>${JSON.stringify(data, undefined, 2).replaceAll(\"<\", \"<\")}</pre>\n\n ${baseUrl\n ? /* HTML */ `\n <astro-dev-toolbar-button\n size=\"small\"\n button-style=\"purple\"\n title=\"View in PocketBase\"\n onclick=\"window.open('${baseUrl}/_/#/collections?collection=${data.collectionId}&recordId=${data.id}&record=${data.id}', '_blank')\"\n >\n View in PocketBase\n </astro-dev-toolbar-button>\n `\n : \"\"}\n </div>\n </astro-dev-toolbar-card>\n `;\n}\n","","import type { ToolbarServerHelpers } from \"astro\";\nimport type { DevToolbarButton } from \"astro/runtime/client/dev-toolbar/ui-library/button.js\";\nimport type { DevToolbarWindow } from \"astro/runtime/client/dev-toolbar/ui-library/window.js\";\nimport { default as packageJson } from \"../../../package.json\";\nimport type { ToolbarOptions } from \"../types/options\";\n\n/**\n * Creates the header for the PocketBase toolbar.\n */\n// oxlint-disable-next-line max-lines-per-function\nexport function createHeader(\n windowElement: DevToolbarWindow,\n server: ToolbarServerHelpers,\n { hasContentLoader, realtime }: ToolbarOptions\n): void {\n const header = windowElement.querySelector(\"header\");\n if (!header) {\n throw new Error(\"The header element is missing\");\n }\n\n header.innerHTML = /* HTML */ `\n <style>\n header {\n display: grid;\n grid-template-columns: auto auto 1fr;\n gap: 0.5rem;\n }\n\n h1 {\n display: flex;\n align-items: center;\n gap: 8px;\n font-weight: 600;\n color: #fff;\n margin: 0;\n font-size: 22px;\n }\n\n .actions {\n display: flex;\n align-items: start;\n justify-content: flex-end;\n gap: 0.25rem;\n\n .toggle-container {\n display: flex;\n align-items: center;\n\n label {\n font-size: 0.8rem;\n }\n }\n }\n </style>\n\n <h1>PocketBase</h1>\n <astro-dev-toolbar-badge badge-style=\"yellow\">\n ${packageJson.version}\n </astro-dev-toolbar-badge>\n\n <div class=\"actions\">\n ${realtime\n ? /* HTML */ `\n <div class=\"toggle-container\">\n <label\n for=\"real-time\"\n title=\"Enable or disable real-time updates temporarily\"\n >\n Real-time updates\n </label>\n <!-- real-time-toggle -->\n </div>\n `\n : \"\"}\n ${hasContentLoader\n ? /* HTML */ `\n <astro-dev-toolbar-button\n id=\"refresh-content\"\n size=\"small\"\n button-style=\"green\"\n title=\"Right click to force refresh every collection\"\n >\n Refresh content\n </astro-dev-toolbar-button>\n `\n : \"\"}\n </div>\n `;\n\n if (realtime) {\n // Create the toggle for real-time updates\n const realTimeToggle = document.createElement(\"astro-dev-toolbar-toggle\");\n realTimeToggle.input.id = \"real-time-toggle\";\n realTimeToggle.input.title =\n \"Enable or disable real-time updates temporarily\";\n // Set the toggle state based on the local storage, default to true\n realTimeToggle.input.checked = !(\n localStorage.getItem(\"astro-integration-pocketbase:real-time\") === \"false\"\n );\n realTimeToggle.input.addEventListener(\"change\", () => {\n // Store the toggle state in the local storage\n localStorage.setItem(\n \"astro-integration-pocketbase:real-time\",\n realTimeToggle.input.checked.toString()\n );\n\n // Send the toggle state to the server\n server.send(\n \"astro-integration-pocketbase:real-time\",\n realTimeToggle.input.checked\n );\n });\n // Send the initial toggle state to the server\n server.send(\n \"astro-integration-pocketbase:real-time\",\n realTimeToggle.input.checked\n );\n windowElement.querySelector(\".toggle-container\")?.append(realTimeToggle);\n }\n\n if (hasContentLoader) {\n // Add click listeners to the refresh button\n const refresh =\n windowElement.querySelector<DevToolbarButton>(\"#refresh-content\");\n if (!refresh) {\n throw new Error(\"The refresh button is missing\");\n }\n\n refresh.addEventListener(\"click\", () => {\n server.send(\"astro-integration-pocketbase:refresh\", { force: false });\n });\n refresh.addEventListener(\"contextmenu\", (event) => {\n event.preventDefault();\n server.send(\"astro-integration-pocketbase:refresh\", { force: true });\n });\n\n server.on(\n \"astro-integration-pocketbase:refresh\",\n ({ loading }: { loading?: boolean }) => {\n // Show loading state while refreshing content\n if (loading) {\n refresh.textContent = \"Refreshing content...\";\n refresh.buttonStyle = \"gray\";\n refresh.style.pointerEvents = \"none\";\n } else {\n refresh.textContent = \"Refresh content\";\n refresh.buttonStyle = \"green\";\n refresh.style.pointerEvents = \"unset\";\n }\n }\n );\n }\n}\n","/**\n * Creates a placeholder card.\n */\nexport function createPlaceholder(): string {\n return /* HTML */ `\n <style>\n #placeholder div {\n display: flex;\n align-items: center;\n justify-content: center;\n }\n </style>\n\n <astro-dev-toolbar-card id=\"placeholder\">\n <div>\n <span> Here you will see the raw content of an entity </span>\n </div>\n </astro-dev-toolbar-card>\n `;\n}\n","import {\n closeOnOutsideClick,\n createWindowElement,\n synchronizePlacementOnUpdate\n} from \"astro/runtime/client/dev-toolbar/apps/utils/window.js\";\nimport type {\n ToolbarAppEventTarget,\n ToolbarServerHelpers\n} from \"astro/runtime/client/dev-toolbar/helpers.js\";\nimport { createEntities, createHeader, createPlaceholder } from \"./dom\";\nimport type { Entity } from \"./types/entity\";\nimport type { ToolbarOptions } from \"./types/options\";\n\ndeclare global {\n interface Window {\n __astro_entities__?: Array<Entity>;\n }\n}\n\n/**\n * Initializes the PocketBase toolbar.\n */\nexport function initToolbar(\n canvas: ShadowRoot,\n app: ToolbarAppEventTarget,\n server: ToolbarServerHelpers\n): void {\n // Options for the toolbar\n let options: ToolbarOptions = {\n realtime: false,\n hasContentLoader: false,\n baseUrl: \"\"\n };\n\n // Update the options and refresh the toolbar\n server.on(\n \"astro-integration-pocketbase:settings\",\n (updatedOptions: ToolbarOptions) => {\n options = updatedOptions;\n createPocketBaseWindow();\n }\n );\n\n // Create the window (for every page navigation)\n createPocketBaseWindow();\n document.addEventListener(\"astro:after-swap\", createPocketBaseWindow);\n\n // Setup the window\n closeOnOutsideClick(app);\n synchronizePlacementOnUpdate(app, canvas);\n\n function createPocketBaseWindow(): void {\n // Clear any existing content\n canvas.innerHTML = \"\";\n\n const entities = window.__astro_entities__ || [];\n\n // Create the main window element\n const windowElement = createWindowElement(/* HTML */ `\n <style>\n :host astro-dev-toolbar-window {\n max-height: 480px;\n }\n\n main {\n display: flex;\n flex-direction: column;\n gap: 1rem;\n overflow-y: auto;\n }\n </style>\n\n <header></header>\n\n <hr />\n\n <main>\n ${entities.length > 0\n ? createEntities(entities, options.baseUrl)\n : createPlaceholder()}\n </main>\n `);\n\n // Create and insert the header\n createHeader(windowElement, server, options);\n\n // Add the window to the canvas\n canvas.append(windowElement);\n\n // Update the toolbar depending on the current state\n if (entities.length > 0) {\n app.toggleNotification({ state: true, level: \"info\" });\n } else {\n app.toggleNotification({ state: false });\n app.toggleState({ state: false });\n }\n }\n}\n","import { defineToolbarApp } from \"astro/toolbar\";\nimport { initToolbar } from \"./init-toolbar\";\n\nexport default defineToolbarApp({\n init: initToolbar\n});\n"],"mappings":";;;;;;AAKA,SAAgB,eAAe,MAAqB,SAAyB;CAC3E,MAAM,cAAc,OAAO,QAAQ,OAAO,SAAS,KAAK,cAAc;CAGtE,OAAkB;;;;;;;;;;;;;;;;;;;;;;MAFE,OAAO,KAAK,WAwBlB,CAAC,CACV,KACE,eAA0B;uCACI,WAAW;YACtC,YAAY,WAAW,EACrB,KAAK,WAAW,aAAa,QAAQ,OAAO,CAAC,CAAC,CAC/C,KAAK,EAAE,EAAE;SAEhB,CAAC,CACA,KAAK,EAAE,EAAE;;AAEhB;;;;AAKA,SAAS,aAAa,MAAc,SAAyB;CAC3D,OAAkB;;;eAGL,KAAK,UAAU,MAAM,KAAA,GAAW,CAAC,CAAC,CAAC,WAAW,KAAK,MAAM,EAAE;;UAEhE,UACa;;;;;wCAKiB,QAAQ,8BAA8B,KAAK,aAAa,YAAY,KAAK,GAAG,UAAU,KAAK,GAAG;;;;gBAK1H,GAAG;;;;AAIf;;;;;;;;;AE1DA,SAAgB,aACd,eACA,QACA,EAAE,kBAAkB,YACd;CACN,MAAM,SAAS,cAAc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;;ACGA,SAAgB,YACd,QACA,KACA,QACM;CAEN,IAAI,UAA0B;EAC5B,UAAU;EACV,kBAAkB;EAClB,SAAS;CACX;CAGA,OAAO,GACL,0CACC,mBAAmC;EAClC,UAAU;EACV,uBAAuB;CACzB,CACF;CAGA,uBAAuB;CACvB,SAAS,iBAAiB,oBAAoB,sBAAsB;CAGpE,oBAAoB,GAAG;CACvB,6BAA6B,KAAK,MAAM;CAExC,SAAS,yBAA+B;EAEtC,OAAO,YAAY;EAEnB,MAAM,WAAW,OAAO,sBAAsB,CAAC;EAG/C,MAAM,gBAAgB,oBAA+B;;;;;;;;;;;;;;;;;;;UAmB/C,SAAS,SAAS,IAChB,eAAe,UAAU,QAAQ,OAAO,IACxC,kBAAkB,EAAE;;KAE3B;EAGD,aAAa,eAAe,QAAQ,OAAO;EAG3C,OAAO,OAAO,aAAa;EAG3B,IAAI,SAAS,SAAS,GACpB,IAAI,mBAAmB;GAAE,OAAO;GAAM,OAAO;EAAO,CAAC;OAChD;GACL,IAAI,mBAAmB,EAAE,OAAO,MAAM,CAAC;GACvC,IAAI,YAAY,EAAE,OAAO,MAAM,CAAC;EAClC;CACF;AACF;;;AC9FA,IAAA,kBAAe,iBAAiB,EAC9B,MAAM,YACR,CAAC"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "astro-integration-pocketbase",
|
|
3
|
-
"version": "3.1.
|
|
3
|
+
"version": "3.1.3",
|
|
4
4
|
"description": "An Astro integration to support developers working with astro-loader-pocketbase.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"astro",
|
|
@@ -50,17 +50,17 @@
|
|
|
50
50
|
"devDependencies": {
|
|
51
51
|
"@commitlint/cli": "21.0.2",
|
|
52
52
|
"@commitlint/config-conventional": "21.0.2",
|
|
53
|
-
"@types/node": "24.
|
|
54
|
-
"astro": "6.4.
|
|
53
|
+
"@types/node": "24.13.2",
|
|
54
|
+
"astro": "6.4.6",
|
|
55
55
|
"eventsource": "4.1.0",
|
|
56
56
|
"globals": "17.6.0",
|
|
57
57
|
"husky": "9.1.7",
|
|
58
|
-
"lint-staged": "17.0.
|
|
59
|
-
"oxfmt": "0.
|
|
60
|
-
"oxlint": "1.
|
|
58
|
+
"lint-staged": "17.0.7",
|
|
59
|
+
"oxfmt": "0.54.0",
|
|
60
|
+
"oxlint": "1.69.0",
|
|
61
61
|
"oxlint-tsgolint": "0.23.0",
|
|
62
62
|
"publint": "0.3.21",
|
|
63
|
-
"tsdown": "0.22.
|
|
63
|
+
"tsdown": "0.22.2"
|
|
64
64
|
},
|
|
65
65
|
"peerDependencies": {
|
|
66
66
|
"astro": "^6.0.0",
|
|
@@ -69,5 +69,8 @@
|
|
|
69
69
|
"engines": {
|
|
70
70
|
"node": ">=22.12.0"
|
|
71
71
|
},
|
|
72
|
-
"packageManager": "npm@11.
|
|
72
|
+
"packageManager": "npm@11.17.0",
|
|
73
|
+
"allowScripts": {
|
|
74
|
+
"esbuild@0.27.7": true
|
|
75
|
+
}
|
|
73
76
|
}
|