@composio/core 0.19.0 → 0.21.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.
Files changed (97) hide show
  1. package/dist/{CustomTool-BMlZfJVz.mjs → CustomTool-B-_VjWpy.mjs} +1 -1
  2. package/dist/{CustomTool-CB5vm1Jc.d.mts → CustomTool-BHOYxLZX.d.mts} +1 -1
  3. package/dist/{FileModifierErrors-BqFmpRsm.mjs → FileModifierErrors-CdGSABoq.mjs} +1 -1
  4. package/dist/{SsrfErrors-C91YhASE.mjs → SsrfErrors-DiQldIdC.mjs} +18 -7
  5. package/dist/{Telemetry-HlftxMx6.mjs → Telemetry-JRJJYS4I.mjs} +2 -2
  6. package/dist/{cancellation-CXpfmiVo.mjs → cancellation-DV8CIi52.mjs} +2 -2
  7. package/dist/{composio-DLGaeN70.d.mts → composio-BTZsFajb.d.mts} +3149 -117
  8. package/dist/{customTool.types-BAmEh3MB.d.mts → customTool.types-D_w21L56.d.mts} +784 -56
  9. package/dist/docs/reference/sdk-reference/typescript/auth-configs.mdx +10 -10
  10. package/dist/docs/reference/sdk-reference/typescript/composio.mdx +7 -3
  11. package/dist/docs/reference/sdk-reference/typescript/connected-accounts.mdx +101 -18
  12. package/dist/docs/reference/sdk-reference/typescript/custom-toolkits.mdx +123 -0
  13. package/dist/docs/reference/sdk-reference/typescript/experimental.mdx +9 -2
  14. package/dist/docs/reference/sdk-reference/typescript/index.mdx +8 -0
  15. package/dist/docs/reference/sdk-reference/typescript/keyring.mdx +56 -0
  16. package/dist/docs/reference/sdk-reference/typescript/logs.mdx +78 -0
  17. package/dist/docs/reference/sdk-reference/typescript/mcp.mdx +15 -15
  18. package/dist/docs/reference/sdk-reference/typescript/meta.json +9 -1
  19. package/dist/docs/reference/sdk-reference/typescript/session-configs.mdx +83 -0
  20. package/dist/docs/reference/sdk-reference/typescript/session-files.mdx +10 -10
  21. package/dist/docs/reference/sdk-reference/typescript/session.mdx +86 -27
  22. package/dist/docs/reference/sdk-reference/typescript/sessions.mdx +26 -6
  23. package/dist/docs/reference/sdk-reference/typescript/toolkits.mdx +149 -12
  24. package/dist/docs/reference/sdk-reference/typescript/tools.mdx +18 -18
  25. package/dist/docs/reference/sdk-reference/typescript/triggers.mdx +25 -25
  26. package/dist/docs/reference/sdk-reference/typescript/usage.mdx +78 -0
  27. package/dist/docs/reference/sdk-reference/typescript/webhook-endpoints.mdx +162 -0
  28. package/dist/docs/reference/sdk-reference/typescript/webhook-subscriptions.mdx +218 -0
  29. package/dist/docs/reference/sdk-reference/typescript/webhooks.mdx +20 -0
  30. package/dist/{errors-BuEKehbI.mjs → errors-Dyiu3ifQ.mjs} +127 -4
  31. package/dist/experimental/index.d.mts +2 -2
  32. package/dist/experimental/index.mjs +1 -1
  33. package/dist/{fileUtils.node-L7XD8UPr.mjs → fileUtils.node-DNLhLg0W.mjs} +4 -4
  34. package/dist/index.d.mts +281 -55
  35. package/dist/index.mjs +3552 -949
  36. package/dist/models/Files.node.mjs +2 -2
  37. package/dist/{sensitiveFileUploadPaths-B6pBt9lO.mjs → sensitiveFileUploadPaths-BlLp-Yo2.mjs} +1 -1
  38. package/dist/{ssrfGuard.node-B9xQB4za.mjs → ssrfGuard.node-BZ270bcu.mjs} +1 -1
  39. package/dist/{types-CxLPO0Xq.d.mts → types-CgRsUGqm.d.mts} +2 -2
  40. package/dist/utils/config-defaults/ConfigDefaults.node.d.mts +1 -1
  41. package/dist/utils/config-defaults/ConfigDefaults.workerd.d.mts +1 -1
  42. package/dist/utils/modifiers/FileToolModifier.node.d.mts +1 -1
  43. package/dist/utils/modifiers/FileToolModifier.node.mjs +5 -5
  44. package/dist/utils/modifiers/FileToolModifier.workerd.d.mts +1 -1
  45. package/dist/utils/ssrfGuard.node.mjs +1 -1
  46. package/dist/utils/ssrfGuard.workerd.mjs +1 -1
  47. package/package.json +4 -2
  48. package/src/composio.ts +215 -10
  49. package/src/errors/ConnectedAccountsErrors.ts +47 -0
  50. package/src/errors/SDKErrors.ts +52 -0
  51. package/src/errors/ToolRouterErrors.ts +61 -0
  52. package/src/errors/index.ts +3 -0
  53. package/src/index.ts +13 -0
  54. package/src/lib/sessionConfigConflict.ts +43 -0
  55. package/src/lib/toolRouterMcp.ts +132 -0
  56. package/src/lib/toolRouterParams.ts +149 -37
  57. package/src/lib/toolRouterSourceSessionConfig.ts +12 -0
  58. package/src/models/ConnectedAccounts.ts +118 -2
  59. package/src/models/CustomToolkits.ts +169 -0
  60. package/src/models/Experimental.ts +27 -0
  61. package/src/models/Keyring.ts +65 -0
  62. package/src/models/Logs.ts +101 -0
  63. package/src/models/RemoteFile.ts +25 -8
  64. package/src/models/SessionConfigs.ts +117 -0
  65. package/src/models/ToolRouter.ts +61 -17
  66. package/src/models/ToolRouterSession.ts +149 -14
  67. package/src/models/Toolkits.ts +180 -0
  68. package/src/models/Tools.ts +10 -6
  69. package/src/models/Triggers.ts +3 -88
  70. package/src/models/Usage.ts +119 -0
  71. package/src/models/Webhooks.ts +520 -0
  72. package/src/services/pusher/Pusher.ts +17 -6
  73. package/src/types/authConfigs.types.ts +2 -0
  74. package/src/types/connectedAccounts.types.ts +54 -0
  75. package/src/types/customToolkits.types.ts +102 -0
  76. package/src/types/keyring.types.ts +32 -0
  77. package/src/types/logs.types.ts +108 -0
  78. package/src/types/sessionConfigs.types.ts +81 -0
  79. package/src/types/tool.types.ts +2 -0
  80. package/src/types/toolRouter.types.ts +352 -16
  81. package/src/types/toolkit.types.ts +144 -0
  82. package/src/types/usage.types.ts +81 -0
  83. package/src/types/webhooks.types.ts +143 -0
  84. package/src/utils/constants.ts +1 -5
  85. package/src/utils/logger.ts +39 -7
  86. package/src/utils/safePath.ts +172 -0
  87. package/src/utils/sdk.ts +385 -22
  88. package/src/utils/transformers/connectedAccounts.ts +37 -2
  89. package/src/utils/transformers/customToolkits.ts +98 -0
  90. package/src/utils/transformers/keyring.ts +24 -0
  91. package/src/utils/transformers/logs.ts +85 -0
  92. package/src/utils/transformers/sessionConfigs.ts +54 -0
  93. package/src/utils/transformers/toolRouterResponseTransform.ts +6 -0
  94. package/src/utils/transformers/toolkits.ts +106 -3
  95. package/src/utils/transformers/triggers.ts +2 -2
  96. package/src/utils/transformers/usage.ts +77 -0
  97. package/src/utils/transformers/webhooks.ts +139 -0
