feat(interfaces): add comprehensive TypeScript interface modules, demo data, docs, and publish metadata

This commit is contained in:
2025-12-18 15:25:36 +00:00
parent f46d8a54cd
commit f3f03bbc57
24 changed files with 6357 additions and 169 deletions

View File

@@ -0,0 +1,231 @@
/**
* @file attachments.ts
* @description Document attachment interfaces
* Exhibits, schedules, prior contracts, and document bundles
*/
import * as plugins from './plugins.js';
import type {
TAttachmentType,
TAttachmentCategory,
TPriorContractRelationship,
TConfidentialityLevel,
} from './types.js';
// ============================================================================
// ATTACHMENT FILE
// ============================================================================
/**
* Storage provider types
*/
export type TStorageProvider = 'local' | 's3' | 'azure' | 'gcs';
/**
* File metadata for attachment
*/
export interface IAttachmentFile {
id: string;
filename: string;
mimeType: string;
size: number;
storageProvider: TStorageProvider;
storageKey: string;
checksum: string;
checksumAlgorithm: 'SHA-256';
thumbnailUrl?: string;
previewUrl?: string;
pageCount?: number;
textExtraction?: string;
}
// ============================================================================
// CONTRACT ATTACHMENT
// ============================================================================
/**
* Extended attachment for contracts
*/
export interface IContractAttachment {
id: string;
contractId: string;
type: TAttachmentType;
category: TAttachmentCategory;
title: string;
description?: string;
file?: IAttachmentFile;
inlineContent?: string;
referencedInParagraphs: string[];
displayOrder: number;
versionId: string;
attachmentVersion: number;
addedAt: number;
addedBy: string;
lastModifiedAt?: number;
lastModifiedBy?: string;
isConfidential: boolean;
confidentialityLevel: TConfidentialityLevel;
}
// ============================================================================
// PRIOR CONTRACT REFERENCE
// ============================================================================
/**
* External contract reference
*/
export interface IExternalContractReference {
title: string;
date: number;
parties: string[];
summary?: string;
documentUrl?: string;
}
/**
* Referenced clause from prior contract
*/
export interface IReferencedClause {
clauseReference: string;
relevance: string;
}
/**
* Prior contract reference
*/
export interface IPriorContractReference {
id: string;
contractId?: string;
externalReference?: IExternalContractReference;
relationshipType: TPriorContractRelationship;
referencedClauses: IReferencedClause[];
notes?: string;
}
// ============================================================================
// DOCUMENT BUNDLE
// ============================================================================
/**
* Export settings for document bundle
*/
export interface IBundleExportSettings {
includeAuditLog: boolean;
includeComments: boolean;
redactConfidential: boolean;
watermark?: string;
}
/**
* Document bundle purpose
*/
export type TBundlePurpose = 'signing_package' | 'due_diligence' | 'archive' | 'discovery' | 'custom';
/**
* Document bundle (collection of related documents)
*/
export interface IDocumentBundle {
id: string;
name: string;
description?: string;
mainContractId: string;
attachmentIds: string[];
priorContractIds: string[];
createdAt: number;
createdBy: string;
purpose: TBundlePurpose;
exportSettings?: IBundleExportSettings;
}
// ============================================================================
// FACTORY FUNCTIONS
// ============================================================================
/**
* Create a new contract attachment
*/
export function createContractAttachment(
contractId: string,
versionId: string,
type: TAttachmentType,
category: TAttachmentCategory,
title: string,
addedBy: string
): IContractAttachment {
return {
id: crypto.randomUUID(),
contractId,
type,
category,
title,
referencedInParagraphs: [],
displayOrder: 0,
versionId,
attachmentVersion: 1,
addedAt: Date.now(),
addedBy,
isConfidential: false,
confidentialityLevel: 'internal',
};
}
/**
* Create a prior contract reference
*/
export function createPriorContractReference(
relationshipType: TPriorContractRelationship,
contractId?: string,
externalReference?: IExternalContractReference
): IPriorContractReference {
return {
id: crypto.randomUUID(),
contractId,
externalReference,
relationshipType,
referencedClauses: [],
};
}
/**
* Create a document bundle
*/
export function createDocumentBundle(
name: string,
mainContractId: string,
purpose: TBundlePurpose,
createdBy: string
): IDocumentBundle {
return {
id: crypto.randomUUID(),
name,
mainContractId,
attachmentIds: [],
priorContractIds: [],
createdAt: Date.now(),
createdBy,
purpose,
};
}
/**
* Create an attachment file metadata
*/
export function createAttachmentFile(
filename: string,
mimeType: string,
size: number,
storageProvider: TStorageProvider,
storageKey: string,
checksum: string
): IAttachmentFile {
return {
id: crypto.randomUUID(),
filename,
mimeType,
size,
storageProvider,
storageKey,
checksum,
checksumAlgorithm: 'SHA-256',
};
}

View File

@@ -0,0 +1,365 @@
/**
* @file collaboration.ts
* @description Collaboration interfaces
* Comments, suggestions, user presence, and collaborative editing support
*/
import * as plugins from './plugins.js';
import type {
TPresenceStatus,
TCommentThreadStatus,
TSuggestionStatus,
TSuggestionChangeType,
TConflictResolutionStrategy,
TEditingMode,
TCollaborationPermission,
} from './types.js';
import type { IVersionChange } from './versioning.js';
// ============================================================================
// USER PRESENCE
// ============================================================================
/**
* User's current location in document
*/
export interface IUserLocation {
paragraphId?: string;
characterPosition?: number;
selectionRange?: {
start: number;
end: number;
};
}
/**
* Device information for presence
*/
export interface IDeviceInfo {
type: 'desktop' | 'tablet' | 'mobile';
browser?: string;
}
/**
* User presence information
*/
export interface IUserPresence {
userId: string;
displayName: string;
avatarUrl?: string;
color: string;
status: TPresenceStatus;
currentLocation?: IUserLocation;
lastActivity: number;
sessionStarted: number;
deviceInfo?: IDeviceInfo;
}
/**
* Real-time cursor position for collaborative editing
*/
export interface ICursorPosition {
userId: string;
paragraphId: string;
offset: number;
timestamp: number;
}
// ============================================================================
// COMMENTS
// ============================================================================
/**
* Anchor point for a comment
*/
export interface ICommentAnchor {
type: 'paragraph' | 'text_range' | 'document' | 'party' | 'attachment';
paragraphId?: string;
textRange?: {
start: number;
end: number;
quotedText: string;
};
elementPath?: string;
}
/**
* User mention in comment
*/
export interface IMention {
userId: string;
displayName: string;
notified: boolean;
notifiedAt?: number;
}
/**
* Reaction on a comment
*/
export interface IReaction {
emoji: string;
userId: string;
timestamp: number;
}
/**
* Individual comment within a thread
*/
export interface IComment {
id: string;
threadId: string;
authorId: string;
authorDisplayName: string;
authorAvatarUrl?: string;
content: string;
createdAt: number;
editedAt?: number;
mentions: IMention[];
reactions: IReaction[];
parentCommentId?: string;
isDeleted: boolean;
}
/**
* Comment thread on a specific location
*/
export interface ICommentThread {
id: string;
contractId: string;
versionId: string;
anchor: ICommentAnchor;
status: TCommentThreadStatus;
resolvedBy?: string;
resolvedAt?: number;
comments: IComment[];
createdAt: number;
createdBy: string;
lastActivityAt: number;
}
// ============================================================================
// SUGGESTIONS
// ============================================================================
/**
* Suggestion for proposed changes (track changes mode)
*/
export interface ISuggestion {
id: string;
contractId: string;
versionId: string;
targetParagraphId: string;
targetTextRange?: {
start: number;
end: number;
};
changeType: TSuggestionChangeType;
originalContent: string;
suggestedContent: string;
status: TSuggestionStatus;
suggestedBy: string;
suggestedByDisplayName: string;
suggestedAt: number;
reviewedBy?: string;
reviewedAt?: number;
rejectionReason?: string;
discussionThreadId?: string;
}
// ============================================================================
// CONFLICTS
// ============================================================================
/**
* Conflicting change from a user
*/
export interface IConflictingChange {
userId: string;
userDisplayName: string;
content: string;
timestamp: number;
}
/**
* Conflict marker for simultaneous edits
*/
export interface IEditConflict {
id: string;
contractId: string;
paragraphId: string;
baseContent: string;
changes: IConflictingChange[];
status: 'unresolved' | 'resolved' | 'auto_merged';
resolvedContent?: string;
resolvedBy?: string;
resolvedAt?: number;
resolutionStrategy?: TConflictResolutionStrategy;
}
// ============================================================================
// COLLABORATION SESSION
// ============================================================================
/**
* Collaborative editing session
*/
export interface ICollaborationSession {
id: string;
contractId: string;
versionId: string;
participants: IUserPresence[];
editingMode: TEditingMode;
activeCursors: ICursorPosition[];
pendingChanges: IVersionChange[];
startedAt: number;
lastActivityAt: number;
autoSaveInterval: number;
}
// ============================================================================
// COLLABORATOR
// ============================================================================
/**
* Notification preferences for a collaborator
*/
export interface INotificationPreferences {
onComment: boolean;
onSuggestion: boolean;
onVersionPublish: boolean;
onSignatureRequest: boolean;
}
/**
* Collaborator with permission
*/
export interface ICollaborator {
userId: string;
contact: plugins.tsclass.business.TContact;
permission: TCollaborationPermission;
invitedBy: string;
invitedAt: number;
acceptedAt?: number;
expiresAt?: number;
notificationPreferences: INotificationPreferences;
}
// ============================================================================
// FACTORY FUNCTIONS
// ============================================================================
/**
* Create a new comment thread
*/
export function createCommentThread(
contractId: string,
versionId: string,
anchor: ICommentAnchor,
userId: string
): ICommentThread {
const now = Date.now();
return {
id: crypto.randomUUID(),
contractId,
versionId,
anchor,
status: 'open',
comments: [],
createdAt: now,
createdBy: userId,
lastActivityAt: now,
};
}
/**
* Create a new comment
*/
export function createComment(
threadId: string,
authorId: string,
authorDisplayName: string,
content: string
): IComment {
return {
id: crypto.randomUUID(),
threadId,
authorId,
authorDisplayName,
content,
createdAt: Date.now(),
mentions: [],
reactions: [],
isDeleted: false,
};
}
/**
* Create a new suggestion
*/
export function createSuggestion(
contractId: string,
versionId: string,
targetParagraphId: string,
changeType: TSuggestionChangeType,
originalContent: string,
suggestedContent: string,
suggestedBy: string,
suggestedByDisplayName: string
): ISuggestion {
return {
id: crypto.randomUUID(),
contractId,
versionId,
targetParagraphId,
changeType,
originalContent,
suggestedContent,
status: 'pending',
suggestedBy,
suggestedByDisplayName,
suggestedAt: Date.now(),
};
}
/**
* Create a new collaborator
*/
export function createCollaborator(
userId: string,
contact: plugins.tsclass.business.TContact,
permission: TCollaborationPermission,
invitedBy: string
): ICollaborator {
return {
userId,
contact,
permission,
invitedBy,
invitedAt: Date.now(),
notificationPreferences: {
onComment: true,
onSuggestion: true,
onVersionPublish: true,
onSignatureRequest: true,
},
};
}
/**
* Create default user presence
*/
export function createUserPresence(
userId: string,
displayName: string,
color: string
): IUserPresence {
const now = Date.now();
return {
userId,
displayName,
color,
status: 'viewing',
lastActivity: now,
sessionStarted: now,
};
}

561
ts_interfaces/contract.ts Normal file
View File

