@openforis/arena-core 2.18.5 → 2.18.7

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.
@@ -138,9 +138,30 @@ export class JobBase {
138
138
  }
139
139
  combineInnerJobsErrors() {
140
140
  const errors = {};
141
- this.innerJobs.forEach((innerJob) => { var _a; return Object.assign(errors, (_a = innerJob.errors) !== null && _a !== void 0 ? _a : {}); });
141
+ this.innerJobs.forEach((innerJob) => JobBase.mergeInnerJobErrors(errors, innerJob));
142
142
  return errors;
143
143
  }
144
+ /**
145
+ * Adds the errors of the inner job to the specified errors.
146
+ * Error keys already in use (e.g. the same item number used by two inner jobs) are prefixed with the inner job type
147
+ * (and suffixed with a counter if still in use), so that no error gets overwritten.
148
+ */
149
+ static mergeInnerJobErrors(errors, innerJob) {
150
+ var _a;
151
+ Object.entries((_a = innerJob.errors) !== null && _a !== void 0 ? _a : {}).forEach(([key, error]) => {
152
+ let uniqueKey = key;
153
+ if (uniqueKey in errors) {
154
+ const prefixedKey = `${innerJob.type} ${key}`;
155
+ uniqueKey = prefixedKey;
156
+ let count = 2;
157
+ while (uniqueKey in errors) {
158
+ uniqueKey = `${prefixedKey} (${count})`;
159
+ count += 1;
160
+ }
161
+ }
162
+ errors[uniqueKey] = error;
163
+ });
164
+ }
144
165
  cancel() {
145
166
  return __awaiter(this, arguments, void 0, function* (options = {}) {
146
167
  const { canceledByAdmin = false } = options;
@@ -315,6 +336,7 @@ export class JobBase {
315
336
  !this.cancelRequested &&
316
337
  this.innerJobs.some((innerJob) => innerJob.isFailed())) {
317
338
  // set only after all inner jobs have run: setting it at the first failure would end this job (onEnd) too early
339
+ yield this.runBeforeEnd();
318
340
  yield this.setStatus(JobStatus.failed);
319
341
  }
320
342
  this.logDebug(`- ${this.processed} inner jobs processed successfully`);
@@ -365,18 +387,27 @@ export class JobBase {
365
387
  */
366
388
  onInnerJobEvent(event) {
367
389
  return __awaiter(this, void 0, void 0, function* () {
368
- var _a, _b;
369
- var _c, _d;
390
+ var _a;
391
+ var _b;
370
392
  const { status } = event;
371
393
  if (status === JobStatus.canceled) {
372
- this.canceledByAdmin = (_c = (_a = this.getCurrentInnerJob()) === null || _a === void 0 ? void 0 : _a.canceledByAdmin) !== null && _c !== void 0 ? _c : false;
394
+ this.canceledByAdmin = (_b = (_a = this.getCurrentInnerJob()) === null || _a === void 0 ? void 0 : _a.canceledByAdmin) !== null && _b !== void 0 ? _b : false;
395
+ // beforeEnd must run before onEnd (it runs only once: it won't run again when the execution ends)
396
+ yield this.runBeforeEnd();
373
397
  return this.setStatus(status);
374
398
  }
375
399
  if (status === JobStatus.failed) {
376
400
  // report the errors of the failed inner job in the failed event (and in the errors) of this job
377
- Object.assign(this.errors, (_d = (_b = this.getCurrentInnerJob()) === null || _b === void 0 ? void 0 : _b.errors) !== null && _d !== void 0 ? _d : {});
401
+ const currentInnerJob = this.getCurrentInnerJob();
402
+ if (currentInnerJob) {
403
+ JobBase.mergeInnerJobErrors(this.errors, currentInnerJob);
404
+ }
378
405
  // when not stopping on inner job failures, this job is set as failed after all the inner jobs have run
379
- return this.stopOnInnerJobFailure ? this.setStatus(status) : undefined;
406
+ if (this.stopOnInnerJobFailure) {
407
+ yield this.runBeforeEnd();
408
+ yield this.setStatus(status);
409
+ }
410
+ return;
380
411
  }
381
412
  if (status === JobStatus.running) {
382
413
  this.notifyEvent({
@@ -510,6 +541,9 @@ export class JobBase {
510
541
  * progress does not flood consumers (e.g. web socket clients).
511
542
  */
512
543
  notifyProgress() {
544
+ // onEnd has already cleared the throttle: no progress events after the job has ended
545
+ if (this.isEnded())
546
+ return;
513
547
  const run = () => {
514
548
  this.progressThrottleTimeoutId = undefined;
515
549
  this.progressThrottleLastRunTime = Date.now();
@@ -1 +1 @@
1
- {"version":3,"file":"JobBase.js","sourceRoot":"","sources":["../../../src/job/JobBase.ts"],"names":[],"mappings":";;;;;;;;;AAEA,OAAO,EAAE,WAAW,EAAE,eAAe,EAAE,MAAM,UA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ErrorKeys } from '../error'\nimport { Logger } from '../logger'\nimport { Survey } from '../survey'\nimport { UUIDs } from '../utils'\n\nimport { Job } from './job'\nimport { JobContext } from './jobContext'\nimport { JobEvent, JobEventType } from './jobEvent'\nimport { JobSerialized } from './jobSerialized'\nimport { JobStatus } from './status'\n\nexport interface JobConstructor {\n new <C extends JobContext, R>(context: C, innerJobs?: JobBase<any>[]): JobBase<C, R>\n readonly prototype: JobBase<any, any>\n}\n\n/**\n * Client able to open a transaction (e.g. a pg-promise database): the job runs inside `client.tx(callback)`.\n */\nexport interface JobTxClient {\n tx(callback: (tx: any) => Promise<void>): Promise<unknown>\n}\n\nconst PROGRESS_NOTIFICATION_THROTTLE_MILLIS = 1000\n\n/**\n * Asynchronous task handler.\n *\n * Status workflow:\n * - pending\n * - running\n * - (end)\n * -- succeeded\n * -- failed\n * -- canceled\n *\n * Methods that can be overwritten by subclasses:\n * - shouldExecute (in tx)\n * - onStart (in tx)\n * - execute (in tx)\n * - beforeSuccess (in tx)\n * - generateResult (in tx)\n * - beforeEnd (in tx)\n * - onEnd (out of tx)\n * - getErrorInfo\n */\nexport abstract class JobBase<C extends JobContext, R = undefined> implements Job<R> {\n static readonly keysContext = {\n surveyId: 'surveyId',\n survey: 'survey',\n user: 'user',\n }\n\n readonly uuid: string\n readonly type: string\n status: JobStatus = JobStatus.pending\n startTime?: Date\n endTime?: Date\n total: number\n result: R | undefined = undefined\n errors: Record<string, any> = {}\n canceledByAdmin?: boolean\n\n protected logger: Logger\n protected context: C\n protected innerJobs: JobBase<C, any>[]\n protected currentInnerJobIndex = -1\n\n private _processed = 0\n private eventListener: ((event: JobEvent) => unknown) | undefined = undefined\n private progressThrottleTimeoutId: ReturnType<typeof setTimeout> | undefined = undefined\n private progressThrottleLastRunTime = 0\n private _stopOnInnerJobFailure = true\n // set as soon as cancel() is called (the canceled status is set only after beforeEnd has run)\n private cancelRequested = false\n private beforeEndCalled = false\n // inner job events are handled in sequence; executeJobs waits for them before going on\n private innerJobEventsQueue: Promise<void> = Promise.resolve()\n\n public constructor(context: C, innerJobs: JobBase<C, any>[] = []) {\n this.context = { ...context }\n this.innerJobs = innerJobs\n\n this.uuid = UUIDs.v4()\n this.type = this.context.type ?? this.constructor.name\n this.total = innerJobs.length > 0 ? innerJobs.length : 1\n\n // Created last, so that createLogger() overrides can safely build the logger name out of\n // the job identity (e.g. arena's `Job <ClassName> (<uuid>)` log correlation id).\n this.logger = this.createLogger()\n }\n\n get processed(): number {\n return this._processed\n }\n\n set processed(value: number) {\n this._processed = value\n this.notifyProgress()\n }\n\n get stopOnInnerJobFailure(): boolean {\n return this._stopOnInnerJobFailure\n }\n\n set stopOnInnerJobFailure(value: boolean) {\n this._stopOnInnerJobFailure = value\n }\n\n protected get surveyId(): number | null {\n return this.context.surveyId ?? null\n }\n\n protected get user(): User {\n return this.context.user\n }\n\n protected get userUuid(): string | undefined {\n return this.user?.uuid\n }\n\n protected get contextSurvey(): Survey | undefined {\n return this.context.survey\n }\n\n /**\n * Returns the value of the specified context prop, or the default value (null if not specified) when not set.\n */\n protected getContextProp<K extends keyof C & string>(prop: K, defaultValue?: C[K] | null): C[K] | null\n /** Context prop not declared in the context type: the value is typed by the caller. */\n protected getContextProp<T = any, P extends string = string>(\n prop: P extends keyof C ? never : P,\n defaultValue?: T | null\n ): T | null\n protected getContextProp(prop: string, defaultValue: unknown = null): unknown {\n const value = (this.context as Record<string, unknown>)[prop]\n return value ?? defaultValue\n }\n\n protected setContext(context: Partial<C>): void {\n Object.assign(this.context, context)\n }\n\n protected deleteContextProps(...propNames: string[]): void {\n propNames.forEach((propName) => {\n delete (this.context as any)[propName]\n })\n }\n\n /**\n * Registers the listener notified of job events (status changes and progress).\n * Only one listener can be registered at a time; registering a new one replaces the previous one.\n * Errors thrown (or rejections returned) by the listener are logged and do not affect the job execution.\n */\n onEvent(listener: (event: JobEvent) => unknown): this {\n this.eventListener = listener\n return this\n }\n\n isPending(): boolean {\n return this.status === JobStatus.pending\n }\n\n isRunning(): boolean {\n return this.status === JobStatus.running\n }\n\n isSucceeded(): boolean {\n return this.status === JobStatus.succeeded\n }\n\n isFailed(): boolean {\n return this.status === JobStatus.failed\n }\n\n isCanceled(): boolean {\n return this.status === JobStatus.canceled\n }\n\n isEnded(): boolean {\n return [JobStatus.succeeded, JobStatus.failed, JobStatus.canceled].includes(this.status)\n }\n\n hasErrors(): boolean {\n return Object.keys(this.errors).length > 0\n }\n\n protected getCurrentInnerJob(): JobBase<C, any> | undefined {\n return this.innerJobs[this.currentInnerJobIndex]\n }\n\n protected combineInnerJobsResults(): Record<string, any> {\n const results: Record<string, any> = {}\n this.innerJobs.forEach((innerJob) => Object.assign(results, innerJob.result ?? {}))\n return results\n }\n\n protected combineInnerJobsErrors(): Record<string, any> {\n const errors: Record<string, any> = {}\n this.innerJobs.forEach((innerJob) => Object.assign(errors, innerJob.errors ?? {}))\n return errors\n }\n\n async cancel(options: { canceledByAdmin?: boolean } = {}): Promise<void> {\n const { canceledByAdmin = false } = options\n if (this.isEnded()) return\n\n this.cancelRequested = true\n\n const currentInnerJob = this.getCurrentInnerJob()\n if (currentInnerJob && !currentInnerJob.isEnded()) {\n // inner job running or about to start (pending):\n // the parent job status will be set to canceled when handling the canceled event of the inner job\n await currentInnerJob.cancel({ canceledByAdmin })\n return\n }\n // no inner job running (job without inner jobs, or between two inner jobs)\n this.canceledByAdmin = canceledByAdmin\n // release the resources (temp files/directories, streams) allocated before the cancellation\n await this.runBeforeEnd()\n await this.setStatus(JobStatus.canceled)\n }\n\n /**\n * Returns true when the job has been canceled (or is no longer running).\n * Long-running subclasses can check it to stop processing items (e.g. in a loop) as soon as the job is canceled.\n */\n protected isCancelRequestedOrNotRunning(): boolean {\n return this.cancelRequested || !this.isRunning()\n }\n\n /**\n * Runs beforeEnd only once (it can be called by cancel() and when the job execution ends).\n */\n private async runBeforeEnd(): Promise<void> {\n if (this.beforeEndCalled) return\n this.beforeEndCalled = true\n await this.beforeEnd()\n }\n\n async start(client: JobTxClient | null = null): Promise<void> {\n // canceled before being started: nothing to execute\n if (this.cancelRequested || this.isEnded()) return\n\n this.logDebug('start')\n\n try {\n if (client) {\n await client.tx(async (tx: any) => {\n this.context.tx = tx\n await this.executeInTransaction()\n })\n } else {\n await this.executeInTransaction()\n }\n if (!this.isCancelRequestedOrNotRunning()) {\n await this.setStatus(JobStatus.succeeded)\n }\n } catch (error: any) {\n // a job can fail while still pending (e.g. the transaction cannot be opened, or onStart fails)\n if (!this.cancelRequested && !this.isFailed() && !this.isCanceled()) {\n this.logError(error.stack ?? error)\n const { key, params } = this.getErrorInfo(error)\n this.addError({ error: { valid: false, errors: [{ key, params }] } })\n await this.setStatus(JobStatus.failed)\n }\n } finally {\n this.context.tx = undefined\n }\n }\n\n private async executeInTransaction(): Promise<void> {\n try {\n // canceled while the transaction was being opened: it must not be set as running again\n if (this.cancelRequested) return\n\n await this.onStart()\n\n const shouldExecute = await this.shouldExecute()\n if (shouldExecute) {\n if (this.innerJobs.length > 0) {\n await this.executeJobs()\n } else {\n await this.execute()\n }\n if (!this.isCancelRequestedOrNotRunning()) {\n await this.beforeSuccess()\n }\n }\n } finally {\n // runs only if not already run by cancel()\n await this.runBeforeEnd()\n this.context.tx = undefined\n }\n\n if (this.isCancelRequestedOrNotRunning()) {\n this.throwError(SystemErrorKeys.job.canceledOrErrorsFound)\n }\n }\n\n /**\n * Generates a plain JSON-serializable representation of the job, including its inner jobs.\n */\n toJSON(): JobSerialized<R> {\n const { errors, processed, result, status, total, type, userUuid, uuid } = this\n\n return {\n uuid,\n type,\n userUuid,\n surveyId: this.surveyId,\n innerJobs: this.innerJobs.map((job) => job.toJSON()),\n currentInnerJobIndex: this.currentInnerJobIndex,\n\n status,\n pending: this.isPending(),\n running: this.isRunning(),\n succeeded: this.isSucceeded(),\n canceled: this.isCanceled(),\n failed: this.isFailed(),\n ended: this.isEnded(),\n\n total,\n processed,\n progressPercent: this.calculateProgressPercent(),\n elapsedMillis: this.calculateElapsedMillis(),\n\n errors: this.isFailed() ? errors : undefined,\n result: this.isSucceeded() ? result : undefined,\n }\n }\n\n private async executeJobs(): Promise<void> {\n this.logDebug(`- ${this.total} inner jobs found`)\n\n for (let i = 0; i < this.innerJobs.length; i++) {\n // canceled between two inner jobs: the next ones must not be started\n if (this.cancelRequested) break\n\n this.logDebug(`- executing inner job ${i + 1}`)\n this.currentInnerJobIndex = i\n const currentInnerJob = this.innerJobs[i]\n if (currentInnerJob.context) {\n Object.assign(this.context, currentInnerJob.context)\n }\n currentInnerJob.context = this.context\n currentInnerJob.onEvent((event) => {\n // handle the inner job events in sequence; errors are logged (they would be unhandled rejections otherwise)\n this.innerJobEventsQueue = this.innerJobEventsQueue\n .then(() => this.onInnerJobEvent(event))\n .catch((error) => this.logError(error?.stack ?? error))\n })\n\n // The inner job shares this very context object, and its own start()/executeInTransaction()\n // clear `context.tx` when they terminate: without saving and restoring it here, the first\n // inner job would wipe the parent's transaction handle, leaving every following inner job\n // (and the parent's own beforeSuccess()/beforeEnd()) running outside of the transaction.\n // start() never throws (it swallows/records errors internally), so a plain restore is enough.\n const parentTx = this.context.tx\n await currentInnerJob.start(parentTx)\n this.context.tx = parentTx\n // the inner job events (e.g. canceled, failed) update the status of this job\n await this.innerJobEventsQueue\n\n if (this.cancelRequested || this.isCanceled() || currentInnerJob.isCanceled()) {\n break\n }\n if (currentInnerJob.isSucceeded()) {\n this.incrementProcessedItems()\n } else if (this.stopOnInnerJobFailure) {\n break\n }\n }\n if (\n !this.stopOnInnerJobFailure &&\n !this.cancelRequested &&\n this.innerJobs.some((innerJob) => innerJob.isFailed())\n ) {\n // set only after all inner jobs have run: setting it at the first failure would end this job (onEnd) too early\n await this.setStatus(JobStatus.failed)\n }\n\n this.logDebug(`- ${this.processed} inner jobs processed successfully`)\n }\n\n /**\n * Runs the job's own work when it has no inner jobs. Default implementation is a no-op, so\n * subclasses that only supply inner jobs (and never override this) don't need to. It also means\n * a subclass can safely call `super.execute()` defensively without knowing whether any ancestor\n * overrides it - if this were `abstract` instead, TypeScript would compile away any runtime\n * property for it entirely, so `super.execute()` would throw the moment no ancestor overrides it\n * (confirmed in production: a subclass whose immediate parent didn't override `execute()` crashed\n * with \"(intermediate value).execute is not a function\" the instant it called `super.execute()`).\n */\n protected async execute(): Promise<void> {\n // to be extended by subclasses\n }\n\n /**\n * Determines whether the job should actually run.\n * When it returns false, \"execute\" (or the inner jobs) will be skipped, but the job will still succeed.\n */\n protected shouldExecute(): Promise<boolean> {\n return Promise.resolve(true)\n }\n\n protected incrementProcessedItems(incrementBy = 1): void {\n this.processed += incrementBy\n }\n\n protected async setStatus(status: JobStatus): Promise<void> {\n this.logDebug(`set status: ${status}`)\n this.status = status\n\n const event: JobEvent = { type: JobEventType.statusChange, status, total: this.total, processed: this.processed }\n if (status === JobStatus.failed) {\n event.errors = this.errors\n }\n\n if (this.isEnded()) {\n this.logDebug('onEnd...')\n await this.onEnd()\n this.logDebug(`onEnd run. Job completed in ${this.elapsedTimePrettyFormat}`)\n }\n\n this.notifyEvent(event)\n }\n\n /**\n * Inner job event handler.\n */\n protected async onInnerJobEvent(event: JobEvent): Promise<void> {\n const { status } = event\n if (status === JobStatus.canceled) {\n this.canceledByAdmin = this.getCurrentInnerJob()?.canceledByAdmin ?? false\n return this.setStatus(status)\n }\n if (status === JobStatus.failed) {\n // report the errors of the failed inner job in the failed event (and in the errors) of this job\n Object.assign(this.errors, this.getCurrentInnerJob()?.errors ?? {})\n // when not stopping on inner job failures, this job is set as failed after all the inner jobs have run\n return this.stopOnInnerJobFailure ? this.setStatus(status) : undefined\n }\n if (status === JobStatus.running) {\n this.notifyEvent({\n type: JobEventType.progress,\n status: this.status,\n total: this.total,\n processed: this.processed,\n })\n return\n }\n this.logDebug(`Unknown inner job status: ${status}`)\n }\n\n /**\n * Called when the job just has been started.\n */\n protected async onStart(): Promise<void> {\n this.startTime = new Date()\n await this.setStatus(JobStatus.running)\n }\n\n /**\n * Called before beforeEnd only if the status will change to 'success'.\n * Default implementation stores the value returned by generateResult() via setResult().\n * It runs INSIDE the current db transaction.\n */\n protected async beforeSuccess(): Promise<void> {\n this.setResult(await this.generateResult())\n }\n\n /**\n * Computes the value beforeSuccess() will store as this job's result.\n * Default implementation returns whatever is already in `this.result`\n * (e.g. accumulated via earlier setResult() calls during execute()).\n */\n protected generateResult(): Promise<R | undefined> {\n return Promise.resolve(this.result)\n }\n\n /**\n * Updates this job's result. When both the current and incoming values are plain objects,\n * they are merged (Object.assign); otherwise the incoming value replaces the current one.\n * This keeps it safe for subclasses whose result is a primitive (e.g. a plain number) as\n * well as ones that build an object result incrementally across multiple setResult() calls.\n */\n protected setResult(result: R | undefined): void {\n if (result && typeof result === 'object' && this.result && typeof this.result === 'object') {\n Object.assign(this.result, result)\n } else {\n this.result = result\n }\n }\n\n /**\n * Called before onEnd. Useful for flushing resources used by the job before it terminates completely.\n * It runs INSIDE the current db transaction.\n */\n protected beforeEnd(): Promise<void> {\n this.logDebug('Cleanup')\n return Promise.resolve()\n }\n\n /**\n * Called when the job status changes to success, failed or canceled\n * (it runs OUTSIDE of the current db transaction)\n */\n protected onEnd(): Promise<void> {\n this.endTime = new Date()\n this.cancelNotifyProgress()\n return Promise.resolve()\n }\n\n protected addError(error: any, errorKey?: string): void {\n const key = errorKey ?? String(this.processed + 1)\n this.errors[key] = error\n }\n\n protected throwError(errorKey: string, params?: Dictionary<any>): void {\n // SystemError: getErrorInfo will report the translatable key instead of a generic error\n throw new SystemError(errorKey, params)\n }\n\n protected getErrorInfo(error: any): { key: string; params: Record<string, any> } {\n if (error instanceof SystemError) {\n return { key: `appErrors:${error.key}`, params: error.params }\n }\n return { key: 'appErrors:generic', params: { text: error.toString() } }\n }\n\n protected abstract createLogger(): Logger\n\n protected logDebug(...msgs: any[]): void {\n this.logger.debug(...msgs)\n }\n\n protected logInfo(...msgs: any[]): void {\n this.logger.info(...msgs)\n }\n\n protected logWarn(...msgs: any[]): void {\n this.logger.warn(...msgs)\n }\n\n protected logError(...msgs: any[]): void {\n this.logger.error(...msgs)\n }\n\n private get elapsedTimePrettyFormat(): string {\n const elapsedTime = this.calculateElapsedMillis()\n const elapsedMins = Math.floor(elapsedTime / 1000 / 60)\n const elapsedSeconds = String(Math.floor(elapsedTime / 1000) % 60).padStart(2, '0')\n const elapsedMillis = String(elapsedTime % 1000).padStart(3, '0')\n return `${elapsedMins}:${elapsedSeconds}.${elapsedMillis}`\n }\n\n private calculatePartialProgress(): number {\n if (this.isSucceeded()) return 100\n if (this.total > 0) return Math.floor((100 * this.processed) / this.total)\n return 0\n }\n\n private calculateProgressPercent(): number {\n const partialProgress = this.calculatePartialProgress()\n const currentInnerJob = this.getCurrentInnerJob()\n if (\n !currentInnerJob ||\n this.currentInnerJobIndex < 0 ||\n partialProgress === 100 ||\n this.processed > this.currentInnerJobIndex\n ) {\n return partialProgress\n }\n return partialProgress + Math.floor(currentInnerJob.calculateProgressPercent() / this.total)\n }\n\n private calculateElapsedMillis(): number {\n if (!this.startTime) return 0\n return (this.endTime ?? new Date()).getTime() - this.startTime.getTime()\n }\n\n /**\n * Notifies a progress event to the registered listener, throttled so that fast-changing\n * progress does not flood consumers (e.g. web socket clients).\n */\n private notifyProgress(): void {\n const run = (): void => {\n this.progressThrottleTimeoutId = undefined\n this.progressThrottleLastRunTime = Date.now()\n this.notifyEvent({\n type: JobEventType.progress,\n status: this.status,\n total: this.total,\n processed: this.processed,\n })\n }\n\n if (this.progressThrottleTimeoutId) return\n\n const elapsed = Date.now() - this.progressThrottleLastRunTime\n if (!this.progressThrottleLastRunTime || elapsed >= PROGRESS_NOTIFICATION_THROTTLE_MILLIS) {\n run()\n } else {\n this.progressThrottleTimeoutId = setTimeout(run, PROGRESS_NOTIFICATION_THROTTLE_MILLIS - elapsed)\n }\n }\n\n /**\n * Cancels any pending throttled progress notification and resets the throttle state.\n */\n private cancelNotifyProgress(): void {\n if (this.progressThrottleTimeoutId) {\n clearTimeout(this.progressThrottleTimeoutId)\n this.progressThrottleTimeoutId = undefined\n }\n this.progressThrottleLastRunTime = 0\n }\n\n /**\n * Notifies the event to the registered listener.\n * Listener errors are only logged: they would otherwise fail the job or, when thrown inside the progress\n * throttle timeout, crash the process.\n */\n private notifyEvent(event: JobEvent): void {\n const listener = this.eventListener\n if (!listener) return\n try {\n Promise.resolve(listener(event)).catch((error) => this.logListenerError(error))\n } catch (error) {\n this.logListenerError(error)\n }\n }\n\n private logListenerError(error: any): void {\n this.logError(`error in job event listener: ${error?.stack ?? error}`)\n }\n}\n"]}
1
+ {"version":3,"file":"JobBase.js","sourceRoot":"","sources":["../../../src/job/JobBase.ts"],"names":[],"mappings":";;;;;;;;;AAEA,OAAO,EAAE,WAAW,EAAE,eAAe,EAAE,MAAM,UAAU,CAAA;AAGvD,OAAO,EAAE,KAAK,EAAE,MAAM,UAAU,CAAA;AAIhC,OAAO,EAAY,YAAY,EAAE,MAAM,YAAY,CAAA;AAEnD,OAAO,EAAE,SAAS,EAAE,MAAM,UAAU,CAAA;AAcpC,MAAM,qCAAqC,GAAG,IAAI,CAAA;AAElD;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,MAAM,OAAgB,OAAO;IAiC3B,YAAmB,OAAU,EAAE,SAAS,GAAsB,EAAE;;QAxBhE,WAAM,GAAc,SAAS,CAAC,OAAO,CAAA;QAIrC,WAAM,GAAkB,SAAS,CAAA;QACjC,WAAM,GAAwB,EAAE,CAAA;QAMtB,yBAAoB,GAAG,CAAC,CAAC,CAAA;QAE3B,eAAU,GAAG,CAAC,CAAA;QACd,kBAAa,GAA+C,SAAS,CAAA;QACrE,8BAAyB,GAA8C,SAAS,CAAA;QAChF,gCAA2B,GAAG,CAAC,CAAA;QAC/B,2BAAsB,GAAG,IAAI,CAAA;QACrC,8FAA8F;QACtF,oBAAe,GAAG,KAAK,CAAA;QACvB,oBAAe,GAAG,KAAK,CAAA;QAC/B,uFAAuF;QAC/E,wBAAmB,GAAkB,OAAO,CAAC,OAAO,EAAE,CAAA;QAG5D,IAAI,CAAC,OAAO,qBAAQ,OAAO,CA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IAChB,IAAI,EAAE,MAAM;CACb,AAJ0B,CAI1B","sourcesContent":["import { User } from '../auth'\nimport { Dictionary } from '../common'\nimport { SystemError, SystemErrorKeys } from '../error'\nimport { Logger } from '../logger'\nimport { Survey } from '../survey'\nimport { UUIDs } from '../utils'\n\nimport { Job } from './job'\nimport { JobContext } from './jobContext'\nimport { JobEvent, JobEventType } from './jobEvent'\nimport { JobSerialized } from './jobSerialized'\nimport { JobStatus } from './status'\n\nexport interface JobConstructor {\n new <C extends JobContext, R>(context: C, innerJobs?: JobBase<any>[]): JobBase<C, R>\n readonly prototype: JobBase<any, any>\n}\n\n/**\n * Client able to open a transaction (e.g. a pg-promise database): the job runs inside `client.tx(callback)`.\n */\nexport interface JobTxClient {\n tx(callback: (tx: any) => Promise<void>): Promise<unknown>\n}\n\nconst PROGRESS_NOTIFICATION_THROTTLE_MILLIS = 1000\n\n/**\n * Asynchronous task handler.\n *\n * Status workflow:\n * - pending\n * - running\n * - (end)\n * -- succeeded\n * -- failed\n * -- canceled\n *\n * Methods that can be overwritten by subclasses:\n * - shouldExecute (in tx)\n * - onStart (in tx)\n * - execute (in tx)\n * - beforeSuccess (in tx)\n * - generateResult (in tx)\n * - beforeEnd (in tx)\n * - onEnd (out of tx)\n * - getErrorInfo\n */\nexport abstract class JobBase<C extends JobContext, R = undefined> implements Job<R> {\n static readonly keysContext = {\n surveyId: 'surveyId',\n survey: 'survey',\n user: 'user',\n }\n\n readonly uuid: string\n readonly type: string\n status: JobStatus = JobStatus.pending\n startTime?: Date\n endTime?: Date\n total: number\n result: R | undefined = undefined\n errors: Record<string, any> = {}\n canceledByAdmin?: boolean\n\n protected logger: Logger\n protected context: C\n protected innerJobs: JobBase<C, any>[]\n protected currentInnerJobIndex = -1\n\n private _processed = 0\n private eventListener: ((event: JobEvent) => unknown) | undefined = undefined\n private progressThrottleTimeoutId: ReturnType<typeof setTimeout> | undefined = undefined\n private progressThrottleLastRunTime = 0\n private _stopOnInnerJobFailure = true\n // set as soon as cancel() is called (the canceled status is set only after beforeEnd has run)\n private cancelRequested = false\n private beforeEndCalled = false\n // inner job events are handled in sequence; executeJobs waits for them before going on\n private innerJobEventsQueue: Promise<void> = Promise.resolve()\n\n public constructor(context: C, innerJobs: JobBase<C, any>[] = []) {\n this.context = { ...context }\n this.innerJobs = innerJobs\n\n this.uuid = UUIDs.v4()\n this.type = this.context.type ?? this.constructor.name\n this.total = innerJobs.length > 0 ? innerJobs.length : 1\n\n // Created last, so that createLogger() overrides can safely build the logger name out of\n // the job identity (e.g. arena's `Job <ClassName> (<uuid>)` log correlation id).\n this.logger = this.createLogger()\n }\n\n get processed(): number {\n return this._processed\n }\n\n set processed(value: number) {\n this._processed = value\n this.notifyProgress()\n }\n\n get stopOnInnerJobFailure(): boolean {\n return this._stopOnInnerJobFailure\n }\n\n set stopOnInnerJobFailure(value: boolean) {\n this._stopOnInnerJobFailure = value\n }\n\n protected get surveyId(): number | null {\n return this.context.surveyId ?? null\n }\n\n protected get user(): User {\n return this.context.user\n }\n\n protected get userUuid(): string | undefined {\n return this.user?.uuid\n }\n\n protected get contextSurvey(): Survey | undefined {\n return this.context.survey\n }\n\n /**\n * Returns the value of the specified context prop, or the default value (null if not specified) when not set.\n */\n protected getContextProp<K extends keyof C & string>(prop: K, defaultValue?: C[K] | null): C[K] | null\n /** Context prop not declared in the context type: the value is typed by the caller. */\n protected getContextProp<T = any, P extends string = string>(\n prop: P extends keyof C ? never : P,\n defaultValue?: T | null\n ): T | null\n protected getContextProp(prop: string, defaultValue: unknown = null): unknown {\n const value = (this.context as Record<string, unknown>)[prop]\n return value ?? defaultValue\n }\n\n protected setContext(context: Partial<C>): void {\n Object.assign(this.context, context)\n }\n\n protected deleteContextProps(...propNames: string[]): void {\n propNames.forEach((propName) => {\n delete (this.context as any)[propName]\n })\n }\n\n /**\n * Registers the listener notified of job events (status changes and progress).\n * Only one listener can be registered at a time; registering a new one replaces the previous one.\n * Errors thrown (or rejections returned) by the listener are logged and do not affect the job execution.\n */\n onEvent(listener: (event: JobEvent) => unknown): this {\n this.eventListener = listener\n return this\n }\n\n isPending(): boolean {\n return this.status === JobStatus.pending\n }\n\n isRunning(): boolean {\n return this.status === JobStatus.running\n }\n\n isSucceeded(): boolean {\n return this.status === JobStatus.succeeded\n }\n\n isFailed(): boolean {\n return this.status === JobStatus.failed\n }\n\n isCanceled(): boolean {\n return this.status === JobStatus.canceled\n }\n\n isEnded(): boolean {\n return [JobStatus.succeeded, JobStatus.failed, JobStatus.canceled].includes(this.status)\n }\n\n hasErrors(): boolean {\n return Object.keys(this.errors).length > 0\n }\n\n protected getCurrentInnerJob(): JobBase<C, any> | undefined {\n return this.innerJobs[this.currentInnerJobIndex]\n }\n\n protected combineInnerJobsResults(): Record<string, any> {\n const results: Record<string, any> = {}\n this.innerJobs.forEach((innerJob) => Object.assign(results, innerJob.result ?? {}))\n return results\n }\n\n protected combineInnerJobsErrors(): Record<string, any> {\n const errors: Record<string, any> = {}\n this.innerJobs.forEach((innerJob) => JobBase.mergeInnerJobErrors(errors, innerJob))\n return errors\n }\n\n /**\n * Adds the errors of the inner job to the specified errors.\n * Error keys already in use (e.g. the same item number used by two inner jobs) are prefixed with the inner job type\n * (and suffixed with a counter if still in use), so that no error gets overwritten.\n */\n private static mergeInnerJobErrors(errors: Record<string, any>, innerJob: JobBase<any, any>): void {\n Object.entries(innerJob.errors ?? {}).forEach(([key, error]) => {\n let uniqueKey = key\n if (uniqueKey in errors) {\n const prefixedKey = `${innerJob.type} ${key}`\n uniqueKey = prefixedKey\n let count = 2\n while (uniqueKey in errors) {\n uniqueKey = `${prefixedKey} (${count})`\n count += 1\n }\n }\n errors[uniqueKey] = error\n })\n }\n\n async cancel(options: { canceledByAdmin?: boolean } = {}): Promise<void> {\n const { canceledByAdmin = false } = options\n if (this.isEnded()) return\n\n this.cancelRequested = true\n\n const currentInnerJob = this.getCurrentInnerJob()\n if (currentInnerJob && !currentInnerJob.isEnded()) {\n // inner job running or about to start (pending):\n // the parent job status will be set to canceled when handling the canceled event of the inner job\n await currentInnerJob.cancel({ canceledByAdmin })\n return\n }\n // no inner job running (job without inner jobs, or between two inner jobs)\n this.canceledByAdmin = canceledByAdmin\n // release the resources (temp files/directories, streams) allocated before the cancellation\n await this.runBeforeEnd()\n await this.setStatus(JobStatus.canceled)\n }\n\n /**\n * Returns true when the job has been canceled (or is no longer running).\n * Long-running subclasses can check it to stop processing items (e.g. in a loop) as soon as the job is canceled.\n */\n protected isCancelRequestedOrNotRunning(): boolean {\n return this.cancelRequested || !this.isRunning()\n }\n\n /**\n * Runs beforeEnd only once (it can be called by cancel() and when the job execution ends).\n */\n private async runBeforeEnd(): Promise<void> {\n if (this.beforeEndCalled) return\n this.beforeEndCalled = true\n await this.beforeEnd()\n }\n\n async start(client: JobTxClient | null = null): Promise<void> {\n // canceled before being started: nothing to execute\n if (this.cancelRequested || this.isEnded()) return\n\n this.logDebug('start')\n\n try {\n if (client) {\n await client.tx(async (tx: any) => {\n this.context.tx = tx\n await this.executeInTransaction()\n })\n } else {\n await this.executeInTransaction()\n }\n if (!this.isCancelRequestedOrNotRunning()) {\n await this.setStatus(JobStatus.succeeded)\n }\n } catch (error: any) {\n // a job can fail while still pending (e.g. the transaction cannot be opened, or onStart fails)\n if (!this.cancelRequested && !this.isFailed() && !this.isCanceled()) {\n this.logError(error.stack ?? error)\n const { key, params } = this.getErrorInfo(error)\n this.addError({ error: { valid: false, errors: [{ key, params }] } })\n await this.setStatus(JobStatus.failed)\n }\n } finally {\n this.context.tx = undefined\n }\n }\n\n private async executeInTransaction(): Promise<void> {\n try {\n // canceled while the transaction was being opened: it must not be set as running again\n if (this.cancelRequested) return\n\n await this.onStart()\n\n const shouldExecute = await this.shouldExecute()\n if (shouldExecute) {\n if (this.innerJobs.length > 0) {\n await this.executeJobs()\n } else {\n await this.execute()\n }\n if (!this.isCancelRequestedOrNotRunning()) {\n await this.beforeSuccess()\n }\n }\n } finally {\n // runs only if not already run by cancel()\n await this.runBeforeEnd()\n this.context.tx = undefined\n }\n\n if (this.isCancelRequestedOrNotRunning()) {\n this.throwError(SystemErrorKeys.job.canceledOrErrorsFound)\n }\n }\n\n /**\n * Generates a plain JSON-serializable representation of the job, including its inner jobs.\n */\n toJSON(): JobSerialized<R> {\n const { errors, processed, result, status, total, type, userUuid, uuid } = this\n\n return {\n uuid,\n type,\n userUuid,\n surveyId: this.surveyId,\n innerJobs: this.innerJobs.map((job) => job.toJSON()),\n currentInnerJobIndex: this.currentInnerJobIndex,\n\n status,\n pending: this.isPending(),\n running: this.isRunning(),\n succeeded: this.isSucceeded(),\n canceled: this.isCanceled(),\n failed: this.isFailed(),\n ended: this.isEnded(),\n\n total,\n processed,\n progressPercent: this.calculateProgressPercent(),\n elapsedMillis: this.calculateElapsedMillis(),\n\n errors: this.isFailed() ? errors : undefined,\n result: this.isSucceeded() ? result : undefined,\n }\n }\n\n private async executeJobs(): Promise<void> {\n this.logDebug(`- ${this.total} inner jobs found`)\n\n for (let i = 0; i < this.innerJobs.length; i++) {\n // canceled between two inner jobs: the next ones must not be started\n if (this.cancelRequested) break\n\n this.logDebug(`- executing inner job ${i + 1}`)\n this.currentInnerJobIndex = i\n const currentInnerJob = this.innerJobs[i]\n if (currentInnerJob.context) {\n Object.assign(this.context, currentInnerJob.context)\n }\n currentInnerJob.context = this.context\n currentInnerJob.onEvent((event) => {\n // handle the inner job events in sequence; errors are logged (they would be unhandled rejections otherwise)\n this.innerJobEventsQueue = this.innerJobEventsQueue\n .then(() => this.onInnerJobEvent(event))\n .catch((error) => this.logError(error?.stack ?? error))\n })\n\n // The inner job shares this very context object, and its own start()/executeInTransaction()\n // clear `context.tx` when they terminate: without saving and restoring it here, the first\n // inner job would wipe the parent's transaction handle, leaving every following inner job\n // (and the parent's own beforeSuccess()/beforeEnd()) running outside of the transaction.\n // start() never throws (it swallows/records errors internally), so a plain restore is enough.\n const parentTx = this.context.tx\n await currentInnerJob.start(parentTx)\n this.context.tx = parentTx\n // the inner job events (e.g. canceled, failed) update the status of this job\n await this.innerJobEventsQueue\n\n if (this.cancelRequested || this.isCanceled() || currentInnerJob.isCanceled()) {\n break\n }\n if (currentInnerJob.isSucceeded()) {\n this.incrementProcessedItems()\n } else if (this.stopOnInnerJobFailure) {\n break\n }\n }\n if (\n !this.stopOnInnerJobFailure &&\n !this.cancelRequested &&\n this.innerJobs.some((innerJob) => innerJob.isFailed())\n ) {\n // set only after all inner jobs have run: setting it at the first failure would end this job (onEnd) too early\n await this.runBeforeEnd()\n await this.setStatus(JobStatus.failed)\n }\n\n this.logDebug(`- ${this.processed} inner jobs processed successfully`)\n }\n\n /**\n * Runs the job's own work when it has no inner jobs. Default implementation is a no-op, so\n * subclasses that only supply inner jobs (and never override this) don't need to. It also means\n * a subclass can safely call `super.execute()` defensively without knowing whether any ancestor\n * overrides it - if this were `abstract` instead, TypeScript would compile away any runtime\n * property for it entirely, so `super.execute()` would throw the moment no ancestor overrides it\n * (confirmed in production: a subclass whose immediate parent didn't override `execute()` crashed\n * with \"(intermediate value).execute is not a function\" the instant it called `super.execute()`).\n */\n protected async execute(): Promise<void> {\n // to be extended by subclasses\n }\n\n /**\n * Determines whether the job should actually run.\n * When it returns false, \"execute\" (or the inner jobs) will be skipped, but the job will still succeed.\n */\n protected shouldExecute(): Promise<boolean> {\n return Promise.resolve(true)\n }\n\n protected incrementProcessedItems(incrementBy = 1): void {\n this.processed += incrementBy\n }\n\n protected async setStatus(status: JobStatus): Promise<void> {\n this.logDebug(`set status: ${status}`)\n this.status = status\n\n const event: JobEvent = { type: JobEventType.statusChange, status, total: this.total, processed: this.processed }\n if (status === JobStatus.failed) {\n event.errors = this.errors\n }\n\n if (this.isEnded()) {\n this.logDebug('onEnd...')\n await this.onEnd()\n this.logDebug(`onEnd run. Job completed in ${this.elapsedTimePrettyFormat}`)\n }\n\n this.notifyEvent(event)\n }\n\n /**\n * Inner job event handler.\n */\n protected async onInnerJobEvent(event: JobEvent): Promise<void> {\n const { status } = event\n if (status === JobStatus.canceled) {\n this.canceledByAdmin = this.getCurrentInnerJob()?.canceledByAdmin ?? false\n // beforeEnd must run before onEnd (it runs only once: it won't run again when the execution ends)\n await this.runBeforeEnd()\n return this.setStatus(status)\n }\n if (status === JobStatus.failed) {\n // report the errors of the failed inner job in the failed event (and in the errors) of this job\n const currentInnerJob = this.getCurrentInnerJob()\n if (currentInnerJob) {\n JobBase.mergeInnerJobErrors(this.errors, currentInnerJob)\n }\n // when not stopping on inner job failures, this job is set as failed after all the inner jobs have run\n if (this.stopOnInnerJobFailure) {\n await this.runBeforeEnd()\n await this.setStatus(status)\n }\n return\n }\n if (status === JobStatus.running) {\n this.notifyEvent({\n type: JobEventType.progress,\n status: this.status,\n total: this.total,\n processed: this.processed,\n })\n return\n }\n this.logDebug(`Unknown inner job status: ${status}`)\n }\n\n /**\n * Called when the job just has been started.\n */\n protected async onStart(): Promise<void> {\n this.startTime = new Date()\n await this.setStatus(JobStatus.running)\n }\n\n /**\n * Called before beforeEnd only if the status will change to 'success'.\n * Default implementation stores the value returned by generateResult() via setResult().\n * It runs INSIDE the current db transaction.\n */\n protected async beforeSuccess(): Promise<void> {\n this.setResult(await this.generateResult())\n }\n\n /**\n * Computes the value beforeSuccess() will store as this job's result.\n * Default implementation returns whatever is already in `this.result`\n * (e.g. accumulated via earlier setResult() calls during execute()).\n */\n protected generateResult(): Promise<R | undefined> {\n return Promise.resolve(this.result)\n }\n\n /**\n * Updates this job's result. When both the current and incoming values are plain objects,\n * they are merged (Object.assign); otherwise the incoming value replaces the current one.\n * This keeps it safe for subclasses whose result is a primitive (e.g. a plain number) as\n * well as ones that build an object result incrementally across multiple setResult() calls.\n */\n protected setResult(result: R | undefined): void {\n if (result && typeof result === 'object' && this.result && typeof this.result === 'object') {\n Object.assign(this.result, result)\n } else {\n this.result = result\n }\n }\n\n /**\n * Called before onEnd. Useful for flushing resources used by the job before it terminates completely.\n * It runs INSIDE the current db transaction.\n */\n protected beforeEnd(): Promise<void> {\n this.logDebug('Cleanup')\n return Promise.resolve()\n }\n\n /**\n * Called when the job status changes to success, failed or canceled\n * (it runs OUTSIDE of the current db transaction)\n */\n protected onEnd(): Promise<void> {\n this.endTime = new Date()\n this.cancelNotifyProgress()\n return Promise.resolve()\n }\n\n protected addError(error: any, errorKey?: string): void {\n const key = errorKey ?? String(this.processed + 1)\n this.errors[key] = error\n }\n\n protected throwError(errorKey: string, params?: Dictionary<any>): void {\n // SystemError: getErrorInfo will report the translatable key instead of a generic error\n throw new SystemError(errorKey, params)\n }\n\n protected getErrorInfo(error: any): { key: string; params: Record<string, any> } {\n if (error instanceof SystemError) {\n return { key: `appErrors:${error.key}`, params: error.params }\n }\n return { key: 'appErrors:generic', params: { text: error.toString() } }\n }\n\n protected abstract createLogger(): Logger\n\n protected logDebug(...msgs: any[]): void {\n this.logger.debug(...msgs)\n }\n\n protected logInfo(...msgs: any[]): void {\n this.logger.info(...msgs)\n }\n\n protected logWarn(...msgs: any[]): void {\n this.logger.warn(...msgs)\n }\n\n protected logError(...msgs: any[]): void {\n this.logger.error(...msgs)\n }\n\n private get elapsedTimePrettyFormat(): string {\n const elapsedTime = this.calculateElapsedMillis()\n const elapsedMins = Math.floor(elapsedTime / 1000 / 60)\n const elapsedSeconds = String(Math.floor(elapsedTime / 1000) % 60).padStart(2, '0')\n const elapsedMillis = String(elapsedTime % 1000).padStart(3, '0')\n return `${elapsedMins}:${elapsedSeconds}.${elapsedMillis}`\n }\n\n private calculatePartialProgress(): number {\n if (this.isSucceeded()) return 100\n if (this.total > 0) return Math.floor((100 * this.processed) / this.total)\n return 0\n }\n\n private calculateProgressPercent(): number {\n const partialProgress = this.calculatePartialProgress()\n const currentInnerJob = this.getCurrentInnerJob()\n if (\n !currentInnerJob ||\n this.currentInnerJobIndex < 0 ||\n partialProgress === 100 ||\n this.processed > this.currentInnerJobIndex\n ) {\n return partialProgress\n }\n return partialProgress + Math.floor(currentInnerJob.calculateProgressPercent() / this.total)\n }\n\n private calculateElapsedMillis(): number {\n if (!this.startTime) return 0\n return (this.endTime ?? new Date()).getTime() - this.startTime.getTime()\n }\n\n /**\n * Notifies a progress event to the registered listener, throttled so that fast-changing\n * progress does not flood consumers (e.g. web socket clients).\n */\n private notifyProgress(): void {\n // onEnd has already cleared the throttle: no progress events after the job has ended\n if (this.isEnded()) return\n\n const run = (): void => {\n this.progressThrottleTimeoutId = undefined\n this.progressThrottleLastRunTime = Date.now()\n this.notifyEvent({\n type: JobEventType.progress,\n status: this.status,\n total: this.total,\n processed: this.processed,\n })\n }\n\n if (this.progressThrottleTimeoutId) return\n\n const elapsed = Date.now() - this.progressThrottleLastRunTime\n if (!this.progressThrottleLastRunTime || elapsed >= PROGRESS_NOTIFICATION_THROTTLE_MILLIS) {\n run()\n } else {\n this.progressThrottleTimeoutId = setTimeout(run, PROGRESS_NOTIFICATION_THROTTLE_MILLIS - elapsed)\n }\n }\n\n /**\n * Cancels any pending throttled progress notification and resets the throttle state.\n */\n private cancelNotifyProgress(): void {\n if (this.progressThrottleTimeoutId) {\n clearTimeout(this.progressThrottleTimeoutId)\n this.progressThrottleTimeoutId = undefined\n }\n this.progressThrottleLastRunTime = 0\n }\n\n /**\n * Notifies the event to the registered listener.\n * Listener errors are only logged: they would otherwise fail the job or, when thrown inside the progress\n * throttle timeout, crash the process.\n */\n private notifyEvent(event: JobEvent): void {\n const listener = this.eventListener\n if (!listener) return\n try {\n Promise.resolve(listener(event)).catch((error) => this.logListenerError(error))\n } catch (error) {\n this.logListenerError(error)\n }\n }\n\n private logListenerError(error: any): void {\n this.logError(`error in job event listener: ${error?.stack ?? error}`)\n }\n}\n"]}
@@ -174,7 +174,9 @@ export const getDescendantsOrSelf = (node, nodeDefDescendant) => (record) => {
174
174
  let currentDescendants = [];
175
175
  for (const currentDescendantDefUuid of descendantNodeDefUuids) {
176
176
  for (const currentAncestor of currentAncestors) {
177
- currentDescendants.push(...getChildren(currentAncestor, currentDescendantDefUuid)(record));
177
+ for (const child of getChildren(currentAncestor, currentDescendantDefUuid)(record)) {
178
+ currentDescendants.push(child);
179
+ }
178
180
  }
179
181
  currentAncestors = currentDescendants;
180
182
  currentDescendants = [];
@@ -282,7 +284,9 @@ export const getAttributeSiblings = (node, nodeDef) => (record) => {
282
284
  return [];
283
285
  const siblingParentEntities = getEntitySiblings(parentEntity)(record);
284
286
  return siblingParentEntities.reduce((siblingsAcc, siblingEntity) => {
285
- siblingsAcc.push(...getChildren(siblingEntity, nodeDef.uuid)(record));
287
+ for (const sibling of getChildren(siblingEntity, nodeDef.uuid)(record)) {
288
+ siblingsAcc.push(sibling);
289
+ }
286
290
  return siblingsAcc;
287
291
  }, []);
288
292
  };
@@ -1 +1 @@
1
- {"version":3,"file":"recordGetters.js","sourceRoot":"","sources":["../../../../src/record/_records/recordGetters.ts"],"names":[],"mappings":"AAAA,OAAO,EAAc,cAAc,EAAE,MAAM,cAAc,CAAA;AACzD,OAAO,EAAE,WAAW,EAAE,eAAe,EAAE,MAAM,aAAa,CAAA;AAC1D,OAAO,EAAgC,KAAK,EAAY,MAAM,YAAY,CAAA;AAC1E,OAAO,EAAE,UAAU,EAAE,MAAM,uBAAuB,CAAA;AAClD,OAAO,EAAwD,QAAQ,EAAe,MAAM,eAAe,CAAA;AAC3G,OAAO,EAAE,YAAY,EAAE,OAAO,EAAE,MAAM,cAAc,CAAA;AAEpD,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,aAAa,CAAA;AAC3C,OAAO,EAAe,mBAAmB,EAAoB,MAAM,WAAW,CAAA;AAC9E,OAAO,EAAE,sBAAsB,EAAE,MAAM,eAAe,CAAA;AACtD,OAAO,EAAE,sBAAsB,EAAE,MAAM,0BAA0B,CAAA;AACjE,OAAO,EAAE,uBAAuB,EAAE,MAAM,2BAA2B,CAAA;AACnE,OAAO,EAAE,qBAAqB,EAAE,MAAM,yBAAyB,CAAA;AAE/D,MAAM,CAAC,MAAM,QAAQ,GAAG,CAAC,MAAmB,EAAU,EAAE,wBAAC,MAAM,CAAC,KAAK,mCAAI,YAAY,GAAA,CAA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GAAA,CAAA;AAE1F,MAAM,CAAC,MAAM,gBAAgB,GAAG,CAAC,MAAmB,EAAW,EAAE,CAAC,OAAO,CAAC,MAAM,CAAC,KAAK,sBAAsB,CAAA","sourcesContent":["import { Dictionary, TraverseMethod } from '../../common'\nimport { SystemError, SystemErrorKeys } from '../../error'\nimport { ArenaRecordNode, NodePointer, Nodes, NodesMap } from '../../node'\nimport { NodeValues } from '../../node/nodeValues'\nimport { NodeDef, NodeDefCode, NodeDefCodeProps, NodeDefProps, NodeDefs, NodeDefType } from '../../nodeDef'\nimport { defaultCycle, Surveys } from '../../survey'\nimport { Survey, SurveyDependencyType } from '../../survey/survey'\nimport { Arrays, Queue } from '../../utils'\nimport { ArenaRecord, RECORD_STEP_DEFAULT, RecordNodesIndex } from '../record'\nimport { RecordStepAnalysisCode } from '../recordStep'\nimport { RecordNodesIndexReader } from './recordNodesIndexReader'\nimport { RecordNodesIndexUpdater } from './recordNodesIndexUpdater'\nimport { NodeDefSelfReferences } from './nodeDefSelfReferences'\n\nexport const getCycle = (record: ArenaRecord): string => record.cycle ?? defaultCycle\n\nexport const getNodes = (record: ArenaRecord): Dictionary<ArenaRecordNode> => record.nodes ?? {}\n\nexport const getNodesArray = (record: ArenaRecord): ArenaRecordNode[] => Object.values(getNodes(record))\n\n/**\n * Returns the nodes index of the record or, if missing, a new index built from all the record nodes (not stored in the record).\n * To be used before updating the index: a partial index would be trusted by the getters.\n */\nexport const getNodesIndexOrBuild = (record: ArenaRecord): RecordNodesIndex =>\n record._nodesIndex ?? RecordNodesIndexUpdater.initializeIndex(record)\n\n/**\n * Returns the node with the specified uuid, or undefined if not found.\n * Like the other node getters, it does not throw an error when the node is not found.\n */\nexport const getNodeByUuid =\n (uuid: string) =>\n (record: ArenaRecord): ArenaRecordNode | undefined =>\n record.nodes?.[uuid]\n\nexport const getNodesByUuids =\n (uuids: string[]) =>\n (record: ArenaRecord): ArenaRecordNode[] =>\n uuids.map((uuid: string) => record.nodes?.[uuid]) as ArenaRecordNode[]\n\n/**\n * Returns the root node, or undefined if the record has no nodes.\n */\nexport const getRoot = (record: ArenaRecord): ArenaRecordNode | undefined => {\n const rootUuid = record._nodesIndex ? RecordNodesIndexReader.getNodeRootUuid(record._nodesIndex) : null\n if (rootUuid) {\n return getNodeByUuid(rootUuid)(record)\n }\n return getNodesArray(record).find((node) => !node.parentUuid)\n}\n\nexport const getChildren =\n (parentNode: ArenaRecordNode, childDefUuid?: string) =>\n (record: ArenaRecord): ArenaRecordNode[] => {\n if (record._nodesIndex) {\n const childrenUuids = childDefUuid\n ? RecordNodesIndexReader.getNodeUuidsByParentAndChildDef({\n parentNodeUuid: parentNode.uuid,\n childDefUuid,\n })(record._nodesIndex)\n : RecordNodesIndexReader.getNodeUuidsByParent(parentNode.uuid)(record._nodesIndex)\n return getNodesByUuids(childrenUuids)(record)\n }\n return getNodesArray(record).filter(\n (node) => node.parentUuid === parentNode.uuid && (!childDefUuid || node.nodeDefUuid == childDefUuid)\n )\n }\n\n/**\n * Returns the only child of the parent node with the specified node def, or undefined if not found.\n * Throws an error if more than one child is found.\n */\nexport const getChild =\n (parentNode: ArenaRecordNode, childDefUuid: string) =>\n (record: ArenaRecord): ArenaRecordNode | undefined => {\n const children = getChildren(parentNode, childDefUuid)(record)\n if (children.length > 1) {\n const errorParams = { childDefUuid, parentNodeUuid: parentNode.uuid, recordUuid: record.uuid }\n throw new SystemError(SystemErrorKeys.record.multipleNodesFound, errorParams)\n }\n return children[0]\n }\n\n// called for every ancestor in the record update loops: keep it a plain lookup\nconst getParentNode = (record: ArenaRecord, node: ArenaRecordNode): ArenaRecordNode | undefined =>\n node.parentUuid ? record.nodes?.[node.parentUuid] : undefined\n\nexport const getParent =\n (node: ArenaRecordNode) =>\n (record: ArenaRecord): ArenaRecordNode | undefined =>\n getParentNode(record, node)\n\nexport const getNodesByDefUuid =\n (nodeDefUuid: string) =>\n (record: ArenaRecord): ArenaRecordNode[] => {\n if (record._nodesIndex) {\n const nodeUuids = RecordNodesIndexReader.getNodeUuidsByDef(nodeDefUuid)(record._nodesIndex)\n return getNodesByUuids(nodeUuids)(record)\n }\n return getNodesArray(record).filter((node) => node.nodeDefUuid === nodeDefUuid)\n }\n\nconst isNodeFlagTrue =\n (isChildFlagTrue: (parent: ArenaRecordNode, nodeDefUuid: string) => boolean) =>\n (node: ArenaRecordNode) =>\n (record: ArenaRecord): boolean => {\n let child = node\n let parent = getParentNode(record, child)\n while (parent) {\n if (!isChildFlagTrue(parent, child.nodeDefUuid)) return false\n child = parent\n parent = getParentNode(record, child)\n }\n return true\n }\n\nexport const isNodeApplicable = isNodeFlagTrue((parent, nodeDefUuid) => Nodes.isChildApplicable(parent, nodeDefUuid))\nexport const isNodeEditable = isNodeFlagTrue((parent, nodeDefUuid) => Nodes.isChildEditable(parent, nodeDefUuid))\nexport const isNodeVisible = isNodeFlagTrue((parent, nodeDefUuid) => Nodes.isChildVisible(parent, nodeDefUuid))\n\n/**\n * Whether a value is required for the node: key or always required attribute, or attribute with a \"required if\"\n * condition met in its parent entity (evaluated condition stored in the parent node meta).\n */\nexport const isNodeRequired =\n (nodeDef: NodeDef<NodeDefType>, node: ArenaRecordNode) =>\n (record: ArenaRecord): boolean => {\n if (NodeDefs.isKey(nodeDef) || NodeDefs.isRequired(nodeDef)) return true\n if (!NodeDefs.isRequiredIfDefined(nodeDef)) return false\n const parent = getParentNode(record, node)\n return !!parent && Nodes.isChildRequired(parent, nodeDef.uuid)\n }\n\nexport const getDependentCodeAttributes =\n (node: ArenaRecordNode) =>\n (record: ArenaRecord): ArenaRecordNode[] => {\n if (record._nodesIndex) {\n const nodeUuids = RecordNodesIndexReader.getNodeCodeDependentUuids(node.uuid)(record._nodesIndex)\n return getNodesByUuids(nodeUuids)(record)\n }\n throw new SystemError(SystemErrorKeys.record.nodesIndexNotInitialized)\n }\n\nexport const getParentCodeAttribute =\n (parentNode: ArenaRecordNode, nodeDef: NodeDefCode) =>\n (record: ArenaRecord): ArenaRecordNode | undefined => {\n const parentCodeDefUuid = NodeDefs.getParentCodeDefUuid(nodeDef)\n if (!parentCodeDefUuid) return undefined\n\n const ancestors = getAncestorsAndSelf(parentNode)(record)\n for (const ancestor of ancestors) {\n const children = getChildren(ancestor, parentCodeDefUuid)(record)\n if (children.length === 1) {\n return children[0]\n }\n }\n return undefined\n }\n\n// ancestors\n\n/**\n * Visits the specified node and its ancestors, from the node up to the root: the visit stops when the visitor returns true.\n */\nexport const visitAncestorsAndSelf =\n (node: ArenaRecordNode, visitor: (node: ArenaRecordNode) => boolean | void) =>\n (record: ArenaRecord): void => {\n let currentNode: ArenaRecordNode | undefined = node\n while (currentNode) {\n if (visitor(currentNode)) return\n currentNode = getParentNode(record, currentNode)\n }\n }\n\n/**\n * Returns the first node satisfying the predicate among the specified node and its ancestors (from the node up to the root).\n */\nexport const findAncestor =\n (node: ArenaRecordNode, predicate: (node: ArenaRecordNode) => boolean) =>\n (record: ArenaRecord): ArenaRecordNode | undefined => {\n let result: ArenaRecordNode | undefined = undefined\n visitAncestorsAndSelf(node, (visitedNode) => {\n if (predicate(visitedNode)) {\n result = visitedNode\n return true\n }\n return false\n })(record)\n return result\n }\n\n/**\n * Returns the specified node, if it has the specified node def, or its ancestor with that node def; undefined if not found.\n */\nexport const getAncestor =\n (node: ArenaRecordNode, ancestorDefUuid: string) =>\n (record: ArenaRecord): ArenaRecordNode | undefined => {\n let ancestor: ArenaRecordNode | undefined = node\n while (ancestor && ancestor.nodeDefUuid !== ancestorDefUuid) {\n ancestor = getParentNode(record, ancestor)\n }\n return ancestor\n }\n\n/**\n * Returns the list of ancestors from the given node to the root entity\n */\nexport const getAncestorsAndSelf =\n (node: ArenaRecordNode) =>\n (record: ArenaRecord): Array<ArenaRecordNode> => {\n const ancestors: Array<ArenaRecordNode> = []\n let currentNode: ArenaRecordNode | undefined = node\n while (currentNode) {\n ancestors.push(currentNode)\n currentNode = getParentNode(record, currentNode)\n }\n return ancestors\n }\n\n// descendants\n\nexport const getDescendantsOrSelf =\n (node: ArenaRecordNode, nodeDefDescendant: NodeDef<any>) =>\n (record: ArenaRecord): ArenaRecordNode[] => {\n if (nodeDefDescendant.uuid === node.nodeDefUuid) return [node]\n\n const nodeDefDescendantFullHierarchy = [...nodeDefDescendant.meta.h, nodeDefDescendant.uuid]\n\n // 1. get the descendant node defs uuids starting from node nodeDefUuid (not inclusive) down to the specified nodeDefDescendant uuid\n const descendantNodeDefUuids = nodeDefDescendantFullHierarchy.slice(\n nodeDefDescendantFullHierarchy.indexOf(node.nodeDefUuid) + 1\n )\n // 2. for every level in the hierarchy, find the children having the nodeDefUuid equal to the current one\n let currentAncestors = [node]\n let currentDescendants: ArenaRecordNode[] = []\n for (const currentDescendantDefUuid of descendantNodeDefUuids) {\n for (const currentAncestor of currentAncestors) {\n currentDescendants.push(...getChildren(currentAncestor, currentDescendantDefUuid)(record))\n }\n currentAncestors = currentDescendants\n currentDescendants = []\n }\n return currentAncestors // currentAncestors is equal to the currentDescendants of the last level\n }\n\n/**\n * Returns the first descendant (or the node itself) with the specified node def, or undefined if not found.\n */\nexport const getDescendant =\n (node: ArenaRecordNode, nodeDefDescendant: NodeDef<any>) =>\n (record: ArenaRecord): ArenaRecordNode | undefined =>\n getDescendantsOrSelf(node, nodeDefDescendant)(record)[0]\n\nexport const isDescendantOf = (node: ArenaRecordNode, ancestor: ArenaRecordNode): boolean =>\n Nodes.getHierarchy(node).includes(ancestor.uuid)\n\nexport const visitDescendantsAndSelf =\n (\n node: ArenaRecordNode,\n visitor: (node: ArenaRecordNode) => boolean | void,\n traverseMethod: TraverseMethod = TraverseMethod.bfs\n ) =>\n (record: ArenaRecord): void => {\n if (traverseMethod === TraverseMethod.bfs) {\n const queue = new Queue<ArenaRecordNode>()\n\n queue.enqueue(node)\n\n while (!queue.isEmpty()) {\n const visitedNode = queue.dequeue()!\n\n if (visitor(visitedNode)) {\n // stop if visitor returns true\n return\n }\n\n const children = getChildren(visitedNode)(record)\n queue.enqueueItems(children)\n }\n } else {\n const stack = []\n\n stack.push(node)\n\n while (stack.length > 0) {\n const visitedNode = stack.pop() as ArenaRecordNode\n\n if (visitor(visitedNode)) {\n // stop if visitor returns true\n return\n }\n\n const children = getChildren(visitedNode)(record)\n\n // add children to stack in reverse order\n for (let index = children.length - 1; index >= 0; index--) {\n const child = children[index]\n stack.push(child)\n }\n }\n }\n }\n\nexport const findDescendantOrSelf =\n (node: ArenaRecordNode, predicate: (node: ArenaRecordNode) => boolean) =>\n (record: ArenaRecord): ArenaRecordNode | undefined => {\n let found = undefined\n\n visitDescendantsAndSelf(node, (currentNode) => {\n if (predicate(currentNode)) {\n found = currentNode\n return true\n }\n return false\n })(record)\n return found\n }\n\nconst getClosestAncestorNode =\n (\n node: ArenaRecordNode,\n nodeDef: NodeDef<NodeDefType, NodeDefProps>,\n dependentDef: NodeDef<NodeDefType, NodeDefProps>,\n dependencyType: SurveyDependencyType\n ) =>\n (record: ArenaRecord): ArenaRecordNode | undefined => {\n // 1a if dependent def is the same as node def, potentially all nodes with\n // nodeDefUuid === dependentDef.uuid in record could be dependent of nodeDef;\n // consider the root node as the closest ancestor node,\n // unless the node def references itself only among the children of its parent entity (e.g. validation \"dbh > 0\")\n if (nodeDef.uuid === dependentDef.uuid) {\n return NodeDefSelfReferences.isSelfReferenceLocal({ nodeDef, dependencyType })\n ? getParent(node)(record)\n : getRoot(record)\n }\n // 1 find common ancestor def\n const commonAncestorDefUuid = Arrays.last(Arrays.intersection(nodeDef.meta.h, dependentDef.meta.h))\n if (!commonAncestorDefUuid) return undefined\n\n // 2 get ancestor node with common parent def\n return getAncestor(node, commonAncestorDefUuid)(record)\n }\n\ntype KeyDefs = NodeDef<NodeDefType, NodeDefProps>[]\n\n/**\n * Returns the key nodes of the entity, indexed by key def uuid; keyDefs, when specified, are used instead of the\n * entity def keys in the cycle.\n */\nexport const getEntityKeyNodesByDefUuid =\n (survey: Survey, entity: ArenaRecordNode, cycle?: string, keyDefs?: KeyDefs) =>\n (record: ArenaRecord): NodesMap => {\n const nodeDef = Surveys.getNodeDefByUuid({ survey, uuid: entity.nodeDefUuid })\n const nodeDefKeys = keyDefs ?? Surveys.getNodeDefKeys({ survey, cycle, nodeDef })\n return nodeDefKeys.reduce((acc: NodesMap, nodeDefKey) => {\n const nodeKey = getDescendant(entity, nodeDefKey)(record)\n // missing key nodes are kept as undefined entries\n acc[nodeDefKey.uuid] = nodeKey as ArenaRecordNode\n return acc\n }, {})\n }\n\nexport const getEntityKeyNodes =\n (survey: Survey, entity: ArenaRecordNode, cycle?: string, keyDefs?: KeyDefs) =>\n (record: ArenaRecord): ArenaRecordNode[] =>\n Object.values(getEntityKeyNodesByDefUuid(survey, entity, cycle, keyDefs)(record))\n\nexport const getEntityKeyValuesByDefUuid =\n (survey: Survey, entity: ArenaRecordNode, cycle?: string, keyDefs?: KeyDefs) =>\n (record: ArenaRecord): Dictionary<any> => {\n const keyNodesByDefUuid = getEntityKeyNodesByDefUuid(survey, entity, cycle, keyDefs)(record)\n return Object.entries(keyNodesByDefUuid).reduce((acc: Dictionary<any>, [uuid, keyNode]) => {\n acc[uuid] = keyNode?.value\n return acc\n }, {})\n }\n\nexport const getEntityKeyValues =\n (survey: Survey, entity: ArenaRecordNode, cycle?: string, keyDefs?: KeyDefs) =>\n (record: ArenaRecord): any[] =>\n Object.values(getEntityKeyValuesByDefUuid(survey, entity, cycle, keyDefs)(record))\n\nexport const getEntitySiblings =\n (entity: ArenaRecordNode, includeSelf = false) =>\n (record: ArenaRecord): ArenaRecordNode[] => {\n const parentEntity = getParent(entity)(record)\n if (!parentEntity) return []\n const siblingEntities = getChildren(parentEntity, entity.nodeDefUuid)(record)\n return includeSelf ? siblingEntities : siblingEntities.filter((sibling) => !Nodes.areEqual(sibling, entity))\n }\n\nexport const getAttributeSiblings =\n (node: ArenaRecordNode, nodeDef: NodeDef<NodeDefType, NodeDefProps>) =>\n (record: ArenaRecord): ArenaRecordNode[] => {\n const parentEntity = getParent(node)(record)\n if (!parentEntity) return []\n const siblingParentEntities = getEntitySiblings(parentEntity)(record)\n return siblingParentEntities.reduce((siblingsAcc: ArenaRecordNode[], siblingEntity) => {\n siblingsAcc.push(...getChildren(siblingEntity, nodeDef.uuid)(record))\n return siblingsAcc\n }, [])\n }\n\nexport const getNodeIndex = (node: ArenaRecordNode) => (record: ArenaRecord) => {\n const parentEntity = getParent(node)(record)\n if (!parentEntity) return 0 // root entity\n const siblings = getChildren(parentEntity, node.nodeDefUuid)(record)\n // compared by uuid: the specified node can be a copy of the one in the record (e.g. an updated version of it)\n return siblings.findIndex((sibling) => sibling.uuid === node.uuid)\n}\n\nexport const findEntityByKeyValues =\n (\n survey: Survey,\n cycle: string,\n parentEntity: ArenaRecordNode,\n entityDefUuid: string,\n keyValuesByDefUuid: Dictionary<any>\n ) =>\n (record: ArenaRecord): ArenaRecordNode | undefined => {\n const entityDef = Surveys.getNodeDefByUuid({ survey, uuid: entityDefUuid })\n const siblingEntities = getChildren(parentEntity, entityDefUuid)(record)\n if (NodeDefs.isSingle(entityDef)) {\n return siblingEntities[0]\n }\n const keyDefs = Surveys.getNodeDefKeys({ survey, cycle, nodeDef: entityDef })\n\n return siblingEntities.find((siblingEntity) => {\n const siblingEntityKeyValuesByDefUuid = getEntityKeyValuesByDefUuid(\n survey,\n siblingEntity,\n undefined,\n keyDefs\n )(record)\n return keyDefs.every((keyDef) => {\n const keyValue = siblingEntityKeyValuesByDefUuid[keyDef.uuid]\n const keyValueSearch = keyValuesByDefUuid[keyDef.uuid]\n return NodeValues.isValueEqual({\n survey,\n nodeDef: keyDef,\n value: keyValue,\n valueSearch: keyValueSearch,\n })\n })\n })\n }\n\nexport const findEntityWithSameKeysInAnotherRecord =\n (survey: Survey, cycle: string, entityUuid: string, recordOther: ArenaRecord) =>\n (record: ArenaRecord): ArenaRecordNode | undefined => {\n const entity = getNodeByUuid(entityUuid)(record)\n if (!entity) return undefined\n\n let otherRecordCurrentParentEntity = getRoot(recordOther)\n if (!otherRecordCurrentParentEntity) return undefined\n\n const entityAncestorsAndSelf = getAncestorsAndSelf(entity)(record)\n const ancestorDefUuidsAndKeys = entityAncestorsAndSelf.map((ancestor) => ({\n entityDefUuid: ancestor.nodeDefUuid,\n keyValuesByDefUuid: getEntityKeyValuesByDefUuid(survey, ancestor)(record),\n }))\n\n const ancestorDefUuidsAndKeysToVisit = [...ancestorDefUuidsAndKeys].reverse()\n\n for (let index = 1; otherRecordCurrentParentEntity && index < ancestorDefUuidsAndKeysToVisit.length; index++) {\n const { entityDefUuid, keyValuesByDefUuid } = ancestorDefUuidsAndKeysToVisit[index]\n otherRecordCurrentParentEntity = findEntityByKeyValues(\n survey,\n cycle,\n otherRecordCurrentParentEntity,\n entityDefUuid,\n keyValuesByDefUuid\n )(recordOther)\n }\n return otherRecordCurrentParentEntity\n }\n\nexport const getDependentNodePointers =\n (\n survey: Survey,\n node: ArenaRecordNode,\n dependencyType: SurveyDependencyType,\n includeSelf = false,\n filterFn: ((nodePointer: NodePointer) => boolean) | null = null\n ) =>\n (record: ArenaRecord): NodePointer[] => {\n const nodeDefUuid = node.nodeDefUuid\n const nodeDef = Surveys.getNodeDefByUuid({ survey, uuid: nodeDefUuid })\n const dependentDefs = Surveys.getNodeDefDependents({ survey, nodeDefUuid, dependencyType })\n const nodePointers: Array<NodePointer> = []\n\n const addToNodePointers = (nodePointer: NodePointer): void => {\n if (filterFn === null || filterFn(nodePointer)) {\n nodePointers.push(nodePointer)\n }\n }\n\n for (const dependentDef of dependentDefs) {\n // 1 find common ancestor node\n const commonAncestorNode = getClosestAncestorNode(node, nodeDef, dependentDef, dependencyType)(record)\n if (!commonAncestorNode) continue\n\n const nodeDefDependentParent = Surveys.getNodeDefParent({ survey, nodeDef: dependentDef })\n if (!nodeDefDependentParent) throw new SystemError(SystemErrorKeys.record.dependencyOnRootFound)\n\n // 2 find descendant nodes of common parent node with nodeDefUuid = dependentDef uuid\n const dependentContextNodes = getDescendantsOrSelf(commonAncestorNode, nodeDefDependentParent)(record)\n\n for (const dependentContextNode of dependentContextNodes) {\n addToNodePointers({\n nodeCtx: dependentContextNode,\n nodeDef: dependentDef,\n })\n }\n }\n if (includeSelf) {\n const parentNode = getParent(node)(record)\n if (parentNode) {\n addToNodePointers({\n nodeCtx: parentNode,\n nodeDef,\n })\n }\n }\n\n return nodePointers\n }\n\n/**\n * Returns the code attributes the specified code attribute depends on, from the top level one to the parent one.\n */\nexport const getAncestorCodeAttributes =\n (survey: Survey, parentNode: ArenaRecordNode, nodeDef: NodeDefCode) =>\n (record: ArenaRecord): ArenaRecordNode[] => {\n const ancestorCodeAttributes = []\n let currentParentCodeAttribute = getParentCodeAttribute(parentNode, nodeDef)(record)\n while (currentParentCodeAttribute) {\n ancestorCodeAttributes.unshift(currentParentCodeAttribute)\n const ancestorCodeDef = Surveys.getNodeDefByUuid({\n survey,\n uuid: currentParentCodeAttribute.nodeDefUuid,\n }) as NodeDefCode\n currentParentCodeAttribute = getParentCodeAttribute(parentNode, ancestorCodeDef)(record)\n }\n return ancestorCodeAttributes\n }\n\nexport const getAncestorCodePath =\n (survey: Survey, parentNode: ArenaRecordNode, nodeDef: NodeDef<NodeDefType.code, NodeDefCodeProps>) =>\n (record: ArenaRecord): string[] =>\n getAncestorCodeAttributes(\n survey,\n parentNode,\n nodeDef\n )(record).map((codeAttribute) => {\n const codeItemUuid = NodeValues.getItemUuid(codeAttribute)\n if (!codeItemUuid) return ''\n // items of big categories are not in the survey ref data: they can be in the node ref data\n const item =\n codeAttribute.refData?.categoryItem ?? Surveys.getCategoryItemByUuid({ survey, itemUuid: codeItemUuid })\n return item?.props.code ?? ''\n })\n\nexport const getCategoryItemUuid =\n (survey: Survey, nodeDef: NodeDef<NodeDefType.code, NodeDefCodeProps>, parentNode: ArenaRecordNode, code: string) =>\n (record: ArenaRecord): string | undefined => {\n const categoryUuid = nodeDef.props.categoryUuid\n\n const codePaths = [...getAncestorCodePath(survey, parentNode, nodeDef)(record), code]\n\n const item = Surveys.getCategoryItemByCodePaths({ survey, categoryUuid, codePaths })\n\n return item?.uuid\n }\n\nexport const isNodeFilledByUser =\n (node: ArenaRecordNode) =>\n (record: ArenaRecord): boolean =>\n !!findDescendantOrSelf(node, (visitedNode) => Nodes.hasUserInputValue(visitedNode))(record)\n\nexport const isNodeEmpty =\n (node: ArenaRecordNode) =>\n (record: ArenaRecord): boolean =>\n !isNodeFilledByUser(node)(record)\n\nexport const isEmpty = (record: ArenaRecord): boolean => {\n const rootNode = getRoot(record)\n return rootNode ? isNodeEmpty(rootNode)(record) : true\n}\n\nexport const getStep = (record: ArenaRecord): string => record.step ?? RECORD_STEP_DEFAULT\n\nexport const isInAnalysisStep = (record: ArenaRecord): boolean => getStep(record) === RecordStepAnalysisCode\n"]}
1
+ {"version":3,"file":"recordGetters.js","sourceRoot":"","sources":["../../../../src/record/_records/recordGetters.ts"],"names":[],"mappings":"AAAA,OAAO,EAAc,cAAc,EAAE,MAAM,cAAc,CAAA;AACzD,OAAO,EAAE,WAAW,EAAE,eAAe,EAAE,MAAM,aAAa,CAAA;AAC1D,OAAO,EAAgC,KAAK,EAAY,MAAM,YAAY,CAAA;AAC1E,OAAO,EAAE,UAAU,EAAE,MAAM,uBAAuB,CAAA;AAClD,OAAO,EAAwD,QAAQ,EAAe,MAAM,eAAe,CAAA;AAC3G,OAAO,EAAE,YAAY,EAAE,OAAO,EAAE,MAAM,cAAc,CAAA;AAEpD,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,aAAa,CAAA;AAC3C,OAAO,EAAe,mBAAmB,EAAoB,MAAM,WAAW,CAAA;AAC9E,OAAO,EAAE,sBAAsB,EAAE,MAAM,eAAe,CAAA;AACtD,OAAO,EAAE,sBAAsB,EAAE,MAAM,0BAA0B,CAAA;AACjE,OAAO,EAAE,uBAAuB,EAAE,MAAM,2BAA2B,CAAA;AACnE,OAAO,EAAE,qBAAqB,EAAE,MAAM,yBAAyB,CAAA;AAE/D,MAAM,CAAC,MAAM,QAAQ,GAAG,CAAC,MAAmB,EAAU,EAAE,wBAAC,MAAM,CAA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,CAAC,IAAI,CAAA;AACxD,CAAC,CAAA;AAED,MAAM,CAAC,MAAM,OAAO,GAAG,CAAC,MAAmB,EAAU,EAAE,wBAAC,MAAM,CAAC,IAAI,mCAAI,mBAAmB,GAAA,CAAA;AAE1F,MAAM,CAAC,MAAM,gBAAgB,GAAG,CAAC,MAAmB,EAAW,EAAE,CAAC,OAAO,CAAC,MAAM,CAAC,KAAK,sBAAsB,CAAA","sourcesContent":["import { Dictionary, TraverseMethod } from '../../common'\nimport { SystemError, SystemErrorKeys } from '../../error'\nimport { ArenaRecordNode, NodePointer, Nodes, NodesMap } from '../../node'\nimport { NodeValues } from '../../node/nodeValues'\nimport { NodeDef, NodeDefCode, NodeDefCodeProps, NodeDefProps, NodeDefs, NodeDefType } from '../../nodeDef'\nimport { defaultCycle, Surveys } from '../../survey'\nimport { Survey, SurveyDependencyType } from '../../survey/survey'\nimport { Arrays, Queue } from '../../utils'\nimport { ArenaRecord, RECORD_STEP_DEFAULT, RecordNodesIndex } from '../record'\nimport { RecordStepAnalysisCode } from '../recordStep'\nimport { RecordNodesIndexReader } from './recordNodesIndexReader'\nimport { RecordNodesIndexUpdater } from './recordNodesIndexUpdater'\nimport { NodeDefSelfReferences } from './nodeDefSelfReferences'\n\nexport const getCycle = (record: ArenaRecord): string => record.cycle ?? defaultCycle\n\nexport const getNodes = (record: ArenaRecord): Dictionary<ArenaRecordNode> => record.nodes ?? {}\n\nexport const getNodesArray = (record: ArenaRecord): ArenaRecordNode[] => Object.values(getNodes(record))\n\n/**\n * Returns the nodes index of the record or, if missing, a new index built from all the record nodes (not stored in the record).\n * To be used before updating the index: a partial index would be trusted by the getters.\n */\nexport const getNodesIndexOrBuild = (record: ArenaRecord): RecordNodesIndex =>\n record._nodesIndex ?? RecordNodesIndexUpdater.initializeIndex(record)\n\n/**\n * Returns the node with the specified uuid, or undefined if not found.\n * Like the other node getters, it does not throw an error when the node is not found.\n */\nexport const getNodeByUuid =\n (uuid: string) =>\n (record: ArenaRecord): ArenaRecordNode | undefined =>\n record.nodes?.[uuid]\n\nexport const getNodesByUuids =\n (uuids: string[]) =>\n (record: ArenaRecord): ArenaRecordNode[] =>\n uuids.map((uuid: string) => record.nodes?.[uuid]) as ArenaRecordNode[]\n\n/**\n * Returns the root node, or undefined if the record has no nodes.\n */\nexport const getRoot = (record: ArenaRecord): ArenaRecordNode | undefined => {\n const rootUuid = record._nodesIndex ? RecordNodesIndexReader.getNodeRootUuid(record._nodesIndex) : null\n if (rootUuid) {\n return getNodeByUuid(rootUuid)(record)\n }\n return getNodesArray(record).find((node) => !node.parentUuid)\n}\n\nexport const getChildren =\n (parentNode: ArenaRecordNode, childDefUuid?: string) =>\n (record: ArenaRecord): ArenaRecordNode[] => {\n if (record._nodesIndex) {\n const childrenUuids = childDefUuid\n ? RecordNodesIndexReader.getNodeUuidsByParentAndChildDef({\n parentNodeUuid: parentNode.uuid,\n childDefUuid,\n })(record._nodesIndex)\n : RecordNodesIndexReader.getNodeUuidsByParent(parentNode.uuid)(record._nodesIndex)\n return getNodesByUuids(childrenUuids)(record)\n }\n return getNodesArray(record).filter(\n (node) => node.parentUuid === parentNode.uuid && (!childDefUuid || node.nodeDefUuid == childDefUuid)\n )\n }\n\n/**\n * Returns the only child of the parent node with the specified node def, or undefined if not found.\n * Throws an error if more than one child is found.\n */\nexport const getChild =\n (parentNode: ArenaRecordNode, childDefUuid: string) =>\n (record: ArenaRecord): ArenaRecordNode | undefined => {\n const children = getChildren(parentNode, childDefUuid)(record)\n if (children.length > 1) {\n const errorParams = { childDefUuid, parentNodeUuid: parentNode.uuid, recordUuid: record.uuid }\n throw new SystemError(SystemErrorKeys.record.multipleNodesFound, errorParams)\n }\n return children[0]\n }\n\n// called for every ancestor in the record update loops: keep it a plain lookup\nconst getParentNode = (record: ArenaRecord, node: ArenaRecordNode): ArenaRecordNode | undefined =>\n node.parentUuid ? record.nodes?.[node.parentUuid] : undefined\n\nexport const getParent =\n (node: ArenaRecordNode) =>\n (record: ArenaRecord): ArenaRecordNode | undefined =>\n getParentNode(record, node)\n\nexport const getNodesByDefUuid =\n (nodeDefUuid: string) =>\n (record: ArenaRecord): ArenaRecordNode[] => {\n if (record._nodesIndex) {\n const nodeUuids = RecordNodesIndexReader.getNodeUuidsByDef(nodeDefUuid)(record._nodesIndex)\n return getNodesByUuids(nodeUuids)(record)\n }\n return getNodesArray(record).filter((node) => node.nodeDefUuid === nodeDefUuid)\n }\n\nconst isNodeFlagTrue =\n (isChildFlagTrue: (parent: ArenaRecordNode, nodeDefUuid: string) => boolean) =>\n (node: ArenaRecordNode) =>\n (record: ArenaRecord): boolean => {\n let child = node\n let parent = getParentNode(record, child)\n while (parent) {\n if (!isChildFlagTrue(parent, child.nodeDefUuid)) return false\n child = parent\n parent = getParentNode(record, child)\n }\n return true\n }\n\nexport const isNodeApplicable = isNodeFlagTrue((parent, nodeDefUuid) => Nodes.isChildApplicable(parent, nodeDefUuid))\nexport const isNodeEditable = isNodeFlagTrue((parent, nodeDefUuid) => Nodes.isChildEditable(parent, nodeDefUuid))\nexport const isNodeVisible = isNodeFlagTrue((parent, nodeDefUuid) => Nodes.isChildVisible(parent, nodeDefUuid))\n\n/**\n * Whether a value is required for the node: key or always required attribute, or attribute with a \"required if\"\n * condition met in its parent entity (evaluated condition stored in the parent node meta).\n */\nexport const isNodeRequired =\n (nodeDef: NodeDef<NodeDefType>, node: ArenaRecordNode) =>\n (record: ArenaRecord): boolean => {\n if (NodeDefs.isKey(nodeDef) || NodeDefs.isRequired(nodeDef)) return true\n if (!NodeDefs.isRequiredIfDefined(nodeDef)) return false\n const parent = getParentNode(record, node)\n return !!parent && Nodes.isChildRequired(parent, nodeDef.uuid)\n }\n\nexport const getDependentCodeAttributes =\n (node: ArenaRecordNode) =>\n (record: ArenaRecord): ArenaRecordNode[] => {\n if (record._nodesIndex) {\n const nodeUuids = RecordNodesIndexReader.getNodeCodeDependentUuids(node.uuid)(record._nodesIndex)\n return getNodesByUuids(nodeUuids)(record)\n }\n throw new SystemError(SystemErrorKeys.record.nodesIndexNotInitialized)\n }\n\nexport const getParentCodeAttribute =\n (parentNode: ArenaRecordNode, nodeDef: NodeDefCode) =>\n (record: ArenaRecord): ArenaRecordNode | undefined => {\n const parentCodeDefUuid = NodeDefs.getParentCodeDefUuid(nodeDef)\n if (!parentCodeDefUuid) return undefined\n\n const ancestors = getAncestorsAndSelf(parentNode)(record)\n for (const ancestor of ancestors) {\n const children = getChildren(ancestor, parentCodeDefUuid)(record)\n if (children.length === 1) {\n return children[0]\n }\n }\n return undefined\n }\n\n// ancestors\n\n/**\n * Visits the specified node and its ancestors, from the node up to the root: the visit stops when the visitor returns true.\n */\nexport const visitAncestorsAndSelf =\n (node: ArenaRecordNode, visitor: (node: ArenaRecordNode) => boolean | void) =>\n (record: ArenaRecord): void => {\n let currentNode: ArenaRecordNode | undefined = node\n while (currentNode) {\n if (visitor(currentNode)) return\n currentNode = getParentNode(record, currentNode)\n }\n }\n\n/**\n * Returns the first node satisfying the predicate among the specified node and its ancestors (from the node up to the root).\n */\nexport const findAncestor =\n (node: ArenaRecordNode, predicate: (node: ArenaRecordNode) => boolean) =>\n (record: ArenaRecord): ArenaRecordNode | undefined => {\n let result: ArenaRecordNode | undefined = undefined\n visitAncestorsAndSelf(node, (visitedNode) => {\n if (predicate(visitedNode)) {\n result = visitedNode\n return true\n }\n return false\n })(record)\n return result\n }\n\n/**\n * Returns the specified node, if it has the specified node def, or its ancestor with that node def; undefined if not found.\n */\nexport const getAncestor =\n (node: ArenaRecordNode, ancestorDefUuid: string) =>\n (record: ArenaRecord): ArenaRecordNode | undefined => {\n let ancestor: ArenaRecordNode | undefined = node\n while (ancestor && ancestor.nodeDefUuid !== ancestorDefUuid) {\n ancestor = getParentNode(record, ancestor)\n }\n return ancestor\n }\n\n/**\n * Returns the list of ancestors from the given node to the root entity\n */\nexport const getAncestorsAndSelf =\n (node: ArenaRecordNode) =>\n (record: ArenaRecord): Array<ArenaRecordNode> => {\n const ancestors: Array<ArenaRecordNode> = []\n let currentNode: ArenaRecordNode | undefined = node\n while (currentNode) {\n ancestors.push(currentNode)\n currentNode = getParentNode(record, currentNode)\n }\n return ancestors\n }\n\n// descendants\n\nexport const getDescendantsOrSelf =\n (node: ArenaRecordNode, nodeDefDescendant: NodeDef<any>) =>\n (record: ArenaRecord): ArenaRecordNode[] => {\n if (nodeDefDescendant.uuid === node.nodeDefUuid) return [node]\n\n const nodeDefDescendantFullHierarchy = [...nodeDefDescendant.meta.h, nodeDefDescendant.uuid]\n\n // 1. get the descendant node defs uuids starting from node nodeDefUuid (not inclusive) down to the specified nodeDefDescendant uuid\n const descendantNodeDefUuids = nodeDefDescendantFullHierarchy.slice(\n nodeDefDescendantFullHierarchy.indexOf(node.nodeDefUuid) + 1\n )\n // 2. for every level in the hierarchy, find the children having the nodeDefUuid equal to the current one\n let currentAncestors = [node]\n let currentDescendants: ArenaRecordNode[] = []\n for (const currentDescendantDefUuid of descendantNodeDefUuids) {\n for (const currentAncestor of currentAncestors) {\n for (const child of getChildren(currentAncestor, currentDescendantDefUuid)(record)) {\n currentDescendants.push(child)\n }\n }\n currentAncestors = currentDescendants\n currentDescendants = []\n }\n return currentAncestors // currentAncestors is equal to the currentDescendants of the last level\n }\n\n/**\n * Returns the first descendant (or the node itself) with the specified node def, or undefined if not found.\n */\nexport const getDescendant =\n (node: ArenaRecordNode, nodeDefDescendant: NodeDef<any>) =>\n (record: ArenaRecord): ArenaRecordNode | undefined =>\n getDescendantsOrSelf(node, nodeDefDescendant)(record)[0]\n\nexport const isDescendantOf = (node: ArenaRecordNode, ancestor: ArenaRecordNode): boolean =>\n Nodes.getHierarchy(node).includes(ancestor.uuid)\n\nexport const visitDescendantsAndSelf =\n (\n node: ArenaRecordNode,\n visitor: (node: ArenaRecordNode) => boolean | void,\n traverseMethod: TraverseMethod = TraverseMethod.bfs\n ) =>\n (record: ArenaRecord): void => {\n if (traverseMethod === TraverseMethod.bfs) {\n const queue = new Queue<ArenaRecordNode>()\n\n queue.enqueue(node)\n\n while (!queue.isEmpty()) {\n const visitedNode = queue.dequeue()!\n\n if (visitor(visitedNode)) {\n // stop if visitor returns true\n return\n }\n\n const children = getChildren(visitedNode)(record)\n queue.enqueueItems(children)\n }\n } else {\n const stack = []\n\n stack.push(node)\n\n while (stack.length > 0) {\n const visitedNode = stack.pop() as ArenaRecordNode\n\n if (visitor(visitedNode)) {\n // stop if visitor returns true\n return\n }\n\n const children = getChildren(visitedNode)(record)\n\n // add children to stack in reverse order\n for (let index = children.length - 1; index >= 0; index--) {\n const child = children[index]\n stack.push(child)\n }\n }\n }\n }\n\nexport const findDescendantOrSelf =\n (node: ArenaRecordNode, predicate: (node: ArenaRecordNode) => boolean) =>\n (record: ArenaRecord): ArenaRecordNode | undefined => {\n let found = undefined\n\n visitDescendantsAndSelf(node, (currentNode) => {\n if (predicate(currentNode)) {\n found = currentNode\n return true\n }\n return false\n })(record)\n return found\n }\n\nconst getClosestAncestorNode =\n (\n node: ArenaRecordNode,\n nodeDef: NodeDef<NodeDefType, NodeDefProps>,\n dependentDef: NodeDef<NodeDefType, NodeDefProps>,\n dependencyType: SurveyDependencyType\n ) =>\n (record: ArenaRecord): ArenaRecordNode | undefined => {\n // 1a if dependent def is the same as node def, potentially all nodes with\n // nodeDefUuid === dependentDef.uuid in record could be dependent of nodeDef;\n // consider the root node as the closest ancestor node,\n // unless the node def references itself only among the children of its parent entity (e.g. validation \"dbh > 0\")\n if (nodeDef.uuid === dependentDef.uuid) {\n return NodeDefSelfReferences.isSelfReferenceLocal({ nodeDef, dependencyType })\n ? getParent(node)(record)\n : getRoot(record)\n }\n // 1 find common ancestor def\n const commonAncestorDefUuid = Arrays.last(Arrays.intersection(nodeDef.meta.h, dependentDef.meta.h))\n if (!commonAncestorDefUuid) return undefined\n\n // 2 get ancestor node with common parent def\n return getAncestor(node, commonAncestorDefUuid)(record)\n }\n\ntype KeyDefs = NodeDef<NodeDefType, NodeDefProps>[]\n\n/**\n * Returns the key nodes of the entity, indexed by key def uuid; keyDefs, when specified, are used instead of the\n * entity def keys in the cycle.\n */\nexport const getEntityKeyNodesByDefUuid =\n (survey: Survey, entity: ArenaRecordNode, cycle?: string, keyDefs?: KeyDefs) =>\n (record: ArenaRecord): NodesMap => {\n const nodeDef = Surveys.getNodeDefByUuid({ survey, uuid: entity.nodeDefUuid })\n const nodeDefKeys = keyDefs ?? Surveys.getNodeDefKeys({ survey, cycle, nodeDef })\n return nodeDefKeys.reduce((acc: NodesMap, nodeDefKey) => {\n const nodeKey = getDescendant(entity, nodeDefKey)(record)\n // missing key nodes are kept as undefined entries\n acc[nodeDefKey.uuid] = nodeKey as ArenaRecordNode\n return acc\n }, {})\n }\n\nexport const getEntityKeyNodes =\n (survey: Survey, entity: ArenaRecordNode, cycle?: string, keyDefs?: KeyDefs) =>\n (record: ArenaRecord): ArenaRecordNode[] =>\n Object.values(getEntityKeyNodesByDefUuid(survey, entity, cycle, keyDefs)(record))\n\nexport const getEntityKeyValuesByDefUuid =\n (survey: Survey, entity: ArenaRecordNode, cycle?: string, keyDefs?: KeyDefs) =>\n (record: ArenaRecord): Dictionary<any> => {\n const keyNodesByDefUuid = getEntityKeyNodesByDefUuid(survey, entity, cycle, keyDefs)(record)\n return Object.entries(keyNodesByDefUuid).reduce((acc: Dictionary<any>, [uuid, keyNode]) => {\n acc[uuid] = keyNode?.value\n return acc\n }, {})\n }\n\nexport const getEntityKeyValues =\n (survey: Survey, entity: ArenaRecordNode, cycle?: string, keyDefs?: KeyDefs) =>\n (record: ArenaRecord): any[] =>\n Object.values(getEntityKeyValuesByDefUuid(survey, entity, cycle, keyDefs)(record))\n\nexport const getEntitySiblings =\n (entity: ArenaRecordNode, includeSelf = false) =>\n (record: ArenaRecord): ArenaRecordNode[] => {\n const parentEntity = getParent(entity)(record)\n if (!parentEntity) return []\n const siblingEntities = getChildren(parentEntity, entity.nodeDefUuid)(record)\n return includeSelf ? siblingEntities : siblingEntities.filter((sibling) => !Nodes.areEqual(sibling, entity))\n }\n\nexport const getAttributeSiblings =\n (node: ArenaRecordNode, nodeDef: NodeDef<NodeDefType, NodeDefProps>) =>\n (record: ArenaRecord): ArenaRecordNode[] => {\n const parentEntity = getParent(node)(record)\n if (!parentEntity) return []\n const siblingParentEntities = getEntitySiblings(parentEntity)(record)\n return siblingParentEntities.reduce((siblingsAcc: ArenaRecordNode[], siblingEntity) => {\n for (const sibling of getChildren(siblingEntity, nodeDef.uuid)(record)) {\n siblingsAcc.push(sibling)\n }\n return siblingsAcc\n }, [])\n }\n\nexport const getNodeIndex = (node: ArenaRecordNode) => (record: ArenaRecord) => {\n const parentEntity = getParent(node)(record)\n if (!parentEntity) return 0 // root entity\n const siblings = getChildren(parentEntity, node.nodeDefUuid)(record)\n // compared by uuid: the specified node can be a copy of the one in the record (e.g. an updated version of it)\n return siblings.findIndex((sibling) => sibling.uuid === node.uuid)\n}\n\nexport const findEntityByKeyValues =\n (\n survey: Survey,\n cycle: string,\n parentEntity: ArenaRecordNode,\n entityDefUuid: string,\n keyValuesByDefUuid: Dictionary<any>\n ) =>\n (record: ArenaRecord): ArenaRecordNode | undefined => {\n const entityDef = Surveys.getNodeDefByUuid({ survey, uuid: entityDefUuid })\n const siblingEntities = getChildren(parentEntity, entityDefUuid)(record)\n if (NodeDefs.isSingle(entityDef)) {\n return siblingEntities[0]\n }\n const keyDefs = Surveys.getNodeDefKeys({ survey, cycle, nodeDef: entityDef })\n\n return siblingEntities.find((siblingEntity) => {\n const siblingEntityKeyValuesByDefUuid = getEntityKeyValuesByDefUuid(\n survey,\n siblingEntity,\n undefined,\n keyDefs\n )(record)\n return keyDefs.every((keyDef) => {\n const keyValue = siblingEntityKeyValuesByDefUuid[keyDef.uuid]\n const keyValueSearch = keyValuesByDefUuid[keyDef.uuid]\n return NodeValues.isValueEqual({\n survey,\n nodeDef: keyDef,\n value: keyValue,\n valueSearch: keyValueSearch,\n })\n })\n })\n }\n\nexport const findEntityWithSameKeysInAnotherRecord =\n (survey: Survey, cycle: string, entityUuid: string, recordOther: ArenaRecord) =>\n (record: ArenaRecord): ArenaRecordNode | undefined => {\n const entity = getNodeByUuid(entityUuid)(record)\n if (!entity) return undefined\n\n let otherRecordCurrentParentEntity = getRoot(recordOther)\n if (!otherRecordCurrentParentEntity) return undefined\n\n const entityAncestorsAndSelf = getAncestorsAndSelf(entity)(record)\n const ancestorDefUuidsAndKeys = entityAncestorsAndSelf.map((ancestor) => ({\n entityDefUuid: ancestor.nodeDefUuid,\n keyValuesByDefUuid: getEntityKeyValuesByDefUuid(survey, ancestor)(record),\n }))\n\n const ancestorDefUuidsAndKeysToVisit = [...ancestorDefUuidsAndKeys].reverse()\n\n for (let index = 1; otherRecordCurrentParentEntity && index < ancestorDefUuidsAndKeysToVisit.length; index++) {\n const { entityDefUuid, keyValuesByDefUuid } = ancestorDefUuidsAndKeysToVisit[index]\n otherRecordCurrentParentEntity = findEntityByKeyValues(\n survey,\n cycle,\n otherRecordCurrentParentEntity,\n entityDefUuid,\n keyValuesByDefUuid\n )(recordOther)\n }\n return otherRecordCurrentParentEntity\n }\n\nexport const getDependentNodePointers =\n (\n survey: Survey,\n node: ArenaRecordNode,\n dependencyType: SurveyDependencyType,\n includeSelf = false,\n filterFn: ((nodePointer: NodePointer) => boolean) | null = null\n ) =>\n (record: ArenaRecord): NodePointer[] => {\n const nodeDefUuid = node.nodeDefUuid\n const nodeDef = Surveys.getNodeDefByUuid({ survey, uuid: nodeDefUuid })\n const dependentDefs = Surveys.getNodeDefDependents({ survey, nodeDefUuid, dependencyType })\n const nodePointers: Array<NodePointer> = []\n\n const addToNodePointers = (nodePointer: NodePointer): void => {\n if (filterFn === null || filterFn(nodePointer)) {\n nodePointers.push(nodePointer)\n }\n }\n\n for (const dependentDef of dependentDefs) {\n // 1 find common ancestor node\n const commonAncestorNode = getClosestAncestorNode(node, nodeDef, dependentDef, dependencyType)(record)\n if (!commonAncestorNode) continue\n\n const nodeDefDependentParent = Surveys.getNodeDefParent({ survey, nodeDef: dependentDef })\n if (!nodeDefDependentParent) throw new SystemError(SystemErrorKeys.record.dependencyOnRootFound)\n\n // 2 find descendant nodes of common parent node with nodeDefUuid = dependentDef uuid\n const dependentContextNodes = getDescendantsOrSelf(commonAncestorNode, nodeDefDependentParent)(record)\n\n for (const dependentContextNode of dependentContextNodes) {\n addToNodePointers({\n nodeCtx: dependentContextNode,\n nodeDef: dependentDef,\n })\n }\n }\n if (includeSelf) {\n const parentNode = getParent(node)(record)\n if (parentNode) {\n addToNodePointers({\n nodeCtx: parentNode,\n nodeDef,\n })\n }\n }\n\n return nodePointers\n }\n\n/**\n * Returns the code attributes the specified code attribute depends on, from the top level one to the parent one.\n */\nexport const getAncestorCodeAttributes =\n (survey: Survey, parentNode: ArenaRecordNode, nodeDef: NodeDefCode) =>\n (record: ArenaRecord): ArenaRecordNode[] => {\n const ancestorCodeAttributes = []\n let currentParentCodeAttribute = getParentCodeAttribute(parentNode, nodeDef)(record)\n while (currentParentCodeAttribute) {\n ancestorCodeAttributes.unshift(currentParentCodeAttribute)\n const ancestorCodeDef = Surveys.getNodeDefByUuid({\n survey,\n uuid: currentParentCodeAttribute.nodeDefUuid,\n }) as NodeDefCode\n currentParentCodeAttribute = getParentCodeAttribute(parentNode, ancestorCodeDef)(record)\n }\n return ancestorCodeAttributes\n }\n\nexport const getAncestorCodePath =\n (survey: Survey, parentNode: ArenaRecordNode, nodeDef: NodeDef<NodeDefType.code, NodeDefCodeProps>) =>\n (record: ArenaRecord): string[] =>\n getAncestorCodeAttributes(\n survey,\n parentNode,\n nodeDef\n )(record).map((codeAttribute) => {\n const codeItemUuid = NodeValues.getItemUuid(codeAttribute)\n if (!codeItemUuid) return ''\n // items of big categories are not in the survey ref data: they can be in the node ref data\n const item =\n codeAttribute.refData?.categoryItem ?? Surveys.getCategoryItemByUuid({ survey, itemUuid: codeItemUuid })\n return item?.props.code ?? ''\n })\n\nexport const getCategoryItemUuid =\n (survey: Survey, nodeDef: NodeDef<NodeDefType.code, NodeDefCodeProps>, parentNode: ArenaRecordNode, code: string) =>\n (record: ArenaRecord): string | undefined => {\n const categoryUuid = nodeDef.props.categoryUuid\n\n const codePaths = [...getAncestorCodePath(survey, parentNode, nodeDef)(record), code]\n\n const item = Surveys.getCategoryItemByCodePaths({ survey, categoryUuid, codePaths })\n\n return item?.uuid\n }\n\nexport const isNodeFilledByUser =\n (node: ArenaRecordNode) =>\n (record: ArenaRecord): boolean =>\n !!findDescendantOrSelf(node, (visitedNode) => Nodes.hasUserInputValue(visitedNode))(record)\n\nexport const isNodeEmpty =\n (node: ArenaRecordNode) =>\n (record: ArenaRecord): boolean =>\n !isNodeFilledByUser(node)(record)\n\nexport const isEmpty = (record: ArenaRecord): boolean => {\n const rootNode = getRoot(record)\n return rootNode ? isNodeEmpty(rootNode)(record) : true\n}\n\nexport const getStep = (record: ArenaRecord): string => record.step ?? RECORD_STEP_DEFAULT\n\nexport const isInAnalysisStep = (record: ArenaRecord): boolean => getStep(record) === RecordStepAnalysisCode\n"]}
@@ -188,7 +188,9 @@ const findSortedNodesToValidate = (params) => {
188
188
  const nodeParent = Records.getParent(node)(record);
189
189
  result.push(...NodePointers.getNodesFromNodePointers({ record, nodePointers: nodePointersAttributeAndDependents }), ...findSiblingKeyNodesToValidate(Object.assign(Object.assign({}, params), { nodeDef, nodeParent, attribute: node, siblingKeyNodesCache })));
190
190
  if ((_a = NodeDefs.getValidations(nodeDef)) === null || _a === void 0 ? void 0 : _a.unique) {
191
- result.push(...Records.getAttributeSiblings(node, nodeDef)(record));
191
+ for (const sibling of Records.getAttributeSiblings(node, nodeDef)(record)) {
192
+ result.push(sibling);
193
+ }
192
194
  }
193
195
  }
194
196
  return result;
@@ -1 +1 @@
1
- {"version":3,"file":"attributeValidator.js","sourceRoot":"","sources":["../../../../src/record/recordValidator/attributeValidator.ts"],"names":[],"mappings":";;;;;;;;;AAGA,OAAO,EAAmB,QAAQ,EAAE,KAAK,EAAE,UAAU,EAAE,MAAM,YAAY,CAAA;AACzE,OAAO,EAA4C,QAAQ,EAAe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,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,IAAI,EAAE,oBAAoB,IAAG,CAC5G,CAAA;QAED,IAAI,MAAA,QAAQ,CAAC,cAAc,CAAC,OAAO,CAAC,0CAAE,MAAM,EAAE,CAAC;YAC7C,MAAM,CAAC,IAAI,CAAC,GAAG,OAAO,CAAC,oBAAoB,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC,MAAM,CAAC,CAAC,CAAA;QACrE,CAAC;IACH,CAAC;IAED,OAAO,MAAM,CAAA;AACf,CAAC,CAAA;AAED,MAAM,wCAAwC,GAAG,CAC/C,MAAuC,EACZ,EAAE;IAC7B,MAAM,eAAe,GAAsB,yBAAyB,CAAC,MAAM,CAAC,CAAA;IAC5E,MAAM,qBAAqB,GAAqB,EAAE,CAAA;IAClD,6EAA6E;IAC7E,MAAM,eAAe,GAAG,qBAAqB,EAAE,CAAA;IAE/C,KAAK,MAAM,cAAc,IAAI,eAAe,EAAE,CAAC;QAC7C,MAAM,QAAQ,GAAG,cAAc,CAAC,IAAI,CAAA;QACpC,iEAAiE;QACjE,IAAI,CAAC,cAAc,CAAC,OAAO,IAAI,CAAC,qBAAqB,CAAC,QAAQ,CAAC,EAAE,CAAC;YAChE,qEAAqE;YACrE,MAAM,wBAAwB,mCAAQ,MAAM,KAAE,SAAS,EAAE,cAAc,EAAE,eAAe,GAAE,CAAA;YAC1F,qBAAqB,CAAC,QAAQ,CAAC,GAAG,MAAM,iBAAiB,CAAC,wBAAwB,CAAC,CAAA,CAAC,UAAU;QAChG,CAAC;IACH,CAAC;IACD,OAAO,qBAAqB,CAAA;AAC9B,CAAC,CAAA,CAAA;AAED,MAAM,CAAC,MAAM,kBAAkB,GAAG;IAChC,wCAAwC;CACzC,CAAA","sourcesContent":["import { User } from '../../auth'\nimport { Dictionary } from '../../common'\nimport { Labels } from '../../language'\nimport { ArenaRecordNode, NodeKeys, Nodes, NodeValues } from '../../node'\nimport { NodeDef, NodeDefExpression, NodeDefProps, NodeDefs, NodeDefType } from '../../nodeDef'\nimport { AreaOfInterestProvider } from '../../nodeDefExpressionEvaluator/areaOfInterestProvider'\nimport { CategoryItemProvider } from '../../nodeDefExpressionEvaluator/categoryItemProvider'\nimport { TaxonProvider } from '../../nodeDefExpressionEvaluator/taxonProvider'\nimport { Survey, Surveys } from '../../survey'\nimport { SurveyDependencyType } from '../../survey/survey'\nimport { Objects } from '../../utils'\nimport {\n ValidationFactory,\n ValidationResult,\n ValidationResultFactory,\n ValidationSeverity,\n Validator,\n} from '../../validation'\nimport { ValidationFields } from '../../validation/validation'\nimport { NodePointers } from '../nodePointers'\nimport { ArenaRecord } from '../record'\nimport { RecordExpressionEvaluator } from '../recordExpressionEvaluator'\nimport { evaluateRequiredIf } from '../recordNodesUpdater/recordNodeDependentsRequiredUpdater'\nimport { Records } from '../records'\nimport { RecordValidations } from '../recordValidations'\nimport { AttributeKeyValidator, createEntityKeysCache, EntityKeysCache } from './attributeKeyValidator'\nimport { AttributeTypeValidator } from './attributeTypeValidator'\nimport { AttributeUniqueValidator } from './attributeUniqueValidator'\n\nconst expressionEvaluator = new RecordExpressionEvaluator()\n\nexport interface RecordValidatorParams {\n user: User\n survey: Survey\n categoryItemProvider?: CategoryItemProvider\n taxonProvider?: TaxonProvider\n areaOfInterestProvider?: AreaOfInterestProvider\n record: ArenaRecord\n}\n\nexport interface AttributeValidatorParams extends RecordValidatorParams {\n attribute: ArenaRecordNode\n}\n\nexport interface AttributesValidatorParams extends RecordValidatorParams {\n nodes: Dictionary<ArenaRecordNode>\n}\n\nexport interface SortedAttributesValidatorParams extends RecordValidatorParams {\n nodesArray: ArenaRecordNode[]\n}\n\ntype SiblingKeyNodeItem = { entityUuid: string; keyNode: ArenaRecordNode; hasErrors: boolean }\n\n// sibling key nodes are cached by ancestor multiple entity parent and def uuid during the same validation call:\n// when many entities are added to the same parent entity (e.g. data import), computing them for every updated\n// key attribute would take a time that grows quadratically with the number of entities\ntype SiblingKeyNodesCache = Map<string, SiblingKeyNodeItem[]>\n\nconst _getSiblingNodeKeys = (\n params: AttributeValidatorParams & { siblingKeyNodesCache?: SiblingKeyNodesCache }\n): SiblingKeyNodeItem[] => {\n const { survey, record, attribute, siblingKeyNodesCache } = params\n\n const attributeDef = Surveys.getNodeDefByUuid({ survey, uuid: attribute.nodeDefUuid })\n const ancestorMultipleEntityDef = Surveys.getNodeDefAncestorMultipleEntity({ survey, nodeDef: attributeDef })\n if (!ancestorMultipleEntityDef) {\n return []\n }\n const ancestorMultipleEntity = Records.getAncestor(attribute, ancestorMultipleEntityDef.uuid)(record)\n if (!ancestorMultipleEntity) return []\n\n const ancestorMultipleEntityParent = Records.getParent(ancestorMultipleEntity)(record)\n if (!ancestorMultipleEntityParent) return []\n\n const cacheKey = `${ancestorMultipleEntityParent.uuid}_${ancestorMultipleEntityDef.uuid}`\n let items = siblingKeyNodesCache?.get(cacheKey)\n if (!items) {\n const keyDefs = Surveys.getNodeDefKeys({ survey, nodeDef: ancestorMultipleEntityDef })\n const entities = Records.getEntitySiblings(ancestorMultipleEntity, true)(record)\n items = []\n for (const entity of entities) {\n const keyNodes = Records.getEntityKeyNodes(survey, entity, undefined, keyDefs)(record)\n for (const keyNode of keyNodes) {\n if (!keyNode) continue\n const nodeValidation =\n record.validation && RecordValidations.getValidationNode({ nodeUuid: keyNode.uuid })(record.validation)\n items.push({ entityUuid: entity.uuid, keyNode, hasErrors: !!nodeValidation && !nodeValidation.valid })\n }\n }\n siblingKeyNodesCache?.set(cacheKey, items)\n }\n return items.filter((item) => item.entityUuid !== ancestorMultipleEntity.uuid)\n}\n\nconst _getValidationMessagesWithDefault = (params: {\n survey: Survey\n expression: NodeDefExpression\n defaultMessage?: string\n}): Labels => {\n const { survey, expression, defaultMessage } = params\n const messages: Labels = { ...expression.messages }\n\n const languages = Surveys.getLanguages(survey)\n const defaultMessageDefined = Objects.isNotEmpty(defaultMessage)\n\n for (const lang of languages) {\n const customMessage = messages[lang]\n if (Objects.isEmpty(customMessage) && defaultMessageDefined) {\n messages[lang] = defaultMessage\n }\n }\n\n return messages\n}\n\nconst _isValueRequired = async (\n params: AttributeValidatorParams & { nodeDef: NodeDef<NodeDefType, NodeDefProps> }\n): Promise<boolean> => {\n const { record, attribute, nodeDef } = params\n if (NodeDefs.isKey(nodeDef) || NodeDefs.isRequired(nodeDef)) return true\n if (!NodeDefs.isRequiredIfDefined(nodeDef)) return false\n const parentNode = Records.getParent(attribute)(record)\n if (!parentNode) return false\n // evaluated here (not read from the parent node meta flag) so validation doesn't depend on up to date node meta\n // (e.g. records created before the \"required if\" condition was defined)\n return evaluateRequiredIf({ ...params, nodeCtx: parentNode, nodeDef })\n}\n\nconst _validateRequired =\n (params: AttributeValidatorParams & { nodeDef: NodeDef<NodeDefType, NodeDefProps> }) =>\n async (_field: string, node: any): Promise<ValidationResult> => {\n const valid = !Nodes.isValueBlank(node) || !(await _isValueRequired(params))\n return valid\n ? ValidationResultFactory.createInstance()\n : ValidationResultFactory.createInstance({\n key: 'record.attribute.valueRequired',\n severity: ValidationSeverity.error,\n valid,\n })\n }\n\n/**\n * Evaluates the validation expressions.\n */\nconst _validateNodeValidations =\n (params: {\n user: User\n survey: Survey\n record: ArenaRecord\n nodeDef: NodeDef<NodeDefType, NodeDefProps>\n areaOfInterestProvider?: AreaOfInterestProvider\n }) =>\n async (_propName: string, node: ArenaRecordNode): Promise<ValidationResult> => {\n const { user, survey, record, nodeDef, areaOfInterestProvider } = params\n if (Nodes.isValueBlank(node)) return ValidationResultFactory.createInstance()\n\n const validations = NodeDefs.getValidations(nodeDef)\n if (!validations?.expressions?.length) return ValidationResultFactory.createInstance()\n\n const applicableExpressionsEval = await expressionEvaluator.evalApplicableExpressions({\n user,\n survey,\n record,\n areaOfInterestProvider,\n nodeCtx: node,\n expressions: validations.expressions,\n stopAtFirstFound: false,\n })\n\n let validationResult = ValidationResultFactory.createInstance()\n\n for (const { expression, value: valid } of applicableExpressionsEval) {\n if (!valid) {\n const messages = _getValidationMessagesWithDefault({\n survey,\n expression,\n defaultMessage: expression.expression,\n })\n\n validationResult = ValidationResultFactory.createInstance({\n valid: false,\n key: 'record.attribute.customValidation',\n severity: expression.severity,\n messages,\n })\n break\n }\n }\n\n return validationResult\n }\n\nconst validateAttribute = async (params: AttributeValidatorParams & { entityKeysCache?: EntityKeysCache }) => {\n const { survey, record, attribute } = params\n if (Records.isNodeApplicable(attribute)(record)) {\n const nodeDef = Surveys.getNodeDefByUuid({ survey, uuid: attribute.nodeDefUuid })\n const validatorParams = { ...params, nodeDef }\n return new Validator().validate(attribute, {\n [NodeKeys.value]: [\n _validateRequired(validatorParams),\n AttributeTypeValidator.validateValueType(validatorParams),\n _validateNodeValidations(validatorParams),\n AttributeKeyValidator.validateAttributeKey(validatorParams),\n AttributeUniqueValidator.validateAttributeUnique(validatorParams),\n ],\n })\n }\n return ValidationFactory.createInstance()\n}\n\nconst findSiblingKeyNodesToValidate = (\n params: AttributeValidatorParams & {\n nodeDef: NodeDef<NodeDefType, NodeDefProps>\n nodeParent?: ArenaRecordNode\n siblingKeyNodesCache?: SiblingKeyNodesCache\n }\n) => {\n const { survey, nodeDef, nodeParent: parentNode, attribute } = params\n if (\n !NodeDefs.isKey(nodeDef) ||\n !parentNode ||\n (NodeDefs.isAutoIncrementalKey(nodeDef) && attribute.created && Nodes.isDefaultValueApplied(attribute))\n ) {\n // when a new node is created and the key is autoincremental, its value will be unique\n // and the validation of sibling key attributes is not necessary\n return []\n }\n // when a key attribute is updated, a sibling key attribute with the same value\n // or a sibling attribute with a validation error (duplicate key) should be re-validated\n const siblingNodeKeys = _getSiblingNodeKeys(params)\n const siblingNodeKeysWithSameValue: ArenaRecordNode[] = []\n const siblingNodeKeysWithErrors: ArenaRecordNode[] = []\n siblingNodeKeys.forEach(({ keyNode, hasErrors }) => {\n if (NodeValues.isValueEqual({ survey, nodeDef, parentNode, value: keyNode.value, valueSearch: attribute.value })) {\n siblingNodeKeysWithSameValue.push(keyNode)\n }\n if (hasErrors) {\n siblingNodeKeysWithErrors.push(keyNode)\n }\n })\n return [...siblingNodeKeysWithSameValue, ...siblingNodeKeysWithErrors]\n}\n\nconst findSortedNodesToValidate = (params: SortedAttributesValidatorParams): ArenaRecordNode[] => {\n const { survey, record, nodesArray } = params\n\n const result = []\n const siblingKeyNodesCache: SiblingKeyNodesCache = new Map()\n for (const node of nodesArray) {\n const nodeDef = Surveys.getNodeDefByUuid({ survey, uuid: node.nodeDefUuid })\n if (!NodeDefs.isAttribute(nodeDef)) {\n continue\n }\n // Get dependents and attribute itself\n const nodePointersAttributeAndDependents = [\n ...Records.getDependentNodePointers(survey, node, SurveyDependencyType.validations, true)(record),\n ...Records.getDependentNodePointers(survey, node, SurveyDependencyType.required)(record),\n ]\n\n const nodeParent = Records.getParent(node)(record)\n\n result.push(\n ...NodePointers.getNodesFromNodePointers({ record, nodePointers: nodePointersAttributeAndDependents }),\n ...findSiblingKeyNodesToValidate({ ...params, nodeDef, nodeParent, attribute: node, siblingKeyNodesCache })\n )\n\n if (NodeDefs.getValidations(nodeDef)?.unique) {\n result.push(...Records.getAttributeSiblings(node, nodeDef)(record))\n }\n }\n\n return result\n}\n\nconst validateSelfAndDependentSortedAttributes = async (\n params: SortedAttributesValidatorParams\n): Promise<ValidationFields> => {\n const nodesToValidate: ArenaRecordNode[] = findSortedNodesToValidate(params)\n const validationsByNodeUuid: ValidationFields = {}\n // the record doesn't change during the validation: entity keys can be cached\n const entityKeysCache = createEntityKeysCache()\n\n for (const nodeToValidate of nodesToValidate) {\n const nodeUuid = nodeToValidate.uuid\n // Validate only attributes not deleted and not validated already\n if (!nodeToValidate.deleted && !validationsByNodeUuid[nodeUuid]) {\n // sequential: avoid concurrent item/taxon lookups on large node sets\n const attributeValidatorParams = { ...params, attribute: nodeToValidate, entityKeysCache }\n validationsByNodeUuid[nodeUuid] = await validateAttribute(attributeValidatorParams) // NOSONAR\n }\n }\n return validationsByNodeUuid\n}\n\nexport const AttributeValidator = {\n validateSelfAndDependentSortedAttributes,\n}\n"]}
1
+ {"version":3,"file":"attributeValidator.js","sourceRoot":"","sources":["../../../../src/record/recordValidator/attributeValidator.ts"],"names":[],"mappings":";;;;;;;;;AAGA,OAAO,EAAmB,QAAQ,EAAE,KAAK,EAAE,UAAU,EAAE,MAAM,YAAY,CAAA;AACzE,OAAO,EAA4C,QAAQ,EAAe,MAAM,eAAe,CAAA;AAI/F,OAAO,EAAU,OAAO,EAAE,MAAM,cAAc,CAAA;AAC9C,OAAO,EAAE,oBAAoB,EAAE,MAAM,qBAAqB,CAAA;AAC1D,OAAO,EAAE,OAAO,EAAE,MAAM,aAAa,CAAA;AACrC,OAAO,EACL,iBAAiB,EAEjB,uBAAuB,EACvB,kBAAkB,EAClB,SAAS,GACV,MAAM,kBAAkB,CAAA;AAEzB,OAAO,EAAE,YAAY,EAAE,MAAM,iBAAiB,CAAA;AAE9C,OAAO,EAAE,yBAAyB,EAAE,MAAM,8BAA8B,CAAA;AACxE,OAAO,EAAE,kBAAkB,EAAE,MAAM,2DAA2D,CAAA;AAC9F,OAAO,EAAE,OAAO,EAAE,MAAM,YAAY,CAAA;AACpC,OAAO,EAAE,iBAAiB,EAAE,MAAM,sBAAsB,CAAA;AACxD,OAAO,EAAE,qBAAqB,EAAE,qBAAqB,EAAmB,MAAM,yBAAyB,CAAA;AACvG,OAAO,EAAE,sBAAsB,EAAE,MAAM,0BAA0B,CAAA;AACjE,OAAO,EAAE,wBAAwB,EAAE,MAAM,4BAA4B,CAAA;AAErE,MAAM,mBAAmB,GAAG,IAAI,yBAAyB,EAAE,CAAA;AA8B3D,MAAM,mBAAmB,GAAG,CAC1B,MAAkF,EAC5D,EAAE;IACxB,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,SAAS,EAAE,oBAAoB,EAAE,GAAG,MAAM,CAAA;IAElE,MAAM,YAAY,GAAG,OAAO,CAAC,gBAAgB,CAAC,EAAE,MAAM,EAAE,IAAI,EAAE,SAAS,CAAC,WAAW,EAAE,CAAC,CAAA;IACtF,MAAM,yBAAyB,GA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qB,CAAA;AAC9B,CAAC,CAAA,CAAA;AAED,MAAM,CAAC,MAAM,kBAAkB,GAAG;IAChC,wCAAwC;CACzC,CAAA","sourcesContent":["import { User } from '../../auth'\nimport { Dictionary } from '../../common'\nimport { Labels } from '../../language'\nimport { ArenaRecordNode, NodeKeys, Nodes, NodeValues } from '../../node'\nimport { NodeDef, NodeDefExpression, NodeDefProps, NodeDefs, NodeDefType } from '../../nodeDef'\nimport { AreaOfInterestProvider } from '../../nodeDefExpressionEvaluator/areaOfInterestProvider'\nimport { CategoryItemProvider } from '../../nodeDefExpressionEvaluator/categoryItemProvider'\nimport { TaxonProvider } from '../../nodeDefExpressionEvaluator/taxonProvider'\nimport { Survey, Surveys } from '../../survey'\nimport { SurveyDependencyType } from '../../survey/survey'\nimport { Objects } from '../../utils'\nimport {\n ValidationFactory,\n ValidationResult,\n ValidationResultFactory,\n ValidationSeverity,\n Validator,\n} from '../../validation'\nimport { ValidationFields } from '../../validation/validation'\nimport { NodePointers } from '../nodePointers'\nimport { ArenaRecord } from '../record'\nimport { RecordExpressionEvaluator } from '../recordExpressionEvaluator'\nimport { evaluateRequiredIf } from '../recordNodesUpdater/recordNodeDependentsRequiredUpdater'\nimport { Records } from '../records'\nimport { RecordValidations } from '../recordValidations'\nimport { AttributeKeyValidator, createEntityKeysCache, EntityKeysCache } from './attributeKeyValidator'\nimport { AttributeTypeValidator } from './attributeTypeValidator'\nimport { AttributeUniqueValidator } from './attributeUniqueValidator'\n\nconst expressionEvaluator = new RecordExpressionEvaluator()\n\nexport interface RecordValidatorParams {\n user: User\n survey: Survey\n categoryItemProvider?: CategoryItemProvider\n taxonProvider?: TaxonProvider\n areaOfInterestProvider?: AreaOfInterestProvider\n record: ArenaRecord\n}\n\nexport interface AttributeValidatorParams extends RecordValidatorParams {\n attribute: ArenaRecordNode\n}\n\nexport interface AttributesValidatorParams extends RecordValidatorParams {\n nodes: Dictionary<ArenaRecordNode>\n}\n\nexport interface SortedAttributesValidatorParams extends RecordValidatorParams {\n nodesArray: ArenaRecordNode[]\n}\n\ntype SiblingKeyNodeItem = { entityUuid: string; keyNode: ArenaRecordNode; hasErrors: boolean }\n\n// sibling key nodes are cached by ancestor multiple entity parent and def uuid during the same validation call:\n// when many entities are added to the same parent entity (e.g. data import), computing them for every updated\n// key attribute would take a time that grows quadratically with the number of entities\ntype SiblingKeyNodesCache = Map<string, SiblingKeyNodeItem[]>\n\nconst _getSiblingNodeKeys = (\n params: AttributeValidatorParams & { siblingKeyNodesCache?: SiblingKeyNodesCache }\n): SiblingKeyNodeItem[] => {\n const { survey, record, attribute, siblingKeyNodesCache } = params\n\n const attributeDef = Surveys.getNodeDefByUuid({ survey, uuid: attribute.nodeDefUuid })\n const ancestorMultipleEntityDef = Surveys.getNodeDefAncestorMultipleEntity({ survey, nodeDef: attributeDef })\n if (!ancestorMultipleEntityDef) {\n return []\n }\n const ancestorMultipleEntity = Records.getAncestor(attribute, ancestorMultipleEntityDef.uuid)(record)\n if (!ancestorMultipleEntity) return []\n\n const ancestorMultipleEntityParent = Records.getParent(ancestorMultipleEntity)(record)\n if (!ancestorMultipleEntityParent) return []\n\n const cacheKey = `${ancestorMultipleEntityParent.uuid}_${ancestorMultipleEntityDef.uuid}`\n let items = siblingKeyNodesCache?.get(cacheKey)\n if (!items) {\n const keyDefs = Surveys.getNodeDefKeys({ survey, nodeDef: ancestorMultipleEntityDef })\n const entities = Records.getEntitySiblings(ancestorMultipleEntity, true)(record)\n items = []\n for (const entity of entities) {\n const keyNodes = Records.getEntityKeyNodes(survey, entity, undefined, keyDefs)(record)\n for (const keyNode of keyNodes) {\n if (!keyNode) continue\n const nodeValidation =\n record.validation && RecordValidations.getValidationNode({ nodeUuid: keyNode.uuid })(record.validation)\n items.push({ entityUuid: entity.uuid, keyNode, hasErrors: !!nodeValidation && !nodeValidation.valid })\n }\n }\n siblingKeyNodesCache?.set(cacheKey, items)\n }\n return items.filter((item) => item.entityUuid !== ancestorMultipleEntity.uuid)\n}\n\nconst _getValidationMessagesWithDefault = (params: {\n survey: Survey\n expression: NodeDefExpression\n defaultMessage?: string\n}): Labels => {\n const { survey, expression, defaultMessage } = params\n const messages: Labels = { ...expression.messages }\n\n const languages = Surveys.getLanguages(survey)\n const defaultMessageDefined = Objects.isNotEmpty(defaultMessage)\n\n for (const lang of languages) {\n const customMessage = messages[lang]\n if (Objects.isEmpty(customMessage) && defaultMessageDefined) {\n messages[lang] = defaultMessage\n }\n }\n\n return messages\n}\n\nconst _isValueRequired = async (\n params: AttributeValidatorParams & { nodeDef: NodeDef<NodeDefType, NodeDefProps> }\n): Promise<boolean> => {\n const { record, attribute, nodeDef } = params\n if (NodeDefs.isKey(nodeDef) || NodeDefs.isRequired(nodeDef)) return true\n if (!NodeDefs.isRequiredIfDefined(nodeDef)) return false\n const parentNode = Records.getParent(attribute)(record)\n if (!parentNode) return false\n // evaluated here (not read from the parent node meta flag) so validation doesn't depend on up to date node meta\n // (e.g. records created before the \"required if\" condition was defined)\n return evaluateRequiredIf({ ...params, nodeCtx: parentNode, nodeDef })\n}\n\nconst _validateRequired =\n (params: AttributeValidatorParams & { nodeDef: NodeDef<NodeDefType, NodeDefProps> }) =>\n async (_field: string, node: any): Promise<ValidationResult> => {\n const valid = !Nodes.isValueBlank(node) || !(await _isValueRequired(params))\n return valid\n ? ValidationResultFactory.createInstance()\n : ValidationResultFactory.createInstance({\n key: 'record.attribute.valueRequired',\n severity: ValidationSeverity.error,\n valid,\n })\n }\n\n/**\n * Evaluates the validation expressions.\n */\nconst _validateNodeValidations =\n (params: {\n user: User\n survey: Survey\n record: ArenaRecord\n nodeDef: NodeDef<NodeDefType, NodeDefProps>\n areaOfInterestProvider?: AreaOfInterestProvider\n }) =>\n async (_propName: string, node: ArenaRecordNode): Promise<ValidationResult> => {\n const { user, survey, record, nodeDef, areaOfInterestProvider } = params\n if (Nodes.isValueBlank(node)) return ValidationResultFactory.createInstance()\n\n const validations = NodeDefs.getValidations(nodeDef)\n if (!validations?.expressions?.length) return ValidationResultFactory.createInstance()\n\n const applicableExpressionsEval = await expressionEvaluator.evalApplicableExpressions({\n user,\n survey,\n record,\n areaOfInterestProvider,\n nodeCtx: node,\n expressions: validations.expressions,\n stopAtFirstFound: false,\n })\n\n let validationResult = ValidationResultFactory.createInstance()\n\n for (const { expression, value: valid } of applicableExpressionsEval) {\n if (!valid) {\n const messages = _getValidationMessagesWithDefault({\n survey,\n expression,\n defaultMessage: expression.expression,\n })\n\n validationResult = ValidationResultFactory.createInstance({\n valid: false,\n key: 'record.attribute.customValidation',\n severity: expression.severity,\n messages,\n })\n break\n }\n }\n\n return validationResult\n }\n\nconst validateAttribute = async (params: AttributeValidatorParams & { entityKeysCache?: EntityKeysCache }) => {\n const { survey, record, attribute } = params\n if (Records.isNodeApplicable(attribute)(record)) {\n const nodeDef = Surveys.getNodeDefByUuid({ survey, uuid: attribute.nodeDefUuid })\n const validatorParams = { ...params, nodeDef }\n return new Validator().validate(attribute, {\n [NodeKeys.value]: [\n _validateRequired(validatorParams),\n AttributeTypeValidator.validateValueType(validatorParams),\n _validateNodeValidations(validatorParams),\n AttributeKeyValidator.validateAttributeKey(validatorParams),\n AttributeUniqueValidator.validateAttributeUnique(validatorParams),\n ],\n })\n }\n return ValidationFactory.createInstance()\n}\n\nconst findSiblingKeyNodesToValidate = (\n params: AttributeValidatorParams & {\n nodeDef: NodeDef<NodeDefType, NodeDefProps>\n nodeParent?: ArenaRecordNode\n siblingKeyNodesCache?: SiblingKeyNodesCache\n }\n) => {\n const { survey, nodeDef, nodeParent: parentNode, attribute } = params\n if (\n !NodeDefs.isKey(nodeDef) ||\n !parentNode ||\n (NodeDefs.isAutoIncrementalKey(nodeDef) && attribute.created && Nodes.isDefaultValueApplied(attribute))\n ) {\n // when a new node is created and the key is autoincremental, its value will be unique\n // and the validation of sibling key attributes is not necessary\n return []\n }\n // when a key attribute is updated, a sibling key attribute with the same value\n // or a sibling attribute with a validation error (duplicate key) should be re-validated\n const siblingNodeKeys = _getSiblingNodeKeys(params)\n const siblingNodeKeysWithSameValue: ArenaRecordNode[] = []\n const siblingNodeKeysWithErrors: ArenaRecordNode[] = []\n siblingNodeKeys.forEach(({ keyNode, hasErrors }) => {\n if (NodeValues.isValueEqual({ survey, nodeDef, parentNode, value: keyNode.value, valueSearch: attribute.value })) {\n siblingNodeKeysWithSameValue.push(keyNode)\n }\n if (hasErrors) {\n siblingNodeKeysWithErrors.push(keyNode)\n }\n })\n return [...siblingNodeKeysWithSameValue, ...siblingNodeKeysWithErrors]\n}\n\nconst findSortedNodesToValidate = (params: SortedAttributesValidatorParams): ArenaRecordNode[] => {\n const { survey, record, nodesArray } = params\n\n const result = []\n const siblingKeyNodesCache: SiblingKeyNodesCache = new Map()\n for (const node of nodesArray) {\n const nodeDef = Surveys.getNodeDefByUuid({ survey, uuid: node.nodeDefUuid })\n if (!NodeDefs.isAttribute(nodeDef)) {\n continue\n }\n // Get dependents and attribute itself\n const nodePointersAttributeAndDependents = [\n ...Records.getDependentNodePointers(survey, node, SurveyDependencyType.validations, true)(record),\n ...Records.getDependentNodePointers(survey, node, SurveyDependencyType.required)(record),\n ]\n\n const nodeParent = Records.getParent(node)(record)\n\n result.push(\n ...NodePointers.getNodesFromNodePointers({ record, nodePointers: nodePointersAttributeAndDependents }),\n ...findSiblingKeyNodesToValidate({ ...params, nodeDef, nodeParent, attribute: node, siblingKeyNodesCache })\n )\n\n if (NodeDefs.getValidations(nodeDef)?.unique) {\n for (const sibling of Records.getAttributeSiblings(node, nodeDef)(record)) {\n result.push(sibling)\n }\n }\n }\n\n return result\n}\n\nconst validateSelfAndDependentSortedAttributes = async (\n params: SortedAttributesValidatorParams\n): Promise<ValidationFields> => {\n const nodesToValidate: ArenaRecordNode[] = findSortedNodesToValidate(params)\n const validationsByNodeUuid: ValidationFields = {}\n // the record doesn't change during the validation: entity keys can be cached\n const entityKeysCache = createEntityKeysCache()\n\n for (const nodeToValidate of nodesToValidate) {\n const nodeUuid = nodeToValidate.uuid\n // Validate only attributes not deleted and not validated already\n if (!nodeToValidate.deleted && !validationsByNodeUuid[nodeUuid]) {\n // sequential: avoid concurrent item/taxon lookups on large node sets\n const attributeValidatorParams = { ...params, attribute: nodeToValidate, entityKeysCache }\n validationsByNodeUuid[nodeUuid] = await validateAttribute(attributeValidatorParams) // NOSONAR\n }\n }\n return validationsByNodeUuid\n}\n\nexport const AttributeValidator = {\n validateSelfAndDependentSortedAttributes,\n}\n"]}