@xrmforge/typegen 0.3.0 → 0.4.0

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.d.ts CHANGED
@@ -21,6 +21,7 @@ declare enum ErrorCode {
21
21
  META_SOLUTION_NOT_FOUND = "META_3002",
22
22
  META_FORM_PARSE_FAILED = "META_3003",
23
23
  META_ATTRIBUTE_UNKNOWN_TYPE = "META_3004",
24
+ META_VERSION_STAMP_EXPIRED = "META_3005",
24
25
  GEN_OUTPUT_WRITE_FAILED = "GEN_4001",
25
26
  GEN_TEMPLATE_FAILED = "GEN_4002",
26
27
  GEN_INVALID_IDENTIFIER = "GEN_4003",
@@ -302,6 +303,8 @@ declare class DataverseHttpClient {
302
303
  private readonly maxRateLimitRetries;
303
304
  private readonly readOnly;
304
305
  private cachedToken;
306
+ /** Pending token refresh promise (prevents concurrent token requests) */
307
+ private pendingTokenRefresh;
305
308
  private activeConcurrentRequests;
306
309
  private readonly waitQueue;
307
310
  constructor(options: HttpClientOptions);
@@ -327,6 +330,16 @@ declare class DataverseHttpClient {
327
330
  * @param signal - Optional AbortSignal to cancel the request
328
331
  */
329
332
  getAll<T>(path: string, signal?: AbortSignal): Promise<T[]>;
333
+ /**
334
+ * Execute a POST request that is semantically a read operation.
335
+ * Used for Dataverse actions like RetrieveMetadataChanges that require POST
336
+ * but do not modify data. Allowed even in read-only mode.
337
+ *
338
+ * @param path - API path (relative to apiUrl)
339
+ * @param body - JSON body to send
340
+ * @param signal - Optional AbortSignal to cancel the request
341
+ */
342
+ postReadOnly<T>(path: string, body: unknown, signal?: AbortSignal): Promise<T>;
330
343
  /**
331
344
  * Returns true if this client is in read-only mode (the safe default).
332
345
  */
@@ -360,6 +373,8 @@ declare class DataverseHttpClient {
360
373
  */
361
374
  static escapeODataString(value: string): string;
362
375
  private getToken;
376
+ /** Internal: actually acquire a new token from the credential provider. */
377
+ private refreshToken;
363
378
  /**
364
379
  * Execute a request within the concurrency semaphore.
365
380
  * The semaphore is acquired ONCE per logical request. Retries happen
@@ -800,9 +815,11 @@ declare class MetadataCache {
800
815
  private readonly cacheDir;
801
816
  private readonly cacheFilePath;
802
817
  /**
803
- * @param projectRoot - Root directory of the project (where .xrmforge/ will be created)
818
+ * @param cacheDir - Directory where cache files are stored.
819
+ * Can be an absolute path or relative to cwd.
820
+ * Defaults to ".xrmforge/cache" when constructed without argument.
804
821
  */
805
- constructor(projectRoot: string);
822
+ constructor(cacheDir?: string);
806
823
  /**
807
824
  * Load cached metadata from disk.
808
825
  * Returns null if no cache exists, cache is for a different environment,
@@ -837,6 +854,58 @@ declare class MetadataCache {
837
854
  exists(): Promise<boolean>;
838
855
  }
839
856
 
857
+ /**
858
+ * @xrmforge/typegen - Metadata Change Detector
859
+ *
860
+ * Uses the Dataverse RetrieveMetadataChanges action to determine
861
+ * which entities have changed since the last generation run.
862
+ * This enables incremental type generation (only re-fetch changed entities).
863
+ *
864
+ * @see https://learn.microsoft.com/en-us/power-apps/developer/data-platform/webapi/samples/retrievemetadatachanges
865
+ */
866
+
867
+ /** Result of a change detection query */
868
+ interface ChangeDetectionResult {
869
+ /** Entity logical names that have changed (new or modified) */
870
+ changedEntityNames: string[];
871
+ /** Entity logical names that have been deleted */
872
+ deletedEntityNames: string[];
873
+ /** New server version stamp (store this for the next run) */
874
+ newVersionStamp: string;
875
+ }
876
+ /**
877
+ * Detects metadata changes in Dataverse using RetrieveMetadataChanges.
878
+ *
879
+ * Usage:
880
+ * ```typescript
881
+ * const detector = new ChangeDetector(httpClient);
882
+ * const result = await detector.detectChanges(cachedVersionStamp);
883
+ * // result.changedEntityNames = ['account', 'contact']
884
+ * // result.newVersionStamp = 'new-stamp-to-cache'
885
+ * ```
886
+ */
887
+ declare class ChangeDetector {
888
+ private readonly http;
889
+ constructor(http: DataverseHttpClient);
890
+ /**
891
+ * Detect which entities have changed since the given version stamp.
892
+ *
893
+ * @param clientVersionStamp - The ServerVersionStamp from the last run (from cache)
894
+ * @returns Changed entity names, deleted entity names, and new version stamp
895
+ * @throws {MetadataError} with META_VERSION_STAMP_EXPIRED if stamp is too old (>90 days)
896
+ */
897
+ detectChanges(clientVersionStamp: string): Promise<ChangeDetectionResult>;
898
+ /**
899
+ * Perform an initial metadata query to get the first ServerVersionStamp.
900
+ * This is used on the very first run (no cache exists).
901
+ *
902
+ * @returns The initial server version stamp
903
+ */
904
+ getInitialVersionStamp(): Promise<string>;
905
+ /** Check if an error is the expired version stamp error (0x80044352) */
906
+ private isExpiredVersionStampError;
907
+ }
908
+
840
909
  /**
841
910
  * @xrmforge/typegen - Label Utilities
842
911
  *
@@ -1815,15 +1884,15 @@ interface GenerateConfig {
1815
1884
  actionsFilter?: string;
1816
1885
  /**
1817
1886
  * Whether to use metadata cache for faster re-generation.
1818
- * @alpha Not yet implemented. Setting this to true will throw a ConfigError.
1819
- * Planned for v0.2.0.
1887
+ * When enabled, only changed entities are re-fetched from Dataverse
1888
+ * using RetrieveMetadataChanges delta detection.
1889
+ * On first run or expired cache, a full refresh is performed automatically.
1820
1890
  * @defaultValue false
1821
1891
  */
1822
1892
  useCache?: boolean;
1823
1893
  /**
1824
- * Cache directory for metadata cache.
1825
- * @alpha Not yet implemented. Ignored until useCache is implemented.
1826
- * Planned for v0.2.0.
1894
+ * Directory for metadata cache files.
1895
+ * Relative paths are resolved from the current working directory.
1827
1896
  * @defaultValue ".xrmforge/cache"
1828
1897
  */
1829
1898
  cacheDir?: string;
@@ -1848,6 +1917,19 @@ interface GeneratedFile {
1848
1917
  /** Type of generated content */
1849
1918
  type: 'entity' | 'optionset' | 'form' | 'action';
1850
1919
  }
1920
+ /** Statistics about cache usage during generation */
1921
+ interface CacheStats {
1922
+ /** Whether the cache was used in this run */
1923
+ cacheUsed: boolean;
1924
+ /** Whether this was a full refresh (no prior cache or expired stamp) */
1925
+ fullRefresh: boolean;
1926
+ /** Number of entities loaded from cache (unchanged) */
1927
+ entitiesFromCache: number;
1928
+ /** Number of entities fetched from Dataverse (new or changed) */
1929
+ entitiesFetched: number;
1930
+ /** Number of entities removed (deleted in Dataverse) */
1931
+ entitiesDeleted: number;
1932
+ }
1851
1933
  /** Overall result of the generation process */
1852
1934
  interface GenerationResult {
1853
1935
  /** Per-entity results */
@@ -1858,6 +1940,8 @@ interface GenerationResult {
1858
1940
  totalWarnings: number;
1859
1941
  /** Duration in milliseconds */
1860
1942
  durationMs: number;
1943
+ /** Cache statistics (present when useCache was enabled) */
1944
+ cacheStats?: CacheStats;
1861
1945
  }
1862
1946
 
1863
1947
  /**
@@ -1902,9 +1986,24 @@ declare class TypeGenerationOrchestrator {
1902
1986
  signal?: AbortSignal;
1903
1987
  }): Promise<GenerationResult>;
1904
1988
  /**
1905
- * Process a single entity: fetch metadata, generate all output files.
1989
+ * Resolve the cache: load existing cache, detect changes, determine which
1990
+ * entities need to be fetched vs. can be served from cache.
1991
+ *
1992
+ * On any failure (corrupt cache, expired stamp), falls back to full refresh.
1993
+ */
1994
+ private resolveCache;
1995
+ /**
1996
+ * Update the metadata cache after a successful generation run.
1997
+ */
1998
+ private updateCache;
1999
+ /**
2000
+ * Generate all output files for a single entity from its metadata.
2001
+ */
2002
+ private generateEntityFiles;
2003
+ /**
2004
+ * Generate Custom API Action/Function executor files.
1906
2005
  */
1907
- private processEntity;
2006
+ private generateActions;
1908
2007
  /**
1909
2008
  * Extract picklist attributes with their OptionSet metadata.
1910
2009
  * Maps the raw EntityTypeInfo data to the format expected by the OptionSet generator.
@@ -1912,4 +2011,4 @@ declare class TypeGenerationOrchestrator {
1912
2011
  private getPicklistAttributes;
1913
2012
  }
1914
2013
 
1915
- export { type ActionGeneratorOptions, ApiRequestError, type AttributeMetadata, type AuthConfig, type AuthMethod, AuthenticationError, BindingType, type BoundActionExecutor, type BoundActionWithParamsExecutor, type BoundFunctionExecutor, type ClientCredentialsAuth, ClientState, ClientType, ConfigError, ConsoleLogSink, type CustomApiTypeInfo, DEFAULT_LABEL_CONFIG, DataverseHttpClient, type DateTimeAttributeMetadata, type DecimalAttributeMetadata, type DeviceCodeAuth, DisplayState, type EntityFieldsGeneratorOptions, type EntityGenerationResult, type EntityGeneratorOptions, type EntityMetadata, type EntityNamesGeneratorOptions, type EntityTypeInfo, ErrorCode, FastXmlParser, type FormControl, type FormGeneratorOptions, FormNotificationLevel, type FormSection, type FormTab, type GenerateConfig, type GeneratedFile, GenerationError, type GenerationResult, type GroupedCustomApis, type HttpClientOptions, type IntegerAttributeMetadata, type InteractiveAuth, JsonLogSink, type Label, type LabelConfig, type LocalizedLabel, type LogEntry, LogLevel, type LogSink, Logger, type LookupAttributeMetadata, type ManyToManyRelationshipMetadata, MetadataCache, MetadataClient, MetadataError, type MoneyAttributeMetadata, type OneToManyRelationshipMetadata, OperationType, type OptionMetadata, type OptionSetGeneratorOptions, type OptionSetMetadata, type ParameterMeta, type ParameterMetaMap, type ParsedForm, type PicklistAttributeMetadata, RequiredLevel, SaveMode, SilentLogSink, type SolutionComponent, type StateAttributeMetadata, type StatusAttributeMetadata, type StringAttributeMetadata, StructuralProperty, SubmitMode, type SystemFormMetadata, TypeGenerationOrchestrator, type UnboundActionExecutor, type UnboundActionWithParamsExecutor, type UnboundFunctionExecutor, type XmlElement, type XmlParser, XrmForgeError, configureLogging, createBoundAction, createBoundFunction, createCredential, createLogger, createUnboundAction, createUnboundFunction, defaultXmlParser, disambiguateEnumMembers, executeMultiple, executeRequest, extractControlFields, getJSDocLabel as formatDualLabel, generateActionDeclarations, generateActionModule, generateActivityPartyInterface, generateEntityFieldsEnum, generateEntityForms, generateEntityInterface, generateEntityNamesEnum, generateEntityNavigationProperties, generateEntityOptionSets, generateEnumMembers, generateFormInterface, generateOptionSetEnum, getEntityPropertyType, getFormAttributeType, getFormControlType, getFormMockValueType, getJSDocLabel, getLabelLanguagesParam, getPrimaryLabel, getSecondaryLabel, groupCustomApis, isLookupType, isPartyListType, isRateLimitError, isXrmForgeError, labelToIdentifier, parseForm, parseFormattedValue, parseLookup, parseLookups, select, selectExpand, shouldIncludeInEntityInterface, toLookupValueProperty, toPascalCase, toSafeIdentifier, withProgress };
2014
+ export { type ActionGeneratorOptions, ApiRequestError, type AttributeMetadata, type AuthConfig, type AuthMethod, AuthenticationError, BindingType, type BoundActionExecutor, type BoundActionWithParamsExecutor, type BoundFunctionExecutor, type CacheStats, type ChangeDetectionResult, ChangeDetector, type ClientCredentialsAuth, ClientState, ClientType, ConfigError, ConsoleLogSink, type CustomApiTypeInfo, DEFAULT_LABEL_CONFIG, DataverseHttpClient, type DateTimeAttributeMetadata, type DecimalAttributeMetadata, type DeviceCodeAuth, DisplayState, type EntityFieldsGeneratorOptions, type EntityGenerationResult, type EntityGeneratorOptions, type EntityMetadata, type EntityNamesGeneratorOptions, type EntityTypeInfo, ErrorCode, FastXmlParser, type FormControl, type FormGeneratorOptions, FormNotificationLevel, type FormSection, type FormTab, type GenerateConfig, type GeneratedFile, GenerationError, type GenerationResult, type GroupedCustomApis, type HttpClientOptions, type IntegerAttributeMetadata, type InteractiveAuth, JsonLogSink, type Label, type LabelConfig, type LocalizedLabel, type LogEntry, LogLevel, type LogSink, Logger, type LookupAttributeMetadata, type ManyToManyRelationshipMetadata, MetadataCache, MetadataClient, MetadataError, type MoneyAttributeMetadata, type OneToManyRelationshipMetadata, OperationType, type OptionMetadata, type OptionSetGeneratorOptions, type OptionSetMetadata, type ParameterMeta, type ParameterMetaMap, type ParsedForm, type PicklistAttributeMetadata, RequiredLevel, SaveMode, SilentLogSink, type SolutionComponent, type StateAttributeMetadata, type StatusAttributeMetadata, type StringAttributeMetadata, StructuralProperty, SubmitMode, type SystemFormMetadata, TypeGenerationOrchestrator, type UnboundActionExecutor, type UnboundActionWithParamsExecutor, type UnboundFunctionExecutor, type XmlElement, type XmlParser, XrmForgeError, configureLogging, createBoundAction, createBoundFunction, createCredential, createLogger, createUnboundAction, createUnboundFunction, defaultXmlParser, disambiguateEnumMembers, executeMultiple, executeRequest, extractControlFields, getJSDocLabel as formatDualLabel, generateActionDeclarations, generateActionModule, generateActivityPartyInterface, generateEntityFieldsEnum, generateEntityForms, generateEntityInterface, generateEntityNamesEnum, generateEntityNavigationProperties, generateEntityOptionSets, generateEnumMembers, generateFormInterface, generateOptionSetEnum, getEntityPropertyType, getFormAttributeType, getFormControlType, getFormMockValueType, getJSDocLabel, getLabelLanguagesParam, getPrimaryLabel, getSecondaryLabel, groupCustomApis, isLookupType, isPartyListType, isRateLimitError, isXrmForgeError, labelToIdentifier, parseForm, parseFormattedValue, parseLookup, parseLookups, select, selectExpand, shouldIncludeInEntityInterface, toLookupValueProperty, toPascalCase, toSafeIdentifier, withProgress };