@sfxcode/nuxt-ui-mongocamp 1.3.4 → 1.4.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 (212) hide show
  1. package/README.md +4 -0
  2. package/dist/module.d.mts +8 -0
  3. package/dist/module.json +1 -1
  4. package/dist/module.mjs +6 -0
  5. package/dist/runtime/components/MongocampAggregationBuilder.vue +302 -3
  6. package/dist/runtime/components/MongocampAggregationChart.d.vue.ts +6 -0
  7. package/dist/runtime/components/MongocampAggregationChart.vue +93 -0
  8. package/dist/runtime/components/MongocampAggregationChart.vue.d.ts +6 -0
  9. package/dist/runtime/components/MongocampAggregationStagePreview.d.vue.ts +9 -0
  10. package/dist/runtime/components/MongocampAggregationStagePreview.vue +148 -0
  11. package/dist/runtime/components/MongocampAggregationStagePreview.vue.d.ts +9 -0
  12. package/dist/runtime/components/MongocampBucketFiles.vue +169 -48
  13. package/dist/runtime/components/MongocampBulkDelete.d.vue.ts +19 -0
  14. package/dist/runtime/components/MongocampBulkDelete.vue +118 -23
  15. package/dist/runtime/components/MongocampBulkDelete.vue.d.ts +19 -0
  16. package/dist/runtime/components/MongocampBulkEdit.d.vue.ts +6 -0
  17. package/dist/runtime/components/MongocampBulkEdit.vue +23 -2
  18. package/dist/runtime/components/MongocampBulkEdit.vue.d.ts +6 -0
  19. package/dist/runtime/components/MongocampChart.d.vue.ts +29 -0
  20. package/dist/runtime/components/MongocampChart.vue +129 -0
  21. package/dist/runtime/components/MongocampChart.vue.d.ts +29 -0
  22. package/dist/runtime/components/MongocampCollectionCharts.d.vue.ts +15 -0
  23. package/dist/runtime/components/MongocampCollectionCharts.vue +199 -0
  24. package/dist/runtime/components/MongocampCollectionCharts.vue.d.ts +15 -0
  25. package/dist/runtime/components/MongocampCollectionCopy.d.vue.ts +23 -0
  26. package/dist/runtime/components/MongocampCollectionCopy.vue +445 -0
  27. package/dist/runtime/components/MongocampCollectionCopy.vue.d.ts +23 -0
  28. package/dist/runtime/components/MongocampCollectionData.d.vue.ts +4 -0
  29. package/dist/runtime/components/MongocampCollectionData.vue +343 -146
  30. package/dist/runtime/components/MongocampCollectionData.vue.d.ts +4 -0
  31. package/dist/runtime/components/MongocampCollectionInfos.vue +106 -238
  32. package/dist/runtime/components/MongocampCollections.vue +62 -0
  33. package/dist/runtime/components/MongocampCommandPalette.d.vue.ts +40 -0
  34. package/dist/runtime/components/MongocampCommandPalette.vue +135 -0
  35. package/dist/runtime/components/MongocampCommandPalette.vue.d.ts +40 -0
  36. package/dist/runtime/components/MongocampConfirmByName.vue +2 -2
  37. package/dist/runtime/components/MongocampDashboard.d.vue.ts +3 -1
  38. package/dist/runtime/components/MongocampDashboard.vue +21 -2
  39. package/dist/runtime/components/MongocampDashboard.vue.d.ts +3 -1
  40. package/dist/runtime/components/MongocampDatabases.vue +22 -0
  41. package/dist/runtime/components/MongocampDocumentCompare.d.vue.ts +20 -0
  42. package/dist/runtime/components/MongocampDocumentCompare.vue +146 -0
  43. package/dist/runtime/components/MongocampDocumentCompare.vue.d.ts +20 -0
  44. package/dist/runtime/components/MongocampDocumentView.d.vue.ts +22 -0
  45. package/dist/runtime/components/MongocampDocumentView.vue +202 -0
  46. package/dist/runtime/components/MongocampDocumentView.vue.d.ts +22 -0
  47. package/dist/runtime/components/MongocampErrorAlert.vue +12 -16
  48. package/dist/runtime/components/MongocampExportAll.d.vue.ts +18 -0
  49. package/dist/runtime/components/MongocampExportAll.vue +204 -0
  50. package/dist/runtime/components/MongocampExportAll.vue.d.ts +18 -0
  51. package/dist/runtime/components/MongocampFilePreview.d.vue.ts +16 -0
  52. package/dist/runtime/components/MongocampFilePreview.vue +162 -0
  53. package/dist/runtime/components/MongocampFilePreview.vue.d.ts +16 -0
  54. package/dist/runtime/components/MongocampFilterBuilder.vue +11 -0
  55. package/dist/runtime/components/MongocampImport.vue +2 -10
  56. package/dist/runtime/components/MongocampIndexes.d.vue.ts +18 -0
  57. package/dist/runtime/components/MongocampIndexes.vue +455 -0
  58. package/dist/runtime/components/MongocampIndexes.vue.d.ts +18 -0
  59. package/dist/runtime/components/MongocampJobs.d.vue.ts +6 -1
  60. package/dist/runtime/components/MongocampJobs.vue +24 -4
  61. package/dist/runtime/components/MongocampJobs.vue.d.ts +6 -1
  62. package/dist/runtime/components/MongocampPermissionMatrix.d.vue.ts +12 -0
  63. package/dist/runtime/components/MongocampPermissionMatrix.vue +301 -0
  64. package/dist/runtime/components/MongocampPermissionMatrix.vue.d.ts +12 -0
  65. package/dist/runtime/components/MongocampQueryBar.d.vue.ts +26 -0
  66. package/dist/runtime/components/MongocampQueryBar.vue +398 -0
  67. package/dist/runtime/components/MongocampQueryBar.vue.d.ts +26 -0
  68. package/dist/runtime/components/MongocampRoleGrants.vue +2 -2
  69. package/dist/runtime/components/MongocampRoles.vue +3 -3
  70. package/dist/runtime/components/MongocampServerOverview.d.vue.ts +20 -0
  71. package/dist/runtime/components/MongocampServerOverview.vue +443 -0
  72. package/dist/runtime/components/MongocampServerOverview.vue.d.ts +20 -0
  73. package/dist/runtime/components/MongocampSettings.d.vue.ts +25 -1
  74. package/dist/runtime/components/MongocampSettings.vue +70 -9
  75. package/dist/runtime/components/MongocampSettings.vue.d.ts +25 -1
  76. package/dist/runtime/components/MongocampUsers.vue +3 -3
  77. package/dist/runtime/composables/useMongocampAdmin.d.ts +2 -1
  78. package/dist/runtime/composables/useMongocampAdmin.js +7 -15
  79. package/dist/runtime/composables/useMongocampAggregation.d.ts +12 -1
  80. package/dist/runtime/composables/useMongocampAggregation.js +33 -25
  81. package/dist/runtime/composables/useMongocampAutoRefresh.d.ts +26 -0
  82. package/dist/runtime/composables/useMongocampAutoRefresh.js +78 -0
  83. package/dist/runtime/composables/useMongocampBucket.d.ts +13 -1
  84. package/dist/runtime/composables/useMongocampBucket.js +34 -0
  85. package/dist/runtime/composables/useMongocampClientApi.d.ts +1 -1
  86. package/dist/runtime/composables/useMongocampClientApi.js +2 -1
  87. package/dist/runtime/composables/useMongocampCollectionCopy.d.ts +85 -0
  88. package/dist/runtime/composables/useMongocampCollectionCopy.js +105 -0
  89. package/dist/runtime/composables/useMongocampCollectionStats.d.ts +10 -0
  90. package/dist/runtime/composables/useMongocampCollectionStats.js +17 -0
  91. package/dist/runtime/composables/useMongocampError.d.ts +2 -1
  92. package/dist/runtime/composables/useMongocampError.js +16 -1
  93. package/dist/runtime/composables/useMongocampExportAll.d.ts +47 -0
  94. package/dist/runtime/composables/useMongocampExportAll.js +27 -0
  95. package/dist/runtime/composables/useMongocampExtendedJson.d.ts +5 -1
  96. package/dist/runtime/composables/useMongocampExtendedJson.js +12 -6
  97. package/dist/runtime/composables/useMongocampFetchAll.d.ts +25 -0
  98. package/dist/runtime/composables/useMongocampFetchAll.js +27 -0
  99. package/dist/runtime/composables/useMongocampPermissions.d.ts +14 -0
  100. package/dist/runtime/composables/useMongocampPermissions.js +21 -0
  101. package/dist/runtime/composables/useMongocampPersistedState.d.ts +15 -0
  102. package/dist/runtime/composables/useMongocampPersistedState.js +21 -0
  103. package/dist/runtime/composables/useMongocampProxyApi.d.ts +1 -1
  104. package/dist/runtime/composables/useMongocampProxyApi.js +2 -1
  105. package/dist/runtime/composables/useMongocampQuery.d.ts +50 -2
  106. package/dist/runtime/composables/useMongocampQuery.js +72 -1
  107. package/dist/runtime/composables/useMongocampSavedPipelines.d.ts +25 -0
  108. package/dist/runtime/composables/useMongocampSavedPipelines.js +23 -0
  109. package/dist/runtime/composables/useMongocampSavedQueries.d.ts +37 -0
  110. package/dist/runtime/composables/useMongocampSavedQueries.js +50 -0
  111. package/dist/runtime/composables/useMongocampServerOverview.d.ts +42 -0
  112. package/dist/runtime/composables/useMongocampServerOverview.js +61 -0
  113. package/dist/runtime/composables/useMongocampSession.d.ts +3 -2
  114. package/dist/runtime/composables/useMongocampSession.js +14 -22
  115. package/dist/runtime/composables/useMongocampSystem.d.ts +7 -2
  116. package/dist/runtime/composables/useMongocampSystem.js +6 -2
  117. package/dist/runtime/locales/de.json +495 -10
  118. package/dist/runtime/locales/en.json +495 -10
  119. package/dist/runtime/plugin.js +8 -5
  120. package/dist/runtime/utils/aggregationPipeline.d.ts +5 -4
  121. package/dist/runtime/utils/aggregationPipeline.js +23 -9
  122. package/dist/runtime/utils/aggregationPreview.d.ts +13 -0
  123. package/dist/runtime/utils/aggregationPreview.js +10 -0
  124. package/dist/runtime/utils/aggregationResult.d.ts +5 -0
  125. package/dist/runtime/utils/aggregationResult.js +4 -0
  126. package/dist/runtime/utils/aggregationTemplates.d.ts +34 -0
  127. package/dist/runtime/utils/aggregationTemplates.js +47 -0
  128. package/dist/runtime/utils/analyzeSamples.d.ts +1 -0
  129. package/dist/runtime/utils/analyzeSamples.js +1 -1
  130. package/dist/runtime/utils/autoRefresh.d.ts +14 -0
  131. package/dist/runtime/utils/autoRefresh.js +15 -0
  132. package/dist/runtime/utils/bigIntJson.d.ts +15 -0
  133. package/dist/runtime/utils/bigIntJson.js +55 -0
  134. package/dist/runtime/utils/bulkDelete.d.ts +9 -1
  135. package/dist/runtime/utils/bulkDelete.js +15 -3
  136. package/dist/runtime/utils/bulkEdit.d.ts +6 -0
  137. package/dist/runtime/utils/bulkEdit.js +7 -0
  138. package/dist/runtime/utils/chartData.d.ts +11 -0
  139. package/dist/runtime/utils/chartData.js +9 -0
  140. package/dist/runtime/utils/collectionChart.d.ts +36 -0
  141. package/dist/runtime/utils/collectionChart.js +73 -0
  142. package/dist/runtime/utils/collectionCopy.d.ts +26 -0
  143. package/dist/runtime/utils/collectionCopy.js +38 -0
  144. package/dist/runtime/utils/collectionStats.d.ts +31 -0
  145. package/dist/runtime/utils/collectionStats.js +42 -0
  146. package/dist/runtime/utils/commandPalette.d.ts +48 -0
  147. package/dist/runtime/utils/commandPalette.js +39 -0
  148. package/dist/runtime/utils/createProxyMongocampApis.d.ts +2 -2
  149. package/dist/runtime/utils/createProxyMongocampApis.js +2 -2
  150. package/dist/runtime/utils/documentCompare.d.ts +31 -0
  151. package/dist/runtime/utils/documentCompare.js +70 -0
  152. package/dist/runtime/utils/documentDiff.d.ts +19 -0
  153. package/dist/runtime/utils/documentDiff.js +71 -0
  154. package/dist/runtime/utils/documentPaths.d.ts +44 -0
  155. package/dist/runtime/utils/documentPaths.js +144 -0
  156. package/dist/runtime/utils/documentTree.d.ts +40 -0
  157. package/dist/runtime/utils/documentTree.js +94 -0
  158. package/dist/runtime/utils/exportDocuments.d.ts +35 -0
  159. package/dist/runtime/utils/exportDocuments.js +54 -0
  160. package/dist/runtime/utils/exportRows.js +1 -1
  161. package/dist/runtime/utils/filePreview.d.ts +27 -0
  162. package/dist/runtime/utils/filePreview.js +50 -0
  163. package/dist/runtime/utils/filterBuilder.d.ts +6 -1
  164. package/dist/runtime/utils/filterBuilder.js +6 -5
  165. package/dist/runtime/utils/formatBytes.d.ts +2 -0
  166. package/dist/runtime/utils/formatBytes.js +11 -0
  167. package/dist/runtime/utils/grantMatching.d.ts +8 -0
  168. package/dist/runtime/utils/grantMatching.js +15 -0
  169. package/dist/runtime/utils/importRows.js +12 -2
  170. package/dist/runtime/utils/indexCopy.d.ts +26 -0
  171. package/dist/runtime/utils/indexCopy.js +22 -0
  172. package/dist/runtime/utils/indexForm.d.ts +69 -0
  173. package/dist/runtime/utils/indexForm.js +63 -0
  174. package/dist/runtime/utils/limitedMap.d.ts +17 -0
  175. package/dist/runtime/utils/limitedMap.js +19 -0
  176. package/dist/runtime/utils/luceneExpression.d.ts +15 -0
  177. package/dist/runtime/utils/luceneExpression.js +74 -0
  178. package/dist/runtime/utils/pagedFetch.d.ts +46 -0
  179. package/dist/runtime/utils/pagedFetch.js +58 -0
  180. package/dist/runtime/utils/paginationHeaders.d.ts +4 -0
  181. package/dist/runtime/utils/paginationHeaders.js +4 -0
  182. package/dist/runtime/utils/permissionDenied.d.ts +10 -0
  183. package/dist/runtime/utils/permissionDenied.js +23 -0
  184. package/dist/runtime/utils/permissionMatrix.d.ts +55 -0
  185. package/dist/runtime/utils/permissionMatrix.js +85 -0
  186. package/dist/runtime/utils/persistedState.d.ts +25 -0
  187. package/dist/runtime/utils/persistedState.js +47 -0
  188. package/dist/runtime/utils/queryState.d.ts +45 -0
  189. package/dist/runtime/utils/queryState.js +75 -0
  190. package/dist/runtime/utils/requestLimits.d.ts +2 -0
  191. package/dist/runtime/utils/requestLimits.js +4 -0
  192. package/dist/runtime/utils/resultChart.d.ts +32 -0
  193. package/dist/runtime/utils/resultChart.js +59 -0
  194. package/dist/runtime/utils/savedPipelines.d.ts +22 -0
  195. package/dist/runtime/utils/savedPipelines.js +46 -0
  196. package/dist/runtime/utils/savedQueries.d.ts +60 -0
  197. package/dist/runtime/utils/savedQueries.js +143 -0
  198. package/dist/runtime/utils/schemaAnalysis.d.ts +16 -0
  199. package/dist/runtime/utils/schemaAnalysis.js +57 -0
  200. package/dist/runtime/utils/serverError.d.ts +19 -0
  201. package/dist/runtime/utils/serverError.js +19 -0
  202. package/dist/runtime/utils/serverOverview.d.ts +47 -0
  203. package/dist/runtime/utils/serverOverview.js +40 -0
  204. package/dist/runtime/utils/sessionGuard.d.ts +3 -0
  205. package/dist/runtime/utils/sessionGuard.js +18 -1
  206. package/package.json +13 -12
  207. package/dist/runtime/utils/failureKind.d.ts +0 -3
  208. package/dist/runtime/utils/failureKind.js +0 -11
  209. package/dist/runtime/utils/serverProbe.d.ts +0 -10
  210. package/dist/runtime/utils/serverProbe.js +0 -25
  211. package/dist/runtime/utils/throttled.d.ts +0 -6
  212. package/dist/runtime/utils/throttled.js +0 -16
