@xrmforge/helpers 0.1.0 → 0.1.1
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/dist/index.js +0 -1
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -191,7 +191,6 @@ function createBoundAction(operationName, entityLogicalName, paramMeta) {
|
|
|
191
191
|
}
|
|
192
192
|
function createUnboundAction(operationName, paramMeta) {
|
|
193
193
|
return {
|
|
194
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- return type varies (Response or parsed JSON)
|
|
195
194
|
async execute(params) {
|
|
196
195
|
const req = buildUnboundRequest(
|
|
197
196
|
operationName,
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/webapi-helpers.ts","../src/xrm-constants.ts","../src/action-runtime.ts","../src/typed-form.ts"],"sourcesContent":["/**\n * @xrmforge/helpers - Web API Helper Functions\n *\n * Lightweight utility functions for building OData query strings\n * with type-safe field names from generated Fields enums.\n *\n * Zero runtime overhead when used with const enums (values are inlined).\n *\n * @example\n * ```typescript\n * import { select } from '@xrmforge/helpers';\n *\n * Xrm.WebApi.retrieveRecord(ref.entityType, ref.id, select(\n * AccountFields.Name,\n * AccountFields.WebsiteUrl,\n * AccountFields.Address1Line1,\n * ));\n * ```\n */\n\n/**\n * Build an OData $select query string from field names.\n *\n * @param fields - Field names (use generated Fields enum for type safety)\n * @returns OData query string (e.g. \"?$select=name,websiteurl,address1_line1\")\n */\nexport function select(...fields: string[]): string {\n if (fields.length === 0) return '';\n return `?$select=${fields.join(',')}`;\n}\n\n/**\n * Parse a lookup field from a Dataverse Web API response into a LookupValue.\n *\n * Dataverse returns lookups as `_fieldname_value` with OData annotations:\n * - `_fieldname_value` (GUID)\n * - `_fieldname_value@OData.Community.Display.V1.FormattedValue` (display name)\n * - `_fieldname_value@Microsoft.Dynamics.CRM.lookuplogicalname` (entity type)\n *\n * This function extracts all three into an `Xrm.LookupValue` object.\n *\n * @param response - The raw Web API response object\n * @param navigationProperty - Navigation property name (use NavigationProperties enum for type safety)\n * @returns Xrm.LookupValue or null if the lookup is empty\n *\n * @example\n * ```typescript\n * // With NavigationProperties enum (recommended):\n * parseLookup(result, AccountNav.Country);\n *\n * // Or with navigation property name directly:\n * parseLookup(result, 'markant_address1_countryid');\n * ```\n */\nexport function parseLookup(\n response: Record<string, unknown>,\n navigationProperty: string,\n): { id: string; name: string; entityType: string } | null {\n const key = `_${navigationProperty}_value`;\n const id = response[key] as string | undefined;\n if (!id) return null;\n\n return {\n id,\n name: (response[`${key}@OData.Community.Display.V1.FormattedValue`] as string) ?? '',\n entityType: (response[`${key}@Microsoft.Dynamics.CRM.lookuplogicalname`] as string) ?? '',\n };\n}\n\n/**\n * Parse multiple lookup fields from a Dataverse Web API response at once.\n *\n * @param response - The raw Web API response object\n * @param navigationProperties - Navigation property names to parse\n * @returns Map of navigation property name to LookupValue (null entries omitted)\n *\n * @example\n * ```typescript\n * const lookups = parseLookups(result, ['markant_address1_countryid', 'parentaccountid']);\n * formContext.getAttribute(Fields.Country).setValue(\n * lookups.markant_address1_countryid ? [lookups.markant_address1_countryid] : null\n * );\n * ```\n */\nexport function parseLookups(\n response: Record<string, unknown>,\n navigationProperties: string[],\n): Record<string, { id: string; name: string; entityType: string } | null> {\n const result: Record<string, { id: string; name: string; entityType: string } | null> = {};\n for (const prop of navigationProperties) {\n result[prop] = parseLookup(response, prop);\n }\n return result;\n}\n\n/**\n * Get the formatted (display) value of any field from a Web API response.\n *\n * Works for OptionSets, Lookups, DateTimes, Money, and other formatted fields.\n *\n * @param response - The raw Web API response object\n * @param fieldName - The field logical name (e.g. \"statecode\", \"createdon\")\n * @returns The formatted string value, or null if not available\n *\n * @example\n * ```typescript\n * const status = parseFormattedValue(result, 'statecode');\n * // \"Active\" (instead of 0)\n * ```\n */\nexport function parseFormattedValue(\n response: Record<string, unknown>,\n fieldName: string,\n): string | null {\n return (response[`${fieldName}@OData.Community.Display.V1.FormattedValue`] as string) ?? null;\n}\n\n/**\n * Build an OData $select and $expand query string.\n *\n * @param fields - Field names to select\n * @param expand - Navigation property to expand (optional)\n * @returns OData query string\n *\n * @example\n * ```typescript\n * Xrm.WebApi.retrieveRecord(\"account\", id, selectExpand(\n * [AccountFields.Name, AccountFields.WebsiteUrl],\n * \"primarycontactid($select=fullname,emailaddress1)\"\n * ));\n * ```\n */\nexport function selectExpand(fields: string[], expand: string): string {\n const parts: string[] = [];\n if (fields.length > 0) parts.push(`$select=${fields.join(',')}`);\n if (expand) parts.push(`$expand=${expand}`);\n return parts.length > 0 ? `?${parts.join('&')}` : '';\n}\n","/**\n * @xrmforge/helpers - Xrm API Constants\n *\n * Const enums for all common Xrm string/number constants.\n * Eliminates raw strings in D365 form scripts.\n *\n * @types/xrm defines these as string literal types for compile-time checking,\n * but does NOT provide runtime constants (XrmEnum is not available at runtime).\n * These const enums are erased at compile time (zero runtime overhead).\n *\n * @example\n * ```typescript\n * import { DisplayState } from '@xrmforge/helpers';\n *\n * if (tab.getDisplayState() === DisplayState.Expanded) { ... }\n * ```\n */\n\n/** Tab/Section display state */\nexport const enum DisplayState {\n Expanded = 'expanded',\n Collapsed = 'collapsed',\n}\n\n// FormType: use XrmEnum.FormType from @types/xrm (already defined as const enum there)\n\n/** Form notification level (formContext.ui.setFormNotification) */\nexport const enum FormNotificationLevel {\n Error = 'ERROR',\n Warning = 'WARNING',\n Info = 'INFO',\n}\n\n/** Attribute required level (attribute.setRequiredLevel) */\nexport const enum RequiredLevel {\n None = 'none',\n Required = 'required',\n Recommended = 'recommended',\n}\n\n/** Attribute submit mode (attribute.setSubmitMode) */\nexport const enum SubmitMode {\n Always = 'always',\n Never = 'never',\n Dirty = 'dirty',\n}\n\n/** Save mode (eventArgs.getSaveMode()) */\nexport const enum SaveMode {\n Save = 1,\n SaveAndClose = 2,\n Deactivate = 5,\n Reactivate = 6,\n Send = 7,\n Disqualify = 15,\n Qualify = 16,\n Assign = 47,\n SaveAsCompleted = 58,\n SaveAndNew = 59,\n AutoSave = 70,\n}\n\n/** Client type (Xrm.Utility.getGlobalContext().client.getClient()) */\nexport const enum ClientType {\n Web = 'Web',\n Outlook = 'Outlook',\n Mobile = 'Mobile',\n}\n\n/** Client state (Xrm.Utility.getGlobalContext().client.getClientState()) */\nexport const enum ClientState {\n Online = 'Online',\n Offline = 'Offline',\n}\n\n// WebApi Execute Constants\n\n/** Operation type for Xrm.WebApi.execute getMetadata().operationType */\nexport const enum OperationType {\n /** Custom Action or OOB Action (POST) */\n Action = 0,\n /** Custom Function or OOB Function (GET) */\n Function = 1,\n /** CRUD operation (Create, Retrieve, Update, Delete) */\n CRUD = 2,\n}\n\n/** Structural property for getMetadata().parameterTypes[].structuralProperty */\nexport const enum StructuralProperty {\n Unknown = 0,\n PrimitiveType = 1,\n ComplexType = 2,\n EnumerationType = 3,\n Collection = 4,\n EntityType = 5,\n}\n\n/** Binding type for Custom API definitions */\nexport const enum BindingType {\n /** Not bound to an entity (globally callable) */\n Global = 0,\n /** Bound to a single entity record */\n Entity = 1,\n /** Bound to an entity collection */\n EntityCollection = 2,\n}\n","/**\n * @xrmforge/helpers - Action/Function Runtime Helpers\n *\n * Factory functions for type-safe Custom API execution.\n * These are imported by generated action/function modules.\n *\n * Design:\n * - `createBoundAction` / `createUnboundAction`: Produce executor objects\n * with `.execute()` (calls Xrm.WebApi) and `.request()` (for executeMultiple)\n * - `executeRequest`: Central execute wrapper (single place for the `as any` cast)\n * - `withProgress`: Convenience wrapper with progress indicator + error dialog\n *\n * @example\n * ```typescript\n * // Generated code (in generated/actions/quote.ts):\n * import { createBoundAction } from '@xrmforge/helpers';\n * export const WinQuote = createBoundAction('markant_winquote', 'quote');\n *\n * // Developer code (in quote-form.ts):\n * import { WinQuote } from '../generated/actions/quote';\n * const response = await WinQuote.execute(recordId);\n * ```\n */\n\nimport { OperationType, StructuralProperty } from './xrm-constants.js';\n\n// Types\n\n/** Parameter metadata for getMetadata().parameterTypes */\nexport interface ParameterMeta {\n typeName: string;\n structuralProperty: number;\n}\n\n/** Map of parameter names to their OData metadata */\nexport type ParameterMetaMap = Record<string, ParameterMeta>;\n\n/** Executor for a bound action without additional parameters */\nexport interface BoundActionExecutor {\n execute(recordId: string): Promise<Response>;\n request(recordId: string): Record<string, unknown>;\n}\n\n/** Executor for a bound action with typed parameters */\nexport interface BoundActionWithParamsExecutor<TParams> {\n execute(recordId: string, params: TParams): Promise<Response>;\n request(recordId: string, params: TParams): Record<string, unknown>;\n}\n\n/** Executor for an unbound action without parameters */\nexport interface UnboundActionExecutor {\n execute(): Promise<Response>;\n request(): Record<string, unknown>;\n}\n\n/** Executor for an unbound action with typed parameters and optional typed response */\nexport interface UnboundActionWithParamsExecutor<TParams, TResult = void> {\n execute(params: TParams): Promise<TResult extends void ? Response : TResult>;\n request(params: TParams): Record<string, unknown>;\n}\n\n/** Executor for an unbound function with typed response */\nexport interface UnboundFunctionExecutor<TResult> {\n execute(): Promise<TResult>;\n request(): Record<string, unknown>;\n}\n\n/** Executor for a bound function with typed response */\nexport interface BoundFunctionExecutor<TResult> {\n execute(recordId: string): Promise<TResult>;\n request(recordId: string): Record<string, unknown>;\n}\n\n// Central Execute\n\n/**\n * Execute a single request via Xrm.WebApi.online.execute().\n *\n * This is the ONLY place in the entire framework where the `as any` cast happens.\n * All generated executors call this function internally.\n */\nexport function executeRequest(request: Record<string, unknown>): Promise<Response> {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return (Xrm.WebApi as any).online.execute(request) as Promise<Response>;\n}\n\n/**\n * Execute multiple requests via Xrm.WebApi.online.executeMultiple().\n *\n * @param requests - Array of request objects (from `.request()` factories).\n * Wrap a subset in an inner array for transactional changeset execution.\n */\nexport function executeMultiple(\n requests: Array<Record<string, unknown> | Array<Record<string, unknown>>>,\n): Promise<Response[]> {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return (Xrm.WebApi as any).online.executeMultiple(requests) as Promise<Response[]>;\n}\n\n// Request Builder (internal)\n\nfunction cleanRecordId(id: string): string {\n return id.replace(/[{}]/g, '');\n}\n\nfunction buildBoundRequest(\n operationName: string,\n entityLogicalName: string,\n operationType: OperationType,\n recordId: string,\n paramMeta?: ParameterMetaMap,\n params?: Record<string, unknown>,\n): Record<string, unknown> {\n const parameterTypes: Record<string, ParameterMeta> = {\n entity: {\n typeName: `mscrm.${entityLogicalName}`,\n structuralProperty: StructuralProperty.EntityType,\n },\n };\n\n if (paramMeta) {\n for (const [key, meta] of Object.entries(paramMeta)) {\n parameterTypes[key] = meta;\n }\n }\n\n const request: Record<string, unknown> = {\n getMetadata: () => ({\n boundParameter: 'entity',\n parameterTypes,\n operationName,\n operationType,\n }),\n entity: {\n id: cleanRecordId(recordId),\n entityType: entityLogicalName,\n },\n };\n\n if (params) {\n for (const [key, value] of Object.entries(params)) {\n request[key] = value;\n }\n }\n\n return request;\n}\n\nfunction buildUnboundRequest(\n operationName: string,\n operationType: OperationType,\n paramMeta?: ParameterMetaMap,\n params?: Record<string, unknown>,\n): Record<string, unknown> {\n const parameterTypes: Record<string, ParameterMeta> = {};\n\n if (paramMeta) {\n for (const [key, meta] of Object.entries(paramMeta)) {\n parameterTypes[key] = meta;\n }\n }\n\n const request: Record<string, unknown> = {\n getMetadata: () => ({\n boundParameter: null,\n parameterTypes,\n operationName,\n operationType,\n }),\n };\n\n if (params) {\n for (const [key, value] of Object.entries(params)) {\n request[key] = value;\n }\n }\n\n return request;\n}\n\n// Action Factories\n\n/**\n * Create an executor for a bound action (entity-bound).\n *\n * @param operationName - Custom API unique name (e.g. \"markant_winquote\")\n * @param entityLogicalName - Entity logical name (e.g. \"quote\")\n */\nexport function createBoundAction(\n operationName: string,\n entityLogicalName: string,\n): BoundActionExecutor;\n\n/**\n * Create an executor for a bound action with typed parameters.\n *\n * @param operationName - Custom API unique name\n * @param entityLogicalName - Entity logical name\n * @param paramMeta - Parameter metadata map (parameter name to OData type info)\n */\nexport function createBoundAction<TParams extends Record<string, unknown>>(\n operationName: string,\n entityLogicalName: string,\n paramMeta: ParameterMetaMap,\n): BoundActionWithParamsExecutor<TParams>;\n\nexport function createBoundAction<TParams extends Record<string, unknown>>(\n operationName: string,\n entityLogicalName: string,\n paramMeta?: ParameterMetaMap,\n): BoundActionExecutor | BoundActionWithParamsExecutor<TParams> {\n return {\n execute(recordId: string, params?: TParams): Promise<Response> {\n const req = buildBoundRequest(\n operationName, entityLogicalName, OperationType.Action,\n recordId, paramMeta, params,\n );\n return executeRequest(req);\n },\n request(recordId: string, params?: TParams): Record<string, unknown> {\n return buildBoundRequest(\n operationName, entityLogicalName, OperationType.Action,\n recordId, paramMeta, params,\n );\n },\n };\n}\n\n/**\n * Create an executor for an unbound (global) action without parameters.\n *\n * @param operationName - Custom API unique name\n */\nexport function createUnboundAction(\n operationName: string,\n): UnboundActionExecutor;\n\n/**\n * Create an executor for an unbound action with typed parameters and response.\n *\n * @param operationName - Custom API unique name\n * @param paramMeta - Parameter metadata map\n */\nexport function createUnboundAction<\n TParams extends Record<string, unknown>,\n TResult = void,\n>(\n operationName: string,\n paramMeta: ParameterMetaMap,\n): UnboundActionWithParamsExecutor<TParams, TResult>;\n\nexport function createUnboundAction<\n TParams extends Record<string, unknown>,\n TResult = void,\n>(\n operationName: string,\n paramMeta?: ParameterMetaMap,\n): UnboundActionExecutor | UnboundActionWithParamsExecutor<TParams, TResult> {\n return {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- return type varies (Response or parsed JSON)\n async execute(params?: TParams): Promise<any> {\n const req = buildUnboundRequest(\n operationName, OperationType.Action, paramMeta, params,\n );\n const response = await executeRequest(req);\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(errorText);\n }\n if (response.status !== 204) {\n return response.json();\n }\n return response;\n },\n request(params?: TParams): Record<string, unknown> {\n return buildUnboundRequest(\n operationName, OperationType.Action, paramMeta, params,\n );\n },\n };\n}\n\n// Function Factories\n\n/**\n * Create an executor for an unbound (global) function with typed response.\n *\n * @param operationName - Function name (e.g. \"WhoAmI\")\n */\nexport function createUnboundFunction<TResult>(\n operationName: string,\n): UnboundFunctionExecutor<TResult> {\n return {\n async execute(): Promise<TResult> {\n const req = buildUnboundRequest(operationName, OperationType.Function);\n const response = await executeRequest(req);\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(errorText);\n }\n return response.json() as Promise<TResult>;\n },\n request(): Record<string, unknown> {\n return buildUnboundRequest(operationName, OperationType.Function);\n },\n };\n}\n\n/**\n * Create an executor for a bound function with typed response.\n *\n * @param operationName - Function name\n * @param entityLogicalName - Entity logical name\n */\nexport function createBoundFunction<TResult>(\n operationName: string,\n entityLogicalName: string,\n): BoundFunctionExecutor<TResult> {\n return {\n async execute(recordId: string): Promise<TResult> {\n const req = buildBoundRequest(\n operationName, entityLogicalName, OperationType.Function, recordId,\n );\n const response = await executeRequest(req);\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(errorText);\n }\n return response.json() as Promise<TResult>;\n },\n request(recordId: string): Record<string, unknown> {\n return buildBoundRequest(\n operationName, entityLogicalName, OperationType.Function, recordId,\n );\n },\n };\n}\n\n// Convenience\n\n/**\n * Execute an async operation with Xrm progress indicator.\n *\n * Shows a progress spinner before the operation, closes it after,\n * and shows an error dialog on failure.\n *\n * @param message - Progress indicator message (e.g. \"Processing quote...\")\n * @param operation - Async function to execute\n * @returns The result of the operation\n *\n * @example\n * ```typescript\n * await withProgress('Processing quote...', () => WinQuote.execute(recordId));\n * ```\n */\nexport async function withProgress<T>(\n message: string,\n operation: () => Promise<T>,\n): Promise<T> {\n Xrm.Utility.showProgressIndicator(message);\n try {\n return await operation();\n } catch (error: unknown) {\n const msg = error instanceof Error ? error.message : String(error);\n Xrm.Navigation.openErrorDialog({ message: msg });\n throw error;\n } finally {\n Xrm.Utility.closeProgressIndicator();\n }\n}\n","/**\n * @xrmforge/helpers - TypedForm Proxy\n *\n * Creates a proxy around Xrm.FormContext that allows direct property access\n * to form fields. Instead of formContext.getAttribute(\"name\").setValue(\"X\"),\n * write form.name.setValue(\"X\").\n *\n * @example\n * ```typescript\n * import { typedForm } from '@xrmforge/helpers';\n *\n * type LeadForm = XrmForge.Forms.Lead.LeadMarkantLeadForm;\n *\n * const form = typedForm<LeadForm>(formContext);\n * form.companyname.setValue(\"Contoso\"); // StringAttribute\n * form.parentaccountid.getValue(); // LookupValue[] | null\n * form.$context.ui.setFormNotification(...); // Full FormContext access\n * form.$control(\"companyname\").setDisabled(true);\n * ```\n */\n\n/**\n * Extracts the Fields union type from a generated Form interface.\n * Works with the XrmForge-generated pattern:\n * getAttribute<K extends Fields>(name: K): AttrMap[K]\n *\n * For overloaded getAttribute, TypeScript resolves to the last overload.\n * Our generated interfaces have the generic overload first, so we use\n * a mapped approach with the AttrMap instead.\n */\nexport type FormFields<TForm> = TForm extends {\n getAttribute(name: infer K): unknown;\n} ? K extends string ? K : string : string;\n\n/**\n * TypedForm: proxy type that maps field names to their attribute types.\n *\n * Since extracting Fields + AttrMap from overloaded getAttribute is unreliable\n * in TypeScript, we use a two-parameter approach internally but expose a\n * single-parameter API via a helper type generated by typegen (FormTypedInfo).\n *\n * For v0.1.0 we support both signatures:\n * typedForm<TForm>(fc) -- works when TForm has proper generic getAttribute\n * typedForm<TForm, TFields, TAttrMap>(fc) -- explicit, always works\n */\nexport type TypedForm<\n _TForm,\n TFields extends string = string,\n TAttrMap extends Record<string, Xrm.Attributes.Attribute> = Record<string, Xrm.Attributes.Attribute>,\n> = {\n readonly [K in TFields]: K extends keyof TAttrMap\n ? TAttrMap[K]\n : Xrm.Attributes.Attribute;\n} & {\n /** Access the underlying FormContext for ui, data, tabs, etc. */\n readonly $context: Xrm.FormContext;\n /** Access a control by field name */\n $control(name: TFields): Xrm.Controls.Control;\n};\n\n/**\n * Create a typed form proxy around a FormContext.\n *\n * The proxy intercepts property access and delegates to getAttribute().\n * Special properties $context and $control provide access to the full\n * FormContext and controls respectively.\n *\n * @param formContext - The Xrm.FormContext from executionContext.getFormContext()\n * @returns A proxy with direct property access to form fields\n */\nexport function typedForm<\n TForm,\n TFields extends string = string,\n TAttrMap extends Record<string, Xrm.Attributes.Attribute> = Record<string, Xrm.Attributes.Attribute>,\n>(formContext: Xrm.FormContext): TypedForm<TForm, TFields, TAttrMap> {\n return new Proxy(formContext as unknown as TypedForm<TForm, TFields, TAttrMap>, {\n get(_target, prop) {\n // Symbols and non-string keys: delegate to formContext\n if (typeof prop !== 'string') {\n return (formContext as unknown as Record<symbol, unknown>)[prop];\n }\n if (prop === '$context') return formContext;\n if (prop === '$control') {\n return (name: string) => formContext.getControl(name);\n }\n // Try getAttribute first (form field access)\n const attr = formContext.getAttribute(prop);\n if (attr) return attr;\n // Fallback to FormContext properties (data, ui, etc.)\n return (formContext as unknown as Record<string, unknown>)[prop];\n },\n\n set(_target, prop, _value) {\n throw new TypeError(\n `Cannot assign to '${String(prop)}'. Use form.${String(prop)}.setValue() instead.`,\n );\n },\n\n has(_target, prop) {\n if (typeof prop !== 'string') return false;\n if (prop === '$context' || prop === '$control') return true;\n return formContext.getAttribute(prop) !== null;\n },\n });\n}\n"],"mappings":";AA0BO,SAAS,UAAU,QAA0B;AAClD,MAAI,OAAO,WAAW,EAAG,QAAO;AAChC,SAAO,YAAY,OAAO,KAAK,GAAG,CAAC;AACrC;AAyBO,SAAS,YACd,UACA,oBACyD;AACzD,QAAM,MAAM,IAAI,kBAAkB;AAClC,QAAM,KAAK,SAAS,GAAG;AACvB,MAAI,CAAC,GAAI,QAAO;AAEhB,SAAO;AAAA,IACL;AAAA,IACA,MAAO,SAAS,GAAG,GAAG,4CAA4C,KAAgB;AAAA,IAClF,YAAa,SAAS,GAAG,GAAG,2CAA2C,KAAgB;AAAA,EACzF;AACF;AAiBO,SAAS,aACd,UACA,sBACyE;AACzE,QAAM,SAAkF,CAAC;AACzF,aAAW,QAAQ,sBAAsB;AACvC,WAAO,IAAI,IAAI,YAAY,UAAU,IAAI;AAAA,EAC3C;AACA,SAAO;AACT;AAiBO,SAAS,o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A,QAAQ,UAA2C;AACjD,aAAO;AAAA,QACL;AAAA,QAAe;AAAA;AAAA,QAA2C;AAAA,MAC5D;AAAA,IACF;AAAA,EACF;AACF;AAmBA,eAAsB,aACpB,SACA,WACY;AACZ,MAAI,QAAQ,sBAAsB,OAAO;AACzC,MAAI;AACF,WAAO,MAAM,UAAU;AAAA,EACzB,SAAS,OAAgB;AACvB,UAAM,MAAM,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AACjE,QAAI,WAAW,gBAAgB,EAAE,SAAS,IAAI,CAAC;AAC/C,UAAM;AAAA,EACR,UAAE;AACA,QAAI,QAAQ,uBAAuB;AAAA,EACrC;AACF;;;AC3SO,SAAS,UAId,aAAmE;AACnE,SAAO,IAAI,MAAM,aAA+D;AAAA,IAC9E,IAAI,SAAS,MAAM;AAEjB,UAAI,OAAO,SAAS,UAAU;AAC5B,eAAQ,YAAmD,IAAI;AAAA,MACjE;AACA,UAAI,SAAS,WAAY,QAAO;AAChC,UAAI,SAAS,YAAY;AACvB,eAAO,CAAC,SAAiB,YAAY,WAAW,IAAI;AAAA,MACtD;AAEA,YAAM,OAAO,YAAY,aAAa,IAAI;AAC1C,UAAI,KAAM,QAAO;AAEjB,aAAQ,YAAmD,IAAI;AAAA,IACjE;AAAA,IAEA,IAAI,SAAS,MAAM,QAAQ;AACzB,YAAM,IAAI;AAAA,QACR,qBAAqB,OAAO,IAAI,CAAC,eAAe,OAAO,IAAI,CAAC;AAAA,MAC9D;AAAA,IACF;AAAA,IAEA,IAAI,SAAS,MAAM;AACjB,UAAI,OAAO,SAAS,SAAU,QAAO;AACrC,UAAI,SAAS,cAAc,SAAS,WAAY,QAAO;AACvD,aAAO,YAAY,aAAa,IAAI,MAAM;AAAA,IAC5C;AAAA,EACF,CAAC;AACH;","names":["DisplayState","FormNotificationLevel","RequiredLevel","SubmitMode","SaveMode","ClientType","ClientState","OperationType","StructuralProperty","BindingType"]}
|
|
1
|
+
{"version":3,"sources":["../src/webapi-helpers.ts","../src/xrm-constants.ts","../src/action-runtime.ts","../src/typed-form.ts"],"sourcesContent":["/**\n * @xrmforge/helpers - Web API Helper Functions\n *\n * Lightweight utility functions for building OData query strings\n * with type-safe field names from generated Fields enums.\n *\n * Zero runtime overhead when used with const enums (values are inlined).\n *\n * @example\n * ```typescript\n * import { select } from '@xrmforge/helpers';\n *\n * Xrm.WebApi.retrieveRecord(ref.entityType, ref.id, select(\n * AccountFields.Name,\n * AccountFields.WebsiteUrl,\n * AccountFields.Address1Line1,\n * ));\n * ```\n */\n\n/**\n * Build an OData $select query string from field names.\n *\n * @param fields - Field names (use generated Fields enum for type safety)\n * @returns OData query string (e.g. \"?$select=name,websiteurl,address1_line1\")\n */\nexport function select(...fields: string[]): string {\n if (fields.length === 0) return '';\n return `?$select=${fields.join(',')}`;\n}\n\n/**\n * Parse a lookup field from a Dataverse Web API response into a LookupValue.\n *\n * Dataverse returns lookups as `_fieldname_value` with OData annotations:\n * - `_fieldname_value` (GUID)\n * - `_fieldname_value@OData.Community.Display.V1.FormattedValue` (display name)\n * - `_fieldname_value@Microsoft.Dynamics.CRM.lookuplogicalname` (entity type)\n *\n * This function extracts all three into an `Xrm.LookupValue` object.\n *\n * @param response - The raw Web API response object\n * @param navigationProperty - Navigation property name (use NavigationProperties enum for type safety)\n * @returns Xrm.LookupValue or null if the lookup is empty\n *\n * @example\n * ```typescript\n * // With NavigationProperties enum (recommended):\n * parseLookup(result, AccountNav.Country);\n *\n * // Or with navigation property name directly:\n * parseLookup(result, 'markant_address1_countryid');\n * ```\n */\nexport function parseLookup(\n response: Record<string, unknown>,\n navigationProperty: string,\n): { id: string; name: string; entityType: string } | null {\n const key = `_${navigationProperty}_value`;\n const id = response[key] as string | undefined;\n if (!id) return null;\n\n return {\n id,\n name: (response[`${key}@OData.Community.Display.V1.FormattedValue`] as string) ?? '',\n entityType: (response[`${key}@Microsoft.Dynamics.CRM.lookuplogicalname`] as string) ?? '',\n };\n}\n\n/**\n * Parse multiple lookup fields from a Dataverse Web API response at once.\n *\n * @param response - The raw Web API response object\n * @param navigationProperties - Navigation property names to parse\n * @returns Map of navigation property name to LookupValue (null entries omitted)\n *\n * @example\n * ```typescript\n * const lookups = parseLookups(result, ['markant_address1_countryid', 'parentaccountid']);\n * formContext.getAttribute(Fields.Country).setValue(\n * lookups.markant_address1_countryid ? [lookups.markant_address1_countryid] : null\n * );\n * ```\n */\nexport function parseLookups(\n response: Record<string, unknown>,\n navigationProperties: string[],\n): Record<string, { id: string; name: string; entityType: string } | null> {\n const result: Record<string, { id: string; name: string; entityType: string } | null> = {};\n for (const prop of navigationProperties) {\n result[prop] = parseLookup(response, prop);\n }\n return result;\n}\n\n/**\n * Get the formatted (display) value of any field from a Web API response.\n *\n * Works for OptionSets, Lookups, DateTimes, Money, and other formatted fields.\n *\n * @param response - The raw Web API response object\n * @param fieldName - The field logical name (e.g. \"statecode\", \"createdon\")\n * @returns The formatted string value, or null if not available\n *\n * @example\n * ```typescript\n * const status = parseFormattedValue(result, 'statecode');\n * // \"Active\" (instead of 0)\n * ```\n */\nexport function parseFormattedValue(\n response: Record<string, unknown>,\n fieldName: string,\n): string | null {\n return (response[`${fieldName}@OData.Community.Display.V1.FormattedValue`] as string) ?? null;\n}\n\n/**\n * Build an OData $select and $expand query string.\n *\n * @param fields - Field names to select\n * @param expand - Navigation property to expand (optional)\n * @returns OData query string\n *\n * @example\n * ```typescript\n * Xrm.WebApi.retrieveRecord(\"account\", id, selectExpand(\n * [AccountFields.Name, AccountFields.WebsiteUrl],\n * \"primarycontactid($select=fullname,emailaddress1)\"\n * ));\n * ```\n */\nexport function selectExpand(fields: string[], expand: string): string {\n const parts: string[] = [];\n if (fields.length > 0) parts.push(`$select=${fields.join(',')}`);\n if (expand) parts.push(`$expand=${expand}`);\n return parts.length > 0 ? `?${parts.join('&')}` : '';\n}\n","/**\n * @xrmforge/helpers - Xrm API Constants\n *\n * Const enums for all common Xrm string/number constants.\n * Eliminates raw strings in D365 form scripts.\n *\n * @types/xrm defines these as string literal types for compile-time checking,\n * but does NOT provide runtime constants (XrmEnum is not available at runtime).\n * These const enums are erased at compile time (zero runtime overhead).\n *\n * @example\n * ```typescript\n * import { DisplayState } from '@xrmforge/helpers';\n *\n * if (tab.getDisplayState() === DisplayState.Expanded) { ... }\n * ```\n */\n\n/** Tab/Section display state */\nexport const enum DisplayState {\n Expanded = 'expanded',\n Collapsed = 'collapsed',\n}\n\n// FormType: use XrmEnum.FormType from @types/xrm (already defined as const enum there)\n\n/** Form notification level (formContext.ui.setFormNotification) */\nexport const enum FormNotificationLevel {\n Error = 'ERROR',\n Warning = 'WARNING',\n Info = 'INFO',\n}\n\n/** Attribute required level (attribute.setRequiredLevel) */\nexport const enum RequiredLevel {\n None = 'none',\n Required = 'required',\n Recommended = 'recommended',\n}\n\n/** Attribute submit mode (attribute.setSubmitMode) */\nexport const enum SubmitMode {\n Always = 'always',\n Never = 'never',\n Dirty = 'dirty',\n}\n\n/** Save mode (eventArgs.getSaveMode()) */\nexport const enum SaveMode {\n Save = 1,\n SaveAndClose = 2,\n Deactivate = 5,\n Reactivate = 6,\n Send = 7,\n Disqualify = 15,\n Qualify = 16,\n Assign = 47,\n SaveAsCompleted = 58,\n SaveAndNew = 59,\n AutoSave = 70,\n}\n\n/** Client type (Xrm.Utility.getGlobalContext().client.getClient()) */\nexport const enum ClientType {\n Web = 'Web',\n Outlook = 'Outlook',\n Mobile = 'Mobile',\n}\n\n/** Client state (Xrm.Utility.getGlobalContext().client.getClientState()) */\nexport const enum ClientState {\n Online = 'Online',\n Offline = 'Offline',\n}\n\n// WebApi Execute Constants\n\n/** Operation type for Xrm.WebApi.execute getMetadata().operationType */\nexport const enum OperationType {\n /** Custom Action or OOB Action (POST) */\n Action = 0,\n /** Custom Function or OOB Function (GET) */\n Function = 1,\n /** CRUD operation (Create, Retrieve, Update, Delete) */\n CRUD = 2,\n}\n\n/** Structural property for getMetadata().parameterTypes[].structuralProperty */\nexport const enum StructuralProperty {\n Unknown = 0,\n PrimitiveType = 1,\n ComplexType = 2,\n EnumerationType = 3,\n Collection = 4,\n EntityType = 5,\n}\n\n/** Binding type for Custom API definitions */\nexport const enum BindingType {\n /** Not bound to an entity (globally callable) */\n Global = 0,\n /** Bound to a single entity record */\n Entity = 1,\n /** Bound to an entity collection */\n EntityCollection = 2,\n}\n","/**\n * @xrmforge/helpers - Action/Function Runtime Helpers\n *\n * Factory functions for type-safe Custom API execution.\n * These are imported by generated action/function modules.\n *\n * Design:\n * - `createBoundAction` / `createUnboundAction`: Produce executor objects\n * with `.execute()` (calls Xrm.WebApi) and `.request()` (for executeMultiple)\n * - `executeRequest`: Central execute wrapper (single place for the `as any` cast)\n * - `withProgress`: Convenience wrapper with progress indicator + error dialog\n *\n * @example\n * ```typescript\n * // Generated code (in generated/actions/quote.ts):\n * import { createBoundAction } from '@xrmforge/helpers';\n * export const WinQuote = createBoundAction('markant_winquote', 'quote');\n *\n * // Developer code (in quote-form.ts):\n * import { WinQuote } from '../generated/actions/quote';\n * const response = await WinQuote.execute(recordId);\n * ```\n */\n\nimport { OperationType, StructuralProperty } from './xrm-constants.js';\n\n// Types\n\n/** Parameter metadata for getMetadata().parameterTypes */\nexport interface ParameterMeta {\n typeName: string;\n structuralProperty: number;\n}\n\n/** Map of parameter names to their OData metadata */\nexport type ParameterMetaMap = Record<string, ParameterMeta>;\n\n/** Executor for a bound action without additional parameters */\nexport interface BoundActionExecutor {\n execute(recordId: string): Promise<Response>;\n request(recordId: string): Record<string, unknown>;\n}\n\n/** Executor for a bound action with typed parameters */\nexport interface BoundActionWithParamsExecutor<TParams> {\n execute(recordId: string, params: TParams): Promise<Response>;\n request(recordId: string, params: TParams): Record<string, unknown>;\n}\n\n/** Executor for an unbound action without parameters */\nexport interface UnboundActionExecutor {\n execute(): Promise<Response>;\n request(): Record<string, unknown>;\n}\n\n/** Executor for an unbound action with typed parameters and optional typed response */\nexport interface UnboundActionWithParamsExecutor<TParams, TResult = void> {\n execute(params: TParams): Promise<TResult extends void ? Response : TResult>;\n request(params: TParams): Record<string, unknown>;\n}\n\n/** Executor for an unbound function with typed response */\nexport interface UnboundFunctionExecutor<TResult> {\n execute(): Promise<TResult>;\n request(): Record<string, unknown>;\n}\n\n/** Executor for a bound function with typed response */\nexport interface BoundFunctionExecutor<TResult> {\n execute(recordId: string): Promise<TResult>;\n request(recordId: string): Record<string, unknown>;\n}\n\n// Central Execute\n\n/**\n * Execute a single request via Xrm.WebApi.online.execute().\n *\n * This is the ONLY place in the entire framework where the `as any` cast happens.\n * All generated executors call this function internally.\n */\nexport function executeRequest(request: Record<string, unknown>): Promise<Response> {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return (Xrm.WebApi as any).online.execute(request) as Promise<Response>;\n}\n\n/**\n * Execute multiple requests via Xrm.WebApi.online.executeMultiple().\n *\n * @param requests - Array of request objects (from `.request()` factories).\n * Wrap a subset in an inner array for transactional changeset execution.\n */\nexport function executeMultiple(\n requests: Array<Record<string, unknown> | Array<Record<string, unknown>>>,\n): Promise<Response[]> {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return (Xrm.WebApi as any).online.executeMultiple(requests) as Promise<Response[]>;\n}\n\n// Request Builder (internal)\n\nfunction cleanRecordId(id: string): string {\n return id.replace(/[{}]/g, '');\n}\n\nfunction buildBoundRequest(\n operationName: string,\n entityLogicalName: string,\n operationType: OperationType,\n recordId: string,\n paramMeta?: ParameterMetaMap,\n params?: Record<string, unknown>,\n): Record<string, unknown> {\n const parameterTypes: Record<string, ParameterMeta> = {\n entity: {\n typeName: `mscrm.${entityLogicalName}`,\n structuralProperty: StructuralProperty.EntityType,\n },\n };\n\n if (paramMeta) {\n for (const [key, meta] of Object.entries(paramMeta)) {\n parameterTypes[key] = meta;\n }\n }\n\n const request: Record<string, unknown> = {\n getMetadata: () => ({\n boundParameter: 'entity',\n parameterTypes,\n operationName,\n operationType,\n }),\n entity: {\n id: cleanRecordId(recordId),\n entityType: entityLogicalName,\n },\n };\n\n if (params) {\n for (const [key, value] of Object.entries(params)) {\n request[key] = value;\n }\n }\n\n return request;\n}\n\nfunction buildUnboundRequest(\n operationName: string,\n operationType: OperationType,\n paramMeta?: ParameterMetaMap,\n params?: Record<string, unknown>,\n): Record<string, unknown> {\n const parameterTypes: Record<string, ParameterMeta> = {};\n\n if (paramMeta) {\n for (const [key, meta] of Object.entries(paramMeta)) {\n parameterTypes[key] = meta;\n }\n }\n\n const request: Record<string, unknown> = {\n getMetadata: () => ({\n boundParameter: null,\n parameterTypes,\n operationName,\n operationType,\n }),\n };\n\n if (params) {\n for (const [key, value] of Object.entries(params)) {\n request[key] = value;\n }\n }\n\n return request;\n}\n\n// Action Factories\n\n/**\n * Create an executor for a bound action (entity-bound).\n *\n * @param operationName - Custom API unique name (e.g. \"markant_winquote\")\n * @param entityLogicalName - Entity logical name (e.g. \"quote\")\n */\nexport function createBoundAction(\n operationName: string,\n entityLogicalName: string,\n): BoundActionExecutor;\n\n/**\n * Create an executor for a bound action with typed parameters.\n *\n * @param operationName - Custom API unique name\n * @param entityLogicalName - Entity logical name\n * @param paramMeta - Parameter metadata map (parameter name to OData type info)\n */\nexport function createBoundAction<TParams extends Record<string, unknown>>(\n operationName: string,\n entityLogicalName: string,\n paramMeta: ParameterMetaMap,\n): BoundActionWithParamsExecutor<TParams>;\n\nexport function createBoundAction<TParams extends Record<string, unknown>>(\n operationName: string,\n entityLogicalName: string,\n paramMeta?: ParameterMetaMap,\n): BoundActionExecutor | BoundActionWithParamsExecutor<TParams> {\n return {\n execute(recordId: string, params?: TParams): Promise<Response> {\n const req = buildBoundRequest(\n operationName, entityLogicalName, OperationType.Action,\n recordId, paramMeta, params,\n );\n return executeRequest(req);\n },\n request(recordId: string, params?: TParams): Record<string, unknown> {\n return buildBoundRequest(\n operationName, entityLogicalName, OperationType.Action,\n recordId, paramMeta, params,\n );\n },\n };\n}\n\n/**\n * Create an executor for an unbound (global) action without parameters.\n *\n * @param operationName - Custom API unique name\n */\nexport function createUnboundAction(\n operationName: string,\n): UnboundActionExecutor;\n\n/**\n * Create an executor for an unbound action with typed parameters and response.\n *\n * @param operationName - Custom API unique name\n * @param paramMeta - Parameter metadata map\n */\nexport function createUnboundAction<\n TParams extends Record<string, unknown>,\n TResult = void,\n>(\n operationName: string,\n paramMeta: ParameterMetaMap,\n): UnboundActionWithParamsExecutor<TParams, TResult>;\n\nexport function createUnboundAction<\n TParams extends Record<string, unknown>,\n TResult = void,\n>(\n operationName: string,\n paramMeta?: ParameterMetaMap,\n): UnboundActionExecutor | UnboundActionWithParamsExecutor<TParams, TResult> {\n return {\n async execute(params?: TParams): Promise<TResult extends void ? Response : TResult> {\n const req = buildUnboundRequest(\n operationName, OperationType.Action, paramMeta, params,\n );\n const response = await executeRequest(req);\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(errorText);\n }\n if (response.status !== 204) {\n return response.json() as Promise<TResult extends void ? Response : TResult>;\n }\n return response as TResult extends void ? Response : TResult;\n },\n request(params?: TParams): Record<string, unknown> {\n return buildUnboundRequest(\n operationName, OperationType.Action, paramMeta, params,\n );\n },\n };\n}\n\n// Function Factories\n\n/**\n * Create an executor for an unbound (global) function with typed response.\n *\n * @param operationName - Function name (e.g. \"WhoAmI\")\n */\nexport function createUnboundFunction<TResult>(\n operationName: string,\n): UnboundFunctionExecutor<TResult> {\n return {\n async execute(): Promise<TResult> {\n const req = buildUnboundRequest(operationName, OperationType.Function);\n const response = await executeRequest(req);\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(errorText);\n }\n return response.json() as Promise<TResult>;\n },\n request(): Record<string, unknown> {\n return buildUnboundRequest(operationName, OperationType.Function);\n },\n };\n}\n\n/**\n * Create an executor for a bound function with typed response.\n *\n * @param operationName - Function name\n * @param entityLogicalName - Entity logical name\n */\nexport function createBoundFunction<TResult>(\n operationName: string,\n entityLogicalName: string,\n): BoundFunctionExecutor<TResult> {\n return {\n async execute(recordId: string): Promise<TResult> {\n const req = buildBoundRequest(\n operationName, entityLogicalName, OperationType.Function, recordId,\n );\n const response = await executeRequest(req);\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(errorText);\n }\n return response.json() as Promise<TResult>;\n },\n request(recordId: string): Record<string, unknown> {\n return buildBoundRequest(\n operationName, entityLogicalName, OperationType.Function, recordId,\n );\n },\n };\n}\n\n// Convenience\n\n/**\n * Execute an async operation with Xrm progress indicator.\n *\n * Shows a progress spinner before the operation, closes it after,\n * and shows an error dialog on failure.\n *\n * @param message - Progress indicator message (e.g. \"Processing quote...\")\n * @param operation - Async function to execute\n * @returns The result of the operation\n *\n * @example\n * ```typescript\n * await withProgress('Processing quote...', () => WinQuote.execute(recordId));\n * ```\n */\nexport async function withProgress<T>(\n message: string,\n operation: () => Promise<T>,\n): Promise<T> {\n Xrm.Utility.showProgressIndicator(message);\n try {\n return await operation();\n } catch (error: unknown) {\n const msg = error instanceof Error ? error.message : String(error);\n Xrm.Navigation.openErrorDialog({ message: msg });\n throw error;\n } finally {\n Xrm.Utility.closeProgressIndicator();\n }\n}\n","/**\n * @xrmforge/helpers - TypedForm Proxy\n *\n * Creates a proxy around Xrm.FormContext that allows direct property access\n * to form fields. Instead of formContext.getAttribute(\"name\").setValue(\"X\"),\n * write form.name.setValue(\"X\").\n *\n * @example\n * ```typescript\n * import { typedForm } from '@xrmforge/helpers';\n *\n * type LeadForm = XrmForge.Forms.Lead.LeadMarkantLeadForm;\n *\n * const form = typedForm<LeadForm>(formContext);\n * form.companyname.setValue(\"Contoso\"); // StringAttribute\n * form.parentaccountid.getValue(); // LookupValue[] | null\n * form.$context.ui.setFormNotification(...); // Full FormContext access\n * form.$control(\"companyname\").setDisabled(true);\n * ```\n */\n\n/**\n * Extracts the Fields union type from a generated Form interface.\n * Works with the XrmForge-generated pattern:\n * getAttribute<K extends Fields>(name: K): AttrMap[K]\n *\n * For overloaded getAttribute, TypeScript resolves to the last overload.\n * Our generated interfaces have the generic overload first, so we use\n * a mapped approach with the AttrMap instead.\n */\nexport type FormFields<TForm> = TForm extends {\n getAttribute(name: infer K): unknown;\n} ? K extends string ? K : string : string;\n\n/**\n * TypedForm: proxy type that maps field names to their attribute types.\n *\n * Since extracting Fields + AttrMap from overloaded getAttribute is unreliable\n * in TypeScript, we use a two-parameter approach internally but expose a\n * single-parameter API via a helper type generated by typegen (FormTypedInfo).\n *\n * For v0.1.0 we support both signatures:\n * typedForm<TForm>(fc) -- works when TForm has proper generic getAttribute\n * typedForm<TForm, TFields, TAttrMap>(fc) -- explicit, always works\n */\nexport type TypedForm<\n _TForm,\n TFields extends string = string,\n TAttrMap extends Record<string, Xrm.Attributes.Attribute> = Record<string, Xrm.Attributes.Attribute>,\n> = {\n readonly [K in TFields]: K extends keyof TAttrMap\n ? TAttrMap[K]\n : Xrm.Attributes.Attribute;\n} & {\n /** Access the underlying FormContext for ui, data, tabs, etc. */\n readonly $context: Xrm.FormContext;\n /** Access a control by field name */\n $control(name: TFields): Xrm.Controls.Control;\n};\n\n/**\n * Create a typed form proxy around a FormContext.\n *\n * The proxy intercepts property access and delegates to getAttribute().\n * Special properties $context and $control provide access to the full\n * FormContext and controls respectively.\n *\n * @param formContext - The Xrm.FormContext from executionContext.getFormContext()\n * @returns A proxy with direct property access to form fields\n */\nexport function typedForm<\n TForm,\n TFields extends string = string,\n TAttrMap extends Record<string, Xrm.Attributes.Attribute> = Record<string, Xrm.Attributes.Attribute>,\n>(formContext: Xrm.FormContext): TypedForm<TForm, TFields, TAttrMap> {\n return new Proxy(formContext as unknown as TypedForm<TForm, TFields, TAttrMap>, {\n get(_target, prop) {\n // Symbols and non-string keys: delegate to formContext\n if (typeof prop !== 'string') {\n return (formContext as unknown as Record<symbol, unknown>)[prop];\n }\n if (prop === '$context') return formContext;\n if (prop === '$control') {\n return (name: string) => formContext.getControl(name);\n }\n // Try getAttribute first (form field access)\n const attr = formContext.getAttribute(prop);\n if (attr) return attr;\n // Fallback to FormContext properties (data, ui, etc.)\n return (formContext as unknown as Record<string, unknown>)[prop];\n },\n\n set(_target, prop, _value) {\n throw new TypeError(\n `Cannot assign to '${String(prop)}'. Use form.${String(prop)}.setValue() instead.`,\n );\n },\n\n has(_target, prop) {\n if (typeof prop !== 'string') return false;\n if (prop === '$context' || prop === '$control') return true;\n return formContext.getAttribute(prop) !== null;\n },\n });\n}\n"],"mappings":";AA0BO,SAAS,UAAU,QAA0B;AAClD,MAAI,OAAO,WAAW,EAAG,QAAO;AAChC,SAAO,YAAY,OAAO,KAAK,GAAG,CAAC;AACrC;AAyBO,SAAS,YACd,UACA,oBACyD;AACzD,QAAM,MAAM,IAAI,kBAAkB;AAClC,QAAM,KAAK,SAAS,GAAG;AACvB,MAAI,CAAC,GAAI,QAAO;AAEhB,SAAO;AAAA,IACL;AAAA,IACA,MAAO,SAAS,GAAG,GAAG,4CAA4C,KAAgB;AAAA,IAClF,YAAa,SAAS,GAAG,GAAG,2CAA2C,KAAgB;AAAA,EACzF;AACF;AAiBO,SAAS,aACd,UACA,sBACyE;AACzE,QAAM,SAAkF,CAAC;AACzF,aAAW,QAAQ,sBAAsB;AACvC,WAAO,IAAI,IAAI,YAAY,UAAU,IAAI;AAAA,EAC3C;AACA,SAAO;AACT;AAiBO,SAAS,oBACd,UACA,WACe;AACf,SAAQ,SAAS,GAAG,SAAS,4CAA4C,KAAgB;AAC3F;AAiBO,SAAS,aAAa,QAAkB,QAAwB;AACrE,QAAM,QAAkB,CAAC;AACzB,MAAI,OAAO,SAAS,EAAG,OAAM,KAAK,WAAW,OAAO,KAAK,GAAG,CAAC,EAAE;AAC/D,MAAI,OAAQ,OAAM,KAAK,WAAW,MAAM,EAAE;AAC1C,SAAO,MAAM,SAAS,IAAI,IAAI,MAAM,KAAK,GAAG,CAAC,KAAK;AACpD;;;ACtHO,IAAW,eAAX,kBAAWA,kBAAX;AACL,EAAAA,cAAA,cAAW;AACX,EAAAA,cAAA,eAAY;AAFI,SAAAA;AAAA,GAAA;AAQX,IAAW,wBAAX,kBAAWC,2BAAX;AACL,EAAAA,uBAAA,WAAQ;AACR,EAAAA,uBAAA,a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S,UAAU;AAC5B,eAAQ,YAAmD,IAAI;AAAA,MACjE;AACA,UAAI,SAAS,WAAY,QAAO;AAChC,UAAI,SAAS,YAAY;AACvB,eAAO,CAAC,SAAiB,YAAY,WAAW,IAAI;AAAA,MACtD;AAEA,YAAM,OAAO,YAAY,aAAa,IAAI;AAC1C,UAAI,KAAM,QAAO;AAEjB,aAAQ,YAAmD,IAAI;AAAA,IACjE;AAAA,IAEA,IAAI,SAAS,MAAM,QAAQ;AACzB,YAAM,IAAI;AAAA,QACR,qBAAqB,OAAO,IAAI,CAAC,eAAe,OAAO,IAAI,CAAC;AAAA,MAC9D;AAAA,IACF;AAAA,IAEA,IAAI,SAAS,MAAM;AACjB,UAAI,OAAO,SAAS,SAAU,QAAO;AACrC,UAAI,SAAS,cAAc,SAAS,WAAY,QAAO;AACvD,aAAO,YAAY,aAAa,IAAI,MAAM;AAAA,IAC5C;AAAA,EACF,CAAC;AACH;","names":["DisplayState","FormNotificationLevel","RequiredLevel","SubmitMode","SaveMode","ClientType","ClientState","OperationType","StructuralProperty","BindingType"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@xrmforge/helpers",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.1",
|
|
4
4
|
"description": "Browser-safe runtime helpers for Dynamics 365 form scripts: select(), parseLookup(), typedForm(), Xrm constants, Action/Function executors",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"dynamics-365",
|