@lokalise/prisma-utils 1.4.0 → 1.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -9,7 +9,28 @@ import { PrismaClientKnownRequestError } from '@prisma/client/runtime/library';
9
9
  */
10
10
  export declare const isPrismaClientKnownRequestError: (error: unknown) => error is PrismaClientKnownRequestError;
11
11
  export declare const isPrismaTransactionClosedError: (error: PrismaClientKnownRequestError) => boolean;
12
+ /**
13
+ * Prisma error code P2025 indicates that the operation failed because it depends on one or more
14
+ * records that were required but not found
15
+ */
12
16
  export declare const PRISMA_NOT_FOUND_ERROR = "P2025";
17
+ /**
18
+ * Prisma error code P2034 indicates a serialization error and that the transaction must be retried.
19
+ * A different error code would indicate that an internal state error happened and that
20
+ * the cluster itself is experiencing an issue which requires intervention
21
+ */
13
22
  export declare const PRISMA_SERIALIZATION_ERROR = "P2034";
23
+ /**
24
+ * Prisma error code P2002 indicates that the operation failed because a unique constraint was
25
+ * violated. This can happen if you try to create a record with a unique field that already exists
26
+ */
14
27
  export declare const PRISMA_UNIQUE_CONSTRAINT_ERROR = "P2002";
28
+ /**
29
+ * Prisma error code P2028 indicates a transaction API error, essentially a placeholder for errors that do not fit into
30
+ * a more specific category. You should look into the error message for more details
31
+ */
15
32
  export declare const PRISMA_TRANSACTION_ERROR = "P2028";
33
+ /**
34
+ * Prisma error code P1017 indicates that the connection to the database server was prematurely terminated by the server
35
+ */
36
+ export declare const PRISMA_SERVER_CLOSED_CONNECTION_ERROR = "P1017";
@@ -1,10 +1,11 @@
1
- import { isError as R } from "@lokalise/node-core";
2
- const n = (s) => !!s && R(s) && "code" in s && typeof s.code == "string" && s.code.startsWith("P"), c = (s) => s.code === o && s.message.includes("Transaction already closed"), i = "P2025", P = "P2034", a = "P2002", o = "P2028";
1
+ import { isError as s } from "@lokalise/node-core";
2
+ const n = (R) => !!R && s(R) && "code" in R && typeof R.code == "string" && R.code.startsWith("P"), c = (R) => R.code === o && R.message.includes("Transaction already closed"), E = "P2025", _ = "P2034", i = "P2002", o = "P2028", O = "P1017";
3
3
  export {
4
- i as PRISMA_NOT_FOUND_ERROR,
5
- P as PRISMA_SERIALIZATION_ERROR,
4
+ E as PRISMA_NOT_FOUND_ERROR,
5
+ _ as PRISMA_SERIALIZATION_ERROR,
6
+ O as PRISMA_SERVER_CLOSED_CONNECTION_ERROR,
6
7
  o as PRISMA_TRANSACTION_ERROR,
7
- a as PRISMA_UNIQUE_CONSTRAINT_ERROR,
8
+ i as PRISMA_UNIQUE_CONSTRAINT_ERROR,
8
9
  n as isPrismaClientKnownRequestError,
9
10
  c as isPrismaTransactionClosedError
10
11
  };