@@ -0,0 +1,561 @@
/**
* @file contract.ts
* @description Enhanced portable contract interface
* The main contract data structure that ties all modules together
*/
import * as plugins from './plugins.js';
import type {
TContractCategory,
TContractType,
TContractStatus,
TPartyRole,
TSigningDependency,
TLegalCapacity,
TSectionType,
TVariableType,
TConditionOperator,
TConditionCombine,
TLegalReferenceType,
TDisputeResolution,
TSignatureType,
TSignatureLegalLevel,
TConfidentialityLevel,
} from './types.js';
import type {
IFinancialTerms,
ITimeTerms,
IObligationTerms,
createEmptyFinancialTerms,
createEmptyTimeTerms,
createEmptyObligationTerms,
} from './terms.js';
import type { ISignature, ISignatureFieldPlacement, ISignatureFieldRequirements, ISignatureDependency } from './signature.js';
import type { IIdentityVerificationResult } from './identity.js';
import type { ILegalComplianceProof } from './legal.js';
import type { IVersionHistory, IVersion } from './versioning.js';
import type { ICollaborator, ICommentThread, ISuggestion } from './collaboration.js';
import type { IDocumentLifecycle, IAuditLog } from './lifecycle.js';
import type { IContractAttachment, IPriorContractReference } from './attachments.js';
import type { IPdfGenerationConfig } from './pdf.js';
// ============================================================================
// METADATA
// ============================================================================
/**
* Governing law and jurisdiction
*/
export interface IGoverningLaw {
country: string;
state?: string;
applicableLaws: string[];
disputeJurisdiction?: string;
disputeResolution: TDisputeResolution;
arbitrationInstitution?: string;
arbitrationRules?: string;
arbitrationSeat?: string;
numberOfArbitrators?: number;
proceedingsLanguage?: string;
}
/**
* Contract metadata
*/
export interface IContractMetadata {
contractNumber?: string;
category: TContractCategory;
contractType: TContractType;
language: string;
additionalLanguages: string[];
bindingLanguage?: string;
governingLaw: IGoverningLaw;
tags: string[];
internalReference?: string;
externalReference?: string;
templateId?: string;
parentContractId?: string;
relatedContractIds: string[];
confidentialityLevel: TConfidentialityLevel;
customFields: Record<string, unknown>;
}
// ============================================================================
// ROLES AND PARTIES
// ============================================================================
/**
* Role definition
*/
export interface IRole {
id: string;
name: string;
description: string;
category: 'party' | 'witness' | 'notary' | 'guarantor' | 'beneficiary';
signatureRequired: boolean;
defaultSigningOrder: number;
legalCapacity?: TLegalCapacity;
notifyOnChanges: boolean;
notifyOnComments: boolean;
displayColor?: string;
icon?: string;
minParties?: number;
maxParties?: number;
}
/**
* Legal proxy information
*/
export interface ILegalProxy {
type: 'self' | 'company_representative' | 'power_of_attorney' | 'guardian' | 'other';
representedEntity: plugins.tsclass.business.TContact;
position?: string;
poaDocumentId?: string;
authorityScope?: string;
}
/**
* Party signature status
*/
export interface IPartySignature {
status: 'pending' | 'viewed' | 'signed' | 'declined' | 'voided';
signedAt?: number;
signature?: ISignature;
declinedAt?: number;
declineReason?: string;
}
/**
* Involved party in contract
*/
export interface IInvolvedParty {
partyId: string;
roleId: string;
contact: plugins.tsclass.business.TContact;
partyRole: TPartyRole;
signingOrder: number;
signingDependency: TSigningDependency;
dependsOnParties: string[];
signature: IPartySignature;
identityVerification?: IIdentityVerificationResult;
legalComplianceProof?: ILegalComplianceProof;
actingAsProxy: boolean;
legalProxy?: ILegalProxy;
deliveryEmail?: string;
deliveryPhone?: string;
preferredLanguage?: string;
internalNotes?: string;
invitationSentAt?: number;
remindersSent: number;
lastReminderAt?: number;
firstViewedAt?: number;
lastViewedAt?: number;
totalViews: number;
metadata: Record<string, unknown>;
}
// ============================================================================
// CONTENT STRUCTURE
// ============================================================================
/**
* Variable validation rules
*/
export interface IVariableValidation {
pattern?: string;
minLength?: number;
maxLength?: number;
min?: number;
max?: number;
options?: string[];
}
/**
* Variable format specification
*/
export interface IVariableFormat {
dateFormat?: string;
numberFormat?: string;
currencyFormat?: string;
}
/**
* Variable source configuration
*/
export interface IVariableSource {
type: 'party_field' | 'contract_field' | 'calculated' | 'external' | 'manual';
path?: string;
formula?: string;
externalSource?: string;
}
/**
* Variable/placeholder definition
*/
export interface IVariable {
variableId: string;
name: string;
type: TVariableType;
value?: unknown;
defaultValue?: unknown;
required: boolean;
source?: IVariableSource;
validation?: IVariableValidation;
format?: IVariableFormat;
}
/**
* Condition for conditional content
*/
export interface ICondition {
conditionId: string;
field: string;
operator: TConditionOperator;
value: unknown;
combine?: TConditionCombine;
nestedConditions: ICondition[];
}
/**
* Legal reference annotation
*/
export interface ILegalReference {
type: TLegalReferenceType;
citation: string;
url?: string;
jurisdiction?: string;
effectiveDate?: number;
}
/**
* Paragraph translation
*/
export interface IParagraphTranslation {
title: string;
content: string;
}
/**
* Paragraph/section in contract
*/
export interface IParagraph {
uniqueId: string;
parentId: string | null;
title: string;
content: string;
sectionType: TSectionType;
numbering?: string;
order: number;
depth: number;
required: boolean;
isEditable: boolean;
variables: IVariable[];
conditions: ICondition[];
legalReferences: ILegalReference[];
language?: string;
translations: Record<string, IParagraphTranslation>;
crossReferences: string[];
attachmentReferences: string[];
jurisdictions: string[];
tags: string[];
aiGenerated: boolean;
templateSourceId?: string;
lastEditedBy?: string;
lastEditedAt?: number;
lockedBy?: string;
lockedAt?: number;
}
// ============================================================================
// SIGNATURE FIELDS
// ============================================================================
/**
* Signer assignment to signature field
*/
export interface ISignerAssignment {
id: string;
partyId?: string;
email: string;
phone?: string;
signingOrder: number;
invitationStatus: 'not_sent' | 'sent' | 'delivered' | 'opened' | 'bounced';
invitationSentAt?: number;
deliveredAt?: number;
openedAt?: number;
remindersSent: number;
lastReminderAt?: number;
accessTokenHash?: string;
tokenExpiresAt?: number;
}
/**
* Signature field in contract
*/
export interface ISignatureField {
id: string;
name: string;
description?: string;
placement: ISignatureFieldPlacement;
requirements: ISignatureFieldRequirements;
dependencies: ISignatureDependency[];
assignedSigner?: ISignerAssignment;
status: 'pending' | 'ready' | 'in_progress' | 'completed' | 'declined' | 'expired' | 'voided';
signature?: ISignature;
createdAt: number;
updatedAt: number;
}
// ============================================================================
// MAIN CONTRACT INTERFACE
// ============================================================================
/**
* Complete portable contract interface
* All fields are required - use empty arrays/objects where no data
*/
export interface IPortableContract {
// Core Identity
id: string;
title: string;
context: string;
metadata: IContractMetadata;
// Parties and Roles
availableRoles: IRole[];
involvedParties: IInvolvedParty[];
// Content Structure
paragraphs: IParagraph[];
variables: IVariable[];
signatureFields: ISignatureField[];
// Structured Terms
financialTerms: IFinancialTerms;
timeTerms: ITimeTerms;
obligationTerms: IObligationTerms;
// Documents
priorContracts: IPriorContractReference[];
attachments: IContractAttachment[];
// Versioning
versionHistory: IVersionHistory;
// Collaboration
collaborators: ICollaborator[];
commentThreads: ICommentThread[];
suggestions: ISuggestion[];
// Lifecycle and Audit
lifecycle: IDocumentLifecycle;
auditLog: IAuditLog;
// PDF Generation (optional)
pdfConfig?: IPdfGenerationConfig;
finalDocument?: plugins.tsclass.business.IPdf;
renderTemplateId?: string;
renderOptions?: Record<string, unknown>;
// Timestamps
createdAt: number;
createdBy: string;
updatedAt: number;
updatedBy?: string;
// Organization
organizationId?: string;
visibility: 'private' | 'organization' | 'public';
// Integrations
integrations: {
crmId?: string;
erpId?: string;
customIntegrations: Record<string, string>;
};
}
// ============================================================================
// FACTORY FUNCTIONS
// ============================================================================
import {
createEmptyFinancialTerms as _createEmptyFinancialTerms,
createEmptyTimeTerms as _createEmptyTimeTerms,
createEmptyObligationTerms as _createEmptyObligationTerms,
} from './terms.js';
import { createInitialVersion, createEmptyVersionHistory } from './versioning.js';
import { createInitialLifecycle, createEmptyAuditLog } from './lifecycle.js';
/**
* Create default governing law
*/
export function createDefaultGoverningLaw(): IGoverningLaw {
return {
country: '',
applicableLaws: [],
disputeResolution: 'litigation',
};
}
/**
* Create default contract metadata
*/
export function createDefaultMetadata(
category: TContractCategory,
contractType: TContractType,
language: string = 'en'
): IContractMetadata {
return {
category,
contractType,
language,
additionalLanguages: [],
governingLaw: createDefaultGoverningLaw(),
tags: [],
relatedContractIds: [],
confidentialityLevel: 'internal',
customFields: {},
};
}
/**
* Create a new empty contract
*/
export function createEmptyContract(
title: string,
category: TContractCategory,
contractType: TContractType,
createdBy: string,
language: string = 'en'
): IPortableContract {
const id = crypto.randomUUID();
const now = Date.now();
const initialVersion = createInitialVersion(createdBy);
return {
id,
title,
context: '',
metadata: createDefaultMetadata(category, contractType, language),
availableRoles: [],
involvedParties: [],
paragraphs: [],
variables: [],
signatureFields: [],
financialTerms: _createEmptyFinancialTerms(),
timeTerms: _createEmptyTimeTerms(),
obligationTerms: _createEmptyObligationTerms(),
priorContracts: [],
attachments: [],
versionHistory: createEmptyVersionHistory(id, initialVersion),
collaborators: [],
commentThreads: [],
suggestions: [],
lifecycle: createInitialLifecycle(id),
auditLog: createEmptyAuditLog(id),
createdAt: now,
createdBy,
updatedAt: now,
visibility: 'private',
integrations: {
customIntegrations: {},
},
};
}
/**
* Create a new role
*/
export function createRole(
id: string,
name: string,
description: string,
options: Partial<IRole> = {}
): IRole {
return {
id,
name,
description,
category: 'party',
signatureRequired: true,
defaultSigningOrder: 1,
notifyOnChanges: true,
notifyOnComments: true,
...options,
};
}
/**
* Create an involved party
*/
export function createInvolvedParty(
roleId: string,
contact: plugins.tsclass.business.TContact,
signingOrder: number = 1
): IInvolvedParty {
return {
partyId: crypto.randomUUID(),
roleId,
contact,
partyRole: 'signer',
signingOrder,
signingDependency: 'none',
dependsOnParties: [],
signature: {
status: 'pending',
},
actingAsProxy: false,
remindersSent: 0,
totalViews: 0,
metadata: {},
};
}
/**
* Create a paragraph
*/
export function createParagraph(
title: string,
content: string,
sectionType: TSectionType = 'clause',
order: number = 0
): IParagraph {
return {
uniqueId: crypto.randomUUID(),
parentId: null,
title,
content,
sectionType,
order,
depth: 0,
required: true,
isEditable: true,
variables: [],
conditions: [],
legalReferences: [],
translations: {},
crossReferences: [],
attachmentReferences: [],
jurisdictions: [],
tags: [],
aiGenerated: false,
};
}
/**
* Create a variable
*/
export function createVariable(
variableId: string,
name: string,
type: TVariableType,
required: boolean = true
): IVariable {
return {
variableId,
name,
type,
required,
};
}

295
ts_interfaces/identity.ts Normal file
View File

@@ -0,0 +1,295 @@
/**
* @file identity.ts
* @description Identity verification interfaces
* Extensible design for passport/NFC, document+selfie, video ident, and third-party providers
*/
import * as plugins from './plugins.js';
import type {
TIdentityVerificationMethod,
TVerificationConfidence,
TIdentityVerificationStatus,
TIdentityDocumentType,
} from './types.js';
// ============================================================================
// IDENTITY VERIFICATION REQUEST
// ============================================================================
/**
* Expected identity to verify against
*/
export interface IExpectedIdentity {
fullName?: string;
dateOfBirth?: string;
nationality?: string;
documentNumber?: string;
}
/**
* Request for identity verification
*/
export interface IIdentityVerificationRequest {
id: string;
methods: TIdentityVerificationMethod[];
requiredConfidence: TVerificationConfidence;
expectedIdentity?: IExpectedIdentity;
createdAt: number;
expiresAt: number;
callbackUrl?: string;
}
// ============================================================================
// DOCUMENT VERIFICATION
// ============================================================================
/**
* Personal information from identity document
*/
export interface IDocumentPersonalInfo {
fullName: string;
givenNames: string;
surname: string;
dateOfBirth: string;
sex: 'M' | 'F' | 'X';
nationality: string;
placeOfBirth?: string;
}
/**
* Document validity information
*/
export interface IDocumentValidity {
issueDate?: string;
expiryDate: string;
issuingAuthority?: string;
}
/**
* Machine Readable Zone data
*/
export interface IMrzData {
raw: string[];
valid: boolean;
checkDigitsValid: boolean;
}
/**
* NFC chip data (for ePassports)
*/
export interface INfcChipData {
readSuccess: boolean;
chipAuthenticated: boolean;
activeAuthentication?: {
performed: boolean;
success: boolean;
};
passiveAuthentication?: {
performed: boolean;
success: boolean;
certificateChainValid: boolean;
};
dataGroupsRead: string[];
photoBase64?: string;
}
/**
* Document images
*/
export interface IDocumentImages {
frontBase64?: string;
backBase64?: string;
portraitBase64?: string;
}
/**
* Identity document data extracted from document
*/
export interface IIdentityDocument {
documentType: TIdentityDocumentType;
issuingCountry: string;
documentNumber: string;
personalInfo: IDocumentPersonalInfo;
validity: IDocumentValidity;
mrz?: IMrzData;
nfcData?: INfcChipData;
images?: IDocumentImages;
}
// ============================================================================
// FACIAL/BIOMETRIC VERIFICATION
// ============================================================================
/**
* Liveness check result
*/
export interface ILivenessResult {
isLive: boolean;
confidence: number;
checks: {
blinkDetected?: boolean;
headMovementDetected?: boolean;
depthAnalysis?: boolean;
textureAnalysis?: boolean;
};
}
/**
* Face matching result
*/
export interface IFaceMatchResult {
matched: boolean;
confidence: number;
referenceSource: 'document_photo' | 'nfc_photo' | 'existing_profile';
}
/**
* Facial verification result
*/
export interface IFacialVerification {
livenessCheckPerformed: boolean;
livenessResult?: ILivenessResult;
faceMatchResult?: IFaceMatchResult;
selfieReference?: string;
capturedAt: number;
}
// ============================================================================
// THIRD-PARTY IDENTITY PROVIDER
// ============================================================================
/**
* Third-party identity provider configuration
*/
export interface IIdentityProvider {
id: string;
name: string;
type: 'oidc' | 'saml' | 'proprietary' | 'bankid' | 'eid';
countries: string[];
methods: TIdentityVerificationMethod[];
maxConfidence: TVerificationConfidence;
config?: Record<string, unknown>;
}
/**
* Third-party verification result
*/
export interface IThirdPartyVerification {
provider: IIdentityProvider;
providerReference: string;
verifiedAt: number;
claims: Record<string, unknown>;
levelOfAssurance?: 'low' | 'substantial' | 'high';
rawAssertionReference?: string;
}
// ============================================================================
// VERIFICATION FAILURES
// ============================================================================
/**
* Verification failure details
*/
export interface IVerificationFailure {
code: string;
method: TIdentityVerificationMethod;
message: string;
timestamp: number;
recoverable: boolean;
}
/**
* Verification audit entry
*/
export interface IVerificationAuditEntry {
timestamp: number;
action: string;
details: Record<string, unknown>;
actor?: {
type: 'user' | 'system' | 'agent';
id: string;
};
}
// ============================================================================
// IDENTITY VERIFICATION RESULT
// ============================================================================
/**
* Verified identity information
*/
export interface IVerifiedIdentity {
fullName: string;
givenNames?: string;
surname?: string;
dateOfBirth?: string;
nationality?: string;
address?: plugins.tsclass.business.IAddress;
}
/**
* Complete identity verification result
*/
export interface IIdentityVerificationResult {
id: string;
requestId: string;
status: TIdentityVerificationStatus;
confidence: TVerificationConfidence;
confidenceScore: number;
methodsAttempted: TIdentityVerificationMethod[];
successfulMethod?: TIdentityVerificationMethod;
verifiedIdentity?: IVerifiedIdentity;
documentVerification?: IIdentityDocument;
facialVerification?: IFacialVerification;
thirdPartyVerification?: IThirdPartyVerification;
timestamps: {
started: number;
completed: number;
expiresAt?: number;
};
failureReasons: IVerificationFailure[];
auditTrail: IVerificationAuditEntry[];
}
// ============================================================================
// FACTORY FUNCTIONS
// ============================================================================
/**
* Create an identity verification request
*/
export function createIdentityVerificationRequest(
methods: TIdentityVerificationMethod[],
requiredConfidence: TVerificationConfidence,
expiresInSeconds: number = 3600
): IIdentityVerificationRequest {
const now = Date.now();
return {
id: crypto.randomUUID(),
methods,
requiredConfidence,
createdAt: now,
expiresAt: now + expiresInSeconds * 1000,
};
}
/**
* Create a pending identity verification result
*/
export function createPendingVerificationResult(requestId: string): IIdentityVerificationResult {
const now = Date.now();
return {
id: crypto.randomUUID(),
requestId,
status: 'pending',
confidence: 'none',
confidenceScore: 0,
methodsAttempted: [],
timestamps: {
started: now,
completed: 0,
},
failureReasons: [],
auditTrail: [],
};
}

