@stackframe/stack-shared 2.8.10 → 2.8.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (154) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/dist/config/{schema.d.cts → schema.d.mts} +38 -33
  3. package/dist/config/schema.d.ts +37 -32
  4. package/dist/config/schema.js +5 -3
  5. package/dist/config/schema.js.map +1 -1
  6. package/dist/{crud.d.cts → crud.d.mts} +1 -1
  7. package/dist/esm/config/schema.js +5 -3
  8. package/dist/esm/config/schema.js.map +1 -1
  9. package/dist/esm/interface/clientInterface.js +8 -6
  10. package/dist/esm/interface/clientInterface.js.map +1 -1
  11. package/dist/esm/interface/crud/project-api-keys.js +20 -15
  12. package/dist/esm/interface/crud/project-api-keys.js.map +1 -1
  13. package/dist/esm/interface/crud/projects.js +5 -12
  14. package/dist/esm/interface/crud/projects.js.map +1 -1
  15. package/dist/esm/interface/serverInterface.js +28 -2
  16. package/dist/esm/interface/serverInterface.js.map +1 -1
  17. package/dist/esm/known-errors.js +43 -1
  18. package/dist/esm/known-errors.js.map +1 -1
  19. package/dist/esm/schema-fields.js +2 -0
  20. package/dist/esm/schema-fields.js.map +1 -1
  21. package/dist/esm/utils/errors.js +4 -0
  22. package/dist/esm/utils/errors.js.map +1 -1
  23. package/dist/esm/utils/hashes.js +1 -1
  24. package/dist/esm/utils/hashes.js.map +1 -1
  25. package/dist/esm/utils/objects.js +24 -0
  26. package/dist/esm/utils/objects.js.map +1 -1
  27. package/dist/esm/utils/promises.js +1 -1
  28. package/dist/esm/utils/promises.js.map +1 -1
  29. package/dist/esm/utils/strings.js +1 -0
  30. package/dist/esm/utils/strings.js.map +1 -1
  31. package/dist/helpers/password.d.mts +11 -0
  32. package/dist/helpers/{production-mode.d.cts → production-mode.d.mts} +3 -3
  33. package/dist/hooks/use-async-callback.js +1 -1
  34. package/dist/hooks/{use-async-external-store.d.cts → use-async-external-store.d.mts} +1 -1
  35. package/dist/index.d.mts +30 -0
  36. package/dist/interface/{adminInterface.d.cts → adminInterface.d.mts} +26 -26
  37. package/dist/interface/{clientInterface.d.cts → clientInterface.d.mts} +18 -18
  38. package/dist/interface/clientInterface.js +8 -6
  39. package/dist/interface/clientInterface.js.map +1 -1
  40. package/dist/interface/crud/{contact-channels.d.cts → contact-channels.d.mts} +2 -2
  41. package/dist/interface/crud/{current-user.d.cts → current-user.d.mts} +2 -2
  42. package/dist/interface/crud/{email-templates.d.cts → email-templates.d.mts} +2 -2
  43. package/dist/interface/crud/{emails.d.cts → emails.d.mts} +2 -2
  44. package/dist/interface/crud/emails.js +1 -1
  45. package/dist/interface/crud/{internal-api-keys.d.cts → internal-api-keys.d.mts} +2 -2
  46. package/dist/interface/crud/{oauth.d.cts → oauth.d.mts} +2 -2
  47. package/dist/interface/crud/{project-api-keys.d.cts → project-api-keys.d.mts} +14 -4
  48. package/dist/interface/crud/project-api-keys.d.ts +12 -2
  49. package/dist/interface/crud/project-api-keys.js +20 -15
  50. package/dist/interface/crud/project-api-keys.js.map +1 -1
  51. package/dist/interface/crud/{project-permissions.d.cts → project-permissions.d.mts} +2 -2
  52. package/dist/interface/crud/project-permissions.js +1 -1
  53. package/dist/interface/crud/{projects.d.cts → projects.d.mts} +9 -22
  54. package/dist/interface/crud/projects.d.ts +7 -20
  55. package/dist/interface/crud/projects.js +6 -13
  56. package/dist/interface/crud/projects.js.map +1 -1
  57. package/dist/interface/crud/{sessions.d.cts → sessions.d.mts} +2 -2
  58. package/dist/interface/crud/{svix-token.d.cts → svix-token.d.mts} +2 -2
  59. package/dist/interface/crud/{team-invitation-details.d.cts → team-invitation-details.d.mts} +2 -2
  60. package/dist/interface/crud/team-invitation-details.js +1 -1
  61. package/dist/interface/crud/{team-invitation.d.cts → team-invitation.d.mts} +2 -2
  62. package/dist/interface/crud/team-invitation.js +1 -1
  63. package/dist/interface/crud/{team-member-profiles.d.cts → team-member-profiles.d.mts} +2 -2
  64. package/dist/interface/crud/team-member-profiles.js +1 -1
  65. package/dist/interface/crud/{team-memberships.d.cts → team-memberships.d.mts} +2 -2
  66. package/dist/interface/crud/{team-permissions.d.cts → team-permissions.d.mts} +2 -2
  67. package/dist/interface/crud/team-permissions.js +1 -1
  68. package/dist/interface/crud/{teams.d.cts → teams.d.mts} +2 -2
  69. package/dist/interface/crud/teams.js +1 -1
  70. package/dist/interface/crud/{users.d.cts → users.d.mts} +2 -2
  71. package/dist/interface/crud/users.js +1 -1
  72. package/dist/interface/{serverInterface.d.cts → serverInterface.d.mts} +23 -21
  73. package/dist/interface/serverInterface.d.ts +2 -0
  74. package/dist/interface/serverInterface.js +28 -2
  75. package/dist/interface/serverInterface.js.map +1 -1
  76. package/dist/{known-errors.d.cts → known-errors.d.mts} +14 -3
  77. package/dist/known-errors.d.ts +11 -0
  78. package/dist/known-errors.js +43 -1
  79. package/dist/known-errors.js.map +1 -1
  80. package/dist/{schema-fields.d.cts → schema-fields.d.mts} +2 -1
  81. package/dist/schema-fields.d.ts +2 -1
  82. package/dist/schema-fields.js +4 -1
  83. package/dist/schema-fields.js.map +1 -1
  84. package/dist/sessions.js +1 -1
  85. package/dist/utils/api-keys.js +1 -1
  86. package/dist/utils/{caches.d.cts → caches.d.mts} +2 -2
  87. package/dist/utils/{errors.d.cts → errors.d.mts} +4 -2
  88. package/dist/utils/errors.d.ts +2 -0
  89. package/dist/utils/errors.js +4 -0
  90. package/dist/utils/errors.js.map +1 -1
  91. package/dist/utils/fs.js +2 -2
  92. package/dist/utils/hashes.js +6 -6
  93. package/dist/utils/hashes.js.map +1 -1
  94. package/dist/utils/ips.js +1 -1
  95. package/dist/utils/{json.d.cts → json.d.mts} +1 -1
  96. package/dist/utils/jwt.js +3 -3
  97. package/dist/utils/{objects.d.cts → objects.d.mts} +9 -5
  98. package/dist/utils/objects.d.ts +9 -5
  99. package/dist/utils/objects.js +28 -0
  100. package/dist/utils/objects.js.map +1 -1
  101. package/dist/utils/{promises.d.cts → promises.d.mts} +1 -1
  102. package/dist/utils/promises.js +1 -1
  103. package/dist/utils/promises.js.map +1 -1
  104. package/dist/utils/react.js +1 -1
  105. package/dist/utils/{stores.d.cts → stores.d.mts} +3 -3
  106. package/dist/utils/strings.js +1 -0
  107. package/dist/utils/strings.js.map +1 -1
  108. package/package.json +9 -6
  109. package/dist/helpers/password.d.cts +0 -11
  110. package/dist/index.d.cts +0 -30
  111. /package/dist/config/{format.d.cts → format.d.mts} +0 -0
  112. /package/dist/{global.d.d.cts → global.d.d.mts} +0 -0
  113. /package/dist/hooks/{use-async-callback.d.cts → use-async-callback.d.mts} +0 -0
  114. /package/dist/hooks/{use-hash.d.cts → use-hash.d.mts} +0 -0
  115. /package/dist/hooks/{use-strict-memo.d.cts → use-strict-memo.d.mts} +0 -0
  116. /package/dist/interface/{webhooks.d.cts → webhooks.d.mts} +0 -0
  117. /package/dist/{sessions.d.cts → sessions.d.mts} +0 -0
  118. /package/dist/utils/{api-keys.d.cts → api-keys.d.mts} +0 -0
  119. /package/dist/utils/{arrays.d.cts → arrays.d.mts} +0 -0
  120. /package/dist/utils/{base64.d.cts → base64.d.mts} +0 -0
  121. /package/dist/utils/{booleans.d.cts → booleans.d.mts} +0 -0
  122. /package/dist/utils/{browser-compat.d.cts → browser-compat.d.mts} +0 -0
  123. /package/dist/utils/{bytes.d.cts → bytes.d.mts} +0 -0
  124. /package/dist/utils/{compile-time.d.cts → compile-time.d.mts} +0 -0
  125. /package/dist/utils/{crypto.d.cts → crypto.d.mts} +0 -0
  126. /package/dist/utils/{dates.d.cts → dates.d.mts} +0 -0
  127. /package/dist/utils/{dom.d.cts → dom.d.mts} +0 -0
  128. /package/dist/utils/{env.d.cts → env.d.mts} +0 -0
  129. /package/dist/utils/{fs.d.cts → fs.d.mts} +0 -0
  130. /package/dist/utils/{functions.d.cts → functions.d.mts} +0 -0
  131. /package/dist/utils/{geo.d.cts → geo.d.mts} +0 -0
  132. /package/dist/utils/{globals.d.cts → globals.d.mts} +0 -0
  133. /package/dist/utils/{hashes.d.cts → hashes.d.mts} +0 -0
  134. /package/dist/utils/{html.d.cts → html.d.mts} +0 -0
  135. /package/dist/utils/{http.d.cts → http.d.mts} +0 -0
  136. /package/dist/utils/{ips.d.cts → ips.d.mts} +0 -0
  137. /package/dist/utils/{jwt.d.cts → jwt.d.mts} +0 -0
  138. /package/dist/utils/{locks.d.cts → locks.d.mts} +0 -0
  139. /package/dist/utils/{maps.d.cts → maps.d.mts} +0 -0
  140. /package/dist/utils/{math.d.cts → math.d.mts} +0 -0
  141. /package/dist/utils/{node-http.d.cts → node-http.d.mts} +0 -0
  142. /package/dist/utils/{numbers.d.cts → numbers.d.mts} +0 -0
  143. /package/dist/utils/{oauth.d.cts → oauth.d.mts} +0 -0
  144. /package/dist/utils/{passkey.d.cts → passkey.d.mts} +0 -0
  145. /package/dist/utils/{proxies.d.cts → proxies.d.mts} +0 -0
  146. /package/dist/utils/{react.d.cts → react.d.mts} +0 -0
  147. /package/dist/utils/{results.d.cts → results.d.mts} +0 -0
  148. /package/dist/utils/{sentry.d.cts → sentry.d.mts} +0 -0
  149. /package/dist/utils/{strings.d.cts → strings.d.mts} +0 -0
  150. /package/dist/utils/{strings.nicify.test.d.cts → strings.nicify.test.d.mts} +0 -0
  151. /package/dist/utils/{types.d.cts → types.d.mts} +0 -0
  152. /package/dist/utils/{unicode.d.cts → unicode.d.mts} +0 -0
  153. /package/dist/utils/{urls.d.cts → urls.d.mts} +0 -0
  154. /package/dist/utils/{uuids.d.cts → uuids.d.mts} +0 -0
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/utils/errors.tsx"],"sourcesContent":["import { globalVar } from \"./globals\";\nimport { Json } from \"./json\";\nimport { pick } from \"./objects\";\nimport { nicify } from \"./strings\";\n\n\nexport function throwErr(errorMessage: string, extraData?: any): never;\nexport function throwErr(error: Error): never;\nexport function throwErr(...args: StatusErrorConstructorParameters): never;\nexport function throwErr(...args: any[]): never {\n if (typeof args[0] === \"string\") {\n throw new StackAssertionError(args[0], args[1]);\n } else if (args[0] instanceof Error) {\n throw args[0];\n } else {\n // @ts-expect-error\n throw new StatusError(...args);\n }\n}\n\nfunction removeStacktraceNameLine(stack: string): string {\n // some browsers (eg. Chrome) prepend the stack with an extra line with the error name\n const addsNameLine = new Error().stack?.startsWith(\"Error\\n\");\n return stack.split(\"\\n\").slice(addsNameLine ? 1 : 0).join(\"\\n\");\n}\n\n\n/**\n * Concatenates the (original) stacktraces of the given errors onto the first.\n *\n * Useful when you invoke an async function to receive a promise without awaiting it immediately. Browsers are smart\n * enough to keep track of the call stack in async function calls when you invoke `.then` within the same async tick,\n * but if you don't, the stacktrace will be lost.\n *\n * Here's an example of the unwanted behavior:\n *\n * ```tsx\n * async function log() {\n * await wait(0); // simulate an put the task on the event loop\n * console.log(new Error().stack);\n * }\n *\n * async function main() {\n * await log(); // good; prints both \"log\" and \"main\" on the stacktrace\n * log(); // bad; prints only \"log\" on the stacktrace\n * }\n * ```\n */\nexport function concatStacktraces(first: Error, ...errors: Error[]): void {\n // some browsers (eg. Firefox) add an extra empty line at the end\n const addsEmptyLineAtEnd = first.stack?.endsWith(\"\\n\");\n\n\n // Add a reference to this function itself so that we know that stacktraces were concatenated\n // If you are coming here from a stacktrace, please know that the two parts before and after this line are different\n // stacktraces that were concatenated with concatStacktraces\n const separator = removeStacktraceNameLine(new Error().stack ?? \"\").split(\"\\n\")[0];\n\n\n for (const error of errors) {\n const toAppend = removeStacktraceNameLine(error.stack ?? \"\");\n first.stack += (addsEmptyLineAtEnd ? \"\" : \"\\n\") + separator + \"\\n\" + toAppend;\n }\n}\n\n\nexport class StackAssertionError extends Error {\n constructor(message: string, public readonly extraData?: Record<string, any> & ErrorOptions) {\n const disclaimer = `\\n\\nThis is likely an error in Stack. Please make sure you are running the newest version and report it.`;\n super(`${message}${message.endsWith(disclaimer) ? \"\" : disclaimer}`, pick(extraData ?? {}, [\"cause\"]));\n\n Object.defineProperty(this, \"customCaptureExtraArgs\", {\n get() {\n return [this.extraData];\n },\n enumerable: false,\n });\n }\n}\nStackAssertionError.prototype.name = \"StackAssertionError\";\n\n\nexport function errorToNiceString(error: unknown): string {\n if (!(error instanceof Error)) return `${typeof error}<${nicify(error)}>`;\n return nicify(error, { maxDepth: 8 });\n}\n\n\nconst errorSinks = new Set<(location: string, error: unknown, ...extraArgs: unknown[]) => void>();\nexport function registerErrorSink(sink: (location: string, error: unknown) => void): void {\n if (errorSinks.has(sink)) {\n return;\n }\n errorSinks.add(sink);\n}\nregisterErrorSink((location, error, ...extraArgs) => {\n console.error(\n `\\x1b[41mCaptured error in ${location}:`,\n // HACK: Log a nicified version of the error to get around buggy Next.js pretty-printing\n // https://www.reddit.com/r/nextjs/comments/1gkxdqe/comment/m19kxgn/?utm_source=share&utm_medium=web3x&utm_name=web3xcss&utm_term=1&utm_content=share_button\n errorToNiceString(error),\n ...extraArgs,\n \"\\x1b[0m\",\n );\n});\nregisterErrorSink((location, error, ...extraArgs) => {\n globalVar.stackCapturedErrors = globalVar.stackCapturedErrors ?? [];\n globalVar.stackCapturedErrors.push({ location, error, extraArgs });\n});\n\nexport function captureError(location: string, error: unknown): void {\n for (const sink of errorSinks) {\n sink(\n location,\n error,\n ...error && (typeof error === 'object' || typeof error === 'function') && \"customCaptureExtraArgs\" in error && Array.isArray(error.customCaptureExtraArgs) ? (error.customCaptureExtraArgs as any[]) : [],\n );\n }\n}\n\n\ntype Status = {\n statusCode: number,\n message: string,\n};\n\ntype StatusErrorConstructorParameters =\n| [\n status: Status,\n message?: string\n]\n| [\n statusCode: number | Status,\n message: string,\n];\n\nexport class StatusError extends Error {\n public name = \"StatusError\";\n public readonly statusCode: number;\n\n public static BadRequest = { statusCode: 400, message: \"Bad Request\" };\n public static Unauthorized = { statusCode: 401, message: \"Unauthorized\" };\n public static PaymentRequired = { statusCode: 402, message: \"Payment Required\" };\n public static Forbidden = { statusCode: 403, message: \"Forbidden\" };\n public static NotFound = { statusCode: 404, message: \"Not Found\" };\n public static MethodNotAllowed = { statusCode: 405, message: \"Method Not Allowed\" };\n public static NotAcceptable = { statusCode: 406, message: \"Not Acceptable\" };\n public static ProxyAuthenticationRequired = { statusCode: 407, message: \"Proxy Authentication Required\" };\n public static RequestTimeout = { statusCode: 408, message: \"Request Timeout\" };\n public static Conflict = { statusCode: 409, message: \"Conflict\" };\n public static Gone = { statusCode: 410, message: \"Gone\" };\n public static LengthRequired = { statusCode: 411, message: \"Length Required\" };\n public static PreconditionFailed = { statusCode: 412, message: \"Precondition Failed\" };\n public static PayloadTooLarge = { statusCode: 413, message: \"Payload Too Large\" };\n public static URITooLong = { statusCode: 414, message: \"URI Too Long\" };\n public static UnsupportedMediaType = { statusCode: 415, message: \"Unsupported Media Type\" };\n public static RangeNotSatisfiable = { statusCode: 416, message: \"Range Not Satisfiable\" };\n public static ExpectationFailed = { statusCode: 417, message: \"Expectation Failed\" };\n public static ImATeapot = { statusCode: 418, message: \"I'm a teapot\" };\n public static MisdirectedRequest = { statusCode: 421, message: \"Misdirected Request\" };\n public static UnprocessableEntity = { statusCode: 422, message: \"Unprocessable Entity\" };\n public static Locked = { statusCode: 423, message: \"Locked\" };\n public static FailedDependency = { statusCode: 424, message: \"Failed Dependency\" };\n public static TooEarly = { statusCode: 425, message: \"Too Early\" };\n public static UpgradeRequired = { statusCode: 426, message: \"Upgrade Required\" };\n public static PreconditionRequired = { statusCode: 428, message: \"Precondition Required\" };\n public static TooManyRequests = { statusCode: 429, message: \"Too Many Requests\" };\n public static RequestHeaderFieldsTooLarge = { statusCode: 431, message: \"Request Header Fields Too Large\" };\n public static UnavailableForLegalReasons = { statusCode: 451, message: \"Unavailable For Legal Reasons\" };\n\n public static InternalServerError = { statusCode: 500, message: \"Internal Server Error\" };\n public static NotImplemented = { statusCode: 501, message: \"Not Implemented\" };\n public static BadGateway = { statusCode: 502, message: \"Bad Gateway\" };\n public static ServiceUnavailable = { statusCode: 503, message: \"Service Unavailable\" };\n public static GatewayTimeout = { statusCode: 504, message: \"Gateway Timeout\" };\n public static HTTPVersionNotSupported = { statusCode: 505, message: \"HTTP Version Not Supported\" };\n public static VariantAlsoNegotiates = { statusCode: 506, message: \"Variant Also Negotiates\" };\n public static InsufficientStorage = { statusCode: 507, message: \"Insufficient Storage\" };\n public static LoopDetected = { statusCode: 508, message: \"Loop Detected\" };\n public static NotExtended = { statusCode: 510, message: \"Not Extended\" };\n public static NetworkAuthenticationRequired = { statusCode: 511, message: \"Network Authentication Required\" };\n\n\n constructor(...args: StatusErrorConstructorParameters);\n constructor(\n status: number | Status,\n message?: string,\n ) {\n if (typeof status === \"object\") {\n message ??= status.message;\n status = status.statusCode;\n }\n super(message);\n this.statusCode = status;\n if (!message) {\n throw new StackAssertionError(\"StatusError always requires a message unless a Status object is passed\", { cause: this });\n }\n }\n\n public isClientError() {\n return this.statusCode >= 400 && this.statusCode < 500;\n }\n\n public isServerError() {\n return !this.isClientError();\n }\n\n public getStatusCode(): number {\n return this.statusCode;\n }\n\n public getBody(): Uint8Array {\n return new TextEncoder().encode(this.message);\n }\n\n public getHeaders(): Record<string, string[]> {\n return {\n \"Content-Type\": [\"text/plain; charset=utf-8\"],\n };\n }\n\n public toDescriptiveJson(): Json {\n return {\n status_code: this.getStatusCode(),\n message: this.message,\n headers: this.getHeaders(),\n };\n }\n\n /**\n * @deprecated this is not a good way to make status errors human-readable, use toDescriptiveJson instead\n */\n public toHttpJson(): Json {\n return {\n status_code: this.statusCode,\n body: this.message,\n headers: this.getHeaders(),\n };\n }\n}\nStatusError.prototype.name = \"StatusError\";\n"],"mappings":";AAAA,SAAS,iBAAiB;AAE1B,SAAS,YAAY;AACrB,SAAS,cAAc;AAMhB,SAAS,YAAY,MAAoB;AAC9C,MAAI,OAAO,KAAK,CAAC,MAAM,UAAU;AAC/B,UAAM,IAAI,oBAAoB,KAAK,CAAC,GAAG,KAAK,CAAC,CAAC;AAAA,EAChD,WAAW,KAAK,CAAC,aAAa,OAAO;AACnC,UAAM,KAAK,CAAC;AAAA,EACd,OAAO;AAEL,UAAM,IAAI,YA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{"version":3,"sources":["../../../src/utils/errors.tsx"],"sourcesContent":["import { globalVar } from \"./globals\";\nimport { Json } from \"./json\";\nimport { pick } from \"./objects\";\nimport { nicify } from \"./strings\";\n\n\nexport function throwErr(errorMessage: string, extraData?: any): never;\nexport function throwErr(error: Error): never;\nexport function throwErr(...args: StatusErrorConstructorParameters): never;\nexport function throwErr(...args: any[]): never {\n if (typeof args[0] === \"string\") {\n throw new StackAssertionError(args[0], args[1]);\n } else if (args[0] instanceof Error) {\n throw args[0];\n } else {\n // @ts-expect-error\n throw new StatusError(...args);\n }\n}\n\nfunction removeStacktraceNameLine(stack: string): string {\n // some browsers (eg. Chrome) prepend the stack with an extra line with the error name\n const addsNameLine = new Error().stack?.startsWith(\"Error\\n\");\n return stack.split(\"\\n\").slice(addsNameLine ? 1 : 0).join(\"\\n\");\n}\n\n\n/**\n * Concatenates the (original) stacktraces of the given errors onto the first.\n *\n * Useful when you invoke an async function to receive a promise without awaiting it immediately. Browsers are smart\n * enough to keep track of the call stack in async function calls when you invoke `.then` within the same async tick,\n * but if you don't, the stacktrace will be lost.\n *\n * Here's an example of the unwanted behavior:\n *\n * ```tsx\n * async function log() {\n * await wait(0); // simulate an put the task on the event loop\n * console.log(new Error().stack);\n * }\n *\n * async function main() {\n * await log(); // good; prints both \"log\" and \"main\" on the stacktrace\n * log(); // bad; prints only \"log\" on the stacktrace\n * }\n * ```\n */\nexport function concatStacktraces(first: Error, ...errors: Error[]): void {\n // some browsers (eg. Firefox) add an extra empty line at the end\n const addsEmptyLineAtEnd = first.stack?.endsWith(\"\\n\");\n\n\n // Add a reference to this function itself so that we know that stacktraces were concatenated\n // If you are coming here from a stacktrace, please know that the two parts before and after this line are different\n // stacktraces that were concatenated with concatStacktraces\n const separator = removeStacktraceNameLine(new Error().stack ?? \"\").split(\"\\n\")[0];\n\n\n for (const error of errors) {\n const toAppend = removeStacktraceNameLine(error.stack ?? \"\");\n first.stack += (addsEmptyLineAtEnd ? \"\" : \"\\n\") + separator + \"\\n\" + toAppend;\n }\n}\n\n\nexport class StackAssertionError extends Error {\n constructor(message: string, public readonly extraData?: Record<string, any> & ErrorOptions) {\n const disclaimer = `\\n\\nThis is likely an error in Stack. Please make sure you are running the newest version and report it.`;\n super(`${message}${message.endsWith(disclaimer) ? \"\" : disclaimer}`, pick(extraData ?? {}, [\"cause\"]));\n\n Object.defineProperty(this, \"customCaptureExtraArgs\", {\n get() {\n return [this.extraData];\n },\n enumerable: false,\n });\n }\n}\nStackAssertionError.prototype.name = \"StackAssertionError\";\n\n\nexport function errorToNiceString(error: unknown): string {\n if (!(error instanceof Error)) return `${typeof error}<${nicify(error)}>`;\n return nicify(error, { maxDepth: 8 });\n}\n\n\nconst errorSinks = new Set<(location: string, error: unknown, ...extraArgs: unknown[]) => void>();\nexport function registerErrorSink(sink: (location: string, error: unknown) => void): void {\n if (errorSinks.has(sink)) {\n return;\n }\n errorSinks.add(sink);\n}\nregisterErrorSink((location, error, ...extraArgs) => {\n console.error(\n `\\x1b[41mCaptured error in ${location}:`,\n // HACK: Log a nicified version of the error to get around buggy Next.js pretty-printing\n // https://www.reddit.com/r/nextjs/comments/1gkxdqe/comment/m19kxgn/?utm_source=share&utm_medium=web3x&utm_name=web3xcss&utm_term=1&utm_content=share_button\n errorToNiceString(error),\n ...extraArgs,\n \"\\x1b[0m\",\n );\n});\nregisterErrorSink((location, error, ...extraArgs) => {\n globalVar.stackCapturedErrors = globalVar.stackCapturedErrors ?? [];\n globalVar.stackCapturedErrors.push({ location, error, extraArgs });\n});\n\nexport function captureError(location: string, error: unknown): void {\n for (const sink of errorSinks) {\n sink(\n location,\n error,\n ...error && (typeof error === 'object' || typeof error === 'function') && \"customCaptureExtraArgs\" in error && Array.isArray(error.customCaptureExtraArgs) ? (error.customCaptureExtraArgs as any[]) : [],\n );\n }\n}\n\n\ntype Status = {\n statusCode: number,\n message: string,\n};\n\ntype StatusErrorConstructorParameters =\n| [\n status: Status,\n message?: string\n]\n| [\n statusCode: number | Status,\n message: string,\n];\n\nexport class StatusError extends Error {\n private readonly __stackStatusErrorBrand = \"stack-status-error-brand-sentinel\" as const;\n public name = \"StatusError\";\n public readonly statusCode: number;\n\n public static BadRequest = { statusCode: 400, message: \"Bad Request\" };\n public static Unauthorized = { statusCode: 401, message: \"Unauthorized\" };\n public static PaymentRequired = { statusCode: 402, message: \"Payment Required\" };\n public static Forbidden = { statusCode: 403, message: \"Forbidden\" };\n public static NotFound = { statusCode: 404, message: \"Not Found\" };\n public static MethodNotAllowed = { statusCode: 405, message: \"Method Not Allowed\" };\n public static NotAcceptable = { statusCode: 406, message: \"Not Acceptable\" };\n public static ProxyAuthenticationRequired = { statusCode: 407, message: \"Proxy Authentication Required\" };\n public static RequestTimeout = { statusCode: 408, message: \"Request Timeout\" };\n public static Conflict = { statusCode: 409, message: \"Conflict\" };\n public static Gone = { statusCode: 410, message: \"Gone\" };\n public static LengthRequired = { statusCode: 411, message: \"Length Required\" };\n public static PreconditionFailed = { statusCode: 412, message: \"Precondition Failed\" };\n public static PayloadTooLarge = { statusCode: 413, message: \"Payload Too Large\" };\n public static URITooLong = { statusCode: 414, message: \"URI Too Long\" };\n public static UnsupportedMediaType = { statusCode: 415, message: \"Unsupported Media Type\" };\n public static RangeNotSatisfiable = { statusCode: 416, message: \"Range Not Satisfiable\" };\n public static ExpectationFailed = { statusCode: 417, message: \"Expectation Failed\" };\n public static ImATeapot = { statusCode: 418, message: \"I'm a teapot\" };\n public static MisdirectedRequest = { statusCode: 421, message: \"Misdirected Request\" };\n public static UnprocessableEntity = { statusCode: 422, message: \"Unprocessable Entity\" };\n public static Locked = { statusCode: 423, message: \"Locked\" };\n public static FailedDependency = { statusCode: 424, message: \"Failed Dependency\" };\n public static TooEarly = { statusCode: 425, message: \"Too Early\" };\n public static UpgradeRequired = { statusCode: 426, message: \"Upgrade Required\" };\n public static PreconditionRequired = { statusCode: 428, message: \"Precondition Required\" };\n public static TooManyRequests = { statusCode: 429, message: \"Too Many Requests\" };\n public static RequestHeaderFieldsTooLarge = { statusCode: 431, message: \"Request Header Fields Too Large\" };\n public static UnavailableForLegalReasons = { statusCode: 451, message: \"Unavailable For Legal Reasons\" };\n\n public static InternalServerError = { statusCode: 500, message: \"Internal Server Error\" };\n public static NotImplemented = { statusCode: 501, message: \"Not Implemented\" };\n public static BadGateway = { statusCode: 502, message: \"Bad Gateway\" };\n public static ServiceUnavailable = { statusCode: 503, message: \"Service Unavailable\" };\n public static GatewayTimeout = { statusCode: 504, message: \"Gateway Timeout\" };\n public static HTTPVersionNotSupported = { statusCode: 505, message: \"HTTP Version Not Supported\" };\n public static VariantAlsoNegotiates = { statusCode: 506, message: \"Variant Also Negotiates\" };\n public static InsufficientStorage = { statusCode: 507, message: \"Insufficient Storage\" };\n public static LoopDetected = { statusCode: 508, message: \"Loop Detected\" };\n public static NotExtended = { statusCode: 510, message: \"Not Extended\" };\n public static NetworkAuthenticationRequired = { statusCode: 511, message: \"Network Authentication Required\" };\n\n\n constructor(...args: StatusErrorConstructorParameters);\n constructor(\n status: number | Status,\n message?: string,\n ) {\n if (typeof status === \"object\") {\n message ??= status.message;\n status = status.statusCode;\n }\n super(message);\n this.statusCode = status;\n if (!message) {\n throw new StackAssertionError(\"StatusError always requires a message unless a Status object is passed\", { cause: this });\n }\n }\n\n public static isStatusError(error: unknown): error is StatusError {\n // like instanceof, but also works for errors thrown in other realms or by different versions of the same package\n return typeof error === \"object\" && error !== null && \"__stackStatusErrorBrand\" in error && error.__stackStatusErrorBrand === \"stack-status-error-brand-sentinel\";\n }\n\n public isClientError() {\n return this.statusCode >= 400 && this.statusCode < 500;\n }\n\n public isServerError() {\n return !this.isClientError();\n }\n\n public getStatusCode(): number {\n return this.statusCode;\n }\n\n public getBody(): Uint8Array {\n return new TextEncoder().encode(this.message);\n }\n\n public getHeaders(): Record<string, string[]> {\n return {\n \"Content-Type\": [\"text/plain; charset=utf-8\"],\n };\n }\n\n public toDescriptiveJson(): Json {\n return {\n status_code: this.getStatusCode(),\n message: this.message,\n headers: this.getHeaders(),\n };\n }\n\n /**\n * @deprecated this is not a good way to make status errors human-readable, use toDescriptiveJson instead\n */\n public toHttpJson(): Json {\n return {\n status_code: this.statusCode,\n body: this.message,\n headers: this.getHeaders(),\n };\n }\n}\nStatusError.prototype.name = \"StatusError\";\n"],"mappings":";AAAA,SAAS,iBAAiB;AAE1B,SAAS,YAAY;AACrB,SAAS,cAAc;AAMhB,SAAS,YAAY,MAAoB;AAC9C,MAAI,OAAO,KAAK,CAAC,MAAM,UAAU;AAC/B,UAAM,IAAI,oBAAoB,KAAK,CAAC,GAAG,KAAK,CAAC,CAAC;AAAA,EAChD,WAAW,KAAK,CAAC,aAAa,OAAO;AACnC,UAAM,KAAK,CAAC;AAAA,EACd,OAAO;AAEL,UAAM,IAAI,YAAY,GAAG,IAAI;AAAA,EAC/B;AACF;AAEA,SAAS,yBAAyB,OAAuB;AAEvD,QAAM,eAAe,IAAI,MAAM,EAAE,OAAO,WAAW,SAAS;AAC5D,SAAO,MAAM,MAAM,IAAI,EAAE,MAAM,eAAe,IAAI,CAAC,EAAE,KAAK,IAAI;AAChE;AAwBO,SAAS,kBAAkB,UAAiB,QAAuB;AAExE,QAAM,qBAAqB,MAAM,OAAO,SAAS,IAAI;AAMrD,QAAM,YAAY,yBAAyB,IAAI,MAAM,EAAE,SAAS,EAAE,EAAE,MAAM,IAAI,EAAE,CAAC;AAGjF,aAAW,SAAS,QAAQ;AAC1B,UAAM,WAAW,yBAAyB,MAAM,SAAS,EAAE;AAC3D,UAAM,UAAU,qBAAqB,KAAK,QAAQ,YAAY,OAAO;AAAA,EACvE;AACF;AAGO,IAAM,sBAAN,cAAkC,MAAM;AAAA,EAC7C,YAAY,SAAiC,WAAgD;AAC3F,UAAM,aAAa;AAAA;AAAA;AACnB,UAAM,GAAG,OAAO,GAAG,QAAQ,SAAS,UAAU,IAAI,KAAK,UAAU,IAAI,KAAK,aAAa,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC;AAF1D;AAI3C,WA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BAAsB,EAAE,YAAY,KAAK,SAAS,wBAAwB;AAnC7E,YAoCG,iBAAiB,EAAE,YAAY,KAAK,SAAS,kBAAkB;AApClE,YAqCG,aAAa,EAAE,YAAY,KAAK,SAAS,cAAc;AArC1D,YAsCG,qBAAqB,EAAE,YAAY,KAAK,SAAS,sBAAsB;AAtC1E,YAuCG,iBAAiB,EAAE,YAAY,KAAK,SAAS,kBAAkB;AAvClE,YAwCG,0BAA0B,EAAE,YAAY,KAAK,SAAS,6BAA6B;AAxCtF,YAyCG,wBAAwB,EAAE,YAAY,KAAK,SAAS,0BAA0B;AAzCjF,YA0CG,sBAAsB,EAAE,YAAY,KAAK,SAAS,uBAAuB;AA1C5E,YA2CG,eAAe,EAAE,YAAY,KAAK,SAAS,gBAAgB;AA3C9D,YA4CG,cAAc,EAAE,YAAY,KAAK,SAAS,eAAe;AA5C5D,YA6CG,gCAAgC,EAAE,YAAY,KAAK,SAAS,kCAAkC;AAiE9G,YAAY,UAAU,OAAO;","names":[]}
@@ -1,5 +1,5 @@
1
1
  // src/utils/hashes.tsx
