From 15a2bfbe01456d89c1eb748f1cb4cdbad8c0ea6f Mon Sep 17 00:00:00 2001 From: Andrey Sobolev Date: Fri, 23 Feb 2024 13:45:07 +0700 Subject: [PATCH] UBERF-5694: Attempt to fix build cache Signed-off-by: Andrey Sobolev --- common/config/rush/command-line.json | 12 +-- common/config/rush/experiments.json | 2 +- dev/tool/package.json | 4 +- packages/collaborator-client/src/client.ts | 20 ++--- packages/collaborator-client/src/uri.ts | 6 +- packages/core/src/__tests__/memdb.test.ts | 10 +-- packages/core/src/client.ts | 50 ++++++------ packages/core/src/collaboration.ts | 12 +-- packages/core/src/component.ts | 2 +- packages/core/src/tx.ts | 38 ++++----- packages/core/src/utils.ts | 68 ++++++++-------- packages/model/src/dsl.ts | 84 +++++++++---------- packages/platform-rig/bin/compile.js | 16 ++-- packages/platform-rig/bin/format.js | 4 +- packages/platform/src/resource.ts | 12 +-- packages/query/src/__tests__/query.test.ts | 2 +- packages/query/src/index.ts | 94 +++++++++++----------- plugins/client-resources/src/connection.ts | 50 ++++++------ plugins/client-resources/src/index.ts | 8 +- plugins/view/src/index.ts | 4 +- plugins/view/src/types.ts | 28 +++---- rush.json | 2 +- server/ws/src/client.ts | 20 ++--- 23 files changed, 276 insertions(+), 272 deletions(-) diff --git a/common/config/rush/command-line.json b/common/config/rush/command-line.json index 8e1d1f07f71..ad8584aa408 100644 --- a/common/config/rush/command-line.json +++ b/common/config/rush/command-line.json @@ -86,16 +86,18 @@ ], "commands": [ { - "commandKind": "bulk", + "commandKind": "phased", "name": "build:watch", "summary": "Build and watch", + "phases": ["_phase:build", "_phase:validate"], "description": "Perform build with tsc and watch for changes with rush", "enableParallelism": true, "incremental": true, - "ignoreMissingScript": true, - "watchForChanges": true, "safeForSimultaneousRushProcesses": true, - "disableBuildCache": false + "watchOptions": { + "alwaysWatch": true, + "watchPhases": ["_phase:build", "_phase:validate"] + } }, { "commandKind": "bulk", @@ -130,7 +132,7 @@ "phases": ["_phase:validate"], "summary": "validate", "enableParallelism": true, - "incremental": true + "incremental": true }, { "commandKind": "phased", diff --git a/common/config/rush/experiments.json b/common/config/rush/experiments.json index 56160d97174..b8710566880 100644 --- a/common/config/rush/experiments.json +++ b/common/config/rush/experiments.json @@ -34,7 +34,7 @@ * If true, build caching will respect the allowWarningsInSuccessfulBuild flag and cache builds with warnings. * This will not replay warnings from the cached build. */ - // "buildCacheWithAllowWarningsInSuccessfulBuild": true, + "buildCacheWithAllowWarningsInSuccessfulBuild": true, /** * If true, the phased commands feature is enabled. To use this feature, create a "phased" command diff --git a/dev/tool/package.json b/dev/tool/package.json index ca76bff9947..8b787124a35 100644 --- a/dev/tool/package.json +++ b/dev/tool/package.json @@ -18,8 +18,8 @@ "docker:build": "docker build -t hardcoreeng/tool .", "docker:staging": "../../common/scripts/docker_tag.sh hardcoreeng/tool staging", "docker:push": "../../common/scripts/docker_tag.sh hardcoreeng/tool", - "run-local": "cross-env SERVER_SECRET=secret MINIO_ACCESS_KEY=minioadmin MINIO_SECRET_KEY=minioadmin MINIO_ENDPOINT=localhost MONGO_URL=mongodb://localhost:27017 TRANSACTOR_URL=ws://localhost:3333 TELEGRAM_DATABASE=telegram-service ELASTIC_URL=http://localhost:9200 REKONI_URL=http://localhost:4004 MODEL_VERSION=$(node ../../common/scripts/show_version.js) GIT_REVISION=$(git describe --all --long) node -r ts-node/register --max-old-space-size=18000 ./src/__start.ts", - "run": "cross-env node -r ts-node/register --max-old-space-size=8000 MODEL_VERSION=$(node ../../common/scripts/show_version.js) ./src/__start.ts", + "run-local": "rush bundle --to @hcengineering/tool >/dev/null && cross-env SERVER_SECRET=secret MINIO_ACCESS_KEY=minioadmin MINIO_SECRET_KEY=minioadmin MINIO_ENDPOINT=localhost MONGO_URL=mongodb://localhost:27017 TRANSACTOR_URL=ws://localhost:3333 TELEGRAM_DATABASE=telegram-service ELASTIC_URL=http://localhost:9200 REKONI_URL=http://localhost:4004 MODEL_VERSION=$(node ../../common/scripts/show_version.js) GIT_REVISION=$(git describe --all --long) node --max-old-space-size=18000 ./bundle/bundle.js", + "run": "rush bundle --to @hcengineering/tool >/dev/null && cross-env node --max-old-space-size=8000 ./bundle/bundle.js", "upgrade": "rushx run-local upgrade", "format": "format src", "test": "jest --passWithNoTests --silent --forceExit", diff --git a/packages/collaborator-client/src/client.ts b/packages/collaborator-client/src/client.ts index 28aa40b4288..68d0914ea2e 100644 --- a/packages/collaborator-client/src/client.ts +++ b/packages/collaborator-client/src/client.ts @@ -118,7 +118,7 @@ export interface CollaboratorClient { } /** @public */ -export function getClient ( +export function getClient( hierarchy: Hierarchy, workspaceId: WorkspaceId, token: string, @@ -128,19 +128,19 @@ export function getClient ( } class CollaboratorClientImpl implements CollaboratorClient { - constructor ( + constructor( private readonly hierarchy: Hierarchy, private readonly workspace: WorkspaceId, private readonly token: string, private readonly collaboratorUrl: string ) {} - initialContentId (workspace: string, classId: Ref>, docId: Ref, attribute: string): DocumentURI { + initialContentId(workspace: string, classId: Ref>, docId: Ref, attribute: string): DocumentURI { const domain = this.hierarchy.getDomain(classId) return mongodbDocumentUri(workspace, domain, docId, attribute) } - private async rpc (method: string, payload: any): Promise { + private async rpc(method: string, payload: any): Promise { const url = concatLink(this.collaboratorUrl, '/rpc') const res = await fetch(url, { @@ -161,7 +161,7 @@ class CollaboratorClientImpl implements CollaboratorClient { return result } - async getContent (collaborativeDoc: CollaborativeDoc, field: string): Promise { + async getContent(collaborativeDoc: CollaborativeDoc, field: string): Promise { const workspace = this.workspace.name const documentId = collaborativeDocumentUri(workspace, collaborativeDoc) @@ -171,7 +171,7 @@ class CollaboratorClientImpl implements CollaboratorClient { return res.html ?? '' } - async updateContent (collaborativeDoc: CollaborativeDoc, field: string, value: Markup): Promise { + async updateContent(collaborativeDoc: CollaborativeDoc, field: string, value: Markup): Promise { const workspace = this.workspace.name const documentId = collaborativeDocumentUri(workspace, collaborativeDoc) @@ -179,7 +179,7 @@ class CollaboratorClientImpl implements CollaboratorClient { await this.rpc('updateContent', payload) } - async copyContent (collaborativeDoc: CollaborativeDoc, sourceField: string, targetField: string): Promise { + async copyContent(collaborativeDoc: CollaborativeDoc, sourceField: string, targetField: string): Promise { const workspace = this.workspace.name const documentId = collaborativeDocumentUri(workspace, collaborativeDoc) @@ -187,7 +187,7 @@ class CollaboratorClientImpl implements CollaboratorClient { await this.rpc('copyContent', payload) } - async branch (source: CollaborativeDoc, target: CollaborativeDoc): Promise { + async branch(source: CollaborativeDoc, target: CollaborativeDoc): Promise { const workspace = this.workspace.name const sourceDocumentId = collaborativeDocumentUri(workspace, source) const targetDocumentId = collaborativeDocumentUri(workspace, target) @@ -196,7 +196,7 @@ class CollaboratorClientImpl implements CollaboratorClient { await this.rpc('branchDocument', payload) } - async remove (collaborativeDoc: CollaborativeDoc): Promise { + async remove(collaborativeDoc: CollaborativeDoc): Promise { const workspace = this.workspace.name const documentId = collaborativeDocumentUri(workspace, collaborativeDoc) @@ -204,7 +204,7 @@ class CollaboratorClientImpl implements CollaboratorClient { await this.rpc('removeDocument', payload) } - async snapshot ( + async snapshot( collaborativeDoc: CollaborativeDoc, params: CollaborativeDocSnapshotParams ): Promise { diff --git a/packages/collaborator-client/src/uri.ts b/packages/collaborator-client/src/uri.ts index f8dec9003f7..e7a9ced9f3c 100644 --- a/packages/collaborator-client/src/uri.ts +++ b/packages/collaborator-client/src/uri.ts @@ -17,12 +17,12 @@ import { Class, CollaborativeDoc, Doc, Domain, Ref, parseCollaborativeDoc } from export type DocumentURI = string & { __documentUri: true } -export function collaborativeDocumentUri (workspaceUrl: string, docId: CollaborativeDoc): DocumentURI { +export function collaborativeDocumentUri(workspaceUrl: string, docId: CollaborativeDoc): DocumentURI { const { documentId, versionId } = parseCollaborativeDoc(docId) return `minio://${workspaceUrl}/${documentId}/${versionId}` as DocumentURI } -export function platformDocumentUri ( +export function platformDocumentUri( workspaceUrl: string, objectClass: Ref>, objectId: Ref, @@ -31,7 +31,7 @@ export function platformDocumentUri ( return `platform://${workspaceUrl}/${objectClass}/${objectId}/${objectAttr}` as DocumentURI } -export function mongodbDocumentUri ( +export function mongodbDocumentUri( workspaceUrl: string, domain: Domain, docId: Ref, diff --git a/packages/core/src/__tests__/memdb.test.ts b/packages/core/src/__tests__/memdb.test.ts index dcb73fa91d7..92da4e7cd0c 100644 --- a/packages/core/src/__tests__/memdb.test.ts +++ b/packages/core/src/__tests__/memdb.test.ts @@ -36,11 +36,11 @@ const txes = genMinModel() class ClientModel extends ModelDb implements Client { notify?: ((...tx: Tx[]) => void) | undefined - getHierarchy (): Hierarchy { + getHierarchy(): Hierarchy { return this.hierarchy } - getModel (): ModelDb { + getModel(): ModelDb { return this } @@ -52,14 +52,14 @@ class ClientModel extends ModelDb implements Client { return (await this.findAll(_class, query, options)).shift() } - async searchFulltext (query: SearchQuery, options: SearchOptions): Promise { + async searchFulltext(query: SearchQuery, options: SearchOptions): Promise { return { docs: [] } } - async close (): Promise {} + async close(): Promise {} } -async function createModel (): Promise<{ model: ClientModel, hierarchy: Hierarchy, txDb: TxDb }> { +async function createModel(): Promise<{ model: ClientModel; hierarchy: Hierarchy; txDb: TxDb }> { const hierarchy = new Hierarchy() for (const tx of txes) { hierarchy.tx(tx) diff --git a/packages/core/src/client.ts b/packages/core/src/client.ts index 8c0e600a0f1..11499d815d5 100644 --- a/packages/core/src/client.ts +++ b/packages/core/src/client.ts @@ -46,7 +46,7 @@ export interface Client extends Storage, FulltextStorage { close: () => Promise } -export type MeasureDoneOperation = () => Promise<{ time: number, serverTime: number }> +export type MeasureDoneOperation = () => Promise<{ time: number; serverTime: number }> export interface MeasureClient extends Client { // Will perform on server operation measure and will return a local client time and on server time @@ -101,18 +101,18 @@ class ClientImpl implements AccountClient, BackupClient, MeasureClient { notify?: (...tx: Tx[]) => void hierarchy!: Hierarchy model!: ModelDb - constructor (private readonly conn: ClientConnection) {} + constructor(private readonly conn: ClientConnection) {} - setModel (hierarchy: Hierarchy, model: ModelDb): void { + setModel(hierarchy: Hierarchy, model: ModelDb): void { this.hierarchy = hierarchy this.model = model } - getHierarchy (): Hierarchy { + getHierarchy(): Hierarchy { return this.hierarchy } - getModel (): ModelDb { + getModel(): ModelDb { return this.model } @@ -136,7 +136,7 @@ class ClientImpl implements AccountClient, BackupClient, MeasureClient { return toFindResult(result, data.total) } - async searchFulltext (query: SearchQuery, options: SearchOptions): Promise { + async searchFulltext(query: SearchQuery, options: SearchOptions): Promise { return await this.conn.searchFulltext(query, options) } @@ -148,7 +148,7 @@ class ClientImpl implements AccountClient, BackupClient, MeasureClient { return (await this.findAll(_class, query, { ...options, limit: 1 }))[0] } - async tx (tx: Tx): Promise { + async tx(tx: Tx): Promise { if (tx.objectSpace === core.space.Model) { this.hierarchy.tx(tx) await this.model.tx(tx) @@ -160,11 +160,11 @@ class ClientImpl implements AccountClient, BackupClient, MeasureClient { return result } - async measure (operationName: string): Promise { + async measure(operationName: string): Promise { return await this.conn.measure(operationName) } - async updateFromRemote (...tx: Tx[]): Promise { + async updateFromRemote(...tx: Tx[]): Promise { for (const t of tx) { if (t.objectSpace === core.space.Model) { this.hierarchy.tx(t) @@ -174,31 +174,31 @@ class ClientImpl implements AccountClient, BackupClient, MeasureClient { this.notify?.(...tx) } - async close (): Promise { + async close(): Promise { await this.conn.close() } - async loadChunk (domain: Domain, idx?: number | undefined): Promise { + async loadChunk(domain: Domain, idx?: number | undefined): Promise { return await this.conn.loadChunk(domain, idx) } - async closeChunk (idx: number): Promise { + async closeChunk(idx: number): Promise { await this.conn.closeChunk(idx) } - async loadDocs (domain: Domain, docs: Ref[]): Promise { + async loadDocs(domain: Domain, docs: Ref[]): Promise { return await this.conn.loadDocs(domain, docs) } - async upload (domain: Domain, docs: Doc[]): Promise { + async upload(domain: Domain, docs: Doc[]): Promise { await this.conn.upload(domain, docs) } - async clean (domain: Domain, docs: Ref[]): Promise { + async clean(domain: Domain, docs: Ref[]): Promise { await this.conn.clean(domain, docs) } - async getAccount (): Promise { + async getAccount(): Promise { return await this.conn.getAccount() } } @@ -214,7 +214,7 @@ export interface TxPersistenceStore { /** * @public */ -export async function createClient ( +export async function createClient( connect: (txHandler: TxHandler) => Promise, // If set will build model with only allowed plugins. allowedPlugins?: Plugin[], @@ -230,7 +230,7 @@ export async function createClient ( let lastTx: number - function txHandler (...tx: Tx[]): void { + function txHandler(...tx: Tx[]): void { if (tx == null || tx.length === 0) { return } @@ -313,7 +313,7 @@ export async function createClient ( return client } -async function tryLoadModel ( +async function tryLoadModel( conn: ClientConnection, reload: boolean, persistence?: TxPersistenceStore @@ -346,7 +346,7 @@ async function tryLoadModel ( } // Ignore Employee accounts. -function isPersonAccount (tx: Tx): boolean { +function isPersonAccount(tx: Tx): boolean { return ( (tx._class === core.class.TxCreateDoc || tx._class === core.class.TxUpdateDoc || @@ -356,7 +356,7 @@ function isPersonAccount (tx: Tx): boolean { ) } -async function loadModel ( +async function loadModel( conn: ClientConnection, allowedPlugins: Plugin[] | undefined, configs: Map, PluginConfiguration>, @@ -385,7 +385,7 @@ async function loadModel ( return modelResponse } -async function buildModel ( +async function buildModel( modelResponse: LoadModelResponse, allowedPlugins: Plugin[] | undefined, configs: Map, PluginConfiguration>, @@ -430,7 +430,7 @@ async function buildModel ( } } -function getLastTxTime (txes: Tx[]): number { +function getLastTxTime(txes: Tx[]): number { let lastTxTime = 0 for (const tx of txes) { if (tx.modifiedOn > lastTxTime) { @@ -440,7 +440,7 @@ function getLastTxTime (txes: Tx[]): number { return lastTxTime } -function fillConfiguration (systemTx: Tx[], configs: Map, PluginConfiguration>): void { +function fillConfiguration(systemTx: Tx[], configs: Map, PluginConfiguration>): void { for (const t of systemTx) { if (t._class === core.class.TxCreateDoc) { const ct = t as TxCreateDoc @@ -459,7 +459,7 @@ function fillConfiguration (systemTx: Tx[], configs: Map, PluginConfiguration>, systemTx: Tx[] diff --git a/packages/core/src/collaboration.ts b/packages/core/src/collaboration.ts index 214b5e5a525..922b25cf654 100644 --- a/packages/core/src/collaboration.ts +++ b/packages/core/src/collaboration.ts @@ -33,12 +33,12 @@ export type CollaborativeDocVersion = string | typeof CollaborativeDocVersionHea export const CollaborativeDocVersionHead = 'HEAD' /** @public */ -export function getCollaborativeDocId (objectId: Ref, objectAttr?: string | undefined): string { +export function getCollaborativeDocId(objectId: Ref, objectAttr?: string | undefined): string { return objectAttr !== undefined && objectAttr !== '' ? `${objectId}%${objectAttr}` : `${objectId}` } /** @public */ -export function getCollaborativeDoc (documentId: string): CollaborativeDoc { +export function getCollaborativeDoc(documentId: string): CollaborativeDoc { return formatCollaborativeDoc({ documentId, versionId: CollaborativeDocVersionHead, @@ -54,18 +54,18 @@ export interface CollaborativeDocData { } /** @public */ -export function parseCollaborativeDoc (id: CollaborativeDoc): CollaborativeDocData { +export function parseCollaborativeDoc(id: CollaborativeDoc): CollaborativeDocData { const [documentId, versionId, revisionId] = id.split(':') return { documentId, versionId, revisionId: revisionId ?? versionId } } /** @public */ -export function formatCollaborativeDoc ({ documentId, versionId, revisionId }: CollaborativeDocData): CollaborativeDoc { +export function formatCollaborativeDoc({ documentId, versionId, revisionId }: CollaborativeDocData): CollaborativeDoc { return `${documentId}:${versionId}:${revisionId}` as CollaborativeDoc } /** @public */ -export function formatCollaborativeDocVersion ({ +export function formatCollaborativeDocVersion({ documentId, versionId }: Omit): CollaborativeDoc { @@ -73,7 +73,7 @@ export function formatCollaborativeDocVersion ({ } /** @public */ -export function toCollaborativeDocVersion (collaborativeDoc: CollaborativeDoc, versionId: string): CollaborativeDoc { +export function toCollaborativeDocVersion(collaborativeDoc: CollaborativeDoc, versionId: string): CollaborativeDoc { const { documentId } = parseCollaborativeDoc(collaborativeDoc) return formatCollaborativeDocVersion({ documentId, versionId }) } diff --git a/packages/core/src/component.ts b/packages/core/src/component.ts index a72ab3e47ba..06bb80ebdba 100644 --- a/packages/core/src/component.ts +++ b/packages/core/src/component.ts @@ -147,7 +147,7 @@ export default plugin(coreId, { }, status: { ObjectNotFound: '' as StatusCode<{ _id: Ref }>, - ItemNotFound: '' as StatusCode<{ _id: Ref, _localId: string }>, + ItemNotFound: '' as StatusCode<{ _id: Ref; _localId: string }>, InvalidProduct: '' as StatusCode<{ productId: string }> }, version: { diff --git a/packages/core/src/tx.ts b/packages/core/src/tx.ts index f2f1ad17b2a..7d08f1ab88c 100644 --- a/packages/core/src/tx.ts +++ b/packages/core/src/tx.ts @@ -149,15 +149,15 @@ export interface TxApplyResult { * @public */ export type MixinData = Omit & -PushOptions> & -IncOptions> + PushOptions> & + IncOptions> /** * @public */ export type MixinUpdate = Partial> & -PushOptions> & -IncOptions> + PushOptions> & + IncOptions> /** * Define Create/Update for mixin attributes. @@ -295,11 +295,11 @@ export interface SpaceUpdate { * @public */ export type DocumentUpdate = Partial> & -PushOptions & -SetEmbeddedOptions & -PushMixinOptions & -IncOptions & -SpaceUpdate + PushOptions & + SetEmbeddedOptions & + PushMixinOptions & + IncOptions & + SpaceUpdate /** * @public @@ -330,7 +330,7 @@ export interface WithTx { * @public */ export abstract class TxProcessor implements WithTx { - async tx (...txes: Tx[]): Promise { + async tx(...txes: Tx[]): Promise { const result: TxResult[] = [] for (const tx of txes) { switch (tx._class) { @@ -413,7 +413,7 @@ export abstract class TxProcessor implements WithTx { let createTx = txes.find((tx) => tx._class === core.class.TxCreateDoc) if (createTx === undefined) { const collectionTxes = txes.filter((tx) => tx._class === core.class.TxCollectionCUD) as Array< - TxCollectionCUD + TxCollectionCUD > const collectionCreateTx = collectionTxes.find((p) => p.tx._class === core.class.TxCreateDoc) if (collectionCreateTx === undefined) return @@ -436,7 +436,7 @@ export abstract class TxProcessor implements WithTx { return doc as D } - static extractTx (tx: Tx): Tx { + static extractTx(tx: Tx): Tx { if (tx._class === core.class.TxCollectionCUD) { const ctx = tx as TxCollectionCUD if (ctx.tx._class === core.class.TxCreateDoc) { @@ -468,12 +468,12 @@ export abstract class TxProcessor implements WithTx { return false } - protected abstract txCreateDoc (tx: TxCreateDoc): Promise - protected abstract txUpdateDoc (tx: TxUpdateDoc): Promise - protected abstract txRemoveDoc (tx: TxRemoveDoc): Promise - protected abstract txMixin (tx: TxMixin): Promise + protected abstract txCreateDoc(tx: TxCreateDoc): Promise + protected abstract txUpdateDoc(tx: TxUpdateDoc): Promise + protected abstract txRemoveDoc(tx: TxRemoveDoc): Promise + protected abstract txMixin(tx: TxMixin): Promise - protected txCollectionCUD (tx: TxCollectionCUD): Promise { + protected txCollectionCUD(tx: TxCollectionCUD): Promise { // We need update only create transactions to contain attached, attachedToClass. if (tx.tx._class === core.class.TxCreateDoc) { const createTx = tx.tx as TxCreateDoc @@ -497,7 +497,7 @@ export abstract class TxProcessor implements WithTx { */ export class TxFactory { private readonly txSpace: Ref - constructor ( + constructor( readonly account: Ref, readonly isDerived: boolean = false ) { @@ -614,7 +614,7 @@ export class TxFactory { } } - createTxApplyIf ( + createTxApplyIf( space: Ref, scope: string, match: DocumentClassQuery[], diff --git a/packages/core/src/utils.ts b/packages/core/src/utils.ts index 5f55cad8b55..808407fe5b9 100644 --- a/packages/core/src/utils.ts +++ b/packages/core/src/utils.ts @@ -20,7 +20,7 @@ import { Hierarchy } from './hierarchy' import { isPredicate } from './predicate' import { DocumentQuery, FindResult } from './storage' -function toHex (value: number, chars: number): string { +function toHex(value: number, chars: number): string { const result = value.toString(16) if (result.length < chars) { return '0'.repeat(chars - result.length) + result @@ -31,12 +31,12 @@ function toHex (value: number, chars: number): string { let counter = (Math.random() * (1 << 24)) | 0 const random = toHex((Math.random() * (1 << 24)) | 0, 6) + toHex((Math.random() * (1 << 16)) | 0, 4) -function timestamp (): string { +function timestamp(): string { const time = (Date.now() / 1000) | 0 return toHex(time, 8) } -function count (): string { +function count(): string { const val = counter++ & 0xffffff return toHex(val, 6) } @@ -45,7 +45,7 @@ function count (): string { * @public * @returns */ -export function generateId (join: string = ''): Ref { +export function generateId(join: string = ''): Ref { return (timestamp() + join + random + join + count()) as Ref } @@ -55,7 +55,7 @@ let currentAccount: Account * @public * @returns */ -export function getCurrentAccount (): Account { +export function getCurrentAccount(): Account { return currentAccount } @@ -63,20 +63,20 @@ export function getCurrentAccount (): Account { * @public * @param account - */ -export function setCurrentAccount (account: Account): void { +export function setCurrentAccount(account: Account): void { currentAccount = account } /** * @public */ -export function escapeLikeForRegexp (value: string): string { +export function escapeLikeForRegexp(value: string): string { return value.replace(/[-/\\^$*+?.()|[\]{}]/g, '\\$&') } /** * @public */ -export function toFindResult (docs: T[], total?: number): FindResult { +export function toFindResult(docs: T[], total?: number): FindResult { const length = total ?? docs.length return Object.assign(docs, { total: length }) } @@ -102,7 +102,7 @@ export interface WorkspaceIdWithUrl extends WorkspaceId { * * Combine workspace with productId, if not equal '' */ -export function getWorkspaceId (workspace: string, productId: string = ''): WorkspaceId { +export function getWorkspaceId(workspace: string, productId: string = ''): WorkspaceId { return { name: workspace, productId @@ -112,7 +112,7 @@ export function getWorkspaceId (workspace: string, productId: string = ''): Work /** * @public */ -export function toWorkspaceString (id: WorkspaceId, sep = '@'): string { +export function toWorkspaceString(id: WorkspaceId, sep = '@'): string { return id.name + (id.productId === '' ? '' : sep + id.productId) } @@ -132,13 +132,13 @@ export interface IndexKeyOptions { * @public */ -export function docUpdKey (name: string, opt?: IndexKeyOptions): string { +export function docUpdKey(name: string, opt?: IndexKeyOptions): string { return attributesPrefix + docKey(name, opt) } /** * @public */ -export function docKey (name: string, opt?: IndexKeyOptions): string { +export function docKey(name: string, opt?: IndexKeyOptions): string { const extra = opt?.extra !== undefined && opt?.extra?.length > 0 ? `#${opt.extra?.join('#') ?? ''}` : '' return opt?._class === undefined ? name : `${opt?._class}%${name}${extra}` } @@ -146,7 +146,7 @@ export function docKey (name: string, opt?: IndexKeyOptions): string { /** * @public */ -export function extractDocKey (key: string): { +export function extractDocKey(key: string): { _class?: Ref> attr: string docId?: Ref @@ -180,7 +180,7 @@ export function extractDocKey (key: string): { /** * @public */ -export function isFullTextAttribute (attr: AnyAttribute): boolean { +export function isFullTextAttribute(attr: AnyAttribute): boolean { return ( attr.index === IndexKind.FullText || attr.type._class === core.class.TypeAttachment || @@ -192,7 +192,7 @@ export function isFullTextAttribute (attr: AnyAttribute): boolean { /** * @public */ -export function isIndexedAttribute (attr: AnyAttribute): boolean { +export function isIndexedAttribute(attr: AnyAttribute): boolean { return attr.index === IndexKind.Indexed || attr.index === IndexKind.IndexedDsc } @@ -204,14 +204,14 @@ export interface IdMap extends Map, T> {} /** * @public */ -export function toIdMap (arr: T[]): IdMap { +export function toIdMap(arr: T[]): IdMap { return new Map(arr.map((p) => [p._id, p])) } /** * @public */ -export function concatLink (host: string, path: string): string { +export function concatLink(host: string, path: string): string { if (!host.endsWith('/') && !path.startsWith('/')) { return `${host}/${path}` } else if (host.endsWith('/') && path.startsWith('/')) { @@ -225,7 +225,7 @@ export function concatLink (host: string, path: string): string { /** * @public */ -export function fillDefaults ( +export function fillDefaults( hierarchy: Hierarchy, object: DocData | T, _class: Ref> @@ -247,7 +247,7 @@ export function fillDefaults ( * @public */ export class AggregateValueData { - constructor ( + constructor( readonly name: string, readonly _id: Ref, readonly space: Ref, @@ -255,7 +255,7 @@ export class AggregateValueData { readonly category?: Ref ) {} - getRank (): string { + getRank(): string { return this.rank ?? '' } } @@ -264,7 +264,7 @@ export class AggregateValueData { * @public */ export class AggregateValue { - constructor ( + constructor( readonly name: string | undefined, readonly values: AggregateValueData[] ) {} @@ -281,23 +281,23 @@ export type CategoryType = number | string | undefined | Ref | AggregateVal export class DocManager { protected readonly byId: IdMap - constructor (protected readonly docs: Doc[]) { + constructor(protected readonly docs: Doc[]) { this.byId = toIdMap(docs) } - get (ref: Ref): Doc | undefined { + get(ref: Ref): Doc | undefined { return this.byId.get(ref) } - getDocs (): Doc[] { + getDocs(): Doc[] { return this.docs } - getIdMap (): IdMap { + getIdMap(): IdMap { return this.byId } - filter (predicate: (value: Doc) => boolean): Doc[] { + filter(predicate: (value: Doc) => boolean): Doc[] { return this.docs.filter(predicate) } } @@ -314,7 +314,7 @@ export class RateLimiter { queue: (() => Promise)[] = [] - constructor (rate: number) { + constructor(rate: number) { this.rate = rate } @@ -341,12 +341,12 @@ export class RateLimiter { } } - async waitProcessing (): Promise { + async waitProcessing(): Promise { await Promise.race(this.processingQueue.values()) } } -export function mergeQueries (query1: DocumentQuery, query2: DocumentQuery): DocumentQuery { +export function mergeQueries(query1: DocumentQuery, query2: DocumentQuery): DocumentQuery { const keys1 = Object.keys(query1) const keys2 = Object.keys(query2) @@ -372,7 +372,7 @@ export function mergeQueries (query1: DocumentQuery, query2: D return query } -function mergeField (field1: any, field2: any): any | undefined { +function mergeField(field1: any, field2: any): any | undefined { // this is a special predicate that causes query never return any docs // it is used in cases when queries intersection is empty const never = { $in: [] } @@ -432,7 +432,7 @@ function mergeField (field1: any, field2: any): any | undefined { } } -function mergePredicateWithPredicate (predicate: string, val1: any, val2: any): any | undefined { +function mergePredicateWithPredicate(predicate: string, val1: any, val2: any): any | undefined { if (val1 === undefined) return val2 if (val2 === undefined) return val1 @@ -453,7 +453,7 @@ function mergePredicateWithPredicate (predicate: string, val1: any, val2: any): return val1 } -function mergePredicateWithValue (predicate: string, val1: any, val2: any): any | undefined { +function mergePredicateWithValue(predicate: string, val1: any, val2: any): any | undefined { switch (predicate) { case '$in': return Array.isArray(val1) && val1.includes(val2) ? val2 : undefined @@ -477,7 +477,7 @@ function mergePredicateWithValue (predicate: string, val1: any, val2: any): any return val2 } -function getInNiN (query1: any, query2: any): any { +function getInNiN(query1: any, query2: any): any { const aIn = typeof query1 === 'object' && '$in' in query1 ? query1.$in : undefined const bIn = typeof query2 === 'object' && '$in' in query2 ? query2.$in : undefined const aNIn = @@ -511,7 +511,7 @@ function getInNiN (query1: any, query2: any): any { return {} } -export function cutObjectArray (obj: any): any { +export function cutObjectArray(obj: any): any { const r = {} for (const key of Object.keys(obj)) { if (Array.isArray(obj[key])) { diff --git a/packages/model/src/dsl.ts b/packages/model/src/dsl.ts index 7e87d833447..3b71d76e1f7 100644 --- a/packages/model/src/dsl.ts +++ b/packages/model/src/dsl.ts @@ -55,7 +55,7 @@ import toposort from 'toposort' const targets = new Map>() -function setIndex (target: any, property: string, index: IndexKind): void { +function setIndex(target: any, property: string, index: IndexKind): void { let indexes = targets.get(target) if (indexes === undefined) { indexes = new Map() @@ -64,7 +64,7 @@ function setIndex (target: any, property: string, index: IndexKind): void { indexes.set(property, index) } -function getIndex (target: any, property: string): IndexKind | undefined { +function getIndex(target: any, property: string): IndexKind | undefined { return targets.get(target)?.get(property) } @@ -84,7 +84,7 @@ interface ClassTxes { const transactions = new Map() -function getTxes (target: any): ClassTxes { +function getTxes(target: any): ClassTxes { const txes = transactions.get(target) if (txes === undefined) { const txes = { txes: [] } as unknown as ClassTxes @@ -95,7 +95,7 @@ function getTxes (target: any): ClassTxes { } const attributes = new Map>>() -function setAttr (target: any, prop: string, key: string, value: any): void { +function setAttr(target: any, prop: string, key: string, value: any): void { const props = attributes.get(target) ?? new Map>() const attrs = props.get(prop) ?? {} attrs[key] = value @@ -104,7 +104,7 @@ function setAttr (target: any, prop: string, key: string, value: any): void { attributes.set(target, props) } -function clearAttrs (target: any, prop: string): void { +function clearAttrs(target: any, prop: string): void { const props = attributes.get(target) props?.delete(prop) @@ -113,7 +113,7 @@ function clearAttrs (target: any, prop: string): void { } } -function getAttrs (target: any, prop: string): Record { +function getAttrs(target: any, prop: string): Record { return attributes.get(target)?.get(prop) ?? {} } @@ -124,7 +124,7 @@ function getAttrs (target: any, prop: string): Record { * @param icon - * @returns */ -export function Prop (type: Type, label: IntlString, extra: Partial> = {}) { +export function Prop(type: Type, label: IntlString, extra: Partial> = {}) { return function (target: any, propertyKey: string): void { const txes = getTxes(target) const tx: TxCreateDoc> = { @@ -156,7 +156,7 @@ export function Prop (type: Type, label: IntlString, extra: Partia /** * @public */ -export function Hidden () { +export function Hidden() { return function (target: any, propertyKey: string): void { setAttr(target, propertyKey, 'hidden', true) } @@ -165,7 +165,7 @@ export function Hidden () { /** * @public */ -export function ReadOnly () { +export function ReadOnly() { return function (target: any, propertyKey: string): void { setAttr(target, propertyKey, 'readonly', true) } @@ -174,7 +174,7 @@ export function ReadOnly () { /** * @public */ -export function Index (kind: IndexKind) { +export function Index(kind: IndexKind) { return function (target: any, propertyKey: string): void { setIndex(target, propertyKey, kind) } @@ -183,13 +183,13 @@ export function Index (kind: IndexKind) { /** * @public */ -export function Model ( +export function Model( _class: Ref>, _extends: Ref>, domain?: Domain, _implements?: Ref>[] ) { - return function classDecorator T> (constructor: C): void { + return function classDecorator T>(constructor: C): void { const txes = getTxes(constructor.prototype) txes._id = _class txes.extends = _class !== core.class.Obj ? _extends : undefined @@ -202,8 +202,8 @@ export function Model ( /** * @public */ -export function Implements (_interface: Ref>, _extends?: Ref>[]) { - return function classDecorator T> (constructor: C): void { +export function Implements(_interface: Ref>, _extends?: Ref>[]) { + return function classDecorator T>(constructor: C): void { const txes = getTxes(constructor.prototype) txes._id = _interface txes.implements = _extends @@ -214,8 +214,8 @@ export function Implements (_interface: Ref>, _exten /** * @public */ -export function Mixin (_class: Ref>, _extends: Ref>) { - return function classDecorator T> (constructor: C): void { +export function Mixin(_class: Ref>, _extends: Ref>) { + return function classDecorator T>(constructor: C): void { const txes = getTxes(constructor.prototype) txes._id = _class txes.extends = _extends @@ -229,14 +229,14 @@ export function Mixin (_class: Ref>, _extends: Ref ( +export function UX( label: IntlString, icon?: Asset, shortLabel?: string, sortingKey?: string, filteringKey?: string ) { - return function classDecorator T> (constructor: C): void { + return function classDecorator T>(constructor: C): void { const txes = getTxes(constructor.prototype) txes.label = label txes.icon = icon @@ -246,7 +246,7 @@ export function UX ( } } -function generateIds (objectId: Ref, txes: TxCreateDoc>[]): Tx[] { +function generateIds(objectId: Ref, txes: TxCreateDoc>[]): Tx[] { return txes.map((tx) => { const withId = { ...tx, @@ -260,7 +260,7 @@ function generateIds (objectId: Ref, txes: TxCreateDoc void - createModel (...classes: Array Obj>): void { + createModel(...classes: Array Obj>): void { const txes = classes.map((ctor) => getTxes(ctor.prototype)) const byId = new Map() @@ -328,7 +328,7 @@ export class Builder { } } - private generateTransactions (txes: ClassTxes[], byId: Map): Tx[] { + private generateTransactions(txes: ClassTxes[], byId: Map): Tx[] { const graph = this.createGraph(txes) const sorted = toposort(graph) .reverse() @@ -336,7 +336,7 @@ export class Builder { return sorted.flatMap((tx) => (tx != null ? _generateTx(tx) : [])) } - private createGraph (txes: ClassTxes[]): [string, string | undefined][] { + private createGraph(txes: ClassTxes[]): [string, string | undefined][] { return txes.map((tx) => [tx._id, tx.extends] as [string, string | undefined]) } @@ -368,7 +368,7 @@ export class Builder { this.onTx?.(tx) } - getTxes (): Tx[] { + getTxes(): Tx[] { return [...this.txes] } } @@ -378,98 +378,98 @@ export class Builder { /** * @public */ -export function TypeString (): Type { +export function TypeString(): Type { return { _class: core.class.TypeString, label: core.string.String } } /** * @public */ -export function TypeAttachment (): Type { +export function TypeAttachment(): Type { return { _class: core.class.TypeAttachment, label: core.string.String } } /** * @public */ -export function TypeHyperlink (): Type { +export function TypeHyperlink(): Type { return { _class: core.class.TypeHyperlink, label: core.string.Hyperlink } } /** * @public */ -export function TypeNumber (): Type { +export function TypeNumber(): Type { return { _class: core.class.TypeNumber, label: core.string.Number } } /** * @public */ -export function TypeMarkup (): Type { +export function TypeMarkup(): Type { return { _class: core.class.TypeMarkup, label: core.string.Markup } } /** * @public */ -export function TypeCollaborativeMarkup (): Type { +export function TypeCollaborativeMarkup(): Type { return { _class: core.class.TypeCollaborativeMarkup, label: core.string.Collaborative } } /** * @public */ -export function TypeRecord (): Type { +export function TypeRecord(): Type { return { _class: core.class.TypeRecord, label: core.string.Record } } /** * @public */ -export function TypeIntlString (): Type { +export function TypeIntlString(): Type { return { _class: core.class.TypeIntlString, label: core.string.IntlString } } /** * @public */ -export function TypeBoolean (): Type { +export function TypeBoolean(): Type { return { _class: core.class.TypeBoolean, label: core.string.Boolean } } /** * @public */ -export function TypeTimestamp (): Type { +export function TypeTimestamp(): Type { return { _class: core.class.TypeTimestamp, label: core.string.Timestamp } } /** * @public */ -export function TypeDate (mode: DateRangeMode = DateRangeMode.DATE, withShift: boolean = true): TypeDateType { +export function TypeDate(mode: DateRangeMode = DateRangeMode.DATE, withShift: boolean = true): TypeDateType { return { _class: core.class.TypeDate, label: core.string.Date, mode, withShift } } /** * @public */ -export function TypeRef (_class: Ref>): RefTo { +export function TypeRef(_class: Ref>): RefTo { return { _class: core.class.RefTo, label: core.string.Ref, to: _class } } /** * @public */ -export function TypeEnum (of: Ref): EnumOf { +export function TypeEnum(of: Ref): EnumOf { return { _class: core.class.EnumOf, label: core.string.Enum, of } } /** * @public */ -export function TypeAny ( +export function TypeAny( presenter: AnyComponent, label: IntlString, editor?: AnyComponent @@ -480,27 +480,27 @@ export function TypeAny ( /** * @public */ -export function Collection (clazz: Ref>, itemLabel?: IntlString): TypeCollection { +export function Collection(clazz: Ref>, itemLabel?: IntlString): TypeCollection { return { _class: core.class.Collection, label: core.string.Collection, of: clazz, itemLabel } } /** * @public */ -export function ArrOf> (type: Type): TypeArrOf { +export function ArrOf>(type: Type): TypeArrOf { return { _class: core.class.ArrOf, label: core.string.Array, of: type } } /** * @public */ -export function TypeCollaborativeDoc (): Type { +export function TypeCollaborativeDoc(): Type { return { _class: core.class.TypeCollaborativeDoc, label: core.string.CollaborativeDoc } } /** * @public */ -export function TypeCollaborativeDocVersion (): Type { +export function TypeCollaborativeDocVersion(): Type { return { _class: core.class.TypeCollaborativeDocVersion, label: core.string.CollaborativeDocVersion } } diff --git a/packages/platform-rig/bin/compile.js b/packages/platform-rig/bin/compile.js index 305818afbe9..d2b9c3c5e86 100755 --- a/packages/platform-rig/bin/compile.js +++ b/packages/platform-rig/bin/compile.js @@ -5,19 +5,19 @@ const { spawn } = require('child_process') const esbuild = require('esbuild') const { copy } = require('esbuild-plugin-copy') -async function execProcess(cmd, logFile, args) { +async function execProcess(cmd, logFile, args, buildDir= '.build') { let compileRoot = dirname(dirname(process.argv[1])) console.log('Running from',) console.log("Compiling...\n", process.cwd(), args) - if (!existsSync(join(process.cwd(), '.build'))) { - mkdirSync(join(process.cwd(), '.build')) + if (!existsSync(join(process.cwd(), buildDir))) { + mkdirSync(join(process.cwd(), buildDir)) } const compileOut = spawn(cmd, args) - const stdoutFilePath = `.build/${logFile}.log` - const stderrFilePath = `.build/${logFile}-err.log` + const stdoutFilePath = `${buildDir}/${logFile}.log` + const stderrFilePath = `${buildDir}/${logFile}-err.log` const outPromise = new Promise((resolve) => { @@ -159,14 +159,14 @@ async function validateTSC(st) { } await execProcess( 'tsc', - 'tsc', + 'validate', [ '-pretty', "--emitDeclarationOnly", - "--incremental", + "--incremental", "--tsBuildInfoFile", ".validate/tsBuildInfoFile.info", "--declarationDir", "types", ...args.splice(1) - ]) + ], '.validate') } diff --git a/packages/platform-rig/bin/format.js b/packages/platform-rig/bin/format.js index f473a7a40b2..6fb9a011b8b 100755 --- a/packages/platform-rig/bin/format.js +++ b/packages/platform-rig/bin/format.js @@ -97,7 +97,9 @@ if( filesToCheck.length > 0 ) { } console.log(`running eslint ${filesToCheck.length}`) - const eslint = spawnSync(join(process.cwd(), 'node_modules/.bin/eslint'), ["--color", "--fix", ...filesToCheck]) + const eslint = spawnSync(join(process.cwd(), 'node_modules/.bin/eslint'), ["--color", "--fix", ...filesToCheck], { + env: {...process.env, NODE_ENV: '--max-old-space-size=4096' }, + }) if(eslint.stdout != null) { writeFileSync('.format/eslint.log', eslint.stdout) if( prettier.status === null || prettier.status === 0) { diff --git a/packages/platform/src/resource.ts b/packages/platform/src/resource.ts index a6507aef515..f70a5c53179 100644 --- a/packages/platform/src/resource.ts +++ b/packages/platform/src/resource.ts @@ -45,7 +45,7 @@ const locations = new Map>() * @param plugin - * @param module - */ -export function addLocation (plugin: Plugin, module: PluginLoader): void { +export function addLocation(plugin: Plugin, module: PluginLoader): void { locations.set(plugin, module) } @@ -53,11 +53,11 @@ export function addLocation (plugin: Plugin, module: Plugin * @public * return list of registred plugins. */ -export function getPlugins (): Plugin[] { +export function getPlugins(): Plugin[] { return Array.from(locations.keys()) } -function getLocation (plugin: Plugin): PluginLoader { +function getLocation(plugin: Plugin): PluginLoader { const location = locations.get(plugin) if (location === undefined) { console.log(plugin) @@ -72,7 +72,7 @@ function getLocation (plugin: Plugin): PluginLoader { const loading = new Map>() -async function loadPlugin (id: Plugin): Promise { +async function loadPlugin(id: Plugin): Promise { let pluginLoader = loading.get(id) if (pluginLoader === undefined) { const status = new Status(Severity.INFO, platform.status.LoadingPlugin, { @@ -103,7 +103,7 @@ const cachedResource = new Map() * @param resource - * @returns */ -export async function getResource (resource: Resource): Promise { +export async function getResource(resource: Resource): Promise { const cached = cachedResource.get(resource) if (cached !== undefined) { return cached @@ -121,7 +121,7 @@ export async function getResource (resource: Resource): Promise { /** * @public */ -export function getResourcePlugin (resource: Resource): Plugin { +export function getResourcePlugin(resource: Resource): Plugin { const info = _parseId(resource) return info.component } diff --git a/packages/query/src/__tests__/query.test.ts b/packages/query/src/__tests__/query.test.ts index 365649b87ab..4eeaf75ddcb 100644 --- a/packages/query/src/__tests__/query.test.ts +++ b/packages/query/src/__tests__/query.test.ts @@ -33,7 +33,7 @@ interface Channel extends Space { x: number } -async function getClient (): Promise<{ liveQuery: LiveQuery, factory: TxOperations }> { +async function getClient(): Promise<{ liveQuery: LiveQuery; factory: TxOperations }> { const storage = await createClient(connect) const liveQuery = new LiveQuery(storage) storage.notify = (...tx: Tx[]) => { diff --git a/packages/query/src/index.ts b/packages/query/src/index.ts index 7410d8b9d25..ed43641cce8 100644 --- a/packages/query/src/index.ts +++ b/packages/query/src/index.ts @@ -79,29 +79,29 @@ export class LiveQuery implements WithTx, Client { private readonly queries: Map>, Query[]> = new Map>, Query[]>() private readonly queue: Query[] = [] - constructor (client: Client) { + constructor(client: Client) { this.client = client } - async updateClient (client: Client): Promise { + async updateClient(client: Client): Promise { this.client = client await this.refreshConnect() } - async close (): Promise { + async close(): Promise { await this.client.close() } - getHierarchy (): Hierarchy { + getHierarchy(): Hierarchy { return this.client.getHierarchy() } - getModel (): ModelDb { + getModel(): ModelDb { return this.client.getModel() } // Perform refresh of content since connection established. - async refreshConnect (): Promise { + async refreshConnect(): Promise { for (const q of [...this.queue]) { if (!this.removeFromQueue(q)) { try { @@ -132,7 +132,7 @@ export class LiveQuery implements WithTx, Client { } } - private match (q: Query, doc: Doc, skipLookup = false): boolean { + private match(q: Query, doc: Doc, skipLookup = false): boolean { if (!this.getHierarchy().isDerived(doc._class, q._class)) { // Check if it is not a mixin and not match class const mixinClass = Hierarchy.mixinClass(doc) @@ -194,7 +194,7 @@ export class LiveQuery implements WithTx, Client { return toFindResult(this.clone(q.result), q.total) as FindResult } - searchFulltext (query: SearchQuery, options: SearchOptions): Promise { + searchFulltext(query: SearchQuery, options: SearchOptions): Promise { return this.client.searchFulltext(query, options) } @@ -242,7 +242,7 @@ export class LiveQuery implements WithTx, Client { } } - private removeFromQueue (q: Query): boolean { + private removeFromQueue(q: Query): boolean { if (q.callbacks.size === 0) { const queueIndex = this.queue.indexOf(q) if (queueIndex !== -1) { @@ -253,7 +253,7 @@ export class LiveQuery implements WithTx, Client { return false } - private pushCallback ( + private pushCallback( q: Query, callback: { callback: (result: Doc[]) => void @@ -292,7 +292,7 @@ export class LiveQuery implements WithTx, Client { private createQuery( _class: Ref>, query: DocumentQuery, - callback: { callback: (result: FindResult) => void, callbackId: string }, + callback: { callback: (result: FindResult) => void; callbackId: string }, options?: FindOptions ): Query { const queries = this.queries.get(_class) ?? [] @@ -323,7 +323,7 @@ export class LiveQuery implements WithTx, Client { return q } - private remove (): void { + private remove(): void { const q = this.queue.shift() if (q === undefined) return const queries = this.queries.get(q._class) @@ -394,7 +394,7 @@ export class LiveQuery implements WithTx, Client { return toFindResult(this.clone((current?.result as T[]) ?? []), current.total) } - private async checkSearch (q: Query, _id: Ref): Promise { + private async checkSearch(q: Query, _id: Ref): Promise { const match = await this.client.findOne(q._class, { $search: q.query.$search, _id }, q.options) if (q.result instanceof Promise) { q.result = await q.result @@ -421,7 +421,7 @@ export class LiveQuery implements WithTx, Client { return false } - private async getDocFromCache ( + private async getDocFromCache( docCache: Map, _id: Ref, _class: Ref>, @@ -441,7 +441,7 @@ export class LiveQuery implements WithTx, Client { return current } - private async getCurrentDoc ( + private async getCurrentDoc( q: Query, _id: Ref, space: Ref, @@ -469,7 +469,7 @@ export class LiveQuery implements WithTx, Client { return false } - private async __updateMixinDoc (q: Query, updatedDoc: WithLookup, tx: TxMixin): Promise { + private async __updateMixinDoc(q: Query, updatedDoc: WithLookup, tx: TxMixin): Promise { updatedDoc = TxProcessor.updateMixin4Doc(updatedDoc, tx) const ops = { @@ -480,7 +480,7 @@ export class LiveQuery implements WithTx, Client { await this.__updateLookup(q, updatedDoc, ops) } - private async checkUpdatedDocMatch (q: Query, updatedDoc: WithLookup): Promise { + private async checkUpdatedDocMatch(q: Query, updatedDoc: WithLookup): Promise { if (q.result instanceof Promise) { q.result = await q.result } @@ -501,7 +501,7 @@ export class LiveQuery implements WithTx, Client { return false } - protected async txMixin (tx: TxMixin, docCache: Map): Promise { + protected async txMixin(tx: TxMixin, docCache: Map): Promise { const hierarchy = this.client.getHierarchy() for (const queries of this.queries) { @@ -555,7 +555,7 @@ export class LiveQuery implements WithTx, Client { return {} } - protected async txCollectionCUD ( + protected async txCollectionCUD( tx: TxCollectionCUD, docCache: Map ): Promise { @@ -590,7 +590,7 @@ export class LiveQuery implements WithTx, Client { return {} } - async txUpdateDoc (tx: TxUpdateDoc, docCache: Map): Promise { + async txUpdateDoc(tx: TxUpdateDoc, docCache: Map): Promise { for (const queries of this.queries) { const isTx = this.client.getHierarchy().isDerived(queries[0], core.class.Tx) for (const q of queries[1]) { @@ -605,7 +605,7 @@ export class LiveQuery implements WithTx, Client { return {} } - private async handleDocUpdate (q: Query, tx: TxUpdateDoc, docCache: Map): Promise { + private async handleDocUpdate(q: Query, tx: TxUpdateDoc, docCache: Map): Promise { if (q.result instanceof Promise) { q.result = await q.result } @@ -645,7 +645,7 @@ export class LiveQuery implements WithTx, Client { await this.handleDocUpdateLookup(q, tx) } - private async handleDocUpdateLookup (q: Query, tx: TxUpdateDoc | TxMixin): Promise { + private async handleDocUpdateLookup(q: Query, tx: TxUpdateDoc | TxMixin): Promise { if (q.options?.lookup === undefined) return const lookup = q.options.lookup if (q.result instanceof Promise) { @@ -662,7 +662,7 @@ export class LiveQuery implements WithTx, Client { } } - private async proccesLookupUpdateDoc ( + private async proccesLookupUpdateDoc( docs: Doc[], lookup: Lookup, tx: TxUpdateDoc | TxMixin @@ -728,7 +728,7 @@ export class LiveQuery implements WithTx, Client { return this.getHierarchy().clone(results) as T[] } - private async refresh (q: Query): Promise { + private async refresh(q: Query): Promise { const res = await this.client.findAll(q._class, q.query, q.options) if (!deepEqual(res, q.result) || (res.total !== q.total && q.options?.total === true)) { q.result = res @@ -737,7 +737,7 @@ export class LiveQuery implements WithTx, Client { } } - private triggerRefresh (q: Query): void { + private triggerRefresh(q: Query): void { const r: Promise> | FindResult = this.client.findAll(q._class, q.query, q.options) q.result = r void r.then(async (qr) => { @@ -750,7 +750,7 @@ export class LiveQuery implements WithTx, Client { } // Check if query is partially matched. - private async matchQuery (q: Query, tx: TxUpdateDoc, docCache: Map): Promise { + private async matchQuery(q: Query, tx: TxUpdateDoc, docCache: Map): Promise { const clazz = this.getHierarchy().isMixin(q._class) ? this.getHierarchy().getBaseClass(q._class) : q._class if (!this.client.getHierarchy().isDerived(tx.objectClass, clazz)) { return false @@ -881,7 +881,7 @@ export class LiveQuery implements WithTx, Client { ;(doc as WithLookup).$lookup = result } - protected async txCreateDoc (tx: TxCreateDoc, docCache: Map): Promise { + protected async txCreateDoc(tx: TxCreateDoc, docCache: Map): Promise { const docTx = TxProcessor.createDoc2Doc(tx) for (const queries of this.queries) { const doc = this.client.getHierarchy().isDerived(queries[0], core.class.Tx) ? tx : docTx @@ -892,7 +892,7 @@ export class LiveQuery implements WithTx, Client { return {} } - private async handleDocAdd (q: Query, doc: Doc, handleLookup = true, docCache: Map): Promise { + private async handleDocAdd(q: Query, doc: Doc, handleLookup = true, docCache: Map): Promise { if (this.match(q, doc, q.options?.lookup !== undefined)) { let needPush = true if (q.result instanceof Promise) { @@ -940,7 +940,7 @@ export class LiveQuery implements WithTx, Client { await this.handleDocAddLookup(q, doc) } - private async callback (q: Query): Promise { + private async callback(q: Query): Promise { if (q.result instanceof Promise) { q.result = await q.result } @@ -950,7 +950,7 @@ export class LiveQuery implements WithTx, Client { }) } - private async handleDocAddLookup (q: Query, doc: Doc): Promise { + private async handleDocAddLookup(q: Query, doc: Doc): Promise { if (q.options?.lookup === undefined) return const lookup = q.options.lookup if (q.result instanceof Promise) { @@ -967,7 +967,7 @@ export class LiveQuery implements WithTx, Client { } } - private proccesLookupAddDoc (docs: Doc[], lookup: Lookup, doc: Doc): boolean { + private proccesLookupAddDoc(docs: Doc[], lookup: Lookup, doc: Doc): boolean { let needCallback = false const lookupWays = this.getLookupWays(lookup, doc._class) for (const lookupWay of lookupWays) { @@ -996,7 +996,7 @@ export class LiveQuery implements WithTx, Client { return needCallback } - protected async txRemoveDoc (tx: TxRemoveDoc, docCache: Map): Promise { + protected async txRemoveDoc(tx: TxRemoveDoc, docCache: Map): Promise { for (const queries of this.queries) { const isTx = this.client.getHierarchy().isDerived(queries[0], core.class.Tx) for (const q of queries[1]) { @@ -1011,7 +1011,7 @@ export class LiveQuery implements WithTx, Client { return {} } - private async handleDocRemove (q: Query, tx: TxRemoveDoc): Promise { + private async handleDocRemove(q: Query, tx: TxRemoveDoc): Promise { const h = this.client.getHierarchy() if (q.result instanceof Promise) { q.result = await q.result @@ -1035,7 +1035,7 @@ export class LiveQuery implements WithTx, Client { await this.handleDocRemoveLookup(q, tx) } - private async handleDocRemoveLookup (q: Query, tx: TxRemoveDoc): Promise { + private async handleDocRemoveLookup(q: Query, tx: TxRemoveDoc): Promise { if (q.options?.lookup === undefined) return let needCallback = false const lookupWays = this.getLookupWays(q.options.lookup, tx.objectClass) @@ -1073,7 +1073,7 @@ export class LiveQuery implements WithTx, Client { } } - private getLookupWays ( + private getLookupWays( lookup: Lookup, _class: Ref>, parent: string = '' @@ -1114,7 +1114,7 @@ export class LiveQuery implements WithTx, Client { return result } - async _tx (tx: Tx, docCache: Map): Promise { + async _tx(tx: Tx, docCache: Map): Promise { switch (tx._class) { case core.class.TxCreateDoc: return await this.txCreateDoc(tx as TxCreateDoc, docCache) @@ -1132,7 +1132,7 @@ export class LiveQuery implements WithTx, Client { return {} } - async tx (...txes: Tx[]): Promise { + async tx(...txes: Tx[]): Promise { const result: TxResult[] = [] const docCache = new Map() for (const tx of txes) { @@ -1145,10 +1145,10 @@ export class LiveQuery implements WithTx, Client { return result } - private async checkUpdateEvents (tx: Tx): Promise { + private async checkUpdateEvents(tx: Tx): Promise { const evt = tx as TxWorkspaceEvent const h = this.client.getHierarchy() - function hasClass (q: Query, classes: Ref>[]): boolean { + function hasClass(q: Query, classes: Ref>[]): boolean { return classes.includes(q._class) || classes.some((it) => h.isDerived(q._class, it) || h.isDerived(it, q._class)) } if (evt.event === WorkspaceEvent.IndexingUpdate) { @@ -1203,7 +1203,7 @@ export class LiveQuery implements WithTx, Client { } } - private async changePrivateHandler (tx: Tx): Promise { + private async changePrivateHandler(tx: Tx): Promise { const evt = tx as TxWorkspaceEvent if (evt.event === WorkspaceEvent.SecurityChange) { for (const q of [...this.queue]) { @@ -1231,7 +1231,7 @@ export class LiveQuery implements WithTx, Client { } } - private async __updateLookup (q: Query, updatedDoc: WithLookup, ops: any): Promise { + private async __updateLookup(q: Query, updatedDoc: WithLookup, ops: any): Promise { for (const key in ops) { if (!key.startsWith('$')) { if (q.options !== undefined) { @@ -1304,7 +1304,7 @@ export class LiveQuery implements WithTx, Client { } } - private async __updateDoc (q: Query, updatedDoc: WithLookup, tx: TxUpdateDoc): Promise { + private async __updateDoc(q: Query, updatedDoc: WithLookup, tx: TxUpdateDoc): Promise { TxProcessor.updateDoc2Doc(updatedDoc, tx) const ops = { @@ -1315,7 +1315,7 @@ export class LiveQuery implements WithTx, Client { await this.__updateLookup(q, updatedDoc, ops) } - private async sort (q: Query, tx: TxUpdateDoc | TxMixin): Promise { + private async sort(q: Query, tx: TxUpdateDoc | TxMixin): Promise { const sort = q.options?.sort if (sort === undefined) return let needSort = sort.modifiedBy !== undefined || sort.modifiedOn !== undefined @@ -1324,7 +1324,7 @@ export class LiveQuery implements WithTx, Client { if (needSort) await resultSort(q.result as Doc[], sort, q._class, this.getHierarchy(), this.client.getModel()) } - private checkNeedSort (sort: SortingQuery, tx: TxUpdateDoc | TxMixin): boolean { + private checkNeedSort(sort: SortingQuery, tx: TxUpdateDoc | TxMixin): boolean { const ops = tx._class === core.class.TxMixin ? (tx as TxMixin).attributes @@ -1341,7 +1341,7 @@ export class LiveQuery implements WithTx, Client { return false } - private async updatedDocCallback (updatedDoc: Doc | undefined, q: Query): Promise { + private async updatedDocCallback(updatedDoc: Doc | undefined, q: Query): Promise { q.result = q.result as Doc[] if (q.options?.limit !== undefined && q.result.length > q.options.limit) { @@ -1362,10 +1362,10 @@ export class LiveQuery implements WithTx, Client { } } -function getNestedLookup (lookup: Ref> | [Ref>, Lookup]): Lookup | undefined { +function getNestedLookup(lookup: Ref> | [Ref>, Lookup]): Lookup | undefined { return Array.isArray(lookup) ? lookup[1] : undefined } -function getLookupClass (lookup: Ref> | [Ref>, Lookup]): Ref> { +function getLookupClass(lookup: Ref> | [Ref>, Lookup]): Ref> { return Array.isArray(lookup) ? lookup[0] : lookup } diff --git a/plugins/client-resources/src/connection.ts b/plugins/client-resources/src/connection.ts index 9e6485ab827..04e580f1b2c 100644 --- a/plugins/client-resources/src/connection.ts +++ b/plugins/client-resources/src/connection.ts @@ -57,7 +57,7 @@ class RequestPromise { resolve!: (value?: any) => void reject!: (reason?: any) => void reconnect?: () => void - constructor ( + constructor( readonly method: string, readonly params: any[], readonly handleResult?: (result: any) => Promise @@ -68,7 +68,7 @@ class RequestPromise { }) } - chunks?: { index: number, data: any[] }[] + chunks?: { index: number; data: any[] }[] } class Connection implements ClientConnection { @@ -81,7 +81,7 @@ class Connection implements ClientConnection { private pingResponse: number = Date.now() - constructor ( + constructor( private readonly url: string, private readonly handler: TxHandler, private readonly onUpgrade?: () => void, @@ -114,7 +114,7 @@ class Connection implements ClientConnection { }, pingTimeout) } - async close (): Promise { + async close(): Promise { this.closed = true clearInterval(this.interval) if (this.websocket !== null) { @@ -132,7 +132,7 @@ class Connection implements ClientConnection { delay = 1 pending: Promise | undefined - private async waitOpenConnection (): Promise { + private async waitOpenConnection(): Promise { while (true) { try { const socket = await this.pending @@ -168,7 +168,7 @@ class Connection implements ClientConnection { incomingTimer: any - private openConnection (): Promise { + private openConnection(): Promise { return new Promise((resolve, reject) => { // Use defined factory or browser default one. const clientSocketFactory = @@ -348,7 +348,7 @@ class Connection implements ClientConnection { }) } - private async sendRequest (data: { + private async sendRequest(data: { method: string params: any[] // If not defined, on reconnect with timeout, will retry automatically. @@ -395,7 +395,7 @@ class Connection implements ClientConnection { return await promise.promise } - async measure (operationName: string): Promise { + async measure(operationName: string): Promise { const dateNow = Date.now() // Send measure-start @@ -415,11 +415,11 @@ class Connection implements ClientConnection { } } - async loadModel (last: Timestamp, hash?: string): Promise { + async loadModel(last: Timestamp, hash?: string): Promise { return await this.sendRequest({ method: 'loadModel', params: [last, hash] }) } - async getAccount (): Promise { + async getAccount(): Promise { return await this.sendRequest({ method: 'getAccount', params: [] }) } @@ -436,7 +436,7 @@ class Connection implements ClientConnection { return result } - tx (tx: Tx): Promise { + tx(tx: Tx): Promise { return this.sendRequest({ method: 'tx', params: [tx], @@ -449,40 +449,40 @@ class Connection implements ClientConnection { handleResult: tx._class === core.class.TxApplyIf ? async (result) => { - if (tx._class === core.class.TxApplyIf) { - // We need to check extra broadcast's and perform them before - const r = result as TxApplyResult - const dr = r?.derived ?? [] - if (dr.length > 0) { - this.handler(...dr) + if (tx._class === core.class.TxApplyIf) { + // We need to check extra broadcast's and perform them before + const r = result as TxApplyResult + const dr = r?.derived ?? [] + if (dr.length > 0) { + this.handler(...dr) + } } } - } : undefined }) } - loadChunk (domain: Domain, idx?: number): Promise { + loadChunk(domain: Domain, idx?: number): Promise { return this.sendRequest({ method: 'loadChunk', params: [domain, idx] }) } - closeChunk (idx: number): Promise { + closeChunk(idx: number): Promise { return this.sendRequest({ method: 'closeChunk', params: [idx] }) } - loadDocs (domain: Domain, docs: Ref[]): Promise { + loadDocs(domain: Domain, docs: Ref[]): Promise { return this.sendRequest({ method: 'loadDocs', params: [domain, docs] }) } - upload (domain: Domain, docs: Doc[]): Promise { + upload(domain: Domain, docs: Doc[]): Promise { return this.sendRequest({ method: 'upload', params: [domain, docs] }) } - clean (domain: Domain, docs: Ref[]): Promise { + clean(domain: Domain, docs: Ref[]): Promise { return this.sendRequest({ method: 'clean', params: [domain, docs] }) } - searchFulltext (query: SearchQuery, options: SearchOptions): Promise { + searchFulltext(query: SearchQuery, options: SearchOptions): Promise { return this.sendRequest({ method: 'searchFulltext', params: [query, options] }) } } @@ -490,7 +490,7 @@ class Connection implements ClientConnection { /** * @public */ -export async function connect ( +export async function connect( url: string, handler: TxHandler, onUpgrade?: () => void, diff --git a/plugins/client-resources/src/index.ts b/plugins/client-resources/src/index.ts index 4304f5e2dda..41b07b389d8 100644 --- a/plugins/client-resources/src/index.ts +++ b/plugins/client-resources/src/index.ts @@ -84,7 +84,7 @@ export default async () => { } } } -function createModelPersistence (token: string): TxPersistenceStore | undefined { +function createModelPersistence(token: string): TxPersistenceStore | undefined { let dbRequest: IDBOpenDBRequest | undefined let dbPromise: Promise = Promise.resolve(undefined) @@ -110,8 +110,8 @@ function createModelPersistence (token: string): TxPersistenceStore | undefined if (db !== undefined) { const transaction = db.transaction('model', 'readwrite') // (1) const models = transaction.objectStore('model') // (2) - const model = await new Promise<{ id: string, model: LoadModelResponse } | undefined>((resolve) => { - const storedValue: IDBRequest<{ id: string, model: LoadModelResponse }> = models.get(token) + const model = await new Promise<{ id: string; model: LoadModelResponse } | undefined>((resolve) => { + const storedValue: IDBRequest<{ id: string; model: LoadModelResponse }> = models.get(token) storedValue.onsuccess = function () { resolve(storedValue.result) } @@ -146,7 +146,7 @@ function createModelPersistence (token: string): TxPersistenceStore | undefined } } -async function hookClient (client: Promise): Promise { +async function hookClient(client: Promise): Promise { const hook = getMetadata(clientPlugin.metadata.ClientHook) if (hook !== undefined) { const hookProc = await getResource(hook) diff --git a/plugins/view/src/index.ts b/plugins/view/src/index.ts index 6d148fc5f6c..503e07300a5 100644 --- a/plugins/view/src/index.ts +++ b/plugins/view/src/index.ts @@ -305,7 +305,7 @@ const view = plugin(viewId, { castRequest?: Ref> // Or list of values to select from - values?: { icon?: Asset, label: IntlString, id: number | string }[] + values?: { icon?: Asset; label: IntlString; id: number | string }[] placeholder?: IntlString }>, @@ -316,7 +316,7 @@ const view = plugin(viewId, { fillProps?: Record // Or list of values to select from - values?: { icon?: Asset, label: IntlString, id: number | string }[] + values?: { icon?: Asset; label: IntlString; id: number | string }[] // If defined, documents will be set into value valueKey?: string diff --git a/plugins/view/src/types.ts b/plugins/view/src/types.ts index e4d57f6093e..10314b9c23e 100644 --- a/plugins/view/src/types.ts +++ b/plugins/view/src/types.ts @@ -310,12 +310,12 @@ export interface ListHeaderExtra extends Class { * @public */ export type SortFunc = Resource< -( - client: TxOperations, - values: PrimitiveType[], - space: Ref | undefined, - viewletDescriptorId?: Ref -) => Promise + ( + client: TxOperations, + values: PrimitiveType[], + space: Ref | undefined, + viewletDescriptorId?: Ref + ) => Promise > /** @@ -329,12 +329,12 @@ export interface ClassSortFuncs extends Class { * @public */ export type GetAllValuesFunc = Resource< -( - query: DocumentQuery | undefined, - onUpdate: () => void, - queryId: Ref, - attr: AnyAttribute -) => Promise + ( + query: DocumentQuery | undefined, + onUpdate: () => void, + queryId: Ref, + attr: AnyAttribute + ) => Promise > /** @@ -712,7 +712,7 @@ export interface CategoryOption extends ViewOption { * @public */ export type ViewQueryAction = Resource< -(value: any, query: DocumentQuery) => DocumentQuery | Promise> + (value: any, query: DocumentQuery) => DocumentQuery | Promise> > /** @@ -737,7 +737,7 @@ export interface ToggleViewOption extends ViewOption { export interface DropdownViewOption extends ViewOption { type: 'dropdown' defaultValue: string - values: Array<{ label: IntlString, id: string, hidden?: (viewOptions: ViewOptions) => boolean }> + values: Array<{ label: IntlString; id: string; hidden?: (viewOptions: ViewOptions) => boolean }> } /** diff --git a/rush.json b/rush.json index c32ba1a4c6e..07566d96b87 100644 --- a/rush.json +++ b/rush.json @@ -16,7 +16,7 @@ * path segment in the "$schema" field for all your Rush config files. This will ensure * correct error-underlining and tab-completion for editors such as VS Code. */ - "rushVersion": "5.113.4", + "rushVersion": "5.115.0", /** * The next field selects which package manager should be installed and determines its version. diff --git a/server/ws/src/client.ts b/server/ws/src/client.ts index 0fb23fd35ba..c23cce83d52 100644 --- a/server/ws/src/client.ts +++ b/server/ws/src/client.ts @@ -57,32 +57,32 @@ export class ClientSession implements Session { total: StatisticsElement = { find: 0, tx: 0 } current: StatisticsElement = { find: 0, tx: 0 } mins5: StatisticsElement = { find: 0, tx: 0 } - measures: { id: string, message: string, time: 0 }[] = [] + measures: { id: string; message: string; time: 0 }[] = [] - constructor ( + constructor( protected readonly broadcast: BroadcastCall, protected readonly token: Token, protected readonly _pipeline: Pipeline ) {} - getUser (): string { + getUser(): string { return this.token.email } - pipeline (): Pipeline { + pipeline(): Pipeline { return this._pipeline } - async ping (): Promise { + async ping(): Promise { // console.log('ping') return 'pong!' } - async loadModel (ctx: MeasureContext, lastModelTx: Timestamp, hash?: string): Promise { + async loadModel(ctx: MeasureContext, lastModelTx: Timestamp, hash?: string): Promise { return await this._pipeline.storage.loadModel(lastModelTx, hash) } - async getAccount (ctx: MeasureContext): Promise { + async getAccount(ctx: MeasureContext): Promise { const account = await this._pipeline.modelDb.findAll(core.class.Account, { email: this.token.email }) if (account.length === 0 && this.token.extra?.admin === 'true') { const systemAccount = await this._pipeline.modelDb.findAll(core.class.Account, { @@ -128,14 +128,14 @@ export class ClientSession implements Session { return await this._pipeline.findAll(context, _class, query, options) } - async searchFulltext (ctx: MeasureContext, query: SearchQuery, options: SearchOptions): Promise { + async searchFulltext(ctx: MeasureContext, query: SearchQuery, options: SearchOptions): Promise { const context = ctx as SessionContext context.userEmail = this.token.email context.admin = this.token.extra?.admin === 'true' return await this._pipeline.searchFulltext(context, query, options) } - async tx (ctx: MeasureContext, tx: Tx): Promise { + async tx(ctx: MeasureContext, tx: Tx): Promise { this.total.tx++ this.current.tx++ const context = ctx as SessionContext @@ -204,7 +204,7 @@ export class ClientSession implements Session { return result } - private createBroadcastEvent (classes: Ref>[]): TxWorkspaceEvent { + private createBroadcastEvent(classes: Ref>[]): TxWorkspaceEvent { return { _class: core.class.TxWorkspaceEvent, _id: generateId(),