View File

@@ -1,27 +1,65 @@
/**
* @file index.ts
* @description Main export file for signature.digital contract interfaces
* Comprehensive contract management system supporting 99.9% of contract use cases
*/
import * as plugins from './plugins.js';
export interface IParagraph {
uniqueId: string;
parent: IParagraph | null;
title: string;
content: string;
}
export interface IRole {
id: string;
name: string;
description: string;
}
// Export plugins for access to tsclass types
export { plugins };
export interface IInvolvedParty {
role: string;
contact: plugins.tsclass.business.TContact;
}
// ============================================================================
// TYPE ALIASES
// ============================================================================
export * from './types.js';
export interface IPortableContract {
title: string;
context: string;
availableRoles: IRole[];
involvedParties: IInvolvedParty[];
priorContracts: IPortableContract[];
paragraphs: IParagraph[];
}
// ============================================================================
// STRUCTURED TERMS
// ============================================================================
export * from './terms.js';
// ============================================================================
// SIGNATURE SYSTEM
// ============================================================================
export * from './signature.js';
// ============================================================================
// IDENTITY VERIFICATION
// ============================================================================
export * from './identity.js';
// ============================================================================
// LEGAL COMPLIANCE
// ============================================================================
export * from './legal.js';
// ============================================================================
// VERSIONING
// ============================================================================
export * from './versioning.js';
// ============================================================================
// COLLABORATION
// ============================================================================
export * from './collaboration.js';
// ============================================================================
// LIFECYCLE AND AUDIT
// ============================================================================
export * from './lifecycle.js';
// ============================================================================
// ATTACHMENTS
// ============================================================================
export * from './attachments.js';
// ============================================================================
// PDF GENERATION
// ============================================================================
export * from './pdf.js';
// ============================================================================
// MAIN CONTRACT INTERFACE
// ============================================================================
export * from './contract.js';

369
ts_interfaces/legal.ts Normal file
View File

@@ -0,0 +1,369 @@
/**
* @file legal.ts
* @description Legal compliance interfaces
* TSA (RFC 3161) timestamps, blockchain anchoring, eIDAS qualified signatures
*/
import type {
TTimestampMethod,
TBlockchainNetwork,
THashAlgorithm,
TSignatureLegalLevel,
TComplianceAction,
TQualificationStatus,
TValidationStatus,
TIdentityVerificationMethod,
} from './types.js';
// ============================================================================
// TSA TIMESTAMP (RFC 3161)
// ============================================================================
/**
* Time Stamp Authority information
*/
export interface ITsaAuthority {
name: string;
url: string;
certificateFingerprint: string;
isQualified: boolean;
country?: string;
}
/**
* Timestamp token data
*/
export interface ITsaToken {
tokenBase64: string;
serialNumber: string;
time: number;
hashAlgorithm: string;
hashedMessage: string;
nonce?: string;
}
/**
* TSA verification status
*/
export interface ITsaVerification {
verified: boolean;
verifiedAt: number;
certificateChainValid: boolean;
signatureValid: boolean;
}
/**
* Qualified TSA information (eIDAS)
*/
export interface IQualifiedTsaInfo {
trustedListReference: string;
serviceId: string;
qualificationStatus: TQualificationStatus;
}
/**
* RFC 3161 Time Stamp Token
*/
export interface ITsaTimestamp {
id: string;
authority: ITsaAuthority;
token: ITsaToken;
verification: ITsaVerification;
qualifiedInfo?: IQualifiedTsaInfo;
}
// ============================================================================
// BLOCKCHAIN TIMESTAMP
// ============================================================================
/**
* Blockchain transaction information
*/
export interface IBlockchainTransaction {
txHash: string;
blockNumber: number;
blockHash: string;
blockTimestamp: number;
txIndex: number;
}
/**
* Merkle proof for aggregated timestamps
*/
export interface IMerkleProof {
root: string;
proof: string[];
leaf: string;
positions: ('left' | 'right')[];
}
/**
* Timestamped data information
*/
export interface ITimestampedData {
dataHash: string;
hashAlgorithm: THashAlgorithm;
dataReference?: string;
}
/**
* Blockchain verification status
*/
export interface IBlockchainVerification {
verified: boolean;
verifiedAt: number;
blockConfirmations: number;
explorerUrl?: string;
}
/**
* Blockchain timestamping provider
*/
export interface IBlockchainProvider {
name: string;
serviceId?: string;
proofUrl?: string;
}
/**
* Blockchain timestamp anchor
*/
export interface IBlockchainTimestamp {
id: string;
network: TBlockchainNetwork;
chainId?: number;
transaction: IBlockchainTransaction;
merkleProof?: IMerkleProof;
timestampedData: ITimestampedData;
verification: IBlockchainVerification;
provider?: IBlockchainProvider;
}
// ============================================================================
// LONG-TERM VALIDATION (LTV)
// ============================================================================
/**
* Long-term validation data (for PAdES-LTV equivalent)
*/
export interface ILongTermValidation {
certificateChains: string[];
ocspResponses: string[];
crlData: string[];
archiveTimestamp?: ITsaTimestamp;
}
/**
* Document hash information
*/
export interface IDocumentHashInfo {
algorithm: THashAlgorithm;
value: string;
scope: 'content_only' | 'content_and_signatures' | 'full_envelope';
}
/**
* Signature validation details
*/
export interface ISignatureValidationDetails {
cryptographicCheck: boolean;
certificateChainValid: boolean;
timestampValid: boolean;
signerIdentityVerified: boolean;
}
/**
* Signature validation result
*/
export interface ISignatureValidation {
validatedAt: number;
status: TValidationStatus;
details: ISignatureValidationDetails;
}
// ============================================================================
// COMPLIANCE AUDIT
// ============================================================================
/**
* Compliance audit entry
*/
export interface IComplianceAuditEntry {
timestamp: number;
action: TComplianceAction;
details: Record<string, unknown>;
actor: {
type: 'system' | 'service' | 'user';
id: string;
};
}
// ============================================================================
// LEGAL COMPLIANCE PROOF
// ============================================================================
/**
* Complete legal compliance proof for a signature
*/
export interface ILegalComplianceProof {
id: string;
schemaVersion: '1.0.0';
eidasLevel?: TSignatureLegalLevel;
jurisdictions: string[];
tsaTimestamps: ITsaTimestamp[];
blockchainTimestamps: IBlockchainTimestamp[];
longTermValidation?: ILongTermValidation;
documentHash: IDocumentHashInfo;
signatureValidation?: ISignatureValidation;
auditTrail: IComplianceAuditEntry[];
createdAt: number;
updatedAt: number;
}
// ============================================================================
// SIGNATURE VALIDATION REQUEST/RESULT
// ============================================================================
/**
* Request to validate a signature
*/
export interface ISignatureValidationRequest {
signatureId: string;
documentHash: string;
validationLevel: 'basic' | 'timestamp' | 'long_term';
checkRevocation: boolean;
validationTime?: number;
}
/**
* Detailed validation result for signature integrity
*/
export interface ISignatureIntegrityResult {
status: 'valid' | 'invalid';
message?: string;
}
/**
* Certificate chain validation result
*/
export interface ICertificateChainResult {
status: 'valid' | 'invalid' | 'unknown';
chainLength: number;
rootTrusted: boolean;
message?: string;
}
/**
* Timestamp validation result
*/
export interface ITimestampValidationResult {
status: 'valid' | 'invalid' | 'not_present';
timestampTime?: number;
tsaName?: string;
}
/**
* Revocation check result
*/
export interface IRevocationResult {
status: 'good' | 'revoked' | 'unknown';
checkedAt: number;
method: 'ocsp' | 'crl' | 'none';
revocationTime?: number;
}
/**
* Identity verification validation result
*/
export interface IIdentityValidationResult {
status: 'verified' | 'not_verified' | 'expired';
method?: TIdentityVerificationMethod;
verifiedAt?: number;
}
/**
* Signature validation result
*/
export interface ISignatureValidationResult {
requestId: string;
status: TValidationStatus;
details: {
signatureIntegrity: ISignatureIntegrityResult;
certificateChain?: ICertificateChainResult;
timestamp?: ITimestampValidationResult;
revocation?: IRevocationResult;
identityVerification?: IIdentityValidationResult;
};
warnings: string[];
validatedAt: number;
reportReference?: string;
}
// ============================================================================
// FACTORY FUNCTIONS
// ============================================================================
/**
* Create empty legal compliance proof
*/
export function createEmptyLegalComplianceProof(): ILegalComplianceProof {
const now = Date.now();
return {
id: crypto.randomUUID(),
schemaVersion: '1.0.0',
jurisdictions: [],
tsaTimestamps: [],
blockchainTimestamps: [],
documentHash: {
algorithm: 'SHA-256',
value: '',
scope: 'full_envelope',
},
auditTrail: [],
createdAt: now,
updatedAt: now,
};
}
/**
* Create a TSA timestamp request result placeholder
*/
export function createPendingTsaTimestamp(authorityUrl: string): Partial<ITsaTimestamp> {
return {
id: crypto.randomUUID(),
authority: {
name: '',
url: authorityUrl,
certificateFingerprint: '',
isQualified: false,
},
verification: {
verified: false,
verifiedAt: 0,
certificateChainValid: false,
signatureValid: false,
},
};
}
/**
* Create a blockchain timestamp placeholder
*/
export function createPendingBlockchainTimestamp(
network: TBlockchainNetwork,
dataHash: string
): Partial<IBlockchainTimestamp> {
return {
id: crypto.randomUUID(),
network,
timestampedData: {
dataHash,
hashAlgorithm: 'SHA-256',
},
verification: {
verified: false,
verifiedAt: 0,
blockConfirmations: 0,
},
};
}

457
ts_interfaces/lifecycle.ts Normal file
View File

