@sfxcode/nuxt-ui-mongocamp 1.4.0 → 1.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (105) hide show
  1. package/README.md +1 -1
  2. package/dist/module.json +2 -2
  3. package/dist/runtime/components/MongocampAggregationBuilder.d.vue.ts +1 -0
  4. package/dist/runtime/components/MongocampAggregationBuilder.vue +29 -2
  5. package/dist/runtime/components/MongocampAggregationBuilder.vue.d.ts +1 -0
  6. package/dist/runtime/components/MongocampAggregationStagePreview.d.vue.ts +1 -0
  7. package/dist/runtime/components/MongocampAggregationStagePreview.vue +4 -3
  8. package/dist/runtime/components/MongocampAggregationStagePreview.vue.d.ts +1 -0
  9. package/dist/runtime/components/MongocampBucketFiles.vue +61 -0
  10. package/dist/runtime/components/MongocampBulkDelete.d.vue.ts +2 -12
  11. package/dist/runtime/components/MongocampBulkDelete.vue +14 -40
  12. package/dist/runtime/components/MongocampBulkDelete.vue.d.ts +2 -12
  13. package/dist/runtime/components/MongocampBulkEdit.d.vue.ts +5 -6
  14. package/dist/runtime/components/MongocampBulkEdit.vue +43 -26
  15. package/dist/runtime/components/MongocampBulkEdit.vue.d.ts +5 -6
  16. package/dist/runtime/components/MongocampChart.vue +1 -4
  17. package/dist/runtime/components/MongocampCollectionCharts.d.vue.ts +2 -0
  18. package/dist/runtime/components/MongocampCollectionCharts.vue +9 -8
  19. package/dist/runtime/components/MongocampCollectionCharts.vue.d.ts +2 -0
  20. package/dist/runtime/components/MongocampCollectionCopy.vue +19 -258
  21. package/dist/runtime/components/MongocampCollectionData.d.vue.ts +2 -0
  22. package/dist/runtime/components/MongocampCollectionData.vue +206 -126
  23. package/dist/runtime/components/MongocampCollectionData.vue.d.ts +2 -0
  24. package/dist/runtime/components/MongocampCollectionRename.d.vue.ts +22 -0
  25. package/dist/runtime/components/MongocampCollectionRename.vue +116 -0
  26. package/dist/runtime/components/MongocampCollectionRename.vue.d.ts +22 -0
  27. package/dist/runtime/components/MongocampCollections.vue +31 -12
  28. package/dist/runtime/components/MongocampCommandPalette.vue +2 -2
  29. package/dist/runtime/components/MongocampDashboard.vue +19 -4
  30. package/dist/runtime/components/MongocampDatabases.vue +13 -2
  31. package/dist/runtime/components/MongocampExportAll.vue +13 -26
  32. package/dist/runtime/components/MongocampImport.vue +169 -3
  33. package/dist/runtime/components/MongocampIndexes.vue +54 -13
  34. package/dist/runtime/components/MongocampJobs.vue +14 -3
  35. package/dist/runtime/components/MongocampRoleGrants.vue +16 -3
  36. package/dist/runtime/components/MongocampRoles.vue +13 -2
  37. package/dist/runtime/components/MongocampServerInfo.d.vue.ts +24 -0
  38. package/dist/runtime/components/MongocampServerInfo.vue +331 -0
  39. package/dist/runtime/components/MongocampServerInfo.vue.d.ts +24 -0
  40. package/dist/runtime/components/MongocampServerOverview.vue +16 -39
  41. package/dist/runtime/components/MongocampSettings.d.vue.ts +3 -0
  42. package/dist/runtime/components/MongocampSettings.vue +14 -2
  43. package/dist/runtime/components/MongocampSettings.vue.d.ts +3 -0
  44. package/dist/runtime/components/MongocampUsers.vue +16 -3
  45. package/dist/runtime/components/MongocampVersion.d.vue.ts +7 -1
  46. package/dist/runtime/components/MongocampVersion.vue +49 -19
  47. package/dist/runtime/components/MongocampVersion.vue.d.ts +7 -1
  48. package/dist/runtime/composables/useMongocampAdminGate.d.ts +12 -0
  49. package/dist/runtime/composables/useMongocampAdminGate.js +12 -0
  50. package/dist/runtime/composables/useMongocampAggregation.d.ts +11 -0
  51. package/dist/runtime/composables/useMongocampAggregation.js +12 -5
  52. package/dist/runtime/composables/useMongocampBulkByFilter.d.ts +15 -0
  53. package/dist/runtime/composables/useMongocampBulkByFilter.js +32 -0
  54. package/dist/runtime/composables/useMongocampCollectionCopy.d.ts +25 -65
  55. package/dist/runtime/composables/useMongocampCollectionCopy.js +27 -84
  56. package/dist/runtime/composables/useMongocampExportAll.d.ts +27 -21
  57. package/dist/runtime/composables/useMongocampExportAll.js +51 -21
  58. package/dist/runtime/composables/useMongocampExtendedJson.d.ts +2 -1
  59. package/dist/runtime/composables/useMongocampExtendedJson.js +32 -5
  60. package/dist/runtime/composables/useMongocampFetchAll.js +1 -1
  61. package/dist/runtime/composables/useMongocampFieldTypes.d.ts +24 -0
  62. package/dist/runtime/composables/useMongocampFieldTypes.js +44 -0
  63. package/dist/runtime/composables/useMongocampImport.d.ts +4 -0
  64. package/dist/runtime/composables/useMongocampImport.js +5 -2
  65. package/dist/runtime/composables/useMongocampIndex.d.ts +6 -1
  66. package/dist/runtime/composables/useMongocampIndex.js +7 -1
  67. package/dist/runtime/composables/useMongocampPermissions.d.ts +8 -5
  68. package/dist/runtime/composables/useMongocampPermissions.js +24 -2
  69. package/dist/runtime/composables/useMongocampQuery.d.ts +3 -3
  70. package/dist/runtime/composables/useMongocampServerOverview.d.ts +4 -11
  71. package/dist/runtime/composables/useMongocampServerOverview.js +12 -22
  72. package/dist/runtime/composables/useMongocampSystem.d.ts +10 -1
  73. package/dist/runtime/composables/useMongocampSystem.js +11 -1
  74. package/dist/runtime/locales/de.json +104 -71
  75. package/dist/runtime/locales/en.json +104 -71
  76. package/dist/runtime/plugin.d.ts +2 -2
  77. package/dist/runtime/utils/aggregationErrors.d.ts +4 -0
  78. package/dist/runtime/utils/aggregationErrors.js +7 -0
  79. package/dist/runtime/utils/batchInsert.d.ts +6 -0
  80. package/dist/runtime/utils/batchInsert.js +31 -3
  81. package/dist/runtime/utils/bsonTypes.d.ts +10 -0
  82. package/dist/runtime/utils/bsonTypes.js +42 -0
  83. package/dist/runtime/utils/collectionCopy.d.ts +0 -2
  84. package/dist/runtime/utils/collectionCopy.js +0 -1
  85. package/dist/runtime/utils/configRows.d.ts +7 -0
  86. package/dist/runtime/utils/configRows.js +4 -0
  87. package/dist/runtime/utils/documentCompare.js +2 -1
  88. package/dist/runtime/utils/documentPaths.d.ts +5 -8
  89. package/dist/runtime/utils/documentPaths.js +5 -10
  90. package/dist/runtime/utils/documentTree.js +9 -1
  91. package/dist/runtime/utils/exportDocuments.d.ts +0 -2
  92. package/dist/runtime/utils/exportDocuments.js +0 -1
  93. package/dist/runtime/utils/exportRows.d.ts +2 -0
  94. package/dist/runtime/utils/exportRows.js +5 -2
  95. package/dist/runtime/utils/fieldDetails.d.ts +51 -0
  96. package/dist/runtime/utils/fieldDetails.js +113 -0
  97. package/dist/runtime/utils/indexForm.d.ts +47 -33
  98. package/dist/runtime/utils/indexForm.js +32 -21
  99. package/dist/runtime/utils/serverInfo.d.ts +8 -0
  100. package/dist/runtime/utils/serverInfo.js +21 -0
  101. package/package.json +11 -11
  102. package/dist/runtime/utils/indexCopy.d.ts +0 -26
  103. package/dist/runtime/utils/indexCopy.js +0 -22
  104. package/dist/runtime/utils/limitedMap.d.ts +0 -17
  105. package/dist/runtime/utils/limitedMap.js +0 -19