@@ -79,7 +79,7 @@ const editUserSchema = reactive([
79
79
  }
80
80
  ]);
81
81
  const loadError = ref(null);
82
- const { describeError } = useMongocampError();
82
+ const { describeError, describeServerError } = useMongocampError();
83
83
  const storage = useMongocampStorage();
84
84
  const rowSelection = ref({});
85
85
  const selectedUserIds = computed(() => Object.keys(rowSelection.value).filter((id) => rowSelection.value[id]));
@@ -179,7 +179,7 @@ async function handleDeleteUser() {
179
179
  isDeleteModalOpen.value = false;
180
180
  await fetchUsers();
181
181
  } catch (e) {
182
- deleteError.value = describeError(e, "nuxtUiMongocamp.users.errorDelete").message;
182
+ deleteError.value = (await describeServerError(e, "nuxtUiMongocamp.users.errorDelete")).message;
183
183
  } finally {
184
184
  deleting.value = false;
185
185
  }
@@ -204,7 +204,7 @@ async function handleRegenerateKey() {
204
204
  newApiKey.value = await regenerateUserApiKey(keyUser.value);
205
205
  await fetchUsers();
206
206
  } catch (e) {
207
- keyError.value = describeError(e).message;
207
+ keyError.value = (await describeServerError(e)).message;
208
208
  } finally {
209
209
  keyBusy.value = false;
210
210
  }