@@ -0,0 +1,457 @@
/**
* @file lifecycle.ts
* @description Document lifecycle and audit interfaces
* Status workflow, transitions, retention policies, and legal holds
*/
import * as plugins from './plugins.js';
import type {
TContractStatus,
TTerminationReason,
TActionCategory,
TActionSeverity,
TPaymentFrequency,
} from './types.js';
import type { IDuration, IMonetaryAmount, IPriceAdjustment } from './terms.js';
// ============================================================================
// STATUS TRANSITIONS
// ============================================================================
/**
* Validation check for status transition
*/
export interface IStatusValidation {
rule: string;
description: string;
passed: boolean;
failureReason?: string;
checkedAt: number;
}
/**
* Status transition with validation
*/
export interface IStatusTransition {
fromStatus: TContractStatus;
toStatus: TContractStatus;
triggeredBy: string;
triggeredAt: number;
reason?: string;
metadata?: Record<string, unknown>;
validationsPerformed: IStatusValidation[];
}
/**
* Validation rule for transitions
*/
export interface ITransitionValidationRule {
id: string;
name: string;
description: string;
validatorType: 'signature_count' | 'approval_chain' | 'date_check' | 'custom';
parameters?: Record<string, unknown>;
}
/**
* Status transition rules configuration
*/
export interface IStatusTransitionRule {
allowedTransitions: TContractStatus[];
requiredValidations: ITransitionValidationRule[];
requiresApproval: boolean;
approverRoles?: string[];
}
/**
* Map of status transition rules
*/
export type TStatusTransitionRules = Record<TContractStatus, IStatusTransitionRule>;
// ============================================================================
// TERMINATION
// ============================================================================
/**
* Early termination penalty
*/
export interface IEarlyTerminationPenalty {
amount: number;
currency: string;
paid: boolean;
paidAt?: number;
}
/**
* Termination record
*/
export interface ITermination {
terminatedAt: number;
terminatedBy: string;
effectiveDate: number;
reason: TTerminationReason;
customReasonDescription?: string;
noticeGiven: boolean;
noticeDate?: number;
noticePeriodDays?: number;
earlyTerminationPenalty?: IEarlyTerminationPenalty;
mutuallyAgreed: boolean;
agreementDocumentId?: string;
}
// ============================================================================
// EXPIRATION AND RENEWAL
// ============================================================================
/**
* Auto-renewal terms
*/
export interface IAutoRenewTerms {
renewalPeriodMonths: number;
maxRenewals: number;
currentRenewalCount: number;
priceAdjustment?: IPriceAdjustment;
}
/**
* Renewal notice information
*/
export interface IRenewalNotice {
requiredNoticeDays: number;
noticeReceivedAt?: number;
renewalDeclined: boolean;
declinedAt?: number;
declinedBy?: string;
}
/**
* Expiration and renewal handling
*/
export interface IExpirationConfig {
expirationDate: number;
reminderDays: number[];
autoRenew: boolean;
autoRenewTerms?: IAutoRenewTerms;
renewalNotice?: IRenewalNotice;
}
// ============================================================================
// STATUS HISTORY
// ============================================================================
/**
* Complete status history entry
*/
export interface IStatusHistoryEntry {
id: string;
previousStatus: TContractStatus | null;
newStatus: TContractStatus;
transition: IStatusTransition;
versionIdAtTransition: string;
hashChainLink: string;
}
// ============================================================================
// DOCUMENT LIFECYCLE
// ============================================================================
/**
* Document lifecycle state
*/
export interface IDocumentLifecycle {
contractId: string;
currentStatus: TContractStatus;
statusHistory: IStatusHistoryEntry[];
createdAt: number;
firstPublishedAt?: number;
executedAt?: number;
effectiveDate?: number;
expiration?: IExpirationConfig;
termination?: ITermination;
supersededBy?: string;
supersedes?: string;
}
// ============================================================================
// AUDIT LOG
// ============================================================================
/**
* Geolocation for audit entry
*/
export interface IAuditGeolocation {
country: string;
region?: string;
city?: string;
coordinates?: {
lat: number;
lng: number;
};
}
/**
* Digital signature for audit entry non-repudiation
*/
export interface IAuditDigitalSignature {
signedBy: string;
algorithm: 'RSA-SHA256' | 'ECDSA-P256';
signature: string;
certificate?: string;
}
/**
* Extended action interface building on IObjectAction from tsclass
*/
export interface IContractAction extends plugins.tsclass.database.IObjectAction {
id: string;
contractId: string;
versionId?: string;
category: TActionCategory;
severity: TActionSeverity;
ipAddress?: string;
userAgent?: string;
sessionId?: string;
location?: IAuditGeolocation;
previousActionHash: string;
actionHash: string;
digitalSignature?: IAuditDigitalSignature;
}
/**
* Audit log statistics
*/
export interface IAuditStatistics {
totalActions: number;
actionsByCategory: Record<TActionCategory, number>;
uniqueUsers: string[];
dateRange: {
earliest: number;
latest: number;
};
}
/**
* Complete audit log for a contract
*/
export interface IAuditLog {
contractId: string;
actions: IContractAction[];
genesisHash: string;
currentHash: string;
chainLength: number;
lastVerifiedAt?: number;
statistics: IAuditStatistics;
}
// ============================================================================
// RETENTION AND LEGAL HOLDS
// ============================================================================
/**
* Retention policy scope
*/
export interface IRetentionScope {
contractTypes?: string[];
jurisdictions?: string[];
tags?: string[];
allContracts?: boolean;
}
/**
* Retention period configuration
*/
export interface IRetentionPeriod {
duration: number;
startFrom: 'execution' | 'expiration' | 'termination' | 'creation';
}
/**
* Retention policy configuration
*/
export interface IRetentionPolicy {
id: string;
name: string;
description: string;
appliesTo: IRetentionScope;
retentionPeriod: IRetentionPeriod;
endOfRetentionAction: 'archive' | 'delete' | 'review' | 'anonymize';
legalBasis?: string;
legalHoldOverrides: boolean;
}
/**
* Legal hold for litigation/investigation
*/
export interface ILegalHold {
id: string;
name: string;
description: string;
contractIds: string[];
userIds?: string[];
dateRange?: {
start: number;
end: number;
};
createdBy: string;
createdAt: number;
reason: string;
caseReference?: string;
indefinite: boolean;
expiresAt?: number;
status: 'active' | 'released' | 'expired';
releasedBy?: string;
releasedAt?: number;
releaseReason?: string;
}
// ============================================================================
// DISCOVERY EXPORT
// ============================================================================
/**
* Discovery export access log entry
*/
export interface IDiscoveryAccessLog {
userId: string;
accessedAt: number;
action: 'download' | 'view';
ipAddress: string;
}
/**
* Export package for legal discovery
*/
export interface IDiscoveryExport {
id: string;
requestedBy: string;
requestedAt: number;
contractIds: string[];
dateRange?: {
start: number;
end: number;
};
includeAuditLog: boolean;
includeVersionHistory: boolean;
includeComments: boolean;
includeAttachments: boolean;
format: 'pdf' | 'json' | 'xml' | 'native';
packageUrl?: string;
packageHash?: string;
generatedAt?: number;
expiresAt?: number;
accessLog: IDiscoveryAccessLog[];
}
// ============================================================================
// COMPLIANCE CHECK
// ============================================================================
/**
* Individual compliance finding
*/
export interface IComplianceFinding {
id: string;
severity: 'critical' | 'major' | 'minor' | 'informational';
title: string;
description: string;
affectedElements?: string[];
recommendation?: string;
}
/**
* Compliance check result
*/
export interface IComplianceCheck {
checkId: string;
contractId: string;
performedAt: number;
performedBy: string;
checkType: 'retention' | 'signature_validity' | 'chain_integrity' | 'access_audit';
passed: boolean;
findings: IComplianceFinding[];
remediationRequired: boolean;
remediationActions?: string[];
remediationDeadline?: number;
}
// ============================================================================
// FACTORY FUNCTIONS
// ============================================================================
/**
* Create initial document lifecycle
*/
export function createInitialLifecycle(contractId: string): IDocumentLifecycle {
const now = Date.now();
return {
contractId,
currentStatus: 'draft',
statusHistory: [],
createdAt: now,
};
}
/**
* Create empty audit log
*/
export function createEmptyAuditLog(contractId: string): IAuditLog {
const genesisHash = crypto.randomUUID();
return {
contractId,
actions: [],
genesisHash,
currentHash: genesisHash,
chainLength: 0,
statistics: {
totalActions: 0,
actionsByCategory: {} as Record<TActionCategory, number>,
uniqueUsers: [],
dateRange: {
earliest: 0,
latest: 0,
},
},
};
}
/**
* Create a status transition
*/
export function createStatusTransition(
fromStatus: TContractStatus,
toStatus: TContractStatus,
triggeredBy: string,
reason?: string
): IStatusTransition {
return {
fromStatus,
toStatus,
triggeredBy,
triggeredAt: Date.now(),
reason,
validationsPerformed: [],
};
}
/**
* Create a legal hold
*/
export function createLegalHold(
name: string,
description: string,
contractIds: string[],
createdBy: string,
reason: string
): ILegalHold {
return {
id: crypto.randomUUID(),
name,
description,
contractIds,
createdBy,
createdAt: Date.now(),
reason,
indefinite: true,
status: 'active',
};
}

502
ts_interfaces/pdf.ts Normal file
View File

