@tidegate/sdk 0.1.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/LICENSE +204 -0
- package/README.md +142 -0
- package/dist/action-bridge.d.ts +106 -0
- package/dist/action-bridge.js +407 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.js +0 -0
- package/dist/server.d.ts +21 -0
- package/dist/server.js +57 -0
- package/package.json +35 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,204 @@
|
|
|
1
|
+
Copyright 2026 Emanuele Puccetti
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
Apache License
|
|
5
|
+
Version 2.0, January 2004
|
|
6
|
+
http://www.apache.org/licenses/
|
|
7
|
+
|
|
8
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
9
|
+
|
|
10
|
+
1. Definitions.
|
|
11
|
+
|
|
12
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
13
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
14
|
+
|
|
15
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
16
|
+
the copyright owner that is granting the License.
|
|
17
|
+
|
|
18
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
19
|
+
other entities that control, are controlled by, or are under common
|
|
20
|
+
control with that entity. For the purposes of this definition,
|
|
21
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
22
|
+
direction or management of such entity, whether by contract or
|
|
23
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
24
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
25
|
+
|
|
26
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
27
|
+
exercising permissions granted by this License.
|
|
28
|
+
|
|
29
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
30
|
+
including but not limited to software source code, documentation
|
|
31
|
+
source, and configuration files.
|
|
32
|
+
|
|
33
|
+
"Object" form shall mean any form resulting from mechanical
|
|
34
|
+
transformation or translation of a Source form, including but
|
|
35
|
+
not limited to compiled object code, generated documentation,
|
|
36
|
+
and conversions to other media types.
|
|
37
|
+
|
|
38
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
39
|
+
Object form, made available under the License, as indicated by a
|
|
40
|
+
copyright notice that is included in or attached to the work
|
|
41
|
+
(an example is provided in the Appendix below).
|
|
42
|
+
|
|
43
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
44
|
+
form, that is based on (or derived from) the Work and for which the
|
|
45
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
46
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
47
|
+
of this License, Derivative Works shall not include works that remain
|
|
48
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
49
|
+
the Work and Derivative Works thereof.
|
|
50
|
+
|
|
51
|
+
"Contribution" shall mean any work of authorship, including
|
|
52
|
+
the original version of the Work and any modifications or additions
|
|
53
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
54
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
55
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
56
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
57
|
+
means any form of electronic, verbal, or written communication sent
|
|
58
|
+
to the Licensor or its representatives, including but not limited to
|
|
59
|
+
communication on electronic mailing lists, source code control systems,
|
|
60
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
61
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
62
|
+
excluding communication that is conspicuously marked or otherwise
|
|
63
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
64
|
+
|
|
65
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
66
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
67
|
+
subsequently incorporated within the Work.
|
|
68
|
+
|
|
69
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
70
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
71
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
72
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
73
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
74
|
+
Work and such Derivative Works in Source or Object form.
|
|
75
|
+
|
|
76
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
77
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
78
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
79
|
+
(except as stated in this section) patent license to make, have made,
|
|
80
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
81
|
+
where such license applies only to those patent claims licensable
|
|
82
|
+
by such Contributor that are necessarily infringed by their
|
|
83
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
84
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
85
|
+
institute patent litigation against any entity (including a
|
|
86
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
87
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
88
|
+
or contributory patent infringement, then any patent licenses
|
|
89
|
+
granted to You under this License for that Work shall terminate
|
|
90
|
+
as of the date such litigation is filed.
|
|
91
|
+
|
|
92
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
93
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
94
|
+
modifications, and in Source or Object form, provided that You
|
|
95
|
+
meet the following conditions:
|
|
96
|
+
|
|
97
|
+
(a) You must give any other recipients of the Work or
|
|
98
|
+
Derivative Works a copy of this License; and
|
|
99
|
+
|
|
100
|
+
(b) You must cause any modified files to carry prominent notices
|
|
101
|
+
stating that You changed the files; and
|
|
102
|
+
|
|
103
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
104
|
+
that You distribute, all copyright, patent, trademark, and
|
|
105
|
+
attribution notices from the Source form of the Work,
|
|
106
|
+
excluding those notices that do not pertain to any part of
|
|
107
|
+
the Derivative Works; and
|
|
108
|
+
|
|
109
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
110
|
+
distribution, then any Derivative Works that You distribute must
|
|
111
|
+
include a readable copy of the attribution notices contained
|
|
112
|
+
within such NOTICE file, excluding those notices that do not
|
|
113
|
+
pertain to any part of the Derivative Works, in at least one
|
|
114
|
+
of the following places: within a NOTICE text file distributed
|
|
115
|
+
as part of the Derivative Works; within the Source form or
|
|
116
|
+
documentation, if provided along with the Derivative Works; or,
|
|
117
|
+
within a display generated by the Derivative Works, if and
|
|
118
|
+
wherever such third-party notices normally appear. The contents
|
|
119
|
+
of the NOTICE file are for informational purposes only and
|
|
120
|
+
do not modify the License. You may add Your own attribution
|
|
121
|
+
notices within Derivative Works that You distribute, alongside
|
|
122
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
123
|
+
that such additional attribution notices cannot be construed
|
|
124
|
+
as modifying the License.
|
|
125
|
+
|
|
126
|
+
You may add Your own copyright statement to Your modifications and
|
|
127
|
+
may provide additional or different license terms and conditions
|
|
128
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
129
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
130
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
131
|
+
the conditions stated in this License.
|
|
132
|
+
|
|
133
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
134
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
135
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
136
|
+
this License, without any additional terms or conditions.
|
|
137
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
138
|
+
the terms of any separate license agreement you may have executed
|
|
139
|
+
with Licensor regarding such Contributions.
|
|
140
|
+
|
|
141
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
142
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
143
|
+
except as required for reasonable and customary use in describing the
|
|
144
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
145
|
+
|
|
146
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
147
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
148
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
149
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
150
|
+
implied, including, without limitation, any warranties or conditions
|
|
151
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
152
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
153
|
+
appropriateness of using or redistributing the Work and assume any
|
|
154
|
+
risks associated with Your exercise of permissions under this License.
|
|
155
|
+
|
|
156
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
157
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
158
|
+
unless required by applicable law (such as deliberate and grossly
|
|
159
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
160
|
+
liable to You for damages, including any direct, indirect, special,
|
|
161
|
+
incidental, or consequential damages of any character arising as a
|
|
162
|
+
result of this License or out of the use or inability to use the
|
|
163
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
164
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
165
|
+
other commercial damages or losses), even if such Contributor
|
|
166
|
+
has been advised of the possibility of such damages.
|
|
167
|
+
|
|
168
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
169
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
170
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
171
|
+
or other liability obligations and/or rights consistent with this
|
|
172
|
+
License. However, in accepting such obligations, You may act only
|
|
173
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
174
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
175
|
+
defend, and hold each Contributor harmless for any liability
|
|
176
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
177
|
+
of your accepting any such warranty or additional liability.
|
|
178
|
+
|
|
179
|
+
END OF TERMS AND CONDITIONS
|
|
180
|
+
|
|
181
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
182
|
+
|
|
183
|
+
To apply the Apache License to your work, attach the following
|
|
184
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
185
|
+
replaced with your own identifying information. (Don't include
|
|
186
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
187
|
+
comment syntax for the file format. We also recommend that a
|
|
188
|
+
file or class name and description of purpose be included on the
|
|
189
|
+
same "printed page" as the copyright notice for easier
|
|
190
|
+
identification within third-party archives.
|
|
191
|
+
|
|
192
|
+
Copyright [yyyy] [name of copyright owner]
|
|
193
|
+
|
|
194
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
195
|
+
you may not use this file except in compliance with the License.
|
|
196
|
+
You may obtain a copy of the License at
|
|
197
|
+
|
|
198
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
199
|
+
|
|
200
|
+
Unless required by applicable law or agreed to in writing, software
|
|
201
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
202
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
203
|
+
See the License for the specific language governing permissions and
|
|
204
|
+
limitations under the License.
|
package/README.md
ADDED
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
# Tidegate SDK
|
|
2
|
+
|
|
3
|
+
Minimal TypeScript SDK for connecting a trusted server to Tidegate.
|
|
4
|
+
|
|
5
|
+
Server/API-key helpers live under `@tidegate/sdk/server` so they are not
|
|
6
|
+
pulled into browser bundles from the root package entrypoint.
|
|
7
|
+
|
|
8
|
+
## Action bridge
|
|
9
|
+
|
|
10
|
+
Use the action bridge to expose your backend capabilities to Tidegate. Tidegate can call
|
|
11
|
+
only registered actions that are also allowlisted by the invoking interaction,
|
|
12
|
+
with input validation, declared-output validation, and server-derived auth.
|
|
13
|
+
|
|
14
|
+
```txt
|
|
15
|
+
TIDEGATE_ACTION_BRIDGE_SECRET=shared_secret_from_eve
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
```ts
|
|
19
|
+
import { z } from "zod";
|
|
20
|
+
import {
|
|
21
|
+
createTidegateActionCatalogManifest,
|
|
22
|
+
createTidegateActionHandler,
|
|
23
|
+
defineTidegateActions,
|
|
24
|
+
tidegateAction,
|
|
25
|
+
} from "@tidegate/sdk/server";
|
|
26
|
+
|
|
27
|
+
const BookingCancelInput = z.object({
|
|
28
|
+
appointmentId: z.string().min(1),
|
|
29
|
+
reason: z.string().optional(),
|
|
30
|
+
});
|
|
31
|
+
|
|
32
|
+
const BookingCancelOutput = z.object({
|
|
33
|
+
ok: z.boolean(),
|
|
34
|
+
appointmentId: z.string(),
|
|
35
|
+
});
|
|
36
|
+
|
|
37
|
+
const actions = defineTidegateActions({
|
|
38
|
+
booking: {
|
|
39
|
+
cancel: tidegateAction({
|
|
40
|
+
input: BookingCancelInput,
|
|
41
|
+
returns: BookingCancelOutput,
|
|
42
|
+
effects: "write",
|
|
43
|
+
requiredPermissions: ["booking:write"],
|
|
44
|
+
tenantScope: { fromAuth: "tenantId" },
|
|
45
|
+
|
|
46
|
+
async execute(input, ctx) {
|
|
47
|
+
return cancelAppointment({
|
|
48
|
+
appointmentId: input.appointmentId,
|
|
49
|
+
reason: input.reason,
|
|
50
|
+
tenantId: ctx.auth.tenantId!,
|
|
51
|
+
});
|
|
52
|
+
},
|
|
53
|
+
}),
|
|
54
|
+
},
|
|
55
|
+
});
|
|
56
|
+
|
|
57
|
+
export const POST = createTidegateActionHandler(actions);
|
|
58
|
+
|
|
59
|
+
export const manifest = createTidegateActionCatalogManifest(actions, {
|
|
60
|
+
catalogId: "salone-ai",
|
|
61
|
+
version: "2026-06-24T00:00:00.000Z",
|
|
62
|
+
});
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
`returns` is optional, like Convex return validators. If you omit it, TypeScript
|
|
66
|
+
still infers the return type of `execute` without a `Promise<...>` annotation,
|
|
67
|
+
and Tidegate emits a permissive output contract until static return-type codegen is
|
|
68
|
+
enabled:
|
|
69
|
+
|
|
70
|
+
```ts
|
|
71
|
+
const actions = defineTidegateActions({
|
|
72
|
+
booking: {
|
|
73
|
+
cancel: tidegateAction({
|
|
74
|
+
input: BookingCancelInput,
|
|
75
|
+
effects: "write",
|
|
76
|
+
|
|
77
|
+
async execute(input, ctx) {
|
|
78
|
+
return {
|
|
79
|
+
ok: true,
|
|
80
|
+
appointmentId: input.appointmentId,
|
|
81
|
+
tenantId: ctx.auth.tenantId,
|
|
82
|
+
};
|
|
83
|
+
},
|
|
84
|
+
}),
|
|
85
|
+
},
|
|
86
|
+
});
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
The request body is limited to `actionId`, `input`, and optional `invocationId`.
|
|
90
|
+
Do not accept `tenantId`, roles, permissions, or user ids from the body. The
|
|
91
|
+
handler derives auth and the interaction action allowlist from the verified Tidegate
|
|
92
|
+
request.
|
|
93
|
+
|
|
94
|
+
The manifest is not executable code. Tidegate uses it to generate a sandbox
|
|
95
|
+
TypeScript client such as `ctx.capabilities.booking.cancel(...)`; the real
|
|
96
|
+
backend action still executes only through `createTidegateActionHandler(...)`.
|
|
97
|
+
The SDK normalizes the namespaced action tree above to the stable wire action id
|
|
98
|
+
`booking.cancel` for manifests, audit logs, allowlists, and bridge calls.
|
|
99
|
+
|
|
100
|
+
## Server invoke
|
|
101
|
+
|
|
102
|
+
Use `interactions.invoke` when your backend, job, or UI server action wants to
|
|
103
|
+
execute a public Tidegate interaction. This is separate from exposing backend actions
|
|
104
|
+
to Tidegate.
|
|
105
|
+
|
|
106
|
+
Set the API key in the server environment:
|
|
107
|
+
|
|
108
|
+
```txt
|
|
109
|
+
TIDEGATE_API_KEY=evk_live_...
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
Then call a public interaction id:
|
|
113
|
+
|
|
114
|
+
```ts
|
|
115
|
+
import { createTidegateServerClient } from "@tidegate/sdk/server";
|
|
116
|
+
|
|
117
|
+
const tidegate = createTidegateServerClient();
|
|
118
|
+
|
|
119
|
+
const result = await tidegate.interactions.invoke("ix.booking.cancelAppointment", {
|
|
120
|
+
interactionVersion: "1",
|
|
121
|
+
input: {
|
|
122
|
+
appointmentId: "apt_123",
|
|
123
|
+
reason: "Client requested cancellation",
|
|
124
|
+
},
|
|
125
|
+
surfaceId: "booking-page",
|
|
126
|
+
sessionId: "sess_123",
|
|
127
|
+
messageId: "msg_123",
|
|
128
|
+
idempotencyKey: "ix.booking.cancelAppointment:sess_123:apt_123",
|
|
129
|
+
});
|
|
130
|
+
```
|
|
131
|
+
|
|
132
|
+
The SDK validates both the request envelope and Tidegate's response with
|
|
133
|
+
`@tidegate/contracts`.
|
|
134
|
+
|
|
135
|
+
For local development, staging, or self-hosting, pass explicit overrides:
|
|
136
|
+
|
|
137
|
+
```ts
|
|
138
|
+
const tidegate = createTidegateServerClient({
|
|
139
|
+
apiKey: process.env.CUSTOM_TIDEGATE_API_KEY,
|
|
140
|
+
baseUrl: "http://localhost:3000/api/tidegate/v1",
|
|
141
|
+
});
|
|
142
|
+
```
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import { TIDEGATE_ACTION_ALLOWED_ACTIONS_HEADER, TIDEGATE_ACTION_AUTH_CONTEXT_HEADER, TIDEGATE_ACTION_INTERACTION_ID_HEADER, TIDEGATE_ACTION_BRIDGE_SECRET_HEADER, TidegateActionErrorCodeSchema, TidegateActionInvokeRequestSchema, TidegateActionInvokeResponseSchema, type TidegateAuthContext, type TidegateActionAuditPolicy, type TidegateActionCatalogManifestV1, type TidegateActionEffect, type TidegateActionErrorCode, type TidegateActionInvokeRequest, type TidegateActionInvokeResponse, type TidegateActionTenantScope } from "@tidegate/contracts";
|
|
3
|
+
export { TIDEGATE_ACTION_ALLOWED_ACTIONS_HEADER, TIDEGATE_ACTION_AUTH_CONTEXT_HEADER, TIDEGATE_ACTION_INTERACTION_ID_HEADER, TIDEGATE_ACTION_BRIDGE_SECRET_HEADER, TidegateActionErrorCodeSchema, TidegateActionInvokeRequestSchema, TidegateActionInvokeResponseSchema, };
|
|
4
|
+
export type { TidegateActionEffect, TidegateActionErrorCode, TidegateActionInvokeRequest, TidegateActionInvokeResponse, };
|
|
5
|
+
export type TidegateActionExecuteArgs<TInput> = {
|
|
6
|
+
input: TInput;
|
|
7
|
+
auth: TidegateAuthContext;
|
|
8
|
+
request: Request;
|
|
9
|
+
signal: AbortSignal;
|
|
10
|
+
/**
|
|
11
|
+
* The runtime invocation id from the invoke request, when present. Use it
|
|
12
|
+
* to correlate downstream calls with the Tidegate execution trace.
|
|
13
|
+
*/
|
|
14
|
+
invocationId?: string;
|
|
15
|
+
};
|
|
16
|
+
export type TidegateActionExecuteContext = Omit<TidegateActionExecuteArgs<unknown>, "input">;
|
|
17
|
+
type MaybePromise<T> = Promise<T> | T;
|
|
18
|
+
type TidegateActionMetadata = {
|
|
19
|
+
description?: string;
|
|
20
|
+
effects: TidegateActionEffect;
|
|
21
|
+
requiredPermissions?: string[];
|
|
22
|
+
tenantScope?: TidegateActionTenantScope;
|
|
23
|
+
audit?: Partial<TidegateActionAuditPolicy>;
|
|
24
|
+
};
|
|
25
|
+
export type TidegateActionDefinition<TInputSchema extends z.ZodType = z.ZodType, TReturnsSchema extends z.ZodType | undefined = z.ZodType | undefined, TOutput = TReturnsSchema extends z.ZodType ? z.infer<TReturnsSchema> : unknown> = TidegateActionMetadata & {
|
|
26
|
+
input: TInputSchema;
|
|
27
|
+
returns?: TReturnsSchema;
|
|
28
|
+
/**
|
|
29
|
+
* @deprecated Use `returns` for new actions. `output` remains supported for
|
|
30
|
+
* existing flat action definitions.
|
|
31
|
+
*/
|
|
32
|
+
output?: TReturnsSchema;
|
|
33
|
+
execute: (args: TidegateActionExecuteArgs<z.infer<TInputSchema>>) => MaybePromise<TOutput>;
|
|
34
|
+
};
|
|
35
|
+
export type AnyTidegateActionDefinition = TidegateActionDefinition<any, any>;
|
|
36
|
+
export type TidegateActionNormalizedDefinition<TInputSchema extends z.ZodType = z.ZodType, TOutputSchema extends z.ZodType = z.ZodType> = TidegateActionMetadata & {
|
|
37
|
+
input: TInputSchema;
|
|
38
|
+
output: TOutputSchema;
|
|
39
|
+
returns?: TOutputSchema;
|
|
40
|
+
execute: (args: TidegateActionExecuteArgs<z.infer<TInputSchema>>) => MaybePromise<z.infer<TOutputSchema>>;
|
|
41
|
+
};
|
|
42
|
+
export type TidegateActionBuilderDefinition<TInputSchema extends z.ZodType = z.ZodType, TOutput = unknown> = TidegateActionMetadata & {
|
|
43
|
+
input: TInputSchema;
|
|
44
|
+
returns?: undefined;
|
|
45
|
+
execute: (input: z.infer<TInputSchema>, ctx: TidegateActionExecuteContext) => MaybePromise<TOutput>;
|
|
46
|
+
};
|
|
47
|
+
export type TidegateActionBuilderWithReturnsDefinition<TInputSchema extends z.ZodType = z.ZodType, TReturnsSchema extends z.ZodType = z.ZodType> = TidegateActionMetadata & {
|
|
48
|
+
input: TInputSchema;
|
|
49
|
+
returns: TReturnsSchema;
|
|
50
|
+
execute: (input: z.infer<TInputSchema>, ctx: TidegateActionExecuteContext) => MaybePromise<z.infer<TReturnsSchema>>;
|
|
51
|
+
};
|
|
52
|
+
export type TidegateActionShorthandWithReturnsDefinition<TInputSchema extends z.ZodType = z.ZodType, TReturnsSchema extends z.ZodType = z.ZodType> = TidegateActionBuilderWithReturnsDefinition<TInputSchema, TReturnsSchema>;
|
|
53
|
+
export type TidegateActionLegacyShorthandDefinition<TInputSchema extends z.ZodType = z.ZodType, TOutputSchema extends z.ZodType = z.ZodType> = TidegateActionMetadata & {
|
|
54
|
+
/**
|
|
55
|
+
* @deprecated Use `input`.
|
|
56
|
+
*/
|
|
57
|
+
inputSchema: TInputSchema;
|
|
58
|
+
/**
|
|
59
|
+
* @deprecated Use `returns`.
|
|
60
|
+
*/
|
|
61
|
+
outputSchema: TOutputSchema;
|
|
62
|
+
execute: (input: z.infer<TInputSchema>, ctx: TidegateActionExecuteContext) => MaybePromise<z.infer<TOutputSchema>>;
|
|
63
|
+
};
|
|
64
|
+
export type TidegateActionShorthandDefinition<TInputSchema extends z.ZodType = z.ZodType, TOutputSchema extends z.ZodType = z.ZodType> = TidegateActionLegacyShorthandDefinition<TInputSchema, TOutputSchema>;
|
|
65
|
+
export type TidegateActionCatalogNode = AnyTidegateActionDefinition | {
|
|
66
|
+
readonly [segment: string]: TidegateActionCatalogNode;
|
|
67
|
+
};
|
|
68
|
+
export type TidegateActionCatalog = {
|
|
69
|
+
readonly [segment: string]: TidegateActionCatalogNode;
|
|
70
|
+
};
|
|
71
|
+
export type CreateTidegateActionCatalogManifestOptions = {
|
|
72
|
+
catalogId: string;
|
|
73
|
+
version?: string;
|
|
74
|
+
};
|
|
75
|
+
export type TidegateVerifiedActionRequest = {
|
|
76
|
+
auth: TidegateAuthContext;
|
|
77
|
+
allowedActionIds: string[];
|
|
78
|
+
interactionId?: string;
|
|
79
|
+
};
|
|
80
|
+
export type TidegateActionRequestVerifier = (request: Request) => Promise<TidegateVerifiedActionRequest> | TidegateVerifiedActionRequest;
|
|
81
|
+
export type CreateTidegateActionHandlerOptions = {
|
|
82
|
+
actionBridgeSecret?: string;
|
|
83
|
+
verifyRequest?: TidegateActionRequestVerifier;
|
|
84
|
+
};
|
|
85
|
+
export declare class TidegateActionHandlerError extends Error {
|
|
86
|
+
name: string;
|
|
87
|
+
readonly code: TidegateActionErrorCode;
|
|
88
|
+
readonly httpStatus: number;
|
|
89
|
+
readonly responseStatus: "rejected" | "failed";
|
|
90
|
+
constructor(code: TidegateActionErrorCode, message: string, httpStatus: number, responseStatus?: "rejected" | "failed");
|
|
91
|
+
}
|
|
92
|
+
export declare class TidegateActionCatalogError extends Error {
|
|
93
|
+
name: string;
|
|
94
|
+
}
|
|
95
|
+
export declare function tidegateAction<TInputSchema extends z.ZodType, TOutputSchema extends z.ZodType>(definition: TidegateActionNormalizedDefinition<TInputSchema, TOutputSchema>): TidegateActionDefinition<TInputSchema, TOutputSchema, z.infer<TOutputSchema>>;
|
|
96
|
+
export declare function tidegateAction<TInputSchema extends z.ZodType, TOutput>(definition: TidegateActionBuilderDefinition<TInputSchema, TOutput>): TidegateActionDefinition<TInputSchema, undefined, Awaited<TOutput>>;
|
|
97
|
+
export declare function tidegateAction<TInputSchema extends z.ZodType, TReturnsSchema extends z.ZodType>(definition: TidegateActionBuilderWithReturnsDefinition<TInputSchema, TReturnsSchema>): TidegateActionDefinition<TInputSchema, TReturnsSchema, z.infer<TReturnsSchema>>;
|
|
98
|
+
export declare function tidegateAction<TInputSchema extends z.ZodType, TOutputSchema extends z.ZodType>(definition: TidegateActionLegacyShorthandDefinition<TInputSchema, TOutputSchema>): TidegateActionDefinition<TInputSchema, TOutputSchema, z.infer<TOutputSchema>>;
|
|
99
|
+
export declare function defineTidegateActions<TActions extends Record<string, AnyTidegateActionDefinition>>(actions: TActions): TActions;
|
|
100
|
+
export declare function defineTidegateActions<TActions extends TidegateActionCatalog>(actions: TActions): TActions;
|
|
101
|
+
export declare function createTidegateActionCatalogManifest<TActions extends TidegateActionCatalog>(actions: TActions, { catalogId, version, }: CreateTidegateActionCatalogManifestOptions): TidegateActionCatalogManifestV1;
|
|
102
|
+
export declare function createTidegateActionHandler<TActions extends TidegateActionCatalog>(actions: TActions, { actionBridgeSecret, verifyRequest, }?: CreateTidegateActionHandlerOptions): (request: Request) => Promise<Response>;
|
|
103
|
+
export declare function verifyTidegateActionRequest({ actionBridgeSecret, request, }: {
|
|
104
|
+
actionBridgeSecret?: string;
|
|
105
|
+
request: Request;
|
|
106
|
+
}): TidegateVerifiedActionRequest;
|
|
@@ -0,0 +1,407 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import { TidegateAuthContextSchema, TIDEGATE_ACTION_ALLOWED_ACTIONS_HEADER, TIDEGATE_ACTION_AUTH_CONTEXT_HEADER, TIDEGATE_ACTION_INTERACTION_ID_HEADER, TIDEGATE_ACTION_BRIDGE_SECRET_HEADER, TidegateActionCatalogManifestV1Schema, TidegateActionIdSchema, TidegateActionErrorCodeSchema, TidegateActionInvokeRequestSchema, TidegateActionInvokeResponseSchema, } from "@tidegate/contracts";
|
|
3
|
+
export { TIDEGATE_ACTION_ALLOWED_ACTIONS_HEADER, TIDEGATE_ACTION_AUTH_CONTEXT_HEADER, TIDEGATE_ACTION_INTERACTION_ID_HEADER, TIDEGATE_ACTION_BRIDGE_SECRET_HEADER, TidegateActionErrorCodeSchema, TidegateActionInvokeRequestSchema, TidegateActionInvokeResponseSchema, };
|
|
4
|
+
export class TidegateActionHandlerError extends Error {
|
|
5
|
+
name = "TidegateActionHandlerError";
|
|
6
|
+
code;
|
|
7
|
+
httpStatus;
|
|
8
|
+
responseStatus;
|
|
9
|
+
constructor(code, message, httpStatus, responseStatus = "rejected") {
|
|
10
|
+
super(message);
|
|
11
|
+
this.code = code;
|
|
12
|
+
this.httpStatus = httpStatus;
|
|
13
|
+
this.responseStatus = responseStatus;
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
export class TidegateActionCatalogError extends Error {
|
|
17
|
+
name = "TidegateActionCatalogError";
|
|
18
|
+
}
|
|
19
|
+
const TIDEGATE_ACTION_DEFINITION_BRAND = Symbol.for("@tidegate/sdk/tidegate-action-definition");
|
|
20
|
+
export function tidegateAction(definition) {
|
|
21
|
+
if (isLegacyShorthandActionDefinition(definition)) {
|
|
22
|
+
const { inputSchema, outputSchema, execute, ...metadata } = definition;
|
|
23
|
+
return brandTidegateActionDefinition({
|
|
24
|
+
...metadata,
|
|
25
|
+
input: inputSchema,
|
|
26
|
+
returns: outputSchema,
|
|
27
|
+
output: outputSchema,
|
|
28
|
+
execute: ({ input, auth, request, signal, invocationId }) => execute(input, { auth, request, signal, invocationId }),
|
|
29
|
+
});
|
|
30
|
+
}
|
|
31
|
+
if (isBuilderActionDefinition(definition)) {
|
|
32
|
+
const { input, returns, execute, ...metadata } = definition;
|
|
33
|
+
return brandTidegateActionDefinition({
|
|
34
|
+
...metadata,
|
|
35
|
+
input,
|
|
36
|
+
returns,
|
|
37
|
+
execute: ({ input, auth, request, signal, invocationId }) => execute(input, { auth, request, signal, invocationId }),
|
|
38
|
+
});
|
|
39
|
+
}
|
|
40
|
+
return brandTidegateActionDefinition(definition);
|
|
41
|
+
}
|
|
42
|
+
export function defineTidegateActions(actions) {
|
|
43
|
+
flattenTidegateActions(actions);
|
|
44
|
+
return actions;
|
|
45
|
+
}
|
|
46
|
+
export function createTidegateActionCatalogManifest(actions, { catalogId, version = "1", }) {
|
|
47
|
+
return TidegateActionCatalogManifestV1Schema.parse({
|
|
48
|
+
schemaVersion: "tidegate.actionCatalog.v1",
|
|
49
|
+
catalogId,
|
|
50
|
+
version,
|
|
51
|
+
actions: Object.fromEntries(flattenTidegateActions(actions).map(([actionId, action]) => {
|
|
52
|
+
const returnsSchema = actionReturnsSchema(action);
|
|
53
|
+
return [
|
|
54
|
+
actionId,
|
|
55
|
+
{
|
|
56
|
+
description: action.description ?? actionId,
|
|
57
|
+
input: toJsonSchema(action.input),
|
|
58
|
+
output: returnsSchema ? toJsonSchema(returnsSchema) : {},
|
|
59
|
+
effects: action.effects,
|
|
60
|
+
requiredPermissions: action.requiredPermissions ?? [],
|
|
61
|
+
tenantScope: action.tenantScope,
|
|
62
|
+
audit: {
|
|
63
|
+
required: action.audit?.required ?? action.effects !== "read",
|
|
64
|
+
redactPaths: action.audit?.redactPaths ?? [],
|
|
65
|
+
},
|
|
66
|
+
},
|
|
67
|
+
];
|
|
68
|
+
})),
|
|
69
|
+
});
|
|
70
|
+
}
|
|
71
|
+
export function createTidegateActionHandler(actions, { actionBridgeSecret = process.env.TIDEGATE_ACTION_BRIDGE_SECRET, verifyRequest, } = {}) {
|
|
72
|
+
const actionMap = new Map(flattenTidegateActions(actions));
|
|
73
|
+
const verifier = verifyRequest ??
|
|
74
|
+
((request) => verifyTidegateActionRequest({ request, actionBridgeSecret }));
|
|
75
|
+
return async function POST(request) {
|
|
76
|
+
let verified;
|
|
77
|
+
try {
|
|
78
|
+
verified = await verifier(request);
|
|
79
|
+
}
|
|
80
|
+
catch (error) {
|
|
81
|
+
return responseFromError(normalizeActionHandlerError(error, "Tidegate action request verification failed."));
|
|
82
|
+
}
|
|
83
|
+
let body;
|
|
84
|
+
try {
|
|
85
|
+
body = await request.json();
|
|
86
|
+
}
|
|
87
|
+
catch {
|
|
88
|
+
return actionErrorResponse({
|
|
89
|
+
code: "invalid_request",
|
|
90
|
+
message: "Request body must be valid JSON.",
|
|
91
|
+
status: "rejected",
|
|
92
|
+
httpStatus: 400,
|
|
93
|
+
});
|
|
94
|
+
}
|
|
95
|
+
const requestResult = TidegateActionInvokeRequestSchema.safeParse(body);
|
|
96
|
+
if (!requestResult.success) {
|
|
97
|
+
return actionErrorResponse({
|
|
98
|
+
code: "invalid_request",
|
|
99
|
+
message: "Request body must include actionId and input only.",
|
|
100
|
+
status: "rejected",
|
|
101
|
+
httpStatus: 400,
|
|
102
|
+
});
|
|
103
|
+
}
|
|
104
|
+
const invokeRequest = requestResult.data;
|
|
105
|
+
if (!verified.allowedActionIds.includes(invokeRequest.actionId)) {
|
|
106
|
+
return actionErrorResponse({
|
|
107
|
+
code: "action_not_allowed",
|
|
108
|
+
message: "The requested Tidegate action is not allowed by this interaction.",
|
|
109
|
+
status: "rejected",
|
|
110
|
+
httpStatus: 403,
|
|
111
|
+
invocationId: invokeRequest.invocationId,
|
|
112
|
+
});
|
|
113
|
+
}
|
|
114
|
+
const action = actionMap.get(invokeRequest.actionId);
|
|
115
|
+
if (!action) {
|
|
116
|
+
return actionErrorResponse({
|
|
117
|
+
code: "action_not_found",
|
|
118
|
+
message: "The requested Tidegate action is not registered.",
|
|
119
|
+
status: "rejected",
|
|
120
|
+
httpStatus: 404,
|
|
121
|
+
invocationId: invokeRequest.invocationId,
|
|
122
|
+
});
|
|
123
|
+
}
|
|
124
|
+
if (!hasRequiredPermissions(verified.auth, action.requiredPermissions ?? [])) {
|
|
125
|
+
return actionErrorResponse({
|
|
126
|
+
code: "permission_denied",
|
|
127
|
+
message: "The Tidegate action request is missing required permissions.",
|
|
128
|
+
status: "rejected",
|
|
129
|
+
httpStatus: 403,
|
|
130
|
+
invocationId: invokeRequest.invocationId,
|
|
131
|
+
});
|
|
132
|
+
}
|
|
133
|
+
const inputResult = action.input.safeParse(invokeRequest.input);
|
|
134
|
+
if (!inputResult.success) {
|
|
135
|
+
return actionErrorResponse({
|
|
136
|
+
code: "action_input_invalid",
|
|
137
|
+
message: "The Tidegate action input does not match the registered schema.",
|
|
138
|
+
status: "rejected",
|
|
139
|
+
httpStatus: 400,
|
|
140
|
+
invocationId: invokeRequest.invocationId,
|
|
141
|
+
});
|
|
142
|
+
}
|
|
143
|
+
let output;
|
|
144
|
+
try {
|
|
145
|
+
output = await action.execute({
|
|
146
|
+
input: inputResult.data,
|
|
147
|
+
auth: verified.auth,
|
|
148
|
+
request,
|
|
149
|
+
signal: request.signal,
|
|
150
|
+
invocationId: invokeRequest.invocationId,
|
|
151
|
+
});
|
|
152
|
+
}
|
|
153
|
+
catch (error) {
|
|
154
|
+
// A structured TidegateActionHandlerError thrown by the action keeps
|
|
155
|
+
// its code/status: this is how a backend surfaces auth_required,
|
|
156
|
+
// permission_denied, action_input_invalid... from downstream systems.
|
|
157
|
+
const handlerError = normalizeActionHandlerError(error, "The Tidegate action failed while executing.");
|
|
158
|
+
return actionErrorResponse({
|
|
159
|
+
code: handlerError.code,
|
|
160
|
+
message: handlerError.message,
|
|
161
|
+
status: handlerError.responseStatus,
|
|
162
|
+
httpStatus: handlerError.httpStatus,
|
|
163
|
+
invocationId: invokeRequest.invocationId,
|
|
164
|
+
});
|
|
165
|
+
}
|
|
166
|
+
const returnsSchema = actionReturnsSchema(action);
|
|
167
|
+
let responseOutput = output;
|
|
168
|
+
if (returnsSchema) {
|
|
169
|
+
const outputResult = returnsSchema.safeParse(output);
|
|
170
|
+
if (!outputResult.success) {
|
|
171
|
+
return actionErrorResponse({
|
|
172
|
+
code: "action_output_invalid",
|
|
173
|
+
message: "The Tidegate action output does not match the registered schema.",
|
|
174
|
+
status: "failed",
|
|
175
|
+
httpStatus: 500,
|
|
176
|
+
invocationId: invokeRequest.invocationId,
|
|
177
|
+
});
|
|
178
|
+
}
|
|
179
|
+
responseOutput = outputResult.data;
|
|
180
|
+
}
|
|
181
|
+
else if (responseOutput === undefined) {
|
|
182
|
+
responseOutput = null;
|
|
183
|
+
}
|
|
184
|
+
return Response.json(TidegateActionInvokeResponseSchema.parse({
|
|
185
|
+
status: "ok",
|
|
186
|
+
invocationId: invokeRequest.invocationId,
|
|
187
|
+
output: responseOutput,
|
|
188
|
+
}));
|
|
189
|
+
};
|
|
190
|
+
}
|
|
191
|
+
export function verifyTidegateActionRequest({ actionBridgeSecret = process.env.TIDEGATE_ACTION_BRIDGE_SECRET, request, }) {
|
|
192
|
+
if (!actionBridgeSecret) {
|
|
193
|
+
throw new TidegateActionHandlerError("auth_required", "TIDEGATE_ACTION_BRIDGE_SECRET is not configured.", 500, "failed");
|
|
194
|
+
}
|
|
195
|
+
const headerSecret = request.headers.get(TIDEGATE_ACTION_BRIDGE_SECRET_HEADER);
|
|
196
|
+
if (!headerSecret || !constantTimeEqual(headerSecret, actionBridgeSecret)) {
|
|
197
|
+
throw new TidegateActionHandlerError("auth_required", "The Tidegate action request is missing a valid credential.", 401);
|
|
198
|
+
}
|
|
199
|
+
const authHeader = request.headers.get(TIDEGATE_ACTION_AUTH_CONTEXT_HEADER);
|
|
200
|
+
const allowedActionsHeader = request.headers.get(TIDEGATE_ACTION_ALLOWED_ACTIONS_HEADER);
|
|
201
|
+
if (!authHeader) {
|
|
202
|
+
throw new TidegateActionHandlerError("invalid_request", "The Tidegate action request is missing server-derived auth context.", 400);
|
|
203
|
+
}
|
|
204
|
+
if (!allowedActionsHeader) {
|
|
205
|
+
throw new TidegateActionHandlerError("invalid_request", "The Tidegate action request is missing its interaction action allowlist.", 400);
|
|
206
|
+
}
|
|
207
|
+
let parsedAuth;
|
|
208
|
+
let parsedAllowedActions;
|
|
209
|
+
try {
|
|
210
|
+
parsedAuth = JSON.parse(authHeader);
|
|
211
|
+
}
|
|
212
|
+
catch {
|
|
213
|
+
throw new TidegateActionHandlerError("invalid_request", "The Tidegate action auth context must be valid JSON.", 400);
|
|
214
|
+
}
|
|
215
|
+
try {
|
|
216
|
+
parsedAllowedActions = JSON.parse(allowedActionsHeader);
|
|
217
|
+
}
|
|
218
|
+
catch {
|
|
219
|
+
throw new TidegateActionHandlerError("invalid_request", "The Tidegate action allowlist must be valid JSON.", 400);
|
|
220
|
+
}
|
|
221
|
+
const authResult = TidegateAuthContextSchema.safeParse(parsedAuth);
|
|
222
|
+
const allowedActionsResult = z.array(z.string().min(1)).safeParse(parsedAllowedActions);
|
|
223
|
+
if (!authResult.success) {
|
|
224
|
+
throw new TidegateActionHandlerError("invalid_request", "The Tidegate action auth context is invalid.", 400);
|
|
225
|
+
}
|
|
226
|
+
if (!allowedActionsResult.success) {
|
|
227
|
+
throw new TidegateActionHandlerError("invalid_request", "The Tidegate action allowlist is invalid.", 400);
|
|
228
|
+
}
|
|
229
|
+
return {
|
|
230
|
+
auth: authResult.data,
|
|
231
|
+
allowedActionIds: allowedActionsResult.data,
|
|
232
|
+
interactionId: request.headers.get(TIDEGATE_ACTION_INTERACTION_ID_HEADER) ?? undefined,
|
|
233
|
+
};
|
|
234
|
+
}
|
|
235
|
+
function responseFromError(error) {
|
|
236
|
+
return actionErrorResponse({
|
|
237
|
+
code: error.code,
|
|
238
|
+
message: error.message,
|
|
239
|
+
status: error.responseStatus,
|
|
240
|
+
httpStatus: error.httpStatus,
|
|
241
|
+
});
|
|
242
|
+
}
|
|
243
|
+
function normalizeActionHandlerError(error, fallbackMessage) {
|
|
244
|
+
if (error instanceof TidegateActionHandlerError) {
|
|
245
|
+
return error;
|
|
246
|
+
}
|
|
247
|
+
return new TidegateActionHandlerError("action_failed", fallbackMessage, 500, "failed");
|
|
248
|
+
}
|
|
249
|
+
function actionErrorResponse({ code, httpStatus, invocationId, message, status, }) {
|
|
250
|
+
return Response.json(TidegateActionInvokeResponseSchema.parse({
|
|
251
|
+
status,
|
|
252
|
+
invocationId,
|
|
253
|
+
error: {
|
|
254
|
+
code,
|
|
255
|
+
// The bridge response contract requires a non-empty message; a
|
|
256
|
+
// downstream system may legitimately produce an empty one.
|
|
257
|
+
message: message.trim().length > 0
|
|
258
|
+
? message
|
|
259
|
+
: `The Tidegate action failed with error code ${code} and no message.`,
|
|
260
|
+
},
|
|
261
|
+
}), { status: httpStatus });
|
|
262
|
+
}
|
|
263
|
+
function hasRequiredPermissions(auth, requiredPermissions) {
|
|
264
|
+
if (requiredPermissions.length === 0) {
|
|
265
|
+
return true;
|
|
266
|
+
}
|
|
267
|
+
const permissions = new Set([
|
|
268
|
+
...(auth.permissions ?? []),
|
|
269
|
+
...(auth.authorization?.permissions ?? []),
|
|
270
|
+
]);
|
|
271
|
+
return requiredPermissions.every((permission) => permissions.has(permission));
|
|
272
|
+
}
|
|
273
|
+
function constantTimeEqual(left, right) {
|
|
274
|
+
if (left.length !== right.length) {
|
|
275
|
+
return false;
|
|
276
|
+
}
|
|
277
|
+
let diff = 0;
|
|
278
|
+
for (let index = 0; index < left.length; index += 1) {
|
|
279
|
+
diff |= left.charCodeAt(index) ^ right.charCodeAt(index);
|
|
280
|
+
}
|
|
281
|
+
return diff === 0;
|
|
282
|
+
}
|
|
283
|
+
function toJsonSchema(schema) {
|
|
284
|
+
return z.toJSONSchema(schema);
|
|
285
|
+
}
|
|
286
|
+
function flattenTidegateActions(actions) {
|
|
287
|
+
assertPlainNamespace(actions, "Tidegate action catalog");
|
|
288
|
+
assertStringKeysOnly(actions, "Tidegate action catalog");
|
|
289
|
+
const entries = new Map();
|
|
290
|
+
for (const [segment, node] of Object.entries(actions)) {
|
|
291
|
+
collectTidegateActionEntries({
|
|
292
|
+
entries,
|
|
293
|
+
path: [segment],
|
|
294
|
+
node,
|
|
295
|
+
});
|
|
296
|
+
}
|
|
297
|
+
assertNoNamespaceCollisions([...entries.keys()]);
|
|
298
|
+
return [...entries.entries()];
|
|
299
|
+
}
|
|
300
|
+
function collectTidegateActionEntries({ entries, path, node, }) {
|
|
301
|
+
if (isTidegateActionDefinition(node)) {
|
|
302
|
+
if (path.length > 1 && !isBrandedTidegateActionDefinition(node)) {
|
|
303
|
+
throw new TidegateActionCatalogError(`Invalid Tidegate action "${path.join(".")}". Wrap input/returns shorthand definitions with tidegateAction(...).`);
|
|
304
|
+
}
|
|
305
|
+
const actionId = path.join(".");
|
|
306
|
+
const actionIdResult = TidegateActionIdSchema.safeParse(actionId);
|
|
307
|
+
if (!actionIdResult.success) {
|
|
308
|
+
throw new TidegateActionCatalogError(`Invalid Tidegate action id "${actionId}": ${actionIdResult.error.issues
|
|
309
|
+
.map((issue) => issue.message)
|
|
310
|
+
.join(" ")}`);
|
|
311
|
+
}
|
|
312
|
+
if (entries.has(actionId)) {
|
|
313
|
+
throw new TidegateActionCatalogError(`Duplicate Tidegate action id "${actionId}". Use only one definition for each action path.`);
|
|
314
|
+
}
|
|
315
|
+
entries.set(actionId, node);
|
|
316
|
+
return;
|
|
317
|
+
}
|
|
318
|
+
if (isShorthandActionDefinition(node)) {
|
|
319
|
+
throw new TidegateActionCatalogError(`Invalid Tidegate action "${path.join(".")}". Wrap input/returns shorthand definitions with tidegateAction(...).`);
|
|
320
|
+
}
|
|
321
|
+
if (!isRecord(node)) {
|
|
322
|
+
throw new TidegateActionCatalogError(`Invalid Tidegate action namespace "${path.join(".")}". Expected an action definition or nested namespace.`);
|
|
323
|
+
}
|
|
324
|
+
const namespace = path.join(".");
|
|
325
|
+
assertPlainNamespace(node, `Tidegate action namespace "${namespace}"`);
|
|
326
|
+
assertStringKeysOnly(node, `Tidegate action namespace "${namespace}"`);
|
|
327
|
+
const childEntries = Object.entries(node);
|
|
328
|
+
if (childEntries.length === 0) {
|
|
329
|
+
throw new TidegateActionCatalogError(`Invalid Tidegate action namespace "${namespace}". Namespaces must contain at least one action.`);
|
|
330
|
+
}
|
|
331
|
+
for (const [segment, child] of childEntries) {
|
|
332
|
+
collectTidegateActionEntries({
|
|
333
|
+
entries,
|
|
334
|
+
path: [...path, segment],
|
|
335
|
+
node: child,
|
|
336
|
+
});
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
function assertNoNamespaceCollisions(actionIds) {
|
|
340
|
+
const knownActionIds = new Set(actionIds);
|
|
341
|
+
for (const actionId of actionIds) {
|
|
342
|
+
const segments = actionId.split(".");
|
|
343
|
+
let prefix = "";
|
|
344
|
+
for (const segment of segments.slice(0, -1)) {
|
|
345
|
+
prefix = prefix.length === 0 ? segment : `${prefix}.${segment}`;
|
|
346
|
+
if (knownActionIds.has(prefix)) {
|
|
347
|
+
throw new TidegateActionCatalogError(`Tidegate action id "${actionId}" conflicts with "${prefix}". Use either a leaf action or a namespace at each path.`);
|
|
348
|
+
}
|
|
349
|
+
}
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
function isTidegateActionDefinition(value) {
|
|
353
|
+
return (isRecord(value) &&
|
|
354
|
+
"input" in value &&
|
|
355
|
+
"effects" in value &&
|
|
356
|
+
"execute" in value &&
|
|
357
|
+
typeof value.execute === "function");
|
|
358
|
+
}
|
|
359
|
+
function isShorthandActionDefinition(value) {
|
|
360
|
+
return (isBuilderActionDefinition(value) ||
|
|
361
|
+
isLegacyShorthandActionDefinition(value));
|
|
362
|
+
}
|
|
363
|
+
function isBuilderActionDefinition(value) {
|
|
364
|
+
return (isRecord(value) &&
|
|
365
|
+
"input" in value &&
|
|
366
|
+
!("output" in value) &&
|
|
367
|
+
"effects" in value &&
|
|
368
|
+
"execute" in value &&
|
|
369
|
+
typeof value.execute === "function");
|
|
370
|
+
}
|
|
371
|
+
function isLegacyShorthandActionDefinition(value) {
|
|
372
|
+
return (isRecord(value) &&
|
|
373
|
+
"inputSchema" in value &&
|
|
374
|
+
"outputSchema" in value &&
|
|
375
|
+
"effects" in value &&
|
|
376
|
+
"execute" in value &&
|
|
377
|
+
typeof value.execute === "function");
|
|
378
|
+
}
|
|
379
|
+
function brandTidegateActionDefinition(action) {
|
|
380
|
+
Object.defineProperty(action, TIDEGATE_ACTION_DEFINITION_BRAND, {
|
|
381
|
+
configurable: false,
|
|
382
|
+
enumerable: false,
|
|
383
|
+
value: true,
|
|
384
|
+
});
|
|
385
|
+
return action;
|
|
386
|
+
}
|
|
387
|
+
function isBrandedTidegateActionDefinition(action) {
|
|
388
|
+
return (action[TIDEGATE_ACTION_DEFINITION_BRAND] ===
|
|
389
|
+
true);
|
|
390
|
+
}
|
|
391
|
+
function actionReturnsSchema(action) {
|
|
392
|
+
return action.returns ?? action.output;
|
|
393
|
+
}
|
|
394
|
+
function isRecord(value) {
|
|
395
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
396
|
+
}
|
|
397
|
+
function assertPlainNamespace(value, label) {
|
|
398
|
+
const prototype = Object.getPrototypeOf(value);
|
|
399
|
+
if (prototype !== Object.prototype && prototype !== null) {
|
|
400
|
+
throw new TidegateActionCatalogError(`${label} must be a plain object with string action ids or namespace keys.`);
|
|
401
|
+
}
|
|
402
|
+
}
|
|
403
|
+
function assertStringKeysOnly(value, label) {
|
|
404
|
+
if (Reflect.ownKeys(value).some((key) => typeof key === "symbol")) {
|
|
405
|
+
throw new TidegateActionCatalogError(`${label} must use string keys only; symbol keys cannot become stable Tidegate action ids.`);
|
|
406
|
+
}
|
|
407
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export type { InvokeInteractionRequest, InvokeInteractionResponse, } from "@tidegate/contracts";
|
package/dist/index.js
ADDED
|
File without changes
|
package/dist/server.d.ts
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { type InvokeInteractionRequest, type InvokeInteractionResponse } from "@tidegate/contracts";
|
|
2
|
+
export { TIDEGATE_ACTION_ALLOWED_ACTIONS_HEADER, TIDEGATE_ACTION_AUTH_CONTEXT_HEADER, TIDEGATE_ACTION_INTERACTION_ID_HEADER, TIDEGATE_ACTION_BRIDGE_SECRET_HEADER, TidegateActionCatalogError, TidegateActionErrorCodeSchema, TidegateActionHandlerError, TidegateActionInvokeRequestSchema, TidegateActionInvokeResponseSchema, createTidegateActionCatalogManifest, createTidegateActionHandler, defineTidegateActions, tidegateAction, verifyTidegateActionRequest, type AnyTidegateActionDefinition, type CreateTidegateActionCatalogManifestOptions, type CreateTidegateActionHandlerOptions, type TidegateActionCatalog, type TidegateActionCatalogNode, type TidegateActionBuilderDefinition, type TidegateActionBuilderWithReturnsDefinition, type TidegateActionDefinition, type TidegateActionEffect, type TidegateActionErrorCode, type TidegateActionExecuteContext, type TidegateActionExecuteArgs, type TidegateActionLegacyShorthandDefinition, type TidegateActionNormalizedDefinition, type TidegateActionShorthandDefinition, type TidegateActionShorthandWithReturnsDefinition, type TidegateActionInvokeRequest, type TidegateActionInvokeResponse, type TidegateActionRequestVerifier, type TidegateVerifiedActionRequest, } from "./action-bridge.js";
|
|
3
|
+
export declare const DEFAULT_TIDEGATE_API_BASE_URL = "https://api.tidegate.ai/v1";
|
|
4
|
+
export type TidegateFetch = (input: Parameters<typeof fetch>[0], init?: Parameters<typeof fetch>[1]) => Promise<Response>;
|
|
5
|
+
export type TidegateServerClientOptions = {
|
|
6
|
+
apiKey?: string;
|
|
7
|
+
baseUrl?: string;
|
|
8
|
+
fetchImpl?: TidegateFetch;
|
|
9
|
+
};
|
|
10
|
+
export type TidegateInteractionsClient = {
|
|
11
|
+
invoke: (interactionId: string, request: InvokeInteractionRequest) => Promise<InvokeInteractionResponse>;
|
|
12
|
+
};
|
|
13
|
+
export type TidegateServerClient = {
|
|
14
|
+
interactions: TidegateInteractionsClient;
|
|
15
|
+
};
|
|
16
|
+
export declare class TidegateSdkError extends Error {
|
|
17
|
+
name: string;
|
|
18
|
+
readonly details?: unknown;
|
|
19
|
+
constructor(message: string, details?: unknown);
|
|
20
|
+
}
|
|
21
|
+
export declare function createTidegateServerClient({ apiKey, baseUrl, fetchImpl, }?: TidegateServerClientOptions): TidegateServerClient;
|
package/dist/server.js
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import { interactionPublicRoutePaths, InvokeInteractionRequestSchema, InvokeInteractionResponseSchema, } from "@tidegate/contracts";
|
|
2
|
+
export { TIDEGATE_ACTION_ALLOWED_ACTIONS_HEADER, TIDEGATE_ACTION_AUTH_CONTEXT_HEADER, TIDEGATE_ACTION_INTERACTION_ID_HEADER, TIDEGATE_ACTION_BRIDGE_SECRET_HEADER, TidegateActionCatalogError, TidegateActionErrorCodeSchema, TidegateActionHandlerError, TidegateActionInvokeRequestSchema, TidegateActionInvokeResponseSchema, createTidegateActionCatalogManifest, createTidegateActionHandler, defineTidegateActions, tidegateAction, verifyTidegateActionRequest, } from "./action-bridge.js";
|
|
3
|
+
export const DEFAULT_TIDEGATE_API_BASE_URL = "https://api.tidegate.ai/v1";
|
|
4
|
+
export class TidegateSdkError extends Error {
|
|
5
|
+
name = "TidegateSdkError";
|
|
6
|
+
details;
|
|
7
|
+
constructor(message, details) {
|
|
8
|
+
super(message);
|
|
9
|
+
this.details = details;
|
|
10
|
+
}
|
|
11
|
+
}
|
|
12
|
+
export function createTidegateServerClient({ apiKey = process.env.TIDEGATE_API_KEY, baseUrl = DEFAULT_TIDEGATE_API_BASE_URL, fetchImpl = globalThis.fetch, } = {}) {
|
|
13
|
+
if (!apiKey) {
|
|
14
|
+
throw new TidegateSdkError("Missing TIDEGATE_API_KEY. Create an API key in the Tidegate dashboard and add it to your server environment.");
|
|
15
|
+
}
|
|
16
|
+
const normalizedBaseUrl = normalizeBaseUrl(baseUrl);
|
|
17
|
+
return {
|
|
18
|
+
interactions: {
|
|
19
|
+
async invoke(interactionId, request) {
|
|
20
|
+
const invokeRequest = InvokeInteractionRequestSchema.parse(request);
|
|
21
|
+
const response = await fetchImpl(urlForInteractionInvoke(normalizedBaseUrl, interactionId), {
|
|
22
|
+
method: "POST",
|
|
23
|
+
headers: {
|
|
24
|
+
accept: "application/json",
|
|
25
|
+
authorization: `Bearer ${apiKey}`,
|
|
26
|
+
"content-type": "application/json",
|
|
27
|
+
},
|
|
28
|
+
body: JSON.stringify(invokeRequest),
|
|
29
|
+
});
|
|
30
|
+
let body;
|
|
31
|
+
try {
|
|
32
|
+
body = await response.json();
|
|
33
|
+
}
|
|
34
|
+
catch (error) {
|
|
35
|
+
throw new TidegateSdkError(`Tidegate returned HTTP ${response.status} without a valid JSON body.`, error);
|
|
36
|
+
}
|
|
37
|
+
const parsed = InvokeInteractionResponseSchema.safeParse(body);
|
|
38
|
+
if (!parsed.success) {
|
|
39
|
+
throw new TidegateSdkError(`Tidegate returned HTTP ${response.status} with an invalid interaction response.`, parsed.error);
|
|
40
|
+
}
|
|
41
|
+
return parsed.data;
|
|
42
|
+
},
|
|
43
|
+
},
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
function normalizeBaseUrl(baseUrl) {
|
|
47
|
+
const normalized = baseUrl.trim().replace(/\/+$/, "");
|
|
48
|
+
if (normalized.length === 0) {
|
|
49
|
+
throw new TidegateSdkError("Tidegate baseUrl cannot be empty.");
|
|
50
|
+
}
|
|
51
|
+
return normalized;
|
|
52
|
+
}
|
|
53
|
+
function urlForInteractionInvoke(baseUrl, interactionId) {
|
|
54
|
+
return `${baseUrl}/${interactionPublicRoutePaths.invokeInteraction({
|
|
55
|
+
interactionId,
|
|
56
|
+
})}`;
|
|
57
|
+
}
|
package/package.json
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@tidegate/sdk",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Tidegate SDK: connect a trusted server to Tidegate (action bridge, public interaction invoke helpers).",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"license": "Apache-2.0",
|
|
7
|
+
"repository": {
|
|
8
|
+
"type": "git",
|
|
9
|
+
"url": "git+https://github.com/puccez/tidegate.git",
|
|
10
|
+
"directory": "packages/tidegate-sdk"
|
|
11
|
+
},
|
|
12
|
+
"sideEffects": false,
|
|
13
|
+
"main": "./dist/index.js",
|
|
14
|
+
"types": "./dist/index.d.ts",
|
|
15
|
+
"exports": {
|
|
16
|
+
".": {
|
|
17
|
+
"types": "./dist/index.d.ts",
|
|
18
|
+
"default": "./dist/index.js"
|
|
19
|
+
},
|
|
20
|
+
"./server": {
|
|
21
|
+
"types": "./dist/server.d.ts",
|
|
22
|
+
"default": "./dist/server.js"
|
|
23
|
+
}
|
|
24
|
+
},
|
|
25
|
+
"files": [
|
|
26
|
+
"dist"
|
|
27
|
+
],
|
|
28
|
+
"dependencies": {
|
|
29
|
+
"@tidegate/contracts": "0.1.0",
|
|
30
|
+
"zod": "4.4.3"
|
|
31
|
+
},
|
|
32
|
+
"publishConfig": {
|
|
33
|
+
"access": "public"
|
|
34
|
+
}
|
|
35
|
+
}
|