@perses-dev/plugin-system 0.53.0 → 0.54.0-beta.0
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/TimeRangeControls/TimeRangeControls.js +2 -2
- package/dist/cjs/components/Variables/VariableEditorForm/VariableEditorForm.js +50 -22
- package/dist/cjs/context/ValidationProvider.js +5 -4
- package/dist/cjs/model/index.js +2 -0
- package/dist/cjs/model/log-volume-utils.js +124 -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/utils/csv-export.js +248 -0
- package/dist/cjs/utils/index.js +1 -0
- package/dist/components/CalculationSelector/CalculationSelector.js +1 -1
- package/dist/components/CalculationSelector/CalculationSelector.js.map +1 -1
- 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.js +1 -1
- package/dist/components/LegendOptionsEditor/LegendOptionsEditor.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 +50 -22
- 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/datasource.d.ts +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 +2 -0
- package/dist/model/index.d.ts.map +1 -1
- package/dist/model/index.js +2 -0
- package/dist/model/index.js.map +1 -1
- package/dist/model/legend.js +1 -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 +1 -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.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/action.js.map +1 -1
- package/dist/utils/csv-export.d.ts +39 -0
- package/dist/utils/csv-export.d.ts.map +1 -0
- package/dist/utils/csv-export.js +214 -0
- package/dist/utils/csv-export.js.map +1 -0
- package/dist/utils/index.d.ts +1 -0
- package/dist/utils/index.d.ts.map +1 -1
- package/dist/utils/index.js +1 -0
- package/dist/utils/index.js.map +1 -1
- package/package.json +9 -6
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/runtime/TimeRangeProvider/TimeRangeProviders.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 { DurationString, TimeRangeValue } from '@perses-dev/
|
|
1
|
+
{"version":3,"sources":["../../../src/runtime/TimeRangeProvider/TimeRangeProviders.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 { DurationString, TimeRangeValue } from '@perses-dev/spec';\nimport React, { ReactElement } from 'react';\nimport { TimeZoneProvider } from '@perses-dev/components';\nimport { TimeRangeProvider } from './TimeRangeProvider';\nimport { useSetRefreshIntervalParams, useTimeRangeParams, useTimeZoneParams } from './query-params';\n\nexport interface TimeRangeProvidersProps {\n initialTimeRange: TimeRangeValue;\n initialRefreshInterval?: DurationString;\n children?: React.ReactNode;\n}\n\nexport function TimeRangeProviderWithQueryParams({\n initialTimeRange,\n initialRefreshInterval,\n children,\n}: TimeRangeProvidersProps): ReactElement {\n const { timeRange, setTimeRange } = useTimeRangeParams(initialTimeRange);\n const { refreshInterval, setRefreshInterval } = useSetRefreshIntervalParams(initialRefreshInterval);\n const { timeZone } = useTimeZoneParams('local');\n\n return (\n <TimeRangeProvider\n timeRange={timeRange}\n refreshInterval={refreshInterval}\n setTimeRange={setTimeRange}\n setRefreshInterval={setRefreshInterval}\n >\n <TimeZoneProvider timeZone={timeZone}>{children}</TimeZoneProvider>\n </TimeRangeProvider>\n );\n}\n\nexport function TimeRangeProviderBasic({\n initialTimeRange,\n initialRefreshInterval,\n children,\n}: TimeRangeProvidersProps): ReactElement {\n const [timeRange, setTimeRange] = React.useState<TimeRangeValue>(initialTimeRange);\n const [refreshInterval, setRefreshInterval] = React.useState<DurationString | undefined>(initialRefreshInterval);\n\n return (\n <TimeRangeProvider\n timeRange={timeRange}\n refreshInterval={refreshInterval}\n setTimeRange={setTimeRange}\n setRefreshInterval={setRefreshInterval}\n >\n {children}\n </TimeRangeProvider>\n );\n}\n"],"names":["React","TimeZoneProvider","TimeRangeProvider","useSetRefreshIntervalParams","useTimeRangeParams","useTimeZoneParams","TimeRangeProviderWithQueryParams","initialTimeRange","initialRefreshInterval","children","timeRange","setTimeRange","refreshInterval","setRefreshInterval","timeZone","TimeRangeProviderBasic","useState"],"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,OAAOA,WAA6B,QAAQ;AAC5C,SAASC,gBAAgB,QAAQ,yBAAyB;AAC1D,SAASC,iBAAiB,QAAQ,sBAAsB;AACxD,SAASC,2BAA2B,EAAEC,kBAAkB,EAAEC,iBAAiB,QAAQ,iBAAiB;AAQpG,OAAO,SAASC,iCAAiC,EAC/CC,gBAAgB,EAChBC,sBAAsB,EACtBC,QAAQ,EACgB;IACxB,MAAM,EAAEC,SAAS,EAAEC,YAAY,EAAE,GAAGP,mBAAmBG;IACvD,MAAM,EAAEK,eAAe,EAAEC,kBAAkB,EAAE,GAAGV,4BAA4BK;IAC5E,MAAM,EAAEM,QAAQ,EAAE,GAAGT,kBAAkB;IAEvC,qBACE,KAACH;QACCQ,WAAWA;QACXE,iBAAiBA;QACjBD,cAAcA;QACdE,oBAAoBA;kBAEpB,cAAA,KAACZ;YAAiBa,UAAUA;sBAAWL;;;AAG7C;AAEA,OAAO,SAASM,uBAAuB,EACrCR,gBAAgB,EAChBC,sBAAsB,EACtBC,QAAQ,EACgB;IACxB,MAAM,CAACC,WAAWC,aAAa,GAAGX,MAAMgB,QAAQ,CAAiBT;IACjE,MAAM,CAACK,iBAAiBC,mBAAmB,GAAGb,MAAMgB,QAAQ,CAA6BR;IAEzF,qBACE,KAACN;QACCQ,WAAWA;QACXE,iBAAiBA;QACjBD,cAAcA;QACdE,oBAAoBA;kBAEnBJ;;AAGP"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/runtime/TimeRangeProvider/TimeRangeSettingsProvider.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 { createContext, ReactElement, ReactNode, useContext, useMemo } from 'react';\nimport { buildRelativeTimeOption, TimeOption } from '@perses-dev/components';\nimport { DurationString } from '@perses-dev/
|
|
1
|
+
{"version":3,"sources":["../../../src/runtime/TimeRangeProvider/TimeRangeSettingsProvider.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 { createContext, ReactElement, ReactNode, useContext, useMemo } from 'react';\nimport { buildRelativeTimeOption, TimeOption } from '@perses-dev/components';\nimport { DurationString } from '@perses-dev/spec';\n\nconst DEFAULT_OPTIONS: DurationString[] = ['5m', '15m', '30m', '1h', '6h', '12h', '24h', '7d', '14d'];\nconst defaultTimeRangeSettings: TimeRangeSettings = {\n showCustom: true,\n showZoomButtons: true,\n options: DEFAULT_OPTIONS.map((duration) => buildRelativeTimeOption(duration)),\n};\n\nexport interface TimeRangeSettingsProviderProps {\n showCustom?: boolean;\n showZoomButtons?: boolean;\n options?: TimeOption[];\n children: ReactNode;\n}\n\nexport interface TimeRangeSettings {\n showCustom: boolean;\n showZoomButtons: boolean;\n options: TimeOption[];\n}\n\nexport const TimeRangeSettingsContext = createContext<TimeRangeSettings>(defaultTimeRangeSettings);\n\nexport function useTimeRangeSettingsContext(): TimeRangeSettings {\n const ctx = useContext(TimeRangeSettingsContext);\n if (ctx === undefined) {\n throw new Error('No TimeRangeContext found. Did you forget a Provider?');\n }\n return ctx;\n}\n\n/**\n * Get and set the current resolved time range at runtime.\n */\nexport function useTimeRangeSettings(): TimeRangeSettings {\n return useTimeRangeSettingsContext();\n}\n\n/**\n * Get the current value of the showCustom setting.\n * @param override If set, the value of the provider will be overridden by this value.\n */\nexport function useShowCustomTimeRangeSetting(override?: boolean): boolean {\n const showCustomTimeRange = useTimeRangeSettings().showCustom;\n if (override !== undefined) {\n return override;\n }\n return showCustomTimeRange;\n}\n\n/**\n * Get the current value of the showZoomButtons setting.\n * @param override If set, the value of the provider will be overridden by this value.\n */\nexport function useShowZoomRangeSetting(override?: boolean): boolean {\n const showZoomTimeRange = useTimeRangeSettings().showZoomButtons;\n if (override !== undefined) {\n return override;\n }\n return showZoomTimeRange;\n}\n\n/**\n * Get the current value of the options setting.\n * @param override If set, the value of the provider will be overridden by this value.\n */\nexport function useTimeRangeOptionsSetting(override?: TimeOption[]): TimeOption[] {\n const showCustomTimeRange = useTimeRangeSettings().options;\n if (override !== undefined) {\n return override;\n }\n return showCustomTimeRange;\n}\n\n/**\n * Provider implementation that supplies the time range state at runtime.\n */\nexport function TimeRangeSettingsProvider(props: TimeRangeSettingsProviderProps): ReactElement {\n const ctx = useMemo(() => {\n return {\n showCustom: props.showCustom === undefined ? defaultTimeRangeSettings.showCustom : props.showCustom,\n showZoomButtons:\n props.showZoomButtons === undefined ? defaultTimeRangeSettings.showZoomButtons : props.showZoomButtons,\n options: props.options === undefined ? defaultTimeRangeSettings.options : props.options,\n };\n }, [props.showCustom, props.showZoomButtons, props.options]);\n\n return <TimeRangeSettingsContext.Provider value={ctx}>{props.children}</TimeRangeSettingsContext.Provider>;\n}\n"],"names":["createContext","useContext","useMemo","buildRelativeTimeOption","DEFAULT_OPTIONS","defaultTimeRangeSettings","showCustom","showZoomButtons","options","map","duration","TimeRangeSettingsContext","useTimeRangeSettingsContext","ctx","undefined","Error","useTimeRangeSettings","useShowCustomTimeRangeSetting","override","showCustomTimeRange","useShowZoomRangeSetting","showZoomTimeRange","useTimeRangeOptionsSetting","TimeRangeSettingsProvider","props","Provider","value","children"],"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,aAAa,EAA2BC,UAAU,EAAEC,OAAO,QAAQ,QAAQ;AACpF,SAASC,uBAAuB,QAAoB,yBAAyB;AAG7E,MAAMC,kBAAoC;IAAC;IAAM;IAAO;IAAO;IAAM;IAAM;IAAO;IAAO;IAAM;CAAM;AACrG,MAAMC,2BAA8C;IAClDC,YAAY;IACZC,iBAAiB;IACjBC,SAASJ,gBAAgBK,GAAG,CAAC,CAACC,WAAaP,wBAAwBO;AACrE;AAeA,OAAO,MAAMC,yCAA2BX,cAAiCK,0BAA0B;AAEnG,OAAO,SAASO;IACd,MAAMC,MAAMZ,WAAWU;IACvB,IAAIE,QAAQC,WAAW;QACrB,MAAM,IAAIC,MAAM;IAClB;IACA,OAAOF;AACT;AAEA;;CAEC,GACD,OAAO,SAASG;IACd,OAAOJ;AACT;AAEA;;;CAGC,GACD,OAAO,SAASK,8BAA8BC,QAAkB;IAC9D,MAAMC,sBAAsBH,uBAAuBV,UAAU;IAC7D,IAAIY,aAAaJ,WAAW;QAC1B,OAAOI;IACT;IACA,OAAOC;AACT;AAEA;;;CAGC,GACD,OAAO,SAASC,wBAAwBF,QAAkB;IACxD,MAAMG,oBAAoBL,uBAAuBT,eAAe;IAChE,IAAIW,aAAaJ,WAAW;QAC1B,OAAOI;IACT;IACA,OAAOG;AACT;AAEA;;;CAGC,GACD,OAAO,SAASC,2BAA2BJ,QAAuB;IAChE,MAAMC,sBAAsBH,uBAAuBR,OAAO;IAC1D,IAAIU,aAAaJ,WAAW;QAC1B,OAAOI;IACT;IACA,OAAOC;AACT;AAEA;;CAEC,GACD,OAAO,SAASI,0BAA0BC,KAAqC;IAC7E,MAAMX,MAAMX,QAAQ;QAClB,OAAO;YACLI,YAAYkB,MAAMlB,UAAU,KAAKQ,YAAYT,yBAAyBC,UAAU,GAAGkB,MAAMlB,UAAU;YACnGC,iBACEiB,MAAMjB,eAAe,KAAKO,YAAYT,yBAAyBE,eAAe,GAAGiB,MAAMjB,eAAe;YACxGC,SAASgB,MAAMhB,OAAO,KAAKM,YAAYT,yBAAyBG,OAAO,GAAGgB,MAAMhB,OAAO;QACzF;IACF,GAAG;QAACgB,MAAMlB,UAAU;QAAEkB,MAAMjB,eAAe;QAAEiB,MAAMhB,OAAO;KAAC;IAE3D,qBAAO,KAACG,yBAAyBc,QAAQ;QAACC,OAAOb;kBAAMW,MAAMG,QAAQ;;AACvE"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { QueryParamConfig } from 'use-query-params';
|
|
2
|
-
import { TimeRangeValue, DurationString } from '@perses-dev/
|
|
2
|
+
import { TimeRangeValue, DurationString } from '@perses-dev/spec';
|
|
3
3
|
import { TimeRange } from './TimeRangeProvider';
|
|
4
4
|
export type TimeOptionValue = Date | DurationString | null | undefined;
|
|
5
5
|
export declare function encodeTimeRangeValue(timeOptionValue: TimeOptionValue): string | null | undefined;
|
|
@@ -13,7 +13,7 @@
|
|
|
13
13
|
import { useMemo, useCallback, useEffect, useState } from 'react';
|
|
14
14
|
import { useQueryParams, StringParam } from 'use-query-params';
|
|
15
15
|
import { getUnixTime, isDate } from 'date-fns';
|
|
16
|
-
import { isRelativeTimeRange, isDurationString } from '@perses-dev/
|
|
16
|
+
import { isRelativeTimeRange, isDurationString } from '@perses-dev/spec';
|
|
17
17
|
/* Interprets an encoded string and returns either the string or null/undefined if not available */ function getEncodedValue(input, allowEmptyString) {
|
|
18
18
|
// '' or []
|
|
19
19
|
if (!input || input.length === 0 && (!allowEmptyString || allowEmptyString && input !== '')) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/runtime/TimeRangeProvider/query-params.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 { useMemo, useCallback, useEffect, useState } from 'react';\nimport { QueryParamConfig, useQueryParams, StringParam } from 'use-query-params';\nimport { getUnixTime, isDate } from 'date-fns';\nimport {\n TimeRangeValue,\n isRelativeTimeRange,\n isDurationString,\n DurationString,\n AbsoluteTimeRange,\n} from '@perses-dev/core';\nimport { TimeRange } from './TimeRangeProvider';\n\nexport type TimeOptionValue = Date | DurationString | null | undefined;\n\n/* Interprets an encoded string and returns either the string or null/undefined if not available */\nfunction getEncodedValue(\n input: string | Array<string | null> | null | undefined,\n allowEmptyString?: boolean\n): string | null | undefined {\n // '' or []\n if (!input || (input.length === 0 && (!allowEmptyString || (allowEmptyString && input !== '')))) {\n return null;\n }\n\n const str = input instanceof Array ? input[0] : input;\n if (str === null || str === undefined) {\n return str;\n }\n if (!allowEmptyString && str === '') {\n return null;\n }\n\n return str;\n}\n\n/* Encodes individual TimeRangeValue as a string, depends on whether start is relative or absolute */\nexport function encodeTimeRangeValue(timeOptionValue: TimeOptionValue): string | null | undefined {\n if (!timeOptionValue) {\n return timeOptionValue;\n }\n\n if (typeof timeOptionValue === 'string') {\n if (isDurationString(timeOptionValue)) {\n return timeOptionValue;\n }\n }\n return (getUnixTime(timeOptionValue) * 1000).toString();\n}\n\n/* Converts param input to supported relative or absolute time range format */\nexport function decodeTimeRangeValue(\n input: string | Array<string | null> | null | undefined\n): Date | DurationString | null | undefined {\n const paramString = getEncodedValue(input);\n if (!paramString) return null;\n return isDurationString(paramString) ? paramString : new Date(Number(paramString));\n}\n\n/**\n * Custom TimeRangeValue param type\n * See: https://github.com/pbeshai/use-query-params/tree/master/packages/serialize-query-params#param-types\n */\nexport const TimeRangeParam: QueryParamConfig<TimeOptionValue, TimeOptionValue> = {\n encode: encodeTimeRangeValue,\n decode: decodeTimeRangeValue,\n equals: (valueA: TimeOptionValue, valueB: TimeOptionValue) => {\n if (valueA === valueB) return true;\n if (!valueA || !valueB) return valueA === valueB;\n return valueA.valueOf() === valueB.valueOf();\n },\n};\n\nexport const timeRangeQueryConfig = {\n start: TimeRangeParam,\n end: TimeRangeParam,\n};\n\nexport const refreshIntervalQueryConfig = {\n refresh: TimeRangeParam,\n};\n\nexport const timeZoneQueryConfig = {\n tz: StringParam,\n};\n\n/**\n * Gets the initial time range taking into account URL params and dashboard JSON duration\n * Sets start query param if it is empty on page load\n */\nexport function useInitialTimeRange(dashboardDuration: DurationString): TimeRangeValue {\n const [query] = useQueryParams(timeRangeQueryConfig, { updateType: 'replaceIn' });\n const { start, end } = query;\n\n return useMemo(() => {\n let initialTimeRange: TimeRangeValue = { pastDuration: dashboardDuration };\n if (!start) {\n return initialTimeRange;\n }\n const startStr = start.toString();\n if (isDurationString(startStr)) {\n initialTimeRange = { pastDuration: startStr };\n } else if (isDate(start) && isDate(end)) {\n initialTimeRange = { start: start, end: end } as AbsoluteTimeRange;\n }\n return initialTimeRange;\n }, [start, end, dashboardDuration]);\n}\n\n/**\n * Returns time range getter and setter, taking the URL query params.\n */\nexport function useTimeRangeParams(initialTimeRange: TimeRangeValue): Pick<TimeRange, 'timeRange' | 'setTimeRange'> {\n const [query, setQuery] = useQueryParams(timeRangeQueryConfig, { updateType: 'replaceIn' });\n // determine whether initial param had previously been populated to fix back btn\n const [paramsLoaded, setParamsLoaded] = useState<boolean>(false);\n\n const { start } = query;\n\n useEffect(() => {\n // when dashboard loaded with no params, default to dashboard duration\n if (!paramsLoaded && !start) {\n if (isRelativeTimeRange(initialTimeRange)) {\n setQuery({ start: initialTimeRange.pastDuration, end: undefined });\n setParamsLoaded(true);\n }\n }\n }, [initialTimeRange, paramsLoaded, start, setQuery]);\n\n const setTimeRange: TimeRange['setTimeRange'] = useCallback(\n (value: TimeRangeValue) => {\n if (isRelativeTimeRange(value)) {\n setQuery({ start: value.pastDuration, end: undefined });\n } else {\n setQuery(value);\n }\n },\n [setQuery]\n );\n\n return { timeRange: initialTimeRange, setTimeRange: setTimeRange };\n}\n\n/**\n * Gets the initial refresh interval taking into account URL params and dashboard JSON duration\n * Sets refresh query param if it is empty on page load\n */\nexport function useInitialRefreshInterval(dashboardDuration: DurationString): DurationString {\n const [query] = useQueryParams(refreshIntervalQueryConfig, { updateType: 'replaceIn' });\n const { refresh } = query;\n return useMemo(() => {\n let initialTimeRange: DurationString = dashboardDuration;\n if (!refresh) {\n return initialTimeRange;\n }\n const startStr = refresh.toString();\n if (isDurationString(startStr)) {\n initialTimeRange = startStr;\n }\n return initialTimeRange;\n }, [dashboardDuration, refresh]);\n}\n\n/**\n * Returns refresh interval getter and setter, taking the URL query params.\n */\nexport function useSetRefreshIntervalParams(\n initialRefreshInterval?: DurationString\n): Pick<TimeRange, 'refreshInterval' | 'setRefreshInterval'> {\n const [query, setQuery] = useQueryParams(refreshIntervalQueryConfig, { updateType: 'replaceIn' });\n\n // determine whether initial param had previously been populated to fix back btn\n const [paramsLoaded, setParamsLoaded] = useState<boolean>(false);\n\n const { refresh } = query;\n\n useEffect(() => {\n // when dashboard loaded with no params, default to dashboard refresh interval\n if (!paramsLoaded && !refresh) {\n setQuery({ refresh: initialRefreshInterval });\n setParamsLoaded(true);\n }\n }, [initialRefreshInterval, paramsLoaded, refresh, setQuery]);\n\n const setRefreshInterval: TimeRange['setRefreshInterval'] = useCallback(\n (refresh: DurationString) => setQuery({ refresh }),\n [setQuery]\n );\n\n return {\n refreshInterval: initialRefreshInterval,\n setRefreshInterval: setRefreshInterval,\n };\n}\n\n/**\n * Returns timezone getter and setter, taking the URL query params.\n * Defaults to 'local' when not set.\n */\nexport function useTimeZoneParams(initialTimeZone?: string): { timeZone: string; setTimeZone: (tz: string) => void } {\n const [query, setQuery] = useQueryParams(timeZoneQueryConfig, { updateType: 'replaceIn' });\n const { tz } = query;\n\n const timeZone = (tz as string | undefined) ?? initialTimeZone ?? 'local';\n\n const setTimeZone = useCallback(\n (newTz: string) => {\n setQuery({ tz: newTz });\n },\n [setQuery]\n );\n\n return { timeZone, setTimeZone };\n}\n"],"names":["useMemo","useCallback","useEffect","useState","useQueryParams","StringParam","getUnixTime","isDate","isRelativeTimeRange","isDurationString","getEncodedValue","input","allowEmptyString","length","str","Array","undefined","encodeTimeRangeValue","timeOptionValue","toString","decodeTimeRangeValue","paramString","Date","Number","TimeRangeParam","encode","decode","equals","valueA","valueB","valueOf","timeRangeQueryConfig","start","end","refreshIntervalQueryConfig","refresh","timeZoneQueryConfig","tz","useInitialTimeRange","dashboardDuration","query","updateType","initialTimeRange","pastDuration","startStr","useTimeRangeParams","setQuery","paramsLoaded","setParamsLoaded","setTimeRange","value","timeRange","useInitialRefreshInterval","useSetRefreshIntervalParams","initialRefreshInterval","setRefreshInterval","refreshInterval","useTimeZoneParams","initialTimeZone","timeZone","setTimeZone","newTz"],"mappings":"AAAA,+BAA+B;AAC/B,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,6CAA6C;AAC7C,EAAE;AACF,sEAAsE;AACtE,oEAAoE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IACtB;AACF;AAEA;;;CAGC,GACD,OAAO,SAASE,kBAAkBC,eAAwB;IACxD,MAAM,CAAClB,OAAOM,SAAS,GAAG1C,eAAegC,qBAAqB;QAAEK,YAAY;IAAY;IACxF,MAAM,EAAEJ,EAAE,EAAE,GAAGG;IAEf,MAAMmB,WAAW,AAACtB,MAA6BqB,mBAAmB;IAElE,MAAME,cAAc3D,YAClB,CAAC4D;QACCf,SAAS;YAAET,IAAIwB;QAAM;IACvB,GACA;QAACf;KAAS;IAGZ,OAAO;QAAEa;QAAUC;IAAY;AACjC"}
|
|
1
|
+
{"version":3,"sources":["../../../src/runtime/TimeRangeProvider/query-params.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 { useMemo, useCallback, useEffect, useState } from 'react';\nimport { QueryParamConfig, useQueryParams, StringParam } from 'use-query-params';\nimport { getUnixTime, isDate } from 'date-fns';\nimport {\n TimeRangeValue,\n isRelativeTimeRange,\n isDurationString,\n DurationString,\n AbsoluteTimeRange,\n} from '@perses-dev/spec';\nimport { TimeRange } from './TimeRangeProvider';\n\nexport type TimeOptionValue = Date | DurationString | null | undefined;\n\n/* Interprets an encoded string and returns either the string or null/undefined if not available */\nfunction getEncodedValue(\n input: string | Array<string | null> | null | undefined,\n allowEmptyString?: boolean\n): string | null | undefined {\n // '' or []\n if (!input || (input.length === 0 && (!allowEmptyString || (allowEmptyString && input !== '')))) {\n return null;\n }\n\n const str = input instanceof Array ? input[0] : input;\n if (str === null || str === undefined) {\n return str;\n }\n if (!allowEmptyString && str === '') {\n return null;\n }\n\n return str;\n}\n\n/* Encodes individual TimeRangeValue as a string, depends on whether start is relative or absolute */\nexport function encodeTimeRangeValue(timeOptionValue: TimeOptionValue): string | null | undefined {\n if (!timeOptionValue) {\n return timeOptionValue;\n }\n\n if (typeof timeOptionValue === 'string') {\n if (isDurationString(timeOptionValue)) {\n return timeOptionValue;\n }\n }\n return (getUnixTime(timeOptionValue) * 1000).toString();\n}\n\n/* Converts param input to supported relative or absolute time range format */\nexport function decodeTimeRangeValue(\n input: string | Array<string | null> | null | undefined\n): Date | DurationString | null | undefined {\n const paramString = getEncodedValue(input);\n if (!paramString) return null;\n return isDurationString(paramString) ? paramString : new Date(Number(paramString));\n}\n\n/**\n * Custom TimeRangeValue param type\n * See: https://github.com/pbeshai/use-query-params/tree/master/packages/serialize-query-params#param-types\n */\nexport const TimeRangeParam: QueryParamConfig<TimeOptionValue, TimeOptionValue> = {\n encode: encodeTimeRangeValue,\n decode: decodeTimeRangeValue,\n equals: (valueA: TimeOptionValue, valueB: TimeOptionValue) => {\n if (valueA === valueB) return true;\n if (!valueA || !valueB) return valueA === valueB;\n return valueA.valueOf() === valueB.valueOf();\n },\n};\n\nexport const timeRangeQueryConfig = {\n start: TimeRangeParam,\n end: TimeRangeParam,\n};\n\nexport const refreshIntervalQueryConfig = {\n refresh: TimeRangeParam,\n};\n\nexport const timeZoneQueryConfig = {\n tz: StringParam,\n};\n\n/**\n * Gets the initial time range taking into account URL params and dashboard JSON duration\n * Sets start query param if it is empty on page load\n */\nexport function useInitialTimeRange(dashboardDuration: DurationString): TimeRangeValue {\n const [query] = useQueryParams(timeRangeQueryConfig, { updateType: 'replaceIn' });\n const { start, end } = query;\n\n return useMemo(() => {\n let initialTimeRange: TimeRangeValue = { pastDuration: dashboardDuration };\n if (!start) {\n return initialTimeRange;\n }\n const startStr = start.toString();\n if (isDurationString(startStr)) {\n initialTimeRange = { pastDuration: startStr };\n } else if (isDate(start) && isDate(end)) {\n initialTimeRange = { start: start, end: end } as AbsoluteTimeRange;\n }\n return initialTimeRange;\n }, [start, end, dashboardDuration]);\n}\n\n/**\n * Returns time range getter and setter, taking the URL query params.\n */\nexport function useTimeRangeParams(initialTimeRange: TimeRangeValue): Pick<TimeRange, 'timeRange' | 'setTimeRange'> {\n const [query, setQuery] = useQueryParams(timeRangeQueryConfig, { updateType: 'replaceIn' });\n // determine whether initial param had previously been populated to fix back btn\n const [paramsLoaded, setParamsLoaded] = useState<boolean>(false);\n\n const { start } = query;\n\n useEffect(() => {\n // when dashboard loaded with no params, default to dashboard duration\n if (!paramsLoaded && !start) {\n if (isRelativeTimeRange(initialTimeRange)) {\n setQuery({ start: initialTimeRange.pastDuration, end: undefined });\n setParamsLoaded(true);\n }\n }\n }, [initialTimeRange, paramsLoaded, start, setQuery]);\n\n const setTimeRange: TimeRange['setTimeRange'] = useCallback(\n (value: TimeRangeValue) => {\n if (isRelativeTimeRange(value)) {\n setQuery({ start: value.pastDuration, end: undefined });\n } else {\n setQuery(value);\n }\n },\n [setQuery]\n );\n\n return { timeRange: initialTimeRange, setTimeRange: setTimeRange };\n}\n\n/**\n * Gets the initial refresh interval taking into account URL params and dashboard JSON duration\n * Sets refresh query param if it is empty on page load\n */\nexport function useInitialRefreshInterval(dashboardDuration: DurationString): DurationString {\n const [query] = useQueryParams(refreshIntervalQueryConfig, { updateType: 'replaceIn' });\n const { refresh } = query;\n return useMemo(() => {\n let initialTimeRange: DurationString = dashboardDuration;\n if (!refresh) {\n return initialTimeRange;\n }\n const startStr = refresh.toString();\n if (isDurationString(startStr)) {\n initialTimeRange = startStr;\n }\n return initialTimeRange;\n }, [dashboardDuration, refresh]);\n}\n\n/**\n * Returns refresh interval getter and setter, taking the URL query params.\n */\nexport function useSetRefreshIntervalParams(\n initialRefreshInterval?: DurationString\n): Pick<TimeRange, 'refreshInterval' | 'setRefreshInterval'> {\n const [query, setQuery] = useQueryParams(refreshIntervalQueryConfig, { updateType: 'replaceIn' });\n\n // determine whether initial param had previously been populated to fix back btn\n const [paramsLoaded, setParamsLoaded] = useState<boolean>(false);\n\n const { refresh } = query;\n\n useEffect(() => {\n // when dashboard loaded with no params, default to dashboard refresh interval\n if (!paramsLoaded && !refresh) {\n setQuery({ refresh: initialRefreshInterval });\n setParamsLoaded(true);\n }\n }, [initialRefreshInterval, paramsLoaded, refresh, setQuery]);\n\n const setRefreshInterval: TimeRange['setRefreshInterval'] = useCallback(\n (refresh: DurationString) => setQuery({ refresh }),\n [setQuery]\n );\n\n return {\n refreshInterval: initialRefreshInterval,\n setRefreshInterval: setRefreshInterval,\n };\n}\n\n/**\n * Returns timezone getter and setter, taking the URL query params.\n * Defaults to 'local' when not set.\n */\nexport function useTimeZoneParams(initialTimeZone?: string): { timeZone: string; setTimeZone: (tz: string) => void } {\n const [query, setQuery] = useQueryParams(timeZoneQueryConfig, { updateType: 'replaceIn' });\n const { tz } = query;\n\n const timeZone = (tz as string | undefined) ?? initialTimeZone ?? 'local';\n\n const setTimeZone = useCallback(\n (newTz: string) => {\n setQuery({ tz: newTz });\n },\n [setQuery]\n );\n\n return { timeZone, setTimeZone };\n}\n"],"names":["useMemo","useCallback","useEffect","useState","useQueryParams","StringParam","getUnixTime","isDate","isRelativeTimeRange","isDurationString","getEncodedValue","input","allowEmptyString","length","str","Array","undefined","encodeTimeRangeValue","timeOptionValue","toString","decodeTimeRangeValue","paramString","Date","Number","TimeRangeParam","encode","decode","equals","valueA","valueB","valueOf","timeRangeQueryConfig","start","end","refreshIntervalQueryConfig","refresh","timeZoneQueryConfig","tz","useInitialTimeRange","dashboardDuration","query","updateType","initialTimeRange","pastDuration","startStr","useTimeRangeParams","setQuery","paramsLoaded","setParamsLoaded","setTimeRange","value","timeRange","useInitialRefreshInterval","useSetRefreshIntervalParams","initialRefreshInterval","setRefreshInterval","refreshInterval","useTimeZoneParams","initialTimeZone","timeZone","setTimeZone","newTz"],"mappings":"AAAA,+BAA+B;AAC/B,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,6CAA6C;AAC7C,EAAE;AACF,sE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F;QACjBC,oBAAoBA;IACtB;AACF;AAEA;;;CAGC,GACD,OAAO,SAASE,kBAAkBC,eAAwB;IACxD,MAAM,CAAClB,OAAOM,SAAS,GAAG1C,eAAegC,qBAAqB;QAAEK,YAAY;IAAY;IACxF,MAAM,EAAEJ,EAAE,EAAE,GAAGG;IAEf,MAAMmB,WAAW,AAACtB,MAA6BqB,mBAAmB;IAElE,MAAME,cAAc3D,YAClB,CAAC4D;QACCf,SAAS;YAAET,IAAIwB;QAAM;IACvB,GACA;QAACf;KAAS;IAGZ,OAAO;QAAEa;QAAUC;IAAY;AACjC"}
|
|
@@ -10,7 +10,7 @@
|
|
|
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
|
-
import { parseDurationString } from '@perses-dev/
|
|
13
|
+
import { parseDurationString } from '@perses-dev/spec';
|
|
14
14
|
import { milliseconds } from 'date-fns';
|
|
15
15
|
/**
|
|
16
16
|
* Utils function to transform a refresh interval in {@link DurationString} format into a number of ms.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/runtime/TimeRangeProvider/refresh-interval.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 { DurationString, parseDurationString } from '@perses-dev/
|
|
1
|
+
{"version":3,"sources":["../../../src/runtime/TimeRangeProvider/refresh-interval.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 { DurationString, parseDurationString } from '@perses-dev/spec';\nimport { milliseconds } from 'date-fns';\n\n/**\n * Utils function to transform a refresh interval in {@link DurationString} format into a number of ms.\n * @param refreshInterval\n */\nexport function getRefreshIntervalInMs(refreshInterval?: DurationString): number {\n if (refreshInterval !== undefined && refreshInterval !== null) {\n return milliseconds(parseDurationString(refreshInterval));\n }\n return 0;\n}\n"],"names":["parseDurationString","milliseconds","getRefreshIntervalInMs","refreshInterval","undefined"],"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,SAAyBA,mBAAmB,QAAQ,mBAAmB;AACvE,SAASC,YAAY,QAAQ,WAAW;AAExC;;;CAGC,GACD,OAAO,SAASC,uBAAuBC,eAAgC;IACrE,IAAIA,oBAAoBC,aAAaD,oBAAoB,MAAM;QAC7D,OAAOF,aAAaD,oBAAoBG;IAC1C;IACA,OAAO;AACT"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"UsageMetricsProvider.d.ts","sourceRoot":"","sources":["../../src/runtime/UsageMetricsProvider.tsx"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"UsageMetricsProvider.d.ts","sourceRoot":"","sources":["../../src/runtime/UsageMetricsProvider.tsx"],"names":[],"mappings":"AAcA,OAAO,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAC;AACnD,OAAO,EAAiB,YAAY,EAAE,SAAS,EAAc,MAAM,OAAO,CAAC;AAE3E,KAAK,UAAU,GAAG,SAAS,GAAG,SAAS,GAAG,OAAO,CAAC;AAElD,UAAU,YAAY;IACpB,OAAO,EAAE,MAAM,CAAC;IAChB,SAAS,EAAE,MAAM,CAAC;IAClB,eAAe,EAAE,MAAM,CAAC;IACxB,gBAAgB,EAAE,MAAM,CAAC;IACzB,gBAAgB,EAAE,MAAM,CAAC;IACzB,cAAc,EAAE,GAAG,CAAC,MAAM,EAAE,UAAU,CAAC,CAAC;IACxC,SAAS,CAAC,EAAE,MAAM,CAAC;CACpB;AAED,UAAU,iBAAiB;IACzB,OAAO,EAAE,MAAM,CAAC;IAChB,SAAS,EAAE,MAAM,CAAC;IAClB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,QAAQ,EAAE,SAAS,CAAC;CACrB;AAED,UAAU,sBAAsB;IAC9B,SAAS,EAAE,CAAC,UAAU,EAAE,eAAe,EAAE,KAAK,EAAE,UAAU,KAAK,IAAI,CAAC;CACrE;AAED,eAAO,MAAM,mBAAmB,mDAAqD,CAAC;AAEtF,eAAO,MAAM,sBAAsB,QAAO,YAAY,GAAG,SAExD,CAAC;AAEF,eAAO,MAAM,eAAe,QAAO,sBA6BlC,CAAC;AAiBF,eAAO,MAAM,oBAAoB,gDAAiD,iBAAiB,KAAG,YAYrG,CAAC"}
|
|
@@ -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 { jsx as _jsx } from "react/jsx-runtime";
|
|
14
|
-
import { fetch } from '@perses-dev/core';
|
|
14
|
+
import { fetch } from '@perses-dev/core'; // TODO
|
|
15
15
|
import { createContext, useContext } from 'react';
|
|
16
16
|
export const UsageMetricsContext = /*#__PURE__*/ createContext(undefined);
|
|
17
17
|
export const useUsageMetricsContext = ()=>{
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/runtime/UsageMetricsProvider.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 { fetch
|
|
1
|
+
{"version":3,"sources":["../../src/runtime/UsageMetricsProvider.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 { fetch } from '@perses-dev/core'; // TODO\nimport { QueryDefinition } from '@perses-dev/spec';\nimport { createContext, ReactElement, ReactNode, useContext } from 'react';\n\ntype QueryState = 'pending' | 'success' | 'error';\n\ninterface UsageMetrics {\n project: string;\n dashboard: string;\n startRenderTime: number;\n renderDurationMs: number;\n renderErrorCount: number;\n pendingQueries: Map<string, QueryState>;\n apiPrefix?: string;\n}\n\ninterface UsageMetricsProps {\n project: string;\n dashboard: string;\n apiPrefix?: string;\n children: ReactNode;\n}\n\ninterface UseUsageMetricsResults {\n markQuery: (definition: QueryDefinition, state: QueryState) => void;\n}\n\nexport const UsageMetricsContext = createContext<UsageMetrics | undefined>(undefined);\n\nexport const useUsageMetricsContext = (): UsageMetrics | undefined => {\n return useContext(UsageMetricsContext);\n};\n\nexport const useUsageMetrics = (): UseUsageMetricsResults => {\n const ctx = useUsageMetricsContext();\n\n return {\n markQuery: (definition: QueryDefinition, newState: QueryState): void => {\n if (ctx === undefined) {\n return;\n }\n\n const definitionKey = JSON.stringify(definition);\n if (ctx.pendingQueries.has(definitionKey) && newState === 'pending') {\n // Never allow transitions back to pending, to avoid re-sending stats on a re-render.\n return;\n }\n\n if (ctx.pendingQueries.get(definitionKey) !== newState) {\n ctx.pendingQueries.set(definitionKey, newState);\n if (newState === 'error') {\n ctx.renderErrorCount += 1;\n }\n\n const allDone = [...ctx.pendingQueries.values()].every((p) => p !== 'pending');\n if (ctx.renderDurationMs === 0 && allDone) {\n ctx.renderDurationMs = Date.now() - ctx.startRenderTime;\n submitMetrics(ctx);\n }\n }\n },\n };\n};\n\nconst submitMetrics = async (stats: UsageMetrics): Promise<void> => {\n await fetch(`${stats.apiPrefix ?? ''}/api/v1/view`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({\n project: stats.project,\n dashboard: stats.dashboard,\n render_time: stats.renderDurationMs / 1000,\n render_errors: stats.renderErrorCount,\n }),\n });\n};\n\nexport const UsageMetricsProvider = ({ apiPrefix, project, dashboard, children }: UsageMetricsProps): ReactElement => {\n const ctx: UsageMetrics = {\n project: project,\n dashboard: dashboard,\n renderErrorCount: 0,\n startRenderTime: Date.now(),\n renderDurationMs: 0,\n pendingQueries: new Map(),\n apiPrefix,\n };\n\n return <UsageMetricsContext.Provider value={ctx}>{children}</UsageMetricsContext.Provider>;\n};\n"],"names":["fetch","createContext","useContext","UsageMetricsContext","undefined","useUsageMetricsContext","useUsageMetrics","ctx","markQuery","definition","newState","definitionKey","JSON","stringify","pendingQueries","has","get","set","renderErrorCount","allDone","values","every","p","renderDurationMs","Date","now","startRenderTime","submitMetrics","stats","apiPrefix","method","headers","body","project","dashboard","render_time","render_errors","UsageMetricsProvider","children","Map","Provider","value"],"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,KAAK,QAAQ,mBAA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,EAAER,SAAS,EAAEI,OAAO,EAAEC,SAAS,EAAEI,QAAQ,EAAqB;IACjG,MAAM/B,MAAoB;QACxB0B,SAASA;QACTC,WAAWA;QACXhB,kBAAkB;QAClBQ,iBAAiBF,KAAKC,GAAG;QACzBF,kBAAkB;QAClBT,gBAAgB,IAAIyB;QACpBV;IACF;IAEA,qBAAO,KAAC1B,oBAAoBqC,QAAQ;QAACC,OAAOlC;kBAAM+B;;AACpD,EAAE"}
|
|
@@ -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 { VariableStateMap } from './variables';
|
|
4
4
|
export type BuiltinVariableSrv = {
|
|
5
5
|
variables: BuiltinVariableDefinition[];
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/runtime/builtin-variables.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 { createContext, useContext, useMemo } from 'react';\nimport { BuiltinVariableDefinition } from '@perses-dev/
|
|
1
|
+
{"version":3,"sources":["../../src/runtime/builtin-variables.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 { createContext, useContext, useMemo } from 'react';\nimport { BuiltinVariableDefinition } from '@perses-dev/spec';\nimport { VariableStateMap } from './variables';\n\nexport type BuiltinVariableSrv = {\n variables: BuiltinVariableDefinition[];\n};\n\nexport const BuiltinVariableContext = createContext<BuiltinVariableSrv | undefined>(undefined);\n\nexport function useBuiltinVariableContext(): BuiltinVariableSrv {\n const ctx = useContext(BuiltinVariableContext);\n if (ctx === undefined) {\n throw new Error('No BuiltinVariableContext found. Did you forget a Provider?');\n }\n return ctx;\n}\n\nexport function useBuiltinVariableValues(names?: string[]): VariableStateMap {\n const { variables } = useBuiltinVariableContext();\n const states = useMemo(() => {\n const values: VariableStateMap = {};\n for (const variable of variables) {\n values[variable.spec.name] = { loading: false, value: variable.spec.value() };\n }\n return values;\n }, [variables]);\n\n const values = useMemo(() => {\n const values: VariableStateMap = {};\n names?.forEach((name) => {\n const s = states[name];\n if (s) {\n values[name] = s;\n }\n });\n return values;\n }, [names, states]);\n\n if (names === undefined) {\n return states;\n }\n\n return values;\n}\n\nexport function useBuiltinVariableDefinitions(): BuiltinVariableDefinition[] {\n const { variables } = useBuiltinVariableContext();\n return variables;\n}\n"],"names":["createContext","useContext","useMemo","BuiltinVariableContext","undefined","useBuiltinVariableContext","ctx","Error","useBuiltinVariableValues","names","variables","states","values","variable","spec","name","loading","value","forEach","s","useBuiltinVariableDefinitions"],"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,aAAa,EAAEC,UAAU,EAAEC,OAAO,QAAQ,QAAQ;AAQ3D,OAAO,MAAMC,yBAAyBH,cAA8CI,WAAW;AAE/F,OAAO,SAASC;IACd,MAAMC,MAAML,WAAWE;IACvB,IAAIG,QAAQF,WAAW;QACrB,MAAM,IAAIG,MAAM;IAClB;IACA,OAAOD;AACT;AAEA,OAAO,SAASE,yBAAyBC,KAAgB;IACvD,MAAM,EAAEC,SAAS,EAAE,GAAGL;IACtB,MAAMM,SAAST,QAAQ;QACrB,MAAMU,SAA2B,CAAC;QAClC,KAAK,MAAMC,YAAYH,UAAW;YAChCE,MAAM,CAACC,SAASC,IAAI,CAACC,IAAI,CAAC,GAAG;gBAAEC,SAAS;gBAAOC,OAAOJ,SAASC,IAAI,CAACG,KAAK;YAAG;QAC9E;QACA,OAAOL;IACT,GAAG;QAACF;KAAU;IAEd,MAAME,SAASV,QAAQ;QACrB,MAAMU,SAA2B,CAAC;QAClCH,OAAOS,QAAQ,CAACH;YACd,MAAMI,IAAIR,MAAM,CAACI,KAAK;YACtB,IAAII,GAAG;gBACLP,MAAM,CAACG,KAAK,GAAGI;YACjB;QACF;QACA,OAAOP;IACT,GAAG;QAACH;QAAOE;KAAO;IAElB,IAAIF,UAAUL,WAAW;QACvB,OAAOO;IACT;IAEA,OAAOC;AACT;AAEA,OAAO,SAASQ;IACd,MAAM,EAAEV,SAAS,EAAE,GAAGL;IACtB,OAAOK;AACT"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/// <reference types="react" />
|
|
2
|
-
import { DatasourceSelector, DatasourceSpec } from '@perses-dev/
|
|
2
|
+
import { DatasourceSelector, DatasourceSpec } from '@perses-dev/spec';
|
|
3
3
|
import { UseQueryResult } from '@tanstack/react-query';
|
|
4
4
|
export interface DatasourceStore {
|
|
5
5
|
getDatasource(selector: DatasourceSelector): Promise<DatasourceSpec>;
|
|
@@ -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,GA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AAIT,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
|
+
{"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,yBAAyB;AAChC,SAASC,KAAK,QAAQ,mBAAmB,CAAC,0CAA0C;AAGpF,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;QAAK;QAE7C,MAAMC,QAAQC,MAAMC,IAAI,CAACP,aAAaQ,MAAM;QAE5C,wCAAwC;QACxC,IAAIC;QACJ,IAAIhB,OAAOiB,YAAY,EAAE;YACvB,MAAMC,aAAaxB,0BAA0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AmB,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,QAA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AAkB,EAAE,GAAGtB;IAE1C,OAAOL,SAAS;QACdc,UAAU;YAAC;SAAsC;QACjDC,SAAS;YACP,MAAMc,cAAc,MAAMF,mBAAmB;gBAAC;aAAa;YAC3D,MAAMG,kBAAkB,IAAIX,IAAIU,YAAYT,GAAG,CAAC,CAACW,aAAeA,WAAWC,IAAI,CAACC,IAAI;YACpF,MAAMX,SAAsC,EAAE;YAC9C,KAAK,MAAMW,QAAQH,gBAAiB;gBAClC,MAAMI,SAAS,MAAMrB,UAAU,cAAcoB;gBAC7C,IAAIC,OAAOC,6BAA6B,EAAE;oBACxCD,OAAOC,6BAA6B,GAAGC,OAAO,CAAC,CAACC,aAAef,OAAOgB,IAAI,CAACD;gBAC7E;YACF;YACA,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 {
|