@@ -0,0 +1,502 @@
/**
* @file pdf.ts
* @description PDF generation configuration interfaces
* Templates, branding, layout, headers/footers, and security
*/
import * as plugins from './plugins.js';
import type {
TPageSize,
TPageOrientation,
THeaderFooterContentType,
TPageNumberFormat,
TPdfEncryptionAlgorithm,
TPdfPrintingPermission,
TPdfJobStatus,
} from './types.js';
// ============================================================================
// FONT CONFIGURATION
// ============================================================================
/**
* Font configuration
*/
export interface IFontConfig {
family: string;
fallback: string[];
size: number;
lineHeight: number;
weight?: 'normal' | 'bold' | number;
}
// ============================================================================
// BRANDING
// ============================================================================
/**
* Logo configuration
*/
export interface ILogoConfig {
url: string;
position: 'left' | 'center' | 'right';
maxWidth: number;
maxHeight: number;
}
/**
* Watermark configuration
*/
export interface IWatermarkConfig {
text?: string;
imageUrl?: string;
opacity: number;
position: 'center' | 'diagonal';
showOnlyOnDraft: boolean;
}
/**
* Branding configuration for PDF
*/
export interface IPdfBranding {
logo?: ILogoConfig;
primaryColor: string;
secondaryColor: string;
textColor: string;
fonts: {
heading: IFontConfig;
body: IFontConfig;
monospace?: IFontConfig;
};
watermark?: IWatermarkConfig;
}
// ============================================================================
// LAYOUT
// ============================================================================
/**
* Custom page size
*/
export interface ICustomPageSize {
width: number;
height: number;
}
/**
* Page margins
*/
export interface IPageMargins {
top: number;
right: number;
bottom: number;
left: number;
}
/**
* PDF layout configuration
*/
export interface IPdfLayout {
pageSize: TPageSize;
customSize?: ICustomPageSize;
orientation: TPageOrientation;
margins: IPageMargins;
columns: 1 | 2;
columnGap?: number;
paragraphSpacing: number;
sectionSpacing: number;
firstPageDifferent: boolean;
firstPageMargins?: IPageMargins;
}
// ============================================================================
// HEADER/FOOTER
// ============================================================================
/**
* Header/Footer content definition
*/
export interface IPdfHeaderFooterContent {
type: THeaderFooterContentType;
text?: string;
imageUrl?: string;
pageNumberFormat?: TPageNumberFormat;
pageNumberPrefix?: string;
includeTotal?: boolean;
dateFormat?: string;
customTemplate?: string;
fontSize?: number;
fontWeight?: 'normal' | 'bold';
color?: string;
}
/**
* Header/Footer configuration
*/
export interface IPdfHeaderFooter {
enabled: boolean;
height: number;
left?: IPdfHeaderFooterContent;
center?: IPdfHeaderFooterContent;
right?: IPdfHeaderFooterContent;
borderBottom?: boolean;
borderTop?: boolean;
borderColor?: string;
skipFirstPage: boolean;
skipLastPage: boolean;
}
// ============================================================================
// PAGE NUMBERING
// ============================================================================
/**
* Page numbering configuration
*/
export interface IPdfPageNumbering {
enabled: boolean;
startFrom: number;
format: TPageNumberFormat;
position: 'header' | 'footer';
alignment: 'left' | 'center' | 'right';
prefix?: string;
suffix?: string;
}
// ============================================================================
// CONTENT OPTIONS
// ============================================================================
/**
* Table of contents configuration
*/
export interface ITocConfig {
enabled: boolean;
depth: number;
title: string;
pageBreakAfter: boolean;
}
/**
* Cover page configuration
*/
export interface ICoverPageConfig {
enabled: boolean;
template: 'standard' | 'minimal' | 'custom';
customTemplateId?: string;
showLogo: boolean;
showDate: boolean;
showParties: boolean;
showConfidentialityNotice: boolean;
confidentialityText?: string;
}
/**
* Signature page configuration
*/
export interface ISignaturePageConfig {
enabled: boolean;
signatureBlockStyle: 'inline' | 'separate_page' | 'both';
includeWitnessLines: boolean;
includeInitialsOnEachPage: boolean;
}
/**
* Attachment handling configuration
*/
export interface IAttachmentConfig {
includeInline: boolean;
includeSeparately: boolean;
attachmentToc: boolean;
}
/**
* Content formatting configuration
*/
export interface IFormattingConfig {
headingNumbering: boolean;
paragraphNumbering: boolean;
preserveMarkdownFormatting: boolean;
convertLinksToFootnotes: boolean;
}
/**
* Content rendering options
*/
export interface IPdfContentOptions {
tableOfContents: ITocConfig;
coverPage?: ICoverPageConfig;
signaturePages: ISignaturePageConfig;
attachments: IAttachmentConfig;
formatting: IFormattingConfig;
}
// ============================================================================
// SECURITY
// ============================================================================
/**
* Encryption configuration
*/
export interface IPdfEncryption {
enabled: boolean;
algorithm: TPdfEncryptionAlgorithm;
}
/**
* Password protection
*/
export interface IPdfPasswords {
userPassword?: string;
ownerPassword?: string;
}
/**
* PDF permissions
*/
export interface IPdfPermissions {
printing: TPdfPrintingPermission;
copying: boolean;
modifying: boolean;
annotating: boolean;
formFilling: boolean;
accessibility: boolean;
assembly: boolean;
}
/**
* PDF digital signature configuration
*/
export interface IPdfDigitalSignature {
enabled: boolean;
certificateId: string;
signatureReason: string;
signatureLocation?: string;
timestampAuthority?: string;
}
/**
* PDF security options
*/
export interface IPdfSecurity {
encryption: IPdfEncryption;
passwords?: IPdfPasswords;
permissions: IPdfPermissions;
digitalSignature?: IPdfDigitalSignature;
}
// ============================================================================
// METADATA
// ============================================================================
/**
* PDF metadata
*/
export interface IPdfMetadata {
title: string;
subject?: string;
author?: string;
creator: string;
producer: string;
keywords: string[];
creationDate: number;
modificationDate?: number;
customProperties?: Record<string, string>;
}
// ============================================================================
// COMPLETE CONFIGURATION
// ============================================================================
/**
* Complete PDF generation configuration
*/
export interface IPdfGenerationConfig {
templateId?: string;
useDefaultTemplate: boolean;
branding: IPdfBranding;
layout: IPdfLayout;
header?: IPdfHeaderFooter;
footer?: IPdfHeaderFooter;
pageNumbering: IPdfPageNumbering;
contentOptions: IPdfContentOptions;
security?: IPdfSecurity;
metadata: IPdfMetadata;
}
// ============================================================================
// PDF TEMPLATE
// ============================================================================
/**
* PDF template definition
*/
export interface IPdfTemplate {
id: string;
name: string;
description?: string;
version: string;
config: IPdfGenerationConfig;
allowedContractTypes?: string[];
organizationId?: string;
isSystem: boolean;
createdAt: number;
createdBy: string;
lastModifiedAt?: number;
lastModifiedBy?: string;
}
// ============================================================================
// PDF GENERATION JOB
// ============================================================================
/**
* PDF generation result
*/
export interface IPdfGenerationResult {
pdf: plugins.tsclass.business.IPdf;
pageCount: number;
fileSize: number;
}
/**
* PDF generation error
*/
export interface IPdfGenerationError {
code: string;
message: string;
details?: unknown;
}
/**
* PDF generation job
*/
export interface IPdfGenerationJob {
id: string;
contractId: string;
versionId: string;
config: IPdfGenerationConfig;
status: TPdfJobStatus;
progress?: number;
queuedAt: number;
startedAt?: number;
completedAt?: number;
result?: IPdfGenerationResult;
error?: IPdfGenerationError;
retryCount: number;
maxRetries: number;
}
// ============================================================================
// FACTORY FUNCTIONS
// ============================================================================
/**
* Create default branding
*/
export function createDefaultBranding(): IPdfBranding {
return {
primaryColor: '#1a1a1a',
secondaryColor: '#666666',
textColor: '#333333',
fonts: {
heading: {
family: 'Helvetica',
fallback: ['Arial', 'sans-serif'],
size: 14,
lineHeight: 1.4,
weight: 'bold',
},
body: {
family: 'Helvetica',
fallback: ['Arial', 'sans-serif'],
size: 11,
lineHeight: 1.5,
},
},
};
}
/**
* Create default layout
*/
export function createDefaultLayout(): IPdfLayout {
return {
pageSize: 'A4',
orientation: 'portrait',
margins: {
top: 25,
right: 20,
bottom: 25,
left: 20,
},
columns: 1,
paragraphSpacing: 10,
sectionSpacing: 20,
firstPageDifferent: false,
};
}
/**
* Create default content options
*/
export function createDefaultContentOptions(): IPdfContentOptions {
return {
tableOfContents: {
enabled: true,
depth: 2,
title: 'Table of Contents',
pageBreakAfter: true,
},
signaturePages: {
enabled: true,
signatureBlockStyle: 'inline',
includeWitnessLines: false,
includeInitialsOnEachPage: false,
},
attachments: {
includeInline: false,
includeSeparately: true,
attachmentToc: true,
},
formatting: {
headingNumbering: true,
paragraphNumbering: false,
preserveMarkdownFormatting: true,
convertLinksToFootnotes: false,
},
};
}
/**
* Create default page numbering
*/
export function createDefaultPageNumbering(): IPdfPageNumbering {
return {
enabled: true,
startFrom: 1,
format: 'numeric',
position: 'footer',
alignment: 'center',
};
}
/**
* Create default PDF generation config
*/
export function createDefaultPdfConfig(title: string): IPdfGenerationConfig {
return {
useDefaultTemplate: true,
branding: createDefaultBranding(),
layout: createDefaultLayout(),
pageNumbering: createDefaultPageNumbering(),
contentOptions: createDefaultContentOptions(),
metadata: {
title,
creator: 'signature.digital',
producer: 'signature.digital PDF Generator',
keywords: [],
creationDate: Date.now(),
},
};
}

204
ts_interfaces/readme.md Normal file
View File

@@ -0,0 +1,204 @@
# @signature.digital/interfaces
Core TypeScript interfaces for the signature.digital contract management system. 📋
This package provides **200+ interfaces and types** covering every aspect of digital contract management from basic contract structure to eIDAS-compliant signatures, identity verification, and legal compliance.
## Install
```bash
pnpm add @signature.digital/interfaces
```
## Usage
```typescript
import type {
IPortableContract,
IRole,
IInvolvedParty,
IParagraph,
TContractStatus,
} from '@signature.digital/interfaces';
```
## Module Structure
The package is organized into focused modules:
| Module | Description |
|--------|-------------|
| `types.ts` | Foundation type aliases (90+ types) |
| `terms.ts` | Financial, time, and obligation terms |
| `signature.ts` | Signature data structures and fields |
| `identity.ts` | Identity verification system |
| `legal.ts` | TSA timestamps, blockchain anchoring, compliance |
| `versioning.ts` | Semantic versioning and change tracking |
| `collaboration.ts` | Comments, suggestions, presence |
| `lifecycle.ts` | Status workflow, audit logs, retention |
| `attachments.ts` | Exhibits, schedules, document bundles |
| `pdf.ts` | PDF generation configuration |
| `contract.ts` | Main `IPortableContract` interface |
## Type Categories
### 📋 Contract Classification
```typescript
type TContractCategory = 'employment' | 'service' | 'sales' | 'lease' | 'license' | 'partnership' | 'confidentiality' | 'financial' | 'real_estate' | 'intellectual_property' | 'government' | 'construction' | 'healthcare' | 'insurance' | 'other';
type TContractType = 'employment_full_time' | 'employment_part_time' | 'employment_minijob' | ... | string;
type TContractStatus = 'draft' | 'internal_review' | 'legal_review' | 'negotiation' | 'pending_approval' | 'pending_signature' | 'partially_signed' | 'signed' | 'executed' | 'active' | 'suspended' | 'renewal_pending' | 'expired' | 'terminated' | 'superseded' | 'cancelled' | 'voided';
```
### ✍️ Signature Types
```typescript
type TSignatureType = 'drawn' | 'typed' | 'click' | 'digital' | 'qualified' | 'biometric';
type TSignatureLegalLevel = 'simple' | 'advanced' | 'qualified';
type TSignatureStatus = 'pending' | 'captured' | 'verified' | 'timestamped' | 'complete' | 'revoked' | 'expired';
```
### 🪪 Identity Verification
```typescript
type TIdentityVerificationMethod = 'none' | 'email' | 'sms' | 'knowledge' | 'document_upload' | 'document_nfc' | 'document_ocr' | 'biometric_facial' | 'video_ident' | 'bankid' | 'eid' | 'third_party_idp';
type TVerificationConfidence = 'none' | 'low' | 'medium' | 'high' | 'verified';
type TIdentityDocumentType = 'passport' | 'national_id' | 'drivers_license' | 'residence_permit' | 'travel_document' | 'other';
```
### 💰 Financial Types
```typescript
type TPaymentFrequency = 'one_time' | 'daily' | 'weekly' | 'bi_weekly' | 'semi_monthly' | 'monthly' | 'bi_monthly' | 'quarterly' | 'semi_annually' | 'annually' | 'on_demand' | 'upon_completion' | 'milestone_based' | 'custom';
type TPaymentMethod = 'bank_transfer' | 'sepa_direct_debit' | 'credit_card' | 'check' | 'cash' | 'paypal' | 'crypto' | 'escrow' | 'letter_of_credit' | 'other';
```
### ⏱️ Time & Duration
```typescript
type TDurationUnit = 'hours' | 'days' | 'weeks' | 'months' | 'years' | 'indefinite';
type TRenewalType = 'none' | 'manual' | 'auto_renew' | 'evergreen' | 'option_to_renew';
type TTerminationReason = 'breach_of_contract' | 'mutual_agreement' | 'convenience' | 'non_performance' | 'insolvency' | 'force_majeure' | 'regulatory_change' | 'merger_acquisition' | 'other';
```
### ⚖️ Legal Compliance
```typescript
type TTimestampMethod = 'tsa' | 'blockchain' | 'qualified_tsa';
type TBlockchainNetwork = 'bitcoin' | 'ethereum' | 'polygon' | 'arbitrum' | 'optimism' | 'hyperledger' | 'private';
type THashAlgorithm = 'SHA-256' | 'SHA-384' | 'SHA-512' | 'Keccak-256';
type TSignatureAlgorithm = 'RSA-SHA256' | 'RSA-SHA384' | 'RSA-SHA512' | 'ECDSA-P256' | 'ECDSA-P384' | 'Ed25519';
```
## Key Interfaces
### IPortableContract
The main contract interface that ties everything together:
```typescript
interface IPortableContract {
id: string;
title: string;
context: string;
metadata: IContractMetadata;
availableRoles: IRole[];
involvedParties: IInvolvedParty[];
paragraphs: IParagraph[];
variables: IVariable[];
signatureFields: ISignatureField[];
financialTerms: IFinancialTerms;
timeTerms: ITimeTerms;
obligationTerms: IObligationTerms;
priorContracts: IPriorContractReference[];
attachments: IContractAttachment[];
versionHistory: IVersionHistory;
collaborators: ICollaborator[];
commentThreads: ICommentThread[];
suggestions: ISuggestion[];
lifecycle: IDocumentLifecycle;
auditLog: IAuditLog;
pdfConfig?: IPdfGenerationConfig;
// ... timestamps, organization, integrations
}
```
### ISignature
Complete signature with data, metadata, and verification:
```typescript
interface ISignature {
id: string;
signatureType: TSignatureType;
legalLevel: TSignatureLegalLevel;
data: TSignatureData; // Discriminated union
metadata: ISignatureMetadata;
consents: IConsent[];
auditTrail: ISignatureAuditEntry[];
status: TSignatureStatus;
}
```
### IIdentityVerificationResult
Full identity verification outcome:
```typescript
interface IIdentityVerificationResult {
id: string;
status: TIdentityVerificationStatus;
confidence: TVerificationConfidence;
confidenceScore: number;
methodsAttempted: TIdentityVerificationMethod[];
verifiedIdentity?: IVerifiedIdentity;
documentVerification?: IIdentityDocument;
facialVerification?: IFacialVerification;
thirdPartyVerification?: IThirdPartyVerification;
// ... timestamps, failures, audit trail
}
```
## Factory Functions
Each module provides factory functions for creating properly initialized objects:
```typescript
import {
createEmptyContract,
createRole,
createParagraph,
createEmptyFinancialTerms,
createInitialVersion,
createCommentThread,
createDefaultPdfConfig,
// ... 30+ factory functions
} from '@signature.digital/interfaces';
```
## Dependencies
- `@tsclass/tsclass` Business entity types (`TContact`, `IAddress`, `IPdf`, etc.)
## License and Legal Information
This repository contains open-source code licensed under the MIT License. A copy of the license can be found in the [LICENSE](../LICENSE) file.
**Please note:** The MIT License does not grant permission to use the trade names, trademarks, service marks, or product names of the project, except as required for reasonable and customary use in describing the origin of the work and reproducing the content of the NOTICE file.
### Trademarks
This project is owned and maintained by Task Venture Capital GmbH. The names and logos associated with Task Venture Capital GmbH and any related products or services are trademarks of Task Venture Capital GmbH or third parties, and are not included within the scope of the MIT license granted herein.
Use of these trademarks must comply with Task Venture Capital GmbH's Trademark Guidelines or the guidelines of the respective third-party owners, and any usage must be approved in writing. Third-party trademarks used herein are the property of their respective owners and used only in a descriptive manner, e.g. for an implementation of an API or similar.
### Company Information
Task Venture Capital GmbH
Registered at District Court Bremen HRB 35230 HB, Germany
For any legal inquiries or further information, please contact us via email at hello@task.vc.
By using this repository, you acknowledge that you have read this section, agree to comply with its terms, and understand that the licensing of the code does not imply endorsement by Task Venture Capital GmbH of any derivative works.

436
ts_interfaces/signature.ts Normal file
View File

