/lsc:lsc-custom-scriptsfrom lsc
Guides Life Sciences Cloud (LSC) Custom Script configuration for validation, checklists, and Visit Action Validation. Covers CodeText, LifeScienceCustomScript, IIFE patterns, Locker Service proxy issues, headless LWC validation components, and troubleshooting Visit Save/Submit hangs on iPadOS 27.
Ships in lsc. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
None: SKILL.md is the whole skill.
Always call MCP tools to get sourced documentation first. Then supplement with the domain knowledge in this skill.
| User asks about... | Call this tool |
|---|---|
| Custom script concepts, setup, documentation | search_lsc_knowledge({ query: "custom scripts validation" }) |
| Current org custom script records | run_soql({ query: "SELECT Id, Name, ComponentName, Type, ObjectName, OperationEventType FROM LifeScienceCustomScript ORDER BY Type, Name" }) |
| Workflow configuration / stage objects | search_lsc_knowledge({ query: "workflow configuration stage objects" }) |
| Admin Console custom script settings | list_admin_settings({ category: "CustomScript" }) |
| Object fields and relationships | describe_sobject({ sobject: "LifeScienceCustomScript" }) |
| Mobile cache status | check_mobile_cache_status() |
| Visit configuration (related) | check_visit_config() |
| Visit validation passes for institutions, or does not run on Save | search_lsc_knowledge({ query: "Visit Action Validation institution guard Save" }) then follow Institution script guard below. |
| Visit Save or Submit hangs on a spinner in Safari or Chrome on iPadOS 27, and the same save works on iPadOS 26 | search_lsc_knowledge({ query: "async Visit validation script Lightning Web Security iPadOS 27" }) then follow Save spinner on iPadOS 27 below. Read the script for async before asking for a HAR or which form is open. |
Always preserve the citation block (lines starting with > 📖, > 🔗, > 📂) from the tool response verbatim in your answer.
Load knowledge/modules/visit-management/support-engineering-visit-submit-async-lws.md. Finish only when the reply states every fact under Required answer. Save and Submit hang in Safari and Chrome on iPadOS 27.0.1 because Lightning Web Security leaves an async promise in the custom validation script unsettled, so submit never fires. The same save works on iPadOS 26.6.1. Remove async. Do not stop at a HAR or at which visit form is open.
Load knowledge/modules/visit-management/support-engineering-visit-script-institution-guard.md. Finish only when the reply states every fact under Required answer. The primary cause is an inverted institution check in the customer's script. A Save path that does not run the script is a second cause, and only when neither account type runs it on Save.
Before building a custom script, help the user choose the right mechanism:
| Mechanism | When to use | Online (Web) | Offline (iPad) |
|---|---|---|---|
| Validation Rule | Simple, single-object, field-level checks expressible with standard formulas | Yes | Yes |
| Custom Script (Visit Action Validation) | Complex validations spanning multiple objects (samples, details, attendees, messages) | Yes | Yes |
| Apex Trigger | Last resort — validation requires data not available on mobile | Yes | No |
Guidance: Start with validation rules whenever possible. Move to Custom Script Visit Action Validation when the logic spans multiple objects or needs conditional checks that validation rules can't express. Use Apex triggers only when the required data isn't synced to the mobile app.
| Type | When it runs | How it's assigned |
|---|---|---|
| Validation | Any workflow action (Record Update) | Assigned to Stage Objects |
| Checklist | User clicks info icon on Record Update actions | Assigned to Stage Objects |
| Visit Action Validation | User clicks Sign or Submit on a visit | Runs automatically (only one script runs — first by ID/creation date) |
Only one Visit Action Validation script runs per org. If multiple scripts of this type exist, only the first one executes (based on ID or creation date). All validation rules must be combined in a single script returning multiple results in the array.
For Validation and Checklist scripts, different scripts can be assigned to different Stage Objects.
| Field | Validation/Checklist | Visit Action Validation |
|---|---|---|
| Name | Required | Required |
| ComponentName | LWC component name | LWC component name |
| Type | Validation or Checklist | VisitActionValidation |
| ObjectName | Not required | ProviderVisit (required!) |
| OperationEventType | Not required | OnUpdate (required!) |
Without ObjectName and OperationEventType, Visit Action Validation scripts silently don't execute.
Custom scripts are headless LWC components deployed to the org. The platform stores the JavaScript in the CodeText field of LifeScienceCustomScript records and executes it from there — not from the deployed LWC directly.
After deploying an updated LWC, the user must click Refresh in Admin Console > Workflow Configuration > Custom Scripts to sync the code to the CodeText field.
CodeText is the runtime source of truthCodeText is read-only via API — it can only be updated through the Refresh buttonThe same CodeText script runs in two completely different JavaScript engines depending on platform:
| Web (Lightning) | iPad (LSC Mobile) | |
|---|---|---|
| Engine | Browser + Locker Service (WKWebView-style sandbox) | Native JavaScriptCore (JSContext) — no Locker Service |
Globals (record, user, db, env) | Locker Service secure proxies | Native Swift objects bridged via JSExport |
| Return values | Wrapped in Locker Service Proxy objects | Bridged native objects (not Locker proxies) |
Where env.log() / console.log goes | Browser devtools console | Device logs (Console.app / Xcode device console) — NOT a browser console |
Why this matters:
unwrapProxy(results) requirement (gotcha #2) exists to strip Locker Service proxies on web. On iPad there is no Locker Service, but JSON.parse(JSON.stringify(results)) is still the correct way to return plain data across the JavaScriptCore bridge — keep it for both platforms.All Visit Action Validation scripts must follow this pattern. Do not deviate. On iPadOS 27 this async pattern hangs Save and Submit in Safari and Chrome. See Save spinner on iPadOS 27 and remove async for that browser. Desktop and iPadOS 26 still use the pattern below.
(() => {
function parseContextData(record) {
try {
if (!record || typeof record.getContextData !== 'function') return {};
var contextData = record.getContextData();
if (typeof contextData === 'string') return JSON.parse(contextData);
if (typeof contextData === 'object' && contextData !== null) return contextData;
return {};
} catch (e) { return {}; }
}
function getFieldData(contextData, baseFieldName) {
return contextData[baseFieldName + '.VisitId'] || contextData[baseFieldName];
}
function unwrapProxy(results) {
return JSON.parse(JSON.stringify(results));
}
async function myValidation(contextData) {
try {
// Validation logic here
// Return { title: "message", status: "success" | "warning" | "error" }
} catch (e) {
return { title: 'Validation error: ' + e.message, status: 'error' };
}
}
async function validateVisit() {
try {
var contextData = parseContextData(record);
var hasWebField = contextData['ProviderVisit'] !== undefined;
var result = await myValidation(contextData);
var results = [result];
if (hasWebField) { var resolved = await Promise.all(results); return unwrapProxy(resolved); }
return unwrapProxy(results);
} catch (error) {
return [{ title: 'Validation error: ' + error.message, status: 'error' }];
}
}
if (record && user && env && db) {
var contextData = parseContextData(record);
var hasWebField = contextData['ProviderVisit'] !== undefined;
if (hasWebField) return [validateVisit()];
else return validateVisit();
}
})();
Workflow Validation and Checklist scripts use a simpler pattern — no platform detection needed:
(() => {
async function validateSomething() {
try {
// Validation logic using record, db, env globals
return { title: "Validation passed", status: "success" };
} catch (error) {
return { title: "Error: " + error.message, status: "error" };
}
}
return [validateSomething()];
})();
record.getContextData() returns a JSON object with the visit and all related child records.
On web, child records are keyed by ObjectName.VisitId. On mobile, they use just the object name.
{
"ProviderVisit": { ... }, // The visit record
"PresentationForum.ForumReferenceId": [ ... ], // CLM presentations
"ProviderVisitProdDetailing.VisitId": [ ... ], // Detailed products
"ProductDisbursement.VisitId": [ ... ], // Samples left
"ProviderVisitRqstSample.VisitId": [ ... ], // Sample requests
"ProviderVisitMarketingItem.VisitId": [ ... ], // Marketing items
"Visit.ParentVisitId": [ ... ], // Attendee child visits
"version": "...", // Data version
"sObjectType": "..." // Object type
}
These objects are in the context payload and can be read directly:
ProviderVisit — visit header fields (Id, AccountId, Channel, Status, Description, etc.)ProviderVisitProdDetailing.VisitId — detailed products (with AdditionalInformation JSON)ProductDisbursement.VisitId — samples (with AdditionalInformation JSON)ProviderVisitRqstSample.VisitId — sample requestsProviderVisitMarketingItem.VisitId — marketing itemsPresentationForum.ForumReferenceId — CLM presentationsVisit.ParentVisitId — attendee child visitsNested (NOT top-level):
ProviderVisitDtlProductMsg — nested on each ProviderVisitProdDetailing record as detailRecord['ProviderVisitDtlProductMsg.VisitId']ProviderVisitProdDiscussion — nested on each detail record similarlyThese are NOT in the context and require await db.query(...):
Account (IsPersonAccount, Specialty, etc.)Product2 (Brand, Name, custom fields)ProductItem (ExpirationDate, Product2Id)Profile (Name — query by name, not hardcoded ID)UserAdditionalInfo (ProfileIdentifier)ObjectTerritory2Association / UserTerritory2AssociationIndividualConsent or custom consent objects{
"Product2": { "Name": "Immunexis 10mg" },
"ProductionBatch": {
"Name": "IMX-BG6678",
"ExpirationDate": "2030-01-30T00:00:00.000Z"
}
}
{
"LifeScienceMarketableProduct": { "Name": "Immunexis" },
"Indication": { "Name": null },
"Brand": { "Name": null },
"TherapeuticArea": { "Name": null }
}
Web and mobile may use different casing:
| Web | Mobile |
|---|---|
ProductItemId | productitemid |
AccountId | accountid |
QuantityDisbursed | quantitydisbursed |
Channel | channel |
Always check both: record.ProductItemId || record.productitemid
stringValue() does NOT work for custom fields (__c) on either platform. Standard fields and custom fields require different access methods:
| Method | Standard Fields | Custom Fields (Web) | Custom Fields (iPad) |
|---|---|---|---|
stringValue('Field') | Works | Does NOT work | Does NOT work |
.sObject.Field__c | Works | Works | No sObject on mobile |
noNs_stringValue('Field__c') | Works | Not needed | Works |
Cross-platform helper (always use this for custom fields):
function getCustomField(queryResult, fieldName) {
if (!queryResult) return null;
// Web: use sObject property
if (queryResult.sObject && queryResult.sObject[fieldName] !== undefined) {
return queryResult.sObject[fieldName];
}
// iPad: use noNs_stringValue
if (typeof queryResult.noNs_stringValue === 'function') {
var val = queryResult.noNs_stringValue(fieldName);
if (val !== undefined) return val;
}
return null;
}
Important details:
sObject on web — they return undefined, not nulldb.query result object is completely different between platforms:
sObject, accessibleFields, sObjectName, namespaceUtils propertiesenableAccessErrors, stringValue, numValue, boolValue, dateValue, setValue, noNs_stringValue, noNs_numValue, noNs_boolValue, noNs_dateValue, noNs_setValue, recordTypeName, saveOn web, AccountId is available in contextData.ProviderVisit.AccountId. On mobile, ProviderVisit doesn't exist in the context. Use the record global as a fallback:
var visit = contextData.ProviderVisit || {};
var accountId = visit.AccountId || visit.accountid;
if (!accountId) {
try { accountId = record.stringValue('AccountId'); } catch (e) {}
}
| Global | Description | Key Methods |
|---|---|---|
record | Current record | stringValue(field), boolValue(field), getContextData() |
user | Current user | stringValue(field) |
db | Database access | query(entity, conditions, fields) |
env | Environment | getOption(key), log(message) |
Injected globals (confirmed against businessRuleValidator/objectInitialization.js):
ConditionBuilder, ConditionBuilder_noNs, ConditionEnhancedBuilder, ConditionEnhancedBuilder_noNs, Query, SetCondition, SetCondition_noNs, FieldCondition, FieldCondition_noNs, DateFieldCondition, DateFieldCondition_noNs, DateTimeFieldCondition, DateTimeFieldCondition_noNs, AndCondition, OrCondition, enableAccessErrors
_noNs variant for accessing custom (__c) fields without the managed-package namespace prefix — use the _noNs form when working with custom fields (mirrors the noNs_stringValue pattern for db.query results).Query is the query builder; enableAccessErrors surfaces field-access errors instead of silently returning null.GroupCondition is NOT injected — it is an internal base class, not available to scripts. Do not reference it.{ title: string, status: string } // "success", "warning", or "error"
| Status | Checklist | Validation |
|---|---|---|
success | Green check | Not displayed |
warning | Yellow alert | Shows warning dialog, user can continue |
error | Red X | Blocks action, shows error dialog |
When helping users write or debug custom scripts, always warn about these:
No comment blocks before the IIFE. JSDoc or multi-line comment blocks (/** ... */) before (() => { cause Locker Service to silently fail — the platform shows a generic error with zero console output. Put comments inside the IIFE only.
Proxy wrapping breaks results. On web, return values get wrapped in Locker Service Proxy objects and translateValidationResults cannot read them. Always call unwrapProxy(results) (JSON.parse(JSON.stringify(results))) before returning. Without this, the platform silently allows the visit through. (iPad runs in native JavaScriptCore with no Locker Service — but unwrapProxy is still required to return plain data across the bridge. See "Two Runtimes" above.)
Large scripts crash silently. If a script is too large, Locker Service fails to evaluate it. Keep scripts small and focused.
CodeText is the runtime source. The platform executes from CodeText, not the deployed LWC. Always click Refresh after deploying.
ObjectName and OperationEventType required. Without ObjectName = 'ProviderVisit' and OperationEventType = 'OnUpdate' on the LifeScienceCustomScript record, Visit Action Validation scripts silently don't execute. Visit Action Validation has no removal event. OnDelete is not a hook for removing an attendee. Do not tell a user to add an OnDelete Visit Action Validation script to block that removal.
Only one Visit Action Validation runs. First by ID/creation date. Combine all rules in one script.
Product messages are nested. ProviderVisitDtlProductMsg is NOT a top-level context key. Access via detailRecord['ProviderVisitDtlProductMsg.VisitId'].
Use env.log() for debugging. Add env.log('scriptName - message') calls to trace execution. Output goes to the browser console on web and to device logs on iPad (JavaScriptCore has no browser console). This is the only way to debug custom scripts.
Guard globals. Always wrap execution in if (record && user && env && db).
Sharing defaults to Private. Rep users need record-level access to LifeScienceCustomScript records. Change OWD to Public Read Only if reps can't see scripts.
Query Profile by name, not ID. Profile IDs differ between orgs. Query Profile where Name = 'Field Sales Representative' and use the returned ID.
The quantity field is QuantityDisbursed, not Quantity. On mobile, field names may be lowercase.
Custom fields (__c) require special access. stringValue() does NOT work for custom fields on either platform. On web, use .sObject.Field__c. On iPad, use noNs_stringValue('Field__c'). Always use the getCustomField() helper for cross-platform code. See the "Accessing Custom Fields" section above.
Null custom fields are silently dropped on web. db.query omits custom fields with null values from the sObject — accessing them returns undefined, which looks identical to "field not supported". Always test with non-null values.
iPad custom fields require DB Schema configuration. Custom fields must be in the mobile metadata cache (Admin Console > Mobile > Object Metadata Cache Configuration). Regenerate cache and re-login after adding fields. Without this, noNs_stringValue returns undefined.
Mobile db.query results have no sObject property. The result object on iPad is completely opaque — no enumerable properties, JSON.stringify returns {}. Use the method-based API (noNs_stringValue, numValue, boolValue, etc.) instead.
AccountId not in contextData on mobile. On web, contextData.ProviderVisit.AccountId works. On mobile, ProviderVisit doesn't exist in the context. Fall back to record.stringValue('AccountId').
async hangs Save and Submit on iPadOS 27. In Safari and Chrome on iPadOS 27.0.1, Lightning Web Security leaves a sandboxed async promise in the custom validation script unsettled, so submit never fires and the spinner stays up. The same script finishes on iPadOS 26.6.1. Remove async. Do not stop at a console or HAR capture, or at Visit Engagement versus Log a Visit. This is the browser, not the native iPad app.
When the user asks about configuring custom scripts, ask them which mode they prefer:
search_lsc_knowledge({ query: "custom scripts" }) and present the relevant sectionsDefault to guided setup when connected to an org, or documentation mode if no org is connected.
run_soql({ query: "SELECT Id, Name, ComponentName, Type, ObjectName, OperationEventType, CreatedDate FROM LifeScienceCustomScript ORDER BY Type, CreatedDate" })
Report:
If more than one Visit Action Validation script exists, warn immediately — only the first one (by ID/creation date) runs. The others are silently ignored.
For each Visit Action Validation script, verify:
ObjectName = ProviderVisitOperationEventType = OnUpdateIf either is missing, the script will silently not execute.
run_soql({ query: "SELECT Id, Name FROM LifeScienceCustomScript LIMIT 1" })
Remind user that LifeScienceCustomScript defaults to Private sharing. If field reps can't see validation results, OWD needs to be changed to Public Read Only.
After any LWC deployment, the user must click Refresh in Admin Console > Workflow Configuration > Custom Scripts to sync code to CodeText.
If the user wants to create a new validation script:
db.query?). If Save or Submit already hangs in Safari or Chrome on iPadOS 27, the script must not be async.env.log() calls for debugging| Correct | Wrong (NEVER use) |
|---|---|
LifeScienceCustomScript | CustomScript__c, LifeSciCustomScript |
ProviderVisit | ProviderVisit__c, Visit__c |
ProviderVisitProdDetailing | ProviderVisitProductDetailing__c |
ProductDisbursement | SampleDrop__c |
ProductItem | InventoryItem__c |
Product2 | SampleProduct__c |
Profile | (query by Name, not hardcoded ID) |
run_soql for Admin Console settings — use list_admin_settingsrun_soql for mobile cache — use check_mobile_cache_status()CodeText via API — it is read-only and can only be synced via the Refresh buttonReference examples are available at https://github.com/lsc-ideas/lsc-custom-scripts-examples. Point users here for working code examples covering common pharma validation patterns.
| Task | Path |
|---|---|
| Custom Scripts | Admin Console > Workflow Configuration > Custom Scripts |
| Refresh CodeText | Admin Console > Workflow Configuration > Custom Scripts > Refresh (per row) |
| Stage Objects (assign scripts) | Admin Console > Workflow Configuration > Stage Objects > Edit |
| Workflow Paths | Admin Console > Workflow Configuration > Workflow Paths |
| Sharing Settings | Setup > Sharing Settings > LifeScienceCustomScript |
What SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
lsc, custom-scripts, visit-validation, locker-service, ipados
39 skills in this plugin
/lsc-account-managementGuides Life Sciences Cloud (LSC) Account Management configuration for web and mobile apps. Use when user asks about provider card, addresses, affiliations, ratings, account search, search before create (SBC), data change requests (DCR), business licenses, multi-object component, ARC graph, ContactPointAddress, HealthcareProvider, ProviderAffiliation, Admin Console account settings, or a web HCO picker that returns no organizations./lsc-activity-planGuides Life Sciences Cloud (LSC) Activity Plan configuration for web and mobile apps. Use when user asks about activity plans, account goals, weighted territory goals, shared territory goals, provider activity goals, goal measures, product goals, activity plan review, activity plan batch jobs, time periods, plan cycle, or Admin Console activity plan settings./lsc-npx claudepluginhub salesforcelabs/lsc-for-claude --plugin lscOther plugins' skills for the same job