2
- import bcrypt from "bcrypt";
2
+ import bcrypt from "bcryptjs";
3
3
  import { StackAssertionError } from "./errors";
4
4
  async function sha512(input) {
5
5
  const bytes = typeof input === "string" ? new TextEncoder().encode(input) : input;
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/utils/hashes.tsx"],"sourcesContent":["import bcrypt from 'bcrypt';\nimport { StackAssertionError } from './errors';\n\nexport async function sha512(input: Uint8Array | string): Promise<Uint8Array> {\n const bytes = typeof input === \"string\" ? new TextEncoder().encode(input) : input;\n return new Uint8Array(await crypto.subtle.digest(\"SHA-512\", bytes));\n}\n\nexport async function hashPassword(password: string) {\n const passwordBytes = new TextEncoder().encode(password);\n if (passwordBytes.length >= 72) {\n throw new StackAssertionError(`Password is too long for bcrypt`, { len: passwordBytes.length });\n }\n const salt = await bcrypt.genSalt(10);\n return await bcrypt.hash(password, salt);\n}\n\nexport async function comparePassword(password: string, hash: string): Promise<boolean> {\n switch (await getPasswordHashAlgorithm(hash)) {\n case \"bcrypt\": {\n return await bcrypt.compare(password, hash);\n }\n default: {\n return false;\n }\n }\n}\n\nexport async function isPasswordHashValid(hash: string) {\n return !!(await getPasswordHashAlgorithm(hash));\n}\n\nexport async function getPasswordHashAlgorithm(hash: string): Promise<\"bcrypt\" | undefined> {\n if (typeof hash !== \"string\") {\n throw new StackAssertionError(`Passed non-string value to getPasswordHashAlgorithm`, { hash });\n }\n if (hash.match(/^\\$2[ayb]\\$.{56}$/)) {\n try {\n if (bcrypt.getRounds(hash) > 16) {\n return undefined;\n }\n await bcrypt.compare(\"any string\", hash);\n return \"bcrypt\";\n } catch (e) {\n console.warn(`Error while checking bcrypt password hash. Assuming the hash is invalid`, e);\n return undefined;\n }\n } else {\n return undefined;\n }\n}\n"],"mappings":";AAAA,OAAO,YAAY;AACnB,SAAS,2BAA2B;AAEpC,eAAsB,OAAO,OAAiD;AAC5E,QAAM,QAAQ,OAAO,UAAU,WAAW,IAAI,YAAY,EAAE,OAAO,KAAK,IAAI;AAC5E,SAAO,IAAI,WAAW,MAAM,OAAO,OAAO,OAAO,WAAW,KAAK,CAAC;AACpE;AAEA,eAAsB,aAAa,UAAkB;AACnD,QAAM,gBAAgB,IAAI,YAAY,EAAE,OAAO,QAAQ;AACvD,MAAI,cAAc,UAAU,IAAI;AAC9B,UAAM,IAAI,oBAAoB,mCAAmC,EAAE,KAAK,cAAc,OAAO,CAAC;AAAA,EAChG;AACA,QAAM,OAAO,MAAM,OAAO,QAAQ,EAAE;AACpC,SAAO,MAAM,OAAO,KAAK,UAAU,IAAI;AACzC;AAEA,eAAsB,gBAAgB,UAAkB,MAAgC;AACtF,UAAQ,MAAM,yBAAyB,IAAI,GAAG;AAAA,IAC5C,KAAK,UAAU;AACb,aAAO,MAAM,OAAO,QAAQ,UAAU,IAAI;AAAA,IAC5C;AAAA,IACA,SAAS;AACP,aAAO;AAAA,IACT;AAAA,EACF;AACF;AAEA,eAAsB,oBAAoB,MAAc;AACtD,SAAO,CAAC,CAAE,MAAM,yBAAyB,IAAI;AAC/C;AAEA,eAAsB,yBAAyB,MAA6C;AAC1F,MAAI,OAAO,SAAS,UAAU;AAC5B,UAAM,IAAI,oBAAoB,uDAAuD,EAAE,KAAK,CAAC;AAAA,EAC/F;AACA,MAAI,KAAK,MAAM,mBAAmB,GAAG;AACnC,QAAI;AACF,UAAI,OAAO,UAAU,IAAI,IAAI,IAAI;AAC/B,eAAO;AAAA,MACT;AACA,YAAM,OAAO,QAAQ,cAAc,IAAI;AACvC,aAAO;AAAA,IACT,SAAS,GAAG;AACV,cAAQ,KAAK,2EAA2E,CAAC;AACzF,aAAO;AAAA,IACT;AAAA,EACF,OAAO;AACL,WAAO;AAAA,EACT;AACF;","names":[]}
1
+ {"version":3,"sources":["../../../src/utils/hashes.tsx"],"sourcesContent":["import bcrypt from 'bcryptjs';\nimport { StackAssertionError } from './errors';\n\nexport async function sha512(input: Uint8Array | string): Promise<Uint8Array> {\n const bytes = typeof input === \"string\" ? new TextEncoder().encode(input) : input;\n return new Uint8Array(await crypto.subtle.digest(\"SHA-512\", bytes));\n}\n\nexport async function hashPassword(password: string) {\n const passwordBytes = new TextEncoder().encode(password);\n if (passwordBytes.length >= 72) {\n throw new StackAssertionError(`Password is too long for bcrypt`, { len: passwordBytes.length });\n }\n const salt = await bcrypt.genSalt(10);\n return await bcrypt.hash(password, salt);\n}\n\nexport async function comparePassword(password: string, hash: string): Promise<boolean> {\n switch (await getPasswordHashAlgorithm(hash)) {\n case \"bcrypt\": {\n return await bcrypt.compare(password, hash);\n }\n default: {\n return false;\n }\n }\n}\n\nexport async function isPasswordHashValid(hash: string) {\n return !!(await getPasswordHashAlgorithm(hash));\n}\n\nexport async function getPasswordHashAlgorithm(hash: string): Promise<\"bcrypt\" | undefined> {\n if (typeof hash !== \"string\") {\n throw new StackAssertionError(`Passed non-string value to getPasswordHashAlgorithm`, { hash });\n }\n if (hash.match(/^\\$2[ayb]\\$.{56}$/)) {\n try {\n if (bcrypt.getRounds(hash) > 16) {\n return undefined;\n }\n await bcrypt.compare(\"any string\", hash);\n return \"bcrypt\";\n } catch (e) {\n console.warn(`Error while checking bcrypt password hash. Assuming the hash is invalid`, e);\n return undefined;\n }\n } else {\n return undefined;\n }\n}\n"],"mappings":";AAAA,OAAO,YAAY;AACnB,SAAS,2BAA2B;AAEpC,eAAsB,OAAO,OAAiD;AAC5E,QAAM,QAAQ,OAAO,UAAU,WAAW,IAAI,YAAY,EAAE,OAAO,KAAK,IAAI;AAC5E,SAAO,IAAI,WAAW,MAAM,OAAO,OAAO,OAAO,WAAW,KAAK,CAAC;AACpE;AAEA,eAAsB,aAAa,UAAkB;AACnD,QAAM,gBAAgB,IAAI,YAAY,EAAE,OAAO,QAAQ;AACvD,MAAI,cAAc,UAAU,IAAI;AAC9B,UAAM,IAAI,oBAAoB,mCAAmC,EAAE,KAAK,cAAc,OAAO,CAAC;AAAA,EAChG;AACA,QAAM,OAAO,MAAM,OAAO,QAAQ,EAAE;AACpC,SAAO,MAAM,OAAO,KAAK,UAAU,IAAI;AACzC;AAEA,eAAsB,gBAAgB,UAAkB,MAAgC;AACtF,UAAQ,MAAM,yBAAyB,IAAI,GAAG;AAAA,IAC5C,KAAK,UAAU;AACb,aAAO,MAAM,OAAO,QAAQ,UAAU,IAAI;AAAA,IAC5C;AAAA,IACA,SAAS;AACP,aAAO;AAAA,IACT;AAAA,EACF;AACF;AAEA,eAAsB,oBAAoB,MAAc;AACtD,SAAO,CAAC,CAAE,MAAM,yBAAyB,IAAI;AAC/C;AAEA,eAAsB,yBAAyB,MAA6C;AAC1F,MAAI,OAAO,SAAS,UAAU;AAC5B,UAAM,IAAI,oBAAoB,uDAAuD,EAAE,KAAK,CAAC;AAAA,EAC/F;AACA,MAAI,KAAK,MAAM,mBAAmB,GAAG;AACnC,QAAI;AACF,UAAI,OAAO,UAAU,IAAI,IAAI,IAAI;AAC/B,eAAO;AAAA,MACT;AACA,YAAM,OAAO,QAAQ,cAAc,IAAI;AACvC,aAAO;AAAA,IACT,SAAS,GAAG;AACV,cAAQ,KAAK,2EAA2E,CAAC;AACzF,aAAO;AAAA,IACT;AAAA,EACF,OAAO;AACL,WAAO;AAAA,EACT;AACF;","names":[]}
@@ -1,6 +1,7 @@
1
1
  // src/utils/objects.tsx
