@sfxcode/nuxt-mongocamp-server 2.1.0 → 2.3.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 (80) hide show
  1. package/README.md +71 -19
  2. package/dist/module.d.mts +16 -0
  3. package/dist/module.json +1 -1
  4. package/dist/module.mjs +103 -11
  5. package/dist/runtime/api/.openapi-generator/FILES +24 -2
  6. package/dist/runtime/api/apis/CollectionApi.d.ts +137 -0
  7. package/dist/runtime/api/apis/CollectionApi.js +213 -0
  8. package/dist/runtime/api/apis/DocumentApi.d.ts +225 -8
  9. package/dist/runtime/api/apis/DocumentApi.js +364 -5
  10. package/dist/runtime/api/docs/AuditEntry.md +52 -0
  11. package/dist/runtime/api/docs/CollectionApi.md +272 -2
  12. package/dist/runtime/api/docs/CollectionDeclaration.md +52 -0
  13. package/dist/runtime/api/docs/CollectionDeclarationAudit.md +34 -0
  14. package/dist/runtime/api/docs/CollectionDeclarationOwner.md +36 -0
  15. package/dist/runtime/api/docs/CollectionDeclarationSoftDelete.md +36 -0
  16. package/dist/runtime/api/docs/CollectionDeclarationTimestamps.md +40 -0
  17. package/dist/runtime/api/docs/CollectionDeclarationVersioned.md +38 -0
  18. package/dist/runtime/api/docs/CountRequest.md +34 -0
  19. package/dist/runtime/api/docs/DocumentApi.md +467 -12
  20. package/dist/runtime/api/docs/ErrorDescription.md +4 -0
  21. package/dist/runtime/api/docs/ExportRequest.md +40 -0
  22. package/dist/runtime/api/docs/MongoAggregateRequest.md +2 -0
  23. package/dist/runtime/api/docs/SettingsResponse.md +0 -6
  24. package/dist/runtime/api/docs/SuggestedValidator.md +40 -0
  25. package/dist/runtime/api/docs/{UpdateRequest.md → UpdateManyRequest.md} +4 -4
  26. package/dist/runtime/api/docs/ValidationIssue.md +36 -0
  27. package/dist/runtime/api/models/AuditEntry.d.ts +88 -0
  28. package/dist/runtime/api/models/AuditEntry.js +56 -0
  29. package/dist/runtime/api/models/CollectionDeclaration.d.ts +80 -0
  30. package/dist/runtime/api/models/CollectionDeclaration.js +73 -0
  31. package/dist/runtime/api/models/CollectionDeclarationAudit.d.ts +30 -0
  32. package/dist/runtime/api/models/CollectionDeclarationAudit.js +26 -0
  33. package/dist/runtime/api/models/CollectionDeclarationOwner.d.ts +43 -0
  34. package/dist/runtime/api/models/CollectionDeclarationOwner.js +34 -0
  35. package/dist/runtime/api/models/CollectionDeclarationSoftDelete.d.ts +34 -0
  36. package/dist/runtime/api/models/CollectionDeclarationSoftDelete.js +28 -0
  37. package/dist/runtime/api/models/CollectionDeclarationTimestamps.d.ts +42 -0
  38. package/dist/runtime/api/models/CollectionDeclarationTimestamps.js +33 -0
  39. package/dist/runtime/api/models/CollectionDeclarationVersioned.d.ts +46 -0
  40. package/dist/runtime/api/models/CollectionDeclarationVersioned.js +36 -0
  41. package/dist/runtime/api/models/CountRequest.d.ts +30 -0
  42. package/dist/runtime/api/models/CountRequest.js +25 -0
  43. package/dist/runtime/api/models/ErrorDescription.d.ts +11 -0
  44. package/dist/runtime/api/models/ErrorDescription.js +10 -2
  45. package/dist/runtime/api/models/ExportRequest.d.ts +42 -0
  46. package/dist/runtime/api/models/ExportRequest.js +31 -0
  47. package/dist/runtime/api/models/Grant.d.ts +10 -1
  48. package/dist/runtime/api/models/Grant.js +5 -0
  49. package/dist/runtime/api/models/MongoAggregateRequest.d.ts +4 -0
  50. package/dist/runtime/api/models/MongoAggregateRequest.js +4 -2
  51. package/dist/runtime/api/models/SettingsResponse.d.ts +0 -14
  52. package/dist/runtime/api/models/SettingsResponse.js +0 -6
  53. package/dist/runtime/api/models/SuggestedValidator.d.ts +44 -0
  54. package/dist/runtime/api/models/SuggestedValidator.js +35 -0
  55. package/dist/runtime/api/models/UpdateManyRequest.d.ts +38 -0
  56. package/dist/runtime/api/models/{UpdateRequest.js → UpdateManyRequest.js} +7 -7
  57. package/dist/runtime/api/models/ValidationIssue.d.ts +34 -0
  58. package/dist/runtime/api/models/ValidationIssue.js +29 -0
  59. package/dist/runtime/api/models/index.d.ts +12 -1
  60. package/dist/runtime/api/models/index.js +12 -1
  61. package/dist/runtime/composables/mongocampApiCollection.d.ts +14 -15
  62. package/dist/runtime/composables/mongocampApiCollection.js +4 -1
  63. package/dist/runtime/composables/mongocampCollection.d.ts +106 -0
  64. package/dist/runtime/composables/mongocampCollection.js +200 -0
  65. package/dist/runtime/composables/mongocampLive.d.ts +33 -0
  66. package/dist/runtime/composables/mongocampLive.js +152 -0
  67. package/dist/runtime/composables/mongocampSearch.d.ts +12 -9
  68. package/dist/runtime/server/mongocamp/core.d.ts +2 -0
  69. package/dist/runtime/server/mongocamp/core.js +8 -1
  70. package/dist/runtime/server/mongocamp/plugin.d.ts +5 -1
  71. package/dist/runtime/server/mongocamp/plugin.js +21 -1
  72. package/dist/runtime/types/collections.d.ts +20 -0
  73. package/dist/runtime/types/collections.js +0 -0
  74. package/dist/runtime/utils/sse.d.ts +10 -0
  75. package/dist/runtime/utils/sse.js +33 -0
  76. package/dist/runtime/utils/toMongocampError.d.ts +7 -0
  77. package/dist/runtime/utils/toMongocampError.js +18 -1
  78. package/dist/types.d.mts +6 -0
  79. package/package.json +4 -3
  80. package/dist/runtime/api/models/UpdateRequest.d.ts +0 -38
