Every Salesforce framework your team keeps rebuilding, in one Apex & LWC library.
Spend your team on the features that move the business, not on rebuilding the trigger framework, logging, security, and the rest of the plumbing every Salesforce org writes anyway. One managed package with the safe behaviour on automatically, open source on GitHub.
You write the line you expect. You get the depth you didn't: the safe behaviour on automatically, with logging, performance, and traceability built in.
Built to stay consistent after years of changes and dozens of contributors.
What it prevents
What happens when…
- the trigger framework you copied into fifteen orgs has drifted in all fifteen, and the bug only reproduces in the one you didn't touch?
- a query runs in system mode, skips the user's field permissions, and the security reviewer asks you to prove it didn't, with no single place to look?
- a clean deploy finishes before the test suite that's supposed to guard it does, so the suite stops being a gate and starts being a formality?
- the AI assistant writes Apex that compiles, passes review, and ignores every naming and bypass rule your team agreed on last quarter?
KernDX makes each one hard to reach: permissions on by default, one trigger path every org shares, every shortcut logged with the reason it was taken, and a standards file your AI assistant actually reads before it writes.
Why it exists
An accelerator you own, not a product you rent.
Most enterprise Salesforce orgs spend three to five years rebuilding the same foundations: selectors, trigger handling, logging, web services, async, masking, and field-level security (FLS) enforcement. They take on tech debt at every layer. The aim of KernDX is to skip the rebuild cycle, not pay to rent your way around it.
KernDX is the integrated package those teams would have built with the budget and design discipline upfront: one library of frameworks for Apex and Lightning Web Components (LWC), plus the onboarding docs, continuous-integration (CI) tooling, and enforced defaults (permissions on by default, audit-logged bypasses, a coverage gate run on every release) that keep those guarantees true after a dozen contributors.
And the architecture stays yours. The source is public under the Apache License 2.0, so you can read it, fork it, deploy it unmanaged, or repackage it under your own namespace. No black box and no lock-in: if you ever move off the managed package, the framework stays in your org as your code, not a vendor's.
What you get on day one
One install. The whole stack.
Each name opens its example below: the plain Salesforce way on the left, the KernDX way on the right. The guide for each feature is linked from its example.
Read and save data
- Selectors every read in user mode, paged past 2,000 rows
- Saving records related records in one all-or-nothing save
- DTOs JSON in and out through typed classes
- Encryption and sharing one call to encrypt, sharing chosen per read
- Data masking card numbers and keys removed from logs
Automate
- Triggers one trigger per object, actions set in metadata
- Validation rules log a rule's failures before it blocks saves
- Background chains steps that recover from a crash
- Scheduled jobs timed and tuned from a record
- Flow actions callouts, flags and logs, ready to drag in
- Feature flags switch code on for a pilot group, no deployment
Integrate
- Outbound services one service class every caller and Flow shares
- Resilient callouts retry, breaker and a test mock on a single call
- Inbound APIs a replayed request answered with HTTP 409
- Logging errors that survive a rollback
Build, test and run
- Lightning web components toasts and navigation in one call
- Test data and mocks 200 records in one line, or none at all
- Code scanning PMD and ESLint rules that know KernDX
- Platform Cache a cache that never breaks the call
- Admin consoles find what failed, from a screen
- AI coding standards rules your AI assistant reads
Take only what you need. Every layer is opt-in: you can install KernDX for logging and the Log Console alone, and leave every existing trigger, query and class as it is.
Two parts lean on others. The code-scanning rules expect the other layers: they flag inline SOQL, hand-written DML, System.debug, raw Http calls and plain Schedulable classes, but they only report until you set a severity threshold. A Flow callout action needs one outbound service class to call.
The same task, with and without KernDX
You write the line you expect. You get the depth you didn't.
Plain Salesforce on the left, KernDX on the right. The KernDX samples use the managed package's kern. prefix, and every read in them goes through a selector.
The KernDX samples here use the managed package's kern. and kern__ prefixes. Samples in the guides sometimes leave them off: how to read the code samples.
Read and save data5 examples
Plain Apex Manual
// Page 82 of 25-row pages = OFFSET 2025 → governor blow-up
Integer offset = (pageNumber - 1) * pageSize; // over the 2,000 cap
List<Account> rows = [
SELECT Id, Name FROM Account WHERE Type = 'Customer'
ORDER BY Name ASC LIMIT :pageSize OFFSET :offset // ☠
];
Integer total = [SELECT COUNT() FROM Account]; // 2nd query
// FLS by hand. Rows deleted under you? You'll never know.KernDX Included
// SEL_Accounts is your own selector: a with sharing class extending kern.SEL_Base.
kern.QRY_Builder.QueryPage page = new SEL_Accounts().query
.condition(Account.Type).equals('Customer')
.orderBy(Account.Name).ascending()
.getPage(82, 25); // no OFFSET wall, USER_MODE FLS on
page.records; // this page
page.totalRecords; // count came back — no 2nd query
page.totalPages; // computed for you
page.hasMorePages; // wire to a "Next" button
page.deletedRecords; // rows the cursor saw deletedWhat you also get
5lines→8capabilities you didn't write
Reliability
Governance
Observability
Performance
Testing
What's actually happening
Salesforce exposes query cursors, but you normally wire one by hand. getPage() runs a pagination cursor for you, folds the row count into that same call instead of a second query, and reports what the cursor saw deleted mid-fetch. All of it runs in the running user's CRUD, FLS and sharing mode by default.
Plain Apex Manual
Account newAccount = new Account(Name = name);
insert newAccount; // committed immediately
Opportunity newOpportunity = new Opportunity(
Name = dealName, StageName = 'Prospecting',
CloseDate = Date.today().addDays(30),
AccountId = newAccount.Id); // manual FK stitch
Contact newContact = new Contact(
LastName = lastName, AccountId = newAccount.Id);
insert newOpportunity;
insert newContact; // if this throws and the service catches it,
// the Account + Opportunity stay committed — orphaned. Safe means a
// Savepoint + try/catch + Database.rollback(savepoint). Every time.KernDX Included
kern.DML_Builder.newTransaction()
.doInsert(newAccount)
.doInsert(newOpportunity, Opportunity.AccountId, newAccount)
.doInsert(newContact, Contact.AccountId, newAccount)
.execute(); // one savepoint, all-or-nothing.
// FKs auto-wired after each parent inserts; any failure rolls back
// the whole graph. USER_MODE FLS by default.What you also get
5lines→7capabilities you didn't write
Reliability
Governance
Observability
What's actually happening
Each foreign key is set from the new parent's Id the moment that parent inserts, and all three rows commit on a single savepoint. So if any insert fails, the whole graph rolls back and a half-saved parent never leaks.
Why: a DTO is a small class holding exactly the fields to move in or out, which turns itself into JSON and back. If your code reads a field by a misspelt name, the class will not compile, and the outside format stays apart from your objects, so an API change touches one class.
Plain Apex Manual
Map<String, Object> customer = (Map<String, Object>)
JSON.deserializeUntyped(response.getBody());
String email = (String)customer.get('emial'); // typo: null, no error
Map<String, Object> address = (Map<String, Object>)customer.get('address');
String city = (String)address.get('city');
// Every caller casts and guesses the shape again.
// The JSON shape leaks into every class that touches it.KernDX Included
// public is enough: getObjectType() names the class, so KernDX does not look it up by name
@JsonAccess(serializable='always' deserializable='always')
public inherited sharing class DTO_Customer extends kern.DTO_JsonBase
{
public String email;
public DTO_Address address;
public override Type getObjectType()
{
return DTO_Customer.class;
}
@JsonAccess(serializable='always' deserializable='always')
public class DTO_Address
{
public String city;
}
}
DTO_Customer customer = (DTO_Customer)new DTO_Customer().deserialize(response.getBody());
String email = customer.email; // a typo here will not compile
String city = customer.address?.city; // the nested part is typed too
String body = customer.serialize(); // and back to JSONYou write: 1 Apex class (the DTO). You configure: nothing.
What you also get
1class→7capabilities you didn't write
Safety
Shape
Integrate
kern/moduleControllerReady-made
Why: one call encrypts and one decrypts; the key is made, kept per user and replaced for you, and every value carries a tamper check. It is for values you hold during a session: keys expire within 8 hours, so it is not long-term storage.
Plain Apex Manual
Blob key = Crypto.generateAesKey(256);
// ...now store the key somewhere safe, per user, and replace it yourself
Blob cipher = Crypto.encryptWithManagedIV('AES256', key, Blob.valueOf(cardToken));
String sealed = EncodingUtil.base64Encode(cipher);
// No tamper check: a changed value fails late, or decrypts to rubbish.
// Sharing is fixed by the class keyword, for every query in it:
public without sharing class CaseReader { }KernDX Included
String sealed = kern.UTIL_SessionEncryption.encrypt(cardToken);
String plain = kern.UTIL_SessionEncryption.decrypt(sealed);
// Key made and kept per user in Platform Cache, replaced after 8 hours.
// Each value carries a tamper check (HMAC-SHA256), checked on decrypt.
// Sharing chosen per read: past sharing, field checks still on.
// SEL_Cases is your own selector: a with sharing class extending kern.SEL_Base.
List<SObject> openCases = new SEL_Cases().query
.condition(Case.IsClosed).equals(false)
.bypassSharing() // written to the bypass audit trail
.toList();You write: 2 calls, and your own selector class. You configure: space in the package's kern.Library cache partition, where the keys are kept.
What you also get
2calls→12capabilities you didn't write
Encryption
Sharing and field security
Governance
Plain Apex Manual
// Hand-rolled redaction in the log message: any long digit run goes.
String body = '{"card":"4111 1111 1111 1111","orderId":"1234567890123456"}';
String safe = body.replaceAll('\\b(?:\\d[ -]?){13,19}\\b', '[REDACTED]');
// Now BOTH are gone:
// {"card":"[REDACTED]","orderId":"[REDACTED]"}
// The order ID was never a card — but the regex can't tell, so support
// loses the one ID they needed. Loosen it to spare the order ID and a
// real card slips through. There is no win.
insert new Error_Log__c(Message__c = safe);KernDX Included
// Just log it. The framework redacts the payment card on the way out.
String body = '{"card":"4111 1111 1111 1111","orderId":"1234567890123456"}';
kern.LOG_Builder.build()
.info(body)
.at('PaymentService.charge')
.emit();
// The persisted LogEntry message reads:
// {"card":"[CARD_REDACTED]","orderId":"1234567890123456"}
// 4111 1111 1111 1111 passes the Luhn check, so it is redacted.
// The 16-digit order ID FAILS Luhn, so it survives untouched.What you also get
4lines→8capabilities you didn't write
Governance
Performance
What's actually happening
A blunt regex can't tell a card from any other 16-digit number: it either shreds the order ID alongside the card or, loosened to spare the order ID, lets a real card through.
The shipped rule runs in CreditCard mode and checks each candidate match against a Luhn (mod-10) checksum first. So the valid card (4111 1111 1111 1111) is redacted, while the order ID, which fails Luhn, passes through untouched.
The masking runs on the framework's own LogEntryEvent__e before it is published, with nothing to configure.
Automate6 examples: triggers, validation rules, background chains, scheduled jobs, Flow actions, feature flags
Plain Apex Manual
// Plain Apex: one fat trigger, inline logic, hand-rolled recursion guard.
trigger AccountTrigger on Account(before update)
{
if(AccountTriggerHandler.alreadyRan) // static re-entry guard
{
return;
}
AccountTriggerHandler.alreadyRan = true;
for(Account a : Trigger.new)
{
Account prior = Trigger.oldMap.get(a.Id);
// rating + naming + territory logic all crammed here, in an
// order nobody can change without editing + redeploying Apex.
if(a.AnnualRevenue != prior.AnnualRevenue)
{
a.Rating = a.AnnualRevenue > 1000000 ? 'Hot' : 'Warm';
}
// ...next dev appends here; ordering is "whoever edited last"...
}
}
// Disable in an incident: comment it out + deploy. Reorder: edit + deploy.
// Unit-test one rule alone: you can't — it's welded to the loop + guard.KernDX Included
// 1. The trigger is one line — forever.
trigger AccountTrigger on Account(before update)
{
new kern.TRG_Dispatcher().run();
}
// 2. Each rule is its own class, testable in isolation, ordered by metadata.
public inherited sharing class TRG_SetAccountRating
extends kern.TRG_Base implements kern.IF_Trigger.BeforeUpdate
{
public void beforeUpdate(List<SObject> newRecords, List<SObject> oldRecords)
{
for(Account a : (List<Account>) newRecords)
{
Account prior = (Account) triggerOldMap.get(a.Id); // TRG_Base helper
if(a.AnnualRevenue != prior.AnnualRevenue)
{
a.Rating = a.AnnualRevenue > 1000000 ? 'Hot' : 'Warm';
}
}
}
}
// 3. Order, kill switch, and recursion are CONFIG, not code — kern__TriggerAction__mdt:
// kern__ApexClassName__c = TRG_SetAccountRating
// kern__Event__c = Before Update
// kern__Order__c = 20 // reorder without a deploy
// kern__BypassExecution__c = false // flip to true to kill it mid-incident
// kern__AllowRecursion__c = false // shield re-entry (defaults to true)What you also get
a 1-line trigger→9capabilities you didn't write
Governance
Reliability
Observability
Testing
What's actually happening
A one-line trigger hands off to TRG_Dispatcher().run(). It queries the TriggerAction__mdt rows for that object and event, sorts them by Order__c, and dispatches each to a small single-purpose class through the matching IF_Trigger interface.
Because order, bypass, recursion, and flag-gating are rows rather than Apex, they change with no redeploy. And because each action just takes a record list, you unit-test one in isolation.
Plain Apex Manual
// Native Salesforce validation rule. It has exactly two states:
// off, or blocking EVERY save the instant you mark it Active —
// including the historical, dirty data you haven't cleaned yet.
//
// Rule: Customer_Requires_Contact
// Formula: AND(ISPICKVAL(Type, "Customer"), ISBLANK(Phone))
// Active: [x] <-- day one, prod saves start failing
//
// There is no "log it, don't block it" switch. To preview the
// blast radius you hand-roll a Flow that writes to a custom log
// object, or you flip Active on and brace for the support tickets.
update accounts; // some now throw FIELD_CUSTOM_VALIDATION_EXCEPTIONKernDX Included
// 1. AUTHOR two CMDT records, no Apex: a kern__ValidationRuleGroup__mdt that
// binds the object + timing (Account · Before · Insert/Update), then a
// kern__ValidationRule__mdt under it. kern__RuleFormula__c returns TRUE when INVALID.
//
// customMetadata/kern__ValidationRule.Customer_Requires_Contact.md-meta.xml
// <values><field>kern__ValidationRuleGroup__c</field>
// <value xsi:type="xsd:string">Account_Before_Save</value></values>
// <values><field>kern__RuleFormula__c</field>
// <value xsi:type="xsd:string">AND(ISPICKVAL(newRecord.Type, "Customer"), ISBLANK(newRecord.Phone))</value></values>
// <values><field>kern__ErrorMessage__c</field>
// <value xsi:type="xsd:string">Customer accounts need a phone</value></values>
// <values><field>kern__Severity__c</field><value xsi:type="xsd:string">Error</value></values>
// <values><field>kern__Order__c</field><value xsi:type="xsd:double">1</value></values>
// 2. Turn on Shadow Mode — ONE field. The live rule still fires on
// every in-scope save and evaluates the SAME formula, but each
// would-be violation is logged instead of calling addError().
// The save commits — even with Severity = Error.
//
// <values><field>kern__ShadowMode__c</field>
// <value xsi:type="xsd:boolean">true</value></values>
// 3. Watch the blast radius accumulate, then flip kern__ShadowMode__c to
// false to enforce. Violations land in kern__LogEntry__c tagged [SHADOW].
// SEL_LogEntries is your own selector: a with sharing class extending kern.SEL_Base.
List<kern__LogEntry__c> shadowViolations = new SEL_LogEntries().query
.fields(new List<SObjectField>{ kern__LogEntry__c.kern__ShortMessage__c, kern__LogEntry__c.CreatedDate })
.condition(kern__LogEntry__c.kern__LogLevel__c).equals('WARN')
.andCondition(kern__LogEntry__c.kern__ShortMessage__c).contains('[SHADOW]')
.orderBy(kern__LogEntry__c.CreatedDate).descending()
.withLimit(100)
.toList();
// Each kern__ShortMessage__c reads: "[SHADOW] Customer_Requires_Contact:
// Customer accounts need a phone". Zero blocked saves.What you also get
2 custom metadata records + a checkbox→8capabilities you didn't write
Reliability
Observability
Governance
What's actually happening
A native validation rule has two states only: off, or blocking every offending save the instant it is Active. So a new rule meets your dirty production data as a wall of FIELD_CUSTOM_VALIDATION_EXCEPTION errors.
With ShadowMode__c = true the rule still fires on every in-scope save and evaluates the very same deployed formula, but each would-be violation is written to LogEntry__c as a [SHADOW] WARN instead of calling addError(), so nothing is blocked.
The log shows how many records the rule would affect. When you are happy with that, flip one checkbox to enforce it.
Plain Apex Manual
// Hand-rolled Queueable chain
public class Step1 implements Queueable
{
public void execute(QueueableContext context)
{
doWork(); // a CPU/heap limit here and the job just dies
System.enqueueJob(new Step2()); // never reached — no error row, no status
}
}
// AsyncApexJob says "Failed", detail-free. Your tracking record sits
// in "Running" forever. You find out from an angry user, not a query.KernDX Included
kern.UTIL_AsyncChain.newChain('OrderSync')
.then(new Step1())
.then(new Step2())
.onError(new NotifyAdminStep())
.execute();
// Each step runs in its own transaction (fresh limits).
// A Finalizer is attached to EVERY step, so even an
// uncatchable governor-limit crash marks the run Failed —
// with a reason + correlation id + a durable log. Never a zombie.What you also get
5lines→10capabilities you didn't write
Reliability
Observability
Performance
What's actually happening
A hand-rolled Queueable that hits an uncatchable governor limit just dies: no finish() hook, no error row, status stuck on "Running." The framework attaches a Finalizer to every step, and a Finalizer is guaranteed to run with fresh limits even after that crash. So the run is marked Failed with a reason and a correlated log instead of vanishing.
Why: saving a Scheduled Job record schedules your class, so nobody runs System.schedule or writes cron by hand. The job declares its settings, and an admin changes them on the record with no deployment.
Plain Apex Manual
public class CaseArchiveJob implements Schedulable
{
public void execute(SchedulableContext context)
{
CaseArchiveService.archiveOlderThan(90); // change 90? edit and deploy
}
}
// Then, in anonymous Apex, by someone who knows cron:
System.schedule('Case archive', '0 0 2 * * ?', new CaseArchiveJob());
// To change the time: find the job, stop it, schedule it again.KernDX Included
// global: KernDX creates this class by name, from its Scheduled Job record
global inherited sharing class CaseArchiveJob extends kern.SCHED_Base
{
public override List<kern.DTO_ScheduledParameterDefinition> getParameterDefinitions()
{
return new List<kern.DTO_ScheduledParameterDefinition>
{
kern.DTO_ScheduledParameterDefinition.of('daysToKeep', 'Days to keep').asNumeric().withDefault('90')
};
}
public void execute(SchedulableContext context)
{
CaseArchiveService.archiveOlderThan(getNumericParameter('daysToKeep'));
}
}
// An admin saves a Scheduled Job record: Class Name, Schedule, Days to keep.You write: 1 Apex class. You configure: 1 ScheduledJob__c record.
What you also get
1 class + 1 record→14capabilities you didn't write
Operations
kern/scheduledJobDetailLimits
Observability
kern/healthCheckGovernance
Ready-made jobs
Why: the actions a Flow needs most ship ready to drag in. They run the same framework code as your Apex, so a callout from a Flow is retried, logged and masked exactly like one from Apex.
Plain Flow Builder Manual
Action: Create HTTP Callout (External Services)
Named Credential: Posts
Method: GET Path: /posts/1
Sample response → Flow builds the output type
→ the body as Flow variables
No Apex, and fine for a simple call. What it does not give you:
no retry, no circuit breaker, no API Call record of the request
and response, nothing masked, and no tracking ID shared with the
other log entries of the same Flow run.
A feature check or a log entry still needs an Apex action of your own.KernDX in Flow Builder Included
Action: Start Flow Correlation
Flow Name: Checkout → a tracking ID for this run
Action: Is Feature Flag Enabled
flagNames: NewCheckout → true or false for this user
Action: Invoke Callout Synchronously
API Name: API_GetPost → the same handler as the Apex call
→ Response Body, API Call Id, success flag
Action: Log Flow Event
Correlation ID: from the first action
Message: Post fetched → a log entry tied to this run
No Apex class of your own. The callout uses the same handler,
API Setting, retries and masking as the Apex call.You write: no Apex (the handler is the one from Outbound services). You configure: 4 actions in one Flow.
What you also get
0 lines of Apex→12ready-made actions and gains
Integrate
Governance
Observability
Validation
Everyday tasks
Why: a flag is a record, so switching it on, off or for a pilot group is a configuration change the next transaction sees. Apex, Flow and LWC ask the same question and get the same answer, and a flag that does not exist answers false.
Plain Apex Manual
// A checkbox on your own hierarchy custom setting
Checkout_Settings__c settings = Checkout_Settings__c.getInstance();
if(settings.Use_New_Checkout__c)
{
newCheckout();
}
// The setting holds an org value, a profile value and a user value,
// with no code. A permission set, a public group or a custom
// permission cannot hold a value, so a pilot is chosen by profile or user.
// The Flow and the LWC each read the setting their own way.KernDX Included
if(kern.UTIL_FeatureFlag.isEnabled('NewCheckout'))
{
newCheckout(); // on for a profile, permission set or group, set in records
}
// The same flag, the same answer, everywhere:
// Flow: the Is Feature Flag Enabled action
// LWC: await isFlagEnabled('NewCheckout') from kern/featureFlag
// A flag that does not exist returns false.You write: 1 line of Apex. You configure: 1 FeatureFlag__mdt record, plus FeatureFlagStrategy__mdt records to choose the pilot group.
What you also get
1line→9capabilities you didn't write
Rollout
One answer
kern/featureFlagPerformance
Testing
Integrate4 examples: outbound services, resilient callouts, inbound APIs, logging
Why: an API_Outbound handler is one small class for one service: what it sends and how it reads the answer. Its API Setting record (custom metadata) holds the endpoint path, the retry count and the circuit breaker switch.
Every caller, from Apex, a Flow or a background job, uses the same class and the same record, so a change is made once and needs no deployment. Every call is kept as an API Call record with its request and response.
Plain Apex Manual
HttpRequest request = new HttpRequest();
request.setEndpoint('callout:Posts/posts/1');
request.setMethod('GET');
request.setTimeout(10000);
HttpResponse response = new Http().send(request);
String post = response.getBody();
// This block is copied into every class that calls the service,
// and a Flow needs an Apex action of its own around it.
// The path and timeout live in code: a change means a deploy.
// No saved record of the call, nothing masked.KernDX Included
// global: KernDX creates this class by name, from its API Setting record
global with sharing class API_GetPost extends kern.API_Outbound
{
public override void configure()
{
super.configure();
requiresTriggeringRecord = false; // no record starts this call
}
public override kern.API_Base.HttpMethod getHttpMethod()
{
return kern.API_Base.HttpMethod.GET;
}
}
// Its API Setting record holds Class Name (API_GetPost), Endpoint Path (/posts/1),
// Max Retry Count and Circuit Breaker Enabled. Any Apex caller:
kern.API_Outbound handler = kern.UTIL_HttpClient.useHandler(API_GetPost.class).invoke();
String post = handler.result.responseBody; // kept as an API Call record
// A Flow calls the same class with Invoke Callout Synchronously.You write: 1 Apex class. You configure: 1 ApiSetting__mdt record, and 1 ApiCredential__mdt record that names your Named Credential.
What you also get
1 class + 1 record→13capabilities you didn't write
Reliability
Observability
Governance
kern__MaskingRule__mdt: the Mask Secret Key Fields in JSON and Mask Payment Card Numbers rulesTesting
Background work
Plain Apex Manual
// Hand-rolled resilient POST — and you still own the test.
HttpRequest request = new HttpRequest();
request.setEndpoint('callout:PaymentGateway/charges');
request.setMethod('POST');
request.setBody(JSON.serialize(chargeRequest));
Set<Integer> retryable = new Set<Integer>{ 500, 502, 503, 504 };
HttpResponse response;
Integer attempts = 0;
do
{
attempts++;
response = new Http().send(request);
}
while(retryable.contains(response.getStatusCode()) && attempts < 4);
// no circuit breaker · no masking before you log the body · no
// dead-letter — and to test it you hand-write an HttpCalloutMock
// class and wire Test.setMock yourselfKernDX Included
HttpResponse charge = kern.UTIL_HttpClient
.post('PaymentGateway', '/charges')
.body(chargeRequest)
.withIdempotencyKey(chargeRequest.orderNumber) // the same key on every attempt: any value unique to this charge, such as its order number
.withRetry(5, 10)
.withCircuitBreaker()
.onFailure(kern.UTIL_HttpClient.FailureAction.RETRY_THEN_LOG)
.send(); // a transient 5xx comes back ON the response — never thrown
// …and the whole mock + assertion in the test, one chain:
kern.API_MockFactory.forService('PaymentGateway')
.body('{"error":"unavailable"}').statusCode(503).register();What you also get
10lines→10capabilities you didn't write
Reliability
Governance
Observability
Testing
What's actually happening
The non-obvious part: a transient 5xx comes back on the response rather than thrown, and because the call carries an idempotency key, the framework knows a repeat is safe. Once in-transaction retries are spent, the call is saved so a scheduled Flow can send it again at a backoff date.
Without a key, a POST that got a 500, 502 or 504 is not sent again, because the other system may already have charged the card.
The resilience outlives the original transaction. After repeated failures the framework stops calling a failing dependency for a cool-off, then resumes (a circuit breaker). That state lives in Platform Cache keyed by the credential, so a dependency that's down stays shorted across transactions, not just within one.
Plain Apex Manual
// Hand-rolled inbound endpoint — you own the dedupe, or you don't have it.
@RestResource(urlMapping='/charge/*')
global with sharing class ChargeApi
{
@HttpPost
global static void doPost()
{
String key = RestContext.request.headers.get('Idempotency-Key');
String body = RestContext.request.requestBody.toString();
// Naive dedupe: did we see this key already?
List<Payment__c> prior =
[
SELECT Id
FROM Payment__c
WHERE IdempotencyKey__c = :key
LIMIT 1
];
if(!prior.isEmpty())
{
RestContext.response.statusCode = 200; // assume same request...
return; // ...never checked the BODY.
}
chargeCard(body); // a retry with a CHANGED body
insert new Payment__c(IdempotencyKey__c = key); // double-charges silently.
}
}KernDX Included
// 1. A normal inbound handler — no dedupe code at all.
@RestResource(urlMapping='/charge/*')
global inherited sharing class REST_Charge
{
@HttpPost
global static void doPost()
{
kern.API_Dispatcher
.processInboundService(API_Charge.class.getName());
}
}
global inherited sharing class API_Charge extends kern.API_Inbound
{
public override void processRequest()
{
chargeCard(requestBody);
}
}
// 2. Flip ONE field on this service's kern__ApiSetting__mdt record:
// kern__IdempotencyEnabled__c = true (kern__Direction__c = Inbound)
//
// Now, for every caller that sends an Idempotency-Key header:
// • same key + same body → cached HTTP 200 (handler never re-runs)
// • same key + CHANGED body → HTTP 409, names the original kern__ApiCall__c.Id
// • new key → fresh processing
// All three outcomes, zero dedupe code. INBOUND, body-hash based.What you also get
1 handler + a checkbox→9capabilities you didn't write
Reliability
Observability
Governance
What's actually happening
A naive hand-rolled dedupe checks only that the key was seen before, never that the body still matches, so a retry that mutates the payload under the same key double-charges in silence.
The framework instead stores a SHA-256 hash of the request body next to the (External-ID-indexed) Idempotency-Key, so a replay with a changed body is detectable: it returns HTTP 409 naming the original ApiCall__c.Id, while an identical replay returns the cached 200 without re-running your handler.
This is inbound body-hash idempotency. Outbound instead uses an explicit idempotency key you stamp via UTIL_HttpClient.withIdempotencyKey().
Plain Apex Manual
try
{
chargeCard(payment);
}
catch(Exception error)
{
// Write a trace so we know what failed...
insert new Error_Log__c(
Message__c = error.getMessage(),
Stack__c = error.getStackTraceString(),
Record__c = payment.Id);
throw error; // ...then the rollback ERASES that Error_Log__c too.
}KernDX Included
try
{
chargeCard(payment);
}
catch(Exception error)
{
kern.LOG_Builder.build()
.error(error)
.forRecord(payment.Id)
.emitAt('PaymentService.charge');
throw error; // the log is a platform event — it OUTLIVES the rollback.
}What you also get
4lines→8capabilities you didn't write
Reliability
Observability
Governance
What's actually happening
The log is published as a platform event committed to the event bus immediately, independent of your transaction, so the rollback that erases the payment can't un-publish the record of why it failed. A plain insert Error_Log__c shares the failing transaction and is undone by the very rollback the re-throw triggers.
Build, test and run5 examples: Lightning web components, test data, code scanning, Platform Cache, admin consoles
Why: ComponentBuilder is a base class with the common wiring already built in: toasts, Apex calls, navigation, the message service and Flow navigation. You name the parts a component uses, and each one is one method call.
Plain LWC Manual
import {LightningElement} from 'lwc';
import {NavigationMixin} from 'lightning/navigation';
import {ShowToastEvent} from 'lightning/platformShowToastEvent';
export default class AccountCard extends NavigationMixin(LightningElement)
{
handleSaved(event)
{
this.dispatchEvent(new ShowToastEvent({title: 'Success', message: 'Saved', variant: 'success'}));
this[NavigationMixin.Navigate]({type: 'standard__recordPage',
attributes: {recordId: event.detail.id, actionName: 'view'}});
}
}KernDX Included
import {ComponentBuilder} from 'kern/componentBuilder';
// Ask only for the parts this component uses
export default class AccountCard extends ComponentBuilder('notification', 'navigation')
{
handleSaved(event)
{
this.showSuccessToast('Saved');
this.redirectToRecordPage(event.detail.id);
}
}You write: 1 Lightning web component. You configure: nothing.
What you also get
1 base class→12capabilities you didn't write
Less code
kern/componentBuilderkern/moduleNotificationkern/moduleNavigationkern/moduleControllerBuilt in too
kern/moduleLightningMessageService · kern/moduleFlowNavigationkern/featureFlagkern/utilityString · kern/utilityArray · kern/utilitySystemkern/flowFooter · kern/jsonViewerObservability
kern/utilityLoggerkern/utilityLoggerkern/utilityLogger · kern.LOG_BuilderWhy: Salesforce has no built-in test-data factory. Test.loadData loads rows from a CSV file kept as a static resource, but the file must carry every required field and is one more thing to keep in step with the org, so most teams build records by hand.
The builder fills required fields for you, saves a list with one save, and can skip the database by handing a selector pretend rows.
Plain Apex Manual
List<Account> accounts = new List<Account>();
for(Integer i = 0; i < 200; i++)
{
accounts.add(new Account(Name = 'Test ' + i, Industry = 'Technology'));
// ...and every required field your org added, by hand
}
insert accounts;
// To test the code that reads them, the rows must really be saved:
// there is no way to hand a query pretend rows.KernDX Included
// 200 Accounts, required fields filled in, saved with one save
List<SObject> accounts = kern.TST_Builder.of(Account.SObjectType)
.withOverride(Account.Industry, 'Technology')
.withCount(200)
.buildList();
// SEL_Accounts is your own selector: a with sharing class extending kern.SEL_Base.
// Or no database at all: the next Account read in this test gets these
kern.TST_Mock.of(Account.SObjectType).withCount(3).buildList();
List<SObject> found = new SEL_Accounts().query.toList(); // the 3 mock rowsYou write: test code only. You configure: nothing.
What you also get
2chains→14capabilities you didn't write
Speed
Less setup
Shared setup
Failure paths
Observability
Why: KernDX ships PMD rules (checks that read your Apex and report a pattern) that know its own way of working. Salesforce Code Analyzer runs them next to its standard rules, in your editor or in CI, and each finding says what to write instead.
Plain Salesforce Code Analyzer and code review Manual
// Your team agreed: every read goes through a selector.
public with sharing class CaseService
{
public static List<Case> openCases()
{
return [SELECT Id, Subject FROM Case WHERE IsClosed = false WITH USER_MODE];
}
}
// The standard rules check security and general style. This query
// runs in user mode, so the security rules have nothing to report:
// they do not know your team's rule. The rule lives in a wiki, and
// a reviewer has to spot every break of it, in every pull request.KernDX rules in Code Analyzer Included
sf code-analyzer run --config-file code-analyzer.yml --target force-app/ --view detail
// The finding, shortened:
CaseService.cls line 6 KernNoInlineSOQL severity 2 (High)
Inline SOQL is not allowed. Read through a selector (SEL_*),
or its query property for a custom query.
// What the message points you to. SEL_Cases is your own selector:
// a with sharing class extending kern.SEL_Base.
return (List<Case>)new SEL_Cases().query
.condition(Case.IsClosed).equals(false)
.toList();You write: nothing. You configure: copy kerndx-pmd-ruleset.xml into a scanner folder and add a code-analyzer.yml file, or run the bundle's kerndx init, which writes both.
What you also get
1scan→16checks you didn't write
Framework patterns
KernNoInlineSOQLKernNoDirectDMLKernNoSystemDebug · KernNoRawHttpKernUseSchedulerBase · KernNoRawScheduleKernTriggerMustDelegateKernNoRawCache · KernNoRawDescribe · KernNoRawCrypto · KernNoRawEmail · KernNoRawEventPublishLimits
KernLimitsThroughWrapperTests and security
KernNoCoverageTheatre · KernNoBooleanExceptionThrownKernCoverageExemptRequiresReasonKernUseTestBuilder · KernNoInlineDmlInTestsKernSecurityBypassCallSiteKernInvocableClassNeedsNoArgConstructor · KernJsonReadClassNeedsJsonAccessBeyond Apex
kerndx/use-component-builder · kerndx/no-hardcoded-user-textscanner/validate-naming.jsscanner/subscriber-naming-pmd-ruleset.xmlReview and CI
Why: Platform Cache keeps a value between requests, so you skip a slow query or callout the next time. UTIL_Cache puts a safe layer over it: it tries the session cache, then the org cache, accepts any key, zips large values, and returns null or false instead of throwing when no cache is there.
The package brings its own partition (a share of the cache), named Library and shown in Setup as LibraryCache.
Plain Apex Manual
Cache.OrgPartition partition = Cache.Org.getPartition('local.Rates');
Object rates = partition.get('usdToEur');
if(rates == null)
{
rates = RateService.fetch();
partition.put('usdToEur', rates, 3600);
}
// A key may hold only letters and digits, 50 at most: 'usd-to-eur' fails.
// A value over 100KB is refused; nothing is zipped for you.
// A partition name that does not exist throws, at every call.
// A value per user? Build the key with the user Id yourself.KernDX Included
kern.UTIL_Cache.Store cache = kern.UTIL_Cache.auto(); // session cache, then org cache
Object rates = cache.get('usd-to-eur'); // any key: a long or odd one is hashed
if(rates == null)
{
rates = RateService.fetch();
cache.put('usd-to-eur', rates, 3600); // zipped when it is large
}
// No cache space? get returns null and put returns false; nothing throws.
kern.UTIL_Cache.OperationResult result = cache.getLastOperationResult();
// result.status says what happened, and errorMessage says why.
// Your own partition instead: kern.UTIL_Cache.partition('local.Rates')You write: a few calls in your own class. You configure: space for the kern.Library partition in Setup (Platform Cache).
What you also get
1store→11capabilities you didn't write
Reliability
Less code
Set up
kern.Library · kern.UTIL_CacheWhy: the Kern app watches your KernDX integrations, events and background chains (not your whole org) and puts the tools to act on them in one place: no Postman, no throwaway anonymous Apex, no streaming client of your own.
Plain Apex and other tools Manual
// Something failed overnight. In anonymous Apex:
List<kern__LogEntry__c> errors = [
SELECT kern__ShortMessage__c, CreatedDate FROM kern__LogEntry__c
WHERE kern__LogLevel__c = 'ERROR' AND CreatedDate = TODAY
];
System.debug(errors.size()); // thousands of rows, mostly one error
// Which step of the chain broke? Read job records by hand.
// Replay the call? Postman. Watch events? Your own streaming client.
// Which fields hold sensitive data? A hand-written audit.KernDX: App Launcher, then Kern Included
Kern Home
Health Check is the org set up right? many fixes in one click
Log Console repeats grouped into problems; one run, one timeline
Chain Monitor which step broke and how far it got; retry or abort
API Test Harness fire a real callout or endpoint, with Safe Mode
Streaming Event Monitor watch platform events arrive as they happen
Data Masking Advisor build a masking configuration from a scanYou write: nothing. You configure: a KernDX permission set for each user, such as Kern Administrator or Kern Read Only.
What you also get
0lines→10screens and actions you didn't build
Troubleshoot
kern/logConsolekern/chainMonitorkern/chainMonitorkern/apiTestHarnessFormMonitor and set up
kern/healthCheckkern/streamingMonitorkern/scheduledJobDetailGovernance
kern/dataMaskingAdvisorkern/dataMaskingAdvisorPick your path
New to KernDX? From Plain Apex to KernDX shows the Apex you already write next to the KernDX version. Deciding whether to use it? Start with Why KernDX.
Built for AI-assisted development
Your AI assistant gets the standards before it writes.
KernDX ships its AI context as plain files in the public repo, with nothing to install, so Claude, Cursor, Copilot, or Gemini generate Apex and LWC that follow the framework (the naming, the secure defaults, the audited-bypass rule) instead of inventing their own.
KernDX is a library of Salesforce frameworks for Apex and LWC, open source under the Apache License 2.0. It is one managed package (namespace kern, API 68.0). It covers trigger handling, secure queries and saves, structured logging, background-job orchestration, scheduled jobs on a shared job runner, inbound and outbound REST, no-code feature flags and validation, and write-time data masking, plus the CI tooling (PMD rulesets, an ESLint plugin, secret scanning, and coverage gates).
What ships, and how to wire it up
- AGENTS.md sits at the repo root: the tool-neutral on-ramp that Claude Code, Cursor, Codex, and Cline read first. It orients your assistant and points it at the conventions and the full reference.
- AI Agent Instructions is the complete code-generation reference. Copy it into the rules file your tool auto-loads (
AGENTS.md,CLAUDE.md, or.cursorrules), or reference it so agit pullkeeps it current. - From then on your assistant writes framework-correct Apex and LWC: the right namespace prefix, FLS-enforced reads and writes, the naming rules, and the audited-bypass pattern, instead of reinventing them.
AGENTS.md · /llms.txt · Code Conventions Guide · PMD + ESLint rules
Those same standards ship as PMD rulesets and an ESLint plugin, so what the assistant follows is also enforced where you already work: inline in VS Code or IntelliJ / Illuminated Cloud, and gated on every pull request in CI.
Open the AI Agent Instructions →Ideas worth taking
Worth reading even if you never adopt KernDX.
These are design decisions, not feature names, so take the ideas with you. Each links to the guide that explains the thinking. The source is public under the Apache License 2.0.
Why a ‘safe to retry’ key isn't enough
If a retry shows up carrying different data than the first try, KernDX rejects it instead of replaying the old result, so a changed request can't silently overwrite the original.
Read the decision →Why a logging tool must avoid logging about itself
When the thing recording events is itself event-driven, naively logging its own activity loops forever. KernDX detects that case and writes the record directly.
Read the decision →Why an empty filter should match nothing, not everything
An empty “only include these” list should return nothing; an empty “exclude these” list, everything. Getting that right stops a filter bug from quietly scanning your whole table.
Read the decision →Why hiding card numbers takes more than pattern-matching
Plenty of 16-digit numbers aren't credit cards. KernDX matches the shape loosely, then runs the card-number checksum, so real cards get hidden while order numbers and dates are left alone.
Read the decision →Why the framework looks for your version of a class first
It checks your project for a class before falling back to its own, so “write your own and it wins” becomes a built-in way to customise behaviour, with nothing to register.
Read the decision →Why feature flags decide like an access list
Each rule can answer yes, no, or “not my call”, and that third answer is what lets you stack “block these, then allow those” rules in order without them fighting.
Read the decision →How a request flows
Many ways in. One secure core. Optional layers.
An LWC call, a DML save, a trigger, a REST endpoint, a batch job: any of them starts the same way. The core transaction is always there; the rest snap in only when your code uses them, and one tracking ID (the correlation ID) ties whichever layers ran into a single trace.
Adopt one layer today (just the query library, say) and snap in the trigger framework or the async chain the day you need it. The correlation ID makes whatever ran traceable as one request, and every chain it launches keeps a link back to it.
Already using fflib, Trigger Actions, or rolling your own?
What's different by default.
- Security is enforced on reads and writes, with an audit entry written when a call opts out through the builders, triggers or validation rules.
- One integrated package: triggers, queries, transactions, logging, REST, async, and masking share one model, instead of you wiring separate libraries together.
- 100% Apex coverage and PMD-clean, enforced on every build, not aspirational.
Honest about scope: where another library has something KernDX does not, the guide names it, capability by capability. For example, nebula-logger offers a choice of how each log is saved, all seven log levels, a retention date per log entry or scenario, and Big Object archiving. fflib-mocks can check how a mock was called and with what (behaviour verification).
Adopt at your own pace
Not all-or-nothing.
No rip-and-replace, and nothing you take all at once, which is what makes it low-risk to bring into an existing program. A typical path in: the query library first, then secure DML, then the trigger framework, adding async, masking, and the AI standards whenever you reach for them. Each layer stands alone, so adoption stays incremental and reversible.
A fit if…
- more than one developer works in the org
- AI is writing more of your Apex
- consistency is getting expensive
- onboarding a contributor takes too long
- you need security you can show a reviewer
Not needed if…
- your org has no Apex and none planned
Already running another framework? That is a cost to weigh, not a reason on its own. Staying has costs too, such as wiring separate libraries together or safety checks that can be switched off without a record. Moving has the cost of the migration. The capability-by-capability comparison sets out both.
Can't install a managed package, or would rather not? Because the source is available, you can deploy KernDX straight into your org as unmanaged code (no namespace, no Dev Hub), or repackage it under your own namespace. Installed unmanaged, its code counts toward your org's 6 MB Apex limit, and you update it by redeploying the source. There's a way in for every org.
Get started
Three ways in.
kern at v1.12 to your org. Swap it in within days.Repackage under your own nameBuild KernDX into your own package, as your code.CI tooling onlyPMD rulesets + ESLint plugin that flag violations inline in VS Code or IntelliJ / Illuminated Cloud and gate them in CI, with no framework code.