@timesheet/sdk 1.0.2 → 1.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -38,6 +38,63 @@ declare class OAuth2Auth implements Authentication {
38
38
  private parseTokenExpiry;
39
39
  }
40
40
 
41
+ type CodeChallengeMethod = 'S256' | 'plain';
42
+ interface PkceCodePair {
43
+ codeVerifier: string;
44
+ codeChallenge: string;
45
+ codeChallengeMethod: CodeChallengeMethod;
46
+ }
47
+ declare function generateCodeVerifier(length?: number): string;
48
+ declare function generateCodeChallenge(codeVerifier: string, method?: CodeChallengeMethod): string;
49
+ declare function generatePkceCodePair(method?: CodeChallengeMethod, verifierLength?: number): PkceCodePair;
50
+ declare function isValidCodeVerifier(codeVerifier: string): boolean;
51
+
52
+ interface AuthorizationUrlOptions {
53
+ clientId: string;
54
+ redirectUri: string;
55
+ codeChallenge: string;
56
+ codeChallengeMethod?: CodeChallengeMethod;
57
+ state?: string;
58
+ scope?: string;
59
+ resource?: string;
60
+ }
61
+ interface TokenExchangeOptions {
62
+ clientId: string;
63
+ clientSecret?: string;
64
+ authorizationCode: string;
65
+ redirectUri: string;
66
+ codeVerifier: string;
67
+ resource?: string;
68
+ }
69
+ interface OAuth21RefreshOptions {
70
+ clientId: string;
71
+ clientSecret?: string;
72
+ refreshToken: string;
73
+ resource?: string;
74
+ }
75
+ declare class OAuth21Auth implements Authentication {
76
+ private static readonly TOKEN_ENDPOINT;
77
+ private static readonly AUTH_ENDPOINT;
78
+ private accessToken;
79
+ private refreshToken?;
80
+ private readonly clientId?;
81
+ private readonly clientSecret?;
82
+ private readonly resource?;
83
+ private tokenExpiry?;
84
+ private refreshPromise?;
85
+ constructor(accessToken: string);
86
+ constructor(options: OAuth21RefreshOptions);
87
+ applyAuth(config: AxiosRequestConfig): void;
88
+ needsRefresh(): boolean;
89
+ refresh(): Promise<void>;
90
+ private performRefresh;
91
+ getAuthHeaders(): Promise<Record<string, string>>;
92
+ static fromAuthorizationCode(options: TokenExchangeOptions): Promise<OAuth21Auth>;
93
+ static buildAuthorizationUrl(options: AuthorizationUrlOptions): string;
94
+ static generatePkce(method?: CodeChallengeMethod): PkceCodePair;
95
+ private parseTokenExpiry;
96
+ }
97
+
41
98
  declare class RetryConfig {
42
99
  readonly maxRetries: number;
43
100
  readonly initialDelay: number;
@@ -1016,6 +1073,26 @@ interface DocumentListParams extends ListParams {
1016
1073
  empty?: boolean;
1017
1074
  }
1018
1075
 
1076
+ type WebhookEventType = 'team.create' | 'team.update' | 'project.create' | 'project.update' | 'todo.create' | 'todo.update' | 'task.create' | 'task.update' | 'tag.create' | 'tag.update' | 'rate.create' | 'rate.update' | 'timer.start' | 'timer.stop' | 'timer.pause' | 'timer.resume';
1077
+ declare const WebhookEvents: {
1078
+ readonly TEAM_CREATE: "team.create";
1079
+ readonly TEAM_UPDATE: "team.update";
1080
+ readonly PROJECT_CREATE: "project.create";
1081
+ readonly PROJECT_UPDATE: "project.update";
1082
+ readonly TODO_CREATE: "todo.create";
1083
+ readonly TODO_UPDATE: "todo.update";
1084
+ readonly TASK_CREATE: "task.create";
1085
+ readonly TASK_UPDATE: "task.update";
1086
+ readonly TAG_CREATE: "tag.create";
1087
+ readonly TAG_UPDATE: "tag.update";
1088
+ readonly RATE_CREATE: "rate.create";
1089
+ readonly RATE_UPDATE: "rate.update";
1090
+ readonly TIMER_START: "timer.start";
1091
+ readonly TIMER_STOP: "timer.stop";
1092
+ readonly TIMER_PAUSE: "timer.pause";
1093
+ readonly TIMER_RESUME: "timer.resume";
1094
+ };
1095
+ declare function combineWebhookEvents(...events: WebhookEventType[]): string;
1019
1096
  interface Webhook {
1020
1097
  id: string;
1021
1098
  target: string;
@@ -1163,6 +1240,332 @@ interface ProfileUpdateRequest {
1163
1240
  newsletter?: boolean;
1164
1241
  }
1165
1242
 
1243
+ interface TaskReportItem {
1244
+ taskDate?: string;
1245
+ taskStartTime?: string;
1246
+ taskEndTime?: string;
1247
+ taskTimeRange?: string;
1248
+ taskDuration?: string;
1249
+ taskDurationRelative?: string;
1250
+ pauseDuration?: string;
1251
+ taskDescription?: string;
1252
+ taskId?: string;
1253
+ userId?: string;
1254
+ invoiceId?: string;
1255
+ startDateTimeRaw?: string;
1256
+ endDateTimeRaw?: string;
1257
+ durationSeconds?: number;
1258
+ durationBreakSeconds?: number;
1259
+ taskLocation?: string;
1260
+ taskLocationStart?: string;
1261
+ taskLocationEnd?: string;
1262
+ taskDistance?: string;
1263
+ taskRateName?: string;
1264
+ taskRate?: string;
1265
+ taskTotal?: string;
1266
+ taskTotalRelative?: string;
1267
+ projectName?: string;
1268
+ projectClient?: string;
1269
+ projectColor?: string;
1270
+ memberName?: string;
1271
+ taskTags?: string;
1272
+ taskSignature?: string;
1273
+ quantityHours?: number;
1274
+ unitPriceNumeric?: number;
1275
+ lineTotalNumeric?: number;
1276
+ salaryTotalNumeric?: number;
1277
+ salaryBreakNumeric?: number;
1278
+ projectId?: string;
1279
+ memberId?: string;
1280
+ billable?: boolean;
1281
+ paid?: boolean;
1282
+ expenses?: ExpenseReportItem[];
1283
+ notes?: NoteReportItem[];
1284
+ }
1285
+ interface ExpenseReportItem {
1286
+ expenseDate?: string;
1287
+ expenseTime?: string;
1288
+ expenseAmount?: string;
1289
+ expenseDescription?: string;
1290
+ expenseDescriptionRaw?: string;
1291
+ expenseDateTimeRaw?: string;
1292
+ expenseId?: string;
1293
+ expenseUserId?: string;
1294
+ attachmentBase64?: string;
1295
+ expenseAuthor?: string;
1296
+ amountNumeric?: number;
1297
+ }
1298
+ interface NoteReportItem {
1299
+ noteDate?: string;
1300
+ noteContent?: string;
1301
+ attachmentBase64?: string;
1302
+ noteType?: string;
1303
+ noteAuthor?: string;
1304
+ }
1305
+ interface DocumentReport {
1306
+ documentTitle?: string;
1307
+ documentDate?: string;
1308
+ invoiceNumber?: string;
1309
+ customerNumber?: string;
1310
+ paymentDate?: string;
1311
+ paymentMethod?: string;
1312
+ companyName?: string;
1313
+ companyAddress1?: string;
1314
+ companyAddress2?: string;
1315
+ companyAddress3?: string;
1316
+ companyAddress4?: string;
1317
+ companyLogo?: string;
1318
+ customerName?: string;
1319
+ customerAddress1?: string;
1320
+ customerAddress2?: string;
1321
+ customerAddress3?: string;
1322
+ customerAddress4?: string;
1323
+ taskSubtotal?: string;
1324
+ expenseSubtotal?: string;
1325
+ subtotalAmount?: string;
1326
+ taxRate?: number;
1327
+ taxAmount?: string;
1328
+ taxSecondRate?: number;
1329
+ taxSecondAmount?: string;
1330
+ discountRate?: number;
1331
+ discountAmount?: string;
1332
+ discountSecondRate?: number;
1333
+ discountSecondAmount?: string;
1334
+ totalAmount?: string;
1335
+ totalDuration?: string;
1336
+ paymentAmount?: string;
1337
+ eInvoiceType?: string;
1338
+ companyVatId?: string;
1339
+ companyTaxNumber?: string;
1340
+ companyRegistrationNumber?: string;
1341
+ companyBankAccount?: string;
1342
+ companyBankBIC?: string;
1343
+ eInvoiceCurrency?: string;
1344
+ deliveryDate?: string;
1345
+ dueDate?: string;
1346
+ paymentReference?: string;
1347
+ orderReference?: string;
1348
+ taxExemptionReason?: string;
1349
+ reverseChargeRate?: number;
1350
+ isReverseCharge?: boolean;
1351
+ eInvoiceDocumentType?: string;
1352
+ invoiceTypeCode?: string;
1353
+ customerVatId?: string;
1354
+ customerTaxNumber?: string;
1355
+ customerOrderNumber?: string;
1356
+ paymentTermDays?: number;
1357
+ cashDiscountRate?: number;
1358
+ cashDiscountDays?: number;
1359
+ originalInvoiceNumber?: string;
1360
+ originalInvoiceDate?: string;
1361
+ projectReference?: string;
1362
+ costCenter?: string;
1363
+ isGovernmentInvoice?: boolean;
1364
+ procurementReference?: string;
1365
+ contractReference?: string;
1366
+ eInvoicingEnabled?: boolean;
1367
+ documentDescription?: string;
1368
+ documentTerms?: string;
1369
+ documentSignature?: string;
1370
+ showTaskTime?: boolean;
1371
+ showRates?: boolean;
1372
+ showTaxes?: boolean;
1373
+ showSecondTax?: boolean;
1374
+ showDiscount?: boolean;
1375
+ showSecondDiscount?: boolean;
1376
+ includeExpenses?: boolean;
1377
+ includeNotes?: boolean;
1378
+ showProjectTitle?: boolean;
1379
+ showMemberName?: boolean;
1380
+ showTags?: boolean;
1381
+ showQrCode?: boolean;
1382
+ qrCodeType?: string;
1383
+ qrCodeContent?: string;
1384
+ qrCodeDescription?: string;
1385
+ hideExpenseDateTime?: boolean;
1386
+ hideSummation?: boolean;
1387
+ useRelatives?: boolean;
1388
+ tasks?: TaskReportItem[];
1389
+ expenses?: ExpenseReportItem[];
1390
+ notes?: NoteReportItem[];
1391
+ labelDescription?: string;
1392
+ labelRate?: string;
1393
+ labelQuantity?: string;
1394
+ labelTotal?: string;
1395
+ labelTotalSum?: string;
1396
+ labelSubtotal?: string;
1397
+ labelTax?: string;
1398
+ labelSecondTax?: string;
1399
+ labelDiscount?: string;
1400
+ labelSecondDiscount?: string;
1401
+ labelExpenseTitle?: string;
1402
+ labelExpenseTotal?: string;
1403
+ templateId?: string;
1404
+ reportType?: string;
1405
+ language?: string;
1406
+ currency?: string;
1407
+ currencyCode?: string;
1408
+ }
1409
+ interface ExportedField {
1410
+ id: string;
1411
+ name?: string;
1412
+ position?: number;
1413
+ projectField?: boolean;
1414
+ teamField?: boolean;
1415
+ customField?: boolean;
1416
+ customValue?: string;
1417
+ customFormula?: string;
1418
+ customType?: string;
1419
+ }
1420
+ interface ExportParams {
1421
+ report: number;
1422
+ email?: string;
1423
+ filename?: string;
1424
+ teamIds?: string[];
1425
+ projectIds?: string[];
1426
+ userIds?: string[];
1427
+ tagIds?: string[];
1428
+ type?: string;
1429
+ startDate: string;
1430
+ endDate: string;
1431
+ format?: ExportFormat;
1432
+ filter?: string;
1433
+ splitTask?: boolean;
1434
+ summarize?: boolean;
1435
+ saveAsTemplate?: boolean;
1436
+ templateName?: string;
1437
+ exportedFields?: ExportedField[];
1438
+ }
1439
+ type ExportFormat = 'xlsx' | 'xlsx1904' | 'csv' | 'pdf';
1440
+ interface ExportTemplateParams {
1441
+ templateId: string;
1442
+ startDate: string;
1443
+ endDate: string;
1444
+ }
1445
+ interface FileResponse {
1446
+ url: string;
1447
+ filename?: string;
1448
+ contentType?: string;
1449
+ }
1450
+ interface ExportTemplate {
1451
+ id: string;
1452
+ user?: string;
1453
+ deleted?: boolean;
1454
+ lastUpdate?: number;
1455
+ created?: number;
1456
+ name: string;
1457
+ report: number;
1458
+ teamIds?: string[];
1459
+ projectIds?: string[];
1460
+ userIds?: string[];
1461
+ tagIds?: string[];
1462
+ type?: string;
1463
+ format?: string;
1464
+ filter?: string;
1465
+ splitTask?: boolean;
1466
+ summarize?: boolean;
1467
+ email?: string;
1468
+ filename?: string;
1469
+ exportedFields?: ExportedField[];
1470
+ }
1471
+ interface ExportTemplateCreateRequest {
1472
+ name: string;
1473
+ report?: number;
1474
+ teamIds?: string[];
1475
+ projectIds?: string[];
1476
+ userIds?: string[];
1477
+ tagIds?: string[];
1478
+ type?: string;
1479
+ format?: string;
1480
+ filter?: string;
1481
+ splitTask?: boolean;
1482
+ summarize?: boolean;
1483
+ email?: string;
1484
+ filename?: string;
1485
+ exportedFields?: ExportedField[];
1486
+ }
1487
+ interface ExportTemplateUpdateRequest {
1488
+ name?: string;
1489
+ report?: number;
1490
+ teamIds?: string[];
1491
+ projectIds?: string[];
1492
+ userIds?: string[];
1493
+ tagIds?: string[];
1494
+ type?: string;
1495
+ format?: string;
1496
+ filter?: string;
1497
+ splitTask?: boolean;
1498
+ summarize?: boolean;
1499
+ email?: string;
1500
+ filename?: string;
1501
+ exportedFields?: ExportedField[];
1502
+ }
1503
+ interface ExportTemplateListParams {
1504
+ sort?: 'alpha' | 'name' | 'created' | 'lastUpdate';
1505
+ order?: 'asc' | 'desc';
1506
+ page?: number;
1507
+ limit?: number;
1508
+ search?: string;
1509
+ }
1510
+ interface ExportFieldDefinition {
1511
+ fieldId: string;
1512
+ nameKey?: string;
1513
+ descriptionKey?: string;
1514
+ name: string;
1515
+ description?: string;
1516
+ type?: string;
1517
+ category?: string;
1518
+ scope?: string;
1519
+ defaultEnabled?: boolean;
1520
+ defaultPosition?: number;
1521
+ customField?: boolean;
1522
+ customType?: string;
1523
+ customValue?: string;
1524
+ customFormula?: string;
1525
+ }
1526
+ interface ExportFieldsResponse {
1527
+ fields: ExportFieldDefinition[];
1528
+ }
1529
+ interface ExportReportType {
1530
+ id: number;
1531
+ name: string;
1532
+ description?: string;
1533
+ acceptsCustomFields?: boolean;
1534
+ fieldScope?: string;
1535
+ }
1536
+ interface ExportReportsResponse {
1537
+ reports: ExportReportType[];
1538
+ }
1539
+ interface CustomExportField {
1540
+ id: string;
1541
+ user?: string;
1542
+ name: string;
1543
+ scope: string;
1544
+ type: string;
1545
+ value?: string;
1546
+ width?: number;
1547
+ deleted?: boolean;
1548
+ lastUpdate?: number;
1549
+ created?: number;
1550
+ }
1551
+ interface CustomExportFieldCreateRequest {
1552
+ name: string;
1553
+ scope: string;
1554
+ type: string;
1555
+ value?: string;
1556
+ width?: number;
1557
+ }
1558
+ interface CustomExportFieldUpdateRequest {
1559
+ name?: string;
1560
+ scope?: string;
1561
+ type?: string;
1562
+ value?: string;
1563
+ width?: number;
1564
+ }
1565
+ interface CustomExportFieldsResponse {
1566
+ fields: CustomExportField[];
1567
+ }
1568
+
1166
1569
  interface ResourceConfig {
1167
1570
  basePath: string;
1168
1571
  }
@@ -1333,6 +1736,60 @@ declare class WebhookResource extends Resource {
1333
1736
  search(params: WebhookListParams): Promise<NavigablePage<Webhook>>;
1334
1737
  }
1335
1738
 
1739
+ declare class DocumentReportResource extends Resource {
1740
+ constructor(client: ApiClient);
1741
+ get(documentId: string): Promise<DocumentReport>;
1742
+ getPdf(documentId: string): Promise<ArrayBuffer>;
1743
+ getXml(documentId: string): Promise<string>;
1744
+ }
1745
+
1746
+ declare class TaskReportResource extends Resource {
1747
+ constructor(client: ApiClient);
1748
+ get(taskId: string): Promise<TaskReportItem>;
1749
+ getPdf(taskId: string): Promise<ArrayBuffer>;
1750
+ }
1751
+
1752
+ declare class ExpenseReportResource extends Resource {
1753
+ constructor(client: ApiClient);
1754
+ get(expenseId: string): Promise<ExpenseReportItem>;
1755
+ getPdf(expenseId: string): Promise<ArrayBuffer>;
1756
+ }
1757
+
1758
+ declare class NoteReportResource extends Resource {
1759
+ constructor(client: ApiClient);
1760
+ get(noteId: string): Promise<NoteReportItem>;
1761
+ getPdf(noteId: string): Promise<ArrayBuffer>;
1762
+ }
1763
+
1764
+ declare class ExportResource extends Resource {
1765
+ constructor(client: ApiClient);
1766
+ generate(params: ExportParams): Promise<FileResponse>;
1767
+ send(params: ExportParams): Promise<void>;
1768
+ generateFromTemplate(params: ExportTemplateParams): Promise<ArrayBuffer>;
1769
+ getFields(scope?: 'all' | 'project' | 'team'): Promise<ExportFieldsResponse>;
1770
+ getReportTypes(): Promise<ExportReportsResponse>;
1771
+ listTemplates(params?: ExportTemplateListParams): Promise<NavigablePage<ExportTemplate>>;
1772
+ searchTemplates(params: ExportTemplateListParams): Promise<NavigablePage<ExportTemplate>>;
1773
+ createTemplate(data: ExportTemplateCreateRequest): Promise<ExportTemplate>;
1774
+ getTemplate(templateId: string): Promise<ExportTemplate>;
1775
+ updateTemplate(templateId: string, data: ExportTemplateUpdateRequest): Promise<ExportTemplate>;
1776
+ deleteTemplate(templateId: string): Promise<void>;
1777
+ listCustomFields(scope?: 'TASK' | 'PROJECT' | 'TEAM'): Promise<CustomExportFieldsResponse>;
1778
+ createCustomField(data: CustomExportFieldCreateRequest): Promise<CustomExportField>;
1779
+ getCustomField(fieldId: string): Promise<CustomExportField>;
1780
+ updateCustomField(fieldId: string, data: CustomExportFieldUpdateRequest): Promise<CustomExportField>;
1781
+ deleteCustomField(fieldId: string): Promise<void>;
1782
+ }
1783
+
1784
+ declare class ReportsClient {
1785
+ readonly documents: DocumentReportResource;
1786
+ readonly tasks: TaskReportResource;
1787
+ readonly expenses: ExpenseReportResource;
1788
+ readonly notes: NoteReportResource;
1789
+ readonly export: ExportResource;
1790
+ constructor(apiClient: ApiClient);
1791
+ }
1792
+
1336
1793
  declare class TimesheetApiError extends Error {
1337
1794
  readonly statusCode?: number;
1338
1795
  readonly responseBody?: string;
@@ -1352,6 +1809,7 @@ declare class TimesheetRateLimitError extends TimesheetApiError {
1352
1809
 
1353
1810
  declare class TimesheetClient {
1354
1811
  private readonly apiClient;
1812
+ private readonly reportsApiClient;
1355
1813
  readonly organizations: OrganizationResource;
1356
1814
  readonly teams: TeamResource;
1357
1815
  readonly projects: ProjectResource;
@@ -1368,6 +1826,7 @@ declare class TimesheetClient {
1368
1826
  readonly timer: TimerResource;
1369
1827
  readonly todos: TodoResource;
1370
1828
  readonly webhooks: WebhookResource;
1829
+ readonly reports: ReportsClient;
1371
1830
  constructor(options: TimesheetClientOptions);
1372
1831
  private createAuthentication;
1373
1832
  }
@@ -1381,9 +1840,11 @@ interface TimesheetClientOptions {
1381
1840
  };
1382
1841
  authentication?: Authentication;
1383
1842
  baseUrl?: string;
1843
+ reportsBaseUrl?: string;
1384
1844
  retryConfig?: RetryConfig;
1385
1845
  httpClient?: AxiosInstance;
1846
+ reportsHttpClient?: AxiosInstance;
1386
1847
  }
1387
1848
  declare function createClient(options: TimesheetClientOptions): TimesheetClient;
1388
1849
 
1389
- export { type Activity, ApiClient, ApiKeyAuth, type Authentication, type Automation, type AutomationCreateRequest, type AutomationList, type AutomationListParams, AutomationResource, type AutomationUpdateRequest, type ClientConfig, type Document, type DocumentCreateRequest, type DocumentList, type DocumentListParams, type DocumentPrint, DocumentResource, type DocumentUpdateRequest, type Expense, type ExpenseCreateRequest, type ExpenseList, type ExpenseListParams, ExpenseResource, type ExpenseStatus, type ExpenseUpdateRequest, type ListParams, type Member, NavigablePage, type Note, type NoteCreateRequest, type NoteList, type NoteListParams, NoteResource, type NoteUpdateRequest, OAuth2Auth, type Organization, type OrganizationCreateRequest, type OrganizationList, type OrganizationListParams, OrganizationResource, type OrganizationUpdateRequest, type Page, type PageParams, type Pause, type PauseCreateRequest, type PauseList, type PauseListParams, PauseResource, type PauseUpdateRequest, type Profile, ProfileResource, type ProfileUpdateRequest, type Project, type ProjectCreateRequest, type ProjectList, type ProjectListParams, type ProjectMember, ProjectResource, type ProjectUpdateRequest, type Rate, type RateCreateRequest, type RateList, type RateListParams, RateResource, type RateUpdateRequest, Resource, RetryConfig, type RetryConfigOptions, type Settings, SettingsResource, type SettingsUpdateRequest, type SortablePageParams, type Tag, type TagCreateRequest, type TagList, type TagListParams, TagResource, type TagUpdateRequest, type Task, type TaskCreateRequest, type TaskList, type TaskListParams, type TaskPerformance, TaskResource, type TaskStatistic, type TaskStatusUpdateRequest, type TaskTimesUpdateRequest, type TaskUpdateRequest, type Team, type TeamCreateRequest, type TeamList, type TeamListParams, type TeamMember, type TeamMemberList, type TeamMemberListParams, TeamResource, type TeamUpdateRequest, type Timer, type TimerPauseRequest, TimerResource, type TimerResumeRequest, type TimerStartRequest, type TimerStopRequest, type TimerUpdateRequest, TimesheetApiError, TimesheetAuthError, TimesheetClient, type TimesheetClientOptions, TimesheetRateLimitError, type Todo, type TodoCreateRequest, type TodoList, type TodoListParams, TodoResource, type TodoUpdateRequest, type Webhook, type WebhookCreateRequest, type WebhookList, type WebhookListParams, WebhookResource, type WebhookUpdateRequest, createClient };
1850
+ export { type Activity, ApiClient, ApiKeyAuth, type Authentication, type AuthorizationUrlOptions, type Automation, type AutomationCreateRequest, type AutomationList, type AutomationListParams, AutomationResource, type AutomationUpdateRequest, type ClientConfig, type CodeChallengeMethod, type CustomExportField, type CustomExportFieldCreateRequest, type CustomExportFieldUpdateRequest, type CustomExportFieldsResponse, type Document, type DocumentCreateRequest, type DocumentList, type DocumentListParams, type DocumentPrint, type DocumentReport, DocumentReportResource, DocumentResource, type DocumentUpdateRequest, type Expense, type ExpenseCreateRequest, type ExpenseList, type ExpenseListParams, type ExpenseReportItem, ExpenseReportResource, ExpenseResource, type ExpenseStatus, type ExpenseUpdateRequest, type ExportFieldDefinition, type ExportFieldsResponse, type ExportFormat, type ExportParams, type ExportReportType, type ExportReportsResponse, ExportResource, type ExportTemplate, type ExportTemplateCreateRequest, type ExportTemplateListParams, type ExportTemplateParams, type ExportTemplateUpdateRequest, type ExportedField, type FileResponse, type ListParams, type Member, NavigablePage, type Note, type NoteCreateRequest, type NoteList, type NoteListParams, type NoteReportItem, NoteReportResource, NoteResource, type NoteUpdateRequest, OAuth21Auth, type OAuth21RefreshOptions, OAuth2Auth, type Organization, type OrganizationCreateRequest, type OrganizationList, type OrganizationListParams, OrganizationResource, type OrganizationUpdateRequest, type Page, type PageParams, type Pause, type PauseCreateRequest, type PauseList, type PauseListParams, PauseResource, type PauseUpdateRequest, type PkceCodePair, type Profile, ProfileResource, type ProfileUpdateRequest, type Project, type ProjectCreateRequest, type ProjectList, type ProjectListParams, type ProjectMember, ProjectResource, type ProjectUpdateRequest, type Rate, type RateCreateRequest, type RateList, type RateListParams, RateResource, type RateUpdateRequest, ReportsClient, Resource, RetryConfig, type RetryConfigOptions, type Settings, SettingsResource, type SettingsUpdateRequest, type SortablePageParams, type Tag, type TagCreateRequest, type TagList, type TagListParams, TagResource, type TagUpdateRequest, type Task, type TaskCreateRequest, type TaskList, type TaskListParams, type TaskPerformance, type TaskReportItem, TaskReportResource, TaskResource, type TaskStatistic, type TaskStatusUpdateRequest, type TaskTimesUpdateRequest, type TaskUpdateRequest, type Team, type TeamCreateRequest, type TeamList, type TeamListParams, type TeamMember, type TeamMemberList, type TeamMemberListParams, TeamResource, type TeamUpdateRequest, type Timer, type TimerPauseRequest, TimerResource, type TimerResumeRequest, type TimerStartRequest, type TimerStopRequest, type TimerUpdateRequest, TimesheetApiError, TimesheetAuthError, TimesheetClient, type TimesheetClientOptions, TimesheetRateLimitError, type Todo, type TodoCreateRequest, type TodoList, type TodoListParams, TodoResource, type TodoUpdateRequest, type TokenExchangeOptions, type Webhook, type WebhookCreateRequest, type WebhookEventType, WebhookEvents, type WebhookList, type WebhookListParams, WebhookResource, type WebhookUpdateRequest, combineWebhookEvents, createClient, generateCodeChallenge, generateCodeVerifier, generatePkceCodePair, isValidCodeVerifier };
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";var Y=Object.create;var z=Object.defineProperty;var V=Object.getOwnPropertyDescriptor;var B=Object.getOwnPropertyNames;var J=Object.getPrototypeOf,Z=Object.prototype.hasOwnProperty;var G=(r,e)=>{for(var t in e)z(r,t,{get:e[t],enumerable:!0})},_=(r,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let m of B(e))!Z.call(r,m)&&m!==t&&z(r,m,{get:()=>e[m],enumerable:!(s=V(e,m))||s.enumerable});return r};var c=(r,e,t)=>(t=r!=null?Y(J(r)):{},_(e||!r||!r.__esModule?z(t,"default",{value:r,enumerable:!0}):t,r)),X=r=>_(z({},"__esModule",{value:!0}),r);var se={};G(se,{ApiClient:()=>I,ApiKeyAuth:()=>S,AutomationResource:()=>A,DocumentResource:()=>$,ExpenseResource:()=>C,NavigablePage:()=>o,NoteResource:()=>w,OAuth2Auth:()=>d,OrganizationResource:()=>f,PauseResource:()=>D,ProfileResource:()=>k,ProjectResource:()=>y,RateResource:()=>R,Resource:()=>i,RetryConfig:()=>O,SettingsResource:()=>v,TagResource:()=>x,TaskResource:()=>b,TeamResource:()=>T,TimerResource:()=>N,TimesheetApiError:()=>h,TimesheetAuthError:()=>E,TimesheetClient:()=>j,TimesheetRateLimitError:()=>L,TodoResource:()=>U,WebhookResource:()=>q,createClient:()=>te});module.exports=X(se);var l=c(require("axios"));var h=class r extends Error{constructor(e,t,s,m){let n=t?m?`${e} (HTTP ${t}, Code: ${m})`:`${e} (HTTP ${t})`:e;super(n),this.name="TimesheetApiError",this.statusCode=t,this.responseBody=s,this.errorCode=m,typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,r)}};var E=class extends h{constructor(e,t=401,s){super(e,t,s,"authentication_error"),this.name="TimesheetAuthError"}};var L=class extends h{constructor(e,t){super(e,429,void 0,"rate_limit_exceeded"),this.name="TimesheetRateLimitError",this.retryAfter=t}getRetryAfterDate(){if(!this.retryAfter)return null;let e=Number(this.retryAfter);if(!isNaN(e))return new Date(e*1e3);let t=new Date(this.retryAfter);return isNaN(t.getTime())?null:t}};var I=class{constructor(e){this.config=e,this.httpClient=e.httpClient||l.default.create({baseURL:e.baseUrl,timeout:3e4,headers:{"User-Agent":"Timesheet-TypeScript-SDK/1.0.0","Content-Type":"application/json"}}),this.httpClient.interceptors.request.use(async t=>{if(t.url!=="/oauth/token"&&this.config.authentication){let s=await this.config.authentication.getAuthHeaders();if(s)for(let[m,n]of Object.entries(s))t.headers.set(m,n)}return t})}async request(e){let t=null,s=this.config.retryConfig;for(let m=0;m<=s.maxRetries;m++)try{return(await this.httpClient.request(e)).data}catch(n){if(t=n,l.default.isAxiosError(n)&&n.response?.status===401){let p=n.response.data;throw new E(p?.message||"Authentication failed",401,JSON.stringify(p))}if(l.default.isAxiosError(n)&&n.response?.status===429){let p=n.response.headers["retry-after"];throw new L("Rate limit exceeded",p)}let P=l.default.isAxiosError(n)?n.response?.status:void 0;if(m<s.maxRetries&&P&&s.retryableStatusCodes.includes(P)){let p=Math.min(s.initialDelay*Math.pow(s.backoffMultiplier,m),s.maxDelay);await this.sleep(p);continue}if(l.default.isAxiosError(n)){let p=n.response?.data;throw new h(p?.message||n.message,n.response?.status,JSON.stringify(p),p?.code)}else throw n instanceof Error?new h(n.message):new h("Unknown error occurred")}throw t||new Error("Unknown error")}async get(e,t){return this.request({method:"GET",url:e,params:t})}async post(e,t,s){return this.request({method:"POST",url:e,data:t,params:s})}async put(e,t,s){return this.request({method:"PUT",url:e,data:t,params:s})}async delete(e,t){return this.request({method:"DELETE",url:e,params:t})}sleep(e){return new Promise(t=>setTimeout(t,e))}};var S=class{constructor(e){this.apiKey=e;if(e===null)throw new Error("API key cannot be null");if(e===void 0)throw new Error("API key cannot be undefined");if(!e)throw new Error("API key cannot be empty");if(typeof e!="string")throw new Error("API key must be a string");if(e.trim().length===0)throw new Error("API key cannot be empty or whitespace");if(!this.isValidFormat(e))throw new Error("Invalid API key format")}isValidFormat(e){return/^ts_[a-zA-Z0-9]+\.[a-zA-Z0-9]+$/.test(e)}applyAuth(e){e.headers||(e.headers={}),e.headers.Authorization=`ApiKey ${this.apiKey}`}needsRefresh(){return!1}async refresh(){throw new Error("API keys cannot be refreshed")}async getAuthHeaders(){return{Authorization:`ApiKey ${this.apiKey}`}}isValid(){return typeof this.apiKey=="string"&&this.apiKey.trim().length>0&&this.isValidFormat(this.apiKey)}};var M=c(require("axios")),W=c(require("jsonwebtoken")),u=class u{constructor(e,t,s){t&&s?(this.clientId=e,this.clientSecret=t,this.refreshToken=s,this.accessToken=""):(this.accessToken=e,this.parseTokenExpiry())}applyAuth(e){e.headers||(e.headers={}),e.headers.Authorization=`Bearer ${this.accessToken}`}needsRefresh(){return this.refreshToken&&!this.accessToken?!0:!this.refreshToken||!this.tokenExpiry?!1:new Date(Date.now()+5*60*1e3)>=this.tokenExpiry}async refresh(){if(!this.refreshToken)throw new Error("Cannot refresh without refresh token");if(this.refreshPromise)return this.refreshPromise;this.refreshPromise=this.performRefresh();try{await this.refreshPromise}finally{this.refreshPromise=void 0}}async performRefresh(){try{let e=await M.default.post(u.TOKEN_ENDPOINT,new URLSearchParams({grant_type:"refresh_token",refresh_token:this.refreshToken,client_id:this.clientId,client_secret:this.clientSecret}),{headers:{"Content-Type":"application/x-www-form-urlencoded"}});this.accessToken=e.data.access_token,e.data.refresh_token&&(this.refreshToken=e.data.refresh_token),this.parseTokenExpiry()}catch(e){let t=e instanceof Error?e.message:"Unknown error";throw new Error(`Failed to refresh OAuth2 token: ${t}`)}}async getAuthHeaders(){return this.needsRefresh()&&await this.refresh(),{Authorization:`Bearer ${this.accessToken}`}}static async fromAuthorizationCode(e,t,s,m){try{let n=await M.default.post(u.TOKEN_ENDPOINT,new URLSearchParams({grant_type:"authorization_code",code:s,redirect_uri:m,client_id:e,client_secret:t}),{headers:{"Content-Type":"application/x-www-form-urlencoded"}}),P=n.data.access_token,p=n.data.refresh_token;return p?new u(e,t,p):new u(P)}catch(n){let P=n instanceof Error?n.message:"Unknown error";throw new Error(`Failed to exchange authorization code: ${P}`)}}static buildAuthorizationUrl(e,t,s){let m=new URLSearchParams({client_id:e,redirect_uri:t,response_type:"code"});return s&&m.append("state",s),`https://api.timesheet.io/oauth2/auth?${m.toString()}`}parseTokenExpiry(){try{let e=W.default.decode(this.accessToken);e&&e.exp&&(this.tokenExpiry=new Date(e.exp*1e3))}catch{this.tokenExpiry=new Date(Date.now()+60*60*1e3)}}};u.TOKEN_ENDPOINT="https://api.timesheet.io/oauth2/token";var d=u;var O=class r{constructor(e={}){this.maxRetries=e.maxRetries??3,this.initialDelay=e.initialDelay??100,this.maxDelay=e.maxDelay??1e4,this.backoffMultiplier=e.backoffMultiplier??2,this.retryableStatusCodes=e.retryableStatusCodes??[429,502,503,504]}static default(){return new r}};var o=class{constructor(e,t){this.items=e.items,this.params=e.params,this.nextPageLoader=t}get totalPages(){return Math.ceil((this.params?.count||0)/(this.params?.limit||25))}get hasNextPage(){return(this.params?.page||1)<this.totalPages}async nextPage(){if(!this.hasNextPage)throw new Error("No more pages available");if(!this.nextPageLoader)throw new Error("Next page loader not configured");return this.nextPageLoader((this.params.page||1)+1)}async*[Symbol.asyncIterator](){let e=this;for(;;){for(let t of e.items)yield t;if(!e.hasNextPage)break;e=await e.nextPage()}}async toArray(){let e=[];for await(let t of this)e.push(t);return e}};var i=class{constructor(e,t){this.http=e;typeof t=="string"?this.basePath=t:this.basePath=t.basePath}createNavigablePage(e,t){return new o(e,t)}};var f=class extends i{constructor(e){super(e,"/v1/organizations")}async list(e){let t=await this.http.get(this.basePath,e);return new o(t,s=>this.list({...e,page:s}))}async create(e){return this.http.post(this.basePath,e)}async update(e,t){return this.http.put(`${this.basePath}/${encodeURIComponent(e)}`,t)}async get(e){return this.http.get(`${this.basePath}/${encodeURIComponent(e)}`)}async delete(e){return this.http.delete(`${this.basePath}/${encodeURIComponent(e)}`)}async search(e){let t=await this.http.post(`${this.basePath}/search`,e);return this.createNavigablePage(t,s=>this.search({...e,page:s}))}};var T=class extends i{constructor(e){super(e,"/v1/teams")}async list(e){let t=await this.http.get(this.basePath,e);return new o(t,s=>this.list({...e,page:s}))}async create(e){return this.http.post(this.basePath,e)}async update(e,t){return this.http.put(`${this.basePath}/${encodeURIComponent(e)}`,t)}async get(e){return this.http.get(`${this.basePath}/${encodeURIComponent(e)}`)}async delete(e){return this.http.delete(`${this.basePath}/${encodeURIComponent(e)}`)}async search(e){let t=await this.http.post(`${this.basePath}/search`,e);return this.createNavigablePage(t,s=>this.search({...e,page:s}))}async listMembers(e,t){let s=await this.http.post(`${this.basePath}/${e}/members/list`,t);return this.createNavigablePage(s,m=>this.listMembers(e,{...t,page:m}))}async getMember(e,t){return this.http.get(`${this.basePath}/${e}/members/${t}`)}async getColleagues(e){let t=await this.http.post(`${this.basePath}/getColleagues`,e);return this.createNavigablePage(t,s=>this.getColleagues({...e,page:s}))}};var y=class extends i{constructor(e){super(e,"/v1/projects")}async list(e){let t=await this.http.get(this.basePath,e);return new o(t,s=>this.list({...e,page:s}))}async create(e){return this.http.post(this.basePath,e)}async update(e,t){return this.http.put(`${this.basePath}/${encodeURIComponent(e)}`,t)}async get(e){return this.http.get(`${this.basePath}/${encodeURIComponent(e)}`)}async delete(e){return this.http.delete(`${this.basePath}/${encodeURIComponent(e)}`)}async search(e){let t=await this.http.post(`${this.basePath}/search`,e);return this.createNavigablePage(t,s=>this.search({...e,page:s}))}};var g=c(require("dayjs")),F=c(require("dayjs/plugin/utc")),K=c(require("dayjs/plugin/timezone")),H=c(require("dayjs/plugin/customParseFormat"));g.default.extend(F.default);g.default.extend(K.default);g.default.extend(H.default);var Q="YYYY-MM-DDTHH:mm:ssZ",ee=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}[+-]\d{2}:\d{2}$/,a={isValidTimestampFormat(r){return ee.test(r)},formatTimestamp(r){return typeof r=="string"&&this.isValidTimestampFormat(r)?r:(0,g.default)(r||new Date).format(Q)},parseTimestamp(r){return(0,g.default)(r).toDate()},formatDate(r){return(0,g.default)(r||new Date).format("YYYY-MM-DD")},now(){return this.formatTimestamp()}};var b=class extends i{constructor(e){super(e,"/v1/tasks")}async create(e){let t={...e,startDateTime:a.formatTimestamp(e.startDateTime),endDateTime:e.endDateTime?a.formatTimestamp(e.endDateTime):void 0};return this.http.post(this.basePath,t)}async update(e,t){let s={...t,startDateTime:t.startDateTime?a.formatTimestamp(t.startDateTime):void 0,endDateTime:t.endDateTime?a.formatTimestamp(t.endDateTime):void 0};return this.http.put(`${this.basePath}/${encodeURIComponent(e)}`,s)}async get(e){return this.http.get(`${this.basePath}/${encodeURIComponent(e)}`)}async delete(e){return this.http.delete(`${this.basePath}/${encodeURIComponent(e)}`)}async search(e){let t=await this.http.post(`${this.basePath}/search`,e);return this.createNavigablePage(t,s=>this.search({...e,page:s}))}async updateStatus(e){return this.http.put(`${this.basePath}/updateStatus`,e)}async updateTimes(e){let t={...e,startDateTime:a.formatTimestamp(e.startDateTime),endDateTime:a.formatTimestamp(e.endDateTime)};return this.http.put(`${this.basePath}/updateTimes`,t)}};var R=class extends i{constructor(e){super(e,"/v1/rates")}async list(e){let t=await this.http.get(this.basePath,e);return new o(t,s=>this.list({...e,page:s}))}async create(e){return this.http.post(this.basePath,e)}async update(e,t){return this.http.put(`${this.basePath}/${encodeURIComponent(e)}`,t)}async get(e){return this.http.get(`${this.basePath}/${encodeURIComponent(e)}`)}async delete(e){return this.http.delete(`${this.basePath}/${encodeURIComponent(e)}`)}async search(e){let t=await this.http.post(`${this.basePath}/search`,e);return this.createNavigablePage(t,s=>this.search({...e,page:s}))}};var x=class extends i{constructor(e){super(e,"/v1/tags")}async list(e){let t=await this.http.get(this.basePath,e);return new o(t,s=>this.list({...e,page:s}))}async create(e){return this.http.post(this.basePath,e)}async update(e,t){return this.http.put(`${this.basePath}/${encodeURIComponent(e)}`,t)}async get(e){return this.http.get(`${this.basePath}/${encodeURIComponent(e)}`)}async delete(e){return this.http.delete(`${this.basePath}/${encodeURIComponent(e)}`)}async search(e){let t=await this.http.post(`${this.basePath}/search`,e);return this.createNavigablePage(t,s=>this.search({...e,page:s}))}};var C=class extends i{constructor(e){super(e,"/v1/expenses")}async list(e){let t=await this.http.get(this.basePath,e);return new o(t,s=>this.list({...e,page:s}))}async create(e){let t={...e,dateTime:a.formatTimestamp(e.dateTime)};return this.http.post(this.basePath,t)}async update(e,t){let s={...t,dateTime:t.dateTime?a.formatTimestamp(t.dateTime):void 0};return this.http.put(`${this.basePath}/${encodeURIComponent(e)}`,s)}async get(e){return this.http.get(`${this.basePath}/${encodeURIComponent(e)}`)}async delete(e){return this.http.delete(`${this.basePath}/${encodeURIComponent(e)}`)}async search(e){let t=await this.http.post(`${this.basePath}/search`,e);return this.createNavigablePage(t,s=>this.search({...e,page:s}))}async updateStatus(e,t){return this.http.put(`${this.basePath}/${e}/status`,t)}};var w=class extends i{constructor(e){super(e,"/v1/notes")}async list(e){let t=await this.http.get(this.basePath,e);return new o(t,s=>this.list({...e,page:s}))}async create(e){let t={...e,dateTime:a.formatTimestamp(e.dateTime)};return this.http.post(this.basePath,t)}async update(e,t){let s={...t,dateTime:a.formatTimestamp(t.dateTime)};return this.http.put(`${this.basePath}/${encodeURIComponent(e)}`,s)}async get(e){return this.http.get(`${this.basePath}/${encodeURIComponent(e)}`)}async delete(e){return this.http.delete(`${this.basePath}/${encodeURIComponent(e)}`)}async search(e){let t=await this.http.post(`${this.basePath}/search`,e);return this.createNavigablePage(t,s=>this.search({...e,page:s}))}};var D=class extends i{constructor(e){super(e,"/v1/pauses")}async list(e){let t=await this.http.get(this.basePath,e);return new o(t,s=>this.list({...e,page:s}))}async create(e){let t={...e,startDateTime:a.formatTimestamp(e.startDateTime),endDateTime:a.formatTimestamp(e.endDateTime)};return this.http.post(this.basePath,t)}async update(e,t){let s={...t,startDateTime:a.formatTimestamp(t.startDateTime),endDateTime:a.formatTimestamp(t.endDateTime)};return this.http.put(`${this.basePath}/${encodeURIComponent(e)}`,s)}async get(e){return this.http.get(`${this.basePath}/${encodeURIComponent(e)}`)}async delete(e){return this.http.delete(`${this.basePath}/${encodeURIComponent(e)}`)}async search(e){let t=await this.http.post(`${this.basePath}/search`,e);return this.createNavigablePage(t,s=>this.search({...e,page:s}))}};var k=class{constructor(e){this.http=e}async getProfile(){return this.http.get("/v1/profiles/me")}async updateProfile(e){return this.http.put("/v1/profiles/me",e)}};var v=class{constructor(e){this.http=e}async get(){return this.http.get("/v1/settings")}async update(e){return this.http.put("/v1/settings",e)}};var A=class extends i{constructor(e){super(e,"/v1/automations")}async list(e){let t=await this.http.get(this.basePath,e);return new o(t,s=>this.list({...e,page:s}))}async create(e){return this.http.post(this.basePath,e)}async update(e,t){return this.http.put(`${this.basePath}/${encodeURIComponent(e)}`,t)}async get(e){return this.http.get(`${this.basePath}/${encodeURIComponent(e)}`)}async delete(e){return this.http.delete(`${this.basePath}/${encodeURIComponent(e)}`)}async search(e){let t=await this.http.post(`${this.basePath}/search`,e);return this.createNavigablePage(t,s=>this.search({...e,page:s}))}};var $=class extends i{constructor(e){super(e,"/v1/documents")}async list(e){let t=await this.http.get(this.basePath,e);return new o(t,s=>this.list({...e,page:s}))}async create(e){return this.http.post(this.basePath,e)}async update(e,t){return this.http.put(`${this.basePath}/${encodeURIComponent(e)}`,t)}async get(e){return this.http.get(`${this.basePath}/${encodeURIComponent(e)}`)}async delete(e){return this.http.delete(`${this.basePath}/${encodeURIComponent(e)}`)}async search(e){let t=await this.http.post(`${this.basePath}/search`,e);return this.createNavigablePage(t,s=>this.search({...e,page:s}))}};var N=class{constructor(e){this.http=e}async get(){return this.http.get("/v1/timer")}async start(e){let t={...e,startDateTime:e.startDateTime?a.formatTimestamp(e.startDateTime):a.formatTimestamp()};return this.http.post("/v1/timer/start",t)}async stop(e){let t=e?{...e,endDateTime:e.endDateTime?a.formatTimestamp(e.endDateTime):a.formatTimestamp()}:{endDateTime:a.formatTimestamp()};return this.http.post("/v1/timer/stop",t)}async pause(e){let t=e?{...e,startDateTime:e.startDateTime?a.formatTimestamp(e.startDateTime):a.formatTimestamp()}:{startDateTime:a.formatTimestamp()};return this.http.post("/v1/timer/pause",t)}async resume(e){let t=e?{...e,endDateTime:e.endDateTime?a.formatTimestamp(e.endDateTime):a.formatTimestamp()}:{endDateTime:a.formatTimestamp()};return this.http.post("/v1/timer/resume",t)}async update(e){let t={...e,startDateTime:e.startDateTime?a.formatTimestamp(e.startDateTime):void 0};return this.http.put("/v1/timer/update",t)}};var U=class extends i{constructor(e){super(e,"/v1/todos")}async list(e){let t=await this.http.get(this.basePath,e);return new o(t,s=>this.list({...e,page:s}))}async create(e){let t={...e,dueDate:e.dueDate?a.formatTimestamp(e.dueDate):void 0};return this.http.post(this.basePath,t)}async update(e,t){let s={...t,dueDate:t.dueDate?a.formatTimestamp(t.dueDate):void 0};return this.http.put(`${this.basePath}/${encodeURIComponent(e)}`,s)}async get(e){return this.http.get(`${this.basePath}/${encodeURIComponent(e)}`)}async delete(e){return this.http.delete(`${this.basePath}/${encodeURIComponent(e)}`)}async search(e){let t=await this.http.post(`${this.basePath}/search`,e);return this.createNavigablePage(t,s=>this.search({...e,page:s}))}};var q=class extends i{constructor(e){super(e,"/v1/webhooks")}async list(e){let t=await this.http.get(this.basePath,e);return new o(t,s=>this.list({...e,page:s}))}async create(e){return this.http.post(this.basePath,e)}async update(e,t){return this.http.put(`${this.basePath}/${encodeURIComponent(e)}`,t)}async get(e){return this.http.get(`${this.basePath}/${encodeURIComponent(e)}`)}async delete(e){return this.http.delete(`${this.basePath}/${encodeURIComponent(e)}`)}async search(e){let t=await this.http.post(`${this.basePath}/search`,e);return this.createNavigablePage(t,s=>this.search({...e,page:s}))}};var j=class{constructor(e){let t=this.createAuthentication(e),s={baseUrl:e.baseUrl||"https://api.timesheet.io",authentication:t,retryConfig:e.retryConfig||O.default(),httpClient:e.httpClient};this.apiClient=new I(s),this.organizations=new f(this.apiClient),this.teams=new T(this.apiClient),this.projects=new y(this.apiClient),this.tasks=new b(this.apiClient),this.rates=new R(this.apiClient),this.tags=new x(this.apiClient),this.expenses=new C(this.apiClient),this.notes=new w(this.apiClient),this.pauses=new D(this.apiClient),this.profile=new k(this.apiClient),this.settings=new v(this.apiClient),this.automations=new A(this.apiClient),this.documents=new $(this.apiClient),this.timer=new N(this.apiClient),this.todos=new U(this.apiClient),this.webhooks=new q(this.apiClient)}createAuthentication(e){if(e.apiKey)return new S(e.apiKey);if(e.oauth2Token)return new d(e.oauth2Token);if(e.oauth2)return new d(e.oauth2.clientId,e.oauth2.clientSecret,e.oauth2.refreshToken);if(e.authentication)return e.authentication;throw new Error("Authentication must be configured")}};function te(r){return new j(r)}0&&(module.exports={ApiClient,ApiKeyAuth,AutomationResource,DocumentResource,ExpenseResource,NavigablePage,NoteResource,OAuth2Auth,OrganizationResource,PauseResource,ProfileResource,ProjectResource,RateResource,Resource,RetryConfig,SettingsResource,TagResource,TaskResource,TeamResource,TimerResource,TimesheetApiError,TimesheetAuthError,TimesheetClient,TimesheetRateLimitError,TodoResource,WebhookResource,createClient});
1
+ "use strict";var ue=Object.create;var V=Object.defineProperty;var le=Object.getOwnPropertyDescriptor;var de=Object.getOwnPropertyNames;var ge=Object.getPrototypeOf,Pe=Object.prototype.hasOwnProperty;var fe=(s,e)=>{for(var t in e)V(s,t,{get:e[t],enumerable:!0})},re=(s,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let p of de(e))!Pe.call(s,p)&&p!==t&&V(s,p,{get:()=>e[p],enumerable:!(r=le(e,p))||r.enumerable});return s};var d=(s,e,t)=>(t=s!=null?ue(ge(s)):{},re(e||!s||!s.__esModule?V(t,"default",{value:s,enumerable:!0}):t,s)),Te=s=>re(V({},"__esModule",{value:!0}),s);var ke={};fe(ke,{ApiClient:()=>y,ApiKeyAuth:()=>K,AutomationResource:()=>N,DocumentReportResource:()=>S,DocumentResource:()=>I,ExpenseReportResource:()=>M,ExpenseResource:()=>A,ExportResource:()=>F,NavigablePage:()=>n,NoteReportResource:()=>z,NoteResource:()=>v,OAuth21Auth:()=>ee,OAuth2Auth:()=>R,OrganizationResource:()=>b,PauseResource:()=>$,ProfileResource:()=>D,ProjectResource:()=>C,RateResource:()=>w,ReportsClient:()=>j,Resource:()=>o,RetryConfig:()=>H,SettingsResource:()=>U,TagResource:()=>E,TaskReportResource:()=>O,TaskResource:()=>k,TeamResource:()=>x,TimerResource:()=>q,TimesheetApiError:()=>c,TimesheetAuthError:()=>W,TimesheetClient:()=>J,TimesheetRateLimitError:()=>B,TodoResource:()=>L,WebhookEvents:()=>ye,WebhookResource:()=>_,combineWebhookEvents:()=>Re,createClient:()=>Ce,generateCodeChallenge:()=>ae,generateCodeVerifier:()=>oe,generatePkceCodePair:()=>Z,isValidCodeVerifier:()=>X});module.exports=Te(ke);var T=d(require("axios"));var c=class s extends Error{constructor(e,t,r,p){let i=t?p?`${e} (HTTP ${t}, Code: ${p})`:`${e} (HTTP ${t})`:e;super(i),this.name="TimesheetApiError",this.statusCode=t,this.responseBody=r,this.errorCode=p,typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,s)}};var W=class extends c{constructor(e,t=401,r){super(e,t,r,"authentication_error"),this.name="TimesheetAuthError"}};var B=class extends c{constructor(e,t){super(e,429,void 0,"rate_limit_exceeded"),this.name="TimesheetRateLimitError",this.retryAfter=t}getRetryAfterDate(){if(!this.retryAfter)return null;let e=Number(this.retryAfter);if(!isNaN(e))return new Date(e*1e3);let t=new Date(this.retryAfter);return isNaN(t.getTime())?null:t}};var y=class{constructor(e){this.config=e,this.httpClient=e.httpClient||T.default.create({baseURL:e.baseUrl,timeout:3e4,headers:{"User-Agent":"Timesheet-TypeScript-SDK/1.0.0","Content-Type":"application/json"}}),this.httpClient.interceptors.request.use(async t=>{if(t.url!=="/oauth/token"&&this.config.authentication){let r=await this.config.authentication.getAuthHeaders();if(r)for(let[p,i]of Object.entries(r))t.headers.set(p,i)}return t})}async request(e){let t=null,r=this.config.retryConfig;for(let p=0;p<=r.maxRetries;p++)try{return(await this.httpClient.request(e)).data}catch(i){if(t=i,T.default.isAxiosError(i)&&i.response?.status===401){let m=i.response.data;throw new W(m?.message||"Authentication failed",401,JSON.stringify(m))}if(T.default.isAxiosError(i)&&i.response?.status===429){let m=i.response.headers["retry-after"];throw new B("Rate limit exceeded",m)}let h=T.default.isAxiosError(i)?i.response?.status:void 0;if(p<r.maxRetries&&h&&r.retryableStatusCodes.includes(h)){let m=Math.min(r.initialDelay*Math.pow(r.backoffMultiplier,p),r.maxDelay);await this.sleep(m);continue}if(T.default.isAxiosError(i)){let m=i.response?.data;throw new c(m?.message||i.message,i.response?.status,JSON.stringify(m),m?.code)}else throw i instanceof Error?new c(i.message):new c("Unknown error occurred")}throw t||new Error("Unknown error")}async get(e,t){return this.request({method:"GET",url:e,params:t})}async post(e,t,r){return this.request({method:"POST",url:e,data:t,params:r})}async put(e,t,r){return this.request({method:"PUT",url:e,data:t,params:r})}async delete(e,t){return this.request({method:"DELETE",url:e,params:t})}sleep(e){return new Promise(t=>setTimeout(t,e))}};var K=class{constructor(e){this.apiKey=e;if(e===null)throw new Error("API key cannot be null");if(e===void 0)throw new Error("API key cannot be undefined");if(!e)throw new Error("API key cannot be empty");if(typeof e!="string")throw new Error("API key must be a string");if(e.trim().length===0)throw new Error("API key cannot be empty or whitespace");if(!this.isValidFormat(e))throw new Error("Invalid API key format")}isValidFormat(e){return/^ts_[a-zA-Z0-9]+\.[a-zA-Z0-9]+$/.test(e)}applyAuth(e){e.headers||(e.headers={}),e.headers.Authorization=`ApiKey ${this.apiKey}`}needsRefresh(){return!1}async refresh(){throw new Error("API keys cannot be refreshed")}async getAuthHeaders(){return{Authorization:`ApiKey ${this.apiKey}`}}isValid(){return typeof this.apiKey=="string"&&this.apiKey.trim().length>0&&this.isValidFormat(this.apiKey)}};var Y=d(require("axios")),se=d(require("jsonwebtoken")),P=class P{constructor(e,t,r){t&&r?(this.clientId=e,this.clientSecret=t,this.refreshToken=r,this.accessToken=""):(this.accessToken=e,this.parseTokenExpiry())}applyAuth(e){e.headers||(e.headers={}),e.headers.Authorization=`Bearer ${this.accessToken}`}needsRefresh(){return this.refreshToken&&!this.accessToken?!0:!this.refreshToken||!this.tokenExpiry?!1:new Date(Date.now()+5*60*1e3)>=this.tokenExpiry}async refresh(){if(!this.refreshToken)throw new Error("Cannot refresh without refresh token");if(this.refreshPromise)return this.refreshPromise;this.refreshPromise=this.performRefresh();try{await this.refreshPromise}finally{this.refreshPromise=void 0}}async performRefresh(){try{let e=await Y.default.post(P.TOKEN_ENDPOINT,new URLSearchParams({grant_type:"refresh_token",refresh_token:this.refreshToken,client_id:this.clientId,client_secret:this.clientSecret}),{headers:{"Content-Type":"application/x-www-form-urlencoded"}});this.accessToken=e.data.access_token,e.data.refresh_token&&(this.refreshToken=e.data.refresh_token),this.parseTokenExpiry()}catch(e){let t=e instanceof Error?e.message:"Unknown error";throw new Error(`Failed to refresh OAuth2 token: ${t}`)}}async getAuthHeaders(){return this.needsRefresh()&&await this.refresh(),{Authorization:`Bearer ${this.accessToken}`}}static async fromAuthorizationCode(e,t,r,p){try{let i=await Y.default.post(P.TOKEN_ENDPOINT,new URLSearchParams({grant_type:"authorization_code",code:r,redirect_uri:p,client_id:e,client_secret:t}),{headers:{"Content-Type":"application/x-www-form-urlencoded"}}),h=i.data.access_token,m=i.data.refresh_token;return m?new P(e,t,m):new P(h)}catch(i){let h=i instanceof Error?i.message:"Unknown error";throw new Error(`Failed to exchange authorization code: ${h}`)}}static buildAuthorizationUrl(e,t,r){let p=new URLSearchParams({client_id:e,redirect_uri:t,response_type:"code"});return r&&p.append("state",r),`https://api.timesheet.io/oauth2/auth?${p.toString()}`}parseTokenExpiry(){try{let e=se.default.decode(this.accessToken);e&&e.exp&&(this.tokenExpiry=new Date(e.exp*1e3))}catch{this.tokenExpiry=new Date(Date.now()+60*60*1e3)}}};P.TOKEN_ENDPOINT="https://api.timesheet.io/oauth2/token";var R=P;var Q=d(require("axios")),ne=d(require("jsonwebtoken"));var G=require("crypto");function oe(s=64){if(s<43||s>128)throw new Error("Code verifier length must be between 43 and 128 characters");let e=(0,G.randomBytes)(Math.ceil(s*3/4));return ie(e).slice(0,s)}function ae(s,e="S256"){if(e==="plain")return s;let t=(0,G.createHash)("sha256").update(s,"ascii").digest();return ie(t)}function Z(s="S256",e=64){let t=oe(e),r=ae(t,s);return{codeVerifier:t,codeChallenge:r,codeChallengeMethod:s}}function X(s){return s.length<43||s.length>128?!1:/^[A-Za-z0-9\-._~]+$/.test(s)}function ie(s){return s.toString("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}var g=class g{constructor(e){if(typeof e=="string")this.accessToken=e,this.parseTokenExpiry();else{let t=e;this.clientId=t.clientId,this.clientSecret=t.clientSecret,this.refreshToken=t.refreshToken,this.resource=t.resource,this.accessToken=""}}applyAuth(e){e.headers||(e.headers={}),e.headers.Authorization=`Bearer ${this.accessToken}`}needsRefresh(){return this.refreshToken&&!this.accessToken?!0:!this.refreshToken||!this.tokenExpiry?!1:new Date(Date.now()+5*60*1e3)>=this.tokenExpiry}async refresh(){if(!this.refreshToken)throw new Error("Cannot refresh without refresh token");if(this.refreshPromise)return this.refreshPromise;this.refreshPromise=this.performRefresh();try{await this.refreshPromise}finally{this.refreshPromise=void 0}}async performRefresh(){try{let e=new URLSearchParams({grant_type:"refresh_token",refresh_token:this.refreshToken,client_id:this.clientId});this.clientSecret&&e.append("client_secret",this.clientSecret),this.resource&&e.append("resource",this.resource);let t=await Q.default.post(g.TOKEN_ENDPOINT,e,{headers:{"Content-Type":"application/x-www-form-urlencoded"}});this.accessToken=t.data.access_token,t.data.refresh_token&&(this.refreshToken=t.data.refresh_token),this.parseTokenExpiry()}catch(e){let t=e instanceof Error?e.message:"Unknown error";throw new Error(`Failed to refresh OAuth 2.1 token: ${t}`)}}async getAuthHeaders(){return this.needsRefresh()&&await this.refresh(),{Authorization:`Bearer ${this.accessToken}`}}static async fromAuthorizationCode(e){let{clientId:t,clientSecret:r,authorizationCode:p,redirectUri:i,codeVerifier:h,resource:m}=e;if(!X(h))throw new Error("Invalid code verifier: must be 43-128 characters using only A-Z, a-z, 0-9, -, ., _, ~");try{let u=new URLSearchParams({grant_type:"authorization_code",code:p,redirect_uri:i,client_id:t,code_verifier:h});r&&u.append("client_secret",r),m&&u.append("resource",m);let l=await Q.default.post(g.TOKEN_ENDPOINT,u,{headers:{"Content-Type":"application/x-www-form-urlencoded"}}),ce=l.data.access_token,te=l.data.refresh_token;return te?new g({clientId:t,clientSecret:r,refreshToken:te,resource:m}):new g(ce)}catch(u){let l=u instanceof Error?u.message:"Unknown error";throw new Error(`Failed to exchange authorization code: ${l}`)}}static buildAuthorizationUrl(e){let{clientId:t,redirectUri:r,codeChallenge:p,codeChallengeMethod:i="S256",state:h,scope:m,resource:u}=e,l=new URLSearchParams({response_type:"code",client_id:t,redirect_uri:r,code_challenge:p,code_challenge_method:i});return h&&l.append("state",h),m&&l.append("scope",m),u&&l.append("resource",u),`${g.AUTH_ENDPOINT}?${l.toString()}`}static generatePkce(e="S256"){return Z(e)}parseTokenExpiry(){try{let e=ne.default.decode(this.accessToken);e&&e.exp&&(this.tokenExpiry=new Date(e.exp*1e3))}catch{this.tokenExpiry=new Date(Date.now()+60*60*1e3)}}};g.TOKEN_ENDPOINT="https://api.timesheet.io/oauth2/token",g.AUTH_ENDPOINT="https://api.timesheet.io/oauth2/auth";var ee=g;var H=class s{constructor(e={}){this.maxRetries=e.maxRetries??3,this.initialDelay=e.initialDelay??100,this.maxDelay=e.maxDelay??1e4,this.backoffMultiplier=e.backoffMultiplier??2,this.retryableStatusCodes=e.retryableStatusCodes??[429,502,503,504]}static default(){return new s}};var n=class{constructor(e,t){this.items=e.items,this.params=e.params,this.nextPageLoader=t}get totalPages(){return Math.ceil((this.params?.count||0)/(this.params?.limit||25))}get hasNextPage(){return(this.params?.page||1)<this.totalPages}async nextPage(){if(!this.hasNextPage)throw new Error("No more pages available");if(!this.nextPageLoader)throw new Error("Next page loader not configured");return this.nextPageLoader((this.params.page||1)+1)}async*[Symbol.asyncIterator](){let e=this;for(;;){for(let t of e.items)yield t;if(!e.hasNextPage)break;e=await e.nextPage()}}async toArray(){let e=[];for await(let t of this)e.push(t);return e}};var ye={TEAM_CREATE:"team.create",TEAM_UPDATE:"team.update",PROJECT_CREATE:"project.create",PROJECT_UPDATE:"project.update",TODO_CREATE:"todo.create",TODO_UPDATE:"todo.update",TASK_CREATE:"task.create",TASK_UPDATE:"task.update",TAG_CREATE:"tag.create",TAG_UPDATE:"tag.update",RATE_CREATE:"rate.create",RATE_UPDATE:"rate.update",TIMER_START:"timer.start",TIMER_STOP:"timer.stop",TIMER_PAUSE:"timer.pause",TIMER_RESUME:"timer.resume"};function Re(...s){return s.join(",")}var o=class{constructor(e,t){this.http=e;typeof t=="string"?this.basePath=t:this.basePath=t.basePath}createNavigablePage(e,t){return new n(e,t)}};var b=class extends o{constructor(e){super(e,"/v1/organizations")}async list(e){let t=await this.http.get(this.basePath,e);return new n(t,r=>this.list({...e,page:r}))}async create(e){return this.http.post(this.basePath,e)}async update(e,t){return this.http.put(`${this.basePath}/${encodeURIComponent(e)}`,t)}async get(e){return this.http.get(`${this.basePath}/${encodeURIComponent(e)}`)}async delete(e){return this.http.delete(`${this.basePath}/${encodeURIComponent(e)}`)}async search(e){let t=await this.http.post(`${this.basePath}/search`,e);return this.createNavigablePage(t,r=>this.search({...e,page:r}))}};var x=class extends o{constructor(e){super(e,"/v1/teams")}async list(e){let t=await this.http.get(this.basePath,e);return new n(t,r=>this.list({...e,page:r}))}async create(e){return this.http.post(this.basePath,e)}async update(e,t){return this.http.put(`${this.basePath}/${encodeURIComponent(e)}`,t)}async get(e){return this.http.get(`${this.basePath}/${encodeURIComponent(e)}`)}async delete(e){return this.http.delete(`${this.basePath}/${encodeURIComponent(e)}`)}async search(e){let t=await this.http.post(`${this.basePath}/search`,e);return this.createNavigablePage(t,r=>this.search({...e,page:r}))}async listMembers(e,t){let r=await this.http.post(`${this.basePath}/${e}/members/list`,t);return this.createNavigablePage(r,p=>this.listMembers(e,{...t,page:p}))}async getMember(e,t){return this.http.get(`${this.basePath}/${e}/members/${t}`)}async getColleagues(e){let t=await this.http.post(`${this.basePath}/getColleagues`,e);return this.createNavigablePage(t,r=>this.getColleagues({...e,page:r}))}};var C=class extends o{constructor(e){super(e,"/v1/projects")}async list(e){let t=await this.http.get(this.basePath,e);return new n(t,r=>this.list({...e,page:r}))}async create(e){return this.http.post(this.basePath,e)}async update(e,t){return this.http.put(`${this.basePath}/${encodeURIComponent(e)}`,t)}async get(e){return this.http.get(`${this.basePath}/${encodeURIComponent(e)}`)}async delete(e){return this.http.delete(`${this.basePath}/${encodeURIComponent(e)}`)}async search(e){let t=await this.http.post(`${this.basePath}/search`,e);return this.createNavigablePage(t,r=>this.search({...e,page:r}))}};var f=d(require("dayjs")),pe=d(require("dayjs/plugin/utc")),me=d(require("dayjs/plugin/timezone")),he=d(require("dayjs/plugin/customParseFormat"));f.default.extend(pe.default);f.default.extend(me.default);f.default.extend(he.default);var be="YYYY-MM-DDTHH:mm:ssZ",xe=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}[+-]\d{2}:\d{2}$/,a={isValidTimestampFormat(s){return xe.test(s)},formatTimestamp(s){return typeof s=="string"&&this.isValidTimestampFormat(s)?s:(0,f.default)(s||new Date).format(be)},parseTimestamp(s){return(0,f.default)(s).toDate()},formatDate(s){return(0,f.default)(s||new Date).format("YYYY-MM-DD")},now(){return this.formatTimestamp()}};var k=class extends o{constructor(e){super(e,"/v1/tasks")}async create(e){let t={...e,startDateTime:a.formatTimestamp(e.startDateTime),endDateTime:e.endDateTime?a.formatTimestamp(e.endDateTime):void 0};return this.http.post(this.basePath,t)}async update(e,t){let r={...t,startDateTime:t.startDateTime?a.formatTimestamp(t.startDateTime):void 0,endDateTime:t.endDateTime?a.formatTimestamp(t.endDateTime):void 0};return this.http.put(`${this.basePath}/${encodeURIComponent(e)}`,r)}async get(e){return this.http.get(`${this.basePath}/${encodeURIComponent(e)}`)}async delete(e){return this.http.delete(`${this.basePath}/${encodeURIComponent(e)}`)}async search(e){let t=await this.http.post(`${this.basePath}/search`,e);return this.createNavigablePage(t,r=>this.search({...e,page:r}))}async updateStatus(e){return this.http.put(`${this.basePath}/updateStatus`,e)}async updateTimes(e){let t={...e,startDateTime:a.formatTimestamp(e.startDateTime),endDateTime:a.formatTimestamp(e.endDateTime)};return this.http.put(`${this.basePath}/updateTimes`,t)}};var w=class extends o{constructor(e){super(e,"/v1/rates")}async list(e){let t=await this.http.get(this.basePath,e);return new n(t,r=>this.list({...e,page:r}))}async create(e){return this.http.post(this.basePath,e)}async update(e,t){return this.http.put(`${this.basePath}/${encodeURIComponent(e)}`,t)}async get(e){return this.http.get(`${this.basePath}/${encodeURIComponent(e)}`)}async delete(e){return this.http.delete(`${this.basePath}/${encodeURIComponent(e)}`)}async search(e){let t=await this.http.post(`${this.basePath}/search`,e);return this.createNavigablePage(t,r=>this.search({...e,page:r}))}};var E=class extends o{constructor(e){super(e,"/v1/tags")}async list(e){let t=await this.http.get(this.basePath,e);return new n(t,r=>this.list({...e,page:r}))}async create(e){return this.http.post(this.basePath,e)}async update(e,t){return this.http.put(`${this.basePath}/${encodeURIComponent(e)}`,t)}async get(e){return this.http.get(`${this.basePath}/${encodeURIComponent(e)}`)}async delete(e){return this.http.delete(`${this.basePath}/${encodeURIComponent(e)}`)}async search(e){let t=await this.http.post(`${this.basePath}/search`,e);return this.createNavigablePage(t,r=>this.search({...e,page:r}))}};var A=class extends o{constructor(e){super(e,"/v1/expenses")}async list(e){let t=await this.http.get(this.basePath,e);return new n(t,r=>this.list({...e,page:r}))}async create(e){let t={...e,dateTime:a.formatTimestamp(e.dateTime)};return this.http.post(this.basePath,t)}async update(e,t){let r={...t,dateTime:t.dateTime?a.formatTimestamp(t.dateTime):void 0};return this.http.put(`${this.basePath}/${encodeURIComponent(e)}`,r)}async get(e){return this.http.get(`${this.basePath}/${encodeURIComponent(e)}`)}async delete(e){return this.http.delete(`${this.basePath}/${encodeURIComponent(e)}`)}async search(e){let t=await this.http.post(`${this.basePath}/search`,e);return this.createNavigablePage(t,r=>this.search({...e,page:r}))}async updateStatus(e,t){return this.http.put(`${this.basePath}/${e}/status`,t)}};var v=class extends o{constructor(e){super(e,"/v1/notes")}async list(e){let t=await this.http.get(this.basePath,e);return new n(t,r=>this.list({...e,page:r}))}async create(e){let t={...e,dateTime:a.formatTimestamp(e.dateTime)};return this.http.post(this.basePath,t)}async update(e,t){let r={...t,dateTime:a.formatTimestamp(t.dateTime)};return this.http.put(`${this.basePath}/${encodeURIComponent(e)}`,r)}async get(e){return this.http.get(`${this.basePath}/${encodeURIComponent(e)}`)}async delete(e){return this.http.delete(`${this.basePath}/${encodeURIComponent(e)}`)}async search(e){let t=await this.http.post(`${this.basePath}/search`,e);return this.createNavigablePage(t,r=>this.search({...e,page:r}))}};var $=class extends o{constructor(e){super(e,"/v1/pauses")}async list(e){let t=await this.http.get(this.basePath,e);return new n(t,r=>this.list({...e,page:r}))}async create(e){let t={...e,startDateTime:a.formatTimestamp(e.startDateTime),endDateTime:a.formatTimestamp(e.endDateTime)};return this.http.post(this.basePath,t)}async update(e,t){let r={...t,startDateTime:a.formatTimestamp(t.startDateTime),endDateTime:a.formatTimestamp(t.endDateTime)};return this.http.put(`${this.basePath}/${encodeURIComponent(e)}`,r)}async get(e){return this.http.get(`${this.basePath}/${encodeURIComponent(e)}`)}async delete(e){return this.http.delete(`${this.basePath}/${encodeURIComponent(e)}`)}async search(e){let t=await this.http.post(`${this.basePath}/search`,e);return this.createNavigablePage(t,r=>this.search({...e,page:r}))}};var D=class{constructor(e){this.http=e}async getProfile(){return this.http.get("/v1/profiles/me")}async updateProfile(e){return this.http.put("/v1/profiles/me",e)}};var U=class{constructor(e){this.http=e}async get(){return this.http.get("/v1/settings")}async update(e){return this.http.put("/v1/settings",e)}};var N=class extends o{constructor(e){super(e,"/v1/automations")}async list(e){let t=await this.http.get(this.basePath,e);return new n(t,r=>this.list({...e,page:r}))}async create(e){return this.http.post(this.basePath,e)}async update(e,t){return this.http.put(`${this.basePath}/${encodeURIComponent(e)}`,t)}async get(e){return this.http.get(`${this.basePath}/${encodeURIComponent(e)}`)}async delete(e){return this.http.delete(`${this.basePath}/${encodeURIComponent(e)}`)}async search(e){let t=await this.http.post(`${this.basePath}/search`,e);return this.createNavigablePage(t,r=>this.search({...e,page:r}))}};var I=class extends o{constructor(e){super(e,"/v1/documents")}async list(e){let t=await this.http.get(this.basePath,e);return new n(t,r=>this.list({...e,page:r}))}async create(e){return this.http.post(this.basePath,e)}async update(e,t){return this.http.put(`${this.basePath}/${encodeURIComponent(e)}`,t)}async get(e){return this.http.get(`${this.basePath}/${encodeURIComponent(e)}`)}async delete(e){return this.http.delete(`${this.basePath}/${encodeURIComponent(e)}`)}async search(e){let t=await this.http.post(`${this.basePath}/search`,e);return this.createNavigablePage(t,r=>this.search({...e,page:r}))}};var q=class{constructor(e){this.http=e}async get(){return this.http.get("/v1/timer")}async start(e){let t={...e,startDateTime:e.startDateTime?a.formatTimestamp(e.startDateTime):a.formatTimestamp()};return this.http.post("/v1/timer/start",t)}async stop(e){let t=e?{...e,endDateTime:e.endDateTime?a.formatTimestamp(e.endDateTime):a.formatTimestamp()}:{endDateTime:a.formatTimestamp()};return this.http.post("/v1/timer/stop",t)}async pause(e){let t=e?{...e,startDateTime:e.startDateTime?a.formatTimestamp(e.startDateTime):a.formatTimestamp()}:{startDateTime:a.formatTimestamp()};return this.http.post("/v1/timer/pause",t)}async resume(e){let t=e?{...e,endDateTime:e.endDateTime?a.formatTimestamp(e.endDateTime):a.formatTimestamp()}:{endDateTime:a.formatTimestamp()};return this.http.post("/v1/timer/resume",t)}async update(e){let t={...e,startDateTime:e.startDateTime?a.formatTimestamp(e.startDateTime):void 0};return this.http.put("/v1/timer/update",t)}};var L=class extends o{constructor(e){super(e,"/v1/todos")}async list(e){let t=await this.http.get(this.basePath,e);return new n(t,r=>this.list({...e,page:r}))}async create(e){let t={...e,dueDate:e.dueDate?a.formatTimestamp(e.dueDate):void 0};return this.http.post(this.basePath,t)}async update(e,t){let r={...t,dueDate:t.dueDate?a.formatTimestamp(t.dueDate):void 0};return this.http.put(`${this.basePath}/${encodeURIComponent(e)}`,r)}async get(e){return this.http.get(`${this.basePath}/${encodeURIComponent(e)}`)}async delete(e){return this.http.delete(`${this.basePath}/${encodeURIComponent(e)}`)}async search(e){let t=await this.http.post(`${this.basePath}/search`,e);return this.createNavigablePage(t,r=>this.search({...e,page:r}))}};var _=class extends o{constructor(e){super(e,"/v1/webhooks")}async list(e){let t=await this.http.get(this.basePath,e);return new n(t,r=>this.list({...e,page:r}))}async create(e){return this.http.post(this.basePath,e)}async update(e,t){return this.http.put(`${this.basePath}/${encodeURIComponent(e)}`,t)}async get(e){return this.http.get(`${this.basePath}/${encodeURIComponent(e)}`)}async delete(e){return this.http.delete(`${this.basePath}/${encodeURIComponent(e)}`)}async search(e){let t=await this.http.post(`${this.basePath}/search`,e);return this.createNavigablePage(t,r=>this.search({...e,page:r}))}};var S=class extends o{constructor(e){super(e,"/v1/documents")}async get(e){return this.http.get(`${this.basePath}/${encodeURIComponent(e)}`)}async getPdf(e){return this.http.request({method:"GET",url:`${this.basePath}/${encodeURIComponent(e)}/pdf`,responseType:"arraybuffer"})}async getXml(e){return this.http.request({method:"GET",url:`${this.basePath}/${encodeURIComponent(e)}/xml`,headers:{Accept:"application/xml"}})}};var O=class extends o{constructor(e){super(e,"/v1/tasks")}async get(e){return this.http.get(`${this.basePath}/${encodeURIComponent(e)}`)}async getPdf(e){return this.http.request({method:"GET",url:`${this.basePath}/${encodeURIComponent(e)}/pdf`,responseType:"arraybuffer"})}};var M=class extends o{constructor(e){super(e,"/v1/expenses")}async get(e){return this.http.get(`${this.basePath}/${encodeURIComponent(e)}`)}async getPdf(e){return this.http.request({method:"GET",url:`${this.basePath}/${encodeURIComponent(e)}/pdf`,responseType:"arraybuffer"})}};var z=class extends o{constructor(e){super(e,"/v1/notes")}async get(e){return this.http.get(`${this.basePath}/${encodeURIComponent(e)}`)}async getPdf(e){return this.http.request({method:"GET",url:`${this.basePath}/${encodeURIComponent(e)}/pdf`,responseType:"arraybuffer"})}};var F=class extends o{constructor(e){super(e,"/v1/export")}async generate(e){return this.http.post(`${this.basePath}/data`,e)}async send(e){return this.http.post(`${this.basePath}/send`,e)}async generateFromTemplate(e){return this.http.request({method:"POST",url:`${this.basePath}/from-template`,data:e,responseType:"arraybuffer"})}async getFields(e){return this.http.get(`${this.basePath}/fields`,e?{scope:e}:void 0)}async getReportTypes(){return this.http.get(`${this.basePath}/report-types`)}async listTemplates(e){let t=await this.http.get(`${this.basePath}/templates`,e);return new n(t,r=>this.listTemplates({...e,page:r}))}async searchTemplates(e){let t=await this.http.post(`${this.basePath}/templates/search`,e);return this.createNavigablePage(t,r=>this.searchTemplates({...e,page:r}))}async createTemplate(e){return this.http.post(`${this.basePath}/templates`,e)}async getTemplate(e){return this.http.get(`${this.basePath}/templates/${encodeURIComponent(e)}`)}async updateTemplate(e,t){return this.http.put(`${this.basePath}/templates/${encodeURIComponent(e)}`,t)}async deleteTemplate(e){return this.http.delete(`${this.basePath}/templates/${encodeURIComponent(e)}`)}async listCustomFields(e){return this.http.get(`${this.basePath}/custom-fields`,e?{scope:e}:void 0)}async createCustomField(e){return this.http.post(`${this.basePath}/custom-fields`,e)}async getCustomField(e){return this.http.get(`${this.basePath}/custom-fields/${encodeURIComponent(e)}`)}async updateCustomField(e,t){return this.http.put(`${this.basePath}/custom-fields/${encodeURIComponent(e)}`,t)}async deleteCustomField(e){return this.http.delete(`${this.basePath}/custom-fields/${encodeURIComponent(e)}`)}};var j=class{constructor(e){this.documents=new S(e),this.tasks=new O(e),this.expenses=new M(e),this.notes=new z(e),this.export=new F(e)}};var J=class{constructor(e){let t=this.createAuthentication(e),r=e.retryConfig||H.default(),p={baseUrl:e.baseUrl||"https://api.timesheet.io",authentication:t,retryConfig:r,httpClient:e.httpClient};this.apiClient=new y(p);let i={baseUrl:e.reportsBaseUrl||"https://reports.timesheet.io",authentication:t,retryConfig:r,httpClient:e.reportsHttpClient};this.reportsApiClient=new y(i),this.organizations=new b(this.apiClient),this.teams=new x(this.apiClient),this.projects=new C(this.apiClient),this.tasks=new k(this.apiClient),this.rates=new w(this.apiClient),this.tags=new E(this.apiClient),this.expenses=new A(this.apiClient),this.notes=new v(this.apiClient),this.pauses=new $(this.apiClient),this.profile=new D(this.apiClient),this.settings=new U(this.apiClient),this.automations=new N(this.apiClient),this.documents=new I(this.apiClient),this.timer=new q(this.apiClient),this.todos=new L(this.apiClient),this.webhooks=new _(this.apiClient),this.reports=new j(this.reportsApiClient)}createAuthentication(e){if(e.apiKey)return new K(e.apiKey);if(e.oauth2Token)return new R(e.oauth2Token);if(e.oauth2)return new R(e.oauth2.clientId,e.oauth2.clientSecret,e.oauth2.refreshToken);if(e.authentication)return e.authentication;throw new Error("Authentication must be configured")}};function Ce(s){return new J(s)}0&&(module.exports={ApiClient,ApiKeyAuth,AutomationResource,DocumentReportResource,DocumentResource,ExpenseReportResource,ExpenseResource,ExportResource,NavigablePage,NoteReportResource,NoteResource,OAuth21Auth,OAuth2Auth,OrganizationResource,PauseResource,ProfileResource,ProjectResource,RateResource,ReportsClient,Resource,RetryConfig,SettingsResource,TagResource,TaskReportResource,TaskResource,TeamResource,TimerResource,TimesheetApiError,TimesheetAuthError,TimesheetClient,TimesheetRateLimitError,TodoResource,WebhookEvents,WebhookResource,combineWebhookEvents,createClient,generateCodeChallenge,generateCodeVerifier,generatePkceCodePair,isValidCodeVerifier});
2
2
  //# sourceMappingURL=index.js.map