@@ -0,0 +1,29 @@
1
+ export function instanceOfValidationIssue(value) {
2
+ if (!("path" in value) || value["path"] === void 0) return false;
3
+ if (!("message" in value) || value["message"] === void 0) return false;
4
+ return true;
5
+ }
6
+ export function ValidationIssueFromJSON(json) {
7
+ return ValidationIssueFromJSONTyped(json, false);
8
+ }
9
+ export function ValidationIssueFromJSONTyped(json, ignoreDiscriminator) {
10
+ if (json == null) {
11
+ return json;
12
+ }
13
+ return {
14
+ "path": json["path"],
15
+ "message": json["message"]
16
+ };
17
+ }
18
+ export function ValidationIssueToJSON(json) {
19
+ return ValidationIssueToJSONTyped(json, false);
20
+ }
21
+ export function ValidationIssueToJSONTyped(value, ignoreDiscriminator = false) {
22
+ if (value == null) {
23
+ return value;
24
+ }
25
+ return {
26
+ "path": value["path"],
27
+ "message": value["message"]
28
+ };
29
+ }
@@ -1,9 +1,16 @@
1
+ export * from './AuditEntry.js';
1
2
  export * from './BucketInformation.js';
2
3
  export * from './Capabilities.js';
3
4
  export * from './CapabilityLimits.js';
4
5
  export * from './ClusterInformation.js';
5
6
  export * from './ClusterMemberInformation.js';
6
7
  export * from './CollectionCollation.js';
8
+ export * from './CollectionDeclaration.js';
9
+ export * from './CollectionDeclarationAudit.js';
10
+ export * from './CollectionDeclarationOwner.js';
11
+ export * from './CollectionDeclarationSoftDelete.js';
12
+ export * from './CollectionDeclarationTimestamps.js';
13
+ export * from './CollectionDeclarationVersioned.js';
7
14
  export * from './CollectionOptions.js';
8
15
  export * from './CollectionPermission.js';
9
16
  export * from './CollectionStatus.js';
@@ -11,11 +18,13 @@ export * from './CollectionSummary.js';
11
18
  export * from './ConnectionStats.js';
12
19
  export * from './CopyRequest.js';
13
20
  export * from './CopyResponse.js';
21
+ export * from './CountRequest.js';
14
22
  export * from './CountResponse.js';
15
23
  export * from './CreateCollectionResponse.js';
16
24
  export * from './DatabaseInfo.js';
17
25
  export * from './DeleteResponse.js';
18
26
  export * from './ErrorDescription.js';
27
+ export * from './ExportRequest.js';
19
28
  export * from './FieldInfo.js';
20
29
  export * from './FieldTypeCount.js';
21
30
  export * from './FileInformation.js';
@@ -55,12 +64,14 @@ export * from './SchemaAnalysisField.js';
55
64
  export * from './SchemaAnalysisFieldType.js';
56
65
  export * from './SearchRequest.js';
57
66
  export * from './SettingsResponse.js';
67
+ export * from './SuggestedValidator.js';
58
68
  export * from './SystemInfo.js';
59
69
  export * from './SystemStats.js';
60
70
  export * from './UpdateFileInformationRequest.js';
61
- export * from './UpdateRequest.js';
71
+ export * from './UpdateManyRequest.js';
62
72
  export * from './UpdateResponse.js';
63
73
  export * from './UpdateRoleRequest.js';
64
74
  export * from './UserInformation.js';