@@ -1 +1 @@
1
- {"version":3,"file":"prismaError.js","sources":["../../src/errors/prismaError.ts"],"sourcesContent":["import { isError } from '@lokalise/node-core'\nimport type { PrismaClientKnownRequestError } from '@prisma/client/runtime/library'\n\n/**\n * What is checked?\n * \t1. error is defined and not null\n * \t2. error is an `Error`\n * \t3. error contains the field code which is a string\n * \t4. code starts by `P` ([doc](https://www.prisma.io/docs/reference/api-reference/error-reference#error-codes))\n */\nexport const isPrismaClientKnownRequestError = (\n error: unknown,\n): error is PrismaClientKnownRequestError =>\n !!error &&\n isError(error) &&\n 'code' in error &&\n typeof error.code === 'string' &&\n error.code.startsWith('P')\n\nexport const isPrismaTransactionClosedError = (error: PrismaClientKnownRequestError): boolean =>\n error.code === PRISMA_TRANSACTION_ERROR && error.message.includes('Transaction already closed')\n\n/*\n * Prisma error code P2025 indicates that the operation failed because it depends on one or more\n * records that were required but not found\n */\nexport const PRISMA_NOT_FOUND_ERROR = 'P2025'\n\n/*\n * Prisma error code P2034 indicates a serialization error and that the transaction must be retried.\n * A different error code would indicate that an internal state error happened and that\n * the cluster itself is experiencing an issue which requires intervention\n */\nexport const PRISMA_SERIALIZATION_ERROR = 'P2034'\n\n/*\n * Prisma error code P2002 indicates that the operation failed because a unique constraint was\n * violated. This can happen if you try to create a record with a unique field that already exists\n */\nexport const PRISMA_UNIQUE_CONSTRAINT_ERROR = 'P2002'\n\n/*\n * Prisma error code P2028 indicates a transaction API error, essentially a placeholder for errors that do not fit into\n * a more specific category. You should look into the error message for more details\n */\nexport const PRISMA_TRANSACTION_ERROR = 'P2028'\n"],"names":["isPrismaClientKnownRequestError","error","isError","isPrismaTransactionClosedError","PRISMA_TRANSACTION_ERROR","PRISMA_NOT_FOUND_ERROR","PRISMA_SERIALIZATION_ERROR","PRISMA_UNIQUE_CONSTRAINT_ERROR"],"mappings":";AAUO,MAAMA,IAAkC,CAC7CC,MAEA,CAAC,CAACA,KACFC,EAAQD,CAAK,KACb,UAAUA,KACV,OAAOA,EAAM,QAAS,YACtBA,EAAM,KAAK,WAAW,GAAG,GAEdE,IAAiC,CAACF,MAC7CA,EAAM,SAASG,KAA4BH,EAAM,QAAQ,SAAS,4BAA4B,GAMnFI,IAAyB,SAOzBC,IAA6B,SAM7BC,IAAiC,SAMjCH,IAA2B;"}
1
+ {"version":3,"file":"prismaError.js","sources":["../../src/errors/prismaError.ts"],"sourcesContent":["import { isError } from '@lokalise/node-core'\nimport type { PrismaClientKnownRequestError } from '@prisma/client/runtime/library'\n\n/**\n * What is checked?\n * \t1. error is defined and not null\n * \t2. error is an `Error`\n * \t3. error contains the field code which is a string\n * \t4. code starts by `P` ([doc](https://www.prisma.io/docs/reference/api-reference/error-reference#error-codes))\n */\nexport const isPrismaClientKnownRequestError = (\n error: unknown,\n): error is PrismaClientKnownRequestError =>\n !!error &&\n isError(error) &&\n 'code' in error &&\n typeof error.code === 'string' &&\n error.code.startsWith('P')\n\nexport const isPrismaTransactionClosedError = (error: PrismaClientKnownRequestError): boolean =>\n error.code === PRISMA_TRANSACTION_ERROR && error.message.includes('Transaction already closed')\n\n/**\n * Prisma error code P2025 indicates that the operation failed because it depends on one or more\n * records that were required but not found\n */\nexport const PRISMA_NOT_FOUND_ERROR = 'P2025'\n\n/**\n * Prisma error code P2034 indicates a serialization error and that the transaction must be retried.\n * A different error code would indicate that an internal state error happened and that\n * the cluster itself is experiencing an issue which requires intervention\n */\nexport const PRISMA_SERIALIZATION_ERROR = 'P2034'\n\n/**\n * Prisma error code P2002 indicates that the operation failed because a unique constraint was\n * violated. This can happen if you try to create a record with a unique field that already exists\n */\nexport const PRISMA_UNIQUE_CONSTRAINT_ERROR = 'P2002'\n\n/**\n * Prisma error code P2028 indicates a transaction API error, essentially a placeholder for errors that do not fit into\n * a more specific category. You should look into the error message for more details\n */\nexport const PRISMA_TRANSACTION_ERROR = 'P2028'\n\n/**\n * Prisma error code P1017 indicates that the connection to the database server was prematurely terminated by the server\n */\nexport const PRISMA_SERVER_CLOSED_CONNECTION_ERROR = 'P1017'\n"],"names":["isPrismaClientKnownRequestError","error","isError","isPrismaTransactionClosedError","PRISMA_TRANSACTION_ERROR","PRISMA_NOT_FOUND_ERROR","PRISMA_SERIALIZATION_ERROR","PRISMA_UNIQUE_CONSTRAINT_ERROR","PRISMA_SERVER_CLOSED_CONNECTION_ERROR"],"mappings":";AAUO,MAAMA,IAAkC,CAC7CC,MAEA,CAAC,CAACA,KACFC,EAAQD,CAAK,KACb,UAAUA,KACV,OAAOA,EAAM,QAAS,YACtBA,EAAM,KAAK,WAAW,GAAG,GAEdE,IAAiC,CAACF,MAC7CA,EAAM,SAASG,KAA4BH,EAAM,QAAQ,SAAS,4BAA4B,GAMnFI,IAAyB,SAOzBC,IAA6B,SAM7BC,IAAiC,SAMjCH,IAA2B,SAK3BI,IAAwC;"}
package/dist/index.cjs CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const i=require("@lokalise/node-core"),T=require("node:timers/promises"),c=e=>!!e&&i.isError(e)&&"code"in e&&typeof e.code=="string"&&e.code.startsWith("P"),R=e=>e.code===u&&e.message.includes("Transaction already closed"),A="P2025",l="P2034",m="P2002",u="P2028",O="40001",_=e=>{const r=e.meta;return r?r.code===O:!1},d={retriesAllowed:2,DbDriver:"CockroachDb",baseRetryDelayMs:100,maxRetryDelayMs:3e4,timeout:5e3,maxTimeout:3e4},y=async(e,r,o)=>{let t={...d,...o},s,a=0;do{if(a>0&&await T.setTimeout(E(a,t.baseRetryDelayMs,t.maxRetryDelayMs)),s=await I(e,r,t),s.result)break;const n=N(s,t.DbDriver);if(!n)break;n==="increase-timeout"&&(t=i.deepClone(t),t.timeout=Math.min(t.timeout*2,t.maxTimeout)),a++}while(a<=t.retriesAllowed);return s??{error:new Error("No transaction executed")}},I=async(e,r,o)=>{try{return{result:await e.$transaction(r,o)}}catch(t){return{error:t}}},E=(e,r,o)=>{const t=Math.pow(2,e-1)*r;return Math.min(t,o)},N=(e,r)=>{if(c(e.error)){const o=e.error;if(o.code===l||r==="CockroachDb"&&_(o))return!0;if(R(o))return"increase-timeout"}return!1};exports.PRISMA_NOT_FOUND_ERROR=A;exports.PRISMA_SERIALIZATION_ERROR=l;exports.PRISMA_TRANSACTION_ERROR=u;exports.PRISMA_UNIQUE_CONSTRAINT_ERROR=m;exports.isPrismaClientKnownRequestError=c;exports.isPrismaTransactionClosedError=R;exports.prismaTransaction=y;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const i=require("@lokalise/node-core"),T=require("node:timers/promises"),R=e=>!!e&&i.isError(e)&&"code"in e&&typeof e.code=="string"&&e.code.startsWith("P"),c=e=>e.code===u&&e.message.includes("Transaction already closed"),_="P2025",l="P2034",E="P2002",u="P2028",O="P1017",A="40001",m=e=>{const r=e.meta;return r?r.code===A:!1},I={retriesAllowed:2,DbDriver:"CockroachDb",baseRetryDelayMs:100,maxRetryDelayMs:3e4,timeout:5e3,maxTimeout:3e4},N=async(e,r,o)=>{let t={...I,...o},s,n=0;do{if(n>0&&await T.setTimeout(d(n,t.baseRetryDelayMs,t.maxRetryDelayMs)),s=await C(e,r,t),s.result)break;const a=y(s,t.DbDriver);if(!a)break;a==="increase-timeout"&&(t=i.deepClone(t),t.timeout=Math.min(t.timeout*2,t.maxTimeout)),n++}while(n<=t.retriesAllowed);return s??{error:new Error("No transaction executed")}},C=async(e,r,o)=>{try{return{result:await e.$transaction(r,o)}}catch(t){return{error:t}}},d=(e,r,o)=>{const t=Math.pow(2,e-1)*r;return Math.min(t,o)},S=[l,O],y=(e,r)=>{if(R(e.error)){const o=e.error;if(S.includes(o.code)||r==="CockroachDb"&&m(o))return!0;if(c(o))return"increase-timeout"}return!1};exports.PRISMA_NOT_FOUND_ERROR=_;exports.PRISMA_SERIALIZATION_ERROR=l;exports.PRISMA_SERVER_CLOSED_CONNECTION_ERROR=O;exports.PRISMA_TRANSACTION_ERROR=u;exports.PRISMA_UNIQUE_CONSTRAINT_ERROR=E;exports.isPrismaClientKnownRequestError=R;exports.isPrismaTransactionClosedError=c;exports.prismaTransaction=N;
2
2
  //# sourceMappingURL=index.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","sources":["../src/errors/prismaError.ts","../src/errors/cockroachdbError.ts","../src/prismaTransaction.ts"],"sourcesContent":["import { isError } from '@lokalise/node-core'\nimport type { PrismaClientKnownRequestError } from '@prisma/client/runtime/library'\n\n/**\n * What is checked?\n * \t1. error is defined and not null\n * \t2. error is an `Error`\n * \t3. error contains the field code which is a string\n * \t4. code starts by `P` ([doc](https://www.prisma.io/docs/reference/api-reference/error-reference#error-codes))\n */\nexport const isPrismaClientKnownRequestError = (\n error: unknown,\n): error is PrismaClientKnownRequestError =>\n !!error &&\n isError(error) &&\n 'code' in error &&\n typeof error.code === 'string' &&\n error.code.startsWith('P')\n\nexport const isPrismaTransactionClosedError = (error: PrismaClientKnownRequestError): boolean =>\n error.code === PRISMA_TRANSACTION_ERROR && error.message.includes('Transaction already closed')\n\n/*\n * Prisma error code P2025 indicates that the operation failed because it depends on one or more\n * records that were required but not found\n */\nexport const PRISMA_NOT_FOUND_ERROR = 'P2025'\n\n/*\n * Prisma error code P2034 indicates a serialization error and that the transaction must be retried.\n * A different error code would indicate that an internal state error happened and that\n * the cluster itself is experiencing an issue which requires intervention\n */\nexport const PRISMA_SERIALIZATION_ERROR = 'P2034'\n\n/*\n * Prisma error code P2002 indicates that the operation failed because a unique constraint was\n * violated. This can happen if you try to create a record with a unique field that already exists\n */\nexport const PRISMA_UNIQUE_CONSTRAINT_ERROR = 'P2002'\n\n/*\n * Prisma error code P2028 indicates a transaction API error, essentially a placeholder for errors that do not fit into\n * a more specific category. You should look into the error message for more details\n */\nexport const PRISMA_TRANSACTION_ERROR = 'P2028'\n","import type { PrismaClientKnownRequestError } from '@prisma/client/runtime/library'\n\n/**\n * https://www.cockroachlabs.com/docs/stable/transaction-retry-error-reference#:~:text=To%20indicate%20that%20a%20transaction,the%20string%20%22restart%20transaction%22%20.\n *\n * All transaction retry errors use the SQLSTATE error code 40001\n */\nconst COCKROACHDB_RETRY_TRANSACTION_CODE = '40001'\n\n/**\n * Check if the error is a CockroachDB transaction retry error\n *\n * @param error\n */\nexport const isCockroachDBRetryTransaction = (error: PrismaClientKnownRequestError): boolean => {\n const meta = error.meta\n if (!meta) return false\n\n return meta.code === COCKROACHDB_RETRY_TRANSACTION_CODE\n}\n","import { setTimeout } from 'node:timers/promises'\n\nimport type { Either } from '@lokalise/node-core'\nimport { deepClone } from '@lokalise/node-core'\nimport type { Prisma, PrismaClient } from '@prisma/client'\nimport type * as runtime from '@prisma/client/runtime/library'\n\nimport { isCockroachDBRetryTransaction } from './errors/cockroachdbError'\nimport {\n PRISMA_SERIALIZATION_ERROR,\n isPrismaClientKnownRequestError,\n isPrismaTransactionClosedError,\n} from './errors/prismaError'\nimport type {\n DbDriver,\n PrismaTransactionBasicOptions,\n PrismaTransactionFn,\n PrismaTransactionOptions,\n PrismaTransactionReturnType,\n} from './types'\n\nconst DEFAULT_OPTIONS = {\n retriesAllowed: 2, // first try + 2 retries = 3 tries\n DbDriver: 'CockroachDb',\n baseRetryDelayMs: 100,\n maxRetryDelayMs: 30000, // 30s\n timeout: 5000, // 5s\n maxTimeout: 30000, // 30s\n} satisfies Partial<PrismaTransactionOptions>\n\n/**\n * Perform a Prisma DB transaction with automatic retries if needed.\n *\n * @template T | T extends Prisma.PrismaPromise<unknown>[]\n * @param {PrismaClient} prisma\n * @param {PrismaTransactionFn<T> | Prisma.PrismaPromise<unknown>[]} arg\t operation to perform into the transaction\n * @param {PrismaTransactionOptions | PrismaTransactionBasicOptions} options transaction configuration\n * @return {Promise<PrismaTransactionReturnType<T>>}\n */\nexport const prismaTransaction = (async <T, P extends PrismaClient>(\n prisma: P,\n arg: PrismaTransactionFn<T, P> | Prisma.PrismaPromise<unknown>[],\n options?: PrismaTransactionOptions | PrismaTransactionBasicOptions,\n): Promise<PrismaTransactionReturnType<T>> => {\n let optionsWithDefaults = { ...DEFAULT_OPTIONS, ...options }\n let result: PrismaTransactionReturnType<T> | undefined = undefined\n\n let retries = 0\n do {\n if (retries > 0) {\n await setTimeout(\n calculateRetryDelay(\n retries,\n optionsWithDefaults.baseRetryDelayMs,\n optionsWithDefaults.maxRetryDelayMs,\n ),\n )\n }\n\n result = await executeTransactionTry(prisma, arg, optionsWithDefaults)\n if (result.result) break\n\n const retryAllowed = isRetryAllowed(result, optionsWithDefaults.DbDriver)\n if (!retryAllowed) break\n\n if (retryAllowed === 'increase-timeout') {\n optionsWithDefaults = deepClone(optionsWithDefaults)\n optionsWithDefaults.timeout = Math.min(\n optionsWithDefaults.timeout * 2,\n optionsWithDefaults.maxTimeout,\n )\n }\n\n retries++\n } while (retries <= optionsWithDefaults.retriesAllowed)\n\n return result ?? { error: new Error('No transaction executed') }\n}) as {\n <T, P extends PrismaClient>(\n prisma: P,\n fn: PrismaTransactionFn<T, P>,\n options?: PrismaTransactionOptions,\n ): Promise<Either<unknown, T>>\n <T extends Prisma.PrismaPromise<unknown>[], P extends PrismaClient>(\n prisma: P,\n args: [...T],\n options?: PrismaTransactionBasicOptions,\n ): Promise<Either<unknown, runtime.Types.Utils.UnwrapTuple<T>>>\n}\n\nconst executeTransactionTry = async <T, P extends PrismaClient>(\n prisma: P,\n arg: PrismaTransactionFn<T, P> | Prisma.PrismaPromise<unknown>[],\n options?: PrismaTransactionOptions,\n): Promise<PrismaTransactionReturnType<T>> => {\n try {\n return {\n // @ts-ignore\n result: await prisma.$transaction<T>(arg, options),\n }\n } catch (error) {\n return { error }\n }\n}\n\nconst calculateRetryDelay = (\n retries: number,\n baseRetryDelayMs: number,\n maxDelayMs: number,\n): number => {\n // exponential backoff -> 2^(retry-1) * baseRetryDelayMs\n const expDelay = Math.pow(2, retries - 1) * baseRetryDelayMs\n return Math.min(expDelay, maxDelayMs)\n}\n\ntype isRetryAllowedResult = boolean | 'increase-timeout'\n\nconst isRetryAllowed = <T>(\n result: PrismaTransactionReturnType<T>,\n dbDriver: DbDriver,\n): isRetryAllowedResult => {\n if (isPrismaClientKnownRequestError(result.error)) {\n const error = result.error\n if (error.code === PRISMA_SERIALIZATION_ERROR) return true\n if (dbDriver === 'CockroachDb' && isCockroachDBRetryTransaction(error)) return true\n if (isPrismaTransactionClosedError(error)) return 'increase-timeout'\n }\n\n return false\n}\n"],"names":["isPrismaClientKnownRequestError","error","isError","isPrismaTransactionClosedError","PRISMA_TRANSACTION_ERROR","PRISMA_NOT_FOUND_ERROR","PRISMA_SERIALIZATION_ERROR","PRISMA_UNIQUE_CONSTRAINT_ERROR","COCKROACHDB_RETRY_TRANSACTION_CODE","isCockroachDBRetryTransaction","meta","DEFAULT_OPTIONS","prismaTransaction","prisma","arg","options","optionsWithDefaults","result","retries","setTimeout","calculateRetryDelay","executeTransactionTry","retryAllowed","isRetryAllowed","deepClone","baseRetryDelayMs","maxDelayMs","expDelay","dbDriver"],"mappings":"yJAUaA,EACXC,GAEA,CAAC,CAACA,GACFC,UAAQD,CAAK,GACb,SAAUA,GACV,OAAOA,EAAM,MAAS,UACtBA,EAAM,KAAK,WAAW,GAAG,EAEdE,EAAkCF,GAC7CA,EAAM,OAASG,GAA4BH,EAAM,QAAQ,SAAS,4BAA4B,EAMnFI,EAAyB,QAOzBC,EAA6B,QAM7BC,EAAiC,QA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ErB,GADIhB,EAAM,OAASK,GACfsB,IAAa,eAAiBnB,EAA8BR,CAAK,EAAU,MAAA,GAC3E,GAAAE,EAA+BF,CAAK,EAAU,MAAA,kBACpD,CAEO,MAAA,EACT"}
