couchset 0.3.0 → 0.4.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.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"next.js","sourceRoot":"","sources":["../src/next.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEA,0DAAoC;AAEpC,iCAA0F;AAE1F,2CAAgD;AAChD,6CAAsE;AAEtE,qDAAwD;AACxD,+BAAoC;AAIpC,uEAAuE;AAC1D,QAAA,SAAS,GAA6B;IAC/C,YAAY,EAAE,UAAC,KAAa,IAAW,OAAA,IAAI,IAAI,CAAC,KAAK,CAAC,EAAf,CAAe;IACtD,UAAU,EAAE,UAAC,KAAW,IAAa,OAAA,KAAK,CAAC,WAAW,EAAE,EAAnB,CAAmB;CAC3D,CAAC;AA6CK,IAAM,WAAW,GAAG,UAAU,UAA8B;IAC/D,IAAI,CAAC,UAAU,IAAI,CAAC,UAAU,CAAC,IAAI,EAAE,CAAC;QAClC,MAAM,IAAI,KAAK,CAAC,uCAAuC,CAAC,CAAC;IAC7D,CAAC;IAED,oBAAW,UAAU,EAAE;AAC3B,CAAC,CAAC;AANW,QAAA,WAAW,eAMtB;AA0EF,IAAM,eAAe,GAAG,UAAC,OAA8B,IAAmB,OAAA,CAAC;IACvE,UAAU,EAAE,OAAO,CAAC,UAAU,IAAI,SAAS;IAC3C,gBAAgB,EAAE,OAAO,CAAC,gBAAgB,IAAI,uBAAuB;IACrE,QAAQ,EAAE,OAAO,CAAC,QAAQ,IAAI,EAAE;IAChC,QAAQ,EAAE,OAAO,CAAC,QAAQ,IAAI,EAAE;IAChC,KAAK,EAAE,OAAO,CAAC,KAAK;CACvB,CAAC,EANwE,CAMxE,CAAC;AAEH,IAAM,SAAS,GAAG,UAAC,KAAU,IAAa,OAAA,UAAG,CAAA,KAA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CAAC;AAEF,IAAM,yBAAyB,GAAG,UAAC,GAAQ,EAAE,MAAwB;IACjE,oEAAoE;IACpE,0EAA0E;IAC1E,4EAA4E;IAC5E,IAAM,UAAU,GAAG,GAAG,CAAC,aAAa,IAAI,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC,CAAC,GAAG,CAAC,WAAW,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC;IACrF,OAAO,CACH,CAAC,CAAC,GAAG,CAAC,QAAQ,IAAI,GAAG,CAAC,QAAQ,KAAK,MAAM,CAAC,KAAK,CAAC;QAChD,CAAC,CAAC,UAAU,IAAI,UAAU,KAAK,MAAM,CAAC,UAAU,CAAC,CACpD,CAAC;AACN,CAAC,CAAC;AAEF,IAAM,kBAAkB,GAAG,UAAC,IAAY,EAAE,UAAgC;IACtE,IAAM,WAAW,GAAG,IAAI,CAAC,SAAS,CAAC;QAC/B,MAAM,EAAE,UAAU,CAAC,MAAM;QACzB,OAAO,EAAE,UAAU,CAAC,OAAO;QAC3B,KAAK,EAAE,UAAU,CAAC,KAAK;KAC1B,CAAC;SACG,KAAK,CAAC,EAAE,CAAC;SACT,MAAM,CAAC,UAAC,IAAI,EAAE,SAAS,IAAK,OAAA,CAAC,IAAI,GAAG,EAAE,GAAG,SAAS,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,EAA3C,CAA2C,EAAE,CAAC,CAAC;SAC3E,QAAQ,CAAC,EAAE,CAAC,CAAC;IAClB,OAAO,UAAG,IAAI,eAAK,WAAW,CAAE,CAAC;AACrC,CAAC,CAAC","sourcesContent":["import type {Bucket, Cluster} from 'couchbase';\n\nimport couchbase from './couchbase';\nimport type {CouchsetArgs} from './connection';\nimport {AutoModelFields, FieldCodec, Model, ModelConnection, ModalOptions} from './model';\nimport type {ModelIndexDefinition} from './model';\nimport {buildIndexQuery} from './model/indexes';\nimport {escapeIdentifier, keyspaceIdentifier} from './model/keyspace';\nimport type {SortType} from './query/interface/query.types';\nimport {buildWhereExpr} from './query/helpers/builders';\nimport {generateUUID} from './uuid';\n\nexport type {FieldCodec} from './model';\n\n/** A JSON-friendly Date codec for models declared with defineModel. */\nexport const dateCodec: FieldCodec<Date, string> = {\n fromDatabase: (value: string): Date => new Date(value),\n toDatabase: (value: Date): string => value.toISOString(),\n};\n\nexport interface ModelCollectionSettings {\n maxExpiry?: number;\n history?: boolean;\n}\n\n/**\n * A model definition has no connection and performs no I/O. Definitions may be\n * reused safely across clients and are the unit the client registers.\n */\nexport type ModelField<T> = Extract<keyof T, string>;\nexport type TypedIndexField<T> = ModelField<T> | Partial<Record<ModelField<T>, SortType>>;\nexport type ModelCodecs<T> = Partial<{\n [Field in ModelField<T>]: FieldCodec<T[Field], any>;\n}> &\n Partial<Record<`${string}.${string}`, FieldCodec<any, any>>>;\n\nexport interface TypedModelIndexDefinition<T> extends Omit<ModelIndexDefinition, 'fields'> {\n fields?: TypedIndexField<T>[];\n}\n\nexport interface ModelDefinition<T = any> extends Omit<ModalOptions, 'codecs' | 'indexes'> {\n name: string;\n collectionSettings?: ModelCollectionSettings;\n codecs?: ModelCodecs<T>;\n indexes?: TypedModelIndexDefinition<T>[];\n}\n\n/** User fields are distinct from CouchSet's generated persistence metadata. */\nexport type ModelCreateInput<T> = Omit<T, keyof AutoModelFields> &\n Partial<Pick<T, Extract<keyof T, keyof AutoModelFields>>>;\n\nexport interface TypedModel<T>\n extends Omit<Model, 'getById' | 'getWithCas' | 'insert' | 'replaceById' | 'replaceIfCas'> {\n getById(id: string, options?: any): Promise<T & AutoModelFields>;\n getWithCas(\n id: string,\n options?: any\n ): Promise<{content: T & AutoModelFields; cas: any; expiryTime?: any}>;\n insert(data: ModelCreateInput<T>, options?: any): Promise<T & AutoModelFields>;\n replaceById(id: string, data: T, options?: any): Promise<T & AutoModelFields>;\n replaceIfCas(id: string, data: T, cas: any, options?: any): Promise<T & AutoModelFields>;\n}\n\nexport const defineModel = <T = any>(definition: ModelDefinition<T>): ModelDefinition<T> => {\n if (!definition || !definition.name) {\n throw new Error('defineModel requires a non-empty name');\n }\n\n return {...definition};\n};\n\nexport interface CouchsetClientDependencies {\n /** Supply a fully controlled runtime for tests or an application-owned connection. */\n connection?: ModelConnection;\n /** Supply an already connected SDK cluster/bucket without using couchbase.connect. */\n cluster?: Cluster;\n bucket?: Bucket;\n /** Override connection construction; useful for dependency injection and test doubles. */\n connect?: (settings: CouchsetArgs) => Promise<Cluster>;\n}\n\nexport interface CouchsetClientOptions extends Partial<CouchsetArgs> {\n models?: Array<ModelDefinition<any>>;\n dependencies?: CouchsetClientDependencies;\n}\n\nexport interface EnsureCollectionsOptions {\n models?: Array<ModelDefinition<any>>;\n timeoutMs?: number;\n pollIntervalMs?: number;\n}\n\nexport interface ProvisionOptions extends EnsureCollectionsOptions {\n collections?: boolean;\n indexes?: boolean;\n waitForIndexes?: boolean;\n}\n\nexport interface RegisterModelOptions extends ProvisionOptions {\n /** Explicitly provision this dynamic model. Constructors and CRUD never do this. */\n provision?: boolean | {collections?: boolean; indexes?: boolean; waitForIndexes?: boolean};\n}\n\nexport interface ProvisionedTarget {\n scope: string;\n collection: string;\n createdScope: boolean;\n createdCollection: boolean;\n}\n\nexport interface IndexPlanItem {\n status: 'create' | 'matching' | 'replace';\n definition: ModelIndexDefinition;\n keyspace: string;\n target: CollectionTarget;\n /** The physical index CouchSet will create. Replacement names are versioned. */\n createAs: string;\n /** Only populated for an explicit or detected safe replacement. */\n replaces?: string;\n reason?: string;\n}\n\nexport interface IndexPlan {\n items: IndexPlanItem[];\n}\n\nexport interface ApplyIndexPlanOptions {\n /** Opt-in only: drop old indexes after the replacement is online. */\n dropReplaced?: boolean;\n timeoutMs?: number;\n}\n\ninterface RegisteredModel<T = any> {\n definition: ModelDefinition<T>;\n model: Model;\n}\n\ninterface CollectionTarget {\n scope: string;\n collection: string;\n settings?: ModelCollectionSettings;\n}\n\nconst defaultSettings = (options: CouchsetClientOptions): CouchsetArgs => ({\n bucketName: options.bucketName || 'default',\n connectionString: options.connectionString || 'couchbase://localhost',\n password: options.password || '',\n username: options.username || '',\n proxy: options.proxy,\n});\n\nconst errorText = (error: any): string => `${error?.name || ''} ${error?.message || error || ''}`;\nconst isAlreadyExists = (error: any): boolean =>\n /already exists|exists|ScopeExists|CollectionExists/i.test(errorText(error));\nconst isNotFound = (error: any): boolean => /not found|not exist/i.test(errorText(error));\n\nconst provisionError = (operation: string, target: string, error: any): Error => {\n const message = errorText(error);\n const privilege = /access|permission|authoriz|privilege|forbidden/i.test(message)\n ? ' This operation requires Couchbase Manage Scopes privileges on the bucket.'\n : '';\n const wrapped: any = new Error(\n `CouchSet could not ${operation} ${target}.${privilege} ${message}`.trim()\n );\n wrapped.cause = error;\n return wrapped;\n};\n\nconst delay = (milliseconds: number): Promise<void> =>\n new Promise((resolve) => setTimeout(resolve, milliseconds));\n\nclass DirectConnection implements ModelConnection {\n public cluster: Cluster;\n public bucket: Bucket;\n private connectPromise?: Promise<Cluster>;\n\n constructor(\n private readonly settings: CouchsetArgs,\n private readonly dependencies: CouchsetClientDependencies\n ) {\n this.cluster = dependencies.cluster as Cluster;\n this.bucket = dependencies.bucket as Bucket;\n\n if (this.cluster && !this.bucket) {\n this.bucket = this.cluster.bucket(settings.bucketName);\n }\n }\n\n public getBucket(): string {\n return this.settings.bucketName;\n }\n\n public getCollection(scopeName?: string, collectionName?: string): any {\n if (!this.bucket) {\n throw new Error('CouchSet client is not connected; call client.ready() first');\n }\n\n if (!scopeName && !collectionName) {\n return this.bucket.defaultCollection();\n }\n\n return this.bucket.scope(scopeName || '_default').collection(collectionName || '_default');\n }\n\n public isConnected(): boolean {\n return !!this.cluster && !!this.bucket;\n }\n\n public async ready(): Promise<DirectConnection> {\n if (this.isConnected()) {\n return this;\n }\n\n if (!this.connectPromise) {\n const connect =\n this.dependencies.connect ||\n ((settings: CouchsetArgs) =>\n couchbase.connect(settings.connectionString, {\n password: settings.password,\n proxy: settings.proxy,\n username: settings.username,\n }));\n this.connectPromise = connect(this.settings);\n }\n\n this.cluster = await this.connectPromise;\n this.bucket = this.cluster.bucket(this.settings.bucketName);\n return this;\n }\n\n public shouldReconnect(): boolean {\n return false;\n }\n\n public markDisconnected(): void {\n // A client-owned connection never retries an arbitrary write operation.\n }\n\n public async shutdown(): Promise<void> {\n if (this.cluster && typeof (this.cluster as any).close === 'function') {\n await (this.cluster as any).close();\n }\n this.cluster = undefined as any;\n this.bucket = undefined as any;\n }\n}\n\n/**\n * A client owns its model-definition registry and connection. It intentionally\n * does not alter the legacy singleton or register models globally.\n */\nexport class CouchsetClient {\n private readonly connection: ModelConnection;\n private readonly registered = new Map<string, RegisteredModel<any>>();\n private readonly settings: CouchsetArgs;\n\n constructor(options: CouchsetClientOptions = {}) {\n this.settings = defaultSettings(options);\n const dependencies = options.dependencies || {};\n\n if (dependencies.connection) {\n const bucketName = dependencies.connection.getBucket();\n if (!bucketName) {\n throw new Error('Injected CouchSet connections must expose a bucket name');\n }\n if (options.bucketName && options.bucketName !== bucketName) {\n throw new Error(\n `Injected CouchSet connection targets ${bucketName}, not requested bucket ${options.bucketName}`\n );\n }\n this.settings.bucketName = bucketName;\n } else if (dependencies.bucket) {\n const bucketName = dependencies.bucket.name;\n if (options.bucketName && options.bucketName !== bucketName) {\n throw new Error(\n `Injected Couchbase bucket targets ${bucketName}, not requested bucket ${options.bucketName}`\n );\n }\n this.settings.bucketName = bucketName;\n } else if (dependencies.cluster && !options.bucketName) {\n throw new Error('bucketName is required when injecting a Couchbase cluster');\n }\n\n this.connection =\n dependencies.connection || new DirectConnection(this.settings, dependencies);\n\n (options.models || []).forEach((definition) => this.model(definition));\n }\n\n public async ready(): Promise<this> {\n await this.connection.ready();\n return this;\n }\n\n public async shutdown(): Promise<void> {\n const shutdown = (this.connection as any).shutdown;\n if (typeof shutdown === 'function') {\n await shutdown.call(this.connection);\n }\n }\n\n public definitions(): ModelDefinition<any>[] {\n return Array.from(this.registered.values()).map(({definition}) => definition);\n }\n\n /** Bind and register a definition without provisioning or index DDL. */\n public model<T>(definition: ModelDefinition<T>): TypedModel<T> {\n const identity = modelIdentity(definition);\n const existing = this.registered.get(identity);\n\n if (existing) {\n assertSameDefinition(existing.definition, definition);\n return existing.model as TypedModel<T>;\n }\n\n const model = new Model(definition.name, definition as ModalOptions, this.connection);\n this.registered.set(identity, {definition, model});\n return model as TypedModel<T>;\n }\n\n /**\n * Async registration for dynamic models. DDL is performed only when the\n * caller explicitly opts into provision; ordinary model() is side-effect-free.\n */\n public async registerModel<T>(\n definition: ModelDefinition<T>,\n options: RegisterModelOptions = {}\n ): Promise<TypedModel<T>> {\n const model = this.model(definition);\n const requested = options.provision;\n\n if (requested) {\n const config =\n typeof requested === 'boolean' ? {collections: true, indexes: true} : requested;\n await this.provision({\n collections: config.collections !== false,\n indexes: config.indexes !== false,\n models: [definition],\n timeoutMs: options.timeoutMs,\n waitForIndexes: config.waitForIndexes,\n });\n }\n\n return model;\n }\n\n /** Create only missing scopes/collections. Existing resources are never altered. */\n public async ensureCollections(\n options: EnsureCollectionsOptions = {}\n ): Promise<ProvisionedTarget[]> {\n await this.ready();\n const targets = this.targets(options.models);\n const manager: any = (this.connection as any).bucket.collections();\n let manifest: any[];\n\n try {\n manifest = await manager.getAllScopes();\n } catch (error) {\n throw provisionError('read the scope manifest for', this.settings.bucketName, error);\n }\n\n const result: ProvisionedTarget[] = [];\n for (const target of targets) {\n const defaultTarget = target.scope === '_default' && target.collection === '_default';\n if (defaultTarget) {\n result.push({...target, createdScope: false, createdCollection: false});\n continue;\n }\n\n let scope = findScope(manifest, target.scope);\n let createdScope = false;\n if (!scope && target.scope !== '_default') {\n try {\n await manager.createScope(target.scope);\n createdScope = true;\n } catch (error) {\n if (!isAlreadyExists(error)) {\n throw provisionError('create scope', target.scope, error);\n }\n }\n manifest = await this.waitForCollectionManifest(target.scope, undefined, options);\n scope = findScope(manifest, target.scope);\n }\n\n if (!scope) {\n throw new Error(`CouchSet could not find scope ${target.scope} after provisioning`);\n }\n\n const exists = (scope.collections || []).some(\n (item: any) => item.name === target.collection\n );\n let createdCollection = false;\n if (!exists) {\n try {\n await manager.createCollection(\n target.collection,\n target.scope,\n target.settings || {}\n );\n createdCollection = true;\n } catch (error) {\n if (!isAlreadyExists(error)) {\n throw provisionError(\n 'create collection',\n `${target.scope}.${target.collection}`,\n error\n );\n }\n }\n }\n\n await this.waitForCollectionManifest(target.scope, target.collection, options);\n result.push({...target, createdScope, createdCollection});\n }\n\n return result;\n }\n\n /** Explicit bootstrap: provisioning occurs before index creation. */\n public async provision(options: ProvisionOptions = {}): Promise<{\n collections: ProvisionedTarget[];\n indexes: string[];\n }> {\n const definitions = options.models || this.definitions();\n const collections =\n options.collections === false\n ? []\n : await this.ensureCollections({...options, models: definitions});\n const indexes = options.indexes\n ? await this.ensureIndexes({\n models: definitions,\n waitForIndexes: options.waitForIndexes,\n timeoutMs: options.timeoutMs,\n })\n : [];\n\n return {collections, indexes};\n }\n\n /** Normal ensureIndexes stays create-only. It never checks, drops, or changes an existing index. */\n public async ensureIndexes(\n options: {\n models?: Array<ModelDefinition<any>>;\n deferred?: boolean;\n waitForIndexes?: boolean;\n timeoutMs?: number;\n } = {}\n ): Promise<string[]> {\n await this.ready();\n const definitions = options.models || this.definitions();\n const queries: string[] = [];\n const indexes: Array<{name: string; target: CollectionTarget}> = [];\n\n for (const definition of definitions) {\n const model = this.model(definition);\n const statements = await model.ensureIndexes({deferred: options.deferred});\n queries.push(...statements);\n indexes.push(\n ...(definition.indexes || []).map((index) => ({\n name: index.name,\n target: definitionTarget(definition),\n }))\n );\n }\n\n if (options.waitForIndexes && indexes.length) {\n await this.waitForIndexes(indexes, options.timeoutMs);\n }\n\n return queries;\n }\n\n /** Report missing, matching, and drifted indexes; this method has no DDL side effects. */\n public async planIndexes(\n options: {models?: Array<ModelDefinition<any>>} = {}\n ): Promise<IndexPlan> {\n await this.ready();\n const rows = await this.indexCatalog();\n const items: IndexPlanItem[] = [];\n\n for (const definition of options.models || this.definitions()) {\n const keyspace = this.keyspace(definition);\n const target = definitionTarget(definition);\n for (const index of definition.indexes || []) {\n const matchingRows = rows.filter((row) => indexRowMatchesTarget(row, definition));\n const desired = matchingRows.find((row) => row.name === index.name);\n const replacementName = versionedIndexName(index.name, index);\n const replacement = matchingRows.find((row) => row.name === replacementName);\n\n // A previous safe rollout may have dropped the old logical name\n // while retaining this deterministic replacement physical name.\n if (replacement && indexMatches(replacement, index)) {\n items.push({\n createAs: replacementName,\n definition: index,\n keyspace,\n status: 'matching',\n target,\n });\n continue;\n }\n\n if (desired && indexMatches(desired, index)) {\n items.push({\n createAs: index.name,\n definition: index,\n keyspace,\n status: 'matching',\n target,\n });\n continue;\n }\n\n // `replaces` explicitly asks for a new physical index, even if\n // the predecessor happens to have equivalent keys.\n const predecessorName = index.replaces || index.name;\n const predecessor = matchingRows.find((row) => row.name === predecessorName);\n\n if (!predecessor) {\n items.push({\n createAs: index.name,\n definition: index,\n keyspace,\n status: 'create',\n target,\n });\n continue;\n }\n\n const createAs = index.replaces ? index.name : replacementName;\n items.push({\n createAs,\n definition: index,\n keyspace,\n reason: 'Declared keys, predicate, or primary mode differs from the live index.',\n replaces: predecessor.name,\n status: 'replace',\n target,\n });\n }\n }\n\n return {items};\n }\n\n /**\n * Apply a reviewed plan by creating versioned replacements and waiting for\n * them. Dropping old indexes is deliberately an explicit second opt-in.\n */\n public async applyIndexPlan(\n plan: IndexPlan,\n options: ApplyIndexPlanOptions = {}\n ): Promise<string[]> {\n await this.ready();\n const applied: string[] = [];\n const replacements: Array<{name: string; target: CollectionTarget}> = [];\n\n for (const item of plan.items) {\n if (item.status === 'matching') {\n continue;\n }\n\n const definition = {...item.definition, name: item.createAs};\n const query = buildIndexQuery(item.keyspace, definition);\n await this.connection.cluster.query(query);\n applied.push(query);\n replacements.push({name: item.createAs, target: item.target});\n }\n\n if (replacements.length) {\n await this.waitForIndexes(replacements, options.timeoutMs);\n }\n\n if (options.dropReplaced) {\n for (const item of plan.items) {\n if (item.status === 'replace' && item.replaces) {\n await this.connection.cluster.query(\n `DROP INDEX ${item.keyspace}.${escapeIdentifier(item.replaces)}`\n );\n }\n }\n }\n\n return applied;\n }\n\n /**\n * Run the callback through Couchbase's transaction retry loop. The callback\n * may execute more than once; do not perform external side effects inside it.\n * A commit-ambiguous error is rethrown and must be resolved by the caller via\n * an idempotency key/outbox, never by blindly retrying a side effect.\n */\n public async transaction<T>(\n callback: (transaction: CouchsetTransaction) => Promise<T>\n ): Promise<T> {\n await this.ready();\n let result: T;\n await (this.connection.cluster as any).transactions().run(async (attempt: any) => {\n result = await callback(new CouchsetTransaction(this, attempt));\n });\n return result as T;\n }\n\n public keyspace(definition: ModelDefinition<any>): string {\n const target = definitionTarget(definition);\n return keyspaceIdentifier({\n bucketName: this.settings.bucketName,\n collectionName: target.collection,\n scopeName: target.scope,\n });\n }\n\n public getConnection(): ModelConnection {\n return this.connection;\n }\n\n private targets(definitions?: Array<ModelDefinition<any>>): CollectionTarget[] {\n const targets = new Map<string, CollectionTarget>();\n for (const definition of definitions || this.definitions()) {\n const target = definitionTarget(definition);\n const identity = `${target.scope}.${target.collection}`;\n const existing = targets.get(identity);\n const settings = definition.collectionSettings;\n\n if (\n existing &&\n JSON.stringify(existing.settings || {}) !== JSON.stringify(settings || {})\n ) {\n throw new Error(\n `Conflicting collection settings declared for ${identity}; CouchSet will not alter an existing collection`\n );\n }\n targets.set(identity, {...target, settings});\n }\n return Array.from(targets.values());\n }\n\n private async waitForCollectionManifest(\n scopeName: string,\n collectionName: string | undefined,\n options: EnsureCollectionsOptions\n ): Promise<any[]> {\n const manager: any = (this.connection as any).bucket.collections();\n const timeout = options.timeoutMs || 30000;\n const poll = options.pollIntervalMs || 100;\n const deadline = Date.now() + timeout;\n\n while (Date.now() <= deadline) {\n try {\n const manifest = await manager.getAllScopes();\n const scope = findScope(manifest, scopeName);\n if (\n scope &&\n (!collectionName ||\n (scope.collections || []).some((item: any) => item.name === collectionName))\n ) {\n return manifest;\n }\n } catch (error) {\n if (!isNotFound(error)) {\n throw provisionError(\n 'wait for collection metadata',\n `${scopeName}.${collectionName || ''}`,\n error\n );\n }\n }\n await delay(poll);\n }\n\n throw new Error(\n `Timed out waiting for Couchbase collection ${scopeName}.${\n collectionName || ''\n } to appear in the manifest`\n );\n }\n\n private async waitForIndexes(\n indexes: Array<{name: string; target: CollectionTarget}>,\n timeoutMs = 30000\n ): Promise<void> {\n const deadline = Date.now() + timeoutMs;\n\n while (Date.now() <= deadline) {\n const rows = await this.indexCatalog();\n if (\n indexes.every((index) =>\n rows.some(\n (row) =>\n row.name === index.name &&\n String(row.state).toLowerCase() === 'online' &&\n indexRowMatchesCollection(row, index.target)\n )\n )\n ) {\n return;\n }\n await delay(100);\n }\n\n throw new Error(\n `Timed out waiting for Couchbase indexes to become online: ${indexes\n .map((index) => index.name)\n .join(', ')}`\n );\n }\n\n private async indexCatalog(): Promise<any[]> {\n const result = await this.connection.cluster.query(\n 'SELECT name, bucket_id, keyspace_id, scope_id, collection_id, index_key, condition, is_primary, state FROM system:indexes WHERE bucket_id = $bucket OR keyspace_id = $bucket',\n {parameters: {bucket: this.settings.bucketName}}\n );\n return (result as any).rows || [];\n }\n}\n\n/** A model bound strictly to a Couchbase transaction attempt. */\nexport class TransactionModel<T = any> {\n constructor(private readonly model: TypedModel<T>, private readonly attempt: any) {}\n\n public async get(id: string): Promise<TransactionDocument<T> | null> {\n try {\n const document = await this.attempt.get(this.model.getCollection(), id);\n return {content: this.model.parse<T & AutoModelFields>(document.content), document};\n } catch (error) {\n if (isNotFound(error)) {\n return null;\n }\n throw error;\n }\n }\n\n public getById(id: string): Promise<TransactionDocument<T> | null> {\n return this.get(id);\n }\n\n public async insert(id: string, data: ModelCreateInput<T>): Promise<TransactionDocument<T>> {\n const stored = await this.model.prepareInsert({...data, id} as T);\n const document = await this.attempt.insert(this.model.getCollection(), id, stored);\n return {\n content: this.model.parse<T & AutoModelFields>(document.content || stored),\n document,\n };\n }\n\n /** Replace requires the prior transactional read, as required by the SDK. */\n public async replace(\n document: TransactionDocument<T>,\n data: T\n ): Promise<TransactionDocument<T>> {\n const stored = await this.model.prepareReplace(document.content.id, data);\n const replacement = await this.attempt.replace(document.document, stored);\n return {\n content: this.model.parse<T & AutoModelFields>(replacement.content || stored),\n document: replacement,\n };\n }\n\n public async replaceById(id: string, data: T): Promise<TransactionDocument<T>> {\n const current = await this.get(id);\n if (!current) {\n throw new Error(`Cannot replace missing transaction document ${id}`);\n }\n return this.replace(current, data);\n }\n\n public async remove(document: TransactionDocument<T>): Promise<void> {\n await this.attempt.remove(document.document);\n }\n\n public query<TRow = any>(statement: string, options?: any): Promise<{rows: TRow[]}> {\n return this.attempt.query(statement, options);\n }\n}\n\nexport interface TransactionDocument<T> {\n content: T & AutoModelFields;\n /** Opaque transaction SDK result; only pass it back to replace/remove. */\n document: any;\n}\n\nexport class CouchsetTransaction {\n constructor(private readonly client: CouchsetClient, private readonly attempt: any) {}\n\n public model<T>(definition: ModelDefinition<T>): TransactionModel<T> {\n return new TransactionModel<T>(this.client.model(definition), this.attempt);\n }\n\n public query<TRow = any>(statement: string, options?: any): Promise<{rows: TRow[]}> {\n return this.attempt.query(statement, options);\n }\n}\n\n/**\n * Creates a short-lived scoped fixture and a cleanup function. The caller must\n * invoke cleanup in after/afterEach; no normal client operation ever drops data.\n */\nexport const createCouchsetTestFixture = async <T = any>(\n client: CouchsetClient,\n definition: Omit<ModelDefinition<T>, 'scope' | 'collection'> & {\n scope?: string;\n collection?: string;\n }\n): Promise<{\n definition: ModelDefinition<T>;\n model: TypedModel<T>;\n cleanup: () => Promise<void>;\n}> => {\n const suffix = generateUUID().replace(/-/g, '').slice(0, 12);\n const fixtureScope = definition.scope || `couchset_test_${suffix}`;\n const generatedScope = fixtureScope !== definition.scope;\n const scoped = defineModel<T>({\n ...definition,\n collection: definition.collection || `fixture_${suffix}`,\n scope: fixtureScope,\n });\n const model = await client.registerModel(scoped, {provision: {collections: true}});\n\n return {\n definition: scoped,\n model,\n cleanup: async () => {\n const target = definitionTarget(scoped);\n const manager: any = (client.getConnection() as any).bucket.collections();\n try {\n await manager.dropCollection(target.collection, target.scope);\n } catch (error) {\n if (!isNotFound(error)) {\n throw provisionError(\n 'drop fixture collection',\n `${target.scope}.${target.collection}`,\n error\n );\n }\n }\n if (generatedScope) {\n try {\n await manager.dropScope(target.scope);\n } catch (error) {\n if (!isNotFound(error)) {\n throw provisionError('drop fixture scope', target.scope, error);\n }\n }\n }\n },\n };\n};\n\nexport const createCouchsetClient = (options: CouchsetClientOptions = {}): CouchsetClient =>\n new CouchsetClient(options);\n\nconst definitionTarget = (definition: ModelDefinition<any>): CollectionTarget => ({\n collection: Object.prototype.hasOwnProperty.call(definition, 'collection')\n ? definition.collection || '_default'\n : '_default',\n scope: Object.prototype.hasOwnProperty.call(definition, 'scope')\n ? definition.scope || '_default'\n : '_default',\n});\n\nconst modelIdentity = (definition: ModelDefinition<any>): string => {\n const target = definitionTarget(definition);\n return `${target.scope}.${target.collection}.${definition.name}`;\n};\n\nconst assertSameDefinition = (left: ModelDefinition<any>, right: ModelDefinition<any>): void => {\n if (!sameValue(left, right)) {\n throw new Error(\n `Model ${modelIdentity(\n left\n )} is already registered with a different definition; create a separate client or use a new model name`\n );\n }\n};\n\nconst sameValue = (left: any, right: any): boolean => {\n if (left === right) {\n return true;\n }\n if (!left || !right || typeof left !== 'object' || typeof right !== 'object') {\n return false;\n }\n if (left instanceof Date || right instanceof Date) {\n return left instanceof Date && right instanceof Date && left.getTime() === right.getTime();\n }\n if (Array.isArray(left) || Array.isArray(right)) {\n return (\n Array.isArray(left) &&\n Array.isArray(right) &&\n left.length === right.length &&\n left.every((item, index) => sameValue(item, right[index]))\n );\n }\n const leftKeys = Object.keys(left).sort();\n const rightKeys = Object.keys(right).sort();\n return (\n leftKeys.length === rightKeys.length &&\n leftKeys.every((key, index) => key === rightKeys[index] && sameValue(left[key], right[key]))\n );\n};\n\nconst findScope = (scopes: any[], name: string): any => scopes.find((scope) => scope.name === name);\n\nconst normalize = (value: any): string =>\n JSON.stringify(value || '')\n .replace(/[\\s`()\"']/g, '')\n .toLowerCase();\n\nconst indexMatches = (row: any, definition: ModelIndexDefinition): boolean => {\n if (!!row.is_primary !== !!definition.primary) {\n return false;\n }\n if (definition.primary) {\n return true;\n }\n\n const expectedKeys = (definition.fields || []).map((field) => {\n if (typeof field === 'string') {\n return field;\n }\n const key = Object.keys(field)[0];\n return `${key} ${field[key]}`;\n });\n return (\n normalize(row.index_key) === normalize(expectedKeys) &&\n normalize(row.condition) === normalize(indexCondition(definition))\n );\n};\n\n/** Match Couchbase's catalogued SQL++ condition against the same SQL++ we declare. */\nconst indexCondition = (definition: ModelIndexDefinition): string =>\n buildWhereExpr(definition.where).replace(/^\\s*WHERE\\s+/i, '');\n\nconst indexRowMatchesTarget = (row: any, definition: ModelDefinition<any>): boolean => {\n return indexRowMatchesCollection(row, definitionTarget(definition));\n};\n\nconst indexRowMatchesCollection = (row: any, target: CollectionTarget): boolean => {\n // On current Couchbase Server, scoped collection indexes expose the\n // collection in keyspace_id and omit collection_id. Older/default targets\n // may use keyspace_id for the bucket, so prefer collection_id when present.\n const collection = row.collection_id || (row.scope_id ? row.keyspace_id : undefined);\n return (\n (!row.scope_id || row.scope_id === target.scope) &&\n (!collection || collection === target.collection)\n );\n};\n\nconst versionedIndexName = (name: string, definition: ModelIndexDefinition): string => {\n const fingerprint = JSON.stringify({\n fields: definition.fields,\n primary: definition.primary,\n where: definition.where,\n })\n .split('')\n .reduce((hash, character) => (hash * 31 + character.charCodeAt(0)) >>> 0, 7)\n .toString(36);\n return `${name}_v${fingerprint}`;\n};\n"]}
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,38 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ /* eslint-disable @typescript-eslint/ban-ts-comment -- this file verifies compiler errors. */
4
+ var next_1 = require("./next");
5
+ var booleanCodec = {
6
+ fromDatabase: function (value) { return value === 'true'; },
7
+ toDatabase: function (value) { return String(value); },
8
+ };
9
+ (0, next_1.defineModel)({
10
+ codecs: { expiresAt: next_1.dateCodec },
11
+ indexes: [{ fields: ['userId'], name: 'idx_typed_session_user' }],
12
+ name: 'TypedSession',
13
+ });
14
+ (0, next_1.defineModel)({
15
+ codecs: {
16
+ // @ts-expect-error Codec keys must exist on the declared document type.
17
+ missing: next_1.dateCodec,
18
+ },
19
+ name: 'InvalidCodecKey',
20
+ });
21
+ (0, next_1.defineModel)({
22
+ codecs: {
23
+ // @ts-expect-error Codec input must match the declared field type.
24
+ expiresAt: booleanCodec,
25
+ },
26
+ name: 'InvalidCodecValue',
27
+ });
28
+ (0, next_1.defineModel)({
29
+ indexes: [
30
+ {
31
+ // @ts-expect-error Declared index fields are checked against the document type.
32
+ fields: ['missing'],
33
+ name: 'idx_invalid_field',
34
+ },
35
+ ],
36
+ name: 'InvalidTypedSession',
37
+ });
38
+ //# sourceMappingURL=next.types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"next.types.js","sourceRoot":"","sources":["../src/next.types.ts"],"names":[],"mappings":";;AAAA,6FAA6F;AAC7F,+BAA0D;AAO1D,IAAM,YAAY,GAAgC;IAC9C,YAAY,EAAE,UAAC,KAAK,IAAK,OAAA,KAAK,KAAK,MAAM,EAAhB,CAAgB;IACzC,UAAU,EAAE,UAAC,KAAK,IAAK,OAAA,MAAM,CAAC,KAAK,CAAC,EAAb,CAAa;CACvC,CAAC;AAEF,IAAA,kBAAW,EAAe;IACtB,MAAM,EAAE,EAAC,SAAS,EAAE,gBAAS,EAAC;IAC9B,OAAO,EAAE,CAAC,EAAC,MAAM,EAAE,CAAC,QAAQ,CAAC,EAAE,IAAI,EAAE,wBAAwB,EAAC,CAAC;IAC/D,IAAI,EAAE,cAAc;CACvB,CAAC,CAAC;AAEH,IAAA,kBAAW,EAAe;IACtB,MAAM,EAAE;QACJ,wEAAwE;QACxE,OAAO,EAAE,gBAAS;KACrB;IACD,IAAI,EAAE,iBAAiB;CAC1B,CAAC,CAAC;AAEH,IAAA,kBAAW,EAAe;IACtB,MAAM,EAAE;QACJ,mEAAmE;QACnE,SAAS,EAAE,YAAY;KAC1B;IACD,IAAI,EAAE,mBAAmB;CAC5B,CAAC,CAAC;AAEH,IAAA,kBAAW,EAAe;IACtB,OAAO,EAAE;QACL;YACI,gFAAgF;YAChF,MAAM,EAAE,CAAC,SAAS,CAAC;YACnB,IAAI,EAAE,mBAAmB;SAC5B;KACJ;IACD,IAAI,EAAE,qBAAqB;CAC9B,CAAC,CAAC","sourcesContent":["/* eslint-disable @typescript-eslint/ban-ts-comment -- this file verifies compiler errors. */\nimport {dateCodec, defineModel, FieldCodec} from './next';\n\ninterface TypedSession {\n expiresAt: Date;\n userId: string;\n}\n\nconst booleanCodec: FieldCodec<boolean, string> = {\n fromDatabase: (value) => value === 'true',\n toDatabase: (value) => String(value),\n};\n\ndefineModel<TypedSession>({\n codecs: {expiresAt: dateCodec},\n indexes: [{fields: ['userId'], name: 'idx_typed_session_user'}],\n name: 'TypedSession',\n});\n\ndefineModel<TypedSession>({\n codecs: {\n // @ts-expect-error Codec keys must exist on the declared document type.\n missing: dateCodec,\n },\n name: 'InvalidCodecKey',\n});\n\ndefineModel<TypedSession>({\n codecs: {\n // @ts-expect-error Codec input must match the declared field type.\n expiresAt: booleanCodec,\n },\n name: 'InvalidCodecValue',\n});\n\ndefineModel<TypedSession>({\n indexes: [\n {\n // @ts-expect-error Declared index fields are checked against the document type.\n fields: ['missing'],\n name: 'idx_invalid_field',\n },\n ],\n name: 'InvalidTypedSession',\n});\n"]}
@@ -0,0 +1,133 @@
1
+ # Document Modeling
2
+
3
+ CouchSet keeps document modeling explicit. Large application objects should not
4
+ be the documents that list pages paginate over. Use one model for lightweight
5
+ list and routing metadata, then keep the full payload in a separate document
6
+ that is fetched by id when a detail view, offline view, export, or worker needs
7
+ the whole object.
8
+
9
+ ## Large Documents
10
+
11
+ Prefer this read shape:
12
+
13
+ - Fetch large documents by id with `getById()` or `findDocById()`.
14
+ - Page smaller metadata documents with `page()` or `findMany()`.
15
+ - Denormalize the fields needed for cards, tables, filters, sort order, auth,
16
+ and cleanup onto the paged metadata document.
17
+ - Store the heavy nested state, snapshots, logs, source data, or arrays in a
18
+ companion model.
19
+ - Join or fetch the companion document only after the caller has selected the
20
+ specific item that needs it.
21
+
22
+ This keeps list queries fast and predictable. A list page should not read a
23
+ large payload only to render a title, status, timestamp, and a few counters.
24
+
25
+ ## Example
26
+
27
+ ```ts
28
+ import {Model} from 'couchset/next';
29
+
30
+ type ReportSummary = {
31
+ id: string;
32
+ tenantId: string;
33
+ payloadId: string;
34
+ title: string;
35
+ status: 'draft' | 'running' | 'complete';
36
+ updatedAt: Date;
37
+ itemCount: number;
38
+ errorCount: number;
39
+ };
40
+
41
+ type ReportPayload = {
42
+ id: string;
43
+ reportId: string;
44
+ tenantId: string;
45
+ sourceRows: unknown[];
46
+ generatedSections: unknown[];
47
+ auditLog: unknown[];
48
+ };
49
+
50
+ const reports = new Model('Report', {
51
+ indexes: [
52
+ {
53
+ name: 'idx_report_tenant_updated',
54
+ fields: ['tenantId', 'updatedAt'],
55
+ },
56
+ ],
57
+ });
58
+
59
+ const reportPayloads = new Model('ReportPayload');
60
+ ```
61
+
62
+ Page the lightweight model:
63
+
64
+ ```ts
65
+ const page = await reports.page<ReportSummary>({
66
+ select: [
67
+ 'id',
68
+ 'tenantId',
69
+ 'payloadId',
70
+ 'title',
71
+ 'status',
72
+ 'updatedAt',
73
+ 'itemCount',
74
+ 'errorCount',
75
+ ],
76
+ where: {tenantId: {$eq: tenantId}},
77
+ orderBy: {updatedAt: 'DESC'},
78
+ limit: 25,
79
+ });
80
+ ```
81
+
82
+ Fetch the heavy document by id only when needed:
83
+
84
+ ```ts
85
+ const summary = await reports.getById<ReportSummary>(reportId);
86
+ const payload = await reportPayloads.getById<ReportPayload>(summary.payloadId);
87
+ ```
88
+
89
+ Use stable id formulas so the relationship is obvious and easy to backfill:
90
+
91
+ ```ts
92
+ const reportId = 'report::123';
93
+ const payloadId = `report-payload::${reportId}`;
94
+ ```
95
+
96
+ ## Joining
97
+
98
+ CouchSet includes can join related documents by key, but large payload joins
99
+ should be reserved for focused detail reads or small result sets.
100
+
101
+ ```ts
102
+ const report = await reports.findOne<ReportSummary & {payload: ReportPayload}>({
103
+ where: {id: {$eq: reportId}},
104
+ include: [
105
+ {
106
+ as: 'payload',
107
+ key: 'payloadId',
108
+ model: reportPayloads,
109
+ optional: true,
110
+ },
111
+ ],
112
+ });
113
+ ```
114
+
115
+ For list pages, keep the companion model out of the query and rely on summary
116
+ fields instead.
117
+
118
+ ## Migrations
119
+
120
+ When splitting an existing large document:
121
+
122
+ - Add the summary fields to the lightweight model first.
123
+ - Backfill companion payload documents with deterministic ids.
124
+ - Keep ownership fields such as `tenantId`, `workspaceId`, or `userId` on both
125
+ documents when they are needed for authorization or cleanup.
126
+ - Keep lifecycle fields such as `createdAt`, `updatedAt`, `deleted`, and
127
+ `deletedAt` on both documents if each document can be cleaned up separately.
128
+ - Switch list reads to the lightweight model before removing legacy heavy
129
+ fields from the list path.
130
+
131
+ The split is a read-model decision, not a CouchSet requirement. Keep a single
132
+ document when callers normally need the whole object and the document remains
133
+ small enough for the expected list and query volume.
@@ -0,0 +1,81 @@
1
+ # CouchSet next primitives
2
+
3
+ `couchset/next` adds a client-owned API without changing the singleton-based `Model` and `couchset` APIs. The new client is useful when an application needs dependency injection, isolated tests, model manifests, or an administrative bootstrap connection.
4
+
5
+ ```ts
6
+ import {createCouchsetClient, dateCodec, defineModel} from 'couchset/next';
7
+
8
+ const sessions = defineModel<{id: string; userId: string; expiresAt: Date}>({
9
+ name: 'Session',
10
+ scope: 'auth',
11
+ collection: 'sessions',
12
+ codecs: {expiresAt: dateCodec},
13
+ indexes: [{name: 'idx_session_user', fields: ['userId']}],
14
+ });
15
+
16
+ const db = createCouchsetClient({
17
+ connectionString: process.env.COUCHBASE_URL,
18
+ bucketName: 'app',
19
+ username: process.env.COUCHBASE_USERNAME,
20
+ password: process.env.COUCHBASE_PASSWORD,
21
+ models: [sessions],
22
+ });
23
+ ```
24
+
25
+ `defineModel()` only describes metadata; `db.model(sessions)` only binds and registers the model. Neither operation creates Couchbase resources. Legacy `new Model()` remains supported and continues to use the existing singleton.
26
+
27
+ ## Provisioning and dynamic models
28
+
29
+ Run administrative DDL explicitly, with credentials that have `Manage Scopes` and query-index permissions:
30
+
31
+ ```ts
32
+ await db.ensureCollections(); // creates missing named scopes, then collections
33
+ await db.ensureIndexes(); // CREATE INDEX IF NOT EXISTS only
34
+
35
+ // An explicitly dynamic model can provision itself.
36
+ const reports = await db.registerModel(reportDefinition, {
37
+ provision: {collections: true, indexes: true, waitForIndexes: true},
38
+ });
39
+ ```
40
+
41
+ Collection creation is idempotent: concurrent already-exists responses are accepted, while existing scopes and collections are never updated, renamed, or dropped. The built-in `_default` scope and collection are not created. A named collection in `_default` is supported. Conflicting collection settings declared for the same target fail instead of silently choosing one.
42
+
43
+ ## Transactions and CAS
44
+
45
+ ```ts
46
+ await db.transaction(async (tx) => {
47
+ const session = tx.model(sessions);
48
+ const found = await session.getById(id);
49
+ if (found) await session.remove(found);
50
+ });
51
+ ```
52
+
53
+ Transaction-bound models use only the SDK transaction attempt context. Couchbase may retry the callback, so it must not send an email, webhook, or other non-idempotent external side effect. Perform that work after the transaction resolves, or use an outbox/idempotency key. Commit-ambiguous errors are surfaced to the caller; CouchSet does not claim success or rerun external work.
54
+
55
+ For an optimistic single-document workflow:
56
+
57
+ ```ts
58
+ const current = await model.getWithCas(id);
59
+ await model.replaceIfCas(id, nextValue, current.cas);
60
+
61
+ const outcome = await model.consumeOnce(id, current.cas);
62
+ // {status: 'consumed'} | {status: 'missing'} | {status: 'conflict'}
63
+ ```
64
+
65
+ `consumeOnce` issues exactly one conditional remove. It does not re-read and retry with a fresh CAS.
66
+
67
+ ## Index drift
68
+
69
+ `ensureIndexes()` remains intentionally create-only. It never compares, changes, drops, or rebuilds an existing index. Operators can instead review a plan:
70
+
71
+ ```ts
72
+ const plan = await db.planIndexes();
73
+ await db.applyIndexPlan(plan); // create missing/versioned replacement indexes and wait for online
74
+ await db.applyIndexPlan(plan, {dropReplaced: true}); // explicit old-index removal after review
75
+ ```
76
+
77
+ When a live definition drifts, the plan creates a versioned physical replacement and waits for it to become online before an old index can be dropped. This avoids an unindexed interval and makes destructive cleanup an affirmative operator action.
78
+
79
+ ## Tests
80
+
81
+ `createCouchsetTestFixture(client, definition)` provisions a unique named scope/collection and returns an explicit `cleanup()` helper. Use it in test setup/teardown; fixture cleanup is the only helper that drops a resource.
@@ -0,0 +1,2 @@
1
+ export * from '../dist/index';
2
+ export {default} from '../dist/index';
package/next/package.json CHANGED
@@ -1,4 +1,4 @@
1
1
  {
2
- "main": "../dist/index.js",
3
- "types": "../dist/index.d.ts"
2
+ "main": "./index.js",
3
+ "types": "./index.d.ts"
4
4
  }
