permix
Version:
Permix is a lightweight, framework-agnostic, type-safe permissions management library for JavaScript applications on the client and server sides.
60 lines (59 loc) • 1.85 kB
JavaScript
import { createPermix as createPermix$1 } from "../core/index.mjs";
import { t as PermixInvalidActionsError } from "../errors-C6Zlceok.mjs";
import { extractTablesFromSchema } from "drizzle-orm";
//#region src/drizzle/permix.ts
/**
* The default CRUD action set used when no `actions` are provided.
*/
const DEFAULT_DRIZZLE_ACTIONS = [
"create",
"read",
"update",
"delete"
];
/**
* Create a type-safe Permix instance whose permission tree mirrors a Drizzle
* **v1** schema. Every exported table (and view) becomes a top-level entity
* with the same set of actions (CRUD by default).
*
* Internally uses Drizzle v1's official `extractTablesFromSchema` helper, so
* `defineRelations(...)` objects, plain helpers, and other non-entity exports
* are skipped automatically — pass `import * as schema` as-is.
*
* If you're still on Drizzle v0 (`drizzle-orm@<1`), import from
* `permix/drizzle/legacy` instead.
*
* @example
* ```ts
* import * as schema from './schema'
* import { createPermix } from 'permix/drizzle'
*
* const permix = createPermix(schema)
*
* permix.setup({
* users: { create: true, read: true, update: false, delete: false },
* posts: { create: true, read: true, update: true, delete: false },
* })
*
* permix.check('users.read') // true
* ```
*
* @example Customising actions
* ```ts
* const permix = createPermix(schema, {
* actions: ['view', 'edit'] as const,
* })
* ```
*/
function createPermix(schema, options = {}) {
const actions = options.actions ?? DEFAULT_DRIZZLE_ACTIONS;
if (!Array.isArray(actions) || actions.length === 0) throw new PermixInvalidActionsError();
const tables = Object.keys(extractTablesFromSchema(schema));
const permix = createPermix$1();
return Object.assign(permix, {
actions,
tables
});
}
//#endregion
export { DEFAULT_DRIZZLE_ACTIONS, PermixInvalidActionsError, createPermix };