1
+ {"version":3,"file":"index.cjs","sources":["../src/errors/prismaError.ts","../src/errors/cockroachdbError.ts","../src/prismaTransaction.ts"],"sourcesContent":["import { isError } from '@lokalise/node-core'\nimport type { PrismaClientKnownRequestError } from '@prisma/client/runtime/library'\n\n/**\n * What is checked?\n * \t1. error is defined and not null\n * \t2. error is an `Error`\n * \t3. error contains the field code which is a string\n * \t4. code starts by `P` ([doc](https://www.prisma.io/docs/reference/api-reference/error-reference#error-codes))\n */\nexport const isPrismaClientKnownRequestError = (\n error: unknown,\n): error is PrismaClientKnownRequestError =>\n !!error &&\n isError(error) &&\n 'code' in error &&\n typeof error.code === 'string' &&\n error.code.startsWith('P')\n\nexport const isPrismaTransactionClosedError = (error: PrismaClientKnownRequestError): boolean =>\n error.code === PRISMA_TRANSACTION_ERROR && error.message.includes('Transaction already closed')\n\n/**\n * Prisma error code P2025 indicates that the operation failed because it depends on one or more\n * records that were required but not found\n */\nexport const PRISMA_NOT_FOUND_ERROR = 'P2025'\n\n/**\n * Prisma error code P2034 indicates a serialization error and that the transaction must be retried.\n * A different error code would indicate that an internal state error happened and that\n * the cluster itself is experiencing an issue which requires intervention\n */\nexport const PRISMA_SERIALIZATION_ERROR = 'P2034'\n\n/**\n * Prisma error code P2002 indicates that the operation failed because a unique constraint was\n * violated. This can happen if you try to create a record with a unique field that already exists\n */\nexport const PRISMA_UNIQUE_CONSTRAINT_ERROR = 'P2002'\n\n/**\n * Prisma error code P2028 indicates a transaction API error, essentially a placeholder for errors that do not fit into\n * a more specific category. You should look into the error message for more details\n */\nexport const PRISMA_TRANSACTION_ERROR = 'P2028'\n\n/**\n * Prisma error code P1017 indicates that the connection to the database server was prematurely terminated by the server\n */\nexport const PRISMA_SERVER_CLOSED_CONNECTION_ERROR = 'P1017'\n","import type { PrismaClientKnownRequestError } from '@prisma/client/runtime/library'\n\n/**\n * https://www.cockroachlabs.com/docs/stable/transaction-retry-error-reference#:~:text=To%20indicate%20that%20a%20transaction,the%20string%20%22restart%20transaction%22%20.\n *\n * All transaction retry errors use the SQLSTATE error code 40001\n */\nconst COCKROACHDB_RETRY_TRANSACTION_CODE = '40001'\n\n/**\n * Check if the error is a CockroachDB transaction retry error\n *\n * @param error\n */\nexport const isCockroachDBRetryTransaction = (error: PrismaClientKnownRequestError): boolean => {\n const meta = error.meta\n if (!meta) return false\n\n return meta.code === COCKROACHDB_RETRY_TRANSACTION_CODE\n}\n","import { setTimeout } from 'node:timers/promises'\n\nimport type { Either } from '@lokalise/node-core'\nimport { deepClone } from '@lokalise/node-core'\nimport type { Prisma, PrismaClient } from '@prisma/client'\nimport type * as runtime from '@prisma/client/runtime/library'\n\nimport { isCockroachDBRetryTransaction } from './errors/cockroachdbError'\nimport {\n PRISMA_SERIALIZATION_ERROR,\n PRISMA_SERVER_CLOSED_CONNECTION_ERROR,\n isPrismaClientKnownRequestError,\n isPrismaTransactionClosedError,\n} from './errors/prismaError'\nimport type {\n DbDriver,\n PrismaTransactionBasicOptions,\n PrismaTransactionFn,\n PrismaTransactionOptions,\n PrismaTransactionReturnType,\n} from './types'\n\nconst DEFAULT_OPTIONS = {\n retriesAllowed: 2, // first try + 2 retries = 3 tries\n DbDriver: 'CockroachDb',\n baseRetryDelayMs: 100,\n maxRetryDelayMs: 30000, // 30s\n timeout: 5000, // 5s\n maxTimeout: 30000, // 30s\n} satisfies Partial<PrismaTransactionOptions>\n\n/**\n * Perform a Prisma DB transaction with automatic retries if needed.\n *\n * @template T | T extends Prisma.PrismaPromise<unknown>[]\n * @param {PrismaClient} prisma\n * @param {PrismaTransactionFn<T> | Prisma.PrismaPromise<unknown>[]} arg\t operation to perform into the transaction\n * @param {PrismaTransactionOptions | PrismaTransactionBasicOptions} options transaction configuration\n * @return {Promise<PrismaTransactionReturnType<T>>}\n */\nexport const prismaTransaction = (async <T, P extends PrismaClient>(\n prisma: P,\n arg: PrismaTransactionFn<T, P> | Prisma.PrismaPromise<unknown>[],\n options?: PrismaTransactionOptions | PrismaTransactionBasicOptions,\n): Promise<PrismaTransactionReturnType<T>> => {\n let optionsWithDefaults = { ...DEFAULT_OPTIONS, ...options }\n let result: PrismaTransactionReturnType<T> | undefined = undefined\n\n let retries = 0\n do {\n if (retries > 0) {\n await setTimeout(\n calculateRetryDelay(\n retries,\n optionsWithDefaults.baseRetryDelayMs,\n optionsWithDefaults.maxRetryDelayMs,\n ),\n )\n }\n\n result = await executeTransactionTry(prisma, arg, optionsWithDefaults)\n if (result.result) break\n\n const retryAllowed = isRetryAllowed(result, optionsWithDefaults.DbDriver)\n if (!retryAllowed) break\n\n if (retryAllowed === 'increase-timeout') {\n optionsWithDefaults = deepClone(optionsWithDefaults)\n optionsWithDefaults.timeout = Math.min(\n optionsWithDefaults.timeout * 2,\n optionsWithDefaults.maxTimeout,\n )\n }\n\n retries++\n } while (retries <= optionsWithDefaults.retriesAllowed)\n\n return result ?? { error: new Error('No transaction executed') }\n}) as {\n <T, P extends PrismaClient>(\n prisma: P,\n fn: PrismaTransactionFn<T, P>,\n options?: PrismaTransactionOptions,\n ): Promise<Either<unknown, T>>\n <T extends Prisma.PrismaPromise<unknown>[], P extends PrismaClient>(\n prisma: P,\n args: [...T],\n options?: PrismaTransactionBasicOptions,\n ): Promise<Either<unknown, runtime.Types.Utils.UnwrapTuple<T>>>\n}\n\nconst executeTransactionTry = async <T, P extends PrismaClient>(\n prisma: P,\n arg: PrismaTransactionFn<T, P> | Prisma.PrismaPromise<unknown>[],\n options?: PrismaTransactionOptions,\n): Promise<PrismaTransactionReturnType<T>> => {\n try {\n return {\n // @ts-ignore\n result: await prisma.$transaction<T>(arg, options),\n }\n } catch (error) {\n return { error }\n }\n}\n\nconst calculateRetryDelay = (\n retries: number,\n baseRetryDelayMs: number,\n maxDelayMs: number,\n): number => {\n // exponential backoff -> 2^(retry-1) * baseRetryDelayMs\n const expDelay = Math.pow(2, retries - 1) * baseRetryDelayMs\n return Math.min(expDelay, maxDelayMs)\n}\n\nconst PrismaCodesToRetry = [PRISMA_SERIALIZATION_ERROR, PRISMA_SERVER_CLOSED_CONNECTION_ERROR]\ntype isRetryAllowedResult = boolean | 'increase-timeout'\n\nconst isRetryAllowed = <T>(\n result: PrismaTransactionReturnType<T>,\n dbDriver: DbDriver,\n): isRetryAllowedResult => {\n if (isPrismaClientKnownRequestError(result.error)) {\n const error = result.error\n // retry if the error code is in the list of codes to retry\n if (PrismaCodesToRetry.includes(error.code)) return true\n // also retry if the error is a CockroachDB retry transaction error\n if (dbDriver === 'CockroachDb' && isCockroachDBRetryTransaction(error)) return true\n // In case transaction is closed (timeout), retry increasing the timeout\n if (isPrismaTransactionClosedError(error)) return 'increase-timeout'\n }\n\n return false\n}\n"],"names":["isPrismaClientKnownRequestError","error","isError","isPrismaTransactionClosedError","PRISMA_TRANSACTION_ERROR","PRISMA_NOT_FOUND_ERROR","PRISMA_SERIALIZATION_ERROR","PRISMA_UNIQUE_CONSTRAINT_ERROR","PRISMA_SERVER_CLOSED_CONNECTION_ERROR","COCKROACHDB_RETRY_TRANSACTION_CODE","isCockroachDBRetryTransaction","meta","DEFAULT_OPTIONS","prismaTransaction","prisma","arg","options","optionsWithDefaults","result","retries","setTimeout","calculateRetryDelay","executeTransactionTry","retryAllowed","isRetryAllowed","deepClone","baseRetryDelayMs","maxDelayMs","expDelay","PrismaCodesToRetry","dbDriver"],"mappings":"yJAUaA,EACXC,GAEA,CAAC,CAACA,GACFC,UAAQD,CAAK,GACb,SAAUA,GACV,OAAOA,EAAM,MAAS,UACtBA,EAAM,KAAK,WAAW,GAAG,EAEdE,EAAkCF,GAC7CA,EAAM,OAASG,GAA4BH,EAAM,QAAQ,SAAS,4BAA4B,EAMnFI,EAAyB,QAOzBC,EAA6B,QAM7BC,EAAiC,QAMjCH,EAA2B,QAK3BI,EAAwC,QC3C/CC,E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AAQiB,EAAO,MAIrB,GAFIW,EAAmB,SAAS5B,EAAM,IAAI,GAEtC6B,IAAa,eAAiBpB,EAA8BT,CAAK,EAAU,MAAA,GAE3E,GAAAE,EAA+BF,CAAK,EAAU,MAAA,kBACpD,CAEO,MAAA,EACT"}
package/dist/index.js CHANGED
@@ -1,12 +1,13 @@
1
- import { PRISMA_NOT_FOUND_ERROR as o, PRISMA_SERIALIZATION_ERROR as I, PRISMA_TRANSACTION_ERROR as _, PRISMA_UNIQUE_CONSTRAINT_ERROR as s, isPrismaClientKnownRequestError as A, isPrismaTransactionClosedError as O } from "./errors/prismaError.js";
2
- import { prismaTransaction as E } from "./prismaTransaction.js";
1
+ import { PRISMA_NOT_FOUND_ERROR as _, PRISMA_SERIALIZATION_ERROR as E, PRISMA_SERVER_CLOSED_CONNECTION_ERROR as O, PRISMA_TRANSACTION_ERROR as I, PRISMA_UNIQUE_CONSTRAINT_ERROR as N, isPrismaClientKnownRequestError as o, isPrismaTransactionClosedError as A } from "./errors/prismaError.js";
2
+ import { prismaTransaction as s } from "./prismaTransaction.js";
3
3
  export {
4
- o as PRISMA_NOT_FOUND_ERROR,
5
- I as PRISMA_SERIALIZATION_ERROR,
6
- _ as PRISMA_TRANSACTION_ERROR,
7
- s as PRISMA_UNIQUE_CONSTRAINT_ERROR,
8
- A as isPrismaClientKnownRequestError,
9
- O as isPrismaTransactionClosedError,
10
- E as prismaTransaction
4
+ _ as PRISMA_NOT_FOUND_ERROR,
5
+ E as PRISMA_SERIALIZATION_ERROR,
6
+ O as PRISMA_SERVER_CLOSED_CONNECTION_ERROR,
7
+ I as PRISMA_TRANSACTION_ERROR,
8
+ N as PRISMA_UNIQUE_CONSTRAINT_ERROR,
9
+ o as isPrismaClientKnownRequestError,
10
+ A as isPrismaTransactionClosedError,
11
+ s as prismaTransaction
11
12
  };