65
75
  export * from './UserProfile.js';
76
+ export * from './ValidationIssue.js';
66
77
  export * from './Version.js';
@@ -1,9 +1,16 @@
1
+ export * from "./AuditEntry.js";
1
2
  export * from "./BucketInformation.js";
2
3
  export * from "./Capabilities.js";
3
4
  export * from "./CapabilityLimits.js";
4
5
  export * from "./ClusterInformation.js";
5
6
  export * from "./ClusterMemberInformation.js";
6
7
  export * from "./CollectionCollation.js";
8
+ export * from "./CollectionDeclaration.js";
9
+ export * from "./CollectionDeclarationAudit.js";
10
+ export * from "./CollectionDeclarationOwner.js";
11
+ export * from "./CollectionDeclarationSoftDelete.js";
12
+ export * from "./CollectionDeclarationTimestamps.js";
13
+ export * from "./CollectionDeclarationVersioned.js";
7
14
  export * from "./CollectionOptions.js";
8
15
  export * from "./CollectionPermission.js";
9
16
  export * from "./CollectionStatus.js";
@@ -11,11 +18,13 @@ export * from "./CollectionSummary.js";
11
18
  export * from "./ConnectionStats.js";
12
19
  export * from "./CopyRequest.js";
13
20
  export * from "./CopyResponse.js";
21
+ export * from "./CountRequest.js";
14
22
  export * from "./CountResponse.js";
15
23
  export * from "./CreateCollectionResponse.js";
16
24
  export * from "./DatabaseInfo.js";
17
25
  export * from "./DeleteResponse.js";
18
26
  export * from "./ErrorDescription.js";
27
+ export * from "./ExportRequest.js";
19
28
  export * from "./FieldInfo.js";
20
29
  export * from "./FieldTypeCount.js";
21
30
  export * from "./FileInformation.js";
@@ -55,12 +64,14 @@ export * from "./SchemaAnalysisField.js";
55
64
  export * from "./SchemaAnalysisFieldType.js";
56
65
  export * from "./SearchRequest.js";
57
66
  export * from "./SettingsResponse.js";
67
+ export * from "./SuggestedValidator.js";
58
68
  export * from "./SystemInfo.js";
59
69
  export * from "./SystemStats.js";
60
70
  export * from "./UpdateFileInformationRequest.js";
61
- export * from "./UpdateRequest.js";
71
+ export * from "./UpdateManyRequest.js";
62
72
  export * from "./UpdateResponse.js";
63
73
  export * from "./UpdateRoleRequest.js";
64
74
  export * from "./UserInformation.js";
65
75
  export * from "./UserProfile.js";
76
+ export * from "./ValidationIssue.js";
66
77
  export * from "./Version.js";
@@ -1,26 +1,25 @@
1
1
  import type { MongoAggregateRequest } from '../api/index.js';
2
+ /**
3
+ * The collection with the generated client, documents as the server sends them. For typed and decoded documents use
4
+ * `useMongocampCollection(name)` (2.3.0).
5
+ */
2
6
  export declare function useMongocampApiCollection(collectionName: string): {
3
- insert: (document: {
4
- [key: string]: string;
5
- }) => Promise<import("../api/index.js").InsertResponse>;
6
- insertMany: (documents: Array<{
7
- [key: string]: string;
8
- }>) => Promise<import("../api/index.js").InsertResponse>;
9
- update: (documentId: string, document: {
10
- [key: string]: string;
11
- }) => Promise<import("../api/index.js").UpdateResponse>;
12
- updatePartial: (documentId: string, document: {
13
- [key: string]: string;
14
- }) => Promise<import("../api/index.js").UpdateResponse>;
7
+ insert: (document: Record<string, unknown>) => Promise<import("../api/index.js").InsertResponse>;
8
+ insertMany: (documents: Array<Record<string, unknown>>) => Promise<import("../api/index.js").InsertResponse>;
9
+ update: (documentId: string, document: Record<string, unknown>) => Promise<import("../api/index.js").UpdateResponse>;
10
+ updatePartial: (documentId: string, document: Record<string, unknown>) => Promise<import("../api/index.js").UpdateResponse>;
15
11
  remove: (documentId: string) => Promise<import("../api/index.js").DeleteResponse>;
16
- removeMany: (query: {
17
- [key: string]: string;
18
- }) => Promise<import("../api/index.js").DeleteResponse>;
12
+ removeMany: (query: Record<string, unknown>) => Promise<import("../api/index.js").DeleteResponse>;
19
13
  aggregate: (mongoAggregateRequest: MongoAggregateRequest, rowsPerPage?: number, page?: number) => Promise<{
20
14
  [key: string]: any;
21
15
  }[]>;
22
16
  information: (includeDetails?: boolean) => Promise<import("../api/index.js").CollectionStatus>;
23
17
  schemaAnalysis: () => Promise<import("../api/index.js").SchemaAnalysis>;
18
+ suggestValidator: (options?: {
19
+ sampleSize?: number;
20
+ depth?: number;
21
+ requiredThreshold?: number;
22
+ }) => Promise<import("../api/index.js").SuggestedValidator>;
24
23
  distinct: (field: string) => Promise<any[]>;
25
24
  clear: () => Promise<import("../api/index.js").JsonValueBoolean>;
26
25
  };
