@perses-dev/plugin-system 0.53.1 → 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.
Files changed (118) hide show
  1. package/dist/cjs/components/TimeRangeControls/TimeRangeControls.js +2 -2
  2. package/dist/cjs/context/ValidationProvider.js +5 -4
  3. package/dist/cjs/model/index.js +2 -0
  4. package/dist/cjs/model/log-volume-utils.js +124 -0
  5. package/dist/cjs/remote/PluginRuntime.js +11 -10
  6. package/dist/cjs/runtime/TimeRangeProvider/TimeRangeProvider.js +6 -6
  7. package/dist/cjs/runtime/TimeRangeProvider/query-params.js +7 -7
  8. package/dist/cjs/runtime/TimeRangeProvider/refresh-interval.js +2 -2
  9. package/dist/components/CalculationSelector/CalculationSelector.js +1 -1
  10. package/dist/components/CalculationSelector/CalculationSelector.js.map +1 -1
  11. package/dist/components/DatasourceEditorForm/DatasourceEditorForm.js.map +1 -1
  12. package/dist/components/DatasourceSelect/DatasourceSelect.d.ts +1 -1
  13. package/dist/components/DatasourceSelect/DatasourceSelect.js.map +1 -1
  14. package/dist/components/HTTPSettingsEditor/HTTPSettingsEditor.js.map +1 -1
  15. package/dist/components/LegendOptionsEditor/LegendOptionsEditor.js +1 -1
  16. package/dist/components/LegendOptionsEditor/LegendOptionsEditor.js.map +1 -1
  17. package/dist/components/MultiQueryEditor/QueryEditorContainer.d.ts +1 -1
  18. package/dist/components/MultiQueryEditor/QueryEditorContainer.js.map +1 -1
  19. package/dist/components/PanelSpecEditor/PanelSpecEditor.d.ts +1 -1
  20. package/dist/components/PanelSpecEditor/PanelSpecEditor.js.map +1 -1
  21. package/dist/components/PluginEditor/PluginEditor.js.map +1 -1
  22. package/dist/components/PluginEditor/plugin-editor-api.d.ts +1 -1
  23. package/dist/components/PluginEditor/plugin-editor-api.js.map +1 -1
  24. package/dist/components/PluginRegistry/PluginRegistry.js.map +1 -1
  25. package/dist/components/PluginSpecEditor/PluginSpecEditor.d.ts +1 -1
  26. package/dist/components/PluginSpecEditor/PluginSpecEditor.js.map +1 -1
  27. package/dist/components/TimeRangeControls/TimeRangeControls.js +1 -1
  28. package/dist/components/TimeRangeControls/TimeRangeControls.js.map +1 -1
  29. package/dist/components/Variables/VariableEditorForm/VariableEditorForm.d.ts +2 -1
  30. package/dist/components/Variables/VariableEditorForm/VariableEditorForm.d.ts.map +1 -1
  31. package/dist/components/Variables/VariableEditorForm/VariableEditorForm.js.map +1 -1
  32. package/dist/components/Variables/VariableEditorForm/VariablePreview.d.ts +1 -1
  33. package/dist/components/Variables/VariableEditorForm/VariablePreview.js.map +1 -1
  34. package/dist/components/Variables/VariableEditorForm/variable-editor-form-model.d.ts +1 -1
  35. package/dist/components/Variables/VariableEditorForm/variable-editor-form-model.js.map +1 -1
  36. package/dist/components/Variables/variable-model.d.ts +1 -1
  37. package/dist/components/Variables/variable-model.js.map +1 -1
  38. package/dist/context/ValidationProvider.d.ts +2 -1
  39. package/dist/context/ValidationProvider.d.ts.map +1 -1
  40. package/dist/context/ValidationProvider.js +3 -2
  41. package/dist/context/ValidationProvider.js.map +1 -1
  42. package/dist/model/datasource.d.ts +1 -1
  43. package/dist/model/datasource.js.map +1 -1
  44. package/dist/model/explore.d.ts +1 -1
  45. package/dist/model/explore.js.map +1 -1
  46. package/dist/model/index.d.ts +2 -0
  47. package/dist/model/index.d.ts.map +1 -1
  48. package/dist/model/index.js +2 -0
  49. package/dist/model/index.js.map +1 -1
  50. package/dist/model/legend.js +1 -1
  51. package/dist/model/legend.js.map +1 -1
  52. package/dist/model/log-queries.d.ts +2 -1
  53. package/dist/model/log-queries.d.ts.map +1 -1
  54. package/dist/model/log-queries.js.map +1 -1
  55. package/dist/model/log-volume-utils.d.ts +6 -0
  56. package/dist/model/log-volume-utils.d.ts.map +1 -0
  57. package/dist/model/log-volume-utils.js +119 -0
  58. package/dist/model/log-volume-utils.js.map +1 -0
  59. package/dist/model/panels.d.ts +1 -1
  60. package/dist/model/panels.js.map +1 -1
  61. package/dist/model/plugin-base.d.ts +1 -1
  62. package/dist/model/plugin-base.js.map +1 -1
  63. package/dist/model/plugins.d.ts +1 -1
  64. package/dist/model/plugins.js.map +1 -1
  65. package/dist/model/profile-queries.d.ts +1 -1
  66. package/dist/model/profile-queries.js.map +1 -1
  67. package/dist/model/time-series-queries.d.ts +1 -1
  68. package/dist/model/time-series-queries.js.map +1 -1
  69. package/dist/model/trace-queries.d.ts +1 -1
  70. package/dist/model/trace-queries.js.map +1 -1
  71. package/dist/model/variables.d.ts +1 -1
  72. package/dist/model/variables.js.map +1 -1
  73. package/dist/remote/PluginRuntime.d.ts.map +1 -1
  74. package/dist/remote/PluginRuntime.js +11 -10
  75. package/dist/remote/PluginRuntime.js.map +1 -1
  76. package/dist/runtime/DataQueriesProvider/DataQueriesProvider.d.ts +1 -1
  77. package/dist/runtime/DataQueriesProvider/DataQueriesProvider.js.map +1 -1
  78. package/dist/runtime/DataQueriesProvider/model.d.ts +1 -1
  79. package/dist/runtime/DataQueriesProvider/model.js.map +1 -1
  80. package/dist/runtime/TimeRangeProvider/TimeRangeProvider.d.ts +1 -1
  81. package/dist/runtime/TimeRangeProvider/TimeRangeProvider.js +1 -1
  82. package/dist/runtime/TimeRangeProvider/TimeRangeProvider.js.map +1 -1
  83. package/dist/runtime/TimeRangeProvider/TimeRangeProviders.d.ts +1 -1
  84. package/dist/runtime/TimeRangeProvider/TimeRangeProviders.js.map +1 -1
  85. package/dist/runtime/TimeRangeProvider/TimeRangeSettingsProvider.js.map +1 -1
  86. package/dist/runtime/TimeRangeProvider/query-params.d.ts +1 -1
  87. package/dist/runtime/TimeRangeProvider/query-params.js +1 -1
  88. package/dist/runtime/TimeRangeProvider/query-params.js.map +1 -1
  89. package/dist/runtime/TimeRangeProvider/refresh-interval.d.ts +1 -1
  90. package/dist/runtime/TimeRangeProvider/refresh-interval.js +1 -1
  91. package/dist/runtime/TimeRangeProvider/refresh-interval.js.map +1 -1
  92. package/dist/runtime/UsageMetricsProvider.d.ts +1 -1
  93. package/dist/runtime/UsageMetricsProvider.d.ts.map +1 -1
  94. package/dist/runtime/UsageMetricsProvider.js +1 -1
  95. package/dist/runtime/UsageMetricsProvider.js.map +1 -1
  96. package/dist/runtime/builtin-variables.d.ts +1 -1
  97. package/dist/runtime/builtin-variables.js.map +1 -1
  98. package/dist/runtime/datasources.d.ts +1 -1
  99. package/dist/runtime/datasources.js.map +1 -1
  100. package/dist/runtime/item-actions.js +1 -1
  101. package/dist/runtime/item-actions.js.map +1 -1
  102. package/dist/runtime/log-queries.d.ts +1 -1
  103. package/dist/runtime/log-queries.js.map +1 -1
  104. package/dist/runtime/plugin-registry.d.ts +1 -1
  105. package/dist/runtime/plugin-registry.js.map +1 -1
  106. package/dist/runtime/profile-queries.d.ts +1 -1
  107. package/dist/runtime/profile-queries.js.map +1 -1
  108. package/dist/runtime/time-series-queries.d.ts +1 -1
  109. package/dist/runtime/time-series-queries.js.map +1 -1
  110. package/dist/runtime/trace-queries.d.ts +1 -1
  111. package/dist/runtime/trace-queries.js.map +1 -1
  112. package/dist/test/mock-data.d.ts +1 -1
  113. package/dist/test/mock-data.js.map +1 -1
  114. package/dist/test/utils.js +1 -1
  115. package/dist/test/utils.js.map +1 -1
  116. package/dist/test-utils/mock-plugin-registry.js.map +1 -1
  117. package/dist/utils/action.js.map +1 -1
  118. package/package.json +8 -5
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/runtime/DataQueriesProvider/model.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 { Definition, QueryDefinition, UnknownSpec, QueryDataType } from '@perses-dev/core';\nimport { QueryObserverOptions, UseQueryResult } from '@tanstack/react-query';\nimport { ReactNode, useCallback, useMemo } from 'react';\nimport { useListPluginMetadata } from '../plugin-registry';\n\nexport type QueryOptions = Record<string, unknown>;\nexport interface DataQueriesProviderProps<QueryPluginSpec = UnknownSpec> {\n definitions: Array<Definition<QueryPluginSpec>>;\n children?: ReactNode;\n options?: QueryOptions;\n queryOptions?: Omit<QueryObserverOptions, 'queryKey'>;\n}\n\nexport interface DataQueriesContextType {\n queryResults: QueryData[];\n refetchAll: () => void;\n isFetching: boolean;\n isLoading: boolean;\n errors: unknown[];\n}\n\nexport interface UseDataQueryResults<T> extends Omit<DataQueriesContextType, 'queryResults'> {\n queryResults: Array<QueryData<T>>;\n}\n\nexport type QueryData<T = QueryDataType> = {\n data?: T;\n definition: QueryDefinition;\n error: Error;\n isFetching: boolean;\n isLoading: boolean;\n refetch?: () => void;\n};\n\nexport function transformQueryResults(results: UseQueryResult[], definitions: QueryDefinition[]): QueryData[] {\n return results.map(({ data, isFetching, isLoading, refetch, error }, i) => {\n return {\n definition: definitions[i],\n data,\n isFetching,\n isLoading,\n refetch,\n error,\n } as QueryData;\n });\n}\n\nexport function useQueryType(): (pluginKind: string) => string | undefined {\n const { data: timeSeriesQueryPlugins, isLoading: isTimeSeriesQueryLoading } = useListPluginMetadata([\n 'TimeSeriesQuery',\n ]);\n const { data: traceQueryPlugins, isLoading: isTraceQueryPluginLoading } = useListPluginMetadata(['TraceQuery']);\n const { data: profileQueryPlugins, isLoading: isProfileQueryPluginLoading } = useListPluginMetadata(['ProfileQuery']);\n const { data: logQueries, isLoading: isLogQueryPluginLoading } = useListPluginMetadata(['LogQuery']);\n\n // For example, `map: {\"TimeSeriesQuery\":[\"PrometheusTimeSeriesQuery\"],\"TraceQuery\":[\"TempoTraceQuery\"]}`\n const queryTypeMap = useMemo(() => {\n const map: Record<string, string[]> = {\n TimeSeriesQuery: [],\n TraceQuery: [],\n ProfileQuery: [],\n LogQuery: [],\n };\n\n if (timeSeriesQueryPlugins) {\n timeSeriesQueryPlugins.forEach((plugin) => {\n map[plugin.kind]?.push(plugin.spec.name);\n });\n }\n\n if (traceQueryPlugins) {\n traceQueryPlugins.forEach((plugin) => {\n map[plugin.kind]?.push(plugin.spec.name);\n });\n }\n\n if (profileQueryPlugins) {\n profileQueryPlugins.forEach((plugin) => {\n map[plugin.kind]?.push(plugin.spec.name);\n });\n }\n\n if (logQueries) {\n logQueries.forEach((plugin) => {\n map[plugin.kind]?.push(plugin.spec.name);\n });\n }\n\n return map;\n }, [timeSeriesQueryPlugins, traceQueryPlugins, profileQueryPlugins, logQueries]);\n\n const getQueryType = useCallback(\n (pluginKind: string) => {\n const isLoading = (pluginKind: string): boolean => {\n switch (pluginKind) {\n case 'PrometheusTimeSeriesQuery':\n return isTimeSeriesQueryLoading;\n case 'TempoTraceQuery':\n return isTraceQueryPluginLoading;\n case 'PyroscopeProfileQuery':\n return isProfileQueryPluginLoading;\n case 'LokiLogQuery':\n return isLogQueryPluginLoading;\n }\n\n return (\n isTraceQueryPluginLoading ||\n isTimeSeriesQueryLoading ||\n isProfileQueryPluginLoading ||\n isLogQueryPluginLoading\n );\n };\n\n if (isLoading(pluginKind)) {\n return undefined;\n }\n\n for (const queryType in queryTypeMap) {\n if (queryTypeMap[queryType]?.includes(pluginKind)) {\n return queryType;\n }\n }\n\n throw new Error(`Unable to determine the query type: ${pluginKind}`);\n },\n [\n queryTypeMap,\n isTimeSeriesQueryLoading,\n isTraceQueryPluginLoading,\n isProfileQueryPluginLoading,\n isLogQueryPluginLoading,\n ]\n );\n\n return getQueryType;\n}\n"],"names":["useCallback","useMemo","useListPluginMetadata","transformQueryResults","results","definitions","map","data","isFetching","isLoading","refetch","error","i","definition","useQueryType","timeSeriesQueryPlugins","isTimeSeriesQueryLoading","traceQueryPlugins","isTraceQueryPluginLoading","profileQueryPlugins","isProfileQueryPluginLoading","logQueries","isLogQueryPluginLoading","queryTypeMap","TimeSeriesQuery","TraceQuery","ProfileQuery","LogQuery","forEach","plugin","kind","push","spec","name","getQueryType","pluginKind","undefined","queryType","includes","Error"],"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;AAIjC,SAAoBA,WAAW,EAAEC,OAAO,QAAQ,QAAQ;AACxD,SAASC,qBAAqB,QAAQ,qBAAqB;AA+B3D,OAAO,SAASC,sBAAsBC,OAAyB,EAAEC,WAA8B;IAC7F,OAAOD,QAAQE,GAAG,CAAC,CAAC,EAAEC,IAAI,EAAEC,UAAU,EAAEC,SAAS,EAAEC,OAAO,EAAEC,KAAK,EAAE,EAAEC;QACnE,OAAO;YACLC,YAAYR,WAAW,CAACO,EAAE;YAC1BL;YACAC;YACAC;YACAC;YACAC;QACF;IACF;AACF;AAEA,OAAO,SAASG;IACd,MAAM,EAAEP,MAAMQ,sBAAsB,EAAEN,WAAWO,wBAAwB,EAAE,GAAGd,sBAAsB;QAClG;KACD;IACD,MAAM,EAAEK,MAAMU,iBAAiB,EAAER,WAAWS,yBAAyB,EAAE,GAAGhB,sBAAsB;QAAC;KAAa;IAC9G,MAAM,EAAEK,MAAMY,mBAAmB,EAAEV,WAAWW,2BAA2B,EAAE,GAAGlB,sBAAsB;QAAC;KAAe;IACpH,MAAM,EAAEK,MAAMc,UAAU,EAAEZ,WAAWa,uBAAuB,EAAE,GAAGpB,sBAAsB;QAAC;KAAW;IAEnG,yGAAyG;IACzG,MAAMqB,eAAetB,QAAQ;QAC3B,MAAMK,MAAgC;YACpCkB,iBAAiB,EAAE;YACnBC,YAAY,EAAE;YACdC,cAAc,EAAE;YAChBC,UAAU,EAAE;QACd;QAEA,IAAIZ,wBAAwB;YAC1BA,uBAAuBa,OAAO,CAAC,CAACC;gBAC9BvB,GAAG,CAACuB,OAAOC,IAAI,CAAC,EAAEC,KAAKF,OAAOG,IAAI,CAACC,IAAI;YACzC;QACF;QAEA,IAAIhB,mBAAmB;YACrBA,kBAAkBW,OAAO,CAAC,CAACC;gBACzBvB,GAAG,CAACuB,OAAOC,IAAI,CAAC,EAAEC,KAAKF,OAAOG,IAAI,CAACC,IAAI;YACzC;QACF;QAEA,IAAId,qBAAqB;YACvBA,oBAAoBS,OAAO,CAAC,CAACC;gBAC3BvB,GAAG,CAACuB,OAAOC,IAAI,CAAC,EAAEC,KAAKF,OAAOG,IAAI,CAACC,IAAI;YACzC;QACF;QAEA,IAAIZ,YAAY;YACdA,WAAWO,OAAO,CAAC,CAACC;gBAClBvB,GAAG,CAACuB,OAAOC,IAAI,CAAC,EAAEC,KAAKF,OAAOG,IAAI,CAACC,IAAI;YACzC;QACF;QAEA,OAAO3B;IACT,GAAG;QAACS;QAAwBE;QAAmBE;QAAqBE;KAAW;IAE/E,MAAMa,eAAelC,YACnB,CAACmC;QACC,MAAM1B,YAAY,CAAC0B;YACjB,OAAQA;gBACN,KAAK;oBACH,OAAOnB;gBACT,KAAK;oBACH,OAAOE;gBACT,KAAK;oBACH,OAAOE;gBACT,KAAK;oBACH,OAAOE;YACX;YAEA,OACEJ,6BACAF,4BACAI,+BACAE;QAEJ;QAEA,IAAIb,UAAU0B,aAAa;YACzB,OAAOC;QACT;QAEA,IAAK,MAAMC,aAAad,aAAc;YACpC,IAAIA,YAAY,CAACc,UAAU,EAAEC,SAASH,aAAa;gBACjD,OAAOE;YACT;QACF;QAEA,MAAM,IAAIE,MAAM,CAAC,oCAAoC,EAAEJ,YAAY;IACrE,GACA;QACEZ;QACAP;QACAE;QACAE;QACAE;KACD;IAGH,OAAOY;AACT"}
1
+ {"version":3,"sources":["../../../src/runtime/DataQueriesProvider/model.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 { Definition, QueryDefinition, UnknownSpec, QueryDataType } from '@perses-dev/spec';\nimport { QueryObserverOptions, UseQueryResult } from '@tanstack/react-query';\nimport { ReactNode, useCallback, useMemo } from 'react';\nimport { useListPluginMetadata } from '../plugin-registry';\n\nexport type QueryOptions = Record<string, unknown>;\nexport interface DataQueriesProviderProps<QueryPluginSpec = UnknownSpec> {\n definitions: Array<Definition<QueryPluginSpec>>;\n children?: ReactNode;\n options?: QueryOptions;\n queryOptions?: Omit<QueryObserverOptions, 'queryKey'>;\n}\n\nexport interface DataQueriesContextType {\n queryResults: QueryData[];\n refetchAll: () => void;\n isFetching: boolean;\n isLoading: boolean;\n errors: unknown[];\n}\n\nexport interface UseDataQueryResults<T> extends Omit<DataQueriesContextType, 'queryResults'> {\n queryResults: Array<QueryData<T>>;\n}\n\nexport type QueryData<T = QueryDataType> = {\n data?: T;\n definition: QueryDefinition;\n error: Error;\n isFetching: boolean;\n isLoading: boolean;\n refetch?: () => void;\n};\n\nexport function transformQueryResults(results: UseQueryResult[], definitions: QueryDefinition[]): QueryData[] {\n return results.map(({ data, isFetching, isLoading, refetch, error }, i) => {\n return {\n definition: definitions[i],\n data,\n isFetching,\n isLoading,\n refetch,\n error,\n } as QueryData;\n });\n}\n\nexport function useQueryType(): (pluginKind: string) => string | undefined {\n const { data: timeSeriesQueryPlugins, isLoading: isTimeSeriesQueryLoading } = useListPluginMetadata([\n 'TimeSeriesQuery',\n ]);\n const { data: traceQueryPlugins, isLoading: isTraceQueryPluginLoading } = useListPluginMetadata(['TraceQuery']);\n const { data: profileQueryPlugins, isLoading: isProfileQueryPluginLoading } = useListPluginMetadata(['ProfileQuery']);\n const { data: logQueries, isLoading: isLogQueryPluginLoading } = useListPluginMetadata(['LogQuery']);\n\n // For example, `map: {\"TimeSeriesQuery\":[\"PrometheusTimeSeriesQuery\"],\"TraceQuery\":[\"TempoTraceQuery\"]}`\n const queryTypeMap = useMemo(() => {\n const map: Record<string, string[]> = {\n TimeSeriesQuery: [],\n TraceQuery: [],\n ProfileQuery: [],\n LogQuery: [],\n };\n\n if (timeSeriesQueryPlugins) {\n timeSeriesQueryPlugins.forEach((plugin) => {\n map[plugin.kind]?.push(plugin.spec.name);\n });\n }\n\n if (traceQueryPlugins) {\n traceQueryPlugins.forEach((plugin) => {\n map[plugin.kind]?.push(plugin.spec.name);\n });\n }\n\n if (profileQueryPlugins) {\n profileQueryPlugins.forEach((plugin) => {\n map[plugin.kind]?.push(plugin.spec.name);\n });\n }\n\n if (logQueries) {\n logQueries.forEach((plugin) => {\n map[plugin.kind]?.push(plugin.spec.name);\n });\n }\n\n return map;\n }, [timeSeriesQueryPlugins, traceQueryPlugins, profileQueryPlugins, logQueries]);\n\n const getQueryType = useCallback(\n (pluginKind: string) => {\n const isLoading = (pluginKind: string): boolean => {\n switch (pluginKind) {\n case 'PrometheusTimeSeriesQuery':\n return isTimeSeriesQueryLoading;\n case 'TempoTraceQuery':\n return isTraceQueryPluginLoading;\n case 'PyroscopeProfileQuery':\n return isProfileQueryPluginLoading;\n case 'LokiLogQuery':\n return isLogQueryPluginLoading;\n }\n\n return (\n isTraceQueryPluginLoading ||\n isTimeSeriesQueryLoading ||\n isProfileQueryPluginLoading ||\n isLogQueryPluginLoading\n );\n };\n\n if (isLoading(pluginKind)) {\n return undefined;\n }\n\n for (const queryType in queryTypeMap) {\n if (queryTypeMap[queryType]?.includes(pluginKind)) {\n return queryType;\n }\n }\n\n throw new Error(`Unable to determine the query type: ${pluginKind}`);\n },\n [\n queryTypeMap,\n isTimeSeriesQueryLoading,\n isTraceQueryPluginLoading,\n isProfileQueryPluginLoading,\n isLogQueryPluginLoading,\n ]\n );\n\n return getQueryType;\n}\n"],"names":["useCallback","useMemo","useListPluginMetadata","transformQueryResults","results","definitions","map","data","isFetching","isLoading","refetch","error","i","definition","useQueryType","timeSeriesQueryPlugins","isTimeSeriesQueryLoading","traceQueryPlugins","isTraceQueryPluginLoading","profileQueryPlugins","isProfileQueryPluginLoading","logQueries","isLogQueryPluginLoading","queryTypeMap","TimeSeriesQuery","TraceQuery","ProfileQuery","LogQuery","forEach","plugin","kind","push","spec","name","getQueryType","pluginKind","undefined","queryType","includes","Error"],"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;AAIjC,SAAoBA,WAAW,EAAEC,OAAO,QAAQ,QAAQ;AACxD,SAASC,qBAAqB,QAAQ,qBAAqB;AA+B3D,OAAO,SAASC,sBAAsBC,OAAyB,EAAEC,WAA8B;IAC7F,OAAOD,QAAQE,GAAG,CAAC,CAAC,EAAEC,IAAI,EAAEC,UAAU,EAAEC,SAAS,EAAEC,OAAO,EAAEC,KAAK,EAAE,EAAEC;QACnE,OAAO;YACLC,YAAYR,WAAW,CAACO,EAAE;YAC1BL;YACAC;YACAC;YACAC;YACAC;QACF;IACF;AACF;AAEA,OAAO,SAASG;IACd,MAAM,EAAEP,MAAMQ,sBAAsB,EAAEN,WAAWO,wBAAwB,EAAE,GAAGd,sBAAsB;QAClG;KACD;IACD,MAAM,EAAEK,MAAMU,iBAAiB,EAAER,WAAWS,yBAAyB,EAAE,GAAGhB,sBAAsB;QAAC;KAAa;IAC9G,MAAM,EAAEK,MAAMY,mBAAmB,EAAEV,WAAWW,2BAA2B,EAAE,GAAGlB,sBAAsB;QAAC;KAAe;IACpH,MAAM,EAAEK,MAAMc,UAAU,EAAEZ,WAAWa,uBAAuB,EAAE,GAAGpB,sBAAsB;QAAC;KAAW;IAEnG,yGAAyG;IACzG,MAAMqB,eAAetB,QAAQ;QAC3B,MAAMK,MAAgC;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Y;AACT"}
@@ -1,5 +1,5 @@
1
1
  import React, { ReactElement } from 'react';
2
- import { AbsoluteTimeRange, DurationString, TimeRangeValue } from '@perses-dev/core';
2
+ import { AbsoluteTimeRange, DurationString, TimeRangeValue } from '@perses-dev/spec';
3
3
  export interface TimeRangeProviderProps {
4
4
  timeRange: TimeRangeValue;
5
5
  refreshInterval?: DurationString;
@@ -12,7 +12,7 @@
12
12
  // limitations under the License.
13
13
  import { jsx as _jsx } from "react/jsx-runtime";
14
14
  import React, { createContext, useCallback, useContext, useEffect, useMemo, useState } from 'react';
15
- import { isRelativeTimeRange, toAbsoluteTimeRange, getSuggestedStepMs } from '@perses-dev/core';
15
+ import { isRelativeTimeRange, toAbsoluteTimeRange, getSuggestedStepMs } from '@perses-dev/spec';
16
16
  import { useQueryClient } from '@tanstack/react-query';
17
17
  import { getRefreshIntervalInMs } from './refresh-interval';
18
18
  export const TimeRangeContext = /*#__PURE__*/ createContext(undefined);
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/runtime/TimeRangeProvider/TimeRangeProvider.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 React, { createContext, ReactElement, useCallback, useContext, useEffect, useMemo, useState } from 'react';\nimport {\n AbsoluteTimeRange,\n DurationString,\n TimeRangeValue,\n isRelativeTimeRange,\n toAbsoluteTimeRange,\n getSuggestedStepMs,\n} from '@perses-dev/core';\nimport { useQueryClient } from '@tanstack/react-query';\nimport { getRefreshIntervalInMs } from './refresh-interval';\n\nexport interface TimeRangeProviderProps {\n timeRange: TimeRangeValue;\n refreshInterval?: DurationString;\n setTimeRange: (value: TimeRangeValue) => void;\n setRefreshInterval: (value: DurationString) => void;\n children?: React.ReactNode;\n}\n\nexport interface TimeRange {\n timeRange: TimeRangeValue;\n absoluteTimeRange: AbsoluteTimeRange; // resolved absolute time for plugins to use\n setTimeRange: (value: TimeRangeValue) => void;\n refresh: () => void;\n refreshInterval?: DurationString;\n refreshIntervalInMs: number;\n setRefreshInterval: (value: DurationString) => void;\n}\n\nexport const TimeRangeContext = createContext<TimeRange | undefined>(undefined);\n\nexport function useTimeRangeContext(): TimeRange {\n const ctx = useContext(TimeRangeContext);\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 useTimeRange(): TimeRange {\n return useTimeRangeContext();\n}\n\n/**\n * Gets the suggested step for a graph query in ms for the currently selected time range.\n */\nexport function useSuggestedStepMs(width?: number): number {\n const { absoluteTimeRange } = useTimeRange();\n if (width === undefined) return 0;\n return getSuggestedStepMs(absoluteTimeRange, width);\n}\n\n/**\n * Provider implementation that supplies the time range state at runtime.\n */\nexport function TimeRangeProvider(props: TimeRangeProviderProps): ReactElement {\n const { timeRange, refreshInterval, children, setTimeRange, setRefreshInterval } = props;\n\n const queryClient = useQueryClient();\n const [absoluteTimeRange, setAbsoluteTimeRange] = useState<AbsoluteTimeRange>(\n isRelativeTimeRange(timeRange) ? toAbsoluteTimeRange(timeRange) : timeRange\n );\n\n const handleSetTimeRange = useCallback(\n (value: TimeRangeValue) => {\n setTimeRange(value);\n setAbsoluteTimeRange(isRelativeTimeRange(value) ? toAbsoluteTimeRange(value) : value);\n },\n [setTimeRange]\n );\n\n // Refresh is called when clicking on the refresh button, it refreshes all queries including variables\n const refresh = useCallback(() => {\n setAbsoluteTimeRange(isRelativeTimeRange(timeRange) ? toAbsoluteTimeRange(timeRange) : timeRange);\n queryClient\n .invalidateQueries({ queryKey: ['query'] })\n .finally(() => queryClient.removeQueries({ queryKey: ['query'], type: 'inactive' }));\n queryClient\n .invalidateQueries({ queryKey: ['variable'] })\n .finally(() => queryClient.removeQueries({ queryKey: ['variable'], type: 'inactive' }));\n }, [queryClient, timeRange]);\n\n // Auto refresh is only refreshing queries of panels\n const autoRefresh = useCallback(() => {\n setAbsoluteTimeRange(isRelativeTimeRange(timeRange) ? toAbsoluteTimeRange(timeRange) : timeRange);\n queryClient.invalidateQueries({ queryKey: ['query'] }).finally(() => {\n queryClient.removeQueries({ queryKey: ['query'], type: 'inactive' });\n queryClient.removeQueries({ queryKey: ['variable'], type: 'inactive' }); // Timerange is in queryKey, can lead to memory leak when using relative timerange\n });\n }, [queryClient, timeRange]);\n\n const refreshIntervalInMs = useMemo(() => getRefreshIntervalInMs(refreshInterval), [refreshInterval]);\n useEffect(() => {\n if (refreshIntervalInMs > 0) {\n const interval = setInterval(() => {\n autoRefresh();\n }, refreshIntervalInMs);\n\n return (): void => clearInterval(interval);\n }\n }, [autoRefresh, refreshIntervalInMs]);\n\n const ctx = useMemo(() => {\n return {\n timeRange: timeRange,\n setTimeRange: handleSetTimeRange,\n absoluteTimeRange: absoluteTimeRange,\n refresh,\n refreshInterval: refreshInterval,\n refreshIntervalInMs: refreshIntervalInMs,\n setRefreshInterval: setRefreshInterval,\n };\n }, [\n absoluteTimeRange,\n handleSetTimeRange,\n refresh,\n refreshInterval,\n refreshIntervalInMs,\n setRefreshInterval,\n timeRange,\n ]);\n\n return <TimeRangeContext.Provider value={ctx}>{children}</TimeRangeContext.Provider>;\n}\n"],"names":["React","createContext","useCallback","useContext","useEffect","useMemo","useState","isRelativeTimeRange","toAbsoluteTimeRange","getSuggestedStepMs","useQueryClient","getRefreshIntervalInMs","TimeRangeContext","undefined","useTimeRangeContext","ctx","Error","useTimeRange","useSuggestedStepMs","width","absoluteTimeRange","TimeRangeProvider","props","timeRange","refreshInterval","children","setTimeRange","setRefreshInterval","queryClient","setAbsoluteTimeRange","handleSetTimeRange","value","refresh","invalidateQueries","queryKey","finally","removeQueries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E;QACAR;QACAe;QACAZ;QACAJ;KACD;IAED,qBAAO,KAACX,iBAAiB+B,QAAQ;QAACZ,OAAOhB;kBAAMU;;AACjD"}
1
+ {"version":3,"sources":["../../../src/runtime/TimeRangeProvider/TimeRangeProvider.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 React, { createContext, ReactElement, useCallback, useContext, useEffect, useMemo, useState } from 'react';\nimport {\n AbsoluteTimeRange,\n DurationString,\n TimeRangeValue,\n isRelativeTimeRange,\n toAbsoluteTimeRange,\n getSuggestedStepMs,\n} from '@perses-dev/spec';\nimport { useQueryClient } from '@tanstack/react-query';\nimport { getRefreshIntervalInMs } from './refresh-interval';\n\nexport interface TimeRangeProviderProps {\n timeRange: TimeRangeValue;\n refreshInterval?: DurationString;\n setTimeRange: (value: TimeRangeValue) => void;\n setRefreshInterval: (value: DurationString) => void;\n children?: React.ReactNode;\n}\n\nexport interface TimeRange {\n timeRange: TimeRangeValue;\n absoluteTimeRange: AbsoluteTimeRange; // resolved absolute time for plugins to use\n setTimeRange: (value: TimeRangeValue) => void;\n refresh: () => void;\n refreshInterval?: DurationString;\n refreshIntervalInMs: number;\n setRefreshInterval: (value: DurationString) => void;\n}\n\nexport const TimeRangeContext = createContext<TimeRange | undefined>(undefined);\n\nexport function useTimeRangeContext(): TimeRange {\n const ctx = useContext(TimeRangeContext);\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 useTimeRange(): TimeRange {\n return useTimeRangeContext();\n}\n\n/**\n * Gets the suggested step for a graph query in ms for the currently selected time range.\n */\nexport function useSuggestedStepMs(width?: number): number {\n const { absoluteTimeRange } = useTimeRange();\n if (width === undefined) return 0;\n return getSuggestedStepMs(absoluteTimeRange, width);\n}\n\n/**\n * Provider implementation that supplies the time range state at runtime.\n */\nexport function TimeRangeProvider(props: TimeRangeProviderProps): ReactElement {\n const { timeRange, refreshInterval, children, setTimeRange, setRefreshInterval } = props;\n\n const queryClient = useQueryClient();\n const [absoluteTimeRange, setAbsoluteTimeRange] = useState<AbsoluteTimeRange>(\n isRelativeTimeRange(timeRange) ? toAbsoluteTimeRange(timeRange) : timeRange\n );\n\n const handleSetTimeRange = useCallback(\n (value: TimeRangeValue) => {\n setTimeRange(value);\n setAbsoluteTimeRange(isRelativeTimeRange(value) ? toAbsoluteTimeRange(value) : value);\n },\n [setTimeRange]\n );\n\n // Refresh is called when clicking on the refresh button, it refreshes all queries including variables\n const refresh = useCallback(() => {\n setAbsoluteTimeRange(isRelativeTimeRange(timeRange) ? toAbsoluteTimeRange(timeRange) : timeRange);\n queryClient\n .invalidateQueries({ queryKey: ['query'] })\n .finally(() => queryClient.removeQueries({ queryKey: ['query'], type: 'inactive' }));\n queryClient\n .invalidateQueries({ queryKey: ['variable'] })\n .finally(() => queryClient.removeQueries({ queryKey: ['variable'], type: 'inactive' }));\n }, [queryClient, timeRange]);\n\n // Auto refresh is only refreshing queries of panels\n const autoRefresh = useCallback(() => {\n setAbsoluteTimeRange(isRelativeTimeRange(timeRange) ? toAbsoluteTimeRange(timeRange) : timeRange);\n queryClient.invalidateQueries({ queryKey: ['query'] }).finally(() => {\n queryClient.removeQueries({ queryKey: ['query'], type: 'inactive' });\n queryClient.removeQueries({ queryKey: ['variable'], type: 'inactive' }); // Timerange is in queryKey, can lead to memory leak when using relative timerange\n });\n }, [queryClient, timeRange]);\n\n const refreshIntervalInMs = useMemo(() => getRefreshIntervalInMs(refreshInterval), [refreshInterval]);\n useEffect(() => {\n if (refreshIntervalInMs > 0) {\n const interval = setInterval(() => {\n autoRefresh();\n }, refreshIntervalInMs);\n\n return (): void => clearInterval(interval);\n }\n }, [autoRefresh, refreshIntervalInMs]);\n\n const ctx = useMemo(() => {\n return {\n timeRange: timeRange,\n setTimeRange: handleSetTimeRange,\n absoluteTimeRange: absoluteTimeRange,\n refresh,\n refreshInterval: refreshInterval,\n refreshIntervalInMs: refreshIntervalInMs,\n setRefreshInterval: setRefreshInterval,\n };\n }, [\n absoluteTimeRange,\n handleSetTimeRange,\n refresh,\n refreshInterval,\n refreshIntervalInMs,\n setRefreshInterval,\n timeRange,\n ]);\n\n return <TimeRangeContext.Provider value={ctx}>{children}</TimeRangeContext.Provider>;\n}\n"],"names":["React","createContext","useCallback","useContext","useEffect","useMemo","useState","isRelativeTimeRange","toAbsoluteTimeRange","getSuggestedStepMs","useQueryClient","getRefreshIntervalInMs","TimeRangeContext","undefined","useTimeRangeContext","ctx","Error","useTimeRange","useSuggestedStepMs","width","absoluteTimeRange","TimeRangeProvider","props","timeRange","refreshInterval","children","setTimeRange","setRefreshInterval","queryClient","setAbsoluteTimeRange","handleSetTimeRange","value","refresh","invalidateQueries","queryKey","finally","removeQueries","type","autoRefresh","refreshIntervalInMs","interval","setInterval","clearInterval","Provider"],"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,OAAOA,SAASC,aAAa,EAAgBC,WAAW,EAAEC,UAAU,EAAEC,SAAS,EAAEC,OAAO,EAAEC,QAAQ,QAAQ,QAAQ;AAClH,SAIEC,mBAAmB,EACnBC,mBAAmB,EACnBC,kBAAkB,QACb,mBAAmB;AAC1B,SAASC,cAAc,QAAQ,wBAAwB;AACvD,SAASC,sBAAsB,QAAQ,qBAAqB;AAoB5D,OAAO,MAAMC,iCAA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AqBtB,oBAAoBgB,aAAaf,oBAAoBe,aAAaA;QACvFK,YAAYK,iBAAiB,CAAC;YAAEC,UAAU;gBAAC;aAAQ;QAAC,GAAGC,OAAO,CAAC;YAC7DP,YAAYQ,aAAa,CAAC;gBAAEF,UAAU;oBAAC;iBAAQ;gBAAEG,MAAM;YAAW;YAClET,YAAYQ,aAAa,CAAC;gBAAEF,UAAU;oBAAC;iBAAW;gBAAEG,MAAM;YAAW,IAAI,kFAAkF;QAC7J;IACF,GAAG;QAACT;QAAaL;KAAU;IAE3B,MAAMgB,sBAAsBlC,QAAQ,IAAMM,uBAAuBa,kBAAkB;QAACA;KAAgB;IACpGpB,UAAU;QACR,IAAImC,sBAAsB,GAAG;YAC3B,MAAMC,WAAWC,YAAY;gBAC3BH;YACF,GAAGC;YAEH,OAAO,IAAYG,cAAcF;QACnC;IACF,GAAG;QAACF;QAAaC;KAAoB;IAErC,MAAMxB,MAAMV,QAAQ;QAClB,OAAO;YACLkB,WAAWA;YACXG,cAAcI;YACdV,mBAAmBA;YACnBY;YACAR,iBAAiBA;YACjBe,qBAAqBA;YACrBZ,oBAAoBA;QACtB;IACF,GAAG;QACDP;QACAU;QACAE;QACAR;QACAe;QACAZ;QACAJ;KACD;IAED,qBAAO,KAACX,iBAAiB+B,QAAQ;QAACZ,OAAOhB;kBAAMU;;AACjD"}
@@ -1,4 +1,4 @@
1
- import { DurationString, TimeRangeValue } from '@perses-dev/core';
1
+ import { DurationString, TimeRangeValue } from '@perses-dev/spec';
2
2
  import React, { ReactElement } from 'react';
3
3
  export interface TimeRangeProvidersProps {
4
4
  initialTimeRange: TimeRangeValue;
@@ -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/core';\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
+ {"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/core';\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,QAAo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QAACgB,MAAMlB,UAAU;QAAEkB,MAAMjB,eAAe;QAAEiB,MAAMhB,OAAO;KAAC;IAE3D,qBAAO,KAACG,yBAAyBc,QAAQ;QAACC,OAAOb;kBAAMW,MAAMG,QAAQ;;AACvE"}
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,mEA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BAAyBC,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/core';
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/core';
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;AACpE,2EAA2E;AAC3E,sEAAsE;AACtE,iCAAiC;AAEjC,SAASA,OAAO,EAAEC,WAAW,EAAEC,SAAS,EAAEC,QAAQ,QAAQ,QAAQ;AAClE,SAA2BC,cAAc,EAAEC,WAAW,QAAQ,mBAAmB;AACjF,SAASC,WAAW,EAAEC,MAAM,QAAQ,WAAW;AAC/C,SAEEC,mBAAmB,EACnBC,gBAAgB,QAGX,mBAAmB;AAK1B,iGAAiG,GACjG,SAASC,gBACPC,KAAuD,EACvDC,gBAA0B;IAE1B,WAAW;IACX,IAAI,CAACD,SAAUA,MAAME,MAAM,KAAK,KAAM,CAAA,CAACD,oBAAqBA,oBAAoBD,UAAU,EAAE,GAAK;QAC/F,OAAO;IACT;IAEA,MAAMG,MAAMH,iBAAiBI,QAAQJ,KAAK,CAAC,EAAE,GAAGA;IAChD,IAAIG,QAAQ,QAAQA,QAAQE,WAAW;QACrC,OAAOF;IACT;IACA,IAAI,CAACF,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AAIV,iBAAiBmC,WAAW;YAC9BF,mBAAmBE;QACrB;QACA,OAAOF;IACT,GAAG;QAACH;QAAmBJ;KAAQ;AACjC;AAEA;;CAEC,GACD,OAAO,SAASkB,4BACdC,sBAAuC;IAEvC,MAAM,CAACd,OAAOM,SAAS,GAAG1C,eAAe8B,4BAA4B;QAAEO,YAAY;IAAY;IAE/F,gFAAgF;IAChF,MAAM,CAACM,cAAcC,gBAAgB,GAAG7C,SAAkB;IAE1D,MAAM,EAAEgC,OAAO,EAAE,GAAGK;IAEpBtC,UAAU;QACR,8EAA8E;QAC9E,IAAI,CAAC6C,gBAAgB,CAACZ,SAAS;YAC7BW,SAAS;gBAAEX,SAASmB;YAAuB;YAC3CN,gBAAgB;QAClB;IACF,GAAG;QAACM;QAAwBP;QAAcZ;QAASW;KAAS;IAE5D,MAAMS,qBAAsDtD,YAC1D,CAACkC,UAA4BW,SAAS;YAAEX;QAAQ,IAChD;QAACW;KAAS;IAGZ,OAAO;QACLU,iBAAiBF;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"}
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,sEAAsE;AACtE,oEAAoE;AACpE,2EAA2E;AAC3E,sEAAsE;AACtE,iCAAiC;AAEjC,SAASA,OAAO,EAAEC,WAAW,EAAEC,SAAS,EAAEC,QAAQ,QAAQ,QAAQ;AAClE,SAA2BC,cAAc,EAAEC,WAAW,QAAQ,mBAAmB;AACjF,SAASC,WAAW,EAAEC,MAAM,QAAQ,WAAW;AAC/C,SAEEC,mBAAmB,EACnBC,gBAAgB,QAGX,mBAAmB;AAK1B,iGAAiG,GACjG,SAASC,gBACPC,KAAuD,EACvDC,gBAA0B;IAE1B,WAAW;IACX,IAAI,CAACD,SAAUA,MAAME,MAAM,KAAK,KAAM,CAAA,CAACD,oBAAqBA,oBAAoBD,UAAU,EAAE,GAAK;QAC/F,OAAO;IACT;IAEA,MAAMG,MAAMH,iBAAiBI,QAAQJ,KAAK,CAAC,EAAE,GAAGA;IAChD,IAAIG,QAAQ,QAAQA,QAAQE,WAAW;QACrC,OAAOF;IACT;IACA,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AQ;QACjC,IAAIV,iBAAiBmC,WAAW;YAC9BF,mBAAmBE;QACrB;QACA,OAAOF;IACT,GAAG;QAACH;QAAmBJ;KAAQ;AACjC;AAEA;;CAEC,GACD,OAAO,SAASkB,4BACdC,sBAAuC;IAEvC,MAAM,CAACd,OAAOM,SAAS,GAAG1C,eAAe8B,4BAA4B;QAAEO,YAAY;IAAY;IAE/F,gFAAgF;IAChF,MAAM,CAACM,cAAcC,gBAAgB,GAAG7C,SAAkB;IAE1D,MAAM,EAAEgC,OAAO,EAAE,GAAGK;IAEpBtC,UAAU;QACR,8EAA8E;QAC9E,IAAI,CAAC6C,gBAAgB,CAACZ,SAAS;YAC7BW,SAAS;gBAAEX,SAASmB;YAAuB;YAC3CN,gBAAgB;QAClB;IACF,GAAG;QAACM;QAAwBP;QAAcZ;QAASW;KAAS;IAE5D,MAAMS,qBAAsDtD,YAC1D,CAACkC,UAA4BW,SAAS;YAAEX;QAAQ,IAChD;QAACW;KAAS;IAGZ,OAAO;QACLU,iBAAiBF;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"}
@@ -1,4 +1,4 @@
1
- import { DurationString } from '@perses-dev/core';
1
+ import { DurationString } from '@perses-dev/spec';
2
2
  /**
3
3
  * Utils function to transform a refresh interval in {@link DurationString} format into a number of ms.
4
4
  * @param refreshInterval
@@ -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/core';
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/core';\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
+ {"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,4 +1,4 @@
1
- import { QueryDefinition } from '@perses-dev/core';
1
+ import { QueryDefinition } from '@perses-dev/spec';
2
2
  import { ReactElement, ReactNode } from 'react';
3
3
  type QueryState = 'pending' | 'success' | 'error';
4
4
  interface UsageMetrics {
@@ -1 +1 @@
1
- {"version":3,"file":"UsageMetricsProvider.d.ts","sourceRoot":"","sources":["../../src/runtime/UsageMetricsProvider.tsx"],"names":[],"mappings":"AAaA,OAAO,EAAS,eAAe,EAAE,MAAM,kBAAkB,CAAC;AAC1D,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"}
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, QueryDefinition } from '@perses-dev/core';\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,QAAyB,mBAAmB;AAC1D,SAASC,aAAa,EAA2BC,UAAU,QAAQ,QAAQ;AAyB3E,OAAO,MAAMC,oCAAsBF,cAAwCG,WAAW;AAEtF,OAAO,MAAMC,yBAAyB;IACpC,OAAOH,WAAWC;AACpB,EAAE;AAEF,OAAO,MAAMG,kBAAkB;IAC7B,MAAMC,MAAMF;IAEZ,OAAO;QACLG,WAAW,CAACC,YAA6BC;YACvC,IAAIH,QAAQH,WAAW;gBACrB;YACF;YAEA,MAAMO,gBAAgBC,KAAKC,SAAS,CAACJ;YACrC,IAAIF,IAAIO,cAAc,CAACC,GAAG,CAACJ,kBAAkBD,aAAa,WAAW;gBACnE,qFAAqF;gBACrF;YACF;YAEA,IAAIH,IAAIO,cAAc,CAACE,GAAG,CAACL,mBAAmBD,UAAU;gBACtDH,IAAIO,cAAc,CAACG,GAAG,CAACN,eAAeD;gBACtC,IAAIA,aAAa,SAAS;oBACxBH,IAAIW,gBAAgB,IAAI;gBAC1B;gBAEA,MAAMC,UAAU;uBAAIZ,IAAIO,cAAc,CAACM,MAAM;iBAAG,CAACC,KAAK,CAAC,CAACC,IAAMA,MAAM;gBACpE,IAAIf,IAAIgB,gBAAgB,KAAK,KAAKJ,SAAS;oBACzCZ,IAAIgB,gBAAgB,GAAGC,KAAKC,GAAG,KAAKlB,IAAImB,eAAe;oBACvDC,cAAcpB;gBAChB;YACF;QACF;IACF;AACF,EAAE;AAEF,MAAMoB,gBAAgB,OAAOC;IAC3B,MAAM5B,MAAM,GAAG4B,MAAMC,SAAS,IAAI,GAAG,YAAY,CAAC,EAAE;QAClDC,QAAQ;QACRC,SAAS;YACP,gBAAgB;QAClB;QACAC,MAAMpB,KAAKC,SAAS,CAAC;YACnBoB,SAASL,MAAMK,OAAO;YACtBC,WAAWN,MAAMM,SAAS;YAC1BC,aAAaP,MAAML,gBAAgB,GAAG;YACtCa,eAAeR,MAAMV,gBAAgB;QACvC;IACF;AACF;AAEA,OAAO,MAAMmB,uBAAuB,CAAC,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
+ {"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,mBAAmB,CAAC,OAAO;AAEjD,SAASC,aAAa,EAA2BC,UAAU,QAAQ,QAAQ;AAyB3E,OAAO,MAAMC,oCAAsBF,cAAwCG,WAAW;AAEtF,OAAO,MAAMC,yBAAyB;IACpC,OAAOH,WAAWC;AACpB,EAAE;AAEF,OAAO,MAAMG,kBAAkB;IAC7B,MAAMC,MAAMF;IAEZ,OAAO;QACLG,WAAW,CAACC,YAA6BC;YACvC,IAAIH,QAAQH,WAAW;gBACrB;YACF;YAEA,MAAMO,gBAAgBC,KAAKC,SAAS,CAACJ;YACrC,IAAIF,IAAIO,cAAc,CAACC,GAAG,CAACJ,kBAAkBD,aAAa,WAAW;gBACnE,qFAAqF;gBACrF;YACF;YAEA,IAAIH,IAAIO,cAAc,CAACE,GAAG,CAACL,mBAAmBD,UAAU;gBACtDH,IAAIO,cAAc,CAACG,GAAG,CAACN,eAAeD;gBACtC,IAAIA,aAAa,SAAS;oBACxBH,IAAIW,gBAAgB,IAAI;gBAC1B;gBAEA,MAAMC,UAAU;uBAAIZ,IAAIO,cAAc,CAACM,MAAM;iBAAG,CAACC,KAAK,CAAC,CAACC,IAAMA,MAAM;gBACpE,IAAIf,IAAIgB,gBAAgB,KAAK,KAAKJ,SAAS;oBACzCZ,IAAIgB,gBAAgB,GAAGC,KAAKC,GAAG,KAAKlB,IAAImB,eAAe;oBACvDC,cAAcpB;gBAChB;YACF;QACF;IACF;AACF,EAAE;AAEF,MAAMoB,gBAAgB,OAAOC;IAC3B,MAAM5B,MAAM,GAAG4B,MAAMC,SAAS,IAAI,GAAG,YAAY,CAAC,EAAE;QAClDC,QAAQ;QACRC,SAAS;YACP,gBAAgB;QAClB;QACAC,MAAMpB,KAAKC,SAAS,CAAC;YACnBoB,SAASL,MAAMK,OAAO;YACtBC,WAAWN,MAAMM,SAAS;YAC1BC,aAAaP,MAAML,gBAAgB,GAAG;YACtCa,eAAeR,MAAMV,gBAAgB;QACvC;IACF;AACF;AAEA,OAAO,MAAMmB,uBAAuB,CAAC,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/core';
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/core';\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
+ {"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/core';
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/core';\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"}
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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AOoB,OAAOC;QAAI;QAC1D,OAAO;YAAEF,SAAS;YAAOC,OAAOC;QAAI;IACtC;AACF;AAEA;;CAEC,GACD,eAAe4B,qBACb5D,MAAqB,EACrBO,YAAoC,EACpCC,aAA2C,EAC3CC,eAA2D;IAE3D,IAAIT,OAAO6D,SAAS,KAAK,SAAS;QAChC,OAAOF,oBAAoB3D,QAAQO,cAAcC,eAAeC;IAClE,OAAO;QACL,OAAOsC,yBAAyB/C,QAAQO,cAAcC,eAAeC;IACvE;AACF;AAEA;;CAEC,GACD,eAAeqD,mBACb9D,MAAmB,EACnBO,YAAoC,EACpCC,aAA2C,EAC3CC,eAA2D;IAE3D,IAAIT,OAAO6D,SAAS,KAAK,SAAS;QAChC,OAAOvD,kBAAkBN,QAAQO,cAAcC,eAAeC;IAChE,OAAO;QACL,OAAO0B,uBAAuBnC,QAAQO,cAAcC,eAAeC;IACrE;AACF;AAEA;;;;;CAKC,GACD,OAAO,eAAesD,cAA4BC,MAA+B;IAC/E,MAAM,EAAEhE,MAAM,EAAEO,YAAY,EAAEC,aAAa,EAAEC,eAAe,EAAE,GAAGuD;IAEjE,IAAIzD,aAAa0D,IAAI,KAAK,GAAG;QAC3B,OAAO;YAAEnC,SAAS;QAAK;IACzB;IAEA,IAAI9B,OAAOkE,IAAI,KAAK,SAAS;QAC3B,OAAOJ,mBAAmB9D,QAAQO,cAAcC,eAAeC;IACjE,OAAO,IAAIT,OAAOkE,IAAI,KAAK,WAAW;QACpC,OAAON,qBAAqB5D,QAAQO,cAAcC,eAAeC;IACnE;IAEA,OAAO;QAAEqB,SAAS;QAAOC,OAAO,IAAIE,MAAM,CAAC,mBAAmB,CAAC;IAAE;AACnE"}
1
+ {"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,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E,MAAM,EAAEhE,MAAM,EAAEO,YAAY,EAAEC,aAAa,EAAEC,eAAe,EAAE,GAAGuD;IAEjE,IAAIzD,aAAa0D,IAAI,KAAK,GAAG;QAC3B,OAAO;YAAEnC,SAAS;QAAK;IACzB;IAEA,IAAI9B,OAAOkE,IAAI,KAAK,SAAS;QAC3B,OAAOJ,mBAAmB9D,QAAQO,cAAcC,eAAeC;IACjE,OAAO,IAAIT,OAAOkE,IAAI,KAAK,WAAW;QACpC,OAAON,qBAAqB5D,QAAQO,cAAcC,eAAeC;IACnE;IAEA,OAAO;QAAEqB,SAAS;QAAOC,OAAO,IAAIE,MAAM,CAAC,mBAAmB,CAAC;IAAE;AACnE"}
@@ -1,4 +1,4 @@
1
- import { QueryDefinition, UnknownSpec } from '@perses-dev/core';
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/core';\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
+ {"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/core';
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 {