@@ -0,0 +1,436 @@
/**
* @file signature.ts
* @description Signature data structures and types
* Supports drawn, typed, click, digital, qualified, and biometric signatures
*/
import type {
TSignatureType,
TSignatureLegalLevel,
TSignatureStatus,
TSignatureAuditAction,
THashAlgorithm,
TSignatureAlgorithm,
} from './types.js';
// ============================================================================
// SIGNATURE DATA STRUCTURES (Discriminated Union)
// ============================================================================
/**
* Base signature data common to all types
*/
export interface ISignatureDataBase {
id: string;
schemaVersion: '1.0.0';
capturedAt: number;
}
/**
* Individual stroke point from signature_pad
*/
export interface ISignatureStrokePoint {
x: number;
y: number;
pressure: number;
time: number;
}
/**
* Drawn signature data (canvas-based)
* Compatible with signature_pad library output
*/
export interface ISignatureDataDrawn extends ISignatureDataBase {
type: 'drawn';
strokeData: ISignatureStrokePoint[][];
svg: string;
pngBase64?: string;
canvasDimensions: {
width: number;
height: number;
devicePixelRatio: number;
};
drawingMetrics?: {
totalStrokes: number;
totalPoints: number;
averageVelocity: number;
drawingDurationMs: number;
};
}
/**
* Typed signature data
*/
export interface ISignatureDataTyped extends ISignatureDataBase {
type: 'typed';
text: string;
fontFamily: string;
fontSize: number;
svg: string;
pngBase64?: string;
}
/**
* Click-to-sign acknowledgment
*/
export interface ISignatureDataClick extends ISignatureDataBase {
type: 'click';
acknowledgmentText: string;
acknowledged: boolean;
fullNameEntered?: string;
jobTitle?: string;
}
/**
* Certificate information for digital signatures
*/
export interface ICertificateInfo {
certificatePem: string;
serialNumber: string;
issuer: string;
subject: string;
validity: {
notBefore: number;
notAfter: number;
};
fingerprint: string;
}
/**
* Digital certificate-based signature (X.509/PKI)
*/
export interface ISignatureDataDigital extends ISignatureDataBase {
type: 'digital';
certificate: ICertificateInfo;
signatureValue: string;
signatureAlgorithm: TSignatureAlgorithm;
contentHash: string;
hashAlgorithm: THashAlgorithm;
}
/**
* Qualified Trust Service Provider information
*/
export interface IQtspInfo {
name: string;
providerId: string;
serviceId: string;
country: string;
}
/**
* Signature creation device information
*/
export interface ISignatureCreationDevice {
type: 'local' | 'remote';
deviceId?: string;
certification?: string;
}
/**
* Qualified Electronic Signature (eIDAS QES)
*/
export interface ISignatureDataQualified extends ISignatureDataBase {
type: 'qualified';
digitalSignature: Omit<ISignatureDataDigital, 'type' | 'id' | 'schemaVersion' | 'capturedAt'>;
qtsp: IQtspInfo;
trustedListReference?: string;
signatureCreationDevice?: ISignatureCreationDevice;
}
/**
* Biometric signature data (extensible for future)
*/
export interface ISignatureDataBiometric extends ISignatureDataBase {
type: 'biometric';
biometricType: 'fingerprint' | 'facial' | 'voice' | 'iris';
templateReference: string;
confidenceScore: number;
provider: string;
}
/**
* Union type of all signature data types
*/
export type TSignatureData =
| ISignatureDataDrawn
| ISignatureDataTyped
| ISignatureDataClick
| ISignatureDataDigital
| ISignatureDataQualified
| ISignatureDataBiometric;
// ============================================================================
// SIGNATURE METADATA
// ============================================================================
/**
* IP geolocation information
*/
export interface IIpGeolocation {
country: string;
countryCode: string;
region?: string;
city?: string;
}
/**
* Device fingerprint for fraud detection
*/
export interface IDeviceFingerprint {
hash: string;
components: {
screenResolution?: string;
timezone?: string;
language?: string;
platform?: string;
colorDepth?: number;
touchSupport?: boolean;
canvasFingerprint?: string;
webglFingerprint?: string;
};
confidence: number;
}
/**
* Session information
*/
export interface ISigningSession {
sessionId: string;
sessionStarted: number;
pageViews: number;
documentsViewed: string[];
}
/**
* Comprehensive signature metadata capturing context
*/
export interface ISignatureMetadata {
timestamps: {
clientCaptured: number;
serverReceived?: number;
blockchainTimestamped?: number;
tsaTimestamped?: number;
};
geolocation?: {
latitude: number;
longitude: number;
accuracy: number;
altitude?: number;
timestamp: number;
source: 'gps' | 'network' | 'ip-based';
};
network: {
ipAddress: string;
ipGeolocation?: IIpGeolocation;
userAgent: string;
};
deviceFingerprint?: IDeviceFingerprint;
session?: ISigningSession;
}
// ============================================================================
// CONSENT AND VERIFICATION
// ============================================================================
/**
* Legal consent record
*/
export interface IConsent {
type: 'terms_accepted' | 'electronic_signature' | 'data_processing' | 'custom';
text: string;
accepted: boolean;
timestamp?: number;
}
/**
* Signature audit trail entry
*/
export interface ISignatureAuditEntry {
timestamp: number;
action: TSignatureAuditAction;
actor: {
type: 'user' | 'system' | 'service';
id: string;
name?: string;
};
details: Record<string, unknown>;
ipAddress?: string;
}
// ============================================================================
// COMPLETE SIGNATURE OBJECT
// ============================================================================
/**
* Forward declaration for identity verification (defined in identity.ts)
*/
export interface IIdentityVerificationResultRef {
id: string;
status: string;
confidence: string;
}
/**
* Forward declaration for legal compliance proof (defined in legal.ts)
*/
export interface ILegalComplianceProofRef {
id: string;
eidasLevel?: TSignatureLegalLevel;
}
/**
* Complete signature with data, metadata, and verification status
*/
export interface ISignature {
id: string;
schemaVersion: '1.0.0';
signatureType: TSignatureType;
legalLevel: TSignatureLegalLevel;
data: TSignatureData;
metadata: ISignatureMetadata;
identityVerificationId?: string;
legalComplianceProofId?: string;
consents: IConsent[];
auditTrail: ISignatureAuditEntry[];
status: TSignatureStatus;
}
// ============================================================================
// SIGNATURE FIELD PLACEMENT
// ============================================================================
/**
* Paragraph-based placement
*/
export interface IPlacementParagraph {
paragraphId: string;
position: 'before' | 'after' | 'inline';
inlineOffset?: number;
}
/**
* Page-based placement (PDF coordinates)
*/
export interface IPlacementPage {
pageNumber: number;
coordinates: {
x: number;
y: number;
width: number;
height: number;
};
}
/**
* Anchor-based placement
*/
export interface IPlacementAnchor {
anchorText: string;
occurrence: number;
offset: {
x: number;
y: number;
};
size: {
width: number;
height: number;
};
}
/**
* Signature field placement configuration
*/
export interface ISignatureFieldPlacement {
type: 'paragraph' | 'page' | 'anchor' | 'append';
paragraph?: IPlacementParagraph;
page?: IPlacementPage;
anchor?: IPlacementAnchor;
displayOrder: number;
}
// ============================================================================
// SIGNATURE FIELD REQUIREMENTS
// ============================================================================
import type { TIdentityVerificationMethod, TVerificationConfidence } from './types.js';
/**
* Requirements for a signature field
*/
export interface ISignatureFieldRequirements {
required: boolean;
allowedSignatureTypes: TSignatureType[];
minimumLegalLevel: TSignatureLegalLevel;
identityVerification: {
required: boolean;
allowedMethods?: TIdentityVerificationMethod[];
minimumConfidence?: TVerificationConfidence;
};
timestamping: {
required: boolean;
types?: ('tsa' | 'qualified_tsa' | 'blockchain')[];
};
deadline?: {
timestamp?: number;
relativeSeconds?: number;
};
customValidation?: {
ruleId: string;
params: Record<string, unknown>;
}[];
}
// ============================================================================
// SIGNATURE DEPENDENCIES
// ============================================================================
import type { TFieldDependencyType } from './types.js';
/**
* Defines dependencies between signature fields
*/
export interface ISignatureDependency {
type: TFieldDependencyType;
dependsOn: string[];
timeConstraint?: {
minSecondsAfter?: number;
maxSecondsAfter?: number;
};
}
// ============================================================================
// FACTORY FUNCTIONS
// ============================================================================
/**
* Create empty signature metadata
*/
export function createEmptySignatureMetadata(): ISignatureMetadata {
return {
timestamps: {
clientCaptured: Date.now(),
},
network: {
ipAddress: '',
userAgent: '',
},
};
}
/**
* Create default signature field requirements
*/
export function createDefaultSignatureFieldRequirements(): ISignatureFieldRequirements {
return {
required: true,
allowedSignatureTypes: ['drawn', 'typed', 'click'],
minimumLegalLevel: 'simple',
identityVerification: {
required: false,
},
timestamping: {
required: false,
},
};
}

405
ts_interfaces/terms.ts Normal file
View File

@@ -0,0 +1,405 @@
/**
* @file terms.ts
* @description Financial, time-based, and obligation terms interfaces
* Machine-readable structured terms for contracts
*/
import * as plugins from './plugins.js';
import type {
TPaymentFrequency,
TPaymentMethod,
TPaymentStatus,
TInterestType,
TPenaltyType,
TDurationUnit,
TRenewalType,
TNoticeEffectivePoint,
TNoticeForm,
TMilestoneStatus,
TObligationType,
TObligationStatus,
TObligationPriority,
TDeliverableStatus,
TInsuranceType,
} from './types.js';
// ============================================================================
// FINANCIAL TERMS INTERFACES
// ============================================================================
/**
* Monetary amount with currency
*/
export interface IMonetaryAmount {
amount: number;
currency: string;
includesTax: boolean;
taxRate?: number;
}
/**
* Payment schedule entry
*/
export interface IPaymentScheduleEntry {
paymentId: string;
description: string;
amount: IMonetaryAmount;
dueDate: number;
frequency: TPaymentFrequency;
numberOfPayments?: number;
isFinalPayment: boolean;
milestoneId?: string;
status: TPaymentStatus;
paidDate?: number;
}
/**
* Interest rate configuration
*/
export interface IInterestRate {
type: TInterestType;
baseRate: number;
spread?: number;
referenceRate?: string;
compoundingFrequency?: TPaymentFrequency;
maxRate?: number;
minRate?: number;
}
/**
* Penalty configuration
*/
export interface IPenalty {
id: string;
type: TPenaltyType;
description: string;
fixedAmount?: IMonetaryAmount;
percentage?: number;
percentageOf?: 'contract_value' | 'outstanding_amount' | 'monthly_value' | 'custom';
interestRate?: IInterestRate;
gracePeriod?: IDuration;
maximumPenalty?: IMonetaryAmount;
}
/**
* Billing rate for time-based contracts
*/
export interface IBillingRate {
id: string;
description: string;
type: 'hourly' | 'daily' | 'weekly' | 'monthly' | 'per_unit' | 'flat';
rate: IMonetaryAmount;
roleId?: string;
minimumUnit?: number;
}
/**
* Price adjustment provisions
*/
export interface IPriceAdjustment {
type: 'fixed_increase' | 'cpi_linked' | 'negotiated' | 'formula_based';
frequency: TPaymentFrequency;
fixedIncreasePercentage?: number;
linkedIndex?: string;
formula?: string;
maxIncrease?: number;
noticePeriod?: IDuration;
}
/**
* Comprehensive financial terms
*/
export interface IFinancialTerms {
totalValue?: IMonetaryAmount;
paymentSchedule: IPaymentScheduleEntry[];
paymentMethods: TPaymentMethod[];
paymentTerms?: string;
paymentDueDays?: number;
deposit?: IMonetaryAmount;
depositRefundable: boolean;
retainer?: IMonetaryAmount;
billingRates: IBillingRate[];
interestRates: {
latePayment?: IInterestRate;
financing?: IInterestRate;
};
penalties: IPenalty[];
priceAdjustment?: IPriceAdjustment;
paymentAccount?: plugins.tsclass.finance.ISepaConnection;
notes?: string;
}
// ============================================================================
// TIME-BASED TERMS INTERFACES
// ============================================================================
/**
* Duration specification
*/
export interface IDuration {
value: number;
unit: TDurationUnit;
}
/**
* Milestone definition
*/
export interface IMilestone {
milestoneId: string;
name: string;
description: string;
targetDate?: number;
completedDate?: number;
status: TMilestoneStatus;
dependsOn: string[];
paymentId?: string;
deliverables: string[];
acceptanceCriteria: string[];
}
/**
* Deadline definition
*/
export interface IDeadline {
id: string;
name: string;
description?: string;
date: number;
type: 'hard' | 'soft';
penalty?: IPenalty;
reminderDays: number[];
}
/**
* Key date for tracking
*/
export interface IKeyDate {
id: string;
name: string;
date: number;
type: 'anniversary' | 'review' | 'renewal_deadline' | 'price_adjustment' | 'custom';
notes?: string;
}
/**
* Notice period configuration
*/
export interface INoticePeriod {
duration: IDuration;
effectivePoint: TNoticeEffectivePoint;
form: TNoticeForm;
}
/**
* Renewal terms
*/
export interface IRenewalTerms {
type: TRenewalType;
renewalPeriod?: IDuration;
maxRenewals?: number;
currentRenewalCount: number;
nonRenewalNotice?: INoticePeriod;
renewalPriceAdjustment?: IPriceAdjustment;
conditions: string[];
}
/**
* Termination terms
*/
export interface ITerminationTerms {
noticePeriod: INoticePeriod;
immediateTerminationGrounds: string[];
terminationFee?: IMonetaryAmount;
postTerminationObligations: string[];
survivalClauses: string[];
}
/**
* Comprehensive time-based terms
*/
export interface ITimeTerms {
effectiveDate?: number;
executionDate?: number;
expirationDate?: number;
duration?: IDuration;
isIndefinite: boolean;
commencementConditions: string[];
milestones: IMilestone[];
deadlines: IDeadline[];
noticePeriods: {
termination?: INoticePeriod;
renewal?: INoticePeriod;
amendment?: INoticePeriod;
priceChange?: INoticePeriod;
};
renewal?: IRenewalTerms;
termination?: ITerminationTerms;
keyDates: IKeyDate[];
}
// ============================================================================
// OBLIGATION TERMS INTERFACES
// ============================================================================
/**
* Deliverable definition
*/
export interface IDeliverable {
deliverableId: string;
name: string;
description: string;
responsiblePartyId: string;
receivingPartyId?: string;
dueDate?: number;
milestoneId?: string;
acceptanceCriteria: string[];
quantity?: number;
unit?: string;
qualityStandards: string[];
deliveryMethod?: string;
status: TDeliverableStatus;
}
/**
* Service level definition
*/
export interface IServiceLevel {
slId: string;
metric: string;
description?: string;
target: number;
unit: string;
measurementPeriod: TPaymentFrequency;
minimumLevel?: number;
penalty?: IPenalty;
remedyCredit?: IMonetaryAmount;
exclusions: string[];
reporting?: {
frequency: TPaymentFrequency;
format?: string;
};
}
/**
* Quantity specification
*/
export interface IQuantitySpec {
minimum?: number;
maximum?: number;
target?: number;
unit: string;
period?: TPaymentFrequency;
}
/**
* General obligation
*/
export interface IObligation {
obligationId: string;
type: TObligationType;
description: string;
obligorPartyId: string;
beneficiaryPartyId?: string;
dueDate?: number;
recurring: boolean;
frequency?: TPaymentFrequency;
duration?: IDuration;
priority: TObligationPriority;
clauseId?: string;
status: TObligationStatus;
}
/**
* Warranty definition
*/
export interface IWarranty {
id: string;
description: string;
duration?: IDuration;
scope?: string;
limitations: string[];
remedies: string[];
}
/**
* Representation definition
*/
export interface IRepresentation {
id: string;
partyId: string;
statement: string;
asOfDate: 'signing' | 'effective_date' | 'ongoing';
}
/**
* Insurance requirement
*/
export interface IInsuranceRequirement {
id: string;
type: TInsuranceType;
minimumCoverage: IMonetaryAmount;
description?: string;
requireCertificate: boolean;
}
/**
* Comprehensive obligation terms
*/
export interface IObligationTerms {
deliverables: IDeliverable[];
serviceLevels: IServiceLevel[];
quantities: IQuantitySpec[];
obligations: IObligation[];
warranties: IWarranty[];
representations: IRepresentation[];
insuranceRequirements: IInsuranceRequirement[];
complianceRequirements: string[];
}
// ============================================================================
// FACTORY FUNCTIONS FOR EMPTY STRUCTURES
// ============================================================================
/**
* Create empty financial terms
*/
export function createEmptyFinancialTerms(): IFinancialTerms {
return {
paymentSchedule: [],
paymentMethods: [],
depositRefundable: false,
billingRates: [],
interestRates: {},
penalties: [],
};
}
/**
* Create empty time terms
*/
export function createEmptyTimeTerms(): ITimeTerms {
return {
isIndefinite: false,
commencementConditions: [],
milestones: [],
deadlines: [],
noticePeriods: {},
keyDates: [],
};
}
/**
* Create empty obligation terms
*/
export function createEmptyObligationTerms(): IObligationTerms {
return {
deliverables: [],
serviceLevels: [],
quantities: [],
obligations: [],
warranties: [],
representations: [],
insuranceRequirements: [],
complianceRequirements: [],
};
}