@@ -30,11 +30,14 @@ export function useMongocampApiCollection(collectionName) {
30
30
  function schemaAnalysis() {
31
31
  return collectionApi.getSchemaAnalysis({ collectionName });
32
32
  }
33
+ function suggestValidator(options = {}) {
34
+ return collectionApi.getSuggestedValidator({ collectionName, ...options });
35
+ }
33
36
  function distinct(field) {
34
37
  return collectionApi.distinct({ collectionName, field });
35
38
  }
36
39
  function clear() {
37
40
  return collectionApi.clearCollection({ collectionName });
38
41
  }
39
- return { insert, insertMany, update, updatePartial, remove, removeMany, aggregate, information, schemaAnalysis, distinct, clear };
42
+ return { insert, insertMany, update, updatePartial, remove, removeMany, aggregate, information, schemaAnalysis, suggestValidator, distinct, clear };
40
43
  }
@@ -0,0 +1,106 @@
1
+ import type { Ref } from 'vue';
2
+ import type { DeleteResponse, InsertResponse, UpdateResponse } from '../api/index.js';
3
+ import type { MongocampCollectionName, MongocampDocument, MongocampDocumentInput } from '../types/collections.js';
4
+ import type { MongocampError } from '../utils/toMongocampError.js';
5
+ /**
6
+ * The documents of one collection with their types (2.3.0): `useMongocampCollection('orders')` for a declared collection
7
+ * (`server/mongocamp/orders.ts`, typed by its schema), `useMongocampCollection<Order>('orders')` for any other. The documents are decoded
8
+ * from Extended JSON (`ObjectId`, `Date`, `Decimal128`, ... as values) and encoded for the requests; a failed request throws a
9
+ * `MongocampRequestError` with status, message and, for a document that is not valid, the `issues` of its fields.
10
+ */
11
+ /**
12
+ * An error of a request: an `Error` with the status and the fields of the error response (`issues` for documents that are not valid).
13
+ * `isConflict` (2.4.0): a change based on an outdated version; `current` is the stored document then (decoded), to show or merge.
14
+ */
15
+ export type MongocampRequestError = Error & Omit<MongocampError, 'current'> & {
16
+ isConflict: boolean;
17
+ current?: Record<string, unknown>;
18
+ };
19
+ export interface CollectionFindOptions {
20
+ /** A Lucene filter (`status:open AND qty:[1 TO 5]`). */
21
+ filter?: string;
22
+ /** Fields to sort by, `-name` for descending. */
23
+ sort?: string[];
24
+ /** Fields to read. */
25
+ projection?: string[];
26
+ page?: number;
27
+ rowsPerPage?: number;
28
+ /** Wildcards of the filter ignore the case. */
29
+ filterCaseInsensitive?: boolean;
30
+ /** Soft-deleted documents too (collections declared with `softDelete`, administrators of the collection only). */
31
+ withDeleted?: boolean;
32
+ }
33
+ export interface UpdateOptions {
34
+ /** On a version conflict, apply the changes once more to the stored document (its version) instead of failing. */
35
+ retryOnConflict?: boolean;
36
+ }
37
+ export interface CollectionPage<T> {
38
+ documents: T[];
39
+ page: number;
40
+ rowsPerPage: number;
41
+ /** The number of matching documents and pages, from the pagination headers (absent when the server does not count). */
42
+ countRows?: number;
43
+ countPages?: number;
44
+ }
45
+ /** One change of a document from the audit records (collections declared with `audit`, 2.4.0); before and after decoded and typed. */
46
+ export interface AuditEntry<T> {
47
+ operation: 'insert' | 'replace' | 'update' | 'delete' | 'softDelete' | 'restore';
48
+ user: string;
49
+ at: Date;
50
+ documentId?: unknown;
51
+ before?: T;
52
+ after?: T;
53
+ }
54
+ /** The id of a document: the text of the path, an `ObjectId` or a document with `_id`. */
55
+ export type DocumentIdentity = string | number | {
56
+ toHexString: () => string;
57
+ } | {
58
+ _id: unknown;
59
+ };
60
+ export interface TypedCollection<T, I = T> {
61
+ readonly name: string;
62
+ find: (options?: CollectionFindOptions) => Promise<T[]>;
63
+ findPage: (options?: CollectionFindOptions) => Promise<CollectionPage<T>>;
64
+ /** The document, `null` when there is none with the id. */
65
+ findById: (id: DocumentIdentity) => Promise<T | null>;
66
+ /** Inserts a document; fields the server writes (timestamps, owner, version) and protected fields are left out. */
67
+ insert: (document: I) => Promise<InsertResponse>;
68
+ insertMany: (documents: I[]) => Promise<InsertResponse>;
69
+ /**
70
+ * Replaces the whole document. Given the document that was read (not only its id), its version goes with the request: a change of
71
+ * someone else in the meantime answers 409 (`isConflict`) instead of being overwritten.
72
+ */
73
+ replace: (target: DocumentIdentity, document: I, options?: UpdateOptions) => Promise<UpdateResponse>;
74
+ /** Changes the given fields (`$set`); with the document that was read, its version goes with the request (see `replace`). */
75
+ update: (target: DocumentIdentity, changes: Partial<T>, options?: UpdateOptions) => Promise<UpdateResponse>;
76
+ remove: (id: DocumentIdentity) => Promise<DeleteResponse>;
77
+ /** Brings a soft-deleted document back (collections declared with `softDelete`). */
78
+ restore: (id: DocumentIdentity) => Promise<UpdateResponse>;
79
+ /**
80
+ * Whether the session user owns the document (collections declared with `owner`), for edit buttons. Reactive: false until the declaration
81
+ * is loaded (once per collection), then the answer.
82
+ */
83
+ isMine: (document: T | null | undefined) => boolean;
84
+ /** The pages of a find as reactive state. */
85
+ paginated: (options?: Omit<CollectionFindOptions, 'page'>) => PaginatedCollection<T>;
86
+ /** The changes of a document, newest first (collections declared with `audit`). */
87
+ history: (id: DocumentIdentity, options?: {
88
+ page?: number;
89
+ rowsPerPage?: number;
90
+ }) => Promise<AuditEntry<T>[]>;
91
+ }
92
+ export interface PaginatedCollection<T> {
93
+ documents: Ref<T[]>;
94
+ page: Ref<number>;
95
+ rowsPerPage: Ref<number>;
96
+ countRows: Ref<number | undefined>;
97
+ countPages: Ref<number | undefined>;
98
+ pending: Ref<boolean>;
99
+ error: Ref<MongocampRequestError | null>;
100
+ load: () => Promise<void>;
101
+ goToPage: (page: number) => Promise<void>;
102
+ nextPage: () => Promise<void>;
103
+ previousPage: () => Promise<void>;
104
+ }
105
+ export declare function useMongocampCollection<N extends MongocampCollectionName>(name: N): TypedCollection<MongocampDocument<N>, MongocampDocumentInput<N>>;
106
+ export declare function useMongocampCollection<T extends object = Record<string, unknown>, I = T>(name: string): TypedCollection<T, I>;
@@ -0,0 +1,200 @@
1
+ import { ref } from "vue";
2
+ import { ResponseError } from "../api/index.js";
3
+ import { documentId, fromExtendedJson, toExtendedJson } from "../utils/extendedJson.js";
4
+ import { toMongocampError } from "../utils/toMongocampError.js";
5
+ import { useMongocampApi } from "./mongocampApi.js";
6
+ import { useMongocampStorage } from "./mongocampStorage.js";
7
+ import { useMongocampUrl } from "./mongocampUrl.js";
8
+ import { useRuntimeConfig } from "#app";
9
+ const VersionConflict = 4092;
10
+ async function requestError(error) {
11
+ const { current, ...described } = await toMongocampError(error);
12
+ return Object.assign(new Error(described.message, { cause: error }), described, {
13
+ isConflict: described.status === 409 && described.code === VersionConflict,
14
+ ...current !== void 0 ? { current: fromExtendedJson(current) } : {}
15
+ });
16
+ }
17
+ const declarations = /* @__PURE__ */ new Map();
18
+ function getPath(document, path) {
19
+ let current = document;
20
+ for (const segment of path.split(".")) {
21
+ if (current === null || typeof current !== "object" || !(segment in current)) {
22
+ return void 0;
23
+ }
24
+ current = current[segment];
25
+ }
26
+ return current;
27
+ }
28
+ function withoutPaths(document, paths) {
29
+ const copy = { ...document };
30
+ for (const path of paths) {
31
+ const segments = path.split(".");
32
+ let current = copy;
33
+ for (const segment of segments.slice(0, -1)) {
34
+ const next = current[segment];
35
+ if (next === null || typeof next !== "object" || Array.isArray(next) || next instanceof Date) {
36
+ current = {};
37
+ break;
38
+ }
39
+ current[segment] = { ...next };
40
+ current = current[segment];
41
+ }
42
+ Reflect.deleteProperty(current, segments.at(-1));
43
+ }
44
+ return copy;
45
+ }
46
+ function isDocument(target) {
47
+ return target !== null && typeof target === "object" && "_id" in target && typeof target.toHexString !== "function";
48
+ }
49
+ function headerNumber(headers, name) {
50
+ const value = headers.get(name);
51
+ const number = value === null || value.trim() === "" ? Number.NaN : Number(value);
52
+ return Number.isFinite(number) ? number : void 0;
53
+ }
54
+ export function useMongocampCollection(name) {
55
+ const { documentApi, collectionApi } = useMongocampApi();
56
+ const config = useRuntimeConfig();
57
+ const session = useMongocampStorage();
58
+ const defaultRows = () => config.public.mongocamp?.paginationSize;
59
+ const declarationKey = `${useMongocampUrl()}|${name}`;
60
+ const declaration = declarations.get(declarationKey) ?? ref(void 0);
61
+ declarations.set(declarationKey, declaration);
62
+ let loading;
63
+ const loadDeclaration = () => {
64
+ if (declaration.value !== void 0) {
65
+ return Promise.resolve(declaration.value);
66
+ }
67
+ loading ??= Promise.resolve().then(() => collectionApi.getCollectionDeclaration({ collectionName: name })).catch(() => null).then((loaded) => {
68
+ declaration.value = loaded;
69
+ return loaded;
70
+ });
71
+ return loading;
72
+ };
73
+ const writable = async (document) => {
74
+ const loaded = await loadDeclaration();
75
+ return loaded === null ? { ...document } : withoutPaths(document, [...loaded.systemFields, ...loaded.protectedFields]);
76
+ };
77
+ const versionOf = async (target) => {
78
+ const loaded = await loadDeclaration();
79
+ if (loaded?.versioned === void 0 || !isDocument(target)) {
80
+ return {};
81
+ }
82
+ const version = getPath(target, loaded.versioned.field);
83
+ return version === void 0 ? {} : { [loaded.versioned.field]: version };
84
+ };
85
+ const withRetry = async (target, options, write) => {
86
+ try {
87
+ return await write(target);
88
+ } catch (error) {
89
+ const failure = error;
90
+ if (options?.retryOnConflict === true && failure.isConflict && failure.current !== void 0) {
91
+ return write(failure.current);
92
+ }
93
+ throw error;
94
+ }
95
+ };
96
+ const call = async (request) => {
97
+ try {
98
+ return await request();
99
+ } catch (error) {
100
+ throw await requestError(error);
101
+ }
102
+ };
103
+ const decode = (documents) => documents.map((document) => fromExtendedJson(document));
104
+ const listParameters = (options) => ({
105
+ collectionName: name,
106
+ filter: options.filter,
107
+ sort: options.sort,
108
+ projection: options.projection,
109
+ page: options.page ?? 1,
110
+ rowsPerPage: options.rowsPerPage ?? defaultRows(),
111
+ filterCaseInsensitive: options.filterCaseInsensitive,
112
+ ...options.withDeleted ? { withDeleted: true } : {}
113
+ });
114
+ const findPage = (options = {}) => call(async () => {
115
+ const parameters = listParameters(options);
116
+ const response = await documentApi.listDocumentsRaw(parameters);
117
+ const headers = response.raw.headers;
118
+ return {
119
+ documents: decode(await response.value()),
120
+ page: parameters.page,
121
+ rowsPerPage: parameters.rowsPerPage,
122
+ countRows: headerNumber(headers, "x-pagination-count-rows"),
123
+ countPages: headerNumber(headers, "x-pagination-count-pages")
124
+ };
125
+ });
126
+ const collection = {
127
+ name,
128
+ find: (options) => call(async () => decode(await documentApi.listDocuments(listParameters(options ?? {})))),
129
+ findPage,
130
+ findById: async (id) => {
131
+ try {
132
+ return fromExtendedJson(await documentApi.getDocument({ collectionName: name, documentId: documentId(id) }));
133
+ } catch (error) {
134
+ if (error instanceof ResponseError && error.response.status === 404) {
135
+ return null;
136
+ }
137
+ throw await requestError(error);
138
+ }
139
+ },
140
+ insert: (document) => call(async () => documentApi.insert({ collectionName: name, requestBody: toExtendedJson(await writable(document)) })),
141
+ insertMany: (documents) => call(async () => documentApi.insertMany({ collectionName: name, requestBody: await Promise.all(documents.map(async (document) => toExtendedJson(await writable(document)))) })),
142
+ replace: (target, document, options) => withRetry(target, options, (current) => call(async () => documentApi.update({
143
+ collectionName: name,
144
+ documentId: documentId(current),
145
+ requestBody: toExtendedJson({ ...await writable(document), ...await versionOf(current) })
146
+ }))),
147
+ update: (target, changes, options) => withRetry(target, options, (current) => call(async () => documentApi.updateDocumentPartial({
148
+ collectionName: name,
149
+ documentId: documentId(current),
150
+ requestBody: toExtendedJson({ ...await writable(changes), ...await versionOf(current) })
151
+ }))),
152
+ remove: (id) => call(() => documentApi._delete({ collectionName: name, documentId: documentId(id) })),
153
+ restore: (id) => call(() => documentApi.restoreDocument({ collectionName: name, documentId: documentId(id) })),
154
+ isMine: (document) => {
155
+ if (declaration.value === void 0) {
156
+ void loadDeclaration();
157
+ return false;
158
+ }
159
+ const field = declaration.value?.owner?.field;
160
+ return field !== void 0 && document !== null && document !== void 0 && session.value.profile.user !== "" && getPath(document, field) === session.value.profile.user;
161
+ },
162
+ history: (id, options = {}) => call(async () => {
163
+ const records = await documentApi.getDocumentHistory({ collectionName: name, documentId: documentId(id), page: options.page ?? 1, rowsPerPage: options.rowsPerPage ?? defaultRows() });
164
+ return records.map((record) => fromExtendedJson(record));
165
+ }),
166
+ paginated: (options = {}) => {
167
+ const state = {
168
+ documents: ref([]),
169
+ page: ref(1),
170
+ rowsPerPage: ref(options.rowsPerPage ?? defaultRows()),
171
+ countRows: ref(void 0),
172
+ countPages: ref(void 0),
173
+ pending: ref(false),
174
+ error: ref(null),
175
+ load: async () => {
176
+ state.pending.value = true;
177
+ state.error.value = null;
178
+ try {
179
+ const result = await findPage({ ...options, page: state.page.value, rowsPerPage: state.rowsPerPage.value });
180
+ state.documents.value = result.documents;
181
+ state.countRows.value = result.countRows;
182
+ state.countPages.value = result.countPages;
183
+ } catch (error) {
184
+ state.error.value = error;
185
+ } finally {
186
+ state.pending.value = false;
187
+ }
188
+ },
189
+ goToPage: (target) => {
190
+ state.page.value = Math.max(1, target);
191
+ return state.load();
192
+ },
193
+ nextPage: () => state.goToPage(state.page.value + 1),
194
+ previousPage: () => state.goToPage(state.page.value - 1)
195
+ };
196
+ return state;
197
+ }
198
+ };
199
+ return collection;
200
+ }
@@ -0,0 +1,33 @@
1
+ import type { Ref } from 'vue';
2
+ import type { MongocampCollectionName, MongocampDocument } from '../types/collections.js';
3
+ import type { CollectionFindOptions, MongocampRequestError } from './mongocampCollection.js';
4
+ /**
5
+ * A live list in one line (2.4.0): `const { documents, status } = useMongocampLive('orders', { filter: 'status:open' })`. The documents
6
+ * are loaded with the typed composable and kept in sync with the live updates of the server (Server-Sent Events on change streams):
7
+ *
8
+ * - mode `patch` (default without `sort` and `page`): an update changes the document in the list, a new one is added, a removed one goes;
9
+ * - mode `refetch` (default with `sort` or `page`): every change loads the page again (debounced), so order and paging stay right;
10
+ * - without a replica set the server answers 501: the list is loaded every `pollInterval` instead (`status: 'polling'`);
11
+ * - a lost connection is opened again (backoff up to 30 s) and resumes after the last event it got.
12
+ *
13
+ * In a component it starts when it is mounted (in the browser) and stops when the component is unmounted.
14
+ */
15
+ export type LiveStatus = 'idle' | 'connecting' | 'live' | 'polling' | 'stopped' | 'error';
16
+ export interface LiveOptions extends CollectionFindOptions {
17
+ /** `patch` the list or `refetch` the page on a change; default `refetch` with `sort` or `page`, else `patch`. */
18
+ mode?: 'patch' | 'refetch';
19
+ /** Milliseconds between two loads without a replica set (default 5000). */
20
+ pollInterval?: number;
21
+ /** Start in `onMounted` (component) or at once (default true); `false`: call `start()`. */
22
+ immediate?: boolean;
23
+ }
24
+ export interface LiveState<T> {
25
+ documents: Ref<T[]>;
26
+ status: Ref<LiveStatus>;
27
+ error: Ref<MongocampRequestError | Error | null>;
28
+ start: () => Promise<void>;
29
+ stop: () => void;
30
+ reload: () => Promise<void>;
31
+ }
32
+ export declare function useMongocampLive<N extends MongocampCollectionName>(name: N, options?: LiveOptions): LiveState<MongocampDocument<N>>;
33
+ export declare function useMongocampLive<T extends object = Record<string, unknown>>(name: string, options?: LiveOptions): LiveState<T>;
@@ -0,0 +1,152 @@
1
+ import { getCurrentInstance, getCurrentScope, onMounted, onScopeDispose, ref } from "vue";
2
+ import { documentId, fromExtendedJson } from "../utils/extendedJson.js";
3
+ import { createSseParser } from "../utils/sse.js";
4
+ import { useMongocampCollection } from "./mongocampCollection.js";
5
+ import { useMongocampStorage } from "./mongocampStorage.js";
6
+ import { useMongocampUrl } from "./mongocampUrl.js";
7
+ const MaxBackoff = 3e4;
8
+ const RefetchDebounce = 200;
9
+ let pollingExplained = false;
10
+ export function useMongocampLive(name, options = {}) {
11
+ const collection = useMongocampCollection(name);
12
+ const url = useMongocampUrl();
13
+ const session = useMongocampStorage();
14
+ const mode = options.mode ?? (options.sort !== void 0 || options.page !== void 0 ? "refetch" : "patch");
15
+ const documents = ref([]);
16
+ const status = ref("idle");
17
+ const error = ref(null);
18
+ let abort;
19
+ let reconnect;
20
+ let poll;
21
+ let debounce;
22
+ let lastEventId;
23
+ let backoff = 1e3;
24
+ let stopped = true;
25
+ const reload = async () => {
26
+ try {
27
+ documents.value = await collection.find(options);
28
+ error.value = null;
29
+ } catch (caught) {
30
+ error.value = caught;
31
+ }
32
+ };
33
+ const apply = (event, data) => {
34
+ if (event === "reset") {
35
+ void reload();
36
+ return;
37
+ }
38
+ if (mode === "refetch") {
39
+ clearTimeout(debounce);
40
+ debounce = setTimeout(() => void reload(), RefetchDebounce);
41
+ return;
42
+ }
43
+ const id = documentId(fromExtendedJson({ _id: data.id }));
44
+ const others = documents.value.filter((document) => documentId(document) !== id);
45
+ if (event === "remove") {
46
+ documents.value = others;
47
+ } else if (event === "upsert" && data.document !== void 0) {
48
+ const document = fromExtendedJson(data.document);
49
+ const index = documents.value.findIndex((entry) => documentId(entry) === id);
50
+ documents.value = index < 0 ? [...documents.value, document] : documents.value.map((entry, position) => position === index ? document : entry);
51
+ }
52
+ };
53
+ const startPolling = () => {
54
+ status.value = "polling";
55
+ if (!pollingExplained) {
56
+ pollingExplained = true;
57
+ console.info("[mongocamp] live updates need a replica set (change streams); the list is loaded every few seconds instead");
58
+ }
59
+ clearInterval(poll);
60
+ poll = setInterval(() => void reload(), options.pollInterval ?? 5e3);
61
+ };
62
+ const connect = async () => {
63
+ if (stopped) {
64
+ return;
65
+ }
66
+ status.value = "connecting";
67
+ abort = new AbortController();
68
+ const query = new URLSearchParams();
69
+ if (options.filter !== void 0 && options.filter !== "") {
70
+ query.set("filter", options.filter);
71
+ }
72
+ if (options.filterCaseInsensitive) {
73
+ query.set("filterCaseInsensitive", "true");
74
+ }
75
+ const headers = { accept: "text/event-stream" };
76
+ if (session.value.token) {
77
+ headers.authorization = `Bearer ${session.value.token}`;
78
+ }
79
+ if (lastEventId !== void 0) {
80
+ headers["last-event-id"] = lastEventId;
81
+ }
82
+ try {
83
+ const search = query.toString();
84
+ const response = await fetch(`${url}/mongodb/collections/${encodeURIComponent(name)}/documents/watch${search === "" ? "" : `?${search}`}`, { headers, signal: abort.signal });
85
+ if (response.status === 501) {
86
+ startPolling();
87
+ return;
88
+ }
89
+ if (!response.ok || response.body === null) {
90
+ throw Object.assign(new Error(response.headers.get("x-error-message") ?? `live updates failed with status ${response.status}`), { status: response.status });
91
+ }
92
+ status.value = "live";
93
+ backoff = 1e3;
94
+ const parse = createSseParser((message) => {
95
+ if (message.id !== void 0) {
96
+ lastEventId = message.id;
97
+ }
98
+ apply(message.event, message.data === "" ? {} : JSON.parse(message.data));
99
+ });
100
+ const reader = response.body.pipeThrough(new TextDecoderStream()).getReader();
101
+ for (; ; ) {
102
+ const { value, done } = await reader.read();
103
+ if (done) {
104
+ break;
105
+ }
106
+ parse(value);
107
+ }
108
+ } catch (caught) {
109
+ if (stopped) {
110
+ return;
111
+ }
112
+ const failure = caught;
113
+ if (failure.status === 401 || failure.status === 403) {
114
+ error.value = failure;
115
+ status.value = "error";
116
+ return;
117
+ }
118
+ }
119
+ if (!stopped) {
120
+ status.value = "connecting";
121
+ reconnect = setTimeout(() => void connect(), backoff);
122
+ backoff = Math.min(backoff * 2, MaxBackoff);
123
+ }
124
+ };
125
+ const start = async () => {
126
+ if (!stopped) {
127
+ return;
128
+ }
129
+ stopped = false;
130
+ await reload();
131
+ void connect();
132
+ };
133
+ const stop = () => {
134
+ stopped = true;
135
+ abort?.abort();
136
+ clearTimeout(reconnect);
137
+ clearTimeout(debounce);
138
+ clearInterval(poll);
139
+ status.value = "stopped";
140
+ };
141
+ if (options.immediate !== false) {
142
+ if (getCurrentInstance() !== null) {
143
+ onMounted(() => void start());
144
+ } else if (import.meta.client) {
145
+ void start();
146
+ }
147
+ }
148
+ if (getCurrentScope() !== void 0) {
149
+ onScopeDispose(stop);
150
+ }
151
+ return { documents, status, error, start, stop, reload };
152
+ }