UNPKG

@settlemint/sdk-utils

Version:

Shared utilities and helper functions for SettleMint SDK modules

1 lines • 17.4 kB
{"version":3,"file":"validation.cjs","names":["schema: T","value: unknown","ZodError","ApplicationAccessTokenSchema: ZodString","z","PersonalAccessTokenSchema: ZodString","AccessTokenSchema: ZodString","value: string","defaultValue: T | null","value: unknown","value","z","z","z","z"],"sources":["../src/validation/validate.ts","../src/validation/access-token.schema.ts","../src/json.ts","../src/validation/unique-name.schema.ts","../src/validation/url.schema.ts","../src/validation/dot-env.schema.ts","../src/validation/id.schema.ts"],"sourcesContent":["import { ZodError, type ZodType } from \"zod\";\n\n/**\n * Validates a value against a given Zod schema.\n *\n * @param schema - The Zod schema to validate against.\n * @param value - The value to validate.\n * @returns The validated and parsed value.\n * @throws Will throw an error if validation fails, with formatted error messages.\n *\n * @example\n * import { validate } from \"@settlemint/sdk-utils/validation\";\n *\n * const validatedId = validate(IdSchema, \"550e8400-e29b-41d4-a716-446655440000\");\n */\nexport function validate<T extends ZodType>(schema: T, value: unknown): T[\"_output\"] {\n try {\n return schema.parse(value);\n } catch (error) {\n if (error instanceof ZodError) {\n const formattedErrors = error.issues.map((err) => `- ${err.path.join(\".\")}: ${err.message}`).join(\"\\n\");\n throw new Error(`Validation error${error.issues.length > 1 ? \"s\" : \"\"}:\\n${formattedErrors}`);\n }\n throw error; // Re-throw if it's not a ZodError\n }\n}\n","import { type ZodString, z } from \"zod\";\n\n/**\n * Schema for validating application access tokens.\n * Application access tokens start with 'sm_aat_' prefix.\n */\nexport const ApplicationAccessTokenSchema: ZodString = z.string().regex(/^sm_aat_.+$/);\nexport type ApplicationAccessToken = z.infer<typeof ApplicationAccessTokenSchema>;\n\n/**\n * Schema for validating personal access tokens.\n * Personal access tokens start with 'sm_pat_' prefix.\n */\nexport const PersonalAccessTokenSchema: ZodString = z.string().regex(/^sm_pat_.+$/);\nexport type PersonalAccessToken = z.infer<typeof PersonalAccessTokenSchema>;\n\n/**\n * Schema for validating both application and personal access tokens.\n * Accepts tokens starting with either 'sm_pat_' or 'sm_aat_' prefix.\n */\nexport const AccessTokenSchema: ZodString = z.string().regex(/^(sm_pat_.+|sm_aat_.+)$/);\nexport type AccessToken = z.infer<typeof AccessTokenSchema>;\n","/**\n * Attempts to parse a JSON string into a typed value, returning a default value if parsing fails.\n *\n * @param value - The JSON string to parse\n * @param defaultValue - The value to return if parsing fails or results in null/undefined\n * @returns The parsed JSON value as type T, or the default value if parsing fails\n *\n * @example\n * import { tryParseJson } from \"@settlemint/sdk-utils\";\n *\n * const config = tryParseJson<{ port: number }>(\n * '{\"port\": 3000}',\n * { port: 8080 }\n * );\n * // Returns: { port: 3000 }\n *\n * const invalid = tryParseJson<string[]>(\n * 'invalid json',\n * []\n * );\n * // Returns: []\n */\nexport function tryParseJson<T>(value: string, defaultValue: T | null = null): T | null {\n try {\n const parsed = JSON.parse(value) as T;\n if (parsed === undefined || parsed === null) {\n return defaultValue;\n }\n return parsed;\n } catch (_err) {\n // Invalid json\n return defaultValue;\n }\n}\n\n/**\n * Extracts a JSON object from a string.\n *\n * @param value - The string to extract the JSON object from\n * @returns The parsed JSON object, or null if no JSON object is found\n * @throws {Error} If the input string is too long (longer than 5000 characters)\n * @example\n * import { extractJsonObject } from \"@settlemint/sdk-utils\";\n *\n * const json = extractJsonObject<{ port: number }>(\n * 'port info: {\"port\": 3000}',\n * );\n * // Returns: { port: 3000 }\n */\nexport function extractJsonObject<T>(value: string): T | null {\n if (value.length > 5000) {\n throw new Error(\"Input too long\");\n }\n const result = /\\{([\\s\\S]*)\\}/.exec(value);\n if (!result) {\n return null;\n }\n return tryParseJson<T>(result[0]);\n}\n\n/**\n * Converts a value to a JSON stringifiable format.\n *\n * @param value - The value to convert\n * @returns The JSON stringifiable value\n *\n * @example\n * import { makeJsonStringifiable } from \"@settlemint/sdk-utils\";\n *\n * const json = makeJsonStringifiable<{ amount: bigint }>({ amount: BigInt(1000) });\n * // Returns: '{\"amount\":\"1000\"}'\n */\nexport function makeJsonStringifiable<T>(value: unknown): T {\n if (value === undefined || value === null) {\n return value as T;\n }\n return tryParseJson<T>(\n JSON.stringify(\n value,\n (_, value) => (typeof value === \"bigint\" ? value.toString() : value), // return everything else unchanged\n ),\n ) as T;\n}\n","import { z } from \"zod\";\n\n/**\n * Schema for validating unique names used across the SettleMint platform.\n * Only accepts lowercase alphanumeric characters and hyphens.\n * Used for workspace names, application names, service names etc.\n *\n * @example\n * import { UniqueNameSchema } from \"@settlemint/sdk-utils/validation\";\n *\n * // Validate a workspace name\n * const isValidName = UniqueNameSchema.safeParse(\"my-workspace-123\").success;\n * // true\n *\n * // Invalid names will fail validation\n * const isInvalidName = UniqueNameSchema.safeParse(\"My Workspace!\").success;\n * // false\n */\nexport const UniqueNameSchema = z.string().regex(/^[a-z0-9-]+$/);\n\n/**\n * Type definition for unique names, inferred from UniqueNameSchema.\n */\nexport type UniqueName = z.infer<typeof UniqueNameSchema>;\n","import { z } from \"zod\";\n\n/**\n * Schema for validating URLs.\n *\n * @example\n * import { UrlSchema } from \"@settlemint/sdk-utils/validation\";\n *\n * // Validate a URL\n * const isValidUrl = UrlSchema.safeParse(\"https://console.settlemint.com\").success;\n * // true\n *\n * // Invalid URLs will fail validation\n * const isInvalidUrl = UrlSchema.safeParse(\"not-a-url\").success;\n * // false\n */\nexport const UrlSchema = z.string().url();\nexport type Url = z.infer<typeof UrlSchema>;\n\n/**\n * Schema for validating URL paths.\n *\n * @example\n * import { UrlPathSchema } from \"@settlemint/sdk-utils/validation\";\n *\n * // Validate a URL path\n * const isValidPath = UrlPathSchema.safeParse(\"/api/v1/users\").success;\n * // true\n *\n * // Invalid paths will fail validation\n * const isInvalidPath = UrlPathSchema.safeParse(\"not-a-path\").success;\n * // false\n */\nexport const UrlPathSchema = z.string().regex(/^\\/(?:[a-zA-Z0-9-_]+(?:\\/[a-zA-Z0-9-_]+)*\\/?)?$/, {\n message: \"Invalid URL path format. Must start with '/' and can contain letters, numbers, hyphens, and underscores.\",\n});\n\nexport type UrlPath = z.infer<typeof UrlPathSchema>;\n\n/**\n * Schema that accepts either a full URL or a URL path.\n *\n * @example\n * import { UrlOrPathSchema } from \"@settlemint/sdk-utils/validation\";\n *\n * // Validate a URL\n * const isValidUrl = UrlOrPathSchema.safeParse(\"https://console.settlemint.com\").success;\n * // true\n *\n * // Validate a path\n * const isValidPath = UrlOrPathSchema.safeParse(\"/api/v1/users\").success;\n * // true\n */\nexport const UrlOrPathSchema = z.union([UrlSchema, UrlPathSchema]);\nexport type UrlOrPath = z.infer<typeof UrlOrPathSchema>;\n","import { z } from \"zod\";\nimport { tryParseJson } from \"@/json.js\";\nimport { ApplicationAccessTokenSchema, PersonalAccessTokenSchema } from \"./access-token.schema.js\";\nimport { UniqueNameSchema } from \"./unique-name.schema.js\";\nimport { UrlSchema } from \"./url.schema.js\";\n\n/**\n * Use this value to indicate that the resources are not part of the SettleMint platform.\n */\nexport const STANDALONE_INSTANCE = \"standalone\";\n/**\n * Use this value to indicate that the resources are not part of the SettleMint platform.\n */\nexport const LOCAL_INSTANCE = \"local\";\n\n/**\n * Schema for validating environment variables used by the SettleMint SDK.\n * Defines validation rules and types for configuration values like URLs,\n * access tokens, workspace names, and service endpoints.\n */\nexport const DotEnvSchema = z.object({\n /** Base URL of the SettleMint platform instance, set to standalone if your resources are not part of the SettleMint platform */\n SETTLEMINT_INSTANCE: z\n .union([UrlSchema, z.literal(STANDALONE_INSTANCE), z.literal(LOCAL_INSTANCE)])\n .default(\"https://console.settlemint.com\"),\n /** Application access token for authenticating with SettleMint services */\n SETTLEMINT_ACCESS_TOKEN: ApplicationAccessTokenSchema.optional(),\n /** @internal */\n SETTLEMINT_PERSONAL_ACCESS_TOKEN: PersonalAccessTokenSchema.optional(),\n /** Unique name of the workspace */\n SETTLEMINT_WORKSPACE: UniqueNameSchema.optional(),\n /** Unique name of the application */\n SETTLEMINT_APPLICATION: UniqueNameSchema.optional(),\n /** Unique name of the blockchain network */\n SETTLEMINT_BLOCKCHAIN_NETWORK: UniqueNameSchema.optional(),\n /** Chain ID of the blockchain network */\n SETTLEMINT_BLOCKCHAIN_NETWORK_CHAIN_ID: z.string().optional(),\n /** Unique name of the blockchain node (should have a private key for signing transactions) */\n SETTLEMINT_BLOCKCHAIN_NODE: UniqueNameSchema.optional(),\n /** JSON RPC endpoint for the blockchain node */\n SETTLEMINT_BLOCKCHAIN_NODE_JSON_RPC_ENDPOINT: UrlSchema.optional(),\n /** Unique name of the blockchain node or load balancer */\n SETTLEMINT_BLOCKCHAIN_NODE_OR_LOAD_BALANCER: UniqueNameSchema.optional(),\n /** JSON RPC endpoint for the blockchain node or load balancer */\n SETTLEMINT_BLOCKCHAIN_NODE_OR_LOAD_BALANCER_JSON_RPC_ENDPOINT: UrlSchema.optional(),\n /** Unique name of the Hasura instance */\n SETTLEMINT_HASURA: UniqueNameSchema.optional(),\n /** Endpoint URL for the Hasura GraphQL API */\n SETTLEMINT_HASURA_ENDPOINT: UrlSchema.optional(),\n /** Admin secret for authenticating with Hasura */\n SETTLEMINT_HASURA_ADMIN_SECRET: z.string().optional(),\n /** Database connection URL for Hasura */\n SETTLEMINT_HASURA_DATABASE_URL: z.string().optional(),\n /** Unique name of The Graph instance */\n SETTLEMINT_THEGRAPH: UniqueNameSchema.optional(),\n /** Array of endpoint URLs for The Graph subgraphs */\n SETTLEMINT_THEGRAPH_SUBGRAPHS_ENDPOINTS: z.preprocess(\n (value) => tryParseJson(value as string, []),\n z.array(UrlSchema).optional(),\n ),\n /** Default The Graph subgraph to use */\n SETTLEMINT_THEGRAPH_DEFAULT_SUBGRAPH: z.string().optional(),\n /** Unique name of the Smart Contract Portal instance */\n SETTLEMINT_PORTAL: UniqueNameSchema.optional(),\n /** GraphQL endpoint URL for the Portal */\n SETTLEMINT_PORTAL_GRAPHQL_ENDPOINT: UrlSchema.optional(),\n /** REST endpoint URL for the Portal */\n SETTLEMINT_PORTAL_REST_ENDPOINT: UrlSchema.optional(),\n /** WebSocket endpoint URL for the Portal */\n SETTLEMINT_PORTAL_WS_ENDPOINT: UrlSchema.optional(),\n /** Unique name of the HD private key */\n SETTLEMINT_HD_PRIVATE_KEY: UniqueNameSchema.optional(),\n /** Address of the HD private key forwarder */\n SETTLEMINT_HD_PRIVATE_KEY_FORWARDER_ADDRESS: z.string().optional(),\n /** Unique name of the accessible private key */\n SETTLEMINT_ACCESSIBLE_PRIVATE_KEY: UniqueNameSchema.optional(),\n /** Unique name of the MinIO instance */\n SETTLEMINT_MINIO: UniqueNameSchema.optional(),\n /** Endpoint URL for MinIO */\n SETTLEMINT_MINIO_ENDPOINT: UrlSchema.optional(),\n /** Access key for MinIO authentication */\n SETTLEMINT_MINIO_ACCESS_KEY: z.string().optional(),\n /** Secret key for MinIO authentication */\n SETTLEMINT_MINIO_SECRET_KEY: z.string().optional(),\n /** Unique name of the IPFS instance */\n SETTLEMINT_IPFS: UniqueNameSchema.optional(),\n /** API endpoint URL for IPFS */\n SETTLEMINT_IPFS_API_ENDPOINT: UrlSchema.optional(),\n /** Pinning service endpoint URL for IPFS */\n SETTLEMINT_IPFS_PINNING_ENDPOINT: UrlSchema.optional(),\n /** Gateway endpoint URL for IPFS */\n SETTLEMINT_IPFS_GATEWAY_ENDPOINT: UrlSchema.optional(),\n /** Unique name of the custom deployment */\n SETTLEMINT_CUSTOM_DEPLOYMENT: UniqueNameSchema.optional(),\n /** Endpoint URL for the custom deployment */\n SETTLEMINT_CUSTOM_DEPLOYMENT_ENDPOINT: UrlSchema.optional(),\n /** Unique name of the Blockscout instance */\n SETTLEMINT_BLOCKSCOUT: UniqueNameSchema.optional(),\n /** GraphQL endpoint URL for Blockscout */\n SETTLEMINT_BLOCKSCOUT_GRAPHQL_ENDPOINT: UrlSchema.optional(),\n /** UI endpoint URL for Blockscout */\n SETTLEMINT_BLOCKSCOUT_UI_ENDPOINT: UrlSchema.optional(),\n /** Name of the new project being created */\n SETTLEMINT_NEW_PROJECT_NAME: z.string().optional(),\n /** The log level to use */\n SETTLEMINT_LOG_LEVEL: z.enum([\"debug\", \"info\", \"warn\", \"error\", \"none\"]).default(\"warn\"),\n});\n\n/**\n * Type definition for the environment variables schema.\n */\nexport type DotEnv = z.infer<typeof DotEnvSchema>;\n\n/**\n * Partial version of the environment variables schema where all fields are optional.\n * Useful for validating incomplete configurations during development or build time.\n */\nexport const DotEnvSchemaPartial = DotEnvSchema.partial();\n\n/**\n * Type definition for the partial environment variables schema.\n */\nexport type DotEnvPartial = z.infer<typeof DotEnvSchemaPartial>;\n","import { z } from \"zod\";\n\n/**\n * Schema for validating database IDs. Accepts both PostgreSQL UUIDs and MongoDB ObjectIDs.\n * PostgreSQL UUIDs are 32 hexadecimal characters with hyphens (e.g. 123e4567-e89b-12d3-a456-426614174000).\n * MongoDB ObjectIDs are 24 hexadecimal characters (e.g. 507f1f77bcf86cd799439011).\n *\n * @example\n * import { IdSchema } from \"@settlemint/sdk-utils/validation\";\n *\n * // Validate PostgreSQL UUID\n * const isValidUuid = IdSchema.safeParse(\"123e4567-e89b-12d3-a456-426614174000\").success;\n *\n * // Validate MongoDB ObjectID\n * const isValidObjectId = IdSchema.safeParse(\"507f1f77bcf86cd799439011\").success;\n */\nexport const IdSchema = z.union([\n z\n .string()\n .uuid(), // PostgreSQL UUID\n z\n .string()\n .regex(/^[0-9a-fA-F]{24}$/), // MongoDB ObjectID\n]);\n\n/**\n * Type definition for database IDs, inferred from IdSchema.\n * Can be either a PostgreSQL UUID string or MongoDB ObjectID string.\n */\nexport type Id = z.infer<typeof IdSchema>;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAeA,SAAgB,SAA4BA,QAAWC,OAA8B;AACnF,KAAI;AACF,SAAO,OAAO,MAAM,MAAM;CAC3B,SAAQ,OAAO;AACd,MAAI,iBAAiBC,cAAU;GAC7B,MAAM,kBAAkB,MAAM,OAAO,IAAI,CAAC,QAAQ,CAAC,EAAE,EAAE,IAAI,KAAK,KAAK,IAAI,CAAC,EAAE,EAAE,IAAI,SAAS,CAAC,CAAC,K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