@@ -0,0 +1,81 @@
1
+ import { z } from 'zod/v3';
2
+
3
+ /**
4
+ * Filters shared by the usage summary and breakdown queries.
5
+ * **Experimental — shape may change in future releases.**
6
+ */
7
+ export const UsageFiltersSchema = z.object({
8
+ /** Only count events for these external end-user IDs (OR logic). */
9
+ userId: z.array(z.string()).nullable().optional(),
10
+ /** Only count events for these session IDs (OR logic). */
11
+ sessionId: z.array(z.string()).nullable().optional(),
12
+ });
13
+ export type UsageFilters = z.infer<typeof UsageFiltersSchema>;
14
+
15
+ /**
16
+ * Params for `composio.experimental.usage.summary()`.
17
+ * **Experimental — shape may change in future releases.**
18
+ */
19
+ export const UsageSummaryParamsSchema = z.object({
20
+ /** Inclusive range start (Unix epoch milliseconds). Defaults to 30 days before `to`. */
21
+ from: z.number().optional(),
22
+ /** Exclusive range end (Unix epoch milliseconds). Defaults to now. */
23
+ to: z.number().optional(),
24
+ /** Restrict to these metering entity types. Omit for all types. */
25
+ entityTypes: z.array(z.string()).optional(),
26
+ filters: UsageFiltersSchema.optional(),
27
+ });
28
+ export type UsageSummaryParams = z.infer<typeof UsageSummaryParamsSchema>;
29
+
30
+ export const UsageOrderBySchema = z.enum(['key', 'total_quantity', 'event_count']);
31
+ export const UsageOrderDirectionSchema = z.enum(['asc', 'desc']);
32
+
33
+ /**
34
+ * Params for `composio.experimental.usage.breakdown()`.
35
+ * **Experimental — shape may change in future releases.**
36
+ */
37
+ export const UsageBreakdownParamsSchema = z.object({
38
+ /** Inclusive range start (Unix epoch milliseconds). Defaults to 30 days before `to`. */
39
+ from: z.number().optional(),
40
+ /** Exclusive range end (Unix epoch milliseconds). Defaults to now. */
41
+ to: z.number().optional(),
42
+ /** Dimension to group by. Defaults to `tool_slug` for tool_calls and `user_id` for sessions. */
43
+ groupBy: z.string().optional(),
44
+ /** Field to order groups by. Defaults to `total_quantity`. */
45
+ orderBy: UsageOrderBySchema.optional(),
46
+ /** Sort direction. Defaults to `desc`. */
47
+ orderDirection: UsageOrderDirectionSchema.optional(),
48
+ /** Maximum number of groups to return. Defaults to 100, max 1000. */
49
+ limit: z.number().optional(),
50
+ filters: UsageFiltersSchema.optional(),
51
+ });
52
+ export type UsageBreakdownParams = z.infer<typeof UsageBreakdownParamsSchema>;
53
+
54
+ export const UsageEntitySummarySchema = z.object({
55
+ unit: z.string(),
56
+ totalQuantity: z.string(),
57
+ eventCount: z.number(),
58
+ });
59
+ export type UsageEntitySummary = z.infer<typeof UsageEntitySummarySchema>;
60
+
61
+ export const UsageSummaryResponseSchema = z.object({
62
+ /** Aggregates keyed by metering entity type (e.g. `tool_calls`, `sessions`). */
63
+ entities: z.record(z.string(), UsageEntitySummarySchema),
64
+ });
65
+ export type UsageSummaryResponse = z.infer<typeof UsageSummaryResponseSchema>;
66
+
67
+ export const UsageBreakdownGroupSchema = z.object({
68
+ key: z.string(),
69
+ totalQuantity: z.string(),
70
+ eventCount: z.number(),
71
+ });
72
+ export type UsageBreakdownGroup = z.infer<typeof UsageBreakdownGroupSchema>;
73
+
74
+ export const UsageBreakdownResponseSchema = z.object({
75
+ entityType: z.string(),
76
+ unit: z.string(),
77
+ totalQuantity: z.string(),
78
+ eventCount: z.number(),
79
+ groups: z.array(UsageBreakdownGroupSchema),
80
+ });
81
+ export type UsageBreakdownResponse = z.infer<typeof UsageBreakdownResponseSchema>;
@@ -0,0 +1,143 @@
1
+ import { z } from 'zod/v3';
2
+ import { SetWebhookSubscriptionParamsSchema } from './triggers.types';
3
+
4
+ /**
5
+ * Webhook payload versions accepted by the webhook subscription endpoints.
6
+ */
7
+ export const WebhookVersionSchema = z.enum(['V1', 'V2', 'V3']);
8
+
9
+ // ---------------------------------------------------------------------------
10
+ // Webhook subscriptions
11
+ // ---------------------------------------------------------------------------
12
+
13
+ /**
14
+ * A project webhook subscription in the SDK's camelCase shape. The signing
15
+ * `secret` is returned by the API on every subscription read/write.
16
+ */
17
+ export const WebhookSubscriptionSchema = z.object({
18
+ id: z.string(),
19
+ webhookUrl: z.string(),
20
+ version: WebhookVersionSchema,
21
+ enabledEvents: z.array(z.string()),
22
+ secret: z.string().optional(),
23
+ createdAt: z.string().optional(),
24
+ updatedAt: z.string().optional(),
25
+ });
26
+
27
+ export const WebhookSubscriptionListParamsSchema = z.object({
28
+ /** Number of items per page, max allowed is 50. */
29
+ limit: z.number().optional(),
30
+ /** Cursor for pagination, taken from a previous response's `nextCursor`. */
31
+ cursor: z.string().optional(),
32
+ });
33
+ export type WebhookSubscriptionListParams = z.infer<typeof WebhookSubscriptionListParamsSchema>;
34
+
35
+ export const WebhookSubscriptionListResponseSchema = z.object({
36
+ items: z.array(WebhookSubscriptionSchema),
37
+ nextCursor: z.string().nullable(),
38
+ totalPages: z.number(),
39
+ currentPage: z.number(),
40
+ totalItems: z.number(),
41
+ });
42
+ export type WebhookSubscriptionListResponse = z.infer<typeof WebhookSubscriptionListResponseSchema>;
43
+
44
+ /**
45
+ * Params for `composio.webhooks.subscriptions.set()`. Identical to the
46
+ * params accepted by `composio.triggers.setWebhookSubscription()`.
47
+ */
48
+ export const WebhookSubscriptionSetParamsSchema = SetWebhookSubscriptionParamsSchema;
49
+ export type WebhookSubscriptionSetParams = z.infer<typeof WebhookSubscriptionSetParamsSchema>;
50
+
51
+ export const WebhookSubscriptionUpdateParamsSchema = z.object({
52
+ /** HTTPS URL to receive webhook events. */
53
+ webhookUrl: z.string().min(1).optional(),
54
+ /** Event types to subscribe to. */
55
+ enabledEvents: z.array(z.string()).min(1).optional(),
56
+ /** Webhook payload version. */
57
+ version: WebhookVersionSchema.optional(),
58
+ });
59
+ export type WebhookSubscriptionUpdateParams = z.infer<typeof WebhookSubscriptionUpdateParamsSchema>;
60
+
61
+ export const WebhookSubscriptionDeleteResponseSchema = z.object({
62
+ success: z.boolean(),
63
+ });
64
+ export type WebhookSubscriptionDeleteResponse = z.infer<
65
+ typeof WebhookSubscriptionDeleteResponseSchema
66
+ >;
67
+
68
+ export const WebhookSubscriptionRotateSecretResponseSchema = z.object({
69
+ id: z.string(),
70
+ /** The new signing secret. Store it — the previous secret stops validating. */
71
+ secret: z.string(),
72
+ });
73
+ export type WebhookSubscriptionRotateSecretResponse = z.infer<
74
+ typeof WebhookSubscriptionRotateSecretResponseSchema
75
+ >;
76
+
77
+ export const WebhookSubscriptionEventTypeSchema = z.object({
78
+ eventType: z.string(),
79
+ description: z.string(),
80
+ supportedVersions: z.array(WebhookVersionSchema),
81
+ });
82
+ export type WebhookSubscriptionEventType = z.infer<typeof WebhookSubscriptionEventTypeSchema>;
83
+
84
+ export const WebhookSubscriptionEventTypesResponseSchema = z.object({
85
+ items: z.array(WebhookSubscriptionEventTypeSchema),
86
+ });
87
+ export type WebhookSubscriptionEventTypesResponse = z.infer<
88
+ typeof WebhookSubscriptionEventTypesResponseSchema
89
+ >;
90
+
91
+ // ---------------------------------------------------------------------------
92
+ // Webhook endpoints (per toolkit + OAuth app inbound ingress URLs)
93
+ // ---------------------------------------------------------------------------
94
+
95
+ export const WebhookEndpointListParamsSchema = z.object({
96
+ /** Only return endpoints for this toolkit slug. */
97
+ toolkitSlug: z.string().optional(),
98
+ });
99
+ export type WebhookEndpointListParams = z.infer<typeof WebhookEndpointListParamsSchema>;
100
+
101
+ export const WebhookEndpointListItemSchema = z.object({
102
+ id: z.string(),
103
+ toolkitSlug: z.string(),
104
+ clientId: z.string().nullable(),
105
+ });
106
+ export type WebhookEndpointListItem = z.infer<typeof WebhookEndpointListItemSchema>;
107
+
108
+ export const WebhookEndpointListResponseSchema = z.object({
109
+ items: z.array(WebhookEndpointListItemSchema),
110
+ });
111
+ export type WebhookEndpointListResponse = z.infer<typeof WebhookEndpointListResponseSchema>;
112
+
113
+ export const WebhookEndpointSchema = z.object({
114
+ id: z.string(),
115
+ toolkitSlug: z.string(),
116
+ clientId: z.string().nullable(),
117
+ /** The inbound URL to register with the third-party provider. */
118
+ webhookUrl: z.string(),
119
+ /** Configured setup fields with secret values masked. */
120
+ data: z.record(z.string(), z.string()).nullable(),
121
+ createdAt: z.string(),
122
+ });
123
+ export type WebhookEndpoint = z.infer<typeof WebhookEndpointSchema>;
124
+
125
+ export const WebhookEndpointCreateParamsSchema = z.object({
126
+ /** Toolkit identifier (e.g. `slack`, `discord`). */
127
+ toolkitSlug: z.string().min(1),
128
+ /** OAuth app client ID — identifies which app this endpoint is for. */
129
+ clientId: z.string().min(1),
130
+ });
131
+ export type WebhookEndpointCreateParams = z.infer<typeof WebhookEndpointCreateParamsSchema>;
132
+
133
+ export const WebhookEndpointReplaceParamsSchema = z.object({
134
+ /** Key-value pairs for ALL required setup fields of the toolkit. */
135
+ data: z.record(z.string(), z.string()),
136
+ });
137
+ export type WebhookEndpointReplaceParams = z.infer<typeof WebhookEndpointReplaceParamsSchema>;
138
+
139
+ export const WebhookEndpointUpdateParamsSchema = z.object({
140
+ /** Key-value pairs to merge into the setup fields. Omitted fields are preserved. */
141
+ data: z.record(z.string(), z.string()),
142
+ });
143
+ export type WebhookEndpointUpdateParams = z.infer<typeof WebhookEndpointUpdateParamsSchema>;
@@ -11,11 +11,7 @@ export const TELEMETRY_URL = 'https://app.composio.dev';
11
11
  export const CLIENT_PUSHER_KEY = getEnvVariable('CLIENT_PUSHER_KEY') || 'ff9f18c208855d77a152';