12
13
  //# sourceMappingURL=index.js.map
@@ -1,7 +1,7 @@
1
1
  import { setTimeout as n } from "node:timers/promises";
2
2
  import { deepClone as c } from "@lokalise/node-core";
3
3
  import { isCockroachDBRetryTransaction as l } from "./errors/cockroachdbError.js";
4
- import { isPrismaClientKnownRequestError as m, PRISMA_SERIALIZATION_ERROR as u, isPrismaTransactionClosedError as y } from "./errors/prismaError.js";
4
+ import { isPrismaClientKnownRequestError as m, isPrismaTransactionClosedError as u, PRISMA_SERIALIZATION_ERROR as R, PRISMA_SERVER_CLOSED_CONNECTION_ERROR as y } from "./errors/prismaError.js";
5
5
  const D = {
6
6
  retriesAllowed: 2,
7
7
  // first try + 2 retries = 3 tries
@@ -13,24 +13,24 @@ const D = {
13
13
  // 5s
14
14
  maxTimeout: 3e4
15
15
  // 30s
16
- }, b = async (t, o, e) => {
17
- let r = { ...D, ...e }, a, i = 0;
16
+ }, A = async (t, o, e) => {
17
+ let r = { ...D, ...e }, i, a = 0;
18
18
  do {
19
- if (i > 0 && await n(
20
- R(
21
- i,
19
+ if (a > 0 && await n(
20
+ T(
21
+ a,
22
22
  r.baseRetryDelayMs,
23
23
  r.maxRetryDelayMs
24
24
  )
25
- ), a = await f(t, o, r), a.result) break;
26
- const s = w(a, r.DbDriver);
25
+ ), i = await f(t, o, r), i.result) break;
26
+ const s = w(i, r.DbDriver);
27
27
  if (!s) break;
28
28
  s === "increase-timeout" && (r = c(r), r.timeout = Math.min(
29
29
  r.timeout * 2,
30
30
  r.maxTimeout
31
- )), i++;
32
- } while (i <= r.retriesAllowed);
33
- return a ?? { error: new Error("No transaction executed") };
31
+ )), a++;
32
+ } while (a <= r.retriesAllowed);
33
+ return i ?? { error: new Error("No transaction executed") };
34
34
  }, f = async (t, o, e) => {
35
35
  try {
36
36
  return {
@@ -40,18 +40,18 @@ const D = {
40
40
  } catch (r) {
41
41
  return { error: r };
42
42
  }
43
- }, R = (t, o, e) => {
43
+ }, T = (t, o, e) => {
44
44
  const r = Math.pow(2, t - 1) * o;
45
45
  return Math.min(r, e);
46
- }, w = (t, o) => {
46
+ }, d = [R, y], w = (t, o) => {
47
47
  if (m(t.error)) {
48
48
  const e = t.error;
49
- if (e.code === u || o === "CockroachDb" && l(e)) return !0;
50
- if (y(e)) return "increase-timeout";
49
+ if (d.includes(e.code) || o === "CockroachDb" && l(e)) return !0;
50
+ if (u(e)) return "increase-timeout";
51
51
  }
52
52
  return !1;
53
53
  };
54
54
  export {
55
- b as prismaTransaction
55
+ A as prismaTransaction
56
56
  };
57
57
  //# sourceMappingURL=prismaTransaction.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"prismaTransaction.js","sources":["../src/prismaTransaction.ts"],"sourcesContent":["import { setTimeout } from 'node:timers/promises'\n\nimport type { Either } from '@lokalise/node-core'\nimport { deepClone } from '@lokalise/node-core'\nimport type { Prisma, PrismaClient } from '@prisma/client'\nimport type * as runtime from '@prisma/client/runtime/library'\n\nimport { isCockroachDBRetryTransaction } from './errors/cockroachdbError'\nimport {\n PRISMA_SERIALIZATION_ERROR,\n isPrismaClientKnownRequestError,\n isPrismaTransactionClosedError,\n} from './errors/prismaError'\nimport type {\n DbDriver,\n PrismaTransactionBasicOptions,\n PrismaTransactionFn,\n PrismaTransactionOptions,\n PrismaTransactionReturnType,\n} from './types'\n\nconst DEFAULT_OPTIONS = {\n retriesAllowed: 2, // first try + 2 retries = 3 tries\n DbDriver: 'CockroachDb',\n baseRetryDelayMs: 100,\n maxRetryDelayMs: 30000, // 30s\n timeout: 5000, // 5s\n maxTimeout: 30000, // 30s\n} satisfies Partial<PrismaTransactionOptions>\n\n/**\n * Perform a Prisma DB transaction with automatic retries if needed.\n *\n * @template T | T extends Prisma.PrismaPromise<unknown>[]\n * @param {PrismaClient} prisma\n * @param {PrismaTransactionFn<T> | Prisma.PrismaPromise<unknown>[]} arg\t operation to perform into the transaction\n * @param {PrismaTransactionOptions | PrismaTransactionBasicOptions} options transaction configuration\n * @return {Promise<PrismaTransactionReturnType<T>>}\n */\nexport const prismaTransaction = (async <T, P extends PrismaClient>(\n prisma: P,\n arg: PrismaTransactionFn<T, P> | Prisma.PrismaPromise<unknown>[],\n options?: PrismaTransactionOptions | PrismaTransactionBasicOptions,\n): Promise<PrismaTransactionReturnType<T>> => {\n let optionsWithDefaults = { ...DEFAULT_OPTIONS, ...options }\n let result: PrismaTransactionReturnType<T> | undefined = undefined\n\n let retries = 0\n do {\n if (retries > 0) {\n await setTimeout(\n calculateRetryDelay(\n retries,\n optionsWithDefaults.baseRetryDelayMs,\n optionsWithDefaults.maxRetryDelayMs,\n ),\n )\n }\n\n result = await executeTransactionTry(prisma, arg, optionsWithDefaults)\n if (result.result) break\n\n const retryAllowed = isRetryAllowed(result, optionsWithDefaults.DbDriver)\n if (!retryAllowed) break\n\n if (retryAllowed === 'increase-timeout') {\n optionsWithDefaults = deepClone(optionsWithDefaults)\n optionsWithDefaults.timeout = Math.min(\n optionsWithDefaults.timeout * 2,\n optionsWithDefaults.maxTimeout,\n )\n }\n\n retries++\n } while (retries <= optionsWithDefaults.retriesAllowed)\n\n return result ?? { error: new Error('No transaction executed') }\n}) as {\n <T, P extends PrismaClient>(\n prisma: P,\n fn: PrismaTransactionFn<T, P>,\n options?: PrismaTransactionOptions,\n ): Promise<Either<unknown, T>>\n <T extends Prisma.PrismaPromise<unknown>[], P extends PrismaClient>(\n prisma: P,\n args: [...T],\n options?: PrismaTransactionBasicOptions,\n ): Promise<Either<unknown, runtime.Types.Utils.UnwrapTuple<T>>>\n}\n\nconst executeTransactionTry = async <T, P extends PrismaClient>(\n prisma: P,\n arg: PrismaTransactionFn<T, P> | Prisma.PrismaPromise<unknown>[],\n options?: PrismaTransactionOptions,\n): Promise<PrismaTransactionReturnType<T>> => {\n try {\n return {\n // @ts-ignore\n result: await prisma.$transaction<T>(arg, options),\n }\n } catch (error) {\n return { error }\n }\n}\n\nconst calculateRetryDelay = (\n retries: number,\n baseRetryDelayMs: number,\n maxDelayMs: number,\n): number => {\n // exponential backoff -> 2^(retry-1) * baseRetryDelayMs\n const expDelay = Math.pow(2, retries - 1) * baseRetryDelayMs\n return Math.min(expDelay, maxDelayMs)\n}\n\ntype isRetryAllowedResult = boolean | 'increase-timeout'\n\nconst isRetryAllowed = <T>(\n result: PrismaTransactionReturnType<T>,\n dbDriver: DbDriver,\n): isRetryAllowedResult => {\n if (isPrismaClientKnownRequestError(result.error)) {\n const error = result.error\n if (error.code === PRISMA_SERIALIZATION_ERROR) return true\n if (dbDriver === 'CockroachDb' && isCockroachDBRetryTransaction(error)) return true\n if (isPrismaTransactionClosedError(error)) return 'increase-timeout'\n }\n\n return false\n}\n"],"names":["DEFAULT_OPTIONS","prismaTransaction","prisma","arg","options","optionsWithDefaults","result","retries","setTimeout","calculateRetryDelay","executeTransactionTry","retryAllowed","isRetryAllowed","deepClone","error","baseRetryDelayMs","maxDelayMs","expDelay","dbDriver","isPrismaClientKnownRequestError","PRISMA_SERIALIZATION_ERROR","isCockroachDBRetryTransaction","isPrismaTransactionClosedError"],"mappings":";;;;AAqBA,MAAMA,IAAkB;AAAA,EACtB,gBAAgB;AAAA;AAAA,EAChB,UAAU;AAAA,EACV,kBAAkB;AAAA,EAClB,iBAAiB;AAAA;AAAA,EACjB,SAAS;AAAA;AAAA,EACT,YAAY;AAAA;AACd,GAWaC,IAAqB,OAChCC,GACAC,GACAC,MAC4C;AAC5C,MAAIC,IAAsB,EAAE,GAAGL,GAAiB,GAAGI,EAAQ,GACvDE,GAEAC,IAAU;AACX,KAAA;AAYD,QAXIA,IAAU,KACN,MAAAC;AAAA,MACJC;AAAA,QACEF;AAAA,QACAF,EAAoB;AAAA,QACpBA,EAAoB;AAAA,MACtB;AAAA,IAAA,GAIJC,IAAS,MAAMI,EAAsBR,GAAQC,GAAKE,CAAmB,GACjEC,EAAO,OAAQ;AAEnB,UAAMK,IAAeC,EAAeN,GAAQD,EAAoB,QAAQ;AACxE,QAAI,CAACM,EAAc;AAEnB,IAAIA,MAAiB,uBACnBN,IAAsBQ,EAAUR,CAAmB,GACnDA,EAAoB,UAAU,KAAK;AAAA,MACjCA,EAAoB,UAAU;AAAA,MAC9BA,EAAoB;AAAA,IAAA,IAIxBE;AAAA,EAAA,SACOA,KAAWF,EAAoB;AAExC,SAAOC,KAAU,EAAE,OAAO,IAAI,MAAM,yBAAyB,EAAE;AACjE,GAaMI,IAAwB,OAC5BR,GACAC,GACAC,MAC4C;AACxC,MAAA;AACK,WAAA;AAAA;AAAA,MAEL,QAAQ,MAAMF,EAAO,aAAgBC,GAAKC,CAAO;AAAA,IAAA;AAAA,WAE5CU,GAAO;AACd,WAAO,EAAE,OAAAA,EAAM;AAAA,EACjB;AACF,GAEML,IAAsB,CAC1BF,GACAQ,GACAC,MACW;AAEX,QAAMC,IAAW,KAAK,IAAI,GAAGV,IAAU,CAAC,IAAIQ;AACrC,SAAA,KAAK,IAAIE,GAAUD,CAAU;AACtC,GAIMJ,IAAiB,CACrBN,GACAY,MACyB;AACrB,MAAAC,EAAgCb,EAAO,KAAK,GAAG;AACjD,UAAMQ,IAAQR,EAAO;AAErB,QADIQ,EAAM,SAASM,KACfF,MAAa,iBAAiBG,EAA8BP,CAAK,EAAU,QAAA;AAC3E,QAAAQ,EAA+BR,CAAK,EAAU,QAAA;AAAA,EACpD;AAEO,SAAA;AACT;"}
1
+ {"version":3,"file":"prismaTransaction.js","sources":["../src/prismaTransaction.ts"],"sourcesContent":["import { setTimeout } from 'node:timers/promises'\n\nimport type { Either } from '@lokalise/node-core'\nimport { deepClone } from '@lokalise/node-core'\nimport type { Prisma, PrismaClient } from '@prisma/client'\nimport type * as runtime from '@prisma/client/runtime/library'\n\nimport { isCockroachDBRetryTransaction } from './errors/cockroachdbError'\nimport {\n PRISMA_SERIALIZATION_ERROR,\n PRISMA_SERVER_CLOSED_CONNECTION_ERROR,\n isPrismaClientKnownRequestError,\n isPrismaTransactionClosedError,\n} from './errors/prismaError'\nimport type {\n DbDriver,\n PrismaTransactionBasicOptions,\n PrismaTransactionFn,\n PrismaTransactionOptions,\n PrismaTransactionReturnType,\n} from './types'\n\nconst DEFAULT_OPTIONS = {\n retriesAllowed: 2, // first try + 2 retries = 3 tries\n DbDriver: 'CockroachDb',\n baseRetryDelayMs: 100,\n maxRetryDelayMs: 30000, // 30s\n timeout: 5000, // 5s\n maxTimeout: 30000, // 30s\n} satisfies Partial<PrismaTransactionOptions>\n\n/**\n * Perform a Prisma DB transaction with automatic retries if needed.\n *\n * @template T | T extends Prisma.PrismaPromise<unknown>[]\n * @param {PrismaClient} prisma\n * @param {PrismaTransactionFn<T> | Prisma.PrismaPromise<unknown>[]} arg\t operation to perform into the transaction\n * @param {PrismaTransactionOptions | PrismaTransactionBasicOptions} options transaction configuration\n * @return {Promise<PrismaTransactionReturnType<T>>}\n */\nexport const prismaTransaction = (async <T, P extends PrismaClient>(\n prisma: P,\n arg: PrismaTransactionFn<T, P> | Prisma.PrismaPromise<unknown>[],\n options?: PrismaTransactionOptions | PrismaTransactionBasicOptions,\n): Promise<PrismaTransactionReturnType<T>> => {\n let optionsWithDefaults = { ...DEFAULT_OPTIONS, ...options }\n let result: PrismaTransactionReturnType<T> | undefined = undefined\n\n let retries = 0\n do {\n if (retries > 0) {\n await setTimeout(\n calculateRetryDelay(\n retries,\n optionsWithDefaults.baseRetryDelayMs,\n optionsWithDefaults.maxRetryDelayMs,\n ),\n )\n }\n\n result = await executeTransactionTry(prisma, arg, optionsWithDefaults)\n if (result.result) break\n\n const retryAllowed = isRetryAllowed(result, optionsWithDefaults.DbDriver)\n if (!retryAllowed) break\n\n if (retryAllowed === 'increase-timeout') {\n optionsWithDefaults = deepClone(optionsWithDefaults)\n optionsWithDefaults.timeout = Math.min(\n optionsWithDefaults.timeout * 2,\n optionsWithDefaults.maxTimeout,\n )\n }\n\n retries++\n } while (retries <= optionsWithDefaults.retriesAllowed)\n\n return result ?? { error: new Error('No transaction executed') }\n}) as {\n <T, P extends PrismaClient>(\n prisma: P,\n fn: PrismaTransactionFn<T, P>,\n options?: PrismaTransactionOptions,\n ): Promise<Either<unknown, T>>\n <T extends Prisma.PrismaPromise<unknown>[], P extends PrismaClient>(\n prisma: P,\n args: [...T],\n options?: PrismaTransactionBasicOptions,\n ): Promise<Either<unknown, runtime.Types.Utils.UnwrapTuple<T>>>\n}\n\nconst executeTransactionTry = async <T, P extends PrismaClient>(\n prisma: P,\n arg: PrismaTransactionFn<T, P> | Prisma.PrismaPromise<unknown>[],\n options?: PrismaTransactionOptions,\n): Promise<PrismaTransactionReturnType<T>> => {\n try {\n return {\n // @ts-ignore\n result: await prisma.$transaction<T>(arg, options),\n }\n } catch (error) {\n return { error }\n }\n}\n\nconst calculateRetryDelay = (\n retries: number,\n baseRetryDelayMs: number,\n maxDelayMs: number,\n): number => {\n // exponential backoff -> 2^(retry-1) * baseRetryDelayMs\n const expDelay = Math.pow(2, retries - 1) * baseRetryDelayMs\n return Math.min(expDelay, maxDelayMs)\n}\n\nconst PrismaCodesToRetry = [PRISMA_SERIALIZATION_ERROR, PRISMA_SERVER_CLOSED_CONNECTION_ERROR]\ntype isRetryAllowedResult = boolean | 'increase-timeout'\n\nconst isRetryAllowed = <T>(\n result: PrismaTransactionReturnType<T>,\n dbDriver: DbDriver,\n): isRetryAllowedResult => {\n if (isPrismaClientKnownRequestError(result.error)) {\n const error = result.error\n // retry if the error code is in the list of codes to retry\n if (PrismaCodesToRetry.includes(error.code)) return true\n // also retry if the error is a CockroachDB retry transaction error\n if (dbDriver === 'CockroachDb' && isCockroachDBRetryTransaction(error)) return true\n // In case transaction is closed (timeout), retry increasing the timeout\n if (isPrismaTransactionClosedError(error)) return 'increase-timeout'\n }\n\n return false\n}\n"],"names":["DEFAULT_OPTIONS","prismaTransaction","prisma","arg","options","optionsWithDefaults","result","retries","setTimeout","calculateRetryDelay","executeTransactionTry","retryAllowed","isRetryAllowed","deepClone","error","baseRetryDelayMs","maxDelayMs","expDelay","PrismaCodesToRetry","PRISMA_SERIALIZATION_ERROR","PRISMA_SERVER_CLOSED_CONNECTION_ERROR","dbDriver","isPrismaClientKnownRequestError","isCockroachDBRetryTransaction","isPrismaTransactionClosedError"],"mappings":";;;;AAsBA,MAAMA,IAAkB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,GAAG;AACjD,UAAMQ,IAAQR,EAAO;AAIrB,QAFIY,EAAmB,SAASJ,EAAM,IAAI,KAEtCO,MAAa,iBAAiBE,EAA8BT,CAAK,EAAU,QAAA;AAE3E,QAAAU,EAA+BV,CAAK,EAAU,QAAA;AAAA,EACpD;AAEO,SAAA;AACT;"}
package/package.json CHANGED
@@ -1,13 +1,9 @@
1
1
  {
2
2
  "name": "@lokalise/prisma-utils",
3
- "version": "1.4.0",
3
+ "version": "1.5.0",
4
4
  "type": "module",
5
5
  "license": "Apache-2.0",
6
- "files": [
7
- "dist",
8
- "README.md",
9
- "LICENSE.md"
10
- ],
6
+ "files": ["dist", "README.md", "LICENSE.md"],
11
7
  "main": "./dist/index.cjs",
12
8
  "module": "./dist/index.js",
13
9
  "types": "./dist/index.d.ts",
@@ -39,7 +35,8 @@
39
35
  "test:ci": "npm run test -- --coverage",
40
36
  "test:ci:teardown": "docker compose down",
41
37
  "prepublishOnly": "npm run build",
42
- "package-version": "echo $npm_package_version"
38
+ "package-version": "echo $npm_package_version",
39
+ "postversion": "biome check --write package.json"
43
40
  },
44
41
  "dependencies": {
45
42
  "@lokalise/node-core": "^11.2.0"
@@ -53,13 +50,13 @@
53
50
  "@lokalise/biome-config": "*",
54
51
  "@lokalise/package-vite-config": "*",
55
52
  "@prisma/client": "^5.14.0",
56
- "@vitest/coverage-v8": "^1.6.0",
53
+ "@vitest/coverage-v8": "^2.0.4",
57
54
  "cross-env": "^7.0.3",
58
55
  "dotenv-cli": "^7.4.1",
59
56
  "prisma": "^5.14.0",
60
57
  "rimraf": "^5.0.7",
61
- "typescript": "5.5.3",
62
- "vite": "^5.3.3",
63
- "vitest": "^1.6.0"
58
+ "typescript": "5.5.4",
59
+ "vite": "5.3.5",
60
+ "vitest": "^2.0.4"
64
61
  }
65
62
  }