View File

@@ -1,5 +1,8 @@
{
"name": "@signature.digital/interfaces",
"order": 1,
"registries": ["useBase"]
"registries": ["useBase"],
"dependencies": [
"@tsclass/tsclass"
]
}

912
ts_interfaces/types.ts Normal file
View File

@@ -0,0 +1,912 @@
/**
* @file types.ts
* @description Foundation type aliases for signature.digital contract system
* All type aliases use T prefix as per project conventions
*/
// ============================================================================
// CONTRACT CLASSIFICATION
// ============================================================================
/**
* Broad categories of contracts for classification and routing
*/
export type TContractCategory =
| 'employment'
| 'service'
| 'sales'
| 'lease'
| 'license'
| 'partnership'
| 'confidentiality'
| 'financial'
| 'real_estate'
| 'intellectual_property'
| 'government'
| 'construction'
| 'healthcare'
| 'insurance'
| 'other';
/**
* Specific contract types within categories - extensible via string literal union
*/
export type TContractType =
// Employment
| 'employment_full_time'
| 'employment_part_time'
| 'employment_minijob'
| 'employment_internship'
| 'employment_freelance'
| 'employment_consulting'
| 'employment_executive'
| 'employment_temporary'
| 'employment_apprenticeship'
// Service
| 'service_agreement'
| 'service_level_agreement'
| 'master_service_agreement'
| 'maintenance_agreement'
| 'support_agreement'
| 'managed_services'
// Sales
| 'sales_agreement'
| 'purchase_order'
| 'distribution_agreement'
| 'supply_agreement'
| 'consignment_agreement'
// Lease/Rental
| 'lease_residential'
| 'lease_commercial'
| 'lease_equipment'
| 'lease_vehicle'
| 'sublease'
// License
| 'software_license'
| 'patent_license'
| 'trademark_license'
| 'franchise_agreement'
| 'content_license'
// Partnership
| 'partnership_general'
| 'partnership_limited'
| 'joint_venture'
| 'strategic_alliance'
| 'consortium_agreement'
// Confidentiality
| 'nda_unilateral'
| 'nda_bilateral'
| 'nda_multilateral'
| 'non_compete'
| 'non_solicitation'
// Financial
| 'loan_agreement'
| 'credit_facility'
| 'guarantee'
| 'security_agreement'
| 'investment_agreement'
| 'shareholder_agreement'
// Other
| 'settlement_agreement'
| 'release_waiver'
| 'power_of_attorney'
| 'memorandum_of_understanding'
| 'letter_of_intent'
| string; // Allow custom types
// ============================================================================
// CONTRACT LIFECYCLE STATUS
// ============================================================================
/**
* Contract lifecycle status - complete workflow states
*/
export type TContractStatus =
// Draft phase
| 'draft'
| 'internal_review'
| 'legal_review'
// Negotiation phase
| 'negotiation'
| 'pending_approval'
// Signature phase
| 'pending_signature'
| 'partially_signed'
| 'signed'
// Active phase
| 'executed'
| 'active'
| 'suspended'
| 'renewal_pending'
// End phase
| 'expired'
| 'terminated'
| 'superseded'
| 'cancelled'
| 'voided';
// ============================================================================
// PARTY AND ROLE TYPES
// ============================================================================
/**
* Role types in contract signing workflow
*/
export type TPartyRole =
| 'signer'
| 'witness'
| 'notary'
| 'cc'
| 'approver'
| 'guarantor'
| 'beneficiary';
/**
* Signing dependency types
*/
export type TSigningDependency =
| 'none'
| 'sequential'
| 'parallel'
| 'after_specific';
/**
* Legal capacity when signing
*/
export type TLegalCapacity =
| 'individual'
| 'representative'
| 'attorney'
| 'guardian';
// ============================================================================
// SIGNATURE TYPES
// ============================================================================
/**
* All supported signature input methods
*/
export type TSignatureType =
| 'drawn'
| 'typed'
| 'click'
| 'digital'
| 'qualified'
| 'biometric';
/**
* Signature legal level based on eIDAS regulation
*/
export type TSignatureLegalLevel =
| 'simple'
| 'advanced'
| 'qualified';
/**
* Signature lifecycle status
*/
export type TSignatureStatus =
| 'pending'
| 'captured'
| 'verified'
| 'timestamped'
| 'complete'
| 'revoked'
| 'expired';
// ============================================================================
// IDENTITY VERIFICATION TYPES
// ============================================================================
/**
* Supported identity verification methods
*/
export type TIdentityVerificationMethod =
| 'none'
| 'email'
| 'sms'
| 'knowledge'
| 'document_upload'
| 'document_nfc'
| 'document_ocr'
| 'biometric_facial'
| 'video_ident'
| 'bankid'
| 'eid'
| 'third_party_idp';
/**
* Verification confidence levels
*/
export type TVerificationConfidence =
| 'none'
| 'low'
| 'medium'
| 'high'
| 'verified';
/**
* Identity verification status
*/
export type TIdentityVerificationStatus =
| 'pending'
| 'in_progress'
| 'manual_review'
| 'verified'
| 'failed'
| 'expired'
| 'cancelled';
/**
* Identity document types
*/
export type TIdentityDocumentType =
| 'passport'
| 'national_id'
| 'drivers_license'
| 'residence_permit'
| 'travel_document'
| 'other';
// ============================================================================
// FINANCIAL TYPES
// ============================================================================
/**
* Payment frequency for recurring payments
*/
export type TPaymentFrequency =
| 'one_time'
| 'daily'
| 'weekly'
| 'bi_weekly'
| 'semi_monthly'
| 'monthly'
| 'bi_monthly'
| 'quarterly'
| 'semi_annually'
| 'annually'
| 'on_demand'
| 'upon_completion'
| 'milestone_based'
| 'custom';
/**
* Payment method types
*/
export type TPaymentMethod =
| 'bank_transfer'
| 'sepa_direct_debit'
| 'credit_card'
| 'check'
| 'cash'
| 'paypal'
| 'crypto'
| 'escrow'
| 'letter_of_credit'
| 'other';
/**
* Interest calculation methods
*/
export type TInterestType =
| 'simple'
| 'compound'
| 'fixed'
| 'variable'
| 'prime_plus'
| 'reference_plus'
| 'none';
/**
* Payment status
*/
export type TPaymentStatus =
| 'pending'
| 'invoiced'
| 'paid'
| 'overdue'
| 'waived'
| 'refunded';
/**
* Penalty types
*/
export type TPenaltyType =
| 'late_payment'
| 'early_termination'
| 'breach'
| 'non_performance'
| 'custom';
// ============================================================================
// TIME AND DURATION TYPES
// ============================================================================
/**
* Duration unit for time periods
*/
export type TDurationUnit =
| 'hours'
| 'days'
| 'weeks'
| 'months'
| 'years'
| 'indefinite';
/**
* Renewal types
*/
export type TRenewalType =
| 'none'
| 'manual'
| 'auto_renew'
| 'evergreen'
| 'option_to_renew';
/**
* Notice effective point
*/
export type TNoticeEffectivePoint =
| 'immediate'
| 'end_of_week'
| 'end_of_month'
| 'end_of_quarter'
| 'end_of_year'
| 'anytime';
/**
* Notice form requirements
*/
export type TNoticeForm =
| 'written'
| 'email'
| 'registered_mail'
| 'any';
/**
* Milestone status
*/
export type TMilestoneStatus =
| 'pending'
| 'in_progress'
| 'completed'
| 'delayed'
| 'cancelled';
/**
* Termination reason taxonomy
*/
export type TTerminationReason =
| 'breach_of_contract'
| 'mutual_agreement'
| 'convenience'
| 'non_performance'
| 'insolvency'
| 'force_majeure'
| 'regulatory_change'
| 'merger_acquisition'
| 'other';
// ============================================================================
// CONTENT AND SECTION TYPES
// ============================================================================
/**
* Section types for contract structure
*/
export type TSectionType =
| 'preamble'
| 'definitions'
| 'clause'
| 'subclause'
| 'schedule'
| 'exhibit'
| 'annex'
| 'amendment'
| 'signature_block'
| 'witness_block'
| 'acknowledgment'
| 'recital'
| 'custom';
/**
* Variable/placeholder types for dynamic content
*/
export type TVariableType =
| 'text'
| 'number'
| 'currency'
| 'date'
| 'duration'
| 'percentage'
| 'party_name'
| 'party_address'
| 'party_contact'
| 'calculated'
| 'selection'
| 'custom';
/**
* Condition operators for conditional sections
*/
export type TConditionOperator =
| 'equals'
| 'not_equals'
| 'contains'
| 'not_contains'
| 'greater_than'
| 'less_than'
| 'in_list'
| 'not_in_list'
| 'is_empty'
| 'is_not_empty'
| 'party_has_role'
| 'contract_type_is';
/**
* Logical combination for conditions
*/
export type TConditionCombine = 'and' | 'or';
// ============================================================================
// VERSIONING TYPES
// ============================================================================
/**
* Version type
*/
export type TVersionType = 'draft' | 'final' | 'amendment';
/**
* Change operation types for diff tracking
*/
export type TChangeOperation =
| 'insert'
| 'delete'
| 'modify'
| 'move'
| 'format'
| 'merge';
/**
* Branch status
*/
export type TBranchStatus = 'active' | 'merged' | 'abandoned';
// ============================================================================
// COLLABORATION TYPES
// ============================================================================
/**
* User presence status
*/
export type TPresenceStatus =
| 'viewing'
| 'editing'
| 'commenting'
| 'idle'
| 'offline';
/**
* Comment thread status
*/
export type TCommentThreadStatus = 'open' | 'resolved' | 'archived';
/**
* Suggestion status
*/
export type TSuggestionStatus = 'pending' | 'accepted' | 'rejected' | 'superseded';
/**
* Suggestion change type
*/
export type TSuggestionChangeType = 'insert' | 'delete' | 'replace' | 'format';
/**
* Conflict resolution strategy
*/
export type TConflictResolutionStrategy = 'accept_first' | 'accept_last' | 'manual_merge';
/**
* Editing mode
*/
export type TEditingMode = 'collaborative' | 'suggestion_only' | 'view_only';
/**
* Permission level for collaboration
*/
export type TCollaborationPermission =
| 'owner'
| 'admin'
| 'editor'
| 'suggester'
| 'commenter'
| 'viewer';
// ============================================================================
// AUDIT TYPES
// ============================================================================
/**
* Action categories for filtering and reporting
*/
export type TActionCategory =
// Document lifecycle
| 'create'
| 'view'
| 'edit'
| 'status_change'
| 'version_create'
| 'version_rollback'
// Collaboration
| 'share'
| 'permission_change'
| 'comment'
| 'suggestion'
// Signature
| 'signature_request'
| 'signature_given'
| 'signature_declined'
| 'signature_revoked'
// Export/Import
| 'export'
| 'print'
| 'download'
// Administrative
| 'archive'
| 'restore'
| 'delete'
| 'retention_policy_applied';
/**
* Action severity levels
*/
export type TActionSeverity = 'info' | 'warning' | 'critical';
/**
* Signature audit action types
*/
export type TSignatureAuditAction =
| 'signature_requested'
| 'document_viewed'
| 'signature_captured'
| 'identity_verification_started'
| 'identity_verification_completed'
| 'identity_verification_failed'
| 'timestamp_requested'
| 'timestamp_received'
| 'signature_validated'
| 'signature_revoked'
| 'certificate_expired';
/**
* Compliance action types
*/
export type TComplianceAction =
| 'proof_created'
| 'tsa_timestamp_requested'
| 'tsa_timestamp_received'
| 'blockchain_anchor_requested'
| 'blockchain_anchor_confirmed'
| 'validation_performed'
| 'ltv_data_collected'
| 'archive_timestamp_added';
// ============================================================================
// ATTACHMENT TYPES
// ============================================================================
/**
* Attachment type classification
*/
export type TAttachmentType =
| 'exhibit'
| 'schedule'
| 'appendix'
| 'amendment'
| 'side_letter'
| 'certificate'
| 'evidence';
/**
* Attachment category for organization
*/
export type TAttachmentCategory =
// Legal documents
| 'legal_entity_docs'
| 'authorization'
| 'insurance'
| 'compliance'
// Identity documents
| 'identity'
| 'address_proof'
// Technical documents
| 'specifications'
| 'diagrams'
| 'data_schemas'
// Financial documents
| 'financial_statements'
| 'pricing'
| 'payment_terms'
// Other
| 'correspondence'
| 'other';
/**
* Prior contract relationship types
*/
export type TPriorContractRelationship =
| 'supersedes'
| 'amends'
| 'extends'
| 'references'
| 'depends_on'
| 'conflicts_with';
/**
* Confidentiality levels
*/
export type TConfidentialityLevel =
| 'public'
| 'internal'
| 'confidential'
| 'restricted';
// ============================================================================
// LEGAL COMPLIANCE TYPES
// ============================================================================
/**
* Timestamping methods
*/
export type TTimestampMethod =
| 'tsa'
| 'blockchain'
| 'qualified_tsa';
/**
* Supported blockchain networks for timestamping
*/
export type TBlockchainNetwork =
| 'bitcoin'
| 'ethereum'
| 'polygon'
| 'arbitrum'
| 'optimism'
| 'hyperledger'
| 'private';
/**
* Hash algorithms
*/
export type THashAlgorithm =
| 'SHA-256'
| 'SHA-384'
| 'SHA-512'
| 'Keccak-256';
/**
* Signature algorithm types
*/
export type TSignatureAlgorithm =
| 'RSA-SHA256'
| 'RSA-SHA384'
| 'RSA-SHA512'
| 'ECDSA-P256'
| 'ECDSA-P384'
| 'Ed25519';
/**
* Qualification status for eIDAS
*/
export type TQualificationStatus = 'qualified' | 'withdrawn' | 'unknown';
/**
* Validation status
*/
export type TValidationStatus = 'valid' | 'invalid' | 'indeterminate' | 'expired';
// ============================================================================
// PDF GENERATION TYPES
// ============================================================================
/**
* Page size presets
*/
export type TPageSize = 'A4' | 'Letter' | 'Legal' | 'custom';
/**
* Page orientation
*/
export type TPageOrientation = 'portrait' | 'landscape';
/**
* Header/footer content types
*/
export type THeaderFooterContentType =
| 'text'
| 'image'
| 'page_number'
| 'date'
| 'custom';
/**
* Page number format
*/
export type TPageNumberFormat = 'numeric' | 'roman' | 'alpha';
/**
* PDF encryption algorithm
*/
export type TPdfEncryptionAlgorithm = 'AES-128' | 'AES-256';
/**
* PDF printing permission level
*/
export type TPdfPrintingPermission = 'none' | 'low_resolution' | 'high_resolution';
/**
* PDF generation job status
*/
export type TPdfJobStatus = 'queued' | 'processing' | 'completed' | 'failed';
// ============================================================================
// OBLIGATION TYPES
// ============================================================================
/**
* Obligation types
*/
export type TObligationType =
| 'performance'
| 'payment'
| 'delivery'
| 'confidentiality'
| 'compliance'
| 'reporting'
| 'insurance'
| 'indemnification'
| 'custom';
/**
* Obligation status
*/
export type TObligationStatus =
| 'pending'
| 'active'
| 'completed'
| 'breached'
| 'waived';
/**
* Obligation priority
*/
export type TObligationPriority = 'critical' | 'high' | 'medium' | 'low';
/**
* Deliverable status
*/
export type TDeliverableStatus =
| 'pending'
| 'in_progress'
| 'delivered'
| 'accepted'
| 'rejected'
| 'revised';
/**
* Insurance requirement types
*/
export type TInsuranceType =
| 'general_liability'
| 'professional_liability'
| 'workers_comp'
| 'property'
| 'auto'
| 'cyber'
| 'other';
// ============================================================================
// WORKFLOW TYPES
// ============================================================================
/**
* Workflow types for signing
*/
export type TWorkflowType =
| 'sequential'
| 'parallel'
| 'hybrid'
| 'custom';
/**
* Workflow status
*/
export type TWorkflowStatus =
| 'draft'
| 'active'
| 'completed'
| 'expired'
| 'cancelled'
| 'voided';
/**
* Workflow events
*/
export type TWorkflowEvent =
| 'workflow_started'
| 'signature_completed'
| 'signature_declined'
| 'workflow_completed'
| 'deadline_approaching'
| 'deadline_expired'
| 'all_signatures_complete';
// ============================================================================
// SIGNATURE FIELD TYPES
// ============================================================================
/**
* Signature field status
*/
export type TSignatureFieldStatus =
| 'pending'
| 'ready'
| 'in_progress'
| 'completed'
| 'declined'
| 'expired'
| 'voided';
/**
* Signature field placement types
*/
export type TPlacementType =
| 'paragraph'
| 'page'
| 'anchor'
| 'append';
/**
* Signing dependency types for fields
*/
export type TFieldDependencyType =
| 'sequential'
| 'parallel'
| 'any'
| 'witness';
/**
* Invitation status
*/
export type TInvitationStatus =
| 'not_sent'
| 'sent'
| 'delivered'
| 'opened'
| 'bounced';
// ============================================================================
// LEGAL REFERENCE TYPES
// ============================================================================
/**
* Legal reference types
*/
export type TLegalReferenceType =
| 'statute'
| 'regulation'
| 'case_law'
| 'internal_clause'
| 'standard'
| 'definition';
/**
* Dispute resolution methods
*/
export type TDisputeResolution =
| 'litigation'
| 'arbitration'
| 'mediation'
| 'negotiation';