12
12
 
13
13
  export const COMPOSIO_LOG_LEVEL = getEnvVariable('COMPOSIO_LOG_LEVEL') as
14
- | 'debug'
15
- | 'info'
16
- | 'warn'
17
- | 'error'
18
- | undefined;
14
+ 'silent' | 'debug' | 'info' | 'warn' | 'error' | undefined;
19
15
 
20
16
  export const IS_DEVELOPMENT_OR_CI = getEnvVariable('DEVELOPMENT') || getEnvVariable('CI') || false;
21
17
 
@@ -23,20 +23,52 @@ export const getLogLevel = (): LogLevel => {
23
23
  return envLevel && envLevel in LOG_LEVELS ? (envLevel as LogLevel) : 'info';
24
24
  };
25
25
 
26
+ /**
27
+ * Destination for SDK log output. Each method receives the already
28
+ * formatted and redacted message as its single argument. `console` satisfies
29
+ * this interface, and so do most structured loggers (pino, winston, ...).
30
+ */
31
+ export interface ComposioLogger {
32
+ error: (...args: unknown[]) => void;
33
+ warn: (...args: unknown[]) => void;
34
+ info: (...args: unknown[]) => void;
35
+ debug: (...args: unknown[]) => void;
36
+ }
37
+
26
38
  interface LoggerOptions {
27
39
  level?: LogLevel;
28
40
  includeTimestamp?: boolean;
41
+ /** Where formatted output is written. Defaults to `console`. */
42
+ sink?: ComposioLogger;
43
+ }
44
+
45
+ export interface LoggerConfigureOptions {
46
+ level?: LogLevel;
47
+ sink?: ComposioLogger;
29
48
  }