@@ -1,3 +1,9 @@
1
- declare const __VLS_export: import("vue").DefineComponent<{}, {}, {}, {}, {}, import("vue").ComponentOptionsMixin, import("vue").ComponentOptionsMixin, {}, string, import("vue").PublicProps, Readonly<{}> & Readonly<{}>, {}, {}, {}, {}, string, import("vue").ComponentProvideOptions, true, {}, any>;
1
+ type __VLS_Props = {
2
+ /** Hide the MongoDB version badge (it is also hidden while the server cannot tell, e.g. before login or below server 1.9.0). */
3
+ hideDatabase?: boolean;
4
+ };
5
+ declare const __VLS_export: import("vue").DefineComponent<__VLS_Props, {}, {}, {}, {}, import("vue").ComponentOptionsMixin, import("vue").ComponentOptionsMixin, {}, string, import("vue").PublicProps, Readonly<__VLS_Props> & Readonly<{}>, {
6
+ hideDatabase: boolean;
7
+ }, {}, {}, {}, string, import("vue").ComponentProvideOptions, false, {}, any>;
2
8
  declare const _default: typeof __VLS_export;
3
9
  export default _default;
@@ -0,0 +1,12 @@
1
+ /**
2
+ * For components that only make sense for an administrator (they call admin endpoints on mount): `blocked` is true when the
3
+ * signed-in user is known **not** to be an administrator, so the component can show `message` ("administrators only")
4
+ * **without sending a request** that the server must refuse. It is a UI hint, not a guard — the server stays the authority.
5
+ *
6
+ * Fail-open: server proxy mode (the api key's power decides), no profile yet, or a profile without an `isAdmin` flag are never
7
+ * blocked.
8
+ */
9
+ export declare function useMongocampAdminGate(): {
10
+ blocked: import("vue").ComputedRef<boolean>;
11
+ message: import("vue").ComputedRef<string>;
12
+ };
@@ -0,0 +1,12 @@
1
+ import { useRuntimeConfig } from "#app";
2
+ import { useI18n, useMongocampStorage } from "#imports";
3
+ import { computed } from "vue";
4
+ export function useMongocampAdminGate() {
5
+ const config = useRuntimeConfig();
6
+ const state = useMongocampStorage();
7
+ const { t } = useI18n();
8
+ const isProxyMode = config.public.nuxtUiMongocampOptions?.useServerProxy ?? false;
9
+ const blocked = computed(() => !isProxyMode && state.value?.profile?.isAdmin === false);
10
+ const message = computed(() => t("nuxtUiMongocamp.common.adminOnly"));
11
+ return { blocked, message };
12
+ }
@@ -1,3 +1,4 @@
1
+ import type { FieldInfo } from '@sfxcode/nuxt-mongocamp-server';
1
2
  import type { RequestStage } from '../utils/aggregationPipeline.js';