package/package.json CHANGED
@@ -1,11 +1,54 @@
1
1
  {
2
2
  "name": "couchset",
3
- "version": "0.3.0",
3
+ "version": "0.4.1",
4
4
  "description": "Couchbase ORM",
5
5
  "private": false,
6
6
  "main": "dist/legacy/index.js",
7
7
  "types": "dist/legacy/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/legacy/index.d.ts",
11
+ "require": "./legacy/index.js",
12
+ "default": "./legacy/index.js"
13
+ },
14
+ "./next": {
15
+ "types": "./dist/index.d.ts",
16
+ "require": "./next/index.js",
17
+ "default": "./next/index.js"
18
+ },
19
+ "./next/index": {
20
+ "types": "./next/index.d.ts",
21
+ "require": "./next/index.js",
22
+ "default": "./next/index.js"
23
+ },
24
+ "./next/index.js": {
25
+ "types": "./next/index.d.ts",
26
+ "require": "./next/index.js",
27
+ "default": "./next/index.js"
28
+ },
29
+ "./legacy": {
30
+ "types": "./dist/legacy/index.d.ts",
31
+ "require": "./legacy/index.js",
32
+ "default": "./legacy/index.js"
33
+ },
34
+ "./legacy/index": {
35
+ "types": "./dist/legacy/index.d.ts",
36
+ "require": "./legacy/index.js",
37
+ "default": "./legacy/index.js"
38
+ },
39
+ "./legacy/index.js": {
40
+ "types": "./dist/legacy/index.d.ts",
41
+ "require": "./legacy/index.js",
42
+ "default": "./legacy/index.js"
43
+ },
44
+ "./register": "./register/index.js",
45
+ "./register/transpile-only": "./register/transpile-only.js",
46
+ "./register/type-check": "./register/type-check.js",
47
+ "./package.json": "./package.json",
48
+ "./*": "./*"
49
+ },
8
50
  "files": [
51
+ "CHANGELOG.md",
9
52
  "docs/",
10
53
  "dist/",
11
54
  "legacy/",
@@ -16,7 +59,9 @@
16
59
  "scripts": {
17
60
  "lint": "tslint \"src/**/*.ts\" --project tsconfig.json",
18
61
  "build": "rimraf dist && ./node_modules/.bin/tsc --skipLibCheck",
19
- "test": "mocha src/index.test.ts --exit",
62
+ "test": "npm run test:unit && npm run test:integration",
63
+ "test:unit": "mocha \"src/**/*.test.ts\" --ignore src/index.test.ts --ignore src/index.serverless.test.ts --exit",
64
+ "test:integration": "mocha src/index.test.ts --exit",
20
65
  "test:serverless": "mocha src/index.serverless.test.ts --exit",
21
66
  "prepublishOnly": "npm run build",
22
67
  "eslint": "eslint ./src --fix --ext=ts"
@@ -84,7 +129,7 @@
84
129
  "eslint-plugin-typescript": "^0.14.0",
85
130
  "husky": "^4.2.5",
86
131
  "lint-staged": "^10.1.7",
87
- "mocha": "^11.3.0",
132
+ "mocha": "^12.0.0",
88
133
  "prettier": "^2.0.5",
89
134
  "reflect-metadata": "^0.1.13",
90
135
  "rimraf": "^2.5.4",
@@ -99,7 +144,7 @@
99
144
  "couchbase-serverless": "^0.0.4",
100
145
  "debug": "^4.3.1",
101
146
  "lodash": "^4.18.1",
102
- "uuid": "^8.3.2"
147
+ "uuid": "^14.0.0"
103
148
  },
104
149
  "overrides": {
105
150
  "serialize-javascript": "^7.0.5",