@@ -1,4 +1,4 @@
1
- import type { Grant, JsonSchema, JsonValueBoolean, Role, UserProfile } from '@sfxcode/nuxt-mongocamp-server';
1
+ import type { Grant, JsonSchema, JsonValueBoolean, Role, SchemaAnalysis, UserProfile } from '@sfxcode/nuxt-mongocamp-server';
2
2
  declare const _default: () => {
3
3
  listUsers: (filter?: string) => Promise<UserProfile[]>;
4
4
  addUser: (userId: string, password: string, apiKey?: string, roles?: string[]) => Promise<UserProfile>;
@@ -13,6 +13,7 @@ declare const _default: () => {
13
13
  clearCollection: (collectionName: string) => Promise<JsonValueBoolean>;
14
14
  deleteCollection: (collectionName: string) => Promise<JsonValueBoolean>;
15
15
  getJsonSchema: (collectionName: string) => Promise<JsonSchema>;
16
+ getSchemaAnalysis: (collectionName: string, documents: number, depth?: number) => Promise<SchemaAnalysis>;
16
17
  getUser: (userId: string) => Promise<UserProfile>;
17
18
  getRole: (roleName: string) => Promise<Role>;
18
19
  regenerateUserApiKey: (userId: string) => Promise<string>;
@@ -1,4 +1,5 @@
1
1
  import { useMongocampClientApi } from "#imports";
2
+ import { analysisSampleSize, analysisTimeoutMs } from "../utils/schemaAnalysis.js";
2
3
  const REQUEST_TIMEOUT_MS = 15e3;
3
4
  function withTimeout() {
4
5
  return { signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS) };
@@ -51,25 +52,16 @@ export default () => {
51
52
  async function clearCollection(collectionName) {
52
53
  return collectionApi.clearCollection({ collectionName }, withTimeout());
53
54
  }
54
- async function collectionIsGone(collectionName) {
55
- try {
56
- return !(await collectionApi.listCollections(withTimeout())).includes(collectionName);
57
- } catch {
58
- return false;
59
- }
60
- }
61
55
  async function deleteCollection(collectionName) {
62
- try {
63
- return await collectionApi.deleteCollection({ collectionName }, withTimeout());
64
- } catch (error) {
65
- const status = error?.response?.status;
66
- if (status === 500 && await collectionIsGone(collectionName)) return { value: true };
67
- throw error;
68
- }
56
+ return collectionApi.deleteCollection({ collectionName }, withTimeout());
69
57
  }
70
58
  async function getJsonSchema(collectionName) {
71
59
  return collectionApi.getJsonSchema({ collectionName }, withTimeout());
72
60
  }
61
+ async function getSchemaAnalysis(collectionName, documents, depth = 3) {
62
+ const sampleSize = analysisSampleSize(documents);
63
+ return collectionApi.getSchemaAnalysis({ collectionName, sampleSize, deepth: depth }, { signal: AbortSignal.timeout(analysisTimeoutMs(sampleSize)) });
64
+ }
73
65
  async function getUser(userId) {
74
66
  return adminApi.getUser({ userId }, withTimeout());
75
67
  }
@@ -80,5 +72,5 @@ export default () => {
80
72
  const result = await adminApi.gnerateNewApiKeyForUser({ userId }, withTimeout());
81
73
  return result.value;
82
74
  }
83
- return { listUsers, addUser, deleteUser, updateUserRoles, updateUserPassword, listRoles, addRole, updateRole, deleteRole, listCollections, clearCollection, deleteCollection, getJsonSchema, getUser, getRole, regenerateUserApiKey };
75
+ return { listUsers, addUser, deleteUser, updateUserRoles, updateUserPassword, listRoles, addRole, updateRole, deleteRole, listCollections, clearCollection, deleteCollection, getJsonSchema, getSchemaAnalysis, getUser, getRole, regenerateUserApiKey };
84
76
  };
@@ -3,6 +3,16 @@ export interface AggregationPaging {
3
3
  page?: number;
4
4
  rowsPerPage?: number;
5
5
  }
6
+ export interface AggregationOptions {
7
+ /**
8
+ * Lets the pipeline use `$collStats` / `$indexStats` (storage and index-usage numbers) — and nothing else from the
9
+ * deny-list. Their results carry the database server's address, so `host` and `ns` are removed from every row.
10
+ * For the module's own stats calls; the aggregation builder never sets it.
11
+ */
12
+ allowStatsStages?: boolean;
13
+ /** Aborting rejects the call (an `AbortError`); the 30 s timeout still applies. */
14
+ signal?: AbortSignal;
15
+ }
6
16
  export interface AggregationResult {
7
17
  rows: Record<string, unknown>[];
8
18
  total: number;
@@ -21,8 +31,9 @@ export interface DescribedAggregationError {
21
31
  message: string;
22
32
  }
23
33
  export declare function useMongocampAggregation(): {
24
- runAggregation: (collectionName: string, pipeline: RequestStage[], paging?: AggregationPaging) => Promise<AggregationResult>;
34
+ runAggregation: (collectionName: string, pipeline: RequestStage[], paging?: AggregationPaging, options?: AggregationOptions) => Promise<AggregationResult>;
25
35
  listDistinct: (collectionName: string, field: string, limit?: number) => Promise<DistinctResult>;
36
+ listFieldNames: (collectionName: string) => Promise<string[]>;
26
37
  sampleDocuments: (collectionName: string, size?: number) => Promise<AggregationResult>;
27
38
  describeAggregationError: (error: unknown) => Promise<DescribedAggregationError>;
28
39
  };
@@ -1,7 +1,12 @@
1
1
  import { useMongocampClientApi, useI18n } from "#imports";
2
2
  import { useMongocampError } from "./useMongocampError.js";
3
- import { findForbidden } from "../utils/aggregationPipeline.js";
4
- import { ForbiddenPipelineError, parseServerError } from "../utils/aggregationErrors.js";
3
+ import { findForbidden, STATS_OPERATORS } from "../utils/aggregationPipeline.js";
4
+ import { ForbiddenPipelineError } from "../utils/aggregationErrors.js";
5
+ import { stripServerFields } from "../utils/aggregationResult.js";
6
+ import { readJsonKeepingLongs } from "../utils/bigIntJson.js";
7
+ import { headerNumber } from "../utils/paginationHeaders.js";
8
+ import { unwrapExtendedJson } from "./useMongocampExtendedJson.js";
9
+ import { notAllowedOperator, OPERATOR_NOT_ALLOWED_CODE, readServerError } from "../utils/serverError.js";
5
10
  const AGGREGATE_TIMEOUT_MS = 3e4;
6
11
  const REQUEST_TIMEOUT_MS = 15e3;
7
12
  const DEFAULT_SAMPLE_SIZE = 500;
@@ -10,19 +15,19 @@ const DEFAULT_DISTINCT_LIMIT = 100;
10
15
  function withTimeout(ms) {
11
16
  return { signal: AbortSignal.timeout(ms) };
12
17
  }
18
+ function requestInit(ms, signal) {
19
+ const timeout = AbortSignal.timeout(ms);
20
+ return { signal: signal && typeof AbortSignal.any === "function" ? AbortSignal.any([signal, timeout]) : timeout };
21
+ }
13
22
  function isPlainObject(value) {
14
23
  return typeof value === "object" && value !== null && !Array.isArray(value);
15
24
  }
16
- function headerNumber(headers, name) {
17
- const parsed = Number.parseInt(headers?.get(name) ?? "", 10);
18
- return Number.isNaN(parsed) ? void 0 : parsed;
19
- }
20
25
  export function useMongocampAggregation() {
21
26
  const { collectionApi } = useMongocampClientApi();
22
27
  const { describeError } = useMongocampError();
23
28
  const { t } = useI18n();
24
- async function runAggregation(collectionName, pipeline, paging = {}) {
25
- const findings = findForbidden(pipeline);
29
+ async function runAggregation(collectionName, pipeline, paging = {}, options = {}) {
30
+ const findings = findForbidden(pipeline, options.allowStatsStages ? STATS_OPERATORS : []);
26
31
  if (findings.length > 0) throw new ForbiddenPipelineError(findings);
27
32
  const page = paging.page ?? 1;
28
33
  const response = await collectionApi.aggregateRaw({
@@ -31,9 +36,10 @@ export function useMongocampAggregation() {
31
36
  mongoAggregateRequest: { pipeline, allowDiskUse: false },
32
37
  rowsPerPage: paging.rowsPerPage,
33
38
  page
34
- }, withTimeout(AGGREGATE_TIMEOUT_MS));
35
- const value = await response.value();
36
- const rows = Array.isArray(value) ? value.filter(isPlainObject) : [];
39
+ }, requestInit(AGGREGATE_TIMEOUT_MS, options.signal));
40
+ const value = await readJsonKeepingLongs(response);
41
+ const unwrapped = Array.isArray(value) ? value.filter(isPlainObject).map((row) => unwrapExtendedJson(row)) : [];
42
+ const rows = options.allowStatsStages ? stripServerFields(unwrapped) : unwrapped;
37
43
  const headers = response.raw?.headers;
38
44
  return {
39
45
  rows,
@@ -42,9 +48,13 @@ export function useMongocampAggregation() {
42
48
  page: headerNumber(headers, "x-pagination-current-page") ?? page
43
49
  };
44
50
  }
51
+ async function listFieldNames(collectionName) {
52
+ const names = await collectionApi.getCollectionFields({ collectionName }, withTimeout(REQUEST_TIMEOUT_MS));
53
+ return [...new Set(names)].sort((a, b) => a.localeCompare(b));
54
+ }
45
55
  async function listDistinct(collectionName, field, limit = DEFAULT_DISTINCT_LIMIT) {
46
56
  const response = await collectionApi.distinctRaw({ collectionName, field, rowsPerPage: limit, page: 1 }, withTimeout(REQUEST_TIMEOUT_MS));
47
- const value = await response.value();
57
+ const value = unwrapExtendedJson(await readJsonKeepingLongs(response));
48
58
  const values = (Array.isArray(value) ? value : []).filter((v) => typeof v === "string" || typeof v === "number" || typeof v === "boolean");
49
59
  const total = headerNumber(response.raw?.headers, "x-pagination-count-rows") ?? values.length;
50
60
  return { values, total, truncated: total > values.length };
@@ -57,22 +67,20 @@ export function useMongocampAggregation() {
57
67
  if (error instanceof ForbiddenPipelineError) {
58
68
  return { kind: "forbidden", message: t("nuxtUiMongocamp.aggregation.errors.forbidden", { operator: error.findings[0]?.operator ?? "" }) };
59
69
  }
60
- const response = error?.response;
61
- const status = response?.status;
70
+ const server = await readServerError(error);
71
+ if (server.code === OPERATOR_NOT_ALLOWED_CODE) {
72
+ const operator = notAllowedOperator(server.message);
73
+ return { kind: "forbidden", message: operator ? t("nuxtUiMongocamp.aggregation.errors.forbidden", { operator }) : t("nuxtUiMongocamp.errors.notAllowed") };
74
+ }
75
+ const status = server.status;
62
76
  if (status === 405) return { kind: "retryable", message: t("nuxtUiMongocamp.aggregation.errors.retryable") };
63
77
  if (status === 503) return { kind: "retryable", message: t("nuxtUiMongocamp.aggregation.errors.unavailable") };
64
- if (response && status !== void 0 && status >= 400 && status !== 401 && status !== 403) {
65
- try {
66
- const body = await response.clone().json();
67
- if (typeof body?.msg === "string" && body.msg) {
68
- const info = parseServerError(body.msg);
69
- if (info.message) return { kind: info.kind, message: info.message };
70
- }
71
- } catch {
72
- }
78
+ if (status !== void 0 && status >= 400 && status !== 401 && status !== 403 && server.message) {
79
+ return { kind: server.kind ?? "other", message: server.message };
73
80
  }
74
81
  const described = describeError(error);
75
- return { kind: described.kind === "forbidden" ? "forbidden-access" : described.kind, message: described.message };
82
+ const kind = described.kind === "forbidden" ? "forbidden-access" : described.kind === "notAllowed" || described.kind === "invalid" ? "other" : described.kind;
83
+ return { kind, message: described.message };
76
84
  }
77
- return { runAggregation, listDistinct, sampleDocuments, describeAggregationError };
85
+ return { runAggregation, listDistinct, listFieldNames, sampleDocuments, describeAggregationError };
78
86
  }
@@ -0,0 +1,26 @@
1
+ import type { MaybeRefOrGetter, Ref } from 'vue';
2
+ import type { BackoffOptions } from '../utils/autoRefresh.js';
3
+ export interface AutoRefreshOptions {
4
+ /** Time between the end of one load and the start of the next (at least 1000; a ref or getter is read at every schedule). */
5
+ intervalMs: MaybeRefOrGetter<number>;
6
+ /** Wait while the tab is hidden and load again as soon as it is shown (default true). */
7
+ pauseWhenHidden?: boolean;
8
+ /** Slow down after failures (`false` = always the plain interval). Default: ×2 up to 5 minutes. */
9
+ backoff?: BackoffOptions | false;
10
+ }
11
+ export interface AutoRefresh {
12
+ start: () => void;
13
+ stop: () => void;
14
+ /** Loads now (unless a load is running) and restarts the wait; works while stopped too, without starting the timer. */
15
+ refreshNow: () => Promise<void>;
16
+ running: Ref<boolean>;
17
+ lastRefreshed: Ref<Date | null>;
18
+ /** The error of the latest load, cleared by the next success. */
19
+ lastError: Ref<unknown>;
20
+ }
21
+ /**
22
+ * Calls `load` repeatedly while running. Loads never overlap (the next wait starts after the previous load ended), a
23
+ * failing load backs the delay off and is reported in `lastError` instead of being thrown, a hidden tab pauses it, and it
24
+ * stops with the component/effect scope that created it. It never runs on the server.
25
+ */
26
+ export declare function useMongocampAutoRefresh(load: () => Promise<unknown> | unknown, options: AutoRefreshOptions): AutoRefresh;
@@ -0,0 +1,78 @@
1
+ import { getCurrentScope, onScopeDispose, ref, toValue } from "vue";
2
+ import { nextDelay } from "../utils/autoRefresh.js";
3
+ export function useMongocampAutoRefresh(load, options) {
4
+ const running = ref(false);
5
+ const lastRefreshed = ref(null);
6
+ const lastError = ref(null);
7
+ const pauseWhenHidden = options.pauseWhenHidden ?? true;
8
+ const isBrowser = typeof document !== "undefined";
9
+ let timer;
10
+ let inFlight;
11
+ let failures = 0;
12
+ let generation = 0;
13
+ let listening = false;
14
+ const hidden = () => pauseWhenHidden && isBrowser && document.hidden;
15
+ const delay = () => nextDelay(toValue(options.intervalMs), failures, options.backoff);
16
+ function clearTimer() {
17
+ if (timer !== void 0) clearTimeout(timer);
18
+ timer = void 0;
19
+ }
20
+ function schedule() {
21
+ clearTimer();
22
+ if (!running.value || hidden()) return;
23
+ timer = setTimeout(() => void run(), delay());
24
+ }
25
+ function run() {
26
+ if (inFlight) return inFlight;
27
+ clearTimer();
28
+ const mine = generation;
29
+ inFlight = (async () => {
30
+ try {
31
+ await load();
32
+ failures = 0;
33
+ lastError.value = null;
34
+ lastRefreshed.value = /* @__PURE__ */ new Date();
35
+ } catch (e) {
36
+ failures++;
37
+ lastError.value = e;
38
+ } finally {
39
+ inFlight = void 0;
40
+ if (mine === generation) schedule();
41
+ }
42
+ })();
43
+ return inFlight;
44
+ }
45
+ function onVisibility() {
46
+ if (!running.value) return;
47
+ if (document.hidden) {
48
+ if (pauseWhenHidden) clearTimer();
49
+ return;
50
+ }
51
+ if (pauseWhenHidden && !inFlight) void run();
52
+ }
53
+ function start() {
54
+ if (!isBrowser || running.value) return;
55
+ running.value = true;
56
+ failures = 0;
57
+ if (!listening) {
58
+ document.addEventListener("visibilitychange", onVisibility);
59
+ listening = true;
60
+ }
61
+ schedule();
62
+ }
63
+ function stop() {
64
+ generation++;
65
+ running.value = false;
66
+ clearTimer();
67
+ if (listening && isBrowser) {
68
+ document.removeEventListener("visibilitychange", onVisibility);
69
+ listening = false;
70
+ }
71
+ }
72
+ async function refreshNow() {
73
+ if (!isBrowser) return;
74
+ await run();
75
+ }
76
+ if (getCurrentScope()) onScopeDispose(stop);
77
+ return { start, stop, refreshNow, running, lastRefreshed, lastError };
78
+ }
@@ -12,7 +12,7 @@ export interface ListFilesResult {
12
12
  }
13
13
  export interface UpdateFileInformationOptions {
14
14
  filename?: string;
15
- metadata?: Record<string, string>;
15
+ metadata?: Record<string, unknown>;
16
16
  }
17
17
  export declare function useMongocampBucket(): {
18
18
  isBucketCollection: (collectionName: string) => boolean;
@@ -22,6 +22,18 @@ export declare function useMongocampBucket(): {
22
22
  uploading: import("vue").Ref<boolean, boolean>;
23
23
  downloadFile: (collectionName: string, fileId: string) => Promise<void>;
24
24
  uploadFile: (collectionName: string, file: File) => Promise<boolean>;
25
+ uploadFiles: (bucketName: string, files: File[], options?: {
26
+ signal?: AbortSignal;
27
+ onProgress?: (done: number, total: number, current?: string) => void;
28
+ }) => Promise<{
29
+ uploaded: string[];
30
+ failed: {
31
+ name: string;
32
+ message: string;
33
+ }[];
34
+ aborted: boolean;
35
+ }>;
36
+ fetchFileBlob: (bucketName: string, fileId: string) => Promise<Blob>;
25
37
  bucketActionInFlight: import("vue").Ref<Set<string> & Omit<Set<string>, keyof Set<any>>, Set<string> | (Set<string> & Omit<Set<string>, keyof Set<any>>)>;
26
38
  fileActionInFlight: import("vue").Ref<Set<string> & Omit<Set<string>, keyof Set<any>>, Set<string> | (Set<string> & Omit<Set<string>, keyof Set<any>>)>;
27
39
  listFiles: (bucketName: string, options?: ListFilesOptions) => Promise<ListFilesResult>;
@@ -1,6 +1,7 @@
1
1
  import { ref } from "vue";
2
2
  import { useI18n, useMongocampClientApi, useToast } from "#imports";
3
3
  import { BUCKET_COLLECTION_SUFFIX } from "../utils/collectionProtection.js";
4
+ import { isFilterTooLong, MAX_ENCODED_FILTER_LENGTH } from "../utils/requestLimits.js";
4
5
  function unwrapId(value) {
5
6
  if (typeof value === "string") return value;
6
7
  if (typeof value === "object" && value !== null && "$oid" in value) {
@@ -62,7 +63,38 @@ export function useMongocampBucket() {
62
63
  uploading.value = false;
63
64
  }
64
65
  }
66
+ async function fetchFileBlob(bucketName, fileId) {
67
+ return fileApi.getFile({ bucketName, fileId });
68
+ }
69
+ async function uploadFiles(bucketName, files, options = {}) {
70
+ const uploaded = [];
71
+ const failed = [];
72
+ let aborted = false;
73
+ uploading.value = true;
74
+ try {
75
+ for (const [index, file] of files.entries()) {
76
+ if (options.signal?.aborted) {
77
+ aborted = true;
78
+ break;
79
+ }
80
+ options.onProgress?.(index, files.length, file.name);
81
+ try {
82
+ await fileApi.insertFile({ bucketName, file, fileName: file.name, metaData: "{}" });
83
+ uploaded.push(file.name);
84
+ } catch (e) {
85
+ failed.push({ name: file.name, message: e instanceof Error ? e.message : t("nuxtUiMongocamp.bucket.uploadFailedFallback") });
86
+ }
87
+ }
88
+ options.onProgress?.(uploaded.length + failed.length, files.length);
89
+ } finally {
90
+ uploading.value = false;
91
+ }
92
+ return { uploaded, failed, aborted };
93
+ }
65
94
  async function listFiles(bucketName, options = {}) {
95
+ if (isFilterTooLong(options.filter)) {
96
+ throw new Error(t("nuxtUiMongocamp.bucket.filterTooLong", { max: MAX_ENCODED_FILTER_LENGTH }));
97
+ }
66
98
  const res = await fileApi.listFilesRaw({
67
99
  bucketName,
68
100
  filter: options.filter,
@@ -145,6 +177,8 @@ export function useMongocampBucket() {
145
177
  uploading,
146
178
  downloadFile,
147
179
  uploadFile,
180
+ uploadFiles,
181
+ fetchFileBlob,
148
182
  bucketActionInFlight,
149
183
  fileActionInFlight,
150
184
  listFiles,
@@ -8,6 +8,6 @@ export declare function useMongocampClientApi(): {
8
8
  documentApi: import("@sfxcode/nuxt-mongocamp-server").DocumentApi;
9
9
  fileApi: import("@sfxcode/nuxt-mongocamp-server").FileApi;
10
10
  indexApi: import("@sfxcode/nuxt-mongocamp-server").IndexApi;
11
- informationApi: import("@sfxcode/nuxt-mongocamp-server").InformationApi;
11
+ systemApi: import("@sfxcode/nuxt-mongocamp-server").SystemApi;
12
12
  jobApi: import("@sfxcode/nuxt-mongocamp-server").JobsApi;
13
13
  };
@@ -1,8 +1,9 @@
1
1
  import { useRuntimeConfig } from "#app";
2
2
  import { useMongocampApi } from "#imports";
3
+ import { installPermissionDeniedMiddleware } from "../utils/permissionDenied.js";
3
4
  import { useMongocampProxyApi } from "./useMongocampProxyApi.js";
4
5
  export function useMongocampClientApi() {
5
6
  const config = useRuntimeConfig();
6
7
  const useServerProxy = config.public.nuxtUiMongocampOptions?.useServerProxy ?? false;
7
- return useServerProxy ? useMongocampProxyApi() : useMongocampApi();
8
+ return useServerProxy ? useMongocampProxyApi() : installPermissionDeniedMiddleware(useMongocampApi());
8
9
  }
@@ -0,0 +1,85 @@
1
+ import type { IndexCopySkipReason } from '../utils/indexCopy.js';
2
+ import type { BatchInsertResult } from './useMongocampImport.js';
3
+ export interface CopyProgress {
4
+ phase: 'reading' | 'writing' | 'indexes';
5
+ done: number;
6
+ total: number;
7
+ }
8
+ export interface CopyOptions {
9
+ source: string;
10
+ target: string;
11
+ /** Lucene filter: copy only the documents that match. */
12
+ filter?: string;
13
+ /** Refuse above this many documents (default 50 000) — nothing is read or written then. */
14
+ maxDocuments?: number;
15
+ onProgress?: (progress: CopyProgress) => void;
16
+ /**
17
+ * Create the same indexes on the new collection after the documents were written (all but `_id_`). Only when every batch
18
+ * was written; kinds the API cannot express are skipped and reported in `indexes`.
19
+ */
20
+ copyIndexes?: boolean;
21
+ /** Aborting while reading writes nothing; while writing it leaves a partly filled target (`aborted`, `skipped`). */
22
+ signal?: AbortSignal;
23
+ }
24
+ export type CopyRefusal = 'target-exists' | 'too-many-documents';
25
+ export interface BackupOptions extends Omit<CopyOptions, 'target'> {
26
+ /** The time put into the name (default: now). */
27
+ now?: Date;
28
+ /** Called with the chosen name before anything is read, so a UI can show it. */
29
+ onTarget?: (target: string) => void;
30
+ }
31
+ export interface IndexCopyResult {
32
+ /** Names of the indexes created on the target. */
33
+ copied: string[];
34
+ /** Indexes that cannot be reproduced through the API, with why (nothing is approximated). */
35
+ skipped: Array<{
36
+ name: string;
37
+ reason: IndexCopySkipReason;
38
+ }>;
39
+ /** Indexes the server refused on the target. */
40
+ failed: Array<{
41
+ name: string;
42
+ error: unknown;
43
+ }>;
44
+ }
45
+ export interface CopyResult {
46
+ /** Why nothing was copied; absent when the copy ran. */
47
+ refused?: CopyRefusal;
48
+ /** How many documents the source (or the filter) holds, as the server reported before reading. */
49
+ sourceTotal: number;
50
+ /** The documents read, in order — kept so failed batches can be retried. Empty when refused. */
51
+ rows: Record<string, unknown>[];
52
+ inserted: number;
53
+ failedBatches: BatchInsertResult['failedBatches'];
54
+ skipped: number;
55
+ aborted: boolean;
56
+ /** Documents were added or removed in the source while it was read. */
57
+ totalChanged: boolean;
58
+ /** Present when `copyIndexes` was asked for and the documents were all written (or there were none). */
59
+ indexes?: IndexCopyResult;
60
+ /** The indexes of the source could not be listed (`indexes` is then absent). */
61
+ indexesError?: unknown;
62
+ }
63
+ /**
64
+ * Copies the documents of one collection into a NEW one: reads every page of the source, then inserts them in batches.
65
+ * Documents are copied as the server gives them, `_id` included (verified on server 1.6.3: dates, 64-bit integers and ids
66
+ * come out with the same types and the read-back text is identical). Grants, the schema and GridFS files are never
67
+ * copied, indexes only with `copyIndexes`. It is not atomic and not a snapshot: the source may change while it is read.
68
+ */
69
+ export declare function useMongocampCollectionCopy(): {
70
+ copyCollection: (options: CopyOptions) => Promise<CopyResult>;
71
+ copyIndexes: (source: string, target: string, onProgress?: (done: number, total: number) => void) => Promise<IndexCopyResult>;
72
+ backupCollection: (options: BackupOptions) => Promise<CopyResult & {
73
+ target: string;
74
+ }>;
75
+ retryBatches: (target: string, rows: Record<string, unknown>[], failed: BatchInsertResult["failedBatches"], options?: Pick<CopyOptions, "signal" | "onProgress">) => Promise<{
76
+ inserted: number;
77
+ failedBatches: import("../utils/batchInsert.js").BatchInsertFailure[];
78
+ skipped: number;
79
+ aborted: boolean;
80
+ rows: Record<string, unknown>[];
81
+ }>;
82
+ listCollectionNames: () => Promise<string[]>;
83
+ countDocuments: (collection: string, filter?: string) => Promise<number>;
84
+ collectionCount: (collection: string) => Promise<number>;
85
+ };
@@ -0,0 +1,105 @@
1
+ import { useMongocampClientApi } from "#imports";
2
+ import { readJsonKeepingLongs } from "../utils/bigIntJson.js";
3
+ import { backupName, canCopyCollection, CollectionNotCopyableError, MAX_COPY_DOCUMENTS } from "../utils/collectionCopy.js";
4
+ import { headerNumber } from "../utils/paginationHeaders.js";
5
+ import { useMongocampFetchAll } from "./useMongocampFetchAll.js";
6
+ import { planIndexCopies } from "../utils/indexCopy.js";
7
+ import { useMongocampImport } from "./useMongocampImport.js";
8
+ import { useMongocampIndex } from "./useMongocampIndex.js";
9
+ const READ_PAGE_SIZE = 1e3;
10
+ export function useMongocampCollectionCopy() {
11
+ const { collectionApi, documentApi } = useMongocampClientApi();
12
+ const { fetchAllDocuments } = useMongocampFetchAll();
13
+ const { importRows } = useMongocampImport();
14
+ const { listIndexes, createIndex, createTextIndex } = useMongocampIndex();
15
+ async function listCollectionNames() {
16
+ return await collectionApi.listCollections();
17
+ }
18
+ async function countDocuments(collection, filter) {
19
+ const response = await documentApi.listDocumentsRaw({ collectionName: collection, filter, rowsPerPage: 1, page: 1 });
20
+ return headerNumber(response.raw?.headers, "x-pagination-count-rows") ?? (await readJsonKeepingLongs(response)).length;
21
+ }
22
+ async function collectionCount(collection) {
23
+ return (await collectionApi.getCollectionInformation({ collectionName: collection })).count;
24
+ }
25
+ async function copyIndexes(source, target, onProgress) {
26
+ const plans = planIndexCopies(await listIndexes(source));
27
+ const result = { copied: [], skipped: [], failed: [] };
28
+ let done = 0;
29
+ for (const plan of plans) {
30
+ if (plan.call === "skip") {
31
+ result.skipped.push({ name: plan.name, reason: plan.reason });
32
+ } else {
33
+ try {
34
+ if (plan.call === "createTextIndex") await createTextIndex(target, plan.field);
35
+ else await createIndex(target, plan.keys, plan.options);
36
+ result.copied.push(plan.name);
37
+ } catch (error) {
38
+ result.failed.push({ name: plan.name, error });
39
+ }
40
+ }
41
+ onProgress?.(++done, plans.length);
42
+ }
43
+ return result;
44
+ }
45
+ async function copyCollection(options) {
46
+ const { source, target, filter, signal } = options;
47
+ const cap = options.maxDocuments ?? MAX_COPY_DOCUMENTS;
48
+ const empty = { rows: [], inserted: 0, failedBatches: [], skipped: 0, aborted: false, totalChanged: false };
49
+ if ((await listCollectionNames()).some((name) => name.toLowerCase() === target.toLowerCase())) return { ...empty, refused: "target-exists", sourceTotal: 0 };
50
+ const sourceTotal = await countDocuments(source, filter);
51
+ if (sourceTotal > cap) return { ...empty, refused: "too-many-documents", sourceTotal };
52
+ const read = await fetchAllDocuments(source, {
53
+ filter,
54
+ pageSize: READ_PAGE_SIZE,
55
+ maxRows: cap,
56
+ signal,
57
+ // skip/limit paging can repeat a document when the source changes during the read
58
+ keyOf: (row) => String(row._id),
59
+ onProgress: (p) => options.onProgress?.({ phase: "reading", done: p.loaded, total: p.target ?? sourceTotal })
60
+ });
61
+ const rows = read.rows;
62
+ const written = rows.length === 0 ? { inserted: 0, failedBatches: [], skipped: 0, aborted: false } : await importRows(target, rows, {
63
+ signal,
64
+ onProgress: (p) => options.onProgress?.({ phase: "writing", done: p.done, total: p.total })
65
+ });
66
+ const result = {
67
+ sourceTotal,
68
+ rows,
69
+ inserted: written.inserted,
70
+ failedBatches: written.failedBatches,
71
+ skipped: written.skipped,
72
+ aborted: written.aborted,
73
+ totalChanged: read.totalChanged
74
+ };
75
+ if (options.copyIndexes && !written.aborted && written.failedBatches.length === 0) {
76
+ try {
77
+ result.indexes = await copyIndexes(source, target, (done, total) => options.onProgress?.({ phase: "indexes", done, total }));
78
+ } catch (error) {
79
+ result.indexesError = error;
80
+ }
81
+ }
82
+ return result;
83
+ }
84
+ async function backupCollection(options) {
85
+ if (!canCopyCollection(options.source)) throw new CollectionNotCopyableError(options.source);
86
+ const { now, onTarget, ...copy } = options;
87
+ let result;
88
+ for (let attempt = 0; attempt < 3; attempt++) {
89
+ const target = backupName(options.source, await listCollectionNames(), now);
90
+ onTarget?.(target);
91
+ result = { ...await copyCollection({ ...copy, target }), target };
92
+ if (result.refused !== "target-exists") break;
93
+ }
94
+ return result;
95
+ }
96
+ async function retryBatches(target, rows, failed, options = {}) {
97
+ const again = failed.flatMap((batch) => rows.slice(batch.start, batch.start + batch.count));
98
+ const result = await importRows(target, again, {
99
+ signal: options.signal,
100
+ onProgress: (p) => options.onProgress?.({ phase: "writing", done: p.done, total: p.total })
101
+ });
102
+ return { rows: again, ...result };
103
+ }
104
+ return { copyCollection, copyIndexes, backupCollection, retryBatches, listCollectionNames, countDocuments, collectionCount };
105
+ }
@@ -0,0 +1,10 @@
1
+ import type { CollectionStorage, IndexUsage } from '../utils/collectionStats.js';
2
+ export type { CollectionStorage, IndexUsage } from '../utils/collectionStats.js';
3
+ /**
4
+ * Typed storage and index-usage numbers of one collection. Both come from the server with a 15 s limit; neither shows
5
+ * the database's host, namespace or an index spec.
6
+ */
7
+ export declare function useMongocampCollectionStats(): {
8
+ getStorage: (collection: string) => Promise<CollectionStorage>;
9
+ getIndexUsage: (collection: string) => Promise<IndexUsage[]>;
10
+ };
@@ -0,0 +1,17 @@
1
+ import { useMongocampClientApi } from "#imports";
2
+ import { mapIndexUsage, mapStorage } from "../utils/collectionStats.js";
3
+ import { useMongocampAggregation } from "./useMongocampAggregation.js";
4
+ const REQUEST_TIMEOUT_MS = 15e3;
5
+ export function useMongocampCollectionStats() {
6
+ const { collectionApi } = useMongocampClientApi();
7
+ const { runAggregation } = useMongocampAggregation();
8
+ async function getStorage(collection) {
9
+ const status = await collectionApi.getCollectionInformation({ collectionName: collection }, { signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS) });
10
+ return mapStorage(status);
11
+ }
12
+ async function getIndexUsage(collection) {
13
+ const { rows } = await runAggregation(collection, [{ stage: "$indexStats", value: {} }], { rowsPerPage: 1e3 }, { allowStatsStages: true });
14
+ return mapIndexUsage(rows);
15
+ }
16
+ return { getStorage, getIndexUsage };
17
+ }