2
2
  import { StackAssertionError } from "./errors";
3
3
  import { identity } from "./functions";
4
+ import { stringCompare } from "./strings";
4
5
  function isNotNull(value) {
5
6
  return value !== null && value !== void 0;
6
7
  }
@@ -96,11 +97,27 @@ function pick(obj, keys) {
96
97
  return Object.fromEntries(Object.entries(obj).filter(([k]) => keys.includes(k)));
97
98
  }
98
99
  function omit(obj, keys) {
100
+ if (!Array.isArray(keys)) throw new StackAssertionError("omit: keys must be an array", { obj, keys });
99
101
  return Object.fromEntries(Object.entries(obj).filter(([k]) => !keys.includes(k)));
100
102
  }
101
103
  function split(obj, keys) {
102
104
  return [pick(obj, keys), omit(obj, keys)];
103
105
  }
106
+ function mapValues(obj, fn) {
107
+ if (Array.isArray(obj)) {
108
+ return obj.map((v) => fn(v));
109
+ }
110
+ return Object.fromEntries(Object.entries(obj).map(([k, v]) => [k, fn(v)]));
111
+ }
112
+ function sortKeys(obj) {
113
+ if (Array.isArray(obj)) {
114
+ return [...obj];
115
+ }
116
+ return Object.fromEntries(Object.entries(obj).sort(([a], [b]) => stringCompare(a, b)));
117
+ }
118
+ function deepSortKeys(obj) {
119
+ return sortKeys(mapValues(obj, (v) => isObjectLike(v) ? deepSortKeys(v) : v));
120
+ }
104
121
  function set(obj, key, value) {
105
122
  Object.defineProperty(obj, key, { value, writable: true, configurable: true, enumerable: true });
106
123
  }
@@ -109,6 +126,9 @@ function get(obj, key) {
109
126
  if (!descriptor) throw new StackAssertionError(`get: key ${String(key)} does not exist`, { obj, key });
110
127
  return descriptor.value;
111
128
  }
129
+ function getOrUndefined(obj, key) {
130
+ return has(obj, key) ? get(obj, key) : void 0;
131
+ }
112
132
  function has(obj, key) {
113
133
  return Object.prototype.hasOwnProperty.call(obj, key);
114
134
  }