2
3
  export interface AggregationPaging {
3
4
  page?: number;
@@ -10,6 +11,12 @@ export interface AggregationOptions {
10
11
  * For the module's own stats calls; the aggregation builder never sets it.
11
12
  */
12
13
  allowStatsStages?: boolean;
14
+ /**
15
+ * A Lucene filter (the syntax of the document list) applied by the server as the first `$match` (server 1.7.0), so an
16
+ * aggregation can follow what a table shows. It travels in the URL: one over ~1 800 encoded characters is refused up front
17
+ * with a `FilterTooLongError` instead of becoming an opaque network failure.
18
+ */
19
+ filter?: string;
13
20
  /** Aborting rejects the call (an `AbortError`); the 30 s timeout still applies. */
14
21
  signal?: AbortSignal;
15
22
  }
@@ -34,6 +41,10 @@ export declare function useMongocampAggregation(): {
34
41
  runAggregation: (collectionName: string, pipeline: RequestStage[], paging?: AggregationPaging, options?: AggregationOptions) => Promise<AggregationResult>;
35
42
  listDistinct: (collectionName: string, field: string, limit?: number) => Promise<DistinctResult>;
36
43
  listFieldNames: (collectionName: string) => Promise<string[]>;
44
+ listFieldDetails: (collectionName: string, options?: {
45
+ sampleSize?: number;
46
+ depth?: number;
47
+ }) => Promise<FieldInfo[]>;
37
48
  sampleDocuments: (collectionName: string, size?: number) => Promise<AggregationResult>;
38
49
  describeAggregationError: (error: unknown) => Promise<DescribedAggregationError>;
39
50
  };
@@ -1,7 +1,9 @@
1
1
  import { useMongocampClientApi, useI18n } from "#imports";
2
2
  import { useMongocampError } from "./useMongocampError.js";
3
3
  import { findForbidden, STATS_OPERATORS } from "../utils/aggregationPipeline.js";
4
- import { ForbiddenPipelineError } from "../utils/aggregationErrors.js";
4
+ import { FilterTooLongError, ForbiddenPipelineError } from "../utils/aggregationErrors.js";
5
+ import { fieldPathsOf } from "../utils/fieldDetails.js";
6
+ import { isFilterTooLong, MAX_ENCODED_FILTER_LENGTH } from "../utils/requestLimits.js";
5
7
  import { stripServerFields } from "../utils/aggregationResult.js";
6
8
  import { readJsonKeepingLongs } from "../utils/bigIntJson.js";
7
9
  import { headerNumber } from "../utils/paginationHeaders.js";
@@ -29,13 +31,15 @@ export function useMongocampAggregation() {
29
31
  async function runAggregation(collectionName, pipeline, paging = {}, options = {}) {
30
32
  const findings = findForbidden(pipeline, options.allowStatsStages ? STATS_OPERATORS : []);
31
33
  if (findings.length > 0) throw new ForbiddenPipelineError(findings);
34
+ if (isFilterTooLong(options.filter)) throw new FilterTooLongError(MAX_ENCODED_FILTER_LENGTH);
32
35
  const page = paging.page ?? 1;
33
36
  const response = await collectionApi.aggregateRaw({
34
37
  collectionName,
35
38
  // the generated type says string values; the server takes any JSON. allowDiskUse is required.
36
39
  mongoAggregateRequest: { pipeline, allowDiskUse: false },
37
40
  rowsPerPage: paging.rowsPerPage,
38
- page
41
+ page,
42
+ filter: options.filter?.trim() ? options.filter : void 0
39
43
  }, requestInit(AGGREGATE_TIMEOUT_MS, options.signal));
40
44
  const value = await readJsonKeepingLongs(response);
41
45
  const unwrapped = Array.isArray(value) ? value.filter(isPlainObject).map((row) => unwrapExtendedJson(row)) : [];
@@ -48,9 +52,11 @@ export function useMongocampAggregation() {
48
52
  page: headerNumber(headers, "x-pagination-current-page") ?? page
49
53
  };
50
54
  }
55
+ async function listFieldDetails(collectionName, options = {}) {
56
+ return collectionApi.getFieldDetails({ collectionName, sampleSize: options.sampleSize, depth: options.depth }, withTimeout(REQUEST_TIMEOUT_MS));
57
+ }
51
58
  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));
