@inbeat/core 0.0.0-stage → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md ADDED
@@ -0,0 +1,76 @@
1
+ # Changelog
2
+
3
+ ## [0.7.0](https://github.com/Genoux/ib-toolkit/compare/core-v0.6.1...core-v0.7.0) (2026-10-01)
4
+
5
+
6
+ ### ⚠ BREAKING CHANGES
7
+
8
+ * consumers must drop the @inbeat registry line from .npmrc/bunfig and the NODE_AUTH_TOKEN setup.
9
+
10
+ ### Features
11
+
12
+ * publish [@inbeat](https://github.com/inbeat) packages publicly on npm ([#27](https://github.com/Genoux/ib-toolkit/issues/27)) ([2bd9f53](https://github.com/Genoux/ib-toolkit/commit/2bd9f53c2d4dd030bdee037b8b1dce1e1bb828b5))
13
+
14
+ ## [0.6.1](https://github.com/Genoux/ib-toolkit/compare/core-v0.6.0...core-v0.6.1) (2026-10-01)
15
+
16
+
17
+ ### Miscellaneous Chores
18
+
19
+ * **core:** Synchronize inbeat versions
20
+
21
+ ## [0.6.0](https://github.com/Genoux/ib-toolkit/compare/core-v0.5.0...core-v0.6.0) (2026-10-01)
22
+
23
+
24
+ ### Miscellaneous Chores
25
+
26
+ * **core:** Synchronize inbeat versions
27
+
28
+ ## [0.5.0](https://github.com/Genoux/ib-toolkit/compare/core-v0.4.0...core-v0.5.0) (2026-10-01)
29
+
30
+
31
+ ### ⚠ BREAKING CHANGES
32
+
33
+ * **standards:** `ib add` is removed (use the vendor init CLIs); `ib check` now requires the shared config presets.
34
+
35
+ ### Features
36
+
37
+ * **standards:** drop add-ons, add ib mcp, enforce shared presets ([#17](https://github.com/Genoux/ib-toolkit/issues/17)) ([9eb8410](https://github.com/Genoux/ib-toolkit/commit/9eb84108432dda5e2a2da312a7bc70299e09c0c9))
38
+
39
+ ## [0.4.0](https://github.com/Genoux/ib-toolkit/compare/core-v0.3.0...core-v0.4.0) (2026-09-30)
40
+
41
+
42
+ ### ⚠ BREAKING CHANGES
43
+
44
+ * **standards:** sync skills to .agents/skills only ([#15](https://github.com/Genoux/ib-toolkit/issues/15))
45
+
46
+ ### Features
47
+
48
+ * **standards:** sync skills to .agents/skills only ([#15](https://github.com/Genoux/ib-toolkit/issues/15)) ([cd3e8a2](https://github.com/Genoux/ib-toolkit/commit/cd3e8a21f028790ad84c26dc1cc832475885c461))
49
+
50
+ ## [0.3.0](https://github.com/Genoux/ib-toolkit/compare/core-v0.2.0...core-v0.3.0) (2026-09-30)
51
+
52
+
53
+ ### Miscellaneous Chores
54
+
55
+ * **core:** Synchronize inbeat versions
56
+
57
+ ## [0.2.0](https://github.com/Genoux/ib-toolkit/compare/core-v0.1.2...core-v0.2.0) (2026-09-30)
58
+
59
+
60
+ ### Miscellaneous Chores
61
+
62
+ * **core:** Synchronize inbeat versions
63
+
64
+ ## [0.1.2](https://github.com/Genoux/ib-toolkit/compare/core-v0.1.1...core-v0.1.2) (2026-09-30)
65
+
66
+
67
+ ### Bug Fixes
68
+
69
+ * resolve workspace ranges from manifests on publish ([#5](https://github.com/Genoux/ib-toolkit/issues/5)) ([0f4328e](https://github.com/Genoux/ib-toolkit/commit/0f4328eb0897501380880f429a952d9d228563a2))
70
+
71
+ ## [0.1.1](https://github.com/Genoux/ib-toolkit/compare/core-v0.1.0...core-v0.1.1) (2026-09-30)
72
+
73
+
74
+ ### Bug Fixes
75
+
76
+ * ship compiled js from core and next ([#3](https://github.com/Genoux/ib-toolkit/issues/3)) ([8fef50a](https://github.com/Genoux/ib-toolkit/commit/8fef50aa87679bcf3c328fe4ca11a351434e2dda))
@@ -0,0 +1,4 @@
1
+ export declare function normalizeEmail(email: string): string;
2
+ export declare function emailDomain(email: string): string | null;
3
+ /** Exact domain match: `a@evil-inbeat.agency` and `a@inbeat.agency.evil.com` never pass. */
4
+ export declare function isEmailInDomains(email: string, domains: readonly string[]): boolean;
package/dist/email.js ADDED
@@ -0,0 +1,13 @@
1
+ export function normalizeEmail(email) {
2
+ return email.trim().toLowerCase();
3
+ }
4
+ export function emailDomain(email) {
5
+ const normalized = normalizeEmail(email);
6
+ const at = normalized.lastIndexOf("@");
7
+ return at > 0 && at < normalized.length - 1 ? normalized.slice(at + 1) : null;
8
+ }
9
+ /** Exact domain match: `a@evil-inbeat.agency` and `a@inbeat.agency.evil.com` never pass. */
10
+ export function isEmailInDomains(email, domains) {
11
+ const domain = emailDomain(email);
12
+ return domain !== null && domains.some((allowed) => normalizeEmail(allowed) === domain);
13
+ }
package/dist/env.d.ts ADDED
@@ -0,0 +1,57 @@
1
+ import { z } from "zod";
2
+ /** Comma-separated list, trimmed, lowercased, empties dropped. */
3
+ export declare const csv: () => z.ZodPipe<z.ZodString, z.ZodTransform<string[], string>>;
4
+ export declare const dbEnv: {
5
+ DATABASE_URL: z.ZodURL;
6
+ };
7
+ export declare const appUrlEnv: {
8
+ APP_URL: z.ZodOptional<z.ZodPipe<z.ZodURL, z.ZodTransform<string, string>>>;
9
+ VERCEL_ENV: z.ZodOptional<z.ZodEnum<{
10
+ production: "production";
11
+ preview: "preview";
12
+ development: "development";
13
+ }>>;
14
+ VERCEL_URL: z.ZodOptional<z.ZodString>;
15
+ VERCEL_PROJECT_PRODUCTION_URL: z.ZodOptional<z.ZodString>;
16
+ };
17
+ type AppUrlEnv = {
18
+ APP_URL?: string;
19
+ VERCEL_ENV?: "production" | "preview" | "development";
20
+ VERCEL_URL?: string;
21
+ VERCEL_PROJECT_PRODUCTION_URL?: string;
22
+ };
23
+ /**
24
+ * Absolute origin for links that leave the app (emails, share links, OAuth redirects).
25
+ * Never derived from request headers: Host / X-Forwarded-Host are client-controlled.
26
+ */
27
+ export declare function resolveAppUrl(env: AppUrlEnv): string;
28
+ export declare const clerkServerEnv: {
29
+ CLERK_SECRET_KEY: z.ZodString;
30
+ CLERK_WEBHOOK_SIGNING_SECRET: z.ZodOptional<z.ZodString>;
31
+ };
32
+ export declare const clerkClientEnv: {
33
+ NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY: z.ZodString;
34
+ };
35
+ export declare const sentryClientEnv: {
36
+ NEXT_PUBLIC_SENTRY_DSN: z.ZodOptional<z.ZodURL>;
37
+ };
38
+ export declare const upstashEnv: {
39
+ UPSTASH_REDIS_REST_URL: z.ZodOptional<z.ZodURL>;
40
+ UPSTASH_REDIS_REST_TOKEN: z.ZodOptional<z.ZodString>;
41
+ };
42
+ export declare const r2Env: {
43
+ R2_ACCOUNT_ID: z.ZodString;
44
+ R2_ACCESS_KEY_ID: z.ZodString;
45
+ R2_SECRET_ACCESS_KEY: z.ZodString;
46
+ R2_BUCKET_NAME: z.ZodString;
47
+ };
48
+ export declare const maintenanceEnv: {
49
+ MAINTENANCE_MODE: z.ZodPipe<z.ZodOptional<z.ZodEnum<{
50
+ 0: "0";
51
+ 1: "1";
52
+ true: "true";
53
+ false: "false";
54
+ }>>, z.ZodTransform<boolean, "0" | "1" | "true" | "false" | undefined>>;
55
+ MAINTENANCE_BYPASS_EMAILS: z.ZodDefault<z.ZodOptional<z.ZodPipe<z.ZodString, z.ZodTransform<string[], string>>>>;
56
+ };
57
+ export {};
package/dist/env.js ADDED
@@ -0,0 +1,56 @@
1
+ import { z } from "zod";
2
+ /** Comma-separated list, trimmed, lowercased, empties dropped. */
3
+ export const csv = () => z.string().transform((value) => value
4
+ .split(",")
5
+ .map((item) => item.trim().toLowerCase())
6
+ .filter(Boolean));
7
+ const booleanFlag = () => z
8
+ .enum(["true", "false", "1", "0"])
9
+ .optional()
10
+ .transform((value) => value === "true" || value === "1");
11
+ export const dbEnv = {
12
+ DATABASE_URL: z.url(),
13
+ };
14
+ export const appUrlEnv = {
15
+ APP_URL: z
16
+ .url()
17
+ .transform((value) => value.replace(/\/+$/, ""))
18
+ .optional(),
19
+ VERCEL_ENV: z.enum(["production", "preview", "development"]).optional(),
20
+ VERCEL_URL: z.string().min(1).optional(),
21
+ VERCEL_PROJECT_PRODUCTION_URL: z.string().min(1).optional(),
22
+ };
23
+ /**
24
+ * Absolute origin for links that leave the app (emails, share links, OAuth redirects).
25
+ * Never derived from request headers: Host / X-Forwarded-Host are client-controlled.
26
+ */
27
+ export function resolveAppUrl(env) {
28
+ if (env.APP_URL)
29
+ return env.APP_URL;
30
+ const host = env.VERCEL_ENV === "production" ? env.VERCEL_PROJECT_PRODUCTION_URL : env.VERCEL_URL;
31
+ return host ? `https://${host}` : "http://localhost:3000";
32
+ }
33
+ export const clerkServerEnv = {
34
+ CLERK_SECRET_KEY: z.string().startsWith("sk_"),
35
+ CLERK_WEBHOOK_SIGNING_SECRET: z.string().startsWith("whsec_").optional(),
36
+ };
37
+ export const clerkClientEnv = {
38
+ NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY: z.string().startsWith("pk_"),
39
+ };
40
+ export const sentryClientEnv = {
41
+ NEXT_PUBLIC_SENTRY_DSN: z.url().optional(),
42
+ };
43
+ export const upstashEnv = {
44
+ UPSTASH_REDIS_REST_URL: z.url().optional(),
45
+ UPSTASH_REDIS_REST_TOKEN: z.string().min(1).optional(),
46
+ };
47
+ export const r2Env = {
48
+ R2_ACCOUNT_ID: z.string().min(1),
49
+ R2_ACCESS_KEY_ID: z.string().min(1),
50
+ R2_SECRET_ACCESS_KEY: z.string().min(1),
51
+ R2_BUCKET_NAME: z.string().min(1),
52
+ };
53
+ export const maintenanceEnv = {
54
+ MAINTENANCE_MODE: booleanFlag(),
55
+ MAINTENANCE_BYPASS_EMAILS: csv().optional().default([]),
56
+ };
@@ -0,0 +1,29 @@
1
+ export type AppErrorKind = "validation" | "auth" | "forbidden" | "not_found" | "conflict" | "rate_limited" | "db_transient" | "db_query" | "timeout" | "external_service" | "unknown";
2
+ export declare const APP_ERROR_MESSAGES: {
3
+ readonly generic: "Something went wrong. Please try again or contact us.";
4
+ readonly auth: "Please sign in to continue.";
5
+ readonly forbidden: "You don't have access to this.";
6
+ readonly notFound: "We couldn't find what you were looking for.";
7
+ readonly rateLimited: "Too many attempts. Please wait a moment and try again.";
8
+ readonly dbTransient: "We're having trouble saving this right now. Please try again in a minute.";
9
+ readonly timeout: "This is taking longer than expected. Please retry.";
10
+ readonly validationFallback: "Some of the information provided could not be validated. Please try again.";
11
+ };
12
+ export declare const APP_ERROR_STATUS: Record<AppErrorKind, number>;
13
+ export type AppErrorOptions = {
14
+ safeMessage?: string;
15
+ cause?: unknown;
16
+ reportToSentry?: boolean;
17
+ isRetryable?: boolean;
18
+ };
19
+ declare const APP_ERROR_BRAND: unique symbol;
20
+ export declare class AppError extends Error {
21
+ readonly [APP_ERROR_BRAND] = true;
22
+ readonly kind: AppErrorKind;
23
+ readonly safeMessage: string;
24
+ readonly reportToSentry: boolean;
25
+ readonly isRetryable: boolean;
26
+ constructor(kind: AppErrorKind, message: string, options?: AppErrorOptions);
27
+ }
28
+ export declare function isAppError(err: unknown, kind?: AppErrorKind): err is AppError;
29
+ export {};
@@ -0,0 +1,53 @@
1
+ export const APP_ERROR_MESSAGES = {
2
+ generic: "Something went wrong. Please try again or contact us.",
3
+ auth: "Please sign in to continue.",
4
+ forbidden: "You don't have access to this.",
5
+ notFound: "We couldn't find what you were looking for.",
6
+ rateLimited: "Too many attempts. Please wait a moment and try again.",
7
+ dbTransient: "We're having trouble saving this right now. Please try again in a minute.",
8
+ timeout: "This is taking longer than expected. Please retry.",
9
+ validationFallback: "Some of the information provided could not be validated. Please try again.",
10
+ };
11
+ export const APP_ERROR_STATUS = {
12
+ validation: 400,
13
+ auth: 401,
14
+ forbidden: 403,
15
+ not_found: 404,
16
+ conflict: 409,
17
+ rate_limited: 429,
18
+ db_transient: 503,
19
+ db_query: 500,
20
+ timeout: 504,
21
+ external_service: 502,
22
+ unknown: 500,
23
+ };
24
+ const DEFAULT_SAFE_MESSAGE = {
25
+ auth: APP_ERROR_MESSAGES.auth,
26
+ forbidden: APP_ERROR_MESSAGES.forbidden,
27
+ not_found: APP_ERROR_MESSAGES.notFound,
28
+ rate_limited: APP_ERROR_MESSAGES.rateLimited,
29
+ db_transient: APP_ERROR_MESSAGES.dbTransient,
30
+ timeout: APP_ERROR_MESSAGES.timeout,
31
+ };
32
+ // Symbol.for survives duplicate copies of this package in one bundle, where instanceof would not.
33
+ const APP_ERROR_BRAND = Symbol.for("inbeat.appError");
34
+ export class AppError extends Error {
35
+ [APP_ERROR_BRAND] = true;
36
+ kind;
37
+ safeMessage;
38
+ reportToSentry;
39
+ isRetryable;
40
+ constructor(kind, message, options = {}) {
41
+ super(message, options.cause === undefined ? undefined : { cause: options.cause });
42
+ this.name = "AppError";
43
+ this.kind = kind;
44
+ this.safeMessage = options.safeMessage ?? DEFAULT_SAFE_MESSAGE[kind] ?? message;
45
+ this.reportToSentry = options.reportToSentry ?? false;
46
+ this.isRetryable = options.isRetryable ?? false;
47
+ }
48
+ }
49
+ export function isAppError(err, kind) {
50
+ return (err instanceof Error &&
51
+ err[APP_ERROR_BRAND] === true &&
52
+ (kind === undefined || err.kind === kind));
53
+ }
@@ -0,0 +1,25 @@
1
+ import { type AppErrorKind } from "./app-error.js";
2
+ export type ClassifiedError = {
3
+ kind: AppErrorKind;
4
+ safeMessage: string;
5
+ reportToSentry: boolean;
6
+ isRetryable: boolean;
7
+ fingerprint?: string[];
8
+ tags: Record<string, string>;
9
+ original: unknown;
10
+ };
11
+ export declare const TRANSIENT_MESSAGE_PATTERNS: readonly RegExp[];
12
+ /** Maps any thrown value to safe user copy, Sentry metadata and a retry decision. */
13
+ export declare function classifyError(err: unknown): ClassifiedError;
14
+ export declare function getSafeErrorMessage(err: unknown): string;
15
+ /**
16
+ * Neon's 57P01 admin_shutdown arrives on the WebSocket after the query already resolved,
17
+ * so it escapes every try/catch and lands in Node's uncaughtException handler.
18
+ * The mechanism is matched by suffix: Sentry 10 reports "auto.node.onuncaughtexception",
19
+ * older SDKs a bare "onuncaughtexception".
20
+ */
21
+ export declare function isTransientUncaughtException(mechanismType: string | undefined, err: unknown): boolean;
22
+ export declare function withTransientRetry<T>(fn: () => Promise<T>, { retries, delayMs }?: {
23
+ retries?: number;
24
+ delayMs?: number;
25
+ }): Promise<T>;
@@ -0,0 +1,124 @@
1
+ import { APP_ERROR_MESSAGES, isAppError } from "./app-error.js";
2
+ import { errorChain, findPgError, PG_CODES, TRANSIENT_PG_CODES } from "./pg.js";
3
+ export const TRANSIENT_MESSAGE_PATTERNS = [
4
+ /control plane request failed/i,
5
+ /terminating connection due to administrator command/i,
6
+ /connection terminated/i,
7
+ /connection reset/i,
8
+ /connection refused/i,
9
+ /connection closed/i,
10
+ /socket hang up/i,
11
+ /econnreset/i,
12
+ /econnrefused/i,
13
+ /etimedout/i,
14
+ /timeout exceeded/i,
15
+ /too many connections/i,
16
+ /cannot connect now/i,
17
+ /server closed the connection unexpectedly/i,
18
+ ];
19
+ const TIMEOUT_PATTERN = /timeout|timed out|deadline exceeded/i;
20
+ // Shape check, not instanceof: Zod 4's `new ZodError(issues)` is not `instanceof Error`
21
+ // (only errors thrown by `.parse()` are), and apps may bundle a different zod copy.
22
+ function isZodError(err) {
23
+ return (typeof err === "object" &&
24
+ err !== null &&
25
+ err.name === "ZodError" &&
26
+ Array.isArray(err.issues));
27
+ }
28
+ function messagesOf(err) {
29
+ return errorChain(err)
30
+ .filter((link) => link instanceof Error)
31
+ .map((link) => link.message);
32
+ }
33
+ function fingerprintFor(kind) {
34
+ if (kind === "db_transient" || kind === "timeout")
35
+ return ["db-transient", kind];
36
+ if (kind === "db_query")
37
+ return ["db-query"];
38
+ return undefined;
39
+ }
40
+ function tagsFor(kind, pg) {
41
+ return {
42
+ "error.kind": kind,
43
+ ...(pg ? { "db.code": pg.code } : {}),
44
+ };
45
+ }
46
+ function build(kind, err, pg, overrides) {
47
+ const reportToSentry = overrides.reportToSentry ?? true;
48
+ return {
49
+ kind,
50
+ isRetryable: false,
51
+ reportToSentry,
52
+ fingerprint: reportToSentry ? fingerprintFor(kind) : undefined,
53
+ tags: tagsFor(kind, pg),
54
+ original: err,
55
+ ...overrides,
56
+ };
57
+ }
58
+ /** Maps any thrown value to safe user copy, Sentry metadata and a retry decision. */
59
+ export function classifyError(err) {
60
+ if (isAppError(err)) {
61
+ return build(err.kind, err, null, {
62
+ safeMessage: err.safeMessage,
63
+ reportToSentry: err.reportToSentry,
64
+ isRetryable: err.isRetryable,
65
+ });
66
+ }
67
+ if (isZodError(err)) {
68
+ return build("validation", err, null, {
69
+ safeMessage: err.issues[0]?.message ?? APP_ERROR_MESSAGES.validationFallback,
70
+ reportToSentry: false,
71
+ });
72
+ }
73
+ const pg = findPgError(err);
74
+ if (pg && TRANSIENT_PG_CODES.has(pg.code)) {
75
+ const kind = pg.code === PG_CODES.queryCanceled ? "timeout" : "db_transient";
76
+ return build(kind, err, pg, {
77
+ safeMessage: kind === "timeout" ? APP_ERROR_MESSAGES.timeout : APP_ERROR_MESSAGES.dbTransient,
78
+ isRetryable: true,
79
+ });
80
+ }
81
+ const messages = messagesOf(err);
82
+ if (messages.some((message) => TRANSIENT_MESSAGE_PATTERNS.some((p) => p.test(message)))) {
83
+ return build("db_transient", err, pg, {
84
+ safeMessage: APP_ERROR_MESSAGES.dbTransient,
85
+ isRetryable: true,
86
+ });
87
+ }
88
+ if (messages.some((message) => TIMEOUT_PATTERN.test(message))) {
89
+ return build("timeout", err, pg, {
90
+ safeMessage: APP_ERROR_MESSAGES.timeout,
91
+ isRetryable: true,
92
+ });
93
+ }
94
+ if (pg || messages.some((message) => message.startsWith("Failed query:"))) {
95
+ return build("db_query", err, pg, { safeMessage: APP_ERROR_MESSAGES.generic });
96
+ }
97
+ return build("unknown", err, pg, { safeMessage: APP_ERROR_MESSAGES.generic });
98
+ }
99
+ export function getSafeErrorMessage(err) {
100
+ return classifyError(err).safeMessage;
101
+ }
102
+ /**
103
+ * Neon's 57P01 admin_shutdown arrives on the WebSocket after the query already resolved,
104
+ * so it escapes every try/catch and lands in Node's uncaughtException handler.
105
+ * The mechanism is matched by suffix: Sentry 10 reports "auto.node.onuncaughtexception",
106
+ * older SDKs a bare "onuncaughtexception".
107
+ */
108
+ export function isTransientUncaughtException(mechanismType, err) {
109
+ return (Boolean(mechanismType?.endsWith("onuncaughtexception")) &&
110
+ err instanceof Error &&
111
+ TRANSIENT_MESSAGE_PATTERNS.some((pattern) => pattern.test(err.message)));
112
+ }
113
+ export async function withTransientRetry(fn, { retries = 2, delayMs = 250 } = {}) {
114
+ for (let attempt = 0;; attempt++) {
115
+ try {
116
+ return await fn();
117
+ }
118
+ catch (err) {
119
+ if (attempt >= retries || !classifyError(err).isRetryable)
120
+ throw err;
121
+ await new Promise((resolve) => setTimeout(resolve, delayMs * (attempt + 1)));
122
+ }
123
+ }
124
+ }
@@ -0,0 +1,3 @@
1
+ export * from "./app-error.js";
2
+ export * from "./classify-error.js";
3
+ export * from "./pg.js";
@@ -0,0 +1,3 @@
1
+ export * from "./app-error.js";
2
+ export * from "./classify-error.js";
3
+ export * from "./pg.js";
@@ -0,0 +1,19 @@
1
+ /** SQLSTATE codes, see https://www.postgresql.org/docs/current/errcodes-appendix.html */
2
+ export declare const PG_CODES: {
3
+ readonly uniqueViolation: "23505";
4
+ readonly foreignKeyViolation: "23503";
5
+ readonly notNullViolation: "23502";
6
+ readonly checkViolation: "23514";
7
+ readonly queryCanceled: "57014";
8
+ };
9
+ export declare const TRANSIENT_PG_CODES: ReadonlySet<string>;
10
+ export type PgErrorLike = {
11
+ code: string;
12
+ severity?: string;
13
+ message?: string;
14
+ };
15
+ /** Walks `cause` because Drizzle wraps driver errors in "Failed query: …". */
16
+ export declare function errorChain(err: unknown): unknown[];
17
+ export declare function findPgError(err: unknown): PgErrorLike | null;
18
+ export declare function hasPgCode(err: unknown, code: string): boolean;
19
+ export declare const isUniqueViolation: (err: unknown) => boolean;
@@ -0,0 +1,47 @@
1
+ /** SQLSTATE codes, see https://www.postgresql.org/docs/current/errcodes-appendix.html */
2
+ export const PG_CODES = {
3
+ uniqueViolation: "23505",
4
+ foreignKeyViolation: "23503",
5
+ notNullViolation: "23502",
6
+ checkViolation: "23514",
7
+ queryCanceled: "57014",
8
+ };
9
+ export const TRANSIENT_PG_CODES = new Set([
10
+ "08000", // connection_exception
11
+ "08001", // sqlclient_unable_to_establish_sqlconnection
12
+ "08003", // connection_does_not_exist
13
+ "08006", // connection_failure
14
+ "08007", // transaction_resolution_unknown
15
+ "53300", // too_many_connections
16
+ "57P01", // admin_shutdown
17
+ "57P02", // crash_shutdown
18
+ "57P03", // cannot_connect_now
19
+ PG_CODES.queryCanceled,
20
+ ]);
21
+ /** Walks `cause` because Drizzle wraps driver errors in "Failed query: …". */
22
+ export function errorChain(err) {
23
+ const chain = [];
24
+ const seen = new Set();
25
+ let current = err;
26
+ while (current !== null && current !== undefined && !seen.has(current)) {
27
+ seen.add(current);
28
+ chain.push(current);
29
+ current = typeof current === "object" ? current.cause : undefined;
30
+ }
31
+ return chain;
32
+ }
33
+ export function findPgError(err) {
34
+ for (const link of errorChain(err)) {
35
+ if (typeof link === "object" &&
36
+ link !== null &&
37
+ typeof link.code === "string" &&
38
+ /^[0-9A-Z]{5}$/.test(link.code)) {
39
+ return link;
40
+ }
41
+ }
42
+ return null;
43
+ }
44
+ export function hasPgCode(err, code) {
45
+ return findPgError(err)?.code === code;
46
+ }
47
+ export const isUniqueViolation = (err) => hasPgCode(err, PG_CODES.uniqueViolation);
@@ -0,0 +1,20 @@
1
+ export type LogLevel = "debug" | "info" | "warn" | "error";
2
+ export type LogContext = Record<string, unknown>;
3
+ export type LogSink = (level: LogLevel, message: string, context: LogContext) => void;
4
+ export type Logger = {
5
+ debug: (message: string, context?: LogContext) => void;
6
+ info: (message: string, context?: LogContext) => void;
7
+ warn: (message: string, context?: LogContext) => void;
8
+ error: (message: string, error?: unknown, context?: LogContext) => void;
9
+ child: (bindings: LogContext) => Logger;
10
+ };
11
+ export type LoggerOptions = {
12
+ level?: LogLevel;
13
+ bindings?: LogContext;
14
+ sinks?: LogSink[];
15
+ };
16
+ /**
17
+ * Structured JSON logger. Log ids, never emails or names: stdout is shipped to Vercel,
18
+ * Sentry and any configured drain.
19
+ */
20
+ export declare function createLogger({ level, bindings, sinks, }?: LoggerOptions): Logger;
package/dist/logger.js ADDED
@@ -0,0 +1,31 @@
1
+ const LEVEL_ORDER = { debug: 10, info: 20, warn: 30, error: 40 };
2
+ const jsonConsoleSink = (level, message, context) => {
3
+ // biome-ignore lint/suspicious/noConsole: the logger is the single sanctioned console writer
4
+ console[level](JSON.stringify({ level, message, ...context }));
5
+ };
6
+ function serializeError(error) {
7
+ if (error instanceof Error) {
8
+ return { error: { name: error.name, message: error.message, stack: error.stack } };
9
+ }
10
+ return error === undefined ? {} : { error: String(error) };
11
+ }
12
+ /**
13
+ * Structured JSON logger. Log ids, never emails or names: stdout is shipped to Vercel,
14
+ * Sentry and any configured drain.
15
+ */
16
+ export function createLogger({ level = "info", bindings = {}, sinks = [jsonConsoleSink], } = {}) {
17
+ const write = (at, message, context) => {
18
+ if (LEVEL_ORDER[at] < LEVEL_ORDER[level])
19
+ return;
20
+ const merged = { ...bindings, ...context };
21
+ for (const sink of sinks)
22
+ sink(at, message, merged);
23
+ };
24
+ return {
25
+ debug: (message, context = {}) => write("debug", message, context),
26
+ info: (message, context = {}) => write("info", message, context),
27
+ warn: (message, context = {}) => write("warn", message, context),
28
+ error: (message, error, context = {}) => write("error", message, { ...context, ...serializeError(error) }),
29
+ child: (extra) => createLogger({ level, sinks, bindings: { ...bindings, ...extra } }),
30
+ };
31
+ }
@@ -0,0 +1,16 @@
1
+ import type { AppErrorKind } from "./errors/app-error.js";
2
+ export type Ok<T> = {
3
+ ok: true;
4
+ data: T;
5
+ };
6
+ export type Fail = {
7
+ ok: false;
8
+ error: string;
9
+ code?: AppErrorKind;
10
+ errorId?: string;
11
+ };
12
+ export type Result<T = void> = Ok<T> | Fail;
13
+ export declare function ok(): Ok<void>;
14
+ export declare function ok<T>(data: T): Ok<T>;
15
+ export declare function fail(error: string, code?: AppErrorKind, errorId?: string): Fail;
16
+ export declare function unwrap<T>(result: Result<T>): T;
package/dist/result.js ADDED
@@ -0,0 +1,16 @@
1
+ export function ok(data) {
2
+ return { ok: true, data };
3
+ }
4
+ export function fail(error, code, errorId) {
5
+ return {
6
+ ok: false,
7
+ error,
8
+ ...(code ? { code } : {}),
9
+ ...(errorId ? { errorId } : {}),
10
+ };
11
+ }
12
+ export function unwrap(result) {
13
+ if (!result.ok)
14
+ throw new Error(result.error);
15
+ return result.data;
16
+ }
package/package.json CHANGED
@@ -1,6 +1,56 @@
1
1
  {
2
2
  "name": "@inbeat/core",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.7.0",
4
+ "description": "Framework-free primitives for inBeat apps: errors, results, logging, env fragments",
5
+ "type": "module",
6
+ "sideEffects": false,
7
+ "files": [
8
+ "CHANGELOG.md",
9
+ "dist"
10
+ ],
11
+ "exports": {
12
+ "./errors": {
13
+ "types": "./dist/errors/index.d.ts",
14
+ "default": "./dist/errors/index.js"
15
+ },
16
+ "./result": {
17
+ "types": "./dist/result.d.ts",
18
+ "default": "./dist/result.js"
19
+ },
20
+ "./logger": {
21
+ "types": "./dist/logger.d.ts",
22
+ "default": "./dist/logger.js"
23
+ },
24
+ "./env": {
25
+ "types": "./dist/env.d.ts",
26
+ "default": "./dist/env.js"
27
+ },
28
+ "./email": {
29
+ "types": "./dist/email.d.ts",
30
+ "default": "./dist/email.js"
31
+ }
32
+ },
33
+ "scripts": {
34
+ "build": "rm -rf dist && tsc -p tsconfig.build.json",
35
+ "dev": "tsc -p tsconfig.build.json --watch --preserveWatchOutput",
36
+ "typecheck": "tsc --noEmit",
37
+ "test": "vitest run"
38
+ },
39
+ "peerDependencies": {
40
+ "zod": "^4"
41
+ },
42
+ "devDependencies": {
43
+ "@inbeat/config": "^0.7.0",
44
+ "vitest": "^4.1.1",
45
+ "zod": "^4.3.6"
46
+ },
47
+ "repository": {
48
+ "type": "git",
49
+ "url": "git+https://github.com/Genoux/ib-toolkit.git",
50
+ "directory": "packages/core"
51
+ },
52
+ "publishConfig": {
53
+ "access": "public"
54
+ },
55
+ "license": "UNLICENSED"
56
+ }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.