@@ -130,19 +150,23 @@ export {
130
150
  deepMerge,
131
151
  deepPlainClone,
132
152
  deepPlainEquals,
153
+ deepSortKeys,
133
154
  deleteKey,
134
155
  filterUndefined,
135
156
  filterUndefinedOrNull,
136
157
  get,
158
+ getOrUndefined,
137
159
  has,
138
160
  hasAndNotUndefined,
139
161
  isCloneable,
140
162
  isNotNull,
141
163
  isObjectLike,
164
+ mapValues,
142
165
  omit,
143
166
  pick,
144
167
  set,
145
168
  shallowClone,
169
+ sortKeys,
146
170
  split,
147
171
  typedAssign,
148
172
  typedEntries,
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/utils/objects.tsx"],"sourcesContent":["import { StackAssertionError } from \"./errors\";\nimport { identity } from \"./functions\";\n\nexport function isNotNull<T>(value: T): value is NonNullable<T> {\n return value !== null && value !== undefined;\n}\nundefined?.test(\"isNotNull\", ({ expect }) => {\n expect(isNotNull(null)).toBe(false);\n expect(isNotNull(undefined)).toBe(false);\n expect(isNotNull(0)).toBe(true);\n expect(isNotNull(\"\")).toBe(true);\n expect(isNotNull(false)).toBe(true);\n expect(isNotNull({})).toBe(true);\n expect(isNotNull([])).toBe(true);\n});\n\nexport type DeepPartial<T> = T extends object ? { [P in keyof T]?: DeepPartial<T[P]> } : T;\nexport type DeepRequired<T> = T extends object ? { [P in keyof T]-?: DeepRequired<T[P]> } : T;\n\n/**\n * Assumes both objects are primitives, arrays, or non-function plain objects, and compares them deeply.\n *\n * Note that since they are assumed to be plain objects, this function does not compare prototypes.\n */\nexport function deepPlainEquals<T>(obj1: T, obj2: unknown, options: { ignoreUndefinedValues?: boolean } = {}): obj2 is T {\n if (typeof obj1 !== typeof obj2) return false;\n if (obj1 === obj2) return true;\n\n switch (typeof obj1) {\n case 'object': {\n if (!obj1 || !obj2) return false;\n\n if (Array.isArray(obj1) || Array.isArray(obj2)) {\n if (!Array.isArray(obj1) || !Array.isArray(obj2)) return false;\n if (obj1.length !== obj2.length) return false;\n return obj1.every((v, i) => deepPlainEquals(v, obj2[i], options));\n }\n\n const entries1 = Object.entries(obj1).filter(([k, v]) => !options.ignoreUndefinedValues || v !== undefined);\n const entries2 = Object.entries(obj2).filter(([k, v]) => !options.ignoreUndefinedValues || v !== undefined);\n if (entries1.length !== entries2.length) return false;\n return entries1.every(([k, v1]) => {\n const e2 = entries2.find(([k2]) => k === k2);\n if (!e2) return false;\n return deepPlainEquals(v1, e2[1], options);\n });\n }\n case 'undefined':\n case 'string':\n case 'number':\n case 'boolean':\n case 'bigint':\n case 'symbol':\n case 'function':{\n return false;\n }\n default: {\n throw new Error(\"Unexpected typeof \" + typeof obj1);\n }\n }\n}\nundefined?.test(\"deepPlainEquals\", ({ expect }) => {\n // Simple values\n expect(deepPlainEquals(1, 1)).toBe(true);\n expect(deepPlainEquals(\"test\", \"test\")).toBe(true);\n expect(deepPlainEquals(1, 2)).toBe(false);\n expect(deepPlainEquals(\"test\", \"other\")).toBe(false);\n\n // Arrays\n expect(deepPlainEquals([1, 2, 3], [1, 2, 3])).toBe(true);\n expect(deepPlainEquals([1, 2, 3], [1, 2, 4])).toBe(false);\n expect(deepPlainEquals([1, 2, 3], [1, 2])).toBe(false);\n\n // Objects\n expect(deepPlainEquals({ a: 1, b: 2 }, { a: 1, b: 2 })).toBe(true);\n expect(deepPlainEquals({ a: 1, b: 2 }, { a: 1, b: 3 })).toBe(false);\n expect(deepPlainEquals({ a: 1, b: 2 }, { a: 1 })).toBe(false);\n\n // Nested structures\n expect(deepPlainEquals({ a: 1, b: [1, 2, { c: 3 }] }, { a: 1, b: [1, 2, { c: 3 }] })).toBe(true);\n expect(deepPlainEquals({ a: 1, b: [1, 2, { c: 3 }] }, { a: 1, b: [1, 2, { c: 4 }] })).toBe(false);\n\n // With options\n expect(deepPlainEquals({ a: 1, b: undefined }, { a: 1 }, { ignoreUndefinedValues: true })).toBe(true);\n expect(deepPlainEquals({ a: 1, b: undefined }, { a: 1 })).toBe(false);\n});\n\nexport function isCloneable<T>(obj: T): obj is Exclude<T, symbol | Function> {\n return typeof obj !== 'symbol' && typeof obj !== 'function';\n}\n\nexport function shallowClone<T extends object>(obj: T): T {\n if (!isCloneable(obj)) throw new StackAssertionError(\"shallowClone does not support symbols or functions\", { obj });\n\n if (Array.isArray(obj)) return obj.map(identity) as T;\n return { ...obj };\n}\nundefined?.test(\"shallowClone\", ({ expect }) => {\n expect(shallowClone({ a: 1, b: 2 })).toEqual({ a: 1, b: 2 });\n expect(shallowClone([1, 2, 3])).toEqual([1, 2, 3]);\n expect(() => shallowClone(() => {})).toThrow();\n});\n\nexport function deepPlainClone<T>(obj: T): T {\n if (typeof obj === 'function') throw new StackAssertionError(\"deepPlainClone does not support functions\");\n if (typeof obj === 'symbol') throw new StackAssertionError(\"deepPlainClone does not support symbols\");\n if (typeof obj !== 'object' || !obj) return obj;\n if (Array.isArray(obj)) return obj.map(deepPlainClone) as any;\n return Object.fromEntries(Object.entries(obj).map(([k, v]) => [k, deepPlainClone(v)])) as any;\n}\nundefined?.test(\"deepPlainClone\", ({ expect }) => {\n // Primitive values\n expect(deepPlainClone(1)).toBe(1);\n expect(deepPlainClone(\"test\")).toBe(\"test\");\n expect(deepPlainClone(null)).toBe(null);\n expect(deepPlainClone(undefined)).toBe(undefined);\n\n // Arrays\n const arr = [1, 2, 3];\n const clonedArr = deepPlainClone(arr);\n expect(clonedArr).toEqual(arr);\n expect(clonedArr).not.toBe(arr); // Different reference\n\n // Objects\n const obj = { a: 1, b: 2 };\n const clonedObj = deepPlainClone(obj);\n expect(clonedObj).toEqual(obj);\n expect(clonedObj).not.toBe(obj); // Different reference\n\n // Nested structures\n const nested = { a: 1, b: [1, 2, { c: 3 }] };\n const clonedNested = deepPlainClone(nested);\n expect(clonedNested).toEqual(nested);\n expect(clonedNested).not.toBe(nested); // Different reference\n expect(clonedNested.b).not.toBe(nested.b); // Different reference for nested array\n expect(clonedNested.b[2]).not.toBe(nested.b[2]); // Different reference for nested object\n\n // Error cases\n expect(() => deepPlainClone(() => {})).toThrow();\n expect(() => deepPlainClone(Symbol())).toThrow();\n});\n\nexport type DeepMerge<T, U> = Omit<T, keyof U> & Omit<U, keyof T> & DeepMergeInner<Pick<T, keyof U & keyof T>, Pick<U, keyof U & keyof T>>;\ntype DeepMergeInner<T, U> = {\n [K in keyof U]-?:\n undefined extends U[K]\n ? K extends keyof T\n ? T[K] extends object\n ? Exclude<U[K], undefined> extends object\n ? DeepMerge<T[K], Exclude<U[K], undefined>>\n : T[K] | Exclude<U[K], undefined>\n : T[K] | Exclude<U[K], undefined>\n : Exclude<U[K], undefined>\n : K extends keyof T\n ? T[K] extends object\n ? U[K] extends object\n ? DeepMerge<T[K], U[K]>\n : U[K]\n : U[K]\n : U[K];\n};\nexport function deepMerge<T extends {}, U extends {}>(baseObj: T, mergeObj: U): DeepMerge<T, U> {\n if ([baseObj, mergeObj, ...Object.values(baseObj), ...Object.values(mergeObj)].some(o => !isCloneable(o))) throw new StackAssertionError(\"deepMerge does not support functions or symbols\", { baseObj, mergeObj });\n\n const res: any = shallowClone(baseObj);\n for (const [key, mergeValue] of Object.entries(mergeObj)) {\n if (has(res, key as any)) {\n const baseValue = get(res, key as any);\n if (isObjectLike(baseValue) && isObjectLike(mergeValue)) {\n set(res, key, deepMerge(baseValue, mergeValue));\n continue;\n }\n }\n set(res, key, mergeValue);\n }\n return res as any;\n}\nundefined?.test(\"deepMerge\", ({ expect }) => {\n // Test merging flat objects\n expect(deepMerge({ a: 1 }, { b: 2 })).toEqual({ a: 1, b: 2 });\n expect(deepMerge({ a: 1 }, { a: 2 })).toEqual({ a: 2 });\n expect(deepMerge({ a: 1, b: 2 }, { b: 3, c: 4 })).toEqual({ a: 1, b: 3, c: 4 });\n\n // Test with nested objects\n expect(deepMerge(\n { a: { x: 1, y: 2 }, b: 3 },\n { a: { y: 3, z: 4 }, c: 5 }\n )).toEqual({ a: { x: 1, y: 3, z: 4 }, b: 3, c: 5 });\n\n // Test with arrays\n expect(deepMerge(\n { a: [1, 2], b: 3 },\n { a: [3, 4], c: 5 }\n )).toEqual({ a: [3, 4], b: 3, c: 5 });\n\n // Test with null values\n expect(deepMerge(\n { a: { x: 1 }, b: null },\n { a: { y: 2 }, b: { z: 3 } }\n )).toEqual({ a: { x: 1, y: 2 }, b: { z: 3 } });\n\n // Test with undefined values\n expect(deepMerge(\n { a: 1, b: undefined },\n { b: 2, c: 3 }\n )).toEqual({ a: 1, b: 2, c: 3 });\n\n // Test deeply nested structures\n expect(deepMerge(\n {\n a: {\n x: { deep: 1 },\n y: [1, 2]\n },\n b: 2\n },\n {\n a: {\n x: { deeper: 3 },\n y: [3, 4]\n },\n c: 3\n }\n )).toEqual({\n a: {\n x: { deep: 1, deeper: 3 },\n y: [3, 4]\n },\n b: 2,\n c: 3\n });\n\n // Test with empty objects\n expect(deepMerge({}, { a: 1 })).toEqual({ a: 1 });\n expect(deepMerge({ a: 1 }, {})).toEqual({ a: 1 });\n expect(deepMerge({}, {})).toEqual({});\n\n // Test that original objects are not modified\n const base = { a: { x: 1 }, b: 2 };\n const merge = { a: { y: 2 }, c: 3 };\n const baseClone = deepPlainClone(base);\n const mergeClone = deepPlainClone(merge);\n\n const result = deepMerge(base, merge);\n expect(base).toEqual(baseClone);\n expect(merge).toEqual(mergeClone);\n expect(result).toEqual({ a: { x: 1, y: 2 }, b: 2, c: 3 });\n\n // Test error cases\n expect(() => deepMerge({ a: () => {} }, { b: 2 })).toThrow();\n expect(() => deepMerge({ a: 1 }, { b: () => {} })).toThrow();\n expect(() => deepMerge({ a: Symbol() }, { b: 2 })).toThrow();\n expect(() => deepMerge({ a: 1 }, { b: Symbol() })).toThrow();\n});\n\nexport function typedEntries<T extends {}>(obj: T): [keyof T, T[keyof T]][] {\n return Object.entries(obj) as any;\n}\nundefined?.test(\"typedEntries\", ({ expect }) => {\n expect(typedEntries({})).toEqual([]);\n expect(typedEntries({ a: 1, b: 2 })).toEqual([[\"a\", 1], [\"b\", 2]]);\n expect(typedEntries({ a: \"hello\", b: true, c: null })).toEqual([[\"a\", \"hello\"], [\"b\", true], [\"c\", null]]);\n\n // Test with object containing methods\n const objWithMethod = { a: 1, b: () => \"test\" };\n const entries = typedEntries(objWithMethod);\n expect(entries.length).toBe(2);\n expect(entries[0][0]).toBe(\"a\");\n expect(entries[0][1]).toBe(1);\n expect(entries[1][0]).toBe(\"b\");\n expect(typeof entries[1][1]).toBe(\"function\");\n});\n\nexport function typedFromEntries<K extends PropertyKey, V>(entries: (readonly [K, V])[]): Record<K, V> {\n return Object.fromEntries(entries) as any;\n}\nundefined?.test(\"typedFromEntries\", ({ expect }) => {\n expect(typedFromEntries([])).toEqual({});\n expect(typedFromEntries([[\"a\", 1], [\"b\", 2]])).toEqual({ a: 1, b: 2 });\n\n // Test with mixed types (using type assertion)\n const mixedEntries = [[\"a\", \"hello\"], [\"b\", true], [\"c\", null]] as [string, string | boolean | null][];\n const mixedObj = typedFromEntries(mixedEntries);\n expect(mixedObj).toEqual({ a: \"hello\", b: true, c: null });\n\n // Test with function values\n const fn = () => \"test\";\n type MixedValue = number | (() => string);\n const fnEntries: [string, MixedValue][] = [[\"a\", 1], [\"b\", fn]];\n const obj = typedFromEntries(fnEntries);\n expect(obj.a).toBe(1);\n expect(typeof obj.b).toBe(\"function\");\n // Type assertion needed for the function call\n expect((obj.b as () => string)()).toBe(\"test\");\n});\n\nexport function typedKeys<T extends {}>(obj: T): (keyof T)[] {\n return Object.keys(obj) as any;\n}\nundefined?.test(\"typedKeys\", ({ expect }) => {\n expect(typedKeys({})).toEqual([]);\n expect(typedKeys({ a: 1, b: 2 })).toEqual([\"a\", \"b\"]);\n expect(typedKeys({ a: \"hello\", b: true, c: null })).toEqual([\"a\", \"b\", \"c\"]);\n\n // Test with object containing methods\n const objWithMethod = { a: 1, b: () => \"test\" };\n expect(typedKeys(objWithMethod)).toEqual([\"a\", \"b\"]);\n});\n\nexport function typedValues<T extends {}>(obj: T): T[keyof T][] {\n return Object.values(obj) as any;\n}\nundefined?.test(\"typedValues\", ({ expect }) => {\n expect(typedValues({})).toEqual([]);\n expect(typedValues({ a: 1, b: 2 })).toEqual([1, 2]);\n\n // Test with mixed types\n type MixedObj = { a: string, b: boolean, c: null };\n const mixedObj: MixedObj = { a: \"hello\", b: true, c: null };\n expect(typedValues(mixedObj)).toEqual([\"hello\", true, null]);\n\n // Test with object containing methods\n type ObjWithFn = { a: number, b: () => string };\n const fn = () => \"test\";\n const objWithMethod: ObjWithFn = { a: 1, b: fn };\n const values = typedValues(objWithMethod);\n expect(values.length).toBe(2);\n expect(values[0]).toBe(1);\n expect(typeof values[1]).toBe(\"function\");\n // Need to cast to the correct type\n const fnValue = values[1] as () => string;\n expect(fnValue()).toBe(\"test\");\n});\n\nexport function typedAssign<T extends {}, U extends {}>(target: T, source: U): T & U {\n return Object.assign(target, source);\n}\nundefined?.test(\"typedAssign\", ({ expect }) => {\n // Test with empty objects\n const emptyTarget = {};\n const emptyResult = typedAssign(emptyTarget, { a: 1 });\n expect(emptyResult).toEqual({ a: 1 });\n expect(emptyResult).toBe(emptyTarget); // Same reference\n\n // Test with non-empty target\n const target = { a: 1, b: 2 };\n const result = typedAssign(target, { c: 3, d: 4 });\n expect(result).toEqual({ a: 1, b: 2, c: 3, d: 4 });\n expect(result).toBe(target); // Same reference\n\n // Test with overlapping properties\n const targetWithOverlap = { a: 1, b: 2 };\n const resultWithOverlap = typedAssign(targetWithOverlap, { b: 3, c: 4 });\n expect(resultWithOverlap).toEqual({ a: 1, b: 3, c: 4 });\n expect(resultWithOverlap).toBe(targetWithOverlap); // Same reference\n});\n\nexport type FilterUndefined<T> =\n & { [k in keyof T as (undefined extends T[k] ? (T[k] extends undefined | void ? never : k) : never)]+?: T[k] & ({} | null) }\n & { [k in keyof T as (undefined extends T[k] ? never : k)]: T[k] & ({} | null) }\n\n/**\n * Returns a new object with all undefined values removed. Useful when spreading optional parameters on an object, as\n * TypeScript's `Partial<XYZ>` type allows `undefined` values.\n */\nexport function filterUndefined<T extends object>(obj: T): FilterUndefined<T> {\n return Object.fromEntries(Object.entries(obj).filter(([, v]) => v !== undefined)) as any;\n}\nundefined?.test(\"filterUndefined\", ({ expect }) => {\n expect(filterUndefined({})).toEqual({});\n expect(filterUndefined({ a: 1, b: 2 })).toEqual({ a: 1, b: 2 });\n expect(filterUndefined({ a: 1, b: undefined })).toEqual({ a: 1 });\n expect(filterUndefined({ a: undefined, b: undefined })).toEqual({});\n expect(filterUndefined({ a: null, b: undefined })).toEqual({ a: null });\n expect(filterUndefined({ a: 0, b: \"\", c: false, d: undefined })).toEqual({ a: 0, b: \"\", c: false });\n});\n\nexport type FilterUndefinedOrNull<T> = FilterUndefined<{ [k in keyof T]: null extends T[k] ? NonNullable<T[k]> | undefined : T[k] }>;\n\n/**\n * Returns a new object with all undefined and null values removed. Useful when spreading optional parameters on an object, as\n * TypeScript's `Partial<XYZ>` type allows `undefined` values.\n */\nexport function filterUndefinedOrNull<T extends object>(obj: T): FilterUndefinedOrNull<T> {\n return Object.fromEntries(Object.entries(obj).filter(([, v]) => v !== undefined && v !== null)) as any;\n}\nundefined?.test(\"filterUndefinedOrNull\", ({ expect }) => {\n expect(filterUndefinedOrNull({})).toEqual({});\n expect(filterUndefinedOrNull({ a: 1, b: 2 })).toEqual({ a: 1, b: 2 });\n});\n\nexport type DeepFilterUndefined<T> = T extends object ? FilterUndefined<{ [K in keyof T]: DeepFilterUndefined<T[K]> }> : T;\n\nexport function deepFilterUndefined<T extends object>(obj: T): DeepFilterUndefined<T> {\n return Object.fromEntries(Object.entries(obj).filter(([, v]) => v !== undefined).map(([k, v]) => [k, isObjectLike(v) ? deepFilterUndefined(v) : v])) as any;\n}\nundefined?.test(\"deepFilterUndefined\", ({ expect }) => {\n expect(deepFilterUndefined({ a: 1, b: undefined })).toEqual({ a: 1 });\n});\n\nexport function pick<T extends {}, K extends keyof T>(obj: T, keys: K[]): Pick<T, K> {\n return Object.fromEntries(Object.entries(obj).filter(([k]) => keys.includes(k as K))) as any;\n}\nundefined?.test(\"pick\", ({ expect }) => {\n const obj = { a: 1, b: 2, c: 3, d: 4 };\n expect(pick(obj, [\"a\", \"c\"])).toEqual({ a: 1, c: 3 });\n expect(pick(obj, [])).toEqual({});\n expect(pick(obj, [\"a\", \"e\" as keyof typeof obj])).toEqual({ a: 1 });\n // Use type assertion for empty object to avoid TypeScript error\n expect(pick({} as Record<string, unknown>, [\"a\"])).toEqual({});\n});\n\nexport function omit<T extends {}, K extends keyof T>(obj: T, keys: K[]): Omit<T, K> {\n return Object.fromEntries(Object.entries(obj).filter(([k]) => !keys.includes(k as K))) as any;\n}\nundefined?.test(\"omit\", ({ expect }) => {\n const obj = { a: 1, b: 2, c: 3, d: 4 };\n expect(omit(obj, [\"a\", \"c\"])).toEqual({ b: 2, d: 4 });\n expect(omit(obj, [])).toEqual(obj);\n expect(omit(obj, [\"a\", \"e\" as keyof typeof obj])).toEqual({ b: 2, c: 3, d: 4 });\n // Use type assertion for empty object to avoid TypeScript error\n expect(omit({} as Record<string, unknown>, [\"a\"])).toEqual({});\n});\n\nexport function split<T extends {}, K extends keyof T>(obj: T, keys: K[]): [Pick<T, K>, Omit<T, K>] {\n return [pick(obj, keys), omit(obj, keys)];\n}\n\nundefined?.test(\"split\", ({ expect }) => {\n const obj = { a: 1, b: 2, c: 3, d: 4 };\n expect(split(obj, [\"a\", \"c\"])).toEqual([{ a: 1, c: 3 }, { b: 2, d: 4 }]);\n expect(split(obj, [])).toEqual([{}, obj]);\n expect(split(obj, [\"a\", \"e\" as keyof typeof obj])).toEqual([{ a: 1 }, { b: 2, c: 3, d: 4 }]);\n // Use type assertion for empty object to avoid TypeScript error\n expect(split({} as Record<string, unknown>, [\"a\"])).toEqual([{}, {}]);\n});\n\nexport function set<T extends object, K extends keyof T>(obj: T, key: K, value: T[K]) {\n Object.defineProperty(obj, key, { value, writable: true, configurable: true, enumerable: true });\n}\n\nexport function get<T extends object, K extends keyof T>(obj: T, key: K): T[K] {\n const descriptor = Object.getOwnPropertyDescriptor(obj, key);\n if (!descriptor) throw new StackAssertionError(`get: key ${String(key)} does not exist`, { obj, key });\n return descriptor.value;\n}\n\nexport function has<T extends object, K extends keyof T>(obj: T, key: K): obj is T & { [k in K]: unknown } {\n return Object.prototype.hasOwnProperty.call(obj, key);\n}\n\nexport function hasAndNotUndefined<T extends object, K extends keyof T>(obj: T, key: K): obj is T & { [k in K]: Exclude<T[K], undefined> } {\n return has(obj, key) && get(obj, key) !== undefined;\n}\n\nexport function deleteKey<T extends object, K extends keyof T>(obj: T, key: K) {\n if (has(obj, key)) {\n Reflect.deleteProperty(obj, key);\n } else {\n throw new StackAssertionError(`deleteKey: key ${String(key)} does not exist`, { obj, key });\n }\n}\n\nexport function isObjectLike(value: unknown): value is object {\n return (typeof value === 'object' || typeof value === 'function') && value !== null;\n}\n"],"mappings":";AAAA,SAAS,2BAA2B;AACpC,SAAS,gBAAgB;AAElB,SAAS,UAAa,OAAmC;AAC9D,SAAO,UAAU,QAAQ,UAAU;AACrC;AAmBO,SAAS,gBAAmB,MAAS,MAAe,UAA+C,CAAC,GAAc;AACvH,MAAI,OAAO,SAAS,OAAO,KAAM,QAAO;AACxC,MAAI,SAAS,KAAM,QAAO;AAE1B,UAAQ,OAAO,MAAM;AAAA,IACnB,KAAK,UAAU;AACb,UAAI,CAAC,QAAQ,CAAC,KAAM,QAAO;AAE3B,UAAI,MAAM,QAAQ,IAAI,KAAK,MAAM,QAAQ,IAAI,GAAG;AAC9C,YAAI,CAAC,MAAM,QAAQ,IAAI,KAAK,CAAC,MAAM,QAAQ,IAAI,EAAG,QAAO;AACzD,YAAI,KAAK,WAAW,KAAK,OAAQ,QAAO;AACxC,eAAO,KAAK,MAAM,CAAC,GAAG,MAAM,gBAAgB,GAAG,KAAK,CAAC,GAAG,OAAO,CAAC;AAAA,MAClE;AAEA,YAAM,WAAW,OAAO,QAAQ,IAAI,EAAE,OAAO,CAAC,CAAC,GAAG,CAAC,MAAM,CAAC,QAAQ,yBAAyB,MAAM,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EO,SAAS,UAA+C,KAAQ,KAAQ;AAC7E,MAAI,IAAI,KAAK,GAAG,GAAG;AACjB,YAAQ,eAAe,KAAK,GAAG;AAAA,EACjC,OAAO;AACL,UAAM,IAAI,oBAAoB,kBAAkB,OAAO,GAAG,CAAC,mBAAmB,EAAE,KAAK,IAAI,CAAC;AAAA,EAC5F;AACF;AAEO,SAAS,aAAa,OAAiC;AAC5D,UAAQ,OAAO,UAAU,YAAY,OAAO,UAAU,eAAe,UAAU;AACjF;","names":[]}
1
+ {"version":3,"sources":["../../../src/utils/objects.tsx"],"sourcesContent":["import { StackAssertionError } from \"./errors\";\nimport { identity } from \"./functions\";\nimport { stringCompare } from \"./strings\";\n\nexport function isNotNull<T>(value: T): value is NonNullable<T> {\n return value !== null && value !== undefined;\n}\nundefined?.test(\"isNotNull\", ({ expect }) => {\n expect(isNotNull(null)).toBe(false);\n expect(isNotNull(undefined)).toBe(false);\n expect(isNotNull(0)).toBe(true);\n expect(isNotNull(\"\")).toBe(true);\n expect(isNotNull(false)).toBe(true);\n expect(isNotNull({})).toBe(true);\n expect(isNotNull([])).toBe(true);\n});\n\nexport type DeepPartial<T> = T extends object ? (T extends (infer E)[] ? T : { [P in keyof T]?: DeepPartial<T[P]> }) : T;\nexport type DeepRequired<T> = T extends object ? (T extends (infer E)[] ? T : { [P in keyof T]-?: DeepRequired<T[P]> }) : T;\n\n/**\n * Assumes both objects are primitives, arrays, or non-function plain objects, and compares them deeply.\n *\n * Note that since they are assumed to be plain objects, this function does not compare prototypes.\n */\nexport function deepPlainEquals<T>(obj1: T, obj2: unknown, options: { ignoreUndefinedValues?: boolean } = {}): obj2 is T {\n if (typeof obj1 !== typeof obj2) return false;\n if (obj1 === obj2) return true;\n\n switch (typeof obj1) {\n case 'object': {\n if (!obj1 || !obj2) return false;\n\n if (Array.isArray(obj1) || Array.isArray(obj2)) {\n if (!Array.isArray(obj1) || !Array.isArray(obj2)) return false;\n if (obj1.length !== obj2.length) return false;\n return obj1.every((v, i) => deepPlainEquals(v, obj2[i], options));\n }\n\n const entries1 = Object.entries(obj1).filter(([k, v]) => !options.ignoreUndefinedValues || v !== undefined);\n const entries2 = Object.entries(obj2).filter(([k, v]) => !options.ignoreUndefinedValues || v !== undefined);\n if (entries1.length !== entries2.length) return false;\n return entries1.every(([k, v1]) => {\n const e2 = entries2.find(([k2]) => k === k2);\n if (!e2) return false;\n return deepPlainEquals(v1, e2[1], options);\n });\n }\n case 'undefined':\n case 'string':\n case 'number':\n case 'boolean':\n case 'bigint':\n case 'symbol':\n case 'function':{\n return false;\n }\n default: {\n throw new Error(\"Unexpected typeof \" + typeof obj1);\n }\n }\n}\nundefined?.test(\"deepPlainEquals\", ({ expect }) => {\n // Simple values\n expect(deepPlainEquals(1, 1)).toBe(true);\n expect(deepPlainEquals(\"test\", \"test\")).toBe(true);\n expect(deepPlainEquals(1, 2)).toBe(false);\n expect(deepPlainEquals(\"test\", \"other\")).toBe(false);\n\n // Arrays\n expect(deepPlainEquals([1, 2, 3], [1, 2, 3])).toBe(true);\n expect(deepPlainEquals([1, 2, 3], [1, 2, 4])).toBe(false);\n expect(deepPlainEquals([1, 2, 3], [1, 2])).toBe(false);\n\n // Objects\n expect(deepPlainEquals({ a: 1, b: 2 }, { a: 1, b: 2 })).toBe(true);\n expect(deepPlainEquals({ a: 1, b: 2 }, { a: 1, b: 3 })).toBe(false);\n expect(deepPlainEquals({ a: 1, b: 2 }, { a: 1 })).toBe(false);\n\n // Nested structures\n expect(deepPlainEquals({ a: 1, b: [1, 2, { c: 3 }] }, { a: 1, b: [1, 2, { c: 3 }] })).toBe(true);\n expect(deepPlainEquals({ a: 1, b: [1, 2, { c: 3 }] }, { a: 1, b: [1, 2, { c: 4 }] })).toBe(false);\n\n // With options\n expect(deepPlainEquals({ a: 1, b: undefined }, { a: 1 }, { ignoreUndefinedValues: true })).toBe(true);\n expect(deepPlainEquals({ a: 1, b: undefined }, { a: 1 })).toBe(false);\n});\n\nexport function isCloneable<T>(obj: T): obj is Exclude<T, symbol | Function> {\n return typeof obj !== 'symbol' && typeof obj !== 'function';\n}\n\nexport function shallowClone<T extends object>(obj: T): T {\n if (!isCloneable(obj)) throw new StackAssertionError(\"shallowClone does not support symbols or functions\", { obj });\n\n if (Array.isArray(obj)) return obj.map(identity) as T;\n return { ...obj };\n}\nundefined?.test(\"shallowClone\", ({ expect }) => {\n expect(shallowClone({ a: 1, b: 2 })).toEqual({ a: 1, b: 2 });\n expect(shallowClone([1, 2, 3])).toEqual([1, 2, 3]);\n expect(() => shallowClone(() => {})).toThrow();\n});\n\nexport function deepPlainClone<T>(obj: T): T {\n if (typeof obj === 'function') throw new StackAssertionError(\"deepPlainClone does not support functions\");\n if (typeof obj === 'symbol') throw new StackAssertionError(\"deepPlainClone does not support symbols\");\n if (typeof obj !== 'object' || !obj) return obj;\n if (Array.isArray(obj)) return obj.map(deepPlainClone) as any;\n return Object.fromEntries(Object.entries(obj).map(([k, v]) => [k, deepPlainClone(v)])) as any;\n}\nundefined?.test(\"deepPlainClone\", ({ expect }) => {\n // Primitive values\n expect(deepPlainClone(1)).toBe(1);\n expect(deepPlainClone(\"test\")).toBe(\"test\");\n expect(deepPlainClone(null)).toBe(null);\n expect(deepPlainClone(undefined)).toBe(undefined);\n\n // Arrays\n const arr = [1, 2, 3];\n const clonedArr = deepPlainClone(arr);\n expect(clonedArr).toEqual(arr);\n expect(clonedArr).not.toBe(arr); // Different reference\n\n // Objects\n const obj = { a: 1, b: 2 };\n const clonedObj = deepPlainClone(obj);\n expect(clonedObj).toEqual(obj);\n expect(clonedObj).not.toBe(obj); // Different reference\n\n // Nested structures\n const nested = { a: 1, b: [1, 2, { c: 3 }] };\n const clonedNested = deepPlainClone(nested);\n expect(clonedNested).toEqual(nested);\n expect(clonedNested).not.toBe(nested); // Different reference\n expect(clonedNested.b).not.toBe(nested.b); // Different reference for nested array\n expect(clonedNested.b[2]).not.toBe(nested.b[2]); // Different reference for nested object\n\n // Error cases\n expect(() => deepPlainClone(() => {})).toThrow();\n expect(() => deepPlainClone(Symbol())).toThrow();\n});\n\nexport type DeepMerge<T, U> = Omit<T, keyof U> & Omit<U, keyof T> & DeepMergeInner<Pick<T, keyof U & keyof T>, Pick<U, keyof U & keyof T>>;\ntype DeepMergeInner<T, U> = {\n [K in keyof U]-?:\n undefined extends U[K]\n ? K extends keyof T\n ? T[K] extends object\n ? Exclude<U[K], undefined> extends object\n ? DeepMerge<T[K], Exclude<U[K], undefined>>\n : T[K] | Exclude<U[K], undefined>\n : T[K] | Exclude<U[K], undefined>\n : Exclude<U[K], undefined>\n : K extends keyof T\n ? T[K] extends object\n ? U[K] extends object\n ? DeepMerge<T[K], U[K]>\n : U[K]\n : U[K]\n : U[K];\n};\nexport function deepMerge<T extends {}, U extends {}>(baseObj: T, mergeObj: U): DeepMerge<T, U> {\n if ([baseObj, mergeObj, ...Object.values(baseObj), ...Object.values(mergeObj)].some(o => !isCloneable(o))) throw new StackAssertionError(\"deepMerge does not support functions or symbols\", { baseObj, mergeObj });\n\n const res: any = shallowClone(baseObj);\n for (const [key, mergeValue] of Object.entries(mergeObj)) {\n if (has(res, key as any)) {\n const baseValue = get(res, key as any);\n if (isObjectLike(baseValue) && isObjectLike(mergeValue)) {\n set(res, key, deepMerge(baseValue, mergeValue));\n continue;\n }\n }\n set(res, key, mergeValue);\n }\n return res as any;\n}\nundefined?.test(\"deepMerge\", ({ expect }) => {\n // Test merging flat objects\n expect(deepMerge({ a: 1 }, { b: 2 })).toEqual({ a: 1, b: 2 });\n expect(deepMerge({ a: 1 }, { a: 2 })).toEqual({ a: 2 });\n expect(deepMerge({ a: 1, b: 2 }, { b: 3, c: 4 })).toEqual({ a: 1, b: 3, c: 4 });\n\n // Test with nested objects\n expect(deepMerge(\n { a: { x: 1, y: 2 }, b: 3 },\n { a: { y: 3, z: 4 }, c: 5 }\n )).toEqual({ a: { x: 1, y: 3, z: 4 }, b: 3, c: 5 });\n\n // Test with arrays\n expect(deepMerge(\n { a: [1, 2], b: 3 },\n { a: [3, 4], c: 5 }\n )).toEqual({ a: [3, 4], b: 3, c: 5 });\n\n // Test with null values\n expect(deepMerge(\n { a: { x: 1 }, b: null },\n { a: { y: 2 }, b: { z: 3 } }\n )).toEqual({ a: { x: 1, y: 2 }, b: { z: 3 } });\n\n // Test with undefined values\n expect(deepMerge(\n { a: 1, b: undefined },\n { b: 2, c: 3 }\n )).toEqual({ a: 1, b: 2, c: 3 });\n\n // Test deeply nested structures\n expect(deepMerge(\n {\n a: {\n x: { deep: 1 },\n y: [1, 2]\n },\n b: 2\n },\n {\n a: {\n x: { deeper: 3 },\n y: [3, 4]\n },\n c: 3\n }\n )).toEqual({\n a: {\n x: { deep: 1, deeper: 3 },\n y: [3, 4]\n },\n b: 2,\n c: 3\n });\n\n // Test with empty objects\n expect(deepMerge({}, { a: 1 })).toEqual({ a: 1 });\n expect(deepMerge({ a: 1 }, {})).toEqual({ a: 1 });\n expect(deepMerge({}, {})).toEqual({});\n\n // Test that original objects are not modified\n const base = { a: { x: 1 }, b: 2 };\n const merge = { a: { y: 2 }, c: 3 };\n const baseClone = deepPlainClone(base);\n const mergeClone = deepPlainClone(merge);\n\n const result = deepMerge(base, merge);\n expect(base).toEqual(baseClone);\n expect(merge).toEqual(mergeClone);\n expect(result).toEqual({ a: { x: 1, y: 2 }, b: 2, c: 3 });\n\n // Test error cases\n expect(() => deepMerge({ a: () => {} }, { b: 2 })).toThrow();\n expect(() => deepMerge({ a: 1 }, { b: () => {} })).toThrow();\n expect(() => deepMerge({ a: Symbol() }, { b: 2 })).toThrow();\n expect(() => deepMerge({ a: 1 }, { b: Symbol() })).toThrow();\n});\n\nexport function typedEntries<T extends {}>(obj: T): [keyof T, T[keyof T]][] {\n return Object.entries(obj) as any;\n}\nundefined?.test(\"typedEntries\", ({ expect }) => {\n expect(typedEntries({})).toEqual([]);\n expect(typedEntries({ a: 1, b: 2 })).toEqual([[\"a\", 1], [\"b\", 2]]);\n expect(typedEntries({ a: \"hello\", b: true, c: null })).toEqual([[\"a\", \"hello\"], [\"b\", true], [\"c\", null]]);\n\n // Test with object containing methods\n const objWithMethod = { a: 1, b: () => \"test\" };\n const entries = typedEntries(objWithMethod);\n expect(entries.length).toBe(2);\n expect(entries[0][0]).toBe(\"a\");\n expect(entries[0][1]).toBe(1);\n expect(entries[1][0]).toBe(\"b\");\n expect(typeof entries[1][1]).toBe(\"function\");\n});\n\nexport function typedFromEntries<K extends PropertyKey, V>(entries: (readonly [K, V])[]): Record<K, V> {\n return Object.fromEntries(entries) as any;\n}\nundefined?.test(\"typedFromEntries\", ({ expect }) => {\n expect(typedFromEntries([])).toEqual({});\n expect(typedFromEntries([[\"a\", 1], [\"b\", 2]])).toEqual({ a: 1, b: 2 });\n\n // Test with mixed types (using type assertion)\n const mixedEntries = [[\"a\", \"hello\"], [\"b\", true], [\"c\", null]] as [string, string | boolean | null][];\n const mixedObj = typedFromEntries(mixedEntries);\n expect(mixedObj).toEqual({ a: \"hello\", b: true, c: null });\n\n // Test with function values\n const fn = () => \"test\";\n type MixedValue = number | (() => string);\n const fnEntries: [string, MixedValue][] = [[\"a\", 1], [\"b\", fn]];\n const obj = typedFromEntries(fnEntries);\n expect(obj.a).toBe(1);\n expect(typeof obj.b).toBe(\"function\");\n // Type assertion needed for the function call\n expect((obj.b as () => string)()).toBe(\"test\");\n});\n\nexport function typedKeys<T extends {}>(obj: T): (keyof T)[] {\n return Object.keys(obj) as any;\n}\nundefined?.test(\"typedKeys\", ({ expect }) => {\n expect(typedKeys({})).toEqual([]);\n expect(typedKeys({ a: 1, b: 2 })).toEqual([\"a\", \"b\"]);\n expect(typedKeys({ a: \"hello\", b: true, c: null })).toEqual([\"a\", \"b\", \"c\"]);\n\n // Test with object containing methods\n const objWithMethod = { a: 1, b: () => \"test\" };\n expect(typedKeys(objWithMethod)).toEqual([\"a\", \"b\"]);\n});\n\nexport function typedValues<T extends {}>(obj: T): T[keyof T][] {\n return Object.values(obj) as any;\n}\nundefined?.test(\"typedValues\", ({ expect }) => {\n expect(typedValues({})).toEqual([]);\n expect(typedValues({ a: 1, b: 2 })).toEqual([1, 2]);\n\n // Test with mixed types\n type MixedObj = { a: string, b: boolean, c: null };\n const mixedObj: MixedObj = { a: \"hello\", b: true, c: null };\n expect(typedValues(mixedObj)).toEqual([\"hello\", true, null]);\n\n // Test with object containing methods\n type ObjWithFn = { a: number, b: () => string };\n const fn = () => \"test\";\n const objWithMethod: ObjWithFn = { a: 1, b: fn };\n const values = typedValues(objWithMethod);\n expect(values.length).toBe(2);\n expect(values[0]).toBe(1);\n expect(typeof values[1]).toBe(\"function\");\n // Need to cast to the correct type\n const fnValue = values[1] as () => string;\n expect(fnValue()).toBe(\"test\");\n});\n\nexport function typedAssign<T extends {}, U extends {}>(target: T, source: U): T & U {\n return Object.assign(target, source);\n}\nundefined?.test(\"typedAssign\", ({ expect }) => {\n // Test with empty objects\n const emptyTarget = {};\n const emptyResult = typedAssign(emptyTarget, { a: 1 });\n expect(emptyResult).toEqual({ a: 1 });\n expect(emptyResult).toBe(emptyTarget); // Same reference\n\n // Test with non-empty target\n const target = { a: 1, b: 2 };\n const result = typedAssign(target, { c: 3, d: 4 });\n expect(result).toEqual({ a: 1, b: 2, c: 3, d: 4 });\n expect(result).toBe(target); // Same reference\n\n // Test with overlapping properties\n const targetWithOverlap = { a: 1, b: 2 };\n const resultWithOverlap = typedAssign(targetWithOverlap, { b: 3, c: 4 });\n expect(resultWithOverlap).toEqual({ a: 1, b: 3, c: 4 });\n expect(resultWithOverlap).toBe(targetWithOverlap); // Same reference\n});\n\nexport type FilterUndefined<T> =\n & { [k in keyof T as (undefined extends T[k] ? (T[k] extends undefined | void ? never : k) : never)]+?: T[k] & ({} | null) }\n & { [k in keyof T as (undefined extends T[k] ? never : k)]: T[k] & ({} | null) }\n\n/**\n * Returns a new object with all undefined values removed. Useful when spreading optional parameters on an object, as\n * TypeScript's `Partial<XYZ>` type allows `undefined` values.\n */\nexport function filterUndefined<T extends object>(obj: T): FilterUndefined<T> {\n return Object.fromEntries(Object.entries(obj).filter(([, v]) => v !== undefined)) as any;\n}\nundefined?.test(\"filterUndefined\", ({ expect }) => {\n expect(filterUndefined({})).toEqual({});\n expect(filterUndefined({ a: 1, b: 2 })).toEqual({ a: 1, b: 2 });\n expect(filterUndefined({ a: 1, b: undefined })).toEqual({ a: 1 });\n expect(filterUndefined({ a: undefined, b: undefined })).toEqual({});\n expect(filterUndefined({ a: null, b: undefined })).toEqual({ a: null });\n expect(filterUndefined({ a: 0, b: \"\", c: false, d: undefined })).toEqual({ a: 0, b: \"\", c: false });\n});\n\nexport type FilterUndefinedOrNull<T> = FilterUndefined<{ [k in keyof T]: null extends T[k] ? NonNullable<T[k]> | undefined : T[k] }>;\n\n/**\n * Returns a new object with all undefined and null values removed. Useful when spreading optional parameters on an object, as\n * TypeScript's `Partial<XYZ>` type allows `undefined` values.\n */\nexport function filterUndefinedOrNull<T extends object>(obj: T): FilterUndefinedOrNull<T> {\n return Object.fromEntries(Object.entries(obj).filter(([, v]) => v !== undefined && v !== null)) as any;\n}\nundefined?.test(\"filterUndefinedOrNull\", ({ expect }) => {\n expect(filterUndefinedOrNull({})).toEqual({});\n expect(filterUndefinedOrNull({ a: 1, b: 2 })).toEqual({ a: 1, b: 2 });\n});\n\nexport type DeepFilterUndefined<T> = T extends object ? FilterUndefined<{ [K in keyof T]: DeepFilterUndefined<T[K]> }> : T;\n\nexport function deepFilterUndefined<T extends object>(obj: T): DeepFilterUndefined<T> {\n return Object.fromEntries(Object.entries(obj).filter(([, v]) => v !== undefined).map(([k, v]) => [k, isObjectLike(v) ? deepFilterUndefined(v) : v])) as any;\n}\nundefined?.test(\"deepFilterUndefined\", ({ expect }) => {\n expect(deepFilterUndefined({ a: 1, b: undefined })).toEqual({ a: 1 });\n});\n\nexport function pick<T extends {}, K extends keyof T>(obj: T, keys: K[]): Pick<T, K> {\n return Object.fromEntries(Object.entries(obj).filter(([k]) => keys.includes(k as K))) as any;\n}\nundefined?.test(\"pick\", ({ expect }) => {\n const obj = { a: 1, b: 2, c: 3, d: 4 };\n expect(pick(obj, [\"a\", \"c\"])).toEqual({ a: 1, c: 3 });\n expect(pick(obj, [])).toEqual({});\n expect(pick(obj, [\"a\", \"e\" as keyof typeof obj])).toEqual({ a: 1 });\n // Use type assertion for empty object to avoid TypeScript error\n expect(pick({} as Record<string, unknown>, [\"a\"])).toEqual({});\n});\n\nexport function omit<T extends {}, K extends keyof T>(obj: T, keys: K[]): Omit<T, K> {\n if (!Array.isArray(keys)) throw new StackAssertionError(\"omit: keys must be an array\", { obj, keys });\n return Object.fromEntries(Object.entries(obj).filter(([k]) => !keys.includes(k as K))) as any;\n}\nundefined?.test(\"omit\", ({ expect }) => {\n const obj = { a: 1, b: 2, c: 3, d: 4 };\n expect(omit(obj, [\"a\", \"c\"])).toEqual({ b: 2, d: 4 });\n expect(omit(obj, [])).toEqual(obj);\n expect(omit(obj, [\"a\", \"e\" as keyof typeof obj])).toEqual({ b: 2, c: 3, d: 4 });\n // Use type assertion for empty object to avoid TypeScript error\n expect(omit({} as Record<string, unknown>, [\"a\"])).toEqual({});\n});\n\nexport function split<T extends {}, K extends keyof T>(obj: T, keys: K[]): [Pick<T, K>, Omit<T, K>] {\n return [pick(obj, keys), omit(obj, keys)];\n}\nundefined?.test(\"split\", ({ expect }) => {\n const obj = { a: 1, b: 2, c: 3, d: 4 };\n expect(split(obj, [\"a\", \"c\"])).toEqual([{ a: 1, c: 3 }, { b: 2, d: 4 }]);\n expect(split(obj, [])).toEqual([{}, obj]);\n expect(split(obj, [\"a\", \"e\" as keyof typeof obj])).toEqual([{ a: 1 }, { b: 2, c: 3, d: 4 }]);\n // Use type assertion for empty object to avoid TypeScript error\n expect(split({} as Record<string, unknown>, [\"a\"])).toEqual([{}, {}]);\n});\n\nexport function mapValues<T extends object, U>(obj: T, fn: (value: T extends (infer E)[] ? E : T[keyof T]) => U): Record<keyof T, U> {\n if (Array.isArray(obj)) {\n return obj.map(v => fn(v)) as any;\n }\n return Object.fromEntries(Object.entries(obj).map(([k, v]) => [k, fn(v)])) as any;\n}\nundefined?.test(\"mapValues\", ({ expect }) => {\n expect(mapValues({ a: 1, b: 2 }, v => v * 2)).toEqual({ a: 2, b: 4 });\n expect(mapValues([1, 2, 3], v => v * 2)).toEqual([2, 4, 6]);\n});\n\nexport function sortKeys<T extends object>(obj: T): T {\n if (Array.isArray(obj)) {\n return [...obj] as any;\n }\n return Object.fromEntries(Object.entries(obj).sort(([a], [b]) => stringCompare(a, b))) as any;\n}\nundefined?.test(\"sortKeys\", ({ expect }) => {\n const obj = {\n \"1\": 0,\n \"10\": 1,\n b: 2,\n \"2\": 3,\n a: 4,\n \"-3.33\": 5,\n \"-4\": 6,\n \"-3\": 7,\n abc: 8,\n \"a-b\": 9,\n ab: 10,\n ac: 11,\n aa: 12,\n aab: 13,\n };\n expect(Object.entries(sortKeys(obj))).toEqual([\n [\"1\", 0],\n [\"2\", 3],\n [\"10\", 1],\n [\"-3\", 7],\n [\"-3.33\", 5],\n [\"-4\", 6],\n [\"a\", 4],\n [\"a-b\", 9],\n [\"aa\", 12],\n [\"aab\", 13],\n [\"ab\", 10],\n [\"abc\", 8],\n [\"ac\", 11],\n [\"b\", 2],\n ]);\n});\n\nexport function deepSortKeys<T extends object>(obj: T): T {\n return sortKeys(mapValues(obj, v => isObjectLike(v) ? deepSortKeys(v) : v)) as any;\n}\nundefined?.test(\"deepSortKeys\", ({ expect }) => {\n const obj = {\n h: { i: { k: 9, j: 8 }, l: 10 },\n b: { d: 3, c: 2 },\n a: 1,\n e: [4, 5, { g: 7, f: 6 }],\n };\n const sorted = deepSortKeys(obj);\n expect(Object.entries(sorted)).toEqual([\n [\"a\", 1],\n [\"b\", { c: 2, d: 3 }],\n [\"e\", [4, 5, { f: 6, g: 7 }]],\n [\"h\", { i: { j: 8, k: 9 }, l: 10 }],\n ]);\n expect(Object.entries(sorted.b)).toEqual([\n [\"c\", 2],\n [\"d\", 3],\n ]);\n expect(Object.entries(sorted.e[2])).toEqual([\n [\"f\", 6],\n [\"g\", 7],\n ]);\n expect(Object.entries(sorted.h)).toEqual([\n [\"i\", { j: 8, k: 9 }],\n [\"l\", 10],\n ]);\n expect(Object.entries(sorted.h.i)).toEqual([\n [\"j\", 8],\n [\"k\", 9],\n ]);\n});\n\nexport function set<T extends object, K extends keyof T>(obj: T, key: K, value: T[K]) {\n Object.defineProperty(obj, key, { value, writable: true, configurable: true, enumerable: true });\n}\n\nexport function get<T extends object, K extends keyof T>(obj: T, key: K): T[K] {\n const descriptor = Object.getOwnPropertyDescriptor(obj, key);\n if (!descriptor) throw new StackAssertionError(`get: key ${String(key)} does not exist`, { obj, key });\n return descriptor.value;\n}\n\nexport function getOrUndefined<T extends object, K extends keyof T>(obj: T, key: K): T[K] | undefined {\n return has(obj, key) ? get(obj, key) : undefined;\n}\n\nexport function has<T extends object, K extends keyof T>(obj: T, key: K): obj is T & { [k in K]: unknown } {\n return Object.prototype.hasOwnProperty.call(obj, key);\n}\n\nundefined?.test(\"has\", ({ expect }) => {\n const obj = { a: 1, b: undefined, c: null };\n expect(has(obj, \"a\")).toBe(true);\n expect(has(obj, \"b\")).toBe(true);\n expect(has(obj, \"c\")).toBe(true);\n expect(has(obj, \"d\" as keyof typeof obj)).toBe(false);\n});\n\n\nexport function hasAndNotUndefined<T extends object, K extends keyof T>(obj: T, key: K): obj is T & { [k in K]: Exclude<T[K], undefined> } {\n return has(obj, key) && get(obj, key) !== undefined;\n}\n\nexport function deleteKey<T extends object, K extends keyof T>(obj: T, key: K) {\n if (has(obj, key)) {\n Reflect.deleteProperty(obj, key);\n } else {\n throw new StackAssertionError(`deleteKey: key ${String(key)} does not exist`, { obj, key });\n }\n}\n\nexport function isObjectLike(value: unknown): value is object {\n return (typeof value === 'object' || typeof value === 'function') && value !== null;\n}\n"],"mappings":";AAAA,SAAS,2BAA2B;AACpC,SAAS,gBAAgB;AACzB,SAAS,qBAAqB;AAEvB,SAAS,UAAa,OAAmC;AAC9D,SAAO,UAAU,QAAQ,U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AAG,IAAI;AACzC;AAEO,SAAS,IAAyC,KAAQ,KAA0C;AACzG,SAAO,OAAO,UAAU,eAAe,KAAK,KAAK,GAAG;AACtD;AAWO,SAAS,mBAAwD,KAAQ,KAA2D;AACzI,SAAO,IAAI,KAAK,GAAG,KAAK,IAAI,KAAK,GAAG,MAAM;AAC5C;AAEO,SAAS,UAA+C,KAAQ,KAAQ;AAC7E,MAAI,IAAI,KAAK,GAAG,GAAG;AACjB,YAAQ,eAAe,KAAK,GAAG;AAAA,EACjC,OAAO;AACL,UAAM,IAAI,oBAAoB,kBAAkB,OAAO,GAAG,CAAC,mBAAmB,EAAE,KAAK,IAAI,CAAC;AAAA,EAC5F;AACF;AAEO,SAAS,aAAa,OAAiC;AAC5D,UAAQ,OAAO,UAAU,YAAY,OAAO,UAAU,eAAe,UAAU;AACjF;","names":[]}
@@ -101,7 +101,7 @@ function runAsynchronouslyWithAlert(...args) {
101
101
  {
102
102
  ...args[1],
103
103
  onError: (error) => {
104
- if (error instanceof KnownError && typeof process !== "undefined" && process.env.NODE_ENV?.includes("production")) {
104
+ if (KnownError.isKnownError(error) && typeof process !== "undefined" && process.env.NODE_ENV?.includes("production")) {
105
105
  alert(error.message);
106
106
  } else {
107
107
  alert(`An unhandled error occurred. Please ${process.env.NODE_ENV === "development" ? `check the browser console for the full error.` : "report this to the developer."}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/utils/promises.tsx"],"sourcesContent":["import { KnownError } from \"..\";\nimport { StackAssertionError, captureError, concatStacktraces } from \"./errors\";\nimport { DependenciesMap } from \"./maps\";\nimport { Result } from \"./results\";\nimport { generateUuid } from \"./uuids\";\n\nexport type ReactPromise<T> = Promise<T> & (\n | { status: \"rejected\", reason: unknown }\n | { status: \"fulfilled\", value: T }\n | { status: \"pending\" }\n);\n\ntype Resolve<T> = (value: T) => void;\ntype Reject = (reason: unknown) => void;\nexport function createPromise<T>(callback: (resolve: Resolve<T>, reject: Reject) => void): ReactPromise<T> {\n let status = \"pending\" as \"fulfilled\" | \"rejected\" | \"pending\";\n let valueOrReason: T | unknown | undefined = undefined;\n let resolve: Resolve<T> | null = null;\n let reject: Reject | null = null;\n const promise = new Promise<T>((res, rej) => {\n resolve = (value) => {\n if (status !== \"pending\") return;\n status = \"fulfilled\";\n valueOrReason = value;\n res(value);\n };\n reject = (reason) => {\n if (status !== \"pending\") return;\n status = \"rejected\";\n valueOrReason = reason;\n rej(reason);\n };\n });\n\n callback(resolve!, reject!);\n return Object.assign(promise, {\n status: status,\n ...status === \"fulfilled\" ? { value: valueOrReason as T } : {},\n ...status === \"rejected\" ? { reason: valueOrReason } : {},\n } as any);\n}\nundefined?.test(\"createPromise\", async ({ expect }) => {\n // Test resolved promise\n const resolvedPromise = createPromise<number>((resolve) => {\n resolve(42);\n });\n expect(resolvedPromise.status).toBe(\"fulfilled\");\n expect((resolvedPromise as any).value).toBe(42);\n expect(await resolvedPromise).toBe(42);\n\n // Test rejected promise\n const error = new Error(\"Test error\");\n const rejectedPromise = createPromise<number>((_, reject) => {\n reject(error);\n });\n expect(rejectedPromise.status).toBe(\"rejected\");\n expect((rejectedPromise as any).reason).toBe(error);\n await expect(rejectedPromise).rejects.toBe(error);\n\n // Test pending promise\n const pendingPromise = createPromise<number>(() => {\n // Do nothing, leave it pending\n });\n expect(pendingPromise.status).toBe(\"pending\");\n expect((pendingPromise as any).value).toBeUndefined();\n expect((pendingPromise as any).reason).toBeUndefined();\n\n // Test that resolving after already resolved does nothing\n let resolveCount = 0;\n const multiResolvePromise = createPromise<number>((resolve) => {\n resolve(1);\n resolveCount++;\n resolve(2);\n resolveCount++;\n });\n expect(resolveCount).toBe(2); // Both resolve calls executed\n expect(multiResolvePromise.status).toBe(\"fulfilled\");\n expect((multiResolvePromise as any).value).toBe(1); // Only first resolve took effect\n expect(await multiResolvePromise).toBe(1);\n});\n\nlet resolvedCache: DependenciesMap<[unknown], ReactPromise<unknown>> | null = null;\n/**\n * Like Promise.resolve(...), but also adds the status and value properties for use with React's `use` hook, and caches\n * the value so that invoking `resolved` twice returns the same promise.\n */\nexport function resolved<T>(value: T): ReactPromise<T> {\n resolvedCache ??= new DependenciesMap<[unknown], ReactPromise<unknown>>();\n if (resolvedCache.has([value])) {\n return resolvedCache.get([value]) as ReactPromise<T>;\n }\n\n const res = Object.assign(Promise.resolve(value), {\n status: \"fulfilled\",\n value,\n } as const);\n resolvedCache.set([value], res);\n return res;\n}\nundefined?.test(\"resolved\", async ({ expect }) => {\n // Test with primitive value\n const promise1 = resolved(42);\n expect(promise1.status).toBe(\"fulfilled\");\n // Need to use type assertion since value is only available when status is \"fulfilled\"\n expect((promise1 as { value: number }).value).toBe(42);\n expect(await promise1).toBe(42);\n\n // Test with object value\n const obj = { test: true };\n const promise2 = resolved(obj);\n expect(promise2.status).toBe(\"fulfilled\");\n expect((promise2 as { value: typeof obj }).value).toBe(obj);\n expect(await promise2).toBe(obj);\n\n // Test caching (same reference for same value)\n const promise3 = resolved(42);\n expect(promise3).toBe(promise1); // Same reference due to caching\n\n // Test with different value (different reference)\n const promise4 = resolved(43);\n expect(promise4).not.toBe(promise1);\n});\n\nlet rejectedCache: DependenciesMap<[unknown], ReactPromise<unknown>> | null = null;\n/**\n * Like Promise.reject(...), but also adds the status and value properties for use with React's `use` hook, and caches\n * the value so that invoking `rejected` twice returns the same promise.\n */\nexport function rejected<T>(reason: unknown): ReactPromise<T> {\n rejectedCache ??= new DependenciesMap<[unknown], ReactPromise<unknown>>();\n if (rejectedCache.has([reason])) {\n return rejectedCache.get([reason]) as ReactPromise<T>;\n }\n\n const promise = Promise.reject(reason);\n ignoreUnhandledRejection(promise);\n const res = Object.assign(promise, {\n status: \"rejected\",\n reason: reason,\n } as const);\n rejectedCache.set([reason], res);\n return res;\n}\nundefined?.test(\"rejected\", ({ expect }) => {\n // Test with error object\n const error = new Error(\"Test error\");\n const promise1 = rejected<number>(error);\n expect(promise1.status).toBe(\"rejected\");\n // Need to use type assertion since reason is only available when status is \"rejected\"\n expect((promise1 as { reason: Error }).reason).toBe(error);\n\n // Test with string reason\n const promise2 = rejected<string>(\"error message\");\n expect(promise2.status).toBe(\"rejected\");\n expect((promise2 as { reason: string }).reason).toBe(\"error message\");\n\n // Test caching (same reference for same reason)\n const promise3 = rejected<number>(error);\n expect(promise3).toBe(promise1); // Same reference due to caching\n\n // Test with different reason (different reference)\n const differentError = new Error(\"Different error\");\n const promise4 = rejected<number>(differentError);\n expect(promise4).not.toBe(promise1);\n\n // Note: We're not using await expect(promise).rejects to avoid unhandled rejections\n});\n\n// We'll skip the rejection test for pending() since it's causing unhandled rejections\n// The function is already well tested through other tests like rejected() and createPromise()\n\n\nconst neverResolvePromise = pending(new Promise<never>(() => {}));\nexport function neverResolve(): ReactPromise<never> {\n return neverResolvePromise;\n}\nundefined?.test(\"neverResolve\", ({ expect }) => {\n const promise = neverResolve();\n expect(promise.status).toBe(\"pending\");\n expect((promise as any).value).toBeUndefined();\n expect((promise as any).reason).toBeUndefined();\n\n // Test that multiple calls return the same promise\n const promise2 = neverResolve();\n expect(promise2).toBe(promise);\n});\n\nexport function pending<T>(promise: Promise<T>, options: { disableErrorWrapping?: boolean } = {}): ReactPromise<T> {\n const res = promise.then(\n value => {\n res.status = \"fulfilled\";\n (res as any).value = value;\n return value;\n },\n actualReason => {\n res.status = \"rejected\";\n (res as any).reason = actualReason;\n throw actualReason;\n },\n ) as ReactPromise<T>;\n res.status = \"pending\";\n return res;\n}\nundefined?.test(\"pending\", async ({ expect }) => {\n // Test with a promise that resolves\n const resolvePromise = Promise.resolve(42);\n const pendingPromise = pending(resolvePromise);\n\n // Initially it should be pending\n expect(pendingPromise.status).toBe(\"pending\");\n\n // After resolution, it should be fulfilled\n await resolvePromise;\n // Need to wait a tick for the then handler to execute\n await new Promise(resolve => setTimeout(resolve, 0));\n expect(pendingPromise.status).toBe(\"fulfilled\");\n expect((pendingPromise as { value: number }).value).toBe(42);\n\n // For the rejection test, we'll use a separate test to avoid unhandled rejections\n});\n\n/**\n * Should be used to wrap Promises that are not immediately awaited, so they don't throw an unhandled promise rejection\n * error.\n *\n * Vercel kills serverless functions on unhandled promise rejection errors, so this is important.\n */\nexport function ignoreUnhandledRejection<T extends Promise<any>>(promise: T): void {\n promise.catch(() => {});\n}\nundefined?.test(\"ignoreUnhandledRejection\", async ({ expect }) => {\n // Test with a promise that resolves\n const resolvePromise = Promise.resolve(42);\n ignoreUnhandledRejection(resolvePromise);\n expect(await resolvePromise).toBe(42); // Should still resolve to the same value\n\n // Test with a promise that rejects\n // The promise should still reject, but the rejection is caught internally\n // so it doesn't cause an unhandled rejection error\n const error = new Error(\"Test error\");\n const rejectPromise = Promise.reject(error);\n ignoreUnhandledRejection(rejectPromise);\n await expect(rejectPromise).rejects.toBe(error);\n});\n\nexport async function wait(ms: number) {\n if (!Number.isFinite(ms) || ms < 0) {\n throw new StackAssertionError(`wait() requires a non-negative integer number of milliseconds to wait. (found: ${ms}ms)`);\n }\n if (ms >= 2**31) {\n throw new StackAssertionError(\"The maximum timeout for wait() is 2147483647ms (2**31 - 1). (found: ${ms}ms)\");\n }\n return await new Promise<void>(resolve => setTimeout(resolve, ms));\n}\nundefined?.test(\"wait\", async ({ expect }) => {\n // Test with valid input\n const start = Date.now();\n await wait(10);\n const elapsed = Date.now() - start;\n expect(elapsed).toBeGreaterThanOrEqual(5); // Allow some flexibility in timing\n\n // Test with zero\n await expect(wait(0)).resolves.toBeUndefined();\n\n // Test with negative number\n await expect(wait(-10)).rejects.toThrow(\"wait() requires a non-negative integer\");\n\n // Test with non-finite number\n await expect(wait(NaN)).rejects.toThrow(\"wait() requires a non-negative integer\");\n await expect(wait(Infinity)).rejects.toThrow(\"wait() requires a non-negative integer\");\n\n // Test with too large number\n await expect(wait(2**31)).rejects.toThrow(\"The maximum timeout for wait()\");\n});\n\nexport async function waitUntil(date: Date) {\n return await wait(date.getTime() - Date.now());\n}\nundefined?.test(\"waitUntil\", async ({ expect }) => {\n // Test with future date\n const futureDate = new Date(Date.now() + 10);\n const start = Date.now();\n await waitUntil(futureDate);\n const elapsed = Date.now() - start;\n expect(elapsed).toBeGreaterThanOrEqual(5); // Allow some flexibility in timing\n\n // Test with past date - this will throw because wait() requires non-negative time\n // We need to verify it throws the correct error\n try {\n await waitUntil(new Date(Date.now() - 1000));\n expect.fail(\"Should have thrown an error\");\n } catch (error) {\n expect(error).toBeInstanceOf(StackAssertionError);\n expect((error as Error).message).toContain(\"wait() requires a non-negative integer\");\n }\n});\n\nexport function runAsynchronouslyWithAlert(...args: Parameters<typeof runAsynchronously>) {\n return runAsynchronously(\n args[0],\n {\n ...args[1],\n onError: error => {\n if (error instanceof KnownError && typeof process !== \"undefined\" && (process.env.NODE_ENV as any)?.includes(\"production\")) {\n alert(error.message);\n } else {\n alert(`An unhandled error occurred. Please ${process.env.NODE_ENV === \"development\" ? `check the browser console for the full error.` : \"report this to the developer.\"}\\n\\n${error}`);\n }\n args[1]?.onError?.(error);\n },\n },\n ...args.slice(2) as [],\n );\n}\nundefined?.test(\"runAsynchronouslyWithAlert\", ({ expect }) => {\n // Simple test to verify the function calls runAsynchronously\n // We can't easily test the alert functionality without mocking\n const testFn = () => Promise.resolve(\"test\");\n const testOptions = { noErrorLogging: true };\n\n // Just verify it doesn't throw\n expect(() => runAsynchronouslyWithAlert(testFn, testOptions)).not.toThrow();\n\n // We can't easily test the error handling without mocking, so we'll\n // just verify the function exists and can be called\n expect(typeof runAsynchronouslyWithAlert).toBe(\"function\");\n});\n\nexport function runAsynchronously(\n promiseOrFunc: void | Promise<unknown> | (() => void | Promise<unknown>) | undefined,\n options: {\n noErrorLogging?: boolean,\n onError?: (error: Error) => void,\n } = {},\n): void {\n if (typeof promiseOrFunc === \"function\") {\n promiseOrFunc = promiseOrFunc();\n }\n const duringError = new Error();\n promiseOrFunc?.catch(error => {\n options.onError?.(error);\n const newError = new StackAssertionError(\n \"Uncaught error in asynchronous function: \" + error.toString(),\n { cause: error },\n );\n concatStacktraces(newError, duringError);\n if (!options.noErrorLogging) {\n captureError(\"runAsynchronously\", newError);\n }\n });\n}\nundefined?.test(\"runAsynchronously\", ({ expect }) => {\n // Simple test to verify the function exists and can be called\n const testFn = () => Promise.resolve(\"test\");\n\n // Just verify it doesn't throw\n expect(() => runAsynchronously(testFn)).not.toThrow();\n expect(() => runAsynchronously(Promise.resolve(\"test\"))).not.toThrow();\n expect(() => runAsynchronously(undefined)).not.toThrow();\n\n // We can't easily test the error handling without mocking, so we'll\n // just verify the function exists and can be called with options\n expect(() => runAsynchronously(testFn, { noErrorLogging: true })).not.toThrow();\n expect(() => runAsynchronously(testFn, { onError: () => {} })).not.toThrow();\n});\n\n\nclass TimeoutError extends Error {\n constructor(public readonly ms: number) {\n super(`Timeout after ${ms}ms`);\n this.name = \"TimeoutError\";\n }\n}\n\nexport async function timeout<T>(promise: Promise<T>, ms: number): Promise<Result<T, TimeoutError>> {\n return await Promise.race([\n promise.then(value => Result.ok(value)),\n wait(ms).then(() => Result.error(new TimeoutError(ms))),\n ]);\n}\nundefined?.test(\"timeout\", async ({ expect }) => {\n // Test with a promise that resolves quickly\n const fastPromise = Promise.resolve(42);\n const fastResult = await timeout(fastPromise, 100);\n expect(fastResult.status).toBe(\"ok\");\n if (fastResult.status === \"ok\") {\n expect(fastResult.data).toBe(42);\n }\n\n // Test with a promise that takes longer than the timeout\n const slowPromise = new Promise(resolve => setTimeout(() => resolve(\"too late\"), 50));\n const slowResult = await timeout(slowPromise, 10);\n expect(slowResult.status).toBe(\"error\");\n if (slowResult.status === \"error\") {\n expect(slowResult.error).toBeInstanceOf(TimeoutError);\n expect((slowResult.error as TimeoutError).ms).toBe(10);\n }\n});\n\nexport async function timeoutThrow<T>(promise: Promise<T>, ms: number): Promise<T> {\n return Result.orThrow(await timeout(promise, ms));\n}\nundefined?.test(\"timeoutThrow\", async ({ expect }) => {\n // Test with a promise that resolves quickly\n const fastPromise = Promise.resolve(42);\n const fastResult = await timeoutThrow(fastPromise, 100);\n expect(fastResult).toBe(42);\n\n // Test with a promise that takes longer than the timeout\n const slowPromise = new Promise(resolve => setTimeout(() => resolve(\"too late\"), 50));\n await expect(timeoutThrow(slowPromise, 10)).rejects.toThrow(\"Timeout after 10ms\");\n await expect(timeoutThrow(slowPromise, 10)).rejects.toBeInstanceOf(TimeoutError);\n});\n\n\nexport type RateLimitOptions = {\n /**\n * The number of requests to process in parallel. Currently only 1 is supported.\n */\n concurrency: 1,\n\n /**\n * If true, multiple requests waiting at the same time will be reduced to just one. Default is false.\n */\n batchCalls?: boolean,\n\n /**\n * Waits for throttleMs since the start of last request before starting the next request. Default is 0.\n */\n throttleMs?: number,\n\n /**\n * Waits for gapMs since the end of last request before starting the next request. Default is 0.\n */\n gapMs?: number,\n\n /**\n * Waits until there have been no new requests for debounceMs before starting a new request. Default is 0.\n */\n debounceMs?: number,\n};\n\nexport function rateLimited<T>(\n func: () => Promise<T>,\n options: RateLimitOptions,\n): () => Promise<T> {\n let waitUntil = performance.now();\n let queue: [(t: T) => void, (e: unknown) => void][] = [];\n let addedToQueueCallbacks = new Map<string, () => void>;\n\n const next = async () => {\n while (true) {\n if (waitUntil > performance.now()) {\n await wait(Math.max(1, waitUntil - performance.now() + 1));\n } else if (queue.length === 0) {\n const uuid = generateUuid();\n await new Promise<void>(resolve => {\n addedToQueueCallbacks.set(uuid, resolve);\n });\n addedToQueueCallbacks.delete(uuid);\n } else {\n break;\n }\n }\n const nextFuncs = options.batchCalls ? queue.splice(0, queue.length) : [queue.shift()!];\n\n const start = performance.now();\n const value = await Result.fromPromise(func());\n const end = performance.now();\n\n waitUntil = Math.max(\n waitUntil,\n start + (options.throttleMs ?? 0),\n end + (options.gapMs ?? 0),\n );\n\n for (const nextFunc of nextFuncs) {\n if (value.status === \"ok\") {\n nextFunc[0](value.data);\n } else {\n nextFunc[1](value.error);\n }\n }\n };\n\n runAsynchronously(async () => {\n while (true) {\n await next();\n }\n });\n\n return () => {\n return new Promise<T>((resolve, reject) => {\n waitUntil = Math.max(\n waitUntil,\n performance.now() + (options.debounceMs ?? 0),\n );\n queue.push([resolve, reject]);\n addedToQueueCallbacks.forEach(cb => cb());\n });\n };\n}\n\nexport function throttled<T, A extends any[]>(func: (...args: A) => Promise<T>, delayMs: number): (...args: A) => Promise<T> {\n let timeout: ReturnType<typeof setTimeout> | null = null;\n let nextAvailable: Promise<T> | null = null;\n return async (...args) => {\n while (nextAvailable !== null) {\n await nextAvailable;\n }\n nextAvailable = new Promise<T>(resolve => {\n timeout = setTimeout(() => {\n nextAvailable = null;\n resolve(func(...args));\n }, delayMs);\n });\n return await nextAvailable;\n };\n}\n"],"mappings":";AAAA,SAAS,kBAAkB;AAC3B,SAAS,qBAAqB,cAAc,yBAAyB;AACrE,SAAS,uBAAuB;AAChC,SAAS,cAAc;AACvB,SAAS,oBAAoB;AAUtB,SAAS,cAAiB,UAA0E;AACzG,MAAI,SAAS;AACb,MAAI,gBAAyC;AAC7C,MAAI,UAA6B;AACjC,MAAI,SAAwB;AAC5B,QAAM,UAAU,IAAI,QAAW,CAAC,KAAK,QAAQ;AAC3C,cAAU,CAAC,UAAU;AACnB,UAAI,WAAW,UAAW;AAC1B,eAAS;AACT,sBAAgB;AAChB,UAAI,KAAK;AAAA,IACX;AACA,aAAS,CAAC,WAAW;AACnB,UAAI,WAAW,UAAW;AAC1B,eAAS;AACT,sBAAgB;AAChB,UAAI,MAAM;AAAA,IACZ;AAAA,EACF,CAAC;AAED,WAAS,SAAU,MAAO;AAC1B,SAAO,OAAO,OAAO,SAAS;AAAA,IAC5B;AAAA,IACA,GAAG,WAAW,cAAc,EAAE,OAAO,cAAmB,IAAI,CAAC;AAAA,IAC7D,GAAG,WAAW,aAAa,EAAE,QAAQ,cAAc,IAAI,CAAC;AAAA,EAC1D,CAAQ;AACV;AAyCA,IAAI,gBAA0E;AAKvE,SAAS,SAAY,OAA2B;AACrD,oBAAkB,IAAI,gBAAkD;AACxE,MAAI,cAAc,IAAI,CAAC,KAAK,CAAC,GAAG;AAC9B,WAAO,cAAc,IAAI,CAAC,KAAK,CAAC;A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;AAAA,EACF;AAEA,oBAAkB,YAAY;AAC5B,WAAO,MAAM;AACX,YAAM,KAAK;AAAA,IACb;AAAA,EACF,CAAC;AAED,SAAO,MAAM;AACX,WAAO,IAAI,QAAW,CAAC,SAAS,WAAW;AACzC,MAAAA,aAAY,KAAK;AAAA,QACfA;AAAA,QACA,YAAY,IAAI,KAAK,QAAQ,cAAc;AAAA,MAC7C;AACA,YAAM,KAAK,CAAC,SAAS,MAAM,CAAC;AAC5B,4BAAsB,QAAQ,QAAM,GAAG,CAAC;AAAA,IAC1C,CAAC;AAAA,EACH;AACF;AAEO,SAAS,UAA8B,MAAkC,SAA6C;AAC3H,MAAIC,WAAgD;AACpD,MAAI,gBAAmC;AACvC,SAAO,UAAU,SAAS;AACxB,WAAO,kBAAkB,MAAM;AAC7B,YAAM;AAAA,IACR;AACA,oBAAgB,IAAI,QAAW,aAAW;AACxC,MAAAA,WAAU,WAAW,MAAM;AACzB,wBAAgB;AAChB,gBAAQ,KAAK,GAAG,IAAI,CAAC;AAAA,MACvB,GAAG,OAAO;AAAA,IACZ,CAAC;AACD,WAAO,MAAM;AAAA,EACf;AACF;","names":["waitUntil","timeout"]}
1
+ {"version":3,"sources":["../../../src/utils/promises.tsx"],"sourcesContent":["import { KnownError } from \"..\";\nimport { StackAssertionError, captureError, concatStacktraces } from \"./errors\";\nimport { DependenciesMap } from \"./maps\";\nimport { Result } from \"./results\";\nimport { generateUuid } from \"./uuids\";\n\nexport type ReactPromise<T> = Promise<T> & (\n | { status: \"rejected\", reason: unknown }\n | { status: \"fulfilled\", value: T }\n | { status: \"pending\" }\n);\n\ntype Resolve<T> = (value: T) => void;\ntype Reject = (reason: unknown) => void;\nexport function createPromise<T>(callback: (resolve: Resolve<T>, reject: Reject) => void): ReactPromise<T> {\n let status = \"pending\" as \"fulfilled\" | \"rejected\" | \"pending\";\n let valueOrReason: T | unknown | undefined = undefined;\n let resolve: Resolve<T> | null = null;\n let reject: Reject | null = null;\n const promise = new Promise<T>((res, rej) => {\n resolve = (value) => {\n if (status !== \"pending\") return;\n status = \"fulfilled\";\n valueOrReason = value;\n res(value);\n };\n reject = (reason) => {\n if (status !== \"pending\") return;\n status = \"rejected\";\n valueOrReason = reason;\n rej(reason);\n };\n });\n\n callback(resolve!, reject!);\n return Object.assign(promise, {\n status: status,\n ...status === \"fulfilled\" ? { value: valueOrReason as T } : {},\n ...status === \"rejected\" ? { reason: valueOrReason } : {},\n } as any);\n}\nundefined?.test(\"createPromise\", async ({ expect }) => {\n // Test resolved promise\n const resolvedPromise = createPromise<number>((resolve) => {\n resolve(42);\n });\n expect(resolvedPromise.status).toBe(\"fulfilled\");\n expect((resolvedPromise as any).value).toBe(42);\n expect(await resolvedPromise).toBe(42);\n\n // Test rejected promise\n const error = new Error(\"Test error\");\n const rejectedPromise = createPromise<number>((_, reject) => {\n reject(error);\n });\n expect(rejectedPromise.status).toBe(\"rejected\");\n expect((rejectedPromise as any).reason).toBe(error);\n await expect(rejectedPromise).rejects.toBe(error);\n\n // Test pending promise\n const pendingPromise = createPromise<number>(() => {\n // Do nothing, leave it pending\n });\n expect(pendingPromise.status).toBe(\"pending\");\n expect((pendingPromise as any).value).toBeUndefined();\n expect((pendingPromise as any).reason).toBeUndefined();\n\n // Test that resolving after already resolved does nothing\n let resolveCount = 0;\n const multiResolvePromise = createPromise<number>((resolve) => {\n resolve(1);\n resolveCount++;\n resolve(2);\n resolveCount++;\n });\n expect(resolveCount).toBe(2); // Both resolve calls executed\n expect(multiResolvePromise.status).toBe(\"fulfilled\");\n expect((multiResolvePromise as any).value).toBe(1); // Only first resolve took effect\n expect(await multiResolvePromise).toBe(1);\n});\n\nlet resolvedCache: DependenciesMap<[unknown], ReactPromise<unknown>> | null = null;\n/**\n * Like Promise.resolve(...), but also adds the status and value properties for use with React's `use` hook, and caches\n * the value so that invoking `resolved` twice returns the same promise.\n */\nexport function resolved<T>(value: T): ReactPromise<T> {\n resolvedCache ??= new DependenciesMap<[unknown], ReactPromise<unknown>>();\n if (resolvedCache.has([value])) {\n return resolvedCache.get([value]) as ReactPromise<T>;\n }\n\n const res = Object.assign(Promise.resolve(value), {\n status: \"fulfilled\",\n value,\n } as const);\n resolvedCache.set([value], res);\n return res;\n}\nundefined?.test(\"resolved\", async ({ expect }) => {\n // Test with primitive value\n const promise1 = resolved(42);\n expect(promise1.status).toBe(\"fulfilled\");\n // Need to use type assertion since value is only available when status is \"fulfilled\"\n expect((promise1 as { value: number }).value).toBe(42);\n expect(await promise1).toBe(42);\n\n // Test with object value\n const obj = { test: true };\n const promise2 = resolved(obj);\n expect(promise2.status).toBe(\"fulfilled\");\n expect((promise2 as { value: typeof obj }).value).toBe(obj);\n expect(await promise2).toBe(obj);\n\n // Test caching (same reference for same value)\n const promise3 = resolved(42);\n expect(promise3).toBe(promise1); // Same reference due to caching\n\n // Test with different value (different reference)\n const promise4 = resolved(43);\n expect(promise4).not.toBe(promise1);\n});\n\nlet rejectedCache: DependenciesMap<[unknown], ReactPromise<unknown>> | null = null;\n/**\n * Like Promise.reject(...), but also adds the status and value properties for use with React's `use` hook, and caches\n * the value so that invoking `rejected` twice returns the same promise.\n */\nexport function rejected<T>(reason: unknown): ReactPromise<T> {\n rejectedCache ??= new DependenciesMap<[unknown], ReactPromise<unknown>>();\n if (rejectedCache.has([reason])) {\n return rejectedCache.get([reason]) as ReactPromise<T>;\n }\n\n const promise = Promise.reject(reason);\n ignoreUnhandledRejection(promise);\n const res = Object.assign(promise, {\n status: \"rejected\",\n reason: reason,\n } as const);\n rejectedCache.set([reason], res);\n return res;\n}\nundefined?.test(\"rejected\", ({ expect }) => {\n // Test with error object\n const error = new Error(\"Test error\");\n const promise1 = rejected<number>(error);\n expect(promise1.status).toBe(\"rejected\");\n // Need to use type assertion since reason is only available when status is \"rejected\"\n expect((promise1 as { reason: Error }).reason).toBe(error);\n\n // Test with string reason\n const promise2 = rejected<string>(\"error message\");\n expect(promise2.status).toBe(\"rejected\");\n expect((promise2 as { reason: string }).reason).toBe(\"error message\");\n\n // Test caching (same reference for same reason)\n const promise3 = rejected<number>(error);\n expect(promise3).toBe(promise1); // Same reference due to caching\n\n // Test with different reason (different reference)\n const differentError = new Error(\"Different error\");\n const promise4 = rejected<number>(differentError);\n expect(promise4).not.toBe(promise1);\n\n // Note: We're not using await expect(promise).rejects to avoid unhandled rejections\n});\n\n// We'll skip the rejection test for pending() since it's causing unhandled rejections\n// The function is already well tested through other tests like rejected() and createPromise()\n\n\nconst neverResolvePromise = pending(new Promise<never>(() => {}));\nexport function neverResolve(): ReactPromise<never> {\n return neverResolvePromise;\n}\nundefined?.test(\"neverResolve\", ({ expect }) => {\n const promise = neverResolve();\n expect(promise.status).toBe(\"pending\");\n expect((promise as any).value).toBeUndefined();\n expect((promise as any).reason).toBeUndefined();\n\n // Test that multiple calls return the same promise\n const promise2 = neverResolve();\n expect(promise2).toBe(promise);\n});\n\nexport function pending<T>(promise: Promise<T>, options: { disableErrorWrapping?: boolean } = {}): ReactPromise<T> {\n const res = promise.then(\n value => {\n res.status = \"fulfilled\";\n (res as any).value = value;\n return value;\n },\n actualReason => {\n res.status = \"rejected\";\n (res as any).reason = actualReason;\n throw actualReason;\n },\n ) as ReactPromise<T>;\n res.status = \"pending\";\n return res;\n}\nundefined?.test(\"pending\", async ({ expect }) => {\n // Test with a promise that resolves\n const resolvePromise = Promise.resolve(42);\n const pendingPromise = pending(resolvePromise);\n\n // Initially it should be pending\n expect(pendingPromise.status).toBe(\"pending\");\n\n // After resolution, it should be fulfilled\n await resolvePromise;\n // Need to wait a tick for the then handler to execute\n await new Promise(resolve => setTimeout(resolve, 0));\n expect(pendingPromise.status).toBe(\"fulfilled\");\n expect((pendingPromise as { value: number }).value).toBe(42);\n\n // For the rejection test, we'll use a separate test to avoid unhandled rejections\n});\n\n/**\n * Should be used to wrap Promises that are not immediately awaited, so they don't throw an unhandled promise rejection\n * error.\n *\n * Vercel kills serverless functions on unhandled promise rejection errors, so this is important.\n */\nexport function ignoreUnhandledRejection<T extends Promise<any>>(promise: T): void {\n promise.catch(() => {});\n}\nundefined?.test(\"ignoreUnhandledRejection\", async ({ expect }) => {\n // Test with a promise that resolves\n const resolvePromise = Promise.resolve(42);\n ignoreUnhandledRejection(resolvePromise);\n expect(await resolvePromise).toBe(42); // Should still resolve to the same value\n\n // Test with a promise that rejects\n // The promise should still reject, but the rejection is caught internally\n // so it doesn't cause an unhandled rejection error\n const error = new Error(\"Test error\");\n const rejectPromise = Promise.reject(error);\n ignoreUnhandledRejection(rejectPromise);\n await expect(rejectPromise).rejects.toBe(error);\n});\n\nexport async function wait(ms: number) {\n if (!Number.isFinite(ms) || ms < 0) {\n throw new StackAssertionError(`wait() requires a non-negative integer number of milliseconds to wait. (found: ${ms}ms)`);\n }\n if (ms >= 2**31) {\n throw new StackAssertionError(\"The maximum timeout for wait() is 2147483647ms (2**31 - 1). (found: ${ms}ms)\");\n }\n return await new Promise<void>(resolve => setTimeout(resolve, ms));\n}\nundefined?.test(\"wait\", async ({ expect }) => {\n // Test with valid input\n const start = Date.now();\n await wait(10);\n const elapsed = Date.now() - start;\n expect(elapsed).toBeGreaterThanOrEqual(5); // Allow some flexibility in timing\n\n // Test with zero\n await expect(wait(0)).resolves.toBeUndefined();\n\n // Test with negative number\n await expect(wait(-10)).rejects.toThrow(\"wait() requires a non-negative integer\");\n\n // Test with non-finite number\n await expect(wait(NaN)).rejects.toThrow(\"wait() requires a non-negative integer\");\n await expect(wait(Infinity)).rejects.toThrow(\"wait() requires a non-negative integer\");\n\n // Test with too large number\n await expect(wait(2**31)).rejects.toThrow(\"The maximum timeout for wait()\");\n});\n\nexport async function waitUntil(date: Date) {\n return await wait(date.getTime() - Date.now());\n}\nundefined?.test(\"waitUntil\", async ({ expect }) => {\n // Test with future date\n const futureDate = new Date(Date.now() + 10);\n const start = Date.now();\n await waitUntil(futureDate);\n const elapsed = Date.now() - start;\n expect(elapsed).toBeGreaterThanOrEqual(5); // Allow some flexibility in timing\n\n // Test with past date - this will throw because wait() requires non-negative time\n // We need to verify it throws the correct error\n try {\n await waitUntil(new Date(Date.now() - 1000));\n expect.fail(\"Should have thrown an error\");\n } catch (error) {\n expect(error).toBeInstanceOf(StackAssertionError);\n expect((error as Error).message).toContain(\"wait() requires a non-negative integer\");\n }\n});\n\nexport function runAsynchronouslyWithAlert(...args: Parameters<typeof runAsynchronously>) {\n return runAsynchronously(\n args[0],\n {\n ...args[1],\n onError: error => {\n if (KnownError.isKnownError(error) && typeof process !== \"undefined\" && (process.env.NODE_ENV as any)?.includes(\"production\")) {\n alert(error.message);\n } else {\n alert(`An unhandled error occurred. Please ${process.env.NODE_ENV === \"development\" ? `check the browser console for the full error.` : \"report this to the developer.\"}\\n\\n${error}`);\n }\n args[1]?.onError?.(error);\n },\n },\n ...args.slice(2) as [],\n );\n}\nundefined?.test(\"runAsynchronouslyWithAlert\", ({ expect }) => {\n // Simple test to verify the function calls runAsynchronously\n // We can't easily test the alert functionality without mocking\n const testFn = () => Promise.resolve(\"test\");\n const testOptions = { noErrorLogging: true };\n\n // Just verify it doesn't throw\n expect(() => runAsynchronouslyWithAlert(testFn, testOptions)).not.toThrow();\n\n // We can't easily test the error handling without mocking, so we'll\n // just verify the function exists and can be called\n expect(typeof runAsynchronouslyWithAlert).toBe(\"function\");\n});\n\nexport function runAsynchronously(\n promiseOrFunc: void | Promise<unknown> | (() => void | Promise<unknown>) | undefined,\n options: {\n noErrorLogging?: boolean,\n onError?: (error: Error) => void,\n } = {},\n): void {\n if (typeof promiseOrFunc === \"function\") {\n promiseOrFunc = promiseOrFunc();\n }\n const duringError = new Error();\n promiseOrFunc?.catch(error => {\n options.onError?.(error);\n const newError = new StackAssertionError(\n \"Uncaught error in asynchronous function: \" + error.toString(),\n { cause: error },\n );\n concatStacktraces(newError, duringError);\n if (!options.noErrorLogging) {\n captureError(\"runAsynchronously\", newError);\n }\n });\n}\nundefined?.test(\"runAsynchronously\", ({ expect }) => {\n // Simple test to verify the function exists and can be called\n const testFn = () => Promise.resolve(\"test\");\n\n // Just verify it doesn't throw\n expect(() => runAsynchronously(testFn)).not.toThrow();\n expect(() => runAsynchronously(Promise.resolve(\"test\"))).not.toThrow();\n expect(() => runAsynchronously(undefined)).not.toThrow();\n\n // We can't easily test the error handling without mocking, so we'll\n // just verify the function exists and can be called with options\n expect(() => runAsynchronously(testFn, { noErrorLogging: true })).not.toThrow();\n expect(() => runAsynchronously(testFn, { onError: () => {} })).not.toThrow();\n});\n\n\nclass TimeoutError extends Error {\n constructor(public readonly ms: number) {\n super(`Timeout after ${ms}ms`);\n this.name = \"TimeoutError\";\n }\n}\n\nexport async function timeout<T>(promise: Promise<T>, ms: number): Promise<Result<T, TimeoutError>> {\n return await Promise.race([\n promise.then(value => Result.ok(value)),\n wait(ms).then(() => Result.error(new TimeoutError(ms))),\n ]);\n}\nundefined?.test(\"timeout\", async ({ expect }) => {\n // Test with a promise that resolves quickly\n const fastPromise = Promise.resolve(42);\n const fastResult = await timeout(fastPromise, 100);\n expect(fastResult.status).toBe(\"ok\");\n if (fastResult.status === \"ok\") {\n expect(fastResult.data).toBe(42);\n }\n\n // Test with a promise that takes longer than the timeout\n const slowPromise = new Promise(resolve => setTimeout(() => resolve(\"too late\"), 50));\n const slowResult = await timeout(slowPromise, 10);\n expect(slowResult.status).toBe(\"error\");\n if (slowResult.status === \"error\") {\n expect(slowResult.error).toBeInstanceOf(TimeoutError);\n expect((slowResult.error as TimeoutError).ms).toBe(10);\n }\n});\n\nexport async function timeoutThrow<T>(promise: Promise<T>, ms: number): Promise<T> {\n return Result.orThrow(await timeout(promise, ms));\n}\nundefined?.test(\"timeoutThrow\", async ({ expect }) => {\n // Test with a promise that resolves quickly\n const fastPromise = Promise.resolve(42);\n const fastResult = await timeoutThrow(fastPromise, 100);\n expect(fastResult).toBe(42);\n\n // Test with a promise that takes longer than the timeout\n const slowPromise = new Promise(resolve => setTimeout(() => resolve(\"too late\"), 50));\n await expect(timeoutThrow(slowPromise, 10)).rejects.toThrow(\"Timeout after 10ms\");\n await expect(timeoutThrow(slowPromise, 10)).rejects.toBeInstanceOf(TimeoutError);\n});\n\n\nexport type RateLimitOptions = {\n /**\n * The number of requests to process in parallel. Currently only 1 is supported.\n */\n concurrency: 1,\n\n /**\n * If true, multiple requests waiting at the same time will be reduced to just one. Default is false.\n */\n batchCalls?: boolean,\n\n /**\n * Waits for throttleMs since the start of last request before starting the next request. Default is 0.\n */\n throttleMs?: number,\n\n /**\n * Waits for gapMs since the end of last request before starting the next request. Default is 0.\n */\n gapMs?: number,\n\n /**\n * Waits until there have been no new requests for debounceMs before starting a new request. Default is 0.\n */\n debounceMs?: number,\n};\n\nexport function rateLimited<T>(\n func: () => Promise<T>,\n options: RateLimitOptions,\n): () => Promise<T> {\n let waitUntil = performance.now();\n let queue: [(t: T) => void, (e: unknown) => void][] = [];\n let addedToQueueCallbacks = new Map<string, () => void>;\n\n const next = async () => {\n while (true) {\n if (waitUntil > performance.now()) {\n await wait(Math.max(1, waitUntil - performance.now() + 1));\n } else if (queue.length === 0) {\n const uuid = generateUuid();\n await new Promise<void>(resolve => {\n addedToQueueCallbacks.set(uuid, resolve);\n });\n addedToQueueCallbacks.delete(uuid);\n } else {\n break;\n }\n }\n const nextFuncs = options.batchCalls ? queue.splice(0, queue.length) : [queue.shift()!];\n\n const start = performance.now();\n const value = await Result.fromPromise(func());\n const end = performance.now();\n\n waitUntil = Math.max(\n waitUntil,\n start + (options.throttleMs ?? 0),\n end + (options.gapMs ?? 0),\n );\n\n for (const nextFunc of nextFuncs) {\n if (value.status === \"ok\") {\n nextFunc[0](value.data);\n } else {\n nextFunc[1](value.error);\n }\n }\n };\n\n runAsynchronously(async () => {\n while (true) {\n await next();\n }\n });\n\n return () => {\n return new Promise<T>((resolve, reject) => {\n waitUntil = Math.max(\n waitUntil,\n performance.now() + (options.debounceMs ?? 0),\n );\n queue.push([resolve, reject]);\n addedToQueueCallbacks.forEach(cb => cb());\n });\n };\n}\n\nexport function throttled<T, A extends any[]>(func: (...args: A) => Promise<T>, delayMs: number): (...args: A) => Promise<T> {\n let timeout: ReturnType<typeof setTimeout> | null = null;\n let nextAvailable: Promise<T> | null = null;\n return async (...args) => {\n while (nextAvailable !== null) {\n await nextAvailable;\n }\n nextAvailable = new Promise<T>(resolve => {\n timeout = setTimeout(() => {\n nextAvailable = null;\n resolve(func(...args));\n }, delayMs);\n });\n return await nextAvailable;\n };\n}\n"],"mappings":";AAAA,SAAS,kBAAkB;AAC3B,SAAS,qBAAqB,cAAc,yBAAyB;AACrE,SAAS,uBAAuB;AAChC,SAAS,cAAc;AACvB,SAAS,oBAAoB;AAUtB,SAAS,cAAiB,UAA0E;AACzG,MAAI,SAAS;AACb,MAAI,gBAAyC;AAC7C,MAAI,UAA6B;AACjC,MAAI,SAAwB;AAC5B,QAAM,UAAU,IAAI,QAAW,CAAC,KAAK,QAAQ;AAC3C,cAAU,CAAC,UAAU;AACnB,UAAI,WAAW,UAAW;AAC1B,eAAS;AACT,sBAAgB;AAChB,UAAI,KAAK;AAAA,IACX;AACA,aAAS,CAAC,WAAW;AACnB,UAAI,WAAW,UAAW;AAC1B,eAAS;AACT,sBAAgB;AAChB,UAAI,MAAM;AAAA,IACZ;AAAA,EACF,CAAC;AAED,WAAS,SAAU,MAAO;AAC1B,SAAO,OAAO,OAAO,SAAS;AAAA,IAC5B;AAAA,IACA,GAAG,WAAW,cAAc,EAAE,OAAO,cAAmB,IAAI,CAAC;AAAA,IAC7D,GAAG,WAAW,aAAa,EAAE,QAAQ,cAAc,IAAI,CAAC;AAAA,EAC1D,CAAQ;AACV;AAyCA,IAAI,gBAA0E;AAKvE,SAAS,SAAY,OAA2B;AACrD,oBAAkB,IAAI,gBAAkD;AACxE,MAAI,cAAc,IAAI,CAAC,KAAK,CAAC,GAAG;AAC9B,WAAO,cAAc,IAAI,CAAC,KAAK,CAAC;AAAA,EAClC;AAEA,QAAM,MAAM,OAAO,OAAO,QAAQ,QAAQ,KAAK,GAAG;AAAA,IAChD,QAAQ;AAAA,IACR;AAAA,EACF,CAAU;AACV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AAM;AACX,WAAO,IAAI,QAAW,CAAC,SAAS,WAAW;AACzC,MAAAA,aAAY,KAAK;AAAA,QACfA;AAAA,QACA,YAAY,IAAI,KAAK,QAAQ,cAAc;AAAA,MAC7C;AACA,YAAM,KAAK,CAAC,SAAS,MAAM,CAAC;AAC5B,4BAAsB,QAAQ,QAAM,GAAG,CAAC;AAAA,IAC1C,CAAC;AAAA,EACH;AACF;AAEO,SAAS,UAA8B,MAAkC,SAA6C;AAC3H,MAAIC,WAAgD;AACpD,MAAI,gBAAmC;AACvC,SAAO,UAAU,SAAS;AACxB,WAAO,kBAAkB,MAAM;AAC7B,YAAM;AAAA,IACR;AACA,oBAAgB,IAAI,QAAW,aAAW;AACxC,MAAAA,WAAU,WAAW,MAAM;AACzB,wBAAgB;AAChB,gBAAQ,KAAK,GAAG,IAAI,CAAC;AAAA,MACvB,GAAG,OAAO;AAAA,IACZ,CAAC;AACD,WAAO,MAAM;AAAA,EACf;AACF;","names":["waitUntil","timeout"]}
@@ -14,6 +14,7 @@ function typedCapitalize(s) {
14
14
  return s.charAt(0).toUpperCase() + s.slice(1);
15
15
  }
16
16
  function stringCompare(a, b) {
17
+ if (typeof a !== "string" || typeof b !== "string") throw new StackAssertionError(`Expected two strings for stringCompare, found ${typeof a} and ${typeof b}`, { a, b });
17
18
  const cmp = (a2, b2) => a2 < b2 ? -1 : a2 > b2 ? 1 : 0;
18
19
  return cmp(a.toUpperCase(), b.toUpperCase()) || cmp(b, a);
19
20
  }