@perses-dev/plugin-system 0.53.1 → 0.54.0-beta.1
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/cjs/components/CalculationSelector/CalculationSelector.js +3 -3
- package/dist/cjs/components/DatasourceEditorForm/DatasourceEditorForm.js +2 -3
- package/dist/cjs/components/LegendOptionsEditor/LegendOptionsEditor.js +4 -5
- package/dist/cjs/components/TimeRangeControls/TimeRangeControls.js +2 -2
- package/dist/cjs/components/Variables/VariableEditorForm/VariableEditorForm.js +2 -3
- package/dist/cjs/context/ValidationProvider.js +5 -4
- package/dist/cjs/model/calculations.js +178 -0
- package/dist/cjs/model/index.js +3 -0
- package/dist/cjs/model/legend.js +6 -5
- package/dist/cjs/model/log-volume-utils.js +124 -0
- package/dist/cjs/model/time-series-queries.js +10 -0
- package/dist/cjs/remote/PluginRuntime.js +11 -10
- package/dist/cjs/runtime/TimeRangeProvider/TimeRangeProvider.js +6 -6
- package/dist/cjs/runtime/TimeRangeProvider/query-params.js +7 -7
- package/dist/cjs/runtime/TimeRangeProvider/refresh-interval.js +2 -2
- package/dist/cjs/test/utils.js +2 -2
- package/dist/cjs/utils/index.js +0 -1
- package/dist/components/CalculationSelector/CalculationSelector.d.ts +1 -1
- package/dist/components/CalculationSelector/CalculationSelector.d.ts.map +1 -1
- package/dist/components/CalculationSelector/CalculationSelector.js +1 -1
- package/dist/components/CalculationSelector/CalculationSelector.js.map +1 -1
- package/dist/components/DatasourceEditorForm/DatasourceEditorForm.d.ts +2 -1
- package/dist/components/DatasourceEditorForm/DatasourceEditorForm.d.ts.map +1 -1
- package/dist/components/DatasourceEditorForm/DatasourceEditorForm.js +1 -2
- package/dist/components/DatasourceEditorForm/DatasourceEditorForm.js.map +1 -1
- package/dist/components/DatasourceSelect/DatasourceSelect.d.ts +1 -1
- package/dist/components/DatasourceSelect/DatasourceSelect.js.map +1 -1
- package/dist/components/HTTPSettingsEditor/HTTPSettingsEditor.js.map +1 -1
- package/dist/components/LegendOptionsEditor/LegendOptionsEditor.d.ts.map +1 -1
- package/dist/components/LegendOptionsEditor/LegendOptionsEditor.js +1 -2
- package/dist/components/LegendOptionsEditor/LegendOptionsEditor.js.map +1 -1
- package/dist/components/MultiQueryEditor/MultiQueryEditor.d.ts +1 -1
- package/dist/components/MultiQueryEditor/MultiQueryEditor.js.map +1 -1
- package/dist/components/MultiQueryEditor/QueryEditorContainer.d.ts +1 -1
- package/dist/components/MultiQueryEditor/QueryEditorContainer.js.map +1 -1
- package/dist/components/PanelSpecEditor/PanelSpecEditor.d.ts +1 -1
- package/dist/components/PanelSpecEditor/PanelSpecEditor.js.map +1 -1
- package/dist/components/PluginEditor/PluginEditor.js.map +1 -1
- package/dist/components/PluginEditor/plugin-editor-api.d.ts +1 -1
- package/dist/components/PluginEditor/plugin-editor-api.js.map +1 -1
- package/dist/components/PluginRegistry/PluginRegistry.js.map +1 -1
- package/dist/components/PluginSpecEditor/PluginSpecEditor.d.ts +1 -1
- package/dist/components/PluginSpecEditor/PluginSpecEditor.js.map +1 -1
- package/dist/components/TimeRangeControls/TimeRangeControls.js +1 -1
- package/dist/components/TimeRangeControls/TimeRangeControls.js.map +1 -1
- package/dist/components/Variables/VariableEditorForm/VariableEditorForm.d.ts +2 -1
- package/dist/components/Variables/VariableEditorForm/VariableEditorForm.d.ts.map +1 -1
- package/dist/components/Variables/VariableEditorForm/VariableEditorForm.js +1 -2
- package/dist/components/Variables/VariableEditorForm/VariableEditorForm.js.map +1 -1
- package/dist/components/Variables/VariableEditorForm/VariablePreview.d.ts +1 -1
- package/dist/components/Variables/VariableEditorForm/VariablePreview.js.map +1 -1
- package/dist/components/Variables/VariableEditorForm/variable-editor-form-model.d.ts +1 -1
- package/dist/components/Variables/VariableEditorForm/variable-editor-form-model.js.map +1 -1
- package/dist/components/Variables/variable-model.d.ts +1 -1
- package/dist/components/Variables/variable-model.js.map +1 -1
- package/dist/context/ValidationProvider.d.ts +2 -1
- package/dist/context/ValidationProvider.d.ts.map +1 -1
- package/dist/context/ValidationProvider.js +3 -2
- package/dist/context/ValidationProvider.js.map +1 -1
- package/dist/model/calculations.d.ts +45 -0
- package/dist/model/calculations.d.ts.map +1 -0
- package/dist/model/calculations.js +165 -0
- package/dist/model/calculations.js.map +1 -0
- package/dist/model/datasource.d.ts +8 -1
- package/dist/model/datasource.d.ts.map +1 -1
- package/dist/model/datasource.js +1 -1
- package/dist/model/datasource.js.map +1 -1
- package/dist/model/explore.d.ts +1 -1
- package/dist/model/explore.js.map +1 -1
- package/dist/model/index.d.ts +3 -0
- package/dist/model/index.d.ts.map +1 -1
- package/dist/model/index.js +3 -0
- package/dist/model/index.js.map +1 -1
- package/dist/model/legend.d.ts +3 -2
- package/dist/model/legend.d.ts.map +1 -1
- package/dist/model/legend.js +2 -1
- package/dist/model/legend.js.map +1 -1
- package/dist/model/log-queries.d.ts +2 -1
- package/dist/model/log-queries.d.ts.map +1 -1
- package/dist/model/log-queries.js.map +1 -1
- package/dist/model/log-volume-utils.d.ts +6 -0
- package/dist/model/log-volume-utils.d.ts.map +1 -0
- package/dist/model/log-volume-utils.js +119 -0
- package/dist/model/log-volume-utils.js.map +1 -0
- package/dist/model/panels.d.ts +1 -1
- package/dist/model/panels.js.map +1 -1
- package/dist/model/plugin-base.d.ts +1 -1
- package/dist/model/plugin-base.js.map +1 -1
- package/dist/model/plugins.d.ts +1 -1
- package/dist/model/plugins.js.map +1 -1
- package/dist/model/profile-queries.d.ts +1 -1
- package/dist/model/profile-queries.js.map +1 -1
- package/dist/model/time-series-queries.d.ts +11 -1
- package/dist/model/time-series-queries.d.ts.map +1 -1
- package/dist/model/time-series-queries.js +4 -1
- package/dist/model/time-series-queries.js.map +1 -1
- package/dist/model/trace-queries.d.ts +1 -1
- package/dist/model/trace-queries.js.map +1 -1
- package/dist/model/variables.d.ts +1 -1
- package/dist/model/variables.js.map +1 -1
- package/dist/remote/PluginRuntime.d.ts.map +1 -1
- package/dist/remote/PluginRuntime.js +11 -10
- package/dist/remote/PluginRuntime.js.map +1 -1
- package/dist/runtime/DataQueriesProvider/DataQueriesProvider.d.ts +1 -1
- package/dist/runtime/DataQueriesProvider/DataQueriesProvider.js.map +1 -1
- package/dist/runtime/DataQueriesProvider/model.d.ts +1 -1
- package/dist/runtime/DataQueriesProvider/model.js.map +1 -1
- package/dist/runtime/TimeRangeProvider/TimeRangeProvider.d.ts +1 -1
- package/dist/runtime/TimeRangeProvider/TimeRangeProvider.js +1 -1
- package/dist/runtime/TimeRangeProvider/TimeRangeProvider.js.map +1 -1
- package/dist/runtime/TimeRangeProvider/TimeRangeProviders.d.ts +1 -1
- package/dist/runtime/TimeRangeProvider/TimeRangeProviders.js.map +1 -1
- package/dist/runtime/TimeRangeProvider/TimeRangeSettingsProvider.js.map +1 -1
- package/dist/runtime/TimeRangeProvider/query-params.d.ts +1 -1
- package/dist/runtime/TimeRangeProvider/query-params.js +1 -1
- package/dist/runtime/TimeRangeProvider/query-params.js.map +1 -1
- package/dist/runtime/TimeRangeProvider/refresh-interval.d.ts +1 -1
- package/dist/runtime/TimeRangeProvider/refresh-interval.js +1 -1
- package/dist/runtime/TimeRangeProvider/refresh-interval.js.map +1 -1
- package/dist/runtime/UsageMetricsProvider.d.ts +1 -1
- package/dist/runtime/UsageMetricsProvider.d.ts.map +1 -1
- package/dist/runtime/UsageMetricsProvider.js +1 -1
- package/dist/runtime/UsageMetricsProvider.js.map +1 -1
- package/dist/runtime/builtin-variables.d.ts +1 -1
- package/dist/runtime/builtin-variables.js.map +1 -1
- package/dist/runtime/datasources.d.ts +1 -1
- package/dist/runtime/datasources.js.map +1 -1
- package/dist/runtime/item-actions.js +1 -1
- package/dist/runtime/item-actions.js.map +1 -1
- package/dist/runtime/log-queries.d.ts +1 -1
- package/dist/runtime/log-queries.js.map +1 -1
- package/dist/runtime/plugin-registry.d.ts +1 -1
- package/dist/runtime/plugin-registry.js.map +1 -1
- package/dist/runtime/profile-queries.d.ts +1 -1
- package/dist/runtime/profile-queries.js.map +1 -1
- package/dist/runtime/time-series-queries.d.ts +1 -1
- package/dist/runtime/time-series-queries.js.map +1 -1
- package/dist/runtime/trace-queries.d.ts +1 -1
- package/dist/runtime/trace-queries.js.map +1 -1
- package/dist/test/mock-data.d.ts +1 -1
- package/dist/test/mock-data.js.map +1 -1
- package/dist/test/utils.d.ts.map +1 -1
- package/dist/test/utils.js +1 -1
- package/dist/test/utils.js.map +1 -1
- package/dist/test-utils/mock-plugin-registry.js.map +1 -1
- package/dist/utils/index.d.ts +0 -1
- package/dist/utils/index.d.ts.map +1 -1
- package/dist/utils/index.js +0 -1
- package/dist/utils/index.js.map +1 -1
- package/package.json +8 -5
- package/dist/cjs/utils/action.js +0 -43
- package/dist/utils/action.d.ts +0 -4
- package/dist/utils/action.d.ts.map +0 -1
- package/dist/utils/action.js +0 -27
- package/dist/utils/action.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/runtime/datasources.ts"],"sourcesContent":["// Copyright The Perses Authors\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\nimport { DatasourceSelector, DatasourceSpec } from '@perses-dev/
|
|
1
|
+
{"version":3,"sources":["../../src/runtime/datasources.ts"],"sourcesContent":["// Copyright The Perses Authors\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\nimport { DatasourceSelector, DatasourceSpec } from '@perses-dev/spec';\nimport { useQuery, UseQueryResult } from '@tanstack/react-query';\nimport { createContext, useContext } from 'react';\n\nexport interface DatasourceStore {\n // TODO: Do we even need this method?\n getDatasource(selector: DatasourceSelector): Promise<DatasourceSpec>;\n\n /**\n * Given a DatasourceSelector, gets a `Client` object from the corresponding Datasource plugin.\n */\n getDatasourceClient<Client>(selector: DatasourceSelector): Promise<Client>;\n\n /**\n * Gets a list of datasource selection items for a plugin kind.\n */\n listDatasourceSelectItems(datasourcePluginName: string): Promise<DatasourceSelectItemGroup[]>;\n\n /**\n * Gets the list of datasources defined in the dashboard\n */\n getLocalDatasources(): Record<string, DatasourceSpec>;\n\n /**\n * Sets the list of datasources defined in the dashboard\n */\n setLocalDatasources(datasources: Record<string, DatasourceSpec>): void;\n\n /**\n * Gets the list of datasources that are available in the dashboard (i.e. dashboards that have been created on the server side that we can use).\n */\n getSavedDatasources(): Record<string, DatasourceSpec>;\n\n /**\n * Sets the list of datasources that are saved in the dashboard\n */\n setSavedDatasources(datasources: Record<string, DatasourceSpec>): void;\n}\n\nexport interface DatasourceSelectItemGroup {\n group?: string;\n editLink?: string;\n items: DatasourceSelectItem[];\n}\n\nexport interface DatasourceSelectItem {\n name: string;\n overridden?: boolean;\n overriding?: boolean;\n saved?: boolean;\n selector: DatasourceSelectItemSelector;\n}\n\n/**\n * Datasource Selector used by the frontend only to differentiate datasources coming from different group.\n */\nexport interface DatasourceSelectItemSelector extends DatasourceSelector {\n /**\n * Group of the datasource.\n * Omit it if you don't store datasource by group.\n */\n group?: string;\n}\n\nexport const DatasourceStoreContext = createContext<DatasourceStore | undefined>(undefined);\n\nexport function useDatasourceStore(): DatasourceStore {\n const ctx = useContext(DatasourceStoreContext);\n if (ctx === undefined) {\n throw new Error('No DatasourceStoreContext found. Did you forget a Provider?');\n }\n return ctx;\n}\n\n/**\n * Lists all available Datasource selection items for a given datasource plugin kind.\n * Returns a list, with all information that can be used in a datasource selection context (group, name, selector, kind, ...)\n */\nexport function useListDatasourceSelectItems(\n datasourcePluginName: string,\n project?: string\n): UseQueryResult<DatasourceSelectItemGroup[]> {\n const { listDatasourceSelectItems } = useDatasourceStore();\n return useQuery<DatasourceSelectItemGroup[]>({\n queryKey: ['listDatasourceSelectItems', datasourcePluginName, project],\n queryFn: () => listDatasourceSelectItems(datasourcePluginName),\n });\n}\n\n/**\n * Provides a convenience hook for getting a DatasourceClient for a given DatasourceSelector.\n */\nexport function useDatasourceClient<Client>(selector: DatasourceSelector): UseQueryResult<Client> {\n const store = useDatasourceStore();\n return useQuery<Client>({\n queryKey: ['getDatasourceClient', selector],\n queryFn: () => store.getDatasourceClient<Client>(selector),\n });\n}\n\nexport function useDatasource(selector: DatasourceSelector): UseQueryResult<DatasourceSpec> {\n const store = useDatasourceStore();\n return useQuery<DatasourceSpec>({\n queryKey: ['getDatasource', selector],\n queryFn: () => store.getDatasource(selector),\n });\n}\n"],"names":["useQuery","createContext","useContext","DatasourceStoreContext","undefined","useDatasourceStore","ctx","Error","useListDatasourceSelectItems","datasourcePluginName","project","listDatasourceSelectItems","queryKey","queryFn","useDatasourceClient","selector","store","getDatasourceClient","useDatasource","getDatasource"],"mappings":"AAAA,+BAA+B;AAC/B,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,6CAA6C;AAC7C,EAAE;AACF,sEAAsE;AACtE,oEAAoE;AACpE,2EAA2E;AAC3E,sEAAsE;AACtE,iCAAiC;AAGjC,SAASA,QAAQ,QAAwB,wBAAwB;AACjE,SAASC,aAAa,EAAEC,UAAU,QAAQ,QAAQ;AA8DlD,OAAO,MAAMC,yBAAyBF,cAA2CG,WAAW;AAE5F,OAAO,SAASC;IACd,MAAMC,MAAMJ,WAAWC;IACvB,IAAIG,QAAQF,WAAW;QACrB,MAAM,IAAIG,MAAM;IAClB;IACA,OAAOD;AACT;AAEA;;;CAGC,GACD,OAAO,SAASE,6BACdC,oBAA4B,EAC5BC,OAAgB;IAEhB,MAAM,EAAEC,yBAAyB,EAAE,GAAGN;IACtC,OAAOL,SAAsC;QAC3CY,UAAU;YAAC;YAA6BH;YAAsBC;SAAQ;QACtEG,SAAS,IAAMF,0BAA0BF;IAC3C;AACF;AAEA;;CAEC,GACD,OAAO,SAASK,oBAA4BC,QAA4B;IACtE,MAAMC,QAAQX;IACd,OAAOL,SAAiB;QACtBY,UAAU;YAAC;YAAuBG;SAAS;QAC3CF,SAAS,IAAMG,MAAMC,mBAAmB,CAASF;IACnD;AACF;AAEA,OAAO,SAASG,cAAcH,QAA4B;IACxD,MAAMC,QAAQX;IACd,OAAOL,SAAyB;QAC9BY,UAAU;YAAC;YAAiBG;SAAS;QACrCF,SAAS,IAAMG,MAAMG,aAAa,CAACJ;IACrC;AACF"}
|
|
@@ -11,7 +11,7 @@
|
|
|
11
11
|
// See the License for the specific language governing permissions and
|
|
12
12
|
// limitations under the License.
|
|
13
13
|
import { interpolateSelectionBatch, interpolateSelectionIndividual } from '@perses-dev/components';
|
|
14
|
-
import { fetch } from '@perses-dev/core';
|
|
14
|
+
import { fetch } from '@perses-dev/core'; // TODO should be part of an utils package
|
|
15
15
|
const BODY_METHODS = new Set([
|
|
16
16
|
'POST',
|
|
17
17
|
'PUT',
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/runtime/item-actions.ts"],"sourcesContent":["// Copyright The Perses Authors\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\nimport {\n ActionStatus,\n interpolateSelectionBatch,\n interpolateSelectionIndividual,\n SelectionItem,\n VariableStateMap,\n} from '@perses-dev/components';\nimport { fetch } from '@perses-dev/core';\nimport { ItemAction, EventAction, WebhookAction } from '../components/ItemSelectionActionsOptionsEditor';\n\nconst BODY_METHODS = new Set(['POST', 'PUT', 'PATCH']);\n\nfunction buildWebhookHeaders(action: WebhookAction): Record<string, string> {\n const headers: Record<string, string> = { ...(action.headers ?? {}) };\n const contentType = action.contentType ?? 'none';\n const supportsBody = BODY_METHODS.has(action.method);\n\n if (supportsBody && contentType === 'json') {\n headers['Content-Type'] = 'application/json';\n } else if (supportsBody && contentType === 'text') {\n headers['Content-Type'] = 'text/plain; charset=utf-8';\n }\n\n return headers;\n}\n\n/**\n * Parameters for executing a selection action\n */\nexport interface ExecuteActionParams<Id = unknown> {\n /** The action to execute */\n action: ItemAction;\n /** Map of selection IDs to their data */\n selectionMap: Map<Id, SelectionItem>;\n /** Optional dashboard variable state for interpolation */\n variableState?: VariableStateMap;\n /** Callback to update action status */\n setActionStatus: (actionName: string, status: Partial<ActionStatus>, itemId?: Id) => void;\n}\n\n/**\n * Result of action execution\n */\nexport interface ActionExecutionResult {\n success: boolean;\n error?: Error;\n /** For individual batch mode, results per item */\n itemResults?: Map<unknown, { success: boolean; error?: Error }>;\n}\n\n/**\n * Execute an event action by dispatching a single CustomEvent with batch data\n */\nfunction executeEventBatch<Id>(\n action: EventAction,\n selectionMap: Map<Id, SelectionItem>,\n variableState: VariableStateMap | undefined,\n setActionStatus: ExecuteActionParams<Id>['setActionStatus']\n): ActionExecutionResult {\n try {\n setActionStatus(action.name, { loading: true });\n\n const items = Array.from(selectionMap.values());\n\n // Interpolate body template if provided\n let body: string | undefined;\n if (action.bodyTemplate) {\n const bodyResult = interpolateSelectionBatch(action.bodyTemplate, items, variableState);\n body = bodyResult.text;\n } else {\n body = JSON.stringify({ items });\n }\n\n const event = new CustomEvent(action.eventName, {\n detail: body,\n bubbles: true,\n cancelable: true,\n });\n\n window.dispatchEvent(event);\n\n setActionStatus(action.name, { loading: false, success: true });\n return { success: true };\n } catch (error) {\n const err = error instanceof Error ? error : new Error(String(error));\n setActionStatus(action.name, { loading: false, error: err });\n return { success: false, error: err };\n }\n}\n\n/**\n * Execute events actions by dispatching one CustomEvent per selection\n */\nfunction executeEventIndividual<Id>(\n action: EventAction,\n selectionMap: Map<Id, SelectionItem>,\n variableState: VariableStateMap | undefined,\n setActionStatus: ExecuteActionParams<Id>['setActionStatus']\n): ActionExecutionResult {\n const entries = Array.from(selectionMap.entries());\n const count = entries.length;\n const itemResults = new Map<Id, { success: boolean; error?: Error }>();\n\n // Initialize all items as loading\n setActionStatus(action.name, { loading: true, itemStatuses: new Map() });\n\n for (let index = 0; index < entries.length; index++) {\n const [id, item] = entries[index]!;\n\n setActionStatus(action.name, { loading: true }, id);\n\n try {\n // Interpolate body template if provided\n let body: string | undefined;\n if (action.bodyTemplate) {\n const bodyResult = interpolateSelectionIndividual(action.bodyTemplate, item, index, count, variableState);\n body = bodyResult.text;\n } else {\n body = JSON.stringify({ id, data: item });\n }\n\n const event = new CustomEvent(action.eventName, {\n detail: body,\n bubbles: true,\n cancelable: true,\n });\n\n window.dispatchEvent(event);\n itemResults.set(id, { success: true });\n setActionStatus(action.name, { loading: false, success: true }, id);\n } catch (error) {\n const err = error instanceof Error ? error : new Error(String(error));\n setActionStatus(action.name, { loading: false, error: err }, id);\n itemResults.set(id, { success: false, error: err });\n }\n }\n\n setActionStatus(action.name, { loading: false, success: true });\n\n return {\n success: true,\n itemResults,\n };\n}\n\n/**\n * Execute a webhook action in individual mode (one request per selection)\n */\nasync function executeWebhookIndividual<Id>(\n action: WebhookAction,\n selectionMap: Map<Id, SelectionItem>,\n variableState: VariableStateMap | undefined,\n setActionStatus: ExecuteActionParams<Id>['setActionStatus']\n): Promise<ActionExecutionResult> {\n const entries = Array.from(selectionMap.entries());\n const count = entries.length;\n const itemResults = new Map<Id, { success: boolean; error?: Error }>();\n\n // Initialize all items as loading\n setActionStatus(action.name, { loading: true, itemStatuses: new Map() });\n\n // Execute requests sequentially to avoid overwhelming the server\n for (let index = 0; index < entries.length; index++) {\n const [id, item] = entries[index]!;\n\n setActionStatus(action.name, { loading: true }, id);\n\n try {\n // Interpolate URL\n const urlResult = interpolateSelectionIndividual(action.url, item, index, count, variableState);\n\n // Interpolate body template if provided\n const contentType = action.contentType ?? 'none';\n const supportsBody = BODY_METHODS.has(action.method) && contentType !== 'none';\n let body: string | undefined;\n if (supportsBody && action.bodyTemplate) {\n const bodyResult = interpolateSelectionIndividual(action.bodyTemplate, item, index, count, variableState);\n body = bodyResult.text;\n }\n\n // Make the request\n const response = await fetch(urlResult.text, {\n method: action.method,\n headers: buildWebhookHeaders(action),\n body: body,\n });\n\n if (!response.ok) {\n throw new Error(`HTTP ${response.status}: ${response.statusText}`);\n }\n\n setActionStatus(action.name, { loading: false, success: true }, id);\n itemResults.set(id, { success: true });\n } catch (error) {\n const err = error instanceof Error ? error : new Error(String(error));\n setActionStatus(action.name, { loading: false, error: err }, id);\n itemResults.set(id, { success: false, error: err });\n }\n }\n\n // Update overall action status\n const allSucceeded = Array.from(itemResults.values()).every((r) => r.success);\n const anyFailed = Array.from(itemResults.values()).some((r) => !r.success);\n\n if (allSucceeded) {\n setActionStatus(action.name, { loading: false, success: true });\n } else if (anyFailed) {\n setActionStatus(action.name, {\n loading: false,\n error: new Error('Some requests failed'),\n });\n }\n\n return {\n success: allSucceeded,\n itemResults,\n };\n}\n\n/**\n * Execute a webhook action in batch mode (single request with all selections)\n */\nasync function executeWebhookBatch<Id>(\n action: WebhookAction,\n selectionMap: Map<Id, SelectionItem>,\n variableState: VariableStateMap | undefined,\n setActionStatus: ExecuteActionParams<Id>['setActionStatus']\n): Promise<ActionExecutionResult> {\n const items = Array.from(selectionMap.values());\n\n setActionStatus(action.name, { loading: true });\n\n try {\n // Interpolate URL\n const urlResult = interpolateSelectionBatch(action.url, items, variableState);\n\n // Interpolate body template if provided\n const contentType = action.contentType ?? 'none';\n const supportsBody = BODY_METHODS.has(action.method) && contentType !== 'none';\n let body: string | undefined;\n if (supportsBody && action.bodyTemplate) {\n const bodyResult = interpolateSelectionBatch(action.bodyTemplate, items, variableState);\n body = bodyResult.text;\n }\n\n // Make the request\n const response = await fetch(urlResult.text, {\n method: action.method,\n headers: buildWebhookHeaders(action),\n body: body,\n });\n\n if (!response.ok) {\n throw new Error(`HTTP ${response.status}: ${response.statusText}`);\n }\n\n setActionStatus(action.name, { loading: false, success: true });\n return { success: true };\n } catch (error) {\n const err = error instanceof Error ? error : new Error(String(error));\n setActionStatus(action.name, { loading: false, error: err });\n return { success: false, error: err };\n }\n}\n\n/**\n * Execute a webhook action\n */\nasync function executeWebhookAction<Id>(\n action: WebhookAction,\n selectionMap: Map<Id, SelectionItem>,\n variableState: VariableStateMap | undefined,\n setActionStatus: ExecuteActionParams<Id>['setActionStatus']\n): Promise<ActionExecutionResult> {\n if (action.batchMode === 'batch') {\n return executeWebhookBatch(action, selectionMap, variableState, setActionStatus);\n } else {\n return executeWebhookIndividual(action, selectionMap, variableState, setActionStatus);\n }\n}\n\n/**\n * Execute an event action\n */\nasync function executeEventAction<Id>(\n action: EventAction,\n selectionMap: Map<Id, SelectionItem>,\n variableState: VariableStateMap | undefined,\n setActionStatus: ExecuteActionParams<Id>['setActionStatus']\n): Promise<ActionExecutionResult> {\n if (action.batchMode === 'batch') {\n return executeEventBatch(action, selectionMap, variableState, setActionStatus);\n } else {\n return executeEventIndividual(action, selectionMap, variableState, setActionStatus);\n }\n}\n\n/**\n * Execute a selection action (event or webhook)\n *\n * @param params - Execution parameters including action, selections, and callbacks\n * @returns Promise resolving to the execution result\n */\nexport async function executeAction<Id = unknown>(params: ExecuteActionParams<Id>): Promise<ActionExecutionResult> {\n const { action, selectionMap, variableState, setActionStatus } = params;\n\n if (selectionMap.size === 0) {\n return { success: true };\n }\n\n if (action.type === 'event') {\n return executeEventAction(action, selectionMap, variableState, setActionStatus);\n } else if (action.type === 'webhook') {\n return executeWebhookAction(action, selectionMap, variableState, setActionStatus);\n }\n\n return { success: false, error: new Error(`Unknown action type`) };\n}\n"],"names":["interpolateSelectionBatch","interpolateSelectionIndividual","fetch","BODY_METHODS","Set","buildWebhookHeaders","action","headers","contentType","supportsBody","has","method","executeEventBatch","selectionMap","variableState","setActionStatus","name","loading","items","Array","from","values","body","bodyTemplate","bodyResult","text","JSON","stringify","event","CustomEvent","eventName","detail","bubbles","cancelable","window","dispatchEvent","success","error","err","Error","String","executeEventIndividual","entries","count","length","itemResults","Map","itemStatuses","index","id","item","data","set","executeWebhookIndividual","urlResult","url","response","ok","status","statusText","allSucceeded","every","r","anyFailed","some","executeWebhookBatch","executeWebhookAction","batchMode","executeEventAction","executeAction","params","size","type"],"mappings":"AAAA,+BAA+B;AAC/B,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,6CAA6C;AAC7C,EAAE;AACF,sEAAsE;AACtE,oEAAoE;AACpE,2EAA2E;AAC3E,sEAAsE;AACtE,iCAAiC;AAEjC,SAEEA,yBAAyB,EACzBC,8BAA8B,QAGzB,yBAAyB;AAChC,SAASC,KAAK,QAAQ,mBAAmB;AAGzC,MAAMC,eAAe,IAAIC,IAAI;IAAC;IAAQ;IAAO;CAAQ;AAErD,SAASC,oBAAoBC,MAAqB;IAChD,MAAMC,UAAkC;QAAE,GAAID,OAAOC,OAAO,IAAI,CAAC,CAAC;IAAE;IACpE,MAAMC,cAAcF,OAAOE,WAAW,IAAI;IAC1C,MAAMC,eAAeN,aAAaO,GAAG,CAACJ,OAAOK,MAAM;IAEnD,IAAIF,gBAAgBD,gBAAgB,QAAQ;QAC1CD,OAAO,CAAC,eAAe,GAAG;IAC5B,OAAO,IAAIE,gBAAgBD,gBAAgB,QAAQ;QACjDD,OAAO,CAAC,eAAe,GAAG;IAC5B;IAEA,OAAOA;AACT;AA0BA;;CAEC,GACD,SAASK,kBACPN,MAAmB,EACnBO,YAAoC,EACpCC,aAA2C,EAC3CC,eAA2D;IAE3D,IAAI;QACFA,gBAAgBT,OAAOU,IAAI,EAAE;YAAEC,SAAS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,OAAO,IAAIT,OAAOkE,IAAI,KAAK,WAAW;QACpC,OAAON,qBAAqB5D,QAAQO,cAAcC,eAAeC;IACnE;IAEA,OAAO;QAAEqB,SAAS;QAAOC,OAAO,IAAIE,MAAM,CAAC,mBAAmB,CAAC;IAAE;AACnE"}
|
|
1
|
+
{"version":3,"sources":["../../src/runtime/item-actions.ts"],"sourcesContent":["// Copyright The Perses Authors\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\nimport {\n ActionStatus,\n interpolateSelectionBatch,\n interpolateSelectionIndividual,\n SelectionItem,\n VariableStateMap,\n} from '@perses-dev/components';\nimport { fetch } from '@perses-dev/core'; // TODO should be part of an utils package\nimport { ItemAction, EventAction, WebhookAction } from '../components/ItemSelectionActionsOptionsEditor';\n\nconst BODY_METHODS = new Set(['POST', 'PUT', 'PATCH']);\n\nfunction buildWebhookHeaders(action: WebhookAction): Record<string, string> {\n const headers: Record<string, string> = { ...(action.headers ?? {}) };\n const contentType = action.contentType ?? 'none';\n const supportsBody = BODY_METHODS.has(action.method);\n\n if (supportsBody && contentType === 'json') {\n headers['Content-Type'] = 'application/json';\n } else if (supportsBody && contentType === 'text') {\n headers['Content-Type'] = 'text/plain; charset=utf-8';\n }\n\n return headers;\n}\n\n/**\n * Parameters for executing a selection action\n */\nexport interface ExecuteActionParams<Id = unknown> {\n /** The action to execute */\n action: ItemAction;\n /** Map of selection IDs to their data */\n selectionMap: Map<Id, SelectionItem>;\n /** Optional dashboard variable state for interpolation */\n variableState?: VariableStateMap;\n /** Callback to update action status */\n setActionStatus: (actionName: string, status: Partial<ActionStatus>, itemId?: Id) => void;\n}\n\n/**\n * Result of action execution\n */\nexport interface ActionExecutionResult {\n success: boolean;\n error?: Error;\n /** For individual batch mode, results per item */\n itemResults?: Map<unknown, { success: boolean; error?: Error }>;\n}\n\n/**\n * Execute an event action by dispatching a single CustomEvent with batch data\n */\nfunction executeEventBatch<Id>(\n action: EventAction,\n selectionMap: Map<Id, SelectionItem>,\n variableState: VariableStateMap | undefined,\n setActionStatus: ExecuteActionParams<Id>['setActionStatus']\n): ActionExecutionResult {\n try {\n setActionStatus(action.name, { loading: true });\n\n const items = Array.from(selectionMap.values());\n\n // Interpolate body template if provided\n let body: string | undefined;\n if (action.bodyTemplate) {\n const bodyResult = interpolateSelectionBatch(action.bodyTemplate, items, variableState);\n body = bodyResult.text;\n } else {\n body = JSON.stringify({ items });\n }\n\n const event = new CustomEvent(action.eventName, {\n detail: body,\n bubbles: true,\n cancelable: true,\n });\n\n window.dispatchEvent(event);\n\n setActionStatus(action.name, { loading: false, success: true });\n return { success: true };\n } catch (error) {\n const err = error instanceof Error ? error : new Error(String(error));\n setActionStatus(action.name, { loading: false, error: err });\n return { success: false, error: err };\n }\n}\n\n/**\n * Execute events actions by dispatching one CustomEvent per selection\n */\nfunction executeEventIndividual<Id>(\n action: EventAction,\n selectionMap: Map<Id, SelectionItem>,\n variableState: VariableStateMap | undefined,\n setActionStatus: ExecuteActionParams<Id>['setActionStatus']\n): ActionExecutionResult {\n const entries = Array.from(selectionMap.entries());\n const count = entries.length;\n const itemResults = new Map<Id, { success: boolean; error?: Error }>();\n\n // Initialize all items as loading\n setActionStatus(action.name, { loading: true, itemStatuses: new Map() });\n\n for (let index = 0; index < entries.length; index++) {\n const [id, item] = entries[index]!;\n\n setActionStatus(action.name, { loading: true }, id);\n\n try {\n // Interpolate body template if provided\n let body: string | undefined;\n if (action.bodyTemplate) {\n const bodyResult = interpolateSelectionIndividual(action.bodyTemplate, item, index, count, variableState);\n body = bodyResult.text;\n } else {\n body = JSON.stringify({ id, data: item });\n }\n\n const event = new CustomEvent(action.eventName, {\n detail: body,\n bubbles: true,\n cancelable: true,\n });\n\n window.dispatchEvent(event);\n itemResults.set(id, { success: true });\n setActionStatus(action.name, { loading: false, success: true }, id);\n } catch (error) {\n const err = error instanceof Error ? error : new Error(String(error));\n setActionStatus(action.name, { loading: false, error: err }, id);\n itemResults.set(id, { success: false, error: err });\n }\n }\n\n setActionStatus(action.name, { loading: false, success: true });\n\n return {\n success: true,\n itemResults,\n };\n}\n\n/**\n * Execute a webhook action in individual mode (one request per selection)\n */\nasync function executeWebhookIndividual<Id>(\n action: WebhookAction,\n selectionMap: Map<Id, SelectionItem>,\n variableState: VariableStateMap | undefined,\n setActionStatus: ExecuteActionParams<Id>['setActionStatus']\n): Promise<ActionExecutionResult> {\n const entries = Array.from(selectionMap.entries());\n const count = entries.length;\n const itemResults = new Map<Id, { success: boolean; error?: Error }>();\n\n // Initialize all items as loading\n setActionStatus(action.name, { loading: true, itemStatuses: new Map() });\n\n // Execute requests sequentially to avoid overwhelming the server\n for (let index = 0; index < entries.length; index++) {\n const [id, item] = entries[index]!;\n\n setActionStatus(action.name, { loading: true }, id);\n\n try {\n // Interpolate URL\n const urlResult = interpolateSelectionIndividual(action.url, item, index, count, variableState);\n\n // Interpolate body template if provided\n const contentType = action.contentType ?? 'none';\n const supportsBody = BODY_METHODS.has(action.method) && contentType !== 'none';\n let body: string | undefined;\n if (supportsBody && action.bodyTemplate) {\n const bodyResult = interpolateSelectionIndividual(action.bodyTemplate, item, index, count, variableState);\n body = bodyResult.text;\n }\n\n // Make the request\n const response = await fetch(urlResult.text, {\n method: action.method,\n headers: buildWebhookHeaders(action),\n body: body,\n });\n\n if (!response.ok) {\n throw new Error(`HTTP ${response.status}: ${response.statusText}`);\n }\n\n setActionStatus(action.name, { loading: false, success: true }, id);\n itemResults.set(id, { success: true });\n } catch (error) {\n const err = error instanceof Error ? error : new Error(String(error));\n setActionStatus(action.name, { loading: false, error: err }, id);\n itemResults.set(id, { success: false, error: err });\n }\n }\n\n // Update overall action status\n const allSucceeded = Array.from(itemResults.values()).every((r) => r.success);\n const anyFailed = Array.from(itemResults.values()).some((r) => !r.success);\n\n if (allSucceeded) {\n setActionStatus(action.name, { loading: false, success: true });\n } else if (anyFailed) {\n setActionStatus(action.name, {\n loading: false,\n error: new Error('Some requests failed'),\n });\n }\n\n return {\n success: allSucceeded,\n itemResults,\n };\n}\n\n/**\n * Execute a webhook action in batch mode (single request with all selections)\n */\nasync function executeWebhookBatch<Id>(\n action: WebhookAction,\n selectionMap: Map<Id, SelectionItem>,\n variableState: VariableStateMap | undefined,\n setActionStatus: ExecuteActionParams<Id>['setActionStatus']\n): Promise<ActionExecutionResult> {\n const items = Array.from(selectionMap.values());\n\n setActionStatus(action.name, { loading: true });\n\n try {\n // Interpolate URL\n const urlResult = interpolateSelectionBatch(action.url, items, variableState);\n\n // Interpolate body template if provided\n const contentType = action.contentType ?? 'none';\n const supportsBody = BODY_METHODS.has(action.method) && contentType !== 'none';\n let body: string | undefined;\n if (supportsBody && action.bodyTemplate) {\n const bodyResult = interpolateSelectionBatch(action.bodyTemplate, items, variableState);\n body = bodyResult.text;\n }\n\n // Make the request\n const response = await fetch(urlResult.text, {\n method: action.method,\n headers: buildWebhookHeaders(action),\n body: body,\n });\n\n if (!response.ok) {\n throw new Error(`HTTP ${response.status}: ${response.statusText}`);\n }\n\n setActionStatus(action.name, { loading: false, success: true });\n return { success: true };\n } catch (error) {\n const err = error instanceof Error ? error : new Error(String(error));\n setActionStatus(action.name, { loading: false, error: err });\n return { success: false, error: err };\n }\n}\n\n/**\n * Execute a webhook action\n */\nasync function executeWebhookAction<Id>(\n action: WebhookAction,\n selectionMap: Map<Id, SelectionItem>,\n variableState: VariableStateMap | undefined,\n setActionStatus: ExecuteActionParams<Id>['setActionStatus']\n): Promise<ActionExecutionResult> {\n if (action.batchMode === 'batch') {\n return executeWebhookBatch(action, selectionMap, variableState, setActionStatus);\n } else {\n return executeWebhookIndividual(action, selectionMap, variableState, setActionStatus);\n }\n}\n\n/**\n * Execute an event action\n */\nasync function executeEventAction<Id>(\n action: EventAction,\n selectionMap: Map<Id, SelectionItem>,\n variableState: VariableStateMap | undefined,\n setActionStatus: ExecuteActionParams<Id>['setActionStatus']\n): Promise<ActionExecutionResult> {\n if (action.batchMode === 'batch') {\n return executeEventBatch(action, selectionMap, variableState, setActionStatus);\n } else {\n return executeEventIndividual(action, selectionMap, variableState, setActionStatus);\n }\n}\n\n/**\n * Execute a selection action (event or webhook)\n *\n * @param params - Execution parameters including action, selections, and callbacks\n * @returns Promise resolving to the execution result\n */\nexport async function executeAction<Id = unknown>(params: ExecuteActionParams<Id>): Promise<ActionExecutionResult> {\n const { action, selectionMap, variableState, setActionStatus } = params;\n\n if (selectionMap.size === 0) {\n return { success: true };\n }\n\n if (action.type === 'event') {\n return executeEventAction(action, selectionMap, variableState, setActionStatus);\n } else if (action.type === 'webhook') {\n return executeWebhookAction(action, selectionMap, variableState, setActionStatus);\n }\n\n return { success: false, error: new Error(`Unknown action type`) };\n}\n"],"names":["interpolateSelectionBatch","interpolateSelectionIndividual","fetch","BODY_METHODS","Set","buildWebhookHeaders","action","headers","contentType","supportsBody","has","method","executeEventBatch","selectionMap","variableState","setActionStatus","name","loading","items","Array","from","values","body","bodyTemplate","bodyResult","text","JSON","stringify","event","CustomEvent","eventName","detail","bubbles","cancelable","window","dispatchEvent","success","error","err","Error","String","executeEventIndividual","entries","count","length","itemResults","Map","itemStatuses","index","id","item","data","set","executeWebhookIndividual","urlResult","url","response","ok","status","statusText","allSucceeded","every","r","anyFailed","some","executeWebhookBatch","executeWebhookAction","batchMode","executeEventAction","executeAction","params","size","type"],"mappings":"AAAA,+BAA+B;AAC/B,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,6CAA6C;AAC7C,EAAE;AACF,sEAAsE;AACtE,oEAAoE;AACpE,2EAA2E;AAC3E,sEAAsE;AACtE,iCAAiC;AAEjC,SAEEA,yBAAyB,EACzBC,8BAA8B,QAGzB,yBAAy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AeC;IAClE,OAAO;QACL,OAAOsC,yBAAyB/C,QAAQO,cAAcC,eAAeC;IACvE;AACF;AAEA;;CAEC,GACD,eAAeqD,mBACb9D,MAAmB,EACnBO,YAAoC,EACpCC,aAA2C,EAC3CC,eAA2D;IAE3D,IAAIT,OAAO6D,SAAS,KAAK,SAAS;QAChC,OAAOvD,kBAAkBN,QAAQO,cAAcC,eAAeC;IAChE,OAAO;QACL,OAAO0B,uBAAuBnC,QAAQO,cAAcC,eAAeC;IACrE;AACF;AAEA;;;;;CAKC,GACD,OAAO,eAAesD,cAA4BC,MAA+B;IAC/E,MAAM,EAAEhE,MAAM,EAAEO,YAAY,EAAEC,aAAa,EAAEC,eAAe,EAAE,GAAGuD;IAEjE,IAAIzD,aAAa0D,IAAI,KAAK,GAAG;QAC3B,OAAO;YAAEnC,SAAS;QAAK;IACzB;IAEA,IAAI9B,OAAOkE,IAAI,KAAK,SAAS;QAC3B,OAAOJ,mBAAmB9D,QAAQO,cAAcC,eAAeC;IACjE,OAAO,IAAIT,OAAOkE,IAAI,KAAK,WAAW;QACpC,OAAON,qBAAqB5D,QAAQO,cAAcC,eAAeC;IACnE;IAEA,OAAO;QAAEqB,SAAS;QAAOC,OAAO,IAAIE,MAAM,CAAC,mBAAmB,CAAC;IAAE;AACnE"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { QueryDefinition, UnknownSpec } from '@perses-dev/
|
|
1
|
+
import { QueryDefinition, UnknownSpec } from '@perses-dev/spec';
|
|
2
2
|
import { UseQueryResult } from '@tanstack/react-query';
|
|
3
3
|
import { LogQueryResult } from '../model/log-queries';
|
|
4
4
|
export type LogQueryDefinition<PluginSpec = UnknownSpec> = QueryDefinition<'LogQuery', PluginSpec>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/runtime/log-queries.ts"],"sourcesContent":["// Copyright The Perses Authors\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\nimport { QueryDefinition, UnknownSpec } from '@perses-dev/
|
|
1
|
+
{"version":3,"sources":["../../src/runtime/log-queries.ts"],"sourcesContent":["// Copyright The Perses Authors\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\nimport { QueryDefinition, UnknownSpec } from '@perses-dev/spec';\nimport { useQueries, UseQueryResult } from '@tanstack/react-query';\nimport { LogQueryResult } from '../model/log-queries';\nimport { useDatasourceStore } from './datasources';\nimport { usePluginRegistry } from './plugin-registry';\nimport { useTimeRange } from './TimeRangeProvider';\nimport { useVariableValues } from './variables';\n\nexport type LogQueryDefinition<PluginSpec = UnknownSpec> = QueryDefinition<'LogQuery', PluginSpec>;\nexport const LOG_QUERY_KEY = 'LogQuery';\n\nexport function useLogQueries(definitions: LogQueryDefinition[]): Array<UseQueryResult<LogQueryResult>> {\n const { getPlugin } = usePluginRegistry();\n const datasourceStore = useDatasourceStore();\n const { absoluteTimeRange } = useTimeRange();\n const variableValues = useVariableValues();\n\n const context = {\n timeRange: absoluteTimeRange,\n variableState: variableValues,\n datasourceStore,\n refreshKey: '',\n };\n\n return useQueries({\n queries: definitions.map((definition) => {\n const queryKey = ['query', LOG_QUERY_KEY, definition, absoluteTimeRange, variableValues] as const;\n const logQueryKind = definition?.spec?.plugin?.kind;\n return {\n queryKey: queryKey,\n refetchOnMount: false,\n refetchOnWindowFocus: false,\n refetchOnReconnect: false,\n staleTime: Infinity,\n queryFn: async ({ signal }: { signal?: AbortSignal }): Promise<LogQueryResult> => {\n const plugin = await getPlugin(LOG_QUERY_KEY, logQueryKind);\n const data = await plugin.getLogData(definition.spec.plugin.spec, context, signal);\n return data;\n },\n\n structuralSharing: false,\n };\n }),\n });\n}\n"],"names":["useQueries","useDatasourceStore","usePluginRegistry","useTimeRange","useVariableValues","LOG_QUERY_KEY","useLogQueries","definitions","getPlugin","datasourceStore","absoluteTimeRange","variableValues","context","timeRange","variableState","refreshKey","queries","map","definition","queryKey","logQueryKind","spec","plugin","kind","refetchOnMount","refetchOnWindowFocus","refetchOnReconnect","staleTime","Infinity","queryFn","signal","data","getLogData","structuralSharing"],"mappings":"AAAA,+BAA+B;AAC/B,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,6CAA6C;AAC7C,EAAE;AACF,sEAAsE;AACtE,oEAAoE;AACpE,2EAA2E;AAC3E,sEAAsE;AACtE,iCAAiC;AAGjC,SAASA,UAAU,QAAwB,wBAAwB;AAEnE,SAASC,kBAAkB,QAAQ,gBAAgB;AACnD,SAASC,iBAAiB,QAAQ,oBAAoB;AACtD,SAASC,YAAY,QAAQ,sBAAsB;AACnD,SAASC,iBAAiB,QAAQ,cAAc;AAGhD,OAAO,MAAMC,gBAAgB,WAAW;AAExC,OAAO,SAASC,cAAcC,WAAiC;IAC7D,MAAM,EAAEC,SAAS,EAAE,GAAGN;IACtB,MAAMO,kBAAkBR;IACxB,MAAM,EAAES,iBAAiB,EAAE,GAAGP;IAC9B,MAAMQ,iBAAiBP;IAEvB,MAAMQ,UAAU;QACdC,WAAWH;QACXI,eAAeH;QACfF;QACAM,YAAY;IACd;IAEA,OAAOf,WAAW;QAChBgB,SAAST,YAAYU,GAAG,CAAC,CAACC;YACxB,MAAMC,WAAW;gBAAC;gBAASd;gBAAea;gBAAYR;gBAAmBC;aAAe;YACxF,MAAMS,eAAeF,YAAYG,MAAMC,QAAQC;YAC/C,OAAO;gBACLJ,UAAUA;gBACVK,gBAAgB;gBAChBC,sBAAsB;gBACtBC,oBAAoB;gBACpBC,WAAWC;gBACXC,SAAS,OAAO,EAAEC,MAAM,EAA4B;oBAClD,MAAMR,SAAS,MAAMd,UAAUH,eAAee;oBAC9C,MAAMW,OAAO,MAAMT,OAAOU,UAAU,CAACd,WAAWG,IAAI,CAACC,MAAM,CAACD,IAAI,EAAET,SAASkB;oBAC3E,OAAOC;gBACT;gBAEAE,mBAAmB;YACrB;QACF;IACF;AACF"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/// <reference types="react" />
|
|
2
|
-
import { BuiltinVariableDefinition } from '@perses-dev/
|
|
2
|
+
import { BuiltinVariableDefinition } from '@perses-dev/spec';
|
|
3
3
|
import { UseQueryOptions, UseQueryResult } from '@tanstack/react-query';
|
|
4
4
|
import { DefaultPluginKinds, PluginImplementation, PluginMetadataWithModule, PluginType } from '../model';
|
|
5
5
|
export interface PluginRegistryContextType {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/runtime/plugin-registry.ts"],"sourcesContent":["// Copyright The Perses Authors\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\nimport { BuiltinVariableDefinition } from '@perses-dev/
|
|
1
|
+
{"version":3,"sources":["../../src/runtime/plugin-registry.ts"],"sourcesContent":["// Copyright The Perses Authors\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\nimport { BuiltinVariableDefinition } from '@perses-dev/spec';\nimport { useQueries, useQuery, UseQueryOptions, UseQueryResult } from '@tanstack/react-query';\nimport { createContext, useContext } from 'react';\nimport { DefaultPluginKinds, PluginImplementation, PluginMetadataWithModule, PluginType } from '../model';\n\nexport interface PluginRegistryContextType {\n getPlugin<T extends PluginType>(kind: T, name: string): Promise<PluginImplementation<T>>;\n listPluginMetadata(pluginTypes: PluginType[]): Promise<PluginMetadataWithModule[]>;\n defaultPluginKinds?: DefaultPluginKinds;\n}\n\nexport const PluginRegistryContext = createContext<PluginRegistryContextType | undefined>(undefined);\n\n/**\n * Use the PluginRegistry context directly. This is meant as an escape hatch for custom async flows. You should probably\n * be using `usePlugin` or `useListPluginMetadata` instead.\n */\nexport function usePluginRegistry(): PluginRegistryContextType {\n const ctx = useContext(PluginRegistryContext);\n if (ctx === undefined) {\n throw new Error('PluginRegistryContext not found. Did you forget a provider?');\n }\n return ctx;\n}\n\n// Allows consumers to pass useQuery options from react-query when loading a plugin\ntype UsePluginOptions<T extends PluginType> = Omit<\n UseQueryOptions<PluginImplementation<T>, Error, PluginImplementation<T>, [string, PluginType | undefined, string]>,\n 'queryKey' | 'queryFn'\n>;\n\n/**\n * Loads a plugin and returns the plugin implementation, along with loading/error state.\n */\nexport function usePlugin<T extends PluginType>(\n pluginType: T | undefined,\n kind: string,\n options?: UsePluginOptions<T>\n): UseQueryResult<PluginImplementation<T>, Error> {\n // We never want to ask for a plugin when the kind isn't set yet, so disable those queries automatically\n options = {\n ...options,\n enabled: (options?.enabled ?? true) && pluginType !== undefined && kind !== '',\n };\n const { getPlugin } = usePluginRegistry();\n return useQuery({\n queryKey: ['getPlugin', pluginType, kind],\n queryFn: () => getPlugin(pluginType!, kind),\n ...options,\n });\n}\n\n/**\n * Loads a list of plugins and returns the plugin implementation, along with loading/error state.\n */\nexport function usePlugins<T extends PluginType>(\n pluginType: T,\n plugins: Array<{ kind: string }>\n): Array<UseQueryResult<PluginImplementation<T>>> {\n const { getPlugin } = usePluginRegistry();\n\n // useQueries() does not support queries with duplicate keys, therefore we de-duplicate the plugin kinds before running useQueries()\n // This resolves the following warning in the JS console: \"[QueriesObserver]: Duplicate Queries found. This might result in unexpected behavior.\"\n // https://github.com/TanStack/query/issues/8224#issuecomment-2523554831\n // https://github.com/TanStack/query/issues/4187#issuecomment-1256336901\n const kinds = [...new Set(plugins.map((p) => p.kind))];\n\n const result: Array<UseQueryResult<PluginImplementation<T>>> = useQueries({\n queries: kinds.map((kind) => {\n return {\n queryKey: ['getPlugin', pluginType, kind],\n queryFn: () => getPlugin(pluginType, kind),\n };\n }),\n });\n\n // Re-assemble array in original order\n return plugins.map((p) => result[kinds.indexOf(p.kind)]!);\n}\n\n// Allow consumers to pass useQuery options from react-query when listing metadata\ntype UseListPluginMetadataOptions = Omit<\n UseQueryOptions<PluginMetadataWithModule[], Error, PluginMetadataWithModule[], [string, string[]]>,\n 'queryKey' | 'queryFn'\n>;\n\n/**\n * Gets a list of plugin metadata for the specified plugin type and returns it, along with loading/error state.\n */\nexport function useListPluginMetadata(\n pluginTypes: PluginType[],\n options?: UseListPluginMetadataOptions\n): UseQueryResult<PluginMetadataWithModule[]> {\n const { listPluginMetadata } = usePluginRegistry();\n return useQuery({\n queryKey: ['listPluginMetadata', pluginTypes],\n queryFn: () => listPluginMetadata(pluginTypes),\n ...options,\n });\n}\n\nexport function usePluginBuiltinVariableDefinitions(): UseQueryResult<BuiltinVariableDefinition[]> {\n const { getPlugin, listPluginMetadata } = usePluginRegistry();\n\n return useQuery({\n queryKey: ['usePluginBuiltinVariableDefinitions'],\n queryFn: async () => {\n const datasources = await listPluginMetadata(['Datasource']);\n const datasourceNames = new Set(datasources.map((datasource) => datasource.spec.name));\n const result: BuiltinVariableDefinition[] = [];\n for (const name of datasourceNames) {\n const plugin = await getPlugin('Datasource', name);\n if (plugin.getBuiltinVariableDefinitions) {\n plugin.getBuiltinVariableDefinitions().forEach((definition) => result.push(definition));\n }\n }\n return result;\n },\n });\n}\n"],"names":["useQueries","useQuery","createContext","useContext","PluginRegistryContext","undefined","usePluginRegistry","ctx","Error","usePlugin","pluginType","kind","options","enabled","getPlugin","queryKey","queryFn","usePlugins","plugins","kinds","Set","map","p","result","queries","indexOf","useListPluginMetadata","pluginTypes","listPluginMetadata","usePluginBuiltinVariableDefinitions","datasources","datasourceNames","datasource","spec","name","plugin","getBuiltinVariableDefinitions","forEach","definition","push"],"mappings":"AAAA,+BAA+B;AAC/B,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,6CAA6C;AAC7C,EAAE;AACF,sEAAsE;AACtE,oEAAoE;AACpE,2EAA2E;AAC3E,sEAAsE;AACtE,iCAAiC;AAGjC,SAASA,UAAU,EAAEC,QAAQ,QAAyC,wBAAwB;AAC9F,SAASC,aAAa,EAAEC,UAAU,QAAQ,QAAQ;AASlD,OAAO,MAAMC,wBAAwBF,cAAqDG,WAAW;AAErG;;;CAGC,GACD,OAAO,SAASC;IACd,MAAMC,MAAMJ,WAAWC;IACvB,IAAIG,QAAQF,WAAW;QACrB,MAAM,IAAIG,MAAM;IAClB;IACA,OAAOD;AACT;AAQA;;CAEC,GACD,OAAO,SAASE,UACdC,UAAyB,EACzBC,IAAY,EACZC,OAA6B;IAE7B,wGAAwG;IACxGA,UAAU;QACR,GAAGA,OAAO;QACVC,SAAS,AAACD,CAAAA,SAASC,WAAW,IAAG,KAAMH,eAAeL,aAAaM,SAAS;IAC9E;IACA,MAAM,EAAEG,SAAS,EAAE,GAAGR;IACtB,OAAOL,SAAS;QACdc,UAAU;YAAC;YAAaL;YAAYC;SAAK;QACzCK,SAAS,IAAMF,UAAUJ,YAAaC;QACtC,GAAGC,OAAO;IACZ;AACF;AAEA;;CAEC,GACD,OAAO,SAASK,WACdP,UAAa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ACA,OAAOf;QACT;IACF;AACF"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { QueryDefinition, UnknownSpec, ProfileData } from '@perses-dev/
|
|
1
|
+
import { QueryDefinition, UnknownSpec, ProfileData } from '@perses-dev/spec';
|
|
2
2
|
import { UseQueryResult } from '@tanstack/react-query';
|
|
3
3
|
export type ProfileQueryDefinition<PluginSpec = UnknownSpec> = QueryDefinition<'ProfileQuery', PluginSpec>;
|
|
4
4
|
export declare const PROFILE_QUERY_KEY = "ProfileQuery";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/runtime/profile-queries.ts"],"sourcesContent":["// Copyright The Perses Authors\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\nimport { QueryDefinition, UnknownSpec, ProfileData } from '@perses-dev/
|
|
1
|
+
{"version":3,"sources":["../../src/runtime/profile-queries.ts"],"sourcesContent":["// Copyright The Perses Authors\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\nimport { QueryDefinition, UnknownSpec, ProfileData } from '@perses-dev/spec';\nimport { useQueries, UseQueryResult } from '@tanstack/react-query';\nimport { useDatasourceStore } from './datasources';\nimport { usePluginRegistry } from './plugin-registry';\nimport { useTimeRange } from './TimeRangeProvider';\nexport type ProfileQueryDefinition<PluginSpec = UnknownSpec> = QueryDefinition<'ProfileQuery', PluginSpec>;\nexport const PROFILE_QUERY_KEY = 'ProfileQuery';\n\n/**\n * Run a profile query using a ProfileQuery plugin and return the results\n * @param definitions: dashboard defintion for a profile query\n */\nexport function useProfileQueries(definitions: ProfileQueryDefinition[]): Array<UseQueryResult<ProfileData>> {\n const { getPlugin } = usePluginRegistry();\n const datasourceStore = useDatasourceStore();\n const { absoluteTimeRange } = useTimeRange();\n\n const context = {\n datasourceStore,\n absoluteTimeRange,\n };\n\n // useQueries() handles data fetching from query plugins (e.g. traceQL queries, promQL queries)\n // https://tanstack.com/query/v4/docs/react/reference/useQuery\n return useQueries({\n queries: definitions.map((definition) => {\n const queryKey = ['query', PROFILE_QUERY_KEY, definition, absoluteTimeRange] as const; // `queryKey` watches and reruns `queryFn` if keys in the array change\n const profileQueryKind = definition?.spec?.plugin?.kind;\n return {\n queryKey: queryKey,\n refetchOnMount: false,\n refetchOnWindowFocus: false,\n refetchOnReconnect: false,\n staleTime: Infinity,\n queryFn: async ({ signal }: { signal?: AbortSignal }): Promise<ProfileData> => {\n const plugin = await getPlugin(PROFILE_QUERY_KEY, profileQueryKind);\n const data = await plugin.getProfileData(definition.spec.plugin.spec, context, signal);\n return data;\n },\n\n structuralSharing: false,\n };\n }),\n });\n}\n"],"names":["useQueries","useDatasourceStore","usePluginRegistry","useTimeRange","PROFILE_QUERY_KEY","useProfileQueries","definitions","getPlugin","datasourceStore","absoluteTimeRange","context","queries","map","definition","queryKey","profileQueryKind","spec","plugin","kind","refetchOnMount","refetchOnWindowFocus","refetchOnReconnect","staleTime","Infinity","queryFn","signal","data","getProfileData","structuralSharing"],"mappings":"AAAA,+BAA+B;AAC/B,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,6CAA6C;AAC7C,EAAE;AACF,sEAAsE;AACtE,oEAAoE;AACpE,2EAA2E;AAC3E,sEAAsE;AACtE,iCAAiC;AAGjC,SAASA,UAAU,QAAwB,wBAAwB;AACnE,SAASC,kBAAkB,QAAQ,gBAAgB;AACnD,SAASC,iBAAiB,QAAQ,oBAAoB;AACtD,SAASC,YAAY,QAAQ,sBAAsB;AAEnD,OAAO,MAAMC,oBAAoB,eAAe;AAEhD;;;CAGC,GACD,OAAO,SAASC,kBAAkBC,WAAqC;IACrE,MAAM,EAAEC,SAAS,EAAE,GAAGL;IACtB,MAAMM,kBAAkBP;IACxB,MAAM,EAAEQ,iBAAiB,EAAE,GAAGN;IAE9B,MAAMO,UAAU;QACdF;QACAC;IACF;IAEA,+FAA+F;IAC/F,8DAA8D;IAC9D,OAAOT,WAAW;QAChBW,SAASL,YAAYM,GAAG,CAAC,CAACC;YACxB,MAAMC,WAAW;gBAAC;gBAASV;gBAAmBS;gBAAYJ;aAAkB,EAAW,sEAAsE;YAC7J,MAAMM,mBAAmBF,YAAYG,MAAMC,QAAQC;YACnD,OAAO;gBACLJ,UAAUA;gBACVK,gBAAgB;gBAChBC,sBAAsB;gBACtBC,oBAAoB;gBACpBC,WAAWC;gBACXC,SAAS,OAAO,EAAEC,MAAM,EAA4B;oBAClD,MAAMR,SAAS,MAAMV,UAAUH,mBAAmBW;oBAClD,MAAMW,OAAO,MAAMT,OAAOU,cAAc,CAACd,WAAWG,IAAI,CAACC,MAAM,CAACD,IAAI,EAAEN,SAASe;oBAC/E,OAAOC;gBACT;gBAEAE,mBAAmB;YACrB;QACF;IACF;AACF"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { TimeSeriesData, TimeSeriesQueryDefinition } from '@perses-dev/
|
|
1
|
+
import { TimeSeriesData, TimeSeriesQueryDefinition } from '@perses-dev/spec';
|
|
2
2
|
import { QueryCache, QueryObserverOptions, UseQueryResult } from '@tanstack/react-query';
|
|
3
3
|
import { TimeSeriesDataQuery, TimeSeriesQueryMode } from '../model';
|
|
4
4
|
export interface UseTimeSeriesQueryOptions {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/runtime/time-series-queries.ts"],"sourcesContent":["// Copyright The Perses Authors\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\nimport { TimeSeriesData, TimeSeriesQueryDefinition, UnknownSpec } from '@perses-dev/core';\nimport {\n Query,\n QueryCache,\n QueryKey,\n QueryObserverOptions,\n useQueries,\n useQuery,\n useQueryClient,\n UseQueryResult,\n} from '@tanstack/react-query';\nimport { TimeSeriesDataQuery, TimeSeriesQueryContext, TimeSeriesQueryMode, TimeSeriesQueryPlugin } from '../model';\nimport { useTimeRange } from './TimeRangeProvider';\nimport { useDatasourceStore } from './datasources';\nimport { usePlugin, usePluginRegistry, usePlugins } from './plugin-registry';\nimport { filterVariableStateMap, getVariableValuesKey } from './utils';\nimport { useAllVariableValues } from './variables';\n\nexport interface UseTimeSeriesQueryOptions {\n suggestedStepMs?: number;\n mode?: TimeSeriesQueryMode;\n}\n\nexport const TIME_SERIES_QUERY_KEY = 'TimeSeriesQuery';\n\nfunction getQueryOptions({\n plugin,\n definition,\n context,\n}: {\n plugin?: TimeSeriesQueryPlugin;\n definition: TimeSeriesQueryDefinition;\n context: TimeSeriesQueryContext;\n}): {\n queryKey: QueryKey;\n queryEnabled: boolean;\n} {\n const { timeRange, suggestedStepMs, mode, variableState } = context;\n\n const dependencies = plugin?.dependsOn ? plugin.dependsOn(definition.spec.plugin.spec, context) : {};\n const variableDependencies = dependencies?.variables;\n\n // Determine queryKey\n const filteredVariabledState = filterVariableStateMap(variableState, variableDependencies);\n const variablesValueKey = getVariableValuesKey(filteredVariabledState);\n\n const queryKey = [\n 'query',\n TIME_SERIES_QUERY_KEY,\n definition,\n timeRange,\n variablesValueKey,\n suggestedStepMs,\n mode,\n ] as const;\n\n // Determine queryEnabled\n let waitToLoad = false;\n if (variableDependencies) {\n waitToLoad = variableDependencies.some((v) => variableState[v]?.loading);\n }\n\n const queryEnabled = plugin !== undefined && !waitToLoad;\n\n return {\n queryKey,\n queryEnabled,\n };\n}\n\n/**\n * Runs a time series query using a plugin and returns the results.\n */\nexport const useTimeSeriesQuery = (\n definition: TimeSeriesQueryDefinition,\n options?: UseTimeSeriesQueryOptions,\n queryOptions?: QueryObserverOptions<TimeSeriesData>\n): UseQueryResult<TimeSeriesData> => {\n const { data: plugin } = usePlugin(TIME_SERIES_QUERY_KEY, definition.spec.plugin.kind);\n const context = useTimeSeriesQueryContext();\n const { queryEnabled, queryKey } = getQueryOptions({ plugin, definition, context });\n return useQuery({\n enabled: (queryOptions?.enabled ?? true) || queryEnabled,\n queryKey: queryKey,\n queryFn: ({ signal }) => {\n // The 'enabled' option should prevent this from happening, but make TypeScript happy by checking\n if (plugin === undefined) {\n throw new Error('Expected plugin to be loaded');\n }\n // Keep options out of query key so we don't re-run queries because suggested step changes\n const ctx: TimeSeriesQueryContext = { ...context, suggestedStepMs: options?.suggestedStepMs };\n return plugin.getTimeSeriesData(definition.spec.plugin.spec, ctx, signal);\n },\n });\n};\n\n/**\n * Runs multiple time series queries using plugins and returns the results.\n */\nexport function useTimeSeriesQueries(\n definitions: TimeSeriesQueryDefinition[],\n options?: UseTimeSeriesQueryOptions,\n queryOptions?: Omit<QueryObserverOptions, 'queryKey'>\n): Array<UseQueryResult<TimeSeriesData>> {\n const { getPlugin } = usePluginRegistry();\n const context = {\n ...useTimeSeriesQueryContext(),\n mode: options?.mode,\n suggestedStepMs: options?.suggestedStepMs,\n };\n\n const pluginLoaderResponse = usePlugins(\n TIME_SERIES_QUERY_KEY,\n definitions.map((d) => ({ kind: d.spec.plugin.kind }))\n );\n return useQueries({\n queries: definitions.map((definition, idx) => {\n const plugin = pluginLoaderResponse[idx]?.data;\n const { queryEnabled, queryKey } = getQueryOptions({ plugin, definition, context });\n return {\n ...queryOptions,\n enabled: (queryOptions?.enabled ?? true) && queryEnabled,\n refetchOnMount: false,\n refetchOnWindowFocus: false,\n refetchOnReconnect: false,\n staleTime: Infinity,\n queryKey: queryKey,\n queryFn: async ({ signal }: { signal: AbortSignal }): Promise<TimeSeriesData> => {\n const plugin = await getPlugin(TIME_SERIES_QUERY_KEY, definition.spec.plugin.kind);\n const data = await plugin.getTimeSeriesData(definition.spec.plugin.spec, context, signal);\n return data;\n },\n } as QueryObserverOptions;\n }),\n }) as Array<UseQueryResult<TimeSeriesData>>;\n}\n\n/**\n * Build the time series query context object from data available at runtime\n */\nfunction useTimeSeriesQueryContext(): TimeSeriesQueryContext {\n const { absoluteTimeRange } = useTimeRange();\n const variableState = useAllVariableValues();\n const datasourceStore = useDatasourceStore();\n\n return {\n timeRange: absoluteTimeRange,\n variableState,\n datasourceStore,\n };\n}\n\n/**\n * Get active time series queries for query results summary\n */\nexport function useActiveTimeSeriesQueries(): TimeSeriesDataQuery[] {\n const queryClient = useQueryClient();\n const queryCache = queryClient.getQueryCache();\n return getActiveTimeSeriesQueries(queryCache);\n}\n\n/**\n * Filter all cached queries down to only active time series queries\n */\nexport function getActiveTimeSeriesQueries(cache: QueryCache): TimeSeriesDataQuery[] {\n const queries: TimeSeriesDataQuery[] = [];\n\n for (const query of cache.findAll({ type: 'active' })) {\n const firstPart = query.queryKey?.[0] as UnknownSpec;\n if (firstPart?.kind && (firstPart.kind as string).startsWith(TIME_SERIES_QUERY_KEY)) {\n queries.push(query as Query<TimeSeriesData, unknown, TimeSeriesData, QueryKey>);\n }\n }\n\n return queries;\n}\n"],"names":["useQueries","useQuery","useQueryClient","useTimeRange","useDatasourceStore","usePlugin","usePluginRegistry","usePlugins","filterVariableStateMap","getVariableValuesKey","useAllVariableValues","TIME_SERIES_QUERY_KEY","getQueryOptions","plugin","definition","context","timeRange","suggestedStepMs","mode","variableState","dependencies","dependsOn","spec","variableDependencies","variables","filteredVariabledState","variablesValueKey","queryKey","waitToLoad","some","v","loading","queryEnabled","undefined","useTimeSeriesQuery","options","queryOptions","data","kind","useTimeSeriesQueryContext","enabled","queryFn","signal","Error","ctx","getTimeSeriesData","useTimeSeriesQueries","definitions","getPlugin","pluginLoaderResponse","map","d","queries","idx","refetchOnMount","refetchOnWindowFocus","refetchOnReconnect","staleTime","Infinity","absoluteTimeRange","datasourceStore","useActiveTimeSeriesQueries","queryClient","queryCache","getQueryCache","getActiveTimeSeriesQueries","cache","query","findAll","type","firstPart","startsWith","push"],"mappings":"AAAA,+BAA+B;AAC/B,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,6CAA6C;AAC7C,EAAE;AACF,sEAAsE;AACtE,oEAAoE;AACpE,2EAA2E;AAC3E,sEAAsE;AACtE,iCAAiC;AAGjC,SAKEA,UAAU,EACVC,QAAQ,EACRC,cAAc,QAET,wBAAwB;AAE/B,SAASC,YAAY,QAAQ,sBAAsB;AACnD,SAASC,kBAAkB,QAAQ,gBAAgB;AACnD,SAASC,SAAS,EAAEC,iBAAiB,EAAEC,UAAU,QAAQ,oBAAoB;AAC7E,SAASC,sBAAsB,EAAEC,oBAAoB,QAAQ,UAAU;AACvE,SAASC,oBAAoB,QAAQ,cAAc;AAOnD,OAAO,MAAMC,wBAAwB,kBAAkB;AAEvD,SAASC,gBAAgB,EACvBC,MAAM,EACNC,UAAU,EACVC,OAAO,EAKR;IAIC,MAAM,EAAEC,SAAS,EAAEC,eAAe,EAAEC,IAAI,EAAEC,aAAa,EAAE,GAAGJ;IAE5D,MAAMK,eAAeP,QAAQQ,YAAYR,OAAOQ,SAAS,CAACP,WAAWQ,IAAI,CAACT,MAAM,CAACS,IAAI,EAAEP,WAAW,CAAC;IACnG,MAAMQ,uBAAuBH,cAAcI;IAE3C,qBAAqB;IACrB,MAAMC,yBAAyBjB,uBAAuBW,eAAeI;IACrE,MAAMG,oBAAoBjB,qBAAqBgB;IAE/C,MAAME,WAAW;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,QAAQ,AAACgC,UAAUhC,IAAI,CAAYiC,UAAU,CAAC5D,wBAAwB;YACnFyC,QAAQoB,IAAI,CAACL;QACf;IACF;IAEA,OAAOf;AACT"}
|
|
1
|
+
{"version":3,"sources":["../../src/runtime/time-series-queries.ts"],"sourcesContent":["// Copyright The Perses Authors\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\nimport { TimeSeriesData, TimeSeriesQueryDefinition, UnknownSpec } from '@perses-dev/spec';\nimport {\n Query,\n QueryCache,\n QueryKey,\n QueryObserverOptions,\n useQueries,\n useQuery,\n useQueryClient,\n UseQueryResult,\n} from '@tanstack/react-query';\nimport { TimeSeriesDataQuery, TimeSeriesQueryContext, TimeSeriesQueryMode, TimeSeriesQueryPlugin } from '../model';\nimport { useTimeRange } from './TimeRangeProvider';\nimport { useDatasourceStore } from './datasources';\nimport { usePlugin, usePluginRegistry, usePlugins } from './plugin-registry';\nimport { filterVariableStateMap, getVariableValuesKey } from './utils';\nimport { useAllVariableValues } from './variables';\n\nexport interface UseTimeSeriesQueryOptions {\n suggestedStepMs?: number;\n mode?: TimeSeriesQueryMode;\n}\n\nexport const TIME_SERIES_QUERY_KEY = 'TimeSeriesQuery';\n\nfunction getQueryOptions({\n plugin,\n definition,\n context,\n}: {\n plugin?: TimeSeriesQueryPlugin;\n definition: TimeSeriesQueryDefinition;\n context: TimeSeriesQueryContext;\n}): {\n queryKey: QueryKey;\n queryEnabled: boolean;\n} {\n const { timeRange, suggestedStepMs, mode, variableState } = context;\n\n const dependencies = plugin?.dependsOn ? plugin.dependsOn(definition.spec.plugin.spec, context) : {};\n const variableDependencies = dependencies?.variables;\n\n // Determine queryKey\n const filteredVariabledState = filterVariableStateMap(variableState, variableDependencies);\n const variablesValueKey = getVariableValuesKey(filteredVariabledState);\n\n const queryKey = [\n 'query',\n TIME_SERIES_QUERY_KEY,\n definition,\n timeRange,\n variablesValueKey,\n suggestedStepMs,\n mode,\n ] as const;\n\n // Determine queryEnabled\n let waitToLoad = false;\n if (variableDependencies) {\n waitToLoad = variableDependencies.some((v) => variableState[v]?.loading);\n }\n\n const queryEnabled = plugin !== undefined && !waitToLoad;\n\n return {\n queryKey,\n queryEnabled,\n };\n}\n\n/**\n * Runs a time series query using a plugin and returns the results.\n */\nexport const useTimeSeriesQuery = (\n definition: TimeSeriesQueryDefinition,\n options?: UseTimeSeriesQueryOptions,\n queryOptions?: QueryObserverOptions<TimeSeriesData>\n): UseQueryResult<TimeSeriesData> => {\n const { data: plugin } = usePlugin(TIME_SERIES_QUERY_KEY, definition.spec.plugin.kind);\n const context = useTimeSeriesQueryContext();\n const { queryEnabled, queryKey } = getQueryOptions({ plugin, definition, context });\n return useQuery({\n enabled: (queryOptions?.enabled ?? true) || queryEnabled,\n queryKey: queryKey,\n queryFn: ({ signal }) => {\n // The 'enabled' option should prevent this from happening, but make TypeScript happy by checking\n if (plugin === undefined) {\n throw new Error('Expected plugin to be loaded');\n }\n // Keep options out of query key so we don't re-run queries because suggested step changes\n const ctx: TimeSeriesQueryContext = { ...context, suggestedStepMs: options?.suggestedStepMs };\n return plugin.getTimeSeriesData(definition.spec.plugin.spec, ctx, signal);\n },\n });\n};\n\n/**\n * Runs multiple time series queries using plugins and returns the results.\n */\nexport function useTimeSeriesQueries(\n definitions: TimeSeriesQueryDefinition[],\n options?: UseTimeSeriesQueryOptions,\n queryOptions?: Omit<QueryObserverOptions, 'queryKey'>\n): Array<UseQueryResult<TimeSeriesData>> {\n const { getPlugin } = usePluginRegistry();\n const context = {\n ...useTimeSeriesQueryContext(),\n mode: options?.mode,\n suggestedStepMs: options?.suggestedStepMs,\n };\n\n const pluginLoaderResponse = usePlugins(\n TIME_SERIES_QUERY_KEY,\n definitions.map((d) => ({ kind: d.spec.plugin.kind }))\n );\n return useQueries({\n queries: definitions.map((definition, idx) => {\n const plugin = pluginLoaderResponse[idx]?.data;\n const { queryEnabled, queryKey } = getQueryOptions({ plugin, definition, context });\n return {\n ...queryOptions,\n enabled: (queryOptions?.enabled ?? true) && queryEnabled,\n refetchOnMount: false,\n refetchOnWindowFocus: false,\n refetchOnReconnect: false,\n staleTime: Infinity,\n queryKey: queryKey,\n queryFn: async ({ signal }: { signal: AbortSignal }): Promise<TimeSeriesData> => {\n const plugin = await getPlugin(TIME_SERIES_QUERY_KEY, definition.spec.plugin.kind);\n const data = await plugin.getTimeSeriesData(definition.spec.plugin.spec, context, signal);\n return data;\n },\n } as QueryObserverOptions;\n }),\n }) as Array<UseQueryResult<TimeSeriesData>>;\n}\n\n/**\n * Build the time series query context object from data available at runtime\n */\nfunction useTimeSeriesQueryContext(): TimeSeriesQueryContext {\n const { absoluteTimeRange } = useTimeRange();\n const variableState = useAllVariableValues();\n const datasourceStore = useDatasourceStore();\n\n return {\n timeRange: absoluteTimeRange,\n variableState,\n datasourceStore,\n };\n}\n\n/**\n * Get active time series queries for query results summary\n */\nexport function useActiveTimeSeriesQueries(): TimeSeriesDataQuery[] {\n const queryClient = useQueryClient();\n const queryCache = queryClient.getQueryCache();\n return getActiveTimeSeriesQueries(queryCache);\n}\n\n/**\n * Filter all cached queries down to only active time series queries\n */\nexport function getActiveTimeSeriesQueries(cache: QueryCache): TimeSeriesDataQuery[] {\n const queries: TimeSeriesDataQuery[] = [];\n\n for (const query of cache.findAll({ type: 'active' })) {\n const firstPart = query.queryKey?.[0] as UnknownSpec;\n if (firstPart?.kind && (firstPart.kind as string).startsWith(TIME_SERIES_QUERY_KEY)) {\n queries.push(query as Query<TimeSeriesData, unknown, TimeSeriesData, QueryKey>);\n }\n }\n\n return queries;\n}\n"],"names":["useQueries","useQuery","useQueryClient","useTimeRange","useDatasourceStore","usePlugin","usePluginRegistry","usePlugins","filterVariableStateMap","getVariableValuesKey","useAllVariableValues","TIME_SERIES_QUERY_KEY","getQueryOptions","plugin","definition","context","timeRange","suggestedStepMs","mode","variableState","dependencies","dependsOn","spec","variableDependencies","variables","filteredVariabledState","variablesValueKey","queryKey","waitToLoad","some","v","loading","queryEnabled","undefined","useTimeSeriesQuery","options","queryOptions","data","kind","useTimeSeriesQueryContext","enabled","queryFn","signal","Error","ctx","getTimeSeriesData","useTimeSeriesQueries","definitions","getPlugin","pluginLoaderResponse","map","d","queries","idx","refetchOnMount","refetchOnWindowFocus","refetchOnReconnect","staleTime","Infinity","absoluteTimeRange","datasourceStore","useActiveTimeSeriesQueries","queryClient","queryCache","getQueryCache","getActiveTimeSeriesQueries","cache","query","findAll","type","firstPart","startsWith","push"],"mappings":"AAAA,+BAA+B;AAC/B,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,6CAA6C;AAC7C,EAAE;AACF,sEAAsE;AACtE,oEAAoE;AACpE,2EAA2E;AAC3E,sEAAsE;AACtE,iCAAiC;AAGjC,SAKEA,UAAU,EACVC,QAAQ,EACRC,cAAc,QAET,wBAAwB;AAE/B,SAASC,YAAY,QAAQ,sBAAsB;AACnD,SAASC,kBAAkB,QAAQ,gBAAgB;AACnD,SAASC,SAAS,EAAEC,iBAAiB,EAAEC,UAAU,QAAQ,oBAAoB;AAC7E,SAASC,sBAAsB,EAAEC,oBAAoB,QAAQ,UAAU;AACvE,SAASC,oBAAoB,QAAQ,cAAc;AAOnD,OAAO,MAAMC,wBAAwB,kBAAkB;AAEvD,SAASC,gBAAgB,EACvBC,MAAM,EACNC,UAAU,EACVC,OAAO,EAKR;IAIC,MAAM,EAAEC,SAAS,EAAEC,eAAe,EAAEC,IAAI,EAAEC,aAAa,EAAE,GAAGJ;IAE5D,MAAMK,eAAeP,QAAQQ,YAAYR,OAAOQ,SAAS,CAACP,WAAWQ,IAAI,CAACT,MAAM,CAACS,IAAI,EAAEP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iC,EAAE;IAEzC,KAAK,MAAMe,SAASD,MAAME,OAAO,CAAC;QAAEC,MAAM;IAAS,GAAI;QACrD,MAAMC,YAAYH,MAAMxC,QAAQ,EAAE,CAAC,EAAE;QACrC,IAAI2C,WAAWhC,QAAQ,AAACgC,UAAUhC,IAAI,CAAYiC,UAAU,CAAC5D,wBAAwB;YACnFyC,QAAQoB,IAAI,CAACL;QACf;IACF;IAEA,OAAOf;AACT"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { QueryDefinition, UnknownSpec, TraceData } from '@perses-dev/
|
|
1
|
+
import { QueryDefinition, UnknownSpec, TraceData } from '@perses-dev/spec';
|
|
2
2
|
import { UseQueryResult } from '@tanstack/react-query';
|
|
3
3
|
export type TraceQueryDefinition<PluginSpec = UnknownSpec> = QueryDefinition<'TraceQuery', PluginSpec>;
|
|
4
4
|
export declare const TRACE_QUERY_KEY = "TraceQuery";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/runtime/trace-queries.ts"],"sourcesContent":["// Copyright The Perses Authors\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\nimport { QueryDefinition, UnknownSpec, TraceData } from '@perses-dev/
|
|
1
|
+
{"version":3,"sources":["../../src/runtime/trace-queries.ts"],"sourcesContent":["// Copyright The Perses Authors\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\nimport { QueryDefinition, UnknownSpec, TraceData } from '@perses-dev/spec';\nimport { QueryKey, useQueries, UseQueryResult } from '@tanstack/react-query';\nimport { TraceQueryContext, TraceQueryPlugin } from '../model';\nimport { useDatasourceStore } from './datasources';\nimport { usePluginRegistry, usePlugins } from './plugin-registry';\nimport { useTimeRange } from './TimeRangeProvider';\nimport { useAllVariableValues } from './variables';\nimport { filterVariableStateMap, getVariableValuesKey } from './utils';\nexport type TraceQueryDefinition<PluginSpec = UnknownSpec> = QueryDefinition<'TraceQuery', PluginSpec>;\nexport const TRACE_QUERY_KEY = 'TraceQuery';\n\n/**\n * Run a trace query using a TraceQuery plugin and return the results\n * @param definitions: dashboard defintion for a trace query, written in Trace Query Language (TraceQL)\n * Documentation for TraceQL: https://grafana.com/docs/tempo/latest/traceql/\n */\nexport function useTraceQueries(definitions: TraceQueryDefinition[]): Array<UseQueryResult<TraceData>> {\n const { getPlugin } = usePluginRegistry();\n const context = useTraceQueryContext();\n\n const pluginLoaderResponse = usePlugins(\n 'TraceQuery',\n definitions.map((d) => ({ kind: d.spec.plugin.kind }))\n );\n\n // useQueries() handles data fetching from query plugins (e.g. traceQL queries, promQL queries)\n // https://tanstack.com/query/v4/docs/react/reference/useQuery\n return useQueries({\n queries: definitions.map((definition, idx) => {\n const plugin = pluginLoaderResponse[idx]?.data;\n const { queryEnabled, queryKey } = getQueryOptions({ context, definition, plugin });\n const traceQueryKind = definition?.spec?.plugin?.kind;\n return {\n enabled: queryEnabled,\n queryKey: queryKey,\n refetchOnMount: false,\n refetchOnWindowFocus: false,\n refetchOnReconnect: false,\n staleTime: Infinity,\n queryFn: async ({ signal }: { signal?: AbortSignal }): Promise<TraceData> => {\n const plugin = await getPlugin(TRACE_QUERY_KEY, traceQueryKind);\n const data = await plugin.getTraceData(definition.spec.plugin.spec, context, signal);\n return data;\n },\n };\n }),\n });\n}\n\nfunction getQueryOptions({\n plugin,\n definition,\n context,\n}: {\n plugin?: TraceQueryPlugin;\n definition: TraceQueryDefinition;\n context: TraceQueryContext;\n}): {\n queryKey: QueryKey;\n queryEnabled: boolean;\n} {\n const { variableState, absoluteTimeRange } = context;\n\n const dependencies = plugin?.dependsOn ? plugin.dependsOn(definition.spec.plugin.spec, context) : {};\n const variableDependencies = dependencies?.variables;\n\n const filteredVariabledState = filterVariableStateMap(variableState, variableDependencies);\n const variablesValueKey = getVariableValuesKey(filteredVariabledState);\n const queryKey = ['query', TRACE_QUERY_KEY, definition, absoluteTimeRange, variablesValueKey] as const;\n\n let waitToLoad = false;\n if (variableDependencies) {\n waitToLoad = variableDependencies.some((v) => variableState[v]?.loading);\n }\n\n const queryEnabled = plugin !== undefined && !waitToLoad;\n return {\n queryKey,\n queryEnabled,\n };\n}\n\nfunction useTraceQueryContext(): TraceQueryContext {\n const { absoluteTimeRange } = useTimeRange();\n const variableState = useAllVariableValues();\n const datasourceStore = useDatasourceStore();\n\n return {\n variableState,\n datasourceStore,\n absoluteTimeRange,\n };\n}\n"],"names":["useQueries","useDatasourceStore","usePluginRegistry","usePlugins","useTimeRange","useAllVariableValues","filterVariableStateMap","getVariableValuesKey","TRACE_QUERY_KEY","useTraceQueries","definitions","getPlugin","context","useTraceQueryContext","pluginLoaderResponse","map","d","kind","spec","plugin","queries","definition","idx","data","queryEnabled","queryKey","getQueryOptions","traceQueryKind","enabled","refetchOnMount","refetchOnWindowFocus","refetchOnReconnect","staleTime","Infinity","queryFn","signal","getTraceData","variableState","absoluteTimeRange","dependencies","dependsOn","variableDependencies","variables","filteredVariabledState","variablesValueKey","waitToLoad","some","v","loading","undefined","datasourceStore"],"mappings":"AAAA,+BAA+B;AAC/B,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,6CAA6C;AAC7C,EAAE;AACF,sEAAsE;AACtE,oEAAoE;AACpE,2EAA2E;AAC3E,sEAAsE;AACtE,iCAAiC;AAGjC,SAAmBA,UA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B,EAAE,GAAG1B;IAE7C,MAAM2B,eAAepB,QAAQqB,YAAYrB,OAAOqB,SAAS,CAACnB,WAAWH,IAAI,CAACC,MAAM,CAACD,IAAI,EAAEN,WAAW,CAAC;IACnG,MAAM6B,uBAAuBF,cAAcG;IAE3C,MAAMC,yBAAyBrC,uBAAuB+B,eAAeI;IACrE,MAAMG,oBAAoBrC,qBAAqBoC;IAC/C,MAAMlB,WAAW;QAAC;QAASjB;QAAiBa;QAAYiB;QAAmBM;KAAkB;IAE7F,IAAIC,aAAa;IACjB,IAAIJ,sBAAsB;QACxBI,aAAaJ,qBAAqBK,IAAI,CAAC,CAACC,IAAMV,aAAa,CAACU,EAAE,EAAEC;IAClE;IAEA,MAAMxB,eAAeL,WAAW8B,aAAa,CAACJ;IAC9C,OAAO;QACLpB;QACAD;IACF;AACF;AAEA,SAASX;IACP,MAAM,EAAEyB,iBAAiB,EAAE,GAAGlC;IAC9B,MAAMiC,gBAAgBhC;IACtB,MAAM6C,kBAAkBjD;IAExB,OAAO;QACLoC;QACAa;QACAZ;IACF;AACF"}
|
package/dist/test/mock-data.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { LogData, ProfileData, TimeSeriesData, TraceData } from '@perses-dev/
|
|
1
|
+
import { LogData, ProfileData, TimeSeriesData, TraceData } from '@perses-dev/spec';
|
|
2
2
|
export declare const MOCK_TIME_SERIES_DATA: TimeSeriesData;
|
|
3
3
|
export declare const MOCK_TRACE_DATA: TraceData;
|
|
4
4
|
export declare const MOCK_LOG_DATA: LogData;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/test/mock-data.ts"],"sourcesContent":["// Copyright The Perses Authors\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\nimport { LogData, ProfileData, TimeSeriesData, TraceData } from '@perses-dev/
|
|
1
|
+
{"version":3,"sources":["../../src/test/mock-data.ts"],"sourcesContent":["// Copyright The Perses Authors\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\nimport { LogData, ProfileData, TimeSeriesData, TraceData } from '@perses-dev/spec';\n\nexport const MOCK_TIME_SERIES_DATA: TimeSeriesData = {\n timeRange: {\n start: new Date(1666625490000),\n end: new Date(1666625535000),\n },\n stepMs: 24379,\n series: [\n {\n name: 'device=\"/dev/vda1\", env=\"demo\", fstype=\"ext4\", instance=\"demo.do.prometheus.io:9100\", job=\"node\", mountpoint=\"/\"',\n values: [\n [1666479357903, 0.27700745551584494],\n [1666479382282, 0.27701284657366565],\n ],\n },\n {\n name: 'device=\"/dev/vda15\", env=\"demo\", fstype=\"vfat\", instance=\"demo.do.prometheus.io:9100\", job=\"node\", mountpoint=\"/boot/efi\"',\n values: [\n [1666479357903, 0.08486496097624885],\n [1666479382282, 0.08486496097624885],\n ],\n },\n ],\n};\n\nexport const MOCK_TRACE_DATA: TraceData = {\n searchResult: [\n {\n durationMs: 1120,\n serviceStats: {\n 'shop-backend': {\n spanCount: 4,\n errorCount: 0,\n },\n 'cart-service': {\n spanCount: 2,\n errorCount: 0,\n },\n 'article-service': {\n spanCount: 2,\n errorCount: 0,\n },\n 'auth-service': {\n spanCount: 1,\n errorCount: 0,\n },\n postgres: {\n spanCount: 1,\n errorCount: 0,\n },\n },\n startTimeUnixMs: 1699916103945861,\n traceId: '95ba9202315c29c801b5aa41452aa775',\n rootServiceName: 'shop-backend',\n rootTraceName: 'article-to-cart',\n },\n ],\n metadata: {\n executedQueryString: '{ duration > 1000ms }',\n },\n};\n\nexport const MOCK_LOG_DATA: LogData = {\n totalCount: 2,\n entries: [\n {\n timestamp: 1666479357903,\n line: 'Error: Something went wrong',\n labels: {\n level: 'error',\n service: 'backend',\n },\n },\n {\n timestamp: 1666479382282,\n line: 'Info: Request processed successfully',\n labels: {\n level: 'info',\n service: 'frontend',\n },\n },\n ],\n};\n\nexport const MOCK_PROFILE_DATA: ProfileData = {\n profile: {\n stackTrace: {\n id: 0,\n name: 'root',\n level: 0,\n start: 1699916103945861,\n end: 1699916105065861,\n total: 1000,\n self: 500,\n children: [],\n },\n },\n metadata: {\n spyName: '',\n sampleRate: 1000000000,\n units: 'samples',\n name: 'cpu',\n },\n};\n\n// Remote Plugin Loader Test Fixtures\nexport const MOCK_VALID_PLUGIN_METADATA = {\n kind: 'Panel' as const,\n spec: {\n name: 'testPlugin',\n display: {\n name: 'Test Plugin',\n description: 'A test plugin for unit testing',\n },\n },\n};\n\nexport const MOCK_VALID_PLUGIN_MODULE_RESOURCE = {\n kind: 'PluginModule' as const,\n metadata: {\n name: 'test-module',\n version: '1.0.0',\n },\n spec: {\n plugins: [MOCK_VALID_PLUGIN_METADATA],\n },\n};\n\nexport const MOCK_INVALID_PLUGIN_MODULE = {\n // Missing required fields\n metadata: {\n name: 'invalid-module',\n },\n spec: {\n plugins: [\n {\n // Missing required fields\n kind: 'Panel',\n },\n ],\n },\n};\n\nexport const MOCK_MIXED_VALIDITY_PLUGIN_MODULES = [\n MOCK_VALID_PLUGIN_MODULE_RESOURCE,\n MOCK_INVALID_PLUGIN_MODULE,\n {\n kind: 'PluginModule' as const,\n metadata: {\n name: 'another-valid-module',\n version: '2.0.0',\n },\n spec: {\n plugins: [\n {\n kind: 'Variable' as const,\n spec: {\n name: 'anotherPlugin',\n display: {\n name: 'Another Plugin',\n },\n },\n },\n ],\n },\n },\n];\n\nexport const MOCK_REMOTE_PLUGIN_MODULE = {\n testPlugin: {\n component: (): null => null,\n createDefaultOptions: (): Record<string, unknown> => ({}),\n },\n};\n\nexport const MOCK_MULTI_PLUGIN_MODULE = {\n kind: 'PluginModule' as const,\n metadata: {\n name: 'multi-plugin-module',\n version: '1.0.0',\n },\n spec: {\n plugins: [\n {\n kind: 'Panel' as const,\n spec: {\n name: 'plugin1',\n display: { name: 'Plugin 1' },\n },\n },\n {\n kind: 'Variable' as const,\n spec: {\n name: 'plugin2',\n display: { name: 'Plugin 2' },\n },\n },\n ],\n },\n};\n\nexport const MOCK_PARTIAL_FAILURE_MODULE = {\n kind: 'PluginModule' as const,\n metadata: {\n name: 'partial-failure-module',\n version: '1.0.0',\n },\n spec: {\n plugins: [\n {\n kind: 'Panel' as const,\n spec: {\n name: 'workingPlugin',\n display: { name: 'Working Plugin' },\n },\n },\n {\n kind: 'Variable' as const,\n spec: {\n name: 'failingPlugin',\n display: { name: 'Failing Plugin' },\n },\n },\n ],\n },\n};\n\nexport const MOCK_EMPTY_PLUGIN_MODULE = {\n kind: 'PluginModule' as const,\n metadata: {\n name: 'empty-module',\n version: '1.0.0',\n },\n spec: {\n plugins: [],\n },\n};\n"],"names":["MOCK_TIME_SERIES_DATA","timeRange","start","Date","end","stepMs","series","name","values","MOCK_TRACE_DATA","searchResult","durationMs","serviceStats","spanCount","errorCount","postgres","startTimeUnixMs","traceId","rootServiceName","rootTraceName","metadata","executedQueryString","MOCK_LOG_DATA","totalCount","entries","timestamp","line","labels","level","service","MOCK_PROFILE_DATA","profile","stackTrace","id","total","self","children","spyName","sampleRate","units","MOCK_VALID_PLUGIN_METADATA","kind","spec","display","description","MOCK_VALID_PLUGIN_MODULE_RESOURCE","version","plugins","MOCK_INVALID_PLUGIN_MODULE","MOCK_MIXED_VALIDITY_PLUGIN_MODULES","MOCK_REMOTE_PLUGIN_MODULE","testPlugin","component","createDefaultOptions","MOCK_MULTI_PLUGIN_MODUL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,MAAM;oBAAW;gBAC9B;YACF;YACA;gBACEkC,MAAM;gBACNC,MAAM;oBACJnC,MAAM;oBACNoC,SAAS;wBAAEpC,MAAM;oBAAW;gBAC9B;YACF;SACD;IACH;AACF,EAAE;AAEF,OAAO,MAAMgD,8BAA8B;IACzCd,MAAM;IACNrB,UAAU;QACRb,MAAM;QACNuC,SAAS;IACX;IACAJ,MAAM;QACJK,SAAS;YACP;gBACEN,MAAM;gBACNC,MAAM;oBACJnC,MAAM;oBACNoC,SAAS;wBAAEpC,MAAM;oBAAiB;gBACpC;YACF;YACA;gBACEkC,MAAM;gBACNC,MAAM;oBACJnC,MAAM;oBACNoC,SAAS;wBAAEpC,MAAM;oBAAiB;gBACpC;YACF;SACD;IACH;AACF,EAAE;AAEF,OAAO,MAAMiD,2BAA2B;IACtCf,MAAM;IACNrB,UAAU;QACRb,MAAM;QACNuC,SAAS;IACX;IACAJ,MAAM;QACJK,SAAS,EAAE;IACb;AACF,EAAE"}
|
package/dist/test/utils.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../../src/test/utils.tsx"],"names":[],"mappings":"AAcA,OAAO,EAAE,SAAS,EAAE,MAAM,OAAO,CAAC;AAGlC,OAAO,EAAE,kBAAkB,EAAE,MAAM,UAAU,CAAC;AAI9C,MAAM,MAAM,cAAc,GAAG;IAC3B,kBAAkB,CAAC,EAAE,kBAAkB,CAAC;CACzC,CAAC;AAEF,wBAAgB,qBAAqB,CAAC,cAAc,CAAC,EAAE,cAAc,
|
|
1
|
+
{"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../../src/test/utils.tsx"],"names":[],"mappings":"AAcA,OAAO,EAAE,SAAS,EAAE,MAAM,OAAO,CAAC;AAGlC,OAAO,EAAE,kBAAkB,EAAE,MAAM,UAAU,CAAC;AAI9C,MAAM,MAAM,cAAc,GAAG;IAC3B,kBAAkB,CAAC,EAAE,kBAAkB,CAAC;CACzC,CAAC;AAEF,wBAAgB,qBAAqB,CAAC,cAAc,CAAC,EAAE,cAAc,kBAQ7B;IAAE,QAAQ,EAAE,SAAS,CAAA;CAAE,KAAG,SAAS,CAkB1E"}
|
package/dist/test/utils.js
CHANGED
|
@@ -12,7 +12,6 @@
|
|
|
12
12
|
// limitations under the License.
|
|
13
13
|
import { jsx as _jsx } from "react/jsx-runtime";
|
|
14
14
|
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
|
|
15
|
-
import { DEFAULT_DASHBOARD_DURATION } from '@perses-dev/core';
|
|
16
15
|
import { PluginRegistry } from '../components';
|
|
17
16
|
import { TimeRangeProviderBasic } from '../runtime';
|
|
18
17
|
import { testPluginLoader } from './test-plugins';
|
|
@@ -26,6 +25,7 @@ export function getTestContextWrapper(contextOptions) {
|
|
|
26
25
|
}
|
|
27
26
|
}
|
|
28
27
|
});
|
|
28
|
+
const DEFAULT_DASHBOARD_DURATION = '1h';
|
|
29
29
|
const timeRange = {
|
|
30
30
|
start: new Date(Date.now() - Number(DEFAULT_DASHBOARD_DURATION)),
|
|
31
31
|
end: new Date()
|
package/dist/test/utils.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/test/utils.tsx"],"sourcesContent":["// Copyright The Perses Authors\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\nimport { QueryClient, QueryClientProvider } from '@tanstack/react-query';\nimport { ReactNode } from 'react';\nimport {
|
|
1
|
+
{"version":3,"sources":["../../src/test/utils.tsx"],"sourcesContent":["// Copyright The Perses Authors\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\nimport { QueryClient, QueryClientProvider } from '@tanstack/react-query';\nimport { ReactNode } from 'react';\nimport { DurationString } from '@perses-dev/spec';\nimport { PluginRegistry } from '../components';\nimport { DefaultPluginKinds } from '../model';\nimport { TimeRangeProviderBasic } from '../runtime';\nimport { testPluginLoader } from './test-plugins';\n\nexport type ContextOptions = {\n defaultPluginKinds?: DefaultPluginKinds;\n};\n\nexport function getTestContextWrapper(contextOptions?: ContextOptions) {\n // Create a new QueryClient for each test to avoid caching issues\n const queryClient = new QueryClient({\n defaultOptions: { queries: { refetchOnWindowFocus: false, retry: false } },\n });\n const DEFAULT_DASHBOARD_DURATION: DurationString = '1h';\n const timeRange = { start: new Date(Date.now() - Number(DEFAULT_DASHBOARD_DURATION)), end: new Date() };\n\n return function Wrapper({ children }: { children: ReactNode }): ReactNode {\n return (\n <QueryClientProvider client={queryClient}>\n <TimeRangeProviderBasic initialTimeRange={timeRange}>\n <PluginRegistry\n pluginLoader={testPluginLoader}\n defaultPluginKinds={\n contextOptions?.defaultPluginKinds ?? {\n TimeSeriesQuery: 'PrometheusTimeSeriesQuery',\n }\n }\n >\n {children}\n </PluginRegistry>\n </TimeRangeProviderBasic>\n </QueryClientProvider>\n );\n };\n}\n"],"names":["QueryClient","QueryClientProvider","PluginRegistry","TimeRangeProviderBasic","testPluginLoader","getTestContextWrapper","contextOptions","queryClient","defaultOptions","queries","refetchOnWindowFocus","retry","DEFAULT_DASHBOARD_DURATION","timeRange","start","Date","now","Number","end","Wrapper","children","client","initialTimeRange","pluginLoader","defaultPluginKinds","TimeSeriesQuery"],"mappings":"AAAA,+BAA+B;AAC/B,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,6CAA6C;AAC7C,EAAE;AACF,sEAAsE;AACtE,oEAAoE;AACpE,2EAA2E;AAC3E,sEAAsE;AACtE,iCAAiC;;AAEjC,SAASA,WAAW,EAAEC,mBAAmB,QAAQ,wBAAwB;AAGzE,SAASC,cAAc,QAAQ,gBAAgB;AAE/C,SAASC,sBAAsB,QAAQ,aAAa;AACpD,SAASC,gBAAgB,QAAQ,iBAAiB;AAMlD,OAAO,SAASC,sBAAsBC,cAA+B;IACnE,iEAAiE;IACjE,MAAMC,cAAc,IAAIP,YAAY;QAClCQ,gBAAgB;YAAEC,SAAS;gBAAEC,sBAAsB;gBAAOC,OAAO;YAAM;QAAE;IAC3E;IACA,MAAMC,6BAA6C;IACnD,MAAMC,YAAY;QAAEC,OAAO,IAAIC,KAAKA,KAAKC,GAAG,KAAKC,OAAOL;QAA8BM,KAAK,IAAIH;IAAO;IAEtG,OAAO,SAASI,QAAQ,EAAEC,QAAQ,EAA2B;QAC3D,qBACE,KAACnB;YAAoBoB,QAAQd;sBAC3B,cAAA,KAACJ;gBAAuBmB,kBAAkBT;0BACxC,cAAA,KAACX;oBACCqB,cAAcnB;oBACdoB,oBACElB,gBAAgBkB,sBAAsB;wBACpCC,iBAAiB;oBACnB;8BAGDL;;;;IAKX;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/test-utils/mock-plugin-registry.tsx"],"sourcesContent":["// Copyright The Perses Authors\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\nimport { UnknownSpec } from '@perses-dev/
|
|
1
|
+
{"version":3,"sources":["../../src/test-utils/mock-plugin-registry.tsx"],"sourcesContent":["// Copyright The Perses Authors\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\nimport { UnknownSpec } from '@perses-dev/spec';\nimport { PluginRegistryProps } from '../components';\nimport { PluginModuleResource, Plugin, PluginLoader, PluginImplementation, PluginType } from '../model';\n\nexport type MockPlugin = {\n [T in PluginType]: {\n kind: T;\n spec: { name: string };\n plugin: PluginImplementation<T>;\n };\n}[PluginType];\n\n/**\n * Helper for mocking `PluginRegistry` data during tests. Returns props that can be spread on the `PluginRegistry`\n * component so that it will load the mock plugins you provide.\n */\nexport function mockPluginRegistry(...mockPlugins: MockPlugin[]): Omit<PluginRegistryProps, 'children'> {\n const mockPluginResource: PluginModuleResource = {\n kind: 'PluginModule',\n metadata: {\n name: 'Fake Plugin Module for Tests',\n version: '0',\n },\n spec: {\n // Add metadata for all mock plugins\n plugins: mockPlugins.map(({ kind, spec: { name } }) => ({\n kind,\n spec: {\n name,\n display: {\n name: getMockPluginName(kind, name),\n },\n },\n })),\n },\n };\n\n const mockPluginModule: Record<string, Plugin<UnknownSpec>> = {};\n for (const mockPlugin of mockPlugins) {\n // \"Export\" on the module under the same name as the kind the plugin handles\n mockPluginModule[mockPlugin.spec.name] = mockPlugin.plugin;\n }\n\n const pluginLoader: PluginLoader = {\n getInstalledPlugins() {\n return Promise.resolve([mockPluginResource]);\n },\n importPluginModule(/* resource */) {\n return Promise.resolve(mockPluginModule);\n },\n };\n\n return {\n pluginLoader,\n defaultPluginKinds: {\n TimeSeriesQuery: 'PrometheusTimeSeriesQuery',\n },\n };\n}\n\n/**\n * The function that's used to generate the display name of mocked plugins in mockPluginRegistry. Can be useful if you\n * need to interact with some UI component that's displaying it.\n */\nexport function getMockPluginName(kind: PluginType, name: string): string {\n return `${kind} Plugin for ${name}`;\n}\n"],"names":["mockPluginRegistry","mockPlugins","mockPluginResource","kind","metadata","name","version","spec","plugins","map","display","getMockPluginName","mockPluginModule","mockPlugin","plugin","pluginLoader","getInstalledPlugins","Promise","resolve","importPluginModule","defaultPluginKinds","TimeSeriesQuery"],"mappings":"AAAA,+BAA+B;AAC/B,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,6CAA6C;AAC7C,EAAE;AACF,sEAAsE;AACtE,oEAAoE;AACpE,2EAA2E;AAC3E,sEAAsE;AACtE,iCAAiC;AAcjC;;;CAGC,GACD,OAAO,SAASA,mBAAmB,GAAGC,WAAyB;IAC7D,MAAMC,qBAA2C;QAC/CC,MAAM;QACNC,UAAU;YACRC,MAAM;YACNC,SAAS;QACX;QACAC,MAAM;YACJ,oCAAoC;YACpCC,SAASP,YAAYQ,GAAG,CAAC,CAAC,EAAEN,IAAI,EAAEI,MAAM,EAAEF,IAAI,EAAE,EAAE,GAAM,CAAA;oBACtDF;oBACAI,MAAM;wBACJF;wBACAK,SAAS;4BACPL,MAAMM,kBAAkBR,MAAME;wBAChC;oBACF;gBACF,CAAA;QACF;IACF;IAEA,MAAMO,mBAAwD,CAAC;IAC/D,KAAK,MAAMC,cAAcZ,YAAa;QACpC,4EAA4E;QAC5EW,gBAAgB,CAACC,WAAWN,IAAI,CAACF,IAAI,CAAC,GAAGQ,WAAWC,MAAM;IAC5D;IAEA,MAAMC,eAA6B;QACjCC;YACE,OAAOC,QAAQC,OAAO,CAAC;gBAAChB;aAAmB;QAC7C;QACAiB;YACE,OAAOF,QAAQC,OAAO,CAACN;QACzB;IACF;IAEA,OAAO;QACLG;QACAK,oBAAoB;YAClBC,iBAAiB;QACnB;IACF;AACF;AAEA;;;CAGC,GACD,OAAO,SAASV,kBAAkBR,IAAgB,EAAEE,IAAY;IAC9D,OAAO,GAAGF,KAAK,YAAY,EAAEE,MAAM;AACrC"}
|
package/dist/utils/index.d.ts
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/utils/index.ts"],"names":[],"mappings":"AAaA,cAAc,
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/utils/index.ts"],"names":[],"mappings":"AAaA,cAAc,SAAS,CAAC;AACxB,cAAc,aAAa,CAAC;AAC5B,cAAc,cAAc,CAAC"}
|
package/dist/utils/index.js
CHANGED
|
@@ -10,7 +10,6 @@
|
|
|
10
10
|
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
11
11
|
// See the License for the specific language governing permissions and
|
|
12
12
|
// limitations under the License.
|
|
13
|
-
export * from './action';
|
|
14
13
|
export * from './event';
|
|
15
14
|
export * from './variables';
|
|
16
15
|
export * from './csv-export';
|
package/dist/utils/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/utils/index.ts"],"sourcesContent":["// Copyright The Perses Authors\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\nexport * from './
|
|
1
|
+
{"version":3,"sources":["../../src/utils/index.ts"],"sourcesContent":["// Copyright The Perses Authors\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\nexport * from './event';\nexport * from './variables';\nexport * from './csv-export';\n"],"names":[],"mappings":"AAAA,+BAA+B;AAC/B,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,6CAA6C;AAC7C,EAAE;AACF,sEAAsE;AACtE,oEAAoE;AACpE,2EAA2E;AAC3E,sEAAsE;AACtE,iCAAiC;AAEjC,cAAc,UAAU;AACxB,cAAc,cAAc;AAC5B,cAAc,eAAe"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@perses-dev/plugin-system",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.54.0-beta.1",
|
|
4
4
|
"description": "The plugin feature in Pereses",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"homepage": "https://github.com/perses/perses/blob/main/README.md",
|
|
@@ -28,20 +28,23 @@
|
|
|
28
28
|
"lint:fix": "eslint --fix src --ext .ts,.tsx"
|
|
29
29
|
},
|
|
30
30
|
"dependencies": {
|
|
31
|
-
"@module-federation/enhanced": "^
|
|
32
|
-
"@perses-dev/components": "0.
|
|
31
|
+
"@module-federation/enhanced": "^2.3.3",
|
|
32
|
+
"@perses-dev/components": "0.54.0-beta.1",
|
|
33
33
|
"@perses-dev/core": "0.53.0",
|
|
34
|
+
"@perses-dev/spec": "0.2.0-beta.0",
|
|
34
35
|
"date-fns": "^4.1.0",
|
|
35
36
|
"date-fns-tz": "^3.2.0",
|
|
36
37
|
"immer": "^10.1.1",
|
|
37
38
|
"react-hook-form": "^7.46.1",
|
|
38
39
|
"use-immer": "^0.11.0",
|
|
39
40
|
"use-query-params": "^2.2.1",
|
|
40
|
-
"zod": "^3.
|
|
41
|
+
"zod": "^3.25.76"
|
|
41
42
|
},
|
|
42
43
|
"peerDependencies": {
|
|
43
|
-
"@
|
|
44
|
+
"@emotion/react": "^11.14.0",
|
|
45
|
+
"@emotion/styled": "^11.14.1",
|
|
44
46
|
"@hookform/resolvers": "^3.2.0",
|
|
47
|
+
"@mui/material": "^6.1.10",
|
|
45
48
|
"@tanstack/react-query": "^4.39.1",
|
|
46
49
|
"react": "^17.0.2 || ^18.0.0",
|
|
47
50
|
"react-dom": "^17.0.2 || ^18.0.0"
|