@stackone/connect-sdk 1.61.0 → 1.63.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.mts CHANGED
@@ -1,5 +1,4 @@
1
1
  import { ZodType } from "@stackone/utils";
2
- import { IOlapClient } from "@stackone/olap";
3
2
  import http from "node:http";
4
3
  import https from "node:https";
5
4
 
@@ -23,18 +22,6 @@ type CompositeIdentifierConnectorConfig = {
23
22
  fields?: ComponentFieldConfig[];
24
23
  };
25
24
  //#endregion
26
- //#region ../core/src/cursor/types.d.ts
27
- type Position = {
28
- pageNumber?: number | null;
29
- providerPageCursor?: string | null;
30
- position?: number | null;
31
- };
32
- type Cursor = {
33
- remote: Record<number, Position>;
34
- version: number;
35
- timestamp: number;
36
- };
37
- //#endregion
38
25
  //#region ../logger/src/types.d.ts
39
26
  interface ILogger {
40
27
  debug({
@@ -280,6 +267,174 @@ declare enum StepFunctionName {
280
267
  STATIC_VALUES = "static_values",
281
268
  }
282
269
  //#endregion
270
+ //#region ../olap/src/olap/olapOptions.d.ts
271
+ type OlapOptions = {
272
+ logs?: LogsOptions;
273
+ advanced?: AdvancedOptions;
274
+ };
275
+ type LogsOptions = {
276
+ enabled?: boolean;
277
+ };
278
+ type AdvancedOptions = {
279
+ enabled?: boolean;
280
+ ttl?: number;
281
+ errorsOnly?: boolean;
282
+ };
283
+ //#endregion
284
+ //#region ../olap/src/types.d.ts
285
+ interface IOlapClient {
286
+ recordAction(actionResult: ActionResult, options?: OlapOptions): void;
287
+ recordStep(stepResult: StepResult, options?: OlapOptions): void;
288
+ }
289
+ type ActionResult = {
290
+ actionRunId: string;
291
+ actionId: string;
292
+ connectorKey: string;
293
+ connectorVersion: string;
294
+ mode?: string;
295
+ category?: string;
296
+ organizationId: string;
297
+ projectSecureId: string;
298
+ accountSecureId: string;
299
+ originOwnerId?: string;
300
+ originOwnerName?: string;
301
+ httpMethod?: string;
302
+ url?: string;
303
+ path?: string;
304
+ sourceId?: string;
305
+ sourceType?: string;
306
+ sourceValue?: string;
307
+ resource?: string;
308
+ subResource?: string;
309
+ childResource?: string;
310
+ status?: string;
311
+ message?: string;
312
+ outputs?: unknown;
313
+ startTime?: Date;
314
+ endTime?: Date;
315
+ };
316
+ type StepResult = {
317
+ actionRunId: string;
318
+ stepId: string;
319
+ status?: string;
320
+ message?: string;
321
+ outputs?: unknown;
322
+ errors?: unknown;
323
+ skipped?: boolean;
324
+ startTime?: Date;
325
+ endTime?: Date;
326
+ };
327
+ //#endregion
328
+ //#region ../core/src/cursor/types.d.ts
329
+ type Position = {
330
+ pageNumber?: number | null;
331
+ providerPageCursor?: string | null;
332
+ position?: number | null;
333
+ };
334
+ type Cursor = {
335
+ remote: Record<number, Position>;
336
+ version: number;
337
+ timestamp: number;
338
+ };
339
+ //#endregion
340
+ //#region ../core/src/settings/types.d.ts
341
+ type Settings = {
342
+ olap: OlapSettings;
343
+ };
344
+ type OlapSettings = {
345
+ logs?: {
346
+ enabled: boolean;
347
+ };
348
+ advanced?: {
349
+ enabled?: boolean;
350
+ ttl?: number;
351
+ errorsOnly?: boolean;
352
+ };
353
+ };
354
+ //#endregion
355
+ //#region ../core/src/blocks/types.d.ts
356
+ type Block = {
357
+ inputs?: {
358
+ [key: string]: unknown;
359
+ };
360
+ connector?: Connector;
361
+ context: BlockContext;
362
+ debug?: DebugParams;
363
+ steps?: StepsSnapshots;
364
+ httpClient?: IHttpClient;
365
+ olapClient?: IOlapClient;
366
+ settings?: Settings;
367
+ logger?: ILogger;
368
+ operation?: Operation;
369
+ credentials?: Credentials;
370
+ outputs?: unknown;
371
+ nextCursor?: Cursor | null;
372
+ response?: {
373
+ statusCode: number;
374
+ successful: boolean;
375
+ message?: string;
376
+ };
377
+ statistics?: BlockStatistics;
378
+ fieldConfigs?: FieldConfig[];
379
+ result?: BlockIndexedRecord[] | BlockIndexedRecord;
380
+ };
381
+ type BlockContext = {
382
+ organizationId?: string;
383
+ projectSecureId: string;
384
+ accountSecureId: string;
385
+ connectorKey: string;
386
+ connectorVersion: string;
387
+ category: Category;
388
+ schema?: string;
389
+ operationType: OperationType;
390
+ authenticationType: string;
391
+ environment: string;
392
+ actionRunId?: string;
393
+ originOwnerId?: string;
394
+ originOwnerName?: string;
395
+ sourceType?: string;
396
+ sourceId?: string;
397
+ sourceValue?: string;
398
+ service: string;
399
+ resource: string;
400
+ subResource?: string;
401
+ childResource?: string;
402
+ };
403
+ type BlockIndexedRecord = {
404
+ id: string;
405
+ remote_id?: string;
406
+ [key: string]: unknown;
407
+ unified_custom_fields?: {
408
+ [key: string]: unknown;
409
+ };
410
+ };
411
+ type EnumMatcherExpression = {
412
+ matchExpression: string;
413
+ value: string;
414
+ };
415
+ type FieldConfig = {
416
+ expression?: string;
417
+ values?: unknown;
418
+ targetFieldKey: string;
419
+ alias?: string;
420
+ type: string;
421
+ custom: boolean;
422
+ hidden: boolean;
423
+ array: boolean;
424
+ enumMapper?: {
425
+ matcher: string | EnumMatcherExpression[];
426
+ };
427
+ properties?: FieldConfig[];
428
+ };
429
+ type DebugParams = {
430
+ custom_mappings?: 'disabled' | 'enabled';
431
+ };
432
+ type Credentials = Record<string, unknown>;
433
+ type BlockStatistics = {
434
+ startTime?: Date;
435
+ endTime?: Date;
436
+ };
437
+ //#endregion
283
438
  //#region ../core/src/stepFunctions/types.d.ts
284
439
  type StepFunction = ({
285
440
  block,
@@ -319,6 +474,7 @@ type StepSnapshot = {
319
474
  skipped?: boolean;
320
475
  message?: string;
321
476
  errors?: StepError[];
477
+ statistics?: StepStatistics;
322
478
  };
323
479
  type StepsSnapshots = {
324
480
  [stepId: string]: StepSnapshot;
@@ -335,8 +491,15 @@ type Step = {
335
491
  successCriteria?: string;
336
492
  condition?: string;
337
493
  };
494
+ type StepStatistics = {
495
+ startTime?: Date;
496
+ endTime?: Date;
497
+ };
338
498
  //#endregion
339
499
  //#region ../core/src/connector/types.d.ts
500
+ declare const ReleaseStages: readonly ["preview", "beta", "ga", "deprecated"];
501
+ type ReleaseStage = (typeof ReleaseStages)[number];
502
+ type ReleaseStages = 'preview' | 'beta' | 'ga' | 'deprecated';
340
503
  type Connector = {
341
504
  title: string;
342
505
  version: string;
@@ -347,10 +510,11 @@ type Connector = {
347
510
  categories?: Category[];
348
511
  authentication?: Authentication;
349
512
  operations?: {
350
- [entrypointUrl: string]: Operation;
513
+ [operationId: string]: Operation;
351
514
  };
352
515
  rateLimit?: RateLimitConfig;
353
516
  concurrency?: ConcurrencyConfig;
517
+ releaseStage?: ReleaseStage;
354
518
  };
355
519
  type Assets = {
356
520
  icon: string;
@@ -377,6 +541,7 @@ type Operation = {
377
541
  context?: string;
378
542
  operationType: OperationType;
379
543
  tags?: string[];
544
+ releaseStage?: ReleaseStage;
380
545
  entrypointUrl?: string;
381
546
  entrypointHttpMethod?: HttpMethod;
382
547
  inputs?: Input[];
@@ -468,93 +633,6 @@ type Authentication = {
468
633
  };
469
634
  };
470
635
  //#endregion
471
- //#region ../core/src/settings/types.d.ts
472
- type Settings = {
473
- olap: OlapSettings;
474
- };
475
- type OlapSettings = {
476
- logs?: {
477
- enabled: boolean;
478
- };
479
- advanced?: {
480
- enabled?: boolean;
481
- ttl?: number;
482
- errorsOnly?: boolean;
483
- };
484
- };
485
- //#endregion
486
- //#region ../core/src/blocks/types.d.ts
487
- type Block = {
488
- inputs?: {
489
- [key: string]: unknown;
490
- };
491
- connector?: Connector;
492
- context: BlockContext;
493
- debug?: DebugParams;
494
- steps?: StepsSnapshots;
495
- httpClient?: IHttpClient;
496
- olapClient?: IOlapClient;
497
- settings?: Settings;
498
- logger?: ILogger;
499
- operation?: Operation;
500
- credentials?: Credentials;
501
- outputs?: unknown;
502
- nextCursor?: Cursor | null;
503
- response?: {
504
- statusCode: number;
505
- successful: boolean;
506
- message?: string;
507
- };
508
- fieldConfigs?: FieldConfig[];
509
- result?: BlockIndexedRecord[] | BlockIndexedRecord;
510
- };
511
- type BlockContext = {
512
- projectSecureId: string;
513
- accountSecureId: string;
514
- connectorKey: string;
515
- connectorVersion: string;
516
- category: Category;
517
- schema?: string;
518
- operationType: OperationType;
519
- authenticationType: string;
520
- environment: string;
521
- actionRunId?: string;
522
- service: string;
523
- resource: string;
524
- subResource?: string;
525
- childResource?: string;
526
- };
527
- type BlockIndexedRecord = {
528
- id: string;
529
- remote_id?: string;
530
- [key: string]: unknown;
531
- unified_custom_fields?: {
532
- [key: string]: unknown;
533
- };
534
- };
535
- type EnumMatcherExpression = {
536
- matchExpression: string;
537
- value: string;
538
- };
539
- type FieldConfig = {
540
- expression?: string;
541
- values?: unknown;
542
- targetFieldKey: string;
543
- alias?: string;
544
- type: string;
545
- custom: boolean;
546
- hidden: boolean;
547
- array: boolean;
548
- enumMapper?: {
549
- matcher: string | EnumMatcherExpression[];
550
- };
551
- properties?: FieldConfig[];
552
- };
553
- type DebugParams = {
554
- custom_mappings?: 'disabled' | 'enabled';
555
- };
556
- type Credentials = Record<string, unknown>;
557
- //#endregion
558
636
  //#region ../core/src/stepFunctions/factory.d.ts
559
637
  declare const StepFunctionsFactory: {
560
638
  build({
@@ -576,7 +654,7 @@ type Account = {
576
654
  providerVersion: string;
577
655
  authConfigKey: string;
578
656
  environment: string;
579
- organizationId: number;
657
+ organizationId: string;
580
658
  secureId: string;
581
659
  credentials?: Record<string, unknown>;
582
660
  projectSecureId: string;
@@ -629,6 +707,10 @@ declare const supportsRefreshAuthentication: (connector: Connector, authConfigKe
629
707
  declare const getTokenExpiresIn: (connector: Connector, authConfigKey: string, environment: string) => number | undefined;
630
708
  declare const getRefreshTokenExpiresIn: (connector: Connector, authConfigKey: string, environment: string) => number | undefined;
631
709
  //#endregion
710
+ //#region src/connectors/releaseStage.d.ts
711
+ declare const isConnectorReleased: (connector: Connector, allowedStages?: string[]) => boolean;
712
+ declare const applyReleaseStageToConnector: (connector: Connector, allowedStages?: string[]) => Connector | undefined;
713
+ //#endregion
632
714
  //#region src/connectors/validators.d.ts
633
715
  type ValidationError = {
634
716
  line: number;
@@ -714,7 +796,8 @@ declare const createBlockContext: ({
714
796
  environment,
715
797
  operation,
716
798
  accountSecureId,
717
- projectSecureId
799
+ projectSecureId,
800
+ organizationId
718
801
  }: {
719
802
  category: Category;
720
803
  connectorKey: string;
@@ -724,6 +807,7 @@ declare const createBlockContext: ({
724
807
  operation?: Operation;
725
808
  accountSecureId: string;
726
809
  projectSecureId: string;
810
+ organizationId: string;
727
811
  }) => BlockContext;
728
812
  //#endregion
729
813
  //#region src/connectors/testOperations.d.ts
@@ -907,4 +991,4 @@ declare const runTestOperations: ({
907
991
  runStepOperationFn?: typeof runStepOperation;
908
992
  }) => Promise<boolean>;
909
993
  //#endregion
910
- export { ConnectSDKError, type ConnectorMeta, type ErrorType, REFRESH_TOKEN_OPERATION_PATH, createBlock, executeStepFunction, getActionsMeta, getActionsMetaFromConnectors, getOperationFromUrl, getRefreshTokenExpiresIn, getTokenExpiresIn, loadConnector, parseOperationInputs, parseYamlConnector, runAction, runConnectorAction, runConnectorOperation, runStepOperation, runTestOperations, supportsRefreshAuthentication, validateYamlConnector };
994
+ export { ConnectSDKError, type ConnectorMeta, type ErrorType, REFRESH_TOKEN_OPERATION_PATH, applyReleaseStageToConnector, createBlock, executeStepFunction, getActionsMeta, getActionsMetaFromConnectors, getOperationFromUrl, getRefreshTokenExpiresIn, getTokenExpiresIn, isConnectorReleased, loadConnector, parseOperationInputs, parseYamlConnector, runAction, runConnectorAction, runConnectorOperation, runStepOperation, runTestOperations, supportsRefreshAuthentication, validateYamlConnector };
package/dist/index.d.ts CHANGED
@@ -1,4 +1,3 @@
1
- import { IOlapClient } from "@stackone/olap";
2
1
  import { ZodType } from "@stackone/utils";
3
2
  import http from "node:http";
4
3
  import https from "node:https";
@@ -23,18 +22,6 @@ type CompositeIdentifierConnectorConfig = {
23
22
  fields?: ComponentFieldConfig[];
24
23
  };
25
24
  //#endregion
26
- //#region ../core/src/cursor/types.d.ts
27
- type Position = {
28
- pageNumber?: number | null;
29
- providerPageCursor?: string | null;
30
- position?: number | null;
31
- };
32
- type Cursor = {
33
- remote: Record<number, Position>;
34
- version: number;
35
- timestamp: number;
36
- };
37
- //#endregion
38
25
  //#region ../logger/src/types.d.ts
39
26
  interface ILogger {
40
27
  debug({
@@ -280,6 +267,174 @@ declare enum StepFunctionName {
280
267
  STATIC_VALUES = "static_values",
281
268
  }
282
269
  //#endregion
270
+ //#region ../olap/src/olap/olapOptions.d.ts
271
+ type OlapOptions = {
272
+ logs?: LogsOptions;
273
+ advanced?: AdvancedOptions;
274
+ };
275
+ type LogsOptions = {
276
+ enabled?: boolean;
277
+ };
278
+ type AdvancedOptions = {
279
+ enabled?: boolean;
280
+ ttl?: number;
281
+ errorsOnly?: boolean;
282
+ };
283
+ //#endregion
284
+ //#region ../olap/src/types.d.ts
285
+ interface IOlapClient {
286
+ recordAction(actionResult: ActionResult, options?: OlapOptions): void;
287
+ recordStep(stepResult: StepResult, options?: OlapOptions): void;
288
+ }
289
+ type ActionResult = {
290
+ actionRunId: string;
291
+ actionId: string;
292
+ connectorKey: string;
293
+ connectorVersion: string;
294
+ mode?: string;
295
+ category?: string;
296
+ organizationId: string;
297
+ projectSecureId: string;
298
+ accountSecureId: string;
299
+ originOwnerId?: string;
300
+ originOwnerName?: string;
301
+ httpMethod?: string;
302
+ url?: string;
303
+ path?: string;
304
+ sourceId?: string;
305
+ sourceType?: string;
306
+ sourceValue?: string;
307
+ resource?: string;
308
+ subResource?: string;
309
+ childResource?: string;
310
+ status?: string;
311
+ message?: string;
312
+ outputs?: unknown;
313
+ startTime?: Date;
314
+ endTime?: Date;
315
+ };
316
+ type StepResult = {
317
+ actionRunId: string;
318
+ stepId: string;
319
+ status?: string;
320
+ message?: string;
321
+ outputs?: unknown;
322
+ errors?: unknown;
323
+ skipped?: boolean;
324
+ startTime?: Date;
325
+ endTime?: Date;
326
+ };
327
+ //#endregion
328
+ //#region ../core/src/cursor/types.d.ts
329
+ type Position = {
330
+ pageNumber?: number | null;
331
+ providerPageCursor?: string | null;
332
+ position?: number | null;
333
+ };
334
+ type Cursor = {
335
+ remote: Record<number, Position>;
336
+ version: number;
337
+ timestamp: number;
338
+ };
339
+ //#endregion
340
+ //#region ../core/src/settings/types.d.ts
341
+ type Settings = {
342
+ olap: OlapSettings;
343
+ };
344
+ type OlapSettings = {
345
+ logs?: {
346
+ enabled: boolean;
347
+ };
348
+ advanced?: {
349
+ enabled?: boolean;
350
+ ttl?: number;
351
+ errorsOnly?: boolean;
352
+ };
353
+ };
354
+ //#endregion
355
+ //#region ../core/src/blocks/types.d.ts
356
+ type Block = {
357
+ inputs?: {
358
+ [key: string]: unknown;
359
+ };
360
+ connector?: Connector;
361
+ context: BlockContext;
362
+ debug?: DebugParams;
363
+ steps?: StepsSnapshots;
364
+ httpClient?: IHttpClient;
365
+ olapClient?: IOlapClient;
366
+ settings?: Settings;
367
+ logger?: ILogger;
368
+ operation?: Operation;
369
+ credentials?: Credentials;
370
+ outputs?: unknown;
371
+ nextCursor?: Cursor | null;
372
+ response?: {
373
+ statusCode: number;
374
+ successful: boolean;
375
+ message?: string;
376
+ };
377
+ statistics?: BlockStatistics;
378
+ fieldConfigs?: FieldConfig[];
379
+ result?: BlockIndexedRecord[] | BlockIndexedRecord;
380
+ };
381
+ type BlockContext = {
382
+ organizationId?: string;
383
+ projectSecureId: string;
384
+ accountSecureId: string;
385
+ connectorKey: string;
386
+ connectorVersion: string;
387
+ category: Category;
388
+ schema?: string;
389
+ operationType: OperationType;
390
+ authenticationType: string;
391
+ environment: string;
392
+ actionRunId?: string;
393
+ originOwnerId?: string;
394
+ originOwnerName?: string;
395
+ sourceType?: string;
396
+ sourceId?: string;
397
+ sourceValue?: string;
398
+ service: string;
399
+ resource: string;
400
+ subResource?: string;
401
+ childResource?: string;
402
+ };
403
+ type BlockIndexedRecord = {
404
+ id: string;
405
+ remote_id?: string;
406
+ [key: string]: unknown;
407
+ unified_custom_fields?: {
408
+ [key: string]: unknown;
409
+ };
410
+ };
411
+ type EnumMatcherExpression = {
412
+ matchExpression: string;
413
+ value: string;
414
+ };
415
+ type FieldConfig = {
416
+ expression?: string;
417
+ values?: unknown;
418
+ targetFieldKey: string;
419
+ alias?: string;
420
+ type: string;
421
+ custom: boolean;
422
+ hidden: boolean;
423
+ array: boolean;
424
+ enumMapper?: {
425
+ matcher: string | EnumMatcherExpression[];
426
+ };
427
+ properties?: FieldConfig[];
428
+ };
429
+ type DebugParams = {
430
+ custom_mappings?: 'disabled' | 'enabled';
431
+ };
432
+ type Credentials = Record<string, unknown>;
433
+ type BlockStatistics = {
434
+ startTime?: Date;
435
+ endTime?: Date;
436
+ };
437
+ //#endregion
283
438
  //#region ../core/src/stepFunctions/types.d.ts
284
439
  type StepFunction = ({
285
440
  block,
@@ -319,6 +474,7 @@ type StepSnapshot = {
319
474
  skipped?: boolean;
320
475
  message?: string;
321
476
  errors?: StepError[];
477
+ statistics?: StepStatistics;
322
478
  };
323
479
  type StepsSnapshots = {
324
480
  [stepId: string]: StepSnapshot;
@@ -335,8 +491,15 @@ type Step = {
335
491
  successCriteria?: string;
336
492
  condition?: string;
337
493
  };
494
+ type StepStatistics = {
495
+ startTime?: Date;
496
+ endTime?: Date;
497
+ };
338
498
  //#endregion
339
499
  //#region ../core/src/connector/types.d.ts
500
+ declare const ReleaseStages: readonly ["preview", "beta", "ga", "deprecated"];
501
+ type ReleaseStage = (typeof ReleaseStages)[number];
502
+ type ReleaseStages = 'preview' | 'beta' | 'ga' | 'deprecated';
340
503
  type Connector = {
341
504
  title: string;
342
505
  version: string;
@@ -347,10 +510,11 @@ type Connector = {
347
510
  categories?: Category[];
348
511
  authentication?: Authentication;
349
512
  operations?: {
350
- [entrypointUrl: string]: Operation;
513
+ [operationId: string]: Operation;
351
514
  };
352
515
  rateLimit?: RateLimitConfig;
353
516
  concurrency?: ConcurrencyConfig;
517
+ releaseStage?: ReleaseStage;
354
518
  };
355
519
  type Assets = {
356
520
  icon: string;
@@ -377,6 +541,7 @@ type Operation = {
377
541
  context?: string;
378
542
  operationType: OperationType;
379
543
  tags?: string[];
544
+ releaseStage?: ReleaseStage;
380
545
  entrypointUrl?: string;
381
546
  entrypointHttpMethod?: HttpMethod;
382
547
  inputs?: Input[];
@@ -468,93 +633,6 @@ type Authentication = {
468
633
  };
469
634
  };
470
635
  //#endregion
471
- //#region ../core/src/settings/types.d.ts
472
- type Settings = {
473
- olap: OlapSettings;
474
- };
475
- type OlapSettings = {
476
- logs?: {
477
- enabled: boolean;
478
- };
479
- advanced?: {
480
- enabled?: boolean;
481
- ttl?: number;
482
- errorsOnly?: boolean;
483
- };
484
- };
485
- //#endregion
486
- //#region ../core/src/blocks/types.d.ts
487
- type Block = {
488
- inputs?: {
489
- [key: string]: unknown;
490
- };
491
- connector?: Connector;
492
- context: BlockContext;
493
- debug?: DebugParams;
494
- steps?: StepsSnapshots;
495
- httpClient?: IHttpClient;
496
- olapClient?: IOlapClient;
497
- settings?: Settings;
498
- logger?: ILogger;
499
- operation?: Operation;
500
- credentials?: Credentials;
501
- outputs?: unknown;
502
- nextCursor?: Cursor | null;
503
- response?: {
504
- statusCode: number;
505
- successful: boolean;
506
- message?: string;
507
- };
508
- fieldConfigs?: FieldConfig[];
509
- result?: BlockIndexedRecord[] | BlockIndexedRecord;
510
- };
511
- type BlockContext = {
512
- projectSecureId: string;
513
- accountSecureId: string;
514
- connectorKey: string;
515
- connectorVersion: string;
516
- category: Category;
517
- schema?: string;
518
- operationType: OperationType;
519
- authenticationType: string;
520
- environment: string;
521
- actionRunId?: string;
522
- service: string;
523
- resource: string;
524
- subResource?: string;
525
- childResource?: string;
526
- };
527
- type BlockIndexedRecord = {
528
- id: string;
529
- remote_id?: string;
530
- [key: string]: unknown;
531
- unified_custom_fields?: {
532
- [key: string]: unknown;
533
- };
534
- };
535
- type EnumMatcherExpression = {
536
- matchExpression: string;
537
- value: string;
538
- };
539
- type FieldConfig = {
540
- expression?: string;
541
- values?: unknown;
542
- targetFieldKey: string;
543
- alias?: string;
544
- type: string;
545
- custom: boolean;
546
- hidden: boolean;
547
- array: boolean;
548
- enumMapper?: {
549
- matcher: string | EnumMatcherExpression[];
550
- };
551
- properties?: FieldConfig[];
552
- };
553
- type DebugParams = {
554
- custom_mappings?: 'disabled' | 'enabled';
555
- };
556
- type Credentials = Record<string, unknown>;
557
- //#endregion
558
636
  //#region ../core/src/stepFunctions/factory.d.ts
559
637
  declare const StepFunctionsFactory: {
560
638
  build({
@@ -576,7 +654,7 @@ type Account = {
576
654
  providerVersion: string;
577
655
  authConfigKey: string;
578
656
  environment: string;
579
- organizationId: number;
657
+ organizationId: string;
580
658
  secureId: string;
581
659
  credentials?: Record<string, unknown>;
582
660
  projectSecureId: string;
@@ -629,6 +707,10 @@ declare const supportsRefreshAuthentication: (connector: Connector, authConfigKe
629
707
  declare const getTokenExpiresIn: (connector: Connector, authConfigKey: string, environment: string) => number | undefined;
630
708
  declare const getRefreshTokenExpiresIn: (connector: Connector, authConfigKey: string, environment: string) => number | undefined;
631
709
  //#endregion
710
+ //#region src/connectors/releaseStage.d.ts
711
+ declare const isConnectorReleased: (connector: Connector, allowedStages?: string[]) => boolean;
712
+ declare const applyReleaseStageToConnector: (connector: Connector, allowedStages?: string[]) => Connector | undefined;
713
+ //#endregion
632
714
  //#region src/connectors/validators.d.ts
633
715
  type ValidationError = {
634
716
  line: number;
@@ -714,7 +796,8 @@ declare const createBlockContext: ({
714
796
  environment,
715
797
  operation,
716
798
  accountSecureId,
717
- projectSecureId
799
+ projectSecureId,
800
+ organizationId
718
801
  }: {
719
802
  category: Category;
720
803
  connectorKey: string;
@@ -724,6 +807,7 @@ declare const createBlockContext: ({
724
807
  operation?: Operation;
725
808
  accountSecureId: string;
726
809
  projectSecureId: string;
810
+ organizationId: string;
727
811
  }) => BlockContext;
728
812
  //#endregion
729
813
  //#region src/connectors/testOperations.d.ts
@@ -907,4 +991,4 @@ declare const runTestOperations: ({
907
991
  runStepOperationFn?: typeof runStepOperation;
908
992
  }) => Promise<boolean>;
909
993
  //#endregion
910
- export { ConnectSDKError, type ConnectorMeta, type ErrorType, REFRESH_TOKEN_OPERATION_PATH, createBlock, executeStepFunction, getActionsMeta, getActionsMetaFromConnectors, getOperationFromUrl, getRefreshTokenExpiresIn, getTokenExpiresIn, loadConnector, parseOperationInputs, parseYamlConnector, runAction, runConnectorAction, runConnectorOperation, runStepOperation, runTestOperations, supportsRefreshAuthentication, validateYamlConnector };
994
+ export { ConnectSDKError, type ConnectorMeta, type ErrorType, REFRESH_TOKEN_OPERATION_PATH, applyReleaseStageToConnector, createBlock, executeStepFunction, getActionsMeta, getActionsMetaFromConnectors, getOperationFromUrl, getRefreshTokenExpiresIn, getTokenExpiresIn, isConnectorReleased, loadConnector, parseOperationInputs, parseYamlConnector, runAction, runConnectorAction, runConnectorOperation, runStepOperation, runTestOperations, supportsRefreshAuthentication, validateYamlConnector };
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},s=(n,r,a)=>(a=n==null?{}:e(i(n)),o(r||!n||!n.__esModule?t(a,`default`,{value:n,enumerable:!0}):a,n));const c=s(require(`@stackone/utils`)),l=s(require(`fs`)),u=s(require(`path`)),d=s(require(`path-to-regexp`)),f=s(require(`@stackone/core`)),p=s(require(`@stackone/transport`)),m=s(require(`yaml`)),h=s(require(`@stackone/expressions`)),g=async({connector:e,inputs:t,context:n,operation:r,credentials:i,nextCursor:a,settings:o,logger:s,getHttpClient:l,getOlapClient:u})=>{if((0,c.isMissing)(l))throw Error(`getHttpClient function is required`);let d=await l(),f=u?await u():void 0;return{connector:e,inputs:t,fieldConfigs:[],context:n,operation:r,credentials:i,nextCursor:a,httpClient:d,olapClient:f,settings:o,logger:s}},_=e=>{if(!e.endsWith(`.s1.yaml`))throw Error(`File must have .s1.yaml extension`);try{let t=(0,l.readFileSync)(e,`utf8`);if(!t.includes(`:`)||!t.includes(`$ref:`))return t;let n=t.split(`
2
2
  `),r=v(n,(0,u.dirname)(e));return r.join(`
3
- `)}catch(e){throw Error(`Failed to process YAML file: ${e.message}`)}},v=(e,t)=>{let n=[];for(let r of e)if(y(r)){let e=r.match(/^(\s*)/)?.[1]?.length||0,i=r.split(`:`)[1]?.trim(),a=b(i,t),o=a.map(t=>` `.repeat(e)+t);n.push(...o)}else n.push(r);return n},y=e=>e.includes(`$ref:`),b=(e,t)=>{let n=(0,u.resolve)((0,u.join)(t,`${e.replaceAll(`'`,``)}.s1.partial.yaml`));try{let e=(0,l.readFileSync)(n,`utf8`);return e.split(`
4
- `).filter(e=>e.trim()!==``)}catch(t){throw Error(`Failed to load partial file '${e}': ${t.message}`)}},x=(e,t,n)=>{let r=n.toUpperCase();if(!e.operations)return;let i=Object.values(e.operations).filter(e=>(0,c.notMissing)(e.endpoint)).map(e=>({operationId:e.id,endpoint:e.endpoint})),a=C(t,r,i);if(a)return{operation:e.operations?.[a.operationId],params:a.params}},S=e=>{let t=e.startsWith(`/`)?e.slice(1):e,n=t.endsWith(`/`)?t.slice(0,-1):t;return n},C=(e,t,n)=>{let r=S(e);for(let e of n)if(e.endpoint?.startsWith(t)){let n=e.endpoint.replace(`${t} `,``).trim(),i=(0,d.match)(S(n)),a=i(S(r));if(a!==!1)return{operationId:e.operationId,path:e.endpoint,params:a.params}}},w=(e,t)=>t?.startsWith(`${e}_`)?t:`${e}_${t}`,ee=(e,t)=>{let n=`${e.key}_`,r=t.startsWith(n)?t:`${n}${t}`;return e.operations?.[r]};var T=class e extends Error{errorType;constructor(t,n){super(n),this.name=`InternalConnectSDKError`,this.errorType=t,Error.captureStackTrace&&Error.captureStackTrace(this,e)}toString(){return`${this.name} [${this.errorType}]: ${this.message}`}},E=class extends T{line;constructor(e,t){super(`INVALID_YAML_FILE_ERROR`,t),this.name=`InvalidYamlFileError`,this.line=e??1}},D=class extends T{issues;constructor(e,t){super(`SCHEMA_VALIDATION_ERROR`,t),this.name=`SchemaValidationError`,this.issues=e}},O=class extends T{operationId;stepId;functionName;functionVersion;constructor(e,t,n,r=`1`){let i=`Invalid Step Function: '${n}' (v${r}) on step '${t}'. Please ensure the function name and version are correct in the operation '${e}'.`;super(`INVALID_STEP_FUNCTION`,i),this.name=`InvalidStepFunctionError`,this.operationId=e,this.stepId=t,this.functionName=n,this.functionVersion=r}},k=class extends T{operationId;stepId;functionName;functionVersion;issues;constructor(e,t,n,r=`1`,i){let a=`Invalid parameters for Step Function: '${n}' (v${r}) on step '${t}'. Please ensure the parameters are correct in the operation '${e}'.`;super(`INVALID_STEP_FUNCTION_PARAMS`,a),this.name=`InvalidStepFunctionParamsError`,this.operationId=e,this.stepId=t,this.functionName=n,this.functionVersion=r,this.issues=i,this.message=a}};const A=25,j=e=>{switch(e){case`list`:return{statusCode:200,description:`The list of records was retrieved.`};case`get`:return{statusCode:200,description:`The record with the given identifier was retrieved.`};case`create`:return{statusCode:201,description:`The record was created successfully.`};case`update`:return{statusCode:200,description:`The record was updated successfully.`};case`delete`:return{statusCode:204,description:`The record was deleted successfully.`};case`custom`:return{statusCode:200,description:`The operation was executed successfully.`};case`refresh_token`:return{statusCode:200,description:`The refresh token operation was executed successfully.`};case`unknown`:return{statusCode:200};default:throw Error(`Unknown operation type: ${e}`)}},M=()=>{let e={400:{statusCode:400,description:`Invalid request.`},401:{statusCode:401,description:`Unauthorized access.`},403:{statusCode:403,description:`Forbidden.`},404:{statusCode:404,description:`Resource not found.`},500:{statusCode:500,description:`Server error while executing the request.`}};return e},N={key:c.z.string(),label:c.z.string(),required:c.z.boolean().optional().default(!1),secret:c.z.boolean().optional().default(!1),readOnly:c.z.boolean().optional().default(!1),placeholder:c.z.string().optional(),description:c.z.string().optional(),tooltip:c.z.string().optional()},P=c.z.discriminatedUnion(`type`,[(0,c.zStrictObject)({...N,type:c.z.enum([`text`,`password`])}),(0,c.zStrictObject)({...N,type:c.z.literal(`select`),options:(0,c.zStrictObject)({value:c.z.string(),label:c.z.string()}).array()})]),te=(0,c.zStrictObject)({targetFieldKey:c.z.string(),alias:c.z.string().optional(),expression:c.z.string().optional(),values:c.z.unknown().optional(),type:c.z.enum([`string`,`number`,`boolean`,`datetime_string`,`enum`,`object`]),array:c.z.boolean().default(!1),custom:c.z.boolean().default(!1),hidden:c.z.boolean().default(!1),enumMapper:(0,c.zStrictObject)({matcher:c.z.enum([`country_alpha2code_by_alpha2code`,`country_alpha3code_by_alpha3code`,`country_code_by_country_code`,`country_name_by_country_name`,`country_name_by_alpha3code`,`country_name_by_alpha2code`,`country_name_by_country_code`,`country_alpha3code_by_alpha2code`,`country_alpha3code_by_country_name`,`country_alpha3code_by_country_code`,`country_alpha2code_by_alpha3code`,`country_alpha2code_by_country_name`,`country_alpha2code_by_country_code`,`country_code_by_alpha2code`,`country_code_by_alpha3code`,`country_code_by_country_name`,`country_subdivisions_by_alpha2code`,`country_subdivision_code_by_subdivision_name`,`country_alpha2code_by_citizenship`,`country_subdivision_name_by_subdivision_code`,`document_file_format_from_extension`]).or((0,c.zStrictObject)({matchExpression:c.z.string(),value:c.z.string()}).array())}).optional(),properties:c.z.lazy(()=>te).array().optional()}),ne=(0,c.zStrictObject)({name:c.z.string(),type:c.z.enum([`string`,`number`,`boolean`,`datetime_string`,`object`]),required:c.z.boolean(),description:c.z.string(),array:c.z.boolean().optional().default(!1),in:c.z.enum([`body`,`query`,`path`,`headers`]),properties:c.z.lazy(()=>ne.omit({in:!0})).array().optional()}),F=(0,c.zStrictObject)({operationId:c.z.string(),categories:c.z.string().array(),operationType:c.z.enum([`list`,`get`,`create`,`update`,`delete`,`custom`,`refresh_token`,`unknown`]),schema:c.z.string().optional(),schemaType:c.z.enum([`native`,`unified`]).optional().default(`native`),entrypointUrl:c.z.string().optional(),entrypointHttpMethod:c.z.string().optional(),label:c.z.string(),description:c.z.string(),tags:c.z.string().array().optional(),context:c.z.string().optional(),responses:(0,c.zStrictObject)({statusCode:c.z.number(),description:c.z.string()}).array().optional(),inputs:ne.array().optional(),cursor:(0,c.zStrictObject)({enabled:c.z.boolean(),pageSize:c.z.number()}).optional(),compositeIdentifiers:(0,c.zStrictObject)({enabled:c.z.boolean(),version:c.z.number().optional(),fields:(0,c.zStrictObject)({targetFieldKey:c.z.string(),remote:c.z.string().optional(),components:c.z.string().array()}).array().optional()}).optional(),scheduledJobs:(0,c.zStrictObject)({enabled:c.z.boolean(),type:c.z.enum([`data_sync`]),schedule:c.z.string(),description:c.z.string(),requestParams:(0,c.zStrictObject)({fields:c.z.string().array().optional(),expand:c.z.string().array().optional(),filter:c.z.record(c.z.string(),c.z.string()).optional()}).optional(),syncFilter:(0,c.zStrictObject)({name:c.z.enum([`updated_after`,`created_after`]),initialLoopbackPeriod:c.z.string(),incrementalLoopbackPeriod:c.z.string()}).optional()}).array().optional(),fieldConfigs:te.array().optional(),steps:(0,c.zStrictObject)({stepId:c.z.string(),description:c.z.string(),stepFunction:(0,c.zStrictObject)({functionName:c.z.string(),version:c.z.string().optional(),parameters:c.z.record(c.z.string(),c.z.unknown())}),condition:c.z.string().optional(),ignoreError:c.z.boolean().optional()}).array(),result:c.z.string().or(c.z.record(c.z.string(),c.z.unknown())).optional()}),re=(0,c.zStrictObject)({schedule:c.z.string().optional(),operation:F.extend({operationType:c.z.literal(`refresh_token`)})}),ie=(0,c.zStrictObject)({mainRatelimit:c.z.number(),subPools:c.z.array((0,c.zStrictObject)({subPoolKey:c.z.string(),urlPattern:c.z.string(),rateLimit:c.z.number()})).optional(),mappedRateLimitErrors:c.z.array((0,c.zStrictObject)({errorStatus:c.z.number(),errorMessage:c.z.string(),errorMessagePath:c.z.string().optional(),retryAfterPath:c.z.string().optional(),retryAfterUnit:c.z.union([c.z.literal(`seconds`),c.z.literal(`milliseconds`),c.z.literal(`date`)]).optional(),retryAfterValue:c.z.number().optional()})).optional()}),ae=(0,c.zStrictObject)({mainMaxConcurrency:c.z.number(),subPools:c.z.array((0,c.zStrictObject)({subPoolKey:c.z.string(),urlPattern:c.z.string(),maxConcurrency:c.z.number()})).optional()}),oe=(0,c.zStrictObject)({StackOne:c.z.string(),info:(0,c.zStrictObject)({title:c.z.string(),version:c.z.string(),key:c.z.string(),assets:(0,c.zStrictObject)({icon:c.z.string()}),description:c.z.string()}),context:c.z.string().optional(),baseUrl:c.z.string(),authentication:c.z.record(c.z.string(),(0,c.zStrictObject)({type:c.z.string(),label:c.z.string(),authorization:f.AUTHENTICATION_SCHEMA,environments:(0,c.zStrictObject)({key:c.z.string(),name:c.z.string()}).array(),support:(0,c.zStrictObject)({link:c.z.string(),description:c.z.string().optional()}),configFields:P.array().optional(),setupFields:P.array().optional(),refreshAuthentication:re.optional(),testOperations:(0,c.zStrictObject)({operation:c.z.string().or(F),condition:c.z.string().optional(),required:c.z.boolean().default(!0)}).array().optional()})).array().optional(),operations:F.array().optional(),rateLimit:ie.optional(),concurrency:ae.optional()}).strict();function I(e){try{let t=(0,m.parse)(e),n=Se(oe,t),r={title:n.info.title,version:n.info.version,key:n.info.key,assets:n.info.assets,description:n.info.description,context:n.context,rateLimit:n.rateLimit,concurrency:n.concurrency},i=le(n),a={baseUrl:n.baseUrl,authentication:L(i)},o=he(n,a);return r.operations=o,se(n.info.key,i,o,a),r.authentication=i,(0,c.notMissing)(o)&&(r.categories=ce(Object.values(o))),r}catch(e){if(e instanceof T)throw e;let t=e.message,n=t.match(/at line (\d+)/),r=n?parseInt(n[1],10):1;throw new E(r,t)}}const L=e=>{let t={};for(let[n,r]of Object.entries(e))if(r&&typeof r==`object`){let{setupFields:e,configFields:i,support:a,refreshAuthentication:o,testOperations:s,...c}=r;t[n]=L(c)}else t[n]=r;return t},se=(e,t,n,r)=>{if(!(!t||!n))for(let i of Object.values(t))for(let t of Object.values(i)){let i=t.testOperations;t.testOperations=i?.map(t=>{if((0,c.notMissing)(t.operation))if(typeof t.operation==`string`){let r=w(e,t.operation),i=Object.values(n).find(e=>e.id===r);if(i)return{...t,operation:i}}else{let n=w(e,t.operation.operationId),i=R(n,t.operation,r);return{...t,operation:i}}return t})}},ce=e=>{let t=e.reduce((e,t)=>{for(let n of t.categories)e.add(n);return e},new Set);return Array.from(t)},le=e=>{let t={};for(let n of e.authentication??[]){let[r]=Object.keys(n),i=n[r].environments.reduce((t,i)=>{let{key:a,name:o}=i,{environments:s,refreshAuthentication:l,testOperations:u,...d}=n[r],f=(0,c.notMissing)(l)?{schedule:l.schedule,operation:R(w(e.info.key,l.operation.operationId),l.operation)}:void 0;return t[a]={...d,refreshAuthentication:f,envKey:a,envName:o,testOperations:u},t},{});t[r]=i}return t},ue=e=>e.entrypointUrl&&e.entrypointHttpMethod?`${e.entrypointHttpMethod.toUpperCase()} ${e.entrypointUrl}`:void 0,de=e=>e.operationType===`list`?`GET /${e.schema}`:`GET /${e.schema}/:id`,fe=e=>{if(e.operationType!==`refresh_token`)return e.entrypointHttpMethod??`get`},pe=e=>{if(!(e.operationType===`refresh_token`||(0,c.isMissing)(e.schema)))return e.operationType===`list`?`/${e.schema}`:`/${e.schema}/:id`},me=e=>{let t={success:j(e.operationType),errors:M()},n=e.responses?.reduce((e,t)=>{let n=(0,p.isSuccessStatusCode)(t.statusCode);return n?e.success={statusCode:t.statusCode,description:t.description}:e.errors[t.statusCode]={statusCode:t.statusCode,description:t.description},e},t);return n??t},he=(e,t)=>{let n=e.operations?.reduce((n,r)=>{let i=ue(r),a=de(r),o=i??a,s=w(e.info.key,r.operationId);return n[s]=R(s,r,t,o),n},{});return n},R=(e,t,n,r)=>{let i=pe(t),a=me(t),o=ve(t),s=t.inputs||[];o.enabled&&(s?.push({type:`string`,name:`page_size`,in:`query`,required:!1,description:`Number of items to return per page`,array:!1}),s?.push({type:`string`,name:`next`,in:`query`,required:!1,description:`Token for the next page of results`,array:!1}));let c=fe(t);return{id:e,categories:t.categories,label:t.label,description:t.description,operationType:t.operationType,schemaType:t.schemaType??`native`,entrypointUrl:t.entrypointUrl??i,entrypointHttpMethod:c,endpoint:r,tags:t.tags,context:t.context,responses:a,cursor:o,compositeIdentifiers:ye(t),scheduledJobs:be(t),inputs:s,steps:t.steps.reduce((e,r)=>{let{customErrors:i,...a}=r.stepFunction.parameters??{},o={id:r.stepId,description:r.description,condition:r.condition,ignoreError:r.ignoreError,stepFunction:{functionName:r.stepFunction.functionName,version:r.stepFunction.version,params:{...xe({stepFunctionName:r.stepFunction.functionName,baseRequestParams:n,customErrors:i}),...r.stepFunction.functionName===`map_fields`||r.stepFunction.functionName===`typecast`?{fields:a.fields??t.fieldConfigs}:{},...a}}};return ge(t.operationId,o),e[r.stepId]=o,e},{}),result:t.result}},ge=(e,t)=>{let n=t.stepFunction.version??`1`,r=f.StepFunctionsRegistry[t.stepFunction.functionName]?.[`v${n}`];if(!r)throw new O(e,t.id,t.stepFunction.functionName,n);let i=r.inputSchema;i&&Ce(i,t.stepFunction.params,e,t.id,t.stepFunction.functionName,n)},z=(e,t)=>{if(!e.inputs)return{};let n=_e(e.inputs),r=c.z.object(n).parse(t);return{...r.headers??{},...r.query??{},...r.path??{},...r.body??{}}},_e=e=>{let t=e.reduce((e,t)=>(e[t.in]||(e[t.in]=[]),e[t.in].push(t),e),{}),n={};for(let[e,r]of Object.entries(t)){let t={};for(let e of r){let n=B(e);e.description&&(n=n.describe(e.description)),e.required||(n=n.optional()),t[e.name]=n}Object.keys(t).length>0&&(n[e]=c.z.object(t))}return n},B=e=>{let t;switch(e.type){case`string`:case`datetime_string`:t=c.z.string();break;case`number`:t=c.z.number();break;case`boolean`:t=c.z.boolean();break;case`object`:if(e.properties&&e.properties.length>0){let n={};for(let t of e.properties){let e=B(t);t.description&&(e=e.describe(t.description)),t.required||(e=e.optional()),n[t.name]=e}t=c.z.object(n)}else t=c.z.record(c.z.string(),c.z.unknown());break;default:t=c.z.unknown()}return e.array&&(t=c.z.array(t)),t},ve=e=>{let t=e.operationType===`list`,n=e.cursor??{enabled:t,pageSize:A};return{enabled:n.enabled&&t,pageSize:n.pageSize}},ye=e=>{if(e.operationType===`refresh_token`)return{enabled:!1};if((0,c.isMissing)(e.compositeIdentifiers)){let t=e.fieldConfigs?.find(e=>e.targetFieldKey===`id`),n=(0,c.notMissing)(t)?[{targetFieldKey:t.targetFieldKey,remote:`id`,components:[{name:t.targetFieldKey,alias:t.alias}]}]:void 0;return{enabled:!0,version:f.COMPOSITE_ID_LATEST_VERSION,fields:n}}let t=[];for(let n of e.compositeIdentifiers?.fields??[]){let r=n.components.map(t=>{let n=e.fieldConfigs?.find(e=>e.targetFieldKey===t);return{name:t,alias:n?.alias}});t.push({targetFieldKey:n.targetFieldKey,remote:n.remote,components:r})}return{enabled:e.compositeIdentifiers.enabled,version:e.compositeIdentifiers.version,fields:t.length>0?t:void 0}},be=e=>{if(!(0,c.isMissing)(e.scheduledJobs))return e.scheduledJobs},xe=({stepFunctionName:e,baseRequestParams:t,customErrors:n={}})=>{if(e===`request`||e===`paginated_request`){let e=[{receivedStatus:500,targetStatus:502}],r=n&&Array.isArray(n)?n:[],i=[...r,...e];return{...t,customErrors:i}}else return{}},Se=(e,t)=>{let n=e.safeParse(t);if(n.success)return n.data;{let e=n.error.issues.map(e=>({code:e.code,message:e.message,input:e.input,path:e.path,keys:e?.keys??[]}));throw new D(e,`Invalid connector schema`)}},Ce=(e,t,n,r,i,a)=>{let o=e.safeParse(t);if(o.success)return o.data;{let e=o.error.issues.map(e=>({code:e.code,message:e.message,input:e.input,path:e.path,keys:e?.keys??[]}));throw new k(n,r,i,a,e)}},V=(e,t,n)=>{if(e.authentication?.[t]?.[n]?.authorization.type!==`oauth2`)return;let r=e.authentication?.[t]?.[n]?.refreshAuthentication?.operation;if((0,c.notMissing)(r))return{operation:r,params:{}}},we=(e,t,n)=>{if(e.authentication?.[t]?.[n]?.authorization.type!==`oauth2`)return!1;let r=V(e,t,n);return(0,c.notMissing)(r)},Te=(e,t,n)=>{let r=e.authentication?.[t]?.[n]?.authorization;if(r?.type===`oauth2`)return r?.tokenExpiresIn},Ee=(e,t,n)=>{let r=e.authentication?.[t]?.[n]?.authorization;if(r?.type===`oauth2`)return r?.tokenRefreshExpiresIn},De=e=>{try{let t=I(e);return{success:!0,connector:t}}catch(t){if(t instanceof D){let n=t.issues,r=[];return n.forEach(t=>{let n=t?.keys?.[0],i=(0,c.isMissing)(n)?t.path:[...t.path,n],a=Oe(i,e);r.push({line:a,message:t.message,field:i.join(`.`)})}),{success:!1,errors:r}}else if(t instanceof E)return{success:!1,errors:[{line:t.line,message:`The YAML connector file is not valid. Please check the syntax and structure.`,field:void 0}]};else if(t instanceof O){let n=H(t.operationId,t.stepId,t.functionName,!1,e);return{success:!1,errors:[{line:n,message:t.message,field:void 0}]}}else if(t instanceof k){let n=t.issues,r=[];return n.forEach(n=>{let i=n?.keys?.[0],a=(0,c.isMissing)(i)?n.path:[...n.path,i],o=H(t.operationId,t.stepId,t.functionName,!0,e);r.push({line:o,message:n.message,field:a.join(`.`)})}),{success:!1,errors:r}}}return{success:!1,errors:[{line:1,message:`An unknown error occurred while parsing the connector.`,field:void 0}]}},Oe=(e,t)=>{let n=t.split(`
5
- `),r=0,i=-1,a=0;for(let t=0;t<n.length;t++){let o=n[t],s=o.match(/^(\s*)/)?.[1]?.length||0,l=o.replace(`- `,``).trim();if(l.startsWith(`#`)||l===``||s<=i)continue;let u=(0,c.notMissing)(e[r])?`${String(e[r])}`:``;if((0,c.isMissing)(u))return a+1;if(isNaN(Number(u))){if(l.startsWith(`${u}:`)){if(r===e.length-1)return t+1;i=s,a=t,r++}}else{let e=parseInt(u,10),i=-1;for(let o=t;o<n.length;o++){let s=n[o],c=s.trim();if(c.startsWith(`-`)&&i++,i===e){r++,a=t,t--;break}else t++}}}return a+1},H=(e,t,n,r,i)=>{let a=i.split(`
6
- `),o=1,s=null,l=null;for(let i=0;i<a.length;i++){let u=a[i],d=u.trim();if((0,c.isMissing)(s)&&d===`- operationId: ${e}`){s=e,o=i+1;continue}if((0,c.notMissing)(s)&&(0,c.isMissing)(l)&&d===`- stepId: ${t}`){l=t,o=i+1;continue}if((0,c.notMissing)(s)&&(0,c.notMissing)(l)&&!r&&d.startsWith(`functionName: ${n}`)||(0,c.notMissing)(s)&&(0,c.notMissing)(l)&&r&&d===`parameters:`)return o=i+1,o}return o};var U=class e extends Error{errorType;context;constructor(t,n,r){super(r),this.name=`ConnectSDKError`,this.errorType=t,this.context=n,Error.captureStackTrace&&Error.captureStackTrace(this,e)}toString(){return`${this.name} [${this.errorType}]: ${this.message}`}},ke=class extends U{constructor(e,t){super(`CONNECTOR_PARSE_ERROR`,e,t),this.name=`ConnectorParseError`}},W=class extends U{constructor(e,t){super(`MISSING_OPERATION_ERROR`,e,t),this.name=`MissingOperationError`}},Ae=class extends U{constructor(e,t){super(`INVALID_OPERATION_INPUTS_ERROR`,e,t),this.name=`InvalidOperationInputsError`}},je=class extends U{constructor(e,t){super(`INVALID_CURSOR_ERROR`,e,t),this.name=`InvalidCursorError`}};const Me=(e,t)=>{let n=Object.keys(e.authentication??{}).map(t=>({type:`custom`,label:e.authentication?.[t].production?.label||`Custom`,key:t})),r=Object.values(e?.operations??{}).map(e=>({id:e.id,description:e.description.replace(/\b\w/g,e=>e.toUpperCase()),label:e.label.replace(/\b\w/g,e=>e.toUpperCase()),schema_type:e.schemaType,tags:e.tags,authentication:n,operation_details:t?.includes(`operation_details`)?e:void 0}));return{version:e.version,name:e.title,key:e.key,icon:e.assets?.icon,description:e.description,authentication:n,actions:r}},Ne=(e,t)=>e.map(e=>Me(e,t)),Pe=`stackone://internal//`,Fe=`${Pe}refresh_token`,Ie=async({block:e,stepFunctionName:t,params:n,buildStepFunction:r=f.StepFunctionsFactory.build})=>{let i=r({functionName:t}).fn,a=await i({block:e,params:n}),o=t===f.StepFunctionName.MAP_FIELDS?{[f.StepFunctionName.MAP_FIELDS.toString()]:{output:{data:a.block.result},errors:a.errors,successful:a.successful}}:{};return{...a.block,steps:{...a?.block?.steps??{},...o}}},G=({category:e,connectorKey:t,connectorVersion:n,authConfigKey:r,environment:i=`production`,operation:a,accountSecureId:o,projectSecureId:s})=>({projectSecureId:s,accountSecureId:o,connectorKey:t,connectorVersion:n,category:e,service:``,resource:``,schema:a?.schema?.key,operationType:a?.operationType??`unknown`,authenticationType:r,environment:i,actionRunId:(0,c.generateActionRunId)()}),Le=(e,t,n)=>e.authentication?.[t]?.[n]?.testOperations,Re=e=>{let t=e.operation?.compositeIdentifiers,n={...e.inputs??{}};if(!t?.enabled||(0,c.isMissing)(n))return e;let r=t.fields?.reduce((e,t)=>(t.components.forEach(t=>{t.alias&&(e[t.name]=t.alias)}),e),{}),i={version:t.version??f.COMPOSITE_ID_LATEST_VERSION,aliases:r};return K(n,i,e.logger),{...e,inputs:n}},K=(e,t,n)=>{for(let r in e){let i=e[r];if(typeof i==`string`||Array.isArray(i)&&i.every(e=>typeof e==`string`))We(i,r,e,t,n);else if(Array.isArray(i))for(let e of i)K(e,t,n);else typeof i==`object`&&i&&K(i,t,n)}},ze=(e,t,n,r)=>{let i=[],a=[];for(let o of e)try{let e=(0,f.decodeCompositeId)(o,n);i.push(e)}catch(e){r?.debug({message:`Received ${t} with invalid composite ID, assuming it is not a composite ID`,category:`processCompositeId`,context:{key:t,inputElement:o,compositeIdentifierConfig:n,error:e}}),a.push(o)}return{compositeIdComponents:i,nonCompositeIds:a}},Be=(e,t,n,r)=>{let i=n.filter(e=>Object.keys(e).length>1);i.length>0&&(e.decoded_ids={...e.decoded_ids??{},[t]:r?i:i[0]})},Ve=e=>{let t=Object.values(e);return t.length===1&&(typeof t[0]==`string`||typeof t[0]==`number`)},He=(e,t,n,r,i)=>{n.every(Ve)&&(i?e[t]=[...n.map(e=>Object.values(e)[0]),...r]:n.length>0&&(e[t]=Object.values(n[0])[0]))},Ue=(e,t,n)=>{e instanceof f.CoreError&&e.type===`COMPOSITE_ID_MISSING_HEADER_ERROR`?n?.debug({message:`Received ${t} with no composite ID header, assuming it is not a composite ID`}):n?.warning({message:`Error processing composite ID for ${t}, ignoring it`,error:e})},We=(e,t,n,r,i)=>{try{let a=Array.isArray(e),o=a?e:[e];if(o.length===0)return;let{compositeIdComponents:s,nonCompositeIds:c}=ze(o,t,r,i);Be(n,t,s,a),He(n,t,s,c,a)}catch(e){Ue(e,t,i)}},q=`remote_`,Ge=e=>{let t=e.operation?.compositeIdentifiers;if(!t?.enabled)return e;let n=`data`,r=e.outputs?.[n];if((0,c.isMissing)(r))return e;let i=Array.isArray(r)?r.map(e=>Ke(e,t)):Ke(r,t);return{...e,outputs:{...e.outputs??{},[n]:i}}},Ke=(e,t)=>{let n=qe(e,t),r=J(n);return{...e,...(0,c.isObject)(r)?r:{}}},qe=(e,t)=>{let n=t.version??f.COMPOSITE_ID_LATEST_VERSION,r={};return t.fields?.forEach(t=>{let i={},a=[];t.components.forEach(t=>{t.alias&&(i[t.name]=t.alias),a.push({key:t.name,value:e[t.name]})});let o=a.length===1?a[0]:{identifiers:a},s={version:n,aliases:Object.keys(i).length>0?i:void 0},c=(0,f.encodeCompositeId)(o,s);r[t.targetFieldKey]=c,t.remote&&(r[`${q}${t.remote}`]=e[t.remote])}),{...e,...r}},Je=e=>e===`id`||/.+_id(s)?$/.test(e),Ye=e=>Array.isArray(e)&&e.every(e=>(0,c.isString)(e)&&e.length>0),Xe=(e,t)=>(0,f.isCompositeId)(e)||t.startsWith(q),Ze=(e,t)=>{try{return(0,f.encodeCompositeId)({key:e,value:t},{version:f.COMPOSITE_ID_LATEST_VERSION})}catch{return t}},Qe=(e,t,n)=>{let r=t.map(t=>(0,c.isString)(t)&&t.length>0&&!(0,f.isCompositeId)(t)?Ze(e,t):t);n[e]=r,n[`${q}${e}`]=t},$e=(e,t,n)=>{if(Xe(t,e))return;let r=(0,f.encodeCompositeId)({key:e,value:t},{version:f.COMPOSITE_ID_LATEST_VERSION});n[e]=r,n[`remote_${e}`]=t},et=(e,t,n)=>{Ye(t)?Qe(e,t,n):(0,c.isString)(t)&&t.length>0&&$e(e,t,n)},J=e=>{if(Array.isArray(e))return e.map(e=>J(e));if(!(0,c.isObject)(e))return e;let t={...e};for(let[n,r]of Object.entries(e))((0,c.isObject)(r)||Array.isArray(r)&&r.length>0&&(0,c.isObject)(r[0]))&&(t[n]=J(r)),Je(n)&&et(n,r,t);return t},tt=(e,t)=>{let n=Number(e.inputs?.page_size),r=(0,c.notMissing)(e.inputs?.page_size)&&(0,c.isNumber)(n)&&!Number.isNaN(n)?n:e.operation?.cursor?.pageSize??t;return r},nt=(e,t,n,r)=>{let i=(0,c.isMissing)(e)?void 0:e.data,a=Object.keys(n).length+1,o=(0,f.isCursorEmpty)({cursor:r,ignoreStepIndex:a});if(!(0,c.isObject)(e)||(0,c.isMissing)(i)||(i?.length??0)<=t)return{result:e,next:(0,c.notMissing)(r)&&!o?(0,f.minifyCursor)(r):null};let s=r?.remote?.[a]?.pageNumber??1,l=(s-1)*t,u=l+t,d=i.slice(l,u),p=i.length>u||!o,m=(0,f.updateCursor)({cursor:r,stepIndex:a,pageNumber:s+1});return{result:{...e,data:d},next:p?(0,f.minifyCursor)(m):null}},rt=e=>{let t=e.settings?.olap;return(0,c.isMissing)(t)?{}:{logs:t.logs?{enabled:t.logs.enabled}:void 0,advanced:t.advanced?{enabled:t.advanced.enabled,ttl:t.advanced.ttl,errorsOnly:t.advanced.errorsOnly}:void 0}},Y=async({block:e,buildStepFunction:t=f.StepFunctionsFactory.build,virtualPaginateResultFn:n=nt,encodeResultCompositeIds:r=Ge,decodeInputCompositeIds:i=Re})=>{let a=i(e),o=await lt({block:a,buildStepFunction:t,virtualPaginateResultFn:n});return r(o)},it=(e,t)=>e.condition?!(0,h.safeEvaluate)(e.condition,t):!1,at=(e,t,n)=>{let r=e.stepFunction,i=f.StepFunctionsRegistry[e.stepFunction.functionName]?.[`v${e.stepFunction.version??1}`],a=(0,c.notMissing)(i?.inputSchema?.shape)?`cursor`in i?.inputSchema?.shape:!1;return t.operation?.cursor.enabled&&a?{...r.params??{},cursor:{token:t.nextCursor?.remote?.[n]?.providerPageCursor,position:t.nextCursor?.remote?.[n]?.position}}:r.params??{}},ot=(e,t,n,r,i)=>{let a=X({block:e,stepId:t,successful:!1,functionOutput:n}),o=r.ignoreError??!1;return o||(i.hasFatalError=!0,i.errorStatusCode??=n.output?.statusCode??500),a},st=async(e,t,n,r,i,a)=>{let o=n[e],s=o.stepFunction,c=a.buildStepFunction({functionName:s.functionName,version:s.version,validateSchemas:!0}).fn;if(it(o,r))return X({block:r,stepId:e,successful:!0,skipped:!0,message:`Step skipped due to condition not met.`});if(i.hasFatalError)return X({block:r,stepId:e,successful:!1,skipped:!0,message:`Step skipped due to previous error.`});let l=at(o,r,t),u=await c({block:r,params:l});if(u.successful===!1)return ot(r,e,u,o,i);let d=r.operation?.cursor.enabled?(0,f.updateCursor)({cursor:r.nextCursor,stepIndex:t,providerPageCursor:u.output?.next,position:u.output?.position}):void 0;return X({block:{...u.block,nextCursor:d},stepId:e,functionOutput:u})},ct=(e,t,n,r,i)=>{let a=!n.hasFatalError,o=a?e.operation?.responses.success.statusCode??200:n.errorStatusCode??500,s=(0,c.notMissing)(i)&&(0,c.isObject)(i.result)?{next:i.next,...i.result}:r;return{...t,outputs:s,response:{successful:a,statusCode:o,message:a?void 0:e.operation?.responses?.errors?.[o]?.description??p.HttpErrorMessages?.[o]??`Error while processing the request`}}},lt=async({block:e,buildStepFunction:t=f.StepFunctionsFactory.build,virtualPaginateResultFn:n=nt})=>{let r=e.operation?.steps||{},i={...e},a=Object.keys(r),o=tt(e,A),s={hasFatalError:!1,errorStatusCode:null},c={block:e,buildStepFunction:t,virtualPaginateResultFn:n};for(let[e,t]of a.entries())i=await st(t,e,r,i,s,c),dt({block:i,stepId:t});let l=e.operation?.result?ut(e.operation.result,i):void 0,u=e.operation?.cursor.enabled?n(l,o,r,i.nextCursor):void 0;return ct(e,i,s,l,u)},ut=(e,t)=>(0,c.isObject)(e)?(0,h.safeEvaluateRecord)(e,t):(0,h.safeEvaluate)(e,t),X=({block:e,stepId:t,successful:n,functionOutput:r,skipped:i,message:a})=>({...e,steps:{...e.steps,[t]:{successful:n??r?.successful??!1,errors:r?.errors,output:r?.output,skipped:i,message:a}}}),dt=({block:e,stepId:t})=>{let n=e.olapClient;if((0,c.isMissing)(n?.recordStep))return;let r=rt(e);n.recordStep({stepId:t,status:e.steps?.[t]?.successful?`success`:`error`},r)},Z=async e=>{let{pathParams:t={},queryParams:n={},body:r={},headers:i={},parseConnector:a=I,parseOperationInputsFn:o=z,createBlockContextFn:s=G,createBlockFn:l=g,runStepOperationFn:u=Y,getOperationFromUrlFn:d=x,getOperationForRefreshAuthenticationFn:f=V,getTestOperationsFn:p=Le,mode:m,account:_,connector:v,getHttpClient:y,getOlapClient:b,settings:S,logger:C,category:w,...T}=e,E=_.authConfigKey,D=_.environment??`production`,O=_.secureId,k=_.projectSecureId,A=_.credentials,j=s({category:w??`action`,connectorKey:_.providerKey,connectorVersion:_.providerVersion,authConfigKey:E,environment:D,accountSecureId:O,projectSecureId:k}),M;try{M=(0,c.isString)(v)?a(v):v}catch{throw new ke(j,`Error while parsing connector`)}let N={connector:M,context:j,credentials:A,settings:S,logger:C,getHttpClient:y,getOlapClient:b};if(m===`operation_id`){let{operationId:e}=T,a=ee(M,e);if((0,c.isMissing)(a))throw new W(j,`No matching operation found`);let s=await Q({operation:a,blockContext:j,queryParams:n,pathParams:t,body:r,headers:i,parseOperationInputsFn:o,createBlockFn:l,createBlockParams:N,runStepOperationFn:u});return $({block:s}),s}else if(m===`test_operations`){let e=p(M,E,D);if((0,c.isMissing)(e)||e.length===0){let e=await ft(l,N);return $({block:e}),e}j.operationType=`test`;for(let t of e){let e=await l({...N,inputs:void 0,operation:t.operation,nextCursor:void 0}),n=(0,c.notMissing)(t.condition)?(0,h.evaluate)(t.condition,e):!0;if(!n)continue;let r=await u({block:e});if(((0,c.isMissing)(r?.response?.successful)||!r.response.successful)&&t.required){C?.error({code:`TestOperationFailed`,message:`Test operation "${t.operation.id}" failed with error: ${r?.response?.message}`});let e=await pt(l,N);return $({block:e}),e}}let t=await ft(l,N);return $({block:t}),t}else if(m===`refresh_authentication`){let e=f(M,E,D);if((0,c.isMissing)(e))throw new W(j,`No matching operation found`);let t=await Q({operation:e.operation,blockContext:j,queryParams:n,pathParams:e.params,body:r,headers:i,parseOperationInputsFn:o,createBlockFn:l,createBlockParams:N,runStepOperationFn:u});return $({block:t}),t}else if(m===`path`){let{path:e,method:t}=T,a=d(M,e,t);if((0,c.isMissing)(a))throw new W(j,`No matching operation found`);let s=await Q({operation:a.operation,blockContext:j,queryParams:n,pathParams:a.params,body:r,headers:i,parseOperationInputsFn:o,createBlockFn:l,createBlockParams:N,runStepOperationFn:u});return $({block:s}),s}else{let e=await pt(l,N);return $({block:e}),e}},Q=async e=>{let{operation:t,blockContext:n,queryParams:r,pathParams:i,body:a,headers:o,parseOperationInputsFn:s,createBlockFn:c,createBlockParams:l,runStepOperationFn:u}=e;n.operationType=t.operationType,n.schema=t.schema?.key;let d=mt(r,n),f;try{f=s(t,{path:i,query:r,body:a,headers:o})}catch{throw new Ae(n,`Error while parsing operation inputs`)}let p=await c({...l,inputs:f,operation:t,nextCursor:d});return await u({block:p})},ft=async(e,t)=>{let n=await e({...t,inputs:void 0,operation:void 0,nextCursor:void 0});return{...n,response:{successful:!0,statusCode:200}}},pt=async(e,t)=>{let n=await e({...t,inputs:void 0,operation:void 0,nextCursor:void 0});return{...n,response:{successful:!1,statusCode:500}}},mt=(e,t)=>{let n=e?.next,r=(0,c.notMissing)(n)&&t.operationType===`list`?(0,f.expandCursor)(n):void 0;if(r===null)throw new je(t,`Invalid cursor.`);return r},$=({block:e})=>{let t=e.olapClient;if((0,c.isMissing)(t?.recordAction))return;let n=rt(e);t.recordAction({status:e.response?.successful?`success`:`error`,message:e.response?.message,outputs:e.outputs},n)},ht=async({operationId:e,account:t,connector:n,pathParams:r={},queryParams:i={},body:a={},headers:o={},logger:s,getHttpClient:c,getOlapClient:l,parseConnector:u=I,parseOperationInputsFn:d=z,createBlockContextFn:f=G,createBlockFn:p=g,runStepOperationFn:m=Y})=>Z({mode:`operation_id`,operationId:e,account:t,connector:n,pathParams:r,queryParams:i,body:a,headers:o,logger:s,getHttpClient:c,getOlapClient:l,parseConnector:u,parseOperationInputsFn:d,createBlockContextFn:f,createBlockFn:p,runStepOperationFn:m}),gt=async({account:e,connector:t,category:n,path:r,method:i=`get`,queryParams:a={},body:o,headers:s,logger:c,getHttpClient:l,parseConnector:u=I,getOperationFromUrlFn:d=x,getOperationForRefreshAuthenticationFn:f=V,parseOperationInputsFn:p=z,createBlockContextFn:m=G,createBlockFn:h=g,runStepOperationFn:_=Y})=>{let v=_t(r),y=v?await Z({mode:`refresh_authentication`,account:e,connector:t,getOperationForRefreshAuthenticationFn:f,parseConnector:u,logger:c,getHttpClient:l,parseOperationInputsFn:p,createBlockContextFn:m,createBlockFn:h,runStepOperationFn:_}):await Z({mode:`path`,account:e,category:n,connector:t,path:r,method:i,queryParams:a,body:o,headers:s,getOperationFromUrlFn:d,parseConnector:u,logger:c,getHttpClient:l,parseOperationInputsFn:p,createBlockContextFn:m,createBlockFn:h,runStepOperationFn:_});return y},_t=e=>e===Fe,vt=async({account:e,connector:t,logger:n,getHttpClient:r,parseConnector:i=I,getTestOperationsFn:a=Le,createBlockContextFn:o=G,createBlockFn:s=g,runStepOperationFn:c=Y})=>{let l=await Z({mode:`test_operations`,account:e,connector:t,logger:n,getHttpClient:r,parseConnector:i,getTestOperationsFn:a,createBlockContextFn:o,createBlockFn:s,runStepOperationFn:c});return l?.response?.successful??!1};exports.ConnectSDKError=U,exports.REFRESH_TOKEN_OPERATION_PATH=Fe,exports.createBlock=g,exports.executeStepFunction=Ie,exports.getActionsMeta=Me,exports.getActionsMetaFromConnectors=Ne,exports.getOperationFromUrl=x,exports.getRefreshTokenExpiresIn=Ee,exports.getTokenExpiresIn=Te,exports.loadConnector=_,exports.parseOperationInputs=z,exports.parseYamlConnector=I,exports.runAction=Z,exports.runConnectorAction=ht,exports.runConnectorOperation=gt,exports.runStepOperation=Y,exports.runTestOperations=vt,exports.supportsRefreshAuthentication=we,exports.validateYamlConnector=De;
3
+ `)}catch(e){throw Error(`Failed to process YAML file: ${e.message}`)}},v=(e,t)=>{let n=[];for(let r of e)if(y(r)){let e=r.match(/^(\s*)/)?.[1]?.length||0,i=r.split(`:`)[1]?.trim(),a=ee(i,t),o=a.map(t=>` `.repeat(e)+t);n.push(...o)}else n.push(r);return n},y=e=>e.includes(`$ref:`),ee=(e,t)=>{let n=(0,u.resolve)((0,u.join)(t,`${e.replaceAll(`'`,``)}.s1.partial.yaml`));try{let e=(0,l.readFileSync)(n,`utf8`);return e.split(`
4
+ `).filter(e=>e.trim()!==``)}catch(t){throw Error(`Failed to load partial file '${e}': ${t.message}`)}},b=(e,t,n)=>{let r=n.toUpperCase();if(!e.operations)return;let i=Object.values(e.operations).filter(e=>(0,c.notMissing)(e.endpoint)).map(e=>({operationId:e.id,endpoint:e.endpoint})),a=S(t,r,i);if(a)return{operation:e.operations?.[a.operationId],params:a.params}},x=e=>{let t=e.startsWith(`/`)?e.slice(1):e,n=t.endsWith(`/`)?t.slice(0,-1):t;return n},S=(e,t,n)=>{let r=x(e);for(let e of n)if(e.endpoint?.startsWith(t)){let n=e.endpoint.replace(`${t} `,``).trim(),i=(0,d.match)(x(n)),a=i(x(r));if(a!==!1)return{operationId:e.operationId,path:e.endpoint,params:a.params}}},C=(e,t)=>t?.startsWith(`${e}_`)?t:`${e}_${t}`,te=(e,t)=>{let n=`${e.key}_`,r=t.startsWith(n)?t:`${n}${t}`;return e.operations?.[r]};var w=class e extends Error{errorType;constructor(t,n){super(n),this.name=`InternalConnectSDKError`,this.errorType=t,Error.captureStackTrace&&Error.captureStackTrace(this,e)}toString(){return`${this.name} [${this.errorType}]: ${this.message}`}},T=class extends w{line;constructor(e,t){super(`INVALID_YAML_FILE_ERROR`,t),this.name=`InvalidYamlFileError`,this.line=e??1}},E=class extends w{issues;constructor(e,t){super(`SCHEMA_VALIDATION_ERROR`,t),this.name=`SchemaValidationError`,this.issues=e}},D=class extends w{operationId;stepId;functionName;functionVersion;constructor(e,t,n,r=`1`){let i=`Invalid Step Function: '${n}' (v${r}) on step '${t}'. Please ensure the function name and version are correct in the operation '${e}'.`;super(`INVALID_STEP_FUNCTION`,i),this.name=`InvalidStepFunctionError`,this.operationId=e,this.stepId=t,this.functionName=n,this.functionVersion=r}},O=class extends w{operationId;stepId;functionName;functionVersion;issues;constructor(e,t,n,r=`1`,i){let a=`Invalid parameters for Step Function: '${n}' (v${r}) on step '${t}'. Please ensure the parameters are correct in the operation '${e}'.`;super(`INVALID_STEP_FUNCTION_PARAMS`,a),this.name=`InvalidStepFunctionParamsError`,this.operationId=e,this.stepId=t,this.functionName=n,this.functionVersion=r,this.issues=i,this.message=a}};const k=25,A=e=>{switch(e){case`list`:return{statusCode:200,description:`The list of records was retrieved.`};case`get`:return{statusCode:200,description:`The record with the given identifier was retrieved.`};case`create`:return{statusCode:201,description:`The record was created successfully.`};case`update`:return{statusCode:200,description:`The record was updated successfully.`};case`delete`:return{statusCode:204,description:`The record was deleted successfully.`};case`custom`:return{statusCode:200,description:`The operation was executed successfully.`};case`refresh_token`:return{statusCode:200,description:`The refresh token operation was executed successfully.`};case`unknown`:return{statusCode:200};default:throw Error(`Unknown operation type: ${e}`)}},j=()=>{let e={400:{statusCode:400,description:`Invalid request.`},401:{statusCode:401,description:`Unauthorized access.`},403:{statusCode:403,description:`Forbidden.`},404:{statusCode:404,description:`Resource not found.`},500:{statusCode:500,description:`Server error while executing the request.`}};return e},M={key:c.z.string(),label:c.z.string(),required:c.z.boolean().optional().default(!1),secret:c.z.boolean().optional().default(!1),readOnly:c.z.boolean().optional().default(!1),placeholder:c.z.string().optional(),description:c.z.string().optional(),tooltip:c.z.string().optional()},N=c.z.discriminatedUnion(`type`,[(0,c.zStrictObject)({...M,type:c.z.enum([`text`,`password`])}),(0,c.zStrictObject)({...M,type:c.z.literal(`select`),options:(0,c.zStrictObject)({value:c.z.string(),label:c.z.string()}).array()})]),P=(0,c.zStrictObject)({targetFieldKey:c.z.string(),alias:c.z.string().optional(),expression:c.z.string().optional(),values:c.z.unknown().optional(),type:c.z.enum([`string`,`number`,`boolean`,`datetime_string`,`enum`,`object`]),array:c.z.boolean().default(!1),custom:c.z.boolean().default(!1),hidden:c.z.boolean().default(!1),enumMapper:(0,c.zStrictObject)({matcher:c.z.enum([`country_alpha2code_by_alpha2code`,`country_alpha3code_by_alpha3code`,`country_code_by_country_code`,`country_name_by_country_name`,`country_name_by_alpha3code`,`country_name_by_alpha2code`,`country_name_by_country_code`,`country_alpha3code_by_alpha2code`,`country_alpha3code_by_country_name`,`country_alpha3code_by_country_code`,`country_alpha2code_by_alpha3code`,`country_alpha2code_by_country_name`,`country_alpha2code_by_country_code`,`country_code_by_alpha2code`,`country_code_by_alpha3code`,`country_code_by_country_name`,`country_subdivisions_by_alpha2code`,`country_subdivision_code_by_subdivision_name`,`country_alpha2code_by_citizenship`,`country_subdivision_name_by_subdivision_code`,`document_file_format_from_extension`]).or((0,c.zStrictObject)({matchExpression:c.z.string(),value:c.z.string()}).array())}).optional(),properties:c.z.lazy(()=>P).array().optional()}),ne=(0,c.zStrictObject)({name:c.z.string(),type:c.z.enum([`string`,`number`,`boolean`,`datetime_string`,`object`]),required:c.z.boolean(),description:c.z.string(),array:c.z.boolean().optional().default(!1),in:c.z.enum([`body`,`query`,`path`,`headers`]),properties:c.z.lazy(()=>ne.omit({in:!0})).array().optional()}),F=(0,c.zStrictObject)({operationId:c.z.string(),categories:c.z.string().array(),operationType:c.z.enum([`list`,`get`,`create`,`update`,`delete`,`custom`,`refresh_token`,`unknown`]),schema:c.z.string().optional(),schemaType:c.z.enum([`native`,`unified`]).optional().default(`native`),entrypointUrl:c.z.string().optional(),entrypointHttpMethod:c.z.string().optional(),label:c.z.string(),description:c.z.string(),tags:c.z.string().array().optional(),releaseStage:c.z.enum(f.ReleaseStages).optional(),context:c.z.string().optional(),responses:(0,c.zStrictObject)({statusCode:c.z.number(),description:c.z.string()}).array().optional(),inputs:ne.array().optional(),cursor:(0,c.zStrictObject)({enabled:c.z.boolean(),pageSize:c.z.number()}).optional(),compositeIdentifiers:(0,c.zStrictObject)({enabled:c.z.boolean(),version:c.z.number().optional(),fields:(0,c.zStrictObject)({targetFieldKey:c.z.string(),remote:c.z.string().optional(),components:c.z.string().array()}).array().optional()}).optional(),scheduledJobs:(0,c.zStrictObject)({enabled:c.z.boolean(),type:c.z.enum([`data_sync`]),schedule:c.z.string(),description:c.z.string(),requestParams:(0,c.zStrictObject)({fields:c.z.string().array().optional(),expand:c.z.string().array().optional(),filter:c.z.record(c.z.string(),c.z.string()).optional()}).optional(),syncFilter:(0,c.zStrictObject)({name:c.z.enum([`updated_after`,`created_after`]),initialLoopbackPeriod:c.z.string(),incrementalLoopbackPeriod:c.z.string()}).optional()}).array().optional(),fieldConfigs:P.array().optional(),steps:(0,c.zStrictObject)({stepId:c.z.string(),description:c.z.string(),stepFunction:(0,c.zStrictObject)({functionName:c.z.string(),version:c.z.string().optional(),parameters:c.z.record(c.z.string(),c.z.unknown())}),condition:c.z.string().optional(),ignoreError:c.z.boolean().optional()}).array(),result:c.z.string().or(c.z.record(c.z.string(),c.z.unknown())).optional()}),re=(0,c.zStrictObject)({schedule:c.z.string().optional(),operation:F.extend({operationType:c.z.literal(`refresh_token`)})}),ie=(0,c.zStrictObject)({mainRatelimit:c.z.number(),subPools:c.z.array((0,c.zStrictObject)({subPoolKey:c.z.string(),urlPattern:c.z.string(),rateLimit:c.z.number()})).optional(),mappedRateLimitErrors:c.z.array((0,c.zStrictObject)({errorStatus:c.z.number(),errorMessage:c.z.string(),errorMessagePath:c.z.string().optional(),retryAfterPath:c.z.string().optional(),retryAfterUnit:c.z.union([c.z.literal(`seconds`),c.z.literal(`milliseconds`),c.z.literal(`date`)]).optional(),retryAfterValue:c.z.number().optional()})).optional()}),ae=(0,c.zStrictObject)({mainMaxConcurrency:c.z.number(),subPools:c.z.array((0,c.zStrictObject)({subPoolKey:c.z.string(),urlPattern:c.z.string(),maxConcurrency:c.z.number()})).optional()}),oe=(0,c.zStrictObject)({StackOne:c.z.string(),info:(0,c.zStrictObject)({title:c.z.string(),version:c.z.string(),key:c.z.string(),assets:(0,c.zStrictObject)({icon:c.z.string()}),description:c.z.string()}),context:c.z.string().optional(),baseUrl:c.z.string(),authentication:c.z.record(c.z.string(),(0,c.zStrictObject)({type:c.z.string(),label:c.z.string(),authorization:f.AUTHENTICATION_SCHEMA,environments:(0,c.zStrictObject)({key:c.z.string(),name:c.z.string()}).array(),support:(0,c.zStrictObject)({link:c.z.string(),description:c.z.string().optional()}),configFields:N.array().optional(),setupFields:N.array().optional(),refreshAuthentication:re.optional(),testOperations:(0,c.zStrictObject)({operation:c.z.string().or(F),condition:c.z.string().optional(),required:c.z.boolean().default(!0)}).array().optional()})).array().optional(),operations:F.array().optional(),rateLimit:ie.optional(),concurrency:ae.optional(),releaseStage:c.z.enum(f.ReleaseStages).optional()}).strict();function I(e){try{let t=(0,m.parse)(e),n=Ce(oe,t),r={title:n.info.title,version:n.info.version,key:n.info.key,assets:n.info.assets,description:n.info.description,context:n.context,rateLimit:n.rateLimit,concurrency:n.concurrency,releaseStage:n.releaseStage},i=ue(n),a={baseUrl:n.baseUrl,authentication:se(i)},o=ge(n,a);return r.operations=o,ce(n.info.key,i,o,a),r.authentication=i,(0,c.notMissing)(o)&&(r.categories=le(Object.values(o))),r}catch(e){if(e instanceof w)throw e;let t=e.message,n=t.match(/at line (\d+)/),r=n?parseInt(n[1],10):1;throw new T(r,t)}}const se=e=>{let t={};for(let[n,r]of Object.entries(e))if(r&&typeof r==`object`){let{setupFields:e,configFields:i,support:a,refreshAuthentication:o,testOperations:s,...c}=r;t[n]=se(c)}else t[n]=r;return t},ce=(e,t,n,r)=>{if(!(!t||!n))for(let i of Object.values(t))for(let t of Object.values(i)){let i=t.testOperations;t.testOperations=i?.map(t=>{if((0,c.notMissing)(t.operation))if(typeof t.operation==`string`){let r=C(e,t.operation),i=Object.values(n).find(e=>e.id===r);if(i)return{...t,operation:i}}else{let n=C(e,t.operation.operationId),i=L(n,t.operation,r);return{...t,operation:i}}return t})}},le=e=>{let t=e.reduce((e,t)=>{for(let n of t.categories)e.add(n);return e},new Set);return Array.from(t)},ue=e=>{let t={};for(let n of e.authentication??[]){let[r]=Object.keys(n),i=n[r].environments.reduce((t,i)=>{let{key:a,name:o}=i,{environments:s,refreshAuthentication:l,testOperations:u,...d}=n[r],f=(0,c.notMissing)(l)?{schedule:l.schedule,operation:L(C(e.info.key,l.operation.operationId),l.operation)}:void 0;return t[a]={...d,refreshAuthentication:f,envKey:a,envName:o,testOperations:u},t},{});t[r]=i}return t},de=e=>e.entrypointUrl&&e.entrypointHttpMethod?`${e.entrypointHttpMethod.toUpperCase()} ${e.entrypointUrl}`:void 0,fe=e=>e.operationType===`list`?`GET /${e.schema}`:`GET /${e.schema}/:id`,pe=e=>{if(e.operationType!==`refresh_token`)return e.entrypointHttpMethod??`get`},me=e=>{if(!(e.operationType===`refresh_token`||(0,c.isMissing)(e.schema)))return e.operationType===`list`?`/${e.schema}`:`/${e.schema}/:id`},he=e=>{let t={success:A(e.operationType),errors:j()},n=e.responses?.reduce((e,t)=>{let n=(0,p.isSuccessStatusCode)(t.statusCode);return n?e.success={statusCode:t.statusCode,description:t.description}:e.errors[t.statusCode]={statusCode:t.statusCode,description:t.description},e},t);return n??t},ge=(e,t)=>{let n=e.operations?.reduce((n,r)=>{let i=de(r),a=fe(r),o=i??a,s=C(e.info.key,r.operationId);return n[s]=L(s,r,t,o),n},{});return n},L=(e,t,n,r)=>{let i=me(t),a=he(t),o=ye(t),s=t.inputs||[];o.enabled&&(s?.push({type:`string`,name:`page_size`,in:`query`,required:!1,description:`Number of items to return per page`,array:!1}),s?.push({type:`string`,name:`next`,in:`query`,required:!1,description:`Token for the next page of results`,array:!1}));let c=pe(t);return{id:e,categories:t.categories,label:t.label,description:t.description,operationType:t.operationType,schemaType:t.schemaType??`native`,entrypointUrl:t.entrypointUrl??i,entrypointHttpMethod:c,endpoint:r,tags:t.tags,releaseStage:t.releaseStage,context:t.context,responses:a,cursor:o,compositeIdentifiers:be(t),scheduledJobs:xe(t),inputs:s,steps:t.steps.reduce((e,r)=>{let{customErrors:i,...a}=r.stepFunction.parameters??{},o={id:r.stepId,description:r.description,condition:r.condition,ignoreError:r.ignoreError,stepFunction:{functionName:r.stepFunction.functionName,version:r.stepFunction.version,params:{...Se({stepFunctionName:r.stepFunction.functionName,baseRequestParams:n,customErrors:i}),...r.stepFunction.functionName===`map_fields`||r.stepFunction.functionName===`typecast`?{fields:a.fields??t.fieldConfigs}:{},...a}}};return _e(t.operationId,o),e[r.stepId]=o,e},{}),result:t.result}},_e=(e,t)=>{let n=t.stepFunction.version??`1`,r=f.StepFunctionsRegistry[t.stepFunction.functionName]?.[`v${n}`];if(!r)throw new D(e,t.id,t.stepFunction.functionName,n);let i=r.inputSchema;i&&we(i,t.stepFunction.params,e,t.id,t.stepFunction.functionName,n)},R=(e,t)=>{if(!e.inputs)return{};let n=ve(e.inputs),r=c.z.object(n).parse(t);return{...r.headers??{},...r.query??{},...r.path??{},...r.body??{}}},ve=e=>{let t=e.reduce((e,t)=>(e[t.in]||(e[t.in]=[]),e[t.in].push(t),e),{}),n={};for(let[e,r]of Object.entries(t)){let t={};for(let e of r){let n=z(e);e.description&&(n=n.describe(e.description)),e.required||(n=n.optional()),t[e.name]=n}Object.keys(t).length>0&&(n[e]=c.z.object(t))}return n},z=e=>{let t;switch(e.type){case`string`:case`datetime_string`:t=c.z.string();break;case`number`:t=c.z.number();break;case`boolean`:t=c.z.boolean();break;case`object`:if(e.properties&&e.properties.length>0){let n={};for(let t of e.properties){let e=z(t);t.description&&(e=e.describe(t.description)),t.required||(e=e.optional()),n[t.name]=e}t=c.z.object(n)}else t=c.z.record(c.z.string(),c.z.unknown());break;default:t=c.z.unknown()}return e.array&&(t=c.z.array(t)),t},ye=e=>{let t=e.operationType===`list`,n=e.cursor??{enabled:t,pageSize:k};return{enabled:n.enabled&&t,pageSize:n.pageSize}},be=e=>{if(e.operationType===`refresh_token`)return{enabled:!1};if((0,c.isMissing)(e.compositeIdentifiers)){let t=e.fieldConfigs?.find(e=>e.targetFieldKey===`id`),n=(0,c.notMissing)(t)?[{targetFieldKey:t.targetFieldKey,remote:`id`,components:[{name:t.targetFieldKey,alias:t.alias}]}]:void 0;return{enabled:!0,version:f.COMPOSITE_ID_LATEST_VERSION,fields:n}}let t=[];for(let n of e.compositeIdentifiers?.fields??[]){let r=n.components.map(t=>{let n=e.fieldConfigs?.find(e=>e.targetFieldKey===t);return{name:t,alias:n?.alias}});t.push({targetFieldKey:n.targetFieldKey,remote:n.remote,components:r})}return{enabled:e.compositeIdentifiers.enabled,version:e.compositeIdentifiers.version,fields:t.length>0?t:void 0}},xe=e=>{if(!(0,c.isMissing)(e.scheduledJobs))return e.scheduledJobs},Se=({stepFunctionName:e,baseRequestParams:t,customErrors:n={}})=>{if(e===`request`||e===`paginated_request`){let e=[{receivedStatus:500,targetStatus:502}],r=n&&Array.isArray(n)?n:[],i=[...r,...e];return{...t,customErrors:i}}else return{}},Ce=(e,t)=>{let n=e.safeParse(t);if(n.success)return n.data;{let e=n.error.issues.map(e=>({code:e.code,message:e.message,input:e.input,path:e.path,keys:e?.keys??[]}));throw new E(e,`Invalid connector schema`)}},we=(e,t,n,r,i,a)=>{let o=e.safeParse(t);if(o.success)return o.data;{let e=o.error.issues.map(e=>({code:e.code,message:e.message,input:e.input,path:e.path,keys:e?.keys??[]}));throw new O(n,r,i,a,e)}},B=(e,t,n)=>{if(e.authentication?.[t]?.[n]?.authorization.type!==`oauth2`)return;let r=e.authentication?.[t]?.[n]?.refreshAuthentication?.operation;if((0,c.notMissing)(r))return{operation:r,params:{}}},Te=(e,t,n)=>{if(e.authentication?.[t]?.[n]?.authorization.type!==`oauth2`)return!1;let r=B(e,t,n);return(0,c.notMissing)(r)},Ee=(e,t,n)=>{let r=e.authentication?.[t]?.[n]?.authorization;if(r?.type===`oauth2`)return r?.tokenExpiresIn},De=(e,t,n)=>{let r=e.authentication?.[t]?.[n]?.authorization;if(r?.type===`oauth2`)return r?.tokenRefreshExpiresIn},Oe=(e,t=[])=>V(t,e.releaseStage),ke=(e,t=[])=>{if(!Oe(e,t))return;let n={};if(e.operations)for(let[r,i]of Object.entries(e.operations))V(t,i.releaseStage)&&(n[r]=i);return{...e,operations:n}},Ae=e=>e??`ga`,V=(e=[],t)=>{let n=Ae(t);return e.includes(n)},je=e=>{try{let t=I(e);return{success:!0,connector:t}}catch(t){if(t instanceof E){let n=t.issues,r=[];return n.forEach(t=>{let n=t?.keys?.[0],i=(0,c.isMissing)(n)?t.path:[...t.path,n],a=Me(i,e);r.push({line:a,message:t.message,field:i.join(`.`)})}),{success:!1,errors:r}}else if(t instanceof T)return{success:!1,errors:[{line:t.line,message:`The YAML connector file is not valid. Please check the syntax and structure.`,field:void 0}]};else if(t instanceof D){let n=Ne(t.operationId,t.stepId,t.functionName,!1,e);return{success:!1,errors:[{line:n,message:t.message,field:void 0}]}}else if(t instanceof O){let n=t.issues,r=[];return n.forEach(n=>{let i=n?.keys?.[0],a=(0,c.isMissing)(i)?n.path:[...n.path,i],o=Ne(t.operationId,t.stepId,t.functionName,!0,e);r.push({line:o,message:n.message,field:a.join(`.`)})}),{success:!1,errors:r}}}return{success:!1,errors:[{line:1,message:`An unknown error occurred while parsing the connector.`,field:void 0}]}},Me=(e,t)=>{let n=t.split(`
5
+ `),r=0,i=-1,a=0;for(let t=0;t<n.length;t++){let o=n[t],s=o.match(/^(\s*)/)?.[1]?.length||0,l=o.replace(`- `,``).trim();if(l.startsWith(`#`)||l===``||s<=i)continue;let u=(0,c.notMissing)(e[r])?`${String(e[r])}`:``;if((0,c.isMissing)(u))return a+1;if(isNaN(Number(u))){if(l.startsWith(`${u}:`)){if(r===e.length-1)return t+1;i=s,a=t,r++}}else{let e=parseInt(u,10),i=-1;for(let o=t;o<n.length;o++){let s=n[o],c=s.trim();if(c.startsWith(`-`)&&i++,i===e){r++,a=t,t--;break}else t++}}}return a+1},Ne=(e,t,n,r,i)=>{let a=i.split(`
6
+ `),o=1,s=null,l=null;for(let i=0;i<a.length;i++){let u=a[i],d=u.trim();if((0,c.isMissing)(s)&&d===`- operationId: ${e}`){s=e,o=i+1;continue}if((0,c.notMissing)(s)&&(0,c.isMissing)(l)&&d===`- stepId: ${t}`){l=t,o=i+1;continue}if((0,c.notMissing)(s)&&(0,c.notMissing)(l)&&!r&&d.startsWith(`functionName: ${n}`)||(0,c.notMissing)(s)&&(0,c.notMissing)(l)&&r&&d===`parameters:`)return o=i+1,o}return o};var H=class e extends Error{errorType;context;constructor(t,n,r){super(r),this.name=`ConnectSDKError`,this.errorType=t,this.context=n,Error.captureStackTrace&&Error.captureStackTrace(this,e)}toString(){return`${this.name} [${this.errorType}]: ${this.message}`}},Pe=class extends H{constructor(e,t){super(`CONNECTOR_PARSE_ERROR`,e,t),this.name=`ConnectorParseError`}},U=class extends H{constructor(e,t){super(`MISSING_OPERATION_ERROR`,e,t),this.name=`MissingOperationError`}},Fe=class extends H{constructor(e,t){super(`INVALID_OPERATION_INPUTS_ERROR`,e,t),this.name=`InvalidOperationInputsError`}},Ie=class extends H{constructor(e,t){super(`INVALID_CURSOR_ERROR`,e,t),this.name=`InvalidCursorError`}};const Le=(e,t)=>{let n=Object.keys(e.authentication??{}).map(t=>({type:`custom`,label:e.authentication?.[t].production?.label||`Custom`,key:t})),r=Object.values(e?.operations??{}).map(e=>({id:e.id,description:e.description.replace(/\b\w/g,e=>e.toUpperCase()),label:e.label.replace(/\b\w/g,e=>e.toUpperCase()),schema_type:e.schemaType,tags:e.tags,authentication:n,operation_details:t?.includes(`operation_details`)?e:void 0}));return{version:e.version,name:e.title,key:e.key,icon:e.assets?.icon,description:e.description,authentication:n,actions:r}},Re=(e,t)=>e.map(e=>Le(e,t)),ze=`stackone://internal//`,Be=`${ze}refresh_token`,Ve=async({block:e,stepFunctionName:t,params:n,buildStepFunction:r=f.StepFunctionsFactory.build})=>{let i=r({functionName:t}).fn,a=await i({block:e,params:n}),o=t===f.StepFunctionName.MAP_FIELDS?{[f.StepFunctionName.MAP_FIELDS.toString()]:{output:{data:a.block.result},errors:a.errors,successful:a.successful}}:{};return{...a.block,steps:{...a?.block?.steps??{},...o}}},W=({category:e,connectorKey:t,connectorVersion:n,authConfigKey:r,environment:i=`production`,operation:a,accountSecureId:o,projectSecureId:s,organizationId:l})=>({organizationId:l,projectSecureId:s,accountSecureId:o,connectorKey:t,connectorVersion:n,category:e,service:``,resource:``,schema:a?.schema?.key,operationType:a?.operationType??`unknown`,authenticationType:r,environment:i,actionRunId:(0,c.generateActionRunId)()}),He=(e,t,n)=>e.authentication?.[t]?.[n]?.testOperations,Ue=e=>{let t=e.operation?.compositeIdentifiers,n={...e.inputs??{}};if(!t?.enabled||(0,c.isMissing)(n))return e;let r=t.fields?.reduce((e,t)=>(t.components.forEach(t=>{t.alias&&(e[t.name]=t.alias)}),e),{}),i={version:t.version??f.COMPOSITE_ID_LATEST_VERSION,aliases:r};return G(n,i,e.logger),{...e,inputs:n}},G=(e,t,n)=>{for(let r in e){let i=e[r];if(typeof i==`string`||Array.isArray(i)&&i.every(e=>typeof e==`string`))Ye(i,r,e,t,n);else if(Array.isArray(i))for(let e of i)G(e,t,n);else typeof i==`object`&&i&&G(i,t,n)}},We=(e,t,n,r)=>{let i=[],a=[];for(let o of e)try{let e=(0,f.decodeCompositeId)(o,n);i.push(e)}catch(e){r?.debug({message:`Received ${t} with invalid composite ID, assuming it is not a composite ID`,category:`processCompositeId`,context:{key:t,inputElement:o,compositeIdentifierConfig:n,error:e}}),a.push(o)}return{compositeIdComponents:i,nonCompositeIds:a}},Ge=(e,t,n,r)=>{let i=n.filter(e=>Object.keys(e).length>1);i.length>0&&(e.decoded_ids={...e.decoded_ids??{},[t]:r?i:i[0]})},Ke=e=>{let t=Object.values(e);return t.length===1&&(typeof t[0]==`string`||typeof t[0]==`number`)},qe=(e,t,n,r,i)=>{n.every(Ke)&&(i?e[t]=[...n.map(e=>Object.values(e)[0]),...r]:n.length>0&&(e[t]=Object.values(n[0])[0]))},Je=(e,t,n)=>{e instanceof f.CoreError&&e.type===`COMPOSITE_ID_MISSING_HEADER_ERROR`?n?.debug({message:`Received ${t} with no composite ID header, assuming it is not a composite ID`}):n?.warning({message:`Error processing composite ID for ${t}, ignoring it`,error:e})},Ye=(e,t,n,r,i)=>{try{let a=Array.isArray(e),o=a?e:[e];if(o.length===0)return;let{compositeIdComponents:s,nonCompositeIds:c}=We(o,t,r,i);Ge(n,t,s,a),qe(n,t,s,c,a)}catch(e){Je(e,t,i)}},K=`remote_`,Xe=e=>{let t=e.operation?.compositeIdentifiers;if(!t?.enabled)return e;let n=`data`,r=e.outputs?.[n];if((0,c.isMissing)(r))return e;let i=Array.isArray(r)?r.map(e=>Ze(e,t)):Ze(r,t);return{...e,outputs:{...e.outputs??{},[n]:i}}},Ze=(e,t)=>{let n=Qe(e,t),r=q(n);return{...e,...(0,c.isObject)(r)?r:{}}},Qe=(e,t)=>{let n=t.version??f.COMPOSITE_ID_LATEST_VERSION,r={};return t.fields?.forEach(t=>{let i={},a=[];t.components.forEach(t=>{t.alias&&(i[t.name]=t.alias),a.push({key:t.name,value:e[t.name]})});let o=a.length===1?a[0]:{identifiers:a},s={version:n,aliases:Object.keys(i).length>0?i:void 0},c=(0,f.encodeCompositeId)(o,s);r[t.targetFieldKey]=c,t.remote&&(r[`${K}${t.remote}`]=e[t.remote])}),{...e,...r}},$e=e=>e===`id`||/.+_id(s)?$/.test(e),et=e=>Array.isArray(e)&&e.every(e=>(0,c.isString)(e)&&e.length>0),tt=(e,t)=>(0,f.isCompositeId)(e)||t.startsWith(K),nt=(e,t)=>{try{return(0,f.encodeCompositeId)({key:e,value:t},{version:f.COMPOSITE_ID_LATEST_VERSION})}catch{return t}},rt=(e,t,n)=>{let r=t.map(t=>(0,c.isString)(t)&&t.length>0&&!(0,f.isCompositeId)(t)?nt(e,t):t);n[e]=r,n[`${K}${e}`]=t},it=(e,t,n)=>{if(tt(t,e))return;let r=(0,f.encodeCompositeId)({key:e,value:t},{version:f.COMPOSITE_ID_LATEST_VERSION});n[e]=r,n[`remote_${e}`]=t},at=(e,t,n)=>{et(t)?rt(e,t,n):(0,c.isString)(t)&&t.length>0&&it(e,t,n)},q=e=>{if(Array.isArray(e))return e.map(e=>q(e));if(!(0,c.isObject)(e))return e;let t={...e};for(let[n,r]of Object.entries(e))((0,c.isObject)(r)||Array.isArray(r)&&r.length>0&&(0,c.isObject)(r[0]))&&(t[n]=q(r)),$e(n)&&at(n,r,t);return t},ot=(e,t)=>{let n=Number(e.inputs?.page_size),r=(0,c.notMissing)(e.inputs?.page_size)&&(0,c.isNumber)(n)&&!Number.isNaN(n)?n:e.operation?.cursor?.pageSize??t;return r},st=(e,t,n,r)=>{let i=(0,c.isMissing)(e)?void 0:e.data,a=Object.keys(n).length+1,o=(0,f.isCursorEmpty)({cursor:r,ignoreStepIndex:a});if(!(0,c.isObject)(e)||(0,c.isMissing)(i)||(i?.length??0)<=t)return{result:e,next:(0,c.notMissing)(r)&&!o?(0,f.minifyCursor)(r):null};let s=r?.remote?.[a]?.pageNumber??1,l=(s-1)*t,u=l+t,d=i.slice(l,u),p=i.length>u||!o,m=(0,f.updateCursor)({cursor:r,stepIndex:a,pageNumber:s+1});return{result:{...e,data:d},next:p?(0,f.minifyCursor)(m):null}},ct=e=>{let t=e.settings?.olap;return(0,c.isMissing)(t)?{}:{logs:t.logs?{enabled:t.logs.enabled}:void 0,advanced:t.advanced?{enabled:t.advanced.enabled,ttl:t.advanced.ttl,errorsOnly:t.advanced.errorsOnly}:void 0}},J=async({block:e,buildStepFunction:t=f.StepFunctionsFactory.build,virtualPaginateResultFn:n=st,encodeResultCompositeIds:r=Xe,decodeInputCompositeIds:i=Ue})=>{let a=i(e),o=await mt({block:a,buildStepFunction:t,virtualPaginateResultFn:n});return r(o)},lt=(e,t)=>e.condition?!(0,h.safeEvaluate)(e.condition,t):!1,ut=(e,t,n)=>{let r=e.stepFunction,i=f.StepFunctionsRegistry[e.stepFunction.functionName]?.[`v${e.stepFunction.version??1}`],a=(0,c.notMissing)(i?.inputSchema?.shape)?`cursor`in i?.inputSchema?.shape:!1;return t.operation?.cursor.enabled&&a?{...r.params??{},cursor:{token:t.nextCursor?.remote?.[n]?.providerPageCursor,position:t.nextCursor?.remote?.[n]?.position}}:r.params??{}},dt=(e,t,n,r,i)=>{let a=Y({block:e,stepId:t,successful:!1,functionOutput:n}),o=r.ignoreError??!1;return o||(i.hasFatalError=!0,i.errorStatusCode??=n.output?.statusCode??500),a},ft=async(e,t,n,r,i,a)=>{let o=n[e],s=o.stepFunction,c=a.buildStepFunction({functionName:s.functionName,version:s.version,validateSchemas:!0}).fn;if(lt(o,r))return Y({block:r,stepId:e,successful:!0,skipped:!0,message:`Step skipped due to condition not met.`});if(i.hasFatalError)return Y({block:r,stepId:e,successful:!1,skipped:!0,message:`Step skipped due to previous error.`});let l=ut(o,r,t),u=await c({block:r,params:l});if(u.successful===!1)return dt(r,e,u,o,i);let d=r.operation?.cursor.enabled?(0,f.updateCursor)({cursor:r.nextCursor,stepIndex:t,providerPageCursor:u.output?.next,position:u.output?.position}):void 0;return Y({block:{...u.block,nextCursor:d},stepId:e,functionOutput:u})},pt=(e,t,n,r,i)=>{let a=!n.hasFatalError,o=a?e.operation?.responses.success.statusCode??200:n.errorStatusCode??500,s=(0,c.notMissing)(i)&&(0,c.isObject)(i.result)?{next:i.next,...i.result}:r;return{...t,outputs:s,response:{successful:a,statusCode:o,message:a?void 0:e.operation?.responses?.errors?.[o]?.description??p.HttpErrorMessages?.[o]??`Error while processing the request`}}},mt=async({block:e,buildStepFunction:t=f.StepFunctionsFactory.build,virtualPaginateResultFn:n=st})=>{let r=e.operation?.steps||{},i={...e},a=Object.keys(r),o=ot(e,k),s={hasFatalError:!1,errorStatusCode:null},c={block:e,buildStepFunction:t,virtualPaginateResultFn:n};for(let[e,t]of a.entries())i=await ft(t,e,r,i,s,c),gt({block:i,stepId:t});let l=e.operation?.result?ht(e.operation.result,i):void 0,u=e.operation?.cursor.enabled?n(l,o,r,i.nextCursor):void 0;return pt(e,i,s,l,u)},ht=(e,t)=>(0,c.isObject)(e)?(0,h.safeEvaluateRecord)(e,t):(0,h.safeEvaluate)(e,t),Y=({block:e,stepId:t,successful:n,functionOutput:r,skipped:i,message:a})=>({...e,steps:{...e.steps,[t]:{successful:n??r?.successful??!1,errors:r?.errors,output:r?.output,skipped:i,message:a}}}),gt=({block:e,stepId:t})=>{let n=e.olapClient;if((0,c.isMissing)(n?.recordStep))return;let r=ct(e),i=e.context,a={actionRunId:i.actionRunId??`unknown`,stepId:t,status:e.steps?.[t]?.successful?`successful`:`failed`,skipped:e.steps?.[t]?.skipped,message:e.steps?.[t]?.message};n.recordStep(a,r)},X=async e=>{let{pathParams:t={},queryParams:n={},body:r={},headers:i={},parseConnector:a=I,parseOperationInputsFn:o=R,createBlockContextFn:s=W,createBlockFn:l=g,runStepOperationFn:u=J,getOperationFromUrlFn:d=b,getOperationForRefreshAuthenticationFn:f=B,getTestOperationsFn:p=He,mode:m,account:_,connector:v,getHttpClient:y,getOlapClient:ee,settings:x,logger:S,category:C,...w}=e,T=_.authConfigKey,E=_.environment??`production`,D=_.secureId,O=_.projectSecureId,k=_.organizationId,A=_.credentials,j=s({category:C??`action`,connectorKey:_.providerKey,connectorVersion:_.providerVersion,authConfigKey:T,environment:E,accountSecureId:D,projectSecureId:O,organizationId:k}),M;try{M=(0,c.isString)(v)?a(v):v}catch{throw new Pe(j,`Error while parsing connector`)}let N={connector:M,context:j,credentials:A,settings:x,logger:S,getHttpClient:y,getOlapClient:ee};if(m===`operation_id`){let{operationId:e}=w,a=te(M,e);if((0,c.isMissing)(a))throw new U(j,`No matching operation found`);let s=await Z({operation:a,blockContext:j,queryParams:n,pathParams:t,body:r,headers:i,parseOperationInputsFn:o,createBlockFn:l,createBlockParams:N,runStepOperationFn:u});return $({block:s}),s}else if(m===`test_operations`){let e=p(M,T,E);if((0,c.isMissing)(e)||e.length===0){let e=await _t(l,N);return $({block:e}),e}j.operationType=`test`;for(let t of e){let e=await l({...N,inputs:void 0,operation:t.operation,nextCursor:void 0}),n=(0,c.notMissing)(t.condition)?(0,h.evaluate)(t.condition,e):!0;if(!n)continue;let r=await u({block:e});if(((0,c.isMissing)(r?.response?.successful)||!r.response.successful)&&t.required){S?.error({code:`TestOperationFailed`,message:`Test operation "${t.operation.id}" failed with error: ${r?.response?.message}`});let e=await Q(l,N);return $({block:e}),e}}let t=await _t(l,N);return $({block:t}),t}else if(m===`refresh_authentication`){let e=f(M,T,E);if((0,c.isMissing)(e))throw new U(j,`No matching operation found`);let t=await Z({operation:e.operation,blockContext:j,queryParams:n,pathParams:e.params,body:r,headers:i,parseOperationInputsFn:o,createBlockFn:l,createBlockParams:N,runStepOperationFn:u});return $({block:t}),t}else if(m===`path`){let{path:e,method:t}=w,a=d(M,e,t);if((0,c.isMissing)(a))throw new U(j,`No matching operation found`);let s=await Z({operation:a.operation,blockContext:j,queryParams:n,pathParams:a.params,body:r,headers:i,parseOperationInputsFn:o,createBlockFn:l,createBlockParams:N,runStepOperationFn:u});return $({block:s}),s}else{let e=await Q(l,N);return $({block:e}),e}},Z=async e=>{let{operation:t,blockContext:n,queryParams:r,pathParams:i,body:a,headers:o,parseOperationInputsFn:s,createBlockFn:c,createBlockParams:l,runStepOperationFn:u}=e;n.operationType=t.operationType,n.schema=t.schema?.key;let d=vt(r,n),f;try{f=s(t,{path:i,query:r,body:a,headers:o})}catch{throw new Fe(n,`Error while parsing operation inputs`)}let p=await c({...l,inputs:f,operation:t,nextCursor:d});return await u({block:p})},_t=async(e,t)=>{let n=await e({...t,inputs:void 0,operation:void 0,nextCursor:void 0});return{...n,response:{successful:!0,statusCode:200}}},Q=async(e,t)=>{let n=await e({...t,inputs:void 0,operation:void 0,nextCursor:void 0});return{...n,response:{successful:!1,statusCode:500}}},vt=(e,t)=>{let n=e?.next,r=(0,c.notMissing)(n)&&t.operationType===`list`?(0,f.expandCursor)(n):void 0;if(r===null)throw new Ie(t,`Invalid cursor.`);return r},$=({block:e})=>{let t=e.olapClient;if((0,c.isMissing)(t?.recordAction))return;let n=ct(e),r=e.context,i={actionRunId:e.context.actionRunId||`unknown`,actionId:e.operation?.id||`unknown`,connectorKey:r.connectorKey,connectorVersion:r.connectorVersion,category:r.category,organizationId:r.organizationId||`unknown`,projectSecureId:r.projectSecureId,accountSecureId:r.accountSecureId,originOwnerId:r.originOwnerId,originOwnerName:r.originOwnerName,httpMethod:e.operation?.entrypointHttpMethod,url:e.operation?.entrypointUrl,sourceId:r.sourceId,sourceType:r.sourceType,sourceValue:r.sourceValue,status:e.response?.successful?`success`:`error`,message:e.response?.message,outputs:e.outputs,startTime:e.statistics?.startTime,endTime:e.statistics?.endTime};t.recordAction(i,n)},yt=async({operationId:e,account:t,connector:n,pathParams:r={},queryParams:i={},body:a={},headers:o={},logger:s,getHttpClient:c,getOlapClient:l,parseConnector:u=I,parseOperationInputsFn:d=R,createBlockContextFn:f=W,createBlockFn:p=g,runStepOperationFn:m=J})=>X({mode:`operation_id`,operationId:e,account:t,connector:n,pathParams:r,queryParams:i,body:a,headers:o,logger:s,getHttpClient:c,getOlapClient:l,parseConnector:u,parseOperationInputsFn:d,createBlockContextFn:f,createBlockFn:p,runStepOperationFn:m}),bt=async({account:e,connector:t,category:n,path:r,method:i=`get`,queryParams:a={},body:o,headers:s,logger:c,getHttpClient:l,parseConnector:u=I,getOperationFromUrlFn:d=b,getOperationForRefreshAuthenticationFn:f=B,parseOperationInputsFn:p=R,createBlockContextFn:m=W,createBlockFn:h=g,runStepOperationFn:_=J})=>{let v=xt(r),y=v?await X({mode:`refresh_authentication`,account:e,connector:t,getOperationForRefreshAuthenticationFn:f,parseConnector:u,logger:c,getHttpClient:l,parseOperationInputsFn:p,createBlockContextFn:m,createBlockFn:h,runStepOperationFn:_}):await X({mode:`path`,account:e,category:n,connector:t,path:r,method:i,queryParams:a,body:o,headers:s,getOperationFromUrlFn:d,parseConnector:u,logger:c,getHttpClient:l,parseOperationInputsFn:p,createBlockContextFn:m,createBlockFn:h,runStepOperationFn:_});return y},xt=e=>e===Be,St=async({account:e,connector:t,logger:n,getHttpClient:r,parseConnector:i=I,getTestOperationsFn:a=He,createBlockContextFn:o=W,createBlockFn:s=g,runStepOperationFn:c=J})=>{let l=await X({mode:`test_operations`,account:e,connector:t,logger:n,getHttpClient:r,parseConnector:i,getTestOperationsFn:a,createBlockContextFn:o,createBlockFn:s,runStepOperationFn:c});return l?.response?.successful??!1};exports.ConnectSDKError=H,exports.REFRESH_TOKEN_OPERATION_PATH=Be,exports.applyReleaseStageToConnector=ke,exports.createBlock=g,exports.executeStepFunction=Ve,exports.getActionsMeta=Le,exports.getActionsMetaFromConnectors=Re,exports.getOperationFromUrl=b,exports.getRefreshTokenExpiresIn=De,exports.getTokenExpiresIn=Ee,exports.isConnectorReleased=Oe,exports.loadConnector=_,exports.parseOperationInputs=R,exports.parseYamlConnector=I,exports.runAction=X,exports.runConnectorAction=yt,exports.runConnectorOperation=bt,exports.runStepOperation=J,exports.runTestOperations=St,exports.supportsRefreshAuthentication=Te,exports.validateYamlConnector=je;
package/dist/index.mjs CHANGED
@@ -1,6 +1,6 @@
1
- import{generateActionRunId as e,isMissing as t,isNumber as n,isObject as r,isString as i,notMissing as a,z as o,zStrictObject as s}from"@stackone/utils";import{readFileSync as c}from"fs";import{dirname as l,join as u,resolve as d}from"path";import{match as f}from"path-to-regexp";import{AUTHENTICATION_SCHEMA as p,COMPOSITE_ID_LATEST_VERSION as m,CoreError as h,StepFunctionName as g,StepFunctionsFactory as _,StepFunctionsRegistry as v,decodeCompositeId as ee,encodeCompositeId as y,expandCursor as b,isCompositeId as x,isCursorEmpty as te,minifyCursor as S,updateCursor as C}from"@stackone/core";import{HttpErrorMessages as w,isSuccessStatusCode as ne}from"@stackone/transport";import{parse as re}from"yaml";import{evaluate as ie,safeEvaluate as T,safeEvaluateRecord as E}from"@stackone/expressions";const D=async({connector:e,inputs:n,context:r,operation:i,credentials:a,nextCursor:o,settings:s,logger:c,getHttpClient:l,getOlapClient:u})=>{if(t(l))throw Error(`getHttpClient function is required`);let d=await l(),f=u?await u():void 0;return{connector:e,inputs:n,fieldConfigs:[],context:r,operation:i,credentials:a,nextCursor:o,httpClient:d,olapClient:f,settings:s,logger:c}},O=e=>{if(!e.endsWith(`.s1.yaml`))throw Error(`File must have .s1.yaml extension`);try{let t=c(e,`utf8`);if(!t.includes(`:`)||!t.includes(`$ref:`))return t;let n=t.split(`
2
- `),r=k(n,l(e));return r.join(`
3
- `)}catch(e){throw Error(`Failed to process YAML file: ${e.message}`)}},k=(e,t)=>{let n=[];for(let r of e)if(ae(r)){let e=r.match(/^(\s*)/)?.[1]?.length||0,i=r.split(`:`)[1]?.trim(),a=oe(i,t),o=a.map(t=>` `.repeat(e)+t);n.push(...o)}else n.push(r);return n},ae=e=>e.includes(`$ref:`),oe=(e,t)=>{let n=d(u(t,`${e.replaceAll(`'`,``)}.s1.partial.yaml`));try{let e=c(n,`utf8`);return e.split(`
4
- `).filter(e=>e.trim()!==``)}catch(t){throw Error(`Failed to load partial file '${e}': ${t.message}`)}},A=(e,t,n)=>{let r=n.toUpperCase();if(!e.operations)return;let i=Object.values(e.operations).filter(e=>a(e.endpoint)).map(e=>({operationId:e.id,endpoint:e.endpoint})),o=se(t,r,i);if(o)return{operation:e.operations?.[o.operationId],params:o.params}},j=e=>{let t=e.startsWith(`/`)?e.slice(1):e,n=t.endsWith(`/`)?t.slice(0,-1):t;return n},se=(e,t,n)=>{let r=j(e);for(let e of n)if(e.endpoint?.startsWith(t)){let n=e.endpoint.replace(`${t} `,``).trim(),i=f(j(n)),a=i(j(r));if(a!==!1)return{operationId:e.operationId,path:e.endpoint,params:a.params}}},M=(e,t)=>t?.startsWith(`${e}_`)?t:`${e}_${t}`,ce=(e,t)=>{let n=`${e.key}_`,r=t.startsWith(n)?t:`${n}${t}`;return e.operations?.[r]};var N=class e extends Error{errorType;constructor(t,n){super(n),this.name=`InternalConnectSDKError`,this.errorType=t,Error.captureStackTrace&&Error.captureStackTrace(this,e)}toString(){return`${this.name} [${this.errorType}]: ${this.message}`}},P=class extends N{line;constructor(e,t){super(`INVALID_YAML_FILE_ERROR`,t),this.name=`InvalidYamlFileError`,this.line=e??1}},le=class extends N{issues;constructor(e,t){super(`SCHEMA_VALIDATION_ERROR`,t),this.name=`SchemaValidationError`,this.issues=e}},ue=class extends N{operationId;stepId;functionName;functionVersion;constructor(e,t,n,r=`1`){let i=`Invalid Step Function: '${n}' (v${r}) on step '${t}'. Please ensure the function name and version are correct in the operation '${e}'.`;super(`INVALID_STEP_FUNCTION`,i),this.name=`InvalidStepFunctionError`,this.operationId=e,this.stepId=t,this.functionName=n,this.functionVersion=r}},F=class extends N{operationId;stepId;functionName;functionVersion;issues;constructor(e,t,n,r=`1`,i){let a=`Invalid parameters for Step Function: '${n}' (v${r}) on step '${t}'. Please ensure the parameters are correct in the operation '${e}'.`;super(`INVALID_STEP_FUNCTION_PARAMS`,a),this.name=`InvalidStepFunctionParamsError`,this.operationId=e,this.stepId=t,this.functionName=n,this.functionVersion=r,this.issues=i,this.message=a}};const de=25,fe=e=>{switch(e){case`list`:return{statusCode:200,description:`The list of records was retrieved.`};case`get`:return{statusCode:200,description:`The record with the given identifier was retrieved.`};case`create`:return{statusCode:201,description:`The record was created successfully.`};case`update`:return{statusCode:200,description:`The record was updated successfully.`};case`delete`:return{statusCode:204,description:`The record was deleted successfully.`};case`custom`:return{statusCode:200,description:`The operation was executed successfully.`};case`refresh_token`:return{statusCode:200,description:`The refresh token operation was executed successfully.`};case`unknown`:return{statusCode:200};default:throw Error(`Unknown operation type: ${e}`)}},pe=()=>{let e={400:{statusCode:400,description:`Invalid request.`},401:{statusCode:401,description:`Unauthorized access.`},403:{statusCode:403,description:`Forbidden.`},404:{statusCode:404,description:`Resource not found.`},500:{statusCode:500,description:`Server error while executing the request.`}};return e},me={key:o.string(),label:o.string(),required:o.boolean().optional().default(!1),secret:o.boolean().optional().default(!1),readOnly:o.boolean().optional().default(!1),placeholder:o.string().optional(),description:o.string().optional(),tooltip:o.string().optional()},he=o.discriminatedUnion(`type`,[s({...me,type:o.enum([`text`,`password`])}),s({...me,type:o.literal(`select`),options:s({value:o.string(),label:o.string()}).array()})]),ge=s({targetFieldKey:o.string(),alias:o.string().optional(),expression:o.string().optional(),values:o.unknown().optional(),type:o.enum([`string`,`number`,`boolean`,`datetime_string`,`enum`,`object`]),array:o.boolean().default(!1),custom:o.boolean().default(!1),hidden:o.boolean().default(!1),enumMapper:s({matcher:o.enum([`country_alpha2code_by_alpha2code`,`country_alpha3code_by_alpha3code`,`country_code_by_country_code`,`country_name_by_country_name`,`country_name_by_alpha3code`,`country_name_by_alpha2code`,`country_name_by_country_code`,`country_alpha3code_by_alpha2code`,`country_alpha3code_by_country_name`,`country_alpha3code_by_country_code`,`country_alpha2code_by_alpha3code`,`country_alpha2code_by_country_name`,`country_alpha2code_by_country_code`,`country_code_by_alpha2code`,`country_code_by_alpha3code`,`country_code_by_country_name`,`country_subdivisions_by_alpha2code`,`country_subdivision_code_by_subdivision_name`,`country_alpha2code_by_citizenship`,`country_subdivision_name_by_subdivision_code`,`document_file_format_from_extension`]).or(s({matchExpression:o.string(),value:o.string()}).array())}).optional(),properties:o.lazy(()=>ge).array().optional()}),_e=s({name:o.string(),type:o.enum([`string`,`number`,`boolean`,`datetime_string`,`object`]),required:o.boolean(),description:o.string(),array:o.boolean().optional().default(!1),in:o.enum([`body`,`query`,`path`,`headers`]),properties:o.lazy(()=>_e.omit({in:!0})).array().optional()}),I=s({operationId:o.string(),categories:o.string().array(),operationType:o.enum([`list`,`get`,`create`,`update`,`delete`,`custom`,`refresh_token`,`unknown`]),schema:o.string().optional(),schemaType:o.enum([`native`,`unified`]).optional().default(`native`),entrypointUrl:o.string().optional(),entrypointHttpMethod:o.string().optional(),label:o.string(),description:o.string(),tags:o.string().array().optional(),context:o.string().optional(),responses:s({statusCode:o.number(),description:o.string()}).array().optional(),inputs:_e.array().optional(),cursor:s({enabled:o.boolean(),pageSize:o.number()}).optional(),compositeIdentifiers:s({enabled:o.boolean(),version:o.number().optional(),fields:s({targetFieldKey:o.string(),remote:o.string().optional(),components:o.string().array()}).array().optional()}).optional(),scheduledJobs:s({enabled:o.boolean(),type:o.enum([`data_sync`]),schedule:o.string(),description:o.string(),requestParams:s({fields:o.string().array().optional(),expand:o.string().array().optional(),filter:o.record(o.string(),o.string()).optional()}).optional(),syncFilter:s({name:o.enum([`updated_after`,`created_after`]),initialLoopbackPeriod:o.string(),incrementalLoopbackPeriod:o.string()}).optional()}).array().optional(),fieldConfigs:ge.array().optional(),steps:s({stepId:o.string(),description:o.string(),stepFunction:s({functionName:o.string(),version:o.string().optional(),parameters:o.record(o.string(),o.unknown())}),condition:o.string().optional(),ignoreError:o.boolean().optional()}).array(),result:o.string().or(o.record(o.string(),o.unknown())).optional()}),ve=s({schedule:o.string().optional(),operation:I.extend({operationType:o.literal(`refresh_token`)})}),ye=s({mainRatelimit:o.number(),subPools:o.array(s({subPoolKey:o.string(),urlPattern:o.string(),rateLimit:o.number()})).optional(),mappedRateLimitErrors:o.array(s({errorStatus:o.number(),errorMessage:o.string(),errorMessagePath:o.string().optional(),retryAfterPath:o.string().optional(),retryAfterUnit:o.union([o.literal(`seconds`),o.literal(`milliseconds`),o.literal(`date`)]).optional(),retryAfterValue:o.number().optional()})).optional()}),be=s({mainMaxConcurrency:o.number(),subPools:o.array(s({subPoolKey:o.string(),urlPattern:o.string(),maxConcurrency:o.number()})).optional()}),xe=s({StackOne:o.string(),info:s({title:o.string(),version:o.string(),key:o.string(),assets:s({icon:o.string()}),description:o.string()}),context:o.string().optional(),baseUrl:o.string(),authentication:o.record(o.string(),s({type:o.string(),label:o.string(),authorization:p,environments:s({key:o.string(),name:o.string()}).array(),support:s({link:o.string(),description:o.string().optional()}),configFields:he.array().optional(),setupFields:he.array().optional(),refreshAuthentication:ve.optional(),testOperations:s({operation:o.string().or(I),condition:o.string().optional(),required:o.boolean().default(!0)}).array().optional()})).array().optional(),operations:I.array().optional(),rateLimit:ye.optional(),concurrency:be.optional()}).strict();function L(e){try{let t=re(e),n=Re(xe,t),r={title:n.info.title,version:n.info.version,key:n.info.key,assets:n.info.assets,description:n.info.description,context:n.context,rateLimit:n.rateLimit,concurrency:n.concurrency},i=we(n),o={baseUrl:n.baseUrl,authentication:R(i)},s=Ae(n,o);return r.operations=s,Se(n.info.key,i,s,o),r.authentication=i,a(s)&&(r.categories=Ce(Object.values(s))),r}catch(e){if(e instanceof N)throw e;let t=e.message,n=t.match(/at line (\d+)/),r=n?parseInt(n[1],10):1;throw new P(r,t)}}const R=e=>{let t={};for(let[n,r]of Object.entries(e))if(r&&typeof r==`object`){let{setupFields:e,configFields:i,support:a,refreshAuthentication:o,testOperations:s,...c}=r;t[n]=R(c)}else t[n]=r;return t},Se=(e,t,n,r)=>{if(!(!t||!n))for(let i of Object.values(t))for(let t of Object.values(i)){let i=t.testOperations;t.testOperations=i?.map(t=>{if(a(t.operation))if(typeof t.operation==`string`){let r=M(e,t.operation),i=Object.values(n).find(e=>e.id===r);if(i)return{...t,operation:i}}else{let n=M(e,t.operation.operationId),i=z(n,t.operation,r);return{...t,operation:i}}return t})}},Ce=e=>{let t=e.reduce((e,t)=>{for(let n of t.categories)e.add(n);return e},new Set);return Array.from(t)},we=e=>{let t={};for(let n of e.authentication??[]){let[r]=Object.keys(n),i=n[r].environments.reduce((t,i)=>{let{key:o,name:s}=i,{environments:c,refreshAuthentication:l,testOperations:u,...d}=n[r],f=a(l)?{schedule:l.schedule,operation:z(M(e.info.key,l.operation.operationId),l.operation)}:void 0;return t[o]={...d,refreshAuthentication:f,envKey:o,envName:s,testOperations:u},t},{});t[r]=i}return t},Te=e=>e.entrypointUrl&&e.entrypointHttpMethod?`${e.entrypointHttpMethod.toUpperCase()} ${e.entrypointUrl}`:void 0,Ee=e=>e.operationType===`list`?`GET /${e.schema}`:`GET /${e.schema}/:id`,De=e=>{if(e.operationType!==`refresh_token`)return e.entrypointHttpMethod??`get`},Oe=e=>{if(!(e.operationType===`refresh_token`||t(e.schema)))return e.operationType===`list`?`/${e.schema}`:`/${e.schema}/:id`},ke=e=>{let t={success:fe(e.operationType),errors:pe()},n=e.responses?.reduce((e,t)=>{let n=ne(t.statusCode);return n?e.success={statusCode:t.statusCode,description:t.description}:e.errors[t.statusCode]={statusCode:t.statusCode,description:t.description},e},t);return n??t},Ae=(e,t)=>{let n=e.operations?.reduce((n,r)=>{let i=Te(r),a=Ee(r),o=i??a,s=M(e.info.key,r.operationId);return n[s]=z(s,r,t,o),n},{});return n},z=(e,t,n,r)=>{let i=Oe(t),a=ke(t),o=Pe(t),s=t.inputs||[];o.enabled&&(s?.push({type:`string`,name:`page_size`,in:`query`,required:!1,description:`Number of items to return per page`,array:!1}),s?.push({type:`string`,name:`next`,in:`query`,required:!1,description:`Token for the next page of results`,array:!1}));let c=De(t);return{id:e,categories:t.categories,label:t.label,description:t.description,operationType:t.operationType,schemaType:t.schemaType??`native`,entrypointUrl:t.entrypointUrl??i,entrypointHttpMethod:c,endpoint:r,tags:t.tags,context:t.context,responses:a,cursor:o,compositeIdentifiers:Fe(t),scheduledJobs:Ie(t),inputs:s,steps:t.steps.reduce((e,r)=>{let{customErrors:i,...a}=r.stepFunction.parameters??{},o={id:r.stepId,description:r.description,condition:r.condition,ignoreError:r.ignoreError,stepFunction:{functionName:r.stepFunction.functionName,version:r.stepFunction.version,params:{...Le({stepFunctionName:r.stepFunction.functionName,baseRequestParams:n,customErrors:i}),...r.stepFunction.functionName===`map_fields`||r.stepFunction.functionName===`typecast`?{fields:a.fields??t.fieldConfigs}:{},...a}}};return je(t.operationId,o),e[r.stepId]=o,e},{}),result:t.result}},je=(e,t)=>{let n=t.stepFunction.version??`1`,r=v[t.stepFunction.functionName]?.[`v${n}`];if(!r)throw new ue(e,t.id,t.stepFunction.functionName,n);let i=r.inputSchema;i&&ze(i,t.stepFunction.params,e,t.id,t.stepFunction.functionName,n)},B=(e,t)=>{if(!e.inputs)return{};let n=Me(e.inputs),r=o.object(n).parse(t);return{...r.headers??{},...r.query??{},...r.path??{},...r.body??{}}},Me=e=>{let t=e.reduce((e,t)=>(e[t.in]||(e[t.in]=[]),e[t.in].push(t),e),{}),n={};for(let[e,r]of Object.entries(t)){let t={};for(let e of r){let n=Ne(e);e.description&&(n=n.describe(e.description)),e.required||(n=n.optional()),t[e.name]=n}Object.keys(t).length>0&&(n[e]=o.object(t))}return n},Ne=e=>{let t;switch(e.type){case`string`:case`datetime_string`:t=o.string();break;case`number`:t=o.number();break;case`boolean`:t=o.boolean();break;case`object`:if(e.properties&&e.properties.length>0){let n={};for(let t of e.properties){let e=Ne(t);t.description&&(e=e.describe(t.description)),t.required||(e=e.optional()),n[t.name]=e}t=o.object(n)}else t=o.record(o.string(),o.unknown());break;default:t=o.unknown()}return e.array&&(t=o.array(t)),t},Pe=e=>{let t=e.operationType===`list`,n=e.cursor??{enabled:t,pageSize:de};return{enabled:n.enabled&&t,pageSize:n.pageSize}},Fe=e=>{if(e.operationType===`refresh_token`)return{enabled:!1};if(t(e.compositeIdentifiers)){let t=e.fieldConfigs?.find(e=>e.targetFieldKey===`id`),n=a(t)?[{targetFieldKey:t.targetFieldKey,remote:`id`,components:[{name:t.targetFieldKey,alias:t.alias}]}]:void 0;return{enabled:!0,version:m,fields:n}}let n=[];for(let t of e.compositeIdentifiers?.fields??[]){let r=t.components.map(t=>{let n=e.fieldConfigs?.find(e=>e.targetFieldKey===t);return{name:t,alias:n?.alias}});n.push({targetFieldKey:t.targetFieldKey,remote:t.remote,components:r})}return{enabled:e.compositeIdentifiers.enabled,version:e.compositeIdentifiers.version,fields:n.length>0?n:void 0}},Ie=e=>{if(!t(e.scheduledJobs))return e.scheduledJobs},Le=({stepFunctionName:e,baseRequestParams:t,customErrors:n={}})=>{if(e===`request`||e===`paginated_request`){let e=[{receivedStatus:500,targetStatus:502}],r=n&&Array.isArray(n)?n:[],i=[...r,...e];return{...t,customErrors:i}}else return{}},Re=(e,t)=>{let n=e.safeParse(t);if(n.success)return n.data;{let e=n.error.issues.map(e=>({code:e.code,message:e.message,input:e.input,path:e.path,keys:e?.keys??[]}));throw new le(e,`Invalid connector schema`)}},ze=(e,t,n,r,i,a)=>{let o=e.safeParse(t);if(o.success)return o.data;{let e=o.error.issues.map(e=>({code:e.code,message:e.message,input:e.input,path:e.path,keys:e?.keys??[]}));throw new F(n,r,i,a,e)}},V=(e,t,n)=>{if(e.authentication?.[t]?.[n]?.authorization.type!==`oauth2`)return;let r=e.authentication?.[t]?.[n]?.refreshAuthentication?.operation;if(a(r))return{operation:r,params:{}}},Be=(e,t,n)=>{if(e.authentication?.[t]?.[n]?.authorization.type!==`oauth2`)return!1;let r=V(e,t,n);return a(r)},Ve=(e,t,n)=>{let r=e.authentication?.[t]?.[n]?.authorization;if(r?.type===`oauth2`)return r?.tokenExpiresIn},He=(e,t,n)=>{let r=e.authentication?.[t]?.[n]?.authorization;if(r?.type===`oauth2`)return r?.tokenRefreshExpiresIn},Ue=e=>{try{let t=L(e);return{success:!0,connector:t}}catch(n){if(n instanceof le){let r=n.issues,i=[];return r.forEach(n=>{let r=n?.keys?.[0],a=t(r)?n.path:[...n.path,r],o=We(a,e);i.push({line:o,message:n.message,field:a.join(`.`)})}),{success:!1,errors:i}}else if(n instanceof P)return{success:!1,errors:[{line:n.line,message:`The YAML connector file is not valid. Please check the syntax and structure.`,field:void 0}]};else if(n instanceof ue){let t=Ge(n.operationId,n.stepId,n.functionName,!1,e);return{success:!1,errors:[{line:t,message:n.message,field:void 0}]}}else if(n instanceof F){let r=n.issues,i=[];return r.forEach(r=>{let a=r?.keys?.[0],o=t(a)?r.path:[...r.path,a],s=Ge(n.operationId,n.stepId,n.functionName,!0,e);i.push({line:s,message:r.message,field:o.join(`.`)})}),{success:!1,errors:i}}}return{success:!1,errors:[{line:1,message:`An unknown error occurred while parsing the connector.`,field:void 0}]}},We=(e,n)=>{let r=n.split(`
5
- `),i=0,o=-1,s=0;for(let n=0;n<r.length;n++){let c=r[n],l=c.match(/^(\s*)/)?.[1]?.length||0,u=c.replace(`- `,``).trim();if(u.startsWith(`#`)||u===``||l<=o)continue;let d=a(e[i])?`${String(e[i])}`:``;if(t(d))return s+1;if(isNaN(Number(d))){if(u.startsWith(`${d}:`)){if(i===e.length-1)return n+1;o=l,s=n,i++}}else{let e=parseInt(d,10),t=-1;for(let a=n;a<r.length;a++){let o=r[a],c=o.trim();if(c.startsWith(`-`)&&t++,t===e){i++,s=n,n--;break}else n++}}}return s+1},Ge=(e,n,r,i,o)=>{let s=o.split(`
6
- `),c=1,l=null,u=null;for(let o=0;o<s.length;o++){let d=s[o],f=d.trim();if(t(l)&&f===`- operationId: ${e}`){l=e,c=o+1;continue}if(a(l)&&t(u)&&f===`- stepId: ${n}`){u=n,c=o+1;continue}if(a(l)&&a(u)&&!i&&f.startsWith(`functionName: ${r}`)||a(l)&&a(u)&&i&&f===`parameters:`)return c=o+1,c}return c};var H=class e extends Error{errorType;context;constructor(t,n,r){super(r),this.name=`ConnectSDKError`,this.errorType=t,this.context=n,Error.captureStackTrace&&Error.captureStackTrace(this,e)}toString(){return`${this.name} [${this.errorType}]: ${this.message}`}},Ke=class extends H{constructor(e,t){super(`CONNECTOR_PARSE_ERROR`,e,t),this.name=`ConnectorParseError`}},U=class extends H{constructor(e,t){super(`MISSING_OPERATION_ERROR`,e,t),this.name=`MissingOperationError`}},qe=class extends H{constructor(e,t){super(`INVALID_OPERATION_INPUTS_ERROR`,e,t),this.name=`InvalidOperationInputsError`}},Je=class extends H{constructor(e,t){super(`INVALID_CURSOR_ERROR`,e,t),this.name=`InvalidCursorError`}};const Ye=(e,t)=>{let n=Object.keys(e.authentication??{}).map(t=>({type:`custom`,label:e.authentication?.[t].production?.label||`Custom`,key:t})),r=Object.values(e?.operations??{}).map(e=>({id:e.id,description:e.description.replace(/\b\w/g,e=>e.toUpperCase()),label:e.label.replace(/\b\w/g,e=>e.toUpperCase()),schema_type:e.schemaType,tags:e.tags,authentication:n,operation_details:t?.includes(`operation_details`)?e:void 0}));return{version:e.version,name:e.title,key:e.key,icon:e.assets?.icon,description:e.description,authentication:n,actions:r}},Xe=(e,t)=>e.map(e=>Ye(e,t)),Ze=`stackone://internal//`,Qe=`${Ze}refresh_token`,$e=async({block:e,stepFunctionName:t,params:n,buildStepFunction:r=_.build})=>{let i=r({functionName:t}).fn,a=await i({block:e,params:n}),o=t===g.MAP_FIELDS?{[g.MAP_FIELDS.toString()]:{output:{data:a.block.result},errors:a.errors,successful:a.successful}}:{};return{...a.block,steps:{...a?.block?.steps??{},...o}}},W=({category:t,connectorKey:n,connectorVersion:r,authConfigKey:i,environment:a=`production`,operation:o,accountSecureId:s,projectSecureId:c})=>({projectSecureId:c,accountSecureId:s,connectorKey:n,connectorVersion:r,category:t,service:``,resource:``,schema:o?.schema?.key,operationType:o?.operationType??`unknown`,authenticationType:i,environment:a,actionRunId:e()}),et=(e,t,n)=>e.authentication?.[t]?.[n]?.testOperations,tt=e=>{let n=e.operation?.compositeIdentifiers,r={...e.inputs??{}};if(!n?.enabled||t(r))return e;let i=n.fields?.reduce((e,t)=>(t.components.forEach(t=>{t.alias&&(e[t.name]=t.alias)}),e),{}),a={version:n.version??m,aliases:i};return G(r,a,e.logger),{...e,inputs:r}},G=(e,t,n)=>{for(let r in e){let i=e[r];if(typeof i==`string`||Array.isArray(i)&&i.every(e=>typeof e==`string`))st(i,r,e,t,n);else if(Array.isArray(i))for(let e of i)G(e,t,n);else typeof i==`object`&&i&&G(i,t,n)}},nt=(e,t,n,r)=>{let i=[],a=[];for(let o of e)try{let e=ee(o,n);i.push(e)}catch(e){r?.debug({message:`Received ${t} with invalid composite ID, assuming it is not a composite ID`,category:`processCompositeId`,context:{key:t,inputElement:o,compositeIdentifierConfig:n,error:e}}),a.push(o)}return{compositeIdComponents:i,nonCompositeIds:a}},rt=(e,t,n,r)=>{let i=n.filter(e=>Object.keys(e).length>1);i.length>0&&(e.decoded_ids={...e.decoded_ids??{},[t]:r?i:i[0]})},it=e=>{let t=Object.values(e);return t.length===1&&(typeof t[0]==`string`||typeof t[0]==`number`)},at=(e,t,n,r,i)=>{n.every(it)&&(i?e[t]=[...n.map(e=>Object.values(e)[0]),...r]:n.length>0&&(e[t]=Object.values(n[0])[0]))},ot=(e,t,n)=>{e instanceof h&&e.type===`COMPOSITE_ID_MISSING_HEADER_ERROR`?n?.debug({message:`Received ${t} with no composite ID header, assuming it is not a composite ID`}):n?.warning({message:`Error processing composite ID for ${t}, ignoring it`,error:e})},st=(e,t,n,r,i)=>{try{let a=Array.isArray(e),o=a?e:[e];if(o.length===0)return;let{compositeIdComponents:s,nonCompositeIds:c}=nt(o,t,r,i);rt(n,t,s,a),at(n,t,s,c,a)}catch(e){ot(e,t,i)}},K=`remote_`,ct=e=>{let n=e.operation?.compositeIdentifiers;if(!n?.enabled)return e;let r=`data`,i=e.outputs?.[r];if(t(i))return e;let a=Array.isArray(i)?i.map(e=>lt(e,n)):lt(i,n);return{...e,outputs:{...e.outputs??{},[r]:a}}},lt=(e,t)=>{let n=ut(e,t),i=q(n);return{...e,...r(i)?i:{}}},ut=(e,t)=>{let n=t.version??m,r={};return t.fields?.forEach(t=>{let i={},a=[];t.components.forEach(t=>{t.alias&&(i[t.name]=t.alias),a.push({key:t.name,value:e[t.name]})});let o=a.length===1?a[0]:{identifiers:a},s={version:n,aliases:Object.keys(i).length>0?i:void 0},c=y(o,s);r[t.targetFieldKey]=c,t.remote&&(r[`${K}${t.remote}`]=e[t.remote])}),{...e,...r}},dt=e=>e===`id`||/.+_id(s)?$/.test(e),ft=e=>Array.isArray(e)&&e.every(e=>i(e)&&e.length>0),pt=(e,t)=>x(e)||t.startsWith(K),mt=(e,t)=>{try{return y({key:e,value:t},{version:m})}catch{return t}},ht=(e,t,n)=>{let r=t.map(t=>i(t)&&t.length>0&&!x(t)?mt(e,t):t);n[e]=r,n[`${K}${e}`]=t},gt=(e,t,n)=>{if(pt(t,e))return;let r=y({key:e,value:t},{version:m});n[e]=r,n[`remote_${e}`]=t},_t=(e,t,n)=>{ft(t)?ht(e,t,n):i(t)&&t.length>0&&gt(e,t,n)},q=e=>{if(Array.isArray(e))return e.map(e=>q(e));if(!r(e))return e;let t={...e};for(let[n,i]of Object.entries(e))(r(i)||Array.isArray(i)&&i.length>0&&r(i[0]))&&(t[n]=q(i)),dt(n)&&_t(n,i,t);return t},vt=(e,t)=>{let r=Number(e.inputs?.page_size),i=a(e.inputs?.page_size)&&n(r)&&!Number.isNaN(r)?r:e.operation?.cursor?.pageSize??t;return i},J=(e,n,i,o)=>{let s=t(e)?void 0:e.data,c=Object.keys(i).length+1,l=te({cursor:o,ignoreStepIndex:c});if(!r(e)||t(s)||(s?.length??0)<=n)return{result:e,next:a(o)&&!l?S(o):null};let u=o?.remote?.[c]?.pageNumber??1,d=(u-1)*n,f=d+n,p=s.slice(d,f),m=s.length>f||!l,h=C({cursor:o,stepIndex:c,pageNumber:u+1});return{result:{...e,data:p},next:m?S(h):null}},yt=e=>{let n=e.settings?.olap;return t(n)?{}:{logs:n.logs?{enabled:n.logs.enabled}:void 0,advanced:n.advanced?{enabled:n.advanced.enabled,ttl:n.advanced.ttl,errorsOnly:n.advanced.errorsOnly}:void 0}},Y=async({block:e,buildStepFunction:t=_.build,virtualPaginateResultFn:n=J,encodeResultCompositeIds:r=ct,decodeInputCompositeIds:i=tt})=>{let a=i(e),o=await Tt({block:a,buildStepFunction:t,virtualPaginateResultFn:n});return r(o)},bt=(e,t)=>e.condition?!T(e.condition,t):!1,xt=(e,t,n)=>{let r=e.stepFunction,i=v[e.stepFunction.functionName]?.[`v${e.stepFunction.version??1}`],o=a(i?.inputSchema?.shape)?`cursor`in i?.inputSchema?.shape:!1;return t.operation?.cursor.enabled&&o?{...r.params??{},cursor:{token:t.nextCursor?.remote?.[n]?.providerPageCursor,position:t.nextCursor?.remote?.[n]?.position}}:r.params??{}},St=(e,t,n,r,i)=>{let a=X({block:e,stepId:t,successful:!1,functionOutput:n}),o=r.ignoreError??!1;return o||(i.hasFatalError=!0,i.errorStatusCode??=n.output?.statusCode??500),a},Ct=async(e,t,n,r,i,a)=>{let o=n[e],s=o.stepFunction,c=a.buildStepFunction({functionName:s.functionName,version:s.version,validateSchemas:!0}).fn;if(bt(o,r))return X({block:r,stepId:e,successful:!0,skipped:!0,message:`Step skipped due to condition not met.`});if(i.hasFatalError)return X({block:r,stepId:e,successful:!1,skipped:!0,message:`Step skipped due to previous error.`});let l=xt(o,r,t),u=await c({block:r,params:l});if(u.successful===!1)return St(r,e,u,o,i);let d=r.operation?.cursor.enabled?C({cursor:r.nextCursor,stepIndex:t,providerPageCursor:u.output?.next,position:u.output?.position}):void 0;return X({block:{...u.block,nextCursor:d},stepId:e,functionOutput:u})},wt=(e,t,n,i,o)=>{let s=!n.hasFatalError,c=s?e.operation?.responses.success.statusCode??200:n.errorStatusCode??500,l=a(o)&&r(o.result)?{next:o.next,...o.result}:i;return{...t,outputs:l,response:{successful:s,statusCode:c,message:s?void 0:e.operation?.responses?.errors?.[c]?.description??w?.[c]??`Error while processing the request`}}},Tt=async({block:e,buildStepFunction:t=_.build,virtualPaginateResultFn:n=J})=>{let r=e.operation?.steps||{},i={...e},a=Object.keys(r),o=vt(e,de),s={hasFatalError:!1,errorStatusCode:null},c={block:e,buildStepFunction:t,virtualPaginateResultFn:n};for(let[e,t]of a.entries())i=await Ct(t,e,r,i,s,c),Dt({block:i,stepId:t});let l=e.operation?.result?Et(e.operation.result,i):void 0,u=e.operation?.cursor.enabled?n(l,o,r,i.nextCursor):void 0;return wt(e,i,s,l,u)},Et=(e,t)=>r(e)?E(e,t):T(e,t),X=({block:e,stepId:t,successful:n,functionOutput:r,skipped:i,message:a})=>({...e,steps:{...e.steps,[t]:{successful:n??r?.successful??!1,errors:r?.errors,output:r?.output,skipped:i,message:a}}}),Dt=({block:e,stepId:n})=>{let r=e.olapClient;if(t(r?.recordStep))return;let i=yt(e);r.recordStep({stepId:n,status:e.steps?.[n]?.successful?`success`:`error`},i)},Z=async e=>{let{pathParams:n={},queryParams:r={},body:o={},headers:s={},parseConnector:c=L,parseOperationInputsFn:l=B,createBlockContextFn:u=W,createBlockFn:d=D,runStepOperationFn:f=Y,getOperationFromUrlFn:p=A,getOperationForRefreshAuthenticationFn:m=V,getTestOperationsFn:h=et,mode:g,account:_,connector:v,getHttpClient:ee,getOlapClient:y,settings:b,logger:x,category:te,...S}=e,C=_.authConfigKey,w=_.environment??`production`,ne=_.secureId,re=_.projectSecureId,T=_.credentials,E=u({category:te??`action`,connectorKey:_.providerKey,connectorVersion:_.providerVersion,authConfigKey:C,environment:w,accountSecureId:ne,projectSecureId:re}),O;try{O=i(v)?c(v):v}catch{throw new Ke(E,`Error while parsing connector`)}let k={connector:O,context:E,credentials:T,settings:b,logger:x,getHttpClient:ee,getOlapClient:y};if(g===`operation_id`){let{operationId:e}=S,i=ce(O,e);if(t(i))throw new U(E,`No matching operation found`);let a=await Q({operation:i,blockContext:E,queryParams:r,pathParams:n,body:o,headers:s,parseOperationInputsFn:l,createBlockFn:d,createBlockParams:k,runStepOperationFn:f});return $({block:a}),a}else if(g===`test_operations`){let e=h(O,C,w);if(t(e)||e.length===0){let e=await Ot(d,k);return $({block:e}),e}E.operationType=`test`;for(let n of e){let e=await d({...k,inputs:void 0,operation:n.operation,nextCursor:void 0}),r=a(n.condition)?ie(n.condition,e):!0;if(!r)continue;let i=await f({block:e});if((t(i?.response?.successful)||!i.response.successful)&&n.required){x?.error({code:`TestOperationFailed`,message:`Test operation "${n.operation.id}" failed with error: ${i?.response?.message}`});let e=await kt(d,k);return $({block:e}),e}}let n=await Ot(d,k);return $({block:n}),n}else if(g===`refresh_authentication`){let e=m(O,C,w);if(t(e))throw new U(E,`No matching operation found`);let n=await Q({operation:e.operation,blockContext:E,queryParams:r,pathParams:e.params,body:o,headers:s,parseOperationInputsFn:l,createBlockFn:d,createBlockParams:k,runStepOperationFn:f});return $({block:n}),n}else if(g===`path`){let{path:e,method:n}=S,i=p(O,e,n);if(t(i))throw new U(E,`No matching operation found`);let a=await Q({operation:i.operation,blockContext:E,queryParams:r,pathParams:i.params,body:o,headers:s,parseOperationInputsFn:l,createBlockFn:d,createBlockParams:k,runStepOperationFn:f});return $({block:a}),a}else{let e=await kt(d,k);return $({block:e}),e}},Q=async e=>{let{operation:t,blockContext:n,queryParams:r,pathParams:i,body:a,headers:o,parseOperationInputsFn:s,createBlockFn:c,createBlockParams:l,runStepOperationFn:u}=e;n.operationType=t.operationType,n.schema=t.schema?.key;let d=At(r,n),f;try{f=s(t,{path:i,query:r,body:a,headers:o})}catch{throw new qe(n,`Error while parsing operation inputs`)}let p=await c({...l,inputs:f,operation:t,nextCursor:d});return await u({block:p})},Ot=async(e,t)=>{let n=await e({...t,inputs:void 0,operation:void 0,nextCursor:void 0});return{...n,response:{successful:!0,statusCode:200}}},kt=async(e,t)=>{let n=await e({...t,inputs:void 0,operation:void 0,nextCursor:void 0});return{...n,response:{successful:!1,statusCode:500}}},At=(e,t)=>{let n=e?.next,r=a(n)&&t.operationType===`list`?b(n):void 0;if(r===null)throw new Je(t,`Invalid cursor.`);return r},$=({block:e})=>{let n=e.olapClient;if(t(n?.recordAction))return;let r=yt(e);n.recordAction({status:e.response?.successful?`success`:`error`,message:e.response?.message,outputs:e.outputs},r)},jt=async({operationId:e,account:t,connector:n,pathParams:r={},queryParams:i={},body:a={},headers:o={},logger:s,getHttpClient:c,getOlapClient:l,parseConnector:u=L,parseOperationInputsFn:d=B,createBlockContextFn:f=W,createBlockFn:p=D,runStepOperationFn:m=Y})=>Z({mode:`operation_id`,operationId:e,account:t,connector:n,pathParams:r,queryParams:i,body:a,headers:o,logger:s,getHttpClient:c,getOlapClient:l,parseConnector:u,parseOperationInputsFn:d,createBlockContextFn:f,createBlockFn:p,runStepOperationFn:m}),Mt=async({account:e,connector:t,category:n,path:r,method:i=`get`,queryParams:a={},body:o,headers:s,logger:c,getHttpClient:l,parseConnector:u=L,getOperationFromUrlFn:d=A,getOperationForRefreshAuthenticationFn:f=V,parseOperationInputsFn:p=B,createBlockContextFn:m=W,createBlockFn:h=D,runStepOperationFn:g=Y})=>{let _=Nt(r),v=_?await Z({mode:`refresh_authentication`,account:e,connector:t,getOperationForRefreshAuthenticationFn:f,parseConnector:u,logger:c,getHttpClient:l,parseOperationInputsFn:p,createBlockContextFn:m,createBlockFn:h,runStepOperationFn:g}):await Z({mode:`path`,account:e,category:n,connector:t,path:r,method:i,queryParams:a,body:o,headers:s,getOperationFromUrlFn:d,parseConnector:u,logger:c,getHttpClient:l,parseOperationInputsFn:p,createBlockContextFn:m,createBlockFn:h,runStepOperationFn:g});return v},Nt=e=>e===Qe,Pt=async({account:e,connector:t,logger:n,getHttpClient:r,parseConnector:i=L,getTestOperationsFn:a=et,createBlockContextFn:o=W,createBlockFn:s=D,runStepOperationFn:c=Y})=>{let l=await Z({mode:`test_operations`,account:e,connector:t,logger:n,getHttpClient:r,parseConnector:i,getTestOperationsFn:a,createBlockContextFn:o,createBlockFn:s,runStepOperationFn:c});return l?.response?.successful??!1};export{H as ConnectSDKError,Qe as REFRESH_TOKEN_OPERATION_PATH,D as createBlock,$e as executeStepFunction,Ye as getActionsMeta,Xe as getActionsMetaFromConnectors,A as getOperationFromUrl,He as getRefreshTokenExpiresIn,Ve as getTokenExpiresIn,O as loadConnector,B as parseOperationInputs,L as parseYamlConnector,Z as runAction,jt as runConnectorAction,Mt as runConnectorOperation,Y as runStepOperation,Pt as runTestOperations,Be as supportsRefreshAuthentication,Ue as validateYamlConnector};
1
+ import{generateActionRunId as e,isMissing as t,isNumber as n,isObject as r,isString as i,notMissing as a,z as o,zStrictObject as s}from"@stackone/utils";import{readFileSync as c}from"fs";import{dirname as l,join as u,resolve as d}from"path";import{match as f}from"path-to-regexp";import{AUTHENTICATION_SCHEMA as p,COMPOSITE_ID_LATEST_VERSION as m,CoreError as h,ReleaseStages as g,StepFunctionName as _,StepFunctionsFactory as v,StepFunctionsRegistry as y,decodeCompositeId as ee,encodeCompositeId as b,expandCursor as x,isCompositeId as S,isCursorEmpty as C,minifyCursor as w,updateCursor as T}from"@stackone/core";import{HttpErrorMessages as te,isSuccessStatusCode as ne}from"@stackone/transport";import{parse as re}from"yaml";import{evaluate as ie,safeEvaluate as E,safeEvaluateRecord as D}from"@stackone/expressions";const O=async({connector:e,inputs:n,context:r,operation:i,credentials:a,nextCursor:o,settings:s,logger:c,getHttpClient:l,getOlapClient:u})=>{if(t(l))throw Error(`getHttpClient function is required`);let d=await l(),f=u?await u():void 0;return{connector:e,inputs:n,fieldConfigs:[],context:r,operation:i,credentials:a,nextCursor:o,httpClient:d,olapClient:f,settings:s,logger:c}},k=e=>{if(!e.endsWith(`.s1.yaml`))throw Error(`File must have .s1.yaml extension`);try{let t=c(e,`utf8`);if(!t.includes(`:`)||!t.includes(`$ref:`))return t;let n=t.split(`
2
+ `),r=A(n,l(e));return r.join(`
3
+ `)}catch(e){throw Error(`Failed to process YAML file: ${e.message}`)}},A=(e,t)=>{let n=[];for(let r of e)if(ae(r)){let e=r.match(/^(\s*)/)?.[1]?.length||0,i=r.split(`:`)[1]?.trim(),a=oe(i,t),o=a.map(t=>` `.repeat(e)+t);n.push(...o)}else n.push(r);return n},ae=e=>e.includes(`$ref:`),oe=(e,t)=>{let n=d(u(t,`${e.replaceAll(`'`,``)}.s1.partial.yaml`));try{let e=c(n,`utf8`);return e.split(`
4
+ `).filter(e=>e.trim()!==``)}catch(t){throw Error(`Failed to load partial file '${e}': ${t.message}`)}},j=(e,t,n)=>{let r=n.toUpperCase();if(!e.operations)return;let i=Object.values(e.operations).filter(e=>a(e.endpoint)).map(e=>({operationId:e.id,endpoint:e.endpoint})),o=se(t,r,i);if(o)return{operation:e.operations?.[o.operationId],params:o.params}},M=e=>{let t=e.startsWith(`/`)?e.slice(1):e,n=t.endsWith(`/`)?t.slice(0,-1):t;return n},se=(e,t,n)=>{let r=M(e);for(let e of n)if(e.endpoint?.startsWith(t)){let n=e.endpoint.replace(`${t} `,``).trim(),i=f(M(n)),a=i(M(r));if(a!==!1)return{operationId:e.operationId,path:e.endpoint,params:a.params}}},N=(e,t)=>t?.startsWith(`${e}_`)?t:`${e}_${t}`,ce=(e,t)=>{let n=`${e.key}_`,r=t.startsWith(n)?t:`${n}${t}`;return e.operations?.[r]};var P=class e extends Error{errorType;constructor(t,n){super(n),this.name=`InternalConnectSDKError`,this.errorType=t,Error.captureStackTrace&&Error.captureStackTrace(this,e)}toString(){return`${this.name} [${this.errorType}]: ${this.message}`}},le=class extends P{line;constructor(e,t){super(`INVALID_YAML_FILE_ERROR`,t),this.name=`InvalidYamlFileError`,this.line=e??1}},ue=class extends P{issues;constructor(e,t){super(`SCHEMA_VALIDATION_ERROR`,t),this.name=`SchemaValidationError`,this.issues=e}},de=class extends P{operationId;stepId;functionName;functionVersion;constructor(e,t,n,r=`1`){let i=`Invalid Step Function: '${n}' (v${r}) on step '${t}'. Please ensure the function name and version are correct in the operation '${e}'.`;super(`INVALID_STEP_FUNCTION`,i),this.name=`InvalidStepFunctionError`,this.operationId=e,this.stepId=t,this.functionName=n,this.functionVersion=r}},fe=class extends P{operationId;stepId;functionName;functionVersion;issues;constructor(e,t,n,r=`1`,i){let a=`Invalid parameters for Step Function: '${n}' (v${r}) on step '${t}'. Please ensure the parameters are correct in the operation '${e}'.`;super(`INVALID_STEP_FUNCTION_PARAMS`,a),this.name=`InvalidStepFunctionParamsError`,this.operationId=e,this.stepId=t,this.functionName=n,this.functionVersion=r,this.issues=i,this.message=a}};const pe=25,me=e=>{switch(e){case`list`:return{statusCode:200,description:`The list of records was retrieved.`};case`get`:return{statusCode:200,description:`The record with the given identifier was retrieved.`};case`create`:return{statusCode:201,description:`The record was created successfully.`};case`update`:return{statusCode:200,description:`The record was updated successfully.`};case`delete`:return{statusCode:204,description:`The record was deleted successfully.`};case`custom`:return{statusCode:200,description:`The operation was executed successfully.`};case`refresh_token`:return{statusCode:200,description:`The refresh token operation was executed successfully.`};case`unknown`:return{statusCode:200};default:throw Error(`Unknown operation type: ${e}`)}},he=()=>{let e={400:{statusCode:400,description:`Invalid request.`},401:{statusCode:401,description:`Unauthorized access.`},403:{statusCode:403,description:`Forbidden.`},404:{statusCode:404,description:`Resource not found.`},500:{statusCode:500,description:`Server error while executing the request.`}};return e},ge={key:o.string(),label:o.string(),required:o.boolean().optional().default(!1),secret:o.boolean().optional().default(!1),readOnly:o.boolean().optional().default(!1),placeholder:o.string().optional(),description:o.string().optional(),tooltip:o.string().optional()},_e=o.discriminatedUnion(`type`,[s({...ge,type:o.enum([`text`,`password`])}),s({...ge,type:o.literal(`select`),options:s({value:o.string(),label:o.string()}).array()})]),F=s({targetFieldKey:o.string(),alias:o.string().optional(),expression:o.string().optional(),values:o.unknown().optional(),type:o.enum([`string`,`number`,`boolean`,`datetime_string`,`enum`,`object`]),array:o.boolean().default(!1),custom:o.boolean().default(!1),hidden:o.boolean().default(!1),enumMapper:s({matcher:o.enum([`country_alpha2code_by_alpha2code`,`country_alpha3code_by_alpha3code`,`country_code_by_country_code`,`country_name_by_country_name`,`country_name_by_alpha3code`,`country_name_by_alpha2code`,`country_name_by_country_code`,`country_alpha3code_by_alpha2code`,`country_alpha3code_by_country_name`,`country_alpha3code_by_country_code`,`country_alpha2code_by_alpha3code`,`country_alpha2code_by_country_name`,`country_alpha2code_by_country_code`,`country_code_by_alpha2code`,`country_code_by_alpha3code`,`country_code_by_country_name`,`country_subdivisions_by_alpha2code`,`country_subdivision_code_by_subdivision_name`,`country_alpha2code_by_citizenship`,`country_subdivision_name_by_subdivision_code`,`document_file_format_from_extension`]).or(s({matchExpression:o.string(),value:o.string()}).array())}).optional(),properties:o.lazy(()=>F).array().optional()}),I=s({name:o.string(),type:o.enum([`string`,`number`,`boolean`,`datetime_string`,`object`]),required:o.boolean(),description:o.string(),array:o.boolean().optional().default(!1),in:o.enum([`body`,`query`,`path`,`headers`]),properties:o.lazy(()=>I.omit({in:!0})).array().optional()}),L=s({operationId:o.string(),categories:o.string().array(),operationType:o.enum([`list`,`get`,`create`,`update`,`delete`,`custom`,`refresh_token`,`unknown`]),schema:o.string().optional(),schemaType:o.enum([`native`,`unified`]).optional().default(`native`),entrypointUrl:o.string().optional(),entrypointHttpMethod:o.string().optional(),label:o.string(),description:o.string(),tags:o.string().array().optional(),releaseStage:o.enum(g).optional(),context:o.string().optional(),responses:s({statusCode:o.number(),description:o.string()}).array().optional(),inputs:I.array().optional(),cursor:s({enabled:o.boolean(),pageSize:o.number()}).optional(),compositeIdentifiers:s({enabled:o.boolean(),version:o.number().optional(),fields:s({targetFieldKey:o.string(),remote:o.string().optional(),components:o.string().array()}).array().optional()}).optional(),scheduledJobs:s({enabled:o.boolean(),type:o.enum([`data_sync`]),schedule:o.string(),description:o.string(),requestParams:s({fields:o.string().array().optional(),expand:o.string().array().optional(),filter:o.record(o.string(),o.string()).optional()}).optional(),syncFilter:s({name:o.enum([`updated_after`,`created_after`]),initialLoopbackPeriod:o.string(),incrementalLoopbackPeriod:o.string()}).optional()}).array().optional(),fieldConfigs:F.array().optional(),steps:s({stepId:o.string(),description:o.string(),stepFunction:s({functionName:o.string(),version:o.string().optional(),parameters:o.record(o.string(),o.unknown())}),condition:o.string().optional(),ignoreError:o.boolean().optional()}).array(),result:o.string().or(o.record(o.string(),o.unknown())).optional()}),ve=s({schedule:o.string().optional(),operation:L.extend({operationType:o.literal(`refresh_token`)})}),ye=s({mainRatelimit:o.number(),subPools:o.array(s({subPoolKey:o.string(),urlPattern:o.string(),rateLimit:o.number()})).optional(),mappedRateLimitErrors:o.array(s({errorStatus:o.number(),errorMessage:o.string(),errorMessagePath:o.string().optional(),retryAfterPath:o.string().optional(),retryAfterUnit:o.union([o.literal(`seconds`),o.literal(`milliseconds`),o.literal(`date`)]).optional(),retryAfterValue:o.number().optional()})).optional()}),be=s({mainMaxConcurrency:o.number(),subPools:o.array(s({subPoolKey:o.string(),urlPattern:o.string(),maxConcurrency:o.number()})).optional()}),xe=s({StackOne:o.string(),info:s({title:o.string(),version:o.string(),key:o.string(),assets:s({icon:o.string()}),description:o.string()}),context:o.string().optional(),baseUrl:o.string(),authentication:o.record(o.string(),s({type:o.string(),label:o.string(),authorization:p,environments:s({key:o.string(),name:o.string()}).array(),support:s({link:o.string(),description:o.string().optional()}),configFields:_e.array().optional(),setupFields:_e.array().optional(),refreshAuthentication:ve.optional(),testOperations:s({operation:o.string().or(L),condition:o.string().optional(),required:o.boolean().default(!0)}).array().optional()})).array().optional(),operations:L.array().optional(),rateLimit:ye.optional(),concurrency:be.optional(),releaseStage:o.enum(g).optional()}).strict();function R(e){try{let t=re(e),n=ze(xe,t),r={title:n.info.title,version:n.info.version,key:n.info.key,assets:n.info.assets,description:n.info.description,context:n.context,rateLimit:n.rateLimit,concurrency:n.concurrency,releaseStage:n.releaseStage},i=Te(n),o={baseUrl:n.baseUrl,authentication:Se(i)},s=je(n,o);return r.operations=s,Ce(n.info.key,i,s,o),r.authentication=i,a(s)&&(r.categories=we(Object.values(s))),r}catch(e){if(e instanceof P)throw e;let t=e.message,n=t.match(/at line (\d+)/),r=n?parseInt(n[1],10):1;throw new le(r,t)}}const Se=e=>{let t={};for(let[n,r]of Object.entries(e))if(r&&typeof r==`object`){let{setupFields:e,configFields:i,support:a,refreshAuthentication:o,testOperations:s,...c}=r;t[n]=Se(c)}else t[n]=r;return t},Ce=(e,t,n,r)=>{if(!(!t||!n))for(let i of Object.values(t))for(let t of Object.values(i)){let i=t.testOperations;t.testOperations=i?.map(t=>{if(a(t.operation))if(typeof t.operation==`string`){let r=N(e,t.operation),i=Object.values(n).find(e=>e.id===r);if(i)return{...t,operation:i}}else{let n=N(e,t.operation.operationId),i=z(n,t.operation,r);return{...t,operation:i}}return t})}},we=e=>{let t=e.reduce((e,t)=>{for(let n of t.categories)e.add(n);return e},new Set);return Array.from(t)},Te=e=>{let t={};for(let n of e.authentication??[]){let[r]=Object.keys(n),i=n[r].environments.reduce((t,i)=>{let{key:o,name:s}=i,{environments:c,refreshAuthentication:l,testOperations:u,...d}=n[r],f=a(l)?{schedule:l.schedule,operation:z(N(e.info.key,l.operation.operationId),l.operation)}:void 0;return t[o]={...d,refreshAuthentication:f,envKey:o,envName:s,testOperations:u},t},{});t[r]=i}return t},Ee=e=>e.entrypointUrl&&e.entrypointHttpMethod?`${e.entrypointHttpMethod.toUpperCase()} ${e.entrypointUrl}`:void 0,De=e=>e.operationType===`list`?`GET /${e.schema}`:`GET /${e.schema}/:id`,Oe=e=>{if(e.operationType!==`refresh_token`)return e.entrypointHttpMethod??`get`},ke=e=>{if(!(e.operationType===`refresh_token`||t(e.schema)))return e.operationType===`list`?`/${e.schema}`:`/${e.schema}/:id`},Ae=e=>{let t={success:me(e.operationType),errors:he()},n=e.responses?.reduce((e,t)=>{let n=ne(t.statusCode);return n?e.success={statusCode:t.statusCode,description:t.description}:e.errors[t.statusCode]={statusCode:t.statusCode,description:t.description},e},t);return n??t},je=(e,t)=>{let n=e.operations?.reduce((n,r)=>{let i=Ee(r),a=De(r),o=i??a,s=N(e.info.key,r.operationId);return n[s]=z(s,r,t,o),n},{});return n},z=(e,t,n,r)=>{let i=ke(t),a=Ae(t),o=Fe(t),s=t.inputs||[];o.enabled&&(s?.push({type:`string`,name:`page_size`,in:`query`,required:!1,description:`Number of items to return per page`,array:!1}),s?.push({type:`string`,name:`next`,in:`query`,required:!1,description:`Token for the next page of results`,array:!1}));let c=Oe(t);return{id:e,categories:t.categories,label:t.label,description:t.description,operationType:t.operationType,schemaType:t.schemaType??`native`,entrypointUrl:t.entrypointUrl??i,entrypointHttpMethod:c,endpoint:r,tags:t.tags,releaseStage:t.releaseStage,context:t.context,responses:a,cursor:o,compositeIdentifiers:Ie(t),scheduledJobs:Le(t),inputs:s,steps:t.steps.reduce((e,r)=>{let{customErrors:i,...a}=r.stepFunction.parameters??{},o={id:r.stepId,description:r.description,condition:r.condition,ignoreError:r.ignoreError,stepFunction:{functionName:r.stepFunction.functionName,version:r.stepFunction.version,params:{...Re({stepFunctionName:r.stepFunction.functionName,baseRequestParams:n,customErrors:i}),...r.stepFunction.functionName===`map_fields`||r.stepFunction.functionName===`typecast`?{fields:a.fields??t.fieldConfigs}:{},...a}}};return Me(t.operationId,o),e[r.stepId]=o,e},{}),result:t.result}},Me=(e,t)=>{let n=t.stepFunction.version??`1`,r=y[t.stepFunction.functionName]?.[`v${n}`];if(!r)throw new de(e,t.id,t.stepFunction.functionName,n);let i=r.inputSchema;i&&Be(i,t.stepFunction.params,e,t.id,t.stepFunction.functionName,n)},B=(e,t)=>{if(!e.inputs)return{};let n=Ne(e.inputs),r=o.object(n).parse(t);return{...r.headers??{},...r.query??{},...r.path??{},...r.body??{}}},Ne=e=>{let t=e.reduce((e,t)=>(e[t.in]||(e[t.in]=[]),e[t.in].push(t),e),{}),n={};for(let[e,r]of Object.entries(t)){let t={};for(let e of r){let n=Pe(e);e.description&&(n=n.describe(e.description)),e.required||(n=n.optional()),t[e.name]=n}Object.keys(t).length>0&&(n[e]=o.object(t))}return n},Pe=e=>{let t;switch(e.type){case`string`:case`datetime_string`:t=o.string();break;case`number`:t=o.number();break;case`boolean`:t=o.boolean();break;case`object`:if(e.properties&&e.properties.length>0){let n={};for(let t of e.properties){let e=Pe(t);t.description&&(e=e.describe(t.description)),t.required||(e=e.optional()),n[t.name]=e}t=o.object(n)}else t=o.record(o.string(),o.unknown());break;default:t=o.unknown()}return e.array&&(t=o.array(t)),t},Fe=e=>{let t=e.operationType===`list`,n=e.cursor??{enabled:t,pageSize:pe};return{enabled:n.enabled&&t,pageSize:n.pageSize}},Ie=e=>{if(e.operationType===`refresh_token`)return{enabled:!1};if(t(e.compositeIdentifiers)){let t=e.fieldConfigs?.find(e=>e.targetFieldKey===`id`),n=a(t)?[{targetFieldKey:t.targetFieldKey,remote:`id`,components:[{name:t.targetFieldKey,alias:t.alias}]}]:void 0;return{enabled:!0,version:m,fields:n}}let n=[];for(let t of e.compositeIdentifiers?.fields??[]){let r=t.components.map(t=>{let n=e.fieldConfigs?.find(e=>e.targetFieldKey===t);return{name:t,alias:n?.alias}});n.push({targetFieldKey:t.targetFieldKey,remote:t.remote,components:r})}return{enabled:e.compositeIdentifiers.enabled,version:e.compositeIdentifiers.version,fields:n.length>0?n:void 0}},Le=e=>{if(!t(e.scheduledJobs))return e.scheduledJobs},Re=({stepFunctionName:e,baseRequestParams:t,customErrors:n={}})=>{if(e===`request`||e===`paginated_request`){let e=[{receivedStatus:500,targetStatus:502}],r=n&&Array.isArray(n)?n:[],i=[...r,...e];return{...t,customErrors:i}}else return{}},ze=(e,t)=>{let n=e.safeParse(t);if(n.success)return n.data;{let e=n.error.issues.map(e=>({code:e.code,message:e.message,input:e.input,path:e.path,keys:e?.keys??[]}));throw new ue(e,`Invalid connector schema`)}},Be=(e,t,n,r,i,a)=>{let o=e.safeParse(t);if(o.success)return o.data;{let e=o.error.issues.map(e=>({code:e.code,message:e.message,input:e.input,path:e.path,keys:e?.keys??[]}));throw new fe(n,r,i,a,e)}},V=(e,t,n)=>{if(e.authentication?.[t]?.[n]?.authorization.type!==`oauth2`)return;let r=e.authentication?.[t]?.[n]?.refreshAuthentication?.operation;if(a(r))return{operation:r,params:{}}},Ve=(e,t,n)=>{if(e.authentication?.[t]?.[n]?.authorization.type!==`oauth2`)return!1;let r=V(e,t,n);return a(r)},He=(e,t,n)=>{let r=e.authentication?.[t]?.[n]?.authorization;if(r?.type===`oauth2`)return r?.tokenExpiresIn},Ue=(e,t,n)=>{let r=e.authentication?.[t]?.[n]?.authorization;if(r?.type===`oauth2`)return r?.tokenRefreshExpiresIn},We=(e,t=[])=>qe(t,e.releaseStage),Ge=(e,t=[])=>{if(!We(e,t))return;let n={};if(e.operations)for(let[r,i]of Object.entries(e.operations))qe(t,i.releaseStage)&&(n[r]=i);return{...e,operations:n}},Ke=e=>e??`ga`,qe=(e=[],t)=>{let n=Ke(t);return e.includes(n)},Je=e=>{try{let t=R(e);return{success:!0,connector:t}}catch(n){if(n instanceof ue){let r=n.issues,i=[];return r.forEach(n=>{let r=n?.keys?.[0],a=t(r)?n.path:[...n.path,r],o=Ye(a,e);i.push({line:o,message:n.message,field:a.join(`.`)})}),{success:!1,errors:i}}else if(n instanceof le)return{success:!1,errors:[{line:n.line,message:`The YAML connector file is not valid. Please check the syntax and structure.`,field:void 0}]};else if(n instanceof de){let t=Xe(n.operationId,n.stepId,n.functionName,!1,e);return{success:!1,errors:[{line:t,message:n.message,field:void 0}]}}else if(n instanceof fe){let r=n.issues,i=[];return r.forEach(r=>{let a=r?.keys?.[0],o=t(a)?r.path:[...r.path,a],s=Xe(n.operationId,n.stepId,n.functionName,!0,e);i.push({line:s,message:r.message,field:o.join(`.`)})}),{success:!1,errors:i}}}return{success:!1,errors:[{line:1,message:`An unknown error occurred while parsing the connector.`,field:void 0}]}},Ye=(e,n)=>{let r=n.split(`
5
+ `),i=0,o=-1,s=0;for(let n=0;n<r.length;n++){let c=r[n],l=c.match(/^(\s*)/)?.[1]?.length||0,u=c.replace(`- `,``).trim();if(u.startsWith(`#`)||u===``||l<=o)continue;let d=a(e[i])?`${String(e[i])}`:``;if(t(d))return s+1;if(isNaN(Number(d))){if(u.startsWith(`${d}:`)){if(i===e.length-1)return n+1;o=l,s=n,i++}}else{let e=parseInt(d,10),t=-1;for(let a=n;a<r.length;a++){let o=r[a],c=o.trim();if(c.startsWith(`-`)&&t++,t===e){i++,s=n,n--;break}else n++}}}return s+1},Xe=(e,n,r,i,o)=>{let s=o.split(`
6
+ `),c=1,l=null,u=null;for(let o=0;o<s.length;o++){let d=s[o],f=d.trim();if(t(l)&&f===`- operationId: ${e}`){l=e,c=o+1;continue}if(a(l)&&t(u)&&f===`- stepId: ${n}`){u=n,c=o+1;continue}if(a(l)&&a(u)&&!i&&f.startsWith(`functionName: ${r}`)||a(l)&&a(u)&&i&&f===`parameters:`)return c=o+1,c}return c};var H=class e extends Error{errorType;context;constructor(t,n,r){super(r),this.name=`ConnectSDKError`,this.errorType=t,this.context=n,Error.captureStackTrace&&Error.captureStackTrace(this,e)}toString(){return`${this.name} [${this.errorType}]: ${this.message}`}},Ze=class extends H{constructor(e,t){super(`CONNECTOR_PARSE_ERROR`,e,t),this.name=`ConnectorParseError`}},U=class extends H{constructor(e,t){super(`MISSING_OPERATION_ERROR`,e,t),this.name=`MissingOperationError`}},Qe=class extends H{constructor(e,t){super(`INVALID_OPERATION_INPUTS_ERROR`,e,t),this.name=`InvalidOperationInputsError`}},$e=class extends H{constructor(e,t){super(`INVALID_CURSOR_ERROR`,e,t),this.name=`InvalidCursorError`}};const et=(e,t)=>{let n=Object.keys(e.authentication??{}).map(t=>({type:`custom`,label:e.authentication?.[t].production?.label||`Custom`,key:t})),r=Object.values(e?.operations??{}).map(e=>({id:e.id,description:e.description.replace(/\b\w/g,e=>e.toUpperCase()),label:e.label.replace(/\b\w/g,e=>e.toUpperCase()),schema_type:e.schemaType,tags:e.tags,authentication:n,operation_details:t?.includes(`operation_details`)?e:void 0}));return{version:e.version,name:e.title,key:e.key,icon:e.assets?.icon,description:e.description,authentication:n,actions:r}},tt=(e,t)=>e.map(e=>et(e,t)),nt=`stackone://internal//`,rt=`${nt}refresh_token`,it=async({block:e,stepFunctionName:t,params:n,buildStepFunction:r=v.build})=>{let i=r({functionName:t}).fn,a=await i({block:e,params:n}),o=t===_.MAP_FIELDS?{[_.MAP_FIELDS.toString()]:{output:{data:a.block.result},errors:a.errors,successful:a.successful}}:{};return{...a.block,steps:{...a?.block?.steps??{},...o}}},W=({category:t,connectorKey:n,connectorVersion:r,authConfigKey:i,environment:a=`production`,operation:o,accountSecureId:s,projectSecureId:c,organizationId:l})=>({organizationId:l,projectSecureId:c,accountSecureId:s,connectorKey:n,connectorVersion:r,category:t,service:``,resource:``,schema:o?.schema?.key,operationType:o?.operationType??`unknown`,authenticationType:i,environment:a,actionRunId:e()}),at=(e,t,n)=>e.authentication?.[t]?.[n]?.testOperations,ot=e=>{let n=e.operation?.compositeIdentifiers,r={...e.inputs??{}};if(!n?.enabled||t(r))return e;let i=n.fields?.reduce((e,t)=>(t.components.forEach(t=>{t.alias&&(e[t.name]=t.alias)}),e),{}),a={version:n.version??m,aliases:i};return G(r,a,e.logger),{...e,inputs:r}},G=(e,t,n)=>{for(let r in e){let i=e[r];if(typeof i==`string`||Array.isArray(i)&&i.every(e=>typeof e==`string`))ft(i,r,e,t,n);else if(Array.isArray(i))for(let e of i)G(e,t,n);else typeof i==`object`&&i&&G(i,t,n)}},st=(e,t,n,r)=>{let i=[],a=[];for(let o of e)try{let e=ee(o,n);i.push(e)}catch(e){r?.debug({message:`Received ${t} with invalid composite ID, assuming it is not a composite ID`,category:`processCompositeId`,context:{key:t,inputElement:o,compositeIdentifierConfig:n,error:e}}),a.push(o)}return{compositeIdComponents:i,nonCompositeIds:a}},ct=(e,t,n,r)=>{let i=n.filter(e=>Object.keys(e).length>1);i.length>0&&(e.decoded_ids={...e.decoded_ids??{},[t]:r?i:i[0]})},lt=e=>{let t=Object.values(e);return t.length===1&&(typeof t[0]==`string`||typeof t[0]==`number`)},ut=(e,t,n,r,i)=>{n.every(lt)&&(i?e[t]=[...n.map(e=>Object.values(e)[0]),...r]:n.length>0&&(e[t]=Object.values(n[0])[0]))},dt=(e,t,n)=>{e instanceof h&&e.type===`COMPOSITE_ID_MISSING_HEADER_ERROR`?n?.debug({message:`Received ${t} with no composite ID header, assuming it is not a composite ID`}):n?.warning({message:`Error processing composite ID for ${t}, ignoring it`,error:e})},ft=(e,t,n,r,i)=>{try{let a=Array.isArray(e),o=a?e:[e];if(o.length===0)return;let{compositeIdComponents:s,nonCompositeIds:c}=st(o,t,r,i);ct(n,t,s,a),ut(n,t,s,c,a)}catch(e){dt(e,t,i)}},K=`remote_`,pt=e=>{let n=e.operation?.compositeIdentifiers;if(!n?.enabled)return e;let r=`data`,i=e.outputs?.[r];if(t(i))return e;let a=Array.isArray(i)?i.map(e=>mt(e,n)):mt(i,n);return{...e,outputs:{...e.outputs??{},[r]:a}}},mt=(e,t)=>{let n=ht(e,t),i=q(n);return{...e,...r(i)?i:{}}},ht=(e,t)=>{let n=t.version??m,r={};return t.fields?.forEach(t=>{let i={},a=[];t.components.forEach(t=>{t.alias&&(i[t.name]=t.alias),a.push({key:t.name,value:e[t.name]})});let o=a.length===1?a[0]:{identifiers:a},s={version:n,aliases:Object.keys(i).length>0?i:void 0},c=b(o,s);r[t.targetFieldKey]=c,t.remote&&(r[`${K}${t.remote}`]=e[t.remote])}),{...e,...r}},gt=e=>e===`id`||/.+_id(s)?$/.test(e),_t=e=>Array.isArray(e)&&e.every(e=>i(e)&&e.length>0),vt=(e,t)=>S(e)||t.startsWith(K),yt=(e,t)=>{try{return b({key:e,value:t},{version:m})}catch{return t}},bt=(e,t,n)=>{let r=t.map(t=>i(t)&&t.length>0&&!S(t)?yt(e,t):t);n[e]=r,n[`${K}${e}`]=t},xt=(e,t,n)=>{if(vt(t,e))return;let r=b({key:e,value:t},{version:m});n[e]=r,n[`remote_${e}`]=t},St=(e,t,n)=>{_t(t)?bt(e,t,n):i(t)&&t.length>0&&xt(e,t,n)},q=e=>{if(Array.isArray(e))return e.map(e=>q(e));if(!r(e))return e;let t={...e};for(let[n,i]of Object.entries(e))(r(i)||Array.isArray(i)&&i.length>0&&r(i[0]))&&(t[n]=q(i)),gt(n)&&St(n,i,t);return t},Ct=(e,t)=>{let r=Number(e.inputs?.page_size),i=a(e.inputs?.page_size)&&n(r)&&!Number.isNaN(r)?r:e.operation?.cursor?.pageSize??t;return i},J=(e,n,i,o)=>{let s=t(e)?void 0:e.data,c=Object.keys(i).length+1,l=C({cursor:o,ignoreStepIndex:c});if(!r(e)||t(s)||(s?.length??0)<=n)return{result:e,next:a(o)&&!l?w(o):null};let u=o?.remote?.[c]?.pageNumber??1,d=(u-1)*n,f=d+n,p=s.slice(d,f),m=s.length>f||!l,h=T({cursor:o,stepIndex:c,pageNumber:u+1});return{result:{...e,data:p},next:m?w(h):null}},wt=e=>{let n=e.settings?.olap;return t(n)?{}:{logs:n.logs?{enabled:n.logs.enabled}:void 0,advanced:n.advanced?{enabled:n.advanced.enabled,ttl:n.advanced.ttl,errorsOnly:n.advanced.errorsOnly}:void 0}},Y=async({block:e,buildStepFunction:t=v.build,virtualPaginateResultFn:n=J,encodeResultCompositeIds:r=pt,decodeInputCompositeIds:i=ot})=>{let a=i(e),o=await At({block:a,buildStepFunction:t,virtualPaginateResultFn:n});return r(o)},Tt=(e,t)=>e.condition?!E(e.condition,t):!1,Et=(e,t,n)=>{let r=e.stepFunction,i=y[e.stepFunction.functionName]?.[`v${e.stepFunction.version??1}`],o=a(i?.inputSchema?.shape)?`cursor`in i?.inputSchema?.shape:!1;return t.operation?.cursor.enabled&&o?{...r.params??{},cursor:{token:t.nextCursor?.remote?.[n]?.providerPageCursor,position:t.nextCursor?.remote?.[n]?.position}}:r.params??{}},Dt=(e,t,n,r,i)=>{let a=X({block:e,stepId:t,successful:!1,functionOutput:n}),o=r.ignoreError??!1;return o||(i.hasFatalError=!0,i.errorStatusCode??=n.output?.statusCode??500),a},Ot=async(e,t,n,r,i,a)=>{let o=n[e],s=o.stepFunction,c=a.buildStepFunction({functionName:s.functionName,version:s.version,validateSchemas:!0}).fn;if(Tt(o,r))return X({block:r,stepId:e,successful:!0,skipped:!0,message:`Step skipped due to condition not met.`});if(i.hasFatalError)return X({block:r,stepId:e,successful:!1,skipped:!0,message:`Step skipped due to previous error.`});let l=Et(o,r,t),u=await c({block:r,params:l});if(u.successful===!1)return Dt(r,e,u,o,i);let d=r.operation?.cursor.enabled?T({cursor:r.nextCursor,stepIndex:t,providerPageCursor:u.output?.next,position:u.output?.position}):void 0;return X({block:{...u.block,nextCursor:d},stepId:e,functionOutput:u})},kt=(e,t,n,i,o)=>{let s=!n.hasFatalError,c=s?e.operation?.responses.success.statusCode??200:n.errorStatusCode??500,l=a(o)&&r(o.result)?{next:o.next,...o.result}:i;return{...t,outputs:l,response:{successful:s,statusCode:c,message:s?void 0:e.operation?.responses?.errors?.[c]?.description??te?.[c]??`Error while processing the request`}}},At=async({block:e,buildStepFunction:t=v.build,virtualPaginateResultFn:n=J})=>{let r=e.operation?.steps||{},i={...e},a=Object.keys(r),o=Ct(e,pe),s={hasFatalError:!1,errorStatusCode:null},c={block:e,buildStepFunction:t,virtualPaginateResultFn:n};for(let[e,t]of a.entries())i=await Ot(t,e,r,i,s,c),Mt({block:i,stepId:t});let l=e.operation?.result?jt(e.operation.result,i):void 0,u=e.operation?.cursor.enabled?n(l,o,r,i.nextCursor):void 0;return kt(e,i,s,l,u)},jt=(e,t)=>r(e)?D(e,t):E(e,t),X=({block:e,stepId:t,successful:n,functionOutput:r,skipped:i,message:a})=>({...e,steps:{...e.steps,[t]:{successful:n??r?.successful??!1,errors:r?.errors,output:r?.output,skipped:i,message:a}}}),Mt=({block:e,stepId:n})=>{let r=e.olapClient;if(t(r?.recordStep))return;let i=wt(e),a=e.context,o={actionRunId:a.actionRunId??`unknown`,stepId:n,status:e.steps?.[n]?.successful?`successful`:`failed`,skipped:e.steps?.[n]?.skipped,message:e.steps?.[n]?.message};r.recordStep(o,i)},Z=async e=>{let{pathParams:n={},queryParams:r={},body:o={},headers:s={},parseConnector:c=R,parseOperationInputsFn:l=B,createBlockContextFn:u=W,createBlockFn:d=O,runStepOperationFn:f=Y,getOperationFromUrlFn:p=j,getOperationForRefreshAuthenticationFn:m=V,getTestOperationsFn:h=at,mode:g,account:_,connector:v,getHttpClient:y,getOlapClient:ee,settings:b,logger:x,category:S,...C}=e,w=_.authConfigKey,T=_.environment??`production`,te=_.secureId,ne=_.projectSecureId,re=_.organizationId,E=_.credentials,D=u({category:S??`action`,connectorKey:_.providerKey,connectorVersion:_.providerVersion,authConfigKey:w,environment:T,accountSecureId:te,projectSecureId:ne,organizationId:re}),k;try{k=i(v)?c(v):v}catch{throw new Ze(D,`Error while parsing connector`)}let A={connector:k,context:D,credentials:E,settings:b,logger:x,getHttpClient:y,getOlapClient:ee};if(g===`operation_id`){let{operationId:e}=C,i=ce(k,e);if(t(i))throw new U(D,`No matching operation found`);let a=await Q({operation:i,blockContext:D,queryParams:r,pathParams:n,body:o,headers:s,parseOperationInputsFn:l,createBlockFn:d,createBlockParams:A,runStepOperationFn:f});return $({block:a}),a}else if(g===`test_operations`){let e=h(k,w,T);if(t(e)||e.length===0){let e=await Nt(d,A);return $({block:e}),e}D.operationType=`test`;for(let n of e){let e=await d({...A,inputs:void 0,operation:n.operation,nextCursor:void 0}),r=a(n.condition)?ie(n.condition,e):!0;if(!r)continue;let i=await f({block:e});if((t(i?.response?.successful)||!i.response.successful)&&n.required){x?.error({code:`TestOperationFailed`,message:`Test operation "${n.operation.id}" failed with error: ${i?.response?.message}`});let e=await Pt(d,A);return $({block:e}),e}}let n=await Nt(d,A);return $({block:n}),n}else if(g===`refresh_authentication`){let e=m(k,w,T);if(t(e))throw new U(D,`No matching operation found`);let n=await Q({operation:e.operation,blockContext:D,queryParams:r,pathParams:e.params,body:o,headers:s,parseOperationInputsFn:l,createBlockFn:d,createBlockParams:A,runStepOperationFn:f});return $({block:n}),n}else if(g===`path`){let{path:e,method:n}=C,i=p(k,e,n);if(t(i))throw new U(D,`No matching operation found`);let a=await Q({operation:i.operation,blockContext:D,queryParams:r,pathParams:i.params,body:o,headers:s,parseOperationInputsFn:l,createBlockFn:d,createBlockParams:A,runStepOperationFn:f});return $({block:a}),a}else{let e=await Pt(d,A);return $({block:e}),e}},Q=async e=>{let{operation:t,blockContext:n,queryParams:r,pathParams:i,body:a,headers:o,parseOperationInputsFn:s,createBlockFn:c,createBlockParams:l,runStepOperationFn:u}=e;n.operationType=t.operationType,n.schema=t.schema?.key;let d=Ft(r,n),f;try{f=s(t,{path:i,query:r,body:a,headers:o})}catch{throw new Qe(n,`Error while parsing operation inputs`)}let p=await c({...l,inputs:f,operation:t,nextCursor:d});return await u({block:p})},Nt=async(e,t)=>{let n=await e({...t,inputs:void 0,operation:void 0,nextCursor:void 0});return{...n,response:{successful:!0,statusCode:200}}},Pt=async(e,t)=>{let n=await e({...t,inputs:void 0,operation:void 0,nextCursor:void 0});return{...n,response:{successful:!1,statusCode:500}}},Ft=(e,t)=>{let n=e?.next,r=a(n)&&t.operationType===`list`?x(n):void 0;if(r===null)throw new $e(t,`Invalid cursor.`);return r},$=({block:e})=>{let n=e.olapClient;if(t(n?.recordAction))return;let r=wt(e),i=e.context,a={actionRunId:e.context.actionRunId||`unknown`,actionId:e.operation?.id||`unknown`,connectorKey:i.connectorKey,connectorVersion:i.connectorVersion,category:i.category,organizationId:i.organizationId||`unknown`,projectSecureId:i.projectSecureId,accountSecureId:i.accountSecureId,originOwnerId:i.originOwnerId,originOwnerName:i.originOwnerName,httpMethod:e.operation?.entrypointHttpMethod,url:e.operation?.entrypointUrl,sourceId:i.sourceId,sourceType:i.sourceType,sourceValue:i.sourceValue,status:e.response?.successful?`success`:`error`,message:e.response?.message,outputs:e.outputs,startTime:e.statistics?.startTime,endTime:e.statistics?.endTime};n.recordAction(a,r)},It=async({operationId:e,account:t,connector:n,pathParams:r={},queryParams:i={},body:a={},headers:o={},logger:s,getHttpClient:c,getOlapClient:l,parseConnector:u=R,parseOperationInputsFn:d=B,createBlockContextFn:f=W,createBlockFn:p=O,runStepOperationFn:m=Y})=>Z({mode:`operation_id`,operationId:e,account:t,connector:n,pathParams:r,queryParams:i,body:a,headers:o,logger:s,getHttpClient:c,getOlapClient:l,parseConnector:u,parseOperationInputsFn:d,createBlockContextFn:f,createBlockFn:p,runStepOperationFn:m}),Lt=async({account:e,connector:t,category:n,path:r,method:i=`get`,queryParams:a={},body:o,headers:s,logger:c,getHttpClient:l,parseConnector:u=R,getOperationFromUrlFn:d=j,getOperationForRefreshAuthenticationFn:f=V,parseOperationInputsFn:p=B,createBlockContextFn:m=W,createBlockFn:h=O,runStepOperationFn:g=Y})=>{let _=Rt(r),v=_?await Z({mode:`refresh_authentication`,account:e,connector:t,getOperationForRefreshAuthenticationFn:f,parseConnector:u,logger:c,getHttpClient:l,parseOperationInputsFn:p,createBlockContextFn:m,createBlockFn:h,runStepOperationFn:g}):await Z({mode:`path`,account:e,category:n,connector:t,path:r,method:i,queryParams:a,body:o,headers:s,getOperationFromUrlFn:d,parseConnector:u,logger:c,getHttpClient:l,parseOperationInputsFn:p,createBlockContextFn:m,createBlockFn:h,runStepOperationFn:g});return v},Rt=e=>e===rt,zt=async({account:e,connector:t,logger:n,getHttpClient:r,parseConnector:i=R,getTestOperationsFn:a=at,createBlockContextFn:o=W,createBlockFn:s=O,runStepOperationFn:c=Y})=>{let l=await Z({mode:`test_operations`,account:e,connector:t,logger:n,getHttpClient:r,parseConnector:i,getTestOperationsFn:a,createBlockContextFn:o,createBlockFn:s,runStepOperationFn:c});return l?.response?.successful??!1};export{H as ConnectSDKError,rt as REFRESH_TOKEN_OPERATION_PATH,Ge as applyReleaseStageToConnector,O as createBlock,it as executeStepFunction,et as getActionsMeta,tt as getActionsMetaFromConnectors,j as getOperationFromUrl,Ue as getRefreshTokenExpiresIn,He as getTokenExpiresIn,We as isConnectorReleased,k as loadConnector,B as parseOperationInputs,R as parseYamlConnector,Z as runAction,It as runConnectorAction,Lt as runConnectorOperation,Y as runStepOperation,zt as runTestOperations,Ve as supportsRefreshAuthentication,Je as validateYamlConnector};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@stackone/connect-sdk",
3
- "version": "1.61.0",
3
+ "version": "1.63.0",
4
4
  "description": "",
5
5
  "main": "dist/index.js",
6
6
  "module": "dist/index.mjs",