30
49
 
31
50
  export class Logger {
32
- private readonly level: LogLevel;
51
+ private level: LogLevel;
33
52
  private readonly includeTimestamp: boolean;
34
- private readonly console: Console;
53
+ private sink: ComposioLogger;
35
54
 
36
55
  constructor(options: LoggerOptions = {}) {
37
56
  this.level = options.level ?? getLogLevel();
38
57
  this.includeTimestamp = options.includeTimestamp ?? true;
39
- this.console = console;
58
+ this.sink = options.sink ?? console;
59
+ }
60
+
61
+ /**
62
+ * Reconfigure the level and/or sink in place. Omitted fields are left
63
+ * unchanged, so `configure({ level: 'debug' })` keeps the current sink.
64
+ */
65
+ configure(options: LoggerConfigureOptions): void {
66
+ if (options.level !== undefined) this.level = options.level;
67
+ if (options.sink !== undefined) this.sink = options.sink;
68
+ }
69
+
70
+ getLevel(): LogLevel {
71
+ return this.level;
40
72
  }
41
73
 
42
74
  private formatMessage(args: unknown[]): string {
@@ -71,25 +103,25 @@ export class Logger {
71
103
 
72
104
  error(...args: unknown[]): void {
73
105
  if (this.shouldLog('error')) {
74
- this.console.error(this.formatMessage(args));
106
+ this.sink.error(this.formatMessage(args));
75
107
  }
76
108
  }
77
109
 
78
110
  warn(...args: unknown[]): void {
79
111
  if (this.shouldLog('warn')) {
80
- this.console.warn(this.formatMessage(args));
112
+ this.sink.warn(this.formatMessage(args));
81
113
  }
82
114
  }
83
115
 
84
116
  info(...args: unknown[]): void {
85
117
  if (this.shouldLog('info')) {
86
- this.console.info(this.formatMessage(args));
118
+ this.sink.info(this.formatMessage(args));
87
119
  }
88
120
  }
89
121
 
90
122
  debug(...args: unknown[]): void {
91
123
  if (this.shouldLog('debug')) {
92
- this.console.debug(this.formatMessage(args));
124
+ this.sink.debug(this.formatMessage(args));
93
125
  }
94
126
  }
95
127
  }
@@ -0,0 +1,172 @@
1
+ /**
2
+ * Filename containment for untrusted input.
3
+ *
4
+ * Every field of an API response is untrusted, including filenames. When such a
5
+ * value becomes part of a filesystem path it must pass through this module
6
+ * first, and validation must happen before any `mkdir` or write so a rejected
7
+ * value leaves nothing behind on disk.
8
+ *
9
+ * TypeScript counterpart of `safe_basename` in `python/composio/utils/safe_path.py`.
10
+ * The two use the same validation order and whitespace rules. Path extraction
11
+ * is intentionally limited here; see `untrustedBasename`.
12
+ *
13
+ * Pure string logic with no filesystem access: no static `node:*` imports, so
14
+ * it is usable from edge/workerd builds.
15
+ */
16
+ import { ValidationError } from '../errors/ValidationErrors';
17
+
18
+ /**
19
+ * Upper bound on a filename, well under the 255-byte limit common to
20
+ * ext4/APFS/NTFS. Keeps a long server-supplied name from failing with a raw
21
+ * `ENAMETOOLONG` mid-write. Matches `MAX_COMPONENT_LENGTH` in the Python SDK.
22
+ */
23
+ export const MAX_FILENAME_BYTES = 128;
24
+
25
+ /**
26
+ * Reserved DOS device names. Writing to one on Windows targets the device
27
+ * rather than a file. Rejected on every platform so behavior does not diverge
28
+ * between a POSIX developer machine and a Windows deployment.
29
+ */
30
+ const WINDOWS_RESERVED_NAMES: ReadonlySet<string> = new Set([
31
+ 'CON',
32
+ 'PRN',
33
+ 'AUX',
34
+ 'NUL',
35
+ ...Array.from({ length: 9 }, (_, i) => `COM${i + 1}`),
36
+ ...Array.from({ length: 9 }, (_, i) => `LPT${i + 1}`),
37
+ ...['¹', '²', '³'].flatMap(superscript => [`COM${superscript}`, `LPT${superscript}`]),
38
+ ]);
39
+
40
+ /** Control characters and characters reserved by Windows. */
41
+ const WINDOWS_INVALID_CHARS = /[\u0000-\u001f<>:"|?*]/;
42
+
43
+ /**
44
+ * Python str.strip() whitespace: Unicode White_Space plus U+001C–U+001F.
45
+ * Unlike JavaScript trim(), this includes U+0085 and preserves U+FEFF.
46
+ */
47
+ const PYTHON_WHITESPACE =
48
+ '[\\u0009-\\u000d\\u001c-\\u0020\\u0085\\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000]';
49
+ const SURROUNDING_WHITESPACE = new RegExp(`^${PYTHON_WHITESPACE}+|${PYTHON_WHITESPACE}+$`, 'g');
50
+
51
+ /**
52
+ * Returns the last path segment of `value`, treating both `/` and `\` as
53
+ * separators, or `''` when there is none.
54
+ *
55
+ * `path.basename()` on POSIX only splits on `/`, so a name crafted for a
56
+ * Windows target (`..\..\evil`) comes back intact on macOS and Linux. Splitting
57
+ * on both and removing an initial drive prefix also handles `C:report.txt`.
58
+ * This is not a full `PureWindowsPath` parser: dot components stay literal,
59
+ * and UNC anchors are not interpreted.
60
+ *
61
+ * Never throws: this is a display value as well as the input to
62
+ * {@link safeBasename}, and it is read while constructing download errors.
63
+ */
64
+ export function untrustedBasename(value: string): string {
65
+ const segments = value.replace(/^[a-z]:/i, '').split(/[/\\]+/);
66
+ // Trailing separators name the same file: `a/b/` and `a/b` both basename to `b`.
67
+ while (segments.length > 0 && segments[segments.length - 1] === '') {
68
+ segments.pop();
69
+ }
70
+ return segments[segments.length - 1] ?? '';
71
+ }
72
+
73
+ /**
74
+ * True when `value` contains a surrogate code unit that is not part of a valid
75
+ * pair. Such a string cannot be encoded as UTF-8; `TextEncoder` silently
76
+ * substitutes U+FFFD, which would write a file under a name the response never
77
+ * specified. `String.prototype.isWellFormed()` is ES2024 and this package
78
+ * targets es2022, hence the manual scan.
79
+ */
80
+ function hasLoneSurrogate(value: string): boolean {
81
+ for (let i = 0; i < value.length; i++) {
82
+ const code = value.charCodeAt(i);
83
+ if (code >= 0xd800 && code <= 0xdbff) {
84
+ const next = value.charCodeAt(i + 1);
85
+ if (!(next >= 0xdc00 && next <= 0xdfff)) {
86
+ return true;
87
+ }
88
+ i++;
89
+ } else if (code >= 0xdc00 && code <= 0xdfff) {
90
+ return true;
91
+ }
92
+ }
93
+ return false;
94
+ }
95
+
96
+ /**
97
+ * Collapses an untrusted filename to a bare, writable basename.
98
+ *
99
+ * Applies, in order: no usable basename (empty or a run of dots once
100
+ * surrounding whitespace is stripped), NUL bytes, control and Windows-reserved
101
+ * characters, trailing space or dot, invalid Unicode, a byte-length bound, and
102
+ * reserved device names. This is the order `safe_basename` uses in the Python
103
+ * SDK. This implementation rejects lone surrogates rather than relying on
104
+ * Python filesystem encoding behavior.
105
+ *
106
+ * Names that leave no usable basename are refused rather than replaced with a
107
+ * generated one: a response that cannot name its own file is malformed or
108
+ * hostile, and inventing a name would hide that. `""`, `"."` and `".."` make
109
+ * an output path equal to, or escape, its own directory, which surfaces as a
110
+ * raw `EISDIR` at write time instead of a validation error.
111
+ *
112
+ * The usability check runs on the *trimmed* basename because that is what gets
113
+ * written: Python-compatible stripping removes whitespace, so `"\u00a0.\u00a0"` would
114
+ * otherwise pass a check on the raw segment and then be written as `"."`. The
115
+ * hazard checks that follow run on the raw segment so a trailing ASCII space or
116
+ * dot is refused, not trimmed away. Check the stripped value for trailing dots
117
+ * too, since stripping whitespace can expose one.
118
+ *
119
+ * @param name - The untrusted filename or relative path to reduce.
120
+ * @param label - How the value is described in error messages.
121
+ * @returns The validated bare basename, with surrounding whitespace trimmed.
122
+ * @throws ValidationError if `name` yields no usable basename or is unsafe to write.
123
+ */
124
+ export function safeBasename(name: string, label: string = 'filename'): string {
125
+ const rawBasename = untrustedBasename(name);
126
+ const basename = rawBasename.replace(SURROUNDING_WHITESPACE, '');
127
+
128
+ if (!basename || /^\.+$/.test(basename)) {
129
+ throw new ValidationError(
130
+ `Path traversal detected: ${label} ${JSON.stringify(name)} leaves no usable basename to write to.`
131
+ );
132
+ }
133
+ if (rawBasename.includes('\u0000')) {
134
+ throw new ValidationError(
135
+ `Refusing to write ${label} containing a NUL byte: ${JSON.stringify(name)}`
136
+ );
137
+ }
138
+ if (WINDOWS_INVALID_CHARS.test(rawBasename)) {
139
+ throw new ValidationError(
140
+ `Refusing to write ${label} containing characters reserved by Windows: ${JSON.stringify(name)}`
141
+ );
142
+ }
143
+ if (rawBasename.endsWith(' ') || rawBasename.endsWith('.') || basename.endsWith('.')) {
144
+ throw new ValidationError(
145
+ `Refusing to write ${label} ending in a space or dot: ${JSON.stringify(name)}`
146
+ );
147
+ }
148
+ if (hasLoneSurrogate(basename)) {
149
+ throw new ValidationError(
150
+ `Refusing to write ${label} containing invalid Unicode: ${JSON.stringify(name)}`
151
+ );
152
+ }
153
+
154
+ const encodedLength = new TextEncoder().encode(basename).length;
155
+ if (encodedLength > MAX_FILENAME_BYTES) {
156
+ throw new ValidationError(
157
+ `Refusing to write ${label} longer than ${MAX_FILENAME_BYTES} bytes: ` +
158
+ `${JSON.stringify(basename.slice(0, 32))}... (${encodedLength} bytes)`
159
+ );
160
+ }
161
+
162
+ // Compare everything before the first dot: on Windows `NUL.tar.gz` opens the
163
+ // null device just as `NUL` does, so extensions provide no protection.
164
+ const deviceName = basename.split('.', 1)[0].replace(/ +$/, '').toUpperCase();
165
+ if (WINDOWS_RESERVED_NAMES.has(deviceName)) {
166
+ throw new ValidationError(
167
+ `Refusing to write ${label} that is a reserved device name: ${JSON.stringify(name)}`
168
+ );
169
+ }
170
+
171
+ return basename;
172
+ }