268
ts_interfaces/versioning.ts Normal file
View File

@@ -0,0 +1,268 @@
/**
* @file versioning.ts
* @description Version management interfaces
* Semantic versioning, change tracking, branches, and diff comparison
*/
import type {
TVersionType,
TChangeOperation,
TBranchStatus,
} from './types.js';
// ============================================================================
// SEMANTIC VERSION
// ============================================================================
/**
* Semantic version following major.minor.patch pattern
* For contracts: major = substantial changes, minor = clause additions, patch = wording fixes
*/
export interface ISemanticVersion {
major: number;
minor: number;
patch: number;
label?: 'alpha' | 'beta' | 'rc' | 'final';
}
/**
* Version string type
*/
export type TVersionString = `${number}.${number}.${number}` | `${number}.${number}.${number}-${string}`;
// ============================================================================
// VERSION CHANGES
// ============================================================================
/**
* Represents a single atomic change within a version
*/
export interface IVersionChange {
id: string;
operation: TChangeOperation;
targetPath: string;
targetParagraphId?: string;
previousValue?: string | object;
newValue?: string | object;
characterRange?: {
start: number;
end: number;
};
timestamp: number;
userId: string;
userDisplayName?: string;
changeReason?: string;
}
// ============================================================================
// AMENDMENT
// ============================================================================
/**
* Amendment-specific information
*/
export interface IAmendmentDetails {
amendmentNumber: number;
amendmentType: 'modification' | 'addendum' | 'rider' | 'waiver' | 'extension';
effectiveDate: number;
supersedes: string[];
requiresResigning: boolean;
affectedSections: string[];
}
// ============================================================================
// VERSION
// ============================================================================
/**
* A complete version snapshot
*/
export interface IVersion {
id: string;
version: ISemanticVersion;
versionString: TVersionString;
type: TVersionType;
createdAt: number;
createdBy: string;
createdByDisplayName?: string;
previousVersionId?: string;
changes: IVersionChange[];
contentHash: string;
parentHash?: string;
title?: string;
description?: string;
tags: string[];
isAmendment: boolean;
amendmentDetails?: IAmendmentDetails;
}
// ============================================================================
// VERSION BRANCH
// ============================================================================
/**
* Branch for parallel version development
*/
export interface IVersionBranch {
id: string;
name: string;
description?: string;
createdAt: number;
createdBy: string;
baseVersionId: string;
headVersionId: string;
status: TBranchStatus;
mergedIntoVersionId?: string;
}
// ============================================================================
// VERSION HISTORY
// ============================================================================
/**
* Complete version history for a contract
*/
export interface IVersionHistory {
contractId: string;
currentVersionId: string;
currentVersion: ISemanticVersion;
versions: IVersion[];
branches: IVersionBranch[];
mainBranchId: string;
publishedVersions: string[];
amendmentVersions: string[];
}
// ============================================================================
// VERSION DIFF
// ============================================================================
/**
* Diff summary statistics
*/
export interface IDiffSummary {
insertions: number;
deletions: number;
modifications: number;
paragraphsAffected: string[];
}
/**
* Version comparison result
*/
export interface IVersionDiff {
fromVersionId: string;
toVersionId: string;
fromVersion: ISemanticVersion;
toVersion: ISemanticVersion;
changes: IVersionChange[];
summary: IDiffSummary;
}
// ============================================================================
// ROLLBACK
// ============================================================================
/**
* Rollback request
*/
export interface IRollbackRequest {
targetVersionId: string;
reason: string;
requestedBy: string;
requestedAt: number;
createNewVersion: boolean;
}
// ============================================================================
// FACTORY FUNCTIONS
// ============================================================================
/**
* Create initial version
*/
export function createInitialVersion(userId: string, userDisplayName?: string): IVersion {
const now = Date.now();
return {
id: crypto.randomUUID(),
version: { major: 0, minor: 1, patch: 0 },
versionString: '0.1.0',
type: 'draft',
createdAt: now,
createdBy: userId,
createdByDisplayName: userDisplayName,
changes: [],
contentHash: '',
tags: [],
isAmendment: false,
};
}
/**
* Create empty version history
*/
export function createEmptyVersionHistory(contractId: string, initialVersion: IVersion): IVersionHistory {
const mainBranchId = crypto.randomUUID();
return {
contractId,
currentVersionId: initialVersion.id,
currentVersion: initialVersion.version,
versions: [initialVersion],
branches: [
{
id: mainBranchId,
name: 'main',
createdAt: initialVersion.createdAt,
createdBy: initialVersion.createdBy,
baseVersionId: initialVersion.id,
headVersionId: initialVersion.id,
status: 'active',
},
],
mainBranchId,
publishedVersions: [],
amendmentVersions: [],
};
}
/**
* Increment semantic version
*/
export function incrementVersion(
current: ISemanticVersion,
incrementType: 'major' | 'minor' | 'patch'
): ISemanticVersion {
switch (incrementType) {
case 'major':
return { major: current.major + 1, minor: 0, patch: 0 };
case 'minor':
return { major: current.major, minor: current.minor + 1, patch: 0 };
case 'patch':
return { major: current.major, minor: current.minor, patch: current.patch + 1 };
}
}
/**
* Convert semantic version to string
*/
export function versionToString(version: ISemanticVersion): TVersionString {
const base = `${version.major}.${version.minor}.${version.patch}` as TVersionString;
if (version.label && version.label !== 'final') {
return `${base}-${version.label}` as TVersionString;
}
return base;
}
/**
* Parse version string to semantic version
*/
export function parseVersionString(versionString: string): ISemanticVersion {
const [base, label] = versionString.split('-');
const [major, minor, patch] = base.split('.').map(Number);
return {
major: major || 0,
minor: minor || 0,
patch: patch || 0,
label: label as ISemanticVersion['label'],
};
}