59
+ return fieldPathsOf(await listFieldDetails(collectionName));
54
60
  }
55
61
  async function listDistinct(collectionName, field, limit = DEFAULT_DISTINCT_LIMIT) {
56
62
  const response = await collectionApi.distinctRaw({ collectionName, field, rowsPerPage: limit, page: 1 }, withTimeout(REQUEST_TIMEOUT_MS));
@@ -64,6 +70,7 @@ export function useMongocampAggregation() {
64
70
  return runAggregation(collectionName, [{ stage: "$sample", value: { size: clamped } }], { page: 1, rowsPerPage: clamped });
65
71
  }
66
72
  async function describeAggregationError(error) {
73
+ if (error instanceof FilterTooLongError) return { kind: "other", message: t("nuxtUiMongocamp.aggregation.errors.filterTooLong", { max: error.max }) };
67
74
  if (error instanceof ForbiddenPipelineError) {
68
75
  return { kind: "forbidden", message: t("nuxtUiMongocamp.aggregation.errors.forbidden", { operator: error.findings[0]?.operator ?? "" }) };
69
76
  }
@@ -82,5 +89,5 @@ export function useMongocampAggregation() {
82
89
  const kind = described.kind === "forbidden" ? "forbidden-access" : described.kind === "notAllowed" || described.kind === "invalid" ? "other" : described.kind;
83
90
  return { kind, message: described.message };
84
91
  }
85
- return { runAggregation, listDistinct, listFieldNames, sampleDocuments, describeAggregationError };
92
+ return { runAggregation, listDistinct, listFieldNames, listFieldDetails, sampleDocuments, describeAggregationError };
86
93
  }
@@ -0,0 +1,15 @@
1
+ export interface BulkUpdateByFilterResult {
2
+ matched: number;
3
+ modified: number;
4
+ }
5
+ /**
6
+ * Count, delete and update by the **Lucene filter** of the list — one request each (server 1.7.0): no ids are collected,
7
+ * so there is no cap, no id snapshot and nothing to chunk. An empty filter would touch the whole collection, which the
8
+ * server only does with `matchAll=true`; it is sent exactly when the filter is empty, so the caller's own confirmation
9
+ * (the typed collection name) is what guards that case. A filter the server cannot parse is answered 400 (nothing changes).
10
+ */
11
+ export declare function useMongocampBulkByFilter(): {
12
+ countDocuments: (collectionName: string, filter?: string, signal?: AbortSignal) => Promise<number>;
13
+ deleteByFilter: (collectionName: string, filter?: string, signal?: AbortSignal) => Promise<number>;
14
+ updateByFilter: (collectionName: string, filter: string | undefined, document: Record<string, unknown>, signal?: AbortSignal) => Promise<BulkUpdateByFilterResult>;
15
+ };
@@ -0,0 +1,32 @@
1
+ import { useMongocampClientApi } from "#imports";
2
+ export function useMongocampBulkByFilter() {
3
+ const { documentApi } = useMongocampClientApi();
4
+ const clean = (filter) => filter && filter.trim() !== "" ? filter : void 0;
5
+ async function countDocuments(collectionName, filter, signal) {
6
+ const response = await documentApi.countDocuments({ collectionName, filter: clean(filter) }, signal ? { signal } : void 0);
7
+ return response.count;
8
+ }
9
+ async function deleteByFilter(collectionName, filter, signal) {
10
+ const lucene = clean(filter);
11
+ const response = await documentApi.deleteMany(
12
+ { collectionName, requestBody: {}, filter: lucene, matchAll: lucene === void 0 ? true : void 0 },
13
+ signal ? { signal } : void 0
14
+ );
15
+ return response.deletedCount;
16
+ }
17
+ async function updateByFilter(collectionName, filter, document, signal) {
18
+ const lucene = clean(filter);
19
+ const response = await documentApi.updateMany(
20
+ {
21
+ collectionName,
22
+ // the generated type says string values only; the server takes any JSON value
23
+ updateRequest: { filter: {}, document },
24
+ filter: lucene,
25
+ matchAll: lucene === void 0 ? true : void 0
26
+ },
27
+ signal ? { signal } : void 0
28
+ );
29
+ return { matched: response.matchedCount, modified: response.modifiedCount };
30
+ }
31
+ return { countDocuments, deleteByFilter, updateByFilter };
32
+ }
@@ -1,85 +1,45 @@
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
1
  export interface CopyOptions {
9
2
  source: string;
10
3
  target: string;
11
4
  /** Lucene filter: copy only the documents that match. */
12
5
  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`). */
6
+ /** Create the same indexes on the new collection (the server reproduces them from the real index specifications). */
7
+ withIndexes?: boolean;
22
8
  signal?: AbortSignal;
23
9
  }
24
- export type CopyRefusal = 'target-exists' | 'too-many-documents';
10
+ export type CopyRefusal = 'target-exists';
11
+ export interface CopyResult {
12
+ /** Why nothing was copied; absent when the copy ran. */
13
+ refused?: CopyRefusal;
14
+ /** The new collection's name. */
15
+ target: string;
16
+ /** How many documents the new collection holds. */
17
+ count: number;
18
+ /** How many indexes (besides `_id_`) were created on it. */
19
+ indexes: number;
20
+ }
25
21
  export interface BackupOptions extends Omit<CopyOptions, 'target'> {
26
22
  /** The time put into the name (default: now). */
27
23
  now?: Date;
28
- /** Called with the chosen name before anything is read, so a UI can show it. */
24
+ /** Called with the chosen name before the request, so a UI can show it. */
29
25
  onTarget?: (target: string) => void;
30
26
  }
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. */
27
+ export interface RenameResult {
47
28
  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;
29
+ /** The collection's new name. */
30
+ target: string;
62
31
  }
63
32
  /**
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.
33
+ * Copy and rename a collection **inside the database** (server 1.8.1): one request, no cap, no browser memory — the server
34
+ * copies with its own checks and, with `withIndexes`, recreates the indexes from the real index specifications (compound
35
+ * order, partial filter, text weights, collation …). Grants, the schema and GridFS files are not copied; the copy is a
36
+ * snapshot taken by the server. A name the server refuses (a target that exists: 409, a reserved one: 400) is thrown, except
37
+ * "target exists", which is returned as `refused` so a dialog can offer another name.
68
38
  */
69
39
  export declare function useMongocampCollectionCopy(): {
70
40
  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
- }>;
41
+ backupCollection: (options: BackupOptions) => Promise<CopyResult>;
42
+ renameCollection: (source: string, target: string, signal?: AbortSignal) => Promise<RenameResult>;
82
43
  listCollectionNames: () => Promise<string[]>;
83
- countDocuments: (collection: string, filter?: string) => Promise<number>;
84
- collectionCount: (collection: string) => Promise<number>;
44
+ countDocuments: (collectionName: string, filter?: string, signal?: AbortSignal) => Promise<number>;
85
45
  };
@@ -1,85 +1,27 @@
1
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;
2
+ import { backupName, canCopyCollection, CollectionNotCopyableError } from "../utils/collectionCopy.js";
3
+ import { useMongocampBulkByFilter } from "./useMongocampBulkByFilter.js";
4
+ function isTargetExists(error) {
5
+ return error?.response?.status === 409;
6
+ }
10
7
  export function useMongocampCollectionCopy() {
11
- const { collectionApi, documentApi } = useMongocampClientApi();
12
- const { fetchAllDocuments } = useMongocampFetchAll();
13
- const { importRows } = useMongocampImport();
14
- const { listIndexes, createIndex, createTextIndex } = useMongocampIndex();
8
+ const { collectionApi } = useMongocampClientApi();
9
+ const { countDocuments } = useMongocampBulkByFilter();
15
10
  async function listCollectionNames() {
16
11
  return await collectionApi.listCollections();
17
12
  }
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
13
  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
- }
14
+ const { source, target, filter, withIndexes, signal } = options;
15
+ try {
16
+ const response = await collectionApi.copyCollection({
17
+ collectionName: source,
18
+ copyRequest: { target, filter: filter?.trim() ? filter : void 0, withIndexes: withIndexes ?? false }
19
+ }, signal ? { signal } : void 0);
20
+ return { target: response.name, count: response.count, indexes: response.indexes };
21
+ } catch (error) {
22
+ if (isTargetExists(error)) return { refused: "target-exists", target, count: 0, indexes: 0 };
23
+ throw error;
81
24
  }
82
- return result;
83
25
  }
84
26
  async function backupCollection(options) {
85
27
  if (!canCopyCollection(options.source)) throw new CollectionNotCopyableError(options.source);
@@ -88,18 +30,19 @@ export function useMongocampCollectionCopy() {
88
30
  for (let attempt = 0; attempt < 3; attempt++) {
89
31
  const target = backupName(options.source, await listCollectionNames(), now);
90
32
  onTarget?.(target);
91
- result = { ...await copyCollection({ ...copy, target }), target };
33
+ result = await copyCollection({ ...copy, target });
92
34
  if (result.refused !== "target-exists") break;
93
35
  }
94
36
  return result;
95
37
  }
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 };
38
+ async function renameCollection(source, target, signal) {
39
+ try {
40
+ const response = await collectionApi.renameCollection({ collectionName: source, renameRequest: { target } }, signal ? { signal } : void 0);
41
+ return { target: response.name };
42
+ } catch (error) {
43
+ if (isTargetExists(error)) return { refused: "target-exists", target };
44
+ throw error;
45
+ }
103
46
  }
104
- return { copyCollection, copyIndexes, backupCollection, retryBatches, listCollectionNames, countDocuments, collectionCount };
47
+ return { copyCollection, backupCollection, renameCollection, listCollectionNames, countDocuments };
105
48
  }
@@ -1,46 +1,52 @@
1
1
  import type { ExportFormat } from '../utils/exportDocuments.js';
2
- import type { FetchAllProgress } from '../utils/pagedFetch.js';
3
2
  export interface ExportCollectionOptions {
4
3
  collection: string;
5
4
  format: ExportFormat;
6
- /** Lucene filter: export only the documents that match (the current filter of a table). */
5
+ /** Lucene filter: export only the documents that match (the current filter of a table). It travels in the URL: over ~1 800 encoded characters it throws `FilterTooLongError`. */
7
6
  filter?: string;
8
7
  sort?: string[];
9
- /** Limit the fields; `columns` also orders a CSV. */
8
+ /** Limit the fields; for a CSV they are also its columns, in this order (default: the fields of the first 1 000 documents). */
10
9
  projection?: string[];
11
- /** CSV columns in this order; default: the keys of all rows, `_id` first. */
10
+ /** CSV columns in this order — the same as `projection`, kept for the old name. */
12
11
  columns?: string[];
13
- /** Stop after this many documents (default 50 000) and report `truncated`. */
12
+ /** Stop after this many documents (`limit`); default: all. */
14
13
  maxRows?: number;
15
- pageSize?: number;
16
- onProgress?: (progress: FetchAllProgress) => void;
14
+ /** How many documents the caller expects (the count of the filter): a file with fewer is reported as `incomplete`. */
15
+ expected?: number;
16
+ /** After every chunk of the stream. */
17
+ onProgress?: (progress: ExportProgress) => void;
17
18
  /** Aborting rejects with an `AbortError`; nothing is downloaded. */
18
19
  signal?: AbortSignal;
19
20
  /** File name; default `<collection>-<yyyymmdd>-<hhmm>.<format>`. */
20
21
  filename?: string;
21
- /** Hand the file to the browser as a download (default `true`). `false` only returns the text. */
22
+ /** Hand the file to the browser as a download (default `true`). `false` only returns the blob. */
22
23
  download?: boolean;
23
24
  }
25
+ export interface ExportProgress {
26
+ /** Bytes received so far. */
27
+ bytes: number;
28
+ /** Lines received so far (NDJSON: documents; CSV: documents + the header, unless a value holds a line break). */
29
+ lines: number;
30
+ }
24
31
  export interface ExportResult {
25
- /** The file's text. */
26
- content: string;
32
+ blob: Blob;
27
33
  filename: string;
28
34
  mimeType: string;
29
35
  format: ExportFormat;
30
- /** Documents written. */
31
- rowCount: number;
32
- /** The server's count when the last page was read. */
33
- total?: number;
34
- /** More documents exist than were exported: the cap was hit. **The file is incomplete** — tell the user. */
35
- truncated: boolean;
36
- /** Documents were added or removed while reading; the file may miss or repeat one. */
37
- totalChanged: boolean;
36
+ bytes: number;
37
+ /** Documents in the file: exact for NDJSON (one per line); for JSON and CSV the expected count when the file is complete. */
38
+ documents?: number;
39
+ /**
40
+ * The file is certainly **cut short**: the server ends a stream that fails midway with a normal `200`, so the file is checked
41
+ * — JSON must end with `]`, NDJSON and CSV must hold at least the expected number of documents. Tell the user.
42
+ */
43
+ incomplete: boolean;
38
44
  }
39
45
  /**
40
46
  * Exports a whole collection, or every document matching a filter, as JSON, NDJSON or CSV — not just the rows on screen.
41
- * It reads every page (`useMongocampFetchAll`: pages of 500, progress, abort) and writes the file in the browser. The rows
42
- * are written as the table shows them, except that an integer beyond 2^53 keeps every digit (bare number in JSON, digits
43
- * in CSV). Everything is held in memory: with the default cap of 50 000 documents that is tens of megabytes.
47
+ * The server streams the file (`GET …/documents/export`, server 1.8.1): there is no document cap and the browser never parses
48
+ * a document. Values are written as plain JSON, so an integer beyond 2^53 keeps every digit as the text the server wrote.
49
+ * The file ends up in a `Blob` (the browser may keep it on disk) and is handed to the browser as a download.
44
50
  */
45
51
  export declare function useMongocampExportAll(): {
46
52
  exportCollection: (options: ExportCollectionOptions) => Promise<ExportResult>;
@@ -1,27 +1,57 @@
1
- import { downloadTextFile } from "../utils/exportRows.js";
2
- import { DEFAULT_EXPORT_MAX_ROWS, EXPORT_MIME_TYPES, exportFilename, formatDocuments, toExportRow } from "../utils/exportDocuments.js";
3
- import { useMongocampFetchAll } from "./useMongocampFetchAll.js";
1
+ import { useMongocampClientApi } from "#imports";
2
+ import { downloadBlob } from "../utils/exportRows.js";
3
+ import { EXPORT_MIME_TYPES, exportFilename } from "../utils/exportDocuments.js";
4
+ import { FilterTooLongError } from "../utils/aggregationErrors.js";
5
+ import { isFilterTooLong, MAX_ENCODED_FILTER_LENGTH } from "../utils/requestLimits.js";
6
+ function countingStream(onProgress) {
7
+ const state = { bytes: 0, newlines: 0, last: 0 };
8
+ const stream = new TransformStream({
9
+ transform(chunk, controller) {
10
+ state.bytes += chunk.length;
11
+ for (const byte of chunk) if (byte === 10) state.newlines++;
12
+ if (chunk.length > 0) state.last = chunk[chunk.length - 1];
13
+ onProgress?.({ bytes: state.bytes, lines: state.newlines + (state.last !== 10 && state.bytes > 0 ? 1 : 0) });
14
+ controller.enqueue(chunk);
15
+ }
16
+ });
17
+ return { stream, state };
18
+ }
4
19
  export function useMongocampExportAll() {
5
- const { fetchAllDocuments } = useMongocampFetchAll();
20
+ const { documentApi } = useMongocampClientApi();
6
21
  async function exportCollection(options) {
7
- const { collection, format, columns, download = true } = options;
8
- const fetched = await fetchAllDocuments(collection, {
9
- filter: options.filter,
10
- sort: options.sort,
11
- projection: options.projection,
12
- pageSize: options.pageSize,
13
- maxRows: options.maxRows ?? DEFAULT_EXPORT_MAX_ROWS,
14
- onProgress: options.onProgress,
15
- signal: options.signal,
16
- // skip/limit paging can repeat a document when the collection changes during the read
17
- keyOf: (row) => String(row._id)
18
- });
19
- const rows = fetched.rows.map(toExportRow);
20
- const content = formatDocuments(rows, format, { columns });
21
- const filename = options.filename ?? exportFilename(collection, format);
22
+ const { collection, format, download = true } = options;
23
+ if (isFilterTooLong(options.filter)) throw new FilterTooLongError(MAX_ENCODED_FILTER_LENGTH);
24
+ const projection = options.projection?.length ? options.projection : options.columns?.length ? options.columns : void 0;
25
+ const response = await documentApi.exportDocumentsRaw({
26
+ collectionName: collection,
27
+ format,
28
+ filter: options.filter?.trim() ? options.filter : void 0,
29
+ sort: options.sort?.length ? options.sort : void 0,
30
+ projection,
31
+ limit: options.maxRows
32
+ }, options.signal ? { signal: options.signal } : void 0);
22
33
  const mimeType = EXPORT_MIME_TYPES[format];
23
- if (download) downloadTextFile(filename, content, mimeType);
24
- return { content, filename, mimeType, format, rowCount: rows.length, total: fetched.total, truncated: fetched.truncated, totalChanged: fetched.totalChanged };
34
+ const { stream, state } = countingStream(options.onProgress);
35
+ const body = response.raw.body;
36
+ const blob = body ? await new Response(body.pipeThrough(stream), { headers: { "content-type": mimeType } }).blob() : await response.raw.blob();
37
+ const bytes = body ? state.bytes : blob.size;
38
+ const lines = body ? state.newlines + (state.last !== 10 && state.bytes > 0 ? 1 : 0) : 0;
39
+ const wanted = options.expected === void 0 ? void 0 : Math.min(options.expected, options.maxRows ?? Infinity);
40
+ let incomplete;
41
+ let documents;
42
+ if (format === "json") {
43
+ incomplete = !(await blob.slice(Math.max(0, bytes - 8)).text()).trimEnd().endsWith("]");
44
+ if (!incomplete) documents = wanted;
45
+ } else if (format === "ndjson") {
46
+ documents = lines;
47
+ incomplete = wanted !== void 0 && lines < wanted;
48
+ } else {
49
+ incomplete = wanted !== void 0 && lines - 1 < wanted;
50
+ if (!incomplete) documents = wanted;
51
+ }
52
+ const filename = options.filename ?? exportFilename(collection, format);
53
+ if (download) downloadBlob(filename, blob);
54
+ return { blob, filename, mimeType, format, bytes, documents, incomplete };
25
55
  }
26
56
  return { exportCollection };
27
57
  }
@@ -1,6 +1,7 @@
1
+ import type { TypeHints } from '../utils/bsonTypes.js';
1
2
  export interface UnwrapOptions {
2
3
  /** Keep a `$numberLong` outside the safe-integer range as its exact digit string (default `true`). `false` gives the rounded number, e.g. for type inference. */
3
4
  exactLongs?: boolean;
4
5
  }
5
6
  export declare function unwrapExtendedJson(value: unknown, options?: UnwrapOptions): unknown;
6
- export declare function wrapExtendedJson(formData: Record<string, unknown>, originalDoc?: Record<string, unknown>): Record<string, unknown>;
7
+ export declare function wrapExtendedJson(formData: Record<string, unknown>, originalDoc?: Record<string, unknown>, hints?: TypeHints): Record<string, unknown>;